const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/LeadSiteHome-l_Dtxo9y.js","assets/useLeadSiteSearchSuggestions-DvZVy3-L.js","assets/CityPagesModule-UzJOSX0P.js","assets/ListingCarouselModule-BoSXZz18.js","assets/imageOptimization-Csrlnz8M.js","assets/LeadSiteLuxuryHome-BRnbSWRq.js","assets/LeadSiteExchangeListings-DXMF0GLh.js","assets/LeadSiteLandRanchHome-Dz-9G-_m.js","assets/LeadSiteSearch-Bgq6QvRO.js","assets/LeadSiteListingCardImage-LFJkPLfr.js","assets/LeadSiteMap-DJpv9cmd.js","assets/LeadSiteLuxurySearch-_fx39hKj.js","assets/LeadSiteListingDetail-BGm0VZXC.js","assets/ListingVideoTour-DyCUVSBD.js","assets/useListingVideos-DycyXfzJ.js","assets/LeadSiteLuxuryListingDetail-B3SNeXJZ.js","assets/LeadSiteBlog-1zP7zOCS.js","assets/purify.es-BnINGy_Y.js","assets/LeadSiteCityPage-DqpbE5lG.js","assets/LeadSiteSubdivisionPage-DdD6P9f-.js","assets/LeadSiteFocusPage-CVhnrqN0.js","assets/PublicLiveEvent-CxFkZgvZ.js","assets/useLiveEngagement-D9E2sL7y.js","assets/LiveEventConsole-COHTR8QK.js","assets/PostcardManager-DJ-wl3ba.js","assets/usePostcardZones-BTlO5uqW.js","assets/DirectMail-USHiEPHS.js","assets/LeadSiteEditor-DnBD6qES.js","assets/ImageUrlField-Ckvo1nvd.js","assets/HomepageModuleManager-BDBFqlfe.js","assets/LeadSiteEditor-BzY4kI8E.css","assets/AdminLeadSiteThemes-Duxgc6Yp.js","assets/AdminFreeWebsiteOfferStudio-lm0Q4g8O.js","assets/MLSListingDetail-C-Nl76-O.js","assets/EmailCampaignComposer-B2eYEKcP.js","assets/EditorModeSelector-BuxVim13.js","assets/SharedCampaignTemplates-DSMHTQGb.js","assets/TemplateEditorDialog-DqLAC3UD.js","assets/AgentTemplates-C6uh4qG8.js","assets/TheLocalMoveHome-D-WZboNP.js","assets/tlm-hero-bg-BbD3acLf.js","assets/TheLocalMoveGetStarted-BFU7Mmv3.js"])))=>i.map(i=>d[i]); var qQt=Object.defineProperty;var vrt=s=>{throw TypeError(s)};var VQt=(s,t,n)=>t in s?qQt(s,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):s[t]=n;var ur=(s,t,n)=>VQt(s,typeof t!="symbol"?t+"":t,n),fPe=(s,t,n)=>t.has(s)||vrt("Cannot "+n);var ge=(s,t,n)=>(fPe(s,t,"read from private field"),n?n.call(s):t.get(s)),ds=(s,t,n)=>t.has(s)?vrt("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(s):t.set(s,n),$t=(s,t,n,r)=>(fPe(s,t,"write to private field"),r?r.call(s,n):t.set(s,n),n),ss=(s,t,n)=>(fPe(s,t,"access private method"),n);var Hy=(s,t,n,r)=>({set _(a){$t(s,t,a,n)},get _(){return ge(s,t,r)}});function HQt(s,t){for(var n=0;nr[a]})}}}return Object.freeze(Object.defineProperty(s,Symbol.toStringTag,{value:"Module"}))}(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const a of document.querySelectorAll('link[rel="modulepreload"]'))r(a);new MutationObserver(a=>{for(const i of a)if(i.type==="childList")for(const l of i.addedNodes)l.tagName==="LINK"&&l.rel==="modulepreload"&&r(l)}).observe(document,{childList:!0,subtree:!0});function n(a){const i={};return a.integrity&&(i.integrity=a.integrity),a.referrerPolicy&&(i.referrerPolicy=a.referrerPolicy),a.crossOrigin==="use-credentials"?i.credentials="include":a.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function r(a){if(a.ep)return;a.ep=!0;const i=n(a);fetch(a.href,i)}})();const GQt="modulepreload",WQt=function(s){return"/"+s},brt={},Ai=function(t,n,r){let a=Promise.resolve();if(n&&n.length>0){document.getElementsByTagName("link");const l=document.querySelector("meta[property=csp-nonce]"),o=(l==null?void 0:l.nonce)||(l==null?void 0:l.getAttribute("nonce"));a=Promise.allSettled(n.map(c=>{if(c=WQt(c),c in brt)return;brt[c]=!0;const d=c.endsWith(".css"),u=d?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${c}"]${u}`))return;const h=document.createElement("link");if(h.rel=d?"stylesheet":GQt,d||(h.as="script"),h.crossOrigin="",h.href=c,o&&h.setAttribute("nonce",o),document.head.appendChild(h),d)return new Promise((m,p)=>{h.addEventListener("load",m),h.addEventListener("error",()=>p(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 jf=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function kd(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}function KQt(s){if(s.__esModule)return s;var t=s.default;if(typeof t=="function"){var n=function r(){return this instanceof r?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};n.prototype=t.prototype}else n={};return Object.defineProperty(n,"__esModule",{value:!0}),Object.keys(s).forEach(function(r){var a=Object.getOwnPropertyDescriptor(s,r);Object.defineProperty(n,r,a.get?a:{enumerable:!0,get:function(){return s[r]}})}),n}var l2t={exports:{}},FCe={},c2t={exports:{}},Rd={};/** * @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 WJ=Symbol.for("react.element"),YQt=Symbol.for("react.portal"),ZQt=Symbol.for("react.fragment"),XQt=Symbol.for("react.strict_mode"),QQt=Symbol.for("react.profiler"),JQt=Symbol.for("react.provider"),eJt=Symbol.for("react.context"),tJt=Symbol.for("react.forward_ref"),sJt=Symbol.for("react.suspense"),nJt=Symbol.for("react.memo"),rJt=Symbol.for("react.lazy"),_rt=Symbol.iterator;function aJt(s){return s===null||typeof s!="object"?null:(s=_rt&&s[_rt]||s["@@iterator"],typeof s=="function"?s:null)}var d2t={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},u2t=Object.assign,h2t={};function Sq(s,t,n){this.props=s,this.context=t,this.refs=h2t,this.updater=n||d2t}Sq.prototype.isReactComponent={};Sq.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")};Sq.prototype.forceUpdate=function(s){this.updater.enqueueForceUpdate(this,s,"forceUpdate")};function m2t(){}m2t.prototype=Sq.prototype;function Hqe(s,t,n){this.props=s,this.context=t,this.refs=h2t,this.updater=n||d2t}var Gqe=Hqe.prototype=new m2t;Gqe.constructor=Hqe;u2t(Gqe,Sq.prototype);Gqe.isPureReactComponent=!0;var wrt=Array.isArray,f2t=Object.prototype.hasOwnProperty,Wqe={current:null},p2t={key:!0,ref:!0,__self:!0,__source:!0};function g2t(s,t,n){var r,a={},i=null,l=null;if(t!=null)for(r in t.ref!==void 0&&(l=t.ref),t.key!==void 0&&(i=""+t.key),t)f2t.call(t,r)&&!p2t.hasOwnProperty(r)&&(a[r]=t[r]);var o=arguments.length-2;if(o===1)a.children=n;else if(1>>1,le=oe[te];if(0>>1;tea(ve,Q))hea(Se,ve)?(oe[te]=Se,oe[he]=Q,te=he):(oe[te]=ve,oe[_e]=Q,te=_e);else if(hea(Se,Q))oe[te]=Se,oe[he]=Q,te=he;else break e}}return me}function a(oe,me){var Q=oe.sortIndex-me.sortIndex;return Q!==0?Q:oe.id-me.id}if(typeof performance=="object"&&typeof performance.now=="function"){var i=performance;s.unstable_now=function(){return i.now()}}else{var l=Date,o=l.now();s.unstable_now=function(){return l.now()-o}}var c=[],d=[],u=1,h=null,m=3,p=!1,g=!1,x=!1,y=typeof setTimeout=="function"?setTimeout:null,v=typeof clearTimeout=="function"?clearTimeout:null,_=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function j(oe){for(var me=n(d);me!==null;){if(me.callback===null)r(d);else if(me.startTime<=oe)r(d),me.sortIndex=me.expirationTime,t(c,me);else break;me=n(d)}}function C(oe){if(x=!1,j(oe),!g)if(n(c)!==null)g=!0,se(A);else{var me=n(d);me!==null&&ee(C,me.startTime-oe)}}function A(oe,me){g=!1,x&&(x=!1,v(P),P=-1),p=!0;var Q=m;try{for(j(me),h=n(c);h!==null&&(!(h.expirationTime>me)||oe&&!B());){var te=h.callback;if(typeof te=="function"){h.callback=null,m=h.priorityLevel;var le=te(h.expirationTime<=me);me=s.unstable_now(),typeof le=="function"?h.callback=le:h===n(c)&&r(c),j(me)}else r(c);h=n(c)}if(h!==null)var fe=!0;else{var _e=n(d);_e!==null&&ee(C,_e.startTime-me),fe=!1}return fe}finally{h=null,m=Q,p=!1}}var M=!1,I=null,P=-1,R=5,O=-1;function B(){return!(s.unstable_now()-Ooe||125te?(oe.sortIndex=Q,t(d,oe),n(c)===null&&oe===n(d)&&(x?(v(P),P=-1):x=!0,ee(C,Q-te))):(oe.sortIndex=le,t(c,oe),g||p||(g=!0,se(A))),oe},s.unstable_shouldYield=B,s.unstable_wrapCallback=function(oe){var me=m;return function(){var Q=m;m=me;try{return oe.apply(this,arguments)}finally{m=Q}}}})(_2t);b2t.exports=_2t;var lK=b2t.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 gJt=k,lj=lK;function Ga(s){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+s,n=1;n"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),oOe=Object.prototype.hasOwnProperty,xJt=/^[: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]*$/,Nrt={},krt={};function yJt(s){return oOe.call(krt,s)?!0:oOe.call(Nrt,s)?!1:xJt.test(s)?krt[s]=!0:(Nrt[s]=!0,!1)}function vJt(s,t,n,r){if(n!==null&&n.type===0)return!1;switch(typeof t){case"function":case"symbol":return!0;case"boolean":return r?!1:n!==null?!n.acceptsBooleans:(s=s.toLowerCase().slice(0,5),s!=="data-"&&s!=="aria-");default:return!1}}function bJt(s,t,n,r){if(t===null||typeof t>"u"||vJt(s,t,n,r))return!0;if(r)return!1;if(n!==null)switch(n.type){case 3:return!t;case 4:return t===!1;case 5:return isNaN(t);case 6:return isNaN(t)||1>t}return!1}function Tb(s,t,n,r,a,i,l){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=r,this.attributeNamespace=a,this.mustUseProperty=n,this.propertyName=s,this.type=t,this.sanitizeURL=i,this.removeEmptyString=l}var pv={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(s){pv[s]=new Tb(s,0,!1,s,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(s){var t=s[0];pv[t]=new Tb(t,1,!1,s[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(s){pv[s]=new Tb(s,2,!1,s.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(s){pv[s]=new Tb(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){pv[s]=new Tb(s,3,!1,s.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(s){pv[s]=new Tb(s,3,!0,s,null,!1,!1)});["capture","download"].forEach(function(s){pv[s]=new Tb(s,4,!1,s,null,!1,!1)});["cols","rows","size","span"].forEach(function(s){pv[s]=new Tb(s,6,!1,s,null,!1,!1)});["rowSpan","start"].forEach(function(s){pv[s]=new Tb(s,5,!1,s.toLowerCase(),null,!1,!1)});var Yqe=/[\-:]([a-z])/g;function Zqe(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(Yqe,Zqe);pv[t]=new Tb(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(Yqe,Zqe);pv[t]=new Tb(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(Yqe,Zqe);pv[t]=new Tb(t,1,!1,s,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(s){pv[s]=new Tb(s,1,!1,s.toLowerCase(),null,!1,!1)});pv.xlinkHref=new Tb("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(s){pv[s]=new Tb(s,1,!1,s.toLowerCase(),null,!0,!0)});function Xqe(s,t,n,r){var a=pv.hasOwnProperty(t)?pv[t]:null;(a!==null?a.type!==0:r||!(2o||a[l]!==i[o]){var c=` `+a[l].replace(" at new "," at ");return s.displayName&&c.includes("")&&(c=c.replace("",s.displayName)),c}while(1<=l&&0<=o);break}}}finally{xPe=!1,Error.prepareStackTrace=n}return(s=s?s.displayName||s.name:"")?gW(s):""}function _Jt(s){switch(s.tag){case 5:return gW(s.type);case 16:return gW("Lazy");case 13:return gW("Suspense");case 19:return gW("SuspenseList");case 0:case 2:case 15:return s=yPe(s.type,!1),s;case 11:return s=yPe(s.type.render,!1),s;case 1:return s=yPe(s.type,!0),s;default:return""}}function uOe(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 J9:return"Fragment";case Q9:return"Portal";case lOe:return"Profiler";case Qqe:return"StrictMode";case cOe:return"Suspense";case dOe:return"SuspenseList"}if(typeof s=="object")switch(s.$$typeof){case N2t:return(s.displayName||"Context")+".Consumer";case j2t:return(s._context.displayName||"Context")+".Provider";case Jqe:var t=s.render;return s=s.displayName,s||(s=t.displayName||t.name||"",s=s!==""?"ForwardRef("+s+")":"ForwardRef"),s;case eVe:return t=s.displayName||null,t!==null?t:uOe(s.type)||"Memo";case lE:t=s._payload,s=s._init;try{return uOe(s(t))}catch{}}return null}function wJt(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 uOe(t);case 8:return t===Qqe?"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 bM(s){switch(typeof s){case"boolean":case"number":case"string":case"undefined":return s;case"object":return s;default:return""}}function S2t(s){var t=s.type;return(s=s.nodeName)&&s.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function jJt(s){var t=S2t(s)?"checked":"value",n=Object.getOwnPropertyDescriptor(s.constructor.prototype,t),r=""+s[t];if(!s.hasOwnProperty(t)&&typeof n<"u"&&typeof n.get=="function"&&typeof n.set=="function"){var a=n.get,i=n.set;return Object.defineProperty(s,t,{configurable:!0,get:function(){return a.call(this)},set:function(l){r=""+l,i.call(this,l)}}),Object.defineProperty(s,t,{enumerable:n.enumerable}),{getValue:function(){return r},setValue:function(l){r=""+l},stopTracking:function(){s._valueTracker=null,delete s[t]}}}}function xne(s){s._valueTracker||(s._valueTracker=jJt(s))}function C2t(s){if(!s)return!1;var t=s._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return s&&(r=S2t(s)?s.checked?"true":"false":s.value),s=r,s!==n?(t.setValue(s),!0):!1}function kke(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 hOe(s,t){var n=t.checked;return qp({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??s._wrapperState.initialChecked})}function Crt(s,t){var n=t.defaultValue==null?"":t.defaultValue,r=t.checked!=null?t.checked:t.defaultChecked;n=bM(t.value!=null?t.value:n),s._wrapperState={initialChecked:r,initialValue:n,controlled:t.type==="checkbox"||t.type==="radio"?t.checked!=null:t.value!=null}}function A2t(s,t){t=t.checked,t!=null&&Xqe(s,"checked",t,!1)}function mOe(s,t){A2t(s,t);var n=bM(t.value),r=t.type;if(n!=null)r==="number"?(n===0&&s.value===""||s.value!=n)&&(s.value=""+n):s.value!==""+n&&(s.value=""+n);else if(r==="submit"||r==="reset"){s.removeAttribute("value");return}t.hasOwnProperty("value")?fOe(s,t.type,n):t.hasOwnProperty("defaultValue")&&fOe(s,t.type,bM(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(s.defaultChecked=!!t.defaultChecked)}function Art(s,t,n){if(t.hasOwnProperty("value")||t.hasOwnProperty("defaultValue")){var r=t.type;if(!(r!=="submit"&&r!=="reset"||t.value!==void 0&&t.value!==null))return;t=""+s._wrapperState.initialValue,n||t===s.value||(s.value=t),s.defaultValue=t}n=s.name,n!==""&&(s.name=""),s.defaultChecked=!!s._wrapperState.initialChecked,n!==""&&(s.name=n)}function fOe(s,t,n){(t!=="number"||kke(s.ownerDocument)!==s)&&(n==null?s.defaultValue=""+s._wrapperState.initialValue:s.defaultValue!==""+n&&(s.defaultValue=""+n))}var xW=Array.isArray;function Pz(s,t,n,r){if(s=s.options,t){t={};for(var a=0;a"+t.valueOf().toString()+"",t=yne.firstChild;s.firstChild;)s.removeChild(s.firstChild);for(;t.firstChild;)s.appendChild(t.firstChild)}});function xZ(s,t){if(t){var n=s.firstChild;if(n&&n===s.lastChild&&n.nodeType===3){n.nodeValue=t;return}}s.textContent=t}var cK={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},NJt=["Webkit","ms","Moz","O"];Object.keys(cK).forEach(function(s){NJt.forEach(function(t){t=t+s.charAt(0).toUpperCase()+s.substring(1),cK[t]=cK[s]})});function P2t(s,t,n){return t==null||typeof t=="boolean"||t===""?"":n||typeof t!="number"||t===0||cK.hasOwnProperty(s)&&cK[s]?(""+t).trim():t+"px"}function I2t(s,t){s=s.style;for(var n in t)if(t.hasOwnProperty(n)){var r=n.indexOf("--")===0,a=P2t(n,t[n],r);n==="float"&&(n="cssFloat"),r?s.setProperty(n,a):s[n]=a}}var kJt=qp({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 xOe(s,t){if(t){if(kJt[s]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(Ga(137,s));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(Ga(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(Ga(61))}if(t.style!=null&&typeof t.style!="object")throw Error(Ga(62))}}function yOe(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 vOe=null;function tVe(s){return s=s.target||s.srcElement||window,s.correspondingUseElement&&(s=s.correspondingUseElement),s.nodeType===3?s.parentNode:s}var bOe=null,Iz=null,Lz=null;function Mrt(s){if(s=ZJ(s)){if(typeof bOe!="function")throw Error(Ga(280));var t=s.stateNode;t&&(t=qCe(t),bOe(s.stateNode,s.type,t))}}function L2t(s){Iz?Lz?Lz.push(s):Lz=[s]:Iz=s}function R2t(){if(Iz){var s=Iz,t=Lz;if(Lz=Iz=null,Mrt(s),t)for(s=0;s>>=0,s===0?32:31-(DJt(s)/OJt|0)|0}var vne=64,bne=4194304;function yW(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 Eke(s,t){var n=s.pendingLanes;if(n===0)return 0;var r=0,a=s.suspendedLanes,i=s.pingedLanes,l=n&268435455;if(l!==0){var o=l&~a;o!==0?r=yW(o):(i&=l,i!==0&&(r=yW(i)))}else l=n&~a,l!==0?r=yW(l):i!==0&&(r=yW(i));if(r===0)return 0;if(t!==0&&t!==r&&!(t&a)&&(a=r&-r,i=t&-t,a>=i||a===16&&(i&4194240)!==0))return t;if(r&4&&(r|=n&16),t=s.entangledLanes,t!==0)for(s=s.entanglements,t&=r;0n;n++)t.push(s);return t}function KJ(s,t,n){s.pendingLanes|=t,t!==536870912&&(s.suspendedLanes=0,s.pingedLanes=0),s=s.eventTimes,t=31-tk(t),s[t]=n}function $Jt(s,t){var n=s.pendingLanes&~t;s.pendingLanes=t,s.suspendedLanes=0,s.pingedLanes=0,s.expiredLanes&=t,s.mutableReadLanes&=t,s.entangledLanes&=t,t=s.entanglements;var r=s.eventTimes;for(s=s.expirationTimes;0=uK),Brt=" ",$rt=!1;function tNt(s,t){switch(s){case"keyup":return pes.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function sNt(s){return s=s.detail,typeof s=="object"&&"data"in s?s.data:null}var ez=!1;function xes(s,t){switch(s){case"compositionend":return sNt(t);case"keypress":return t.which!==32?null:($rt=!0,Brt);case"textInput":return s=t.data,s===Brt&&$rt?null:s;default:return null}}function yes(s,t){if(ez)return s==="compositionend"||!cVe&&tNt(s,t)?(s=J2t(),qie=iVe=xT=null,ez=!1,s):null;switch(s){case"paste":return null;case"keypress":if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1=t)return{node:n,offset:t-s};s=r}e:{for(;n;){if(n.nextSibling){n=n.nextSibling;break e}n=n.parentNode}n=void 0}n=Hrt(n)}}function iNt(s,t){return s&&t?s===t?!0:s&&s.nodeType===3?!1:t&&t.nodeType===3?iNt(s,t.parentNode):"contains"in s?s.contains(t):s.compareDocumentPosition?!!(s.compareDocumentPosition(t)&16):!1:!1}function oNt(){for(var s=window,t=kke();t instanceof s.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)s=t.contentWindow;else break;t=kke(s.document)}return t}function dVe(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 Ces(s){var t=oNt(),n=s.focusedElem,r=s.selectionRange;if(t!==n&&n&&n.ownerDocument&&iNt(n.ownerDocument.documentElement,n)){if(r!==null&&dVe(n)){if(t=r.start,s=r.end,s===void 0&&(s=t),"selectionStart"in n)n.selectionStart=t,n.selectionEnd=Math.min(s,n.value.length);else if(s=(t=n.ownerDocument||document)&&t.defaultView||window,s.getSelection){s=s.getSelection();var a=n.textContent.length,i=Math.min(r.start,a);r=r.end===void 0?i:Math.min(r.end,a),!s.extend&&i>r&&(a=r,r=i,i=a),a=Grt(n,i);var l=Grt(n,r);a&&l&&(s.rangeCount!==1||s.anchorNode!==a.node||s.anchorOffset!==a.offset||s.focusNode!==l.node||s.focusOffset!==l.offset)&&(t=t.createRange(),t.setStart(a.node,a.offset),s.removeAllRanges(),i>r?(s.addRange(t),s.extend(l.node,l.offset)):(t.setEnd(l.node,l.offset),s.addRange(t)))}}for(t=[],s=n;s=s.parentNode;)s.nodeType===1&&t.push({element:s,left:s.scrollLeft,top:s.scrollTop});for(typeof n.focus=="function"&&n.focus(),n=0;n=document.documentMode,tz=null,SOe=null,mK=null,COe=!1;function Wrt(s,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;COe||tz==null||tz!==kke(r)||(r=tz,"selectionStart"in r&&dVe(r)?r={start:r.selectionStart,end:r.selectionEnd}:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection(),r={anchorNode:r.anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset}),mK&&jZ(mK,r)||(mK=r,r=Pke(SOe,"onSelect"),0rz||(s.current=IOe[rz],IOe[rz]=null,rz--)}function Om(s,t){rz++,IOe[rz]=s.current,s.current=t}var _M={},p1=HM(_M),g_=HM(!1),_O=_M;function iU(s,t){var n=s.type.contextTypes;if(!n)return _M;var r=s.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===t)return r.__reactInternalMemoizedMaskedChildContext;var a={},i;for(i in n)a[i]=t[i];return r&&(s=s.stateNode,s.__reactInternalMemoizedUnmaskedChildContext=t,s.__reactInternalMemoizedMaskedChildContext=a),a}function x_(s){return s=s.childContextTypes,s!=null}function Lke(){Nf(g_),Nf(p1)}function eat(s,t,n){if(p1.current!==_M)throw Error(Ga(168));Om(p1,t),Om(g_,n)}function gNt(s,t,n){var r=s.stateNode;if(t=t.childContextTypes,typeof r.getChildContext!="function")return n;r=r.getChildContext();for(var a in r)if(!(a in t))throw Error(Ga(108,wJt(s)||"Unknown",a));return qp({},n,r)}function Rke(s){return s=(s=s.stateNode)&&s.__reactInternalMemoizedMergedChildContext||_M,_O=p1.current,Om(p1,s),Om(g_,g_.current),!0}function tat(s,t,n){var r=s.stateNode;if(!r)throw Error(Ga(169));n?(s=gNt(s,t,_O),r.__reactInternalMemoizedMergedChildContext=s,Nf(g_),Nf(p1),Om(p1,s)):Nf(g_),Om(g_,n)}var bC=null,VCe=!1,PPe=!1;function xNt(s){bC===null?bC=[s]:bC.push(s)}function zes(s){VCe=!0,xNt(s)}function GM(){if(!PPe&&bC!==null){PPe=!0;var s=0,t=Oh;try{var n=bC;for(Oh=1;s>=l,a-=l,t3=1<<32-tk(t)+a|n<P?(R=I,I=null):R=I.sibling;var O=m(v,I,j[P],C);if(O===null){I===null&&(I=R);break}s&&I&&O.alternate===null&&t(v,I),_=i(O,_,P),M===null?A=O:M.sibling=O,M=O,I=R}if(P===j.length)return n(v,I),tp&&_P(v,P),A;if(I===null){for(;PP?(R=I,I=null):R=I.sibling;var B=m(v,I,O.value,C);if(B===null){I===null&&(I=R);break}s&&I&&B.alternate===null&&t(v,I),_=i(B,_,P),M===null?A=B:M.sibling=B,M=B,I=R}if(O.done)return n(v,I),tp&&_P(v,P),A;if(I===null){for(;!O.done;P++,O=j.next())O=h(v,O.value,C),O!==null&&(_=i(O,_,P),M===null?A=O:M.sibling=O,M=O);return tp&&_P(v,P),A}for(I=r(v,I);!O.done;P++,O=j.next())O=p(I,v,P,O.value,C),O!==null&&(s&&O.alternate!==null&&I.delete(O.key===null?P:O.key),_=i(O,_,P),M===null?A=O:M.sibling=O,M=O);return s&&I.forEach(function(U){return t(v,U)}),tp&&_P(v,P),A}function y(v,_,j,C){if(typeof j=="object"&&j!==null&&j.type===J9&&j.key===null&&(j=j.props.children),typeof j=="object"&&j!==null){switch(j.$$typeof){case gne:e:{for(var A=j.key,M=_;M!==null;){if(M.key===A){if(A=j.type,A===J9){if(M.tag===7){n(v,M.sibling),_=a(M,j.props.children),_.return=v,v=_;break e}}else if(M.elementType===A||typeof A=="object"&&A!==null&&A.$$typeof===lE&&rat(A)===M.type){n(v,M.sibling),_=a(M,j.props),_.ref=YH(v,M,j),_.return=v,v=_;break e}n(v,M);break}else t(v,M);M=M.sibling}j.type===J9?(_=E8(j.props.children,v.mode,C,j.key),_.return=v,v=_):(C=Xie(j.type,j.key,j.props,null,v.mode,C),C.ref=YH(v,_,j),C.return=v,v=C)}return l(v);case Q9:e:{for(M=j.key;_!==null;){if(_.key===M)if(_.tag===4&&_.stateNode.containerInfo===j.containerInfo&&_.stateNode.implementation===j.implementation){n(v,_.sibling),_=a(_,j.children||[]),_.return=v,v=_;break e}else{n(v,_);break}else t(v,_);_=_.sibling}_=BPe(j,v.mode,C),_.return=v,v=_}return l(v);case lE:return M=j._init,y(v,_,M(j._payload),C)}if(xW(j))return g(v,_,j,C);if(VH(j))return x(v,_,j,C);Cne(v,j)}return typeof j=="string"&&j!==""||typeof j=="number"?(j=""+j,_!==null&&_.tag===6?(n(v,_.sibling),_=a(_,j),_.return=v,v=_):(n(v,_),_=zPe(j,v.mode,C),_.return=v,v=_),l(v)):n(v,_)}return y}var lU=_Nt(!0),wNt=_Nt(!1),Fke=HM(null),zke=null,oz=null,fVe=null;function pVe(){fVe=oz=zke=null}function gVe(s){var t=Fke.current;Nf(Fke),s._currentValue=t}function DOe(s,t,n){for(;s!==null;){var r=s.alternate;if((s.childLanes&t)!==t?(s.childLanes|=t,r!==null&&(r.childLanes|=t)):r!==null&&(r.childLanes&t)!==t&&(r.childLanes|=t),s===n)break;s=s.return}}function Dz(s,t){zke=s,fVe=oz=null,s=s.dependencies,s!==null&&s.firstContext!==null&&(s.lanes&t&&(h_=!0),s.firstContext=null)}function M2(s){var t=s._currentValue;if(fVe!==s)if(s={context:s,memoizedValue:t,next:null},oz===null){if(zke===null)throw Error(Ga(308));oz=s,zke.dependencies={lanes:0,firstContext:s}}else oz=oz.next=s;return t}var eD=null;function xVe(s){eD===null?eD=[s]:eD.push(s)}function jNt(s,t,n,r){var a=t.interleaved;return a===null?(n.next=n,xVe(t)):(n.next=a.next,a.next=n),t.interleaved=n,O3(s,r)}function O3(s,t){s.lanes|=t;var n=s.alternate;for(n!==null&&(n.lanes|=t),n=s,s=s.return;s!==null;)s.childLanes|=t,n=s.alternate,n!==null&&(n.childLanes|=t),n=s,s=s.return;return n.tag===3?n.stateNode:null}var cE=!1;function yVe(s){s.updateQueue={baseState:s.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function NNt(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 m3(s,t){return{eventTime:s,lane:t,tag:0,payload:null,callback:null,next:null}}function IT(s,t,n){var r=s.updateQueue;if(r===null)return null;if(r=r.shared,Nu&2){var a=r.pending;return a===null?t.next=t:(t.next=a.next,a.next=t),r.pending=t,O3(s,n)}return a=r.interleaved,a===null?(t.next=t,xVe(r)):(t.next=a.next,a.next=t),r.interleaved=t,O3(s,n)}function Hie(s,t,n){if(t=t.updateQueue,t!==null&&(t=t.shared,(n&4194240)!==0)){var r=t.lanes;r&=s.pendingLanes,n|=r,t.lanes=n,nVe(s,n)}}function aat(s,t){var n=s.updateQueue,r=s.alternate;if(r!==null&&(r=r.updateQueue,n===r)){var a=null,i=null;if(n=n.firstBaseUpdate,n!==null){do{var l={eventTime:n.eventTime,lane:n.lane,tag:n.tag,payload:n.payload,callback:n.callback,next:null};i===null?a=i=l:i=i.next=l,n=n.next}while(n!==null);i===null?a=i=t:i=i.next=t}else a=i=t;n={baseState:r.baseState,firstBaseUpdate:a,lastBaseUpdate:i,shared:r.shared,effects:r.effects},s.updateQueue=n;return}s=n.lastBaseUpdate,s===null?n.firstBaseUpdate=t:s.next=t,n.lastBaseUpdate=t}function Bke(s,t,n,r){var a=s.updateQueue;cE=!1;var i=a.firstBaseUpdate,l=a.lastBaseUpdate,o=a.shared.pending;if(o!==null){a.shared.pending=null;var c=o,d=c.next;c.next=null,l===null?i=d:l.next=d,l=c;var u=s.alternate;u!==null&&(u=u.updateQueue,o=u.lastBaseUpdate,o!==l&&(o===null?u.firstBaseUpdate=d:o.next=d,u.lastBaseUpdate=c))}if(i!==null){var h=a.baseState;l=0,u=d=c=null,o=i;do{var m=o.lane,p=o.eventTime;if((r&m)===m){u!==null&&(u=u.next={eventTime:p,lane:0,tag:o.tag,payload:o.payload,callback:o.callback,next:null});e:{var g=s,x=o;switch(m=t,p=n,x.tag){case 1:if(g=x.payload,typeof g=="function"){h=g.call(p,h,m);break e}h=g;break e;case 3:g.flags=g.flags&-65537|128;case 0:if(g=x.payload,m=typeof g=="function"?g.call(p,h,m):g,m==null)break e;h=qp({},h,m);break e;case 2:cE=!0}}o.callback!==null&&o.lane!==0&&(s.flags|=64,m=a.effects,m===null?a.effects=[o]:m.push(o))}else p={eventTime:p,lane:m,tag:o.tag,payload:o.payload,callback:o.callback,next:null},u===null?(d=u=p,c=h):u=u.next=p,l|=m;if(o=o.next,o===null){if(o=a.shared.pending,o===null)break;m=o,o=m.next,m.next=null,a.lastBaseUpdate=m,a.shared.pending=null}}while(!0);if(u===null&&(c=h),a.baseState=c,a.firstBaseUpdate=d,a.lastBaseUpdate=u,t=a.shared.interleaved,t!==null){a=t;do l|=a.lane,a=a.next;while(a!==t)}else i===null&&(a.shared.lanes=0);NO|=l,s.lanes=l,s.memoizedState=h}}function iat(s,t,n){if(s=t.effects,t.effects=null,s!==null)for(t=0;tn?n:4,s(!0);var r=LPe.transition;LPe.transition={};try{s(!1),t()}finally{Oh=n,LPe.transition=r}}function $Nt(){return P2().memoizedState}function qes(s,t,n){var r=RT(s);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},UNt(s))qNt(t,n);else if(n=jNt(s,t,n,r),n!==null){var a=mb();sk(n,s,r,a),VNt(n,t,r)}}function Ves(s,t,n){var r=RT(s),a={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(UNt(s))qNt(t,a);else{var i=s.alternate;if(s.lanes===0&&(i===null||i.lanes===0)&&(i=t.lastRenderedReducer,i!==null))try{var l=t.lastRenderedState,o=i(l,n);if(a.hasEagerState=!0,a.eagerState=o,gk(o,l)){var c=t.interleaved;c===null?(a.next=a,xVe(t)):(a.next=c.next,c.next=a),t.interleaved=a;return}}catch{}finally{}n=jNt(s,t,a,r),n!==null&&(a=mb(),sk(n,s,r,a),VNt(n,t,r))}}function UNt(s){var t=s.alternate;return s===Fp||t!==null&&t===Fp}function qNt(s,t){fK=Uke=!0;var n=s.pending;n===null?t.next=t:(t.next=n.next,n.next=t),s.pending=t}function VNt(s,t,n){if(n&4194240){var r=t.lanes;r&=s.pendingLanes,n|=r,t.lanes=n,nVe(s,n)}}var qke={readContext:M2,useCallback:zv,useContext:zv,useEffect:zv,useImperativeHandle:zv,useInsertionEffect:zv,useLayoutEffect:zv,useMemo:zv,useReducer:zv,useRef:zv,useState:zv,useDebugValue:zv,useDeferredValue:zv,useTransition:zv,useMutableSource:zv,useSyncExternalStore:zv,useId:zv,unstable_isNewReconciler:!1},Hes={readContext:M2,useCallback:function(s,t){return NS().memoizedState=[s,t===void 0?null:t],s},useContext:M2,useEffect:lat,useImperativeHandle:function(s,t,n){return n=n!=null?n.concat([s]):null,Wie(4194308,4,DNt.bind(null,t,s),n)},useLayoutEffect:function(s,t){return Wie(4194308,4,s,t)},useInsertionEffect:function(s,t){return Wie(4,2,s,t)},useMemo:function(s,t){var n=NS();return t=t===void 0?null:t,s=s(),n.memoizedState=[s,t],s},useReducer:function(s,t,n){var r=NS();return t=n!==void 0?n(t):t,r.memoizedState=r.baseState=t,s={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:s,lastRenderedState:t},r.queue=s,s=s.dispatch=qes.bind(null,Fp,s),[r.memoizedState,s]},useRef:function(s){var t=NS();return s={current:s},t.memoizedState=s},useState:oat,useDebugValue:SVe,useDeferredValue:function(s){return NS().memoizedState=s},useTransition:function(){var s=oat(!1),t=s[0];return s=Ues.bind(null,s[1]),NS().memoizedState=s,[t,s]},useMutableSource:function(){},useSyncExternalStore:function(s,t,n){var r=Fp,a=NS();if(tp){if(n===void 0)throw Error(Ga(407));n=n()}else{if(n=t(),f0===null)throw Error(Ga(349));jO&30||ANt(r,t,n)}a.memoizedState=n;var i={value:n,getSnapshot:t};return a.queue=i,lat(TNt.bind(null,r,i,s),[s]),r.flags|=2048,MZ(9,ENt.bind(null,r,i,n,t),void 0,null),n},useId:function(){var s=NS(),t=f0.identifierPrefix;if(tp){var n=s3,r=t3;n=(r&~(1<<32-tk(r)-1)).toString(32)+n,t=":"+t+"R"+n,n=EZ++,0<\/script>",s=s.removeChild(s.firstChild)):typeof r.is=="string"?s=l.createElement(n,{is:r.is}):(s=l.createElement(n),n==="select"&&(l=s,r.multiple?l.multiple=!0:r.size&&(l.size=r.size))):s=l.createElementNS(s,n),s[o5]=t,s[SZ]=r,ekt(s,t,!1,!1),t.stateNode=s;e:{switch(l=yOe(n,r),n){case"dialog":ff("cancel",s),ff("close",s),a=r;break;case"iframe":case"object":case"embed":ff("load",s),a=r;break;case"video":case"audio":for(a=0;auU&&(t.flags|=128,r=!0,ZH(i,!1),t.lanes=4194304)}else{if(!r)if(s=$ke(l),s!==null){if(t.flags|=128,r=!0,n=s.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),ZH(i,!0),i.tail===null&&i.tailMode==="hidden"&&!l.alternate&&!tp)return Bv(t),null}else 2*Wg()-i.renderingStartTime>uU&&n!==1073741824&&(t.flags|=128,r=!0,ZH(i,!1),t.lanes=4194304);i.isBackwards?(l.sibling=t.child,t.child=l):(n=i.last,n!==null?n.sibling=l:t.child=l,i.last=l)}return i.tail!==null?(t=i.tail,i.rendering=t,i.tail=t.sibling,i.renderingStartTime=Wg(),t.sibling=null,n=Ep.current,Om(Ep,r?n&1|2:n&1),t):(Bv(t),null);case 22:case 23:return PVe(),r=t.memoizedState!==null,s!==null&&s.memoizedState!==null!==r&&(t.flags|=8192),r&&t.mode&1?Iw&1073741824&&(Bv(t),t.subtreeFlags&6&&(t.flags|=8192)):Bv(t),null;case 24:return null;case 25:return null}throw Error(Ga(156,t.tag))}function Jes(s,t){switch(hVe(t),t.tag){case 1:return x_(t.type)&&Lke(),s=t.flags,s&65536?(t.flags=s&-65537|128,t):null;case 3:return cU(),Nf(g_),Nf(p1),_Ve(),s=t.flags,s&65536&&!(s&128)?(t.flags=s&-65537|128,t):null;case 5:return bVe(t),null;case 13:if(Nf(Ep),s=t.memoizedState,s!==null&&s.dehydrated!==null){if(t.alternate===null)throw Error(Ga(340));oU()}return s=t.flags,s&65536?(t.flags=s&-65537|128,t):null;case 19:return Nf(Ep),null;case 4:return cU(),null;case 10:return gVe(t.type._context),null;case 22:case 23:return PVe(),null;case 24:return null;default:return null}}var Ene=!1,s1=!1,ets=typeof WeakSet=="function"?WeakSet:Set,go=null;function lz(s,t){var n=s.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){pg(s,t,r)}else n.current=null}function HOe(s,t,n){try{n()}catch(r){pg(s,t,r)}}var vat=!1;function tts(s,t){if(AOe=Tke,s=oNt(),dVe(s)){if("selectionStart"in s)var n={start:s.selectionStart,end:s.selectionEnd};else e:{n=(n=s.ownerDocument)&&n.defaultView||window;var r=n.getSelection&&n.getSelection();if(r&&r.rangeCount!==0){n=r.anchorNode;var a=r.anchorOffset,i=r.focusNode;r=r.focusOffset;try{n.nodeType,i.nodeType}catch{n=null;break e}var l=0,o=-1,c=-1,d=0,u=0,h=s,m=null;t:for(;;){for(var p;h!==n||a!==0&&h.nodeType!==3||(o=l+a),h!==i||r!==0&&h.nodeType!==3||(c=l+r),h.nodeType===3&&(l+=h.nodeValue.length),(p=h.firstChild)!==null;)m=h,h=p;for(;;){if(h===s)break t;if(m===n&&++d===a&&(o=l),m===i&&++u===r&&(c=l),(p=h.nextSibling)!==null)break;h=m,m=h.parentNode}h=p}n=o===-1||c===-1?null:{start:o,end:c}}else n=null}n=n||{start:0,end:0}}else n=null;for(EOe={focusedElem:s,selectionRange:n},Tke=!1,go=t;go!==null;)if(t=go,s=t.child,(t.subtreeFlags&1028)!==0&&s!==null)s.return=t,go=s;else for(;go!==null;){t=go;try{var g=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(g!==null){var x=g.memoizedProps,y=g.memoizedState,v=t.stateNode,_=v.getSnapshotBeforeUpdate(t.elementType===t.type?x:jN(t.type,x),y);v.__reactInternalSnapshotBeforeUpdate=_}break;case 3:var j=t.stateNode.containerInfo;j.nodeType===1?j.textContent="":j.nodeType===9&&j.documentElement&&j.removeChild(j.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(Ga(163))}}catch(C){pg(t,t.return,C)}if(s=t.sibling,s!==null){s.return=t.return,go=s;break}go=t.return}return g=vat,vat=!1,g}function pK(s,t,n){var r=t.updateQueue;if(r=r!==null?r.lastEffect:null,r!==null){var a=r=r.next;do{if((a.tag&s)===s){var i=a.destroy;a.destroy=void 0,i!==void 0&&HOe(t,n,i)}a=a.next}while(a!==r)}}function WCe(s,t){if(t=t.updateQueue,t=t!==null?t.lastEffect:null,t!==null){var n=t=t.next;do{if((n.tag&s)===s){var r=n.create;n.destroy=r()}n=n.next}while(n!==t)}}function GOe(s){var t=s.ref;if(t!==null){var n=s.stateNode;switch(s.tag){case 5:s=n;break;default:s=n}typeof t=="function"?t(s):t.current=s}}function nkt(s){var t=s.alternate;t!==null&&(s.alternate=null,nkt(t)),s.child=null,s.deletions=null,s.sibling=null,s.tag===5&&(t=s.stateNode,t!==null&&(delete t[o5],delete t[SZ],delete t[POe],delete t[Oes],delete t[Fes])),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 rkt(s){return s.tag===5||s.tag===3||s.tag===4}function bat(s){e:for(;;){for(;s.sibling===null;){if(s.return===null||rkt(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 WOe(s,t,n){var r=s.tag;if(r===5||r===6)s=s.stateNode,t?n.nodeType===8?n.parentNode.insertBefore(s,t):n.insertBefore(s,t):(n.nodeType===8?(t=n.parentNode,t.insertBefore(s,n)):(t=n,t.appendChild(s)),n=n._reactRootContainer,n!=null||t.onclick!==null||(t.onclick=Ike));else if(r!==4&&(s=s.child,s!==null))for(WOe(s,t,n),s=s.sibling;s!==null;)WOe(s,t,n),s=s.sibling}function KOe(s,t,n){var r=s.tag;if(r===5||r===6)s=s.stateNode,t?n.insertBefore(s,t):n.appendChild(s);else if(r!==4&&(s=s.child,s!==null))for(KOe(s,t,n),s=s.sibling;s!==null;)KOe(s,t,n),s=s.sibling}var G0=null,zN=!1;function IA(s,t,n){for(n=n.child;n!==null;)akt(s,t,n),n=n.sibling}function akt(s,t,n){if(w5&&typeof w5.onCommitFiberUnmount=="function")try{w5.onCommitFiberUnmount(zCe,n)}catch{}switch(n.tag){case 5:s1||lz(n,t);case 6:var r=G0,a=zN;G0=null,IA(s,t,n),G0=r,zN=a,G0!==null&&(zN?(s=G0,n=n.stateNode,s.nodeType===8?s.parentNode.removeChild(n):s.removeChild(n)):G0.removeChild(n.stateNode));break;case 18:G0!==null&&(zN?(s=G0,n=n.stateNode,s.nodeType===8?MPe(s.parentNode,n):s.nodeType===1&&MPe(s,n),_Z(s)):MPe(G0,n.stateNode));break;case 4:r=G0,a=zN,G0=n.stateNode.containerInfo,zN=!0,IA(s,t,n),G0=r,zN=a;break;case 0:case 11:case 14:case 15:if(!s1&&(r=n.updateQueue,r!==null&&(r=r.lastEffect,r!==null))){a=r=r.next;do{var i=a,l=i.destroy;i=i.tag,l!==void 0&&(i&2||i&4)&&HOe(n,t,l),a=a.next}while(a!==r)}IA(s,t,n);break;case 1:if(!s1&&(lz(n,t),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(o){pg(n,t,o)}IA(s,t,n);break;case 21:IA(s,t,n);break;case 22:n.mode&1?(s1=(r=s1)||n.memoizedState!==null,IA(s,t,n),s1=r):IA(s,t,n);break;default:IA(s,t,n)}}function _at(s){var t=s.updateQueue;if(t!==null){s.updateQueue=null;var n=s.stateNode;n===null&&(n=s.stateNode=new ets),t.forEach(function(r){var a=dts.bind(null,s,r);n.has(r)||(n.add(r),r.then(a,a))})}}function cN(s,t){var n=t.deletions;if(n!==null)for(var r=0;ra&&(a=l),r&=~i}if(r=a,r=Wg()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*nts(r/1960))-r,10s?16:s,yT===null)var r=!1;else{if(s=yT,yT=null,Gke=0,Nu&6)throw Error(Ga(331));var a=Nu;for(Nu|=4,go=s.current;go!==null;){var i=go,l=i.child;if(go.flags&16){var o=i.deletions;if(o!==null){for(var c=0;cWg()-TVe?A8(s,0):EVe|=n),y_(s,t)}function mkt(s,t){t===0&&(s.mode&1?(t=bne,bne<<=1,!(bne&130023424)&&(bne=4194304)):t=1);var n=mb();s=O3(s,t),s!==null&&(KJ(s,t,n),y_(s,n))}function cts(s){var t=s.memoizedState,n=0;t!==null&&(n=t.retryLane),mkt(s,n)}function dts(s,t){var n=0;switch(s.tag){case 13:var r=s.stateNode,a=s.memoizedState;a!==null&&(n=a.retryLane);break;case 19:r=s.stateNode;break;default:throw Error(Ga(314))}r!==null&&r.delete(t),mkt(s,n)}var fkt;fkt=function(s,t,n){if(s!==null)if(s.memoizedProps!==t.pendingProps||g_.current)h_=!0;else{if(!(s.lanes&n)&&!(t.flags&128))return h_=!1,Xes(s,t,n);h_=!!(s.flags&131072)}else h_=!1,tp&&t.flags&1048576&&yNt(t,Oke,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;Kie(s,t),s=t.pendingProps;var a=iU(t,p1.current);Dz(t,n),a=jVe(null,t,r,s,a,n);var i=NVe();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,x_(r)?(i=!0,Rke(t)):i=!1,t.memoizedState=a.state!==null&&a.state!==void 0?a.state:null,yVe(t),a.updater=GCe,t.stateNode=a,a._reactInternals=t,FOe(t,r,s,n),t=$Oe(null,t,r,!0,i,n)):(t.tag=0,tp&&i&&uVe(t),Q1(null,t,a,n),t=t.child),t;case 16:r=t.elementType;e:{switch(Kie(s,t),s=t.pendingProps,a=r._init,r=a(r._payload),t.type=r,a=t.tag=hts(r),s=jN(r,s),a){case 0:t=BOe(null,t,r,s,n);break e;case 1:t=gat(null,t,r,s,n);break e;case 11:t=fat(null,t,r,s,n);break e;case 14:t=pat(null,t,r,jN(r.type,s),n);break e}throw Error(Ga(306,r,""))}return t;case 0:return r=t.type,a=t.pendingProps,a=t.elementType===r?a:jN(r,a),BOe(s,t,r,a,n);case 1:return r=t.type,a=t.pendingProps,a=t.elementType===r?a:jN(r,a),gat(s,t,r,a,n);case 3:e:{if(XNt(t),s===null)throw Error(Ga(387));r=t.pendingProps,i=t.memoizedState,a=i.element,NNt(s,t),Bke(t,r,null,n);var l=t.memoizedState;if(r=l.element,i.isDehydrated)if(i={element:r,isDehydrated:!1,cache:l.cache,pendingSuspenseBoundaries:l.pendingSuspenseBoundaries,transitions:l.transitions},t.updateQueue.baseState=i,t.memoizedState=i,t.flags&256){a=dU(Error(Ga(423)),t),t=xat(s,t,r,n,a);break e}else if(r!==a){a=dU(Error(Ga(424)),t),t=xat(s,t,r,n,a);break e}else for(Vw=PT(t.stateNode.containerInfo.firstChild),Kw=t,tp=!0,HN=null,n=wNt(t,null,r,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(oU(),r===a){t=F3(s,t,n);break e}Q1(s,t,r,n)}t=t.child}return t;case 5:return kNt(t),s===null&&ROe(t),r=t.type,a=t.pendingProps,i=s!==null?s.memoizedProps:null,l=a.children,TOe(r,a)?l=null:i!==null&&TOe(r,i)&&(t.flags|=32),ZNt(s,t),Q1(s,t,l,n),t.child;case 6:return s===null&&ROe(t),null;case 13:return QNt(s,t,n);case 4:return vVe(t,t.stateNode.containerInfo),r=t.pendingProps,s===null?t.child=lU(t,null,r,n):Q1(s,t,r,n),t.child;case 11:return r=t.type,a=t.pendingProps,a=t.elementType===r?a:jN(r,a),fat(s,t,r,a,n);case 7:return Q1(s,t,t.pendingProps,n),t.child;case 8:return Q1(s,t,t.pendingProps.children,n),t.child;case 12:return Q1(s,t,t.pendingProps.children,n),t.child;case 10:e:{if(r=t.type._context,a=t.pendingProps,i=t.memoizedProps,l=a.value,Om(Fke,r._currentValue),r._currentValue=l,i!==null)if(gk(i.value,l)){if(i.children===a.children&&!g_.current){t=F3(s,t,n);break e}}else for(i=t.child,i!==null&&(i.return=t);i!==null;){var o=i.dependencies;if(o!==null){l=i.child;for(var c=o.firstContext;c!==null;){if(c.context===r){if(i.tag===1){c=m3(-1,n&-n),c.tag=2;var d=i.updateQueue;if(d!==null){d=d.shared;var u=d.pending;u===null?c.next=c:(c.next=u.next,u.next=c),d.pending=c}}i.lanes|=n,c=i.alternate,c!==null&&(c.lanes|=n),DOe(i.return,n,t),o.lanes|=n;break}c=c.next}}else if(i.tag===10)l=i.type===t.type?null:i.child;else if(i.tag===18){if(l=i.return,l===null)throw Error(Ga(341));l.lanes|=n,o=l.alternate,o!==null&&(o.lanes|=n),DOe(l,n,t),l=i.sibling}else l=i.child;if(l!==null)l.return=i;else for(l=i;l!==null;){if(l===t){l=null;break}if(i=l.sibling,i!==null){i.return=l.return,l=i;break}l=l.return}i=l}Q1(s,t,a.children,n),t=t.child}return t;case 9:return a=t.type,r=t.pendingProps.children,Dz(t,n),a=M2(a),r=r(a),t.flags|=1,Q1(s,t,r,n),t.child;case 14:return r=t.type,a=jN(r,t.pendingProps),a=jN(r.type,a),pat(s,t,r,a,n);case 15:return KNt(s,t,t.type,t.pendingProps,n);case 17:return r=t.type,a=t.pendingProps,a=t.elementType===r?a:jN(r,a),Kie(s,t),t.tag=1,x_(r)?(s=!0,Rke(t)):s=!1,Dz(t,n),HNt(t,r,a),FOe(t,r,a,n),$Oe(null,t,r,!0,s,n);case 19:return JNt(s,t,n);case 22:return YNt(s,t,n)}throw Error(Ga(156,t.tag))};function pkt(s,t){return U2t(s,t)}function uts(s,t,n,r){this.tag=s,this.key=n,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=t,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=r,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function h2(s,t,n,r){return new uts(s,t,n,r)}function LVe(s){return s=s.prototype,!(!s||!s.isReactComponent)}function hts(s){if(typeof s=="function")return LVe(s)?1:0;if(s!=null){if(s=s.$$typeof,s===Jqe)return 11;if(s===eVe)return 14}return 2}function DT(s,t){var n=s.alternate;return n===null?(n=h2(s.tag,t,s.key,s.mode),n.elementType=s.elementType,n.type=s.type,n.stateNode=s.stateNode,n.alternate=s,s.alternate=n):(n.pendingProps=t,n.type=s.type,n.flags=0,n.subtreeFlags=0,n.deletions=null),n.flags=s.flags&14680064,n.childLanes=s.childLanes,n.lanes=s.lanes,n.child=s.child,n.memoizedProps=s.memoizedProps,n.memoizedState=s.memoizedState,n.updateQueue=s.updateQueue,t=s.dependencies,n.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext},n.sibling=s.sibling,n.index=s.index,n.ref=s.ref,n}function Xie(s,t,n,r,a,i){var l=2;if(r=s,typeof s=="function")LVe(s)&&(l=1);else if(typeof s=="string")l=5;else e:switch(s){case J9:return E8(n.children,a,i,t);case Qqe:l=8,a|=8;break;case lOe:return s=h2(12,n,t,a|2),s.elementType=lOe,s.lanes=i,s;case cOe:return s=h2(13,n,t,a),s.elementType=cOe,s.lanes=i,s;case dOe:return s=h2(19,n,t,a),s.elementType=dOe,s.lanes=i,s;case k2t:return YCe(n,a,i,t);default:if(typeof s=="object"&&s!==null)switch(s.$$typeof){case j2t:l=10;break e;case N2t:l=9;break e;case Jqe:l=11;break e;case eVe:l=14;break e;case lE:l=16,r=null;break e}throw Error(Ga(130,s==null?s:typeof s,""))}return t=h2(l,n,t,a),t.elementType=s,t.type=r,t.lanes=i,t}function E8(s,t,n,r){return s=h2(7,s,r,t),s.lanes=n,s}function YCe(s,t,n,r){return s=h2(22,s,r,t),s.elementType=k2t,s.lanes=n,s.stateNode={isHidden:!1},s}function zPe(s,t,n){return s=h2(6,s,null,t),s.lanes=n,s}function BPe(s,t,n){return t=h2(4,s.children!==null?s.children:[],s.key,t),t.lanes=n,t.stateNode={containerInfo:s.containerInfo,pendingChildren:null,implementation:s.implementation},t}function mts(s,t,n,r,a){this.tag=t,this.containerInfo=s,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=bPe(0),this.expirationTimes=bPe(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=bPe(0),this.identifierPrefix=r,this.onRecoverableError=a,this.mutableSourceEagerHydrationData=null}function RVe(s,t,n,r,a,i,l,o,c){return s=new mts(s,t,n,o,c),t===1?(t=1,i===!0&&(t|=8)):t=0,i=h2(3,null,null,t),s.current=i,i.stateNode=s,i.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},yVe(i),s}function fts(s,t,n){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(vkt)}catch(s){console.error(s)}}vkt(),v2t.exports=mj;var a1=v2t.exports;const bkt=kd(a1);var _kt,Eat=a1;_kt=Eat.createRoot,Eat.hydrateRoot;const vts=new Set(["localhost","relevelup.com","thelocalmove.com","www.thelocalmove.com"]),bts=s=>s.toLowerCase().replace(/:\d+$/,"").replace(/^www\./,"");function _ts(s){return!!(s==="localhost"||s.endsWith(".localhost")||/^\d{1,3}(\.\d{1,3}){3}$/.test(s)||s.endsWith(".lovable.app")||s.endsWith(".lovableproject.com")||s.endsWith(".lovable.dev")||s.endsWith(".vercel.app")||s==="relevelup.com"||s.endsWith(".relevelup.com")||s==="thelocalmove.com"||s.endsWith(".thelocalmove.com")||vts.has(s))}function wkt(s){return jkt(s)!==null}function jkt(s){const t=bts(s);return _ts(t)?null:t}const wts=1,jts=1e6;let $Pe=0;function Nts(){return $Pe=($Pe+1)%Number.MAX_SAFE_INTEGER,$Pe.toString()}const UPe=new Map,Tat=s=>{if(UPe.has(s))return;const t=setTimeout(()=>{UPe.delete(s),yK({type:"REMOVE_TOAST",toastId:s})},jts);UPe.set(s,t)},kts=(s,t)=>{switch(t.type){case"ADD_TOAST":return{...s,toasts:[t.toast,...s.toasts].slice(0,wts)};case"UPDATE_TOAST":return{...s,toasts:s.toasts.map(n=>n.id===t.toast.id?{...n,...t.toast}:n)};case"DISMISS_TOAST":{const{toastId:n}=t;return n?Tat(n):s.toasts.forEach(r=>{Tat(r.id)}),{...s,toasts:s.toasts.map(r=>r.id===n||n===void 0?{...r,open:!1}:r)}}case"REMOVE_TOAST":return t.toastId===void 0?{...s,toasts:[]}:{...s,toasts:s.toasts.filter(n=>n.id!==t.toastId)}}},Qie=[];let Jie={toasts:[]};function yK(s){Jie=kts(Jie,s),Qie.forEach(t=>{t(Jie)})}function Ma({...s}){const t=Nts(),n=a=>yK({type:"UPDATE_TOAST",toast:{...a,id:t}}),r=()=>yK({type:"DISMISS_TOAST",toastId:t});return yK({type:"ADD_TOAST",toast:{...s,id:t,open:!0,onOpenChange:a=>{a||r()}}}),{id:t,dismiss:r,update:n}}function Fi(){const[s,t]=k.useState(Jie);return k.useEffect(()=>(Qie.push(t),()=>{const n=Qie.indexOf(t);n>-1&&Qie.splice(n,1)}),[s]),{...s,toast:Ma,dismiss:n=>yK({type:"DISMISS_TOAST",toastId:n})}}var Sts=Object.defineProperty,Eq=(s,t)=>Sts(s,"name",{value:t,configurable:!0}),Nkt=!!(typeof window<"u"&&window.document&&window.document.createElement);function ga(s,t,{checkForDefaultPrevented:n=!0}={}){return Eq(function(a){if(s==null||s(a),n===!1||!a||!a.defaultPrevented)return t==null?void 0:t(a)},"handleEvent")}Eq(ga,"composeEventHandlers");function Cts(s){var t;if(!Nkt)throw new Error("Cannot access window outside of the DOM");return((t=s==null?void 0:s.ownerDocument)==null?void 0:t.defaultView)??window}Eq(Cts,"getOwnerWindow");function JOe(s){if(!Nkt)throw new Error("Cannot access document outside of the DOM");return(s==null?void 0:s.ownerDocument)??document}Eq(JOe,"getOwnerDocument");function kkt(s,t=!1){const{activeElement:n}=JOe(s);if(!(n!=null&&n.nodeName))return null;if(Skt(n)&&n.contentDocument)return kkt(n.contentDocument.body,t);if(t){const r=n.getAttribute("aria-activedescendant");if(r){const a=JOe(n).getElementById(r);if(a)return a}}return n}Eq(kkt,"getActiveElement");function Skt(s){return s.tagName==="IFRAME"}Eq(Skt,"isFrame");var Ats=Object.defineProperty,zVe=(s,t)=>Ats(s,"name",{value:t,configurable:!0});function eFe(s,t){if(typeof s=="function")return s(t);s!=null&&(s.current=t)}zVe(eFe,"setRef");function SO(...s){return t=>{let n=!1;const r=s.map(a=>{const i=eFe(a,t);return!n&&typeof i=="function"&&(n=!0),i});if(n)return()=>{for(let a=0;aEts(s,"name",{value:t,configurable:!0});function Tts(s,t){const n=k.createContext(t);n.displayName=s+"Context";const r=r2(i=>{const{children:l,...o}=i,c=k.useMemo(()=>o,Object.values(o));return e.jsx(n.Provider,{value:c,children:l})},"Provider");r.displayName=s+"Provider";function a(i,l={}){const{optional:o=!1}=l,c=k.useContext(n);if(c)return c;if(t!==void 0)return t;if(!o)throw new Error(`\`${i}\` must be used within \`${s}\``)}return r2(a,"useContext"),[r,a]}r2(Tts,"createContext");function qm(s,t=[]){let n=[];function r(i,l){const o=k.createContext(l);o.displayName=i+"Context";const c=n.length;n=[...n,l];const d=r2(h=>{var v;const{scope:m,children:p,...g}=h,x=((v=m==null?void 0:m[s])==null?void 0:v[c])||o,y=k.useMemo(()=>g,Object.values(g));return e.jsx(x.Provider,{value:y,children:p})},"Provider");d.displayName=i+"Provider";function u(h,m,p={}){var v;const{optional:g=!1}=p,x=((v=m==null?void 0:m[s])==null?void 0:v[c])||o,y=k.useContext(x);if(y)return y;if(l!==void 0)return l;if(!g)throw new Error(`\`${h}\` must be used within \`${i}\``)}return r2(u,"useContext"),[d,u]}r2(r,"createContext");const a=r2(()=>{const i=n.map(l=>k.createContext(l));return r2(function(o){const c=(o==null?void 0:o[s])||i;return k.useMemo(()=>({[`__scope${s}`]:{...o,[s]:c}}),[o,c])},"useScope")},"createScope");return a.scopeName=s,[r,Ckt(a,...t)]}r2(qm,"createContextScope");function Ckt(...s){const t=s[0];if(s.length===1)return t;const n=r2(()=>{const r=s.map(a=>({useScope:a(),scopeName:a.scopeName}));return r2(function(i){const l=r.reduce((o,{useScope:c,scopeName:d})=>{const h=c(i)[`__scope${d}`];return{...o,...h}},{});return k.useMemo(()=>({[`__scope${t.scopeName}`]:l}),[l])},"useComposedScopes")},"createScope");return n.scopeName=t.scopeName,n}r2(Ckt,"composeContextScopes");var Mts=Object.defineProperty,Nk=(s,t)=>Mts(s,"name",{value:t,configurable:!0});function xk(s){const t=k.forwardRef((n,r)=>{let{children:a,...i}=n,l=null,o=!1;const c=[];tFe(a)&&typeof Pne=="function"&&(a=Pne(a._payload)),k.Children.forEach(a,m=>{var p;if(Pkt(m)){o=!0;const g=m;let x="child"in g.props?g.props.child:g.props.children;tFe(x)&&typeof Pne=="function"&&(x=Pne(x._payload)),l=Pts(g,x),c.push((p=l==null?void 0:l.props)==null?void 0:p.children)}else c.push(m)}),l?l=k.cloneElement(l,void 0,c):!o&&k.Children.count(a)===1&&k.isValidElement(a)&&(l=a);const d=l?Mkt(l):void 0,u=Ao(r,d);if(!l){if(a||a===0)throw new Error(o?Rts(s):Lts(s));return a}const h=Tkt(i,l.props??{});return l.type!==k.Fragment&&(h.ref=r?u:d),k.cloneElement(l,h)});return t.displayName=`${s}.Slot`,t}Nk(xk,"createSlot");var BVe=xk("Slot"),Akt=Symbol.for("radix.slottable");function Ekt(s){const t=Nk(n=>"child"in n?n.children(n.child):n.children,"Slottable");return t.displayName=`${s}.Slottable`,t.__radixId=Akt,t}Nk(Ekt,"createSlottable");var Pts=Nk((s,t)=>{if("child"in s.props){const n=s.props.child;return k.isValidElement(n)?k.cloneElement(n,void 0,s.props.children(n.props.children)):null}return k.isValidElement(t)?t:null},"getSlottableElementFromSlottable");function Tkt(s,t){const n={...t};for(const r in t){const a=s[r],i=t[r];/^on[A-Z]/.test(r)?a&&i?n[r]=(...o)=>{const c=i(...o);return a(...o),c}:a&&(n[r]=a):r==="style"?n[r]={...a,...i}:r==="className"&&(n[r]=[a,i].filter(Boolean).join(" "))}return{...s,...n}}Nk(Tkt,"mergeProps");function Mkt(s){var r,a;let t=(r=Object.getOwnPropertyDescriptor(s.props,"ref"))==null?void 0:r.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?s.ref:(t=(a=Object.getOwnPropertyDescriptor(s,"ref"))==null?void 0:a.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?s.props.ref:s.props.ref||s.ref)}Nk(Mkt,"getElementRef");function Pkt(s){return k.isValidElement(s)&&typeof s.type=="function"&&"__radixId"in s.type&&s.type.__radixId===Akt}Nk(Pkt,"isSlottable");var Its=Symbol.for("react.lazy");function tFe(s){return s!=null&&typeof s=="object"&&"$$typeof"in s&&s.$$typeof===Its&&"_payload"in s&&Ikt(s._payload)}Nk(tFe,"isLazyComponent");function Ikt(s){return typeof s=="object"&&s!==null&&"then"in s}Nk(Ikt,"isPromiseLike");var Lts=Nk(s=>`${s} failed to slot onto its children. Expected a single React element child or \`Slottable\`.`,"createSlotError"),Rts=Nk(s=>`${s} failed to slot onto its \`Slottable\`. Expected \`Slottable\` to receive a single React element child.`,"createSlottableError"),Pne=uF[" use ".trim().toString()],Dts=Object.defineProperty,d0=(s,t)=>Dts(s,"name",{value:t,configurable:!0});function fF(s){const t=s+"CollectionProvider",[n,r]=qm(t),[a,i]=n(t,{collectionRef:{current:null},itemMap:new Map}),l=d0(x=>{const{scope:y,children:v}=x,_=k.useRef(null),j=k.useRef(new Map).current;return e.jsx(a,{scope:y,itemMap:j,collectionRef:_,children:v})},"CollectionProvider");l.displayName=t;const o=s+"CollectionSlot",c=xk(o),d=k.forwardRef((x,y)=>{const{scope:v,children:_}=x,j=i(o,v),C=Ao(y,j.collectionRef);return e.jsx(c,{ref:C,children:_})});d.displayName=o;const u=s+"CollectionItemSlot",h="data-radix-collection-item",m=xk(u),p=k.forwardRef((x,y)=>{const{scope:v,children:_,...j}=x,C=k.useRef(null),A=Ao(y,C),M=i(u,v);return k.useEffect(()=>(M.itemMap.set(C,{ref:C,...j}),()=>void M.itemMap.delete(C))),e.jsx(m,{[h]:"",ref:A,children:_})});p.displayName=u;function g(x){const y=i(s+"CollectionConsumer",x);return k.useCallback(()=>{const _=y.collectionRef.current;if(!_)return[];const j=Array.from(_.querySelectorAll(`[${h}]`));return Array.from(y.itemMap.values()).sort((M,I)=>j.indexOf(M.ref.current)-j.indexOf(I.ref.current))},[y.collectionRef,y.itemMap])}return d0(g,"useCollection"),[{Provider:l,Slot:d,ItemSlot:p},g,r]}d0(fF,"createCollection");var Mat=new WeakMap,Nx,Rw,qPe=(Rw=class extends Map{constructor(n){super(n);ds(this,Nx);$t(this,Nx,[...super.keys()]),Mat.set(this,!0)}set(n,r){return Mat.get(this)&&(this.has(n)?ge(this,Nx)[ge(this,Nx).indexOf(n)]=n:ge(this,Nx).push(n)),super.set(n,r),this}insert(n,r,a){const i=this.has(r),l=ge(this,Nx).length,o=$Ve(n);let c=o>=0?o:l+o;const d=c<0||c>=l?-1:c;if(d===this.size||i&&d===this.size-1||d===-1)return this.set(r,a),this;const u=this.size+(i?0:1);o<0&&c++;const h=[...ge(this,Nx)];let m,p=!1;for(let g=c;g=this.size&&(i=this.size-1),this.at(i)}keyFrom(n,r){const a=this.indexOf(n);if(a===-1)return;let i=a+r;return i<0&&(i=0),i>=this.size&&(i=this.size-1),this.keyAt(i)}find(n,r){let a=0;for(const i of this){if(Reflect.apply(n,r,[i,a,this]))return i;a++}}findIndex(n,r){let a=0;for(const i of this){if(Reflect.apply(n,r,[i,a,this]))return a;a++}return-1}filter(n,r){const a=[];let i=0;for(const l of this)Reflect.apply(n,r,[l,i,this])&&a.push(l),i++;return new Rw(a)}map(n,r){const a=[];let i=0;for(const l of this)a.push([l[0],Reflect.apply(n,r,[l,i,this])]),i++;return new Rw(a)}reduce(...n){const[r,a]=n;let i=0,l=a??this.at(0);for(const o of this)i===0&&n.length===1?l=o:l=Reflect.apply(r,this,[l,o,i,this]),i++;return l}reduceRight(...n){const[r,a]=n;let i=a??this.at(-1);for(let l=this.size-1;l>=0;l--){const o=this.at(l);l===this.size-1&&n.length===1?i=o:i=Reflect.apply(r,this,[i,o,l,this])}return i}toSorted(n){const r=[...this.entries()].sort(n);return new Rw(r)}toReversed(){const n=new Rw;for(let r=this.size-1;r>=0;r--){const a=this.keyAt(r),i=this.get(a);n.set(a,i)}return n}toSpliced(...n){const r=[...this.entries()];return r.splice(...n),new Rw(r)}slice(n,r){const a=new Rw;let i=this.size-1;if(n===void 0)return a;n<0&&(n=n+this.size),r!==void 0&&r>0&&(i=r-1);for(let l=n;l<=i;l++){const o=this.keyAt(l),c=this.get(o);a.set(o,c)}return a}every(n,r){let a=0;for(const i of this){if(!Reflect.apply(n,r,[i,a,this]))return!1;a++}return!0}some(n,r){let a=0;for(const i of this){if(Reflect.apply(n,r,[i,a,this]))return!0;a++}return!1}},Nx=new WeakMap,d0(Rw,"OrderedDict"),Rw);function eoe(s,t){if("at"in Array.prototype)return Array.prototype.at.call(s,t);const n=Lkt(s,t);return n===-1?void 0:s[n]}d0(eoe,"at");function Lkt(s,t){const n=s.length,r=$Ve(t),a=r>=0?r:n+r;return a<0||a>=n?-1:a}d0(Lkt,"toSafeIndex");function $Ve(s){return s!==s||s===0?0:Math.trunc(s)}d0($Ve,"toSafeInteger");function Ots(s){const t=s+"CollectionProvider",[n,r]=qm(t),[a,i]=n(t,{collectionElement:null,collectionRef:{current:null},collectionRefObject:{current:null},itemMap:new qPe,setItemMap:d0(()=>{},"setItemMap")}),l=d0(({state:j,...C})=>j?e.jsx(c,{...C,state:j}):e.jsx(o,{...C}),"CollectionProvider");l.displayName=t;const o=d0(j=>{const C=y();return e.jsx(c,{...j,state:C})},"CollectionInit");o.displayName=t+"Init";const c=d0(j=>{const{scope:C,children:A,state:M}=j,I=k.useRef(null),[P,R]=k.useState(null),O=Ao(I,R),[B,U]=M;return k.useEffect(()=>{if(!P)return;const G=Okt(()=>{});return G.observe(P,{childList:!0,subtree:!0}),()=>{G.disconnect()}},[P]),e.jsx(a,{scope:C,itemMap:B,setItemMap:U,collectionRef:O,collectionRefObject:I,collectionElement:P,children:A})},"CollectionProviderImpl");c.displayName=t+"Impl";const d=s+"CollectionSlot",u=xk(d),h=k.forwardRef((j,C)=>{const{scope:A,children:M}=j,I=i(d,A),P=Ao(C,I.collectionRef);return e.jsx(u,{ref:P,children:M})});h.displayName=d;const m=s+"CollectionItemSlot",p="data-radix-collection-item",g=xk(m),x=k.forwardRef((j,C)=>{const{scope:A,children:M,...I}=j,P=k.useRef(null),[R,O]=k.useState(null),B=Ao(C,P,O),U=i(m,A),{setItemMap:G}=U,H=k.useRef(I);Rkt(H.current,I)||(H.current=I);const Y=H.current;return k.useEffect(()=>{const se=Y;return G(ee=>R?ee.has(R)?ee.set(R,{...se,element:R}).toSorted(sFe):(ee.set(R,{...se,element:R}),ee.toSorted(sFe)):ee),()=>{G(ee=>!R||!ee.has(R)?ee:(ee.delete(R),new qPe(ee)))}},[R,Y,G]),e.jsx(g,{[p]:"",ref:B,children:M})});x.displayName=m;function y(){return k.useState(new qPe)}d0(y,"useInitCollection");function v(j){const{itemMap:C}=i(s+"CollectionConsumer",j);return C}return d0(v,"useCollection"),[{Provider:l,Slot:h,ItemSlot:x},{createCollectionScope:r,useCollection:v,useInitCollection:y}]}d0(Ots,"createCollection");function Rkt(s,t){if(s===t)return!0;if(typeof s!="object"||typeof t!="object"||s==null||t==null)return!1;const n=Object.keys(s),r=Object.keys(t);if(n.length!==r.length)return!1;for(const a of n)if(!Object.prototype.hasOwnProperty.call(t,a)||s[a]!==t[a])return!1;return!0}d0(Rkt,"shallowEqual");function Dkt(s,t){return!!(t.compareDocumentPosition(s)&Node.DOCUMENT_POSITION_PRECEDING)}d0(Dkt,"isElementPreceding");function sFe(s,t){return!s[1].element||!t[1].element?0:Dkt(s[1].element,t[1].element)?-1:1}d0(sFe,"sortByDocumentPosition");function Okt(s){return new MutationObserver(n=>{for(const r of n)if(r.type==="childList"){s();return}})}d0(Okt,"getChildListObserver");var Fts=Object.defineProperty,zts=(s,t)=>Fts(s,"name",{value:t,configurable:!0}),Bts=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],hi=Bts.reduce((s,t)=>{const n=xk(`Primitive.${t}`),r=k.forwardRef((a,i)=>{const{asChild:l,...o}=a,c=l?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),e.jsx(c,{...o,ref:i})});return r.displayName=`Primitive.${t}`,{...s,[t]:r}},{});function e3e(s,t){s&&a1.flushSync(()=>s.dispatchEvent(t))}zts(e3e,"dispatchDiscreteCustomEvent");var $ts=Object.defineProperty,Uts=(s,t)=>$ts(s,"name",{value:t,configurable:!0});function sp(s){const t=k.useRef(s);return k.useEffect(()=>{t.current=s}),k.useMemo(()=>(...n)=>{var r;return(r=t.current)==null?void 0:r.call(t,...n)},[])}Uts(sp,"useCallbackRef");var qts=Object.defineProperty,fy=(s,t)=>qts(s,"name",{value:t,configurable:!0}),nFe="dismissableLayer.update",Vts="dismissableLayer.pointerDownOutside",Hts="dismissableLayer.focusOutside",Pat,UVe=k.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set,dismissableSurfaces:new Set}),pF=k.forwardRef(fy(function(t,n){const{disableOutsidePointerEvents:r=!1,deferPointerDownOutside:a=!1,onEscapeKeyDown:i,onPointerDownOutside:l,onFocusOutside:o,onInteractOutside:c,onDismiss:d,...u}=t,h=k.useContext(UVe),[m,p]=k.useState(null),g=(m==null?void 0:m.ownerDocument)??(globalThis==null?void 0:globalThis.document),[,x]=k.useState({}),y=Ao(n,p),v=Array.from(h.layers),[_]=[...h.layersWithOutsidePointerEventsDisabled].slice(-1),j=_?v.indexOf(_):-1,C=m?v.indexOf(m):-1,A=h.layersWithOutsidePointerEventsDisabled.size>0,M=C>=j,I=k.useRef(!1),P=zkt(U=>{l==null||l(U),c==null||c(U),U.defaultPrevented||d==null||d()},{ownerDocument:g,deferPointerDownOutside:a,isDeferredPointerDownOutsideRef:I,dismissableSurfaces:h.dismissableSurfaces,shouldHandlePointerDownOutside:k.useCallback(U=>{if(!(U instanceof Node))return!1;const G=[...h.branches].some(H=>H.contains(U));return M&&!G},[h.branches,M])}),R=Bkt(U=>{if(a&&I.current)return;const G=U.target;[...h.branches].some(Y=>Y.contains(G))||(o==null||o(U),c==null||c(U),U.defaultPrevented||d==null||d())},g),O=m?C===v.length-1:!1,B=sp(U=>{U.key==="Escape"&&(i==null||i(U),!U.defaultPrevented&&d&&(U.preventDefault(),d()))});return k.useEffect(()=>{if(O)return g.addEventListener("keydown",B,{capture:!0}),()=>g.removeEventListener("keydown",B,{capture:!0})},[g,O,B]),k.useEffect(()=>{if(m)return r&&(h.layersWithOutsidePointerEventsDisabled.size===0&&(Pat=g.body.style.pointerEvents,g.body.style.pointerEvents="none"),h.layersWithOutsidePointerEventsDisabled.add(m)),h.layers.add(m),rFe(),()=>{r&&(h.layersWithOutsidePointerEventsDisabled.delete(m),h.layersWithOutsidePointerEventsDisabled.size===0&&(g.body.style.pointerEvents=Pat))}},[m,g,r,h]),k.useEffect(()=>()=>{m&&(h.layers.delete(m),h.layersWithOutsidePointerEventsDisabled.delete(m),rFe())},[m,h]),k.useEffect(()=>{const U=fy(()=>x({}),"handleUpdate");return document.addEventListener(nFe,U),()=>document.removeEventListener(nFe,U)},[]),e.jsx(hi.div,{...u,ref:y,style:{pointerEvents:A?M?"auto":"none":void 0,...t.style},onFocusCapture:ga(t.onFocusCapture,R.onFocusCapture),onBlurCapture:ga(t.onBlurCapture,R.onBlurCapture),onPointerDownCapture:ga(t.onPointerDownCapture,P.onPointerDownCapture)})},"DismissableLayer")),Gts=k.forwardRef(fy(function(t,n){const r=k.useContext(UVe),a=k.useRef(null),i=Ao(n,a);return k.useEffect(()=>{const l=a.current;if(l)return r.branches.add(l),()=>{r.branches.delete(l)}},[r.branches]),e.jsx(hi.div,{...t,ref:i})},"DismissableLayerBranch"));function Fkt(){const s=k.useContext(UVe),[t,n]=k.useState(null);return k.useEffect(()=>{if(t)return s.dismissableSurfaces.add(t),()=>{s.dismissableSurfaces.delete(t)}},[t,s.dismissableSurfaces]),n}fy(Fkt,"useDismissableLayerSurface");var Wts=fy(()=>!0,"IS_TRUE");function zkt(s,t){const{ownerDocument:n=globalThis==null?void 0:globalThis.document,deferPointerDownOutside:r=!1,isDeferredPointerDownOutsideRef:a,dismissableSurfaces:i,shouldHandlePointerDownOutside:l=Wts}=t,o=sp(s),c=k.useRef(!1),d=k.useRef(!1),u=k.useRef(new Map),h=k.useRef(()=>{});return k.useEffect(()=>{function m(){d.current=!1,a.current=!1,u.current.clear()}fy(m,"resetOutsideInteraction");function p(){return Array.from(u.current.values()).some(Boolean)}fy(p,"isOutsideInteractionIntercepted");function g(j){if(!d.current)return;const C=j.target;C instanceof Node&&[...i].some(M=>M.contains(C))||u.current.set(j.type,!0),j.type==="click"&&window.setTimeout(()=>{d.current&&h.current()},0)}fy(g,"handleInteractionCapture");function x(j){d.current&&u.current.set(j.type,!1)}fy(x,"handleInteractionBubble");const y=fy(j=>{if(j.target&&!c.current){let C=function(){n.removeEventListener("click",h.current);const M=p();m(),M||qVe(Vts,o,A,{discrete:!0})};if(fy(C,"handleAndDispatchPointerDownOutsideEvent"),!l(j.target)){n.removeEventListener("click",h.current),m(),c.current=!1;return}const A={originalEvent:j};d.current=!0,a.current=r&&j.button===0,u.current.clear(),!r||j.button!==0?C():(n.removeEventListener("click",h.current),h.current=C,n.addEventListener("click",h.current,{once:!0}))}else n.removeEventListener("click",h.current),m();c.current=!1},"handlePointerDown"),v=["pointerup","mousedown","mouseup","touchstart","touchend","click"];for(const j of v)n.addEventListener(j,g,!0),n.addEventListener(j,x);const _=window.setTimeout(()=>{n.addEventListener("pointerdown",y)},0);return()=>{window.clearTimeout(_),n.removeEventListener("pointerdown",y),n.removeEventListener("click",h.current);for(const j of v)n.removeEventListener(j,g,!0),n.removeEventListener(j,x)}},[n,o,r,a,i,l]),{onPointerDownCapture:fy(()=>c.current=!0,"onPointerDownCapture")}}fy(zkt,"usePointerDownOutside");function Bkt(s,t=globalThis==null?void 0:globalThis.document){const n=sp(s),r=k.useRef(!1);return k.useEffect(()=>{const a=fy(i=>{i.target&&!r.current&&qVe(Hts,n,{originalEvent:i},{discrete:!1})},"handleFocus");return t.addEventListener("focusin",a),()=>t.removeEventListener("focusin",a)},[t,n]),{onFocusCapture:fy(()=>r.current=!0,"onFocusCapture"),onBlurCapture:fy(()=>r.current=!1,"onBlurCapture")}}fy(Bkt,"useFocusOutside");function rFe(){const s=new CustomEvent(nFe);document.dispatchEvent(s)}fy(rFe,"dispatchUpdate");function qVe(s,t,n,{discrete:r}){const a=n.originalEvent.target,i=new CustomEvent(s,{bubbles:!1,cancelable:!0,detail:n});t&&a.addEventListener(s,t,{once:!0}),r?e3e(a,i):a.dispatchEvent(i)}fy(qVe,"handleAndDispatchCustomEvent");var Kts=pF,Yts=Gts,_m=globalThis!=null&&globalThis.document?k.useLayoutEffect:()=>{},Zts=Object.defineProperty,Xts=(s,t)=>Zts(s,"name",{value:t,configurable:!0}),QJ=k.forwardRef(Xts(function(t,n){var c;const{container:r,...a}=t,[i,l]=k.useState(!1);_m(()=>l(!0),[]);const o=r||i&&((c=globalThis==null?void 0:globalThis.document)==null?void 0:c.body);return o?a1.createPortal(e.jsx(hi.div,{...a,ref:n}),o):null},"Portal")),Qts=Object.defineProperty,z3=(s,t)=>Qts(s,"name",{value:t,configurable:!0});function $kt(s,t){return k.useReducer((n,r)=>t[n][r]??n,s)}z3($kt,"useStateMachine");var cx=z3(s=>{const{present:t,children:n}=s,r=Ukt(t),a=typeof n=="function"?n({present:r.isPresent}):k.Children.only(n),i=qkt(r.ref,Vkt(a));return typeof n=="function"||r.isPresent?k.cloneElement(a,{ref:i}):null},"Presence");function Ukt(s){const[t,n]=k.useState(),r=k.useRef(null),a=k.useRef(s),i=k.useRef("none"),l=k.useRef(void 0),o=s?"mounted":"unmounted",[c,d]=$kt(o,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return k.useEffect(()=>{c==="mounted"?(i.current=l.current??E9(r.current),l.current=void 0):i.current="none"},[c]),_m(()=>{const u=r.current,h=a.current;if(h!==s){const p=i.current,g=E9(u);s?(l.current=g,d("MOUNT")):g==="none"||(u==null?void 0:u.display)==="none"?d("UNMOUNT"):d(h&&p!==g?"ANIMATION_OUT":"UNMOUNT"),a.current=s}},[s,d]),_m(()=>{if(t){let u;const h=t.ownerDocument.defaultView??window,m=z3(g=>{const y=E9(r.current).includes(CSS.escape(g.animationName));if(g.target===t&&y&&(d("ANIMATION_END"),!a.current)){const v=t.style.animationFillMode;t.style.animationFillMode="forwards",u=h.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=v)})}},"handleAnimationEnd"),p=z3(g=>{g.target===t&&(i.current=E9(r.current))},"handleAnimationStart");return t.addEventListener("animationstart",p),t.addEventListener("animationcancel",m),t.addEventListener("animationend",m),()=>{h.clearTimeout(u),t.removeEventListener("animationstart",p),t.removeEventListener("animationcancel",m),t.removeEventListener("animationend",m)}}else d("ANIMATION_END")},[t,d]),{isPresent:["mounted","unmountSuspended"].includes(c),ref:k.useCallback(u=>{if(u){const h=getComputedStyle(u);r.current=h,l.current=E9(h)}else r.current=null;n(u)},[])}}z3(Ukt,"usePresence");function aFe(s,t){if(typeof s=="function")return s(t);s!=null&&(s.current=t)}z3(aFe,"setRef");function qkt(...s){const t=k.useRef(s);return t.current=s,k.useCallback(n=>{const r=t.current;let a=!1;const i=r.map(l=>{const o=aFe(l,n);return!a&&typeof o=="function"&&(a=!0),o});if(a)return()=>{for(let l=0;lJts(s,"name",{value:t,configurable:!0}),Iat=uF[" useEffectEvent ".trim().toString()],Lat=uF[" useInsertionEffect ".trim().toString()];function Hkt(s){if(typeof Iat=="function")return Iat(s);const t=k.useRef(()=>{throw new Error("Cannot call an event handler while rendering.")});return typeof Lat=="function"?Lat(()=>{t.current=s}):_m(()=>{t.current=s}),k.useMemo(()=>(...n)=>{var r;return(r=t.current)==null?void 0:r.call(t,...n)},[])}ess(Hkt,"useEffectEvent");var tss=Object.defineProperty,JJ=(s,t)=>tss(s,"name",{value:t,configurable:!0}),sss=uF[" useInsertionEffect ".trim().toString()]||_m;function ox({prop:s,defaultProp:t,onChange:n=JJ(()=>{},"onChange"),caller:r}){const[a,i,l]=Gkt({defaultProp:t,onChange:n}),o=s!==void 0,c=o?s:a,d=k.useCallback(u=>{var h;if(o){const m=Wkt(u)?u(s):u;m!==s&&((h=l.current)==null||h.call(l,m))}else i(u)},[o,s,i,l]);return[c,d]}JJ(ox,"useControllableState");function Gkt({defaultProp:s,onChange:t}){const[n,r]=k.useState(s),a=k.useRef(n),i=k.useRef(t);return sss(()=>{i.current=t},[t]),k.useEffect(()=>{var l;a.current!==n&&((l=i.current)==null||l.call(i,n),a.current=n)},[n,a]),[n,r,i]}JJ(Gkt,"useUncontrolledState");function Wkt(s){return typeof s=="function"}JJ(Wkt,"isFunction");var Rat=Symbol("RADIX:SYNC_STATE");function nss(s,t,n,r){const{prop:a,defaultProp:i,onChange:l,caller:o}=t,c=a!==void 0,d=Hkt(l),u=[{...n,state:i}];r&&u.push(r);const[h,m]=k.useReducer((y,v)=>{if(v.type===Rat)return{...y,state:v.state};const _=s(y,v);return c&&!Object.is(_.state,y.state)&&d(_.state),_},...u),p=h.state,g=k.useRef(p);k.useEffect(()=>{g.current!==p&&(g.current=p,c||d(p))},[p,g,c]);const x=k.useMemo(()=>a!==void 0?{...h,state:a}:h,[h,a]);return k.useEffect(()=>{c&&!Object.is(a,h.state)&&m({type:Rat,state:a})},[a,h.state,c]),[x,m]}JJ(nss,"useControllableStateReducer");var rss=Object.defineProperty,ass=(s,t)=>rss(s,"name",{value:t,configurable:!0}),Kkt=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"}),VVe=k.forwardRef(ass(function(t,n){return e.jsx(hi.span,{...t,ref:n,style:{...Kkt,...t.style}})},"VisuallyHidden")),iss=VVe,oss=Object.defineProperty,hm=(s,t)=>oss(s,"name",{value:t,configurable:!0}),Ykt="ToastProvider",[HVe,Zkt,lss]=fF("Toast"),[Xkt,lQn]=qm("Toast",[lss]),[css,t3e]=Xkt(Ykt),dss=hm(s=>{const{__scopeToast:t,label:n="Notification",duration:r=5e3,swipeDirection:a="right",swipeThreshold:i=50,announcerContainer:l,children:o}=s,[c,d]=k.useState(null),[u,h]=k.useState(0),m=k.useRef(!1);return n.trim()||console.error(`Invalid prop \`label\` supplied to \`${Ykt}\`. Expected non-empty \`string\`.`),e.jsx(HVe.Provider,{scope:t,children:e.jsx(css,{scope:t,label:n,duration:r,swipeDirection:a,swipeThreshold:i,toastCount:u,viewport:c,onViewportChange:d,onToastAdd:k.useCallback(()=>h(p=>p+1),[]),onToastRemove:k.useCallback(()=>h(p=>p-1),[]),isClosePausedRef:m,announcerContainer:l,children:o})})},"ToastProvider"),uss="ToastViewport",hss=["F8"],iFe="toast.viewportPause",oFe="toast.viewportResume",mss=k.forwardRef(hm(function(t,n){const{__scopeToast:r,hotkey:a=hss,label:i="Notifications ({hotkey})",...l}=t,o=t3e(uss,r),c=Zkt(r),d=k.useRef(null),u=k.useRef(null),h=k.useRef(null),m=k.useRef(null),p=Ao(n,m,o.onViewportChange),g=a.join("+").replace(/Key/g,"").replace(/Digit/g,""),x=o.toastCount>0;k.useEffect(()=>{const v=hm(_=>{var C;a.length!==0&&a.every(A=>_[A]||_.code===A)&&((C=m.current)==null||C.focus())},"handleKeyDown");return document.addEventListener("keydown",v),()=>document.removeEventListener("keydown",v)},[a]),k.useEffect(()=>{const v=d.current,_=m.current;if(x&&v&&_){const j=hm(()=>{if(!o.isClosePausedRef.current){const I=new CustomEvent(iFe);_.dispatchEvent(I),o.isClosePausedRef.current=!0}},"handlePause"),C=hm(()=>{if(o.isClosePausedRef.current){const I=new CustomEvent(oFe);_.dispatchEvent(I),o.isClosePausedRef.current=!1}},"handleResume"),A=hm(I=>{!v.contains(I.relatedTarget)&&C()},"handleFocusOutResume"),M=hm(()=>{v.contains(document.activeElement)||C()},"handlePointerLeaveResume");return v.addEventListener("focusin",j),v.addEventListener("focusout",A),v.addEventListener("pointermove",j),v.addEventListener("pointerleave",M),window.addEventListener("blur",j),window.addEventListener("focus",C),()=>{v.removeEventListener("focusin",j),v.removeEventListener("focusout",A),v.removeEventListener("pointermove",j),v.removeEventListener("pointerleave",M),window.removeEventListener("blur",j),window.removeEventListener("focus",C)}}},[x,o.isClosePausedRef]);const y=k.useCallback(({tabbingDirection:v})=>{const j=c().map(C=>{const A=C.ref.current,M=[A,...sSt(A)];return v==="forwards"?M:M.reverse()});return(v==="forwards"?j.reverse():j).flat()},[c]);return k.useEffect(()=>{const v=m.current;if(v){const _=hm(j=>{var M,I,P;const C=j.altKey||j.ctrlKey||j.metaKey;if(j.key==="Tab"&&!C){const R=document.activeElement,O=j.shiftKey;if(j.target===v&&O){(M=u.current)==null||M.focus();return}const G=y({tabbingDirection:O?"backwards":"forwards"}),H=G.findIndex(Y=>Y===R);toe(G.slice(H+1))?j.preventDefault():O?(I=u.current)==null||I.focus():(P=h.current)==null||P.focus()}},"handleKeyDown");return v.addEventListener("keydown",_),()=>v.removeEventListener("keydown",_)}},[c,y]),e.jsxs(Yts,{ref:d,role:"region","aria-label":i.replace("{hotkey}",g),tabIndex:-1,style:{pointerEvents:x?void 0:"none"},children:[x&&e.jsx(Dat,{ref:u,onFocusFromOutsideViewport:()=>{const v=y({tabbingDirection:"forwards"});toe(v)}}),e.jsx(HVe.Slot,{scope:r,children:e.jsx(hi.ol,{tabIndex:-1,...l,ref:p})}),x&&e.jsx(Dat,{ref:h,onFocusFromOutsideViewport:()=>{const v=y({tabbingDirection:"backwards"});toe(v)}})]})},"ToastViewport")),fss="ToastFocusProxy",Dat=k.forwardRef(hm(function(t,n){const{__scopeToast:r,onFocusFromOutsideViewport:a,...i}=t,l=t3e(fss,r);return e.jsx(VVe,{tabIndex:0,...i,ref:n,style:{position:"fixed"},onFocus:o=>{var u;const c=o.relatedTarget;!((u=l.viewport)!=null&&u.contains(c))&&a()}})},"ToastFocusProxy")),s3e="Toast",pss="toast.swipeStart",gss="toast.swipeMove",xss="toast.swipeCancel",yss="toast.swipeEnd",vss=k.forwardRef(hm(function(t,n){const{forceMount:r,open:a,defaultOpen:i,onOpenChange:l,...o}=t,[c,d]=ox({prop:a,defaultProp:i??!0,onChange:l,caller:s3e});return e.jsx(cx,{present:r||c,children:e.jsx(wss,{open:c,...o,ref:n,onClose:()=>d(!1),onPause:sp(t.onPause),onResume:sp(t.onResume),onSwipeStart:ga(t.onSwipeStart,u=>{u.currentTarget.setAttribute("data-swipe","start")}),onSwipeMove:ga(t.onSwipeMove,u=>{const{x:h,y:m}=u.detail.delta;u.currentTarget.setAttribute("data-swipe","move"),u.currentTarget.style.setProperty("--radix-toast-swipe-move-x",`${h}px`),u.currentTarget.style.setProperty("--radix-toast-swipe-move-y",`${m}px`)}),onSwipeCancel:ga(t.onSwipeCancel,u=>{u.currentTarget.setAttribute("data-swipe","cancel"),u.currentTarget.style.removeProperty("--radix-toast-swipe-move-x"),u.currentTarget.style.removeProperty("--radix-toast-swipe-move-y"),u.currentTarget.style.removeProperty("--radix-toast-swipe-end-x"),u.currentTarget.style.removeProperty("--radix-toast-swipe-end-y")}),onSwipeEnd:ga(t.onSwipeEnd,u=>{const{x:h,y:m}=u.detail.delta;u.currentTarget.setAttribute("data-swipe","end"),u.currentTarget.style.removeProperty("--radix-toast-swipe-move-x"),u.currentTarget.style.removeProperty("--radix-toast-swipe-move-y"),u.currentTarget.style.setProperty("--radix-toast-swipe-end-x",`${h}px`),u.currentTarget.style.setProperty("--radix-toast-swipe-end-y",`${m}px`),d(!1)})})})},"Toast")),[bss,_ss]=Xkt(s3e,{onClose(){}}),wss=k.forwardRef(hm(function(t,n){const{__scopeToast:r,type:a="foreground",duration:i,open:l,onClose:o,onEscapeKeyDown:c,onPause:d,onResume:u,onSwipeStart:h,onSwipeMove:m,onSwipeCancel:p,onSwipeEnd:g,...x}=t,y=t3e(s3e,r),v=Zkt(r),[_,j]=k.useState(null),C=Ao(n,j),A=k.useRef(null),M=k.useRef(null),I=i||y.duration,P=k.useRef(0),R=k.useRef(I),O=k.useRef(0),{onToastAdd:B,onToastRemove:U}=y,G=sp(()=>{var ee;(_==null?void 0:_.contains(document.activeElement))&&((ee=y.viewport)==null||ee.focus()),o()}),H=k.useCallback(se=>{!se||se===1/0||(window.clearTimeout(O.current),P.current=new Date().getTime(),O.current=window.setTimeout(G,se))},[G]);k.useEffect(()=>{const se=y.viewport;if(se){const ee=hm(()=>{H(R.current),u==null||u()},"handleResume"),oe=hm(()=>{const me=new Date().getTime()-P.current;R.current=R.current-me,window.clearTimeout(O.current),d==null||d()},"handlePause");return se.addEventListener(iFe,oe),se.addEventListener(oFe,ee),()=>{se.removeEventListener(iFe,oe),se.removeEventListener(oFe,ee)}}},[y.viewport,I,d,u,H]),k.useEffect(()=>{l&&!y.isClosePausedRef.current&&H(I)},[l,I,y.isClosePausedRef,H]),k.useEffect(()=>()=>{window.clearTimeout(O.current)},[]),k.useEffect(()=>(B(),()=>U()),[B,U]);const Y=k.useMemo(()=>_?GVe(_):null,[_]);return y.viewport?e.jsxs(e.Fragment,{children:[Y&&e.jsx(jss,{__scopeToast:r,role:"status","aria-live":a==="foreground"?"assertive":"polite",children:Y}),e.jsx(bss,{scope:r,onClose:G,children:a1.createPortal(e.jsx(HVe.ItemSlot,{scope:r,children:e.jsx(Kts,{asChild:!0,onEscapeKeyDown:ga(c,se=>{v().some(oe=>{var me;return(me=oe.ref.current)==null?void 0:me.contains(se.target)})||G()}),children:e.jsx(hi.li,{tabIndex:0,"data-state":l?"open":"closed","data-swipe-direction":y.swipeDirection,...x,ref:C,style:{userSelect:"none",touchAction:"none",...t.style},onKeyDown:ga(t.onKeyDown,se=>{se.key==="Escape"&&(c==null||c(se.nativeEvent),se.nativeEvent.defaultPrevented||G())}),onPointerDown:ga(t.onPointerDown,se=>{se.button===0&&(A.current={x:se.clientX,y:se.clientY})}),onPointerMove:ga(t.onPointerMove,se=>{if(!A.current)return;const ee=se.clientX-A.current.x,oe=se.clientY-A.current.y,me=!!M.current,Q=["left","right"].includes(y.swipeDirection),te=["left","up"].includes(y.swipeDirection)?Math.min:Math.max,le=Q?te(0,ee):0,fe=Q?0:te(0,oe),_e=se.pointerType==="touch"?10:2,ve={x:le,y:fe},he={originalEvent:se,delta:ve};me?(M.current=ve,bW(gss,m,he,{discrete:!1})):Oat(ve,y.swipeDirection,_e)?(M.current=ve,bW(pss,h,he,{discrete:!1}),se.target.setPointerCapture(se.pointerId)):(Math.abs(ee)>_e||Math.abs(oe)>_e)&&(A.current=null)}),onPointerUp:ga(t.onPointerUp,se=>{const ee=M.current,oe=se.target;if(oe.hasPointerCapture(se.pointerId)&&oe.releasePointerCapture(se.pointerId),M.current=null,A.current=null,ee){const me=se.currentTarget,Q={originalEvent:se,delta:ee};Oat(ee,y.swipeDirection,y.swipeThreshold)?bW(yss,g,Q,{discrete:!0}):bW(xss,p,Q,{discrete:!0}),me.addEventListener("click",te=>te.preventDefault(),{once:!0})}})})})}),y.viewport)})]}):null},"ToastImpl")),jss=hm(s=>{const{__scopeToast:t,children:n,...r}=s,a=t3e(s3e,t),[i,l]=k.useState(!1),[o,c]=k.useState(!1);return eSt(()=>l(!0)),k.useEffect(()=>{const d=window.setTimeout(()=>c(!0),1e3);return()=>window.clearTimeout(d)},[]),o?null:e.jsx(QJ,{asChild:!0,container:a.announcerContainer||void 0,children:e.jsx(VVe,{...r,children:i&&e.jsxs(e.Fragment,{children:[a.label," ",n]})})})},"ToastAnnounce"),Nss=k.forwardRef(hm(function(t,n){const{__scopeToast:r,...a}=t;return e.jsx(hi.div,{...a,ref:n})},"ToastTitle")),kss=k.forwardRef(hm(function(t,n){const{__scopeToast:r,...a}=t;return e.jsx(hi.div,{...a,ref:n})},"ToastDescription")),Sss="ToastAction",Css=k.forwardRef(hm(function(t,n){const{altText:r,...a}=t;return r.trim()?e.jsx(Jkt,{altText:r,asChild:!0,children:e.jsx(Qkt,{...a,ref:n})}):(console.error(`Invalid prop \`altText\` supplied to \`${Sss}\`. Expected non-empty \`string\`.`),null)},"ToastAction")),Ass="ToastClose",Qkt=k.forwardRef(hm(function(t,n){const{__scopeToast:r,...a}=t,i=_ss(Ass,r);return e.jsx(Jkt,{asChild:!0,children:e.jsx(hi.button,{type:"button",...a,ref:n,onClick:ga(t.onClick,i.onClose)})})},"ToastClose")),Jkt=k.forwardRef(hm(function(t,n){const{__scopeToast:r,altText:a,...i}=t;return e.jsx(hi.div,{"data-radix-toast-announce-exclude":"","data-radix-toast-announce-alt":a||void 0,...i,ref:n})},"ToastAnnounceExclude"));function GVe(s){const t=[];return Array.from(s.childNodes).forEach(r=>{if(r.nodeType===r.TEXT_NODE&&r.textContent&&t.push(r.textContent),tSt(r)){const a=r.ariaHidden||r.hidden||r.style.display==="none",i=r.dataset.radixToastAnnounceExclude==="";if(!a)if(i){const l=r.dataset.radixToastAnnounceAlt;l&&t.push(l)}else t.push(...GVe(r))}}),t}hm(GVe,"getAnnounceTextContent");function bW(s,t,n,{discrete:r}){const a=n.originalEvent.currentTarget,i=new CustomEvent(s,{bubbles:!0,cancelable:!0,detail:n});t&&a.addEventListener(s,t,{once:!0}),r?e3e(a,i):a.dispatchEvent(i)}hm(bW,"handleAndDispatchCustomEvent");var Oat=hm((s,t,n=0)=>{const r=Math.abs(s.x),a=Math.abs(s.y),i=r>a;return t==="left"||t==="right"?i&&r>n:!i&&a>n},"isDeltaInDirection");function eSt(s=()=>{}){const t=sp(s);_m(()=>{let n=0,r=0;return n=window.requestAnimationFrame(()=>r=window.requestAnimationFrame(t)),()=>{window.cancelAnimationFrame(n),window.cancelAnimationFrame(r)}},[t])}hm(eSt,"useNextFrame");function tSt(s){return s.nodeType===s.ELEMENT_NODE}hm(tSt,"isHTMLElement");function sSt(s){const t=[],n=document.createTreeWalker(s,NodeFilter.SHOW_ELEMENT,{acceptNode:hm(r=>{const a=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||a?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP},"acceptNode")});for(;n.nextNode();)t.push(n.currentNode);return t}hm(sSt,"getTabbableCandidates");function toe(s){const t=document.activeElement;return s.some(n=>n===t?!0:(n.focus(),document.activeElement!==t))}hm(toe,"focusFirst");var Ess=dss,nSt=mss,rSt=vss,aSt=Nss,iSt=kss,oSt=Css,lSt=Qkt;function cSt(s){var t,n,r="";if(typeof s=="string"||typeof s=="number")r+=s;else if(typeof s=="object")if(Array.isArray(s)){var a=s.length;for(t=0;ttypeof s=="boolean"?`${s}`:s===0?"0":s,zat=bc,gF=(s,t)=>n=>{var r;if((t==null?void 0:t.variants)==null)return zat(s,n==null?void 0:n.class,n==null?void 0:n.className);const{variants:a,defaultVariants:i}=t,l=Object.keys(a).map(d=>{const u=n==null?void 0:n[d],h=i==null?void 0:i[d];if(u===null)return null;const m=Fat(u)||Fat(h);return a[d][m]}),o=n&&Object.entries(n).reduce((d,u)=>{let[h,m]=u;return m===void 0||(d[h]=m),d},{}),c=t==null||(r=t.compoundVariants)===null||r===void 0?void 0:r.reduce((d,u)=>{let{class:h,className:m,...p}=u;return Object.entries(p).every(g=>{let[x,y]=g;return Array.isArray(y)?y.includes({...i,...o}[x]):{...i,...o}[x]===y})?[...d,h,m]:d},[]);return zat(s,l,c,n==null?void 0:n.class,n==null?void 0:n.className)};/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Tss=s=>s.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),dSt=(...s)=>s.filter((t,n,r)=>!!t&&t.trim()!==""&&r.indexOf(t)===n).join(" ").trim();/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */var Mss={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 uSt=k.forwardRef(({color:s="currentColor",size:t=24,strokeWidth:n=2,absoluteStrokeWidth:r,className:a="",children:i,iconNode:l,...o},c)=>k.createElement("svg",{ref:c,...Mss,width:t,height:t,stroke:s,strokeWidth:r?Number(n)*24/Number(t):n,className:dSt("lucide",a),...o},[...l.map(([d,u])=>k.createElement(d,u)),...Array.isArray(i)?i:[i]]));/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ue=(s,t)=>{const n=k.forwardRef(({className:r,...a},i)=>k.createElement(uSt,{ref:i,iconNode:t,className:dSt(`lucide-${Tss(s)}`,r),...a}));return n.displayName=`${s}`,n};/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const soe=ue("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 noe=ue("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 roe=ue("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 aoe=ue("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 zp=ue("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 ioe=ue("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 ooe=ue("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 jP=ue("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 NP=ue("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 loe=ue("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 kP=ue("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 coe=ue("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 doe=ue("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 uoe=ue("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 hoe=ue("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 moe=ue("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 T8=ue("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 foe=ue("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 poe=ue("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 goe=ue("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 xoe=ue("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 yoe=ue("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 voe=ue("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 boe=ue("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 _oe=ue("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 woe=ue("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 joe=ue("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 Noe=ue("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 M8=ue("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 P8=ue("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 koe=ue("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 Soe=ue("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 Coe=ue("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 Aoe=ue("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 Eoe=ue("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 Toe=ue("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 Moe=ue("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 Poe=ue("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 Ioe=ue("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 Loe=ue("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 Roe=ue("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 Doe=ue("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 Ooe=ue("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 Foe=ue("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 zoe=ue("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 Boe=ue("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 $oe=ue("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 Uoe=ue("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 qoe=ue("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 Voe=ue("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 Hoe=ue("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 Goe=ue("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 Woe=ue("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 OT=ue("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 Koe=ue("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 kf=ue("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 Yoe=ue("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 Zoe=ue("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 Xoe=ue("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 Qoe=ue("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 Joe=ue("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 ele=ue("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 tle=ue("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 sle=ue("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 nle=ue("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 rle=ue("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 ale=ue("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 SP=ue("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 ile=ue("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 ole=ue("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 lle=ue("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 vK=ue("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 cle=ue("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 dle=ue("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 ule=ue("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 CP=ue("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 AP=ue("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 nx=ue("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 hle=ue("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 bK=ue("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 mle=ue("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 Ia=ue("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 fle=ue("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 N5=ue("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 ple=ue("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 xi=ue("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 gle=ue("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 xle=ue("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 EP=ue("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 Ix=ue("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 yle=ue("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 vle=ue("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 ble=ue("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 TP=ue("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 FT=ue("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 _le=ue("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 wle=ue("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 MP=ue("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 ap=ue("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 jle=ue("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 Nle=ue("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 kle=ue("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 Sle=ue("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 Cle=ue("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 Ale=ue("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 oh=ue("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 Ele=ue("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 PP=ue("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 Tle=ue("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 Mle=ue("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 Ple=ue("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 Ile=ue("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 IP=ue("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 Lle=ue("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 Rle=ue("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 Dle=ue("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 Ole=ue("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 Fle=ue("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 zle=ue("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 Ble=ue("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 $le=ue("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 Ule=ue("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 qle=ue("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 Vle=ue("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 Hle=ue("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 Gle=ue("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 Wle=ue("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 Kle=ue("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 Fz=ue("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 Yle=ue("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 Zle=ue("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 Xle=ue("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 Qle=ue("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 Jle=ue("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 p0=ue("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 ece=ue("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 tce=ue("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 sce=ue("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 nce=ue("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 rce=ue("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 ace=ue("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 _K=ue("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 ice=ue("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 oce=ue("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 f3=ue("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 lce=ue("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 Yw=ue("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 cce=ue("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 dce=ue("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 uce=ue("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 hce=ue("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 mce=ue("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 fce=ue("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 k5=ue("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 pce=ue("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 p3=ue("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 Fx=ue("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 LP=ue("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 RP=ue("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 gce=ue("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 xce=ue("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 yce=ue("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 vce=ue("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 bce=ue("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 _ce=ue("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 wce=ue("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 jce=ue("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 Nce=ue("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 kce=ue("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 Sce=ue("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 Cce=ue("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 Ace=ue("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 Ece=ue("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 Tce=ue("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 Mce=ue("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 zT=ue("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 Pce=ue("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 Ice=ue("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 Lce=ue("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 Rce=ue("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 Dce=ue("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 Oce=ue("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 Fce=ue("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 DP=ue("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 zce=ue("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 Bce=ue("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 $ce=ue("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 Uce=ue("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 qce=ue("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 Vce=ue("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 Hce=ue("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 Gce=ue("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 Wce=ue("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 Kce=ue("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 wg=ue("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 Yce=ue("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 Zce=ue("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 Xce=ue("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 Qce=ue("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 Jce=ue("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 ede=ue("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 tde=ue("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 sde=ue("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 nde=ue("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 rde=ue("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 BT=ue("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 ade=ue("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 jy=ue("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 ide=ue("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 ode=ue("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 lde=ue("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 S5=ue("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 wK=ue("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 cde=ue("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 OP=ue("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 dde=ue("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 ude=ue("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 hde=ue("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 jK=ue("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 mde=ue("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 fde=ue("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 pde=ue("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 gde=ue("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 zx=ue("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 xde=ue("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 yde=ue("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 vde=ue("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 bde=ue("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 _de=ue("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 Gi=ue("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 I8=ue("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 wde=ue("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 jde=ue("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 Nde=ue("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 kde=ue("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 Sde=ue("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 ip=ue("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 C5=ue("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 Cde=ue("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 Ade=ue("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 Ede=ue("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 Tde=ue("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 fb=ue("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 wm=ue("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 Mde=ue("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 fd=ue("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 Pde=ue("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 nk=ue("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 Ide=ue("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 Lde=ue("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 zz=ue("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 Rde=ue("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 i1=ue("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 Dde=ue("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 Ode=ue("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 Fde=ue("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 zde=ue("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 NK=ue("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 ha=ue("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 Bde=ue("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 g0=ue("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 $de=ue("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 Ude=ue("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 qde=ue("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 Vde=ue("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 Hde=ue("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 FP=ue("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 Gde=ue("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 Wde=ue("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 Kde=ue("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 Yde=ue("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 Zde=ue("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 Xde=ue("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 Qde=ue("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 Jde=ue("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 eue=ue("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 tue=ue("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 sue=ue("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 nue=ue("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 rue=ue("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 zP=ue("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 BP=ue("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 aue=ue("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 iue=ue("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 oue=ue("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 $P=ue("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 UP=ue("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 qP=ue("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 lue=ue("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 VP=ue("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 cue=ue("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 Ul=ue("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 due=ue("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 HP=ue("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 uue=ue("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 hue=ue("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 GP=ue("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 WP=ue("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 mue=ue("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 KP=ue("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 YP=ue("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 ZP=ue("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 fue=ue("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 L8=ue("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 ma=ue("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 pue=ue("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 gue=ue("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 Go=ue("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 xue=ue("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 yue=ue("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 Ld=ue("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 fi=ue("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 Ny=ue("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 vue=ue("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 bue=ue("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 _ue=ue("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 wue=ue("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 jue=ue("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 Nue=ue("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 kue=ue("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 v_=ue("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 Sue=ue("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 R8=ue("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 Cue=ue("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 Aue=ue("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 Eue=ue("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 Ho=ue("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 XP=ue("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 QP=ue("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 JP=ue("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 eI=ue("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 tI=ue("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 sI=ue("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 nI=ue("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 rI=ue("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 nl=ue("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 Gr=ue("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 aI=ue("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 iI=ue("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 oI=ue("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 lI=ue("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 Tue=ue("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 cI=ue("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 Mue=ue("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 Pue=ue("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 Iue=ue("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 Lue=ue("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 Rue=ue("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 Due=ue("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 Oue=ue("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 dI=ue("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 _C=ue("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 uI=ue("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 Fue=ue("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 hI=ue("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 mI=ue("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 fI=ue("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 pI=ue("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 mm=ue("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 gI=ue("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 xI=ue("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 yI=ue("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 zue=ue("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 vI=ue("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 bI=ue("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 _I=ue("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 ju=ue("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 rx=ue("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 Bue=ue("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 $ue=ue("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 Bz=ue("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 A5=ue("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 Uue=ue("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 lv=ue("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 que=ue("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 Vue=ue("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 wI=ue("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 jI=ue("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 Hue=ue("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 Gue=ue("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 Wue=ue("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 Kue=ue("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 Yue=ue("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 Zue=ue("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 Xue=ue("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 Que=ue("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 Jue=ue("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 kK=ue("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 ehe=ue("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 the=ue("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 she=ue("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 nhe=ue("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 rhe=ue("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 ahe=ue("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 ihe=ue("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 ohe=ue("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 lhe=ue("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 sa=ue("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 che=ue("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 dhe=ue("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 NI=ue("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 uhe=ue("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 hhe=ue("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 mhe=ue("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 fhe=ue("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 phe=ue("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 ghe=ue("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 xhe=ue("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 yhe=ue("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 vhe=ue("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 bhe=ue("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 _he=ue("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 whe=ue("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 kI=ue("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 jhe=ue("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 Nhe=ue("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 n3=ue("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 khe=ue("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 wC=ue("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 $T=ue("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 She=ue("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 Che=ue("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 b_=ue("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 Ahe=ue("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 SK=ue("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 SI=ue("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 dE=ue("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 Ehe=ue("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 The=ue("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 Mhe=ue("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 D8=ue("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 Phe=ue("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 Ihe=ue("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 Lhe=ue("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 Rhe=ue("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 Dhe=ue("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 CI=ue("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 O8=ue("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 Ohe=ue("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 Fhe=ue("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 zhe=ue("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 Bhe=ue("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 $he=ue("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 Uhe=ue("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 qhe=ue("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 Vhe=ue("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 Hhe=ue("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 Da=ue("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 Ghe=ue("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 Whe=ue("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 Khe=ue("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 Yhe=ue("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 Zhe=ue("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 Xhe=ue("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 Qhe=ue("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 Jhe=ue("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 eme=ue("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 tme=ue("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 sme=ue("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 nme=ue("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 cv=ue("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 rme=ue("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 ame=ue("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 ime=ue("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 ome=ue("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 ky=ue("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 lme=ue("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 cme=ue("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 dme=ue("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 ume=ue("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 hme=ue("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 mme=ue("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 fme=ue("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 CK=ue("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 pme=ue("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 gme=ue("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 xme=ue("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 yme=ue("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 AI=ue("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 vme=ue("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 bme=ue("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 _me=ue("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 wme=ue("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 jme=ue("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 Nme=ue("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 kme=ue("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 Sme=ue("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 Cme=ue("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 Ame=ue("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 Eme=ue("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 Tme=ue("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 Mme=ue("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 Pme=ue("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 Ime=ue("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 Lme=ue("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 Rme=ue("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 Dme=ue("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 Ome=ue("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 Su=ue("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 Fme=ue("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 zme=ue("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 x2=ue("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 Bme=ue("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 ji=ue("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 $me=ue("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 Ume=ue("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 qme=ue("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 Vme=ue("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 Hme=ue("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 pb=ue("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 Gme=ue("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 Wme=ue("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 Kme=ue("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 Yme=ue("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 Zme=ue("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 Xme=ue("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 EI=ue("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 Qme=ue("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 Jme=ue("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 efe=ue("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 $z=ue("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 Z0=ue("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 u0=ue("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 tfe=ue("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 sfe=ue("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 nfe=ue("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 rfe=ue("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 afe=ue("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 ife=ue("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 ofe=ue("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 Ir=ue("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 lfe=ue("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 x0=ue("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 ba=ue("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 ax=ue("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 cfe=ue("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 dfe=ue("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 ufe=ue("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 hfe=ue("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 mfe=ue("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 ffe=ue("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 pfe=ue("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 gfe=ue("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 xfe=ue("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 yfe=ue("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 TI=ue("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 vfe=ue("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 bfe=ue("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 _fe=ue("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 MI=ue("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 PI=ue("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 II=ue("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 LI=ue("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 wfe=ue("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 AK=ue("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 jfe=ue("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 Nfe=ue("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 kfe=ue("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 RI=ue("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 Sfe=ue("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 Cfe=ue("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 y2=ue("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 Afe=ue("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 UT=ue("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 Efe=ue("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 Tfe=ue("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 Mfe=ue("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 Pfe=ue("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 Ife=ue("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 Lfe=ue("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 Rfe=ue("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 Dfe=ue("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 Ofe=ue("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 Ffe=ue("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 zfe=ue("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 uE=ue("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 DI=ue("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 Bfe=ue("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 $fe=ue("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 Ufe=ue("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 qfe=ue("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 Vfe=ue("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 Hfe=ue("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 Gfe=ue("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 rk=ue("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 EK=ue("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 Wfe=ue("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 Kfe=ue("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 ea=ue("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 Yfe=ue("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 Zfe=ue("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 Xfe=ue("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 Qfe=ue("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 Jfe=ue("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 TK=ue("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 epe=ue("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 tpe=ue("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 spe=ue("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 npe=ue("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 rpe=ue("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 Uz=ue("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 ape=ue("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 em=ue("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 ipe=ue("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 v2=ue("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 ope=ue("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 lpe=ue("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 cpe=ue("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 dpe=ue("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 upe=ue("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 hpe=ue("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 mpe=ue("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 fpe=ue("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 g3=ue("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 ppe=ue("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 iu=ue("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 gpe=ue("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 xpe=ue("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 ype=ue("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 qT=ue("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 vpe=ue("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 bpe=ue("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 MK=ue("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 _pe=ue("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 wpe=ue("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 QN=ue("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 jpe=ue("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 Npe=ue("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 kpe=ue("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 Spe=ue("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 Cpe=ue("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 Ape=ue("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 Epe=ue("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 Tpe=ue("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 Mpe=ue("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 OI=ue("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 Ppe=ue("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 Ipe=ue("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 Lpe=ue("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 Rpe=ue("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 Dpe=ue("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 Ope=ue("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 Fpe=ue("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 zpe=ue("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 Bpe=ue("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 $pe=ue("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 Upe=ue("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 d1=ue("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 qpe=ue("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 FI=ue("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 Vpe=ue("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 Hpe=ue("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 Gpe=ue("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 Wpe=ue("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 Kpe=ue("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 Ype=ue("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 Zpe=ue("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 Xpe=ue("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 Qpe=ue("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 Jpe=ue("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 ege=ue("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 tge=ue("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 sge=ue("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 nge=ue("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 rge=ue("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 age=ue("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 ige=ue("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 oge=ue("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 lge=ue("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 cge=ue("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 dge=ue("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 uge=ue("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 hge=ue("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 mge=ue("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 fge=ue("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 pge=ue("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 gge=ue("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 xge=ue("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 yge=ue("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 F8=ue("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 Zo=ue("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 vge=ue("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 bge=ue("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 zI=ue("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 _ge=ue("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 wge=ue("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 jge=ue("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 Nge=ue("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 kge=ue("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 Sge=ue("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 Cge=ue("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 Age=ue("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 Ege=ue("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 Tge=ue("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 Mge=ue("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 Pge=ue("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 Ige=ue("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 Lge=ue("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 Rge=ue("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 Dge=ue("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 Oge=ue("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 kc=ue("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 Fge=ue("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 zge=ue("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 Bm=ue("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 Bge=ue("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 $ge=ue("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 BI=ue("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 Uge=ue("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 $I=ue("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 Tw=ue("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 qge=ue("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 Bp=ue("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 Vge=ue("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 Hge=ue("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 Gge=ue("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 Wge=ue("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 PK=ue("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 Kge=ue("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 z8=ue("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 n5=ue("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 Yge=ue("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 Zge=ue("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 qz=ue("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 E5=ue("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 Xge=ue("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 Qge=ue("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 IK=ue("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 Jge=ue("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 VT=ue("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 exe=ue("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 txe=ue("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 Vz=ue("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 Hz=ue("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 LK=ue("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 sxe=ue("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 nxe=ue("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 rxe=ue("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 axe=ue("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 ixe=ue("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 oxe=ue("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 lxe=ue("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 cxe=ue("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 B8=ue("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 dxe=ue("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 uxe=ue("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 Bo=ue("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 hxe=ue("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 mxe=ue("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 fxe=ue("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 b2=ue("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 pxe=ue("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 gxe=ue("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 xxe=ue("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 yxe=ue("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 RK=ue("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 vxe=ue("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 bxe=ue("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 ua=ue("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 UI=ue("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 qI=ue("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 _xe=ue("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 wxe=ue("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 jxe=ue("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 Nxe=ue("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 kxe=ue("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 gb=ue("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 Sxe=ue("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 Cxe=ue("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 zc=ue("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 Axe=ue("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 Exe=ue("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 HT=ue("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 VI=ue("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 HI=ue("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 Txe=ue("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 Mxe=ue("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 T5=ue("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 Pxe=ue("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 Sf=ue("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 GT=ue("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 Ixe=ue("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 Lxe=ue("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 Rxe=ue("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 Dxe=ue("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 M5=ue("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 x3=ue("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 Oxe=ue("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 __=ue("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 Fxe=ue("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 zxe=ue("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 Bxe=ue("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 $xe=ue("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 Uxe=ue("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 qxe=ue("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 Vxe=ue("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 Hxe=ue("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 Gxe=ue("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 Wxe=ue("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 Gz=ue("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 Kxe=ue("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 Yxe=ue("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 GI=ue("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 Zxe=ue("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 Xxe=ue("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 Qxe=ue("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 Jxe=ue("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 eye=ue("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 tye=ue("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 Wz=ue("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 $8=ue("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 y0=ue("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 sye=ue("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 nye=ue("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 rye=ue("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 Zw=ue("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 aye=ue("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 iye=ue("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 oye=ue("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 lye=ue("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 cye=ue("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 xb=ue("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 Kz=ue("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 dye=ue("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 uye=ue("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 P5=ue("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 hye=ue("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 pd=ue("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 od=ue("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 dv=ue("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 mye=ue("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 op=ue("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 fye=ue("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 pye=ue("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 DK=ue("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 gye=ue("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 xye=ue("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 _2=ue("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 yye=ue("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 vye=ue("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 bye=ue("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 _ye=ue("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 wye=ue("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 jye=ue("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 Nye=ue("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 Sy=ue("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 Jt=ue("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 kye=ue("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 Sye=ue("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 Cye=ue("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 Aye=ue("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 Yz=ue("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 WI=ue("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 Eye=ue("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 KI=ue("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 fu=ue("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 U8=ue("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 q8=ue("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 Tye=ue("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 Mye=ue("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 Pye=ue("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 Iye=ue("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 Zz=ue("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 Lye=ue("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 Xz=ue("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 OK=ue("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 Rye=ue("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 Dye=ue("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 Oye=ue("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 Qz=ue("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 pn=ue("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 Fye=ue("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 zye=ue("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 Bye=ue("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 $ye=ue("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 Uye=ue("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 qye=ue("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 Vye=ue("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 Hye=ue("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 Gye=ue("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 Wye=ue("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 Kye=ue("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 Yye=ue("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 Si=ue("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 Zye=ue("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 V8=ue("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 Xye=ue("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 FK=ue("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 H8=ue("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 y3=ue("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 Qye=ue("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 xm=ue("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 Jye=ue("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 e0e=ue("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 WT=ue("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 t0e=ue("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 s0e=ue("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 n0e=ue("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 Jz=ue("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 r0e=ue("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 a0e=ue("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 i0e=ue("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 eB=ue("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 o0e=ue("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 l0e=ue("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 c0e=ue("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 Vu=ue("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 d0e=ue("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 u0e=ue("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 h0e=ue("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 m0e=ue("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 tB=ue("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 f0e=ue("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 zK=ue("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 p0e=ue("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 h5=ue("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 v3=ue("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 g0e=ue("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 x0e=ue("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 y0e=ue("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 v0e=ue("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 b0e=ue("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 bo=ue("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 sB=ue("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 _0e=ue("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 YI=ue("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 w2=ue("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 w0e=ue("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 j0e=ue("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 N0e=ue("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 k0e=ue("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 S0e=ue("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 C0e=ue("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 A0e=ue("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 E0e=ue("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 ak=ue("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 T0e=ue("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 M0e=ue("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 P0e=ue("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 I0e=ue("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 L0e=ue("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 R0e=ue("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 nB=ue("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 D0e=ue("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 O0e=ue("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 F0e=ue("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 G8=ue("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 z0e=ue("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 j2=ue("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 B0e=ue("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 $0e=ue("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 U0e=ue("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 q0e=ue("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 V0e=ue("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 H0e=ue("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 G0e=ue("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 rh=ue("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 sv=ue("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 W0e=ue("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 ZI=ue("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 K0e=ue("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 Y0e=ue("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 Z0e=ue("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 X0e=ue("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 Q0e=ue("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 J0e=ue("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 eve=ue("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 tve=ue("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 sve=ue("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 nve=ue("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 rve=ue("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 ave=ue("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 BK=ue("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 ive=ue("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 ove=ue("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 lve=ue("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 rB=ue("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 cve=ue("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 dve=ue("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 uve=ue("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 $K=ue("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 hve=ue("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 N2=ue("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 mve=ue("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 fve=ue("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 pve=ue("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 gve=ue("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 xve=ue("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 yve=ue("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 vve=ue("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 bve=ue("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 _ve=ue("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 GN=ue("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 wve=ue("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 XI=ue("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 QI=ue("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 jve=ue("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 Nve=ue("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 kve=ue("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 Sve=ue("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 Cve=ue("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 Ave=ue("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 Eve=ue("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 Tve=ue("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 Mve=ue("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 UK=ue("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 Pve=ue("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 Ive=ue("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 bh=ue("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 Lve=ue("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 Rve=ue("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 JI=ue("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 Dve=ue("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 gd=ue("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 Ove=ue("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 eL=ue("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 Fve=ue("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 zve=ue("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 tL=ue("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 sL=ue("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 nL=ue("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 rL=ue("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 Bve=ue("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 aL=ue("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 $ve=ue("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 Uve=ue("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 qve=ue("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 iL=ue("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 Vve=ue("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 Hve=ue("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 Gve=ue("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 Wve=ue("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 jC=ue("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 KT=ue("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 Kve=ue("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 Yve=ue("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 jg=ue("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 uv=ue("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 Zve=ue("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 Xve=ue("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 WN=ue("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 Qve=ue("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 YT=ue("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 s2=ue("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 aB=ue("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 Jve=ue("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 e1e=ue("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 ui=ue("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 t1e=ue("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 ZT=ue("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 s1e=ue("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 n1e=ue("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 qK=ue("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 r1e=ue("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 a1e=ue("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 i1e=ue("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 o1e=ue("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 l1e=ue("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 ka=ue("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 c1e=ue("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 d1e=ue("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 u1e=ue("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 h1e=ue("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 m1e=ue("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 f1e=ue("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 p1e=ue("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 g1e=ue("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 x1e=ue("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 y1e=ue("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 v1e=ue("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 VK=ue("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 XT=ue("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 b1e=ue("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 _1e=ue("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 w1e=ue("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 j1e=ue("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 HK=ue("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 pu=ue("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 N1e=ue("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 oL=ue("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 k2=ue("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 nn=ue("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 k1e=ue("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 S1e=ue("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 C1e=ue("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 A1e=ue("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 E1e=ue("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 T1e=ue("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 M1e=ue("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 P1e=ue("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 I1e=ue("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 GK=ue("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 hv=ue("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 L1e=ue("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 QT=ue("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 R1e=ue("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 D1e=ue("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 O1e=ue("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 F1e=ue("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 Bx=ue("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 ik=ue("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 z1e=ue("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 iB=ue("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 B1e=ue("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 $1e=ue("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 U1e=ue("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 q1e=ue("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 Cy=ue("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 V1e=ue("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 H1e=ue("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 G1e=ue("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 W1e=ue("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 K1e=ue("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 Y1e=ue("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 Z1e=ue("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 X1e=ue("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 Q1e=ue("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 J1e=ue("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 ebe=ue("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 tbe=ue("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 sbe=ue("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 nbe=ue("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 lL=ue("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 rbe=ue("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 abe=ue("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 ibe=ue("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 obe=ue("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 lbe=ue("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 JT=ue("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 cbe=ue("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 oB=ue("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 dbe=ue("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 yo=ue("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 ube=ue("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 hbe=ue("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 mbe=ue("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 fbe=ue("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 pbe=ue("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 lB=ue("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 gbe=ue("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 xbe=ue("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 ybe=ue("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 WK=ue("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 vbe=ue("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 bbe=ue("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 v0=ue("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 _be=ue("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 wbe=ue("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 cL=ue("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 jbe=ue("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 jm=ue("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 Nbe=ue("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 W8=ue("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 kbe=ue("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 cB=ue("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 Sbe=ue("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 dL=ue("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 uL=ue("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 Cbe=ue("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 Abe=ue("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 b3=ue("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 Ebe=ue("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 Tbe=ue("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 Mbe=ue("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 Pbe=ue("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 Ibe=ue("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 Lbe=ue("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 Rbe=ue("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 Dbe=ue("SaveOff",[["path",{d:"M13 13H8a1 1 0 0 0-1 1v7",key:"h8g396"}],["path",{d:"M14 8h1",key:"1lfen6"}],["path",{d:"M17 21v-4",key:"1yknxs"}],["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M20.41 20.41A2 2 0 0 1 19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 .59-1.41",key:"1t4vdl"}],["path",{d:"M29.5 11.5s5 5 4 5",key:"zzn4i6"}],["path",{d:"M9 3h6.2a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V15",key:"24cby9"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ml=ue("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 hL=ue("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 KK=ue("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 Obe=ue("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 Fbe=ue("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 zbe=ue("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 Bbe=ue("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 $be=ue("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 Ube=ue("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 qbe=ue("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 Vbe=ue("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 Hbe=ue("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 Gbe=ue("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 Wbe=ue("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 Kbe=ue("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 Ybe=ue("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 Zbe=ue("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 YK=ue("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 Xbe=ue("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 Qbe=ue("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 Jbe=ue("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 e_e=ue("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 ZK=ue("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 Yr=ue("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 t_e=ue("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 mL=ue("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 s_e=ue("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 Wr=ue("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 n_e=ue("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 r_e=ue("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 a_e=ue("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 i_e=ue("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 o_e=ue("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 l_e=ue("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 eM=ue("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 Yc=ue("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 c_e=ue("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 ou=ue("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 XK=ue("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 d_e=ue("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 u_e=ue("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 dB=ue("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 h_e=ue("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 b0=ue("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 m_e=ue("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 f_e=ue("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 p_e=ue("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 K8=ue("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 g_e=ue("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 x_e=ue("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 fL=ue("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 Ng=ue("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 y_e=ue("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 v_e=ue("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 b_e=ue("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 I5=ue("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 __e=ue("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 ok=ue("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 w_e=ue("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 j_e=ue("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 N_e=ue("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 k_e=ue("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 Y8=ue("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 S_e=ue("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 C_e=ue("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 A_e=ue("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 E_e=ue("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 T_e=ue("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 M_e=ue("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 P_e=ue("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 I_e=ue("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 L_e=ue("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 R_e=ue("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 D_e=ue("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 QK=ue("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 O_e=ue("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 F_e=ue("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 z_e=ue("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 B_e=ue("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 tM=ue("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 pL=ue("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 $_e=ue("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 U_e=ue("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 yb=ue("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 q_e=ue("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 V_e=ue("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 H_e=ue("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 Hw=ue("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 G_e=ue("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 W_e=ue("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 K_e=ue("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 Y_e=ue("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 _3=ue("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 kn=ue("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 Z_e=ue("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 X_e=ue("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 Q_e=ue("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 J_e=ue("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 ewe=ue("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 twe=ue("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 swe=ue("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 sM=ue("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 gL=ue("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 xL=ue("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 yL=ue("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 vL=ue("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 bL=ue("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 _L=ue("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 wL=ue("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 jL=ue("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 NL=ue("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 kL=ue("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 SL=ue("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 CL=ue("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 AL=ue("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 EL=ue("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 TL=ue("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 vS=ue("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 r5=ue("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 ML=ue("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 PL=ue("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 IL=ue("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 LL=ue("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 RL=ue("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 DL=ue("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 nwe=ue("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 rwe=ue("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 OL=ue("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 FL=ue("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 zL=ue("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 BL=ue("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 $L=ue("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 UL=ue("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 qL=ue("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 VL=ue("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 HL=ue("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 GL=ue("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 WL=ue("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 KL=ue("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 YL=ue("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 ZL=ue("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 XL=ue("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 Cp=ue("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 QL=ue("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 JL=ue("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 eR=ue("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 tR=ue("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 sR=ue("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 nR=ue("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 awe=ue("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 rR=ue("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 aR=ue("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 iR=ue("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 oR=ue("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 lR=ue("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 iwe=ue("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 owe=ue("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 cR=ue("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 dR=ue("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 uR=ue("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 hR=ue("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 w_=ue("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 lwe=ue("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 cwe=ue("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 dwe=ue("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 uwe=ue("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 hwe=ue("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 ri=ue("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 mwe=ue("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 fwe=ue("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 pwe=ue("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 gwe=ue("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 Z8=ue("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 uB=ue("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 xwe=ue("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 ywe=ue("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 JK=ue("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 vwe=ue("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 bwe=ue("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 _we=ue("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 wwe=ue("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 jwe=ue("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 S2=ue("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 Nwe=ue("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 kwe=ue("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 Swe=ue("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 Cwe=ue("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 Awe=ue("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 Ewe=ue("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 Twe=ue("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 Mwe=ue("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 Pwe=ue("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 hB=ue("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 Iwe=ue("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 Lwe=ue("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 Rwe=ue("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 Dwe=ue("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 Owe=ue("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 Fwe=ue("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 mB=ue("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 zwe=ue("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 fB=ue("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 Bwe=ue("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 kg=ue("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 eY=ue("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 $we=ue("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 Uwe=ue("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 qwe=ue("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 Vwe=ue("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 Hwe=ue("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 Gwe=ue("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 _h=ue("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 Wwe=ue("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 Kwe=ue("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 Ywe=ue("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 Zwe=ue("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 mR=ue("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 Xwe=ue("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 Qwe=ue("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 Jwe=ue("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 eje=ue("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 tje=ue("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 sje=ue("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 fR=ue("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 nje=ue("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 rje=ue("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 aje=ue("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 ije=ue("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 tY=ue("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 sY=ue("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 Ay=ue("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 oje=ue("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 lje=ue("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 cje=ue("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 dje=ue("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 uje=ue("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 hje=ue("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 X8=ue("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 mje=ue("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 fje=ue("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 pje=ue("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 gje=ue("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 xje=ue("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 yje=ue("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 vje=ue("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 bje=ue("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 _je=ue("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 wje=ue("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 jje=ue("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 Nje=ue("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 kje=ue("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 Sje=ue("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 Cje=ue("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 Aje=ue("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 Eje=ue("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 Tje=ue("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 Mje=ue("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 pR=ue("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 Un=ue("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 Pje=ue("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 Ije=ue("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 gR=ue("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 nM=ue("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 Lje=ue("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 Rje=ue("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 lk=ue("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 Dje=ue("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 mc=ue("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 Gd=ue("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 Oje=ue("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 Fje=ue("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 ql=ue("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 nY=ue("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 zje=ue("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 Bje=ue("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 xR=ue("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 $je=ue("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 Uje=ue("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 qje=ue("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 Vje=ue("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 Hje=ue("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 Gje=ue("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 Wje=ue("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 pB=ue("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 rY=ue("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 Kje=ue("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 rM=ue("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 Yje=ue("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 Zje=ue("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 Xje=ue("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 yR=ue("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 Qje=ue("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 Q8=ue("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 aY=ue("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 gi=ue("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 Jje=ue("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 ck=ue("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 iY=ue("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 gB=ue("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 e2e=ue("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 Pl=ue("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 vR=ue("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 bR=ue("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 _R=ue("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 t2e=ue("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 wR=ue("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 s2e=ue("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 jR=ue("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 NR=ue("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 n2e=ue("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 r2e=ue("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 el=ue("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 tb=ue("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 Xn=ue("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 kR=ue("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 SR=ue("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 a2e=ue("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 xB=ue("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 i2e=ue("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 o2e=ue("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 l2e=ue("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 c2e=ue("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 d2e=ue("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 u2e=ue("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 ia=ue("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 h2e=ue("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 m2e=ue("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 f2e=ue("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 p2e=ue("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 g2e=ue("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 oY=ue("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 x2e=ue("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 lY=ue("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 y2e=ue("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 v2e=ue("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 b2e=ue("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 CR=ue("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 cY=ue("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 _2e=ue("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 vf=ue("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 w2e=ue("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 j2e=ue("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 N2e=ue("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 k2e=ue("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 S2e=ue("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 C2e=ue("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 A2e=ue("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 E2e=ue("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 T2e=ue("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 M2e=ue("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 P2e=ue("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 I2e=ue("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 L2e=ue("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 R2e=ue("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 D2e=ue("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 O2e=ue("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 F2e=ue("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 z2e=ue("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 B2e=ue("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 $2e=ue("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 U2e=ue("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 dY=ue("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 uY=ue("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 q2e=ue("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 V2e=ue("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 L5=ue("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 mr=ue("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 H2e=ue("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 G2e=ue("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 ix=ue("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 aM=ue("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 yB=ue("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 Pss=Object.freeze(Object.defineProperty({__proto__:null,AArrowDown:soe,AArrowUp:noe,ALargeSmall:roe,Accessibility:aoe,Activity:zp,AirVent:ioe,Airplay:ooe,AlarmClock:coe,AlarmClockCheck:jP,AlarmClockMinus:NP,AlarmClockOff:loe,AlarmClockPlus:kP,AlarmSmoke:doe,Album:uoe,AlignCenter:T8,AlignCenterHorizontal:hoe,AlignCenterVertical:moe,AlignEndHorizontal:foe,AlignEndVertical:poe,AlignHorizontalDistributeCenter:goe,AlignHorizontalDistributeEnd:xoe,AlignHorizontalDistributeStart:yoe,AlignHorizontalJustifyCenter:voe,AlignHorizontalJustifyEnd:boe,AlignHorizontalJustifyStart:_oe,AlignHorizontalSpaceAround:woe,AlignHorizontalSpaceBetween:joe,AlignJustify:Noe,AlignLeft:M8,AlignRight:P8,AlignStartHorizontal:koe,AlignStartVertical:Soe,AlignVerticalDistributeCenter:Coe,AlignVerticalDistributeEnd:Aoe,AlignVerticalDistributeStart:Eoe,AlignVerticalJustifyCenter:Toe,AlignVerticalJustifyEnd:Moe,AlignVerticalJustifyStart:Poe,AlignVerticalSpaceAround:Ioe,AlignVerticalSpaceBetween:Loe,Ambulance:Roe,Ampersand:Doe,Ampersands:Ooe,Amphora:Foe,Anchor:zoe,Angry:Boe,Annoyed:$oe,Antenna:Uoe,Anvil:qoe,Aperture:Voe,AppWindow:Goe,AppWindowMac:Hoe,Apple:Woe,Archive:kf,ArchiveRestore:OT,ArchiveX:Koe,Armchair:Yoe,ArrowBigDown:Xoe,ArrowBigDownDash:Zoe,ArrowBigLeft:Joe,ArrowBigLeftDash:Qoe,ArrowBigRight:tle,ArrowBigRightDash:ele,ArrowBigUp:nle,ArrowBigUpDash:sle,ArrowDown:nx,ArrowDown01:rle,ArrowDown10:ale,ArrowDownAZ:SP,ArrowDownFromLine:ile,ArrowDownLeft:ole,ArrowDownNarrowWide:lle,ArrowDownRight:vK,ArrowDownToDot:cle,ArrowDownToLine:dle,ArrowDownUp:ule,ArrowDownWideNarrow:CP,ArrowDownZA:AP,ArrowLeft:Ia,ArrowLeftFromLine:hle,ArrowLeftRight:bK,ArrowLeftToLine:mle,ArrowRight:xi,ArrowRightFromLine:fle,ArrowRightLeft:N5,ArrowRightToLine:ple,ArrowUp:ap,ArrowUp01:gle,ArrowUp10:xle,ArrowUpAZ:EP,ArrowUpDown:Ix,ArrowUpFromDot:yle,ArrowUpFromLine:vle,ArrowUpLeft:ble,ArrowUpNarrowWide:TP,ArrowUpRight:FT,ArrowUpToLine:_le,ArrowUpWideNarrow:wle,ArrowUpZA:MP,ArrowsUpFromLine:jle,Asterisk:Nle,AtSign:kle,Atom:Sle,AudioLines:Cle,AudioWaveform:Ale,Award:oh,Axe:Ele,Axis3d:PP,Baby:Tle,Backpack:Mle,Badge:Wle,BadgeAlert:Ple,BadgeCent:Ile,BadgeCheck:IP,BadgeDollarSign:Lle,BadgeEuro:Rle,BadgeHelp:Dle,BadgeIndianRupee:Ole,BadgeInfo:Fle,BadgeJapaneseYen:zle,BadgeMinus:Ble,BadgePercent:$le,BadgePlus:Ule,BadgePoundSterling:qle,BadgeRussianRuble:Vle,BadgeSwissFranc:Hle,BadgeX:Gle,BaggageClaim:Kle,Ban:Fz,Banana:Yle,Bandage:Zle,Banknote:Xle,Barcode:Qle,Baseline:Jle,Bath:p0,Battery:ace,BatteryCharging:ece,BatteryFull:tce,BatteryLow:sce,BatteryMedium:nce,BatteryWarning:rce,Beaker:_K,Bean:oce,BeanOff:ice,Bed:Yw,BedDouble:f3,BedSingle:lce,Beef:cce,Beer:uce,BeerOff:dce,Bell:Fx,BellDot:hce,BellElectric:mce,BellMinus:fce,BellOff:k5,BellPlus:pce,BellRing:p3,BetweenHorizontalEnd:LP,BetweenHorizontalStart:RP,BetweenVerticalEnd:gce,BetweenVerticalStart:xce,BicepsFlexed:yce,Bike:vce,Binary:bce,Binoculars:_ce,Biohazard:wce,Bird:jce,Bitcoin:Nce,Blend:kce,Blinds:Sce,Blocks:Cce,Bluetooth:Mce,BluetoothConnected:Ace,BluetoothOff:Ece,BluetoothSearching:Tce,Bold:zT,Bolt:Pce,Bomb:Ice,Bone:Lce,Book:sde,BookA:Rce,BookAudio:Dce,BookCheck:Oce,BookCopy:Fce,BookDashed:DP,BookDown:zce,BookHeadphones:Bce,BookHeart:$ce,BookImage:Uce,BookKey:qce,BookLock:Vce,BookMarked:Hce,BookMinus:Gce,BookOpen:wg,BookOpenCheck:Wce,BookOpenText:Kce,BookPlus:Yce,BookText:Zce,BookType:Xce,BookUp:Jce,BookUp2:Qce,BookUser:ede,BookX:tde,Bookmark:jy,BookmarkCheck:nde,BookmarkMinus:rde,BookmarkPlus:BT,BookmarkX:ade,BoomBox:ide,Bot:S5,BotMessageSquare:ode,BotOff:lde,Box:wK,Boxes:cde,Braces:OP,Brackets:dde,Brain:jK,BrainCircuit:ude,BrainCog:hde,BrickWall:mde,Briefcase:zx,BriefcaseBusiness:fde,BriefcaseConveyorBelt:pde,BriefcaseMedical:gde,BringToFront:xde,Brush:yde,Bug:_de,BugOff:vde,BugPlay:bde,Building:I8,Building2:Gi,Bus:jde,BusFront:wde,Cable:kde,CableCar:Nde,Cake:ip,CakeSlice:Sde,Calculator:C5,Calendar:ha,Calendar1:Cde,CalendarArrowDown:Ade,CalendarArrowUp:Ede,CalendarCheck:fb,CalendarCheck2:Tde,CalendarClock:wm,CalendarCog:Mde,CalendarDays:fd,CalendarFold:Pde,CalendarHeart:nk,CalendarMinus:Lde,CalendarMinus2:Ide,CalendarOff:zz,CalendarPlus:i1,CalendarPlus2:Rde,CalendarRange:Dde,CalendarSearch:Ode,CalendarSync:Fde,CalendarX:NK,CalendarX2:zde,Camera:g0,CameraOff:Bde,Candy:qde,CandyCane:$de,CandyOff:Ude,Cannabis:Vde,Captions:FP,CaptionsOff:Hde,Car:Kde,CarFront:Gde,CarTaxiFront:Wde,Caravan:Yde,Carrot:Zde,CaseLower:Xde,CaseSensitive:Qde,CaseUpper:Jde,CassetteTape:eue,Cast:tue,Castle:sue,Cat:nue,Cctv:rue,ChartArea:zP,ChartBar:$P,ChartBarBig:BP,ChartBarDecreasing:aue,ChartBarIncreasing:iue,ChartBarStacked:oue,ChartCandlestick:UP,ChartColumn:Ul,ChartColumnBig:qP,ChartColumnDecreasing:lue,ChartColumnIncreasing:VP,ChartColumnStacked:cue,ChartGantt:due,ChartLine:HP,ChartNetwork:uue,ChartNoAxesColumn:WP,ChartNoAxesColumnDecreasing:hue,ChartNoAxesColumnIncreasing:GP,ChartNoAxesCombined:mue,ChartNoAxesGantt:KP,ChartPie:YP,ChartScatter:ZP,ChartSpline:fue,Check:ma,CheckCheck:L8,ChefHat:pue,Cherry:gue,ChevronDown:Go,ChevronFirst:xue,ChevronLast:yue,ChevronLeft:Ld,ChevronRight:fi,ChevronUp:Ny,ChevronsDown:bue,ChevronsDownUp:vue,ChevronsLeft:jue,ChevronsLeftRight:wue,ChevronsLeftRightEllipsis:_ue,ChevronsRight:kue,ChevronsRightLeft:Nue,ChevronsUp:Sue,ChevronsUpDown:v_,Chrome:R8,Church:Cue,Cigarette:Eue,CigaretteOff:Aue,Circle:rx,CircleAlert:Ho,CircleArrowDown:XP,CircleArrowLeft:QP,CircleArrowOutDownLeft:JP,CircleArrowOutDownRight:eI,CircleArrowOutUpLeft:tI,CircleArrowOutUpRight:sI,CircleArrowRight:nI,CircleArrowUp:rI,CircleCheck:Gr,CircleCheckBig:nl,CircleChevronDown:aI,CircleChevronLeft:iI,CircleChevronRight:oI,CircleChevronUp:lI,CircleDashed:Tue,CircleDivide:cI,CircleDollarSign:Mue,CircleDot:Iue,CircleDotDashed:Pue,CircleEllipsis:Lue,CircleEqual:Rue,CircleFadingArrowUp:Due,CircleFadingPlus:Oue,CircleGauge:dI,CircleHelp:_C,CircleMinus:uI,CircleOff:Fue,CircleParking:mI,CircleParkingOff:hI,CirclePause:fI,CirclePercent:pI,CirclePlay:mm,CirclePlus:gI,CirclePower:xI,CircleSlash:zue,CircleSlash2:yI,CircleStop:vI,CircleUser:_I,CircleUserRound:bI,CircleX:ju,CircuitBoard:Bue,Citrus:$ue,Clapperboard:Bz,Clipboard:Kue,ClipboardCheck:A5,ClipboardCopy:Uue,ClipboardList:lv,ClipboardMinus:que,ClipboardPaste:Vue,ClipboardPen:jI,ClipboardPenLine:wI,ClipboardPlus:Hue,ClipboardType:Gue,ClipboardX:Wue,Clock:sa,Clock1:Yue,Clock10:Zue,Clock11:Xue,Clock12:Que,Clock2:Jue,Clock3:kK,Clock4:ehe,Clock5:the,Clock6:she,Clock7:nhe,Clock8:rhe,Clock9:ahe,ClockAlert:ihe,ClockArrowDown:ohe,ClockArrowUp:lhe,Cloud:jhe,CloudAlert:che,CloudCog:dhe,CloudDownload:NI,CloudDrizzle:uhe,CloudFog:hhe,CloudHail:mhe,CloudLightning:fhe,CloudMoon:ghe,CloudMoonRain:phe,CloudOff:xhe,CloudRain:vhe,CloudRainWind:yhe,CloudSnow:bhe,CloudSun:whe,CloudSunRain:_he,CloudUpload:kI,Cloudy:Nhe,Clover:n3,Club:khe,Code:$T,CodeXml:wC,Codepen:She,Codesandbox:Che,Coffee:b_,Cog:Ahe,Coins:SK,Columns2:SI,Columns3:dE,Columns4:Ehe,Combine:The,Command:Mhe,Compass:D8,Component:Phe,Computer:Ihe,ConciergeBell:Lhe,Cone:Rhe,Construction:Dhe,Contact:O8,ContactRound:CI,Container:Ohe,Contrast:Fhe,Cookie:zhe,CookingPot:Bhe,Copy:Da,CopyCheck:$he,CopyMinus:Uhe,CopyPlus:qhe,CopySlash:Vhe,CopyX:Hhe,Copyleft:Ghe,Copyright:Whe,CornerDownLeft:Khe,CornerDownRight:Yhe,CornerLeftDown:Zhe,CornerLeftUp:Xhe,CornerRightDown:Qhe,CornerRightUp:Jhe,CornerUpLeft:eme,CornerUpRight:tme,Cpu:sme,CreativeCommons:nme,CreditCard:cv,Croissant:rme,Crop:ame,Cross:ime,Crosshair:ome,Crown:ky,Cuboid:lme,CupSoda:cme,Currency:dme,Cylinder:ume,Dam:hme,Database:CK,DatabaseBackup:mme,DatabaseZap:fme,Delete:pme,Dessert:gme,Diameter:xme,Diamond:bme,DiamondMinus:yme,DiamondPercent:AI,DiamondPlus:vme,Dice1:_me,Dice2:wme,Dice3:jme,Dice4:Nme,Dice5:kme,Dice6:Sme,Dices:Cme,Diff:Ame,Disc:Pme,Disc2:Eme,Disc3:Tme,DiscAlbum:Mme,Divide:Ime,Dna:Rme,DnaOff:Lme,Dock:Dme,Dog:Ome,DollarSign:Su,Donut:Fme,DoorClosed:zme,DoorOpen:x2,Dot:Bme,Download:ji,DraftingCompass:$me,Drama:Ume,Dribbble:qme,Drill:Vme,Droplet:Hme,Droplets:pb,Drum:Gme,Drumstick:Wme,Dumbbell:Kme,Ear:Zme,EarOff:Yme,Earth:EI,EarthLock:Xme,Eclipse:Qme,Egg:$z,EggFried:Jme,EggOff:efe,Ellipsis:u0,EllipsisVertical:Z0,Equal:nfe,EqualApproximately:tfe,EqualNot:sfe,Eraser:rfe,EthernetPort:afe,Euro:ife,Expand:ofe,ExternalLink:Ir,Eye:ba,EyeClosed:lfe,EyeOff:x0,Facebook:ax,Factory:cfe,Fan:dfe,FastForward:ufe,Feather:hfe,Fence:mfe,FerrisWheel:ffe,Figma:pfe,File:Uz,FileArchive:gfe,FileAudio:yfe,FileAudio2:xfe,FileAxis3d:TI,FileBadge:bfe,FileBadge2:vfe,FileBox:_fe,FileChartColumn:PI,FileChartColumnIncreasing:MI,FileChartLine:II,FileChartPie:LI,FileCheck:AK,FileCheck2:wfe,FileClock:jfe,FileCode:kfe,FileCode2:Nfe,FileCog:RI,FileDiff:Sfe,FileDigit:Cfe,FileDown:y2,FileHeart:Afe,FileImage:UT,FileInput:Efe,FileJson:Mfe,FileJson2:Tfe,FileKey:Ife,FileKey2:Pfe,FileLock:Rfe,FileLock2:Lfe,FileMinus:Ofe,FileMinus2:Dfe,FileMusic:Ffe,FileOutput:zfe,FilePen:DI,FilePenLine:uE,FilePlus:$fe,FilePlus2:Bfe,FileQuestion:Ufe,FileScan:qfe,FileSearch:Hfe,FileSearch2:Vfe,FileSliders:Gfe,FileSpreadsheet:rk,FileStack:EK,FileSymlink:Wfe,FileTerminal:Kfe,FileText:ea,FileType:Zfe,FileType2:Yfe,FileUp:Xfe,FileUser:Qfe,FileVideo:TK,FileVideo2:Jfe,FileVolume:tpe,FileVolume2:epe,FileWarning:spe,FileX:rpe,FileX2:npe,Files:ape,Film:em,Filter:v2,FilterX:ipe,Fingerprint:ope,FireExtinguisher:lpe,Fish:upe,FishOff:cpe,FishSymbol:dpe,Flag:g3,FlagOff:hpe,FlagTriangleLeft:mpe,FlagTriangleRight:fpe,Flame:iu,FlameKindling:ppe,Flashlight:xpe,FlashlightOff:gpe,FlaskConical:qT,FlaskConicalOff:ype,FlaskRound:vpe,FlipHorizontal:MK,FlipHorizontal2:bpe,FlipVertical:wpe,FlipVertical2:_pe,Flower:jpe,Flower2:QN,Focus:Npe,FoldHorizontal:kpe,FoldVertical:Spe,Folder:Jpe,FolderArchive:Cpe,FolderCheck:Ape,FolderClock:Epe,FolderClosed:Tpe,FolderCode:Mpe,FolderCog:OI,FolderDot:Ppe,FolderDown:Ipe,FolderGit:Rpe,FolderGit2:Lpe,FolderHeart:Dpe,FolderInput:Ope,FolderKanban:Fpe,FolderKey:zpe,FolderLock:Bpe,FolderMinus:$pe,FolderOpen:d1,FolderOpenDot:Upe,FolderOutput:qpe,FolderPen:FI,FolderPlus:Vpe,FolderRoot:Hpe,FolderSearch:Wpe,FolderSearch2:Gpe,FolderSymlink:Kpe,FolderSync:Ype,FolderTree:Zpe,FolderUp:Xpe,FolderX:Qpe,Folders:ege,Footprints:tge,Forklift:sge,Forward:nge,Frame:rge,Framer:age,Frown:ige,Fuel:oge,Fullscreen:lge,GalleryHorizontal:dge,GalleryHorizontalEnd:cge,GalleryThumbnails:uge,GalleryVertical:mge,GalleryVerticalEnd:hge,Gamepad:pge,Gamepad2:fge,Gauge:gge,Gavel:xge,Gem:yge,Ghost:F8,Gift:Zo,GitBranch:bge,GitBranchPlus:vge,GitCommitHorizontal:zI,GitCommitVertical:_ge,GitCompare:jge,GitCompareArrows:wge,GitFork:Nge,GitGraph:kge,GitMerge:Sge,GitPullRequest:Pge,GitPullRequestArrow:Cge,GitPullRequestClosed:Age,GitPullRequestCreate:Tge,GitPullRequestCreateArrow:Ege,GitPullRequestDraft:Mge,Github:Ige,Gitlab:Lge,GlassWater:Rge,Glasses:Dge,Globe:kc,GlobeLock:Oge,Goal:Fge,Grab:zge,GraduationCap:Bm,Grape:Bge,Grid2x2:$I,Grid2x2Check:$ge,Grid2x2Plus:BI,Grid2x2X:Uge,Grid3x3:Tw,Grip:Vge,GripHorizontal:qge,GripVertical:Bp,Group:Hge,Guitar:Gge,Ham:Wge,Hammer:PK,Hand:qz,HandCoins:Kge,HandHeart:z8,HandHelping:n5,HandMetal:Yge,HandPlatter:Zge,Handshake:E5,HardDrive:IK,HardDriveDownload:Xge,HardDriveUpload:Qge,HardHat:Jge,Hash:VT,Haze:exe,HdmiPort:txe,Heading:axe,Heading1:Vz,Heading2:Hz,Heading3:LK,Heading4:sxe,Heading5:nxe,Heading6:rxe,HeadphoneOff:ixe,Headphones:oxe,Headset:lxe,Heart:Bo,HeartCrack:cxe,HeartHandshake:B8,HeartOff:dxe,HeartPulse:uxe,Heater:hxe,Hexagon:mxe,Highlighter:fxe,History:b2,Hop:gxe,HopOff:pxe,Hospital:xxe,Hotel:yxe,Hourglass:RK,House:ua,HousePlug:vxe,HousePlus:bxe,IceCreamBowl:UI,IceCreamCone:qI,IdCard:_xe,Image:zc,ImageDown:wxe,ImageMinus:jxe,ImageOff:Nxe,ImagePlay:kxe,ImagePlus:gb,ImageUp:Sxe,ImageUpscale:Cxe,Images:Axe,Import:Exe,Inbox:HT,IndentDecrease:VI,IndentIncrease:HI,IndianRupee:Txe,Infinity:Mxe,Info:T5,InspectionPanel:Pxe,Instagram:Sf,Italic:GT,IterationCcw:Ixe,IterationCw:Lxe,JapaneseYen:Rxe,Joystick:Dxe,Kanban:M5,Key:__,KeyRound:x3,KeySquare:Oxe,Keyboard:Bxe,KeyboardMusic:Fxe,KeyboardOff:zxe,Lamp:Gxe,LampCeiling:$xe,LampDesk:Uxe,LampFloor:qxe,LampWallDown:Vxe,LampWallUp:Hxe,LandPlot:Wxe,Landmark:Gz,Languages:Kxe,Laptop:Zxe,LaptopMinimal:GI,LaptopMinimalCheck:Yxe,Lasso:Qxe,LassoSelect:Xxe,Laugh:Jxe,Layers:Wz,Layers2:eye,Layers3:tye,LayoutDashboard:$8,LayoutGrid:y0,LayoutList:sye,LayoutPanelLeft:nye,LayoutPanelTop:rye,LayoutTemplate:Zw,Leaf:aye,LeafyGreen:iye,Lectern:oye,LetterText:lye,Library:xb,LibraryBig:cye,LifeBuoy:Kz,Ligature:dye,Lightbulb:P5,LightbulbOff:uye,Link:od,Link2:pd,Link2Off:hye,Linkedin:dv,List:Sy,ListCheck:mye,ListChecks:op,ListCollapse:fye,ListEnd:pye,ListFilter:DK,ListMinus:gye,ListMusic:xye,ListOrdered:_2,ListPlus:yye,ListRestart:vye,ListStart:bye,ListTodo:_ye,ListTree:wye,ListVideo:jye,ListX:Nye,Loader:Sye,LoaderCircle:Jt,LoaderPinwheel:kye,Locate:Yz,LocateFixed:Cye,LocateOff:Aye,Lock:fu,LockKeyhole:Eye,LockKeyholeOpen:WI,LockOpen:KI,LogIn:U8,LogOut:q8,Logs:Tye,Lollipop:Mye,Luggage:Pye,Magnet:Iye,Mail:pn,MailCheck:Zz,MailMinus:Lye,MailOpen:Xz,MailPlus:OK,MailQuestion:Rye,MailSearch:Dye,MailWarning:Oye,MailX:Qz,Mailbox:Fye,Mails:zye,Map:V8,MapPin:Si,MapPinCheck:$ye,MapPinCheckInside:Bye,MapPinHouse:Uye,MapPinMinus:Vye,MapPinMinusInside:qye,MapPinOff:Hye,MapPinPlus:Wye,MapPinPlusInside:Gye,MapPinX:Yye,MapPinXInside:Kye,MapPinned:Zye,Martini:Xye,Maximize:H8,Maximize2:FK,Medal:y3,Megaphone:xm,MegaphoneOff:Qye,Meh:Jye,MemoryStick:e0e,Menu:WT,Merge:t0e,MessageCircle:Vu,MessageCircleCode:s0e,MessageCircleDashed:n0e,MessageCircleHeart:Jz,MessageCircleMore:r0e,MessageCircleOff:a0e,MessageCirclePlus:i0e,MessageCircleQuestion:eB,MessageCircleReply:o0e,MessageCircleWarning:l0e,MessageCircleX:c0e,MessageSquare:bo,MessageSquareCode:d0e,MessageSquareDashed:u0e,MessageSquareDiff:h0e,MessageSquareDot:m0e,MessageSquareHeart:tB,MessageSquareLock:f0e,MessageSquareMore:zK,MessageSquareOff:p0e,MessageSquarePlus:h5,MessageSquareQuote:v3,MessageSquareReply:g0e,MessageSquareShare:x0e,MessageSquareText:y0e,MessageSquareWarning:v0e,MessageSquareX:b0e,MessagesSquare:sB,Mic:w2,MicOff:_0e,MicVocal:YI,Microchip:w0e,Microscope:j0e,Microwave:N0e,Milestone:k0e,Milk:C0e,MilkOff:S0e,Minimize:E0e,Minimize2:A0e,Minus:ak,Monitor:j2,MonitorCheck:T0e,MonitorCog:M0e,MonitorDot:P0e,MonitorDown:I0e,MonitorOff:L0e,MonitorPause:R0e,MonitorPlay:nB,MonitorSmartphone:D0e,MonitorSpeaker:O0e,MonitorStop:F0e,MonitorUp:G8,MonitorX:z0e,Moon:$0e,MoonStar:B0e,Mountain:q0e,MountainSnow:U0e,Mouse:W0e,MouseOff:V0e,MousePointer:sv,MousePointer2:H0e,MousePointerBan:G0e,MousePointerClick:rh,Move:BK,Move3d:ZI,MoveDiagonal:Y0e,MoveDiagonal2:K0e,MoveDown:Q0e,MoveDownLeft:Z0e,MoveDownRight:X0e,MoveHorizontal:J0e,MoveLeft:eve,MoveRight:tve,MoveUp:rve,MoveUpLeft:sve,MoveUpRight:nve,MoveVertical:ave,Music:rB,Music2:ive,Music3:ove,Music4:lve,Navigation:$K,Navigation2:dve,Navigation2Off:cve,NavigationOff:uve,Network:hve,Newspaper:N2,Nfc:mve,Notebook:xve,NotebookPen:fve,NotebookTabs:pve,NotebookText:gve,NotepadText:vve,NotepadTextDashed:yve,Nut:_ve,NutOff:bve,Octagon:jve,OctagonAlert:GN,OctagonMinus:wve,OctagonPause:XI,OctagonX:QI,Omega:Nve,Option:kve,Orbit:Sve,Origami:Cve,Package:bh,Package2:Ave,PackageCheck:Eve,PackageMinus:Tve,PackageOpen:Mve,PackagePlus:UK,PackageSearch:Pve,PackageX:Ive,PaintBucket:Lve,PaintRoller:Rve,Paintbrush:Dve,PaintbrushVertical:JI,Palette:gd,PanelBottom:zve,PanelBottomClose:Ove,PanelBottomDashed:eL,PanelBottomOpen:Fve,PanelLeft:rL,PanelLeftClose:tL,PanelLeftDashed:sL,PanelLeftOpen:nL,PanelRight:Uve,PanelRightClose:Bve,PanelRightDashed:aL,PanelRightOpen:$ve,PanelTop:Hve,PanelTopClose:qve,PanelTopDashed:iL,PanelTopOpen:Vve,PanelsLeftBottom:Gve,PanelsRightBottom:Wve,PanelsTopLeft:jC,Paperclip:KT,Parentheses:Kve,ParkingMeter:Yve,PartyPopper:jg,Pause:uv,PawPrint:Zve,PcCase:Xve,Pen:s2,PenLine:WN,PenOff:Qve,PenTool:YT,Pencil:ui,PencilLine:aB,PencilOff:Jve,PencilRuler:e1e,Pentagon:t1e,Percent:ZT,PersonStanding:s1e,PhilippinePeso:n1e,Phone:ka,PhoneCall:qK,PhoneForwarded:r1e,PhoneIncoming:a1e,PhoneMissed:i1e,PhoneOff:o1e,PhoneOutgoing:l1e,Pi:c1e,Piano:d1e,Pickaxe:u1e,PictureInPicture:m1e,PictureInPicture2:h1e,PiggyBank:f1e,Pilcrow:x1e,PilcrowLeft:p1e,PilcrowRight:g1e,Pill:v1e,PillBottle:y1e,Pin:XT,PinOff:VK,Pipette:b1e,Pizza:_1e,Plane:HK,PlaneLanding:w1e,PlaneTakeoff:j1e,Play:pu,Plug:k2,Plug2:N1e,PlugZap:oL,Plus:nn,Pocket:S1e,PocketKnife:k1e,Podcast:C1e,Pointer:E1e,PointerOff:A1e,Popcorn:T1e,Popsicle:M1e,PoundSterling:P1e,Power:GK,PowerOff:I1e,Presentation:hv,Printer:QT,PrinterCheck:L1e,Projector:R1e,Proportions:D1e,Puzzle:O1e,Pyramid:F1e,QrCode:Bx,Quote:ik,Rabbit:z1e,Radar:iB,Radiation:B1e,Radical:$1e,Radio:Cy,RadioReceiver:U1e,RadioTower:q1e,Radius:V1e,RailSymbol:H1e,Rainbow:G1e,Rat:W1e,Ratio:K1e,Receipt:nbe,ReceiptCent:Y1e,ReceiptEuro:Z1e,ReceiptIndianRupee:X1e,ReceiptJapaneseYen:Q1e,ReceiptPoundSterling:J1e,ReceiptRussianRuble:ebe,ReceiptSwissFranc:tbe,ReceiptText:sbe,RectangleEllipsis:lL,RectangleHorizontal:rbe,RectangleVertical:abe,Recycle:ibe,Redo:JT,Redo2:obe,RedoDot:lbe,RefreshCcw:oB,RefreshCcwDot:cbe,RefreshCw:yo,RefreshCwOff:dbe,Refrigerator:ube,Regex:hbe,RemoveFormatting:mbe,Repeat:lB,Repeat1:fbe,Repeat2:pbe,Replace:xbe,ReplaceAll:gbe,Reply:WK,ReplyAll:ybe,Rewind:vbe,Ribbon:bbe,Rocket:v0,RockingChair:_be,RollerCoaster:wbe,Rotate3d:cL,RotateCcw:jm,RotateCcwSquare:jbe,RotateCw:W8,RotateCwSquare:Nbe,Route:cB,RouteOff:kbe,Router:Sbe,Rows2:dL,Rows3:uL,Rows4:Cbe,Rss:Abe,Ruler:b3,RussianRuble:Ebe,Sailboat:Tbe,Salad:Mbe,Sandwich:Pbe,Satellite:Lbe,SatelliteDish:Ibe,Save:Ml,SaveAll:Rbe,SaveOff:Dbe,Scale:KK,Scale3d:hL,Scaling:Obe,Scan:Hbe,ScanBarcode:Fbe,ScanEye:zbe,ScanFace:Bbe,ScanLine:$be,ScanQrCode:Ube,ScanSearch:qbe,ScanText:Vbe,School:Gbe,Scissors:Kbe,ScissorsLineDashed:Wbe,ScreenShare:Zbe,ScreenShareOff:Ybe,Scroll:Xbe,ScrollText:YK,Search:Yr,SearchCheck:Qbe,SearchCode:Jbe,SearchSlash:e_e,SearchX:ZK,Section:t_e,Send:Wr,SendHorizontal:mL,SendToBack:s_e,SeparatorHorizontal:n_e,SeparatorVertical:r_e,Server:l_e,ServerCog:a_e,ServerCrash:i_e,ServerOff:o_e,Settings:Yc,Settings2:eM,Shapes:c_e,Share:XK,Share2:ou,Sheet:d_e,Shell:u_e,Shield:Ng,ShieldAlert:dB,ShieldBan:h_e,ShieldCheck:b0,ShieldEllipsis:m_e,ShieldHalf:f_e,ShieldMinus:p_e,ShieldOff:K8,ShieldPlus:g_e,ShieldQuestion:x_e,ShieldX:fL,Ship:v_e,ShipWheel:y_e,Shirt:b_e,ShoppingBag:I5,ShoppingBasket:__e,ShoppingCart:ok,Shovel:w_e,ShowerHead:j_e,Shrink:N_e,Shrub:k_e,Shuffle:Y8,Sigma:S_e,Signal:M_e,SignalHigh:C_e,SignalLow:A_e,SignalMedium:E_e,SignalZero:T_e,Signature:P_e,Signpost:L_e,SignpostBig:I_e,Siren:R_e,SkipBack:D_e,SkipForward:QK,Skull:O_e,Slack:F_e,Slash:z_e,Slice:B_e,SlidersHorizontal:tM,SlidersVertical:pL,Smartphone:yb,SmartphoneCharging:$_e,SmartphoneNfc:U_e,Smile:V_e,SmilePlus:q_e,Snail:H_e,Snowflake:Hw,Sofa:G_e,Soup:W_e,Space:K_e,Spade:Y_e,Sparkle:_3,Sparkles:kn,Speaker:Z_e,Speech:X_e,SpellCheck:J_e,SpellCheck2:Q_e,Spline:ewe,Split:twe,SprayCan:swe,Sprout:sM,Square:w_,SquareActivity:gL,SquareArrowDown:vL,SquareArrowDownLeft:xL,SquareArrowDownRight:yL,SquareArrowLeft:bL,SquareArrowOutDownLeft:_L,SquareArrowOutDownRight:wL,SquareArrowOutUpLeft:jL,SquareArrowOutUpRight:NL,SquareArrowRight:kL,SquareArrowUp:AL,SquareArrowUpLeft:SL,SquareArrowUpRight:CL,SquareAsterisk:EL,SquareBottomDashedScissors:TL,SquareChartGantt:vS,SquareCheck:ML,SquareCheckBig:r5,SquareChevronDown:PL,SquareChevronLeft:IL,SquareChevronRight:LL,SquareChevronUp:RL,SquareCode:DL,SquareDashed:zL,SquareDashedBottom:rwe,SquareDashedBottomCode:nwe,SquareDashedKanban:OL,SquareDashedMousePointer:FL,SquareDivide:BL,SquareDot:$L,SquareEqual:UL,SquareFunction:qL,SquareKanban:VL,SquareLibrary:HL,SquareM:GL,SquareMenu:WL,SquareMinus:KL,SquareMousePointer:YL,SquareParking:XL,SquareParkingOff:ZL,SquarePen:Cp,SquarePercent:QL,SquarePi:JL,SquarePilcrow:eR,SquarePlay:tR,SquarePlus:sR,SquarePower:nR,SquareRadical:awe,SquareScissors:rR,SquareSigma:aR,SquareSlash:iR,SquareSplitHorizontal:oR,SquareSplitVertical:lR,SquareSquare:iwe,SquareStack:owe,SquareTerminal:cR,SquareUser:uR,SquareUserRound:dR,SquareX:hR,Squircle:lwe,Squirrel:cwe,Stamp:dwe,Star:ri,StarHalf:uwe,StarOff:hwe,StepBack:mwe,StepForward:fwe,Stethoscope:pwe,Sticker:gwe,StickyNote:Z8,Store:uB,StretchHorizontal:xwe,StretchVertical:ywe,Strikethrough:JK,Subscript:vwe,Sun:S2,SunDim:bwe,SunMedium:_we,SunMoon:wwe,SunSnow:jwe,Sunrise:Nwe,Sunset:kwe,Superscript:Swe,SwatchBook:Cwe,SwissFranc:Awe,SwitchCamera:Ewe,Sword:Twe,Swords:Mwe,Syringe:Pwe,Table:mB,Table2:hB,TableCellsMerge:Iwe,TableCellsSplit:Lwe,TableColumnsSplit:Rwe,TableOfContents:Dwe,TableProperties:Owe,TableRowsSplit:Fwe,Tablet:fB,TabletSmartphone:zwe,Tablets:Bwe,Tag:kg,Tags:eY,Tally1:$we,Tally2:Uwe,Tally3:qwe,Tally4:Vwe,Tally5:Hwe,Tangent:Gwe,Target:_h,Telescope:Wwe,Tent:Ywe,TentTree:Kwe,Terminal:Zwe,TestTube:Xwe,TestTubeDiagonal:mR,TestTubes:Qwe,Text:nje,TextCursor:eje,TextCursorInput:Jwe,TextQuote:tje,TextSearch:sje,TextSelect:fR,Theater:rje,Thermometer:tY,ThermometerSnowflake:aje,ThermometerSun:ije,ThumbsDown:sY,ThumbsUp:Ay,Ticket:X8,TicketCheck:oje,TicketMinus:lje,TicketPercent:cje,TicketPlus:dje,TicketSlash:uje,TicketX:hje,Tickets:fje,TicketsPlane:mje,Timer:xje,TimerOff:pje,TimerReset:gje,ToggleLeft:yje,ToggleRight:vje,Toilet:bje,Tornado:_je,Torus:wje,Touchpad:Nje,TouchpadOff:jje,TowerControl:kje,ToyBrick:Sje,Tractor:Cje,TrafficCone:Aje,TrainFront:Tje,TrainFrontTunnel:Eje,TrainTrack:Mje,TramFront:pR,Trash:Pje,Trash2:Un,TreeDeciduous:Ije,TreePalm:gR,TreePine:nM,Trees:Lje,Trello:Rje,TrendingDown:lk,TrendingUp:mc,TrendingUpDown:Dje,Triangle:Fje,TriangleAlert:Gd,TriangleRight:Oje,Trophy:ql,Truck:nY,Turtle:zje,Tv:$je,TvMinimal:xR,TvMinimalPlay:Bje,Twitch:Uje,Twitter:qje,Type:Hje,TypeOutline:Vje,Umbrella:Wje,UmbrellaOff:Gje,Underline:pB,Undo:rM,Undo2:rY,UndoDot:Kje,UnfoldHorizontal:Yje,UnfoldVertical:Zje,Ungroup:Xje,University:yR,Unlink:Q8,Unlink2:Qje,Unplug:aY,Upload:gi,Usb:Jje,User:el,UserCheck:ck,UserCog:iY,UserMinus:gB,UserPen:e2e,UserPlus:Pl,UserRound:NR,UserRoundCheck:vR,UserRoundCog:bR,UserRoundMinus:_R,UserRoundPen:t2e,UserRoundPlus:wR,UserRoundSearch:s2e,UserRoundX:jR,UserSearch:n2e,UserX:r2e,Users:Xn,UsersRound:tb,Utensils:SR,UtensilsCrossed:kR,UtilityPole:a2e,Variable:xB,Vault:i2e,Vegan:o2e,VenetianMask:l2e,Vibrate:d2e,VibrateOff:c2e,Video:ia,VideoOff:u2e,Videotape:h2e,View:m2e,Voicemail:f2e,Volleyball:p2e,Volume:y2e,Volume1:g2e,Volume2:oY,VolumeOff:x2e,VolumeX:lY,Vote:v2e,Wallet:cY,WalletCards:b2e,WalletMinimal:CR,Wallpaper:_2e,Wand:w2e,WandSparkles:vf,Warehouse:j2e,WashingMachine:N2e,Watch:k2e,Waves:S2e,Waypoints:C2e,Webcam:A2e,Webhook:T2e,WebhookOff:E2e,Weight:M2e,Wheat:I2e,WheatOff:P2e,WholeWord:L2e,Wifi:z2e,WifiHigh:R2e,WifiLow:D2e,WifiOff:O2e,WifiZero:F2e,Wind:$2e,WindArrowDown:B2e,Wine:dY,WineOff:U2e,Workflow:uY,Worm:q2e,WrapText:V2e,Wrench:L5,X:mr,Youtube:H2e,Zap:ix,ZapOff:G2e,ZoomIn:aM,ZoomOut:yB},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 n3e=Object.freeze(Object.defineProperty({__proto__:null,AArrowDown:soe,AArrowDownIcon:soe,AArrowUp:noe,AArrowUpIcon:noe,ALargeSmall:roe,ALargeSmallIcon:roe,Accessibility:aoe,AccessibilityIcon:aoe,Activity:zp,ActivityIcon:zp,ActivitySquare:gL,ActivitySquareIcon:gL,AirVent:ioe,AirVentIcon:ioe,Airplay:ooe,AirplayIcon:ooe,AlarmCheck:jP,AlarmCheckIcon:jP,AlarmClock:coe,AlarmClockCheck:jP,AlarmClockCheckIcon:jP,AlarmClockIcon:coe,AlarmClockMinus:NP,AlarmClockMinusIcon:NP,AlarmClockOff:loe,AlarmClockOffIcon:loe,AlarmClockPlus:kP,AlarmClockPlusIcon:kP,AlarmMinus:NP,AlarmMinusIcon:NP,AlarmPlus:kP,AlarmPlusIcon:kP,AlarmSmoke:doe,AlarmSmokeIcon:doe,Album:uoe,AlbumIcon:uoe,AlertCircle:Ho,AlertCircleIcon:Ho,AlertOctagon:GN,AlertOctagonIcon:GN,AlertTriangle:Gd,AlertTriangleIcon:Gd,AlignCenter:T8,AlignCenterHorizontal:hoe,AlignCenterHorizontalIcon:hoe,AlignCenterIcon:T8,AlignCenterVertical:moe,AlignCenterVerticalIcon:moe,AlignEndHorizontal:foe,AlignEndHorizontalIcon:foe,AlignEndVertical:poe,AlignEndVerticalIcon:poe,AlignHorizontalDistributeCenter:goe,AlignHorizontalDistributeCenterIcon:goe,AlignHorizontalDistributeEnd:xoe,AlignHorizontalDistributeEndIcon:xoe,AlignHorizontalDistributeStart:yoe,AlignHorizontalDistributeStartIcon:yoe,AlignHorizontalJustifyCenter:voe,AlignHorizontalJustifyCenterIcon:voe,AlignHorizontalJustifyEnd:boe,AlignHorizontalJustifyEndIcon:boe,AlignHorizontalJustifyStart:_oe,AlignHorizontalJustifyStartIcon:_oe,AlignHorizontalSpaceAround:woe,AlignHorizontalSpaceAroundIcon:woe,AlignHorizontalSpaceBetween:joe,AlignHorizontalSpaceBetweenIcon:joe,AlignJustify:Noe,AlignJustifyIcon:Noe,AlignLeft:M8,AlignLeftIcon:M8,AlignRight:P8,AlignRightIcon:P8,AlignStartHorizontal:koe,AlignStartHorizontalIcon:koe,AlignStartVertical:Soe,AlignStartVerticalIcon:Soe,AlignVerticalDistributeCenter:Coe,AlignVerticalDistributeCenterIcon:Coe,AlignVerticalDistributeEnd:Aoe,AlignVerticalDistributeEndIcon:Aoe,AlignVerticalDistributeStart:Eoe,AlignVerticalDistributeStartIcon:Eoe,AlignVerticalJustifyCenter:Toe,AlignVerticalJustifyCenterIcon:Toe,AlignVerticalJustifyEnd:Moe,AlignVerticalJustifyEndIcon:Moe,AlignVerticalJustifyStart:Poe,AlignVerticalJustifyStartIcon:Poe,AlignVerticalSpaceAround:Ioe,AlignVerticalSpaceAroundIcon:Ioe,AlignVerticalSpaceBetween:Loe,AlignVerticalSpaceBetweenIcon:Loe,Ambulance:Roe,AmbulanceIcon:Roe,Ampersand:Doe,AmpersandIcon:Doe,Ampersands:Ooe,AmpersandsIcon:Ooe,Amphora:Foe,AmphoraIcon:Foe,Anchor:zoe,AnchorIcon:zoe,Angry:Boe,AngryIcon:Boe,Annoyed:$oe,AnnoyedIcon:$oe,Antenna:Uoe,AntennaIcon:Uoe,Anvil:qoe,AnvilIcon:qoe,Aperture:Voe,ApertureIcon:Voe,AppWindow:Goe,AppWindowIcon:Goe,AppWindowMac:Hoe,AppWindowMacIcon:Hoe,Apple:Woe,AppleIcon:Woe,Archive:kf,ArchiveIcon:kf,ArchiveRestore:OT,ArchiveRestoreIcon:OT,ArchiveX:Koe,ArchiveXIcon:Koe,AreaChart:zP,AreaChartIcon:zP,Armchair:Yoe,ArmchairIcon:Yoe,ArrowBigDown:Xoe,ArrowBigDownDash:Zoe,ArrowBigDownDashIcon:Zoe,ArrowBigDownIcon:Xoe,ArrowBigLeft:Joe,ArrowBigLeftDash:Qoe,ArrowBigLeftDashIcon:Qoe,ArrowBigLeftIcon:Joe,ArrowBigRight:tle,ArrowBigRightDash:ele,ArrowBigRightDashIcon:ele,ArrowBigRightIcon:tle,ArrowBigUp:nle,ArrowBigUpDash:sle,ArrowBigUpDashIcon:sle,ArrowBigUpIcon:nle,ArrowDown:nx,ArrowDown01:rle,ArrowDown01Icon:rle,ArrowDown10:ale,ArrowDown10Icon:ale,ArrowDownAZ:SP,ArrowDownAZIcon:SP,ArrowDownAz:SP,ArrowDownAzIcon:SP,ArrowDownCircle:XP,ArrowDownCircleIcon:XP,ArrowDownFromLine:ile,ArrowDownFromLineIcon:ile,ArrowDownIcon:nx,ArrowDownLeft:ole,ArrowDownLeftFromCircle:JP,ArrowDownLeftFromCircleIcon:JP,ArrowDownLeftFromSquare:_L,ArrowDownLeftFromSquareIcon:_L,ArrowDownLeftIcon:ole,ArrowDownLeftSquare:xL,ArrowDownLeftSquareIcon:xL,ArrowDownNarrowWide:lle,ArrowDownNarrowWideIcon:lle,ArrowDownRight:vK,ArrowDownRightFromCircle:eI,ArrowDownRightFromCircleIcon:eI,ArrowDownRightFromSquare:wL,ArrowDownRightFromSquareIcon:wL,ArrowDownRightIcon:vK,ArrowDownRightSquare:yL,ArrowDownRightSquareIcon:yL,ArrowDownSquare:vL,ArrowDownSquareIcon:vL,ArrowDownToDot:cle,ArrowDownToDotIcon:cle,ArrowDownToLine:dle,ArrowDownToLineIcon:dle,ArrowDownUp:ule,ArrowDownUpIcon:ule,ArrowDownWideNarrow:CP,ArrowDownWideNarrowIcon:CP,ArrowDownZA:AP,ArrowDownZAIcon:AP,ArrowDownZa:AP,ArrowDownZaIcon:AP,ArrowLeft:Ia,ArrowLeftCircle:QP,ArrowLeftCircleIcon:QP,ArrowLeftFromLine:hle,ArrowLeftFromLineIcon:hle,ArrowLeftIcon:Ia,ArrowLeftRight:bK,ArrowLeftRightIcon:bK,ArrowLeftSquare:bL,ArrowLeftSquareIcon:bL,ArrowLeftToLine:mle,ArrowLeftToLineIcon:mle,ArrowRight:xi,ArrowRightCircle:nI,ArrowRightCircleIcon:nI,ArrowRightFromLine:fle,ArrowRightFromLineIcon:fle,ArrowRightIcon:xi,ArrowRightLeft:N5,ArrowRightLeftIcon:N5,ArrowRightSquare:kL,ArrowRightSquareIcon:kL,ArrowRightToLine:ple,ArrowRightToLineIcon:ple,ArrowUp:ap,ArrowUp01:gle,ArrowUp01Icon:gle,ArrowUp10:xle,ArrowUp10Icon:xle,ArrowUpAZ:EP,ArrowUpAZIcon:EP,ArrowUpAz:EP,ArrowUpAzIcon:EP,ArrowUpCircle:rI,ArrowUpCircleIcon:rI,ArrowUpDown:Ix,ArrowUpDownIcon:Ix,ArrowUpFromDot:yle,ArrowUpFromDotIcon:yle,ArrowUpFromLine:vle,ArrowUpFromLineIcon:vle,ArrowUpIcon:ap,ArrowUpLeft:ble,ArrowUpLeftFromCircle:tI,ArrowUpLeftFromCircleIcon:tI,ArrowUpLeftFromSquare:jL,ArrowUpLeftFromSquareIcon:jL,ArrowUpLeftIcon:ble,ArrowUpLeftSquare:SL,ArrowUpLeftSquareIcon:SL,ArrowUpNarrowWide:TP,ArrowUpNarrowWideIcon:TP,ArrowUpRight:FT,ArrowUpRightFromCircle:sI,ArrowUpRightFromCircleIcon:sI,ArrowUpRightFromSquare:NL,ArrowUpRightFromSquareIcon:NL,ArrowUpRightIcon:FT,ArrowUpRightSquare:CL,ArrowUpRightSquareIcon:CL,ArrowUpSquare:AL,ArrowUpSquareIcon:AL,ArrowUpToLine:_le,ArrowUpToLineIcon:_le,ArrowUpWideNarrow:wle,ArrowUpWideNarrowIcon:wle,ArrowUpZA:MP,ArrowUpZAIcon:MP,ArrowUpZa:MP,ArrowUpZaIcon:MP,ArrowsUpFromLine:jle,ArrowsUpFromLineIcon:jle,Asterisk:Nle,AsteriskIcon:Nle,AsteriskSquare:EL,AsteriskSquareIcon:EL,AtSign:kle,AtSignIcon:kle,Atom:Sle,AtomIcon:Sle,AudioLines:Cle,AudioLinesIcon:Cle,AudioWaveform:Ale,AudioWaveformIcon:Ale,Award:oh,AwardIcon:oh,Axe:Ele,AxeIcon:Ele,Axis3D:PP,Axis3DIcon:PP,Axis3d:PP,Axis3dIcon:PP,Baby:Tle,BabyIcon:Tle,Backpack:Mle,BackpackIcon:Mle,Badge:Wle,BadgeAlert:Ple,BadgeAlertIcon:Ple,BadgeCent:Ile,BadgeCentIcon:Ile,BadgeCheck:IP,BadgeCheckIcon:IP,BadgeDollarSign:Lle,BadgeDollarSignIcon:Lle,BadgeEuro:Rle,BadgeEuroIcon:Rle,BadgeHelp:Dle,BadgeHelpIcon:Dle,BadgeIcon:Wle,BadgeIndianRupee:Ole,BadgeIndianRupeeIcon:Ole,BadgeInfo:Fle,BadgeInfoIcon:Fle,BadgeJapaneseYen:zle,BadgeJapaneseYenIcon:zle,BadgeMinus:Ble,BadgeMinusIcon:Ble,BadgePercent:$le,BadgePercentIcon:$le,BadgePlus:Ule,BadgePlusIcon:Ule,BadgePoundSterling:qle,BadgePoundSterlingIcon:qle,BadgeRussianRuble:Vle,BadgeRussianRubleIcon:Vle,BadgeSwissFranc:Hle,BadgeSwissFrancIcon:Hle,BadgeX:Gle,BadgeXIcon:Gle,BaggageClaim:Kle,BaggageClaimIcon:Kle,Ban:Fz,BanIcon:Fz,Banana:Yle,BananaIcon:Yle,Bandage:Zle,BandageIcon:Zle,Banknote:Xle,BanknoteIcon:Xle,BarChart:GP,BarChart2:WP,BarChart2Icon:WP,BarChart3:Ul,BarChart3Icon:Ul,BarChart4:VP,BarChart4Icon:VP,BarChartBig:qP,BarChartBigIcon:qP,BarChartHorizontal:$P,BarChartHorizontalBig:BP,BarChartHorizontalBigIcon:BP,BarChartHorizontalIcon:$P,BarChartIcon:GP,Barcode:Qle,BarcodeIcon:Qle,Baseline:Jle,BaselineIcon:Jle,Bath:p0,BathIcon:p0,Battery:ace,BatteryCharging:ece,BatteryChargingIcon:ece,BatteryFull:tce,BatteryFullIcon:tce,BatteryIcon:ace,BatteryLow:sce,BatteryLowIcon:sce,BatteryMedium:nce,BatteryMediumIcon:nce,BatteryWarning:rce,BatteryWarningIcon:rce,Beaker:_K,BeakerIcon:_K,Bean:oce,BeanIcon:oce,BeanOff:ice,BeanOffIcon:ice,Bed:Yw,BedDouble:f3,BedDoubleIcon:f3,BedIcon:Yw,BedSingle:lce,BedSingleIcon:lce,Beef:cce,BeefIcon:cce,Beer:uce,BeerIcon:uce,BeerOff:dce,BeerOffIcon:dce,Bell:Fx,BellDot:hce,BellDotIcon:hce,BellElectric:mce,BellElectricIcon:mce,BellIcon:Fx,BellMinus:fce,BellMinusIcon:fce,BellOff:k5,BellOffIcon:k5,BellPlus:pce,BellPlusIcon:pce,BellRing:p3,BellRingIcon:p3,BetweenHorizonalEnd:LP,BetweenHorizonalEndIcon:LP,BetweenHorizonalStart:RP,BetweenHorizonalStartIcon:RP,BetweenHorizontalEnd:LP,BetweenHorizontalEndIcon:LP,BetweenHorizontalStart:RP,BetweenHorizontalStartIcon:RP,BetweenVerticalEnd:gce,BetweenVerticalEndIcon:gce,BetweenVerticalStart:xce,BetweenVerticalStartIcon:xce,BicepsFlexed:yce,BicepsFlexedIcon:yce,Bike:vce,BikeIcon:vce,Binary:bce,BinaryIcon:bce,Binoculars:_ce,BinocularsIcon:_ce,Biohazard:wce,BiohazardIcon:wce,Bird:jce,BirdIcon:jce,Bitcoin:Nce,BitcoinIcon:Nce,Blend:kce,BlendIcon:kce,Blinds:Sce,BlindsIcon:Sce,Blocks:Cce,BlocksIcon:Cce,Bluetooth:Mce,BluetoothConnected:Ace,BluetoothConnectedIcon:Ace,BluetoothIcon:Mce,BluetoothOff:Ece,BluetoothOffIcon:Ece,BluetoothSearching:Tce,BluetoothSearchingIcon:Tce,Bold:zT,BoldIcon:zT,Bolt:Pce,BoltIcon:Pce,Bomb:Ice,BombIcon:Ice,Bone:Lce,BoneIcon:Lce,Book:sde,BookA:Rce,BookAIcon:Rce,BookAudio:Dce,BookAudioIcon:Dce,BookCheck:Oce,BookCheckIcon:Oce,BookCopy:Fce,BookCopyIcon:Fce,BookDashed:DP,BookDashedIcon:DP,BookDown:zce,BookDownIcon:zce,BookHeadphones:Bce,BookHeadphonesIcon:Bce,BookHeart:$ce,BookHeartIcon:$ce,BookIcon:sde,BookImage:Uce,BookImageIcon:Uce,BookKey:qce,BookKeyIcon:qce,BookLock:Vce,BookLockIcon:Vce,BookMarked:Hce,BookMarkedIcon:Hce,BookMinus:Gce,BookMinusIcon:Gce,BookOpen:wg,BookOpenCheck:Wce,BookOpenCheckIcon:Wce,BookOpenIcon:wg,BookOpenText:Kce,BookOpenTextIcon:Kce,BookPlus:Yce,BookPlusIcon:Yce,BookTemplate:DP,BookTemplateIcon:DP,BookText:Zce,BookTextIcon:Zce,BookType:Xce,BookTypeIcon:Xce,BookUp:Jce,BookUp2:Qce,BookUp2Icon:Qce,BookUpIcon:Jce,BookUser:ede,BookUserIcon:ede,BookX:tde,BookXIcon:tde,Bookmark:jy,BookmarkCheck:nde,BookmarkCheckIcon:nde,BookmarkIcon:jy,BookmarkMinus:rde,BookmarkMinusIcon:rde,BookmarkPlus:BT,BookmarkPlusIcon:BT,BookmarkX:ade,BookmarkXIcon:ade,BoomBox:ide,BoomBoxIcon:ide,Bot:S5,BotIcon:S5,BotMessageSquare:ode,BotMessageSquareIcon:ode,BotOff:lde,BotOffIcon:lde,Box:wK,BoxIcon:wK,BoxSelect:zL,BoxSelectIcon:zL,Boxes:cde,BoxesIcon:cde,Braces:OP,BracesIcon:OP,Brackets:dde,BracketsIcon:dde,Brain:jK,BrainCircuit:ude,BrainCircuitIcon:ude,BrainCog:hde,BrainCogIcon:hde,BrainIcon:jK,BrickWall:mde,BrickWallIcon:mde,Briefcase:zx,BriefcaseBusiness:fde,BriefcaseBusinessIcon:fde,BriefcaseConveyorBelt:pde,BriefcaseConveyorBeltIcon:pde,BriefcaseIcon:zx,BriefcaseMedical:gde,BriefcaseMedicalIcon:gde,BringToFront:xde,BringToFrontIcon:xde,Brush:yde,BrushIcon:yde,Bug:_de,BugIcon:_de,BugOff:vde,BugOffIcon:vde,BugPlay:bde,BugPlayIcon:bde,Building:I8,Building2:Gi,Building2Icon:Gi,BuildingIcon:I8,Bus:jde,BusFront:wde,BusFrontIcon:wde,BusIcon:jde,Cable:kde,CableCar:Nde,CableCarIcon:Nde,CableIcon:kde,Cake:ip,CakeIcon:ip,CakeSlice:Sde,CakeSliceIcon:Sde,Calculator:C5,CalculatorIcon:C5,Calendar:ha,Calendar1:Cde,Calendar1Icon:Cde,CalendarArrowDown:Ade,CalendarArrowDownIcon:Ade,CalendarArrowUp:Ede,CalendarArrowUpIcon:Ede,CalendarCheck:fb,CalendarCheck2:Tde,CalendarCheck2Icon:Tde,CalendarCheckIcon:fb,CalendarClock:wm,CalendarClockIcon:wm,CalendarCog:Mde,CalendarCogIcon:Mde,CalendarDays:fd,CalendarDaysIcon:fd,CalendarFold:Pde,CalendarFoldIcon:Pde,CalendarHeart:nk,CalendarHeartIcon:nk,CalendarIcon:ha,CalendarMinus:Lde,CalendarMinus2:Ide,CalendarMinus2Icon:Ide,CalendarMinusIcon:Lde,CalendarOff:zz,CalendarOffIcon:zz,CalendarPlus:i1,CalendarPlus2:Rde,CalendarPlus2Icon:Rde,CalendarPlusIcon:i1,CalendarRange:Dde,CalendarRangeIcon:Dde,CalendarSearch:Ode,CalendarSearchIcon:Ode,CalendarSync:Fde,CalendarSyncIcon:Fde,CalendarX:NK,CalendarX2:zde,CalendarX2Icon:zde,CalendarXIcon:NK,Camera:g0,CameraIcon:g0,CameraOff:Bde,CameraOffIcon:Bde,CandlestickChart:UP,CandlestickChartIcon:UP,Candy:qde,CandyCane:$de,CandyCaneIcon:$de,CandyIcon:qde,CandyOff:Ude,CandyOffIcon:Ude,Cannabis:Vde,CannabisIcon:Vde,Captions:FP,CaptionsIcon:FP,CaptionsOff:Hde,CaptionsOffIcon:Hde,Car:Kde,CarFront:Gde,CarFrontIcon:Gde,CarIcon:Kde,CarTaxiFront:Wde,CarTaxiFrontIcon:Wde,Caravan:Yde,CaravanIcon:Yde,Carrot:Zde,CarrotIcon:Zde,CaseLower:Xde,CaseLowerIcon:Xde,CaseSensitive:Qde,CaseSensitiveIcon:Qde,CaseUpper:Jde,CaseUpperIcon:Jde,CassetteTape:eue,CassetteTapeIcon:eue,Cast:tue,CastIcon:tue,Castle:sue,CastleIcon:sue,Cat:nue,CatIcon:nue,Cctv:rue,CctvIcon:rue,ChartArea:zP,ChartAreaIcon:zP,ChartBar:$P,ChartBarBig:BP,ChartBarBigIcon:BP,ChartBarDecreasing:aue,ChartBarDecreasingIcon:aue,ChartBarIcon:$P,ChartBarIncreasing:iue,ChartBarIncreasingIcon:iue,ChartBarStacked:oue,ChartBarStackedIcon:oue,ChartCandlestick:UP,ChartCandlestickIcon:UP,ChartColumn:Ul,ChartColumnBig:qP,ChartColumnBigIcon:qP,ChartColumnDecreasing:lue,ChartColumnDecreasingIcon:lue,ChartColumnIcon:Ul,ChartColumnIncreasing:VP,ChartColumnIncreasingIcon:VP,ChartColumnStacked:cue,ChartColumnStackedIcon:cue,ChartGantt:due,ChartGanttIcon:due,ChartLine:HP,ChartLineIcon:HP,ChartNetwork:uue,ChartNetworkIcon:uue,ChartNoAxesColumn:WP,ChartNoAxesColumnDecreasing:hue,ChartNoAxesColumnDecreasingIcon:hue,ChartNoAxesColumnIcon:WP,ChartNoAxesColumnIncreasing:GP,ChartNoAxesColumnIncreasingIcon:GP,ChartNoAxesCombined:mue,ChartNoAxesCombinedIcon:mue,ChartNoAxesGantt:KP,ChartNoAxesGanttIcon:KP,ChartPie:YP,ChartPieIcon:YP,ChartScatter:ZP,ChartScatterIcon:ZP,ChartSpline:fue,ChartSplineIcon:fue,Check:ma,CheckCheck:L8,CheckCheckIcon:L8,CheckCircle:nl,CheckCircle2:Gr,CheckCircle2Icon:Gr,CheckCircleIcon:nl,CheckIcon:ma,CheckSquare:r5,CheckSquare2:ML,CheckSquare2Icon:ML,CheckSquareIcon:r5,ChefHat:pue,ChefHatIcon:pue,Cherry:gue,CherryIcon:gue,ChevronDown:Go,ChevronDownCircle:aI,ChevronDownCircleIcon:aI,ChevronDownIcon:Go,ChevronDownSquare:PL,ChevronDownSquareIcon:PL,ChevronFirst:xue,ChevronFirstIcon:xue,ChevronLast:yue,ChevronLastIcon:yue,ChevronLeft:Ld,ChevronLeftCircle:iI,ChevronLeftCircleIcon:iI,ChevronLeftIcon:Ld,ChevronLeftSquare:IL,ChevronLeftSquareIcon:IL,ChevronRight:fi,ChevronRightCircle:oI,ChevronRightCircleIcon:oI,ChevronRightIcon:fi,ChevronRightSquare:LL,ChevronRightSquareIcon:LL,ChevronUp:Ny,ChevronUpCircle:lI,ChevronUpCircleIcon:lI,ChevronUpIcon:Ny,ChevronUpSquare:RL,ChevronUpSquareIcon:RL,ChevronsDown:bue,ChevronsDownIcon:bue,ChevronsDownUp:vue,ChevronsDownUpIcon:vue,ChevronsLeft:jue,ChevronsLeftIcon:jue,ChevronsLeftRight:wue,ChevronsLeftRightEllipsis:_ue,ChevronsLeftRightEllipsisIcon:_ue,ChevronsLeftRightIcon:wue,ChevronsRight:kue,ChevronsRightIcon:kue,ChevronsRightLeft:Nue,ChevronsRightLeftIcon:Nue,ChevronsUp:Sue,ChevronsUpDown:v_,ChevronsUpDownIcon:v_,ChevronsUpIcon:Sue,Chrome:R8,ChromeIcon:R8,Church:Cue,ChurchIcon:Cue,Cigarette:Eue,CigaretteIcon:Eue,CigaretteOff:Aue,CigaretteOffIcon:Aue,Circle:rx,CircleAlert:Ho,CircleAlertIcon:Ho,CircleArrowDown:XP,CircleArrowDownIcon:XP,CircleArrowLeft:QP,CircleArrowLeftIcon:QP,CircleArrowOutDownLeft:JP,CircleArrowOutDownLeftIcon:JP,CircleArrowOutDownRight:eI,CircleArrowOutDownRightIcon:eI,CircleArrowOutUpLeft:tI,CircleArrowOutUpLeftIcon:tI,CircleArrowOutUpRight:sI,CircleArrowOutUpRightIcon:sI,CircleArrowRight:nI,CircleArrowRightIcon:nI,CircleArrowUp:rI,CircleArrowUpIcon:rI,CircleCheck:Gr,CircleCheckBig:nl,CircleCheckBigIcon:nl,CircleCheckIcon:Gr,CircleChevronDown:aI,CircleChevronDownIcon:aI,CircleChevronLeft:iI,CircleChevronLeftIcon:iI,CircleChevronRight:oI,CircleChevronRightIcon:oI,CircleChevronUp:lI,CircleChevronUpIcon:lI,CircleDashed:Tue,CircleDashedIcon:Tue,CircleDivide:cI,CircleDivideIcon:cI,CircleDollarSign:Mue,CircleDollarSignIcon:Mue,CircleDot:Iue,CircleDotDashed:Pue,CircleDotDashedIcon:Pue,CircleDotIcon:Iue,CircleEllipsis:Lue,CircleEllipsisIcon:Lue,CircleEqual:Rue,CircleEqualIcon:Rue,CircleFadingArrowUp:Due,CircleFadingArrowUpIcon:Due,CircleFadingPlus:Oue,CircleFadingPlusIcon:Oue,CircleGauge:dI,CircleGaugeIcon:dI,CircleHelp:_C,CircleHelpIcon:_C,CircleIcon:rx,CircleMinus:uI,CircleMinusIcon:uI,CircleOff:Fue,CircleOffIcon:Fue,CircleParking:mI,CircleParkingIcon:mI,CircleParkingOff:hI,CircleParkingOffIcon:hI,CirclePause:fI,CirclePauseIcon:fI,CirclePercent:pI,CirclePercentIcon:pI,CirclePlay:mm,CirclePlayIcon:mm,CirclePlus:gI,CirclePlusIcon:gI,CirclePower:xI,CirclePowerIcon:xI,CircleSlash:zue,CircleSlash2:yI,CircleSlash2Icon:yI,CircleSlashIcon:zue,CircleSlashed:yI,CircleSlashedIcon:yI,CircleStop:vI,CircleStopIcon:vI,CircleUser:_I,CircleUserIcon:_I,CircleUserRound:bI,CircleUserRoundIcon:bI,CircleX:ju,CircleXIcon:ju,CircuitBoard:Bue,CircuitBoardIcon:Bue,Citrus:$ue,CitrusIcon:$ue,Clapperboard:Bz,ClapperboardIcon:Bz,Clipboard:Kue,ClipboardCheck:A5,ClipboardCheckIcon:A5,ClipboardCopy:Uue,ClipboardCopyIcon:Uue,ClipboardEdit:jI,ClipboardEditIcon:jI,ClipboardIcon:Kue,ClipboardList:lv,ClipboardListIcon:lv,ClipboardMinus:que,ClipboardMinusIcon:que,ClipboardPaste:Vue,ClipboardPasteIcon:Vue,ClipboardPen:jI,ClipboardPenIcon:jI,ClipboardPenLine:wI,ClipboardPenLineIcon:wI,ClipboardPlus:Hue,ClipboardPlusIcon:Hue,ClipboardSignature:wI,ClipboardSignatureIcon:wI,ClipboardType:Gue,ClipboardTypeIcon:Gue,ClipboardX:Wue,ClipboardXIcon:Wue,Clock:sa,Clock1:Yue,Clock10:Zue,Clock10Icon:Zue,Clock11:Xue,Clock11Icon:Xue,Clock12:Que,Clock12Icon:Que,Clock1Icon:Yue,Clock2:Jue,Clock2Icon:Jue,Clock3:kK,Clock3Icon:kK,Clock4:ehe,Clock4Icon:ehe,Clock5:the,Clock5Icon:the,Clock6:she,Clock6Icon:she,Clock7:nhe,Clock7Icon:nhe,Clock8:rhe,Clock8Icon:rhe,Clock9:ahe,Clock9Icon:ahe,ClockAlert:ihe,ClockAlertIcon:ihe,ClockArrowDown:ohe,ClockArrowDownIcon:ohe,ClockArrowUp:lhe,ClockArrowUpIcon:lhe,ClockIcon:sa,Cloud:jhe,CloudAlert:che,CloudAlertIcon:che,CloudCog:dhe,CloudCogIcon:dhe,CloudDownload:NI,CloudDownloadIcon:NI,CloudDrizzle:uhe,CloudDrizzleIcon:uhe,CloudFog:hhe,CloudFogIcon:hhe,CloudHail:mhe,CloudHailIcon:mhe,CloudIcon:jhe,CloudLightning:fhe,CloudLightningIcon:fhe,CloudMoon:ghe,CloudMoonIcon:ghe,CloudMoonRain:phe,CloudMoonRainIcon:phe,CloudOff:xhe,CloudOffIcon:xhe,CloudRain:vhe,CloudRainIcon:vhe,CloudRainWind:yhe,CloudRainWindIcon:yhe,CloudSnow:bhe,CloudSnowIcon:bhe,CloudSun:whe,CloudSunIcon:whe,CloudSunRain:_he,CloudSunRainIcon:_he,CloudUpload:kI,CloudUploadIcon:kI,Cloudy:Nhe,CloudyIcon:Nhe,Clover:n3,CloverIcon:n3,Club:khe,ClubIcon:khe,Code:$T,Code2:wC,Code2Icon:wC,CodeIcon:$T,CodeSquare:DL,CodeSquareIcon:DL,CodeXml:wC,CodeXmlIcon:wC,Codepen:She,CodepenIcon:She,Codesandbox:Che,CodesandboxIcon:Che,Coffee:b_,CoffeeIcon:b_,Cog:Ahe,CogIcon:Ahe,Coins:SK,CoinsIcon:SK,Columns:SI,Columns2:SI,Columns2Icon:SI,Columns3:dE,Columns3Icon:dE,Columns4:Ehe,Columns4Icon:Ehe,ColumnsIcon:SI,Combine:The,CombineIcon:The,Command:Mhe,CommandIcon:Mhe,Compass:D8,CompassIcon:D8,Component:Phe,ComponentIcon:Phe,Computer:Ihe,ComputerIcon:Ihe,ConciergeBell:Lhe,ConciergeBellIcon:Lhe,Cone:Rhe,ConeIcon:Rhe,Construction:Dhe,ConstructionIcon:Dhe,Contact:O8,Contact2:CI,Contact2Icon:CI,ContactIcon:O8,ContactRound:CI,ContactRoundIcon:CI,Container:Ohe,ContainerIcon:Ohe,Contrast:Fhe,ContrastIcon:Fhe,Cookie:zhe,CookieIcon:zhe,CookingPot:Bhe,CookingPotIcon:Bhe,Copy:Da,CopyCheck:$he,CopyCheckIcon:$he,CopyIcon:Da,CopyMinus:Uhe,CopyMinusIcon:Uhe,CopyPlus:qhe,CopyPlusIcon:qhe,CopySlash:Vhe,CopySlashIcon:Vhe,CopyX:Hhe,CopyXIcon:Hhe,Copyleft:Ghe,CopyleftIcon:Ghe,Copyright:Whe,CopyrightIcon:Whe,CornerDownLeft:Khe,CornerDownLeftIcon:Khe,CornerDownRight:Yhe,CornerDownRightIcon:Yhe,CornerLeftDown:Zhe,CornerLeftDownIcon:Zhe,CornerLeftUp:Xhe,CornerLeftUpIcon:Xhe,CornerRightDown:Qhe,CornerRightDownIcon:Qhe,CornerRightUp:Jhe,CornerRightUpIcon:Jhe,CornerUpLeft:eme,CornerUpLeftIcon:eme,CornerUpRight:tme,CornerUpRightIcon:tme,Cpu:sme,CpuIcon:sme,CreativeCommons:nme,CreativeCommonsIcon:nme,CreditCard:cv,CreditCardIcon:cv,Croissant:rme,CroissantIcon:rme,Crop:ame,CropIcon:ame,Cross:ime,CrossIcon:ime,Crosshair:ome,CrosshairIcon:ome,Crown:ky,CrownIcon:ky,Cuboid:lme,CuboidIcon:lme,CupSoda:cme,CupSodaIcon:cme,CurlyBraces:OP,CurlyBracesIcon:OP,Currency:dme,CurrencyIcon:dme,Cylinder:ume,CylinderIcon:ume,Dam:hme,DamIcon:hme,Database:CK,DatabaseBackup:mme,DatabaseBackupIcon:mme,DatabaseIcon:CK,DatabaseZap:fme,DatabaseZapIcon:fme,Delete:pme,DeleteIcon:pme,Dessert:gme,DessertIcon:gme,Diameter:xme,DiameterIcon:xme,Diamond:bme,DiamondIcon:bme,DiamondMinus:yme,DiamondMinusIcon:yme,DiamondPercent:AI,DiamondPercentIcon:AI,DiamondPlus:vme,DiamondPlusIcon:vme,Dice1:_me,Dice1Icon:_me,Dice2:wme,Dice2Icon:wme,Dice3:jme,Dice3Icon:jme,Dice4:Nme,Dice4Icon:Nme,Dice5:kme,Dice5Icon:kme,Dice6:Sme,Dice6Icon:Sme,Dices:Cme,DicesIcon:Cme,Diff:Ame,DiffIcon:Ame,Disc:Pme,Disc2:Eme,Disc2Icon:Eme,Disc3:Tme,Disc3Icon:Tme,DiscAlbum:Mme,DiscAlbumIcon:Mme,DiscIcon:Pme,Divide:Ime,DivideCircle:cI,DivideCircleIcon:cI,DivideIcon:Ime,DivideSquare:BL,DivideSquareIcon:BL,Dna:Rme,DnaIcon:Rme,DnaOff:Lme,DnaOffIcon:Lme,Dock:Dme,DockIcon:Dme,Dog:Ome,DogIcon:Ome,DollarSign:Su,DollarSignIcon:Su,Donut:Fme,DonutIcon:Fme,DoorClosed:zme,DoorClosedIcon:zme,DoorOpen:x2,DoorOpenIcon:x2,Dot:Bme,DotIcon:Bme,DotSquare:$L,DotSquareIcon:$L,Download:ji,DownloadCloud:NI,DownloadCloudIcon:NI,DownloadIcon:ji,DraftingCompass:$me,DraftingCompassIcon:$me,Drama:Ume,DramaIcon:Ume,Dribbble:qme,DribbbleIcon:qme,Drill:Vme,DrillIcon:Vme,Droplet:Hme,DropletIcon:Hme,Droplets:pb,DropletsIcon:pb,Drum:Gme,DrumIcon:Gme,Drumstick:Wme,DrumstickIcon:Wme,Dumbbell:Kme,DumbbellIcon:Kme,Ear:Zme,EarIcon:Zme,EarOff:Yme,EarOffIcon:Yme,Earth:EI,EarthIcon:EI,EarthLock:Xme,EarthLockIcon:Xme,Eclipse:Qme,EclipseIcon:Qme,Edit:Cp,Edit2:s2,Edit2Icon:s2,Edit3:WN,Edit3Icon:WN,EditIcon:Cp,Egg:$z,EggFried:Jme,EggFriedIcon:Jme,EggIcon:$z,EggOff:efe,EggOffIcon:efe,Ellipsis:u0,EllipsisIcon:u0,EllipsisVertical:Z0,EllipsisVerticalIcon:Z0,Equal:nfe,EqualApproximately:tfe,EqualApproximatelyIcon:tfe,EqualIcon:nfe,EqualNot:sfe,EqualNotIcon:sfe,EqualSquare:UL,EqualSquareIcon:UL,Eraser:rfe,EraserIcon:rfe,EthernetPort:afe,EthernetPortIcon:afe,Euro:ife,EuroIcon:ife,Expand:ofe,ExpandIcon:ofe,ExternalLink:Ir,ExternalLinkIcon:Ir,Eye:ba,EyeClosed:lfe,EyeClosedIcon:lfe,EyeIcon:ba,EyeOff:x0,EyeOffIcon:x0,Facebook:ax,FacebookIcon:ax,Factory:cfe,FactoryIcon:cfe,Fan:dfe,FanIcon:dfe,FastForward:ufe,FastForwardIcon:ufe,Feather:hfe,FeatherIcon:hfe,Fence:mfe,FenceIcon:mfe,FerrisWheel:ffe,FerrisWheelIcon:ffe,Figma:pfe,FigmaIcon:pfe,File:Uz,FileArchive:gfe,FileArchiveIcon:gfe,FileAudio:yfe,FileAudio2:xfe,FileAudio2Icon:xfe,FileAudioIcon:yfe,FileAxis3D:TI,FileAxis3DIcon:TI,FileAxis3d:TI,FileAxis3dIcon:TI,FileBadge:bfe,FileBadge2:vfe,FileBadge2Icon:vfe,FileBadgeIcon:bfe,FileBarChart:MI,FileBarChart2:PI,FileBarChart2Icon:PI,FileBarChartIcon:MI,FileBox:_fe,FileBoxIcon:_fe,FileChartColumn:PI,FileChartColumnIcon:PI,FileChartColumnIncreasing:MI,FileChartColumnIncreasingIcon:MI,FileChartLine:II,FileChartLineIcon:II,FileChartPie:LI,FileChartPieIcon:LI,FileCheck:AK,FileCheck2:wfe,FileCheck2Icon:wfe,FileCheckIcon:AK,FileClock:jfe,FileClockIcon:jfe,FileCode:kfe,FileCode2:Nfe,FileCode2Icon:Nfe,FileCodeIcon:kfe,FileCog:RI,FileCog2:RI,FileCog2Icon:RI,FileCogIcon:RI,FileDiff:Sfe,FileDiffIcon:Sfe,FileDigit:Cfe,FileDigitIcon:Cfe,FileDown:y2,FileDownIcon:y2,FileEdit:DI,FileEditIcon:DI,FileHeart:Afe,FileHeartIcon:Afe,FileIcon:Uz,FileImage:UT,FileImageIcon:UT,FileInput:Efe,FileInputIcon:Efe,FileJson:Mfe,FileJson2:Tfe,FileJson2Icon:Tfe,FileJsonIcon:Mfe,FileKey:Ife,FileKey2:Pfe,FileKey2Icon:Pfe,FileKeyIcon:Ife,FileLineChart:II,FileLineChartIcon:II,FileLock:Rfe,FileLock2:Lfe,FileLock2Icon:Lfe,FileLockIcon:Rfe,FileMinus:Ofe,FileMinus2:Dfe,FileMinus2Icon:Dfe,FileMinusIcon:Ofe,FileMusic:Ffe,FileMusicIcon:Ffe,FileOutput:zfe,FileOutputIcon:zfe,FilePen:DI,FilePenIcon:DI,FilePenLine:uE,FilePenLineIcon:uE,FilePieChart:LI,FilePieChartIcon:LI,FilePlus:$fe,FilePlus2:Bfe,FilePlus2Icon:Bfe,FilePlusIcon:$fe,FileQuestion:Ufe,FileQuestionIcon:Ufe,FileScan:qfe,FileScanIcon:qfe,FileSearch:Hfe,FileSearch2:Vfe,FileSearch2Icon:Vfe,FileSearchIcon:Hfe,FileSignature:uE,FileSignatureIcon:uE,FileSliders:Gfe,FileSlidersIcon:Gfe,FileSpreadsheet:rk,FileSpreadsheetIcon:rk,FileStack:EK,FileStackIcon:EK,FileSymlink:Wfe,FileSymlinkIcon:Wfe,FileTerminal:Kfe,FileTerminalIcon:Kfe,FileText:ea,FileTextIcon:ea,FileType:Zfe,FileType2:Yfe,FileType2Icon:Yfe,FileTypeIcon:Zfe,FileUp:Xfe,FileUpIcon:Xfe,FileUser:Qfe,FileUserIcon:Qfe,FileVideo:TK,FileVideo2:Jfe,FileVideo2Icon:Jfe,FileVideoIcon:TK,FileVolume:tpe,FileVolume2:epe,FileVolume2Icon:epe,FileVolumeIcon:tpe,FileWarning:spe,FileWarningIcon:spe,FileX:rpe,FileX2:npe,FileX2Icon:npe,FileXIcon:rpe,Files:ape,FilesIcon:ape,Film:em,FilmIcon:em,Filter:v2,FilterIcon:v2,FilterX:ipe,FilterXIcon:ipe,Fingerprint:ope,FingerprintIcon:ope,FireExtinguisher:lpe,FireExtinguisherIcon:lpe,Fish:upe,FishIcon:upe,FishOff:cpe,FishOffIcon:cpe,FishSymbol:dpe,FishSymbolIcon:dpe,Flag:g3,FlagIcon:g3,FlagOff:hpe,FlagOffIcon:hpe,FlagTriangleLeft:mpe,FlagTriangleLeftIcon:mpe,FlagTriangleRight:fpe,FlagTriangleRightIcon:fpe,Flame:iu,FlameIcon:iu,FlameKindling:ppe,FlameKindlingIcon:ppe,Flashlight:xpe,FlashlightIcon:xpe,FlashlightOff:gpe,FlashlightOffIcon:gpe,FlaskConical:qT,FlaskConicalIcon:qT,FlaskConicalOff:ype,FlaskConicalOffIcon:ype,FlaskRound:vpe,FlaskRoundIcon:vpe,FlipHorizontal:MK,FlipHorizontal2:bpe,FlipHorizontal2Icon:bpe,FlipHorizontalIcon:MK,FlipVertical:wpe,FlipVertical2:_pe,FlipVertical2Icon:_pe,FlipVerticalIcon:wpe,Flower:jpe,Flower2:QN,Flower2Icon:QN,FlowerIcon:jpe,Focus:Npe,FocusIcon:Npe,FoldHorizontal:kpe,FoldHorizontalIcon:kpe,FoldVertical:Spe,FoldVerticalIcon:Spe,Folder:Jpe,FolderArchive:Cpe,FolderArchiveIcon:Cpe,FolderCheck:Ape,FolderCheckIcon:Ape,FolderClock:Epe,FolderClockIcon:Epe,FolderClosed:Tpe,FolderClosedIcon:Tpe,FolderCode:Mpe,FolderCodeIcon:Mpe,FolderCog:OI,FolderCog2:OI,FolderCog2Icon:OI,FolderCogIcon:OI,FolderDot:Ppe,FolderDotIcon:Ppe,FolderDown:Ipe,FolderDownIcon:Ipe,FolderEdit:FI,FolderEditIcon:FI,FolderGit:Rpe,FolderGit2:Lpe,FolderGit2Icon:Lpe,FolderGitIcon:Rpe,FolderHeart:Dpe,FolderHeartIcon:Dpe,FolderIcon:Jpe,FolderInput:Ope,FolderInputIcon:Ope,FolderKanban:Fpe,FolderKanbanIcon:Fpe,FolderKey:zpe,FolderKeyIcon:zpe,FolderLock:Bpe,FolderLockIcon:Bpe,FolderMinus:$pe,FolderMinusIcon:$pe,FolderOpen:d1,FolderOpenDot:Upe,FolderOpenDotIcon:Upe,FolderOpenIcon:d1,FolderOutput:qpe,FolderOutputIcon:qpe,FolderPen:FI,FolderPenIcon:FI,FolderPlus:Vpe,FolderPlusIcon:Vpe,FolderRoot:Hpe,FolderRootIcon:Hpe,FolderSearch:Wpe,FolderSearch2:Gpe,FolderSearch2Icon:Gpe,FolderSearchIcon:Wpe,FolderSymlink:Kpe,FolderSymlinkIcon:Kpe,FolderSync:Ype,FolderSyncIcon:Ype,FolderTree:Zpe,FolderTreeIcon:Zpe,FolderUp:Xpe,FolderUpIcon:Xpe,FolderX:Qpe,FolderXIcon:Qpe,Folders:ege,FoldersIcon:ege,Footprints:tge,FootprintsIcon:tge,ForkKnife:SR,ForkKnifeCrossed:kR,ForkKnifeCrossedIcon:kR,ForkKnifeIcon:SR,Forklift:sge,ForkliftIcon:sge,FormInput:lL,FormInputIcon:lL,Forward:nge,ForwardIcon:nge,Frame:rge,FrameIcon:rge,Framer:age,FramerIcon:age,Frown:ige,FrownIcon:ige,Fuel:oge,FuelIcon:oge,Fullscreen:lge,FullscreenIcon:lge,FunctionSquare:qL,FunctionSquareIcon:qL,GalleryHorizontal:dge,GalleryHorizontalEnd:cge,GalleryHorizontalEndIcon:cge,GalleryHorizontalIcon:dge,GalleryThumbnails:uge,GalleryThumbnailsIcon:uge,GalleryVertical:mge,GalleryVerticalEnd:hge,GalleryVerticalEndIcon:hge,GalleryVerticalIcon:mge,Gamepad:pge,Gamepad2:fge,Gamepad2Icon:fge,GamepadIcon:pge,GanttChart:KP,GanttChartIcon:KP,GanttChartSquare:vS,GanttChartSquareIcon:vS,Gauge:gge,GaugeCircle:dI,GaugeCircleIcon:dI,GaugeIcon:gge,Gavel:xge,GavelIcon:xge,Gem:yge,GemIcon:yge,Ghost:F8,GhostIcon:F8,Gift:Zo,GiftIcon:Zo,GitBranch:bge,GitBranchIcon:bge,GitBranchPlus:vge,GitBranchPlusIcon:vge,GitCommit:zI,GitCommitHorizontal:zI,GitCommitHorizontalIcon:zI,GitCommitIcon:zI,GitCommitVertical:_ge,GitCommitVerticalIcon:_ge,GitCompare:jge,GitCompareArrows:wge,GitCompareArrowsIcon:wge,GitCompareIcon:jge,GitFork:Nge,GitForkIcon:Nge,GitGraph:kge,GitGraphIcon:kge,GitMerge:Sge,GitMergeIcon:Sge,GitPullRequest:Pge,GitPullRequestArrow:Cge,GitPullRequestArrowIcon:Cge,GitPullRequestClosed:Age,GitPullRequestClosedIcon:Age,GitPullRequestCreate:Tge,GitPullRequestCreateArrow:Ege,GitPullRequestCreateArrowIcon:Ege,GitPullRequestCreateIcon:Tge,GitPullRequestDraft:Mge,GitPullRequestDraftIcon:Mge,GitPullRequestIcon:Pge,Github:Ige,GithubIcon:Ige,Gitlab:Lge,GitlabIcon:Lge,GlassWater:Rge,GlassWaterIcon:Rge,Glasses:Dge,GlassesIcon:Dge,Globe:kc,Globe2:EI,Globe2Icon:EI,GlobeIcon:kc,GlobeLock:Oge,GlobeLockIcon:Oge,Goal:Fge,GoalIcon:Fge,Grab:zge,GrabIcon:zge,GraduationCap:Bm,GraduationCapIcon:Bm,Grape:Bge,GrapeIcon:Bge,Grid:Tw,Grid2X2:$I,Grid2X2Icon:$I,Grid2X2Plus:BI,Grid2X2PlusIcon:BI,Grid2x2:$I,Grid2x2Check:$ge,Grid2x2CheckIcon:$ge,Grid2x2Icon:$I,Grid2x2Plus:BI,Grid2x2PlusIcon:BI,Grid2x2X:Uge,Grid2x2XIcon:Uge,Grid3X3:Tw,Grid3X3Icon:Tw,Grid3x3:Tw,Grid3x3Icon:Tw,GridIcon:Tw,Grip:Vge,GripHorizontal:qge,GripHorizontalIcon:qge,GripIcon:Vge,GripVertical:Bp,GripVerticalIcon:Bp,Group:Hge,GroupIcon:Hge,Guitar:Gge,GuitarIcon:Gge,Ham:Wge,HamIcon:Wge,Hammer:PK,HammerIcon:PK,Hand:qz,HandCoins:Kge,HandCoinsIcon:Kge,HandHeart:z8,HandHeartIcon:z8,HandHelping:n5,HandHelpingIcon:n5,HandIcon:qz,HandMetal:Yge,HandMetalIcon:Yge,HandPlatter:Zge,HandPlatterIcon:Zge,Handshake:E5,HandshakeIcon:E5,HardDrive:IK,HardDriveDownload:Xge,HardDriveDownloadIcon:Xge,HardDriveIcon:IK,HardDriveUpload:Qge,HardDriveUploadIcon:Qge,HardHat:Jge,HardHatIcon:Jge,Hash:VT,HashIcon:VT,Haze:exe,HazeIcon:exe,HdmiPort:txe,HdmiPortIcon:txe,Heading:axe,Heading1:Vz,Heading1Icon:Vz,Heading2:Hz,Heading2Icon:Hz,Heading3:LK,Heading3Icon:LK,Heading4:sxe,Heading4Icon:sxe,Heading5:nxe,Heading5Icon:nxe,Heading6:rxe,Heading6Icon:rxe,HeadingIcon:axe,HeadphoneOff:ixe,HeadphoneOffIcon:ixe,Headphones:oxe,HeadphonesIcon:oxe,Headset:lxe,HeadsetIcon:lxe,Heart:Bo,HeartCrack:cxe,HeartCrackIcon:cxe,HeartHandshake:B8,HeartHandshakeIcon:B8,HeartIcon:Bo,HeartOff:dxe,HeartOffIcon:dxe,HeartPulse:uxe,HeartPulseIcon:uxe,Heater:hxe,HeaterIcon:hxe,HelpCircle:_C,HelpCircleIcon:_C,HelpingHand:n5,HelpingHandIcon:n5,Hexagon:mxe,HexagonIcon:mxe,Highlighter:fxe,HighlighterIcon:fxe,History:b2,HistoryIcon:b2,Home:ua,HomeIcon:ua,Hop:gxe,HopIcon:gxe,HopOff:pxe,HopOffIcon:pxe,Hospital:xxe,HospitalIcon:xxe,Hotel:yxe,HotelIcon:yxe,Hourglass:RK,HourglassIcon:RK,House:ua,HouseIcon:ua,HousePlug:vxe,HousePlugIcon:vxe,HousePlus:bxe,HousePlusIcon:bxe,IceCream:qI,IceCream2:UI,IceCream2Icon:UI,IceCreamBowl:UI,IceCreamBowlIcon:UI,IceCreamCone:qI,IceCreamConeIcon:qI,IceCreamIcon:qI,Icon:uSt,IdCard:_xe,IdCardIcon:_xe,Image:zc,ImageDown:wxe,ImageDownIcon:wxe,ImageIcon:zc,ImageMinus:jxe,ImageMinusIcon:jxe,ImageOff:Nxe,ImageOffIcon:Nxe,ImagePlay:kxe,ImagePlayIcon:kxe,ImagePlus:gb,ImagePlusIcon:gb,ImageUp:Sxe,ImageUpIcon:Sxe,ImageUpscale:Cxe,ImageUpscaleIcon:Cxe,Images:Axe,ImagesIcon:Axe,Import:Exe,ImportIcon:Exe,Inbox:HT,InboxIcon:HT,Indent:HI,IndentDecrease:VI,IndentDecreaseIcon:VI,IndentIcon:HI,IndentIncrease:HI,IndentIncreaseIcon:HI,IndianRupee:Txe,IndianRupeeIcon:Txe,Infinity:Mxe,InfinityIcon:Mxe,Info:T5,InfoIcon:T5,Inspect:YL,InspectIcon:YL,InspectionPanel:Pxe,InspectionPanelIcon:Pxe,Instagram:Sf,InstagramIcon:Sf,Italic:GT,ItalicIcon:GT,IterationCcw:Ixe,IterationCcwIcon:Ixe,IterationCw:Lxe,IterationCwIcon:Lxe,JapaneseYen:Rxe,JapaneseYenIcon:Rxe,Joystick:Dxe,JoystickIcon:Dxe,Kanban:M5,KanbanIcon:M5,KanbanSquare:VL,KanbanSquareDashed:OL,KanbanSquareDashedIcon:OL,KanbanSquareIcon:VL,Key:__,KeyIcon:__,KeyRound:x3,KeyRoundIcon:x3,KeySquare:Oxe,KeySquareIcon:Oxe,Keyboard:Bxe,KeyboardIcon:Bxe,KeyboardMusic:Fxe,KeyboardMusicIcon:Fxe,KeyboardOff:zxe,KeyboardOffIcon:zxe,Lamp:Gxe,LampCeiling:$xe,LampCeilingIcon:$xe,LampDesk:Uxe,LampDeskIcon:Uxe,LampFloor:qxe,LampFloorIcon:qxe,LampIcon:Gxe,LampWallDown:Vxe,LampWallDownIcon:Vxe,LampWallUp:Hxe,LampWallUpIcon:Hxe,LandPlot:Wxe,LandPlotIcon:Wxe,Landmark:Gz,LandmarkIcon:Gz,Languages:Kxe,LanguagesIcon:Kxe,Laptop:Zxe,Laptop2:GI,Laptop2Icon:GI,LaptopIcon:Zxe,LaptopMinimal:GI,LaptopMinimalCheck:Yxe,LaptopMinimalCheckIcon:Yxe,LaptopMinimalIcon:GI,Lasso:Qxe,LassoIcon:Qxe,LassoSelect:Xxe,LassoSelectIcon:Xxe,Laugh:Jxe,LaughIcon:Jxe,Layers:Wz,Layers2:eye,Layers2Icon:eye,Layers3:tye,Layers3Icon:tye,LayersIcon:Wz,Layout:jC,LayoutDashboard:$8,LayoutDashboardIcon:$8,LayoutGrid:y0,LayoutGridIcon:y0,LayoutIcon:jC,LayoutList:sye,LayoutListIcon:sye,LayoutPanelLeft:nye,LayoutPanelLeftIcon:nye,LayoutPanelTop:rye,LayoutPanelTopIcon:rye,LayoutTemplate:Zw,LayoutTemplateIcon:Zw,Leaf:aye,LeafIcon:aye,LeafyGreen:iye,LeafyGreenIcon:iye,Lectern:oye,LecternIcon:oye,LetterText:lye,LetterTextIcon:lye,Library:xb,LibraryBig:cye,LibraryBigIcon:cye,LibraryIcon:xb,LibrarySquare:HL,LibrarySquareIcon:HL,LifeBuoy:Kz,LifeBuoyIcon:Kz,Ligature:dye,LigatureIcon:dye,Lightbulb:P5,LightbulbIcon:P5,LightbulbOff:uye,LightbulbOffIcon:uye,LineChart:HP,LineChartIcon:HP,Link:od,Link2:pd,Link2Icon:pd,Link2Off:hye,Link2OffIcon:hye,LinkIcon:od,Linkedin:dv,LinkedinIcon:dv,List:Sy,ListCheck:mye,ListCheckIcon:mye,ListChecks:op,ListChecksIcon:op,ListCollapse:fye,ListCollapseIcon:fye,ListEnd:pye,ListEndIcon:pye,ListFilter:DK,ListFilterIcon:DK,ListIcon:Sy,ListMinus:gye,ListMinusIcon:gye,ListMusic:xye,ListMusicIcon:xye,ListOrdered:_2,ListOrderedIcon:_2,ListPlus:yye,ListPlusIcon:yye,ListRestart:vye,ListRestartIcon:vye,ListStart:bye,ListStartIcon:bye,ListTodo:_ye,ListTodoIcon:_ye,ListTree:wye,ListTreeIcon:wye,ListVideo:jye,ListVideoIcon:jye,ListX:Nye,ListXIcon:Nye,Loader:Sye,Loader2:Jt,Loader2Icon:Jt,LoaderCircle:Jt,LoaderCircleIcon:Jt,LoaderIcon:Sye,LoaderPinwheel:kye,LoaderPinwheelIcon:kye,Locate:Yz,LocateFixed:Cye,LocateFixedIcon:Cye,LocateIcon:Yz,LocateOff:Aye,LocateOffIcon:Aye,Lock:fu,LockIcon:fu,LockKeyhole:Eye,LockKeyholeIcon:Eye,LockKeyholeOpen:WI,LockKeyholeOpenIcon:WI,LockOpen:KI,LockOpenIcon:KI,LogIn:U8,LogInIcon:U8,LogOut:q8,LogOutIcon:q8,Logs:Tye,LogsIcon:Tye,Lollipop:Mye,LollipopIcon:Mye,LucideAArrowDown:soe,LucideAArrowUp:noe,LucideALargeSmall:roe,LucideAccessibility:aoe,LucideActivity:zp,LucideActivitySquare:gL,LucideAirVent:ioe,LucideAirplay:ooe,LucideAlarmCheck:jP,LucideAlarmClock:coe,LucideAlarmClockCheck:jP,LucideAlarmClockMinus:NP,LucideAlarmClockOff:loe,LucideAlarmClockPlus:kP,LucideAlarmMinus:NP,LucideAlarmPlus:kP,LucideAlarmSmoke:doe,LucideAlbum:uoe,LucideAlertCircle:Ho,LucideAlertOctagon:GN,LucideAlertTriangle:Gd,LucideAlignCenter:T8,LucideAlignCenterHorizontal:hoe,LucideAlignCenterVertical:moe,LucideAlignEndHorizontal:foe,LucideAlignEndVertical:poe,LucideAlignHorizontalDistributeCenter:goe,LucideAlignHorizontalDistributeEnd:xoe,LucideAlignHorizontalDistributeStart:yoe,LucideAlignHorizontalJustifyCenter:voe,LucideAlignHorizontalJustifyEnd:boe,LucideAlignHorizontalJustifyStart:_oe,LucideAlignHorizontalSpaceAround:woe,LucideAlignHorizontalSpaceBetween:joe,LucideAlignJustify:Noe,LucideAlignLeft:M8,LucideAlignRight:P8,LucideAlignStartHorizontal:koe,LucideAlignStartVertical:Soe,LucideAlignVerticalDistributeCenter:Coe,LucideAlignVerticalDistributeEnd:Aoe,LucideAlignVerticalDistributeStart:Eoe,LucideAlignVerticalJustifyCenter:Toe,LucideAlignVerticalJustifyEnd:Moe,LucideAlignVerticalJustifyStart:Poe,LucideAlignVerticalSpaceAround:Ioe,LucideAlignVerticalSpaceBetween:Loe,LucideAmbulance:Roe,LucideAmpersand:Doe,LucideAmpersands:Ooe,LucideAmphora:Foe,LucideAnchor:zoe,LucideAngry:Boe,LucideAnnoyed:$oe,LucideAntenna:Uoe,LucideAnvil:qoe,LucideAperture:Voe,LucideAppWindow:Goe,LucideAppWindowMac:Hoe,LucideApple:Woe,LucideArchive:kf,LucideArchiveRestore:OT,LucideArchiveX:Koe,LucideAreaChart:zP,LucideArmchair:Yoe,LucideArrowBigDown:Xoe,LucideArrowBigDownDash:Zoe,LucideArrowBigLeft:Joe,LucideArrowBigLeftDash:Qoe,LucideArrowBigRight:tle,LucideArrowBigRightDash:ele,LucideArrowBigUp:nle,LucideArrowBigUpDash:sle,LucideArrowDown:nx,LucideArrowDown01:rle,LucideArrowDown10:ale,LucideArrowDownAZ:SP,LucideArrowDownAz:SP,LucideArrowDownCircle:XP,LucideArrowDownFromLine:ile,LucideArrowDownLeft:ole,LucideArrowDownLeftFromCircle:JP,LucideArrowDownLeftFromSquare:_L,LucideArrowDownLeftSquare:xL,LucideArrowDownNarrowWide:lle,LucideArrowDownRight:vK,LucideArrowDownRightFromCircle:eI,LucideArrowDownRightFromSquare:wL,LucideArrowDownRightSquare:yL,LucideArrowDownSquare:vL,LucideArrowDownToDot:cle,LucideArrowDownToLine:dle,LucideArrowDownUp:ule,LucideArrowDownWideNarrow:CP,LucideArrowDownZA:AP,LucideArrowDownZa:AP,LucideArrowLeft:Ia,LucideArrowLeftCircle:QP,LucideArrowLeftFromLine:hle,LucideArrowLeftRight:bK,LucideArrowLeftSquare:bL,LucideArrowLeftToLine:mle,LucideArrowRight:xi,LucideArrowRightCircle:nI,LucideArrowRightFromLine:fle,LucideArrowRightLeft:N5,LucideArrowRightSquare:kL,LucideArrowRightToLine:ple,LucideArrowUp:ap,LucideArrowUp01:gle,LucideArrowUp10:xle,LucideArrowUpAZ:EP,LucideArrowUpAz:EP,LucideArrowUpCircle:rI,LucideArrowUpDown:Ix,LucideArrowUpFromDot:yle,LucideArrowUpFromLine:vle,LucideArrowUpLeft:ble,LucideArrowUpLeftFromCircle:tI,LucideArrowUpLeftFromSquare:jL,LucideArrowUpLeftSquare:SL,LucideArrowUpNarrowWide:TP,LucideArrowUpRight:FT,LucideArrowUpRightFromCircle:sI,LucideArrowUpRightFromSquare:NL,LucideArrowUpRightSquare:CL,LucideArrowUpSquare:AL,LucideArrowUpToLine:_le,LucideArrowUpWideNarrow:wle,LucideArrowUpZA:MP,LucideArrowUpZa:MP,LucideArrowsUpFromLine:jle,LucideAsterisk:Nle,LucideAsteriskSquare:EL,LucideAtSign:kle,LucideAtom:Sle,LucideAudioLines:Cle,LucideAudioWaveform:Ale,LucideAward:oh,LucideAxe:Ele,LucideAxis3D:PP,LucideAxis3d:PP,LucideBaby:Tle,LucideBackpack:Mle,LucideBadge:Wle,LucideBadgeAlert:Ple,LucideBadgeCent:Ile,LucideBadgeCheck:IP,LucideBadgeDollarSign:Lle,LucideBadgeEuro:Rle,LucideBadgeHelp:Dle,LucideBadgeIndianRupee:Ole,LucideBadgeInfo:Fle,LucideBadgeJapaneseYen:zle,LucideBadgeMinus:Ble,LucideBadgePercent:$le,LucideBadgePlus:Ule,LucideBadgePoundSterling:qle,LucideBadgeRussianRuble:Vle,LucideBadgeSwissFranc:Hle,LucideBadgeX:Gle,LucideBaggageClaim:Kle,LucideBan:Fz,LucideBanana:Yle,LucideBandage:Zle,LucideBanknote:Xle,LucideBarChart:GP,LucideBarChart2:WP,LucideBarChart3:Ul,LucideBarChart4:VP,LucideBarChartBig:qP,LucideBarChartHorizontal:$P,LucideBarChartHorizontalBig:BP,LucideBarcode:Qle,LucideBaseline:Jle,LucideBath:p0,LucideBattery:ace,LucideBatteryCharging:ece,LucideBatteryFull:tce,LucideBatteryLow:sce,LucideBatteryMedium:nce,LucideBatteryWarning:rce,LucideBeaker:_K,LucideBean:oce,LucideBeanOff:ice,LucideBed:Yw,LucideBedDouble:f3,LucideBedSingle:lce,LucideBeef:cce,LucideBeer:uce,LucideBeerOff:dce,LucideBell:Fx,LucideBellDot:hce,LucideBellElectric:mce,LucideBellMinus:fce,LucideBellOff:k5,LucideBellPlus:pce,LucideBellRing:p3,LucideBetweenHorizonalEnd:LP,LucideBetweenHorizonalStart:RP,LucideBetweenHorizontalEnd:LP,LucideBetweenHorizontalStart:RP,LucideBetweenVerticalEnd:gce,LucideBetweenVerticalStart:xce,LucideBicepsFlexed:yce,LucideBike:vce,LucideBinary:bce,LucideBinoculars:_ce,LucideBiohazard:wce,LucideBird:jce,LucideBitcoin:Nce,LucideBlend:kce,LucideBlinds:Sce,LucideBlocks:Cce,LucideBluetooth:Mce,LucideBluetoothConnected:Ace,LucideBluetoothOff:Ece,LucideBluetoothSearching:Tce,LucideBold:zT,LucideBolt:Pce,LucideBomb:Ice,LucideBone:Lce,LucideBook:sde,LucideBookA:Rce,LucideBookAudio:Dce,LucideBookCheck:Oce,LucideBookCopy:Fce,LucideBookDashed:DP,LucideBookDown:zce,LucideBookHeadphones:Bce,LucideBookHeart:$ce,LucideBookImage:Uce,LucideBookKey:qce,LucideBookLock:Vce,LucideBookMarked:Hce,LucideBookMinus:Gce,LucideBookOpen:wg,LucideBookOpenCheck:Wce,LucideBookOpenText:Kce,LucideBookPlus:Yce,LucideBookTemplate:DP,LucideBookText:Zce,LucideBookType:Xce,LucideBookUp:Jce,LucideBookUp2:Qce,LucideBookUser:ede,LucideBookX:tde,LucideBookmark:jy,LucideBookmarkCheck:nde,LucideBookmarkMinus:rde,LucideBookmarkPlus:BT,LucideBookmarkX:ade,LucideBoomBox:ide,LucideBot:S5,LucideBotMessageSquare:ode,LucideBotOff:lde,LucideBox:wK,LucideBoxSelect:zL,LucideBoxes:cde,LucideBraces:OP,LucideBrackets:dde,LucideBrain:jK,LucideBrainCircuit:ude,LucideBrainCog:hde,LucideBrickWall:mde,LucideBriefcase:zx,LucideBriefcaseBusiness:fde,LucideBriefcaseConveyorBelt:pde,LucideBriefcaseMedical:gde,LucideBringToFront:xde,LucideBrush:yde,LucideBug:_de,LucideBugOff:vde,LucideBugPlay:bde,LucideBuilding:I8,LucideBuilding2:Gi,LucideBus:jde,LucideBusFront:wde,LucideCable:kde,LucideCableCar:Nde,LucideCake:ip,LucideCakeSlice:Sde,LucideCalculator:C5,LucideCalendar:ha,LucideCalendar1:Cde,LucideCalendarArrowDown:Ade,LucideCalendarArrowUp:Ede,LucideCalendarCheck:fb,LucideCalendarCheck2:Tde,LucideCalendarClock:wm,LucideCalendarCog:Mde,LucideCalendarDays:fd,LucideCalendarFold:Pde,LucideCalendarHeart:nk,LucideCalendarMinus:Lde,LucideCalendarMinus2:Ide,LucideCalendarOff:zz,LucideCalendarPlus:i1,LucideCalendarPlus2:Rde,LucideCalendarRange:Dde,LucideCalendarSearch:Ode,LucideCalendarSync:Fde,LucideCalendarX:NK,LucideCalendarX2:zde,LucideCamera:g0,LucideCameraOff:Bde,LucideCandlestickChart:UP,LucideCandy:qde,LucideCandyCane:$de,LucideCandyOff:Ude,LucideCannabis:Vde,LucideCaptions:FP,LucideCaptionsOff:Hde,LucideCar:Kde,LucideCarFront:Gde,LucideCarTaxiFront:Wde,LucideCaravan:Yde,LucideCarrot:Zde,LucideCaseLower:Xde,LucideCaseSensitive:Qde,LucideCaseUpper:Jde,LucideCassetteTape:eue,LucideCast:tue,LucideCastle:sue,LucideCat:nue,LucideCctv:rue,LucideChartArea:zP,LucideChartBar:$P,LucideChartBarBig:BP,LucideChartBarDecreasing:aue,LucideChartBarIncreasing:iue,LucideChartBarStacked:oue,LucideChartCandlestick:UP,LucideChartColumn:Ul,LucideChartColumnBig:qP,LucideChartColumnDecreasing:lue,LucideChartColumnIncreasing:VP,LucideChartColumnStacked:cue,LucideChartGantt:due,LucideChartLine:HP,LucideChartNetwork:uue,LucideChartNoAxesColumn:WP,LucideChartNoAxesColumnDecreasing:hue,LucideChartNoAxesColumnIncreasing:GP,LucideChartNoAxesCombined:mue,LucideChartNoAxesGantt:KP,LucideChartPie:YP,LucideChartScatter:ZP,LucideChartSpline:fue,LucideCheck:ma,LucideCheckCheck:L8,LucideCheckCircle:nl,LucideCheckCircle2:Gr,LucideCheckSquare:r5,LucideCheckSquare2:ML,LucideChefHat:pue,LucideCherry:gue,LucideChevronDown:Go,LucideChevronDownCircle:aI,LucideChevronDownSquare:PL,LucideChevronFirst:xue,LucideChevronLast:yue,LucideChevronLeft:Ld,LucideChevronLeftCircle:iI,LucideChevronLeftSquare:IL,LucideChevronRight:fi,LucideChevronRightCircle:oI,LucideChevronRightSquare:LL,LucideChevronUp:Ny,LucideChevronUpCircle:lI,LucideChevronUpSquare:RL,LucideChevronsDown:bue,LucideChevronsDownUp:vue,LucideChevronsLeft:jue,LucideChevronsLeftRight:wue,LucideChevronsLeftRightEllipsis:_ue,LucideChevronsRight:kue,LucideChevronsRightLeft:Nue,LucideChevronsUp:Sue,LucideChevronsUpDown:v_,LucideChrome:R8,LucideChurch:Cue,LucideCigarette:Eue,LucideCigaretteOff:Aue,LucideCircle:rx,LucideCircleAlert:Ho,LucideCircleArrowDown:XP,LucideCircleArrowLeft:QP,LucideCircleArrowOutDownLeft:JP,LucideCircleArrowOutDownRight:eI,LucideCircleArrowOutUpLeft:tI,LucideCircleArrowOutUpRight:sI,LucideCircleArrowRight:nI,LucideCircleArrowUp:rI,LucideCircleCheck:Gr,LucideCircleCheckBig:nl,LucideCircleChevronDown:aI,LucideCircleChevronLeft:iI,LucideCircleChevronRight:oI,LucideCircleChevronUp:lI,LucideCircleDashed:Tue,LucideCircleDivide:cI,LucideCircleDollarSign:Mue,LucideCircleDot:Iue,LucideCircleDotDashed:Pue,LucideCircleEllipsis:Lue,LucideCircleEqual:Rue,LucideCircleFadingArrowUp:Due,LucideCircleFadingPlus:Oue,LucideCircleGauge:dI,LucideCircleHelp:_C,LucideCircleMinus:uI,LucideCircleOff:Fue,LucideCircleParking:mI,LucideCircleParkingOff:hI,LucideCirclePause:fI,LucideCirclePercent:pI,LucideCirclePlay:mm,LucideCirclePlus:gI,LucideCirclePower:xI,LucideCircleSlash:zue,LucideCircleSlash2:yI,LucideCircleSlashed:yI,LucideCircleStop:vI,LucideCircleUser:_I,LucideCircleUserRound:bI,LucideCircleX:ju,LucideCircuitBoard:Bue,LucideCitrus:$ue,LucideClapperboard:Bz,LucideClipboard:Kue,LucideClipboardCheck:A5,LucideClipboardCopy:Uue,LucideClipboardEdit:jI,LucideClipboardList:lv,LucideClipboardMinus:que,LucideClipboardPaste:Vue,LucideClipboardPen:jI,LucideClipboardPenLine:wI,LucideClipboardPlus:Hue,LucideClipboardSignature:wI,LucideClipboardType:Gue,LucideClipboardX:Wue,LucideClock:sa,LucideClock1:Yue,LucideClock10:Zue,LucideClock11:Xue,LucideClock12:Que,LucideClock2:Jue,LucideClock3:kK,LucideClock4:ehe,LucideClock5:the,LucideClock6:she,LucideClock7:nhe,LucideClock8:rhe,LucideClock9:ahe,LucideClockAlert:ihe,LucideClockArrowDown:ohe,LucideClockArrowUp:lhe,LucideCloud:jhe,LucideCloudAlert:che,LucideCloudCog:dhe,LucideCloudDownload:NI,LucideCloudDrizzle:uhe,LucideCloudFog:hhe,LucideCloudHail:mhe,LucideCloudLightning:fhe,LucideCloudMoon:ghe,LucideCloudMoonRain:phe,LucideCloudOff:xhe,LucideCloudRain:vhe,LucideCloudRainWind:yhe,LucideCloudSnow:bhe,LucideCloudSun:whe,LucideCloudSunRain:_he,LucideCloudUpload:kI,LucideCloudy:Nhe,LucideClover:n3,LucideClub:khe,LucideCode:$T,LucideCode2:wC,LucideCodeSquare:DL,LucideCodeXml:wC,LucideCodepen:She,LucideCodesandbox:Che,LucideCoffee:b_,LucideCog:Ahe,LucideCoins:SK,LucideColumns:SI,LucideColumns2:SI,LucideColumns3:dE,LucideColumns4:Ehe,LucideCombine:The,LucideCommand:Mhe,LucideCompass:D8,LucideComponent:Phe,LucideComputer:Ihe,LucideConciergeBell:Lhe,LucideCone:Rhe,LucideConstruction:Dhe,LucideContact:O8,LucideContact2:CI,LucideContactRound:CI,LucideContainer:Ohe,LucideContrast:Fhe,LucideCookie:zhe,LucideCookingPot:Bhe,LucideCopy:Da,LucideCopyCheck:$he,LucideCopyMinus:Uhe,LucideCopyPlus:qhe,LucideCopySlash:Vhe,LucideCopyX:Hhe,LucideCopyleft:Ghe,LucideCopyright:Whe,LucideCornerDownLeft:Khe,LucideCornerDownRight:Yhe,LucideCornerLeftDown:Zhe,LucideCornerLeftUp:Xhe,LucideCornerRightDown:Qhe,LucideCornerRightUp:Jhe,LucideCornerUpLeft:eme,LucideCornerUpRight:tme,LucideCpu:sme,LucideCreativeCommons:nme,LucideCreditCard:cv,LucideCroissant:rme,LucideCrop:ame,LucideCross:ime,LucideCrosshair:ome,LucideCrown:ky,LucideCuboid:lme,LucideCupSoda:cme,LucideCurlyBraces:OP,LucideCurrency:dme,LucideCylinder:ume,LucideDam:hme,LucideDatabase:CK,LucideDatabaseBackup:mme,LucideDatabaseZap:fme,LucideDelete:pme,LucideDessert:gme,LucideDiameter:xme,LucideDiamond:bme,LucideDiamondMinus:yme,LucideDiamondPercent:AI,LucideDiamondPlus:vme,LucideDice1:_me,LucideDice2:wme,LucideDice3:jme,LucideDice4:Nme,LucideDice5:kme,LucideDice6:Sme,LucideDices:Cme,LucideDiff:Ame,LucideDisc:Pme,LucideDisc2:Eme,LucideDisc3:Tme,LucideDiscAlbum:Mme,LucideDivide:Ime,LucideDivideCircle:cI,LucideDivideSquare:BL,LucideDna:Rme,LucideDnaOff:Lme,LucideDock:Dme,LucideDog:Ome,LucideDollarSign:Su,LucideDonut:Fme,LucideDoorClosed:zme,LucideDoorOpen:x2,LucideDot:Bme,LucideDotSquare:$L,LucideDownload:ji,LucideDownloadCloud:NI,LucideDraftingCompass:$me,LucideDrama:Ume,LucideDribbble:qme,LucideDrill:Vme,LucideDroplet:Hme,LucideDroplets:pb,LucideDrum:Gme,LucideDrumstick:Wme,LucideDumbbell:Kme,LucideEar:Zme,LucideEarOff:Yme,LucideEarth:EI,LucideEarthLock:Xme,LucideEclipse:Qme,LucideEdit:Cp,LucideEdit2:s2,LucideEdit3:WN,LucideEgg:$z,LucideEggFried:Jme,LucideEggOff:efe,LucideEllipsis:u0,LucideEllipsisVertical:Z0,LucideEqual:nfe,LucideEqualApproximately:tfe,LucideEqualNot:sfe,LucideEqualSquare:UL,LucideEraser:rfe,LucideEthernetPort:afe,LucideEuro:ife,LucideExpand:ofe,LucideExternalLink:Ir,LucideEye:ba,LucideEyeClosed:lfe,LucideEyeOff:x0,LucideFacebook:ax,LucideFactory:cfe,LucideFan:dfe,LucideFastForward:ufe,LucideFeather:hfe,LucideFence:mfe,LucideFerrisWheel:ffe,LucideFigma:pfe,LucideFile:Uz,LucideFileArchive:gfe,LucideFileAudio:yfe,LucideFileAudio2:xfe,LucideFileAxis3D:TI,LucideFileAxis3d:TI,LucideFileBadge:bfe,LucideFileBadge2:vfe,LucideFileBarChart:MI,LucideFileBarChart2:PI,LucideFileBox:_fe,LucideFileChartColumn:PI,LucideFileChartColumnIncreasing:MI,LucideFileChartLine:II,LucideFileChartPie:LI,LucideFileCheck:AK,LucideFileCheck2:wfe,LucideFileClock:jfe,LucideFileCode:kfe,LucideFileCode2:Nfe,LucideFileCog:RI,LucideFileCog2:RI,LucideFileDiff:Sfe,LucideFileDigit:Cfe,LucideFileDown:y2,LucideFileEdit:DI,LucideFileHeart:Afe,LucideFileImage:UT,LucideFileInput:Efe,LucideFileJson:Mfe,LucideFileJson2:Tfe,LucideFileKey:Ife,LucideFileKey2:Pfe,LucideFileLineChart:II,LucideFileLock:Rfe,LucideFileLock2:Lfe,LucideFileMinus:Ofe,LucideFileMinus2:Dfe,LucideFileMusic:Ffe,LucideFileOutput:zfe,LucideFilePen:DI,LucideFilePenLine:uE,LucideFilePieChart:LI,LucideFilePlus:$fe,LucideFilePlus2:Bfe,LucideFileQuestion:Ufe,LucideFileScan:qfe,LucideFileSearch:Hfe,LucideFileSearch2:Vfe,LucideFileSignature:uE,LucideFileSliders:Gfe,LucideFileSpreadsheet:rk,LucideFileStack:EK,LucideFileSymlink:Wfe,LucideFileTerminal:Kfe,LucideFileText:ea,LucideFileType:Zfe,LucideFileType2:Yfe,LucideFileUp:Xfe,LucideFileUser:Qfe,LucideFileVideo:TK,LucideFileVideo2:Jfe,LucideFileVolume:tpe,LucideFileVolume2:epe,LucideFileWarning:spe,LucideFileX:rpe,LucideFileX2:npe,LucideFiles:ape,LucideFilm:em,LucideFilter:v2,LucideFilterX:ipe,LucideFingerprint:ope,LucideFireExtinguisher:lpe,LucideFish:upe,LucideFishOff:cpe,LucideFishSymbol:dpe,LucideFlag:g3,LucideFlagOff:hpe,LucideFlagTriangleLeft:mpe,LucideFlagTriangleRight:fpe,LucideFlame:iu,LucideFlameKindling:ppe,LucideFlashlight:xpe,LucideFlashlightOff:gpe,LucideFlaskConical:qT,LucideFlaskConicalOff:ype,LucideFlaskRound:vpe,LucideFlipHorizontal:MK,LucideFlipHorizontal2:bpe,LucideFlipVertical:wpe,LucideFlipVertical2:_pe,LucideFlower:jpe,LucideFlower2:QN,LucideFocus:Npe,LucideFoldHorizontal:kpe,LucideFoldVertical:Spe,LucideFolder:Jpe,LucideFolderArchive:Cpe,LucideFolderCheck:Ape,LucideFolderClock:Epe,LucideFolderClosed:Tpe,LucideFolderCode:Mpe,LucideFolderCog:OI,LucideFolderCog2:OI,LucideFolderDot:Ppe,LucideFolderDown:Ipe,LucideFolderEdit:FI,LucideFolderGit:Rpe,LucideFolderGit2:Lpe,LucideFolderHeart:Dpe,LucideFolderInput:Ope,LucideFolderKanban:Fpe,LucideFolderKey:zpe,LucideFolderLock:Bpe,LucideFolderMinus:$pe,LucideFolderOpen:d1,LucideFolderOpenDot:Upe,LucideFolderOutput:qpe,LucideFolderPen:FI,LucideFolderPlus:Vpe,LucideFolderRoot:Hpe,LucideFolderSearch:Wpe,LucideFolderSearch2:Gpe,LucideFolderSymlink:Kpe,LucideFolderSync:Ype,LucideFolderTree:Zpe,LucideFolderUp:Xpe,LucideFolderX:Qpe,LucideFolders:ege,LucideFootprints:tge,LucideForkKnife:SR,LucideForkKnifeCrossed:kR,LucideForklift:sge,LucideFormInput:lL,LucideForward:nge,LucideFrame:rge,LucideFramer:age,LucideFrown:ige,LucideFuel:oge,LucideFullscreen:lge,LucideFunctionSquare:qL,LucideGalleryHorizontal:dge,LucideGalleryHorizontalEnd:cge,LucideGalleryThumbnails:uge,LucideGalleryVertical:mge,LucideGalleryVerticalEnd:hge,LucideGamepad:pge,LucideGamepad2:fge,LucideGanttChart:KP,LucideGanttChartSquare:vS,LucideGauge:gge,LucideGaugeCircle:dI,LucideGavel:xge,LucideGem:yge,LucideGhost:F8,LucideGift:Zo,LucideGitBranch:bge,LucideGitBranchPlus:vge,LucideGitCommit:zI,LucideGitCommitHorizontal:zI,LucideGitCommitVertical:_ge,LucideGitCompare:jge,LucideGitCompareArrows:wge,LucideGitFork:Nge,LucideGitGraph:kge,LucideGitMerge:Sge,LucideGitPullRequest:Pge,LucideGitPullRequestArrow:Cge,LucideGitPullRequestClosed:Age,LucideGitPullRequestCreate:Tge,LucideGitPullRequestCreateArrow:Ege,LucideGitPullRequestDraft:Mge,LucideGithub:Ige,LucideGitlab:Lge,LucideGlassWater:Rge,LucideGlasses:Dge,LucideGlobe:kc,LucideGlobe2:EI,LucideGlobeLock:Oge,LucideGoal:Fge,LucideGrab:zge,LucideGraduationCap:Bm,LucideGrape:Bge,LucideGrid:Tw,LucideGrid2X2:$I,LucideGrid2X2Plus:BI,LucideGrid2x2:$I,LucideGrid2x2Check:$ge,LucideGrid2x2Plus:BI,LucideGrid2x2X:Uge,LucideGrid3X3:Tw,LucideGrid3x3:Tw,LucideGrip:Vge,LucideGripHorizontal:qge,LucideGripVertical:Bp,LucideGroup:Hge,LucideGuitar:Gge,LucideHam:Wge,LucideHammer:PK,LucideHand:qz,LucideHandCoins:Kge,LucideHandHeart:z8,LucideHandHelping:n5,LucideHandMetal:Yge,LucideHandPlatter:Zge,LucideHandshake:E5,LucideHardDrive:IK,LucideHardDriveDownload:Xge,LucideHardDriveUpload:Qge,LucideHardHat:Jge,LucideHash:VT,LucideHaze:exe,LucideHdmiPort:txe,LucideHeading:axe,LucideHeading1:Vz,LucideHeading2:Hz,LucideHeading3:LK,LucideHeading4:sxe,LucideHeading5:nxe,LucideHeading6:rxe,LucideHeadphoneOff:ixe,LucideHeadphones:oxe,LucideHeadset:lxe,LucideHeart:Bo,LucideHeartCrack:cxe,LucideHeartHandshake:B8,LucideHeartOff:dxe,LucideHeartPulse:uxe,LucideHeater:hxe,LucideHelpCircle:_C,LucideHelpingHand:n5,LucideHexagon:mxe,LucideHighlighter:fxe,LucideHistory:b2,LucideHome:ua,LucideHop:gxe,LucideHopOff:pxe,LucideHospital:xxe,LucideHotel:yxe,LucideHourglass:RK,LucideHouse:ua,LucideHousePlug:vxe,LucideHousePlus:bxe,LucideIceCream:qI,LucideIceCream2:UI,LucideIceCreamBowl:UI,LucideIceCreamCone:qI,LucideIdCard:_xe,LucideImage:zc,LucideImageDown:wxe,LucideImageMinus:jxe,LucideImageOff:Nxe,LucideImagePlay:kxe,LucideImagePlus:gb,LucideImageUp:Sxe,LucideImageUpscale:Cxe,LucideImages:Axe,LucideImport:Exe,LucideInbox:HT,LucideIndent:HI,LucideIndentDecrease:VI,LucideIndentIncrease:HI,LucideIndianRupee:Txe,LucideInfinity:Mxe,LucideInfo:T5,LucideInspect:YL,LucideInspectionPanel:Pxe,LucideInstagram:Sf,LucideItalic:GT,LucideIterationCcw:Ixe,LucideIterationCw:Lxe,LucideJapaneseYen:Rxe,LucideJoystick:Dxe,LucideKanban:M5,LucideKanbanSquare:VL,LucideKanbanSquareDashed:OL,LucideKey:__,LucideKeyRound:x3,LucideKeySquare:Oxe,LucideKeyboard:Bxe,LucideKeyboardMusic:Fxe,LucideKeyboardOff:zxe,LucideLamp:Gxe,LucideLampCeiling:$xe,LucideLampDesk:Uxe,LucideLampFloor:qxe,LucideLampWallDown:Vxe,LucideLampWallUp:Hxe,LucideLandPlot:Wxe,LucideLandmark:Gz,LucideLanguages:Kxe,LucideLaptop:Zxe,LucideLaptop2:GI,LucideLaptopMinimal:GI,LucideLaptopMinimalCheck:Yxe,LucideLasso:Qxe,LucideLassoSelect:Xxe,LucideLaugh:Jxe,LucideLayers:Wz,LucideLayers2:eye,LucideLayers3:tye,LucideLayout:jC,LucideLayoutDashboard:$8,LucideLayoutGrid:y0,LucideLayoutList:sye,LucideLayoutPanelLeft:nye,LucideLayoutPanelTop:rye,LucideLayoutTemplate:Zw,LucideLeaf:aye,LucideLeafyGreen:iye,LucideLectern:oye,LucideLetterText:lye,LucideLibrary:xb,LucideLibraryBig:cye,LucideLibrarySquare:HL,LucideLifeBuoy:Kz,LucideLigature:dye,LucideLightbulb:P5,LucideLightbulbOff:uye,LucideLineChart:HP,LucideLink:od,LucideLink2:pd,LucideLink2Off:hye,LucideLinkedin:dv,LucideList:Sy,LucideListCheck:mye,LucideListChecks:op,LucideListCollapse:fye,LucideListEnd:pye,LucideListFilter:DK,LucideListMinus:gye,LucideListMusic:xye,LucideListOrdered:_2,LucideListPlus:yye,LucideListRestart:vye,LucideListStart:bye,LucideListTodo:_ye,LucideListTree:wye,LucideListVideo:jye,LucideListX:Nye,LucideLoader:Sye,LucideLoader2:Jt,LucideLoaderCircle:Jt,LucideLoaderPinwheel:kye,LucideLocate:Yz,LucideLocateFixed:Cye,LucideLocateOff:Aye,LucideLock:fu,LucideLockKeyhole:Eye,LucideLockKeyholeOpen:WI,LucideLockOpen:KI,LucideLogIn:U8,LucideLogOut:q8,LucideLogs:Tye,LucideLollipop:Mye,LucideLuggage:Pye,LucideMSquare:GL,LucideMagnet:Iye,LucideMail:pn,LucideMailCheck:Zz,LucideMailMinus:Lye,LucideMailOpen:Xz,LucideMailPlus:OK,LucideMailQuestion:Rye,LucideMailSearch:Dye,LucideMailWarning:Oye,LucideMailX:Qz,LucideMailbox:Fye,LucideMails:zye,LucideMap:V8,LucideMapPin:Si,LucideMapPinCheck:$ye,LucideMapPinCheckInside:Bye,LucideMapPinHouse:Uye,LucideMapPinMinus:Vye,LucideMapPinMinusInside:qye,LucideMapPinOff:Hye,LucideMapPinPlus:Wye,LucideMapPinPlusInside:Gye,LucideMapPinX:Yye,LucideMapPinXInside:Kye,LucideMapPinned:Zye,LucideMartini:Xye,LucideMaximize:H8,LucideMaximize2:FK,LucideMedal:y3,LucideMegaphone:xm,LucideMegaphoneOff:Qye,LucideMeh:Jye,LucideMemoryStick:e0e,LucideMenu:WT,LucideMenuSquare:WL,LucideMerge:t0e,LucideMessageCircle:Vu,LucideMessageCircleCode:s0e,LucideMessageCircleDashed:n0e,LucideMessageCircleHeart:Jz,LucideMessageCircleMore:r0e,LucideMessageCircleOff:a0e,LucideMessageCirclePlus:i0e,LucideMessageCircleQuestion:eB,LucideMessageCircleReply:o0e,LucideMessageCircleWarning:l0e,LucideMessageCircleX:c0e,LucideMessageSquare:bo,LucideMessageSquareCode:d0e,LucideMessageSquareDashed:u0e,LucideMessageSquareDiff:h0e,LucideMessageSquareDot:m0e,LucideMessageSquareHeart:tB,LucideMessageSquareLock:f0e,LucideMessageSquareMore:zK,LucideMessageSquareOff:p0e,LucideMessageSquarePlus:h5,LucideMessageSquareQuote:v3,LucideMessageSquareReply:g0e,LucideMessageSquareShare:x0e,LucideMessageSquareText:y0e,LucideMessageSquareWarning:v0e,LucideMessageSquareX:b0e,LucideMessagesSquare:sB,LucideMic:w2,LucideMic2:YI,LucideMicOff:_0e,LucideMicVocal:YI,LucideMicrochip:w0e,LucideMicroscope:j0e,LucideMicrowave:N0e,LucideMilestone:k0e,LucideMilk:C0e,LucideMilkOff:S0e,LucideMinimize:E0e,LucideMinimize2:A0e,LucideMinus:ak,LucideMinusCircle:uI,LucideMinusSquare:KL,LucideMonitor:j2,LucideMonitorCheck:T0e,LucideMonitorCog:M0e,LucideMonitorDot:P0e,LucideMonitorDown:I0e,LucideMonitorOff:L0e,LucideMonitorPause:R0e,LucideMonitorPlay:nB,LucideMonitorSmartphone:D0e,LucideMonitorSpeaker:O0e,LucideMonitorStop:F0e,LucideMonitorUp:G8,LucideMonitorX:z0e,LucideMoon:$0e,LucideMoonStar:B0e,LucideMoreHorizontal:u0,LucideMoreVertical:Z0,LucideMountain:q0e,LucideMountainSnow:U0e,LucideMouse:W0e,LucideMouseOff:V0e,LucideMousePointer:sv,LucideMousePointer2:H0e,LucideMousePointerBan:G0e,LucideMousePointerClick:rh,LucideMousePointerSquareDashed:FL,LucideMove:BK,LucideMove3D:ZI,LucideMove3d:ZI,LucideMoveDiagonal:Y0e,LucideMoveDiagonal2:K0e,LucideMoveDown:Q0e,LucideMoveDownLeft:Z0e,LucideMoveDownRight:X0e,LucideMoveHorizontal:J0e,LucideMoveLeft:eve,LucideMoveRight:tve,LucideMoveUp:rve,LucideMoveUpLeft:sve,LucideMoveUpRight:nve,LucideMoveVertical:ave,LucideMusic:rB,LucideMusic2:ive,LucideMusic3:ove,LucideMusic4:lve,LucideNavigation:$K,LucideNavigation2:dve,LucideNavigation2Off:cve,LucideNavigationOff:uve,LucideNetwork:hve,LucideNewspaper:N2,LucideNfc:mve,LucideNotebook:xve,LucideNotebookPen:fve,LucideNotebookTabs:pve,LucideNotebookText:gve,LucideNotepadText:vve,LucideNotepadTextDashed:yve,LucideNut:_ve,LucideNutOff:bve,LucideOctagon:jve,LucideOctagonAlert:GN,LucideOctagonMinus:wve,LucideOctagonPause:XI,LucideOctagonX:QI,LucideOmega:Nve,LucideOption:kve,LucideOrbit:Sve,LucideOrigami:Cve,LucideOutdent:VI,LucidePackage:bh,LucidePackage2:Ave,LucidePackageCheck:Eve,LucidePackageMinus:Tve,LucidePackageOpen:Mve,LucidePackagePlus:UK,LucidePackageSearch:Pve,LucidePackageX:Ive,LucidePaintBucket:Lve,LucidePaintRoller:Rve,LucidePaintbrush:Dve,LucidePaintbrush2:JI,LucidePaintbrushVertical:JI,LucidePalette:gd,LucidePalmtree:gR,LucidePanelBottom:zve,LucidePanelBottomClose:Ove,LucidePanelBottomDashed:eL,LucidePanelBottomInactive:eL,LucidePanelBottomOpen:Fve,LucidePanelLeft:rL,LucidePanelLeftClose:tL,LucidePanelLeftDashed:sL,LucidePanelLeftInactive:sL,LucidePanelLeftOpen:nL,LucidePanelRight:Uve,LucidePanelRightClose:Bve,LucidePanelRightDashed:aL,LucidePanelRightInactive:aL,LucidePanelRightOpen:$ve,LucidePanelTop:Hve,LucidePanelTopClose:qve,LucidePanelTopDashed:iL,LucidePanelTopInactive:iL,LucidePanelTopOpen:Vve,LucidePanelsLeftBottom:Gve,LucidePanelsLeftRight:dE,LucidePanelsRightBottom:Wve,LucidePanelsTopBottom:uL,LucidePanelsTopLeft:jC,LucidePaperclip:KT,LucideParentheses:Kve,LucideParkingCircle:mI,LucideParkingCircleOff:hI,LucideParkingMeter:Yve,LucideParkingSquare:XL,LucideParkingSquareOff:ZL,LucidePartyPopper:jg,LucidePause:uv,LucidePauseCircle:fI,LucidePauseOctagon:XI,LucidePawPrint:Zve,LucidePcCase:Xve,LucidePen:s2,LucidePenBox:Cp,LucidePenLine:WN,LucidePenOff:Qve,LucidePenSquare:Cp,LucidePenTool:YT,LucidePencil:ui,LucidePencilLine:aB,LucidePencilOff:Jve,LucidePencilRuler:e1e,LucidePentagon:t1e,LucidePercent:ZT,LucidePercentCircle:pI,LucidePercentDiamond:AI,LucidePercentSquare:QL,LucidePersonStanding:s1e,LucidePhilippinePeso:n1e,LucidePhone:ka,LucidePhoneCall:qK,LucidePhoneForwarded:r1e,LucidePhoneIncoming:a1e,LucidePhoneMissed:i1e,LucidePhoneOff:o1e,LucidePhoneOutgoing:l1e,LucidePi:c1e,LucidePiSquare:JL,LucidePiano:d1e,LucidePickaxe:u1e,LucidePictureInPicture:m1e,LucidePictureInPicture2:h1e,LucidePieChart:YP,LucidePiggyBank:f1e,LucidePilcrow:x1e,LucidePilcrowLeft:p1e,LucidePilcrowRight:g1e,LucidePilcrowSquare:eR,LucidePill:v1e,LucidePillBottle:y1e,LucidePin:XT,LucidePinOff:VK,LucidePipette:b1e,LucidePizza:_1e,LucidePlane:HK,LucidePlaneLanding:w1e,LucidePlaneTakeoff:j1e,LucidePlay:pu,LucidePlayCircle:mm,LucidePlaySquare:tR,LucidePlug:k2,LucidePlug2:N1e,LucidePlugZap:oL,LucidePlugZap2:oL,LucidePlus:nn,LucidePlusCircle:gI,LucidePlusSquare:sR,LucidePocket:S1e,LucidePocketKnife:k1e,LucidePodcast:C1e,LucidePointer:E1e,LucidePointerOff:A1e,LucidePopcorn:T1e,LucidePopsicle:M1e,LucidePoundSterling:P1e,LucidePower:GK,LucidePowerCircle:xI,LucidePowerOff:I1e,LucidePowerSquare:nR,LucidePresentation:hv,LucidePrinter:QT,LucidePrinterCheck:L1e,LucideProjector:R1e,LucideProportions:D1e,LucidePuzzle:O1e,LucidePyramid:F1e,LucideQrCode:Bx,LucideQuote:ik,LucideRabbit:z1e,LucideRadar:iB,LucideRadiation:B1e,LucideRadical:$1e,LucideRadio:Cy,LucideRadioReceiver:U1e,LucideRadioTower:q1e,LucideRadius:V1e,LucideRailSymbol:H1e,LucideRainbow:G1e,LucideRat:W1e,LucideRatio:K1e,LucideReceipt:nbe,LucideReceiptCent:Y1e,LucideReceiptEuro:Z1e,LucideReceiptIndianRupee:X1e,LucideReceiptJapaneseYen:Q1e,LucideReceiptPoundSterling:J1e,LucideReceiptRussianRuble:ebe,LucideReceiptSwissFranc:tbe,LucideReceiptText:sbe,LucideRectangleEllipsis:lL,LucideRectangleHorizontal:rbe,LucideRectangleVertical:abe,LucideRecycle:ibe,LucideRedo:JT,LucideRedo2:obe,LucideRedoDot:lbe,LucideRefreshCcw:oB,LucideRefreshCcwDot:cbe,LucideRefreshCw:yo,LucideRefreshCwOff:dbe,LucideRefrigerator:ube,LucideRegex:hbe,LucideRemoveFormatting:mbe,LucideRepeat:lB,LucideRepeat1:fbe,LucideRepeat2:pbe,LucideReplace:xbe,LucideReplaceAll:gbe,LucideReply:WK,LucideReplyAll:ybe,LucideRewind:vbe,LucideRibbon:bbe,LucideRocket:v0,LucideRockingChair:_be,LucideRollerCoaster:wbe,LucideRotate3D:cL,LucideRotate3d:cL,LucideRotateCcw:jm,LucideRotateCcwSquare:jbe,LucideRotateCw:W8,LucideRotateCwSquare:Nbe,LucideRoute:cB,LucideRouteOff:kbe,LucideRouter:Sbe,LucideRows:dL,LucideRows2:dL,LucideRows3:uL,LucideRows4:Cbe,LucideRss:Abe,LucideRuler:b3,LucideRussianRuble:Ebe,LucideSailboat:Tbe,LucideSalad:Mbe,LucideSandwich:Pbe,LucideSatellite:Lbe,LucideSatelliteDish:Ibe,LucideSave:Ml,LucideSaveAll:Rbe,LucideSaveOff:Dbe,LucideScale:KK,LucideScale3D:hL,LucideScale3d:hL,LucideScaling:Obe,LucideScan:Hbe,LucideScanBarcode:Fbe,LucideScanEye:zbe,LucideScanFace:Bbe,LucideScanLine:$be,LucideScanQrCode:Ube,LucideScanSearch:qbe,LucideScanText:Vbe,LucideScatterChart:ZP,LucideSchool:Gbe,LucideSchool2:yR,LucideScissors:Kbe,LucideScissorsLineDashed:Wbe,LucideScissorsSquare:rR,LucideScissorsSquareDashedBottom:TL,LucideScreenShare:Zbe,LucideScreenShareOff:Ybe,LucideScroll:Xbe,LucideScrollText:YK,LucideSearch:Yr,LucideSearchCheck:Qbe,LucideSearchCode:Jbe,LucideSearchSlash:e_e,LucideSearchX:ZK,LucideSection:t_e,LucideSend:Wr,LucideSendHorizonal:mL,LucideSendHorizontal:mL,LucideSendToBack:s_e,LucideSeparatorHorizontal:n_e,LucideSeparatorVertical:r_e,LucideServer:l_e,LucideServerCog:a_e,LucideServerCrash:i_e,LucideServerOff:o_e,LucideSettings:Yc,LucideSettings2:eM,LucideShapes:c_e,LucideShare:XK,LucideShare2:ou,LucideSheet:d_e,LucideShell:u_e,LucideShield:Ng,LucideShieldAlert:dB,LucideShieldBan:h_e,LucideShieldCheck:b0,LucideShieldClose:fL,LucideShieldEllipsis:m_e,LucideShieldHalf:f_e,LucideShieldMinus:p_e,LucideShieldOff:K8,LucideShieldPlus:g_e,LucideShieldQuestion:x_e,LucideShieldX:fL,LucideShip:v_e,LucideShipWheel:y_e,LucideShirt:b_e,LucideShoppingBag:I5,LucideShoppingBasket:__e,LucideShoppingCart:ok,LucideShovel:w_e,LucideShowerHead:j_e,LucideShrink:N_e,LucideShrub:k_e,LucideShuffle:Y8,LucideSidebar:rL,LucideSidebarClose:tL,LucideSidebarOpen:nL,LucideSigma:S_e,LucideSigmaSquare:aR,LucideSignal:M_e,LucideSignalHigh:C_e,LucideSignalLow:A_e,LucideSignalMedium:E_e,LucideSignalZero:T_e,LucideSignature:P_e,LucideSignpost:L_e,LucideSignpostBig:I_e,LucideSiren:R_e,LucideSkipBack:D_e,LucideSkipForward:QK,LucideSkull:O_e,LucideSlack:F_e,LucideSlash:z_e,LucideSlashSquare:iR,LucideSlice:B_e,LucideSliders:pL,LucideSlidersHorizontal:tM,LucideSlidersVertical:pL,LucideSmartphone:yb,LucideSmartphoneCharging:$_e,LucideSmartphoneNfc:U_e,LucideSmile:V_e,LucideSmilePlus:q_e,LucideSnail:H_e,LucideSnowflake:Hw,LucideSofa:G_e,LucideSortAsc:TP,LucideSortDesc:CP,LucideSoup:W_e,LucideSpace:K_e,LucideSpade:Y_e,LucideSparkle:_3,LucideSparkles:kn,LucideSpeaker:Z_e,LucideSpeech:X_e,LucideSpellCheck:J_e,LucideSpellCheck2:Q_e,LucideSpline:ewe,LucideSplit:twe,LucideSplitSquareHorizontal:oR,LucideSplitSquareVertical:lR,LucideSprayCan:swe,LucideSprout:sM,LucideSquare:w_,LucideSquareActivity:gL,LucideSquareArrowDown:vL,LucideSquareArrowDownLeft:xL,LucideSquareArrowDownRight:yL,LucideSquareArrowLeft:bL,LucideSquareArrowOutDownLeft:_L,LucideSquareArrowOutDownRight:wL,LucideSquareArrowOutUpLeft:jL,LucideSquareArrowOutUpRight:NL,LucideSquareArrowRight:kL,LucideSquareArrowUp:AL,LucideSquareArrowUpLeft:SL,LucideSquareArrowUpRight:CL,LucideSquareAsterisk:EL,LucideSquareBottomDashedScissors:TL,LucideSquareChartGantt:vS,LucideSquareCheck:ML,LucideSquareCheckBig:r5,LucideSquareChevronDown:PL,LucideSquareChevronLeft:IL,LucideSquareChevronRight:LL,LucideSquareChevronUp:RL,LucideSquareCode:DL,LucideSquareDashed:zL,LucideSquareDashedBottom:rwe,LucideSquareDashedBottomCode:nwe,LucideSquareDashedKanban:OL,LucideSquareDashedMousePointer:FL,LucideSquareDivide:BL,LucideSquareDot:$L,LucideSquareEqual:UL,LucideSquareFunction:qL,LucideSquareGanttChart:vS,LucideSquareKanban:VL,LucideSquareLibrary:HL,LucideSquareM:GL,LucideSquareMenu:WL,LucideSquareMinus:KL,LucideSquareMousePointer:YL,LucideSquareParking:XL,LucideSquareParkingOff:ZL,LucideSquarePen:Cp,LucideSquarePercent:QL,LucideSquarePi:JL,LucideSquarePilcrow:eR,LucideSquarePlay:tR,LucideSquarePlus:sR,LucideSquarePower:nR,LucideSquareRadical:awe,LucideSquareScissors:rR,LucideSquareSigma:aR,LucideSquareSlash:iR,LucideSquareSplitHorizontal:oR,LucideSquareSplitVertical:lR,LucideSquareSquare:iwe,LucideSquareStack:owe,LucideSquareTerminal:cR,LucideSquareUser:uR,LucideSquareUserRound:dR,LucideSquareX:hR,LucideSquircle:lwe,LucideSquirrel:cwe,LucideStamp:dwe,LucideStar:ri,LucideStarHalf:uwe,LucideStarOff:hwe,LucideStars:kn,LucideStepBack:mwe,LucideStepForward:fwe,LucideStethoscope:pwe,LucideSticker:gwe,LucideStickyNote:Z8,LucideStopCircle:vI,LucideStore:uB,LucideStretchHorizontal:xwe,LucideStretchVertical:ywe,LucideStrikethrough:JK,LucideSubscript:vwe,LucideSubtitles:FP,LucideSun:S2,LucideSunDim:bwe,LucideSunMedium:_we,LucideSunMoon:wwe,LucideSunSnow:jwe,LucideSunrise:Nwe,LucideSunset:kwe,LucideSuperscript:Swe,LucideSwatchBook:Cwe,LucideSwissFranc:Awe,LucideSwitchCamera:Ewe,LucideSword:Twe,LucideSwords:Mwe,LucideSyringe:Pwe,LucideTable:mB,LucideTable2:hB,LucideTableCellsMerge:Iwe,LucideTableCellsSplit:Lwe,LucideTableColumnsSplit:Rwe,LucideTableOfContents:Dwe,LucideTableProperties:Owe,LucideTableRowsSplit:Fwe,LucideTablet:fB,LucideTabletSmartphone:zwe,LucideTablets:Bwe,LucideTag:kg,LucideTags:eY,LucideTally1:$we,LucideTally2:Uwe,LucideTally3:qwe,LucideTally4:Vwe,LucideTally5:Hwe,LucideTangent:Gwe,LucideTarget:_h,LucideTelescope:Wwe,LucideTent:Ywe,LucideTentTree:Kwe,LucideTerminal:Zwe,LucideTerminalSquare:cR,LucideTestTube:Xwe,LucideTestTube2:mR,LucideTestTubeDiagonal:mR,LucideTestTubes:Qwe,LucideText:nje,LucideTextCursor:eje,LucideTextCursorInput:Jwe,LucideTextQuote:tje,LucideTextSearch:sje,LucideTextSelect:fR,LucideTextSelection:fR,LucideTheater:rje,LucideThermometer:tY,LucideThermometerSnowflake:aje,LucideThermometerSun:ije,LucideThumbsDown:sY,LucideThumbsUp:Ay,LucideTicket:X8,LucideTicketCheck:oje,LucideTicketMinus:lje,LucideTicketPercent:cje,LucideTicketPlus:dje,LucideTicketSlash:uje,LucideTicketX:hje,LucideTickets:fje,LucideTicketsPlane:mje,LucideTimer:xje,LucideTimerOff:pje,LucideTimerReset:gje,LucideToggleLeft:yje,LucideToggleRight:vje,LucideToilet:bje,LucideTornado:_je,LucideTorus:wje,LucideTouchpad:Nje,LucideTouchpadOff:jje,LucideTowerControl:kje,LucideToyBrick:Sje,LucideTractor:Cje,LucideTrafficCone:Aje,LucideTrain:pR,LucideTrainFront:Tje,LucideTrainFrontTunnel:Eje,LucideTrainTrack:Mje,LucideTramFront:pR,LucideTrash:Pje,LucideTrash2:Un,LucideTreeDeciduous:Ije,LucideTreePalm:gR,LucideTreePine:nM,LucideTrees:Lje,LucideTrello:Rje,LucideTrendingDown:lk,LucideTrendingUp:mc,LucideTrendingUpDown:Dje,LucideTriangle:Fje,LucideTriangleAlert:Gd,LucideTriangleRight:Oje,LucideTrophy:ql,LucideTruck:nY,LucideTurtle:zje,LucideTv:$je,LucideTv2:xR,LucideTvMinimal:xR,LucideTvMinimalPlay:Bje,LucideTwitch:Uje,LucideTwitter:qje,LucideType:Hje,LucideTypeOutline:Vje,LucideUmbrella:Wje,LucideUmbrellaOff:Gje,LucideUnderline:pB,LucideUndo:rM,LucideUndo2:rY,LucideUndoDot:Kje,LucideUnfoldHorizontal:Yje,LucideUnfoldVertical:Zje,LucideUngroup:Xje,LucideUniversity:yR,LucideUnlink:Q8,LucideUnlink2:Qje,LucideUnlock:KI,LucideUnlockKeyhole:WI,LucideUnplug:aY,LucideUpload:gi,LucideUploadCloud:kI,LucideUsb:Jje,LucideUser:el,LucideUser2:NR,LucideUserCheck:ck,LucideUserCheck2:vR,LucideUserCircle:_I,LucideUserCircle2:bI,LucideUserCog:iY,LucideUserCog2:bR,LucideUserMinus:gB,LucideUserMinus2:_R,LucideUserPen:e2e,LucideUserPlus:Pl,LucideUserPlus2:wR,LucideUserRound:NR,LucideUserRoundCheck:vR,LucideUserRoundCog:bR,LucideUserRoundMinus:_R,LucideUserRoundPen:t2e,LucideUserRoundPlus:wR,LucideUserRoundSearch:s2e,LucideUserRoundX:jR,LucideUserSearch:n2e,LucideUserSquare:uR,LucideUserSquare2:dR,LucideUserX:r2e,LucideUserX2:jR,LucideUsers:Xn,LucideUsers2:tb,LucideUsersRound:tb,LucideUtensils:SR,LucideUtensilsCrossed:kR,LucideUtilityPole:a2e,LucideVariable:xB,LucideVault:i2e,LucideVegan:o2e,LucideVenetianMask:l2e,LucideVerified:IP,LucideVibrate:d2e,LucideVibrateOff:c2e,LucideVideo:ia,LucideVideoOff:u2e,LucideVideotape:h2e,LucideView:m2e,LucideVoicemail:f2e,LucideVolleyball:p2e,LucideVolume:y2e,LucideVolume1:g2e,LucideVolume2:oY,LucideVolumeOff:x2e,LucideVolumeX:lY,LucideVote:v2e,LucideWallet:cY,LucideWallet2:CR,LucideWalletCards:b2e,LucideWalletMinimal:CR,LucideWallpaper:_2e,LucideWand:w2e,LucideWand2:vf,LucideWandSparkles:vf,LucideWarehouse:j2e,LucideWashingMachine:N2e,LucideWatch:k2e,LucideWaves:S2e,LucideWaypoints:C2e,LucideWebcam:A2e,LucideWebhook:T2e,LucideWebhookOff:E2e,LucideWeight:M2e,LucideWheat:I2e,LucideWheatOff:P2e,LucideWholeWord:L2e,LucideWifi:z2e,LucideWifiHigh:R2e,LucideWifiLow:D2e,LucideWifiOff:O2e,LucideWifiZero:F2e,LucideWind:$2e,LucideWindArrowDown:B2e,LucideWine:dY,LucideWineOff:U2e,LucideWorkflow:uY,LucideWorm:q2e,LucideWrapText:V2e,LucideWrench:L5,LucideX:mr,LucideXCircle:ju,LucideXOctagon:QI,LucideXSquare:hR,LucideYoutube:H2e,LucideZap:ix,LucideZapOff:G2e,LucideZoomIn:aM,LucideZoomOut:yB,Luggage:Pye,LuggageIcon:Pye,MSquare:GL,MSquareIcon:GL,Magnet:Iye,MagnetIcon:Iye,Mail:pn,MailCheck:Zz,MailCheckIcon:Zz,MailIcon:pn,MailMinus:Lye,MailMinusIcon:Lye,MailOpen:Xz,MailOpenIcon:Xz,MailPlus:OK,MailPlusIcon:OK,MailQuestion:Rye,MailQuestionIcon:Rye,MailSearch:Dye,MailSearchIcon:Dye,MailWarning:Oye,MailWarningIcon:Oye,MailX:Qz,MailXIcon:Qz,Mailbox:Fye,MailboxIcon:Fye,Mails:zye,MailsIcon:zye,Map:V8,MapIcon:V8,MapPin:Si,MapPinCheck:$ye,MapPinCheckIcon:$ye,MapPinCheckInside:Bye,MapPinCheckInsideIcon:Bye,MapPinHouse:Uye,MapPinHouseIcon:Uye,MapPinIcon:Si,MapPinMinus:Vye,MapPinMinusIcon:Vye,MapPinMinusInside:qye,MapPinMinusInsideIcon:qye,MapPinOff:Hye,MapPinOffIcon:Hye,MapPinPlus:Wye,MapPinPlusIcon:Wye,MapPinPlusInside:Gye,MapPinPlusInsideIcon:Gye,MapPinX:Yye,MapPinXIcon:Yye,MapPinXInside:Kye,MapPinXInsideIcon:Kye,MapPinned:Zye,MapPinnedIcon:Zye,Martini:Xye,MartiniIcon:Xye,Maximize:H8,Maximize2:FK,Maximize2Icon:FK,MaximizeIcon:H8,Medal:y3,MedalIcon:y3,Megaphone:xm,MegaphoneIcon:xm,MegaphoneOff:Qye,MegaphoneOffIcon:Qye,Meh:Jye,MehIcon:Jye,MemoryStick:e0e,MemoryStickIcon:e0e,Menu:WT,MenuIcon:WT,MenuSquare:WL,MenuSquareIcon:WL,Merge:t0e,MergeIcon:t0e,MessageCircle:Vu,MessageCircleCode:s0e,MessageCircleCodeIcon:s0e,MessageCircleDashed:n0e,MessageCircleDashedIcon:n0e,MessageCircleHeart:Jz,MessageCircleHeartIcon:Jz,MessageCircleIcon:Vu,MessageCircleMore:r0e,MessageCircleMoreIcon:r0e,MessageCircleOff:a0e,MessageCircleOffIcon:a0e,MessageCirclePlus:i0e,MessageCirclePlusIcon:i0e,MessageCircleQuestion:eB,MessageCircleQuestionIcon:eB,MessageCircleReply:o0e,MessageCircleReplyIcon:o0e,MessageCircleWarning:l0e,MessageCircleWarningIcon:l0e,MessageCircleX:c0e,MessageCircleXIcon:c0e,MessageSquare:bo,MessageSquareCode:d0e,MessageSquareCodeIcon:d0e,MessageSquareDashed:u0e,MessageSquareDashedIcon:u0e,MessageSquareDiff:h0e,MessageSquareDiffIcon:h0e,MessageSquareDot:m0e,MessageSquareDotIcon:m0e,MessageSquareHeart:tB,MessageSquareHeartIcon:tB,MessageSquareIcon:bo,MessageSquareLock:f0e,MessageSquareLockIcon:f0e,MessageSquareMore:zK,MessageSquareMoreIcon:zK,MessageSquareOff:p0e,MessageSquareOffIcon:p0e,MessageSquarePlus:h5,MessageSquarePlusIcon:h5,MessageSquareQuote:v3,MessageSquareQuoteIcon:v3,MessageSquareReply:g0e,MessageSquareReplyIcon:g0e,MessageSquareShare:x0e,MessageSquareShareIcon:x0e,MessageSquareText:y0e,MessageSquareTextIcon:y0e,MessageSquareWarning:v0e,MessageSquareWarningIcon:v0e,MessageSquareX:b0e,MessageSquareXIcon:b0e,MessagesSquare:sB,MessagesSquareIcon:sB,Mic:w2,Mic2:YI,Mic2Icon:YI,MicIcon:w2,MicOff:_0e,MicOffIcon:_0e,MicVocal:YI,MicVocalIcon:YI,Microchip:w0e,MicrochipIcon:w0e,Microscope:j0e,MicroscopeIcon:j0e,Microwave:N0e,MicrowaveIcon:N0e,Milestone:k0e,MilestoneIcon:k0e,Milk:C0e,MilkIcon:C0e,MilkOff:S0e,MilkOffIcon:S0e,Minimize:E0e,Minimize2:A0e,Minimize2Icon:A0e,MinimizeIcon:E0e,Minus:ak,MinusCircle:uI,MinusCircleIcon:uI,MinusIcon:ak,MinusSquare:KL,MinusSquareIcon:KL,Monitor:j2,MonitorCheck:T0e,MonitorCheckIcon:T0e,MonitorCog:M0e,MonitorCogIcon:M0e,MonitorDot:P0e,MonitorDotIcon:P0e,MonitorDown:I0e,MonitorDownIcon:I0e,MonitorIcon:j2,MonitorOff:L0e,MonitorOffIcon:L0e,MonitorPause:R0e,MonitorPauseIcon:R0e,MonitorPlay:nB,MonitorPlayIcon:nB,MonitorSmartphone:D0e,MonitorSmartphoneIcon:D0e,MonitorSpeaker:O0e,MonitorSpeakerIcon:O0e,MonitorStop:F0e,MonitorStopIcon:F0e,MonitorUp:G8,MonitorUpIcon:G8,MonitorX:z0e,MonitorXIcon:z0e,Moon:$0e,MoonIcon:$0e,MoonStar:B0e,MoonStarIcon:B0e,MoreHorizontal:u0,MoreHorizontalIcon:u0,MoreVertical:Z0,MoreVerticalIcon:Z0,Mountain:q0e,MountainIcon:q0e,MountainSnow:U0e,MountainSnowIcon:U0e,Mouse:W0e,MouseIcon:W0e,MouseOff:V0e,MouseOffIcon:V0e,MousePointer:sv,MousePointer2:H0e,MousePointer2Icon:H0e,MousePointerBan:G0e,MousePointerBanIcon:G0e,MousePointerClick:rh,MousePointerClickIcon:rh,MousePointerIcon:sv,MousePointerSquareDashed:FL,MousePointerSquareDashedIcon:FL,Move:BK,Move3D:ZI,Move3DIcon:ZI,Move3d:ZI,Move3dIcon:ZI,MoveDiagonal:Y0e,MoveDiagonal2:K0e,MoveDiagonal2Icon:K0e,MoveDiagonalIcon:Y0e,MoveDown:Q0e,MoveDownIcon:Q0e,MoveDownLeft:Z0e,MoveDownLeftIcon:Z0e,MoveDownRight:X0e,MoveDownRightIcon:X0e,MoveHorizontal:J0e,MoveHorizontalIcon:J0e,MoveIcon:BK,MoveLeft:eve,MoveLeftIcon:eve,MoveRight:tve,MoveRightIcon:tve,MoveUp:rve,MoveUpIcon:rve,MoveUpLeft:sve,MoveUpLeftIcon:sve,MoveUpRight:nve,MoveUpRightIcon:nve,MoveVertical:ave,MoveVerticalIcon:ave,Music:rB,Music2:ive,Music2Icon:ive,Music3:ove,Music3Icon:ove,Music4:lve,Music4Icon:lve,MusicIcon:rB,Navigation:$K,Navigation2:dve,Navigation2Icon:dve,Navigation2Off:cve,Navigation2OffIcon:cve,NavigationIcon:$K,NavigationOff:uve,NavigationOffIcon:uve,Network:hve,NetworkIcon:hve,Newspaper:N2,NewspaperIcon:N2,Nfc:mve,NfcIcon:mve,Notebook:xve,NotebookIcon:xve,NotebookPen:fve,NotebookPenIcon:fve,NotebookTabs:pve,NotebookTabsIcon:pve,NotebookText:gve,NotebookTextIcon:gve,NotepadText:vve,NotepadTextDashed:yve,NotepadTextDashedIcon:yve,NotepadTextIcon:vve,Nut:_ve,NutIcon:_ve,NutOff:bve,NutOffIcon:bve,Octagon:jve,OctagonAlert:GN,OctagonAlertIcon:GN,OctagonIcon:jve,OctagonMinus:wve,OctagonMinusIcon:wve,OctagonPause:XI,OctagonPauseIcon:XI,OctagonX:QI,OctagonXIcon:QI,Omega:Nve,OmegaIcon:Nve,Option:kve,OptionIcon:kve,Orbit:Sve,OrbitIcon:Sve,Origami:Cve,OrigamiIcon:Cve,Outdent:VI,OutdentIcon:VI,Package:bh,Package2:Ave,Package2Icon:Ave,PackageCheck:Eve,PackageCheckIcon:Eve,PackageIcon:bh,PackageMinus:Tve,PackageMinusIcon:Tve,PackageOpen:Mve,PackageOpenIcon:Mve,PackagePlus:UK,PackagePlusIcon:UK,PackageSearch:Pve,PackageSearchIcon:Pve,PackageX:Ive,PackageXIcon:Ive,PaintBucket:Lve,PaintBucketIcon:Lve,PaintRoller:Rve,PaintRollerIcon:Rve,Paintbrush:Dve,Paintbrush2:JI,Paintbrush2Icon:JI,PaintbrushIcon:Dve,PaintbrushVertical:JI,PaintbrushVerticalIcon:JI,Palette:gd,PaletteIcon:gd,Palmtree:gR,PalmtreeIcon:gR,PanelBottom:zve,PanelBottomClose:Ove,PanelBottomCloseIcon:Ove,PanelBottomDashed:eL,PanelBottomDashedIcon:eL,PanelBottomIcon:zve,PanelBottomInactive:eL,PanelBottomInactiveIcon:eL,PanelBottomOpen:Fve,PanelBottomOpenIcon:Fve,PanelLeft:rL,PanelLeftClose:tL,PanelLeftCloseIcon:tL,PanelLeftDashed:sL,PanelLeftDashedIcon:sL,PanelLeftIcon:rL,PanelLeftInactive:sL,PanelLeftInactiveIcon:sL,PanelLeftOpen:nL,PanelLeftOpenIcon:nL,PanelRight:Uve,PanelRightClose:Bve,PanelRightCloseIcon:Bve,PanelRightDashed:aL,PanelRightDashedIcon:aL,PanelRightIcon:Uve,PanelRightInactive:aL,PanelRightInactiveIcon:aL,PanelRightOpen:$ve,PanelRightOpenIcon:$ve,PanelTop:Hve,PanelTopClose:qve,PanelTopCloseIcon:qve,PanelTopDashed:iL,PanelTopDashedIcon:iL,PanelTopIcon:Hve,PanelTopInactive:iL,PanelTopInactiveIcon:iL,PanelTopOpen:Vve,PanelTopOpenIcon:Vve,PanelsLeftBottom:Gve,PanelsLeftBottomIcon:Gve,PanelsLeftRight:dE,PanelsLeftRightIcon:dE,PanelsRightBottom:Wve,PanelsRightBottomIcon:Wve,PanelsTopBottom:uL,PanelsTopBottomIcon:uL,PanelsTopLeft:jC,PanelsTopLeftIcon:jC,Paperclip:KT,PaperclipIcon:KT,Parentheses:Kve,ParenthesesIcon:Kve,ParkingCircle:mI,ParkingCircleIcon:mI,ParkingCircleOff:hI,ParkingCircleOffIcon:hI,ParkingMeter:Yve,ParkingMeterIcon:Yve,ParkingSquare:XL,ParkingSquareIcon:XL,ParkingSquareOff:ZL,ParkingSquareOffIcon:ZL,PartyPopper:jg,PartyPopperIcon:jg,Pause:uv,PauseCircle:fI,PauseCircleIcon:fI,PauseIcon:uv,PauseOctagon:XI,PauseOctagonIcon:XI,PawPrint:Zve,PawPrintIcon:Zve,PcCase:Xve,PcCaseIcon:Xve,Pen:s2,PenBox:Cp,PenBoxIcon:Cp,PenIcon:s2,PenLine:WN,PenLineIcon:WN,PenOff:Qve,PenOffIcon:Qve,PenSquare:Cp,PenSquareIcon:Cp,PenTool:YT,PenToolIcon:YT,Pencil:ui,PencilIcon:ui,PencilLine:aB,PencilLineIcon:aB,PencilOff:Jve,PencilOffIcon:Jve,PencilRuler:e1e,PencilRulerIcon:e1e,Pentagon:t1e,PentagonIcon:t1e,Percent:ZT,PercentCircle:pI,PercentCircleIcon:pI,PercentDiamond:AI,PercentDiamondIcon:AI,PercentIcon:ZT,PercentSquare:QL,PercentSquareIcon:QL,PersonStanding:s1e,PersonStandingIcon:s1e,PhilippinePeso:n1e,PhilippinePesoIcon:n1e,Phone:ka,PhoneCall:qK,PhoneCallIcon:qK,PhoneForwarded:r1e,PhoneForwardedIcon:r1e,PhoneIcon:ka,PhoneIncoming:a1e,PhoneIncomingIcon:a1e,PhoneMissed:i1e,PhoneMissedIcon:i1e,PhoneOff:o1e,PhoneOffIcon:o1e,PhoneOutgoing:l1e,PhoneOutgoingIcon:l1e,Pi:c1e,PiIcon:c1e,PiSquare:JL,PiSquareIcon:JL,Piano:d1e,PianoIcon:d1e,Pickaxe:u1e,PickaxeIcon:u1e,PictureInPicture:m1e,PictureInPicture2:h1e,PictureInPicture2Icon:h1e,PictureInPictureIcon:m1e,PieChart:YP,PieChartIcon:YP,PiggyBank:f1e,PiggyBankIcon:f1e,Pilcrow:x1e,PilcrowIcon:x1e,PilcrowLeft:p1e,PilcrowLeftIcon:p1e,PilcrowRight:g1e,PilcrowRightIcon:g1e,PilcrowSquare:eR,PilcrowSquareIcon:eR,Pill:v1e,PillBottle:y1e,PillBottleIcon:y1e,PillIcon:v1e,Pin:XT,PinIcon:XT,PinOff:VK,PinOffIcon:VK,Pipette:b1e,PipetteIcon:b1e,Pizza:_1e,PizzaIcon:_1e,Plane:HK,PlaneIcon:HK,PlaneLanding:w1e,PlaneLandingIcon:w1e,PlaneTakeoff:j1e,PlaneTakeoffIcon:j1e,Play:pu,PlayCircle:mm,PlayCircleIcon:mm,PlayIcon:pu,PlaySquare:tR,PlaySquareIcon:tR,Plug:k2,Plug2:N1e,Plug2Icon:N1e,PlugIcon:k2,PlugZap:oL,PlugZap2:oL,PlugZap2Icon:oL,PlugZapIcon:oL,Plus:nn,PlusCircle:gI,PlusCircleIcon:gI,PlusIcon:nn,PlusSquare:sR,PlusSquareIcon:sR,Pocket:S1e,PocketIcon:S1e,PocketKnife:k1e,PocketKnifeIcon:k1e,Podcast:C1e,PodcastIcon:C1e,Pointer:E1e,PointerIcon:E1e,PointerOff:A1e,PointerOffIcon:A1e,Popcorn:T1e,PopcornIcon:T1e,Popsicle:M1e,PopsicleIcon:M1e,PoundSterling:P1e,PoundSterlingIcon:P1e,Power:GK,PowerCircle:xI,PowerCircleIcon:xI,PowerIcon:GK,PowerOff:I1e,PowerOffIcon:I1e,PowerSquare:nR,PowerSquareIcon:nR,Presentation:hv,PresentationIcon:hv,Printer:QT,PrinterCheck:L1e,PrinterCheckIcon:L1e,PrinterIcon:QT,Projector:R1e,ProjectorIcon:R1e,Proportions:D1e,ProportionsIcon:D1e,Puzzle:O1e,PuzzleIcon:O1e,Pyramid:F1e,PyramidIcon:F1e,QrCode:Bx,QrCodeIcon:Bx,Quote:ik,QuoteIcon:ik,Rabbit:z1e,RabbitIcon:z1e,Radar:iB,RadarIcon:iB,Radiation:B1e,RadiationIcon:B1e,Radical:$1e,RadicalIcon:$1e,Radio:Cy,RadioIcon:Cy,RadioReceiver:U1e,RadioReceiverIcon:U1e,RadioTower:q1e,RadioTowerIcon:q1e,Radius:V1e,RadiusIcon:V1e,RailSymbol:H1e,RailSymbolIcon:H1e,Rainbow:G1e,RainbowIcon:G1e,Rat:W1e,RatIcon:W1e,Ratio:K1e,RatioIcon:K1e,Receipt:nbe,ReceiptCent:Y1e,ReceiptCentIcon:Y1e,ReceiptEuro:Z1e,ReceiptEuroIcon:Z1e,ReceiptIcon:nbe,ReceiptIndianRupee:X1e,ReceiptIndianRupeeIcon:X1e,ReceiptJapaneseYen:Q1e,ReceiptJapaneseYenIcon:Q1e,ReceiptPoundSterling:J1e,ReceiptPoundSterlingIcon:J1e,ReceiptRussianRuble:ebe,ReceiptRussianRubleIcon:ebe,ReceiptSwissFranc:tbe,ReceiptSwissFrancIcon:tbe,ReceiptText:sbe,ReceiptTextIcon:sbe,RectangleEllipsis:lL,RectangleEllipsisIcon:lL,RectangleHorizontal:rbe,RectangleHorizontalIcon:rbe,RectangleVertical:abe,RectangleVerticalIcon:abe,Recycle:ibe,RecycleIcon:ibe,Redo:JT,Redo2:obe,Redo2Icon:obe,RedoDot:lbe,RedoDotIcon:lbe,RedoIcon:JT,RefreshCcw:oB,RefreshCcwDot:cbe,RefreshCcwDotIcon:cbe,RefreshCcwIcon:oB,RefreshCw:yo,RefreshCwIcon:yo,RefreshCwOff:dbe,RefreshCwOffIcon:dbe,Refrigerator:ube,RefrigeratorIcon:ube,Regex:hbe,RegexIcon:hbe,RemoveFormatting:mbe,RemoveFormattingIcon:mbe,Repeat:lB,Repeat1:fbe,Repeat1Icon:fbe,Repeat2:pbe,Repeat2Icon:pbe,RepeatIcon:lB,Replace:xbe,ReplaceAll:gbe,ReplaceAllIcon:gbe,ReplaceIcon:xbe,Reply:WK,ReplyAll:ybe,ReplyAllIcon:ybe,ReplyIcon:WK,Rewind:vbe,RewindIcon:vbe,Ribbon:bbe,RibbonIcon:bbe,Rocket:v0,RocketIcon:v0,RockingChair:_be,RockingChairIcon:_be,RollerCoaster:wbe,RollerCoasterIcon:wbe,Rotate3D:cL,Rotate3DIcon:cL,Rotate3d:cL,Rotate3dIcon:cL,RotateCcw:jm,RotateCcwIcon:jm,RotateCcwSquare:jbe,RotateCcwSquareIcon:jbe,RotateCw:W8,RotateCwIcon:W8,RotateCwSquare:Nbe,RotateCwSquareIcon:Nbe,Route:cB,RouteIcon:cB,RouteOff:kbe,RouteOffIcon:kbe,Router:Sbe,RouterIcon:Sbe,Rows:dL,Rows2:dL,Rows2Icon:dL,Rows3:uL,Rows3Icon:uL,Rows4:Cbe,Rows4Icon:Cbe,RowsIcon:dL,Rss:Abe,RssIcon:Abe,Ruler:b3,RulerIcon:b3,RussianRuble:Ebe,RussianRubleIcon:Ebe,Sailboat:Tbe,SailboatIcon:Tbe,Salad:Mbe,SaladIcon:Mbe,Sandwich:Pbe,SandwichIcon:Pbe,Satellite:Lbe,SatelliteDish:Ibe,SatelliteDishIcon:Ibe,SatelliteIcon:Lbe,Save:Ml,SaveAll:Rbe,SaveAllIcon:Rbe,SaveIcon:Ml,SaveOff:Dbe,SaveOffIcon:Dbe,Scale:KK,Scale3D:hL,Scale3DIcon:hL,Scale3d:hL,Scale3dIcon:hL,ScaleIcon:KK,Scaling:Obe,ScalingIcon:Obe,Scan:Hbe,ScanBarcode:Fbe,ScanBarcodeIcon:Fbe,ScanEye:zbe,ScanEyeIcon:zbe,ScanFace:Bbe,ScanFaceIcon:Bbe,ScanIcon:Hbe,ScanLine:$be,ScanLineIcon:$be,ScanQrCode:Ube,ScanQrCodeIcon:Ube,ScanSearch:qbe,ScanSearchIcon:qbe,ScanText:Vbe,ScanTextIcon:Vbe,ScatterChart:ZP,ScatterChartIcon:ZP,School:Gbe,School2:yR,School2Icon:yR,SchoolIcon:Gbe,Scissors:Kbe,ScissorsIcon:Kbe,ScissorsLineDashed:Wbe,ScissorsLineDashedIcon:Wbe,ScissorsSquare:rR,ScissorsSquareDashedBottom:TL,ScissorsSquareDashedBottomIcon:TL,ScissorsSquareIcon:rR,ScreenShare:Zbe,ScreenShareIcon:Zbe,ScreenShareOff:Ybe,ScreenShareOffIcon:Ybe,Scroll:Xbe,ScrollIcon:Xbe,ScrollText:YK,ScrollTextIcon:YK,Search:Yr,SearchCheck:Qbe,SearchCheckIcon:Qbe,SearchCode:Jbe,SearchCodeIcon:Jbe,SearchIcon:Yr,SearchSlash:e_e,SearchSlashIcon:e_e,SearchX:ZK,SearchXIcon:ZK,Section:t_e,SectionIcon:t_e,Send:Wr,SendHorizonal:mL,SendHorizonalIcon:mL,SendHorizontal:mL,SendHorizontalIcon:mL,SendIcon:Wr,SendToBack:s_e,SendToBackIcon:s_e,SeparatorHorizontal:n_e,SeparatorHorizontalIcon:n_e,SeparatorVertical:r_e,SeparatorVerticalIcon:r_e,Server:l_e,ServerCog:a_e,ServerCogIcon:a_e,ServerCrash:i_e,ServerCrashIcon:i_e,ServerIcon:l_e,ServerOff:o_e,ServerOffIcon:o_e,Settings:Yc,Settings2:eM,Settings2Icon:eM,SettingsIcon:Yc,Shapes:c_e,ShapesIcon:c_e,Share:XK,Share2:ou,Share2Icon:ou,ShareIcon:XK,Sheet:d_e,SheetIcon:d_e,Shell:u_e,ShellIcon:u_e,Shield:Ng,ShieldAlert:dB,ShieldAlertIcon:dB,ShieldBan:h_e,ShieldBanIcon:h_e,ShieldCheck:b0,ShieldCheckIcon:b0,ShieldClose:fL,ShieldCloseIcon:fL,ShieldEllipsis:m_e,ShieldEllipsisIcon:m_e,ShieldHalf:f_e,ShieldHalfIcon:f_e,ShieldIcon:Ng,ShieldMinus:p_e,ShieldMinusIcon:p_e,ShieldOff:K8,ShieldOffIcon:K8,ShieldPlus:g_e,ShieldPlusIcon:g_e,ShieldQuestion:x_e,ShieldQuestionIcon:x_e,ShieldX:fL,ShieldXIcon:fL,Ship:v_e,ShipIcon:v_e,ShipWheel:y_e,ShipWheelIcon:y_e,Shirt:b_e,ShirtIcon:b_e,ShoppingBag:I5,ShoppingBagIcon:I5,ShoppingBasket:__e,ShoppingBasketIcon:__e,ShoppingCart:ok,ShoppingCartIcon:ok,Shovel:w_e,ShovelIcon:w_e,ShowerHead:j_e,ShowerHeadIcon:j_e,Shrink:N_e,ShrinkIcon:N_e,Shrub:k_e,ShrubIcon:k_e,Shuffle:Y8,ShuffleIcon:Y8,Sidebar:rL,SidebarClose:tL,SidebarCloseIcon:tL,SidebarIcon:rL,SidebarOpen:nL,SidebarOpenIcon:nL,Sigma:S_e,SigmaIcon:S_e,SigmaSquare:aR,SigmaSquareIcon:aR,Signal:M_e,SignalHigh:C_e,SignalHighIcon:C_e,SignalIcon:M_e,SignalLow:A_e,SignalLowIcon:A_e,SignalMedium:E_e,SignalMediumIcon:E_e,SignalZero:T_e,SignalZeroIcon:T_e,Signature:P_e,SignatureIcon:P_e,Signpost:L_e,SignpostBig:I_e,SignpostBigIcon:I_e,SignpostIcon:L_e,Siren:R_e,SirenIcon:R_e,SkipBack:D_e,SkipBackIcon:D_e,SkipForward:QK,SkipForwardIcon:QK,Skull:O_e,SkullIcon:O_e,Slack:F_e,SlackIcon:F_e,Slash:z_e,SlashIcon:z_e,SlashSquare:iR,SlashSquareIcon:iR,Slice:B_e,SliceIcon:B_e,Sliders:pL,SlidersHorizontal:tM,SlidersHorizontalIcon:tM,SlidersIcon:pL,SlidersVertical:pL,SlidersVerticalIcon:pL,Smartphone:yb,SmartphoneCharging:$_e,SmartphoneChargingIcon:$_e,SmartphoneIcon:yb,SmartphoneNfc:U_e,SmartphoneNfcIcon:U_e,Smile:V_e,SmileIcon:V_e,SmilePlus:q_e,SmilePlusIcon:q_e,Snail:H_e,SnailIcon:H_e,Snowflake:Hw,SnowflakeIcon:Hw,Sofa:G_e,SofaIcon:G_e,SortAsc:TP,SortAscIcon:TP,SortDesc:CP,SortDescIcon:CP,Soup:W_e,SoupIcon:W_e,Space:K_e,SpaceIcon:K_e,Spade:Y_e,SpadeIcon:Y_e,Sparkle:_3,SparkleIcon:_3,Sparkles:kn,SparklesIcon:kn,Speaker:Z_e,SpeakerIcon:Z_e,Speech:X_e,SpeechIcon:X_e,SpellCheck:J_e,SpellCheck2:Q_e,SpellCheck2Icon:Q_e,SpellCheckIcon:J_e,Spline:ewe,SplineIcon:ewe,Split:twe,SplitIcon:twe,SplitSquareHorizontal:oR,SplitSquareHorizontalIcon:oR,SplitSquareVertical:lR,SplitSquareVerticalIcon:lR,SprayCan:swe,SprayCanIcon:swe,Sprout:sM,SproutIcon:sM,Square:w_,SquareActivity:gL,SquareActivityIcon:gL,SquareArrowDown:vL,SquareArrowDownIcon:vL,SquareArrowDownLeft:xL,SquareArrowDownLeftIcon:xL,SquareArrowDownRight:yL,SquareArrowDownRightIcon:yL,SquareArrowLeft:bL,SquareArrowLeftIcon:bL,SquareArrowOutDownLeft:_L,SquareArrowOutDownLeftIcon:_L,SquareArrowOutDownRight:wL,SquareArrowOutDownRightIcon:wL,SquareArrowOutUpLeft:jL,SquareArrowOutUpLeftIcon:jL,SquareArrowOutUpRight:NL,SquareArrowOutUpRightIcon:NL,SquareArrowRight:kL,SquareArrowRightIcon:kL,SquareArrowUp:AL,SquareArrowUpIcon:AL,SquareArrowUpLeft:SL,SquareArrowUpLeftIcon:SL,SquareArrowUpRight:CL,SquareArrowUpRightIcon:CL,SquareAsterisk:EL,SquareAsteriskIcon:EL,SquareBottomDashedScissors:TL,SquareBottomDashedScissorsIcon:TL,SquareChartGantt:vS,SquareChartGanttIcon:vS,SquareCheck:ML,SquareCheckBig:r5,SquareCheckBigIcon:r5,SquareCheckIcon:ML,SquareChevronDown:PL,SquareChevronDownIcon:PL,SquareChevronLeft:IL,SquareChevronLeftIcon:IL,SquareChevronRight:LL,SquareChevronRightIcon:LL,SquareChevronUp:RL,SquareChevronUpIcon:RL,SquareCode:DL,SquareCodeIcon:DL,SquareDashed:zL,SquareDashedBottom:rwe,SquareDashedBottomCode:nwe,SquareDashedBottomCodeIcon:nwe,SquareDashedBottomIcon:rwe,SquareDashedIcon:zL,SquareDashedKanban:OL,SquareDashedKanbanIcon:OL,SquareDashedMousePointer:FL,SquareDashedMousePointerIcon:FL,SquareDivide:BL,SquareDivideIcon:BL,SquareDot:$L,SquareDotIcon:$L,SquareEqual:UL,SquareEqualIcon:UL,SquareFunction:qL,SquareFunctionIcon:qL,SquareGanttChart:vS,SquareGanttChartIcon:vS,SquareIcon:w_,SquareKanban:VL,SquareKanbanIcon:VL,SquareLibrary:HL,SquareLibraryIcon:HL,SquareM:GL,SquareMIcon:GL,SquareMenu:WL,SquareMenuIcon:WL,SquareMinus:KL,SquareMinusIcon:KL,SquareMousePointer:YL,SquareMousePointerIcon:YL,SquareParking:XL,SquareParkingIcon:XL,SquareParkingOff:ZL,SquareParkingOffIcon:ZL,SquarePen:Cp,SquarePenIcon:Cp,SquarePercent:QL,SquarePercentIcon:QL,SquarePi:JL,SquarePiIcon:JL,SquarePilcrow:eR,SquarePilcrowIcon:eR,SquarePlay:tR,SquarePlayIcon:tR,SquarePlus:sR,SquarePlusIcon:sR,SquarePower:nR,SquarePowerIcon:nR,SquareRadical:awe,SquareRadicalIcon:awe,SquareScissors:rR,SquareScissorsIcon:rR,SquareSigma:aR,SquareSigmaIcon:aR,SquareSlash:iR,SquareSlashIcon:iR,SquareSplitHorizontal:oR,SquareSplitHorizontalIcon:oR,SquareSplitVertical:lR,SquareSplitVerticalIcon:lR,SquareSquare:iwe,SquareSquareIcon:iwe,SquareStack:owe,SquareStackIcon:owe,SquareTerminal:cR,SquareTerminalIcon:cR,SquareUser:uR,SquareUserIcon:uR,SquareUserRound:dR,SquareUserRoundIcon:dR,SquareX:hR,SquareXIcon:hR,Squircle:lwe,SquircleIcon:lwe,Squirrel:cwe,SquirrelIcon:cwe,Stamp:dwe,StampIcon:dwe,Star:ri,StarHalf:uwe,StarHalfIcon:uwe,StarIcon:ri,StarOff:hwe,StarOffIcon:hwe,Stars:kn,StarsIcon:kn,StepBack:mwe,StepBackIcon:mwe,StepForward:fwe,StepForwardIcon:fwe,Stethoscope:pwe,StethoscopeIcon:pwe,Sticker:gwe,StickerIcon:gwe,StickyNote:Z8,StickyNoteIcon:Z8,StopCircle:vI,StopCircleIcon:vI,Store:uB,StoreIcon:uB,StretchHorizontal:xwe,StretchHorizontalIcon:xwe,StretchVertical:ywe,StretchVerticalIcon:ywe,Strikethrough:JK,StrikethroughIcon:JK,Subscript:vwe,SubscriptIcon:vwe,Subtitles:FP,SubtitlesIcon:FP,Sun:S2,SunDim:bwe,SunDimIcon:bwe,SunIcon:S2,SunMedium:_we,SunMediumIcon:_we,SunMoon:wwe,SunMoonIcon:wwe,SunSnow:jwe,SunSnowIcon:jwe,Sunrise:Nwe,SunriseIcon:Nwe,Sunset:kwe,SunsetIcon:kwe,Superscript:Swe,SuperscriptIcon:Swe,SwatchBook:Cwe,SwatchBookIcon:Cwe,SwissFranc:Awe,SwissFrancIcon:Awe,SwitchCamera:Ewe,SwitchCameraIcon:Ewe,Sword:Twe,SwordIcon:Twe,Swords:Mwe,SwordsIcon:Mwe,Syringe:Pwe,SyringeIcon:Pwe,Table:mB,Table2:hB,Table2Icon:hB,TableCellsMerge:Iwe,TableCellsMergeIcon:Iwe,TableCellsSplit:Lwe,TableCellsSplitIcon:Lwe,TableColumnsSplit:Rwe,TableColumnsSplitIcon:Rwe,TableIcon:mB,TableOfContents:Dwe,TableOfContentsIcon:Dwe,TableProperties:Owe,TablePropertiesIcon:Owe,TableRowsSplit:Fwe,TableRowsSplitIcon:Fwe,Tablet:fB,TabletIcon:fB,TabletSmartphone:zwe,TabletSmartphoneIcon:zwe,Tablets:Bwe,TabletsIcon:Bwe,Tag:kg,TagIcon:kg,Tags:eY,TagsIcon:eY,Tally1:$we,Tally1Icon:$we,Tally2:Uwe,Tally2Icon:Uwe,Tally3:qwe,Tally3Icon:qwe,Tally4:Vwe,Tally4Icon:Vwe,Tally5:Hwe,Tally5Icon:Hwe,Tangent:Gwe,TangentIcon:Gwe,Target:_h,TargetIcon:_h,Telescope:Wwe,TelescopeIcon:Wwe,Tent:Ywe,TentIcon:Ywe,TentTree:Kwe,TentTreeIcon:Kwe,Terminal:Zwe,TerminalIcon:Zwe,TerminalSquare:cR,TerminalSquareIcon:cR,TestTube:Xwe,TestTube2:mR,TestTube2Icon:mR,TestTubeDiagonal:mR,TestTubeDiagonalIcon:mR,TestTubeIcon:Xwe,TestTubes:Qwe,TestTubesIcon:Qwe,Text:nje,TextCursor:eje,TextCursorIcon:eje,TextCursorInput:Jwe,TextCursorInputIcon:Jwe,TextIcon:nje,TextQuote:tje,TextQuoteIcon:tje,TextSearch:sje,TextSearchIcon:sje,TextSelect:fR,TextSelectIcon:fR,TextSelection:fR,TextSelectionIcon:fR,Theater:rje,TheaterIcon:rje,Thermometer:tY,ThermometerIcon:tY,ThermometerSnowflake:aje,ThermometerSnowflakeIcon:aje,ThermometerSun:ije,ThermometerSunIcon:ije,ThumbsDown:sY,ThumbsDownIcon:sY,ThumbsUp:Ay,ThumbsUpIcon:Ay,Ticket:X8,TicketCheck:oje,TicketCheckIcon:oje,TicketIcon:X8,TicketMinus:lje,TicketMinusIcon:lje,TicketPercent:cje,TicketPercentIcon:cje,TicketPlus:dje,TicketPlusIcon:dje,TicketSlash:uje,TicketSlashIcon:uje,TicketX:hje,TicketXIcon:hje,Tickets:fje,TicketsIcon:fje,TicketsPlane:mje,TicketsPlaneIcon:mje,Timer:xje,TimerIcon:xje,TimerOff:pje,TimerOffIcon:pje,TimerReset:gje,TimerResetIcon:gje,ToggleLeft:yje,ToggleLeftIcon:yje,ToggleRight:vje,ToggleRightIcon:vje,Toilet:bje,ToiletIcon:bje,Tornado:_je,TornadoIcon:_je,Torus:wje,TorusIcon:wje,Touchpad:Nje,TouchpadIcon:Nje,TouchpadOff:jje,TouchpadOffIcon:jje,TowerControl:kje,TowerControlIcon:kje,ToyBrick:Sje,ToyBrickIcon:Sje,Tractor:Cje,TractorIcon:Cje,TrafficCone:Aje,TrafficConeIcon:Aje,Train:pR,TrainFront:Tje,TrainFrontIcon:Tje,TrainFrontTunnel:Eje,TrainFrontTunnelIcon:Eje,TrainIcon:pR,TrainTrack:Mje,TrainTrackIcon:Mje,TramFront:pR,TramFrontIcon:pR,Trash:Pje,Trash2:Un,Trash2Icon:Un,TrashIcon:Pje,TreeDeciduous:Ije,TreeDeciduousIcon:Ije,TreePalm:gR,TreePalmIcon:gR,TreePine:nM,TreePineIcon:nM,Trees:Lje,TreesIcon:Lje,Trello:Rje,TrelloIcon:Rje,TrendingDown:lk,TrendingDownIcon:lk,TrendingUp:mc,TrendingUpDown:Dje,TrendingUpDownIcon:Dje,TrendingUpIcon:mc,Triangle:Fje,TriangleAlert:Gd,TriangleAlertIcon:Gd,TriangleIcon:Fje,TriangleRight:Oje,TriangleRightIcon:Oje,Trophy:ql,TrophyIcon:ql,Truck:nY,TruckIcon:nY,Turtle:zje,TurtleIcon:zje,Tv:$je,Tv2:xR,Tv2Icon:xR,TvIcon:$je,TvMinimal:xR,TvMinimalIcon:xR,TvMinimalPlay:Bje,TvMinimalPlayIcon:Bje,Twitch:Uje,TwitchIcon:Uje,Twitter:qje,TwitterIcon:qje,Type:Hje,TypeIcon:Hje,TypeOutline:Vje,TypeOutlineIcon:Vje,Umbrella:Wje,UmbrellaIcon:Wje,UmbrellaOff:Gje,UmbrellaOffIcon:Gje,Underline:pB,UnderlineIcon:pB,Undo:rM,Undo2:rY,Undo2Icon:rY,UndoDot:Kje,UndoDotIcon:Kje,UndoIcon:rM,UnfoldHorizontal:Yje,UnfoldHorizontalIcon:Yje,UnfoldVertical:Zje,UnfoldVerticalIcon:Zje,Ungroup:Xje,UngroupIcon:Xje,University:yR,UniversityIcon:yR,Unlink:Q8,Unlink2:Qje,Unlink2Icon:Qje,UnlinkIcon:Q8,Unlock:KI,UnlockIcon:KI,UnlockKeyhole:WI,UnlockKeyholeIcon:WI,Unplug:aY,UnplugIcon:aY,Upload:gi,UploadCloud:kI,UploadCloudIcon:kI,UploadIcon:gi,Usb:Jje,UsbIcon:Jje,User:el,User2:NR,User2Icon:NR,UserCheck:ck,UserCheck2:vR,UserCheck2Icon:vR,UserCheckIcon:ck,UserCircle:_I,UserCircle2:bI,UserCircle2Icon:bI,UserCircleIcon:_I,UserCog:iY,UserCog2:bR,UserCog2Icon:bR,UserCogIcon:iY,UserIcon:el,UserMinus:gB,UserMinus2:_R,UserMinus2Icon:_R,UserMinusIcon:gB,UserPen:e2e,UserPenIcon:e2e,UserPlus:Pl,UserPlus2:wR,UserPlus2Icon:wR,UserPlusIcon:Pl,UserRound:NR,UserRoundCheck:vR,UserRoundCheckIcon:vR,UserRoundCog:bR,UserRoundCogIcon:bR,UserRoundIcon:NR,UserRoundMinus:_R,UserRoundMinusIcon:_R,UserRoundPen:t2e,UserRoundPenIcon:t2e,UserRoundPlus:wR,UserRoundPlusIcon:wR,UserRoundSearch:s2e,UserRoundSearchIcon:s2e,UserRoundX:jR,UserRoundXIcon:jR,UserSearch:n2e,UserSearchIcon:n2e,UserSquare:uR,UserSquare2:dR,UserSquare2Icon:dR,UserSquareIcon:uR,UserX:r2e,UserX2:jR,UserX2Icon:jR,UserXIcon:r2e,Users:Xn,Users2:tb,Users2Icon:tb,UsersIcon:Xn,UsersRound:tb,UsersRoundIcon:tb,Utensils:SR,UtensilsCrossed:kR,UtensilsCrossedIcon:kR,UtensilsIcon:SR,UtilityPole:a2e,UtilityPoleIcon:a2e,Variable:xB,VariableIcon:xB,Vault:i2e,VaultIcon:i2e,Vegan:o2e,VeganIcon:o2e,VenetianMask:l2e,VenetianMaskIcon:l2e,Verified:IP,VerifiedIcon:IP,Vibrate:d2e,VibrateIcon:d2e,VibrateOff:c2e,VibrateOffIcon:c2e,Video:ia,VideoIcon:ia,VideoOff:u2e,VideoOffIcon:u2e,Videotape:h2e,VideotapeIcon:h2e,View:m2e,ViewIcon:m2e,Voicemail:f2e,VoicemailIcon:f2e,Volleyball:p2e,VolleyballIcon:p2e,Volume:y2e,Volume1:g2e,Volume1Icon:g2e,Volume2:oY,Volume2Icon:oY,VolumeIcon:y2e,VolumeOff:x2e,VolumeOffIcon:x2e,VolumeX:lY,VolumeXIcon:lY,Vote:v2e,VoteIcon:v2e,Wallet:cY,Wallet2:CR,Wallet2Icon:CR,WalletCards:b2e,WalletCardsIcon:b2e,WalletIcon:cY,WalletMinimal:CR,WalletMinimalIcon:CR,Wallpaper:_2e,WallpaperIcon:_2e,Wand:w2e,Wand2:vf,Wand2Icon:vf,WandIcon:w2e,WandSparkles:vf,WandSparklesIcon:vf,Warehouse:j2e,WarehouseIcon:j2e,WashingMachine:N2e,WashingMachineIcon:N2e,Watch:k2e,WatchIcon:k2e,Waves:S2e,WavesIcon:S2e,Waypoints:C2e,WaypointsIcon:C2e,Webcam:A2e,WebcamIcon:A2e,Webhook:T2e,WebhookIcon:T2e,WebhookOff:E2e,WebhookOffIcon:E2e,Weight:M2e,WeightIcon:M2e,Wheat:I2e,WheatIcon:I2e,WheatOff:P2e,WheatOffIcon:P2e,WholeWord:L2e,WholeWordIcon:L2e,Wifi:z2e,WifiHigh:R2e,WifiHighIcon:R2e,WifiIcon:z2e,WifiLow:D2e,WifiLowIcon:D2e,WifiOff:O2e,WifiOffIcon:O2e,WifiZero:F2e,WifiZeroIcon:F2e,Wind:$2e,WindArrowDown:B2e,WindArrowDownIcon:B2e,WindIcon:$2e,Wine:dY,WineIcon:dY,WineOff:U2e,WineOffIcon:U2e,Workflow:uY,WorkflowIcon:uY,Worm:q2e,WormIcon:q2e,WrapText:V2e,WrapTextIcon:V2e,Wrench:L5,WrenchIcon:L5,X:mr,XCircle:ju,XCircleIcon:ju,XIcon:mr,XOctagon:QI,XOctagonIcon:QI,XSquare:hR,XSquareIcon:hR,Youtube:H2e,YoutubeIcon:H2e,Zap:ix,ZapIcon:ix,ZapOff:G2e,ZapOffIcon:G2e,ZoomIn:aM,ZoomInIcon:aM,ZoomOut:yB,ZoomOutIcon:yB,createLucideIcon:ue,icons:Pss},Symbol.toStringTag,{value:"Module"})),WVe="-",Iss=s=>{const t=Rss(s),{conflictingClassGroups:n,conflictingClassGroupModifiers:r}=s;return{getClassGroupId:l=>{const o=l.split(WVe);return o[0]===""&&o.length!==1&&o.shift(),hSt(o,t)||Lss(l)},getConflictingClassGroupIds:(l,o)=>{const c=n[l]||[];return o&&r[l]?[...c,...r[l]]:c}}},hSt=(s,t)=>{var l;if(s.length===0)return t.classGroupId;const n=s[0],r=t.nextPart.get(n),a=r?hSt(s.slice(1),r):void 0;if(a)return a;if(t.validators.length===0)return;const i=s.join(WVe);return(l=t.validators.find(({validator:o})=>o(i)))==null?void 0:l.classGroupId},Bat=/^\[(.+)\]$/,Lss=s=>{if(Bat.test(s)){const t=Bat.exec(s)[1],n=t==null?void 0:t.substring(0,t.indexOf(":"));if(n)return"arbitrary.."+n}},Rss=s=>{const{theme:t,prefix:n}=s,r={nextPart:new Map,validators:[]};return Oss(Object.entries(s.classGroups),n).forEach(([i,l])=>{lFe(l,r,i,t)}),r},lFe=(s,t,n,r)=>{s.forEach(a=>{if(typeof a=="string"){const i=a===""?t:$at(t,a);i.classGroupId=n;return}if(typeof a=="function"){if(Dss(a)){lFe(a(r),t,n,r);return}t.validators.push({validator:a,classGroupId:n});return}Object.entries(a).forEach(([i,l])=>{lFe(l,$at(t,i),n,r)})})},$at=(s,t)=>{let n=s;return t.split(WVe).forEach(r=>{n.nextPart.has(r)||n.nextPart.set(r,{nextPart:new Map,validators:[]}),n=n.nextPart.get(r)}),n},Dss=s=>s.isThemeGetter,Oss=(s,t)=>t?s.map(([n,r])=>{const a=r.map(i=>typeof i=="string"?t+i:typeof i=="object"?Object.fromEntries(Object.entries(i).map(([l,o])=>[t+l,o])):i);return[n,a]}):s,Fss=s=>{if(s<1)return{get:()=>{},set:()=>{}};let t=0,n=new Map,r=new Map;const a=(i,l)=>{n.set(i,l),t++,t>s&&(t=0,r=n,n=new Map)};return{get(i){let l=n.get(i);if(l!==void 0)return l;if((l=r.get(i))!==void 0)return a(i,l),l},set(i,l){n.has(i)?n.set(i,l):a(i,l)}}},mSt="!",zss=s=>{const{separator:t,experimentalParseClassName:n}=s,r=t.length===1,a=t[0],i=t.length,l=o=>{const c=[];let d=0,u=0,h;for(let y=0;yu?h-u:void 0;return{modifiers:c,hasImportantModifier:p,baseClassName:g,maybePostfixModifierPosition:x}};return n?o=>n({className:o,parseClassName:l}):l},Bss=s=>{if(s.length<=1)return s;const t=[];let n=[];return s.forEach(r=>{r[0]==="["?(t.push(...n.sort(),r),n=[]):n.push(r)}),t.push(...n.sort()),t},$ss=s=>({cache:Fss(s.cacheSize),parseClassName:zss(s),...Iss(s)}),Uss=/\s+/,qss=(s,t)=>{const{parseClassName:n,getClassGroupId:r,getConflictingClassGroupIds:a}=t,i=[],l=s.trim().split(Uss);let o="";for(let c=l.length-1;c>=0;c-=1){const d=l[c],{modifiers:u,hasImportantModifier:h,baseClassName:m,maybePostfixModifierPosition:p}=n(d);let g=!!p,x=r(g?m.substring(0,p):m);if(!x){if(!g){o=d+(o.length>0?" "+o:o);continue}if(x=r(m),!x){o=d+(o.length>0?" "+o:o);continue}g=!1}const y=Bss(u).join(":"),v=h?y+mSt:y,_=v+x;if(i.includes(_))continue;i.push(_);const j=a(x,g);for(let C=0;C0?" "+o:o)}return o};function Vss(){let s=0,t,n,r="";for(;s{if(typeof s=="string")return s;let t,n="";for(let r=0;rh(u),s());return n=$ss(d),r=n.cache.get,a=n.cache.set,i=o,o(c)}function o(c){const d=r(c);if(d)return d;const u=qss(c,n);return a(c,u),u}return function(){return i(Vss.apply(null,arguments))}}const hf=s=>{const t=n=>n[s]||[];return t.isThemeGetter=!0,t},pSt=/^\[(?:([a-z-]+):)?(.+)\]$/i,Gss=/^\d+\/\d+$/,Wss=new Set(["px","full","screen"]),Kss=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,Yss=/\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$/,Zss=/^(rgba?|hsla?|hwb|(ok)?(lab|lch)|color-mix)\(.+\)$/,Xss=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,Qss=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,H4=s=>vB(s)||Wss.has(s)||Gss.test(s),LA=s=>Tq(s,"length",ins),vB=s=>!!s&&!Number.isNaN(Number(s)),VPe=s=>Tq(s,"number",vB),QH=s=>!!s&&Number.isInteger(Number(s)),Jss=s=>s.endsWith("%")&&vB(s.slice(0,-1)),Gc=s=>pSt.test(s),RA=s=>Kss.test(s),ens=new Set(["length","size","percentage"]),tns=s=>Tq(s,ens,gSt),sns=s=>Tq(s,"position",gSt),nns=new Set(["image","url"]),rns=s=>Tq(s,nns,lns),ans=s=>Tq(s,"",ons),JH=()=>!0,Tq=(s,t,n)=>{const r=pSt.exec(s);return r?r[1]?typeof t=="string"?r[1]===t:t.has(r[1]):n(r[2]):!1},ins=s=>Yss.test(s)&&!Zss.test(s),gSt=()=>!1,ons=s=>Xss.test(s),lns=s=>Qss.test(s),cns=()=>{const s=hf("colors"),t=hf("spacing"),n=hf("blur"),r=hf("brightness"),a=hf("borderColor"),i=hf("borderRadius"),l=hf("borderSpacing"),o=hf("borderWidth"),c=hf("contrast"),d=hf("grayscale"),u=hf("hueRotate"),h=hf("invert"),m=hf("gap"),p=hf("gradientColorStops"),g=hf("gradientColorStopPositions"),x=hf("inset"),y=hf("margin"),v=hf("opacity"),_=hf("padding"),j=hf("saturate"),C=hf("scale"),A=hf("sepia"),M=hf("skew"),I=hf("space"),P=hf("translate"),R=()=>["auto","contain","none"],O=()=>["auto","hidden","clip","visible","scroll"],B=()=>["auto",Gc,t],U=()=>[Gc,t],G=()=>["",H4,LA],H=()=>["auto",vB,Gc],Y=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],se=()=>["solid","dashed","dotted","double","none"],ee=()=>["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"],oe=()=>["start","end","center","between","around","evenly","stretch"],me=()=>["","0",Gc],Q=()=>["auto","avoid","all","avoid-page","page","left","right","column"],te=()=>[vB,Gc];return{cacheSize:500,separator:":",theme:{colors:[JH],spacing:[H4,LA],blur:["none","",RA,Gc],brightness:te(),borderColor:[s],borderRadius:["none","","full",RA,Gc],borderSpacing:U(),borderWidth:G(),contrast:te(),grayscale:me(),hueRotate:te(),invert:me(),gap:U(),gradientColorStops:[s],gradientColorStopPositions:[Jss,LA],inset:B(),margin:B(),opacity:te(),padding:U(),saturate:te(),scale:te(),sepia:me(),skew:te(),space:U(),translate:U()},classGroups:{aspect:[{aspect:["auto","square","video",Gc]}],container:["container"],columns:[{columns:[RA]}],"break-after":[{"break-after":Q()}],"break-before":[{"break-before":Q()}],"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:[...Y(),Gc]}],overflow:[{overflow:O()}],"overflow-x":[{"overflow-x":O()}],"overflow-y":[{"overflow-y":O()}],overscroll:[{overscroll:R()}],"overscroll-x":[{"overscroll-x":R()}],"overscroll-y":[{"overscroll-y":R()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:[x]}],"inset-x":[{"inset-x":[x]}],"inset-y":[{"inset-y":[x]}],start:[{start:[x]}],end:[{end:[x]}],top:[{top:[x]}],right:[{right:[x]}],bottom:[{bottom:[x]}],left:[{left:[x]}],visibility:["visible","invisible","collapse"],z:[{z:["auto",QH,Gc]}],basis:[{basis:B()}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["wrap","wrap-reverse","nowrap"]}],flex:[{flex:["1","auto","initial","none",Gc]}],grow:[{grow:me()}],shrink:[{shrink:me()}],order:[{order:["first","last","none",QH,Gc]}],"grid-cols":[{"grid-cols":[JH]}],"col-start-end":[{col:["auto",{span:["full",QH,Gc]},Gc]}],"col-start":[{"col-start":H()}],"col-end":[{"col-end":H()}],"grid-rows":[{"grid-rows":[JH]}],"row-start-end":[{row:["auto",{span:[QH,Gc]},Gc]}],"row-start":[{"row-start":H()}],"row-end":[{"row-end":H()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":["auto","min","max","fr",Gc]}],"auto-rows":[{"auto-rows":["auto","min","max","fr",Gc]}],gap:[{gap:[m]}],"gap-x":[{"gap-x":[m]}],"gap-y":[{"gap-y":[m]}],"justify-content":[{justify:["normal",...oe()]}],"justify-items":[{"justify-items":["start","end","center","stretch"]}],"justify-self":[{"justify-self":["auto","start","end","center","stretch"]}],"align-content":[{content:["normal",...oe(),"baseline"]}],"align-items":[{items:["start","end","center","baseline","stretch"]}],"align-self":[{self:["auto","start","end","center","stretch","baseline"]}],"place-content":[{"place-content":[...oe(),"baseline"]}],"place-items":[{"place-items":["start","end","center","baseline","stretch"]}],"place-self":[{"place-self":["auto","start","end","center","stretch"]}],p:[{p:[_]}],px:[{px:[_]}],py:[{py:[_]}],ps:[{ps:[_]}],pe:[{pe:[_]}],pt:[{pt:[_]}],pr:[{pr:[_]}],pb:[{pb:[_]}],pl:[{pl:[_]}],m:[{m:[y]}],mx:[{mx:[y]}],my:[{my:[y]}],ms:[{ms:[y]}],me:[{me:[y]}],mt:[{mt:[y]}],mr:[{mr:[y]}],mb:[{mb:[y]}],ml:[{ml:[y]}],"space-x":[{"space-x":[I]}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":[I]}],"space-y-reverse":["space-y-reverse"],w:[{w:["auto","min","max","fit","svw","lvw","dvw",Gc,t]}],"min-w":[{"min-w":[Gc,t,"min","max","fit"]}],"max-w":[{"max-w":[Gc,t,"none","full","min","max","fit","prose",{screen:[RA]},RA]}],h:[{h:[Gc,t,"auto","min","max","fit","svh","lvh","dvh"]}],"min-h":[{"min-h":[Gc,t,"min","max","fit","svh","lvh","dvh"]}],"max-h":[{"max-h":[Gc,t,"min","max","fit","svh","lvh","dvh"]}],size:[{size:[Gc,t,"auto","min","max","fit"]}],"font-size":[{text:["base",RA,LA]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:["thin","extralight","light","normal","medium","semibold","bold","extrabold","black",VPe]}],"font-family":[{font:[JH]}],"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",Gc]}],"line-clamp":[{"line-clamp":["none",vB,VPe]}],leading:[{leading:["none","tight","snug","normal","relaxed","loose",H4,Gc]}],"list-image":[{"list-image":["none",Gc]}],"list-style-type":[{list:["none","disc","decimal",Gc]}],"list-style-position":[{list:["inside","outside"]}],"placeholder-color":[{placeholder:[s]}],"placeholder-opacity":[{"placeholder-opacity":[v]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"text-color":[{text:[s]}],"text-opacity":[{"text-opacity":[v]}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...se(),"wavy"]}],"text-decoration-thickness":[{decoration:["auto","from-font",H4,LA]}],"underline-offset":[{"underline-offset":["auto",H4,Gc]}],"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:U()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",Gc]}],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",Gc]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-opacity":[{"bg-opacity":[v]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:[...Y(),sns]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",tns]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},rns]}],"bg-color":[{bg:[s]}],"gradient-from-pos":[{from:[g]}],"gradient-via-pos":[{via:[g]}],"gradient-to-pos":[{to:[g]}],"gradient-from":[{from:[p]}],"gradient-via":[{via:[p]}],"gradient-to":[{to:[p]}],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":[v]}],"border-style":[{border:[...se(),"hidden"]}],"divide-x":[{"divide-x":[o]}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":[o]}],"divide-y-reverse":["divide-y-reverse"],"divide-opacity":[{"divide-opacity":[v]}],"divide-style":[{divide:se()}],"border-color":[{border:[a]}],"border-color-x":[{"border-x":[a]}],"border-color-y":[{"border-y":[a]}],"border-color-s":[{"border-s":[a]}],"border-color-e":[{"border-e":[a]}],"border-color-t":[{"border-t":[a]}],"border-color-r":[{"border-r":[a]}],"border-color-b":[{"border-b":[a]}],"border-color-l":[{"border-l":[a]}],"divide-color":[{divide:[a]}],"outline-style":[{outline:["",...se()]}],"outline-offset":[{"outline-offset":[H4,Gc]}],"outline-w":[{outline:[H4,LA]}],"outline-color":[{outline:[s]}],"ring-w":[{ring:G()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:[s]}],"ring-opacity":[{"ring-opacity":[v]}],"ring-offset-w":[{"ring-offset":[H4,LA]}],"ring-offset-color":[{"ring-offset":[s]}],shadow:[{shadow:["","inner","none",RA,ans]}],"shadow-color":[{shadow:[JH]}],opacity:[{opacity:[v]}],"mix-blend":[{"mix-blend":[...ee(),"plus-lighter","plus-darker"]}],"bg-blend":[{"bg-blend":ee()}],filter:[{filter:["","none"]}],blur:[{blur:[n]}],brightness:[{brightness:[r]}],contrast:[{contrast:[c]}],"drop-shadow":[{"drop-shadow":["","none",RA,Gc]}],grayscale:[{grayscale:[d]}],"hue-rotate":[{"hue-rotate":[u]}],invert:[{invert:[h]}],saturate:[{saturate:[j]}],sepia:[{sepia:[A]}],"backdrop-filter":[{"backdrop-filter":["","none"]}],"backdrop-blur":[{"backdrop-blur":[n]}],"backdrop-brightness":[{"backdrop-brightness":[r]}],"backdrop-contrast":[{"backdrop-contrast":[c]}],"backdrop-grayscale":[{"backdrop-grayscale":[d]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[u]}],"backdrop-invert":[{"backdrop-invert":[h]}],"backdrop-opacity":[{"backdrop-opacity":[v]}],"backdrop-saturate":[{"backdrop-saturate":[j]}],"backdrop-sepia":[{"backdrop-sepia":[A]}],"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",Gc]}],duration:[{duration:te()}],ease:[{ease:["linear","in","out","in-out",Gc]}],delay:[{delay:te()}],animate:[{animate:["none","spin","ping","pulse","bounce",Gc]}],transform:[{transform:["","gpu","none"]}],scale:[{scale:[C]}],"scale-x":[{"scale-x":[C]}],"scale-y":[{"scale-y":[C]}],rotate:[{rotate:[QH,Gc]}],"translate-x":[{"translate-x":[P]}],"translate-y":[{"translate-y":[P]}],"skew-x":[{"skew-x":[M]}],"skew-y":[{"skew-y":[M]}],"transform-origin":[{origin:["center","top","top-right","right","bottom-right","bottom","bottom-left","left","top-left",Gc]}],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",Gc]}],"caret-color":[{caret:[s]}],"pointer-events":[{"pointer-events":["none","auto"]}],resize:[{resize:["none","y","x",""]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":U()}],"scroll-mx":[{"scroll-mx":U()}],"scroll-my":[{"scroll-my":U()}],"scroll-ms":[{"scroll-ms":U()}],"scroll-me":[{"scroll-me":U()}],"scroll-mt":[{"scroll-mt":U()}],"scroll-mr":[{"scroll-mr":U()}],"scroll-mb":[{"scroll-mb":U()}],"scroll-ml":[{"scroll-ml":U()}],"scroll-p":[{"scroll-p":U()}],"scroll-px":[{"scroll-px":U()}],"scroll-py":[{"scroll-py":U()}],"scroll-ps":[{"scroll-ps":U()}],"scroll-pe":[{"scroll-pe":U()}],"scroll-pt":[{"scroll-pt":U()}],"scroll-pr":[{"scroll-pr":U()}],"scroll-pb":[{"scroll-pb":U()}],"scroll-pl":[{"scroll-pl":U()}],"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",Gc]}],fill:[{fill:[s,"none"]}],"stroke-w":[{stroke:[H4,LA,VPe]}],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"]}}},dns=Hss(cns);function Ot(...s){return dns(bc(s))}function yh(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 Uat(s){const t=new Date(s);return new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric",year:"numeric"}).format(t)}function IZ(s){return s?s.replace(/<[^>]*>/g,""):""}const uns=Ess,xSt=k.forwardRef(({className:s,...t},n)=>e.jsx(nSt,{ref:n,className:Ot("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}));xSt.displayName=nSt.displayName;const hns=gF("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"}}),ySt=k.forwardRef(({className:s,variant:t,...n},r)=>e.jsx(rSt,{ref:r,className:Ot(hns({variant:t}),s),...n}));ySt.displayName=rSt.displayName;const mns=k.forwardRef(({className:s,...t},n)=>e.jsx(oSt,{ref:n,className:Ot("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}));mns.displayName=oSt.displayName;const vSt=k.forwardRef(({className:s,...t},n)=>e.jsx(lSt,{ref:n,className:Ot("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(mr,{className:"h-4 w-4"})}));vSt.displayName=lSt.displayName;const bSt=k.forwardRef(({className:s,...t},n)=>e.jsx(aSt,{ref:n,className:Ot("text-sm font-semibold",s),...t}));bSt.displayName=aSt.displayName;const _St=k.forwardRef(({className:s,...t},n)=>e.jsx(iSt,{ref:n,className:Ot("text-sm opacity-90",s),...t}));_St.displayName=iSt.displayName;function fns(){const{toasts:s}=Fi();return e.jsxs(uns,{children:[s.map(function({id:t,title:n,description:r,action:a,...i}){return e.jsxs(ySt,{...i,children:[e.jsxs("div",{className:"grid gap-1",children:[n&&e.jsx(bSt,{children:n}),r&&e.jsx(_St,{children:r})]}),a,e.jsx(vSt,{})]},t)}),e.jsx(xSt,{})]})}var qat=["light","dark"],pns="(prefers-color-scheme: dark)",gns=k.createContext(void 0),xns={setTheme:s=>{},themes:[]},yns=()=>{var s;return(s=k.useContext(gns))!=null?s:xns};k.memo(({forcedTheme:s,storageKey:t,attribute:n,enableSystem:r,enableColorScheme:a,defaultTheme:i,value:l,attrs:o,nonce:c})=>{let d=i==="system",u=n==="class"?`var d=document.documentElement,c=d.classList;${`c.remove(${o.map(g=>`'${g}'`).join(",")})`};`:`var d=document.documentElement,n='${n}',s='setAttribute';`,h=a?qat.includes(i)&&i?`if(e==='light'||e==='dark'||!e)d.style.colorScheme=e||'${i}'`:"if(e==='light'||e==='dark')d.style.colorScheme=e":"",m=(g,x=!1,y=!0)=>{let v=l?l[g]:g,_=x?g+"|| ''":`'${v}'`,j="";return a&&y&&!x&&qat.includes(g)&&(j+=`d.style.colorScheme = '${g}';`),n==="class"?x||v?j+=`c.add(${_})`:j+="null":v&&(j+=`d[s](n,${_})`),j},p=s?`!function(){${u}${m(s)}}()`:r?`!function(){try{${u}var e=localStorage.getItem('${t}');if('system'===e||(!e&&${d})){var t='${pns}',m=window.matchMedia(t);if(m.media!==t||m.matches){${m("dark")}}else{${m("light")}}}else if(e){${l?`var x=${JSON.stringify(l)};`:""}${m(l?"x[e]":"e",!0)}}${d?"":"else{"+m(i,!1,!1)+"}"}${h}}catch(e){}}()`:`!function(){try{${u}var e=localStorage.getItem('${t}');if(e){${l?`var x=${JSON.stringify(l)};`:""}${m(l?"x[e]":"e",!0)}}else{${m(i,!1,!1)};}${h}}catch(t){}}();`;return k.createElement("script",{nonce:c,dangerouslySetInnerHTML:{__html:p}})});var vns=s=>{switch(s){case"success":return wns;case"info":return Nns;case"warning":return jns;case"error":return kns;default:return null}},bns=Array(12).fill(0),_ns=({visible:s,className:t})=>zt.createElement("div",{className:["sonner-loading-wrapper",t].filter(Boolean).join(" "),"data-visible":s},zt.createElement("div",{className:"sonner-spinner"},bns.map((n,r)=>zt.createElement("div",{className:"sonner-loading-bar",key:`spinner-bar-${r}`})))),wns=zt.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},zt.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"})),jns=zt.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor",height:"20",width:"20"},zt.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"})),Nns=zt.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},zt.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"})),kns=zt.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},zt.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"})),Sns=zt.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"},zt.createElement("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),zt.createElement("line",{x1:"6",y1:"6",x2:"18",y2:"18"})),Cns=()=>{let[s,t]=zt.useState(document.hidden);return zt.useEffect(()=>{let n=()=>{t(document.hidden)};return document.addEventListener("visibilitychange",n),()=>window.removeEventListener("visibilitychange",n)},[]),s},cFe=1,Ans=class{constructor(){this.subscribe=t=>(this.subscribers.push(t),()=>{let n=this.subscribers.indexOf(t);this.subscribers.splice(n,1)}),this.publish=t=>{this.subscribers.forEach(n=>n(t))},this.addToast=t=>{this.publish(t),this.toasts=[...this.toasts,t]},this.create=t=>{var n;let{message:r,...a}=t,i=typeof(t==null?void 0:t.id)=="number"||((n=t.id)==null?void 0:n.length)>0?t.id:cFe++,l=this.toasts.find(c=>c.id===i),o=t.dismissible===void 0?!0:t.dismissible;return this.dismissedToasts.has(i)&&this.dismissedToasts.delete(i),l?this.toasts=this.toasts.map(c=>c.id===i?(this.publish({...c,...t,id:i,title:r}),{...c,...t,id:i,dismissible:o,title:r}):c):this.addToast({title:r,...a,dismissible:o,id:i}),i},this.dismiss=t=>(this.dismissedToasts.add(t),t||this.toasts.forEach(n=>{this.subscribers.forEach(r=>r({id:n.id,dismiss:!0}))}),this.subscribers.forEach(n=>n({id:t,dismiss:!0})),t),this.message=(t,n)=>this.create({...n,message:t}),this.error=(t,n)=>this.create({...n,message:t,type:"error"}),this.success=(t,n)=>this.create({...n,type:"success",message:t}),this.info=(t,n)=>this.create({...n,type:"info",message:t}),this.warning=(t,n)=>this.create({...n,type:"warning",message:t}),this.loading=(t,n)=>this.create({...n,type:"loading",message:t}),this.promise=(t,n)=>{if(!n)return;let r;n.loading!==void 0&&(r=this.create({...n,promise:t,type:"loading",message:n.loading,description:typeof n.description!="function"?n.description:void 0}));let a=t instanceof Promise?t:t(),i=r!==void 0,l,o=a.then(async d=>{if(l=["resolve",d],zt.isValidElement(d))i=!1,this.create({id:r,type:"default",message:d});else if(Tns(d)&&!d.ok){i=!1;let u=typeof n.error=="function"?await n.error(`HTTP error! status: ${d.status}`):n.error,h=typeof n.description=="function"?await n.description(`HTTP error! status: ${d.status}`):n.description;this.create({id:r,type:"error",message:u,description:h})}else if(n.success!==void 0){i=!1;let u=typeof n.success=="function"?await n.success(d):n.success,h=typeof n.description=="function"?await n.description(d):n.description;this.create({id:r,type:"success",message:u,description:h})}}).catch(async d=>{if(l=["reject",d],n.error!==void 0){i=!1;let u=typeof n.error=="function"?await n.error(d):n.error,h=typeof n.description=="function"?await n.description(d):n.description;this.create({id:r,type:"error",message:u,description:h})}}).finally(()=>{var d;i&&(this.dismiss(r),r=void 0),(d=n.finally)==null||d.call(n)}),c=()=>new Promise((d,u)=>o.then(()=>l[0]==="reject"?u(l[1]):d(l[1])).catch(u));return typeof r!="string"&&typeof r!="number"?{unwrap:c}:Object.assign(r,{unwrap:c})},this.custom=(t,n)=>{let r=(n==null?void 0:n.id)||cFe++;return this.create({jsx:t(r),id:r,...n}),r},this.getActiveToasts=()=>this.toasts.filter(t=>!this.dismissedToasts.has(t.id)),this.subscribers=[],this.toasts=[],this.dismissedToasts=new Set}},a_=new Ans,Ens=(s,t)=>{let n=(t==null?void 0:t.id)||cFe++;return a_.addToast({title:s,...t,id:n}),n},Tns=s=>s&&typeof s=="object"&&"ok"in s&&typeof s.ok=="boolean"&&"status"in s&&typeof s.status=="number",Mns=Ens,Pns=()=>a_.toasts,Ins=()=>a_.getActiveToasts(),ae=Object.assign(Mns,{success:a_.success,info:a_.info,warning:a_.warning,error:a_.error,custom:a_.custom,message:a_.message,promise:a_.promise,dismiss:a_.dismiss,loading:a_.loading},{getHistory:Pns,getToasts:Ins});function Lns(s,{insertAt:t}={}){if(typeof document>"u")return;let n=document.head||document.getElementsByTagName("head")[0],r=document.createElement("style");r.type="text/css",t==="top"&&n.firstChild?n.insertBefore(r,n.firstChild):n.appendChild(r),r.styleSheet?r.styleSheet.cssText=s:r.appendChild(document.createTextNode(s))}Lns(`: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 Ine(s){return s.label!==void 0}var Rns=3,Dns="32px",Ons="16px",Vat=4e3,Fns=356,zns=14,Bns=20,$ns=200;function dN(...s){return s.filter(Boolean).join(" ")}function Uns(s){let[t,n]=s.split("-"),r=[];return t&&r.push(t),n&&r.push(n),r}var qns=s=>{var t,n,r,a,i,l,o,c,d,u,h;let{invert:m,toast:p,unstyled:g,interacting:x,setHeights:y,visibleToasts:v,heights:_,index:j,toasts:C,expanded:A,removeToast:M,defaultRichColors:I,closeButton:P,style:R,cancelButtonStyle:O,actionButtonStyle:B,className:U="",descriptionClassName:G="",duration:H,position:Y,gap:se,loadingIcon:ee,expandByDefault:oe,classNames:me,icons:Q,closeButtonAriaLabel:te="Close toast",pauseWhenPageIsHidden:le}=s,[fe,_e]=zt.useState(null),[ve,he]=zt.useState(null),[Se,Te]=zt.useState(!1),[Ie,Ue]=zt.useState(!1),[Be,je]=zt.useState(!1),[Ye,Ee]=zt.useState(!1),[Re,ke]=zt.useState(!1),[Fe,Oe]=zt.useState(0),[Ge,yt]=zt.useState(0),tt=zt.useRef(p.duration||H||Vat),ut=zt.useRef(null),nt=zt.useRef(null),et=j===0,at=j+1<=v,wt=p.type,rt=p.dismissible!==!1,Ft=p.className||"",Ut=p.descriptionClassName||"",Is=zt.useMemo(()=>_.findIndex(un=>un.toastId===p.id)||0,[_,p.id]),xs=zt.useMemo(()=>{var un;return(un=p.closeButton)!=null?un:P},[p.closeButton,P]),st=zt.useMemo(()=>p.duration||H||Vat,[p.duration,H]),dt=zt.useRef(0),jt=zt.useRef(0),gt=zt.useRef(0),rs=zt.useRef(null),[Ns,us]=Y.split("-"),Bs=zt.useMemo(()=>_.reduce((un,jr,Ln)=>Ln>=Is?un:un+jr.height,0),[_,Is]),Ts=Cns(),Fn=p.invert||m,An=wt==="loading";jt.current=zt.useMemo(()=>Is*se+Bs,[Is,Bs]),zt.useEffect(()=>{tt.current=st},[st]),zt.useEffect(()=>{Te(!0)},[]),zt.useEffect(()=>{let un=nt.current;if(un){let jr=un.getBoundingClientRect().height;return yt(jr),y(Ln=>[{toastId:p.id,height:jr,position:p.position},...Ln]),()=>y(Ln=>Ln.filter(Sr=>Sr.toastId!==p.id))}},[y,p.id]),zt.useLayoutEffect(()=>{if(!Se)return;let un=nt.current,jr=un.style.height;un.style.height="auto";let Ln=un.getBoundingClientRect().height;un.style.height=jr,yt(Ln),y(Sr=>Sr.find(Qn=>Qn.toastId===p.id)?Sr.map(Qn=>Qn.toastId===p.id?{...Qn,height:Ln}:Qn):[{toastId:p.id,height:Ln,position:p.position},...Sr])},[Se,p.title,p.description,y,p.id]);let js=zt.useCallback(()=>{Ue(!0),Oe(jt.current),y(un=>un.filter(jr=>jr.toastId!==p.id)),setTimeout(()=>{M(p)},$ns)},[p,M,y,jt]);zt.useEffect(()=>{if(p.promise&&wt==="loading"||p.duration===1/0||p.type==="loading")return;let un;return A||x||le&&Ts?(()=>{if(gt.current{var jr;(jr=p.onAutoClose)==null||jr.call(p,p),js()},tt.current)),()=>clearTimeout(un)},[A,x,p,wt,le,Ts,js]),zt.useEffect(()=>{p.delete&&js()},[js,p.delete]);function In(){var un,jr,Ln;return Q!=null&&Q.loading?zt.createElement("div",{className:dN(me==null?void 0:me.loader,(un=p==null?void 0:p.classNames)==null?void 0:un.loader,"sonner-loader"),"data-visible":wt==="loading"},Q.loading):ee?zt.createElement("div",{className:dN(me==null?void 0:me.loader,(jr=p==null?void 0:p.classNames)==null?void 0:jr.loader,"sonner-loader"),"data-visible":wt==="loading"},ee):zt.createElement(_ns,{className:dN(me==null?void 0:me.loader,(Ln=p==null?void 0:p.classNames)==null?void 0:Ln.loader),visible:wt==="loading"})}return zt.createElement("li",{tabIndex:0,ref:nt,className:dN(U,Ft,me==null?void 0:me.toast,(t=p==null?void 0:p.classNames)==null?void 0:t.toast,me==null?void 0:me.default,me==null?void 0:me[wt],(n=p==null?void 0:p.classNames)==null?void 0:n[wt]),"data-sonner-toast":"","data-rich-colors":(r=p.richColors)!=null?r:I,"data-styled":!(p.jsx||p.unstyled||g),"data-mounted":Se,"data-promise":!!p.promise,"data-swiped":Re,"data-removed":Ie,"data-visible":at,"data-y-position":Ns,"data-x-position":us,"data-index":j,"data-front":et,"data-swiping":Be,"data-dismissible":rt,"data-type":wt,"data-invert":Fn,"data-swipe-out":Ye,"data-swipe-direction":ve,"data-expanded":!!(A||oe&&Se),style:{"--index":j,"--toasts-before":j,"--z-index":C.length-j,"--offset":`${Ie?Fe:jt.current}px`,"--initial-height":oe?"auto":`${Ge}px`,...R,...p.style},onDragEnd:()=>{je(!1),_e(null),rs.current=null},onPointerDown:un=>{An||!rt||(ut.current=new Date,Oe(jt.current),un.target.setPointerCapture(un.pointerId),un.target.tagName!=="BUTTON"&&(je(!0),rs.current={x:un.clientX,y:un.clientY}))},onPointerUp:()=>{var un,jr,Ln,Sr;if(Ye||!rt)return;rs.current=null;let Qn=Number(((un=nt.current)==null?void 0:un.style.getPropertyValue("--swipe-amount-x").replace("px",""))||0),En=Number(((jr=nt.current)==null?void 0:jr.style.getPropertyValue("--swipe-amount-y").replace("px",""))||0),pr=new Date().getTime()-((Ln=ut.current)==null?void 0:Ln.getTime()),xn=fe==="x"?Qn:En,Ar=Math.abs(xn)/pr;if(Math.abs(xn)>=Bns||Ar>.11){Oe(jt.current),(Sr=p.onDismiss)==null||Sr.call(p,p),he(fe==="x"?Qn>0?"right":"left":En>0?"down":"up"),js(),Ee(!0),ke(!1);return}je(!1),_e(null)},onPointerMove:un=>{var jr,Ln,Sr,Qn;if(!rs.current||!rt||((jr=window.getSelection())==null?void 0:jr.toString().length)>0)return;let En=un.clientY-rs.current.y,pr=un.clientX-rs.current.x,xn=(Ln=s.swipeDirections)!=null?Ln:Uns(Y);!fe&&(Math.abs(pr)>1||Math.abs(En)>1)&&_e(Math.abs(pr)>Math.abs(En)?"x":"y");let Ar={x:0,y:0};fe==="y"?(xn.includes("top")||xn.includes("bottom"))&&(xn.includes("top")&&En<0||xn.includes("bottom")&&En>0)&&(Ar.y=En):fe==="x"&&(xn.includes("left")||xn.includes("right"))&&(xn.includes("left")&&pr<0||xn.includes("right")&&pr>0)&&(Ar.x=pr),(Math.abs(Ar.x)>0||Math.abs(Ar.y)>0)&&ke(!0),(Sr=nt.current)==null||Sr.style.setProperty("--swipe-amount-x",`${Ar.x}px`),(Qn=nt.current)==null||Qn.style.setProperty("--swipe-amount-y",`${Ar.y}px`)}},xs&&!p.jsx?zt.createElement("button",{"aria-label":te,"data-disabled":An,"data-close-button":!0,onClick:An||!rt?()=>{}:()=>{var un;js(),(un=p.onDismiss)==null||un.call(p,p)},className:dN(me==null?void 0:me.closeButton,(a=p==null?void 0:p.classNames)==null?void 0:a.closeButton)},(i=Q==null?void 0:Q.close)!=null?i:Sns):null,p.jsx||k.isValidElement(p.title)?p.jsx?p.jsx:typeof p.title=="function"?p.title():p.title:zt.createElement(zt.Fragment,null,wt||p.icon||p.promise?zt.createElement("div",{"data-icon":"",className:dN(me==null?void 0:me.icon,(l=p==null?void 0:p.classNames)==null?void 0:l.icon)},p.promise||p.type==="loading"&&!p.icon?p.icon||In():null,p.type!=="loading"?p.icon||(Q==null?void 0:Q[wt])||vns(wt):null):null,zt.createElement("div",{"data-content":"",className:dN(me==null?void 0:me.content,(o=p==null?void 0:p.classNames)==null?void 0:o.content)},zt.createElement("div",{"data-title":"",className:dN(me==null?void 0:me.title,(c=p==null?void 0:p.classNames)==null?void 0:c.title)},typeof p.title=="function"?p.title():p.title),p.description?zt.createElement("div",{"data-description":"",className:dN(G,Ut,me==null?void 0:me.description,(d=p==null?void 0:p.classNames)==null?void 0:d.description)},typeof p.description=="function"?p.description():p.description):null),k.isValidElement(p.cancel)?p.cancel:p.cancel&&Ine(p.cancel)?zt.createElement("button",{"data-button":!0,"data-cancel":!0,style:p.cancelButtonStyle||O,onClick:un=>{var jr,Ln;Ine(p.cancel)&&rt&&((Ln=(jr=p.cancel).onClick)==null||Ln.call(jr,un),js())},className:dN(me==null?void 0:me.cancelButton,(u=p==null?void 0:p.classNames)==null?void 0:u.cancelButton)},p.cancel.label):null,k.isValidElement(p.action)?p.action:p.action&&Ine(p.action)?zt.createElement("button",{"data-button":!0,"data-action":!0,style:p.actionButtonStyle||B,onClick:un=>{var jr,Ln;Ine(p.action)&&((Ln=(jr=p.action).onClick)==null||Ln.call(jr,un),!un.defaultPrevented&&js())},className:dN(me==null?void 0:me.actionButton,(h=p==null?void 0:p.classNames)==null?void 0:h.actionButton)},p.action.label):null))};function Hat(){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 Vns(s,t){let n={};return[s,t].forEach((r,a)=>{let i=a===1,l=i?"--mobile-offset":"--offset",o=i?Ons:Dns;function c(d){["top","right","bottom","left"].forEach(u=>{n[`${l}-${u}`]=typeof d=="number"?`${d}px`:d})}typeof r=="number"||typeof r=="string"?c(r):typeof r=="object"?["top","right","bottom","left"].forEach(d=>{r[d]===void 0?n[`${l}-${d}`]=o:n[`${l}-${d}`]=typeof r[d]=="number"?`${r[d]}px`:r[d]}):c(o)}),n}var Hns=k.forwardRef(function(s,t){let{invert:n,position:r="bottom-right",hotkey:a=["altKey","KeyT"],expand:i,closeButton:l,className:o,offset:c,mobileOffset:d,theme:u="light",richColors:h,duration:m,style:p,visibleToasts:g=Rns,toastOptions:x,dir:y=Hat(),gap:v=zns,loadingIcon:_,icons:j,containerAriaLabel:C="Notifications",pauseWhenPageIsHidden:A}=s,[M,I]=zt.useState([]),P=zt.useMemo(()=>Array.from(new Set([r].concat(M.filter(le=>le.position).map(le=>le.position)))),[M,r]),[R,O]=zt.useState([]),[B,U]=zt.useState(!1),[G,H]=zt.useState(!1),[Y,se]=zt.useState(u!=="system"?u:typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"),ee=zt.useRef(null),oe=a.join("+").replace(/Key/g,"").replace(/Digit/g,""),me=zt.useRef(null),Q=zt.useRef(!1),te=zt.useCallback(le=>{I(fe=>{var _e;return(_e=fe.find(ve=>ve.id===le.id))!=null&&_e.delete||a_.dismiss(le.id),fe.filter(({id:ve})=>ve!==le.id)})},[]);return zt.useEffect(()=>a_.subscribe(le=>{if(le.dismiss){I(fe=>fe.map(_e=>_e.id===le.id?{..._e,delete:!0}:_e));return}setTimeout(()=>{bkt.flushSync(()=>{I(fe=>{let _e=fe.findIndex(ve=>ve.id===le.id);return _e!==-1?[...fe.slice(0,_e),{...fe[_e],...le},...fe.slice(_e+1)]:[le,...fe]})})})}),[]),zt.useEffect(()=>{if(u!=="system"){se(u);return}if(u==="system"&&(window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?se("dark"):se("light")),typeof window>"u")return;let le=window.matchMedia("(prefers-color-scheme: dark)");try{le.addEventListener("change",({matches:fe})=>{se(fe?"dark":"light")})}catch{le.addListener(({matches:_e})=>{try{se(_e?"dark":"light")}catch(ve){console.error(ve)}})}},[u]),zt.useEffect(()=>{M.length<=1&&U(!1)},[M]),zt.useEffect(()=>{let le=fe=>{var _e,ve;a.every(he=>fe[he]||fe.code===he)&&(U(!0),(_e=ee.current)==null||_e.focus()),fe.code==="Escape"&&(document.activeElement===ee.current||(ve=ee.current)!=null&&ve.contains(document.activeElement))&&U(!1)};return document.addEventListener("keydown",le),()=>document.removeEventListener("keydown",le)},[a]),zt.useEffect(()=>{if(ee.current)return()=>{me.current&&(me.current.focus({preventScroll:!0}),me.current=null,Q.current=!1)}},[ee.current]),zt.createElement("section",{ref:t,"aria-label":`${C} ${oe}`,tabIndex:-1,"aria-live":"polite","aria-relevant":"additions text","aria-atomic":"false",suppressHydrationWarning:!0},P.map((le,fe)=>{var _e;let[ve,he]=le.split("-");return M.length?zt.createElement("ol",{key:le,dir:y==="auto"?Hat():y,tabIndex:-1,ref:ee,className:o,"data-sonner-toaster":!0,"data-theme":Y,"data-y-position":ve,"data-lifted":B&&M.length>1&&!i,"data-x-position":he,style:{"--front-toast-height":`${((_e=R[0])==null?void 0:_e.height)||0}px`,"--width":`${Fns}px`,"--gap":`${v}px`,...p,...Vns(c,d)},onBlur:Se=>{Q.current&&!Se.currentTarget.contains(Se.relatedTarget)&&(Q.current=!1,me.current&&(me.current.focus({preventScroll:!0}),me.current=null))},onFocus:Se=>{Se.target instanceof HTMLElement&&Se.target.dataset.dismissible==="false"||Q.current||(Q.current=!0,me.current=Se.relatedTarget)},onMouseEnter:()=>U(!0),onMouseMove:()=>U(!0),onMouseLeave:()=>{G||U(!1)},onDragEnd:()=>U(!1),onPointerDown:Se=>{Se.target instanceof HTMLElement&&Se.target.dataset.dismissible==="false"||H(!0)},onPointerUp:()=>H(!1)},M.filter(Se=>!Se.position&&fe===0||Se.position===le).map((Se,Te)=>{var Ie,Ue;return zt.createElement(qns,{key:Se.id,icons:j,index:Te,toast:Se,defaultRichColors:h,duration:(Ie=x==null?void 0:x.duration)!=null?Ie:m,className:x==null?void 0:x.className,descriptionClassName:x==null?void 0:x.descriptionClassName,invert:n,visibleToasts:g,closeButton:(Ue=x==null?void 0:x.closeButton)!=null?Ue:l,interacting:G,position:le,style:x==null?void 0:x.style,unstyled:x==null?void 0:x.unstyled,classNames:x==null?void 0:x.classNames,cancelButtonStyle:x==null?void 0:x.cancelButtonStyle,actionButtonStyle:x==null?void 0:x.actionButtonStyle,removeToast:te,toasts:M.filter(Be=>Be.position==Se.position),heights:R.filter(Be=>Be.position==Se.position),setHeights:O,expandByDefault:i,gap:v,loadingIcon:_,expanded:B,pauseWhenPageIsHidden:A,swipeDirections:s.swipeDirections})})):null}))});const Gns=({...s})=>{const{theme:t="system"}=yns();return e.jsx(Hns,{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 Wns=Object.defineProperty,Kns=(s,t)=>Wns(s,"name",{value:t,configurable:!0}),Yns=uF[" useId ".trim().toString()]||(()=>{}),Zns=0;function $x(s){const[t,n]=k.useState(Yns());return _m(()=>{s||n(r=>r??String(Zns++))},[s]),s||(t?`radix-${t}`:"")}Kns($x,"useId");var Xns=Object.defineProperty,rb=(s,t)=>Xns(s,"name",{value:t,configurable:!0}),HPe="focusScope.autoFocusOnMount",GPe="focusScope.autoFocusOnUnmount",Gat={bubbles:!1,cancelable:!0},r3e=k.forwardRef(rb(function(t,n){const{loop:r=!1,trapped:a=!1,onMountAutoFocus:i,onUnmountAutoFocus:l,...o}=t,[c,d]=k.useState(null),u=sp(i),h=sp(l),m=k.useRef(null),p=Ao(n,d),g=k.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;k.useEffect(()=>{if(a){let y=function(C){if(g.paused||!c)return;const A=C.target;c.contains(A)?m.current=A:fC(m.current,{select:!0})},v=function(C){if(g.paused||!c)return;const A=C.relatedTarget;A!==null&&(c.contains(A)||fC(m.current,{select:!0}))},_=function(C){if(document.activeElement===document.body)for(const M of C)M.removedNodes.length>0&&fC(c)};rb(y,"handleFocusIn"),rb(v,"handleFocusOut"),rb(_,"handleMutations"),document.addEventListener("focusin",y),document.addEventListener("focusout",v);const j=new MutationObserver(_);return c&&j.observe(c,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",y),document.removeEventListener("focusout",v),j.disconnect()}}},[a,c,g.paused]),k.useEffect(()=>{if(c){Wat.add(g);const y=document.activeElement;if(!c.contains(y)){const _=new CustomEvent(HPe,Gat);c.addEventListener(HPe,u),c.dispatchEvent(_),_.defaultPrevented||(wSt(CSt(KVe(c)),{select:!0}),document.activeElement===y&&fC(c))}return()=>{c.removeEventListener(HPe,u),setTimeout(()=>{const _=new CustomEvent(GPe,Gat);c.addEventListener(GPe,h),c.dispatchEvent(_),_.defaultPrevented||fC(y??document.body,{select:!0}),c.removeEventListener(GPe,h),Wat.remove(g)},0)}}},[c,u,h,g]);const x=k.useCallback(y=>{if(!r&&!a||g.paused)return;const v=y.key==="Tab"&&!y.altKey&&!y.ctrlKey&&!y.metaKey,_=document.activeElement;if(v&&_){const j=y.currentTarget,[C,A]=jSt(j);C&&A?!y.shiftKey&&_===A?(y.preventDefault(),r&&fC(C,{select:!0})):y.shiftKey&&_===C&&(y.preventDefault(),r&&fC(A,{select:!0})):_===j&&y.preventDefault()}},[r,a,g.paused]);return e.jsx(hi.div,{tabIndex:-1,...o,ref:p,onKeyDown:x})},"FocusScope"));function wSt(s,{select:t=!1}={}){const n=document.activeElement;for(const r of s)if(fC(r,{select:t}),document.activeElement!==n)return}rb(wSt,"focusFirst");function jSt(s){const t=KVe(s),n=dFe(t,s),r=dFe(t.reverse(),s);return[n,r]}rb(jSt,"getTabbableEdges");function KVe(s){const t=[],n=document.createTreeWalker(s,NodeFilter.SHOW_ELEMENT,{acceptNode:rb(r=>{const a=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||a?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP},"acceptNode")});for(;n.nextNode();)t.push(n.currentNode);return t}rb(KVe,"getTabbableCandidates");function dFe(s,t){const n=typeof t.checkVisibility=="function"&&t.checkVisibility({checkVisibilityCSS:!0});for(const r of s)if(!(n?!r.checkVisibility({checkVisibilityCSS:!0}):NSt(r,{upTo:t})))return r}rb(dFe,"findVisible");function NSt(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}rb(NSt,"isHidden");function kSt(s){return s instanceof HTMLInputElement&&"select"in s}rb(kSt,"isSelectableInput");function fC(s,{select:t=!1}={}){if(s&&s.focus){const n=document.activeElement;s.focus({preventScroll:!0}),s!==n&&kSt(s)&&t&&s.select()}}rb(fC,"focus");var Wat=SSt();function SSt(){let s=[];return{add(t){const n=s[0];t!==n&&(n==null||n.pause()),s=uFe(s,t),s.unshift(t)},remove(t){var n;s=uFe(s,t),(n=s[0])==null||n.resume()}}}rb(SSt,"createFocusScopesStack");function uFe(s,t){const n=[...s],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}rb(uFe,"arrayRemove");function CSt(s){return s.filter(t=>t.tagName!=="A")}rb(CSt,"removeLinks");var Qns=Object.defineProperty,YVe=(s,t)=>Qns(s,"name",{value:t,configurable:!0}),Lne=0,lS=null;function Jns(s){return Mq(),s.children}YVe(Jns,"FocusGuards");function Mq(){k.useEffect(()=>{lS||(lS={start:hFe(),end:hFe()});const{start:s,end:t}=lS;return document.body.firstElementChild!==s&&document.body.insertAdjacentElement("afterbegin",s),document.body.lastElementChild!==t&&document.body.insertAdjacentElement("beforeend",t),Lne++,()=>{Lne===1&&(lS==null||lS.start.remove(),lS==null||lS.end.remove(),lS=null),Lne=Math.max(0,Lne-1)}},[])}YVe(Mq,"useFocusGuards");function hFe(){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}YVe(hFe,"createFocusGuard");var l5=function(){return l5=Object.assign||function(t){for(var n,r=1,a=arguments.length;r"u")return grs;var t=xrs(s),n=document.documentElement.clientWidth,r=window.innerWidth;return{left:t[0],top:t[1],right:t[2],gap:Math.max(0,r-n+t[2]-t[0])}},vrs=MSt(),bB="data-scroll-locked",brs=function(s,t,n,r){var a=s.left,i=s.top,l=s.right,o=s.gap;return n===void 0&&(n="margin"),` .`.concat(trs,` { overflow: hidden `).concat(r,`; padding-right: `).concat(o,"px ").concat(r,`; } body[`).concat(bB,`] { overflow: hidden `).concat(r,`; overscroll-behavior: contain; `).concat([t&&"position: relative ".concat(r,";"),n==="margin"&&` padding-left: `.concat(a,`px; padding-top: `).concat(i,`px; padding-right: `).concat(l,`px; margin-left:0; margin-top:0; margin-right: `).concat(o,"px ").concat(r,`; `),n==="padding"&&"padding-right: ".concat(o,"px ").concat(r,";")].filter(Boolean).join(""),` } .`).concat(W2e,` { right: `).concat(o,"px ").concat(r,`; } .`).concat(K2e,` { margin-right: `).concat(o,"px ").concat(r,`; } .`).concat(W2e," .").concat(W2e,` { right: 0 `).concat(r,`; } .`).concat(K2e," .").concat(K2e,` { margin-right: 0 `).concat(r,`; } body[`).concat(bB,`] { `).concat(srs,": ").concat(o,`px; } `)},Yat=function(){var s=parseInt(document.body.getAttribute(bB)||"0",10);return isFinite(s)?s:0},_rs=function(){k.useEffect(function(){return document.body.setAttribute(bB,(Yat()+1).toString()),function(){var s=Yat()-1;s<=0?document.body.removeAttribute(bB):document.body.setAttribute(bB,s.toString())}},[])},wrs=function(s){var t=s.noRelative,n=s.noImportant,r=s.gapMode,a=r===void 0?"margin":r;_rs();var i=k.useMemo(function(){return yrs(a)},[a]);return k.createElement(vrs,{styles:brs(i,!t,a,n?"":"!important")})},mFe=!1;if(typeof window<"u")try{var Rne=Object.defineProperty({},"passive",{get:function(){return mFe=!0,!0}});window.addEventListener("test",Rne,Rne),window.removeEventListener("test",Rne,Rne)}catch{mFe=!1}var L7=mFe?{passive:!1}:!1,jrs=function(s){return s.tagName==="TEXTAREA"},PSt=function(s,t){if(!(s instanceof Element))return!1;var n=window.getComputedStyle(s);return n[t]!=="hidden"&&!(n.overflowY===n.overflowX&&!jrs(s)&&n[t]==="visible")},Nrs=function(s){return PSt(s,"overflowY")},krs=function(s){return PSt(s,"overflowX")},Zat=function(s,t){var n=t.ownerDocument,r=t;do{typeof ShadowRoot<"u"&&r instanceof ShadowRoot&&(r=r.host);var a=ISt(s,r);if(a){var i=LSt(s,r),l=i[1],o=i[2];if(l>o)return!0}r=r.parentNode}while(r&&r!==n.body);return!1},Srs=function(s){var t=s.scrollTop,n=s.scrollHeight,r=s.clientHeight;return[t,n,r]},Crs=function(s){var t=s.scrollLeft,n=s.scrollWidth,r=s.clientWidth;return[t,n,r]},ISt=function(s,t){return s==="v"?Nrs(t):krs(t)},LSt=function(s,t){return s==="v"?Srs(t):Crs(t)},Ars=function(s,t){return s==="h"&&t==="rtl"?-1:1},Ers=function(s,t,n,r,a){var i=Ars(s,window.getComputedStyle(t).direction),l=i*r,o=n.target,c=t.contains(o),d=!1,u=l>0,h=0,m=0;do{if(!o)break;var p=LSt(s,o),g=p[0],x=p[1],y=p[2],v=x-y-i*g;(g||v)&&ISt(s,o)&&(h+=v,m+=g);var _=o.parentNode;o=_&&_.nodeType===Node.DOCUMENT_FRAGMENT_NODE?_.host:_}while(!c&&o!==document.body||c&&(t.contains(o)||t===o));return(u&&Math.abs(h)<1||!u&&Math.abs(m)<1)&&(d=!0),d},Dne=function(s){return"changedTouches"in s?[s.changedTouches[0].clientX,s.changedTouches[0].clientY]:[0,0]},Xat=function(s){return[s.deltaX,s.deltaY]},Qat=function(s){return s&&"current"in s?s.current:s},Trs=function(s,t){return s[0]===t[0]&&s[1]===t[1]},Mrs=function(s){return` .block-interactivity-`.concat(s,` {pointer-events: none;} .allow-interactivity-`).concat(s,` {pointer-events: all;} `)},Prs=0,R7=[];function Irs(s){var t=k.useRef([]),n=k.useRef([0,0]),r=k.useRef(),a=k.useState(Prs++)[0],i=k.useState(MSt)[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 x=ers([s.lockRef.current],(s.shards||[]).map(Qat),!0).filter(Boolean);return x.forEach(function(y){return y.classList.add("allow-interactivity-".concat(a))}),function(){document.body.classList.remove("block-interactivity-".concat(a)),x.forEach(function(y){return y.classList.remove("allow-interactivity-".concat(a))})}}},[s.inert,s.lockRef.current,s.shards]);var o=k.useCallback(function(x,y){if("touches"in x&&x.touches.length===2||x.type==="wheel"&&x.ctrlKey)return!l.current.allowPinchZoom;var v=Dne(x),_=n.current,j="deltaX"in x?x.deltaX:_[0]-v[0],C="deltaY"in x?x.deltaY:_[1]-v[1],A,M=x.target,I=Math.abs(j)>Math.abs(C)?"h":"v";if("touches"in x&&I==="h"&&M.type==="range")return!1;var P=window.getSelection(),R=P&&P.anchorNode,O=R?R===M||R.contains(M):!1;if(O)return!1;var B=Zat(I,M);if(!B)return!0;if(B?A=I:(A=I==="v"?"h":"v",B=Zat(I,M)),!B)return!1;if(!r.current&&"changedTouches"in x&&(j||C)&&(r.current=A),!A)return!0;var U=r.current||A;return Ers(U,y,x,U==="h"?j:C)},[]),c=k.useCallback(function(x){var y=x;if(!(!R7.length||R7[R7.length-1]!==i)){var v="deltaY"in y?Xat(y):Dne(y),_=t.current.filter(function(A){return A.name===y.type&&(A.target===y.target||y.target===A.shadowParent)&&Trs(A.delta,v)})[0];if(_&&_.should){y.cancelable&&y.preventDefault();return}if(!_){var j=(l.current.shards||[]).map(Qat).filter(Boolean).filter(function(A){return A.contains(y.target)}),C=j.length>0?o(y,j[0]):!l.current.noIsolation;C&&y.cancelable&&y.preventDefault()}}},[]),d=k.useCallback(function(x,y,v,_){var j={name:x,delta:y,target:v,should:_,shadowParent:Lrs(v)};t.current.push(j),setTimeout(function(){t.current=t.current.filter(function(C){return C!==j})},1)},[]),u=k.useCallback(function(x){n.current=Dne(x),r.current=void 0},[]),h=k.useCallback(function(x){d(x.type,Xat(x),x.target,o(x,s.lockRef.current))},[]),m=k.useCallback(function(x){d(x.type,Dne(x),x.target,o(x,s.lockRef.current))},[]);k.useEffect(function(){return R7.push(i),s.setCallbacks({onScrollCapture:h,onWheelCapture:h,onTouchMoveCapture:m}),document.addEventListener("wheel",c,L7),document.addEventListener("touchmove",c,L7),document.addEventListener("touchstart",u,L7),function(){R7=R7.filter(function(x){return x!==i}),document.removeEventListener("wheel",c,L7),document.removeEventListener("touchmove",c,L7),document.removeEventListener("touchstart",u,L7)}},[]);var p=s.removeScrollBar,g=s.inert;return k.createElement(k.Fragment,null,g?k.createElement(i,{styles:Mrs(a)}):null,p?k.createElement(wrs,{noRelative:s.noRelative,gapMode:s.gapMode}):null)}function Lrs(s){for(var t=null;s!==null;)s instanceof ShadowRoot&&(t=s.host,s=s.host),s=s.parentNode;return t}const Rrs=crs(TSt,Irs);var eee=k.forwardRef(function(s,t){return k.createElement(a3e,l5({},s,{ref:t,sideCar:Rrs}))});eee.classNames=a3e.classNames;var Drs=function(s){if(typeof document>"u")return null;var t=Array.isArray(s)?s[0]:s;return t.ownerDocument.body},D7=new WeakMap,One=new WeakMap,Fne={},ZPe=0,RSt=function(s){return s&&(s.host||RSt(s.parentNode))},Ors=function(s,t){return t.map(function(n){if(s.contains(n))return n;var r=RSt(n);return r&&s.contains(r)?r:(console.error("aria-hidden",n,"in not contained inside",s,". Doing nothing"),null)}).filter(function(n){return!!n})},Frs=function(s,t,n,r){var a=Ors(t,Array.isArray(s)?s:[s]);Fne[n]||(Fne[n]=new WeakMap);var i=Fne[n],l=[],o=new Set,c=new Set(a),d=function(h){!h||o.has(h)||(o.add(h),d(h.parentNode))};a.forEach(d);var u=function(h){!h||c.has(h)||Array.prototype.forEach.call(h.children,function(m){if(o.has(m))u(m);else try{var p=m.getAttribute(r),g=p!==null&&p!=="false",x=(D7.get(m)||0)+1,y=(i.get(m)||0)+1;D7.set(m,x),i.set(m,y),l.push(m),x===1&&g&&One.set(m,!0),y===1&&m.setAttribute(n,"true"),g||m.setAttribute(r,"true")}catch(v){console.error("aria-hidden: cannot operate on ",m,v)}})};return u(t),o.clear(),ZPe++,function(){l.forEach(function(h){var m=D7.get(h)-1,p=i.get(h)-1;D7.set(h,m),i.set(h,p),m||(One.has(h)||h.removeAttribute(r),One.delete(h)),p||h.removeAttribute(n)}),ZPe--,ZPe||(D7=new WeakMap,D7=new WeakMap,One=new WeakMap,Fne={})}},i3e=function(s,t,n){n===void 0&&(n="data-aria-hidden");var r=Array.from(Array.isArray(s)?s:[s]),a=Drs(s);return a?(r.push.apply(r,Array.from(a.querySelectorAll("[aria-live], script"))),Frs(r,a,n,"aria-hidden")):function(){return null}},zrs=Object.defineProperty,pj=(s,t)=>zrs(s,"name",{value:t,configurable:!0}),ZVe="Dialog",[DSt,OSt]=qm(ZVe),[Brs,kk]=DSt(ZVe),o3e=pj(s=>{const{__scopeDialog:t,children:n,open:r,defaultOpen:a,onOpenChange:i,modal:l=!0}=s,o=k.useRef(null),c=k.useRef(null),[d,u]=ox({prop:r,defaultProp:a??!1,onChange:i,caller:ZVe}),[h,m]=k.useState(0),[p,g]=k.useState(0);return e.jsx(Brs,{scope:t,triggerRef:o,contentRef:c,contentId:$x(),titleId:$x(),descriptionId:$x(),titlePresent:h>0,descriptionPresent:p>0,setTitleCount:m,setDescriptionCount:g,open:d,onOpenChange:u,onOpenToggle:k.useCallback(()=>u(x=>!x),[u]),modal:l,children:n})},"Dialog"),$rs="DialogTrigger",XVe=k.forwardRef(pj(function(t,n){const{__scopeDialog:r,...a}=t,i=kk($rs,r),l=Ao(n,i.triggerRef);return e.jsx(hi.button,{type:"button","aria-haspopup":"dialog","aria-expanded":i.open,"aria-controls":i.open?i.contentId:void 0,"data-state":c3e(i.open),...a,ref:l,onClick:ga(t.onClick,i.onOpenToggle)})},"DialogTrigger")),FSt="DialogPortal",[Urs,zSt]=DSt(FSt,{forceMount:void 0}),l3e=pj(s=>{const{__scopeDialog:t,forceMount:n,children:r,container:a}=s,i=kk(FSt,t);return e.jsx(Urs,{scope:t,forceMount:n,children:k.Children.map(r,l=>e.jsx(cx,{present:n||i.open,children:e.jsx(QJ,{asChild:!0,container:a,children:l})}))})},"DialogPortal"),fFe="DialogOverlay",Pq=k.forwardRef(pj(function(t,n){const r=zSt(fFe,t.__scopeDialog),{forceMount:a=r.forceMount,...i}=t,l=kk(fFe,t.__scopeDialog);return l.modal?e.jsx(cx,{present:a||l.open,children:e.jsx(Vrs,{...i,ref:n})}):null},"DialogOverlay")),qrs=xk("DialogOverlay.RemoveScroll"),Vrs=k.forwardRef(pj(function(t,n){const{__scopeDialog:r,...a}=t,i=kk(fFe,r),l=Fkt(),o=Ao(n,l);return e.jsx(eee,{as:qrs,allowPinchZoom:!0,shards:[i.contentRef],children:e.jsx(hi.div,{"data-state":c3e(i.open),...a,ref:o,style:{pointerEvents:"auto",...a.style}})})},"DialogOverlayImpl")),LZ="DialogContent",Iq=k.forwardRef(pj(function(t,n){const r=zSt(LZ,t.__scopeDialog),{forceMount:a=r.forceMount,...i}=t,l=kk(LZ,t.__scopeDialog);return e.jsx(cx,{present:a||l.open,children:l.modal?e.jsx(Hrs,{...i,ref:n}):e.jsx(Grs,{...i,ref:n})})},"DialogContent")),Hrs=k.forwardRef(pj(function(t,n){const r=kk(LZ,t.__scopeDialog),a=k.useRef(null),i=Ao(n,r.contentRef,a);return k.useEffect(()=>{const l=a.current;if(l)return i3e(l)},[]),e.jsx(BSt,{...t,ref:i,trapFocus:r.open,disableOutsidePointerEvents:r.open,onCloseAutoFocus:ga(t.onCloseAutoFocus,l=>{var o;l.preventDefault(),(o=r.triggerRef.current)==null||o.focus()}),onPointerDownOutside:ga(t.onPointerDownOutside,l=>{const o=l.detail.originalEvent,c=o.button===0&&o.ctrlKey===!0;(o.button===2||c)&&l.preventDefault()}),onFocusOutside:ga(t.onFocusOutside,l=>l.preventDefault())})},"DialogContentModal")),Grs=k.forwardRef(pj(function(t,n){const r=kk(LZ,t.__scopeDialog),a=k.useRef(!1),i=k.useRef(!1);return e.jsx(BSt,{...t,ref:n,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:l=>{var o,c;(o=t.onCloseAutoFocus)==null||o.call(t,l),l.defaultPrevented||(a.current||(c=r.triggerRef.current)==null||c.focus(),l.preventDefault()),a.current=!1,i.current=!1},onInteractOutside:l=>{var d,u;(d=t.onInteractOutside)==null||d.call(t,l),l.defaultPrevented||(a.current=!0,l.detail.originalEvent.type==="pointerdown"&&(i.current=!0));const o=l.target;((u=r.triggerRef.current)==null?void 0:u.contains(o))&&l.preventDefault(),l.detail.originalEvent.type==="focusin"&&i.current&&l.preventDefault()}})},"DialogContentNonModal")),BSt=k.forwardRef(pj(function(t,n){const{__scopeDialog:r,trapFocus:a,onOpenAutoFocus:i,onCloseAutoFocus:l,...o}=t,c=kk(LZ,r);return Mq(),e.jsx(e.Fragment,{children:e.jsx(r3e,{asChild:!0,loop:!0,trapped:a,onMountAutoFocus:i,onUnmountAutoFocus:l,children:e.jsx(pF,{role:"dialog",id:c.contentId,"aria-describedby":c.descriptionPresent?c.descriptionId:void 0,"aria-labelledby":c.titlePresent?c.titleId:void 0,"data-state":c3e(c.open),...o,ref:n,deferPointerDownOutside:!0,onDismiss:()=>c.onOpenChange(!1)})})})},"DialogContentImpl")),Wrs="DialogTitle",tee=k.forwardRef(pj(function(t,n){const{__scopeDialog:r,...a}=t,i=kk(Wrs,r),{setTitleCount:l}=i;return _m(()=>(l(o=>o+1),()=>l(o=>o-1)),[l]),e.jsx(hi.h2,{id:i.titleId,...a,ref:n})},"DialogTitle")),Krs="DialogDescription",see=k.forwardRef(pj(function(t,n){const{__scopeDialog:r,...a}=t,i=kk(Krs,r),{setDescriptionCount:l}=i;return _m(()=>(l(o=>o+1),()=>l(o=>o-1)),[l]),e.jsx(hi.p,{id:i.descriptionId,...a,ref:n})},"DialogDescription")),Yrs="DialogClose",nee=k.forwardRef(pj(function(t,n){const{__scopeDialog:r,...a}=t,i=kk(Yrs,r);return e.jsx(hi.button,{type:"button",...a,ref:n,onClick:ga(t.onClick,()=>i.onOpenChange(!1))})},"DialogClose"));function c3e(s){return s?"open":"closed"}pj(c3e,"getState");var Zrs=Object.defineProperty,eA=(s,t)=>Zrs(s,"name",{value:t,configurable:!0}),Xrs="AlertDialog",[Qrs,dQn]=qm(Xrs,[OSt]),tA=OSt(),Jrs=eA(s=>{const{__scopeAlertDialog:t,...n}=s,r=tA(t);return e.jsx(o3e,{...r,...n,modal:!0})},"AlertDialog"),eas=k.forwardRef(eA(function(t,n){const{__scopeAlertDialog:r,...a}=t,i=tA(r);return e.jsx(XVe,{...i,...a,ref:n})},"AlertDialogTrigger")),tas=eA(s=>{const{__scopeAlertDialog:t,...n}=s,r=tA(t);return e.jsx(l3e,{...r,...n})},"AlertDialogPortal"),sas=k.forwardRef(eA(function(t,n){const{__scopeAlertDialog:r,...a}=t,i=tA(r);return e.jsx(Pq,{...i,...a,ref:n})},"AlertDialogOverlay")),nas="AlertDialogContent",[ras,aas]=Qrs(nas),ias=k.forwardRef(eA(function(t,n){const{__scopeAlertDialog:r,children:a,...i}=t,l=tA(r),o=k.useRef(null),c=Ao(n,o),d=k.useRef(null);return e.jsx(ras,{scope:r,cancelRef:d,children:e.jsx(Iq,{role:"alertdialog",...l,...i,ref:c,onOpenAutoFocus:ga(i.onOpenAutoFocus,u=>{var h;u.preventDefault(),(h=d.current)==null||h.focus({preventScroll:!0})}),onPointerDownOutside:u=>u.preventDefault(),onInteractOutside:u=>u.preventDefault(),children:a})})},"AlertDialogContent")),oas=k.forwardRef(eA(function(t,n){const{__scopeAlertDialog:r,...a}=t,i=tA(r);return e.jsx(tee,{...i,...a,ref:n})},"AlertDialogTitle")),las=k.forwardRef(eA(function(t,n){const{__scopeAlertDialog:r,...a}=t,i=tA(r);return e.jsx(see,{...i,...a,ref:n})},"AlertDialogDescription")),cas=k.forwardRef(eA(function(t,n){const{__scopeAlertDialog:r,...a}=t,i=tA(r);return e.jsx(nee,{...i,...a,ref:n})},"AlertDialogAction")),das="AlertDialogCancel",uas=k.forwardRef(eA(function(t,n){const{__scopeAlertDialog:r,...a}=t,{cancelRef:i}=aas(das,r),l=tA(r),o=Ao(n,i);return e.jsx(nee,{...l,...a,ref:o})},"AlertDialogCancel")),has=Jrs,mas=eas,fas=tas,$St=sas,USt=ias,qSt=cas,VSt=uas,HSt=oas,GSt=las;const hU=gF("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"}}),$=k.forwardRef(({className:s,variant:t,size:n,asChild:r=!1,...a},i)=>{const l=r?BVe:"button";return e.jsx(l,{className:Ot(hU({variant:t,size:n,className:s})),ref:i,...a})});$.displayName="Button";const oc=has,_g=mas,pas=fas,WSt=k.forwardRef(({className:s,...t},n)=>e.jsx($St,{className:Ot("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",s),...t,ref:n}));WSt.displayName=$St.displayName;const Ql=k.forwardRef(({className:s,...t},n)=>e.jsxs(pas,{children:[e.jsx(WSt,{}),e.jsx(USt,{ref:n,className:Ot("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})]}));Ql.displayName=USt.displayName;const Jl=({className:s,...t})=>e.jsx("div",{className:Ot("flex flex-col space-y-2 text-center sm:text-left",s),...t});Jl.displayName="AlertDialogHeader";const ec=({className:s,...t})=>e.jsx("div",{className:Ot("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",s),...t});ec.displayName="AlertDialogFooter";const tc=k.forwardRef(({className:s,...t},n)=>e.jsx(HSt,{ref:n,className:Ot("text-lg font-semibold",s),...t}));tc.displayName=HSt.displayName;const sc=k.forwardRef(({className:s,...t},n)=>e.jsx(GSt,{ref:n,className:Ot("text-sm text-muted-foreground",s),...t}));sc.displayName=GSt.displayName;const Vl=k.forwardRef(({className:s,...t},n)=>e.jsx(qSt,{ref:n,className:Ot(hU(),s),...t}));Vl.displayName=qSt.displayName;const nc=k.forwardRef(({className:s,...t},n)=>e.jsx(VSt,{ref:n,className:Ot(hU({variant:"outline"}),"mt-2 sm:mt-0",s),...t}));nc.displayName=VSt.displayName;let Yke=null;const gas=["delete","remove","revoke","cannot be undone","permanently"];function io(s,t={}){const n=typeof s=="string"?{description:s,...t}:s,r=`${n.title??""} ${n.description??""}`.toLowerCase(),a=n.destructive??gas.some(i=>r.includes(i));return new Promise(i=>{if(!Yke){i(window.confirm(n.description??n.title??"Are you sure?"));return}Yke({...n,destructive:a,resolve:i})})}function xas(){const[s,t]=k.useState(null);k.useEffect(()=>(Yke=a=>t(a),()=>{Yke=null}),[]);const n=a=>{s==null||s.resolve(a),t(null)},r=!!(s!=null&&s.destructive);return e.jsx(oc,{open:!!s,onOpenChange:a=>!a&&n(!1),children:e.jsxs(Ql,{className:"sm:max-w-md",children:[e.jsx(Jl,{children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:Ot("mt-0.5 flex h-10 w-10 shrink-0 items-center justify-center rounded-full",r?"bg-destructive/10 text-destructive":"bg-primary/10 text-primary"),children:e.jsx(Gd,{className:"h-5 w-5"})}),e.jsxs("div",{className:"space-y-1.5 text-left",children:[e.jsx(tc,{children:(s==null?void 0:s.title)??(r?"Are you sure?":"Please confirm")}),(s==null?void 0:s.description)&&e.jsx(sc,{className:"leading-relaxed",children:s.description})]})]})}),e.jsxs(ec,{className:"gap-2 sm:gap-2",children:[e.jsx(nc,{onClick:()=>n(!1),children:(s==null?void 0:s.cancelText)??"Cancel"}),e.jsx(Vl,{onClick:()=>n(!0),className:Ot(r&&"bg-destructive text-destructive-foreground hover:bg-destructive/90"),children:(s==null?void 0:s.confirmText)??(r?"Delete":"Continue")})]})]})})}const yas=["top","right","bottom","left"],wM=Math.min,w3=Math.max,Zke=Math.round,zne=Math.floor,j3=s=>({x:s,y:s}),vas={left:"right",right:"left",bottom:"top",top:"bottom"};function KSt(s,t,n){return w3(s,wM(t,n))}function B3(s,t){return typeof s=="function"?s(t):s}function jM(s){return s.split("-")[0]}function Lq(s){return s.split("-")[1]}function QVe(s){return s==="x"?"y":"x"}function JVe(s){return s==="y"?"height":"width"}function m5(s){const t=s[0];return t==="t"||t==="b"?"y":"x"}function eHe(s){return QVe(m5(s))}function bas(s,t,n){n===void 0&&(n=!1);const r=Lq(s),a=eHe(s),i=JVe(a);let l=a==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return t.reference[i]>t.floating[i]&&(l=Xke(l)),[l,Xke(l)]}function _as(s){const t=Xke(s);return[pFe(s),t,pFe(t)]}function pFe(s){return s.includes("start")?s.replace("start","end"):s.replace("end","start")}const Jat=["left","right"],eit=["right","left"],was=["top","bottom"],jas=["bottom","top"];function Nas(s,t,n){switch(s){case"top":case"bottom":return n?t?eit:Jat:t?Jat:eit;case"left":case"right":return t?was:jas;default:return[]}}function kas(s,t,n,r){const a=Lq(s);let i=Nas(jM(s),n==="start",r);return a&&(i=i.map(l=>l+"-"+a),t&&(i=i.concat(i.map(pFe)))),i}function Xke(s){const t=jM(s);return vas[t]+s.slice(t.length)}function Sas(s){var t,n,r,a;return{top:(t=s.top)!=null?t:0,right:(n=s.right)!=null?n:0,bottom:(r=s.bottom)!=null?r:0,left:(a=s.left)!=null?a:0}}function YSt(s){return typeof s!="number"?Sas(s):{top:s,right:s,bottom:s,left:s}}function Qke(s){const{x:t,y:n,width:r,height:a}=s;return{width:r,height:a,top:n,left:t,right:t+r,bottom:n+a,x:t,y:n}}function tit(s,t,n){let{reference:r,floating:a}=s;const i=m5(t),l=eHe(t),o=JVe(l),c=jM(t),d=i==="y",u=r.x+r.width/2-a.width/2,h=r.y+r.height/2-a.height/2,m=r[o]/2-a[o]/2;let p;switch(c){case"top":p={x:u,y:r.y-a.height};break;case"bottom":p={x:u,y:r.y+r.height};break;case"right":p={x:r.x+r.width,y:h};break;case"left":p={x:r.x-a.width,y:h};break;default:p={x:r.x,y:r.y}}const g=Lq(t);return g&&(p[l]+=m*(g==="end"?1:-1)*(n&&d?-1:1)),p}async function Cas(s,t){var n;t===void 0&&(t={});const{x:r,y:a,platform:i,rects:l,elements:o,strategy:c}=s,{boundary:d="clippingAncestors",rootBoundary:u="viewport",elementContext:h="floating",altBoundary:m=!1,padding:p=0}=B3(t,s),g=YSt(p),y=o[m?h==="floating"?"reference":"floating":h],v=Qke(await i.getClippingRect({element:(n=await(i.isElement==null?void 0:i.isElement(y)))==null||n?y:y.contextElement||await(i.getDocumentElement==null?void 0:i.getDocumentElement(o.floating)),boundary:d,rootBoundary:u,strategy:c})),_=h==="floating"?{x:r,y:a,width:l.floating.width,height:l.floating.height}:l.reference,j=await(i.getOffsetParent==null?void 0:i.getOffsetParent(o.floating)),C=await(i.isElement==null?void 0:i.isElement(j))&&await(i.getScale==null?void 0:i.getScale(j))||{x:1,y:1},A=Qke(i.convertOffsetParentRelativeRectToViewportRelativeRect?await i.convertOffsetParentRelativeRectToViewportRelativeRect({elements:o,rect:_,offsetParent:j,strategy:c}):_);return{top:(v.top-A.top+g.top)/C.y,bottom:(A.bottom-v.bottom+g.bottom)/C.y,left:(v.left-A.left+g.left)/C.x,right:(A.right-v.right+g.right)/C.x}}const Aas=50,Eas=async(s,t,n)=>{const{placement:r="bottom",strategy:a="absolute",middleware:i=[],platform:l}=n,o=l.detectOverflow?l:{...l,detectOverflow:Cas},c=await(l.isRTL==null?void 0:l.isRTL(t));let d=await l.getElementRects({reference:s,floating:t,strategy:a}),{x:u,y:h}=tit(d,r,c),m=r,p=0;const g={};for(let x=0;x({name:"arrow",options:s,async fn(t){const{x:n,y:r,placement:a,rects:i,platform:l,elements:o,middlewareData:c}=t,{element:d,padding:u=0}=B3(s,t)||{};if(d==null)return{};const h=YSt(u),m={x:n,y:r},p=eHe(a),g=JVe(p),x=await l.getDimensions(d),y=p==="y",v=y?"top":"left",_=y?"bottom":"right",j=y?"clientHeight":"clientWidth",C=i.reference[g]+i.reference[p]-m[p]-i.floating[g],A=m[p]-i.reference[p],M=await(l.getOffsetParent==null?void 0:l.getOffsetParent(d));let I=M?M[j]:0;(!I||!await(l.isElement==null?void 0:l.isElement(M)))&&(I=o.floating[j]||i.floating[g]);const P=C/2-A/2,R=I/2-x[g]/2-1,O=wM(h[v],R),B=wM(h[_],R),U=I-x[g]-B,G=I/2-x[g]/2+P,H=KSt(O,G,U),Y=!c.arrow&&Lq(a)!=null&&G!==H&&i.reference[g]/2-(GH<=0)){var B,U;const H=(((B=i.flip)==null?void 0:B.index)||0)+1,Y=I[H];if(Y&&(!(h==="alignment"?_!==m5(Y):!1)||O.every(oe=>m5(oe.placement)===_?oe.overflows[0]>0:!0)))return{data:{index:H,overflows:O},reset:{placement:Y}};let se=(U=O.filter(ee=>ee.overflows[0]<=0).sort((ee,oe)=>ee.overflows[1]-oe.overflows[1])[0])==null?void 0:U.placement;if(!se)switch(p){case"bestFit":{var G;const ee=(G=O.filter(oe=>{if(M){const me=m5(oe.placement);return me===_||me==="y"}return!0}).map(oe=>[oe.placement,oe.overflows.filter(me=>me>0).reduce((me,Q)=>me+Q,0)]).sort((oe,me)=>oe[1]-me[1])[0])==null?void 0:G[0];ee&&(se=ee);break}case"initialPlacement":se=o;break}if(a!==se)return{reset:{placement:se}}}return{}}}};function sit(s,t){return{top:s.top-t.height,right:s.right-t.width,bottom:s.bottom-t.height,left:s.left-t.width}}function nit(s){return yas.some(t=>s[t]>=0)}const Pas=function(s){return s===void 0&&(s={}),{name:"hide",options:s,async fn(t){const{rects:n,platform:r}=t,{strategy:a="referenceHidden",...i}=B3(s,t);switch(a){case"referenceHidden":{const l=await r.detectOverflow(t,{...i,elementContext:"reference"}),o=sit(l,n.reference);return{data:{referenceHiddenOffsets:o,referenceHidden:nit(o)}}}case"escaped":{const l=await r.detectOverflow(t,{...i,altBoundary:!0}),o=sit(l,n.floating);return{data:{escapedOffsets:o,escaped:nit(o)}}}default:return{}}}}},ZSt=new Set(["left","top"]);async function Ias(s,t){const{placement:n,platform:r,elements:a}=s,i=await(r.isRTL==null?void 0:r.isRTL(a.floating)),l=jM(n),o=Lq(n),c=m5(n)==="y",d=ZSt.has(l)?-1:1,u=i&&c?-1:1,h=B3(t,s);let{mainAxis:m,crossAxis:p,alignmentAxis:g}=typeof h=="number"?{mainAxis:h,crossAxis:0,alignmentAxis:null}:{mainAxis:h.mainAxis||0,crossAxis:h.crossAxis||0,alignmentAxis:h.alignmentAxis};return o&&typeof g=="number"&&(p=o==="end"?g*-1:g),c?{x:p*u,y:m*d}:{x:m*d,y:p*u}}const Las=function(s){return s===void 0&&(s=0),{name:"offset",options:s,async fn(t){var n,r;const{x:a,y:i,placement:l,middlewareData:o}=t,c=await Ias(t,s);return l===((n=o.offset)==null?void 0:n.placement)&&(r=o.arrow)!=null&&r.alignmentOffset?{}:{x:a+c.x,y:i+c.y,data:{...c,placement:l}}}}},Ras=function(s){return s===void 0&&(s={}),{name:"shift",options:s,async fn(t){const{x:n,y:r,placement:a,platform:i}=t,{mainAxis:l=!0,crossAxis:o=!1,limiter:c={fn:_=>{let{x:j,y:C}=_;return{x:j,y:C}}},...d}=B3(s,t),u={x:n,y:r},h=await i.detectOverflow(t,d),m=m5(a),p=QVe(m);let g=u[p],x=u[m];const y=(_,j)=>KSt(j+h[_==="y"?"top":"left"],j,j-h[_==="y"?"bottom":"right"]);l&&(g=y(p,g)),o&&(x=y(m,x));const v=c.fn({...t,[p]:g,[m]:x});return{...v,data:{x:v.x-n,y:v.y-r,enabled:{[p]:l,[m]:o}}}}}},Das=function(s){return s===void 0&&(s={}),{options:s,fn(t){var n,r;const{x:a,y:i,placement:l,rects:o,middlewareData:c}=t,{offset:d=0,mainAxis:u=!0,crossAxis:h=!0}=B3(s,t),m={x:a,y:i},p=m5(l),g=QVe(p);let x=m[g],y=m[p];const v=B3(d,t),_=typeof v=="number"?{mainAxis:v,crossAxis:0}:{mainAxis:(n=v.mainAxis)!=null?n:0,crossAxis:(r=v.crossAxis)!=null?r:0};if(u){const A=g==="y"?"height":"width",M=o.reference[g]-o.floating[A]+_.mainAxis,I=o.reference[g]+o.reference[A]-_.mainAxis;xI&&(x=I)}if(h){var j,C;const A=g==="y"?"width":"height",M=ZSt.has(jM(l)),I=o.reference[p]-o.floating[A]+(M&&((j=c.offset)==null?void 0:j[p])||0)+(M?0:_.crossAxis),P=o.reference[p]+o.reference[A]+(M?0:((C=c.offset)==null?void 0:C[p])||0)-(M?_.crossAxis:0);yP&&(y=P)}return{[g]:x,[p]:y}}}},Oas=function(s){return s===void 0&&(s={}),{name:"size",options:s,async fn(t){const{placement:n,rects:r,platform:a,elements:i}=t,{apply:l=()=>{},...o}=B3(s,t),c=await a.detectOverflow(t,o),d=jM(n),u=Lq(n),h=m5(n)==="y",{width:m,height:p}=r.floating;let g,x;d==="top"||d==="bottom"?(g=d,x=u===(await(a.isRTL==null?void 0:a.isRTL(i.floating))?"start":"end")?"left":"right"):(x=d,g=u==="end"?"top":"bottom");const y=p-c.top-c.bottom,v=m-c.left-c.right,_=wM(p-c[g],y),j=wM(m-c[x],v),C=t.middlewareData.shift,A=!C;let M=_,I=j;C!=null&&C.enabled.x&&(I=v),C!=null&&C.enabled.y&&(M=y),A&&!u&&(h?I=m-2*w3(c.left,c.right):M=p-2*w3(c.top,c.bottom)),await l({...t,availableWidth:I,availableHeight:M});const P=await a.getDimensions(i.floating);return m!==P.width||p!==P.height?{reset:{rects:!0}}:{}}}};function d3e(){return typeof window<"u"}function Rq(s){return XSt(s)?(s.nodeName||"").toLowerCase():"#document"}function j_(s){var t;return(s==null||(t=s.ownerDocument)==null?void 0:t.defaultView)||window}function sA(s){var t;return(t=(XSt(s)?s.ownerDocument:s.document)||window.document)==null?void 0:t.documentElement}function XSt(s){return d3e()?s instanceof Node||s instanceof j_(s).Node:!1}function U5(s){return d3e()?s instanceof Element||s instanceof j_(s).Element:!1}function WM(s){return d3e()?s instanceof HTMLElement||s instanceof j_(s).HTMLElement:!1}function rit(s){return!d3e()||typeof ShadowRoot>"u"?!1:s instanceof ShadowRoot||s instanceof j_(s).ShadowRoot}function u3e(s){const{overflow:t,overflowX:n,overflowY:r,display:a}=q5(s);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&a!=="inline"&&a!=="contents"}function Fas(s){return/^(table|td|th)$/.test(Rq(s))}function h3e(s){try{if(s.matches(":popover-open"))return!0}catch{}try{return s.matches(":modal")}catch{return!1}}const zas=/transform|translate|scale|rotate|perspective|filter/,Bas=/paint|layout|strict|content/,sP=s=>!!s&&s!=="none";let XPe;function tHe(s){const t=U5(s)?q5(s):s;return sP(t.transform)||sP(t.translate)||sP(t.scale)||sP(t.rotate)||sP(t.perspective)||!sHe()&&(sP(t.backdropFilter)||sP(t.filter))||zas.test(t.willChange||"")||Bas.test(t.contain||"")}function $as(s){let t=CO(s);for(;WM(t)&&!RZ(t);){if(tHe(t))return t;if(h3e(t))return null;t=CO(t)}return null}function sHe(){return XPe==null&&(XPe=typeof CSS<"u"&&CSS.supports&&CSS.supports("-webkit-backdrop-filter","none")),XPe}function RZ(s){return/^(html|body|#document)$/.test(Rq(s))}function q5(s){return j_(s).getComputedStyle(s)}function m3e(s){return U5(s)?{scrollLeft:s.scrollLeft,scrollTop:s.scrollTop}:{scrollLeft:s.scrollX,scrollTop:s.scrollY}}function CO(s){if(Rq(s)==="html")return s;const t=s.assignedSlot||s.parentNode||rit(s)&&s.host||sA(s);return rit(t)?t.host:t}function QSt(s){const t=CO(s);return RZ(t)?(s.ownerDocument||s).body:WM(t)&&u3e(t)?t:QSt(t)}function DZ(s,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const a=QSt(s),i=a===((r=s.ownerDocument)==null?void 0:r.body),l=j_(a);if(i){const o=gFe(l);return t.concat(l,l.visualViewport||[],u3e(a)?a:[],o&&n?DZ(o):[])}else return t.concat(a,DZ(a,[],n))}function gFe(s){return s.parent&&Object.getPrototypeOf(s.parent)?s.frameElement:null}function JSt(s){const t=q5(s);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const a=WM(s),i=a?s.offsetWidth:n,l=a?s.offsetHeight:r,o=Zke(n)!==i||Zke(r)!==l;return o&&(n=i,r=l),{width:n,height:r,$:o}}function nHe(s){return U5(s)?s:s.contextElement}function _B(s){const t=nHe(s);if(!WM(t))return j3(1);const n=t.getBoundingClientRect(),{width:r,height:a,$:i}=JSt(t);let l=(i?Zke(n.width):n.width)/r,o=(i?Zke(n.height):n.height)/a;return(!l||!Number.isFinite(l))&&(l=1),(!o||!Number.isFinite(o))&&(o=1),{x:l,y:o}}const Uas=j3(0);function e5t(s){const t=j_(s);return!sHe()||!t.visualViewport?Uas:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function qas(s,t,n){return t===void 0&&(t=!1),!!n&&t&&n===j_(s)}function AO(s,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const a=s.getBoundingClientRect(),i=nHe(s);let l=j3(1);t&&(r?U5(r)&&(l=_B(r)):l=_B(s));const o=qas(i,n,r)?e5t(i):j3(0);let c=(a.left+o.x)/l.x,d=(a.top+o.y)/l.y,u=a.width/l.x,h=a.height/l.y;if(i&&r){const m=j_(i),p=U5(r)?j_(r):r;let g=m,x=gFe(g);for(;x&&p!==g;){const y=_B(x),v=x.getBoundingClientRect(),_=q5(x),j=v.left+(x.clientLeft+parseFloat(_.paddingLeft))*y.x,C=v.top+(x.clientTop+parseFloat(_.paddingTop))*y.y;c*=y.x,d*=y.y,u*=y.x,h*=y.y,c+=j,d+=C,g=j_(x),x=gFe(g)}}return Qke({width:u,height:h,x:c,y:d})}function f3e(s,t){const n=m3e(s).scrollLeft;return t?t.left+n:AO(sA(s)).left+n}function t5t(s,t){const n=s.getBoundingClientRect(),r=n.left+t.scrollLeft-f3e(s,n),a=n.top+t.scrollTop;return{x:r,y:a}}function Vas(s){let{elements:t,rect:n,offsetParent:r,strategy:a}=s;const i=a==="fixed",l=sA(r),o=t?h3e(t.floating):!1;if(r===l||o&&i)return n;let c={scrollLeft:0,scrollTop:0},d=j3(1);const u=j3(0),h=WM(r);if((h||!i)&&((Rq(r)!=="body"||u3e(l))&&(c=m3e(r)),h)){const p=AO(r);d=_B(r),u.x=p.x+r.clientLeft,u.y=p.y+r.clientTop}const m=l&&!h&&!i?t5t(l,c):j3(0);return{width:n.width*d.x,height:n.height*d.y,x:n.x*d.x-c.scrollLeft*d.x+u.x+m.x,y:n.y*d.y-c.scrollTop*d.y+u.y+m.y}}function Has(s){return s.getClientRects?Array.from(s.getClientRects()):[]}function Gas(s){const t=m3e(s),n=s.ownerDocument.body,r=w3(s.scrollWidth,s.clientWidth,n.scrollWidth,n.clientWidth),a=w3(s.scrollHeight,s.clientHeight,n.scrollHeight,n.clientHeight);let i=-t.scrollLeft+f3e(s);const l=-t.scrollTop;return q5(n).direction==="rtl"&&(i+=w3(s.clientWidth,n.clientWidth)-r),{width:r,height:a,x:i,y:l}}const Was=25;function Kas(s,t,n){n===void 0&&(n="viewport");const r=n==="layoutViewport",a=j_(s),i=sA(s),l=a.visualViewport;let o=i.clientWidth,c=i.clientHeight,d=0,u=0;if(l){const m=!sHe()||t==="fixed";r?m||(d=-l.offsetLeft,u=-l.offsetTop):(o=l.width,c=l.height,m&&(d=l.offsetLeft,u=l.offsetTop))}if(f3e(i)<=0){const m=i.ownerDocument,p=m.body,g=getComputedStyle(p),x=m.compatMode==="CSS1Compat"&&parseFloat(g.marginLeft)+parseFloat(g.marginRight)||0,y=Math.abs(i.clientWidth-p.clientWidth-x),v=getComputedStyle(i).scrollbarGutter==="stable both-edges"?y/2:y;v<=Was&&(o-=v)}return{width:o,height:c,x:d,y:u}}function Yas(s,t){const n=AO(s,!0,t==="fixed"),r=n.top+s.clientTop,a=n.left+s.clientLeft,i=_B(s),l=s.clientWidth*i.x,o=s.clientHeight*i.y,c=a*i.x,d=r*i.y;return{width:l,height:o,x:c,y:d}}function ait(s,t,n){let r;if(t==="viewport"||t==="layoutViewport")r=Kas(s,n,t);else if(t==="document")r=Gas(sA(s));else if(U5(t))r=Yas(t,n);else{const a=e5t(s);r={x:t.x-a.x,y:t.y-a.y,width:t.width,height:t.height}}return Qke(r)}function Zas(s,t){const n=t.get(s);if(n)return n;let r=DZ(s,[],!1).filter(o=>U5(o)&&Rq(o)!=="body"),a=null;const i=q5(s).position==="fixed";let l=i?CO(s):s;for(;U5(l)&&!RZ(l);){const o=q5(l),c=tHe(l),d=a?a.position:i?"fixed":"";!c&&(d==="fixed"||d==="absolute"&&o.position==="static")?r=r.filter(h=>h!==l):a=o,l=CO(l)}return t.set(s,r),r}function Xas(s){let{element:t,boundary:n,rootBoundary:r,strategy:a}=s;const l=[...n==="clippingAncestors"?h3e(t)?[]:Zas(t,this._c):[].concat(n),r],o=ait(t,l[0],a);let c=o.top,d=o.right,u=o.bottom,h=o.left;for(let m=1;m{o(!1,1e-7)},1e3)}I=!1}try{r=new IntersectionObserver(P,{...M,root:i.ownerDocument})}catch{r=new IntersectionObserver(P,M)}r.observe(s)}const c=j_(s),d=()=>o(n);return c.addEventListener("resize",d),o(!0),()=>{c.removeEventListener("resize",d),l()}}function ris(s,t,n,r){r===void 0&&(r={});const{ancestorScroll:a=!0,ancestorResize:i=!0,elementResize:l=typeof ResizeObserver=="function",layoutShift:o=typeof IntersectionObserver=="function",animationFrame:c=!1}=r,d=nHe(s),u=a||i?[...d?DZ(d):[],...t?DZ(t):[]]:[];u.forEach(v=>{a&&v.addEventListener("scroll",n),i&&v.addEventListener("resize",n)});const h=d&&o?nis(d,n,i):null;let m=-1,p=null;l&&(p=new ResizeObserver(v=>{let[_]=v;_&&_.target===d&&p&&t&&(p.unobserve(t),cancelAnimationFrame(m),m=requestAnimationFrame(()=>{var j;(j=p)==null||j.observe(t)})),n()}),d&&!c&&p.observe(d),t&&p.observe(t));let g,x=c?AO(s):null;c&&y();function y(){const v=AO(s);x&&!n5t(x,v)&&n(),x=v,g=requestAnimationFrame(y)}return n(),()=>{var v;u.forEach(_=>{a&&_.removeEventListener("scroll",n),i&&_.removeEventListener("resize",n)}),h==null||h(),(v=p)==null||v.disconnect(),p=null,c&&cancelAnimationFrame(g)}}const ais=Las,iis=Ras,ois=Mas,lis=Oas,cis=Pas,oit=Tas,dis=Das,uis=(s,t,n)=>{const r=new Map,a=n??{},i={...sis,...a.platform,_c:r};return Eas(s,t,{...a,platform:i})};var his=typeof document<"u",mis=function(){},Y2e=his?k.useLayoutEffect:mis;function Jke(s,t){if(s===t)return!0;if(typeof s!=typeof t)return!1;if(typeof s=="function"&&s.toString()===t.toString())return!0;let n,r,a;if(s&&t&&typeof s=="object"){if(Array.isArray(s)){if(n=s.length,n!==t.length)return!1;for(r=n;r--!==0;)if(!Jke(s[r],t[r]))return!1;return!0}if(a=Object.keys(s),n=a.length,n!==Object.keys(t).length)return!1;for(r=n;r--!==0;)if(!{}.hasOwnProperty.call(t,a[r]))return!1;for(r=n;r--!==0;){const i=a[r];if(!(i==="_owner"&&s.$$typeof)&&!Jke(s[i],t[i]))return!1}return!0}return s!==s&&t!==t}function r5t(s){return typeof window>"u"?1:(s.ownerDocument.defaultView||window).devicePixelRatio||1}function lit(s,t){const n=r5t(s);return Math.round(t*n)/n}function JPe(s){const t=k.useRef(s);return Y2e(()=>{t.current=s}),t}function fis(s){s===void 0&&(s={});const{placement:t="bottom",strategy:n="absolute",middleware:r=[],platform:a,elements:{reference:i,floating:l}={},transform:o=!0,whileElementsMounted:c,open:d}=s,[u,h]=k.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[m,p]=k.useState(r);Jke(m,r)||p(r);const[g,x]=k.useState(null),[y,v]=k.useState(null),_=k.useCallback(oe=>{oe!==M.current&&(M.current=oe,x(oe))},[]),j=k.useCallback(oe=>{oe!==I.current&&(I.current=oe,v(oe))},[]),C=i||g,A=l||y,M=k.useRef(null),I=k.useRef(null),P=k.useRef(u),R=c!=null,O=JPe(c),B=JPe(a),U=JPe(d),G=k.useCallback(()=>{if(!M.current||!I.current)return;const oe={placement:t,strategy:n,middleware:m};B.current&&(oe.platform=B.current),uis(M.current,I.current,oe).then(me=>{const Q={...me,isPositioned:U.current!==!1};H.current&&!Jke(P.current,Q)&&(P.current=Q,a1.flushSync(()=>{h(Q)}))})},[m,t,n,B,U]);Y2e(()=>{d===!1&&P.current.isPositioned&&(P.current.isPositioned=!1,h(oe=>({...oe,isPositioned:!1})))},[d]);const H=k.useRef(!1);Y2e(()=>(H.current=!0,()=>{H.current=!1}),[]),Y2e(()=>{if(C&&(M.current=C),A&&(I.current=A),C&&A){if(O.current)return O.current(C,A,G);G()}},[C,A,G,O,R]);const Y=k.useMemo(()=>({reference:M,floating:I,setReference:_,setFloating:j}),[_,j]),se=k.useMemo(()=>({reference:C,floating:A}),[C,A]),ee=k.useMemo(()=>{const oe={position:n,left:0,top:0};if(!se.floating)return oe;const me=lit(se.floating,u.x),Q=lit(se.floating,u.y);return o?{...oe,transform:"translate("+me+"px, "+Q+"px)",...r5t(se.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:me,top:Q}},[n,o,se.floating,u.x,u.y]);return k.useMemo(()=>({...u,update:G,refs:Y,elements:se,floatingStyles:ee}),[u,G,Y,se,ee])}const pis=s=>{function t(n){return{}.hasOwnProperty.call(n,"current")}return{name:"arrow",options:s,fn(n){const{element:r,padding:a}=typeof s=="function"?s(n):s;return r&&t(r)?r.current!=null?oit({element:r.current,padding:a}).fn(n):{}:r?oit({element:r,padding:a}).fn(n):{}}}},gis=(s,t)=>{const n=ais(s);return{name:n.name,fn:n.fn,options:[s,t]}},xis=(s,t)=>{const n=iis(s);return{name:n.name,fn:n.fn,options:[s,t]}},yis=(s,t)=>({fn:dis(s).fn,options:[s,t]}),vis=(s,t)=>{const n=ois(s);return{name:n.name,fn:n.fn,options:[s,t]}},bis=(s,t)=>{const n=lis(s);return{name:n.name,fn:n.fn,options:[s,t]}},_is=(s,t)=>{const n=cis(s);return{name:n.name,fn:n.fn,options:[s,t]}},wis=(s,t)=>{const n=pis(s);return{name:n.name,fn:n.fn,options:[s,t]}};var jis=Object.defineProperty,Nis=(s,t)=>jis(s,"name",{value:t,configurable:!0});function Dq(s){const[t,n]=k.useState(void 0);return _m(()=>{if(s){n({width:s.offsetWidth,height:s.offsetHeight});const r=new ResizeObserver(a=>{if(!Array.isArray(a)||!a.length)return;const i=a[0];let l,o;if("borderBoxSize"in i){const c=i.borderBoxSize,d=Array.isArray(c)?c[0]:c;l=d.inlineSize,o=d.blockSize}else l=s.offsetWidth,o=s.offsetHeight;n({width:l,height:o})});return r.observe(s,{box:"border-box"}),()=>r.unobserve(s)}else n(void 0)},[s]),t}Nis(Dq,"useSize");var kis=Object.defineProperty,iM=(s,t)=>kis(s,"name",{value:t,configurable:!0}),a5t="Popper",[i5t,Q5]=qm(a5t),[Sis,o5t]=i5t(a5t),Cis=iM(s=>{const{__scopePopper:t,children:n}=s,[r,a]=k.useState(null),[i,l]=k.useState(void 0);return e.jsx(Sis,{scope:t,anchor:r,onAnchorChange:a,placementState:i,setPlacementState:l,children:n})},"Popper"),Ais="PopperAnchor",Eis=k.forwardRef(iM(function(t,n){const{__scopePopper:r,virtualRef:a,...i}=t,l=o5t(Ais,r),o=k.useRef(null),c=l.onAnchorChange,d=k.useCallback(x=>{o.current=x,x&&c(x)},[c]),u=Ao(n,d),h=k.useRef(null);k.useEffect(()=>{if(!a)return;const x=h.current;h.current=a.current,x!==h.current&&c(h.current)});const m=l.placementState&&p3e(l.placementState),p=m==null?void 0:m[0],g=m==null?void 0:m[1];return a?null:e.jsx(hi.div,{"data-radix-popper-side":p,"data-radix-popper-align":g,...i,ref:u})},"PopperAnchor")),l5t="PopperContent",[Tis,uQn]=i5t(l5t),Mis=k.forwardRef(iM(function(t,n){var Ie,Ue,Be,je,Ye,Ee,Re;const{__scopePopper:r,side:a="bottom",sideOffset:i=0,align:l="center",alignOffset:o=0,arrowPadding:c=0,avoidCollisions:d=!0,collisionBoundary:u=[],collisionPadding:h=0,sticky:m="partial",hideWhenDetached:p=!1,updatePositionStrategy:g="optimized",onPlaced:x,...y}=t,v=o5t(l5t,r),[_,j]=k.useState(null),C=Ao(n,j),[A,M]=k.useState(null),I=Dq(A),P=(I==null?void 0:I.width)??0,R=(I==null?void 0:I.height)??0,O=a+(l!=="center"?"-"+l:""),B=typeof h=="number"?h:{top:0,right:0,bottom:0,left:0,...h},U=Array.isArray(u)?u:[u],G=U.length>0,H={padding:B,boundary:U.filter(c5t),altBoundary:G},{refs:Y,floatingStyles:se,placement:ee,isPositioned:oe,middlewareData:me}=fis({strategy:"fixed",placement:O,whileElementsMounted:iM((...ke)=>ris(...ke,{animationFrame:g==="always"}),"whileElementsMounted"),elements:{reference:v.anchor},middleware:[gis({mainAxis:i+R,alignmentAxis:o}),d&&xis({mainAxis:!0,crossAxis:!1,limiter:m==="partial"?yis():void 0,...H}),d&&vis({...H}),bis({...H,apply:iM(({elements:ke,rects:Fe,availableWidth:Oe,availableHeight:Ge})=>{const{width:yt,height:tt}=Fe.reference,ut=ke.floating.style;ut.setProperty("--radix-popper-available-width",`${Oe}px`),ut.setProperty("--radix-popper-available-height",`${Ge}px`),ut.setProperty("--radix-popper-anchor-width",`${yt}px`),ut.setProperty("--radix-popper-anchor-height",`${tt}px`)},"apply")}),A&&wis({element:A,padding:c}),Pis({arrowWidth:P,arrowHeight:R}),p&&_is({strategy:"referenceHidden",...H,boundary:G?H.boundary:void 0})]}),Q=v.setPlacementState;_m(()=>(Q(ee),()=>{Q(void 0)}),[ee,Q]);const[te,le]=p3e(ee),fe=sp(x);_m(()=>{oe&&(fe==null||fe())},[oe,fe]);const _e=(Ie=me.arrow)==null?void 0:Ie.x,ve=(Ue=me.arrow)==null?void 0:Ue.y,he=((Be=me.arrow)==null?void 0:Be.centerOffset)!==0,[Se,Te]=k.useState();return _m(()=>{_&&Te(window.getComputedStyle(_).zIndex)},[_]),e.jsx("div",{ref:Y.setFloating,"data-radix-popper-content-wrapper":"",style:{...se,transform:oe?se.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:Se,"--radix-popper-transform-origin":[(je=me.transformOrigin)==null?void 0:je.x,(Ye=me.transformOrigin)==null?void 0:Ye.y].join(" "),...((Ee=me.hide)==null?void 0:Ee.referenceHidden)&&{visibility:"hidden",pointerEvents:"none"}},dir:t.dir,children:e.jsx(Tis,{scope:r,placedSide:te,placedAlign:le,onArrowChange:M,arrowX:_e,arrowY:ve,shouldHideArrow:he,children:e.jsx(hi.div,{"data-side":te,"data-align":le,...y,ref:C,style:{...y.style,animation:oe?(Re=y.style)==null?void 0:Re.animation:"none"}})})})},"PopperContent"));function c5t(s){return s!==null}iM(c5t,"isNotNull");var Pis=iM(s=>({name:"transformOrigin",options:s,fn(t){var y,v,_;const{placement:n,rects:r,middlewareData:a}=t,l=((y=a.arrow)==null?void 0:y.centerOffset)!==0,o=l?0:s.arrowWidth,c=l?0:s.arrowHeight,[d,u]=p3e(n),h={start:"0%",center:"50%",end:"100%"}[u],m=(((v=a.arrow)==null?void 0:v.x)??0)+o/2,p=(((_=a.arrow)==null?void 0:_.y)??0)+c/2;let g="",x="";return d==="bottom"?(g=l?h:`${m}px`,x=`${-c}px`):d==="top"?(g=l?h:`${m}px`,x=`${r.floating.height+c}px`):d==="right"?(g=`${-c}px`,x=l?h:`${p}px`):d==="left"&&(g=`${r.floating.width+c}px`,x=l?h:`${p}px`),{data:{x:g,y:x}}}}),"transformOrigin");function p3e(s){const[t,n="center"]=s.split("-");return[t,n]}iM(p3e,"getSideAndAlignFromPlacement");var ree=Cis,aee=Eis,iee=Mis,Iis=Object.defineProperty,nv=(s,t)=>Iis(s,"name",{value:t,configurable:!0}),[rHe,hQn]=qm("Tooltip",[Q5]),aHe=Q5(),Lis="TooltipProvider",Ris=700,xFe="tooltip.open",[Dis,iHe]=rHe(Lis),Ois=nv(s=>{const{__scopeTooltip:t,delayDuration:n=Ris,skipDelayDuration:r=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(Dis,{scope:t,isOpenDelayedRef:l,delayDuration:n,onOpen:k.useCallback(()=>{r<=0||(window.clearTimeout(c.current),l.current=!1)},[r]),onClose:k.useCallback(()=>{r<=0||(window.clearTimeout(c.current),c.current=window.setTimeout(()=>l.current=!0,r))},[r]),isPointerInTransitRef:o,onPointerInTransitChange:k.useCallback(d=>{o.current=d},[]),disableHoverableContent:a,children:i})},"TooltipProvider"),yFe="Tooltip",[Fis,g3e]=rHe(yFe),zis=nv(s=>{const{__scopeTooltip:t,children:n,open:r,defaultOpen:a,onOpenChange:i,disableHoverableContent:l,delayDuration:o}=s,c=iHe(yFe,s.__scopeTooltip),d=aHe(t),[u,h]=k.useState(null),[m,p]=k.useState(void 0),g=$x(),x=k.useRef(0),y=l??c.disableHoverableContent,v=o??c.delayDuration,_=k.useRef(!1),[j,C]=ox({prop:r,defaultProp:a??!1,onChange:nv(O=>{O?(c.onOpen(),document.dispatchEvent(new CustomEvent(xFe))):c.onClose(),i==null||i(O)},"onChange"),caller:yFe}),A=k.useMemo(()=>j?_.current?"delayed-open":"instant-open":"closed",[j]),M=k.useCallback(()=>{window.clearTimeout(x.current),x.current=0,_.current=!1,C(!0)},[C]),I=k.useCallback(()=>{window.clearTimeout(x.current),x.current=0,C(!1)},[C]),P=k.useCallback(()=>{window.clearTimeout(x.current),x.current=window.setTimeout(()=>{_.current=!0,C(!0),x.current=0},v)},[v,C]);k.useEffect(()=>()=>{x.current&&(window.clearTimeout(x.current),x.current=0)},[]);const R=m??g;return e.jsx(ree,{...d,children:e.jsx(Fis,{scope:t,contentId:R,setContentId:p,open:j,stateAttribute:A,trigger:u,onTriggerChange:h,onTriggerEnter:k.useCallback(()=>{c.isOpenDelayedRef.current?P():M()},[c.isOpenDelayedRef,P,M]),onTriggerLeave:k.useCallback(()=>{y?I():(window.clearTimeout(x.current),x.current=0)},[I,y]),onOpen:M,onClose:I,disableHoverableContent:y,children:n})})},"Tooltip"),cit="TooltipTrigger",Bis=k.forwardRef(nv(function(t,n){const{__scopeTooltip:r,...a}=t,i=g3e(cit,r),l=iHe(cit,r),o=aHe(r),c=k.useRef(null),d=Ao(n,c,i.onTriggerChange),u=k.useRef(!1),h=k.useRef(!1),m=k.useCallback(()=>u.current=!1,[]);return k.useEffect(()=>()=>document.removeEventListener("pointerup",m),[m]),e.jsx(aee,{asChild:!0,...o,children:e.jsx(hi.button,{"aria-describedby":i.open?i.contentId:void 0,"data-state":i.stateAttribute,...a,ref:d,onPointerMove:ga(t.onPointerMove,p=>{p.pointerType!=="touch"&&!h.current&&!l.isPointerInTransitRef.current&&(i.onTriggerEnter(),h.current=!0)}),onPointerLeave:ga(t.onPointerLeave,()=>{i.onTriggerLeave(),h.current=!1}),onPointerDown:ga(t.onPointerDown,()=>{i.open&&i.onClose(),u.current=!0,document.addEventListener("pointerup",m,{once:!0})}),onFocus:ga(t.onFocus,()=>{u.current||i.onOpen()}),onBlur:ga(t.onBlur,i.onClose),onClick:ga(t.onClick,i.onClose)})})},"TooltipTrigger")),$is="TooltipPortal",[mQn,Uis]=rHe($is,{forceMount:void 0}),OZ="TooltipContent",qis=k.forwardRef(nv(function(t,n){const r=Uis(OZ,t.__scopeTooltip),{forceMount:a=r.forceMount,side:i="top",...l}=t,o=g3e(OZ,t.__scopeTooltip);return e.jsx(cx,{present:a||o.open,children:o.disableHoverableContent?e.jsx(d5t,{side:i,...l,ref:n}):e.jsx(Vis,{side:i,...l,ref:n})})},"TooltipContent")),Vis=k.forwardRef(nv(function(t,n){const r=g3e(OZ,t.__scopeTooltip),a=iHe(OZ,t.__scopeTooltip),i=k.useRef(null),l=Ao(n,i),[o,c]=k.useState(null),{trigger:d,onClose:u}=r,h=i.current,{onPointerInTransitChange:m}=a,p=k.useCallback(()=>{c(null),m(!1)},[m]),g=k.useCallback((x,y)=>{const v=x.currentTarget,_={x:x.clientX,y:x.clientY},j=u5t(_,v.getBoundingClientRect()),C=h5t(_,j),A=m5t(y.getBoundingClientRect()),M=p5t([...C,...A]);c(M),m(!0)},[m]);return k.useEffect(()=>()=>p(),[p]),k.useEffect(()=>{if(d&&h){const x=nv(v=>g(v,h),"handleTriggerLeave"),y=nv(v=>g(v,d),"handleContentLeave");return d.addEventListener("pointerleave",x),h.addEventListener("pointerleave",y),()=>{d.removeEventListener("pointerleave",x),h.removeEventListener("pointerleave",y)}}},[d,h,g,p]),k.useEffect(()=>{if(o){const x=nv(y=>{const v=y.target,_={x:y.clientX,y:y.clientY},j=(d==null?void 0:d.contains(v))||(h==null?void 0:h.contains(v)),C=!f5t(_,o);j?p():C&&(p(),u())},"handleTrackPointerGrace");return document.addEventListener("pointermove",x),()=>document.removeEventListener("pointermove",x)}},[d,h,o,u,p]),e.jsx(d5t,{...t,ref:l})},"TooltipContentHoverable")),His=Ekt("TooltipContent"),d5t=k.forwardRef(nv(function(t,n){const{__scopeTooltip:r,children:a,"aria-label":i,id:l,onEscapeKeyDown:o,onPointerDownOutside:c,...d}=t,u=g3e(OZ,r),h=aHe(r),{onClose:m}=u;k.useEffect(()=>(document.addEventListener(xFe,m),()=>document.removeEventListener(xFe,m)),[m]),k.useEffect(()=>{if(u.trigger){const g=nv(x=>{x.target instanceof Node&&x.target.contains(u.trigger)&&m()},"handleScroll");return window.addEventListener("scroll",g,{capture:!0}),()=>window.removeEventListener("scroll",g,{capture:!0})}},[u.trigger,m]);const{setContentId:p}=u;return _m(()=>(p(l),()=>{p(void 0)}),[l,p]),e.jsx(pF,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:o,onPointerDownOutside:c,onFocusOutside:g=>g.preventDefault(),onDismiss:m,children:e.jsxs(iee,{"data-state":u.stateAttribute,role:i?void 0:"tooltip",id:i?void 0:u.contentId,...h,...d,ref:n,style:{...d.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(His,{children:a}),i?e.jsx(iss,{id:u.contentId,role:"tooltip",children:i}):null]})})},"TooltipContentImpl"));function u5t(s,t){const n=Math.abs(t.top-s.y),r=Math.abs(t.bottom-s.y),a=Math.abs(t.right-s.x),i=Math.abs(t.left-s.x);switch(Math.min(n,r,a,i)){case i:return"left";case a:return"right";case n:return"top";case r:return"bottom";default:throw new Error("unreachable")}}nv(u5t,"getExitSideFromRect");function h5t(s,t,n=5){const r=[];switch(t){case"top":r.push({x:s.x-n,y:s.y+n},{x:s.x+n,y:s.y+n});break;case"bottom":r.push({x:s.x-n,y:s.y-n},{x:s.x+n,y:s.y-n});break;case"left":r.push({x:s.x+n,y:s.y-n},{x:s.x+n,y:s.y+n});break;case"right":r.push({x:s.x-n,y:s.y-n},{x:s.x-n,y:s.y+n});break}return r}nv(h5t,"getPaddedExitPoints");function m5t(s){const{top:t,right:n,bottom:r,left:a}=s;return[{x:a,y:t},{x:n,y:t},{x:n,y:r},{x:a,y:r}]}nv(m5t,"getPointsFromRect");function f5t(s,t){const{x:n,y:r}=s;let a=!1;for(let i=0,l=t.length-1;ir!=m>r&&n<(h-d)*(r-u)/(m-u)+d&&(a=!a)}return a}nv(f5t,"isPointInPolygon");function p5t(s){const t=s.slice();return t.sort((n,r)=>n.xr.x?1:n.yr.y?1:0),g5t(t)}nv(p5t,"getHull");function g5t(s){if(s.length<=1)return s.slice();const t=[];for(let r=0;r=2;){const i=t[t.length-1],l=t[t.length-2];if((i.x-l.x)*(a.y-l.y)>=(i.y-l.y)*(a.x-l.x))t.pop();else break}t.push(a)}t.pop();const n=[];for(let r=s.length-1;r>=0;r--){const a=s[r];for(;n.length>=2;){const i=n[n.length-1],l=n[n.length-2];if((i.x-l.x)*(a.y-l.y)>=(i.y-l.y)*(a.x-l.x))n.pop();else break}n.push(a)}return n.pop(),t.length===1&&n.length===1&&t[0].x===n[0].x&&t[0].y===n[0].y?t:t.concat(n)}nv(g5t,"getHullPresorted");var Gis=Ois,Wis=zis,Kis=Bis,x5t=qis;const Sk=Gis,Lx=Wis,Rx=Kis,Jg=k.forwardRef(({className:s,sideOffset:t=4,...n},r)=>e.jsx(x5t,{ref:r,sideOffset:t,className:Ot("z-50 overflow-hidden rounded-md border bg-popover px-3 py-1.5 text-sm text-popover-foreground shadow-md animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",s),...n}));Jg.displayName=x5t.displayName;var Oq=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(){}},wD,RE,KB,Yjt,Yis=(Yjt=class extends Oq{constructor(){super();ds(this,wD);ds(this,RE);ds(this,KB);$t(this,KB,t=>{if(typeof window<"u"&&window.addEventListener){const n=()=>t();return window.addEventListener("visibilitychange",n,!1),()=>{window.removeEventListener("visibilitychange",n)}}})}onSubscribe(){ge(this,RE)||this.setEventListener(ge(this,KB))}onUnsubscribe(){var t;this.hasListeners()||((t=ge(this,RE))==null||t.call(this),$t(this,RE,void 0))}setEventListener(t){var n;$t(this,KB,t),(n=ge(this,RE))==null||n.call(this),$t(this,RE,t(r=>{typeof r=="boolean"?this.setFocused(r):this.onFocus()}))}setFocused(t){ge(this,wD)!==t&&($t(this,wD,t),this.onFocus())}onFocus(){const t=this.isFocused();this.listeners.forEach(n=>{n(t)})}isFocused(){var t;return typeof ge(this,wD)=="boolean"?ge(this,wD):((t=globalThis.document)==null?void 0:t.visibilityState)!=="hidden"}},wD=new WeakMap,RE=new WeakMap,KB=new WeakMap,Yjt),oHe=new Yis,Zis={setTimeout:(s,t)=>setTimeout(s,t),clearTimeout:s=>clearTimeout(s),setInterval:(s,t)=>setInterval(s,t),clearInterval:s=>clearInterval(s)},DE,Vqe,Zjt,Xis=(Zjt=class{constructor(){ds(this,DE,Zis);ds(this,Vqe,!1)}setTimeoutProvider(s){$t(this,DE,s)}setTimeout(s,t){return ge(this,DE).setTimeout(s,t)}clearTimeout(s){ge(this,DE).clearTimeout(s)}setInterval(s,t){return ge(this,DE).setInterval(s,t)}clearInterval(s){ge(this,DE).clearInterval(s)}},DE=new WeakMap,Vqe=new WeakMap,Zjt),sD=new Xis;function Qis(s){setTimeout(s,0)}var Jis=typeof window>"u"||"Deno"in globalThis;function J1(){}function eos(s,t){return typeof s=="function"?s(t):s}function vFe(s){return typeof s=="number"&&s>=0&&s!==1/0}function y5t(s,t){return Math.max(s+(t||0)-Date.now(),0)}function oM(s,t){return typeof s=="function"?s(t):s}function Ow(s,t){return typeof s=="function"?s(t):s}function dit(s,t){const{type:n="all",exact:r,fetchStatus:a,predicate:i,queryKey:l,stale:o}=s;if(l){if(r){if(t.queryHash!==lHe(l,t.options))return!1}else if(!mU(t.queryKey,l))return!1}if(n!=="all"){const c=t.isActive();if(n==="active"&&!c||n==="inactive"&&c)return!1}return!(typeof o=="boolean"&&t.isStale()!==o||a&&a!==t.state.fetchStatus||i&&!i(t))}function uit(s,t){const{exact:n,status:r,predicate:a,mutationKey:i}=s;if(i){if(!t.options.mutationKey)return!1;if(n){if(EO(t.options.mutationKey)!==EO(i))return!1}else if(!mU(t.options.mutationKey,i))return!1}return!(r&&t.state.status!==r||a&&!a(t))}function lHe(s,t){return((t==null?void 0:t.queryKeyHashFn)||EO)(s)}function EO(s){return JSON.stringify(s,(t,n)=>bFe(n)?Object.keys(n).sort().reduce((r,a)=>(r[a]=n[a],r),{}):n)}function mU(s,t){if(s===t)return!0;if(typeof s!=typeof t)return!1;if(s&&t&&typeof s=="object"&&typeof t=="object"){if(Array.isArray(s)&&Array.isArray(t)){for(let r=0;r500)return t;const r=hit(s)&&hit(t);if(!r&&!(bFe(s)&&bFe(t)))return t;const i=(r?s:Object.keys(s)).length,l=r?t:Object.keys(t),o=l.length,c=r?new Array(o):{};let d=0;for(let u=0;u{sD.setTimeout(t,s)})}function _Fe(s,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(s,t):n.structuralSharing!==!1?v5t(s,t):t}function nos(s,t,n=0){const r=[...s,t];return n&&r.length>n?r.slice(1):r}function ros(s,t,n=0){const r=[t,...s];return n&&r.length>n?r.slice(0,-1):r}var cHe=Symbol();function b5t(s,t){return!s.queryFn&&(t!=null&&t.initialPromise)?()=>t.initialPromise:!s.queryFn||s.queryFn===cHe?()=>Promise.reject(new Error(`Missing queryFn: '${s.queryHash}'`)):s.queryFn}function dHe(s,t){return typeof s=="function"?s(...t):!!s}function aos(s,t,n){let r=!1,a;return Object.defineProperty(s,"signal",{enumerable:!0,get:()=>(a??(a=t()),r||(r=!0,a.aborted?n():a.addEventListener("abort",n,{once:!0})),a)}),s}var FZ=(()=>{let s=()=>Jis;return{isServer(){return s()},setIsServer(t){s=t}}})();function wFe(){let s,t;const n=new Promise((a,i)=>{s=a,t=i});n.status="pending",n.catch(()=>{});function r(a){Object.assign(n,a),delete n.resolve,delete n.reject}return n.resolve=a=>{r({status:"fulfilled",value:a}),s(a)},n.reject=a=>{r({status:"rejected",reason:a}),t(a)},n}var ios=Qis;function oos(){let s=[],t=0,n=o=>{o()},r=o=>{o()},a=ios;const i=o=>{t?s.push(o):a(()=>{n(o)})},l=()=>{const o=s;s=[],o.length&&a(()=>{r(()=>{o.forEach(c=>{n(c)})})})};return{batch:o=>{let c;t++;try{c=o()}finally{t--,t||l()}return c},batchCalls:o=>(...c)=>{i(()=>{o(...c)})},schedule:i,setNotifyFunction:o=>{n=o},setBatchNotifyFunction:o=>{r=o},setScheduler:o=>{a=o}}}var gy=oos(),YB,OE,ZB,Xjt,los=(Xjt=class extends Oq{constructor(){super();ds(this,YB,!0);ds(this,OE);ds(this,ZB);$t(this,ZB,t=>{if(typeof window<"u"&&window.addEventListener){const n=()=>t(!0),r=()=>t(!1);return window.addEventListener("online",n,!1),window.addEventListener("offline",r,!1),()=>{window.removeEventListener("online",n),window.removeEventListener("offline",r)}}})}onSubscribe(){ge(this,OE)||this.setEventListener(ge(this,ZB))}onUnsubscribe(){var t;this.hasListeners()||((t=ge(this,OE))==null||t.call(this),$t(this,OE,void 0))}setEventListener(t){var n;$t(this,ZB,t),(n=ge(this,OE))==null||n.call(this),$t(this,OE,t(this.setOnline.bind(this)))}setOnline(t){ge(this,YB)!==t&&($t(this,YB,t),this.listeners.forEach(r=>{r(t)}))}isOnline(){return ge(this,YB)}},YB=new WeakMap,OE=new WeakMap,ZB=new WeakMap,Xjt),tSe=new los;function cos(s){return Math.min(1e3*2**s,3e4)}function _5t(s){return(s??"online")==="online"?tSe.isOnline():!0}var jFe=class extends Error{constructor(s){super("CancelledError"),this.revert=s==null?void 0:s.revert,this.silent=s==null?void 0:s.silent}};function w5t(s){let t=!1,n=0,r;const a=wFe(),i=()=>a.status!=="pending",l=x=>{var y;if(!i()){const v=new jFe(x);m(v),(y=s.onCancel)==null||y.call(s,v)}},o=()=>{t=!0},c=()=>{t=!1},d=()=>oHe.isFocused()&&(s.networkMode==="always"||tSe.isOnline())&&s.canRun(),u=()=>_5t(s.networkMode)&&s.canRun(),h=x=>{i()||(r==null||r(),a.resolve(x))},m=x=>{i()||(r==null||r(),a.reject(x))},p=()=>new Promise(x=>{var y;r=v=>{(i()||d())&&x(v)},(y=s.onPause)==null||y.call(s)}).then(()=>{var x;r=void 0,i()||(x=s.onContinue)==null||x.call(s)}),g=()=>{if(i())return;let x;const y=n===0?s.initialPromise:void 0;try{x=y??s.fn()}catch(v){x=Promise.reject(v)}Promise.resolve(x).then(h).catch(v=>{var M;if(i())return;const _=s.retry??(FZ.isServer()?0:3),j=s.retryDelay??cos,C=typeof j=="function"?j(n,v):j,A=_===!0||typeof _=="number"&&n<_||typeof _=="function"&&_(n,v);if(t||!A){m(v);return}n++,(M=s.onFail)==null||M.call(s,n,v),sos(C).then(()=>d()?void 0:p()).then(()=>{t?m(v):g()})})};return{promise:a,status:()=>a.status,cancel:l,continue:()=>(r==null||r(),a),cancelRetry:o,continueRetry:c,canStart:u,start:()=>(u()?g():p().then(g),a)}}var jD,Qjt,j5t=(Qjt=class{constructor(){ds(this,jD)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),vFe(this.gcTime)&&$t(this,jD,sD.setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(s){this.gcTime=Math.max(this.gcTime||0,s??(FZ.isServer()?1/0:5*60*1e3))}clearGcTimeout(){ge(this,jD)!==void 0&&(sD.clearTimeout(ge(this,jD)),$t(this,jD,void 0))}},jD=new WeakMap,Qjt);function dos(s){return{onFetch:(t,n)=>{var u,h,m,p,g;const r=t.options,a=(m=(h=(u=t.fetchOptions)==null?void 0:u.meta)==null?void 0:h.fetchMore)==null?void 0:m.direction,i=((p=t.state.data)==null?void 0:p.pages)||[],l=((g=t.state.data)==null?void 0:g.pageParams)||[];let o={pages:[],pageParams:[]},c=0;const d=async()=>{let x=!1;const y=j=>{aos(j,()=>t.signal,()=>x=!0)},v=b5t(t.options,t.fetchOptions),_=async(j,C,A)=>{if(x)return Promise.reject(t.signal.reason);if(C==null&&j.pages.length)return Promise.resolve(j);const I=(()=>{const B={client:t.client,queryKey:t.queryKey,pageParam:C,direction:A?"backward":"forward",meta:t.options.meta};return y(B),B})(),P=await v(I),{maxPages:R}=t.options,O=A?ros:nos;return{pages:O(j.pages,P,R),pageParams:O(j.pageParams,C,R)}};if(a&&i.length){const j=a==="backward",C=j?N5t:NFe,A={pages:i,pageParams:l},M=C(r,A);o=await _(A,M,j)}else{const j=s??i.length;do{const C=c===0?l[0]??r.initialPageParam:NFe(r,o);if(c>0&&C==null)break;o=await _(o,C),c++}while(c{var x,y;return(y=(x=t.options).persister)==null?void 0:y.call(x,d,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n)}:t.fetchFn=d}}}function NFe(s,{pages:t,pageParams:n}){const r=t.length-1;return t.length>0?s.getNextPageParam(t[r],t,n[r],n):void 0}function N5t(s,{pages:t,pageParams:n}){var r;return t.length>0?(r=s.getPreviousPageParam)==null?void 0:r.call(s,t[0],t,n[0],n):void 0}function uos(s,t){return t?NFe(s,t)!=null:!1}function hos(s,t){return!t||!s.getPreviousPageParam?!1:N5t(s,t)!=null}var XB,ND,QB,Gj,kD,Zy,CQ,SD,Dw,k5t,iC,Jjt,mos=(Jjt=class extends j5t{constructor(t){super();ds(this,Dw);ds(this,XB);ds(this,ND);ds(this,QB);ds(this,Gj);ds(this,kD);ds(this,Zy);ds(this,CQ);ds(this,SD);$t(this,SD,!1),$t(this,CQ,t.defaultOptions),this.setOptions(t.options),this.observers=[],$t(this,kD,t.client),$t(this,Gj,ge(this,kD).getQueryCache()),this.queryKey=t.queryKey,this.queryHash=t.queryHash,$t(this,ND,pit(this.options)),this.state=t.state??ge(this,ND),this.scheduleGc()}get meta(){return this.options.meta}get queryType(){return ge(this,XB)}get promise(){var t;return(t=ge(this,Zy))==null?void 0:t.promise}setOptions(t){if(this.options={...ge(this,CQ),...t},t!=null&&t._type&&$t(this,XB,t._type),this.updateGcTime(this.options.gcTime),this.state&&this.state.data===void 0){const n=pit(this.options);n.data!==void 0&&(this.setState(fit(n.data,n.dataUpdatedAt)),$t(this,ND,n))}}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&ge(this,Gj).remove(this)}setData(t,n){const r=_Fe(this.state.data,t,this.options);return ss(this,Dw,iC).call(this,{data:r,type:"success",dataUpdatedAt:n==null?void 0:n.updatedAt,manual:n==null?void 0:n.manual}),r}setState(t){ss(this,Dw,iC).call(this,{type:"setState",state:t})}cancel(t){var r,a;const n=(r=ge(this,Zy))==null?void 0:r.promise;return(a=ge(this,Zy))==null||a.cancel(t),n?n.then(J1).catch(J1):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}get resetState(){return ge(this,ND)}reset(){this.destroy(),this.setState(this.resetState)}isActive(){return this.observers.some(t=>Ow(t.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===cHe||!this.isFetched()}isFetched(){return this.state.dataUpdateCount+this.state.errorUpdateCount>0}isStatic(){return this.getObserversCount()>0?this.observers.some(t=>oM(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:!y5t(this.state.dataUpdatedAt,t)}onFocus(){var n;const t=this.observers.find(r=>r.shouldFetchOnWindowFocus());t==null||t.refetch({cancelRefetch:!1}),(n=ge(this,Zy))==null||n.continue()}onOnline(){var n;const t=this.observers.find(r=>r.shouldFetchOnReconnect());t==null||t.refetch({cancelRefetch:!1}),(n=ge(this,Zy))==null||n.continue()}addObserver(t){this.observers.includes(t)||(this.observers.push(t),this.clearGcTimeout(),ge(this,Gj).notify({type:"observerAdded",query:this,observer:t}))}removeObserver(t){this.observers.includes(t)&&(this.observers=this.observers.filter(n=>n!==t),this.observers.length||(ge(this,Zy)&&(ge(this,SD)||ss(this,Dw,k5t).call(this)?ge(this,Zy).cancel({revert:!0}):ge(this,Zy).cancelRetry()),this.scheduleGc()),ge(this,Gj).notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||ss(this,Dw,iC).call(this,{type:"invalidate"})}async fetch(t,n){var d,u,h,m,p,g,x,y,v,_,j;if(this.state.fetchStatus!=="idle"&&((d=ge(this,Zy))==null?void 0:d.status())!=="rejected"){if(this.state.data!==void 0&&(n!=null&&n.cancelRefetch))this.cancel({silent:!0});else if(ge(this,Zy))return ge(this,Zy).continueRetry(),ge(this,Zy).promise}if(t&&this.setOptions(t),!this.options.queryFn){const C=this.observers.find(A=>A.options.queryFn);C&&this.setOptions(C.options)}const r=new AbortController,a=C=>{Object.defineProperty(C,"signal",{enumerable:!0,get:()=>($t(this,SD,!0),r.signal)})},i=()=>{const C=b5t(this.options,n),M=(()=>{const I={client:ge(this,kD),queryKey:this.queryKey,meta:this.meta};return a(I),I})();return $t(this,SD,!1),this.options.persister?this.options.persister(C,M,this):C(M)},o=(()=>{const C={fetchOptions:n,options:this.options,queryKey:this.queryKey,client:ge(this,kD),state:this.state,fetchFn:i};return a(C),C})(),c=ge(this,XB)==="infinite"?dos(this.options.pages):this.options.behavior;c==null||c.onFetch(o,this),$t(this,QB,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==((u=o.fetchOptions)==null?void 0:u.meta))&&ss(this,Dw,iC).call(this,{type:"fetch",meta:(h=o.fetchOptions)==null?void 0:h.meta}),$t(this,Zy,w5t({initialPromise:n==null?void 0:n.initialPromise,fn:o.fetchFn,onCancel:C=>{C instanceof jFe&&C.revert&&this.setState({...ge(this,QB),fetchStatus:"idle"}),r.abort()},onFail:(C,A)=>{ss(this,Dw,iC).call(this,{type:"failed",failureCount:C,error:A})},onPause:()=>{ss(this,Dw,iC).call(this,{type:"pause"})},onContinue:()=>{ss(this,Dw,iC).call(this,{type:"continue"})},retry:o.options.retry,retryDelay:o.options.retryDelay,networkMode:o.options.networkMode,canRun:()=>!0}));try{const C=await ge(this,Zy).start();if(C===void 0)throw new Error(`${this.queryHash} data is undefined`);return this.setData(C),(p=(m=ge(this,Gj).config).onSuccess)==null||p.call(m,C,this),(x=(g=ge(this,Gj).config).onSettled)==null||x.call(g,C,this.state.error,this),C}catch(C){if(C instanceof jFe){if(C.silent)return ge(this,Zy).promise;if(C.revert){if(this.state.data===void 0)throw C;return this.state.data}}throw ss(this,Dw,iC).call(this,{type:"error",error:C}),(v=(y=ge(this,Gj).config).onError)==null||v.call(y,C,this),(j=(_=ge(this,Gj).config).onSettled)==null||j.call(_,this.state.data,C,this),C}finally{this.scheduleGc()}}},XB=new WeakMap,ND=new WeakMap,QB=new WeakMap,Gj=new WeakMap,kD=new WeakMap,Zy=new WeakMap,CQ=new WeakMap,SD=new WeakMap,Dw=new WeakSet,k5t=function(){return this.state.fetchStatus==="paused"&&this.state.status==="pending"},iC=function(t){const n=r=>{switch(t.type){case"failed":return{...r,fetchFailureCount:t.failureCount,fetchFailureReason:t.error};case"pause":return{...r,fetchStatus:"paused"};case"continue":return{...r,fetchStatus:"fetching"};case"fetch":return{...r,...S5t(r.data,this.options),fetchMeta:t.meta??null};case"success":const a={...r,...fit(t.data,t.dataUpdatedAt),dataUpdateCount:r.dataUpdateCount+1,...!t.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};return $t(this,QB,t.manual?a:void 0),a;case"error":const i=t.error;return{...r,error:i,errorUpdateCount:r.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:r.fetchFailureCount+1,fetchFailureReason:i,fetchStatus:"idle",status:"error",isInvalidated:!0};case"invalidate":return{...r,isInvalidated:!0};case"setState":return{...r,...t.state}}};this.state=n(this.state),gy.batch(()=>{this.observers.forEach(r=>{r.onQueryUpdate()}),ge(this,Gj).notify({query:this,type:"updated",action:t})})},Jjt);function S5t(s,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:_5t(t.networkMode)?"fetching":"paused",...s===void 0&&{error:null,status:"pending"}}}function fit(s,t){return{data:s,dataUpdatedAt:t??Date.now(),error:null,isInvalidated:!1,status:"success"}}function pit(s){const t=typeof s.initialData=="function"?s.initialData():s.initialData,n=t!==void 0,r=n?typeof s.initialDataUpdatedAt=="function"?s.initialDataUpdatedAt():s.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?"success":"pending",fetchStatus:"idle"}}var e_,tu,AQ,X1,CD,JB,kC,FE,EQ,e$,t$,AD,ED,zE,s$,vh,_W,kFe,SFe,CFe,AFe,EFe,TFe,MFe,A5t,e2t,C5t=(e2t=class extends Oq{constructor(t,n){super();ds(this,vh);ds(this,e_);ds(this,tu);ds(this,AQ);ds(this,X1);ds(this,CD);ds(this,JB);ds(this,kC);ds(this,FE);ds(this,EQ);ds(this,e$);ds(this,t$);ds(this,AD);ds(this,ED);ds(this,zE);ds(this,s$,new Set);this.options=n,$t(this,e_,t),$t(this,FE,null),$t(this,kC,wFe()),this.bindMethods(),this.setOptions(n)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(ge(this,tu).addObserver(this),git(ge(this,tu),this.options)?ss(this,vh,_W).call(this):this.updateResult(),ss(this,vh,AFe).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return PFe(ge(this,tu),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return PFe(ge(this,tu),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,ss(this,vh,EFe).call(this),ss(this,vh,TFe).call(this),ge(this,tu).removeObserver(this)}setOptions(t){const n=this.options,r=ge(this,tu);if(this.options=ge(this,e_).defaultQueryOptions(t),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof Ow(this.options.enabled,ge(this,tu))!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");ss(this,vh,MFe).call(this),ge(this,tu).setOptions(this.options),n._defaulted&&!eSe(this.options,n)&&ge(this,e_).getQueryCache().notify({type:"observerOptionsUpdated",query:ge(this,tu),observer:this});const a=this.hasListeners();a&&xit(ge(this,tu),r,this.options,n)&&ss(this,vh,_W).call(this),this.updateResult(),a&&(ge(this,tu)!==r||Ow(this.options.enabled,ge(this,tu))!==Ow(n.enabled,ge(this,tu))||oM(this.options.staleTime,ge(this,tu))!==oM(n.staleTime,ge(this,tu)))&&ss(this,vh,kFe).call(this);const i=ss(this,vh,SFe).call(this);a&&(ge(this,tu)!==r||Ow(this.options.enabled,ge(this,tu))!==Ow(n.enabled,ge(this,tu))||i!==ge(this,zE))&&ss(this,vh,CFe).call(this,i)}getOptimisticResult(t){const n=ge(this,e_).getQueryCache().build(ge(this,e_),t),r=this.createResult(n,t);return pos(this,r)&&($t(this,X1,r),$t(this,JB,this.options),$t(this,CD,ge(this,tu).state)),r}getCurrentResult(){return ge(this,X1)}trackResult(t,n){return new Proxy(t,{get:(r,a)=>(this.trackProp(a),n==null||n(a),a==="promise"&&(this.trackProp("data"),!this.options.experimental_prefetchInRender&&ge(this,kC).status==="pending"&&ge(this,kC).reject(new Error("experimental_prefetchInRender feature flag is not enabled"))),Reflect.get(r,a))})}trackProp(t){ge(this,s$).add(t)}getCurrentQuery(){return ge(this,tu)}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){const n=ge(this,e_).defaultQueryOptions(t),r=ge(this,e_).getQueryCache().build(ge(this,e_),n);return r.fetch().then(()=>this.createResult(r,n))}fetch(t){return ss(this,vh,_W).call(this,{...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),ge(this,X1)))}createResult(t,n){var R;const r=ge(this,tu),a=this.options,i=ge(this,X1),l=ge(this,CD),o=ge(this,JB),d=t!==r?t.state:ge(this,AQ),{state:u}=t;let h={...u},m=!1,p;if(n._optimisticResults){const O=this.hasListeners(),B=!O&&git(t,n),U=O&&xit(t,r,n,a);(B||U)&&(h={...h,...S5t(u.data,t.options)}),n._optimisticResults==="isRestoring"&&(h.fetchStatus="idle")}let{error:g,errorUpdatedAt:x,status:y}=h;p=h.data;let v=!1;if(n.placeholderData!==void 0&&p===void 0&&y==="pending"){let O;i!=null&&i.isPlaceholderData&&n.placeholderData===(o==null?void 0:o.placeholderData)?(O=i.data,v=!0):O=typeof n.placeholderData=="function"?n.placeholderData((R=ge(this,t$))==null?void 0:R.state.data,ge(this,t$)):n.placeholderData,O!==void 0&&(y="success",p=_Fe(i==null?void 0:i.data,O,n),m=!0)}if(n.select&&p!==void 0&&!v)if(i&&p===(l==null?void 0:l.data)&&n.select===ge(this,EQ))p=ge(this,e$);else try{$t(this,EQ,n.select),p=n.select(p),p=_Fe(i==null?void 0:i.data,p,n),$t(this,e$,p),$t(this,FE,null)}catch(O){$t(this,FE,O)}ge(this,FE)&&(g=ge(this,FE),p=ge(this,e$),x=Date.now(),y="error");const _=h.fetchStatus==="fetching",j=y==="pending",C=y==="error",A=j&&_,M=p!==void 0,P={status:y,fetchStatus:h.fetchStatus,isPending:j,isSuccess:y==="success",isError:C,isInitialLoading:A,isLoading:A,data:p,dataUpdatedAt:h.dataUpdatedAt,error:g,errorUpdatedAt:x,failureCount:h.fetchFailureCount,failureReason:h.fetchFailureReason,errorUpdateCount:h.errorUpdateCount,isFetched:t.isFetched(),isFetchedAfterMount:h.dataUpdateCount>d.dataUpdateCount||h.errorUpdateCount>d.errorUpdateCount,isFetching:_,isRefetching:_&&!j,isLoadingError:C&&!M,isPaused:h.fetchStatus==="paused",isPlaceholderData:m,isRefetchError:C&&M,isStale:uHe(t,n),refetch:this.refetch,promise:ge(this,kC),isEnabled:Ow(n.enabled,t)!==!1};if(this.options.experimental_prefetchInRender){const O=P.data!==void 0,B=P.status==="error"&&!O,U=Y=>{B?Y.reject(P.error):O&&Y.resolve(P.data)},G=()=>{const Y=$t(this,kC,P.promise=wFe());U(Y)},H=ge(this,kC);switch(H.status){case"pending":t.queryHash===r.queryHash&&U(H);break;case"fulfilled":(B||P.data!==H.value)&&G();break;case"rejected":(!B||P.error!==H.reason)&&G();break}}return P}updateResult(){const t=ge(this,X1),n=this.createResult(ge(this,tu),this.options);if($t(this,CD,ge(this,tu).state),$t(this,JB,this.options),ge(this,CD).data!==void 0&&$t(this,t$,ge(this,tu)),eSe(n,t))return;$t(this,X1,n);const r=()=>{if(!t)return!0;const{notifyOnChangeProps:a}=this.options,i=typeof a=="function"?a():a;if(i==="all"||!i&&!ge(this,s$).size)return!0;const l=new Set(i??ge(this,s$));return this.options.throwOnError&&l.add("error"),Object.keys(ge(this,X1)).some(o=>{const c=o;return ge(this,X1)[c]!==t[c]&&l.has(c)})};ss(this,vh,A5t).call(this,{listeners:r()})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&ss(this,vh,AFe).call(this)}},e_=new WeakMap,tu=new WeakMap,AQ=new WeakMap,X1=new WeakMap,CD=new WeakMap,JB=new WeakMap,kC=new WeakMap,FE=new WeakMap,EQ=new WeakMap,e$=new WeakMap,t$=new WeakMap,AD=new WeakMap,ED=new WeakMap,zE=new WeakMap,s$=new WeakMap,vh=new WeakSet,_W=function(t){ss(this,vh,MFe).call(this);let n=ge(this,tu).fetch(this.options,t);return t!=null&&t.throwOnError||(n=n.catch(J1)),n},kFe=function(){ss(this,vh,EFe).call(this);const t=oM(this.options.staleTime,ge(this,tu));if(FZ.isServer()||ge(this,X1).isStale||!vFe(t))return;const r=y5t(ge(this,X1).dataUpdatedAt,t)+1;$t(this,AD,sD.setTimeout(()=>{ge(this,X1).isStale||this.updateResult()},r))},SFe=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(ge(this,tu)):this.options.refetchInterval)??!1},CFe=function(t){ss(this,vh,TFe).call(this),$t(this,zE,t),!(FZ.isServer()||Ow(this.options.enabled,ge(this,tu))===!1||!vFe(ge(this,zE))||ge(this,zE)===0)&&$t(this,ED,sD.setInterval(()=>{(this.options.refetchIntervalInBackground||oHe.isFocused())&&ss(this,vh,_W).call(this)},ge(this,zE)))},AFe=function(){ss(this,vh,kFe).call(this),ss(this,vh,CFe).call(this,ss(this,vh,SFe).call(this))},EFe=function(){ge(this,AD)!==void 0&&(sD.clearTimeout(ge(this,AD)),$t(this,AD,void 0))},TFe=function(){ge(this,ED)!==void 0&&(sD.clearInterval(ge(this,ED)),$t(this,ED,void 0))},MFe=function(){const t=ge(this,e_).getQueryCache().build(ge(this,e_),this.options);if(t===ge(this,tu))return;const n=ge(this,tu);$t(this,tu,t),$t(this,AQ,t.state),this.hasListeners()&&(n==null||n.removeObserver(this),t.addObserver(this))},A5t=function(t){gy.batch(()=>{t.listeners&&this.listeners.forEach(n=>{n(ge(this,X1))}),ge(this,e_).getQueryCache().notify({query:ge(this,tu),type:"observerResultsUpdated"})})},e2t);function fos(s,t){return Ow(t.enabled,s)!==!1&&s.state.data===void 0&&!(s.state.status==="error"&&Ow(t.retryOnMount,s)===!1)}function git(s,t){return fos(s,t)||s.state.data!==void 0&&PFe(s,t,t.refetchOnMount)}function PFe(s,t,n){if(Ow(t.enabled,s)!==!1&&oM(t.staleTime,s)!=="static"){const r=typeof n=="function"?n(s):n;return r==="always"||r!==!1&&uHe(s,t)}return!1}function xit(s,t,n,r){return(s!==t||Ow(r.enabled,s)===!1)&&(!n.suspense||s.state.status!=="error")&&uHe(s,n)}function uHe(s,t){return Ow(t.enabled,s)!==!1&&s.isStaleByTime(oM(t.staleTime,s))}function pos(s,t){return!eSe(s.getCurrentResult(),t)}var gos=class extends C5t{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 g,x;const{state:n}=s,r=super.createResult(s,t),{isFetching:a,isRefetching:i,isError:l,isRefetchError:o}=r,c=(x=(g=n.fetchMeta)==null?void 0:g.fetchMore)==null?void 0:x.direction,d=l&&c==="forward",u=a&&c==="forward",h=l&&c==="backward",m=a&&c==="backward";return{...r,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:uos(t,n.data),hasPreviousPage:hos(t,n.data),isFetchNextPageError:d,isFetchingNextPage:u,isFetchPreviousPageError:h,isFetchingPreviousPage:m,isRefetchError:o&&!d&&!h,isRefetching:i&&!u&&!m}}},TQ,DS,Kv,TD,OS,QA,t2t,xos=(t2t=class extends j5t{constructor(t){super();ds(this,OS);ds(this,TQ);ds(this,DS);ds(this,Kv);ds(this,TD);$t(this,TQ,t.client),this.mutationId=t.mutationId,$t(this,Kv,t.mutationCache),$t(this,DS,[]),this.state=t.state||E5t(),this.setOptions(t.options),this.scheduleGc()}setOptions(t){this.options=t,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(t){ge(this,DS).includes(t)||(ge(this,DS).push(t),this.clearGcTimeout(),ge(this,Kv).notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){$t(this,DS,ge(this,DS).filter(n=>n!==t)),this.scheduleGc(),ge(this,Kv).notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){ge(this,DS).length||(this.state.status==="pending"?this.scheduleGc():ge(this,Kv).remove(this))}continue(){var t;return((t=ge(this,TD))==null?void 0:t.continue())??this.execute(this.state.variables)}async execute(t){var l,o,c,d,u,h,m,p,g,x,y,v,_,j,C,A,M,I;const n=()=>{ss(this,OS,QA).call(this,{type:"continue"})},r={client:ge(this,TQ),meta:this.options.meta,mutationKey:this.options.mutationKey};$t(this,TD,w5t({fn:()=>this.options.mutationFn?this.options.mutationFn(t,r):Promise.reject(new Error("No mutationFn found")),onFail:(P,R)=>{ss(this,OS,QA).call(this,{type:"failed",failureCount:P,error:R})},onPause:()=>{ss(this,OS,QA).call(this,{type:"pause"})},onContinue:n,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>ge(this,Kv).canRun(this)}));const a=this.state.status==="pending",i=!ge(this,TD).canStart();try{if(a)n();else{ss(this,OS,QA).call(this,{type:"pending",variables:t,isPaused:i}),ge(this,Kv).config.onMutate&&await ge(this,Kv).config.onMutate(t,this,r);const R=await((o=(l=this.options).onMutate)==null?void 0:o.call(l,t,r));R!==this.state.context&&ss(this,OS,QA).call(this,{type:"pending",context:R,variables:t,isPaused:i})}const P=await ge(this,TD).start();return await((d=(c=ge(this,Kv).config).onSuccess)==null?void 0:d.call(c,P,t,this.state.context,this,r)),await((h=(u=this.options).onSuccess)==null?void 0:h.call(u,P,t,this.state.context,r)),await((p=(m=ge(this,Kv).config).onSettled)==null?void 0:p.call(m,P,null,this.state.variables,this.state.context,this,r)),await((x=(g=this.options).onSettled)==null?void 0:x.call(g,P,null,t,this.state.context,r)),ss(this,OS,QA).call(this,{type:"success",data:P}),P}catch(P){try{await((v=(y=ge(this,Kv).config).onError)==null?void 0:v.call(y,P,t,this.state.context,this,r))}catch(R){Promise.reject(R)}try{await((j=(_=this.options).onError)==null?void 0:j.call(_,P,t,this.state.context,r))}catch(R){Promise.reject(R)}try{await((A=(C=ge(this,Kv).config).onSettled)==null?void 0:A.call(C,void 0,P,this.state.variables,this.state.context,this,r))}catch(R){Promise.reject(R)}try{await((I=(M=this.options).onSettled)==null?void 0:I.call(M,void 0,P,t,this.state.context,r))}catch(R){Promise.reject(R)}throw ss(this,OS,QA).call(this,{type:"error",error:P}),P}finally{ge(this,Kv).runNext(this)}}},TQ=new WeakMap,DS=new WeakMap,Kv=new WeakMap,TD=new WeakMap,OS=new WeakSet,QA=function(t){const n=r=>{switch(t.type){case"failed":return{...r,failureCount:t.failureCount,failureReason:t.error};case"pause":return{...r,isPaused:!0};case"continue":return{...r,isPaused:!1};case"pending":return{...r,context:t.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:t.isPaused,status:"pending",variables:t.variables,submittedAt:Date.now()};case"success":return{...r,data:t.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...r,data:void 0,error:t.error,failureCount:r.failureCount+1,failureReason:t.error,isPaused:!1,status:"error"}}};this.state=n(this.state),gy.batch(()=>{ge(this,DS).forEach(r=>{r.onMutationUpdate(t)}),ge(this,Kv).notify({mutation:this,type:"updated",action:t})})},t2t);function E5t(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var SC,kN,MQ,s2t,yos=(s2t=class extends Oq{constructor(t={}){super();ds(this,SC);ds(this,kN);ds(this,MQ);this.config=t,$t(this,SC,new Set),$t(this,kN,new Map),$t(this,MQ,0)}build(t,n,r){const a=new xos({client:t,mutationCache:this,mutationId:++Hy(this,MQ)._,options:t.defaultMutationOptions(n),state:r});return this.add(a),a}add(t){ge(this,SC).add(t);const n=Bne(t);if(typeof n=="string"){const r=ge(this,kN).get(n);r?r.push(t):ge(this,kN).set(n,[t])}this.notify({type:"added",mutation:t})}remove(t){if(ge(this,SC).delete(t)){const n=Bne(t);if(typeof n=="string"){const r=ge(this,kN).get(n);if(r)if(r.length>1){const a=r.indexOf(t);a!==-1&&r.splice(a,1)}else r[0]===t&&ge(this,kN).delete(n)}}this.notify({type:"removed",mutation:t})}canRun(t){const n=Bne(t);if(typeof n=="string"){const r=ge(this,kN).get(n),a=r==null?void 0:r.find(i=>i.state.status==="pending");return!a||a===t}else return!0}runNext(t){var r;const n=Bne(t);if(typeof n=="string"){const a=(r=ge(this,kN).get(n))==null?void 0:r.find(i=>i!==t&&i.state.isPaused);return(a==null?void 0:a.continue())??Promise.resolve()}else return Promise.resolve()}clear(){gy.batch(()=>{ge(this,SC).forEach(t=>{this.notify({type:"removed",mutation:t})}),ge(this,SC).clear(),ge(this,kN).clear()})}getAll(){return Array.from(ge(this,SC))}find(t){const n={exact:!0,...t};return this.getAll().find(r=>uit(n,r))}findAll(t={}){return this.getAll().filter(n=>uit(t,n))}notify(t){gy.batch(()=>{this.listeners.forEach(n=>{n(t)})})}resumePausedMutations(){const t=this.getAll().filter(n=>n.state.isPaused);return gy.batch(()=>Promise.all(t.map(n=>n.continue().catch(J1))))}},SC=new WeakMap,kN=new WeakMap,MQ=new WeakMap,s2t);function Bne(s){var t;return(t=s.options.scope)==null?void 0:t.id}var CC,BE,t_,AC,P3,Z2e,IFe,n2t,vos=(n2t=class extends Oq{constructor(n,r){super();ds(this,P3);ds(this,CC);ds(this,BE);ds(this,t_);ds(this,AC);$t(this,CC,n),this.setOptions(r),this.bindMethods(),ss(this,P3,Z2e).call(this)}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(n){var a;const r=this.options;this.options=ge(this,CC).defaultMutationOptions(n),eSe(this.options,r)||ge(this,CC).getMutationCache().notify({type:"observerOptionsUpdated",mutation:ge(this,t_),observer:this}),r!=null&&r.mutationKey&&this.options.mutationKey&&EO(r.mutationKey)!==EO(this.options.mutationKey)?this.reset():((a=ge(this,t_))==null?void 0:a.state.status)==="pending"&&ge(this,t_).setOptions(this.options)}onUnsubscribe(){var n;this.hasListeners()||(n=ge(this,t_))==null||n.removeObserver(this)}onMutationUpdate(n){ss(this,P3,Z2e).call(this),ss(this,P3,IFe).call(this,n)}getCurrentResult(){return ge(this,BE)}reset(){var n;(n=ge(this,t_))==null||n.removeObserver(this),$t(this,t_,void 0),ss(this,P3,Z2e).call(this),ss(this,P3,IFe).call(this)}mutate(n,r){var a;return $t(this,AC,r),(a=ge(this,t_))==null||a.removeObserver(this),$t(this,t_,ge(this,CC).getMutationCache().build(ge(this,CC),this.options)),ge(this,t_).addObserver(this),ge(this,t_).execute(n)}},CC=new WeakMap,BE=new WeakMap,t_=new WeakMap,AC=new WeakMap,P3=new WeakSet,Z2e=function(){var r;const n=((r=ge(this,t_))==null?void 0:r.state)??E5t();$t(this,BE,{...n,isPending:n.status==="pending",isSuccess:n.status==="success",isError:n.status==="error",isIdle:n.status==="idle",mutate:this.mutate,reset:this.reset})},IFe=function(n){gy.batch(()=>{var r,a,i,l,o,c,d,u;if(ge(this,AC)&&this.hasListeners()){const h=ge(this,BE).variables,m=ge(this,BE).context,p={client:ge(this,CC),meta:this.options.meta,mutationKey:this.options.mutationKey};if((n==null?void 0:n.type)==="success"){try{(a=(r=ge(this,AC)).onSuccess)==null||a.call(r,n.data,h,m,p)}catch(g){Promise.reject(g)}try{(l=(i=ge(this,AC)).onSettled)==null||l.call(i,n.data,null,h,m,p)}catch(g){Promise.reject(g)}}else if((n==null?void 0:n.type)==="error"){try{(c=(o=ge(this,AC)).onError)==null||c.call(o,n.error,h,m,p)}catch(g){Promise.reject(g)}try{(u=(d=ge(this,AC)).onSettled)==null||u.call(d,void 0,n.error,h,m,p)}catch(g){Promise.reject(g)}}}this.listeners.forEach(h=>{h(ge(this,BE))})})},n2t),FS,r2t,bos=(r2t=class extends Oq{constructor(t={}){super();ds(this,FS);this.config=t,$t(this,FS,new Map)}build(t,n,r){const a=n.queryKey,i=n.queryHash??lHe(a,n);let l=this.get(i);return l||(l=new mos({client:t,queryKey:a,queryHash:i,options:t.defaultQueryOptions(n),state:r,defaultOptions:t.getQueryDefaults(a)}),this.add(l)),l}add(t){ge(this,FS).has(t.queryHash)||(ge(this,FS).set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){const n=ge(this,FS).get(t.queryHash);n&&(t.destroy(),n===t&&ge(this,FS).delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){gy.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}get(t){return ge(this,FS).get(t)}getAll(){return[...ge(this,FS).values()]}find(t){const n={exact:!0,...t};return this.getAll().find(r=>dit(n,r))}findAll(t={}){const n=this.getAll();return Object.keys(t).length>0?n.filter(r=>dit(t,r)):n}notify(t){gy.batch(()=>{this.listeners.forEach(n=>{n(t)})})}onFocus(){gy.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){gy.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}},FS=new WeakMap,r2t),dg,$E,UE,n$,r$,qE,a$,i$,a2t,_os=(a2t=class{constructor(s={}){ds(this,dg);ds(this,$E);ds(this,UE);ds(this,n$);ds(this,r$);ds(this,qE);ds(this,a$);ds(this,i$);$t(this,dg,s.queryCache||new bos),$t(this,$E,s.mutationCache||new yos),$t(this,UE,s.defaultOptions||{}),$t(this,n$,new Map),$t(this,r$,new Map),$t(this,qE,0)}mount(){Hy(this,qE)._++,ge(this,qE)===1&&($t(this,a$,oHe.subscribe(async s=>{s&&(await this.resumePausedMutations(),ge(this,dg).onFocus())})),$t(this,i$,tSe.subscribe(async s=>{s&&(await this.resumePausedMutations(),ge(this,dg).onOnline())})))}unmount(){var s,t;Hy(this,qE)._--,ge(this,qE)===0&&((s=ge(this,a$))==null||s.call(this),$t(this,a$,void 0),(t=ge(this,i$))==null||t.call(this),$t(this,i$,void 0))}isFetching(s){return ge(this,dg).findAll({...s,fetchStatus:"fetching"}).length}isMutating(s){return ge(this,$E).findAll({...s,status:"pending"}).length}getQueryData(s){var n;const t=this.defaultQueryOptions({queryKey:s});return(n=ge(this,dg).get(t.queryHash))==null?void 0:n.state.data}ensureQueryData(s){const t=this.defaultQueryOptions(s),n=ge(this,dg).build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(s):(s.revalidateIfStale&&n.isStaleByTime(oM(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(s){return ge(this,dg).findAll(s).map(({queryKey:t,state:n})=>{const r=n.data;return[t,r]})}setQueryData(s,t,n){const r=this.defaultQueryOptions({queryKey:s}),a=ge(this,dg).get(r.queryHash),i=a==null?void 0:a.state.data,l=eos(t,i);if(l!==void 0)return ge(this,dg).build(this,r).setData(l,{...n,manual:!0})}setQueriesData(s,t,n){return gy.batch(()=>ge(this,dg).findAll(s).map(({queryKey:r})=>[r,this.setQueryData(r,t,n)]))}getQueryState(s){var n;const t=this.defaultQueryOptions({queryKey:s});return(n=ge(this,dg).get(t.queryHash))==null?void 0:n.state}removeQueries(s){const t=ge(this,dg);gy.batch(()=>{t.findAll(s).forEach(n=>{t.remove(n)})})}resetQueries(s,t){const n=ge(this,dg);return gy.batch(()=>(n.findAll(s).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...s},t)))}cancelQueries(s,t={}){const n={revert:!0,...t},r=gy.batch(()=>ge(this,dg).findAll(s).map(a=>a.cancel(n)));return Promise.all(r).then(J1).catch(J1)}invalidateQueries(s,t={}){return gy.batch(()=>(ge(this,dg).findAll(s).forEach(n=>{n.invalidate()}),(s==null?void 0:s.refetchType)==="none"?Promise.resolve():this.refetchQueries({...s,type:(s==null?void 0:s.refetchType)??(s==null?void 0:s.type)??"active"},t)))}refetchQueries(s,t={}){const n={...t,cancelRefetch:t.cancelRefetch??!0},r=gy.batch(()=>ge(this,dg).findAll(s).filter(a=>!a.isDisabled()&&!a.isStatic()).map(a=>{let i=a.fetch(void 0,n);return n.throwOnError||(i=i.catch(J1)),a.state.fetchStatus==="paused"?Promise.resolve():i}));return Promise.all(r).then(J1)}fetchQuery(s){const t=this.defaultQueryOptions(s);t.retry===void 0&&(t.retry=!1);const n=ge(this,dg).build(this,t);return n.isStaleByTime(oM(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(s){return this.fetchQuery(s).then(J1).catch(J1)}fetchInfiniteQuery(s){return s._type="infinite",this.fetchQuery(s)}prefetchInfiniteQuery(s){return this.fetchInfiniteQuery(s).then(J1).catch(J1)}ensureInfiniteQueryData(s){return s._type="infinite",this.ensureQueryData(s)}resumePausedMutations(){return tSe.isOnline()?ge(this,$E).resumePausedMutations():Promise.resolve()}getQueryCache(){return ge(this,dg)}getMutationCache(){return ge(this,$E)}getDefaultOptions(){return ge(this,UE)}setDefaultOptions(s){$t(this,UE,s)}setQueryDefaults(s,t){ge(this,n$).set(EO(s),{queryKey:s,defaultOptions:t})}getQueryDefaults(s){const t=[...ge(this,n$).values()],n={};return t.forEach(r=>{mU(s,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(s,t){ge(this,r$).set(EO(s),{mutationKey:s,defaultOptions:t})}getMutationDefaults(s){const t=[...ge(this,r$).values()],n={};return t.forEach(r=>{mU(s,r.mutationKey)&&Object.assign(n,r.defaultOptions)}),n}defaultQueryOptions(s){if(s._defaulted)return s;const t={...ge(this,UE).queries,...this.getQueryDefaults(s.queryKey),...s,_defaulted:!0};return t.queryHash||(t.queryHash=lHe(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===cHe&&(t.enabled=!1),t}defaultMutationOptions(s){return s!=null&&s._defaulted?s:{...ge(this,UE).mutations,...(s==null?void 0:s.mutationKey)&&this.getMutationDefaults(s.mutationKey),...s,_defaulted:!0}}clear(){ge(this,dg).clear(),ge(this,$E).clear()}},dg=new WeakMap,$E=new WeakMap,UE=new WeakMap,n$=new WeakMap,r$=new WeakMap,qE=new WeakMap,a$=new WeakMap,i$=new WeakMap,a2t),T5t=k.createContext(void 0),ls=s=>{const t=k.useContext(T5t);if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},wos=({client:s,children:t})=>(k.useEffect(()=>(s.mount(),()=>{s.unmount()}),[s]),e.jsx(T5t.Provider,{value:s,children:t})),M5t=k.createContext(!1),jos=()=>k.useContext(M5t);M5t.Provider;function Nos(){let s=!1;return{clearReset:()=>{s=!1},reset:()=>{s=!0},isReset:()=>s}}var kos=k.createContext(Nos()),Sos=()=>k.useContext(kos),Cos=(s,t,n)=>{const r=n!=null&&n.state.error&&typeof s.throwOnError=="function"?dHe(s.throwOnError,[n.state.error,n]):s.throwOnError;(s.suspense||s.experimental_prefetchInRender||r)&&(t.isReset()||(s.retryOnMount=!1))},Aos=s=>{k.useEffect(()=>{s.clearReset()},[s])},Eos=({result:s,errorResetBoundary:t,throwOnError:n,query:r,suspense:a})=>s.isError&&!t.isReset()&&!s.isFetching&&r&&(a&&s.data===void 0||dHe(n,[s.error,r])),Tos=s=>{if(s.suspense){const n=a=>a==="static"?a:Math.max(a??1e3,1e3),r=s.staleTime;s.staleTime=typeof r=="function"?(...a)=>n(r(...a)):n(r),typeof s.gcTime=="number"&&(s.gcTime=Math.max(s.gcTime,1e3))}},Mos=(s,t)=>s.isLoading&&s.isFetching&&!t,Pos=(s,t)=>(s==null?void 0:s.suspense)&&t.isPending,yit=(s,t,n)=>t.fetchOptimistic(s).catch(()=>{n.clearReset()});function P5t(s,t,n){var p,g,x,y;const r=jos(),a=Sos(),i=ls(),l=i.defaultQueryOptions(s);(g=(p=i.getDefaultOptions().queries)==null?void 0:p._experimental_beforeQuery)==null||g.call(p,l);const o=i.getQueryCache().get(l.queryHash),c=s.subscribed!==!1;l._optimisticResults=r?"isRestoring":c?"optimistic":void 0,Tos(l),Cos(l,a,o),Aos(a);const d=!i.getQueryCache().get(l.queryHash),[u]=k.useState(()=>new t(i,l)),h=u.getOptimisticResult(l),m=!r&&c;if(k.useSyncExternalStore(k.useCallback(v=>{const _=m?u.subscribe(gy.batchCalls(v)):J1;return u.updateResult(),_},[u,m]),()=>u.getCurrentResult(),()=>u.getCurrentResult()),k.useEffect(()=>{u.setOptions(l)},[l,u]),Pos(l,h))throw yit(l,u,a);if(Eos({result:h,errorResetBoundary:a,throwOnError:l.throwOnError,query:o,suspense:l.suspense}))throw h.error;if((y=(x=i.getDefaultOptions().queries)==null?void 0:x._experimental_afterQuery)==null||y.call(x,l,h),l.experimental_prefetchInRender&&!FZ.isServer()&&Mos(h,r)){const v=d?yit(l,u,a):o==null?void 0:o.promise;v==null||v.catch(J1).finally(()=>{u.updateResult()})}return l.notifyOnChangeProps?h:u.trackResult(h)}function pt(s,t){return P5t(s,C5t)}function Nt(s,t){const n=ls(),[r]=k.useState(()=>new vos(n,s));k.useEffect(()=>{r.setOptions(s)},[r,s]);const a=k.useSyncExternalStore(k.useCallback(l=>r.subscribe(gy.batchCalls(l)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),i=k.useCallback((l,o)=>{r.mutate(l,o).catch(J1)},[r]);if(a.error&&dHe(r.options.throwOnError,[a.error]))throw a.error;return{...a,mutate:i,mutateAsync:a.mutate}}function Ios(s,t){return P5t(s,gos)}/** * @remix-run/router v1.23.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 zZ(){return zZ=Object.assign?Object.assign.bind():function(s){for(var t=1;t"u")throw new Error(t)}function I5t(s,t){if(!s){typeof console<"u"&&console.warn(t);try{throw new Error(t)}catch{}}}function Ros(){return Math.random().toString(36).substr(2,8)}function bit(s,t){return{usr:s.state,key:s.key,idx:t}}function LFe(s,t,n,r){return n===void 0&&(n=null),zZ({pathname:typeof s=="string"?s:s.pathname,search:"",hash:""},typeof t=="string"?Fq(t):t,{state:n,key:t&&t.key||r||Ros()})}function sSe(s){let{pathname:t="/",search:n="",hash:r=""}=s;return n&&n!=="?"&&(t+=n.charAt(0)==="?"?n:"?"+n),r&&r!=="#"&&(t+=r.charAt(0)==="#"?r:"#"+r),t}function Fq(s){let t={};if(s){let n=s.indexOf("#");n>=0&&(t.hash=s.substr(n),s=s.substr(0,n));let r=s.indexOf("?");r>=0&&(t.search=s.substr(r),s=s.substr(0,r)),s&&(t.pathname=s)}return t}function Dos(s,t,n,r){r===void 0&&(r={});let{window:a=document.defaultView,v5Compat:i=!1}=r,l=a.history,o=vT.Pop,c=null,d=u();d==null&&(d=0,l.replaceState(zZ({},l.state,{idx:d}),""));function u(){return(l.state||{idx:null}).idx}function h(){o=vT.Pop;let y=u(),v=y==null?null:y-d;d=y,c&&c({action:o,location:x.location,delta:v})}function m(y,v){o=vT.Push;let _=LFe(x.location,y,v);d=u()+1;let j=bit(_,d),C=x.createHref(_);try{l.pushState(j,"",C)}catch(A){if(A instanceof DOMException&&A.name==="DataCloneError")throw A;a.location.assign(C)}i&&c&&c({action:o,location:x.location,delta:1})}function p(y,v){o=vT.Replace;let _=LFe(x.location,y,v);d=u();let j=bit(_,d),C=x.createHref(_);l.replaceState(j,"",C),i&&c&&c({action:o,location:x.location,delta:0})}function g(y){let v=a.location.origin!=="null"?a.location.origin:a.location.href,_=typeof y=="string"?y:sSe(y);return _=_.replace(/ $/,"%20"),$p(v,"No window.location.(origin|href) available to create URL for href: "+_),new URL(_,v)}let x={get action(){return o},get location(){return s(a,l)},listen(y){if(c)throw new Error("A history only accepts one active listener");return a.addEventListener(vit,h),c=y,()=>{a.removeEventListener(vit,h),c=null}},createHref(y){return t(a,y)},createURL:g,encodeLocation(y){let v=g(y);return{pathname:v.pathname,search:v.search,hash:v.hash}},push:m,replace:p,go(y){return l.go(y)}};return x}var _it;(function(s){s.data="data",s.deferred="deferred",s.redirect="redirect",s.error="error"})(_it||(_it={}));function Oos(s,t,n){return n===void 0&&(n="/"),Fos(s,t,n)}function Fos(s,t,n,r){let a=typeof t=="string"?Fq(t):t,i=fU(a.pathname||"/",n);if(i==null)return null;let l=L5t(s);zos(l);let o=null,c=Zos(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("/")&&($p(c.relativePath.startsWith(r),'Absolute route path "'+c.relativePath+'" nested under path '+('"'+r+'" is not valid. An absolute child route path ')+"must start with the combined path of all its parent routes."),c.relativePath=c.relativePath.slice(r.length));let d=lM([r,c.relativePath]),u=n.concat(c);i.children&&i.children.length>0&&($p(i.index!==!0,"Index routes must not have child routes. Please remove "+('all child routes from route path "'+d+'".')),L5t(i.children,t,u,d)),!(i.path==null&&!i.index)&&t.push({path:d,score:Gos(d,i.index),routesMeta:u})};return s.forEach((i,l)=>{var o;if(i.path===""||!((o=i.path)!=null&&o.includes("?")))a(i,l);else for(let c of R5t(i.path))a(i,l,c)}),t}function R5t(s){let t=s.split("/");if(t.length===0)return[];let[n,...r]=t,a=n.endsWith("?"),i=n.replace(/\?$/,"");if(r.length===0)return a?[i,""]:[i];let l=R5t(r.join("/")),o=[];return o.push(...l.map(c=>c===""?i:[i,c].join("/"))),a&&o.push(...l),o.map(c=>s.startsWith("/")&&c===""?"/":c)}function zos(s){s.sort((t,n)=>t.score!==n.score?n.score-t.score:Wos(t.routesMeta.map(r=>r.childrenIndex),n.routesMeta.map(r=>r.childrenIndex)))}const Bos=/^:[\w-]+$/,$os=3,Uos=2,qos=1,Vos=10,Hos=-2,wit=s=>s==="*";function Gos(s,t){let n=s.split("/"),r=n.length;return n.some(wit)&&(r+=Hos),t&&(r+=Uos),n.filter(a=>!wit(a)).reduce((a,i)=>a+(Bos.test(i)?$os:i===""?qos:Vos),r)}function Wos(s,t){return s.length===t.length&&s.slice(0,-1).every((r,a)=>r===t[a])?s[s.length-1]-t[t.length-1]:0}function Kos(s,t,n){let{routesMeta:r}=s,a={},i="/",l=[];for(let o=0;o{let{paramName:m,isOptional:p}=u;if(m==="*"){let x=o[h]||"";l=i.slice(0,i.length-x.length).replace(/(.)\/+$/,"$1")}const g=o[h];return p&&!g?d[m]=void 0:d[m]=(g||"").replace(/%2F/g,"/"),d},{}),pathname:i,pathnameBase:l,pattern:s}}function Yos(s,t,n){t===void 0&&(t=!1),n===void 0&&(n=!0),I5t(s==="*"||!s.endsWith("*")||s.endsWith("/*"),'Route path "'+s+'" will be treated as if it were '+('"'+s.replace(/\*$/,"/*")+'" because the `*` character must ')+"always follow a `/` in the pattern. To get rid of this warning, "+('please change the route path to "'+s.replace(/\*$/,"/*")+'".'));let r=[],a="^"+s.replace(/\/*\*?$/,"").replace(/^\/*/,"/").replace(/[\\.*+^${}|()[\]]/g,"\\$&").replace(/\/:([\w-]+)(\?)?/g,(l,o,c)=>(r.push({paramName:o,isOptional:c!=null}),c?"/?([^\\/]+)?":"/([^\\/]+)"));return s.endsWith("*")?(r.push({paramName:"*"}),a+=s==="*"||s==="/*"?"(.*)$":"(?:\\/(.+)|\\/*)$"):n?a+="\\/*$":s!==""&&s!=="/"&&(a+="(?:(?=\\/|$))"),[new RegExp(a,t?void 0:"i"),r]}function Zos(s){try{return s.split("/").map(t=>decodeURIComponent(t).replace(/\//g,"%2F")).join("/")}catch(t){return I5t(!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 fU(s,t){if(t==="/")return s;if(!s.toLowerCase().startsWith(t.toLowerCase()))return null;let n=t.endsWith("/")?t.length-1:t.length,r=s.charAt(n);return r&&r!=="/"?null:s.slice(n)||"/"}function Xos(s,t){t===void 0&&(t="/");let{pathname:n,search:r="",hash:a=""}=typeof s=="string"?Fq(s):s,i;return n?(n=D5t(n),n.startsWith("/")?i=jit(n.substring(1),"/"):i=jit(n,t)):i=t,{pathname:i,search:els(r),hash:tls(a)}}function jit(s,t){let n=t.replace(/\/+$/,"").split("/");return s.split("/").forEach(a=>{a===".."?n.length>1&&n.pop():a!=="."&&n.push(a)}),n.length>1?n.join("/"):"/"}function eIe(s,t,n,r){return"Cannot include a '"+s+"' character in a manually specified "+("`to."+t+"` field ["+JSON.stringify(r)+"]. Please separate it out to the ")+("`to."+n+"` field. Alternatively you may provide the full path as ")+'a string in and the router will parse it for you.'}function Qos(s){return s.filter((t,n)=>n===0||t.route.path&&t.route.path.length>0)}function hHe(s,t){let n=Qos(s);return t?n.map((r,a)=>a===n.length-1?r.pathname:r.pathnameBase):n.map(r=>r.pathnameBase)}function mHe(s,t,n,r){r===void 0&&(r=!1);let a;typeof s=="string"?a=Fq(s):(a=zZ({},s),$p(!a.pathname||!a.pathname.includes("?"),eIe("?","pathname","search",a)),$p(!a.pathname||!a.pathname.includes("#"),eIe("#","pathname","hash",a)),$p(!a.search||!a.search.includes("#"),eIe("#","search","hash",a)));let i=s===""||a.pathname==="",l=i?"/":a.pathname,o;if(l==null)o=n;else{let h=t.length-1;if(!r&&l.startsWith("..")){let m=l.split("/");for(;m[0]==="..";)m.shift(),h-=1;a.pathname=m.join("/")}o=h>=0?t[h]:"/"}let c=Xos(a,o),d=l&&l!=="/"&&l.endsWith("/"),u=(i||l===".")&&n.endsWith("/");return!c.pathname.endsWith("/")&&(d||u)&&(c.pathname+="/"),c}const D5t=s=>s.replace(/\/\/+/g,"/"),lM=s=>D5t(s.join("/")),Jos=s=>s.replace(/\/+$/,"").replace(/^\/*/,"/"),els=s=>!s||s==="?"?"":s.startsWith("?")?s:"?"+s,tls=s=>!s||s==="#"?"":s.startsWith("#")?s:"#"+s;function sls(s){return s!=null&&typeof s.status=="number"&&typeof s.statusText=="string"&&typeof s.internal=="boolean"&&"data"in s}const O5t=["post","put","patch","delete"];new Set(O5t);const nls=["get",...O5t];new Set(nls);/** * React Router v6.30.6 * * 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 BZ(){return BZ=Object.assign?Object.assign.bind():function(s){for(var t=1;t{o.current=!0}),k.useCallback(function(d,u){if(u===void 0&&(u={}),!o.current)return;if(typeof d=="number"){r.go(d);return}let h=mHe(d,JSON.parse(l),i,u.relative==="path");s==null&&t!=="/"&&(h.pathname=h.pathname==="/"?t:lM([t,h.pathname])),(u.replace?r.replace:r.push)(h,u.state,u)},[t,r,l,i,s])}const ils=k.createContext(null);function ols(s){let t=k.useContext(J5).outlet;return t&&k.createElement(ils.Provider,{value:s},t)}function oo(){let{matches:s}=k.useContext(J5),t=s[s.length-1];return t?t.params:{}}function v3e(s,t){let{relative:n}=t===void 0?{}:t,{future:r}=k.useContext(nA),{matches:a}=k.useContext(J5),{pathname:i}=Tu(),l=JSON.stringify(hHe(a,r.v7_relativeSplatPath));return k.useMemo(()=>mHe(s,JSON.parse(l),i,n==="path"),[s,l,i,n])}function lls(s,t){return cls(s,t)}function cls(s,t,n,r){zq()||$p(!1);let{navigator:a}=k.useContext(nA),{matches:i}=k.useContext(J5),l=i[i.length-1],o=l?l.params:{};l&&l.pathname;let c=l?l.pathnameBase:"/";l&&l.route;let d=Tu(),u;if(t){var h;let y=typeof t=="string"?Fq(t):t;c==="/"||(h=y.pathname)!=null&&h.startsWith(c)||$p(!1),u=y}else u=d;let m=u.pathname||"/",p=m;if(c!=="/"){let y=c.replace(/^\//,"").split("/");p="/"+m.replace(/^\//,"").split("/").slice(y.length).join("/")}let g=Oos(s,{pathname:p}),x=fls(g&&g.map(y=>Object.assign({},y,{params:Object.assign({},o,y.params),pathname:lM([c,a.encodeLocation?a.encodeLocation(y.pathname).pathname:y.pathname]),pathnameBase:y.pathnameBase==="/"?c:lM([c,a.encodeLocation?a.encodeLocation(y.pathnameBase).pathname:y.pathnameBase])})),i,n,r);return t&&x?k.createElement(y3e.Provider,{value:{location:BZ({pathname:"/",search:"",hash:"",state:null,key:"default"},u),navigationType:vT.Pop}},x):x}function dls(){let s=yls(),t=sls(s)?s.status+" "+s.statusText:s instanceof Error?s.message:JSON.stringify(s),n=s instanceof Error?s.stack:null,a={padding:"0.5rem",backgroundColor:"rgba(200,200,200, 0.5)"};return k.createElement(k.Fragment,null,k.createElement("h2",null,"Unexpected Application Error!"),k.createElement("h3",{style:{fontStyle:"italic"}},t),n?k.createElement("pre",{style:a},n):null,null)}const uls=k.createElement(dls,null);class hls 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,n){return n.location!==t.location||n.revalidation!=="idle"&&t.revalidation==="idle"?{error:t.error,location:t.location,revalidation:t.revalidation}:{error:t.error!==void 0?t.error:n.error,location:n.location,revalidation:t.revalidation||n.revalidation}}componentDidCatch(t,n){console.error("React Router caught the following error during render",t,n)}render(){return this.state.error!==void 0?k.createElement(J5.Provider,{value:this.props.routeContext},k.createElement(z5t.Provider,{value:this.state.error,children:this.props.component})):this.props.children}}function mls(s){let{routeContext:t,match:n,children:r}=s,a=k.useContext(x3e);return a&&a.static&&a.staticContext&&(n.route.errorElement||n.route.ErrorBoundary)&&(a.staticContext._deepestRenderedBoundaryId=n.route.id),k.createElement(J5.Provider,{value:t},r)}function fls(s,t,n,r){var a;if(t===void 0&&(t=[]),n===void 0&&(n=null),r===void 0&&(r=null),s==null){var i;if(!n)return null;if(n.errors)s=n.matches;else if((i=r)!=null&&i.v7_partialHydration&&t.length===0&&!n.initialized&&n.matches.length>0)s=n.matches;else return null}let l=s,o=(a=n)==null?void 0:a.errors;if(o!=null){let u=l.findIndex(h=>h.route.id&&(o==null?void 0:o[h.route.id])!==void 0);u>=0||$p(!1),l=l.slice(0,Math.min(l.length,u+1))}let c=!1,d=-1;if(n&&r&&r.v7_partialHydration)for(let u=0;u=0?l=l.slice(0,d+1):l=[l[0]];break}}}return l.reduceRight((u,h,m)=>{let p,g=!1,x=null,y=null;n&&(p=o&&h.route.id?o[h.route.id]:void 0,x=h.route.errorElement||uls,c&&(d<0&&m===0?(bls("route-fallback"),g=!0,y=null):d===m&&(g=!0,y=h.route.hydrateFallbackElement||null)));let v=t.concat(l.slice(0,m+1)),_=()=>{let j;return p?j=x:g?j=y:h.route.Component?j=k.createElement(h.route.Component,null):h.route.element?j=h.route.element:j=u,k.createElement(mls,{match:h,routeContext:{outlet:u,matches:v,isDataRoute:n!=null},children:j})};return n&&(h.route.ErrorBoundary||h.route.errorElement||m===0)?k.createElement(hls,{location:n.location,revalidation:n.revalidation,component:x,error:p,children:_(),routeContext:{outlet:null,matches:v,isDataRoute:!0}}):_()},null)}var $5t=function(s){return s.UseBlocker="useBlocker",s.UseRevalidator="useRevalidator",s.UseNavigateStable="useNavigate",s}($5t||{}),U5t=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}(U5t||{});function pls(s){let t=k.useContext(x3e);return t||$p(!1),t}function gls(s){let t=k.useContext(F5t);return t||$p(!1),t}function xls(s){let t=k.useContext(J5);return t||$p(!1),t}function q5t(s){let t=xls(),n=t.matches[t.matches.length-1];return n.route.id||$p(!1),n.route.id}function yls(){var s;let t=k.useContext(z5t),n=gls(),r=q5t();return t!==void 0?t:(s=n.errors)==null?void 0:s[r]}function vls(){let{router:s}=pls($5t.UseNavigateStable),t=q5t(U5t.UseNavigateStable),n=k.useRef(!1);return B5t(()=>{n.current=!0}),k.useCallback(function(a,i){i===void 0&&(i={}),n.current&&(typeof a=="number"?s.navigate(a):s.navigate(a,BZ({fromRouteId:t},i)))},[s,t])}const Nit={};function bls(s,t,n){Nit[s]||(Nit[s]=!0)}function _ls(s,t){s==null||s.v7_startTransition,s==null||s.v7_relativeSplatPath}function ab(s){let{to:t,replace:n,state:r,relative:a}=s;zq()||$p(!1);let{future:i,static:l}=k.useContext(nA),{matches:o}=k.useContext(J5),{pathname:c}=Tu(),d=Jn(),u=mHe(t,hHe(o,i.v7_relativeSplatPath),c,a==="path"),h=JSON.stringify(u);return k.useEffect(()=>d(JSON.parse(h),{replace:n,state:r,relative:a}),[d,h,a,n,r]),null}function V5t(s){return ols(s.context)}function fs(s){$p(!1)}function wls(s){let{basename:t="/",children:n=null,location:r,navigationType:a=vT.Pop,navigator:i,static:l=!1,future:o}=s;zq()&&$p(!1);let c=t.replace(/^\/*/,"/"),d=k.useMemo(()=>({basename:c,navigator:i,static:l,future:BZ({v7_relativeSplatPath:!1},o)}),[c,o,i,l]);typeof r=="string"&&(r=Fq(r));let{pathname:u="/",search:h="",hash:m="",state:p=null,key:g="default"}=r,x=k.useMemo(()=>{let y=fU(u,c);return y==null?null:{location:{pathname:y,search:h,hash:m,state:p,key:g},navigationType:a}},[c,u,h,m,p,g,a]);return x==null?null:k.createElement(nA.Provider,{value:d},k.createElement(y3e.Provider,{children:n,value:x}))}function $Z(s){let{children:t,location:n}=s;return lls(DFe(t),n)}new Promise(()=>{});function DFe(s,t){t===void 0&&(t=[]);let n=[];return k.Children.forEach(s,(r,a)=>{if(!k.isValidElement(r))return;let i=[...t,a];if(r.type===k.Fragment){n.push.apply(n,DFe(r.props.children,i));return}r.type!==fs&&$p(!1),!r.props.index||!r.props.children||$p(!1);let l={id:r.props.id||i.join("-"),caseSensitive:r.props.caseSensitive,element:r.props.element,Component:r.props.Component,index:r.props.index,path:r.props.path,loader:r.props.loader,action:r.props.action,errorElement:r.props.errorElement,ErrorBoundary:r.props.ErrorBoundary,hasErrorBoundary:r.props.ErrorBoundary!=null||r.props.errorElement!=null,shouldRevalidate:r.props.shouldRevalidate,handle:r.props.handle,lazy:r.props.lazy};r.props.children&&(l.children=DFe(r.props.children,i)),n.push(l)}),n}/** * React Router DOM v6.30.6 * * 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 nSe(){return nSe=Object.assign?Object.assign.bind():function(s){for(var t=1;t{let r=s[n];return t.concat(Array.isArray(r)?r.map(a=>[n,a]):[[n,r]])},[]))}function kls(s,t){let n=OFe(s);return t&&t.forEach((r,a)=>{n.has(a)||t.getAll(a).forEach(i=>{n.append(a,i)})}),n}const Sls=["onClick","relative","reloadDocument","replace","state","target","to","preventScrollReset","viewTransition"],Cls=["aria-current","caseSensitive","className","end","style","to","viewTransition","children"],Als="6";try{window.__reactRouterVersion=Als}catch{}const Els=k.createContext({isTransitioning:!1}),Tls="startTransition",kit=uF[Tls];function Mls(s){let{basename:t,children:n,future:r,window:a}=s,i=k.useRef();i.current==null&&(i.current=Los({window:a,v5Compat:!0}));let l=i.current,[o,c]=k.useState({action:l.action,location:l.location}),{v7_startTransition:d}=r||{},u=k.useCallback(h=>{d&&kit?kit(()=>c(h)):c(h)},[c,d]);return k.useLayoutEffect(()=>l.listen(u),[l,u]),k.useEffect(()=>_ls(r),[r]),k.createElement(wls,{basename:t,children:n,location:o.location,navigationType:o.action,navigator:l,future:r})}const Pls=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",Ils=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,nr=k.forwardRef(function(t,n){let{onClick:r,relative:a,reloadDocument:i,replace:l,state:o,target:c,to:d,preventScrollReset:u,viewTransition:h}=t,m=H5t(t,Sls),{basename:p}=k.useContext(nA),g,x=!1;if(typeof d=="string"&&Ils.test(d)&&(g=d,Pls))try{let j=new URL(window.location.href),C=d.startsWith("//")?new URL(j.protocol+d):new URL(d),A=fU(C.pathname,p);C.origin===j.origin&&A!=null?d=A+C.search+C.hash:x=!0}catch{}let y=rls(d,{relative:a}),v=Rls(d,{replace:l,state:o,target:c,preventScrollReset:u,relative:a,viewTransition:h});function _(j){r&&r(j),j.defaultPrevented||v(j)}return k.createElement("a",nSe({},m,{href:g||y,onClick:x||i?r:_,ref:n,target:c}))}),JA=k.forwardRef(function(t,n){let{"aria-current":r="page",caseSensitive:a=!1,className:i="",end:l=!1,style:o,to:c,viewTransition:d,children:u}=t,h=H5t(t,Cls),m=v3e(c,{relative:h.relative}),p=Tu(),g=k.useContext(F5t),{navigator:x,basename:y}=k.useContext(nA),v=g!=null&&Dls(m)&&d===!0,_=x.encodeLocation?x.encodeLocation(m).pathname:m.pathname,j=p.pathname,C=g&&g.navigation&&g.navigation.location?g.navigation.location.pathname:null;a||(j=j.toLowerCase(),C=C?C.toLowerCase():null,_=_.toLowerCase()),C&&y&&(C=fU(C,y)||C);const A=_!=="/"&&_.endsWith("/")?_.length-1:_.length;let M=j===_||!l&&j.startsWith(_)&&j.charAt(A)==="/",I=C!=null&&(C===_||!l&&C.startsWith(_)&&C.charAt(_.length)==="/"),P={isActive:M,isPending:I,isTransitioning:v},R=M?r:void 0,O;typeof i=="function"?O=i(P):O=[i,M?"active":null,I?"pending":null,v?"transitioning":null].filter(Boolean).join(" ");let B=typeof o=="function"?o(P):o;return k.createElement(nr,nSe({},h,{"aria-current":R,className:O,ref:n,style:B,to:c,viewTransition:d}),typeof u=="function"?u(P):u)});var FFe;(function(s){s.UseScrollRestoration="useScrollRestoration",s.UseSubmit="useSubmit",s.UseSubmitFetcher="useSubmitFetcher",s.UseFetcher="useFetcher",s.useViewTransitionState="useViewTransitionState"})(FFe||(FFe={}));var Sit;(function(s){s.UseFetcher="useFetcher",s.UseFetchers="useFetchers",s.UseScrollRestoration="useScrollRestoration"})(Sit||(Sit={}));function Lls(s){let t=k.useContext(x3e);return t||$p(!1),t}function Rls(s,t){let{target:n,replace:r,state:a,preventScrollReset:i,relative:l,viewTransition:o}=t===void 0?{}:t,c=Jn(),d=Tu(),u=v3e(s,{relative:l});return k.useCallback(h=>{if(Nls(h,n)){h.preventDefault();let m=r!==void 0?r:sSe(d)===sSe(u);c(s,{replace:m,state:a,preventScrollReset:i,relative:l,viewTransition:o})}},[d,c,u,r,a,n,s,i,l,o])}function Jc(s){let t=k.useRef(OFe(s)),n=k.useRef(!1),r=Tu(),a=k.useMemo(()=>kls(r.search,n.current?null:t.current),[r.search]),i=Jn(),l=k.useCallback((o,c)=>{const d=OFe(typeof o=="function"?o(a):o);n.current=!0,i("?"+d,c)},[i,a]);return[a,l]}function Dls(s,t){t===void 0&&(t={});let n=k.useContext(Els);n==null&&$p(!1);let{basename:r}=Lls(FFe.useViewTransitionState),a=v3e(s,{relative:t.relative});if(!n.isTransitioning)return!1;let i=fU(n.currentLocation.pathname,r)||n.currentLocation.pathname,l=fU(n.nextLocation.pathname,r)||n.nextLocation.pathname;return RFe(a.pathname,l)!=null||RFe(a.pathname,i)!=null}var Ols=typeof Element<"u",Fls=typeof Map=="function",zls=typeof Set=="function",Bls=typeof ArrayBuffer=="function"&&!!ArrayBuffer.isView;function X2e(s,t){if(s===t)return!0;if(s&&t&&typeof s=="object"&&typeof t=="object"){if(s.constructor!==t.constructor)return!1;var n,r,a;if(Array.isArray(s)){if(n=s.length,n!=t.length)return!1;for(r=n;r--!==0;)if(!X2e(s[r],t[r]))return!1;return!0}var i;if(Fls&&s instanceof Map&&t instanceof Map){if(s.size!==t.size)return!1;for(i=s.entries();!(r=i.next()).done;)if(!t.has(r.value[0]))return!1;for(i=s.entries();!(r=i.next()).done;)if(!X2e(r.value[1],t.get(r.value[0])))return!1;return!0}if(zls&&s instanceof Set&&t instanceof Set){if(s.size!==t.size)return!1;for(i=s.entries();!(r=i.next()).done;)if(!t.has(r.value[0]))return!1;return!0}if(Bls&&ArrayBuffer.isView(s)&&ArrayBuffer.isView(t)){if(n=s.length,n!=t.length)return!1;for(r=n;r--!==0;)if(s[r]!==t[r])return!1;return!0}if(s.constructor===RegExp)return s.source===t.source&&s.flags===t.flags;if(s.valueOf!==Object.prototype.valueOf&&typeof s.valueOf=="function"&&typeof t.valueOf=="function")return s.valueOf()===t.valueOf();if(s.toString!==Object.prototype.toString&&typeof s.toString=="function"&&typeof t.toString=="function")return s.toString()===t.toString();if(a=Object.keys(s),n=a.length,n!==Object.keys(t).length)return!1;for(r=n;r--!==0;)if(!Object.prototype.hasOwnProperty.call(t,a[r]))return!1;if(Ols&&s instanceof Element)return!1;for(r=n;r--!==0;)if(!((a[r]==="_owner"||a[r]==="__v"||a[r]==="__o")&&s.$$typeof)&&!X2e(s[a[r]],t[a[r]]))return!1;return!0}return s!==s&&t!==t}var $ls=function(t,n){try{return X2e(t,n)}catch(r){if((r.message||"").match(/stack|recursion/i))return console.warn("react-fast-compare cannot handle circular refs"),!1;throw r}};const Uls=kd($ls);var qls=function(s,t,n,r,a,i,l,o){if(!s){var c;if(t===void 0)c=new Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var d=[n,r,a,i,l,o],u=0;c=new Error(t.replace(/%s/g,function(){return d[u++]})),c.name="Invariant Violation"}throw c.framesToPop=1,c}},Vls=qls;const Cit=kd(Vls);var Hls=function(t,n,r,a){var i=r?r.call(a,t,n):void 0;if(i!==void 0)return!!i;if(t===n)return!0;if(typeof t!="object"||!t||typeof n!="object"||!n)return!1;var l=Object.keys(t),o=Object.keys(n);if(l.length!==o.length)return!1;for(var c=Object.prototype.hasOwnProperty.bind(n),d=0;d(s.BASE="base",s.BODY="body",s.HEAD="head",s.HTML="html",s.LINK="link",s.META="meta",s.NOSCRIPT="noscript",s.SCRIPT="script",s.STYLE="style",s.TITLE="title",s.FRAGMENT="Symbol(react.fragment)",s))(G5t||{}),tIe={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"]}},Ait=Object.values(G5t),fHe={accesskey:"accessKey",charset:"charSet",class:"className",contenteditable:"contentEditable",contextmenu:"contextMenu","http-equiv":"httpEquiv",itemprop:"itemProp",tabindex:"tabIndex"},Wls=Object.entries(fHe).reduce((s,[t,n])=>(s[n]=t,s),{}),JN="data-rh",wB={DEFAULT_TITLE:"defaultTitle",DEFER:"defer",ENCODE_SPECIAL_CHARACTERS:"encodeSpecialCharacters",ON_CHANGE_CLIENT_STATE:"onChangeClientState",TITLE_TEMPLATE:"titleTemplate",PRIORITIZE_SEO_TAGS:"prioritizeSeoTags"},jB=(s,t)=>{for(let n=s.length-1;n>=0;n-=1){const r=s[n];if(Object.prototype.hasOwnProperty.call(r,t))return r[t]}return null},Kls=s=>{let t=jB(s,"title");const n=jB(s,wB.TITLE_TEMPLATE);if(Array.isArray(t)&&(t=t.join("")),n&&t)return n.replace(/%s/g,()=>t);const r=jB(s,wB.DEFAULT_TITLE);return t||r||void 0},Yls=s=>jB(s,wB.ON_CHANGE_CLIENT_STATE)||(()=>{}),sIe=(s,t)=>t.filter(n=>typeof n[s]<"u").map(n=>n[s]).reduce((n,r)=>({...n,...r}),{}),Zls=(s,t)=>t.filter(n=>typeof n.base<"u").map(n=>n.base).reverse().reduce((n,r)=>{if(!n.length){const a=Object.keys(r);for(let i=0;iconsole&&typeof console.warn=="function"&&console.warn(s),eG=(s,t,n)=>{const r={};return n.filter(a=>Array.isArray(a[s])?!0:(typeof a[s]<"u"&&Xls(`Helmet: ${s} should be of type "Array". Instead found type "${typeof a[s]}"`),!1)).map(a=>a[s]).reverse().reduce((a,i)=>{const l={};i.filter(c=>{let d;const u=Object.keys(c);for(let m=0;ma.push(c));const o=Object.keys(l);for(let c=0;c{if(Array.isArray(s)&&s.length){for(let n=0;n({baseTag:Zls(["href"],s),bodyAttributes:sIe("bodyAttributes",s),defer:jB(s,wB.DEFER),encode:jB(s,wB.ENCODE_SPECIAL_CHARACTERS),htmlAttributes:sIe("htmlAttributes",s),linkTags:eG("link",["rel","href"],s),metaTags:eG("meta",["name","charset","http-equiv","property","itemprop"],s),noscriptTags:eG("noscript",["innerHTML"],s),onChangeClientState:Yls(s),scriptTags:eG("script",["src","innerHTML"],s),styleTags:eG("style",["cssText"],s),title:Kls(s),titleAttributes:sIe("titleAttributes",s),prioritizeSeoTags:Qls(s,wB.PRIORITIZE_SEO_TAGS)}),W5t=s=>Array.isArray(s)?s.join(""):s,ecs=(s,t)=>{const n=Object.keys(s);for(let r=0;rArray.isArray(s)?s.reduce((n,r)=>(ecs(r,t)?n.priority.push(r):n.default.push(r),n),{priority:[],default:[]}):{default:s,priority:[]},Eit=(s,t)=>({...s,[t]:void 0}),tcs=["noscript","script","style"],zFe=(s,t=!0)=>t===!1?String(s):String(s).replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'"),K5t=s=>Object.keys(s).reduce((t,n)=>{const r=typeof s[n]<"u"?`${n}="${s[n]}"`:`${n}`;return t?`${t} ${r}`:r},""),scs=(s,t,n,r)=>{const a=K5t(n),i=W5t(t);return a?`<${s} ${JN}="true" ${a}>${zFe(i,r)}`:`<${s} ${JN}="true">${zFe(i,r)}`},ncs=(s,t,n=!0)=>t.reduce((r,a)=>{const i=a,l=Object.keys(i).filter(d=>!(d==="innerHTML"||d==="cssText")).reduce((d,u)=>{const h=typeof i[u]>"u"?u:`${u}="${zFe(i[u],n)}"`;return d?`${d} ${h}`:h},""),o=i.innerHTML||i.cssText||"",c=tcs.indexOf(s)===-1;return`${r}<${s} ${JN}="true" ${l}${c?"/>":`>${o}`}`},""),Y5t=(s,t={})=>Object.keys(s).reduce((n,r)=>{const a=fHe[r];return n[a||r]=s[r],n},t),rcs=(s,t,n)=>{const r={key:t,[JN]:!0},a=Y5t(n,r);return[zt.createElement("title",a,t)]},Q2e=(s,t)=>t.map((n,r)=>{const a={key:r,[JN]:!0};return Object.keys(n).forEach(i=>{const o=fHe[i]||i;if(o==="innerHTML"||o==="cssText"){const c=n.innerHTML||n.cssText;a.dangerouslySetInnerHTML={__html:c}}else a[o]=n[i]}),zt.createElement(s,a)}),Hj=(s,t,n=!0)=>{switch(s){case"title":return{toComponent:()=>rcs(s,t.title,t.titleAttributes),toString:()=>scs(s,t.title,t.titleAttributes,n)};case"bodyAttributes":case"htmlAttributes":return{toComponent:()=>Y5t(t),toString:()=>K5t(t)};default:return{toComponent:()=>Q2e(s,t),toString:()=>ncs(s,t,n)}}},acs=({metaTags:s,linkTags:t,scriptTags:n,encode:r})=>{const a=nIe(s,tIe.meta),i=nIe(t,tIe.link),l=nIe(n,tIe.script);return{priorityMethods:{toComponent:()=>[...Q2e("meta",a.priority),...Q2e("link",i.priority),...Q2e("script",l.priority)],toString:()=>`${Hj("meta",a.priority,r)} ${Hj("link",i.priority,r)} ${Hj("script",l.priority,r)}`},metaTags:a.default,linkTags:i.default,scriptTags:l.default}},ics=s=>{const{baseTag:t,bodyAttributes:n,encode:r=!0,htmlAttributes:a,noscriptTags:i,styleTags:l,title:o="",titleAttributes:c,prioritizeSeoTags:d}=s;let{linkTags:u,metaTags:h,scriptTags:m}=s,p={toComponent:()=>{},toString:()=>""};return d&&({priorityMethods:p,linkTags:u,metaTags:h,scriptTags:m}=acs(s)),{priority:p,base:Hj("base",t,r),bodyAttributes:Hj("bodyAttributes",n,r),htmlAttributes:Hj("htmlAttributes",a,r),link:Hj("link",u,r),meta:Hj("meta",h,r),noscript:Hj("noscript",i,r),script:Hj("script",m,r),style:Hj("style",l,r),title:Hj("title",{title:o,titleAttributes:c},r)}},BFe=ics,$ne=[],Z5t=!!(typeof window<"u"&&window.document&&window.document.createElement),$Fe=class{constructor(s,t){ur(this,"instances",[]);ur(this,"canUseDOM",Z5t);ur(this,"context");ur(this,"value",{setHelmet:s=>{this.context.helmet=s},helmetInstances:{get:()=>this.canUseDOM?$ne:this.instances,add:s=>{(this.canUseDOM?$ne:this.instances).push(s)},remove:s=>{const t=(this.canUseDOM?$ne:this.instances).indexOf(s);(this.canUseDOM?$ne:this.instances).splice(t,1)}}});this.context=s,this.canUseDOM=t||!1,t||(s.helmet=BFe({baseTag:[],bodyAttributes:{},htmlAttributes:{},linkTags:[],metaTags:[],noscriptTags:[],scriptTags:[],styleTags:[],title:"",titleAttributes:{}}))}},ocs={},X5t=zt.createContext(ocs),MD,Q5t=(MD=class extends k.Component{constructor(n){super(n);ur(this,"helmetData");this.helmetData=new $Fe(this.props.context||{},MD.canUseDOM)}render(){return zt.createElement(X5t.Provider,{value:this.helmetData.value},this.props.children)}},ur(MD,"canUseDOM",Z5t),MD),O7=(s,t)=>{const n=document.head||document.querySelector("head"),r=n.querySelectorAll(`${s}[${JN}]`),a=[].slice.call(r),i=[];let l;return t&&t.length&&t.forEach(o=>{const c=document.createElement(s);for(const d in o)if(Object.prototype.hasOwnProperty.call(o,d))if(d==="innerHTML")c.innerHTML=o.innerHTML;else if(d==="cssText")c.styleSheet?c.styleSheet.cssText=o.cssText:c.appendChild(document.createTextNode(o.cssText));else{const u=d,h=typeof o[u]>"u"?"":o[u];c.setAttribute(d,h)}c.setAttribute(JN,"true"),a.some((d,u)=>(l=u,c.isEqualNode(d)))?a.splice(l,1):i.push(c)}),a.forEach(o=>{var c;return(c=o.parentNode)==null?void 0:c.removeChild(o)}),i.forEach(o=>n.appendChild(o)),{oldTags:a,newTags:i}},UFe=(s,t)=>{const n=document.getElementsByTagName(s)[0];if(!n)return;const r=n.getAttribute(JN),a=r?r.split(","):[],i=[...a],l=Object.keys(t);for(const o of l){const c=t[o]||"";n.getAttribute(o)!==c&&n.setAttribute(o,c),a.indexOf(o)===-1&&a.push(o);const d=i.indexOf(o);d!==-1&&i.splice(d,1)}for(let o=i.length-1;o>=0;o-=1)n.removeAttribute(i[o]);a.length===i.length?n.removeAttribute(JN):n.getAttribute(JN)!==l.join(",")&&n.setAttribute(JN,l.join(","))},lcs=(s,t)=>{typeof s<"u"&&document.title!==s&&(document.title=W5t(s)),UFe("title",t)},Tit=(s,t)=>{const{baseTag:n,bodyAttributes:r,htmlAttributes:a,linkTags:i,metaTags:l,noscriptTags:o,onChangeClientState:c,scriptTags:d,styleTags:u,title:h,titleAttributes:m}=s;UFe("body",r),UFe("html",a),lcs(h,m);const p={baseTag:O7("base",n),linkTags:O7("link",i),metaTags:O7("meta",l),noscriptTags:O7("noscript",o),scriptTags:O7("script",d),styleTags:O7("style",u)},g={},x={};Object.keys(p).forEach(y=>{const{newTags:v,oldTags:_}=p[y];v.length&&(g[y]=v),_.length&&(x[y]=p[y].oldTags)}),t&&t(),c(s,g,x)},tG=null,ccs=s=>{tG&&cancelAnimationFrame(tG),s.defer?tG=requestAnimationFrame(()=>{Tit(s,()=>{tG=null})}):(Tit(s),tG=null)},dcs=ccs,Mit=class extends k.Component{constructor(){super(...arguments);ur(this,"rendered",!1)}shouldComponentUpdate(t){return!Gls(t,this.props)}componentDidUpdate(){this.emitChange()}componentWillUnmount(){const{helmetInstances:t}=this.props.context;t.remove(this),this.emitChange()}emitChange(){const{helmetInstances:t,setHelmet:n}=this.props.context;let r=null;const a=Jls(t.get().map(i=>{const l={...i.props};return delete l.context,l}));Q5t.canUseDOM?dcs(a):BFe&&(r=BFe(a)),n(r)}init(){if(this.rendered)return;this.rendered=!0;const{helmetInstances:t}=this.props.context;t.add(this),this.emitChange()}render(){return this.init(),null}},iOe,Sc=(iOe=class extends k.Component{shouldComponentUpdate(s){return!Uls(Eit(this.props,"helmetData"),Eit(s,"helmetData"))}mapNestedChildrenToProps(s,t){if(!t)return null;switch(s.type){case"script":case"noscript":return{innerHTML:t};case"style":return{cssText:t};default:throw new Error(`<${s.type} /> elements are self-closing and can not contain children. Refer to our API for more information.`)}}flattenArrayTypeChildren(s,t,n,r){return{...t,[s.type]:[...t[s.type]||[],{...n,...this.mapNestedChildrenToProps(s,r)}]}}mapObjectTypeChildren(s,t,n,r){switch(s.type){case"title":return{...t,[s.type]:r,titleAttributes:{...n}};case"body":return{...t,bodyAttributes:{...n}};case"html":return{...t,htmlAttributes:{...n}};default:return{...t,[s.type]:{...n}}}}mapArrayTypeChildrenToProps(s,t){let n={...t};return Object.keys(s).forEach(r=>{n={...n,[r]:s[r]}}),n}warnOnInvalidChildren(s,t){return Cit(Ait.some(n=>s.type===n),typeof s.type=="function"?"You may be attempting to nest components within each other, which is not allowed. Refer to our API for more information.":`Only elements types ${Ait.join(", ")} are allowed. Helmet does not support rendering <${s.type}> elements. Refer to our API for more information.`),Cit(!t||typeof t=="string"||Array.isArray(t)&&!t.some(n=>typeof n!="string"),`Helmet expects a string as a child of <${s.type}>. Did you forget to wrap your children in braces? ( <${s.type}>{\`\`} ) Refer to our API for more information.`),!0}mapChildrenToProps(s,t){let n={};return zt.Children.forEach(s,r=>{if(!r||!r.props)return;const{children:a,...i}=r.props,l=Object.keys(i).reduce((c,d)=>(c[Wls[d]||d]=i[d],c),{});let{type:o}=r;switch(typeof o=="symbol"?o=o.toString():this.warnOnInvalidChildren(r,a),o){case"Symbol(react.fragment)":t=this.mapChildrenToProps(a,t);break;case"link":case"meta":case"noscript":case"script":case"style":n=this.flattenArrayTypeChildren(r,n,l,a);break;default:t=this.mapObjectTypeChildren(r,t,l,a);break}}),this.mapArrayTypeChildrenToProps(n,t)}render(){const{children:s,...t}=this.props;let n={...t},{helmetData:r}=t;if(s&&(n=this.mapChildrenToProps(s,n)),r&&!(r instanceof $Fe)){const a=r;r=new $Fe(a.context,!0),delete n.helmetData}return r?zt.createElement(Mit,{...n,context:r.value}):zt.createElement(X5t.Consumer,null,a=>zt.createElement(Mit,{...n,context:a}))}},ur(iOe,"defaultProps",{defer:!0,encodeSpecialCharacters:!0,prioritizeSeoTags:!1}),iOe);const ucs=s=>{let t;return s?t=s:typeof fetch>"u"?t=(...n)=>Ai(async()=>{const{default:r}=await Promise.resolve().then(()=>Bq);return{default:r}},void 0).then(({default:r})=>r(...n)):t=fetch,(...n)=>t(...n)};class pHe extends Error{constructor(t,n="FunctionsError",r){super(t),this.name=n,this.context=r}}class hcs extends pHe{constructor(t){super("Failed to send a request to the Edge Function","FunctionsFetchError",t)}}class mcs extends pHe{constructor(t){super("Relay Error invoking the Edge Function","FunctionsRelayError",t)}}class J5t extends pHe{constructor(t){super("Edge Function returned a non-2xx status code","FunctionsHttpError",t)}}var qFe;(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"})(qFe||(qFe={}));var fcs=function(s,t,n,r){function a(i){return i instanceof n?i:new n(function(l){l(i)})}return new(n||(n=Promise))(function(i,l){function o(u){try{d(r.next(u))}catch(h){l(h)}}function c(u){try{d(r.throw(u))}catch(h){l(h)}}function d(u){u.done?i(u.value):a(u.value).then(o,c)}d((r=r.apply(s,t||[])).next())})};class pcs{constructor(t,{headers:n={},customFetch:r,region:a=qFe.Any}={}){this.url=t,this.headers=n,this.region=a,this.fetch=ucs(r)}setAuth(t){this.headers.Authorization=`Bearer ${t}`}invoke(t,n={}){var r;return fcs(this,void 0,void 0,function*(){try{const{headers:a,method:i,body:l}=n;let o={},{region:c}=n;c||(c=this.region),c&&c!=="any"&&(o["x-region"]=c);let d;l&&(a&&!Object.prototype.hasOwnProperty.call(a,"Content-Type")||!a)&&(typeof Blob<"u"&&l instanceof Blob||l instanceof ArrayBuffer?(o["Content-Type"]="application/octet-stream",d=l):typeof l=="string"?(o["Content-Type"]="text/plain",d=l):typeof FormData<"u"&&l instanceof FormData?d=l:(o["Content-Type"]="application/json",d=JSON.stringify(l)));const u=yield this.fetch(`${this.url}/${t}`,{method:i||"POST",headers:Object.assign(Object.assign(Object.assign({},o),this.headers),a),body:d}).catch(g=>{throw new hcs(g)}),h=u.headers.get("x-relay-error");if(h&&h==="true")throw new mcs(u);if(!u.ok)throw new J5t(u);let m=((r=u.headers.get("Content-Type"))!==null&&r!==void 0?r:"text/plain").split(";")[0].trim(),p;return m==="application/json"?p=yield u.json():m==="application/octet-stream"?p=yield u.blob():m==="text/event-stream"?p=u:m==="multipart/form-data"?p=yield u.formData():p=yield u.text(),{data:p,error:null}}catch(a){return{data:null,error:a}}})}}var d_={},gHe={},b3e={},oee={},_3e={},w3e={},gcs=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")},pU=gcs();const xcs=pU.fetch,e4t=pU.fetch.bind(pU),t4t=pU.Headers,ycs=pU.Request,vcs=pU.Response,Bq=Object.freeze(Object.defineProperty({__proto__:null,Headers:t4t,Request:ycs,Response:vcs,default:e4t,fetch:xcs},Symbol.toStringTag,{value:"Module"})),bcs=KQt(Bq);var j3e={};Object.defineProperty(j3e,"__esModule",{value:!0});let _cs=class extends Error{constructor(t){super(t.message),this.name="PostgrestError",this.details=t.details,this.hint=t.hint,this.code=t.code}};j3e.default=_cs;var s4t=jf&&jf.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(w3e,"__esModule",{value:!0});const wcs=s4t(bcs),jcs=s4t(j3e);let Ncs=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=wcs.default:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(t,n){return this.headers=Object.assign({},this.headers),this.headers[t]=n,this}then(t,n){this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers["Accept-Profile"]=this.schema:this.headers["Content-Profile"]=this.schema),this.method!=="GET"&&this.method!=="HEAD"&&(this.headers["Content-Type"]="application/json");const r=this.fetch;let a=r(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async i=>{var l,o,c;let d=null,u=null,h=null,m=i.status,p=i.statusText;if(i.ok){if(this.method!=="HEAD"){const v=await i.text();v===""||(this.headers.Accept==="text/csv"||this.headers.Accept&&this.headers.Accept.includes("application/vnd.pgrst.plan+text")?u=v:u=JSON.parse(v))}const x=(l=this.headers.Prefer)===null||l===void 0?void 0:l.match(/count=(exact|planned|estimated)/),y=(o=i.headers.get("content-range"))===null||o===void 0?void 0:o.split("/");x&&y&&y.length>1&&(h=parseInt(y[1])),this.isMaybeSingle&&this.method==="GET"&&Array.isArray(u)&&(u.length>1?(d={code:"PGRST116",details:`Results contain ${u.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},u=null,h=null,m=406,p="Not Acceptable"):u.length===1?u=u[0]:u=null)}else{const x=await i.text();try{d=JSON.parse(x),Array.isArray(d)&&i.status===404&&(u=[],d=null,m=200,p="OK")}catch{i.status===404&&x===""?(m=204,p="No Content"):d={message:x}}if(d&&this.isMaybeSingle&&(!((c=d==null?void 0:d.details)===null||c===void 0)&&c.includes("0 rows"))&&(d=null,m=200,p="OK"),d&&this.shouldThrowOnError)throw new jcs.default(d)}return{error:d,data:u,count:h,status:m,statusText:p}});return this.shouldThrowOnError||(a=a.catch(i=>{var l,o,c;return{error:{message:`${(l=i==null?void 0:i.name)!==null&&l!==void 0?l:"FetchError"}: ${i==null?void 0:i.message}`,details:`${(o=i==null?void 0:i.stack)!==null&&o!==void 0?o:""}`,hint:"",code:`${(c=i==null?void 0:i.code)!==null&&c!==void 0?c:""}`},data:null,count:null,status:0,statusText:""}})),a.then(t,n)}returns(){return this}overrideTypes(){return this}};w3e.default=Ncs;var kcs=jf&&jf.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(_3e,"__esModule",{value:!0});const Scs=kcs(w3e);let Ccs=class extends Scs.default{select(t){let n=!1;const r=(t??"*").split("").map(a=>/\s/.test(a)&&!n?"":(a==='"'&&(n=!n),a)).join("");return this.url.searchParams.set("select",r),this.headers.Prefer&&(this.headers.Prefer+=","),this.headers.Prefer+="return=representation",this}order(t,{ascending:n=!0,nullsFirst:r,foreignTable:a,referencedTable:i=a}={}){const l=i?`${i}.order`:"order",o=this.url.searchParams.get(l);return this.url.searchParams.set(l,`${o?`${o},`:""}${t}.${n?"asc":"desc"}${r===void 0?"":r?".nullsfirst":".nullslast"}`),this}limit(t,{foreignTable:n,referencedTable:r=n}={}){const a=typeof r>"u"?"limit":`${r}.limit`;return this.url.searchParams.set(a,`${t}`),this}range(t,n,{foreignTable:r,referencedTable:a=r}={}){const i=typeof a>"u"?"offset":`${a}.offset`,l=typeof a>"u"?"limit":`${a}.limit`;return this.url.searchParams.set(i,`${t}`),this.url.searchParams.set(l,`${n-t+1}`),this}abortSignal(t){return this.signal=t,this}single(){return this.headers.Accept="application/vnd.pgrst.object+json",this}maybeSingle(){return this.method==="GET"?this.headers.Accept="application/json":this.headers.Accept="application/vnd.pgrst.object+json",this.isMaybeSingle=!0,this}csv(){return this.headers.Accept="text/csv",this}geojson(){return this.headers.Accept="application/geo+json",this}explain({analyze:t=!1,verbose:n=!1,settings:r=!1,buffers:a=!1,wal:i=!1,format:l="text"}={}){var o;const c=[t?"analyze":null,n?"verbose":null,r?"settings":null,a?"buffers":null,i?"wal":null].filter(Boolean).join("|"),d=(o=this.headers.Accept)!==null&&o!==void 0?o:"application/json";return this.headers.Accept=`application/vnd.pgrst.plan+${l}; for="${d}"; options=${c};`,l==="json"?this:this}rollback(){var t;return((t=this.headers.Prefer)!==null&&t!==void 0?t:"").trim().length>0?this.headers.Prefer+=",tx=rollback":this.headers.Prefer="tx=rollback",this}returns(){return this}};_3e.default=Ccs;var Acs=jf&&jf.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(oee,"__esModule",{value:!0});const Ecs=Acs(_3e);let Tcs=class extends Ecs.default{eq(t,n){return this.url.searchParams.append(t,`eq.${n}`),this}neq(t,n){return this.url.searchParams.append(t,`neq.${n}`),this}gt(t,n){return this.url.searchParams.append(t,`gt.${n}`),this}gte(t,n){return this.url.searchParams.append(t,`gte.${n}`),this}lt(t,n){return this.url.searchParams.append(t,`lt.${n}`),this}lte(t,n){return this.url.searchParams.append(t,`lte.${n}`),this}like(t,n){return this.url.searchParams.append(t,`like.${n}`),this}likeAllOf(t,n){return this.url.searchParams.append(t,`like(all).{${n.join(",")}}`),this}likeAnyOf(t,n){return this.url.searchParams.append(t,`like(any).{${n.join(",")}}`),this}ilike(t,n){return this.url.searchParams.append(t,`ilike.${n}`),this}ilikeAllOf(t,n){return this.url.searchParams.append(t,`ilike(all).{${n.join(",")}}`),this}ilikeAnyOf(t,n){return this.url.searchParams.append(t,`ilike(any).{${n.join(",")}}`),this}is(t,n){return this.url.searchParams.append(t,`is.${n}`),this}in(t,n){const r=Array.from(new Set(n)).map(a=>typeof a=="string"&&new RegExp("[,()]").test(a)?`"${a}"`:`${a}`).join(",");return this.url.searchParams.append(t,`in.(${r})`),this}contains(t,n){return typeof n=="string"?this.url.searchParams.append(t,`cs.${n}`):Array.isArray(n)?this.url.searchParams.append(t,`cs.{${n.join(",")}}`):this.url.searchParams.append(t,`cs.${JSON.stringify(n)}`),this}containedBy(t,n){return typeof n=="string"?this.url.searchParams.append(t,`cd.${n}`):Array.isArray(n)?this.url.searchParams.append(t,`cd.{${n.join(",")}}`):this.url.searchParams.append(t,`cd.${JSON.stringify(n)}`),this}rangeGt(t,n){return this.url.searchParams.append(t,`sr.${n}`),this}rangeGte(t,n){return this.url.searchParams.append(t,`nxl.${n}`),this}rangeLt(t,n){return this.url.searchParams.append(t,`sl.${n}`),this}rangeLte(t,n){return this.url.searchParams.append(t,`nxr.${n}`),this}rangeAdjacent(t,n){return this.url.searchParams.append(t,`adj.${n}`),this}overlaps(t,n){return typeof n=="string"?this.url.searchParams.append(t,`ov.${n}`):this.url.searchParams.append(t,`ov.{${n.join(",")}}`),this}textSearch(t,n,{config:r,type:a}={}){let i="";a==="plain"?i="pl":a==="phrase"?i="ph":a==="websearch"&&(i="w");const l=r===void 0?"":`(${r})`;return this.url.searchParams.append(t,`${i}fts${l}.${n}`),this}match(t){return Object.entries(t).forEach(([n,r])=>{this.url.searchParams.append(n,`eq.${r}`)}),this}not(t,n,r){return this.url.searchParams.append(t,`not.${n}.${r}`),this}or(t,{foreignTable:n,referencedTable:r=n}={}){const a=r?`${r}.or`:"or";return this.url.searchParams.append(a,`(${t})`),this}filter(t,n,r){return this.url.searchParams.append(t,`${n}.${r}`),this}};oee.default=Tcs;var Mcs=jf&&jf.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(b3e,"__esModule",{value:!0});const sG=Mcs(oee);let Pcs=class{constructor(t,{headers:n={},schema:r,fetch:a}){this.url=t,this.headers=n,this.schema=r,this.fetch=a}select(t,{head:n=!1,count:r}={}){const a=n?"HEAD":"GET";let i=!1;const l=(t??"*").split("").map(o=>/\s/.test(o)&&!i?"":(o==='"'&&(i=!i),o)).join("");return this.url.searchParams.set("select",l),r&&(this.headers.Prefer=`count=${r}`),new sG.default({method:a,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}insert(t,{count:n,defaultToNull:r=!0}={}){const a="POST",i=[];if(this.headers.Prefer&&i.push(this.headers.Prefer),n&&i.push(`count=${n}`),r||i.push("missing=default"),this.headers.Prefer=i.join(","),Array.isArray(t)){const l=t.reduce((o,c)=>o.concat(Object.keys(c)),[]);if(l.length>0){const o=[...new Set(l)].map(c=>`"${c}"`);this.url.searchParams.set("columns",o.join(","))}}return new sG.default({method:a,url:this.url,headers:this.headers,schema:this.schema,body:t,fetch:this.fetch,allowEmpty:!1})}upsert(t,{onConflict:n,ignoreDuplicates:r=!1,count:a,defaultToNull:i=!0}={}){const l="POST",o=[`resolution=${r?"ignore":"merge"}-duplicates`];if(n!==void 0&&this.url.searchParams.set("on_conflict",n),this.headers.Prefer&&o.push(this.headers.Prefer),a&&o.push(`count=${a}`),i||o.push("missing=default"),this.headers.Prefer=o.join(","),Array.isArray(t)){const c=t.reduce((d,u)=>d.concat(Object.keys(u)),[]);if(c.length>0){const d=[...new Set(c)].map(u=>`"${u}"`);this.url.searchParams.set("columns",d.join(","))}}return new sG.default({method:l,url:this.url,headers:this.headers,schema:this.schema,body:t,fetch:this.fetch,allowEmpty:!1})}update(t,{count:n}={}){const r="PATCH",a=[];return this.headers.Prefer&&a.push(this.headers.Prefer),n&&a.push(`count=${n}`),this.headers.Prefer=a.join(","),new sG.default({method:r,url:this.url,headers:this.headers,schema:this.schema,body:t,fetch:this.fetch,allowEmpty:!1})}delete({count:t}={}){const n="DELETE",r=[];return t&&r.push(`count=${t}`),this.headers.Prefer&&r.unshift(this.headers.Prefer),this.headers.Prefer=r.join(","),new sG.default({method:n,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}};b3e.default=Pcs;var N3e={},k3e={};Object.defineProperty(k3e,"__esModule",{value:!0});k3e.version=void 0;k3e.version="0.0.0-automated";Object.defineProperty(N3e,"__esModule",{value:!0});N3e.DEFAULT_HEADERS=void 0;const Ics=k3e;N3e.DEFAULT_HEADERS={"X-Client-Info":`postgrest-js/${Ics.version}`};var n4t=jf&&jf.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(gHe,"__esModule",{value:!0});const Lcs=n4t(b3e),Rcs=n4t(oee),Dcs=N3e;let Ocs=class r4t{constructor(t,{headers:n={},schema:r,fetch:a}={}){this.url=t,this.headers=Object.assign(Object.assign({},Dcs.DEFAULT_HEADERS),n),this.schemaName=r,this.fetch=a}from(t){const n=new URL(`${this.url}/${t}`);return new Lcs.default(n,{headers:Object.assign({},this.headers),schema:this.schemaName,fetch:this.fetch})}schema(t){return new r4t(this.url,{headers:this.headers,schema:t,fetch:this.fetch})}rpc(t,n={},{head:r=!1,get:a=!1,count:i}={}){let l;const o=new URL(`${this.url}/rpc/${t}`);let c;r||a?(l=r?"HEAD":"GET",Object.entries(n).filter(([u,h])=>h!==void 0).map(([u,h])=>[u,Array.isArray(h)?`{${h.join(",")}}`:`${h}`]).forEach(([u,h])=>{o.searchParams.append(u,h)})):(l="POST",c=n);const d=Object.assign({},this.headers);return i&&(d.Prefer=`count=${i}`),new Rcs.default({method:l,url:o,headers:d,schema:this.schemaName,body:c,fetch:this.fetch,allowEmpty:!1})}};gHe.default=Ocs;var $q=jf&&jf.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(d_,"__esModule",{value:!0});d_.PostgrestError=d_.PostgrestBuilder=d_.PostgrestTransformBuilder=d_.PostgrestFilterBuilder=d_.PostgrestQueryBuilder=d_.PostgrestClient=void 0;const a4t=$q(gHe);d_.PostgrestClient=a4t.default;const i4t=$q(b3e);d_.PostgrestQueryBuilder=i4t.default;const o4t=$q(oee);d_.PostgrestFilterBuilder=o4t.default;const l4t=$q(_3e);d_.PostgrestTransformBuilder=l4t.default;const c4t=$q(w3e);d_.PostgrestBuilder=c4t.default;const d4t=$q(j3e);d_.PostgrestError=d4t.default;var Fcs=d_.default={PostgrestClient:a4t.default,PostgrestQueryBuilder:i4t.default,PostgrestFilterBuilder:o4t.default,PostgrestTransformBuilder:l4t.default,PostgrestBuilder:c4t.default,PostgrestError:d4t.default};const{PostgrestClient:zcs,PostgrestQueryBuilder:bQn,PostgrestFilterBuilder:_Qn,PostgrestTransformBuilder:wQn,PostgrestBuilder:jQn,PostgrestError:NQn}=Fcs;let VFe;typeof window>"u"?VFe=require("ws"):VFe=window.WebSocket;const Bcs="2.11.10",$cs={"X-Client-Info":`realtime-js/${Bcs}`},Ucs="1.0.0",u4t=1e4,qcs=1e3;var NB;(function(s){s[s.connecting=0]="connecting",s[s.open=1]="open",s[s.closing=2]="closing",s[s.closed=3]="closed"})(NB||(NB={}));var Y1;(function(s){s.closed="closed",s.errored="errored",s.joined="joined",s.joining="joining",s.leaving="leaving"})(Y1||(Y1={}));var BN;(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"})(BN||(BN={}));var HFe;(function(s){s.websocket="websocket"})(HFe||(HFe={}));var HR;(function(s){s.Connecting="connecting",s.Open="open",s.Closing="closing",s.Closed="closed"})(HR||(HR={}));class Vcs{constructor(){this.HEADER_LENGTH=1}decode(t,n){return t.constructor===ArrayBuffer?n(this._binaryDecode(t)):n(typeof t=="string"?JSON.parse(t):{})}_binaryDecode(t){const n=new DataView(t),r=new TextDecoder;return this._decodeBroadcast(t,n,r)}_decodeBroadcast(t,n,r){const a=n.getUint8(1),i=n.getUint8(2);let l=this.HEADER_LENGTH+2;const o=r.decode(t.slice(l,l+a));l=l+a;const c=r.decode(t.slice(l,l+i));l=l+i;const d=JSON.parse(r.decode(t.slice(l,t.byteLength)));return{ref:null,topic:o,event:c,payload:d}}}class h4t{constructor(t,n){this.callback=t,this.timerCalc=n,this.timer=void 0,this.tries=0,this.callback=t,this.timerCalc=n}reset(){this.tries=0,clearTimeout(this.timer)}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}}var Tm;(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"})(Tm||(Tm={}));const Pit=(s,t,n={})=>{var r;const a=(r=n.skipTypes)!==null&&r!==void 0?r:[];return Object.keys(t).reduce((i,l)=>(i[l]=Hcs(l,s,t,a),i),{})},Hcs=(s,t,n,r)=>{const a=t.find(o=>o.name===s),i=a==null?void 0:a.type,l=n[s];return i&&!r.includes(i)?m4t(i,l):GFe(l)},m4t=(s,t)=>{if(s.charAt(0)==="_"){const n=s.slice(1,s.length);return Ycs(t,n)}switch(s){case Tm.bool:return Gcs(t);case Tm.float4:case Tm.float8:case Tm.int2:case Tm.int4:case Tm.int8:case Tm.numeric:case Tm.oid:return Wcs(t);case Tm.json:case Tm.jsonb:return Kcs(t);case Tm.timestamp:return Zcs(t);case Tm.abstime:case Tm.date:case Tm.daterange:case Tm.int4range:case Tm.int8range:case Tm.money:case Tm.reltime:case Tm.text:case Tm.time:case Tm.timestamptz:case Tm.timetz:case Tm.tsrange:case Tm.tstzrange:return GFe(t);default:return GFe(t)}},GFe=s=>s,Gcs=s=>{switch(s){case"t":return!0;case"f":return!1;default:return s}},Wcs=s=>{if(typeof s=="string"){const t=parseFloat(s);if(!Number.isNaN(t))return t}return s},Kcs=s=>{if(typeof s=="string")try{return JSON.parse(s)}catch(t){return console.log(`JSON parse error: ${t}`),s}return s},Ycs=(s,t)=>{if(typeof s!="string")return s;const n=s.length-1,r=s[n];if(s[0]==="{"&&r==="}"){let i;const l=s.slice(1,n);try{i=JSON.parse("["+l+"]")}catch{i=l?l.split(","):[]}return i.map(o=>m4t(t,o))}return s},Zcs=s=>typeof s=="string"?s.replace(" ","T"):s,f4t=s=>{let t=s;return t=t.replace(/^ws/i,"http"),t=t.replace(/(\/socket\/websocket|\/socket|\/websocket)\/?$/i,""),t.replace(/\/+$/,"")};class rIe{constructor(t,n,r={},a=u4t){this.channel=t,this.event=n,this.payload=r,this.timeout=a,this.sent=!1,this.timeoutTimer=void 0,this.ref="",this.receivedResp=null,this.recHooks=[],this.refEvent=null}resend(t){this.timeout=t,this._cancelRefEvent(),this.ref="",this.refEvent=null,this.receivedResp=null,this.sent=!1,this.send()}send(){this._hasReceived("timeout")||(this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload,ref:this.ref,join_ref:this.channel._joinRef()}))}updatePayload(t){this.payload=Object.assign(Object.assign({},this.payload),t)}receive(t,n){var r;return this._hasReceived(t)&&n((r=this.receivedResp)===null||r===void 0?void 0:r.response),this.recHooks.push({status:t,callback:n}),this}startTimeout(){if(this.timeoutTimer)return;this.ref=this.channel.socket._makeRef(),this.refEvent=this.channel._replyEventName(this.ref);const t=n=>{this._cancelRefEvent(),this._cancelTimeout(),this.receivedResp=n,this._matchReceive(n)};this.channel._on(this.refEvent,{},t),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}trigger(t,n){this.refEvent&&this.channel._trigger(this.refEvent,{status:t,response:n})}destroy(){this._cancelRefEvent(),this._cancelTimeout()}_cancelRefEvent(){this.refEvent&&this.channel._off(this.refEvent,{})}_cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=void 0}_matchReceive({status:t,response:n}){this.recHooks.filter(r=>r.status===t).forEach(r=>r.callback(n))}_hasReceived(t){return this.receivedResp&&this.receivedResp.status===t}}var Iit;(function(s){s.SYNC="sync",s.JOIN="join",s.LEAVE="leave"})(Iit||(Iit={}));class hY{constructor(t,n){this.channel=t,this.state={},this.pendingDiffs=[],this.joinRef=null,this.caller={onJoin:()=>{},onLeave:()=>{},onSync:()=>{}};const r=(n==null?void 0:n.events)||{state:"presence_state",diff:"presence_diff"};this.channel._on(r.state,{},a=>{const{onJoin:i,onLeave:l,onSync:o}=this.caller;this.joinRef=this.channel._joinRef(),this.state=hY.syncState(this.state,a,i,l),this.pendingDiffs.forEach(c=>{this.state=hY.syncDiff(this.state,c,i,l)}),this.pendingDiffs=[],o()}),this.channel._on(r.diff,{},a=>{const{onJoin:i,onLeave:l,onSync:o}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(a):(this.state=hY.syncDiff(this.state,a,i,l),o())}),this.onJoin((a,i,l)=>{this.channel._trigger("presence",{event:"join",key:a,currentPresences:i,newPresences:l})}),this.onLeave((a,i,l)=>{this.channel._trigger("presence",{event:"leave",key:a,currentPresences:i,leftPresences:l})}),this.onSync(()=>{this.channel._trigger("presence",{event:"sync"})})}static syncState(t,n,r,a){const i=this.cloneDeep(t),l=this.transformState(n),o={},c={};return this.map(i,(d,u)=>{l[d]||(c[d]=u)}),this.map(l,(d,u)=>{const h=i[d];if(h){const m=u.map(y=>y.presence_ref),p=h.map(y=>y.presence_ref),g=u.filter(y=>p.indexOf(y.presence_ref)<0),x=h.filter(y=>m.indexOf(y.presence_ref)<0);g.length>0&&(o[d]=g),x.length>0&&(c[d]=x)}else o[d]=u}),this.syncDiff(i,{joins:o,leaves:c},r,a)}static syncDiff(t,n,r,a){const{joins:i,leaves:l}={joins:this.transformState(n.joins),leaves:this.transformState(n.leaves)};return r||(r=()=>{}),a||(a=()=>{}),this.map(i,(o,c)=>{var d;const u=(d=t[o])!==null&&d!==void 0?d:[];if(t[o]=this.cloneDeep(c),u.length>0){const h=t[o].map(p=>p.presence_ref),m=u.filter(p=>h.indexOf(p.presence_ref)<0);t[o].unshift(...m)}r(o,u,c)}),this.map(l,(o,c)=>{let d=t[o];if(!d)return;const u=c.map(h=>h.presence_ref);d=d.filter(h=>u.indexOf(h.presence_ref)<0),t[o]=d,a(o,d,c),d.length===0&&delete t[o]}),t}static map(t,n){return Object.getOwnPropertyNames(t).map(r=>n(r,t[r]))}static transformState(t){return t=this.cloneDeep(t),Object.getOwnPropertyNames(t).reduce((n,r)=>{const a=t[r];return"metas"in a?n[r]=a.metas.map(i=>(i.presence_ref=i.phx_ref,delete i.phx_ref,delete i.phx_ref_prev,i)):n[r]=a,n},{})}static cloneDeep(t){return JSON.parse(JSON.stringify(t))}onJoin(t){this.caller.onJoin=t}onLeave(t){this.caller.onLeave=t}onSync(t){this.caller.onSync=t}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel._joinRef()}}var Lit;(function(s){s.ALL="*",s.INSERT="INSERT",s.UPDATE="UPDATE",s.DELETE="DELETE"})(Lit||(Lit={}));var Rit;(function(s){s.BROADCAST="broadcast",s.PRESENCE="presence",s.POSTGRES_CHANGES="postgres_changes",s.SYSTEM="system"})(Rit||(Rit={}));var pC;(function(s){s.SUBSCRIBED="SUBSCRIBED",s.TIMED_OUT="TIMED_OUT",s.CLOSED="CLOSED",s.CHANNEL_ERROR="CHANNEL_ERROR"})(pC||(pC={}));class xHe{constructor(t,n={config:{}},r){this.topic=t,this.params=n,this.socket=r,this.bindings={},this.state=Y1.closed,this.joinedOnce=!1,this.pushBuffer=[],this.subTopic=t.replace(/^realtime:/i,""),this.params.config=Object.assign({broadcast:{ack:!1,self:!1},presence:{key:""},private:!1},n.config),this.timeout=this.socket.timeout,this.joinPush=new rIe(this,BN.join,this.params,this.timeout),this.rejoinTimer=new h4t(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=Y1.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=Y1.closed,this.socket._remove(this)}),this._onError(a=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,a),this.state=Y1.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=Y1.errored,this.rejoinTimer.scheduleTimeout())}),this._on(BN.reply,{},(a,i)=>{this._trigger(this._replyEventName(i),a)}),this.presence=new hY(this),this.broadcastEndpointURL=f4t(this.socket.endPoint)+"/api/broadcast",this.private=this.params.config.private||!1}subscribe(t,n=this.timeout){var r,a;if(this.socket.isConnected()||this.socket.connect(),this.joinedOnce)throw"tried to subscribe multiple times. 'subscribe' can only be called a single time per channel instance";{const{config:{broadcast:i,presence:l,private:o}}=this.params;this._onError(u=>t==null?void 0:t(pC.CHANNEL_ERROR,u)),this._onClose(()=>t==null?void 0:t(pC.CLOSED));const c={},d={broadcast:i,presence:l,postgres_changes:(a=(r=this.bindings.postgres_changes)===null||r===void 0?void 0:r.map(u=>u.filter))!==null&&a!==void 0?a:[],private:o};this.socket.accessTokenValue&&(c.access_token=this.socket.accessTokenValue),this.updateJoinPayload(Object.assign({config:d},c)),this.joinedOnce=!0,this._rejoin(n),this.joinPush.receive("ok",async({postgres_changes:u})=>{var h;if(this.socket.setAuth(),u===void 0){t==null||t(pC.SUBSCRIBED);return}else{const m=this.bindings.postgres_changes,p=(h=m==null?void 0:m.length)!==null&&h!==void 0?h:0,g=[];for(let x=0;x{this.state=Y1.errored,t==null||t(pC.CHANNEL_ERROR,new Error(JSON.stringify(Object.values(u).join(", ")||"error")))}).receive("timeout",()=>{t==null||t(pC.TIMED_OUT)})}return this}presenceState(){return this.presence.state}async track(t,n={}){return await this.send({type:"presence",event:"track",payload:t},n.timeout||this.timeout)}async untrack(t={}){return await this.send({type:"presence",event:"untrack"},t)}on(t,n,r){return this._on(t,n,r)}async send(t,n={}){var r,a;if(!this._canPush()&&t.type==="broadcast"){const{event:i,payload:l}=t,c={method:"POST",headers:{Authorization:this.socket.accessTokenValue?`Bearer ${this.socket.accessTokenValue}`:"",apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"},body:JSON.stringify({messages:[{topic:this.subTopic,event:i,payload:l,private:this.private}]})};try{const d=await this._fetchWithTimeout(this.broadcastEndpointURL,c,(r=n.timeout)!==null&&r!==void 0?r:this.timeout);return await((a=d.body)===null||a===void 0?void 0:a.cancel()),d.ok?"ok":"error"}catch(d){return d.name==="AbortError"?"timed out":"error"}}else return new Promise(i=>{var l,o,c;const d=this._push(t.type,t,n.timeout||this.timeout);t.type==="broadcast"&&!(!((c=(o=(l=this.params)===null||l===void 0?void 0:l.config)===null||o===void 0?void 0:o.broadcast)===null||c===void 0)&&c.ack)&&i("ok"),d.receive("ok",()=>i("ok")),d.receive("error",()=>i("error")),d.receive("timeout",()=>i("timed out"))})}updateJoinPayload(t){this.joinPush.updatePayload(t)}unsubscribe(t=this.timeout){this.state=Y1.leaving;const n=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(BN.close,"leave",this._joinRef())};return this.joinPush.destroy(),new Promise(r=>{const a=new rIe(this,BN.leave,{},t);a.receive("ok",()=>{n(),r("ok")}).receive("timeout",()=>{n(),r("timed out")}).receive("error",()=>{r("error")}),a.send(),this._canPush()||a.trigger("ok",{})})}teardown(){this.pushBuffer.forEach(t=>t.destroy()),this.rejoinTimer&&clearTimeout(this.rejoinTimer.timer),this.joinPush.destroy()}async _fetchWithTimeout(t,n,r){const a=new AbortController,i=setTimeout(()=>a.abort(),r),l=await this.socket.fetch(t,Object.assign(Object.assign({},n),{signal:a.signal}));return clearTimeout(i),l}_push(t,n,r=this.timeout){if(!this.joinedOnce)throw`tried to push '${t}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`;let a=new rIe(this,t,n,r);return this._canPush()?a.send():(a.startTimeout(),this.pushBuffer.push(a)),a}_onMessage(t,n,r){return n}_isMember(t){return this.topic===t}_joinRef(){return this.joinPush.ref}_trigger(t,n,r){var a,i;const l=t.toLocaleLowerCase(),{close:o,error:c,leave:d,join:u}=BN;if(r&&[o,c,d,u].indexOf(l)>=0&&r!==this._joinRef())return;let m=this._onMessage(l,n,r);if(n&&!m)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(p=>{var g,x,y;return((g=p.filter)===null||g===void 0?void 0:g.event)==="*"||((y=(x=p.filter)===null||x===void 0?void 0:x.event)===null||y===void 0?void 0:y.toLocaleLowerCase())===l}).map(p=>p.callback(m,r)):(i=this.bindings[l])===null||i===void 0||i.filter(p=>{var g,x,y,v,_,j;if(["broadcast","presence","postgres_changes"].includes(l))if("id"in p){const C=p.id,A=(g=p.filter)===null||g===void 0?void 0:g.event;return C&&((x=n.ids)===null||x===void 0?void 0:x.includes(C))&&(A==="*"||(A==null?void 0:A.toLocaleLowerCase())===((y=n.data)===null||y===void 0?void 0:y.type.toLocaleLowerCase()))}else{const C=(_=(v=p==null?void 0:p.filter)===null||v===void 0?void 0:v.event)===null||_===void 0?void 0:_.toLocaleLowerCase();return C==="*"||C===((j=n==null?void 0:n.event)===null||j===void 0?void 0:j.toLocaleLowerCase())}else return p.type.toLocaleLowerCase()===l}).map(p=>{if(typeof m=="object"&&"ids"in m){const g=m.data,{schema:x,table:y,commit_timestamp:v,type:_,errors:j}=g;m=Object.assign(Object.assign({},{schema:x,table:y,commit_timestamp:v,eventType:_,new:{},old:{},errors:j}),this._getPayloadRecords(g))}p.callback(m,r)})}_isClosed(){return this.state===Y1.closed}_isJoined(){return this.state===Y1.joined}_isJoining(){return this.state===Y1.joining}_isLeaving(){return this.state===Y1.leaving}_replyEventName(t){return`chan_reply_${t}`}_on(t,n,r){const a=t.toLocaleLowerCase(),i={type:a,filter:n,callback:r};return this.bindings[a]?this.bindings[a].push(i):this.bindings[a]=[i],this}_off(t,n){const r=t.toLocaleLowerCase();return this.bindings[r]=this.bindings[r].filter(a=>{var i;return!(((i=a.type)===null||i===void 0?void 0:i.toLocaleLowerCase())===r&&xHe.isEqual(a.filter,n))}),this}static isEqual(t,n){if(Object.keys(t).length!==Object.keys(n).length)return!1;for(const r in t)if(t[r]!==n[r])return!1;return!0}_rejoinUntilConnected(){this.rejoinTimer.scheduleTimeout(),this.socket.isConnected()&&this._rejoin()}_onClose(t){this._on(BN.close,{},t)}_onError(t){this._on(BN.error,{},n=>t(n))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(t=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=Y1.joining,this.joinPush.resend(t))}_getPayloadRecords(t){const n={new:{},old:{}};return(t.type==="INSERT"||t.type==="UPDATE")&&(n.new=Pit(t.columns,t.record)),(t.type==="UPDATE"||t.type==="DELETE")&&(n.old=Pit(t.columns,t.old_record)),n}}const Dit=()=>{},Xcs=` addEventListener("message", (e) => { if (e.data.event === "start") { setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval); } });`;class Qcs{constructor(t,n){var r;this.accessTokenValue=null,this.apiKey=null,this.channels=new Array,this.endPoint="",this.httpEndpoint="",this.headers=$cs,this.params={},this.timeout=u4t,this.heartbeatIntervalMs=25e3,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.heartbeatCallback=Dit,this.ref=0,this.logger=Dit,this.conn=null,this.sendBuffer=[],this.serializer=new Vcs,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.accessToken=null,this._resolveFetch=i=>{let l;return i?l=i:typeof fetch>"u"?l=(...o)=>Ai(async()=>{const{default:c}=await Promise.resolve().then(()=>Bq);return{default:c}},void 0).then(({default:c})=>c(...o)):l=fetch,(...o)=>l(...o)},this.endPoint=`${t}/${HFe.websocket}`,this.httpEndpoint=f4t(t),n!=null&&n.transport?this.transport=n.transport:this.transport=null,n!=null&&n.params&&(this.params=n.params),n!=null&&n.headers&&(this.headers=Object.assign(Object.assign({},this.headers),n.headers)),n!=null&&n.timeout&&(this.timeout=n.timeout),n!=null&&n.logger&&(this.logger=n.logger),(n!=null&&n.logLevel||n!=null&&n.log_level)&&(this.logLevel=n.logLevel||n.log_level,this.params=Object.assign(Object.assign({},this.params),{log_level:this.logLevel})),n!=null&&n.heartbeatIntervalMs&&(this.heartbeatIntervalMs=n.heartbeatIntervalMs);const a=(r=n==null?void 0:n.params)===null||r===void 0?void 0:r.apikey;if(a&&(this.accessTokenValue=a,this.apiKey=a),this.reconnectAfterMs=n!=null&&n.reconnectAfterMs?n.reconnectAfterMs:i=>[1e3,2e3,5e3,1e4][i-1]||1e4,this.encode=n!=null&&n.encode?n.encode:(i,l)=>l(JSON.stringify(i)),this.decode=n!=null&&n.decode?n.decode:this.serializer.decode.bind(this.serializer),this.reconnectTimer=new h4t(async()=>{this.disconnect(),this.connect()},this.reconnectAfterMs),this.fetch=this._resolveFetch(n==null?void 0:n.fetch),n!=null&&n.worker){if(typeof window<"u"&&!window.Worker)throw new Error("Web Worker is not supported");this.worker=(n==null?void 0:n.worker)||!1,this.workerUrl=n==null?void 0:n.workerUrl}this.accessToken=(n==null?void 0:n.accessToken)||null}connect(){if(!this.conn){if(this.transport||(this.transport=VFe),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 Jcs(this.endpointURL(),void 0,{close:()=>{this.conn=null}})}}endpointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:Ucs}))}disconnect(t,n){this.conn&&(this.conn.onclose=function(){},t?this.conn.close(t,n??""):this.conn.close(),this.conn=null,this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.reconnectTimer.reset(),this.channels.forEach(r=>r.teardown()))}getChannels(){return this.channels}async removeChannel(t){const n=await t.unsubscribe();return this.channels=this.channels.filter(r=>r._joinRef!==t._joinRef),this.channels.length===0&&this.disconnect(),n}async removeAllChannels(){const t=await Promise.all(this.channels.map(n=>n.unsubscribe()));return this.channels=[],this.disconnect(),t}log(t,n,r){this.logger(t,n,r)}connectionState(){switch(this.conn&&this.conn.readyState){case NB.connecting:return HR.Connecting;case NB.open:return HR.Open;case NB.closing:return HR.Closing;default:return HR.Closed}}isConnected(){return this.connectionState()===HR.Open}channel(t,n={config:{}}){const r=`realtime:${t}`,a=this.getChannels().find(i=>i.topic===r);if(a)return a;{const i=new xHe(`realtime:${t}`,n,this);return this.channels.push(i),i}}push(t){const{topic:n,event:r,payload:a,ref:i}=t,l=()=>{this.encode(t,o=>{var c;(c=this.conn)===null||c===void 0||c.send(o)})};this.log("push",`${n} ${r} (${i})`,a),this.isConnected()?l():this.sendBuffer.push(l)}async setAuth(t=null){let n=t||this.accessToken&&await this.accessToken()||this.accessTokenValue;this.accessTokenValue!=n&&(this.accessTokenValue=n,this.channels.forEach(r=>{n&&r.updateJoinPayload({access_token:n,version:this.headers&&this.headers["X-Client-Info"]}),r.joinedOnce&&r._isJoined()&&r._push(BN.access_token,{access_token:n})}))}async sendHeartbeat(){var t;if(!this.isConnected()){this.heartbeatCallback("disconnected");return}if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this.log("transport","heartbeat timeout. Attempting to re-establish connection"),this.heartbeatCallback("timeout"),(t=this.conn)===null||t===void 0||t.close(qcs,"hearbeat timeout");return}this.pendingHeartbeatRef=this._makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef}),this.heartbeatCallback("sent"),await this.setAuth()}onHeartbeat(t){this.heartbeatCallback=t}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(t=>t()),this.sendBuffer=[])}_makeRef(){let t=this.ref+1;return t===this.ref?this.ref=0:this.ref=t,this.ref.toString()}_leaveOpenTopic(t){let n=this.channels.find(r=>r.topic===t&&(r._isJoined()||r._isJoining()));n&&(this.log("transport",`leaving duplicate topic "${t}"`),n.unsubscribe())}_remove(t){this.channels=this.channels.filter(n=>n.topic!==t.topic)}setupConnection(){this.conn&&(this.conn.binaryType="arraybuffer",this.conn.onopen=()=>this._onConnOpen(),this.conn.onerror=t=>this._onConnError(t),this.conn.onmessage=t=>this._onConnMessage(t),this.conn.onclose=t=>this._onConnClose(t))}_onConnMessage(t){this.decode(t.data,n=>{let{topic:r,event:a,payload:i,ref:l}=n;r==="phoenix"&&a==="phx_reply"&&this.heartbeatCallback(n.payload.status=="ok"?"ok":"error"),l&&l===this.pendingHeartbeatRef&&(this.pendingHeartbeatRef=null),this.log("receive",`${i.status||""} ${r} ${a} ${l&&"("+l+")"||""}`,i),Array.from(this.channels).filter(o=>o._isMember(r)).forEach(o=>o._trigger(a,i,l)),this.stateChangeCallbacks.message.forEach(o=>o(n))})}_onConnOpen(){if(this.log("transport",`connected to ${this.endpointURL()}`),this.flushSendBuffer(),this.reconnectTimer.reset(),!this.worker)this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval(()=>this.sendHeartbeat(),this.heartbeatIntervalMs);else{this.workerUrl?this.log("worker",`starting worker for from ${this.workerUrl}`):this.log("worker","starting default worker");const t=this._workerObjectUrl(this.workerUrl);this.workerRef=new Worker(t),this.workerRef.onerror=n=>{this.log("worker","worker error",n.message),this.workerRef.terminate()},this.workerRef.onmessage=n=>{n.data.event==="keepAlive"&&this.sendHeartbeat()},this.workerRef.postMessage({event:"start",interval:this.heartbeatIntervalMs})}this.stateChangeCallbacks.open.forEach(t=>t())}_onConnClose(t){this.log("transport","close",t),this._triggerChanError(),this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.reconnectTimer.scheduleTimeout(),this.stateChangeCallbacks.close.forEach(n=>n(t))}_onConnError(t){this.log("transport",t.message),this._triggerChanError(),this.stateChangeCallbacks.error.forEach(n=>n(t))}_triggerChanError(){this.channels.forEach(t=>t._trigger(BN.error))}_appendParams(t,n){if(Object.keys(n).length===0)return t;const r=t.match(/\?/)?"&":"?",a=new URLSearchParams(n);return`${t}${r}${a}`}_workerObjectUrl(t){let n;if(t)n=t;else{const r=new Blob([Xcs],{type:"application/javascript"});n=URL.createObjectURL(r)}return n}}class Jcs{constructor(t,n,r){this.binaryType="arraybuffer",this.onclose=()=>{},this.onerror=()=>{},this.onmessage=()=>{},this.onopen=()=>{},this.readyState=NB.connecting,this.send=()=>{},this.url=null,this.url=t,this.close=r.close}}class yHe extends Error{constructor(t){super(t),this.__isStorageError=!0,this.name="StorageError"}}function s0(s){return typeof s=="object"&&s!==null&&"__isStorageError"in s}class eds extends yHe{constructor(t,n){super(t),this.name="StorageApiError",this.status=n}toJSON(){return{name:this.name,message:this.message,status:this.status}}}class WFe extends yHe{constructor(t,n){super(t),this.name="StorageUnknownError",this.originalError=n}}var tds=function(s,t,n,r){function a(i){return i instanceof n?i:new n(function(l){l(i)})}return new(n||(n=Promise))(function(i,l){function o(u){try{d(r.next(u))}catch(h){l(h)}}function c(u){try{d(r.throw(u))}catch(h){l(h)}}function d(u){u.done?i(u.value):a(u.value).then(o,c)}d((r=r.apply(s,t||[])).next())})};const p4t=s=>{let t;return s?t=s:typeof fetch>"u"?t=(...n)=>Ai(async()=>{const{default:r}=await Promise.resolve().then(()=>Bq);return{default:r}},void 0).then(({default:r})=>r(...n)):t=fetch,(...n)=>t(...n)},sds=()=>tds(void 0,void 0,void 0,function*(){return typeof Response>"u"?(yield Ai(()=>Promise.resolve().then(()=>Bq),void 0)).Response:Response}),KFe=s=>{if(Array.isArray(s))return s.map(n=>KFe(n));if(typeof s=="function"||s!==Object(s))return s;const t={};return Object.entries(s).forEach(([n,r])=>{const a=n.replace(/([-_][a-z])/gi,i=>i.toUpperCase().replace(/[-_]/g,""));t[a]=KFe(r)}),t};var xF=function(s,t,n,r){function a(i){return i instanceof n?i:new n(function(l){l(i)})}return new(n||(n=Promise))(function(i,l){function o(u){try{d(r.next(u))}catch(h){l(h)}}function c(u){try{d(r.throw(u))}catch(h){l(h)}}function d(u){u.done?i(u.value):a(u.value).then(o,c)}d((r=r.apply(s,t||[])).next())})};const aIe=s=>s.msg||s.message||s.error_description||s.error||JSON.stringify(s),nds=(s,t,n)=>xF(void 0,void 0,void 0,function*(){const r=yield sds();s instanceof r&&!(n!=null&&n.noResolveJson)?s.json().then(a=>{t(new eds(aIe(a),s.status||500))}).catch(a=>{t(new WFe(aIe(a),a))}):t(new WFe(aIe(s),s))}),rds=(s,t,n,r)=>{const a={method:s,headers:(t==null?void 0:t.headers)||{}};return s==="GET"?a:(a.headers=Object.assign({"Content-Type":"application/json"},t==null?void 0:t.headers),r&&(a.body=JSON.stringify(r)),Object.assign(Object.assign({},a),n))};function lee(s,t,n,r,a,i){return xF(this,void 0,void 0,function*(){return new Promise((l,o)=>{s(n,rds(t,r,a,i)).then(c=>{if(!c.ok)throw c;return r!=null&&r.noResolveJson?c:c.json()}).then(c=>l(c)).catch(c=>nds(c,o,r))})})}function rSe(s,t,n,r){return xF(this,void 0,void 0,function*(){return lee(s,"GET",t,n,r)})}function hE(s,t,n,r,a){return xF(this,void 0,void 0,function*(){return lee(s,"POST",t,r,a,n)})}function ads(s,t,n,r,a){return xF(this,void 0,void 0,function*(){return lee(s,"PUT",t,r,a,n)})}function ids(s,t,n,r){return xF(this,void 0,void 0,function*(){return lee(s,"HEAD",t,Object.assign(Object.assign({},n),{noResolveJson:!0}),r)})}function g4t(s,t,n,r,a){return xF(this,void 0,void 0,function*(){return lee(s,"DELETE",t,r,a,n)})}var Vb=function(s,t,n,r){function a(i){return i instanceof n?i:new n(function(l){l(i)})}return new(n||(n=Promise))(function(i,l){function o(u){try{d(r.next(u))}catch(h){l(h)}}function c(u){try{d(r.throw(u))}catch(h){l(h)}}function d(u){u.done?i(u.value):a(u.value).then(o,c)}d((r=r.apply(s,t||[])).next())})};const ods={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},Oit={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};class lds{constructor(t,n={},r,a){this.url=t,this.headers=n,this.bucketId=r,this.fetch=p4t(a)}uploadOrUpdate(t,n,r,a){return Vb(this,void 0,void 0,function*(){try{let i;const l=Object.assign(Object.assign({},Oit),a);let o=Object.assign(Object.assign({},this.headers),t==="POST"&&{"x-upsert":String(l.upsert)});const c=l.metadata;typeof Blob<"u"&&r instanceof Blob?(i=new FormData,i.append("cacheControl",l.cacheControl),c&&i.append("metadata",this.encodeMetadata(c)),i.append("",r)):typeof FormData<"u"&&r instanceof FormData?(i=r,i.append("cacheControl",l.cacheControl),c&&i.append("metadata",this.encodeMetadata(c))):(i=r,o["cache-control"]=`max-age=${l.cacheControl}`,o["content-type"]=l.contentType,c&&(o["x-metadata"]=this.toBase64(this.encodeMetadata(c)))),a!=null&&a.headers&&(o=Object.assign(Object.assign({},o),a.headers));const d=this._removeEmptyFolders(n),u=this._getFinalPath(d),h=yield this.fetch(`${this.url}/object/${u}`,Object.assign({method:t,body:i,headers:o},l!=null&&l.duplex?{duplex:l.duplex}:{})),m=yield h.json();return h.ok?{data:{path:d,id:m.Id,fullPath:m.Key},error:null}:{data:null,error:m}}catch(i){if(s0(i))return{data:null,error:i};throw i}})}upload(t,n,r){return Vb(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",t,n,r)})}uploadToSignedUrl(t,n,r,a){return Vb(this,void 0,void 0,function*(){const i=this._removeEmptyFolders(t),l=this._getFinalPath(i),o=new URL(this.url+`/object/upload/sign/${l}`);o.searchParams.set("token",n);try{let c;const d=Object.assign({upsert:Oit.upsert},a),u=Object.assign(Object.assign({},this.headers),{"x-upsert":String(d.upsert)});typeof Blob<"u"&&r instanceof Blob?(c=new FormData,c.append("cacheControl",d.cacheControl),c.append("",r)):typeof FormData<"u"&&r instanceof FormData?(c=r,c.append("cacheControl",d.cacheControl)):(c=r,u["cache-control"]=`max-age=${d.cacheControl}`,u["content-type"]=d.contentType);const h=yield this.fetch(o.toString(),{method:"PUT",body:c,headers:u}),m=yield h.json();return h.ok?{data:{path:i,fullPath:m.Key},error:null}:{data:null,error:m}}catch(c){if(s0(c))return{data:null,error:c};throw c}})}createSignedUploadUrl(t,n){return Vb(this,void 0,void 0,function*(){try{let r=this._getFinalPath(t);const a=Object.assign({},this.headers);n!=null&&n.upsert&&(a["x-upsert"]="true");const i=yield hE(this.fetch,`${this.url}/object/upload/sign/${r}`,{},{headers:a}),l=new URL(this.url+i.url),o=l.searchParams.get("token");if(!o)throw new yHe("No token returned by API");return{data:{signedUrl:l.toString(),path:t,token:o},error:null}}catch(r){if(s0(r))return{data:null,error:r};throw r}})}update(t,n,r){return Vb(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",t,n,r)})}move(t,n,r){return Vb(this,void 0,void 0,function*(){try{return{data:yield hE(this.fetch,`${this.url}/object/move`,{bucketId:this.bucketId,sourceKey:t,destinationKey:n,destinationBucket:r==null?void 0:r.destinationBucket},{headers:this.headers}),error:null}}catch(a){if(s0(a))return{data:null,error:a};throw a}})}copy(t,n,r){return Vb(this,void 0,void 0,function*(){try{return{data:{path:(yield hE(this.fetch,`${this.url}/object/copy`,{bucketId:this.bucketId,sourceKey:t,destinationKey:n,destinationBucket:r==null?void 0:r.destinationBucket},{headers:this.headers})).Key},error:null}}catch(a){if(s0(a))return{data:null,error:a};throw a}})}createSignedUrl(t,n,r){return Vb(this,void 0,void 0,function*(){try{let a=this._getFinalPath(t),i=yield hE(this.fetch,`${this.url}/object/sign/${a}`,Object.assign({expiresIn:n},r!=null&&r.transform?{transform:r.transform}:{}),{headers:this.headers});const l=r!=null&&r.download?`&download=${r.download===!0?"":r.download}`:"";return i={signedUrl:encodeURI(`${this.url}${i.signedURL}${l}`)},{data:i,error:null}}catch(a){if(s0(a))return{data:null,error:a};throw a}})}createSignedUrls(t,n,r){return Vb(this,void 0,void 0,function*(){try{const a=yield hE(this.fetch,`${this.url}/object/sign/${this.bucketId}`,{expiresIn:n,paths:t},{headers:this.headers}),i=r!=null&&r.download?`&download=${r.download===!0?"":r.download}`:"";return{data:a.map(l=>Object.assign(Object.assign({},l),{signedUrl:l.signedURL?encodeURI(`${this.url}${l.signedURL}${i}`):null})),error:null}}catch(a){if(s0(a))return{data:null,error:a};throw a}})}download(t,n){return Vb(this,void 0,void 0,function*(){const a=typeof(n==null?void 0:n.transform)<"u"?"render/image/authenticated":"object",i=this.transformOptsToQueryString((n==null?void 0:n.transform)||{}),l=i?`?${i}`:"";try{const o=this._getFinalPath(t);return{data:yield(yield rSe(this.fetch,`${this.url}/${a}/${o}${l}`,{headers:this.headers,noResolveJson:!0})).blob(),error:null}}catch(o){if(s0(o))return{data:null,error:o};throw o}})}info(t){return Vb(this,void 0,void 0,function*(){const n=this._getFinalPath(t);try{const r=yield rSe(this.fetch,`${this.url}/object/info/${n}`,{headers:this.headers});return{data:KFe(r),error:null}}catch(r){if(s0(r))return{data:null,error:r};throw r}})}exists(t){return Vb(this,void 0,void 0,function*(){const n=this._getFinalPath(t);try{return yield ids(this.fetch,`${this.url}/object/${n}`,{headers:this.headers}),{data:!0,error:null}}catch(r){if(s0(r)&&r instanceof WFe){const a=r.originalError;if([400,404].includes(a==null?void 0:a.status))return{data:!1,error:r}}throw r}})}getPublicUrl(t,n){const r=this._getFinalPath(t),a=[],i=n!=null&&n.download?`download=${n.download===!0?"":n.download}`:"";i!==""&&a.push(i);const o=typeof(n==null?void 0:n.transform)<"u"?"render/image":"object",c=this.transformOptsToQueryString((n==null?void 0:n.transform)||{});c!==""&&a.push(c);let d=a.join("&");return d!==""&&(d=`?${d}`),{data:{publicUrl:encodeURI(`${this.url}/${o}/public/${r}${d}`)}}}remove(t){return Vb(this,void 0,void 0,function*(){try{return{data:yield g4t(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:t},{headers:this.headers}),error:null}}catch(n){if(s0(n))return{data:null,error:n};throw n}})}list(t,n,r){return Vb(this,void 0,void 0,function*(){try{const a=Object.assign(Object.assign(Object.assign({},ods),n),{prefix:t||""});return{data:yield hE(this.fetch,`${this.url}/object/list/${this.bucketId}`,a,{headers:this.headers},r),error:null}}catch(a){if(s0(a))return{data:null,error:a};throw a}})}encodeMetadata(t){return JSON.stringify(t)}toBase64(t){return typeof Buffer<"u"?Buffer.from(t).toString("base64"):btoa(t)}_getFinalPath(t){return`${this.bucketId}/${t}`}_removeEmptyFolders(t){return t.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}transformOptsToQueryString(t){const n=[];return t.width&&n.push(`width=${t.width}`),t.height&&n.push(`height=${t.height}`),t.resize&&n.push(`resize=${t.resize}`),t.format&&n.push(`format=${t.format}`),t.quality&&n.push(`quality=${t.quality}`),n.join("&")}}const cds="2.7.1",dds={"X-Client-Info":`storage-js/${cds}`};var F7=function(s,t,n,r){function a(i){return i instanceof n?i:new n(function(l){l(i)})}return new(n||(n=Promise))(function(i,l){function o(u){try{d(r.next(u))}catch(h){l(h)}}function c(u){try{d(r.throw(u))}catch(h){l(h)}}function d(u){u.done?i(u.value):a(u.value).then(o,c)}d((r=r.apply(s,t||[])).next())})};class uds{constructor(t,n={},r){this.url=t,this.headers=Object.assign(Object.assign({},dds),n),this.fetch=p4t(r)}listBuckets(){return F7(this,void 0,void 0,function*(){try{return{data:yield rSe(this.fetch,`${this.url}/bucket`,{headers:this.headers}),error:null}}catch(t){if(s0(t))return{data:null,error:t};throw t}})}getBucket(t){return F7(this,void 0,void 0,function*(){try{return{data:yield rSe(this.fetch,`${this.url}/bucket/${t}`,{headers:this.headers}),error:null}}catch(n){if(s0(n))return{data:null,error:n};throw n}})}createBucket(t,n={public:!1}){return F7(this,void 0,void 0,function*(){try{return{data:yield hE(this.fetch,`${this.url}/bucket`,{id:t,name:t,public:n.public,file_size_limit:n.fileSizeLimit,allowed_mime_types:n.allowedMimeTypes},{headers:this.headers}),error:null}}catch(r){if(s0(r))return{data:null,error:r};throw r}})}updateBucket(t,n){return F7(this,void 0,void 0,function*(){try{return{data:yield ads(this.fetch,`${this.url}/bucket/${t}`,{id:t,name:t,public:n.public,file_size_limit:n.fileSizeLimit,allowed_mime_types:n.allowedMimeTypes},{headers:this.headers}),error:null}}catch(r){if(s0(r))return{data:null,error:r};throw r}})}emptyBucket(t){return F7(this,void 0,void 0,function*(){try{return{data:yield hE(this.fetch,`${this.url}/bucket/${t}/empty`,{},{headers:this.headers}),error:null}}catch(n){if(s0(n))return{data:null,error:n};throw n}})}deleteBucket(t){return F7(this,void 0,void 0,function*(){try{return{data:yield g4t(this.fetch,`${this.url}/bucket/${t}`,{},{headers:this.headers}),error:null}}catch(n){if(s0(n))return{data:null,error:n};throw n}})}}class hds extends uds{constructor(t,n={},r){super(t,n,r)}from(t){return new lds(this.url,this.headers,t,this.fetch)}}const mds="2.49.10";let wW="";typeof Deno<"u"?wW="deno":typeof document<"u"?wW="web":typeof navigator<"u"&&navigator.product==="ReactNative"?wW="react-native":wW="node";const fds={"X-Client-Info":`supabase-js-${wW}/${mds}`},pds={headers:fds},gds={schema:"public"},xds={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},yds={};var vds=function(s,t,n,r){function a(i){return i instanceof n?i:new n(function(l){l(i)})}return new(n||(n=Promise))(function(i,l){function o(u){try{d(r.next(u))}catch(h){l(h)}}function c(u){try{d(r.throw(u))}catch(h){l(h)}}function d(u){u.done?i(u.value):a(u.value).then(o,c)}d((r=r.apply(s,t||[])).next())})};const bds=s=>{let t;return s?t=s:typeof fetch>"u"?t=e4t:t=fetch,(...n)=>t(...n)},_ds=()=>typeof Headers>"u"?t4t:Headers,wds=(s,t,n)=>{const r=bds(n),a=_ds();return(i,l)=>vds(void 0,void 0,void 0,function*(){var o;const c=(o=yield t())!==null&&o!==void 0?o:s;let d=new a(l==null?void 0:l.headers);return d.has("apikey")||d.set("apikey",s),d.has("Authorization")||d.set("Authorization",`Bearer ${c}`),r(i,Object.assign(Object.assign({},l),{headers:d}))})};var jds=function(s,t,n,r){function a(i){return i instanceof n?i:new n(function(l){l(i)})}return new(n||(n=Promise))(function(i,l){function o(u){try{d(r.next(u))}catch(h){l(h)}}function c(u){try{d(r.throw(u))}catch(h){l(h)}}function d(u){u.done?i(u.value):a(u.value).then(o,c)}d((r=r.apply(s,t||[])).next())})};function Nds(s){return s.endsWith("/")?s:s+"/"}function kds(s,t){var n,r;const{db:a,auth:i,realtime:l,global:o}=s,{db:c,auth:d,realtime:u,global:h}=t,m={db:Object.assign(Object.assign({},c),a),auth:Object.assign(Object.assign({},d),i),realtime:Object.assign(Object.assign({},u),l),global:Object.assign(Object.assign(Object.assign({},h),o),{headers:Object.assign(Object.assign({},(n=h==null?void 0:h.headers)!==null&&n!==void 0?n:{}),(r=o==null?void 0:o.headers)!==null&&r!==void 0?r:{})}),accessToken:()=>jds(this,void 0,void 0,function*(){return""})};return s.accessToken?m.accessToken=s.accessToken:delete m.accessToken,m}const x4t="2.69.1",T9=30*1e3,YFe=3,iIe=YFe*T9,Sds="http://localhost:9999",Cds="supabase.auth.token",Ads={"X-Client-Info":`gotrue-js/${x4t}`},ZFe="X-Supabase-Api-Version",y4t={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},Eds=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,Tds=6e5;class vHe extends Error{constructor(t,n,r){super(t),this.__isAuthError=!0,this.name="AuthError",this.status=n,this.code=r}}function Wc(s){return typeof s=="object"&&s!==null&&"__isAuthError"in s}class Mds extends vHe{constructor(t,n,r){super(t,n,r),this.name="AuthApiError",this.status=n,this.code=r}}function Pds(s){return Wc(s)&&s.name==="AuthApiError"}class v4t extends vHe{constructor(t,n){super(t),this.name="AuthUnknownError",this.originalError=n}}class KM extends vHe{constructor(t,n,r,a){super(t,r,a),this.name=n,this.status=r}}class eE extends KM{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}function Ids(s){return Wc(s)&&s.name==="AuthSessionMissingError"}class oIe extends KM{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}}class Une extends KM{constructor(t){super(t,"AuthInvalidCredentialsError",400,void 0)}}class qne extends KM{constructor(t,n=null){super(t,"AuthImplicitGrantRedirectError",500,void 0),this.details=null,this.details=n}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}function Lds(s){return Wc(s)&&s.name==="AuthImplicitGrantRedirectError"}class Fit extends KM{constructor(t,n=null){super(t,"AuthPKCEGrantCodeExchangeError",500,void 0),this.details=null,this.details=n}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}class XFe extends KM{constructor(t,n){super(t,"AuthRetryableFetchError",n,void 0)}}function lIe(s){return Wc(s)&&s.name==="AuthRetryableFetchError"}class zit extends KM{constructor(t,n,r){super(t,"AuthWeakPasswordError",n,"weak_password"),this.reasons=r}}class mY extends KM{constructor(t){super(t,"AuthInvalidJwtError",400,"invalid_jwt")}}const Bit="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),$it=` \r=`.split(""),Rds=(()=>{const s=new Array(128);for(let t=0;t-1)for(t.queue=t.queue<<6|r,t.queuedBits+=6;t.queuedBits>=8;)n(t.queue>>t.queuedBits-8&255),t.queuedBits-=8;else{if(r===-2)return;throw new Error(`Invalid Base64-URL character "${String.fromCharCode(s)}"`)}}function Uit(s){const t=[],n=l=>{t.push(String.fromCodePoint(l))},r={utf8seq:0,codepoint:0},a={queue:0,queuedBits:0},i=l=>{Fds(l,r,n)};for(let l=0;l>6),t(128|s&63);return}else if(s<=65535){t(224|s>>12),t(128|s>>6&63),t(128|s&63);return}else if(s<=1114111){t(240|s>>18),t(128|s>>12&63),t(128|s>>6&63),t(128|s&63);return}throw new Error(`Unrecognized Unicode codepoint: ${s.toString(16)}`)}function Ods(s,t){for(let n=0;n55295&&r<=56319){const a=(r-55296)*1024&65535;r=(s.charCodeAt(n+1)-56320&65535|a)+65536,n+=1}Dds(r,t)}}function Fds(s,t,n){if(t.utf8seq===0){if(s<=127){n(s);return}for(let r=1;r<6;r+=1)if(!(s>>7-r&1)){t.utf8seq=r;break}if(t.utf8seq===2)t.codepoint=s&31;else if(t.utf8seq===3)t.codepoint=s&15;else if(t.utf8seq===4)t.codepoint=s&7;else throw new Error("Invalid UTF-8 sequence");t.utf8seq-=1}else if(t.utf8seq>0){if(s<=127)throw new Error("Invalid UTF-8 sequence");t.codepoint=t.codepoint<<6|s&63,t.utf8seq-=1,t.utf8seq===0&&n(t.codepoint)}}function zds(s){const t=[],n={queue:0,queuedBits:0},r=a=>{t.push(a)};for(let a=0;at.push(n)),new Uint8Array(t)}function $ds(s){return Math.round(Date.now()/1e3)+s}function Uds(){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 bS=()=>typeof window<"u"&&typeof document<"u",nP={tested:!1,writable:!1},fY=()=>{if(!bS())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(nP.tested)return nP.writable;const s=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(s,s),globalThis.localStorage.removeItem(s),nP.tested=!0,nP.writable=!0}catch{nP.tested=!0,nP.writable=!1}return nP.writable};function qds(s){const t={},n=new URL(s);if(n.hash&&n.hash[0]==="#")try{new URLSearchParams(n.hash.substring(1)).forEach((a,i)=>{t[i]=a})}catch{}return n.searchParams.forEach((r,a)=>{t[a]=r}),t}const _4t=s=>{let t;return s?t=s:typeof fetch>"u"?t=(...n)=>Ai(async()=>{const{default:r}=await Promise.resolve().then(()=>Bq);return{default:r}},void 0).then(({default:r})=>r(...n)):t=fetch,(...n)=>t(...n)},Vds=s=>typeof s=="object"&&s!==null&&"status"in s&&"ok"in s&&"json"in s&&typeof s.json=="function",w4t=async(s,t,n)=>{await s.setItem(t,JSON.stringify(n))},Vne=async(s,t)=>{const n=await s.getItem(t);if(!n)return null;try{return JSON.parse(n)}catch{return n}},Hne=async(s,t)=>{await s.removeItem(t)};class S3e{constructor(){this.promise=new S3e.promiseConstructor((t,n)=>{this.resolve=t,this.reject=n})}}S3e.promiseConstructor=Promise;function cIe(s){const t=s.split(".");if(t.length!==3)throw new mY("Invalid JWT structure");for(let r=0;r{setTimeout(()=>t(null),s)})}function Gds(s,t){return new Promise((r,a)=>{(async()=>{for(let i=0;i<1/0;i++)try{const l=await s(i);if(!t(i,null,l)){r(l);return}}catch(l){if(!t(i,l)){a(l);return}}})()})}function Wds(s){return("0"+s.toString(16)).substr(-2)}function Kds(){const t=new Uint32Array(56);if(typeof crypto>"u"){const n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",r=n.length;let a="";for(let i=0;i<56;i++)a+=n.charAt(Math.floor(Math.random()*r));return a}return crypto.getRandomValues(t),Array.from(t,Wds).join("")}async function Yds(s){const n=new TextEncoder().encode(s),r=await crypto.subtle.digest("SHA-256",n),a=new Uint8Array(r);return Array.from(a).map(i=>String.fromCharCode(i)).join("")}async function Zds(s){if(!(typeof crypto<"u"&&typeof crypto.subtle<"u"&&typeof TextEncoder<"u"))return console.warn("WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256."),s;const n=await Yds(s);return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function z7(s,t,n=!1){const r=Kds();let a=r;n&&(a+="/PASSWORD_RECOVERY"),await w4t(s,`${t}-code-verifier`,a);const i=await Zds(r);return[i,r===i?"plain":"s256"]}const Xds=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function Qds(s){const t=s.headers.get(ZFe);if(!t||!t.match(Xds))return null;try{return new Date(`${t}T00:00:00.0Z`)}catch{return null}}function Jds(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 eus(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 tus=function(s,t){var n={};for(var r in s)Object.prototype.hasOwnProperty.call(s,r)&&t.indexOf(r)<0&&(n[r]=s[r]);if(s!=null&&typeof Object.getOwnPropertySymbols=="function")for(var a=0,r=Object.getOwnPropertySymbols(s);as.msg||s.message||s.error_description||s.error||JSON.stringify(s),sus=[502,503,504];async function qit(s){var t;if(!Vds(s))throw new XFe(AR(s),0);if(sus.includes(s.status))throw new XFe(AR(s),s.status);let n;try{n=await s.json()}catch(i){throw new v4t(AR(i),i)}let r;const a=Qds(s);if(a&&a.getTime()>=y4t["2024-01-01"].timestamp&&typeof n=="object"&&n&&typeof n.code=="string"?r=n.code:typeof n=="object"&&n&&typeof n.error_code=="string"&&(r=n.error_code),r){if(r==="weak_password")throw new zit(AR(n),s.status,((t=n.weak_password)===null||t===void 0?void 0:t.reasons)||[]);if(r==="session_not_found")throw new eE}else if(typeof n=="object"&&n&&typeof n.weak_password=="object"&&n.weak_password&&Array.isArray(n.weak_password.reasons)&&n.weak_password.reasons.length&&n.weak_password.reasons.reduce((i,l)=>i&&typeof l=="string",!0))throw new zit(AR(n),s.status,n.weak_password.reasons);throw new Mds(AR(n),s.status||500,r)}const nus=(s,t,n,r)=>{const a={method:s,headers:(t==null?void 0:t.headers)||{}};return s==="GET"?a:(a.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},t==null?void 0:t.headers),a.body=JSON.stringify(r),Object.assign(Object.assign({},a),n))};async function Hd(s,t,n,r){var a;const i=Object.assign({},r==null?void 0:r.headers);i[ZFe]||(i[ZFe]=y4t["2024-01-01"].name),r!=null&&r.jwt&&(i.Authorization=`Bearer ${r.jwt}`);const l=(a=r==null?void 0:r.query)!==null&&a!==void 0?a:{};r!=null&&r.redirectTo&&(l.redirect_to=r.redirectTo);const o=Object.keys(l).length?"?"+new URLSearchParams(l).toString():"",c=await rus(s,t,n+o,{headers:i,noResolveJson:r==null?void 0:r.noResolveJson},{},r==null?void 0:r.body);return r!=null&&r.xform?r==null?void 0:r.xform(c):{data:Object.assign({},c),error:null}}async function rus(s,t,n,r,a,i){const l=nus(t,r,a,i);let o;try{o=await s(n,Object.assign({},l))}catch(c){throw console.error(c),new XFe(AR(c),0)}if(o.ok||await qit(o),r!=null&&r.noResolveJson)return o;try{return await o.json()}catch(c){await qit(c)}}function tE(s){var t;let n=null;lus(s)&&(n=Object.assign({},s),s.expires_at||(n.expires_at=$ds(s.expires_in)));const r=(t=s.user)!==null&&t!==void 0?t:s;return{data:{session:n,user:r},error:null}}function Vit(s){const t=tE(s);return!t.error&&s.weak_password&&typeof s.weak_password=="object"&&Array.isArray(s.weak_password.reasons)&&s.weak_password.reasons.length&&s.weak_password.message&&typeof s.weak_password.message=="string"&&s.weak_password.reasons.reduce((n,r)=>n&&typeof r=="string",!0)&&(t.data.weak_password=s.weak_password),t}function AE(s){var t;return{data:{user:(t=s.user)!==null&&t!==void 0?t:s},error:null}}function aus(s){return{data:s,error:null}}function ius(s){const{action_link:t,email_otp:n,hashed_token:r,redirect_to:a,verification_type:i}=s,l=tus(s,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),o={action_link:t,email_otp:n,hashed_token:r,redirect_to:a,verification_type:i},c=Object.assign({},l);return{data:{properties:o,user:c},error:null}}function ous(s){return s}function lus(s){return s.access_token&&s.refresh_token&&s.expires_in}var cus=function(s,t){var n={};for(var r in s)Object.prototype.hasOwnProperty.call(s,r)&&t.indexOf(r)<0&&(n[r]=s[r]);if(s!=null&&typeof Object.getOwnPropertySymbols=="function")for(var a=0,r=Object.getOwnPropertySymbols(s);a0&&(p.forEach(g=>{const x=parseInt(g.split(";")[0].split("=")[1].substring(0,1)),y=JSON.parse(g.split(";")[1].split("=")[1]);d[`${y}Page`]=x}),d.total=parseInt(m)),{data:Object.assign(Object.assign({},h),d),error:null}}catch(d){if(Wc(d))return{data:{users:[]},error:d};throw d}}async getUserById(t){try{return await Hd(this.fetch,"GET",`${this.url}/admin/users/${t}`,{headers:this.headers,xform:AE})}catch(n){if(Wc(n))return{data:{user:null},error:n};throw n}}async updateUserById(t,n){try{return await Hd(this.fetch,"PUT",`${this.url}/admin/users/${t}`,{body:n,headers:this.headers,xform:AE})}catch(r){if(Wc(r))return{data:{user:null},error:r};throw r}}async deleteUser(t,n=!1){try{return await Hd(this.fetch,"DELETE",`${this.url}/admin/users/${t}`,{headers:this.headers,body:{should_soft_delete:n},xform:AE})}catch(r){if(Wc(r))return{data:{user:null},error:r};throw r}}async _listFactors(t){try{const{data:n,error:r}=await Hd(this.fetch,"GET",`${this.url}/admin/users/${t.userId}/factors`,{headers:this.headers,xform:a=>({data:{factors:a},error:null})});return{data:n,error:r}}catch(n){if(Wc(n))return{data:null,error:n};throw n}}async _deleteFactor(t){try{return{data:await Hd(this.fetch,"DELETE",`${this.url}/admin/users/${t.userId}/factors/${t.id}`,{headers:this.headers}),error:null}}catch(n){if(Wc(n))return{data:null,error:n};throw n}}}const uus={getItem:s=>fY()?globalThis.localStorage.getItem(s):null,setItem:(s,t)=>{fY()&&globalThis.localStorage.setItem(s,t)},removeItem:s=>{fY()&&globalThis.localStorage.removeItem(s)}};function Hit(s={}){return{getItem:t=>s[t]||null,setItem:(t,n)=>{s[t]=n},removeItem:t=>{delete s[t]}}}function hus(){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 B7={debug:!!(globalThis&&fY()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")};class j4t extends Error{constructor(t){super(t),this.isAcquireTimeout=!0}}class mus extends j4t{}async function fus(s,t,n){B7.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",s,t);const r=new globalThis.AbortController;return t>0&&setTimeout(()=>{r.abort(),B7.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",s)},t),await Promise.resolve().then(()=>globalThis.navigator.locks.request(s,t===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:r.signal},async a=>{if(a){B7.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",s,a.name);try{return await n()}finally{B7.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",s,a.name)}}else{if(t===0)throw B7.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",s),new mus(`Acquiring an exclusive Navigator LockManager lock "${s}" immediately failed`);if(B7.debug)try{const i=await globalThis.navigator.locks.query();console.log("@supabase/gotrue-js: Navigator LockManager state",JSON.stringify(i,null," "))}catch(i){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",i)}return console.warn("@supabase/gotrue-js: Navigator LockManager returned a null lock when using #request without ifAvailable set to true, it appears this browser is not following the LockManager spec https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request"),await n()}}))}hus();const pus={url:Sds,storageKey:Cds,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:Ads,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1};async function Git(s,t,n){return await n()}class UZ{constructor(t){var n,r;this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.initializePromise=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log,this.instanceID=UZ.nextInstanceID,UZ.nextInstanceID+=1,this.instanceID>0&&bS()&&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({},pus),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 dus({url:a.url,headers:a.headers,fetch:a.fetch}),this.url=a.url,this.headers=a.headers,this.fetch=_4t(a.fetch),this.lock=a.lock||Git,this.detectSessionInUrl=a.detectSessionInUrl,this.flowType=a.flowType,this.hasCustomAuthorizationHeader=a.hasCustomAuthorizationHeader,a.lock?this.lock=a.lock:bS()&&(!((n=globalThis==null?void 0:globalThis.navigator)===null||n===void 0)&&n.locks)?this.lock=fus:this.lock=Git,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:fY()?this.storage=uus:(this.memoryStorage={},this.storage=Hit(this.memoryStorage)):(this.memoryStorage={},this.storage=Hit(this.memoryStorage)),bS()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(i){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",i)}(r=this.broadcastChannel)===null||r===void 0||r.addEventListener("message",async i=>{this._debug("received broadcast notification from other tab or client",i),await this._notifyAllSubscribers(i.data.event,i.data.session,!1)})}this.initialize()}_debug(...t){return this.logDebugMessages&&this.logger(`GoTrueClient@${this.instanceID} (${x4t}) ${new Date().toISOString()}`,...t),this}async initialize(){return this.initializePromise?await this.initializePromise:(this.initializePromise=(async()=>await this._acquireLock(-1,async()=>await this._initialize()))(),await this.initializePromise)}async _initialize(){var t;try{const n=qds(window.location.href);let r="none";if(this._isImplicitGrantCallback(n)?r="implicit":await this._isPKCECallback(n)&&(r="pkce"),bS()&&this.detectSessionInUrl&&r!=="none"){const{data:a,error:i}=await this._getSessionFromURL(n,r);if(i){if(this._debug("#_initialize()","error detecting session from URL",i),Lds(i)){const c=(t=i.details)===null||t===void 0?void 0:t.code;if(c==="identity_already_exists"||c==="identity_not_found"||c==="single_identity_not_deletable")return{error:i}}return await this._removeSession(),{error:i}}const{session:l,redirectType:o}=a;return this._debug("#_initialize()","detected session in URL",l,"redirect type",o),await this._saveSession(l),setTimeout(async()=>{o==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",l):await this._notifyAllSubscribers("SIGNED_IN",l)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(n){return Wc(n)?{error:n}:{error:new v4t("Unexpected error during initialization",n)}}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(t){var n,r,a;try{const i=await Hd(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(r=(n=t==null?void 0:t.options)===null||n===void 0?void 0:n.data)!==null&&r!==void 0?r:{},gotrue_meta_security:{captcha_token:(a=t==null?void 0:t.options)===null||a===void 0?void 0:a.captchaToken}},xform:tE}),{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(Wc(i))return{data:{user:null,session:null},error:i};throw i}}async signUp(t){var n,r,a;try{let i;if("email"in t){const{email:u,password:h,options:m}=t;let p=null,g=null;this.flowType==="pkce"&&([p,g]=await z7(this.storage,this.storageKey)),i=await Hd(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:m==null?void 0:m.emailRedirectTo,body:{email:u,password:h,data:(n=m==null?void 0:m.data)!==null&&n!==void 0?n:{},gotrue_meta_security:{captcha_token:m==null?void 0:m.captchaToken},code_challenge:p,code_challenge_method:g},xform:tE})}else if("phone"in t){const{phone:u,password:h,options:m}=t;i=await Hd(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:u,password:h,data:(r=m==null?void 0:m.data)!==null&&r!==void 0?r:{},channel:(a=m==null?void 0:m.channel)!==null&&a!==void 0?a:"sms",gotrue_meta_security:{captcha_token:m==null?void 0:m.captchaToken}},xform:tE})}else throw new Une("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(Wc(i))return{data:{user:null,session:null},error:i};throw i}}async signInWithPassword(t){try{let n;if("email"in t){const{email:i,password:l,options:o}=t;n=await Hd(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:Vit})}else if("phone"in t){const{phone:i,password:l,options:o}=t;n=await Hd(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:Vit})}else throw new Une("You must provide either an email or phone number and a password");const{data:r,error:a}=n;return a?{data:{user:null,session:null},error:a}:!r||!r.session||!r.user?{data:{user:null,session:null},error:new oIe}:(r.session&&(await this._saveSession(r.session),await this._notifyAllSubscribers("SIGNED_IN",r.session)),{data:Object.assign({user:r.user,session:r.session},r.weak_password?{weakPassword:r.weak_password}:null),error:a})}catch(n){if(Wc(n))return{data:{user:null,session:null},error:n};throw n}}async signInWithOAuth(t){var n,r,a,i;return await this._handleProviderSignIn(t.provider,{redirectTo:(n=t.options)===null||n===void 0?void 0:n.redirectTo,scopes:(r=t.options)===null||r===void 0?void 0:r.scopes,queryParams:(a=t.options)===null||a===void 0?void 0:a.queryParams,skipBrowserRedirect:(i=t.options)===null||i===void 0?void 0:i.skipBrowserRedirect})}async exchangeCodeForSession(t){return await this.initializePromise,this._acquireLock(-1,async()=>this._exchangeCodeForSession(t))}async _exchangeCodeForSession(t){const n=await Vne(this.storage,`${this.storageKey}-code-verifier`),[r,a]=(n??"").split("/");try{const{data:i,error:l}=await Hd(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:t,code_verifier:r},xform:tE});if(await Hne(this.storage,`${this.storageKey}-code-verifier`),l)throw l;return!i||!i.session||!i.user?{data:{user:null,session:null,redirectType:null},error:new oIe}:(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(Wc(i))return{data:{user:null,session:null,redirectType:null},error:i};throw i}}async signInWithIdToken(t){try{const{options:n,provider:r,token:a,access_token:i,nonce:l}=t,o=await Hd(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:r,id_token:a,access_token:i,nonce:l,gotrue_meta_security:{captcha_token:n==null?void 0:n.captchaToken}},xform:tE}),{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 oIe}:(c.session&&(await this._saveSession(c.session),await this._notifyAllSubscribers("SIGNED_IN",c.session)),{data:c,error:d})}catch(n){if(Wc(n))return{data:{user:null,session:null},error:n};throw n}}async signInWithOtp(t){var n,r,a,i,l;try{if("email"in t){const{email:o,options:c}=t;let d=null,u=null;this.flowType==="pkce"&&([d,u]=await z7(this.storage,this.storageKey));const{error:h}=await Hd(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:o,data:(n=c==null?void 0:c.data)!==null&&n!==void 0?n:{},create_user:(r=c==null?void 0:c.shouldCreateUser)!==null&&r!==void 0?r:!0,gotrue_meta_security:{captcha_token:c==null?void 0:c.captchaToken},code_challenge:d,code_challenge_method:u},redirectTo:c==null?void 0:c.emailRedirectTo});return{data:{user:null,session:null},error:h}}if("phone"in t){const{phone:o,options:c}=t,{data:d,error:u}=await Hd(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:o,data:(a=c==null?void 0:c.data)!==null&&a!==void 0?a:{},create_user:(i=c==null?void 0:c.shouldCreateUser)!==null&&i!==void 0?i:!0,gotrue_meta_security:{captcha_token:c==null?void 0:c.captchaToken},channel:(l=c==null?void 0:c.channel)!==null&&l!==void 0?l:"sms"}});return{data:{user:null,session:null,messageId:d==null?void 0:d.message_id},error:u}}throw new Une("You must provide either an email or phone number.")}catch(o){if(Wc(o))return{data:{user:null,session:null},error:o};throw o}}async verifyOtp(t){var n,r;try{let a,i;"options"in t&&(a=(n=t.options)===null||n===void 0?void 0:n.redirectTo,i=(r=t.options)===null||r===void 0?void 0:r.captchaToken);const{data:l,error:o}=await Hd(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},t),{gotrue_meta_security:{captcha_token:i}}),redirectTo:a,xform:tE});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(Wc(a))return{data:{user:null,session:null},error:a};throw a}}async signInWithSSO(t){var n,r,a;try{let i=null,l=null;return this.flowType==="pkce"&&([i,l]=await z7(this.storage,this.storageKey)),await Hd(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in t?{provider_id:t.providerId}:null),"domain"in t?{domain:t.domain}:null),{redirect_to:(r=(n=t.options)===null||n===void 0?void 0:n.redirectTo)!==null&&r!==void 0?r:void 0}),!((a=t==null?void 0:t.options)===null||a===void 0)&&a.captchaToken?{gotrue_meta_security:{captcha_token:t.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:i,code_challenge_method:l}),headers:this.headers,xform:aus})}catch(i){if(Wc(i))return{data:null,error:i};throw i}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async t=>{const{data:{session:n},error:r}=t;if(r)throw r;if(!n)throw new eE;const{error:a}=await Hd(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:n.access_token});return{data:{user:null,session:null},error:a}})}catch(t){if(Wc(t))return{data:{user:null,session:null},error:t};throw t}}async resend(t){try{const n=`${this.url}/resend`;if("email"in t){const{email:r,type:a,options:i}=t,{error:l}=await Hd(this.fetch,"POST",n,{headers:this.headers,body:{email:r,type:a,gotrue_meta_security:{captcha_token:i==null?void 0:i.captchaToken}},redirectTo:i==null?void 0:i.emailRedirectTo});return{data:{user:null,session:null},error:l}}else if("phone"in t){const{phone:r,type:a,options:i}=t,{data:l,error:o}=await Hd(this.fetch,"POST",n,{headers:this.headers,body:{phone:r,type:a,gotrue_meta_security:{captcha_token:i==null?void 0:i.captchaToken}}});return{data:{user:null,session:null,messageId:l==null?void 0:l.message_id},error:o}}throw new Une("You must provide either an email or phone number and a type")}catch(n){if(Wc(n))return{data:{user:null,session:null},error:n};throw n}}async getSession(){return await this.initializePromise,await this._acquireLock(-1,async()=>this._useSession(async n=>n))}async _acquireLock(t,n){this._debug("#_acquireLock","begin",t);try{if(this.lockAcquired){const r=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),a=(async()=>(await r,await n()))();return this.pendingInLock.push((async()=>{try{await a}catch{}})()),a}return await this.lock(`lock:${this.storageKey}`,t,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;const r=n();for(this.pendingInLock.push((async()=>{try{await r}catch{}})()),await r;this.pendingInLock.length;){const a=[...this.pendingInLock];await Promise.all(a),this.pendingInLock.splice(0,a.length)}return await r}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(t){this._debug("#_useSession","begin");try{const n=await this.__loadSession();return await t(n)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let t=null;const n=await Vne(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",n),n!==null&&(this._isValidSession(n)?t=n:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!t)return{data:{session:null},error:null};const r=t.expires_at?t.expires_at*1e3-Date.now()(!l&&d==="user"&&(console.warn("Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and may not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server."),l=!0,this.suppressGetSessionWarning=!0),Reflect.get(c,d,u))})}return{data:{session:t},error:null}}const{session:a,error:i}=await this._callRefreshToken(t.refresh_token);return i?{data:{session:null},error:i}:{data:{session:a},error:null}}finally{this._debug("#__loadSession()","end")}}async getUser(t){return t?await this._getUser(t):(await this.initializePromise,await this._acquireLock(-1,async()=>await this._getUser()))}async _getUser(t){try{return t?await Hd(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:t,xform:AE}):await this._useSession(async n=>{var r,a,i;const{data:l,error:o}=n;if(o)throw o;return!(!((r=l.session)===null||r===void 0)&&r.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new eE}:await Hd(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:AE})})}catch(n){if(Wc(n))return Ids(n)&&(await this._removeSession(),await Hne(this.storage,`${this.storageKey}-code-verifier`)),{data:{user:null},error:n};throw n}}async updateUser(t,n={}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._updateUser(t,n))}async _updateUser(t,n={}){try{return await this._useSession(async r=>{const{data:a,error:i}=r;if(i)throw i;if(!a.session)throw new eE;const l=a.session;let o=null,c=null;this.flowType==="pkce"&&t.email!=null&&([o,c]=await z7(this.storage,this.storageKey));const{data:d,error:u}=await Hd(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:n==null?void 0:n.emailRedirectTo,body:Object.assign(Object.assign({},t),{code_challenge:o,code_challenge_method:c}),jwt:l.access_token,xform:AE});if(u)throw u;return l.user=d.user,await this._saveSession(l),await this._notifyAllSubscribers("USER_UPDATED",l),{data:{user:l.user},error:null}})}catch(r){if(Wc(r))return{data:{user:null},error:r};throw r}}async setSession(t){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._setSession(t))}async _setSession(t){try{if(!t.access_token||!t.refresh_token)throw new eE;const n=Date.now()/1e3;let r=n,a=!0,i=null;const{payload:l}=cIe(t.access_token);if(l.exp&&(r=l.exp,a=r<=n),a){const{session:o,error:c}=await this._callRefreshToken(t.refresh_token);if(c)return{data:{user:null,session:null},error:c};if(!o)return{data:{user:null,session:null},error:null};i=o}else{const{data:o,error:c}=await this._getUser(t.access_token);if(c)throw c;i={access_token:t.access_token,refresh_token:t.refresh_token,user:o.user,token_type:"bearer",expires_in:r-n,expires_at:r},await this._saveSession(i),await this._notifyAllSubscribers("SIGNED_IN",i)}return{data:{user:i.user,session:i},error:null}}catch(n){if(Wc(n))return{data:{session:null,user:null},error:n};throw n}}async refreshSession(t){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._refreshSession(t))}async _refreshSession(t){try{return await this._useSession(async n=>{var r;if(!t){const{data:l,error:o}=n;if(o)throw o;t=(r=l.session)!==null&&r!==void 0?r:void 0}if(!(t!=null&&t.refresh_token))throw new eE;const{session:a,error:i}=await this._callRefreshToken(t.refresh_token);return i?{data:{user:null,session:null},error:i}:a?{data:{user:a.user,session:a},error:null}:{data:{user:null,session:null},error:null}})}catch(n){if(Wc(n))return{data:{user:null,session:null},error:n};throw n}}async _getSessionFromURL(t,n){try{if(!bS())throw new qne("No browser detected.");if(t.error||t.error_description||t.error_code)throw new qne(t.error_description||"Error in URL with unspecified error_description",{error:t.error||"unspecified_error",code:t.error_code||"unspecified_code"});switch(n){case"implicit":if(this.flowType==="pkce")throw new Fit("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new qne("Not a valid implicit grant flow url.");break;default:}if(n==="pkce"){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!t.code)throw new Fit("No code detected.");const{data:_,error:j}=await this._exchangeCodeForSession(t.code);if(j)throw j;const C=new URL(window.location.href);return C.searchParams.delete("code"),window.history.replaceState(window.history.state,"",C.toString()),{data:{session:_.session,redirectType:null},error:null}}const{provider_token:r,provider_refresh_token:a,access_token:i,refresh_token:l,expires_in:o,expires_at:c,token_type:d}=t;if(!i||!o||!l||!d)throw new qne("No session defined in URL");const u=Math.round(Date.now()/1e3),h=parseInt(o);let m=u+h;c&&(m=parseInt(c));const p=m-u;p*1e3<=T9&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${p}s, should have been closer to ${h}s`);const g=m-h;u-g>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",g,m,u):u-g<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",g,m,u);const{data:x,error:y}=await this._getUser(i);if(y)throw y;const v={provider_token:r,provider_refresh_token:a,access_token:i,expires_in:h,expires_at:m,refresh_token:l,token_type:d,user:x.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),{data:{session:v,redirectType:t.type},error:null}}catch(r){if(Wc(r))return{data:{session:null,redirectType:null},error:r};throw r}}_isImplicitGrantCallback(t){return!!(t.access_token||t.error_description)}async _isPKCECallback(t){const n=await Vne(this.storage,`${this.storageKey}-code-verifier`);return!!(t.code&&n)}async signOut(t={scope:"global"}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._signOut(t))}async _signOut({scope:t}={scope:"global"}){return await this._useSession(async n=>{var r;const{data:a,error:i}=n;if(i)return{error:i};const l=(r=a.session)===null||r===void 0?void 0:r.access_token;if(l){const{error:o}=await this.admin.signOut(l,t);if(o&&!(Pds(o)&&(o.status===404||o.status===401||o.status===403)))return{error:o}}return t!=="others"&&(await this._removeSession(),await Hne(this.storage,`${this.storageKey}-code-verifier`)),{error:null}})}onAuthStateChange(t){const n=Uds(),r={id:n,callback:t,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",n),this.stateChangeEmitters.delete(n)}};return this._debug("#onAuthStateChange()","registered callback with id",n),this.stateChangeEmitters.set(n,r),(async()=>(await this.initializePromise,await this._acquireLock(-1,async()=>{this._emitInitialSession(n)})))(),{data:{subscription:r}}}async _emitInitialSession(t){return await this._useSession(async n=>{var r,a;try{const{data:{session:i},error:l}=n;if(l)throw l;await((r=this.stateChangeEmitters.get(t))===null||r===void 0?void 0:r.callback("INITIAL_SESSION",i)),this._debug("INITIAL_SESSION","callback id",t,"session",i)}catch(i){await((a=this.stateChangeEmitters.get(t))===null||a===void 0?void 0:a.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",t,"error",i),console.error(i)}})}async resetPasswordForEmail(t,n={}){let r=null,a=null;this.flowType==="pkce"&&([r,a]=await z7(this.storage,this.storageKey,!0));try{return await Hd(this.fetch,"POST",`${this.url}/recover`,{body:{email:t,code_challenge:r,code_challenge_method:a,gotrue_meta_security:{captcha_token:n.captchaToken}},headers:this.headers,redirectTo:n.redirectTo})}catch(i){if(Wc(i))return{data:null,error:i};throw i}}async getUserIdentities(){var t;try{const{data:n,error:r}=await this.getUser();if(r)throw r;return{data:{identities:(t=n.user.identities)!==null&&t!==void 0?t:[]},error:null}}catch(n){if(Wc(n))return{data:null,error:n};throw n}}async linkIdentity(t){var n;try{const{data:r,error:a}=await this._useSession(async i=>{var l,o,c,d,u;const{data:h,error:m}=i;if(m)throw m;const p=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 Hd(this.fetch,"GET",p,{headers:this.headers,jwt:(u=(d=h.session)===null||d===void 0?void 0:d.access_token)!==null&&u!==void 0?u:void 0})});if(a)throw a;return bS()&&!(!((n=t.options)===null||n===void 0)&&n.skipBrowserRedirect)&&window.location.assign(r==null?void 0:r.url),{data:{provider:t.provider,url:r==null?void 0:r.url},error:null}}catch(r){if(Wc(r))return{data:{provider:t.provider,url:null},error:r};throw r}}async unlinkIdentity(t){try{return await this._useSession(async n=>{var r,a;const{data:i,error:l}=n;if(l)throw l;return await Hd(this.fetch,"DELETE",`${this.url}/user/identities/${t.identity_id}`,{headers:this.headers,jwt:(a=(r=i.session)===null||r===void 0?void 0:r.access_token)!==null&&a!==void 0?a:void 0})})}catch(n){if(Wc(n))return{data:null,error:n};throw n}}async _refreshAccessToken(t){const n=`#_refreshAccessToken(${t.substring(0,5)}...)`;this._debug(n,"begin");try{const r=Date.now();return await Gds(async a=>(a>0&&await Hds(200*Math.pow(2,a-1)),this._debug(n,"refreshing attempt",a),await Hd(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:t},headers:this.headers,xform:tE})),(a,i)=>{const l=200*Math.pow(2,a);return i&&lIe(i)&&Date.now()+l-r{try{await o.callback(t,n)}catch(c){i.push(c)}});if(await Promise.all(l),i.length>0){for(let o=0;othis._autoRefreshTokenTick(),T9);this.autoRefreshTicker=t,t&&typeof t=="object"&&typeof t.unref=="function"?t.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(t),setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");const t=this.autoRefreshTicker;this.autoRefreshTicker=null,t&&clearInterval(t)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async _autoRefreshTokenTick(){this._debug("#_autoRefreshTokenTick()","begin");try{await this._acquireLock(0,async()=>{try{const t=Date.now();try{return await this._useSession(async n=>{const{data:{session:r}}=n;if(!r||!r.refresh_token||!r.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}const a=Math.floor((r.expires_at*1e3-t)/T9);this._debug("#_autoRefreshTokenTick()",`access token expires in ${a} ticks, a tick lasts ${T9}ms, refresh threshold is ${YFe} ticks`),a<=YFe&&await this._callRefreshToken(r.refresh_token)})}catch(n){console.error("Auto refresh tick failed with error. This is likely a transient error.",n)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(t){if(t.isAcquireTimeout||t instanceof j4t)this._debug("auto refresh token tick lock not available");else throw t}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!bS()||!(window!=null&&window.addEventListener))return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>await this._onVisibilityChanged(!1),window==null||window.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(t){console.error("_handleVisibilityChange",t)}}async _onVisibilityChanged(t){const n=`#_onVisibilityChanged(${t})`;this._debug(n,"visibilityState",document.visibilityState),document.visibilityState==="visible"?(this.autoRefreshToken&&this._startAutoRefresh(),t||(await this.initializePromise,await this._acquireLock(-1,async()=>{if(document.visibilityState!=="visible"){this._debug(n,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()}))):document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(t,n,r){const a=[`provider=${encodeURIComponent(n)}`];if(r!=null&&r.redirectTo&&a.push(`redirect_to=${encodeURIComponent(r.redirectTo)}`),r!=null&&r.scopes&&a.push(`scopes=${encodeURIComponent(r.scopes)}`),this.flowType==="pkce"){const[i,l]=await z7(this.storage,this.storageKey),o=new URLSearchParams({code_challenge:`${encodeURIComponent(i)}`,code_challenge_method:`${encodeURIComponent(l)}`});a.push(o.toString())}if(r!=null&&r.queryParams){const i=new URLSearchParams(r.queryParams);a.push(i.toString())}return r!=null&&r.skipBrowserRedirect&&a.push(`skip_http_redirect=${r.skipBrowserRedirect}`),`${t}?${a.join("&")}`}async _unenroll(t){try{return await this._useSession(async n=>{var r;const{data:a,error:i}=n;return i?{data:null,error:i}:await Hd(this.fetch,"DELETE",`${this.url}/factors/${t.factorId}`,{headers:this.headers,jwt:(r=a==null?void 0:a.session)===null||r===void 0?void 0:r.access_token})})}catch(n){if(Wc(n))return{data:null,error:n};throw n}}async _enroll(t){try{return await this._useSession(async n=>{var r,a;const{data:i,error:l}=n;if(l)return{data:null,error:l};const o=Object.assign({friendly_name:t.friendlyName,factor_type:t.factorType},t.factorType==="phone"?{phone:t.phone}:{issuer:t.issuer}),{data:c,error:d}=await Hd(this.fetch,"POST",`${this.url}/factors`,{body:o,headers:this.headers,jwt:(r=i==null?void 0:i.session)===null||r===void 0?void 0:r.access_token});return d?{data:null,error:d}:(t.factorType==="totp"&&(!((a=c==null?void 0:c.totp)===null||a===void 0)&&a.qr_code)&&(c.totp.qr_code=`data:image/svg+xml;utf-8,${c.totp.qr_code}`),{data:c,error:null})})}catch(n){if(Wc(n))return{data:null,error:n};throw n}}async _verify(t){return this._acquireLock(-1,async()=>{try{return await this._useSession(async n=>{var r;const{data:a,error:i}=n;if(i)return{data:null,error:i};const{data:l,error:o}=await Hd(this.fetch,"POST",`${this.url}/factors/${t.factorId}/verify`,{body:{code:t.code,challenge_id:t.challengeId},headers:this.headers,jwt:(r=a==null?void 0:a.session)===null||r===void 0?void 0:r.access_token});return o?{data:null,error:o}:(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+l.expires_in},l)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",l),{data:l,error:o})})}catch(n){if(Wc(n))return{data:null,error:n};throw n}})}async _challenge(t){return this._acquireLock(-1,async()=>{try{return await this._useSession(async n=>{var r;const{data:a,error:i}=n;return i?{data:null,error:i}:await Hd(this.fetch,"POST",`${this.url}/factors/${t.factorId}/challenge`,{body:{channel:t.channel},headers:this.headers,jwt:(r=a==null?void 0:a.session)===null||r===void 0?void 0:r.access_token})})}catch(n){if(Wc(n))return{data:null,error:n};throw n}})}async _challengeAndVerify(t){const{data:n,error:r}=await this._challenge({factorId:t.factorId});return r?{data:null,error:r}:await this._verify({factorId:t.factorId,challengeId:n.id,code:t.code})}async _listFactors(){const{data:{user:t},error:n}=await this.getUser();if(n)return{data:null,error:n};const r=(t==null?void 0:t.factors)||[],a=r.filter(l=>l.factor_type==="totp"&&l.status==="verified"),i=r.filter(l=>l.factor_type==="phone"&&l.status==="verified");return{data:{all:r,totp:a,phone:i},error:null}}async _getAuthenticatorAssuranceLevel(){return this._acquireLock(-1,async()=>await this._useSession(async t=>{var n,r;const{data:{session:a},error:i}=t;if(i)return{data:null,error:i};if(!a)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};const{payload:l}=cIe(a.access_token);let o=null;l.aal&&(o=l.aal);let c=o;((r=(n=a.user.factors)===null||n===void 0?void 0:n.filter(h=>h.status==="verified"))!==null&&r!==void 0?r:[]).length>0&&(c="aal2");const u=l.amr||[];return{data:{currentLevel:o,nextLevel:c,currentAuthenticationMethods:u},error:null}}))}async fetchJwk(t,n={keys:[]}){let r=n.keys.find(l=>l.kid===t);if(r||(r=this.jwks.keys.find(l=>l.kid===t),r&&this.jwks_cached_at+Tds>Date.now()))return r;const{data:a,error:i}=await Hd(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 mY("JWKS is empty");if(this.jwks=a,this.jwks_cached_at=Date.now(),r=a.keys.find(l=>l.kid===t),!r)throw new mY("No matching signing key found in JWKS");return r}async getClaims(t,n={keys:[]}){try{let r=t;if(!r){const{data:p,error:g}=await this.getSession();if(g||!p.session)return{data:null,error:g};r=p.session.access_token}const{header:a,payload:i,signature:l,raw:{header:o,payload:c}}=cIe(r);if(Jds(i.exp),!a.kid||a.alg==="HS256"||!("crypto"in globalThis&&"subtle"in globalThis.crypto)){const{error:p}=await this.getUser(r);if(p)throw p;return{data:{claims:i,header:a,signature:l},error:null}}const d=eus(a.alg),u=await this.fetchJwk(a.kid,n),h=await crypto.subtle.importKey("jwk",u,d,!0,["verify"]);if(!await crypto.subtle.verify(d,h,l,Bds(`${o}.${c}`)))throw new mY("Invalid JWT signature");return{data:{claims:i,header:a,signature:l},error:null}}catch(r){if(Wc(r))return{data:null,error:r};throw r}}}UZ.nextInstanceID=0;const gus=UZ;class xus extends gus{constructor(t){super(t)}}var yus=function(s,t,n,r){function a(i){return i instanceof n?i:new n(function(l){l(i)})}return new(n||(n=Promise))(function(i,l){function o(u){try{d(r.next(u))}catch(h){l(h)}}function c(u){try{d(r.throw(u))}catch(h){l(h)}}function d(u){u.done?i(u.value):a(u.value).then(o,c)}d((r=r.apply(s,t||[])).next())})};class vus{constructor(t,n,r){var a,i,l;if(this.supabaseUrl=t,this.supabaseKey=n,!t)throw new Error("supabaseUrl is required.");if(!n)throw new Error("supabaseKey is required.");const o=Nds(t),c=new URL(o);this.realtimeUrl=new URL("realtime/v1",c),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace("http","ws"),this.authUrl=new URL("auth/v1",c),this.storageUrl=new URL("storage/v1",c),this.functionsUrl=new URL("functions/v1",c);const d=`sb-${c.hostname.split(".")[0]}-auth-token`,u={db:gds,realtime:yds,auth:Object.assign(Object.assign({},xds),{storageKey:d}),global:pds},h=kds(r??{},u);this.storageKey=(a=h.auth.storageKey)!==null&&a!==void 0?a:"",this.headers=(i=h.global.headers)!==null&&i!==void 0?i:{},h.accessToken?(this.accessToken=h.accessToken,this.auth=new Proxy({},{get:(m,p)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(p)} is not possible`)}})):this.auth=this._initSupabaseAuthClient((l=h.auth)!==null&&l!==void 0?l:{},this.headers,h.global.fetch),this.fetch=wds(n,this._getAccessToken.bind(this),h.global.fetch),this.realtime=this._initRealtimeClient(Object.assign({headers:this.headers,accessToken:this._getAccessToken.bind(this)},h.realtime)),this.rest=new zcs(new URL("rest/v1",c).href,{headers:this.headers,schema:h.db.schema,fetch:this.fetch}),h.accessToken||this._listenForAuthEvents()}get functions(){return new pcs(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}get storage(){return new hds(this.storageUrl.href,this.headers,this.fetch)}from(t){return this.rest.from(t)}schema(t){return this.rest.schema(t)}rpc(t,n={},r={}){return this.rest.rpc(t,n,r)}channel(t,n={config:{}}){return this.realtime.channel(t,n)}getChannels(){return this.realtime.getChannels()}removeChannel(t){return this.realtime.removeChannel(t)}removeAllChannels(){return this.realtime.removeAllChannels()}_getAccessToken(){var t,n;return yus(this,void 0,void 0,function*(){if(this.accessToken)return yield this.accessToken();const{data:r}=yield this.auth.getSession();return(n=(t=r.session)===null||t===void 0?void 0:t.access_token)!==null&&n!==void 0?n:null})}_initSupabaseAuthClient({autoRefreshToken:t,persistSession:n,detectSessionInUrl:r,storage:a,storageKey:i,flowType:l,lock:o,debug:c},d,u){const h={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new xus({url:this.authUrl.href,headers:Object.assign(Object.assign({},h),d),storageKey:i,autoRefreshToken:t,persistSession:n,detectSessionInUrl:r,storage:a,flowType:l,lock:o,debug:c,fetch:u,hasCustomAuthorizationHeader:"Authorization"in this.headers})}_initRealtimeClient(t){return new Qcs(this.realtimeUrl.href,Object.assign(Object.assign({},t),{params:Object.assign({apikey:this.supabaseKey},t==null?void 0:t.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((n,r)=>{this._handleTokenChanged(n,"CLIENT",r==null?void 0:r.access_token)})}_handleTokenChanged(t,n,r){(t==="TOKEN_REFRESHED"||t==="SIGNED_IN")&&this.changedAccessToken!==r?this.changedAccessToken=r:t==="SIGNED_OUT"&&(this.realtime.setAuth(),n=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}}const bus=(s,t,n)=>new vus(s,t,n),_us="https://relzejiswnotikjgvjhz.supabase.co",wus="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InJlbHplamlzd25vdGlramd2amh6Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjE5NTAzNDQsImV4cCI6MjA3NzUyNjM0NH0.dzIkIr_oFSbFE3oWS0ktIr83iKHHkZxt40Gc7SpC_mM",V=bus(_us,wus,{auth:{storage:localStorage,persistSession:!0,autoRefreshToken:!0}}),jus=Object.freeze(Object.defineProperty({__proto__:null,supabase:V},Symbol.toStringTag,{value:"Module"})),N4t=k.createContext(void 0),Nus=({children:s})=>{const[t,n]=k.useState(null),[r,a]=k.useState(null),[i,l]=k.useState(!0),[o,c]=k.useState(!0),[d,u]=k.useState(!1),[h,m]=k.useState(!1),[p,g]=k.useState(!1),[x,y]=k.useState(null),[v,_]=k.useState([]),[j,C]=k.useState(null),A=k.useRef(null),M=k.useRef(!1),I=k.useRef(!1),P=Jn(),R=()=>{u(!1),m(!1),g(!1),y(null),_([]),C(null),A.current=null,M.current=!1},O=async H=>{if(!(M.current&&A.current===H)&&!I.current){I.current=!0,c(!0);try{console.log("Checking roles via RPC for user:",H);const[{data:Y,error:se},{data:ee,error:oe},{data:me,error:Q}]=await Promise.all([V.rpc("has_role",{_user_id:H,_role:"admin"}),V.rpc("has_role",{_user_id:H,_role:"brokerage_manager"}),V.rpc("has_role",{_user_id:H,_role:"coach"})]);if(se||oe)console.error("Role RPC errors:",{isAdminError:se,isBrokerError:oe,isCoachError:Q}),u(!1),m(!1),g(!1);else{const fe=!!Y,_e=!!ee,ve=!!me;console.log("RPC roles result:",{adminValue:fe,brokerValue:_e,coachValue:ve}),u(fe),m(_e),g(ve)}const{data:te,error:le}=await V.from("profiles").select("brokerage_id").eq("id",H).single();if(y(!le&&te?te.brokerage_id:null),ee){console.log("Fetching managed brokerages for user:",H);const{data:fe,error:_e}=await V.from("brokerage_manager_assignments").select("brokerage_id").eq("user_id",H);if(console.log("Managed brokerage assignments result:",{assignments:fe,assignmentsError:_e}),_e||!fe){console.error("Error fetching managed brokerage assignments:",_e),_([]);return}const ve=Array.from(new Set(fe.map(Ie=>Ie.brokerage_id).filter(Boolean)));if(ve.length===0){_([]);return}const{data:he,error:Se}=await V.from("brokerages").select("id, name").in("id",ve);if(console.log("Managed brokerages details result:",{brokeragesData:he,brokeragesError:Se}),Se||!he){console.error("Error fetching managed brokerages details:",Se),_([]);return}const Te=he.map(Ie=>({id:Ie.id,name:Ie.name})).sort((Ie,Ue)=>ve.indexOf(Ie.id)-ve.indexOf(Ue.id));console.log("Parsed managed brokerages:",Te),_(Te),Te.length>0&&C(Ie=>Ie??Te[0].id)}else console.log("User is not a brokerage manager, skipping managed brokerages fetch"),_([]);A.current=H,M.current=!0}catch(Y){console.error("Unexpected error in checkRoles:",Y),R()}finally{I.current=!1,c(!1)}}};k.useEffect(()=>{let H=!0,Y=!1;const se=()=>{!H||Y||(Y=!0,l(!1))},{data:{subscription:ee}}=V.auth.onAuthStateChange((Q,te)=>{console.log("Auth event:",Q),H&&(a(te),n((te==null?void 0:te.user)??null),se(),Q==="PASSWORD_RECOVERY"&&(console.log("Password recovery detected, redirecting to profile"),setTimeout(()=>{P("/profile?reset=true")},100)),te!=null&&te.user?(!M.current||A.current!==te.user.id)&&setTimeout(()=>{O(te.user.id)},0):(R(),c(!1)))}),oe=window.setTimeout(()=>{console.warn("Auth initialization timeout reached. Continuing without blocking UI."),se()},4e3);return(async()=>{try{const{data:{session:Q}}=await V.auth.getSession();if(!H)return;a(Q),n((Q==null?void 0:Q.user)??null),Q!=null&&Q.user?await O(Q.user.id):R()}catch(Q){console.error("Error restoring auth session:",Q),H&&(a(null),n(null),R())}finally{se()}})(),()=>{H=!1,window.clearTimeout(oe),ee.unsubscribe()}},[]);const B=async(H,Y)=>{const{error:se}=await V.auth.signInWithPassword({email:H,password:Y});if(se)throw ae.error(se.message),se;ae.success("Welcome back!")},U=async(H,Y,se)=>{var te;const ee=`${window.location.origin}/dashboard`,oe=localStorage.getItem("levelup_referral_code")||null,{data:me,error:Q}=await V.auth.signUp({email:H,password:Y,options:{emailRedirectTo:ee,data:{name:se,referred_by_code:oe}}});if(Q)throw ae.error(Q.message),Q;if(oe&&((te=me.user)!=null&&te.id))try{await V.from("profiles").update({referred_by_code:oe}).eq("id",me.user.id),localStorage.removeItem("levelup_referral_code")}catch(le){console.warn("Failed to attach referral code to profile",le)}ae.success("Account created! Welcome to LevelUp."),P("/dashboard")},G=async()=>{try{const{data:{session:H}}=await V.auth.getSession();if(H){const{error:Y}=await V.auth.signOut();Y?Y.message==="Auth session missing!"?console.warn("Sign out warning (ignored):",Y.message):(console.error("Sign out error:",Y),ae.error(Y.message)):ae.success("Signed out successfully")}else console.log("No active session found, redirecting to auth");n(null),a(null),u(!1),m(!1),y(null),_([]),C(null),P("/auth")}catch(H){console.error("Unexpected sign out error:",H),P("/auth")}};return e.jsx(N4t.Provider,{value:{user:t,session:r,loading:i,rolesLoading:o,signIn:B,signUp:U,signOut:G,isAdmin:d,isBrokerageManager:h,isCoach:p,brokerageId:x,managedBrokerages:v,selectedBrokerageId:j,setSelectedBrokerageId:C},children:s})},ks=()=>{const s=k.useContext(N4t);if(s===void 0)throw new Error("useAuth must be used within an AuthProvider");return s},k4t=k.createContext({onlineUsers:[],totalOnline:0}),kus=3*60*1e3,Sus=45*1e3,Cus=30*1e3,Aus=({children:s})=>{const{user:t,brokerageId:n,isAdmin:r}=ks(),[a,i]=k.useState([]),l=k.useRef(new Date().toISOString()),o=k.useCallback(async()=>{t&&await V.from("user_presence").upsert({user_id:t.id,last_seen_at:new Date().toISOString(),online_since:l.current,current_path:window.location.pathname},{onConflict:"user_id"})},[t==null?void 0:t.id]),c=k.useCallback(async()=>{if(!t)return;const u=new Date(Date.now()-kus).toISOString(),{data:h}=await V.from("user_presence").select("user_id, last_seen_at, online_since").gte("last_seen_at",u).order("last_seen_at",{ascending:!1}).limit(200);if(!(h!=null&&h.length)){i([]);return}const m=h.map(x=>x.user_id),{data:p}=await V.from("profiles").select("id, name, email, avatar_url, brokerage_id").in("id",m),g=new Map((p||[]).map(x=>[x.id,x]));i(h.map(x=>{var v;const y=g.get(x.user_id);return{id:x.user_id,name:(y==null?void 0:y.name)||((v=y==null?void 0:y.email)==null?void 0:v.split("@")[0])||"Member",avatarUrl:(y==null?void 0:y.avatar_url)||void 0,brokerageId:(y==null?void 0:y.brokerage_id)||void 0,onlineSince:x.online_since||x.last_seen_at}}))},[t==null?void 0:t.id]);k.useEffect(()=>{if(!t){i([]);return}l.current=new Date().toISOString();let u=!1;const h=async()=>{u||(await o(),await c())};h();const m=window.setInterval(()=>{o()},Sus),p=window.setInterval(()=>{c()},Cus),g=()=>{document.visibilityState==="visible"&&h()};return document.addEventListener("visibilitychange",g),()=>{u=!0,window.clearInterval(m),window.clearInterval(p),document.removeEventListener("visibilitychange",g)}},[t==null?void 0:t.id,o,c]);const d=a.filter(u=>!!(u.id===(t==null?void 0:t.id)||r||n&&u.brokerageId===n||!n&&!u.brokerageId));return e.jsx(k4t.Provider,{value:{onlineUsers:d,totalOnline:d.length},children:s})},S4t=()=>k.useContext(k4t),C4t=k.createContext(void 0),rP="levelup_admin_session",DA="levelup_impersonation",dIe="levelup_impersonation_return",Eus=({children:s})=>{const[t,n]=k.useState(!1),[r,a]=k.useState(null),[i,l]=k.useState(!1);k.useEffect(()=>{const d=sessionStorage.getItem(DA);if(d)try{const u=JSON.parse(d);n(!0),a(u)}catch{sessionStorage.removeItem(DA)}},[]);const o=async(d,u)=>{l(!0);try{const{data:{session:h}}=await V.auth.getSession();if(!h)return ae.error("No active session found"),!1;const m={access_token:h.access_token,refresh_token:h.refresh_token};sessionStorage.setItem(rP,JSON.stringify(m)),u&&sessionStorage.setItem(dIe,u);const p=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/impersonate-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${h.access_token}`},body:JSON.stringify({targetUserId:d})}),g=await p.json();if(!p.ok)throw new Error(g.error||"Failed to impersonate user");const x={id:g.targetUser.id,name:g.targetUser.name,email:g.targetUser.email};if(sessionStorage.setItem(DA,JSON.stringify(x)),g.method==="session"){const{error:y}=await V.auth.setSession({access_token:g.access_token,refresh_token:g.refresh_token});if(y)throw console.error("Set session error:",y),sessionStorage.removeItem(rP),sessionStorage.removeItem(DA),new Error("Failed to establish impersonation session")}else{const y=g.type||"recovery",{error:v}=await V.auth.verifyOtp({token_hash:g.token_hash,type:y});if(v)throw console.error("Verify OTP error:",v),sessionStorage.removeItem(rP),sessionStorage.removeItem(DA),new Error("Failed to establish impersonation session")}return n(!0),a(x),ae.success(`Now viewing as ${x.name}`),window.location.href="/dashboard",!0}catch(h){return console.error("Impersonation error:",h),ae.error(h.message||"Failed to impersonate user"),sessionStorage.removeItem(rP),sessionStorage.removeItem(DA),!1}finally{l(!1)}},c=async()=>{l(!0);try{const d=sessionStorage.getItem(rP);if(!d){await V.auth.signOut(),window.location.href="/auth";return}const u=JSON.parse(d);await V.auth.signOut();const{error:h}=await V.auth.setSession({access_token:u.access_token,refresh_token:u.refresh_token});if(sessionStorage.removeItem(rP),sessionStorage.removeItem(DA),h){console.error("Failed to restore admin session:",h),ae.error("Admin session expired, please sign in again"),window.location.href="/auth";return}n(!1),a(null),ae.success("Returned to your account");const m=sessionStorage.getItem(dIe)||"/admin/members";sessionStorage.removeItem(dIe),window.location.href=m}catch(d){console.error("Stop impersonation error:",d),ae.error("Failed to restore admin session"),sessionStorage.removeItem(rP),sessionStorage.removeItem(DA),window.location.href="/auth"}finally{l(!1)}};return e.jsx(C4t.Provider,{value:{isImpersonating:t,impersonatedUser:r,startImpersonation:o,stopImpersonation:c,isLoading:i},children:s})},C3e=()=>{const s=k.useContext(C4t);if(s===void 0)throw new Error("useImpersonation must be used within an ImpersonationProvider");return s},Tus=()=>{const{isImpersonating:s,impersonatedUser:t,stopImpersonation:n,isLoading:r}=C3e();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(Gd,{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($,{size:"sm",variant:"secondary",onClick:n,disabled:r,className:"bg-amber-100 hover:bg-amber-200 text-amber-950 border-0",children:r?e.jsx(Jt,{className:"h-4 w-4 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(mr,{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"})]})})]})})},A4t=k.createContext(void 0),$7="levelup_acting_as",Gne="levelup_acting_as_self",Mus=({children:s})=>{const{user:t}=ks(),[n,r]=k.useState(!1),[a,i]=k.useState([]),[l,o]=k.useState(null),[c,d]=k.useState({}),[u,h]=k.useState(!0),[m,p]=k.useState(()=>sessionStorage.getItem(Gne)==="true");k.useEffect(()=>{if(!(t!=null&&t.id)){r(!1),i([]),o(null),d({}),h(!1);return}(async()=>{h(!0);try{const{data:j}=await V.rpc("has_role",{_user_id:t.id,_role:"assistant"});if(!j){r(!1),i([]),o(null),d({}),h(!1);return}r(!0);const{data:C,error:A}=await V.from("agent_assistant_assignments").select("agent_id, permissions").eq("assistant_id",t.id);if(A||!C||C.length===0){i([]),h(!1);return}const M=C.map(R=>R.agent_id),{data:I}=await V.from("profiles").select("id, name, email, avatar_url").in("id",M),P=(I||[]).map(R=>({id:R.id,name:R.name||R.email||"Unknown",email:R.email||"",avatar_url:R.avatar_url}));if(i(P),sessionStorage.getItem(Gne)==="true")p(!0),o(null),d({});else{const R=sessionStorage.getItem($7);if(R){const O=P.find(B=>B.id===R);if(O){o(O);const B=C.find(U=>U.agent_id===R);d((B==null?void 0:B.permissions)||{})}else if(P.length>0){o(P[0]);const B=C.find(U=>U.agent_id===P[0].id);d((B==null?void 0:B.permissions)||{}),sessionStorage.setItem($7,P[0].id)}}else if(P.length>0){o(P[0]);const O=C.find(B=>B.agent_id===P[0].id);d((O==null?void 0:O.permissions)||{}),sessionStorage.setItem($7,P[0].id)}}}catch(j){console.error("Error loading assistant data:",j)}finally{h(!1)}})()},[t==null?void 0:t.id]);const g=_=>{o(_),p(!1),sessionStorage.removeItem(Gne),_?(sessionStorage.setItem($7,_.id),V.from("agent_assistant_assignments").select("permissions").eq("assistant_id",(t==null?void 0:t.id)||"").eq("agent_id",_.id).single().then(({data:j})=>{d((j==null?void 0:j.permissions)||{})})):(sessionStorage.removeItem($7),d({}))},x=()=>{p(!0),o(null),d({}),sessionStorage.setItem(Gne,"true"),sessionStorage.removeItem($7)},y=_=>!n||m?!0:c[_]===!0,v=n&&l&&!m?l.id:(t==null?void 0:t.id)||null;return e.jsx(A4t.Provider,{value:{isAssistant:n,assignedAgents:a,actingAsAgent:l,setActingAsAgent:g,effectiveUserId:v,permissions:c,hasPermission:y,isLoading:u,isActingAsSelf:m,setActingAsSelf:x},children:s})},cee=()=>{const s=k.useContext(A4t);if(s===void 0)throw new Error("useActingAs must be used within an ActingAsProvider");return s},ai=()=>{const{effectiveUserId:s}=cee();return s};var Pus=Object.defineProperty,$3=(s,t)=>Pus(s,"name",{value:t,configurable:!0}),E4t="Avatar",[Ius,kQn]=qm(E4t),Lus=[0,()=>{}],[Rus,T4t]=Ius(E4t),M4t=k.forwardRef($3(function(t,n){const{__scopeAvatar:r,...a}=t,[i,l]=k.useState("idle"),[o,c]=R4t();return e.jsx(Rus,{scope:r,imageLoadingStatus:i,setImageLoadingStatus:l,imageCount:o,setImageCount:c,children:e.jsx(hi.span,{...a,ref:n})})},"Avatar")),Dus="AvatarImage",P4t=k.forwardRef($3(function(t,n){const{__scopeAvatar:r,src:a,onLoadingStatusChange:i,...l}=t,o=T4t(Dus,r);o.setImageCount;const c=L4t(a,{referrerPolicy:l.referrerPolicy,crossOrigin:l.crossOrigin,loadingStatus:o.imageLoadingStatus,setLoadingStatus:o.setImageLoadingStatus}),d=sp(h=>{i==null||i(h)}),u=k.useRef(c);return _m(()=>{const h=u.current;u.current=c,c!==h&&d(c)},[c,d]),c==="loaded"?e.jsx(hi.img,{...l,ref:n,src:a}):null},"AvatarImage")),Ous="AvatarFallback",I4t=k.forwardRef($3(function(t,n){const{__scopeAvatar:r,delayMs:a,...i}=t,l=T4t(Ous,r),[o,c]=k.useState(a===void 0);return k.useEffect(()=>{if(a!==void 0){const d=window.setTimeout(()=>c(!0),a);return()=>window.clearTimeout(d)}},[a]),o&&l.imageLoadingStatus!=="loaded"?e.jsx(hi.span,{...i,ref:n}):null},"AvatarFallback"));function L4t(s,{loadingStatus:t,setLoadingStatus:n,referrerPolicy:r,crossOrigin:a}){return _m(()=>{if(!s){n("error");return}const i=new window.Image,l=$3(c=>{const d=c.currentTarget;n(QFe(d))},"handleLoad"),o=$3(()=>n("error"),"handleError");return i.addEventListener("load",l),i.addEventListener("error",o),r&&(i.referrerPolicy=r),i.crossOrigin=a??null,i.src=s,n(QFe(i)),()=>{i.removeEventListener("load",l),i.removeEventListener("error",o),n("idle")}},[s,a,r,n]),t}$3(L4t,"useImageLoadingStatus");function QFe(s){return s.complete?s.naturalWidth>0?"loaded":"error":"loading"}$3(QFe,"getImageLoadingStatus");function R4t(){return Lus}$3(R4t,"useImageCount");function Fus(s){}$3(Fus,"useUpdateImageCount");const Wa=k.forwardRef(({className:s,...t},n)=>e.jsx(M4t,{ref:n,className:Ot("relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",s),...t}));Wa.displayName=M4t.displayName;const eo=k.forwardRef(({className:s,...t},n)=>e.jsx(P4t,{ref:n,className:Ot("aspect-square h-full w-full",s),...t}));eo.displayName=P4t.displayName;const Ka=k.forwardRef(({className:s,...t},n)=>e.jsx(I4t,{ref:n,className:Ot("flex h-full w-full items-center justify-center rounded-full bg-muted",s),...t}));Ka.displayName=I4t.displayName;const zus=gF("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 qe({className:s,variant:t,...n}){return e.jsx("div",{className:Ot(zus({variant:t}),s),...n})}var Bus=Object.defineProperty,$us=(s,t)=>Bus(s,"name",{value:t,configurable:!0}),Uus=k.createContext(void 0);function e4(s){const t=k.useContext(Uus);return s||t||"ltr"}$us(e4,"useDirection");var qus=Object.defineProperty,bHe=(s,t)=>qus(s,"name",{value:t,configurable:!0}),uIe=!1;function D4t(){const[s,t]=k.useState(uIe);return k.useEffect(()=>{uIe||(uIe=!0,t(!0))},[]),s}bHe(D4t,"useIsHydrated");var O4t=uF[" useSyncExternalStore ".trim().toString()];function F4t(){return()=>{}}bHe(F4t,"subscribe");function z4t(){return O4t(F4t,()=>!0,()=>!1)}bHe(z4t,"useIsHydratedModern");var Vus=typeof O4t=="function"?z4t:D4t,Hus=Object.defineProperty,yF=(s,t)=>Hus(s,"name",{value:t,configurable:!0}),hIe="rovingFocusGroup.onEntryFocus",Gus={bubbles:!1,cancelable:!0},A3e="RovingFocusGroup",[JFe,B4t,Wus]=fF(A3e),[Kus,YM]=qm(A3e,[Wus]),[Yus,Zus]=Kus(A3e),Xus=k.forwardRef(yF(function(t,n){return e.jsx(JFe.Provider,{scope:t.__scopeRovingFocusGroup,children:e.jsx(JFe.Slot,{scope:t.__scopeRovingFocusGroup,children:e.jsx(Qus,{...t,ref:n})})})},"RovingFocusGroup")),Qus=k.forwardRef(yF(function(t,n){const{__scopeRovingFocusGroup:r,orientation:a,loop:i=!1,dir:l,currentTabStopId:o,defaultCurrentTabStopId:c,onCurrentTabStopIdChange:d,onEntryFocus:u,preventScrollOnEntryFocus:h=!1,...m}=t,p=k.useRef(null),g=Ao(n,p),x=e4(l),[y,v]=ox({prop:o,defaultProp:c??null,onChange:d,caller:A3e}),[_,j]=k.useState(!1),C=sp(u),A=B4t(r),M=k.useRef(!1),[I,P]=k.useState(0);return k.useEffect(()=>{const R=p.current;if(R)return R.addEventListener(hIe,C),()=>R.removeEventListener(hIe,C)},[C]),e.jsx(Yus,{scope:r,orientation:a,dir:x,loop:i,currentTabStopId:y,onItemFocus:k.useCallback(R=>v(R),[v]),onItemShiftTab:k.useCallback(()=>j(!0),[]),onFocusableItemAdd:k.useCallback(()=>P(R=>R+1),[]),onFocusableItemRemove:k.useCallback(()=>P(R=>R-1),[]),children:e.jsx(hi.div,{tabIndex:_||I===0?-1:0,"data-orientation":a,...m,ref:g,style:{outline:"none",...t.style},onMouseDown:ga(t.onMouseDown,()=>{M.current=!0}),onFocus:ga(t.onFocus,R=>{const O=!M.current;if(R.target===R.currentTarget&&O&&!_){const B=new CustomEvent(hIe,Gus);if(R.currentTarget.dispatchEvent(B),!B.defaultPrevented){const U=A().filter(ee=>ee.focusable),G=U.find(ee=>ee.active),H=U.find(ee=>ee.id===y),se=[G,H,...U].filter(Boolean).map(ee=>ee.ref.current);_He(se,h)}}M.current=!1}),onBlur:ga(t.onBlur,()=>j(!1))})})},"RovingFocusGroupImpl")),Jus="RovingFocusGroupItem",ehs=k.forwardRef(yF(function(t,n){const{__scopeRovingFocusGroup:r,focusable:a=!0,active:i=!1,tabStopId:l,children:o,...c}=t,d=$x(),u=l||d,h=Zus(Jus,r),m=h.currentTabStopId===u,p=B4t(r),{onFocusableItemAdd:g,onFocusableItemRemove:x,currentTabStopId:y}=h,v=Vus();return _m(()=>{if(!(!v||!a))return g(),()=>x()},[v,a,g,x]),k.useEffect(()=>{if(!(v||!a))return g(),()=>x()},[v,a,g,x]),e.jsx(JFe.ItemSlot,{scope:r,id:u,focusable:a,active:i,children:e.jsx(hi.span,{tabIndex:m?0:-1,"data-orientation":h.orientation,...c,ref:n,onMouseDown:ga(t.onMouseDown,_=>{a?h.onItemFocus(u):_.preventDefault()}),onFocus:ga(t.onFocus,()=>h.onItemFocus(u)),onKeyDown:ga(t.onKeyDown,_=>{if(_.key==="Tab"&&_.shiftKey){h.onItemShiftTab();return}if(_.target!==_.currentTarget)return;const j=U4t(_,h.orientation,h.dir);if(j!==void 0){if(_.metaKey||_.ctrlKey||_.altKey||_.shiftKey)return;_.preventDefault();let A=p().filter(M=>M.focusable).map(M=>M.ref.current);if(j==="last")A.reverse();else if(j==="prev"||j==="next"){j==="prev"&&A.reverse();const M=A.indexOf(_.currentTarget);A=h.loop?q4t(A,M+1):A.slice(M+1)}setTimeout(()=>_He(A))}}),children:typeof o=="function"?o({isCurrentTabStop:m,hasTabStop:y!=null}):o})})},"RovingFocusGroupItem")),ths={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function $4t(s,t){return t!=="rtl"?s:s==="ArrowLeft"?"ArrowRight":s==="ArrowRight"?"ArrowLeft":s}yF($4t,"getDirectionAwareKey");function U4t(s,t,n){const r=$4t(s.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return ths[r]}yF(U4t,"getFocusIntent");function _He(s,t=!1){const n=document.activeElement;for(const r of s)if(r===n||(r.focus({preventScroll:t}),document.activeElement!==n))return}yF(_He,"focusFirst");function q4t(s,t){return s.map((n,r)=>s[(t+r)%s.length])}yF(q4t,"wrapArray");var E3e=Xus,T3e=ehs,shs=Object.defineProperty,qu=(s,t)=>shs(s,"name",{value:t,configurable:!0}),e7e=["Enter"," "],nhs=["ArrowDown","PageUp","Home"],V4t=["ArrowUp","PageDown","End"],rhs=[...nhs,...V4t],ahs={ltr:[...e7e,"ArrowRight"],rtl:[...e7e,"ArrowLeft"]},ihs={ltr:["ArrowLeft"],rtl:["ArrowRight"]},M3e="Menu",[qZ,ohs,lhs]=fF(M3e),[vF,H4t]=qm(M3e,[lhs,Q5,YM]),wHe=Q5(),G4t=YM(),[chs,bF]=vF(M3e),[dhs,dee]=vF(M3e),uhs=qu(s=>{const{__scopeMenu:t,open:n=!1,children:r,dir:a,onOpenChange:i,modal:l=!0}=s,o=wHe(t),[c,d]=k.useState(null),u=k.useRef(!1),h=sp(i),m=e4(a);return k.useEffect(()=>{const p=qu(()=>{u.current=!0,document.addEventListener("pointerdown",g,{capture:!0,once:!0}),document.addEventListener("pointermove",g,{capture:!0,once:!0})},"handleKeyDown"),g=qu(()=>u.current=!1,"handlePointer");return document.addEventListener("keydown",p,{capture:!0}),()=>{document.removeEventListener("keydown",p,{capture:!0}),document.removeEventListener("pointerdown",g,{capture:!0}),document.removeEventListener("pointermove",g,{capture:!0})}},[]),k.useEffect(()=>{if(!n)return;const p=qu(()=>h(!1),"handleBlur");return window.addEventListener("blur",p),()=>window.removeEventListener("blur",p)},[n,h]),e.jsx(ree,{...o,children:e.jsx(chs,{scope:t,open:n,onOpenChange:h,content:c,onContentChange:d,children:e.jsx(dhs,{scope:t,onClose:k.useCallback(()=>h(!1),[h]),isUsingKeyboardRef:u,dir:m,modal:l,children:r})})})},"Menu"),W4t=k.forwardRef(qu(function(t,n){const{__scopeMenu:r,...a}=t,i=wHe(r);return e.jsx(aee,{...i,...a,ref:n})},"MenuAnchor")),K4t="MenuPortal",[hhs,Y4t]=vF(K4t,{forceMount:void 0}),mhs=qu(s=>{const{__scopeMenu:t,forceMount:n,children:r,container:a}=s,i=bF(K4t,t);return e.jsx(hhs,{scope:t,forceMount:n,children:e.jsx(cx,{present:n||i.open,children:e.jsx(QJ,{asChild:!0,container:a,children:r})})})},"MenuPortal"),dk="MenuContent",[fhs,jHe]=vF(dk),phs=k.forwardRef(qu(function(t,n){const r=Y4t(dk,t.__scopeMenu),{forceMount:a=r.forceMount,...i}=t,l=bF(dk,t.__scopeMenu),o=dee(dk,t.__scopeMenu);return e.jsx(qZ.Provider,{scope:t.__scopeMenu,children:e.jsx(cx,{present:a||l.open,children:e.jsx(qZ.Slot,{scope:t.__scopeMenu,children:o.modal?e.jsx(ghs,{...i,ref:n}):e.jsx(xhs,{...i,ref:n})})})})},"MenuContent")),ghs=k.forwardRef(qu(function(t,n){const r=bF(dk,t.__scopeMenu),a=k.useRef(null),i=Ao(n,a);return k.useEffect(()=>{const l=a.current;if(l)return i3e(l)},[]),e.jsx(NHe,{...t,ref:i,trapFocus:r.open,disableOutsidePointerEvents:r.open,disableOutsideScroll:!0,onFocusOutside:ga(t.onFocusOutside,l=>l.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>r.onOpenChange(!1)})},"MenuRootContentModal")),xhs=k.forwardRef(qu(function(t,n){const r=bF(dk,t.__scopeMenu);return e.jsx(NHe,{...t,ref:n,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>r.onOpenChange(!1)})},"MenuRootContentNonModal")),yhs=xk("MenuContent.ScrollLock"),NHe=k.forwardRef(qu(function(t,n){const{__scopeMenu:r,loop:a=!1,trapFocus:i,onOpenAutoFocus:l,onCloseAutoFocus:o,disableOutsidePointerEvents:c,onEntryFocus:d,onEscapeKeyDown:u,onPointerDownOutside:h,onFocusOutside:m,onInteractOutside:p,onDismiss:g,disableOutsideScroll:x,...y}=t,v=bF(dk,r),_=dee(dk,r),j=wHe(r),C=G4t(r),A=ohs(r),[M,I]=k.useState(null),P=k.useRef(null),R=Ao(n,P,v.onContentChange),O=k.useRef(0),B=k.useRef(""),U=k.useRef(0),G=k.useRef(null),H=k.useRef("right"),Y=k.useRef(0),se=x?eee:k.Fragment,ee=x?{as:yhs,allowPinchZoom:!0}:void 0,oe=qu(Q=>{var Te,Ie;const te=B.current+Q,le=A().filter(Ue=>!Ue.disabled),fe=document.activeElement,_e=(Te=le.find(Ue=>Ue.ref.current===fe))==null?void 0:Te.textValue,ve=le.map(Ue=>Ue.textValue),he=sCt(ve,te,_e),Se=(Ie=le.find(Ue=>Ue.textValue===he))==null?void 0:Ie.ref.current;qu(function Ue(Be){B.current=Be,window.clearTimeout(O.current),Be!==""&&(O.current=window.setTimeout(()=>Ue(""),1e3))},"updateSearch")(te),Se&&setTimeout(()=>Se.focus())},"handleTypeaheadSearch");k.useEffect(()=>()=>window.clearTimeout(O.current),[]),Mq();const me=k.useCallback(Q=>{var le,fe;return H.current===((le=G.current)==null?void 0:le.side)&&rCt(Q,(fe=G.current)==null?void 0:fe.area)},[]);return e.jsx(fhs,{scope:r,searchRef:B,onItemEnter:k.useCallback(Q=>{me(Q)&&Q.preventDefault()},[me]),onItemLeave:k.useCallback(Q=>{var te;me(Q)||((te=P.current)==null||te.focus(),I(null))},[me]),onTriggerLeave:k.useCallback(Q=>{me(Q)&&Q.preventDefault()},[me]),pointerGraceTimerRef:U,onPointerGraceIntentChange:k.useCallback(Q=>{G.current=Q},[]),children:e.jsx(se,{...ee,children:e.jsx(r3e,{asChild:!0,trapped:i,onMountAutoFocus:ga(l,Q=>{var te;Q.preventDefault(),(te=P.current)==null||te.focus({preventScroll:!0})}),onUnmountAutoFocus:o,children:e.jsx(pF,{asChild:!0,disableOutsidePointerEvents:c,onEscapeKeyDown:u,onPointerDownOutside:h,onFocusOutside:m,onInteractOutside:p,onDismiss:g,children:e.jsx(E3e,{asChild:!0,...C,dir:_.dir,orientation:"vertical",loop:a,currentTabStopId:M,onCurrentTabStopIdChange:I,onEntryFocus:ga(d,Q=>{_.isUsingKeyboardRef.current||Q.preventDefault()}),preventScrollOnEntryFocus:!0,children:e.jsx(iee,{role:"menu","aria-orientation":"vertical","data-state":SHe(v.open),"data-radix-menu-content":"",dir:_.dir,...j,...y,ref:R,style:{outline:"none",...y.style},onKeyDown:ga(y.onKeyDown,Q=>{const le=Q.target.closest("[data-radix-menu-content]")===Q.currentTarget,fe=Q.ctrlKey||Q.altKey||Q.metaKey,_e=Q.key.length===1;le&&(Q.key==="Tab"&&Q.preventDefault(),!fe&&_e&&oe(Q.key));const ve=P.current;if(Q.target!==ve||!rhs.includes(Q.key))return;Q.preventDefault();const Se=A().filter(Te=>!Te.disabled).map(Te=>Te.ref.current);V4t.includes(Q.key)&&Se.reverse(),eCt(Se)}),onBlur:ga(t.onBlur,Q=>{Q.currentTarget.contains(Q.target)||(window.clearTimeout(O.current),B.current="")}),onPointerMove:ga(t.onPointerMove,gU(Q=>{const te=Q.target,le=Y.current!==Q.clientX;if(Q.currentTarget.contains(te)&&le){const fe=Q.clientX>Y.current?"right":"left";H.current=fe,Y.current=Q.clientX}}))})})})})})})},"MenuContentImpl")),vhs=k.forwardRef(qu(function(t,n){const{__scopeMenu:r,...a}=t;return e.jsx(hi.div,{...a,ref:n})},"MenuLabel")),t7e="MenuItem",Wit="menu.itemSelect",kHe=k.forwardRef(qu(function(t,n){const{disabled:r=!1,onSelect:a,...i}=t,l=k.useRef(null),o=dee(t7e,t.__scopeMenu),c=jHe(t7e,t.__scopeMenu),d=Ao(n,l),u=k.useRef(!1),h=qu(()=>{const m=l.current;if(!r&&m){const p=new CustomEvent(Wit,{bubbles:!0,cancelable:!0});m.addEventListener(Wit,g=>a==null?void 0:a(g),{once:!0}),e3e(m,p),p.defaultPrevented?u.current=!1:o.onClose()}},"handleSelect");return e.jsx(Z4t,{...i,ref:d,disabled:r,onClick:ga(t.onClick,h),onPointerDown:m=>{var p;(p=t.onPointerDown)==null||p.call(t,m),u.current=!0},onPointerUp:ga(t.onPointerUp,m=>{var p;u.current||(p=m.currentTarget)==null||p.click()}),onKeyDown:ga(t.onKeyDown,m=>{r||m.target!==m.currentTarget||c.searchRef.current!==""&&m.key===" "||e7e.includes(m.key)&&(m.currentTarget.click(),m.preventDefault())})})},"MenuItem")),Z4t=k.forwardRef(qu(function(t,n){const{__scopeMenu:r,disabled:a=!1,textValue:i,...l}=t,o=jHe(t7e,r),c=G4t(r),d=k.useRef(null),u=Ao(n,d),[h,m]=k.useState(!1),[p,g]=k.useState("");return k.useEffect(()=>{const x=d.current;x&&g((x.textContent??"").trim())},[l.children]),e.jsx(qZ.ItemSlot,{scope:r,disabled:a,textValue:i??p,children:e.jsx(T3e,{asChild:!0,...c,focusable:!a,children:e.jsx(hi.div,{role:"menuitem","data-highlighted":h?"":void 0,"aria-disabled":a||void 0,"data-disabled":a?"":void 0,...l,ref:u,onPointerMove:ga(t.onPointerMove,gU(x=>{a?o.onItemLeave(x):(o.onItemEnter(x),x.defaultPrevented||x.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:ga(t.onPointerLeave,gU(x=>o.onItemLeave(x))),onFocus:ga(t.onFocus,()=>m(!0)),onBlur:ga(t.onBlur,()=>m(!1))})})})},"MenuItemImpl")),bhs=k.forwardRef(qu(function(t,n){const{checked:r=!1,onCheckedChange:a,...i}=t;return e.jsx(Q4t,{scope:t.__scopeMenu,checked:r,children:e.jsx(kHe,{role:"menuitemcheckbox","aria-checked":VZ(r)?"mixed":r,...i,ref:n,"data-state":P3e(r),onSelect:ga(i.onSelect,()=>a==null?void 0:a(VZ(r)?!0:!r),{checkForDefaultPrevented:!1})})})},"MenuCheckboxItem")),_hs="MenuRadioGroup",[SQn,whs]=vF(_hs,{value:void 0,onValueChange:qu(()=>{},"onValueChange")}),jhs="MenuRadioItem",Nhs=k.forwardRef(qu(function(t,n){const{value:r,...a}=t,i=whs(jhs,t.__scopeMenu),l=r===i.value;return e.jsx(Q4t,{scope:t.__scopeMenu,checked:l,children:e.jsx(kHe,{role:"menuitemradio","aria-checked":l,...a,ref:n,"data-state":P3e(l),onSelect:ga(a.onSelect,()=>{var o;return(o=i.onValueChange)==null?void 0:o.call(i,r)},{checkForDefaultPrevented:!1})})})},"MenuRadioItem")),X4t="MenuItemIndicator",[Q4t,khs]=vF(X4t,{checked:!1}),Shs=k.forwardRef(qu(function(t,n){const{__scopeMenu:r,forceMount:a,...i}=t,l=khs(X4t,r);return e.jsx(cx,{present:a||VZ(l.checked)||l.checked===!0,children:e.jsx(hi.span,{...i,ref:n,"data-state":P3e(l.checked)})})},"MenuItemIndicator")),Chs=k.forwardRef(qu(function(t,n){const{__scopeMenu:r,...a}=t;return e.jsx(hi.div,{role:"separator","aria-orientation":"horizontal",...a,ref:n})},"MenuSeparator")),Ahs="MenuSub",[CQn,J4t]=vF(Ahs),Wne="MenuSubTrigger",Ehs=k.forwardRef(qu(function(t,n){const r=bF(Wne,t.__scopeMenu),a=dee(Wne,t.__scopeMenu),i=J4t(Wne,t.__scopeMenu),l=jHe(Wne,t.__scopeMenu),o=k.useRef(null),{pointerGraceTimerRef:c,onPointerGraceIntentChange:d}=l,u={__scopeMenu:t.__scopeMenu},h=k.useCallback(()=>{o.current&&window.clearTimeout(o.current),o.current=null},[]);k.useEffect(()=>h,[h]),k.useEffect(()=>{const p=c.current;return()=>{window.clearTimeout(p),d(null)}},[c,d]);const m=Ao(n,i.onTriggerChange);return e.jsx(W4t,{asChild:!0,...u,children:e.jsx(Z4t,{id:i.triggerId,"aria-haspopup":"menu","aria-expanded":r.open,"aria-controls":r.open?i.contentId:void 0,"data-state":SHe(r.open),...t,ref:m,onClick:p=>{var g;(g=t.onClick)==null||g.call(t,p),!(t.disabled||p.defaultPrevented)&&(p.currentTarget.focus(),r.open||r.onOpenChange(!0))},onPointerMove:ga(t.onPointerMove,gU(p=>{l.onItemEnter(p),!p.defaultPrevented&&!t.disabled&&!r.open&&!o.current&&(l.onPointerGraceIntentChange(null),o.current=window.setTimeout(()=>{r.onOpenChange(!0),h()},100))})),onPointerLeave:ga(t.onPointerLeave,gU(p=>{var x,y;h();const g=(x=r.content)==null?void 0:x.getBoundingClientRect();if(g){const v=(y=r.content)==null?void 0:y.dataset.side,_=v==="right",j=_?-5:5,C=g[_?"left":"right"],A=g[_?"right":"left"];l.onPointerGraceIntentChange({area:[{x:p.clientX+j,y:p.clientY},{x:C,y:g.top},{x:A,y:g.top},{x:A,y:g.bottom},{x:C,y:g.bottom}],side:v}),window.clearTimeout(c.current),c.current=window.setTimeout(()=>l.onPointerGraceIntentChange(null),300)}else{if(l.onTriggerLeave(p),p.defaultPrevented)return;l.onPointerGraceIntentChange(null)}})),onKeyDown:ga(t.onKeyDown,p=>{var x;t.disabled||p.target!==p.currentTarget||l.searchRef.current!==""&&p.key===" "||ahs[a.dir].includes(p.key)&&(r.onOpenChange(!0),(x=r.content)==null||x.focus(),p.preventDefault())})})})},"MenuSubTrigger")),Ths="MenuSubContent",Mhs=k.forwardRef(qu(function(t,n){const r=Y4t(dk,t.__scopeMenu),{forceMount:a=r.forceMount,align:i="start",...l}=t,o=bF(dk,t.__scopeMenu),c=dee(dk,t.__scopeMenu),d=J4t(Ths,t.__scopeMenu),u=k.useRef(null),h=Ao(n,u);return e.jsx(qZ.Provider,{scope:t.__scopeMenu,children:e.jsx(cx,{present:a||o.open,children:e.jsx(qZ.Slot,{scope:t.__scopeMenu,children:e.jsx(NHe,{id:d.contentId,"aria-labelledby":d.triggerId,...l,ref:h,align:i,side:c.dir==="rtl"?"left":"right",disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:m=>{var p;c.isUsingKeyboardRef.current&&((p=u.current)==null||p.focus()),m.preventDefault()},onCloseAutoFocus:m=>m.preventDefault(),onFocusOutside:ga(t.onFocusOutside,m=>{m.target!==d.trigger&&o.onOpenChange(!1)}),onEscapeKeyDown:ga(t.onEscapeKeyDown,m=>{c.onClose(),m.preventDefault()}),onKeyDown:ga(t.onKeyDown,m=>{var x;const p=m.currentTarget.contains(m.target),g=ihs[c.dir].includes(m.key);p&&g&&(o.onOpenChange(!1),(x=d.trigger)==null||x.focus(),m.preventDefault())})})})})})},"MenuSubContent"));function SHe(s){return s?"open":"closed"}qu(SHe,"getOpenState");function VZ(s){return s==="indeterminate"}qu(VZ,"isIndeterminate");function P3e(s){return VZ(s)?"indeterminate":s?"checked":"unchecked"}qu(P3e,"getCheckedState");function eCt(s){const t=document.activeElement;for(const n of s)if(n===t||(n.focus(),document.activeElement!==t))return}qu(eCt,"focusFirst");function tCt(s,t){return s.map((n,r)=>s[(t+r)%s.length])}qu(tCt,"wrapArray");function sCt(s,t,n){const a=t.length>1&&Array.from(t).every(d=>d===t[0])?t[0]:t,i=n?s.indexOf(n):-1;let l=tCt(s,Math.max(i,0));a.length===1&&(l=l.filter(d=>d!==n));const c=l.find(d=>d.toLowerCase().startsWith(a.toLowerCase()));return c!==n?c:void 0}qu(sCt,"getNextMatch");function nCt(s,t){const{x:n,y:r}=s;let a=!1;for(let i=0,l=t.length-1;ir!=m>r&&n<(h-d)*(r-u)/(m-u)+d&&(a=!a)}return a}qu(nCt,"isPointInPolygon");function rCt(s,t){if(!t)return!1;const n={x:s.clientX,y:s.clientY};return nCt(n,t)}qu(rCt,"isPointerInGraceArea");function gU(s){return t=>t.pointerType==="mouse"?s(t):void 0}qu(gU,"whenMouse");var Phs=uhs,Ihs=W4t,Lhs=mhs,Rhs=phs,Dhs=vhs,Ohs=kHe,Fhs=bhs,zhs=Nhs,Bhs=Shs,$hs=Chs,Uhs=Ehs,qhs=Mhs,Vhs=Object.defineProperty,B2=(s,t)=>Vhs(s,"name",{value:t,configurable:!0}),CHe="DropdownMenu",[Hhs,AQn]=qm(CHe,[H4t]),$2=H4t(),[Ghs,aCt]=Hhs(CHe),Whs=B2(s=>{const{__scopeDropdownMenu:t,children:n,dir:r,open:a,defaultOpen:i,onOpenChange:l,modal:o=!0}=s,c=$2(t),d=k.useRef(null),[u,h]=ox({prop:a,defaultProp:i??!1,onChange:l,caller:CHe});return e.jsx(Ghs,{scope:t,triggerId:$x(),triggerRef:d,contentId:$x(),open:u,onOpenChange:h,onOpenToggle:k.useCallback(()=>h(m=>!m),[h]),modal:o,children:e.jsx(Phs,{...c,open:u,onOpenChange:h,dir:r,modal:o,children:n})})},"DropdownMenu"),Khs="DropdownMenuTrigger",Yhs=k.forwardRef(B2(function(t,n){const{__scopeDropdownMenu:r,disabled:a=!1,...i}=t,l=aCt(Khs,r),o=$2(r),c=Ao(n,l.triggerRef);return e.jsx(Ihs,{asChild:!0,...o,children:e.jsx(hi.button,{type:"button",id:l.triggerId,"aria-haspopup":"menu","aria-expanded":l.open,"aria-controls":l.open?l.contentId:void 0,"data-state":l.open?"open":"closed","data-disabled":a?"":void 0,disabled:a,...i,ref:c,onPointerDown:ga(t.onPointerDown,d=>{!a&&d.button===0&&d.ctrlKey===!1&&(l.onOpenToggle(),l.open||d.preventDefault())}),onKeyDown:ga(t.onKeyDown,d=>{a||(["Enter"," "].includes(d.key)&&l.onOpenToggle(),d.key==="ArrowDown"&&l.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(d.key)&&d.preventDefault())})})})},"DropdownMenuTrigger")),Zhs=B2(s=>{const{__scopeDropdownMenu:t,...n}=s,r=$2(t);return e.jsx(Lhs,{...r,...n})},"DropdownMenuPortal"),Xhs="DropdownMenuContent",Qhs=k.forwardRef(B2(function(t,n){const{__scopeDropdownMenu:r,...a}=t,i=aCt(Xhs,r),l=$2(r),o=k.useRef(!1);return e.jsx(Rhs,{id:i.contentId,"aria-labelledby":i.triggerId,...l,...a,ref:n,onCloseAutoFocus:ga(t.onCloseAutoFocus,c=>{var d;o.current||(d=i.triggerRef.current)==null||d.focus(),o.current=!1,c.preventDefault()}),onInteractOutside:ga(t.onInteractOutside,c=>{const d=c.detail.originalEvent,u=d.button===0&&d.ctrlKey===!0,h=d.button===2||u;(!i.modal||h)&&(o.current=!0)}),style:{...t.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)"}})},"DropdownMenuContent")),Jhs=k.forwardRef(B2(function(t,n){const{__scopeDropdownMenu:r,...a}=t,i=$2(r);return e.jsx(Dhs,{...i,...a,ref:n})},"DropdownMenuLabel")),ems=k.forwardRef(B2(function(t,n){const{__scopeDropdownMenu:r,...a}=t,i=$2(r);return e.jsx(Ohs,{...i,...a,ref:n})},"DropdownMenuItem")),tms=k.forwardRef(B2(function(t,n){const{__scopeDropdownMenu:r,...a}=t,i=$2(r);return e.jsx(Fhs,{...i,...a,ref:n})},"DropdownMenuCheckboxItem")),sms=k.forwardRef(B2(function(t,n){const{__scopeDropdownMenu:r,...a}=t,i=$2(r);return e.jsx(zhs,{...i,...a,ref:n})},"DropdownMenuRadioItem")),nms=k.forwardRef(B2(function(t,n){const{__scopeDropdownMenu:r,...a}=t,i=$2(r);return e.jsx(Bhs,{...i,...a,ref:n})},"DropdownMenuItemIndicator")),rms=k.forwardRef(B2(function(t,n){const{__scopeDropdownMenu:r,...a}=t,i=$2(r);return e.jsx($hs,{...i,...a,ref:n})},"DropdownMenuSeparator")),ams=k.forwardRef(B2(function(t,n){const{__scopeDropdownMenu:r,...a}=t,i=$2(r);return e.jsx(Uhs,{...i,...a,ref:n})},"DropdownMenuSubTrigger")),ims=k.forwardRef(B2(function(t,n){const{__scopeDropdownMenu:r,...a}=t,i=$2(r);return e.jsx(qhs,{...i,...a,ref:n,style:{...t.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)"}})},"DropdownMenuSubContent")),oms=Whs,lms=Yhs,cms=Zhs,iCt=Qhs,oCt=Jhs,lCt=ems,cCt=tms,dCt=sms,uCt=nms,hCt=rms,mCt=ams,fCt=ims;const Au=oms,Eu=lms,dms=k.forwardRef(({className:s,inset:t,children:n,...r},a)=>e.jsxs(mCt,{ref:a,className:Ot("flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none data-[state=open]:bg-accent focus:bg-accent",t&&"pl-8",s),...r,children:[n,e.jsx(fi,{className:"ml-auto h-4 w-4"})]}));dms.displayName=mCt.displayName;const ums=k.forwardRef(({className:s,...t},n)=>e.jsx(fCt,{ref:n,className:Ot("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}));ums.displayName=fCt.displayName;const gu=k.forwardRef(({className:s,sideOffset:t=4,...n},r)=>e.jsx(cms,{children:e.jsx(iCt,{ref:r,sideOffset:t,className:Ot("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",s),...n})}));gu.displayName=iCt.displayName;const Pa=k.forwardRef(({className:s,inset:t,...n},r)=>e.jsx(lCt,{ref:r,className:Ot("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors data-[disabled]:pointer-events-none data-[disabled]:opacity-50 focus:bg-accent focus:text-accent-foreground",t&&"pl-8",s),...n}));Pa.displayName=lCt.displayName;const hms=k.forwardRef(({className:s,children:t,checked:n,...r},a)=>e.jsxs(cCt,{ref:a,className:Ot("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors data-[disabled]:pointer-events-none data-[disabled]:opacity-50 focus:bg-accent focus:text-accent-foreground",s),checked:n,...r,children:[e.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e.jsx(uCt,{children:e.jsx(ma,{className:"h-4 w-4"})})}),t]}));hms.displayName=cCt.displayName;const mms=k.forwardRef(({className:s,children:t,...n},r)=>e.jsxs(dCt,{ref:r,className:Ot("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors data-[disabled]:pointer-events-none data-[disabled]:opacity-50 focus:bg-accent focus:text-accent-foreground",s),...n,children:[e.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e.jsx(uCt,{children:e.jsx(rx,{className:"h-2 w-2 fill-current"})})}),t]}));mms.displayName=dCt.displayName;const TO=k.forwardRef(({className:s,inset:t,...n},r)=>e.jsx(oCt,{ref:r,className:Ot("px-2 py-1.5 text-sm font-semibold",t&&"pl-8",s),...n}));TO.displayName=oCt.displayName;const j0=k.forwardRef(({className:s,...t},n)=>e.jsx(hCt,{ref:n,className:Ot("-mx-1 my-1 h-px bg-muted",s),...t}));j0.displayName=hCt.displayName;const fms=()=>{const{isAssistant:s,actingAsAgent:t,assignedAgents:n,setActingAsAgent:r,isActingAsSelf:a,setActingAsSelf:i}=cee();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(el,{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(Xn,{className:"h-4 w-4 flex-shrink-0"}),e.jsx("span",{className:"font-medium text-sm",children:"Acting as"})]}),e.jsxs(Au,{children:[e.jsx(Eu,{asChild:!0,children:e.jsxs($,{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(el,{className:"h-4 w-4"}),e.jsx("strong",{children:"My Account"})]}):t?e.jsxs(e.Fragment,{children:[e.jsxs(Wa,{className:"h-5 w-5",children:[e.jsx(eo,{src:t.avatar_url||void 0}),e.jsx(Ka,{className:"text-[10px] bg-primary-foreground/30",children:l(t.name)})]}),e.jsx("strong",{children:t.name})]}):e.jsx("strong",{children:"Select..."}),e.jsx(Go,{className:"h-3 w-3"})]})}),e.jsxs(gu,{align:"start",className:"z-[2147483647]",children:[e.jsxs(Pa,{onClick:i,className:"gap-2",children:[e.jsx(el,{className:"h-4 w-4"}),e.jsx("span",{children:"My Account"}),a&&e.jsx(qe,{variant:"secondary",className:"ml-auto text-[10px]",children:"Current"})]}),e.jsx(j0,{}),n.map(o=>e.jsxs(Pa,{onClick:()=>r(o),className:"gap-2",children:[e.jsxs(Wa,{className:"h-6 w-6",children:[e.jsx(eo,{src:o.avatar_url||void 0}),e.jsx(Ka,{className:"text-[10px]",children:l(o.name)})]}),e.jsx("span",{children:o.name}),!a&&o.id===(t==null?void 0:t.id)&&e.jsx(qe,{variant:"secondary",className:"ml-auto text-[10px]",children:"Current"})]},o.id))]})]})]}),e.jsx(qe,{variant:"secondary",className:"bg-primary-foreground/20 text-primary-foreground border-0 text-xs",children:a?"Personal Mode":"Assistant Mode"})]})})};function rA(){var c,d;const{user:s,isAdmin:t}=ks(),{data:n,isLoading:r}=pt({queryKey:["partnership-membership",s==null?void 0:s.id],enabled:!!(s!=null&&s.id),staleTime:5*60*1e3,queryFn:async()=>{const{data:u}=await V.from("partnership_memberships").select("id, status, package_id, program_id").eq("user_id",s.id).eq("status","active").maybeSingle();if(!u)return null;const[{data:h},{data:m}]=await Promise.all([V.from("partnership_packages").select("*").eq("id",u.package_id).maybeSingle(),V.from("partnership_programs").select("id, name, enabled, brokerage_id").eq("id",u.program_id).maybeSingle()]);return!h||!(m!=null&&m.enabled)?null:{membership:u,pkg:h,program:m}}}),a=k.useMemo(()=>{var u;return new Set(((u=n==null?void 0:n.pkg)==null?void 0:u.included_features)||[])},[n]),i=!!n,l=u=>t||!i?!0:a.has(u),o=u=>{var p,g;const h=((p=n==null?void 0:n.pkg)==null?void 0:p.feature_limits)||{},m=(g=h==null?void 0:h[u])==null?void 0:g.monthly_limit;return typeof m=="number"?m:null};return{isLoading:r,isMember:i,membership:(n==null?void 0:n.membership)??null,pkg:(n==null?void 0:n.pkg)??null,program:(n==null?void 0:n.program)??null,packageKey:((c=n==null?void 0:n.pkg)==null?void 0:c.key)??null,packageName:((d=n==null?void 0:n.pkg)==null?void 0:d.name)??null,features:a,hasFeature:l,limitFor:o,isRestricted:i&&!t}}const AHe={crm:"Contacts & CRM",mass_email:"Mass Email",website:"Agent Website",deals:"Deal Pipeline",listing_exchange:"Listing Exchange",smart_card:"Smart Card",guest_book:"Guest Book",landing_pages:"Landing Pages",learn:"Learn & Academy",community:"Community",quickvid:"QuickVid",reelflow:"ReelFlow",direct_mail:"Direct Mail",levelup_attract:"LevelUp Attract",listing_revival:"Listing Revival",fsbo_breakthrough:"By-Owner Breakthrough",weekly_reels:"Weekly Reels",coaching_access:"Coaching",marketing_studio:"Marketing Studio",video_library:"Video Library",presentations:"Presentations",card_studio:"Card Studio",newsletter:"Newsletters",scheduler:"Scheduler",client_portals:"Client Portals",social:"Social Swag"},EQn=Object.keys(AHe),pms={home:null,crm:"crm",deals:"deals",listings:"listing_exchange",marketing:"marketing_studio",websites:"website",academy:"learn",events:"learn",apps:null,brokerage:"community",more:null},Kit={"mission-control":"crm",contacts:"crm","sphere-gaps":"crm","mass-emails":"mass_email","bulk-email":"mass_email",newsletters:"newsletter","my-card":"smart_card","guest-book":"guest_book","landing-pages":"landing_pages","card-studio":"card_studio","direct-mail":"direct_mail",quickvid:"quickvid","video-library":"video_library",reelflow:"reelflow",scheduler:"scheduler",community:"community",coaching:"coaching_access","my-coach":"coaching_access","client-portals":"client_portals",presentations:"presentations","social-swag":"social",attract:"levelup_attract","listing-revival":"listing_revival",fsbo:"fsbo_breakthrough","weekly-reels":"weekly_reels"},gms={quickvid:"quickvid","smart-card":"smart_card","smart-presentations":"presentations","listing-presentation-studio":"presentations","landing-pages":"landing_pages","guest-book":"guest_book","card-studio":"card_studio","direct-mail":"direct_mail",reelflow:"reelflow","mass-emails":"mass_email","newsletter-pro":"newsletter","listing-studio":"listing_exchange","listing-revival":"listing_revival","fsbo-breakthrough":"fsbo_breakthrough",attract:"levelup_attract",scheduler:"scheduler","client-portals":"client_portals","social-swag":"social","weekly-reels":"weekly_reels"};function xms(s){return s.id in Kit?Kit[s.id]:pms[s.primaryCategory]??null}function yms(s){return gms[s]??null}const vms=[["/mission-control/pipeline","deals"],["/mission-control/transactions","deals"],["/mission-control/tasks","deals"],["/mission-control/client-portals","client_portals"],["/mission-control/scheduler","scheduler"],["/mission-control/guest-book","guest_book"],["/mission-control/landing-pages","landing_pages"],["/mission-control/card-studio","card_studio"],["/mission-control/direct-mail","direct_mail"],["/mission-control/video-library","video_library"],["/mission-control/video","quickvid"],["/mission-control/my-card","smart_card"],["/mission-control/listing-presentations","presentations"],["/mission-control/sent-emails","mass_email"],["/mission-control/listings","listing_exchange"],["/mission-control/listing-studio","listing_exchange"],["/mission-control/cma","listing_exchange"],["/apps/listing-presentation-studio","presentations"],["/apps/listing-revival","listing_revival"],["/apps/fsbo-breakthrough","fsbo_breakthrough"],["/marketing-studio","marketing_studio"],["/social-swag","social"],["/weekly-reels","weekly_reels"],["/newsletters","newsletter"],["/email-campaigns","mass_email"],["/templates","marketing_studio"],["/reelflow","reelflow"],["/attract","levelup_attract"],["/community","community"],["/coaching","coaching_access"],["/my-coach","coaching_access"],["/events","learn"],["/academy","learn"],["/levelup-u","learn"],["/toolbox","learn"],["/programs","learn"]];function pCt(s){let t=null;for(const n of vms){const[r]=n;(s===r||s.startsWith(r+"/")||s.startsWith(r+"?"))&&(!t||r.length>t[0].length)&&(t=n)}return t?t[1]:null}const we=k.forwardRef(({className:s,...t},n)=>e.jsx("div",{ref:n,className:Ot("rounded-lg border bg-card text-card-foreground shadow-sm",s),...t}));we.displayName="Card";const Vt=k.forwardRef(({className:s,...t},n)=>e.jsx("div",{ref:n,className:Ot("flex flex-col space-y-1.5 p-6",s),...t}));Vt.displayName="CardHeader";const Yt=k.forwardRef(({className:s,...t},n)=>e.jsx("h3",{ref:n,className:Ot("text-2xl font-semibold leading-none tracking-tight",s),...t}));Yt.displayName="CardTitle";const vr=k.forwardRef(({className:s,...t},n)=>e.jsx("p",{ref:n,className:Ot("text-sm text-muted-foreground",s),...t}));vr.displayName="CardDescription";const De=k.forwardRef(({className:s,...t},n)=>e.jsx("div",{ref:n,className:Ot("p-6 pt-0",s),...t}));De.displayName="CardContent";const pY=k.forwardRef(({className:s,...t},n)=>e.jsx("div",{ref:n,className:Ot("flex items-center p-6 pt-0",s),...t}));pY.displayName="CardFooter";const Ls=k.forwardRef(({className:s,...t},n)=>e.jsx("textarea",{className:Ot("flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",s),ref:n,...t}));Ls.displayName="Textarea";const zs=o3e,yl=XVe,bms=l3e,TQn=nee,gCt=k.forwardRef(({className:s,...t},n)=>e.jsx(Pq,{ref:n,className:Ot("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}));gCt.displayName=Pq.displayName;const Rs=k.forwardRef(({className:s,children:t,overlayClassName:n,...r},a)=>e.jsxs(bms,{children:[e.jsx(gCt,{className:n}),e.jsxs(Iq,{ref:a,className:Ot("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",s),...r,children:[t,e.jsxs(nee,{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(mr,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));Rs.displayName=Iq.displayName;const Vs=({className:s,...t})=>e.jsx("div",{className:Ot("flex flex-col space-y-1.5 text-center sm:text-left",s),...t});Vs.displayName="DialogHeader";const kr=({className:s,...t})=>e.jsx("div",{className:Ot("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",s),...t});kr.displayName="DialogFooter";const $s=k.forwardRef(({className:s,...t},n)=>e.jsx(tee,{ref:n,className:Ot("text-lg font-semibold leading-none tracking-tight",s),...t}));$s.displayName=tee.displayName;const Cr=k.forwardRef(({className:s,...t},n)=>e.jsx(see,{ref:n,className:Ot("text-sm text-muted-foreground",s),...t}));Cr.displayName=see.displayName;function _ms({featureKey:s,open:t,onOpenChange:n}){const{user:r}=ks(),a=ls(),[i,l]=k.useState(""),{data:o}=pt({queryKey:["partnership-upgrade-requests",r==null?void 0:r.id],enabled:!!(r!=null&&r.id)&&t,queryFn:async()=>{const{data:h}=await V.from("lead_site_upgrade_requests").select("id, feature_key, status").eq("user_id",r.id);return h||[]}}),c=!!(o!=null&&o.some(h=>h.feature_key===s&&h.status!=="declined")),d=Nt({mutationFn:async()=>{const{error:h}=await V.from("lead_site_upgrade_requests").insert({user_id:r.id,feature_key:s,notes:i||null});if(h)throw h},onSuccess:()=>{a.invalidateQueries({queryKey:["partnership-upgrade-requests"]}),ae.success("Request sent — we'll be in touch shortly."),l(""),n(!1)},onError:h=>ae.error((h==null?void 0:h.message)||"Could not send your request")}),u=AHe[s]||s;return e.jsx(zs,{open:t,onOpenChange:n,children:e.jsxs(Rs,{className:"sm:max-w-md",children:[e.jsxs(Vs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(kn,{className:"h-5 w-5 text-primary"}),"Request ",u]}),e.jsxs(Cr,{children:[u," is included with the Signature package. Send a request and we'll get you set up."]})]}),c?e.jsxs("div",{className:"rounded-lg border border-border bg-muted/40 p-4 text-sm flex items-start gap-2",children:[e.jsx(ma,{className:"h-4 w-4 mt-0.5 text-primary"}),e.jsx("span",{children:"You've already requested this. We'll follow up soon."})]}):e.jsx(Ls,{placeholder:"Anything we should know? (optional)",value:i,onChange:h=>l(h.target.value),rows:4}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>n(!1),children:"Close"}),!c&&e.jsx($,{onClick:()=>d.mutate(),disabled:d.isPending,children:d.isPending?"Sending…":"Send request"})]})]})})}function wms({featureKey:s}){const[t,n]=k.useState(!1),r=AHe[s]||s;return e.jsxs("div",{className:"flex items-center justify-center py-16 px-4",children:[e.jsx(we,{className:"max-w-lg w-full border-border/60",children:e.jsxs(De,{className:"p-8 text-center space-y-4",children:[e.jsx("div",{className:"mx-auto h-12 w-12 rounded-full bg-primary/10 flex items-center justify-center",children:e.jsx(fu,{className:"h-6 w-6 text-primary"})}),e.jsxs("h2",{className:"text-2xl font-semibold",children:[r," is a Signature feature"]}),e.jsxs("p",{className:"text-muted-foreground",children:["Your current package doesn't include ",r,". Request access and our team will upgrade your account."]}),e.jsxs($,{onClick:()=>n(!0),className:"gap-2",children:[e.jsx(kn,{className:"h-4 w-4"})," Request access"]})]})}),e.jsx(_ms,{featureKey:s,open:t,onOpenChange:n})]})}const xCt=s=>{const[t,n]=k.useState(null),[r,a]=k.useState(!0);return k.useEffect(()=>{if(!s){a(!1);return}(async()=>{try{const{data:o}=await V.storage.from("avatars").list(`${s}`);if(o&&o.length>0){const{data:c}=V.storage.from("avatars").getPublicUrl(`${s}/${o[0].name}`);n(`${c.publicUrl}?t=${Date.now()}`)}else n(null)}catch(o){console.error("Error fetching avatar:",o),n(null)}finally{a(!1)}})()},[s]),{avatarUrl:t,loading:r,refreshAvatar:async()=>{if(s)try{const{data:l}=await V.storage.from("avatars").list(`${s}`);if(l&&l.length>0){const{data:o}=V.storage.from("avatars").getPublicUrl(`${s}/${l[0].name}`);n(`${o.publicUrl}?t=${Date.now()}`)}}catch(l){console.error("Error refreshing avatar:",l)}}}},yCt=async s=>{const t=new Map;return await Promise.all(s.map(async n=>{try{const{data:r}=await V.storage.from("avatars").list(`${n}`);if(r&&r.length>0){const{data:a}=V.storage.from("avatars").getPublicUrl(`${n}/${r[0].name}`);t.set(n,a.publicUrl)}}catch{}})),t},jms=s=>{const[t,n]=k.useState({isTrial:!1,isExpired:!1,expiresAt:null,daysLeft:null,loading:!0});return k.useEffect(()=>{if(!s){n(a=>({...a,loading:!1}));return}(async()=>{try{const{data:a,error:i}=await V.from("profiles").select("is_trial, trial_expires_at, subscription_status, subscription_end_date").eq("id",s).single();if(i){console.error("Error fetching trial status:",i),n(h=>({...h,loading:!1}));return}const l=(a==null?void 0:a.subscription_status)==="trialing",o=!!(a!=null&&a.is_trial),c=!!(a!=null&&a.trial_expires_at)&&new Date(a.trial_expires_at).getTime()>Date.now()&&(a==null?void 0:a.subscription_status)!=="active",d=l&&(a==null?void 0:a.subscription_end_date)||(a==null?void 0:a.trial_expires_at)||(a==null?void 0:a.subscription_end_date)||null;if((l||o||c)&&!!d&&d){const h=new Date().getTime(),m=new Date(d).getTime(),p=Math.ceil((m-h)/(1e3*60*60*24)),g=p<=0;n({isTrial:!0,isExpired:g,expiresAt:d,daysLeft:g?0:p,loading:!1})}else n({isTrial:!1,isExpired:!1,expiresAt:null,daysLeft:null,loading:!1})}catch(a){console.error("Error in useTrialStatus:",a),n(i=>({...i,loading:!1}))}})()},[s]),t},EHe=()=>{const{data:s,isLoading:t}=pt({queryKey:["feature-flags"],queryFn:async()=>{const{data:r,error:a}=await V.from("feature_flags").select("*");if(a)throw a;return r}}),n=r=>{if(!s)return!1;const a=s.find(i=>i.key===r);return(a==null?void 0:a.enabled)??!1};return{flags:s,isLoading:t,isFeatureEnabled:n,isAgentOSEnabled:n("agent_os_enabled"),isInnerCircleEnabled:n("innercircle_enabled"),isMarketplaceEnabled:n("marketplace")}},Yit="community_last_seen_post_at";function Nms(){const{user:s}=ks(),t=Tu(),[n,r]=k.useState(0),[a,i]=k.useState(null);k.useEffect(()=>{if(!s)return;const o=localStorage.getItem(`${Yit}_${s.id}`);i(o)},[s]),k.useEffect(()=>{if(!s)return;const o=`community_unread_count_${s.id}`,c=2*60*1e3;(async()=>{try{const p=sessionStorage.getItem(o);if(p){const g=JSON.parse(p);if(g.ts&&Date.now()-g.ts{if(!s)return;const o=V.channel("community-new-posts").on("postgres_changes",{event:"INSERT",schema:"public",table:"community_posts"},async c=>{const d=c.new;if(d.user_id===s.id)return;const u=t.pathname==="/community";u||r(x=>x+1);const{data:h}=await V.from("profiles").select("name").eq("id",d.user_id).single(),m=(h==null?void 0:h.name)||"Someone",p=d.content.replace(/@\[([^\]]+)\]\([^)]+\)/g,"@$1"),g=p.length>50?p.substring(0,50)+"...":p;u||ae("New Community Post",{description:`${m}: ${g}`,action:{label:"View",onClick:()=>{window.location.href="/community"}}})}).subscribe();return()=>{V.removeChannel(o)}},[s,t.pathname]);const l=k.useCallback(()=>{if(!s)return;const o=new Date().toISOString();localStorage.setItem(`${Yit}_${s.id}`,o),i(o),r(0)},[s]);return k.useEffect(()=>{t.pathname==="/community"&&n>0&&l()},[t.pathname,n,l]),{unreadCount:n,markAsRead:l}}function kms(){const{isAdmin:s}=ks(),{data:t=0}=pt({queryKey:["wishlist-open-count"],queryFn:async()=>{const{count:n,error:r}=await V.from("wishlist_items").select("*",{count:"exact",head:!0}).eq("status","open");if(r)throw r;return n||0},enabled:s,staleTime:6e4});return{openCount:s?t:0}}const mIe=s=>`levelup:activeTeam:${s}`,Sms=()=>{const s=ai();return pt({queryKey:["user-teams",s],queryFn:async()=>{const{data:t,error:n}=await V.from("team_members").select("id, team_id, role").eq("user_id",s);if(n)throw n;if(!(t!=null&&t.length))return[];const{data:r,error:a}=await V.from("teams").select("*").in("id",t.map(l=>l.team_id));if(a)throw a;const i=new Map((r||[]).map(l=>[l.id,l]));return t.filter(l=>i.has(l.team_id)).map(l=>({membershipId:l.id,teamId:l.team_id,role:l.role,team:i.get(l.team_id)})).sort((l,o)=>{var c,d;return l.role!==o.role?l.role==="team_leader"?-1:1:(((c=l.team)==null?void 0:c.name)||"").localeCompare(((d=o.team)==null?void 0:d.name)||"")})},enabled:!!s,staleTime:5*60*1e3})},gj=()=>{const s=ai(),t=Sms(),n=k.useMemo(()=>t.data||[],[t.data]),[r,a]=k.useState(()=>!s||typeof window>"u"?null:window.localStorage.getItem(mIe(s)));k.useEffect(()=>{!s||typeof window>"u"||a(window.localStorage.getItem(mIe(s)))},[s]);const i=k.useCallback(o=>{a(o),s&&typeof window<"u"&&window.localStorage.setItem(mIe(s),o)},[s]),l=k.useMemo(()=>n.length?n.find(o=>o.teamId===r)||n[0]:null,[n,r]);return{...t,data:l,teams:n,activeTeamId:(l==null?void 0:l.teamId)??null,setActiveTeamId:i}},dz="weekly_reels";function I3e(){const{user:s,loading:t,isAdmin:n}=ks(),{data:r,isLoading:a}=pt({queryKey:["feature-entitlement",dz,s==null?void 0:s.id],enabled:!!s&&!n,staleTime:5*60*1e3,queryFn:async()=>{const{data:i,error:l}=await V.from("feature_entitlements").select("enabled, expires_at, tier").eq("user_id",s.id).eq("feature_key",dz).maybeSingle();if(l)throw l;return i?{hasAccess:i.enabled&&(!i.expires_at||new Date(i.expires_at).getTime()>Date.now()),tier:i.tier??null}:{hasAccess:!1,tier:null}}});return{hasAccess:n||!!(r!=null&&r.hasAccess),tier:n?"admin":(r==null?void 0:r.tier)??null,isLoading:t||!n&&!!s&&a}}const D_=o3e,uee=XVe,Cms=l3e,vCt=k.forwardRef(({className:s,...t},n)=>e.jsx(Pq,{className:Ot("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",s),...t,ref:n}));vCt.displayName=Pq.displayName;const Ams=gF("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"}}),Mb=k.forwardRef(({side:s="right",className:t,children:n,...r},a)=>e.jsxs(Cms,{children:[e.jsx(vCt,{}),e.jsxs(Iq,{ref:a,className:Ot(Ams({side:s}),t),...r,children:[n,e.jsxs(nee,{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(mr,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));Mb.displayName=Iq.displayName;const xj=({className:s,...t})=>e.jsx("div",{className:Ot("flex flex-col space-y-2 text-center sm:text-left",s),...t});xj.displayName="SheetHeader";const bCt=({className:s,...t})=>e.jsx("div",{className:Ot("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",s),...t});bCt.displayName="SheetFooter";const yj=k.forwardRef(({className:s,...t},n)=>e.jsx(tee,{ref:n,className:Ot("text-lg font-semibold text-foreground",s),...t}));yj.displayName=tee.displayName;const hee=k.forwardRef(({className:s,...t},n)=>e.jsx(see,{ref:n,className:Ot("text-sm text-muted-foreground",s),...t}));hee.displayName=see.displayName;var Ems=Object.defineProperty,Tms=(s,t)=>Ems(s,"name",{value:t,configurable:!0});function xU(s,[t,n]){return Math.min(n,Math.max(t,s))}Tms(xU,"clamp");var Mms=Object.defineProperty,Pd=(s,t)=>Mms(s,"name",{value:t,configurable:!0});function _Ct(s,t){return k.useReducer((n,r)=>t[n][r]??n,s)}Pd(_Ct,"useStateMachine");var wCt="ScrollArea",[jCt,MQn]=qm(wCt),[Pms,U2]=jCt(wCt),Ims=k.forwardRef(Pd(function(t,n){const{__scopeScrollArea:r,type:a="hover",dir:i,scrollHideDelay:l=600,...o}=t,[c,d]=k.useState(null),[u,h]=k.useState(null),[m,p]=k.useState(null),[g,x]=k.useState(null),[y,v]=k.useState(null),[_,j]=k.useState(0),[C,A]=k.useState(0),[M,I]=k.useState(!1),[P,R]=k.useState(!1),O=Ao(n,d),B=e4(i);return e.jsx(Pms,{scope:r,type:a,dir:B,scrollHideDelay:l,scrollArea:c,viewport:u,onViewportChange:h,content:m,onContentChange:p,scrollbarX:g,onScrollbarXChange:x,scrollbarXEnabled:M,onScrollbarXEnabledChange:I,scrollbarY:y,onScrollbarYChange:v,scrollbarYEnabled:P,onScrollbarYEnabledChange:R,onCornerWidthChange:j,onCornerHeightChange:A,children:e.jsx(hi.div,{dir:B,...o,ref:O,style:{position:"relative","--radix-scroll-area-corner-width":_+"px","--radix-scroll-area-corner-height":C+"px",...t.style}})})},"ScrollArea")),Lms="ScrollAreaViewport",Rms=k.forwardRef(Pd(function(t,n){const{__scopeScrollArea:r,children:a,nonce:i,...l}=t,o=U2(Lms,r),c=k.useRef(null),d=Ao(n,c,o.onViewportChange);return e.jsxs(e.Fragment,{children:[e.jsx(Dms,{nonce:i}),e.jsx(hi.div,{"data-radix-scroll-area-viewport":"",...l,ref:d,style:{overflowX:o.scrollbarXEnabled?"scroll":"hidden",overflowY:o.scrollbarYEnabled?"scroll":"hidden",...t.style},children:e.jsx("div",{ref:o.onContentChange,style:{minWidth:"100%",display:"table"},children:a})})]})},"ScrollAreaViewport")),Dms=k.memo(Pd(function({nonce:t}){return 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:t})},"ScrollAreaViewportStyle"),(s,t)=>s.nonce===t.nonce),aA="ScrollAreaScrollbar",NCt=k.forwardRef(Pd(function(t,n){const{forceMount:r,...a}=t,i=U2(aA,t.__scopeScrollArea),{onScrollbarXEnabledChange:l,onScrollbarYEnabledChange:o}=i,c=t.orientation==="horizontal";return k.useEffect(()=>(c?l(!0):o(!0),()=>{c?l(!1):o(!1)}),[c,l,o]),i.type==="hover"?e.jsx(Oms,{...a,ref:n,forceMount:r}):i.type==="scroll"?e.jsx(Fms,{...a,ref:n,forceMount:r}):i.type==="auto"?e.jsx(kCt,{...a,ref:n,forceMount:r}):i.type==="always"?e.jsx(THe,{...a,ref:n,"data-state":"visible"}):null},"ScrollAreaScrollbar")),Oms=k.forwardRef(Pd(function(t,n){const{forceMount:r,...a}=t,i=U2(aA,t.__scopeScrollArea),[l,o]=k.useState(!1);return k.useEffect(()=>{const c=i.scrollArea;let d=0;if(c){const u=Pd(()=>{window.clearTimeout(d),o(!0)},"handlePointerEnter"),h=Pd(()=>{d=window.setTimeout(()=>o(!1),i.scrollHideDelay)},"handlePointerLeave");return c.addEventListener("pointerenter",u),c.addEventListener("pointerleave",h),()=>{window.clearTimeout(d),c.removeEventListener("pointerenter",u),c.removeEventListener("pointerleave",h)}}},[i.scrollArea,i.scrollHideDelay]),e.jsx(cx,{present:r||l,children:e.jsx(kCt,{"data-state":l?"visible":"hidden",...a,ref:n})})},"ScrollAreaScrollbarHover")),Fms=k.forwardRef(Pd(function(t,n){const{forceMount:r,...a}=t,i=U2(aA,t.__scopeScrollArea),l=t.orientation==="horizontal",o=fee(()=>d("SCROLL_END"),100),[c,d]=_Ct("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(c==="idle"){const u=window.setTimeout(()=>d("HIDE"),i.scrollHideDelay);return()=>window.clearTimeout(u)}},[c,i.scrollHideDelay,d]),k.useEffect(()=>{const u=i.viewport,h=l?"scrollLeft":"scrollTop";if(u){let m=u[h];const p=Pd(()=>{const g=u[h];m!==g&&(d("SCROLL"),o()),m=g},"handleScroll");return u.addEventListener("scroll",p),()=>u.removeEventListener("scroll",p)}},[i.viewport,l,d,o]),e.jsx(cx,{present:r||c!=="hidden",children:e.jsx(THe,{"data-state":c==="hidden"?"hidden":"visible",...a,ref:n,onPointerEnter:ga(t.onPointerEnter,()=>d("POINTER_ENTER")),onPointerLeave:ga(t.onPointerLeave,()=>d("POINTER_LEAVE"))})})},"ScrollAreaScrollbarScroll")),kCt=k.forwardRef(Pd(function(t,n){const r=U2(aA,t.__scopeScrollArea),{forceMount:a,...i}=t,[l,o]=k.useState(!1),c=t.orientation==="horizontal",d=fee(()=>{if(r.viewport){const u=r.viewport.offsetWidth0&&u<1,onThumbChange:Pd(p=>l.current=p,"onThumbChange"),onThumbPointerUp:Pd(()=>o.current=0,"onThumbPointerUp"),onThumbPointerDown:Pd(p=>o.current=p,"onThumbPointerDown")};function m(p,g){return ECt(p,o.current,c,g)}return Pd(m,"getScrollPosition"),r==="horizontal"?e.jsx(zms,{...h,ref:n,onThumbPositionChange:()=>{if(i.viewport&&l.current){const p=i.viewport.scrollLeft,g=n7e(p,c,i.dir);l.current.style.transform=`translate3d(${g}px, 0, 0)`}},onWheelScroll:p=>{i.viewport&&(i.viewport.scrollLeft=p)},onDragScroll:p=>{i.viewport&&(i.viewport.scrollLeft=m(p,i.dir))}}):r==="vertical"?e.jsx(Bms,{...h,ref:n,onThumbPositionChange:()=>{if(i.viewport&&l.current){const p=i.viewport.scrollTop,g=n7e(p,c);l.current.style.transform=`translate3d(0, ${g}px, 0)`}},onWheelScroll:p=>{i.viewport&&(i.viewport.scrollTop=p)},onDragScroll:p=>{i.viewport&&(i.viewport.scrollTop=m(p))}}):null},"ScrollAreaScrollbarVisible")),zms=k.forwardRef(Pd(function(t,n){const{sizes:r,onSizesChange:a,...i}=t,l=U2(aA,t.__scopeScrollArea),[o,c]=k.useState(),d=k.useRef(null),u=Ao(n,d,l.onScrollbarXChange);return k.useEffect(()=>{d.current&&c(getComputedStyle(d.current))},[d]),e.jsx(CCt,{"data-orientation":"horizontal",...i,ref:u,sizes:r,style:{bottom:0,left:l.dir==="rtl"?"var(--radix-scroll-area-corner-width)":0,right:l.dir==="ltr"?"var(--radix-scroll-area-corner-width)":0,"--radix-scroll-area-thumb-width":mee(r)+"px",...t.style},onThumbPointerDown:h=>t.onThumbPointerDown(h.x),onDragScroll:h=>t.onDragScroll(h.x),onWheelScroll:(h,m)=>{if(l.viewport){const p=l.viewport.scrollLeft+h.deltaX;t.onWheelScroll(p),IHe(p,m)&&h.preventDefault()}},onResize:()=>{d.current&&l.viewport&&o&&a({content:l.viewport.scrollWidth,viewport:l.viewport.offsetWidth,scrollbar:{size:d.current.clientWidth,paddingStart:HZ(o.paddingLeft),paddingEnd:HZ(o.paddingRight)}})}})},"ScrollAreaScrollbarX")),Bms=k.forwardRef(Pd(function(t,n){const{sizes:r,onSizesChange:a,...i}=t,l=U2(aA,t.__scopeScrollArea),[o,c]=k.useState(),d=k.useRef(null),u=Ao(n,d,l.onScrollbarYChange);return k.useEffect(()=>{d.current&&c(getComputedStyle(d.current))},[d]),e.jsx(CCt,{"data-orientation":"vertical",...i,ref:u,sizes:r,style:{top:0,right:l.dir==="ltr"?0:void 0,left:l.dir==="rtl"?0:void 0,bottom:"var(--radix-scroll-area-corner-height)","--radix-scroll-area-thumb-height":mee(r)+"px",...t.style},onThumbPointerDown:h=>t.onThumbPointerDown(h.y),onDragScroll:h=>t.onDragScroll(h.y),onWheelScroll:(h,m)=>{if(l.viewport){const p=l.viewport.scrollTop+h.deltaY;t.onWheelScroll(p),IHe(p,m)&&h.preventDefault()}},onResize:()=>{d.current&&l.viewport&&o&&a({content:l.viewport.scrollHeight,viewport:l.viewport.offsetHeight,scrollbar:{size:d.current.clientHeight,paddingStart:HZ(o.paddingTop),paddingEnd:HZ(o.paddingBottom)}})}})},"ScrollAreaScrollbarY")),[$ms,SCt]=jCt(aA),CCt=k.forwardRef(Pd(function(t,n){const{__scopeScrollArea:r,sizes:a,hasThumb:i,onThumbChange:l,onThumbPointerUp:o,onThumbPointerDown:c,onThumbPositionChange:d,onDragScroll:u,onWheelScroll:h,onResize:m,...p}=t,g=U2(aA,r),[x,y]=k.useState(null),v=Ao(n,y),_=k.useRef(null),j=k.useRef(""),C=g.viewport,A=a.content-a.viewport,M=sp(h),I=sp(d),P=fee(m,10);function R(O){if(_.current){const B=O.clientX-_.current.left,U=O.clientY-_.current.top;u({x:B,y:U})}}return Pd(R,"handleDragScroll"),k.useEffect(()=>{const O=Pd(B=>{const U=B.target;(x==null?void 0:x.contains(U))&&M(B,A)},"handleWheel");return document.addEventListener("wheel",O,{passive:!1}),()=>document.removeEventListener("wheel",O,{passive:!1})},[C,x,A,M]),k.useEffect(I,[a,I]),MO(x,P),MO(g.content,P),e.jsx($ms,{scope:r,scrollbar:x,hasThumb:i,onThumbChange:sp(l),onThumbPointerUp:sp(o),onThumbPositionChange:I,onThumbPointerDown:sp(c),children:e.jsx(hi.div,{...p,ref:v,style:{position:"absolute",...p.style},onPointerDown:ga(t.onPointerDown,O=>{O.button===0&&(O.target.setPointerCapture(O.pointerId),_.current=x.getBoundingClientRect(),j.current=document.body.style.webkitUserSelect,document.body.style.webkitUserSelect="none",g.viewport&&(g.viewport.style.scrollBehavior="auto"),R(O))}),onPointerMove:ga(t.onPointerMove,R),onPointerUp:ga(t.onPointerUp,O=>{const B=O.target;B.hasPointerCapture(O.pointerId)&&B.releasePointerCapture(O.pointerId),document.body.style.webkitUserSelect=j.current,g.viewport&&(g.viewport.style.scrollBehavior=""),_.current=null})})})},"ScrollAreaScrollbarImpl")),s7e="ScrollAreaThumb",Ums=k.forwardRef(Pd(function(t,n){const{forceMount:r,...a}=t,i=SCt(s7e,t.__scopeScrollArea);return e.jsx(cx,{present:r||i.hasThumb,children:e.jsx(qms,{ref:n,...a})})},"ScrollAreaThumb")),qms=k.forwardRef(Pd(function(t,n){const{__scopeScrollArea:r,style:a,...i}=t,l=U2(s7e,r),o=SCt(s7e,r),{onThumbPositionChange:c}=o,d=Ao(n,o.onThumbChange),u=k.useRef(void 0),h=fee(()=>{u.current&&(u.current(),u.current=void 0)},100);return k.useEffect(()=>{const m=l.viewport;if(m){const p=Pd(()=>{if(h(),!u.current){const g=Gms(m,c);u.current=g,c()}},"handleScroll");return c(),m.addEventListener("scroll",p),()=>m.removeEventListener("scroll",p)}},[l.viewport,h,c]),e.jsx(hi.div,{"data-state":o.hasThumb?"visible":"hidden",...i,ref:d,style:{width:"var(--radix-scroll-area-thumb-width)",height:"var(--radix-scroll-area-thumb-height)",...a},onPointerDownCapture:ga(t.onPointerDownCapture,m=>{const g=m.target.getBoundingClientRect(),x=m.clientX-g.left,y=m.clientY-g.top;o.onThumbPointerDown({x,y})}),onPointerUp:ga(t.onPointerUp,o.onThumbPointerUp)})},"ScrollAreaThumbImpl")),ACt="ScrollAreaCorner",Vms=k.forwardRef(Pd(function(t,n){const r=U2(ACt,t.__scopeScrollArea),a=!!(r.scrollbarX&&r.scrollbarY);return r.type!=="scroll"&&a?e.jsx(Hms,{...t,ref:n}):null},"ScrollAreaCorner")),Hms=k.forwardRef(Pd(function(t,n){const{__scopeScrollArea:r,...a}=t,i=U2(ACt,r),[l,o]=k.useState(0),[c,d]=k.useState(0),u=!!(l&&c),{onCornerWidthChange:h,onCornerHeightChange:m}=i;return MO(i.scrollbarX,()=>{var g;const p=((g=i.scrollbarX)==null?void 0:g.offsetHeight)||0;i.onCornerHeightChange(p),d(p)}),MO(i.scrollbarY,()=>{var g;const p=((g=i.scrollbarY)==null?void 0:g.offsetWidth)||0;i.onCornerWidthChange(p),o(p)}),k.useEffect(()=>()=>{h(0),m(0)},[h,m]),u?e.jsx(hi.div,{...a,ref:n,style:{width:l,height:c,position:"absolute",right:i.dir==="ltr"?0:void 0,left:i.dir==="rtl"?0:void 0,bottom:0,...t.style}}):null},"ScrollAreaCornerImpl"));function HZ(s){return s?parseInt(s,10):0}Pd(HZ,"toInt");function MHe(s,t){const n=s/t;return isNaN(n)?0:n}Pd(MHe,"getThumbRatio");function mee(s){const t=MHe(s.viewport,s.content),n=s.scrollbar.paddingStart+s.scrollbar.paddingEnd,r=(s.scrollbar.size-n)*t;return Math.max(r,18)}Pd(mee,"getThumbSize");function ECt(s,t,n,r="ltr"){const a=mee(n),i=a/2,l=t||i,o=a-l,c=n.scrollbar.paddingStart+l,d=n.scrollbar.size-n.scrollbar.paddingEnd-o,u=n.content-n.viewport,h=r==="ltr"?[0,u]:[u*-1,0];return PHe([c,d],h)(s)}Pd(ECt,"getScrollPositionFromPointer");function n7e(s,t,n="ltr"){const r=mee(t),a=t.scrollbar.paddingStart+t.scrollbar.paddingEnd,i=t.scrollbar.size-a,l=t.content-t.viewport,o=i-r,c=n==="ltr"?[0,l]:[l*-1,0],d=xU(s,c);return PHe([0,l],[0,o])(d)}Pd(n7e,"getThumbOffsetFromScroll");function PHe(s,t){return n=>{if(s[0]===s[1]||t[0]===t[1])return t[0];const r=(t[1]-t[0])/(s[1]-s[0]);return t[0]+r*(n-s[0])}}Pd(PHe,"linearScale");function IHe(s,t){return s>0&&s{})=>{let n={left:s.scrollLeft,top:s.scrollTop},r=0;return Pd(function a(){const i={left:s.scrollLeft,top:s.scrollTop},l=n.left!==i.left,o=n.top!==i.top;(l||o)&&t(),n=i,r=window.requestAnimationFrame(a)},"loop")(),()=>window.cancelAnimationFrame(r)},"addUnlinkedScrollListener");function fee(s,t){const n=sp(s),r=k.useRef(0);return k.useEffect(()=>()=>window.clearTimeout(r.current),[]),k.useCallback(()=>{window.clearTimeout(r.current),r.current=window.setTimeout(n,t)},[n,t])}Pd(fee,"useDebounceCallback");function MO(s,t){const n=sp(t);_m(()=>{let r=0;if(s){const a=new ResizeObserver(()=>{cancelAnimationFrame(r),r=window.requestAnimationFrame(n)});return a.observe(s),()=>{window.cancelAnimationFrame(r),a.unobserve(s)}}},[s,n])}Pd(MO,"useResizeObserver");var TCt=Ims,Wms=Rms,Kms=Vms;const Eo=k.forwardRef(({className:s,children:t,...n},r)=>e.jsxs(TCt,{ref:r,className:Ot("relative overflow-hidden",s),...n,children:[e.jsx(Wms,{className:"h-full w-full rounded-[inherit]",children:t}),e.jsx(Uq,{}),e.jsx(Kms,{})]}));Eo.displayName=TCt.displayName;const Uq=k.forwardRef(({className:s,orientation:t="vertical",...n},r)=>e.jsx(NCt,{ref:r,orientation:t,className:Ot("flex touch-none select-none transition-colors",t==="vertical"&&"h-full w-2.5 border-l border-l-transparent p-[1px]",t==="horizontal"&&"h-2.5 flex-col border-t border-t-transparent p-[1px]",s),...n,children:e.jsx(Ums,{className:"relative flex-1 rounded-full bg-border"})}));Uq.displayName=NCt.displayName;const Yms="/assets/levelup-logo-Eif24dqY.png",Zms="/assets/levelup-logo-icon-C-7iromj.png",Xms="/assets/levelup-logo-mobile-B9skSjUG.png";var pee=s=>s.type==="checkbox",L3e=s=>s.type==="file",r3=s=>s instanceof Date,a0=s=>s==null;const LHe=s=>typeof s=="object";var Pp=s=>!a0(s)&&!Array.isArray(s)&&LHe(s)&&!r3(s),r7e=s=>Pp(s)&&s.target?pee(s.target)?s.target.checked:L3e(s.target)?s.target.files:s.target.value:s,MCt=(s,t)=>t.split(".").some((n,r,a)=>!isNaN(Number(n))&&s.has(a.slice(0,r).join("."))),PCt=s=>{const t=s.constructor&&s.constructor.prototype;return Pp(t)&&t.hasOwnProperty("isPrototypeOf")},R3e=typeof window<"u"&&typeof window.HTMLElement<"u"&&typeof document<"u";function Kf(s){if(s instanceof Date)return new Date(s);const t=typeof FileList<"u"&&s instanceof FileList;if(R3e&&(s instanceof Blob||t))return s;const n=Array.isArray(s);if(!n&&!(Pp(s)&&PCt(s)))return s;const r=n?[]:Object.create(Object.getPrototypeOf(s));for(const a in s)Object.prototype.hasOwnProperty.call(s,a)&&(r[a]=Kf(s[a]));return r}const mE={BLUR:"blur",FOCUS_OUT:"focusout",CHANGE:"change",SUBMIT:"submit",TRIGGER:"trigger",VALID:"valid"},YN={onBlur:"onBlur",onChange:"onChange",onSubmit:"onSubmit",onTouched:"onTouched",all:"all"},yN={max:"max",min:"min",maxLength:"maxLength",minLength:"minLength",pattern:"pattern",required:"required",validate:"validate"},ICt="root",RHe=["__proto__","constructor","prototype"],Qms=/^\w*$/;var yU=s=>Qms.test(s),xf=s=>s===void 0;const Jms=/[.[\]'"]/;var GZ=s=>s.split(Jms).filter(Boolean),pi=(s,t,n)=>{if(!t||!Pp(s))return n;const r=yU(t)?[t]:GZ(t);if(r.some(i=>RHe.includes(i)))return n;const a=r.reduce((i,l)=>a0(i)?void 0:i[l],s);return xf(a)||a===s?xf(s[t])?n:s[t]:a},Fw=s=>typeof s=="boolean",n1=s=>typeof s=="function",xh=(s,t,n)=>{let r=-1;const a=yU(t)?[t]:GZ(t),i=a.length,l=i-1;for(;++rzt.useContext(DHe);var LCt=(s,t,n,r=!0)=>{const a={};for(const i in s)Object.defineProperty(a,i,{get:()=>{const l=i;return t._proxyFormState[l]!==YN.all&&(t._proxyFormState[l]=!r||YN.all),n&&(n[l]=!0),s[l]}});return a};const FHe=R3e?zt.useLayoutEffect:zt.useEffect;var a7e=s=>a0(s)||!LHe(s);const Zit=(s,t)=>t.length===0&&!Array.isArray(s)&&!PCt(s);function l_(s,t,n=new WeakMap){if(s===t)return!0;if(a7e(s)||a7e(t))return Object.is(s,t);if(r3(s)&&r3(t))return Object.is(s.getTime(),t.getTime());const r=Object.keys(s),a=Object.keys(t);if(r.length!==a.length)return!1;if(Zit(s,r)||Zit(t,a))return Object.is(s,t);if(!r.length&&Array.isArray(s)!==Array.isArray(t))return!1;const i=n.get(s);if(i&&i.has(t))return!0;if(i)i.add(t);else{const l=new WeakSet;l.add(t),n.set(s,l)}for(const l of r){const o=s[l];if(!(l in t))return!1;if(l!=="ref"){const c=t[l];if(r3(o)&&r3(c)||(Pp(o)||Array.isArray(o))&&(Pp(c)||Array.isArray(c))?!l_(o,c,n):!Object.is(o,c))return!1}}return!0}function zHe(){const s=zt.useRef(!1),t=zt.useRef(void 0),n=zt.useCallback((a,i,l)=>{if(a&&s.current){const o=i();l_(t.current,o)||l(o)}s.current=!0},[]),r=zt.useCallback((a,i)=>{a&&(t.current=Kf(i()))},[]);return{resyncIfNeeded:n,snapshot:r}}function efs(s){const t=OHe(),{control:n=t,disabled:r,name:a,exact:i}=s||{},[l,o]=zt.useState(()=>({...n._formState,defaultValues:n._defaultValues})),c=zt.useRef({isDirty:!1,isLoading:!1,dirtyFields:!1,touchedFields:!1,validatingFields:!1,isValidating:!1,isValid:!1,errors:!1}),{resyncIfNeeded:d,snapshot:u}=zHe();return FHe(()=>{const h=()=>({...n._formState,defaultValues:n._defaultValues});d(!r,h,o);const m=n._subscribe({name:a,formState:c.current,exact:i,callback:p=>{!r&&o({...n._formState,...p,defaultValues:n._defaultValues})}});return()=>{m(),u(!r,h)}},[a,r,i,d,u]),zt.useEffect(()=>{c.current.isValid&&n._setValid(!0)},[n]),zt.useMemo(()=>LCt(l,n,c.current,!1),[l,n])}var X0=s=>typeof s=="string",i7e=(s,t,n,r,a)=>X0(s)?(r&&t.watch.add(s),pi(n,s,a)):Array.isArray(s)?s.map(i=>(r&&t.watch.add(i),pi(n,i))):(r&&(t.watchAll=!0),n);function tfs(s){const t=OHe(),{control:n=t,name:r,defaultValue:a,disabled:i,exact:l,compute:o}=s||{},c=zt.useRef(a),d=zt.useRef(o),u=zt.useRef(void 0),h=zt.useRef(n),m=zt.useRef(r);d.current=o;const[p,g]=zt.useState(()=>{const P=n._getWatch(r,c.current);return d.current?d.current(P):P}),x=zt.useCallback(P=>{const R=i7e(r,n._names,P||n._formValues,!1,c.current);return d.current?d.current(R):R},[n._formValues,n._names,r]),y=zt.useCallback(P=>{if(!i){const R=i7e(r,n._names,P||n._formValues,!1,c.current);if(d.current){const O=d.current(R);l_(O,u.current)||(g(O),u.current=O)}else g(R)}},[n._formValues,n._names,i,r]),{resyncIfNeeded:v,snapshot:_}=zHe(),j=zt.useRef(y);j.current=y;const C=zt.useRef(x);C.current=x,FHe(()=>{h.current!==n||!l_(m.current,r)?(h.current=n,m.current=r,j.current()):v(!i,()=>C.current(),R=>{g(R),u.current=R});const P=n._subscribe({name:r,formState:{values:!0},exact:l,callback:R=>{j.current(R.values)}});return()=>{P(),_(!i,()=>C.current())}},[n,l,r,i,v,_]),zt.useEffect(()=>n._removeUnmounted());const A=h.current!==n,M=m.current,I=zt.useMemo(()=>{if(i)return null;const P=!A&&!l_(M,r);return A||P?x():null},[i,A,r,M,x]);return I!==null?I:p}function sfs(s){const t=OHe(),{name:n,disabled:r,control:a=t,shouldUnregister:i,defaultValue:l,exact:o=!0}=s,c=MCt(a._names.array,n),d=zt.useMemo(()=>pi(a._formValues,n,pi(a._defaultValues,n,l)),[a,n,l]),u=tfs({control:a,name:n,defaultValue:d,exact:o}),h=efs({control:a,name:n,exact:o}),m=zt.useRef(s),p=zt.useRef(null),g=zt.useRef(a.register(n,{...s.rules,value:u,...Fw(s.disabled)?{disabled:s.disabled}:{}}));m.current=s;const x=zt.useMemo(()=>Object.defineProperties({},{invalid:{enumerable:!0,get:()=>!!pi(h.errors,n)},isDirty:{enumerable:!0,get:()=>!!pi(h.dirtyFields,n)},isTouched:{enumerable:!0,get:()=>!!pi(h.touchedFields,n)},isValidating:{enumerable:!0,get:()=>!!pi(h.validatingFields,n)},error:{enumerable:!0,get:()=>pi(h.errors,n)}}),[h,n]),y=zt.useCallback(C=>{const A=r7e(C);return pi(a._fields,n)||(g.current=a.register(n,{...m.current.rules,value:A})),g.current.onChange({target:{value:r7e(C),name:n},type:mE.CHANGE})},[n,a]),v=zt.useCallback(()=>g.current.onBlur({target:{value:pi(a._formValues,n),name:n},type:mE.BLUR}),[n,a._formValues]),_=zt.useCallback(C=>{C&&(p.current={focus:()=>n1(C.focus)&&C.focus(),select:()=>n1(C.select)&&C.select(),setCustomValidity:M=>n1(C.setCustomValidity)&&C.setCustomValidity(M),reportValidity:()=>n1(C.reportValidity)&&C.reportValidity()});const A=pi(a._fields,n);A&&A._f&&C&&(A._f.ref=p.current)},[a._fields,n]),j=zt.useMemo(()=>({name:n,value:u,...Fw(r)||h.disabled?{disabled:h.disabled||r}:{},onChange:y,onBlur:v,ref:_}),[n,r,h.disabled,y,v,_,u]);return zt.useEffect(()=>{const C=a._options.shouldUnregister||i;g.current=a.register(n,{...m.current.rules,...Fw(m.current.disabled)?{disabled:m.current.disabled}:{}});const A=(M,I)=>{const P=pi(a._fields,M);P&&P._f&&(P._f.mount=I)};if(A(n,!0),C){const M=Kf(pi(i?a._defaultValues:a._options.values||a._defaultValues,n,pi(a._options.defaultValues,n,m.current.defaultValue)));xh(a._defaultValues,n,M),xf(pi(a._formValues,n))&&xh(a._formValues,n,M)}if(!c&&a.register(n),p.current){const M=pi(a._fields,n);M&&M._f&&(M._f.ref=p.current)}return()=>{(c?C&&!a._state.action:C)?a.unregister(n):A(n,!1)}},[n,a,c,i]),zt.useEffect(()=>{a._setDisabledField({disabled:r,name:n})},[r,n,a]),zt.useMemo(()=>({field:j,formState:h,fieldState:x}),[j,h,x])}const nfs=s=>s.render(sfs(s));var Kne=s=>({isOnSubmit:!s||s===YN.onSubmit,isOnBlur:s===YN.onBlur,isOnChange:s===YN.onChange,isOnAll:s===YN.all,isOnTouch:s===YN.onTouched}),fIe=(s,t,n)=>{if(n)return!1;if(t.watchAll||t.watch.has(s))return!0;for(const r of t.watch)if(s.startsWith(r)&&s.charAt(r.length)===".")return!0;return!1};const gY=(s,t,n,r)=>{for(const a of n||Object.keys(s)){if(a==="_f")continue;const i=n?pi(s,a):s[a];if(i){const{_f:l}=i;if(l){if(l.refs&&l.refs[0]&&t(l.refs[0],a)&&!r)return!0;if(l.ref&&t(l.ref,l.name)&&!r)return!0;if(gY(i,t))break}else if((Pp(i)||Array.isArray(i))&&gY(i,t))break}}};var Xit=(s,t,n)=>{const r=pi(s,n),a=Array.isArray(r)?r:[];return xh(a,ICt,t[n]),xh(s,n,a),s},$0=s=>Pp(s)&&!Object.keys(s).length,aSe=s=>{if(!R3e)return!1;const t=s?s.ownerDocument:0;return s instanceof(t&&t.defaultView?t.defaultView.HTMLElement:HTMLElement)},BHe=s=>s.type==="radio",iSe=s=>s instanceof RegExp,RCt=(s,t,n,r,a)=>t?{...n[s],types:{...n[s]&&n[s].types?n[s].types:{},[r]:a||!0}}:{};const Qit={value:!1,isValid:!1},Jit={value:!0,isValid:!0};var DCt=s=>{if(Array.isArray(s)){if(s.length>1){const t=s.filter(n=>n&&n.checked&&!n.disabled).map(n=>n.value);return{value:t,isValid:!!t.length}}return s[0].checked&&!s[0].disabled?s[0].attributes&&!xf(s[0].attributes.value)?xf(s[0].value)||s[0].value===""?Jit:{value:s[0].value,isValid:!0}:Jit:Qit}return Qit};const eot={isValid:!1,value:null};var OCt=s=>Array.isArray(s)?s.reduce((t,n)=>n&&n.checked&&!n.disabled?{isValid:!0,value:n.value}:t,eot):eot;function tot(s,t,n="validate"){if(X0(s)||Array.isArray(s)&&s.every(X0)||Fw(s)&&!s)return{type:n,message:X0(s)?s:"",ref:t}}var U7=s=>Pp(s)&&!iSe(s)?s:{value:s,message:""},sot=async(s,t,n,r,a,i)=>{const{ref:l,refs:o,required:c,maxLength:d,minLength:u,min:h,max:m,pattern:p,validate:g,name:x,valueAsNumber:y,mount:v}=s._f,_=pi(n,x);if(!v||t.has(x))return{};const j=o?o[0]:l,C=U=>{if(a&&j.reportValidity){const G=Fw(U)?"":U||"";o?o.forEach(H=>H.setCustomValidity(G)):j.setCustomValidity(G),j.reportValidity()}},A={},M=BHe(l),I=pee(l),P=M||I,R=(y||L3e(l))&&xf(l.value)&&xf(_)||aSe(l)&&l.value===""||_===""||Array.isArray(_)&&!_.length,O=RCt.bind(null,x,r,A),B=(U,G,H,Y=yN.maxLength,se=yN.minLength)=>{const ee=U?G:H;A[x]={type:U?Y:se,message:ee,ref:l,...O(U?Y:se,ee)}};if(i?!Array.isArray(_)||!_.length:c&&(!P&&(R||a0(_))||Fw(_)&&!_||I&&!DCt(o).isValid||M&&!OCt(o).isValid)){const{value:U,message:G}=X0(c)?{value:!!c,message:c}:U7(c);if(U&&(A[x]={type:yN.required,message:G,ref:j,...O(yN.required,G)},!r))return C(G),A}if(!R&&(!a0(h)||!a0(m))){let U,G;const H=U7(m),Y=U7(h);if(!a0(_)&&!r3(_)&&!isNaN(_)){const se=l.valueAsNumber||_&&+_;a0(H.value)||(U=se>H.value),a0(Y.value)||(G=senew Date(new Date().toDateString()+" "+Q),oe=l.type=="time",me=l.type=="week";X0(H.value)&&_&&(U=oe?ee(_)>ee(H.value):me?_>H.value:se>new Date(H.value)),X0(Y.value)&&_&&(G=oe?ee(_)+U.value,Y=!a0(G.value)&&_.length<+G.value;if((H||Y)&&(B(H,U.message,G.message),!r))return C(A[x].message),A}if(p&&!R&&X0(_)){const{value:U,message:G}=U7(p);if(iSe(U)&&!_.match(U)&&(A[x]={type:yN.pattern,message:G,ref:l,...O(yN.pattern,G)},!r))return C(G),A}if(g){if(n1(g)){const U=await g(_,n),G=tot(U,j);if(G&&(A[x]={...G,...O(yN.validate,G.message)},!r))return C(G.message),A}else if(Pp(g)){let U={};for(const G in g){if(!$0(U)&&!r)break;const H=tot(await g[G](_,n),j,G);H&&(U={...H,...O(G,H.message)},C(H.message),r&&(A[x]=U))}if(!$0(U)&&(A[x]={ref:j,...U},!r))return A}}return C(!0),A},J2e=s=>Array.isArray(s)?s:[s],FCt=s=>Array.isArray(s)?s.filter(Boolean):[];function rfs(s,t){const n=t.length-1;let r=0;for(;rRHe.includes(String(l))))return s;const r=n.length===1?s:rfs(s,n),a=n.length-1,i=n[a];return r&&delete r[i],a!==0&&(Pp(r)&&$0(r)||Array.isArray(r)&&afs(r))&&qg(s,n.slice(0,-1)),s}const zCt=s=>{const t={};for(const n of Object.keys(s))if(LHe(s[n])&&s[n]!==null&&!r3(s[n])){const r=zCt(s[n]);for(const a of Object.keys(r))t[`${n}.${a}`]=r[a]}else t[n]=s[n];return t},$He=zt.createContext(null);$He.displayName="HookFormContext";const ifs=()=>zt.useContext($He),ofs=({children:s,watch:t,getValues:n,getFieldState:r,setError:a,clearErrors:i,setValue:l,setValues:o,trigger:c,formState:d,resetField:u,reset:h,resetDefaultValues:m,handleSubmit:p,unregister:g,control:x,register:y,setFocus:v,subscribe:_})=>{const j=zt.useMemo(()=>({watch:t,getValues:n,getFieldState:r,setError:a,clearErrors:i,setValue:l,setValues:o,trigger:c,formState:d,resetField:u,reset:h,resetDefaultValues:m,handleSubmit:p,unregister:g,control:x,register:y,setFocus:v,subscribe:_}),[i,x,d,r,n,p,y,h,m,u,a,v,l,o,_,c,g,t]);return zt.createElement($He.Provider,{value:j},zt.createElement(DHe.Provider,{value:j.control},s))};var not=()=>{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 BCt(s,t){const n={};for(const r in s)if(s.hasOwnProperty(r)){const a=s[r],i=t[r];if(a&&Pp(a)&&i){const l=BCt(a,i);Pp(l)&&(n[r]=l)}else s[r]&&(n[r]=i)}return n}var $Ct=s=>s.type==="select-multiple",lfs=s=>BHe(s)||pee(s),pIe=s=>aSe(s)&&s.isConnected;function rot(s){return Array.isArray(s)||Pp(s)}function UCt(s,t,n="",r=[]){for(const a in s){const i=n?`${n}.${a}`:a,l=s[a];rot(l)&&rot(pi(t,i))?UCt(l,t,i,r):r.push(i)}return r}var cfs=s=>{for(const t in s)if(n1(s[t]))return!0;return!1};function qCt(s){return Array.isArray(s)||Pp(s)&&!cfs(s)}function VCt(s){return!!(s&&"_f"in s)}function HCt(s){return Array.isArray(s)?!s.some(t=>!xf(t)):!Object.keys(s).length}function o7e(s,t){Array.isArray(s)?s[t]=void 0:delete s[t]}function l7e(s,t={},n){for(const r in s){const a=s[r],i=n&&n[r];qCt(a)&&(!Array.isArray(a)||!VCt(i))?(t[r]=Array.isArray(a)?[]:{},l7e(a,t[r],i),HCt(t[r])&&o7e(t,r)):xf(a)||(t[r]=!0)}return t}function ER(s,t,n,r){n||(n=l7e(t,{},r));for(const a in s){const i=s[a],l=r&&r[a];qCt(i)&&(!Array.isArray(i)||!VCt(l))?(xf(t)||a7e(n[a])?n[a]=l7e(i,Array.isArray(i)?[]:{},l):ER(i,a0(t)?{}:t[a],n[a],l),HCt(n[a])&&o7e(n,a)):l_(i,t[a])?o7e(n,a):n[a]=!0}return n}var GCt=(s,{valueAsNumber:t,valueAsDate:n,setValueAs:r})=>xf(s)?s:t?s===""?NaN:s&&+s:n&&X0(s)?new Date(s):r?r(s):s;function aot(s){const t=s.ref;return L3e(t)?t.files:BHe(t)?OCt(s.refs).value:$Ct(t)?[...t.selectedOptions].map(({value:n})=>n):pee(t)?DCt(s.refs).value:GCt(t.value,s)}var dfs=(s,t,n,r)=>{const a={};for(const i of s){const l=pi(t,i);l&&xh(a,i,l._f)}return{criteriaMode:n,names:[...s],fields:a,shouldUseNativeValidation:r}},nG=s=>xf(s)?s:iSe(s)?s.source:Pp(s)?iSe(s.value)?s.value.source:s.value:s;const iot="AsyncFunction";var ufs=s=>{if(!s||!s.validate)return!1;if(n1(s.validate))return s.validate.constructor.name===iot;if(Pp(s.validate)){for(const t in s.validate)if(s.validate[t].constructor.name===iot)return!0}return!1},hfs=s=>s.mount&&(s.required||s.min||s.max||s.maxLength||s.minLength||s.pattern||s.validate);function oot(s,t,n){const r=pi(s,n);if(r||yU(n))return{error:r,name:n};const a=n.split(".");for(;a.length;){const i=a.join("."),l=pi(t,i),o=pi(s,i);if(l&&!Array.isArray(l)&&n!==i)return{name:n};if(o&&o.type)return{name:i,error:o};if(o&&o.root&&o.root.type)return{name:`${i}.root`,error:o.root};a.pop()}return{name:n}}var mfs=(s,t,n,r)=>{n(s);const a=Object.keys(s).filter(i=>i!=="name");return!a.length||r&&a.length>=Object.keys(t).length||a.find(i=>t[i]===(!r||YN.all))},ffs=(s,t,n)=>!s||!t||s===t||J2e(s).some(r=>r&&(n?r===t||r.startsWith(t+"."):r.startsWith(t)||t.startsWith(r))),pfs=(s,t,n,r,a)=>a.isOnAll?!1:!n&&a.isOnTouch?!(t||s):(n?r.isOnBlur:a.isOnBlur)?!s:(n?r.isOnChange:a.isOnChange)?s:!0,gfs=(s,t)=>{const n=pi(s,t);!FCt(n).length&&!(n!=null&&n.root)&&qg(s,t)};const xfs={mode:YN.onSubmit,reValidateMode:YN.onChange,shouldFocusError:!0},gIe="form",yfs=(s,t)=>{for(const n in s)n in t||delete s[n];Object.assign(s,t)},WCt={submitCount:0,isDirty:!1,isReady:!1,isValidating:!1,isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,touchedFields:{},dirtyFields:{},validatingFields:{}};function vfs(s={}){let t={...xfs,...s},n={...Kf(WCt),isLoading:n1(t.defaultValues),errors:t.errors||{},disabled:t.disabled||!1},r={},a=Pp(t.defaultValues)||Pp(t.values)?Kf(t.defaultValues||t.values)||{}:{},i=t.shouldUnregister?{}:Kf(a),l={action:!1,actionArrayLengths:new Map,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};const c={},d={};let u=0,h=Kne(t.mode),m=Kne(t.reValidateMode);const p={isDirty:!1,dirtyFields:!1,validatingFields:!1,touchedFields:!1,isValidating:!1,isValid:!1,errors:!1},g={...p};let x={...g};const y={array:not(),state:not()};let v=0;const _=t.criteriaMode===YN.all,j=(st,dt)=>jt=>{clearTimeout(d[st]),d[st]=setTimeout(dt,jt)},C=async st=>{if(!l.keepIsValid&&!t.disabled&&(g.isValid||x.isValid||st)){const dt=++v;let jt;t.resolver?(jt=$0((await Y()).errors),dt===v&&A()):jt=await oe({fields:r,onlyCheckValid:!0,eventType:mE.VALID}),dt===v&&jt!==n.isValid&&y.state.next({isValid:jt})}},A=(st,dt)=>{!t.disabled&&(g.isValidating||g.validatingFields||x.isValidating||x.validatingFields)&&((st||Array.from(o.mount)).forEach(jt=>{jt&&(dt?xh(n.validatingFields,jt,dt):qg(n.validatingFields,jt))}),y.state.next({validatingFields:n.validatingFields,isValidating:!$0(n.validatingFields)}))},M=()=>{n.dirtyFields=ER(a,i,void 0,r)},I=(st,dt=[],jt,gt,rs=!0,Ns=!0)=>{if(gt&&jt&&!t.disabled){if(l.action=!0,!l.actionArrayLengths.has(st)){const us=pi(r,st);l.actionArrayLengths.set(st,Array.isArray(us)?us.length:0)}if(Ns&&Array.isArray(pi(r,st))){const us=jt(pi(r,st),gt.argA,gt.argB);rs&&xh(r,st,us)}if(Ns&&Array.isArray(pi(n.errors,st))){const us=pi(n.errors,st),Bs=us.root,Ts=jt(us,gt.argA,gt.argB)||us;Bs&&(Ts.root=Bs),rs&&xh(n.errors,st,Ts),gfs(n.errors,st)}if((g.touchedFields||x.touchedFields)&&Ns&&Array.isArray(pi(n.touchedFields,st))){const us=jt(pi(n.touchedFields,st),gt.argA,gt.argB);rs&&xh(n.touchedFields,st,us)}(g.dirtyFields||x.dirtyFields)&&M(),y.state.next({name:st,isDirty:Q(st,dt),dirtyFields:n.dirtyFields,errors:n.errors,isValid:n.isValid})}else xh(i,st,dt)},P=(st,dt)=>{xh(n.errors,st,dt),n.errors={...n.errors},y.state.next({errors:n.errors})},R=st=>{n.errors=st,y.state.next({errors:n.errors,isValid:!1})},O=st=>{const dt=yU(st)?[st]:GZ(st);let jt=i,gt=a;for(let rs=0;rs{if(!l.actionArrayLengths.size)return!1;const dt=yU(st)?[st]:GZ(st);let jt=i,gt="",rs=-1,Ns=0;for(let us=0;us=jt.length)return rs===-1?!1:us===rs?+Bs{const rs=pi(r,st);if(rs){if(O(st)||B(st))return;const Ns=xf(pi(i,st)),us=pi(i,st,xf(jt)?pi(a,st):jt);xf(us)||gt&>.defaultChecked||dt?xh(i,st,dt?us:aot(rs._f)):fe(st,us),l.mount&&!l.action&&(C(),Ns&&n.isDirty&&(g.isDirty||x.isDirty)&&(Q()||(n.isDirty=!1,y.state.next({...n}))),s.shouldUnregister&&Ns&&!xf(pi(i,st))&&fIe(st,o)&&(l.watch=!0))}},G=(st,dt,jt,gt,rs)=>{let Ns=!1,us=!1;const Bs={name:st};if(!t.disabled||gt===!0){if(!jt||gt){const Ts=l_(pi(a,st),dt);(g.isDirty||x.isDirty)&&(us=n.isDirty,n.isDirty=Bs.isDirty=!Ts||Q(),Ns=us!==Bs.isDirty),us=!!pi(n.dirtyFields,st),Ts!==n.isDirty?yfs(n.dirtyFields,ER(a,i,void 0,r)):Ts?qg(n.dirtyFields,st):xh(n.dirtyFields,st,!0),Bs.dirtyFields=n.dirtyFields,Ns=Ns||(g.dirtyFields||x.dirtyFields)&&us!==!Ts}if(jt){const Ts=pi(n.touchedFields,st);Ts||(xh(n.touchedFields,st,jt),Bs.touchedFields=n.touchedFields,Ns=Ns||(g.touchedFields||x.touchedFields)&&Ts!==jt)}Ns&&rs&&y.state.next(Bs)}return Ns?Bs:{}},H=(st,dt,jt,gt)=>{const rs=pi(n.errors,st),Ns=(g.isValid||x.isValid)&&Fw(dt)&&n.isValid!==dt;if(t.delayError&&jt?(c[st]=j(st,()=>P(st,jt)),c[st](t.delayError)):(clearTimeout(d[st]),delete c[st],jt?xh(n.errors,st,jt):qg(n.errors,st),n.errors={...n.errors}),(jt?!l_(rs,jt):rs)||!$0(gt)||Ns){const us={...gt,...Ns&&Fw(dt)?{isValid:dt}:{},errors:n.errors,name:st};n={...n,...us},y.state.next(us)}},Y=async st=>(A(st,!0),await t.resolver(i,t.context,dfs(st||o.mount,r,t.criteriaMode,t.shouldUseNativeValidation))),se=async st=>{const{errors:dt}=await Y(st);if(A(st),st){for(const jt of st){const gt=pi(dt,jt);gt?o.array.has(jt)&&Pp(gt)&&!Object.keys(gt).some(rs=>!Number.isNaN(Number(rs)))?Xit(n.errors,{[jt]:gt},jt):xh(n.errors,jt,gt):qg(n.errors,jt)}n.errors={...n.errors}}else n.errors=dt;return dt},ee=async({name:st,eventType:dt})=>{if(s.validate){const jt=await s.validate({formValues:i,formState:n,name:st,eventType:dt});if(Pp(jt))for(const gt in jt){const rs=jt[gt];rs&&Ee(`${gIe}.${gt}`,{message:X0(rs.message)?rs.message:"",type:rs.type||yN.validate})}else X0(jt)||!jt?Ee(gIe,{message:jt||"",type:yN.validate}):Ye(gIe);return jt}return!0},oe=async({fields:st,onlyCheckValid:dt,name:jt,eventType:gt,context:rs={valid:!0,runRootValidation:!1}})=>{if(s.validate&&(rs.runRootValidation=!0,!await ee({name:jt,eventType:gt})&&(rs.valid=!1,dt)))return rs.valid;for(const Ns in st){const us=st[Ns];if(us){const{_f:Bs,...Ts}=us;if(Bs){const Fn=o.array.has(Bs.name),An=us._f&&ufs(us._f),js=g.validatingFields||g.isValidating||x.validatingFields||x.isValidating;An&&js&&A([Bs.name],!0);const In=await sot(us,o.disabled,i,_,t.shouldUseNativeValidation&&!dt,Fn);if(An&&js&&A([Bs.name]),In[Bs.name]&&(rs.valid=!1,dt)||(!dt&&(pi(In,Bs.name)?Fn?Xit(n.errors,In,Bs.name):xh(n.errors,Bs.name,In[Bs.name]):qg(n.errors,Bs.name)),s.shouldUseNativeValidation&&In[Bs.name]))break}!$0(Ts)&&await oe({context:rs,onlyCheckValid:dt,fields:Ts,name:Ns,eventType:gt})}}return rs.valid},me=()=>{for(const st of o.unMount){const dt=pi(r,st);dt&&(dt._f.refs?dt._f.refs.every(jt=>!pIe(jt)):!pIe(dt._f.ref))&&Oe(st)}o.unMount=new Set},Q=(st,dt)=>(st&&dt&&xh(i,st,dt),!l_(l.mount?i:a,a)),te=(st,dt,jt)=>i7e(st,o,{...l.mount?i:xf(dt)||X0(st)?a:dt},jt,dt),le=st=>FCt(pi(l.mount?i:a,st,t.shouldUnregister?pi(a,st,[]):[])),fe=(st,dt,jt={},gt=!1,rs=!1,Ns=!1)=>{const us=pi(r,st);let Bs=dt;if(us){const Ts=us._f;Ts&&(!Ts.disabled&&xh(i,st,GCt(dt,Ts)),Bs=aSe(Ts.ref)&&a0(dt)?"":dt,$Ct(Ts.ref)?[...Ts.ref.options].forEach(Fn=>Fn.selected=Bs.includes(Fn.value)):Ts.refs?pee(Ts.ref)?Ts.refs.forEach(Fn=>{(!Fn.defaultChecked||!Fn.disabled)&&(Array.isArray(Bs)?Fn.checked=!!Bs.find(An=>An===Fn.value):Fn.checked=Bs===Fn.value||!!Bs)}):Ts.refs.forEach(Fn=>Fn.checked=Fn.value===Bs):L3e(Ts.ref)?Ts.ref.value="":(Ts.ref.value=Bs,!Ts.ref.type&&!rs&&!Ns&&y.state.next({name:st,values:gt?i:Kf(i)})))}(jt.shouldDirty||jt.shouldTouch)&&G(st,Bs,jt.shouldTouch,jt.shouldDirty,!rs),jt.shouldValidate&&Ue(st,{delayError:jt.delayError})},_e=(st,dt,jt,gt=!1,rs=!1,Ns=!1)=>{o.array.has(st)&&y.array.next({name:st,values:gt?i:Kf(i)});for(const us in dt){if(!dt.hasOwnProperty(us))return;const Bs=dt[us],Ts=st+"."+us,Fn=pi(r,Ts);(o.array.has(st)||Pp(Bs)||Fn&&!Fn._f)&&!r3(Bs)?_e(Ts,Bs,jt,gt,rs,Ns):fe(Ts,Bs,jt,gt,rs,Ns)}},ve=(st,dt,jt,gt,rs=!1)=>{const Ns=pi(r,st),us=o.array.has(st),Bs=gt?dt:Kf(dt),Ts=pi(i,st),Fn=l_(Ts,Bs);if(Fn||xh(i,st,Bs),us)y.array.next({name:st,values:gt?i:Kf(i)}),(g.isDirty||g.dirtyFields||x.isDirty||x.dirtyFields)&&jt.shouldDirty&&(M(),rs||y.state.next({name:st,dirtyFields:n.dirtyFields,isDirty:Q(st,Bs)}));else{const An=Array.isArray(Bs)&&!Bs.length||$0(Bs),js=!Fn&&!rs;!Ns||Ns._f||a0(Bs)||An?fe(st,Bs,jt,gt,rs,js):_e(st,Bs,jt,gt,rs,js)}if(!Fn&&!rs){const An=fIe(st,o),js=gt?i:Kf(i);y.state.next({...An&&n,name:l.mount||An?st:void 0,values:js})}},he=(st,dt,jt={})=>ve(st,dt,jt,!1),Se=(st,dt={})=>{const jt=n1(st)?st(i):st;if(!l_(i,jt)){i={...i,...jt};const gt=zCt(jt);for(const rs of o.mount)rs in gt&&ve(rs,gt[rs],dt,!0,!0);y.state.next({...n,name:void 0,type:void 0,...u?{values:i}:{}}),dt.shouldValidate&&C()}},Te=async st=>{l.mount=!0;const dt=st.target;let jt=dt.name,gt=!0;const rs=pi(r,jt),Ns=us=>{gt=Number.isNaN(us)||r3(us)&&isNaN(us.getTime())||l_(us,pi(i,jt,us))};if(rs){let us,Bs;const Ts=dt.type?aot(rs._f):r7e(st),Fn=st.type===mE.BLUR||st.type===mE.FOCUS_OUT,An=!hfs(rs._f)&&!s.validate&&!t.resolver&&!pi(n.errors,jt)&&!rs._f.deps,js=An||pfs(Fn,pi(n.touchedFields,jt),n.isSubmitted,m,h),In=fIe(jt,o,Fn);if(xh(i,jt,Ts),Fn){if(!dt||!dt.readOnly){rs._f.onBlur&&rs._f.onBlur(st);const Ln=c[jt];Ln&&Ln(0)}}else rs._f.onChange&&rs._f.onChange(st);const un=G(jt,Ts,Fn),jr=!$0(un)||In;if(!Fn&&y.state.next({name:jt,type:st.type,...u?{values:Kf(i)}:{}}),js)return(!An||!n.isValid)&&(g.isValid||x.isValid)&&(t.mode==="onBlur"?Fn&&C():Fn||C()),jr&&y.state.next({name:jt,...In?{}:un});if(!t.resolver&&s.validate&&await ee({name:jt,eventType:st.type}),!Fn&&In&&y.state.next({...n}),t.resolver){const{errors:Ln}=await Y([jt]);if(A([jt]),Ns(Ts),!gt){!$0(un)&&y.state.next(un);return}const Sr=oot(n.errors,r,jt),Qn=oot(Ln,r,Sr.name||jt);us=Qn.error,jt=Qn.name,Bs=$0(Ln)}else A([jt],!0),us=(await sot(rs,o.disabled,i,_,t.shouldUseNativeValidation))[jt],A([jt]),Ns(Ts),gt&&(us?Bs=!1:(g.isValid||x.isValid)&&(Bs=await oe({fields:r,onlyCheckValid:!0,name:jt,eventType:st.type})));gt&&(rs._f.deps&&(!Array.isArray(rs._f.deps)||rs._f.deps.length>0)&&Ue(rs._f.deps),H(jt,Bs,us,un))}},Ie=(st,dt)=>{if(pi(n.errors,dt)&&st.focus)return st.focus(),1},Ue=async(st,dt={})=>{let jt,gt;const rs=J2e(st);if(t.resolver){const Ns=await se(xf(st)?st:rs);jt=$0(Ns),gt=st?!rs.some(us=>pi(Ns,us)):jt}else st?(gt=(await Promise.all(rs.map(async Ns=>{const us=pi(r,Ns);return await oe({fields:us&&us._f?{[Ns]:us}:us,eventType:mE.TRIGGER})}))).every(Boolean),!(!gt&&!n.isValid)&&C()):gt=jt=await oe({fields:r,name:st,eventType:mE.TRIGGER});if(dt.delayError&&t.delayError&&X0(st)){const Ns=pi(n.errors,st);Ns?(qg(n.errors,st),c[st]=j(st,()=>P(st,Ns)),c[st](t.delayError)):(clearTimeout(d[st]),delete c[st])}return y.state.next({...!X0(st)||(g.isValid||x.isValid)&&jt!==n.isValid?{}:{name:st},...t.resolver||!st?{isValid:jt}:{},errors:n.errors}),dt.shouldFocus&&!gt&&gY(r,Ie,st?rs:o.mount),gt},Be=(st,dt)=>{let jt={...l.mount?i:a};return dt&&(jt=BCt(dt.dirtyFields?n.dirtyFields:n.touchedFields,jt)),xf(st)?jt:X0(st)?pi(jt,st):st.map(gt=>pi(jt,gt))},je=(st,dt)=>({invalid:!!pi((dt||n).errors,st),isDirty:!!pi((dt||n).dirtyFields,st),error:pi((dt||n).errors,st),isValidating:!!pi(n.validatingFields,st),isTouched:!!pi((dt||n).touchedFields,st)}),Ye=st=>{const dt=st?J2e(st):void 0;dt==null||dt.forEach(jt=>qg(n.errors,jt)),dt?dt.forEach(jt=>{y.state.next({name:jt,errors:n.errors})}):(n.errors={},y.state.next({errors:n.errors}))},Ee=(st,dt,jt)=>{const gt=(pi(r,st,{_f:{}})._f||{}).ref,rs=pi(n.errors,st)||{},{ref:Ns,message:us,type:Bs,...Ts}=rs;xh(n.errors,st,{...Ts,...dt,ref:gt}),y.state.next({name:st,errors:n.errors,isValid:!1}),jt&&jt.shouldFocus&>&>.focus&>.focus()},Re=(st,dt)=>{if(n1(st)){u++;const{unsubscribe:jt}=y.state.subscribe({next:rs=>"values"in rs&&st(rs.values||te(void 0,dt),rs)});let gt=!1;return{unsubscribe:()=>{gt||(gt=!0,u--,jt())}}}return te(st,dt,!0)},ke=st=>{var dt;const jt=!!(!((dt=st.formState)===null||dt===void 0)&&dt.values);jt&&u++;const{unsubscribe:gt}=y.state.subscribe({next:Ns=>{if(ffs(st.name,Ns.name,st.exact)&&mfs(Ns,st.formState||g,Ft,st.reRenderRoot)){const us={...i};st.callback({values:us,...n,...Ns,defaultValues:a})}}});if(!jt)return gt;let rs=!1;return()=>{rs||(rs=!0,u--,gt())}},Fe=st=>(l.mount=!0,x={...x,...st.formState},ke({...st,formState:{...p,...st.formState}})),Oe=(st,dt={})=>{for(const jt of st?J2e(st):o.mount)o.mount.delete(jt),o.array.delete(jt),dt.keepValue||(qg(r,jt),qg(i,jt)),!dt.keepError&&qg(n.errors,jt),!dt.keepDirty&&qg(n.dirtyFields,jt),!dt.keepTouched&&qg(n.touchedFields,jt),!dt.keepIsValidating&&qg(n.validatingFields,jt),!t.shouldUnregister&&!dt.keepDefaultValue&&qg(a,jt);y.state.next({values:Kf(i)}),y.state.next({...n,...dt.keepDirty?{isDirty:Q()}:{}}),!dt.keepIsValid&&C()},Ge=({disabled:st,name:dt})=>{if(Fw(st)&&l.mount||st||o.disabled.has(dt)){const rs=o.disabled.has(dt)!==!!st;st?o.disabled.add(dt):o.disabled.delete(dt),rs&&l.mount&&!l.action&&C()}},yt=(st,dt={})=>{let jt=pi(r,st);const gt=Fw(dt.disabled)||Fw(t.disabled),rs=!o.registerName.has(st)&&jt&&jt._f&&!jt._f.mount;return xh(r,st,{...jt||{},_f:{...jt&&jt._f?jt._f:{ref:{name:st}},name:st,mount:!0,...dt}}),o.mount.add(st),jt&&!rs?Ge({disabled:Fw(dt.disabled)?dt.disabled:t.disabled,name:st}):U(st,!0,dt.value),{...gt?{disabled:dt.disabled||t.disabled}:{},...t.progressive?{required:!!dt.required,min:nG(dt.min),max:nG(dt.max),minLength:nG(dt.minLength),maxLength:nG(dt.maxLength),pattern:nG(dt.pattern)}:{},name:st,onChange:Te,onBlur:Te,ref:Ns=>{if(Ns){o.registerName.add(st),yt(st,dt),o.registerName.delete(st),jt=pi(r,st);const us=xf(Ns.value)&&Ns.querySelectorAll&&Ns.querySelectorAll("input,select,textarea")[0]||Ns,Bs=lfs(us),Ts=jt._f.refs||[];if(Bs?Ts.find(An=>An===us):us===jt._f.ref)return;const Fn={...jt._f};Bs?(Fn.refs=[...Ts.filter(pIe),us,...Array.isArray(pi(a,st))?[{}]:[]],Fn.ref={type:us.type,name:st}):(Fn.ref=us,delete Fn.refs),xh(r,st,{_f:Fn}),U(st,!1,void 0,us)}else jt=pi(r,st,{}),jt._f&&(jt._f.mount=!1),(t.shouldUnregister||dt.shouldUnregister)&&!(MCt(o.array,st)&&l.action)&&o.unMount.add(st)}}},tt=()=>t.shouldFocusError&&!t.shouldUseNativeValidation&&gY(r,Ie,o.mount),ut=st=>{Fw(st)&&(y.state.next({disabled:st}),gY(r,(dt,jt)=>{const gt=pi(r,jt);gt&&(dt.disabled=gt._f.disabled||st,Array.isArray(gt._f.refs)&>._f.refs.forEach(rs=>{rs.disabled=gt._f.disabled||st}))},0,!1))},nt=(st,dt)=>async jt=>{let gt,rs;jt&&(jt.preventDefault&&jt.preventDefault(),jt.persist&&jt.persist());let Ns=Kf(i);if(y.state.next({isSubmitting:!0}),t.resolver){const{errors:us,values:Bs}=await Y();A(),n.errors=us,Ns=Kf(Bs)}else await oe({fields:r,eventType:mE.SUBMIT});if(o.disabled.size)for(const us of o.disabled)qg(Ns,us);if(qg(n.errors,ICt),$0(n.errors)){y.state.next({errors:{}});try{gt=await st(Ns,jt)}catch(us){rs=us}}else dt&&await dt({...n.errors},jt),tt(),setTimeout(tt);if(y.state.next({isSubmitted:!0,isSubmitting:!1,isSubmitSuccessful:$0(n.errors)&&!rs,submitCount:n.submitCount+1,errors:n.errors}),rs)throw rs;return gt},et=(st,dt={})=>{pi(r,st)&&(xf(dt.defaultValue)?he(st,Kf(pi(a,st))):(he(st,dt.defaultValue),xh(a,st,Kf(dt.defaultValue))),dt.keepTouched||qg(n.touchedFields,st),dt.keepDirty||(qg(n.dirtyFields,st),n.isDirty=dt.defaultValue?Q(st,Kf(pi(a,st))):Q()),dt.keepError||(qg(n.errors,st),g.isValid&&C()),y.state.next({...n}))},at=(st,dt={})=>{const jt=st?Kf(st):a,gt=Kf(jt),rs=$0(st),Ns=gt,us=r;if(dt.keepDefaultValues||(a=jt),!dt.keepValues){if(dt.keepDirtyValues){const Bs=new Set([...o.mount,...UCt(ER(a,i,void 0,us),n.dirtyFields)]);for(const Ts of Array.from(Bs)){const Fn=pi(n.dirtyFields,Ts),An=pi(i,Ts),js=pi(Ns,Ts);Fn&&!xf(An)?xh(Ns,Ts,An):!Fn&&!xf(js)&&he(Ts,js)}}else{if(R3e&&xf(st))for(const Bs of o.mount){const Ts=pi(r,Bs);if(Ts&&Ts._f){const Fn=Array.isArray(Ts._f.refs)?Ts._f.refs[0]:Ts._f.ref;if(aSe(Fn)){const An=Fn.closest("form");if(An){An.reset();break}}}}if(dt.keepFieldsRef)for(const Bs of o.mount)he(Bs,pi(Ns,Bs));else r={}}if(t.shouldUnregister){if(i=dt.keepDefaultValues?Kf(a):{},dt.keepFieldsRef)for(const Bs of o.mount)xh(i,Bs,pi(Ns,Bs))}else i=Kf(Ns);y.array.next({values:{...Ns}}),y.state.next({name:void 0,type:void 0,values:{...Ns}})}o={mount:dt.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=!g.isValid||!!dt.keepIsValid||!!dt.keepDirtyValues||!t.shouldUnregister&&!$0(Ns),l.watch=!!t.shouldUnregister,l.keepIsValid=!!dt.keepIsValid,l.action=!1,l.actionArrayLengths.clear(),dt.keepErrors||(n.errors={}),y.state.next({submitCount:dt.keepSubmitCount?n.submitCount:0,isDirty:rs?!1:dt.keepDirty?n.isDirty:dt.keepValues?Q():!!(dt.keepDefaultValues&&!l_(st,a)),isSubmitted:dt.keepIsSubmitted?n.isSubmitted:!1,dirtyFields:rs?{}:dt.keepDirtyValues?dt.keepDefaultValues&&i?ER(a,i,void 0,us):n.dirtyFields:dt.keepDefaultValues&&st?ER(a,st,void 0,us):dt.keepDirty?n.dirtyFields:{},touchedFields:dt.keepTouched?n.touchedFields:{},errors:dt.keepErrors?n.errors:{},isSubmitSuccessful:dt.keepIsSubmitSuccessful?n.isSubmitSuccessful:!1,isSubmitting:!1,defaultValues:a})},wt=(st,dt)=>at(n1(st)?st(i):st,{...t.resetOptions,...dt}),rt=(st,dt={})=>{const jt=pi(r,st),gt=jt&&jt._f;if(gt){const rs=gt.refs?gt.refs[0]:gt.ref;rs.focus&&setTimeout(()=>{rs.focus(),dt.shouldSelect&&n1(rs.select)&&rs.select()})}},Ft=st=>{const{name:dt,type:jt,values:gt,...rs}=st;n={...n,...rs}};y.state.subscribe({next:Ft});const xs={control:{register:yt,unregister:Oe,getFieldState:je,handleSubmit:nt,setError:Ee,_subscribe:ke,_runSchema:Y,_updateIsValidating:A,_focusError:tt,_getWatch:te,_getDirty:Q,_setValid:C,_setFieldArray:I,_setDisabledField:Ge,_setErrors:R,_getFieldArray:le,_reset:at,_resetDefaultValues:()=>n1(t.defaultValues)&&t.defaultValues().then(st=>{wt(st,t.resetOptions),y.state.next({isLoading:!1})}),_removeUnmounted:me,_disableForm:ut,_subjects:y,_proxyFormState:g,get _fields(){return r},get _formValues(){return i},get _state(){return l},set _state(st){l=st},get _defaultValues(){return a},get _names(){return o},set _names(st){o=st},get _formState(){return n},get _options(){return t},set _options(st){t={...t,...st},h=Kne(t.mode),m=Kne(t.reValidateMode)}},subscribe:Fe,trigger:Ue,register:yt,handleSubmit:nt,watch:Re,setValue:he,setValues:Se,getValues:Be,reset:wt,resetField:et,resetDefaultValues:(st,dt={})=>{if(a=Kf(st),!dt.keepDirty){const jt=ER(a,i,void 0,r);n.dirtyFields=jt,n.isDirty=!$0(jt)}dt.keepIsValid||C(),y.state.next({...n,defaultValues:a})},clearErrors:Ye,unregister:Oe,setError:Ee,setFocus:rt,getFieldState:je};return{...xs,formControl:xs}}function D3e(s={}){const t=zt.useRef(void 0),n=zt.useRef(void 0),r=zt.useRef(s.formControl),[a,i]=zt.useState(()=>({...Kf(WCt),isLoading:n1(s.defaultValues),errors:s.errors||{},disabled:s.disabled||!1,defaultValues:n1(s.defaultValues)?void 0:s.defaultValues}));if(!t.current||s.formControl&&r.current!==s.formControl)if(r.current=s.formControl,s.formControl)t.current={...s.formControl,formState:a},s.defaultValues&&!n1(s.defaultValues)&&s.formControl.reset(s.defaultValues,s.resetOptions);else{const{formControl:d,...u}=vfs(s);t.current={...u,formState:a}}const l=t.current.control;l._options=s;const{resyncIfNeeded:o,snapshot:c}=zHe();return FHe(()=>{const d=()=>({...l._formState,defaultValues:l._defaultValues});o(!0,d,i);const u=l._subscribe({formState:l._proxyFormState,callback:()=>i({...l._formState,defaultValues:l._defaultValues}),reRenderRoot:!0});return i(h=>({...h,isReady:!0})),l._formState.isReady=!0,()=>{u(),c(!0,d)}},[l,o,c]),zt.useEffect(()=>l._disableForm(s.disabled),[l,s.disabled]),zt.useEffect(()=>{s.mode&&(l._options.mode=s.mode),s.reValidateMode&&(l._options.reValidateMode=s.reValidateMode)},[l,s.mode,s.reValidateMode]),zt.useEffect(()=>{s.errors&&(l._setErrors(s.errors),l._focusError())},[l,s.errors]),zt.useEffect(()=>{s.shouldUnregister&&l._subjects.state.next({values:l._getWatch()})},[l,s.shouldUnregister]),zt.useEffect(()=>{if(l._proxyFormState.isDirty){const d=l._getDirty();d!==a.isDirty&&l._subjects.state.next({isDirty:d})}},[l,a.isDirty]),zt.useEffect(()=>{var d;s.values&&!l_(s.values,n.current)?(l._reset(s.values,{keepFieldsRef:!0,...l._options.resetOptions}),!((d=l._options.resetOptions)===null||d===void 0)&&d.keepIsValid||l._setValid(),n.current=s.values,i(u=>({...u}))):l._resetDefaultValues()},[l,s.values]),zt.useEffect(()=>{l._state.mount||(l._setValid(),l._state.mount=!0),l._state.watch&&(l._state.watch=!1,l._subjects.state.next({...l._formState})),l._removeUnmounted()}),t.current.formState=zt.useMemo(()=>LCt(a,l),[l,a]),t.current}const lot=(s,t,n)=>{if(s&&"reportValidity"in s){const r=pi(n,t);s.setCustomValidity(r&&r.message||""),s.reportValidity()}},KCt=(s,t)=>{for(const n in t.fields){const r=t.fields[n];r&&r.ref&&"reportValidity"in r.ref?lot(r.ref,n,s):r.refs&&r.refs.forEach(a=>lot(a,n,s))}},bfs=(s,t)=>{t.shouldUseNativeValidation&&KCt(s,t);const n={};for(const r in s){const a=pi(t.fields,r),i=Object.assign(s[r]||{},{ref:a&&a.ref});if(_fs(t.names||Object.keys(s),r)){const l=Object.assign({},pi(n,r));xh(l,"root",i),xh(n,r,l)}else xh(n,r,i)}return n},_fs=(s,t)=>s.some(n=>n.startsWith(t+"."));var wfs=function(s,t){for(var n={};s.length;){var r=s[0],a=r.code,i=r.message,l=r.path.join(".");if(!n[l])if("unionErrors"in r){var o=r.unionErrors[0].errors[0];n[l]={message:o.message,type:o.code}}else n[l]={message:i,type:a};if("unionErrors"in r&&r.unionErrors.forEach(function(u){return u.errors.forEach(function(h){return s.push(h)})}),t){var c=n[l].types,d=c&&c[r.code];n[l]=RCt(l,t,n,a,d?[].concat(d,r.message):r.message)}s.shift()}return n},O3e=function(s,t,n){return n===void 0&&(n={}),function(r,a,i){try{return Promise.resolve(function(l,o){try{var c=Promise.resolve(s[n.mode==="sync"?"parse":"parseAsync"](r,t)).then(function(d){return i.shouldUseNativeValidation&&KCt({},i),{errors:{},values:n.raw?r:d}})}catch(d){return o(d)}return c&&c.then?c.then(void 0,o):c}(0,function(l){if(function(o){return Array.isArray(o==null?void 0:o.errors)}(l))return{values:{},errors:bfs(wfs(l.errors,!i.shouldUseNativeValidation&&i.criteriaMode==="all"),i)};throw l}))}catch(l){return Promise.reject(l)}}},cot;function ca(s,t,n){function r(o,c){if(o._zod||Object.defineProperty(o,"_zod",{value:{def:c,constr:l,traits:new Set},enumerable:!1}),o._zod.traits.has(s))return;o._zod.traits.add(s),t(o,c);const d=l.prototype,u=Object.keys(d);for(let h=0;h{var c,d;return n!=null&&n.Parent&&o instanceof n.Parent?!0:(d=(c=o==null?void 0:o._zod)==null?void 0:c.traits)==null?void 0:d.has(s)}}),Object.defineProperty(l,"name",{value:s}),l}class kB extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class YCt extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}}(cot=globalThis).__zod_globalConfig??(cot.__zod_globalConfig={});const UHe=globalThis.__zod_globalConfig;function PO(s){return UHe}function ZCt(s){const t=Object.values(s).filter(r=>typeof r=="number");return Object.entries(s).filter(([r,a])=>t.indexOf(+r)===-1).map(([r,a])=>a)}function c7e(s,t){return typeof t=="bigint"?t.toString():t}function qHe(s){return{get value(){{const t=s();return Object.defineProperty(this,"value",{value:t}),t}}}}function VHe(s){return s==null}function HHe(s){const t=s.startsWith("^")?1:0,n=s.endsWith("$")?s.length-1:s.length;return s.slice(t,n)}function jfs(s,t){const n=s/t,r=Math.round(n),a=Number.EPSILON*Math.max(Math.abs(n),1);return Math.abs(n-r){};function oSe(s){return typeof s=="object"&&s!==null&&!Array.isArray(s)}const kfs=qHe(()=>{var s;if(UHe.jitless||typeof navigator<"u"&&((s=navigator==null?void 0:navigator.userAgent)!=null&&s.includes("Cloudflare")))return!1;try{const t=Function;return new t(""),!0}catch{return!1}});function WZ(s){if(oSe(s)===!1)return!1;const t=s.constructor;if(t===void 0||typeof t!="function")return!0;const n=t.prototype;return!(oSe(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function QCt(s){return WZ(s)?{...s}:Array.isArray(s)?[...s]:s instanceof Map?new Map(s):s instanceof Set?new Set(s):s}const Sfs=new Set(["string","number","symbol"]);function vU(s){return s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function XM(s,t,n){const r=new s._zod.constr(t??s._zod.def);return(!t||n!=null&&n.parent)&&(r._zod.parent=s),r}function ml(s){const t=s;if(!t)return{};if(typeof t=="string")return{error:()=>t};if((t==null?void 0:t.message)!==void 0){if((t==null?void 0:t.error)!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function Cfs(s){return Object.keys(s).filter(t=>s[t]._zod.optin==="optional"&&s[t]._zod.optout==="optional")}const Afs={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function Efs(s,t){const n=s._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");const i=ZM(s._zod.def,{get shape(){const l={};for(const o in t){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);t[o]&&(l[o]=n.shape[o])}return _F(this,"shape",l),l},checks:[]});return XM(s,i)}function Tfs(s,t){const n=s._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");const i=ZM(s._zod.def,{get shape(){const l={...s._zod.def.shape};for(const o in t){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);t[o]&&delete l[o]}return _F(this,"shape",l),l},checks:[]});return XM(s,i)}function Mfs(s,t){if(!WZ(t))throw new Error("Invalid input to extend: expected a plain object");const n=s._zod.def.checks;if(n&&n.length>0){const i=s._zod.def.shape;for(const l in t)if(Object.getOwnPropertyDescriptor(i,l)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}const a=ZM(s._zod.def,{get shape(){const i={...s._zod.def.shape,...t};return _F(this,"shape",i),i}});return XM(s,a)}function Pfs(s,t){if(!WZ(t))throw new Error("Invalid input to safeExtend: expected a plain object");const n=ZM(s._zod.def,{get shape(){const r={...s._zod.def.shape,...t};return _F(this,"shape",r),r}});return XM(s,n)}function Ifs(s,t){var r;if((r=s._zod.def.checks)!=null&&r.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");const n=ZM(s._zod.def,{get shape(){const a={...s._zod.def.shape,...t._zod.def.shape};return _F(this,"shape",a),a},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return XM(s,n)}function Lfs(s,t,n){const a=t._zod.def.checks;if(a&&a.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");const l=ZM(t._zod.def,{get shape(){const o=t._zod.def.shape,c={...o};if(n)for(const d in n){if(!(d in o))throw new Error(`Unrecognized key: "${d}"`);n[d]&&(c[d]=s?new s({type:"optional",innerType:o[d]}):o[d])}else for(const d in o)c[d]=s?new s({type:"optional",innerType:o[d]}):o[d];return _F(this,"shape",c),c},checks:[]});return XM(t,l)}function Rfs(s,t,n){const r=ZM(t._zod.def,{get shape(){const a=t._zod.def.shape,i={...a};if(n)for(const l in n){if(!(l in i))throw new Error(`Unrecognized key: "${l}"`);n[l]&&(i[l]=new s({type:"nonoptional",innerType:a[l]}))}else for(const l in a)i[l]=new s({type:"nonoptional",innerType:a[l]});return _F(this,"shape",i),i}});return XM(t,r)}function uz(s,t=0){var n;if(s.aborted===!0)return!0;for(let r=t;r{var r;return(r=n).path??(r.path=[]),n.path.unshift(s),n})}function Yne(s){return typeof s=="string"?s:s==null?void 0:s.message}function IO(s,t,n){var c,d,u,h,m,p;const r=s.message?s.message:Yne((u=(d=(c=s.inst)==null?void 0:c._zod.def)==null?void 0:d.error)==null?void 0:u.call(d,s))??Yne((h=t==null?void 0:t.error)==null?void 0:h.call(t,s))??Yne((m=n.customError)==null?void 0:m.call(n,s))??Yne((p=n.localeError)==null?void 0:p.call(n,s))??"Invalid input",{inst:a,continue:i,input:l,...o}=s;return o.path??(o.path=[]),o.message=r,t!=null&&t.reportInput&&(o.input=l),o}function GHe(s){return Array.isArray(s)?"array":typeof s=="string"?"string":"unknown"}function KZ(...s){const[t,n,r]=s;return typeof t=="string"?{message:t,code:"custom",input:n,inst:r}:{...t}}const e3t=(s,t)=>{s.name="$ZodError",Object.defineProperty(s,"_zod",{value:s._zod,enumerable:!1}),Object.defineProperty(s,"issues",{value:t,enumerable:!1}),s.message=JSON.stringify(t,c7e,2),Object.defineProperty(s,"toString",{value:()=>s.message,enumerable:!1})},t3t=ca("$ZodError",e3t),s3t=ca("$ZodError",e3t,{Parent:Error});function Ofs(s,t=n=>n.message){const n={},r=[];for(const a of s.issues)a.path.length>0?(n[a.path[0]]=n[a.path[0]]||[],n[a.path[0]].push(t(a))):r.push(t(a));return{formErrors:r,fieldErrors:n}}function Ffs(s,t=n=>n.message){const n={_errors:[]},r=(a,i=[])=>{for(const l of a.issues)if(l.code==="invalid_union"&&l.errors.length)l.errors.map(o=>r({issues:o},[...i,...l.path]));else if(l.code==="invalid_key")r({issues:l.issues},[...i,...l.path]);else if(l.code==="invalid_element")r({issues:l.issues},[...i,...l.path]);else{const o=[...i,...l.path];if(o.length===0)n._errors.push(t(l));else{let c=n,d=0;for(;d(t,n,r,a)=>{const i=r?{...r,async:!1}:{async:!1},l=t._zod.run({value:n,issues:[]},i);if(l instanceof Promise)throw new kB;if(l.issues.length){const o=new((a==null?void 0:a.Err)??s)(l.issues.map(c=>IO(c,i,PO())));throw XCt(o,a==null?void 0:a.callee),o}return l.value},KHe=s=>async(t,n,r,a)=>{const i=r?{...r,async:!0}:{async:!0};let l=t._zod.run({value:n,issues:[]},i);if(l instanceof Promise&&(l=await l),l.issues.length){const o=new((a==null?void 0:a.Err)??s)(l.issues.map(c=>IO(c,i,PO())));throw XCt(o,a==null?void 0:a.callee),o}return l.value},F3e=s=>(t,n,r)=>{const a=r?{...r,async:!1}:{async:!1},i=t._zod.run({value:n,issues:[]},a);if(i instanceof Promise)throw new kB;return i.issues.length?{success:!1,error:new(s??t3t)(i.issues.map(l=>IO(l,a,PO())))}:{success:!0,data:i.value}},zfs=F3e(s3t),z3e=s=>async(t,n,r)=>{const a=r?{...r,async:!0}:{async:!0};let i=t._zod.run({value:n,issues:[]},a);return i instanceof Promise&&(i=await i),i.issues.length?{success:!1,error:new s(i.issues.map(l=>IO(l,a,PO())))}:{success:!0,data:i.value}},Bfs=z3e(s3t),$fs=s=>(t,n,r)=>{const a=r?{...r,direction:"backward"}:{direction:"backward"};return WHe(s)(t,n,a)},Ufs=s=>(t,n,r)=>WHe(s)(t,n,r),qfs=s=>async(t,n,r)=>{const a=r?{...r,direction:"backward"}:{direction:"backward"};return KHe(s)(t,n,a)},Vfs=s=>async(t,n,r)=>KHe(s)(t,n,r),Hfs=s=>(t,n,r)=>{const a=r?{...r,direction:"backward"}:{direction:"backward"};return F3e(s)(t,n,a)},Gfs=s=>(t,n,r)=>F3e(s)(t,n,r),Wfs=s=>async(t,n,r)=>{const a=r?{...r,direction:"backward"}:{direction:"backward"};return z3e(s)(t,n,a)},Kfs=s=>async(t,n,r)=>z3e(s)(t,n,r),Yfs=/^[cC][0-9a-z]{6,}$/,Zfs=/^[0-9a-z]+$/,Xfs=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,Qfs=/^[0-9a-vA-V]{20}$/,Jfs=/^[A-Za-z0-9]{27}$/,eps=/^[a-zA-Z0-9_-]{21}$/,tps=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,sps=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,hot=s=>s?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${s}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,nps=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,rps="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function aps(){return new RegExp(rps,"u")}const ips=/^(?:(?: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])$/,ops=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,lps=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,cps=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,dps=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,n3t=/^[A-Za-z0-9_-]*$/,ups=/^https?$/,hps=/^\+[1-9]\d{6,14}$/,r3t="(?:(?:\\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])))",mps=new RegExp(`^${r3t}$`);function a3t(s){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof s.precision=="number"?s.precision===-1?`${t}`:s.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${s.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function fps(s){return new RegExp(`^${a3t(s)}$`)}function pps(s){const t=a3t({precision:s.precision}),n=["Z"];s.local&&n.push(""),s.offset&&n.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const r=`${t}(?:${n.join("|")})`;return new RegExp(`^${r3t}T(?:${r})$`)}const gps=s=>{const t=s?`[\\s\\S]{${(s==null?void 0:s.minimum)??0},${(s==null?void 0:s.maximum)??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},xps=/^-?\d+$/,yps=/^-?\d+(?:\.\d+)?$/,vps=/^(?:true|false)$/i,bps=/^[^A-Z]*$/,_ps=/^[^a-z]*$/,O_=ca("$ZodCheck",(s,t)=>{var n;s._zod??(s._zod={}),s._zod.def=t,(n=s._zod).onattach??(n.onattach=[])}),i3t={number:"number",bigint:"bigint",object:"date"},o3t=ca("$ZodCheckLessThan",(s,t)=>{O_.init(s,t);const n=i3t[typeof t.value];s._zod.onattach.push(r=>{const a=r._zod.bag,i=(t.inclusive?a.maximum:a.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value{(t.inclusive?r.value<=t.value:r.value{O_.init(s,t);const n=i3t[typeof t.value];s._zod.onattach.push(r=>{const a=r._zod.bag,i=(t.inclusive?a.minimum:a.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>i&&(t.inclusive?a.minimum=t.value:a.exclusiveMinimum=t.value)}),s._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:n,code:"too_small",minimum:typeof t.value=="object"?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:s,continue:!t.abort})}}),wps=ca("$ZodCheckMultipleOf",(s,t)=>{O_.init(s,t),s._zod.onattach.push(n=>{var r;(r=n._zod.bag).multipleOf??(r.multipleOf=t.value)}),s._zod.check=n=>{if(typeof n.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof n.value=="bigint"?n.value%t.value===BigInt(0):jfs(n.value,t.value)===0)||n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:t.value,input:n.value,inst:s,continue:!t.abort})}}),jps=ca("$ZodCheckNumberFormat",(s,t)=>{var l;O_.init(s,t),t.format=t.format||"float64";const n=(l=t.format)==null?void 0:l.includes("int"),r=n?"int":"number",[a,i]=Afs[t.format];s._zod.onattach.push(o=>{const c=o._zod.bag;c.format=t.format,c.minimum=a,c.maximum=i,n&&(c.pattern=xps)}),s._zod.check=o=>{const c=o.value;if(n){if(!Number.isInteger(c)){o.issues.push({expected:r,format:t.format,code:"invalid_type",continue:!1,input:c,inst:s});return}if(!Number.isSafeInteger(c)){c>0?o.issues.push({input:c,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:s,origin:r,inclusive:!0,continue:!t.abort}):o.issues.push({input:c,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:s,origin:r,inclusive:!0,continue:!t.abort});return}}ci&&o.issues.push({origin:"number",input:c,code:"too_big",maximum:i,inclusive:!0,inst:s,continue:!t.abort})}}),Nps=ca("$ZodCheckMaxLength",(s,t)=>{var n;O_.init(s,t),(n=s._zod.def).when??(n.when=r=>{const a=r.value;return!VHe(a)&&a.length!==void 0}),s._zod.onattach.push(r=>{const a=r._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum{const a=r.value;if(a.length<=t.maximum)return;const l=GHe(a);r.issues.push({origin:l,code:"too_big",maximum:t.maximum,inclusive:!0,input:a,inst:s,continue:!t.abort})}}),kps=ca("$ZodCheckMinLength",(s,t)=>{var n;O_.init(s,t),(n=s._zod.def).when??(n.when=r=>{const a=r.value;return!VHe(a)&&a.length!==void 0}),s._zod.onattach.push(r=>{const a=r._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>a&&(r._zod.bag.minimum=t.minimum)}),s._zod.check=r=>{const a=r.value;if(a.length>=t.minimum)return;const l=GHe(a);r.issues.push({origin:l,code:"too_small",minimum:t.minimum,inclusive:!0,input:a,inst:s,continue:!t.abort})}}),Sps=ca("$ZodCheckLengthEquals",(s,t)=>{var n;O_.init(s,t),(n=s._zod.def).when??(n.when=r=>{const a=r.value;return!VHe(a)&&a.length!==void 0}),s._zod.onattach.push(r=>{const a=r._zod.bag;a.minimum=t.length,a.maximum=t.length,a.length=t.length}),s._zod.check=r=>{const a=r.value,i=a.length;if(i===t.length)return;const l=GHe(a),o=i>t.length;r.issues.push({origin:l,...o?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:r.value,inst:s,continue:!t.abort})}}),B3e=ca("$ZodCheckStringFormat",(s,t)=>{var n,r;O_.init(s,t),s._zod.onattach.push(a=>{const i=a._zod.bag;i.format=t.format,t.pattern&&(i.patterns??(i.patterns=new Set),i.patterns.add(t.pattern))}),t.pattern?(n=s._zod).check??(n.check=a=>{t.pattern.lastIndex=0,!t.pattern.test(a.value)&&a.issues.push({origin:"string",code:"invalid_format",format:t.format,input:a.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:s,continue:!t.abort})}):(r=s._zod).check??(r.check=()=>{})}),Cps=ca("$ZodCheckRegex",(s,t)=>{B3e.init(s,t),s._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:s,continue:!t.abort})}}),Aps=ca("$ZodCheckLowerCase",(s,t)=>{t.pattern??(t.pattern=bps),B3e.init(s,t)}),Eps=ca("$ZodCheckUpperCase",(s,t)=>{t.pattern??(t.pattern=_ps),B3e.init(s,t)}),Tps=ca("$ZodCheckIncludes",(s,t)=>{O_.init(s,t);const n=vU(t.includes),r=new RegExp(typeof t.position=="number"?`^.{${t.position}}${n}`:n);t.pattern=r,s._zod.onattach.push(a=>{const i=a._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(r)}),s._zod.check=a=>{a.value.includes(t.includes,t.position)||a.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:a.value,inst:s,continue:!t.abort})}}),Mps=ca("$ZodCheckStartsWith",(s,t)=>{O_.init(s,t);const n=new RegExp(`^${vU(t.prefix)}.*`);t.pattern??(t.pattern=n),s._zod.onattach.push(r=>{const a=r._zod.bag;a.patterns??(a.patterns=new Set),a.patterns.add(n)}),s._zod.check=r=>{r.value.startsWith(t.prefix)||r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:r.value,inst:s,continue:!t.abort})}}),Pps=ca("$ZodCheckEndsWith",(s,t)=>{O_.init(s,t);const n=new RegExp(`.*${vU(t.suffix)}$`);t.pattern??(t.pattern=n),s._zod.onattach.push(r=>{const a=r._zod.bag;a.patterns??(a.patterns=new Set),a.patterns.add(n)}),s._zod.check=r=>{r.value.endsWith(t.suffix)||r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:r.value,inst:s,continue:!t.abort})}}),Ips=ca("$ZodCheckOverwrite",(s,t)=>{O_.init(s,t),s._zod.check=n=>{n.value=t.tx(n.value)}});class Lps{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}const r=t.split(` `).filter(l=>l),a=Math.min(...r.map(l=>l.length-l.trimStart().length)),i=r.map(l=>l.slice(a)).map(l=>" ".repeat(this.indent*2)+l);for(const l of i)this.content.push(l)}compile(){const t=Function,n=this==null?void 0:this.args,a=[...((this==null?void 0:this.content)??[""]).map(i=>` ${i}`)];return new t(...n,a.join(` `))}}const Rps={major:4,minor:4,patch:3},Ag=ca("$ZodType",(s,t)=>{var a;var n;s??(s={}),s._zod.def=t,s._zod.bag=s._zod.bag||{},s._zod.version=Rps;const r=[...s._zod.def.checks??[]];s._zod.traits.has("$ZodCheck")&&r.unshift(s);for(const i of r)for(const l of i._zod.onattach)l(s);if(r.length===0)(n=s._zod).deferred??(n.deferred=[]),(a=s._zod.deferred)==null||a.push(()=>{s._zod.run=s._zod.parse});else{const i=(o,c,d)=>{let u=uz(o),h;for(const m of c){if(m._zod.def.when){if(Dfs(o)||!m._zod.def.when(o))continue}else if(u)continue;const p=o.issues.length,g=m._zod.check(o);if(g instanceof Promise&&(d==null?void 0:d.async)===!1)throw new kB;if(h||g instanceof Promise)h=(h??Promise.resolve()).then(async()=>{await g,o.issues.length!==p&&(u||(u=uz(o,p)))});else{if(o.issues.length===p)continue;u||(u=uz(o,p))}}return h?h.then(()=>o):o},l=(o,c,d)=>{if(uz(o))return o.aborted=!0,o;const u=i(c,r,d);if(u instanceof Promise){if(d.async===!1)throw new kB;return u.then(h=>s._zod.parse(h,d))}return s._zod.parse(u,d)};s._zod.run=(o,c)=>{if(c.skipChecks)return s._zod.parse(o,c);if(c.direction==="backward"){const u=s._zod.parse({value:o.value,issues:[]},{...c,skipChecks:!0});return u instanceof Promise?u.then(h=>l(h,o,c)):l(u,o,c)}const d=s._zod.parse(o,c);if(d instanceof Promise){if(c.async===!1)throw new kB;return d.then(u=>i(u,r,c))}return i(d,r,c)}}tm(s,"~standard",()=>({validate:i=>{var l;try{const o=zfs(s,i);return o.success?{value:o.data}:{issues:(l=o.error)==null?void 0:l.issues}}catch{return Bfs(s,i).then(c=>{var d;return c.success?{value:c.data}:{issues:(d=c.error)==null?void 0:d.issues}})}},vendor:"zod",version:1}))}),YHe=ca("$ZodString",(s,t)=>{var n;Ag.init(s,t),s._zod.pattern=[...((n=s==null?void 0:s._zod.bag)==null?void 0:n.patterns)??[]].pop()??gps(s._zod.bag),s._zod.parse=(r,a)=>{if(t.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:s}),r}}),dp=ca("$ZodStringFormat",(s,t)=>{B3e.init(s,t),YHe.init(s,t)}),Dps=ca("$ZodGUID",(s,t)=>{t.pattern??(t.pattern=sps),dp.init(s,t)}),Ops=ca("$ZodUUID",(s,t)=>{if(t.version){const r={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(r===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=hot(r))}else t.pattern??(t.pattern=hot());dp.init(s,t)}),Fps=ca("$ZodEmail",(s,t)=>{t.pattern??(t.pattern=nps),dp.init(s,t)}),zps=ca("$ZodURL",(s,t)=>{dp.init(s,t),s._zod.check=n=>{var r;try{const a=n.value.trim();if(!t.normalize&&((r=t.protocol)==null?void 0:r.source)===ups.source&&!/^https?:\/\//i.test(a)){n.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:n.value,inst:s,continue:!t.abort});return}const i=new URL(a);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(i.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:n.value,inst:s,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(i.protocol.endsWith(":")?i.protocol.slice(0,-1):i.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:s,continue:!t.abort})),t.normalize?n.value=i.href:n.value=a;return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:s,continue:!t.abort})}}}),Bps=ca("$ZodEmoji",(s,t)=>{t.pattern??(t.pattern=aps()),dp.init(s,t)}),$ps=ca("$ZodNanoID",(s,t)=>{t.pattern??(t.pattern=eps),dp.init(s,t)}),Ups=ca("$ZodCUID",(s,t)=>{t.pattern??(t.pattern=Yfs),dp.init(s,t)}),qps=ca("$ZodCUID2",(s,t)=>{t.pattern??(t.pattern=Zfs),dp.init(s,t)}),Vps=ca("$ZodULID",(s,t)=>{t.pattern??(t.pattern=Xfs),dp.init(s,t)}),Hps=ca("$ZodXID",(s,t)=>{t.pattern??(t.pattern=Qfs),dp.init(s,t)}),Gps=ca("$ZodKSUID",(s,t)=>{t.pattern??(t.pattern=Jfs),dp.init(s,t)}),Wps=ca("$ZodISODateTime",(s,t)=>{t.pattern??(t.pattern=pps(t)),dp.init(s,t)}),Kps=ca("$ZodISODate",(s,t)=>{t.pattern??(t.pattern=mps),dp.init(s,t)}),Yps=ca("$ZodISOTime",(s,t)=>{t.pattern??(t.pattern=fps(t)),dp.init(s,t)}),Zps=ca("$ZodISODuration",(s,t)=>{t.pattern??(t.pattern=tps),dp.init(s,t)}),Xps=ca("$ZodIPv4",(s,t)=>{t.pattern??(t.pattern=ips),dp.init(s,t),s._zod.bag.format="ipv4"}),Qps=ca("$ZodIPv6",(s,t)=>{t.pattern??(t.pattern=ops),dp.init(s,t),s._zod.bag.format="ipv6",s._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:s,continue:!t.abort})}}}),Jps=ca("$ZodCIDRv4",(s,t)=>{t.pattern??(t.pattern=lps),dp.init(s,t)}),egs=ca("$ZodCIDRv6",(s,t)=>{t.pattern??(t.pattern=cps),dp.init(s,t),s._zod.check=n=>{const r=n.value.split("/");try{if(r.length!==2)throw new Error;const[a,i]=r;if(!i)throw new Error;const l=Number(i);if(`${l}`!==i)throw new Error;if(l<0||l>128)throw new Error;new URL(`http://[${a}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:s,continue:!t.abort})}}});function c3t(s){if(s==="")return!0;if(/\s/.test(s)||s.length%4!==0)return!1;try{return atob(s),!0}catch{return!1}}const tgs=ca("$ZodBase64",(s,t)=>{t.pattern??(t.pattern=dps),dp.init(s,t),s._zod.bag.contentEncoding="base64",s._zod.check=n=>{c3t(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:s,continue:!t.abort})}});function sgs(s){if(!n3t.test(s))return!1;const t=s.replace(/[-_]/g,r=>r==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return c3t(n)}const ngs=ca("$ZodBase64URL",(s,t)=>{t.pattern??(t.pattern=n3t),dp.init(s,t),s._zod.bag.contentEncoding="base64url",s._zod.check=n=>{sgs(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:s,continue:!t.abort})}}),rgs=ca("$ZodE164",(s,t)=>{t.pattern??(t.pattern=hps),dp.init(s,t)});function ags(s,t=null){try{const n=s.split(".");if(n.length!==3)return!1;const[r]=n;if(!r)return!1;const a=JSON.parse(atob(r));return!("typ"in a&&(a==null?void 0:a.typ)!=="JWT"||!a.alg||t&&(!("alg"in a)||a.alg!==t))}catch{return!1}}const igs=ca("$ZodJWT",(s,t)=>{dp.init(s,t),s._zod.check=n=>{ags(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:s,continue:!t.abort})}}),d3t=ca("$ZodNumber",(s,t)=>{Ag.init(s,t),s._zod.pattern=s._zod.bag.pattern??yps,s._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}const a=n.value;if(typeof a=="number"&&!Number.isNaN(a)&&Number.isFinite(a))return n;const i=typeof a=="number"?Number.isNaN(a)?"NaN":Number.isFinite(a)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:a,inst:s,...i?{received:i}:{}}),n}}),ogs=ca("$ZodNumberFormat",(s,t)=>{jps.init(s,t),d3t.init(s,t)}),lgs=ca("$ZodBoolean",(s,t)=>{Ag.init(s,t),s._zod.pattern=vps,s._zod.parse=(n,r)=>{if(t.coerce)try{n.value=!!n.value}catch{}const a=n.value;return typeof a=="boolean"||n.issues.push({expected:"boolean",code:"invalid_type",input:a,inst:s}),n}}),cgs=ca("$ZodUnknown",(s,t)=>{Ag.init(s,t),s._zod.parse=n=>n}),dgs=ca("$ZodNever",(s,t)=>{Ag.init(s,t),s._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:s}),n)});function mot(s,t,n){s.issues.length&&t.issues.push(...JCt(n,s.issues)),t.value[n]=s.value}const ugs=ca("$ZodArray",(s,t)=>{Ag.init(s,t),s._zod.parse=(n,r)=>{const a=n.value;if(!Array.isArray(a))return n.issues.push({expected:"array",code:"invalid_type",input:a,inst:s}),n;n.value=Array(a.length);const i=[];for(let l=0;lmot(d,n,l))):mot(c,n,l)}return i.length?Promise.all(i).then(()=>n):n}});function lSe(s,t,n,r,a,i){const l=n in r;if(s.issues.length){if(a&&i&&!l)return;t.issues.push(...JCt(n,s.issues))}if(!l&&!a){s.issues.length||t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[n]});return}s.value===void 0?l&&(t.value[n]=void 0):t.value[n]=s.value}function u3t(s){var r,a,i,l;const t=Object.keys(s.shape);for(const o of t)if(!((l=(i=(a=(r=s.shape)==null?void 0:r[o])==null?void 0:a._zod)==null?void 0:i.traits)!=null&&l.has("$ZodType")))throw new Error(`Invalid element at key "${o}": expected a Zod schema`);const n=Cfs(s.shape);return{...s,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function h3t(s,t,n,r,a,i){const l=[],o=a.keySet,c=a.catchall._zod,d=c.def.type,u=c.optin==="optional",h=c.optout==="optional";for(const m in t){if(m==="__proto__"||o.has(m))continue;if(d==="never"){l.push(m);continue}const p=c.run({value:t[m],issues:[]},r);p instanceof Promise?s.push(p.then(g=>lSe(g,n,m,t,u,h))):lSe(p,n,m,t,u,h)}return l.length&&n.issues.push({code:"unrecognized_keys",keys:l,input:t,inst:i}),s.length?Promise.all(s).then(()=>n):n}const hgs=ca("$ZodObject",(s,t)=>{Ag.init(s,t);const n=Object.getOwnPropertyDescriptor(t,"shape");if(!(n!=null&&n.get)){const o=t.shape;Object.defineProperty(t,"shape",{get:()=>{const c={...o};return Object.defineProperty(t,"shape",{value:c}),c}})}const r=qHe(()=>u3t(t));tm(s._zod,"propValues",()=>{const o=t.shape,c={};for(const d in o){const u=o[d]._zod;if(u.values){c[d]??(c[d]=new Set);for(const h of u.values)c[d].add(h)}}return c});const a=oSe,i=t.catchall;let l;s._zod.parse=(o,c)=>{l??(l=r.value);const d=o.value;if(!a(d))return o.issues.push({expected:"object",code:"invalid_type",input:d,inst:s}),o;o.value={};const u=[],h=l.shape;for(const m of l.keys){const p=h[m],g=p._zod.optin==="optional",x=p._zod.optout==="optional",y=p._zod.run({value:d[m],issues:[]},c);y instanceof Promise?u.push(y.then(v=>lSe(v,o,m,d,g,x))):lSe(y,o,m,d,g,x)}return i?h3t(u,d,o,c,r.value,s):u.length?Promise.all(u).then(()=>o):o}}),mgs=ca("$ZodObjectJIT",(s,t)=>{hgs.init(s,t);const n=s._zod.parse,r=qHe(()=>u3t(t)),a=m=>{var j,C;const p=new Lps(["shape","payload","ctx"]),g=r.value,x=A=>{const M=uot(A);return`shape[${M}]._zod.run({ value: input[${M}], issues: [] }, ctx)`};p.write("const input = payload.value;");const y=Object.create(null);let v=0;for(const A of g.keys)y[A]=`key_${v++}`;p.write("const newResult = {};");for(const A of g.keys){const M=y[A],I=uot(A),P=m[A],R=((j=P==null?void 0:P._zod)==null?void 0:j.optin)==="optional",O=((C=P==null?void 0:P._zod)==null?void 0:C.optout)==="optional";p.write(`const ${M} = ${x(A)};`),R&&O?p.write(` if (${M}.issues.length) { if (${I} in input) { payload.issues = payload.issues.concat(${M}.issues.map(iss => ({ ...iss, path: iss.path ? [${I}, ...iss.path] : [${I}] }))); } } if (${M}.value === undefined) { if (${I} in input) { newResult[${I}] = undefined; } } else { newResult[${I}] = ${M}.value; } `):R?p.write(` if (${M}.issues.length) { payload.issues = payload.issues.concat(${M}.issues.map(iss => ({ ...iss, path: iss.path ? [${I}, ...iss.path] : [${I}] }))); } if (${M}.value === undefined) { if (${I} in input) { newResult[${I}] = undefined; } } else { newResult[${I}] = ${M}.value; } `):p.write(` const ${M}_present = ${I} in input; if (${M}.issues.length) { payload.issues = payload.issues.concat(${M}.issues.map(iss => ({ ...iss, path: iss.path ? [${I}, ...iss.path] : [${I}] }))); } if (!${M}_present && !${M}.issues.length) { payload.issues.push({ code: "invalid_type", expected: "nonoptional", input: undefined, path: [${I}] }); } if (${M}_present) { if (${M}.value === undefined) { newResult[${I}] = undefined; } else { newResult[${I}] = ${M}.value; } } `)}p.write("payload.value = newResult;"),p.write("return payload;");const _=p.compile();return(A,M)=>_(m,A,M)};let i;const l=oSe,o=!UHe.jitless,d=o&&kfs.value,u=t.catchall;let h;s._zod.parse=(m,p)=>{h??(h=r.value);const g=m.value;return l(g)?o&&d&&(p==null?void 0:p.async)===!1&&p.jitless!==!0?(i||(i=a(t.shape)),m=i(m,p),u?h3t([],g,m,p,h,s):m):n(m,p):(m.issues.push({expected:"object",code:"invalid_type",input:g,inst:s}),m)}});function fot(s,t,n,r){for(const i of s)if(i.issues.length===0)return t.value=i.value,t;const a=s.filter(i=>!uz(i));return a.length===1?(t.value=a[0].value,a[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:s.map(i=>i.issues.map(l=>IO(l,r,PO())))}),t)}const fgs=ca("$ZodUnion",(s,t)=>{Ag.init(s,t),tm(s._zod,"optin",()=>t.options.some(r=>r._zod.optin==="optional")?"optional":void 0),tm(s._zod,"optout",()=>t.options.some(r=>r._zod.optout==="optional")?"optional":void 0),tm(s._zod,"values",()=>{if(t.options.every(r=>r._zod.values))return new Set(t.options.flatMap(r=>Array.from(r._zod.values)))}),tm(s._zod,"pattern",()=>{if(t.options.every(r=>r._zod.pattern)){const r=t.options.map(a=>a._zod.pattern);return new RegExp(`^(${r.map(a=>HHe(a.source)).join("|")})$`)}});const n=t.options.length===1?t.options[0]._zod.run:null;s._zod.parse=(r,a)=>{if(n)return n(r,a);let i=!1;const l=[];for(const o of t.options){const c=o._zod.run({value:r.value,issues:[]},a);if(c instanceof Promise)l.push(c),i=!0;else{if(c.issues.length===0)return c;l.push(c)}}return i?Promise.all(l).then(o=>fot(o,r,s,a)):fot(l,r,s,a)}}),pgs=ca("$ZodIntersection",(s,t)=>{Ag.init(s,t),s._zod.parse=(n,r)=>{const a=n.value,i=t.left._zod.run({value:a,issues:[]},r),l=t.right._zod.run({value:a,issues:[]},r);return i instanceof Promise||l instanceof Promise?Promise.all([i,l]).then(([c,d])=>pot(n,c,d)):pot(n,i,l)}});function d7e(s,t){if(s===t)return{valid:!0,data:s};if(s instanceof Date&&t instanceof Date&&+s==+t)return{valid:!0,data:s};if(WZ(s)&&WZ(t)){const n=Object.keys(t),r=Object.keys(s).filter(i=>n.indexOf(i)!==-1),a={...s,...t};for(const i of r){const l=d7e(s[i],t[i]);if(!l.valid)return{valid:!1,mergeErrorPath:[i,...l.mergeErrorPath]};a[i]=l.data}return{valid:!0,data:a}}if(Array.isArray(s)&&Array.isArray(t)){if(s.length!==t.length)return{valid:!1,mergeErrorPath:[]};const n=[];for(let r=0;ro.l&&o.r).map(([o])=>o);if(i.length&&a&&s.issues.push({...a,keys:i}),uz(s))return s;const l=d7e(t.value,n.value);if(!l.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(l.mergeErrorPath)}`);return s.value=l.data,s}const ggs=ca("$ZodEnum",(s,t)=>{Ag.init(s,t);const n=ZCt(t.entries),r=new Set(n);s._zod.values=r,s._zod.pattern=new RegExp(`^(${n.filter(a=>Sfs.has(typeof a)).map(a=>typeof a=="string"?vU(a):a.toString()).join("|")})$`),s._zod.parse=(a,i)=>{const l=a.value;return r.has(l)||a.issues.push({code:"invalid_value",values:n,input:l,inst:s}),a}}),xgs=ca("$ZodLiteral",(s,t)=>{if(Ag.init(s,t),t.values.length===0)throw new Error("Cannot create literal schema with no valid values");const n=new Set(t.values);s._zod.values=n,s._zod.pattern=new RegExp(`^(${t.values.map(r=>typeof r=="string"?vU(r):r?vU(r.toString()):String(r)).join("|")})$`),s._zod.parse=(r,a)=>{const i=r.value;return n.has(i)||r.issues.push({code:"invalid_value",values:t.values,input:i,inst:s}),r}}),ygs=ca("$ZodTransform",(s,t)=>{Ag.init(s,t),s._zod.optin="optional",s._zod.parse=(n,r)=>{if(r.direction==="backward")throw new YCt(s.constructor.name);const a=t.transform(n.value,n);if(r.async)return(a instanceof Promise?a:Promise.resolve(a)).then(l=>(n.value=l,n.fallback=!0,n));if(a instanceof Promise)throw new kB;return n.value=a,n.fallback=!0,n}});function got(s,t){return t===void 0&&(s.issues.length||s.fallback)?{issues:[],value:void 0}:s}const m3t=ca("$ZodOptional",(s,t)=>{Ag.init(s,t),s._zod.optin="optional",s._zod.optout="optional",tm(s._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),tm(s._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${HHe(n.source)})?$`):void 0}),s._zod.parse=(n,r)=>{if(t.innerType._zod.optin==="optional"){const a=n.value,i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(l=>got(l,a)):got(i,a)}return n.value===void 0?n:t.innerType._zod.run(n,r)}}),vgs=ca("$ZodExactOptional",(s,t)=>{m3t.init(s,t),tm(s._zod,"values",()=>t.innerType._zod.values),tm(s._zod,"pattern",()=>t.innerType._zod.pattern),s._zod.parse=(n,r)=>t.innerType._zod.run(n,r)}),bgs=ca("$ZodNullable",(s,t)=>{Ag.init(s,t),tm(s._zod,"optin",()=>t.innerType._zod.optin),tm(s._zod,"optout",()=>t.innerType._zod.optout),tm(s._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${HHe(n.source)}|null)$`):void 0}),tm(s._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),s._zod.parse=(n,r)=>n.value===null?n:t.innerType._zod.run(n,r)}),_gs=ca("$ZodDefault",(s,t)=>{Ag.init(s,t),s._zod.optin="optional",tm(s._zod,"values",()=>t.innerType._zod.values),s._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);if(n.value===void 0)return n.value=t.defaultValue,n;const a=t.innerType._zod.run(n,r);return a instanceof Promise?a.then(i=>xot(i,t)):xot(a,t)}});function xot(s,t){return s.value===void 0&&(s.value=t.defaultValue),s}const wgs=ca("$ZodPrefault",(s,t)=>{Ag.init(s,t),s._zod.optin="optional",tm(s._zod,"values",()=>t.innerType._zod.values),s._zod.parse=(n,r)=>(r.direction==="backward"||n.value===void 0&&(n.value=t.defaultValue),t.innerType._zod.run(n,r))}),jgs=ca("$ZodNonOptional",(s,t)=>{Ag.init(s,t),tm(s._zod,"values",()=>{const n=t.innerType._zod.values;return n?new Set([...n].filter(r=>r!==void 0)):void 0}),s._zod.parse=(n,r)=>{const a=t.innerType._zod.run(n,r);return a instanceof Promise?a.then(i=>yot(i,s)):yot(a,s)}});function yot(s,t){return!s.issues.length&&s.value===void 0&&s.issues.push({code:"invalid_type",expected:"nonoptional",input:s.value,inst:t}),s}const Ngs=ca("$ZodCatch",(s,t)=>{Ag.init(s,t),s._zod.optin="optional",tm(s._zod,"optout",()=>t.innerType._zod.optout),tm(s._zod,"values",()=>t.innerType._zod.values),s._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);const a=t.innerType._zod.run(n,r);return a instanceof Promise?a.then(i=>(n.value=i.value,i.issues.length&&(n.value=t.catchValue({...n,error:{issues:i.issues.map(l=>IO(l,r,PO()))},input:n.value}),n.issues=[],n.fallback=!0),n)):(n.value=a.value,a.issues.length&&(n.value=t.catchValue({...n,error:{issues:a.issues.map(i=>IO(i,r,PO()))},input:n.value}),n.issues=[],n.fallback=!0),n)}}),kgs=ca("$ZodPipe",(s,t)=>{Ag.init(s,t),tm(s._zod,"values",()=>t.in._zod.values),tm(s._zod,"optin",()=>t.in._zod.optin),tm(s._zod,"optout",()=>t.out._zod.optout),tm(s._zod,"propValues",()=>t.in._zod.propValues),s._zod.parse=(n,r)=>{if(r.direction==="backward"){const i=t.out._zod.run(n,r);return i instanceof Promise?i.then(l=>Zne(l,t.in,r)):Zne(i,t.in,r)}const a=t.in._zod.run(n,r);return a instanceof Promise?a.then(i=>Zne(i,t.out,r)):Zne(a,t.out,r)}});function Zne(s,t,n){return s.issues.length?(s.aborted=!0,s):t._zod.run({value:s.value,issues:s.issues,fallback:s.fallback},n)}const Sgs=ca("$ZodReadonly",(s,t)=>{Ag.init(s,t),tm(s._zod,"propValues",()=>t.innerType._zod.propValues),tm(s._zod,"values",()=>t.innerType._zod.values),tm(s._zod,"optin",()=>{var n,r;return(r=(n=t.innerType)==null?void 0:n._zod)==null?void 0:r.optin}),tm(s._zod,"optout",()=>{var n,r;return(r=(n=t.innerType)==null?void 0:n._zod)==null?void 0:r.optout}),s._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);const a=t.innerType._zod.run(n,r);return a instanceof Promise?a.then(vot):vot(a)}});function vot(s){return s.value=Object.freeze(s.value),s}const Cgs=ca("$ZodCustom",(s,t)=>{O_.init(s,t),Ag.init(s,t),s._zod.parse=(n,r)=>n,s._zod.check=n=>{const r=n.value,a=t.fn(r);if(a instanceof Promise)return a.then(i=>bot(i,n,r,s));bot(a,n,r,s)}});function bot(s,t,n,r){if(!s){const a={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(a.params=r._zod.def.params),t.issues.push(KZ(a))}}var _ot;class Ags{constructor(){this._map=new WeakMap,this._idmap=new Map}add(t,...n){const r=n[0];return this._map.set(t,r),r&&typeof r=="object"&&"id"in r&&this._idmap.set(r.id,t),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(t){const n=this._map.get(t);return n&&typeof n=="object"&&"id"in n&&this._idmap.delete(n.id),this._map.delete(t),this}get(t){const n=t._zod.parent;if(n){const r={...this.get(n)??{}};delete r.id;const a={...r,...this._map.get(t)};return Object.keys(a).length?a:void 0}return this._map.get(t)}has(t){return this._map.has(t)}}function Egs(){return new Ags}(_ot=globalThis).__zod_globalRegistry??(_ot.__zod_globalRegistry=Egs());const jW=globalThis.__zod_globalRegistry;function Tgs(s,t){return new s({type:"string",...ml(t)})}function Mgs(s,t){return new s({type:"string",format:"email",check:"string_format",abort:!1,...ml(t)})}function wot(s,t){return new s({type:"string",format:"guid",check:"string_format",abort:!1,...ml(t)})}function Pgs(s,t){return new s({type:"string",format:"uuid",check:"string_format",abort:!1,...ml(t)})}function Igs(s,t){return new s({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...ml(t)})}function Lgs(s,t){return new s({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...ml(t)})}function Rgs(s,t){return new s({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...ml(t)})}function Dgs(s,t){return new s({type:"string",format:"url",check:"string_format",abort:!1,...ml(t)})}function Ogs(s,t){return new s({type:"string",format:"emoji",check:"string_format",abort:!1,...ml(t)})}function Fgs(s,t){return new s({type:"string",format:"nanoid",check:"string_format",abort:!1,...ml(t)})}function zgs(s,t){return new s({type:"string",format:"cuid",check:"string_format",abort:!1,...ml(t)})}function Bgs(s,t){return new s({type:"string",format:"cuid2",check:"string_format",abort:!1,...ml(t)})}function $gs(s,t){return new s({type:"string",format:"ulid",check:"string_format",abort:!1,...ml(t)})}function Ugs(s,t){return new s({type:"string",format:"xid",check:"string_format",abort:!1,...ml(t)})}function qgs(s,t){return new s({type:"string",format:"ksuid",check:"string_format",abort:!1,...ml(t)})}function Vgs(s,t){return new s({type:"string",format:"ipv4",check:"string_format",abort:!1,...ml(t)})}function Hgs(s,t){return new s({type:"string",format:"ipv6",check:"string_format",abort:!1,...ml(t)})}function Ggs(s,t){return new s({type:"string",format:"cidrv4",check:"string_format",abort:!1,...ml(t)})}function Wgs(s,t){return new s({type:"string",format:"cidrv6",check:"string_format",abort:!1,...ml(t)})}function Kgs(s,t){return new s({type:"string",format:"base64",check:"string_format",abort:!1,...ml(t)})}function Ygs(s,t){return new s({type:"string",format:"base64url",check:"string_format",abort:!1,...ml(t)})}function Zgs(s,t){return new s({type:"string",format:"e164",check:"string_format",abort:!1,...ml(t)})}function Xgs(s,t){return new s({type:"string",format:"jwt",check:"string_format",abort:!1,...ml(t)})}function Qgs(s,t){return new s({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...ml(t)})}function Jgs(s,t){return new s({type:"string",format:"date",check:"string_format",...ml(t)})}function exs(s,t){return new s({type:"string",format:"time",check:"string_format",precision:null,...ml(t)})}function txs(s,t){return new s({type:"string",format:"duration",check:"string_format",...ml(t)})}function sxs(s,t){return new s({type:"number",checks:[],...ml(t)})}function nxs(s,t){return new s({type:"number",check:"number_format",abort:!1,format:"safeint",...ml(t)})}function rxs(s,t){return new s({type:"boolean",...ml(t)})}function axs(s){return new s({type:"unknown"})}function ixs(s,t){return new s({type:"never",...ml(t)})}function jot(s,t){return new o3t({check:"less_than",...ml(t),value:s,inclusive:!1})}function xIe(s,t){return new o3t({check:"less_than",...ml(t),value:s,inclusive:!0})}function Not(s,t){return new l3t({check:"greater_than",...ml(t),value:s,inclusive:!1})}function yIe(s,t){return new l3t({check:"greater_than",...ml(t),value:s,inclusive:!0})}function kot(s,t){return new wps({check:"multiple_of",...ml(t),value:s})}function f3t(s,t){return new Nps({check:"max_length",...ml(t),maximum:s})}function cSe(s,t){return new kps({check:"min_length",...ml(t),minimum:s})}function p3t(s,t){return new Sps({check:"length_equals",...ml(t),length:s})}function oxs(s,t){return new Cps({check:"string_format",format:"regex",...ml(t),pattern:s})}function lxs(s){return new Aps({check:"string_format",format:"lowercase",...ml(s)})}function cxs(s){return new Eps({check:"string_format",format:"uppercase",...ml(s)})}function dxs(s,t){return new Tps({check:"string_format",format:"includes",...ml(t),includes:s})}function uxs(s,t){return new Mps({check:"string_format",format:"starts_with",...ml(t),prefix:s})}function hxs(s,t){return new Pps({check:"string_format",format:"ends_with",...ml(t),suffix:s})}function qq(s){return new Ips({check:"overwrite",tx:s})}function mxs(s){return qq(t=>t.normalize(s))}function fxs(){return qq(s=>s.trim())}function pxs(){return qq(s=>s.toLowerCase())}function gxs(){return qq(s=>s.toUpperCase())}function xxs(){return qq(s=>Nfs(s))}function yxs(s,t,n){return new s({type:"array",element:t,...ml(n)})}function vxs(s,t,n){return new s({type:"custom",check:"custom",fn:t,...ml(n)})}function bxs(s,t){const n=_xs(r=>(r.addIssue=a=>{if(typeof a=="string")r.issues.push(KZ(a,r.value,n._zod.def));else{const i=a;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=r.value),i.inst??(i.inst=n),i.continue??(i.continue=!n._zod.def.abort),r.issues.push(KZ(i))}},s(r.value,r)),t);return n}function _xs(s,t){const n=new O_({check:"custom",...ml(t)});return n._zod.check=s,n}function g3t(s){let t=(s==null?void 0:s.target)??"draft-2020-12";return t==="draft-4"&&(t="draft-04"),t==="draft-7"&&(t="draft-07"),{processors:s.processors??{},metadataRegistry:(s==null?void 0:s.metadata)??jW,target:t,unrepresentable:(s==null?void 0:s.unrepresentable)??"throw",override:(s==null?void 0:s.override)??(()=>{}),io:(s==null?void 0:s.io)??"output",counter:0,seen:new Map,cycles:(s==null?void 0:s.cycles)??"ref",reused:(s==null?void 0:s.reused)??"inline",external:(s==null?void 0:s.external)??void 0}}function gv(s,t,n={path:[],schemaPath:[]}){var u,h;var r;const a=s._zod.def,i=t.seen.get(s);if(i)return i.count++,n.schemaPath.includes(s)&&(i.cycle=n.path),i.schema;const l={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(s,l);const o=(h=(u=s._zod).toJSONSchema)==null?void 0:h.call(u);if(o)l.schema=o;else{const m={...n,schemaPath:[...n.schemaPath,s],path:n.path};if(s._zod.processJSONSchema)s._zod.processJSONSchema(t,l.schema,m);else{const g=l.schema,x=t.processors[a.type];if(!x)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${a.type}`);x(s,t,g,m)}const p=s._zod.parent;p&&(l.ref||(l.ref=p),gv(p,t,m),t.seen.get(p).isParent=!0)}const c=t.metadataRegistry.get(s);return c&&Object.assign(l.schema,c),t.io==="input"&&H1(s)&&(delete l.schema.examples,delete l.schema.default),t.io==="input"&&"_prefault"in l.schema&&((r=l.schema).default??(r.default=l.schema._prefault)),delete l.schema._prefault,t.seen.get(s).schema}function x3t(s,t){var l,o,c,d;const n=s.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const r=new Map;for(const u of s.seen.entries()){const h=(l=s.metadataRegistry.get(u[0]))==null?void 0:l.id;if(h){const m=r.get(h);if(m&&m!==u[0])throw new Error(`Duplicate schema id "${h}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(h,u[0])}}const a=u=>{var x;const h=s.target==="draft-2020-12"?"$defs":"definitions";if(s.external){const y=(x=s.external.registry.get(u[0]))==null?void 0:x.id,v=s.external.uri??(j=>j);if(y)return{ref:v(y)};const _=u[1].defId??u[1].schema.id??`schema${s.counter++}`;return u[1].defId=_,{defId:_,ref:`${v("__shared")}#/${h}/${_}`}}if(u[1]===n)return{ref:"#"};const p=`#/${h}/`,g=u[1].schema.id??`__schema${s.counter++}`;return{defId:g,ref:p+g}},i=u=>{if(u[1].schema.$ref)return;const h=u[1],{ref:m,defId:p}=a(u);h.def={...h.schema},p&&(h.defId=p);const g=h.schema;for(const x in g)delete g[x];g.$ref=m};if(s.cycles==="throw")for(const u of s.seen.entries()){const h=u[1];if(h.cycle)throw new Error(`Cycle detected: #/${(o=h.cycle)==null?void 0:o.join("/")}/ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const u of s.seen.entries()){const h=u[1];if(t===u[0]){i(u);continue}if(s.external){const p=(c=s.external.registry.get(u[0]))==null?void 0:c.id;if(t!==u[0]&&p){i(u);continue}}if((d=s.metadataRegistry.get(u[0]))==null?void 0:d.id){i(u);continue}if(h.cycle){i(u);continue}if(h.count>1&&s.reused==="ref"){i(u);continue}}}function y3t(s,t){var o,c,d,u;const n=s.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const r=h=>{const m=s.seen.get(h);if(m.ref===null)return;const p=m.def??m.schema,g={...p},x=m.ref;if(m.ref=null,x){r(x);const v=s.seen.get(x),_=v.schema;if(_.$ref&&(s.target==="draft-07"||s.target==="draft-04"||s.target==="openapi-3.0")?(p.allOf=p.allOf??[],p.allOf.push(_)):Object.assign(p,_),Object.assign(p,g),h._zod.parent===x)for(const C in p)C==="$ref"||C==="allOf"||C in g||delete p[C];if(_.$ref&&v.def)for(const C in p)C==="$ref"||C==="allOf"||C in v.def&&JSON.stringify(p[C])===JSON.stringify(v.def[C])&&delete p[C]}const y=h._zod.parent;if(y&&y!==x){r(y);const v=s.seen.get(y);if(v!=null&&v.schema.$ref&&(p.$ref=v.schema.$ref,v.def))for(const _ in p)_==="$ref"||_==="allOf"||_ in v.def&&JSON.stringify(p[_])===JSON.stringify(v.def[_])&&delete p[_]}s.override({zodSchema:h,jsonSchema:p,path:m.path??[]})};for(const h of[...s.seen.entries()].reverse())r(h[0]);const a={};if(s.target==="draft-2020-12"?a.$schema="https://json-schema.org/draft/2020-12/schema":s.target==="draft-07"?a.$schema="http://json-schema.org/draft-07/schema#":s.target==="draft-04"?a.$schema="http://json-schema.org/draft-04/schema#":s.target,(o=s.external)!=null&&o.uri){const h=(c=s.external.registry.get(t))==null?void 0:c.id;if(!h)throw new Error("Schema is missing an `id` property");a.$id=s.external.uri(h)}Object.assign(a,n.def??n.schema);const i=(d=s.metadataRegistry.get(t))==null?void 0:d.id;i!==void 0&&a.id===i&&delete a.id;const l=((u=s.external)==null?void 0:u.defs)??{};for(const h of s.seen.entries()){const m=h[1];m.def&&m.defId&&(m.def.id===m.defId&&delete m.def.id,l[m.defId]=m.def)}s.external||Object.keys(l).length>0&&(s.target==="draft-2020-12"?a.$defs=l:a.definitions=l);try{const h=JSON.parse(JSON.stringify(a));return Object.defineProperty(h,"~standard",{value:{...t["~standard"],jsonSchema:{input:dSe(t,"input",s.processors),output:dSe(t,"output",s.processors)}},enumerable:!1,writable:!1}),h}catch{throw new Error("Error converting schema to JSON.")}}function H1(s,t){const n=t??{seen:new Set};if(n.seen.has(s))return!1;n.seen.add(s);const r=s._zod.def;if(r.type==="transform")return!0;if(r.type==="array")return H1(r.element,n);if(r.type==="set")return H1(r.valueType,n);if(r.type==="lazy")return H1(r.getter(),n);if(r.type==="promise"||r.type==="optional"||r.type==="nonoptional"||r.type==="nullable"||r.type==="readonly"||r.type==="default"||r.type==="prefault")return H1(r.innerType,n);if(r.type==="intersection")return H1(r.left,n)||H1(r.right,n);if(r.type==="record"||r.type==="map")return H1(r.keyType,n)||H1(r.valueType,n);if(r.type==="pipe")return s._zod.traits.has("$ZodCodec")?!0:H1(r.in,n)||H1(r.out,n);if(r.type==="object"){for(const a in r.shape)if(H1(r.shape[a],n))return!0;return!1}if(r.type==="union"){for(const a of r.options)if(H1(a,n))return!0;return!1}if(r.type==="tuple"){for(const a of r.items)if(H1(a,n))return!0;return!!(r.rest&&H1(r.rest,n))}return!1}const wxs=(s,t={})=>n=>{const r=g3t({...n,processors:t});return gv(s,r),x3t(r,s),y3t(r,s)},dSe=(s,t,n={})=>r=>{const{libraryOptions:a,target:i}=r??{},l=g3t({...a??{},target:i,io:t,processors:n});return gv(s,l),x3t(l,s),y3t(l,s)},jxs={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},Nxs=(s,t,n,r)=>{const a=n;a.type="string";const{minimum:i,maximum:l,format:o,patterns:c,contentEncoding:d}=s._zod.bag;if(typeof i=="number"&&(a.minLength=i),typeof l=="number"&&(a.maxLength=l),o&&(a.format=jxs[o]??o,a.format===""&&delete a.format,o==="time"&&delete a.format),d&&(a.contentEncoding=d),c&&c.size>0){const u=[...c];u.length===1?a.pattern=u[0].source:u.length>1&&(a.allOf=[...u.map(h=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:h.source}))])}},kxs=(s,t,n,r)=>{const a=n,{minimum:i,maximum:l,format:o,multipleOf:c,exclusiveMaximum:d,exclusiveMinimum:u}=s._zod.bag;typeof o=="string"&&o.includes("int")?a.type="integer":a.type="number";const h=typeof u=="number"&&u>=(i??Number.NEGATIVE_INFINITY),m=typeof d=="number"&&d<=(l??Number.POSITIVE_INFINITY),p=t.target==="draft-04"||t.target==="openapi-3.0";h?p?(a.minimum=u,a.exclusiveMinimum=!0):a.exclusiveMinimum=u:typeof i=="number"&&(a.minimum=i),m?p?(a.maximum=d,a.exclusiveMaximum=!0):a.exclusiveMaximum=d:typeof l=="number"&&(a.maximum=l),typeof c=="number"&&(a.multipleOf=c)},Sxs=(s,t,n,r)=>{n.type="boolean"},Cxs=(s,t,n,r)=>{n.not={}},Axs=(s,t,n,r)=>{},Exs=(s,t,n,r)=>{const a=s._zod.def,i=ZCt(a.entries);i.every(l=>typeof l=="number")&&(n.type="number"),i.every(l=>typeof l=="string")&&(n.type="string"),n.enum=i},Txs=(s,t,n,r)=>{const a=s._zod.def,i=[];for(const l of a.values)if(l===void 0){if(t.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof l=="bigint"){if(t.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");i.push(Number(l))}else i.push(l);if(i.length!==0)if(i.length===1){const l=i[0];n.type=l===null?"null":typeof l,t.target==="draft-04"||t.target==="openapi-3.0"?n.enum=[l]:n.const=l}else i.every(l=>typeof l=="number")&&(n.type="number"),i.every(l=>typeof l=="string")&&(n.type="string"),i.every(l=>typeof l=="boolean")&&(n.type="boolean"),i.every(l=>l===null)&&(n.type="null"),n.enum=i},Mxs=(s,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},Pxs=(s,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},Ixs=(s,t,n,r)=>{const a=n,i=s._zod.def,{minimum:l,maximum:o}=s._zod.bag;typeof l=="number"&&(a.minItems=l),typeof o=="number"&&(a.maxItems=o),a.type="array",a.items=gv(i.element,t,{...r,path:[...r.path,"items"]})},Lxs=(s,t,n,r)=>{var d;const a=n,i=s._zod.def;a.type="object",a.properties={};const l=i.shape;for(const u in l)a.properties[u]=gv(l[u],t,{...r,path:[...r.path,"properties",u]});const o=new Set(Object.keys(l)),c=new Set([...o].filter(u=>{const h=i.shape[u]._zod;return t.io==="input"?h.optin===void 0:h.optout===void 0}));c.size>0&&(a.required=Array.from(c)),((d=i.catchall)==null?void 0:d._zod.def.type)==="never"?a.additionalProperties=!1:i.catchall?i.catchall&&(a.additionalProperties=gv(i.catchall,t,{...r,path:[...r.path,"additionalProperties"]})):t.io==="output"&&(a.additionalProperties=!1)},Rxs=(s,t,n,r)=>{const a=s._zod.def,i=a.inclusive===!1,l=a.options.map((o,c)=>gv(o,t,{...r,path:[...r.path,i?"oneOf":"anyOf",c]}));i?n.oneOf=l:n.anyOf=l},Dxs=(s,t,n,r)=>{const a=s._zod.def,i=gv(a.left,t,{...r,path:[...r.path,"allOf",0]}),l=gv(a.right,t,{...r,path:[...r.path,"allOf",1]}),o=d=>"allOf"in d&&Object.keys(d).length===1,c=[...o(i)?i.allOf:[i],...o(l)?l.allOf:[l]];n.allOf=c},Oxs=(s,t,n,r)=>{const a=s._zod.def,i=gv(a.innerType,t,r),l=t.seen.get(s);t.target==="openapi-3.0"?(l.ref=a.innerType,n.nullable=!0):n.anyOf=[i,{type:"null"}]},Fxs=(s,t,n,r)=>{const a=s._zod.def;gv(a.innerType,t,r);const i=t.seen.get(s);i.ref=a.innerType},zxs=(s,t,n,r)=>{const a=s._zod.def;gv(a.innerType,t,r);const i=t.seen.get(s);i.ref=a.innerType,n.default=JSON.parse(JSON.stringify(a.defaultValue))},Bxs=(s,t,n,r)=>{const a=s._zod.def;gv(a.innerType,t,r);const i=t.seen.get(s);i.ref=a.innerType,t.io==="input"&&(n._prefault=JSON.parse(JSON.stringify(a.defaultValue)))},$xs=(s,t,n,r)=>{const a=s._zod.def;gv(a.innerType,t,r);const i=t.seen.get(s);i.ref=a.innerType;let l;try{l=a.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}n.default=l},Uxs=(s,t,n,r)=>{const a=s._zod.def,i=a.in._zod.traits.has("$ZodTransform"),l=t.io==="input"?i?a.out:a.in:a.out;gv(l,t,r);const o=t.seen.get(s);o.ref=l},qxs=(s,t,n,r)=>{const a=s._zod.def;gv(a.innerType,t,r);const i=t.seen.get(s);i.ref=a.innerType,n.readOnly=!0},v3t=(s,t,n,r)=>{const a=s._zod.def;gv(a.innerType,t,r);const i=t.seen.get(s);i.ref=a.innerType},Vxs=ca("ZodISODateTime",(s,t)=>{Wps.init(s,t),Vp.init(s,t)});function Hxs(s){return Qgs(Vxs,s)}const Gxs=ca("ZodISODate",(s,t)=>{Kps.init(s,t),Vp.init(s,t)});function Wxs(s){return Jgs(Gxs,s)}const Kxs=ca("ZodISOTime",(s,t)=>{Yps.init(s,t),Vp.init(s,t)});function Yxs(s){return exs(Kxs,s)}const Zxs=ca("ZodISODuration",(s,t)=>{Zps.init(s,t),Vp.init(s,t)});function Xxs(s){return txs(Zxs,s)}const b3t=(s,t)=>{t3t.init(s,t),s.name="ZodError",Object.defineProperties(s,{format:{value:n=>Ffs(s,n)},flatten:{value:n=>Ofs(s,n)},addIssue:{value:n=>{s.issues.push(n),s.message=JSON.stringify(s.issues,c7e,2)}},addIssues:{value:n=>{s.issues.push(...n),s.message=JSON.stringify(s.issues,c7e,2)}},isEmpty:{get(){return s.issues.length===0}}})},Qxs=ca("ZodError",b3t),q2=ca("ZodError",b3t,{Parent:Error}),Jxs=WHe(q2),eys=KHe(q2),tys=F3e(q2),sys=z3e(q2),nys=$fs(q2),rys=Ufs(q2),ays=qfs(q2),iys=Vfs(q2),oys=Hfs(q2),lys=Gfs(q2),cys=Wfs(q2),dys=Kfs(q2),Sot=new WeakMap;function gee(s,t,n){const r=Object.getPrototypeOf(s);let a=Sot.get(r);if(a||(a=new Set,Sot.set(r,a)),!a.has(t)){a.add(t);for(const i in n){const l=n[i];Object.defineProperty(r,i,{configurable:!0,enumerable:!1,get(){const o=l.bind(this);return Object.defineProperty(this,i,{configurable:!0,writable:!0,enumerable:!0,value:o}),o},set(o){Object.defineProperty(this,i,{configurable:!0,writable:!0,enumerable:!0,value:o})}})}}}const Eg=ca("ZodType",(s,t)=>(Ag.init(s,t),Object.assign(s["~standard"],{jsonSchema:{input:dSe(s,"input"),output:dSe(s,"output")}}),s.toJSONSchema=wxs(s,{}),s.def=t,s.type=t.type,Object.defineProperty(s,"_def",{value:t}),s.parse=(n,r)=>Jxs(s,n,r,{callee:s.parse}),s.safeParse=(n,r)=>tys(s,n,r),s.parseAsync=async(n,r)=>eys(s,n,r,{callee:s.parseAsync}),s.safeParseAsync=async(n,r)=>sys(s,n,r),s.spa=s.safeParseAsync,s.encode=(n,r)=>nys(s,n,r),s.decode=(n,r)=>rys(s,n,r),s.encodeAsync=async(n,r)=>ays(s,n,r),s.decodeAsync=async(n,r)=>iys(s,n,r),s.safeEncode=(n,r)=>oys(s,n,r),s.safeDecode=(n,r)=>lys(s,n,r),s.safeEncodeAsync=async(n,r)=>cys(s,n,r),s.safeDecodeAsync=async(n,r)=>dys(s,n,r),gee(s,"ZodType",{check(...n){const r=this.def;return this.clone(ZM(r,{checks:[...r.checks??[],...n.map(a=>typeof a=="function"?{_zod:{check:a,def:{check:"custom"},onattach:[]}}:a)]}),{parent:!0})},with(...n){return this.check(...n)},clone(n,r){return XM(this,n,r)},brand(){return this},register(n,r){return n.add(this,r),this},refine(n,r){return this.check(a0s(n,r))},superRefine(n,r){return this.check(i0s(n,r))},overwrite(n){return this.check(qq(n))},optional(){return Tot(this)},exactOptional(){return Gys(this)},nullable(){return Mot(this)},nullish(){return Tot(Mot(this))},nonoptional(n){return Qys(this,n)},array(){return Dys(this)},or(n){return zys([this,n])},and(n){return $ys(this,n)},transform(n){return Pot(this,Vys(n))},default(n){return Yys(this,n)},prefault(n){return Xys(this,n)},catch(n){return e0s(this,n)},pipe(n){return Pot(this,n)},readonly(){return n0s(this)},describe(n){const r=this.clone();return jW.add(r,{description:n}),r},meta(...n){if(n.length===0)return jW.get(this);const r=this.clone();return jW.add(r,n[0]),r},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(n){return n(this)}}),Object.defineProperty(s,"description",{get(){var n;return(n=jW.get(s))==null?void 0:n.description},configurable:!0}),s)),_3t=ca("_ZodString",(s,t)=>{YHe.init(s,t),Eg.init(s,t),s._zod.processJSONSchema=(r,a,i)=>Nxs(s,r,a);const n=s._zod.bag;s.format=n.format??null,s.minLength=n.minimum??null,s.maxLength=n.maximum??null,gee(s,"_ZodString",{regex(...r){return this.check(oxs(...r))},includes(...r){return this.check(dxs(...r))},startsWith(...r){return this.check(uxs(...r))},endsWith(...r){return this.check(hxs(...r))},min(...r){return this.check(cSe(...r))},max(...r){return this.check(f3t(...r))},length(...r){return this.check(p3t(...r))},nonempty(...r){return this.check(cSe(1,...r))},lowercase(r){return this.check(lxs(r))},uppercase(r){return this.check(cxs(r))},trim(){return this.check(fxs())},normalize(...r){return this.check(mxs(...r))},toLowerCase(){return this.check(pxs())},toUpperCase(){return this.check(gxs())},slugify(){return this.check(xxs())}})}),uys=ca("ZodString",(s,t)=>{YHe.init(s,t),_3t.init(s,t),s.email=n=>s.check(Mgs(hys,n)),s.url=n=>s.check(Dgs(mys,n)),s.jwt=n=>s.check(Xgs(Ays,n)),s.emoji=n=>s.check(Ogs(fys,n)),s.guid=n=>s.check(wot(Cot,n)),s.uuid=n=>s.check(Pgs(Xne,n)),s.uuidv4=n=>s.check(Igs(Xne,n)),s.uuidv6=n=>s.check(Lgs(Xne,n)),s.uuidv7=n=>s.check(Rgs(Xne,n)),s.nanoid=n=>s.check(Fgs(pys,n)),s.guid=n=>s.check(wot(Cot,n)),s.cuid=n=>s.check(zgs(gys,n)),s.cuid2=n=>s.check(Bgs(xys,n)),s.ulid=n=>s.check($gs(yys,n)),s.base64=n=>s.check(Kgs(kys,n)),s.base64url=n=>s.check(Ygs(Sys,n)),s.xid=n=>s.check(Ugs(vys,n)),s.ksuid=n=>s.check(qgs(bys,n)),s.ipv4=n=>s.check(Vgs(_ys,n)),s.ipv6=n=>s.check(Hgs(wys,n)),s.cidrv4=n=>s.check(Ggs(jys,n)),s.cidrv6=n=>s.check(Wgs(Nys,n)),s.e164=n=>s.check(Zgs(Cys,n)),s.datetime=n=>s.check(Hxs(n)),s.date=n=>s.check(Wxs(n)),s.time=n=>s.check(Yxs(n)),s.duration=n=>s.check(Xxs(n))});function uc(s){return Tgs(uys,s)}const Vp=ca("ZodStringFormat",(s,t)=>{dp.init(s,t),_3t.init(s,t)}),hys=ca("ZodEmail",(s,t)=>{Fps.init(s,t),Vp.init(s,t)}),Cot=ca("ZodGUID",(s,t)=>{Dps.init(s,t),Vp.init(s,t)}),Xne=ca("ZodUUID",(s,t)=>{Ops.init(s,t),Vp.init(s,t)}),mys=ca("ZodURL",(s,t)=>{zps.init(s,t),Vp.init(s,t)}),fys=ca("ZodEmoji",(s,t)=>{Bps.init(s,t),Vp.init(s,t)}),pys=ca("ZodNanoID",(s,t)=>{$ps.init(s,t),Vp.init(s,t)}),gys=ca("ZodCUID",(s,t)=>{Ups.init(s,t),Vp.init(s,t)}),xys=ca("ZodCUID2",(s,t)=>{qps.init(s,t),Vp.init(s,t)}),yys=ca("ZodULID",(s,t)=>{Vps.init(s,t),Vp.init(s,t)}),vys=ca("ZodXID",(s,t)=>{Hps.init(s,t),Vp.init(s,t)}),bys=ca("ZodKSUID",(s,t)=>{Gps.init(s,t),Vp.init(s,t)}),_ys=ca("ZodIPv4",(s,t)=>{Xps.init(s,t),Vp.init(s,t)}),wys=ca("ZodIPv6",(s,t)=>{Qps.init(s,t),Vp.init(s,t)}),jys=ca("ZodCIDRv4",(s,t)=>{Jps.init(s,t),Vp.init(s,t)}),Nys=ca("ZodCIDRv6",(s,t)=>{egs.init(s,t),Vp.init(s,t)}),kys=ca("ZodBase64",(s,t)=>{tgs.init(s,t),Vp.init(s,t)}),Sys=ca("ZodBase64URL",(s,t)=>{ngs.init(s,t),Vp.init(s,t)}),Cys=ca("ZodE164",(s,t)=>{rgs.init(s,t),Vp.init(s,t)}),Ays=ca("ZodJWT",(s,t)=>{igs.init(s,t),Vp.init(s,t)}),w3t=ca("ZodNumber",(s,t)=>{d3t.init(s,t),Eg.init(s,t),s._zod.processJSONSchema=(r,a,i)=>kxs(s,r,a),gee(s,"ZodNumber",{gt(r,a){return this.check(Not(r,a))},gte(r,a){return this.check(yIe(r,a))},min(r,a){return this.check(yIe(r,a))},lt(r,a){return this.check(jot(r,a))},lte(r,a){return this.check(xIe(r,a))},max(r,a){return this.check(xIe(r,a))},int(r){return this.check(Aot(r))},safe(r){return this.check(Aot(r))},positive(r){return this.check(Not(0,r))},nonnegative(r){return this.check(yIe(0,r))},negative(r){return this.check(jot(0,r))},nonpositive(r){return this.check(xIe(0,r))},multipleOf(r,a){return this.check(kot(r,a))},step(r,a){return this.check(kot(r,a))},finite(){return this}});const n=s._zod.bag;s.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,s.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,s.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),s.isFinite=!0,s.format=n.format??null});function xY(s){return sxs(w3t,s)}const Eys=ca("ZodNumberFormat",(s,t)=>{ogs.init(s,t),w3t.init(s,t)});function Aot(s){return nxs(Eys,s)}const Tys=ca("ZodBoolean",(s,t)=>{lgs.init(s,t),Eg.init(s,t),s._zod.processJSONSchema=(n,r,a)=>Sxs(s,n,r)});function Mys(s){return rxs(Tys,s)}const Pys=ca("ZodUnknown",(s,t)=>{cgs.init(s,t),Eg.init(s,t),s._zod.processJSONSchema=(n,r,a)=>Axs()});function Eot(){return axs(Pys)}const Iys=ca("ZodNever",(s,t)=>{dgs.init(s,t),Eg.init(s,t),s._zod.processJSONSchema=(n,r,a)=>Cxs(s,n,r)});function Lys(s){return ixs(Iys,s)}const Rys=ca("ZodArray",(s,t)=>{ugs.init(s,t),Eg.init(s,t),s._zod.processJSONSchema=(n,r,a)=>Ixs(s,n,r,a),s.element=t.element,gee(s,"ZodArray",{min(n,r){return this.check(cSe(n,r))},nonempty(n){return this.check(cSe(1,n))},max(n,r){return this.check(f3t(n,r))},length(n,r){return this.check(p3t(n,r))},unwrap(){return this.element}})});function Dys(s,t){return yxs(Rys,s,t)}const Oys=ca("ZodObject",(s,t)=>{mgs.init(s,t),Eg.init(s,t),s._zod.processJSONSchema=(n,r,a)=>Lxs(s,n,r,a),tm(s,"shape",()=>t.shape),gee(s,"ZodObject",{keyof(){return ZHe(Object.keys(this._zod.def.shape))},catchall(n){return this.clone({...this._zod.def,catchall:n})},passthrough(){return this.clone({...this._zod.def,catchall:Eot()})},loose(){return this.clone({...this._zod.def,catchall:Eot()})},strict(){return this.clone({...this._zod.def,catchall:Lys()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(n){return Mfs(this,n)},safeExtend(n){return Pfs(this,n)},merge(n){return Ifs(this,n)},pick(n){return Efs(this,n)},omit(n){return Tfs(this,n)},partial(...n){return Lfs(j3t,this,n[0])},required(...n){return Rfs(N3t,this,n[0])}})});function t4(s,t){const n={type:"object",shape:s??{},...ml(t)};return new Oys(n)}const Fys=ca("ZodUnion",(s,t)=>{fgs.init(s,t),Eg.init(s,t),s._zod.processJSONSchema=(n,r,a)=>Rxs(s,n,r,a),s.options=t.options});function zys(s,t){return new Fys({type:"union",options:s,...ml(t)})}const Bys=ca("ZodIntersection",(s,t)=>{pgs.init(s,t),Eg.init(s,t),s._zod.processJSONSchema=(n,r,a)=>Dxs(s,n,r,a)});function $ys(s,t){return new Bys({type:"intersection",left:s,right:t})}const u7e=ca("ZodEnum",(s,t)=>{ggs.init(s,t),Eg.init(s,t),s._zod.processJSONSchema=(r,a,i)=>Exs(s,r,a),s.enum=t.entries,s.options=Object.values(t.entries);const n=new Set(Object.keys(t.entries));s.extract=(r,a)=>{const i={};for(const l of r)if(n.has(l))i[l]=t.entries[l];else throw new Error(`Key ${l} not found in enum`);return new u7e({...t,checks:[],...ml(a),entries:i})},s.exclude=(r,a)=>{const i={...t.entries};for(const l of r)if(n.has(l))delete i[l];else throw new Error(`Key ${l} not found in enum`);return new u7e({...t,checks:[],...ml(a),entries:i})}});function ZHe(s,t){const n=Array.isArray(s)?Object.fromEntries(s.map(r=>[r,r])):s;return new u7e({type:"enum",entries:n,...ml(t)})}const Uys=ca("ZodLiteral",(s,t)=>{xgs.init(s,t),Eg.init(s,t),s._zod.processJSONSchema=(n,r,a)=>Txs(s,n,r),s.values=new Set(t.values),Object.defineProperty(s,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function c0(s,t){return new Uys({type:"literal",values:Array.isArray(s)?s:[s],...ml(t)})}const qys=ca("ZodTransform",(s,t)=>{ygs.init(s,t),Eg.init(s,t),s._zod.processJSONSchema=(n,r,a)=>Pxs(s,n),s._zod.parse=(n,r)=>{if(r.direction==="backward")throw new YCt(s.constructor.name);n.addIssue=i=>{if(typeof i=="string")n.issues.push(KZ(i,n.value,t));else{const l=i;l.fatal&&(l.continue=!1),l.code??(l.code="custom"),l.input??(l.input=n.value),l.inst??(l.inst=s),n.issues.push(KZ(l))}};const a=t.transform(n.value,n);return a instanceof Promise?a.then(i=>(n.value=i,n.fallback=!0,n)):(n.value=a,n.fallback=!0,n)}});function Vys(s){return new qys({type:"transform",transform:s})}const j3t=ca("ZodOptional",(s,t)=>{m3t.init(s,t),Eg.init(s,t),s._zod.processJSONSchema=(n,r,a)=>v3t(s,n,r,a),s.unwrap=()=>s._zod.def.innerType});function Tot(s){return new j3t({type:"optional",innerType:s})}const Hys=ca("ZodExactOptional",(s,t)=>{vgs.init(s,t),Eg.init(s,t),s._zod.processJSONSchema=(n,r,a)=>v3t(s,n,r,a),s.unwrap=()=>s._zod.def.innerType});function Gys(s){return new Hys({type:"optional",innerType:s})}const Wys=ca("ZodNullable",(s,t)=>{bgs.init(s,t),Eg.init(s,t),s._zod.processJSONSchema=(n,r,a)=>Oxs(s,n,r,a),s.unwrap=()=>s._zod.def.innerType});function Mot(s){return new Wys({type:"nullable",innerType:s})}const Kys=ca("ZodDefault",(s,t)=>{_gs.init(s,t),Eg.init(s,t),s._zod.processJSONSchema=(n,r,a)=>zxs(s,n,r,a),s.unwrap=()=>s._zod.def.innerType,s.removeDefault=s.unwrap});function Yys(s,t){return new Kys({type:"default",innerType:s,get defaultValue(){return typeof t=="function"?t():QCt(t)}})}const Zys=ca("ZodPrefault",(s,t)=>{wgs.init(s,t),Eg.init(s,t),s._zod.processJSONSchema=(n,r,a)=>Bxs(s,n,r,a),s.unwrap=()=>s._zod.def.innerType});function Xys(s,t){return new Zys({type:"prefault",innerType:s,get defaultValue(){return typeof t=="function"?t():QCt(t)}})}const N3t=ca("ZodNonOptional",(s,t)=>{jgs.init(s,t),Eg.init(s,t),s._zod.processJSONSchema=(n,r,a)=>Fxs(s,n,r,a),s.unwrap=()=>s._zod.def.innerType});function Qys(s,t){return new N3t({type:"nonoptional",innerType:s,...ml(t)})}const Jys=ca("ZodCatch",(s,t)=>{Ngs.init(s,t),Eg.init(s,t),s._zod.processJSONSchema=(n,r,a)=>$xs(s,n,r,a),s.unwrap=()=>s._zod.def.innerType,s.removeCatch=s.unwrap});function e0s(s,t){return new Jys({type:"catch",innerType:s,catchValue:typeof t=="function"?t:()=>t})}const t0s=ca("ZodPipe",(s,t)=>{kgs.init(s,t),Eg.init(s,t),s._zod.processJSONSchema=(n,r,a)=>Uxs(s,n,r,a),s.in=t.in,s.out=t.out});function Pot(s,t){return new t0s({type:"pipe",in:s,out:t})}const s0s=ca("ZodReadonly",(s,t)=>{Sgs.init(s,t),Eg.init(s,t),s._zod.processJSONSchema=(n,r,a)=>qxs(s,n,r,a),s.unwrap=()=>s._zod.def.innerType});function n0s(s){return new s0s({type:"readonly",innerType:s})}const r0s=ca("ZodCustom",(s,t)=>{Cgs.init(s,t),Eg.init(s,t),s._zod.processJSONSchema=(n,r,a)=>Mxs(s,n)});function a0s(s,t={}){return vxs(r0s,s,t)}function i0s(s,t){return bxs(s,t)}var o0s=Object.defineProperty,l0s=(s,t)=>o0s(s,"name",{value:t,configurable:!0}),c0s=k.forwardRef(l0s(function(t,n){return e.jsx(hi.label,{...t,ref:n,onMouseDown:r=>{var i;r.target.closest("button, input, select, textarea")||((i=t.onMouseDown)==null||i.call(t,r),!r.defaultPrevented&&r.detail>1&&r.preventDefault())}})},"Label")),k3t=c0s;const d0s=gF("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),re=k.forwardRef(({className:s,...t},n)=>e.jsx(k3t,{ref:n,className:Ot(d0s(),s),...t}));re.displayName=k3t.displayName;const $3e=ofs,S3t=k.createContext({}),Sp=({...s})=>e.jsx(S3t.Provider,{value:{name:s.name},children:e.jsx(nfs,{...s})}),U3e=()=>{const s=k.useContext(S3t),t=k.useContext(C3t),{getFieldState:n,formState:r}=ifs(),a=n(s.name,r);if(!s)throw new Error("useFormField should be used within ");const{id:i}=t;return{id:i,name:s.name,formItemId:`${i}-form-item`,formDescriptionId:`${i}-form-item-description`,formMessageId:`${i}-form-item-message`,...a}},C3t=k.createContext({}),Zf=k.forwardRef(({className:s,...t},n)=>{const r=k.useId();return e.jsx(C3t.Provider,{value:{id:r},children:e.jsx("div",{ref:n,className:Ot("space-y-2",s),...t})})});Zf.displayName="FormItem";const Xf=k.forwardRef(({className:s,...t},n)=>{const{error:r,formItemId:a}=U3e();return e.jsx(re,{ref:n,className:Ot(r&&"text-destructive",s),htmlFor:a,...t})});Xf.displayName="FormLabel";const Qf=k.forwardRef(({...s},t)=>{const{error:n,formItemId:r,formDescriptionId:a,formMessageId:i}=U3e();return e.jsx(BVe,{ref:t,id:r,"aria-describedby":n?`${a} ${i}`:`${a}`,"aria-invalid":!!n,...s})});Qf.displayName="FormControl";const eNe=k.forwardRef(({className:s,...t},n)=>{const{formDescriptionId:r}=U3e();return e.jsx("p",{ref:n,id:r,className:Ot("text-sm text-muted-foreground",s),...t})});eNe.displayName="FormDescription";const ib=k.forwardRef(({className:s,children:t,...n},r)=>{const{error:a,formMessageId:i}=U3e(),l=a?String(a==null?void 0:a.message):t;return l?e.jsx("p",{ref:r,id:i,className:Ot("text-sm font-medium text-destructive",s),...n,children:l}):null});ib.displayName="FormMessage";const be=k.forwardRef(({className:s,type:t,...n},r)=>e.jsx("input",{type:t,className:Ot("flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-base ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",s),ref:r,...n}));be.displayName="Input";var u0s=Object.defineProperty,h0s=(s,t)=>u0s(s,"name",{value:t,configurable:!0});function XHe(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])}h0s(XHe,"usePrevious");var m0s=Object.defineProperty,au=(s,t)=>m0s(s,"name",{value:t,configurable:!0}),f0s=[" ","Enter","ArrowUp","ArrowDown"],p0s=[" ","Enter"],bU="Select",[q3e,V3e,g0s]=fF(bU),[wF,PQn]=qm(bU,[g0s,Q5]),QHe=Q5(),[x0s,QM]=wF(bU),[y0s,v0s]=wF(bU);function A3t(s){const{__scopeSelect:t,children:n,open:r,defaultOpen:a,onOpenChange:i,value:l,defaultValue:o,onValueChange:c,dir:d,name:u,autoComplete:h,disabled:m,required:p,form:g,internal_do_not_use_render:x}=s,y=QHe(t),[v,_]=k.useState(null),[j,C]=k.useState(null),[A,M]=k.useState(!1),I=e4(d),[P,R]=ox({prop:r,defaultProp:a??!1,onChange:i,caller:bU}),[O,B]=ox({prop:l,defaultProp:o,onChange:c,caller:bU}),U=k.useRef(null),G=k.useRef(O);k.useEffect(()=>{const le=g?v==null?void 0:v.ownerDocument.getElementById(g):v==null?void 0:v.form;if(le instanceof HTMLFormElement){const fe=au(()=>B(G.current),"reset");return le.addEventListener("reset",fe),()=>le.removeEventListener("reset",fe)}},[g,v,B]);const H=v?!!g||!!v.closest("form"):!0,[Y,se]=k.useState(new Set),ee=$x(),oe=Array.from(Y).map(le=>le.props.value).join(";"),me=k.useCallback(le=>{se(fe=>new Set(fe).add(le))},[]),Q=k.useCallback(le=>{se(fe=>{const _e=new Set(fe);return _e.delete(le),_e})},[]),te={required:p,trigger:v,onTriggerChange:_,valueNode:j,onValueNodeChange:C,valueNodeHasChildren:A,onValueNodeHasChildrenChange:M,contentId:ee,value:O,onValueChange:B,open:P,onOpenChange:R,dir:I,triggerPointerDownPosRef:U,disabled:m,name:u,autoComplete:h,form:g,nativeOptions:Y,nativeSelectKey:oe,isFormControl:H};return e.jsx(ree,{...y,children:e.jsx(x0s,{scope:t,...te,children:e.jsx(q3e.Provider,{scope:t,children:e.jsx(y0s,{scope:t,onNativeOptionAdd:me,onNativeOptionRemove:Q,children:z3t(x)?x(te):n})})})})}au(A3t,"SelectProvider");var b0s=au(s=>{const{__scopeSelect:t,children:n,...r}=s;return e.jsx(A3t,{__scopeSelect:t,...r,internal_do_not_use_render:({isFormControl:a})=>e.jsxs(e.Fragment,{children:[n,a?e.jsx(q0s,{__scopeSelect:t}):null]})})},"Select"),_0s="SelectTrigger",E3t=k.forwardRef(au(function(t,n){const{__scopeSelect:r,disabled:a=!1,...i}=t,l=QHe(r),o=QM(_0s,r),c=o.disabled||a,d=Ao(n,o.onTriggerChange),u=V3e(r),h=k.useRef("touch"),[m,p,g]=eGe(y=>{const v=u().filter(C=>!C.disabled),_=v.find(C=>C.value===o.value),j=tGe(v,y,_);j!==void 0&&o.onValueChange(j.value)}),x=au(y=>{c||(o.onOpenChange(!0),g()),y&&(o.triggerPointerDownPosRef.current={x:Math.round(y.pageX),y:Math.round(y.pageY)})},"handleOpen");return e.jsx(aee,{asChild:!0,...l,children:e.jsx(hi.button,{type:"button",role:"combobox","aria-controls":o.open?o.contentId:void 0,"aria-expanded":o.open,"aria-required":o.required,"aria-autocomplete":"none",dir:o.dir,"data-state":o.open?"open":"closed",disabled:c,"data-disabled":c?"":void 0,"data-placeholder":xee(o.value)?"":void 0,...i,ref:d,onClick:ga(i.onClick,y=>{y.currentTarget.focus(),h.current!=="mouse"&&x(y)}),onPointerDown:ga(i.onPointerDown,y=>{h.current=y.pointerType;const v=y.target;v.hasPointerCapture(y.pointerId)&&v.releasePointerCapture(y.pointerId),y.button===0&&y.ctrlKey===!1&&y.pointerType==="mouse"&&(x(y),y.preventDefault())}),onKeyDown:ga(i.onKeyDown,y=>{const v=m.current!=="";!(y.ctrlKey||y.altKey||y.metaKey)&&y.key.length===1&&p(y.key),!(v&&y.key===" ")&&f0s.includes(y.key)&&(x(),y.preventDefault())})})})},"SelectTrigger")),w0s="SelectValue",j0s=k.forwardRef(au(function(t,n){const{__scopeSelect:r,className:a,style:i,children:l,placeholder:o="",...c}=t,d=QM(w0s,r),{onValueNodeHasChildrenChange:u}=d,h=l!==void 0,m=Ao(n,d.onValueNodeChange);_m(()=>{u(h)},[u,h]);const p=xee(d.value);return e.jsx(hi.span,{...c,asChild:p?!1:c.asChild,ref:m,style:{pointerEvents:"none"},children:e.jsx(k.Fragment,{children:p?o:l},p?"placeholder":"value")})},"SelectValue")),N0s=k.forwardRef(au(function(t,n){const{__scopeSelect:r,children:a,...i}=t;return e.jsx(hi.span,{"aria-hidden":!0,...i,ref:n,children:a||"▼"})},"SelectIcon")),k0s="SelectPortal",[S0s,C0s]=wF(k0s,{forceMount:void 0}),A0s=au(s=>{const{__scopeSelect:t,forceMount:n,...r}=s;return e.jsx(S0s,{scope:s.__scopeSelect,forceMount:n,children:e.jsx(QJ,{asChild:!0,...r})})},"SelectPortal"),LO="SelectContent",T3t=k.forwardRef(au(function(t,n){const r=C0s(LO,t.__scopeSelect),{forceMount:a=r.forceMount,...i}=t,l=QM(LO,t.__scopeSelect),[o,c]=k.useState();return _m(()=>{c(new DocumentFragment)},[]),e.jsx(cx,{present:a||l.open,children:({present:d})=>d?e.jsx(M0s,{...i,ref:n}):e.jsx(E0s,{...i,fragment:o})})},"SelectContent")),E0s=k.forwardRef(au(function(t,n){const{__scopeSelect:r,children:a,fragment:i}=t;return i?a1.createPortal(e.jsx(M3t,{scope:r,children:e.jsx(q3e.Slot,{scope:r,children:e.jsx("div",{ref:n,children:a})})}),i):null},"SelectContentFragment")),vN=10,[M3t,jF]=wF(LO),T0s=xk("SelectContent.RemoveScroll"),M0s=k.forwardRef(au(function(t,n){const{__scopeSelect:r}=t,{position:a="item-aligned",onCloseAutoFocus:i,onEscapeKeyDown:l,onPointerDownOutside:o,side:c,sideOffset:d,align:u,alignOffset:h,arrowPadding:m,collisionBoundary:p,collisionPadding:g,sticky:x,hideWhenDetached:y,avoidCollisions:v,..._}=t,j=QM(LO,r),[C,A]=k.useState(null),[M,I]=k.useState(null),P=Ao(n,A),[R,O]=k.useState(null),[B,U]=k.useState(null),G=V3e(r),[H,Y]=k.useState(!1),se=k.useRef(!1);k.useEffect(()=>{if(C)return i3e(C)},[C]),Mq();const ee=k.useCallback(Te=>{const[Ie,...Ue]=G().map(Ye=>Ye.ref.current),[Be]=Ue.slice(-1),je=document.activeElement;for(const Ye of Te)if(Ye===je||(Ye==null||Ye.scrollIntoView({block:"nearest"}),Ye===Ie&&M&&(M.scrollTop=0),Ye===Be&&M&&(M.scrollTop=M.scrollHeight),Ye==null||Ye.focus(),document.activeElement!==je))return},[G,M]),oe=k.useCallback(()=>ee([R,C]),[ee,R,C]);k.useEffect(()=>{H&&oe()},[H,oe]);const{onOpenChange:me,triggerPointerDownPosRef:Q}=j;k.useEffect(()=>{if(C){let Te={x:0,y:0};const Ie=au(Be=>{var je,Ye;Te={x:Math.abs(Math.round(Be.pageX)-(((je=Q.current)==null?void 0:je.x)??0)),y:Math.abs(Math.round(Be.pageY)-(((Ye=Q.current)==null?void 0:Ye.y)??0))}},"handlePointerMove"),Ue=au(Be=>{Te.x<=10&&Te.y<=10?Be.preventDefault():Be.composedPath().includes(C)||me(!1),document.removeEventListener("pointermove",Ie),Q.current=null},"handlePointerUp");return Q.current!==null&&(document.addEventListener("pointermove",Ie),document.addEventListener("pointerup",Ue,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",Ie),document.removeEventListener("pointerup",Ue,{capture:!0})}}},[C,me,Q]),k.useEffect(()=>{const Te=au(()=>me(!1),"close");return window.addEventListener("blur",Te),window.addEventListener("resize",Te),()=>{window.removeEventListener("blur",Te),window.removeEventListener("resize",Te)}},[me]);const[te,le]=eGe(Te=>{const Ie=G().filter(je=>!je.disabled),Ue=Ie.find(je=>je.ref.current===document.activeElement),Be=tGe(Ie,Te,Ue);Be&&setTimeout(()=>{var je;return(je=Be.ref.current)==null?void 0:je.focus()})}),fe=k.useCallback((Te,Ie,Ue)=>{const Be=!se.current&&!Ue;(j.value!==void 0&&j.value===Ie||Be)&&(O(Te),Be&&(se.current=!0))},[j.value]),_e=k.useCallback(()=>C==null?void 0:C.focus(),[C]),ve=k.useCallback((Te,Ie,Ue)=>{const Be=!se.current&&!Ue;(j.value!==void 0&&j.value===Ie||Be)&&U(Te)},[j.value]),he=a==="popper"?Iot:P0s,Se=he===Iot?{side:c,sideOffset:d,align:u,alignOffset:h,arrowPadding:m,collisionBoundary:p,collisionPadding:g,sticky:x,hideWhenDetached:y,avoidCollisions:v}:{};return e.jsx(M3t,{scope:r,content:C,viewport:M,onViewportChange:I,itemRefCallback:fe,selectedItem:R,onItemLeave:_e,itemTextRefCallback:ve,focusSelectedItem:oe,selectedItemText:B,position:a,isPositioned:H,searchRef:te,children:e.jsx(eee,{as:T0s,allowPinchZoom:!0,children:e.jsx(r3e,{asChild:!0,trapped:j.open,onMountAutoFocus:Te=>{Te.preventDefault()},onUnmountAutoFocus:ga(i,Te=>{var Ie;(Ie=j.trigger)==null||Ie.focus({preventScroll:!0}),Te.preventDefault()}),children:e.jsx(pF,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:l,onPointerDownOutside:o,onFocusOutside:Te=>Te.preventDefault(),onDismiss:()=>j.onOpenChange(!1),children:e.jsx(he,{role:"listbox",id:j.contentId,"data-state":j.open?"open":"closed",dir:j.dir,onContextMenu:Te=>Te.preventDefault(),..._,...Se,onPlaced:()=>Y(!0),ref:P,style:{display:"flex",flexDirection:"column",outline:"none",..._.style},onKeyDown:ga(_.onKeyDown,Te=>{const Ie=Te.ctrlKey||Te.altKey||Te.metaKey;if(Te.key==="Tab"&&Te.preventDefault(),!Ie&&Te.key.length===1&&le(Te.key),["ArrowUp","ArrowDown","Home","End"].includes(Te.key)){let Be=G().filter(je=>!je.disabled).map(je=>je.ref.current);if(["ArrowUp","End"].includes(Te.key)&&(Be=Be.slice().reverse()),["ArrowUp","ArrowDown"].includes(Te.key)){const je=Te.target,Ye=Be.indexOf(je);Be=Be.slice(Ye+1)}setTimeout(()=>ee(Be)),Te.preventDefault()}})})})})})})},"SelectContentImpl")),P0s=k.forwardRef(au(function(t,n){const{__scopeSelect:r,onPlaced:a,...i}=t,l=QM(LO,r),o=jF(LO,r),[c,d]=k.useState(null),[u,h]=k.useState(null),m=Ao(n,h),p=V3e(r),g=k.useRef(!1),x=k.useRef(!0),{viewport:y,selectedItem:v,selectedItemText:_,focusSelectedItem:j}=o,C=k.useCallback(()=>{if(l.trigger&&l.valueNode&&c&&u&&y&&v&&_){const P=l.trigger.getBoundingClientRect(),R=u.getBoundingClientRect(),O=l.valueNode.getBoundingClientRect(),B=_.getBoundingClientRect();if(l.dir!=="rtl"){const je=B.left-R.left,Ye=O.left-je,Ee=P.left-Ye,Re=P.width+Ee,ke=Math.max(Re,R.width),Fe=window.innerWidth-vN,Oe=xU(Ye,[vN,Math.max(vN,Fe-ke)]);c.style.minWidth=Re+"px",c.style.left=Oe+"px"}else{const je=R.right-B.right,Ye=window.innerWidth-O.right-je,Ee=window.innerWidth-P.right-Ye,Re=P.width+Ee,ke=Math.max(Re,R.width),Fe=window.innerWidth-vN,Oe=xU(Ye,[vN,Math.max(vN,Fe-ke)]);c.style.minWidth=Re+"px",c.style.right=Oe+"px"}const U=p(),G=window.innerHeight-vN*2,H=y.scrollHeight,Y=window.getComputedStyle(u),se=parseInt(Y.borderTopWidth,10),ee=parseInt(Y.paddingTop,10),oe=parseInt(Y.borderBottomWidth,10),me=parseInt(Y.paddingBottom,10),Q=se+ee+H+me+oe,te=Math.min(v.offsetHeight*5,Q),le=window.getComputedStyle(y),fe=parseInt(le.paddingTop,10),_e=parseInt(le.paddingBottom,10),ve=P.top+P.height/2-vN,he=G-ve,Se=v.offsetHeight/2,Te=v.offsetTop+Se,Ie=se+ee+Te,Ue=Q-Ie;if(Ie<=ve){const je=U.length>0&&v===U[U.length-1].ref.current;c.style.bottom="0px";const Ye=u.clientHeight-y.offsetTop-y.offsetHeight,Ee=Math.max(he,Se+(je?_e:0)+Ye+oe),Re=Ie+Ee;c.style.height=Re+"px"}else{const je=U.length>0&&v===U[0].ref.current;c.style.top="0px";const Ee=Math.max(ve,se+y.offsetTop+(je?fe:0)+Se)+Ue;c.style.height=Ee+"px",y.scrollTop=Ie-ve+y.offsetTop}c.style.margin=`${vN}px 0`,c.style.minHeight=te+"px",c.style.maxHeight=G+"px",a==null||a(),requestAnimationFrame(()=>g.current=!0)}},[p,l.trigger,l.valueNode,c,u,y,v,_,l.dir,a]);_m(()=>C(),[C]);const[A,M]=k.useState();_m(()=>{u&&M(window.getComputedStyle(u).zIndex)},[u]);const I=k.useCallback(P=>{P&&x.current===!0&&(C(),j==null||j(),x.current=!1)},[C,j]);return e.jsx(I0s,{scope:r,contentWrapper:c,shouldExpandOnScrollRef:g,onScrollButtonChange:I,children:e.jsx("div",{ref:d,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:A},children:e.jsx(hi.div,{...i,ref:m,style:{boxSizing:"border-box",maxHeight:"100%",...i.style}})})})},"SelectItemAlignedPosition")),Iot=k.forwardRef(au(function(t,n){const{__scopeSelect:r,align:a="start",collisionPadding:i=vN,...l}=t,o=QHe(r);return e.jsx(iee,{...o,...l,ref:n,align:a,collisionPadding:i,style:{boxSizing:"border-box",...l.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)"}})},"SelectPopperPosition")),[I0s,JHe]=wF(LO,{}),Lot="SelectViewport",L0s=k.forwardRef(au(function(t,n){const{__scopeSelect:r,nonce:a,...i}=t,l=jF(Lot,r),o=JHe(Lot,r),c=Ao(n,l.onViewportChange),d=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:a}),e.jsx(q3e.Slot,{scope:r,children:e.jsx(hi.div,{"data-radix-select-viewport":"",role:"presentation",...i,ref:c,style:{position:"relative",flex:1,overflow:"hidden auto",...i.style},onScroll:ga(i.onScroll,u=>{const h=u.currentTarget,{contentWrapper:m,shouldExpandOnScrollRef:p}=o;if(p!=null&&p.current&&m){const g=Math.abs(d.current-h.scrollTop);if(g>0){const x=window.innerHeight-vN*2,y=parseFloat(m.style.minHeight),v=parseFloat(m.style.height),_=Math.max(y,v);if(_0?A:0,m.style.justifyContent="flex-end")}}}d.current=h.scrollTop})})})]})},"SelectViewport")),R0s="SelectGroup",[IQn,D0s]=wF(R0s),O0s="SelectLabel",P3t=k.forwardRef(au(function(t,n){const{__scopeSelect:r,...a}=t,i=D0s(O0s,r);return e.jsx(hi.div,{id:i.id,...a,ref:n})},"SelectLabel")),h7e="SelectItem",[F0s,I3t]=wF(h7e),L3t=k.forwardRef(au(function(t,n){const{__scopeSelect:r,value:a,disabled:i=!1,textValue:l,...o}=t,c=QM(h7e,r),d=jF(h7e,r),u=c.value===a,[h,m]=k.useState(l??""),[p,g]=k.useState(!1),x=sp(C=>{var A;return(A=d.itemRefCallback)==null?void 0:A.call(d,C,a,i)}),y=Ao(n,x),v=$x(),_=k.useRef("touch"),j=au(()=>{i||(c.onValueChange(a),c.onOpenChange(!1))},"handleSelect");return e.jsx(F0s,{scope:r,value:a,disabled:i,textId:v,isSelected:u,onItemTextChange:k.useCallback(C=>{m(A=>A||((C==null?void 0:C.textContent)??"").trim())},[]),children:e.jsx(q3e.ItemSlot,{scope:r,value:a,disabled:i,textValue:h,children:e.jsx(hi.div,{role:"option","aria-labelledby":v,"data-highlighted":p?"":void 0,"aria-selected":u&&p,"data-state":u?"checked":"unchecked","aria-disabled":i||void 0,"data-disabled":i?"":void 0,tabIndex:i?void 0:-1,...o,ref:y,onFocus:ga(o.onFocus,()=>g(!0)),onBlur:ga(o.onBlur,()=>g(!1)),onClick:ga(o.onClick,()=>{_.current!=="mouse"&&j()}),onPointerUp:ga(o.onPointerUp,()=>{_.current==="mouse"&&j()}),onPointerDown:ga(o.onPointerDown,C=>{_.current=C.pointerType}),onPointerMove:ga(o.onPointerMove,C=>{var A;_.current=C.pointerType,i?(A=d.onItemLeave)==null||A.call(d):_.current==="mouse"&&C.currentTarget.focus({preventScroll:!0})}),onPointerLeave:ga(o.onPointerLeave,C=>{var A;C.currentTarget===document.activeElement&&((A=d.onItemLeave)==null||A.call(d))}),onKeyDown:ga(o.onKeyDown,C=>{var M;i||C.target!==C.currentTarget||((M=d.searchRef)==null?void 0:M.current)!==""&&C.key===" "||(p0s.includes(C.key)&&j(),C.key===" "&&C.preventDefault())})})})})},"SelectItem")),Qne="SelectItemText",z0s=k.forwardRef(au(function(t,n){const{__scopeSelect:r,className:a,style:i,...l}=t,o=QM(Qne,r),c=jF(Qne,r),d=I3t(Qne,r),u=v0s(Qne,r),[h,m]=k.useState(null),p=sp(j=>{var C;return(C=c.itemTextRefCallback)==null?void 0:C.call(c,j,d.value,d.disabled)}),g=Ao(n,m,d.onItemTextChange,p),x=h==null?void 0:h.textContent,y=k.useMemo(()=>e.jsx("option",{value:d.value,disabled:d.disabled,children:x},d.value),[d.disabled,d.value,x]),{onNativeOptionAdd:v,onNativeOptionRemove:_}=u;return _m(()=>(v(y),()=>_(y)),[v,_,y]),e.jsxs(e.Fragment,{children:[e.jsx(hi.span,{id:d.textId,...l,ref:g}),d.isSelected&&o.valueNode&&!o.valueNodeHasChildren&&!xee(o.value)?a1.createPortal(l.children,o.valueNode):null]})},"SelectItemText")),B0s="SelectItemIndicator",$0s=k.forwardRef(au(function(t,n){const{__scopeSelect:r,...a}=t;return I3t(B0s,r).isSelected?e.jsx(hi.span,{"aria-hidden":!0,...a,ref:n}):null},"SelectItemIndicator")),Rot="SelectScrollUpButton",R3t=k.forwardRef(au(function(t,n){const r=jF(Rot,t.__scopeSelect),a=JHe(Rot,t.__scopeSelect),[i,l]=k.useState(!1),o=Ao(n,a.onScrollButtonChange);return _m(()=>{if(r.viewport&&r.isPositioned){let c=function(){const u=d.scrollTop>0;l(u)};au(c,"handleScroll");const d=r.viewport;return c(),d.addEventListener("scroll",c),()=>d.removeEventListener("scroll",c)}},[r.viewport,r.isPositioned]),i?e.jsx(O3t,{...t,ref:o,onAutoScroll:()=>{const{viewport:c,selectedItem:d}=r;c&&d&&(c.scrollTop=c.scrollTop-d.offsetHeight)}}):null},"SelectScrollUpButton")),Dot="SelectScrollDownButton",D3t=k.forwardRef(au(function(t,n){const r=jF(Dot,t.__scopeSelect),a=JHe(Dot,t.__scopeSelect),[i,l]=k.useState(!1),o=Ao(n,a.onScrollButtonChange);return _m(()=>{if(r.viewport&&r.isPositioned){let c=function(){const u=d.scrollHeight-d.clientHeight,h=Math.ceil(d.scrollTop)d.removeEventListener("scroll",c)}},[r.viewport,r.isPositioned]),i?e.jsx(O3t,{...t,ref:o,onAutoScroll:()=>{const{viewport:c,selectedItem:d}=r;c&&d&&(c.scrollTop=c.scrollTop+d.offsetHeight)}}):null},"SelectScrollDownButton")),O3t=k.forwardRef(au(function(t,n){const{__scopeSelect:r,onAutoScroll:a,...i}=t,l=jF("SelectScrollButton",r),o=k.useRef(null),c=V3e(r),d=k.useCallback(()=>{o.current!==null&&(window.clearInterval(o.current),o.current=null)},[]);return k.useEffect(()=>()=>d(),[d]),_m(()=>{var h;const u=c().find(m=>m.ref.current===document.activeElement);(h=u==null?void 0:u.ref.current)==null||h.scrollIntoView({block:"nearest"})},[c]),e.jsx(hi.div,{"aria-hidden":!0,...i,ref:n,style:{flexShrink:0,...i.style},onPointerDown:ga(i.onPointerDown,()=>{o.current===null&&(o.current=window.setInterval(a,50))}),onPointerMove:ga(i.onPointerMove,()=>{var u;(u=l.onItemLeave)==null||u.call(l),o.current===null&&(o.current=window.setInterval(a,50))}),onPointerLeave:ga(i.onPointerLeave,()=>{d()})})},"SelectScrollButtonImpl")),F3t=k.forwardRef(au(function(t,n){const{__scopeSelect:r,...a}=t;return e.jsx(hi.div,{"aria-hidden":!0,...a,ref:n})},"SelectSeparator")),U0s="SelectBubbleInput",q0s=k.forwardRef(au(function({__scopeSelect:t,...n},r){const a=QM(U0s,t),{value:i,onValueChange:l,required:o,disabled:c,name:d,autoComplete:u,form:h}=a,{nativeOptions:m,nativeSelectKey:p}=a,g=k.useRef(null),x=Ao(r,g),y=i??"",v=XHe(y),_=Array.from(m).some(j=>(j.props.value??"")==="");return k.useEffect(()=>{const j=g.current;if(!j)return;const C=window.HTMLSelectElement.prototype,M=Object.getOwnPropertyDescriptor(C,"value").set;if(v!==y&&M){const I=new Event("change",{bubbles:!0});M.call(j,y),j.dispatchEvent(I)}},[v,y]),e.jsxs(hi.select,{"aria-hidden":!0,required:o,tabIndex:-1,name:d,autoComplete:u,disabled:c,form:h,onChange:j=>l(j.target.value),...n,style:{...Kkt,...n.style},ref:x,defaultValue:y,children:[xee(i)&&!_?e.jsx("option",{value:""}):null,Array.from(m)]},p)},"SelectBubbleInput"));function z3t(s){return typeof s=="function"}au(z3t,"isFunction");function xee(s){return s===""||s===void 0}au(xee,"shouldShowPlaceholder");function eGe(s){const t=sp(s),n=k.useRef(""),r=k.useRef(0),a=k.useCallback(l=>{const o=n.current+l;t(o),au(function c(d){n.current=d,window.clearTimeout(r.current),d!==""&&(r.current=window.setTimeout(()=>c(""),1e3))},"updateSearch")(o)},[t]),i=k.useCallback(()=>{n.current="",window.clearTimeout(r.current)},[]);return k.useEffect(()=>()=>window.clearTimeout(r.current),[]),[n,a,i]}au(eGe,"useTypeaheadSearch");function tGe(s,t,n){const a=t.length>1&&Array.from(t).every(d=>d===t[0])?t[0]:t,i=n?s.indexOf(n):-1;let l=B3t(s,Math.max(i,0));a.length===1&&(l=l.filter(d=>d!==n));const c=l.find(d=>d.textValue.toLowerCase().startsWith(a.toLowerCase()));return c!==n?c:void 0}au(tGe,"findNextItem");function B3t(s,t){return s.map((n,r)=>s[(t+r)%s.length])}au(B3t,"wrapArray");const bs=b0s,_s=j0s,ys=k.forwardRef(({className:s,children:t,...n},r)=>e.jsxs(E3t,{ref:r,className:Ot("flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",s),...n,children:[t,e.jsx(N0s,{asChild:!0,children:e.jsx(Go,{className:"h-4 w-4 opacity-50"})})]}));ys.displayName=E3t.displayName;const $3t=k.forwardRef(({className:s,...t},n)=>e.jsx(R3t,{ref:n,className:Ot("flex cursor-default items-center justify-center py-1",s),...t,children:e.jsx(Ny,{className:"h-4 w-4"})}));$3t.displayName=R3t.displayName;const U3t=k.forwardRef(({className:s,...t},n)=>e.jsx(D3t,{ref:n,className:Ot("flex cursor-default items-center justify-center py-1",s),...t,children:e.jsx(Go,{className:"h-4 w-4"})}));U3t.displayName=D3t.displayName;const vs=k.forwardRef(({className:s,children:t,position:n="popper",...r},a)=>e.jsx(A0s,{children:e.jsxs(T3t,{ref:a,className:Ot("relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",n==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",s),position:n,...r,children:[e.jsx($3t,{}),e.jsx(L0s,{className:Ot("p-1",n==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:t}),e.jsx(U3t,{})]})}));vs.displayName=T3t.displayName;const V0s=k.forwardRef(({className:s,...t},n)=>e.jsx(P3t,{ref:n,className:Ot("py-1.5 pl-8 pr-2 text-sm font-semibold",s),...t}));V0s.displayName=P3t.displayName;const We=k.forwardRef(({className:s,children:t,...n},r)=>e.jsxs(L3t,{ref:r,className:Ot("relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 focus:bg-accent focus:text-accent-foreground",s),...n,children:[e.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e.jsx($0s,{children:e.jsx(ma,{className:"h-4 w-4"})})}),e.jsx(z0s,{children:t})]}));We.displayName=L3t.displayName;const H0s=k.forwardRef(({className:s,...t},n)=>e.jsx(F3t,{ref:n,className:Ot("-mx-1 my-1 h-px bg-muted",s),...t}));H0s.displayName=F3t.displayName;const G0s=t4({category:ZHe(["general","technology","crm","marketing"]),subject:uc().min(5,"Subject must be at least 5 characters").max(200),description:uc().min(20,"Please provide more details (at least 20 characters)").max(2e3)}),W0s={general:"General Support",technology:"Technology Support",crm:"CRM Support",marketing:"Marketing Support"};function m7e({trigger:s}){const[t,n]=k.useState(!1),[r,a]=k.useState(!1),{user:i}=ks(),l=D3e({resolver:O3e(G0s),defaultValues:{category:"general",subject:"",description:""}}),o=async c=>{if(!i){ae.error("You must be logged in to submit a ticket");return}a(!0);try{const{error:d}=await V.from("support_tickets").insert({user_id:i.id,category:c.category,subject:c.subject,description:c.description});if(d)throw d;try{await V.functions.invoke("support-ticket-notify",{body:{category:W0s[c.category],subject:c.subject}})}catch(u){console.log("Notification send attempted:",u)}ae.success("Support ticket submitted successfully!"),l.reset(),n(!1)}catch(d){console.error("Error submitting ticket:",d),ae.error("Failed to submit ticket. Please try again.")}finally{a(!1)}};return e.jsxs(zs,{open:t,onOpenChange:n,children:[e.jsx(yl,{asChild:!0,children:s||e.jsxs($,{variant:"ghost",size:"icon",className:"relative",children:[e.jsx(eB,{className:"h-5 w-5"}),e.jsx("span",{className:"sr-only",children:"Support"})]})}),e.jsxs(Rs,{className:"sm:max-w-[500px]",children:[e.jsxs(Vs,{children:[e.jsx($s,{children:"Need Help?"}),e.jsx(Cr,{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(ka,{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($3e,{...l,children:e.jsxs("form",{onSubmit:l.handleSubmit(o),className:"space-y-4",children:[e.jsx(Sp,{control:l.control,name:"category",render:({field:c})=>e.jsxs(Zf,{children:[e.jsx(Xf,{children:"Category"}),e.jsxs(bs,{onValueChange:c.onChange,defaultValue:c.value,children:[e.jsx(Qf,{children:e.jsx(ys,{children:e.jsx(_s,{placeholder:"Select a category"})})}),e.jsxs(vs,{children:[e.jsx(We,{value:"general",children:"General Support"}),e.jsx(We,{value:"technology",children:"Technology Support"}),e.jsx(We,{value:"crm",children:"CRM Support"}),e.jsx(We,{value:"marketing",children:"Marketing Support"})]})]}),e.jsx(ib,{})]})}),e.jsx(Sp,{control:l.control,name:"subject",render:({field:c})=>e.jsxs(Zf,{children:[e.jsx(Xf,{children:"Subject"}),e.jsx(Qf,{children:e.jsx(be,{placeholder:"Brief description of your issue",...c})}),e.jsx(ib,{})]})}),e.jsx(Sp,{control:l.control,name:"description",render:({field:c})=>e.jsxs(Zf,{children:[e.jsx(Xf,{children:"Description"}),e.jsx(Qf,{children:e.jsx(Ls,{placeholder:"Please describe your issue in detail...",className:"min-h-[120px]",...c})}),e.jsx(ib,{})]})}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx($,{type:"button",variant:"outline",onClick:()=>n(!1),children:"Cancel"}),e.jsx($,{type:"submit",disabled:r,children:r?"Submitting...":"Submit Ticket"})]})]})})]})]})}function mo(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 Lh(s,t){return s instanceof Date?new s.constructor(t):new Date(t)}function wu(s,t){const n=mo(s);return isNaN(t)?Lh(s,NaN):(t&&n.setDate(n.getDate()+t),n)}function Ux(s,t){const n=mo(s);if(isNaN(t))return Lh(s,NaN);if(!t)return n;const r=n.getDate(),a=Lh(s,n.getTime());a.setMonth(n.getMonth()+t+1,0);const i=a.getDate();return r>=i?a:(n.setFullYear(a.getFullYear(),a.getMonth(),r),n)}function q3t(s,t){const n=+mo(s);return Lh(s,n+t)}const sGe=6048e5,K0s=864e5,H3e=6e4,G3e=36e5,Y0s=1e3,Jne=43200,Oot=1440;function Fot(s,t){return q3t(s,t*G3e)}let Z0s={};function JM(){return Z0s}function My(s,t){var o,c,d,u;const n=JM(),r=(t==null?void 0:t.weekStartsOn)??((c=(o=t==null?void 0:t.locale)==null?void 0:o.options)==null?void 0:c.weekStartsOn)??n.weekStartsOn??((u=(d=n.locale)==null?void 0:d.options)==null?void 0:u.weekStartsOn)??0,a=mo(s),i=a.getDay(),l=(i=a.getTime()?n+1:t.getTime()>=l.getTime()?n:n-1}function np(s){const t=mo(s);return t.setHours(0,0,0,0),t}function NM(s){const t=mo(s),n=new Date(Date.UTC(t.getFullYear(),t.getMonth(),t.getDate(),t.getHours(),t.getMinutes(),t.getSeconds(),t.getMilliseconds()));return n.setUTCFullYear(t.getFullYear()),+s-+n}function o1(s,t){const n=np(s),r=np(t),a=+n-NM(n),i=+r-NM(r);return Math.round((a-i)/K0s)}function X0s(s){const t=V3t(s),n=Lh(s,0);return n.setFullYear(t,0,4),n.setHours(0,0,0,0),U3(n)}function zot(s,t){return q3t(s,t*H3e)}function a3(s,t){const n=t*7;return wu(s,n)}function Q0s(s,t){return Ux(s,t*12)}function J0s(s){let t;return s.forEach(function(n){const r=mo(n);(t===void 0||t{const r=mo(n);(!t||t>r||isNaN(+r))&&(t=r)}),t||new Date(NaN)}function tNe(s,t){const n=mo(s),r=mo(t),a=n.getTime()-r.getTime();return a<0?-1:a>0?1:a}function W3e(s){return Lh(s,Date.now())}function ah(s,t){const n=np(s),r=np(t);return+n==+r}function nGe(s){return s instanceof Date||typeof s=="object"&&Object.prototype.toString.call(s)==="[object Date]"}function f7e(s){if(!nGe(s)&&typeof s!="number")return!1;const t=mo(s);return!isNaN(Number(t))}function _U(s,t){const n=mo(s),r=mo(t),a=n.getFullYear()-r.getFullYear(),i=n.getMonth()-r.getMonth();return a*12+i}function tvs(s,t,n){const r=My(s,n),a=My(t,n),i=+r-NM(r),l=+a-NM(a);return Math.round((i-l)/sGe)}function I2(s,t){const n=mo(s),r=mo(t),a=Bot(n,r),i=Math.abs(o1(n,r));n.setDate(n.getDate()-a*i);const l=+(Bot(n,r)===-a),o=a*(i-l);return o===0?0:o}function Bot(s,t){const n=s.getFullYear()-t.getFullYear()||s.getMonth()-t.getMonth()||s.getDate()-t.getDate()||s.getHours()-t.getHours()||s.getMinutes()-t.getMinutes()||s.getSeconds()-t.getSeconds()||s.getMilliseconds()-t.getMilliseconds();return n<0?-1:n>0?1:n}function svs(s){return t=>{const r=(s?Math[s]:Math.trunc)(t);return r===0?0:r}}function nvs(s,t){return+mo(s)-+mo(t)}function rvs(s){const t=mo(s);return t.setHours(23,59,59,999),t}function eb(s){const t=mo(s),n=t.getMonth();return t.setFullYear(t.getFullYear(),n+1,0),t.setHours(23,59,59,999),t}function avs(s){const t=mo(s);return+rvs(t)==+eb(t)}function ivs(s,t){const n=mo(s),r=mo(t),a=tNe(n,r),i=Math.abs(_U(n,r));let l;if(i<1)l=0;else{n.getMonth()===1&&n.getDate()>27&&n.setDate(30),n.setMonth(n.getMonth()-a*i);let o=tNe(n,r)===-a;avs(mo(s))&&i===1&&tNe(s,r)===1&&(o=!1),l=a*(i-Number(o))}return l===0?0:l}function ovs(s,t,n){const r=nvs(s,t)/1e3;return svs(n==null?void 0:n.roundingMethod)(r)}function p7e(s,t){const n=mo(s.start),r=mo(s.end);let a=+n>+r;const i=a?+n:+r,l=a?r:n;l.setHours(0,0,0,0);let o=1;const c=[];for(;+l<=i;)c.push(mo(l)),l.setDate(l.getDate()+o),l.setHours(0,0,0,0);return a?c.reverse():c}function Ih(s){const t=mo(s);return t.setDate(1),t.setHours(0,0,0,0),t}function H3t(s){const t=mo(s),n=Lh(s,0);return n.setFullYear(t.getFullYear(),0,1),n.setHours(0,0,0,0),n}function wU(s,t){var o,c,d,u;const n=JM(),r=(t==null?void 0:t.weekStartsOn)??((c=(o=t==null?void 0:t.locale)==null?void 0:o.options)==null?void 0:c.weekStartsOn)??n.weekStartsOn??((u=(d=n.locale)==null?void 0:d.options)==null?void 0:u.weekStartsOn)??0,a=mo(s),i=a.getDay(),l=(i{let r;const a=lvs[s];return typeof a=="string"?r=a:t===1?r=a.one:r=a.other.replace("{{count}}",t.toString()),n!=null&&n.addSuffix?n.comparison&&n.comparison>0?"in "+r:r+" ago":r};function vIe(s){return(t={})=>{const n=t.width?String(t.width):s.defaultWidth;return s.formats[n]||s.formats[s.defaultWidth]}}const dvs={full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},uvs={full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},hvs={full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},mvs={date:vIe({formats:dvs,defaultWidth:"full"}),time:vIe({formats:uvs,defaultWidth:"full"}),dateTime:vIe({formats:hvs,defaultWidth:"full"})},fvs={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"},pvs=(s,t,n,r)=>fvs[s];function rG(s){return(t,n)=>{const r=n!=null&&n.context?String(n.context):"standalone";let a;if(r==="formatting"&&s.formattingValues){const l=s.defaultFormattingWidth||s.defaultWidth,o=n!=null&&n.width?String(n.width):l;a=s.formattingValues[o]||s.formattingValues[l]}else{const l=s.defaultWidth,o=n!=null&&n.width?String(n.width):s.defaultWidth;a=s.values[o]||s.values[l]}const i=s.argumentCallback?s.argumentCallback(t):t;return a[i]}}const gvs={narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},xvs={narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},yvs={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"]},vvs={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"]},bvs={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"}},_vs={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"}},wvs=(s,t)=>{const n=Number(s),r=n%100;if(r>20||r<10)switch(r%10){case 1:return n+"st";case 2:return n+"nd";case 3:return n+"rd"}return n+"th"},jvs={ordinalNumber:wvs,era:rG({values:gvs,defaultWidth:"wide"}),quarter:rG({values:xvs,defaultWidth:"wide",argumentCallback:s=>s-1}),month:rG({values:yvs,defaultWidth:"wide"}),day:rG({values:vvs,defaultWidth:"wide"}),dayPeriod:rG({values:bvs,defaultWidth:"wide",formattingValues:_vs,defaultFormattingWidth:"wide"})};function aG(s){return(t,n={})=>{const r=n.width,a=r&&s.matchPatterns[r]||s.matchPatterns[s.defaultMatchWidth],i=t.match(a);if(!i)return null;const l=i[0],o=r&&s.parsePatterns[r]||s.parsePatterns[s.defaultParseWidth],c=Array.isArray(o)?kvs(o,h=>h.test(l)):Nvs(o,h=>h.test(l));let d;d=s.valueCallback?s.valueCallback(c):c,d=n.valueCallback?n.valueCallback(d):d;const u=t.slice(l.length);return{value:d,rest:u}}}function Nvs(s,t){for(const n in s)if(Object.prototype.hasOwnProperty.call(s,n)&&t(s[n]))return n}function kvs(s,t){for(let n=0;n{const r=t.match(s.matchPattern);if(!r)return null;const a=r[0],i=t.match(s.parsePattern);if(!i)return null;let l=s.valueCallback?s.valueCallback(i[0]):i[0];l=n.valueCallback?n.valueCallback(l):l;const o=t.slice(a.length);return{value:l,rest:o}}}const Cvs=/^(\d+)(th|st|nd|rd)?/i,Avs=/\d+/i,Evs={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},Tvs={any:[/^b/i,/^(a|c)/i]},Mvs={narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},Pvs={any:[/1/i,/2/i,/3/i,/4/i]},Ivs={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},Lvs={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]},Rvs={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},Dvs={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]},Ovs={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},Fvs={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}},zvs={ordinalNumber:Svs({matchPattern:Cvs,parsePattern:Avs,valueCallback:s=>parseInt(s,10)}),era:aG({matchPatterns:Evs,defaultMatchWidth:"wide",parsePatterns:Tvs,defaultParseWidth:"any"}),quarter:aG({matchPatterns:Mvs,defaultMatchWidth:"wide",parsePatterns:Pvs,defaultParseWidth:"any",valueCallback:s=>s+1}),month:aG({matchPatterns:Ivs,defaultMatchWidth:"wide",parsePatterns:Lvs,defaultParseWidth:"any"}),day:aG({matchPatterns:Rvs,defaultMatchWidth:"wide",parsePatterns:Dvs,defaultParseWidth:"any"}),dayPeriod:aG({matchPatterns:Ovs,defaultMatchWidth:"any",parsePatterns:Fvs,defaultParseWidth:"any"})},K3e={code:"en-US",formatDistance:cvs,formatLong:mvs,formatRelative:pvs,localize:jvs,match:zvs,options:{weekStartsOn:0,firstWeekContainsDate:1}};function Bvs(s){const t=mo(s);return o1(t,H3t(t))+1}function rGe(s){const t=mo(s),n=+U3(t)-+X0s(t);return Math.round(n/sGe)+1}function aGe(s,t){var u,h,m,p;const n=mo(s),r=n.getFullYear(),a=JM(),i=(t==null?void 0:t.firstWeekContainsDate)??((h=(u=t==null?void 0:t.locale)==null?void 0:u.options)==null?void 0:h.firstWeekContainsDate)??a.firstWeekContainsDate??((p=(m=a.locale)==null?void 0:m.options)==null?void 0:p.firstWeekContainsDate)??1,l=Lh(s,0);l.setFullYear(r+1,0,i),l.setHours(0,0,0,0);const o=My(l,t),c=Lh(s,0);c.setFullYear(r,0,i),c.setHours(0,0,0,0);const d=My(c,t);return n.getTime()>=o.getTime()?r+1:n.getTime()>=d.getTime()?r:r-1}function $vs(s,t){var o,c,d,u;const n=JM(),r=(t==null?void 0:t.firstWeekContainsDate)??((c=(o=t==null?void 0:t.locale)==null?void 0:o.options)==null?void 0:c.firstWeekContainsDate)??n.firstWeekContainsDate??((u=(d=n.locale)==null?void 0:d.options)==null?void 0:u.firstWeekContainsDate)??1,a=aGe(s,t),i=Lh(s,0);return i.setFullYear(a,0,r),i.setHours(0,0,0,0),My(i,t)}function iGe(s,t){const n=mo(s),r=+My(n,t)-+$vs(n,t);return Math.round(r/sGe)+1}function Mh(s,t){const n=s<0?"-":"",r=Math.abs(s).toString().padStart(t,"0");return n+r}const OA={y(s,t){const n=s.getFullYear(),r=n>0?n:1-n;return Mh(t==="yy"?r%100:r,t.length)},M(s,t){const n=s.getMonth();return t==="M"?String(n+1):Mh(n+1,2)},d(s,t){return Mh(s.getDate(),t.length)},a(s,t){const n=s.getHours()/12>=1?"pm":"am";switch(t){case"a":case"aa":return n.toUpperCase();case"aaa":return n;case"aaaaa":return n[0];case"aaaa":default:return n==="am"?"a.m.":"p.m."}},h(s,t){return Mh(s.getHours()%12||12,t.length)},H(s,t){return Mh(s.getHours(),t.length)},m(s,t){return Mh(s.getMinutes(),t.length)},s(s,t){return Mh(s.getSeconds(),t.length)},S(s,t){const n=t.length,r=s.getMilliseconds(),a=Math.trunc(r*Math.pow(10,n-3));return Mh(a,t.length)}},q7={midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},$ot={G:function(s,t,n){const r=s.getFullYear()>0?1:0;switch(t){case"G":case"GG":case"GGG":return n.era(r,{width:"abbreviated"});case"GGGGG":return n.era(r,{width:"narrow"});case"GGGG":default:return n.era(r,{width:"wide"})}},y:function(s,t,n){if(t==="yo"){const r=s.getFullYear(),a=r>0?r:1-r;return n.ordinalNumber(a,{unit:"year"})}return OA.y(s,t)},Y:function(s,t,n,r){const a=aGe(s,r),i=a>0?a:1-a;if(t==="YY"){const l=i%100;return Mh(l,2)}return t==="Yo"?n.ordinalNumber(i,{unit:"year"}):Mh(i,t.length)},R:function(s,t){const n=V3t(s);return Mh(n,t.length)},u:function(s,t){const n=s.getFullYear();return Mh(n,t.length)},Q:function(s,t,n){const r=Math.ceil((s.getMonth()+1)/3);switch(t){case"Q":return String(r);case"QQ":return Mh(r,2);case"Qo":return n.ordinalNumber(r,{unit:"quarter"});case"QQQ":return n.quarter(r,{width:"abbreviated",context:"formatting"});case"QQQQQ":return n.quarter(r,{width:"narrow",context:"formatting"});case"QQQQ":default:return n.quarter(r,{width:"wide",context:"formatting"})}},q:function(s,t,n){const r=Math.ceil((s.getMonth()+1)/3);switch(t){case"q":return String(r);case"qq":return Mh(r,2);case"qo":return n.ordinalNumber(r,{unit:"quarter"});case"qqq":return n.quarter(r,{width:"abbreviated",context:"standalone"});case"qqqqq":return n.quarter(r,{width:"narrow",context:"standalone"});case"qqqq":default:return n.quarter(r,{width:"wide",context:"standalone"})}},M:function(s,t,n){const r=s.getMonth();switch(t){case"M":case"MM":return OA.M(s,t);case"Mo":return n.ordinalNumber(r+1,{unit:"month"});case"MMM":return n.month(r,{width:"abbreviated",context:"formatting"});case"MMMMM":return n.month(r,{width:"narrow",context:"formatting"});case"MMMM":default:return n.month(r,{width:"wide",context:"formatting"})}},L:function(s,t,n){const r=s.getMonth();switch(t){case"L":return String(r+1);case"LL":return Mh(r+1,2);case"Lo":return n.ordinalNumber(r+1,{unit:"month"});case"LLL":return n.month(r,{width:"abbreviated",context:"standalone"});case"LLLLL":return n.month(r,{width:"narrow",context:"standalone"});case"LLLL":default:return n.month(r,{width:"wide",context:"standalone"})}},w:function(s,t,n,r){const a=iGe(s,r);return t==="wo"?n.ordinalNumber(a,{unit:"week"}):Mh(a,t.length)},I:function(s,t,n){const r=rGe(s);return t==="Io"?n.ordinalNumber(r,{unit:"week"}):Mh(r,t.length)},d:function(s,t,n){return t==="do"?n.ordinalNumber(s.getDate(),{unit:"date"}):OA.d(s,t)},D:function(s,t,n){const r=Bvs(s);return t==="Do"?n.ordinalNumber(r,{unit:"dayOfYear"}):Mh(r,t.length)},E:function(s,t,n){const r=s.getDay();switch(t){case"E":case"EE":case"EEE":return n.day(r,{width:"abbreviated",context:"formatting"});case"EEEEE":return n.day(r,{width:"narrow",context:"formatting"});case"EEEEEE":return n.day(r,{width:"short",context:"formatting"});case"EEEE":default:return n.day(r,{width:"wide",context:"formatting"})}},e:function(s,t,n,r){const a=s.getDay(),i=(a-r.weekStartsOn+8)%7||7;switch(t){case"e":return String(i);case"ee":return Mh(i,2);case"eo":return n.ordinalNumber(i,{unit:"day"});case"eee":return n.day(a,{width:"abbreviated",context:"formatting"});case"eeeee":return n.day(a,{width:"narrow",context:"formatting"});case"eeeeee":return n.day(a,{width:"short",context:"formatting"});case"eeee":default:return n.day(a,{width:"wide",context:"formatting"})}},c:function(s,t,n,r){const a=s.getDay(),i=(a-r.weekStartsOn+8)%7||7;switch(t){case"c":return String(i);case"cc":return Mh(i,t.length);case"co":return n.ordinalNumber(i,{unit:"day"});case"ccc":return n.day(a,{width:"abbreviated",context:"standalone"});case"ccccc":return n.day(a,{width:"narrow",context:"standalone"});case"cccccc":return n.day(a,{width:"short",context:"standalone"});case"cccc":default:return n.day(a,{width:"wide",context:"standalone"})}},i:function(s,t,n){const r=s.getDay(),a=r===0?7:r;switch(t){case"i":return String(a);case"ii":return Mh(a,t.length);case"io":return n.ordinalNumber(a,{unit:"day"});case"iii":return n.day(r,{width:"abbreviated",context:"formatting"});case"iiiii":return n.day(r,{width:"narrow",context:"formatting"});case"iiiiii":return n.day(r,{width:"short",context:"formatting"});case"iiii":default:return n.day(r,{width:"wide",context:"formatting"})}},a:function(s,t,n){const a=s.getHours()/12>=1?"pm":"am";switch(t){case"a":case"aa":return n.dayPeriod(a,{width:"abbreviated",context:"formatting"});case"aaa":return n.dayPeriod(a,{width:"abbreviated",context:"formatting"}).toLowerCase();case"aaaaa":return n.dayPeriod(a,{width:"narrow",context:"formatting"});case"aaaa":default:return n.dayPeriod(a,{width:"wide",context:"formatting"})}},b:function(s,t,n){const r=s.getHours();let a;switch(r===12?a=q7.noon:r===0?a=q7.midnight:a=r/12>=1?"pm":"am",t){case"b":case"bb":return n.dayPeriod(a,{width:"abbreviated",context:"formatting"});case"bbb":return n.dayPeriod(a,{width:"abbreviated",context:"formatting"}).toLowerCase();case"bbbbb":return n.dayPeriod(a,{width:"narrow",context:"formatting"});case"bbbb":default:return n.dayPeriod(a,{width:"wide",context:"formatting"})}},B:function(s,t,n){const r=s.getHours();let a;switch(r>=17?a=q7.evening:r>=12?a=q7.afternoon:r>=4?a=q7.morning:a=q7.night,t){case"B":case"BB":case"BBB":return n.dayPeriod(a,{width:"abbreviated",context:"formatting"});case"BBBBB":return n.dayPeriod(a,{width:"narrow",context:"formatting"});case"BBBB":default:return n.dayPeriod(a,{width:"wide",context:"formatting"})}},h:function(s,t,n){if(t==="ho"){let r=s.getHours()%12;return r===0&&(r=12),n.ordinalNumber(r,{unit:"hour"})}return OA.h(s,t)},H:function(s,t,n){return t==="Ho"?n.ordinalNumber(s.getHours(),{unit:"hour"}):OA.H(s,t)},K:function(s,t,n){const r=s.getHours()%12;return t==="Ko"?n.ordinalNumber(r,{unit:"hour"}):Mh(r,t.length)},k:function(s,t,n){let r=s.getHours();return r===0&&(r=24),t==="ko"?n.ordinalNumber(r,{unit:"hour"}):Mh(r,t.length)},m:function(s,t,n){return t==="mo"?n.ordinalNumber(s.getMinutes(),{unit:"minute"}):OA.m(s,t)},s:function(s,t,n){return t==="so"?n.ordinalNumber(s.getSeconds(),{unit:"second"}):OA.s(s,t)},S:function(s,t){return OA.S(s,t)},X:function(s,t,n){const r=s.getTimezoneOffset();if(r===0)return"Z";switch(t){case"X":return qot(r);case"XXXX":case"XX":return TR(r);case"XXXXX":case"XXX":default:return TR(r,":")}},x:function(s,t,n){const r=s.getTimezoneOffset();switch(t){case"x":return qot(r);case"xxxx":case"xx":return TR(r);case"xxxxx":case"xxx":default:return TR(r,":")}},O:function(s,t,n){const r=s.getTimezoneOffset();switch(t){case"O":case"OO":case"OOO":return"GMT"+Uot(r,":");case"OOOO":default:return"GMT"+TR(r,":")}},z:function(s,t,n){const r=s.getTimezoneOffset();switch(t){case"z":case"zz":case"zzz":return"GMT"+Uot(r,":");case"zzzz":default:return"GMT"+TR(r,":")}},t:function(s,t,n){const r=Math.trunc(s.getTime()/1e3);return Mh(r,t.length)},T:function(s,t,n){const r=s.getTime();return Mh(r,t.length)}};function Uot(s,t=""){const n=s>0?"-":"+",r=Math.abs(s),a=Math.trunc(r/60),i=r%60;return i===0?n+String(a):n+String(a)+t+Mh(i,2)}function qot(s,t){return s%60===0?(s>0?"-":"+")+Mh(Math.abs(s)/60,2):TR(s,t)}function TR(s,t=""){const n=s>0?"-":"+",r=Math.abs(s),a=Mh(Math.trunc(r/60),2),i=Mh(r%60,2);return n+a+t+i}const Vot=(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"})}},W3t=(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"})}},Uvs=(s,t)=>{const n=s.match(/(P+)(p+)?/)||[],r=n[1],a=n[2];if(!a)return Vot(s,t);let i;switch(r){case"P":i=t.dateTime({width:"short"});break;case"PP":i=t.dateTime({width:"medium"});break;case"PPP":i=t.dateTime({width:"long"});break;case"PPPP":default:i=t.dateTime({width:"full"});break}return i.replace("{{date}}",Vot(r,t)).replace("{{time}}",W3t(a,t))},g7e={p:W3t,P:Uvs},qvs=/^D+$/,Vvs=/^Y+$/,Hvs=["D","DD","YY","YYYY"];function K3t(s){return qvs.test(s)}function Y3t(s){return Vvs.test(s)}function x7e(s,t,n){const r=Gvs(s,t,n);if(console.warn(r),Hvs.includes(s))throw new RangeError(r)}function Gvs(s,t,n){const r=s[0]==="Y"?"years":"days of the month";return`Use \`${s.toLowerCase()}\` instead of \`${s}\` (in \`${t}\`) for formatting ${r} to the input \`${n}\`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md`}const Wvs=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,Kvs=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,Yvs=/^'([^]*?)'?$/,Zvs=/''/g,Xvs=/[a-zA-Z]/;function Ys(s,t,n){var u,h,m,p,g,x,y,v;const r=JM(),a=(n==null?void 0:n.locale)??r.locale??K3e,i=(n==null?void 0:n.firstWeekContainsDate)??((h=(u=n==null?void 0:n.locale)==null?void 0:u.options)==null?void 0:h.firstWeekContainsDate)??r.firstWeekContainsDate??((p=(m=r.locale)==null?void 0:m.options)==null?void 0:p.firstWeekContainsDate)??1,l=(n==null?void 0:n.weekStartsOn)??((x=(g=n==null?void 0:n.locale)==null?void 0:g.options)==null?void 0:x.weekStartsOn)??r.weekStartsOn??((v=(y=r.locale)==null?void 0:y.options)==null?void 0:v.weekStartsOn)??0,o=mo(s);if(!f7e(o))throw new RangeError("Invalid time value");let c=t.match(Kvs).map(_=>{const j=_[0];if(j==="p"||j==="P"){const C=g7e[j];return C(_,a.formatLong)}return _}).join("").match(Wvs).map(_=>{if(_==="''")return{isToken:!1,value:"'"};const j=_[0];if(j==="'")return{isToken:!1,value:Qvs(_)};if($ot[j])return{isToken:!0,value:_};if(j.match(Xvs))throw new RangeError("Format string contains an unescaped latin alphabet character `"+j+"`");return{isToken:!1,value:_}});a.localize.preprocessor&&(c=a.localize.preprocessor(o,c));const d={firstWeekContainsDate:i,weekStartsOn:l,locale:a};return c.map(_=>{if(!_.isToken)return _.value;const j=_.value;(!(n!=null&&n.useAdditionalWeekYearTokens)&&Y3t(j)||!(n!=null&&n.useAdditionalDayOfYearTokens)&&K3t(j))&&x7e(j,t,String(s));const C=$ot[j[0]];return C(o,j,a.localize,d)}).join("")}function Qvs(s){const t=s.match(Yvs);return t?t[1].replace(Zvs,"'"):s}function Jvs(s,t,n){const r=JM(),a=(n==null?void 0:n.locale)??r.locale??K3e,i=2520,l=tNe(s,t);if(isNaN(l))throw new RangeError("Invalid time value");const o=Object.assign({},n,{addSuffix:n==null?void 0:n.addSuffix,comparison:l});let c,d;l>0?(c=mo(t),d=mo(s)):(c=mo(s),d=mo(t));const u=ovs(d,c),h=(NM(d)-NM(c))/1e3,m=Math.round((u-h)/60);let p;if(m<2)return n!=null&&n.includeSeconds?u<5?a.formatDistance("lessThanXSeconds",5,o):u<10?a.formatDistance("lessThanXSeconds",10,o):u<20?a.formatDistance("lessThanXSeconds",20,o):u<40?a.formatDistance("halfAMinute",0,o):u<60?a.formatDistance("lessThanXMinutes",1,o):a.formatDistance("xMinutes",1,o):m===0?a.formatDistance("lessThanXMinutes",1,o):a.formatDistance("xMinutes",m,o);if(m<45)return a.formatDistance("xMinutes",m,o);if(m<90)return a.formatDistance("aboutXHours",1,o);if(mr.getTime()}function Xw(s,t){const n=mo(s),r=mo(t);return+n<+r}function i1s(s){return+mo(s)>Date.now()}function o1s(s,t){const n=t instanceof Date?Lh(t,0):new t(0);return n.setFullYear(s.getFullYear(),s.getMonth(),s.getDate()),n.setHours(s.getHours(),s.getMinutes(),s.getSeconds(),s.getMilliseconds()),n}const l1s=10;class Z3t{constructor(){ur(this,"subPriority",0)}validate(t,n){return!0}}class c1s extends Z3t{constructor(t,n,r,a,i){super(),this.value=t,this.validateValue=n,this.setValue=r,this.priority=a,i&&(this.subPriority=i)}validate(t,n){return this.validateValue(t,this.value,n)}set(t,n,r){return this.setValue(t,n,this.value,r)}}class d1s extends Z3t{constructor(){super(...arguments);ur(this,"priority",l1s);ur(this,"subPriority",-1)}set(n,r){return r.timestampIsSet?n:Lh(n,o1s(n,Date))}}class ch{run(t,n,r,a){const i=this.parse(t,n,r,a);return i?{setter:new c1s(i.value,this.validate,this.set,this.priority,this.subPriority),rest:i.rest}:null}validate(t,n,r){return!0}}class u1s extends ch{constructor(){super(...arguments);ur(this,"priority",140);ur(this,"incompatibleTokens",["R","u","t","T"])}parse(n,r,a){switch(r){case"G":case"GG":case"GGG":return a.era(n,{width:"abbreviated"})||a.era(n,{width:"narrow"});case"GGGGG":return a.era(n,{width:"narrow"});case"GGGG":default:return a.era(n,{width:"wide"})||a.era(n,{width:"abbreviated"})||a.era(n,{width:"narrow"})}}set(n,r,a){return r.era=a,n.setFullYear(a,0,1),n.setHours(0,0,0,0),n}}const ex={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}/},c5={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 tx(s,t){return s&&{value:t(s.value),rest:s.rest}}function Ip(s,t){const n=t.match(s);return n?{value:parseInt(n[0],10),rest:t.slice(n[0].length)}:null}function d5(s,t){const n=t.match(s);if(!n)return null;if(n[0]==="Z")return{value:0,rest:t.slice(1)};const r=n[1]==="+"?1:-1,a=n[2]?parseInt(n[2],10):0,i=n[3]?parseInt(n[3],10):0,l=n[5]?parseInt(n[5],10):0;return{value:r*(a*G3e+i*H3e+l*Y0s),rest:t.slice(n[0].length)}}function X3t(s){return Ip(ex.anyDigitsSigned,s)}function Sg(s,t){switch(s){case 1:return Ip(ex.singleDigit,t);case 2:return Ip(ex.twoDigits,t);case 3:return Ip(ex.threeDigits,t);case 4:return Ip(ex.fourDigits,t);default:return Ip(new RegExp("^\\d{1,"+s+"}"),t)}}function uSe(s,t){switch(s){case 1:return Ip(ex.singleDigitSigned,t);case 2:return Ip(ex.twoDigitsSigned,t);case 3:return Ip(ex.threeDigitsSigned,t);case 4:return Ip(ex.fourDigitsSigned,t);default:return Ip(new RegExp("^-?\\d{1,"+s+"}"),t)}}function oGe(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 Q3t(s,t){const n=t>0,r=n?t:1-t;let a;if(r<=50)a=s||100;else{const i=r+50,l=Math.trunc(i/100)*100,o=s>=i%100;a=s+l-(o?100:0)}return n?a:1-a}function J3t(s){return s%400===0||s%4===0&&s%100!==0}class h1s extends ch{constructor(){super(...arguments);ur(this,"priority",130);ur(this,"incompatibleTokens",["Y","R","u","w","I","i","e","c","t","T"])}parse(n,r,a){const i=l=>({year:l,isTwoDigitYear:r==="yy"});switch(r){case"y":return tx(Sg(4,n),i);case"yo":return tx(a.ordinalNumber(n,{unit:"year"}),i);default:return tx(Sg(r.length,n),i)}}validate(n,r){return r.isTwoDigitYear||r.year>0}set(n,r,a){const i=n.getFullYear();if(a.isTwoDigitYear){const o=Q3t(a.year,i);return n.setFullYear(o,0,1),n.setHours(0,0,0,0),n}const l=!("era"in r)||r.era===1?a.year:1-a.year;return n.setFullYear(l,0,1),n.setHours(0,0,0,0),n}}class m1s extends ch{constructor(){super(...arguments);ur(this,"priority",130);ur(this,"incompatibleTokens",["y","R","u","Q","q","M","L","I","d","D","i","t","T"])}parse(n,r,a){const i=l=>({year:l,isTwoDigitYear:r==="YY"});switch(r){case"Y":return tx(Sg(4,n),i);case"Yo":return tx(a.ordinalNumber(n,{unit:"year"}),i);default:return tx(Sg(r.length,n),i)}}validate(n,r){return r.isTwoDigitYear||r.year>0}set(n,r,a,i){const l=aGe(n,i);if(a.isTwoDigitYear){const c=Q3t(a.year,l);return n.setFullYear(c,0,i.firstWeekContainsDate),n.setHours(0,0,0,0),My(n,i)}const o=!("era"in r)||r.era===1?a.year:1-a.year;return n.setFullYear(o,0,i.firstWeekContainsDate),n.setHours(0,0,0,0),My(n,i)}}class f1s extends ch{constructor(){super(...arguments);ur(this,"priority",130);ur(this,"incompatibleTokens",["G","y","Y","u","Q","q","M","L","w","d","D","e","c","t","T"])}parse(n,r){return uSe(r==="R"?4:r.length,n)}set(n,r,a){const i=Lh(n,0);return i.setFullYear(a,0,4),i.setHours(0,0,0,0),U3(i)}}class p1s extends ch{constructor(){super(...arguments);ur(this,"priority",130);ur(this,"incompatibleTokens",["G","y","Y","R","w","I","i","e","c","t","T"])}parse(n,r){return uSe(r==="u"?4:r.length,n)}set(n,r,a){return n.setFullYear(a,0,1),n.setHours(0,0,0,0),n}}class g1s extends ch{constructor(){super(...arguments);ur(this,"priority",120);ur(this,"incompatibleTokens",["Y","R","q","M","L","w","I","d","D","i","e","c","t","T"])}parse(n,r,a){switch(r){case"Q":case"QQ":return Sg(r.length,n);case"Qo":return a.ordinalNumber(n,{unit:"quarter"});case"QQQ":return a.quarter(n,{width:"abbreviated",context:"formatting"})||a.quarter(n,{width:"narrow",context:"formatting"});case"QQQQQ":return a.quarter(n,{width:"narrow",context:"formatting"});case"QQQQ":default:return a.quarter(n,{width:"wide",context:"formatting"})||a.quarter(n,{width:"abbreviated",context:"formatting"})||a.quarter(n,{width:"narrow",context:"formatting"})}}validate(n,r){return r>=1&&r<=4}set(n,r,a){return n.setMonth((a-1)*3,1),n.setHours(0,0,0,0),n}}class x1s extends ch{constructor(){super(...arguments);ur(this,"priority",120);ur(this,"incompatibleTokens",["Y","R","Q","M","L","w","I","d","D","i","e","c","t","T"])}parse(n,r,a){switch(r){case"q":case"qq":return Sg(r.length,n);case"qo":return a.ordinalNumber(n,{unit:"quarter"});case"qqq":return a.quarter(n,{width:"abbreviated",context:"standalone"})||a.quarter(n,{width:"narrow",context:"standalone"});case"qqqqq":return a.quarter(n,{width:"narrow",context:"standalone"});case"qqqq":default:return a.quarter(n,{width:"wide",context:"standalone"})||a.quarter(n,{width:"abbreviated",context:"standalone"})||a.quarter(n,{width:"narrow",context:"standalone"})}}validate(n,r){return r>=1&&r<=4}set(n,r,a){return n.setMonth((a-1)*3,1),n.setHours(0,0,0,0),n}}class y1s extends ch{constructor(){super(...arguments);ur(this,"incompatibleTokens",["Y","R","q","Q","L","w","I","D","i","e","c","t","T"]);ur(this,"priority",110)}parse(n,r,a){const i=l=>l-1;switch(r){case"M":return tx(Ip(ex.month,n),i);case"MM":return tx(Sg(2,n),i);case"Mo":return tx(a.ordinalNumber(n,{unit:"month"}),i);case"MMM":return a.month(n,{width:"abbreviated",context:"formatting"})||a.month(n,{width:"narrow",context:"formatting"});case"MMMMM":return a.month(n,{width:"narrow",context:"formatting"});case"MMMM":default:return a.month(n,{width:"wide",context:"formatting"})||a.month(n,{width:"abbreviated",context:"formatting"})||a.month(n,{width:"narrow",context:"formatting"})}}validate(n,r){return r>=0&&r<=11}set(n,r,a){return n.setMonth(a,1),n.setHours(0,0,0,0),n}}class v1s extends ch{constructor(){super(...arguments);ur(this,"priority",110);ur(this,"incompatibleTokens",["Y","R","q","Q","M","w","I","D","i","e","c","t","T"])}parse(n,r,a){const i=l=>l-1;switch(r){case"L":return tx(Ip(ex.month,n),i);case"LL":return tx(Sg(2,n),i);case"Lo":return tx(a.ordinalNumber(n,{unit:"month"}),i);case"LLL":return a.month(n,{width:"abbreviated",context:"standalone"})||a.month(n,{width:"narrow",context:"standalone"});case"LLLLL":return a.month(n,{width:"narrow",context:"standalone"});case"LLLL":default:return a.month(n,{width:"wide",context:"standalone"})||a.month(n,{width:"abbreviated",context:"standalone"})||a.month(n,{width:"narrow",context:"standalone"})}}validate(n,r){return r>=0&&r<=11}set(n,r,a){return n.setMonth(a,1),n.setHours(0,0,0,0),n}}function b1s(s,t,n){const r=mo(s),a=iGe(r,n)-t;return r.setDate(r.getDate()-a*7),r}class _1s extends ch{constructor(){super(...arguments);ur(this,"priority",100);ur(this,"incompatibleTokens",["y","R","u","q","Q","M","L","I","d","D","i","t","T"])}parse(n,r,a){switch(r){case"w":return Ip(ex.week,n);case"wo":return a.ordinalNumber(n,{unit:"week"});default:return Sg(r.length,n)}}validate(n,r){return r>=1&&r<=53}set(n,r,a,i){return My(b1s(n,a,i),i)}}function w1s(s,t){const n=mo(s),r=rGe(n)-t;return n.setDate(n.getDate()-r*7),n}class j1s extends ch{constructor(){super(...arguments);ur(this,"priority",100);ur(this,"incompatibleTokens",["y","Y","u","q","Q","M","L","w","d","D","e","c","t","T"])}parse(n,r,a){switch(r){case"I":return Ip(ex.week,n);case"Io":return a.ordinalNumber(n,{unit:"week"});default:return Sg(r.length,n)}}validate(n,r){return r>=1&&r<=53}set(n,r,a){return U3(w1s(n,a))}}const N1s=[31,28,31,30,31,30,31,31,30,31,30,31],k1s=[31,29,31,30,31,30,31,31,30,31,30,31];class S1s extends ch{constructor(){super(...arguments);ur(this,"priority",90);ur(this,"subPriority",1);ur(this,"incompatibleTokens",["Y","R","q","Q","w","I","D","i","e","c","t","T"])}parse(n,r,a){switch(r){case"d":return Ip(ex.date,n);case"do":return a.ordinalNumber(n,{unit:"date"});default:return Sg(r.length,n)}}validate(n,r){const a=n.getFullYear(),i=J3t(a),l=n.getMonth();return i?r>=1&&r<=k1s[l]:r>=1&&r<=N1s[l]}set(n,r,a){return n.setDate(a),n.setHours(0,0,0,0),n}}class C1s extends ch{constructor(){super(...arguments);ur(this,"priority",90);ur(this,"subpriority",1);ur(this,"incompatibleTokens",["Y","R","q","Q","M","L","w","I","d","E","i","e","c","t","T"])}parse(n,r,a){switch(r){case"D":case"DD":return Ip(ex.dayOfYear,n);case"Do":return a.ordinalNumber(n,{unit:"date"});default:return Sg(r.length,n)}}validate(n,r){const a=n.getFullYear();return J3t(a)?r>=1&&r<=366:r>=1&&r<=365}set(n,r,a){return n.setMonth(0,a),n.setHours(0,0,0,0),n}}function lGe(s,t,n){var h,m,p,g;const r=JM(),a=(n==null?void 0:n.weekStartsOn)??((m=(h=n==null?void 0:n.locale)==null?void 0:h.options)==null?void 0:m.weekStartsOn)??r.weekStartsOn??((g=(p=r.locale)==null?void 0:p.options)==null?void 0:g.weekStartsOn)??0,i=mo(s),l=i.getDay(),c=(t%7+7)%7,d=7-a,u=t<0||t>6?t-(l+d)%7:(c+d)%7-(l+d)%7;return wu(i,u)}class A1s extends ch{constructor(){super(...arguments);ur(this,"priority",90);ur(this,"incompatibleTokens",["D","i","e","c","t","T"])}parse(n,r,a){switch(r){case"E":case"EE":case"EEE":return a.day(n,{width:"abbreviated",context:"formatting"})||a.day(n,{width:"short",context:"formatting"})||a.day(n,{width:"narrow",context:"formatting"});case"EEEEE":return a.day(n,{width:"narrow",context:"formatting"});case"EEEEEE":return a.day(n,{width:"short",context:"formatting"})||a.day(n,{width:"narrow",context:"formatting"});case"EEEE":default:return a.day(n,{width:"wide",context:"formatting"})||a.day(n,{width:"abbreviated",context:"formatting"})||a.day(n,{width:"short",context:"formatting"})||a.day(n,{width:"narrow",context:"formatting"})}}validate(n,r){return r>=0&&r<=6}set(n,r,a,i){return n=lGe(n,a,i),n.setHours(0,0,0,0),n}}class E1s extends ch{constructor(){super(...arguments);ur(this,"priority",90);ur(this,"incompatibleTokens",["y","R","u","q","Q","M","L","I","d","D","E","i","c","t","T"])}parse(n,r,a,i){const l=o=>{const c=Math.floor((o-1)/7)*7;return(o+i.weekStartsOn+6)%7+c};switch(r){case"e":case"ee":return tx(Sg(r.length,n),l);case"eo":return tx(a.ordinalNumber(n,{unit:"day"}),l);case"eee":return a.day(n,{width:"abbreviated",context:"formatting"})||a.day(n,{width:"short",context:"formatting"})||a.day(n,{width:"narrow",context:"formatting"});case"eeeee":return a.day(n,{width:"narrow",context:"formatting"});case"eeeeee":return a.day(n,{width:"short",context:"formatting"})||a.day(n,{width:"narrow",context:"formatting"});case"eeee":default:return a.day(n,{width:"wide",context:"formatting"})||a.day(n,{width:"abbreviated",context:"formatting"})||a.day(n,{width:"short",context:"formatting"})||a.day(n,{width:"narrow",context:"formatting"})}}validate(n,r){return r>=0&&r<=6}set(n,r,a,i){return n=lGe(n,a,i),n.setHours(0,0,0,0),n}}class T1s extends ch{constructor(){super(...arguments);ur(this,"priority",90);ur(this,"incompatibleTokens",["y","R","u","q","Q","M","L","I","d","D","E","i","e","t","T"])}parse(n,r,a,i){const l=o=>{const c=Math.floor((o-1)/7)*7;return(o+i.weekStartsOn+6)%7+c};switch(r){case"c":case"cc":return tx(Sg(r.length,n),l);case"co":return tx(a.ordinalNumber(n,{unit:"day"}),l);case"ccc":return a.day(n,{width:"abbreviated",context:"standalone"})||a.day(n,{width:"short",context:"standalone"})||a.day(n,{width:"narrow",context:"standalone"});case"ccccc":return a.day(n,{width:"narrow",context:"standalone"});case"cccccc":return a.day(n,{width:"short",context:"standalone"})||a.day(n,{width:"narrow",context:"standalone"});case"cccc":default:return a.day(n,{width:"wide",context:"standalone"})||a.day(n,{width:"abbreviated",context:"standalone"})||a.day(n,{width:"short",context:"standalone"})||a.day(n,{width:"narrow",context:"standalone"})}}validate(n,r){return r>=0&&r<=6}set(n,r,a,i){return n=lGe(n,a,i),n.setHours(0,0,0,0),n}}function M1s(s,t){const n=mo(s),r=s1s(n),a=t-r;return wu(n,a)}class P1s extends ch{constructor(){super(...arguments);ur(this,"priority",90);ur(this,"incompatibleTokens",["y","Y","u","q","Q","M","L","w","d","D","E","e","c","t","T"])}parse(n,r,a){const i=l=>l===0?7:l;switch(r){case"i":case"ii":return Sg(r.length,n);case"io":return a.ordinalNumber(n,{unit:"day"});case"iii":return tx(a.day(n,{width:"abbreviated",context:"formatting"})||a.day(n,{width:"short",context:"formatting"})||a.day(n,{width:"narrow",context:"formatting"}),i);case"iiiii":return tx(a.day(n,{width:"narrow",context:"formatting"}),i);case"iiiiii":return tx(a.day(n,{width:"short",context:"formatting"})||a.day(n,{width:"narrow",context:"formatting"}),i);case"iiii":default:return tx(a.day(n,{width:"wide",context:"formatting"})||a.day(n,{width:"abbreviated",context:"formatting"})||a.day(n,{width:"short",context:"formatting"})||a.day(n,{width:"narrow",context:"formatting"}),i)}}validate(n,r){return r>=1&&r<=7}set(n,r,a){return n=M1s(n,a),n.setHours(0,0,0,0),n}}class I1s extends ch{constructor(){super(...arguments);ur(this,"priority",80);ur(this,"incompatibleTokens",["b","B","H","k","t","T"])}parse(n,r,a){switch(r){case"a":case"aa":case"aaa":return a.dayPeriod(n,{width:"abbreviated",context:"formatting"})||a.dayPeriod(n,{width:"narrow",context:"formatting"});case"aaaaa":return a.dayPeriod(n,{width:"narrow",context:"formatting"});case"aaaa":default:return a.dayPeriod(n,{width:"wide",context:"formatting"})||a.dayPeriod(n,{width:"abbreviated",context:"formatting"})||a.dayPeriod(n,{width:"narrow",context:"formatting"})}}set(n,r,a){return n.setHours(oGe(a),0,0,0),n}}class L1s extends ch{constructor(){super(...arguments);ur(this,"priority",80);ur(this,"incompatibleTokens",["a","B","H","k","t","T"])}parse(n,r,a){switch(r){case"b":case"bb":case"bbb":return a.dayPeriod(n,{width:"abbreviated",context:"formatting"})||a.dayPeriod(n,{width:"narrow",context:"formatting"});case"bbbbb":return a.dayPeriod(n,{width:"narrow",context:"formatting"});case"bbbb":default:return a.dayPeriod(n,{width:"wide",context:"formatting"})||a.dayPeriod(n,{width:"abbreviated",context:"formatting"})||a.dayPeriod(n,{width:"narrow",context:"formatting"})}}set(n,r,a){return n.setHours(oGe(a),0,0,0),n}}class R1s extends ch{constructor(){super(...arguments);ur(this,"priority",80);ur(this,"incompatibleTokens",["a","b","t","T"])}parse(n,r,a){switch(r){case"B":case"BB":case"BBB":return a.dayPeriod(n,{width:"abbreviated",context:"formatting"})||a.dayPeriod(n,{width:"narrow",context:"formatting"});case"BBBBB":return a.dayPeriod(n,{width:"narrow",context:"formatting"});case"BBBB":default:return a.dayPeriod(n,{width:"wide",context:"formatting"})||a.dayPeriod(n,{width:"abbreviated",context:"formatting"})||a.dayPeriod(n,{width:"narrow",context:"formatting"})}}set(n,r,a){return n.setHours(oGe(a),0,0,0),n}}class D1s extends ch{constructor(){super(...arguments);ur(this,"priority",70);ur(this,"incompatibleTokens",["H","K","k","t","T"])}parse(n,r,a){switch(r){case"h":return Ip(ex.hour12h,n);case"ho":return a.ordinalNumber(n,{unit:"hour"});default:return Sg(r.length,n)}}validate(n,r){return r>=1&&r<=12}set(n,r,a){const i=n.getHours()>=12;return i&&a<12?n.setHours(a+12,0,0,0):!i&&a===12?n.setHours(0,0,0,0):n.setHours(a,0,0,0),n}}class O1s extends ch{constructor(){super(...arguments);ur(this,"priority",70);ur(this,"incompatibleTokens",["a","b","h","K","k","t","T"])}parse(n,r,a){switch(r){case"H":return Ip(ex.hour23h,n);case"Ho":return a.ordinalNumber(n,{unit:"hour"});default:return Sg(r.length,n)}}validate(n,r){return r>=0&&r<=23}set(n,r,a){return n.setHours(a,0,0,0),n}}class F1s extends ch{constructor(){super(...arguments);ur(this,"priority",70);ur(this,"incompatibleTokens",["h","H","k","t","T"])}parse(n,r,a){switch(r){case"K":return Ip(ex.hour11h,n);case"Ko":return a.ordinalNumber(n,{unit:"hour"});default:return Sg(r.length,n)}}validate(n,r){return r>=0&&r<=11}set(n,r,a){return n.getHours()>=12&&a<12?n.setHours(a+12,0,0,0):n.setHours(a,0,0,0),n}}class z1s extends ch{constructor(){super(...arguments);ur(this,"priority",70);ur(this,"incompatibleTokens",["a","b","h","H","K","t","T"])}parse(n,r,a){switch(r){case"k":return Ip(ex.hour24h,n);case"ko":return a.ordinalNumber(n,{unit:"hour"});default:return Sg(r.length,n)}}validate(n,r){return r>=1&&r<=24}set(n,r,a){const i=a<=24?a%24:a;return n.setHours(i,0,0,0),n}}class B1s extends ch{constructor(){super(...arguments);ur(this,"priority",60);ur(this,"incompatibleTokens",["t","T"])}parse(n,r,a){switch(r){case"m":return Ip(ex.minute,n);case"mo":return a.ordinalNumber(n,{unit:"minute"});default:return Sg(r.length,n)}}validate(n,r){return r>=0&&r<=59}set(n,r,a){return n.setMinutes(a,0,0),n}}class $1s extends ch{constructor(){super(...arguments);ur(this,"priority",50);ur(this,"incompatibleTokens",["t","T"])}parse(n,r,a){switch(r){case"s":return Ip(ex.second,n);case"so":return a.ordinalNumber(n,{unit:"second"});default:return Sg(r.length,n)}}validate(n,r){return r>=0&&r<=59}set(n,r,a){return n.setSeconds(a,0),n}}class U1s extends ch{constructor(){super(...arguments);ur(this,"priority",30);ur(this,"incompatibleTokens",["t","T"])}parse(n,r){const a=i=>Math.trunc(i*Math.pow(10,-r.length+3));return tx(Sg(r.length,n),a)}set(n,r,a){return n.setMilliseconds(a),n}}class q1s extends ch{constructor(){super(...arguments);ur(this,"priority",10);ur(this,"incompatibleTokens",["t","T","x"])}parse(n,r){switch(r){case"X":return d5(c5.basicOptionalMinutes,n);case"XX":return d5(c5.basic,n);case"XXXX":return d5(c5.basicOptionalSeconds,n);case"XXXXX":return d5(c5.extendedOptionalSeconds,n);case"XXX":default:return d5(c5.extended,n)}}set(n,r,a){return r.timestampIsSet?n:Lh(n,n.getTime()-NM(n)-a)}}class V1s extends ch{constructor(){super(...arguments);ur(this,"priority",10);ur(this,"incompatibleTokens",["t","T","X"])}parse(n,r){switch(r){case"x":return d5(c5.basicOptionalMinutes,n);case"xx":return d5(c5.basic,n);case"xxxx":return d5(c5.basicOptionalSeconds,n);case"xxxxx":return d5(c5.extendedOptionalSeconds,n);case"xxx":default:return d5(c5.extended,n)}}set(n,r,a){return r.timestampIsSet?n:Lh(n,n.getTime()-NM(n)-a)}}class H1s extends ch{constructor(){super(...arguments);ur(this,"priority",40);ur(this,"incompatibleTokens","*")}parse(n){return X3t(n)}set(n,r,a){return[Lh(n,a*1e3),{timestampIsSet:!0}]}}class G1s extends ch{constructor(){super(...arguments);ur(this,"priority",20);ur(this,"incompatibleTokens","*")}parse(n){return X3t(n)}set(n,r,a){return[Lh(n,a),{timestampIsSet:!0}]}}const W1s={G:new u1s,y:new h1s,Y:new m1s,R:new f1s,u:new p1s,Q:new g1s,q:new x1s,M:new y1s,L:new v1s,w:new _1s,I:new j1s,d:new S1s,D:new C1s,E:new A1s,e:new E1s,c:new T1s,i:new P1s,a:new I1s,b:new L1s,B:new R1s,h:new D1s,H:new O1s,K:new F1s,k:new z1s,m:new B1s,s:new $1s,S:new U1s,X:new q1s,x:new V1s,t:new H1s,T:new G1s},K1s=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,Y1s=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,Z1s=/^'([^]*?)'?$/,X1s=/''/g,Q1s=/\S/,J1s=/[a-zA-Z]/;function cGe(s,t,n,r){var x,y,v,_;const a=t1s(),i=a.locale??K3e,l=a.firstWeekContainsDate??((y=(x=a.locale)==null?void 0:x.options)==null?void 0:y.firstWeekContainsDate)??1,o=a.weekStartsOn??((_=(v=a.locale)==null?void 0:v.options)==null?void 0:_.weekStartsOn)??0;if(t==="")return s===""?mo(n):Lh(n,NaN);const c={firstWeekContainsDate:l,weekStartsOn:o,locale:i},d=[new d1s],u=t.match(Y1s).map(j=>{const C=j[0];if(C in g7e){const A=g7e[C];return A(j,i.formatLong)}return j}).join("").match(K1s),h=[];for(let j of u){Y3t(j)&&x7e(j,t,s),K3t(j)&&x7e(j,t,s);const C=j[0],A=W1s[C];if(A){const{incompatibleTokens:M}=A;if(Array.isArray(M)){const P=h.find(R=>M.includes(R.token)||R.token===C);if(P)throw new RangeError(`The format string mustn't contain \`${P.fullToken}\` and \`${j}\` at the same time`)}else if(A.incompatibleTokens==="*"&&h.length>0)throw new RangeError(`The format string mustn't contain \`${j}\` and any other token at the same time`);h.push({token:C,fullToken:j});const I=A.run(s,j,i.match,c);if(!I)return Lh(n,NaN);d.push(I.setter),s=I.rest}else{if(C.match(J1s))throw new RangeError("Format string contains an unescaped latin alphabet character `"+C+"`");if(j==="''"?j="'":C==="'"&&(j=ebs(j)),s.indexOf(j)===0)s=s.slice(j.length);else return Lh(n,NaN)}}if(s.length>0&&Q1s.test(s))return Lh(n,NaN);const m=d.map(j=>j.priority).sort((j,C)=>C-j).filter((j,C,A)=>A.indexOf(j)===C).map(j=>d.filter(C=>C.priority===j).sort((C,A)=>A.subPriority-C.subPriority)).map(j=>j[0]);let p=mo(n);if(isNaN(p.getTime()))return Lh(n,NaN);const g={};for(const j of m){if(!j.validate(p,c))return Lh(n,NaN);const C=j.set(p,g,c);Array.isArray(C)?(p=C[0],Object.assign(g,C[1])):p=C}return Lh(n,p)}function ebs(s){return s.match(Z1s)[1].replace(X1s,"'")}function R5(s){return+mo(s)i-l);return n>=r&&n<=a}function yY(s,t){return wu(s,-t)}function Mp(s,t){const r=lbs(s);let a;if(r.date){const c=cbs(r.date,2);a=dbs(c.restDateString,c.year)}if(!a||isNaN(a.getTime()))return new Date(NaN);const i=a.getTime();let l=0,o;if(r.time&&(l=ubs(r.time),isNaN(l)))return new Date(NaN);if(r.timezone){if(o=hbs(r.timezone),isNaN(o))return new Date(NaN)}else{const c=new Date(i+l),d=new Date(0);return d.setFullYear(c.getUTCFullYear(),c.getUTCMonth(),c.getUTCDate()),d.setHours(c.getUTCHours(),c.getUTCMinutes(),c.getUTCSeconds(),c.getUTCMilliseconds()),d}return new Date(i+l+o)}const ere={dateTimeDelimiter:/[T ]/,timeZoneDelimiter:/[Z ]/i,timezone:/([Z+-].*)$/},abs=/^-?(?:(\d{3})|(\d{2})(?:-?(\d{2}))?|W(\d{2})(?:-?(\d{1}))?|)$/,ibs=/^(\d{2}(?:[.,]\d*)?)(?::?(\d{2}(?:[.,]\d*)?))?(?::?(\d{2}(?:[.,]\d*)?))?$/,obs=/^([+-])(\d{2})(?::?(\d{2}))?$/;function lbs(s){const t={},n=s.split(ere.dateTimeDelimiter);let r;if(n.length>2)return t;if(/:/.test(n[0])?r=n[0]:(t.date=n[0],r=n[1],ere.timeZoneDelimiter.test(t.date)&&(t.date=s.split(ere.timeZoneDelimiter)[0],r=s.substr(t.date.length,s.length))),r){const a=ere.timezone.exec(r);a?(t.time=r.replace(a[1],""),t.timezone=a[1]):t.time=r}return t}function cbs(s,t){const n=new RegExp("^(?:(\\d{4}|[+-]\\d{"+(4+t)+"})|(\\d{2}|[+-]\\d{"+(2+t)+"})$)"),r=s.match(n);if(!r)return{year:NaN,restDateString:""};const a=r[1]?parseInt(r[1]):null,i=r[2]?parseInt(r[2]):null;return{year:i===null?a:i*100,restDateString:s.slice((r[1]||r[2]).length)}}function dbs(s,t){if(t===null)return new Date(NaN);const n=s.match(abs);if(!n)return new Date(NaN);const r=!!n[4],a=iG(n[1]),i=iG(n[2])-1,l=iG(n[3]),o=iG(n[4]),c=iG(n[5])-1;if(r)return xbs(t,o,c)?mbs(t,o,c):new Date(NaN);{const d=new Date(0);return!pbs(t,i,l)||!gbs(t,a)?new Date(NaN):(d.setUTCFullYear(t,i,Math.max(a,l)),d)}}function iG(s){return s?parseInt(s):1}function ubs(s){const t=s.match(ibs);if(!t)return NaN;const n=bIe(t[1]),r=bIe(t[2]),a=bIe(t[3]);return ybs(n,r,a)?n*G3e+r*H3e+a*1e3:NaN}function bIe(s){return s&&parseFloat(s.replace(",","."))||0}function hbs(s){if(s==="Z")return 0;const t=s.match(obs);if(!t)return 0;const n=t[1]==="+"?-1:1,r=parseInt(t[2]),a=t[3]&&parseInt(t[3])||0;return vbs(r,a)?n*(r*G3e+a*H3e):NaN}function mbs(s,t,n){const r=new Date(0);r.setUTCFullYear(s,0,4);const a=r.getUTCDay()||7,i=(t-1)*7+n+1-a;return r.setUTCDate(r.getUTCDate()+i),r}const fbs=[31,null,31,30,31,30,31,31,30,31,30,31];function eAt(s){return s%400===0||s%4===0&&s%100!==0}function pbs(s,t,n){return t>=0&&t<=11&&n>=1&&n<=(fbs[t]||(eAt(s)?29:28))}function gbs(s,t){return t>=1&&t<=(eAt(s)?366:365)}function xbs(s,t,n){return t>=1&&t<=53&&n>=0&&n<=6}function ybs(s,t,n){return s===24?t===0&&n===0:n>=0&&n<60&&t>=0&&t<60&&s>=0&&s<25}function vbs(s,t){return t>=0&&t<=59}function _Ie(s,t){const n=mo(s),r=n.getFullYear(),a=n.getDate(),i=Lh(s,0);i.setFullYear(r,t,15),i.setHours(0,0,0,0);const l=e1s(i);return n.setMonth(t,Math.min(a,l)),n}function tAt(s,t){const n=mo(s);return n.setHours(t),n}function sAt(s,t){const n=mo(s);return n.setMinutes(t),n}function Got(s,t){const n=mo(s);return isNaN(+n)?Lh(s,NaN):(n.setFullYear(t),n)}function nD(s,t){return Ux(s,-t)}const bbs=()=>{const{user:s}=ks(),t=Jn(),[n,r]=k.useState([]),[a,i]=k.useState(0),[l,o]=k.useState(!1),[c,d]=k.useState(null),u=k.useRef(null);k.useEffect(()=>{u.current=c},[c]),k.useEffect(()=>{if(!s)return;const x=`notification_last_read_${s.id}`,y=localStorage.getItem(x);y&&!u.current&&(u.current=y,d(y));const v=`nb_cache_${s.id}`,_=60*1e3,j=async()=>{try{const P=sessionStorage.getItem(v);if(P){const R=JSON.parse(P);if(R.ts&&Date.now()-R.ts<_&&Array.isArray(R.data)){C(R.data);return}}}catch{}const{data:M,error:I}=await V.from("push_notifications").select("*").order("created_at",{ascending:!1}).limit(20);!I&&M&&(sessionStorage.setItem(v,JSON.stringify({ts:Date.now(),data:M})),C(M))},C=M=>{r(M);const I=u.current?new Date(u.current):null,P=M.filter(R=>I?new Date(R.created_at)>I:!0);i(P.length)};j();const A=V.channel("push-notifications").on("postgres_changes",{event:"INSERT",schema:"public",table:"push_notifications"},M=>{const I=M.new;r(R=>{const O=[I,...R].slice(0,20);try{sessionStorage.setItem(v,JSON.stringify({ts:Date.now(),data:O}))}catch{}return O});const P=u.current?new Date(u.current):null;(!P||new Date(I.created_at)>P)&&i(R=>R+1),Notification.permission==="granted"&&new Notification(I.title,{body:I.body,icon:"/favicon.ico"})}).subscribe();return()=>{V.removeChannel(A)}},[s]);const h=x=>{const y=x.toLowerCase();return y.includes("community")||y.includes("post")?bo:y.includes("academy")||y.includes("video")?ia:y.includes("template")?gd:y.includes("event")?ha:y.includes("newsletter")?N2:y.includes("brokerage")?zx:y.includes("swag")||y.includes("social")?Zo:y.includes("toolbox")||y.includes("tool")?L5:y.includes("brief")?kn:bo},m=x=>{o(!1),x.url&&x.url!=="/"&&t(x.url)},p=()=>{if(!s)return;const x=new Date().toISOString(),y=`notification_last_read_${s.id}`;localStorage.setItem(y,x),d(x),i(0)},g=x=>{o(x),x&&a>0&&p()};return e.jsxs(Au,{open:l,onOpenChange:g,children:[e.jsx(Eu,{asChild:!0,children:e.jsxs($,{variant:"ghost",size:"icon",className:"relative",children:[e.jsx(Fx,{className:"h-5 w-5"}),a>0&&e.jsx(qe,{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(gu,{align:"end",className:"w-80",children:[e.jsxs("div",{className:"flex items-center justify-between px-3 py-2 border-b",children:[e.jsx("span",{className:"font-semibold",children:"Notifications"}),n.length>0&&e.jsx($,{variant:"ghost",size:"sm",className:"text-xs h-6",onClick:p,children:"Mark all read"})]}),e.jsx(Eo,{className:"h-[300px]",children:n.length===0?e.jsx("div",{className:"p-4 text-center text-muted-foreground text-sm",children:"No notifications yet"}):n.map(x=>{const y=h(x.title);return e.jsxs(Pa,{className:"group flex items-start gap-3 p-3 cursor-pointer data-[highlighted]:bg-accent data-[highlighted]:text-accent-foreground",onClick:()=>m(x),children:[e.jsx("div",{className:"flex-shrink-0 mt-0.5",children:e.jsx(y,{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:x.title}),e.jsx("span",{className:"text-xs text-muted-foreground line-clamp-2 group-data-[highlighted]:text-accent-foreground/80",children:x.body}),e.jsx("span",{className:"text-xs text-muted-foreground group-data-[highlighted]:text-accent-foreground/80",children:Zc(new Date(x.created_at),{addSuffix:!0})})]})]},x.id)})})]})]})};function _bs(s){return s!=null&&s.length?s.find(t=>t.is_active&&t.mls_provider_id&&!t.no_mls_mode)||s[0]:null}function Tg(){const{user:s}=ks(),{data:t,isLoading:n}=pt({queryKey:["agent-lead-site",s==null?void 0:s.id],queryFn:async()=>{const{data:r,error:a}=await V.from("lead_sites").select("id, subdomain_slug, custom_domain, site_title, is_active, plan_tier, mls_provider_id, no_mls_mode, mls_agent_id, mls_agent_key, mls_office_id").eq("agent_id",s.id).eq("is_active",!0).order("created_at",{ascending:!0}).limit(10);if(a)throw a;return _bs(r)},enabled:!!s,staleTime:5*60*1e3});return{leadSite:t??null,hasLeadSite:!!t,isFreePlan:(t==null?void 0:t.plan_tier)==="free_luxury",hasIdx:!!(t!=null&&t.mls_provider_id)&&!(t!=null&&t.no_mls_mode),isLoading:n,siteUrl:t?t.custom_domain?`https://${t.custom_domain}`:`https://${t.subdomain_slug}.thelocalmove.com`:null}}function Y3e(s=!0){const{user:t}=ks(),{data:n,isLoading:r}=pt({queryKey:["free-lead-site-offer",t==null?void 0:t.id],enabled:!!t&&s,staleTime:5*60*1e3,queryFn:async()=>{const{data:a}=await V.from("profiles").select("brokerage_id").eq("id",t.id).maybeSingle();if(!(a!=null&&a.brokerage_id))return null;const{data:i}=await V.from("lead_site_brokerage_offers").select("*").eq("brokerage_id",a.brokerage_id).eq("enabled",!0).maybeSingle();return i??null}});return{offer:n??null,hasOffer:!!n,isLoading:r}}const wbs="coaching_access";function nAt(){const{user:s,loading:t,isAdmin:n,isCoach:r}=ks(),{data:a,isLoading:i}=pt({queryKey:["coaching-access",s==null?void 0:s.id],enabled:!!s,staleTime:5*60*1e3,queryFn:async()=>{const[l,o]=await Promise.all([V.from("coaching_assignments").select("id").eq("agent_id",s.id).eq("status","active").limit(1),V.from("feature_entitlements").select("enabled, expires_at").eq("user_id",s.id).eq("feature_key",wbs).maybeSingle()]),c=(l.data||[]).length>0,d=o.data,u=!!(d!=null&&d.enabled)&&(!d.expires_at||new Date(d.expires_at).getTime()>Date.now());return{hasAssignment:c,entitled:u}}});return{hasAccess:!!(n||r||a!=null&&a.hasAssignment||a!=null&&a.entitled),hasAssignment:!!(a!=null&&a.hasAssignment),isLoading:t||i}}const Z3e=[{id:"home",label:"Home",icon:$8,route:"/dashboard",accent:"nav-home"},{id:"crm",label:"CRM",icon:Bo,description:"Contacts and follow-up",accent:"nav-crm"},{id:"deals",label:"Deals",icon:M5,description:"Pipeline, transactions and tasks",accent:"nav-deals"},{id:"listings",label:"Listings",icon:Gi,description:"Win and market listings",accent:"nav-listings"},{id:"marketing",label:"Marketing",icon:xm,description:"Content, email and video",accent:"nav-marketing"},{id:"websites",label:"Websites",icon:kc,description:"Your site and add-ons",accent:"nav-websites"},{id:"academy",label:"Learn",icon:Bm,description:"Training, programs and coaching",accent:"nav-academy"},{id:"events",label:"Events",icon:X8,route:"/events",accent:"nav-events"},{id:"apps",label:"Apps",icon:Tw,route:"/apps",accent:"nav-apps"},{id:"brokerage",label:"Brokerage",icon:Gz,description:"Your brokerage, teams and recruiting",accent:"nav-brokerage",visible:s=>!s.isAdmin&&(!!s.brokerageId||s.isBrokerageManager||s.isOnTeam)},{id:"more",label:"More",icon:u0,description:"Community, marketplace and help",accent:"nav-more"}],Hb=s=>t=>t.hasPermission(s),jbs=[{id:"mission-control",label:"Mission Control",route:"/mission-control",icon:S5,description:"Your daily relationship command center",primaryCategory:"crm",section:"Overview",visible:Hb("contacts"),searchKeywords:["agent os","mission control","dashboard"],displayOrder:10},{id:"client-portals",label:"Client Portals",route:"/mission-control/client-portals",icon:kn,description:"Private portals for buyers and sellers",primaryCategory:"crm",section:"Overview",searchKeywords:["portal","client portal"],displayOrder:20},{id:"contacts",label:"All Contacts",route:"/mission-control/contacts",icon:Xn,description:"Every contact in your database",primaryCategory:"crm",section:"Contacts",visible:Hb("contacts"),searchKeywords:["contacts","database","sphere","people"],displayOrder:30},{id:"relationship-report",label:"Relationship Report",route:"/mission-control/relationship-scorecard",icon:zp,description:"See who needs attention next",primaryCategory:"crm",section:"Contacts",visible:Hb("contacts"),searchKeywords:["relationship","scorecard","report"],displayOrder:40},{id:"sphere-gaps",label:"Sphere Gaps",route:"/mission-control/sphere-gaps",icon:ZK,description:"Find missing info across your sphere",primaryCategory:"crm",section:"Contacts",visible:Hb("contacts"),searchKeywords:["gaps","missing data"],displayOrder:50},{id:"sent-emails",label:"Sent Emails",route:"/mission-control/sent-emails",icon:Wr,description:"History of everything you have sent",primaryCategory:"crm",section:"Contacts",visible:Hb("contacts"),searchKeywords:["sent","email history"],displayOrder:60},{id:"connect-page",label:"Connect Page",route:"/mission-control/connect-page",icon:pd,description:"Your shareable intake and link page",primaryCategory:"crm",section:"Contacts",visible:Hb("contacts"),searchKeywords:["connect","link in bio","intake"],displayOrder:70},{id:"touchplans",label:"TouchPlans",route:"/mission-control/plans",icon:fd,description:"Structured touch plans for your people",primaryCategory:"crm",section:"Follow-Up",visible:Hb("contacts"),searchKeywords:["touch plan","follow up plan"],displayOrder:80},{id:"smart-drips",label:"Smart Drips",route:"/mission-control/smart-drips",icon:ix,description:"Automated drip campaigns that pause when they reply",primaryCategory:"crm",section:"Follow-Up",badge:"beta",searchKeywords:["drip","automation","campaign"],displayOrder:90},{id:"email-templates",label:"Email Templates",route:"/email-campaigns/templates",icon:pn,description:"Reusable email templates",primaryCategory:"crm",section:"Follow-Up",searchKeywords:["email template"],displayOrder:100},{id:"signals",label:"Signals",route:"/mission-control/signals",icon:iB,description:"Buying and selling signals from your database",primaryCategory:"crm",section:"Follow-Up",searchKeywords:["signals","intent","hot leads"],displayOrder:110},{id:"popbys",label:"Popbys",route:"/mission-control/popbys",icon:Zo,description:"Plan and log in-person pop-bys",primaryCategory:"crm",section:"Follow-Up",visible:Hb("popbys"),searchKeywords:["pop by","gifts","drop off"],displayOrder:120},{id:"pipeline",label:"Deal Pipeline",route:"/mission-control/pipeline",icon:M5,description:"Track every deal from lead to close",primaryCategory:"deals",section:"Pipeline",visible:Hb("pipeline"),searchKeywords:["pipeline","deals","kanban"],displayOrder:130},{id:"transactions",label:"Transactions",route:"/mission-control/transactions",icon:A5,description:"Closed and in-progress transactions",primaryCategory:"deals",section:"Pipeline",visible:Hb("pipeline"),searchKeywords:["transactions","closings"],displayOrder:140},{id:"tasks",label:"Tasks",route:"/mission-control/tasks",icon:r5,description:"Everything on your plate today",primaryCategory:"deals",section:"Pipeline",visible:Hb("pipeline"),searchKeywords:["tasks","to do"],displayOrder:150},{id:"scorecard",label:"Scorecard",route:"/mission-control/scorecard",icon:Ul,description:"Your production numbers at a glance",primaryCategory:"deals",section:"Pipeline",visible:Hb("scorecard"),searchKeywords:["scorecard","production","goals"],displayOrder:160},{id:"scheduler",label:"LevelUp Scheduler",route:"/mission-control/scheduler",icon:fd,description:"Share your booking link and sync your calendar",primaryCategory:"crm",section:"Overview",toolId:"scheduler",visible:s=>s.isAdmin,searchKeywords:["scheduler","booking","calendar","appointments"],displayOrder:25},{id:"listing-exchange",label:"Listing Exchange",route:"/mission-control/listings",icon:Gi,description:"Publish and browse member listings",primaryCategory:"listings",section:"Manage Listings",visible:Hb("listings"),searchKeywords:["listings","exchange","my listings"],displayOrder:10},{id:"listing-presentation-studio",label:"Listing Presentation Studio",route:"/apps/listing-presentation-studio",icon:hv,description:"Build a polished listing presentation PDF",primaryCategory:"listings",section:"Win the Listing",toolId:"listing-presentation-studio",searchKeywords:["listing presentation","pdf","pitch"],displayOrder:20},{id:"listing-revival",label:"Listing Revival",route:"/apps/listing-revival",icon:iu,description:"Win expired and withdrawn listings",primaryCategory:"listings",section:"Win the Listing",toolId:"listing-revival",searchKeywords:["expired","revival","withdrawn"],displayOrder:30},{id:"fsbo-breakthrough",label:"By-Owner Breakthrough",route:"/apps/fsbo-breakthrough",icon:ua,description:"Convert for-sale-by-owner sellers",primaryCategory:"listings",section:"Win the Listing",toolId:"fsbo-breakthrough",searchKeywords:["fsbo","by owner"],displayOrder:40},{id:"cma",label:"CMA Reports",route:"/mission-control/cma",icon:C5,description:"Comparative market analysis for sellers",primaryCategory:"listings",section:"Win the Listing",toolId:"cma",visible:s=>s.hasLeadSiteMLS,searchKeywords:["cma","market analysis","pricing"],displayOrder:50},{id:"guest-book",label:"Guest Book",route:"/mission-control/guest-book",icon:A5,description:"Digital open house sign-in",primaryCategory:"listings",section:"Open Houses",toolId:"guest-book",searchKeywords:["open house","sign in","guest book"],displayOrder:60},{id:"listing-studio",label:"Listing Studio",route:"/mission-control/listing-studio",icon:zc,description:"Marketing assets for a listing",primaryCategory:"listings",section:"Market the Listing",toolId:"listing-studio",searchKeywords:["listing marketing","flyer","just listed"],displayOrder:70},{id:"templates",label:"Templates",route:"/templates",icon:gd,description:"Ready-to-edit Canva templates",primaryCategory:"marketing",section:"Create",searchKeywords:["templates","canva","graphics"],displayOrder:10},{id:"marketing-studio",label:"Marketing Studio",route:"/marketing-studio",icon:zc,description:"Create branded marketing assets",primaryCategory:"marketing",section:"Create",searchKeywords:["marketing studio","design","brand kit"],displayOrder:20},{id:"social-swag",label:"Social Swag",route:"/social-swag-2",icon:yb,description:"Daily social posts you can publish in a tap",primaryCategory:"marketing",section:"Social & Content",searchKeywords:["social","posts","instagram","facebook"],displayOrder:30},{id:"weekly-reels",label:"Weekly Reels",route:"/weekly-reels",icon:em,description:"A fresh reel script every Monday",primaryCategory:"marketing",section:"Social & Content",toolId:"weekly-reels",visible:s=>s.hasWeeklyReels,searchKeywords:["reels","video script","instagram"],displayOrder:40},{id:"newsletter-pro",label:"Newsletter Pro",route:"/newsletters",icon:N2,description:"Send a branded monthly newsletter",primaryCategory:"marketing",section:"Email & Mail",badge:"new",toolId:"newsletter-pro",searchKeywords:["newsletter","email marketing"],displayOrder:50},{id:"mass-emails",label:"Mass Emails",route:"/admin/email-campaigns",icon:pn,description:"Email your whole database at once",primaryCategory:"marketing",section:"Email & Mail",toolId:"mass-emails",searchKeywords:["mass email","campaign","blast"],displayOrder:60},{id:"direct-mail",label:"Direct Mail",route:"/mission-control/direct-mail",icon:Wr,description:"Send postcards to your farm",primaryCategory:"marketing",section:"Email & Mail",visible:s=>s.isAdmin,toolId:"direct-mail",searchKeywords:["postcard","direct mail","farming"],displayOrder:70},{id:"card-studio",label:"Card Studio",route:"/mission-control/card-studio",icon:Zo,description:"Send digital celebration cards",primaryCategory:"marketing",section:"Email & Mail",toolId:"card-studio",searchKeywords:["cards","birthday","anniversary"],displayOrder:80},{id:"video-library",label:"Video Library",route:"/mission-control/video-library",icon:ia,description:"All of your recorded videos",primaryCategory:"marketing",section:"Video",visible:Hb("videos"),searchKeywords:["videos","library"],displayOrder:90},{id:"quickvid",label:"QuickVid",route:"/mission-control/video/record",icon:ia,description:"Record a personalized video in seconds",primaryCategory:"marketing",section:"Video",toolId:"quickvid",searchKeywords:["record video","video email","screen record"],displayOrder:100},{id:"reelflow",label:"ReelFlow",route:"/admin/beta/homereel",icon:em,description:"AI-assisted short-form video creation",primaryCategory:"marketing",section:"Video",toolId:"reelflow",searchKeywords:["reelflow","ai video","reels"],displayOrder:110},{id:"landing-pages",label:"Landing Pages",route:"/mission-control/landing-pages",icon:v0,description:"Capture leads with focused landing pages",primaryCategory:"marketing",section:"Lead Capture",toolId:"landing-pages",searchKeywords:["landing page","lead capture","funnel"],displayOrder:120},{id:"smart-card",label:"Smart Card",route:"/mission-control/my-card",icon:pd,description:"Your digital business card",primaryCategory:"marketing",section:"Lead Capture",toolId:"smart-card",searchKeywords:["digital card","business card","qr"],displayOrder:130},{id:"get-my-website",label:"Get My Website",route:"/get-my-website",icon:kc,description:"Claim the free site your brokerage offers",primaryCategory:"websites",section:"My Website",visible:s=>!s.hasLeadSite&&s.hasFreeSiteOffer,searchKeywords:["website","claim site","free site"],displayOrder:5},{id:"need-a-website",label:"Need a Website",route:"/need-a-website",icon:kc,description:"Request your free beta agent website",primaryCategory:"websites",section:"My Website",badge:"beta",visible:s=>!s.hasLeadSite&&!s.hasFreeSiteOffer,searchKeywords:["website","need a website","beta site","free website"],displayOrder:6},{id:"view-site",label:"View Site",route:s=>s.siteUrl||"#",icon:ba,description:"Open your live website",primaryCategory:"websites",section:"My Website",external:!0,openInNewTab:!0,visible:s=>s.hasLeadSite&&!!s.siteUrl,searchKeywords:["view site","live site"],displayOrder:10},{id:"edit-website",label:"Edit Website",route:s=>`/my-website/${s.leadSiteId}/edit`,icon:ui,description:"Site builder for pages, branding and content",primaryCategory:"websites",section:"My Website",visible:s=>s.hasLeadSite&&!!s.leadSiteId,searchKeywords:["edit website","site builder","pages"],displayOrder:20},{id:"mls-listings",label:"MLS Listings",route:"/my-website/mls-listings",icon:ua,description:"Control which listings appear on your site",primaryCategory:"websites",section:"My Website",visible:s=>s.hasLeadSite,searchKeywords:["mls","idx","listings on site"],displayOrder:30},{id:"market-reports",label:"Market Reports",route:"/my-website/market-report",icon:Ul,description:"Monthly market reports for your areas",primaryCategory:"websites",section:"My Website",visible:s=>s.hasLeadSite&&s.hasLeadSiteMLS,searchKeywords:["market report","stats"],displayOrder:40},{id:"website-activity",label:"Website Activity",route:"/mission-control/website-activity",icon:zp,description:"See who is browsing your site",primaryCategory:"websites",section:"My Website",visible:s=>s.hasLeadSite,searchKeywords:["website activity","visitors","analytics"],displayOrder:50},{id:"mobile-command",label:"Mobile Command",route:"/m",icon:yb,description:"The mobile-first agent console",primaryCategory:"websites",section:"My Website",visible:s=>s.hasLeadSite,searchKeywords:["mobile","command"],displayOrder:60},{id:"website-apps",label:"Website Apps",route:"/website-apps",icon:kn,description:"Lead magnets, video greeter and more",primaryCategory:"websites",section:"Website Add-Ons",toolId:"website-apps",searchKeywords:["widgets","lead magnet","video greeter"],displayOrder:70},{id:"levelup-u",label:"LevelUp U",route:"/levelup-u",icon:Bm,description:"Structured courses and certifications",primaryCategory:"academy",section:"Learn",badge:"new",searchKeywords:["levelup u","courses","training"],displayOrder:10},{id:"academy",label:"Academy",route:"/academy",icon:wg,description:"On-demand training videos",primaryCategory:"academy",section:"Learn",searchKeywords:["academy","videos","training"],displayOrder:20},{id:"toolbox",label:"Toolbox",route:"/toolbox",icon:L5,description:"Scripts, checklists and downloads",primaryCategory:"academy",section:"Learn",searchKeywords:["toolbox","scripts","downloads"],displayOrder:30},{id:"events",label:"Events",route:"/events",icon:X8,description:"Live trainings and member events",primaryCategory:"events",section:"Events",searchKeywords:["events","live","webinar"],displayOrder:10},{id:"programs",label:"Programs",route:"/programs",icon:v0,description:"Cohort programs like Reel Estate 90",primaryCategory:"academy",section:"Programs & Coaching",searchKeywords:["programs","reel estate 90","cohort"],displayOrder:50},{id:"coaching",label:"Coaching",route:"/coaching",icon:Bm,description:"Your coaching hub and calendar",primaryCategory:"academy",section:"Programs & Coaching",visible:s=>s.isCoach,searchKeywords:["coaching","coach hub"],displayOrder:60},{id:"my-coach",label:"My Coach",route:"/my-coach",icon:Bo,description:"Sessions, goals and notes with your coach",primaryCategory:"academy",section:"Programs & Coaching",visible:s=>s.hasCoach||s.hasCoachingAccess,searchKeywords:["my coach","sessions"],displayOrder:70},{id:"community",label:"Community",route:"/community",icon:bo,description:"Talk shop with other LevelUp members",primaryCategory:"more",section:"Community",badgeKey:"community",searchKeywords:["community","forum","posts"],displayOrder:10},{id:"wishlist",label:"Wishlist",route:"/wishlist",icon:P5,description:"Request and vote on new features",primaryCategory:"more",section:"Community",badgeKey:"wishlist",searchKeywords:["wishlist","feature request"],displayOrder:20},{id:"facebook-group",label:"Facebook Group",route:"https://www.facebook.com/share/g/1CC6thti2V/",icon:Ir,description:"Our private Facebook community",primaryCategory:"more",section:"Community",external:!0,openInNewTab:!0,searchKeywords:["facebook group"],displayOrder:30},{id:"marketplace",label:"Marketplace",route:"/marketplace",icon:uB,description:"Print and promo products",primaryCategory:"more",section:"The Goods",badge:"new",visible:s=>s.isMarketplaceEnabled,searchKeywords:["marketplace","shop","print"],displayOrder:40},{id:"reward-store",label:"Reward Store",route:"/reward-store",icon:ql,description:"Spend the points you have earned",primaryCategory:"more",section:"The Goods",searchKeywords:["rewards","points","store"],displayOrder:50},{id:"refer-friends",label:"Refer & Earn",route:"/refer-friends",icon:Zo,description:"Invite agents and earn rewards",primaryCategory:"more",section:"The Goods",searchKeywords:["referral","refer a friend"],displayOrder:60},{id:"support",label:"Support",route:"/support",icon:Kz,description:"Get help from the LevelUp team",primaryCategory:"more",section:"Help & Services",searchKeywords:["support","help","ticket"],displayOrder:70},{id:"additional-services",label:"Additional Services",route:"/additional-services",icon:kn,description:"Done-for-you services from LevelUp",primaryCategory:"more",section:"Help & Services",searchKeywords:["services","done for you"],displayOrder:80},{id:"integrations",label:"Integrations",route:"/mission-control/integrations",icon:k2,description:"Connect your CRM, calendar and socials",primaryCategory:"more",section:"Help & Services",searchKeywords:["integrations","connect","crm sync"],displayOrder:90},{id:"browser-extension",label:"Browser Extension",route:"/mission-control/browser-extension",icon:k2,description:"Install the LevelUp Chrome extension",primaryCategory:"more",section:"Help & Services",searchKeywords:["extension","chrome"],displayOrder:100},{id:"attract",label:"LevelUp Attract",route:"/attract",icon:kn,description:"Relationship-first attraction coach",primaryCategory:"more",section:"Help & Services",badge:"beta",visible:s=>s.email==="jeremy@relevelup.com",searchKeywords:["attract","recruiting"],displayOrder:110},{id:"admin-dashboard",label:"Admin Dashboard",route:"/admin",icon:fu,description:"Manage members, content and settings",primaryCategory:"more",section:"Admin",visible:s=>s.isAdmin,searchKeywords:["admin"],displayOrder:120},{id:"my-brokerage",label:"My Brokerage",route:"/my-brokerage",icon:Gi,description:"Your brokerage hub",primaryCategory:"brokerage",section:"My Brokerage",visible:s=>!!s.brokerageId&&!s.isAdmin,searchKeywords:["brokerage"],displayOrder:130},{id:"help-board",label:"Help Board",route:"/brokerage/help-board",icon:n5,description:"Ask for showing and open house coverage",primaryCategory:"brokerage",section:"My Brokerage",visible:s=>!!s.brokerageId&&!s.isAdmin,searchKeywords:["help board","coverage"],displayOrder:140},{id:"brokerage-content",label:"Brokerage Content",route:"/brokerage-content",icon:wg,description:"Content shared by your brokerage",primaryCategory:"brokerage",section:"My Brokerage",visible:s=>!!s.brokerageId&&!s.isAdmin,searchKeywords:["brokerage content"],displayOrder:150},{id:"my-team",label:"My Team",route:"/my-team",icon:Xn,description:"Your team roster and lead pond",primaryCategory:"brokerage",section:"My Team",visible:s=>s.isOnTeam&&!s.isBrokerageManager&&!s.isAdmin,searchKeywords:["team","lead pond"],displayOrder:160},{id:"manage-brokerages",label:"Manage Brokerages",route:"/brokerage/dashboard",icon:Yc,description:"Brokerage manager dashboard",primaryCategory:"brokerage",section:"Manage Brokerage",visible:s=>s.isBrokerageManager&&!s.isAdmin,searchKeywords:["manage brokerage"],displayOrder:170},{id:"brokerage-teams",label:"Teams",route:"/brokerage/teams",icon:Xn,description:"Teams, rosters and lead ponds",primaryCategory:"brokerage",section:"Manage Brokerage",badge:"new",visible:s=>s.isBrokerageManager&&!s.isAdmin,searchKeywords:["teams","pond"],displayOrder:180},{id:"brokerage-recruiting",label:"Recruiting",route:"/brokerage/recruiting",icon:xm,description:"Recruit and nurture agents",primaryCategory:"brokerage",section:"Manage Brokerage",visible:s=>s.isBrokerageManager&&!s.isAdmin,searchKeywords:["recruiting"],displayOrder:190},{id:"brokerage-vendors",label:"Vendors",route:"/brokerage/vendors",icon:E5,description:"Preferred vendor directory",primaryCategory:"brokerage",section:"Manage Brokerage",visible:s=>s.isBrokerageManager&&!s.isAdmin,searchKeywords:["vendors"],displayOrder:200},{id:"brokerage-resources",label:"Brokerage Resources",route:"/brokerage-resources",icon:zx,description:"Documents and links for your agents",primaryCategory:"brokerage",section:"Manage Brokerage",visible:s=>s.isBrokerageManager&&!s.isAdmin,searchKeywords:["resources"],displayOrder:210},{id:"my-partnership",label:"My Package",route:"/my-partnership",icon:kn,description:"What is included in your partnership package",primaryCategory:"more",section:"Account",visible:s=>s.isPartnershipMember,searchKeywords:["partnership","package","upgrade","exp luxury"],displayOrder:5},{id:"coaching-onboarding",label:"Coaching Onboarding",route:"/coaching/onboarding",icon:lv,description:"Tell your coach about your business before session one",primaryCategory:"academy",section:"Coaching",visible:s=>s.hasCoachingOnboarding,searchKeywords:["coaching","onboarding","intake"],displayOrder:45}];function rAt(s,t){return typeof s.route=="function"?s.route(t):s.route}function aAt(){const{user:s,isAdmin:t,isBrokerageManager:n,isCoach:r,brokerageId:a}=ks(),{hasPermission:i}=cee(),{isInnerCircleEnabled:l,isMarketplaceEnabled:o}=EHe(),{hasAccess:c}=I3e(),{data:d}=gj(),{leadSite:u,hasLeadSite:h,siteUrl:m}=Tg(),{hasOffer:p}=Y3e(!h),g=rA(),{hasAccess:x}=nAt(),y=ls(),{data:v}=pt({queryKey:["my-coach-nav",s==null?void 0:s.id],enabled:!!(s!=null&&s.id),staleTime:5*60*1e3,queryFn:async()=>{const{data:H}=await V.from("coaching_assignments").select("id").eq("agent_id",s.id).eq("status","active").limit(1);return(H||[]).length>0}}),{data:_}=pt({queryKey:["user-tool-favorites",s==null?void 0:s.id],enabled:!!(s!=null&&s.id),staleTime:60*1e3,queryFn:async()=>{const{data:H}=await V.from("user_tool_favorites").select("tool_id").eq("user_id",s.id);return(H||[]).map(Y=>Y.tool_id)}}),j=k.useMemo(()=>new Set(_||[]),[_]),C=Nt({mutationFn:async H=>{s!=null&&s.id&&(j.has(H)?await V.from("user_tool_favorites").delete().eq("user_id",s.id).eq("tool_id",H):await V.from("user_tool_favorites").insert({user_id:s.id,tool_id:H}))},onSuccess:()=>{y.invalidateQueries({queryKey:["user-tool-favorites"]}),y.invalidateQueries({queryKey:["app-catalog"]})}}),A=k.useMemo(()=>{var H,Y;return{isAdmin:!!t,isBrokerageManager:!!n,isCoach:!!r,isOnTeam:!!d,hasCoach:!!v,brokerageId:a??null,hasPermission:i,isInnerCircleEnabled:!!l,isMarketplaceEnabled:!!o,hasWeeklyReels:!!c,hasLeadSite:!!h,hasLeadSiteMLS:!!(u!=null&&u.mls_provider_id),hasFreeSiteOffer:!!p,leadSiteId:(u==null?void 0:u.id)??null,siteUrl:m??null,email:(s==null?void 0:s.email)??null,isPartnershipMember:g.isMember,hasCoachingOnboarding:g.isMember&&!!((H=g.pkg)!=null&&H.includes_coaching),hasCoachingAccess:!!x||g.isMember&&!!((Y=g.pkg)!=null&&Y.includes_coaching)}},[t,n,r,d,v,a,i,l,o,c,h,u,p,m,s==null?void 0:s.email,g.isMember,g.pkg,x]),M=k.useMemo(()=>jbs.filter(H=>H.visible?H.visible(A):!0).map(H=>{if(!g.isRestricted)return H;const Y=xms(H);return!Y||g.hasFeature(Y)?H:{...H,locked:!0,route:`/upgrade/${Y}`}}).sort((H,Y)=>H.displayOrder-Y.displayOrder),[A,g.isRestricted,g.features]),I=k.useMemo(()=>Z3e.filter(H=>H.visible?H.visible(A):!0),[A]),P=k.useMemo(()=>I.filter(H=>!H.route).map(H=>{const Y=M.filter(oe=>oe.primaryCategory===H.id),se=[],ee=new Map;for(const oe of Y)ee.has(oe.section)||(ee.set(oe.section,[]),se.push(oe.section)),ee.get(oe.section).push(oe);return{id:H.id,label:H.label,sections:se.map(oe=>({title:oe,items:ee.get(oe)}))}}),[M,I]),R=k.useMemo(()=>new Map(P.map(H=>[H.id,H])),[P]),O=H=>H.toolId||`nav:${H.id}`,B=H=>j.has(O(H));return{ctx:A,categories:P,railCategories:I,categoryMap:R,destinations:M,favorites:j,isFavorite:B,favoritesFor:H=>M.filter(Y=>Y.primaryCategory===H&&B(Y)),favoriteKey:O,toggleFavorite:H=>C.mutate(H),searchDestinations:H=>{const Y=H.trim().toLowerCase();return Y?M.map(ee=>{const oe=ee.label.toLowerCase(),me=(ee.description||"").toLowerCase(),Q=(ee.searchKeywords||[]).join(" ").toLowerCase();let te=0;return oe===Y?te=100:oe.startsWith(Y)?te=80:oe.includes(Y)?te=60:Q.includes(Y)?te=40:me.includes(Y)?te=20:ee.section.toLowerCase().includes(Y)&&(te=10),te&&B(ee)&&(te+=5),{d:ee,score:te}}).filter(ee=>ee.score>0).sort((ee,oe)=>oe.score-ee.score).map(ee=>ee.d):[]},routeFor:H=>rAt(H,A)}}var Wot=1,Nbs=.9,kbs=.8,Sbs=.17,wIe=.1,jIe=.999,Cbs=.9999,Abs=.99,Ebs=/[\\\/_+.#"@\[\(\{&]/,Tbs=/[\\\/_+.#"@\[\(\{&]/g,Mbs=/[\s-]/,iAt=/[\s-]/g;function y7e(s,t,n,r,a,i,l){if(i===t.length)return a===s.length?Wot:Abs;var o=`${a},${i}`;if(l[o]!==void 0)return l[o];for(var c=r.charAt(i),d=n.indexOf(c,a),u=0,h,m,p,g;d>=0;)h=y7e(s,t,n,r,d+1,i+1,l),h>u&&(d===a?h*=Wot:Ebs.test(s.charAt(d-1))?(h*=kbs,p=s.slice(a,d-1).match(Tbs),p&&a>0&&(h*=Math.pow(jIe,p.length))):Mbs.test(s.charAt(d-1))?(h*=Nbs,g=s.slice(a,d-1).match(iAt),g&&a>0&&(h*=Math.pow(jIe,g.length))):(h*=Sbs,a>0&&(h*=Math.pow(jIe,d-a))),s.charAt(d)!==t.charAt(i)&&(h*=Cbs)),(hh&&(h=m*wIe)),h>u&&(u=h),d=n.indexOf(c,d+1);return l[o]=u,u}function Kot(s){return s.toLowerCase().replace(iAt," ")}function Pbs(s,t,n){return s=n&&n.length>0?`${s+" "+n.join(" ")}`:s,y7e(s,t,Kot(s),Kot(t),0,0,{})}var oG='[cmdk-group=""]',NIe='[cmdk-group-items=""]',Ibs='[cmdk-group-heading=""]',oAt='[cmdk-item=""]',Yot=`${oAt}:not([aria-disabled="true"])`,v7e="cmdk-item-select",M9="data-value",Lbs=(s,t,n)=>Pbs(s,t,n),lAt=k.createContext(void 0),yee=()=>k.useContext(lAt),cAt=k.createContext(void 0),dGe=()=>k.useContext(cAt),dAt=k.createContext(void 0),uAt=k.forwardRef((s,t)=>{let n=P9(()=>{var le,fe;return{search:"",value:(fe=(le=s.value)!=null?le:s.defaultValue)!=null?fe:"",selectedItemId:void 0,filtered:{count:0,items:new Map,groups:new Set}}}),r=P9(()=>new Set),a=P9(()=>new Map),i=P9(()=>new Map),l=P9(()=>new Set),o=hAt(s),{label:c,children:d,value:u,onValueChange:h,filter:m,shouldFilter:p,loop:g,disablePointerSelection:x=!1,vimBindings:y=!0,...v}=s,_=$x(),j=$x(),C=$x(),A=k.useRef(null),M=Hbs();RO(()=>{if(u!==void 0){let le=u.trim();n.current.value=le,I.emit()}},[u]),RO(()=>{M(6,G)},[]);let I=k.useMemo(()=>({subscribe:le=>(l.current.add(le),()=>l.current.delete(le)),snapshot:()=>n.current,setState:(le,fe,_e)=>{var ve,he,Se,Te;if(!Object.is(n.current[le],fe)){if(n.current[le]=fe,le==="search")U(),O(),M(1,B);else if(le==="value"){if(document.activeElement.hasAttribute("cmdk-input")||document.activeElement.hasAttribute("cmdk-root")){let Ie=document.getElementById(C);Ie?Ie.focus():(ve=document.getElementById(_))==null||ve.focus()}if(M(7,()=>{var Ie;n.current.selectedItemId=(Ie=H())==null?void 0:Ie.id,I.emit()}),_e||M(5,G),((he=o.current)==null?void 0:he.value)!==void 0){let Ie=fe??"";(Te=(Se=o.current).onValueChange)==null||Te.call(Se,Ie);return}}I.emit()}},emit:()=>{l.current.forEach(le=>le())}}),[]),P=k.useMemo(()=>({value:(le,fe,_e)=>{var ve;fe!==((ve=i.current.get(le))==null?void 0:ve.value)&&(i.current.set(le,{value:fe,keywords:_e}),n.current.filtered.items.set(le,R(fe,_e)),M(2,()=>{O(),I.emit()}))},item:(le,fe)=>(r.current.add(le),fe&&(a.current.has(fe)?a.current.get(fe).add(le):a.current.set(fe,new Set([le]))),M(3,()=>{U(),O(),n.current.value||B(),I.emit()}),()=>{i.current.delete(le),r.current.delete(le),n.current.filtered.items.delete(le);let _e=H();M(4,()=>{U(),(_e==null?void 0:_e.getAttribute("id"))===le&&B(),I.emit()})}),group:le=>(a.current.has(le)||a.current.set(le,new Set),()=>{i.current.delete(le),a.current.delete(le)}),filter:()=>o.current.shouldFilter,label:c||s["aria-label"],getDisablePointerSelection:()=>o.current.disablePointerSelection,listId:_,inputId:C,labelId:j,listInnerRef:A}),[]);function R(le,fe){var _e,ve;let he=(ve=(_e=o.current)==null?void 0:_e.filter)!=null?ve:Lbs;return le?he(le,n.current.search,fe):0}function O(){if(!n.current.search||o.current.shouldFilter===!1)return;let le=n.current.filtered.items,fe=[];n.current.filtered.groups.forEach(ve=>{let he=a.current.get(ve),Se=0;he.forEach(Te=>{let Ie=le.get(Te);Se=Math.max(Ie,Se)}),fe.push([ve,Se])});let _e=A.current;Y().sort((ve,he)=>{var Se,Te;let Ie=ve.getAttribute("id"),Ue=he.getAttribute("id");return((Se=le.get(Ue))!=null?Se:0)-((Te=le.get(Ie))!=null?Te:0)}).forEach(ve=>{let he=ve.closest(NIe);he?he.appendChild(ve.parentElement===he?ve:ve.closest(`${NIe} > *`)):_e.appendChild(ve.parentElement===_e?ve:ve.closest(`${NIe} > *`))}),fe.sort((ve,he)=>he[1]-ve[1]).forEach(ve=>{var he;let Se=(he=A.current)==null?void 0:he.querySelector(`${oG}[${M9}="${encodeURIComponent(ve[0])}"]`);Se==null||Se.parentElement.appendChild(Se)})}function B(){let le=Y().find(_e=>_e.getAttribute("aria-disabled")!=="true"),fe=le==null?void 0:le.getAttribute(M9);I.setState("value",fe||void 0)}function U(){var le,fe,_e,ve;if(!n.current.search||o.current.shouldFilter===!1){n.current.filtered.count=r.current.size;return}n.current.filtered.groups=new Set;let he=0;for(let Se of r.current){let Te=(fe=(le=i.current.get(Se))==null?void 0:le.value)!=null?fe:"",Ie=(ve=(_e=i.current.get(Se))==null?void 0:_e.keywords)!=null?ve:[],Ue=R(Te,Ie);n.current.filtered.items.set(Se,Ue),Ue>0&&he++}for(let[Se,Te]of a.current)for(let Ie of Te)if(n.current.filtered.items.get(Ie)>0){n.current.filtered.groups.add(Se);break}n.current.filtered.count=he}function G(){var le,fe,_e;let ve=H();ve&&(((le=ve.parentElement)==null?void 0:le.firstChild)===ve&&((_e=(fe=ve.closest(oG))==null?void 0:fe.querySelector(Ibs))==null||_e.scrollIntoView({block:"nearest"})),ve.scrollIntoView({block:"nearest"}))}function H(){var le;return(le=A.current)==null?void 0:le.querySelector(`${oAt}[aria-selected="true"]`)}function Y(){var le;return Array.from(((le=A.current)==null?void 0:le.querySelectorAll(Yot))||[])}function se(le){let fe=Y()[le];fe&&I.setState("value",fe.getAttribute(M9))}function ee(le){var fe;let _e=H(),ve=Y(),he=ve.findIndex(Te=>Te===_e),Se=ve[he+le];(fe=o.current)!=null&&fe.loop&&(Se=he+le<0?ve[ve.length-1]:he+le===ve.length?ve[0]:ve[he+le]),Se&&I.setState("value",Se.getAttribute(M9))}function oe(le){let fe=H(),_e=fe==null?void 0:fe.closest(oG),ve;for(;_e&&!ve;)_e=le>0?qbs(_e,oG):Vbs(_e,oG),ve=_e==null?void 0:_e.querySelector(Yot);ve?I.setState("value",ve.getAttribute(M9)):ee(le)}let me=()=>se(Y().length-1),Q=le=>{le.preventDefault(),le.metaKey?me():le.altKey?oe(1):ee(1)},te=le=>{le.preventDefault(),le.metaKey?se(0):le.altKey?oe(-1):ee(-1)};return k.createElement(hi.div,{ref:t,tabIndex:-1,...v,"cmdk-root":"",onKeyDown:le=>{var fe;(fe=v.onKeyDown)==null||fe.call(v,le);let _e=le.nativeEvent.isComposing||le.keyCode===229;if(!(le.defaultPrevented||_e))switch(le.key){case"n":case"j":{y&&le.ctrlKey&&Q(le);break}case"ArrowDown":{Q(le);break}case"p":case"k":{y&&le.ctrlKey&&te(le);break}case"ArrowUp":{te(le);break}case"Home":{le.preventDefault(),se(0);break}case"End":{le.preventDefault(),me();break}case"Enter":{le.preventDefault();let ve=H();if(ve){let he=new Event(v7e);ve.dispatchEvent(he)}}}}},k.createElement("label",{"cmdk-label":"",htmlFor:P.inputId,id:P.labelId,style:Wbs},c),X3e(s,le=>k.createElement(cAt.Provider,{value:I},k.createElement(lAt.Provider,{value:P},le))))}),Rbs=k.forwardRef((s,t)=>{var n,r;let a=$x(),i=k.useRef(null),l=k.useContext(dAt),o=yee(),c=hAt(s),d=(r=(n=c.current)==null?void 0:n.forceMount)!=null?r:l==null?void 0:l.forceMount;RO(()=>{if(!d)return o.item(a,l==null?void 0:l.id)},[d]);let u=mAt(a,i,[s.value,s.children,i],s.keywords),h=dGe(),m=kM(M=>M.value&&M.value===u.current),p=kM(M=>d||o.filter()===!1?!0:M.search?M.filtered.items.get(a)>0:!0);k.useEffect(()=>{let M=i.current;if(!(!M||s.disabled))return M.addEventListener(v7e,g),()=>M.removeEventListener(v7e,g)},[p,s.onSelect,s.disabled]);function g(){var M,I;x(),(I=(M=c.current).onSelect)==null||I.call(M,u.current)}function x(){h.setState("value",u.current,!0)}if(!p)return null;let{disabled:y,value:v,onSelect:_,forceMount:j,keywords:C,...A}=s;return k.createElement(hi.div,{ref:SO(i,t),...A,id:a,"cmdk-item":"",role:"option","aria-disabled":!!y,"aria-selected":!!m,"data-disabled":!!y,"data-selected":!!m,onPointerMove:y||o.getDisablePointerSelection()?void 0:x,onClick:y?void 0:g},s.children)}),Dbs=k.forwardRef((s,t)=>{let{heading:n,children:r,forceMount:a,...i}=s,l=$x(),o=k.useRef(null),c=k.useRef(null),d=$x(),u=yee(),h=kM(p=>a||u.filter()===!1?!0:p.search?p.filtered.groups.has(l):!0);RO(()=>u.group(l),[]),mAt(l,o,[s.value,s.heading,c]);let m=k.useMemo(()=>({id:l,forceMount:a}),[a]);return k.createElement(hi.div,{ref:SO(o,t),...i,"cmdk-group":"",role:"presentation",hidden:h?void 0:!0},n&&k.createElement("div",{ref:c,"cmdk-group-heading":"","aria-hidden":!0,id:d},n),X3e(s,p=>k.createElement("div",{"cmdk-group-items":"",role:"group","aria-labelledby":n?d:void 0},k.createElement(dAt.Provider,{value:m},p))))}),Obs=k.forwardRef((s,t)=>{let{alwaysRender:n,...r}=s,a=k.useRef(null),i=kM(l=>!l.search);return!n&&!i?null:k.createElement(hi.div,{ref:SO(a,t),...r,"cmdk-separator":"",role:"separator"})}),Fbs=k.forwardRef((s,t)=>{let{onValueChange:n,...r}=s,a=s.value!=null,i=dGe(),l=kM(d=>d.search),o=kM(d=>d.selectedItemId),c=yee();return k.useEffect(()=>{s.value!=null&&i.setState("search",s.value)},[s.value]),k.createElement(hi.input,{ref:t,...r,"cmdk-input":"",autoComplete:"off",autoCorrect:"off",spellCheck:!1,"aria-autocomplete":"list",role:"combobox","aria-expanded":!0,"aria-controls":c.listId,"aria-labelledby":c.labelId,"aria-activedescendant":o,id:c.inputId,type:"text",value:a?s.value:l,onChange:d=>{a||i.setState("search",d.target.value),n==null||n(d.target.value)}})}),zbs=k.forwardRef((s,t)=>{let{children:n,label:r="Suggestions",...a}=s,i=k.useRef(null),l=k.useRef(null),o=kM(d=>d.selectedItemId),c=yee();return k.useEffect(()=>{if(l.current&&i.current){let d=l.current,u=i.current,h,m=new ResizeObserver(()=>{h=requestAnimationFrame(()=>{let p=d.offsetHeight;u.style.setProperty("--cmdk-list-height",p.toFixed(1)+"px")})});return m.observe(d),()=>{cancelAnimationFrame(h),m.unobserve(d)}}},[]),k.createElement(hi.div,{ref:SO(i,t),...a,"cmdk-list":"",role:"listbox",tabIndex:-1,"aria-activedescendant":o,"aria-label":r,id:c.listId},X3e(s,d=>k.createElement("div",{ref:SO(l,c.listInnerRef),"cmdk-list-sizer":""},d)))}),Bbs=k.forwardRef((s,t)=>{let{open:n,onOpenChange:r,overlayClassName:a,contentClassName:i,container:l,...o}=s;return k.createElement(o3e,{open:n,onOpenChange:r},k.createElement(l3e,{container:l},k.createElement(Pq,{"cmdk-overlay":"",className:a}),k.createElement(Iq,{"aria-label":s.label,"cmdk-dialog":"",className:i},k.createElement(uAt,{ref:t,...o}))))}),$bs=k.forwardRef((s,t)=>kM(n=>n.filtered.count===0)?k.createElement(hi.div,{ref:t,...s,"cmdk-empty":"",role:"presentation"}):null),Ubs=k.forwardRef((s,t)=>{let{progress:n,children:r,label:a="Loading...",...i}=s;return k.createElement(hi.div,{ref:t,...i,"cmdk-loading":"",role:"progressbar","aria-valuenow":n,"aria-valuemin":0,"aria-valuemax":100,"aria-label":a},X3e(s,l=>k.createElement("div",{"aria-hidden":!0},l)))}),F_=Object.assign(uAt,{List:zbs,Item:Rbs,Input:Fbs,Group:Dbs,Separator:Obs,Dialog:Bbs,Empty:$bs,Loading:Ubs});function qbs(s,t){let n=s.nextElementSibling;for(;n;){if(n.matches(t))return n;n=n.nextElementSibling}}function Vbs(s,t){let n=s.previousElementSibling;for(;n;){if(n.matches(t))return n;n=n.previousElementSibling}}function hAt(s){let t=k.useRef(s);return RO(()=>{t.current=s}),t}var RO=typeof window>"u"?k.useEffect:k.useLayoutEffect;function P9(s){let t=k.useRef();return t.current===void 0&&(t.current=s()),t}function kM(s){let t=dGe(),n=()=>s(t.snapshot());return k.useSyncExternalStore(t.subscribe,n,n)}function mAt(s,t,n,r=[]){let a=k.useRef(),i=yee();return RO(()=>{var l;let o=(()=>{var d;for(let u of n){if(typeof u=="string")return u.trim();if(typeof u=="object"&&"current"in u)return u.current?(d=u.current.textContent)==null?void 0:d.trim():a.current}})(),c=r.map(d=>d.trim());i.value(s,o,c),(l=t.current)==null||l.setAttribute(M9,o),a.current=o}),a}var Hbs=()=>{let[s,t]=k.useState(),n=P9(()=>new Map);return RO(()=>{n.current.forEach(r=>r()),n.current=new Map},[s]),(r,a)=>{n.current.set(r,a),t({})}};function Gbs(s){let t=s.type;return typeof t=="function"?t(s.props):"render"in t?t.render(s.props):s}function X3e({asChild:s,children:t},n){return s&&k.isValidElement(t)?k.cloneElement(Gbs(t),{ref:t.ref},n(t.props.children)):n(t)}var Wbs={position:"absolute",width:"1px",height:"1px",padding:"0",margin:"-1px",overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",borderWidth:"0"};const M_=k.forwardRef(({className:s,...t},n)=>e.jsx(F_,{ref:n,className:Ot("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",s),...t}));M_.displayName=F_.displayName;const Kbs=({children:s,...t})=>e.jsx(zs,{...t,children:e.jsx(Rs,{className:"overflow-hidden p-0 shadow-lg",children:e.jsx(M_,{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})})}),P_=k.forwardRef(({className:s,...t},n)=>e.jsxs("div",{className:"flex items-center border-b px-3","cmdk-input-wrapper":"",children:[e.jsx(Yr,{className:"mr-2 h-4 w-4 shrink-0 opacity-50"}),e.jsx(F_.Input,{ref:n,className:Ot("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})]}));P_.displayName=F_.Input.displayName;const I_=k.forwardRef(({className:s,...t},n)=>e.jsx(F_.List,{ref:n,className:Ot("max-h-[300px] overflow-y-auto overflow-x-hidden",s),...t}));I_.displayName=F_.List.displayName;const L_=k.forwardRef((s,t)=>e.jsx(F_.Empty,{ref:t,className:"py-6 text-center text-sm",...s}));L_.displayName=F_.Empty.displayName;const Nb=k.forwardRef(({className:s,...t},n)=>e.jsx(F_.Group,{ref:n,className:Ot("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}));Nb.displayName=F_.Group.displayName;const Ybs=k.forwardRef(({className:s,...t},n)=>e.jsx(F_.Separator,{ref:n,className:Ot("-mx-1 h-px bg-border",s),...t}));Ybs.displayName=F_.Separator.displayName;const rv=k.forwardRef(({className:s,...t},n)=>e.jsx(F_.Item,{ref:n,className:Ot("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}));rv.displayName=F_.Item.displayName;const Zbs={event:{label:"Events",icon:fd,color:"bg-blue-500/10 text-blue-600"},template:{label:"Templates",icon:gd,color:"bg-purple-500/10 text-purple-600"},academy:{label:"Academy",icon:Bm,color:"bg-amber-500/10 text-amber-600"},toolbox:{label:"Toolbox",icon:L5,color:"bg-green-500/10 text-green-600"},"social-swag":{label:"Social Swag",icon:kn,color:"bg-fuchsia-500/10 text-fuchsia-600"}},Zot=()=>{const[s,t]=k.useState(!1),[n,r]=k.useState(""),[a,i]=k.useState([]),[l,o]=k.useState(!1),c=Jn(),{searchDestinations:d,isFavorite:u,routeFor:h}=aAt(),m=n.trim()?d(n).slice(0,6):[];k.useEffect(()=>{const y=v=>{v.key==="k"&&(v.metaKey||v.ctrlKey)&&(v.preventDefault(),t(_=>!_))};return document.addEventListener("keydown",y),()=>document.removeEventListener("keydown",y)},[]);const p=k.useCallback(async y=>{if(!y.trim()){i([]);return}o(!0);const v=`%${y}%`;try{const[_,j,C,A,M]=await Promise.all([V.from("events").select("id, title, description, event_date").eq("is_published",!0).or(`title.ilike.${v},description.ilike.${v}`).limit(5),V.from("canva_templates").select("id, name, description, publish_date").or(`name.ilike.${v},description.ilike.${v}`).limit(5),V.from("academy_videos").select("id, title, description, publish_date").eq("is_published",!0).or(`title.ilike.${v},description.ilike.${v}`).limit(5),V.from("resource_kits").select("id, name, description, publish_date").eq("is_published",!0).or(`name.ilike.${v},description.ilike.${v}`).limit(5),V.from("social_swag").select("id, title, description, publish_date").eq("is_published",!0).or(`title.ilike.${v},description.ilike.${v}`).limit(5)]),I=[];_.data&&_.data.forEach(P=>{I.push({id:P.id,title:P.title,description:P.description,type:"event",date:P.event_date,path:`/event/${P.id}`})}),j.data&&j.data.forEach(P=>{I.push({id:P.id,title:P.name,description:P.description,type:"template",date:P.publish_date,path:`/templates/${P.id}`})}),C.data&&C.data.forEach(P=>{I.push({id:P.id,title:P.title,description:P.description,type:"academy",date:P.publish_date,path:`/academy/${P.id}`})}),A.data&&A.data.forEach(P=>{I.push({id:P.id,title:P.name,description:P.description,type:"toolbox",date:P.publish_date,path:`/toolbox/${P.id}`})}),M.data&&M.data.forEach(P=>{I.push({id:P.id,title:P.title,description:P.description,type:"social-swag",date:P.publish_date,path:`/social-swag/${P.id}`})}),i(I)}catch(_){console.error("Search error:",_)}finally{o(!1)}},[]);k.useEffect(()=>{const y=setTimeout(()=>{p(n)},300);return()=>clearTimeout(y)},[n,p]);const g=y=>{t(!1),r(""),c(y)},x=a.reduce((y,v)=>(y[v.type]||(y[v.type]=[]),y[v.type].push(v),y),{});return e.jsxs(e.Fragment,{children:[e.jsxs($,{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(Yr,{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(Kbs,{open:s,onOpenChange:t,children:[e.jsx(P_,{placeholder:"Search events, templates, academy, toolbox, social swag...",value:n,onValueChange:r}),e.jsxs(I_,{children:[m.length>0&&e.jsx(Nb,{heading:"Go to",children:m.map(y=>{const v=y.icon;return e.jsxs(rv,{value:`nav-${y.id}-${y.label}`,onSelect:()=>{const _=h(y);y.external||y.openInNewTab?(t(!1),r(""),window.open(_,"_blank","noopener,noreferrer")):g(_)},className:"flex items-start gap-3 py-3 cursor-pointer",children:[e.jsx("div",{className:"p-2 rounded-md bg-primary/10 text-primary",children:e.jsx(v,{className:"h-4 w-4"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"font-medium truncate flex items-center gap-1.5",children:[y.label,u(y)&&e.jsx(jy,{className:"h-3 w-3 fill-current text-primary"})]}),y.description&&e.jsx("div",{className:"text-sm text-muted-foreground truncate",children:y.description})]}),e.jsx(qe,{variant:"secondary",className:"text-xs shrink-0",children:y.section})]},`nav-${y.id}`)})}),l&&e.jsx("div",{className:"py-6 text-center text-sm text-muted-foreground",children:"Searching..."}),!l&&n&&a.length===0&&m.length===0&&e.jsxs(L_,{children:['No results found for "',n,'"']}),!l&&!n&&e.jsx("div",{className:"py-6 text-center text-sm text-muted-foreground",children:"Start typing to search pages, apps and content..."}),Object.entries(x).map(([y,v])=>{const _=Zbs[y],j=_.icon;return e.jsx(Nb,{heading:_.label,children:v.map(C=>e.jsxs(rv,{value:`${C.type}-${C.id}-${C.title}`,onSelect:()=>g(C.path),className:"flex items-start gap-3 py-3 cursor-pointer",children:[e.jsx("div",{className:`p-2 rounded-md ${_.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:C.title}),C.description&&e.jsx("div",{className:"text-sm text-muted-foreground truncate group-data-[selected=true]:text-primary-foreground/80",children:C.description})]}),e.jsxs("div",{className:"flex flex-col items-end gap-1 shrink-0",children:[e.jsx(qe,{variant:"secondary",className:"text-xs",children:_.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:Zc(new Date(C.date),{addSuffix:!0})})]})]},`${C.type}-${C.id}`))},y)})]})]})]})},Xbs=({expiresAt:s,className:t,showUpgradeButton:n=!0})=>{const[r,a]=k.useState(null),i=Jn();if(k.useEffect(()=>{const d=()=>{const h=new Date().getTime(),p=new Date(s).getTime()-h;if(p<=0){a({days:0,hours:0,minutes:0});return}const g=Math.floor(p/(1e3*60*60*24)),x=Math.floor(p%(1e3*60*60*24)/(1e3*60*60)),y=Math.floor(p%(1e3*60*60)/(1e3*60));a({days:g,hours:x,minutes:y})};d();const u=setInterval(d,6e4);return()=>clearInterval(u)},[s]),!r)return null;const l=r.days===0&&r.hours===0&&r.minutes===0,o=r.days<=1,c=r.days<=3&&!o;return l?e.jsxs("div",{className:Ot("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(Gd,{className:"h-4 w-4 text-destructive"}),e.jsx("span",{className:"text-sm font-medium text-destructive",children:"Your free trial has expired"})]}),n&&e.jsxs($,{size:"sm",onClick:()=>i("/subscription"),className:"bg-primary hover:bg-primary/90 text-xs h-7 px-3",children:[e.jsx(kn,{className:"h-3 w-3 mr-1"}),"Upgrade Now"]})]}):e.jsxs("div",{className:Ot("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(sa,{className:Ot("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:Ot("text-sm font-medium",o?"text-destructive":c?"text-amber-600":"text-primary"),children:"Free Trial:"}),e.jsxs("div",{className:"flex items-center gap-1",children:[r.days>0&&e.jsxs("span",{className:Ot("text-sm font-bold",o?"text-destructive":c?"text-amber-600":"text-primary"),children:[r.days,"d"]}),e.jsxs("span",{className:Ot("text-sm font-bold",o?"text-destructive":c?"text-amber-600":"text-primary"),children:[r.hours,"h"]}),e.jsxs("span",{className:Ot("text-sm font-bold",o?"text-destructive":c?"text-amber-600":"text-primary"),children:[r.minutes,"m"]}),e.jsx("span",{className:Ot("text-xs",o?"text-destructive/70":c?"text-amber-600/70":"text-primary/70"),children:"remaining"})]})]})]}),n&&e.jsxs($,{size:"sm",onClick:()=>i("/subscription"),variant:o?"destructive":c?"default":"outline",className:Ot("text-xs h-7 px-3",c&&"bg-amber-500 hover:bg-amber-600 text-white"),children:[e.jsx(kn,{className:"h-3 w-3 mr-1"}),"Upgrade"]})]})},Qbs=()=>{const s=Jn();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(we,{className:"w-full max-w-2xl shadow-2xl border-destructive/20 my-8",children:[e.jsxs(Vt,{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(Gd,{className:"h-8 w-8 text-destructive"})}),e.jsx(Yt,{className:"text-2xl",children:"Your Free Trial Has Ended"}),e.jsx(vr,{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(we,{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(Xn,{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($,{className:"w-full",onClick:t=>{t.stopPropagation(),s("/subscription")},children:[e.jsx(kn,{className:"h-4 w-4 mr-2"}),"Choose Individual"]})]})}),e.jsx(we,{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(Gi,{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($,{variant:"outline",className:"w-full border-amber-500 text-amber-600 hover:bg-amber-50",onClick:t=>{t.stopPropagation(),s("/subscription")},children:[e.jsx(Gi,{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(ka,{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(pn,{className:"h-4 w-4"}),e.jsx("span",{children:"support@relevelup.com"})]})]})]})]})]})})},Jbs=({hasUnseenBrief:s,onClick:t,className:n})=>e.jsxs(Lx,{children:[e.jsx(Rx,{asChild:!0,children:e.jsxs($,{variant:"ghost",size:"icon",onClick:t,className:Ot("relative transition-colors",s&&"text-primary hover:text-primary",n),children:[e.jsx(xm,{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(Jg,{children:e.jsx("p",{children:"The LevelUp Brief"})})]});var e_s=Object.defineProperty,q3=(s,t)=>e_s(s,"name",{value:t,configurable:!0}),uGe="Checkbox",[t_s,LQn]=qm(uGe),[s_s,hGe]=t_s(uGe);function fAt(s){const{__scopeCheckbox:t,checked:n,children:r,defaultChecked:a,disabled:i,form:l,name:o,onCheckedChange:c,required:d,value:u="on",internal_do_not_use_render:h}=s,[m,p]=ox({prop:n,defaultProp:a??!1,onChange:c,caller:uGe}),[g,x]=k.useState(null),[y,v]=k.useState(null),_=k.useRef(!1),[j,C]=k.useReducer(I=>I+1,0),A=g?!!l||!!g.closest("form"):!0,M={checked:m,disabled:i,setChecked:p,control:g,setControl:x,name:o,form:l,value:u,hasConsumerStoppedPropagationRef:_,userInteractionCount:j,onUserInteraction:C,required:d,defaultChecked:N3(a)?!1:a,isFormControl:A,bubbleInput:y,setBubbleInput:v};return e.jsx(s_s,{scope:t,...M,children:gAt(h)?h(M):r})}q3(fAt,"CheckboxProvider");var n_s="CheckboxTrigger",r_s=k.forwardRef(q3(function({__scopeCheckbox:t,onKeyDown:n,onClick:r,...a},i){const{control:l,value:o,disabled:c,checked:d,required:u,setControl:h,setChecked:m,hasConsumerStoppedPropagationRef:p,onUserInteraction:g,isFormControl:x,bubbleInput:y}=hGe(n_s,t),v=Ao(i,h),_=k.useRef(d);return k.useEffect(()=>{const j=l==null?void 0:l.form;if(j){const C=q3(()=>m(_.current),"reset");return j.addEventListener("reset",C),()=>j.removeEventListener("reset",C)}},[l,m]),e.jsx(hi.button,{type:"button",role:"checkbox","aria-checked":N3(d)?"mixed":d,"aria-required":u,"data-state":mGe(d),"data-disabled":c?"":void 0,disabled:c,value:o,...a,ref:v,onKeyDown:ga(n,j=>{j.key==="Enter"&&j.preventDefault()}),onClick:ga(r,j=>{g(),m(C=>N3(C)?!0:!C),y&&x&&(p.current=j.isPropagationStopped(),p.current||j.stopPropagation())})})},"CheckboxTrigger")),pAt=k.forwardRef(q3(function(t,n){const{__scopeCheckbox:r,name:a,checked:i,defaultChecked:l,required:o,disabled:c,value:d,onCheckedChange:u,form:h,...m}=t;return e.jsx(fAt,{__scopeCheckbox:r,checked:i,defaultChecked:l,disabled:c,required:o,onCheckedChange:u,name:a,form:h,value:d,internal_do_not_use_render:({isFormControl:p})=>e.jsxs(e.Fragment,{children:[e.jsx(r_s,{...m,ref:n,__scopeCheckbox:r}),p&&e.jsx(l_s,{__scopeCheckbox:r})]})})},"Checkbox")),a_s="CheckboxIndicator",i_s=k.forwardRef(q3(function(t,n){const{__scopeCheckbox:r,forceMount:a,...i}=t,l=hGe(a_s,r);return e.jsx(cx,{present:a||N3(l.checked)||l.checked===!0,children:e.jsx(hi.span,{"data-state":mGe(l.checked),"data-disabled":l.disabled?"":void 0,...i,ref:n,style:{pointerEvents:"none",...t.style}})})},"CheckboxIndicator")),o_s="CheckboxBubbleInput",l_s=k.forwardRef(q3(function({__scopeCheckbox:t,onClick:n,...r},a){const{control:i,hasConsumerStoppedPropagationRef:l,userInteractionCount:o,checked:c,defaultChecked:d,required:u,disabled:h,name:m,value:p,form:g,bubbleInput:x,setBubbleInput:y}=hGe(o_s,t),v=Ao(a,y),_=Dq(i),j=k.useRef(!1),C=k.useRef(c),A=k.useRef(o);k.useEffect(()=>{const I=x;if(!I)return;const P=window.HTMLInputElement.prototype,O=Object.getOwnPropertyDescriptor(P,"checked").set,B=o!==A.current;A.current=o;const U=C.current!==c;C.current=c;const G=!(B&&l.current);if(U&&O){j.current=!B;const H=new Event("click",{bubbles:G});I.indeterminate=N3(c),O.call(I,N3(c)?!1:c),I.dispatchEvent(H),j.current=!1}},[x,c,l,o]);const M=k.useRef(N3(c)?!1:c);return e.jsx(hi.input,{type:"checkbox","aria-hidden":!0,defaultChecked:d??M.current,required:u,disabled:h,name:m,value:p,form:g,...r,tabIndex:-1,ref:v,onClick:ga(n,I=>{j.current&&I.stopPropagation()}),style:{...r.style,..._,position:"absolute",pointerEvents:"none",opacity:0,margin:0,transform:"translateX(-100%)"}})},"CheckboxBubbleInput"));function gAt(s){return typeof s=="function"}q3(gAt,"isFunction");function N3(s){return s==="indeterminate"}q3(N3,"isIndeterminate");function mGe(s){return N3(s)?"indeterminate":s?"checked":"unchecked"}q3(mGe,"getState");const Li=k.forwardRef(({className:s,...t},n)=>e.jsx(pAt,{ref:n,className:Ot("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(i_s,{className:Ot("flex items-center justify-center text-current"),children:e.jsx(ma,{className:"h-4 w-4"})})}));Li.displayName=pAt.displayName;var c_s=Object.defineProperty,u1=(s,t)=>c_s(s,"name",{value:t,configurable:!0}),xAt="Radio",[d_s,yAt]=qm(xAt),[u_s,Q3e]=d_s(xAt);function vAt(s){const{__scopeRadio:t,checked:n=!1,children:r,disabled:a,form:i,name:l,onCheck:o,required:c,value:d="on",internal_do_not_use_render:u}=s,[h,m]=k.useState(null),[p,g]=k.useState(null),x=k.useRef(!1),[y,v]=k.useReducer(C=>C+1,0),_=h?!!i||!!h.closest("form"):!0,j={checked:n,disabled:a,required:c,name:l,form:i,value:d,control:h,setControl:m,hasConsumerStoppedPropagationRef:x,userInteractionCount:y,onUserInteraction:v,isFormControl:_,bubbleInput:p,setBubbleInput:g,onCheck:u1(()=>o==null?void 0:o(),"onCheck")};return e.jsx(u_s,{scope:t,...j,children:bAt(u)?u(j):r})}u1(vAt,"RadioProvider");var h_s="RadioTrigger",m_s=k.forwardRef(u1(function({__scopeRadio:t,onClick:n,...r},a){const{checked:i,disabled:l,value:o,setControl:c,onCheck:d,hasConsumerStoppedPropagationRef:u,onUserInteraction:h,isFormControl:m,bubbleInput:p}=Q3e(h_s,t),g=Ao(a,c);return e.jsx(hi.button,{type:"button",role:"radio","aria-checked":i,"data-state":fGe(i),"data-disabled":l?"":void 0,disabled:l,value:o,...r,ref:g,onClick:ga(n,x=>{i||(h(),d()),p&&m&&(u.current=x.isPropagationStopped(),u.current||x.stopPropagation())})})},"RadioTrigger")),f_s="RadioIndicator",p_s=k.forwardRef(u1(function(t,n){const{__scopeRadio:r,forceMount:a,...i}=t,l=Q3e(f_s,r);return e.jsx(cx,{present:a||l.checked,children:e.jsx(hi.span,{"data-state":fGe(l.checked),"data-disabled":l.disabled?"":void 0,...i,ref:n})})},"RadioIndicator")),g_s="RadioBubbleInput",x_s=k.forwardRef(u1(function({__scopeRadio:t,onClick:n,...r},a){const{control:i,checked:l,required:o,disabled:c,name:d,value:u,form:h,bubbleInput:m,setBubbleInput:p,hasConsumerStoppedPropagationRef:g,userInteractionCount:x}=Q3e(g_s,t),y=Ao(a,p),v=Dq(i),_=k.useRef(!1),j=k.useRef(l),C=k.useRef(x);k.useEffect(()=>{const M=m;if(!M)return;const I=window.HTMLInputElement.prototype,R=Object.getOwnPropertyDescriptor(I,"checked").set,O=x!==C.current;C.current=x;const B=j.current!==l;j.current=l;const U=!(O&&g.current);if(B&&R){_.current=!O;const G=new Event("click",{bubbles:U});R.call(M,l),M.dispatchEvent(G),_.current=!1}},[m,l,g,x]);const A=k.useRef(l);return e.jsx(hi.input,{type:"radio","aria-hidden":!0,defaultChecked:A.current,required:o,disabled:c,name:d,value:u,form:h,...r,tabIndex:-1,ref:y,onClick:ga(n,M=>{_.current&&M.stopPropagation()}),style:{...r.style,...v,position:"absolute",pointerEvents:"none",opacity:0,margin:0,transform:"translateX(-100%)"}})},"RadioBubbleInput"));function bAt(s){return typeof s=="function"}u1(bAt,"isFunction");function fGe(s){return s?"checked":"unchecked"}u1(fGe,"getState");var y_s=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],pGe="RadioGroup",[v_s,RQn]=qm(pGe,[YM,yAt]),_At=YM(),J3e=yAt(),[b_s,__s]=v_s(pGe),wAt=k.forwardRef(u1(function(t,n){const{__scopeRadioGroup:r,name:a,form:i,defaultValue:l,value:o,required:c=!1,disabled:d=!1,orientation:u,dir:h,loop:m=!0,onValueChange:p,...g}=t,x=_At(r),y=e4(h),[v,_]=ox({prop:o,defaultProp:l??null,onChange:p,caller:pGe}),[j,C]=k.useState(null),A=Ao(n,C),M=k.useRef(v);return k.useEffect(()=>{const I=i?j==null?void 0:j.ownerDocument.getElementById(i):j==null?void 0:j.closest("form");if(I instanceof HTMLFormElement){const P=u1(()=>_(M.current),"reset");return I.addEventListener("reset",P),()=>I.removeEventListener("reset",P)}},[j,i,_]),e.jsx(b_s,{scope:r,name:a,form:i,required:c,disabled:d,value:v,onValueChange:_,children:e.jsx(E3e,{asChild:!0,...x,orientation:u,dir:y,loop:m,children:e.jsx(hi.div,{role:"radiogroup","aria-required":c,"aria-orientation":u,"data-disabled":d?"":void 0,dir:y,...g,ref:A})})})},"RadioGroup")),w_s="RadioGroupItemProvider",j_s="RadioGroupItemTrigger";function jAt(s){const{__scopeRadioGroup:t,value:n,disabled:r,children:a,internal_do_not_use_render:i}=s,l=__s(w_s,t),o=J3e(t),c=l.disabled||r;return e.jsx(vAt,{...o,checked:l.value===n,disabled:c,required:l.required,name:l.name,form:l.form,value:n,onCheck:()=>l.onValueChange(n),internal_do_not_use_render:i,children:a})}u1(jAt,"RadioGroupItemProvider");var N_s=k.forwardRef(u1(function(t,n){const{__scopeRadioGroup:r,...a}=t,i=_At(r),l=J3e(r),{checked:o,disabled:c}=Q3e(j_s,l.__scopeRadio),d=k.useRef(null),u=Ao(n,d),h=k.useRef(!1);return k.useEffect(()=>{const m=u1(g=>{y_s.includes(g.key)&&(h.current=!0)},"handleKeyDown"),p=u1(()=>h.current=!1,"handleKeyUp");return document.addEventListener("keydown",m),document.addEventListener("keyup",p),()=>{document.removeEventListener("keydown",m),document.removeEventListener("keyup",p)}},[]),e.jsx(T3e,{asChild:!0,...i,focusable:!c,active:o,children:e.jsx(m_s,{...l,...a,ref:u,onKeyDown:ga(a.onKeyDown,m=>{m.key==="Enter"&&m.preventDefault()}),onFocus:ga(a.onFocus,()=>{var m;h.current&&((m=d.current)==null||m.click())})})})},"RadioGroupItemTrigger")),NAt=k.forwardRef(u1(function(t,n){const{__scopeRadioGroup:r,value:a,disabled:i,...l}=t;return e.jsx(jAt,{__scopeRadioGroup:r,value:a,disabled:i,internal_do_not_use_render:({isFormControl:o})=>e.jsxs(e.Fragment,{children:[e.jsx(N_s,{...l,ref:n,__scopeRadioGroup:r}),o&&e.jsx(k_s,{__scopeRadioGroup:r})]})})},"RadioGroupItem")),k_s=k.forwardRef(u1(function(t,n){const{__scopeRadioGroup:r,...a}=t,i=J3e(r);return e.jsx(x_s,{...i,...a,ref:n})},"RadioGroupItemBubbleInput")),S_s=k.forwardRef(u1(function(t,n){const{__scopeRadioGroup:r,...a}=t,i=J3e(r);return e.jsx(p_s,{...i,...a,ref:n})},"RadioGroupIndicator"));const m_=k.forwardRef(({className:s,...t},n)=>e.jsx(wAt,{className:Ot("grid gap-2",s),...t,ref:n}));m_.displayName=wAt.displayName;const Yh=k.forwardRef(({className:s,...t},n)=>e.jsx(NAt,{ref:n,className:Ot("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(S_s,{className:"flex items-center justify-center",children:e.jsx(rx,{className:"h-2.5 w-2.5 fill-current text-current"})})}));Yh.displayName=NAt.displayName;const C_s=({brief:s,open:t,onClose:n,onDismiss:r})=>{const{user:a}=ks(),[i,l]=k.useState({}),[o,c]=k.useState({}),[d,u]=k.useState([]);k.useEffect(()=>{t&&a&&s.polls.length>0&&h()},[t,a,s.polls]);const h=async()=>{if(!a)return;const y=s.polls.map(_=>_.id),{data:v}=await V.from("levelup_brief_poll_responses").select("poll_id, option_id").eq("user_id",a.id).in("poll_id",y);if(v){const _={};v.forEach(j=>{_[j.poll_id]||(_[j.poll_id]=[]),_[j.poll_id].push(j.option_id)}),c(_)}},m=(y,v)=>{l(_=>({..._,[y]:v}))},p=(y,v,_)=>{l(j=>{const C=j[y]||[];return _?{...j,[y]:[...C,v]}:{...j,[y]:C.filter(A=>A!==v)}})},g=async y=>{if(!a)return;const v=i[y];if(!v||Array.isArray(v)&&v.length===0){ae.error("Please select an option");return}u(_=>[..._,y]);try{await V.from("levelup_brief_poll_responses").delete().eq("poll_id",y).eq("user_id",a.id);const _=Array.isArray(v)?v:[v],j=_.map(A=>({poll_id:y,option_id:A,user_id:a.id})),{error:C}=await V.from("levelup_brief_poll_responses").insert(j);if(C)throw C;c(A=>({...A,[y]:_})),ae.success("Response submitted!")}catch(_){console.error("Error submitting poll response:",_),ae.error("Failed to submit response")}finally{u(_=>_.filter(j=>j!==y))}},x=y=>(y.includes("mediadelivery.net")||y.includes("bunny"),y);return e.jsx(zs,{open:t,onOpenChange:y=>!y&&n(),children:e.jsxs(Rs,{className:"max-w-2xl max-h-[90vh] p-0 overflow-hidden [&>button]:hidden",children:[e.jsxs("div",{className:"bg-gradient-to-r from-primary to-primary/80 p-4 pr-12 text-primary-foreground relative",children:[e.jsx("button",{onClick:n,className:"absolute top-3 right-3 p-1.5 rounded-full bg-white/30 hover:bg-white/50 transition-colors","aria-label":"Close",children:e.jsx(mr,{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(xm,{className:"h-6 w-6"})}),e.jsxs("div",{children:[e.jsx(qe,{variant:"secondary",className:"mb-1 bg-white/20 text-white border-0",children:"The LevelUp Brief"}),e.jsx($s,{className:"text-xl font-bold text-white",children:s.brief.title})]})]})]}),e.jsx(Eo,{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:x(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(y=>e.jsxs($,{variant:"outline",size:"sm",onClick:()=>window.open(y.url,"_blank"),className:"gap-2",children:[e.jsx(Ir,{className:"h-4 w-4"}),y.title]},y.id))})]}),s.polls.map(y=>{var j,C;const v=((j=o[y.id])==null?void 0:j.length)>0,_=d.includes(y.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:y.question}),v&&e.jsxs(qe,{variant:"secondary",className:"gap-1",children:[e.jsx(Gr,{className:"h-3 w-3"}),"Responded"]})]}),y.poll_type==="single"?e.jsx(m_,{value:i[y.id]||((C=o[y.id])==null?void 0:C[0])||"",onValueChange:A=>m(y.id,A),className:"space-y-2",children:y.options.map(A=>e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Yh,{value:A.id,id:A.id}),e.jsx(re,{htmlFor:A.id,className:"cursor-pointer",children:A.option_text})]},A.id))}):e.jsx("div",{className:"space-y-2",children:y.options.map(A=>{const I=(i[y.id]||o[y.id]||[]).includes(A.id);return e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Li,{id:A.id,checked:I,onCheckedChange:P=>p(y.id,A.id,P)}),e.jsx(re,{htmlFor:A.id,className:"cursor-pointer",children:A.option_text})]},A.id)})}),e.jsx($,{size:"sm",onClick:()=>g(y.id),disabled:_,children:_?"Submitting...":v?"Update Response":"Submit"})]},y.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($,{onClick:n,className:"w-full max-w-xs",children:"Got it!"}),e.jsx($,{variant:"ghost",size:"sm",onClick:r,children:"Don't show again"})]})]})})},A_s=()=>{const{user:s}=ks(),[t,n]=k.useState(null),[r,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:g,error:x}=await V.from("levelup_briefs").select("*").eq("is_published",!0).lte("publish_date",new Date().toISOString()).order("publish_date",{ascending:!1}).limit(1).single();if(x||!g){l(!1);return}const{data:y}=await V.from("levelup_brief_views").select("*").eq("brief_id",g.id).eq("user_id",s.id).maybeSingle(),[v,_]=await Promise.all([V.from("levelup_brief_links").select("*").eq("brief_id",g.id).order("sort_order"),V.from("levelup_brief_polls").select("*").eq("brief_id",g.id).order("sort_order")]),j=[];if(_.data)for(const P of _.data){const{data:R}=await V.from("levelup_brief_poll_options").select("*").eq("poll_id",P.id).order("sort_order");j.push({...P,options:R||[]})}const C={brief:g,links:v.data||[],polls:j};n(C);const A=!!y,M=(y==null?void 0:y.dismissed_at)!=null,I=localStorage.getItem(`brief-dismissed-${g.id}`)==="true";if(M||I)c(!1),a(!1);else if(!A)a(!0),c(!0);else if(g.show_frequency==="every_login")a(!0),c(!0);else if(g.show_frequency==="daily"){const P=new Date(y.viewed_at);(new Date().getTime()-P.getTime())/(1e3*60*60)>=24&&(a(!0),c(!0))}else c(!1)}catch(g){console.error("Error fetching brief:",g)}finally{l(!1)}},[s]);k.useEffect(()=>{d()},[d]);const u=async()=>{if(!(!s||!t))try{const{data:g}=await V.from("levelup_brief_views").select("id").eq("brief_id",t.brief.id).eq("user_id",s.id).maybeSingle();g?await V.from("levelup_brief_views").update({viewed_at:new Date().toISOString()}).eq("id",g.id):await V.from("levelup_brief_views").insert({brief_id:t.brief.id,user_id:s.id})}catch(g){console.error("Error marking brief as viewed:",g)}};return{currentBrief:t,shouldShowPopup:r,hasUnseenBrief:o,loading:i,openBrief:()=>{a(!0)},closeBrief:()=>{a(!1),u()},dismissBrief:async()=>{if(!(!s||!t)){a(!1),c(!1);try{const{data:g,error:x}=await V.from("levelup_brief_views").select("id").eq("brief_id",t.brief.id).eq("user_id",s.id).maybeSingle();if(x&&console.error("Error checking existing brief view:",x),g){const{error:y}=await V.from("levelup_brief_views").update({dismissed_at:new Date().toISOString()}).eq("id",g.id).eq("user_id",s.id);y&&console.error("Error updating brief dismiss:",y)}else{const{error:y}=await V.from("levelup_brief_views").insert({brief_id:t.brief.id,user_id:s.id,dismissed_at:new Date().toISOString()});y&&console.error("Error inserting brief dismiss:",y)}localStorage.setItem(`brief-dismissed-${t.brief.id}`,"true")}catch(g){console.error("Error dismissing brief:",g),t&&localStorage.setItem(`brief-dismissed-${t.brief.id}`,"true")}}},refetch:d}};function E_s(){const[s,t]=k.useState(!1),[n,r]=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 h=/iPhone|iPad|iPod/i.test(navigator.userAgent);r(h),t(!0);const m=p=>{p.preventDefault(),i(p)};return window.addEventListener("beforeinstallprompt",m),()=>{window.removeEventListener("beforeinstallprompt",m)}},[]);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(ji,{className:"h-5 w-5"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium text-sm",children:"Add LevelUp to your home screen"}),n?e.jsxs("p",{className:"text-xs opacity-80 flex items-center gap-1",children:["Tap ",e.jsx(XK,{className:"h-3 w-3 inline"}),' then "Add to Home Screen"']}):e.jsx("p",{className:"text-xs opacity-80",children:"Quick access anytime"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[!n&&a&&e.jsx($,{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(mr,{className:"h-4 w-4"})})]})]})}):null}const T_s=({children:s,onRefresh:t})=>{const[n,r]=k.useState(!1),[a,i]=k.useState(0),[l,o]=k.useState(!1),c=k.useRef(null),d=k.useRef(0),u=ls(),h=80,m=120,p=k.useCallback(_=>{const j=c.current;j&&j.scrollTop<=0&&(d.current=_.touches[0].clientY,r(!0))},[]),g=k.useCallback(_=>{if(!n||l)return;const j=c.current;if(!j||j.scrollTop>0){r(!1),i(0);return}const A=_.touches[0].clientY-d.current;if(A>0){const I=Math.min(A*.5,m);i(I),I>10&&_.preventDefault()}},[n,l]),x=k.useCallback(async()=>{if(n)if(r(!1),a>=h&&!l){o(!0),i(h);try{t?await t():await u.invalidateQueries()}catch(_){console.error("Refresh failed:",_)}finally{o(!1),i(0)}}else i(0)},[n,a,l,t,u]),y=Math.min(a/h,1),v=y*180;return e.jsxs("div",{ref:c,className:"h-full overflow-auto",onTouchStart:p,onTouchMove:g,onTouchEnd:x,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:y},children:e.jsx("div",{className:`p-2 rounded-full bg-primary/10 ${l?"animate-spin":""}`,style:{transform:l?void 0:`rotate(${v}deg)`,transition:l?void 0:"transform 0.1s ease-out"},children:e.jsx(yo,{className:"h-5 w-5 text-primary"})})}),e.jsx("div",{style:{transform:a>0?`translateY(${Math.max(0,a-60)}px)`:void 0,transition:n?void 0:"transform 0.2s ease-out"},children:s})]})},kAt=()=>{const{user:s}=ks(),[t,n]=k.useState(!1),[r,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:p}=await V.from("membership_reviews").select("id").eq("user_id",s.id).maybeSingle();if(p){a(!0),n(!1),c(!1);return}const{data:g}=await V.from("profiles").select("login_count").eq("id",s.id).single(),x=(g==null?void 0:g.login_count)||0;l(x);const y=sessionStorage.getItem("review-prompt-dismissed");n(x>=4&&!y)}catch(p){console.error("Error checking review eligibility:",p)}finally{c(!1)}})()},[s]);const d=k.useCallback(()=>{sessionStorage.setItem("review-prompt-dismissed","true"),n(!1)},[]),u=k.useCallback(async(m,p)=>{if(!s)return{success:!1,error:"Not authenticated"};try{const{error:g}=await V.from("membership_reviews").insert({user_id:s.id,rating:m,review_text:p});if(g)throw g;return a(!0),n(!1),{success:!0,pointsAwarded:25}}catch(g){return console.error("Error submitting review:",g),{success:!1,error:g.message}}},[s]),h=k.useCallback(async()=>{if(s)try{await V.from("membership_reviews").update({posted_to_google:!0}).eq("user_id",s.id)}catch(m){console.error("Error updating Google review status:",m)}},[s]);return{shouldShowPrompt:t,hasSubmittedReview:r,loginCount:i,isLoading:o,dismissPrompt:d,submitReview:u,markPostedToGoogle:h}},M_s="https://search.google.com/local/writereview?placeid=ChIJM73ERQD1QogRPxupMFObuck&source=g.page.m.ia._&laa=nmx-review-solicitation-ia2",P_s=()=>{const{shouldShowPrompt:s,isLoading:t,dismissPrompt:n,submitReview:r,markPostedToGoogle:a}=kAt(),[i,l]=k.useState(!1),[o,c]=k.useState("review"),[d,u]=k.useState(0),[h,m]=k.useState(0),[p,g]=k.useState(""),[x,y]=k.useState(!1),[v,_]=k.useState(!1);if(t||!s&&!v)return null;const j=async()=>{if(d===0){Ma({title:"Please select a rating",variant:"destructive"});return}y(!0);const M=await r(d,p);y(!1),M.success?(_(!0),Ma({title:"Thank you for your feedback!",description:"Your review helps us improve."}),c("google")):Ma({title:"Error submitting review",description:M.error,variant:"destructive"})},C=async M=>{M&&(await navigator.clipboard.writeText(p||`${d} star rating for LevelUp!`),Ma({title:"Review copied!",description:"Paste it on Google Reviews."}),await a(),window.open(M_s,"_blank")),l(!1),n()},A=()=>{l(!1),n()};return e.jsxs(e.Fragment,{children:[e.jsxs("button",{onClick:()=>l(!0),className:"fixed bottom-20 left-1/2 -translate-x-1/2 z-40 flex items-center gap-2 rounded-full bg-primary/90 px-3 py-2 text-xs text-primary-foreground shadow-lg backdrop-blur-sm transition-all hover:bg-primary hover:scale-105 md:bottom-6",children:[e.jsx(ri,{className:"h-3.5 w-3.5 fill-current"}),e.jsx("span",{className:"hidden sm:inline",children:"Leave a Review"})]}),e.jsx(zs,{open:i,onOpenChange:A,children:e.jsx(Rs,{className:"sm:max-w-md",children:o==="review"?e.jsxs(e.Fragment,{children:[e.jsxs(Vs,{children:[e.jsx($s,{className:"text-center",children:"How are you enjoying LevelUp?"}),e.jsx(Cr,{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(M=>e.jsx("button",{type:"button",onClick:()=>u(M),onMouseEnter:()=>m(M),onMouseLeave:()=>m(0),className:"p-1 transition-transform hover:scale-110",children:e.jsx(ri,{className:Ot("h-8 w-8 transition-colors",(h||d)>=M?"fill-yellow-400 text-yellow-400":"text-muted-foreground")})},M))}),e.jsx(Ls,{placeholder:"Tell us about your experience (optional)",value:p,onChange:M=>g(M.target.value),rows:4,className:"resize-none"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{variant:"outline",onClick:A,className:"flex-1",children:"Maybe Later"}),e.jsx($,{onClick:j,disabled:x||d===0,className:"flex-1",children:x?"Submitting...":"Submit Review"})]})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs(Vs,{children:[e.jsx($s,{className:"text-center",children:"🎉 Thank you!"}),e.jsx(Cr,{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($,{variant:"outline",onClick:()=>C(!1),className:"flex-1",children:"No Thanks"}),e.jsx($,{onClick:()=>C(!0),className:"flex-1",children:"Yes, Open Google"})]})]})]})})})]})};function I_s(s){const t="=".repeat((4-s.length%4)%4),n=(s+t).replace(/-/g,"+").replace(/_/g,"/"),r=window.atob(n),a=new Uint8Array(r.length);for(let i=0;i{if(!h){l(!1);return}(async()=>{try{const x="vapid_public_key";let y=localStorage.getItem(x);if(!y){const{data:j,error:C}=await V.functions.invoke("get-vapid-public-key",{body:{}});if(C)throw C;if(y=(j==null?void 0:j.vapidPublicKey)??null,!y)throw new Error("Missing VAPID public key");localStorage.setItem(x,y)}u(y);const v=await navigator.serviceWorker.register("/push-sw.js",{scope:"/push-notifications/"});c(v),n(Notification.permission);const _=await v.pushManager.getSubscription();a(!!_)}catch(x){console.error("Error initializing push notifications:",x)}finally{l(!1)}})()},[h]);const m=k.useCallback(async()=>{if(!h||!o||!s)return console.error("Push notifications not supported or user not logged in"),!1;if(!d)return ae.error("Push notifications are not ready yet. Please try again in a moment."),!1;try{l(!0);const g=await o.pushManager.getSubscription();if(g){try{await g.unsubscribe()}catch(C){console.warn("Failed to unsubscribe existing push subscription:",C)}const{error:j}=await V.from("push_subscriptions").delete().eq("user_id",s.id);j&&console.warn("Failed to cleanup push_subscriptions rows:",j)}if(Notification.permission!=="granted"){const j=await Notification.requestPermission();if(n(j),j!=="granted")return j==="denied"?ae.error("Notifications blocked. Please enable them in your browser settings (click the lock icon in the address bar)."):ae.error("Notification permission was dismissed. Please try again."),!1}const x=I_s(d);let y;try{y=await o.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:x})}catch(j){console.error("PushManager.subscribe() failed:",j);const C=(j==null?void 0:j.message)||String(j);return C.includes("permission")?ae.error("Push permission denied. Check your browser notification settings."):C.includes("key")||C.includes("VAPID")?ae.error("Push configuration error. Please contact support."):C.includes("AbortError")?ae.error("Push subscription was cancelled. Please try again."):ae.error(`Failed to subscribe: ${C}`),!1}const v=y.toJSON(),{error:_}=await V.from("push_subscriptions").upsert({user_id:s.id,endpoint:v.endpoint,p256dh_key:v.keys.p256dh,auth_key:v.keys.auth},{onConflict:"user_id,endpoint"});if(_)throw console.error("Error saving subscription:",_),ae.error("Failed to save notification preferences. Please try again."),_;return a(!0),ae.success("Push notifications enabled!"),!0}catch(g){if(console.error("Error subscribing to push notifications:",g),!(g instanceof Error&&g.message.includes("toast"))){const x=g instanceof Error?g.message:"Unknown error";ae.error("Failed to enable push notifications: "+x)}return!1}finally{l(!1)}},[h,o,s,d]),p=k.useCallback(async()=>{if(!o||!s)return!1;try{l(!0);const g=await o.pushManager.getSubscription();return g&&await g.unsubscribe(),await V.from("push_subscriptions").delete().eq("user_id",s.id),a(!1),ae.success("Push notifications disabled"),!0}catch(g){console.error("Error unsubscribing:",g);const x=g instanceof Error?g.message:"Unknown error";return ae.error("Failed to disable push notifications: "+x),!1}finally{l(!1)}},[o,s]);return{isSupported:h,permission:t,isSubscribed:r,isLoading:i,vapidPublicKey:d,subscribe:m,unsubscribe:p}}const kIe="push_notification_prompt_dismissed",L_s=["/dashboard","/admin"],R_s=()=>{const{user:s}=ks(),{isSupported:t,isSubscribed:n,isLoading:r,subscribe:a}=SAt(),i=Tu(),[l,o]=k.useState(!1),[c,d]=k.useState(!1),u=L_s.some(p=>i.pathname===p||i.pathname.startsWith(`${p}/`));k.useEffect(()=>{if(u){o(!1);return}if(!s||!t||n||r||localStorage.getItem(`${kIe}_${s.id}`))return;const g=setTimeout(()=>{o(!0)},2e3);return()=>clearTimeout(g)},[s,t,n,r,u]);const h=async()=>{d(!0);const p=await a();d(!1),p&&(s&&localStorage.setItem(`${kIe}_${s.id}`,"true"),o(!1))},m=()=>{s&&localStorage.setItem(`${kIe}_${s.id}`,"true"),o(!1)};return!t||n||u?null:e.jsx(zs,{open:l,onOpenChange:p=>!p&&m(),children:e.jsxs(Rs,{className:"sm:max-w-md",children:[e.jsxs(Vs,{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(Fx,{className:"h-6 w-6 text-primary"})}),e.jsx($s,{className:"text-center",children:"Stay in the Loop!"}),e.jsx(Cr,{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($,{onClick:h,disabled:c,className:"w-full",children:c?"Enabling...":"Enable Notifications"}),e.jsx($,{variant:"ghost",onClick:m,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."})]})})},Xot=s=>{let t;const n=new Set,r=(d,u)=>{const h=typeof d=="function"?d(t):d;if(!Object.is(h,t)){const m=t;t=u??(typeof h!="object"||h===null)?h:Object.assign({},t,h),n.forEach(p=>p(t,m))}},a=()=>t,o={setState:r,getState:a,getInitialState:()=>c,subscribe:d=>(n.add(d),()=>n.delete(d))},c=t=s(r,a,o);return o},D_s=s=>s?Xot(s):Xot,O_s=s=>s;function F_s(s,t=O_s){const n=zt.useSyncExternalStore(s.subscribe,zt.useCallback(()=>t(s.getState()),[s,t]),zt.useCallback(()=>t(s.getInitialState()),[s,t]));return zt.useDebugValue(n),n}const Qot=s=>{const t=D_s(s),n=r=>F_s(t,r);return Object.assign(n,t),n},z_s=s=>s?Qot(s):Qot;function B_s(s,t){let n;try{n=s()}catch{return}return{getItem:a=>{var i;const l=c=>c===null?null:JSON.parse(c,void 0),o=(i=n.getItem(a))!=null?i:null;return o instanceof Promise?o.then(l):l(o)},setItem:(a,i)=>n.setItem(a,JSON.stringify(i,void 0)),removeItem:a=>n.removeItem(a)}}const b7e=s=>t=>{try{const n=s(t);return n instanceof Promise?n:{then(r){return b7e(r)(n)},catch(r){return this}}}catch(n){return{then(r){return this},catch(r){return b7e(r)(n)}}}},$_s=(s,t)=>(n,r,a)=>{let i={storage:B_s(()=>window.localStorage),partialize:y=>y,version:0,merge:(y,v)=>({...v,...y}),...t},l=!1,o=0;const c=new Set,d=new Set;let u=i.storage;if(!u)return s((...y)=>{console.warn(`[zustand persist middleware] Unable to update item '${i.name}', the given storage is currently unavailable.`),n(...y)},r,a);const h=()=>{const y=i.partialize({...r()});return u.setItem(i.name,{state:y,version:i.version})},m=a.setState;a.setState=(y,v)=>(m(y,v),h());const p=s((...y)=>(n(...y),h()),r,a);a.getInitialState=()=>p;let g;const x=()=>{var y,v;if(!u)return;const _=++o;l=!1,c.forEach(C=>{var A;return C((A=r())!=null?A:p)});const j=((v=i.onRehydrateStorage)==null?void 0:v.call(i,(y=r())!=null?y:p))||void 0;return b7e(u.getItem.bind(u))(i.name).then(C=>{if(C)if(typeof C.version=="number"&&C.version!==i.version){if(i.migrate){const A=i.migrate(C.state,C.version);return A instanceof Promise?A.then(M=>[!0,M]):[!0,A]}console.error("State loaded from storage couldn't be migrated since no migrate function was provided")}else return[!1,C.state];return[!1,void 0]}).then(C=>{var A;if(_!==o)return;const[M,I]=C;if(g=i.merge(I,(A=r())!=null?A:p),n(g,!0),M)return h()}).then(()=>{_===o&&(j==null||j(r(),void 0),g=r(),l=!0,d.forEach(C=>C(g)))}).catch(C=>{_===o&&(j==null||j(void 0,C))})};return a.persist={setOptions:y=>{i={...i,...y},y.storage&&(u=y.storage)},clearStorage:()=>{++o,u==null||u.removeItem(i.name)},getOptions:()=>i,rehydrate:()=>x(),hasHydrated:()=>l,onHydrate:y=>(c.add(y),()=>{c.delete(y)}),onFinishHydration:y=>(d.add(y),()=>{d.delete(y)})},i.skipHydration||x(),g||p},U_s=$_s,eAe=z_s()(U_s((s,t)=>({cartItems:[],addToCart:(n,r,a=1,i)=>{s(l=>{const o=l.cartItems.findIndex(c=>{var d;return c.product.id===n.id&&((d=c.variant)==null?void 0:d.id)===(r==null?void 0:r.id)});if(o>=0){const c=[...l.cartItems];return c[o].quantity+=a,i&&(c[o].artworkUrl=i),{cartItems:c}}return{cartItems:[...l.cartItems,{product:n,variant:r,quantity:a,artworkUrl:i}]}})},removeFromCart:(n,r)=>{s(a=>({cartItems:a.cartItems.filter(i=>{var l;return!(i.product.id===n&&((l=i.variant)==null?void 0:l.id)===r)})}))},updateQuantity:(n,r,a)=>{s(i=>({cartItems:i.cartItems.map(l=>{var o;return l.product.id===n&&((o=l.variant)==null?void 0:o.id)===r?{...l,quantity:Math.max(1,a)}:l})}))},updateArtwork:(n,r,a)=>{s(i=>({cartItems:i.cartItems.map(l=>{var o;return l.product.id===n&&((o=l.variant)==null?void 0:o.id)===r?{...l,artworkUrl:a}:l})}))},clearCart:()=>s({cartItems:[]}),getItemPrice:n=>{const r=Number(n.product.base_price),a=n.variant?Number(n.variant.price_adjustment):0;return r+a},getSubtotal:()=>{const{cartItems:n,getItemPrice:r}=t();return n.reduce((a,i)=>a+r(i)*i.quantity,0)},getShippingTotal:()=>{const{cartItems:n}=t();return n.reduce((r,a)=>r+Number(a.product.shipping_fee)*a.quantity,0)},getTotal:()=>{const{getSubtotal:n,getShippingTotal:r}=t();return n()+r()}}),{name:"marketplace-cart",partialize:s=>({cartItems:s.cartItems})}));function q_s({activeCategory:s,currentCategory:t,onSelect:n,onHover:r,badgeCounts:a,categories:i=Z3e}){return e.jsx("nav",{"aria-label":"Primary",className:"flex flex-col gap-1 p-2",children:i.map(l=>{const o=l.icon,c=s===l.id,d=t===l.id,u=(a==null?void 0:a[l.id])??0,h=`hsl(var(--${l.accent}))`,m=c||d;return e.jsxs("button",{type:"button",onClick:()=>n(l.id),onMouseEnter:()=>r==null?void 0:r(l.id),"aria-expanded":l.route?void 0:c,"aria-controls":l.route?void 0:"primary-nav-flyout","aria-current":d?"page":void 0,style:{color:m?h:void 0,backgroundColor:m?`hsl(var(--${l.accent}) / 0.12)`:void 0},className:Ot("group relative flex flex-col items-center gap-1 rounded-xl px-1 py-2.5 text-[11px] font-medium transition-colors","text-sidebar-foreground/70 hover:bg-sidebar-accent/10","focus:outline-none focus-visible:ring-2 focus-visible:ring-primary"),children:[d&&e.jsx("span",{className:"absolute left-0 top-1/2 h-6 w-1 -translate-y-1/2 rounded-r",style:{backgroundColor:h}}),e.jsxs("span",{className:"relative",children:[e.jsx(o,{className:"h-5 w-5 transition-colors",style:{color:h}}),u>0&&e.jsx("span",{className:"absolute -right-1.5 -top-1 flex h-4 min-w-4 items-center justify-center rounded-full px-1 text-[9px] font-bold text-primary-foreground",style:{backgroundColor:h},children:u>9?"9+":u})]}),e.jsx("span",{className:"leading-tight",children:l.label})]},l.id)})})}function V_s({category:s,top:t,left:n,onClose:r,onNavigate:a,isFavorite:i,favorites:l,onToggleFavorite:o,isCurrent:c,badgeCounts:d}){const u=k.useRef(null);k.useEffect(()=>{const m=g=>{g.key==="Escape"&&r()},p=g=>{var y;if(!u.current)return;const x=g.target;!u.current.contains(x)&&!((y=x==null?void 0:x.closest)!=null&&y.call(x,"[data-nav-rail]"))&&r()};return document.addEventListener("keydown",m),document.addEventListener("mousedown",p),()=>{document.removeEventListener("keydown",m),document.removeEventListener("mousedown",p)}},[r]);const h=m=>{const p=m.icon,g=m.badgeKey?(d==null?void 0:d[m.badgeKey])??0:0;return e.jsxs("div",{className:Ot("group flex items-start gap-3 rounded-lg p-2 transition-colors hover:bg-muted",c(m)&&"bg-muted"),children:[e.jsxs("button",{type:"button",onClick:()=>a(m),className:"flex flex-1 items-start gap-3 text-left focus:outline-none focus-visible:ring-2 focus-visible:ring-primary rounded-md",children:[e.jsx("span",{className:"mt-0.5 flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-primary/10 text-primary",children:e.jsx(p,{className:"h-4 w-4"})}),e.jsxs("span",{className:"min-w-0",children:[e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"text-sm font-medium text-foreground",children:m.label}),m.badge==="new"&&e.jsx("span",{className:"rounded bg-primary px-1 py-px text-[9px] font-bold uppercase tracking-wide text-primary-foreground",children:"New"}),m.badge==="beta"&&e.jsx("span",{className:"rounded border border-amber-500 bg-amber-500/10 px-1 py-px text-[9px] font-bold uppercase tracking-wide text-amber-600 dark:text-amber-400",children:"Beta"}),m.locked&&e.jsx(fu,{className:"h-3 w-3 text-muted-foreground","aria-label":"Upgrade required"}),g>0&&e.jsx("span",{className:"flex h-4 min-w-4 items-center justify-center rounded-full bg-muted-foreground/15 px-1 text-[10px] font-medium text-muted-foreground",children:g>9?"9+":g})]}),m.description&&e.jsx("span",{className:"mt-0.5 block text-xs leading-snug text-muted-foreground line-clamp-2",children:m.description})]})]}),e.jsx("button",{type:"button","aria-label":i(m)?`Remove ${m.label} from favorites`:`Add ${m.label} to favorites`,onClick:x=>{x.stopPropagation(),o(m)},className:Ot("mt-1 rounded p-1 opacity-0 transition-opacity focus:outline-none focus-visible:ring-2 focus-visible:ring-primary group-hover:opacity-100",i(m)&&"opacity-100 text-primary",!i(m)&&"text-muted-foreground/60 hover:text-primary"),children:e.jsx(jy,{className:Ot("h-4 w-4",i(m)&&"fill-current")})})]},m.id)};return e.jsxs("div",{id:"primary-nav-flyout",ref:u,role:"dialog","aria-label":`${s.label} navigation`,style:{top:t,left:n,maxHeight:`calc(100vh - ${t+16}px)`},className:"fixed z-40 hidden w-[min(720px,calc(100vw-8rem))] animate-in fade-in-0 slide-in-from-left-2 duration-200 motion-reduce:animate-none overflow-hidden rounded-2xl border border-border bg-card shadow-2xl md:block",children:[e.jsx("div",{className:"flex items-center justify-between border-b border-border px-5 py-3",children:e.jsx("h2",{className:"text-sm font-semibold text-foreground",children:s.label})}),e.jsxs("div",{className:"max-h-[70vh] overflow-y-auto p-4",children:[l.length>0&&e.jsxs("section",{className:"mb-4",children:[e.jsxs("h3",{className:"mb-2 flex items-center gap-1.5 px-2 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground",children:[e.jsx(jy,{className:"h-3 w-3 fill-current text-primary"})," My Favorites"]}),e.jsx("div",{className:"grid grid-cols-1 gap-1 sm:grid-cols-2",children:l.map(h)})]}),s.sections.map(m=>e.jsxs("section",{className:"mb-4 last:mb-0",children:[e.jsx("h3",{className:"mb-2 px-2 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground",children:m.title}),e.jsx("div",{className:"grid grid-cols-1 gap-1 sm:grid-cols-2",children:m.items.map(h)})]},m.title)),s.sections.length===0&&e.jsx("p",{className:"px-2 py-6 text-sm text-muted-foreground",children:"Nothing here yet."})]})]})}function H_s({categories:s,railCategories:t=Z3e,currentCategory:n,onNavigate:r,onNavigateRoute:a,isCurrent:i,badgeCounts:l,isFavorite:o,onToggleFavorite:c}){const[d,u]=k.useState(n);return e.jsx("nav",{"aria-label":"Primary",className:"p-2",children:t.map(h=>{const m=h.icon;if(h.route)return e.jsxs("button",{type:"button",onClick:()=>a(h.route),className:Ot("flex w-full items-center gap-3 rounded-lg px-3 py-3 text-sm font-medium text-sidebar-foreground hover:bg-sidebar-accent",n===h.id&&"bg-sidebar-accent"),children:[e.jsx(m,{className:"h-4 w-4",style:{color:`hsl(var(--${h.accent}))`}}),h.label]},h.id);const p=s.find(x=>x.id===h.id),g=d===h.id;return e.jsxs("div",{children:[e.jsxs("button",{type:"button","aria-expanded":g,onClick:()=>u(g?null:h.id),className:Ot("flex w-full items-center gap-3 rounded-lg px-3 py-3 text-sm font-medium text-sidebar-foreground hover:bg-sidebar-accent",n===h.id&&"text-primary"),children:[e.jsx(m,{className:"h-4 w-4",style:{color:`hsl(var(--${h.accent}))`}}),h.label,e.jsx(Go,{className:Ot("ml-auto h-4 w-4 transition-transform",g&&"rotate-180")})]}),g&&p&&e.jsx("div",{className:"space-y-3 pb-3 pl-4 pr-1",children:p.sections.map(x=>e.jsxs("div",{children:[e.jsx("p",{className:"px-2 py-1 text-[11px] font-semibold uppercase tracking-wider text-muted-foreground",children:x.title}),x.items.map(y=>{const v=y.icon,_=y.badgeKey?(l==null?void 0:l[y.badgeKey])??0:0,j=(o==null?void 0:o(y))??!1;return e.jsxs("div",{className:Ot("flex w-full items-center gap-2 rounded-md pr-1 hover:bg-sidebar-accent",i(y)&&"bg-sidebar-accent"),children:[e.jsxs("button",{type:"button",onClick:()=>r(y),className:"flex flex-1 items-center gap-2 px-2 py-2 text-left text-sm text-sidebar-foreground",children:[e.jsx(v,{className:"h-4 w-4 shrink-0"}),e.jsx("span",{className:"truncate",children:y.label}),_>0&&e.jsx("span",{className:"ml-auto flex h-5 w-5 items-center justify-center rounded-full bg-muted text-xs text-muted-foreground",children:_>9?"9+":_})]}),c&&e.jsx("button",{type:"button","aria-label":j?`Remove ${y.label} from favorites`:`Add ${y.label} to favorites`,onClick:()=>c(y),className:Ot("rounded p-2",j?"text-primary":"text-muted-foreground/60"),children:e.jsx(jy,{className:Ot("h-4 w-4",j&&"fill-current")})})]},y.id)})]},x.title))})]},h.id)})})}function CAt(){const s=Jn(),t=Tu(),n=aAt(),r=k.useCallback(o=>rAt(o,n.ctx),[n.ctx]),a=k.useMemo(()=>{if(t.pathname.startsWith("/apps"))return"apps";if(t.pathname==="/dashboard")return"home";let o=null;for(const c of n.destinations){if(c.external)continue;const d=r(c);d!=="/"&&t.pathname.startsWith(d)&&(!o||d.length>o.len)&&(o={id:c.primaryCategory,len:d.length})}return(o==null?void 0:o.id)??null},[t.pathname,n.destinations,r]),i=k.useCallback(o=>!o.external&&t.pathname===r(o),[t.pathname,r]),l=k.useCallback(o=>{const c=r(o);if(o.external||o.openInNewTab){window.open(c,"_blank","noopener,noreferrer");return}s(c)},[s,r]);return{nav:n,navigate:s,currentCategory:a,isCurrent:i,go:l}}function G_s({communityUnreadCount:s=0,wishlistOpenCount:t=0,flyoutTop:n=64,flyoutLeft:r=80}){const{nav:a,navigate:i,currentCategory:l,isCurrent:o,go:c}=CAt(),[d,u]=k.useState(null),h=k.useRef(null),m=x=>{const y=Z3e.find(v=>v.id===x);if(y!=null&&y.route){u(null),i(y.route);return}u(v=>v===x?null:x)},p=d?a.categoryMap.get(d):void 0,g={more:s+t};return e.jsxs("div",{"data-nav-rail":!0,className:"flex h-full flex-col",onMouseLeave:()=>{h.current&&window.clearTimeout(h.current),h.current=window.setTimeout(()=>u(null),250)},onMouseEnter:()=>{h.current&&window.clearTimeout(h.current)},children:[e.jsx(q_s,{activeCategory:d,currentCategory:l,onSelect:m,categories:a.railCategories,badgeCounts:g}),p&&e.jsx(V_s,{category:p,top:n,left:r,onClose:()=>u(null),onNavigate:x=>{u(null),c(x)},isFavorite:a.isFavorite,favorites:a.favoritesFor(p.id),onToggleFavorite:x=>a.toggleFavorite(a.favoriteKey(x)),isCurrent:o,badgeCounts:{community:s,wishlist:t}})]})}function W_s({communityUnreadCount:s=0,wishlistOpenCount:t=0,onNavigated:n}){const{nav:r,navigate:a,currentCategory:i,isCurrent:l,go:o}=CAt();return e.jsx(H_s,{categories:r.categories,railCategories:r.railCategories,currentCategory:i,isCurrent:l,isFavorite:r.isFavorite,onToggleFavorite:c=>r.toggleFavorite(r.favoriteKey(c)),badgeCounts:{community:s,wishlist:t},onNavigate:c=>{o(c),n==null||n()},onNavigateRoute:c=>{a(c),n==null||n()}})}const Xs=({children:s,title:t})=>{var ve;const{user:n,signOut:r,isAdmin:a,isBrokerageManager:i,isCoach:l,brokerageId:o}=ks(),{isAssistant:c,actingAsAgent:d,hasPermission:u}=cee();I3e();const{isImpersonating:h}=C3e(),p=(c&&!!d?40:0)+(h?40:0),{avatarUrl:g}=xCt(n==null?void 0:n.id),{isTrial:x,isExpired:y,expiresAt:v}=jms(n==null?void 0:n.id),{isMarketplaceEnabled:_}=EHe(),{currentBrief:j,shouldShowPopup:C,hasUnseenBrief:A,openBrief:M,closeBrief:I,dismissBrief:P}=A_s(),{unreadCount:R}=Nms(),{openCount:O}=kms();gj();const U=eAe(he=>he.cartItems).reduce((he,Se)=>he+Se.quantity,0),{hasLeadSite:G}=Tg();Y3e(!G);const H=Jn(),Y=Tu(),[se,ee]=k.useState(null);k.useEffect(()=>{n!=null&&n.id&&V.from("profiles").select("name").eq("id",n.id).single().then(({data:he})=>{he!=null&&he.name&&ee(he.name)})},[n==null?void 0:n.id]);const oe=se||((ve=n==null?void 0:n.user_metadata)==null?void 0:ve.name)||(n==null?void 0:n.email)||"User",[me,Q]=k.useState(!1),te=he=>he.split(" ").map(Se=>Se[0]).join("").toUpperCase().slice(0,2),le=he=>Y.pathname===he,fe=()=>e.jsxs("div",{className:"flex h-full flex-col",children:[e.jsx("div",{className:"flex h-16 shrink-0 items-center justify-center border-b border-sidebar-border",children:e.jsx("button",{type:"button",onClick:()=>H("/dashboard"),"aria-label":"LevelUp home",children:e.jsx("img",{src:Zms,alt:"LevelUp",className:"h-8 w-auto"})})}),e.jsxs(Eo,{className:"flex-1 [&_[data-radix-scroll-area-scrollbar]]:w-1.5",children:[e.jsx(G_s,{communityUnreadCount:R,wishlistOpenCount:O,flyoutTop:p+64,flyoutLeft:80}),x&&!y&&e.jsx("div",{className:"p-2",children:e.jsxs("button",{type:"button",onClick:()=>H("/subscription"),className:"flex w-full flex-col items-center gap-1 rounded-xl border border-amber-500/30 bg-amber-500/10 px-1 py-2 text-[10px] font-semibold text-amber-600 dark:text-amber-400",children:[e.jsx(kn,{className:"h-4 w-4"}),"Upgrade"]})})]})]}),_e=({onNavigated:he})=>e.jsxs("div",{className:"flex h-full flex-col",children:[e.jsx("div",{className:"flex items-center gap-2 border-b border-sidebar-border p-3",children:e.jsx("img",{src:Yms,alt:"LevelUp",className:"h-8 w-auto"})}),e.jsxs(Eo,{className:"flex-1",children:[x&&!y&&e.jsx("div",{className:"p-2",children:e.jsx("button",{type:"button",onClick:()=>{H("/subscription"),he==null||he()},className:Ot("relative mb-1 w-full overflow-hidden rounded-md p-[1.5px]","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(kn,{className:"h-4 w-4 text-amber-500"}),e.jsx("span",{className:"flex-1 text-left",children:"Ready to Upgrade?"}),v&&e.jsxs("span",{className:"rounded border border-amber-500/30 bg-amber-500/15 px-1.5 py-0.5 text-[10px] font-bold uppercase tracking-wide text-amber-600 dark:text-amber-400",children:[Math.max(0,Math.ceil((new Date(v).getTime()-Date.now())/864e5)),"d left"]})]})})}),e.jsx(W_s,{communityUnreadCount:R,wishlistOpenCount:O,onNavigated:he})]}),e.jsxs("div",{className:"border-t border-sidebar-border p-3",children:[e.jsxs($,{variant:"ghost",size:"sm",className:Ot("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",le("/profile")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>{H("/profile"),he==null||he()},children:[e.jsx(el,{className:"h-4 w-4"}),"Profile"]}),e.jsxs($,{variant:"ghost",size:"sm",className:"w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",onClick:r,children:[e.jsx(q8,{className:"h-4 w-4"}),"Sign Out"]})]})]});return e.jsx(Sk,{children:e.jsxs("div",{className:"min-h-screen bg-background flex",children:[x&&y&&Y.pathname!=="/subscription"&&e.jsx(Qbs,{}),typeof document<"u"&&a1.createPortal(e.jsx("aside",{className:"hidden md:flex flex-col bg-card border-r border-border fixed left-0 z-30 !pointer-events-auto w-20",style:{top:`${p}px`,height:`calc(100vh - ${p}px)`},children:e.jsx(fe,{})}),document.body),e.jsxs("div",{className:"flex-1 flex flex-col overflow-hidden md:ml-20",style:{height:`calc(100vh - ${p}px)`,marginTop:`${p}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(D_,{open:me,onOpenChange:Q,children:[e.jsx(uee,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:"md:hidden",children:e.jsx(WT,{className:"h-5 w-5"})})}),e.jsx(Mb,{side:"left",className:"w-72 p-0 bg-card",children:e.jsx(_e,{onNavigated:()=>Q(!1)})})]}),e.jsx("div",{className:"flex-1 md:hidden",children:e.jsx("img",{src:Xms,alt:"LevelUp",className:"h-8 w-auto"})}),e.jsx("div",{className:"hidden md:flex flex-1 justify-center",children:e.jsx(Zot,{})}),e.jsxs("div",{className:"flex items-center gap-3 ml-auto",children:[x&&!y&&v&&e.jsx(Xbs,{expiresAt:v,className:"hidden lg:flex"}),e.jsx("div",{className:"md:hidden",children:e.jsx(Zot,{})}),j&&e.jsx(Jbs,{hasUnseenBrief:A,onClick:M}),_&&e.jsxs($,{variant:"ghost",size:"icon",className:"relative",onClick:()=>H("/marketplace/cart"),children:[e.jsx(ok,{className:"h-5 w-5"}),U>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:U>99?"99+":U})]}),e.jsx(bbs,{}),e.jsx(m7e,{}),e.jsxs("span",{className:"hidden sm:block text-sm font-medium text-foreground",children:["Hello, ",oe.split(" ")[0],"!"]}),e.jsxs(Au,{children:[e.jsx(Eu,{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(Wa,{className:"h-9 w-9 cursor-pointer hover:opacity-80 transition-opacity",children:[e.jsx(eo,{src:g||void 0}),e.jsx(Ka,{className:"bg-primary text-primary-foreground font-medium text-sm",children:te(oe)})]})})}),e.jsxs(gu,{align:"end",className:"w-48",children:[e.jsxs(Pa,{onClick:()=>H("/profile"),className:"cursor-pointer",children:[e.jsx(el,{className:"h-4 w-4 mr-2"}),"Profile"]}),e.jsxs(Pa,{onClick:()=>H("/mission-control/integrations"),className:"cursor-pointer",children:[e.jsx(k2,{className:"h-4 w-4 mr-2"}),"Integrations"]}),e.jsxs(Pa,{onClick:()=>H("/mission-control/browser-extension"),className:"cursor-pointer",children:[e.jsx(k2,{className:"h-4 w-4 mr-2"}),"Browser Extension"]}),e.jsx(j0,{}),e.jsxs(Pa,{onClick:r,className:"cursor-pointer text-destructive focus:text-destructive",children:[e.jsx(q8,{className:"h-4 w-4 mr-2"}),"Sign Out"]})]})]})]})]})}),e.jsx(T_s,{children:e.jsx("main",{className:"p-4 sm:p-6 lg:p-8 overflow-x-hidden",children:s})}),j&&e.jsx(C_s,{brief:j,open:C,onClose:I,onDismiss:P}),e.jsx(E_s,{}),e.jsx(P_s,{}),e.jsx(R_s,{})]})]})})},Cn=({children:s,requireAdmin:t=!1,requireBrokerageManager:n=!1})=>{const{user:r,loading:a,rolesLoading:i,isAdmin:l,isBrokerageManager:o}=ks(),c=Tu(),d=rA();if(a||(t||n)&&i)return e.jsx("div",{className:"flex min-h-screen items-center justify-center bg-background",children:e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent mx-auto mb-4"}),e.jsx("p",{className:"text-muted-foreground",children:"Loading..."})]})});if(!r){const u=c.pathname+c.search+c.hash;return u&&u!=="/auth"&&sessionStorage.setItem("redirectAfterLogin",u),e.jsx(ab,{to:"/auth",replace:!0})}if(t&&!l)return e.jsx(ab,{to:"/dashboard",replace:!0});if(n&&!o&&!l)return e.jsx(ab,{to:"/dashboard",replace:!0});if(d.isRestricted&&!d.isLoading){const u=pCt(c.pathname);if(u&&!d.hasFeature(u))return e.jsx(Xs,{title:"Upgrade required",children:e.jsx(wms,{featureKey:u})})}return e.jsx(e.Fragment,{children:s})};var gGe={};(function s(t,n,r,a){var i=!!(t.Worker&&t.Blob&&t.Promise&&t.OffscreenCanvas&&t.OffscreenCanvasRenderingContext2D&&t.HTMLCanvasElement&&t.HTMLCanvasElement.prototype.transferControlToOffscreen&&t.URL&&t.URL.createObjectURL),l=typeof Path2D=="function"&&typeof DOMMatrix=="function",o=function(){if(!t.OffscreenCanvas)return!1;try{var Q=new OffscreenCanvas(1,1),te=Q.getContext("2d");te.fillRect(0,0,1,1);var le=Q.transferToImageBitmap();te.createPattern(le,"no-repeat")}catch{return!1}return!0}();function c(){}function d(Q){var te=n.exports.Promise,le=te!==void 0?te:t.Promise;return typeof le=="function"?new le(Q):(Q(c,c),null)}var u=function(Q,te){return{transform:function(le){if(Q)return le;if(te.has(le))return te.get(le);var fe=new OffscreenCanvas(le.width,le.height),_e=fe.getContext("2d");return _e.drawImage(le,0,0),te.set(le,fe),fe},clear:function(){te.clear()}}}(o,new Map),h=function(){var Q=Math.floor(16.666666666666668),te,le,fe={},_e=0;return typeof requestAnimationFrame=="function"&&typeof cancelAnimationFrame=="function"?(te=function(ve){var he=Math.random();return fe[he]=requestAnimationFrame(function Se(Te){_e===Te||_e+Q-1{const{data:t,error:n}=await V.from("celebration_queue").select("*").eq("user_id",s.id).is("seen_at",null).order("created_at",{ascending:!0});if(n)throw n;return t},enabled:!!(s!=null&&s.id),refetchOnWindowFocus:!0,staleTime:0})}function Y_s(){const s=ls();return Nt({mutationFn:async t=>{const{error:n}=await V.from("celebration_queue").update({seen_at:new Date().toISOString()}).eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["celebrations"]})}})}function Z_s(){const s=ls(),{user:t}=ks();return Nt({mutationFn:async n=>{const{error:r}=await V.from("celebration_queue").insert({user_id:n.user_id,celebration_type:n.celebration_type,title:n.title,message:n.message||null,points_amount:n.points_amount||null,created_by:t==null?void 0:t.id});if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["celebrations"]})}})}const X_s={points_earned:ql,listing_created:ua,deal_closed:Su,custom:ri},elt={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"},tlt=()=>{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 Q_s(){const{user:s}=ks(),t=ls(),{data:n}=K_s(),r=Y_s(),[a,i]=k.useState(null),[l,o]=k.useState(!1),c=k.useCallback(()=>{const p=Date.now()+3e3,g={startVelocity:30,spread:360,ticks:60,zIndex:9999},x=(v,_)=>Math.random()*(_-v)+v,y=setInterval(()=>{const v=p-Date.now();if(v<=0){clearInterval(y);return}const _=50*(v/3e3);Jot({...g,particleCount:_,origin:{x:x(.1,.3),y:Math.random()-.2},colors:["#ff6b6b","#feca57","#48dbfb","#ff9ff3","#54a0ff","#5f27cd"]}),Jot({...g,particleCount:_,origin:{x:x(.7,.9),y:Math.random()-.2},colors:["#ff6b6b","#feca57","#48dbfb","#ff9ff3","#54a0ff","#5f27cd"]})},250)},[]);k.useEffect(()=>{tlt()||n&&n.length>0&&!a&&(i(n[0]),o(!0),setTimeout(c,100))},[n,a,c]);const d=async()=>{if(a){const m=a.id;o(!1),i(null),t.setQueryData(["celebrations","pending",s==null?void 0:s.id],p=>(p==null?void 0:p.filter(g=>g.id!==m))??[]),await r.mutateAsync(m)}};if(tlt()||!a)return null;const u=X_s[a.celebration_type]||ri,h=elt[a.celebration_type]||elt.custom;return e.jsx(zs,{open:l,onOpenChange:m=>!m&&d(),children:e.jsxs(Rs,{className:"sm:max-w-md text-center border-0 overflow-hidden",children:[e.jsx("div",{className:`absolute inset-0 bg-gradient-to-br ${h} opacity-10`}),e.jsxs("div",{className:"relative z-10 py-6",children:[e.jsx("div",{className:"flex justify-center mb-4",children:e.jsx("div",{className:`w-20 h-20 rounded-full bg-gradient-to-br ${h} flex items-center justify-center animate-bounce`,children:e.jsx(u,{className:"w-10 h-10 text-white"})})}),e.jsxs("div",{className:"flex justify-center gap-1 mb-4",children:[e.jsx(kn,{className:"w-5 h-5 text-yellow-500 animate-pulse"}),e.jsx(kn,{className:"w-5 h-5 text-yellow-500 animate-pulse delay-75"}),e.jsx(kn,{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($,{onClick:d,className:"w-full",size:"lg",children:"Awesome! 🙌"}),n&&n.length>1&&e.jsxs("p",{className:"text-sm text-muted-foreground mt-3",children:["+",n.length-1," more celebration",n.length>2?"s":""," waiting"]})]})]})})}function fn({className:s,...t}){return e.jsx("div",{className:Ot("animate-pulse rounded-md bg-muted",s),...t})}var J_s=Object.defineProperty,Hq=(s,t)=>J_s(s,"name",{value:t,configurable:!0}),xGe="Tabs",[ews,DQn]=qm(xGe,[YM]),AAt=YM(),[tws,yGe]=ews(xGe),sws=k.forwardRef(Hq(function(t,n){const{__scopeTabs:r,value:a,onValueChange:i,defaultValue:l,orientation:o="horizontal",dir:c,activationMode:d="automatic",...u}=t,h=e4(c),[m,p]=ox({prop:a,onChange:i,defaultProp:l??"",caller:xGe});return e.jsx(tws,{scope:r,baseId:$x(),value:m,onValueChange:p,orientation:o,dir:h,activationMode:d,children:e.jsx(hi.div,{dir:h,"data-orientation":o,...u,ref:n})})},"Tabs")),nws="TabsList",rws=k.forwardRef(Hq(function(t,n){const{__scopeTabs:r,loop:a=!0,...i}=t,l=yGe(nws,r),o=AAt(r);return e.jsx(E3e,{asChild:!0,...o,orientation:l.orientation,dir:l.dir,loop:a,children:e.jsx(hi.div,{role:"tablist","aria-orientation":l.orientation,...i,ref:n})})},"TabsList")),aws="TabsTrigger",iws=k.forwardRef(Hq(function(t,n){const{__scopeTabs:r,value:a,disabled:i=!1,...l}=t,o=yGe(aws,r),c=AAt(r),d=vGe(o.baseId,a),u=bGe(o.baseId,a),h=a===o.value;return e.jsx(T3e,{asChild:!0,...c,focusable:!i,active:h,children:e.jsx(hi.button,{type:"button",role:"tab","aria-selected":h,"aria-controls":u,"data-state":h?"active":"inactive","data-disabled":i?"":void 0,disabled:i,id:d,...l,ref:n,onMouseDown:ga(t.onMouseDown,m=>{!i&&m.button===0&&m.ctrlKey===!1?o.onValueChange(a):m.preventDefault()}),onKeyDown:ga(t.onKeyDown,m=>{i||m.target!==m.currentTarget||[" ","Enter"].includes(m.key)&&o.onValueChange(a)}),onFocus:ga(t.onFocus,()=>{const m=o.activationMode!=="manual";!h&&!i&&m&&o.onValueChange(a)})})})},"TabsTrigger")),ows="TabsContent",lws=k.forwardRef(Hq(function(t,n){const{__scopeTabs:r,value:a,forceMount:i,children:l,...o}=t,c=yGe(ows,r),d=vGe(c.baseId,a),u=bGe(c.baseId,a),h=a===c.value,m=k.useRef(h);return k.useEffect(()=>{const p=requestAnimationFrame(()=>m.current=!1);return()=>cancelAnimationFrame(p)},[]),e.jsx(cx,{present:i||h,children:({present:p})=>e.jsx(hi.div,{"data-state":h?"active":"inactive","data-orientation":c.orientation,role:"tabpanel","aria-labelledby":d,hidden:!p,id:u,tabIndex:0,...o,ref:n,style:{...t.style,animationDuration:m.current?"0s":void 0},children:p&&l})})},"TabsContent"));function vGe(s,t){return`${s}-trigger-${t}`}Hq(vGe,"makeTriggerId");function bGe(s,t){return`${s}-content-${t}`}Hq(bGe,"makeContentId");var cws=sws,EAt=rws,TAt=iws,MAt=lws;const ya=cws,va=k.forwardRef(({className:s,...t},n)=>e.jsx(EAt,{ref:n,className:Ot("inline-flex h-10 items-center justify-center rounded-md bg-muted p-1 text-muted-foreground",s),...t}));va.displayName=EAt.displayName;const is=k.forwardRef(({className:s,...t},n)=>e.jsx(TAt,{ref:n,className:Ot("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}));is.displayName=TAt.displayName;const cs=k.forwardRef(({className:s,...t},n)=>e.jsx(MAt,{ref:n,className:Ot("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",s),...t}));cs.displayName=MAt.displayName;const YZ="#0d0d0d",hSe="#1a1a1a",tv="#c9a84c",vee="#f0d78c",V5={captured:"lup_lead_captured_v1",stickyDismissed:"lup_sticky_dismissed_v1",exitShown:"lup_exit_shown_v1",savedListings:"lup_saved_listings_v1"};async function tAe(s){const t={...s,source_page:typeof window<"u"?window.location.pathname:null,user_agent:typeof navigator<"u"?navigator.userAgent:null,referrer:typeof document<"u"?document.referrer:null},{data:n,error:r}=await V.functions.invoke("public-site-lead",{body:t});if(r)throw r;try{localStorage.setItem(V5.captured,JSON.stringify({email:s.email,ts:Date.now()}))}catch{}return n}function _Ge(){try{return!!localStorage.getItem(V5.captured)}catch{return!1}}function dws(){try{const s=localStorage.getItem(V5.captured);return s?JSON.parse(s).email??null:null}catch{return null}}function wGe({open:s,onClose:t,children:n}){return k.useEffect(()=>{if(!s)return;const r=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{document.body.style.overflow=r}},[s]),s?a1.createPortal(e.jsx("div",{className:"fixed inset-0 z-[100] flex items-center justify-center p-4 animate-in fade-in",style:{background:"rgba(0,0,0,0.82)",backdropFilter:"blur(6px)"},onClick:t,children:e.jsxs("div",{onClick:r=>r.stopPropagation(),className:"relative w-full max-w-md rounded-2xl overflow-hidden animate-in zoom-in-95",style:{background:`linear-gradient(180deg, ${hSe} 0%, ${YZ} 100%)`,border:`1px solid ${tv}33`,boxShadow:`0 30px 80px rgba(0,0,0,0.6), 0 0 0 1px ${tv}22 inset`},children:[e.jsx("button",{onClick:t,className:"absolute right-4 top-4 z-10 rounded-full p-2 text-white/60 hover:text-white hover:bg-white/10 transition","aria-label":"Close",children:e.jsx(mr,{className:"h-4 w-4"})}),n]})}),document.body):null}function jGe(){const[s,t]=k.useState({first_name:"",email:"",phone:"",area:""}),[n,r]=k.useState(!1),[a,i]=k.useState("");return{values:s,setValues:t,loading:n,setLoading:r,honeypot:a,setHoneypot:i}}function NGe({values:s,setValues:t,honeypot:n,setHoneypot:r,showPhone:a=!0,showArea:i=!0,areaPlaceholder:l="City, ZIP, or neighborhood"}){const o="w-full rounded-lg px-11 py-3 text-sm text-white placeholder:text-white/40 border transition focus:outline-none",c={background:"rgba(255,255,255,0.04)",borderColor:"rgba(255,255,255,0.12)"};return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(el,{className:"absolute left-3.5 top-1/2 -translate-y-1/2 h-4 w-4 text-white/40"}),e.jsx("input",{type:"text",placeholder:"First name",value:s.first_name,onChange:d=>t({...s,first_name:d.target.value}),className:o,style:c})]}),e.jsxs("div",{className:"relative",children:[e.jsx(pn,{className:"absolute left-3.5 top-1/2 -translate-y-1/2 h-4 w-4 text-white/40"}),e.jsx("input",{type:"email",required:!0,placeholder:"Email address",value:s.email,onChange:d=>t({...s,email:d.target.value}),className:o,style:c})]}),a&&e.jsxs("div",{className:"relative",children:[e.jsx(ka,{className:"absolute left-3.5 top-1/2 -translate-y-1/2 h-4 w-4 text-white/40"}),e.jsx("input",{type:"tel",placeholder:"Phone (optional)",value:s.phone,onChange:d=>t({...s,phone:d.target.value}),className:o,style:c})]}),i&&e.jsxs("div",{className:"relative",children:[e.jsx(Si,{className:"absolute left-3.5 top-1/2 -translate-y-1/2 h-4 w-4 text-white/40"}),e.jsx("input",{type:"text",placeholder:l,value:s.area,onChange:d=>t({...s,area:d.target.value}),className:o,style:c})]}),e.jsx("input",{type:"text",value:n,onChange:d=>r(d.target.value),tabIndex:-1,autoComplete:"off",className:"absolute -left-[9999px] w-0 h-0 opacity-0","aria-hidden":"true"})]})}function kGe({children:s,disabled:t,onClick:n,type:r="button"}){return e.jsx("button",{type:r,disabled:t,onClick:n,className:"w-full rounded-lg py-3 text-sm font-semibold uppercase tracking-widest transition disabled:opacity-60 disabled:cursor-not-allowed",style:{background:`linear-gradient(180deg, ${vee} 0%, ${tv} 100%)`,color:YZ,boxShadow:`0 8px 24px ${tv}55`},children:s})}function slt({open:s,onClose:t,initialCriteria:n}){const{values:r,setValues:a,loading:i,setLoading:l,honeypot:o,setHoneypot:c}=jGe(),[d,u]=k.useState(!1),h=async m=>{if(m.preventDefault(),!!r.email){l(!0);try{await tAe({lead_type:"new_listing_alerts",email:r.email.trim().toLowerCase(),first_name:r.first_name.trim()||void 0,phone:r.phone.trim()||void 0,criteria:{...n||{},...r.area.trim()?{area:r.area.trim()}:{}}}),u(!0);try{localStorage.setItem(V5.stickyDismissed,"1")}catch{}setTimeout(t,2200)}catch{ae.error("Something went wrong. Please try again.")}finally{l(!1)}}};return e.jsx(wGe,{open:s,onClose:t,children:e.jsxs("div",{className:"p-8",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(Fx,{className:"h-4 w-4",style:{color:tv}}),e.jsx("span",{className:"text-xs uppercase tracking-[0.2em]",style:{color:vee},children:"New Listing Alerts"})]}),e.jsx("h2",{className:"text-2xl font-serif text-white leading-tight mb-2",children:"Be the first to know."}),e.jsx("p",{className:"text-sm text-white/60 mb-6 leading-relaxed",children:"The best homes go before they hit the market. Get instant alerts the moment new listings match your search."}),d?e.jsxs("div",{className:"py-6 text-center",children:[e.jsx("div",{className:"mx-auto mb-3 h-12 w-12 rounded-full flex items-center justify-center",style:{background:`${tv}22`,border:`1px solid ${tv}55`},children:e.jsx(kn,{className:"h-5 w-5",style:{color:tv}})}),e.jsx("div",{className:"text-white font-medium",children:"You're on the list."}),e.jsx("div",{className:"text-white/50 text-xs mt-1",children:"Check your inbox for confirmation."})]}):e.jsxs("form",{onSubmit:h,className:"space-y-4",children:[e.jsx(NGe,{values:r,setValues:a,honeypot:o,setHoneypot:c}),e.jsx(kGe,{type:"submit",disabled:i||!r.email,children:i?"Activating…":"Activate Alerts"}),e.jsx("p",{className:"text-[10px] text-white/40 text-center leading-relaxed",children:"We respect your inbox. Unsubscribe any time."})]})]})})}function uws(){const[s,t]=k.useState(!0),[n,r]=k.useState(!1);k.useEffect(()=>{try{const i=!!localStorage.getItem(V5.stickyDismissed)||_Ge();t(i)}catch{t(!1)}},[]);const a=()=>{t(!0);try{localStorage.setItem(V5.stickyDismissed,"1")}catch{}};return s?e.jsx(slt,{open:n,onClose:()=>r(!1)}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed bottom-0 left-0 right-0 z-40 animate-in slide-in-from-bottom",style:{background:`linear-gradient(180deg, ${hSe} 0%, ${YZ} 100%)`,borderTop:`1px solid ${tv}44`,boxShadow:"0 -8px 30px rgba(0,0,0,0.5)"},children:e.jsxs("div",{className:"max-w-6xl mx-auto px-4 sm:px-6 py-3 flex items-center gap-3",children:[e.jsx("div",{className:"hidden sm:flex h-9 w-9 rounded-full items-center justify-center flex-shrink-0",style:{background:`${tv}22`,border:`1px solid ${tv}55`},children:e.jsx(Fx,{className:"h-4 w-4",style:{color:tv}})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-white text-sm font-medium truncate",children:"Be the first to know when new homes hit the market"}),e.jsx("div",{className:"text-white/50 text-xs hidden sm:block",children:"Instant alerts. No spam. Unsubscribe anytime."})]}),e.jsx("button",{onClick:()=>r(!0),className:"rounded-lg px-4 py-2 text-xs font-semibold uppercase tracking-wider whitespace-nowrap transition hover:brightness-110",style:{background:`linear-gradient(180deg, ${vee} 0%, ${tv} 100%)`,color:YZ},children:"Get Alerts"}),e.jsx("button",{onClick:a,className:"p-2 text-white/50 hover:text-white transition","aria-label":"Dismiss",children:e.jsx(mr,{className:"h-4 w-4"})})]})}),e.jsx(slt,{open:n,onClose:()=>r(!1)})]})}function hws(){const[s,t]=k.useState(!1),n=k.useRef(!1);k.useEffect(()=>{try{if(sessionStorage.getItem(V5.exitShown)||_Ge())return}catch{}const m=setTimeout(()=>{n.current=!0},8e3),p=g=>{if(n.current&&!(g.clientY>0)){t(!0);try{sessionStorage.setItem(V5.exitShown,"1")}catch{}window.removeEventListener("mouseleave",p),document.removeEventListener("mouseleave",p)}};return document.addEventListener("mouseleave",p),()=>{clearTimeout(m),document.removeEventListener("mouseleave",p)}},[]);const{values:r,setValues:a,loading:i,setLoading:l,honeypot:o,setHoneypot:c}=jGe(),[d,u]=k.useState(!1),h=async m=>{if(m.preventDefault(),!!r.email){l(!0);try{await tAe({lead_type:"exit_intent",email:r.email.trim().toLowerCase(),first_name:r.first_name.trim()||void 0,phone:r.phone.trim()||void 0,criteria:r.area.trim()?{area:r.area.trim()}:void 0}),u(!0),setTimeout(()=>t(!1),2200)}catch{ae.error("Something went wrong. Please try again.")}finally{l(!1)}}};return e.jsx(wGe,{open:s,onClose:()=>t(!1),children:e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"h-32 w-full",style:{background:`linear-gradient(135deg, ${YZ} 0%, ${hSe} 60%, ${tv} 130%)`},children:e.jsx("div",{className:"absolute top-4 left-6",children:e.jsx("span",{className:"text-[10px] uppercase tracking-[0.25em]",style:{color:vee},children:"Before You Go"})})}),e.jsxs("div",{className:"p-8 -mt-10",children:[e.jsx("div",{className:"mx-auto mb-5 h-16 w-16 rounded-full flex items-center justify-center",style:{background:hSe,border:`1px solid ${tv}55`,boxShadow:"0 8px 24px rgba(0,0,0,0.5)"},children:e.jsx(kn,{className:"h-6 w-6",style:{color:tv}})}),e.jsx("h2",{className:"text-2xl font-serif text-white text-center leading-tight mb-2",children:"Wait — get a fresh list of homes."}),e.jsx("p",{className:"text-sm text-white/60 text-center mb-6 leading-relaxed",children:"Drop your email and we'll send you a curated list of homes matching your area, updated weekly."}),d?e.jsxs("div",{className:"py-4 text-center",children:[e.jsx("div",{className:"text-white font-medium",children:"Sent — check your inbox."}),e.jsx("div",{className:"text-white/50 text-xs mt-1",children:"Your list is on its way."})]}):e.jsxs("form",{onSubmit:h,className:"space-y-4",children:[e.jsx(NGe,{values:r,setValues:a,honeypot:o,setHoneypot:c,showPhone:!1}),e.jsx(kGe,{type:"submit",disabled:i||!r.email,children:i?"Sending…":"Send My List"})]})]})]})})}function mws(){const[s,t]=k.useState([]);k.useEffect(()=>{try{const o=localStorage.getItem(V5.savedListings);o&&t(JSON.parse(o))}catch{}},[]);const n=o=>{t(o);try{localStorage.setItem(V5.savedListings,JSON.stringify(o))}catch{}},r=k.useCallback(o=>s.includes(o),[s]),a=o=>{s.includes(o)||n([...s,o])},i=o=>n(s.filter(c=>c!==o));return{ids:s,has:r,add:a,remove:i,toggle:o=>s.includes(o)?i(o):a(o)}}function fws({listingId:s,listingAddress:t,className:n}){const{has:r,add:a,remove:i}=mws(),l=r(s),[o,c]=k.useState(!1),d=()=>{if(l){i(s);return}if(_Ge()){a(s),ae.success("Saved to your favorites"),tAe({lead_type:"saved_listing",email:dws()||"unknown@local",listing_id:s,listing_address:t}).catch(()=>{});return}c(!0)};return e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:d,className:n,"aria-label":l?"Remove from favorites":"Save to favorites",children:e.jsx(Bo,{className:`h-5 w-5 ${l?"fill-current":""}`})}),e.jsx(pws,{open:o,onClose:()=>c(!1),listingId:s,listingAddress:t,onSaved:()=>a(s)})]})}function pws({open:s,onClose:t,listingId:n,listingAddress:r,onSaved:a}){const{values:i,setValues:l,loading:o,setLoading:c,honeypot:d,setHoneypot:u}=jGe(),h=async m=>{if(m.preventDefault(),!!i.email){c(!0);try{await tAe({lead_type:"saved_listing",email:i.email.trim().toLowerCase(),first_name:i.first_name.trim()||void 0,phone:i.phone.trim()||void 0,listing_id:n,listing_address:r}),a(),ae.success("Saved to your favorites"),t()}catch{ae.error("Something went wrong. Please try again.")}finally{c(!1)}}};return e.jsx(wGe,{open:s,onClose:t,children:e.jsxs("div",{className:"p-8",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(Bo,{className:"h-4 w-4",style:{color:tv}}),e.jsx("span",{className:"text-xs uppercase tracking-[0.2em]",style:{color:vee},children:"Save This Home"})]}),e.jsx("h2",{className:"text-2xl font-serif text-white leading-tight mb-2",children:"One click to save."}),e.jsx("p",{className:"text-sm text-white/60 mb-6 leading-relaxed",children:"Get an alert if the price drops or the status changes. No spam — just the updates that matter."}),e.jsxs("form",{onSubmit:h,className:"space-y-4",children:[e.jsx(NGe,{values:i,setValues:l,honeypot:d,setHoneypot:u}),e.jsx(kGe,{type:"submit",disabled:o||!i.email,children:o?"Saving…":"Save Home"})]})]})})}var gws=Object.defineProperty,$u=(s,t)=>gws(s,"name",{value:t,configurable:!0}),PAt=["PageUp","PageDown"],IAt=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],LAt={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},bee="Slider",[_7e,xws,yws]=fF(bee),[SGe,OQn]=qm(bee,[yws]),[vws,_ee]=SGe(bee),RAt=k.forwardRef($u(function(t,n){const{name:r,min:a=0,max:i=100,step:l=1,orientation:o="horizontal",disabled:c=!1,minStepsBetweenThumbs:d=0,defaultValue:u=[a],value:h,onValueChange:m=$u(()=>{},"onValueChange"),onValueCommit:p=$u(()=>{},"onValueCommit"),inverted:g=!1,form:x,...y}=t,v=k.useRef(new Set),_=k.useRef(0),j=k.useRef(!1),A=o==="horizontal"?bws:_ws,[M,I]=k.useState(null),P=Ao(n,I),[R=[],O]=ox({prop:h,defaultProp:u,onChange:$u(ee=>{var me;(me=[...v.current][_.current])==null||me.focus({preventScroll:!0,focusVisible:j.current}),j.current=!1,m(ee)},"onChange")}),B=k.useRef(R),U=k.useRef(R);k.useEffect(()=>{const ee=x?M==null?void 0:M.ownerDocument.getElementById(x):M==null?void 0:M.closest("form");if(ee instanceof HTMLFormElement){const oe=$u(()=>O(U.current),"reset");return ee.addEventListener("reset",oe),()=>ee.removeEventListener("reset",oe)}},[M,x,O]);function G(ee){const oe=qAt(R,ee);se(ee,oe)}$u(G,"handleSlideStart");function H(ee){se(ee,_.current)}$u(H,"handleSlideMove");function Y(){String(R)!==String(B.current)&&p(R)}$u(Y,"handleSlideEnd");function se(ee,oe,{commit:me}={commit:!1}){const Q=AGe(l),te=vY(Math.round((ee-a)/l)*l+a,Q),le=xU(te,[a,i]);O((fe=[])=>{const _e=$At(fe,le,oe);if(GAt(_e,d*l)){_.current=_e.indexOf(le);const ve=String(_e)!==String(fe);return ve&&me&&p(_e),ve?_e:fe}else return fe})}return $u(se,"updateValues"),e.jsx(vws,{scope:t.__scopeSlider,name:r,disabled:c,min:a,max:i,valueIndexToChangeRef:_,thumbs:v.current,values:R,orientation:o,form:x,children:e.jsx(_7e.Provider,{scope:t.__scopeSlider,children:e.jsx(_7e.Slot,{scope:t.__scopeSlider,children:e.jsx(A,{"aria-disabled":c,"data-disabled":c?"":void 0,...y,ref:P,onPointerDown:ga(y.onPointerDown,()=>{c||(B.current=R,j.current=!1)}),min:a,max:i,inverted:g,onSlideStart:c?void 0:G,onSlideMove:c?void 0:H,onSlideEnd:c?void 0:Y,onHomeKeyDown:()=>{c||(j.current=!0,se(a,0,{commit:!0}))},onEndKeyDown:()=>{c||(j.current=!0,se(i,R.length-1,{commit:!0}))},onStepKeyDown:({event:ee,direction:oe})=>{if(!c){j.current=!0;const te=PAt.includes(ee.key)||ee.shiftKey&&IAt.includes(ee.key)?10:1,le=_.current,fe=R[le],_e=WAt(fe,{min:a,step:l,direction:oe,multiplier:te});se(_e,le,{commit:!0})}}})})})})},"Slider")),[DAt,OAt]=SGe(bee,{startEdge:"left",endEdge:"right",size:"width",direction:1}),bws=k.forwardRef($u(function(t,n){const{min:r,max:a,dir:i,inverted:l,onSlideStart:o,onSlideMove:c,onSlideEnd:d,onStepKeyDown:u,...h}=t,[m,p]=k.useState(null),g=Ao(n,p),x=k.useRef(void 0),y=e4(i),v=y==="ltr",_=v&&!l||!v&&l;function j(C){const A=x.current||m.getBoundingClientRect(),M=[0,A.width],P=sAe(M,_?[r,a]:[a,r]);return x.current=A,P(C-A.left)}return $u(j,"getValueFromPointer"),e.jsx(DAt,{scope:t.__scopeSlider,startEdge:_?"left":"right",endEdge:_?"right":"left",direction:_?1:-1,size:"width",children:e.jsx(FAt,{dir:y,"data-orientation":"horizontal",...h,ref:g,style:{...h.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:C=>{const A=j(C.clientX);o==null||o(A)},onSlideMove:C=>{const A=j(C.clientX);c==null||c(A)},onSlideEnd:()=>{x.current=void 0,d==null||d()},onStepKeyDown:C=>{const M=LAt[_?"from-left":"from-right"].includes(C.key);u==null||u({event:C,direction:M?-1:1})}})})},"SliderHorizontal")),_ws=k.forwardRef($u(function(t,n){const{min:r,max:a,inverted:i,onSlideStart:l,onSlideMove:o,onSlideEnd:c,onStepKeyDown:d,...u}=t,h=k.useRef(null),m=Ao(n,h),p=k.useRef(void 0),g=!i;function x(y){const v=p.current||h.current.getBoundingClientRect(),_=[0,v.height],C=sAe(_,g?[a,r]:[r,a]);return p.current=v,C(y-v.top)}return $u(x,"getValueFromPointer"),e.jsx(DAt,{scope:t.__scopeSlider,startEdge:g?"bottom":"top",endEdge:g?"top":"bottom",size:"height",direction:g?1:-1,children:e.jsx(FAt,{"data-orientation":"vertical",...u,ref:m,style:{...u.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:y=>{const v=x(y.clientY);l==null||l(v)},onSlideMove:y=>{const v=x(y.clientY);o==null||o(v)},onSlideEnd:()=>{p.current=void 0,c==null||c()},onStepKeyDown:y=>{const _=LAt[g?"from-bottom":"from-top"].includes(y.key);d==null||d({event:y,direction:_?-1:1})}})})},"SliderVertical")),FAt=k.forwardRef($u(function(t,n){const{__scopeSlider:r,onSlideStart:a,onSlideMove:i,onSlideEnd:l,onHomeKeyDown:o,onEndKeyDown:c,onStepKeyDown:d,...u}=t,h=_ee(bee,r);return e.jsx(hi.span,{...u,ref:n,onKeyDown:ga(t.onKeyDown,m=>{m.key==="Home"?(o(m),m.preventDefault()):m.key==="End"?(c(m),m.preventDefault()):PAt.concat(IAt).includes(m.key)&&(d(m),m.preventDefault())}),onPointerDown:ga(t.onPointerDown,m=>{const p=m.target;p.setPointerCapture(m.pointerId),m.preventDefault(),h.thumbs.has(p)?p.focus({preventScroll:!0,focusVisible:!1}):a(m)}),onPointerMove:ga(t.onPointerMove,m=>{m.target.hasPointerCapture(m.pointerId)&&i(m)}),onPointerUp:ga(t.onPointerUp,m=>{const p=m.target;p.hasPointerCapture(m.pointerId)&&(p.releasePointerCapture(m.pointerId),l(m))})})},"SliderImpl")),wws="SliderTrack",jws=k.forwardRef($u(function(t,n){const{__scopeSlider:r,...a}=t,i=_ee(wws,r);return e.jsx(hi.span,{"data-disabled":i.disabled?"":void 0,"data-orientation":i.orientation,...a,ref:n})},"SliderTrack")),nlt="SliderRange",Nws=k.forwardRef($u(function(t,n){const{__scopeSlider:r,...a}=t,i=_ee(nlt,r),l=OAt(nlt,r),o=k.useRef(null),c=Ao(n,o),d=i.values.length,u=i.values.map(p=>CGe(p,i.min,i.max)),h=d>1?Math.min(...u):0,m=100-Math.max(...u);return e.jsx(hi.span,{"data-orientation":i.orientation,"data-disabled":i.disabled?"":void 0,...a,ref:c,style:{...t.style,[l.startEdge]:h+"%",[l.endEdge]:m+"%"}})},"SliderRange")),kws="SliderThumb",[Sws,zAt]=SGe(kws),Cws="SliderThumbProvider";function BAt(s){const{__scopeSlider:t,name:n,children:r,internal_do_not_use_render:a}=s,i=_ee(Cws,t),l=xws(t),[o,c]=k.useState(null),d=k.useMemo(()=>o?l().findIndex(y=>y.ref.current===o):-1,[l,o]),u=Dq(o),h=o?!!i.form||!!o.closest("form"):!0,m=i.values[d],p=n??(i.name?i.name+(i.values.length>1?"[]":""):void 0),g=m===void 0?0:CGe(m,i.min,i.max);k.useEffect(()=>{if(o)return i.thumbs.add(o),()=>{i.thumbs.delete(o)}},[o,i.thumbs]);const x={value:m,name:p,form:i.form,isFormControl:h,index:d,thumb:o,onThumbChange:c,percent:g,size:u};return e.jsx(Sws,{scope:t,...x,children:KAt(a)?a(x):r})}$u(BAt,"SliderThumbProvider");var SIe="SliderThumbTrigger",Aws=k.forwardRef($u(function(t,n){const{__scopeSlider:r,...a}=t,i=_ee(SIe,r),l=OAt(SIe,r),{index:o,value:c,percent:d,size:u,onThumbChange:h}=zAt(SIe,r),m=Ao(n,h),p=UAt(o,i.values.length),g=u==null?void 0:u[l.size],x=g?VAt(g,d,l.direction):0;return e.jsx("span",{style:{transform:"var(--radix-slider-thumb-transform)",position:"absolute",[l.startEdge]:`calc(${d}% + ${x}px)`},children:e.jsx(_7e.ItemSlot,{scope:r,children:e.jsx(hi.span,{role:"slider","aria-label":t["aria-label"]||p,"aria-valuemin":i.min,"aria-valuenow":c,"aria-valuemax":i.max,"aria-orientation":i.orientation,"data-orientation":i.orientation,"data-disabled":i.disabled?"":void 0,tabIndex:i.disabled?void 0:0,...a,ref:m,style:c===void 0?{display:"none"}:t.style,onFocus:ga(t.onFocus,()=>{i.valueIndexToChangeRef.current=o})})})})},"SliderThumbTrigger")),Ews=k.forwardRef($u(function(t,n){const{__scopeSlider:r,name:a,...i}=t;return e.jsx(BAt,{__scopeSlider:r,name:a,internal_do_not_use_render:({index:l,isFormControl:o})=>e.jsxs(e.Fragment,{children:[e.jsx(Aws,{...i,ref:n,__scopeSlider:r}),o?e.jsx(Mws,{__scopeSlider:r},l):null]})})},"SliderThumb")),Tws="SliderBubbleInput",Mws=k.forwardRef($u(function({__scopeSlider:t,...n},r){const{value:a,name:i,form:l}=zAt(Tws,t),o=k.useRef(null),c=Ao(o,r),d=XHe(a);return k.useEffect(()=>{const u=o.current;if(!u)return;const h=window.HTMLInputElement.prototype,p=Object.getOwnPropertyDescriptor(h,"value").set;if(d!==a&&p){const g=new Event("input",{bubbles:!0});p.call(u,a),u.dispatchEvent(g)}},[d,a]),e.jsx(hi.input,{style:{display:"none"},name:i,form:l,...n,ref:c,defaultValue:a})},"SliderBubbleInput"));function $At(s=[],t,n){const r=[...s];return r[n]=t,r.sort((a,i)=>a-i)}$u($At,"getNextSortedValues");function CGe(s,t,n){const i=100/(n-t)*(s-t);return xU(i,[0,100])}$u(CGe,"convertValueToPercentage");function UAt(s,t){return t>2?`Value ${s+1} of ${t}`:t===2?["Minimum","Maximum"][s]:void 0}$u(UAt,"getLabel");function qAt(s,t){if(s.length===1)return 0;const n=s.map(a=>Math.abs(a-t)),r=Math.min(...n);return n.indexOf(r)}$u(qAt,"getClosestValueIndex");function VAt(s,t,n){const r=s/2,i=sAe([0,50],[0,r]);return(r-i(t)*n)*n}$u(VAt,"getThumbInBoundsOffset");function HAt(s){return s.slice(0,-1).map((t,n)=>s[n+1]-t)}$u(HAt,"getStepsBetweenValues");function GAt(s,t){if(t>0){const n=HAt(s);return Math.min(...n)>=t}return!0}$u(GAt,"hasMinStepsBetweenValues");function sAe(s,t){return n=>{if(s[0]===s[1]||t[0]===t[1])return t[0];const r=(t[1]-t[0])/(s[1]-s[0]);return t[0]+r*(n-s[0])}}$u(sAe,"linearScale");function AGe(s){if(!Number.isFinite(s))return 0;const t=s.toString();if(t.includes("e")){const[r,a]=t.split("e"),i=r.split(".")[1]||"",l=Number(a);return Math.max(0,i.length-l)}const n=t.split(".")[1];return n?n.length:0}$u(AGe,"getDecimalCount");function vY(s,t){const n=Math.pow(10,t);return Math.round(s*n)/n}$u(vY,"roundValue");function WAt(s,{min:t,step:n,direction:r,multiplier:a}){const i=AGe(n),l=(s-t)/n,o=Math.round(l),c=vY(o*n+t,i)===vY(s,i);let d;return c?d=o+a*r:r>0?d=Math.ceil(l):d=Math.floor(l),vY(d*n+t,i)}$u(WAt,"getNextStepValue");function KAt(s){return typeof s=="function"}$u(KAt,"isFunction");const sx=k.forwardRef(({className:s,...t},n)=>e.jsxs(RAt,{ref:n,className:Ot("relative flex w-full touch-none select-none items-center",s),...t,children:[e.jsx(jws,{className:"relative h-2 w-full grow overflow-hidden rounded-full bg-secondary",children:e.jsx(Nws,{className:"absolute h-full bg-primary"})}),e.jsx(Ews,{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"})]}));sx.displayName=RAt.displayName;const Pws=s=>pt({queryKey:["public-listings",s],queryFn:async()=>{let t=V.from("listings").select(` id, slug, agent_id, property_address, city, state, neighborhood, price, property_type, status, bedrooms, bathrooms, square_footage, lot_size, year_built, has_hoa, description, latitude, longitude, created_at, updated_at, photos:listing_photos(id, photo_url, is_primary), agent:profiles!listings_agent_id_fkey(id, name, email, phone, avatar_url, brokerage_name, brokerage:brokerages(name)) `).eq("is_approved",!0).eq("is_public",!0).order("created_at",{ascending:!1});if(s!=null&&s.status&&(t=t.eq("status",s.status)),s!=null&&s.propertyType&&(t=t.eq("property_type",s.propertyType)),s!=null&&s.city){const a=s.city.replace(/[%,()]/g," ").trim();if(a){const i=`%${a}%`;t=t.or(`city.ilike.${i},neighborhood.ilike.${i},property_address.ilike.${i}`)}}s!=null&&s.minPrice&&(t=t.gte("price",s.minPrice)),s!=null&&s.maxPrice&&(t=t.lte("price",s.maxPrice));const{data:n,error:r}=await t;if(r)throw r;return n}}),Iws=()=>pt({queryKey:["public-listings-search-index"],staleTime:5*60*1e3,queryFn:async()=>{const{data:s,error:t}=await V.from("listings").select("city, state, neighborhood, property_address").eq("is_approved",!0).eq("is_public",!0);if(t)throw t;const n=new Map,r=new Map,a=new Map;return(s||[]).forEach(i=>{if(i.city){const l=`${i.city}|${i.state||""}`.toLowerCase(),o=i.state?`${i.city}, ${i.state}`:i.city,c=n.get(l);c?c.count++:n.set(l,{label:o,city:i.city,state:i.state,count:1})}if(i.neighborhood){const l=`${i.neighborhood}|${i.city||""}`.toLowerCase(),o=i.city?`${i.neighborhood} — ${i.city}`:i.neighborhood,c=r.get(l);c?c.count++:r.set(l,{label:o,city:i.city||"",neighborhood:i.neighborhood,count:1})}if(i.property_address){const l=String(i.property_address).match(/\b(\d{5})(?:-\d{4})?\b/);if(l){const o=l[1],c=a.get(o);c?c.count++:a.set(o,{label:o,zip:o,count:1})}}}),{cities:Array.from(n.values()).sort((i,l)=>l.count-i.count),neighborhoods:Array.from(r.values()).sort((i,l)=>l.count-i.count),zips:Array.from(a.values()).sort((i,l)=>l.count-i.count)}}}),Lws=s=>pt({queryKey:["public-listing",s],queryFn:async()=>{const t=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(s);let n=V.from("listings").select(` id, slug, agent_id, property_address, city, state, neighborhood, price, property_type, status, bedrooms, bathrooms, square_footage, lot_size, year_built, has_hoa, description, agent_notes, agent_notes_public, mls_link, video_link, video_id, latitude, longitude, page_config, page_theme, created_at, updated_at, co_agent_name, co_agent_email, co_agent_phone, co_agent_brokerage, co_agent_photo_url, photos:listing_photos(id, photo_url, is_primary, sort_order), agent:profiles!listings_agent_id_fkey(id, name, email, phone, avatar_url, brokerage_name, brokerage:brokerages(name)), video:agent_videos!listings_video_id_fkey(id, playback_url, thumbnail_url, title, duration_seconds, bunny_video_id) `).eq("is_approved",!0).eq("is_public",!0);t?n=n.eq("id",s):n=n.eq("slug",s);const{data:r,error:a}=await n.single();if(a)throw a;return r},enabled:!!s}),Rws=()=>Nt({mutationFn:async({listingId:s,agentId:t,firstName:n,lastName:r,email:a,phone:i,shareToken:l,leadType:o="info_request",preferredDate:c,preferredTime:d,showingMode:u,message:h})=>{let m=null,p=null;if(l){const{data:v}=await V.from("listing_shares").select("id, sharing_agent_id").eq("share_token",l).eq("listing_id",s).maybeSingle();v&&(m=v.id,p=v.sharing_agent_id)}const{data:g,error:x}=await V.from("listing_leads").insert({listing_id:s,agent_id:p||t,first_name:n,last_name:r,email:a,phone:i,share_id:m,referred_by_agent_id:p,lead_type:o,preferred_date:c||null,preferred_time:d||null,showing_mode:u||null,message:h||null}).select().single();if(x)throw x;const{error:y}=await V.functions.invoke("process-listing-lead",{body:{leadId:g.id}});return y&&console.error("Error processing lead:",y),g}}),Dws=()=>Nt({mutationFn:async s=>{const{error:t}=await V.rpc("increment_listing_share_click",{p_share_token:s});if(t)throw t}}),rlt="/assets/levelup-logo-color-BeKd2k_g.png",Ows={active:"bg-emerald-500",coming_soon:"bg-sky-500",office_exclusive:"bg-indigo-500",pre_market:"bg-cyan-500",price_improvement:"bg-orange-500",under_contract:"bg-purple-500",sold:"bg-gray-600"},Fws={active:"For Sale",coming_soon:"Coming Soon",office_exclusive:"Office Exclusive",pre_market:"Pre-Market",price_improvement:"Price Improvement",under_contract:"Under Contract",sold:"Sold"},alt={single_family:"Single Family",condo:"Condo",townhouse:"Townhouse",land:"Land",multi_family:"Multi-Family",luxury:"Luxury",commercial:"Commercial",other:"Other"},tre=s=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s),lG=s=>new Intl.NumberFormat("en-US").format(s);function YAt({slugOverride:s}={}){var Is,xs,st,dt,jt;const t=oo(),n=s||t.slugOrId,[r]=Jc(),{data:a,isLoading:i}=Lws(n||""),l=Rws(),o=Dws(),c=r.get("ref"),[d,u]=k.useState(""),[h,m]=k.useState(""),[p,g]=k.useState(""),[x,y]=k.useState(""),[v,_]=k.useState(""),[j,C]=k.useState(""),[A,M]=k.useState(""),[I,P]=k.useState("in_person"),[R,O]=k.useState("info"),[B,U]=k.useState(!1),[G,H]=k.useState(!1),[Y,se]=k.useState(null),[ee,oe]=k.useState(!1),[me,Q]=k.useState(!1),[te,le]=k.useState(!1),[fe,_e]=k.useState(20),[ve,he]=k.useState(6.5),[Se,Te]=k.useState(30),Ie=k.useRef(null),[Ue,Be]=k.useState(!1);k.useEffect(()=>{const gt=()=>Be(window.scrollY>300);return window.addEventListener("scroll",gt,{passive:!0}),()=>window.removeEventListener("scroll",gt)},[]),k.useEffect(()=>{c&&o.mutate(c)},[c]),k.useEffect(()=>{window.scrollTo({top:0,left:0,behavior:"auto"})},[n]);const je=(a==null?void 0:a.photos)||[],Ye=je.find(gt=>gt.is_primary)||je[0],Ee=k.useMemo(()=>{if(!(a!=null&&a.price))return 0;const gt=a.price*(1-fe/100),rs=ve/100/12,Ns=Se*12;return rs===0?gt/Ns:gt*rs/(1-Math.pow(1+rs,-Ns))},[a==null?void 0:a.price,fe,ve,Se]),Re=async()=>{const gt=window.location.href;if(navigator.share)try{await navigator.share({title:document.title,url:gt})}catch{}else await navigator.clipboard.writeText(gt),ae.success("Link copied to clipboard")},ke=async gt=>{if(gt.preventDefault(),!d.trim()||!p.trim()||!a)return;const rs=R==="showing";if(rs&&!j){ae.error("Please pick a preferred date for your showing");return}U(!0);try{await l.mutateAsync({listingId:a.id,agentId:a.agent_id,firstName:d.trim(),lastName:h.trim(),email:p.trim(),phone:x.trim(),shareToken:c,leadType:rs?"showing_request":"info_request",preferredDate:rs?j:null,preferredTime:rs&&A||null,showingMode:rs?I:null,message:v.trim()||null}),H(!0),ae.success(rs?"Showing request sent! The agent will confirm details shortly.":"Thanks! The agent will be in touch soon.")}catch(Ns){console.error("Lead submission error:",Ns),ae.error(`Failed to submit: ${Ns.message||"Please try again"}`)}finally{U(!1)}},Fe=()=>{Y!==null&&se(Y===0?je.length-1:Y-1)},Oe=()=>{Y!==null&&se(Y===je.length-1?0:Y+1)};if(i)return e.jsx("div",{className:"min-h-screen bg-neutral-950",children:e.jsx(fn,{className:"h-[100svh] w-full rounded-none bg-neutral-900"})});if(!a)return e.jsxs("div",{className:"min-h-screen bg-background",children:[e.jsx("header",{className:"border-b bg-card",children:e.jsx("div",{className:"container mx-auto px-4 py-4",children:e.jsx(nr,{to:"/public/listings",className:"flex items-center gap-2",children:e.jsx("img",{src:rlt,alt:"LevelUp",className:"h-8"})})})}),e.jsxs("div",{className:"container mx-auto px-4 py-24 text-center",children:[e.jsx(ua,{className:"h-16 w-16 mx-auto text-muted-foreground mb-4"}),e.jsx("h1",{className:"text-2xl font-bold mb-2",children:"Listing Not Found"}),e.jsx("p",{className:"text-muted-foreground mb-6",children:"This listing may no longer be available."}),e.jsx($,{asChild:!0,children:e.jsx(nr,{to:typeof window<"u"&&window.location.host==="listings.relevelup.com"?"/":"/public/listings",children:"Browse All Listings"})})]})]});const Ge=a.property_address?`${a.property_address} — ${a.city}, ${a.state}`:`${a.city}, ${a.state} Home for Sale`,yt=((xs=(Is=a.agent)==null?void 0:Is.brokerage)==null?void 0:xs.name)||((st=a.agent)==null?void 0:st.brokerage_name),tt=a.latitude&&a.longitude?`https://maps.google.com/maps?q=${a.latitude},${a.longitude}&z=15&output=embed`:a.property_address?`https://maps.google.com/maps?q=${encodeURIComponent(`${a.property_address}, ${a.city}, ${a.state}`)}&z=15&output=embed`:null,ut=a.description||"",nt=ut.length>420,et=te||!nt?ut:ut.slice(0,420).trimEnd()+"…",at=a.page_config||{},wt=gt=>{var rs;return(((rs=at.sections)==null?void 0:rs[gt])??!0)!==!1},rt=Array.isArray(at.addons)?at.addons:[],Ft=at.custom_note||"",Ut=at.accent_color||null;return e.jsxs(e.Fragment,{children:[e.jsxs(Sc,{children:[e.jsxs("title",{children:[Ge," | LevelUp Listings"]}),e.jsx("meta",{name:"description",content:`${tre(a.price)} · ${a.bedrooms||""}BD ${a.bathrooms||""}BA ${a.square_footage?a.square_footage.toLocaleString()+" sqft · ":""}${alt[a.property_type]} in ${a.city}, ${a.state}. ${ut.slice(0,140)}`}),e.jsx("link",{rel:"canonical",href:`https://listings.relevelup.com/${a.slug||a.id}`}),e.jsx("link",{rel:"preconnect",href:"https://fonts.googleapis.com"}),e.jsx("link",{rel:"preconnect",href:"https://fonts.gstatic.com",crossOrigin:""}),e.jsx("link",{href:"https://fonts.googleapis.com/css2?family=Fraunces:opsz,wght@9..144,300;9..144,400;9..144,500;9..144,600&display=swap",rel:"stylesheet"}),e.jsx("meta",{property:"og:title",content:Ge}),e.jsx("meta",{property:"og:description",content:`${tre(a.price)} · ${a.city}, ${a.state}`}),e.jsx("meta",{property:"og:type",content:"website"}),e.jsx("meta",{property:"og:url",content:`https://listings.relevelup.com/${a.slug||a.id}`}),Ye&&e.jsx("meta",{property:"og:image",content:Ye.photo_url}),e.jsx("meta",{property:"og:site_name",content:"LevelUp Listings"}),e.jsx("meta",{name:"twitter:card",content:"summary_large_image"}),e.jsx("meta",{name:"twitter:title",content:Ge}),e.jsx("meta",{name:"twitter:description",content:`${tre(a.price)} · ${a.city}, ${a.state}`}),Ye&&e.jsx("meta",{name:"twitter:image",content:Ye.photo_url}),e.jsx("meta",{name:"robots",content:"index, follow"}),e.jsx("script",{type:"application/ld+json",children:JSON.stringify({"@context":"https://schema.org","@type":"RealEstateListing",name:a.property_address||`${a.city}, ${a.state} Home`,description:ut,url:`https://listings.relevelup.com/${a.slug||a.id}`,datePosted:a.created_at,image:je.map(gt=>gt.photo_url),address:{"@type":"PostalAddress",streetAddress:a.property_address||void 0,addressLocality:a.city,addressRegion:a.state,addressCountry:"US"},offers:{"@type":"Offer",price:a.price,priceCurrency:"USD",availability:a.status==="sold"?"https://schema.org/SoldOut":a.status==="under_contract"?"https://schema.org/LimitedAvailability":"https://schema.org/InStock"},numberOfRooms:a.bedrooms||void 0,numberOfBathroomsTotal:a.bathrooms||void 0,floorSize:a.square_footage?{"@type":"QuantitativeValue",value:a.square_footage,unitCode:"FTK"}:void 0,yearBuilt:a.year_built||void 0})}),e.jsx("style",{children:` .font-display { font-family: 'Fraunces', ui-serif, Georgia, serif; font-optical-sizing: auto; letter-spacing: -0.02em; } @keyframes kb-zoom { from { transform: scale(1.08); } to { transform: scale(1); } } .kb-zoom { animation: kb-zoom 12s ease-out forwards; } .noscroll::-webkit-scrollbar { display: none; } `})]}),e.jsxs("div",{className:"bg-neutral-950 text-neutral-100 min-h-screen",children:[e.jsx("header",{className:`fixed inset-x-0 top-0 z-40 transition-all duration-300 ${Ue?"bg-neutral-950/85 backdrop-blur-xl border-b border-white/10 py-3":"bg-gradient-to-b from-black/60 to-transparent py-4"}`,children:e.jsxs("div",{className:"max-w-7xl mx-auto px-4 sm:px-6 flex items-center justify-between gap-3",children:[e.jsxs(nr,{to:typeof window<"u"&&window.location.host==="listings.relevelup.com"?"/":"/public/listings",className:"flex items-center gap-2 text-white/90 hover:text-white",children:[e.jsx(Ia,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm font-medium hidden sm:inline",children:"All Listings"})]}),Ue&&e.jsx("div",{className:"hidden md:flex items-center gap-1 text-sm",children:[["overview","Overview"],["gallery","Gallery"],["story","The Story"],["video","Video"],["map","Location"],["payment","Payment"],["agent","Agent"]].map(([gt,rs])=>e.jsx("a",{href:`#${gt}`,className:"px-3 py-1.5 rounded-full text-white/70 hover:text-white hover:bg-white/10 transition",children:rs},gt))}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(fws,{listingId:a.id,listingAddress:a.property_address?`${a.property_address}, ${a.city}, ${a.state}`:`${a.city}, ${a.state}`,className:"h-9 w-9 rounded-full border border-white/20 bg-white/5 backdrop-blur hover:bg-white/15 flex items-center justify-center transition text-white"}),e.jsx("button",{onClick:Re,className:"h-9 w-9 rounded-full border border-white/20 bg-white/5 backdrop-blur hover:bg-white/15 flex items-center justify-center transition","aria-label":"Share",children:e.jsx(ou,{className:"h-4 w-4 text-white"})}),e.jsx($,{size:"sm",onClick:()=>oe(!0),className:"hidden sm:inline-flex bg-white text-neutral-900 hover:bg-white/90 rounded-full h-9 px-4 font-medium",children:"Request Tour"})]})]})}),e.jsxs("section",{ref:Ie,id:"overview",className:"relative h-[100svh] min-h-[620px] w-full overflow-hidden",children:[Ye?e.jsx("img",{src:Ye.photo_url,alt:a.property_address||`${a.city}, ${a.state}`,className:"absolute inset-0 h-full w-full object-cover kb-zoom"}):e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-neutral-800 to-neutral-950"}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-black via-black/50 to-black/20"}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-r from-black/40 via-transparent to-transparent"}),e.jsxs("div",{className:"absolute top-24 right-4 sm:right-8 z-10 flex flex-col items-end gap-2",children:[e.jsx(qe,{className:`${Ows[a.status]} text-white border-0 uppercase tracking-widest text-[10px] px-3 py-1 rounded-full shadow-lg`,children:Fws[a.status]}),je.length>0&&e.jsxs("button",{onClick:()=>se(0),className:"flex items-center gap-1.5 text-xs text-white/90 bg-black/40 backdrop-blur border border-white/20 rounded-full px-3 py-1.5 hover:bg-black/60 transition",children:[e.jsx(g0,{className:"h-3.5 w-3.5"}),je.length," photos"]})]}),e.jsx("div",{className:"absolute inset-x-0 bottom-0 z-10 px-4 sm:px-8 pb-10 sm:pb-14",children:e.jsxs("div",{className:"max-w-7xl mx-auto",children:[e.jsxs("div",{className:"flex items-end justify-between gap-6 flex-wrap",children:[e.jsxs("div",{className:"max-w-3xl",children:[a.neighborhood&&e.jsxs("p",{className:"text-white/70 uppercase tracking-[0.25em] text-xs mb-3 font-medium",children:[a.neighborhood," · ",a.city,", ",a.state]}),a.property_address&&e.jsx("h1",{className:"font-display text-white text-4xl sm:text-6xl md:text-7xl leading-[0.95] mb-4 font-light",children:a.property_address}),!a.property_address&&e.jsxs("h1",{className:"font-display text-white text-4xl sm:text-6xl md:text-7xl leading-[0.95] mb-4 font-light",children:[a.city,", ",a.state]}),e.jsxs("div",{className:"flex items-center gap-4 flex-wrap",children:[e.jsx("p",{className:"font-display text-white text-3xl sm:text-4xl md:text-5xl font-medium",children:tre(a.price)}),e.jsx("div",{className:"h-8 w-px bg-white/30 hidden sm:block"}),e.jsxs("div",{className:"flex items-center gap-4 text-white/80 text-sm sm:text-base",children:[a.bedrooms&&e.jsxs("span",{children:[e.jsx("span",{className:"font-semibold text-white",children:a.bedrooms})," bd"]}),a.bathrooms&&e.jsxs("span",{children:[e.jsx("span",{className:"font-semibold text-white",children:a.bathrooms})," ba"]}),a.square_footage&&e.jsxs("span",{children:[e.jsx("span",{className:"font-semibold text-white",children:lG(a.square_footage)})," sqft"]})]})]})]}),a.agent&&e.jsxs("div",{className:"hidden md:flex items-center gap-3 bg-white/10 backdrop-blur-xl border border-white/20 rounded-2xl px-4 py-3 shadow-2xl",children:[a.agent.avatar_url?e.jsx("img",{src:a.agent.avatar_url,alt:a.agent.name,className:"h-12 w-12 rounded-full object-cover"}):e.jsx("div",{className:"h-12 w-12 rounded-full bg-white/20 flex items-center justify-center",children:e.jsx(el,{className:"h-6 w-6 text-white"})}),e.jsxs("div",{className:"pr-2",children:[e.jsx("p",{className:"text-[11px] uppercase tracking-widest text-white/60",children:"Listing Agent"}),e.jsx("p",{className:"text-white font-medium leading-tight",children:a.agent.name}),yt&&e.jsx("p",{className:"text-xs text-white/60",children:yt})]}),e.jsx($,{size:"sm",onClick:()=>oe(!0),className:"bg-white text-neutral-900 hover:bg-white/90 rounded-full h-9 px-4",children:"Contact"})]})]}),e.jsxs("div",{className:"mt-10 flex items-center gap-2 text-white/50 text-xs uppercase tracking-widest",children:[e.jsx("span",{className:"h-px w-8 bg-white/30"}),"Scroll to explore"]})]})})]}),wt("stats")&&e.jsx("section",{className:"border-b border-white/10 bg-neutral-950",children:e.jsx("div",{className:"max-w-7xl mx-auto px-4 sm:px-8 py-8 grid grid-cols-2 md:grid-cols-5 gap-6",children:[a.bedrooms&&{icon:Yw,label:"Bedrooms",value:a.bedrooms},a.bathrooms&&{icon:p0,label:"Bathrooms",value:a.bathrooms},a.square_footage&&{icon:w_,label:"Interior",value:`${lG(a.square_footage)} sqft`},a.lot_size&&{icon:b3,label:"Lot Size",value:a.lot_size},a.year_built&&{icon:ha,label:"Year Built",value:a.year_built},!a.year_built&&a.square_footage&&{icon:C5,label:"Price / sqft",value:`$${lG(Math.round(a.price/a.square_footage))}`}].filter(Boolean).slice(0,5).map((gt,rs)=>e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-full bg-white/5 border border-white/10 flex items-center justify-center shrink-0",children:e.jsx(gt.icon,{className:"h-4 w-4 text-white/70"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] uppercase tracking-widest text-white/50",children:gt.label}),e.jsx("p",{className:"font-display text-2xl text-white font-light",children:gt.value})]})]},rs))})}),e.jsxs("div",{className:"max-w-7xl mx-auto px-4 sm:px-8 py-16 grid lg:grid-cols-3 gap-12",children:[e.jsxs("div",{className:"lg:col-span-2 space-y-20",children:[wt("story")&&ut&&e.jsxs("section",{id:"story",children:[e.jsx("p",{className:"text-[11px] uppercase tracking-[0.3em] text-white/40 mb-3",children:"The Story"}),e.jsx("h2",{className:"font-display text-3xl sm:text-4xl font-light mb-6 text-white",children:"A closer look at this home"}),e.jsx("div",{className:"prose prose-invert prose-lg max-w-none",children:e.jsx("p",{className:"text-white/75 leading-relaxed whitespace-pre-wrap",children:et})}),nt&&e.jsx("button",{onClick:()=>le(!te),className:"mt-4 text-sm text-white/60 hover:text-white underline underline-offset-4",children:te?"Show less":"Read more"}),e.jsxs("div",{className:"mt-8 flex flex-wrap gap-2",children:[e.jsxs(qe,{variant:"outline",className:"border-white/20 text-white/80 bg-white/5",children:[e.jsx(Gi,{className:"h-3 w-3 mr-1.5"}),alt[a.property_type]]}),a.has_hoa&&e.jsx(qe,{variant:"outline",className:"border-white/20 text-white/80 bg-white/5",children:"HOA"}),a.mls_link&&e.jsx($,{variant:"outline",size:"sm",asChild:!0,className:"ml-2 border-white/20 bg-white/5 text-white hover:bg-white/15",children:e.jsxs("a",{href:a.mls_link,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(Ir,{className:"h-3.5 w-3.5 mr-1.5"})," MLS"]})})]}),(Ft||a.agent_notes&&a.agent_notes_public)&&e.jsxs("div",{className:"mt-10 rounded-2xl border border-white/10 bg-white/5 p-6",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(kn,{className:"h-4 w-4 text-amber-300"}),e.jsx("p",{className:"text-[11px] uppercase tracking-[0.25em] text-white/60",children:"A note from the agent"})]}),e.jsxs("p",{className:"text-white/80 whitespace-pre-wrap leading-relaxed italic font-display",children:['"',Ft||a.agent_notes,'"']})]})]}),wt("gallery")&&je.length>1&&e.jsxs("section",{id:"gallery",children:[e.jsxs("div",{className:"flex items-end justify-between mb-6",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] uppercase tracking-[0.3em] text-white/40 mb-2",children:"Gallery"}),e.jsx("h2",{className:"font-display text-3xl sm:text-4xl font-light text-white",children:"Every angle, every detail"})]}),e.jsxs("button",{onClick:()=>se(0),className:"text-sm text-white/60 hover:text-white underline underline-offset-4 hidden sm:inline",children:["View all ",je.length]})]}),e.jsx("div",{className:"grid grid-cols-4 gap-2 sm:gap-3",children:je.slice(0,7).map((gt,rs)=>{const Ns=["col-span-4 sm:col-span-2 sm:row-span-2 aspect-square sm:aspect-auto","col-span-2 sm:col-span-2 aspect-[4/3]","col-span-2 sm:col-span-2 aspect-[4/3]","col-span-2 sm:col-span-1 aspect-square","col-span-2 sm:col-span-1 aspect-square","col-span-2 sm:col-span-1 aspect-square","col-span-2 sm:col-span-1 aspect-square"],us=rs===6&&je.length>7;return e.jsxs("button",{onClick:()=>se(rs),className:`${Ns[rs]} relative rounded-xl overflow-hidden group bg-neutral-900`,children:[e.jsx("img",{src:gt.photo_url,alt:`Photo ${rs+1}`,className:"absolute inset-0 h-full w-full object-cover group-hover:scale-[1.04] transition-transform duration-500"}),us&&e.jsxs("div",{className:"absolute inset-0 bg-black/60 flex flex-col items-center justify-center text-white",children:[e.jsx(g0,{className:"h-6 w-6 mb-1"}),e.jsxs("span",{className:"font-medium",children:["+",je.length-7," more"]})]})]},gt.id)})})]}),wt("video")&&((dt=a.video)==null?void 0:dt.playback_url)&&e.jsxs("section",{id:"video",children:[e.jsx("p",{className:"text-[11px] uppercase tracking-[0.3em] text-white/40 mb-2",children:"Video Tour"}),e.jsx("h2",{className:"font-display text-3xl sm:text-4xl font-light text-white mb-6",children:"Walk through the home"}),e.jsx("div",{className:"relative rounded-2xl overflow-hidden bg-black shadow-2xl aspect-video",children:e.jsx("iframe",{src:a.video.playback_url,className:"absolute inset-0 h-full w-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0,title:"Video Tour"})})]}),wt("map")&&tt&&e.jsxs("section",{id:"map",children:[e.jsx("p",{className:"text-[11px] uppercase tracking-[0.3em] text-white/40 mb-2",children:"Location"}),e.jsxs("h2",{className:"font-display text-3xl sm:text-4xl font-light text-white mb-6",children:[a.neighborhood?a.neighborhood:a.city,", ",a.state]}),e.jsx("div",{className:"rounded-2xl overflow-hidden border border-white/10 shadow-2xl aspect-[16/10]",children:e.jsx("iframe",{src:tt,className:"w-full h-full grayscale-[.2] contrast-[1.05]",loading:"lazy",title:"Map"})}),e.jsxs("div",{className:"mt-4 flex items-center gap-2 text-white/60 text-sm",children:[e.jsx(Si,{className:"h-4 w-4"}),a.property_address?`${a.property_address}, `:"",a.city,", ",a.state]})]}),wt("payment")&&e.jsxs("section",{id:"payment",children:[e.jsx("p",{className:"text-[11px] uppercase tracking-[0.3em] text-white/40 mb-2",children:"Payment"}),e.jsx("h2",{className:"font-display text-3xl sm:text-4xl font-light text-white mb-6",children:"Estimate your monthly"}),e.jsxs("div",{className:"rounded-2xl border border-white/10 bg-gradient-to-br from-white/5 to-transparent p-6 sm:p-8",children:[e.jsxs("div",{className:"flex items-baseline gap-3 mb-8",children:[e.jsxs("p",{className:"font-display text-5xl sm:text-6xl font-light text-white",children:["$",lG(Math.round(Ee))]}),e.jsx("p",{className:"text-white/60",children:"/ month"})]}),e.jsxs("div",{className:"grid sm:grid-cols-3 gap-8",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(re,{className:"text-white/70 text-xs uppercase tracking-widest",children:"Down Payment"}),e.jsxs("span",{className:"text-white font-medium",children:[fe,"%"]})]}),e.jsx(sx,{value:[fe],onValueChange:gt=>_e(gt[0]),min:0,max:50,step:1}),e.jsxs("p",{className:"text-xs text-white/50 mt-2",children:["$",lG(Math.round(a.price*fe/100))," down"]})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(re,{className:"text-white/70 text-xs uppercase tracking-widest",children:"Interest Rate"}),e.jsxs("span",{className:"text-white font-medium",children:[ve.toFixed(2),"%"]})]}),e.jsx(sx,{value:[ve],onValueChange:gt=>he(gt[0]),min:2,max:10,step:.125})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(re,{className:"text-white/70 text-xs uppercase tracking-widest",children:"Loan Term"}),e.jsxs("span",{className:"text-white font-medium",children:[Se," yr"]})]}),e.jsx(sx,{value:[Se],onValueChange:gt=>Te(gt[0]),min:10,max:30,step:5})]})]}),e.jsx("p",{className:"text-xs text-white/40 mt-6",children:"Estimated principal & interest only. Taxes, insurance, and HOA not included."})]})]}),rt.map(gt=>{const rs=gt.type,Ns=gt.data||{};if(rs==="extra_video"&&Ns.url){const us=String(Ns.url).includes("youtu")?`https://www.youtube.com/embed/${String(Ns.url).split(/[/=]/).pop()}`:Ns.url;return e.jsxs("section",{children:[e.jsx("p",{className:"text-[11px] uppercase tracking-[0.3em] text-white/40 mb-2",children:Ns.eyebrow||"Featured Video"}),e.jsx("h2",{className:"font-display text-3xl sm:text-4xl font-light text-white mb-6",children:Ns.title||"Watch"}),e.jsx("div",{className:"relative rounded-2xl overflow-hidden bg-black shadow-2xl aspect-video",children:e.jsx("iframe",{src:us,className:"absolute inset-0 h-full w-full",allowFullScreen:!0,title:Ns.title||"Video"})})]},gt.id)}return rs==="3d_tour"&&Ns.url?e.jsxs("section",{children:[e.jsx("p",{className:"text-[11px] uppercase tracking-[0.3em] text-white/40 mb-2",children:"3D Tour"}),e.jsx("h2",{className:"font-display text-3xl sm:text-4xl font-light text-white mb-6",children:Ns.title||"Step inside"}),e.jsx("div",{className:"relative rounded-2xl overflow-hidden bg-black shadow-2xl aspect-video",children:e.jsx("iframe",{src:Ns.url,className:"absolute inset-0 h-full w-full",allowFullScreen:!0,title:"3D Tour"})})]},gt.id):rs==="floor_plan"&&Ns.image_url?e.jsxs("section",{children:[e.jsx("p",{className:"text-[11px] uppercase tracking-[0.3em] text-white/40 mb-2",children:"Floor Plan"}),e.jsx("h2",{className:"font-display text-3xl sm:text-4xl font-light text-white mb-6",children:Ns.title||"Layout"}),e.jsx("img",{src:Ns.image_url,alt:"Floor plan",className:"w-full rounded-2xl border border-white/10"})]},gt.id):rs==="testimonial"&&Ns.quote?e.jsxs("section",{className:"rounded-2xl border border-white/10 bg-white/[0.03] p-8",children:[e.jsxs("p",{className:"font-display italic text-2xl text-white/90 leading-relaxed",children:['"',Ns.quote,'"']}),Ns.author&&e.jsxs("p",{className:"mt-4 text-sm text-white/60",children:["— ",Ns.author]})]},gt.id):rs==="custom_cta"&&Ns.label?e.jsxs("section",{className:"rounded-2xl p-8 text-center",style:{background:Ut?`${Ut}22`:"rgba(255,255,255,0.05)",border:`1px solid ${Ut||"rgba(255,255,255,0.1)"}`},children:[Ns.title&&e.jsx("h3",{className:"font-display text-3xl text-white mb-4",children:Ns.title}),e.jsx($,{asChild:!0,size:"lg",style:Ut?{background:Ut}:void 0,children:e.jsx("a",{href:Ns.url||"#agent",children:Ns.label})})]},gt.id):null})]}),e.jsxs("aside",{id:"agent",className:"lg:sticky lg:top-24 lg:self-start space-y-6",children:[a.agent&&e.jsxs("div",{className:"rounded-2xl border border-white/10 bg-white/[0.03] p-6 backdrop-blur",children:[e.jsxs("div",{className:"flex items-start gap-4",children:[a.agent.avatar_url?e.jsx("img",{src:a.agent.avatar_url,alt:a.agent.name,className:"h-16 w-16 rounded-full object-cover border-2 border-white/20"}):e.jsx("div",{className:"h-16 w-16 rounded-full bg-white/10 flex items-center justify-center border-2 border-white/20",children:e.jsx(el,{className:"h-7 w-7 text-white/70"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-widest text-white/50",children:"Listing Agent"}),e.jsx("p",{className:"font-display text-xl text-white font-medium leading-tight",children:a.agent.name}),yt&&e.jsx("p",{className:"text-sm text-white/60 mt-0.5",children:yt})]})]}),e.jsxs("div",{className:"mt-4 grid grid-cols-2 gap-2",children:[a.agent.phone&&e.jsx($,{asChild:!0,variant:"outline",size:"sm",className:"border-white/20 bg-white/5 text-white hover:bg-white/15",children:e.jsxs("a",{href:`tel:${a.agent.phone}`,children:[e.jsx(ka,{className:"h-3.5 w-3.5 mr-1.5"}),"Call"]})}),a.agent.email&&e.jsx($,{asChild:!0,variant:"outline",size:"sm",className:"border-white/20 bg-white/5 text-white hover:bg-white/15",children:e.jsxs("a",{href:`mailto:${a.agent.email}`,children:[e.jsx(pn,{className:"h-3.5 w-3.5 mr-1.5"}),"Email"]})})]})]}),a.co_agent_name&&e.jsxs("div",{className:"rounded-2xl border border-white/10 bg-white/[0.03] p-6 backdrop-blur",children:[e.jsxs("div",{className:"flex items-start gap-4",children:[a.co_agent_photo_url?e.jsx("img",{src:a.co_agent_photo_url,alt:a.co_agent_name,className:"h-16 w-16 rounded-full object-cover border-2 border-white/20"}):e.jsx("div",{className:"h-16 w-16 rounded-full bg-white/10 flex items-center justify-center border-2 border-white/20",children:e.jsx(el,{className:"h-7 w-7 text-white/70"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-widest text-white/50",children:"Co-Listing Agent"}),e.jsx("p",{className:"font-display text-xl text-white font-medium leading-tight",children:a.co_agent_name}),a.co_agent_brokerage&&e.jsx("p",{className:"text-sm text-white/60 mt-0.5",children:a.co_agent_brokerage})]})]}),(a.co_agent_phone||a.co_agent_email)&&e.jsxs("div",{className:"mt-4 grid grid-cols-2 gap-2",children:[a.co_agent_phone&&e.jsx($,{asChild:!0,variant:"outline",size:"sm",className:"border-white/20 bg-white/5 text-white hover:bg-white/15",children:e.jsxs("a",{href:`tel:${a.co_agent_phone}`,children:[e.jsx(ka,{className:"h-3.5 w-3.5 mr-1.5"}),"Call"]})}),a.co_agent_email&&e.jsx($,{asChild:!0,variant:"outline",size:"sm",className:"border-white/20 bg-white/5 text-white hover:bg-white/15",children:e.jsxs("a",{href:`mailto:${a.co_agent_email}`,children:[e.jsx(pn,{className:"h-3.5 w-3.5 mr-1.5"}),"Email"]})})]})]}),e.jsx("div",{id:"contact",className:"rounded-2xl border border-white/10 bg-white text-neutral-900 p-6 shadow-2xl",children:e.jsx(ilt,{submitted:G,activeTab:R,setActiveTab:O,firstName:d,setFirstName:u,lastName:h,setLastName:m,email:p,setEmail:g,phone:x,setPhone:y,message:v,setMessage:_,preferredDate:j,setPreferredDate:C,preferredTime:A,setPreferredTime:M,showingMode:I,setShowingMode:P,isSubmitting:B,onSubmit:ke})})]})]}),e.jsxs("div",{className:"lg:hidden fixed bottom-0 inset-x-0 z-40 bg-neutral-950/95 backdrop-blur-xl border-t border-white/10 px-4 py-3 flex items-center gap-2 safe-area-inset-bottom",children:[((jt=a.agent)==null?void 0:jt.phone)&&e.jsx($,{asChild:!0,variant:"outline",size:"sm",className:"border-white/20 bg-white/5 text-white hover:bg-white/15 flex-1",children:e.jsxs("a",{href:`tel:${a.agent.phone}`,children:[e.jsx(ka,{className:"h-4 w-4 mr-1.5"}),"Call"]})}),e.jsxs($,{onClick:()=>oe(!0),className:"bg-white text-neutral-900 hover:bg-white/90 flex-[2] font-medium",children:[e.jsx(wm,{className:"h-4 w-4 mr-1.5"}),"Request Tour"]})]}),e.jsx("footer",{className:"border-t border-white/10 py-10 mt-24 mb-16 lg:mb-0",children:e.jsxs("div",{className:"max-w-7xl mx-auto px-4 sm:px-8 flex flex-col sm:flex-row items-center justify-between gap-4 text-sm text-white/50",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("img",{src:rlt,alt:"LevelUp",className:"h-6 opacity-80"}),e.jsxs("span",{children:["© ",new Date().getFullYear()," LevelUp"]})]}),e.jsx("a",{href:"https://relevelup.com",target:"_blank",rel:"noopener noreferrer",className:"hover:text-white",children:"relevelup.com"})]})}),e.jsx(zs,{open:Y!==null,onOpenChange:()=>se(null),children:e.jsxs(Rs,{className:"max-w-6xl p-0 bg-black/95 border-0",children:[e.jsx(Vs,{className:"sr-only",children:e.jsx($s,{children:"Photo Gallery"})}),e.jsx("button",{onClick:()=>se(null),className:"absolute right-4 top-4 z-50 rounded-full bg-white/10 hover:bg-white/20 p-2 text-white",children:e.jsx(mr,{className:"h-5 w-5"})}),Y!==null&&je[Y]&&e.jsxs("div",{className:"relative",children:[e.jsx("img",{src:je[Y].photo_url,alt:`Photo ${Y+1}`,className:"w-full max-h-[85vh] object-contain"}),je.length>1&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:Fe,className:"absolute left-4 top-1/2 -translate-y-1/2 rounded-full bg-white/10 hover:bg-white/20 p-3 text-white",children:e.jsx(Ld,{className:"h-6 w-6"})}),e.jsx("button",{onClick:Oe,className:"absolute right-4 top-1/2 -translate-y-1/2 rounded-full bg-white/10 hover:bg-white/20 p-3 text-white",children:e.jsx(fi,{className:"h-6 w-6"})}),e.jsxs("div",{className:"absolute bottom-4 left-1/2 -translate-x-1/2 text-white bg-black/60 px-3 py-1 rounded-full text-sm",children:[Y+1," / ",je.length]})]})]})]})}),e.jsx(zs,{open:ee,onOpenChange:oe,children:e.jsxs(Rs,{className:"max-w-md p-0 bg-white text-neutral-900",children:[e.jsx(Vs,{className:"sr-only",children:e.jsx($s,{children:"Contact the agent"})}),e.jsx("div",{className:"p-6",children:e.jsx(ilt,{submitted:G,activeTab:R,setActiveTab:O,firstName:d,setFirstName:u,lastName:h,setLastName:m,email:p,setEmail:g,phone:x,setPhone:y,message:v,setMessage:_,preferredDate:j,setPreferredDate:C,preferredTime:A,setPreferredTime:M,showingMode:I,setShowingMode:P,isSubmitting:B,onSubmit:ke})})]})})]})]})}function ilt(s){const{submitted:t,activeTab:n,setActiveTab:r,firstName:a,setFirstName:i,lastName:l,setLastName:o,email:c,setEmail:d,phone:u,setPhone:h,message:m,setMessage:p,preferredDate:g,setPreferredDate:x,preferredTime:y,setPreferredTime:v,showingMode:_,setShowingMode:j,isSubmitting:C,onSubmit:A}=s;return t?e.jsxs("div",{className:"text-center py-6",children:[e.jsx("div",{className:"h-14 w-14 rounded-full bg-emerald-100 flex items-center justify-center mx-auto mb-3",children:e.jsx(ma,{className:"h-7 w-7 text-emerald-600"})}),e.jsx("p",{className:"font-display text-2xl font-medium mb-1",children:n==="showing"?"Showing request sent!":"Thanks — you're all set!"}),e.jsx("p",{className:"text-sm text-neutral-600",children:n==="showing"?"The listing agent will reach out to confirm your showing time.":"The listing agent will contact you shortly with more details."})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-[0.25em] text-neutral-500 mb-1",children:"Interested?"}),e.jsx("h3",{className:"font-display text-2xl font-medium",children:"Talk to the listing agent"})]}),e.jsxs(ya,{value:n,onValueChange:M=>r(M),children:[e.jsxs(va,{className:"grid w-full grid-cols-2 mb-4",children:[e.jsxs(is,{value:"info",className:"gap-1.5",children:[e.jsx(bo,{className:"h-3.5 w-3.5"})," Get Info"]}),e.jsxs(is,{value:"showing",className:"gap-1.5",children:[e.jsx(wm,{className:"h-3.5 w-3.5"})," Request Tour"]})]}),e.jsxs("form",{onSubmit:A,className:"space-y-3",children:[e.jsxs(cs,{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(re,{htmlFor:"preferredDate",children:"Preferred Date *"}),e.jsx(be,{id:"preferredDate",type:"date",value:g,onChange:M=>x(M.target.value),min:new Date().toISOString().split("T")[0],required:n==="showing"})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"preferredTime",children:"Preferred Time"}),e.jsxs(bs,{value:y,onValueChange:v,children:[e.jsx(ys,{id:"preferredTime",children:e.jsx(_s,{placeholder:"Any time"})}),e.jsxs(vs,{children:[e.jsx(We,{value:"morning",children:"Morning (9am–12pm)"}),e.jsx(We,{value:"afternoon",children:"Afternoon (12pm–5pm)"}),e.jsx(We,{value:"evening",children:"Evening (5pm–8pm)"})]})]})]})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"showingMode",children:"Tour Type"}),e.jsxs(bs,{value:_,onValueChange:M=>j(M),children:[e.jsx(ys,{id:"showingMode",children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"in_person",children:"🏡 In-person showing"}),e.jsx(We,{value:"video",children:"📱 Video tour (FaceTime/Zoom)"}),e.jsx(We,{value:"either",children:"Either works for me"})]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(re,{htmlFor:"firstName",children:"First Name *"}),e.jsx(be,{id:"firstName",value:a,onChange:M=>i(M.target.value),required:!0})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"lastName",children:"Last Name"}),e.jsx(be,{id:"lastName",value:l,onChange:M=>o(M.target.value)})]})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"email",children:"Email *"}),e.jsx(be,{id:"email",type:"email",value:c,onChange:M=>d(M.target.value),required:!0})]}),e.jsxs("div",{children:[e.jsxs(re,{htmlFor:"phone",children:["Phone ",n==="showing"&&"*"]}),e.jsx(be,{id:"phone",type:"tel",value:u,onChange:M=>h(M.target.value),required:n==="showing"})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"message",children:n==="showing"?"Anything else?":"Message (optional)"}),e.jsx(Ls,{id:"message",value:m,onChange:M=>p(M.target.value),rows:2})]}),e.jsx($,{type:"submit",disabled:C,className:"w-full bg-neutral-900 hover:bg-neutral-800 text-white h-11",children:C?"Sending…":n==="showing"?"Request Showing":"Get More Info"}),e.jsx("p",{className:"text-[11px] text-neutral-500 text-center",children:"The listing agent will contact you directly. No spam."})]})]})]})}const mSe="/assets/levelup-logo-white-C2RAgAoG.png",zws="/assets/listings-hero-noir-BHCJrhvU.jpg";var ZAt={exports:{}};(function(s,t){(function(n,r){s.exports=r()})(jf,function(){let n,r,a;typeof self<"u"&&(self.__mapboxImport=o=>import(o));function i(o,c){if(!n)n=c;else if(!r)r=c;else{const d={};n(void 0,d),a=c(d);const u="self.onerror = function() { console.error('An error occurred while parsing the WebWorker bundle. This is most likely due to improper transpilation by Babel; please see https://docs.mapbox.com/mapbox-gl-js/guides/install/#transpiling'); }; var sharedChunk = {}; self.__mapboxImport = (u) => import(u); ("+n+")(undefined, sharedChunk); ("+r+")(undefined, sharedChunk); self.onerror = null;";typeof window<"u"&&window&&window.URL&&window.URL.createObjectURL&&(a.workerUrl=window.URL.createObjectURL(new Blob([u],{type:"text/javascript"})))}}i(["require","exports"],function(o,c){var d="3.29.0",u=1e-6,h=typeof Float32Array<"u"?Float32Array:Array;function m(w,f){var b=f[0],S=f[1],T=f[2],D=f[3],F=b*D-T*S;return F?(w[0]=D*(F=1/F),w[1]=-S*F,w[2]=-T*F,w[3]=b*F,w):null}function p(){var w=new h(9);return h!=Float32Array&&(w[1]=0,w[2]=0,w[3]=0,w[5]=0,w[6]=0,w[7]=0),w[0]=1,w[4]=1,w[8]=1,w}function g(w,f,b){var S=f[0],T=f[1],D=f[2],F=f[3],q=f[4],K=f[5],X=f[6],ce=f[7],pe=f[8],xe=b[0],Ne=b[1],Me=b[2],ze=b[3],Ve=b[4],Je=b[5],lt=b[6],ht=b[7],ct=b[8];return w[0]=xe*S+Ne*F+Me*X,w[1]=xe*T+Ne*q+Me*ce,w[2]=xe*D+Ne*K+Me*pe,w[3]=ze*S+Ve*F+Je*X,w[4]=ze*T+Ve*q+Je*ce,w[5]=ze*D+Ve*K+Je*pe,w[6]=lt*S+ht*F+ct*X,w[7]=lt*T+ht*q+ct*ce,w[8]=lt*D+ht*K+ct*pe,w}function x(w,f){var b=Math.sin(f),S=Math.cos(f);return w[0]=S,w[1]=b,w[2]=0,w[3]=-b,w[4]=S,w[5]=0,w[6]=0,w[7]=0,w[8]=1,w}function y(){var w=new h(16);return h!=Float32Array&&(w[1]=0,w[2]=0,w[3]=0,w[4]=0,w[6]=0,w[7]=0,w[8]=0,w[9]=0,w[11]=0,w[12]=0,w[13]=0,w[14]=0),w[0]=1,w[5]=1,w[10]=1,w[15]=1,w}function v(w){var f=new h(16);return f[0]=w[0],f[1]=w[1],f[2]=w[2],f[3]=w[3],f[4]=w[4],f[5]=w[5],f[6]=w[6],f[7]=w[7],f[8]=w[8],f[9]=w[9],f[10]=w[10],f[11]=w[11],f[12]=w[12],f[13]=w[13],f[14]=w[14],f[15]=w[15],f}function _(w,f){return w[0]=f[0],w[1]=f[1],w[2]=f[2],w[3]=f[3],w[4]=f[4],w[5]=f[5],w[6]=f[6],w[7]=f[7],w[8]=f[8],w[9]=f[9],w[10]=f[10],w[11]=f[11],w[12]=f[12],w[13]=f[13],w[14]=f[14],w[15]=f[15],w}function j(w){return w[0]=1,w[1]=0,w[2]=0,w[3]=0,w[4]=0,w[5]=1,w[6]=0,w[7]=0,w[8]=0,w[9]=0,w[10]=1,w[11]=0,w[12]=0,w[13]=0,w[14]=0,w[15]=1,w}function C(w,f){if(w===f){var b=f[1],S=f[2],T=f[3],D=f[6],F=f[7],q=f[11];w[1]=f[4],w[2]=f[8],w[3]=f[12],w[4]=b,w[6]=f[9],w[7]=f[13],w[8]=S,w[9]=D,w[11]=f[14],w[12]=T,w[13]=F,w[14]=q}else w[0]=f[0],w[1]=f[4],w[2]=f[8],w[3]=f[12],w[4]=f[1],w[5]=f[5],w[6]=f[9],w[7]=f[13],w[8]=f[2],w[9]=f[6],w[10]=f[10],w[11]=f[14],w[12]=f[3],w[13]=f[7],w[14]=f[11],w[15]=f[15];return w}function A(w,f){var b=f[0],S=f[1],T=f[2],D=f[3],F=f[4],q=f[5],K=f[6],X=f[7],ce=f[8],pe=f[9],xe=f[10],Ne=f[11],Me=f[12],ze=f[13],Ve=f[14],Je=f[15],lt=b*q-S*F,ht=b*K-T*F,ct=b*X-D*F,xt=S*K-T*q,kt=S*X-D*q,es=T*X-D*K,Ct=ce*ze-pe*Me,Lt=ce*Ve-xe*Me,Zt=ce*Je-Ne*Me,Qt=pe*Ve-xe*ze,Cs=pe*Je-Ne*ze,Fs=xe*Je-Ne*Ve,on=lt*Fs-ht*Cs+ct*Qt+xt*Zt-kt*Lt+es*Ct;return on?(w[0]=(q*Fs-K*Cs+X*Qt)*(on=1/on),w[1]=(T*Cs-S*Fs-D*Qt)*on,w[2]=(ze*es-Ve*kt+Je*xt)*on,w[3]=(xe*kt-pe*es-Ne*xt)*on,w[4]=(K*Zt-F*Fs-X*Lt)*on,w[5]=(b*Fs-T*Zt+D*Lt)*on,w[6]=(Ve*ct-Me*es-Je*ht)*on,w[7]=(ce*es-xe*ct+Ne*ht)*on,w[8]=(F*Cs-q*Zt+X*Ct)*on,w[9]=(S*Zt-b*Cs-D*Ct)*on,w[10]=(Me*kt-ze*ct+Je*lt)*on,w[11]=(pe*ct-ce*kt-Ne*lt)*on,w[12]=(q*Lt-F*Qt-K*Ct)*on,w[13]=(b*Qt-S*Lt+T*Ct)*on,w[14]=(ze*ht-Me*xt-Ve*lt)*on,w[15]=(ce*xt-pe*ht+xe*lt)*on,w):null}function M(w,f,b){var S=f[0],T=f[1],D=f[2],F=f[3],q=f[4],K=f[5],X=f[6],ce=f[7],pe=f[8],xe=f[9],Ne=f[10],Me=f[11],ze=f[12],Ve=f[13],Je=f[14],lt=f[15],ht=b[0],ct=b[1],xt=b[2],kt=b[3];return w[0]=ht*S+ct*q+xt*pe+kt*ze,w[1]=ht*T+ct*K+xt*xe+kt*Ve,w[2]=ht*D+ct*X+xt*Ne+kt*Je,w[3]=ht*F+ct*ce+xt*Me+kt*lt,w[4]=(ht=b[4])*S+(ct=b[5])*q+(xt=b[6])*pe+(kt=b[7])*ze,w[5]=ht*T+ct*K+xt*xe+kt*Ve,w[6]=ht*D+ct*X+xt*Ne+kt*Je,w[7]=ht*F+ct*ce+xt*Me+kt*lt,w[8]=(ht=b[8])*S+(ct=b[9])*q+(xt=b[10])*pe+(kt=b[11])*ze,w[9]=ht*T+ct*K+xt*xe+kt*Ve,w[10]=ht*D+ct*X+xt*Ne+kt*Je,w[11]=ht*F+ct*ce+xt*Me+kt*lt,w[12]=(ht=b[12])*S+(ct=b[13])*q+(xt=b[14])*pe+(kt=b[15])*ze,w[13]=ht*T+ct*K+xt*xe+kt*Ve,w[14]=ht*D+ct*X+xt*Ne+kt*Je,w[15]=ht*F+ct*ce+xt*Me+kt*lt,w}function I(w,f,b){var S,T,D,F,q,K,X,ce,pe,xe,Ne,Me,ze=b[0],Ve=b[1],Je=b[2];return f===w?(w[12]=f[0]*ze+f[4]*Ve+f[8]*Je+f[12],w[13]=f[1]*ze+f[5]*Ve+f[9]*Je+f[13],w[14]=f[2]*ze+f[6]*Ve+f[10]*Je+f[14],w[15]=f[3]*ze+f[7]*Ve+f[11]*Je+f[15]):(T=f[1],D=f[2],F=f[3],q=f[4],K=f[5],X=f[6],ce=f[7],pe=f[8],xe=f[9],Ne=f[10],Me=f[11],w[0]=S=f[0],w[1]=T,w[2]=D,w[3]=F,w[4]=q,w[5]=K,w[6]=X,w[7]=ce,w[8]=pe,w[9]=xe,w[10]=Ne,w[11]=Me,w[12]=S*ze+q*Ve+pe*Je+f[12],w[13]=T*ze+K*Ve+xe*Je+f[13],w[14]=D*ze+X*Ve+Ne*Je+f[14],w[15]=F*ze+ce*Ve+Me*Je+f[15]),w}function P(w,f,b){var S=b[0],T=b[1],D=b[2];return w[0]=f[0]*S,w[1]=f[1]*S,w[2]=f[2]*S,w[3]=f[3]*S,w[4]=f[4]*T,w[5]=f[5]*T,w[6]=f[6]*T,w[7]=f[7]*T,w[8]=f[8]*D,w[9]=f[9]*D,w[10]=f[10]*D,w[11]=f[11]*D,w[12]=f[12],w[13]=f[13],w[14]=f[14],w[15]=f[15],w}function R(w,f,b){var S=Math.sin(b),T=Math.cos(b),D=f[4],F=f[5],q=f[6],K=f[7],X=f[8],ce=f[9],pe=f[10],xe=f[11];return f!==w&&(w[0]=f[0],w[1]=f[1],w[2]=f[2],w[3]=f[3],w[12]=f[12],w[13]=f[13],w[14]=f[14],w[15]=f[15]),w[4]=D*T+X*S,w[5]=F*T+ce*S,w[6]=q*T+pe*S,w[7]=K*T+xe*S,w[8]=X*T-D*S,w[9]=ce*T-F*S,w[10]=pe*T-q*S,w[11]=xe*T-K*S,w}function O(w,f,b){var S=Math.sin(b),T=Math.cos(b),D=f[0],F=f[1],q=f[2],K=f[3],X=f[8],ce=f[9],pe=f[10],xe=f[11];return f!==w&&(w[4]=f[4],w[5]=f[5],w[6]=f[6],w[7]=f[7],w[12]=f[12],w[13]=f[13],w[14]=f[14],w[15]=f[15]),w[0]=D*T-X*S,w[1]=F*T-ce*S,w[2]=q*T-pe*S,w[3]=K*T-xe*S,w[8]=D*S+X*T,w[9]=F*S+ce*T,w[10]=q*S+pe*T,w[11]=K*S+xe*T,w}function B(w,f,b){var S=Math.sin(b),T=Math.cos(b),D=f[0],F=f[1],q=f[2],K=f[3],X=f[4],ce=f[5],pe=f[6],xe=f[7];return f!==w&&(w[8]=f[8],w[9]=f[9],w[10]=f[10],w[11]=f[11],w[12]=f[12],w[13]=f[13],w[14]=f[14],w[15]=f[15]),w[0]=D*T+X*S,w[1]=F*T+ce*S,w[2]=q*T+pe*S,w[3]=K*T+xe*S,w[4]=X*T-D*S,w[5]=ce*T-F*S,w[6]=pe*T-q*S,w[7]=xe*T-K*S,w}function U(w,f){return w[0]=1,w[1]=0,w[2]=0,w[3]=0,w[4]=0,w[5]=1,w[6]=0,w[7]=0,w[8]=0,w[9]=0,w[10]=1,w[11]=0,w[12]=f[0],w[13]=f[1],w[14]=f[2],w[15]=1,w}function G(w,f){return w[0]=f[0],w[1]=0,w[2]=0,w[3]=0,w[4]=0,w[5]=f[1],w[6]=0,w[7]=0,w[8]=0,w[9]=0,w[10]=f[2],w[11]=0,w[12]=0,w[13]=0,w[14]=0,w[15]=1,w}function H(w,f,b){var S,T,D,F=b[0],q=b[1],K=b[2],X=Math.sqrt(F*F+q*q+K*K);return X0?(Ve=2*Math.sqrt(ze+1),w[3]=.25*Ve,w[0]=(pe-Ne)/Ve,w[1]=(xe-K)/Ve,w[2]=(q-X)/Ve):F>ce&&F>Me?(Ve=2*Math.sqrt(1+F-ce-Me),w[3]=(pe-Ne)/Ve,w[0]=.25*Ve,w[1]=(q+X)/Ve,w[2]=(xe+K)/Ve):ce>Me?(Ve=2*Math.sqrt(1+ce-F-Me),w[3]=(xe-K)/Ve,w[0]=(q+X)/Ve,w[1]=.25*Ve,w[2]=(pe+Ne)/Ve):(Ve=2*Math.sqrt(1+Me-F-ce),w[3]=(q-X)/Ve,w[0]=(xe+K)/Ve,w[1]=(pe+Ne)/Ve,w[2]=.25*Ve),w}function ee(w,f){var b=f[0],S=f[1],T=f[2],D=f[3],F=b+b,q=S+S,K=T+T,X=b*F,ce=S*F,pe=S*q,xe=T*F,Ne=T*q,Me=T*K,ze=D*F,Ve=D*q,Je=D*K;return w[0]=1-pe-Me,w[1]=ce+Je,w[2]=xe-Ve,w[3]=0,w[4]=ce-Je,w[5]=1-X-Me,w[6]=Ne+ze,w[7]=0,w[8]=xe+Ve,w[9]=Ne-ze,w[10]=1-X-pe,w[11]=0,w[12]=0,w[13]=0,w[14]=0,w[15]=1,w}var oe=function(w,f,b,S,T){var D=1/Math.tan(f/2);if(w[0]=D/b,w[1]=0,w[2]=0,w[3]=0,w[4]=0,w[5]=D,w[6]=0,w[7]=0,w[8]=0,w[9]=0,w[11]=-1,w[12]=0,w[13]=0,w[15]=0,T!=null&&T!==1/0){var F=1/(S-T);w[10]=(T+S)*F,w[14]=2*T*S*F}else w[10]=-1,w[14]=-2*S;return w},me=function(w,f,b,S,T,D,F){var q=1/(f-b),K=1/(S-T),X=1/(D-F);return w[0]=-2*q,w[1]=0,w[2]=0,w[3]=0,w[4]=0,w[5]=-2*K,w[6]=0,w[7]=0,w[8]=0,w[9]=0,w[10]=2*X,w[11]=0,w[12]=(f+b)*q,w[13]=(T+S)*K,w[14]=(F+D)*X,w[15]=1,w},Q=M;function te(){var w=new h(3);return h!=Float32Array&&(w[0]=0,w[1]=0,w[2]=0),w}function le(w){var f=new h(3);return f[0]=w[0],f[1]=w[1],f[2]=w[2],f}function fe(w){var f=w[0],b=w[1],S=w[2];return Math.sqrt(f*f+b*b+S*S)}function _e(w,f,b){var S=new h(3);return S[0]=w,S[1]=f,S[2]=b,S}function ve(w,f,b,S){return w[0]=f,w[1]=b,w[2]=S,w}function he(w,f,b){return w[0]=f[0]+b[0],w[1]=f[1]+b[1],w[2]=f[2]+b[2],w}function Se(w,f,b){return w[0]=f[0]-b[0],w[1]=f[1]-b[1],w[2]=f[2]-b[2],w}function Te(w,f,b){return w[0]=f[0]*b[0],w[1]=f[1]*b[1],w[2]=f[2]*b[2],w}function Ie(w,f,b){return w[0]=Math.min(f[0],b[0]),w[1]=Math.min(f[1],b[1]),w[2]=Math.min(f[2],b[2]),w}function Ue(w,f,b){return w[0]=Math.max(f[0],b[0]),w[1]=Math.max(f[1],b[1]),w[2]=Math.max(f[2],b[2]),w}function Be(w,f,b){return w[0]=f[0]*b,w[1]=f[1]*b,w[2]=f[2]*b,w}function je(w,f,b,S){return w[0]=f[0]+b[0]*S,w[1]=f[1]+b[1]*S,w[2]=f[2]+b[2]*S,w}function Ye(w,f){var b=f[0]-w[0],S=f[1]-w[1],T=f[2]-w[2];return Math.sqrt(b*b+S*S+T*T)}function Ee(w,f){var b=f[0]-w[0],S=f[1]-w[1],T=f[2]-w[2];return b*b+S*S+T*T}function Re(w){var f=w[0],b=w[1],S=w[2];return f*f+b*b+S*S}function ke(w,f){return w[0]=-f[0],w[1]=-f[1],w[2]=-f[2],w}function Fe(w,f){var b=f[0],S=f[1],T=f[2],D=b*b+S*S+T*T;return D>0&&(D=1/Math.sqrt(D)),w[0]=f[0]*D,w[1]=f[1]*D,w[2]=f[2]*D,w}function Oe(w,f){return w[0]*f[0]+w[1]*f[1]+w[2]*f[2]}function Ge(w,f,b){var S=f[0],T=f[1],D=f[2],F=b[0],q=b[1],K=b[2];return w[0]=T*K-D*q,w[1]=D*F-S*K,w[2]=S*q-T*F,w}function yt(w,f,b,S){var T=f[0],D=f[1],F=f[2];return w[0]=T+S*(b[0]-T),w[1]=D+S*(b[1]-D),w[2]=F+S*(b[2]-F),w}function tt(w,f,b){var S=f[0],T=f[1],D=f[2],F=b[3]*S+b[7]*T+b[11]*D+b[15];return w[0]=(b[0]*S+b[4]*T+b[8]*D+b[12])/(F=F||1),w[1]=(b[1]*S+b[5]*T+b[9]*D+b[13])/F,w[2]=(b[2]*S+b[6]*T+b[10]*D+b[14])/F,w}function ut(w,f,b){var S=f[0],T=f[1],D=f[2];return w[0]=S*b[0]+T*b[3]+D*b[6],w[1]=S*b[1]+T*b[4]+D*b[7],w[2]=S*b[2]+T*b[5]+D*b[8],w}function nt(w,f,b){var S=b[0],T=b[1],D=b[2],F=b[3],q=f[0],K=f[1],X=f[2],ce=T*X-D*K,pe=D*q-S*X,xe=S*K-T*q;return w[0]=q+F*(ce+=ce)+T*(xe+=xe)-D*(pe+=pe),w[1]=K+F*pe+D*ce-S*xe,w[2]=X+F*xe+S*pe-T*ce,w}function et(w){return w[0]=0,w[1]=0,w[2]=0,w}function at(w,f){return w[0]===f[0]&&w[1]===f[1]&&w[2]===f[2]}var wt=Se,rt=Te,Ft=fe;function Ut(){var w=new h(4);return h!=Float32Array&&(w[0]=0,w[1]=0,w[2]=0,w[3]=0),w}function Is(w,f,b,S){var T=new h(4);return T[0]=w,T[1]=f,T[2]=b,T[3]=S,T}function xs(w,f,b){return w[0]=f[0]*b,w[1]=f[1]*b,w[2]=f[2]*b,w[3]=f[3]*b,w}function st(w,f){var b=f[0],S=f[1],T=f[2],D=f[3],F=b*b+S*S+T*T+D*D;return F>0&&(F=1/Math.sqrt(F)),w[0]=b*F,w[1]=S*F,w[2]=T*F,w[3]=D*F,w}function dt(w,f,b){var S=f[0],T=f[1],D=f[2],F=f[3];return w[0]=b[0]*S+b[4]*T+b[8]*D+b[12]*F,w[1]=b[1]*S+b[5]*T+b[9]*D+b[13]*F,w[2]=b[2]*S+b[6]*T+b[10]*D+b[14]*F,w[3]=b[3]*S+b[7]*T+b[11]*D+b[15]*F,w}function jt(){var w=new h(4);return h!=Float32Array&&(w[0]=0,w[1]=0,w[2]=0),w[3]=1,w}function gt(w){return w[0]=0,w[1]=0,w[2]=0,w[3]=1,w}function rs(w,f){var b=2*Math.acos(f[3]),S=Math.sin(b/2);return S>u?(w[0]=f[0]/S,w[1]=f[1]/S,w[2]=f[2]/S):(w[0]=1,w[1]=0,w[2]=0),b}function Ns(w,f,b){b*=.5;var S=f[0],T=f[1],D=f[2],F=f[3],q=Math.sin(b),K=Math.cos(b);return w[0]=S*K+F*q,w[1]=T*K+D*q,w[2]=D*K-T*q,w[3]=F*K-S*q,w}function us(w,f,b){b*=.5;var S=f[0],T=f[1],D=f[2],F=f[3],q=Math.sin(b),K=Math.cos(b);return w[0]=S*K-D*q,w[1]=T*K+F*q,w[2]=D*K+S*q,w[3]=F*K-T*q,w}function Bs(w,f,b){b*=.5;var S=f[0],T=f[1],D=f[2],F=f[3],q=Math.sin(b),K=Math.cos(b);return w[0]=S*K+T*q,w[1]=T*K-S*q,w[2]=D*K+F*q,w[3]=F*K-D*q,w}te(),Ut();var Ts,Fn,An,js=st,In=(Ts=te(),Fn=_e(1,0,0),An=_e(0,1,0),function(w,f,b){var S=Oe(f,b);return S<-.999999?(Ge(Ts,Fn,f),Ft(Ts)<1e-6&&Ge(Ts,An,f),Fe(Ts,Ts),function(T,D,F){F*=.5;var q=Math.sin(F);T[0]=q*D[0],T[1]=q*D[1],T[2]=q*D[2],T[3]=Math.cos(F)}(w,Ts,Math.PI),w):S>.999999?(w[0]=0,w[1]=0,w[2]=0,w[3]=1,w):(Ge(Ts,f,b),w[0]=Ts[0],w[1]=Ts[1],w[2]=Ts[2],w[3]=1+S,js(w,w))});function un(){var w=new h(2);return h!=Float32Array&&(w[0]=0,w[1]=0),w}function jr(w,f){var b=new h(2);return b[0]=w,b[1]=f,b}function Ln(w,f,b){return w[0]=f,w[1]=b,w}function Sr(w,f,b){return w[0]=f[0]+b[0],w[1]=f[1]+b[1],w}function Qn(w,f,b){return w[0]=f[0]-b[0],w[1]=f[1]-b[1],w}function En(w,f,b){return w[0]=f[0]*b,w[1]=f[1]*b,w}function pr(w){var f=w[0],b=w[1];return Math.sqrt(f*f+b*b)}function xn(w,f){var b=f[0],S=f[1],T=b*b+S*S;return T>0&&(T=1/Math.sqrt(T)),w[0]=f[0]*T,w[1]=f[1]*T,w}function Ar(w,f){return w[0]*f[0]+w[1]*f[1]}jt(),jt(),p();var Zr=Qn;function dn(w,f,b,S){const T=3*w,D=3*(b-w)-T,F=1-T-D,q=3*f,K=3*(S-f)-q,X=1-q-K;return function(ce,pe=1e-6){if(ce<=0)return 0;if(ce>=1)return 1;let xe=ce;for(let ze=0;ze<8;ze++){const Ve=((F*xe+D)*xe+T)*xe-ce;if(Math.abs(Ve)Ve?Ne=xe:Me=xe,xe=.5*(Ne+Me)}return((X*xe+K)*xe+q)*xe}}function Kt(w,f){this.x=w,this.y=f}function Er(w,f){if(Array.isArray(w)){if(!Array.isArray(f)||w.length!==f.length)return!1;for(let b=0;bb;){if(S-b>600){const K=S-b+1,X=f-b+1,ce=Math.log(K),pe=.5*Math.exp(2*ce/3),xe=.5*Math.sqrt(ce*pe*(K-pe)/K)*(X-K/2<0?-1:1);ti(w,f,Math.max(b,Math.floor(f-X*pe/K+xe)),Math.min(S,Math.floor(f+(K-X)*pe/K+xe)),T)}const D=w[f];let F=b,q=S;for(Ba(w,b,f),T(w[S],D)>0&&Ba(w,b,S);F0;)q--}T(w[b],D)===0?Ba(w,b,q):(q++,Ba(w,q,S)),q<=f&&(b=q+1),f<=q&&(S=q-1)}}function Ba(w,f,b){const S=w[f];w[f]=w[b],w[b]=S}function lo(w,f){return wf?1:0}function Yn(w){let f=0;for(let b,S,T=0,D=w.length,F=D-1;T1)for(let F=0;F=f[2]||w[1]<=f[1]||w[3]>=f[3])}function co(w,f,b){const S=w[0]-f[0],T=w[1]-f[1],D=w[0]-b[0],F=w[1]-b[1];return S*F-D*T===0&&S*D<=0&&T*F<=0}function Tn(w,f,b){return f[1]>w[1]!=b[1]>w[1]&&w[0]<(b[0]-f[0])*(w[1]-f[1])/(b[1]-f[1])+f[0]}function Mr(w,f,b=!1){let S=!1;for(let T=0,D=f.length;T0&&q<0||F<0&&q>0}function Lo(w,f,b,S){return(T=[S[0]-b[0],S[1]-b[1]])[0]*(D=[f[0]-w[0],f[1]-w[1]])[1]-T[1]*D[0]!==0&&!(!Aa(w,f,b,S)||!Aa(b,S,w,f));var T,D}function Ac(w){const f=new Kt(Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY),b=new Kt(Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY);for(const S of w[0])f.x>S.x&&(f.x=S.x),f.y>S.y&&(f.y=S.y),b.x=1)return 1;const f=w*w,b=f*w;return 4*(w<.5?b:3*(w-f)+b-.75)}const dh=dn(.25,.1,.25,1);function Jr(w,f,b){return Math.min(b,Math.max(f,w))}function Uo(w,f,b){return(b=Jr((b-w)/(f-w),0,1))*b*(3-2*b)}function fc(w,f,b){const S=b-f,T=((w-f)%S+S)%S+f;return T===f?b:T}function Lc(w,f,b){if(!w.length)return b(null,[]);let S=w.length;const T=new Array(w.length);let D=null;w.forEach((F,q)=>{f(F,(K,X)=>{K&&(D=K),T[q]=X,--S===0&&b(D,T)})})}function Ss(w,f){const b={};for(let S=0;S>f/4)).toString(16):([1e7]+-[1e3]+-4e3+-8e3+-1e11).replace(/[018]/g,w)}()}function fa(w){return w<=1?1:Math.pow(2,Math.ceil(Math.log2(w)))}function zn(w){return!!w&&To.test(w)}function Rr(w,f){w.forEach(b=>{f[b]&&(f[b]=f[b].bind(f))})}function ja(w,f,b){const S={};for(const T in w)S[T]=f.call(this,w[T],T,w);return S}function Il(w,f,b){const S={};for(const T in w)f.call(this,w[T],T,w)&&(S[T]=w[T]);return S}function zo(w){return Array.isArray(w)?w.map(zo):typeof w=="object"&&w?ja(w,zo):w}function Hl(w,f){for(let b=0;b(f.y-w.y)*(b.x-w.x)}function zh([w,f,b]){const S=_a(f+90),T=_a(b);return{x:w*Math.cos(S)*Math.sin(T),y:w*Math.sin(S)*Math.sin(T),z:w*Math.cos(T),azimuthal:f,polar:b}}function Gm(w,f,b){const S=Math.sqrt(w*w+f*f+b*b),T=S>0?Math.acos(b/S)*Ol:0;let D=w!==0||f!==0?Math.atan2(-f,-w)*Ol+90:0;return D<0&&(D+=360),[S,D,T]}function Gu(w){return(typeof self<"u"||w!==void 0)&&typeof WorkerGlobalScope<"u"&&(w!==void 0?w:self)instanceof WorkerGlobalScope}function Zd(w){const f={};if(w.replace(/(?:^|(?:\s*\,\s*))([^\x00-\x20\(\)<>@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)(?:\=(?:([^\x00-\x20\(\)<>@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)|(?:\"((?:[^"\\]|\\.)*)\")))?/g,(b,S,T,D)=>{const F=T||D;return f[S]=!F||F.toLowerCase(),""}),f["max-age"]){const b=parseInt(f["max-age"],10);isNaN(b)?delete f["max-age"]:f["max-age"]=b}return f}function Bh(w){return w?{cacheControl:w.get("cache-control"),expires:w.get("expires")}:{cacheControl:void 0,expires:void 0}}function Mg(w){try{const f=self[w];return f.setItem("_mapbox_test_",1),f.removeItem("_mapbox_test_"),!0}catch{return!1}}function Sd(w,f){return[w[4*f],w[4*f+1],w[4*f+2],w[4*f+3]]}function $h(w,f,b){w[4*f+0]=b[0],w[4*f+1]=b[1],w[4*f+2]=b[2],w[4*f+3]=b[3]}function Af(w){return[Math.pow(w[0],1/2.2),Math.pow(w[1],1/2.2),Math.pow(w[2],1/2.2)]}function Gp(w){return w>0?1/(1.001-w):1+w}function Ef(w){return w>0?1-1/(1.001-w):-w}function Wx(w,f,b){return(w-f.min)*(b.max-b.min)/(f.max-f.min)+b.min}function rl(w){return w*w*w*w*w}function to(w){return w>>>=0,w=Math.imul(2747636419^w,2654435769)>>>0,w=Math.imul(w^w>>>16,2654435769)>>>0,(w=Math.imul(w^w>>>16,2654435769)>>>0)/4294967296}let Pg,Kx,Tt,He,ot,At;function Ht(){return Pg??(Pg=self.OffscreenCanvas&&!!new OffscreenCanvas(1,1).getContext("2d")&&typeof self.createImageBitmap=="function"),Pg}const qt={requestIdleCallback:w=>{if(typeof requestIdleCallback<"u")return requestIdleCallback(w);setTimeout(()=>w({didTimeout:!1,timeRemaining:()=>50}),0)},now:()=>He!==void 0?He:performance.now(),setNow(w){He=w},restoreNow(){He=void 0},frame(w){const f=requestAnimationFrame(w);return{cancel:()=>cancelAnimationFrame(f)}},getImageData(w,f=0){const{width:b,height:S}=w;ot||(ot=document.createElement("canvas"));const T=ot.getContext("2d",{willReadFrequently:!0});if(!T)throw new Error("failed to create canvas 2d context");return(b>ot.width||S>ot.height)&&(ot.width=b,ot.height=S),T.clearRect(-f,-f,b+2*f,S+2*f),T.drawImage(w,0,0,b,S),T.getImageData(-f,-f,b+2*f,S+2*f)},resolveURL:w=>(Kx||(Kx=document.createElement("a")),Kx.href=w,Kx.href),get devicePixelRatio(){return window.devicePixelRatio},get prefersReducedMotion(){return!!window.matchMedia&&(Tt??(Tt=window.matchMedia("(prefers-reduced-motion: reduce)")),Tt.matches)},hasCanvasFingerprintNoise(){if(At!==void 0)return At;if(!Ht())return At=!1,!1;const w=new OffscreenCanvas(85,1),f=w.getContext("2d",{willReadFrequently:!0});let b=0;for(let T=0;T0?`?${D}`:""}`}const qn="mapbox-tiles";let Zn=500,la=50;const Br=["language","worldview","jobid"];let wr;function Ea(){try{return caches}catch{}}function na(){const w=Ea();w&&wr==null&&(wr=w.open(qn))}let yi=1/0;function so(w){return Xt.API_URL_REGEX.test(w)}function _i(w){return w.indexOf("mapbox:")===0}function Ni(w){return Xt.API_CDN_URL_REGEX.test(w)}function vi(w){return Xt.API_SPRITE_REGEX.test(w)}function qo(w){return Xt.API_STYLE_REGEX.test(w)&&!vi(w)}const Ro={Unknown:"Unknown",Style:"Style",Source:"Source",Tile:"Tile",Glyphs:"Glyphs",SpriteImage:"SpriteImage",SpriteJSON:"SpriteJSON",Iconset:"Iconset",Image:"Image",Model:"Model"};Object.freeze(Ro);class Ti extends Error{constructor(f,b,S){super(),this.url=S,this.statusText=f,this.status=b}get message(){return this.status===401&&so(this.url)?`${this.statusText}: you may have provided an invalid Mapbox access token. See https://docs.mapbox.com/api/guides/#access-tokens-and-token-scopes`:this.statusText}toString(){return`${this.name}: ${this.message} (${this.status}): ${this.url}`}}function jo(w){return typeof w=="object"&&w!==null&&"status"in w&&w.status===404}const Xe=Gu()?()=>self.worker.referrer:()=>(location.protocol==="blob:"?parent:self).location.href,Bt=/^\w+:/,As=/[\r\n]+/;async function Hs(w,f){let b;return b=w.type==="arrayBuffer"?await f.arrayBuffer():w.type==="json"?await f.json():await f.text(),{data:b,headers:f.headers}}async function cn(w,f){return f&&f.throwIfAborted(),(b=w.url).startsWith("file:")||Xe().startsWith("file:")&&!Bt.test(b)?async function(S,T){return new Promise((D,F)=>{const q=new XMLHttpRequest,K=()=>{T.removeEventListener("abort",K),q.abort(),F(T.reason)};T&&T.addEventListener("abort",K),q.open(S.method||"GET",S.url,!0),S.type==="arrayBuffer"&&(q.responseType="arraybuffer");for(const X in S.headers)q.setRequestHeader(X,S.headers[X]);S.type==="json"&&(q.responseType="text",q.setRequestHeader("Accept","application/json")),q.withCredentials=S.credentials==="include",q.onerror=()=>{T&&T.removeEventListener("abort",K),F(new Error(q.statusText))},q.onload=()=>{if(T&&T.removeEventListener("abort",K),(q.status>=200&&q.status<300||q.status===0)&&q.response!==null){let X=q.response;if(S.type==="json")try{X=JSON.parse(q.response)}catch(pe){return void F(pe)}const ce=new Headers;q.getAllResponseHeaders().trim().split(As).forEach(pe=>{const xe=pe.split(": "),Ne=xe.shift(),Me=xe.join(": ");Ne&&ce.set(Ne,Me)}),D({data:X,headers:ce})}else F(new Ti(q.statusText,q.status,S.url))},q.send(S.body)})}(w,f):async function(S,T){const D=new Request(S.url,{method:S.method||"GET",body:S.body,credentials:S.credentials,headers:S.headers,referrer:Xe(),referrerPolicy:S.referrerPolicy,signal:T}),F=(q=D.url).indexOf("sku=")>0&&so(q);var q;if(S.type==="json"&&D.headers.set("Accept","application/json"),F){let xe=null;try{xe=await async function(Ne){if(na(),wr==null)return null;const Me=await wr;let ze=mn(Ne.url,{persistentParams:Br});const Ve=Ne.headers.get("Range");Ve&&(ze=rn(ze,{range:Ve}));const Je=await Me.match(ze);if(!Je)return null;const lt=function(ht){if(!ht)return!1;const ct=new Date(ht.headers.get("expires")||0),xt=Zd(ht.headers.get("cache-control")||"");return Number(ct)>Date.now()&&!xt["no-cache"]}(Je);return Me.delete(ze).catch(ht=>oi(ht.message)),lt&&Me.put(ze,Je.clone()).catch(ht=>oi(ht.message)),{response:Je,fresh:lt}}(D)}catch(Ne){Ne.message!=="SecurityError"&&oi(Ne.toString())}if(xe&&xe.fresh)return T&&T.throwIfAborted(),Hs(S,xe.response)}const K=Date.now();let X;try{X=await fetch(D)}catch(xe){throw xe.name==="AbortError"?xe:new Error(`${xe.message} ${S.url}`,{cause:xe})}if(T&&T.throwIfAborted(),!X.ok)throw new Ti(X.statusText,X.status,S.url);const ce=F?X.clone():null,pe=await Hs(S,X);return ce&&async function(xe,Ne,Me){if(na(),wr==null)return;const ze=Zd(Ne.headers.get("cache-control")||"");if(ze["no-store"])return;const Ve={status:Ne.status,statusText:Ne.statusText,headers:new Headers(Ne.headers)};ze["max-age"]&&Ve.headers.set("Expires",new Date(Me+1e3*ze["max-age"]).toUTCString());const Je=Ve.headers.get("expires");if(!Je||new Date(Je).getTime()-Me<42e4)return;let lt=mn(xe.url,{persistentParams:Br});if(Ne.status===206){const xt=xe.headers.get("Range");if(!xt)return;Ve.status=200,lt=rn(lt,{range:xt})}const ht=new Response((ct=Ne.status)!==200&&ct!==404&&[101,103,204,205,304].includes(ct)?null:Ne.body,Ve);var ct;if(na(),wr!=null)try{await(await wr).put(lt,ht)}catch(xt){oi(xt.message)}}(D,ce,K),pe}(w,f);var b}async function gr(w,f){return cn(Object.assign(w,{type:"json"}),f)}async function fr(w,f){return cn(Object.assign(w,{type:"arrayBuffer"}),f)}function za(w){const f=document.createElement("a");return f.href=w,f.protocol===location.protocol&&f.host===location.host}let Rt,tn;Rt=[],tn=0;const yn="01",xr={create:"create",load:"load",fullLoad:"fullLoad"},$r={mark(w){performance.mark(w)},measure(w,f,b){performance.measure(w,f,b)}};function Ca(w){const f=w.name.split("?")[0];return Ni(f)&&f.includes("mapbox-gl.js")?"javascript":Ni(f)&&f.includes("mapbox-gl.css")?"css":function(b){return Xt.API_FONTS_REGEX.test(b)}(f)?"fontRange":vi(f)?"sprite":qo(f)?"style":function(b){return Xt.API_TILEJSON_REGEX.test(b)}(f)?"tilejson":"other"}const xa=/(\.(png|jpg)\d*)(?=$)/,Oa=/^.+\/v4\//,jl=/\.[\w]+$/,Ri=/^(\/v4\/|\/(raster|rasterarrays)\/v1\/)/,Ki=/^access_token=(.*)$/,Rc="NO_ACCESS_TOKEN",xd=/^(\w+):\/\/([^/?]*)(\/[^?]+)?\??(.+)?/;function ro(w){const f=w.match(xd);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 pc(w){const f=w.params.length?`?${w.params.join("&")}`:"";return`${w.protocol}://${w.authority}${w.path}${f}`}const ed="mapbox.eventData";function Nh(w){if(!w)return null;const f=w.split(".");if(!f||f.length!==3)return null;try{return JSON.parse(decodeURIComponent(atob(f[1]).split("").map(b=>"%"+("00"+b.charCodeAt(0).toString(16)).slice(-2)).join("")))}catch{return null}}function xu(w){return!(!Xt.EVENTS_URL||!w&&!Xt.ACCESS_TOKEN)}let Dd;const td=/^[\w.+-]+(\/[\w.+-]+)?$/;let Uh="other";class Nl{constructor(f){this.type=f,this.anonId=null,this.anonIdTimestamp=null,this.eventData={},this.queue=[],this.pendingRequest=!1}getStorageKey(f){const b=Nh(Xt.ACCESS_TOKEN);let S="";return S=b&&b.u?btoa(encodeURIComponent(b.u).replace(/%([0-9A-F]{2})/g,(T,D)=>String.fromCharCode(+("0x"+D)))):Xt.ACCESS_TOKEN||"",f?`${ed}.${f}:${S}`:`${ed}:${S}`}fetchEventData(){const f=Mg("localStorage"),b=this.getStorageKey(),S=this.getStorageKey("uuid"),T=this.getStorageKey("uuidTimestamp");if(f)try{const D=localStorage.getItem(b);D&&(this.eventData=JSON.parse(D));const F=localStorage.getItem(S);F&&(this.anonId=F);const q=localStorage.getItem(T);q&&(this.anonIdTimestamp=Number(q));const K=Date.now()-864e5;(!this.anonIdTimestamp||this.anonIdTimestamp=1&&localStorage.setItem(b,JSON.stringify(this.eventData)),F&&localStorage.setItem(T,F.toString())}catch{oi("Unable to write to LocalStorage")}}processRequests(){}postEvent(f,b,S,T){if(!Xt.EVENTS_URL)return;const D=ro(Xt.EVENTS_URL);D.params.push(`access_token=${T||Xt.ACCESS_TOKEN||""}`);const F={event:this.type,created:new Date(f).toISOString()},q=b?Object.assign(F,b):F,K={url:pc(D),headers:{"Content-Type":"text/plain"},body:JSON.stringify([q])};this.pendingRequest=!0,async function(X){return cn(Object.assign(X,{method:"POST"}),void 0)}(K).then(()=>{this.pendingRequest=!1,S(null),this.saveEventData(),this.processRequests()}).catch(X=>{this.pendingRequest=!1,S(X),this.saveEventData(),this.processRequests()})}queueRequest(f,b){this.queue.push({...f,customAccessToken:b}),this.processRequests()}}class ld extends Nl{constructor(f){super("metrics"),f&&(this.data=f)}postMetricsEvent(f){if(!xu(f))return;this.anonId||this.fetchEventData(),zn(this.anonId)||this.refreshUUID();const b={...this.data,sessionId:this.anonId};this.queueRequest({timestamp:Date.now(),payload:b},f)}processRequests(){if(this.pendingRequest||this.queue.length===0)return;const{timestamp:f,payload:b,customAccessToken:S}=this.queue.shift();this.postEvent(f,b,()=>{},S)}}const cd=new class extends Nl{constructor(w){super("appUserTurnstile"),this._customAccessToken=w}postTurnstileEvent(w,f){xu(f)&&Array.isArray(w)&&w.some(b=>_i(b)||so(b))&&this.queueRequest({timestamp:Date.now()},f)}processRequests(){if(this.pendingRequest||this.queue.length===0)return;this.anonId&&this.anonIdTimestamp&&this.eventData.lastSuccess&&this.eventData.tokenU||this.fetchEventData();const w=Nh(Xt.ACCESS_TOKEN),f=w?w.u:Xt.ACCESS_TOKEN;let b=f!==this.eventData.tokenU;zn(this.anonId)||(this.refreshUUID(),b=!0);const{timestamp:S,customAccessToken:T}=this.queue.shift();if(this.eventData.lastSuccess){const F=new Date(this.eventData.lastSuccess),q=new Date(S),K=(S-this.eventData.lastSuccess)/864e5;b=b||K>=1||K<-1||F.getDate()!==q.getDate()}else b=!0;if(!b)return void this.processRequests();const D={version:"2.2",sdkIdentifier:"mapbox-gl-js",sdkVersion:d,skuId:yn,"enabled.telemetry":!1,userId:this.anonId,bundleFormat:"umd",bundleDistribution:Uh};Dd&&(D.sdkInfo=Dd),this.postEvent(S,D,F=>{F||(this.eventData.lastSuccess=S,this.eventData.tokenU=f)},T)}},yd=cd.postTurnstileEvent.bind(cd),Wu=new class extends Nl{constructor(){super("map.load"),this.success={},this.skuToken=""}postMapLoadEvent(w,f,b,S){this.skuToken=f,this.errorCb=S,Xt.EVENTS_URL&&(b||Xt.ACCESS_TOKEN?this.queueRequest({id:w,timestamp:Date.now()},b):this.errorCb(new Error(Rc)))}processRequests(){if(this.pendingRequest||this.queue.length===0)return;const{id:w,timestamp:f,customAccessToken:b}=this.queue.shift();if(w&&this.success[w])return;this.anonId&&this.anonIdTimestamp||this.fetchEventData(),zn(this.anonId)||this.refreshUUID();const S={version:"2.2",sdkIdentifier:"mapbox-gl-js",sdkVersion:d,skuId:yn,skuToken:this.skuToken,userId:this.anonId,bundleFormat:"umd",bundleDistribution:Uh};Dd&&(S.sdkInfo=Dd),this.postEvent(f,S,T=>{T?this.errorCb(T):w&&(this.success[w]=!0)},b)}remove(){this.errorCb=null}},$c=Wu.postMapLoadEvent.bind(Wu),Od=new class extends Nl{constructor(){super("style.load"),this.eventIdPerMapInstanceMap=new Map,this.mapInstanceIdMap=new WeakMap}getMapInstanceId(w){let f=this.mapInstanceIdMap.get(w);return f||(f=Ci(),this.mapInstanceIdMap.set(w,f)),f}getEventId(w){const f=this.eventIdPerMapInstanceMap.get(w)||0;return this.eventIdPerMapInstanceMap.set(w,f+1),f}postStyleLoadEvent(w,f){const{map:b,style:S,importedStyles:T}=f;if(!xu(w))return;const D=this.getMapInstanceId(b),F={mapInstanceId:D,eventId:this.getEventId(D),style:S};T.length&&(F.importedStyles=T),this.queueRequest({timestamp:Date.now(),payload:F},w)}processRequests(){if(this.pendingRequest||this.queue.length===0)return;const{timestamp:w,payload:f,customAccessToken:b}=this.queue.shift();this.postEvent(w,f,()=>{},b)}},yu=Od.postStyleLoadEvent.bind(Od),Wm=new ld({attributes:[{name:"maps/js/layer-animations/style-with-appearances"}]}),lu=Wm.postMetricsEvent.bind(Wm),rc=new ld({attributes:[{name:"maps/js/layer-animations/runtime-appearances"}]}),Ku=rc.postMetricsEvent.bind(rc),gc=new class extends Nl{constructor(){super("gljs.performance")}postPerformanceEvent(w,f){xu(w)&&this.queueRequest({timestamp:Date.now(),performanceData:f},w)}processRequests(){if(this.pendingRequest||this.queue.length===0)return;const{timestamp:w,performanceData:f,customAccessToken:b}=this.queue.shift(),S=function(T){const D=performance.getEntriesByType("resource"),F=performance.getEntriesByType("mark"),q=function(Ne){const Me={};if(Ne){for(const ze in Ne)if(ze!=="other")for(const Ve of Ne[ze]){const Je=`${ze}ResolveRangeMin`,lt=`${ze}ResolveRangeMax`,ht=`${ze}RequestCount`,ct=`${ze}RequestCachedCount`;Me[Je]=Math.min(Me[Je]||1/0,Ve.startTime),Me[lt]=Math.max(Me[lt]||-1/0,Ve.responseEnd);const xt=kt=>{Me[kt]===void 0&&(Me[kt]=0),++Me[kt]};Ve.transferSize!==void 0&&Ve.transferSize===0&&xt(ct),xt(ht)}}return Me}(function(Ne,Me){const ze={};if(Ne)for(const Ve of Ne){const Je=Me(Ve);ze[Je]===void 0&&(ze[Je]=[]),ze[Je].push(Ve)}return ze}(D,Ca)),K=window.devicePixelRatio,X=navigator.connection||navigator.mozConnection||navigator.webkitConnection,ce=X?X.effectiveType:void 0,pe={counters:[],metadata:[],attributes:[]},xe=(Ne,Me,ze)=>{ze!=null&&Ne.push({name:Me,value:ze.toString()})};for(const Ne in q)xe(pe.counters,Ne,q[Ne]);if(T.interactionRange[0]!==1/0&&T.interactionRange[1]!==-1/0&&(xe(pe.counters,"interactionRangeMin",T.interactionRange[0]),xe(pe.counters,"interactionRangeMax",T.interactionRange[1])),F)for(const Ne of Object.values(xr)){const Me=F.find(ze=>ze.name===Ne);Me&&xe(pe.counters,Ne,Me.startTime)}return xe(pe.counters,"visibilityHidden",T.visibilityHidden),xe(pe.attributes,"style",function(Ne){if(Ne)for(const Me of Ne){const ze=Me.name.split("?")[0];if(qo(ze)){const Ve=ze.split("/").slice(-2);if(Ve.length===2)return`mapbox://styles/${Ve[0]}/${Ve[1]}`}}}(D)),xe(pe.attributes,"terrainEnabled",T.terrainEnabled?"true":"false"),xe(pe.attributes,"fogEnabled",T.fogEnabled?"true":"false"),xe(pe.attributes,"projection",T.projection),xe(pe.attributes,"zoom",T.zoom),xe(pe.metadata,"devicePixelRatio",K),xe(pe.metadata,"connectionEffectiveType",ce),xe(pe.metadata,"navigatorUserAgent",navigator.userAgent),xe(pe.metadata,"screenWidth",window.screen.width),xe(pe.metadata,"screenHeight",window.screen.height),xe(pe.metadata,"windowWidth",window.innerWidth),xe(pe.metadata,"windowHeight",window.innerHeight),xe(pe.metadata,"mapWidth",T.width/K),xe(pe.metadata,"mapHeight",T.height/K),xe(pe.metadata,"webglRenderer",T.renderer),xe(pe.metadata,"webglVendor",T.vendor),xe(pe.metadata,"sdkVersion",d),xe(pe.metadata,"sdkIdentifier","mapbox-gl-js"),pe}(f);for(const T of S.metadata);for(const T of S.counters);for(const T of S.attributes);this.postEvent(w,S,()=>{},b)}},kl=gc.postPerformanceEvent.bind(gc),sd=new class extends Nl{constructor(){super("map.auth"),this.success={},this.skuToken=""}getSession(w,f,b,S){if(!Xt.API_URL||!Xt.SESSION_PATH)return;const T=ro(Xt.API_URL+Xt.SESSION_PATH);T.params.push(`sku=${f||""}`),T.params.push(`access_token=${S||Xt.ACCESS_TOKEN||""}`);const D={url:pc(T),headers:{"Content-Type":"text/plain"}};this.pendingRequest=!0,async function(F){return cn(Object.assign(F,{method:"GET"}),void 0)}(D).then(()=>{this.pendingRequest=!1,b(null),this.saveEventData(),this.processRequests()}).catch(F=>{this.pendingRequest=!1,b(F),this.saveEventData(),this.processRequests()})}getSessionAPI(w,f,b,S){this.skuToken=f,this.errorCb=S,Xt.EVENTS_URL&&Xt.SESSION_PATH&&Xt.API_URL&&(b||Xt.ACCESS_TOKEN?this.queueRequest({id:w,timestamp:Date.now()},b):this.errorCb(new Error(Rc)))}processRequests(){if(this.pendingRequest||this.queue.length===0)return;const{id:w,timestamp:f,customAccessToken:b}=this.queue.shift();w&&this.success[w]||this.getSession(f,this.skuToken,S=>{S?this.errorCb(S):w&&(this.success[w]=!0)},b)}remove(){this.errorCb=null}},Tf=sd.getSessionAPI.bind(sd),Pu=new Set;function up(w,f=0){const T=w.length,D=T-(3&T);let F,q=0|f,K=0;for(;K>>17,F=Math.imul(F,461845907),q^=F,q=q<<13|q>>>19,q=Math.imul(q,5)+3864292196|0;F=0;const X=3&T;return X>0&&(X>=3&&(F^=(255&w.charCodeAt(K+2))<<16),X>=2&&(F^=(255&w.charCodeAt(K+1))<<8),F^=255&w.charCodeAt(K),F=Math.imul(F,3432918353),F=F<<15|F>>>17,F=Math.imul(F,461845907),q^=F),q^=T,q^=q>>>16,q=Math.imul(q,2246822507),q^=q>>>13,q=Math.imul(q,3266489909),q^=q>>>16,q>>>0}class Km{constructor(f,...b){Object.assign(this,b[0]||{}),this.type=f}}class vu extends Km{constructor(f,b={}){super("error",{error:f,...b}),this.error=f}}function Fl(w,f,b){b[w]&&b[w].includes(f)||(b[w]=b[w]||[],b[w].push(f))}function Mf(w,f,b){if(b[w]){const S=b[w].indexOf(f);S!==-1&&b[w].splice(S,1)}}class Fd{constructor(){this._listeners={},this._oneTimeListeners={}}on(f,b){return Fl(f,b,this._listeners),this}off(f,b){return Mf(f,b,this._listeners),Mf(f,b,this._oneTimeListeners),this}once(f,b){return b?(Fl(f,b,this._oneTimeListeners),this):new Promise(S=>{this.once(f,S)})}fire(f,b){const S=typeof f=="string"?new Km(f,b):f,T=S.type;if(this.listens(T)){S.target=this;const D=this._listeners[T]?this._listeners[T].slice():[];for(const K of D)K.call(this,S);const F=this._oneTimeListeners[T]?this._oneTimeListeners[T].slice():[];for(const K of F)Mf(T,K,this._oneTimeListeners),K.call(this,S);const q=this._eventedParent;if(q){const K=typeof this._eventedParentData=="function"?this._eventedParentData():this._eventedParentData;Object.assign(S,K),q.fire(S)}}else S instanceof vu&&console.error(S.error);return this}listens(f){return!!(this._listeners[f]&&this._listeners[f].length>0||this._oneTimeListeners[f]&&this._oneTimeListeners[f].length>0||this._eventedParent&&this._eventedParent.listens(f))}setEventedParent(f,b){return this._eventedParent=f,this._eventedParentData=b,this}}class Gl{constructor(f){typeof f=="string"?this.name=f:(this.name=f.name,this.iconsetId=f.iconsetId)}static from(f){return new Gl(f)}static toString(f){return f.iconsetId?`${f.name}${f.iconsetId}`:f.name}static parse(f){const[b,S]=f.split("");return new Gl({name:b,iconsetId:S})}static isEqual(f,b){return f.name===b.name&&f.iconsetId===b.iconsetId}toString(){return Gl.toString(this)}serialize(){return{name:this.name,iconsetId:this.iconsetId}}}var km,Sm={},Ig=function(){if(km)return Sm;km=1;var w={transparent:[0,0,0,0],aliceblue:[240,248,255,1],antiquewhite:[250,235,215,1],aqua:[0,255,255,1],aquamarine:[127,255,212,1],azure:[240,255,255,1],beige:[245,245,220,1],bisque:[255,228,196,1],black:[0,0,0,1],blanchedalmond:[255,235,205,1],blue:[0,0,255,1],blueviolet:[138,43,226,1],brown:[165,42,42,1],burlywood:[222,184,135,1],cadetblue:[95,158,160,1],chartreuse:[127,255,0,1],chocolate:[210,105,30,1],coral:[255,127,80,1],cornflowerblue:[100,149,237,1],cornsilk:[255,248,220,1],crimson:[220,20,60,1],cyan:[0,255,255,1],darkblue:[0,0,139,1],darkcyan:[0,139,139,1],darkgoldenrod:[184,134,11,1],darkgray:[169,169,169,1],darkgreen:[0,100,0,1],darkgrey:[169,169,169,1],darkkhaki:[189,183,107,1],darkmagenta:[139,0,139,1],darkolivegreen:[85,107,47,1],darkorange:[255,140,0,1],darkorchid:[153,50,204,1],darkred:[139,0,0,1],darksalmon:[233,150,122,1],darkseagreen:[143,188,143,1],darkslateblue:[72,61,139,1],darkslategray:[47,79,79,1],darkslategrey:[47,79,79,1],darkturquoise:[0,206,209,1],darkviolet:[148,0,211,1],deeppink:[255,20,147,1],deepskyblue:[0,191,255,1],dimgray:[105,105,105,1],dimgrey:[105,105,105,1],dodgerblue:[30,144,255,1],firebrick:[178,34,34,1],floralwhite:[255,250,240,1],forestgreen:[34,139,34,1],fuchsia:[255,0,255,1],gainsboro:[220,220,220,1],ghostwhite:[248,248,255,1],gold:[255,215,0,1],goldenrod:[218,165,32,1],gray:[128,128,128,1],green:[0,128,0,1],greenyellow:[173,255,47,1],grey:[128,128,128,1],honeydew:[240,255,240,1],hotpink:[255,105,180,1],indianred:[205,92,92,1],indigo:[75,0,130,1],ivory:[255,255,240,1],khaki:[240,230,140,1],lavender:[230,230,250,1],lavenderblush:[255,240,245,1],lawngreen:[124,252,0,1],lemonchiffon:[255,250,205,1],lightblue:[173,216,230,1],lightcoral:[240,128,128,1],lightcyan:[224,255,255,1],lightgoldenrodyellow:[250,250,210,1],lightgray:[211,211,211,1],lightgreen:[144,238,144,1],lightgrey:[211,211,211,1],lightpink:[255,182,193,1],lightsalmon:[255,160,122,1],lightseagreen:[32,178,170,1],lightskyblue:[135,206,250,1],lightslategray:[119,136,153,1],lightslategrey:[119,136,153,1],lightsteelblue:[176,196,222,1],lightyellow:[255,255,224,1],lime:[0,255,0,1],limegreen:[50,205,50,1],linen:[250,240,230,1],magenta:[255,0,255,1],maroon:[128,0,0,1],mediumaquamarine:[102,205,170,1],mediumblue:[0,0,205,1],mediumorchid:[186,85,211,1],mediumpurple:[147,112,219,1],mediumseagreen:[60,179,113,1],mediumslateblue:[123,104,238,1],mediumspringgreen:[0,250,154,1],mediumturquoise:[72,209,204,1],mediumvioletred:[199,21,133,1],midnightblue:[25,25,112,1],mintcream:[245,255,250,1],mistyrose:[255,228,225,1],moccasin:[255,228,181,1],navajowhite:[255,222,173,1],navy:[0,0,128,1],oldlace:[253,245,230,1],olive:[128,128,0,1],olivedrab:[107,142,35,1],orange:[255,165,0,1],orangered:[255,69,0,1],orchid:[218,112,214,1],palegoldenrod:[238,232,170,1],palegreen:[152,251,152,1],paleturquoise:[175,238,238,1],palevioletred:[219,112,147,1],papayawhip:[255,239,213,1],peachpuff:[255,218,185,1],peru:[205,133,63,1],pink:[255,192,203,1],plum:[221,160,221,1],powderblue:[176,224,230,1],purple:[128,0,128,1],rebeccapurple:[102,51,153,1],red:[255,0,0,1],rosybrown:[188,143,143,1],royalblue:[65,105,225,1],saddlebrown:[139,69,19,1],salmon:[250,128,114,1],sandybrown:[244,164,96,1],seagreen:[46,139,87,1],seashell:[255,245,238,1],sienna:[160,82,45,1],silver:[192,192,192,1],skyblue:[135,206,235,1],slateblue:[106,90,205,1],slategray:[112,128,144,1],slategrey:[112,128,144,1],snow:[255,250,250,1],springgreen:[0,255,127,1],steelblue:[70,130,180,1],tan:[210,180,140,1],teal:[0,128,128,1],thistle:[216,191,216,1],tomato:[255,99,71,1],turquoise:[64,224,208,1],violet:[238,130,238,1],wheat:[245,222,179,1],white:[255,255,255,1],whitesmoke:[245,245,245,1],yellow:[255,255,0,1],yellowgreen:[154,205,50,1]};function f(D){return(D=Math.round(D))<0?0:D>255?255:D}function b(D){return f(D[D.length-1]==="%"?parseFloat(D)/100*255:parseInt(D))}function S(D){return(F=D[D.length-1]==="%"?parseFloat(D)/100:parseFloat(D))<0?0:F>1?1:F;var F}function T(D,F,q){return q<0?q+=1:q>1&&(q-=1),6*q<1?D+(F-D)*q*6:2*q<1?F:3*q<2?D+(F-D)*(2/3-q)*6:D}try{Sm.parseCSSColor=function(D){var F,q=D.replace(/ /g,"").toLowerCase();if(q in w)return w[q].slice();if(q[0]==="#")return q.length===4?(F=parseInt(q.substr(1),16))>=0&&F<=4095?[(3840&F)>>4|(3840&F)>>8,240&F|(240&F)>>4,15&F|(15&F)<<4,1]:null:q.length===7&&(F=parseInt(q.substr(1),16))>=0&&F<=16777215?[(16711680&F)>>16,(65280&F)>>8,255&F,1]:null;var K=q.indexOf("("),X=q.indexOf(")");if(K!==-1&&X+1===q.length){var ce=q.substr(0,K),pe=q.substr(K+1,X-(K+1)).split(","),xe=1;switch(ce){case"rgba":if(pe.length!==4)return null;xe=S(pe.pop());case"rgb":return pe.length!==3?null:[b(pe[0]),b(pe[1]),b(pe[2]),xe];case"hsla":if(pe.length!==4)return null;xe=S(pe.pop());case"hsl":if(pe.length!==3)return null;var Ne=(parseFloat(pe[0])%360+360)%360/360,Me=S(pe[1]),ze=S(pe[2]),Ve=ze<=.5?ze*(Me+1):ze+Me-ze*Me,Je=2*ze-Ve;return[f(255*T(Je,Ve,Ne+1/3)),f(255*T(Je,Ve,Ne)),f(255*T(Je,Ve,Ne-1/3)),xe];default:return null}}return null}}catch{}return Sm}();function da(w,f,b){return w*(1-b)+f*b}const Ec=new Map;class Mi{constructor(f,b,S,T=1){this.r=f,this.g=b,this.b=S,this.a=T}static parse(f){if(!f)return;if(f instanceof Mi)return f;if(typeof f!="string")return;const b=Ec.get(f);if(b)return b;const S=Ig.parseCSSColor(f);if(!S)return;const T=new Mi(S[0]/255,S[1]/255,S[2]/255,S[3]);return Ec.set(f,T),T}toString(){const{r:f,g:b,b:S,a:T}=this;return`rgba(${Math.round(255*f)},${Math.round(255*b)},${Math.round(255*S)},${T})`}toNonPremultipliedRenderColor(f){const{r:b,g:S,b:T,a:D}=this;return new ux(f,b,S,T,D)}toPremultipliedRenderColor(f){const{r:b,g:S,b:T,a:D}=this;return new hx(f,b*D,S*D,T*D,D)}clone(){return new Mi(this.r,this.g,this.b,this.a)}}class Ym{constructor(f,b,S,T,D,F=!1){if(this.premultiplied=!1,this.premultiplied=F,f){const q=f.image.height,K=q*q;this.premultiplied?(b=D===0?0:b/D*(q-1),S=D===0?0:S/D*(q-1),T=D===0?0:T/D*(q-1)):(b*=q-1,S*=q-1,T*=q-1),b=Math.max(0,Math.min(q-1,b)),S=Math.max(0,Math.min(q-1,S)),T=Math.max(0,Math.min(q-1,T));const X=Math.floor(b),ce=Math.floor(S),pe=Math.floor(T),xe=Math.ceil(b),Ne=Math.ceil(S),Me=Math.ceil(T),ze=b-X,Ve=S-ce,Je=T-pe,lt=f.image.data,ht=4*(X+ce*K+pe*q),ct=4*(X+ce*K+Me*q),xt=4*(X+Ne*K+pe*q),kt=4*(X+Ne*K+Me*q),es=4*(xe+ce*K+pe*q),Ct=4*(xe+ce*K+Me*q),Lt=4*(xe+Ne*K+pe*q),Zt=4*(xe+Ne*K+Me*q);this.r=da(da(da(lt[ht],lt[ct],Je),da(lt[xt],lt[kt],Je),Ve),da(da(lt[es],lt[Ct],Je),da(lt[Lt],lt[Zt],Je),Ve),ze)/255*(this.premultiplied?D:1),this.g=da(da(da(lt[ht+1],lt[ct+1],Je),da(lt[xt+1],lt[kt+1],Je),Ve),da(da(lt[es+1],lt[Ct+1],Je),da(lt[Lt+1],lt[Zt+1],Je),Ve),ze)/255*(this.premultiplied?D:1),this.b=da(da(da(lt[ht+2],lt[ct+2],Je),da(lt[xt+2],lt[kt+2],Je),Ve),da(da(lt[es+2],lt[Ct+2],Je),da(lt[Lt+2],lt[Zt+2],Je),Ve),ze)/255*(this.premultiplied?D:1),this.a=D}else this.r=b,this.g=S,this.b=T,this.a=D}toArray(){const{r:f,g:b,b:S,a:T}=this;return[255*f,255*b,255*S,T]}toHslaArray(){let{r:f,g:b,b:S,a:T}=this;if(this.premultiplied){if(T===0)return[0,0,0,0];const Me=1/T;f*=Me,b*=Me,S*=Me}const D=Math.min(Math.max(f,0),1),F=Math.min(Math.max(b,0),1),q=Math.min(Math.max(S,0),1),K=Math.min(D,F,q),X=Math.max(D,F,q),ce=X-K,pe=.5*(K+X);if(ce===0)return[0,0,100*pe,T];const xe=pe>.5?ce/(2-X-K):ce/(X+K);let Ne;switch(X){case D:Ne=60*((F-q)/ce+(Fda(S,f[T],b))}Mi.black=new Mi(0,0,0,1),Mi.white=new Mi(1,1,1,1),Mi.transparent=new Mi(0,0,0,0),Mi.red=new Mi(1,0,0,1),Mi.blue=new Mi(0,0,1,1);var Xd=Object.freeze({__proto__:null,array:uh,color:function(w,f,b){return new Mi(da(w.r,f.r,b),da(w.g,f.g,b),da(w.b,f.b,b),da(w.a,f.a,b))},number:da});class al extends Error{constructor(f,b){super(b),this.message=b,this.key=f}}class tl{constructor(f,b=[]){this.parent=f,this.bindings=Object.create(null);for(const[S,T]of b)this.bindings[S]=T}concat(f){return new tl(this,f)}get(f){if(this.bindings[f])return this.bindings[f];if(this.parent)return this.parent.get(f);throw new Error(`${f} not found in scope.`)}has(f){return!!this.bindings[f]||!!this.parent&&this.parent.has(f)}}const sl={kind:"null"},Or={kind:"number"},$i={kind:"string"},Qi={kind:"boolean"},kh={kind:"color"},nd={kind:"object"},Po={kind:"value"},hp={kind:"collator"},mx={kind:"formatted"},Pf={kind:"resolvedImage"};function Sl(w,f){return{kind:"array",itemType:w,N:f}}function Wl(w){if(w.kind==="array"){const f=Wl(w.itemType);return typeof w.N=="number"?`array<${f}, ${w.N}>`:w.itemType.kind==="value"?"array":`array<${f}>`}return w.kind}const Wp=[sl,Or,$i,Qi,kh,mx,nd,Sl(Po),Pf];function Zm(w,f){if(f.kind==="error")return null;if(w.kind==="array"){if(f.kind==="array"&&(f.N===0&&f.itemType.kind==="value"||!Zm(w.itemType,f.itemType))&&(typeof w.N!="number"||w.N===f.N))return null}else{if(w.kind===f.kind)return null;if(w.kind==="value"){for(const b of Wp)if(!Zm(b,f))return null}}return`Expected ${Wl(w)} but found ${Wl(f)} instead.`}function Pb(w,f){return f.some(b=>b==="null"?w===null:b==="array"?Array.isArray(w):b==="object"?w&&!Array.isArray(w)&&typeof w=="object":b===typeof w)}function k1(w,f){return w.kind==="array"&&f.kind==="array"?w.N===f.N&&k1(w.itemType,f.itemType):w.kind===f.kind}class Ib{constructor(f,b,S){this.sensitivity=f?b?"variant":"case":b?"accent":"base",this.locale=S,this.collator=new Intl.Collator(this.locale?this.locale:[],{sensitivity:this.sensitivity,usage:"search"})}compare(f,b){return this.collator.compare(f,b)}resolvedLocale(){return new Intl.Collator(this.locale?this.locale:[]).resolvedOptions().locale}}class _v{constructor(f,b,S,T,D){this.text=f.normalize?f.normalize():f,this.image=b,this.scale=S,this.fontStack=T,this.textColor=D}}class Yu{constructor(f){this.sections=f}static fromString(f){return new Yu([new _v(f,null,null,null,null)])}isEmpty(){return this.sections.length===0||!this.sections.some(f=>f.text.length!==0||!!f.image&&f.image.hasPrimary())}static factory(f){return f instanceof Yu?f:Yu.fromString(f)}toString(){return this.sections.length===0?"":this.sections.map(f=>f.text).join("")}serialize(){const f=["format"];for(const b of this.sections){if(b.image){const T=b.image.getPrimary().id.toString();f.push(["image",T]);continue}f.push(b.text);const S={};b.fontStack&&(S["text-font"]=["literal",b.fontStack.split(",")]),b.scale&&(S["font-scale"]=b.scale),b.textColor&&(S["text-color"]=["rgba"].concat(b.textColor.toNonPremultipliedRenderColor(null).toArray())),f.push(S)}return f}}class Kp{constructor(f,b={}){this.id=Gl.from(f),this.params=b.params,this.sx=b.sx||1,this.sy=b.sy||1}toString(){return JSON.stringify(this)}static parse(f){let b,S,T,D;try{({id:b,params:S,sx:T,sy:D}=JSON.parse(f)||{})}catch{return null}return b?new Kp(b,{params:S,sx:T,sy:D}):null}scaleSelf(f,b=f){return this.sx*=f,this.sy*=b,this}}class rm{constructor(f,b,S,T,D=!1){this.primaryId=Gl.from(f),this.primaryOptions=b,S&&(this.secondaryId=Gl.from(S)),this.secondaryOptions=T,this.available=D}toString(){return this.primaryId&&this.secondaryId?`[${this.primaryId.name},${this.secondaryId.name}]`:this.primaryId.name}hasPrimary(){return!!this.primaryId}getPrimary(){return new Kp(this.primaryId,this.primaryOptions)}hasSecondary(){return!!this.secondaryId}getSecondary(){return this.secondaryId?new Kp(this.secondaryId,this.secondaryOptions):null}static from(f){return typeof f!="string"?f:rm.build({name:f})}static build(f,b,S,T){return!f||typeof f=="object"&&!("name"in f)?null:new rm(f,S,b,T)}}function S1(w,f,b,S){return typeof w=="number"&&w>=0&&w<=255&&typeof f=="number"&&f>=0&&f<=255&&typeof b=="number"&&b>=0&&b<=255?S===void 0||typeof S=="number"&&S>=0&&S<=1?null:`Invalid rgba value [${[w,f,b,S].join(", ")}]: 'a' must be between 0 and 1.`:`Invalid rgba value [${(typeof S=="number"?[w,f,b,S]:[w,f,b]).join(", ")}]: 'r', 'g', and 'b' must be between 0 and 255.`}function Zu(w){if(w===null||typeof w=="string"||typeof w=="boolean"||typeof w=="number"||w instanceof Mi||w instanceof Ib||w instanceof Yu||w instanceof rm)return!0;if(Array.isArray(w)){for(const f of w)if(!Zu(f))return!1;return!0}if(typeof w=="object"){for(const f in w)if(!Zu(w[f]))return!1;return!0}return!1}function rd(w){if(w===null)return sl;if(typeof w=="string")return $i;if(typeof w=="boolean")return Qi;if(typeof w=="number")return Or;if(w instanceof Mi)return kh;if(w instanceof Ib)return hp;if(w instanceof Yu)return mx;if(w instanceof rm)return Pf;if(Array.isArray(w)){const f=w.length;let b;for(const S of w){const T=rd(S);if(b){if(b===T)continue;b=Po;break}b=T}return Sl(b||Po,f)}return nd}function Xm(w){return w===null?"":typeof w=="string"||typeof w=="number"||typeof w=="boolean"?String(w):w instanceof Yu||w instanceof rm||w instanceof Mi?w.toString():JSON.stringify(w)}class If{constructor(f,b){this.type=f,this.value=b}static parse(f,b){if(f.length!==2)return b.error(`'literal' expression requires exactly one argument, but found ${f.length-1} instead.`);if(!Zu(f[1]))return b.error("invalid value");const S=f[1];let T=rd(S);const D=b.expectedType;return T.kind!=="array"||T.N!==0||!D||D.kind!=="array"||typeof D.N=="number"&&D.N!==0||(T=D),new If(T,S)}evaluate(){return this.value}eachChild(){}outputDefined(){return!0}serialize(){return this.type.kind==="array"||this.type.kind==="object"?["literal",this.value]:this.value instanceof Mi?["rgba"].concat(this.value.toNonPremultipliedRenderColor(null).toArray()):this.value instanceof Yu?this.value.serialize():this.value}}class Iu{constructor(f){this.name="ExpressionEvaluationError",this.message=f}toJSON(){return this.message}}const E0={string:$i,number:Or,boolean:Qi,object:nd};class wi{constructor(f,b){this.type=f,this.args=b}static parse(f,b){if(f.length<2)return b.error("Expected at least one argument.");let S,T=1;const D=f[0];if(D==="array"){let q,K;if(f.length>2){const X=f[1];if(typeof X!="string"||!(X in E0)||X==="object")return b.error('The item type argument of "array" must be one of string, number, boolean',1);q=E0[X],T++}else q=Po;if(f.length>3){if(f[2]!==null&&(typeof f[2]!="number"||f[2]<0||f[2]!==Math.floor(f[2])))return b.error('The length argument to "array" must be a positive integer literal',2);K=f[2],T++}S=Sl(q,K)}else S=E0[D];const F=[];for(;Tf.outputDefined())}serialize(){const f=this.type,b=[f.kind];if(f.kind==="array"){const S=f.itemType;if(S.kind==="string"||S.kind==="number"||S.kind==="boolean"){b.push(S.kind);const T=f.N;(typeof T=="number"||this.args.length>1)&&b.push(T)}}return b.concat(this.args.map(S=>S.serialize()))}}class Lf{constructor(f){this.type=mx,this.sections=f}static parse(f,b){if(f.length<2)return b.error("Expected at least one argument.");const S=f[1];if(!Array.isArray(S)&&typeof S=="object")return b.error("First argument must be an image or text section.");const T=[];let D=!1;for(let F=1;F<=f.length-1;++F){const q=f[F];if(D&&typeof q=="object"&&!Array.isArray(q)){D=!1;let K=null;if(q["font-scale"]&&(K=b.parseObjectValue(q["font-scale"],F,"font-scale",Or),!K))return null;let X=null;if(q["text-font"]&&(X=b.parseObjectValue(q["text-font"],F,"text-font",Sl($i)),!X))return null;let ce=null;if(q["text-color"]&&(ce=b.parseObjectValue(q["text-color"],F,"text-color",kh),!ce))return null;const pe=T.at(-1);pe.scale=K,pe.font=X,pe.textColor=ce}else{const K=b.parse(f[F],F,Po);if(!K)return null;const X=K.type.kind;if(X!=="string"&&X!=="value"&&X!=="null"&&X!=="resolvedImage")return b.error("Formatted text type must be 'string', 'value', 'image' or 'null'.");D=!0,T.push({content:K,scale:null,font:null,textColor:null})}}return new Lf(T)}evaluate(f){return new Yu(this.sections.map(b=>{const S=b.content.evaluate(f);return k1(rd(S),Pf)?new _v("",S,null,null,null):new _v(Xm(S),null,b.scale?b.scale.evaluate(f):null,b.font?b.font.evaluate(f).join(","):null,b.textColor?b.textColor.evaluate(f):null)}))}eachChild(f){for(const b of this.sections)f(b.content),b.scale&&f(b.scale),b.font&&f(b.font),b.textColor&&f(b.textColor)}outputDefined(){return!1}serialize(){const f=["format"];for(const b of this.sections){f.push(b.content.serialize());const S={};b.scale&&(S["font-scale"]=b.scale.serialize()),b.font&&(S["text-font"]=b.font.serialize()),b.textColor&&(S["text-color"]=b.textColor.serialize()),f.push(S)}return f}}class wv{constructor(f,b,S,T){this._imageWarnHistory={},this.type=Pf,this.namePrimary=f,this.nameSecondary=b,S&&(this.paramsPrimary=S.params,this.iconsetIdPrimary=S.iconset?S.iconset.id:void 0),T&&(this.paramsSecondary=T.params,this.iconsetIdSecondary=T.iconset?T.iconset.id:void 0)}static parse(f,b){if(f.length<2)return b.error("Expected two or more arguments.");let S=1;const T=[];function D(){if(SGl.isEqual(F,D)),T.available){const F=T.getSecondary()?T.getSecondary().id:null;F&&(T.available=f.availableImages.some(q=>Gl.isEqual(q,F)))}}return T}eachChild(f){if(f(this.namePrimary),this.paramsPrimary)for(const b in this.paramsPrimary)this.paramsPrimary[b]&&f(this.paramsPrimary[b]);if(this.nameSecondary&&(f(this.nameSecondary),this.paramsSecondary))for(const b in this.paramsSecondary)this.paramsSecondary[b]&&f(this.paramsSecondary[b])}outputDefined(){return!1}serializeOptions(f,b){const S={};if(b&&(S.iconset={id:b}),f){S.params={};for(const T in f)f[T]&&(S.params[T]=f[T].serialize())}return Object.keys(S).length>0?S:void 0}serialize(){const f=["image",this.namePrimary.serialize()];if(this.paramsPrimary||this.iconsetIdPrimary){const b=this.serializeOptions(this.paramsPrimary,this.iconsetIdPrimary);b&&f.push(b)}if(this.nameSecondary&&(f.push(this.nameSecondary.serialize()),this.paramsSecondary||this.iconsetIdSecondary)){const b=this.serializeOptions(this.paramsSecondary,this.iconsetIdSecondary);b&&f.push(b)}return f}}function jv(w){return Nv(w)?"string":T0(w)?"number":Nj(w)?"boolean":Array.isArray(w)?"array":w===null?"null":Ry(w)?"object":typeof w}function Ry(w){return w!=null&&!Array.isArray(w)&&typeof w!="function"&&!(w instanceof String||w instanceof Number||w instanceof Boolean)&&typeof w=="object"}function Nv(w){return typeof w=="string"||w instanceof String}function T0(w){return typeof w=="number"||w instanceof Number}function Nj(w){return typeof w=="boolean"||w instanceof Boolean}const Ok={"to-boolean":Qi,"to-color":kh,"to-number":Or,"to-string":$i};class Dy{constructor(f,b){this.type=f,this.args=b}static parse(f,b){if(f.length<2)return b.error("Expected at least one argument.");const S=f[0],T=[];let D=sl;if(S==="to-array"){if(!Array.isArray(f[1]))return null;const F=f[1].length;if(b.expectedType){if(b.expectedType.kind!=="array")return b.error(`Expected ${b.expectedType.kind} but found array.`);D=Sl(b.expectedType.itemType,F)}else{if(!(F>0&&Zu(f[1][0])))return null;D=Sl(rd(f[1][0]),F)}for(let q=0;q4?`Invalid rbga value ${JSON.stringify(b)}: expected an array containing either three or four numeric values.`:S1(b[0],b[1],b[2],b[3]),!S))return new Mi(b[0]/255,b[1]/255,b[2]/255,b[3])}throw new Iu(S||`Could not parse color from value '${typeof b=="string"?b:String(JSON.stringify(b))}'`)}if(this.type.kind==="number"){let b=null;for(const S of this.args){if(b=S.evaluate(f),b===null)return 0;const T=Number(b);if(!isNaN(T))return T}throw new Iu(`Could not convert ${JSON.stringify(b)} to number.`)}return this.type.kind==="formatted"?Yu.fromString(Xm(this.args[0].evaluate(f))):this.type.kind==="resolvedImage"?rm.build(Xm(this.args[0].evaluate(f))):this.type.kind==="array"?this.args.map(b=>b.evaluate(f)):Xm(this.args[0].evaluate(f))}eachChild(f){this.args.forEach(f)}outputDefined(){return this.args.every(f=>f.outputDefined())}serialize(){if(this.type.kind==="formatted")return new Lf([{content:this.args[0],scale:null,font:null,textColor:null}]).serialize();if(this.type.kind==="resolvedImage")return new wv(this.args[0]).serialize();const f=this.type.kind==="array"?[]:[`to-${this.type.kind}`];return this.eachChild(b=>{f.push(b.serialize())}),f}}const Fk=["Unknown","Point","LineString","Polygon"];class fx{constructor(f,b,S){this.globals=null,this.feature=null,this.featureState=null,this.formattedSection=null,this.availableImages=null,this.canonical=null,this.featureTileCoord=null,this.featureDistanceData=null,this.scope=f,this.options=b,this.iconImageUseTheme=S}id(){return this.feature&&this.feature.id!==void 0?this.feature.id:null}geometryType(){return this.feature?typeof this.feature.type=="number"?Fk[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(f){return this.globals.brightness||0}distanceFromCenter(){if(this.featureTileCoord&&this.featureDistanceData){const f=this.featureDistanceData.center,b=this.featureDistanceData.scale,{x:S,y:T}=this.featureTileCoord;return this.featureDistanceData.bearing[0]*(S*b-f[0])+this.featureDistanceData.bearing[1]*(T*b-f[1])}return 0}parseColor(f){return Mi.parse(f)}getConfig(f){return this.options?this.options.get(f):null}}class Rf{constructor(f,b,S,T,D){this.name=f,this.type=b,this._evaluate=S,this.args=T,this._overloadIndex=D}evaluate(f){if(!this._evaluate){const b=Rf.definitions[this.name];this._evaluate=Array.isArray(b)?b[2]:b.overloads[this._overloadIndex][1]}return this._evaluate(f,this.args)}eachChild(f){this.args.forEach(f)}outputDefined(){return!1}serialize(){return[this.name].concat(this.args.map(f=>f.serialize()))}static parse(f,b){const S=f[0],T=Rf.definitions[S];if(!T)return b.error(`Unknown expression "${S}". If you wanted a literal array, use ["literal", [...]].`,0);const D=Array.isArray(T)?T[0]:T.type,F=Array.isArray(T)?[[T[1],T[2]]]:T.overloads,q=[];let K=null,X=-1;for(const[ce,pe]of F){if(Array.isArray(ce)&&ce.length!==f.length-1)continue;q.push(ce),X++,K===null?K=b._forkForSignature():K.errors.length=0;const xe=[];let Ne=!1;for(let Me=1;Mexe)).map(Z2).join(" | "),pe=[];for(let xe=1;xeb[2]){const T=.5*S;let D=w[0]-b[0]>T?-S:b[0]-w[0]>T?S:0;D===0&&(D=w[0]-b[2]>T?-S:b[2]-w[0]>T?S:0),w[0]+=D}Ei(f,w)}function Lb(w,f,b,S){const T=Math.pow(2,S.z)*ef,D=[S.x*ef,S.y*ef],F=[];if(!w)return F;for(const q of w)for(const K of q){const X=[K.x+D[0],K.y+D[1]];Fy(X,f,b,T),F.push(X)}return F}function Bk(w,f,b,S){const T=Math.pow(2,S.z)*ef,D=[S.x*ef,S.y*ef],F=[];if(!w)return F;for(const K of w){const X=[];for(const ce of K){const pe=[ce.x+D[0],ce.y+D[1]];Ei(f,pe),X.push(pe)}F.push(X)}if(f[2]-f[0]<=T/2){(q=f)[0]=q[1]=1/0,q[2]=q[3]=-1/0;for(const K of F)for(const X of K)Fy(X,f,b,T)}var q;return F}class Lg{constructor(f,b){this.type=Qi,this.geojson=f,this.geometries=b}static parse(f,b){if(f.length!==2)return b.error(`'within' expression requires exactly one argument, but found ${f.length-1} instead.`);if(Zu(f[1])){const S=f[1];if(S.type==="FeatureCollection")for(let T=0;TST?1:0){if(this.data=f,this.length=this.data.length,this.compare=b,this.length>0)for(let S=(this.length>>1)-1;S>=0;S--)this._down(S)}push(f){this.data.push(f),this._up(this.length++)}pop(){if(this.length===0)return;const f=this.data[0],b=this.data.pop();return--this.length>0&&(this.data[0]=b,this._down(0)),f}peek(){return this.data[0]}_up(f){const{data:b,compare:S}=this,T=b[f];for(;f>0;){const D=f-1>>1,F=b[D];if(S(T,F)>=0)break;b[f]=F,f=D}b[f]=T}_down(f){const{data:b,compare:S}=this,T=this.length>>1,D=b[f];for(;f=0)break;b[f]=b[F],f=F}b[f]=D}}var br=8192;function V_(w,f,b){return[w,f,b].filter(Boolean).join("")}function Rb(w,f){switch(w){case"string":return Xm(f);case"number":return+f;case"boolean":return!!f;case"color":return Mi.parse(f);case"formatted":return Yu.fromString(Xm(f));case"resolvedImage":return rm.build(Xm(f))}return f}function y4(w,f,b,S){return S!==void 0&&(w=S*Math.round(w/S)),f!==void 0&&wb&&(w=b),w}class Cm{constructor(f,b,S,T=!1){this.type=f,this.key=b,this.scope=S,this.featureConstant=T}static parse(f,b){let S=b.expectedType;if(S??(S=Po),f.length<2||f.length>3)return b.error("Invalid number of arguments for 'config' expression.");const T=b.parse(f[1],1);if(!(T instanceof If))return b.error("Key name of 'config' expression must be a string literal.");let D,F=!0;const q=Xm(T.value);if(f.length>=3){const K=b.parse(f[2],2);if(!(K instanceof If))return b.error("Scope of 'config' expression must be a string literal.");D=Xm(K.value)}if(b.options){const K=V_(q,D,b._scope),X=b.options.get(K);X&&(F=qh(X.value||X.default))}return new Cm(S,q,D,F)}evaluate(f){const b=V_(this.key,this.scope,f.scope),S=f.getConfig(b);if(!S)return null;const{type:T,value:D,values:F,minValue:q,maxValue:K,stepValue:X}=S,ce=S.default.evaluate(f);let pe=ce;if(D){const xe=f.scope;f.scope=(xe||"").split("").slice(1).join(""),pe=D.evaluate(f),f.scope=xe}return T&&(pe=Rb(T,pe)),pe===void 0||q===void 0&&K===void 0&&X===void 0||(typeof pe=="number"?pe=y4(pe,q,K,X):Array.isArray(pe)&&(pe=pe.map(xe=>typeof xe=="number"?y4(xe,q,K,X):xe))),D!==void 0&&pe!==void 0&&F&&!F.includes(pe)&&(pe=ce,T&&(pe=Rb(T,pe))),(T&&T!==this.type||pe!==void 0&&!k1(rd(pe),this.type))&&(pe=Rb(this.type.kind,pe)),pe}eachChild(){}outputDefined(){return!1}serialize(){const f=["config",this.key];return this.scope&&f.concat(this.scope),f}}function qh(w){if(w instanceof Rf&&(w.name==="get"&&w.args.length===1||w.name==="feature-state"||w.name==="has"&&w.args.length===1||w.name==="properties"||w.name==="geometry-type"||w.name==="id"||w.name.startsWith("filter-"))||w instanceof Lg||w instanceof Yi)return!1;if(w instanceof Cm)return w.featureConstant;let f=!0;return w.eachChild(b=>{f&&!qh(b)&&(f=!1)}),f}function A1(w){if(w instanceof Rf&&w.name==="feature-state")return!1;let f=!0;return w.eachChild(b=>{f&&!A1(b)&&(f=!1)}),f}function E1(w,f){if(w instanceof Rf&&f.has(w.name))return!1;let b=!0;return w.eachChild(S=>{b&&!E1(S,f)&&(b=!1)}),b}function Yp(w,f){return E1(w,new Set(f))}const kv=1/298.257223563,Q2=kv*(2-kv),H_=Math.PI/180;function J2(w){const f=6378.137*H_*1e3,b=Math.cos(w*H_),S=1/(1-Q2*(1-b*b)),T=Math.sqrt(S);return[f*T*b,f*T*S*(1-Q2)]}function T1(w){for(;w<-180;)w+=360;for(;w>180;)w-=360;return w}function kj(w,f,b,S){const T=T1(w[0]-f[0])*b,D=(w[1]-f[1])*S;return Math.sqrt(T*T+D*D)}function Sj(w,f,b,S,T){let D=f[0],F=f[1],q=T1(b[0]-D)*S,K=(b[1]-F)*T;if(q!==0||K!==0){const X=(T1(w[0]-D)*S*q+(w[1]-F)*T*K)/(q*q+K*K);X>1?(D=b[0],F=b[1]):X>0&&(D+=q/S*X,F+=K/T*X)}return q=T1(w[0]-D)*S,K=(w[1]-F)*T,Math.sqrt(q*q+K*K)}function $k(w,f){return f.dist-w.dist}function Uk(w){const f=[1/0,1/0,-1/0,-1/0];if(f.length!==w.length)return!1;for(let b=0;b=w[0]&&w[1]w[1])return[null,null];const b=eN(w);if(f){if(b===2)return[w,null];const S=Math.floor(b/2);return[[w[0],w[0]+S],[w[0]+S,w[1]]]}{if(b===1)return[w,null];const S=Math.floor(b/2)-1;return[[w[0],w[0]+S],[w[0]+S+1,w[1]]]}}function G_(w,f){const b=[1/0,1/0,-1/0,-1/0];if(!Yx(f,w.length))return b;for(let S=f[0];S<=f[1];++S)Ei(b,w[S]);return b}function gx(w){const f=[1/0,1/0,-1/0,-1/0];for(let b=0;bf[2]&&(T=w[0]-f[2]),w[1]>f[3]&&(D=w[1]-f[3]),w[3]1?(Ne=D[xe+1][0],Me=D[xe+1][1]):Je>0&&(Ne+=ze/q*Je,Me+=Ve/K*Je)),ze=T1(F[0]-Ne)*q,Ve=(F[1]-Me)*K;const lt=ze*ze+Ve*Ve;lt=T)return T;if(fo(D,F)){if(Qs(w,f))return 0}else if(Qs(f,w))return 0;let q=T;for(const K of w)for(let X=0,ce=K.length,pe=ce-1;X=F)continue;const pe=ce.range1;if(eN(pe)<=K){if(!Yx(pe,w.length))return NaN;if(f){const xe=Ps(w,pe,b,S,T);if((F=Math.min(F,xe))===0)return F}else for(let xe=pe[0];xe<=pe[1];++xe){const Ne=Es(w[xe],b,S,T);if((F=Math.min(F,Ne))===0)return F}}else{const xe=px(pe,f);if(xe[0]!==null){const Ne=Sv(G_(w,xe[0]),X,S,T);Ne=q)continue;const xe=pe.range1,Ne=pe.range2;if(eN(xe)<=X&&eN(Ne)<=ce){if(!Yx(xe,w.length)||!Yx(Ne,b.length))return NaN;if(f&&S?q=Math.min(q,hs(w,xe,b,Ne,T,D)):f||S?f&&!S?q=Math.min(q,Et(b,Ne,w,xe,T,D)):!f&&S&&(q=Math.min(q,Et(w,xe,b,Ne,T,D))):q=Math.min(q,gs(w,xe,b,Ne,T,D)),q===0)return q}else{const Me=px(xe,f),ze=px(Ne,S);dr(K,q,T,D,w,b,Me[0],ze[0]),dr(K,q,T,D,w,b,Me[0],ze[1]),dr(K,q,T,D,w,b,Me[1],ze[0]),dr(K,q,T,D,w,b,Me[1],ze[1])}}return q}function or(w,f,b,S,T,D=1/0){let F=D;const q=G_(w,[0,w.length-1]);for(const K of b)if(!(F!==1/0&&Sv(q,G_(K,[0,K.length-1]),S,T)>=F)&&(F=Math.min(F,Vn(w,f,K,!0,S,T,F)),F===0))return F;return F}function zr(w,f,b,S,T,D=1/0){let F=D;const q=G_(w,[0,w.length-1]);for(const K of b){if(F!==1/0&&Sv(q,gx(K),S,T)>=F)continue;const X=Ws(w,f,K,S,T,F);if(isNaN(X))return X;if((F=Math.min(F,X))===0)return F}return F}function rr(w,f,b){const S=[];for(const F of w)for(const q of F)S.push(Ae(q,f));const[T,D]=J2(S[0][1]);return b.type==="Point"||b.type==="MultiPoint"||b.type==="LineString"?Vn(S,!1,b.type==="Point"?[b.coordinates]:b.coordinates,b.type==="LineString",T,D):b.type==="MultiLineString"?or(S,!1,b.coordinates,T,D):b.type==="Polygon"||b.type==="MultiPolygon"?zr(S,!1,b.type==="Polygon"?[b.coordinates]:b.coordinates,T,D):null}function Xr(w,f,b){const S=[];for(const F of w){const q=[];for(const K of F)q.push(Ae(K,f));S.push(q)}const[T,D]=J2(S[0][0][1]);if(b.type==="Point"||b.type==="MultiPoint"||b.type==="LineString")return or(b.type==="Point"?[b.coordinates]:b.coordinates,b.type==="LineString",S,T,D);if(b.type==="MultiLineString"){let F=1/0;for(let q=0;q`[${T}]`).join("")}`;this.errors.push(new al(S,f))}checkSubtype(f,b,S){const T=Zm(f,b);return T&&this.error(T,...typeof S=="number"?[S]:[]),T}}const zi=new Set(["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 _c(w,f,b){return b==="assert"?new wi(f,[w]):b==="coerce"?new Dy(f,[w]):w}function Vh(w){if(w instanceof Ui)return Vh(w.boundExpression);if(w instanceof Rf&&w.name==="error"||w instanceof C1||w instanceof Lg||w instanceof Yi||w instanceof Cm)return!1;const f=w instanceof Dy||w instanceof wi;let b=!0;return w.eachChild(S=>{b=f?b&&Vh(S):b&&S instanceof If}),!!b&&qh(w)&&E1(w,zi)}function Cl(w,f){const b=w.length-1;let S,T,D=0,F=b,q=0;for(;D<=F;)if(q=Math.floor((D+F)/2),S=w[q],T=w[q+1],S<=f){if(q===b||ff))throw new Iu("Input is not a number.");F=q-1}return 0}class Hi{constructor(f,b,S){this.type=f,this.input=b,this.labels=[],this.outputs=[];for(const[T,D]of S)this.labels.push(T),this.outputs.push(D)}static parse(f,b){if(f.length-1<4)return b.error(`Expected at least 4 arguments, but found only ${f.length-1}.`);if((f.length-1)%2!=0)return b.error("Expected an even number of arguments.");const S=b.parse(f[1],1,Or);if(!S)return null;const T=[];let D=null;b.expectedType&&b.expectedType.kind!=="value"&&(D=b.expectedType);for(let F=1;F=q)return b.error('Input/output pairs for "step" expressions must be arranged with input values in strictly ascending order.',X);const pe=b.parse(K,ce,D);if(!pe)return null;D=D||pe.type,T.push([q,pe])}return new Hi(D,S,T)}evaluate(f){const b=this.labels,S=this.outputs;if(b.length===1)return S[0].evaluate(f);const T=this.input.evaluate(f);if(T<=b[0])return S[0].evaluate(f);const D=b.length;return T>=b[D-1]?S[D-1].evaluate(f):S[Cl(b,T)].evaluate(f)}eachChild(f){f(this.input);for(const b of this.outputs)f(b)}outputDefined(){return this.outputs.every(f=>f.outputDefined())}serialize(){const f=["step",this.input.serialize()];for(let b=0;b0&&f.push(this.labels[b]),f.push(this.outputs[b].serialize());return f}}const li=.95047,Do=1.08883,po=4/29,ol=6/29,Uc=3*ol*ol,tf=ol*ol*ol,Zp=Math.PI/180,vd=180/Math.PI;function sf(w){return w>tf?Math.pow(w,1/3):w/Uc+po}function Lu(w){return w>ol?w*w*w:Uc*(w-po)}function am(w){return 255*(w<=.0031308?12.92*w:1.055*Math.pow(w,1/2.4)-.055)}function Dc(w){return(w/=255)<=.04045?w/12.92:Math.pow((w+.055)/1.055,2.4)}function Cd(w){const f=Dc(w.r),b=Dc(w.g),S=Dc(w.b),T=sf((.4124564*f+.3575761*b+.1804375*S)/li),D=sf((.2126729*f+.7151522*b+.072175*S)/1);return{l:116*D-16,a:500*(T-D),b:200*(D-sf((.0193339*f+.119192*b+.9503041*S)/Do)),alpha:w.a}}function mh(w){let f=(w.l+16)/116,b=isNaN(w.a)?f:f+w.a/500,S=isNaN(w.b)?f:f-w.b/200;return f=1*Lu(f),b=li*Lu(b),S=Do*Lu(S),new Mi(am(3.2404542*b-1.5371385*f-.4985314*S),am(-.969266*b+1.8760108*f+.041556*S),am(.0556434*b-.2040259*f+1.0572252*S),w.alpha)}function zd(w,f,b){const S=f-w;return w+b*(S>180||S<-180?S-360*Math.round(S/360):S)}const fh={forward:Cd,reverse:mh,interpolate:function(w,f,b){return{l:da(w.l,f.l,b),a:da(w.a,f.a,b),b:da(w.b,f.b,b),alpha:da(w.alpha,f.alpha,b)}}},Of={forward:function(w){const{l:f,a:b,b:S}=Cd(w),T=Math.atan2(S,b)*vd;return{h:T<0?T+360:T,c:Math.sqrt(b*b+S*S),l:f,alpha:w.a}},reverse:function(w){const f=w.h*Zp,b=w.c;return mh({l:w.l,a:Math.cos(f)*b,b:Math.sin(f)*b,alpha:w.alpha})},interpolate:function(w,f,b){return{h:zd(w.h,f.h,b),c:da(w.c,f.c,b),l:da(w.l,f.l,b),alpha:da(w.alpha,f.alpha,b)}}};var Xu=Object.freeze({__proto__:null,hcl:Of,lab:fh});class Qd{constructor(f,b,S,T,D){this.type=f,this.operator=b,this.interpolation=S,this.input=T,this.labels=[],this.outputs=[];for(const[F,q]of D)this.labels.push(F),this.outputs.push(q)}static interpolationFactor(f,b,S,T){let D=0;if(f.name==="exponential")D=bd(b,f.base,S,T);else if(f.name==="linear")D=bd(b,1,S,T);else if(f.name==="cubic-bezier"){const F=f.controlPoints;D=dn(F[0],F[1],F[2],F[3])(bd(b,1,S,T))}return D}static parse(f,b){let[S,T,D,...F]=f;if(!Array.isArray(T)||T.length===0)return b.error("Expected an interpolation type expression.",1);if(T[0]==="linear")T={name:"linear"};else if(T[0]==="exponential"){const X=T[1];if(typeof X!="number")return b.error("Exponential interpolation requires a numeric base.",1,1);T={name:"exponential",base:X}}else{if(T[0]!=="cubic-bezier")return b.error(`Unknown interpolation type ${String(T[0])}`,1,0);{const X=T.slice(1);if(X.length!==4||X.some(ce=>typeof ce!="number"||ce<0||ce>1))return b.error("Cubic bezier interpolation requires four numeric arguments with values between 0 and 1.",1);T={name:"cubic-bezier",controlPoints:X}}}if(f.length-1<4)return b.error(`Expected at least 4 arguments, but found only ${f.length-1}.`);if(f.length-1>3&&(f.length-1)%2!=0)return b.error("Expected an even number of arguments.");if(D=b.parse(D,2,Or),!D)return null;const q=[];let K=null;S==="interpolate-hcl"||S==="interpolate-lab"?K=kh:b.expectedType&&b.expectedType.kind!=="value"&&(K=b.expectedType);for(let X=0;X=ce)return b.error('Input/output pairs for "interpolate" expressions must be arranged with input values in strictly ascending order.',xe);const Me=b.parse(pe,Ne,K);if(!Me)return null;K=K||Me.type,q.push([ce,Me])}return K.kind==="number"||K.kind==="color"||K.kind==="array"&&K.itemType.kind==="number"&&typeof K.N=="number"?new Qd(K,S,T,D,q):b.error(`Type ${Wl(K)} is not interpolatable.`)}evaluate(f){const b=this.labels,S=this.outputs;if(b.length===1)return S[0].evaluate(f);const T=this.input.evaluate(f);if(T<=b[0])return S[0].evaluate(f);const D=b.length;if(T>=b[D-1])return S[D-1].evaluate(f);const F=Cl(b,T),q=Qd.interpolationFactor(this.interpolation,T,b[F],b[F+1]),K=S[F].evaluate(f),X=S[F+1].evaluate(f);return this.operator==="interpolate"?Xd[this.type.kind.toLowerCase()](K,X,q):this.operator==="interpolate-hcl"?Of.reverse(Of.interpolate(Of.forward(K),Of.forward(X),q)):fh.reverse(fh.interpolate(fh.forward(K),fh.forward(X),q))}eachChild(f){f(this.input);for(const b of this.outputs)f(b)}outputDefined(){return this.outputs.every(f=>f.outputDefined())}serialize(){let f;f=this.interpolation.name==="linear"?["linear"]:this.interpolation.name==="exponential"?this.interpolation.base===1?["linear"]:["exponential",this.interpolation.base]:["cubic-bezier",...this.interpolation.controlPoints];const b=[this.operator,f,this.input.serialize()];for(let S=0;SZm(T,q.type));return new Ru(F?Po:S,D)}evaluate(f){let b,S=null,T=0;for(const D of this.args){if(T++,S=D.evaluate(f),S&&S instanceof rm&&!S.available&&(b||(b=S),S=null,T===this.args.length))return b;if(S!==null)break}return S}eachChild(f){this.args.forEach(f)}outputDefined(){return this.args.every(f=>f.outputDefined())}serialize(){const f=["coalesce"];return this.eachChild(b=>{f.push(b.serialize())}),f}}const Rg=/[^a-zA-Z0-9_]/;class Am{constructor(f,b){this.type=b.type,this.bindings=[].concat(f),this.result=b}evaluate(f){return this.result.evaluate(f)}eachChild(f){for(const b of this.bindings)f(b[1]);f(this.result)}static parse(f,b){if(f.length<4)return b.error(`Expected at least 3 arguments, but found ${f.length-1} instead.`);const S=[];for(let D=1;D=S.length)throw new Iu("Array index out of bounds: index exceeds array size");if(b!==Math.floor(b))throw new Iu("Array index must be an integer. Use at-interpolated for fractional indices");return S[b]}eachChild(f){f(this.index),f(this.input)}outputDefined(){return!1}serialize(){return["at",this.index.serialize(),this.input.serialize()]}}class Xp{constructor(f,b,S){this.type=f,this.index=b,this.input=S}static parse(f,b){if(f.length!==3)return b.error(`Expected 2 arguments, but found ${f.length-1} instead.`);const S=b.parse(f[1],1,Or),T=b.parse(f[2],2,Sl(b.expectedType||Po));return S&&T?new Xp(T.type.itemType,S,T):null}evaluate(f){const b=this.index.evaluate(f),S=this.input.evaluate(f);if(b<0)throw new Iu(`Array index out of bounds: ${b} < 0.`);if(b>S.length-1)throw new Iu(`Array index out of bounds: ${b} > ${S.length-1}.`);if(b===Math.floor(b))return S[b];const T=Math.floor(b),D=Math.ceil(b),F=S[T],q=S[D];if(typeof F!="number"||typeof q!="number")throw new Iu(`Cannot interpolate between non-number values at index ${b}.`);return da(F,q,b-T)}eachChild(f){f(this.index),f(this.input)}outputDefined(){return!1}serialize(){return["at-interpolated",this.index.serialize(),this.input.serialize()]}}class Ff{constructor(f,b,S,T,D,F){this.inputType=f,this.type=b,this.input=S,this.cases=T,this.outputs=D,this.otherwise=F}static parse(f,b){if(f.length<5)return b.error(`Expected at least 4 arguments, but found only ${f.length-1}.`);if(f.length%2!=1)return b.error("Expected an even number of arguments.");let S,T;b.expectedType&&b.expectedType.kind!=="value"&&(T=b.expectedType);const D={},F=[];for(let X=2;XNumber.MAX_SAFE_INTEGER)return b.error(`Branch labels must be integers no larger than ${Number.MAX_SAFE_INTEGER}.`,X);if(typeof Ne=="number"&&Math.floor(Ne)!==Ne)return b.error("Numeric branch labels must be integer values.",X);if(S){if(b.checkSubtype(S,rd(Ne),X))return null}else S=rd(Ne);if(D[String(Ne)]!==void 0)return b.error("Branch labels must be unique.",X);D[String(Ne)]=F.length}const xe=b.parse(pe,X,T);if(!xe)return null;T=T||xe.type,F.push(xe)}const q=b.parse(f[1],1,Po);if(!q)return null;const K=b.parse(f.at(-1),f.length-1,T);return K?q.type.kind!=="value"&&b.checkSubtype(S,q.type,1)?null:new Ff(S,T,q,D,F,K):null}evaluate(f){const b=this.input.evaluate(f);return(k1(rd(b),this.inputType)&&this.outputs[this.cases[b]]||this.otherwise).evaluate(f)}eachChild(f){f(this.input),this.outputs.forEach(f),f(this.otherwise)}outputDefined(){return this.outputs.every(f=>f.outputDefined())&&this.otherwise.outputDefined()}serialize(){const f=["match",this.input.serialize()],b=Object.keys(this.cases).sort(),S=[],T={};for(const F of b){const q=T[this.cases[F]];q===void 0?(T[this.cases[F]]=S.length,S.push([this.cases[F],[F]])):S[q][1].push(F)}const D=F=>this.inputType.kind==="number"?Number(F):F;for(const[F,q]of S)f.push(q.length===1?D(q[0]):q.map(D)),f.push(this.outputs[F].serialize());return f.push(this.otherwise.serialize()),f}}class Dg{constructor(f,b,S){this.type=f,this.branches=b,this.otherwise=S}static parse(f,b){if(f.length<4)return b.error(`Expected at least 3 arguments, but found only ${f.length-1}.`),null;if(f.length%2!=0)return b.error("Expected an odd number of arguments."),null;let S;b.expectedType&&b.expectedType.kind!=="value"&&(S=b.expectedType);const T=[];for(let F=1;Fb.outputDefined())&&this.otherwise.outputDefined()}serialize(){const f=["case"];return this.eachChild(b=>{f.push(b.serialize())}),f}}class _d{constructor(f,b,S,T){this.type=f,this.input=b,this.beginIndex=S,this.endIndex=T}static parse(f,b){if(f.length<=2||f.length>=5)return b.error(`Expected 3 or 4 arguments, but found ${f.length-1} instead.`),null;const S=b.parse(f[1],1,Po),T=b.parse(f[2],2,Or);if(!S||!T)return null;if(D=S.type,![Sl(Po),$i,Po].some(F=>F.kind===D.kind))return b.error(`Expected first argument to be of type array or string, but found ${Wl(S.type)} instead`),null;var D;if(f.length===4){const F=b.parse(f[3],3,Or);return F?new _d(S.type,S,T,F):null}return new _d(S.type,S,T)}evaluate(f){const b=this.input.evaluate(f),S=this.beginIndex.evaluate(f);if(!Pb(b,["string","array"]))throw new Iu(`Expected first argument to be of type array or string, but found ${Wl(rd(b))} instead.`);if(this.endIndex){const T=this.endIndex.evaluate(f);return b.slice(S,T)}return b.slice(S)}eachChild(f){f(this.input),f(this.beginIndex),this.endIndex&&f(this.endIndex)}outputDefined(){return!1}serialize(){if(this.endIndex!=null&&this.endIndex!==void 0){const f=this.endIndex.serialize();return["slice",this.input.serialize(),this.beginIndex.serialize(),f]}return["slice",this.input.serialize(),this.beginIndex.serialize()]}}function Qp(w,f){return w==="=="||w==="!="?f.kind==="boolean"||f.kind==="string"||f.kind==="number"||f.kind==="null"||f.kind==="value":f.kind==="string"||f.kind==="number"||f.kind==="value"}function wd(w,f,b,S){return S.compare(f,b)===0}function ll(w,f,b){const S=w!=="=="&&w!=="!=";return class XAt{constructor(D,F,q){this.type=Qi,this.lhs=D,this.rhs=F,this.collator=q,this.hasUntypedArgument=D.type.kind==="value"||F.type.kind==="value"}static parse(D,F){if(D.length!==3&&D.length!==4)return F.error("Expected two or three arguments.");const q=D[0];let K=F.parse(D[1],1,Po);if(!K)return null;if(!Qp(q,K.type))return F.error(`"${q}" comparisons are not supported for type '${Wl(K.type)}'.`,1);let X=F.parse(D[2],2,Po);if(!X)return null;if(!Qp(q,X.type))return F.error(`"${q}" comparisons are not supported for type '${Wl(X.type)}'.`,2);if(K.type.kind!==X.type.kind&&K.type.kind!=="value"&&X.type.kind!=="value")return F.error(`Cannot compare types '${Wl(K.type)}' and '${Wl(X.type)}'.`);S&&(K.type.kind==="value"&&X.type.kind!=="value"?K=new wi(X.type,[K]):K.type.kind!=="value"&&X.type.kind==="value"&&(X=new wi(K.type,[X])));let ce=null;if(D.length===4){if(K.type.kind!=="string"&&X.type.kind!=="string"&&K.type.kind!=="value"&&X.type.kind!=="value")return F.error("Cannot use collator to compare non-string types.");if(ce=F.parse(D[3],3,hp),!ce)return null}return new XAt(K,X,ce)}evaluate(D){const F=this.lhs.evaluate(D),q=this.rhs.evaluate(D);if(S&&this.hasUntypedArgument){const K=rd(F),X=rd(q);if(K.kind!==X.kind||K.kind!=="string"&&K.kind!=="number")throw new Iu(`Expected arguments for "${w}" to be (string, string) or (number, number), but found (${K.kind}, ${X.kind}) instead.`)}if(this.collator&&!S&&this.hasUntypedArgument){const K=rd(F),X=rd(q);if(K.kind!=="string"||X.kind!=="string")return f(D,F,q)}return this.collator?b(D,F,q,this.collator.evaluate(D)):f(D,F,q)}eachChild(D){D(this.lhs),D(this.rhs),this.collator&&D(this.collator)}outputDefined(){return!0}serialize(){const D=[w];return this.eachChild(F=>{D.push(F.serialize())}),D}}}const Du=ll("==",function(w,f,b){return f===b},wd),Oc=ll("!=",function(w,f,b){return f!==b},function(w,f,b,S){return!wd(0,f,b,S)}),Hh=ll("<",function(w,f,b){return f",function(w,f,b){return f>b},function(w,f,b,S){return S.compare(f,b)>0}),Cv=ll("<=",function(w,f,b){return f<=b},function(w,f,b,S){return S.compare(f,b)<=0}),Sh=ll(">=",function(w,f,b){return f>=b},function(w,f,b,S){return S.compare(f,b)>=0});class W_{constructor(f,b,S,T,D,F){this.type=$i,this.number=f,this.locale=b,this.currency=S,this.unit=T,this.minFractionDigits=D,this.maxFractionDigits=F}static parse(f,b){if(f.length!==3)return b.error("Expected two arguments.");const S=b.parse(f[1],1,Or);if(!S)return null;const T=f[2];if(typeof T!="object"||Array.isArray(T))return b.error("NumberFormat options argument must be an object.");let D=null;if(T.locale&&(D=b.parseObjectValue(T.locale,2,"locale",$i),!D))return null;let F=null;if(T.currency&&(F=b.parseObjectValue(T.currency,2,"currency",$i),!F))return null;let q=null;if(T.unit&&(q=b.parseObjectValue(T.unit,2,"unit",$i),!q))return null;let K=null;if(T["min-fraction-digits"]!==void 0&&(K=b.parseObjectValue(T["min-fraction-digits"],2,"min-fraction-digits",Or),!K))return null;let X=null;return T["max-fraction-digits"]===void 0||(X=b.parseObjectValue(T["max-fraction-digits"],2,"max-fraction-digits",Or),X)?new W_(S,D,F,q,K,X):null}evaluate(f){return new Intl.NumberFormat(this.locale?this.locale.evaluate(f):[],{style:(this.currency?"currency":this.unit&&"unit")||"decimal",currency:this.currency?this.currency.evaluate(f):void 0,unit:this.unit?this.unit.evaluate(f):void 0,minimumFractionDigits:this.minFractionDigits?this.minFractionDigits.evaluate(f):void 0,maximumFractionDigits:this.maxFractionDigits?this.maxFractionDigits.evaluate(f):void 0}).format(this.number.evaluate(f))}eachChild(f){f(this.number),this.locale&&f(this.locale),this.currency&&f(this.currency),this.unit&&f(this.unit),this.minFractionDigits&&f(this.minFractionDigits),this.maxFractionDigits&&f(this.maxFractionDigits)}outputDefined(){return!1}serialize(){const f={};return this.locale&&(f.locale=this.locale.serialize()),this.currency&&(f.currency=this.currency.serialize()),this.unit&&(f.unit=this.unit.serialize()),this.minFractionDigits&&(f["min-fraction-digits"]=this.minFractionDigits.serialize()),this.maxFractionDigits&&(f["max-fraction-digits"]=this.maxFractionDigits.serialize()),["number-format",this.number.serialize(),f]}}class M1{constructor(f){this.type=Or,this.input=f}static parse(f,b){if(f.length!==2)return b.error(`Expected 1 argument, but found ${f.length-1} instead.`),null;const S=b.parse(f[1],1);return S?S.type.kind!=="array"&&S.type.kind!=="string"&&S.type.kind!=="value"?(b.error(`Expected argument of type string or array, but found ${Wl(S.type)} instead.`),null):new M1(S):null}evaluate(f){const b=this.input.evaluate(f);if(typeof b=="string"||Array.isArray(b))return b.length;throw new Iu(`Expected value to be of type string or array, but found ${Wl(rd(b))} instead.`)}eachChild(f){f(this.input)}outputDefined(){return!1}serialize(){const f=["length"];return this.eachChild(b=>{f.push(b.serialize())}),f}}function P1(w){return function(){w=1831565813+(w|=0)|0;let f=Math.imul(w^w>>>15,1|w);return f=f+Math.imul(f^f>>>7,61|f)^f,((f^f>>>14)>>>0)/4294967296}}const Jp={"==":Du,"!=":Oc,">":zf,"<":Hh,">=":Sh,"<=":Cv,array:wi,at:pp,"at-interpolated":Xp,boolean:wi,case:Dg,coalesce:Ru,collator:C1,format:Lf,image:wv,interpolate:Qd,"interpolate-hcl":Qd,"interpolate-lab":Qd,length:M1,let:Am,literal:If,match:Ff,number:wi,"number-format":W_,object:wi,slice:_d,step:Hi,string:wi,"to-boolean":Dy,"to-color":Dy,"to-number":Dy,"to-string":Dy,var:Ui,within:Lg,distance:Yi,config:Cm};function M0(w,[f,b,S,T]){f=f.evaluate(w),b=b.evaluate(w),S=S.evaluate(w);const D=T?T.evaluate(w):1,F=S1(f,b,S,D);if(F)throw new Iu(F);return new Mi(f/255,b/255,S/255,D)}function eg(w,[f,b,S,T]){f=f.evaluate(w),b=b.evaluate(w),S=S.evaluate(w);const D=T?T.evaluate(w):1,F=function(X,ce,pe,xe){return typeof X=="number"&&X>=0&&X<=360?typeof ce=="number"&&ce>=0&&ce<=100&&typeof pe=="number"&&pe>=0&&pe<=100?xe===void 0||typeof xe=="number"&&xe>=0&&xe<=1?null:`Invalid hsla value [${[X,ce,pe,xe].join(", ")}]: 'a' must be between 0 and 1.`:`Invalid hsla value [${(typeof xe=="number"?[X,ce,pe,xe]:[X,ce,pe]).join(", ")}]: 's', and 'l' must be between 0 and 100.`:`Invalid hsla value [${(typeof xe=="number"?[X,ce,pe,xe]:[X,ce,pe]).join(", ")}]: 'h' must be between 0 and 360.`}(f,b,S,D);if(F)throw new Iu(F);const q=`hsla(${f}, ${b}%, ${S}%, ${D})`,K=Mi.parse(q);if(!K)throw new Iu(`Failed to parse HSLA color: ${q}`);return K}function qk(w,f){return w in f}function Db(w,f){const b=f[w];return b===void 0?null:b}function nf(w){return{type:w}}function I1(w,f){if(!Pb(w,["boolean","string","number","null"]))throw new Iu(`Expected first argument to be of type boolean, string, number or null, but found ${Wl(rd(w))} instead.`);if(!Pb(f,["string","array"]))throw new Iu(`Expected second argument to be of type array or string, but found ${Wl(rd(f))} instead.`)}function L1(w){if(w instanceof Cm)return new Set([w.key]);let f=new Set;return w.eachChild(b=>{f=new Set([...f,...L1(b)])}),f}function Av(w){if(w instanceof Rf&&w.name==="is-active-floor")return!0;let f=!1;return w.eachChild(b=>{!f&&Av(b)&&(f=!0)}),f}function P0(w){return{result:"success",value:w}}function Og(w){return{result:"error",value:w}}function I0(w,f){return!!w&&!!w.parameters&&w.parameters.includes(f)}function Ob(w){return w["property-type"]==="data-driven"}function Ev(w){return I0(w.expression,"measure-light")}function Cj(w){return I0(w.expression,"zoom")}function Fb(w){return!!w.expression&&w.expression.interpolated}function Zx(w){return typeof w=="object"&&w!==null&&!Array.isArray(w)}function gp(w){return w}function Tv(w,f){const b=f.type==="color",S=w.stops&&typeof w.stops[0][0]=="object",T=S||!(S||w.property!==void 0),D=w.type||(Fb(f)?"exponential":"interval");if(b&&((w={...w}).stops&&(w.stops=w.stops.map(X=>[X[0],Mi.parse(X[1])])),w.default=Mi.parse(w.default?w.default:f.default)),w.colorSpace&&w.colorSpace!=="rgb"&&!Xu[w.colorSpace])throw new Error(`Unknown color space: ${w.colorSpace}`);let F,q,K;if(D==="exponential")F=Vk;else if(D==="interval")F=zb;else if(D==="categorical"){F=Fg,q=Object.create(null);for(const X of w.stops)q[X[0]]=X[1];K=typeof w.stops[0][0]}else{if(D!=="identity")throw new Error(`Unknown function type "${D}"`);F=tN}if(S){const X={},ce=[];for(let Ne=0;NeNe[0]),evaluate:({zoom:Ne},Me)=>Vk({stops:pe,base:w.base},f,Ne).evaluate(Ne,Me)}}if(T){const X=D==="exponential"?{name:"exponential",base:w.base!==void 0?w.base:1}:null;return{kind:"camera",interpolationType:X,interpolationFactor:Qd.interpolationFactor.bind(void 0,X),zoomStops:w.stops.map(ce=>ce[0]),evaluate:({zoom:ce})=>F(w,f,ce,q,K)}}return{kind:"source",evaluate(X,ce){const pe=ce&&ce.properties?ce.properties[w.property]:void 0;return pe===void 0?tg(w.default,f.default):F(w,f,pe,q,K)}}}function tg(w,f,b){return w!==void 0?w:f!==void 0?f:b!==void 0?b:void 0}function Fg(w,f,b,S,T){return tg(typeof b===T?S[b]:void 0,w.default,f.default)}function zb(w,f,b){if(!T0(b))return tg(w.default,f.default);const S=w.stops.length;if(S===1||b<=w.stops[0][0])return w.stops[0][1];if(b>=w.stops[S-1][0])return w.stops[S-1][1];const T=Cl(w.stops.map(D=>D[0]),b);return w.stops[T][1]}function Vk(w,f,b){const S=w.base!==void 0?w.base:1;if(!T0(b))return tg(w.default,f.default);const T=w.stops.length;if(T===1||b<=w.stops[0][0])return w.stops[0][1];if(b>=w.stops[T-1][0])return w.stops[T-1][1];const D=Cl(w.stops.map(ce=>ce[0]),b),F=function(ce,pe,xe,Ne){const Me=Ne-xe,ze=ce-xe;return Me===0?0:pe===1?ze/Me:(Math.pow(pe,ze)-1)/(Math.pow(pe,Me)-1)}(b,S,w.stops[D][0],w.stops[D+1][0]),q=w.stops[D][1],K=w.stops[D+1][1];let X=Xd[f.type]||gp;if(w.colorSpace&&w.colorSpace!=="rgb"){const ce=Xu[w.colorSpace];X=(pe,xe)=>ce.reverse(ce.interpolate(ce.forward(pe),ce.forward(xe),F))}return typeof q.evaluate=="function"?{evaluate(...ce){const pe=q.evaluate.apply(void 0,ce),xe=K.evaluate.apply(void 0,ce);if(pe!==void 0&&xe!==void 0)return X(pe,xe,F)}}:X(q,K,F)}function tN(w,f,b){return f.type==="color"?b=Mi.parse(b):f.type==="formatted"?b=Yu.fromString(b.toString()):f.type==="resolvedImage"?b=rm.build(b.toString()):jv(b)===f.type||f.type==="enum"&&f.values[b]||(b=void 0),tg(b,w.default,f.default)}Rf.register(Jp,{error:[{kind:"error"},[$i],(w,[f])=>{throw new Iu(f.evaluate(w))}],typeof:[$i,[Po],(w,[f])=>Wl(rd(f.evaluate(w)))],"to-rgba":[Sl(Or,4),[kh],(w,[f])=>f.evaluate(w).toNonPremultipliedRenderColor(null).toArray()],"to-hsla":[Sl(Or,4),[kh],(w,[f])=>f.evaluate(w).toNonPremultipliedRenderColor(null).toHslaArray()],rgb:[kh,[Or,Or,Or],M0],rgba:[kh,[Or,Or,Or,Or],M0],hsl:[kh,[Or,Or,Or],eg],hsla:[kh,[Or,Or,Or,Or],eg],has:{type:Qi,overloads:[[[$i],(w,[f])=>qk(f.evaluate(w),w.properties())],[[$i,nd],(w,[f,b])=>qk(f.evaluate(w),b.evaluate(w))]]},get:{type:Po,overloads:[[[$i],(w,[f])=>Db(f.evaluate(w),w.properties())],[[$i,nd],(w,[f,b])=>Db(f.evaluate(w),b.evaluate(w))]]},"feature-state":[Po,[$i],(w,[f])=>Db(f.evaluate(w),w.featureState||{})],properties:[nd,[],w=>w.properties()],"geometry-type":[$i,[],w=>w.geometryType()],worldview:[$i,[],w=>w.globals.worldview||""],"is-active-floor":[Qi,nf($i),(w,f)=>{if(!(w.globals&&w.globals.activeFloors&&w.globals.activeFloors.size>0))return!1;if(f.length===0)return!0;const b=w.globals.activeFloors;return f.some(S=>{const T=S.evaluate(w);return b.has(T)})}],id:[Po,[],w=>w.id()],zoom:[Or,[],w=>w.globals.zoom],pitch:[Or,[],w=>w.globals.pitch||0],"distance-from-center":[Or,[],w=>w.distanceFromCenter()],"measure-light":[Or,[$i],(w,[f])=>w.measureLight(f.evaluate(w))],"heatmap-density":[Or,[],w=>w.globals.heatmapDensity||0],"line-progress":[Or,[],w=>w.globals.lineProgress||0],"raster-value":[Or,[],w=>w.globals.rasterValue||0],"raster-particle-speed":[Or,[],w=>w.globals.rasterParticleSpeed||0],"sky-radial-progress":[Or,[],w=>w.globals.skyRadialProgress||0],accumulated:[Po,[],w=>w.globals.accumulated===void 0?null:w.globals.accumulated],"+":[Or,nf(Or),(w,f)=>{let b=0;for(const S of f)b+=S.evaluate(w);return b}],"*":[Or,nf(Or),(w,f)=>{let b=1;for(const S of f)b*=S.evaluate(w);return b}],"-":{type:Or,overloads:[[[Or,Or],(w,[f,b])=>f.evaluate(w)-b.evaluate(w)],[[Or],(w,[f])=>-f.evaluate(w)]]},"/":[Or,[Or,Or],(w,[f,b])=>f.evaluate(w)/b.evaluate(w)],"%":[Or,[Or,Or],(w,[f,b])=>f.evaluate(w)%b.evaluate(w)],ln2:[Or,[],()=>Math.LN2],pi:[Or,[],()=>Math.PI],e:[Or,[],()=>Math.E],"^":[Or,[Or,Or],(w,[f,b])=>Math.pow(f.evaluate(w),b.evaluate(w))],sqrt:[Or,[Or],(w,[f])=>Math.sqrt(f.evaluate(w))],log10:[Or,[Or],(w,[f])=>Math.log(f.evaluate(w))/Math.LN10],ln:[Or,[Or],(w,[f])=>Math.log(f.evaluate(w))],log2:[Or,[Or],(w,[f])=>Math.log2(f.evaluate(w))],sin:[Or,[Or],(w,[f])=>Math.sin(f.evaluate(w))],cos:[Or,[Or],(w,[f])=>Math.cos(f.evaluate(w))],tan:[Or,[Or],(w,[f])=>Math.tan(f.evaluate(w))],asin:[Or,[Or],(w,[f])=>Math.asin(f.evaluate(w))],acos:[Or,[Or],(w,[f])=>Math.acos(f.evaluate(w))],atan:[Or,[Or],(w,[f])=>Math.atan(f.evaluate(w))],min:[Or,nf(Or),(w,f)=>Math.min(...f.map(b=>b.evaluate(w)))],max:[Or,nf(Or),(w,f)=>Math.max(...f.map(b=>b.evaluate(w)))],abs:[Or,[Or],(w,[f])=>Math.abs(f.evaluate(w))],round:[Or,[Or],(w,[f])=>{const b=f.evaluate(w);return b<0?-Math.round(-b):Math.round(b)}],floor:[Or,[Or],(w,[f])=>Math.floor(f.evaluate(w))],ceil:[Or,[Or],(w,[f])=>Math.ceil(f.evaluate(w))],"filter-==":[Qi,[$i,Po],(w,[f,b])=>w.properties()[f.value]===b.value],"filter-id-==":[Qi,[Po],(w,[f])=>w.id()===f.value],"filter-type-==":[Qi,[$i],(w,[f])=>w.geometryType()===f.value],"filter-<":[Qi,[$i,Po],(w,[f,b])=>{const S=w.properties()[f.value],T=b.value;return typeof S==typeof T&&S{const b=w.id(),S=f.value;return typeof b==typeof S&&b":[Qi,[$i,Po],(w,[f,b])=>{const S=w.properties()[f.value],T=b.value;return typeof S==typeof T&&S>T}],"filter-id->":[Qi,[Po],(w,[f])=>{const b=w.id(),S=f.value;return typeof b==typeof S&&b>S}],"filter-<=":[Qi,[$i,Po],(w,[f,b])=>{const S=w.properties()[f.value],T=b.value;return typeof S==typeof T&&S<=T}],"filter-id-<=":[Qi,[Po],(w,[f])=>{const b=w.id(),S=f.value;return typeof b==typeof S&&b<=S}],"filter->=":[Qi,[$i,Po],(w,[f,b])=>{const S=w.properties()[f.value],T=b.value;return typeof S==typeof T&&S>=T}],"filter-id->=":[Qi,[Po],(w,[f])=>{const b=w.id(),S=f.value;return typeof b==typeof S&&b>=S}],"filter-has":[Qi,[Po],(w,[f])=>f.value in w.properties()],"filter-has-id":[Qi,[],w=>w.id()!==null&&w.id()!==void 0],"filter-type-in":[Qi,[Sl($i)],(w,[f])=>f.value.includes(w.geometryType())],"filter-id-in":[Qi,[Sl(Po)],(w,[f])=>f.value.includes(w.id())],"filter-in-small":[Qi,[$i,Sl(Po)],(w,[f,b])=>b.value.includes(w.properties()[f.value])],"filter-in-large":[Qi,[$i,Sl(Po)],(w,[f,b])=>function(S,T,D,F){for(;D<=F;){const q=D+F>>1;if(T[q]===S)return!0;T[q]>S?F=q-1:D=q+1}return!1}(w.properties()[f.value],b.value,0,b.value.length-1)],all:{type:Qi,overloads:[[[Qi,Qi],(w,[f,b])=>f.evaluate(w)&&b.evaluate(w)],[nf(Qi),(w,f)=>{for(const b of f)if(!b.evaluate(w))return!1;return!0}]]},any:{type:Qi,overloads:[[[Qi,Qi],(w,[f,b])=>f.evaluate(w)||b.evaluate(w)],[nf(Qi),(w,f)=>{for(const b of f)if(b.evaluate(w))return!0;return!1}]]},"!":[Qi,[Qi],(w,[f])=>!f.evaluate(w)],"is-supported-script":[Qi,[$i],(w,[f])=>{const b=w.globals&&w.globals.isSupportedScript;return!b||b(f.evaluate(w))}],upcase:[$i,[$i],(w,[f])=>f.evaluate(w).toUpperCase()],downcase:[$i,[$i],(w,[f])=>f.evaluate(w).toLowerCase()],concat:[$i,nf(Po),(w,f)=>f.map(b=>Xm(b.evaluate(w))).join("")],split:[Sl($i),[$i,$i],(w,[f,b])=>f.evaluate(w).split(b.evaluate(w))],in:[Qi,[Po,Po],(w,[f,b])=>{const S=f.evaluate(w),T=b.evaluate(w);return T!=null&&(I1(S,T),T.includes(S))}],"index-of":{type:Or,overloads:[[[Po,Po],(w,[f,b])=>{const S=f.evaluate(w),T=b.evaluate(w);return I1(S,T),T.indexOf(S)}],[[Po,Po,Or],(w,[f,b,S])=>{const T=f.evaluate(w),D=b.evaluate(w),F=S.evaluate(w);return I1(T,D),D.indexOf(T,F)}]]},"resolved-locale":[$i,[hp],(w,[f])=>f.evaluate(w).resolvedLocale()],random:[Or,[Or,Or,Po],(w,f)=>{const[b,S,T]=f.map(F=>F.evaluate(w));if(b>S||b===S)return b;let D;if(typeof T=="string")D=function(F){let q=0;if(F.length===0)return q;for(let K=0;KJSON.stringify(pe)).join(", ")}, but found ${JSON.stringify(ce)} instead.`);return ce}catch(ce){const pe=ce;return this._warningHistory[pe.message]||(this._warningHistory[pe.message]=!0,typeof console<"u"&&console.warn(`Failed to evaluate expression "${JSON.stringify(this.expression.serialize())}". ${pe.message}`)),this._defaultValue}}}function Xx(w){return Array.isArray(w)&&w.length>0&&typeof w[0]=="string"&&Object.hasOwn(Jp,w[0])}function R1(w,f,b,S,T){const D=new il(Jp,[],f?function(q){const K={color:kh,string:$i,number:Or,enum:$i,boolean:Qi,formatted:mx,resolvedImage:Pf,object:nd};return q.type==="array"?Sl(K[q.value]||Po,q.length):K[q.type]}(f):void 0,void 0,void 0,b,S,T),F=D.parse(w,void 0,void 0,void 0,f&&f.type==="string"?{typeAnnotation:"coerce"}:void 0);return F?P0(new Hk(F,f,b,S,T)):Og(D.errors)}class D1{constructor(f,b,S,T){this.kind=f,this._styleExpression=b,this.isLightConstant=S,this.isLineProgressConstant=T,this.isStateDependent=f!=="constant"&&!A1(b.expression),this.configDependencies=L1(b.expression),this.isIndoorDependent=Av(b.expression)}evaluateWithoutErrorHandling(f,b,S,T,D,F){return this._styleExpression.evaluateWithoutErrorHandling(f,b,S,T,D,F)}evaluate(f,b,S,T,D,F,q){return this._styleExpression.evaluate(f,b,S,T,D,F,void 0,void 0,q)}}class xp{constructor(f,b,S,T,D,F){this.kind=f,this.zoomStops=S,this._styleExpression=b,this.isStateDependent=f!=="camera"&&!A1(b.expression),this.isIndoorDependent=Av(b.expression),this.isLightConstant=D,this.isLineProgressConstant=F,this.configDependencies=L1(b.expression),this.interpolationType=T}evaluateWithoutErrorHandling(f,b,S,T,D,F){return this._styleExpression.evaluateWithoutErrorHandling(f,b,S,T,D,F)}evaluate(f,b,S,T,D,F){return this._styleExpression.evaluate(f,b,S,T,D,F)}interpolationFactor(f,b,S){return this.interpolationType?Qd.interpolationFactor(this.interpolationType,f,b,S):0}}function L0(w,f,b,S,T){if((w=R1(w,f,b,S,T)).result==="error")return w;const D=w.value.expression,F=qh(D);if(!F&&!Ob(f))return Og([new al("","data expressions not supported")]);const q=Yp(D,["zoom","pitch","distance-from-center"]);if(!q&&!Cj(f))return Og([new al("","zoom expressions not supported")]);const K=Yp(D,["measure-light"]);if(!K&&!Ev(f))return Og([new al("","measure-light expression not supported")]);const X=Yp(D,["line-progress"]);if(!X&&!function(xe){return I0(xe.expression,"line-progress")}(f))return Og([new al("","line-progress expression not supported")]);const ce=f.expression&&f.expression.relaxZoomRestriction,pe=yp(D);return pe||q||ce?pe instanceof al?Og([pe]):pe instanceof Qd&&!Fb(f)?Og([new al("",'"interpolate" expressions cannot be used with this property')]):P0(pe?new xp(F&&X?"camera":"composite",w.value,pe.labels,pe instanceof Qd?pe.interpolation:void 0,K,X):new D1(F&&X?"constant":"source",w.value,K,X)):Og([new al("",'"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression, or in the properties of atmosphere.')])}class Qx{constructor(f,b){this._parameters=f,this._specification=b,Object.assign(this,Tv(this._parameters,this._specification))}static deserialize(f){return new Qx(f._parameters,f._specification)}static serialize(f){return{_parameters:f._parameters,_specification:f._specification}}}function yp(w){let f=null;if(w instanceof Am)f=yp(w.result);else if(w instanceof Ru){for(const b of w.args)if(f=yp(b),f)break}else(w instanceof Hi||w instanceof Qd)&&w.input instanceof Rf&&w.input.name==="zoom"&&(f=w);return f instanceof al||w.eachChild(b=>{const S=yp(b);S instanceof al?f=S:f&&S&&f!==S&&(f=new al("",'Only one zoom-based "step" or "interpolate" subexpression may be used in an expression.'))}),f}class xx{constructor(f,b,S){if(this.boxSeen=new Uint32Array(0),this.circleSeen=new Uint32Array(0),this.generation=0,f instanceof ArrayBuffer){const T=new Int32Array(f);this.width=T[0],this.height=T[1],this.xCellCount=T[2],this.yCellCount=T[3],this.boxUid=T[4],this.circleUid=T[5];const D=this.xCellCount*this.yCellCount,F=[];for(let ce=0;cethis.width||T<0||b>this.height)return F;const q=this._nextGen(),{boxCells:K,circleCells:X,boxKeys:ce,circleKeys:pe,bboxes:xe,circles:Ne,boxSeen:Me,circleSeen:ze,xCellCount:Ve}=this,Je=this._xCell(f),lt=this._yCell(b),ht=this._xCell(S),ct=this._yCell(T);for(let xt=Je;xt<=ht;xt++)for(let kt=lt;kt<=ct;kt++){const es=Ve*kt+xt,Ct=K[es];if(Ct)for(let Zt=0;Zt=Fs&&T>=on&&(!D||D(ce[Qt]))&&F.push({key:ce[Qt],x1:Fs,y1:on,x2:sn,y2:hn})}const Lt=X[es];if(Lt)for(let Zt=0;Ztthis.width||T<0||b>this.height)return F;const q=this._nextGen(),{boxCells:K,boxKeys:X,bboxes:ce,boxSeen:pe,xCellCount:xe,xScale:Ne,yScale:Me}=this,ze=this._xCell(f),Ve=this._yCell(b),Je=this._xCell(S),lt=this._yCell(T);for(let ht=ze;ht<=Je;ht++)for(let ct=Ve;ct<=lt;ct++){if(D&&!D(ht/Ne,ct/Me,(ht+1)/Ne,(ct+1)/Me))continue;const xt=K[xe*ct+ht];if(xt)for(let kt=0;kt=Lt&&T>=Zt)&&F.push(X[es])}}return F}hitTest(f,b,S,T,D){if(S<0||f>this.width||T<0||b>this.height)return!1;const F=this._nextGen(),{boxCells:q,circleCells:K,boxKeys:X,circleKeys:ce,bboxes:pe,circles:xe,boxSeen:Ne,circleSeen:Me,xCellCount:ze}=this,Ve=this._xCell(f),Je=this._yCell(b),lt=this._xCell(S),ht=this._yCell(T);for(let ct=Ve;ct<=lt;ct++)for(let xt=Je;xt<=ht;xt++){const kt=ze*xt+ct,es=q[kt];if(es)for(let Lt=0;Lt=pe[Qt]&&T>=pe[Qt+1]&&(!D||D(X[Zt])))return!0}const Ct=K[kt];if(Ct)for(let Lt=0;Ltthis.width||K<0||F>this.height)return!1;const X=this._nextGen(),{boxCells:ce,circleCells:pe,boxKeys:xe,circleKeys:Ne,bboxes:Me,circles:ze,boxSeen:Ve,circleSeen:Je,xCellCount:lt}=this,ht=this._xCell(D),ct=this._yCell(F),xt=this._xCell(q),kt=this._yCell(K);for(let es=ht;es<=xt;es++)for(let Ct=ct;Ct<=kt;Ct++){const Lt=lt*Ct+es,Zt=ce[Lt];if(Zt)for(let Cs=0;Cs>>0,this.generation===0&&(this.boxSeen.fill(0),this.circleSeen.fill(0),this.generation=1),this.generation}_circlesCollide(f,b,S,T,D,F){const q=T-f,K=D-b,X=S+F;return X*X>q*q+K*K}_circleAndRectCollide(f,b,S,T,D,F,q){const K=(F-T)/2,X=Math.abs(f-(T+K));if(X>K+S)return!1;const ce=(q-D)/2,pe=Math.abs(b-(D+ce));if(pe>ce+S)return!1;if(X<=K||pe<=ce)return!0;const xe=X-K,Ne=pe-ce;return xe*xe+Ne*Ne<=S*S}}const Jx={};function Vr(w,f,b={}){Object.defineProperty(w,"_classRegistryKey",{value:f,writable:!1}),Jx[f]={klass:w,omit:b.omit||[]}}Vr(Object,"Object"),Vr(xx,"Grid"),delete Kt.prototype.constructor,Vr(Mi,"Color"),Vr(Yu,"Formatted"),Vr(_v,"FormattedSection"),Vr(rm,"ResolvedImage"),Vr(Qx,"StylePropertyFunction"),Vr(Hk,"StyleExpression",{omit:["_evaluator"]}),Vr(Gl,"ImageId"),Vr(Kp,"ImageVariant"),Vr(xp,"ZoomDependentExpression"),Vr(D1,"ZoomConstantExpression"),Vr(Rf,"CompoundExpression",{omit:["_evaluate"]});for(const w in Jp)Jx[Jp[w]._classRegistryKey]||Vr(Jp[w],`Expression${w}`);function v4(w){return w&&(w instanceof ArrayBuffer||w.constructor&&w.constructor.name==="ArrayBuffer")}const b4={Error,TypeError,RangeError,SyntaxError,ReferenceError,URIError,EvalError},K_=new Set(["message","stack","cause","errors","name","class"]);function Gh(w,f){if(w===null)return null;const b=typeof w;if(b!=="object")return b==="bigint"?{$name:"BigInt",value:w.toString()}:w;if(Array.isArray(w)){const F=w.length,q=[];q.length=F;for(let K=0;Kce!==F).map(ce=>Gh(ce,f)));const X=F;for(const ce in X)Object.hasOwn(X,ce)&&(K_.has(ce)||(K[ce]=Gh(X[ce],f)));return K}const S=w.constructor||Object,T=S._classRegistryKey;if(!T)throw new Error(`Can't serialize object of unregistered class "${S.name}".`);const D=S.serialize?S.serialize(w,f):{};if(!S.serialize){const F=Jx[T].omit,q=w;for(const K in q)Object.hasOwn(q,K)&&(F.includes(K)||(D[K]=Gh(q[K],f)))}if(D.$name)throw new Error("$name property is reserved for worker serialization logic.");return T!=="Object"&&(D.$name=T),D}function R0(w){if(w===null||typeof w!="object")return w;if(Array.isArray(w)){for(let T=0;Tw>=1536&&w<=1791,C6=w=>w>=1872&&w<=1919,Ou=w=>w>=2208&&w<=2303,_4=w=>w>=11904&&w<=12031,w4=w=>w>=12032&&w<=12255,A6=w=>w>=12272&&w<=12287,j4=w=>w>=12288&&w<=12351,N4=w=>w>=12352&&w<=12447,sN=w=>w>=12448&&w<=12543,E6=w=>w>=12544&&w<=12591,ey=w=>w>=12704&&w<=12735,pA=w=>w>=12736&&w<=12783,e7=w=>w>=12784&&w<=12799,Z_=w=>w>=12800&&w<=13055,k4=w=>w>=13056&&w<=13311,X_=w=>w>=13312&&w<=19903,D0=w=>w>=19968&&w<=40959,S4=w=>w>=40960&&w<=42127,Q_=w=>w>=42128&&w<=42191,t7=w=>w>=44032&&w<=55215,T6=w=>w>=63744&&w<=64255,gA=w=>w>=64336&&w<=65023,M6=w=>w>=65040&&w<=65055,xA=w=>w>=65072&&w<=65103,C4=w=>w>=65104&&w<=65135,P6=w=>w>=65136&&w<=65279,nN=w=>w>=65280&&w<=65519;function J(w){for(const f of w)if(Le(f.charCodeAt(0)))return!0;return!1}function ie(w){return!(Y_(w)||C6(w)||Ou(w)||gA(w)||P6(w))}function Le(w){return!(w!==746&&w!==747&&(w<4352||!(ey(w)||E6(w)||xA(w)&&!(w>=65097&&w<=65103)||T6(w)||k4(w)||_4(w)||pA(w)||!(!j4(w)||w>=12296&&w<=12305||w>=12308&&w<=12319||w===12336)||X_(w)||D0(w)||Z_(w)||(f=>f>=12592&&f<=12687)(w)||(f=>f>=43360&&f<=43391)(w)||(f=>f>=55216&&f<=55295)(w)||(f=>f>=4352&&f<=4607)(w)||t7(w)||N4(w)||A6(w)||(f=>f>=12688&&f<=12703)(w)||w4(w)||e7(w)||sN(w)&&w!==12540||!(!nN(w)||w===65288||w===65289||w===65293||w>=65306&&w<=65310||w===65339||w===65341||w===65343||w>=65371&&w<=65503||w===65507||w>=65512&&w<=65519)||!(!C4(w)||w>=65112&&w<=65118||w>=65123&&w<=65126)||(f=>f>=5120&&f<=5759)(w)||(f=>f>=6320&&f<=6399)(w)||M6(w)||(f=>f>=19904&&f<=19967)(w)||S4(w)||Q_(w))))}function Qe(w){return!(Le(w)||function(f){return!!((b=>b>=128&&b<=255)(f)&&(f===167||f===169||f===174||f===177||f===188||f===189||f===190||f===215||f===247)||(b=>b>=8192&&b<=8303)(f)&&(f===8214||f===8224||f===8225||f===8240||f===8241||f===8251||f===8252||f===8258||f===8263||f===8264||f===8265||f===8273)||(b=>b>=8448&&b<=8527)(f)||(b=>b>=8528&&b<=8591)(f)||(b=>b>=8960&&b<=9215)(f)&&(f>=8960&&f<=8967||f>=8972&&f<=8991||f>=8996&&f<=9e3||f===9003||f>=9085&&f<=9114||f>=9150&&f<=9165||f===9167||f>=9169&&f<=9179||f>=9186&&f<=9215)||(b=>b>=9216&&b<=9279)(f)&&f!==9251||(b=>b>=9280&&b<=9311)(f)||(b=>b>=9312&&b<=9471)(f)||(b=>b>=9632&&b<=9727)(f)||(b=>b>=9728&&b<=9983)(f)&&!(f>=9754&&f<=9759)||(b=>b>=11008&&b<=11263)(f)&&(f>=11026&&f<=11055||f>=11088&&f<=11097||f>=11192&&f<=11243)||j4(f)||sN(f)||(b=>b>=57344&&b<=63743)(f)||xA(f)||C4(f)||nN(f)||f===8734||f===8756||f===8757||f>=9984&&f<=10087||f>=10102&&f<=10131||f===65532||f===65533)}(w))}function it(w){return w>=1424&&w<=2303||gA(w)||P6(w)}function It(w,f){return!(!f&&it(w)||w>=2304&&w<=3583||w>=3840&&w<=4255||(b=>b>=6016&&b<=6143)(w))}function Ds(w){for(const f of w)if(it(f.charCodeAt(0)))return!0;return!1}const $n={unavailable:"unavailable",deferred:"deferred",loading:"loading",parsing:"parsing",parsed:"parsed",loaded:"loaded",error:"error"};let Pr=null,Sa=$n.unavailable,qi=null;const Kl=function(w){w&&(Sa=$n.error),Pr&&Pr(w)};function Di(){cu.fire(new Km("pluginStateChange",{pluginStatus:Sa,pluginURL:qi}))}const cu=new Fd,Bd=function(){return Sa},Qu=function(){if(Sa!==$n.deferred||!qi)throw new Error("rtl-text-plugin cannot be downloaded unless a pluginURL is specified");Sa=$n.loading,Di(),qi&&fr({url:qi}).then(()=>{Sa=$n.loaded,Di()}).catch(w=>{Kl(w)})},vp={applyArabicShaping:null,processBidirectionalText:null,processStyledBidirectionalText:null,isLoaded:()=>Sa===$n.loaded||vp.applyArabicShaping!=null,isLoading:()=>Sa===$n.loading,setState(w){Sa=w.pluginStatus,qi=w.pluginURL},isParsing:()=>Sa===$n.parsing,isParsed:()=>Sa===$n.parsed,getPluginURL:()=>qi};class tr{constructor(f,b){this.zoom=f,b?(this.now=b.now,this.fadeDuration=b.fadeDuration,this.transition=b.transition,this.pitch=b.pitch,this.brightness=b.brightness,this.worldview=b.worldview,this.activeFloors=b.activeFloors):(this.now=0,this.fadeDuration=0,this.transition={},this.pitch=0,this.brightness=0)}isSupportedScript(f){return function(b,S){for(const T of b)if(!It(T.charCodeAt(0),S))return!1;return!0}(f,vp.isLoaded())}}class ar{constructor(f,b,S,T,D){this.property=f,this.value=b,this.expression=function(F,q,K,X,ce){if(Zx(F))return new Qx(F,q);if(Xx(F)||Array.isArray(F)&&F.length>0){const pe=L0(F,q,K,X,ce);if(pe.result==="error")throw new Error(pe.value.map(xe=>`${xe.key}: ${xe.message}`).join(", "));return pe.value}{let pe=F;return typeof F=="string"&&q.type==="color"&&(pe=Mi.parse(F)),{kind:"constant",configDependencies:new Set,isIndoorDependent:!1,evaluate:()=>pe}}}(b===void 0?f.specification.default:b,f.specification,S,T,D)}isIndoorDependent(){return this.expression.isIndoorDependent}isDataDriven(){return this.expression.kind==="source"||this.expression.kind==="composite"}possiblyEvaluate(f,b,S,T){return this.property.possiblyEvaluate(this,f,b,S,T)}}class qr{constructor(f,b,S,T){this.property=f,this.value=new ar(f,void 0,b,S,T)}transitioned(f,b){return new Vo(this.property,this.value,b,{...f.transition,...this.transition},f.now)}untransitioned(){return new Vo(this.property,this.value,null,{},0)}}class Vi{constructor(f,b,S,T){this._properties=f,this._values=Object.create(f.defaultTransitionablePropertyValues),this._scope=b,this._options=S,this._iconImageUseTheme=T,this._isIndoorDependent=!1,this.configDependencies=new Set}getValue(f){return zo(this._values[f].value.value)}setValue(f,b){Object.hasOwn(this._values,f)||(this._values[f]=new qr(this._values[f].property,this._scope,this._options,this._iconImageUseTheme)),this._values[f].value=new ar(this._values[f].property,b===null?void 0:zo(b),this._scope,this._options,this._iconImageUseTheme),this._values[f].value.expression.configDependencies&&(this.configDependencies=new Set([...this.configDependencies,...this._values[f].value.expression.configDependencies]),this._isIndoorDependent=this._isIndoorDependent||this._values[f].value.isIndoorDependent())}setTransitionOrValue(f,b){b&&(this._options=b);const S=this._properties.properties;if(f)for(const T in f){const D=f[T];if(T.endsWith("-transition")){const F=T.slice(0,-11);S[F]&&this.setTransition(F,D)}else Object.hasOwn(S,T)&&this.setValue(T,D)}}getTransition(f){return zo(this._values[f].transition)}setTransition(f,b){Object.hasOwn(this._values,f)||(this._values[f]=new qr(this._values[f].property)),this._values[f].transition=zo(b)||void 0}serialize(){const f={};for(const b of Object.keys(this._values)){const S=this.getValue(b);S!==void 0&&(f[b]=S);const T=this.getTransition(b);T!==void 0&&(f[`${b}-transition`]=T)}return f}transitioned(f,b){const S=new xc(this._properties);for(const T of Object.keys(this._values))S._values[T]=this._values[T].transitioned(f,b._values[T]);return S}untransitioned(){const f=new xc(this._properties);for(const b of Object.keys(this._values))f._values[b]=this._values[b].untransitioned();return f}isIndoorDependent(){return this._isIndoorDependent}}class Vo{constructor(f,b,S,T,D){const F=T.delay||0,q=T.duration||0;D=D||0,this.property=f,this.value=b,this.begin=D+F,this.end=this.begin+q,f.specification.transition&&(T.delay||T.duration)&&(this.prior=S)}possiblyEvaluate(f,b,S){const T=f.now||0,D=this.value.possiblyEvaluate(f,b,S),F=this.prior;if(F){if(T>this.end)return this.prior=null,D;if(this.value.isDataDriven())return this.prior=null,D;if(T":1,">=":1,"<":1,"<=":1,"in":1,"!in":1,"all":1,"any":1,"none":1,"has":1,"!has":1}},"geometry_type":{"type":"enum","values":{"Point":1,"LineString":1,"Polygon":1}},"function_stop":{"type":"array","minimum":0,"maximum":24,"length":2,"value":["number","color"]},"fog":{"range":{"type":"array","default":[0.5,10],"minimum":-20,"maximum":20,"length":2,"value":"number","expression":{"interpolated":1,"parameters":["measure-light","zoom"],"relaxZoomRestriction":1},"transition":1},"color":{"type":"color","default":"#ffffff","expression":{"interpolated":1,"parameters":["measure-light","zoom"],"relaxZoomRestriction":1},"transition":1,"use-theme":1},"high-color":{"type":"color","default":"#245cdf","expression":{"interpolated":1,"parameters":["measure-light","zoom"],"relaxZoomRestriction":1},"transition":1,"use-theme":1},"space-color":{"type":"color","default":["interpolate",["linear"],["zoom"],4,"#010b19",7,"#367ab9"],"expression":{"interpolated":1,"parameters":["measure-light","zoom"],"relaxZoomRestriction":1},"transition":1,"use-theme":1},"horizon-blend":{"type":"number","default":["interpolate",["linear"],["zoom"],4,0.2,7,0.1],"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["measure-light","zoom"],"relaxZoomRestriction":1},"transition":1},"star-intensity":{"type":"number","default":["interpolate",["linear"],["zoom"],5,0.35,6,0],"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["measure-light","zoom"],"relaxZoomRestriction":1},"transition":1},"vertical-range":{"type":"array","default":[0,0],"minimum":0,"length":2,"value":"number","expression":{"interpolated":1,"parameters":["measure-light","zoom"],"relaxZoomRestriction":1},"transition":1}},"snow":{"density":{"type":"number","default":["interpolate",["linear"],["zoom"],11,0,13,0.85],"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["measure-light","zoom"],"relaxZoomRestriction":1},"transition":1},"intensity":{"type":"number","default":1,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["measure-light","zoom"],"relaxZoomRestriction":1},"transition":1},"color":{"type":"color","default":"#ffffff","expression":{"interpolated":1,"parameters":["measure-light","zoom"],"relaxZoomRestriction":1},"transition":1,"use-theme":1},"opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["measure-light","zoom"],"relaxZoomRestriction":1},"transition":1},"vignette":{"type":"number","default":["interpolate",["linear"],["zoom"],11,0,13,0.3],"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["measure-light","zoom"],"relaxZoomRestriction":1},"transition":1},"vignette-color":{"type":"color","default":"#ffffff","expression":{"interpolated":1,"parameters":["measure-light","zoom"],"relaxZoomRestriction":1},"transition":1,"use-theme":1},"center-thinning":{"type":"number","default":0.4,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["measure-light","zoom"],"relaxZoomRestriction":1},"transition":1},"direction":{"type":"array","default":[0,50],"minimum":0,"maximum":360,"length":2,"value":"number","expression":{"interpolated":1,"parameters":["measure-light","zoom"],"relaxZoomRestriction":1},"transition":1},"flake-size":{"type":"number","default":0.71,"minimum":0,"maximum":5,"expression":{"interpolated":1,"parameters":["measure-light","zoom"],"relaxZoomRestriction":1},"transition":1}},"rain":{"density":{"type":"number","default":["interpolate",["linear"],["zoom"],11,0,13,0.5],"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["measure-light","zoom"],"relaxZoomRestriction":1},"transition":1},"intensity":{"type":"number","default":1,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["measure-light","zoom"],"relaxZoomRestriction":1},"transition":1},"color":{"type":"color","default":["interpolate",["linear"],["measure-light","brightness"],0,"#03113d",0.3,"#a8adbc"],"expression":{"interpolated":1,"parameters":["measure-light","zoom"],"relaxZoomRestriction":1},"transition":1,"use-theme":1},"opacity":{"type":"number","default":["interpolate",["linear"],["measure-light","brightness"],0,0.88,1,0.7],"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["measure-light","zoom"],"relaxZoomRestriction":1},"transition":1},"vignette":{"type":"number","default":["interpolate",["linear"],["zoom"],11,0,13,1],"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["measure-light","zoom"],"relaxZoomRestriction":1},"transition":1},"vignette-color":{"type":"color","default":["interpolate",["linear"],["measure-light","brightness"],0,"#001736",0.3,"#464646"],"expression":{"interpolated":1,"parameters":["measure-light","zoom"],"relaxZoomRestriction":1},"transition":1,"use-theme":1},"center-thinning":{"type":"number","default":0.57,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["measure-light","zoom"],"relaxZoomRestriction":1},"transition":1},"direction":{"type":"array","default":[0,80],"minimum":0,"maximum":360,"length":2,"value":"number","expression":{"interpolated":1,"parameters":["measure-light","zoom"],"relaxZoomRestriction":1},"transition":1},"droplet-size":{"type":"array","default":[2.6,18.2],"minimum":0,"maximum":50,"length":2,"value":"number","expression":{"interpolated":1,"parameters":["measure-light","zoom"],"relaxZoomRestriction":1},"transition":1},"distortion-strength":{"type":"number","default":0.7,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["measure-light","zoom"],"relaxZoomRestriction":1},"transition":1}},"camera":{"camera-projection":{"type":"enum","default":"perspective","values":{"perspective":1,"orthographic":1}}},"colorTheme":{"data":{"type":"string","expression":1}},"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","expression":{"interpolated":1,"parameters":["zoom"]},"transition":1},"color":{"type":"color","default":"#ffffff","expression":{"interpolated":1,"parameters":["zoom"]},"transition":1,"use-theme":1},"intensity":{"type":"number","default":0.5,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["zoom"]},"transition":1}},"projection":{"name":{"type":"enum","default":"mercator","values":{"albers":1,"equalEarth":1,"equirectangular":1,"lambertConformalConic":1,"mercator":1,"naturalEarth":1,"winkelTripel":1,"globe":1}},"center":{"type":"array","minimum":[-180,-90],"maximum":[180,90],"length":2,"value":"number"},"parallels":{"type":"array","minimum":[-90,-90],"maximum":[90,90],"length":2,"value":"number"}},"terrain":{"source":{"type":"string"},"exaggeration":{"type":"number","default":1,"minimum":0,"maximum":1000,"expression":{"interpolated":1,"parameters":["zoom"]},"transition":1}},"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,"expression":{"interpolated":1,"parameters":["feature","feature-state","measure-light","zoom"]},"transition":1,"property-type":"data-driven"},"fill-color":{"type":"color","default":"#000000","expression":{"interpolated":1,"parameters":["feature","feature-state","measure-light","zoom"]},"transition":1,"use-theme":1,"property-type":"data-driven"},"fill-outline-color":{"type":"color","expression":{"interpolated":1,"parameters":["feature","feature-state","measure-light","zoom"]},"transition":1,"use-theme":1,"property-type":"data-driven"},"fill-translate":{"type":"array","default":[0,0],"length":2,"value":"number","expression":{"interpolated":1,"parameters":["zoom"]},"transition":1},"fill-translate-anchor":{"type":"enum","default":"map","values":{"map":1,"viewport":1},"expression":{"parameters":["zoom"]}},"fill-pattern":{"type":"resolvedImage","expression":{"parameters":["feature","zoom"]},"property-type":"data-driven"},"fill-pattern-cross-fade":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["measure-light","zoom"]}},"fill-emissive-strength":{"type":"number","default":0,"minimum":0,"expression":{"interpolated":1,"parameters":["measure-light","zoom"]},"transition":1},"fill-z-offset":{"type":"number","default":0,"minimum":0,"expression":{"interpolated":1,"parameters":["feature","zoom"]},"transition":1,"property-type":"data-driven"},"fill-bridge-guard-rail-color":{"type":"color","default":"rgba(241, 236, 225, 255)","expression":{"interpolated":1,"parameters":["feature","measure-light","zoom"]},"transition":1,"use-theme":1,"property-type":"data-driven"},"fill-tunnel-structure-color":{"type":"color","default":"rgba(241, 236, 225, 255)","expression":{"interpolated":1,"parameters":["feature","measure-light","zoom"]},"transition":1,"use-theme":1,"property-type":"data-driven"}},"paint_fill-extrusion":{"fill-extrusion-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["zoom"]},"transition":1},"fill-extrusion-color":{"type":"color","default":"#000000","expression":{"interpolated":1,"parameters":["feature","feature-state","measure-light","zoom"]},"transition":1,"use-theme":1,"property-type":"data-driven"},"fill-extrusion-translate":{"type":"array","default":[0,0],"length":2,"value":"number","expression":{"interpolated":1,"parameters":["zoom"]},"transition":1},"fill-extrusion-translate-anchor":{"type":"enum","default":"map","values":{"map":1,"viewport":1},"expression":{"parameters":["zoom"]}},"fill-extrusion-pattern":{"type":"resolvedImage","expression":{"parameters":["feature","zoom"]},"property-type":"data-driven"},"fill-extrusion-pattern-cross-fade":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["measure-light","zoom"]}},"fill-extrusion-height":{"type":"number","default":0,"minimum":0,"expression":{"interpolated":1,"parameters":["feature","feature-state","zoom"]},"transition":1,"property-type":"data-driven"},"fill-extrusion-base":{"type":"number","default":0,"minimum":0,"expression":{"interpolated":1,"parameters":["feature","feature-state","zoom"]},"transition":1,"property-type":"data-driven"},"fill-extrusion-height-alignment":{"type":"enum","default":"flat","values":{"terrain":1,"flat":1}},"fill-extrusion-base-alignment":{"type":"enum","default":"terrain","values":{"terrain":1,"flat":1}},"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":1,"parameters":["zoom"]},"transition":1},"fill-extrusion-ambient-occlusion-radius":{"type":"number","default":3,"minimum":0,"expression":{"interpolated":1,"parameters":["zoom"]},"transition":1},"fill-extrusion-ambient-occlusion-wall-radius":{"type":"number","default":3,"minimum":0,"expression":{"interpolated":1,"parameters":["zoom"]},"transition":1},"fill-extrusion-ambient-occlusion-ground-radius":{"type":"number","default":3,"minimum":0,"expression":{"interpolated":1,"parameters":["zoom"]},"transition":1},"fill-extrusion-ambient-occlusion-ground-attenuation":{"type":"number","default":0.69,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["zoom"]},"transition":1},"fill-extrusion-flood-light-color":{"type":"color","default":"#ffffff","expression":{"interpolated":1,"parameters":["measure-light","zoom"]},"transition":1,"use-theme":1},"fill-extrusion-flood-light-intensity":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["measure-light","zoom"]},"transition":1},"fill-extrusion-flood-light-wall-radius":{"type":"number","default":0,"minimum":0,"expression":{"interpolated":1,"parameters":["feature","feature-state"]},"transition":1,"property-type":"data-driven"},"fill-extrusion-flood-light-ground-radius":{"type":"number","default":0,"expression":{"interpolated":1,"parameters":["feature","feature-state"]},"transition":1,"property-type":"data-driven"},"fill-extrusion-flood-light-ground-attenuation":{"type":"number","default":0.69,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["zoom"]},"transition":1},"fill-extrusion-vertical-scale":{"type":"number","default":1,"minimum":0,"expression":{"interpolated":1,"parameters":["zoom"]},"transition":1},"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":1},"fill-extrusion-front-cutoff":{"type":"array","default":[0,0,1],"minimum":[0,0,0],"maximum":[1,1,1],"length":3,"value":"number","expression":{"interpolated":1,"parameters":["zoom"]}},"fill-extrusion-emissive-strength":{"type":"number","default":0,"minimum":0,"expression":{"interpolated":1,"parameters":["feature-state","measure-light","zoom"]},"transition":1,"property-type":"data-driven"},"fill-extrusion-line-width":{"type":"number","default":0,"minimum":0,"expression":{"interpolated":1,"parameters":["feature","feature-state","measure-light","zoom"]},"transition":1,"property-type":"data-driven"},"fill-extrusion-cast-shadows":{"type":"boolean","default":true}},"paint_building":{"building-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["zoom"]},"transition":1},"building-ambient-occlusion-intensity":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{"parameters":[]},"transition":1},"building-ambient-occlusion-ground-intensity":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["zoom"]},"transition":1},"building-ambient-occlusion-ground-radius":{"type":"number","default":3,"minimum":0,"expression":{"interpolated":1,"parameters":["zoom"]},"transition":1},"building-ambient-occlusion-ground-attenuation":{"type":"number","default":0.69,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["zoom"]},"transition":1},"building-vertical-scale":{"type":"number","default":1,"minimum":0,"expression":{"interpolated":1,"parameters":["zoom"]},"transition":1},"building-cast-shadows":{"type":"boolean","default":true},"building-color":{"type":"color","default":"rgba(193, 154, 127, 1)","expression":{"interpolated":1,"parameters":["feature","feature-state","measure-light"]},"use-theme":1,"property-type":"data-driven"},"building-emissive-strength":{"type":"number","default":0,"minimum":0,"maximum":5,"expression":{"interpolated":1,"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":1,"parameters":["measure-light","zoom"]}},"building-cutoff-fade-range":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":1},"building-front-cutoff":{"type":"array","default":[0,0,1],"minimum":[0,0,0],"maximum":[1,1,1],"length":3,"value":"number","expression":{"interpolated":1,"parameters":["zoom"]}},"building-flood-light-color":{"type":"color","default":"#ffffff","expression":{"interpolated":1,"parameters":["measure-light","zoom"]},"transition":1,"use-theme":1},"building-flood-light-intensity":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["measure-light","zoom"]},"transition":1},"building-flood-light-ground-attenuation":{"type":"number","default":0.69,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["zoom"]},"transition":1}},"paint_line":{"line-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["feature","feature-state","measure-light","zoom"]},"transition":1,"property-type":"data-driven"},"line-color":{"type":"color","default":"#000000","expression":{"interpolated":1,"parameters":["feature","feature-state","measure-light","zoom"]},"transition":1,"use-theme":1,"property-type":"data-driven"},"line-translate":{"type":"array","default":[0,0],"length":2,"value":"number","expression":{"interpolated":1,"parameters":["zoom"]},"transition":1},"line-translate-anchor":{"type":"enum","default":"map","values":{"map":1,"viewport":1},"expression":{"parameters":["zoom"]}},"line-width":{"type":"number","default":1,"minimum":0,"expression":{"interpolated":1,"parameters":["feature","feature-state","line-progress","measure-light","zoom"]},"transition":1,"property-type":"data-driven"},"line-gap-width":{"type":"number","default":0,"minimum":0,"expression":{"interpolated":1,"parameters":["feature","feature-state","measure-light","zoom"]},"transition":1,"property-type":"data-driven"},"line-offset":{"type":"number","default":0,"expression":{"interpolated":1,"parameters":["feature","feature-state","measure-light","zoom"]},"transition":1,"property-type":"data-driven"},"line-blur":{"type":"number","default":0,"minimum":0,"expression":{"interpolated":1,"parameters":["feature","feature-state","measure-light","zoom"]},"transition":1,"property-type":"data-driven"},"line-dasharray":{"type":"array","minimum":0,"value":"number","expression":{"parameters":["feature","zoom"]},"property-type":"data-driven"},"line-pattern":{"type":"resolvedImage","expression":{"parameters":["feature","zoom"]},"property-type":"data-driven"},"line-pattern-cross-fade":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["measure-light","zoom"]}},"line-gradient":{"type":"color","expression":{"interpolated":1,"parameters":["line-progress"]},"use-theme":1},"line-trim-offset":{"type":"array","default":[0,0],"minimum":[0,0],"maximum":[1,1],"length":2,"value":"number"},"line-trim-fade-range":{"type":"array","default":[0,0],"minimum":[0,0],"maximum":[1,1],"length":2,"value":"number","expression":{"interpolated":1,"parameters":["measure-light","zoom"]}},"line-trim-color":{"type":"color","default":"transparent","expression":{"interpolated":1,"parameters":["measure-light","zoom"]},"transition":1,"use-theme":1},"line-emissive-strength":{"type":"number","default":0,"minimum":0,"expression":{"interpolated":1,"parameters":["line-progress","measure-light","zoom"]},"transition":1,"property-type":"data-driven"},"line-border-width":{"type":"number","default":0,"minimum":0,"expression":{"interpolated":1,"parameters":["feature","feature-state","zoom"]},"transition":1,"property-type":"data-driven"},"line-border-color":{"type":"color","default":"rgba(0, 0, 0, 0)","expression":{"interpolated":1,"parameters":["feature","feature-state","zoom"]},"transition":1,"use-theme":1,"property-type":"data-driven"},"line-border-gradient":{"type":"color","expression":{"interpolated":1,"parameters":["line-progress"]},"use-theme":1},"line-occlusion-opacity":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["zoom"]},"transition":1},"line-blend-mode":{"type":"enum","default":"default","values":{"default":1,"multiply":1,"additive":1},"expression":{"parameters":["zoom"]}},"line-blend-additive-clamp":{"type":"number","default":0,"minimum":0,"expression":{"interpolated":1,"parameters":["zoom"]}},"line-cutout-depth":{"type":"number","default":0,"minimum":0,"expression":{"interpolated":1,"parameters":["zoom"]},"transition":1}},"paint_circle":{"circle-radius":{"type":"number","default":5,"minimum":0,"expression":{"interpolated":1,"parameters":["feature","feature-state","measure-light","zoom"]},"transition":1,"property-type":"data-driven"},"circle-color":{"type":"color","default":"#000000","expression":{"interpolated":1,"parameters":["feature","feature-state","measure-light","zoom"]},"transition":1,"use-theme":1,"property-type":"data-driven"},"circle-blur":{"type":"number","default":0,"expression":{"interpolated":1,"parameters":["feature","feature-state","measure-light","zoom"]},"transition":1,"property-type":"data-driven"},"circle-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["feature","feature-state","measure-light","zoom"]},"transition":1,"property-type":"data-driven"},"circle-translate":{"type":"array","default":[0,0],"length":2,"value":"number","expression":{"interpolated":1,"parameters":["zoom"]},"transition":1},"circle-translate-anchor":{"type":"enum","default":"map","values":{"map":1,"viewport":1},"expression":{"parameters":["zoom"]}},"circle-pitch-scale":{"type":"enum","default":"map","values":{"map":1,"viewport":1},"expression":{"parameters":["zoom"]}},"circle-pitch-alignment":{"type":"enum","default":"viewport","values":{"map":1,"viewport":1},"expression":{"parameters":["zoom"]}},"circle-stroke-width":{"type":"number","default":0,"minimum":0,"expression":{"interpolated":1,"parameters":["feature","feature-state","measure-light","zoom"]},"transition":1,"property-type":"data-driven"},"circle-stroke-color":{"type":"color","default":"#000000","expression":{"interpolated":1,"parameters":["feature","feature-state","measure-light","zoom"]},"transition":1,"use-theme":1,"property-type":"data-driven"},"circle-stroke-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["feature","feature-state","measure-light","zoom"]},"transition":1,"property-type":"data-driven"},"circle-emissive-strength":{"type":"number","default":0,"minimum":0,"expression":{"interpolated":1,"parameters":["measure-light","zoom"]},"transition":1}},"paint_heatmap":{"heatmap-radius":{"type":"number","default":30,"minimum":1,"expression":{"interpolated":1,"parameters":["feature","feature-state","measure-light","zoom"]},"transition":1,"property-type":"data-driven"},"heatmap-weight":{"type":"number","default":1,"minimum":0,"expression":{"interpolated":1,"parameters":["feature","feature-state","measure-light","zoom"]},"property-type":"data-driven"},"heatmap-intensity":{"type":"number","default":1,"minimum":0,"expression":{"interpolated":1,"parameters":["zoom"]},"transition":1},"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"],"expression":{"interpolated":1,"parameters":["heatmap-density"]},"use-theme":1},"heatmap-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["zoom"]},"transition":1}},"paint_symbol":{"icon-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["feature","feature-state","measure-light","zoom"]},"transition":1,"property-type":"data-driven","appearance":1},"icon-occlusion-opacity":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["feature","feature-state","measure-light","zoom"]},"transition":1,"property-type":"data-driven","appearance":1},"icon-emissive-strength":{"type":"number","default":1,"minimum":0,"expression":{"interpolated":1,"parameters":["feature-state","measure-light","zoom"]},"transition":1,"property-type":"data-driven","appearance":1},"text-emissive-strength":{"type":"number","default":1,"minimum":0,"expression":{"interpolated":1,"parameters":["feature-state","measure-light","zoom"]},"transition":1,"property-type":"data-driven","appearance":1},"icon-color":{"type":"color","default":"#000000","expression":{"interpolated":1,"parameters":["feature","feature-state","measure-light","zoom"]},"transition":1,"use-theme":1,"property-type":"data-driven","appearance":1},"icon-halo-color":{"type":"color","default":"rgba(0, 0, 0, 0)","expression":{"interpolated":1,"parameters":["feature","feature-state","measure-light","zoom"]},"transition":1,"use-theme":1,"property-type":"data-driven","appearance":1},"icon-halo-width":{"type":"number","default":0,"minimum":0,"expression":{"interpolated":1,"parameters":["feature","feature-state","measure-light","zoom"]},"transition":1,"property-type":"data-driven","appearance":1},"icon-halo-blur":{"type":"number","default":0,"minimum":0,"expression":{"interpolated":1,"parameters":["feature","feature-state","measure-light","zoom"]},"transition":1,"property-type":"data-driven","appearance":1},"icon-translate":{"type":"array","default":[0,0],"length":2,"value":"number","expression":{"interpolated":1,"parameters":["zoom"]},"transition":1,"appearance":1},"icon-translate-anchor":{"type":"enum","default":"map","values":{"map":1,"viewport":1},"expression":{"parameters":["zoom"]}},"icon-image-cross-fade":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["measure-light","zoom"]}},"text-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["feature","feature-state","measure-light","zoom"]},"transition":1,"property-type":"data-driven","appearance":1},"text-occlusion-opacity":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["feature","feature-state","measure-light","zoom"]},"transition":1,"property-type":"data-driven","appearance":1},"text-color":{"type":"color","default":"#000000","expression":{"interpolated":1,"parameters":["feature","feature-state","measure-light","zoom"]},"transition":1,"use-theme":1,"property-type":"data-driven","appearance":1,"overridable":1},"text-halo-color":{"type":"color","default":"rgba(0, 0, 0, 0)","expression":{"interpolated":1,"parameters":["feature","feature-state","measure-light","zoom"]},"transition":1,"use-theme":1,"property-type":"data-driven","appearance":1},"text-halo-width":{"type":"number","default":0,"minimum":0,"expression":{"interpolated":1,"parameters":["feature","feature-state","measure-light","zoom"]},"transition":1,"property-type":"data-driven","appearance":1},"text-halo-blur":{"type":"number","default":0,"minimum":0,"expression":{"interpolated":1,"parameters":["feature","feature-state","measure-light","zoom"]},"transition":1,"property-type":"data-driven","appearance":1},"text-translate":{"type":"array","default":[0,0],"length":2,"value":"number","expression":{"interpolated":1,"parameters":["zoom"]},"transition":1,"appearance":1},"text-translate-anchor":{"type":"enum","default":"map","values":{"map":1,"viewport":1},"expression":{"parameters":["zoom"]}},"icon-color-saturation":{"type":"number","default":0,"minimum":-1,"maximum":1,"expression":1},"icon-color-contrast":{"type":"number","default":0,"minimum":-1,"maximum":1,"expression":1},"icon-color-brightness-min":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":1},"icon-color-brightness-max":{"type":"number","default":1,"minimum":0,"maximum":1,"expression":1},"symbol-z-offset":{"type":"number","default":0,"minimum":0,"expression":{"interpolated":1,"parameters":["feature","zoom"]},"transition":1,"property-type":"data-driven","appearance":1}},"paint_raster":{"raster-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["zoom"]},"transition":1},"raster-color":{"type":"color","expression":{"interpolated":1,"parameters":["raster-value"]},"use-theme":1},"raster-color-mix":{"type":"array","default":[0.2126,0.7152,0.0722,0],"length":4,"value":"number","expression":{"interpolated":1,"parameters":["zoom"]},"transition":1},"raster-color-range":{"type":"array","length":2,"value":"number","expression":{"interpolated":1,"parameters":["zoom"]},"transition":1},"raster-color-scale":{"type":"enum","default":"linear","values":{"linear":1,"log":1},"expression":{"parameters":[]}},"raster-hue-rotate":{"type":"number","default":0,"expression":{"interpolated":1,"parameters":["zoom"]},"transition":1},"raster-brightness-min":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["zoom"]},"transition":1},"raster-brightness-max":{"type":"number","default":1,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["zoom"]},"transition":1},"raster-saturation":{"type":"number","default":0,"minimum":-1,"maximum":1,"expression":{"interpolated":1,"parameters":["zoom"]},"transition":1},"raster-contrast":{"type":"number","default":0,"minimum":-1,"maximum":1,"expression":{"interpolated":1,"parameters":["zoom"]},"transition":1},"raster-resampling":{"type":"enum","default":"linear","values":{"linear":1,"nearest":1},"expression":{"parameters":["zoom"]}},"raster-fade-duration":{"type":"number","default":300,"minimum":0,"expression":{"interpolated":1,"parameters":["zoom"]}},"raster-emissive-strength":{"type":"number","default":0,"minimum":0,"expression":{"interpolated":1,"parameters":["measure-light","zoom"]},"transition":1},"raster-array-band":{"type":"string"},"raster-elevation":{"type":"number","default":0,"minimum":0,"expression":{"interpolated":1,"parameters":["zoom"]},"transition":1},"raster-elevation-reference":{"type":"enum","default":"sea","values":{"sea":1,"ground":1},"expression":1},"raster-allow-draping":{"type":"boolean","default":true}},"paint_raster-particle":{"raster-particle-array-band":{"type":"string"},"raster-particle-count":{"type":"number","default":512,"minimum":1},"raster-particle-color":{"type":"color","expression":{"interpolated":1,"parameters":["raster-particle-speed"]},"use-theme":1},"raster-particle-max-speed":{"type":"number","default":1,"minimum":1},"raster-particle-speed-factor":{"type":"number","default":0.2,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["zoom"]},"transition":1},"raster-particle-fade-opacity-factor":{"type":"number","default":0.98,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["zoom"]},"transition":1},"raster-particle-reset-rate-factor":{"type":"number","default":0.8,"minimum":0,"maximum":1},"raster-particle-elevation":{"type":"number","default":0,"minimum":0,"expression":{"interpolated":1,"parameters":["zoom"]},"transition":1}},"paint_hillshade":{"hillshade-illumination-direction":{"type":"number","default":335,"minimum":0,"maximum":359,"expression":{"interpolated":1,"parameters":["zoom"]}},"hillshade-illumination-anchor":{"type":"enum","default":"viewport","values":{"map":1,"viewport":1},"expression":{"parameters":["zoom"]}},"hillshade-exaggeration":{"type":"number","default":0.5,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["zoom"]},"transition":1},"hillshade-shadow-color":{"type":"color","default":"#000000","expression":{"interpolated":1,"parameters":["measure-light","zoom"]},"transition":1,"use-theme":1},"hillshade-highlight-color":{"type":"color","default":"#FFFFFF","expression":{"interpolated":1,"parameters":["measure-light","zoom"]},"transition":1,"use-theme":1},"hillshade-accent-color":{"type":"color","default":"#000000","expression":{"interpolated":1,"parameters":["measure-light","zoom"]},"transition":1,"use-theme":1},"hillshade-emissive-strength":{"type":"number","default":0,"minimum":0,"expression":{"interpolated":1,"parameters":["measure-light","zoom"]},"transition":1}},"paint_background":{"background-pitch-alignment":{"type":"enum","default":"map","values":{"map":1,"viewport":1},"expression":{"parameters":[]}},"background-color":{"type":"color","default":"#000000","expression":{"interpolated":1,"parameters":["measure-light","zoom"]},"transition":1,"use-theme":1},"background-pattern":{"type":"resolvedImage","expression":{"parameters":["zoom"]}},"background-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["zoom"]},"transition":1},"background-emissive-strength":{"type":"number","default":0,"minimum":0,"expression":{"interpolated":1,"parameters":["measure-light","zoom"]},"transition":1}},"paint_sky":{"sky-type":{"type":"enum","default":"atmosphere","values":{"gradient":1,"atmosphere":1},"expression":{"parameters":["zoom"]}},"sky-atmosphere-sun":{"type":"array","minimum":[0,0],"maximum":[360,180],"length":2,"value":"number","expression":{"parameters":["zoom"]}},"sky-atmosphere-sun-intensity":{"type":"number","default":10,"minimum":0,"maximum":100},"sky-gradient-center":{"type":"array","default":[0,0],"minimum":[0,0],"maximum":[360,180],"length":2,"value":"number","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"],"expression":{"interpolated":1,"parameters":["sky-radial-progress"]},"use-theme":1},"sky-atmosphere-halo-color":{"type":"color","default":"white","use-theme":1},"sky-atmosphere-color":{"type":"color","default":"white","use-theme":1},"sky-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["zoom"]},"transition":1}},"paint_model":{"model-opacity":{"type":"number","default":1,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["feature","feature-state","zoom"]},"transition":1,"property-type":"data-driven"},"model-rotation":{"type":"array","default":[0,0,0],"length":3,"value":"number","expression":{"interpolated":1,"parameters":["feature","feature-state","zoom"]},"transition":1,"property-type":"data-driven"},"model-scale":{"type":"array","default":[1,1,1],"length":3,"value":"number","expression":{"interpolated":1,"parameters":["feature","feature-state","zoom"]},"transition":1,"property-type":"data-driven"},"model-translation":{"type":"array","default":[0,0,0],"length":3,"value":"number","expression":{"interpolated":1,"parameters":["feature","feature-state","zoom"]},"transition":1,"property-type":"data-driven"},"model-color":{"type":"color","default":"#ffffff","expression":{"interpolated":1,"parameters":["feature","feature-state","measure-light","zoom"]},"transition":1,"use-theme":1,"property-type":"data-driven"},"model-color-mix-intensity":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["feature","feature-state","measure-light"]},"transition":1,"property-type":"data-driven"},"model-type":{"type":"enum","default":"common-3d","values":{"common-3d":1,"location-indicator":1}},"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":1,"parameters":["zoom"]},"transition":1},"model-emissive-strength":{"type":"number","default":0,"minimum":0,"maximum":5,"expression":{"interpolated":1,"parameters":["feature","feature-state","measure-light"]},"transition":1,"property-type":"data-driven"},"model-roughness":{"type":"number","default":1,"minimum":0,"maximum":1,"expression":{"interpolated":1,"parameters":["feature","feature-state"]},"transition":1,"property-type":"data-driven"},"model-height-based-emissive-strength-multiplier":{"type":"array","default":[1,1,1,1,0],"length":5,"value":"number","expression":{"interpolated":1,"parameters":["feature","feature-state","measure-light"]},"transition":1,"property-type":"data-driven"},"model-cutoff-fade-range":{"type":"number","default":0,"minimum":0,"maximum":1,"expression":1},"model-front-cutoff":{"type":"array","default":[0,0,1],"minimum":[0,0,0],"maximum":[1,1,1],"length":3,"value":"number","expression":{"interpolated":1,"parameters":["zoom"]}},"model-elevation-reference":{"type":"enum","default":"ground","values":{"sea":1,"ground":1,"hd-road-markup":1},"expression":1},"model-line-cutout-mode":{"type":"enum","default":"enabled","values":{"enabled":1,"disabled":1,"enabled-above-cutout":1},"expression":1}},"promoteId":{"*":{"type":"*"}}}');function XV(w){return w instanceof Number||w instanceof String||w instanceof Boolean?w.valueOf():w}function I6(w){if(Array.isArray(w))return w.map(I6);if(w instanceof Object&&!(w instanceof Number||w instanceof String||w instanceof Boolean)){const f={},b=w;for(const S in b)f[S]=I6(b[S]);return f}return XV(w)}function QV(w){if(w===!0||w===!1)return!0;if(!Array.isArray(w)||w.length===0)return!1;switch(w[0]){case"has":return w.length>=2&&w[1]!=="$id"&&w[1]!=="$type";case"in":return w.length>=3&&(typeof w[1]!="string"||Array.isArray(w[2]));case"!in":case"!has":case"none":return!1;case"==":case"!=":case">":case">=":case"<":case"<=":return w.length!==3||Array.isArray(w[1])||Array.isArray(w[2]);case"any":case"all":for(const f of w.slice(1))if(!QV(f)&&typeof f!="boolean")return!1;return!0;default:return!0}}function L6(w,f="",b=null,S="fill"){if(w==null)return{filter:()=>!0,needGeometry:!1,needFeature:!1};QV(w)||(w=n7(w));const T=w;let D=!0;try{D=function(ce){if(!yA(ce))return ce;let pe=I6(ce);return JV(pe),pe=R6(pe),pe}(T)}catch{console.warn(`Failed to extract static filter. Filter will continue working, but at higher memory usage and slower framerate. This is most likely a bug, please report this via https://github.com/mapbox/mapbox-gl-js/issues/new?assignees=&labels=&template=Bug_report.md and paste the contents of this message in the report. Thank you! Filter Expression: ${JSON.stringify(T,null,2)} `)}let F=null,q=null;if(S!=="background"&&S!=="sky"&&S!=="slot"){q=Us[`filter_${S}`];const ce=R1(D,q,f,b);if(ce.result==="error")throw new Error(ce.value.map(pe=>`${pe.key}: ${pe.message}`).join(", "));F=(pe,xe,Ne)=>ce.value.evaluate(pe,xe,{},Ne)}let K=null,X=null;if(D!==T){const ce=R1(T,q,f,b);if(ce.result==="error")throw new Error(ce.value.map(pe=>`${pe.key}: ${pe.message}`).join(", "));K=(pe,xe,Ne,Me,ze)=>ce.value.evaluate(pe,xe,{},Ne,void 0,void 0,Me,ze),X=!qh(ce.value.expression)}return{filter:F,dynamicFilter:K||void 0,needGeometry:s7(D),needFeature:!!X}}function R6(w){if(!Array.isArray(w))return w;const f=function(b){if(Ate.has(b[0])){for(let S=1;SR6(b))}function JV(w){let f=!1;const b=[];if(w[0]==="case"){for(let S=1;S",">=","<","<=","to-boolean"]);function lMe(w,f){return wf?1:0}function s7(w){if(!Array.isArray(w))return!1;if(w[0]==="within"||w[0]==="distance")return!0;for(let f=1;f"||f==="<="||f===">="?eH(w[1],w[2],f):f==="any"?(b=w.slice(1),["any"].concat(b.map(n7))):f==="all"?["all"].concat(w.slice(1).map(n7)):f==="none"?["all"].concat(w.slice(1).map(n7).map(D6)):f==="in"?Ete(w[1],w.slice(2)):f==="!in"?D6(Ete(w[1],w.slice(2))):f==="has"?Tte(w[1]):f!=="!has"||D6(Tte(w[1]));var b}function eH(w,f,b){switch(w){case"$type":return[`filter-type-${b}`,f];case"$id":return[`filter-id-${b}`,f];default:return[`filter-${b}`,w,f]}}function Ete(w,f){if(f.length===0)return!1;switch(w){case"$type":return["filter-type-in",["literal",f]];case"$id":return["filter-id-in",["literal",f]];default:return f.length>200&&!f.some(b=>typeof b!=typeof f[0])?["filter-in-large",w,["literal",f.sort(lMe)]]:["filter-in-small",w,["literal",f]]}}function Tte(w){switch(w){case"$type":return!0;case"$id":return["filter-has-id"];default:return["filter-has",w]}}function D6(w){return["!",w]}const O6="";function r7(w,f){return f?`${w}${O6}${f}`:w}function Mte(w){const f=w.indexOf(O6);return f>=0?w.slice(f+1):""}let Pte;const Ite=()=>Pte||(Pte=new $d({"icon-size":new hr(Us.layout_symbol["icon-size"]),"icon-image":new hr(Us.layout_symbol["icon-image"]),"icon-rotate":new hr(Us.layout_symbol["icon-rotate"]),"icon-offset":new hr(Us.layout_symbol["icon-offset"]),"text-size":new hr(Us.layout_symbol["text-size"]),"text-rotate":new hr(Us.layout_symbol["text-rotate"]),"text-offset":new hr(Us.layout_symbol["text-offset"])}));let Lte;const Rte=()=>Lte||(Lte=new $d({"icon-opacity":new hr(Us.paint_symbol["icon-opacity"]),"icon-occlusion-opacity":new hr(Us.paint_symbol["icon-occlusion-opacity"]),"icon-emissive-strength":new hr(Us.paint_symbol["icon-emissive-strength"]),"text-emissive-strength":new hr(Us.paint_symbol["text-emissive-strength"]),"icon-color":new hr(Us.paint_symbol["icon-color"]),"icon-halo-color":new hr(Us.paint_symbol["icon-halo-color"]),"icon-halo-width":new hr(Us.paint_symbol["icon-halo-width"]),"icon-halo-blur":new hr(Us.paint_symbol["icon-halo-blur"]),"icon-translate":new hr(Us.paint_symbol["icon-translate"]),"text-opacity":new hr(Us.paint_symbol["text-opacity"]),"text-occlusion-opacity":new hr(Us.paint_symbol["text-occlusion-opacity"]),"text-color":new hr(Us.paint_symbol["text-color"],{runtimeType:kh,getOverride:w=>w.textColor,hasOverride:w=>!!w.textColor}),"text-halo-color":new hr(Us.paint_symbol["text-halo-color"]),"text-halo-width":new hr(Us.paint_symbol["text-halo-width"]),"text-halo-blur":new hr(Us.paint_symbol["text-halo-blur"]),"text-translate":new hr(Us.paint_symbol["text-translate"]),"symbol-z-offset":new hr(Us.paint_symbol["symbol-z-offset"]),"icon-color-use-theme":new hr({type:"string",default:"default","property-type":"data-driven"}),"icon-halo-color-use-theme":new hr({type:"string",default:"default","property-type":"data-driven"}),"text-color-use-theme":new hr({type:"string",default:"default","property-type":"data-driven"}),"text-halo-color-use-theme":new hr({type:"string",default:"default","property-type":"data-driven"})}));class cMe{constructor(f,b,S,T,D,F){this._conditionSpec=f,this._propertiesSpec=S;const q=R1(f,Us.appearance.condition);if(q.result==="success"&&(this.condition=q.value),this.name=b,S){this.layoutProperties=new Ch(Ite()),this.unevaluatedLayout=new Al(Ite(),T,D,F),this.paintProperties=new Ch(Rte()),this.unevaluatedPaint=new Al(Rte(),T,D,"");for(const K in S)K in this.unevaluatedLayout._values?this.unevaluatedLayout.setValue(K,S[K]):K in this.unevaluatedPaint._values&&this.unevaluatedPaint.setValue(K,S[K])}}isActive(f){return!(this.condition||!f.isHidden||this.name!=="hidden")||this.condition.evaluate(f.globals,f.feature,f.featureState,f.canonical)}getCondition(){return this.condition}getName(){return this.name}getLayoutProperty(f){return this.layoutProperties.get(f)}getPaintProperty(f){return this.paintProperties.get(f)}getUnevaluatedLayoutProperties(){return this.unevaluatedLayout}getUnevaluatedLayoutProperty(f){return this.unevaluatedLayout._values[f]}getUnevaluatedPaintProperty(f){return this.unevaluatedPaint._values[f]}recalculate(f,b,S){this.unevaluatedLayout&&(this.layoutProperties=this.unevaluatedLayout.possiblyEvaluate(f,void 0,b,S)),this.unevaluatedPaint&&(this.paintProperties=this.unevaluatedPaint.possiblyEvaluate(f,void 0,b,""))}serialize(){const f={};f.condition=this.condition.expression.serialize(),this.name&&(f.name=this.name);const b={...this.unevaluatedLayout?this.unevaluatedLayout.serialize():{},...this.unevaluatedPaint?this.unevaluatedPaint.serialize():{}};return Object.keys(b).length>0&&(f.properties=b),f}hasIconLayoutProperties(){const f=this.hasLayoutProperty("icon-image"),b=this.hasLayoutProperty("icon-size"),S=this.hasLayoutProperty("icon-offset"),T=this.hasLayoutProperty("icon-rotate");return f||b||S||T}hasTextLayoutProperties(){const f=this.hasLayoutProperty("text-size"),b=this.hasLayoutProperty("text-offset"),S=this.hasLayoutProperty("text-rotate");return f||b||S}hasIconPaintProperties(){return!!this.unevaluatedPaint&&Object.keys(this.unevaluatedPaint._values).filter(f=>!f.endsWith("-use-theme")).some(f=>(f.startsWith("icon-")||f==="symbol-z-offset")&&this.hasPaintProperty(f))}hasTextPaintProperties(){return!!this.unevaluatedPaint&&Object.keys(this.unevaluatedPaint._values).filter(f=>!f.endsWith("-use-theme")).some(f=>(f.startsWith("text-")||f==="symbol-z-offset")&&this.hasPaintProperty(f))}hasLayoutProperty(f){return this.unevaluatedLayout&&this.unevaluatedLayout._values[f].value!==void 0}hasPaintProperty(f){return this.unevaluatedPaint&&this.unevaluatedPaint._values[f].value!==void 0}}const Dte="-transition",a7=new Set(["fill","line","background","hillshade","raster"]);class zy extends Fd{constructor(f,b,S,T,D,F){if(super(),this.id=f.id,this.fqid=r7(this.id,S),this.type=f.type,this.scope=S,this.lut=T,this.options=D,this.iconImageUseTheme=F,this.appearances=new Array,this.appearancesVersion=0,this._featureFilter={filter:()=>!0,needGeometry:!1,needFeature:!1},this._filterCompiled=!1,f.type!=="custom"&&(this.metadata=f.metadata,this.minzoom=f.minzoom,this.maxzoom=f.maxzoom,f.type&&f.type!=="background"&&f.type!=="sky"&&f.type!=="slot"&&(this.source=f.source,this.sourceLayer=f["source-layer"],this.filter=f.filter),f.slot&&(this.slot=f.slot),f.appearances&&this.setAppearances(f.appearances),b.layout&&(this._unevaluatedLayout=new Al(b.layout,this.scope,D,this.iconImageUseTheme)),b.paint)){this._transitionablePaint=new Vi(b.paint,this.scope,D);for(const q in f.paint)this.setPaintProperty(q,f.paint[q]);for(const q in f.layout)this.setLayoutProperty(q,f.layout[q]);this._transitioningPaint=this._transitionablePaint.untransitioned(),this.paint=new Ch(b.paint)}}onAdd(f){}onRemove(f){}isDraped(f){return!this.is3D(!0)&&a7.has(this.type)}getLayoutProperty(f){return f==="visibility"?this.visibility:this._unevaluatedLayout.getValue(f)}setLayoutProperty(f,b){if(this.type==="custom"&&f==="visibility")return void(this.visibility=b);const S=this._unevaluatedLayout;S._properties.properties[f]&&(S.setValue(f,b),f==="visibility"&&this.possiblyEvaluateVisibility())}setAppearances(f){this.appearances=[],f.forEach(b=>{this.appearances.push(new cMe(b.condition,b.name,b.properties,this.scope,this.options,this.iconImageUseTheme))}),this.appearancesVersion++}possiblyEvaluateVisibility(){this._unevaluatedLayout._values.visibility&&(this.visibility=this._unevaluatedLayout._values.visibility.possiblyEvaluate({zoom:0}))}getPaintProperty(f){return f.endsWith(Dte)?this._transitionablePaint.getTransition(f.slice(0,-11)):this._transitionablePaint.getValue(f)}isPaintProperty(f){return!!this._transitionablePaint._properties.properties[f]}setPaintProperty(f,b){const S=this._transitionablePaint,T=S._properties.properties;if(f.endsWith(Dte)){const pe=f.slice(0,-11);return T[pe]&&S.setTransition(pe,b||void 0),!1}if(!T[f])return!1;const D=S._values[f],F=D.value.isDataDriven(),q=D.value;S.setValue(f,b),this._handleSpecialPaintPropertyUpdate(f);const K=S._values[f].value,X=K.isDataDriven(),ce=f.endsWith("pattern")||f==="line-dasharray";return X||F||ce||this._handleOverridablePaintPropertyUpdate(f,q,K)}_handleSpecialPaintPropertyUpdate(f){}getProgramIds(){return null}getDefaultProgramParams(f,b,S){return null}_handleOverridablePaintPropertyUpdate(f,b,S){return!1}isHidden(f){return!!(this.minzoom&&f=this.maxzoom)||this.visibility==="none"}updateTransitions(f){this._transitioningPaint=this._transitionablePaint.transitioned(f,this._transitioningPaint)}hasTransition(){return this._transitioningPaint.hasTransition()}recalculate(f,b){this._unevaluatedLayout&&(this.layout=this._unevaluatedLayout.possiblyEvaluate(f,void 0,b,this.iconImageUseTheme)),this.paint=this._transitioningPaint.possiblyEvaluate(f,void 0,b)}serialize(){const f={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&&(f.appearances=this.appearances.map(b=>b.serialize())),Il(f,(b,S)=>!(b===void 0||S==="layout"&&!Object.keys(b).length||S==="paint"&&!Object.keys(b).length))}is3D(f){return!1}hasElevation(){return!1}mayUse(f){return!1}prepare(){return Promise.resolve()}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 f in this.paint._values){const b=this.paint.get(f);if(b instanceof wc&&Ob(b.property.specification)&&(b.value.kind==="source"||b.value.kind==="composite")&&b.value.isStateDependent)return!0}for(const f of this.appearances)if(!A1(f.condition.expression))return!0;return!1}compileFilter(f){this._filterCompiled||(this._featureFilter=L6(this.filter,this.scope,f),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(f){this._stats&&(f.renderPass==="shadow"?this._stats.numRenderedVerticesInShadowPass=0:this._stats.numRenderedVerticesInTransparentPass=0)}getAppearances(){return this.appearances}queryRenderedFeatures(f,b,S){return{}}queryRadius(f){}queryIntersectsFeature(f,b,S,T,D,F,q,K,X,ce){}}function i7(w,f,b){if(!w._unevaluatedLayout)return!1;const S=w._unevaluatedLayout.getValue(f);return S!==void 0&&(typeof S!="string"||b(S))}function rN(w,f,b=2){const S=f&&f.length,T=S?f[0]*b:w.length;let D=Ote(w,0,T,b,!0);const F=[];if(!D||D.next===D.prev)return F;let q,K,X;if(S&&(D=function(ce,pe,xe,Ne){const Me=[];for(let ze=0,Ve=pe.length;ze80*b){q=w[0],K=w[1];let ce=q,pe=K;for(let xe=b;xece&&(ce=Ne),Me>pe&&(pe=Me)}X=Math.max(ce-q,pe-K),X=X!==0?32767/X:0}return F6(D,F,b,q,K,X,0),F}function Ote(w,f,b,S,T){let D;if(T===function(F,q,K,X){let ce=0;for(let pe=q,xe=K-X;pe0)for(let F=f;F=f;F-=S)D=B6(F/S|0,w[F],w[F+1],D);return D&&A4(D,D.next)&&($6(D),D=D.next),D}function Gk(w,f){if(!w)return w;f||(f=w);let b,S=w;do if(b=!1,S.steiner||!A4(S,S.next)&&rf(S.prev,S,S.next)!==0)S=S.next;else{if($6(S),S=f=S.prev,S===S.next)break;b=!0}while(b||S!==f);return f}function F6(w,f,b,S,T,D,F){if(!w)return;!F&&D&&function(K,X,ce,pe){let xe=K;do xe.z===0&&(xe.z=tH(xe.x,xe.y,X,ce,pe)),xe.prevZ=xe.prev,xe.nextZ=xe.next,xe=xe.next;while(xe!==K);xe.prevZ.nextZ=null,xe.prevZ=null,function(Ne){let Me,ze=1;do{let Ve,Je=Ne;Ne=null;let lt=null;for(Me=0;Je;){Me++;let ht=Je,ct=0;for(let kt=0;kt0||xt>0&&ht;)ct!==0&&(xt===0||!ht||Je.z<=ht.z)?(Ve=Je,Je=Je.nextZ,ct--):(Ve=ht,ht=ht.nextZ,xt--),lt?lt.nextZ=Ve:Ne=Ve,Ve.prevZ=lt,lt=Ve;Je=ht}lt.nextZ=null,ze*=2}while(Me>1)}(xe)}(w,S,T,D);let q=w;for(;w.prev!==w.next;){const K=w.prev,X=w.next;if(D?Fte(w,S,T,D):dMe(w))f.push(K.i,w.i,X.i),$6(w),w=X.next,q=X.next;else if((w=X)===q){F?F===1?F6(w=zte(Gk(w),f),f,b,S,T,D,2):F===2&&Bte(w,f,b,S,T,D):F6(Gk(w),f,b,S,T,D,1);break}}}function dMe(w){const f=w.prev,b=w,S=w.next;if(rf(f,b,S)>=0)return!1;const T=f.x,D=b.x,F=S.x,q=f.y,K=b.y,X=S.y,ce=Math.min(T,D,F),pe=Math.min(q,K,X),xe=Math.max(T,D,F),Ne=Math.max(q,K,X);let Me=S.next;for(;Me!==f;){if(Me.x>=ce&&Me.x<=xe&&Me.y>=pe&&Me.y<=Ne&&z6(T,q,D,K,F,X,Me.x,Me.y)&&rf(Me.prev,Me,Me.next)>=0)return!1;Me=Me.next}return!0}function Fte(w,f,b,S){const T=w.prev,D=w,F=w.next;if(rf(T,D,F)>=0)return!1;const q=T.x,K=D.x,X=F.x,ce=T.y,pe=D.y,xe=F.y,Ne=Math.min(q,K,X),Me=Math.min(ce,pe,xe),ze=Math.max(q,K,X),Ve=Math.max(ce,pe,xe),Je=tH(Ne,Me,f,b,S),lt=tH(ze,Ve,f,b,S);let ht=w.prevZ,ct=w.nextZ;for(;ht&&ht.z>=Je&&ct&&ct.z<=lt;){if(ht.x>=Ne&&ht.x<=ze&&ht.y>=Me&&ht.y<=Ve&&ht!==T&&ht!==F&&z6(q,ce,K,pe,X,xe,ht.x,ht.y)&&rf(ht.prev,ht,ht.next)>=0||(ht=ht.prevZ,ct.x>=Ne&&ct.x<=ze&&ct.y>=Me&&ct.y<=Ve&&ct!==T&&ct!==F&&z6(q,ce,K,pe,X,xe,ct.x,ct.y)&&rf(ct.prev,ct,ct.next)>=0))return!1;ct=ct.nextZ}for(;ht&&ht.z>=Je;){if(ht.x>=Ne&&ht.x<=ze&&ht.y>=Me&&ht.y<=Ve&&ht!==T&&ht!==F&&z6(q,ce,K,pe,X,xe,ht.x,ht.y)&&rf(ht.prev,ht,ht.next)>=0)return!1;ht=ht.prevZ}for(;ct&&ct.z<=lt;){if(ct.x>=Ne&&ct.x<=ze&&ct.y>=Me&&ct.y<=Ve&&ct!==T&&ct!==F&&z6(q,ce,K,pe,X,xe,ct.x,ct.y)&&rf(ct.prev,ct,ct.next)>=0)return!1;ct=ct.nextZ}return!0}function zte(w,f){let b=w;do{const S=b.prev,T=b.next.next;!A4(S,T)&&o7(S,b,b.next,T)&&E4(S,T)&&E4(T,S)&&(f.push(S.i,b.i,T.i),$6(b),$6(b.next),b=w=T),b=b.next}while(b!==w);return Gk(b)}function Bte(w,f,b,S,T,D){let F=w;do{let q=F.next.next;for(;q!==F.prev;){if(F.i!==q.i&&fMe(F,q)){let K=qte(F,q);return F=Gk(F,F.next),K=Gk(K,K.next),F6(F,f,b,S,T,D,0),void F6(K,f,b,S,T,D,0)}q=q.next}F=F.next}while(F!==w)}function uMe(w,f){let b=w.x-f.x;return b===0&&(b=w.y-f.y,b===0)&&(b=(w.next.y-w.y)/(w.next.x-w.x)-(f.next.y-f.y)/(f.next.x-f.x)),b}function hMe(w,f){const b=function(T,D){let F=D;const q=T.x,K=T.y;let X,ce=-1/0;if(A4(T,F))return F;do{if(A4(T,F.next))return F.next;if(K<=F.y&&K>=F.next.y&&F.next.y!==F.y){const ze=F.x+(K-F.y)*(F.next.x-F.x)/(F.next.y-F.y);if(ze<=q&&ze>ce&&(ce=ze,X=F.x=F.x&&F.x>=xe&&q!==F.x&&Ute(KX.x||F.x===X.x&&$te(X,F)))&&(X=F,Me=ze)}F=F.next}while(F!==pe);return X}(w,f);if(!b)return f;const S=qte(b,w);return Gk(S,S.next),Gk(b,b.next)}function $te(w,f){return rf(w.prev,w,f.prev)<0&&rf(f.next,w,w.next)<0}function tH(w,f,b,S,T){return(w=1431655765&((w=858993459&((w=252645135&((w=16711935&((w=(w-b)*T|0)|w<<8))|w<<4))|w<<2))|w<<1))|(f=1431655765&((f=858993459&((f=252645135&((f=16711935&((f=(f-S)*T|0)|f<<8))|f<<4))|f<<2))|f<<1))<<1}function mMe(w){let f=w,b=w;do(f.x=(w-F)*(D-q)&&(w-F)*(S-q)>=(b-F)*(f-q)&&(b-F)*(D-q)>=(T-F)*(S-q)}function z6(w,f,b,S,T,D,F,q){return!(w===F&&f===q)&&Ute(w,f,b,S,T,D,F,q)}function fMe(w,f){return w.next.i!==f.i&&w.prev.i!==f.i&&!function(b,S){let T=b;do{if(T.i!==b.i&&T.next.i!==b.i&&T.i!==S.i&&T.next.i!==S.i&&o7(T,T.next,b,S))return!0;T=T.next}while(T!==b);return!1}(w,f)&&(E4(w,f)&&E4(f,w)&&function(b,S){let T=b,D=!1;const F=(b.x+S.x)/2,q=(b.y+S.y)/2;do T.y>q!=T.next.y>q&&T.next.y!==T.y&&F<(T.next.x-T.x)*(q-T.y)/(T.next.y-T.y)+T.x&&(D=!D),T=T.next;while(T!==b);return D}(w,f)&&(rf(w.prev,w,f.prev)||rf(w,f.prev,f))||A4(w,f)&&rf(w.prev,w,w.next)>0&&rf(f.prev,f,f.next)>0)}function rf(w,f,b){return(f.y-w.y)*(b.x-f.x)-(f.x-w.x)*(b.y-f.y)}function A4(w,f){return w.x===f.x&&w.y===f.y}function o7(w,f,b,S){const T=O1(rf(w,f,b)),D=O1(rf(w,f,S)),F=O1(rf(b,S,w)),q=O1(rf(b,S,f));return T!==D&&F!==q||!(T!==0||!l7(w,b,f))||!(D!==0||!l7(w,S,f))||!(F!==0||!l7(b,w,S))||!(q!==0||!l7(b,f,S))}function l7(w,f,b){return f.x<=Math.max(w.x,b.x)&&f.x>=Math.min(w.x,b.x)&&f.y<=Math.max(w.y,b.y)&&f.y>=Math.min(w.y,b.y)}function O1(w){return w>0?1:w<0?-1:0}function E4(w,f){return rf(w.prev,w,w.next)<0?rf(w,f,w.next)>=0&&rf(w,w.prev,f)>=0:rf(w,f,w.prev)<0||rf(w,w.next,f)<0}function qte(w,f){const b=Wk(w.i,w.x,w.y),S=Wk(f.i,f.x,f.y),T=w.next,D=f.prev;return w.next=f,f.prev=w,b.next=T,T.prev=b,S.next=b,b.prev=S,D.next=S,S.prev=D,S}function B6(w,f,b,S){const T=Wk(w,f,b);return S?(T.next=S.next,T.prev=S,S.next.prev=T,S.next=T):(T.prev=T,T.next=T),T}function $6(w){w.next.prev=w.prev,w.prev.next=w.next,w.prevZ&&(w.prevZ.nextZ=w.nextZ),w.nextZ&&(w.nextZ.prevZ=w.prevZ)}function Wk(w,f,b){return{i:w,x:f,y:b,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}function Vte(w,f,b=1){if(!w)return null;const S=typeof w=="string"?rm.from(w).getPrimary():w.getPrimary(),T=typeof w=="string"?null:w.getSecondary();for(const D of[S,T]){if(!D)continue;const F=D.id.toString();f.has(F)||f.set(F,[]),D.scaleSelf(b),f.get(F).push(D)}return{primary:S.toString(),secondary:T?T.toString():null}}function sH(w,f,b,S){const T=S.patternDependencies;let D=!1;for(const F of f){const q=F.paint.get(`${w}-pattern`);q.isConstant()||(D=!0),Vte(q.constantOr(null),T,b)&&(D=!0)}return D}function nH(w,f,b,S,T,D){const F=D.patternDependencies;for(const q of f){const K=q.paint.get(`${w}-pattern`).value;if(K.kind!=="constant"){const X=Vte(K.evaluate({zoom:S},b,{},void 0,D.availableImages),F,T);if(!X)continue;const{primary:ce,secondary:pe}=X;ce&&(b.patterns[q.id]=[ce,pe].filter(Boolean))}}return b}const By=br/Math.PI/2,T4=64,c7=[T4,32,16],Mv=-By,J_=By;function L(w,f,b,S=By){return b=_a(b),[w*Math.sin(b)*S,-f*S,w*Math.cos(b)*S]}function N(w,f,b){return L(Math.cos(_a(w)),Math.sin(_a(w)),f,b)}const E=63710088e-1,z=2*Math.PI*E;class W{constructor(f,b){if(isNaN(f)||isNaN(b))throw new Error(`Invalid LngLat object: (${f}, ${b})`);if(this.lng=+f,this.lat=+b,this.lat>90||this.lat<-90)throw new Error("Invalid LngLat latitude value: must be between -90 and 90")}wrap(){return new W(fc(this.lng,-180,180),this.lat)}toArray(){return[this.lng,this.lat]}toString(){return`LngLat(${this.lng}, ${this.lat})`}distanceTo(f){const b=Math.PI/180,S=this.lat*b,T=f.lat*b,D=Math.sin(S)*Math.sin(T)+Math.cos(S)*Math.cos(T)*Math.cos((f.lng-this.lng)*b);return E*Math.acos(Math.min(D,1))}toBounds(f=0){const b=360*f/40075017,S=b/Math.cos(Math.PI/180*this.lat);return new Z({lng:this.lng-S,lat:this.lat-b},{lng:this.lng+S,lat:this.lat+b})}toEcef(f){return N(this.lat,this.lng,By+f*By/E)}static convert(f){if(f instanceof W)return f;if(Array.isArray(f)&&(f.length===2||f.length===3))return new W(Number(f[0]),Number(f[1]));if(!Array.isArray(f)&&typeof f=="object"&&f!==null)return new W(Number("lng"in f?f.lng:f.lon),Number(f.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 Z{constructor(f,b){f&&(b?this.setSouthWest(f).setNorthEast(b):Array.isArray(f)&&f.length===4?this.setSouthWest([f[0],f[1]]).setNorthEast([f[2],f[3]]):this.setSouthWest(f[0]).setNorthEast(f[1]))}setNorthEast(f){return this._ne=f instanceof W?new W(f.lng,f.lat):W.convert(f),this}setSouthWest(f){return this._sw=f instanceof W?new W(f.lng,f.lat):W.convert(f),this}extend(f){const b=this._sw,S=this._ne;let T,D;if(f instanceof W)T=f,D=f;else{if(!(f instanceof Z))return Array.isArray(f)?f.length===4||f.every(Array.isArray)?this.extend(Z.convert(f)):this.extend(W.convert(f)):typeof f=="object"&&f!==null&&Object.hasOwn(f,"lat")&&(Object.hasOwn(f,"lon")||Object.hasOwn(f,"lng"))?this.extend(W.convert(f)):this;if(T=f._sw,D=f._ne,!T||!D)return this}return b||S?(b.lng=Math.min(T.lng,b.lng),b.lat=Math.min(T.lat,b.lat),S.lng=Math.max(D.lng,S.lng),S.lat=Math.max(D.lat,S.lat)):(this._sw=new W(T.lng,T.lat),this._ne=new W(D.lng,D.lat)),this}getCenter(){return new W((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 W(this.getWest(),this.getNorth())}getSouthEast(){return new W(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(f){const{lng:b,lat:S}=W.convert(f);let T=this._sw.lng<=b&&b<=this._ne.lng;return this._sw.lng>this._ne.lng&&(T=this._sw.lng>=b&&b>=this._ne.lng),this._sw.lat<=S&&S<=this._ne.lat&&T}static convert(f){if(f)return f instanceof Z?f:new Z(f)}}function ne(w){return z*Math.cos(w*Math.PI/180)}function de(w,f){return w/ne(f)}function ye(w,f){return w*ne(hh(f))}const Ce=85.051129;function Pe(w){return Math.cos(_a(Jr(w,-85.051129,Ce)))}function Ke(w,f){const b=Jr(f,0,25.5),S=Math.pow(2,b);return Pe(w)*z/(512*S)}function Ze(w){return 1/Math.cos(w*Math.PI/180)}function mt(w,f=0){const b=Math.exp(Math.PI*(1-(w.y+f/br)/(1<=K?(bt(w,f,b,X,ce,D,pe,q,K),bt(w,X,ce,S,T,pe,F,q,K)):w.push(F)}function St(w,f,b){let S=w[0],T=S.x,D=S.y;f(S);const F=[S];for(let q=1;qw.x+1||Sw.y+1)&&oi("Geometry exceeds allowed extent, reduce your vector tile buffer size"),w}function Ms(w,f,b){const S=w.loadGeometry(),T=w.extent,D=br/T;if(f&&b&&b.projection.isReprojectedInTileSpace){const F=1<{const Ne=Jm((f.x+xe.x/T)/F),Me=hh((f.y+xe.y/T)/F),ze=ce.project(Ne,Me);xe.x=(ze.x*q-K)*T,xe.y=(ze.y*q-X)*T};for(let xe=0;xe=T||Me.y<0||Me.y>=T||(pe(Me),Ne.push(Me));S[xe]=Ne}}for(const F of S)for(const q of F)Gs(q,D);return S}function Js(w,f){return{type:w.type,id:w.id,properties:w.properties,geometry:f?Ms(w):[]}}const Os={Int8:Int8Array,Uint8:Uint8Array,Int16:Int16Array,Uint16:Uint16Array,Int32:Int32Array,Uint32:Uint32Array,Float32:Float32Array};class Ks{constructor(f,b){this._structArray=f,this._pos1=b*this.size,this._pos2=this._pos1/2,this._pos4=this._pos1/4,this._pos8=this._pos1/8}}const _n=new ArrayBuffer(0);class ln{constructor(){this._reallocCount=0,this.capacity=0,this.length=0}static serialize(f,b){return f._trim(),b&&f.arrayBuffer&&b.add(f.arrayBuffer),{length:f.length,arrayBuffer:f.arrayBuffer}}static deserialize(f){const b=Object.create(this.prototype);return b.arrayBuffer=f.arrayBuffer,b.length=f.length,f.arrayBuffer?b.capacity=f.arrayBuffer.byteLength/b.bytesPerElement:(b.capacity=0,b.arrayBuffer=_n),b._refreshViews(),b}_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(f){this.reserve(f),this.length=f}resizeExact(f){this.reserveExact(f),this.length=f}reserve(f){f>this.capacity&&this._allocate(Math.max(f,Math.floor(5*this.capacity),128))}reserveExact(f){(f>this.capacity||!this.arrayBuffer)&&this._allocate(f)}_allocate(f){this._reallocCount++,this.capacity=f,this.arrayBuffer=new ArrayBuffer(this.capacity*this.bytesPerElement);const b=this.uint8;this._refreshViews(),b&&this.uint8.set(b)}reserveForAdditional(f){this.reserve(this.length+f)}_refreshViews(){throw new Error("StructArray#_refreshViews() must be implemented by each concrete StructArray layout")}emplace(...f){throw new Error("StructArray#emplace() must be implemented by each concrete StructArray layout")}emplaceBack(...f){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 an(w,f=1){let b=0,S=0;return{members:w.map(T=>{const D=Os[T.type].BYTES_PER_ELEMENT,F=b=bn(b,Math.max(f,D)),q=T.components||1;return S=Math.max(S,D),b+=D*q,{name:T.name,type:T.type,components:q,offset:F}}),size:bn(b,Math.max(S,f)),alignment:f}}function bn(w,f){return Math.ceil(w/f)*f}class Sn extends ln{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(f,b){const S=this.length;return this.resize(S+1),this.emplace(S,f,b)}emplace(f,b,S){const T=2*f;return this.int16[T+0]=b,this.int16[T+1]=S,f}}Sn.prototype.bytesPerElement=4,Vr(Sn,"StructArrayLayout2i4");class lr extends ln{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(f,b,S){const T=this.length;return this.resize(T+1),this.emplace(T,f,b,S)}emplace(f,b,S,T){const D=3*f;return this.int16[D+0]=b,this.int16[D+1]=S,this.int16[D+2]=T,f}}lr.prototype.bytesPerElement=6,Vr(lr,"StructArrayLayout3i6");class Mn extends ln{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(f,b,S,T){const D=this.length;return this.resize(D+1),this.emplace(D,f,b,S,T)}emplace(f,b,S,T,D){const F=4*f;return this.int16[F+0]=b,this.int16[F+1]=S,this.uint16[F+2]=T,this.uint16[F+3]=D,f}}Mn.prototype.bytesPerElement=8,Vr(Mn,"StructArrayLayout2i2ui8");class Hn extends ln{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(f){const b=this.length;return this.resize(b+1),this.emplace(b,f)}emplace(f,b){return this.float32[1*f+0]=b,f}}Hn.prototype.bytesPerElement=4,Vr(Hn,"StructArrayLayout1f4");class Tr extends ln{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(f,b,S){const T=this.length;return this.resize(T+1),this.emplace(T,f,b,S)}emplace(f,b,S,T){const D=4*f,F=2*f;return this.int16[D+0]=b,this.int16[D+1]=S,this.float32[F+1]=T,f}}Tr.prototype.bytesPerElement=8,Vr(Tr,"StructArrayLayout2i1f8");class oa extends ln{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(f,b,S){const T=this.length;return this.resize(T+1),this.emplace(T,f,b,S)}emplace(f,b,S,T){const D=4*f;return this.int16[D+0]=b,this.int16[D+1]=S,this.int16[D+2]=T,f}}oa.prototype.bytesPerElement=8,Vr(oa,"StructArrayLayout3i8");class Qr extends ln{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(f,b,S,T){const D=this.length;return this.resize(D+1),this.emplace(D,f,b,S,T)}emplace(f,b,S,T,D){const F=4*f;return this.int16[F+0]=b,this.int16[F+1]=S,this.int16[F+2]=T,this.int16[F+3]=D,f}}Qr.prototype.bytesPerElement=8,Vr(Qr,"StructArrayLayout4i8");class Lr extends ln{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(f,b,S,T,D){const F=this.length;return this.resize(F+1),this.emplace(F,f,b,S,T,D)}emplace(f,b,S,T,D,F){const q=5*f;return this.int16[q+0]=b,this.int16[q+1]=S,this.int16[q+2]=T,this.int16[q+3]=D,this.int16[q+4]=F,f}}Lr.prototype.bytesPerElement=10,Vr(Lr,"StructArrayLayout5i10");class qa extends ln{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(f,b,S,T,D,F,q){const K=this.length;return this.resize(K+1),this.emplace(K,f,b,S,T,D,F,q)}emplace(f,b,S,T,D,F,q,K){const X=6*f,ce=12*f,pe=3*f;return this.int16[X+0]=b,this.int16[X+1]=S,this.uint8[ce+4]=T,this.uint8[ce+5]=D,this.uint8[ce+6]=F,this.uint8[ce+7]=q,this.float32[pe+2]=K,f}}qa.prototype.bytesPerElement=12,Vr(qa,"StructArrayLayout2i4ub1f12");class Nr extends ln{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(f,b,S){const T=this.length;return this.resize(T+1),this.emplace(T,f,b,S)}emplace(f,b,S,T){const D=3*f;return this.float32[D+0]=b,this.float32[D+1]=S,this.float32[D+2]=T,f}}Nr.prototype.bytesPerElement=12,Vr(Nr,"StructArrayLayout3f12");class cr extends ln{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(f,b,S,T,D){const F=this.length;return this.resize(F+1),this.emplace(F,f,b,S,T,D)}emplace(f,b,S,T,D,F){const q=6*f,K=3*f;return this.uint16[q+0]=b,this.uint16[q+1]=S,this.uint16[q+2]=T,this.uint16[q+3]=D,this.float32[K+2]=F,f}}cr.prototype.bytesPerElement=12,Vr(cr,"StructArrayLayout4ui1f12");class Fr extends ln{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(f,b,S,T){const D=this.length;return this.resize(D+1),this.emplace(D,f,b,S,T)}emplace(f,b,S,T,D){const F=4*f;return this.uint16[F+0]=b,this.uint16[F+1]=S,this.uint16[F+2]=T,this.uint16[F+3]=D,f}}Fr.prototype.bytesPerElement=8,Vr(Fr,"StructArrayLayout4ui8");class Fa extends ln{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(f,b,S,T,D,F){const q=this.length;return this.resize(q+1),this.emplace(q,f,b,S,T,D,F)}emplace(f,b,S,T,D,F,q){const K=6*f;return this.int16[K+0]=b,this.int16[K+1]=S,this.int16[K+2]=T,this.int16[K+3]=D,this.int16[K+4]=F,this.int16[K+5]=q,f}}Fa.prototype.bytesPerElement=12,Vr(Fa,"StructArrayLayout6i12");class ta extends ln{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(f,b,S,T,D,F,q,K,X,ce,pe,xe){const Ne=this.length;return this.resize(Ne+1),this.emplace(Ne,f,b,S,T,D,F,q,K,X,ce,pe,xe)}emplace(f,b,S,T,D,F,q,K,X,ce,pe,xe,Ne){const Me=12*f;return this.int16[Me+0]=b,this.int16[Me+1]=S,this.int16[Me+2]=T,this.int16[Me+3]=D,this.uint16[Me+4]=F,this.uint16[Me+5]=q,this.uint16[Me+6]=K,this.uint16[Me+7]=X,this.int16[Me+8]=ce,this.int16[Me+9]=pe,this.int16[Me+10]=xe,this.int16[Me+11]=Ne,f}}ta.prototype.bytesPerElement=24,Vr(ta,"StructArrayLayout4i4ui4i24");class Ta extends ln{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(f,b,S,T,D,F){const q=this.length;return this.resize(q+1),this.emplace(q,f,b,S,T,D,F)}emplace(f,b,S,T,D,F,q){const K=10*f,X=5*f;return this.int16[K+0]=b,this.int16[K+1]=S,this.int16[K+2]=T,this.float32[X+2]=D,this.float32[X+3]=F,this.float32[X+4]=q,f}}Ta.prototype.bytesPerElement=20,Vr(Ta,"StructArrayLayout3i3f20");class ci extends ln{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(f,b,S,T){const D=this.length;return this.resize(D+1),this.emplace(D,f,b,S,T)}emplace(f,b,S,T,D){const F=4*f;return this.float32[F+0]=b,this.float32[F+1]=S,this.float32[F+2]=T,this.float32[F+3]=D,f}}ci.prototype.bytesPerElement=16,Vr(ci,"StructArrayLayout4f16");class uo extends ln{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer)}emplaceBack(f){const b=this.length;return this.resize(b+1),this.emplace(b,f)}emplace(f,b){return this.uint32[1*f+0]=b,f}}uo.prototype.bytesPerElement=4,Vr(uo,"StructArrayLayout1ul4");class ao extends ln{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(f,b){const S=this.length;return this.resize(S+1),this.emplace(S,f,b)}emplace(f,b,S){const T=2*f;return this.uint16[T+0]=b,this.uint16[T+1]=S,f}}ao.prototype.bytesPerElement=4,Vr(ao,"StructArrayLayout2ui4");class Io extends ln{_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(f,b,S,T,D,F,q,K,X,ce,pe,xe,Ne){const Me=this.length;return this.resize(Me+1),this.emplace(Me,f,b,S,T,D,F,q,K,X,ce,pe,xe,Ne)}emplace(f,b,S,T,D,F,q,K,X,ce,pe,xe,Ne,Me){const ze=20*f,Ve=10*f;return this.int16[ze+0]=b,this.int16[ze+1]=S,this.int16[ze+2]=T,this.int16[ze+3]=D,this.int16[ze+4]=F,this.float32[Ve+3]=q,this.float32[Ve+4]=K,this.float32[Ve+5]=X,this.float32[Ve+6]=ce,this.int16[ze+14]=pe,this.uint32[Ve+8]=xe,this.uint16[ze+18]=Ne,this.uint16[ze+19]=Me,f}}Io.prototype.bytesPerElement=40,Vr(Io,"StructArrayLayout5i4f1i1ul2ui40");class qc extends ln{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(f,b,S,T,D,F,q){const K=this.length;return this.resize(K+1),this.emplace(K,f,b,S,T,D,F,q)}emplace(f,b,S,T,D,F,q,K){const X=8*f;return this.int16[X+0]=b,this.int16[X+1]=S,this.int16[X+2]=T,this.int16[X+4]=D,this.int16[X+5]=F,this.int16[X+6]=q,this.int16[X+7]=K,f}}qc.prototype.bytesPerElement=16,Vr(qc,"StructArrayLayout3i2i2i16");class Tc extends ln{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(f,b,S,T,D){const F=this.length;return this.resize(F+1),this.emplace(F,f,b,S,T,D)}emplace(f,b,S,T,D,F){const q=4*f,K=8*f;return this.float32[q+0]=b,this.float32[q+1]=S,this.float32[q+2]=T,this.int16[K+6]=D,this.int16[K+7]=F,f}}Tc.prototype.bytesPerElement=16,Vr(Tc,"StructArrayLayout2f1f2i16");class Wo extends ln{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(f,b,S,T,D,F){const q=this.length;return this.resize(q+1),this.emplace(q,f,b,S,T,D,F)}emplace(f,b,S,T,D,F,q){const K=20*f,X=5*f;return this.uint8[K+0]=b,this.uint8[K+1]=S,this.float32[X+1]=T,this.float32[X+2]=D,this.float32[X+3]=F,this.float32[X+4]=q,f}}Wo.prototype.bytesPerElement=20,Vr(Wo,"StructArrayLayout2ub4f20");class Va extends ln{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(f,b,S){const T=this.length;return this.resize(T+1),this.emplace(T,f,b,S)}emplace(f,b,S,T){const D=3*f;return this.uint16[D+0]=b,this.uint16[D+1]=S,this.uint16[D+2]=T,f}}Va.prototype.bytesPerElement=6,Vr(Va,"StructArrayLayout3ui6");class Vc extends ln{_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(f,b,S,T,D,F,q,K,X,ce,pe,xe,Ne,Me,ze,Ve,Je,lt,ht,ct,xt){const kt=this.length;return this.resize(kt+1),this.emplace(kt,f,b,S,T,D,F,q,K,X,ce,pe,xe,Ne,Me,ze,Ve,Je,lt,ht,ct,xt)}emplace(f,b,S,T,D,F,q,K,X,ce,pe,xe,Ne,Me,ze,Ve,Je,lt,ht,ct,xt,kt){const es=30*f,Ct=15*f,Lt=60*f;return this.int16[es+0]=b,this.int16[es+1]=S,this.int16[es+2]=T,this.float32[Ct+2]=D,this.float32[Ct+3]=F,this.uint16[es+8]=q,this.uint16[es+9]=K,this.uint32[Ct+5]=X,this.uint32[Ct+6]=ce,this.uint32[Ct+7]=pe,this.uint16[es+16]=xe,this.uint16[es+17]=Ne,this.uint16[es+18]=Me,this.float32[Ct+10]=ze,this.float32[Ct+11]=Ve,this.uint8[Lt+48]=Je,this.uint8[Lt+49]=lt,this.uint8[Lt+50]=ht,this.uint32[Ct+13]=ct,this.int16[es+28]=xt,this.uint8[Lt+58]=kt,f}}Vc.prototype.bytesPerElement=60,Vr(Vc,"StructArrayLayout3i2f2ui3ul3ui2f3ub1ul1i1ub60");class Ju extends ln{_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(f,b,S,T,D,F,q,K,X,ce,pe,xe,Ne,Me,ze,Ve,Je,lt,ht,ct,xt,kt,es,Ct,Lt,Zt,Qt,Cs,Fs,on,sn,hn,Rn){const ws=this.length;return this.resize(ws+1),this.emplace(ws,f,b,S,T,D,F,q,K,X,ce,pe,xe,Ne,Me,ze,Ve,Je,lt,ht,ct,xt,kt,es,Ct,Lt,Zt,Qt,Cs,Fs,on,sn,hn,Rn)}emplace(f,b,S,T,D,F,q,K,X,ce,pe,xe,Ne,Me,ze,Ve,Je,lt,ht,ct,xt,kt,es,Ct,Lt,Zt,Qt,Cs,Fs,on,sn,hn,Rn,ws){const qs=20*f,en=40*f,wn=80*f;return this.float32[qs+0]=b,this.float32[qs+1]=S,this.int16[en+4]=T,this.int16[en+5]=D,this.int16[en+6]=F,this.int16[en+7]=q,this.int16[en+8]=K,this.int16[en+9]=X,this.int16[en+10]=ce,this.int16[en+11]=pe,this.int16[en+12]=xe,this.uint16[en+13]=Ne,this.uint16[en+14]=Me,this.uint16[en+15]=ze,this.uint16[en+16]=Ve,this.uint16[en+17]=Je,this.uint16[en+18]=lt,this.uint16[en+19]=ht,this.uint16[en+20]=ct,this.uint16[en+21]=xt,this.uint16[en+22]=kt,this.uint16[en+23]=es,this.uint16[en+24]=Ct,this.uint16[en+25]=Lt,this.uint16[en+26]=Zt,this.uint16[en+27]=Qt,this.uint32[qs+14]=Cs,this.float32[qs+15]=Fs,this.float32[qs+16]=on,this.float32[qs+17]=sn,this.float32[qs+18]=hn,this.uint8[wn+76]=Rn,this.uint16[en+39]=ws,f}}Ju.prototype.bytesPerElement=80,Vr(Ju,"StructArrayLayout2f9i15ui1ul4f1ub1ui80");class du extends ln{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(f,b,S,T,D,F){const q=this.length;return this.resize(q+1),this.emplace(q,f,b,S,T,D,F)}emplace(f,b,S,T,D,F,q){const K=6*f;return this.float32[K+0]=b,this.float32[K+1]=S,this.float32[K+2]=T,this.float32[K+3]=D,this.float32[K+4]=F,this.float32[K+5]=q,f}}du.prototype.bytesPerElement=24,Vr(du,"StructArrayLayout6f24");class bl extends ln{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(f,b,S,T,D){const F=this.length;return this.resize(F+1),this.emplace(F,f,b,S,T,D)}emplace(f,b,S,T,D,F){const q=5*f;return this.float32[q+0]=b,this.float32[q+1]=S,this.float32[q+2]=T,this.float32[q+3]=D,this.float32[q+4]=F,f}}bl.prototype.bytesPerElement=20,Vr(bl,"StructArrayLayout5f20");class uu extends ln{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(f,b,S,T,D,F,q){const K=this.length;return this.resize(K+1),this.emplace(K,f,b,S,T,D,F,q)}emplace(f,b,S,T,D,F,q,K){const X=7*f;return this.float32[X+0]=b,this.float32[X+1]=S,this.float32[X+2]=T,this.float32[X+3]=D,this.float32[X+4]=F,this.float32[X+5]=q,this.float32[X+6]=K,f}}uu.prototype.bytesPerElement=28,Vr(uu,"StructArrayLayout7f28");class dd extends ln{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(f,b,S,T,D,F,q,K,X,ce,pe){const xe=this.length;return this.resize(xe+1),this.emplace(xe,f,b,S,T,D,F,q,K,X,ce,pe)}emplace(f,b,S,T,D,F,q,K,X,ce,pe,xe){const Ne=11*f;return this.float32[Ne+0]=b,this.float32[Ne+1]=S,this.float32[Ne+2]=T,this.float32[Ne+3]=D,this.float32[Ne+4]=F,this.float32[Ne+5]=q,this.float32[Ne+6]=K,this.float32[Ne+7]=X,this.float32[Ne+8]=ce,this.float32[Ne+9]=pe,this.float32[Ne+10]=xe,f}}dd.prototype.bytesPerElement=44,Vr(dd,"StructArrayLayout11f44");class gl extends ln{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(f,b,S,T,D,F,q,K,X){const ce=this.length;return this.resize(ce+1),this.emplace(ce,f,b,S,T,D,F,q,K,X)}emplace(f,b,S,T,D,F,q,K,X,ce){const pe=9*f;return this.float32[pe+0]=b,this.float32[pe+1]=S,this.float32[pe+2]=T,this.float32[pe+3]=D,this.float32[pe+4]=F,this.float32[pe+5]=q,this.float32[pe+6]=K,this.float32[pe+7]=X,this.float32[pe+8]=ce,f}}gl.prototype.bytesPerElement=36,Vr(gl,"StructArrayLayout9f36");class Hc extends ln{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(f,b){const S=this.length;return this.resize(S+1),this.emplace(S,f,b)}emplace(f,b,S){const T=2*f;return this.float32[T+0]=b,this.float32[T+1]=S,f}}Hc.prototype.bytesPerElement=8,Vr(Hc,"StructArrayLayout2f8");class Fu extends ln{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(f,b,S,T){const D=this.length;return this.resize(D+1),this.emplace(D,f,b,S,T)}emplace(f,b,S,T,D){const F=6*f;return this.uint32[3*f+0]=b,this.uint16[F+2]=S,this.uint16[F+3]=T,this.uint16[F+4]=D,f}}Fu.prototype.bytesPerElement=12,Vr(Fu,"StructArrayLayout1ul3ui12");class Yl extends ln{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(f){const b=this.length;return this.resize(b+1),this.emplace(b,f)}emplace(f,b){return this.uint16[1*f+0]=b,f}}Yl.prototype.bytesPerElement=2,Vr(Yl,"StructArrayLayout1ui2");class zl extends ln{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(f,b,S,T,D,F,q,K,X,ce,pe,xe,Ne,Me,ze,Ve){const Je=this.length;return this.resize(Je+1),this.emplace(Je,f,b,S,T,D,F,q,K,X,ce,pe,xe,Ne,Me,ze,Ve)}emplace(f,b,S,T,D,F,q,K,X,ce,pe,xe,Ne,Me,ze,Ve,Je){const lt=16*f;return this.float32[lt+0]=b,this.float32[lt+1]=S,this.float32[lt+2]=T,this.float32[lt+3]=D,this.float32[lt+4]=F,this.float32[lt+5]=q,this.float32[lt+6]=K,this.float32[lt+7]=X,this.float32[lt+8]=ce,this.float32[lt+9]=pe,this.float32[lt+10]=xe,this.float32[lt+11]=Ne,this.float32[lt+12]=Me,this.float32[lt+13]=ze,this.float32[lt+14]=Ve,this.float32[lt+15]=Je,f}}zl.prototype.bytesPerElement=64,Vr(zl,"StructArrayLayout16f64");class Ud extends ln{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(f,b,S,T,D,F,q){const K=this.length;return this.resize(K+1),this.emplace(K,f,b,S,T,D,F,q)}emplace(f,b,S,T,D,F,q,K){const X=10*f,ce=5*f;return this.uint16[X+0]=b,this.uint16[X+1]=S,this.uint16[X+2]=T,this.uint16[X+3]=D,this.float32[ce+2]=F,this.float32[ce+3]=q,this.float32[ce+4]=K,f}}Ud.prototype.bytesPerElement=20,Vr(Ud,"StructArrayLayout4ui3f20");class af extends ln{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(f){const b=this.length;return this.resize(b+1),this.emplace(b,f)}emplace(f,b){return this.int16[1*f+0]=b,f}}af.prototype.bytesPerElement=2,Vr(af,"StructArrayLayout1i2");class Pv extends ln{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer)}emplaceBack(f){const b=this.length;return this.resize(b+1),this.emplace(b,f)}emplace(f,b){return this.uint8[1*f+0]=b,f}}Pv.prototype.bytesPerElement=1,Vr(Pv,"StructArrayLayout1ub1");class ty extends Ks{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]}}ty.prototype.size=40;class ew extends Io{get(f){return new ty(this,f)}}Vr(ew,"CollisionBoxArray");class Ad extends Ks{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(f){this._structArray.uint8[this._pos1+49]=f}get hidden(){return this._structArray.uint8[this._pos1+50]}set hidden(f){this._structArray.uint8[this._pos1+50]=f}get crossTileID(){return this._structArray.uint32[this._pos4+13]}set crossTileID(f){this._structArray.uint32[this._pos4+13]=f}get associatedIconIndex(){return this._structArray.int16[this._pos2+28]}get flipState(){return this._structArray.uint8[this._pos1+58]}set flipState(f){this._structArray.uint8[this._pos1+58]=f}}Ad.prototype.size=60;class jc extends Vc{get(f){return new Ad(this,f)}}Vr(jc,"PlacedSymbolArray");class Zl extends Ks{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(f){this._structArray.uint32[this._pos4+14]=f}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(f){this._structArray.float32[this._pos4+18]=f}get hasIconTextFit(){return this._structArray.uint8[this._pos1+76]}get elevationFeatureIndex(){return this._structArray.uint16[this._pos2+39]}}Zl.prototype.size=80;class zu extends Ju{get(f){return new Zl(this,f)}}Vr(zu,"SymbolInstanceArray");class bp extends Hn{getoffsetX(f){return this.float32[1*f+0]}}Vr(bp,"GlyphOffsetArray");class qd extends Sn{getx(f){return this.int16[2*f+0]}gety(f){return this.int16[2*f+1]}}Vr(qd,"SymbolLineVertexArray");class _l extends Ks{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]}}_l.prototype.size=12;class of extends Fu{get(f){return new _l(this,f)}}Vr(of,"FeatureIndexArray");class Bf extends ao{geta_centroid_pos0(f){return this.uint16[2*f+0]}geta_centroid_pos1(f){return this.uint16[2*f+1]}}Vr(Bf,"FillExtrusionCentroidArray");class Bb extends Ks{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]}}Bb.prototype.size=6;class $b extends lr{get(f){return new Bb(this,f)}}Vr($b,"FillExtrusionWallArray");const Ej=an([{name:"a_pos",components:2,type:"Int16"}],4),F1=an([{name:"a_road_z_offset",components:1,type:"Float32"}],4),Kk=an([{name:"a_pos",components:2,type:"Int16"},{name:"a_height",components:1,type:"Float32"}],4),tw=an([{name:"a_pos_normal_3",components:3,type:"Int16"}],4);class lc{constructor(f=[]){this.segments=f}_prepareSegment(f,b,S,T,D){let F=this.segments.at(-1);return f>lc.MAX_VERTEX_ARRAY_LENGTH&&oi(`Max vertices per segment is ${lc.MAX_VERTEX_ARRAY_LENGTH}: bucket requested ${f}`),(!F||F.vertexLength+f>lc.MAX_VERTEX_ARRAY_LENGTH||F.sortKey!==T||D!==void 0&&F&&F.batchIndex!==void 0&&F.batchIndex!==D)&&(F={vertexOffset:b,primitiveOffset:S,vertexLength:0,primitiveLength:0},T!==void 0&&(F.sortKey=T),D!==void 0&&(F.batchIndex=D),this.segments.push(F)),F}prepareSegment(f,b,S,T,D){return this._prepareSegment(f,b.length,S.length,T,D)}get(){return this.segments}destroy(){for(const f of this.segments)for(const b in f.vaos)f.vaos[b].destroy()}static simpleSegment(f,b,S,T){return new lc([{vertexOffset:f,primitiveOffset:b,vertexLength:S,primitiveLength:T,vaos:{},sortKey:0}])}}function Yk(w,f){return 256*(w=Jr(Math.floor(w),0,255))+Jr(Math.floor(f),0,255)}lc.MAX_VERTEX_ARRAY_LENGTH=Math.pow(2,16)-1,Vr(lc,"SegmentVector");const d7=an([{name:"a_pattern",components:4,type:"Uint16"},{name:"a_pixel_ratio",components:1,type:"Float32"}]),rH=an([{name:"a_pattern_b",components:4,type:"Uint16"}]),aH=an([{name:"a_dash",components:4,type:"Uint16"}]);class M4{constructor(){this.ids=[],this.uniqueIds=[],this.positions=[],this.indexed=!1}add(f,b,S,T){this.ids.push(u7(f)),this.positions.push(b,S,T)}eachPosition(f,b){const S=u7(f);let T=0,D=this.ids.length-1;for(;T>1;this.ids[F]>=S?D=F:T=F+1}for(;this.ids[T]===S;)b(this.positions[3*T],this.positions[3*T+1],this.positions[3*T+2]),T++}static serialize(f,b){const S=new Float64Array(f.ids),T=new Uint32Array(f.positions);return U6(S,T,0,S.length-1),b&&(b.add(S.buffer),b.add(T.buffer)),{ids:S,positions:T}}static deserialize(f){const b=new M4;let S;b.ids=f.ids,b.positions=f.positions;for(const T of b.ids)T!==S&&b.uniqueIds.push(T),S=T;return b.indexed=!0,b}}function u7(w){const f=+w;return Number.isSafeInteger(f)?f:up(String(w))}function U6(w,f,b,S){for(;b>1];let D=b-1,F=S+1;for(;;){do D++;while(w[D]T);if(D>=F)break;vA(w,D,F),vA(f,3*D,3*F),vA(f,3*D+1,3*F+1),vA(f,3*D+2,3*F+2)}F-b`u_${D}`),this.type=S,this.context=T}setUniform(f,b,S,T,D){const F=T.constantOr(this.value);b.set(f,D,F instanceof Mi?F.toPremultipliedRenderColor(this.lutExpression&&this.lutExpression.kind==="constant"&&this.lutExpression.value==="none"?null:this.context.lut):F)}getBinding(f,b){return this.type==="color"?new pMe(f):new Zi(f)}}class iH{constructor(f,b){this.uniformNames=b.map(S=>`u_${S}`),this.pattern=null,this.patternTransition=null,this.pixelRatio=1}setConstantPatternPositions(f,b){this.pixelRatio=f.pixelRatio||1,this.pattern=f.tl.concat(f.br),this.patternTransition=b?b.tl.concat(b.br):this.pattern}setUniform(f,b,S,T,D){let F=null;D!=="u_pattern"&&D!=="u_dash"||(F=this.pattern),D==="u_pattern_b"&&(F=this.patternTransition),D==="u_pixel_ratio"&&(F=this.pixelRatio),F&&b.set(f,D,F)}getBinding(f,b){return b==="u_pattern"||b==="u_pattern_b"||b==="u_dash"?new OKt(f):new Zi(f)}}class I4{constructor(f,b,S,T){this.expression=f,this.type=S,this.maxValue=0,this.paintVertexAttributes=b.map(D=>({name:`a_${D}`,type:"Float32",components:S==="color"?2:1,offset:0})),this.paintVertexArray=new T}populatePaintArray(f,b,S,T,D,F,q,K){const X=this.paintVertexArray.length,ce=this.expression.kind==="composite"||this.expression.kind==="source"?this.expression.evaluate(new tr(0,{brightness:F,worldview:K}),b,{},D,T,q):this.expression.kind==="constant"&&this.expression.value,pe=Hte(this.lutExpression,b,{},T,D,F,q,K);this.paintVertexArray.resize(f),this._setPaintValue(X,f,ce,pe?null:this.context.lut)}updatePaintArray(f,b,S,T,D,F,q,K){const X=this.expression.kind==="composite"||this.expression.kind==="source"?this.expression.evaluate({zoom:0,brightness:q,worldview:K},S,T,void 0,D):this.expression.kind==="constant"&&this.expression.value,ce=Hte(this.lutExpression,S,T,D,void 0,q,void 0,K);this._setPaintValue(f,b,X,ce?null:this.context.lut)}_setPaintValue(f,b,S,T){if(this.type==="color"){const D=xMe(S.toPremultipliedRenderColor(T));for(let F=f;F`u_${q}_t`),this.type=S,this.useIntegerZoom=T,this.context=D,this.maxValue=0,this.paintVertexAttributes=b.map(q=>({name:`a_${q}`,type:"Float32",components:S==="color"?4:2,offset:0})),this.paintVertexArray=new F}populatePaintArray(f,b,S,T,D,F,q,K){const X=this.expression.evaluate(new tr(this.context.zoom,{brightness:F,worldview:K}),b,{},D,T,q),ce=this.expression.evaluate(new tr(this.context.zoom+1,{brightness:F,worldview:K}),b,{},D,T,q),pe=Hte(this.lutExpression,b,{},T,D,F,q,K),xe=this.paintVertexArray.length;this.paintVertexArray.resize(f),this._setPaintValue(xe,f,X,ce,pe?null:this.context.lut)}updatePaintArray(f,b,S,T,D,F,q,K){const X=this.expression.evaluate({zoom:this.context.zoom,brightness:q,worldview:K},S,T,void 0,D),ce=this.expression.evaluate({zoom:this.context.zoom+1,brightness:q,worldview:K},S,T,void 0,D),pe=Hte(this.lutExpression,S,T,D,void 0,q,void 0,K);this._setPaintValue(f,b,X,ce,pe?null:this.context.lut)}_setPaintValue(f,b,S,T,D){if(this.type==="color"){const F=xMe(S.toPremultipliedRenderColor(D)),q=xMe(T.toPremultipliedRenderColor(D));for(let K=f;K!0){this.binders={},this._buffers=[],this.context=b;const T=[],D=f;for(const F in f.paint._values){const q=D.paint.get(F);if(F.endsWith("-use-theme")||!S(F)||!(q instanceof wc&&Ob(q.property.specification)))continue;const K=zKt(F,f.type),X=q.value,ce=q.property.specification.type,pe=!!q.property.useIntegerZoom,xe=F==="line-dasharray"||F.endsWith("pattern"),Ne=D.paint.get(`${F}-use-theme`),Me=F==="line-dasharray"&&D.layout.get("line-cap").value.kind!=="constant"||Ne&&Ne.value.kind!=="constant";if(X.kind!=="constant"||Me)if(X.kind==="source"||Me||xe){const ze=AJe(F,ce,"source");this.binders[F]=xe?new Xk(X,K,ce,ze,f.id):new I4(X,K,ce,ze),T.push(`/a_${F}`)}else{const ze=AJe(F,ce,"composite");this.binders[F]=new Zk(X,K,ce,pe,b,ze),T.push(`/z_${F}`)}else this.binders[F]=xe?new iH(X.value,K):new Gte(X.value,K,ce,b),T.push(`/u_${F}`);Ne&&(this.binders[F].lutExpression=Ne.value)}this.cacheKey=T.sort().join("")}updateExpressions(f){const b=f;for(const S in this.binders){const T=this.binders[S];if(T instanceof I4||T instanceof Zk||T instanceof Xk){const D=b.paint.get(S);T.expression=D.value}}}getMaxValue(f){const b=this.binders[f];return b instanceof I4||b instanceof Zk?b.maxValue:0}populatePaintArrays(f,b,S,T,D,F,q,K){for(const X in this.binders){const ce=this.binders[X];ce.context=this.context,(ce instanceof I4||ce instanceof Zk||ce instanceof Xk)&&ce.populatePaintArray(f,b,S,T,D,F,q,K)}}setConstantPatternPositions(f,b){for(const S in this.binders){const T=this.binders[S];T instanceof iH&&T.setConstantPatternPositions(f,b)}}getPatternTransitionVertexBuffer(f){const b=this.binders[f];return b instanceof Xk?b.paintTransitionVertexBuffer:null}updatePaintArrays(f,b,S,T,D,F,q,K,X,ce){let pe=!1;const xe=Object.keys(f),Ne=xe.length!==0&&!K,Me=Ne?xe:b.uniqueIds;this.context.lut=D.lut;for(const ze in this.binders){const Ve=this.binders[ze];if(Ve.context=this.context,(Ve instanceof I4||Ve instanceof Zk||Ve instanceof Xk)&&Ve.expression&&Ve.expression.kind&&Ve.expression.kind!=="constant"&&(Ve.expression.isStateDependent===!0||Ve.expression.isLightConstant===!1)){const Je=D.paint.get(ze);Ve.expression=Je.value;for(const lt of Me){const ht=f[lt.toString()];b.eachPosition(lt,(ct,xt,kt)=>{const es=T.feature(ct);Ve.updatePaintArray(xt,kt,es,ht,F,q,X,ce)})}if(!Ne)for(const lt of S.uniqueIds){const ht=f[lt.toString()];S.eachPosition(lt,(ct,xt,kt)=>{const es=T.feature(ct);Ve.updatePaintArray(xt,kt,es,ht,F,q,X,ce)})}pe=!0}}return pe}defines(){const f=[];for(const b in this.binders){const S=this.binders[b];(S instanceof Gte||S instanceof iH)&&f.push(...S.uniformNames.map(T=>`#define HAS_UNIFORM_${T}`))}return f}getPaintVertexBuffers(){return this._buffers}getUniforms(f){const b=[];for(const S in this.binders){const T=this.binders[S];if(T instanceof Gte||T instanceof iH||T instanceof Zk)for(const D of T.uniformNames)b.push({name:D,property:S,binding:T.getBinding(f,D)})}return b}setUniforms(f,b,S,T,D){for(const{name:F,property:q,binding:K}of S)this.binders[q].setUniform(f,K,D,T.get(q),F)}updatePaintBuffers(){this._buffers=[];for(const f in this.binders){const b=this.binders[f];(b instanceof I4||b instanceof Zk||b instanceof Xk)&&b.paintVertexBuffer&&this._buffers.push(b.paintVertexBuffer),b instanceof Xk&&b.paintTransitionVertexBuffer&&this._buffers.push(b.paintTransitionVertexBuffer)}}upload(f){for(const b in this.binders){const S=this.binders[b];(S instanceof I4||S instanceof Zk||S instanceof Xk)&&S.upload(f)}this.updatePaintBuffers()}destroy(){for(const f in this.binders){const b=this.binders[f];(b instanceof I4||b instanceof Zk||b instanceof Xk)&&b.destroy()}}}class aN{constructor(f,b,S=()=>!0){this.programConfigurations={};for(const T of f)this.programConfigurations[T.id]=new q6(T,b,S);this.needsUpload=!1,this._featureMap=new M4,this._featureMapWithoutIds=new M4,this._bufferOffset=0,this._idlessCounter=0}populatePaintArrays(f,b,S,T,D,F,q,K,X){for(const ce in this.programConfigurations)this.programConfigurations[ce].populatePaintArrays(f,b,T,D,F,q,K,X);b.id!==void 0?this._featureMap.add(b.id,S,this._bufferOffset,f):(this._featureMapWithoutIds.add(this._idlessCounter,S,this._bufferOffset,f),this._idlessCounter+=1),this._bufferOffset=f,this.needsUpload=!0}updatePaintArrays(f,b,S,T,D,F,q,K){for(const X of S)this.needsUpload=this.programConfigurations[X.id].updatePaintArrays(f,this._featureMap,this._featureMapWithoutIds,b,X,T,D,F,q||0,K)||this.needsUpload}get(f){return this.programConfigurations[f]}upload(f){if(this.needsUpload){for(const b in this.programConfigurations)this.programConfigurations[b].upload(f);this.needsUpload=!1}}destroy(){for(const f in this.programConfigurations)this.programConfigurations[f].destroy()}updateExpressions(f){const b=new Set;for(const S of f){const T=this.programConfigurations[S.id];T&&(T.updateExpressions(S),b.add(S.id))}for(const S in this.programConfigurations)b.has(S)||delete this.programConfigurations[S]}}const FKt={"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 zKt(w,f){return FKt[w]||[w.replace(`${f}-`,"").replace(/-/g,"_")]}const BKt={"line-pattern":{source:cr,composite:cr},"fill-pattern":{source:cr,composite:cr},"fill-extrusion-pattern":{source:cr,composite:cr},"line-dasharray":{source:Fr,composite:Fr}},$Kt={color:{source:Hc,composite:ci},number:{source:Hn,composite:Hc}};function AJe(w,f,b){const S=BKt[w];return S&&S[b]||$Kt[f][b]}Vr(Gte,"ConstantBinder"),Vr(iH,"PatternConstantBinder"),Vr(I4,"SourceExpressionBinder",{omit:["expression"]}),Vr(Xk,"PatternCompositeBinder",{omit:["expression"]}),Vr(Zk,"CompositeExpressionBinder",{omit:["expression"]}),Vr(q6,"ProgramConfiguration",{omit:["_buffers"]}),Vr(aN,"ProgramConfigurationSet");class yMe{constructor(f,b,S){this.layoutVertexArray=new Sn,this.indexArray=new Va,this.lineIndexArray=new ao,this.triangleSegments=new lc,this.lineSegments=new lc,this.programConfigurations=new aN(f,{zoom:b,lut:S}),this.uploaded=!1}update(f,b,S,T,D,F,q,K){this.programConfigurations.updatePaintArrays(f,b,D,S,T,F,q,K)}isEmpty(){return this.layoutVertexArray.length===0}needsUpload(){return this.programConfigurations.needsUpload}upload(f){this.uploaded||(this.layoutVertexBuffer=f.createVertexBuffer(this.layoutVertexArray,Ej.members),this.indexBuffer=f.createIndexBuffer(this.indexArray),this.lineIndexBuffer=f.createIndexBuffer(this.lineIndexArray)),this.programConfigurations.upload(f),this.uploaded=!0}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.lineIndexBuffer.destroy(),this.programConfigurations.destroy(),this.triangleSegments.destroy(),this.lineSegments.destroy())}populatePaintArrays(f,b,S,T,D,F,q){this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,f,b,S,T,D,F,void 0,q)}}Vr(yMe,"FillBufferData");class vMe{constructor(f){this.zoom=f.zoom,this.pixelRatio=f.pixelRatio,this.overscaling=f.overscaling,this.layers=f.layers,this.layerIds=this.layers.map(b=>b.fqid),this.index=f.index,this.hasPattern=!1,this.patternFeatures=[],this.lut=f.lut,this.bufferData=new yMe(f.layers,f.zoom,f.lut),this.stateDependentLayerIds=this.layers.filter(b=>b.isStateDependent()).map(b=>b.id),this.projection=f.projection,this.sourceLayerIndex=f.sourceLayerIndex,this.sourceLayerName=f.sourceLayerName||"",this.worldview=f.worldview,this.hasAppearances=null}updateFootprints(f,b){}updateAppearances(f,b,S,T){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(f,b,S,T){this.hasPattern=sH("fill",this.layers,this.pixelRatio,b);const D=this.layers[0].layout.get("fill-sort-key"),F=[];for(const{feature:q,id:K,index:X,sourceLayerIndex:ce}of f){const pe=this.layers[0]._featureFilter.needGeometry,xe=Js(q,pe);if(!this.layers[0]._featureFilter.filter(new tr(this.zoom,{worldview:this.worldview,activeFloors:b.activeFloors}),xe,S))continue;const Ne=D?D.evaluate(xe,{},S,b.availableImages):void 0,Me={id:K,properties:q.properties,type:q.type,sourceLayerIndex:ce,index:X,geometry:pe?xe.geometry:Ms(q,S,T),patterns:{},sortKey:Ne};F.push(Me)}D&&F.sort((q,K)=>q.sortKey-K.sortKey);for(const q of F){const{geometry:K,index:X,sourceLayerIndex:ce}=q;if(this.hasPattern){const pe=nH("fill",this.layers,q,this.zoom,this.pixelRatio,b);this.patternFeatures.push(pe)}else this.addFeature(q,K,X,S,{},b.availableImages,b.brightness,b.elevationFeatures);b.featureIndex.insert(f[X].feature,K,X,ce,this.index)}!this.hasPattern&&this.hdExt&&this.hdExt.buildFrcSegments(this)}update(f,b,S,T,D,F,q){this.bufferData.update(f,b,S,T,D,F,q,this.worldview),this.hdExt&&this.hdExt.update(f,b,S,T,D,F,q,this.worldview)}updateExpressions(f){this.bufferData.programConfigurations.updateExpressions(f),this.hdExt&&this.hdExt.updateExpressions(f)}addFeatures(f,b,S,T,D,F){for(const q of this.patternFeatures)this.addFeature(q,q.geometry,q.index,b,S,T,F,f.elevationFeatures);this.hdExt&&this.hdExt.buildFrcSegments(this)}isEmpty(){return this.bufferData.isEmpty()&&(!this.hdExt||this.hdExt.isEmpty())}uploadPending(){return!this.uploaded||this.bufferData.needsUpload()||this.hdExt!=null&&this.hdExt.needsUpload()}upload(f){this.bufferData.upload(f),this.hdExt&&this.hdExt.upload(f)}destroy(){this.bufferData.destroy(),this.hdExt&&this.hdExt.destroy()}addFeature(f,b,S,T,D,F=[],q,K){const X=this.hdExt?this.hdExt.trackFeatureFrc(f.properties):null,ce=this.bufferData.indexArray.length,pe=Ur(b,500);this.hdExt!=null&&this.hdExt.handleFeature(f,pe,S,T,K,this)||this.addGeometry(pe,this.bufferData),this.bufferData.populatePaintArrays(f,S,D,F,T,q,this.worldview),this.hdExt&&this.hdExt.populatePaintArrays(f,S,D,F,T,q,this.worldview),this.hdExt&&this.hdExt.recordFeatureRange(this,ce,this.bufferData.indexArray.length,X)}addGeometry(f,b,S,T){let D=Number.POSITIVE_INFINITY,F=Number.NEGATIVE_INFINITY,q=null;S&&(q=S.elevationSampler.constantElevation(S.elevation,S.bias),q!=null&&(D=q,F=q));const K=S?b:null,X=(ce,pe,xe)=>{if(S!=null)if(pe.push(ce),q!=null)K.elevatedLayoutVertexArray.emplaceBack(q),xe.push(q);else{const Ne=S.elevationSampler.pointElevation(ce,S.elevation,S.bias);K.elevatedLayoutVertexArray.emplaceBack(Ne),xe.push(Ne),D=Math.min(D,Ne),F=Math.max(F,Ne)}};for(const ce of f){let pe=0;for(const xt of ce)pe+=xt.length;const xe=b.triangleSegments.prepareSegment(pe,b.layoutVertexArray,b.indexArray),Ne=xe.vertexLength,Me=[],ze=[],Ve=[],Je=[],lt=[],ht=b.layoutVertexArray.length;for(const xt of ce){if(xt.length===0)continue;xt!==ce[0]&&ze.push(Me.length/2);const kt=b.lineSegments.prepareSegment(xt.length,b.layoutVertexArray,b.lineIndexArray),es=kt.vertexLength;S&<.push(b.layoutVertexArray.length-ht),X(xt[0],Ve,Je),b.layoutVertexArray.emplaceBack(xt[0].x,xt[0].y),b.lineIndexArray.emplaceBack(es+xt.length-1,es),Me.push(xt[0].x),Me.push(xt[0].y);for(let Ct=1;Ct0&&S&&T){const xt=S.elevation.isTunnel(),kt=S.elevation.safeArea,es=T.addVertices(Ve,Je);T.addTriangles(ct,es,xt);const Ct=lt.length;if(Ct>0){for(let Lt=0;Lt>3,F===0)continue}if(F--,D===1)q+=f.readSVarint(),K+=f.readSVarint(),T&&S.push(T),T=[new Kt(q,K)];else if(D===2)q+=f.readSVarint(),K+=f.readSVarint(),T&&T.push(new Kt(q,K));else{if(D!==7)throw new Error(`unknown command ${D}`);T&&T.push(T[0].clone())}}return T&&S.push(T),S}bbox(){if(this._geometry<0)throw new Error("feature has no geometry");const f=this._pbf;f.pos=this._geometry;const b=f.readVarint()+f.pos;let S=1,T=0,D=0,F=0,q=1/0,K=-1/0,X=1/0,ce=-1/0;for(;f.pos>3,T===0)continue}if(T--,S===1||S===2)D+=f.readSVarint(),F+=f.readSVarint(),DK&&(K=D),Fce&&(ce=F);else if(S!==7)throw new Error(`unknown command ${S}`)}return[q,X,K,ce]}toGeoJSON(f,b,S){const T=this.extent*Math.pow(2,S),D=this.extent*f,F=this.extent*b,q=this.loadGeometry();function K(xe){return[360*(xe.x+D)/T-180,360/Math.PI*Math.atan(Math.exp((1-2*(xe.y+F)/T)*Math.PI))-90]}function X(xe){return xe.map(K)}let ce;if(this.type===1){const xe=[];for(const Me of q)xe.push(Me[0]);const Ne=X(xe);ce=xe.length===1?{type:"Point",coordinates:Ne[0]}:{type:"MultiPoint",coordinates:Ne}}else if(this.type===2){const xe=q.map(X);ce=xe.length===1?{type:"LineString",coordinates:xe[0]}:{type:"MultiLineString",coordinates:xe}}else{if(this.type!==3)throw new Error("unknown feature type");{const xe=function(Me){const ze=Me.length;if(ze<=1)return[Me];const Ve=[];let Je,lt;for(let ht=0;ht=this._features.length)throw new Error("feature index out of bounds");this._pbf.pos=this._features[f];const b=this._pbf.readVarint()+this._pbf.pos;return new bA(this._pbf,b,this.extent,this._keys,this._values)}}function JKt(w){let f=null;const b=w.readVarint()+w.pos;for(;w.pos1){if(jMe(w,f))return!0;for(let S=0;S1?b:b.sub(f)._mult(T)._add(f))}function TJe(w,f){let b,S,T,D=!1;for(let F=0;Ff.y!=T.y>f.y&&f.x<(T.x-S.x)*(f.y-S.y)/(T.y-S.y)+S.x&&(D=!D)}return D}function _A(w,f){let b=!1;for(let S=0,T=w.length-1;Sf.y!=F.y>f.y&&f.x<(F.x-D.x)*(f.y-D.y)/(F.y-D.y)+D.x&&(b=!b)}return b}function SMe(w,f,b,S,T){for(const F of w)if(f<=F.x&&b<=F.y&&S>=F.x&&T>=F.y)return!0;const D=[new Kt(f,b),new Kt(f,T),new Kt(S,T),new Kt(S,b)];if(w.length>2){for(const F of D)if(_A(w,F))return!0}for(let F=0;FT.x&&f.x>T.x||w.yT.y&&f.y>T.y)return!1;const D=Mo(w,f,b[0]);return D!==Mo(w,f,b[1])||D!==Mo(w,f,b[2])||D!==Mo(w,f,b[3])}function m7(w,f,b,S,T,D){let F=f.y-w.y,q=w.x-f.x;if(D=D||0){const K=F*F+q*q;if(K===0)return!0;const X=Math.sqrt(K);F/=X,q/=X}return!((b.x-w.x)*F+(b.y-w.y)*q-D<0||(S.x-w.x)*F+(S.y-w.y)*q-D<0||(T.x-w.x)*F+(T.y-w.y)*q-D<0)}function CMe(w,f,b,S,T,D,F){return!(m7(w,f,S,T,D,F)||m7(f,b,S,T,D,F)||m7(b,w,S,T,D,F)||m7(S,T,w,f,b,F)||m7(T,D,w,f,b,F)||m7(D,S,w,f,b,F))}class V6 extends Kt{constructor(f,b,S){super(f,b),this.z=S}}class MJe extends V6{constructor(f,b,S,T){super(f,b,S),this.w=T}}function PJe(w,f,b,S){const T=b==="x"?"y":"x",D=(S-w[b])/(f[b]-w[b]);w[T]=Math.round(w[T]+(f[T]-w[T])*D),w[b]=S,Object.hasOwn(w,"z")&&(w.z=da(w.z,f.z,D)),Object.hasOwn(w,"w")&&(w.w=da(w.w,f.w,D))}function IJe(w,f,b,S){const T=b,D=S;for(const F of["x","y"]){let q=w,K=f;q[F]>=K[F]&&(q=f,K=w),q[F]T&&PJe(q,K,F,T),q[F]D&&PJe(K,q,F,D)}}function AMe(w,f,b,S,T,D){const F=[];for(let q=0;q=S&&Me.x>=S||(Ne.x>=S?Ne=new Kt(S,Ne.y+(S-Ne.x)/(Me.x-Ne.x)*(Me.y-Ne.y))._round():Me.x>=S&&(Me=new Kt(S,Ne.y+(S-Ne.x)/(Me.x-Ne.x)*(Me.y-Ne.y))._round()),Ne.y>=T&&Me.y>=T||(Ne.y>=T?Ne=new Kt(Ne.x+(T-Ne.y)/(Me.y-Ne.y)*(Me.x-Ne.x),T)._round():Me.y>=T&&(Me=new Kt(Ne.x+(T-Ne.y)/(Me.y-Ne.y)*(Me.x-Ne.x),T)._round()),X&&Ne.equals(X.at(-1))||(X=[Ne],F.push(X),D&&D.push({progress:{min:Ve+LJe(Je,lt,Ne)*ze,max:1},parentIndex:q,prevPoint:Je,nextPoint:lt})),X.push(Me),D&&(D.at(-1).progress.max=Ve+LJe(Je,lt,Me)*ze,D.at(-1).nextPoint=lt)))))}if(D&&pe>0)for(let xe=ce;xeX.t-ce.t);let F=0,q=0,K=[];for(S.push(K);F!==w.length;){if(q===D.length){for(;F!==w.length;)K.length!==0&&K.at(-1).equals(w[F])||K.push(w[F]),F++;break}D[q].t<=F?(K.length!==0&&K.at(-1).equals(D[q].point)||K.push(D[q].point),Math.trunc(D[q].t),q++):(K.length!==0&&K.at(-1).equals(w[F])||K.push(w[F]),F++)}}function LJe(w,f,b){return w.x!==f.x?(b.x-w.x)/(f.x-w.x):w.y!==f.y?(b.y-w.y)/(f.y-w.y):0}function RJe(w,{width:f,height:b},S,T){if(T){if(T instanceof Uint8ClampedArray)T=new Uint8Array(T.buffer);else if(T.length!==f*b*S)throw new RangeError("mismatched image size")}else T=new Uint8Array(f*b*S);return w.width=f,w.height=b,w.data=T,w}function DJe(w,f,b){const{width:S,height:T}=f;S===w.width&&T===w.height||(EMe(w,f,{x:0,y:0},{x:0,y:0},{width:Math.min(w.width,S),height:Math.min(w.height,T)},b,null),w.width=S,w.height=T,w.data=f.data)}function EMe(w,f,b,S,T,D,F,q){if(T.width===0||T.height===0)return f;if(T.width>w.width||T.height>w.height||b.x>w.width-T.width||b.y>w.height-T.height)throw new RangeError("out of range source coordinates for image copy");if(T.width>f.width||T.height>f.height||S.x>f.width-T.width||S.y>f.height-T.height)throw new RangeError("out of range destination coordinates for image copy");const K=w.data,X=f.data,ce=D===4&&q;for(let pe=0;pe1&&(K=f[++q]);const ce=Math.abs(X-K.left),pe=Math.abs(X-K.right),xe=Math.min(ce,pe);let Ne;const Me=D/S*(T+1);if(K.isDash){const ze=T-Math.abs(Me);Ne=Math.sqrt(xe*xe+ze*ze)}else Ne=T-Math.sqrt(xe*xe+Me*Me);this.image.data[F+X]=Math.max(0,Math.min(255,Ne+128))}}}addRegularDash(f,b){for(let K=f.length-1;K>=0;--K){const X=f[K],ce=f[K+1];X.zeroLength?f.splice(K,1):ce&&ce.isDash===X.isDash&&(ce.left=X.left,f.splice(K,1))}const S=f[0],T=f.at(-1);S.isDash===T.isDash&&(S.left=T.left-this.width,T.right=S.right+this.width);const D=this.width*this.nextRow;let F=0,q=f[F];for(let K=0;K1&&(q=f[++F]);const X=Math.abs(K-q.left),ce=Math.abs(K-q.right),pe=Math.min(X,ce);this.image.data[D+K]=Math.max(0,Math.min(255,(q.isDash?pe:-pe)+b+128))}}addDash(f,b){const S=this.getKey(f,b);if(this.positions[S])return this.positions[S];const T=b==="round",D=T?7:0,F=2*D+1;if(this.nextRow+F>this.height)return oi("LineAtlas out of space"),null;f.length===0&&f.push(1);let q=0;for(let Ne=0;Ne=128&&X++}const ce=Math.round(X/this.width*4095);this.nextRow+=F;const pe=Math.floor(q),xe={tl:[K,D|ce<<4],br:[pe,Math.round(65535*(q-pe))]};return this.positions[S]=xe,xe}}Vr(FJe,"LineAtlas");const L4="3d_elevation_id",zJe="level",aYt=bA.types,iYt=Math.cos(Math.PI/180*37.5),oYt=Math.cos(Math.PI/180*5);class TMe{constructor(f){this.evaluationGlobals={zoom:0,lineProgress:void 0},this.elevationType="none",this.isSeaLevelReference=!1,this.showElevationIdDebug=!1,this.terrainEnabled=!1,this.zoom=f.zoom,this.evaluationGlobals.zoom=this.zoom,this.overscaling=f.overscaling,this.pixelRatio=f.pixelRatio,this.layers=f.layers,this.layerIds=this.layers.map(b=>b.fqid),this.index=f.index,this.projection=f.projection,this.hasPattern=!1,this.hasCrossSlope=!1,this.patternFeatures=[],this.lineClipsArray=[],this.gradients={},this.borderGradients={},this.layers.forEach(b=>{this.gradients[b.id]={},this.borderGradients[b.id]={}}),this.layoutVertexArray=new qa,this.layoutVertexArray2=new Nr,this.patternVertexArray=new Nr,this.indexArray=new Va,this.programConfigurations=new aN(f.layers,{zoom:f.zoom,lut:f.lut}),this.segments=new lc,this.sourceLayerName=f.sourceLayerName||"",this.maxLineLength=0,this.zOffsetVertexArray=new ci,this.elevationIdColVertexArray=new Nr,this.elevationGroundScaleVertexArray=new Hn,this.stateDependentLayerIds=this.layers.filter(b=>b.isStateDependent()).map(b=>b.id),this.tessellationStep=f.tessellationStep?f.tessellationStep:128,this.worldview=f.worldview,this.hasAppearances=null}updateFootprints(f,b){}updateAppearances(f,b,S,T){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(f,b,S,T){this.showElevationIdDebug=b.showElevationIdDebug,this.terrainEnabled=b.terrainEnabled,this.hasPattern=sH("line",this.layers,this.pixelRatio,b);const D=this.layers[0].layout.get("line-sort-key");this.tileToMeter=mt(S);const F=this.layers[0].layout.get("line-elevation-reference");if(F==="hd-road-markup")this.elevationType="road";else{const xe=this.layers[0].layout.get("line-z-offset"),Ne=xe.isConstant()&&!xe.constantOr(0);this.elevationType=F!=="sea"&&F!=="ground"&&Ne?"none":"offset",this.elevationType==="offset"&&F==="none"&&oi(`line-elevation-reference: ground is used for the layer ${this.layerIds[0]} because non-zero line-z-offset value was found.`),this.isSeaLevelReference=F==="sea"}const q=this.layers[0].layout.get("line-cross-slope");this.hasCrossSlope=this.elevationType==="offset"&&q!==void 0;const K=[];for(const{feature:xe,id:Ne,index:Me,sourceLayerIndex:ze}of f){const Ve=this.layers[0]._featureFilter.needGeometry,Je=Js(xe,Ve);if(!this.layers[0]._featureFilter.filter(new tr(this.zoom,{worldview:this.worldview,activeFloors:b.activeFloors}),Je,S))continue;const lt=D?D.evaluate(Je,{},S):void 0,ht={id:Ne,properties:xe.properties,type:xe.type,sourceLayerIndex:ze,index:Me,geometry:Ve?Je.geometry:Ms(xe,S,T),patterns:{},sortKey:lt};K.push(ht)}D&&K.sort((xe,Ne)=>xe.sortKey-Ne.sortKey);const{lineAtlas:X,featureIndex:ce}=b,pe=this.addConstantDashes(X);for(const xe of K){const{geometry:Ne,index:Me,sourceLayerIndex:ze}=xe;if(pe&&this.addFeatureDashes(xe,X),this.hasPattern){const Ve=nH("line",this.layers,xe,this.zoom,this.pixelRatio,b);this.patternFeatures.push(Ve)}else this.addFeature(xe,Ne,Me,S,X.positions,b.availableImages,b.brightness,b.elevationFeatures,b.elevationParams,b.crossSourceElevationEnabled);ce.insert(f[Me].feature,Ne,Me,ze,this.index)}!this.hasPattern&&this.hdExt&&this.hdExt.buildFrcSegments(this),this.hdExt&&this.hdExt.endPopulate()}addConstantDashes(f){let b=!1;for(const S of this.layers){const T=S.paint.get("line-dasharray").value,D=S.layout.get("line-cap").value;if(T.kind!=="constant"||D.kind!=="constant")b=!0;else{const F=D.value,q=T.value;if(!q)continue;f.addDash(q,F)}}return b}addFeatureDashes(f,b){const S=this.zoom;for(const T of this.layers){const D=T.paint.get("line-dasharray").value,F=T.layout.get("line-cap").value;if(D.kind==="constant"&&F.kind==="constant")continue;let q,K;if(D.kind==="constant"){if(q=D.value,!q)continue}else q=D.evaluate({zoom:S},f);K=F.kind==="constant"?F.value:F.evaluate({zoom:S},f),b.addDash(q,K),f.patterns[T.id]=[b.getKey(q,K)]}}update(f,b,S,T,D,F,q,K,X){this.programConfigurations.updatePaintArrays(f,b,D,S,T,F,q,X)}updateExpressions(f){this.programConfigurations.updateExpressions(f)}addFeatures(f,b,S,T,D,F){for(const q of this.patternFeatures)this.addFeature(q,q.geometry,q.index,b,S,T,F,f.elevationFeatures,f.elevationParams,f.crossSourceElevationEnabled);this.hdExt&&(this.hdExt.buildFrcSegments(this),this.hdExt.endPopulate())}isEmpty(){return this.layoutVertexArray.length===0}uploadPending(){return!this.uploaded||this.programConfigurations.needsUpload}upload(f){this.uploaded||(this.layoutVertexArray2.length!==0&&(this.layoutVertexBuffer2=f.createVertexBuffer(this.layoutVertexArray2,KKt)),this.patternVertexArray.length!==0&&(this.patternVertexBuffer=f.createVertexBuffer(this.patternVertexArray,ZKt)),!this.zOffsetVertexBuffer&&this.zOffsetVertexArray.length>0&&(this.zOffsetVertexBuffer=f.createVertexBuffer(this.zOffsetVertexArray,qKt.members,!0)),!this.elevationIdColVertexBuffer&&this.elevationIdColVertexArray.length>0&&(this.elevationIdColVertexBuffer=f.createVertexBuffer(this.elevationIdColVertexArray,VKt.members,!0)),!this.elevationGroundScaleVertexBuffer&&this.elevationGroundScaleVertexArray.length>0&&(this.elevationGroundScaleVertexBuffer=f.createVertexBuffer(this.elevationGroundScaleVertexArray,HKt.members,!0)),this.layoutVertexBuffer=f.createVertexBuffer(this.layoutVertexArray,GKt),this.indexBuffer=f.createIndexBuffer(this.indexArray)),this.programConfigurations.upload(f),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(f,b){let S,T;if(b&&b>0?(S=`mapbox_clip_start_${b}`,T=`mapbox_clip_end_${b}`):(S="mapbox_clip_start",T="mapbox_clip_end"),f.properties&&Object.hasOwn(f.properties,S)&&Object.hasOwn(f.properties,T))return{start:+f.properties[S],end:+f.properties[T]}}addFeature(f,b,S,T,D,F,q,K,X,ce){const pe=this.layers[0].layout,xe=this.hdExt?this.hdExt.trackFeatureFrc(f.properties):null,Ne=this.indexArray.length,Me=pe.get("line-join").evaluate(f,{}),ze=pe.get("line-cap").evaluate(f,{}),Ve=pe.get("line-miter-limit"),Je=pe.get("line-round-limit");this.lineClips=this.lineFeatureClips(f),this.lineFeature=f;const lt=!(!f.properties||!Object.hasOwn(f.properties,"mapbox_line_metrics"))&&f.properties.mapbox_line_metrics;this.zOffsetValue=pe.get("line-z-offset").value;const ht=this.layers[0].paint,ct=ht.get("line-width").value;ct.kind!=="constant"&&ct.isLineProgressConstant===!1&&(this.variableWidthValue=ct);const xt=ht.get("line-emissive-strength").value;if(xt.kind!=="constant"&&xt.isLineProgressConstant===!1&&(this.variableEmissiveStrengthValue=xt),this.isSeaLevelReference){const kt=pe.get("line-elevation-ground-scale").value;kt.kind==="constant"&&kt.value===0||(this.elevationGroundScaleValue=kt)}if(this.hdExt==null||!this.hdExt.handleFeature(f,b,T,K,X,!!ce,Me,ze,Ve,Je,this))for(let kt=0;kt0?kt:null);this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,f,S,D,F,T,q,void 0,this.worldview),this.hdExt&&this.hdExt.recordFeatureRange(this,Ne,this.indexArray.length,xe)}fillNonElevatedRoadSegment(f){for(let b=Math.max(f,this.zOffsetVertexArray.length);b0,xe=K&&K.progress.max<1;if(this.lineClips){let Lt={min:this.lineClips.start,max:this.lineClips.end},Zt=1;if(K){const Fs=this.lineClips.end-this.lineClips.start;Lt=function(on,sn,hn){return{min:Wx(on.min,sn,hn),max:Wx(on.max,sn,hn)}}(K.progress,{min:0,max:1},Lt),Fs>0&&(Zt=(Lt.max-Lt.min)/Fs)}const Qt=+b.properties.mapbox_clip_feature_len,Cs=+b.properties.mapbox_clip_seg_len;if(Number.isNaN(Qt)||Number.isNaN(Cs)){for(let on=0;on=2&&f[Me-1].equals(f[Me-2]);)Me--;let ze=0;for(;ze0,qs=this.overscaling<=16?122880/(512*this.overscaling):0;if(Zt&&Qt==="round"){if(snF&&(Qt="bevel"),Qt==="bevel"&&(sn>2&&(Qt="flipbevel"),sn2*qs){const Nn=Je.sub(Je.sub(lt)._mult(qs/en)._round());this.updateDistance(lt,Nn),this.addCurrentVertex(Nn,ct,0,0,Ve,Ct),lt=Nn}this.updateDistance(lt,Je),Fs._mult(sn),this.addCurrentVertex(Je,Fs,0,0,Ve,Ct);const wn=Je.dist(ht);if(wn>2*qs){const Nn=Je.add(ht.sub(Je)._mult(qs/wn)._round());this.updateDistance(Je,Nn),this.addCurrentVertex(Nn,xt,0,0,Ve,Ct),Je=Nn}}else Fs._mult(sn),this.addCurrentVertex(Je,Fs,0,0,Ve,Ct);else if(Qt==="flipbevel"){if(sn>100)Fs=xt.mult(-1);else{const en=sn*ct.add(xt).mag()/ct.sub(xt).mag();Fs._perp()._mult(en*(ws?-1:1))}this.addCurrentVertex(Je,Fs,0,0,Ve,Ct),this.addCurrentVertex(Je,Fs.mult(-1),0,0,Ve,Ct)}else if(Qt==="bevel"||Qt==="fakeround"){const en=Je.dist(lt);let wn=1;if(this.elevationType==="offset"&&Qt==="bevel"&&this.currentLineJoinType!=="round"&&!this.patternJoinNone&&Ct!=null&<&&ht){const sr=4*qs;en1){this.lineSoFar=f.w;const ze=(b.x-f.x)/pe,Ve=(b.y-f.y)/pe,Je=(b.z-f.z)/pe,lt=(b.w-f.w)/pe,ht=b.x-f.x,ct=b.y-f.y,xt=Math.sqrt(ht*ht+ct*ct);if(xt===0)return;const kt=-ct/xt,es=ht/xt,Ct=kt,Lt=es,Zt=-kt,Qt=-es;for(let Cs=1;Cs=0&&this.e2>=0&&(this.indexArray.emplaceBack(this.e1,this.e2,ce),K.primitiveLength++),F?this.e2=ce:this.e1=ce,X!=null&&(this.zOffsetVertexArray.emplaceBack(X.zOffset,X.variableWidth,X.variableWidth,X.variableEmissiveStrength),this.showElevationIdDebug&&this.elevationIdColVertexArray.emplaceBack(0,0,0)),this.elevationGroundScaleValue){const pe=X?X.elevationGroundScale:this.evaluateElevationGroundScale();this.elevationGroundScaleVertexArray.emplaceBack(pe)}}updateScaledDistance(){this.lineClips?(this.scaledDistance=this.distance/this.totalDistance,this.lineSoFar=this.totalFeatureLength*this.lineClips.start+this.distance):this.lineSoFar=this.distance}updateDistance(f,b){this.prevDistance=this.distance,this.distance+=f.dist(b),this.updateScaledDistance()}}function MMe(w,f,b){return w.xb||w.yb}Vr(TMe,"LineBucket",{omit:["layers","patternFeatures","currentVertex","currentVertexIsOutside"]});const lYt=an([{name:"a_pos",components:2,type:"Int16"}],4),cYt=an([{name:"a_circle_z_offset",components:1,type:"Float32"}],4),dYt=an([{name:"a_pos_3",components:3,type:"Int16"},{name:"a_pos_normal_3",components:3,type:"Int16"}]);class Wte{constructor(f){this.zoom=f.zoom,this.overscaling=f.overscaling,this.layers=f.layers,this.layerIds=this.layers.map(b=>b.fqid),this.index=f.index,this.hasPattern=!1,this.projection=f.projection,this.layoutVertexArray=new Sn,this.indexArray=new Va,this.segments=new lc,this.programConfigurations=new aN(f.layers,{zoom:f.zoom,lut:f.lut}),this.stateDependentLayerIds=this.layers.filter(b=>b.isStateDependent()).map(b=>b.id),this.worldview=f.worldview,this.hasAppearances=null}updateFootprints(f,b){}updateAppearances(f,b,S,T){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(f,b,S,T){const D=this.layers[0],F=[];let q=null;D.type==="circle"&&(q=D.layout.get("circle-sort-key"));for(const{feature:X,id:ce,index:pe,sourceLayerIndex:xe}of f){const Ne=this.layers[0]._featureFilter.needGeometry,Me=Js(X,Ne);if(!this.layers[0]._featureFilter.filter(new tr(this.zoom,{worldview:this.worldview,activeFloors:b.activeFloors}),Me,S))continue;const ze=q?q.evaluate(Me,{},S):void 0,Ve={id:ce,properties:X.properties,type:X.type,sourceLayerIndex:xe,index:pe,geometry:Ne?Me.geometry:Ms(X,S,T),patterns:{},sortKey:ze};F.push(Ve)}q&&F.sort((X,ce)=>X.sortKey-ce.sortKey);let K=null;T.projection.name==="globe"&&(this.globeExtVertexArray=new Fa,K=T.projection);for(const X of F){const{geometry:ce,index:pe,sourceLayerIndex:xe}=X,Ne=f[pe].feature;this.addFeature(X,ce,pe,b.availableImages,S,K,b.brightness,b.elevationFeatures),b.featureIndex.insert(Ne,ce,pe,xe,this.index)}this.hdExt&&this.hdExt.finalize()}update(f,b,S,T,D,F,q){this.programConfigurations.updatePaintArrays(f,b,D,S,T,F,q,this.worldview)}updateExpressions(f){this.programConfigurations.updateExpressions(f)}isEmpty(){return this.layoutVertexArray.length===0}uploadPending(){return!this.uploaded||this.programConfigurations.needsUpload}upload(f){this.uploaded||(this.layoutVertexBuffer=f.createVertexBuffer(this.layoutVertexArray,lYt.members),this.indexBuffer=f.createIndexBuffer(this.indexArray),this.globeExtVertexArray&&(this.globeExtVertexBuffer=f.createVertexBuffer(this.globeExtVertexArray,dYt.members)),this.hdExt&&this.hdExt.upload(f)),this.programConfigurations.upload(f),this.uploaded=!0}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy(),this.globeExtVertexBuffer&&this.globeExtVertexBuffer.destroy(),this.hdExt&&this.hdExt.destroy())}addFeature(f,b,S,T,D,F,q,K){this.hdExt&&this.hdExt.beginFeature(f,K,D);for(const X of b)for(const ce of X){const pe=ce.x,xe=ce.y;if(pe<0||pe>=br||xe<0||xe>=br)continue;if(F){const ze=F.projectTilePoint(pe,xe,D),Ve=F.upVector(D,pe,xe);this.addGlobeExtVertex(ze,Ve),this.addGlobeExtVertex(ze,Ve),this.addGlobeExtVertex(ze,Ve),this.addGlobeExtVertex(ze,Ve)}const Ne=this.segments.prepareSegment(4,this.layoutVertexArray,this.indexArray,f.sortKey),Me=Ne.vertexLength;this.addCircleVertex(pe,xe,-1,-1),this.addCircleVertex(pe,xe,1,-1),this.addCircleVertex(pe,xe,1,1),this.addCircleVertex(pe,xe,-1,1),this.hdExt&&this.hdExt.writeVertexQuad(pe,xe),this.indexArray.emplaceBack(Me,Me+1,Me+2),this.indexArray.emplaceBack(Me,Me+2,Me+3),Ne.vertexLength+=4,Ne.primitiveLength+=2}this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,f,S,{},T,D,q,void 0,this.worldview)}addCircleVertex(f,b,S,T){this.layoutVertexArray.emplaceBack(2*f+(S+1)/2,2*b+(T+1)/2)}addGlobeExtVertex(f,b){this.globeExtVertexArray.emplaceBack(f.x,f.y,f.z,b[0]*16384,b[1]*16384,b[2]*16384)}}Vr(Wte,"CircleBucket",{omit:["layers"]});const uYt=an([{name:"a_pos_offset",components:4,type:"Int16"},{name:"a_tex_size",components:4,type:"Uint16"},{name:"a_pixeloffset",components:4,type:"Int16"}],4),hYt=an([{name:"a_globe_anchor",components:3,type:"Int16"},{name:"a_globe_normal",components:3,type:"Float32"}],4),mYt=an([{name:"a_projected_pos",components:4,type:"Float32"}],4);an([{name:"a_fade_opacity",components:1,type:"Uint32"}],4);const fYt=an([{name:"a_auto_z_offset",components:1,type:"Float32"}],4),pYt=an([{name:"a_feature_index",components:1,type:"Float32"}],4),gYt=an([{name:"a_x_axis",components:3,type:"Float32"},{name:"a_y_axis",components:3,type:"Float32"}]),xYt=an([{name:"a_texb",components:2,type:"Uint16"}]),yYt=an([{name:"a_placed",components:2,type:"Uint8"},{name:"a_shift",components:2,type:"Float32"},{name:"a_elevation_from_sea",components:2,type:"Float32"}]),vYt=an([{name:"a_size_scale",components:1,type:"Float32"},{name:"a_padding",components:2,type:"Float32"},{name:"a_auto_z_offset",components:1,type:"Float32"}]);an([{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 BJe=an([{name:"a_pos",components:3,type:"Int16"},{name:"a_anchor_pos",components:2,type:"Int16"},{name:"a_extrude",components:2,type:"Int16"}],4),bYt=an([{name:"a_pos_2f",components:2,type:"Float32"},{name:"a_radius",components:1,type:"Float32"},{name:"a_flags",components:2,type:"Int16"}],4);an([{name:"triangle",components:3,type:"Uint16"}]),an([{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"}]),an([{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"}]),an([{type:"Float32",name:"offsetX"}]),an([{type:"Int16",name:"x"},{type:"Int16",name:"y"}]);const $Je=new Float32Array(1),_Yt=new Uint32Array($Je.buffer);function Kte(w){return $Je[0]=w,_Yt[0]}const f7=class I9{static getBlockIndices(f){let b=I9._blockIndicesTemplate;if(!b){b=I9._blockIndicesTemplate=new Uint32Array(f);for(let S=0;Sf.maxUniformBlockSize)throw new Error(`UBO size ${this.totalBytes} exceeds device limit ${f.maxUniformBlockSize}`);if(this.headerBuffer=b.createBuffer(),!this.headerBuffer)throw new Error("Failed to create header UBO buffer");if(b.bindBuffer(b.UNIFORM_BUFFER,this.headerBuffer),b.bufferData(b.UNIFORM_BUFFER,I9.HEADER_BYTES,b.DYNAMIC_DRAW),this.propertiesBuffer=b.createBuffer(),!this.propertiesBuffer)throw new Error("Failed to create properties UBO buffer");if(b.bindBuffer(b.UNIFORM_BUFFER,this.propertiesBuffer),b.bufferData(b.UNIFORM_BUFFER,this.totalBytes,b.DYNAMIC_DRAW),this.blockIndicesBuffer=b.createBuffer(),!this.blockIndicesBuffer)throw new Error("Failed to create block-indices UBO buffer");b.bindBuffer(b.UNIFORM_BUFFER,this.blockIndicesBuffer),b.bufferData(b.UNIFORM_BUFFER,this.totalBytes,b.DYNAMIC_DRAW),b.bindBuffer(b.UNIFORM_BUFFER,null)}markHeaderDirty(){this._headerDirty=!0}writeDataDrivenBlock(f,b){const S=this.headerData,T=4*S[2];if(T===0)return;const D=b*T;if(D+T>this.propertiesData.length)throw new Error(`UBO write out of bounds: feature index ${b} exceeds propertiesData capacity`);const F=S[0];for(let K=0;K<9;K++)F&1<this._propsDirtyMax&&(this._propsDirtyMax=q)}rightSizeForTransfer(){const f=this._propsDirtyMax===-1?0:this._propsDirtyMax;f>>b&1?8:4);const D=I9.EVAL_FLAT_OFFSETS[b];this.propertiesData.set(S.subarray(D,D+T),f)}upload(f){this.context||(this.context=f);const b=f.gl;this.headerBuffer&&this.propertiesBuffer&&this.blockIndicesBuffer||this._initBuffers(f);let S=!1;if(this._headerDirty&&(b.bindBuffer(b.UNIFORM_BUFFER,this.headerBuffer),b.bufferSubData(b.UNIFORM_BUFFER,0,this.headerData),this._headerDirty=!1,S=!0),this._propsDirtyMin!==-1){const T=this._propsDirtyMin,D=this._propsDirtyMax;b.bindBuffer(b.UNIFORM_BUFFER,this.propertiesBuffer),b.bufferSubData(b.UNIFORM_BUFFER,4*T,this.propertiesData,T,D-T),this._propsDirtyMin=-1,this._propsDirtyMax=-1,S=!0}this._blockIndicesDirty&&(b.bindBuffer(b.UNIFORM_BUFFER,this.blockIndicesBuffer),b.bufferSubData(b.UNIFORM_BUFFER,0,I9.getBlockIndices(this.propsDwords)),this._blockIndicesDirty=!1,S=!0),S&&b.bindBuffer(b.UNIFORM_BUFFER,null)}bind(f,b){const S=f.gl,T=(F,q,K)=>{if(!q)return;const X=S.getUniformBlockIndex(b,F);X!==S.INVALID_INDEX&&(S.uniformBlockBinding(b,X,K),S.bindBufferBase(S.UNIFORM_BUFFER,K,q))},D=3*this.batchIndex;T("SymbolPaintPropertiesHeaderUniform",this.headerBuffer,D),T("SymbolPaintPropertiesUniform",this.propertiesBuffer,D+1),T("SymbolPaintPropertiesIndexUniform",this.blockIndicesBuffer,D+2)}destroy(){if(this.context){const f=this.context.gl;this.headerBuffer&&(f.deleteBuffer(this.headerBuffer),this.headerBuffer=null),this.propertiesBuffer&&(f.deleteBuffer(this.propertiesBuffer),this.propertiesBuffer=null),this.blockIndicesBuffer&&(f.deleteBuffer(this.blockIndicesBuffer),this.blockIndicesBuffer=null)}}};f7.HEADER_DWORDS=16,f7.HEADER_BYTES=64,f7.EVAL_FLAT_OFFSETS=[0,8,16,20,24,28,32,36,40],f7.EVAL_FLAT_TOTAL=48,f7._blockIndicesTemplate=null;let oH=f7;function UJe(w,f,b,S,T,D,F,q){return!!w&&(w.kind==="constant"?w.value==="none":w.evaluate({zoom:0,brightness:D,worldview:q},f,b,T,S,F)==="none")}function qJe(w){if(!(w instanceof wc))return!1;const f=w.value;return(f.kind==="source"||f.kind==="composite")&&f.isStateDependent}Vr(oH,"SymbolPropertiesUBO",{omit:["headerBuffer","propertiesBuffer","blockIndicesBuffer"]});const lH=["icon","text"].map(w=>[`${w}-color`,`${w}-halo-color`,`${w}-opacity`,`${w}-halo-width`,`${w}-halo-blur`,`${w}-emissive-strength`,`${w}-occlusion-opacity`,"symbol-z-offset",`${w}-translate`]),Ah=new Float32Array(oH.EVAL_FLAT_TOTAL),wYt=[0,0],VJe=new WeakMap;class PMe{constructor(f,b,S,T,D="",F,q){this.layer=f,this.zoom=b,this.lut=S,this.isText=T,this.worldview=D,this.maxUniformBufferBindings=F||24,this.uboSizeDwords=q||4096,this.allFeatureVtIndices=[],this.allFeatureIds=[],this.allFormattedSections=[],this.featureVertexRangesFromId=null,this.featureVertexRangesFromVtIndex=null,this.ubos=[],this.featureCount=0,this.cachedConstantUniforms=null,this.cachedConstantRenderZoom=null,this.cachedConstantBrightness=void 0,this.cachedConstantPaint=null,this.activeAppearanceByVtIndex=null,this.zoomDependency=new Uint8Array(9),this.sharedZoomRanges=new Float32Array(18),this._zoomRangeScratch=new Float32Array(2),this._floorZoom=Math.floor(this.zoom),this.header=new Uint32Array(oH.HEADER_DWORDS),this.updateHeader(),this.isAllConstant=this.header[0]===0;const K=4*this.header[2];this.maxFeaturesPerBatch=K===0?Number.MAX_SAFE_INTEGER:Math.floor(this.uboSizeDwords/K)}updateHeader(){const f=this.layer.paint;let b=0,S=0,T=0,D=0,F=!0;const q=this._floorZoom,K=lH[+this.isText];for(let X=0;X<9;X++){const ce=K[X],pe=X<2,xe=f.get(ce),Ne=!(!xe||typeof xe.isConstant!="function"||xe.isConstant()),Me=this._appearancesHavePaintProperties(ce);if(!Ne&&!Me){const xt=this._layerUnevaluated(ce);xt&&xt.expression&&xt.expression.kind==="camera"&&(T|=1<{if(!X)return;this._computeZoomRange(X,b,this._zoomRangeScratch,0);const ce=this._zoomRangeScratch[0],pe=this._zoomRangeScratch[1];S?ce===F&&pe===q||(T=!0):(S=!0,F=ce,q=pe,D=X)};K(this._zoomExprOf(this._layerUnevaluated(f)));for(const X of this.layer.getAppearances()||[])X.hasPaintProperty(f)&&K(this._zoomExprOf(X.getUnevaluatedPaintProperty(f)));return{hasZoom:S,differs:T,representative:D}}evaluateAllProperties(f,b,S,T,D,F,q){const K={brightness:D,worldview:this.worldview},X={feature:f,featureState:b,canonical:S,availableImages:T,params:new tr(this.zoom,K),paramsNext:new tr(this.zoom+1,K),formattedSection:F,activeAppearance:q},ce=lH[+this.isText];for(let pe=0;pe<9;pe++){const xe=ce[pe],Ne=pe<2,Me=pe===8,ze=this.zoomDependency[pe],Ve=ze!==0,Je=ze===2,lt=oH.EVAL_FLAT_OFFSETS[pe],ht=lt+(Ne||Me?4:2);Ne?this._evaluateColorValue(xe,pe,Ve,Je,ht,X,lt):Me?this._evaluateTranslateValue(xe,pe,Ve,Je,ht,X,lt):this._evaluateFloatValue(xe,pe,Ve,Je,ht,X,lt)}return Ah}_resolveProp(f,b,S=!1,T){const D=this.layer.paint,F=D.get(f),q=f,K=!(!b||!b.hasPaintProperty(q)),X=K?T&&F&&F.property.overrides&&F.property.overrides.hasOverride(T)?F:b.paintProperties.get(q):D.get(f);if(S||!X||typeof X.isConstant!="function"||!X.isConstant())return X;const ce=K?b.getUnevaluatedPaintProperty(q):this._layerUnevaluated(f);return this._unbakeCamera(X,ce)}_unbakeCamera(f,b){const S=b&&b.expression;if(!S||S.kind!=="camera")return f;let T=VJe.get(b);return T||(T=new wc(f.property,S,f.parameters,f.iconImageUseTheme),VJe.set(b,T)),T}_layerUnevaluated(f){const b=this.layer._transitionablePaint._values[f];return b&&b.value}_zoomExprOf(f){const b=f&&f.expression;return!b||b.kind!=="composite"&&b.kind!=="camera"?null:b}_evalAt(f,b,S){return f.property.evaluate(f.value,b,S.feature,S.featureState,S.canonical,S.availableImages,f.iconImageUseTheme,S.formattedSection)}_evaluateColorValue(f,b,S,T,D,F,q){const K=this._resolveProp(f,F.activeAppearance,!1,F.formattedSection);if(this._writePropertyZoomRange(b,S,T,K,D),!K)return Ah[q]=0,Ah[q+1]=0,Ah[q+2]=0,void(Ah[q+3]=1);const X=this._resolveProp(`${f}-use-theme`,F.activeAppearance,!0),ce=UJe(X&&typeof X!="string"?X.value:void 0,F.feature,F.featureState,F.availableImages,F.canonical,F.params.brightness,F.formattedSection,this.worldview)?null:this.lut,pe=(K.isConstant()?K.constantOr(Mi.transparent):this._evalAt(K,F.params,F)||Mi.transparent).toNonPremultipliedRenderColor(ce);if(Ah[q]=Yk(255*pe.r,255*pe.g),Ah[q+1]=Yk(255*pe.b,255*pe.a),S){const xe=(this._evalAt(K,F.paramsNext,F)||Mi.transparent).toNonPremultipliedRenderColor(ce);Ah[q+2]=Yk(255*xe.r,255*xe.g),Ah[q+3]=Yk(255*xe.b,255*xe.a)}else Ah[q+2]=Ah[q],Ah[q+3]=Ah[q+1]}_computeZoomRange(f,b,S,T){let D=0,F=1;const q=!f||f.kind!=="composite"&&f.kind!=="camera"?null:f.zoomStops;if(q&&q.length>0)if(f.interpolationType==null){D=F=1;for(const K of q)if(K>b&&Kb&&q[0]b.hasPaintProperty(f))}hasStateDependentPaint(f){const b=f.paint,S=lH[+this.isText];for(const T of S)if(qJe(b.get(T)))return!0;for(const T of f.getAppearances()||[])for(const D of S){const F=D;if(T.hasPaintProperty(F)&&qJe(T.paintProperties.get(F)))return!0}return!1}hasPerFeatureTranslate(){return!!(256&this.header[0])}getCurrentBatchIndex(){return this.maxFeaturesPerBatch===0?0:Math.floor(this.featureCount/this.maxFeaturesPerBatch)}_writeFeatureBlock(f,b){const S=this.isAllConstant?0:f;let T=Math.floor(S/this.maxFeaturesPerBatch),D=S%this.maxFeaturesPerBatch;this._batchExceedsDeviceLimit(T)&&(T=0,D=0);const F=this.ubos[T];return!!F&&(F.writeDataDrivenBlock(b,D),!0)}_batchExceedsDeviceLimit(f){return 3*f+2>=this.maxUniformBufferBindings}_reevaluateAt(f,b,S,T,D,F){if(!b)return;const q=this.allFeatureVtIndices[f],K=b.feature(q);if(!K)return;const X=this.allFeatureIds[f],ce=X!=null&&D[X]||{},pe={type:K.type,id:X,properties:K.properties||{},geometry:[]},xe=this.activeAppearanceByVtIndex?this.activeAppearanceByVtIndex.get(q):void 0,Ne=this.evaluateAllProperties(pe,ce,S,T,F,(this.allFormattedSections?this.allFormattedSections[f]:void 0)||void 0,xe);this._writeFeatureBlock(f,Ne)}_ensureRangeMaps(){if(!this.featureVertexRangesFromId){this.featureVertexRangesFromId=new Map,this.featureVertexRangesFromVtIndex=new Map;for(let f=0;f{const xe=q[pe],Ne=T.get(xe);if(!Ne)return[0,0,0,1];const Me=T.get(`${xe}-use-theme`),ze=UJe(Me&&typeof Me!="string"?Me.value:void 0,F,{},[],void 0,b,void 0,this.worldview)?null:this.lut;return(this.cameraMask&1<{const Ne=T.get(q[pe]);return Ne?this.cameraMask&1<{S.text=function(T,D,F){const q=D.layout.get("text-transform").evaluate(F,{});return q==="uppercase"?T=T.toLocaleUpperCase():q==="lowercase"&&(T=T.toLocaleLowerCase()),vp.applyArabicShaping&&(T=vp.applyArabicShaping(T)),T}(S.text,f,b)}),w}const R4={horizontal:1,vertical:2,horizontalOnly:3};function HJe(w){let f=.5,b=.5;switch(w){case"right":case"top-right":case"bottom-right":f=1;break;case"left":case"top-left":case"bottom-left":f=0}switch(w){case"bottom":case"bottom-right":case"bottom-left":b=1;break;case"top":case"top-right":case"top-left":b=0}return{horizontalAlign:f,verticalAlign:b}}function GJe(w,f,b,S){const{horizontalAlign:T,verticalAlign:D}=HJe(S),F=b[0]-w.displaySize[0]*T,q=b[1]-w.displaySize[1]*D;return{imagePrimary:w,imageSecondary:f,top:q,bottom:q+w.displaySize[1],left:F,right:F+w.displaySize[0]}}function WJe(w,f,b,S,T,D){const F=w.imagePrimary;let q;if(F.content){const Ve=F.content,Je=F.pixelRatio||1;q=[Ve[0]/Je,Ve[1]/Je,F.displaySize[0]-Ve[2]/Je,F.displaySize[1]-Ve[3]/Je]}const K=f.left*D,X=f.right*D;let ce,pe,xe,Ne;b==="width"||b==="both"?(Ne=T[0]+K-S[3],pe=T[0]+X+S[1]):(Ne=T[0]+(K+X-F.displaySize[0])/2,pe=Ne+F.displaySize[0]);const Me=f.top*D,ze=f.bottom*D;return b==="height"||b==="both"?(ce=T[1]+Me-S[0],xe=T[1]+ze+S[2]):(ce=T[1]+(Me+ze-F.displaySize[1])/2,xe=ce+F.displaySize[1]),{imagePrimary:F,imageSecondary:void 0,top:ce,right:pe,bottom:xe,left:Ne,collisionPadding:q}}const cH={"!":"︕","#":"#",$:"$","%":"%","&":"&","(":"︵",")":"︶","*":"*","+":"+",",":"︐","-":"︲",".":"・","/":"/",":":"︓",";":"︔","<":"︿","=":"=",">":"﹀","?":"︖","@":"@","[":"﹇","\\":"\","]":"﹈","^":"^",_:"︳","`":"`","{":"︷","|":"―","}":"︸","~":"~","¢":"¢","£":"£","¥":"¥","¦":"¦","¬":"¬","¯":" ̄","–":"︲","—":"︱","‘":"﹃","’":"﹄","“":"﹁","”":"﹂","…":"︙","‧":"・","₩":"₩","、":"︑","。":"︒","〈":"︿","〉":"﹀","《":"︽","》":"︾","「":"﹁","」":"﹂","『":"﹃","』":"﹄","【":"︻","】":"︼","〔":"︹","〕":"︺","〖":"︗","〗":"︘","!":"︕","(":"︵",")":"︶",",":"︐","-":"︲",".":"・",":":"︓",";":"︔","<":"︿",">":"﹀","?":"︖","[":"﹇","]":"﹈","_":"︳","{":"︷","|":"―","}":"︸","⦅":"︵","⦆":"︶","。":"︒","「":"﹁","」":"﹂"};function NYt(w){return w==="︶"||w==="﹈"||w==="︸"||w==="﹄"||w==="﹂"||w==="︾"||w==="︼"||w==="︺"||w==="︘"||w==="﹀"||w==="︐"||w==="︓"||w==="︔"||w==="`"||w===" ̄"||w==="︑"||w==="︒"}function kYt(w){return w==="︵"||w==="﹇"||w==="︷"||w==="﹃"||w==="﹁"||w==="︽"||w==="︻"||w==="︹"||w==="︗"||w==="︿"}const jA=128;function g7(w,f,b,S){const{expression:T}=f;if(T.kind==="constant")return{kind:"constant",layoutSize:T.evaluate(new tr(w+1,{worldview:b}),void 0,void 0,void 0,S)};if(T.kind==="source")return{kind:"source"};{const{zoomStops:D,interpolationType:F}=T;let q=0;for(;qK*q)}}function YJe(w,f,b,S,T,D,F){return{appearanceTextOffset:x7(w,f,b,S,"text-offset",T,([K,X])=>[K*p7,X*p7]),appearanceTextRotate:x7(w,f,b,S,"text-rotate",D),appearanceTextSize:x7(w,f,b,S,"text-size",F)}}function ZJe(w,f,b,S,T,D,F,q,K,X){if(!w)return;const ce=function(pe,xe,Ne,Me,ze,Ve,Je){if(pe.kind==="camera")return pe.maxSize;if(pe.kind==="composite"){const lt=xe.possiblyEvaluate(new tr(pe.maxZoom,{worldview:Ve}),Ne,Je).evaluate(ze,{},Ne,Je),ht=xe.possiblyEvaluate(new tr(pe.minZoom,{worldview:Ve}),Ne,Je).evaluate(ze,{},Ne,Je);return Math.max(lt,ht)}return xe.possiblyEvaluate(new tr(Me,{worldview:Ve}),Ne,Je).evaluate(ze,{},Ne,Je)}(f,b,S,T,D,K,X);return w.scaleSelf(ce*q*F)}function IMe(w,f,b,S,T,D,F,q,K,X){return{iconPrimary:ZJe(w.getPrimary(),f,b,S,T,D,F,q,K,X),iconSecondary:ZJe(w.getSecondary(),f,b,S,T,D,F,q,K,X)}}function XJe(w,f){return w*f/24}function QJe(w,f,b,S,T,D){let F=null;return f.kind==="source"?(F=[jA*b*S],F[0]>G6&&oi(`${w}: Value for "text-size" or "icon-size" is >= 255. Reduce your "text-size" or "icon-size".`)):f.kind==="composite"&&(F=[jA*T*S,jA*D*S],(F[0]>G6||F[1]>G6)&&oi(`${w}: Value for "text-size" or "icon-size" is >= 255. Reduce your "text-size" or "icon-size".`)),F}const AYt=an([{type:"Float32",name:"a_globe_pos",components:3},{type:"Float32",name:"a_uv",components:2}]),{members:Zte}=AYt,EYt=an([{name:"a_pos_3",components:3,type:"Int16"}]);var LMe=an([{name:"a_pos",type:"Int16",components:2}]);class TYt{constructor(f,b){this.pos=f,this.dir=b}intersectsPlane(f,b,S){const T=Ar(b,this.dir);if(Math.abs(T)<1e-6)return!1;const D=((f[0]-this.pos[0])*b[0]+(f[1]-this.pos[1])*b[1])/T;return S[0]=this.pos[0]+this.dir[0]*D,S[1]=this.pos[1]+this.dir[1]*D,!0}}class Xte{constructor(f,b){this.pos=f,this.dir=b}intersectsPlane(f,b,S){const T=Oe(b,this.dir);if(Math.abs(T)<1e-6)return!1;const D=((f[0]-this.pos[0])*b[0]+(f[1]-this.pos[1])*b[1]+(f[2]-this.pos[2])*b[2])/T;return S[0]=this.pos[0]+this.dir[0]*D,S[1]=this.pos[1]+this.dir[1]*D,S[2]=this.pos[2]+this.dir[2]*D,!0}closestPointOnSphere(f,b,S){if(function(Ne,Me){var ze=Ne[0],Ve=Ne[1],Je=Ne[2],lt=Me[0],ht=Me[1],ct=Me[2];return Math.abs(ze-lt)<=u*Math.max(1,Math.abs(ze),Math.abs(lt))&&Math.abs(Ve-ht)<=u*Math.max(1,Math.abs(Ve),Math.abs(ht))&&Math.abs(Je-ct)<=u*Math.max(1,Math.abs(Je),Math.abs(ct))}(this.pos,f)||b===0)return S[0]=S[1]=S[2]=0,!1;const[T,D,F]=this.dir,q=this.pos[0]-f[0],K=this.pos[1]-f[1],X=this.pos[2]-f[2],ce=T*T+D*D+F*F,pe=2*(q*T+K*D+X*F),xe=pe*pe-4*ce*(q*q+K*K+X*X-b*b);if(xe<0){const Ne=Math.max(-pe/2,0),Me=q+T*Ne,ze=K+D*Ne,Ve=X+F*Ne,Je=Math.hypot(Me,ze,Ve);return S[0]=Me*b/Je,S[1]=ze*b/Je,S[2]=Ve*b/Je,!1}{const Ne=(-pe-Math.sqrt(xe))/(2*ce);if(Ne<0){const Me=Math.hypot(q,K,X);return S[0]=q*b/Me,S[1]=K*b/Me,S[2]=X*b/Me,!1}return S[0]=q+T*Ne,S[1]=K+D*Ne,S[2]=X+F*Ne,!0}}}class RMe{constructor(f,b,S,T,D){this.TL=f,this.TR=b,this.BR=S,this.BL=T,this.horizon=D}static fromInvProjectionMatrix(f,b,S){const T=[-1,1,1],D=[1,1,1],F=[1,-1,1],q=[-1,-1,1],K=tt(T,T,f),X=tt(D,D,f),ce=tt(F,F,f),pe=tt(q,q,f);return new RMe(K,X,ce,pe,b/S)}}function DMe(w,f,b,S){const T=f[0],D=f[1],F=f[2],q=b[0],K=b[1],X=b[2];let ce=1/0,pe=-1/0;for(let xe=0;xepe&&(pe=Me)}return S[0]=ce,S[1]=pe,S}function JJe(w,f){let b=!0;for(let S=0;S=0);if(D===0)return 0;D!==f.length&&(b=!1)}return b?2:1}const MYt=[0,0];function eet(w,f){for(const b of w.projections){const S=DMe(f,w.points[0],b.axis,MYt);if(b.projection[1]S[1])return 0}return 1}function tet(w,f){const b=f[0],S=f[1],T=f[2],D=f[3];for(let F=0;F=0)return!0}return!1}class D4{constructor(f,b){this.points=f||new Array(8).fill([0,0,0]),this.planes=b||new Array(6).fill([0,0,0,0]),this.bounds=jd.fromPoints(this.points),this.projections=[],this.frustumEdges=[wt([],this.points[2],this.points[3]),wt([],this.points[0],this.points[3]),wt([],this.points[4],this.points[0]),wt([],this.points[5],this.points[1]),wt([],this.points[6],this.points[2]),wt([],this.points[7],this.points[3])];for(const S of this.frustumEdges){const T=[0,-S[2],S[1]],D=[S[2],0,-S[0]];this.projections.push({axis:T,projection:DMe(this.points,this.points[0],T,[0,0])}),this.projections.push({axis:D,projection:DMe(this.points,this.points[0],D,[0,0])})}}static fromInvProjectionMatrix(f,b,S,T){const D=Math.pow(2,S),F=[[-1,1,-1,1],[1,1,-1,1],[1,-1,-1,1],[-1,-1,-1,1],[-1,1,1,1],[1,1,1,1],[1,-1,1,1],[-1,-1,1,1]].map(X=>{const ce=dt([],X,f),pe=1/ce[3]/b*D;return(xe=ce)[0]=(Ne=ce)[0]*(Me=[pe,pe,T?1/ce[3]:pe,pe])[0],xe[1]=Ne[1]*Me[1],xe[2]=Ne[2]*Me[2],xe[3]=Ne[3]*Me[3],xe;var xe,Ne,Me}),q=[[0,1,2],[6,5,4],[0,3,7],[2,1,5],[3,2,6],[0,4,5]].map(X=>{const ce=Fe([],Ge([],wt([],F[X[0]],F[X[1]]),wt([],F[X[2]],F[X[1]]))),pe=-Oe(ce,F[X[1]]);return ce.concat(pe)}),K=[];for(let X=0;XMe&&(Me=ht)}let ze=1/0,Ve=-1/0;for(let Je=0;JeVe&&(Ve=ht)}if(Ne>Ve||ze>Me)return 0}return 1}containsPoint(f){for(const b of this.planes){const S=b[3];if(Oe([b[0],b[1],b[2]],f)+S<0)return!1}return!0}}class jd{static fromPoints(f){const b=[1/0,1/0,1/0],S=[-1/0,-1/0,-1/0];for(const T of f)Ie(b,b,T),Ue(S,S,T);return new jd(b,S)}static fromTileIdAndHeight(f,b,S){const T=1<f.max[b]||f.min[b]>this.max[b])return!1;return!0}intersectsAabbXY(f){return!(this.min[0]>f.max[0]||f.min[0]>this.max[0]||this.min[1]>f.max[1]||f.min[1]>this.max[1])}encapsulate(f){for(let b=0;b<3;b++)this.min[b]=Math.min(this.min[b],f.min[b]),this.max[b]=Math.max(this.max[b],f.max[b])}encapsulatePoint(f){for(let b=0;b<3;b++)this.min[b]=Math.min(this.min[b],f[b]),this.max[b]=Math.max(this.max[b],f[b])}closestPoint(f){return[Math.max(Math.min(this.max[0],f[0]),this.min[0]),Math.max(Math.min(this.max[1],f[1]),this.min[1]),Math.max(Math.min(this.max[2],f[2]),this.min[2])]}}function Qte(w){return w*By/E}Vr(jd,"Aabb");const PYt=[new jd([Mv,Mv,Mv],[J_,J_,J_]),new jd([Mv,Mv,Mv],[0,0,J_]),new jd([0,Mv,Mv],[J_,0,J_]),new jd([Mv,0,Mv],[0,J_,J_]),new jd([0,0,Mv],[J_,J_,J_])];function set(w,f,b,S=!0){const T=Be([],w._camera.position,w.worldSize),D=[f,b,1,1];dt(D,D,w.pixelMatrixInverse),xs(D,D,1/D[3]);const F=Fe([],wt([],D,T)),q=w.globeMatrix,K=[q[12],q[13],q[14]],X=wt([],K,T),ce=fe(X),pe=Fe([],X),xe=w.worldSize/(2*Math.PI),Ne=Oe(pe,F),Me=Math.asin(xe/ce);if(Me1?null:function(S,T,D,F){const q=Math.sin(D);return S*(Math.sin((1-F)*D)/q)+T*(Math.sin(F*D)/q)}(w.a[f],w.b[f],w.angle,Jr(b,0,1))+w.center[f]}function Qk(w){if(w.z<=1)return PYt[w.z+2*w.y+w.x];const f=zMe(Jte(w));return jd.fromPoints(f)}function O4(w,f,b){return Be(w,w,1-b),je(w,w,f,b)}function net(w,f,b){for(const S of w)tt(S,S,f),Be(S,S,b)}function FMe(w,f,b,S){const T=f/w.worldSize,D=w.globeMatrix;if(b.z<=1){const Lt=Qk(b).getCorners();return net(Lt,D,T),jd.fromPoints(Lt)}const F=Jte(b,S),q=zMe(F,By+Qte(w._tileCoverLift));net(q,D,T);const K=Number.MAX_VALUE,X=[-K,-K,-K],ce=[K,K,K];if(F.contains(w.center)){for(const Qt of q)Ie(ce,ce,Qt),Ue(X,X,Qt);X[2]=0;const Lt=w.point,Zt=[Lt.x*T,Lt.y*T,0];return Ie(ce,ce,Zt),Ue(X,X,Zt),new jd(ce,X)}if(w._tileCoverLift>0){for(const Lt of q)Ie(ce,ce,Lt),Ue(X,X,Lt);return new jd(ce,X)}const pe=[D[12]*T,D[13]*T,D[14]*T],xe=F.getCenter(),Ne=Jr(w.center.lat,-85.051129,Ce),Me=Jr(xe.lat,-85.051129,Ce),ze=Qm(w.center.lng),Ve=mp(Ne);let Je=ze-Qm(xe.lng);const lt=Ve-mp(Me);Je>.5?Je-=1:Je<-.5&&(Je+=1);let ht=0;Math.abs(Je)>Math.abs(lt)?ht=Je>=0?1:3:(ht=lt>=0?0:2,je(pe,pe,[D[4]*T,D[5]*T,D[6]*T],-Math.sin(_a(lt>=0?F.getSouth():F.getNorth()))*By));const ct=q[ht],xt=q[(ht+1)%4],kt=new IYt(ct,xt,pe),es=[OMe(kt,0)||ct[0],OMe(kt,1)||ct[1],OMe(kt,2)||ct[2]],Ct=F4(w.zoom);if(Ct>0){const Lt=function({x:Qt,y:Cs,z:Fs},on,sn,hn,Rn){const ws=1/(1<.5?Pn=-1:jn<-.5&&(Pn=1),qs=((qs+Pn)*on-(hn*=on))*sn+hn,en=((en+Pn)*on-hn)*sn+hn,wn=(wn*on-(Rn*=on))*sn+Rn,Nn=(Nn*on-Rn)*sn+Rn,[[qs,Nn,0],[en,Nn,0],[en,wn,0],[qs,wn,0]]}(b,f,w._pixelsPerMercatorPixel,ze,Ve);for(let Qt=0;QtMath.PI/2*1.01}const oet=_a(85),LYt=Math.cos(oet),RYt=Math.sin(oet);function cet(w,f){const b=w.fovAboveCenter,S=w.elevation?w.elevation.getMinElevationBelowMSL()*f:0,T=Math.min(S,w.isOrthographic?-10*f:0),D=(w._camera.position[2]*w.worldSize-T)/Math.cos(w._pitch),F=Math.sin(b)*D/Math.sin(Math.max(Math.PI/2-w._pitch-b,.01));let q=Math.sin(w._pitch)*F+D;const K=D*(1/w._horizonShift);if(!w.elevation||w.elevation.exaggeration()===0){let X=Math.max(w.zoom-17,0);w.isOrthographic&&(X/=10),q*=1+X}return Math.min(1.01*q,K)}class NA{constructor(f,b,S){this.z=f,this.x=b,this.y=S,this.key=kA(0,f,f,b,S)}equals(f){return this.z===f.z&&this.x===f.x&&this.y===f.y}isChildOf(f){const b=this.z-f.z;return f.z===0||f.z>b&&f.y===this.y>>b}url(f,b){const S=function(D,F,q){const K=2**q,X=2*Math.PI*6378137,ce=X*(D/K-.5),pe=X*(.5-(F+1)/K);return`${ce},${pe},${ce+X/K},${pe+X/K}`}(this.x,this.y,this.z),T=function(D,F,q){let K,X="";for(let ce=D;ce>0;ce--)K=1<this.canonical.z?new _p(f,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y):new _p(f,this.wrap,f,this.canonical.x>>b,this.canonical.y>>b)}calculateScaledKey(f,b=!0){if(this.overscaledZ===f&&b)return this.key;if(f>this.canonical.z)return kA(this.wrap*+b,f,this.canonical.z,this.canonical.x,this.canonical.y);{const S=this.canonical.z-f;return kA(this.wrap*+b,f,f,this.canonical.x>>S,this.canonical.y>>S)}}isChildOf(f){if(f.wrap!==this.wrap)return!1;const b=this.canonical.z-f.canonical.z;return f.overscaledZ===0||f.overscaledZ>b&&f.canonical.y===this.canonical.y>>b}children(f){if(this.overscaledZ>=f)return[new _p(this.overscaledZ+1,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y)];const b=this.canonical.z+1,S=2*this.canonical.x,T=2*this.canonical.y;return[new _p(b,this.wrap,b,S,T),new _p(b,this.wrap,b,S+1,T),new _p(b,this.wrap,b,S,T+1),new _p(b,this.wrap,b,S+1,T+1)]}isLessThan(f){return this.wrapf.wrap)&&(this.overscaledZf.overscaledZ)&&(this.canonical.xf.canonical.x)&&this.canonical.y{let f=w.canonical.x-1,b=w.wrap;return f<0&&(f=(1<{let f=w.canonical.x+1,b=w.wrap;return f===1<new _p(w.overscaledZ,w.wrap,w.canonical.z,w.canonical.x,(w.canonical.y===0?1<new _p(w.overscaledZ,w.wrap,w.canonical.z,w.canonical.x,w.canonical.y===(1<ht&&(ct(kt,on,Ct,Lt,Cs,Fs),ct(on,es,Cs,Fs,Zt,Qt))}ct(pe,xe,S,D,T,D),ct(xe,Ne,T,D,T,F),ct(Ne,Me,T,F,S,F),ct(Me,pe,S,F,S,D),ze-=ht,Ve-=ht,Je+=ht,lt+=ht;const xt=1/Math.max(Je-ze,lt-Ve);return{scale:xt,x:ze*xt,y:Ve*xt,x2:Je*xt,y2:lt*xt,projection:f}}function uet(w,f,b,S,T,D,F,q,K){if(K.name==="globe")return FMe(w,f,new NA(b,S,T),!1);const X=qMe({z:b,x:S,y:T},K);return new jd([(D+X.x/X.scale)*f,f*(X.y/X.scale),F],[(D+X.x2/X.scale)*f,f*(X.y2/X.scale),q])}Vr(NA,"CanonicalTileID"),Vr(_p,"OverscaledTileID",{omit:["projMatrix","expandedProjMatrix"]});const DYt=j(new Float32Array(16));class SA{constructor(f){this.spec=f,this.name=f.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(f,b){return{x:0,y:0,z:0}}unproject(f,b){return new W(0,0)}projectTilePoint(f,b,S){return{x:f,y:b,z:0}}locationPoint(f,b,S,T=!0){return f._coordinatePoint(f.locationCoordinate(b,S),T)}pixelsPerMeter(f,b){return de(1,f)*b}pixelSpaceConversion(f,b,S){return 1}farthestPixelDistance(f){return cet(f,f.pixelsPerMeter)}pointCoordinate(f,b,S,T){const D=f.horizonLineFromTop(!1),F=new Kt(b,Math.max(D,S));return f.rayIntersectionCoordinate(f.pointRayIntersection(F,T))}pointCoordinate3D(f,b,S){const T=new Kt(b,S);if(f.elevation)return f.elevation.pointCoordinate(T);{const D=this.pointCoordinate(f,T.x,T.y,0);return[D.x,D.y,D.z]}}isPointAboveHorizon(f,b){if(f.elevation&&f.elevation.visibleDemTiles.length)return!this.pointCoordinate3D(f,b.x,b.y);const S=f.horizonLineFromTop();return b.y0?b<-y7+S&&(b=-y7+S):b>y7-S&&(b=y7-S);const F=D/Math.pow(ase(b),T);let q=F*Math.sin(T*f),K=D-F*Math.cos(T*f);return q=.5*(q/Math.PI+.5),K=.5*(K/Math.PI+.5),{x:q,y:this.southernCenter?K:1-K,z:0}}unproject(f,b){f=(2*f-.5)*Math.PI,this.southernCenter&&(b=1-b),b=(2*(1-b)-.5)*Math.PI;const{n:S,f:T}=this,D=T-b,F=Math.sign(D),q=Math.sign(S)*Math.sqrt(f*f+D*D);let K=Math.atan2(f,Math.abs(D))*F;D*S<0&&(K-=Math.PI*Math.sign(f)*F);const X=Jr($o(K/S)+this.center[0],-180,180),ce=Jr($o(2*Math.atan(Math.pow(T/q,1/S))-y7),-85.051129,Ce);return new W(X,this.southernCenter?-ce:ce)}}class het extends SA{constructor(f){super(f),this.wrap=!0,this.supportsWorldCopies=!0,this.supportsTerrain=!0,this.supportsFog=!0,this.supportsFreeCamera=!0,this.isReprojectedInTileSpace=!1,this.unsupportedLayers=[],this.range=null}project(f,b){return{x:Qm(f),y:mp(b),z:0}}unproject(f,b){const S=Jm(f),T=hh(b);return new W(S,T)}}const met=_a(Ce);class $Yt extends SA{project(f,b){const S=(b=_a(b))*b,T=S*S;return{x:.5*((f=_a(f))*(.8707-.131979*S+T*(T*(.003971*S-.001529*T)-.013791))/Math.PI+.5),y:1-.5*(b*(1.007226+S*(.015085+T*(.028874*S-.044475-.005916*T)))/Math.PI+1),z:0}}unproject(f,b){f=(2*f-.5)*Math.PI;let S=b=(2*(1-b)-1)*Math.PI,T=25,D=0,F=S*S;do{F=S*S;const X=F*F;D=(S*(1.007226+F*(.015085+X*(.028874*F-.044475-.005916*X)))-b)/(1.007226+F*(.045255+X*(.259866*F-.311325-.005916*11*X))),S=Jr(S-D,-met,met)}while(Math.abs(D)>1e-6&&--T>0);F=S*S;const q=Jr($o(f/(.8707+F*(F*(F*F*F*(.003971-.001529*F)-.013791)-.131979))),-180,180),K=$o(S);return new W(q,K)}}const fet=_a(Ce);class UYt extends SA{project(f,b){b=_a(b),f=_a(f);const S=Math.cos(b),T=2/Math.PI,D=Math.acos(S*Math.cos(f/2)),F=Math.sin(D)/D,q=.5*(f*T+2*S*Math.sin(f/2)/F)||0,K=.5*(b+Math.sin(b)/F)||0;return{x:.5*(q/Math.PI+.5),y:1-.5*(K/Math.PI+1),z:0}}unproject(f,b){let S=f=(2*f-.5)*Math.PI,T=b=(2*(1-b)-1)*Math.PI,D=25;const F=1e-6;let q=0,K=0;do{const X=Math.cos(T),ce=Math.sin(T),pe=2*ce*X,xe=ce*ce,Ne=X*X,Me=Math.cos(S/2),ze=Math.sin(S/2),Ve=2*Me*ze,Je=ze*ze,lt=1-Ne*Me*Me,ht=lt?1/lt:0,ct=lt?Math.acos(X*Me)*Math.sqrt(1/lt):0,xt=.5*(2*ct*X*ze+2*S/Math.PI)-f,kt=.5*(ct*ce+T)-b,es=.5*ht*(Ne*Je+ct*X*Me*xe)+1/Math.PI,Ct=ht*(Ve*pe/4-ct*ce*ze),Lt=.125*ht*(pe*ze-ct*ce*Ne*Ve),Zt=.5*ht*(xe*Me+ct*Je*X)+.5,Qt=Ct*Lt-Zt*es;q=(kt*Ct-xt*Zt)/Qt,K=(xt*Lt-kt*es)/Qt,S=Jr(S-q,-Math.PI,Math.PI),T=Jr(T-K,-fet,fet)}while((Math.abs(q)>F||Math.abs(K)>F)&&--D>0);return new W($o(S),$o(T))}}class pet extends SA{constructor(f){super(f),this.center=f.center||[0,0],this.parallels=f.parallels||[0,0],this.cosPhi=Math.max(.01,Math.cos(_a(this.parallels[0]))),this.scale=1/(2*Math.max(Math.PI*this.cosPhi,1/this.cosPhi)),this.wrap=!0,this.supportsWorldCopies=!0}project(f,b){const{scale:S,cosPhi:T}=this;return{x:_a(f)*T*S+.5,y:-Math.sin(_a(b))/T*S+.5,z:0}}unproject(f,b){const{scale:S,cosPhi:T}=this,D=-(b-.5)/S,F=Jr($o((f-.5)/S)/T,-180,180),q=Math.asin(Jr(D*T,-1,1)),K=Jr($o(q),-85.051129,Ce);return new W(F,K)}}class qYt extends het{constructor(f){super(f),this.requiresDraping=!0,this.supportsWorldCopies=!1,this.supportsFog=!0,this.zAxisUnit="pixels",this.unsupportedLayers=["debug"],this.range=[3,5]}projectTilePoint(f,b,S){const T=dH(f,b,S);return tt(T,T,sse(Qk(S))),{x:T[0],y:T[1],z:T[2]}}locationPoint(f,b,S){const T=N(b.lat,b.lng),D=Fe([],T),F=S?f._centerAltitude+S:f.elevation?f.elevation.getAtPointOrZero(f.locationCoordinate(b),f._centerAltitude):f._centerAltitude;je(T,T,D,de(1,0)*br*F);const q=j(new Float64Array(16));return M(q,f.pixelMatrix,f.globeMatrix),tt(T,T,q),new Kt(T[0],T[1])}pixelsPerMeter(f,b){return de(1,0)*b}pixelSpaceConversion(f,b,S){const T=de(1,f)*b,D=da(de(1,45)*b,T,S);return this.pixelsPerMeter(f,b)/D}createTileMatrix(f,b,S){const T=BMe(Qk(S.canonical));return M(new Float64Array(16),f.globeMatrix,T)}createInversionMatrix(f,b){const{center:S}=f,T=sse(Qk(b));return O(T,T,_a(S.lng)),R(T,T,_a(S.lat)),P(T,T,[f._pixelsPerMercatorPixel,f._pixelsPerMercatorPixel,1]),Float32Array.from(T)}pointCoordinate(f,b,S,T){return set(f,b,S,!0)||new vt(0,0)}pointCoordinate3D(f,b,S){const T=this.pointCoordinate(f,b,S,0);return[T.x,T.y,T.z]}isPointAboveHorizon(f,b){return!set(f,b.x,b.y,!1)}farthestPixelDistance(f){const b=function(T,D){const F=T.cameraToCenterDistance,q=T._centerAltitude*D,K=T._camera,X=T._camera.forward(),ce=he([],Be([],X,-F),[0,0,q]),pe=T.worldSize/(2*Math.PI),xe=[0,0,-pe],Ne=T.width/T.height,Me=Math.tan(T.fovAboveCenter),ze=Be([],K.up(),Me),Ve=Be([],K.right(),Me*Ne),Je=Fe([],he([],he([],X,ze),Ve)),lt=[];let ht;if(new Xte(ce,Je).closestPointOnSphere(xe,pe,lt)){const ct=he([],lt,xe),xt=wt([],ct,ce);ht=Math.cos(T.fovAboveCenter)*fe(xt)}else{const ct=wt([],ce,xe),xt=wt([],xe,ce);Fe(xt,xt);const kt=fe(ct)-pe;ht=Math.sqrt(kt*(kt+2*pe));const es=Math.acos(ht/(pe+kt))-Math.acos(Oe(X,xt));ht*=Math.cos(es)}return 1.01*ht}(f,this.pixelsPerMeter(f.center.lat,f.worldSize)),S=F4(f.zoom);if(S>0){const T=cet(f,de(1,f.center.lat)*f.worldSize),D=f.worldSize/(2*Math.PI),F=Math.max(f.width,f.height)/f.worldSize*Math.PI;return da(b,T+D*(1-Math.cos(F)),Math.pow(S,10))}return b}upVector(f,b,S){return dH(b,S,f,1)}upVectorScale(f){return{metersToTile:Qte(ese(Qk(f)))}}}function ise(w){const f=w.parallels,b=!!f&&Math.abs(f[0]+f[1])<.01;switch(w.name){case"mercator":return new het(w);case"equirectangular":return new zYt(w);case"naturalEarth":return new $Yt(w);case"equalEarth":return new FYt(w);case"winkelTripel":return new UYt(w);case"albers":return b?new pet(w):new OYt(w);case"lambertConformalConic":return b?new pet(w):new BYt(w);case"globe":return new qYt(w)}throw new Error(`Invalid projection name: ${w.name}`)}const pH=Number.MAX_SAFE_INTEGER,VYt=pH-1;function get(w,f,b,S){return w.orderf.max.x||w.max.xf.max.y||w.max.ynew Kt((K.x+D.x*br)*q-F.x*br,(K.y+D.y*br)*q-F.y*br))}return HMe(b,T,w.indices,0,w.indices.length,0,0)}function bet(w,f,b,S){const T=Math.pow(2,S.z-b.z);return new Kt((w+b.x*br)*T-S.x*br,(f+b.y*br)*T-S.y*br)}function GMe(w,f){const b=[];f.grid.queryPoint(w,b);const S=f.indices,T=f.vertices;for(let D=0;D"u"?null:new TextDecoder("utf-8");class cse{constructor(f){this.buf=ArrayBuffer.isView(f)?f:new Uint8Array(f),this.dataView=new DataView(this.buf.buffer,this.buf.byteOffset,this.buf.byteLength),this.pos=0,this.type=0,this._valueStart=-1,this.length=this.buf.length}readFields(f,b,S=this.length){let T;for(;T=this.nextField(S);)f(T,b,this);return b}readMessage(f,b){return this.readFields(f,b,this.readVarint()+this.pos)}readFixed32(){const f=this.dataView.getUint32(this.pos,!0);return this.pos+=4,f}readSFixed32(){const f=this.dataView.getInt32(this.pos,!0);return this.pos+=4,f}readFixed64(){const f=this.dataView.getUint32(this.pos,!0)+this.dataView.getUint32(this.pos+4,!0)*WMe;return this.pos+=8,f}readSFixed64(){const f=this.dataView.getUint32(this.pos,!0)+this.dataView.getInt32(this.pos+4,!0)*WMe;return this.pos+=8,f}readFloat(){const f=this.dataView.getFloat32(this.pos,!0);return this.pos+=4,f}readDouble(){const f=this.dataView.getFloat64(this.pos,!0);return this.pos+=8,f}readVarint(f){const b=this.buf,S=b[this.pos++];if(S<128)return S;let T,D=127&S;return T=b[this.pos++],D|=(127&T)<<7,T<128?D:(T=b[this.pos++],D|=(127&T)<<14,T<128?D:(T=b[this.pos++],D|=(127&T)<<21,T<128?D:(T=b[this.pos],D|=(15&T)<<28,function(F,q,K){const X=K.buf;let ce,pe;if(pe=X[K.pos++],ce=(112&pe)>>4,pe<128||(pe=X[K.pos++],ce|=(127&pe)<<3,pe<128)||(pe=X[K.pos++],ce|=(127&pe)<<10,pe<128)||(pe=X[K.pos++],ce|=(127&pe)<<17,pe<128)||(pe=X[K.pos++],ce|=(127&pe)<<24,pe<128)||(pe=X[K.pos++],ce|=(1&pe)<<31,pe<128))return v7(F,ce,q);throw new Error("Expected varint not more than 10 bytes")}(D,f,this))))}readSVarint(){const f=this.readVarint();return f%2==1?(f+1)/-2:f/2}readBoolean(){return!!this.readVarint()}readString(){const f=this.readVarint()+this.pos,b=this.pos;return this.pos=f,f-b>=12&&wet?wet.decode(this.buf.subarray(b,f)):function(S,T,D){let F="",q=T;for(;q239?4:K>223?3:K>191?2:1;if(q+Ne>D)break;Ne===1?K<128&&(xe=K):Ne===2?(X=S[q+1],(192&X)==128&&(xe=(31&K)<<6|63&X,xe<=127&&(xe=null))):Ne===3?(X=S[q+1],ce=S[q+2],(192&X)==128&&(192&ce)==128&&(xe=(15&K)<<12|(63&X)<<6|63&ce,(xe<=2047||xe>=55296&&xe<=57343)&&(xe=null))):Ne===4&&(X=S[q+1],ce=S[q+2],pe=S[q+3],(192&X)==128&&(192&ce)==128&&(192&pe)==128&&(xe=(15&K)<<18|(63&X)<<12|(63&ce)<<6|63&pe,(xe<=65535||xe>=1114112)&&(xe=null))),xe===null?(xe=65533,Ne=1):xe>65535&&(xe-=65536,F+=String.fromCharCode(xe>>>10&1023|55296),xe=56320|1023&xe),F+=String.fromCharCode(xe),q+=Ne}return F}(this.buf,b,f)}readBytes(){const f=this.readVarint()+this.pos,b=this.buf.subarray(this.pos,f);return this.pos=f,b}readPackedVarint(f=[],b){const S=this.readPackedEnd();for(;this.pos=f)return 0;const b=this.readVarint();return this.type=7&b,this._valueStart=this.pos,b>>>3}skip(f){const b=7&f;if(b===0)for(;this.buf[this.pos++]>127;);else if(b===2)this.pos=this.readVarint()+this.pos;else if(b===5)this.pos+=4;else{if(b!==1)throw new Error(`Unimplemented type: ${b}`);this.pos+=8}}}function v7(w,f,b){return b?4294967296*f+(w>>>0):4294967296*(f>>>0)+(w>>>0)}function jet(w,f,b){const S=f<=16383?1:f<=2097151?2:f<=268435455?3:Math.floor(Math.log(f)/(7*Math.LN2));b.realloc(S),b.buf.copyWithin(w+S,w,b.pos)}function GYt(w,f){const b=w.length;let S=f.buf,T=f.pos,D=f.length;for(let F=0;FD)f.pos=T,f.writeVarint(q),S=f.buf,T=f.pos,D=f.length;else{for(;q>127;)S[T++]=q%128|128,q=Math.floor(q/128);S[T++]=q}}f.pos=T}function WYt(w,f){for(let b=0;bq.h-F.h);const S=[{x:0,y:0,w:Math.max(Math.ceil(Math.sqrt(f/.95)),b),h:1/0}];let T=0,D=0;for(const F of w)for(let q=S.length-1;q>=0;q--){const K=S[q];if(!(F.w>K.w||F.h>K.h)){if(F.x=K.x,F.y=K.y,D=Math.max(D,F.y+F.h),T=Math.max(T,F.x+F.w),F.w===K.w&&F.h===K.h){const X=S.pop();X&&qf.id?1:w.versionf.version?1:w.sxf.sx?1:w.syf.sy?1:0}function use(w){let f=0;for(let b=0;b0,ket(f,S,this.iconDescriptors,F),ket(b,S,this.patternDescriptors,F),this.iconDescriptors.sort(dse),this.patternDescriptors.sort(dse);let q=0;q=sw(q,use(D)),q=sw(q,1);const K=T?T.data:"";K&&(q=sw(q,use(K))),q=sw(q,1);for(const X of this.iconDescriptors)q=sw(q,use(X.id)),q=sw(q,X.version),q=sw(q,X.sx),q=sw(q,X.sy);q=sw(q,1);for(const X of this.patternDescriptors)q=sw(q,use(X.id)),q=sw(q,X.version),q=sw(q,X.sx),q=sw(q,X.sy);this.hash=q}subsetOf(f){return this.scope===f.scope&&this.isSubsetArray(this.iconDescriptors,f.iconDescriptors,dse)&&this.isSubsetArray(this.patternDescriptors,f.patternDescriptors,dse)}isSubsetArray(f,b,S){let T=0,D=0;if(f.length>b.length)return!1;for(;T0&&ce>0){const xe=this.useMipmap?Math.floor(Math.log2(Math.max(X,ce)))+1:1;F.texStorage2D(F.TEXTURE_2D,xe,this.format,X,ce),this.size=[X,ce]}this.size&&(pe?F.texSubImage2D(F.TEXTURE_2D,0,q,K,YMe(this.format),ZMe(this.format),f):"data"in f&&f.data&&F.texSubImage2D(F.TEXTURE_2D,0,q,K,S,T,YMe(this.format),ZMe(this.format),f.data)),this.useMipmap&&F.generateMipmap(F.TEXTURE_2D)}bind(f,b,S=!1){const{context:T}=this,{gl:D}=T;D.bindTexture(D.TEXTURE_2D,this.texture),f!==this.minFilter&&(D.texParameteri(D.TEXTURE_2D,D.TEXTURE_MAG_FILTER,f),D.texParameteri(D.TEXTURE_2D,D.TEXTURE_MIN_FILTER,this.useMipmap&&!S?f===D.NEAREST?D.NEAREST_MIPMAP_NEAREST:D.LINEAR_MIPMAP_LINEAR:f),this.minFilter=f),b!==this.wrapS&&(D.texParameteri(D.TEXTURE_2D,D.TEXTURE_WRAP_S,b),D.texParameteri(D.TEXTURE_2D,D.TEXTURE_WRAP_T,b),this.wrapS=b)}bindExtraParam(f,b,S,T,D){const{context:F}=this,{gl:q}=F;q.bindTexture(q.TEXTURE_2D,this.texture),b!==this.magFilter&&(q.texParameteri(q.TEXTURE_2D,q.TEXTURE_MAG_FILTER,b),this.magFilter=b),f!==this.minFilter&&(q.texParameteri(q.TEXTURE_2D,q.TEXTURE_MIN_FILTER,this.useMipmap?f===q.NEAREST?q.NEAREST_MIPMAP_NEAREST:q.LINEAR_MIPMAP_LINEAR:f),this.minFilter=f),S!==this.wrapS&&(q.texParameteri(q.TEXTURE_2D,q.TEXTURE_WRAP_S,S),this.wrapS=S),T!==this.wrapT&&(q.texParameteri(q.TEXTURE_2D,q.TEXTURE_WRAP_T,T),this.wrapT=T),D!==this.compareMode&&(D?(q.texParameteri(q.TEXTURE_2D,q.TEXTURE_COMPARE_MODE,q.COMPARE_REF_TO_TEXTURE),q.texParameteri(q.TEXTURE_2D,q.TEXTURE_COMPARE_FUNC,D)):q.texParameteri(q.TEXTURE_2D,q.TEXTURE_COMPARE_MODE,q.NONE),this.compareMode=D)}destroy(){const{gl:f}=this.context;f.deleteTexture(this.texture),this.texture=null}}class Cet{constructor(f,b,S,T){this.context=f,this.format=T,this.size=S,this.texture=f.gl.createTexture();const[D,F,q]=this.size,{gl:K}=f;K.bindTexture(K.TEXTURE_3D,this.texture),f.pixelStoreUnpackFlipY.set(!1),f.pixelStoreUnpack.set(1),f.pixelStoreUnpackPremultiplyAlpha.set(!1),"data"in b&&b.data&&K.texImage3D(K.TEXTURE_3D,0,this.format,D,F,q,0,YMe(this.format),ZMe(this.format),b.data)}bind(f,b){const{context:S}=this,{gl:T}=S;T.bindTexture(T.TEXTURE_3D,this.texture),f!==this.minFilter&&(T.texParameteri(T.TEXTURE_3D,T.TEXTURE_MAG_FILTER,f),T.texParameteri(T.TEXTURE_3D,T.TEXTURE_MIN_FILTER,f),this.minFilter=f),b!==this.wrapS&&(T.texParameteri(T.TEXTURE_3D,T.TEXTURE_WRAP_S,b),T.texParameteri(T.TEXTURE_3D,T.TEXTURE_WRAP_T,b),this.wrapS=b)}destroy(){const{gl:f}=this.context;f.deleteTexture(this.texture),this.texture=null}}class gH{static getImagePositionScale(f,b,S){if(b&&f){const{sx:T,sy:D}=f;return{x:T,y:D}}return{x:S,y:S}}constructor(f,b,S,T){this.paddedRect=f;const{pixelRatio:D,version:F,stretchX:q,stretchY:K,content:X,sdf:ce,usvg:pe}=b;this.pixelRatio=D,this.stretchX=q,this.stretchY=K,this.content=X,this.version=F,this.padding=S,this.sdf=ce,this.usvg=pe,this.scale=gH.getImagePositionScale(T,pe,D)}get tl(){return[this.paddedRect.x+this.padding,this.paddedRect.y+this.padding]}get br(){return[this.paddedRect.x+this.paddedRect.w-this.padding,this.paddedRect.y+this.paddedRect.h-this.padding]}get displaySize(){return[(this.paddedRect.w-2*this.padding)/this.scale.x,(this.paddedRect.h-2*this.padding)/this.scale.y]}}function Aet(w,f,b){const S=Kp.parse(w),T=function(D,F,q=[1,1]){return{x:0,y:0,w:(D.data?D.data.width:D.width*q[0])+2*F,h:(D.data?D.data.height:D.height*q[1])+2*F}}(f,b,[S.sx,S.sy]);return{bin:T,imagePosition:new gH(T,f,b,S),imageVariant:S}}function XMe(w,f){const b=[];for(const[T,D]of w.entries()){const F=Kp.parse(T);F&&(b.push({key:T,value:D,variant:F}),f&&f.set(T,F))}b.sort((T,D)=>{const F=T.variant.id.toString().localeCompare(D.variant.id.toString());return F!==0?F:T.variant.sx!==D.variant.sx?T.variant.sx-D.variant.sx:T.variant.sy!==D.variant.sy?T.variant.sy-D.variant.sy:T.key.localeCompare(D.key)});const S=new Map;for(const T of b)S.set(T.key,T.value);return S}class Eet{constructor(f){this.sourceAtlasHash=f}}class Tet{constructor(f,b,S,T,D=""){const F=new Map,q=new Map;this.haveRenderCallbacks=[];const K=[],X=T!==void 0,ce=X?new Map:void 0,pe=X?XMe(f,ce):f,xe=X?XMe(b,ce):b;this.addImages(pe,F,1,K),this.addImages(xe,q,2,K);const{w:Ne,h:Me}=Net(K),ze=new sy({width:Ne||1,height:Me||1});for(const[Ve,Je]of pe.entries()){const lt=F.get(Ve).paddedRect;sy.copy(Je.data,ze,{x:0,y:0},{x:lt.x+1,y:lt.y+1},Je.data,null,Je.sdf)}for(const[Ve,Je]of xe.entries()){const lt=q.get(Ve),ht=lt.paddedRect;let ct=lt.padding;const xt=ht.x+ct,kt=ht.y+ct,es=Je.data.width,Ct=Je.data.height;ct=ct>1?ct-1:ct,sy.copy(Je.data,ze,{x:0,y:0},{x:xt,y:kt},Je.data,S),sy.copy(Je.data,ze,{x:0,y:Ct-ct},{x:xt,y:kt-ct},{width:es,height:ct},S),sy.copy(Je.data,ze,{x:0,y:0},{x:xt,y:kt+Ct},{width:es,height:ct},S),sy.copy(Je.data,ze,{x:es-ct,y:0},{x:xt-ct,y:kt},{width:ct,height:Ct},S),sy.copy(Je.data,ze,{x:0,y:0},{x:xt+es,y:kt},{width:ct,height:Ct},S),sy.copy(Je.data,ze,{x:es-ct,y:Ct-ct},{x:xt-ct,y:kt-ct},{width:ct,height:ct},S),sy.copy(Je.data,ze,{x:0,y:Ct-ct},{x:xt+es,y:kt-ct},{width:ct,height:ct},S),sy.copy(Je.data,ze,{x:0,y:0},{x:xt+es,y:kt+Ct},{width:ct,height:ct},S),sy.copy(Je.data,ze,{x:es-ct,y:0},{x:xt-ct,y:kt+Ct},{width:ct,height:ct},S)}this.lut=S,this.image=ze,this.iconPositions=F,this.patternPositions=q,X&&(this.contentDescriptor=new KMe(pe,xe,T,S,D,ce))}addImages(f,b,S,T){for(const[D,F]of f.entries()){const{bin:q,imagePosition:K,imageVariant:X}=Aet(D,F,S);b.set(D,K),T.push(q),F.hasRenderCallback&&this.haveRenderCallbacks.push(X.id)}}patchUpdatedImages(f,b,S,T){this.haveRenderCallbacks=this.haveRenderCallbacks.filter(D=>f.hasImage(D,S)),f.dispatchRenderCallbacks(this.haveRenderCallbacks,S);for(const D of f.getUpdatedImages(S)){for(const F of this.iconPositions.keys()){const q=Kp.parse(F);if(Gl.isEqual(q.id,D)){const K=f.getImage(D,S);this.patchUpdatedImage(this.iconPositions.get(F),K,b,null)}}for(const F of this.patternPositions.keys()){const q=Kp.parse(F);if(Gl.isEqual(q.id,D)){const K=f.getImage(D,S);this.patchUpdatedImage(this.patternPositions.get(F),K,b,T||this.lut)}}}}patchUpdatedImage(f,b,S,T=null){if(!f||!b||f.version===b.version)return;f.version=b.version;const[D,F]=f.tl,q=f.sdf;if(this.lut||q){const K={width:b.data.width,height:b.data.height},X=new sy(K);sy.copy(b.data,X,{x:0,y:0},{x:0,y:0},K,T,q),S.update(X,{position:{x:D,y:F},recreateWhenResize:!1})}else S.update(b.data,{position:{x:D,y:F},recreateWhenResize:!1})}}Vr(gH,"ImagePosition"),Vr(Tet,"ImageAtlas",{omit:["lut"]}),Vr(Eet,"ImageAtlasReference");class xH{constructor(f){this.pendingRequests=new Map,this.cachedRanges=new Map,this.fontstackCompositing=f&&f.fontstackCompositing||"client"}loadGlyphRange(f,b,S,T,D){if(this.fontstackCompositing==="server")return void xH.loadGlyphRange(f,b,S,T,D);const F=f.split(",").map(q=>q.trim()).filter(q=>q.length>0);F.length!==0?F.length!==1?this._loadMultipleFonts(F,b,S,T,D):this._loadFont(F[0],b,S,T,D):D(new Error("Empty fontstack"))}_loadMultipleFonts(f,b,S,T,D){const F=f.map(()=>null),q={completed:0,firstError:null,callbackCalled:!1},K=(X,ce,pe)=>{if(!q.callbackCalled&&(ce&&!q.firstError&&(q.firstError=ce),pe&&(F[X]=pe),q.completed++,q.completed===f.length)){q.callbackCalled=!0;const xe=F.filter(Me=>Me!==null);if(xe.length===0)return void D(q.firstError||new Error("All fonts failed to load"));const Ne=this._composeGlyphs(xe);D(null,Ne)}};for(let X=0;X{K(X,ce,pe)})}_loadFont(f,b,S,T,D){const F=`${f}:${b}`;if(this.cachedRanges.has(F)){const K=this.cachedRanges.get(F);return void qt.frame(()=>D(null,K))}const q=this.pendingRequests.get(F);q?q.push(D):(this.pendingRequests.set(F,[D]),xH.loadGlyphRange(f,b,S,T,(K,X)=>{K||this.cachedRanges.set(F,X||null);const ce=this.pendingRequests.get(F);if(this.pendingRequests.delete(F),ce)for(const pe of ce)pe(K,X)}))}_composeGlyphs(f){const b={};let S,T;for(const D of f)if(S===void 0&&D.ascender!==void 0&&(S=D.ascender),T===void 0&&D.descender!==void 0&&(T=D.descender),D.glyphs)for(const F in D.glyphs)b[F]===void 0&&(b[F]=D.glyphs[F]);return{glyphs:b,ascender:S,descender:T}}}xH.loadGlyphRange=async function(w,f,b,S,T){const D=256*f,F=D+255;let q;try{const K=await S.transformRequest(S.normalizeGlyphsURL(b).replace("{fontstack}",w).replace("{range}",`${D}-${F}`),Ro.Glyphs),{data:X}=await fr(K),ce={},pe=function(xe){return function(Ne){const Me={glyphs:[]};let ze;for(;ze=Ne.nextField();)ze===1&&tZt(Ne,Ne.readVarint()+Ne.pos,Me);return Me}(new cse(xe))}(X);for(const xe of pe.glyphs)ce[xe.id]=xe;q={glyphs:ce,ascender:pe.ascender,descender:pe.descender}}catch(K){return T(K)}T(null,q)};const yH=1e20,QMe=new Float64Array(256);for(let w=0;w<256;w++){const f=.5-Math.pow(w/255,.45454545454545453);QMe[w]=f*Math.abs(f)}function Met(w,f,b,S,T,D,F,q,K){for(let X=f;X-1);K++,D[K]=q,F[K]=X,F[K+1]=yH}for(let q=0,K=0;q{if(F){T.ascender=F.ascender,T.descender=F.descender;for(const q in F.glyphs)this._doesCharSupportLocalGlyph(+q)||(T.glyphs[+q]=F.glyphs[+q]);T.ranges[b]=!0}for(const q of T.requests[b]||[])q(D,F);delete T.requests[b]}))}getGlyphs(f,b){const S=[],T=this.url||Xt.GLYPHS_URL;for(const D in f)for(const F of f[D])S.push({stack:D,id:F});Lc(S,({stack:D,id:F},q)=>{let K=this.entries[D];K||(K=this.entries[D]={glyphs:{},requests:{},ranges:{},ascender:void 0,descender:void 0});let X=K.glyphs[F];if(X!==void 0)return void q(null,{stack:D,id:F,glyph:X});if(X=this._tinySDF(K,D,F),X)return K.glyphs[F]=X,void q(null,{stack:D,id:F,glyph:X});const ce=Math.floor(F/256);if(256*ce>65535)return oi("glyphs > 65535 not supported"),void q(null,{stack:D,id:F,glyph:X});if(K.ranges[ce])return void q(null,{stack:D,id:F,glyph:X});let pe=K.requests[ce];pe||(pe=K.requests[ce]=[],this.glyphLoader.loadGlyphRange(D,ce,T,this.requestManager,(xe,Ne)=>{if(Ne){K.ascender=Ne.ascender,K.descender=Ne.descender;for(const Me in Ne.glyphs)this._doesCharSupportLocalGlyph(+Me)||(K.glyphs[+Me]=Ne.glyphs[+Me]);K.ranges[ce]=!0}for(const Me of pe)Me(xe,Ne);delete K.requests[ce]})),pe.push((xe,Ne)=>{xe?q(xe):Ne&&q(null,{stack:D,id:F,glyph:Ne.glyphs[F]||null})})},(D,F)=>{if(D)b(D);else if(F){const q={};for(const{stack:K,id:X,glyph:ce}of F)q[K]===void 0&&(q[K]={}),q[K].glyphs===void 0&&(q[K].glyphs={}),q[K].glyphs[X]=ce&&{id:ce.id,bitmap:ce.bitmap.clone(),metrics:ce.metrics},q[K].ascender=this.entries[K].ascender,q[K].descender=this.entries[K].descender;b(null,q)}})}_doesCharSupportLocalGlyph(f){return this.localGlyphMode!==JMe.none&&(this.localGlyphMode===JMe.all?!!this.localFontFamily:!!this.localFontFamily&&(D0(f)||t7(f)||N4(f)||sN(f)||j4(f)||X_(f)||(b=f)>=131072&&b<=173791||(S=>S>=66736&&S<=66815)(f)));var b}_tinySDF(f,b,S){const T=this.localFontFamily;if(!T||!this._doesCharSupportLocalGlyph(S))return;let D=f.tinySDF;if(!D){let Ve="400";nZt.test(b)?Ve="900":rZt.test(b)?Ve="500":aZt.test(b)&&(Ve="200"),D=f.tinySDF=new mse.TinySDF({fontFamily:T,fontWeight:Ve,fontSize:48,buffer:6,radius:16}),D.fontWeight=Ve}const F=D.fontWeight;if(this.localGlyphs[F][S])return this.localGlyphs[F][S];const q=String.fromCodePoint(S),{data:K,width:X,height:ce,glyphWidth:pe,glyphHeight:xe,glyphLeft:Ne,glyphTop:Me,glyphAdvance:ze}=D.draw(q);return this.localGlyphs[F][S]={id:S,bitmap:new wA({width:X,height:ce},K),metrics:{width:pe/2,height:xe/2,left:Ne/2,top:Me/2-27,advance:ze/2,localGlyph:!0}}}}function Iet(w,f){return w+f[1]-f[0]}function Let(w,f,b,S,T=1){const D=[],F=w.imagePrimary,q=F.pixelRatio,K=F.paddedRect.w-2,X=F.paddedRect.h-2,ce=(w.right-w.left)*T,pe=(w.bottom-w.top)*T,xe=F.stretchX||[[0,K]],Ne=F.stretchY||[[0,X]],Me=xe.reduce(Iet,0),ze=Ne.reduce(Iet,0),Ve=K-Me,Je=X-ze;let lt=0,ht=Me,ct=0,xt=ze,kt=0,es=Ve,Ct=0,Lt=Je;if(F.content&&S){const Qt=F.content;lt=fse(xe,0,Qt[0]),ct=fse(Ne,0,Qt[1]),ht=fse(xe,Qt[0],Qt[2]),xt=fse(Ne,Qt[1],Qt[3]),kt=Qt[0]-lt,Ct=Qt[1]-ct,es=Qt[2]-Qt[0]-ht,Lt=Qt[3]-Qt[1]-xt}const Zt=(Qt,Cs,Fs,on)=>{const sn=pse(Qt.stretch-lt,ht,ce,w.left*T),hn=gse(Qt.fixed-kt,es,Qt.stretch,Me),Rn=pse(Cs.stretch-ct,xt,pe,w.top*T),ws=gse(Cs.fixed-Ct,Lt,Cs.stretch,ze),qs=pse(Fs.stretch-lt,ht,ce,w.left*T),en=gse(Fs.fixed-kt,es,Fs.stretch,Me),wn=pse(on.stretch-ct,xt,pe,w.top*T),Nn=gse(on.fixed-Ct,Lt,on.stretch,ze),Pn=new Kt(sn,Rn),jn=new Kt(qs,Rn),Wn=new Kt(qs,wn),Kn=new Kt(sn,wn),Dr=new Kt(hn/q,ws/q),sr=new Kt(en/q,Nn/q),yr=f*Math.PI/180;if(yr){const bi=Math.sin(yr),Bl=Math.cos(yr),cl=[Bl,-bi,bi,Bl];Pn._matMult(cl),jn._matMult(cl),Kn._matMult(cl),Wn._matMult(cl)}const Ra=Qt.stretch+Qt.fixed,$a=Fs.stretch+Fs.fixed,si=Cs.stretch+Cs.fixed,La=on.stretch+on.fixed,Oi=w.imageSecondary;return{tl:Pn,tr:jn,bl:Kn,br:Wn,texPrimary:{x:F.paddedRect.x+1+Ra,y:F.paddedRect.y+1+si,w:$a-Ra,h:La-si},texSecondary:Oi?{x:Oi.paddedRect.x+1+Ra,y:Oi.paddedRect.y+1+si,w:$a-Ra,h:La-si}:void 0,writingMode:void 0,glyphOffset:[0,0],sectionIndex:0,pixelOffsetTL:Dr,pixelOffsetBR:sr,minFontScaleX:es/q/ce,minFontScaleY:Lt/q/pe,isSDF:b}};if(F.stretchX||F.stretchY){const Qt=Ret(xe,Ve,Me),Cs=Ret(Ne,Je,ze);for(let Fs=0;Fs0?[lt,-ht]:ct<0?[-lt,ht]:lt===0?[ht,lt]:[ht,-lt]}(b);let Ne=Math.abs(f.top-f.bottom);for(const Je of f.positionedLines)Ne-=Je.lineOffset;const Me=f.positionedLines.length,ze=Ne/Me;let Ve=f.top-b[1];for(let Je=0;Jefunction(D){if(!D.condition)return{featureDependent:!1,stateDependent:!1,zoomDependent:!1,pitchDependent:!1,brightnessDependent:!1,worldviewDependent:!1};const F=D.condition.expression;return{featureDependent:!qh(F),stateDependent:!A1(F),zoomDependent:!Yp(F,["zoom"]),pitchDependent:!Yp(F,["pitch"]),brightnessDependent:!Yp(F,["brightness","measure-light"]),worldviewDependent:!Yp(F,["worldview"])}}(T));this.anyFeatureDependent=S.some(T=>T.featureDependent),this.anyStateDependent=S.some(T=>T.stateDependent)}update(f,b){const S=this.lastParams,T=!S||S.zoom!==f.zoom||S.pitch!==(f.pitch||0)||S.brightness!==(f.brightness||0)||S.worldview!==f.worldview;this.lastParams={zoom:f.zoom,pitch:f.pitch||0,brightness:f.brightness||0,worldview:f.worldview};const D=b&&this.anyStateDependent;if(!T&&!D&&this.lastAllFeaturesIndex!==-2)return{kind:"no-changes"};if(!this.anyFeatureDependent&&!D){const F=this.evaluateAllFeatures(f);return F===this.lastAllFeaturesIndex?{kind:"no-changes"}:(this.lastAllFeaturesIndex=F,{kind:"all-features",appearanceIndex:F})}return{kind:"per-feature"}}evaluateAllFeatures(f){for(let b=0;bF-q),D=new Map;for(const F of T){const q=S.get(F);D.set(F,new lc(q))}return b&&(this.cachedBatchIndices=T,this.cachedBatchSegments=D),{batchIndices:T,batchSegments:D}}snapshotSymbolVertexData(f,b){const S=f*b7;return this.layoutVertexArray.uint16.slice(S,S+b*b7)}restoreSymbolVertexData(f,b){this.layoutVertexArray.uint16.set(b,f*b7)}snapshotIconTransitioningVertexData(f,b){const S=2*f;return this.iconTransitioningVertexArray.uint16.slice(S,S+2*b)}restoreIconTransitioningVertexData(f,b){this.iconTransitioningVertexArray.uint16.set(b,2*f)}updateSymbolVertexData(f,b,S,T,D,F,q,K,X,ce,pe,xe,Ne){const Me=this.layoutVertexArray.uint16,ze=f*b7;Me[ze]=b,Me[ze+1]=S,Me[ze+2]=T,Me[ze+3]=D,Me[ze+4]=F,Me[ze+5]=q,Me[ze+6]=K,Me[ze+7]=X,Me[ze+8]=ce,Me[ze+9]=pe,Me[ze+10]=xe,Me[ze+11]=Ne}upload(f,b,S,T,D,F){this.isEmpty()||(S&&(this.cachedBatchIndices=null,this.cachedBatchSegments=null,this.layoutVertexBuffer=f.createVertexBuffer(this.layoutVertexArray,uYt.members,!!F),this.indexBuffer=f.createIndexBuffer(this.indexArray,b),this.dynamicLayoutVertexBuffer=f.createVertexBuffer(this.dynamicLayoutVertexArray,mYt.members,!0),this.opacityVertexBuffer=f.createVertexBuffer(this.opacityVertexArray,cZt,!0),this.iconTransitioningVertexArray.length>0&&(this.iconTransitioningVertexBuffer=f.createVertexBuffer(this.iconTransitioningVertexArray,xYt.members,!0)),this.globeExtVertexArray.length>0&&(this.globeExtVertexBuffer=f.createVertexBuffer(this.globeExtVertexArray,hYt.members,!0)),!this.zOffsetVertexBuffer&&(this.zOffsetVertexArray.length>0||D)&&(this.zOffsetVertexBuffer=f.createVertexBuffer(this.zOffsetVertexArray,fYt.members,!0)),!this.orientationVertexBuffer&&this.orientationVertexArray&&this.orientationVertexArray.length>0&&(this.orientationVertexBuffer=f.createVertexBuffer(this.orientationVertexArray,gYt.members,!0)),this.opacityVertexBuffer.itemSize=1,this.featureIdArray.length>0&&(this.featureIdBuffer=f.createVertexBuffer(this.featureIdArray,pYt.members,!1))),(S||T)&&(this.programConfigurations.upload(f),this.uboBinder&&this.uboBinder.upload(f)))}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())}}Vr(e6e,"SymbolBuffers",{omit:["cachedBatchIndices","cachedBatchSegments"]});class t6e{constructor(f,b,S){this.layoutVertexArray=new f,this.layoutAttributes=b,this.indexArray=new S,this.segments=new lc,this.collisionVertexArray=new Wo,this.collisionVertexArrayExt=new ci}upload(f){this.layoutVertexBuffer=f.createVertexBuffer(this.layoutVertexArray,this.layoutAttributes),this.indexBuffer=f.createIndexBuffer(this.indexArray),this.collisionVertexBuffer=f.createVertexBuffer(this.collisionVertexArray,yYt.members,!0),this.collisionVertexBufferExt=f.createVertexBuffer(this.collisionVertexArrayExt,vYt.members,!0)}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.segments.destroy(),this.collisionVertexBuffer.destroy(),this.collisionVertexBufferExt.destroy())}}Vr(t6e,"CollisionBuffers");class yse{constructor(f){this.collisionBoxArray=f.collisionBoxArray,this.zoom=f.zoom,this.overscaling=f.overscaling,this.layers=f.layers,this.layerIds=this.layers.map(F=>F.fqid),this.index=f.index,this.pixelRatio=f.pixelRatio,this.sourceLayerIndex=f.sourceLayerIndex,this.hasPattern=!1,this.hasRTLText=!1,this.fullyClipped=!1,this.hasAnyIconTextFit=!1,this.sortKeyRanges=[],this.collisionCircleArray=[],this.placementInvProjMatrix=j([]),this.placementViewportMatrix=j([]);const b=this.layers[0]._unevaluatedLayout._values;this.worldview=f.worldview,this.localizable=f.localizable,this.maxUniformBufferBindings=f.maxUniformBufferBindings,this.maxUniformBlockSizeDwords=f.maxUniformBlockSizeDwords,this.textSizeData=g7(this.zoom,b["text-size"],this.worldview,f.availableImages),this.iconSizeData=g7(this.zoom,b["icon-size"],this.worldview,f.availableImages);const S=this.layers[0].layout,T=S.get("symbol-sort-key"),D=S.get("symbol-z-order");this.lut=f.lut,this.canOverlap=S.get("text-allow-overlap")||S.get("icon-allow-overlap")||S.get("text-ignore-placement")||S.get("icon-ignore-placement"),this.sortFeaturesByKey=D!=="viewport-y"&&T.constantOr(1)!==void 0,this.sortFeaturesByY=(D==="viewport-y"||D==="auto"&&!this.sortFeaturesByKey)&&this.canOverlap,this.writingModes=S.get("text-writing-mode").map(F=>R4[F]),this.stateDependentLayerIds=this.layers.filter(F=>F.isStateDependent()).map(F=>F.id),this.sourceID=f.sourceID,this.projection=f.projection,this.hasAnyZOffset=!1,this.zOffsetSortDirty=!1,this.zOffsetBuffersNeedUpload=!1,this.elevationType="none",this.activeReplacements=[],this.replacementUpdateTime=0,this.hasAnySecondaryIcon=!1,this.hasAppearances=null,this.featureAppearances=null,this.featureAppearanceData=new Map}hasAnyAppearanceLayoutProperty(f){const b=this.layers[0].getAppearances();if(!b||b.length===0)return!1;const S=Array.isArray(f)?f:[f];return b.some(T=>S.some(D=>T.hasLayoutProperty(D)))}getAppearanceFeatureData(f){return this.featureAppearanceData.get(f)}createArrays(){this.text=new e6e(new aN(this.layers,{zoom:this.zoom,lut:this.lut},f=>f.startsWith("text")||f.startsWith("symbol"))),this.icon=new e6e(new aN(this.layers,{zoom:this.zoom,lut:this.lut},f=>f.startsWith("icon")||f.startsWith("symbol"))),this.text.uboBinder=new PMe(this.layers[0],this.zoom,this.lut,!0,"",this.maxUniformBufferBindings,this.maxUniformBlockSizeDwords),this.icon.uboBinder=new PMe(this.layers[0],this.zoom,this.lut,!1,"",this.maxUniformBufferBindings,this.maxUniformBlockSizeDwords),this.glyphOffsetArray=new bp,this.lineVertexArray=new qd,this.symbolInstances=new zu}calculateGlyphDependencies(f,b,S,T,D){for(const F of f){const q=F.codePointAt(0);if(q===void 0)break;if(b[q]=!0,T&&D&&q<=65535){const K=cH[F];K&&(b[K.charCodeAt(0)]=!0)}}}calculateEffectiveAppearanceIconSize(f,b,S,T,D,F,q){if(!f.hasLayoutProperty("icon-size"))return q*F;let K=1;const X=f.getUnevaluatedLayoutProperty("icon-size"),ce=g7(this.zoom,X,this.worldview,D),pe=H6(ce,b);if(ce.kind!=="constant"&&ce.kind!=="camera"||(K=pe.uSize),ce.kind==="composite"){const{minZoom:xe,maxZoom:Ne}=ce,Me=X.possiblyEvaluate(new tr(xe,{worldview:this.worldview}),T),ze=X.possiblyEvaluate(new tr(Ne,{worldview:this.worldview}),T),Ve=Me.evaluate(S,{},T,D);K=Ve+(ze.evaluate(S,{},T,D)-Ve)*pe.uSizeT}return ce.kind==="source"&&(K=X.possiblyEvaluate(new tr(this.zoom,{worldview:this.worldview}),T).evaluate(S,{},T,D)),K*F}updateFootprints(f,b){}updateReplacement(f,b){if(b.updateTime===this.replacementUpdateTime)return!1;this.replacementUpdateTime=b.updateTime;const S=b.getReplacementRegionsForTile(f.toUnwrapped(),!0);return!lse(this.activeReplacements,S)&&(this.activeReplacements=S,!0)}getResolvedImageFromTokens(f){return typeof f=="string"?rm.build(f):f}populate(f,b,S,T){const D=this.layers[0],F=D.layout,q=this.projection.name==="globe",K=F.get("text-font"),X=F.get("text-field"),ce=F.get("icon-image"),[pe,xe]=F.get("icon-size-scale-range"),Ne=Jr(b.scaleFactor||1,pe,xe),[Me,ze]=F.get("text-size-scale-range"),Ve=Jr(b.scaleFactor||1,Me,ze),Je=(X.value.kind!=="constant"||X.value.value instanceof Yu&&!X.value.value.isEmpty()||X.value.value.toString().length>0)&&(K.value.kind!=="constant"||K.value.value.length>0),lt=ce.value.kind!=="constant"||!!ce.value.value||Object.keys(ce.parameters).length>0,ht=this.hasAnyAppearanceLayoutProperty("icon-image"),ct=F.get("symbol-sort-key");if(this.features=[],this.featureAppearanceData=new Map,!Je&&!lt&&!ht)return;const xt=b.iconDependencies,kt=b.glyphDependencies,es=b.availableImages,Ct=new tr(this.zoom,{worldview:this.worldview,activeFloors:b.activeFloors}),Lt=Zt=>{const Qt=Zt.id.toString();xt.has(Qt)?xt.get(Qt).push(Zt):xt.set(Qt,[Zt])};for(const Zt of f){const{feature:Qt,id:Cs,index:Fs,sourceLayerIndex:on}=Zt,sn=D._featureFilter.needGeometry,hn=Js(Qt,sn);if(!D._featureFilter.filter(Ct,hn,S))continue;if(sn||(hn.geometry=Ms(Qt,S,T)),q&&Qt.type!==1&&S.z<=5){const jn=hn.geometry,Wn=.98078528056,Kn=(Dr,sr)=>Oe(dH(Dr.x,Dr.y,S,1),dH(sr.x,sr.y,S,1)){if(!jn.getLayoutProperty("icon-image"))return;const{iconPrimary:Wn,iconSecondary:Kn}=this.getCombinedIconVariants(jn,qs,hn,S,es,Nn,Ne);Wn&&(Lt(Wn),Kn&&(this.hasAnySecondaryIcon=!0,Lt(Kn)))}),Rn){const jn=K.evaluate(hn,{},S).join(","),Wn=F.get("text-rotation-alignment")==="map"&&F.get("symbol-placement")!=="point";this.allowVerticalPlacement=this.writingModes&&this.writingModes.includes(R4.vertical);for(const Kn of Rn.sections)if(Kn.image){const Dr=Kn.image.getPrimary().scaleSelf(this.pixelRatio*Ve),sr=Dr.id.toString(),yr=xt.get(sr)||[];yr.push(Dr),xt.set(sr,yr)}else{const Dr=J(Rn.toString()),sr=Kn.fontStack||jn,yr=kt[sr]=kt[sr]||{};this.calculateGlyphDependencies(Kn.text,yr,Wn,this.allowVerticalPlacement,Dr)}}}F.get("symbol-placement")==="line"&&(this.features=function(Zt){const Qt={},Cs={},Fs=[];let on=0;function sn(qs){Fs.push(Zt[qs]),on++}function hn(qs,en,wn){const Nn=Cs[qs];return delete Cs[qs],Cs[en]=Nn,Fs[Nn].geometry[0].pop(),Fs[Nn].geometry[0]=Fs[Nn].geometry[0].concat(wn[0]),Nn}function Rn(qs,en,wn){const Nn=Qt[en];return delete Qt[en],Qt[qs]=Nn,Fs[Nn].geometry[0].shift(),Fs[Nn].geometry[0]=wn[0].concat(Fs[Nn].geometry[0]),Nn}function ws(qs,en,wn){const Nn=wn?en[0].at(-1):en[0][0];return`${qs}:${Nn.x}:${Nn.y}`}for(let qs=0;qs1){sn(qs);continue}const Pn=ws(Nn,wn,!1),jn=ws(Nn,wn,!0);if(Pn in Cs&&jn in Qt&&Cs[Pn]!==Qt[jn]){const Wn=Rn(Pn,jn,wn),Kn=hn(Pn,jn,Fs[Wn].geometry);delete Qt[Pn],delete Cs[jn],Cs[ws(Nn,Fs[Kn].geometry,!0)]=Kn,Fs[Wn].geometry=null}else Pn in Cs?hn(Pn,jn,wn):jn in Qt?Rn(Pn,jn,wn):(sn(qs),Qt[Pn]=on-1,Cs[jn]=on-1)}return Fs.filter(qs=>qs.geometry)}(this.features)),F.get("symbol-elevation-reference")==="hd-road-markup"?(this.elevationType="road",this.hdExt&&(this.hdExt.configureCrossSource(S,b.elevationParams,b.crossSourceElevationEnabled,b.terrainEnabled),b.elevationFeatures&&b.elevationFeatures.length>0&&this.hdExt.addElevationFeatures(b.elevationFeatures,S))):F.get("symbol-z-elevate")&&(this.elevationType="offset"),this.elevationType!=="none"&&(this.zOffsetBuffersNeedUpload=!0),this.sortFeaturesByKey&&this.features.sort((Zt,Qt)=>Zt.sortKey-Qt.sortKey)}getCombinedIconVariants(f,b,S,T,D,F,q){let K;if(f.hasLayoutProperty("icon-image")){const X=b.getAppearanceValueAndResolveTokens(f,"icon-image",S,T,D);K=this.getResolvedImageFromTokens(X)}else{const X=b.getValueAndResolveTokens("icon-image",S,T,D);K=this.getResolvedImageFromTokens(X)}if(K){const X=f.hasLayoutProperty("icon-size")?f.getUnevaluatedLayoutProperty("icon-size"):b._unevaluatedLayout._values["icon-size"],ce=g7(this.zoom,X,this.worldview,D),{iconPrimary:pe,iconSecondary:xe}=IMe(K,ce,X,T,this.zoom,F,this.pixelRatio,q,this.worldview,D);return{iconPrimary:pe,iconSecondary:xe}}return{iconPrimary:void 0,iconSecondary:void 0}}getCombinedIconPrimary(f,b,S,T,D,F,q){return this.getCombinedIconVariants(f,b,S,T,D,F,q).iconPrimary}updateSymbolInstanceIconVertices(f,b,S,T,D,F){const{canonical:q,availableImages:K,globalProperties:X,layer:ce,iconScaleFactor:pe,featureState:xe,layoutIconOffset:Ne,layoutIconSize:Me,layoutIconRotate:ze}=F;if(f.placedIconSymbolIndex<0)return{vertexOffsetDelta:0,hasChanges:!1};if(b.activeAppearanceIndex===S)return{vertexOffsetDelta:f.numIconVertices,hasChanges:!1};const Ve=S>=0?ce.appearances[S]:null;if(Ve){const Je={sortKey:void 0,text:void 0,icon:null,index:f.featureIndex,sourceLayerIndex:f.featureIndex,geometry:[],properties:b.properties,type:"Point",id:b.id},{iconPrimary:lt,iconSecondary:ht}=this.getCombinedIconVariants(Ve,ce,T,q,K,Je,pe);if(!lt)return{vertexOffsetDelta:0,hasChanges:!1};const ct=lt.toString(),xt=this.iconAtlasPositions&&this.iconAtlasPositions.get(ct);if(xt){const{appearanceIconOffset:kt,appearanceIconRotate:es}=KJe(Ve,ce,T,q,Ne,ze,Me,pe),Ct=ce.layout.get("icon-anchor").evaluate(T,xe,q);let Lt=GJe(xt,ht?this.iconAtlasPositions&&this.iconAtlasPositions.get(ht.toString()):void 0,kt,Ct);const Zt=xt.sdf,Qt=ce.layout.get("icon-text-fit").constantOr("none");Qt!=="none"&&b.textShaping&&b.iconTextFitPadding&&b.fontScale&&(Lt=WJe(Lt,b.textShaping,Qt,b.iconTextFitPadding,kt,b.fontScale));const Cs=this.calculateEffectiveAppearanceIconSize(Ve,X.zoom,T,q,K,pe,Me),Fs=0,on=1+(Math.min(G6,Math.round(Cs*jA))<<1),sn=Let(Lt,es,Zt,Qt!=="none",pe),hn=this.icon.iconTransitioningVertexArray.length>0;b.isUsingAppearanceIconVertexData||(b.isUsingAppearanceIconVertexData=!0,b.layoutBasedIconVertexData=this.icon.snapshotSymbolVertexData(D,f.numIconVertices),hn&&(b.layoutBasedIconTransitioningVertexData=this.icon.snapshotIconTransitioningVertexData(D,f.numIconVertices)));const Rn=Math.floor(f.numIconVertices/4),ws=Math.min(sn.length,Rn);let qs=D;const en=hn?this.icon.iconTransitioningVertexArray.uint16:null;for(let Nn=0;Nn0||f.numVerticalGlyphVertices>0;if(!ct)return{vertexOffsetDelta:ct?f.numHorizontalGlyphVertices+f.numVerticalGlyphVertices:0,hasChanges:!1};if(b.activeAppearanceIndex===S)return{vertexOffsetDelta:f.numHorizontalGlyphVertices+f.numVerticalGlyphVertices,hasChanges:!1};const xt=S>=0?K.appearances[S]:null;if(xt&&b.textShaping){const{appearanceTextOffset:kt,appearanceTextRotate:es,appearanceTextSize:Ct}=YJe(xt,K,T,q,xe,Me,Ne);b.fontScale=XJe(Ct,b.textScaleFactor);const Lt=xt.getUnevaluatedLayoutProperty("text-size");let Zt=this.textSizeData,Qt=Je,Cs=lt;xt.hasLayoutProperty("text-size")&&(Zt=g7(this.zoom,Lt,this.worldview,ht),Qt=this.textSizeData.kind==="composite"?this.textSizeData.minZoom:0,Cs=this.textSizeData.kind==="composite"?this.textSizeData.maxZoom:0);const Fs=b.textShaping.bottom-xe[1],on=b.textShaping.left-xe[0],sn=b.textShaping.right-xe[0];b.textShaping.top=kt[1]+(b.textShaping.top-xe[1]),b.textShaping.bottom=kt[1]+Fs,b.textShaping.left=kt[0]+on,b.textShaping.right=kt[0]+sn;const hn=Oet(0,b.textShaping,kt,K,!1,T,ce,this.allowVerticalPlacement,es),Rn=Ct&&Zt.kind==="composite"?Lt.possiblyEvaluate(new tr(Qt,{}),q).evaluate(T,pe,q):ze,ws=Ct&&Zt.kind==="composite"?Lt.possiblyEvaluate(new tr(Cs,{}),q).evaluate(T,pe,q):Ve,qs=QJe(xt.name,Zt,Ct,X,Rn,ws),en=Array.isArray(qs)?qs[1]:Ct,wn=0,Nn=1+(Math.min(G6,Math.round(en*jA))<<1);b.isUsingAppearanceTextVertexData||(b.isUsingAppearanceTextVertexData=!0,b.layoutBasedTextVertexData=this.text.snapshotSymbolVertexData(D,f.numHorizontalGlyphVertices+f.numVerticalGlyphVertices));for(let Pn=0;Pn0){const X=D[0],ce=[this.text.uboBinder,this.icon.uboBinder].filter(pe=>pe&&pe.hasStateDependentPaint(X));if(ce.length>0){const pe=new Set(Object.keys(f).map(xe=>{const Ne=Number(xe);return!isNaN(Ne)&&Number.isSafeInteger(Ne)&&String(Ne)===xe?Ne:xe}));for(const xe of ce)xe.updateFeatures(pe,X,b,K,S,f,q)}}}}updateZOffset(){const f=(D,F,q)=>{S+=F,S>D.length&&D.resize(S);for(let K=-F;K<0;K++)D.emplace(K+S,q)},b=(D,F,q)=>{T+=F,T>D.length&&D.resize(T);for(let K=-F;K<0;K++)D.emplace(K+T,q)};if(!this.zOffsetBuffersNeedUpload)return;this.zOffsetBuffersNeedUpload=!1;let S=0,T=0;for(let D=0;D0;if((q>0||K>0)&&(f(this.text.zOffsetVertexArray,q,ce),f(this.text.zOffsetVertexArray,K,ce)),pe){const{placedIconSymbolIndex:xe,verticalPlacedIconSymbolIndex:Ne}=F;xe>=0&&b(this.icon.zOffsetVertexArray,X,ce),Ne>=0&&b(this.icon.zOffsetVertexArray,F.numVerticalIconVertices,ce)}}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(f,b,S,T,D){!this.uploaded&&this.hasDebugData()&&(this.textCollisionBox.upload(f),this.iconCollisionBox.upload(f)),this.text.upload(f,this.sortFeaturesByY,!this.uploaded,this.text.programConfigurations.needsUpload,this.zOffsetBuffersNeedUpload,this.hasAppearances),this.hasAppearances===null&&(this.hasAppearances=this.layers.some(F=>F.appearances&&F.appearances.length>0)),this.icon.upload(f,this.sortFeaturesByY,!this.uploaded,this.icon.programConfigurations.needsUpload,this.zOffsetBuffersNeedUpload,this.hasAppearances),this.uploaded=!0}updateAppearances(f,b,S,T,D,F=!1){const q={hasLayoutChanges:!1,hasUboChanges:!1};if(!f||!S||!this.featureAppearanceData)return q;const K=b||{},X=this.icon.layoutVertexArray&&this.icon.layoutVertexArray.length>0&&this.icon.layoutVertexArray.arrayBuffer,ce=this.text.layoutVertexArray&&this.text.layoutVertexArray.length>0&&this.text.layoutVertexArray.arrayBuffer;if(!X&&!ce)return q;const pe=this.layers[0],xe=pe.layout;this.featureAppearances&&this.featureAppearances.appearancesVersion===pe.appearancesVersion||(this.featureAppearances=new oZt(pe.appearances,pe.appearancesVersion));const Ne=this.featureAppearances.update(T,F);if(Ne.kind==="no-changes")return q;let Me=1,ze=0,Ve=!1,Je=!1;if(X){const[es,Ct]=xe.get("icon-size-scale-range");Me=Jr(1,es,Ct)}let lt=1,ht=0,ct=!1;if(ce){const[es,Ct]=xe.get("text-size-scale-range");lt=Jr(1,es,Ct)}const xt=new Map;if(D&&S)for(const es of S){const Ct=D.getImage(es,pe.scope);if(Ct){const Lt=new Kp(es.toString());xt.set(Lt.toString(),Ct)}}const kt=[this.text.uboBinder,this.icon.uboBinder];for(let es=0;eshn.isActive({globals:T,feature:Cs,canonical:f,featureState:Qt})):-1;Fs=sn>=0?sn:-1}const on=Lt.activeAppearanceIndex!==Fs;if(ce){const sn=xe.get("text-size"),hn=this.textSizeData.kind==="composite"?this.textSizeData.minZoom:0,Rn=this.textSizeData.kind==="composite"?this.textSizeData.maxZoom:0,ws={canonical:f,layer:pe,featureState:Qt,availableImages:S,textScaleFactor:lt,imageMap:xt,layoutTextOffset:xe.get("text-offset").evaluate(Cs,Qt,f).map(en=>en*p7),layoutTextSize:sn.evaluate(Cs,Qt,f),layoutTextRotate:xe.get("text-rotate").evaluate(Cs,Qt,f),layoutMinZoomSize:sn.evaluate(Cs,{zoom:hn},f),layoutMaxZoomSize:sn.evaluate(Cs,{zoom:Rn},f),layoutTextSizeMinZoom:hn,layoutTextSizeMaxZoom:Rn},qs=this.updateSymbolInstanceTextVertices(Ct,Lt,Fs,Cs,ht,ws);ht+=qs.vertexOffsetDelta,ct=ct||qs.hasChanges}if(X){const sn={canonical:f,layer:pe,featureState:Qt,availableImages:S,globalProperties:T,iconScaleFactor:Me,layoutIconOffset:xe.get("icon-offset").evaluate(Cs,Qt,f),layoutIconSize:xe.get("icon-size").evaluate(Cs,Qt,f,S),layoutIconRotate:xe.get("icon-rotate").evaluate(Cs,Qt,f)},hn=this.updateSymbolInstanceIconVertices(Ct,Lt,Fs,Cs,ze,sn);ze+=hn.vertexOffsetDelta,Ve=Ve||hn.hasChanges}if(on){const sn=Ct.featureIndex,hn=T?T.brightness:null,Rn=Qt||{},ws=Fs>=0?pe.appearances[Fs]:null;for(const qs of kt)qs&&(qs.layer=pe,Je=qs.updateFeaturePaintForAppearance(sn,Cs,Rn,f,S,hn,ws)||Je)}Lt.activeAppearanceIndex=Fs}return Ve&&this.icon.layoutVertexBuffer&&this.icon.layoutVertexArray.arrayBuffer!==null&&this.icon.layoutVertexArray.length===this.icon.layoutVertexBuffer.length&&this.icon.layoutVertexBuffer.updateData(this.icon.layoutVertexArray),Ve&&this.icon.iconTransitioningVertexBuffer&&this.icon.iconTransitioningVertexArray.length>0&&this.icon.iconTransitioningVertexArray.length===this.icon.iconTransitioningVertexBuffer.length&&this.icon.iconTransitioningVertexBuffer.updateData(this.icon.iconTransitioningVertexArray),ct&&this.text.layoutVertexBuffer&&this.text.layoutVertexArray.arrayBuffer!==null&&this.text.layoutVertexArray.length===this.text.layoutVertexBuffer.length&&this.text.layoutVertexBuffer.updateData(this.text.layoutVertexArray),{hasLayoutChanges:Ve||ct,hasUboChanges:Je}}destroyDebugData(){this.textCollisionBox.destroy(),this.iconCollisionBox.destroy()}getProjection(){return this.projectionInstance||(this.projectionInstance=ise(this.projection)),this.projectionInstance}destroy(){this.text.destroy(),this.icon.destroy(),this.hasDebugData()&&this.destroyDebugData()}addToLineVertexArray(f,b){const S=this.lineVertexArray.length;if(f.segment!==void 0)for(const{x:T,y:D}of b)this.lineVertexArray.emplaceBack(T,D);return{lineStartIndex:S,lineLength:this.lineVertexArray.length-S}}addSymbols(f,b,S,T,D,F,q,K,X,ce,pe,xe,Ne,Me,ze,Ve,Je,lt){const ht=f.indexArray,ct=f.layoutVertexArray,xt=f.globeExtVertexArray,kt=lt,es=f.uboBinder?f.uboBinder.getCurrentBatchIndex():void 0,Ct=f.segments.prepareSegment(4*kt,ct,ht,this.canOverlap?F.sortKey:void 0,es),Lt=this.glyphOffsetArray.length,Zt=Ct.vertexLength,Qt=this.allowVerticalPlacement&&q===R4.vertical?Math.PI/2:0,Cs=F.text&&F.text.sections;let Fs=ct.length,on=-1;for(let Rn=0;Rn=0)){const Rn=4*sn;for(let ws=0;ws=0?b.rightJustifiedTextSymbolIndex:b.centerJustifiedTextSymbolIndex>=0?b.centerJustifiedTextSymbolIndex:b.leftJustifiedTextSymbolIndex>=0?b.leftJustifiedTextSymbolIndex:b.verticalPlacedTextSymbolIndex>=0?b.verticalPlacedTextSymbolIndex:T),F=Yte(this.textSizeData,f,D)/p7;return this.tilePixelRatio*F}getSymbolInstanceIconSize(f,b,S){const T=this.icon.placedSymbolArray.get(S),D=Yte(this.iconSizeData,f,T);return this.tilePixelRatio*D}_commitDebugCollisionVertexUpdate(f,b,S,T){f.emplaceBack(b,-S,-S,T),f.emplaceBack(b,S,-S,T),f.emplaceBack(b,S,S,T),f.emplaceBack(b,-S,S,T)}_updateTextDebugCollisionBoxes(f,b,S,T,D,F,q){for(let K=T;K0}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(f,b){const S=f.placedSymbolArray.get(b),T=S.vertexStartIndex+4*S.numGlyphs;for(let D=S.vertexStartIndex;DT[q]-T[K]||D[K]-D[q]),F}getSortedIndexesByZOffset(){if(!this.zOffsetSortDirty)return this.symbolInstanceIndexesSortedZOffset;if(!this.symbolInstanceIndexesSortedZOffset){this.symbolInstanceIndexesSortedZOffset=[];for(let f=0;fthis.symbolInstances.get(b).zOffset-this.symbolInstances.get(f).zOffset)}addToSortKeyRanges(f,b){const S=this.sortKeyRanges.at(-1);S&&S.sortKey===b?S.symbolInstanceEnd=f+1:this.sortKeyRanges.push({sortKey:b,symbolInstanceStart:f,symbolInstanceEnd:f+1})}sortFeatures(f){if(this.sortFeaturesByY&&this.sortedAngle!==f)if(this.text.segments.get().length>1||this.icon.segments.get().length>1)this.sortFeaturesByY=!1;else{this.symbolInstanceIndexes=this.getSortedSymbolIndexes(f),this.sortedAngle=f,this.text.indexArray.clear(),this.icon.indexArray.clear(),this.featureSortOrder=[];for(const b of this.symbolInstanceIndexes){const S=this.symbolInstances.get(b);this.featureSortOrder.push(S.featureIndex);const{rightJustifiedTextSymbolIndex:T,centerJustifiedTextSymbolIndex:D,leftJustifiedTextSymbolIndex:F,verticalPlacedTextSymbolIndex:q,placedIconSymbolIndex:K,verticalPlacedIconSymbolIndex:X}=S;T>=0&&this.addIndicesForPlacedSymbol(this.text,T),D>=0&&D!==T&&this.addIndicesForPlacedSymbol(this.text,D),F>=0&&F!==D&&F!==T&&this.addIndicesForPlacedSymbol(this.text,F),q>=0&&this.addIndicesForPlacedSymbol(this.text,q),K>=0&&this.addIndicesForPlacedSymbol(this.icon,K),X>=0&&this.addIndicesForPlacedSymbol(this.icon,X)}this.text.indexBuffer&&this.text.indexBuffer.updateData(this.text.indexArray),this.icon.indexBuffer&&this.icon.indexBuffer.updateData(this.icon.indexArray)}}}Vr(yse,"SymbolBucket",{omit:["layers","collisionBoxArray","compareText","features"]}),yse.addDynamicAttributes=W6;class Fet extends yMe{constructor(f,b,S){super(f,b,S),this.elevatedLayoutVertexArray=new Hn}upload(f){const b=this.uploaded;super.upload(f),!b&&this.elevatedLayoutVertexArray.length>0&&(this.elevatedLayoutVertexBuffer=f.createVertexBuffer(this.elevatedLayoutVertexArray,F1.members))}destroy(){this.elevatedLayoutVertexBuffer&&this.elevatedLayoutVertexBuffer.destroy(),super.destroy()}}Vr(Fet,"ElevatedFillBufferData");class z4{constructor(){this.portals=[]}static isOnBorder(f,b){return f<=0&&b<=0||f>=br&&b>=br}static evaluate(f){if(f.length===0)return new z4;let b=[];for(const K of f)b.push(...K.portals);if(b.length===0)return new z4;for(const K of b){const X=K.va,ce=K.vb;(z4.isOnBorder(X.x,ce.x)||z4.isOnBorder(X.y,ce.y))&&(K.type="border")}const S=b.filter(K=>K.type!=="unevaluated"),T=b.filter(K=>K.type==="unevaluated");if(T.length===0)return new z4;T.sort((K,X)=>K.hash===X.hash?K.isTunnel===X.isTunnel?0:K.isTunnel?-1:1:K.hashK.hashD!=="fill-tunnel-structure-color"),this.tunnelProgramConfigurations=new aN(b,{zoom:S,lut:T},D=>D!=="fill-bridge-guard-rail-color")}addVertices(f,b){const S=this.unevalVertices.length;for(let T=0;T=D.min.x&&pe.x<=D.max.x&&pe.y>=D.min.y&&pe.y<=D.max.y||xe.x>=D.min.x&&xe.x<=D.max.x&&xe.y>=D.min.y&&xe.y<=D.max.y||h7(pe,xe,q))||this.isOnBorder(pe.x,xe.x)||this.isOnBorder(pe.y,xe.y))continue;const Ne=z1.computeEdgeHash(this.unevalVertices[X],this.unevalVertices[ce]);let Me,ze=this.vertexHashLookup.get(z1.computePosHash(pe));ze!=null?Me=ze.next:(ze=this.vertexHashLookup.get(z1.computePosHash(xe)),Me=ze!=null?ze.prev:Ne),this.unevalEdges.push({polygonIdx:f,a:X,b:ce,hash:Ne,portalHash:Me,isTunnel:T,type:"unevaluated",featureInfo:F})}}addPortalCandidates(f,b,S,T,D){if(b.length!==0){this.vertexHashLookup.clear();for(const F of b){if(F.length===0)continue;const q=F[0];let K=z1.computeEdgeHash(q[q.length-2],q.at(-1));for(let X=0;X({vertexOffset:0,primitiveOffset:this.indexArray.length}),S=xe=>{xe.primitiveLength=this.indexArray.length-xe.primitiveOffset},T=new uZt(this.vertexPositions,this.vertexNormals,this.indexArray);this.prepareEdges(f.portals,this.unevalEdges);const D=b(),F=b(),q=b(),K=(xe,Ne)=>{xe.sort((ze,Ve)=>ze.type===Ne&&Ve.type!==Ne?-1:ze.type!==Ne&&Ve.type===Ne?1:0);const Me=xe.findIndex(ze=>ze.type!==Ne);return Me>=0?Me:xe.length};let X=0;this.unevalEdges.length>0&&(X=K(this.unevalEdges,"none"),this.constructBridgeStructures(T,this.unevalVertices,this.unevalHeights,this.unevalEdges,{min:0,max:X},this.tileToMeters)),S(q);const ce=b(),pe=b();if(this.unevalEdges.length>0){const xe=this.unevalEdges.splice(X),Ne=K(xe,"tunnel")+X;this.unevalEdges.push(...xe),this.constructTunnelStructures(T,this.unevalVertices,this.unevalHeights,this.unevalEdges,{min:0,max:X},{min:X,max:Ne})}S(ce),T.addTriangles(this.unevalTriangles,this.unevalVertices,this.unevalHeights),S(pe),T.addTriangles(this.unevalTunnelTriangles,this.unevalVertices,this.unevalHeights),S(F),T.addTriangles(this.unevalTunnelTriangles,this.unevalVertices,this.unevalHeights,4),S(D),this.maskSegments=lc.simpleSegment(0,pe.primitiveOffset,0,pe.primitiveLength),this.depthSegments=lc.simpleSegment(0,F.primitiveOffset,0,F.primitiveLength),this.renderableBridgeSegments=lc.simpleSegment(0,q.primitiveOffset,0,q.primitiveLength),this.renderableTunnelSegments=lc.simpleSegment(0,ce.primitiveOffset,0,ce.primitiveLength),this.shadowCasterSegments=lc.simpleSegment(0,D.primitiveOffset,0,D.primitiveLength)}update(f,b,S,T,D,F,q,K){this.bridgeProgramConfigurations.updatePaintArrays(f,b,D,S,T,F,q,K),this.tunnelProgramConfigurations.updatePaintArrays(f,b,D,S,T,F,q,K)}upload(f){this.vertexBuffer||this.vertexPositions.length===0||this.vertexNormals.length===0||this.indexArray.length===0||(this.vertexBuffer=f.createVertexBuffer(this.vertexPositions,Kk.members),this.vertexBufferNormal=f.createVertexBuffer(this.vertexNormals,tw.members),this.indexBuffer=f.createIndexBuffer(this.indexArray),this.bridgeProgramConfigurations.upload(f),this.tunnelProgramConfigurations.upload(f))}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(f,b,S,T,D){const F=(q,K)=>{for(let X=0;Xve(sn,b[hn].x,b[hn].y,S[hn]*K),pe=te(),xe=te(),Ne=te(),Me=te(),ze=te(),Ve=(sn,hn)=>{const Rn=q.get(z1.computePosHash(b[hn])),ws=Rn.from,qs=Rn.to;if(!ws||!qs)return;ce(pe,ws),ce(xe,hn),ce(Ne,qs),et(Me),at(pe,xe)||(wt(ze,xe,pe),Fe(Me,ze)),at(Ne,xe)||(wt(ze,Ne,xe),he(Me,Me,Fe(ze,ze)));const en=Ft(Me);return en>0?Be(sn,Me,1/en):void 0};let Je=Number.POSITIVE_INFINITY;this.sortSubarray(T,D.min,D.max,(sn,hn)=>sn.featureInfo.featureIndex-hn.featureInfo.featureIndex);const lt=te(),ht=te(),ct=te(),xt=te(),kt=te(),es=te(),Ct=te(),Lt=te(),Zt=te(),Qt=[te(),te(),te(),te()],Cs=[te(),te(),te(),te()],Fs=[{coord:new Kt(0,0),height:0},{coord:new Kt(0,0),height:0}],on=(sn,hn)=>sn>hn;for(let sn=D.min;snJe.featureInfo.featureIndex-lt.featureInfo.featureIndex;this.sortSubarray(T,D.min,D.max,K),this.sortSubarray(T,F.min,F.max,K);const X=Je=>Fe(Je,Je),ce=[{coord:new Kt(0,0),height:0},{coord:new Kt(0,0),height:0}],pe=(Je,lt)=>Jeq.hash===K.hash?K.polygonIdx-q.polygonIdx:K.hash>q.hash?1:-1);let S=0,T=0,D=0,F=b[S].polygonIdx;do T++,(T===b.length||b[S].hash!==b[T].hash)&&((T-S===1||b[T-1].polygonIdx!==F)&&(DX.portalHashce.hash?q++:ce.hash>X.portalHash?K++:(X.type=ce.type,q++)}}}isOnBorder(f,b){return f<=0&&b<=0||f>=br&&b>=br}addFeatureSection(f,b,S,T){return f!==b&&(b=f,S.push({featureIndex:f,vertexStart:T.getVertexCount()}),T.clearVertexLookup()),b}sortSubarray(f,b,S,T){const D=f.slice(b,S);D.sort(T),f.splice(b,D.length,...D)}static computeEdgeHash(f,b){return(f.y===b.y&&f.x>b.x||f.y>b.y)&&([f,b]=[b,f]),BigInt(z1.computePosHash(f))<<32n|BigInt(z1.computePosHash(b))}static computePosHash(f){return((65535&f.x)<<16|65535&f.y)>>>0}}class hZt{constructor(){this._valid=!1}reset(f){return this.feature=f,this._valid=!0,this._geometry=f.loadGeometry(),this._geometry.length!==0&&this._geometry[0].length!==0||(this._valid=!1),this}geometry(f,b){return this._valid&&f(b(this._geometry)),this}require(f,b,S){return this.get(f,!0,b,S)}optional(f,b,S){return this.get(f,!1,b,S)}success(){return this._valid}get(f,b,S,T){const D=Object.hasOwn(this.feature.properties,f)?+this.feature.properties[f]:void 0;return this._valid&&D!==void 0&&!Number.isNaN(D)?S(T?T(D):D):b&&(this._valid=!1),this}}class zet{constructor(f,b){this.featureFunc=f,this.vertexFunc=b}parseFeature(f,b,S){return this.featureFunc(f,b,S)}parseVertex(f,b,S){return this.vertexFunc(f,b,S)}}const mZt=new zet((w,f,b)=>w.reset(f).require(L4,S=>{b.id=S}).optional("fixed_height_relative",S=>{b.constantHeight=S},B4.decodeRelativeHeight).geometry(S=>{b.bounds=S},Ac).success(),(w,f,b)=>w.reset(f).require(L4,S=>{b.id=S}).require("elevation_idx",S=>{b.idx=S}).require("extent",S=>{b.extent=S}).require("height_relative",S=>{b.height=S},B4.decodeRelativeHeight).geometry(S=>{b.position=S},B4.getPoint).success()),fZt=new zet((w,f,b)=>w.reset(f).require(L4,S=>{b.id=S}).optional("fixed_height",S=>{b.constantHeight=S},B4.decodeMetricHeight).geometry(S=>{b.bounds=S},Ac).success(),(w,f,b)=>w.reset(f).require(L4,S=>{b.id=S}).require("elevation_idx",S=>{b.idx=S}).require("extent",S=>{b.extent=S}).require("height",S=>{b.height=S},B4.decodeMetricHeight).geometry(S=>{b.position=S},B4.getPoint).success());class B4{static getPoint(f){return jr(f[0][0].x,f[0][0].y)}static decodeRelativeHeight(f){return 1e-4*f*5}static decodeMetricHeight(f){return 1e-4*f}static getVersionSchema(f){return f?f==="1.0.1"?fZt:void 0:mZt}static parse(f){const b=[],S=[],T=f.length,D=new hZt;for(let F=0;F{return q.a0?Be(K,K,1/X):ve(K,0,0,1)}getSafeArea(){return this.safeArea}isTunnel(){return this.heightRange.max<=-5}getClosestEdge(f){if(this.edges.length===0)return;let b=0,S=Number.POSITIVE_INFINITY,T=0;const[D,F,q,K,X,ce,pe]=pZt;Ln(pe,f.x,f.y);const xe=new TYt(pe,null);for(let Ne=0;Ne0?Ar(K,q)/ct:0,kt=Jr(xt,0,1),es=Math.abs((xt-kt)*this.edgeProps[Ne].len);Qn(X,pe,Ve),Ln(ce,ze[1],-ze[0]);const Ct=es+Math.abs(Ar(X,ce));Ct=0;--F){const q=this.edges[F].a,K=this.edges[F].b,{position:X,height:ce,extent:pe}=this.vertices[q],{position:xe,height:Ne,extent:Me}=this.vertices[K],ze=this.vertexProps[q].dir,Ve=this.vertexProps[K].dir;if(ve(b,X[0]/f,X[1]/f,ce),ve(S,xe[0]/f,xe[1]/f,Ne),ve(T,ze[1],-ze[0],0),Be(T,T,pe),ve(D,Ve[1],-Ve[0],0),Be(D,D,Me),this.distSqLines(_e(b[0]+.5*T[0],b[1]+.5*T[1],b[2]+.5*T[2]),_e(S[0]-.5*D[0],S[1]-.5*D[1],S[2]-.5*D[2]),_e(b[0]-.5*T[0],b[1]-.5*T[1],b[2]-.5*T[2]),_e(S[0]+.5*D[0],S[1]+.5*D[1],S[2]+.5*D[2]))<=.0025000000000000005)continue;const Je=this.vertices.length,lt=Sr(un(),X,xe);this.vertices.push({position:En(lt,lt,.5),height:.5*(ce+Ne),extent:.5*(pe+Me),index:.5*((this.vertices[q].index!==void 0?this.vertices[q].index:q)+(this.vertices[K].index!==void 0?this.vertices[K].index:K))});const ht=Sr(un(),ze,Ve);this.vertexProps.push({dir:xn(ht,ht)}),this.edges.splice(F,1),this.edgeProps.splice(F,1),this.edges.push({a:q,b:Je}),this.edges.push({a:Je,b:K});const ct=Qn(un(),this.vertices[Je].position,X),xt=pr(ct),kt={vec:ct,dir:En(un(),ct,1/xt),len:xt};this.edgeProps.push(kt),this.edgeProps.push(kt)}}distSqLines(f,b,S,T){const D=Se(te(),b,f),F=Se(te(),T,S),q=Se(te(),f,S),K=Oe(D,D),X=Oe(D,F),ce=Oe(D,q),pe=Oe(F,F),xe=Oe(F,q),Ne=K*pe-X*X;if(Ne===0)return Ee(yt(D,S,T,Oe(q,F)/Oe(F,F)),f);const Me=(K*xe-X*ce)/Ne;return Ee(yt(D,f,b,(X*xe-ce*pe)/Ne),yt(F,S,T,Me))}static serialize(f,b){const S={id:f.id,heightRange:{min:f.heightRange.min,max:f.heightRange.max},safeArea:(T=f.safeArea,{min:{x:T.min.x,y:T.min.y},max:{x:T.max.x,y:T.max.y}})};var T;return f.constantHeight!=null?(S.constantHeight=f.constantHeight,S):f.vertices.length===0?(S.vertices=[],S.vertexProps=[],S.edges=[],S.edgeProps=[],S):(S.vertices=f.vertices.map(D=>({position:vse(D.position),height:D.height,extent:D.extent,index:D.index})),S.vertexProps=f.vertexProps.map(D=>({dir:vse(D.dir)})),S.edges=f.edges.map(D=>({a:D.a,b:D.b})),S.edgeProps=f.edgeProps.map(D=>({vec:vse(D.vec),dir:vse(D.dir),len:D.len})),S)}static deserialize(f){const b=function(T){return{min:new Kt(T.min.x,T.min.y),max:new Kt(T.max.x,T.max.y)}}(f.safeArea);if(f.constantHeight!=null)return new $4(f.id,b,f.constantHeight);if(!f.vertices||f.vertices.length===0){const T=Object.create($4.prototype);return T.id=f.id,T.constantHeight=void 0,T.heightRange={min:f.heightRange.min,max:f.heightRange.max},T.safeArea=b,T.vertices=[],T.vertexProps=[],T.edges=[],T.edgeProps=[],T}const S=Object.create($4.prototype);return S.id=f.id,S.constantHeight=void 0,S.heightRange={min:f.heightRange.min,max:f.heightRange.max},S.safeArea=b,S.vertices=f.vertices.map(T=>({position:bse(T.position),height:T.height,extent:T.extent,index:T.index})),S.vertexProps=(f.vertexProps||[]).map(T=>({dir:bse(T.dir)})),S.edges=(f.edges||[]).map(T=>({a:T.a,b:T.b})),S.edgeProps=(f.edgeProps||[]).map(T=>({vec:bse(T.vec),dir:bse(T.dir),len:T.len})),S}}class _7{constructor(f,b){this.zScale=1,this.xOffset=0,this.yOffset=0,f.equals(b)||(this.zScale=Math.pow(2,b.z-f.z),this.xOffset=(f.x*this.zScale-b.x)*br,this.yOffset=(f.y*this.zScale-b.y)*br)}pointTransform(f){return jr(f[0]*this.zScale+this.xOffset,f[1]*this.zScale+this.yOffset)}pointTransformInPlace(f){f[0]=f[0]*this.zScale+this.xOffset,f[1]=f[1]*this.zScale+this.yOffset}constantElevation(f,b){if(f.constantHeight!=null)return this.computeBiasedHeight(f.constantHeight,b)}pointElevation(f,b,S){const T=this.constantElevation(b,S);return T??(f.x=f.x*this.zScale+this.xOffset,f.y=f.y*this.zScale+this.yOffset,this.computeBiasedHeight(b.pointElevation(f),S))}computeBiasedHeight(f,b){return b<=0?f:f+b*Uo(0,b,f>=0?f:Math.abs(.5*f))}}function gZt(w){if(w===0)return[0,0,0];const f=P1(w);return[f(),f(),f()]}function $et(w,f){let b=0,S=w.length-1;for(;b<=S;){const T=b+S>>1;w[T].feature.idq.id===T);if(F&&S)return{tileId:S,feature:F}}if(!b||b.length===0)return;const D=$et(b,T);if(!(D<0)){if(S){for(let F=D;Ff?1:w0))return b;b=b.left}}return null}contains(f){for(var b=this._root,S=this._compare;b;){var T=S(f,b.key);if(T===0)return!0;b=T<0?b.left:b.right}return!1}remove(f){var b=this.find(f);if(!b)return!1;if(this.splay(b),b.left)if(b.right){var S=this.minNode(b.right);S.parent!==b&&(this.replace(S,S.right),S.right=b.right,S.right.parent=S),this.replace(b,S),S.left=b.left,S.left.parent=S}else this.replace(b,b.left);else this.replace(b,b.right);return this._size--,!0}removeNode(f){if(!f)return!1;if(this.splay(f),f.left)if(f.right){var b=this.minNode(f.right);b.parent!==f&&(this.replace(b,b.right),b.right=f.right,b.right.parent=b),this.replace(f,b),b.left=f.left,b.left.parent=b}else this.replace(f,f.left);else this.replace(f,f.right);return this._size--,!0}erase(f){var b=this.find(f);if(b){this.splay(b);var S=b.left,T=b.right,D=null;S&&(S.parent=null,D=this.maxNode(S),this.splay(D),this._root=D),T&&(S?D.right=T:this._root=T,T.parent=D),this._size--}}pop(){var f=this._root,b=null;if(f){for(;f.left;)f=f.left;b={key:f.key,data:f.data},this.remove(f.key)}return b}next(f){var b=f;if(b)if(b.right)for(b=b.right;b&&b.left;)b=b.left;else for(b=f.parent;b&&b.right===f;)f=b,b=b.parent;return b}prev(f){var b=f;if(b)if(b.left)for(b=b.left;b&&b.right;)b=b.right;else for(b=f.parent;b&&b.left===f;)f=b,b=b.parent;return b}forEach(f){for(var b=this._root,S=[],T=!1,D=0;!T;)b?(S.push(b),b=b.left):S.length>0?(f(b=S.pop(),D++),b=b.right):T=!0;return this}range(f,b,S,T){const D=[],F=this._compare;let q,K=this._root;for(;D.length!==0||K;)if(K)D.push(K),K=K.left;else{if(K=D.pop(),q=F(K.key,b),q>0)break;if(F(K.key,f)>=0&&S.call(T,K))return this;K=K.right}return this}keys(){for(var f=this._root,b=[],S=[],T=!1;!T;)f?(b.push(f),f=f.left):b.length>0?(f=b.pop(),S.push(f.key),f=f.right):T=!0;return S}values(){for(var f=this._root,b=[],S=[],T=!1;!T;)f?(b.push(f),f=f.left):b.length>0?(f=b.pop(),S.push(f.data),f=f.right):T=!0;return S}at(f){for(var b=this._root,S=[],T=!1,D=0;!T;)if(b)S.push(b),b=b.left;else if(S.length>0){if(b=S.pop(),D===f)return b;D++,b=b.right}else T=!0;return null}load(f=[],b=[],S=!1){if(this._size!==0)throw new Error("bulk-load: tree is not empty");const T=f.length;return S&&r6e(f,b,0,T-1,this._compare),this._root=n6e(null,f,b,0,T),this._size=T,this}min(){var f=this.minNode(this._root);return f?f.key:null}max(){var f=this.maxNode(this._root);return f?f.key:null}isEmpty(){return this._root===null}get size(){return this._size}static createTree(f,b,S,T,D){return new s6e(S,D).load(f,b,T)}}function n6e(w,f,b,S,T){const D=T-S;if(D>0){const F=S+Math.floor(D/2),q={key:f[F],data:b[F],parent:w};return q.left=n6e(q,f,b,S,F),q.right=n6e(q,f,b,F+1,T),q}return null}function r6e(w,f,b,S,T){if(b>=S)return;const D=w[b+S>>1];let F=b-1,q=S+1;for(;;){do F++;while(T(w[F],D)<0);do q--;while(T(w[q],D)>0);if(F>=q)break;let K=w[F];w[F]=w[q],w[q]=K,K=f[F],f[F]=f[q],f[q]=K}r6e(w,f,b,q,T),r6e(w,f,q+1,S,T)}const Uet=11102230246251565e-32,Iv=134217729,yZt=(3+8*Uet)*Uet;function a6e(w,f,b,S,T){let D,F,q,K,X=f[0],ce=S[0],pe=0,xe=0;ce>X==ce>-X?(D=X,X=f[++pe]):(D=ce,ce=S[++xe]);let Ne=0;if(peX==ce>-X?(F=X+D,q=D-(F-X),X=f[++pe]):(F=ce+D,q=D-(F-ce),ce=S[++xe]),D=F,q!==0&&(T[Ne++]=q);peX==ce>-X?(F=D+X,K=F-D,q=D-(F-K)+(X-K),X=f[++pe]):(F=D+ce,K=F-D,q=D-(F-K)+(ce-K),ce=S[++xe]),D=F,q!==0&&(T[Ne++]=q);for(;pe0:(S[0]-f[0])*(b[1]-f[1])-(b[0]-f[0])*(S[1]-f[1])>0}isAbove(f){return!this.isBelow(f)}isVertical(){return this.point[0]===this.otherEvent.point[0]}get inResult(){return this.resultTransition!==0}clone(){const f=new j7(this.point,this.left,this.otherEvent,this.isSubject,this.type);return f.contourId=this.contourId,f.resultTransition=this.resultTransition,f.prevInResult=this.prevInResult,f.isExteriorRing=this.isExteriorRing,f.inOut=this.inOut,f.otherInOut=this.otherInOut,f}}function Jk(w,f){return w[0]===f[0]&&w[1]===f[1]}function i6e(w,f,b){const S=function(T,D,F,q,K,X){const ce=(D-X)*(F-K),pe=(T-K)*(q-X),xe=ce-pe;if(ce===0||pe===0||ce>0!=pe>0)return xe;const Ne=Math.abs(ce+pe);return Math.abs(xe)>=33306690738754716e-32*Ne?xe:-function(Me,ze,Ve,Je,lt,ht,ct){let xt,kt,es,Ct,Lt,Zt,Qt,Cs,Fs,on,sn,hn,Rn,ws,qs,en,wn,Nn;const Pn=Me-lt,jn=Ve-lt,Wn=ze-ht,Kn=Je-ht;ws=Pn*Kn,Zt=Iv*Pn,Qt=Zt-(Zt-Pn),Cs=Pn-Qt,Zt=Iv*Kn,Fs=Zt-(Zt-Kn),on=Kn-Fs,qs=Cs*on-(ws-Qt*Fs-Cs*Fs-Qt*on),en=Wn*jn,Zt=Iv*Wn,Qt=Zt-(Zt-Wn),Cs=Wn-Qt,Zt=Iv*jn,Fs=Zt-(Zt-jn),on=jn-Fs,wn=Cs*on-(en-Qt*Fs-Cs*Fs-Qt*on),sn=qs-wn,Lt=qs-sn,w7[0]=qs-(sn+Lt)+(Lt-wn),hn=ws+sn,Lt=hn-ws,Rn=ws-(hn-Lt)+(sn-Lt),sn=Rn-en,Lt=Rn-sn,w7[1]=Rn-(sn+Lt)+(Lt-en),Nn=hn+sn,Lt=Nn-hn,w7[2]=hn-(Nn-Lt)+(sn-Lt),w7[3]=Nn;let Dr=function(si,La){let Oi=La[0];for(let bi=1;bi<4;bi++)Oi+=La[bi];return Oi}(0,w7),sr=22204460492503146e-32*ct;if(Dr>=sr||-Dr>=sr||(Lt=Me-Pn,xt=Me-(Pn+Lt)+(Lt-lt),Lt=Ve-jn,es=Ve-(jn+Lt)+(Lt-lt),Lt=ze-Wn,kt=ze-(Wn+Lt)+(Lt-ht),Lt=Je-Kn,Ct=Je-(Kn+Lt)+(Lt-ht),xt===0&&kt===0&&es===0&&Ct===0)||(sr=11093356479670487e-47*ct+yZt*Math.abs(Dr),Dr+=Pn*Ct+Kn*xt-(Wn*es+jn*kt),Dr>=sr||-Dr>=sr))return Dr;ws=xt*Kn,Zt=Iv*xt,Qt=Zt-(Zt-xt),Cs=xt-Qt,Zt=Iv*Kn,Fs=Zt-(Zt-Kn),on=Kn-Fs,qs=Cs*on-(ws-Qt*Fs-Cs*Fs-Qt*on),en=kt*jn,Zt=Iv*kt,Qt=Zt-(Zt-kt),Cs=kt-Qt,Zt=Iv*jn,Fs=Zt-(Zt-jn),on=jn-Fs,wn=Cs*on-(en-Qt*Fs-Cs*Fs-Qt*on),sn=qs-wn,Lt=qs-sn,B1[0]=qs-(sn+Lt)+(Lt-wn),hn=ws+sn,Lt=hn-ws,Rn=ws-(hn-Lt)+(sn-Lt),sn=Rn-en,Lt=Rn-sn,B1[1]=Rn-(sn+Lt)+(Lt-en),Nn=hn+sn,Lt=Nn-hn,B1[2]=hn-(Nn-Lt)+(sn-Lt),B1[3]=Nn;const yr=a6e(4,w7,4,B1,qet);ws=Pn*Ct,Zt=Iv*Pn,Qt=Zt-(Zt-Pn),Cs=Pn-Qt,Zt=Iv*Ct,Fs=Zt-(Zt-Ct),on=Ct-Fs,qs=Cs*on-(ws-Qt*Fs-Cs*Fs-Qt*on),en=Wn*es,Zt=Iv*Wn,Qt=Zt-(Zt-Wn),Cs=Wn-Qt,Zt=Iv*es,Fs=Zt-(Zt-es),on=es-Fs,wn=Cs*on-(en-Qt*Fs-Cs*Fs-Qt*on),sn=qs-wn,Lt=qs-sn,B1[0]=qs-(sn+Lt)+(Lt-wn),hn=ws+sn,Lt=hn-ws,Rn=ws-(hn-Lt)+(sn-Lt),sn=Rn-en,Lt=Rn-sn,B1[1]=Rn-(sn+Lt)+(Lt-en),Nn=hn+sn,Lt=Nn-hn,B1[2]=hn-(Nn-Lt)+(sn-Lt),B1[3]=Nn;const Ra=a6e(yr,qet,4,B1,Vet);ws=xt*Ct,Zt=Iv*xt,Qt=Zt-(Zt-xt),Cs=xt-Qt,Zt=Iv*Ct,Fs=Zt-(Zt-Ct),on=Ct-Fs,qs=Cs*on-(ws-Qt*Fs-Cs*Fs-Qt*on),en=kt*es,Zt=Iv*kt,Qt=Zt-(Zt-kt),Cs=kt-Qt,Zt=Iv*es,Fs=Zt-(Zt-es),on=es-Fs,wn=Cs*on-(en-Qt*Fs-Cs*Fs-Qt*on),sn=qs-wn,Lt=qs-sn,B1[0]=qs-(sn+Lt)+(Lt-wn),hn=ws+sn,Lt=hn-ws,Rn=ws-(hn-Lt)+(sn-Lt),sn=Rn-en,Lt=Rn-sn,B1[1]=Rn-(sn+Lt)+(Lt-en),Nn=hn+sn,Lt=Nn-hn,B1[2]=hn-(Nn-Lt)+(sn-Lt),B1[3]=Nn;const $a=a6e(Ra,Vet,4,B1,Het);return Het[$a-1]}(T,D,F,q,K,X,Ne)}(w[0],w[1],f[0],f[1],b[0],b[1]);return S>0?-1:S<0?1:0}function CA(w,f){const b=w.point,S=f.point;return b[0]>S[0]?1:b[0]S[1]?1:-1:function(T,D,F){return T.left!==D.left?T.left?1:-1:i6e(F,T.otherEvent.point,D.otherEvent.point)!==0?T.isBelow(D.otherEvent.point)?-1:1:!T.isSubject&&D.isSubject?1:-1}(w,f,b)}function AA(w,f,b){const S=new j7(f,!1,w,w.isSubject),T=new j7(f,!0,w.otherEvent,w.isSubject);return Jk(w.point,w.otherEvent.point)&&console.warn("what is that, a collapsed segment?",w),S.contourId=T.contourId=w.contourId,CA(T,w.otherEvent)>0&&(w.otherEvent.left=!0,T.left=!1),w.otherEvent.otherEvent=T,w.otherEvent=S,b.push(T),b.push(S),b}function _se(w,f){return w[0]*f[1]-w[1]*f[0]}function o6e(w,f){return w[0]*f[0]+w[1]*f[1]}function l6e(w,f,b){const S=function(K,X,ce,pe){const xe=[X[0]-K[0],X[1]-K[1]],Ne=[pe[0]-ce[0],pe[1]-ce[1]];function Me(es,Ct,Lt){return[es[0]+Ct*Lt[0],es[1]+Ct*Lt[1]]}const ze=[ce[0]-K[0],ce[1]-K[1]];let Ve=_se(xe,Ne),Je=Ve*Ve;const lt=o6e(xe,xe);if(Je>0){const es=_se(ze,Ne)/Ve;if(es<0||es>1)return null;const Ct=_se(ze,xe)/Ve;return Ct<0||Ct>1?null:es===0||es===1?[Me(K,es,xe)]:Ct===0||Ct===1?[Me(ce,Ct,Ne)]:[Me(K,es,xe)]}if(Ve=_se(ze,xe),Je=Ve*Ve,Je>0)return null;const ht=o6e(xe,ze)/lt,ct=ht+o6e(xe,Ne)/lt,xt=Math.min(ht,ct),kt=Math.max(ht,ct);return xt<=1&&kt>=0?xt===1?[Me(K,xt>0?xt:0,xe)]:kt===0?[Me(K,kt<1?kt:1,xe)]:[Me(K,xt>0?xt:0,xe),Me(K,kt<1?kt:1,xe)]:null}(w.point,w.otherEvent.point,f.point,f.otherEvent.point),T=S?S.length:0;if(T===0||T===1&&(Jk(w.point,f.point)||Jk(w.otherEvent.point,f.otherEvent.point))||T===2&&w.isSubject===f.isSubject)return 0;if(T===1)return!Jk(w.point,S[0])&&!Jk(w.otherEvent.point,S[0])&&AA(w,S[0],b),!Jk(f.point,S[0])&&!Jk(f.otherEvent.point,S[0])&&AA(f,S[0],b),1;const D=[];let F=!1,q=!1;return Jk(w.point,f.point)?F=!0:CA(w,f)===1?D.push(f,w):D.push(w,f),Jk(w.otherEvent.point,f.otherEvent.point)?q=!0:CA(w.otherEvent,f.otherEvent)===1?D.push(f.otherEvent,w.otherEvent):D.push(w.otherEvent,f.otherEvent),F&&q||F?(f.type=1,w.type=f.inOut===w.inOut?2:3,F&&!q&&AA(D[1].otherEvent,D[0].point,b),2):q?(AA(D[0],D[1].point,b),3):D[0]!==D[3].otherEvent?(AA(D[0],D[1].point,b),AA(D[1],D[2].point,b),3):(AA(D[0],D[1].point,b),AA(D[3].otherEvent,D[2].point,b),3)}function vZt(w,f){if(w===f)return 0;if(i6e(w.point,w.otherEvent.point,f.point)!==0||i6e(w.point,w.otherEvent.point,f.otherEvent.point)!==0)return Jk(w.point,f.point)?w.isBelow(f.otherEvent.point)?-1:1:w.point[0]===f.point[0]?w.point[1](f.contourId??0)?1:-1}return CA(w,f)===1?1:-1}class bZt{constructor(){this.points=[],this.holeIds=[],this.holeOf=null,this.depth=null}isExterior(){return this.holeOf==null}}function _Zt(w,f,b,S){let T,D=w+1,F=f[w].point;const q=f.length;for(DS;)D--;return D}function wZt(w,f,b){const S=new bZt;if(w.prevInResult!=null){const T=w.prevInResult,D=T.outputContourId;if(T.resultTransition>0){const F=f[D];if(F.holeOf!=null){const q=F.holeOf;f[q].holeIds.push(b),S.holeOf=q,S.depth=f[D].depth}else f[D].holeIds.push(b),S.holeOf=D,S.depth=f[D].depth+1}else S.holeOf=null,S.depth=f[D].depth}else S.holeOf=null,S.depth=0;return S}const Wet=Math.max,Ket=Math.min;let wse=0;function Yet(w,f,b,S,T,D){let F,q,K,X,ce,pe;for(F=0,q=w.length-1;F0?pe.left=!0:ce.left=!0;const xe=K[0],Ne=K[1];T[0]=Ket(T[0],xe),T[1]=Ket(T[1],Ne),T[2]=Wet(T[2],xe),T[3]=Wet(T[3],Ne),S.push(ce),S.push(pe)}}const jse=[];function Zet(w,f,b){let S=w,T=f;typeof w[0][0][0]=="number"&&(S=[w]),typeof f[0][0][0]=="number"&&(T=[f]);let D=function(xe,Ne,Me){let ze=null;return xe.length*Ne.length===0&&(Me===0?ze=jse:Me===2?ze=xe:(Me===1||Me===3)&&(ze=xe.length===0?Ne:xe)),ze}(S,T,b);if(D)return D===jse?null:D;const F=[1/0,1/0,-1/0,-1/0],q=[1/0,1/0,-1/0,-1/0],K=function(xe,Ne,Me,ze,Ve){const Je=new fp(void 0,CA);let lt,ht,ct,xt,kt,es;for(ct=0,xt=xe.length;ctze[2]||ze[0]>Me[2]||Me[1]>ze[3]||ze[1]>Me[3])&&(Ve===0?Je=jse:Ve===2?Je=xe:(Ve===1||Ve===3)&&(Je=xe.concat(Ne))),Je}(S,T,F,q,b),D)return D===jse?null:D;const X=function(xe,Ne,Me,ze,Ve,Je){const lt=new s6e(vZt),ht=[],ct=Math.min(ze[2],Ve[2]);let xt,kt,es;for(;xe.length!==0;){let Ct=xe.pop();if(ht.push(Ct),Je===0&&Ct.point[0]>ct||Je===2&&Ct.point[0]>ze[2])break;if(Ct.left){kt=xt=lt.insert(Ct),es=lt.minNode(),xt=xt!==es?lt.prev(xt):null,kt=lt.next(kt);const Lt=xt?xt.key:null;let Zt;if(NH(Ct,Lt,Je),kt&&l6e(Ct,kt.key,xe)===2&&(NH(Ct,Lt,Je),NH(kt.key,Ct,Je)),xt&&l6e(xt.key,Ct,xe)===2){let Qt=xt;Qt=Qt!==es?lt.prev(Qt):null,Zt=Qt?Qt.key:null,NH(Lt,Zt,Je),NH(Ct,Lt,Je)}}else Ct=Ct.otherEvent,kt=xt=lt.find(Ct),xt&&kt&&(xt=xt!==es?lt.prev(xt):null,kt=lt.next(kt),lt.remove(Ct),kt&&xt&&l6e(xt.key,kt.key,xe))}return ht}(K,0,0,F,q,b),ce=function(xe){let Ne,Me;const ze=function(lt){let ht,ct,xt,kt,es;const Ct=[];for(ct=0,xt=lt.length;ct{Ve[es]=!0,es=ze.length)&&ze[xt];);Je.push(ht)}return Je}(X),pe=[];for(let xe=0;xe0&&(T=Zet(T,D,2)),Qet(T,1/65536,.001)}function c6e(w,f=1){return[w.map(b=>b.map(S=>[S.x*f,S.y*f]))]}function Xet(w,f){const b=Math.floor(w)+.5;return Math.abs(w-b)<=f?Math.round(b):Math.round(w)}class kZt{constructor(f){this.xs=[],this.ys=[],this.ixs=[],this.iys=[],this.buckets=new Map,this.tolerance=f}canonicalize(f,b){const S=this.tolerance,T=Math.floor(f/S),D=Math.floor(b/S);for(let K=-1;K<=1;K++){const X=this.buckets.get(T+K);if(X)for(let ce=-1;ce<=1;ce++){const pe=X.get(D+ce);if(pe){for(const xe of pe)if(Math.abs(this.xs[xe]-f)<=S&&Math.abs(this.ys[xe]-b)<=S){const Ne=this.ixs[xe],Me=this.iys[xe];return this.xs[xe]===f&&this.ys[xe]===b||this.store(f,b,Ne,Me,T,D),[Ne,Me]}}}}const F=Xet(f,S),q=Xet(b,S);return this.store(f,b,F,q,T,D),[F,q]}store(f,b,S,T,D,F){const q=this.xs.length;this.xs.push(f),this.ys.push(b),this.ixs.push(S),this.iys.push(T);let K=this.buckets.get(D);K||(K=new Map,this.buckets.set(D,K));let X=K.get(F);X||(X=[],K.set(F,X)),X.push(q)}}function Qet(w,f=1,b){const S=b!=null?new kZt(b):null;return w.map(T=>T.map((D,F)=>{const q=D.map(K=>{const X=K[0]*f,ce=K[1]*f;if(S){const[pe,xe]=S.canonicalize(X,ce);return new Kt(pe,xe)}return new Kt(Math.round(X),Math.round(ce))});return F>0&&q.reverse(),q}))}class d6e{constructor(){this.frcCoverage=new Set,this.featureTriSegments=[],this.frcPerLevel=new Map,this.frcNonRoadSegments=new lc}empty(){return this.frcCoverage.size===0}}function Jet(w,f,b){if(w.frcCoverage.size===0||w.featureTriSegments.length===0)return;const S=b.get(),T=f.uint16,D=[];w.featureTriSegments.sort((pe,xe)=>pe.segIdx!==xe.segIdx?pe.segIdx-xe.segIdx:pe.frc===null&&xe.frc===null?0:pe.frc===null?-1:xe.frc===null?1:xe.frc-pe.frc);const F=new Map;let q=0,K=w.featureTriSegments[0].frc,X={vertexOffset:S[q].vertexOffset,primitiveOffset:0,vertexLength:S[q].vertexLength,primitiveLength:0,vaos:{},sortKey:void 0};const ce=()=>{X.primitiveLength>0&&(F.has(K)||F.set(K,[]),F.get(K).push({...X}))};for(const pe of w.featureTriSegments){pe.segIdx!==q&&(ce(),q=pe.segIdx,K=pe.frc,X={vertexOffset:S[q].vertexOffset,primitiveOffset:D.length/3,vertexLength:S[q].vertexLength,primitiveLength:0,vaos:{},sortKey:void 0}),pe.frc!==K&&(ce(),K=pe.frc,X={...X,primitiveOffset:D.length/3,primitiveLength:0});for(let xe=pe.start;xe0?D.length-1:0,frc:T})}buildFrcSegments(f){this.frcData&&!this.frcData.empty()&&Jet(this.frcData,f.bufferData.indexArray,f.bufferData.triangleSegments)}handleFeature(f,b,S,T,D,F){const q=new Array;if(!this.elevationMode)return!1;const K=wH(f,D,void 0,T);if(!K)return!1;{const ce=this.clipPolygonsToTile(b,1);ce.length>0&&q.push({polygons:ce,elevationFeature:K.feature,elevationTileID:K.tileId})}const X={guardRailEnabled:F.layers[0].layout.get("fill-construct-bridge-guard-rail").evaluate(f,{},T),featureIndex:S};for(const ce of q)if(ce.elevationFeature){if(this.elevationMode==="hd-road-base"){this.elevatedStructures||(this.elevatedStructures=new z1(ce.elevationTileID,F.layers,F.zoom,F.lut));const xe=ce.elevationFeature.isTunnel();let Ne=0;Object.hasOwn(f.properties,zJe)&&(Ne=+f.properties[zJe]),this.elevatedStructures.addPortalCandidates(ce.elevationFeature.id,ce.polygons,xe,ce.elevationFeature,Ne)}ce.elevationFeature.constantHeight==null&&(ce.polygons=this.prepareElevatedPolygons(ce.polygons,ce.elevationFeature,ce.elevationTileID));const pe=new _7(T,ce.elevationTileID);this.addElevatedGeometry(F,ce.polygons,pe,ce.elevationFeature,this.elevationMode==="hd-road-base"?0:.05,S,X)}return!0}populatePaintArrays(f,b,S,T,D,F,q){this.elevationBufferData&&this.elevationBufferData.populatePaintArrays(f,b,S,T,D,F,q)}update(f,b,S,T,D,F,q,K){this.elevationBufferData&&this.elevationBufferData.update(f,b,S,T,D,F,q,K),this.elevatedStructures&&this.elevatedStructures.update(f,b,S,T,D,F,q,K)}updateExpressions(f){this.elevationBufferData&&this.elevationBufferData.programConfigurations.updateExpressions(f),this.elevatedStructures&&(this.elevatedStructures.bridgeProgramConfigurations.updateExpressions(f),this.elevatedStructures.tunnelProgramConfigurations.updateExpressions(f))}upload(f){this.elevationBufferData&&this.elevationBufferData.upload(f),this.elevatedStructures&&this.elevatedStructures.upload(f)}destroy(){this.elevationBufferData&&this.elevationBufferData.destroy(),this.elevatedStructures&&this.elevatedStructures.destroy()}getUnevaluatedPortalGraph(){return this.elevatedStructures?this.elevatedStructures.unevaluatedPortals:void 0}setEvaluatedPortalGraph(f,b,S,T,D,F){this.elevatedStructures&&(this.elevatedStructures.construct(f),this.elevatedStructures.populatePaintArrays(b,S,T,D,F))}addElevatedGeometry(f,b,S,T,D,F,q){const K={elevation:T,elevationSampler:S,bias:D,index:F,featureInfo:q},[X,ce]=f.addGeometry(b,this.elevationBufferData,K,this.elevatedStructures);this.elevationBufferData.heightRange==null?this.elevationBufferData.heightRange={min:X,max:ce}:(this.elevationBufferData.heightRange.min=Math.min(this.elevationBufferData.heightRange.min,X),this.elevationBufferData.heightRange.max=Math.max(this.elevationBufferData.heightRange.max,ce))}prepareElevatedPolygons(f,b,S){const T=1/mt(S),D=[];for(const F of f){const q=NZt(F,new Bet(b,T),.1);D.push(...q)}return D}clipPolygonsToTile(f,b){const S=-b,T=-b,D=br+b,F=br+b;let q=0;const K=[],X=[];for(;q=S&&Ne.max.x<=D&&Ne.min.y>=T&&Ne.max.y<=F?K:X).push(xe)}if(K.length===f.length)return f;const ce=[new Kt(S,T),new Kt(D,T),new Kt(D,F),new Kt(S,F),new Kt(S,T)],pe=K;for(const xe of X)pe.push(...jZt(xe,ce));return pe}}function CZt(w,f){return w.nextPoint.sub(f.at(-2)).unit()}function AZt(w,f){return f[1].sub(w.prevPoint).unit()}Vr(ett,"FillHDExtension"),Vr(z1,"ElevatedStructures");class ttt{constructor(f,b){this.elevationEnabled=f,this.hasDeferredElevationFeatures=!1,b&&(this.frcData=new d6e)}isEmpty(){const f=!this.elevationEnabled||this.heightRange===void 0,b=!this.frcData||this.frcData.empty();return f&&b}trackFeatureFrc(f){if(!this.frcData)return null;const b=Nse(f||{});return b!==null&&this.frcData.frcCoverage.add(b),b}recordFeatureRange(f,b,S,T){if(!this.frcData||S<=b)return;const D=f.segments.get();this.frcData.featureTriSegments.push({start:3*b,end:3*S,segIdx:D.length>0?D.length-1:0,frc:T})}buildFrcSegments(f){this.frcData&&!this.frcData.empty()&&Jet(this.frcData,f.indexArray,f.segments)}handleFeature(f,b,S,T,D,F,q,K,X,ce,pe){if(!this.elevationEnabled)return!1;if(!pe.terrainEnabled){const Ve=wH(f,T,D?D.registry:void 0,S),Je=f.properties!=null&&Object.hasOwn(f.properties,L4)&&!Number.isNaN(+f.properties[L4]);if(!Ve&&Je&&F&&(!D||!D.allProvidersReady))return this.hasDeferredElevationFeatures=!0,!0;if(Ve){let lt=Ve.feature,ht=Ve.tileId;if(!Ve.tileId.equals(S)){const kt=this.mergedFeatureCache?this.mergedFeatureCache.get(lt.id):void 0;if(kt)lt=kt,ht=S;else{const es=function(Ct,Lt,Zt){if(!Ct.properties||!Lt||Lt.length===0)return[];const Qt=+Ct.properties[L4];if(Number.isNaN(Qt))return[];const Cs=$et(Lt,Qt);if(Cs<0)return[];const Fs=[];for(let on=Cs;on1&&(lt=function(Ct,Lt){const Zt=Lt.slice().sort((ws,qs)=>qs.tileId.z-ws.tileId.z),Qt=new Kt(Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY),Cs=new Kt(Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY),Fs=[];for(const ws of Zt){const qs=new _7(ws.tileId,Ct);for(const wn of ws.feature.vertices)Fs.push({position:qs.pointTransform(wn.position),height:wn.height,extent:wn.extent,index:wn.index});const en=ws.feature.safeArea;K6[0]=en.min.x,K6[1]=en.min.y,Y6[0]=en.max.x,Y6[1]=en.max.y,qs.pointTransformInPlace(K6),qs.pointTransformInPlace(Y6),Qt.x=Math.min(Qt.x,K6[0],Y6[0]),Qt.y=Math.min(Qt.y,K6[1],Y6[1]),Cs.x=Math.max(Cs.x,K6[0],Y6[0]),Cs.y=Math.max(Cs.y,K6[1],Y6[1])}const on={min:Qt,max:Cs};if(Zt[0].feature.constantHeight!=null)return new $4(Zt[0].feature.id,on,Zt[0].feature.constantHeight);Fs.sort((ws,qs)=>ws.index-qs.index);const sn=[];for(const ws of Fs)sn.length!==0&&sn.at(-1).index===ws.index||sn.push(ws);const hn=[];for(let ws=1;ws>1,pe.layoutVertexArray.int16[6*Zt+1]>>1),Cs=Ct.pointElevation(Qt,lt,.05);this.updateHeightRange(Cs),Zt0?lt.parentIndex:null)}return pe.fillNonElevatedRoadSegment(Ne),!0}prepareElevatedLines(f,b,S,T){if(b.constantHeight!=null)return f;const D=[],F=1/mt(T),q=S.equals(T)?null:new _7(S,T);for(const K of f)rYt(K,new Bet(b,F,q),0,D);return D}updateHeightRange(f){this.heightRange?(this.heightRange.min=Math.min(this.heightRange.min,f),this.heightRange.max=Math.max(this.heightRange.max,f)):this.heightRange={min:f,max:f}}endPopulate(){this.mergedFeatureCache=void 0}}Vr(ttt,"LineHDExtension");class stt{constructor(){this.elevatedLayoutVertexArray=new Hn,this.hasElevation=!1}beginFeature(f,b,S){const T=wH(f,b,void 0,S);this.currentFeatureElevation=T?T.feature:void 0}writeVertexQuad(f,b){const S=this.currentFeatureElevation?this.currentFeatureElevation.pointElevation(new Kt(f,b)):0;this.hasElevation=this.hasElevation||S!==0;for(let T=0;T<4;T++)this.elevatedLayoutVertexArray.emplaceBack(S)}finalize(){this.hasElevation||(this.elevatedLayoutVertexArray=void 0)}upload(f){this.elevatedLayoutVertexArray&&!this.elevatedLayoutVertexBuffer&&(this.elevatedLayoutVertexBuffer=f.createVertexBuffer(this.elevatedLayoutVertexArray,cYt.members))}destroy(){this.elevatedLayoutVertexBuffer&&this.elevatedLayoutVertexBuffer.destroy()}}Vr(stt,"CircleHDExtension");const kse=(w,f,b,S)=>{for(let T=0;T=this.elevationFeatures.length)return!1;const S=this.elevationFeatureTileIds[f];return S!=null&&!S.equals(b)}getRoadFeatureHeightAtAnchor(f,b,S){if(f===65535||f>=this.elevationFeatures.length)return null;const T=this.elevationFeatures[f],D=this.elevationFeatureTileIds[f];return D.equals(S)?T.pointElevation(b):this.getElevationFeatureSampler(S,D).pointElevation(new Kt(b.x,b.y),T,0)}sampleRoadFeatureHeight(f,b,S){const T=this.getRoadFeatureHeightAtAnchor(f,b,S);return T===null?void 0:T}clearWorkerState(){this.consumerCanonical=void 0,this.elevationParams=null,this.crossSourceElevationEnabled=!1,this.terrainEnabled=!1,this.elevationFeatureIdToIndex.clear()}updateRoadElevation(f,b){if(this.elevationStateComplete)return;this.elevationStateComplete=!0,f.hasAnyZOffset=!1;let S=!1;const T=mt(b),D=1/T;let F=!1,q=!1;for(let K=0;K0||Ne>0,Je=Me>0,lt=X.elevationFeatureIndex,ht=lt=0&&kse(f.icon.orientationVertexArray,Me,ce,pe),xt>=0&&kse(f.icon.orientationVertexArray,ze,ce,pe)}}F||(f.text.orientationVertexArray=void 0),q||(f.icon.orientationVertexArray=void 0),S&&(f.zOffsetBuffersNeedUpload=!0,f.zOffsetSortDirty=!0)}getRoadFeatureHeightForPlacedSymbol(f,b,S,T,D){const F=f.symbolInstances.get(b.symbolInstanceIndices[S]);return this.getRoadFeatureHeightAtAnchor(F.elevationFeatureIndex,T,D)}getElevationFeatureForPlacedSymbol(f,b,S){const T=f.symbolInstances.get(b.symbolInstanceIndices[S]).elevationFeatureIndex;if(T{const Me=this.getRoadFeatureHeightForPlacedSymbol(f,b,S,Ne,T.canonical);return function(ze,Ve,Je,lt,ht,ct){const xt=lt.upVector(Ve,Je.x,Je.y);return Be(xt,xt,ze*lt.upVectorScale(Ve,ht,ct).metersToTile),[xt[0],xt[1],xt[2]]}(Me!==null?Me:0,T.canonical,Ne,q,K,X)},elevation:F,elevationFeature:null}:{getElevation:D,elevation:F,elevationFeature:pe}}}Vr(ntt,"SymbolHDExtension",{omit:["consumerCanonical","elevationParams","crossSourceElevationEnabled","terrainEnabled","hasDeferredElevationFeatures","elevationFeatureIdToIndex"]});let iN=null,Sse=null,h6e=null,Cse=null;const rtt=5120,att=5121,itt=5122,ott=5123,ltt=5125,ctt=5126,Ase={[rtt]:Int8Array,[att]:Uint8Array,[itt]:Int16Array,[ott]:Uint16Array,[ltt]:Uint32Array,[ctt]:Float32Array},EZt={[rtt]:"DT_INT8",[att]:"DT_UINT8",[itt]:"DT_INT16",[ott]:"DT_UINT16",[ltt]:"DT_UINT32",[ctt]:"DT_FLOAT32"},kH={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16};function dtt(w,f,b){const S=b.json.bufferViews.length,T=b.buffers.length;f.bufferView=S,b.json.bufferViews[S]={buffer:T,byteLength:w.byteLength},b.buffers[T]=w}const m6e="KHR_draco_mesh_compression";function TZt(w,f){const b=w.extensions&&w.extensions[m6e];if(!b)return;const S=new iN.Decoder,T=ftt(f,b.bufferView),D=new iN.Mesh;if(!S.DecodeArrayToMesh(T,T.byteLength,D))throw new Error("Failed to decode Draco mesh");const F=f.json.accessors[w.indices],q=Ase[F.componentType],K=F.count*q.BYTES_PER_ELEMENT,X=iN._malloc(K);q===Uint16Array?S.GetTrianglesUInt16Array(D,K,X):S.GetTrianglesUInt32Array(D,K,X),dtt(iN.memory.buffer.slice(X,X+K),F,f),iN._free(X);for(const ce of Object.keys(b.attributes)){const pe=S.GetAttributeByUniqueId(D,b.attributes[ce]),xe=f.json.accessors[w.attributes[ce]],Ne=EZt[xe.componentType],Me=xe.count*kH[xe.type]*Ase[xe.componentType].BYTES_PER_ELEMENT,ze=iN._malloc(Me);S.GetAttributeDataArrayForAllPoints(D,pe,iN[Ne],Me,ze),dtt(iN.memory.buffer.slice(ze,ze+Me),xe,f),iN._free(ze)}S.destroy(),D.destroy(),delete w.extensions[m6e]}const Ese="EXT_meshopt_compression";function MZt(w,f){if(!w.extensions||!w.extensions[Ese])return;const b=w.extensions[Ese],S=new Uint8Array(f.buffers[b.buffer],b.byteOffset||0,b.byteLength||0),T=new Uint8Array(b.count*b.byteStride);h6e.decodeGltfBuffer(T,b.count,b.byteStride,S,b.mode,b.filter),w.buffer=f.buffers.length,w.byteOffset=0,f.buffers[w.buffer]=T.buffer,delete w.extensions[Ese]}const utt=1179937895,htt=new TextDecoder("utf8");function mtt(w,f){return new URL(w,f).href}async function PZt(w,f,b,S,T){const D=await fetch(mtt(w.uri,S),{signal:T}),F=await D.arrayBuffer();f.buffers[b]=F}function ftt(w,f){const b=w.json.bufferViews[f];return new Uint8Array(w.buffers[b.buffer],b.byteOffset||0,b.byteLength)}async function IZt(w,f,b,S,T){if(w.uri){const D=mtt(w.uri,S),F=await fetch(D,{signal:T}),q=await F.blob(),K=await createImageBitmap(q);f.images[b]=K}else if(w.bufferView!==void 0){const D=ftt(f,w.bufferView),F=new Blob([D],{type:w.mimeType}),q=await createImageBitmap(F);f.images[b]=q}}async function ptt(w,f=0,b,S){const T={json:null,images:[],buffers:[]};if(new Uint32Array(w,f,1)[0]===utt){const Ne=new Uint32Array(w,f);let Me=2;const ze=(Ne[Me++]>>2)-3,Ve=Ne[Me++]>>2;if(Me++,T.json=JSON.parse(htt.decode(Ne.subarray(Me,Me+Ve))),Me+=Ve,Me>>0,Math.ceil(1.2*ht)),xt=Math.ceil((ct-ht)/65536);try{return ze.grow(xt),Ve(),!0}catch{return!1}},b:Je}}).then(lt=>{const{Rb:ht,Qb:ct,P:xt,T:kt,X:es,Ja:Ct,La:Lt,Qa:Zt,Va:Qt,Wa:Cs,eb:Fs,jb:on,f:sn,e:hn,yb:Rn,zb:ws,Ab:qs,Bb:en,Db:wn,Gb:Nn}=lt.instance.exports;ze=hn;const Pn=(()=>{let jn=0,Wn=0,Kn=0,Dr=0;return sr=>{Kn&&(ht(Dr),ht(jn),Wn+=Kn,Kn=jn=0),jn||(Wn+=128,jn=ct(Wn));const yr=sr.length+7&-8;let Ra=jn;yr>=Wn&&(Kn=yr,Ra=Dr=ct(yr));for(let $a=0;$a{iN=Ne,Sse=null})),Sse}()),xe&&ce.push(function(){var Ne;if(!h6e)return Cse!=null||(Cse=(Ne=fetch(ps()),WebAssembly.instantiateStreaming(Ne,{}).then(Me=>{const{sbrk:ze,memory:Ve,meshopt_decodeVertexBuffer:Je,meshopt_decodeIndexBuffer:lt,meshopt_decodeIndexSequence:ht,meshopt_decodeFilterOct:ct,meshopt_decodeFilterQuat:xt,meshopt_decodeFilterExp:kt}=Me.instance.exports,es={ATTRIBUTES:Je,TRIANGLES:lt,INDICES:ht},Ct={OCTAHEDRAL:ct,QUATERNION:xt,EXPONENTIAL:kt};return Me.instance.exports.__wasm_call_ctors(),{decodeGltfBuffer(Lt,Zt,Qt,Cs,Fs,on){const sn=Zt+3&-4,hn=ze(sn*Qt),Rn=ze(Cs.length),ws=new Uint8Array(Ve.buffer);ws.set(Cs,Rn);const qs=es[Fs](hn,Zt,Qt,Rn,Cs.length);if(qs===0&&Ct[on]&&Ct[on](hn,sn,Qt),Lt.set(ws.subarray(hn,hn+Zt*Qt)),ze(hn-ze(0)),qs!==0)throw new Error(`Malformed buffer data: ${qs}`)}}})).then(Me=>{h6e=Me,Cse=null})),Cse}()),F)for(let Ne=0;Nepe.cellIdx-xe.cellIdx||pe.triIdx-xe.triIdx);let ce=0;for(;cethis.max.x||this.min.x>f.x||f.y>this.max.y||this.min.y>f.y)return;const S=eS(f.x-this.min.x,this.xScale,this.cellsX),T=eS(f.y-this.min.y,this.yScale,this.cellsY),D=this.cells[T*this.cellsX+S];if(D){this._lazyInitLookup();for(let F=0;Fthis.max.x||this.min.x>b.x||f.y>this.max.y||this.min.y>b.y)return;this._lazyInitLookup();const T=eS(f.x-this.min.x,this.xScale,this.cellsX),D=eS(b.x-this.min.x,this.xScale,this.cellsX),F=eS(f.y-this.min.y,this.yScale,this.cellsY),q=eS(b.y-this.min.y,this.yScale,this.cellsY);for(let K=F;K<=q;K++)for(let X=T;X<=D;X++){const ce=this.cells[K*this.cellsX+X];if(ce)for(let pe=0;pe0){const D=function(F,q){const K=q.worldSize,X=de(1,0)*K*Ke(q.center.lat,q.zoom)/$Me(K),ce=de(1,q.center.lat)*K,pe=j([]);O(pe,pe,_a(q.center.lng)),R(pe,pe,_a(q.center.lat)),I(pe,pe,[0,0,By]),P(pe,pe,[X,X,X*ce]);const xe=q.point;return I(pe,pe,[-xe.x,-xe.y,0]),M(pe,pe,F),M(pe,q.globeMatrix,pe)}(w,f);return function(F,q,K){const X=(Me,ze,Ve)=>{const Je=fe(Me),lt=fe(ze),ht=O4(Me,ze,Ve);return Be(ht,ht,1/fe(ht)*da(Je,lt,Ve))},ce=X([F[0],F[1],F[2]],[q[0],q[1],q[2]],K),pe=X([F[4],F[5],F[6]],[q[4],q[5],q[6]],K),xe=X([F[8],F[9],F[10]],[q[8],q[9],q[10]],K),Ne=O4([F[12],F[13],F[14]],[q[12],q[13],q[14]],K);return[ce[0],ce[1],ce[2],0,pe[0],pe[1],pe[2],0,xe[0],xe[1],xe[2],0,Ne[0],Ne[1],Ne[2],1]}(T,D,S)}return T}function p6e(w,f,b,S){const T=jd.projectAabbCorners(S,b);let D=Number.MAX_VALUE;for(let q=0;q0||Ve===0&&Me[0]*ze[0]+Me[1]*ze[1]>=0&&Me[0]*Me[0]+Me[1]*Me[1]>ze[0]*ze[0]+ze[1]*ze[1])&&(ce=Ne)}pe=ce}while(pe!==X);return K.length>0&&K.push(K[0]),K}(T);if(_Me(w,F))return D}const Z6=64,UZt=[1,1,1];function Ise(w,f,b,S,T,D,F,q,K,X=!1){const ce=b.zoom,pe=b.project(S),xe=Ke(S.lat,ce),Ne=1/xe;j(w),I(w,w,[pe.x+F[0]*Ne,pe.y+F[1]*Ne,F[2]]);let Me=1,ze=1;const Ve=b.worldSize;if(X){if(b.projection.name==="mercator"){let ct=0;b.elevation&&(ct=b.elevation.getAtPointOrZero(new vt(pe.x/Ve,pe.y/Ve),0));const xt=dt([],[pe.x,pe.y,ct,1],b.projMatrix)[3]/b.cameraToCenterDistance;Me=xt,ze=xt*Ke(b.center.lat,ce)}else if(b.projection.name==="globe"){const ct=Pse(w,b),xt=[0,0,0,1];dt(xt,xt,M([],b.projMatrix,ct));const kt=xt[3]/b.cameraToCenterDistance,es=F4(ce),Ct=b.projection.pixelsPerMeter(S.lat,Ve)*Ke(S.lat,ce),Lt=b.projection.pixelsPerMeter(b.center.lat,Ve)*Ke(b.center.lat,ce);Me=kt/da(Ct,Pe(b.center.lat),es),ze=kt*xe/Ct,Me*=Lt,ze*=Lt}}else Me=Ne;P(w,w,[Me,Me,ze]);const Je=[...w],lt=f.orientation,ht=[];if(btt(ht,[lt[0]+(T?T[0]:0),lt[1]+(T?T[1]:0),lt[2]+(T?T[2]:0)],D),M(w,Je,ht),q&&b.elevation){let ct=0;const xt=[];if(K&&b.elevation){ct=function(es,Ct,Lt,Zt,Qt){const Cs=Ct.elevation;if(!Cs)return 0;const Fs=jd.projectAabbCorners(Lt,Zt),on=de(1,Qt.lat)*Ct.worldSize,sn=function(Kn,Dr){const sr=[0,0,1],yr=[{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 Ra of yr){const $a=Kn[Ra.corners[0]],si=Kn[Ra.corners[1]],La=Kn[Ra.corners[2]],Oi=[si[0]-$a[0],si[1]-$a[1],Dr*(si[2]-$a[2])],bi=Ge(Oi,Oi,[La[0]-$a[0],La[1]-$a[1],Dr*(La[2]-$a[2])]);Fe(bi,bi),Ra.dotProductWithUp=Oe(bi,sr)}return yr.sort((Ra,$a)=>Ra.dotProductWithUp-$a.dotProductWithUp),yr[0].corners}(Fs,on),hn=Fs[sn[0]],Rn=Fs[sn[1]],ws=Fs[sn[2]],qs=Fs[sn[3]],en=Cs.getAtPointOrZero(new vt(hn[0]/Ct.worldSize,hn[1]/Ct.worldSize),0),wn=Cs.getAtPointOrZero(new vt(Rn[0]/Ct.worldSize,Rn[1]/Ct.worldSize),0),Nn=Cs.getAtPointOrZero(new vt(ws[0]/Ct.worldSize,ws[1]/Ct.worldSize),0),Pn=Cs.getAtPointOrZero(new vt(qs[0]/Ct.worldSize,qs[1]/Ct.worldSize),0),jn=(en+Pn)/2,Wn=(wn+Nn)/2;return jn>Wn?wn=f.gl.NEAREST_MIPMAP_NEAREST}),w.uploaded=!0,w.image=null)}function wtt(w,f,b){w.indexBuffer=f.createIndexBuffer(w.indexArray,!1,!0),w.vertexBuffer=f.createVertexBuffer(w.vertexArray,LZt.members,!1,!0),w.normalArray&&(w.normalBuffer=f.createVertexBuffer(w.normalArray,FZt.members,!1,!0)),w.texcoordArray&&(w.texcoordBuffer=f.createVertexBuffer(w.texcoordArray,OZt.members,!1,!0)),w.colorArray&&(w.colorBuffer=f.createVertexBuffer(w.colorArray,(w.colorArray.bytesPerElement===12?RZt:DZt).members,!1,!0)),w.featureArray&&(w.pbrBuffer=f.createVertexBuffer(w.featureArray,BZt.members,!0)),w.segments=lc.simpleSegment(0,0,w.vertexArray.length,w.indexArray.length);const S=w.material;S.pbrMetallicRoughness.baseColorTexture&&CH(S.pbrMetallicRoughness.baseColorTexture,f),S.pbrMetallicRoughness.metallicRoughnessTexture&&CH(S.pbrMetallicRoughness.metallicRoughnessTexture,f),S.normalTexture&&CH(S.normalTexture,f),S.occlusionTexture&&CH(S.occlusionTexture,f,b),S.emissionTexture&&CH(S.emissionTexture,f)}function g6e(w,f,b){if(w.meshes)for(const S of w.meshes)wtt(S,f,b);if(w.lodMeshes)for(const S of w.lodMeshes)wtt(S,f,b);if(w.children)for(const S of w.children)g6e(S,f,b)}function jtt(w){w.indexArray.destroy(),w.vertexArray.destroy(),w.colorArray&&w.colorArray.destroy(),w.normalArray&&w.normalArray.destroy(),w.texcoordArray&&w.texcoordArray.destroy(),w.featureArray&&w.featureArray.destroy()}function Lse(w){if(w.meshes)for(const f of w.meshes)jtt(f);if(w.lodMeshes)for(const f of w.lodMeshes)jtt(f);if(w.children)for(const f of w.children)Lse(f)}function Ntt(w){var f;w.vertexBuffer&&(w.vertexBuffer.destroy(),w.indexBuffer.destroy(),w.normalBuffer&&w.normalBuffer.destroy(),w.texcoordBuffer&&w.texcoordBuffer.destroy(),w.colorBuffer&&w.colorBuffer.destroy(),w.pbrBuffer&&w.pbrBuffer.destroy(),w.segments.destroy(),w.material&&((f=w.material).pbrMetallicRoughness.baseColorTexture&&f.pbrMetallicRoughness.baseColorTexture.gfxTexture&&f.pbrMetallicRoughness.baseColorTexture.gfxTexture.destroy(),f.pbrMetallicRoughness.metallicRoughnessTexture&&f.pbrMetallicRoughness.metallicRoughnessTexture.gfxTexture&&f.pbrMetallicRoughness.metallicRoughnessTexture.gfxTexture.destroy(),f.normalTexture&&f.normalTexture.gfxTexture&&f.normalTexture.gfxTexture.destroy(),f.emissionTexture&&f.emissionTexture.gfxTexture&&f.emissionTexture.gfxTexture.destroy(),f.occlusionTexture&&f.occlusionTexture.gfxTexture&&f.occlusionTexture.gfxTexture.destroy()))}function x6e(w){if(w.meshes)for(const f of w.meshes)Ntt(f);if(w.lodMeshes)for(const f of w.lodMeshes)Ntt(f);if(w.footprintDebugMesh&&(w.footprintDebugMesh.vertexBuffer.destroy(),w.footprintDebugMesh.indexBuffer.destroy(),w.footprintDebugMesh.segments.destroy()),w.children)for(const f of w.children)x6e(f)}function y6e(w,f,b,S){return w[0]<=S[0]&&f[0]>=b[0]&&w[1]<=S[1]&&f[1]>=b[1]&&w[2]<=S[2]&&f[2]>=b[2]}function qZt(w,f,b,S,T,D,F,q,K,X,ce){const pe=.5*(X[0]+ce[0]),xe=.5*(X[1]+ce[1]),Ne=.5*(X[2]+ce[2]),Me=.5*(ce[0]-X[0]),ze=.5*(ce[1]-X[1]),Ve=.5*(ce[2]-X[2]),Je=w-pe,lt=f-xe,ht=b-Ne,ct=S-pe,xt=T-xe,kt=D-Ne,es=F-pe,Ct=q-xe,Lt=K-Ne,Zt=ct-Je,Qt=xt-lt,Cs=kt-ht,Fs=es-ct,on=Ct-xt,sn=Lt-kt,hn=Je-es,Rn=lt-Ct,ws=ht-Lt;let qs,en,wn,Nn,Pn,jn;if(qs=ht*Qt-lt*Cs,en=kt*Qt-xt*Cs,wn=Lt*Qt-Ct*Cs,Nn=Math.min(qs,en,wn),Pn=Math.max(qs,en,wn),jn=Math.abs(Cs)*ze+Math.abs(Qt)*Ve,Nn>jn||Pn<-jn||(qs=ht*on-lt*sn,en=kt*on-xt*sn,wn=Lt*on-Ct*sn,Nn=Math.min(qs,en,wn),Pn=Math.max(qs,en,wn),jn=Math.abs(sn)*ze+Math.abs(on)*Ve,Nn>jn||Pn<-jn)||(qs=ht*Rn-lt*ws,en=kt*Rn-xt*ws,wn=Lt*Rn-Ct*ws,Nn=Math.min(qs,en,wn),Pn=Math.max(qs,en,wn),jn=Math.abs(ws)*ze+Math.abs(Rn)*Ve,Nn>jn||Pn<-jn)||(qs=Je*Cs-ht*Zt,en=ct*Cs-kt*Zt,wn=es*Cs-Lt*Zt,Nn=Math.min(qs,en,wn),Pn=Math.max(qs,en,wn),jn=Math.abs(Cs)*Me+Math.abs(Zt)*Ve,Nn>jn||Pn<-jn)||(qs=Je*sn-ht*Fs,en=ct*sn-kt*Fs,wn=es*sn-Lt*Fs,Nn=Math.min(qs,en,wn),Pn=Math.max(qs,en,wn),jn=Math.abs(sn)*Me+Math.abs(Fs)*Ve,Nn>jn||Pn<-jn)||(qs=Je*ws-ht*hn,en=ct*ws-kt*hn,wn=es*ws-Lt*hn,Nn=Math.min(qs,en,wn),Pn=Math.max(qs,en,wn),jn=Math.abs(ws)*Me+Math.abs(hn)*Ve,Nn>jn||Pn<-jn)||(qs=lt*Zt-Je*Qt,en=xt*Zt-ct*Qt,wn=Ct*Zt-es*Qt,Nn=Math.min(qs,en,wn),Pn=Math.max(qs,en,wn),jn=Math.abs(Qt)*Me+Math.abs(Zt)*ze,Nn>jn||Pn<-jn)||(qs=lt*Fs-Je*on,en=xt*Fs-ct*on,wn=Ct*Fs-es*on,Nn=Math.min(qs,en,wn),Pn=Math.max(qs,en,wn),jn=Math.abs(on)*Me+Math.abs(Fs)*ze,Nn>jn||Pn<-jn)||(qs=lt*hn-Je*Rn,en=xt*hn-ct*Rn,wn=Ct*hn-es*Rn,Nn=Math.min(qs,en,wn),Pn=Math.max(qs,en,wn),jn=Math.abs(Rn)*Me+Math.abs(hn)*ze,Nn>jn||Pn<-jn)||(Nn=Math.min(Je,ct,es),Pn=Math.max(Je,ct,es),Nn>Me||Pn<-Me)||(Nn=Math.min(lt,xt,Ct),Pn=Math.max(lt,xt,Ct),Nn>ze||Pn<-ze)||(Nn=Math.min(ht,kt,Lt),Pn=Math.max(ht,kt,Lt),Nn>Ve||Pn<-Ve))return!1;const Wn=Qt*sn-Cs*on,Kn=Cs*Fs-Zt*sn,Dr=Zt*on-Qt*Fs,sr=-(Wn*Je+Kn*lt+Dr*ht);return jn=Me*Math.abs(Wn)+ze*Math.abs(Kn)+Ve*Math.abs(Dr),!(Math.abs(sr)>jn)}const VZt=[];class ktt{serializeFromGltf(f,b,S,T){if(f.length<7)return;let D=0;if(f[D++]!==109||f[D++]!==98||f[D++]!==120||f[D++]!==98||f[D++]!==118||f[D++]!==104||f[D++]!==43)return;const F=new DataView(f.buffer,f.byteOffset),q=F.getUint16(D,!0);if(D+=2,q===0)return;this._nodes=[];let K=0;for(let ce=0;ce0;){const D=S.pop(),F=this._nodes[D];if(F.aabbMax[2]<=T)continue;if(F.backChild===65535){for(let Ne=0;Ne=0?T:null}}function X6(w,f){const b=w.json.bufferViews[f.bufferView],S=Ase[f.componentType];return new S(w.buffers[b.buffer],(f.byteOffset||0)+(b.byteOffset||0),f.count*(b.byteStride&&b.byteStride!==kH[f.type]*S.BYTES_PER_ELEMENT?b.byteStride/S.BYTES_PER_ELEMENT:kH[f.type]))}function v6e(w,f,b,S){const T=Ase[f.componentType],D=function(pe){switch(pe){case Int8Array:return 1/127;case Uint8Array:return 1/255;case Int16Array:return 1/32767;case Uint16Array:return 1/65535;default:return 1}}(T),F=w.json.bufferViews[f.bufferView],q=F.byteStride?F.byteStride/T.BYTES_PER_ELEMENT:kH[f.type],K=b.float32,X=K.length/b.capacity,ce=f.count*q;for(let pe=0,xe=0;pe0){D.texcoordArray=new Hc;const Je=f.json.accessors[T.TEXCOORD_0];D.texcoordArray.resizeExact(Je.count);const lt=X6(f,Je);v6e(f,Je,D.texcoordArray,lt)}if(T._FEATURE_ID_RGBA4444!==void 0){const Je=f.json.accessors[T._FEATURE_ID_RGBA4444];f.json.extensionsUsed&&f.json.extensionsUsed.includes("EXT_meshopt_compression")&&(D.featureData=X6(f,Je))}T._FEATURE_RGBA4444!==void 0&&(D.featureData=new Uint32Array(X6(f,f.json.accessors[T._FEATURE_RGBA4444]).buffer));const Ve=w.material;return D.material=function(Je,lt){const{emissiveFactor:ht=[0,0,0],alphaMode:ct="OPAQUE",alphaCutoff:xt=.5,normalTexture:kt,occlusionTexture:es,emissiveTexture:Ct,doubleSided:Lt,name:Zt}=Je,{baseColorFactor:Qt=[1,1,1,1],metallicFactor:Cs=1,roughnessFactor:Fs=1,baseColorTexture:on,metallicRoughnessTexture:sn}=Je.pbrMetallicRoughness||{},hn=es?lt[es.index]:void 0;if(es&&es.extensions&&es.extensions.KHR_texture_transform&&hn){const Rn=es.extensions.KHR_texture_transform;hn.offsetScale=[Rn.offset[0],Rn.offset[1],Rn.scale[0],Rn.scale[1]]}return{name:Zt,pbrMetallicRoughness:{baseColorFactor:new Mi(...Qt),metallicFactor:Cs,roughnessFactor:Fs,baseColorTexture:on?lt[on.index]:void 0,metallicRoughnessTexture:sn?lt[sn.index]:void 0},doubleSided:Lt,emissiveFactor:new Mi(...ht),alphaMode:ct,alphaCutoff:xt,normalTexture:kt?lt[kt.index]:void 0,occlusionTexture:hn,emissionTexture:Ct?lt[Ct.index]:void 0,defined:Je.defined===void 0}}(Ve!==void 0?f.json.materials[Ve]:{defined:!1},b),D}function b6e(w,f,b){const{matrix:S,rotation:T,translation:D,scale:F,mesh:q,extras:K,children:X,name:ce}=w,pe={};if(pe.name=ce,pe.localMatrix=S||function(xe,Ne,Me,ze){var Ve=Ne[0],Je=Ne[1],lt=Ne[2],ht=Ne[3],ct=Ve+Ve,xt=Je+Je,kt=lt+lt,es=Ve*ct,Ct=Ve*xt,Lt=Ve*kt,Zt=Je*xt,Qt=Je*kt,Cs=lt*kt,Fs=ht*ct,on=ht*xt,sn=ht*kt,hn=ze[0],Rn=ze[1],ws=ze[2];return xe[0]=(1-(Zt+Cs))*hn,xe[1]=(Ct+sn)*hn,xe[2]=(Lt-on)*hn,xe[3]=0,xe[4]=(Ct-sn)*Rn,xe[5]=(1-(es+Cs))*Rn,xe[6]=(Qt+Fs)*Rn,xe[7]=0,xe[8]=(Lt+on)*ws,xe[9]=(Qt-Fs)*ws,xe[10]=(1-(es+Zt))*ws,xe[11]=0,xe[12]=Me[0],xe[13]=Me[1],xe[14]=Me[2],xe[15]=1,xe}([],T||[0,0,0,1],D||[0,0,0],F||[1,1,1]),pe.globalMatrix=v(pe.localMatrix),q!==void 0){pe.meshes=b[q];const xe=pe.anchor=[0,0];for(const Ne of pe.meshes){const{min:Me,max:ze}=Ne.aabb;xe[0]+=Me[0]+ze[0],xe[1]+=Me[1]+ze[1]}xe[0]=Math.floor(xe[0]/pe.meshes.length/2),xe[1]=Math.floor(xe[1]/pe.meshes.length/2)}if(K&&(K.id&&(pe.id=K.id),K.lights&&(pe.lights=function(xe){if(!xe.length)return[];const Ne=function(lt){const ht=atob(lt),ct=new Uint8Array(ht.length);for(let xt=0;xt=ht.length||Ve>=ht.length||Je>=ht.length||lt>=ht.length)return null;const ct=ht[ze],xt=ht[Ve],kt=ht[Je],es=ht[lt];if(ct.bufferView===void 0||xt.bufferView===void 0||kt.bufferView===void 0||es.bufferView===void 0)return null;const Ct=xe.json.bufferViews;if(ct.bufferView>=Ct.length||xt.bufferView>=Ct.length||kt.bufferView>=Ct.length||es.bufferView>=Ct.length)return null;const Lt=Ct[ct.bufferView],Zt=Ct[xt.bufferView],Qt=Ct[kt.bufferView],Cs=Ct[es.bufferView];if(Lt.buffer>=xe.buffers.length||Zt.buffer>=xe.buffers.length||Qt.buffer>=xe.buffers.length||Cs.buffer>=xe.buffers.length)return null;const Fs=(Pn,jn,Wn)=>Pn>=0&&Pn<=Wn&&jn<=Wn-Pn,on=ct.byteOffset||0,sn=xt.byteOffset||0,hn=kt.byteOffset||0,Rn=es.byteOffset||0;if(!(Fs(on,0,Lt.byteLength)&&Fs(sn,3*xt.count*4,Zt.byteLength)&&Fs(hn,3*kt.count*4,Qt.byteLength)&&Fs(Rn,4*es.count,Cs.byteLength)))return null;const ws=new Uint8Array(xe.buffers[Lt.buffer],(Lt.byteOffset||0)+on,Lt.byteLength-on),qs=new Float32Array(xe.buffers[Zt.buffer],(Zt.byteOffset||0)+sn,3*xt.count),en=new Float32Array(xe.buffers[Qt.buffer],(Qt.byteOffset||0)+hn,3*kt.count),wn=new Uint32Array(xe.buffers[Cs.buffer],(Cs.byteOffset||0)+Rn,es.count),Nn=new ktt;if(Nn.serializeFromGltf(ws,qs,en,wn),Me!==void 0&&xe.json.meshes&&xe.json.meshes[Me]){const Pn=xe.json.meshes[Me].primitives[0];if(Pn&&Pn.attributes.POSITION!==void 0&&Pn.attributes.POSITION1&&S.at(-1).equals(S[0])&&S.pop();let T=0;for(let F=0;F0&&S.reverse();const D=rN(S.flatMap(F=>[F.x,F.y]),[]);return D.length===0?null:{vertices:S,indices:D}}function KZt(w,f){const b=[],S=[];let T=0;const D=[];for(const F of w){T=b.length;const q=F.vertexArray.float32,K=F.indexArray.uint16;for(let X=0;X0&&([S[F+1],S[F+2]]=[S[F+2],S[F+1]])}return{vertices:b,indices:S}}function Stt(w,f){for(let b=0;b0){const ze=Array.from(Me.values()).sort((Ve,Je)=>Ve-Je);for(let Ve=ze.length-1;Ve>=0;Ve--)ce.splice(ze[Ve],1)}})(K,q,w.json.nodes);const X=S?Stt(S,"LOD"):-1;if(X>=0){const ce=S[X].nodes,pe=new Map;for(const xe of ce){const Ne=b6e(D[xe],w,b);Ne.id&&pe.set(Ne.id,Ne)}for(const xe of K)if(xe.id){const Ne=pe.get(xe.id);Ne&&Ne.meshes&&(xe.lodMeshes=Ne.meshes,Ne.meshBVH&&(xe.meshBVH=Ne.meshBVH))}}return K}function YZt(w){w.heightmap=new Float32Array(4096),w.heightmap.fill(-1);const f=w.vertexArray.float32,b=w.aabb.min[0]-1,S=w.aabb.min[1]-1,T=Z6/(w.aabb.max[0]-b+2),D=Z6/(w.aabb.max[1]-S+2);for(let F=0;Fw.heightmap[X*Z6+K]&&(w.heightmap[X*Z6+K]=q)}}function Ctt(w,f,b,S,T){b.reserve(b.length+4*w.length),S.reserve(S.length+10*w.length),T.reserve(T.length+10*w.length);let D=S.length;for(const F of w){const q=Math.min(10,Math.max(4,1.3*F.height))*f,K=[-F.normal[1],F.normal[0],0],X=Math.min(.29,.1*F.width/F.depth),ce=F.width-2*F.depth*f*(X+.01),pe=je([],F.pos,K,ce/2),xe=je([],F.pos,K,-ce/2),Ne=[pe[0],pe[1],pe[2]+F.height],Me=[xe[0],xe[1],xe[2]+F.height],ze=je([],F.normal,K,X);Be(ze,ze,q);const Ve=je([],F.normal,K,-X);Be(Ve,Ve,q),he(ze,pe,ze),he(Ve,xe,Ve),pe[2]+=.1,xe[2]+=.1,S.emplaceBack(ze[0],ze[1],ze[2]),S.emplaceBack(Ve[0],Ve[1],Ve[2]),S.emplaceBack(pe[0],pe[1],pe[2]),S.emplaceBack(xe[0],xe[1],xe[2]),S.emplaceBack(Ne[0],Ne[1],Ne[2]),S.emplaceBack(Me[0],Me[1],Me[2]),S.emplaceBack(pe[0],pe[1],pe[2]),S.emplaceBack(xe[0],xe[1],xe[2]),S.emplaceBack(ze[0],ze[1],ze[2]),S.emplaceBack(Ve[0],Ve[1],Ve[2]);const Je=ce/q/2;T.emplaceBack(-Je-X,-1,Je,.8),T.emplaceBack(Je+X,-1,Je,.8),T.emplaceBack(-Je,0,Je,1.3),T.emplaceBack(Je,0,Je,1.3),T.emplaceBack(Je+X,-.8,Je,.7),T.emplaceBack(Je+X,-.8,Je,.7),T.emplaceBack(0,0,Je,1.3),T.emplaceBack(0,0,Je,1.3),T.emplaceBack(Je+X,-1.2,Je,.8),T.emplaceBack(Je+X,-1.2,Je,.8),b.emplaceBack(6+D,4+D,8+D),b.emplaceBack(7+D,9+D,5+D),b.emplaceBack(0+D,1+D,2+D),b.emplaceBack(1+D,3+D,2+D),D+=10}}function ZZt(w,f){const b={};b.indexArray=new Va,b.vertexArray=new Nr,b.colorArray=new ci,b.indexArray.reserveExact(4*w.length),b.vertexArray.reserveExact(10*w.length),b.colorArray.reserveExact(10*w.length),Ctt(w,f,b.indexArray,b.vertexArray,b.colorArray);const S={defined:!0};S.emissiveFactor=Mi.black;const T={};return T.baseColorFactor=Mi.white,S.pbrMetallicRoughness=T,b.material=S,b.aabb=new jd([1/0,1/0,1/0],[-1/0,-1/0,-1/0]),b}Vr(ktt,"ModelBVH");const Att=an([{name:"a_pos_3f",components:3,type:"Float32"}]),XZt=an([{name:"a_normal_3",components:3,type:"Int16"}]),QZt=an([{name:"a_centroid_3",components:3,type:"Int16"}]),Ett=an([{name:"a_part_color_emissive",components:2,type:"Uint16"}]),JZt=an([{name:"a_faux_facade_color_emissive",components:2,type:"Uint16"}]),eXt=an([{name:"a_faux_facade_data",components:4,type:"Uint16"}]),tXt=an([{name:"a_faux_facade_vertical_range",components:2,type:"Uint16"}]),sXt=an([{name:"a_bloom_attenuation",components:4,type:"Float32"}]),nXt=an([{name:"a_flood_light_wall_radius_1i16",components:1,type:"Int16"}]),rXt=an([{name:"a_pos_normal_ed",components:4,type:"Int16"}]),aXt=an([{name:"a_pos_end",components:4,type:"Int16"},{name:"a_angular_offset_factor",components:1,type:"Int16"}]),iXt=an([{name:"a_flood_light_ground_radius",components:1,type:"Float32"}]),oXt=an([{name:"a_centroid_pos",components:2,type:"Uint16"}]),lXt=an([{name:"a_join_normal_inside",components:3,type:"Int16"}]),cXt=an([{name:"a_hidden_by_landmark",components:1,type:"Uint8"}]),dXt=an([{name:"a_pos_3",components:3,type:"Int16"},{name:"a_pos_normal_3",components:3,type:"Int16"}]),{members:uXt}=rXt;function Rse(w,f,b,S){const T=[],D=S===0?(F,q,K,X,ce,pe)=>{F.push(new Kt(pe,K+(pe-q)/(X-q)*(ce-K)))}:(F,q,K,X,ce,pe)=>{F.push(new Kt(q+(pe-K)/(ce-K)*(X-q),pe))};for(const F of w){const q=[];for(const K of F){if(K.length<=2)continue;const X=[];for(let xe=0;xef&&D(X,Ne,Me,ze,Ve,f):Je>b?lt=f&&D(X,Ne,Me,ze,Ve,f),lt>b&&Je<=b&&D(X,Ne,Me,ze,Ve,b)}let ce=K.at(-1);const pe=S===0?ce.x:ce.y;pe>=f&&pe<=b&&X.push(ce),X.length&&(ce=X.at(-1),X[0].x===ce.x&&X[0].y===ce.y||X.push(X[0]),q.push(X))}q.length&&T.push(q)}return T}const Dse={None:0,Model:1,Symbol:2,FillExtrusion:4},w6e=[new Kt(0,0),new Kt(br,0),new Kt(br,br),new Kt(0,br)];function Ttt(w,f){const b=[];let S=[];if(!f||w.length<2)return[w];if(w.length===2)return h7(w[0],w[1],w6e)?[w]:[];for(let T=0;T0&&(S.length>1&&b.push(S),S=[])}return S.length>1&&b.push(S),b}const j6e=bA.types,hXt=["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"],mXt=["fill-extrusion-flood-light-ground-radius"],fXt=Math.pow(2,13),pXt=Math.pow(2,15)-1,Ose=new Kt(0,1),U4=2147483648,Fse=1073741824;function AH(w,f,b,S,T,D,F,q){w.emplaceBack((f<<1)+F,(b<<1)+D,(Math.floor(S*fXt)<<1)+T,Math.round(q))}function EH(w,f,b){w.emplaceBack(f.x*br,f.y*br,b?1:0)}function zse(w,f,b,S,T,D){w.emplaceBack(f.x,f.y,(b.x<<1)+S,(b.y<<1)+T,D)}function TH(w,f,b){w.emplaceBack(f.x,f.y,f.z,b[0]*16384,b[1]*16384,b[2]*16384)}class Mtt{constructor(){this.vertexOffset=0,this.vertexCount=0,this.indexOffset=0,this.indexCount=0}}class Bse{constructor(){this.data=[]}get length(){return this.data.length}push(f){this.data.push(f)}get(f){return this.data[f]}static serialize(f,b){const S=f.data.length,T=new Uint32Array(4*S),D=[];D.length=S;for(let F=0;Ff.max.x&&(f.max.x=b.x,T=!0),b.yf.max.y&&(f.max.y=b.y,T=!0),((b.x===0||b.x===br)&&b.x===S.x)!=((b.y===0||b.y===br)&&b.y===S.y)&&this.processBorderOverlap(b,S),T&&this.checkBorderIntersection(b,S)}checkBorderIntersection(f,b){b.x<0!=f.x<0&&this.addBorderIntersection(0,da(b.y,f.y,(0-b.x)/(f.x-b.x))),b.x>br!=f.x>br&&this.addBorderIntersection(1,da(b.y,f.y,(br-b.x)/(f.x-b.x))),b.y<0!=f.y<0&&this.addBorderIntersection(2,da(b.x,f.x,(0-b.y)/(f.y-b.y))),b.y>br!=f.y>br&&this.addBorderIntersection(3,da(b.x,f.x,(br-b.y)/(f.y-b.y)))}addBorderIntersection(f,b){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 S=this.borders[f];bS[1]&&(S[1]=b)}processBorderOverlap(f,b){if(f.x===b.x){if(f.y===b.y)return;const S=f.x===0?0:1;this.addBorderIntersection(S,b.y),this.addBorderIntersection(S,f.y)}else{const S=f.y===0?2:3;this.addBorderIntersection(S,b.x),this.addBorderIntersection(S,f.x)}}centroid(){return this.accCount===0?new Kt(0,0):new Kt(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((f,b)=>f+ +(b[0]!==Number.MAX_VALUE),0):0}}function Ptt(w,f){const b=w.add(f)._unit(),S=Jr(w.x*b.x+w.y*b.y,-1,1);var T,D,F;return F=Math.acos(S),Math.min(4,Math.max(-4,Math.tan(F)))/4*pXt*((T=w).x*(D=f).y-T.y*D.x<0?-1:1)}const gXt=[w=>w.x<0,w=>w.x>br,w=>w.y<0,w=>w.y>br];function xXt(w,f,b,S){const T=[4];if(S===0)return T;b._mult(S);const D=w.sub(b),F=f.sub(b),q=[w,f,D,F];for(let K=0;K<4;K++)for(const X of q)if(gXt[K](X)){T.push(K);break}return T}class k6e{constructor(f){this.groundRadiusArray=null,this.groundRadiusBuffer=null,this.vertexArray=new Lr,this.indexArray=new Va,this.programConfigurations=new aN(f.layers,{zoom:f.zoom,lut:f.lut},b=>mXt.includes(b)),this._segments=new lc,this.hiddenByLandmarkVertexArray=new Pv,this._segmentToGroundQuads={},this._segmentToGroundQuads[0]=[],this._segmentToRegionTriCounts={},this._segmentToRegionTriCounts[0]=[0,0,0,0,0],this.regionSegments={},this.regionSegments[4]=new lc}getDefaultSegment(){return this.regionSegments[4]}hasData(){return this.vertexArray.length!==0}addData(f,b,S,T=!1){const D=f.length;if(D>2){let F=Math.max(0,this._segments.get().length-1);const q=this._segments._prepareSegment(4*D,this.vertexArray.length,2*this._segmentToGroundQuads[F].length);let K;F!==this._segments.get().length-1&&(F++,this._segmentToGroundQuads[F]=[],this._segmentToRegionTriCounts[F]=[0,0,0,0,0]);{const X=f[0],ce=f[1];K=Ptt(X.sub(f[D-1])._perp()._unit(),ce.sub(X)._perp()._unit())}for(let X=0;XT.region-D.region);for(let S=0;SK+X,0);let q=0;for(let K=0;K<=4;K++){const X=F[K];if(X!==0){let ce=this.regionSegments[K];ce||(ce=this.regionSegments[K]=new lc);const pe={vertexOffset:D.vertexOffset,primitiveOffset:D.primitiveOffset+q,vertexLength:D.vertexLength,primitiveLength:X};ce.get().push(pe)}q+=X}for(let K=0;K0?this.hiddenByLandmarkVertexBuffer=f.createVertexBuffer(this.hiddenByLandmarkVertexArray,cXt.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 f=0;f<=4;f++){const b=this.regionSegments[f];b&&b.destroy()}}}}class qse{constructor(f){this.zoom=f.zoom,this.canonical=f.canonical,this.overscaling=f.overscaling,this.layers=f.layers,this.pixelRatio=f.pixelRatio,this.layerIds=this.layers.map(b=>b.fqid),this.index=f.index,this.hasPattern=!1,this.edgeRadius=0,this.projection=f.projection,this.activeReplacements=[],this.replacementUpdateTime=0,this.centroidData=new Use,this.footprintIndices=new Va,this.footprintVertices=new Sn,this.footprintSegments=new Bse,this.layoutVertexArray=new Qr,this.centroidVertexArray=new Bf,this.wallVertexArray=new $b,this.indexArray=new Va,this.programConfigurations=new aN(f.layers,{zoom:f.zoom,lut:f.lut},b=>hXt.includes(b)),this.segments=new lc,this.stateDependentLayerIds=this.layers.filter(b=>b.isStateDependent()).map(b=>b.id),this.groundEffect=new k6e(f),this.maxHeight=0,this.partLookup={},this.triangleSubSegments=[],this.polygonSegments=[],this.buildingGroups=new Map,this.worldview=f.worldview,this.hasAppearances=null}updateFootprints(f,b){}updateAppearances(f,b,S,T){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(f,b,S,T){this.features=[],this.hasPattern=sH("fill-extrusion",this.layers,this.pixelRatio,b),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=mt(S),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:D,id:F,index:q,sourceLayerIndex:K}of f){const X=this.layers[0]._featureFilter.needGeometry,ce=Js(D,X);if(!this.layers[0]._featureFilter.filter(new tr(this.zoom,{worldview:this.worldview,activeFloors:b.activeFloors}),ce,S))continue;const pe={id:F,sourceLayerIndex:K,index:q,geometry:X?ce.geometry:Ms(D,S,T),properties:D.properties,type:D.type,patterns:{}},xe=this.layoutVertexArray.length,Ne=j6e[pe.type]==="Polygon";if(this.hasPattern)this.features.push({featureId:D.id,feature:nH("fill-extrusion",this.layers,pe,this.zoom,this.pixelRatio,b)});else if(this.wallMode)for(const Me of pe.geometry)for(const ze of Ttt(Me,Ne))this.addFeature(D.id,pe,[ze],q,S,{},b.availableImages,T,b.brightness);else this.addFeature(D.id,pe,pe.geometry,q,S,{},b.availableImages,T,b.brightness);b.featureIndex.insert(D,pe.geometry,q,K,this.index,xe)}this._finalizeBuildingGroups(),this.sortBorders(),this.projection.name==="mercator"&&this.splitToSubtiles(),this.groundEffect.prepareBorderSegments(),this.polygonSegments.length=0}addFeatures(f,b,S,T,D,F){for(const{featureId:q,feature:K}of this.features){const X=j6e[K.type]==="Polygon",{geometry:ce}=K;if(this.wallMode)for(const pe of ce)for(const xe of Ttt(pe,X))this.addFeature(q,K,[xe],K.index,b,S,T,D,F);else this.addFeature(q,K,ce,K.index,b,S,T,D,F)}this._finalizeBuildingGroups(),this.sortBorders(),this.projection.name==="mercator"&&this.splitToSubtiles()}update(f,b,S,T,D,F,q){this.programConfigurations.updatePaintArrays(f,b,D,S,T,F,q,this.worldview),this.groundEffect.update(f,b,D,S,T,F,q,this.worldview)}updateExpressions(f){this.programConfigurations.updateExpressions(f),this.groundEffect.programConfigurations.updateExpressions(f)}isEmpty(){return this.layoutVertexArray.length===0}uploadPending(){return!this.uploaded||this.programConfigurations.needsUpload||this.groundEffect.programConfigurations.needsUpload}upload(f){this.uploaded||(this.layoutVertexBuffer=f.createVertexBuffer(this.layoutVertexArray,uXt),this.indexBuffer=f.createIndexBuffer(this.indexArray),this.wallVertexBuffer=f.createVertexBuffer(this.wallVertexArray,lXt.members),this.layoutVertexExtArray&&(this.layoutVertexExtBuffer=f.createVertexBuffer(this.layoutVertexExtArray,dXt.members,!0)),this.groundEffect.upload(f)),this.groundEffect.uploadPaintProperties(f),this.programConfigurations.upload(f),this.uploaded=!0}uploadCentroid(f){this.groundEffect.uploadHiddenByLandmark(f),this.needsCentroidUpdate&&(!this.centroidVertexBuffer&&this.centroidVertexArray.length>0?this.centroidVertexBuffer=f.createVertexBuffer(this.centroidVertexArray,oXt.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(f,b,S,T,D,F,q,K,X){const ce=this.layers[0].paint.get("fill-extrusion-flood-light-ground-radius").evaluate(b,{})/this.tileToMeter,pe=[new Kt(0,0),new Kt(br,br)],xe=K.projection,Ne=xe.name==="globe",Me=this.wallMode||j6e[b.type]==="Polygon",ze=new N6e;ze.centroidDataIndex=this.centroidData.length;const Ve=new $se;Ve.buildingId=f,b.properties&&Object.hasOwn(b.properties,"building_id")&&(Ve.buildingId=Number(b.properties.building_id)),ze.buildingId=Ve.buildingId;const Je=this.layers[0].paint.get("fill-extrusion-base").evaluate(b,{},D)<=0,lt=this.layers[0].paint.get("fill-extrusion-height").evaluate(b,{},D);let ht;if(Ve.height=lt,Ve.vertexArrayOffset=this.layoutVertexArray.length,Ve.groundVertexArrayOffset=this.groundEffect.vertexArray.length,Ne&&!this.layoutVertexExtArray&&(this.layoutVertexExtArray=new Fa),this.wallMode){if(Ne)return void oi("Non zero fill-extrusion-line-width is not yet supported on globe.");if(S.length!==1)return;ht=function(Zt){const Qt=Zt[0].x===Zt.at(-1).x&&Zt[0].y===Zt.at(-1).y;(function(Wn){let Kn=0;const Dr=Wn.length;for(let sr=0;sr=0})(Zt)||(Zt=Zt.reverse());const Fs={geometry:[],joinNormals:[],indices:[]},on=[],sn=[],hn=[];let Rn=Zt.length;for(;Rn>=2&&Zt[Rn-1].equals(Zt[Rn-2]);)Rn--;if(Rn<(Qt?3:2))return Fs;let ws,qs,en,wn,Nn,Pn=0;for(;Pn0;let Ra="miter";const $a=2;Ra==="miter"&&sr>$a&&(Ra="bevel"),Ra==="bevel"&&(sr>100&&(Ra="flipbevel"),sr<$a&&(Ra="miter"));const si=(La,Oi,bi,Bl)=>{const cl=new Kt(La.x,La.y),Ll=new Kt(La.x,La.y);cl.x+=Oi.x*Bl,cl.y+=Oi.y*Bl,Ll.x-=Oi.x*Math.max(bi,1),Ll.y-=Oi.y*Math.max(bi,1),hn.push(Oi),on.push(cl),sn.push(Ll)};if(Ra==="miter")Kn._mult(sr),si(ws,Kn,0,0);else if(Ra==="flipbevel")Kn=Nn.mult(-1),si(ws,Kn,0,0),si(ws,Kn.mult(-1),0,0);else{const La=-Math.sqrt(sr*sr-1),Oi=yr?La:0,bi=yr?0:La;qs&&si(ws,wn,Oi,bi),en&&si(ws,Nn,Oi,bi)}}Fs.geometry=[...on,...sn.reverse(),on[0]],Fs.joinNormals=[...hn,...hn.reverse(),hn.at(-1)];const jn=Fs.geometry.length-1;for(let Wn=0;WnZt<(Qt.length-1)/2||Zt===Qt.length-1,xt=this.wallMode?[S]:Ur(S,500);for(let Zt=xt.length-1;Zt>=0;Zt--){const Qt=xt[Zt];(Qt.length===0||bXt(Qt[0]))&&xt.splice(Zt,1)}let kt;if(Ne)kt=ztt(xt,pe,D);else{kt=[];for(const Zt of xt)kt.push({polygon:Zt,bounds:pe})}const es=Me?this.edgeRadius:0,Ct=es>0&&this.zoom<17,Lt=(Zt,Qt)=>{if(Zt.length===0)return!1;const Cs=Zt.at(-1);return Qt.x===Cs.x&&Qt.y===Cs.y};for(const{polygon:Zt,bounds:Qt}of kt){let Cs=0,Fs=0;for(const Rn of Zt)Me&&!Rn[0].equals(Rn.at(-1))&&Rn.push(Rn[0]),Fs+=Me?Rn.length-1:Rn.length;const on=this.segments.prepareSegment((Me?5:4)*Fs,this.layoutVertexArray,this.indexArray);Ve.footprintSegIdx<0&&(Ve.footprintSegIdx=this.footprintSegments.length),Ve.polygonSegIdx<0&&(Ve.polygonSegIdx=this.polygonSegments.length);const sn={triangleArrayOffset:this.indexArray.length,triangleCount:0,triangleSegIdx:this.segments.segments.length-1},hn=new Mtt;if(hn.vertexOffset=this.footprintVertices.length,hn.indexOffset=3*this.footprintIndices.length,hn.ringIndices=[],Me){const Rn=[],ws=[];Cs=on.vertexLength;for(let en=0;en4&&Dtt(ws[ws.length-2],ws[0],ws[1]),en=es?vXt(ws[ws.length-2],ws[0],ws[1],es):0;const wn=[];let Nn,Pn,jn;Pn=ws[1].sub(ws[0])._perp()._unit();let Wn=!0;for(let Kn=1,Dr=0;Kn0?1:0,Oi=sr.dist(yr);if(Dr+Oi>32768&&(Dr=0),es){jn=Vse(yr,Ra,Pn);let Ll=Ltt(sr,yr,Ra,S6e(Pn,jn),es);isNaN(Ll)&&(Ll=0);const dc=yXt(sr,yr,new Kt(0,0));sr=sr.add(dc.mult(en))._round(),yr=yr.add(dc.mult(-Ll))._round(),en=Ll,Pn=jn,Je&&this.zoom>=17&&(Lt(wn,sr)||wn.push(sr),Lt(wn,yr)||wn.push(yr))}const bi=on.vertexLength,Bl=ws.length>4&&Dtt(sr,yr,Ra);let cl=Ott(Dr,qs,Wn);if(AH(this.layoutVertexArray,sr.x,sr.y,si,La,0,0,cl),AH(this.layoutVertexArray,sr.x,sr.y,si,La,0,1,cl),this.wallMode){const Ll=ct(Kn-1,ws),dc=ht.joinNormals[Kn-1];EH(this.wallVertexArray,dc,Ll),EH(this.wallVertexArray,dc,Ll)}if(Dr+=Oi,cl=Ott(Dr,Bl,!Wn),qs=Bl,AH(this.layoutVertexArray,yr.x,yr.y,si,La,0,0,cl),AH(this.layoutVertexArray,yr.x,yr.y,si,La,0,1,cl),this.wallMode){const Ll=ct(Kn,ws),dc=ht.joinNormals[Kn];EH(this.wallVertexArray,dc,Ll),EH(this.wallVertexArray,dc,Ll)}if(on.vertexLength+=4,this.indexArray.emplaceBack(bi+0,bi+1,bi+2),this.indexArray.emplaceBack(bi+1,bi+3,bi+2),on.primitiveLength+=2,es){const Ll=Cs+(Kn===1?ws.length-2:Kn-2),dc=Kn===1?Cs:Ll+1;if(this.indexArray.emplaceBack(bi+1,Ll,bi+3),this.indexArray.emplaceBack(Ll,dc,bi+3),on.primitiveLength+=2,Nn===void 0&&(Nn=bi),!C6e(Ra,ws[Kn],Qt)){const cf=Kn===ws.length-1?Nn:on.vertexLength;this.indexArray.emplaceBack(bi+2,bi+3,cf),this.indexArray.emplaceBack(bi+3,cf+1,cf),this.indexArray.emplaceBack(bi+3,dc,cf+1),on.primitiveLength+=3}Wn=!Wn}if(Ne){const Ll=this.layoutVertexExtArray,dc=xe.projectTilePoint(sr.x,sr.y,D),cf=xe.projectTilePoint(yr.x,yr.y,D),$1=xe.upVector(D,sr.x,sr.y),Wh=xe.upVector(D,yr.x,yr.y);TH(Ll,dc,$1),TH(Ll,dc,$1),TH(Ll,cf,Wh),TH(Ll,cf,Wh)}}Me&&(Cs+=ws.length-1),Je&&es&&this.zoom>=17&&(wn.length!==0&&Lt(wn,wn[0])&&wn.pop(),this.groundEffect.addData(wn,Qt,ce,es>0))}this.footprintSegments.push(hn),sn.triangleCount=this.indexArray.length-sn.triangleArrayOffset,this.polygonSegments.push(sn),++Ve.footprintSegLen,++Ve.polygonSegLen}if(Ve.vertexCount=this.layoutVertexArray.length-Ve.vertexArrayOffset,Ve.groundVertexCount=this.groundEffect.vertexArray.length-Ve.groundVertexArrayOffset,Ve.vertexCount!==0){if(Ve.centroidXY=ze.borders?Ose:this.encodeCentroid(ze,Ve),b.properties&&Object.hasOwn(b.properties,"building_id")){const Zt=Ve.buildingId;let Qt=this.buildingGroups.get(Zt);Qt||(Qt={accX:0,accY:0,accCount:0,mergedMin:new Kt(Number.MAX_VALUE,Number.MAX_VALUE),mergedMax:new Kt(-Number.MAX_VALUE,-Number.MAX_VALUE),partIndices:[]},this.buildingGroups.set(Zt,Qt)),Qt.accX+=ze.acc.x,Qt.accY+=ze.acc.y,Qt.accCount+=ze.accCount,Qt.mergedMin.x=Math.min(Qt.mergedMin.x,Ve.min.x),Qt.mergedMin.y=Math.min(Qt.mergedMin.y,Ve.min.y),Qt.mergedMax.x=Math.max(Qt.mergedMax.x,Ve.max.x),Qt.mergedMax.y=Math.max(Qt.mergedMax.y,Ve.max.y),Qt.partIndices.push(this.centroidData.length)}if(this.centroidData.push(Ve),ze.borders){this.featuresOnBorder.push(ze);const Zt=this.featuresOnBorder.length-1;for(let Qt=0;Qtthis.featuresOnBorder[b].borders[f][0]-this.featuresOnBorder[S].borders[f][0])}splitToSubtiles(){const f=[];for(let q=0;qbr),ce=2*X+(+(K.min.x+K.max.x>br)^X);for(let pe=0;peq.triangleSegmentIdx===K.triangleSegmentIdx?q.subtile-K.subtile:q.triangleSegmentIdx-K.triangleSegmentIdx);let S=0,T=0,D=0;for(const q of f){if(q.triangleSegmentIdx!==S)break;D++}const F=f.length;for(;T!==f.length;){S=f[T].triangleSegmentIdx;let q=0,K=T,X=T;for(let ce=K;ce0&&this.triangleSubSegments.push({segment:Ne,min:pe,max:xe}),K=X;for(let Me=K;Me[da(ze[0],Ve[0],Je[0]),da(ze[1],Ve[1],Je[1])],Ne=[],Me=[];for(const ze of this.triangleSubSegments){Ne[0]=ze.min.x/br,Ne[1]=ze.min.y/br,Me[0]=ze.max.x/br,Me[1]=ze.max.y/br;const Ve=xe(ce,pe,Ne),Je=xe(ce,pe,Me);if(new jd([Ve[0],Ve[1],D],[Je[0],Je[1],F]).intersectsPrecise(S)===0){X&&(T.segments.push(X),X=void 0);continue}const lt=ze.segment;X&&X.vertexOffset!==lt.vertexOffset&&(T.segments.push(X),X=void 0),X?(X.vertexLength+=lt.vertexLength,X.primitiveLength+=lt.primitiveLength):X={vertexOffset:lt.vertexOffset,primitiveLength:lt.primitiveLength,vertexLength:lt.vertexLength,primitiveOffset:lt.primitiveOffset,sortKey:void 0,vaos:{}}}return X&&T.segments.push(X),T}encodeCentroid(f,b){const S=f.centroid(),T=b.span(),D=Math.min(7,Math.round(T.x*this.tileToMeter/10)),F=Math.min(6,Math.round(T.y*this.tileToMeter/10));return new Kt(Jr(S.x,1,8191)<<3|D,Jr(S.y,1,8191)<<3|F)}encodeBorderCentroid(f){if(!f.borders)return new Kt(0,0);const b=f.borders,S=Number.MAX_VALUE;if(b[0][0]!==S||b[1][0]!==S){const T=b[0][0]!==S?0:1;return new Kt(6|(b[0][0]!==S?0:65528),(b[T][0]+b[T][1])/2<<3|6)}{const T=b[2][0]!==S?2:3;return new Kt((b[T][0]+b[T][1])/2<<3|6,6|(b[2][0]!==S?0:65528))}}showCentroid(f){const b=this.centroidData.get(f.centroidDataIndex);if(b.flags&=U4,b.groupCentroidPos.x!==0||b.groupCentroidPos.y!==0){const S=b.span(),T=Math.min(7,Math.round(S.x*this.tileToMeter/10)),D=Math.min(6,Math.round(S.y*this.tileToMeter/10));b.centroidXY=new Kt(Jr(b.groupCentroidPos.x,1,8191)<<3|T,Jr(b.groupCentroidPos.y,1,8191)<<3|D)}else b.centroidXY=new Kt(0,0);this.writeCentroidToBuffer(b)}writeCentroidToBuffer(f){this.groundEffect.updateHiddenByLandmark(f);const b=f.vertexArrayOffset,S=f.vertexCount+f.vertexArrayOffset,T=-1073741824&f.flags?Ose:f.centroidXY,D=this.centroidVertexArray.geta_centroid_pos0(b);if(this.centroidVertexArray.geta_centroid_pos1(b)!==T.y||D!==T.x){for(let F=b;FK.max.x||K.min.x>F.max.x||F.min.y>K.max.y||K.min.y>F.max.y||F.footprint.buildingIds.has(K.buildingId)&&(K.flags|=F.clipMask!==Dse.None?-1073741824:U4);else for(const K of this.centroidData)if(!(K.flags&U4||K.flags&Fse||F.min.x>K.max.x||K.min.x>F.max.x||F.min.y>K.max.y||K.min.y>F.max.y))for(let X=0;Xb!=Ne>b&&f<(this.footprintVertices.int16[2*(ce+F.vertexOffset)+0]-pe)*(b-xe)/(Ne-xe)+pe&&(T=!T)}q=K}}return T}getHeightAtTileCoord(f,b){let S=Number.NEGATIVE_INFINITY,T=!0;const D=4*(f+br)*br+(b+br);if(Object.hasOwn(this.partLookup,D)){const K=this.partLookup[D];return K?{height:K.height,hidden:!!(K.flags&U4)}:void 0}const F=this.centroidData.buffer,q=this.centroidData.length;for(let K=0;KF[X+4]||F[X+2]>f||b>F[X+5]||F[X+3]>b)continue;const ce=F[X+13];if(ce<=S)continue;const pe=this.centroidData.get(K);this.footprintContainsPoint(f,b,pe)&&(S=ce,this.partLookup[D]=pe,T=!!(pe.flags&U4))}if(S!==Number.NEGATIVE_INFINITY)return{height:S,hidden:T};this.partLookup[D]=void 0}}function yXt(w,f,b){return w.equals(f)?b:f.sub(w)._unit()}function Vse(w,f,b){return w.equals(f)?b:f.sub(w)._perp()._unit()}function Itt(w,f){const b=w.add(f),S=b.mag();return S===0?w:b.div(S)}function S6e(w,f){const b=Itt(w,f);return w.x*b.x+w.y*b.y}function vXt(w,f,b,S){let T,D;return w.equals(f)?(D=Vse(f,b,new Kt(0,0)),T=D):(T=f.sub(w)._perp()._unit(),D=Vse(f,b,T)),Ltt(w,f,b,S6e(T,D),S)}function Ltt(w,f,b,S,T){const D=Math.sqrt(1-S*S);return Math.min(w.dist(f)/3,f.dist(b)/3,T*D/S)}function C6e(w,f,b){return w.xb[1].x&&f.x>b[1].x||w.yb[1].y&&f.y>b[1].y}function Rtt(w,f){return w.xf[1].x||w.yf[1].y}function bXt(w){return w.every(f=>f.x<=0)||w.every(f=>f.x>=br)||w.every(f=>f.y<=0)||w.every(f=>f.y>=br)}function Dtt(w,f,b){if(w.x<0||w.x>=br||f.x<0||f.x>=br||b.x<0||b.x>=br)return!1;const S=b.sub(f),T=S.perp(),D=w.sub(f);return(S.x*D.x+S.y*D.y)/Math.sqrt((S.x*S.x+S.y*S.y)*(D.x*D.x+D.y*D.y))>-.866&&T.x*D.x+T.y*D.y<0}function Ott(w,f,b){const S=f?2|w:-3&w;return b?1|S:-2&S}function Ftt(){const w=Math.PI/32,f=Math.tan(w),b=E;return b*Math.sqrt(1+2*f*f)-b}function ztt(w,f,b){const S=1<{for(const Ct of kt)Me.push({polygon:Ct,bounds:es})},Ve=Math.ceil(Math.log2(ce)),Je=Math.ceil(Math.log2(pe)),lt=Ve-Je,ht=[];for(let kt=0;kt0?0:1);for(let kt=0;ktes+1?xt.push({polygons:on,bounds:hn,depth:es+1}):ze(on,hn)}if(sn.length){const hn=[new Kt(Ct===0?Fs:Lt.x,Ct===1?Fs:Lt.y),Zt];ht.length>es+1?xt.push({polygons:sn,bounds:hn,depth:es+1}):ze(sn,hn)}}return Me}(w,f,Math.ceil((D-T)/11.25),Math.ceil((F-q)/11.25),1,(K,X,ce)=>{if(K===0)return .5*(X+ce);{const pe=hh((b.y+X/br)/S);return(mp(.5*(hh((b.y+ce/br)/S)+pe))*S-b.y)*br}})}function _Xt(w,f,b,S,T,D){const F=Math.pow(2,S.z-T.z);for(let q=0;qA6e?-1:(new Int32Array(this.module.heap32.buffer,b,f.length).set(f),b)}createFloatArray(f){const b=this.memoryStackNextFree;return this.memoryStackNextFree+=f.length*Float32Array.BYTES_PER_ELEMENT,this.memoryStackNextFree-this.memoryStack>A6e?-1:(new Float32Array(this.module.heapF32.buffer,b,f.length).set(f),b)}readStringBuffer(f){let b="";for(;this.module.heapU8[f]!==0;)b+=String.fromCharCode(this.module.heapU8[f]),++f;return b}setStyle(f){const b=f.normalScale;this.module.setStyle(b[0],b[1],b[2],f.tileToMeters)}setAOOptions(f,b){this.module.setAOOptions(f?1:0,b)}setMetricOptions(f,b){this.module.setMetricOptions(f?1:0,b)}setStructuralOptions(f){this.module.setStructuralOptions(f?1:0)}setFacadeOptions(f,b){this.module.setFacadeOptions(f,b?1:0)}setFauxFacadeOptions(f,b,S){this.module.setFauxFacadeOptions(f?1:0,b?1:0,S)}setFacadeClassifierOptions(f){this.module.setFacadeClassifierOptions(f)}generateMesh(f,b){this.memoryStackNextFree=this.memoryStack;for(const q of f){const K=this.createIntArray(q.ringIndices),X=this.createFloatArray(q.coordinates);if(K===-1||X===-1)return`building_gen: Out of stack memory: ${this.memoryStackNextFree-this.memoryStack}/4096`;this.module.addFeature(q.id,q.sourceId,q.minHeight,q.height,q.roofType,X,K,q.ringIndices.length-1)}for(const q of b){let K;K=q.entrances?JSON.parse(q.entrances):[];const X=this.createFloatArray(K),ce=this.createFloatArray(q.coordinates);if(X===-1||ce===-1)return`building_gen: Out of stack memory: ${this.memoryStackNextFree-this.memoryStack}/4096`;this.module.addFacade(q.sourceId,q.crossPerc,q.distanceToRoad,X,K.length,ce,q.coordinates.length)}if(!this.module.generateMesh()){const q=this.module.getLastError();return this.readStringBuffer(q)}const S=this.module.getMeshCount(),T=new Array(S);for(let q=0;qb||T.y<-f||T.y>b)return!1;return!0}function NXt(w){switch(w){case"flat":return 3;case"hipped":return 1;case"gabled":return 2;case"parapet":return 0;case"mansard":return 4;case"skillion":return 5;case"pyramidal":return 6;default:throw new Error(`Unknown roof shape: ${w}`)}}let $tt,Utt,N7=null,qtt=null,nw=null;class E6e{constructor(){this.layoutVertexArray=new Nr,this.layoutAttenuationArray=new ci,this.layoutColorArray=new ao,this.indexArray=new Va,this.indexArrayForConflation=new Va,this.segmentsBucket=new lc}}class T6e{constructor(f){this.layoutFacadePaintArray=null,this.layoutFacadeDataArray=null,this.layoutFacadeVerticalRangeArray=null,this.segmentsBucket=new lc,this.entranceBloom=new E6e;const b=66560;this.layoutVertexArray=new Nr,this.layoutVertexArray.reserve(b),this.layoutNormalArray=new lr,this.layoutNormalArray.reserve(b),this.layoutCentroidArray=new lr,this.layoutCentroidArray.reserve(b),this.layoutColorArray=new ao,this.layoutColorArray.reserve(b),this.layoutFloodLightDataArray=new af,this.layoutFloodLightDataArray.reserve(b),this.layoutAOArray=new Pv,this.layoutAOArray.reserve(b),this.indexArray=new Va,this.indexArray.reserve(66560),this.indexArrayForConflation=new Va,this.segmentsBucket=new lc,this.entranceBloom=new E6e,f&&(this.layoutFacadePaintArray=new ao,this.layoutFacadeDataArray=new Fr,this.layoutFacadeVerticalRangeArray=new ao)}reserve(f,b,S){this.layoutVertexArray.reserveForAdditional(f),this.layoutCentroidArray.reserveForAdditional(f),this.layoutFloodLightDataArray.reserveForAdditional(f),this.layoutNormalArray.reserveForAdditional(f),this.layoutAOArray.reserveForAdditional(f),this.layoutColorArray.reserveForAdditional(f),this.indexArray.reserveForAdditional(b),S&&(this.layoutFacadePaintArray.reserveForAdditional(f),this.layoutFacadeDataArray.reserveForAdditional(f),this.layoutFacadeVerticalRangeArray.reserveForAdditional(f))}}class Vtt{constructor(f){this.requiresHDRuntime=!0,this.colorBufferUploaded=!1,this.maxHeight=0,this.replacementUpdateTime=0,this.activeReplacements=[],this.footprints=[],this.footprintsVertices=new Hc,this.footprintsIndices=new Yl,this.footprintsMin=new Kt(1/0,1/0),this.footprintsMax=new Kt(-1/0,-1/0),this.featuresOnBorder=[],this.buildingWithoutFacade=new T6e(!1),this.buildingWithFacade=new T6e(!0),this.indexArrayForConflationUploaded=!1,this.featureFootprintLookup=new Map,this.buildingIds=new Set,this.footprintLookup={},this.zoom=f.zoom,this.canonical=f.canonical,this.layers=f.layers,this.layerIds=this.layers.map(b=>b.fqid),this.index=f.index,this.hasPattern=!1,this.worldview=f.worldview,this.lut=f.lut,this.programConfigurations=new aN(f.layers,{zoom:f.zoom,lut:f.lut}),this.stateDependentLayerIds=this.layers.filter(b=>b.isStateDependent()).map(b=>b.id),this.projection=f.projection,this.groundEffect=new k6e(f),this.groundEffect.groundRadiusArray=new Hn,this.hasAppearances=null}updateFootprints(f,b){const S=new Tse([],[],1),T={vertices:[],indices:new Uint32Array(0),grid:S,min:this.footprintsMin,max:this.footprintsMax,buildingIds:this.buildingIds};b.push({footprint:T,id:f})}updateAppearances(f,b,S,T){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(f,b,S,T){if(!nw)return;const D=mt(S);this.tileToMeter=D,this.brightness=b.brightness,nw.setStyle({normalScale:[1,-1,D],tileToMeters:D}),nw.setAOOptions(!1,.3),nw.setMetricOptions(!1,16),nw.setStructuralOptions(!0),nw.setFacadeClassifierOptions(3);const F=new Map,q=new Map;let K=0;for(const{feature:Ve}of f){if(Btt[Ve.type]!=="LineString"){F.set(Ve.id,Ve.properties.source_id);continue}const Je=this.layers[0]._featureFilter.needGeometry;if(Je&&!this.layers[0]._featureFilter.filter(new tr(this.zoom),Ve,S))continue;const lt=Js(Ve,Je);if(!Je&&!this.layers[0]._featureFilter.filter(new tr(this.zoom),lt,S))continue;const ht=Je?lt.geometry:Ms(Ve,S,T),ct=[];for(const Ct of ht)for(const Lt of Ct)ct.push(Lt.x),ct.push(Lt.y);const xt={coordinates:ct,crossPerc:Ve.properties.cross_perc,distanceToRoad:Ve.properties.distance_to_road,entrances:Ve.properties.entrances,sourceId:0},kt=Ve.properties.source_id;let es=q.get(kt);es||(es=[],q.set(kt,es)),es.push(xt),++K}this.maxHeight=0;const X=new Array,ce=new Set,pe=Ve=>{Ve!=null&&ce.add(Ve)},xe=(Ve,Je)=>{Ve!=null&&X.push({buildingId:Ve,footprintIndex:Je})},Ne=64*(f.length-K),Me=Ne/2;this.buildingWithFacade.reserve(Ne,Me,!0),this.buildingWithoutFacade.reserve(2*Ne,2*Me,!1),this.footprintsIndices.reserve(16*(f.length-K)),this.footprintsVertices.reserve(8*(f.length-K));for(const{feature:Ve,id:Je,index:lt,sourceLayerIndex:ht}of f){if(Btt[Ve.type]==="LineString")continue;const ct=this.layers[0]._featureFilter.needGeometry;if(ct&&!this.layers[0]._featureFilter.filter(new tr(this.zoom),Ve,S))continue;let xt=null;if(Ve.properties&&Object.hasOwn(Ve.properties,"building_id")&&(xt=Number(Ve.properties.building_id),ce.has(xt)))continue;const kt=Js(Ve,ct);if(!ct&&!this.layers[0]._featureFilter.filter(new tr(this.zoom),kt,S))continue;const es=ct?kt.geometry:Ms(Ve,S,T),Ct=Ur(es,500);let Lt=!1;for(const _o of Ct)if(_o.length!==1){Lt=!0;break}if(Lt){pe(xt);continue}if(!jXt(es,163)){pe(xt);continue}const Zt=this.layers[0],Qt=NXt(Zt.layout.get("building-roof-shape").evaluate(Ve,{},S)),Cs=Zt.layout.get("building-base").evaluate(Ve,{},S),Fs=Zt.layout.get("building-height").evaluate(Ve,{},S),on=Zt.layout.get("building-flood-light-ground-radius").evaluate(Ve,{},S),sn=Zt.paint.get("building-ambient-occlusion-intensity"),hn=on/this.tileToMeter;Ve.properties["building-part"]="roof";const Rn=Zt.paint.get("building-color").evaluate(Ve,{},this.canonical).toPremultipliedRenderColor(this.lut),ws=Zt.paint.get("building-emissive-strength").evaluate(Ve,{},this.canonical);Ve.properties["building-part"]="wall";const qs=Zt.paint.get("building-color").evaluate(Ve,{},this.canonical).toPremultipliedRenderColor(this.lut),en=Zt.paint.get("building-emissive-strength").evaluate(Ve,{},this.canonical);Ve.properties["building-part"]="window";const wn=Zt.paint.get("building-color").evaluate(Ve,{},this.canonical).toPremultipliedRenderColor(this.lut),Nn=Zt.paint.get("building-emissive-strength").evaluate(Ve,{},this.canonical);Ve.properties["building-part"]="door";const Pn=Zt.paint.get("building-color").evaluate(Ve,{},this.canonical).toPremultipliedRenderColor(this.lut),jn=Zt.paint.get("building-emissive-strength").evaluate(Ve,{},this.canonical);let Wn=Zt.layout.get("building-flood-light-wall-radius").evaluate(Ve,{},S);Wn=Jr(Wn,0,2048);const Kn=Wn/2048*Hse,Dr=F.get(Je),sr=q.get(Dr)||[],yr=sr.length!==0&&Zt.layout.get("building-facade").evaluate(Ve,{},S);nw.setFacadeOptions(4,!0),nw.setFauxFacadeOptions(yr,!1,1);let Ra=0,$a=0,si=0,La=0,Oi=0,bi=0,Bl=0,cl=0,Ll=0,dc=0,cf=0;if(yr){let _o=Math.round(Zt.layout.get("building-facade-floors").evaluate(Ve,{},S));if(Cs===0){_o=Math.max(1,_o-(sr.length>0?1:0));let hu=4;if(Fs>100){const uf=[10,13,15];hu=uf[Ve.id?Ve.id%uf.length:0]}else Fs<=10&&(hu=3);nw.setFacadeOptions(hu,!0),Oi=(Fs<15?1.3:1.61803)*hu/D}else Oi=Cs/D;bi=Fs/D,Oi=Math.min(Oi,bi),si=Zt.layout.get("building-facade-unit-width").evaluate(Ve,{},S)/D,La=(bi-Oi)/_o,nw.setFauxFacadeOptions(!0,!0,si);const lm=Zt.layout.get("building-facade-window").evaluate(Ve,{},S);Ra=lm[0],$a=lm[1],Bl=Math.floor(65535*Math.min(1,Oi/br)),cl=Math.floor(65535*Math.min(1,bi/br)),Ll=Math.floor(255*Ra)<<8|Math.floor(255*$a),dc=Math.floor(65535*Math.min(1,si/br)),cf=Math.floor(65535*Math.min(1,La/br))}const $1=Array(Ct.length),Wh={x:1/0,y:1/0},xl={x:-1/0,y:-1/0},Jd={x:0,y:0};let om=0;for(let _o=0;_o0){const hu=[],uf=Array(lm.length+1);uf[0]=0;for(let ny=0;nybr||Wh.y<0||xl.y>br)&&this.featuresOnBorder.push({featureId:Ve.id,footprintIndex:this.footprints.length});{const _o=rN(nS,null,2);this.footprintsIndices.resize(this.footprintsIndices.length+_o.length),this.footprintsIndices.uint16.set(_o,Fv),this.buildingIds.add(xt??Ve.id),this.footprintsMin.x=Math.min(this.footprintsMin.x,qb.x),this.footprintsMin.y=Math.min(this.footprintsMin.y,qb.y),this.footprintsMax.x=Math.max(this.footprintsMax.x,qy.x),this.footprintsMax.y=Math.max(this.footprintsMax.y,qy.y);const lm={footprintVertexOffset:$g,footprintVertexLength:this.footprintsVertices.length-$g,footprintIndexOffset:Fv,footprintIndexLength:this.footprintsIndices.length-Fv,min:qb,max:qy,hiddenFlags:0,indicesOffset:_x,indicesLength:Ov,bloomIndicesOffset:Lv,bloomIndicesLength:Rv,groundEffectVertexOffset:rS,groundEffectVertexLength:aS,hasFauxFacade:yr,height:Dv,promoteId:Je,feature:kt,parts:$y,buildingBloom:Uy},hu=this.footprints.length;Ve.id!==void 0&&this.featureFootprintLookup.set(Ve.id,hu),xe(xt,hu),this.footprints.push(lm)}this.programConfigurations.populatePaintArrays(Xi.layoutVertexArray.length,Ve,lt,{},b.availableImages,S,b.brightness),this.groundEffect.addPaintPropertiesData(Ve,lt,{},b.availableImages,S,b.brightness),b.featureIndex.insert(Ve,es,lt,ht,this.index,bx)}X.forEach(({buildingId:Ve,footprintIndex:Je})=>{ce.has(Ve)&&(this.footprints[Je].hiddenFlags|=4)});const ze=new Set;this.buildingIds.forEach((Ve,Je,lt)=>{ce.has(Ve)||ze.add(Ve)}),this.buildingIds=ze,this.groundEffect.prepareBorderSegments()}update(f,b,S,T,D,F,q){this.programConfigurations.updatePaintArrays(f,b,D,S,T,F,q),this.groundEffect.update(f,b,D,S,T,F,q),this.evaluate(this.layers[0],f),this.colorBufferUploaded=!1}updateExpressions(f){this.programConfigurations.updateExpressions(f),this.groundEffect.programConfigurations.updateExpressions(f)}isEmpty(){return this.buildingWithoutFacade.layoutVertexArray.length===0&&this.buildingWithFacade.layoutVertexArray.length===0}uploadPending(){return!this.uploaded||this.programConfigurations.needsUpload||this.groundEffect.programConfigurations.needsUpload}upload(f){const b=S=>{S.layoutVertexBuffer=f.createVertexBuffer(S.layoutVertexArray,Att.members),S.layoutNormalBuffer=f.createVertexBuffer(S.layoutNormalArray,XZt.members),S.layoutCentroidBuffer=f.createVertexBuffer(S.layoutCentroidArray,QZt.members),S.layoutFloodLightDataBuffer=f.createVertexBuffer(S.layoutFloodLightDataArray,nXt.members),S.layoutFacadeDataArray&&S.layoutFacadeDataArray.length&&(S.layoutFacadeDataBuffer=f.createVertexBuffer(S.layoutFacadeDataArray,eXt.members)),S.layoutFacadeVerticalRangeArray&&S.layoutFacadeVerticalRangeArray.length&&(S.layoutFacadeVerticalRangeBuffer=f.createVertexBuffer(S.layoutFacadeVerticalRangeArray,tXt.members)),S.entranceBloom.layoutVertexArray.length&&(S.entranceBloom.layoutVertexBuffer=f.createVertexBuffer(S.entranceBloom.layoutVertexArray,Att.members),S.entranceBloom.layoutAttenuationBuffer=f.createVertexBuffer(S.entranceBloom.layoutAttenuationArray,sXt.members)),this.uploadUpdatedColorBuffer(f),this.uploadUpdatedIndexBuffer(f)};this.uploaded||(b(this.buildingWithoutFacade),b(this.buildingWithFacade),this.groundEffect.upload(f)),this.groundEffect.uploadPaintProperties(f),this.programConfigurations.upload(f),this.uploaded=!0}destroy(){const f=b=>{b.layoutVertexBuffer&&(b.layoutVertexBuffer.destroy(),b.layoutNormalBuffer.destroy(),b.layoutColorBuffer.destroy(),b.segmentsBucket.destroy(),b.indexBuffer&&b.indexBuffer.destroy(),b.entranceBloom.layoutVertexBuffer&&(b.entranceBloom.layoutVertexBuffer.destroy(),b.entranceBloom.layoutColorBuffer.destroy(),b.entranceBloom.layoutAttenuationBuffer.destroy(),b.entranceBloom.indexBuffer.destroy(),b.entranceBloom.segmentsBucket.destroy()))};f(this.buildingWithoutFacade),f(this.buildingWithFacade),this.groundEffect.destroy(),this.programConfigurations.destroy()}updateFootprintHiddenFlags(f,b,S=!0){let T=!1;const D=S?b:0,F=0|(S?-1:~b);this.groundEffect.hiddenByLandmarkVertexArray.length===0&&this.groundEffect.hiddenByLandmarkVertexArray.resize(this.groundEffect.vertexArray.length);for(const q of f){const K=this.footprints[q],X=K.hiddenFlags&F|D;K.hiddenFlags!==X&&(K.hiddenFlags=X,T=!0,this.groundEffect.updateHiddenByLandmarkRange(K.groundEffectVertexOffset,K.groundEffectVertexLength,K.hiddenFlags!==0))}return T&&(this.indexArrayForConflationUploaded=!1),T}uploadUpdatedIndexBuffer(f){if(this.groundEffect.uploadHiddenByLandmark(f),this.indexArrayForConflationUploaded)return;const b=T=>{T.indexArray.length!==0&&(T.indexArrayForConflation.resize(T.indexArray.length),T.indexArrayForConflation.uint16.set(T.indexArray.uint16),T.entranceBloom.indexArrayForConflation.resize(T.entranceBloom.indexArray.length),T.entranceBloom.indexArrayForConflation.uint16.set(T.entranceBloom.indexArray.uint16))};b(this.buildingWithoutFacade),b(this.buildingWithFacade);for(const T of this.footprints){const D=T.hasFauxFacade?this.buildingWithFacade:this.buildingWithoutFacade,F=T.indicesOffset+T.indicesLength;if(T.hiddenFlags!==0){for(let K=T.indicesOffset;K{T.indexArray.length!==0&&(T.indexBuffer?T.indexBuffer.updateData(T.indexArrayForConflation):T.indexBuffer=f.createIndexBuffer(T.indexArrayForConflation,!0),T.entranceBloom.indexBuffer?T.entranceBloom.indexBuffer.updateData(T.entranceBloom.indexArrayForConflation):T.entranceBloom.indexBuffer=f.createIndexBuffer(T.entranceBloom.indexArrayForConflation,!0))};S(this.buildingWithoutFacade),S(this.buildingWithFacade),this.indexArrayForConflationUploaded=!0}uploadUpdatedColorBuffer(f){const b=S=>{S.layoutColorBuffer?S.layoutColorBuffer.updateData(S.layoutColorArray):S.layoutColorBuffer=f.createVertexBuffer(S.layoutColorArray,Ett.members,!0),S.layoutFacadePaintArray&&(S.layoutFacadePaintBuffer?S.layoutFacadePaintBuffer.updateData(S.layoutFacadePaintArray):S.layoutFacadePaintBuffer=f.createVertexBuffer(S.layoutFacadePaintArray,JZt.members,!0)),S.entranceBloom.layoutColorBuffer?S.entranceBloom.layoutColorBuffer.updateData(S.entranceBloom.layoutColorArray):S.entranceBloom.layoutColorBuffer=f.createVertexBuffer(S.entranceBloom.layoutColorArray,Ett.members,!0)};b(this.buildingWithoutFacade),b(this.buildingWithFacade),this.colorBufferUploaded=!0}evaluate(f,b){const S=f.paint.get("building-ambient-occlusion-intensity");for(const T of this.footprints){if(4&T.hiddenFlags)continue;const D=b[T.promoteId],F=T.feature;F.properties["building-part"]="roof";const q=f.paint.get("building-color").evaluate(F,D,this.canonical).toPremultipliedRenderColor(this.lut),K=f.paint.get("building-emissive-strength").evaluate(F,D,this.canonical);F.properties["building-part"]="wall";const X=f.paint.get("building-color").evaluate(F,D,this.canonical).toPremultipliedRenderColor(this.lut),ce=f.paint.get("building-emissive-strength").evaluate(F,D,this.canonical);F.properties["building-part"]="window";const pe=f.paint.get("building-color").evaluate(F,D,this.canonical).toPremultipliedRenderColor(this.lut),xe=f.paint.get("building-emissive-strength").evaluate(F,D,this.canonical);F.properties["building-part"]="door";const Ne=f.paint.get("building-color").evaluate(F,D,this.canonical).toPremultipliedRenderColor(this.lut),Me=f.paint.get("building-emissive-strength").evaluate(F,D,this.canonical),ze=T.hasFauxFacade?this.buildingWithFacade:this.buildingWithoutFacade;for(const Je of T.parts){let lt,ht=q;Je.part===1?(ht=q,lt=K):Je.part===0?(ht=X,lt=ce):Je.part===2?(ht=pe,lt=xe):Je.part===3&&(ht=Ne,lt=Me),lt=Jr(lt,0,1);for(let ct=0;ctF.max.x||K.max.xF.max.y||K.max.yq.max.x||q.min.x>f||b>q.max.y||q.min.y>b||q.height<=S||kXt(F,this.footprintsVertices.float32.subarray(2*q.footprintVertexOffset,2*(q.footprintVertexOffset+q.footprintVertexLength)),this.footprintsIndices.uint16.subarray(q.footprintIndexOffset,q.footprintIndexOffset+q.footprintIndexLength))&&(S=q.height,this.footprintLookup[D]=q,T=q.hiddenFlags!==0);if(S!==Number.NEGATIVE_INFINITY)return{height:S,hidden:T};this.footprintLookup[D]=void 0}}function kXt(w,f,b){for(let S=0;S0&&this.rings[0].length>0}}async function Gse(){}function k7(w,f,b){const S=f.paint.get(w).value;return S.kind==="constant"?S.value:b.programConfigurations.get(f.id).getMaxValue(w)}function Wse(w){return Math.sqrt(w[0]*w[0]+w[1]*w[1])}function Gtt(w,f,b,S,T){if(!f[0]&&!f[1])return w;const D=Kt.convert(f)._mult(T);b==="viewport"&&D._rotate(-S);const F=[];for(let q=0;q{const f=[];return w.paint.get("circle-pitch-alignment")==="map"&&f.push("PITCH_WITH_MAP"),w.paint.get("circle-pitch-scale")==="map"&&f.push("SCALE_WITH_MAP"),f};function Ytt(w,f,b,S,T,D,F,q,K){if(D&&w.queryGeometry.isAboveHorizon)return!1;D&&(K*=w.pixelToTileUnitsFactor);const X=w.tileID.canonical,ce=b.projection.upVectorScale(X,b.center.lat,b.worldSize).metersToTile;for(const pe of f)for(const xe of pe){const Ne=xe.add(q),Me=T&&b.elevation?b.elevation.exaggeration()*T.getElevationAt(Ne.x,Ne.y,!0):0,ze=b.projection.projectTilePoint(Ne.x,Ne.y,X);if(Me>0){const ht=b.projection.upVector(X,Ne.x,Ne.y);ze.x+=ht[0]*ce*Me,ze.y+=ht[1]*ce*Me,ze.z+=ht[2]*ce*Me}const Ve=D?Ne:AXt(ze.x,ze.y,ze.z,S),Je=D?w.tilespaceRays.map(ht=>TXt(ht,Me)):w.queryGeometry.screenGeometry,lt=dt([],[ze.x,ze.y,ze.z,1],S);if(!F&&D?K*=lt[3]/b.cameraToCenterDistance:F&&!D&&(K*=b.cameraToCenterDistance/lt[3]),D){const ht=hh((xe.y/br+X.y)/(1<da(f,b,S==="log"?(Math.pow(10,w)-1)/9:w);function MH(w){const{expression:f,evaluationKey:b,resolution:S=256,clips:T,scale:D="linear",lut:F=null}=w,q=T?T.length:1,K=w.image||new sy({width:S,height:q}),X={},ce=(pe,xe,Ne)=>{X[b]=Ne;const Me=f.evaluate(X),ze=(Me==null?void 0:Me.toNonPremultipliedRenderColor(F))??null;ze&&(K.data[pe+xe+0]=Math.floor(255*ze.r),K.data[pe+xe+1]=Math.floor(255*ze.g),K.data[pe+xe+2]=Math.floor(255*ze.b),K.data[pe+xe+3]=Math.floor(255*ze.a))};for(let pe=0,xe=0;peb.fqid),this.index=f.index,this.hasPattern=!1,this.stateDependentLayerIds=this.layers.filter(b=>b.isStateDependent()).map(b=>b.id),this.footprints=[],this.worldview=f.worldview,this.hasAppearances=null}updateFootprints(f,b){for(const S of this.footprints)b.push({footprint:S,id:f})}updateAppearances(f,b,S,T){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(f,b,S,T){const D=[];for(const{feature:F,id:q,index:K,sourceLayerIndex:X}of f){const ce=this.layers[0]._featureFilter.needGeometry,pe=Js(F,ce);if(!this.layers[0]._featureFilter.filter(new tr(this.zoom,{worldview:this.worldview,activeFloors:b.activeFloors}),pe,S))continue;const xe={id:q,properties:F.properties,type:F.type,sourceLayerIndex:X,index:K,geometry:ce?pe.geometry:Ms(F,S,T),patterns:{}};D.push(xe)}for(const F of D){const{geometry:q,index:K,sourceLayerIndex:X}=F;this.addFeature(F,q,K,S,{},b.availableImages,b.brightness),b.featureIndex.insert(f[K].feature,q,K,X,this.index)}}isEmpty(){return this.footprints.length===0}uploadPending(){return!1}upload(f){}update(f,b,S,T,D,F,q){}destroy(){}addFeature(f,b,S,T,D,F=[],q){for(const K of Ur(b,2)){const X=[],ce=[],pe=[],xe=new Kt(1/0,1/0),Ne=new Kt(-1/0,-1/0);for(const Ve of K)if(Ve.length!==0){Ve!==K[0]&&pe.push(ce.length/2);for(let Je=0;Je{Fs[0]=on,Fs[1]=sn,Fs[2]=hn,Fs[3]=1},Cs=Ftt();Ne>0&&(Ne+=Cs),Me+=Cs;for(const Fs of xe){const on=[],sn=[];for(const hn of Fs){const Rn=hn.x+ze.x,ws=hn.y+ze.y,qs=pe.projection.projectTilePoint(Rn,ws,xt),en=pe.projection.upVector(xt,hn.x,hn.y);let wn=Ne,Nn=Me;if(Je){const Pn=gst(Rn,ws,Ne,Me,Je,lt,ht,ct);wn+=Pn.base,Nn+=Pn.top}Ne!==0?Qt(Lt,qs.x+en[0]*Ct*wn,qs.y+en[1]*Ct*wn,qs.z+en[2]*Ct*wn):Qt(Lt,qs.x,qs.y,qs.z),Qt(Zt,qs.x+en[0]*Ct*Nn,qs.y+en[1]*Ct*Nn,qs.z+en[2]*Ct*Nn),tt(Lt,Lt,Ve),tt(Zt,Zt,Ve),on.push(new V6(Lt[0],Lt[1],Lt[2])),sn.push(new V6(Zt[0],Zt[1],Zt[2]))}kt.push(on),es.push(sn)}return[kt,es]}(w,f,b,S,T,D,F,q,K,X,ce):F?function(pe,xe,Ne,Me,ze,Ve,Je,lt,ht){const ct=[],xt=[],kt=[0,0,0,1];for(const es of pe){const Ct=[],Lt=[];for(const Zt of es){const Qt=Zt.x+Me.x,Cs=Zt.y+Me.y,Fs=gst(Qt,Cs,xe,Ne,Ve,Je,lt,ht);kt[0]=Qt,kt[1]=Cs,kt[2]=Fs.base,kt[3]=1,dt(kt,kt,ze),kt[3]=Math.max(kt[3],1e-5);const on=new V6(kt[0]/kt[3],kt[1]/kt[3],kt[2]/kt[3]);kt[0]=Qt,kt[1]=Cs,kt[2]=Fs.top,kt[3]=1,dt(kt,kt,ze),kt[3]=Math.max(kt[3],1e-5);const sn=new V6(kt[0]/kt[3],kt[1]/kt[3],kt[2]/kt[3]);Ct.push(on),Lt.push(sn)}ct.push(Ct),xt.push(Lt)}return[ct,xt]}(f,b,S,T,D,F,q,K,X):function(pe,xe,Ne,Me,ze){const Ve=[],Je=[],lt=ze[8]*xe,ht=ze[9]*xe,ct=ze[10]*xe,xt=ze[11]*xe,kt=ze[8]*Ne,es=ze[9]*Ne,Ct=ze[10]*Ne,Lt=ze[11]*Ne;for(const Zt of pe){const Qt=[],Cs=[];for(const Fs of Zt){const on=Fs.x+Me.x,sn=Fs.y+Me.y,hn=ze[0]*on+ze[4]*sn+ze[12],Rn=ze[1]*on+ze[5]*sn+ze[13],ws=ze[2]*on+ze[6]*sn+ze[14],qs=ze[3]*on+ze[7]*sn+ze[15],en=hn+lt,wn=Rn+ht,Nn=ws+ct,Pn=Math.max(qs+xt,1e-5),jn=hn+kt,Wn=Rn+es,Kn=ws+Ct,Dr=Math.max(qs+Lt,1e-5);Qt.push(new V6(en/Pn,wn/Pn,Nn/Pn)),Cs.push(new V6(jn/Dr,Wn/Dr,Kn/Dr))}Ve.push(Qt),Je.push(Cs)}return[Ve,Je]}(f,b,S,T,D)}function gst(w,f,b,S,T,D,F,q){const K=F*T.getElevationAt(w,f,!0,!0),X=D[0]!==0,ce=X?D[1]===0?F*(D[0]/7-450):F*function(pe,xe,Ne){const Me=Math.floor(xe[0]/8),ze=Math.floor(xe[1]/8),Ve=10*(xe[0]-8*Me),Je=10*(xe[1]-8*ze),lt=pe.getElevationAt(Me,ze,!0,!0),ht=pe.getMeterToDEM(Ne),ct=Math.floor(.5*(Ve*ht-1)),xt=Math.floor(.5*(Je*ht-1)),kt=pe.tileCoordToPixel(Me,ze),es=2*ct+1,Ct=2*xt+1,Lt=function(sn,hn,Rn,ws,qs){return[sn.getElevationAtPixel(hn,Rn,!0),sn.getElevationAtPixel(hn+qs,Rn,!0),sn.getElevationAtPixel(hn,Rn+qs,!0),sn.getElevationAtPixel(hn+ws,Rn+qs,!0)]}(pe,kt.x-ct,kt.y-xt,es,Ct),Zt=Math.abs(Lt[0]-Lt[1]),Qt=Math.abs(Lt[2]-Lt[3]),Cs=Math.abs(Lt[0]-Lt[2])+Math.abs(Lt[1]-Lt[3]),Fs=Math.min(.25,.5*ht*(Zt+Qt)/es),on=Math.min(.25,.5*ht*Cs/Ct);return lt+Math.max(Fs*Ve,on*Je)}(T,D,q):K;return{base:K+(b===0?-1:b),top:X?Math.max(ce+S,K+b+2):K+S}}function IH(w,f,b){return f*(br/(w.tileSize*Math.pow(2,b-w.tileID.overscaledZ)))}function xst(w,f){return 1/IH(w,1,f.tileZoom)}function yst(w,f,b,S){return w.translatePosMatrix(S||f.tileID.projMatrix,f,b.paint.get("line-translate"),b.paint.get("line-translate-anchor"))}Vr(hst,"ClipBucket",{omit:["layers"]});const vst=w=>{const f=[];bst(w)&&f.push("RENDER_LINE_DASH"),w.paint.get("line-gradient")&&f.push("RENDER_LINE_GRADIENT"),w.paint.get("line-blend-mode")==="multiply"&&f.push("LINE_BLEND_MULTIPLY"),w.paint.get("line-blend-mode")==="additive"&&f.push("LINE_BLEND_ADDITIVE");const b=w.paint.get("line-trim-offset");b[0]===0&&b[1]===0||f.push("RENDER_LINE_TRIM_OFFSET");const S=w.paint.get("line-border-width").constantOr(1)!==0;S&&f.push("RENDER_LINE_BORDER"),S&&w.paint.get("line-border-gradient")&&f.push("RENDER_LINE_BORDER_GRADIENT");const T=w.layout.get("line-join").constantOr("miter")==="none",D=!!w.paint.get("line-pattern").constantOr(1);return T&&D&&f.push("LINE_JOIN_NONE"),f};function bst(w){const f=w.paint.get("line-dasharray").value;return f.kind!=="constant"||f.value}let M6e;const _st=()=>M6e||(M6e={layout:dst||(dst=new $d({"line-cap":new hr(Us.layout_line["line-cap"]),"line-join":new hr(Us.layout_line["line-join"]),"line-miter-limit":new Bn(Us.layout_line["line-miter-limit"]),"line-round-limit":new Bn(Us.layout_line["line-round-limit"]),"line-sort-key":new hr(Us.layout_line["line-sort-key"]),"line-z-offset":new hr(Us.layout_line["line-z-offset"]),"line-elevation-reference":new Bn(Us.layout_line["line-elevation-reference"]),"line-cross-slope":new Bn(Us.layout_line["line-cross-slope"]),visibility:new Bn(Us.layout_line.visibility),"line-width-unit":new Bn(Us.layout_line["line-width-unit"]),"line-elevation-ground-scale":new hr(Us.layout_line["line-elevation-ground-scale"])})),paint:ust||(ust=new $d({"line-opacity":new hr(Us.paint_line["line-opacity"]),"line-color":new hr(Us.paint_line["line-color"]),"line-translate":new Bn(Us.paint_line["line-translate"]),"line-translate-anchor":new Bn(Us.paint_line["line-translate-anchor"]),"line-width":new hr(Us.paint_line["line-width"]),"line-gap-width":new hr(Us.paint_line["line-gap-width"]),"line-offset":new hr(Us.paint_line["line-offset"]),"line-blur":new hr(Us.paint_line["line-blur"]),"line-dasharray":new hr(Us.paint_line["line-dasharray"]),"line-pattern":new hr(Us.paint_line["line-pattern"]),"line-pattern-cross-fade":new Bn(Us.paint_line["line-pattern-cross-fade"]),"line-gradient":new Aj(Us.paint_line["line-gradient"]),"line-trim-offset":new Bn(Us.paint_line["line-trim-offset"]),"line-trim-fade-range":new Bn(Us.paint_line["line-trim-fade-range"]),"line-trim-color":new Bn(Us.paint_line["line-trim-color"]),"line-emissive-strength":new hr(Us.paint_line["line-emissive-strength"]),"line-border-width":new hr(Us.paint_line["line-border-width"]),"line-border-color":new hr(Us.paint_line["line-border-color"]),"line-border-gradient":new Aj(Us.paint_line["line-border-gradient"]),"line-occlusion-opacity":new Bn(Us.paint_line["line-occlusion-opacity"]),"line-blend-mode":new Bn(Us.paint_line["line-blend-mode"]),"line-blend-additive-clamp":new Bn(Us.paint_line["line-blend-additive-clamp"]),"line-cutout-depth":new Bn(Us.paint_line["line-cutout-depth"]),"line-color-use-theme":new hr({type:"string",default:"default","property-type":"data-driven"}),"line-gradient-use-theme":new hr({type:"string",default:"default","property-type":"data-driven"}),"line-trim-color-use-theme":new hr({type:"string",default:"default","property-type":"data-driven"}),"line-border-color-use-theme":new hr({type:"string",default:"default","property-type":"data-driven"}),"line-border-gradient-use-theme":new hr({type:"string",default:"default","property-type":"data-driven"})}))},M6e);class PXt extends hr{possiblyEvaluate(f,b){return b=new tr(Math.floor(b.zoom),{now:b.now,fadeDuration:b.fadeDuration,transition:b.transition,worldview:b.worldview}),super.possiblyEvaluate(f,b)}evaluate(f,b,S,T){return b={...b,zoom:Math.floor(b.zoom)},super.evaluate(f,b,S,T)}}let LH,wst,jst,P6e;function Nst(w,f){return f>0?f+2*w:w}function kst(w,f){return f.replace(/{([^{}]+)}/g,(b,S)=>S in w?String(w[S]):"")}class Sst{constructor(f){this.type=f.property.overrides?f.property.overrides.runtimeType:sl,this.defaultValue=f}evaluate(f){if(f.formattedSection){const b=this.defaultValue.property.overrides;if(b&&b.hasOverride(f.formattedSection))return b.getOverride(f.formattedSection)}return f.feature&&f.featureState?this.defaultValue.evaluate(f.feature,f.featureState):this.defaultValue.property.specification.default}eachChild(f){this.defaultValue.isConstant()||f(this.defaultValue.value._styleExpression.expression)}outputDefined(){return!1}serialize(){return null}}Vr(Sst,"FormatSectionOverride",{omit:["defaultValue"]});const I6e=()=>P6e||(P6e={layout:wst||(wst=new $d({"symbol-placement":new Bn(Us.layout_symbol["symbol-placement"]),"symbol-spacing":new Bn(Us.layout_symbol["symbol-spacing"]),"symbol-avoid-edges":new Bn(Us.layout_symbol["symbol-avoid-edges"]),"symbol-sort-key":new hr(Us.layout_symbol["symbol-sort-key"]),"symbol-z-order":new Bn(Us.layout_symbol["symbol-z-order"]),"symbol-z-elevate":new Bn(Us.layout_symbol["symbol-z-elevate"]),"symbol-elevation-reference":new Bn(Us.layout_symbol["symbol-elevation-reference"]),"icon-allow-overlap":new Bn(Us.layout_symbol["icon-allow-overlap"]),"icon-ignore-placement":new Bn(Us.layout_symbol["icon-ignore-placement"]),"icon-optional":new Bn(Us.layout_symbol["icon-optional"]),"icon-rotation-alignment":new Bn(Us.layout_symbol["icon-rotation-alignment"]),"icon-size":new hr(Us.layout_symbol["icon-size"]),"icon-size-scale-range":new Bn(Us.layout_symbol["icon-size-scale-range"]),"icon-text-fit":new hr(Us.layout_symbol["icon-text-fit"]),"icon-text-fit-padding":new hr(Us.layout_symbol["icon-text-fit-padding"]),"icon-image":new hr(Us.layout_symbol["icon-image"]),"icon-image-use-theme":new Bn({type:"string",default:"default","property-type":"data-constant"}),"icon-rotate":new hr(Us.layout_symbol["icon-rotate"]),"icon-padding":new Bn(Us.layout_symbol["icon-padding"]),"icon-keep-upright":new Bn(Us.layout_symbol["icon-keep-upright"]),"icon-offset":new hr(Us.layout_symbol["icon-offset"]),"icon-anchor":new hr(Us.layout_symbol["icon-anchor"]),"icon-pitch-alignment":new Bn(Us.layout_symbol["icon-pitch-alignment"]),"text-pitch-alignment":new Bn(Us.layout_symbol["text-pitch-alignment"]),"text-rotation-alignment":new Bn(Us.layout_symbol["text-rotation-alignment"]),"text-field":new hr(Us.layout_symbol["text-field"]),"text-font":new hr(Us.layout_symbol["text-font"]),"text-size":new hr(Us.layout_symbol["text-size"]),"text-size-scale-range":new Bn(Us.layout_symbol["text-size-scale-range"]),"text-max-width":new hr(Us.layout_symbol["text-max-width"]),"text-line-height":new hr(Us.layout_symbol["text-line-height"]),"text-letter-spacing":new hr(Us.layout_symbol["text-letter-spacing"]),"text-justify":new hr(Us.layout_symbol["text-justify"]),"text-radial-offset":new hr(Us.layout_symbol["text-radial-offset"]),"text-variable-anchor":new Bn(Us.layout_symbol["text-variable-anchor"]),"text-anchor":new hr(Us.layout_symbol["text-anchor"]),"text-max-angle":new Bn(Us.layout_symbol["text-max-angle"]),"text-writing-mode":new Bn(Us.layout_symbol["text-writing-mode"]),"text-rotate":new hr(Us.layout_symbol["text-rotate"]),"text-padding":new Bn(Us.layout_symbol["text-padding"]),"text-keep-upright":new Bn(Us.layout_symbol["text-keep-upright"]),"text-transform":new hr(Us.layout_symbol["text-transform"]),"text-offset":new hr(Us.layout_symbol["text-offset"]),"text-allow-overlap":new Bn(Us.layout_symbol["text-allow-overlap"]),"text-ignore-placement":new Bn(Us.layout_symbol["text-ignore-placement"]),"text-optional":new Bn(Us.layout_symbol["text-optional"]),visibility:new Bn(Us.layout_symbol.visibility)})),paint:jst||(jst=new $d({"icon-opacity":new hr(Us.paint_symbol["icon-opacity"]),"icon-occlusion-opacity":new hr(Us.paint_symbol["icon-occlusion-opacity"]),"icon-emissive-strength":new hr(Us.paint_symbol["icon-emissive-strength"]),"text-emissive-strength":new hr(Us.paint_symbol["text-emissive-strength"]),"icon-color":new hr(Us.paint_symbol["icon-color"]),"icon-halo-color":new hr(Us.paint_symbol["icon-halo-color"]),"icon-halo-width":new hr(Us.paint_symbol["icon-halo-width"]),"icon-halo-blur":new hr(Us.paint_symbol["icon-halo-blur"]),"icon-translate":new Bn(Us.paint_symbol["icon-translate"]),"icon-translate-anchor":new Bn(Us.paint_symbol["icon-translate-anchor"]),"icon-image-cross-fade":new Bn(Us.paint_symbol["icon-image-cross-fade"]),"text-opacity":new hr(Us.paint_symbol["text-opacity"]),"text-occlusion-opacity":new hr(Us.paint_symbol["text-occlusion-opacity"]),"text-color":new hr(Us.paint_symbol["text-color"],{runtimeType:kh,getOverride:w=>w.textColor,hasOverride:w=>!!w.textColor}),"text-halo-color":new hr(Us.paint_symbol["text-halo-color"]),"text-halo-width":new hr(Us.paint_symbol["text-halo-width"]),"text-halo-blur":new hr(Us.paint_symbol["text-halo-blur"]),"text-translate":new Bn(Us.paint_symbol["text-translate"]),"text-translate-anchor":new Bn(Us.paint_symbol["text-translate-anchor"]),"icon-color-saturation":new Bn(Us.paint_symbol["icon-color-saturation"]),"icon-color-contrast":new Bn(Us.paint_symbol["icon-color-contrast"]),"icon-color-brightness-min":new Bn(Us.paint_symbol["icon-color-brightness-min"]),"icon-color-brightness-max":new Bn(Us.paint_symbol["icon-color-brightness-max"]),"symbol-z-offset":new hr(Us.paint_symbol["symbol-z-offset"]),"icon-color-use-theme":new hr({type:"string",default:"default","property-type":"data-driven"}),"icon-halo-color-use-theme":new hr({type:"string",default:"default","property-type":"data-driven"}),"text-color-use-theme":new hr({type:"string",default:"default","property-type":"data-driven"}),"text-halo-color-use-theme":new hr({type:"string",default:"default","property-type":"data-driven"})}))},P6e);class Kse extends zy{constructor(f,b,S,T){super(f,I6e(),b,S,T,f.layout?f.layout["icon-image-use-theme"]:null),this._colorAdjustmentMatrix=j([]),this.hasOcclusionOpacityProperties=f.paint!==void 0&&("icon-occlusion-opacity"in f.paint||"text-occlusion-opacity"in f.paint)}_handleSpecialPaintPropertyUpdate(f){f!=="icon-occlusion-opacity"&&f!=="text-occlusion-opacity"||(this.hasOcclusionOpacityProperties=!0)}recalculate(f,b){super.recalculate(f,b),this.appearances&&this.appearances.forEach(T=>{T.recalculate(f,b,this.iconImageUseTheme)}),this.appearances.length!==0&&delete this.layout._values["text-variable-anchor"],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 S=this.layout.get("text-writing-mode");if(S){const T=[];for(const D of S)T.includes(D)||T.push(D);this.layout._values["text-writing-mode"]=T}else this.layout._values["text-writing-mode"]=this.layout.get("symbol-placement")==="point"?["horizontal"]:["horizontal","vertical"];this._setPaintOverrides()}getColorAdjustmentMatrix(f,b,S,T){return this._saturation===f&&this._contrast===b&&this._brightnessMin===S&&this._brightnessMax===T||(this._colorAdjustmentMatrix=function(D,F,q,K){D=Ef(D),F=Gp(F);const X=y(),ce=D/3,pe=1-2*ce,xe=[pe,ce,ce,0,ce,pe,ce,0,ce,ce,pe,0,0,0,0,1],Ne=.5-.5*F,Me=K-q;return M(X,[Me,0,0,0,0,Me,0,0,0,0,Me,0,q,q,q,1],[F,0,0,0,0,F,0,0,0,0,F,0,Ne,Ne,Ne,1]),M(X,X,xe),X}(f,b,S,T),this._saturation=f,this._contrast=b,this._brightnessMin=S,this._brightnessMax=T),this._colorAdjustmentMatrix}getValueAndResolveTokens(f,b,S,T){const D=this.layout.get(f).evaluate(b,{},S,T),F=this._unevaluatedLayout._values[f];return F.isDataDriven()||Xx(F.value)||!D?D:kst(b.properties,D)}getAppearanceValueAndResolveTokens(f,b,S,T,D){const F=f.getLayoutProperty(b);if(!F)return;const q=F.evaluate(S,{},T,D),K=f.getUnevaluatedLayoutProperties()._values[b];return K.isDataDriven()||Xx(K.value)||!q||typeof q!="string"?q:kst(S.properties,q)}createBucket(f){return new yse(f)}queryRadius(){return 0}queryIntersectsFeature(){return!1}_setPaintOverrides(){for(const f of I6e().paint.overridableProperties){if(!Kse.hasPaintOverride(this.layout,f))continue;const b=this.paint.get(f),S=new Sst(b),T=new Hk(S,b.property.specification,this.scope,this.options,this.layout.get("icon-image-use-theme"));let D=null;D=b.value.kind==="constant"||b.value.kind==="source"?new D1("source",T):new xp("composite",T,b.value.zoomStops,b.value.interpolationType),this.paint._values[f]=new wc(b.property,D,b.parameters)}}_handleOverridablePaintPropertyUpdate(f,b,S){return!(!this.layout||b.isDataDriven()||S.isDataDriven())&&Kse.hasPaintOverride(this.layout,f)}static hasPaintOverride(f,b){const S=f.get("text-field"),T=I6e().paint.properties[b];let D=!1;const F=q=>{for(const K of q)if(T.overrides&&T.overrides.hasOverride(K))return void(D=!0)};if(S.value.kind==="constant"&&S.value.value instanceof Yu)F(S.value.value.sections);else if(S.value.kind==="source"){const q=X=>{D||(X instanceof If&&rd(X.value)===mx?F(X.value.sections):X instanceof Lf?F(X.sections):X.eachChild(q))},K=S.value;K._styleExpression&&q(K._styleExpression.expression)}return D}getProgramIds(){return["symbol"]}getDefaultProgramParams(f,b,S){return{config:new q6(this,{zoom:b,lut:S}),overrideFog:!1}}hasElevation(){return this.layout&&this.layout.get("symbol-elevation-reference")==="hd-road-markup"}mayUse(f){return f==="HD"&&i7(this,"symbol-elevation-reference",b=>b==="hd-road-markup")}prepare(){return this.mayUse("HD")?Gse():Promise.resolve()}}let Cst,Ast,Est,Tst;const L6e=1024,IXt=(Math.pow(L6e,2)-1)/268170240;class Mst extends zy{constructor(f,b,S,T){super(f,{layout:Est||(Est=new $d({visibility:new Bn(Us.layout_raster.visibility)})),paint:Tst||(Tst=new $d({"raster-opacity":new Bn(Us.paint_raster["raster-opacity"]),"raster-color":new Aj(Us.paint_raster["raster-color"]),"raster-color-mix":new Bn(Us.paint_raster["raster-color-mix"]),"raster-color-range":new Bn(Us.paint_raster["raster-color-range"]),"raster-color-scale":new Bn(Us.paint_raster["raster-color-scale"]),"raster-hue-rotate":new Bn(Us.paint_raster["raster-hue-rotate"]),"raster-brightness-min":new Bn(Us.paint_raster["raster-brightness-min"]),"raster-brightness-max":new Bn(Us.paint_raster["raster-brightness-max"]),"raster-saturation":new Bn(Us.paint_raster["raster-saturation"]),"raster-contrast":new Bn(Us.paint_raster["raster-contrast"]),"raster-resampling":new Bn(Us.paint_raster["raster-resampling"]),"raster-fade-duration":new Bn(Us.paint_raster["raster-fade-duration"]),"raster-emissive-strength":new Bn(Us.paint_raster["raster-emissive-strength"]),"raster-array-band":new Bn(Us.paint_raster["raster-array-band"]),"raster-elevation":new Bn(Us.paint_raster["raster-elevation"]),"raster-elevation-reference":new Bn(Us.paint_raster["raster-elevation-reference"]),"raster-allow-draping":new Bn(Us.paint_raster["raster-allow-draping"]),"raster-color-use-theme":new hr({type:"string",default:"default","property-type":"data-driven"})}))},b,S,T),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(f){const b=f?f._source:null;return(!b||b.type!=="image"&&b.type!=="video"&&b.type!=="canvas"||!b.onNorthPole&&!b.onSouthPole)&&this.paint.get("raster-elevation")===0&&this.paint.get("raster-allow-draping")}_handleSpecialPaintPropertyUpdate(f){f!=="raster-color"&&f!=="raster-color-range"&&f!=="raster-color-scale"||(this._curRampRange=[NaN,NaN],this.updateColorRamp())}_clear(){this.colorRampTexture&&(this.colorRampTexture.destroy(),this.colorRampTexture=null)}updateColorRamp(f){if(!this.hasColorMap()||!this._curRampRange)return;const b=this._transitionablePaint._values["raster-color"].value.expression,[S,T]=f||this._transitionablePaint._values["raster-color-range"].value.expression.evaluate({zoom:0})||[NaN,NaN];if(isNaN(S)&&isNaN(T)||S===this._curRampRange[0]&&T===this._curRampRange[1])return;const D=this._transitionablePaint._values["raster-color-scale"].value.expression.evaluate({zoom:0});this.colorRamp=MH({expression:b,evaluationKey:"rasterValue",image:this.colorRamp,clips:[{start:S,end:T}],resolution:L6e,scale:D}),this.colorRampTexture=null,this._curRampRange=[S,T]}is3D(f){return this.paint.get("raster-elevation")>0||!this.paint.get("raster-allow-draping")}}let Pst,Ist,Lst,Rst,Dst,Ost,Fst;class zst extends zy{constructor(f,b,S,T){super(f,{layout:Pst||(Pst=new $d({visibility:new Bn(Us["layout_raster-particle"].visibility)})),paint:Ist||(Ist=new $d({"raster-particle-array-band":new Bn(Us["paint_raster-particle"]["raster-particle-array-band"]),"raster-particle-count":new Bn(Us["paint_raster-particle"]["raster-particle-count"]),"raster-particle-color":new Aj(Us["paint_raster-particle"]["raster-particle-color"]),"raster-particle-max-speed":new Bn(Us["paint_raster-particle"]["raster-particle-max-speed"]),"raster-particle-speed-factor":new Bn(Us["paint_raster-particle"]["raster-particle-speed-factor"]),"raster-particle-fade-opacity-factor":new Bn(Us["paint_raster-particle"]["raster-particle-fade-opacity-factor"]),"raster-particle-reset-rate-factor":new Bn(Us["paint_raster-particle"]["raster-particle-reset-rate-factor"]),"raster-particle-elevation":new Bn(Us["paint_raster-particle"]["raster-particle-elevation"]),"raster-particle-color-use-theme":new hr({type:"string",default:"default","property-type":"data-driven"})}))},b,S,T),this._updateColorRamp(),this.lastInvalidatedAt=qt.now()}mayUse(f){return f==="HD"}_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(f){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(f){return!1}_handleSpecialPaintPropertyUpdate(f){f!=="raster-particle-color"&&f!=="raster-particle-max-speed"||(this._updateColorRamp(),this._invalidateAnimationState()),f==="raster-particle-count"&&this._invalidateAnimationState()}_updateColorRamp(){if(!this.hasColorMap())return;const f=this._transitionablePaint._values["raster-particle-color"].value.expression,b=this._transitionablePaint._values["raster-particle-max-speed"].value.expression.evaluate({zoom:0});this.colorRamp=MH({expression:f,evaluationKey:"rasterParticleSpeed",image:this.colorRamp,clips:[{start:0,end:b}],resolution:256}),this.colorRampTexture=null}_invalidateAnimationState(){this.lastInvalidatedAt=qt.now()}tileCoverLift(){return this.paint.get("raster-particle-elevation")}}class LXt extends zy{constructor(f,b){super(f,{},b,null),this.implementation=f,f.slot&&(this.slot=f.slot)}is3D(f){return this.implementation.renderingMode==="3d"}hasOffscreenPass(){return this.implementation.prerender!==void 0}isDraped(f){return this.implementation.renderToTile!==void 0}shouldRedrape(){return!!this.implementation.shouldRerenderTiles&&this.implementation.shouldRerenderTiles()}recalculate(){}updateTransitions(){}hasTransition(){return!1}serialize(){}onAdd(f){this.implementation.onAdd&&this.implementation.onAdd(f,f.painter.context.gl)}onRemove(f){this.implementation.onRemove&&this.implementation.onRemove(f,f.painter.context.gl)}}function R6e(w,f,b){const S=[0,0,1],T=gt([]);return us(T,T,b?-_a(w)+Math.PI:_a(w)),Ns(T,T,-_a(f)),nt(S,S,T),Fe(S,S)}class Bst{constructor(f,b){this.feature=f,this.instancedDataOffset=b,this.instancedDataCount=0,this.rotation=[0,0,0],this.scale=[1,1,1],this.translation=[0,0,0]}}class $st{constructor(){this.maxScale=1,this.maxXYTranslationDistance=0,this.instancedDataArray=new zl,this.instancesEvaluatedElevation=[],this.features=[],this.idToFeaturesIndex={}}colorForInstance(f){const b=16*f,S=this.instancedDataArray.float32;let T=Math.floor(S[b+2]);const D=1.05*(S[b+2]-T);return T/=100,[S[b]%1*1.05,S[b+1]%1*1.05,D,T]}tileCoordinatesForInstance(f){const b=16*f,S=this.instancedDataArray.float32;let T=S[b+0];return T=T>br?T-br:T,new Kt(Math.trunc(T),Math.trunc(S[b+1]))}translationForInstance(f){const b=16*f,S=this.instancedDataArray.float32;return[S[b+4],S[b+5],S[b+6]]}rotationScaleForInstance(f){const b=16*f,S=this.instancedDataArray.float32;return[S[b+7],S[b+8],S[b+9],S[b+10],S[b+11],S[b+12],S[b+13],S[b+14],S[b+15]]}transformForInstance(f){const b=16*f,S=this.instancedDataArray.float32;return[S[b+7],S[b+8],S[b+9],S[b+4],S[b+10],S[b+11],S[b+12],S[b+5],S[b+13],S[b+14],S[b+15],S[b+6],0,0,0,1]}}class D6e{constructor(f){this.requiresStandardRuntime=!0,this.zoom=f.zoom,this.canonical=f.canonical,this.overscaledZ=this.canonical.z+Math.log2(f.overscaling),this.layers=f.layers,this.layerIds=this.layers.map(b=>b.fqid),this.projection=f.projection,this.index=f.index,this.worldview=f.worldview,this.hasZoomDependentProperties=this.layers[0].isZoomDependent(),this.stateDependentLayerIds=this.layers.filter(b=>b.isStateDependent()).map(b=>b.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=f.styleDefinedModelURLs,this.hasAppearances=null}updateFootprints(f,b){}updateAppearances(f,b,S,T){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(f,b,S,T){this.tileToMeter=mt(S);const D=this.layers[0]._featureFilter.needGeometry;this.lookup=new Uint8Array(this.lookupDim*this.lookupDim);const F=this.layers[0].paint.get("model-elevation-reference")==="hd-road-markup"?b.elevationFeatures:void 0;for(const{feature:q,id:K,index:X,sourceLayerIndex:ce}of f){const pe=K??(q.properties&&Object.hasOwn(q.properties,"id")?q.properties.id:void 0),xe=Js(q,D);if(!this.layers[0]._featureFilter.filter(new tr(this.zoom,{worldview:this.worldview,activeFloors:b.activeFloors}),xe,S))continue;const Ne={id:pe,sourceLayerIndex:ce,index:X,geometry:D?xe.geometry:Ms(q,S,T),properties:q.properties,type:q.type,patterns:{}},Me=this.addFeature(Ne,Ne.geometry,xe,F,S);Me&&b.featureIndex.insert(q,Ne.geometry,X,ce,this.index,this.instancesPerModel[Me].instancedDataArray.length,256)}this.lookup=null}evaluateQueryRenderedFeaturePadding(){const f=this.layers[0].modelManager,b=this.layers[0].scope;let S=0;for(const T of this.modelUris){const D=f.getModel(T,b);if(!D)continue;const F=this.instancesPerModel[T];if(F){const q=.5*Ye(D.aabb.max,D.aabb.min)*F.maxScale+F.maxXYTranslationDistance,K=Math.min(br,Math.max(q/this.tileToMeter,256));S=Math.max(K,S)}}return S}update(f,b,S,T){for(const D in this.instancesPerModel){const F=this.instancesPerModel[D];for(const q in f)Object.hasOwn(F.idToFeaturesIndex,q)&&(this.evaluate(F.features[F.idToFeaturesIndex[q]],f[q],F,!0),this.uploaded=!1)}this.maxHeight=0}updateZoomBasedPaintProperties(){if(!this.hasZoomDependentProperties)return!1;let f=!1;for(const b in this.instancesPerModel){const S=this.instancesPerModel[b];for(const T of S.features){const D=this.layers[0],F=T.feature,q=this.canonical,K=D.paint.get("model-rotation").evaluate(F,{},q),X=D.paint.get("model-scale").evaluate(F,{},q),ce=D.paint.get("model-translation").evaluate(F,{},q);at(T.rotation,K)&&at(T.scale,X)&&at(T.translation,ce)||(this.evaluate(T,T.featureStates,S,!0),f=!0)}}return f}updateReplacement(f,b,S,T){if(b.updateTime===this.replacementUpdateTime)return!1;this.replacementUpdateTime=b.updateTime;const D=b.getReplacementRegionsForTile(f.toUnwrapped(),!0);if(lse(this.activeReplacements,D))return!1;this.activeReplacements=D;let F=!1;for(const q in this.instancesPerModel){const K=this.instancesPerModel[q],X=K.instancedDataArray;for(const ce of K.features){const pe=ce.instancedDataOffset,xe=ce.instancedDataCount;for(let Ne=0;Nebr;ze=Ve?ze-br:ze;const Je=Math.floor(ze),lt=Math.floor(X.float32[Me+1]);let ht=!1;for(const ct of this.activeReplacements)if(!get(ct,S,Dse.Model,T)&&!(ct.min.x>Je||Je>ct.max.x||ct.min.y>lt||lt>ct.max.y)&&(ht=GMe(bet(Je,lt,f.canonical,ct.footprintTileId.canonical),ct.footprint),ht))break;X.float32[Me]=ht?ze+br:ze,F=F||ht!==Ve}}}return F}isEmpty(){for(const f in this.instancesPerModel)if(this.instancesPerModel[f].instancedDataArray.length!==0)return!1;return!0}uploadPending(){return!this.uploaded}upload(f){if(!this.uploaded)for(const b in this.instancesPerModel){const S=this.instancesPerModel[b];S.instancedDataArray.length<0||S.instancedDataArray.length===0||(S.instancedDataBuffer?S.instancedDataBuffer.updateData(S.instancedDataArray):S.instancedDataBuffer=f.createVertexBuffer(S.instancedDataArray,zZt.members,!0,void 0,this.instanceCount))}this.uploaded=!0}destroy(f){for(const S in this.instancesPerModel){const T=this.instancesPerModel[S];T.instancedDataArray.length!==0&&T.instancedDataBuffer&&T.instancedDataBuffer.destroy()}const b=this.layers[0].modelManager;if(f&&b&&this.modelUris&&this.modelsRequested)for(const S of this.modelUris)b.removeModel(S,"",!0)}addFeature(f,b,S,T,D){const F=this.layers[0],q=F.layout.get("model-id"),K=F.layout.get("model-allow-density-reduction"),X=q.evaluate(S,{},this.canonical);if(!X)return oi(`modelId is not evaluated for layer ${F.id} and it is not going to get rendered.`),X;!X.includes("://")&&!this.styleDefinedModelURLs[X]||this.modelUris.includes(X)||this.modelUris.push(X),this.instancesPerModel[X]||(this.instancesPerModel[X]=new $st);const ce=this.instancesPerModel[X],pe=ce.instancedDataArray,xe=new Bst(S,pe.length);let Ne;if(T){const Me=wH(f,T,void 0,D);Ne=Me?Me.feature:void 0}for(const Me of b)for(const ze of Me){if(ze.x<0||ze.x>=br||ze.y<0||ze.y>=br)continue;if(this.lookupDim!==0&&K){const Je=(this.lookupDim-1)/br,lt=this.lookupDim*(ze.y*Je|0)+ze.x*Je|0;if(this.lookup){if(this.lookup[lt]!==0)continue;this.lookup[lt]=1}}this.instanceCount++;const Ve=pe.length;if(pe.resize(Ve+1),T){ce.instancesRoadElevation||(ce.instancesRoadElevation=[]);const Je=Ne?Ne.pointElevation(new Kt(ze.x,ze.y)):0;ce.instancesRoadElevation.push(Je)}ce.instancesEvaluatedElevation.push(0),pe.float32[16*Ve]=ze.x,pe.float32[16*Ve+1]=ze.y}return xe.instancedDataCount=ce.instancedDataArray.length-xe.instancedDataOffset,xe.instancedDataCount>0&&(f.id&&(ce.idToFeaturesIndex[f.id]=ce.features.length),ce.features.push(xe),this.evaluate(xe,{},ce,!1)),X}getModelUris(){return this.modelUris}evaluate(f,b,S,T){const D=this.layers[0],F=f.feature,q=this.canonical,K=f.rotation=D.paint.get("model-rotation").evaluate(F,b,q),X=f.scale=D.paint.get("model-scale").evaluate(F,b,q),ce=f.translation=D.paint.get("model-translation").evaluate(F,b,q),{r:pe,g:xe,b:Ne}=D.paint.get("model-color").evaluate(F,b,q),Me=D.paint.get("model-color-mix-intensity").evaluate(F,b,q),ze=[];this.maxVerticalOffset0?Math.sqrt(Ve):0;S.maxScale=Math.max(Math.max(S.maxScale,X[0]),Math.max(X[1],X[2])),S.maxXYTranslationDistance=Math.max(S.maxXYTranslationDistance,Je),this.maxScale=Math.max(Math.max(this.maxScale,X[0]),Math.max(X[1],X[2])),btt(ze,K,X);const lt=Math.round(100*Me)+Ne/1.05;for(let ht=0;ht10?this.tileToMeter:mt(q,Ct)),kt[xt+4]=ce[0],kt[xt+5]=ce[1],kt[xt+6]=ce[2]+(S.instancesRoadElevation?S.instancesRoadElevation[ct]:0)+es,kt[xt+7]=ze[0],kt[xt+8]=ze[1],kt[xt+9]=ze[2],kt[xt+10]=ze[4],kt[xt+11]=ze[5],kt[xt+12]=ze[6],kt[xt+13]=ze[8],kt[xt+14]=ze[9],kt[xt+15]=ze[10],S.instancesEvaluatedElevation[ct]=ce[2]}}}Vr(D6e,"ModelBucket",{omit:["layers"]}),Vr($st,"PerModelAttributes"),Vr(Bst,"ModelFeature");class S7{constructor(f,b,S){this._demTile=f,this._dem=this._demTile.dem,this._scale=b,this._offset=S}static create(f,b,S){const T=S||f.findDEMTileFor(b);if(!T||!T.dem)return;const D=T.dem,F=T.tileID,q=1<X.fqid),this.stateDependentLayerIds=this.layers.filter(X=>X.isStateDependent()).map(X=>X.id),this.modelTraits|=1,this.uploaded=!1,this.hasPattern=!1,T&&(this.modelTraits|=4),D&&(this.modelTraits|=8),this.zoom=-1,this.terrainExaggeration=1,this.projection={name:"mercator"},this.replacementUpdateTime=0,this.elevationReadFromZ=255,this.brightness=F,this.worldview=K,this.dirty=!0,this.needsUpload=!1,this.filter=null,this.nodesInfo=[];for(const X of b)this.nodesInfo.push(new Vst(X)),qst(X,q.featureIndexArray.length,q.grid),q.featureIndexArray.emplaceBack(this.nodesInfo.length-1,0,q.bucketLayerIDs.length-1,0);this.states={},this.hasAppearances=null}updateFootprints(f,b){for(const S of this.getNodesInfo()){const T=S.node;T.footprint&&b.push({footprint:T.footprint,id:f})}}updateAppearances(f,b,S,T){return{hasLayoutChanges:!1,hasUboChanges:!1}}update(f){const b=Object.keys(f).length!==0;if(b&&!this.stateDependentLayers.length)return;const S=b?this.stateDependentLayers:this.layers;if(!Er(f,this.states))for(const T of S)this.evaluate(T,f);this.states=structuredClone(f)}populate(){console.log("populate 3D model bucket")}uploadPending(){return!this.uploaded||this.needsUpload}upload(f){if(!this.needsUpload)return;const b=this.getNodesInfo();for(const S of b){const T=S.node;this.uploaded?this.updatePbrBuffer(T):g6e(T,f,!0)}for(const S of b)Lse(S.node);this.uploaded=!0,this.needsUpload=!1}updatePbrBuffer(f){let b=!1;if(!f.meshes)return b;for(const S of f.meshes)S.pbrBuffer&&(S.pbrBuffer.updateData(S.featureArray),b=!0);if(f.lodMeshes)for(const S of f.lodMeshes)S.pbrBuffer&&(S.pbrBuffer.updateData(S.featureArray),b=!0);return b}needsReEvaluation(f,b,S){const T=f.transform.projectionOptions,D=f.style.getBrightness(),F=this.brightness!==D;if(!this.uploaded||this.dirty||T.name!==this.projection.name||RH(S.paint.get("model-color").value,F)||RH(S.paint.get("model-color-mix-intensity").value,F)||RH(S.paint.get("model-roughness").value,F)||RH(S.paint.get("model-emissive-strength").value,F)||RH(S.paint.get("model-height-based-emissive-strength-multiplier").value,F)){this.projection=T,this.brightness=D;const q=this.getNodesInfo();for(const K of q)K.state=null;return!0}return!1}evaluateTransform(f,b){if(f.transform.zoom===this.zoom)return;this.zoom=f.transform.zoom;const S=this.getNodesInfo(),T=this.id.canonical;for(const D of S){const F=D.feature;D.evaluatedTranslation=b.paint.get("model-translation").evaluate(F,{},T),D.evaluatedScale=b.paint.get("model-scale").evaluate(F,{},T)}}evaluate(f,b){const S=this.getNodesInfo();for(const T of S){if(!T.node.meshes)continue;const D=T.feature,F=b&&b[D.id];if(Er(F,T.state))continue;T.state=structuredClone(F);const q=T.node.meshes&&T.node.meshes[0].featureData,K=T.evaluatedColor[2],X=T.evaluatedRMEA[2],ce=this.id.canonical;if(T.hasTranslucentParts=!1,q){for(let pe=0;pe=kt)continue;const Rn=O6e[hn],ws=Math.abs(Rn);ws>Qt&&(Zt=Rn,Qt=ws,Cs=sn,Fs=on)}if(Qt>.1){const on=1-(kt+.5*Math.abs(Cs*Fs))/Me;let sn=b._dem.get(Ct,es)+Zt*on;const hn=b._dem.get(Ct+Cs,es+Fs),Rn=b._dem.get(Ct-Cs,es-Fs,!0);(sn-hn)*(sn-Rn)>0&&(sn=(hn+Rn)/2),O6e[Lt]=b._dem.set(Ct,es,sn),Q6[Lt]=kt}}}}}q&&(b._demTile.needsDEMTextureUpload=!0,b._dem._timestamp=qt.now())}setFilter(f){this.filter=f?L6(f):null}getNodesInfo(){return this.filter?this.nodesInfo.filter(f=>this.filter.filter(new tr(this.id.overscaledZ,{worldview:this.worldview}),f.feature,this.id.canonical)):this.nodesInfo}destroy(){const f=this.getNodesInfo();for(const b of f)Lse(b.node),x6e(b.node)}isEmpty(){return!this.nodesInfo.length}updateReplacement(f,b){if(b.updateTime===this.replacementUpdateTime)return;this.replacementUpdateTime=b.updateTime;const S=b.getReplacementRegionsForTile(f.toUnwrapped());for(const T of this.getNodesInfo()){const D=T.node.footprint;T.hiddenByReplacement=!!D&&!S.some(F=>F.footprint===D)}}getHeightAtTileCoord(f,b){const S=[0,0,0],T=j([]);for(const D of this.getNodesInfo()){const F=D.node.meshes[0],q=F.transformedAabb;if(fq.max[0]||b>q.max[1])continue;if(D.node.hidden===!0)return{height:1/0,maxHeight:D.feature.properties.height,hidden:!1,verticalScale:D.evaluatedScale[2]};if(A(T,D.node.globalMatrix),S[0]=f,S[1]=b,S[2]=0,tt(S,S,T),D.node.meshBVH){const pe=S[0],xe=S[1];Yse[0]=pe-1,Yse[1]=xe-1,Yse[2]=-1e3,Zse[0]=pe+1,Zse[1]=xe+1,Zse[2]=1e3;const Ne=D.node.meshBVH.findHighestPoint(Yse,Zse);if(Ne!==null)return{height:Ne,maxHeight:D.feature.properties.height,hidden:D.hiddenByReplacement,verticalScale:D.evaluatedScale[2]};continue}const K=(S[0]-F.aabb.min[0])/(F.aabb.max[0]-F.aabb.min[0])*Z6|0,X=Math.min(63,(S[1]-F.aabb.min[1])/(F.aabb.max[1]-F.aabb.min[1])*Z6|0)*Z6+Math.min(63,K),ce=F.heightmap[X];if(ce<0&&D.node.footprint){const pe=[];if(D.node.footprint.grid.query(new Kt(f,b),new Kt(f,b),pe),pe.length>0)return{height:void 0,maxHeight:D.feature.properties.height,hidden:D.hiddenByReplacement,verticalScale:D.evaluatedScale[2]};continue}return D.hiddenByReplacement?void 0:{height:ce,maxHeight:D.feature.properties.height,hidden:!1,verticalScale:D.evaluatedScale[2]}}}}function RH(w,f){return w instanceof D1&&!w.isLightConstant&&f}function RXt(w){const f=Jr(w,0,2);return Math.min(Math.round(.5*f*255),255)}const Gst=new Float64Array(10*Xse.length);function Wst(w,f,b,S,T,D){if(!w.featureData)return;const F=w.featureArray=new Ud;F.reserveExact(w.featureData.length),function(ce,pe,xe){const Ne=xe-pe;for(let Me=0;Me>b&65535,xe=ce>>S&15,Ne=xe<8?xe:0,Me=10*Ne;let ze=(61440&pe|(61440&pe)>>4)>>8,Ve=(3840&pe|(3840&pe)>>4)>>4,Je=240&pe|(240&pe)>>4;const lt=(15&pe|(15&pe)<<4)/255,ht=q[Me+3];ht>0&&(ze=da(ze,q[Me],ht),Ve=da(Ve,q[Me+1],ht),Je=da(Je,q[Me+2],ht)),D&&(ze*=lt,Ve*=lt,Je*=lt);const ct=ze<<8|Ve,xt=Je<<8|q[Me+4],kt=q[Me+5],es=q[Me+6],Ct=q[Me+7],Lt=q[Me+8],Zt=q[Me+9];if(F.emplaceBack(ct,xt,kt,es,Ct,Lt,Zt),X&&Ne===2){X=!1;const Qt=10*K.lights.length,Cs=new Ud;Cs.reserveExact(Qt);for(let Fs=0;Fs{let ht=Yst,ct=0,xt=Yst;if(!lt){const Lt=T.style.light,Zt=Lt.properties.get("position");if(ht=[-Zt.x,-Zt.y,Zt.z],Lt.properties.get("anchor")==="viewport"){const Cs=p();x(Cs,-T.transform.angle),ut(ht,ht,Cs)}const Qt=Lt.properties.get("color").toNonPremultipliedRenderColor(null);ct=Lt.properties.get("intensity"),xt=[Qt.r,Qt.g,Qt.b]}const kt=ce.alphaMode==="MASK",es=xe.paint.get("model-ambient-occlusion-intensity"),Ct=xe.paint.get("model-color").constantOr(Mi.white).toNonPremultipliedRenderColor(null);return Ct.a=xe.paint.get("model-color-mix-intensity").constantOr(0),Ve&&(Ct.r=Ve[0],Ct.g=Ve[1],Ct.b=Ve[2],Ct.a=Ve[3]),ze&&(Ct.r=ze.color.r,Ct.g=ze.color.g,Ct.b=ze.color.b,Ct.a=ze.colorMix,pe=ze.emissionStrength,D*=ze.opacity),{u_matrix:w,u_lighting_matrix:f,u_normal_matrix:b,u_node_matrix:S||F6e,u_lightpos:ht,u_lightintensity:ct,u_lightcolor:xt,u_camera_pos:Ne,u_opacity:D,u_baseTextureIsAlpha:0,u_alphaMask:+kt,u_alphaCutoff:ce.alphaCutoff,u_baseColorFactor:F.toNonPremultipliedRenderColor(null).toArray01(),u_emissiveFactor:q.toNonPremultipliedRenderColor(null).toArray01(),u_metallicFactor:K,u_roughnessFactor:X,u_baseColorTexture:O0.BaseColor,u_metallicRoughnessTexture:O0.MetallicRoughness,u_normalTexture:O0.Normal,u_occlusionTexture:O0.Occlusion,u_emissionTexture:O0.Emission,u_lutTexture:O0.LUT,u_color_mix:Ct.toArray01(),u_aoIntensity:es,u_emissive_strength:pe,u_occlusionTextureTransform:Me||[0,0,0,0],u_dithered_discard_threshold:Je}},Zst=(w,f=F6e,b=F6e)=>({u_matrix:w,u_instance:f,u_node_matrix:b}),B6e=7680;class rw{constructor(f,b,S,T,D,F){this.test=f,this.ref=b,this.mask=S,this.fail=T,this.depthFail=D,this.pass=F}}rw.disabled=new rw({func:519,mask:0},0,0,B6e,B6e,B6e);const Qse=770,C7=771;class bu{constructor(f,b,S,T){this.blendFunction=f,this.blendColor=b.toNonPremultipliedRenderColor(null),this.mask=S,this.blendEquation=T}}bu.Replace=[1,0,1,0],bu.disabled=new bu(bu.Replace,Mi.transparent,[!1,!1,!1,!1]),bu.unblended=new bu(bu.Replace,Mi.transparent,[!0,!0,!0,!0]),bu.alphaBlended=new bu([1,C7,1,C7],Mi.transparent,[!0,!0,!0,!0]),bu.alphaBlendedNonPremultiplied=new bu([Qse,C7,Qse,C7],Mi.transparent,[!0,!0,!0,!0]),bu.multiply=new bu([774,0,774,0],Mi.transparent,[!0,!0,!0,!0]),bu.multiplyAccumulateAlpha=new bu([774,0,1,C7],Mi.transparent,[!0,!0,!0,!0]),bu.additive=new bu([1,1,1,1],Mi.transparent,[!0,!0,!0,!0]),bu.additiveAlphaWeighted=new bu([Qse,1,773,1],Mi.transparent,[!0,!0,!0,!0]),bu.additiveAlphaWeightedUnboundedAlpha=new bu([Qse,1,1,1],Mi.transparent,[!0,!0,!0,!0]);class yx{constructor(f,b,S){this.func=f,this.mask=b,this.range=S}}yx.ReadOnly=!1,yx.ReadWrite=!0,yx.disabled=new yx(519,yx.ReadOnly,[0,1]);const $6e=1029,U6e=2305;class vx{constructor(f,b,S){this.enable=f,this.mode=b,this.frontFace=S}}vx.disabled=new vx(!1,$6e,U6e),vx.backCCW=new vx(!0,$6e,U6e),vx.backCW=new vx(!0,$6e,2304),vx.frontCW=new vx(!0,1028,2304),vx.frontCCW=new vx(!0,1028,U6e);class q6e{constructor(f=0,b=0,S=0,T=0){if(isNaN(f)||f<0||isNaN(b)||b<0||isNaN(S)||S<0||isNaN(T)||T<0)throw new Error("Invalid value for edge-insets, top, bottom, left and right must all be numbers");this.top=f,this.bottom=b,this.left=S,this.right=T}interpolate(f,b,S){return b.top!=null&&f.top!=null&&(this.top=da(f.top,b.top,S)),b.bottom!=null&&f.bottom!=null&&(this.bottom=da(f.bottom,b.bottom,S)),b.left!=null&&f.left!=null&&(this.left=da(f.left,b.left,S)),b.right!=null&&f.right!=null&&(this.right=da(f.right,b.right,S)),this}getCenter(f,b){return new Kt(Jr((this.left+f-this.right)/2,0,f),Jr((this.top+b-this.bottom)/2,0,b))}equals(f){return this.top===f.top&&this.bottom===f.bottom&&this.left===f.left&&this.right===f.right}clone(){return new q6e(this.top,this.bottom,this.left,this.right)}toJSON(){return{top:this.top,bottom:this.bottom,left:this.left,right:this.right}}}function Xst(w,f){const b=Sd(w,3);ee(w,f),$h(w,3,b)}function V6e(w,f){const b=gt([]);return Bs(b,b,-f),Ns(b,b,-w),b}function Qst(w,f){const b=[w[0],w[1],0],S=[f[0],f[1],0];if(fe(b)>=1e-15){const F=Fe([],b);Be(S,F,Oe(S,F)),f[0]=S[0],f[1]=S[1]}const T=Ge([],f,w);if(Ft(T)<1e-15)return null;const D=Math.atan2(-T[1],T[0]);return V6e(Math.atan2(Math.sqrt(w[0]*w[0]+w[1]*w[1]),-w[2]),D)}class Jst{constructor(f,b){this.position=f,this.orientation=b}get position(){return this._position}set position(f){if(f){const b=f instanceof vt?f:new vt(f[0],f[1],f[2]);this._renderWorldCopies&&(b.x=fc(b.x,0,1)),this._position=b}else this._position=null}lookAtPoint(f,b,S){if(this.orientation=null,!this.position)return;const T=this.position,D=S||(this._elevation?this._elevation.getAtPointOrZero(vt.fromLngLat(f)):0),F=vt.fromLngLat(f,D),q=[F.x-T.x,F.y-T.y,F.z-T.z];b||(b=[0,0,1]),b[2]=Math.abs(b[2]),this.orientation=Qst(q,b)}setPitchBearing(f,b){this.orientation=V6e(_a(f),_a(-b))}}class Jse{constructor(f,b){this._transform=j([]),this.orientation=b,this.position=f}get mercatorPosition(){const f=this.position;return new vt(f[0],f[1],f[2])}get position(){const f=Sd(this._transform,3);return[f[0],f[1],f[2]]}set position(f){var b;f&&$h(this._transform,3,[(b=f)[0],b[1],b[2],1])}get orientation(){return this._orientation}set orientation(f){this._orientation=f||gt([]),f&&Xst(this._transform,this._orientation)}getPitchBearing(){const f=this.forward(),b=this.right();return{bearing:Math.atan2(-b[1],b[0]),pitch:Math.atan2(Math.sqrt(f[0]*f[0]+f[1]*f[1]),-f[2])}}setPitchBearing(f,b){this._orientation=V6e(f,b),Xst(this._transform,this._orientation)}forward(){const f=Sd(this._transform,2);return[-f[0],-f[1],-f[2]]}up(){const f=Sd(this._transform,1);return[-f[0],-f[1],-f[2]]}right(){const f=Sd(this._transform,0);return[f[0],f[1],f[2]]}getCameraToWorld(f,b){const S=new Float64Array(16);return A(S,this.getWorldToCamera(f,b)),S}getCameraToWorldMercator(){return this._transform}getWorldToCameraPosition(f,b,S){const T=this.position;Be(T,T,-f);const D=new Float64Array(16);return G(D,[S,S,S]),I(D,D,T),D[10]*=b,D}getWorldToCamera(f,b){const S=new Float64Array(16),T=new Float64Array(4),D=this.position;var F,q;return(F=T)[0]=-(q=this._orientation)[0],F[1]=-q[1],F[2]=-q[2],F[3]=q[3],Be(D,D,-f),ee(S,T),I(S,S,D),S[1]*=-1,S[5]*=-1,S[9]*=-1,S[13]*=-1,S[8]*=b,S[9]*=b,S[10]*=b,S[11]*=b,S}getCameraToClipPerspective(f,b,S,T){const D=new Float64Array(16);return oe(D,f,b,S,T),D}getCameraToClipOrthographic(f,b,S,T,D,F){const q=new Float64Array(16);return me(q,f,b,S,T,D,F),q}getDistanceToElevation(f,b=!1){const S=f===0?0:de(f,b?hh(this.position[1]):this.position[1]),T=this.forward();return(S-this.position[2])/T[2]}clone(){return new Jse([...this.position],[...this.orientation])}}const FXt=Math.tan(85*Math.PI/180);function H6e(w,f,b,S,T,D,F){const q=y();if(b)if(D.name==="globe"){const K=function(X,ce){const{x:pe,y:xe}=X.point,Ne=aet(pe,xe,X.worldSize/X._pixelsPerMercatorPixel,0,0);return M(Ne,Ne,BMe(Qk(ce)))}(T,f);M(q,q,K)}else{const K=m([],F);q[0]=K[0],q[1]=K[1],q[4]=K[2],q[5]=K[3],S||B(q,q,T.angle)}else M(q,T.labelPlaneMatrix,w);return q}function TA(w,f,b,S){const T=[w,f,b,1];b?dt(T,T,S):ont(T,T,S);const D=T[3];return T[0]/=D,T[1]/=D,T[2]/=D,T}function ent(w,f){return Math.min(.5+w/f*.5,1.5)}function zXt(w,f){const b=w[0]/w[3],S=w[1]/w[3];return b>=-f[0]&&b<=f[0]&&S>=-f[1]&&S<=f[1]}function tnt(w,f,b,S,T,D,F,q,K,X,ce,pe,xe,Ne,Me,ze,Ve,Je){const{lineStartIndex:lt,glyphStartIndex:ht,segment:ct}=q,xt=ht+q.numGlyphs,kt=lt+q.lineLength,es=f.getoffsetX(ht),Ct=f.getoffsetX(xt-1),Lt=ene(w*es,b,S,T,D,F,ct,lt,kt,K,X,ce,pe,xe,!0,Ne,Me,ze,Ve,Je);if(!Lt)return null;const Zt=ene(w*Ct,b,S,T,D,F,ct,lt,kt,K,X,ce,pe,xe,!0,Ne,Me,ze,Ve,Je);return Zt?{first:Lt,last:Zt}:null}function snt(w,f,b,S){return w===R4.horizontal&&Math.abs(S)>Math.abs(b)?{useVertical:!0}:w===R4.vertical?S>0?{needsFlipping:!0}:null:f!==0&&function(T,D){return T===0||Math.abs(D/T)>FXt}(b,S)?f===1?{needsFlipping:!0}:null:b<0?{needsFlipping:!0}:null}function nnt(w,f,b,S,T,D,F,q,K,X,ce,pe,xe,Ne,Me,ze,Ve,Je,lt,ht,ct){const xt=f/24,kt=w.lineOffsetX*xt,es=w.lineOffsetY*xt,{lineStartIndex:Ct,glyphStartIndex:Lt,numGlyphs:Zt,segment:Qt,writingMode:Cs,flipState:Fs}=w,on=Ct+w.lineLength,sn=hn=>{if(ce){const[en,wn,Nn]=hn.up,Pn=X.length;xse(ce,Pn+0,en,wn,Nn),xse(ce,Pn+1,en,wn,Nn),xse(ce,Pn+2,en,wn,Nn),xse(ce,Pn+3,en,wn,Nn)}const[Rn,ws,qs]=hn.point;W6(X,Rn,ws,qs,hn.angle)};if(Zt>1){const hn=tnt(xt,q,kt,es,b,pe,xe,w,K,D,Ne,ze,!1,Ve,Je,lt,ht,ct);if(!hn)return{notEnoughRoom:!0};if(S&&!b){let[Rn,ws,qs]=hn.first.point,[en,wn,Nn]=hn.last.point;[Rn,ws]=TA(Rn,ws,qs,F),[en,wn]=TA(en,wn,Nn,F);const Pn=snt(Cs,Fs,(en-Rn)*Me,wn-ws);if(w.flipState=Pn&&Pn.needsFlipping?1:2,Pn)return Pn}sn(hn.first);for(let Rn=Lt+1;Rn0?en:int(xe,qs,Rn,1,T,void 0,Ve,Je.canonical),Nn=snt(Cs,Fs,(wn[0]-Rn[0])*Me,wn[1]-Rn[1]);if(w.flipState=Nn&&Nn.needsFlipping?1:2,Nn)return Nn}const hn=ene(xt*q.getoffsetX(Lt),kt,es,b,pe,xe,Qt,Ct,on,K,D,Ne,ze,!1,!1,Ve,Je,lt,ht,ct);if(!hn)return{notEnoughRoom:!0};sn(hn)}return{}}function rnt(w,f,b){const S=1<0?1:-1,kt=0;S&&(xt*=-1,kt=Math.PI),xt<0&&(kt+=Math.PI);let es=q+F+(xt>0?0:1)|0,Ct=T,Lt=T,Zt=0,Qt=0;const Cs=Math.abs(ct),Fs=[],on=[];let sn=D,hn=sn,Rn=et([]);const ws=()=>int(hn,sn,Lt,Cs-Zt+1,ce,xe,ze,Ve.canonical,ht);for(;Zt+Qt<=Cs;){if(es+=xt,es=K)return null;if(Lt=Ct,hn=sn,Fs.push(Lt),Ne&&on.push(hn),sn=new Kt(X.getx(es),X.gety(es)),Ct=pe[es],!Ct){const sr=ant(sn,Ve.canonical,ce,ze,xe,ht);Ct=sr[3]>0?pe[es]=sr:ws()}Zt+=Qt;const Kn=wt([],Ct,Lt),Dr=Ye(Lt,Ct);if(b&&Dr>0&&Qt>0&&Oe(Rn,Kn)/(Qt*Dr)0&&this.elevation.exaggeration()>0&&this._centerAltitudeValidForExaggeration;if(!this._elevation||f===Number.NEGATIVE_INFINITY&&(!b||!this._centerAltitude))return this._centerAltitude=0,this._seaLevelZoom=null,void(this._centerAltitudeValidForExaggeration=void 0);const S=this._elevation;b||this._centerAltitude&&this._centerAltitudeValidForExaggeration&&S.exaggeration()&&this._centerAltitudeValidForExaggeration!==S.exaggeration()?(this._centerAltitude=this._centerAltitude/this._centerAltitudeValidForExaggeration*S.exaggeration(),this._centerAltitudeValidForExaggeration=S.exaggeration()):(this._centerAltitude=f||0,this._centerAltitudeValidForExaggeration=S.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,b=[[.5,.2],[.3,.5],[.5,.5],[.7,.5],[.5,.8]],S=this.horizonLineFromTop();let T=0,D=0;for(let F=0;F{const Ve=kA(xe,pe,Ne,Me,ze);K.has(Ve)||(D.push(new _p(pe,xe,Ne,Me,ze)),K.add(Ve))};for(let pe=0;pexe.canonical.z)continue;const Ne=xe.canonical,Me=xe.overscaledZ,ze=xe.wrap,Ve=1<0,ht=Ne.y+10,xt=xe.wrap-(lt?0:1),kt=xe.wrap+(Je?0:1),es=lt?Ne.x-1:Ve-1,Ct=Je?Ne.x+1:0;if(F)S[0]<0?(X(Me,kt,Ne.z,Ct,Ne.y),S[1]<0&&ht&&(X(Me,ze,Ne.z,Ne.x,Ne.y+1),X(Me,kt,Ne.z,Ct,Ne.y+1)),S[1]>0&&ct&&(X(Me,ze,Ne.z,Ne.x,Ne.y-1),X(Me,kt,Ne.z,Ct,Ne.y-1))):S[0]>0?(X(Me,xt,Ne.z,es,Ne.y),S[1]<0&&ht&&(X(Me,ze,Ne.z,Ne.x,Ne.y+1),X(Me,xt,Ne.z,es,Ne.y+1)),S[1]>0&&ct&&(X(Me,ze,Ne.z,Ne.x,Ne.y-1),X(Me,xt,Ne.z,es,Ne.y-1))):S[1]<0&&ht?X(Me,ze,Ne.z,Ne.x,Ne.y+1):ct&&X(Me,ze,Ne.z,Ne.x,Ne.y-1);else{const Lt=xe.visibleQuadrants;1&Lt&&(X(Me,xt,Ne.z,es,Ne.y),ct&&(X(Me,ze,Ne.z,Ne.x,Ne.y-1),X(Me,xt,Ne.z,es,Ne.y-1))),2&Lt&&(X(Me,kt,Ne.z,Ct,Ne.y),ct&&(X(Me,ze,Ne.z,Ne.x,Ne.y-1),X(Me,kt,Ne.z,Ct,Ne.y-1))),4&Lt&&(X(Me,xt,Ne.z,es,Ne.y),ht&&(X(Me,ze,Ne.z,Ne.x,Ne.y+1),X(Me,xt,Ne.z,es,Ne.y+1))),8&Lt&&(X(Me,kt,Ne.z,Ct,Ne.y),ht&&(X(Me,ze,Ne.z,Ne.x,Ne.y+1),X(Me,kt,Ne.z,Ct,Ne.y+1)))}}const ce=[];for(const pe of D)D.some(xe=>pe.isChildOf(xe))||ce.push(pe);if(D=ce.filter(pe=>!f.some(xe=>!!(pe.overscaledZ{const Je=Ve.canonical.x+.5-Ne[0],lt=Ve.canonical.y+.5-Ne[1];return Je*Je+lt*lt{const es=kA(ht,lt,ct,xt,kt);D.has(es)||(T.push(new _p(lt,ht,ct,xt,kt)),D.add(es))},q=f.reduce((lt,ht)=>Math.max(lt,ht.overscaledZ),S),K=1<{const ct=Math.floor(lt[0]),xt=Math.floor(lt[1]),kt=(lt[0]-ct)*br,es=(lt[1]-xt)*br,Ct=Math.floor(ht[0]),Lt=Math.floor(ht[1]),Zt=(ht[0]-Ct)*br,Qt=(ht[1]-Lt)*br;for(let Cs=-1;Cs<=1;Cs++){const Fs=ct+Cs;if(!(Fs<0||Fs>=K)){ce.x=kt-Cs*br,pe.x=Zt-(Fs-Ct)*br;for(let on=-1;on<=1;on++){const sn=xt+on;ce.y=es-on*br,pe.y=Qt-(sn-Lt)*br,h7(ce,pe,X)&&F(q,0,S,Fs,sn)}}}},Ne=b.points,Me=Ne[3],ze=Ne[2],Ve=this._projectToGround(Me,Ne[7]),Je=this._projectToGround(ze,Ne[6]);return xe(Me,Ve),xe(ze,Je),T}_projectToGround(f,b){return yt(te(),f,b,f[2]/(f[2]-b[2]))}_projectToZ(f,b,S){const T=f[2]-b[2];return Math.abs(T)<1e-6?le(f):yt(te(),f,b,(f[2]-S)/T)}extendTileCoverForTunnels(f,b,S,T){if(S<18)return[];const D=b.points,F=D[0],q=D[1],K=D[4],X=D[5];if(K[2]>=0&&X[2]>=0||F[2]<=0||q[2]<=0)return[];const ce=K[2]<0?this._projectToZ(F,K,0):K,pe=X[2]<0?this._projectToZ(q,X,0):X,xe=-T,Ne=K[2]3&&(ze.length=3),ze}_findExtensionTilesInQuad(f,b,S,T){const D=[],F=new Set;for(const Ct of f)F.add(Ct.key);const q=f.reduce((Ct,Lt)=>Math.max(Ct,Lt.overscaledZ),b),K=1<{const Zt=Ct.canonical.x+.5-kt,Qt=Ct.canonical.y+.5-es,Cs=Lt.canonical.x+.5-kt,Fs=Lt.canonical.y+.5-es;return Zt*Zt+Qt*Qt-(Cs*Cs+Fs*Fs)||Ct.canonical.x-Lt.canonical.x||Ct.canonical.y-Lt.canonical.y}),D}coveringTiles(f){let b=this.coveringZoomLevel(f);const S=b,T=this.elevation&&this.elevation.exaggeration(),D=T&&!f.isTerrainDEM,F=this.projection.name==="mercator";if(f.minzoom!==void 0&&bf.maxzoom&&(b=f.maxzoom);const q=this.locationCoordinate(this.center),K=this.center.lat,X=1<{const en=new vt(ws.x+25e-6,ws.y,ws.z),wn=new vt(ws.x,ws.y+25e-6,ws.z),Nn=ws.toLngLat(),Pn=en.toLngLat(),jn=wn.toLngLat(),Wn=this.locationCoordinate(Nn),Kn=this.locationCoordinate(Pn),Dr=this.locationCoordinate(jn),sr=Math.hypot(Kn.x-Wn.x,Kn.y-Wn.y),yr=Math.hypot(Dr.x-Wn.x,Dr.y-Wn.y);return Math.sqrt(sr*yr)*es/25e-6},Lt=ws=>{const qs=xt,en=kt;return{aabb:uet(this,X,0,0,0,ws,en,qs,this.projection),zoom:0,x:0,y:0,minZ:en,maxZ:qs,wrap:ws,fullyVisible:!1}},Zt=[];let Qt=[];const Cs=b,Fs=f.reparseOverscaled?S:b,on=(Ve-this._centerAltitude)*ze,sn=ws=>{if(!this._elevation||!ws.tileID||!F)return;const qs=this._elevation.getMinMaxForTile(ws.tileID),en=ws.aabb;qs?(en.min[2]=qs.min,en.max[2]=qs.max,en.center[2]=(en.min[2]+en.max[2])/2):(ws.shouldSplit=Rn(ws),ws.shouldSplit||(en.min[2]=en.max[2]=en.center[2]=this._centerAltitude))},hn=(ws,qs)=>{if(.707*qs{if(ws.zoom=.9)return!0}else if(D&&(wn=ws.aabb.distanceZ(Je)*ze),this.projection.isReprojectedInTileSpace&&S<=5){const yr=Math.pow(2,ws.zoom),Ra=Ct(new vt((ws.x+.5)/yr,(ws.y+.5)/yr));Nn=Ra>.85?1:Ra}if(!F&&!pe){const yr=Math.sqrt(qs*qs+en*en+wn*wn);let Ra=(1<0;){const ws=Zt.pop(),qs=ws.x,en=ws.y;let wn=ws.fullyVisible;const Nn=()=>this.projection.name==="globe"&&(ws.y===0||ws.y===(1<Pn)continue;let jn=0;if(!wn){let sr=lt?ws.aabb.intersectsPrecise(Ne):ws.aabb.intersectsPreciseFlat(Ne);if(sr===0&&Nn()){const yr=new NA(ws.zoom,qs,en);sr=FMe(this,X,yr,!0).intersectsPrecise(Ne)}if(sr===0)continue;if(f.calculateQuadrantVisibility)if(Ne.containsPoint(ws.aabb.center))jn=15;else for(let yr=0;yr<4;yr++)ws.aabb.quadrant(yr).intersects(Ne)!==0&&(jn|=1<>1),Kn={aabb:F?ws.aabb.quadrant(Pn):uet(this,X,ws.zoom+1,jn,Wn,ws.wrap,ws.minZ,ws.maxZ,this.projection),zoom:ws.zoom+1,x:jn,y:Wn,wrap:ws.wrap,fullyVisible:wn,tileID:void 0,shouldSplit:void 0,minZ:ws.minZ,maxZ:ws.maxZ};D&&!pe&&(Kn.tileID=new _p(ws.zoom+1===Cs?Fs:ws.zoom+1,ws.wrap,ws.zoom+1,jn,Wn),sn(Kn)),Zt.push(Kn)}}if(this.fogCullDistSq){const ws=this.fogCullDistSq,qs=this.horizonLineFromTop();Qt=Qt.filter(en=>{const wn=[0,0,0,1],Nn=[br,br,0,1],Pn=this.calculateFogTileMatrix(en.tileID.toUnwrapped());dt(wn,wn,Pn),dt(Nn,Nn,Pn);const jn=(sr=wn,yr=Nn,(Dr=[])[0]=Math.min(sr[0],yr[0]),Dr[1]=Math.min(sr[1],yr[1]),Dr[2]=Math.min(sr[2],yr[2]),Dr[3]=Math.min(sr[3],yr[3]),Dr),Wn=function(si,La,Oi){return si[0]=Math.max(La[0],Oi[0]),si[1]=Math.max(La[1],Oi[1]),si[2]=Math.max(La[2],Oi[2]),si[3]=Math.max(La[3],Oi[3]),si}([],wn,Nn),Kn=function(si,La){let Oi=0;for(let bi=0;bi<2;++bi)si[bi]>0&&(Oi+=(si[bi]-0)*(si[bi]-0)),La[bi]<0&&(Oi+=(0-La[bi])*(0-La[bi]));return Oi}(jn,Wn);var Dr,sr,yr;if(Kn===0)return!0;let Ra=!1;const $a=this._elevation;if($a&&Kn>ws&&qs!==0){const si=this.calculateProjMatrix(en.tileID.toUnwrapped());let La;f.isTerrainDEM||(La=$a.getMinMaxForTile(en.tileID)),La||(La={min:kt,max:xt});const Oi=function(Bl){const cl=Math.round((Bl+45+360)%360/90)%4;return jh[cl]}(this.rotation),bi=[Oi[0]*br,Oi[1]*br,La.max];tt(bi,bi,si),Ra=(1-bi[1])*this.height*.5ws.distanceSq-qs.distanceSq).map(ws=>ws.tileID)}resize(f,b){this.width=f,this.height=b,this.pixelsToGLUnits=[2/f,-2/b],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 b=Jr(f.lat,-85.051129,Ce),S=this.projection.project(f.lng,b);return new Kt(S.x*this.worldSize,S.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/de(1,this.center.lat)/this.worldSize}setLocationAtPoint(f,b){let S,T;const D=this.centerPoint;if(this.projection.name==="globe"){const q=this.worldSize;S=(b.x-D.x)/q,T=(b.y-D.y)/q}else{const q=this.pointCoordinate(b),K=this.pointCoordinate(D);S=q.x-K.x,T=q.y-K.y}const F=this.locationCoordinate(f);this.setLocation(new vt(F.x-S,F.y-T))}setLocation(f){this.center=this.coordinateLocation(f),this.projection.wrap&&(this.center=this.center.wrap())}locationPoint(f,b){return this.projection.locationPoint(this,f,b)}locationPoint3D(f,b){return this.projection.locationPoint(this,f,b,!0)}pointLocation(f){return this.coordinateLocation(this.pointCoordinate(f))}pointLocation3D(f,b){return this.coordinateLocation(this.pointCoordinate3D(f,b))}locationCoordinate(f,b){const S=b?de(b,f.lat):void 0,T=this.projection.project(f.lng,f.lat);return new vt(T.x,T.y,S)}coordinateLocation(f){return this.projection.unproject(f.x,f.y)}pointRayIntersection(f,b){const S=b??this._centerAltitude,T=[f.x,f.y,0,1],D=[f.x,f.y,1,1];dt(T,T,this.pixelMatrixInverse),dt(D,D,this.pixelMatrixInverse);const F=D[3];xs(T,T,1/T[3]),xs(D,D,1/F);const q=T[2],K=D[2];return{p0:T,p1:D,t:q===K?0:(S-q)/(K-q)}}screenPointToMercatorRay(f){const b=[f.x,f.y,0,1],S=[f.x,f.y,1,1];return dt(b,b,this.pixelMatrixInverse),dt(S,S,this.pixelMatrixInverse),xs(b,b,1/b[3]),xs(S,S,1/S[3]),b[2]=de(b[2],this._center.lat)*this.worldSize,S[2]=de(S[2],this._center.lat)*this.worldSize,xs(b,b,1/this.worldSize),xs(S,S,1/this.worldSize),new Xte([b[0],b[1],b[2]],Fe([],wt([],S,b)))}rayIntersectionCoordinate(f){const{p0:b,p1:S,t:T}=f,D=de(b[2],this._center.lat),F=de(S[2],this._center.lat);return new vt(da(b[0],S[0],T)/this.worldSize,da(b[1],S[1],T)/this.worldSize,da(D,F,T))}pointCoordinate(f,b=this._centerAltitude){return this.projection.pointCoordinate(this,f.x,f.y,b)}pointCoordinate3D(f,b){if(!this.elevation)return this.pointCoordinate(f,b);let S=this.projection.pointCoordinate3D(this,f.x,f.y);if(S)return new vt(S[0],S[1],S[2]);let T=0,D=this.horizonLineFromTop();if(f.y>D)return this.pointCoordinate(f,b);const F=.02*D,q=f.clone();for(let K=0;K<10&&D-T>F;K++){q.y=da(T,D,.66);const X=this.projection.pointCoordinate3D(this,q.x,q.y);X?(D=q.y,S=X):T=q.y}return S?new vt(S[0],S[1],S[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>=6)return!this.isPointAboveHorizon(f);const b=this.pointCoordinate(f);return b.y>=0&&b.y<=1}_coordinatePoint(f,b){const S=b&&this.elevation?this.elevation.getAtPointOrZero(f,this._centerAltitude):this._centerAltitude,T=[f.x*this.worldSize,f.y*this.worldSize,S+f.toAltitude(),1];return dt(T,T,this.pixelMatrix),T[3]>0?new Kt(T[0]/T[3],T[1]/T[3]):new Kt(Number.MAX_VALUE,Number.MAX_VALUE)}_getBoundsNonRectangular(){const{top:f,left:b}=this._edgeInsets,S=this.height-this._edgeInsets.bottom,T=this.width-this._edgeInsets.right,D=this.pointLocation3D(new Kt(b,f)),F=this.pointLocation3D(new Kt(T,f)),q=this.pointLocation3D(new Kt(T,S)),K=this.pointLocation3D(new Kt(b,S));let X=Math.min(D.lng,F.lng,q.lng,K.lng),ce=Math.max(D.lng,F.lng,q.lng,K.lng),pe=Math.min(D.lat,F.lat,q.lat,K.lat),xe=Math.max(D.lat,F.lat,q.lat,K.lat);const Ne=Math.pow(2,-this.zoom)/16*270,Me=this.projection.name==="globe"?1:4,ze=(Ve,Je,lt,ht,ct)=>{const xt=(Ve+lt)/2,kt=(Je+ht)/2,es=new Kt(xt,kt),{lng:Ct,lat:Lt}=this.pointLocation3D(es),Zt=Math.max(0,X-Ct,pe-Lt,Ct-ce,Lt-xe);X=Math.min(X,Ct),ce=Math.max(ce,Ct),pe=Math.min(pe,Lt),xe=Math.max(xe,Lt),(ctNe)&&(ze(Ve,Je,xt,kt,ct+1),ze(xt,kt,lt,ht,ct+1))};if(ze(b,f,T,f,1),ze(T,f,T,S,1),ze(T,S,b,S,1),ze(b,S,b,f,1),this.projection.name==="globe"){const[Ve,Je]=function(lt){const ht=j(new Float64Array(16));M(ht,lt.pixelMatrix,lt.globeMatrix);const ct=[0,Mv,0],xt=[0,J_,0];return tt(ct,ct,ht),tt(xt,xt,ht),[ct[0]>0&&ct[0]<=lt.width&&ct[1]>0&&ct[1]<=lt.height&&!UMe(lt,new W(lt.center.lat,90)),xt[0]>0&&xt[0]<=lt.width&&xt[1]>0&&xt[1]<=lt.height&&!UMe(lt,new W(lt.center.lat,-90))]}(this);Ve?(xe=90,ce=180,X=-180):Je&&(pe=-90,ce=180,X=-180)}return new Z(new W(X,pe),new W(ce,xe))}_getBoundsRectangular(f,b){const{top:S,left:T}=this._edgeInsets,D=this.height-this._edgeInsets.bottom,F=this.width-this._edgeInsets.right,q=new Kt(T,S),K=new Kt(F,S),X=new Kt(F,D),ce=new Kt(T,D);let pe=this.pointCoordinate(q,f),xe=this.pointCoordinate(K,f);const Ne=this.pointCoordinate(X,b),Me=this.pointCoordinate(ce,b),ze=(Ve,Je)=>(Je.y-Ve.y)/(Je.x-Ve.x);return pe.y>1&&xe.y>=0?pe=new vt((1-Me.y)/ze(Me,pe)+Me.x,1):pe.y<0&&xe.y<=1&&(pe=new vt(-Me.y/ze(Me,pe)+Me.x,0)),xe.y>1&&pe.y>=0?xe=new vt((1-Ne.y)/ze(Ne,xe)+Ne.x,1):xe.y<0&&pe.y<=1&&(xe=new vt(-Ne.y/ze(Ne,xe)+Ne.x,0)),new Z().extend(this.coordinateLocation(pe)).extend(this.coordinateLocation(xe)).extend(this.coordinateLocation(Me)).extend(this.coordinateLocation(Ne))}_getBoundsRectangularTerrain(){const f=this.elevation;if(!f.visibleDemTiles.length||f.isUsingMockSource())return this._getBoundsRectangular(0,0);const b=f.visibleDemTiles.reduce((S,T)=>{if(T.dem){const D=T.dem.tree;S.min=Math.min(S.min,D.minimums[0]),S.max=Math.max(S.max,D.maximums[0])}return S},{min:Number.MAX_VALUE,max:0});return this._getBoundsRectangular(b.min*f.exaggeration(),b.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 b=this.height/2/Math.tan(this._fov/2)/Math.tan(Math.max(this._pitch,.1))-this.centerOffset.y,S=this.height/2-b*(1-this._horizonShift);return f?Math.max(0,S):S}getMaxBounds(){return this.maxBounds}setMaxBounds(f){this.maxBounds=f,this.minLat=-85.051129,this.maxLat=Ce,this.minLng=-180,this.maxLng=180,f&&(this.minLat=f.getSouth(),this.maxLat=f.getNorth(),this.minLng=f.getWest(),this.maxLng=f.getEast(),this.maxLngpe&&(q=pe-X),pe-ceNe&&(F=Ne-K),Ne-xe{for(let Fs=0;Fs<16;Fs++)Lt[Fs]=da(Zt[Fs],Qt[Fs],Cs)})(q,q,K,rl(this.pitch>=A7?1:this.pitch/A7))}else q=K;const X=Q([],K,F),ce=Q([],q,F);if(this.projection.isReprojectedInTileSpace){const xt=this.locationCoordinate(this.center);j(this._mat4Scratch);const kt=this._mat4Scratch;I(kt,kt,[xt.x*this.worldSize,xt.y*this.worldSize,0]),M(kt,kt,xtt(this)),I(kt,kt,[-xt.x*this.worldSize,-xt.y*this.worldSize,0]),M(ce,ce,kt),M(X,X,kt),this.inverseAdjustmentMatrix=function(es){const Ct=xtt(es,!0);return m([],[Ct[0],Ct[1],Ct[4],Ct[5]])}(this)}else this.inverseAdjustmentMatrix=[1,0,0,1];if(P(this.mercatorMatrix,ce,[this.worldSize,this.worldSize,this.worldSize/D,1]),this.projMatrix=ce,A(this.invProjMatrix,this.projMatrix),b){const xt=this._camera.getCameraToClipPerspective(this._fov,this.width/this.height,this._nearZ,1/0);xt[8]=2*-f.x/this.width,xt[9]=2*f.y/this.height,Q(this._expandedFarZProjMatrixBuf,xt,F),this.expandedFarZProjMatrix=this._expandedFarZProjMatrixBuf}else this.expandedFarZProjMatrix=this.projMatrix;A(this._mat4Scratch,q),this.frustumCorners=RMe.fromInvProjectionMatrix(this._mat4Scratch,this.horizonLineFromTop(),this.height),this.cameraFrustum=D4.fromInvProjectionMatrix(this.invProjMatrix,this.worldSize,0,!b),G(this.skyboxMatrix,[1,-1,1]),R(this.skyboxMatrix,this.skyboxMatrix,this._pitch),B(this.skyboxMatrix,this.skyboxMatrix,this.angle),oe(this.starsProjMatrix,this._fov,this.width/this.height,this._nearZ,this._farZ);const pe=(Math.PI/2-this._pitch)*(this.height/this._fov)*this._horizonShift;_(this._mat4Scratch,this.starsProjMatrix),this._mat4Scratch[8]=2*-f.x/this.width,this._mat4Scratch[9]=2*(f.y+pe)/this.height,M(this.skyboxMatrix,this._mat4Scratch,this.skyboxMatrix);const xe=this.point,Ne=xe.x,Me=xe.y,ze=this.width%2/2,Ve=this.height%2/2,Je=Math.cos(this.angle),lt=Math.sin(this.angle),ht=Ne-Math.round(Ne)+Je*ze+lt*Ve,ct=Me-Math.round(Me)+Je*Ve+lt*ze;if(_(this.alignedProjMatrix,ce),I(this.alignedProjMatrix,this.alignedProjMatrix,[ht>.5?ht-1:ht,ct>.5?ct-1:ct,0]),G(this.labelPlaneMatrix,[this.width/2,-this.height/2,1]),I(this.labelPlaneMatrix,this.labelPlaneMatrix,[1,-1,0]),G(this.glCoordMatrix,[1,-1,1]),I(this.glCoordMatrix,this.glCoordMatrix,[-1,-1,0]),P(this.glCoordMatrix,this.glCoordMatrix,[2/this.width,2/this.height,1]),M(this.pixelMatrix,this.labelPlaneMatrix,X),this._calcFogMatrices(),this._distanceTileDataCache={},!A(this.pixelMatrixInverse,this.pixelMatrix))throw new Error("failed to invert matrix");if(this.projection.name==="globe"||this.mercatorFromTransition){this.globeMatrix=function(kt){const{x:es,y:Ct}=kt.point,{lng:Lt,lat:Zt}=kt._center;return aet(es,Ct,kt.worldSize,Lt,Zt)}(this);const xt=[this.globeMatrix[12],this.globeMatrix[13],this.globeMatrix[14]];this.globeCenterInViewSpace=tt(xt,xt,F),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,b=this.cameraPixelsPerMeter,S=this._camera.position,T=1/this.height/this._pixelsPerMercatorPixel,D=[f,f,b];Be(D,D,T),Be(S,S,-1),Te(S,S,D),U(this.mercatorFogMatrix,S),P(this.mercatorFogMatrix,this.mercatorFogMatrix,D),this.worldToFogMatrix=this._camera.getWorldToCameraPosition(f,b,T)}_computeCameraPosition(f){const b=(f=f||this.pixelsPerMeter)/this.pixelsPerMeter,S=this._camera.forward(),T=this.point,D=this._mercatorZfromZoom(this._seaLevelZoom?this._seaLevelZoom:this._zoom)*b-f/this.worldSize*this._centerAltitude;return[T.x/this.worldSize-S[0]*D,T.y/this.worldSize-S[1]*D,f/this.worldSize*this._centerAltitude-S[2]*D]}_updateCameraState(){this.height&&(this._camera.setPitchBearing(this._pitch,this.angle),this._camera.position=this._computeCameraPosition())}_translateCameraConstrained(f){const b=this._maxCameraBoundsDistance()*Math.cos(this._pitch),S=this._camera.position[2],T=f[2];let D=1;this.projection.wrap&&(this.center=this.center.wrap()),T>0&&(D=Math.min((b-S)/T,1)),this._camera.position=je([],this._camera.position,f,D),this._updateStateFromCamera()}_updateStateFromCamera(){const f=this._camera.position,b=this._camera.forward(),{pitch:S,bearing:T}=this._camera.getPitchBearing(),D=de(this._centerAltitude,this.center.lat)*this._pixelsPerMercatorPixel,F=this._mercatorZfromZoom(this._maxZoom)*Math.cos(_a(this._maxPitch)),q=Math.max((f[2]-D)/Math.cos(S),F),K=this._zoomFromMercatorZ(q);je(f,f,b,q),this._pitch=Jr(S,_a(this.minPitch),_a(this.maxPitch)),this.angle=fc(T,-Math.PI,Math.PI),this._setZoom(Jr(K,this._minZoom,this._maxZoom)),this._updateSeaLevelZoom(),this._center=this.coordinateLocation(new vt(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??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 b=0,S=6,T=0,D=1/0;for(;S-b>1e-6&&S>b;){const F=b+.5*(S-b),q=this.tileSize*Math.pow(2,F),K=this.getCameraToCenterDistance(this.projection,F,q),X=this.scaleZoom(K/(Math.max(0,f)*this.tileSize)),ce=Math.abs(F-X);ceX||xe.y>1)return!0}return!1}isHorizonVisible(){return this.pitch+$o(this.fovAboveCenter)>88||this.anyCornerOffEdge(new Kt(0,0),new Kt(this.width,this.height))}zoomDeltaToMovement(f,b){const S=fe(wt([],this._camera.position,f)),T=this._zoomFromMercatorZ(S)+b;return S-this._mercatorZfromZoom(T)}getCameraPoint(){if(this.projection.name==="globe"){const f=function([b,S,T],D){const F=[b,S,T,1];dt(F,F,D);const q=F[3]=Math.max(F[3],1e-6);return F[0]/=q,F[1]/=q,F[2]/=q,F}([this.globeMatrix[12],this.globeMatrix[13],this.globeMatrix[14]],this.pixelMatrix);return new Kt(f[0],f[1])}{const f=Math.tan(this._pitch)*(this.cameraToCenterDistance||1);return this.centerPoint.add(new Kt(0,f))}}getCameraToCenterDistance(f,b=this.zoom,S=this.worldSize){const T=SH(f,b,this.width,this.height,1024),D=f.pixelSpaceConversion(this.center.lat,S,T);let F=.5/Math.tan(.5*this._fov)*this.height*D;return this.isOrthographic&&(F=da(1,F,rl(this.pitch>=A7?1:this.pitch/A7))),F}getWorldToCameraMatrix(){const f=this._camera.getWorldToCamera(this.worldSize,this.projection.zAxisUnit==="meters"?this.pixelsPerMeter:1);return this.projection.name==="globe"&&M(f,f,this.globeMatrix),f}getFrustum(f){return D4.fromInvProjectionMatrix(this.invProjMatrix,this.worldSize,f,this.projection.zAxisUnit==="meters")}}const E7=(w,f)=>{if(f<=0||w.terrain)return{shouldRenderCutoff:!1,uniformValues:{u_cutoff_params:[0,0,0,1]}};const b=w.transform,S=b.pitch,T=b.isLODDisabled(!1)?60:30;if(S0,uniformValues:{u_cutoff_params:[b._nearZ,b._farZ,(ce-b._nearZ)/D,(ce-pe-b._nearZ)/D]}}},OH=.05;function tne(w,f,b){const S=Uo(45,65,b),[T,D]=w.range;let F=1-Math.min(1,Math.exp((f-T)/(D-T)*-6));return F*=F*F,F=Math.min(1,1.00747*F),F*S*w.alpha}function lnt(w,f,b,S,T){return tne(w,fe(tt([],[f,b,S],T.mercatorFogMatrix)),T.pitch)}function W6e(w,f,b,S){const T=1<({u_matrix:w,u_color:f,u_overlay:0,u_overlay_scale:b}),tS=new Float64Array(16),MA=new Float64Array(16),dnt=new Float64Array(16),K6e=new Float64Array(16),Y6e=new Float64Array(16),sne=new Float64Array(16),BXt=new Float64Array(16),nne=[0,0,0],$Xt=new Float32Array(16),rne=[0,0,0],UXt=[0,0,0],Z6e=[];function unt(w,f,b){const S=b.cameraWorldSizeForFog/b.worldSize;return P(w,b.worldToFogMatrix,[S,S,1]),M(w,w,f),w}function FH(w,f,b,S){return I(w,f,b),at(S,UZt)||P(w,w,S),w}function X6e(w,f,b,S,T){const D=b.material,F=S.context,{baseColorTexture:q,metallicRoughnessTexture:K}=D.pbrMetallicRoughness,{normalTexture:X,occlusionTexture:ce,emissionTexture:pe}=D;function xe(Me,ze,Ve){if(Me&&(w.push(ze),F.activeTexture.set(F.gl.TEXTURE0+Ve),Me.gfxTexture)){const{minFilter:Je,magFilter:lt,wrapS:ht,wrapT:ct}=Me.sampler;Me.gfxTexture.bindExtraParam(Je,lt,ht,ct)}}xe(q,"HAS_TEXTURE_u_baseColorTexture",O0.BaseColor),xe(K,"HAS_TEXTURE_u_metallicRoughnessTexture",O0.MetallicRoughness),xe(X,"HAS_TEXTURE_u_normalTexture",O0.Normal),xe(ce,"HAS_TEXTURE_u_occlusionTexture",O0.Occlusion),xe(pe,"HAS_TEXTURE_u_emissionTexture",O0.Emission),T&&(T.texture||(T.texture=new Cet(S.context,T.image,[T.image.height,T.image.height,T.image.height],F.gl.RGBA8)),F.activeTexture.set(F.gl.TEXTURE0+O0.LUT),T.texture&&T.texture.bind(F.gl.LINEAR,F.gl.CLAMP_TO_EDGE),w.push("APPLY_LUT_ON_GPU")),b.texcoordBuffer&&(w.push("HAS_ATTRIBUTE_a_uv_2f"),f.push(b.texcoordBuffer)),b.colorBuffer&&(w.push(b.colorBuffer.itemSize===12?"HAS_ATTRIBUTE_a_color_3f":"HAS_ATTRIBUTE_a_color_4f"),f.push(b.colorBuffer)),b.normalBuffer&&(w.push("HAS_ATTRIBUTE_a_normal_3f"),f.push(b.normalBuffer)),b.pbrBuffer&&(w.push("HAS_ATTRIBUTE_a_pbr"),w.push("HAS_ATTRIBUTE_a_heightBasedEmissiveStrength"),f.push(b.pbrBuffer)),D.alphaMode!=="OPAQUE"&&D.alphaMode!=="MASK"||w.push("UNPREMULT_TEXTURE_IN_SHADER"),D.defined||w.push("DIFFUSE_SHADED");const Ne=S.shadowRenderer;Ne&&(w.push("RENDER_SHADOWS"),Ne.useNormalOffset&&w.push("NORMAL_OFFSET"))}function Q6e(w,f,b,S,T,D){const F=w.modelOpacity,q=f.context,K=new yx(f.context.gl.LEQUAL,w.isLightMesh?yx.ReadOnly:yx.ReadWrite,f.depthRangeFor3D),X=f.transform,ce=w.mesh,pe=ce.material,xe=pe.pbrMetallicRoughness,Ne=f.style.fog;f.transform.projection.zAxisUnit==="pixels"?tS.set(w.nodeModelMatrix):M(tS,S.zScaleMatrix,w.nodeModelMatrix),M(tS,S.negCameraPosMatrix,tS),A(MA,tS),C(MA,MA);const Me=b.paint.get("model-color-use-theme").constantOr("default")==="none",ze=b.paint.get("model-emissive-strength").constantOr(0),Ve={defines:[]},Je=[],lt=f.shadowRenderer;lt&&(lt.useNormalOffset=!1),X6e(Ve.defines,Je,ce,f,Me?null:b.lut);let ht=null;if(Ne&&(ht=unt(dnt,w.nodeModelMatrix,f.transform),X.projection.name!=="globe")){const es=ce.aabb.min,Ct=ce.aabb.max,[Lt,Zt]=Ne.getOpacityForBounds(ht,es[0],es[1],Ct[0],Ct[1]);Ve.overrideFog=Lt>=OH||Zt>=OH}const ct=E7(f,b.paint.get("model-cutoff-fade-range"));ct.shouldRenderCutoff&&Ve.defines.push("RENDER_CUTOFF");const xt=f.getOrCreateProgram("model",Ve),kt=z6e(w.worldViewProjection,tS,MA,null,f,F,xe.baseColorFactor,pe.emissiveFactor,xe.metallicFactor,xe.roughnessFactor,pe,ze,b,void 0,void 0,w.materialOverride,w.modelColor,1,xt.fixedDefines.includes("LIGHTING_3D_MODE"));f.uploadCommonUniforms(q,xt,null,ht,ct,w.lightOverrides),f.renderPass!=="shadow"&<&<.setupShadowsFromMatrix(w.nodeModelMatrix,xt),xt.draw(f,q.gl.TRIANGLES,K,T,D,ce.material.doubleSided?vx.disabled:vx.backCCW,kt,b.id,ce.vertexBuffer,ce.indexBuffer,ce.segments,b.paint,f.transform.zoom,void 0,Je)}function hnt(w,f){return w.style._importedAsBasemap?"basemap":f.scope}function J6e(w,f,b,S,T,D,F,q,K,X,ce){const pe=w.transform,xe=!!f.isGeometryBloom&&f.isGeometryBloom;if(f.minZoom!==void 0&&w.transform.zoomf.maxZoom||xe&&w.renderPass==="shadow")return;const Ne=pe.projection.name==="globe"?Pse(b,pe):[...b];M(Ne,Ne,f.globalMatrix);const Me=M([],S,Ne);if(f.meshes)for(const ze of f.meshes){const Ve=q.get(ze.material.name);if(Ve&&Ve.opacity<=0)continue;if(ze.material.alphaMode!=="BLEND"){F.push({mesh:ze,depth:0,modelIndex:T,worldViewProjection:Me,nodeModelMatrix:Ne,isLightMesh:xe,materialOverride:Ve,modelOpacity:K,modelColor:X,lightOverrides:ce,node:f,modelMatrix:b});continue}const Je=tt([],ze.centroid,Me);!pe.isOrthographic&&Je[2]<=0||D.push({mesh:ze,depth:Je[2],modelIndex:T,worldViewProjection:Me,nodeModelMatrix:Ne,isLightMesh:xe,materialOverride:Ve,modelOpacity:K,modelColor:X,lightOverrides:ce,node:f,modelMatrix:b})}if(f.children)for(const ze of f.children)J6e(w,ze,b,S,T,D,F,q,K,X,ce)}function zH(w,f,b,S,T){const D=b.shadowRenderer;if(!D)return;const F=D.getShadowPassDepthMode(),q=T||D.calculateShadowPassMatrixFromMatrix(f),K=Zst(q);b.getOrCreateProgram("modelDepth").draw(b,b.context.gl.TRIANGLES,F,rw.disabled,bu.disabled,vx.disabled,K,S.id,w.vertexBuffer,w.indexBuffer,w.segments,S.paint,b.transform.zoom,void 0,void 0)}function mnt(w,f,b,S){const T=function(ce,pe){if(pe.footprintDebugMesh)return pe.footprintDebugMesh;if(!pe.footprint)return null;const xe=ce.context,Ne=pe.footprint.vertices,Me=pe.footprint.indices,ze=new Sn;ze.reserve(Ne.length);for(const Zt of Ne)ze.emplaceBack(Zt.x,Zt.y);const Ve=new Va;Ve.reserve(Me.length);for(let Zt=0;Zt0){const xe=D.terrain,Ne=xe.findDEMTileFor(q);Ne&&Ne.dem?K=S7.create(xe,q,Ne):pe=0}if(pe===0&&(F.terrainElevationMin=0,F.terrainElevationMax=0),pe===F.validForExaggeration&&(pe===0||K&&K._demTile&&K._demTile.tileID===F.validForDEMTile.id&&K._dem._timestamp===F.validForDEMTile.timestamp))return!1;for(const xe in F.instancesPerModel){const Ne=F.instancesPerModel[xe];for(let Me=0;MeX&&(X=Ne.max)}const ce=Jr(S.x,D,F)-S.x,pe=Jr(S.y,q,K)-S.y,xe=de(X,f.center.lat)-S.z;return f._zoomFromMercatorZ(Math.sqrt(ce*ce+pe*pe+xe*xe))}function pnt(w,f,b,S,T,D,F){const q=w.context,K=w.renderPass==="shadow",X=w.shadowRenderer,ce=K&&X?X.getShadowPassDepthMode():new yx(q.gl.LEQUAL,yx.ReadWrite,w.depthRangeFor3D),pe=w.isTileAffectedByFog(D),xe=w.transform.projection.name==="globe";if(b.meshes)for(const Ne of b.meshes){const Me=xe?[]:["MODEL_POSITION_ON_GPU"],ze=[];let Ve,Je,lt;const ht=!xe&&S.instancedDataArray.length>20;ht&&Me.push("INSTANCED_ARRAYS");const ct=E7(w,f.paint.get("model-cutoff-fade-range"));if(ct.shouldRenderCutoff&&Me.push("RENDER_CUTOFF"),K&&X)Ve=w.getOrCreateProgram("modelDepth",{defines:Me}),Je=Zst(F.shadowTileMatrix,F.shadowTileMatrix,b.globalMatrix),lt=bu.disabled;else{X6e(Me,ze,Ne,w,f.paint.get("model-color-use-theme").constantOr("default")==="none"?null:f.lut),Ve=w.getOrCreateProgram("model",{defines:Me,overrideFog:pe});const kt=Ne.material,es=kt.pbrMetallicRoughness,Ct=f.paint.get("model-opacity").constantOr(1),Lt=f.paint.get("model-emissive-strength").constantOr(0);Je=z6e(D.expandedProjMatrix,b.globalMatrix,$Xt,null,w,Ct,es.baseColorFactor,kt.emissiveFactor,es.metallicFactor,es.roughnessFactor,kt,Lt,f,T,void 0,void 0,void 0,1,Ve.fixedDefines.includes("LIGHTING_3D_MODE")),X&&(F.shadowUniformsInitialized?Ve.setShadowUniformValues(q,X.getShadowUniformValues()):(X.setupShadows(D.toUnwrapped(),Ve,"model-tile"),F.shadowUniformsInitialized=!0)),lt=ct.shouldRenderCutoff||Ct<1||kt.alphaMode!=="OPAQUE"?bu.alphaBlended:bu.unblended}w.uploadCommonUniforms(q,Ve,D.toUnwrapped(),null,ct);const xt=Ne.material.doubleSided?vx.disabled:vx.backCCW;if(ht)ze.push(S.instancedDataBuffer),Ve.draw(w,q.gl.TRIANGLES,ce,rw.disabled,lt,xt,Je,f.id,Ne.vertexBuffer,Ne.indexBuffer,Ne.segments,f.paint,w.transform.zoom,void 0,ze,S.instancedDataArray.length);else{const kt=K?"u_instance":"u_normal_matrix";for(let es=0;es0)if(w.targetLod<0)w.targetLod=f>S?1:0;else{const F=T>0?b/1e3/T:1;w.targetLod=Jr(f>S?w.targetLod+F:w.targetLod-F,0,1)}else w.targetLod=0}function KXt(w,f,b,S){if(!b.modelManager)return!0;const T=b.modelManager;if(!b.shadowRenderer)return!0;const D=b.shadowRenderer,F=f.aabb;let q=!0,K=w.maxHeight;if(K===0){let ce=0;for(const pe in w.instancesPerModel){const xe=T.getModel(pe,S);xe?ce=Math.max(ce,Math.max(Math.max(xe.aabb.max[0],xe.aabb.max[1]),xe.aabb.max[2])):q=!1}K=w.maxScale*ce*1.41+w.maxVerticalOffset,q&&(w.maxHeight=K)}F.max[2]=K,F.min[2]+=w.terrainElevationMin,F.max[2]+=w.terrainElevationMax,tt(F.min,F.min,f.tileMatrix),tt(F.max,F.max,f.tileMatrix);const X=F.intersects(D.getCurrentCascadeFrustum());return b.currentShadowCascade===0&&(w.isInsideFirstShadowMapFrustum=X===2),X===0}function YXt(w,f){const b=w.uniformValues.u_cutoff_params[0],S=w.uniformValues.u_cutoff_params[1],T=w.uniformValues.u_cutoff_params[2],D=w.uniformValues.u_cutoff_params[3];return S===b||D===T?1:Jr(((f-b)/(S-b)-T)/(D-T),0,1)}function ZXt(w,f,b,S){if(f.pitch<20)return 1;const T=f.getWorldToCameraMatrix();M(T,T,w);const D=Is(b.min[0],b.min[1],b.min[2],1);let F=dt(Ut(),D,T),q=F,K=F;D[1]=b.max[1],F=dt(Ut(),D,T),q=F[1]K[1]?F:K,D[0]=b.max[0],F=dt(Ut(),D,T),q=F[1]K[1]?F:K,D[1]=b.min[1],F=dt(Ut(),D,T),q=F[1]K[1]?F:K;const X=Jr(S[0],0,1),ce=100*f.pixelsPerMeter*Jr(S[1],0,1),pe=Jr(S[2],0,1),xe=(ze=Ut(),ct=(Ve=q)[1],xt=Ve[2],kt=Ve[3],ze[0]=(ht=Ve[0])+(lt=X)*((Je=K)[0]-ht),ze[1]=ct+lt*(Je[1]-ct),ze[2]=xt+lt*(Je[2]-xt),ze[3]=kt+lt*(Je[3]-kt),ze),Ne=Math.tan(.5*f.fovX),Me=-xe[2]*Ne;var ze,Ve,Je,lt,ht,ct,xt,kt;if(ce===0)return xe[1]<-Math.abs(Me)?pe:1;const es=Jr(da(1,pe,(-Math.abs(Me)-xe[1])/ce),pe,1);return da(1,es,Jr((f.pitch-20)/20,0,1))}var ePe=` #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`,gnt=` #if defined(VIEWPORT_ORIGIN_TOP_LEFT) || defined(FLIP_Y) #define FLIP_VIEWPORT_UV_Y(uv) (uv).y=1.0-(uv).y #else #define FLIP_VIEWPORT_UV_Y(uv) #endif #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) { #ifdef CLIP_ZERO_TO_ONE highp float depth=ndc_z; #else highp float depth=ndc_z*0.5+0.5; #endif 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;}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 );int viewport_dither_index(vec2 fragCoordXY) {return (int(fragCoordXY.x) % 4)*4+(int(fragCoordXY.y) % 4);} #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);}`,xnt=` #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`,ynt="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;}",vnt=` #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; #endif vec3 elevationVector(vec2 pos) { #ifdef PROJECTION_GLOBE_VIEW 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 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 }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);} #endif float elevation(vec2 apos) { #ifdef TERRAIN #ifdef ZERO_EXAGGERATION return 0.0; #endif #ifdef TERRAIN_VERTEX_MORPHING float nextElevation=currentElevation(apos);float prevElevation=prevElevation(apos);return mix(prevElevation,nextElevation,u_dem_lerp); #else return currentElevation(apos); #endif #else 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`,bnt=`#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`,_nt=`#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;FLIP_VIEWPORT_UV_Y(uv);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`,tPe=` #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`,wnt=`#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`,jnt=`#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`,Nnt=`#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;highp vec2 shadow_map_ndc_to_uv(highp vec2 ndc_xy) { #ifdef SHADOW_MAP_FLIP_Y return ndc_xy*vec2(0.5,-0.5)+0.5; #else return ndc_xy*0.5+0.5; #endif }highp vec3 shadow_map_ndc_to_sample_space(highp vec3 ndc) { #ifdef CLIP_ZERO_TO_ONE return vec3(shadow_map_ndc_to_uv(ndc.xy),ndc.z); #else return vec3(shadow_map_ndc_to_uv(ndc.xy),ndc.z*0.5+0.5); #endif }float shadow_sample(sampler2DShadow shadowmap,highp vec3 pos,highp float bias) { #ifdef CLIP_ZERO_TO_ONE highp vec3 coord=vec3(shadow_map_ndc_to_uv(pos.xy),pos.z-bias); #else highp vec3 coord=vec3(shadow_map_ndc_to_uv(pos.xy),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=shadow_map_ndc_to_sample_space(light_view_pos0.xyz/light_view_pos0.w);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 knt=/^#include\s+"([^"]+)"\s*\r?\n/gm,Snt=/#pragma mapbox: ([\w\-]+) ([\w]+) ([\w]+) ([\w]+)/g,XXt=/\b[A-Za-z_][A-Za-z0-9_]*\b/g,QXt=new Set(["ifdef","ifndef","elif","if","defined"]),ane=new Set;T7(ePe,ane),T7(xnt,ane),T7(gnt,ane);const Cnt={"_prelude_fog.vertex.glsl":bnt,"_prelude_terrain.vertex.glsl":vnt,"_prelude_shadow.vertex.glsl":jnt,"_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":_nt,"_prelude_shadow.fragment.glsl":Nnt,"_prelude_lighting.glsl":tPe,"_prelude_raster_array.glsl":wnt,"_prelude_indicator_cutout.fragment.glsl":` #ifdef INDICATOR_CUTOUT uniform vec3 u_indicator_cutout_centers;uniform vec4 u_indicator_cutout_params; #endif 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 }`,"_prelude_feature_cutout.fragment.glsl":`// feature cutout (gl-native only) `,"_prelude_feature_cutout.vertex.glsl":`// feature cutout (gl-native only) `},ine={},Ant="precision highp float;",Ent="precision mediump float;",Tnt=` #if defined(GL_EXT_blend_func_extended) && defined(DUAL_SOURCE_BLENDING) #extension GL_EXT_blend_func_extended : require #endif`,Mnt={preludeTerrain:cc("",vnt),preludeFog:cc(_nt,bnt),preludeShadow:cc(Nnt,jnt),preludeRasterArray:cc(wnt,""),preludeLighting:cc(tPe,tPe),preludePrecisionQualifiers:cc(Ent,Ant),prelude:cc(gnt,xnt),preludeExtensions:cc(Tnt,"")},JXt=[Tnt,Ent,ePe,Mnt.prelude.fragmentSource].join(` `),eQt=[Ant,ePe,Mnt.prelude.vertexSource].join(` `);var tQt={background:cc(`#include "_prelude_fog.fragment.glsl" #include "_prelude_feature_cutout.fragment.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=fragcoord_to_viewport_uv(gl_FragCoord.xy,u_inv_viewport_size.xy);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:cc(`#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:cc(`#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:cc("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:cc(`#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_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:cc(`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:cc("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:cc("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:cc("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 }`),fill:cc(`#include "_prelude_fog.fragment.glsl" #include "_prelude_lighting.glsl" #include "_prelude_shadow.fragment.glsl" #include "_prelude_indicator_cutout.fragment.glsl" #include "_prelude_feature_cutout.fragment.glsl" #pragma mapbox: define highp vec4 color #pragma mapbox: define lowp float opacity uniform float u_emissive_strength;uniform lowp float u_opacity_multiplier; #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*u_opacity_multiplier); #ifdef INDICATOR_CUTOUT if (v_z_offset >=0.0) {out_color=applyCutout(out_color,v_z_offset);} #endif #ifdef FEATURE_CUTOUT float z=0.0; #ifdef ELEVATED_ROADS z=v_road_z_offset; #endif out_color=apply_feature_cutout(out_color,gl_FragCoord,cutout_factors.x,z); #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;uniform lowp float u_opacity_multiplier; #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:cc(`#include "_prelude_fog.fragment.glsl" #include "_prelude_lighting.glsl" #include "_prelude_shadow.fragment.glsl" #include "_prelude_feature_cutout.fragment.glsl" in highp vec2 v_pos;uniform float u_emissive_strength;uniform lowp float u_opacity_multiplier; #ifdef ELEVATED_ROADS in highp float v_road_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 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 float z=0.0; #ifdef ELEVATED_ROADS z=v_road_z_offset; #endif out_color=apply_feature_cutout(out_color,gl_FragCoord,cutout_factors.x,z); #endif glFragColor=out_color*(alpha*opacity*u_opacity_multiplier); #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 uniform mat4 u_matrix;uniform vec2 u_world;uniform lowp float u_opacity_multiplier;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;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 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:cc(`#include "_prelude_fog.fragment.glsl" #include "_prelude_lighting.glsl" #include "_prelude_shadow.fragment.glsl" #include "_prelude_feature_cutout.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;uniform lowp float u_opacity_multiplier; #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 #ifdef ELEVATED_ROADS in highp float v_road_z_offset; #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=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);out_color.rgb*=mix(u_ground_shadow_factor,vec3(1.0),light); #endif #endif #ifdef FEATURE_CUTOUT float z=0.0; #ifdef ELEVATED_ROADS z=v_road_z_offset; #endif out_color=apply_feature_cutout(out_color,gl_FragCoord,cutout_factors.x,z); #endif #ifdef FOG out_color=fog_dither(fog_apply_premultiplied(out_color,v_fog_pos)); #endif glFragColor=out_color*(alpha*opacity*u_opacity_multiplier); #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 lowp float u_opacity_multiplier;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;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;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);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:cc(`#include "_prelude_fog.fragment.glsl" #include "_prelude_lighting.glsl" #include "_prelude_shadow.fragment.glsl" #include "_prelude_feature_cutout.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;uniform lowp float u_opacity_multiplier; #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 float z=0.0; #ifdef ELEVATED_ROADS z=v_road_z_offset; #endif out_color=apply_feature_cutout(out_color,gl_FragCoord,cutout_factors.x,z); #endif #ifdef FOG out_color=fog_dither(fog_apply_premultiplied(out_color,v_fog_pos)); #endif glFragColor=out_color*(opacity*u_opacity_multiplier); #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 lowp float u_opacity_multiplier;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:cc(`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:cc("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:cc(`#include "_prelude_fog.fragment.glsl" #include "_prelude_shadow.fragment.glsl" #include "_prelude_lighting.glsl" #include "_prelude_indicator_cutout.fragment.glsl" #include "_prelude_feature_cutout.fragment.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=viewport_dither_index(gl_FragCoord.xy);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=viewport_dither_index(gl_FragCoord.xy);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,0.0); #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; #ifndef LIGHTING_3D_MODE uniform vec3 u_lightcolor;uniform lowp vec3 u_lightpos;uniform lowp float u_lightintensity; #endif 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 }`),fillExtrusionPattern:cc(`#include "_prelude_fog.fragment.glsl" #include "_prelude_lighting.glsl" #include "_prelude_indicator_cutout.fragment.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; #ifndef LIGHTING_3D_MODE uniform vec3 u_lightcolor;uniform lowp vec3 u_lightpos;uniform lowp float u_lightintensity; #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 #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 }`),hillshadePrepare:cc(`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:cc(`#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 VIEWPORT_ORIGIN_TOP_LEFT v_pos.y=1.0-v_pos.y; #endif #ifdef FOG v_fog_pos=fog_position(vec2(a_pos)); #endif }`),line:cc(`#include "_prelude_fog.fragment.glsl" #include "_prelude_lighting.glsl" #include "_prelude_shadow.fragment.glsl" #include "_prelude_indicator_cutout.fragment.glsl" #include "_prelude_feature_cutout.fragment.glsl" uniform lowp float u_device_pixel_ratio;uniform highp float u_width_scale;uniform float u_alpha_discard_threshold;uniform lowp float u_opacity_multiplier;uniform bool u_clip_to_tile_borders;in vec4 v_width2_dilute;in vec2 v_normal;in float v_gamma_scale;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;uniform highp float u_floor_width_scale;in highp vec2 v_tex; #endif #ifdef DEBUG_ELEVATION_ID in vec3 v_elevation_id_col; #endif #if defined(RENDER_LINE_GRADIENT) || defined(RENDER_LINE_BORDER_GRADIENT) || defined(RENDER_LINE_TRIM_OFFSET) in highp vec3 v_uv; #endif #ifdef RENDER_LINE_GRADIENT uniform sampler2D u_gradient_image; #endif #ifdef RENDER_LINE_BORDER_GRADIENT uniform sampler2D u_border_gradient_image; #endif #ifdef RENDER_LINE_TRIM_OFFSET 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; #endif #ifdef INDICATOR_CUTOUT in highp float v_z_offset; #endif #ifdef RENDER_SHADOWS uniform bool u_emissive_in_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;float ANTIALIASING=1.0/u_device_pixel_ratio/2.0; #ifdef RENDER_LINE_BORDER #ifndef VARIABLE_LINE_WIDTH ANTIALIASING*=8.0; #endif #endif #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);float pxStep;float delta; #ifdef RENDER_LINE_BORDER #ifndef VARIABLE_LINE_WIDTH pxStep=fwidth(dist);float out_edge=v_width2_dilute.x-dist;float in_edge=dist-(v_width2_dilute.y-2.0*ANTIALIASING);delta=v_width2_dilute.y > 0.0 ? min(in_edge,out_edge) : out_edge;float edge=ANTIALIASING;alpha=delta > 0.0 ? smoothstep(edge-pxStep,u_width_scale*blur+edge+pxStep,delta) : 0.0; #endif #endif #ifdef RENDER_LINE_DASH highp float dash_w=float(dash.w);highp float dash_len=float(dash.z)+dash_w/65535.0;float sdfgamma=ANTIALIASING/float(dash_len);float scaled_floorwidth=(floorwidth*u_floor_width_scale);float periods_per_pixel=fwidth(v_tex.x);float dash_coverage=float(dash.y >> 4u)/4095.0;float fade=linearstep(0.25,0.5,periods_per_pixel);float gamma=max(sdfgamma/scaled_floorwidth,0.5*periods_per_pixel);if (fade >=1.0) {alpha*=dash_coverage;} else if (periods_per_pixel < 0.1) {float sdfdist=texture(u_dash_image,v_tex).r;alpha*=linearstep(0.5-gamma,0.5+gamma,sdfdist);} else {float span=min(periods_per_pixel,1.0);float tap_offset=span*0.25;float sdf0=texture(u_dash_image,vec2(v_tex.x-tap_offset,v_tex.y)).r;float sdf1=texture(u_dash_image,vec2(v_tex.x+tap_offset,v_tex.y)).r;alpha*=mix(0.5*( linearstep(0.5-gamma,0.5+gamma,sdf0)+linearstep(0.5-gamma,0.5+gamma,sdf1) ),dash_coverage,fade);} #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 edge2=border_width*u_width_scale+ANTIALIASING;float alpha2=smoothstep(edge2-pxStep,edge2+pxStep,delta);if (alpha2 < 1.) { #ifdef RENDER_LINE_BORDER_GRADIENT vec4 border_gradient_color=texture(u_border_gradient_image,v_uv.xy);out_color=mix(border_gradient_color*trim_alpha,out_color,alpha2); #else if (border_color.a==0.0) { #ifndef RENDER_LINE_GRADIENT 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-alpha2));} else {out_color.rgb*=(0.6+0.4*alpha2);} #else out_color.rgb*=(0.6+0.4*alpha2); #endif } else {out_color=mix(border_color*trim_alpha,out_color,alpha2);} #endif 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*u_opacity_multiplier); #ifdef INDICATOR_CUTOUT out_color=applyCutout(out_color,v_z_offset); #endif #ifdef FEATURE_CUTOUT float z=0.0; #ifdef ELEVATED_ROADS z=v_road_z_offset; #endif out_color=apply_feature_cutout(out_color,gl_FragCoord,cutout_factors.x,z); #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) || defined(VARIABLE_LINE_EMISSIVE_STRENGTH) in vec4 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_BORDER_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_road_view_depth_bias;uniform highp vec4 u_road_clip_to_view; #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 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 highp float u_floor_width_scale;uniform vec2 u_texsize;uniform float u_tile_units_to_pixels;out highp vec2 v_tex; #endif #if defined(RENDER_LINE_GRADIENT) || defined(RENDER_LINE_BORDER_GRADIENT) || defined(RENDER_LINE_TRIM_OFFSET) out highp vec3 v_uv; #endif #if defined(RENDER_LINE_GRADIENT) || defined(RENDER_LINE_BORDER_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 #ifdef VARIABLE_LINE_EMISSIVE_STRENGTH emissive_strength=a_z_offset_width.w; #endif 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_BORDER_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; #ifdef RENDER_LINE_BORDER #ifndef VARIABLE_LINE_WIDTH ANTIALIASING*=8.0; #endif #endif 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;float symmetric_outset=0.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);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*=apply;}offset=border_width > 0.0 ? (left_width+right_width)*u_width_scale : 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;symmetric_outset=zero_right_width ? u_width_scale*left_width : halfwidth;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 ? ANTIALIASING : 0.0);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; #ifdef VARIABLE_LINE_WIDTH #ifndef ELEVATED if (u_road_view_depth_bias > 0.0) {highp float z_in=gl_Position.z/gl_Position.w*0.5+0.5;highp float a=u_road_clip_to_view.x;highp float b=u_road_clip_to_view.y;highp float c=u_road_clip_to_view.z;highp float d=u_road_clip_to_view.w;highp float view=(a*z_in+b)/(c*z_in+d);highp float view_new=view+u_road_view_depth_bias;highp float z_new=(view_new*d-b)/(a-view_new*c);z_new=clamp(z_new,0.0,1.0);gl_Position.z=(z_new*2.0-1.0)*gl_Position.w;} #endif #endif #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_BORDER_GRADIENT) || defined(RENDER_LINE_TRIM_OFFSET) highp float a_uv_x=a_packed[0];float a_split_index=a_packed[1]; #if defined(RENDER_LINE_GRADIENT) || defined(RENDER_LINE_BORDER_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);highp float dash_w=float(dash.w);highp float totalLength=float(dash.z)+dash_w/65535.0;float scale=totalLength==0.0 ? 0.0 : u_tile_units_to_pixels/totalLength;float dash_half_height=float(dash.y & 15u);v_tex=vec2(a_linesofar*scale/(floorwidth*u_floor_width_scale),(-normal.y*dash_half_height+dashf.x+0.5)/u_texsize.y); #endif v_width2_dilute=vec4(outset,inset,dilute_scale,dilute_border_scale); #ifdef VARIABLE_LINE_WIDTH v_width2_dilute.x=symmetric_outset; #endif #ifdef FOG v_fog_pos=fog_position(pos); #endif #ifdef INDICATOR_CUTOUT v_z_offset=a_z_offset; #endif }`),linePattern:cc(`#include "_prelude_fog.fragment.glsl" #include "_prelude_lighting.glsl" #include "_prelude_shadow.fragment.glsl" #include "_prelude_indicator_cutout.fragment.glsl" uniform highp float u_device_pixel_ratio;uniform highp float u_width_scale;uniform highp float u_alpha_discard_threshold;uniform lowp float u_opacity_multiplier;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*u_opacity_multiplier);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 vec4 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:cc(`#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;uniform highp float u_color_ramp_size; #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; #ifdef RASTER_COLOR_SCALE_LOG float N=u_color_ramp_size;float vNorm=max((value.x-0.5/N)*N/(N-1.0),0.0);vNorm=log(vNorm*(10.0-1.0)+1.0)/log(10.0);value.x=0.5/N+vNorm*(N-1.0)/N; #endif #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:cc(`#include "_prelude_lighting.glsl" #include "_prelude_shadow.fragment.glsl" #include "_prelude_indicator_cutout.fragment.glsl" #include "_prelude_feature_cutout.fragment.glsl" #define SDF_PX 8.0 #define SDF 1.0 #define ICON 0.0 uniform sampler2D u_texture; #ifdef RENDER_TEXT_AND_SYMBOL uniform sampler2D u_texture_icon; #endif uniform highp float u_gamma_scale;uniform lowp float u_device_pixel_ratio;uniform bool u_is_text;uniform bool u_is_sdf;uniform lowp float u_scale_factor;uniform lowp float u_opacity_multiplier; #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 in lowp float v_opacity;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; #ifdef LIGHTING_3D_MODE in lowp float v_emissive_strength; #endif void main() {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;if (u_is_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;}lowp float emissive_strength=0.0; #ifdef LIGHTING_3D_MODE emissive_strength=v_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*u_opacity_multiplier;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 if (u_is_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 }out_color*=opacity*fade_opacity*u_opacity_multiplier; #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,0.0); #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; #ifdef RENDER_SHADOWS uniform mat4 u_inv_matrix; #endif 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; #ifdef PROJECTION_GLOBE_VIEW uniform vec3 u_up_vector; #endif #ifdef RENDER_TEXT_AND_SYMBOL uniform vec2 u_texsize_icon; #endif 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 #ifndef MAX_UBO_SIZE_VEC4 #define MAX_UBO_SIZE_VEC4 1024u #endif #define SPP_HEADER_SIZE_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;};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;uniform highp float u_spp_zoom_fraction;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;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; #ifdef LIGHTING_3D_MODE out lowp float v_emissive_strength; #endif float zoomFactor(float zm,float zM) {if (zm==zM) return u_spp_zoom_fraction-zm >=0.0 ? 1.0 : 0.0;return clamp((u_spp_zoom_fraction-zm)/(zM-zm),0.0,1.0);}vec4 readColor(uint base,bool isDataDriven,uint offsetVec4,uint dzr,vec2 headerZoom,vec4 fallbackValue) {if (!isDataDriven) return fallbackValue;vec4 value=u_spp_properties.properties[base+offsetVec4];vec2 blockZoom=u_spp_properties.properties[base+offsetVec4+dzr].xy;vec2 zr=mix(headerZoom,blockZoom,float(dzr));return unpack_mix_color(value,zoomFactor(zr.x,zr.y));}uint uvec4At(uvec4 v,uint index) {return (index==0u) ? v.x : (index==1u) ? v.y : (index==2u) ? v.z : v.w;}float readScalar(uint base,bool isDataDriven,uint offsetVec4,float fallbackValue) {if (!isDataDriven) return fallbackValue;vec4 slot=u_spp_properties.properties[base+offsetVec4];return unpack_mix_vec2(slot.xy,zoomFactor(slot.z,slot.w));}vec2 readTranslate(uint base,bool isDataDriven,uint offsetVec4,uint dzr) {if (!isDataDriven) return vec2(0.0);vec4 value=u_spp_properties.properties[base+offsetVec4];vec2 blockZoom=u_spp_properties.properties[base+offsetVec4+dzr].xy;float t=zoomFactor(blockZoom.x,blockZoom.y)*float(dzr);return mix(value.xy,value.zw,t);}SymbolPaintProperties readSymbolPaintProperties() {uint dataDrivenMask=u_spp_header.header[0][0];uint dzrMask =u_spp_header.header[0][1];uint blockSizeVec4 =u_spp_header.header[0][2];uint fillColorDzr=dzrMask & 1u;uint haloColorDzr=(dzrMask >> 1u) & 1u;vec2 fillColorHeaderZoom=uintBitsToFloat(u_spp_header.header[3].xy);vec2 haloColorHeaderZoom=uintBitsToFloat(u_spp_header.header[3].zw);uint featureIndex=uint(a_feature_index);uvec4 indexSlot=u_spp_index.block_indices[featureIndex/4u];uint base=uvec4At(indexSlot,featureIndex % 4u)*blockSizeVec4;SymbolPaintProperties props;props.fill_np_color =readColor(base,(dataDrivenMask & (1u << 0u)) !=0u,u_spp_header.header[0][3],fillColorDzr,fillColorHeaderZoom,u_spp_fill_np_color);props.halo_np_color =readColor(base,(dataDrivenMask & (1u << 1u)) !=0u,u_spp_header.header[1][0],haloColorDzr,haloColorHeaderZoom,u_spp_halo_np_color);props.opacity =readScalar(base,(dataDrivenMask & (1u << 2u)) !=0u,u_spp_header.header[1][1],u_spp_opacity);props.halo_width =readScalar(base,(dataDrivenMask & (1u << 3u)) !=0u,u_spp_header.header[1][2],u_spp_halo_width);props.halo_blur =readScalar(base,(dataDrivenMask & (1u << 4u)) !=0u,u_spp_header.header[1][3],u_spp_halo_blur);props.emissive_strength=readScalar(base,(dataDrivenMask & (1u << 5u)) !=0u,u_spp_header.header[2][0],u_spp_emissive_strength);props.occlusion_opacity=readScalar(base,(dataDrivenMask & (1u << 6u)) !=0u,u_spp_header.header[2][1],u_spp_occlusion_opacity);props.z_offset =readScalar(base,(dataDrivenMask & (1u << 7u)) !=0u,u_spp_header.header[2][2],u_spp_z_offset);uint translateDzr=(dzrMask >> 8u) & 1u;props.translate =readTranslate(base,(dataDrivenMask & (1u << 8u)) !=0u,u_spp_header.header[2][3],translateDzr);return props;}vec2 unpack_opacity(uint packedOpacity) {return vec2(float(packedOpacity/2u)/127.0,float(packedOpacity & 1u));}void main() {SymbolPaintProperties paint_properties=readSymbolPaintProperties();lowp float opacity=paint_properties.opacity;v_opacity=opacity;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; #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;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);{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;}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:cc(`#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; #ifdef VIEWPORT_ORIGIN_TOP_LEFT v_pos0.y=1.0-v_pos0.y; #endif 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:cc("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:cc(`#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 }`,ynt),skyboxGradient:cc(`#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 }`,ynt),skyboxCapture:cc(` 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; #ifndef VIEWPORT_ORIGIN_TOP_LEFT v_position.y*=-1.0; #endif 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:cc(`#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;FLIP_VIEWPORT_UV_Y(uv);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; #ifndef GLOBE_POLES uniform mat4 u_merc_matrix; #endif uniform float u_zoom_transition;uniform vec2 u_merc_center; #ifndef GLOBE_POLES uniform mat3 u_grid_matrix; #endif 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; #ifdef VIEWPORT_ORIGIN_TOP_LEFT v_pos0.y=1.0-v_pos0.y; #endif 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:cc(`#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);}`),stars:cc(`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:cc("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 T7(w,f){const b=w.split(` `);for(let S of b){if(S=S.trimStart(),S[0]!=="#"||!S.includes("if")||S.startsWith("#endif"))continue;const T=S.match(XXt);if(T)for(const D of T)QXt.has(D)||f.add(D)}}function Pnt(w){return new Set(["uint","int","uvec2","ivec2","uvec3","ivec3","uvec4","ivec4"]).has(w)}function cc(w,f){const b=new Set,S=[],T=[];w=w.replace(knt,(F,q)=>(T.push(q),"")),f=f.replace(knt,(F,q)=>(S.push(q),""));let D=new Set(ane);T7(w,D),T7(f,D);for(const F of[...S,...T])ine[F]||(ine[F]=new Set,T7(Cnt[F],ine[F])),D=new Set([...D,...ine[F]]);return{fragmentSource:w=w.replace(Snt,(F,q,K,X,ce)=>(b.add(ce),q==="define"?` #ifndef HAS_UNIFORM_u_${ce} ${Pnt(X)?"flat ":""}in ${K} ${X} ${ce}; #else uniform ${K} ${X} u_${ce}; #endif `:q==="initialize"?` #ifdef HAS_UNIFORM_u_${ce} ${K} ${X} ${ce} = u_${ce}; #endif `:q==="define-attribute"?` #ifdef HAS_ATTRIBUTE_a_${ce} in ${K} ${X} ${ce}; #endif `:q==="initialize-attribute"?"":void 0)),vertexSource:f=f.replace(Snt,(F,q,K,X,ce)=>{const pe=`MATERIAL_ATTRIBUTE_OFFSET_${ce}`,xe=X==="float"?"vec2":X,Ne=`GET_ATTRIBUTE_${xe}(a_${ce}, materialInfo, ${pe})`,Me=ce.includes("color")?"color":xe;return q==="define-attribute-vertex-shader-only"?` #ifdef HAS_ATTRIBUTE_a_${ce} in ${K} ${X} a_${ce}; #endif `:b.has(ce)?q==="define"?` #ifndef HAS_UNIFORM_u_${ce} uniform lowp float u_${ce}_t; #if !defined(${pe}) in ${K} ${xe} a_${ce}; #endif ${Pnt(X)?"flat ":""}out ${K} ${X} ${ce}; #else uniform ${K} ${X} u_${ce}; #endif `:q==="initialize"?Me==="vec4"||Me==="uvec4"?` #ifndef HAS_UNIFORM_u_${ce} ${ce} = a_${ce}; #else ${K} ${X} ${ce} = u_${ce}; #endif `:` #if !defined(HAS_UNIFORM_u_${ce}) #ifdef ${pe} ${ce} = unpack_mix_${Me}(${Ne}, u_${ce}_t); #else ${ce} = unpack_mix_${Me}(a_${ce}, u_${ce}_t); #endif #else ${K} ${X} ${ce} = u_${ce}; #endif `:q==="define-attribute"?` #ifdef HAS_ATTRIBUTE_a_${ce} in ${K} ${X} a_${ce}; out ${K} ${X} ${ce}; #endif `:q==="initialize-attribute"?` #ifdef HAS_ATTRIBUTE_a_${ce} ${ce} = a_${ce}; #endif `:void 0:q==="define"?` #ifndef HAS_UNIFORM_u_${ce} uniform lowp float u_${ce}_t; #if !defined(${pe}) in ${K} ${xe} a_${ce}; #endif #else uniform ${K} ${X} u_${ce}; #endif `:q==="define-instanced"?Me==="mat4"?` #ifdef INSTANCED_ARRAYS in vec4 a_${ce}0; in vec4 a_${ce}1; in vec4 a_${ce}2; in vec4 a_${ce}3; #else uniform ${K} ${X} u_${ce}; #endif `:` #ifdef INSTANCED_ARRAYS in ${K} ${xe} a_${ce}; #else uniform ${K} ${X} u_${ce}; #endif `:q==="initialize-attribute-custom"?` #ifdef HAS_ATTRIBUTE_a_${ce} ${K} ${X} ${ce} = a_${ce}; #endif `:Me==="vec4"||Me==="uvec4"?` #ifndef HAS_UNIFORM_u_${ce} #ifdef ${pe} ${K} ${X} ${ce} = ${Ne}; #else ${K} ${X} ${ce} = a_${ce}; #endif #else ${K} ${X} ${ce} = u_${ce}; #endif `:` #ifndef HAS_UNIFORM_u_${ce} #ifdef ${pe} ${K} ${X} ${ce} = unpack_mix_${Me}(${Ne}, u_${ce}_t); #else ${K} ${X} ${ce} = unpack_mix_${Me}(a_${ce}, u_${ce}_t); #endif #else ${K} ${X} ${ce} = u_${ce}; #endif `}),usedDefines:D,vertexIncludes:S,fragmentIncludes:T}}var sQt={model:cc(`#include "_prelude_fog.fragment.glsl" #include "_prelude_shadow.fragment.glsl" #include "_prelude_lighting.glsl" #include "_prelude_indicator_cutout.fragment.glsl" #include "_prelude_feature_cutout.fragment.glsl" uniform float u_opacity; #ifdef DITHERED_DISCARD uniform float u_dithered_discard_threshold; #endif #ifndef LIGHTING_3D_MODE uniform vec3 u_lightcolor;uniform vec3 u_lightpos;uniform float u_lightintensity; #endif 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 FEATURE_CUTOUT_VERTEX in highp float v_cutout_factor; #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;vec3 lightColor; #ifdef LIGHTING_3D_MODE lightDir=u_lighting_directional_dir;lightDir.xy=-lightDir.xy;lightColor=u_lighting_directional_color; #else lightDir=u_lightpos;lightColor=u_lightcolor; #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_VERTEX apply_feature_cutout_dither(gl_FragCoord,v_cutout_factor); #else #ifdef FEATURE_CUTOUT finalColor=apply_feature_cutout(finalColor,gl_FragCoord,get_cutout_factors(gl_FragCoord).x,0.0); #endif #endif glFragColor=finalColor; #ifdef OVERDRAW_INSPECTOR glFragColor=vec4(1.0); #endif HANDLE_WIREFRAME_DEBUG;}`,`#include "_prelude_fog.vertex.glsl" #include "_prelude_shadow.vertex.glsl" #include "_prelude_feature_cutout.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 FEATURE_CUTOUT_VERTEX out highp float v_cutout_factor; #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 #ifdef FEATURE_CUTOUT_VERTEX v_cutout_factor=1.0; #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; #ifdef FEATURE_CUTOUT_VERTEX highp vec4 ground_pos=vec4(pos_a.xy,0.0,1.0);highp vec4 cutout_clip_pos=mix(u_matrix*ground_pos,AWAY,hidden);highp vec3 cutout_ndc=cutout_clip_pos.xyz/cutout_clip_pos.w;vec2 uv=cutout_ndc.xy*0.5+0.5;highp float fragDepthNDC=cutout_ndc.z*0.5+0.5; #ifdef FLIP_Y fragDepthNDC=cutout_ndc.z; #endif highp float cutoutFactor=get_cutout_factors_vert(uv).x;highp float cutoutDepthNDC=sample_cutout_depth(u_cutout_depth_image,uv);highp float groundThreshold=0.001;highp float groundLimit=clamp((fragDepthNDC+groundThreshold-cutoutDepthNDC)/groundThreshold+0.5,0.0,1.0);v_cutout_factor=mix(1.0-cutoutFactor,1.0,groundLimit); #endif #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:cc("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 }`),fillExtrusionDepth:cc("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);}`),fillExtrusionGroundEffect:cc(`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 }`),groundShadow:cc(`#include "_prelude_shadow.fragment.glsl" #include "_prelude_indicator_cutout.fragment.glsl" #include "_prelude_feature_cutout.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 vec2 uv=gl_FragCoord.xy*u_inv_viewport_size.xy; #ifdef FLIP_Y uv.y=1.0-uv.y; #endif highp float cutoutFactor=get_cutout_factors(gl_FragCoord).y;highp float cutoutDepthNDC=sample_cutout_depth_bilinear(u_cutout_depth_image,uv);highp float fragDepthNDC=gl_FragCoord.z/u_feature_cutout_params.w;highp float groundThreshold=-0.001;highp float groundLimit=clamp((fragDepthNDC+groundThreshold-cutoutDepthNDC)/groundThreshold+0.5,0.0,1.0);cutoutFactor=mix(0.0,cutoutFactor,groundLimit);shadow=mix(shadow,vec3(1.0),cutoutFactor); #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 }`)};const nQt=(w,f)=>({u_matrix:w,u_ground_shadow_factor:f});function Int(w,f,b=0){const S=Math.pow(2,f.tileID.overscaledZ),T=f.tileSize*Math.pow(2,w.transform.tileZoom)/S,D=T*(f.tileID.canonical.x+f.tileID.wrap*S),F=T*f.tileID.canonical.y;return{u_image:0,u_texsize:f.imageAtlasTexture?f.imageAtlasTexture.size:[0,0],u_tile_units_to_pixels:1/IH(f,1,w.transform.tileZoom),u_pixel_coord_upper:[D>>16,F>>16],u_pixel_coord_lower:[65535&D,65535&F],u_pattern_transition:b}}const one={terrain:0,flat:1},rQt=y(),Lnt=[0,0,0],Rnt=(w,f,b,S,T,D,F,q,K,X,ce,pe,xe,Ne,Me,ze,Ve,Je,lt=[0,0,1],ht=!1)=>{let ct=Lnt,xt=0,kt=Lnt;if(!ht){const Lt=f.style.light,Zt=Lt.properties.get("position");if(ct=[Zt.x,Zt.y,Zt.z],Lt.properties.get("anchor")==="viewport"){const Cs=p();x(Cs,-f.transform.angle),ut(ct,ct,Cs)}const Qt=Lt.properties.get("color").toPremultipliedRenderColor(null);xt=Lt.properties.get("intensity"),kt=[Qt.r,Qt.g,Qt.b]}const es=f.transform,Ct={u_matrix:w,u_lightpos:ct,u_lightintensity:xt,u_lightcolor:kt,u_vertical_gradient:+b,u_opacity:S,u_tile_id:[0,0,0],u_zoom_transition:0,u_inv_rot_matrix:rQt,u_merc_center:[0,0],u_up_dir:[0,0,0],u_height_lift:0,u_height_type:one[X],u_base_type:one[ce],u_ao:T,u_edge_radius:D,u_width_scale:F,u_flood_light_color:Me,u_vertical_scale:ze,u_flood_light_intensity:Ve,u_ground_shadow_factor:Je,u_front_cutoff_params:lt};return es.projection.name==="globe"&&(Ct.u_tile_id=[q.canonical.x,q.canonical.y,1<{let en=Lt;hn.groundRadiusBuffer!=null&&(en=Lt.concat("HAS_ATTRIBUTE_a_flood_light_ground_radius"));const wn=hn.programConfigurations.get(S.id),Nn=f.isTileAffectedByFog(sn),Pn=f.getOrCreateProgram("fillExtrusionGroundEffect",{config:wn,defines:en,overrideFog:Nn}),jn=((Kn,Dr,sr,yr,Ra,$a,si,La,Oi,bi)=>({u_matrix:Kn,u_opacity:Dr,u_ao_pass:sr?1:0,u_meter_to_tile:yr,u_ao:Ra,u_flood_light_intensity:$a,u_flood_light_color:si,u_attenuation:La,u_edge_radius:Oi,u_fb:0,u_fb_size:bi,u_dynamic_offset:1}))(ws,pe,X,qs,[xe,Ne*qs],Me,ze,Ve,Ct>=17?0:Cs*qs,ht?ht.size[0]:0),Wn=[];Je&&Wn.push(hn.hiddenByLandmarkVertexBuffer),hn.groundRadiusBuffer!=null&&Wn.push(hn.groundRadiusBuffer),f.uploadCommonUniforms(xt,Pn,sn.toUnwrapped(),null,Fs),Pn.draw(f,xt.gl.TRIANGLES,D,F,q,K,jn,S.id,hn.vertexBuffer,hn.indexBuffer,Rn,S.paint,Ct,wn,Wn)};for(const sn of T){const hn=b.getTile(sn),Rn=hn.getBucket(S);if(!Rn||Rn.projection.name!==es.projection.name||!Rn.groundEffect||Rn.groundEffect&&!Rn.groundEffect.hasData())continue;const ws=Rn.groundEffect,qs=1/Rn.tileToMeter;{const en=f.translatePosMatrix(sn.projMatrix,hn,Zt,Qt),wn=ws.getDefaultSegment();on(sn,ws,wn,en,qs)}if(lt)for(let en=0;en<4;en++){const wn=det[en](sn),Nn=b.getTile(wn);if(!Nn)continue;const Pn=Nn.getBucket(S);if(!Pn||Pn.projection.name!==es.projection.name||!Pn.groundEffect||Pn.groundEffect&&!Pn.groundEffect.hasData())continue;const jn=Pn.groundEffect;let Wn,Kn;en===0?(Wn=[-8192,0,0],Kn=1):en===1?(Wn=[br,0,0],Kn=0):en===2?(Wn=[0,-8192,0],Kn=3):(Wn=[0,br,0],Kn=2);const Dr=jn.regionSegments[Kn];Dr&&(I(Dnt,sn.projMatrix,Wn),on(sn,jn,Dr,f.translatePosMatrix(Dnt,hn,Zt,Qt),qs))}}}const aQt={model:w=>({u_matrix:new sg(w),u_lighting_matrix:new sg(w),u_normal_matrix:new sg(w),u_node_matrix:new sg(w),u_lightpos:new $f(w),u_lightintensity:new Zi(w),u_lightcolor:new $f(w),u_camera_pos:new $f(w),u_opacity:new Zi(w),u_baseColorFactor:new P4(w),u_emissiveFactor:new P4(w),u_metallicFactor:new Zi(w),u_roughnessFactor:new Zi(w),u_baseTextureIsAlpha:new im(w),u_alphaMask:new im(w),u_alphaCutoff:new Zi(w),u_baseColorTexture:new im(w),u_metallicRoughnessTexture:new im(w),u_normalTexture:new im(w),u_occlusionTexture:new im(w),u_emissionTexture:new im(w),u_lutTexture:new im(w),u_color_mix:new P4(w),u_aoIntensity:new Zi(w),u_emissive_strength:new Zi(w),u_occlusionTextureTransform:new P4(w),u_dithered_discard_threshold:new Zi(w)}),modelDepth:w=>({u_matrix:new sg(w),u_instance:new sg(w),u_node_matrix:new sg(w)}),groundShadow:w=>({u_matrix:new sg(w),u_ground_shadow_factor:new $f(w)}),fillExtrusionDepth:w=>({u_matrix:new sg(w),u_edge_radius:new Zi(w),u_width_scale:new Zi(w),u_vertical_scale:new Zi(w),u_height_type:new im(w),u_base_type:new im(w)}),fillExtrusionGroundEffect:w=>({u_matrix:new sg(w),u_opacity:new Zi(w),u_ao_pass:new Zi(w),u_meter_to_tile:new Zi(w),u_ao:new zg(w),u_flood_light_intensity:new Zi(w),u_flood_light_color:new $f(w),u_attenuation:new Zi(w),u_edge_radius:new Zi(w),u_fb:new im(w),u_fb_size:new Zi(w),u_dynamic_offset:new Zi(w)})};function Fnt(w){const f=w.properties.get("direction"),b=Gm(f.x,f.y,f.z);b[2]=Jr(b[2],0,75);const S=zh([b[0],b[1],b[2]]);return _e(S.x,S.y,S.z)}function znt(w,f,b){const S=f.properties.get("color-use-theme")==="none",T=f.properties.get("color"),D=f.properties.get("intensity"),F=f.properties.get("direction"),q=[F.x,F.y,F.z],K=b.properties.get("color-use-theme")==="none",X=b.properties.get("color"),ce=b.properties.get("intensity"),pe=Math.max(Oe([0,0,1],q),0),xe=[0,0,0];Be(xe,X.toPremultipliedRenderColor(K?null:w.getLut(f.scope)).toArray01Linear().slice(0,3),ce);const Ne=[0,0,0];return Be(Ne,T.toPremultipliedRenderColor(S?null:w.getLut(b.scope)).toArray01Linear().slice(0,3),pe*D),Af([xe[0]>0?xe[0]/(xe[0]+Ne[0]):0,xe[1]>0?xe[1]/(xe[1]+Ne[1]):0,xe[2]>0?xe[2]/(xe[2]+Ne[2]):0])}const lne=[];function Bnt(w){return lne[w]=lne[w]||new Float64Array(16)}const cne=[],iQt=new Float32Array(16);class oQt{constructor(f,b){this.aabb=f,this.lastCascade=b}}class lQt{add(f,b){const S=this.receivers[f.key];S!==void 0?(S.aabb.min[0]=Math.min(S.aabb.min[0],b.min[0]),S.aabb.min[1]=Math.min(S.aabb.min[1],b.min[1]),S.aabb.min[2]=Math.min(S.aabb.min[2],b.min[2]),S.aabb.max[0]=Math.max(S.aabb.max[0],b.max[0]),S.aabb.max[1]=Math.max(S.aabb.max[1],b.max[1]),S.aabb.max[2]=Math.max(S.aabb.max[2],b.max[2])):this.receivers[f.key]=new oQt(b,null)}clear(){this.receivers={}}get(f){return this.receivers[f.key]}computeRequiredCascades(f,b,S){const T=jd.fromPoints(f.points);let D=0;for(const F in this.receivers){const q=this.receivers[F];if(!q||!T.intersectsAabb(q.aabb))continue;q.aabb.min=T.closestPoint(q.aabb.min),q.aabb.max=T.closestPoint(q.aabb.max);const K=q.aabb.getCorners();for(let X=0;X1||xe[1]<-1||xe[1]>1){ce=!1;break}}if(q.lastCascade=X,D=Math.max(D,X),ce)break}}return D+1}}function dne(w,f,b){const S=Ge([],wt([],b,f),wt([],w,f)),T=fe(S);return T===0?[0,0,1,0]:(Be(S,S,1/T),[S[0],S[1],S[2],-Oe(S,f)])}function cQt(w,f,b,S,T,D){const F=w.zoom,q=w.scale,K=w.worldSize,X=1/K,ce=w.aspect,pe=Math.sqrt(1+ce*ce)*Math.tan(.5*w.fovX),xe=pe*pe,Ne=S-b,Me=S+b;let ze,Ve;xe>Ne/Me?(ze=S,Ve=S*pe):(ze=.5*Me*(1+xe),Ve=.5*Math.sqrt(Ne*Ne+2*(S*S+b*b)*xe+Me*Me*xe*xe));const Je=w.projection.pixelsPerMeter(w.center.lat,K),lt=[0,0,-ze*X];tt(lt,lt,w._camera.getCameraToWorldMercator());let ht=Ve*X;const ct=function(qs){return qs[0]/=q,qs[1]/=q,qs[2]=de(qs[2],w._center.lat),qs},xt=w._edgeInsets;if(!(xt.left===0&&xt.top===0&&xt.right===0&&xt.bottom===0||xt.left===xt.right&&xt.top===xt.bottom)){const qs=w._camera.getWorldToCamera(w.worldSize,w.projection.zAxisUnit==="meters"?Je:1),en=w._camera.getCameraToClipPerspective(w._fov,w.width/w.height,b,S);en[8]=2*-w.centerOffset.x/w.width,en[9]=2*w.centerOffset.y/w.height;const wn=new Float64Array(16);Q(wn,en,qs);const Nn=new Float64Array(16);A(Nn,wn);const Pn=D4.fromInvProjectionMatrix(Nn,K,F,!0);for(const jn of Pn.points){const Wn=ct(jn);ht=Math.max(ht,Ft(Se([],lt,Wn)))}}ht*=T/(T-1);const kt=Math.acos(f[2]),es=Math.atan2(-f[0],-f[1]),Ct=new Jse;Ct.position=lt,Ct.setPitchBearing(kt,es);const Lt=Ct.getWorldToCamera(K,Je),Zt=ht*K,Qt=Math.min(w._mercatorZfromZoom(17)*K*-2,-2*Zt),Cs=Ct.getCameraToClipOrthographic(-Zt,Zt,-Zt,Zt,Qt,(Zt+D*Je)/f[2]),Fs=new Float64Array(16);M(Fs,Cs,Lt);const on=.5*T,sn=[0,0,0];tt(sn,_e(Math.floor(1e6*lt[0])/1e6*K,Math.floor(1e6*lt[1])/1e6*K,0),Fs),Be(sn,sn,on);const hn=[Math.floor(sn[0]),Math.floor(sn[1]),Math.floor(sn[2])],Rn=[0,0,0];wt(Rn,sn,hn),Be(Rn,Rn,-1/on);const ws=new Float64Array(16);return j(ws),I(ws,ws,Rn),M(Fs,ws,Fs),[Fs,Zt]}class q4 extends Fd{constructor(f,b,S,T){super(),this.id=f,this.type="model",this.models=[],this._options=b,this._modelsInfo=new Map,this._abortController=null}cancelModelRequests(){this._abortController&&(this._abortController.abort(),this._abortController=null)}async loadGLTFFromURI(f,b){return gtt((await this.map._requestManager.transformRequest(f,Ro.Model,b)).url,b)}async loadModel(f,b,S){try{const T=await this.loadGLTFFromURI(b.uri,S);if(S.aborted)return;const D=this._modelsInfo.get(f);if(!D)return;const F=_6e(T),q=D.modelSpec,K=new _tt(f,q.uri,q.position,q.orientation,F);q4.applyModelSpecification(K,q),K.computeBoundsAndApplyParent(),this.models.push(K),D.model=K}catch(T){if(S.aborted)return;this.fire(new vu(new Error(`Could not load model ${f} from ${b.uri}`,{cause:T})))}}async load(){this._abortController||(this._abortController=new AbortController);const f=this._abortController.signal,b=[];for(const S in this._options.models){const T=this._options.models[S],D=this._modelsInfo.get(S);if(D&&D.model){D.modelSpec=T;const F=D.model;F.position=T.position!=null?new W(T.position[0],T.position[1]):new W(0,0),F.orientation=T.orientation??[0,0,0],q4.applyModelSpecification(F,T),F.computeBoundsAndApplyParent(),this.models.push(F)}else D?D.modelSpec=T:(this._modelsInfo.set(S,{modelSpec:T,model:null}),b.push(this.loadModel(S,T,f)))}b.length!==0?(await Promise.allSettled(b),f.aborted||this.fire(new Km("data",{dataType:"source",sourceDataType:"metadata"}))):this.loaded()&&this.fire(new Km("data",{dataType:"source",sourceDataType:"metadata"}))}static arrayFromColorSpecification(f){const b=f;if(b===void 0)return;if(Array.isArray(b))return[b[0],b[1],b[2]];const S=Mi.parse(b);return S?[S.r,S.g,S.b]:void 0}static applyModelSpecification(f,b){if(b.nodeOverrides&&q4.convertNodeOverrides(f,b.nodeOverrides),b.materialOverrides&&q4.convertMaterialOverrides(f,b.materialOverrides),b.nodeOverrideNames&&(f.nodeOverrideNames=[...b.nodeOverrideNames]),b.materialOverrideNames&&(f.materialOverrideNames=[...b.materialOverrideNames]),b.featureProperties&&(f.featureProperties=b.featureProperties),b.lightOverrides){const S=b.lightOverrides,T=q4.arrayFromColorSpecification(S["light-ambient-color"]),D=q4.arrayFromColorSpecification(S["light-directional-color"]);f.lightOverrides={ambientIntensity:S["light-ambient-intensity"],ambientColor:T,directionalIntensity:S["light-directional-intensity"],directionalColor:D}}else f.lightOverrides=void 0}static convertNodeOverrides(f,b){if(Array.isArray(b)&&b.every(S=>typeof S=="string")){f.nodeOverrideNames=[];for(const S of b)f.nodeOverrideNames.push(S)}else Object.entries(b).forEach(([S,T])=>{const D={orientation:[0,0,0],minZoom:void 0,maxZoom:void 0};if(Object.hasOwn(T,"orientation")){const F=T.orientation;F&&(D.orientation=F)}Object.hasOwn(T,"minzoom")&&(D.minZoom=T.minzoom),Object.hasOwn(T,"maxzoom")&&(D.maxZoom=T.maxzoom),f.nodeOverrides.set(S,D)})}static convertMaterialOverrides(f,b){if(Array.isArray(b)&&b.every(S=>typeof S=="string")){f.materialOverrideNames=[];for(const S of b)f.materialOverrideNames.push(S)}else Object.entries(b).forEach(([S,T])=>{const D=q4.arrayFromColorSpecification(T["model-color"]),F={color:D!==void 0?new Mi(D[0],D[1],D[2]):new Mi(1,1,1),colorMix:0,emissionStrength:0,opacity:1},q=T["model-color-mix-intensity"];q!==void 0&&(F.colorMix=q);const K=T["model-emissive-strength"];K!==void 0&&(F.emissionStrength=K);const X=T["model-opacity"];X!==void 0&&(F.opacity=X),f.materialOverrides.set(S,F)})}onAdd(f){this.map=f,this.load()}hasTransition(){return!1}loaded(){if(this._modelsInfo.size===0)return!0;for(const f of this._modelsInfo.values())if(f.model==null)return!1;return!0}getModels(){return this.models}loadTile(f,b){}serialize(){return this._options}setProperty(f,b){return!1}reload(){this.cancelModelRequests();const f=r7(this.id,this.scope);this.map.style.clearSource(f),this.models=[],this._modelsInfo.clear(),this.load()}onRemove(f){this.cancelModelRequests()}setModels(f){this.models=[];const b=new Map;for(const S in f){const T=f[S],D=this._modelsInfo.get(S);D&&D.modelSpec.uri===T.uri&&b.set(S,D)}if(this._modelsInfo.size!==b.size){this.cancelModelRequests();for(const[S,T]of b)T.model||b.delete(S)}this._modelsInfo=b,this._options.models=f,this.load()}}function $nt(w,f,b){try{f=function(T){if(!T.variants)return T;if(!Array.isArray(T.variants))throw new Error("variants must be an array");for(const D of T.variants){if(D==null||typeof D!="object"||D.constructor!==Object)throw new Error("variant must be an object");if(!Array.isArray(D.capabilities))throw new Error("capabilities must be an array");if(D.capabilities.length===1&&D.capabilities[0]==="meshopt")return Object.assign(T,D)}return T}(f)}catch(T){return new Error("Failed to process TileJSON variants",{cause:T})}const S=Ss({...f,...w},["tilejson","tiles","minzoom","maxzoom","attribution","mapbox_logo","bounds","extra_bounds","scheme","tileSize","encoding","vector_layers","raster_layers","worldview_options","worldview_default","worldview"]);return w.url&&f.tiles&&w.tiles&&(S.tiles=f.tiles),S.tiles=b.canonicalizeTileset(S,w.url),S}function Unt(w,f,b,S,T){const D=function(q,K){if(q)return T(q);if(K){w.url&&K.tiles&&w.tiles&&delete w.tiles;const X=$nt(w,K,f);if(X instanceof Error)return T(X);T(null,X)}},F=function(q,K,X){if(!q)return null;if(!K&&!X)return q;X=X||q.worldview_default;const ce=Object.values(q.language||{});if(ce.length===0)return null;const pe=Object.values(q.worldview||{});if(pe.length===0)return null;const xe=ce.every(Me=>Me===K),Ne=pe.every(Me=>Me===X);return xe&&Ne?q:K in(q.language_options||{})||X in(q.worldview_options||{})?null:q.language_options&&q.worldview_options?q:null}(w.data,b,S);if(F)return qt.frame(()=>D(null,F));if(w.url){const q=new AbortController;return(async()=>{const K=await f.transformRequest(f.normalizeSourceURL(w.url,null,b,S),Ro.Source,q.signal),{data:X}=await gr(K,q.signal);D(null,X)})().catch(K=>{q.signal.aborted||D(K)}),{cancel:()=>q.abort()}}return qt.frame(()=>{const{data:q,...K}=w;D(null,K)})}function qnt(w,f){const b=Math.pow(2,f.z),S=Math.floor(Qm(w.getWest())*b),T=Math.floor(mp(w.getNorth())*b),D=Math.ceil(Qm(w.getEast())*b),F=Math.ceil(mp(w.getSouth())*b);return f.x>=S&&f.x=T&&f.ythis.maxzoom||f.z{X&&(X.useNormalOffset=!0,ce||(X.enabled=!0))},xe=f.getSource();if(w.renderPass==="light-beam"&&xe.type!=="batched-model")return;if(xe.type==="vector"||xe.type==="geojson")return function(ct,xt,kt,es,Ct){const Lt=ct.transform,Zt=Lt.projection.name==="globe",Qt=Lt.getFreeCameraOptions().position;if(!ct.modelManager)return;const Cs=ct.modelManager;kt.modelManager=Cs;const Fs=ct.shadowRenderer;if(!Object.hasOwn(kt._unevaluatedLayout._values,"model-id"))return;const on=kt._unevaluatedLayout._values["model-id"],sn={...kt.layout.get("model-id").parameters},hn=ct.style.order.indexOf(kt.fqid),Rn=kt.paint.get("model-opacity").constantOr(1);for(const ws of es){const qs=xt.getTile(ws).getBucket(kt);if(!qs||qs.projection.name!==Lt.projection.name)continue;const en=qs.getModelUris();if(en&&!qs.modelsRequested&&(Cs.addModelsFromBucket(en,Ct),qs.modelsRequested=!0),Zt)sn.zoom=ws.overscaledZ;else{const sr=GXt(ws,Lt);sn.zoom=sr}const wn=on.possiblyEvaluate(sn);if(HXt(ct,qs,ws),sS.shadowUniformsInitialized=!1,sS.useSingleShadowCascade=!!Fs&&Fs.getMaxCascadeForTile(ws.toUnwrapped())===0,ct.renderPass==="shadow"&&Fs){if(ct.currentShadowCascade===1&&qs.isInsideFirstShadowMapFrustum)continue;const sr=Lt.calculatePosMatrix(ws.toUnwrapped(),Lt.worldSize);if(sS.tileMatrix.set(sr),sS.shadowTileMatrix.set(Fs.calculateShadowPassMatrixFromMatrix(sr)),sS.aabb.min=[0,0,0],sS.aabb.max[0]=sS.aabb.max[1]=br,sS.aabb.max[2]=0,KXt(qs,sS,ct,kt.scope))continue}const Nn=1<0&&ct.style.isLayerClipped(kt,xt.getSource())&&qs.updateReplacement(ws,ct.replacementSource,hn,kt.scope)&&(qs.uploaded=!1,qs.upload(ct.context));let jn=0;const Wn=new Array,Kn=new Array,Dr=new Array;for(let sr in qs.instancesPerModel){const yr=qs.instancesPerModel[sr];yr.features.length>0&&!Zt&&(sr=wn.evaluate(yr.features[0].feature,{}));const Ra=Cs.getModel(sr,Ct);if(Ra||Cs.hasURLBeenRequested(sr)||qs.modelUris.includes(sr)||(qs.modelUris.push(sr),qs.modelsRequested=!1),Ra&&Ra.uploaded)if(Zt){const $a=Be([],[Qt.x,Qt.y,Qt.z],ct.transform.worldSize);ke($a,$a);for(let si=0;si0&&Bl.elevationUpdate(yr.terrain,La,bi,$a.source),Bl.needsReEvaluation(yr,Oi,$a)&&Bl.evaluate($a))}})(ct,xt,kt,es),function(){const yr=new Map;let Ra,$a,si;Kn?(Ra=es.length-1,$a=-1,si=-1):(Ra=0,$a=es.length,si=1);const La=te(),Oi=new Kt(0,0);for(let bi=Ra;bi!==$a;bi+=si){const Bl=es[bi],cl=xt.getTile(Bl).getBucket(kt);if(!cl||!cl.uploaded)continue;let Ll=!1;Qt&&(Ll=Qt.getMaxCascadeForTile(Bl.toUnwrapped())===0);const dc=Lt.calculatePosMatrix(Bl.toUnwrapped(),Lt.worldSize),cf=!!(4&cl.modelTraits);M(K6e,hn,dc),M(Y6e,Lt.expandedFarZProjMatrix,dc),A(sne,K6e),C(sne,sne);const $1=!wn&&Qt&&Qt.enabled?Qt.computeCascadeTileMatrices(dc):null;!wn&&Kn&&(A(MA,dc),tt(La,Fs,MA),Oi.x=La[0],Oi.y=La[1]);const Wh=[];cl.setFilter(kt.filter);for(const xl of cl.getNodesInfo()){if(xl.hiddenByReplacement||!xl.node.meshes)continue;const Jd=xl.node;let om=0;ct.terrain&&Jd.elevation&&(om=Jd.elevation*ct.terrain.exaggeration());const df=()=>{const eu=xl.aabb,Ov=en.min,Fv=en.max;return Ov[0]=eu.min[0],Ov[1]=eu.min[1],Ov[2]=eu.min[2]+om,Fv[0]=eu.max[0],Fv[1]=eu.max[1],Fv[2]=eu.max[2]+om,tt(Ov,Ov,dc),tt(Fv,Fv,dc),en},Xi=df(),ng=xl.evaluatedScale;if(ng[0]<=1&&ng[1]<=1&&ng[2]<=1&&Xi.intersects(jn)===0)continue;if(!wn){const eu=Xi.min,Ov=Xi.max;rne[0]=.5*(eu[0]+Ov[0]),rne[1]=.5*(eu[1]+Ov[1]),rne[2]=.5*(eu[2]+Ov[2]);const Fv=Ye(Fs,rne)*sn,$g=ct._debugParams.lodSwitchDistance,nS=$g>=0;if(nS&&$g>=9999)xl.targetLod=0;else{let qb;if(nS)qb=$g;else{const qy=(Ov[2]-eu[2])*sn*ng[2],V4=Math.max(Ov[0]-eu[0],Ov[1]-eu[1])*sn*Math.max(ng[0],ng[1]);let rS;rS=qy>=30?1:V4>=80?.5:Math.max(qy,V4)>=20?.25:0,qb=2e3+3e3*rS}WXt(xl,Fv,Math.min(ct.frameTimeDelta,1e3/30),qb,ct._debugParams.lodSwitchFadeDuration)}}if(!wn&&Kn){const eu=.16666666666666666;xl.cameraCollisionOpacity=Fs[0]>Xi.min[0]&&Fs[0]Xi.min[1]&&Fs[1]!Kn||xl.opacity===1&&Jd.opacity===1?xl.depthJd.depth?-1:1);for(const xl of Wh){const Jd=xl.nodeInfo,om=Jd.node;let df=null;if(ct._debugParams.show3DModelFootprints&&om.footprint){const _x=om.id||om.name||"footprint";if(!yr.has(_x)){const Dv=FH(new Float64Array(16),Y6e,xl.tileTranslation,xl.nodeInfo.evaluatedScale);yr.set(_x,{node:om,mvp:Dv})}}const Xi=xl.nodeInfo.evaluatedScale;FH(tS,K6e,xl.tileTranslation,Xi),nne[0]=1/Xi[0],nne[1]=-1/Xi[1],nne[2]=1/Xi[2],P(MA,sne,nne),M(tS,tS,om.globalMatrix);const ng=cf?0:Jd.evaluatedRMEA[0][2],rg=Jd.targetLod,$y=om.lodMeshes&&om.lodMeshes.length>0,Uy=$y&&rg>0&&rg<1;if(wn&&$y&&Math.round(rg)===1)continue;const Lv=!wn&&Zt?unt(dnt,xl.nodeModelMatrix,ct.transform):null,Rv=wn&&Qt?Qt.calculateShadowPassMatrixFromMatrix(xl.nodeModelMatrix):null,bx=Uy?2:1,Bg=$y&&Math.round(rg)===1;for(let _x=0;_x=OH||ow>=OH}const aS=$g.material;let _o;aS.occlusionTexture&&aS.occlusionTexture.offsetScale&&(_o=aS.occlusionTexture.offsetScale,qy.defines.push("OCCLUSION_TEXTURE_TRANSFORM")),Uy&&qy.defines.push("DITHERED_DISCARD");const lm=ct.getOrCreateProgram("model",qy);if(!wn&&Qt&&Qt.enabled)if(df!==rS){for(let ny=0;ny<$1.length;ny++)FH(Z6e[ny]=Z6e[ny]||new Float64Array(16),$1[ny],xl.tileTranslation,xl.nodeInfo.evaluatedScale);Qt.setupShadowsFromCascadeMatrices(Z6e,lm,rS),df=rS}else lm.setShadowUniformValues(Ct,Qt.getShadowUniformValues());ct.uploadCommonUniforms(Ct,lm,null,Lv);const hu=aS.pbrMetallicRoughness;hu.metallicFactor=.9,hu.roughnessFactor=.5;const uf=z6e(qb,tS,MA,om.globalMatrix,ct,xl.opacity,hu.baseColorFactor,aS.emissiveFactor,hu.metallicFactor,hu.roughnessFactor,aS,ng,kt,UXt,_o,void 0,void 0,Ov,lm.fixedDefines.includes("LIGHTING_3D_MODE"));!nS&&(Jd.hasTranslucentParts||xl.opacity<1)&&lm.draw(ct,Ct.gl.TRIANGLES,ws,rw.disabled,bu.disabled,vx.backCCW,uf,kt.id,$g.vertexBuffer,$g.indexBuffer,$g.segments,kt.paint,ct.transform.zoom,void 0,V4),lm.draw(ct,Ct.gl.TRIANGLES,nS?qs:ws,rw.disabled,nS||xl.opacity<1||Jd.hasTranslucentParts?bu.alphaBlended:bu.unblended,vx.backCCW,uf,kt.id,$g.vertexBuffer,$g.indexBuffer,$g.segments,kt.paint,ct.transform.zoom,void 0,V4)}}}}if(ct._debugParams.show3DModelFootprints&&yr.size>0){const bi=Array.from(yr.keys()).sort();for(const Bl of bi){const{node:cl,mvp:Ll}=yr.get(Bl);mnt(ct,0,cl,Ll)}}}()}(w,f,b,S),void pe();if(xe.type!=="model")return;const Ne=xe.getModels(),Me=[],ze=w.transform.getFreeCameraOptions().position,Ve=Be([],[ze.x,ze.y,ze.z],w.transform.worldSize);ke(Ve,Ve);const Je=[],lt=[];let ht=0;for(const ct of Ne){const xt=f.getFeatureState("",ct.id),kt={type:"Unknown",id:ct.id,properties:ct.featureProperties},es=b.paint.get("model-rotation").evaluate(kt,xt),Ct=b.paint.get("model-scale").evaluate(kt,xt),Lt=b.paint.get("model-translation").evaluate(kt,xt),Zt=b.paint.get("model-opacity").evaluate(kt,xt);qXt(b,ct.id,xt,ct.featureProperties,ct.nodeOverrideNames,ct.nodeOverrides),VXt(b,ct.id,xt,ct.featureProperties,ct.materialOverrideNames,ct.materialOverrides),ct.nodeOverrides.size>0&&ct.computeBoundsAndApplyParent(),ct.computeModelMatrix(w,es,Ct,Lt,q,F,!1);const Qt=U([],Ve),Cs=G([],[1,1,1/Ke(ct.position.lat,w.transform.zoom)]);Me.push({zScaleMatrix:Cs,negCameraPosMatrix:Qt});for(const Fs of ct.nodes)J6e(w,Fs,ct.matrix,w.transform.expandedFarZProjMatrix,ht,Je,lt,ct.materialOverrides,Zt,void 0,ct.lightOverrides);ht++}if(Je.sort((ct,xt)=>xt.depth-ct.depth),w.renderPass!=="shadow"){if(w._debugParams.show3DModelFootprints){const ct=w.transform.projMatrix,xt=new Map,kt=(Ct,Lt)=>{if(Ct.footprint){const Zt=Ct.id||Ct.name||"footprint";if(!xt.has(Zt)){const Qt=M([],ct,Lt);xt.set(Zt,{node:Ct,mvp:Qt})}}};for(const Ct of lt)kt(Ct.node,Ct.modelMatrix);for(const Ct of Je)kt(Ct.node,Ct.modelMatrix);const es=Array.from(xt.keys()).sort();for(const Ct of es){const{node:Lt,mvp:Zt}=xt.get(Ct);mnt(w,0,Lt,Zt)}}fnt(w,b,Je,lt,Me),pe()}else{for(const ct of lt)zH(ct.mesh,ct.nodeModelMatrix,w,b);for(const ct of Je)zH(ct.mesh,ct.nodeModelMatrix,w,b);pe()}},prepare:function(w,f,b){const S=f.getSource();if(!S.loaded())return;if(S.type==="vector"||S.type==="geojson")return void(b.modelManager&&b.modelManager.upload(b,hnt(b,w)));if(S.type==="batched-model"||S.type!=="model")return;const T=S.getModels();for(const D of T)D.upload(b.context)},shaders:sQt,programUniforms:aQt,ShadowRenderer:class{constructor(w){this.painter=w,this._enabled=!1,this._drawShadowAfterLayer=-1,this._numCascadesToRender=0,this._cascades=[],this._groundShadowTiles=[],this._receivers=new lQt,this._depthMode=new yx(w.context.gl.LEQUAL,yx.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 w of this._cascades)w.texture.destroy(),w.framebuffer.destroy();this._cascades=[]}updateShadowParameters(w,f){const b=this.painter;if(this._enabled=!1,this._drawShadowAfterLayer=-1,this._receivers.clear(),!f||!f.properties)return;const S=f.properties.get("shadow-intensity"),T=f.properties.get("shadow-draw-before-layer");if(!f.shadowsEnabled()||S<=0)return;let D=-1,F=0;for(const Ve of b.style.order){const Je=b.style._mergedLayers[Ve];Je.hasShadowPass()&&!Je.isHidden(w.zoom)&&(D=F),!T||T!==Ve&&T!==Je.slot||(this._drawShadowAfterLayer=F>0?F-1:0),F+=1}if(this._enabled=D>=0,!this.enabled)return;this._drawShadowAfterLayer<0&&(this._drawShadowAfterLayer=D);const q=b.context,K=this._shadowParameters.shadowMapResolution,X=this._shadowParameters.shadowMapResolution;if(this._cascades.length===0||this._shadowParameters.shadowMapResolution!==this._cascades[0].texture.size[0]){this._cascades=[];for(let Ve=0;Velt.dem).forEach(lt=>{const ht=lt.dem.tree;Je[0]=Math.min(Je[0],ht.minimums[0]),Je[1]=Math.max(Je[1],ht.maximums[0])}),Je[0]!==1e4&&(ce=(Je[1]-Je[0])*Ve.exaggeration())}const pe=1.5*w.cameraToCenterDistance,xe=3*pe,Ne=new Float64Array(16);for(let Ve=0;Ve=0)return{};const T=function(q,K,X){const ce=X/(1<0&&(he(T[1],T[1],[S[0]*D,0,0]),he(T[2],T[2],[S[0]*D,0,0])),S[1]<0?(he(T[0],T[0],[0,S[1]*D,0]),he(T[1],T[1],[0,S[1]*D,0])):S[1]>0&&(he(T[2],T[2],[0,S[1]*D,0]),he(T[3],T[3],[0,S[1]*D,0]));const F={};return F.vertices=T,F.planes=[dne(T[1],T[0],T[4]),dne(T[2],T[1],T[5]),dne(T[3],T[2],T[6]),dne(T[0],T[3],T[7])],F}addShadowReceiver(w,f,b){this._receivers.add(w,jd.fromTileIdAndHeight(w,f,b))}getMaxCascadeForTile(w){const f=this._receivers.get(w);return f&&f.lastCascade?f.lastCascade:0}},drawGroundEffect:Ont,queryModelLayerRendered:function(w,f,b,S){const T=b.getSource();if(!T||T.type!=="model")return{};const D=T,F={};F[w.id]=[];const q=F[w.id];let K=0;for(const X of D.models){const ce=b.getFeatureState(w.sourceLayer,X.id),pe={type:"Unknown",id:X.id,properties:X.featureProperties},xe=w.paint.get("model-rotation").evaluate(pe,ce),Ne=w.paint.get("model-scale").evaluate(pe,ce),Me=w.paint.get("model-translation").evaluate(pe,ce),ze=w.paint.get("model-elevation-reference");let Ve=[];Ise(Ve,X,S,X.position,xe,Ne,Me,ze==="ground",ze==="ground",!1),S.projection.name==="globe"&&(Ve=Pse(Ve,S));const Je=M([],S.projMatrix,Ve),lt=p6e(f.isPointQuery()?f.screenBounds:f.screenGeometry,S,Je,X.aabb);if(lt!=null){const ht=new J6(void 0,0,0,0,X.id);ht.layer=w.layer,ht.properties=structuredClone(X.featureProperties),ht.properties.layer=w.id,ht.properties.uri=X.uri,ht.properties.orientation=X.orientation,ht.sourceLayer=w.sourceLayer,ht.geometry={type:"Point",coordinates:[X.position.lng,X.position.lat]},ht.state=ce,ht.source=w.source,q.push({featureIndex:K,feature:ht,intersectionZ:lt})}++K}return F},queryModelLayerIntersectsFeature:function(w,f,b,S,T,D){if(!w.modelManager)return!1;const F=w.modelManager,q=f.tile.getBucket(w);if(!(q&&q instanceof D6e))return!1;for(const K in q.instancesPerModel){const X=q.instancesPerModel[K],ce=b.id!==void 0?b.id:b.properties&&Object.hasOwn(b.properties,"id")?b.properties.id:void 0;if(Object.hasOwn(X.idToFeaturesIndex,ce)){const pe=X.features[X.idToFeaturesIndex[ce]],xe=F.getModel(K,D||w.scope);if(!xe)return!1;let Ne=[];const Me=new W(0,0),ze=q.canonical;let Ve=Number.MAX_VALUE;for(let Je=0;Jethis.map.style.clearSource(w))}cancelTileJSONRequest(){this._tileJSONRequest&&(this._tileJSONRequest.cancel(),this._tileJSONRequest=null)}load(w){this._loaded=!1,this.fire(new Km("dataloading",{dataType:"source"}));const f=Array.isArray(this.map._language)?this.map._language.join():this.map._language,b=this.map.getWorldview();this._tileJSONRequest=Unt(this._options,this.map._requestManager,f,b,(S,T)=>{this._tileJSONRequest=null,this._loaded=!0,S?(f&&console.warn(`Ensure that your requested language string is a valid BCP-47 code or list of codes. Found: ${f}`),b&&b.length!==2&&console.warn(`Requested worldview strings must be a valid ISO alpha-2 code. Found: ${b}`),this.fire(new vu(S))):T&&(Object.assign(this,T),T.bounds&&(this.tileBounds=new une(T.bounds,this.minzoom,this.maxzoom)),yd(T.tiles,this.map._requestManager._customAccessToken),this.fire(new Km("data",{dataType:"source",sourceDataType:"metadata"})),this.fire(new Km("data",{dataType:"source",sourceDataType:"content"}))),w&&w(S)})}hasTransition(){return!1}hasTile(w){return!this.tileBounds||this.tileBounds.contains(w.canonical)}loaded(){return this._loaded}async loadTile(w,f){const b=this.map._requestManager.normalizeTileURL(w.tileID.canonical.url(this.tiles,this.scheme)),S=!w.actor||w.state==="expired";if(S)w.actor=this.dispatcher.getActor();else{if(w.state==="loading")return void(w.reloadCallback=f);if(w.buckets){const q=Object.values(w.buckets);for(const K of q)K.dirty=!0;return void(w.state="loaded")}}const T=S?"loadTile":"reloadTile",D=new AbortController;w.request=D;const F=(q,K)=>(delete w.request,w.aborted?f(null):q&&!jo(q)?f(q):(this.map._refreshExpiredTiles&&K&&w.setExpiryData(Bh(K.headers)),w.loadModelData(K,this.map.painter),w.state="loaded",f(null),void(w.reloadCallback&&(this.loadTile(w,w.reloadCallback),w.reloadCallback=null))));try{const q=await this.map._requestManager.transformRequest(b,Ro.Tile,D.signal);if(D.signal.aborted)return f(null);const K={request:q,data:void 0,uid:w.uid,tileID:w.tileID,tileZoom:w.tileZoom,zoom:w.tileID.overscaledZ,tileSize:this.tileSize*w.tileID.overscaleFactor(),type:this.type,source:this.id,scope:this.scope,showCollisionBoxes:this.map.showCollisionBoxes,renderSourceType:w.renderSourceType,brightness:this.map.style&&this.map.style.getBrightness()||0,pixelRatio:qt.devicePixelRatio,promoteId:this.promoteId};w.request=w.actor.sendCancelable(T,K,{},F)}catch(q){if(D.signal.aborted)return f(null);f(q)}}abortTile(w){w.request&&(w.request.abort(),delete w.request),w.actor&&w.actor.notify("abortTile",{uid:w.uid,type:this.type,source:this.id,scope:this.scope})}serialize(){return{...this._options}}},loadModel:async function(w,f,b){const S=await gtt(w),T=new _tt(f,b,void 0,void 0,_6e(S));return T.computeBoundsAndApplyParent(),T}};class Vnt{constructor(f,b){this.tileID=f,this.x=f.canonical.x,this.y=f.canonical.y,this.z=f.canonical.z,this.grid=new xx(br,br,512),this.featureIndexArray=new of,this.promoteId=b,this.is3DTile=!1,this.serializedLayersCache=new Map}insert(f,b,S,T,D,F=0,q=0){const K=this.featureIndexArray.length;this.featureIndexArray.emplaceBack(S,T,D,F);const X=this.grid;for(let ce=0;ce=0&&xe[3]>=0&&X.insert(K,xe[0],xe[1],xe[2],xe[3])}}loadVTLayers(){if(!this.vtLayers){this.vtLayers=new bMe(new cse(this.rawTileData)).layers,this.sourceLayerCoder=new Kst(this.vtLayers?Object.keys(this.vtLayers).sort():["_geojsonTileLayer"]),this.vtFeatures={};for(const f in this.vtLayers)this.vtFeatures[f]=[]}return this.vtLayers}query(f,b){const{tilespaceGeometry:S,transform:T,tileTransform:D,pixelPosMatrix:F,availableImages:q,worldview:K}=b;this.loadVTLayers(),this.serializedLayersCache.clear();const X=b.queryRadius?b.queryRadius:0,ce=S.bufferedTilespaceBounds,pe=this.grid.queryKeys(ce.min.x,ce.min.y,ce.max.x,ce.max.y,(ze,Ve,Je,lt)=>SMe(S.bufferedTilespaceGeometry,ze-X,Ve-X,Je+X,lt+X));pe.sort(dQt);let xe=null;T.elevation&&pe.length>0&&(xe=S7.create(T.elevation,this.tileID));const Ne={};let Me;for(let ze=0;ze(lt||(lt=Ms(ht,this.tileID.canonical,D)),ct.queryIntersectsFeature(S,ht,xt,lt,this.z,T,F,xe,kt,b.scope)))}return Ne}loadMatchingFeature(f,b,S,T,D,F){const{featureIndex:q,bucketIndex:K,sourceLayerIndex:X,layoutVertexArrayOffset:ce}=b,pe=this.bucketLayerIDs[K],xe=S.layers,Ne=Object.keys(xe);if(Ne.length&&!Hl(Ne,pe))return;const Me=S.sourceCache,ze=this.sourceLayerCoder.decode(X),Ve=this.vtLayers[ze].feature(q),Je=this.getId(Ve,ze);for(let lt=0;lt`${q.key}: ${q.message}`).join(", ");return void oi(`Failed to create expression for promoteId: ${F}`)}this.promoteIdExpression=D.value}S=this.promoteIdExpression.evaluate({zoom:0},f)}else S=f.properties[T];typeof S=="boolean"&&(S=Number(S))}return S}}function Hnt(w,f,b,S,T){return ja(w,(D,F)=>{const q=f instanceof Ch?f.get(F):null;return q&&q.evaluate?q.evaluate(b,S,void 0,T):q})}function dQt(w,f){return f-w}async function Gnt(){return Promise.resolve()}Vr(Vnt,"FeatureIndex",{omit:["rawTileData","sourceLayerCoder"]});const uQt={circle:class extends zy{constructor(w,f,b,S){super(w,{layout:$tt||($tt=new $d({"circle-sort-key":new hr(Us.layout_circle["circle-sort-key"]),"circle-elevation-reference":new Bn(Us.layout_circle["circle-elevation-reference"]),visibility:new Bn(Us.layout_circle.visibility)})),paint:Utt||(Utt=new $d({"circle-radius":new hr(Us.paint_circle["circle-radius"]),"circle-color":new hr(Us.paint_circle["circle-color"]),"circle-blur":new hr(Us.paint_circle["circle-blur"]),"circle-opacity":new hr(Us.paint_circle["circle-opacity"]),"circle-translate":new Bn(Us.paint_circle["circle-translate"]),"circle-translate-anchor":new Bn(Us.paint_circle["circle-translate-anchor"]),"circle-pitch-scale":new Bn(Us.paint_circle["circle-pitch-scale"]),"circle-pitch-alignment":new Bn(Us.paint_circle["circle-pitch-alignment"]),"circle-stroke-width":new hr(Us.paint_circle["circle-stroke-width"]),"circle-stroke-color":new hr(Us.paint_circle["circle-stroke-color"]),"circle-stroke-opacity":new hr(Us.paint_circle["circle-stroke-opacity"]),"circle-emissive-strength":new Bn(Us.paint_circle["circle-emissive-strength"]),"circle-color-use-theme":new hr({type:"string",default:"default","property-type":"data-driven"}),"circle-stroke-color-use-theme":new hr({type:"string",default:"default","property-type":"data-driven"})}))},f,b,S)}createBucket(w){return new Wte(w)}queryRadius(w){const f=w;return k7("circle-radius",this,f)+k7("circle-stroke-width",this,f)+Wse(this.paint.get("circle-translate"))}queryIntersectsFeature(w,f,b,S,T,D,F,q){const K=Wtt(this.paint.get("circle-translate"),this.paint.get("circle-translate-anchor"),D.angle,w.pixelToTileUnitsFactor),X=this.paint.get("circle-radius").evaluate(f,b)+this.paint.get("circle-stroke-width").evaluate(f,b);return Ytt(w,S,D,F,q,this.paint.get("circle-pitch-alignment")==="map",this.paint.get("circle-pitch-scale")==="map",K,X)}getProgramIds(){return["circle"]}getDefaultProgramParams(w,f,b){const S=Ktt(this);return{config:new q6(this,{zoom:f,lut:b}),defines:S,overrideFog:!1}}is3D(w){return!w&&!!this.layout&&this.layout.get("circle-elevation-reference")!=="none"}hasElevation(){return this.layout&&this.layout.get("circle-elevation-reference")!=="none"}mayUse(w){return w==="HD"&&i7(this,"circle-elevation-reference",f=>f==="hd-road-markup")}prepare(){return this.mayUse("HD")?Gse():Promise.resolve()}},heatmap:class extends zy{createBucket(w){return new Xtt(w)}constructor(w,f,b,S){super(w,{layout:Qtt||(Qtt=new $d({visibility:new Bn(Us.layout_heatmap.visibility)})),paint:Jtt||(Jtt=new $d({"heatmap-radius":new hr(Us.paint_heatmap["heatmap-radius"]),"heatmap-weight":new hr(Us.paint_heatmap["heatmap-weight"]),"heatmap-intensity":new Bn(Us.paint_heatmap["heatmap-intensity"]),"heatmap-color":new Aj(Us.paint_heatmap["heatmap-color"]),"heatmap-opacity":new Bn(Us.paint_heatmap["heatmap-opacity"]),"heatmap-color-use-theme":new hr({type:"string",default:"default","property-type":"data-driven"})}))},f,b,S),this._updateColorRamp()}_handleSpecialPaintPropertyUpdate(w){w==="heatmap-color"&&this._updateColorRamp()}_updateColorRamp(){this.colorRamp=MH({expression:this._transitionablePaint._values["heatmap-color"].value.expression,evaluationKey:"heatmapDensity",image:this.colorRamp}),this.colorRampTexture=null}resize(){this.heatmapFbo&&(this.heatmapFbo.destroy(),this.heatmapFbo=null)}_clear(){this.heatmapFbo&&(this.heatmapFbo.destroy(),this.heatmapFbo=null),this.colorRampTexture&&(this.colorRampTexture.destroy(),this.colorRampTexture=null)}queryRadius(w){return k7("heatmap-radius",this,w)}queryIntersectsFeature(w,f,b,S,T,D,F,q){const K=this.paint.get("heatmap-radius").evaluate(f,b);return Ytt(w,S,D,F,q,!0,!0,new Kt(0,0),K)}hasOffscreenPass(){return this.paint.get("heatmap-opacity")!==0&&this.visibility!=="none"}getProgramIds(){return["heatmap","heatmapTexture"]}getDefaultProgramParams(w,f,b){return w==="heatmap"?{config:new q6(this,{zoom:f,lut:b}),overrideFog:!1}:{}}},hillshade:class extends zy{constructor(w,f,b,S){super(w,{layout:est||(est=new $d({visibility:new Bn(Us.layout_hillshade.visibility)})),paint:tst||(tst=new $d({"hillshade-illumination-direction":new Bn(Us.paint_hillshade["hillshade-illumination-direction"]),"hillshade-illumination-anchor":new Bn(Us.paint_hillshade["hillshade-illumination-anchor"]),"hillshade-exaggeration":new Bn(Us.paint_hillshade["hillshade-exaggeration"]),"hillshade-shadow-color":new Bn(Us.paint_hillshade["hillshade-shadow-color"]),"hillshade-highlight-color":new Bn(Us.paint_hillshade["hillshade-highlight-color"]),"hillshade-accent-color":new Bn(Us.paint_hillshade["hillshade-accent-color"]),"hillshade-emissive-strength":new Bn(Us.paint_hillshade["hillshade-emissive-strength"]),"hillshade-shadow-color-use-theme":new hr({type:"string",default:"default","property-type":"data-driven"}),"hillshade-highlight-color-use-theme":new hr({type:"string",default:"default","property-type":"data-driven"}),"hillshade-accent-color-use-theme":new hr({type:"string",default:"default","property-type":"data-driven"})}))},f,b,S)}shouldRedrape(){return this.hasOffscreenPass()&&this.paint.get("hillshade-illumination-anchor")==="viewport"}hasOffscreenPass(){return this.paint.get("hillshade-exaggeration")!==0&&this.visibility!=="none"}getProgramIds(){return["hillshade","hillshadePrepare"]}getDefaultProgramParams(w,f,b){return{overrideFog:!1}}},fill:class extends zy{constructor(w,f,b,S){super(w,{layout:sst||(sst=new $d({"fill-sort-key":new hr(Us.layout_fill["fill-sort-key"]),visibility:new Bn(Us.layout_fill.visibility),"fill-elevation-reference":new Bn(Us.layout_fill["fill-elevation-reference"]),"fill-construct-bridge-guard-rail":new hr(Us.layout_fill["fill-construct-bridge-guard-rail"])})),paint:nst||(nst=new $d({"fill-antialias":new Bn(Us.paint_fill["fill-antialias"]),"fill-opacity":new hr(Us.paint_fill["fill-opacity"]),"fill-color":new hr(Us.paint_fill["fill-color"]),"fill-outline-color":new hr(Us.paint_fill["fill-outline-color"]),"fill-translate":new Bn(Us.paint_fill["fill-translate"]),"fill-translate-anchor":new Bn(Us.paint_fill["fill-translate-anchor"]),"fill-pattern":new hr(Us.paint_fill["fill-pattern"]),"fill-pattern-cross-fade":new Bn(Us.paint_fill["fill-pattern-cross-fade"]),"fill-emissive-strength":new Bn(Us.paint_fill["fill-emissive-strength"]),"fill-z-offset":new hr(Us.paint_fill["fill-z-offset"]),"fill-bridge-guard-rail-color":new hr(Us.paint_fill["fill-bridge-guard-rail-color"]),"fill-tunnel-structure-color":new hr(Us.paint_fill["fill-tunnel-structure-color"]),"fill-color-use-theme":new hr({type:"string",default:"default","property-type":"data-driven"}),"fill-outline-color-use-theme":new hr({type:"string",default:"default","property-type":"data-driven"}),"fill-bridge-guard-rail-color-use-theme":new hr({type:"string",default:"default","property-type":"data-driven"}),"fill-tunnel-structure-color-use-theme":new hr({type:"string",default:"default","property-type":"data-driven"})}))},f,b,S)}getProgramIds(){const w=this.paint.get("fill-pattern"),f=w&&w.constantOr(1),b=[f?"fillPattern":"fill"];return this.paint.get("fill-antialias")&&b.push(f&&!this.getPaintProperty("fill-outline-color")?"fillOutlinePattern":"fillOutline"),b}getDefaultProgramParams(w,f,b){return{config:new q6(this,{zoom:f,lut:b}),overrideFog:!1}}recalculate(w,f){super.recalculate(w,f);const b=this.paint._values["fill-outline-color"];b.value.kind==="constant"&&b.value.value===void 0&&(this.paint._values["fill-outline-color"]=this.paint._values["fill-color"])}createBucket(w){return new vMe(w)}queryRadius(){return Wse(this.paint.get("fill-translate"))}queryIntersectsFeature(w,f,b,S,T,D){return!w.queryGeometry.isAboveHorizon&&wMe(Gtt(w.tilespaceGeometry,this.paint.get("fill-translate"),this.paint.get("fill-translate-anchor"),D.angle,w.pixelToTileUnitsFactor),S)}isTileClipped(){return this.paint.get("fill-z-offset").constantOr(1)===0}is3D(w){if(this.paint.get("fill-z-offset").constantOr(1)!==0)return!0;const f=this.layout&&this.layout.get("fill-elevation-reference")!=="none";return w!=null?f&&!w:f}hasElevation(){return this.layout&&this.layout.get("fill-elevation-reference")!=="none"}mayUse(w){return w==="HD"&&i7(this,"fill-elevation-reference",f=>f!=="none")}prepare(){return this.mayUse("HD")?Gse():Promise.resolve()}hasShadowPass(){return this.layout&&this.layout.get("fill-elevation-reference")!=="none"}},"fill-extrusion":class extends zy{constructor(w,f,b,S){super(w,{layout:ist||(ist=new $d({visibility:new Bn(Us["layout_fill-extrusion"].visibility),"fill-extrusion-edge-radius":new Bn(Us["layout_fill-extrusion"]["fill-extrusion-edge-radius"]),"source-max-zoom":new Bn(Us["layout_fill-extrusion"]["source-max-zoom"])})),paint:ost||(ost=new $d({"fill-extrusion-opacity":new Bn(Us["paint_fill-extrusion"]["fill-extrusion-opacity"]),"fill-extrusion-color":new hr(Us["paint_fill-extrusion"]["fill-extrusion-color"]),"fill-extrusion-translate":new Bn(Us["paint_fill-extrusion"]["fill-extrusion-translate"]),"fill-extrusion-translate-anchor":new Bn(Us["paint_fill-extrusion"]["fill-extrusion-translate-anchor"]),"fill-extrusion-pattern":new hr(Us["paint_fill-extrusion"]["fill-extrusion-pattern"]),"fill-extrusion-pattern-cross-fade":new Bn(Us["paint_fill-extrusion"]["fill-extrusion-pattern-cross-fade"]),"fill-extrusion-height":new hr(Us["paint_fill-extrusion"]["fill-extrusion-height"]),"fill-extrusion-base":new hr(Us["paint_fill-extrusion"]["fill-extrusion-base"]),"fill-extrusion-height-alignment":new Bn(Us["paint_fill-extrusion"]["fill-extrusion-height-alignment"]),"fill-extrusion-base-alignment":new Bn(Us["paint_fill-extrusion"]["fill-extrusion-base-alignment"]),"fill-extrusion-vertical-gradient":new Bn(Us["paint_fill-extrusion"]["fill-extrusion-vertical-gradient"]),"fill-extrusion-ambient-occlusion-intensity":new Bn(Us["paint_fill-extrusion"]["fill-extrusion-ambient-occlusion-intensity"]),"fill-extrusion-ambient-occlusion-radius":new Bn(Us["paint_fill-extrusion"]["fill-extrusion-ambient-occlusion-radius"]),"fill-extrusion-ambient-occlusion-wall-radius":new Bn(Us["paint_fill-extrusion"]["fill-extrusion-ambient-occlusion-wall-radius"]),"fill-extrusion-ambient-occlusion-ground-radius":new Bn(Us["paint_fill-extrusion"]["fill-extrusion-ambient-occlusion-ground-radius"]),"fill-extrusion-ambient-occlusion-ground-attenuation":new Bn(Us["paint_fill-extrusion"]["fill-extrusion-ambient-occlusion-ground-attenuation"]),"fill-extrusion-flood-light-color":new Bn(Us["paint_fill-extrusion"]["fill-extrusion-flood-light-color"]),"fill-extrusion-flood-light-intensity":new Bn(Us["paint_fill-extrusion"]["fill-extrusion-flood-light-intensity"]),"fill-extrusion-flood-light-wall-radius":new hr(Us["paint_fill-extrusion"]["fill-extrusion-flood-light-wall-radius"]),"fill-extrusion-flood-light-ground-radius":new hr(Us["paint_fill-extrusion"]["fill-extrusion-flood-light-ground-radius"]),"fill-extrusion-flood-light-ground-attenuation":new Bn(Us["paint_fill-extrusion"]["fill-extrusion-flood-light-ground-attenuation"]),"fill-extrusion-vertical-scale":new Bn(Us["paint_fill-extrusion"]["fill-extrusion-vertical-scale"]),"fill-extrusion-rounded-roof":new Bn(Us["paint_fill-extrusion"]["fill-extrusion-rounded-roof"]),"fill-extrusion-cutoff-fade-range":new Bn(Us["paint_fill-extrusion"]["fill-extrusion-cutoff-fade-range"]),"fill-extrusion-front-cutoff":new Bn(Us["paint_fill-extrusion"]["fill-extrusion-front-cutoff"]),"fill-extrusion-emissive-strength":new hr(Us["paint_fill-extrusion"]["fill-extrusion-emissive-strength"]),"fill-extrusion-line-width":new hr(Us["paint_fill-extrusion"]["fill-extrusion-line-width"]),"fill-extrusion-cast-shadows":new Bn(Us["paint_fill-extrusion"]["fill-extrusion-cast-shadows"]),"fill-extrusion-color-use-theme":new hr({type:"string",default:"default","property-type":"data-driven"}),"fill-extrusion-flood-light-color-use-theme":new hr({type:"string",default:"default","property-type":"data-driven"})}))},f,b,S),this._stats={numRenderedVerticesInShadowPass:0,numRenderedVerticesInTransparentPass:0}}createBucket(w){return new qse(w)}queryRadius(){return Wse(this.paint.get("fill-extrusion-translate"))}is3D(w){return!0}hasShadowPass(){return this.paint.get("fill-extrusion-cast-shadows")}cutoffRange(){return this.paint.get("fill-extrusion-cutoff-fade-range")}canCastShadows(){return!0}getProgramIds(){return[this.paint.get("fill-extrusion-pattern").constantOr(1)?"fillExtrusionPattern":"fillExtrusion"]}queryIntersectsFeature(w,f,b,S,T,D,F,q,K){const X=Wtt(this.paint.get("fill-extrusion-translate"),this.paint.get("fill-extrusion-translate-anchor"),D.angle,w.pixelToTileUnitsFactor),ce=this.paint.get("fill-extrusion-height").evaluate(f,b),pe=this.paint.get("fill-extrusion-base").evaluate(f,b),xe=[0,0],Ne=q&&D.elevation,Me=D.elevation?D.elevation.exaggeration():1,ze=w.tile.getBucket(this);if(ze instanceof qse){const ct=ze.centroidData.find(xt=>K>=xt.vertexArrayOffset&&Kct.polygon).flat());const Ve=Ne?q:null,[Je,lt]=pst(D,S,pe,ce,X,F,Ve,xe,Me,D.center.lat,w.tileID.canonical),ht=w.queryGeometry;return fst(Je,lt,ht.isPointQuery()?ht.screenBounds:ht.screenGeometry)}},building:class extends zy{constructor(w,f,b,S){super(w,{layout:lst||(lst=new $d({visibility:new Bn(Us.layout_building.visibility),"building-facade":new hr(Us.layout_building["building-facade"]),"building-facade-floors":new hr(Us.layout_building["building-facade-floors"]),"building-facade-unit-width":new hr(Us.layout_building["building-facade-unit-width"]),"building-facade-window":new hr(Us.layout_building["building-facade-window"]),"building-roof-shape":new hr(Us.layout_building["building-roof-shape"]),"building-height":new hr(Us.layout_building["building-height"]),"building-base":new hr(Us.layout_building["building-base"]),"building-flood-light-wall-radius":new hr(Us.layout_building["building-flood-light-wall-radius"]),"building-flood-light-ground-radius":new hr(Us.layout_building["building-flood-light-ground-radius"]),"building-flip-roof-orientation":new hr(Us.layout_building["building-flip-roof-orientation"])})),paint:cst||(cst=new $d({"building-opacity":new Bn(Us.paint_building["building-opacity"]),"building-ambient-occlusion-intensity":new Bn(Us.paint_building["building-ambient-occlusion-intensity"]),"building-ambient-occlusion-ground-intensity":new Bn(Us.paint_building["building-ambient-occlusion-ground-intensity"]),"building-ambient-occlusion-ground-radius":new Bn(Us.paint_building["building-ambient-occlusion-ground-radius"]),"building-ambient-occlusion-ground-attenuation":new Bn(Us.paint_building["building-ambient-occlusion-ground-attenuation"]),"building-vertical-scale":new Bn(Us.paint_building["building-vertical-scale"]),"building-cast-shadows":new Bn(Us.paint_building["building-cast-shadows"]),"building-color":new hr(Us.paint_building["building-color"]),"building-emissive-strength":new hr(Us.paint_building["building-emissive-strength"]),"building-facade-emissive-chance":new Bn(Us.paint_building["building-facade-emissive-chance"]),"building-cutoff-fade-range":new Bn(Us.paint_building["building-cutoff-fade-range"]),"building-front-cutoff":new Bn(Us.paint_building["building-front-cutoff"]),"building-flood-light-color":new Bn(Us.paint_building["building-flood-light-color"]),"building-flood-light-intensity":new Bn(Us.paint_building["building-flood-light-intensity"]),"building-flood-light-ground-attenuation":new Bn(Us.paint_building["building-flood-light-ground-attenuation"]),"building-color-use-theme":new hr({type:"string",default:"default","property-type":"data-driven"}),"building-flood-light-color-use-theme":new hr({type:"string",default:"default","property-type":"data-driven"})}))},f,b,S),this._stats={numRenderedVerticesInShadowPass:0,numRenderedVerticesInTransparentPass:0}}mayUse(w){return w==="HD"}prepare(){return async function(){return function(){if(!Gu(self)||nw!=null||qtt!=null)return null;if(N7!=null)return N7;const w=fetch(Zs());return N7=function(f){let b,S,T,D,F;function q(){b=new Uint8Array(F.buffer),S=new Int16Array(F.buffer),T=new Int32Array(F.buffer),D=new Float32Array(F.buffer)}function K(){throw new Error("Unexpected BuildingGen error.")}const X=()=>{},ce={a:{a:K,f:function(pe){const xe=b.length,Ne=Math.max(pe>>>0,Math.ceil(1.2*xe)),Me=Math.ceil((Ne-xe)/65536);try{return F.grow(Me),q(),!0}catch{return!1}},g:K,b:X,c:X,d:X,e:X}};return(WebAssembly.instantiateStreaming?WebAssembly.instantiateStreaming(f,ce):f.then(pe=>pe.arrayBuffer()).then(pe=>WebAssembly.instantiate(pe,ce))).then(pe=>{const xe=pe.instance.exports;return(0,xe.g)(),F=xe.f,q(),new wXt({setStyle:xe.h,setAOOptions:xe.i,setMetricOptions:xe.j,setStructuralOptions:xe.k,setFacadeOptions:xe.l,setFauxFacadeOptions:xe.m,setFacadeClassifierOptions:xe.n,addFeature:xe.o,addFacade:xe.p,generateMesh:xe.q,getLastError:xe.r,getOuterRingLength:xe.s,getMeshCount:xe.t,getPositionsPtr:xe.u,getPositionsLength:xe.v,getNormalsPtr:xe.w,getNormalsLength:xe.x,getAOPtr:xe.y,getAOLength:xe.z,getUVPtr:xe.A,getUVLength:xe.B,getFauxFacadePtr:xe.C,getFauxFacadeLength:xe.D,getIndicesPtr:xe.E,getIndicesLength:xe.F,getBuildingPart:xe.G,getRingCount:xe.H,getRingPtr:xe.I,getRingLength:xe.J,malloc:xe.K,free:xe.L,heapU8:b,heap16:S,heap32:T,heapF32:D})})}(w).then(f=>{N7=null,nw=f}).catch(f=>{oi("Could not load building-gen"),N7=null,qtt=f}),N7}()}()}createBucket(w){return new Vtt(w)}cutoffRange(){return this.paint.get("building-cutoff-fade-range")}hasShadowPass(){return this.paint.get("building-cast-shadows")}hasLightBeamPass(){return!0}canCastShadows(){return!0}is3D(w){return!0}queryRadius(w){return 0}queryIntersectsFeature(w,f,b,S,T,D,F,q,K,X){let ce=this.layout.get("building-height").evaluate(f,b);const pe=this.layout.get("building-base").evaluate(f,b),xe=w.tile.getBucket(this).getFootprint(f);if(xe){if(xe.hiddenFlags!==0)return!1;ce=xe.height}const[Ne,Me]=pst(D,S,pe,ce,new Kt(0,0),F,null,[0,0],1,D.center.lat,w.tileID.canonical),ze=w.queryGeometry;return fst(Ne,Me,ze.isPointQuery()?ze.screenBounds:ze.screenGeometry)}},line:class extends zy{constructor(w,f,b,S){const T=_st();super(w,T,f,b,S),T.layout&&(this.layout=new Ch(T.layout)),this.gradientVersion=0,this.borderGradientVersion=0,this.hasElevatedBuckets=!1,this.hasNonElevatedBuckets=!1,this.lineBlendFbos=null,this.lineBlendDensityReadback=null}_handleSpecialPaintPropertyUpdate(w){if(w==="line-gradient"){const f=this._transitionablePaint._values["line-gradient"].value.expression;this.stepInterpolant=f._styleExpression&&f._styleExpression.expression instanceof Hi,this.gradientVersion=(this.gradientVersion+1)%Number.MAX_SAFE_INTEGER}else if(w==="line-gradient-use-theme")this.gradientVersion=(this.gradientVersion+1)%Number.MAX_SAFE_INTEGER;else if(w==="line-border-gradient"){const f=this._transitionablePaint._values["line-border-gradient"].value.expression;this.borderStepInterpolant=f._styleExpression&&f._styleExpression.expression instanceof Hi,this.borderGradientVersion=(this.borderGradientVersion+1)%Number.MAX_SAFE_INTEGER}else w==="line-border-gradient-use-theme"&&(this.borderGradientVersion=(this.borderGradientVersion+1)%Number.MAX_SAFE_INTEGER)}gradientExpression(){return this._transitionablePaint._values["line-gradient"].value.expression}borderGradientExpression(){return this._transitionablePaint._values["line-border-gradient"].value.expression}widthExpression(){return this._transitionablePaint._values["line-width"].value.expression}emissiveStrengthExpression(){return this._transitionablePaint._values["line-emissive-strength"].value.expression}recalculate(w,f){super.recalculate(w,f),this.paint._values["line-floorwidth"]=(()=>{if(LH)return LH;const b=_st();return LH=new PXt(b.paint.properties["line-width"].specification),LH.useIntegerZoom=!0,LH})().possiblyEvaluate(this._transitioningPaint._values["line-width"].value,w)}createBucket(w){return new TMe(w)}getProgramIds(){const w=[this.paint.get("line-pattern").constantOr(1)?"linePattern":"line"];return this.paint.get("line-blend-mode")!=="default"&&w.push("lineBlendComposite"),w}getDefaultProgramParams(w,f,b){if(w==="lineBlendComposite")return{};const S=vst(this);return{config:new q6(this,{zoom:f,lut:b}),defines:S,overrideFog:!1}}queryRadius(w){const f=w,b=Nst(k7("line-width",this,f),k7("line-gap-width",this,f)),S=k7("line-offset",this,f);return b/2+Math.abs(S)+Wse(this.paint.get("line-translate"))}queryIntersectsFeature(w,f,b,S,T,D){if(w.queryGeometry.isAboveHorizon)return!1;const F=Gtt(w.tilespaceGeometry,this.paint.get("line-translate"),this.paint.get("line-translate-anchor"),D.angle,w.pixelToTileUnitsFactor),q=w.pixelToTileUnitsFactor/2*Nst(this.paint.get("line-width").evaluate(f,b),this.paint.get("line-gap-width").evaluate(f,b)),K=this.paint.get("line-offset").evaluate(f,b);return K&&(S=function(X,ce){const pe=[],xe=new Kt(0,0);for(let Ne=0;Ne=3){for(let Me=0;Mef==="hd-road-markup")}prepare(){return this.mayUse("HD")?Gse():Promise.resolve()}hasOffscreenPass(){return this.paint.get("line-blend-mode")!=="default"&&this.paint.get("line-opacity").constantOr(1)!==0&&this.paint.get("line-width").constantOr(1)!==0&&this.visibility!=="none"}resize(){this._destroyLineBlendFbo()}onRemove(w){this._destroyLineBlendFbo(w.painter&&w.painter.context&&w.painter.context.gl||void 0)}_clear(){this._destroyLineBlendFbo()}_destroyLineBlendFbo(w){this.lineBlendFbos&&(this.lineBlendFbos.destroy(),this.lineBlendFbos=null),w&&this.lineBlendDensityReadback&&this.lineBlendDensityReadback.destroy(w),this.lineBlendDensityReadback=null}},symbol:Kse,background:class extends zy{constructor(w,f,b,S){super(w,{layout:Cst||(Cst=new $d({visibility:new Bn(Us.layout_background.visibility)})),paint:Ast||(Ast=new $d({"background-pitch-alignment":new Bn(Us.paint_background["background-pitch-alignment"]),"background-color":new Bn(Us.paint_background["background-color"]),"background-pattern":new Bn(Us.paint_background["background-pattern"]),"background-opacity":new Bn(Us.paint_background["background-opacity"]),"background-emissive-strength":new Bn(Us.paint_background["background-emissive-strength"]),"background-color-use-theme":new hr({type:"string",default:"default","property-type":"data-driven"})}))},f,b,S)}getProgramIds(){return[this.paint.get("background-pattern")?"backgroundPattern":"background"]}getDefaultProgramParams(w,f,b){return{overrideFog:!1}}is3D(w){return this.paint.get("background-pitch-alignment")==="viewport"}},raster:Mst,"raster-particle":zst,sky:class extends zy{constructor(w,f,b,S){super(w,{layout:Lst||(Lst=new $d({visibility:new Bn(Us.layout_sky.visibility)})),paint:Rst||(Rst=new $d({"sky-type":new Bn(Us.paint_sky["sky-type"]),"sky-atmosphere-sun":new Bn(Us.paint_sky["sky-atmosphere-sun"]),"sky-atmosphere-sun-intensity":new Bn(Us.paint_sky["sky-atmosphere-sun-intensity"]),"sky-gradient-center":new Bn(Us.paint_sky["sky-gradient-center"]),"sky-gradient-radius":new Bn(Us.paint_sky["sky-gradient-radius"]),"sky-gradient":new Aj(Us.paint_sky["sky-gradient"]),"sky-atmosphere-halo-color":new Bn(Us.paint_sky["sky-atmosphere-halo-color"]),"sky-atmosphere-color":new Bn(Us.paint_sky["sky-atmosphere-color"]),"sky-opacity":new Bn(Us.paint_sky["sky-opacity"]),"sky-gradient-use-theme":new hr({type:"string",default:"default","property-type":"data-driven"}),"sky-atmosphere-halo-color-use-theme":new hr({type:"string",default:"default","property-type":"data-driven"}),"sky-atmosphere-color-use-theme":new hr({type:"string",default:"default","property-type":"data-driven"})}))},f,b,S),this._updateColorRamp()}_clear(){this.skyboxFbo&&(this.skyboxFbo.destroy(),this.skyboxFbo=null),this.colorRampTexture&&(this.colorRampTexture.destroy(),this.colorRampTexture=null),this._skyboxInvalidated=!0}_handleSpecialPaintPropertyUpdate(w){w==="sky-gradient"?this._updateColorRamp():w!=="sky-atmosphere-sun"&&w!=="sky-atmosphere-halo-color"&&w!=="sky-atmosphere-color"&&w!=="sky-atmosphere-sun-intensity"||(this._skyboxInvalidated=!0)}_updateColorRamp(){this.colorRamp=MH({expression:this._transitionablePaint._values["sky-gradient"].value.expression,evaluationKey:"skyRadialProgress"}),this.colorRampTexture&&(this.colorRampTexture.destroy(),this.colorRampTexture=null)}needsSkyboxCapture(w){if(this._skyboxInvalidated||!this.skyboxTexture||!this.skyboxGeometry)return!0;if(!this.paint.get("sky-atmosphere-sun")){const f=w.style.light.properties.get("position");return this._lightPosition.azimuthal!==f.azimuthal||this._lightPosition.polar!==f.polar}return!1}getCenter(w,f){if(this.paint.get("sky-type")==="atmosphere"){const S=this.paint.get("sky-atmosphere-sun"),T=!S,D=w.style.light,F=D.properties.get("position");return T&&D.properties.get("anchor")==="viewport"&&oi("The sun direction is attached to a light with viewport anchor, lighting may behave unexpectedly."),T?R6e(F.azimuthal,90-F.polar,f):R6e(S[0],90-S[1],f)}const b=this.paint.get("sky-gradient-center");return R6e(b[0],90-b[1],f)}isSky(){return!0}markSkyboxValid(w){this._skyboxInvalidated=!1,this._lightPosition=w.style.light.properties.get("position")}hasOffscreenPass(){return!0}getProgramIds(){const w=this.paint.get("sky-type");return w==="atmosphere"?["skyboxCapture","skybox"]:w==="gradient"?["skyboxGradient"]:null}},slot:class extends zy{constructor(w,f,b,S){super(w,{paint:Dst||(Dst=new $d({}))},f,null)}},model:class extends zy{constructor(w,f,b,S){super(w,{layout:Ost||(Ost=new $d({visibility:new Bn(Us.layout_model.visibility),"model-id":new hr(Us.layout_model["model-id"]),"model-allow-density-reduction":new Bn(Us.layout_model["model-allow-density-reduction"])})),paint:Fst||(Fst=new $d({"model-opacity":new hr(Us.paint_model["model-opacity"]),"model-rotation":new hr(Us.paint_model["model-rotation"]),"model-scale":new hr(Us.paint_model["model-scale"]),"model-translation":new hr(Us.paint_model["model-translation"]),"model-color":new hr(Us.paint_model["model-color"]),"model-color-mix-intensity":new hr(Us.paint_model["model-color-mix-intensity"]),"model-type":new Bn(Us.paint_model["model-type"]),"model-cast-shadows":new Bn(Us.paint_model["model-cast-shadows"]),"model-receive-shadows":new Bn(Us.paint_model["model-receive-shadows"]),"model-ambient-occlusion-intensity":new Bn(Us.paint_model["model-ambient-occlusion-intensity"]),"model-emissive-strength":new hr(Us.paint_model["model-emissive-strength"]),"model-roughness":new hr(Us.paint_model["model-roughness"]),"model-height-based-emissive-strength-multiplier":new hr(Us.paint_model["model-height-based-emissive-strength-multiplier"]),"model-cutoff-fade-range":new Bn(Us.paint_model["model-cutoff-fade-range"]),"model-front-cutoff":new Bn(Us.paint_model["model-front-cutoff"]),"model-elevation-reference":new Bn(Us.paint_model["model-elevation-reference"]),"model-line-cutout-mode":new Bn(Us.paint_model["model-line-cutout-mode"]),"model-color-use-theme":new hr({type:"string",default:"default","property-type":"data-driven"})}))},f,b,S),this.layer=w,this._stats={numRenderedVerticesInShadowPass:0,numRenderedVerticesInTransparentPass:0}}mayUse(w){return w==="Standard"}prepare(){return Gnt()}createBucket(w){return new D6e(w)}getProgramIds(){return["model"]}is3D(w){return!0}hasShadowPass(){return!0}canCastShadows(){return!0}hasLightBeamPass(){return!0}cutoffRange(){return this.paint.get("model-cutoff-fade-range")}queryRadius(w){return w.isTiled3dModelBucket?8191:0}queryRenderedFeatures(w,f,b){return eP.queryModelLayerRendered?eP.queryModelLayerRendered(this,w,f,b):{}}queryIntersectsFeature(w,f,b,S,T,D,F,q,K,X){return!!eP.queryModelLayerIntersectsFeature&&eP.queryModelLayerIntersectsFeature(this,w,f,b,D,X)}_handleOverridablePaintPropertyUpdate(w,f,b){return!(!this.layout||f.isDataDriven()||b.isDataDriven()||w!=="model-color"&&w!=="model-color-mix-intensity"&&w!=="model-rotation"&&w!=="model-scale"&&w!=="model-translation"&&w!=="model-emissive-strength")}_isPropertyZoomDependent(w){const f=this._transitionablePaint._values[w];return f!=null&&f.value!=null&&f.value.expression!=null&&f.value.expression instanceof xp}isZoomDependent(){return this._isPropertyZoomDependent("model-scale")||this._isPropertyZoomDependent("model-rotation")||this._isPropertyZoomDependent("model-translation")}},clip:class extends zy{constructor(w,f,b,S){super(w,{layout:rst||(rst=new $d({"clip-layer-types":new Bn(Us.layout_clip["clip-layer-types"]),"clip-layer-scope":new Bn(Us.layout_clip["clip-layer-scope"]),visibility:new Bn(Us.layout_clip.visibility)})),paint:ast||(ast=new $d({}))},f,b,S)}recalculate(w,f){super.recalculate(w,f)}createBucket(w){return new hst(w)}is3D(w){return!0}}};class sPe{constructor(f){this.capacity=f,this.cache=new Map}get(f){if(!this.cache.has(f))return;const b=this.cache.get(f);return this.cache.delete(f),this.cache.set(f,b),b}put(f,b){this.cache.has(f)?this.cache.delete(f):this.cache.size===this.capacity&&this.cache.delete(this.cache.keys().next().value),this.cache.set(f,b)}delete(f){this.cache.delete(f)}}Vr(sPe,"LRUCache");class hQt{constructor(f){this._callback=f,this._triggered=!1,typeof MessageChannel<"u"&&(this._channel=new MessageChannel,this._channel.port2.onmessage=()=>{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&&(this._channel.port1.close(),this._channel.port2.close()),this._callback=()=>{}}}const Wnt={Other:0,Symbol:1,FillExtrusion:2,HdRoadCoverage:3,HdRoadElevation:4};class mQt{constructor(){this.tasks=new Map,Rr(["process"],this),this.invoker=new hQt(this.process),this.nextId=0}add(f,b){const S=this.nextId++,T=function({type:D,renderSourceType:F,zoom:q}){q=q||0;const K=F===Wnt.Symbol;return D==="message"?0:D!=="maybePrepare"||K?D!=="parseTile"||K?D==="parseTile"&&K?300-q:D==="maybePrepare"&&K?400-q:500:200-q:100-q}(b);if(T===0){try{f()}finally{}return null}return this.tasks.set(S,{fn:f,metadata:b,priority:T,id:S}),this.invoker.trigger(),{cancel:()=>{this.tasks.delete(S)}}}process(){try{const f=this.pick();if(!f)return;this.tasks.delete(f.id),this.tasks.size>0&&this.invoker.trigger(),f.fn()}finally{}}pick(){let f=null,b=1/0;for(const S of this.tasks.values())S.priorityf[F])return null}else{const q=1/S[F];let K=(w[F]-b[F])*q,X=(f[F]-b[F])*q;if(K>X){const ce=K;K=X,X=ce}if(K>T&&(T=K),XD)return null}return T}function Qnt(w,f,b,S,T,D,F,q,K,X,ce){const pe=S-w,xe=T-f,Ne=D-b,Me=F-w,ze=q-f,Ve=K-b,Je=ce[1]*Ve-ce[2]*ze,lt=ce[2]*Me-ce[0]*Ve,ht=ce[0]*ze-ce[1]*Me,ct=pe*Je+xe*lt+Ne*ht;if(Math.abs(ct)<1e-15)return null;const xt=1/ct,kt=X[0]-w,es=X[1]-f,Ct=X[2]-b,Lt=(kt*Je+es*lt+Ct*ht)*xt;if(Lt<0||Lt>1)return null;const Zt=es*Ne-Ct*xe,Qt=Ct*pe-kt*Ne,Cs=kt*xe-es*pe,Fs=(ce[0]*Zt+ce[1]*Qt+ce[2]*Cs)*xt;return Fs<0||Lt+Fs>1?null:(Me*Zt+ze*Qt+Ve*Cs)*xt}function Jnt(w,f,b,S,T,D,F,q,K){const X=1<{const xt=ht?1:0,kt=(Ve+1)*lt-xt,es=Je*lt,Ct=(Je+1)*lt-xt;ct[0]=Ve*lt,ct[1]=es,ct[2]=kt,ct[3]=Ct};let pe=new Znt(X);const xe=1/X,{floatView:Ne,stride:Me}=D,ze=[];for(let Ve=0;VeCs&&(Cs=hn)}}pe.minimums.push(es),pe.maximums.push(Cs),pe.leaves.push(1)}for(K.push(pe),X/=2;X>=1;X/=2){const Ve=K.at(-1);pe=new Znt(X);for(let Je=0;Je0;){const{idx:Me,t:ze,nodex:Ve,nodey:Je,depth:lt}=Ne.pop();if(this.leaves[Me]){Jnt(Ve,Je,lt,f,b,S,T,pe,xe);const ct=1<1e-10,Wn=Math.abs(F[1])>1e-10,Kn=F[0]>=0?1:-1,Dr=F[1]>=0?1:-1;let sr=Math.max(0,Math.min(sn-1,Math.floor((Nn-Rn)/qs))),yr=Math.max(0,Math.min(hn-1,Math.floor((Pn-ws)/en)));const Ra=jn?Math.abs(qs/F[0]):Number.MAX_VALUE,$a=Wn?Math.abs(en/F[1]):Number.MAX_VALUE;let si=jn?wn+(Rn+(F[0]>=0?sr+1:sr)*qs-Nn)/F[0]:Number.MAX_VALUE,La=Wn?wn+(ws+(F[1]>=0?yr+1:yr)*en-Pn)/F[1]:Number.MAX_VALUE;const Oi=(df,Xi)=>Zt[(Xi+1)*Qt+df+1]*q;let bi=Oi(Cs+sr,on+yr),Bl=Oi(Cs+sr+1,on+yr),cl=Oi(Cs+sr,on+yr+1),Ll=Oi(Cs+sr+1,on+yr+1),dc=null;for(let df=0;df=0||D[2]+F[2]*Xi<=Math.max(bi,Bl,cl,Ll)){const rg=Rn+sr*qs,$y=rg+qs,Uy=ws+yr*en,Lv=Uy+en,Rv=Qnt($y,Uy,Bl,rg,Uy,bi,rg,Lv,cl,D,F),bx=Qnt(rg,Lv,cl,$y,Lv,Ll,$y,Uy,Bl,D,F);Rv!=null&&Rv>=0&&(dc===null||Rv=0&&(dc===null||bx=sn||yr<0||yr>=hn||dc!==null&&Xi>dc)break;ng?Kn>0?(bi=Bl,cl=Ll,Bl=Oi(Cs+sr+1,on+yr),Ll=Oi(Cs+sr+1,on+yr+1)):(Bl=bi,Ll=cl,bi=Oi(Cs+sr,on+yr),cl=Oi(Cs+sr,on+yr+1)):Dr>0?(bi=cl,Bl=Ll,cl=Oi(Cs+sr,on+yr+1),Ll=Oi(Cs+sr+1,on+yr+1)):(cl=bi,Ll=Bl,bi=Oi(Cs+sr,on+yr),Bl=Oi(Cs+sr+1,on+yr))}if(dc!==null)return dc||0;const cf=je([],D,F,ze),$1=(cf[0]-pe[0])/(xe[0]-pe[0]),Wh=(cf[1]-pe[1])/(xe[1]-pe[1]),xl=PA(xt,es,this.dem)*q,Jd=PA(kt,es,this.dem)*q,om=PA(kt,Ct,this.dem)*q;if(trt(xl,Jd,PA(xt,Ct,this.dem)*q,om,$1,Wh)>=cf[2])return ze;continue}let ht=0;for(let ct=0;ct=X[ce[Ct]]&&(ce.splice(Ct,0,ct),es=!0);es||(ce[ht]=ct),ht++}}for(let ct=0;ct=this.dim+1||b<-1||b>=this.dim+1)throw new RangeError("out of range source coordinates for DEM data");return(b+1)*this.stride+(f+1)}static pack(f,b){const S=[0,0,0,0],T=hne.getUnpackVector(b);let D=Math.floor((f+T[3])/T[2]);return S[2]=D%256,D=Math.floor(D/256),S[1]=D%256,D=Math.floor(D/256),S[0]=D,S}getPixels(){return new OJe({width:this.stride,height:this.stride},this.pixels)}backfillBorder(f,b,S){if(this.dim!==f.dim)throw new Error("dem dimension mismatch");let T=b*this.dim,D=b*this.dim+this.dim,F=S*this.dim,q=S*this.dim+this.dim;switch(b){case-1:T=D-1;break;case 1:D=T+1}switch(S){case-1:F=q-1;break;case 1:q=F+1}const K=-b*this.dim,X=-S*this.dim;for(let ce=F;ce=1;S--){const T=S===1?1:0,D=S===2?1:0;for(let F=0;F>>1^-(1&w[f]);return w}function kQt(w,f){switch(f){case"uint32":return w;case"uint16":for(let b=0;b>4|(61440&S)>>8|(240&T)<<4|61440&T,w[b+1]=15&S|(3840&S)>>4|(15&T)<<8|(3840&T)<<4}return w;case"uint8":for(let b=0;b>6|(192&T)>>4|(192&D)>>2|192&F,w[b+1]=(48&S)>>4|(48&T)>>2|48&D|(48&F)<<2,w[b+2]=(12&S)>>2|12&T|(12&D)<<2|(12&F)<<4,w[b+3]=3&S|(3&T)<<2|(3&D)<<4|(3&F)<<6}return w;default:throw new Error(`Invalid pixel format, "${f}"`)}}Vr(hne,"DEMData"),Vr(ert,"DemMinMaxQuadTree",{omit:["dem"]});var aw=Uint8Array,BH=Uint16Array,SQt=Int32Array,srt=new aw([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]),nrt=new aw([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]),CQt=new aw([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),rrt=function(w,f){for(var b=new BH(31),S=0;S<31;++S)b[S]=f+=1<>1|(21845&lf)<<1;ort[lf]=((65280&(M7=(61680&(M7=(52428&M7)>>2|(13107&M7)<<2))>>4|(3855&M7)<<4))>>8|(255&M7)<<8)>>1}var $H=function(w,f,b){for(var S=w.length,T=0,D=new BH(f);T>K]=X;return F},UH=new aw(288);for(lf=0;lf<144;++lf)UH[lf]=8;for(lf=144;lf<256;++lf)UH[lf]=9;for(lf=256;lf<280;++lf)UH[lf]=7;for(lf=280;lf<288;++lf)UH[lf]=8;var lrt=new aw(32);for(lf=0;lf<32;++lf)lrt[lf]=5;var TQt=$H(UH,9),MQt=$H(lrt,5),rPe=function(w){for(var f=w[0],b=1;bf&&(f=w[b]);return f},oN=function(w,f,b){var S=f/8|0;return(w[S]|w[S+1]<<8)>>(7&f)&b},aPe=function(w,f){var b=f/8|0;return(w[b]|w[b+1]<<8|w[b+2]<<16)>>(7&f)},PQt=function(w){return(w+7)/8|0},IQt=["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"],lN=function(w,f,b){var S=new Error(f||IQt[w]);if(S.code=w,Error.captureStackTrace&&Error.captureStackTrace(S,lN),!b)throw S;return S},LQt=new aw(0),RQt=typeof TextDecoder<"u"&&new TextDecoder;try{RQt.decode(LQt,{stream:!0})}catch{}const DQt={gzip_data:"gzip"};class Tj extends Error{constructor(f){super(f),this.name="MRTError"}}const OQt={0:"uint32",1:"uint32",2:"uint16",3:"uint8"},crt={uint32:1,uint16:2,uint8:4},FQt={uint32:Uint32Array,uint16:Uint16Array,uint8:Uint8Array};let iPe;class mne{constructor(f=5){this.x=NaN,this.y=NaN,this.z=NaN,this.layers={},this._cacheSize=f}getLayer(f){const b=this.layers[f];if(!b)throw new Tj(`Layer '${f}' not found`);return b}getHeaderLength(f){const b=new Uint8Array(f),S=new DataView(f);if(b[0]!==13)throw new Tj("File is not a valid MRT.");return S.getUint32(1,!0)}parseHeader(f){const b=new Uint8Array(f),S=this.getHeaderLength(f);if(b.length= ${S} but got buffer of length ${b.length}`);const T=function(D){const F={headerLength:0,x:0,y:0,z:0,layers:[]};let q;for(;q=D.nextField(void 0);)q===1?F.headerLength=D.readFixed32():q===2?F.x=D.readVarint():q===3?F.y=D.readVarint():q===4?F.z=D.readVarint():q===5&&F.layers.push(_Qt(D,D.readVarint()+D.pos));return F}(new iPe(b.subarray(0,S)));if(!isNaN(this.x)&&(this.x!==T.x||this.y!==T.y||this.z!==T.z))throw new Tj(`Invalid attempt to parse header ${T.z}/${T.x}/${T.y} for tile ${this.z}/${this.x}/${this.y}`);this.x=T.x,this.y=T.y,this.z=T.z;for(const D of T.layers)this.layers[D.name]=new drt(D,{cacheSize:this._cacheSize});return this}createDecodingTask(f){const b=[],S=this.getLayer(f.layerName);for(let T of f.blockIndices){const D=S.dataIndex[T],F=D.firstByte-f.firstByte,q=D.lastByte-f.firstByte;if(S._blocksInProgress.has(T))continue;const K={layerName:S.name,firstByte:F,lastByte:q,pixelFormat:S.pixelFormat,blockIndex:T,blockShape:[D.bands.length].concat(S.bandShape),buffer:S.buffer,codec:D.codec.codec,filters:D.filters.map(X=>X.filter)};S._blocksInProgress.add(T),b.push(K)}return new urt(b,()=>{b.forEach(T=>S._blocksInProgress.delete(T.blockIndex))},(T,D)=>{if(b.forEach(F=>S._blocksInProgress.delete(F.blockIndex)),T)throw T;D.forEach(F=>{this.getLayer(F.layerName).processDecodedData(F)})})}}class drt{constructor({version:f,name:b,units:S,tileSize:T,pixelFormat:D,buffer:F,dataIndex:q},K){if(this.version=f,this.version!==1)throw new Tj(`Cannot parse raster layer encoded with MRT version ${f}`);this.name=b,this.units=S,this.tileSize=T,this.buffer=F,this.pixelFormat=OQt[D],this.dataIndex=q,this.bandShape=[T+2*F,T+2*F,crt[this.pixelFormat]],this._decodedBlocks=new sPe(K?K.cacheSize:5),this._blocksInProgress=new Set}get dimension(){return crt[this.pixelFormat]}get cacheSize(){return this._decodedBlocks.capacity}getBandList(){return this.dataIndex.map(({bands:f})=>f).flat()}processDecodedData(f){const b=f.blockIndex.toString();this._decodedBlocks.get(b)||this._decodedBlocks.put(b,f.data)}getBlockForBand(f){let b=0;switch(typeof f){case"string":for(const[S,T]of this.dataIndex.entries()){for(const[D,F]of T.bands.entries())if(F===f)return{bandIndex:b+D,blockIndex:S,blockBandIndex:D};b+=T.bands.length}break;case"number":for(const[S,T]of this.dataIndex.entries()){if(f>=b&&fthis.cacheSize)throw new Tj(`Number of blocks to decode (${D.size}) exceeds cache size (${this.cacheSize}).`);return{layerName:this.name,firstByte:b,lastByte:S,blockIndices:T}}hasBand(f){const{blockIndex:b}=this.getBlockForBand(f);return b>=0}hasDataForBand(f){const{blockIndex:b}=this.getBlockForBand(f);return b>=0&&!!this._decodedBlocks.get(b.toString())}getBandView(f){const{blockIndex:b,blockBandIndex:S}=this.getBlockForBand(f);if(b<0)throw new Tj(`Band not found: ${JSON.stringify(f)}`);const T=this._decodedBlocks.get(b.toString());if(!T)throw new Tj(`Data for band ${JSON.stringify(f)} of layer "${this.name}" not decoded.`);const D=this.dataIndex[b],F=this.bandShape.reduce((X,ce)=>X*ce,1),q=S*F,K=T.subarray(q,q+F);return{data:K,bytes:new Uint8Array(K.buffer).subarray(K.byteOffset,K.byteOffset+K.byteLength),tileSize:this.tileSize,buffer:this.buffer,pixelFormat:this.pixelFormat,dimension:this.dimension,offset:D.offset,scale:D.scale}}}mne.setPbf=function(w){iPe=w};class urt{constructor(f,b,S){this.tasks=f,this._onCancel=b,this._onComplete=S,this._finalized=!1}cancel(){this._finalized||(this._onCancel(),this._finalized=!0)}complete(f,b){this._finalized||(this._onComplete(f,b),this._finalized=!0)}}mne.performDecoding=function(w,f){const b=new Uint8Array(w);return Promise.all(f.tasks.map(S=>{const{layerName:T,firstByte:D,lastByte:F,pixelFormat:q,blockShape:K,blockIndex:X,filters:ce,codec:pe}=S,xe=b.subarray(D,F+1),Ne=new Uint32Array(K[0]*K[1]*K[2]);let Me;if(pe!=="gzip_data")throw new Tj(`Unhandled codec: ${pe}`);return Me=function(ze,Ve){if(!globalThis.DecompressionStream&&Ve==="gzip_data")return Promise.resolve((xt=function(Ct){Ct[0]==31&&Ct[1]==139&&Ct[2]==8||lN(6,"invalid gzip data");var Lt=Ct[3],Zt=10;4&Lt&&(Zt+=2+(Ct[10]|Ct[11]<<8));for(var Qt=(Lt>>3&1)+(Lt>>4&1);Qt>0;Qt-=!Ct[Zt++]);return Zt+(2&Lt)}(Je=ze),xt+8>Je.length&&lN(6,"invalid gzip data"),function(Ct,Lt,Zt,Qt){var Cs=Ct.length;if(!Cs||Lt.f&&!Lt.l)return Zt||new aw(0);var Fs=!Zt,on=Fs||Lt.i!=2,sn=Lt.i;Fs&&(Zt=new aw(3*Cs));var hn=function(bx){var Bg=Zt.length;if(bx>Bg){var _x=new aw(Math.max(2*Bg,bx));_x.set(Zt),Zt=_x}},Rn=Lt.f||0,ws=Lt.p||0,qs=Lt.b||0,en=Lt.l,wn=Lt.d,Nn=Lt.m,Pn=Lt.n,jn=8*Cs;do{if(!en){Rn=oN(Ct,ws,1);var Wn=oN(Ct,ws+1,3);if(ws+=3,!Wn){var Kn=Ct[(cl=PQt(ws)+4)-4]|Ct[cl-3]<<8,Dr=cl+Kn;if(Dr>Cs){sn&&lN(0);break}on&&hn(qs+Kn),Zt.set(Ct.subarray(cl,Dr),qs),Lt.b=qs+=Kn,Lt.p=ws=8*Dr,Lt.f=Rn;continue}if(Wn==1)en=TQt,wn=MQt,Nn=9,Pn=5;else if(Wn==2){var sr=oN(Ct,ws,31)+257,yr=oN(Ct,ws+10,15)+4,Ra=sr+oN(Ct,ws+5,31)+1;ws+=14;for(var $a=new aw(Ra),si=new aw(19),La=0;La>4)<16)$a[La++]=cl;else{var dc=0,cf=0;for(cl==16?(cf=3+oN(Ct,ws,3),ws+=2,dc=$a[La-1]):cl==17?(cf=3+oN(Ct,ws,7),ws+=3):cl==18&&(cf=11+oN(Ct,ws,127),ws+=7);cf--;)$a[La++]=dc}}var $1=$a.subarray(0,sr),Wh=$a.subarray(sr);Nn=rPe($1),Pn=rPe(Wh),en=$H($1,Nn),wn=$H(Wh,Pn)}else lN(1);if(ws>jn){sn&&lN(0);break}}on&&hn(qs+131072);for(var xl=(1<>4;if((ws+=15&dc)>jn){sn&&lN(0);break}if(dc||lN(2),df<256)Zt[qs++]=df;else{if(df==256){om=ws,en=null;break}var Xi=df-254;df>264&&(Xi=oN(Ct,ws,(1<<($y=srt[La=df-257]))-1)+irt[La],ws+=$y);var ng=wn[aPe(Ct,ws)&Jd],rg=ng>>4;if(ng||lN(3),ws+=15&ng,Wh=EQt[rg],rg>3){var $y=nrt[rg];Wh+=aPe(Ct,ws)&(1<<$y)-1,ws+=$y}if(ws>jn){sn&&lN(0);break}on&&hn(qs+131072);var Uy=qs+Xi;if(qsbx.length)&&(_x=bx.length),new aw(bx.subarray(0,_x))}(Zt,0,qs):Zt.subarray(0,qs)}(Je.subarray(xt,-8),{i:2},new aw(((ht=Je)[(ct=ht.length)-4]|ht[ct-3]<<8|ht[ct-2]<<16|ht[ct-1]<<24)>>>0),lt)));var Je,lt,ht,ct,xt;const kt=DQt[Ve];if(!kt)throw new Error(`Unhandled codec: ${Ve}`);const es=new globalThis.DecompressionStream(kt);return new Response(new Blob([ze]).stream().pipeThrough(es)).arrayBuffer().then(Ct=>new Uint8Array(Ct))}(xe,pe).then(ze=>(function(Ve,Je){let lt;for(;lt=Ve.nextField();)if(lt===2)wQt(Ve,Ve.readVarint()+Ve.pos,Je);else if(lt===3)throw new Error("Not implemented")}(new iPe(ze),Ne),new FQt[q](Ne.buffer))),Me.then(ze=>{for(let Ve=ce.length-1;Ve>=0;Ve--)switch(ce[Ve]){case"delta_filter":jQt(ze,K);break;case"zigzag_filter":NQt(ze);break;case"bitshuffle_filter":kQt(ze,q);break;default:throw new Tj(`Unhandled filter "${ce[Ve]}"`)}return{layerName:T,blockIndex:X,data:ze}}).catch(ze=>{throw ze})}))},Vr(urt,"MRTDecodingBatch",{omit:["_onCancel","_onComplete"]}),Vr(mne,"MapboxRasterTile"),Vr(drt,"MapboxRasterLayer",{omit:["_blocksInProgress"]});const hrt=[Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array],Uf=new Uint32Array(96);class oPe{static from(f){if(!f||f.byteLength===void 0||f.buffer)throw new Error("Data must be an instance of ArrayBuffer or SharedArrayBuffer.");const[b,S]=new Uint8Array(f,0,2);if(b!==219)throw new Error("Data does not appear to be in a KDBush format.");const T=S>>4;if(T!==1)throw new Error(`Got v${T} data when expected v1.`);const D=hrt[15&S];if(!D)throw new Error("Unrecognized array type.");const[F]=new Uint16Array(f,2,1),[q]=new Uint32Array(f,4,1);return new oPe(q,F,D,void 0,f)}constructor(f,b=64,S=Float64Array,T=ArrayBuffer,D){if(isNaN(f)||f<0)throw new Error(`Unexpected numItems value: ${f}.`);this.numItems=+f,this.nodeSize=Math.min(Math.max(+b,2),65535),this.ArrayType=S,this.IndexArrayType=f<65536?Uint16Array:Uint32Array;const F=hrt.indexOf(this.ArrayType),q=2*f*this.ArrayType.BYTES_PER_ELEMENT,K=f*this.IndexArrayType.BYTES_PER_ELEMENT,X=(8-K%8)%8;if(F<0)throw new Error(`Unexpected typed array class: ${S}.`);if(D)this.data=D,this.ids=new this.IndexArrayType(D,8,f),this.coords=new S(D,8+K+X,2*f),this._pos=2*f,this._finished=!0;else{const ce=this.data=new T(8+q+K+X);this.ids=new this.IndexArrayType(ce,8,f),this.coords=new S(ce,8+K+X,2*f),this._pos=0,this._finished=!1,new Uint8Array(ce,0,2).set([219,16+F]),new Uint16Array(ce,2,1)[0]=b,new Uint32Array(ce,4,1)[0]=f}}add(f,b){const S=this._pos>>1;return this.ids[S]=S,this.coords[this._pos++]=f,this.coords[this._pos++]=b,S}finish(){const f=this._pos>>1;if(f!==this.numItems)throw new Error(`Added ${f} items when expected ${this.numItems}.`);return lPe(this.ids,this.coords,this.nodeSize,0,this.numItems-1,0),this._finished=!0,this}range(f,b,S,T){if(!this._finished)throw new Error("Data not yet indexed - call index.finish().");const{ids:D,coords:F,nodeSize:q}=this;Uf[0]=0,Uf[1]=D.length-1,Uf[2]=0;let K=3;const X=[];for(;K>0;){const ce=Uf[--K],pe=Uf[--K],xe=Uf[--K];if(pe-xe<=q){for(let Ve=xe;Ve<=pe;Ve++){const Je=F[2*Ve],lt=F[2*Ve+1];Je>=f&&Je<=S&<>=b&<<=T&&X.push(D[Ve])}continue}const Ne=xe+pe>>1,Me=F[2*Ne],ze=F[2*Ne+1];Me>=f&&Me<=S&&ze>=b&&ze<=T&&X.push(D[Ne]),(ce===0?f<=Me:b<=ze)&&(Uf[K++]=xe,Uf[K++]=Ne-1,Uf[K++]=1-ce),(ce===0?S>=Me:T>=ze)&&(Uf[K++]=Ne+1,Uf[K++]=pe,Uf[K++]=1-ce)}return X}within(f,b,S){const T=[];return this.withinInto(f,b,S,T),T}withinInto(f,b,S,T){if(!this._finished)throw new Error("Data not yet indexed - call index.finish().");const{ids:D,coords:F,nodeSize:q}=this;Uf[0]=0,Uf[1]=D.length-1,Uf[2]=0;let K=3,X=0;const ce=S*S;for(;K>0;){const pe=Uf[--K],xe=Uf[--K],Ne=Uf[--K];if(xe-Ne<=q){for(let Je=Ne;Je<=xe;Je++)frt(F[2*Je],F[2*Je+1],f,b)<=ce&&(T[X++]=D[Je]);continue}const Me=Ne+xe>>1,ze=F[2*Me],Ve=F[2*Me+1];frt(ze,Ve,f,b)<=ce&&(T[X++]=D[Me]),(pe===0?f-S<=ze:b-S<=Ve)&&(Uf[K++]=Ne,Uf[K++]=Me-1,Uf[K++]=1-pe),(pe===0?f+S>=ze:b+S>=Ve)&&(Uf[K++]=Me+1,Uf[K++]=xe,Uf[K++]=1-pe)}return X}}function lPe(w,f,b,S,T,D){if(T-S<=b)return;const F=S+T>>1;mrt(w,f,F,S,T,D),lPe(w,f,b,S,F-1,1-D),lPe(w,f,b,F+1,T,1-D)}function mrt(w,f,b,S,T,D){for(;T>S;){if(T-S>600){const X=T-S+1,ce=b-S+1,pe=Math.log(X),xe=.5*Math.exp(2*pe/3),Ne=.5*Math.sqrt(pe*xe*(X-xe)/X)*(ce-X/2<0?-1:1);mrt(w,f,b,Math.max(S,Math.floor(b-ce*xe/X+Ne)),Math.min(T,Math.floor(b+(X-ce)*xe/X+Ne)),D)}const F=f[2*b+D];let q=S,K=T;for(qH(w,f,S,b),f[2*T+D]>F&&qH(w,f,S,T);qF;)K--}f[2*S+D]===F?qH(w,f,S,K):(K++,qH(w,f,K,T)),K<=b&&(S=K+1),b<=K&&(T=K-1)}}function qH(w,f,b,S){cPe(w,b,S),cPe(f,2*b,2*S),cPe(f,2*b+1,2*S+1)}function cPe(w,f,b){const S=w[f];w[f]=w[b],w[b]=S}function frt(w,f,b,S){const T=w-b,D=f-S;return T*T+D*D}c.$=vx,c.A=A1,c.B=Yp,c.C=Mi,c.D=qh,c.E=Fd,c.F=Rf,c.G=Nj,c.H=Nv,c.I=Gl,c.J=QV,c.K=/^(.*)-transition$/,c.L=sPe,c.M=Zx,c.N=Ev,c.O=Er,c.P=Kt,c.Q=v,c.R=Ro,c.S=F4,c.T=hse,c.U=/^(.*)-use-theme$/,c.V=function(w,f){const b=F4(f.zoom);if(b===0)return Qk(w);const S=Jte(w),T=zMe(S),D=Qm(S.getWest())*f.worldSize,F=Qm(S.getEast())*f.worldSize,q=mp(S.getNorth())*f.worldSize,K=mp(S.getSouth())*f.worldSize,X=[D,q,0],ce=[F,q,0],pe=[D,K,0],xe=[F,K,0],Ne=A([],f.globeMatrix);return tt(X,X,Ne),tt(ce,ce,Ne),tt(pe,pe,Ne),tt(xe,xe,Ne),T[0]=O4(T[0],pe,b),T[1]=O4(T[1],xe,b),T[2]=O4(T[2],ce,b),T[3]=O4(T[3],X,b),jd.fromPoints(T)},c.W=BMe,c.X=M,c.Y=y,c.Z=yx,c._=rw,c.a=async function(w,f){w.headers||(w.headers={}),w.headers.accept="image/webp,*/*";const b=await function(S){return new Promise((T,D)=>{if(S&&S.aborted)return void D(S.reason);const F=()=>{const X=Rt.shift();X?X():tn--};if(tn{S&&S.removeEventListener("abort",K),T(F)},K=()=>{const X=Rt.indexOf(q);X!==-1&&Rt.splice(X,1),D(S.reason)};S&&S.addEventListener("abort",K),Rt.push(q)})}(f);try{const{data:S,headers:T}=await fr(w,f);let D;try{D=await createImageBitmap(new Blob([new Uint8Array(S)],{type:"image/png"}))}catch(F){throw new Error(`Could not load image because of ${F.message}. Please make sure to use a supported image type such as PNG or JPEG. Note that SVGs are not supported.`,{cause:F})}return f&&f.throwIfAborted(),{data:D,headers:T}}finally{b()}},c.a$=af,c.a0=cnt,c.a1=bu,c.a2=br,c.a3=zg,c.a4=Zi,c.a5=sg,c.a6=$f,c.a7=Qm,c.a8=mp,c.a9=Q,c.aA=Ke,c.aB=det,c.aC=qse,c.aD=Ftt,c.aE=E7,c.aF=znt,c.aG=rm,c.aH=(w,f,b,S,T,D,F,q,K,X,ce,pe,xe,Ne,Me,ze,Ve,Je,lt=!1)=>{const ht=Rnt(w,f,b,S,T,D,F,q,X,ce,pe,xe,Ne,Me,ze,Ve,1,[0,0,0],[0,0,1],lt),ct={u_height_factor:-Math.pow(2,q.overscaledZ)/K.tileSize/8};return Object.assign(ht,Int(f,K,Je),ct)},c.aI=Rnt,c.aJ=U4,c.aK=450,c.aL=7,c.aM=(w,f,b,S,T,D)=>({u_matrix:w,u_edge_radius:f,u_width_scale:b,u_vertical_scale:S,u_height_type:one[T],u_base_type:one[D]}),c.aN=P,c.aO=A,c.aP=C,c.aQ=Ont,c.aR=4,c.aS=2,c.aT=_Me,c.aU=wMe,c.aV=Rr,c.aW=class{static calculate(w,f,b){const S=new Set,T=new Map,D=new Set,F=new Set;for(const K of Object.values(w))for(const[X,ce]of Object.entries(K.floors)){D.add(X),ce.isDefault&&F.add(X),ce.conflicts&&T.set(X,ce.conflicts);const pe=X===f,xe=ce.connections&&f&&ce.connections.has(f);(pe||xe)&&S.add(X)}const q=K=>{const X=T.get(K)||new Set;for(const ce of S)if((T.get(ce)||new Set).has(K)||X.has(ce))return!0;return!1};if(b)for(const K of b)D.has(K)&&(q(K)||S.add(K));for(const K of F)S.has(K)||q(K)||S.add(K);return S}},c.aX=im,c.aY=P4,c.aZ=class extends Ub{constructor(w){super(w),this.current=new Float32Array(9)}set(w,f,b){if(!this.fetchUniformLocation(w,f))return;const S=this.current;for(let T=0;T<9;T++)if(b[T]!==S[T]){S.set(b),this.gl.uniformMatrix3fv(this.location,!1,S);break}}},c.a_=an,c.aa=Tc,c.ab=bYt,c.ac=lc,c.ad=Va,c.ae=Vi,c.af=$d,c.ag=Bn,c.ah=class{constructor(w){this.specification=w}possiblyEvaluate(w,f){return zh(w.expression.evaluate(f))}interpolate(w,f,b){return{x:da(w.x,f.x,b),y:da(w.y,f.y,b),z:da(w.z,f.z,b),azimuthal:da(w.azimuthal,f.azimuthal,b),polar:da(w.polar,f.polar,b)}}},c.ai=tr,c.aj=xp,c.ak=Ch,c.al=da,c.am=Uo,c.an=65,c.ao=45,c.ap=function(w,f,b){const S=vt.fromLngLat(f),T=b.elevation?b.elevation.getAtPointOrZero(S):0;return lnt(w,S.x,S.y,T,b)},c.aq=function(w,f,b,S,T,D,F){const q=[[b,S,0],[T,S,0],[T,D,0],[b,D,0]];let K=Number.MAX_VALUE,X=-Number.MAX_VALUE;for(const ce of q){const pe=fe(tt([],ce,f));K=Math.min(K,pe),X=Math.max(X,pe)}return[tne(w,K,F.pitch),tne(w,X,F.pitch)]},c.ar=uh,c.as=lnt,c.at=OH,c.au=_a,c.av=function(){return wa++},c.aw=class{constructor(w,f,b){this.target=w,this.parent=f,this.mapId=b,this.pendingResponses=new Map,Rr(["receive"],this),this.target.addEventListener("message",this.receive,!1),this.scheduler=new mQt}send(w,f,b){const{signal:S,targetMapId:T,metadata:D}=b||{},F=Math.round(1e18*Math.random()).toString(36).substring(0,10),q=new Set;return S&&S.aborted?Promise.reject(S.reason):(this.target.postMessage({id:F,type:w,targetMapId:T,sourceMapId:this.mapId,data:Gh(f,q)},[...q]),new Promise((K,X)=>{const ce={resolve:K,reject:X,metadata:D||Knt};if(S){const pe=()=>{this.pendingResponses.delete(F),X(S.reason)};S.addEventListener("abort",pe,{once:!0}),ce.detach=()=>S.removeEventListener("abort",pe)}this.pendingResponses.set(F,ce)}))}notify(w,f,b){const{targetMapId:S}=b||{},T=new Set;this.target.postMessage({type:w,targetMapId:S,sourceMapId:this.mapId,data:Gh(f,T)},[...T])}sendCancelable(w,f,b,S){const T=new AbortController;return this.send(w,f,{...b,signal:T.signal}).then(D=>S(null,D)).catch(D=>{D.name!=="AbortError"&&S(D)}),T}getWorkerSourceActor(w){return{scheduler:this.scheduler,send:(f,b,S)=>this.send(f,b,{...S,targetMapId:w}),notify:(f,b)=>{this.notify(f,b,{targetMapId:w})},sendCancelable:(f,b,S,T)=>this.sendCancelable(f,b,{...S,targetMapId:w},T)}}receive(w){const f=w.data;if(!f)return;const b=f.id;if(!f.targetMapId||this.mapId===f.targetMapId)if(Gu(self)){const S=this.pendingResponses.get(b);this.scheduler.add(()=>{this.processTask(b,f)},S&&S.metadata||Knt)}else this.processTask(b,f)}async processTask(w,f){if(f.type===""){const T=this.pendingResponses.get(w);if(this.pendingResponses.delete(w),T){T.detach&&T.detach();try{f.error?T.reject(R0(f.error)):T.resolve(R0(f.data))}catch(D){T.reject(D)}}return}const b=new Set,S=R0(f.data);try{let T;if(this.parent[f.type])T=await this.parent[f.type](f.sourceMapId,S);else{if(!this.parent.getWorkerSource)throw new Error(`Could not find function ${f.type}`);{const D=f.type.split("."),{source:F,scope:q}=S;T=await this.parent.getWorkerSource(f.sourceMapId,{type:D[0],source:F,scope:q})[D[1]](S)}}if(!w)return;this.target.postMessage({id:w,type:"",sourceMapId:this.mapId,error:null,data:Gh(T,b)},[...b])}catch(T){this.target.postMessage({id:w,type:"",sourceMapId:this.mapId,error:Gh(T),data:null},[])}}remove(){for(const w of this.pendingResponses.values())w.detach&&w.detach(),w.reject(new DOMException("Actor removed","AbortError"));this.pendingResponses.clear(),this.scheduler.remove(),this.target.removeEventListener("message",this.receive,!1)}},c.ax=class{constructor(w){this.specification=w}possiblyEvaluate(w,f){return function([b,S]){const T=zh([1,b,S]);return{x:T.x,y:T.y,z:T.z}}(w.expression.evaluate(f))}interpolate(w,f,b){return{x:da(w.x,f.x,b),y:da(w.y,f.y,b),z:da(w.z,f.z,b)}}},c.ay=eP,c.az=D4,c.b=sy,c.b$=function(w,{x:f,y:b},S=0){return new Kt(((f-S)*w.scale-w.x)*br,(b*w.scale-w.y)*br)},c.b0=Jr,c.b1=6,c.b2=Jte,c.b3=function(w){const f=80.051129;w=Jr(w,-80.051129,f)/f*90;const b=Math.pow(Math.abs(Math.sin(_a(w))),3);return Math.round(b*(c7.length-1))},c.b4=sse,c.b5=Qk,c.b6=function(w){const f=w.pixelsPerMeter,b=f/de(1,w.center.lat),S=j(new Float64Array(16));return I(S,S,[w.point.x,w.point.y,0]),P(S,S,[b,b,f]),Float32Array.from(S)},c.b7=function(w,f,b,S){const T=f.getNorth(),D=f.getSouth(),F=f.getWest(),q=f.getEast(),K=1<0){const Me=180/S;g(Ne,Ne,[Me/X+1,0,0,0,Me/ce+1,0,-.5*Me/pe,.5*Me/xe,1])}return Ne[2]=K,Ne[5]=w.x,Ne[8]=w.y,Ne},c.b8=to,c.b9=256,c.bA=vMe,c.bB=Ms,c.bC=Sn,c.bD=Yl,c.bE=LMe,c.bF=rN,c.bG=dH,c.bH=tt,c.bI=O4,c.bJ=lr,c.bK=EYt,c.bL=G,c.bM=I,c.bN=function(){vp.isLoading()||vp.isLoaded()||Bd()!=="deferred"||Qu()},c.bO=jo,c.bP=_p,c.bQ=function(w,f){const b=[];for(const S in w)S in f||b.push(S);return b},c.bR=Wnt,c.bS=vt,c.bT=Lc,c.bU="hd_road_coverage",c.bV=function(w){const f=w.indexOf(O6);return f>=0?w.slice(0,f):w},c.bW=Mte,c.bX=NA,c.bY=nse,c.bZ=function(w,f,b=0,S=!0){const T=new Kt(b,b),D=w.sub(T),F=f.add(T),q=[D,new Kt(F.x,D.y),F,new Kt(D.x,F.y)];return S&&q.push(D.clone()),q},c.b_=function(w,f){const b=[];for(let S=0;S1)return!1;const b=f.getSource().maxzoom,S=1<1)return f;const T=S.getSource().maxzoom,D=1<{const q=this.getAtTileOffset(w,T,D,F),K=S.upVector(w.canonical,T.x,T.y);return Be(K,K,q*S.upVectorScale(w.canonical,f,b).metersToTile),K}}getForTilePoints(w,f,b,S){if(this.isUsingMockSource())return!1;const T=S7.create(this,w,S);return!!T&&(f.forEach(D=>{D[2]=this.exaggeration()*T.getElevationAt(D[0],D[1],b,!0)}),!0)}getMinMaxForTile(w){if(this.isUsingMockSource())return null;const f=this.findDEMTileFor(w);if(!f||!f.dem)return null;const b=f.dem.tree,S=f.tileID,T=1<{S(D,F)},f):S(D,F),()=>{}}return T.callbacks.push(S),T.cancel||(T.cancel=b((D,F)=>{T.result=[D,F];for(const q of T.callbacks)this.scheduler?this.scheduler.add(()=>{q(D,F)},f):q(D,F);setTimeout(()=>delete this.entries[w],3e3)})),()=>{T.result||(T.callbacks=T.callbacks.filter(D=>D!==S),T.callbacks.length||(T.cancel(),delete this.entries[w]))}}},c.cd=function(w){if("provider"in w&&!w.provider)return null;let f=w.provider;if(!f&&"url"in w&&w.url&&(f=function(T){try{const D=new URL(T).pathname.split("/").pop()||"",F=D.lastIndexOf(".");return F>=0?D.slice(F+1):""}catch{return""}}(w.url)),!f)return null;const b=Xt.TILE_PROVIDER_URLS[f];if(!b)return null;let S;try{S=new URL(b,Xt.API_URL).href}catch{return new Error(`TileProvider "${f}" has an invalid URL: "${b}"`)}return{name:f,url:S}},c.ce=Unt,c.cf=une,c.cg=_i,c.ch=function(w,f,b){const S=JSON.stringify(w.request);return w.data&&(this.deduped.entries[S]={result:[null,w.data]}),this.deduped.request(S,{type:"parseTile",renderSourceType:w.renderSourceType,zoom:w.tileZoom},T=>{const D=new AbortController;return fr(w.request,D.signal).then(({data:F,headers:q})=>{T(null,{rawData:F,vectorTile:b?void 0:new bMe(new cse(F)),headers:q})}).catch(F=>{D.signal.aborted||(jo(F)?T(null,null):T(F))}),()=>{D.abort(),T(null,null)}},f)},c.ci=Bh,c.cj=function(w){yi++,yi>la&&(w.getActor().notify("enforceCacheSizeLimit",Zn),yi=0)},c.ck=yd,c.cl=async function(w,f,b){const S=w.url&&!w.tiles?await f.transformRequest(w.url,Ro.Source,b):void 0;return{request:S,options:S?{...w,url:S.url}:w}},c.cm=function(w,f,b){return f?$nt(w,f,b):w.tiles&&w.tiles.length>0?{tiles:w.tiles}:new Error('TileJSON is missing required "tiles" property')},c.cn=async function(w,f){const b=Ynt.get(w);if(b)return b;const S=nPe.get(w);if(S!==void 0)return S;const T=self.__mapboxImport(f).catch(D=>{throw new Error(`TileProvider "${w}" failed to load: ${D instanceof Error?D.message:String(D)}`)}).then(D=>{const F=D.default;if(typeof F!="function")throw new Error(`TileProvider "${w}" module must default-export a class`);if(typeof F.prototype.loadTile!="function")throw new Error(`TileProvider "${w}" class must have a loadTile method`);return Ynt.set(w,F),F}).finally(()=>{nPe.delete(w)});return nPe.set(w,T),T},c.co=class{constructor(w,f){this.context=w,this.texture=f}bind(w,f){const{context:b}=this,{gl:S}=b;S.bindTexture(S.TEXTURE_2D,this.texture),w!==this.minFilter&&(S.texParameteri(S.TEXTURE_2D,S.TEXTURE_MAG_FILTER,w),S.texParameteri(S.TEXTURE_2D,S.TEXTURE_MIN_FILTER,w),this.minFilter=w),f!==this.wrapS&&(S.texParameteri(S.TEXTURE_2D,S.TEXTURE_WRAP_S,f),S.texParameteri(S.TEXTURE_2D,S.TEXTURE_WRAP_T,f),this.wrapS=f)}},c.cp=Ce,c.cq=function(w,f,b,S){for(;f>1;w[T]<=S?f=T+1:b=T}return f},c.cr=function(w,f,b,S){for(;f>1;w[T]{f.onloadstart=()=>b(),f.onerror=()=>S(new Error(`Could not load video: ${w.join(", ")}`))}),f},c.cx=Mst,c.cy=zst,c.cz=W,c.d=class{constructor(w){this.cache=new Map,this.textures=new Map,this.textureAccessTimes=new Map,this.textureMemoryUsed=0,this.maxTextureMemory=1024*(w&&w.maxTextureMemoryMB?w.maxTextureMemoryMB:256)*1024,this.currentFrameAtlases=new Set,this.finalizationRegistry=new FinalizationRegistry(f=>{this.cache.delete(f),this.clearExpiredTextures()})}beginFrame(){this.currentFrameAtlases.clear()}calculateTextureMemory(w){return w.image?Math.ceil(w.image.width*w.image.height*4*(w.patternPositions.size>0?1.33:1)):0}evictTexture(w){const f=this.textures.get(w);if(f){const b=this.calculateTextureMemory(w);f.destroy(),this.textures.delete(w),this.textureAccessTimes.delete(w),this.textureMemoryUsed-=b,w.uploaded=!1}}evictTexturesIfNeeded(w){for(;this.textureMemoryUsed+w>this.maxTextureMemory&&this.textures.size>0;){let f=null,b=1/0;for(const[S]of this.textures.entries()){if(this.currentFrameAtlases.has(S))continue;const T=this.textureAccessTimes.get(S)||0;T({u_cutoff_params:new P4(w)}),c.dJ=w=>({u_light_matrix_0:new sg(w),u_light_matrix_1:new sg(w),u_fade_range:new zg(w),u_shadow_normal_offset:new $f(w),u_shadow_intensity:new Zi(w),u_shadow_texel_size:new Zi(w),u_shadow_map_resolution:new Zi(w),u_shadow_direction:new $f(w),u_shadow_bias:new $f(w),u_shadowmap_0:new im(w),u_shadowmap_1:new im(w)}),c.dK=Int,c.dL=ret,c.dM=L6e,c.dN=Gp,c.dO=Ef,c.dP=function(w,f){const b=[0,0,0];return tt(b,b,sse(Qk(f.canonical))),tt(b,b,w),b},c.dQ=O0,c.dR=function(w,f,b,S,T,D){const{width:F,height:q}=S.imageManager.getPixelSize(f),K=Math.pow(2,D.tileID.overscaledZ),X=D.tileSize*Math.pow(2,S.transform.tileZoom)/K,ce=X*(D.tileID.canonical.x+D.tileID.wrap*K),pe=X*D.tileID.canonical.y;return{u_image:0,u_pattern_tl:b.tl,u_pattern_br:b.br,u_texsize:[F,q],u_pattern_size:b.displaySize,u_pattern_units_to_pixels:T?[S.transform.width,-1*S.transform.height]:[1/IH(D,1,S.transform.tileZoom),1/IH(D,1,S.transform.tileZoom)],u_pixel_coord_upper:[ce>>16,pe>>16],u_pixel_coord_lower:[65535&ce,65535&pe]}},c.dS=w=>({u_matrix:new sg(w),u_texsize:new zg(w),u_pixels_to_tile_units:new gMe(w),u_device_pixel_ratio:new Zi(w),u_width_scale:new Zi(w),u_floor_width_scale:new Zi(w),u_image:new im(w),u_units_to_pixels:new zg(w),u_tile_units_to_pixels:new Zi(w),u_alpha_discard_threshold:new Zi(w),u_trim_offset:new zg(w),u_trim_fade_range:new zg(w),u_trim_gradient_mix_range:new zg(w),u_trim_color:new P4(w),u_zbias_factor:new Zi(w),u_tile_to_meter:new Zi(w),u_ground_shadow_factor:new $f(w),u_pattern_transition:new Zi(w),u_opacity_multiplier:new Zi(w)}),c.dT=w=>({u_matrix:new sg(w),u_pixels_to_tile_units:new gMe(w),u_device_pixel_ratio:new Zi(w),u_width_scale:new Zi(w),u_floor_width_scale:new Zi(w),u_units_to_pixels:new zg(w),u_dash_image:new im(w),u_gradient_image:new im(w),u_border_gradient_image:new im(w),u_image_height:new Zi(w),u_texsize:new zg(w),u_tile_units_to_pixels:new Zi(w),u_alpha_discard_threshold:new Zi(w),u_trim_offset:new zg(w),u_trim_fade_range:new zg(w),u_trim_gradient_mix_range:new zg(w),u_trim_color:new P4(w),u_zbias_factor:new Zi(w),u_road_view_depth_bias:new Zi(w),u_road_clip_to_view:new P4(w),u_tile_to_meter:new Zi(w),u_ground_shadow_factor:new $f(w),u_opacity_multiplier:new Zi(w)}),c.dU=w=>({u_color:new pMe(w),u_matrix:new sg(w),u_overlay:new im(w),u_overlay_scale:new Zi(w)}),c.dV=w=>({u_camera_to_center_distance:new Zi(w),u_extrude_scale:new gMe(w),u_device_pixel_ratio:new Zi(w),u_matrix:new sg(w),u_inv_rot_matrix:new sg(w),u_merc_center:new zg(w),u_tile_id:new $f(w),u_zoom_transition:new Zi(w),u_up_dir:new $f(w),u_emissive_strength:new Zi(w)}),c.dW=w=>({u_matrix:new sg(w),u_lightpos:new $f(w),u_lightintensity:new Zi(w),u_lightcolor:new $f(w),u_vertical_gradient:new Zi(w),u_height_factor:new Zi(w),u_edge_radius:new Zi(w),u_width_scale:new Zi(w),u_ao:new zg(w),u_height_type:new im(w),u_base_type:new im(w),u_tile_id:new $f(w),u_zoom_transition:new Zi(w),u_inv_rot_matrix:new sg(w),u_merc_center:new zg(w),u_up_dir:new $f(w),u_height_lift:new Zi(w),u_image:new im(w),u_texsize:new zg(w),u_pixel_coord_upper:new zg(w),u_pixel_coord_lower:new zg(w),u_tile_units_to_pixels:new Zi(w),u_opacity:new Zi(w),u_pattern_transition:new Zi(w)}),c.dX=w=>({u_matrix:new sg(w),u_lightpos:new $f(w),u_lightintensity:new Zi(w),u_lightcolor:new $f(w),u_vertical_gradient:new Zi(w),u_opacity:new Zi(w),u_edge_radius:new Zi(w),u_width_scale:new Zi(w),u_ao:new zg(w),u_height_type:new im(w),u_base_type:new im(w),u_tile_id:new $f(w),u_zoom_transition:new Zi(w),u_inv_rot_matrix:new sg(w),u_merc_center:new zg(w),u_up_dir:new $f(w),u_height_lift:new Zi(w),u_flood_light_color:new $f(w),u_vertical_scale:new Zi(w),u_flood_light_intensity:new Zi(w),u_ground_shadow_factor:new $f(w),u_front_cutoff_params:new $f(w)}),c.dY=H6e,c.dZ=DH,c.d_=ent,c.da=Kl,c.db=mn,c.dc=up,c.dd=zo,c.de=Gm,c.df=function(w){return w.includes(O6)},c.dg=function(w){const f=w.lastIndexOf(O6);return f>=0?w.slice(f+1):""},c.dh=function(w,f={}){const b=f.type&&!f.array&&Array.isArray(w)?{type:f.type,"property-type":"data-constant"}:void 0;return R1(w===null||typeof w!="object"||Array.isArray(w)?w:["literal",w],b)},c.di=function(w){const f=[],b=w.id;return b===void 0&&f.push({message:`layers.${b}: missing required property "id"`}),w.render===void 0&&f.push({message:`layers.${b}: missing required method "render"`}),w.renderingMode&&w.renderingMode!=="2d"&&w.renderingMode!=="3d"&&f.push({message:`layers.${b}: property "renderingMode" must be either "2d" or "3d"`}),f},c.dj=function(w,f,b,S){return w.type==="custom"?new LXt(w,f):new uQt[w.type](w,f,b,S)},c.dk=Il,c.dl=class extends J6{constructor(w,f){super(w._vectorTileFeature,w._z,w._x,w._y,w.id),w.state&&(this.state={...w.state}),this.target=f.target,this.namespace=f.namespace,f.properties&&(this.properties=f.properties),this.target&&("featuresetId"in this.target&&!this.target.importId||"layerId"in this.target)&&(this.source=w.source,this.sourceLayer=w.sourceLayer,this.layer=w.layer)}toJSON(){const w=super.toJSON();return w.target=this.target,w.namespace=this.namespace,w}},c.dm=cu,c.dn=Fnt,c.dp=function(){return{API_URL:Xt.API_URL,DRACO_URL:Xt.DRACO_URL,MESHOPT_URL:Xt.MESHOPT_URL,MESHOPT_SIMD_URL:Xt.MESHOPT_SIMD_URL,BUILDING_GEN_URL:Xt.BUILDING_GEN_URL}},c.dq=pMe,c.dr=me,c.ds=Mu,c.dt=function(w,f,b){const S=F4(b.zoom),T=w.style.map._antialias,D=w.terrain&&w.terrain.exaggeration()>0;return S===0&&!T&&!D},c.du=function(w,f,b){const S=j(new Float64Array(16)),T=(f/(1<{if(!Me)return null;const Ct=F4(pe.zoom);return Ct===0?null:{t:Ct,invMatrix:pe.projection.createInversionMatrix(pe,X.canonical),mercCenter:[Qm(pe.center.lng),mp(pe.center.lat)]}})(),Ve=[256/b.width*2+1,256/b.height*2+1],Je=S?w.text.dynamicLayoutVertexArray:w.icon.dynamicLayoutVertexArray;Je.clear();let lt=null;Me&&(lt=S?w.text.globeExtVertexArray:w.icon.globeExtVertexArray);const ht=w.lineVertexArray,ct=S?w.text.placedSymbolArray:w.icon.placedSymbolArray,xt=b.transform.width/b.transform.height;let kt,es=!1;for(let Ct=0;Ct{const F=w.transform,q=F.projection.name==="globe";let K;if(D.paint.get("circle-pitch-alignment")==="map")if(q){const ce=ret(F.zoom,f.canonical)*F._pixelsPerMercatorPixel;K=Float32Array.from([ce,0,0,ce])}else K=F.calculatePixelsToTileUnitsMatrix(b);else K=new Float32Array([F.pixelsToGLUnits[0],0,0,F.pixelsToGLUnits[1]]);const X={u_camera_to_center_distance:w.transform.getCameraToCenterDistance(F.projection),u_matrix:w.translatePosMatrix(f.projMatrix,b,D.paint.get("circle-translate"),D.paint.get("circle-translate-anchor")),u_device_pixel_ratio:qt.devicePixelRatio,u_extrude_scale:K,u_inv_rot_matrix:CXt,u_merc_center:[0,0],u_tile_id:[0,0,0],u_zoom_transition:0,u_up_dir:[0,0,0],u_emissive_strength:D.paint.get("circle-emissive-strength")};if(q){X.u_inv_rot_matrix=S,X.u_merc_center=T,X.u_tile_id=[f.canonical.x,f.canonical.y,1<{const ce=w.transform,pe=ce.pitch<15?da(.07,.7,Jr((14-ce.zoom)/5,0,1)):.07,xe=b.paint.get("line-trim-color-use-theme").constantOr("default")==="none";return{u_matrix:yst(w,f,b,S),u_texsize:f.imageAtlasTexture?f.imageAtlasTexture.size:[0,0],u_pixels_to_tile_units:ce.calculatePixelsToTileUnitsMatrix(f),u_device_pixel_ratio:T,u_width_scale:D,u_floor_width_scale:F,u_image:0,u_tile_units_to_pixels:xst(f,ce),u_units_to_pixels:[1/ce.pixelsToGLUnits[0],1/ce.pixelsToGLUnits[1]],u_alpha_discard_threshold:0,u_trim_offset:q,u_trim_fade_range:b.paint.get("line-trim-fade-range"),u_trim_gradient_mix_range:[1,1],u_trim_color:b.paint.get("line-trim-color").toPremultipliedRenderColor(xe?null:b.lut).toArray01(),u_zbias_factor:pe,u_tile_to_meter:mt(f.tileID.canonical,0),u_ground_shadow_factor:K,u_pattern_transition:X,u_opacity_multiplier:1}},c.e6=(w,f,b,S,T,D,F,q,K,X)=>{const ce=w.transform,pe=ce.calculatePixelsToTileUnitsMatrix(f),xe=b.paint.get("line-trim-color-use-theme").constantOr("default")==="none",Ne=ce.pitch<15?da(.07,.7,Jr((14-ce.zoom)/5,0,1)):.07;return{u_matrix:yst(w,f,b,S),u_pixels_to_tile_units:pe,u_device_pixel_ratio:D,u_width_scale:F,u_floor_width_scale:q,u_units_to_pixels:[1/ce.pixelsToGLUnits[0],1/ce.pixelsToGLUnits[1]],u_dash_image:0,u_gradient_image:1,u_border_gradient_image:2,u_image_height:T,u_texsize:bst(b)&&f.lineAtlasTexture?f.lineAtlasTexture.size:[0,0],u_tile_units_to_pixels:xst(f,w.transform),u_alpha_discard_threshold:0,u_trim_offset:K,u_trim_fade_range:b.paint.get("line-trim-fade-range"),u_trim_gradient_mix_range:[1,1],u_trim_color:b.paint.get("line-trim-color").toPremultipliedRenderColor(xe?null:b.lut).toArray01(),u_zbias_factor:Ne,u_road_view_depth_bias:0,u_road_clip_to_view:[0,0,0,0],u_tile_to_meter:mt(f.tileID.canonical,0),u_ground_shadow_factor:X,u_opacity_multiplier:1}},c.e7=fa,c.e8=MH,c.e9=5,c.eA=function(w,f,b){return w[0]=f[0]/b[0],w[1]=f[1]/b[1],w[2]=f[2]/b[2],w},c.eB=rt,c.eC=Z,c.eD=N,c.eE=Ge,c.eF=jd,c.eG=Re,c.eH=ve,c.eI=function([w,f,b]){const S=Math.hypot(w,f,b),T=Math.atan2(w,b),D=.5*Math.PI-Math.acos(-f/S);return new W($o(T),$o(D))},c.eJ=Ye,c.eK=st,c.eL=f6e,c.eM=Xt,c.eN=$r,c.eO=xr,c.eP=G6e,c.eQ=class{constructor(w,f,b){this._transformRequestFn=w,this._customAccessToken=f,this._silenceAuthErrors=!!b,this._createSkuToken()}_createSkuToken(){const w=function(){let f="";for(let b=0;b<10;b++)f+="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"[Math.floor(62*Math.random())];return{token:["1",yn,f].join(""),tokenExpiresAt:Date.now()+432e5}}();this._skuToken=w.token,this._skuTokenExpiresAt=w.tokenExpiresAt}_isSkuTokenExpired(){return Date.now()>this._skuTokenExpiresAt}async transformRequest(w,f,b){if(!this._transformRequestFn)return{url:w};const S=b?{signal:b}:{};return await this._transformRequestFn(w,f,S)||{url:w}}normalizeStyleURL(w,f){if(!_i(w))return w;const b=ro(w);return b.params.push(`sdk=js-${d}`),b.path=`/styles/v1${b.path}`,this._makeAPIURL(b,this._customAccessToken||f)}normalizeGlyphsURL(w,f){if(!_i(w))return w;const b=ro(w);return b.path=`/fonts/v1${b.path}`,this._makeAPIURL(b,this._customAccessToken||f)}normalizeModelURL(w,f){if(!_i(w))return w;const b=ro(w);return b.path=`/models/v1${b.path}`,this._makeAPIURL(b,this._customAccessToken||f)}normalizeSourceURL(w,f,b,S){if(!_i(w))return w;const T=ro(w);return T.path=`/v4/${T.authority}.json`,T.params.push("secure"),b&&T.params.push(`language=${b}`),S&&T.params.push(`worldview=${S}`),this._makeAPIURL(T,this._customAccessToken||f)}normalizeIconsetURL(w,f){const b=ro(w);return _i(w)?(b.path=`/styles/v1${b.path}/iconset.pbf`,this._makeAPIURL(b,this._customAccessToken||f)):pc(b)}normalizeSpriteURL(w,f,b,S){const T=ro(w);return _i(w)?(T.path=`/styles/v1${T.path}/sprite${f}${b}`,this._makeAPIURL(T,this._customAccessToken||S)):(T.path+=`${f}${b}`,pc(T))}normalizeTileURL(w,f,b){if(this._isSkuTokenExpired()&&this._createSkuToken(),w&&!_i(w))return w;const S=ro(w);S.path=S.path.replace(xa,(f||b&&S.authority!=="raster"&&b===512?"@2x":"")+".webp"),S.authority==="raster"?S.path=`/${Xt.RASTER_URL_PREFIX}${S.path}`:S.authority==="rasterarrays"?S.path=`/${Xt.RASTERARRAYS_URL_PREFIX}${S.path}`:S.authority==="3dtiles"?S.path=`/${Xt.TILES3D_URL_PREFIX}${S.path}`:(S.path=S.path.replace(Oa,"/"),S.path=`/${Xt.TILE_URL_VERSION}${S.path}`);const T=this._customAccessToken||function(D){for(const F of D){const q=F.match(Ki);if(q)return q[1]}return null}(S.params)||Xt.ACCESS_TOKEN;return Xt.REQUIRE_ACCESS_TOKEN&&T&&this._skuToken&&S.params.push(`sku=${this._skuToken}`),this._makeAPIURL(S,T)}canonicalizeTileURL(w,f){const b=ro(w);if(!Ri.test(b.path)||!jl.test(b.path))return w;let S="mapbox://";b.path.startsWith("/raster/v1/")?S+=`raster/${b.path.replace(`/${Xt.RASTER_URL_PREFIX}/`,"")}`:b.path.startsWith("/rasterarrays/v1/")?S+=`rasterarrays/${b.path.replace(`/${Xt.RASTERARRAYS_URL_PREFIX}/`,"")}`:S+=`tiles/${b.path.replace(`/${Xt.TILE_URL_VERSION}/`,"")}`;let T=b.params;return f&&(T=T.filter(D=>!D.match(Ki))),T.length&&(S+=`?${T.join("&")}`),S}canonicalizeTileset(w,f){const b=!!f&&_i(f),S=[];for(const T of w.tiles||[])so(T)?S.push(this.canonicalizeTileURL(T,b)):S.push(T);return S}_makeAPIURL(w,f){const b="See https://docs.mapbox.com/api/overview/#access-tokens-and-token-scopes",S=ro(Xt.API_URL);if(w.protocol=S.protocol,w.authority=S.authority,w.protocol==="http"){const T=w.params.indexOf("secure");T>=0&&w.params.splice(T,1)}if(S.path!=="/"&&(w.path=`${S.path}${w.path}`),!Xt.REQUIRE_ACCESS_TOKEN)return pc(w);if(f=f||Xt.ACCESS_TOKEN,!this._silenceAuthErrors){if(!f)throw new Error(`An API access token is required to use Mapbox GL. ${b}`);if(f[0]==="s")throw new Error(`Use a public access token (pk.*) with Mapbox GL, not a secret access token (sk.*). ${b}`)}return w.params=w.params.filter(T=>!T.includes("access_token")),w.params.push(`access_token=${f||""}`),pc(w)}},c.eR=Nh,c.eS=function(w,f){f?Pu.add(w):Pu.delete(w)},c.eT=kl,c.eU=Tf,c.eV=Rc,c.eW=$c,c.eX=yu,c.eY=lu,c.eZ=Ku,c.e_=function(w){Pu.delete(w)},c.ea=IXt,c.eb=Nr,c.ec=function(w,f){var b=Math.sin(f),S=Math.cos(f);return w[0]=S,w[1]=0,w[2]=-b,w[3]=0,w[4]=0,w[5]=1,w[6]=0,w[7]=0,w[8]=b,w[9]=0,w[10]=S,w[11]=0,w[12]=0,w[13]=0,w[14]=0,w[15]=1,w},c.ed=function(w,f){var b=Math.sin(f),S=Math.cos(f);return w[0]=1,w[1]=0,w[2]=0,w[3]=0,w[4]=0,w[5]=S,w[6]=b,w[7]=0,w[8]=0,w[9]=-b,w[10]=S,w[11]=0,w[12]=0,w[13]=0,w[14]=0,w[15]=1,w},c.ee=function(w,f){return w[0]=f[0],w[1]=f[1],w[2]=f[2],w[3]=f[4],w[4]=f[5],w[5]=f[6],w[6]=f[8],w[7]=f[9],w[8]=f[10],w},c.ef=p,c.eg=bl,c.eh=1,c.ei=C7,c.ej=0,c.ek=uu,c.el=function(w,f,b,S,T){return Jr((w-f)/(b-f)*(T-S)+S,S,T)},c.em=fe,c.en=us,c.eo=function(w,f){var b=f[0],S=f[1],T=f[2],D=f[3],F=f[4],q=f[5],K=f[6],X=f[7],ce=f[8],pe=ce*F-q*X,xe=-ce*D+q*K,Ne=X*D-F*K,Me=b*pe+S*xe+T*Ne;return Me?(w[0]=pe*(Me=1/Me),w[1]=(-ce*S+T*X)*Me,w[2]=(q*S-T*F)*Me,w[3]=xe*Me,w[4]=(ce*b-T*K)*Me,w[5]=(-q*b+T*D)*Me,w[6]=Ne*Me,w[7]=(-X*b+S*K)*Me,w[8]=(F*b-S*D)*Me,w):null},c.ep=ao,c.eq=class{constructor(){this._updateTime=0,this._sourceIds=[],this._activeRegions=[],this._prevRegions=[],this._globalClipBounds={min:new Kt(1/0,1/0),max:new Kt(-1/0,-1/0)}}clear(){this._activeRegions.length>0&&++this._updateTime,this._activeRegions=[],this._prevRegions=[]}get updateTime(){return this._updateTime}getReplacementRegionsForTile(w,f=!1){const b=yet(new Kt(0,0),new Kt(br,br),w),S=[];if(f&&!VMe(b,this._globalClipBounds))return S;for(const T of this._activeRegions){if(T.hiddenByOverlap||!VMe(b,T))continue;const D=HYt(T.min,T.max,w);S.push({min:D.min,max:D.max,sourceId:this._sourceIds[T.priority],footprint:T.footprint,footprintTileId:T.tileId,order:T.order,clipMask:T.clipMask,clipScope:T.clipScope})}return S}setSources(w){this._setSources(w.map(f=>({getSourceId:()=>f.cache.id,getFootprints:()=>{const b=[];for(const S of f.cache.getVisibleCoordinates()){const T=f.cache.getTile(S).buckets[f.layer];T&&T.updateFootprints(S.toUnwrapped(),b)}return b},getOrder:()=>f.order,getClipMask:()=>f.clipMask,getClipScope:()=>f.clipScope})))}_addSource(w){const f=w.getFootprints();if(f.length===0)return;const b=w.getOrder(),S=w.getClipMask(),T=w.getClipScope();for(const D of f){if(!D.footprint)continue;const F=yet(D.footprint.min,D.footprint.max,D.id);this._activeRegions.push({min:F.min,max:F.max,hiddenByOverlap:!1,priority:this._sourceIds.length,tileId:D.id,footprint:D.footprint,order:b,clipMask:S,clipScope:T})}this._sourceIds.push(w.getSourceId())}_computeReplacement(){this._activeRegions.sort((f,b)=>f.priority-b.priority||ose(f.min,b.min)||ose(f.max,b.max)||f.order-b.order||f.clipMask-b.clipMask||function(S,T){const D=(F,q)=>F+q;return S.length-T.length||S.reduce(D,"").localeCompare(T.reduce(D,""))}(f.clipScope,b.clipScope));let w=this._activeRegions.length!==this._prevRegions.length;if(!w){let f=0;for(;!w&&f!==this._activeRegions.length;){const b=this._activeRegions[f],S=this._prevRegions[f];w=b.priority!==S.priority||!xet(b,S)||b.order!==S.order||b.clipMask!==S.clipMask||!Er(b.clipScope,S.clipScope),this._activeRegions[f].hiddenByOverlap=S.hiddenByOverlap,++f}}if(w){++this._updateTime;for(const b of this._activeRegions)b.order!==pH&&(this._globalClipBounds.min.x=Math.min(this._globalClipBounds.min.x,b.min.x),this._globalClipBounds.min.y=Math.min(this._globalClipBounds.min.y,b.min.y),this._globalClipBounds.max.x=Math.max(this._globalClipBounds.max.x,b.max.x),this._globalClipBounds.max.y=Math.max(this._globalClipBounds.max.y,b.max.y));const f=b=>{const S=this._activeRegions;if(b>=S.length)return b;const T=S[b].priority;for(;b1){let b=0,S=f(b);for(;b!==S;){let T=b;const D=b;for(;T!==S;){const F=this._activeRegions[T];F.hiddenByOverlap=!1;for(let q=0;q=0;f--)this._addSource(w[f]);this._computeReplacement()}},c.er=pH,c.es=class{constructor(w){this._createGrid(w),this._createPoles(w)}destroy(){this._poleIndexBuffer.destroy(),this._gridBuffer.destroy(),this._gridIndexBuffer.destroy(),this._poleNorthVertexBuffer.destroy(),this._poleSouthVertexBuffer.destroy();for(const w of this._poleSegments)w.destroy();for(const w of this._gridSegments)w.withSkirts.destroy(),w.withoutSkirts.destroy()}_fillGridMeshWithLods(w,f){const b=new Sn,S=new Va,T=[],D=w+1+2,F=f[0]+1,q=f[0]+1+(1+f.length),K=(X,ce,pe)=>{let xe=X===D-1?X-2:X===0?X:X-1;return xe+=pe?24575:0,[xe,ce]};for(let X=0;X=w.byteLength)&&oi("Invalid b3dm header information.")}return ptt(w,f)},c.fC=function(w,f){const b=w.json.extensionsUsed&&w.json.extensionsUsed.includes("mbx_bvh"),S=_6e(w);for(const T of S){if(!b)for(const D of T.meshes)YZt(D);T.lights&&(T.lightMeshIndex=T.meshes.length,T.meshes.push(ZZt(T.lights,f)))}return S},c.fD=mt,c.fE=Hst,c.fF=Vr,c.fG=function(w,f){let b="";for(let S=0;S=8592&&w<=8595||w===8208||w===8229||w===8741||w>=9472&&w<=9547||w===65294||w===65309||w===65374||w===65507},c.fM=3,c.fN=fp,c.fO=EJe,c.fP=L4,c.fQ=function(w){for(const f of w)if(!ie(f.charCodeAt(0)))return!1;return!0},c.fR=J,c.fS=IMe,c.fT=GJe,c.fU=XJe,c.fV=WJe,c.fW=Aet,c.fX=1,c.fY=KJe,c.fZ=YJe,c.f_=Ur,c.fa=function(w,f){if(!w||!f)throw new Error("TileProvider name and URL are required");Xt.TILE_PROVIDER_URLS[w]=qt.resolveURL(f)},c.fb=function(w){typeof w!="string"||w.length>64||!td.test(w)?oi(`Invalid SDK info "${w}"; expected a "Name/version" string. Ignoring.`):Dd=w},c.fc=Bd,c.fd=function(w,f,b=!1){if(Sa===$n.deferred||Sa===$n.loading||Sa===$n.loaded)throw new Error("setRTLTextPlugin cannot be called multiple times.");qi=qt.resolveURL(w),Sa=$n.deferred,Pr=f,Di(),b||Qu()},c.fe=function(w){Xt.BUILDING_GEN_URL=qt.resolveURL(w)},c.ff=Zs,c.fg=function(w){const f=qt.resolveURL(w);Xt.MESHOPT_URL=f,Xt.MESHOPT_SIMD_URL=f},c.fh=ps,c.fi=function(w){Xt.DRACO_URL=qt.resolveURL(w)},c.fj=ns,c.fk=function(w){const f=Ea();if(!f)return;const b=f.delete(qn);w&&b.then(()=>w()).catch(w)},c.fl=function(w){Xt.MAX_PARALLEL_IMAGE_REQUESTS=w},c.fm=function(w){Xt.API_URL=w},c.fn=function(w){Xt.ACCESS_TOKEN=w},c.fo="hd_road_elevation",c.fp=class{static parseFrom(w,f){const b=B4.parse(w);if(!b)return[];let{vertices:S,features:T}=b;const D=1/mt(f);T.sort((X,ce)=>X.id-ce.id),S.sort((X,ce)=>X.id-ce.id||X.idx-ce.idx),S=S.filter((X,ce,pe)=>ce===pe.findIndex(xe=>xe.id===X.id&&xe.idx===X.idx));const F=new Array;let q=0;const K=S.length;for(const X of T){if(X.constantHeight){F.push(new $4(X.id,X.bounds,X.constantHeight));continue}for(;q!==K&&S[q].id0&&u6e(f,w.layers[0].source,w.sourceLayerName);(S||T)&&(w.hdExt=new ett(w,S,T))},c.fw=function(w,f){const b=w.layers[0].layout.get("line-elevation-reference")==="hd-road-markup",S=!!f&&f.length>0&&u6e(f,w.layers[0].source,w.sourceLayerName);(b||S)&&(w.hdExt=new ttt(b,S))},c.fx=Wte,c.fy=function(w){const f=w.layers[0];f.type==="circle"&&f.layout.get("circle-elevation-reference")==="hd-road-markup"&&(w.hdExt=new stt)},c.fz=function(w){w.layers[0].layout.get("symbol-elevation-reference")==="hd-road-markup"&&(w.hdExt=new ntt)},c.g=gr,c.g0=Let,c.g1=QJe,c.g2=function(w,f){const b=w.stretchY||[[0,w.paddedRect.h-2]];return w.stretchX||w.stretchY?Det(w.stretchX||[[0,w.paddedRect.w-2]])*Det(b):1},c.g3=Oet,c.g4=wA,c.g5=2,c.g6=Kst,c.g7=FJe,c.g8=u6e,c.g9=function(w,f){const b=Nse(w);return b!==null&&!!(f&1<=0&&w<128)return this.pos>=this.length&&this.realloc(1),void(this.buf[this.pos++]=w);w>268435455||w<0?function(f,b){let S,T;if(f>=0?(S=f%4294967296|0,T=f/4294967296|0):(S=~(-f%4294967296),T=~(-f/4294967296),4294967295^S?S=S+1|0:(S=0,T=T+1|0)),f>=18446744073709552e3||f<-18446744073709552e3)throw new Error("Given varint doesn't fit into 10 bytes");b.realloc(10),function(D,F,q){q.buf[q.pos++]=127&D|128,D>>>=7,q.buf[q.pos++]=127&D|128,D>>>=7,q.buf[q.pos++]=127&D|128,D>>>=7,q.buf[q.pos++]=127&D|128,q.buf[q.pos]=127&(D>>>=7)}(S,0,b),function(D,F){const q=(7&D)<<4;F.buf[F.pos++]|=q|((D>>>=3)?128:0),D&&(F.buf[F.pos++]=127&D|((D>>>=7)?128:0),D&&(F.buf[F.pos++]=127&D|((D>>>=7)?128:0),D&&(F.buf[F.pos++]=127&D|((D>>>=7)?128:0),D&&(F.buf[F.pos++]=127&D|((D>>>=7)?128:0),D&&(F.buf[F.pos++]=127&D)))))}(T,b)}(w,this):(this.realloc(4),this.buf[this.pos++]=127&w|(w>127?128:0),w<=127||(this.buf[this.pos++]=127&(w>>>=7)|(w>127?128:0),w<=127||(this.buf[this.pos++]=127&(w>>>=7)|(w>127?128:0),w<=127||(this.buf[this.pos++]=w>>>7&127))))}writeSVarint(w){this.writeVarint(w<0?2*-w-1:2*w)}writeBoolean(w){this.writeVarint(+w)}writeString(w){w=String(w),this.realloc(4*w.length),this.pos++;const f=this.pos;this.pos=function(S,T,D){for(let F,q,K=0;K55295&&F<57344){if(!q){F>56319||K+1===T.length?(S[D++]=239,S[D++]=191,S[D++]=189):q=F;continue}if(F<56320){S[D++]=239,S[D++]=191,S[D++]=189,q=F;continue}F=q-55296<<10|F-56320|65536,q=null}else q&&(S[D++]=239,S[D++]=191,S[D++]=189,q=null);F<128?S[D++]=F:(F<2048?S[D++]=F>>6|192:(F<65536?S[D++]=F>>12|224:(S[D++]=F>>18|240,S[D++]=F>>12&63|128),S[D++]=F>>6&63|128),S[D++]=63&F|128)}return D}(this.buf,w,this.pos);const b=this.pos-f;b>=128&&jet(f,b,this),this.pos=f-1,this.writeVarint(b),this.pos+=b}writeFloat(w){this.realloc(4),this.dataView.setFloat32(this.pos,w,!0),this.pos+=4}writeDouble(w){this.realloc(8),this.dataView.setFloat64(this.pos,w,!0),this.pos+=8}writeBytes(w){const f=w.length;this.writeVarint(f),this.realloc(f),this.buf.set(w,this.pos),this.pos+=f}writeRawMessage(w,f){this.pos++;const b=this.pos;w(f,this);const S=this.pos-b;S>=128&&jet(b,S,this),this.pos=b-1,this.writeVarint(S),this.pos+=S}writeMessage(w,f,b){this.writeTag(w,2),this.writeRawMessage(f,b)}writePackedVarint(w,f){f.length&&this.writeMessage(w,GYt,f)}writePackedSVarint(w,f){f.length&&this.writeMessage(w,WYt,f)}writePackedBoolean(w,f){f.length&&this.writeMessage(w,ZYt,f)}writePackedFloat(w,f){f.length&&this.writeMessage(w,KYt,f)}writePackedDouble(w,f){f.length&&this.writeMessage(w,YYt,f)}writePackedFixed32(w,f){f.length&&this.writeMessage(w,XYt,f)}writePackedSFixed32(w,f){f.length&&this.writeMessage(w,QYt,f)}writePackedFixed64(w,f){f.length&&this.writeMessage(w,JYt,f)}writePackedSFixed64(w,f){f.length&&this.writeMessage(w,eZt,f)}writeBytesField(w,f){this.writeTag(w,2),this.writeBytes(f)}writeFixed32Field(w,f){this.writeTag(w,5),this.writeFixed32(f)}writeSFixed32Field(w,f){this.writeTag(w,5),this.writeSFixed32(f)}writeFixed64Field(w,f){this.writeTag(w,1),this.writeFixed64(f)}writeSFixed64Field(w,f){this.writeTag(w,1),this.writeSFixed64(f)}writeVarintField(w,f){this.writeTag(w,0),this.writeVarint(f)}writeSVarintField(w,f){this.writeTag(w,0),this.writeSVarint(f)}writeStringField(w,f){this.writeTag(w,2),this.writeString(f)}writeFloatField(w,f){this.writeTag(w,5),this.writeFloat(f)}writeDoubleField(w,f){this.writeTag(w,1),this.writeDouble(f)}writeBooleanField(w,f){this.writeVarintField(w,+f)}},c.gk=Gu,c.gl=ise,c.gm=$n,c.gn=Gnt,c.go=function(w){na(),wr!=null&&wr.then(f=>{f.keys().then(b=>{for(let S=0;Soi(T.message))}).catch(b=>oi(b.message))}).catch(f=>oi(f.message))},c.h=Km,c.i=Kp,c.j=2,c.k=gH,c.l=Ry,c.m=r7,c.n=jv,c.o=Ht,c.p=Net,c.q=T0,c.r=Fb,c.s=Us,c.t=Ob,c.u=XV,c.v=Cj,c.w=oi,c.x=Xx,c.y=I6,c.z=L0}),i(["require","./shared"],function(o,c){function d(Tt){const He=Tt?Tt.url.toString():void 0;return He?performance.getEntriesByName(He):[]}function u(Tt,He){if(Object.hasOwn(Tt.layers,c.fo))return c.fp.parseFrom(Tt.layers[c.fo],He)}function h({buckets:Tt,data:He,sourceLayerCoder:ot,canonical:At,options:Ht}){if(!Ht.elevationFeatures||Ht.elevationFeatures.length===0)return;const qt=[];for(const Xt of Object.values(Tt))if(Xt instanceof c.bA&&Xt.hdExt){const ns=Xt.hdExt.getUnevaluatedPortalGraph();ns&&qt.push(ns)}const Wt=c.fq.evaluate(qt);for(const Xt of Object.values(Tt))if(Xt instanceof c.bA&&Xt.hdExt){const ns=He.layers[ot.decode(Xt.sourceLayerIndex)];Xt.hdExt.setEvaluatedPortalGraph(Wt,ns,At,Ht.availableImages,Ht.brightness,Xt.worldview)}}function m(Tt){const He=[];for(let ot=0;ot0){let ns=!1;for(const ps of Wt[0])if(ps.x<0||ps.x>c.a2||ps.y<0||ps.y>c.a2){ns=!0;break}if(ns)continue}const Xt=Wt.length===1&&Wt[0].length===5&&Wt[0].some(ns=>ns.x<=0&&ns.y<=0)&&Wt[0].some(ns=>ns.x>=c.a2&&ns.y<=0)&&Wt[0].some(ns=>ns.x>=c.a2&&ns.y>=c.a2)&&Wt[0].some(ns=>ns.x<=0&&ns.y>=c.a2);He.push(new c.fr(qt,Xt?[]:Wt))}return He}function p(Tt,He,ot,At,Ht){const qt=c.fs(He);if(qt===null)return!1;let Wt=ot.x,Xt=ot.y;const ns=Ht??At.z;if(At.z!==ns){const ps=1<rn.map(mn=>[mn.x,mn.y]));if(c.ft([Wt,Xt],Zs))return!0}return!1}function g(Tt,He,ot,At){const Ht=He.indoorState.activeFloorsVisible;if(!He.sourceLayers)return Ht?He.indoorState.activeFloors:void 0;const qt=function(ns,ps){if(!ns)return c.w("No source layers defined in indoor specification"),ps;if(ns.size===0)return ps;const Zs=ns.difference(ps);for(const rn of Zs)c.w(`Missing source layer required in indoor specification: ${rn}`);return ps.intersection(ps)}(He.sourceLayers,new Set(Object.keys(Tt.layers))),Wt=He.indoorState,Xt=function(ns,ps,Zs,rn,mn){const qn={};for(const Zn of ps){const la=ns.layers[Zn];if(la)for(let Br=0;BrZn.map(la=>c.fu(la,rn,Zs.extent)));return qn.length===0?void 0:{type:"Polygon",coordinates:[qn[0]]}}(Tt,He);return{id:ot,isDefault:At,connections:Ht,conflicts:qt,buildings:Wt,name:Xt,zIndex:ns,geometry:ps}}function j(Tt,He){return He.every(ot=>Tt.properties&&Tt.properties[ot]!=null)}function C(Tt){return j(Tt,["type","id","name"])&&Tt.properties.type==="structure"}function A(Tt){return j(Tt,["type","id","name","z_index"])&&Tt.properties.type==="floor"}function M(Tt,He){Tt instanceof c.bA?c.fv(Tt,He):Tt instanceof c.bz?c.fw(Tt,He):Tt instanceof c.fx?c.fy(Tt):Tt instanceof c.bu&&c.fz(Tt)}function I(Tt){for(const He in Tt){const ot=Tt[He];if(ot instanceof c.bz&&ot.hdExt&&ot.hdExt.hasDeferredElevationFeatures||ot instanceof c.bu&&ot.hdExt&&ot.hdExt.hasDeferredElevationFeatures)return!0}return!1}class P{constructor(He,ot,At){this.tileID=new c.bP(He.tileID.overscaledZ,He.tileID.wrap,He.tileID.canonical.z,He.tileID.canonical.x,He.tileID.canonical.y),this.tileZoom=He.tileZoom,this.uid=He.uid,this.zoom=He.zoom,this.canonical=He.tileID.canonical,this.pixelRatio=He.pixelRatio,this.tileSize=He.tileSize,this.source=He.source,this.overscaling=this.tileID.overscaleFactor(),this.projection=He.projection,this.brightness=ot,this.worldview=At}async parse(He,ot,At){this.status="parsing";const Ht=new c.bP(At.tileID.overscaledZ,At.tileID.wrap,At.tileID.canonical.z,At.tileID.canonical.x,At.tileID.canonical.y),qt=[],Wt=ot.familiesBySource[At.source],Xt=new c.fA(Ht,At.promoteId);Xt.bucketLayerIDs=[],Xt.is3DTile=!0;const ns=await c.fB(He),ps=ns.json.extensionsUsed&&ns.json.extensionsUsed.includes("MAPBOX_mesh_features")||ns.json.asset.extras&&ns.json.asset.extras.MAPBOX_mesh_features,Zs=ns.json.extensionsUsed&&ns.json.extensionsUsed.includes("EXT_meshopt_compression"),rn=new c.ai(this.zoom,{brightness:this.brightness,worldview:this.worldview});for(const mn in Wt)for(const qn of Wt[mn]){const Zn=qn[0];Xt.bucketLayerIDs.push(qn.map(wr=>c.m(wr.id,wr.scope))),Zn.recalculate(rn,[]);const la=c.fC(ns,1/c.fD(At.tileID.canonical)),Br=new c.fE(qn,la,Ht,ps,Zs,this.brightness,Xt,this.worldview);ps||(Br.needsUpload=!0),qt.push(Br),Br.evaluate(Zn)}return this.status="done",{buckets:qt,featureIndex:Xt,collisionBoxArray:null,glyphAtlasImage:null,lineAtlas:null,imageAtlas:null,brightness:null}}}class R{constructor({actor:He,layerIndex:ot,availableImages:At,availableModels:Ht,brightness:qt,worldview:Wt}){this.actor=He,this.layerIndex=ot,this.availableImages=At,this.availableModels=Ht,this.brightness=qt,this.loading={},this.loaded={},this.worldview=Wt}async loadTile(He){const ot=He.uid,At=new AbortController,Ht=this.loading[ot]=new P(He,this.brightness,this.worldview);Ht.abort=()=>At.abort();const qt=(Xt,ns)=>{const ps=Ht.reloadCallback;ps&&(delete Ht.reloadCallback,ps(Xt,ns))};let Wt;try{Wt=(await c.cC(He.request,At.signal)).data}catch(Xt){if(delete this.loading[ot],Ht.status="done",this.loaded[ot]=Ht,At.signal.aborted)return null;throw Xt}if(delete this.loading[ot],!Wt||Wt.byteLength===0)return Ht.status="done",this.loaded[ot]=Ht,null;try{const Xt=await Ht.parse(Wt,this.layerIndex,He);return this.loaded[ot]=Ht,qt(null,Xt),Xt}catch(Xt){throw this.loaded[ot]=Ht,qt(Xt),Xt}}async reloadTile(He){const ot=this.loaded&&this.loaded[He.uid];if(ot)return ot.projection=He.projection,ot.brightness=He.brightness,ot.status==="parsing"&&await new Promise((At,Ht)=>{ot.reloadCallback=qt=>{qt?Ht(qt):At()}}),this.loadTile(He)}abortTile(He){const ot=He.uid,At=this.loading[ot];At&&(At.abort&&At.abort(),delete this.loading[ot])}removeTile(He){const ot=this.loaded,At=He.uid;ot&&ot[At]&&delete ot[At]}}function O(Tt){if(typeof Tt=="number"||typeof Tt=="boolean"||typeof Tt=="string"||Tt==null)return JSON.stringify(Tt);if(Array.isArray(Tt)){let ot="[";for(const At of Tt)ot+=`${O(At)},`;return`${ot}]`}let He="{";for(const ot of Object.keys(Tt).sort())He+=`${ot}:${O(Tt[ot])},`;return`${He}}`}function B(Tt){let He="";for(const ot of c.cD)He+=`/${O(Tt[ot])}`;return He}function U(Tt,He){return function ot(At){return typeof At=="string"&&At===He||(Array.isArray(At)?At.some(ot):!(!At||typeof At!="object")&&Object.values(At).some(ot))}(Tt)}class G{constructor(He){this.keyCache=Object.create(null),this._layers=Object.create(null),this._layerConfigs=Object.create(null),He&&this.replace(He)}replace(He,ot){this._layerConfigs=Object.create(null),this._layers=Object.create(null),this.update(He,[],ot)}update(He,ot,At){this._options=At;for(const qt of He)this._layerConfigs[qt.id]=qt,(this._layers[qt.id]=c.dj(qt,this.scope,null,this._options)).compileFilter(At),this.keyCache[qt.id]&&delete this.keyCache[qt.id];for(const qt of ot)delete this.keyCache[qt],delete this._layerConfigs[qt],delete this._layers[qt];this.familiesBySource=Object.create(null);const Ht=function(qt,Wt){const Xt=Object.create(null);for(let ps=0;psthis._layers[mn.id]),Xt=Wt[0];if(Xt.visibility==="none")continue;const ns=Xt.source||"";let ps=this.familiesBySource[ns];ps||(ps=this.familiesBySource[ns]=Object.create(null));const Zs=Xt.sourceLayer||"_geojsonTileLayer";let rn=ps[Zs];rn||(rn=ps[Zs]=[]),rn.push(Wt)}}}class H extends c.P{constructor(He,ot,At,Ht,qt){super(He,ot),this.angle=Ht,this.z=At,qt!==void 0&&(this.segment=qt)}clone(){return new H(this.x,this.y,this.z,this.angle,this.segment)}}function Y(Tt,He,ot,At,Ht){if(He.segment===void 0)return!0;let qt=He,Wt=He.segment+1,Xt=0;for(;Xt>-ot/2;){if(Wt--,Wt<0)return!1;Xt-=Tt[Wt].dist(qt),qt=Tt[Wt]}Xt+=Tt[Wt].dist(Tt[Wt+1]),Wt++;const ns=[];let ps=0;for(;XtAt;)ps-=ns.shift().angleDelta;if(ps>Ht)return!1;Wt++,Xt+=Zs.dist(rn)}return!0}function se(Tt){let He=0;for(let ot=0;otps){const Zn=(ps-ns)/qn,la=c.al(rn.x,mn.x,Zn),Br=c.al(rn.y,mn.y,Zn),wr=new H(la,Br,0,mn.angleTo(rn),Zs);return!Wt||Y(Tt,wr,Xt,Wt,He)?wr:void 0}ns+=qn}}function Q(Tt,He,ot,At,Ht,qt,Wt,Xt,ns){const ps=ee(At,qt,Wt),Zs=oe(At,Ht),rn=Zs*Wt,mn=Tt[0].x===0||Tt[0].x===ns||Tt[0].y===0||Tt[0].y===ns;return He-rn=0&&yi=0&&so=0&&mn+ps<=Zs){const _i=new H(yi,so,0,Ea,Zn);At&&!Y(Tt,_i,qt,At,Ht)||qn.push(_i)}}rn+=wr}return Xt||qn.length||Wt||(qn=te(Tt,rn/2,ot,At,Ht,qt,Wt,!0,ns)),qn}c.fF(H,"Anchor");class le{constructor(){this.scale=1,this.fontStack="",this.image=null}static forText(He,ot){const At=new le;return At.scale=He||1,At.fontStack=ot,At}static forImage(He){const ot=new le;return ot.image=He,ot}}class fe{constructor(){this.text="",this.sectionIndex=[],this.sections=[],this.imageSectionID=null}static fromFeature(He,ot,At,Ht=1){const qt=new fe;for(let Wt=0;Wt=0&&At>=He&&ve[this.text.charCodeAt(At)];At--)ot--;this.text=this.text.substring(He,ot),this.sectionIndex=this.sectionIndex.slice(He,ot)}substring(He,ot){const At=new fe;return At.text=this.text.substring(He,ot),At.sectionIndex=this.sectionIndex.slice(He,ot),At.sections=this.sections,At}toString(){return this.text}getMaxScale(){return this.sectionIndex.reduce((He,ot)=>Math.max(He,this.sections[ot].scale),0)}addTextSection(He,ot){this.text+=He.text,this.sections.push(le.forText(He.scale,He.fontStack||ot));const At=this.sections.length-1;for(let Ht=0;Ht=63743?null:++this.imageSectionID:(this.imageSectionID=57344,this.imageSectionID)}}function _e(Tt,He,ot,At,Ht,qt,Wt,Xt,ns,ps,Zs,rn,mn,qn,Zn,la=1,Br=1){const wr=fe.fromFeature(Tt,Ht,la,Br);rn===c.cL.vertical&&wr.verticalizePunctuation(mn);let Ea=[];const na=function(vi,qo,Ro,Ti,jo,Xe,Bt){if(!vi)return[];const As=[],Hs=function(fr,za,Rt,tn,yn,xr,$r){let Ca=0;for(let xa=0;xa0&&kl>pc&&(pc=kl)}else{const lu=Ro[td.fontStack];if(!lu)continue;lu[Nl]&&(yd=lu[Nl]);const rc=qo[td.fontStack];if(!rc)continue;const Ku=rc.glyphs[Nl];if(!Ku)continue;if(cd=Ku.metrics,$c=Nl!==8203?c.d1:0,$r){const gc=rc.ascender!==void 0?Math.abs(rc.ascender):0,kl=rc.descender!==void 0?Math.abs(rc.descender):0,sd=(gc+kl)*ld;edqt)&&(qt=Zn.x),(!qn||Zn.y>Wt)&&(Wt=Zn.y)}const ns=Math.min(qt-At,Wt-Ht);let ps=ns/2;const Zs=new c.fN([],Ee);if(ns===0)return new c.P(At,Ht);for(let qn=At;qnrn.d||!rn.d)&&(rn=qn,ot&&console.log("found best %d after %d probes",Math.round(1e4*qn.d)/1e4,mn)),qn.max-rn.d<=He||(ps=qn.h/2,Zs.push(new Re(qn.p.x-ps,qn.p.y-ps,ps,Tt)),Zs.push(new Re(qn.p.x+ps,qn.p.y-ps,ps,Tt)),Zs.push(new Re(qn.p.x-ps,qn.p.y+ps,ps,Tt)),Zs.push(new Re(qn.p.x+ps,qn.p.y+ps,ps,Tt)),mn+=4)}return ot&&(console.log(`num probes: ${mn}`),console.log(`best distance: ${rn.d}`)),rn.p}function Ee(Tt,He){return He.max-Tt.max}class Re{constructor(He,ot,At,Ht){this.p=new c.P(He,ot),this.h=At,this.d=function(qt,Wt){let Xt=!1,ns=1/0;for(let ps=0;psqt.y!=la.y>qt.y&&qt.x<(la.x-Zn.x)*(qt.y-Zn.y)/(la.y-Zn.y)+Zn.x&&(Xt=!Xt),ns=Math.min(ns,c.fO(qt,Zn,la))}}return(Xt?1:-1)*Math.sqrt(ns)}(this.p,Ht),this.max=this.d+this.h*Math.SQRT2}}const ke=Object.keys;function Fe(Tt){return Tt.imagePrimary!==void 0&&Tt.top!==void 0&&Tt.bottom!==void 0&&Tt.left!==void 0&&Tt.right!==void 0}function Oe(Tt){return!Tt.imagePrimary.stretchX}function Ge(Tt){return!Tt.imagePrimary.stretchY}function yt(Tt){return{width:Tt.right-Tt.left,height:Tt.bottom-Tt.top}}const tt=Number.POSITIVE_INFINITY;function ut(Tt,He,ot,At,Ht,qt){const Wt=Fe(Tt)&&Tt.collisionPadding?Tt.collisionPadding:[0,0,0,0],Xt={top:Tt.top-Wt[1],bottom:Tt.bottom+Wt[3],left:Tt.left-Wt[0],right:Tt.right+Wt[2],scaled:!1};return At!==void 0&&function(ns,ps){ns.top*=ps,ns.bottom*=ps,ns.left*=ps,ns.right*=ps,ns.scaled=!0}(Xt,At),qt&&(Xt.left+=qt[0],Xt.right+=qt[0],Xt.top+=qt[1],Xt.bottom+=qt[1]),ot&&function(ns,ps,Zs){if(!ps)return;const rn=c.au(ps),mn=new c.P(Zs?Zs[0]:0,Zs?Zs[1]:0),qn=new c.P(ns.left,ns.top),Zn=new c.P(ns.right,ns.top),la=new c.P(ns.left,ns.bottom),Br=new c.P(ns.right,ns.bottom);qn._rotateAround(rn,mn),Zn._rotateAround(rn,mn),la._rotateAround(rn,mn),Br._rotateAround(rn,mn),ns.left=Math.min(qn.x,Zn.x,la.x,Br.x),ns.right=Math.max(qn.x,Zn.x,la.x,Br.x),ns.top=Math.min(qn.y,Zn.y,la.y,Br.y),ns.bottom=Math.max(qn.y,Zn.y,la.y,Br.y)}(Xt,ot,Ht),He?{top:Math.min(He.top,Xt.top),bottom:Math.max(He.bottom,Xt.bottom),left:Math.min(He.left,Xt.left),right:Math.max(He.right,Xt.right),scaled:He.scaled||Xt.scaled}:Xt}function nt(Tt,He,ot,At,Ht,qt,Wt,Xt=1,ns,ps,Zs,rn,mn,qn,Zn,la,Br){Tt.createArrays(),Tt.tilePixelRatio=c.a2/(512*Tt.overscaling),Tt.compareText={},Tt.iconsNeedLinear=!1;const wr=Tt.layers[0].layout,Ea=Tt.layers[0]._unevaluatedLayout._values,na={};na.scaleFactor=Xt,na.textSizeScaleRange=wr.get("text-size-scale-range"),na.iconSizeScaleRange=wr.get("icon-size-scale-range");const[yi,so]=na.textSizeScaleRange,[_i,Ni]=na.iconSizeScaleRange;na.textScaleFactor=c.b0(na.scaleFactor,yi,so),na.iconScaleFactor=c.b0(na.scaleFactor,_i,Ni);const vi=Ea["text-size"],qo=Ea["icon-size"];if(Tt.textSizeData.kind==="composite"){const{minZoom:Hs,maxZoom:cn}=Tt.textSizeData;na.compositeTextSizes=[vi.possiblyEvaluate(new c.ai(Hs,{worldview:Zs}),qt),vi.possiblyEvaluate(new c.ai(cn,{worldview:Zs}),qt)]}if(Tt.iconSizeData.kind==="composite"){const{minZoom:Hs,maxZoom:cn}=Tt.iconSizeData;na.compositeIconSizes=[qo.possiblyEvaluate(new c.ai(Hs,{worldview:Zs}),qt,rn),qo.possiblyEvaluate(new c.ai(cn,{worldview:Zs}),qt,rn)]}na.layoutTextSize=vi.possiblyEvaluate(new c.ai(Wt+1,{worldview:Zs}),qt),na.layoutIconSize=qo.possiblyEvaluate(new c.ai(Wt+1,{worldview:Zs}),qt,rn),na.textMaxSize=vi.possiblyEvaluate(new c.ai(18,{worldview:Zs}),qt);const Ro=wr.get("symbol-placement"),Ti=wr.get("text-rotation-alignment")==="map"&&Ro!=="point",jo=wr.get("text-size");let Xe=!1;const Bt=[],As=mn!=null&&mn!==0;for(const Hs of Tt.features){if(As&&Hs.properties&&la&&la(Hs.properties,mn))continue;let cn=65535;if(Tt.hdExt&&Hs.properties&&Object.hasOwn(Hs.properties,c.fP)){const Nl=+Hs.properties[c.fP];if(!Number.isNaN(Nl)){const ld=Tt.hdExt.resolveRoadElevation(Hs,Nl);if(ld==="defer")continue;cn=ld}}const gr=wr.get("text-font").evaluate(Hs,{},qt).join(","),fr=jo.evaluate(Hs,{},qt)*na.textScaleFactor,za=na.layoutTextSize.evaluate(Hs,{},qt)*na.textScaleFactor,Rt=na.layoutIconSize.evaluate(Hs,{},qt,rn)*na.iconScaleFactor,tn={horizontal:{},vertical:void 0},yn=Hs.text;let xr,$r=[0,0];if(yn){const Nl=yn.toString(),ld=wr.get("text-letter-spacing").evaluate(Hs,{},qt)*c.d1,cd=wr.get("text-line-height").evaluate(Hs,{},qt)*c.d1,yd=c.fQ(Nl)?ld:0,Wu=wr.get("text-anchor").evaluate(Hs,{},qt),$c=wr.get("text-variable-anchor");if(!$c){const rc=wr.get("text-radial-offset").evaluate(Hs,{},qt);if(rc)$r=c.cN(Wu,[rc*c.d1,tt]);else{const Ku=wr.get("text-offset").evaluate(Hs,{},qt);$r=[Ku[0]*c.d1,Ku[1]*c.d1]}}let Od=Ti?"center":wr.get("text-justify").evaluate(Hs,{},qt);const yu=Ro==="point",Wm=yu?wr.get("text-max-width").evaluate(Hs,{},qt)*c.d1:1/0,lu=rc=>{Tt.allowVerticalPlacement&&c.fR(Nl)&&(tn.vertical=_e(yn,He,ot,Ht,gr,Wm,cd,Wu,rc,yd,$r,c.cL.vertical,!0,za,fr,ns,na.textScaleFactor))};if(!Ti&&$c){const rc=Od==="auto"?$c.map(gc=>c.cO(gc)):[Od];let Ku=!1;for(let gc=0;gc0?wr/ns:1;Ea&&(Tt.iconBBox=ut(Ea,Tt.iconBBox,Br,so!==1?so:void 0)),na&&(Tt.iconVerticalBBox=ut(na,Tt.iconVerticalBBox,Br+90,so!==1?so:void 0))}function wt(Tt,He,ot,At,Ht,qt,Wt,Xt){let ns=null;const ps=He.getAppearanceValueAndResolveTokens(ot,"icon-image",At,Ht,Xt);if(ps){const Zs=Tt.getResolvedImageFromTokens(ps),rn=ot.hasLayoutProperty("icon-size")?ot.getUnevaluatedLayoutProperty("icon-size"):He._unevaluatedLayout._values["icon-size"],mn=c.f$(Tt.zoom,rn,Tt.worldview,Xt),qn=c.fS(Zs,mn,rn,Ht,Tt.zoom,At,Tt.pixelRatio,Wt,Tt.worldview,Xt);ns=qt.get(qn.iconPrimary.toString())}return ns}function rt(Tt,He,ot,At,Ht,qt,Wt,Xt,ns,ps){const{appearanceTextOffset:Zs,appearanceTextRotate:rn,appearanceTextSize:mn}=c.fZ(ot,He,At,Ht,qt,Wt,Xt),qn=mn/Xt,Zn=[(Zs[0]-qt[0])*qn,(Zs[1]-qt[1])*qn],la=Zn[0]!==0||Zn[1]!==0;ns&&(Tt.textBBox=ut(ns,Tt.textBBox,rn,qn,Zs,la?Zn:void 0)),ps&&(Tt.textVerticalBBox=ut(ps,Tt.textVerticalBBox,rn+90,qn,Zs,la?Zn:void 0))}function Ft(Tt,He,ot,At,Ht,qt,Wt,Xt){if(!Tt||!Tt.usvg)return;const ns=yt(ot),ps=yt(At),Zs=Ht!=="both"&&Ht!=="width"||!Oe(ot)?1:ps.width/ns.width,rn=Ht!=="both"&&Ht!=="height"||!Ge(ot)?1:ps.height/ns.height;He.scaleSelf(Zs,rn);const mn=He.toString();qt.set(mn,He),Wt.set(mn,Tt);const{imagePosition:qn}=c.fW(mn,Tt,c.fX);Xt.set(mn,qn)}function Ut(Tt,He,ot){if(!He)return;const At=ot.get(Tt.toString()),Ht=ot.get(He.toString());At&&Ht&&(At.paddedRect.w===Ht.paddedRect.w&&At.paddedRect.h===Ht.paddedRect.h||c.w(`Mismatch in icon variant sizes: ${Tt.toString()} and ${He.toString()}`),At.usvg!==Ht.usvg&&c.w(`Mismatch in icon variant image types: ${Tt.id} and ${He.id}`))}function Is(Tt,He,ot,At,Ht,qt,Wt,Xt,ns,ps){Tt.iconAtlasPositions=ps.iconPositions;const{featureData:Zs,sizes:rn,textAlongLine:mn,symbolPlacement:qn,coveragePolygons:Zn,coverageTileZoom:la,symbolAnchorInFrcCoverage:Br}=He,wr=He.hasAnySecondaryIcon||Tt.hasAnySecondaryIcon;for(const Ea of Zs){const{shapedIcon:na,verticallyShapedIcon:yi,feature:so,shapedTextOrientations:_i,shapedText:Ni,layoutTextSize:vi,textOffset:qo,isSDFIcon:Ro,iconPrimary:Ti,iconSecondary:jo,iconTextFit:Xe,iconOffset:Bt,iconCollisionBounds:As,iconVerticalCollisionBounds:Hs,textCollisionBounds:cn,elevationFeatureIndex:gr}=Ea;xs(na,ps.iconPositions,Ti,jo),xs(yi,ps.iconPositions,Ti,jo),st(_i,ps.iconPositions),Ut(Ti,jo,ps.iconPositions),(Ni||na)&>(Tt,so,_i,na,yi,ns,rn,vi,0,qo,Ro,At,Ht,Wt,Xt,wr,Xe,Bt,mn,qn,As,Hs,cn,0,0,Zn,la,Br,gr)}ot&&Tt.generateCollisionDebugBuffers(qt,Tt.collisionBoxArray,rn.textScaleFactor),Tt.text.uboBinder&&Tt.text.uboBinder.finalize(),Tt.icon.uboBinder&&Tt.icon.uboBinder.finalize()}function xs(Tt,He,ot,At){if(!Tt)return;const Ht=He.get(ot.toString());if(Ht&&(Tt.imagePrimary=Ht),At){const qt=He.get(At.toString());Tt.imageSecondary=qt}}function st(Tt,He){for(const ot in Tt.horizontal)dt(Tt.horizontal[ot],He);dt(Tt.vertical,He)}function dt(Tt,He){if(Tt){for(const ot of Tt.positionedLines)for(const At of ot.positionedGlyphs)if(At.image!==null){const Ht=At.image.toString();At.rect=He.get(Ht).paddedRect}}}function jt(Tt,He,ot,At,Ht,qt,Wt,Xt,ns){const ps=Ns(qt.horizontal)||qt.vertical,Zs=ot.get("icon-text-fit-padding").evaluate(At,{},Ht);let rn,mn=He;return He&&ns!=="none"&&(Tt.allowVerticalPlacement&&qt.vertical&&(rn=c.fV(He,qt.vertical,ns,Zs,Xt,Wt)),ps&&(mn=c.fV(He,ps,ns,Zs,Xt,Wt))),{defaultShapedIcon:mn,verticallyShapedIcon:rn}}function gt(Tt,He,ot,At,Ht,qt,Wt,Xt,ns,ps,Zs,rn,mn,qn,Zn,la,Br,wr,Ea,na,yi,so,_i,Ni,vi,qo,Ro,Ti,jo=65535){let Xe=Wt.textMaxSize.evaluate(He,{},mn);Xe===void 0?Xe=Xt*Wt.textScaleFactor:Xe*=Wt.textScaleFactor;const Bt=Tt.layers[0].layout,As=c.d1,Hs=c.fU(Xt,Wt.textScaleFactor),cn=Ns(ot.horizontal)||ot.vertical,gr=Tt.hasAnyAppearanceLayoutProperty(["text-size","text-offset","text-rotate"]),fr=Tt.getAppearanceFeatureData(He.index);(Br!=="none"||gr)&&fr&&(fr.textShaping=cn,fr.iconTextFitPadding=Bt.get("icon-text-fit-padding").evaluate(He,{},mn),fr.fontScale=Hs,fr.textScaleFactor=Wt.textScaleFactor);const za=qn.name==="globe",Rt=Tt.tilePixelRatio*Xe/As,tn=(Oa=Tt.overscaling,Tt.zoom>18&&Oa>2&&(Oa>>=1),Math.max(c.a2/(512*Oa),1)*Bt.get("symbol-spacing")),yn=Bt.get("text-padding")*Tt.tilePixelRatio,xr=Bt.get("icon-padding")*Tt.tilePixelRatio,$r=c.au(Bt.get("text-max-angle")),Ca=Bt.get("icon-rotation-alignment")==="map"&&na!=="point",xa=tn/2;var Oa;Tt.hasAnyIconTextFit===!1&&Br!=="none"&&(Tt.hasAnyIconTextFit=!0);const jl=(Ri,Ki,Rc)=>{if(Ki.x<0||Ki.x>=c.a2||Ki.y<0||Ki.y>=c.a2||qo&&qo.length>0&&He.properties&&Ti&&Ti(qo,He.properties,Ki,mn,Ro))return;let xd=null;if(za){const{x:ro,y:pc,z:ed}=qn.projectTilePoint(Ki.x,Ki.y,Rc);xd={anchor:new H(ro,pc,ed,0,void 0),up:qn.upVector(Rc,Ki.x,Ki.y)}}(function(ro,pc,ed,Nh,xu,Dd,td,Uh,Nl,ld,cd,yd,Wu,$c,Od,yu,Wm,lu,rc,Ku,gc,kl,sd,Tf,Pu,up,Km,vu,Fl,Mf,Fd,Gl){const km=ro.addToLineVertexArray(pc,Nh);let Sm,Ig,da,Ec,Mi,Ym,ux,hx=0,uh=0,Xd=0,al=0,tl=-1,sl=-1;const Or={};let $i=c.dc("");const Qi=ed?ed.anchor:pc,kh=vu!=="none";let nd=0,Po=0;if(Nl._unevaluatedLayout.getValue("text-radial-offset")===void 0){const Sl=Nl.layout.get("text-offset").evaluate(gc,{},Pu);nd=Sl[0]*c.d1,Po=Sl[1]*c.d1}else nd=Nl.layout.get("text-radial-offset").evaluate(gc,{},Pu)*c.d1,Po=tt;if(ro.allowVerticalPlacement&&xu.vertical){const Sl=xu.vertical;if(Od)Ym=Bs(Sl),Uh&&(ux=Bs(Uh));else{const Wl=Nl.layout.get("text-rotate").evaluate(gc,{},Pu)+90;da=us(ld,Qi,pc,cd,yd,Wu,Sl,$c,Wl,yu,Gl),Uh&&(Ec=us(ld,Qi,pc,cd,yd,Wu,Uh,lu,Wl,null,Fd))}}if(Dd){const Sl=Nl.layout.get("icon-rotate").evaluate(gc,{},Pu),Wl=c.g0(Dd,Sl,sd,kh,kl.iconScaleFactor),Wp=Uh?c.g0(Uh,Sl,sd,kh,kl.iconScaleFactor):void 0;Ig=us(ld,Qi,pc,cd,yd,Wu,Dd,lu,Sl,null,Mf);const Zm=function(Yu,Kp,rm,S1,Zu,rd,Xm,If,Iu){const E0=Yu.layers[0],wi=E0.appearances;let Lf=Kp.length;if(rm&&(Lf=Math.max(Lf,rm.length)),wi.length===0)return Lf;const[wv,jv]=S1.get("icon-size-scale-range"),Ry=c.b0(1,wv,jv);for(const Nv of wi)if(Nv.hasLayoutProperty("icon-image")){const T0=wt(Yu,E0,Nv,Zu,rd,Xm,Ry,Iu);T0&&(Lf=Math.max(Lf,c.g2(T0)))}return Lf}(ro,Wl,Wp,Nl.layout,gc,Pu,ro.iconAtlasPositions,0,Tf);hx=4*Zm;const Pb=Nl.layout.get("icon-size").evaluate(gc,{},Pu,Tf),k1=kl.compositeIconSizes?kl.compositeIconSizes[0].evaluate(gc,{},Pu,Tf):0,Ib=kl.compositeIconSizes?kl.compositeIconSizes[1].evaluate(gc,{},Pu,Tf):0,_v=c.g1(ro.layerIds[0],ro.iconSizeData,Pb,Dd.imagePrimary.usvg?1:kl.iconScaleFactor,k1,Ib);ro.addSymbols(ro.icon,Wl,_v,Ku,rc,gc,void 0,ed,pc,km.lineStartIndex,km.lineLength,-1,Tf,Pu,up,Km,ro.symbolInstances.length,Zm),tl=ro.icon.placedSymbolArray.length-1,Wp&&(uh=4*Zm,ro.addSymbols(ro.icon,Wp,_v,Ku,rc,gc,c.cL.vertical,ed,pc,km.lineStartIndex,km.lineLength,-1,Tf,Pu,up,Km,ro.symbolInstances.length,Zm),sl=ro.icon.placedSymbolArray.length-1)}for(const Sl in xu.horizontal){const Wl=Sl,Wp=xu.horizontal[Wl];Sm||($i=c.dc(Wp.text),Od?Mi=Bs(Wp):Sm=us(ld,Qi,pc,cd,yd,Wu,Wp,$c,Nl.layout.get("text-rotate").evaluate(gc,{},Pu),yu,Gl));const Zm=Wp.positionedLines.length===1;if(Xd+=rs(ro,ed,pc,Wp,td,Nl,Od,gc,yu,km,xu.vertical?c.cL.horizontal:c.cL.horizontalOnly,Zm?ke(xu.horizontal):[Wl],Or,tl,kl,Tf,Pu,ro.symbolInstances.length,up),Zm)break}xu.vertical&&(al+=rs(ro,ed,pc,xu.vertical,td,Nl,Od,gc,yu,km,c.cL.vertical,["vertical"],Or,sl,kl,Tf,Pu,ro.symbolInstances.length,up));let hp=-1;const mx=(Sl,Wl)=>Sl?Math.max(Sl,Wl):Wl;hp=mx(Mi,hp),hp=mx(Ym,hp),hp=mx(ux,hp);const Pf=hp>-1?1:0;ro.glyphOffsetArray.length>=65535&&c.w("Too many glyphs being rendered in a tile. See https://github.com/mapbox/mapbox-gl-js/issues/2907"),gc.sortKey!==void 0&&ro.addToSortKeyRanges(ro.symbolInstances.length,gc.sortKey),ro.symbolInstances.emplaceBack(pc.x,pc.y,Qi.x,Qi.y,Qi.z,Or.right>=0?Or.right:-1,Or.center>=0?Or.center:-1,Or.left>=0?Or.left:-1,Or.vertical>=0?Or.vertical:-1,tl,sl,$i,Sm!==void 0?Sm:ro.collisionBoxArray.length,Sm!==void 0?Sm+1:ro.collisionBoxArray.length,da!==void 0?da:ro.collisionBoxArray.length,da!==void 0?da+1:ro.collisionBoxArray.length,Ig!==void 0?Ig:ro.collisionBoxArray.length,Ig!==void 0?Ig+1:ro.collisionBoxArray.length,Ec||ro.collisionBoxArray.length,Ec?Ec+1:ro.collisionBoxArray.length,cd,Xd,al,hx,uh,Pf,0,nd,Po,hp,0,kh?1:0,Fl)})(Tt,Ki,xd,Ri,ot,At,qt,Ht,Tt.layers[0],Tt.collisionBoxArray,He.index,He.sourceLayerIndex,Tt.index,yn,Ea,ps,0,xr,Ca,wr,He,Wt,Zs,rn,mn,Zn,la,Br,jo,yi,so,_i)};if(na==="line")for(const Ri of c.cZ(He.geometry,0,0,c.a2,c.a2)){const Ki=Q(Ri,tn,$r,ot.vertical||cn,At,As,Rt,Tt.overscaling,c.a2);for(const Rc of Ki)cn&&Ts(Tt,cn.text,xa,Rc)||jl(Ri,Rc,mn)}else if(na==="line-center"){for(const Ri of He.geometry)if(Ri.length>1){const Ki=me(Ri,$r,ot.vertical||cn,At,As,Rt);Ki&&jl(Ri,Ki,mn)}}else if(He.type==="Polygon")for(const Ri of c.f_(He.geometry,0)){const Ki=Ye(Ri,16);jl(Ri[0],new H(Ki.x,Ki.y,0,0,void 0),mn)}else if(He.type==="LineString")for(const Ri of He.geometry)jl(Ri,new H(Ri[0].x,Ri[0].y,0,0,void 0),mn);else if(He.type==="Point")for(const Ri of He.geometry)for(const Ki of Ri)jl([Ki],new H(Ki.x,Ki.y,0,0,void 0),mn)}function rs(Tt,He,ot,At,Ht,qt,Wt,Xt,ns,ps,Zs,rn,mn,qn,Zn,la,Br,wr,Ea){const na=c.g3(ot,At,ns,qt,Wt,Xt,Ht,Tt.allowVerticalPlacement,void 0,Zn.textScaleFactor),yi=qt.layout.get("text-size").evaluate(Xt,{},Br),so=Zn.compositeTextSizes?Zn.compositeTextSizes[0].evaluate(Xt,{},Br):0,_i=Zn.compositeTextSizes?Zn.compositeTextSizes[1].evaluate(Xt,{},Br):0,Ni=c.g1(Tt.layerIds[0],Tt.textSizeData,yi,Zn.textScaleFactor,so,_i);Tt.addSymbols(Tt.text,na,Ni,ns,Wt,Xt,Zs,He,ot,ps.lineStartIndex,ps.lineLength,qn,la,Br,Ea,!1,wr,na.length);for(const vi of rn)mn[vi]=Tt.text.placedSymbolArray.length-1;return 4*na.length}function Ns(Tt){for(const He in Tt)return Tt[He];return null}function us(Tt,He,ot,At,Ht,qt,Wt,Xt,ns,ps,Zs){let rn,mn,qn,Zn;if(rn=Zs?Zs.top:Wt.top,mn=Zs?Zs.bottom:Wt.bottom,qn=Zs?Zs.left:Wt.left,Zn=Zs?Zs.right:Wt.right,Fe(Wt)&&Wt.collisionPadding){const la=Wt.collisionPadding;qn-=la[0],rn-=la[1],Zn+=la[2],mn+=la[3]}if(ns){const la=new c.P(qn,rn),Br=new c.P(Zn,rn),wr=new c.P(qn,mn),Ea=new c.P(Zn,mn),na=c.au(ns);let yi=new c.P(0,0);ps&&(yi=new c.P(ps[0],ps[1])),la._rotateAround(na,yi),Br._rotateAround(na,yi),wr._rotateAround(na,yi),Ea._rotateAround(na,yi),qn=Math.min(la.x,Br.x,wr.x,Ea.x),Zn=Math.max(la.x,Br.x,wr.x,Ea.x),rn=Math.min(la.y,Br.y,wr.y,Ea.y),mn=Math.max(la.y,Br.y,wr.y,Ea.y)}return Tt.emplaceBack(He.x,He.y,He.z,ot.x,ot.y,qn,rn,Zn,mn,Xt,At,Ht,qt),Tt.length-1}function Bs(Tt){Fe(Tt)&&Tt.collisionPadding&&(Tt.top-=Tt.collisionPadding[1],Tt.bottom+=Tt.collisionPadding[3]);const He=Tt.bottom-Tt.top;return He>0?Math.max(10,He):null}function Ts(Tt,He,ot,At){const Ht=Tt.compareText;if(He in Ht){const qt=Ht[He];for(let Wt=qt.length-1;Wt>=0;Wt--)if(At.dist(qt[Wt])=He.maxzoom||He.visibility==="none")}parse(He,ot,At,Ht,qt,Wt){this._parseAfterHD(He,ot,At,Ht,qt,Wt)}_parseAfterHD(He,ot,At,Ht,qt,Wt){let Xt;if(this.status="parsing",this.data=He,this.renderSourceType===c.bR.HdRoadCoverage){const Br=He.layers[c.bU];Xt=Br&&m?m(Br):[]}this.collisionBoxArray=new c.bt;const ns=new c.g6(Object.keys(He.layers).sort()),ps=new c.fA(this.tileID,this.promoteId);ps.bucketLayerIDs=[];const Zs={},rn=new c.g7(256,256),mn={featureIndex:ps,iconDependencies:new Map,patternDependencies:new Map,glyphDependencies:{},lineAtlas:rn,availableImages:At,brightness:this.brightness,scaleFactor:this.scaleFactor,showElevationIdDebug:this.showElevationIdDebug,elevationFeatures:void 0,elevationParams:this.elevation,crossSourceElevationEnabled:this.crossSourceElevationEnabled,terrainEnabled:this.terrainEnabled,activeFloors:void 0};this.indoor&&g&&(mn.activeFloors=g(He,this.indoor,qt,this.canonical));const qn=[],Zn=ot.familiesBySource[this.source];if(this.renderSourceType===c.bR.HdRoadElevation){const Br=u&&u(He,this.canonical)||[],wr=new An({});return this.status="done",void Wt(null,{buckets:[],containsHdExt:!1,containsStandardExt:!1,featureIndex:ps,collisionBoxArray:this.collisionBoxArray,glyphAtlasImage:wr.image,lineAtlas:rn,imageAtlas:null,brightness:this.brightness,parsedElevationFeatures:Br})}if(this.deferRoadStructure=!1,this.renderSourceType!==c.bR.HdRoadCoverage&&this.frcCoverage!=null&&!this.frcCoverage.resolved&&this.frcCoverage.frcMask===null){for(const Br in Zn)if(c.g8&&c.g8(this.frcCoverage.sourceLayers,this.source,Br)){this.deferRoadStructure=!0;break}}for(const Br in Zn){const wr=He.layers[Br];if(!wr)continue;let Ea=!1,na=!1,yi=!1,so=!1;for(const Ti of Zn[Br])Ti[0].type==="symbol"?Ea=!0:Ti[0].type==="fill-extrusion"?na=!0:yi=!0,Ti[0].is3D()&&Ti[0].type!=="model"&&(so=!0);if(this.extraShadowCaster&&!so||this.renderSourceType===c.bR.Symbol&&!Ea||this.renderSourceType===c.bR.FillExtrusion&&!na||(this.renderSourceType===c.bR.Other||this.renderSourceType===c.bR.HdRoadCoverage)&&!yi)continue;const _i=this.frcCoverage!=null&&!!c.g8&&c.g8(this.frcCoverage.sourceLayers,this.source,Br);if(this.deferRoadStructure&&_i)continue;wr.version===1&&c.w(`Vector tile source "${this.source}" layer "${Br}" does not use vector tile spec v2 and therefore may have some rendering errors.`);const Ni=ns.encode(Br),vi=[],qo=this.localizableLayerIds&&this.localizableLayerIds.has(Br);let Ro=!1;for(let Ti=0,jo=0;Tic.m(As.id,As.scope)));const Bt=()=>{Ln(Ti,this.zoom,mn.brightness,At,this.worldview,mn.activeFloors);const As=Zs[jo.id]=jo.createBucket({index:Xe,layers:Ti,zoom:this.zoom,lut:this.lut,canonical:this.canonical,pixelRatio:this.pixelRatio,overscaling:this.overscaling,collisionBoxArray:this.collisionBoxArray,sourceLayerIndex:Ni,sourceLayerName:Br,sourceID:this.source,projection:this.projection.spec,tessellationStep:this.tessellationStep,styleDefinedModelURLs:Ht,worldview:this.worldview,localizable:qo,availableImages:At,maxUniformBufferBindings:this.maxUniformBufferBindings,maxUniformBlockSizeDwords:this.maxUniformBlockSizeDwords});M&&M(As,this.frcCoverage?this.frcCoverage.sourceLayers:null),As.populate(vi,mn,this.tileID.canonical,this.tileTransform)};jo.mayUse("HD")||jo.mayUse("Standard")?qn.push(jo.prepare().then(()=>Bt())):Bt()}}const la=()=>{rn.trim();const Br=!(!mn.elevationFeatures||!mn.elevationFeatures.some(Ti=>Ti.heightRange.min<0));let wr,Ea,na,yi,so,_i,Ni;const vi={type:"maybePrepare",renderSourceType:this.renderSourceType,zoom:this.zoom},qo=()=>{if(wr)return this.status="done",Wt(wr);if(this.extraShadowCaster){this.status="done";const Ti=Object.values(Zs).filter(Xe=>!Xe.isEmpty()),jo=mn.elevationFeatures;Wt(null,{buckets:Ti,containsHdExt:js(Ti),containsStandardExt:In(Ti),featureIndex:ps,collisionBoxArray:null,hasTunnelGeometry:Br,glyphAtlasImage:null,lineAtlas:null,imageAtlas:null,brightness:mn.brightness,hasDeferredElevationFeatures:!!I&&I(Zs),parsedElevationFeatures:jo,glyphMap:null,iconMap:null,glyphPositions:null})}else if(Ea&&na&&yi&&Ni){const jo=new An(Ea),Xe=new Map;for(const[As,Hs]of na.entries()){const{imagePosition:cn}=c.fW(As,Hs,c.fX);Xe.set(As,cn)}const Bt={};for(const As in Zs){const Hs=Zs[As];if(Hs instanceof c.bu){Ln(Hs.layers,this.zoom,mn.brightness,At,this.worldview,mn.activeFloors);const cn=un(this.frcCoverage,this.source,Hs.layers[0].sourceLayer);Bt[As]=nt(Hs,Ea,jo.positions,na,Xe,this.tileID.canonical,this.tileZoom,this.scaleFactor,this.pixelRatio,so,this.worldview,At,cn.frcMask,cn.polygons,cn.tileZoom,c.g9||null,p||null)}}so.size||_i.size?this.rasterizeTask=qt.sendCancelable("rasterizeImages",{scope:this.scope,iconTasks:so,patternTasks:_i},{},(As,Hs)=>{if(!As)for(const[cn,gr]of Hs.entries())na.has(cn)&&na.set(cn,Object.assign(na.get(cn),{data:gr})),yi.has(cn)&&yi.set(cn,Object.assign(yi.get(cn),{data:gr}));Ro(Bt,jo,void 0,Ni)}):Ro(Bt,jo,void 0,Ni)}},Ro=(Ti,jo,Xe,Bt)=>{const As=na.size>0||yi.size>0,Hs=Object.keys(Ti).length>0,cn=mn.elevationFeatures;if(!As&&!Hs){this.status="done";const fr=Object.values(Zs).filter(za=>!za.isEmpty());return void Wt(null,{buckets:fr,containsHdExt:js(fr),containsStandardExt:In(fr),featureIndex:ps,collisionBoxArray:this.collisionBoxArray,hasTunnelGeometry:Br,glyphAtlasImage:jo.image,lineAtlas:rn,imageAtlas:null,brightness:mn.brightness,hasDeferredRoadStructure:this.deferRoadStructure,frcCoveragePolygons:Xt,hasDeferredElevationFeatures:!!I&&I(Zs),parsedElevationFeatures:cn})}const gr=(fr,za)=>{for(const tn in Zs){const yn=Zs[tn];if(tn in Ti)Is(yn,Ti[tn],this.showCollisionBoxes,At,this.tileID.canonical,this.tileZoom,this.projection,this.brightness,na,za);else if(yn.hasPattern&&(yn instanceof c.bz||yn instanceof c.bA||yn instanceof c.aC)){Ln(yn.layers,this.zoom,mn.brightness,At,this.worldview,mn.activeFloors);const xr=Object.fromEntries(za.patternPositions);yn.addFeatures(mn,this.tileID.canonical,xr,At,this.tileTransform,this.brightness)}}this.status="done";const Rt=Object.values(Zs).filter(tn=>!tn.isEmpty());Wt(null,{buckets:Rt,containsHdExt:js(Rt),containsStandardExt:In(Rt),featureIndex:ps,collisionBoxArray:this.collisionBoxArray,hasTunnelGeometry:Br,glyphAtlasImage:jo.image,lineAtlas:rn,imageAtlas:fr,brightness:mn.brightness,hasDeferredRoadStructure:this.deferRoadStructure,frcCoveragePolygons:Xt,hasDeferredElevationFeatures:!!I&&I(Zs),parsedElevationFeatures:cn})};if(As){const fr=new Map,za=c.gb(na,fr),Rt=c.gb(yi,fr),tn=new c.gc(za,Rt,Bt,this.lut,this.scope,fr);qt.send("checkAtlasCache",{descriptor:tn,scope:this.scope}).then(yn=>{let xr,$r;if(yn)xr=new c.gd(yn.sourceHash),$r=yn;else{const Ca=new c.ge(na,yi,this.lut,Bt,this.scope);xr=Ca,$r=Ca}gr(xr,$r)}).catch(yn=>{yn.name!=="AbortError"&&c.w(`[Worker] Error checking atlas cache: ${yn.message}`);const xr=new c.ge(na,yi,this.lut,Bt,this.scope);gr(xr,xr)})}else gr(null,{iconPositions:new Map,patternPositions:new Map})};if(!this.extraShadowCaster){const Ti=c.ga(mn.glyphDependencies,Bt=>Object.keys(Bt).map(Number));Object.keys(Ti).length?qt.send("getGlyphs",{uid:this.uid,stacks:Ti},{metadata:vi}).then(Bt=>{wr||(Ea=Bt,qo())}).catch(Bt=>{wr||(wr=Bt,qo())}):Ea={},Ni=new Map;const jo=Array.from(mn.iconDependencies.keys()).map(Bt=>c.I.parse(Bt)),Xe=Array.from(mn.patternDependencies.keys()).map(Bt=>c.I.parse(Bt));jo.length||Xe.length?qt.send("getImages",{icons:jo,patterns:Xe,source:this.source,scope:this.scope,tileID:this.tileID},{metadata:vi}).then(Bt=>{if(!wr){na=new Map,yi=new Map,so=this.updateImageMapAndGetImageTaskQueue(na,Bt.images,mn.iconDependencies),_i=this.updateImageMapAndGetImageTaskQueue(yi,Bt.images,mn.patternDependencies);for(const[As,Hs]of Bt.versions.entries())Ni.set(As,Hs);qo()}}).catch(Bt=>{wr||(wr=Bt,qo())}):(na=new Map,yi=new Map,so=new Map,_i=new Map)}h&&h({buckets:Zs,data:He,sourceLayerCoder:ns,canonical:this.tileID.canonical,options:mn}),qo()};qn.length>0?Promise.allSettled(qn).then(la).catch(Wt):la()}updateParameters(He){this.scaleFactor=He.scaleFactor,this.showCollisionBoxes=He.showCollisionBoxes,this.showElevationIdDebug=He.showElevationIdDebug,this.projection=He.projection,this.brightness=He.brightness,this.tileTransform=c.bp(He.tileID.canonical,He.projection),this.extraShadowCaster=He.extraShadowCaster,this.lut=He.lut,this.worldview=He.worldview,this.indoor=He.indoor,this.frcCoverage=He.frcCoverage||null,this.elevation=He.elevation||null,this.terrainEnabled=!!He.terrainEnabled}updateImageMapAndGetImageTaskQueue(He,ot,At){const Ht=new Map;for(const qt of ot.keys()){const Wt=At.get(qt)||[];for(const Xt of Wt){const ns=Xt.toString(),ps=ot.get(Xt.id.toString());ps.usvg?Ht.has(ns)||(Ht.set(ns,Xt),He.set(ns,{...ps})):He.set(ns,ps)}}return Ht}cancelRasterize(){this.rasterizeTask&&this.rasterizeTask.abort()}}function Ln(Tt,He,ot,At,Ht,qt){const Wt=new c.ai(He,{brightness:ot,worldview:Ht,activeFloors:qt});for(const Xt of Tt)Xt.recalculate(Wt,At)}class Sr extends c.E{constructor({actor:He,layerIndex:ot,availableImages:At,availableModels:Ht,isSpriteLoaded:qt,tileProvider:Wt,brightness:Xt,maxUniformBufferBindings:ns,maxUniformBlockSizeDwords:ps}){super(),this.actor=He,this.layerIndex=ot,this.availableImages=At,this.availableModels=Ht,this.loadVectorData=c.ch,this.tileProvider=Wt,this.loading={},this.loaded={},this.deduped=new c.cc(He.scheduler),this.isSpriteLoaded=qt,this.scheduler=He.scheduler,this.brightness=Xt,this.maxUniformBufferBindings=ns,this.maxUniformBlockSizeDwords=ps}loadTileData(He,ot){if(!this.tileProvider)return this.loadVectorData(He,ot);const At=new AbortController;return this.loadTileWithProvider(this.tileProvider,He,At,ot),()=>At.abort()}async loadTileWithProvider(He,ot,At,Ht){const{z:qt,x:Wt,y:Xt}=ot.tileID.canonical;try{const ns=await He.loadTile({z:qt,x:Wt,y:Xt},{request:ot.request,signal:At.signal});if(At.signal.aborted)return;if(ns==null){const Zs=new Error("Tile not found");return Zs.status=404,Ht(Zs)}if(ns.data==null)return Ht(null,null);if(ns.data instanceof ImageBitmap)return Ht(new Error("Vector tiles require ArrayBuffer data"));const ps=new Headers;ns.expires&&ps.set("expires",ns.expires),ns.cacheControl&&ps.set("cache-control",ns.cacheControl),Ht(null,{rawData:ns.data,headers:ps})}catch(ns){if(At.signal.aborted)return;Ht(ns instanceof Error?ns:new Error(String(ns)))}}_fetchTileData(He,ot){return new Promise((At,Ht)=>{He.abort=this.loadTileData(ot,(qt,Wt)=>{qt?Ht(qt):At(Wt)})})}async _parse(He,ot){const At=!this.isSpriteLoaded;return At&&await this.once("isSpriteLoaded"),new Promise((Ht,qt)=>{const Wt=()=>He.parse(He.vectorTile,this.layerIndex,this.availableImages,this.availableModels,this.actor,(Xt,ns)=>{Xt?qt(Xt):Ht(ns)});At&&this.scheduler?this.scheduler.add(Wt,{type:"parseTile",renderSourceType:ot.renderSourceType,zoom:ot.tileZoom}):Wt()})}async loadTile(He){const ot=He.uid,At=He&&He.request,Ht=At&&At.collectResourceTiming,qt=this.loading[ot]=new jr(He);qt.maxUniformBufferBindings=this.maxUniformBufferBindings,qt.maxUniformBlockSizeDwords=this.maxUniformBlockSizeDwords;const Wt=(Zn,la)=>{const Br=qt.reloadCallback;Br&&(delete qt.reloadCallback,Zn||!la?Br(Zn,null):qt.parse(qt.vectorTile,this.layerIndex,this.availableImages,this.availableModels,this.actor,Br))};let Xt,ns;try{Xt=await this._fetchTileData(qt,He)}catch(Zn){ns=Zn}const ps=!this.loading[ot];if(delete this.loading[ot],qt.cancelRasterize(),ns||ps||!Xt){if(qt.status="done",ps||(this.loaded[ot]=qt),ns)throw ns;return null}const Zs=Xt.rawData;let rn;qt.vectorTile=Xt.vectorTile||new c.gf(new c.cB(Zs)),this.loaded=this.loaded||{},this.loaded[ot]=qt;try{rn=await this._parse(qt,He)}catch(Zn){throw Wt(Zn),Zn}if(!rn)return Wt(null,null),null;const mn={};if(Ht){const Zn=d(At);Zn.length>0&&(mn.resourceTiming=JSON.parse(JSON.stringify(Zn)))}const qn={rawTileData:Zs.slice(0),headers:Xt.headers,...rn,...mn};return Wt(null,rn),qn}async reloadTile(He){const ot=this.loaded,At=He.uid;if(ot&&ot[At])return new Promise((Ht,qt)=>{const Wt=ot[At];Wt.updateParameters(He);const Xt=(ns,ps)=>{const Zs=Wt.reloadCallback;Zs&&(delete Wt.reloadCallback,Wt.parse(Wt.vectorTile,this.layerIndex,this.availableImages,this.availableModels,this.actor,Zs)),ns?qt(ns):Ht(ps)};Wt.status==="parsing"?Wt.reloadCallback=Xt:Wt.status==="done"?Wt.vectorTile?Wt.parse(Wt.vectorTile,this.layerIndex,this.availableImages,this.availableModels,this.actor,Xt):Xt():Ht(void 0)})}abortTile(He){const ot=He.uid,At=this.loading[ot];At&&(At.abort&&At.abort(),delete this.loading[ot])}removeTile(He){const ot=this.loaded,At=He.uid;ot&&ot[At]&&delete ot[At]}}class Qn{constructor(He){this.tileProvider=He.tileProvider,this.loading={}}async loadTile(He){const ot=He.uid,At=new AbortController;if(this.loading[ot]={cancel:()=>At.abort()},this.tileProvider)return this.loadTileWithProvider(this.tileProvider,ot,He,At);try{const{data:Ht,headers:qt}=await c.cC(He.request,At.signal);if(!Ht)return null;const Wt=await this.decodeTile(ot,Ht,He.encoding);return Wt.headers=qt,Wt}catch(Ht){if(At.signal.aborted)return null;throw Ht}finally{delete this.loading[ot]}}async decodeTile(He,ot,At){const Ht=ot instanceof ImageBitmap?ot:await createImageBitmap(new Blob([new Uint8Array(ot)],{type:"image/png"})),qt=1-(Ht.width-c.gg(Ht.width))/2,Wt=qt<1,Xt=this.getImageData(Ht,qt);return Ht.close(),{dem:new c.gh(He,Xt,At,Wt),borderReady:Wt}}async loadTileWithProvider(He,ot,At,Ht){const{z:qt,x:Wt,y:Xt}=At.tileID.canonical;try{const ns=await He.loadTile({z:qt,x:Wt,y:Xt},{request:At.request,signal:Ht.signal});if(Ht.signal.aborted)return null;if(ns==null){const rn=new Error("Tile not found");throw rn.status=404,rn}if(ns.data==null)return null;const ps=await this.decodeTile(ot,ns.data,At.encoding);if(Ht.signal.aborted)return null;const Zs=new Headers;return ns.expires&&Zs.set("expires",ns.expires),ns.cacheControl&&Zs.set("cache-control",ns.cacheControl),ps.headers=Zs,ps}catch(ns){if(Ht.signal.aborted)return null;throw ns}finally{delete this.loading[ot]}}async reloadTile(He){}abortTile(He){const ot=He.uid,At=this.loading[ot];At&&(At.cancel(),delete this.loading[ot])}removeTile(He){}getImageData(He,ot){this.offscreenCanvas&&this.offscreenCanvasContext||(this.offscreenCanvas=new OffscreenCanvas(He.width,He.height),this.offscreenCanvasContext=this.offscreenCanvas.getContext("2d",{willReadFrequently:!0})),this.offscreenCanvas.width=He.width,this.offscreenCanvas.height=He.height,this.offscreenCanvasContext.drawImage(He,0,0,He.width,He.height);const At=this.offscreenCanvasContext.getImageData(-ot,-ot,He.width+2*ot,He.height+2*ot);return this.offscreenCanvasContext.clearRect(0,0,this.offscreenCanvas.width,this.offscreenCanvas.height),At}}const En=c.gi.prototype.toGeoJSON;class pr{constructor(He){this._feature=He,this.extent=c.a2,this.type=He.type,this.properties=He.tags,"id"in He&&!isNaN(He.id)&&(this.id=parseInt(He.id,10))}loadGeometry(){if(this._feature.type===1){const He=[];for(const ot of this._feature.geometry)He.push([new c.P(ot[0],ot[1])]);return He}{const He=[];for(const ot of this._feature.geometry){const At=[];for(const Ht of ot)At.push(new c.P(Ht[0],Ht[1]));He.push(At)}return He}}toGeoJSON(He,ot,At){return En.call(this,He,ot,At)}}class xn{constructor(He,ot){this.name=He,this.extent=c.a2,this.length=ot.length,this._jsonFeatures=ot}feature(He){return new pr(this._jsonFeatures[He])}}class Ar{constructor(He){this.layers={},this.extent=c.a2;for(const ot of Object.keys(He))this.layers[ot]=new xn(ot,He[ot])}}const Zr=64/4096;class dn{constructor(){this.features=new Map}clear(){this.features.clear()}load(He=[],ot){for(const At of He){const Ht=At.id;if(Ht==null)continue;let qt=this.features.get(Ht);qt&&this.updateCache(qt,ot),At.geometry?(qt=Er(At),this.updateCache(qt,ot),this.features.set(Ht,qt)):this.features.delete(Ht),this.updateCache(qt,ot)}}updateCache(He,ot){for(const{canonical:At,uid:Ht}of Object.values(ot)){const{z:qt,x:Wt,y:Xt}=At;Kt(He,Math.pow(2,qt),Wt,Xt)&&delete ot[Ht]}}getTile(He,ot,At){const Ht=Math.pow(2,He),qt=[];for(const Wt of this.features.values())Kt(Wt,Ht,ot,At)&&qt.push(Yn(Wt,Ht,ot,At));return{features:qt}}getFeatures(){return[...this.features.values()]}}function Kt({minX:Tt,minY:He,maxX:ot,maxY:At},Ht,qt,Wt){return Tt<(qt+1+Zr)/Ht&&He<(Wt+1+Zr)/Ht&&ot>(qt-Zr)/Ht&&At>(Wt-Zr)/Ht}function Er(Tt){const{id:He,geometry:ot,properties:At}=Tt;if(!ot)return;if(ot.type==="GeometryCollection")throw new Error("GeometryCollection not supported in dynamic mode.");const{type:Ht,coordinates:qt}=ot,Wt={id:He,type:1,geometry:[],tags:At,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0},Xt=Wt.geometry;if(Ht==="Point")ti(qt,Xt,Wt);else if(Ht==="MultiPoint")for(const ns of qt)ti(ns,Xt,Wt);else if(Ht==="LineString")Wt.type=2,Ba(qt,Xt,Wt);else if(Ht==="MultiLineString")Wt.type=2,lo(qt,Xt,Wt);else if(Ht==="Polygon")Wt.type=3,lo(qt,Xt,Wt,!0);else{if(Ht!=="MultiPolygon")throw new Error("Input data is not a valid GeoJSON object.");Wt.type=3;for(const ns of qt)lo(ns,Xt,Wt,!0)}return Wt}function ti([Tt,He],ot,At){const Ht=c.a7(Tt);let qt=c.a8(He);qt=qt<0?0:qt>1?1:qt,ot.push(Ht,qt),At.minX=Math.min(At.minX,Ht),At.minY=Math.min(At.minY,qt),At.maxX=Math.max(At.maxX,Ht),At.maxY=Math.max(At.maxY,qt)}function Ba(Tt,He,ot,At=!1,Ht=!1){const qt=[];for(const Wt of Tt)ti(Wt,qt,ot);He.push(qt),At&&function(Wt,Xt){let ns=0;for(let ps=0,Zs=Wt.length,rn=Zs-2;ps0===Xt)for(let ps=0,Zs=Wt.length;ps=Wt&&rn>=Wt||(ps>=Wt?(Zs+=Math.round(Zn*((Wt-ps)/qn)),ps=Wt):rn>=Wt&&(mn=Zs+Math.round(Zn*((Wt-ps)/qn)),rn=Wt),Zs>=Wt&&mn>=Wt||(Zs>=Wt?(ps+=Math.round(qn*((Wt-Zs)/Zn)),Zs=Wt):mn>=Wt&&(rn=ps+Math.round(qn*((Wt-Zs)/Zn)),mn=Wt),Xt&&ps===Xt.at(-1)[0]&&Zs===Xt.at(-1)[1]||(Xt=[[ps,Zs]],Ht.push(Xt)),Xt.push([rn,mn])))))}}function Ur(Tt,He,ot,At,Ht){const qt=(ot-Zr)/He,Wt=(At-Zr)/He,Xt=(ot+1+Zr)/He,ns=(At+1+Zr)/He;function ps(mn,qn){let Zn=0;return mnXt&&(Zn|=2),qnns&&(Zn|=8),Zn}let Zs=[];for(let mn=1;mn<=8;mn*=2){let qn=Tt[Tt.length-2],Zn=Tt.at(-1),la=!(ps(qn,Zn)&mn);for(let Br=0;Br>31}function Aa(Tt,He){const{geometry:ot,type:At}=Tt;let Ht=0,qt=0;if(At===1){He.writeVarint(Tn(1,ot.length));for(const Wt of ot){const Xt=Wt[0]-Ht,ns=Wt[1]-qt;He.writeVarint(Mr(Xt)),He.writeVarint(Mr(ns)),Ht+=Xt,qt+=ns}}else for(const Wt of ot){if(Wt.length===0)continue;He.writeVarint(Tn(1,1));const Xt=Wt.length-(At===3?1:0);for(let ns=0;nsTt},vl=Math.fround||(Ol=new Float32Array(1),Tt=>(Ol[0]=+Tt,Ol[0]));var Ol;class To{constructor(He){this.options=Object.assign(Object.create(Ac),He),this.trees=new Array(this.options.maxZoom+1),this.stride=this.options.reduce?7:6,this.clusterProps=[]}load(He){const{log:ot,minZoom:At,maxZoom:Ht}=this.options;ot&&console.time("total time");const qt=`prepare ${He.length} points`;ot&&console.time(qt),this.points=He;const Wt=[];for(let ns=0;ns=At;ns--){const ps=+Date.now();Xt=this.trees[ns]=this._createTree(this._cluster(Xt,ns)),ot&&console.log("z%d: %d clusters in %dms",ns,Xt.numItems,+Date.now()-ps)}return ot&&console.timeEnd("total time"),this}getClusters(He,ot){let At=((He[0]+180)%360+360)%360-180;const Ht=Math.max(-90,Math.min(90,He[1]));let qt=He[2]===180?180:((He[2]+180)%360+360)%360-180;const Wt=Math.max(-90,Math.min(90,He[3]));if(He[2]-He[0]>=360)At=-180,qt=180;else if(At>qt){const rn=this.getClusters([At,Ht,180,Wt],ot),mn=this.getClusters([-180,Ht,qt,Wt],ot);return rn.concat(mn)}const Xt=this.trees[this._limitZoom(ot)],ns=Xt.range(jh(At),Mu(Wt),jh(qt),Mu(Ht)),ps=Xt.data,Zs=[];for(const rn of ns){const mn=this.stride*rn;Zs.push(ps[mn+5]>1?_a(ps,mn,this.clusterProps):this.points[ps[mn+3]])}return Zs}getChildren(He){const ot=this._getOriginId(He),At=this._getOriginZoom(He),Ht="No cluster with the specified id.",qt=this.trees[At];if(!qt)throw new Error(Ht);const Wt=qt.data;if(ot*this.stride>=Wt.length)throw new Error(Ht);const Xt=this.options.radius/(this.options.extent*Math.pow(2,At-1)),ns=qt.within(Wt[ot*this.stride],Wt[ot*this.stride+1],Xt),ps=[];for(const Zs of ns){const rn=Zs*this.stride;Wt[rn+4]===He&&ps.push(Wt[rn+5]>1?_a(Wt,rn,this.clusterProps):this.points[Wt[rn+3]])}if(ps.length===0)throw new Error(Ht);return ps}getLeaves(He,ot,At){const Ht=[];return this._appendLeaves(Ht,He,ot=ot||10,At=At||0,0),Ht}getTile(He,ot,At){const Ht=this.trees[this._limitZoom(He)],qt=Math.pow(2,He),{extent:Wt,radius:Xt}=this.options,ns=Xt/Wt,ps=(At-ns)/qt,Zs=(At+1+ns)/qt,rn={features:[]};return this._addTileFeatures(Ht.range((ot-ns)/qt,ps,(ot+1+ns)/qt,Zs),Ht.data,ot,At,qt,rn),ot===0&&this._addTileFeatures(Ht.range(1-ns/qt,ps,1,Zs),Ht.data,qt,At,qt,rn),ot===qt-1&&this._addTileFeatures(Ht.range(0,ps,ns/qt,Zs),Ht.data,-1,At,qt,rn),rn.features.length?rn:null}getClusterExpansionZoom(He){let ot=this._getOriginZoom(He)-1;for(;ot<=this.options.maxZoom;){const At=this.getChildren(He);if(ot++,At.length!==1)break;He=At[0].properties.cluster_id}return ot}_appendLeaves(He,ot,At,Ht,qt){const Wt=this.getChildren(ot);for(const Xt of Wt){const ns=Xt.properties;if(ns&&ns.cluster?qt+ns.point_count<=Ht?qt+=ns.point_count:qt=this._appendLeaves(He,ns.cluster_id,At,Ht,qt):qt1;let Zs,rn,mn;if(ps)Zs=$o(ot,ns,this.clusterProps),rn=ot[ns],mn=ot[ns+1];else{const la=this.points[ot[ns+3]];Zs=la.properties;const[Br,wr]=la.geometry.coordinates;rn=jh(Br),mn=Mu(wr)}const qn={type:1,geometry:[[Math.round(this.options.extent*(rn*qt-At)),Math.round(this.options.extent*(mn*qt-Ht))]],tags:Zs};let Zn;Zn=ps||this.options.generateId?ot[ns+3]:this.points[ot[ns+3]].id,Zn!==void 0&&(qn.id=Zn),Wt.features.push(qn)}}_limitZoom(He){return Math.max(this.options.minZoom,Math.min(Math.floor(+He),this.options.maxZoom+1))}_cluster(He,ot){const{radius:At,extent:Ht,reduce:qt,minPoints:Wt}=this.options,Xt=At/(Ht*Math.pow(2,ot)),ns=He.data,ps=[],Zs=this.stride;for(let rn=0;rnot&&(Br+=ns[Ea+5])}if(Br>la&&Br>=Wt){let wr,Ea=mn*la,na=qn*la,yi=-1;const so=(rn/Zs<<5)+(ot+1)+this.points.length;for(const _i of Zn){const Ni=_i*Zs;if(ns[Ni+2]<=ot)continue;ns[Ni+2]=ot;const vi=ns[Ni+5];Ea+=ns[Ni]*vi,na+=ns[Ni+1]*vi,ns[Ni+4]=so,qt&&(wr||(wr=this._map(ns,rn,!0),yi=this.clusterProps.length,this.clusterProps.push(wr)),qt(wr,this._map(ns,Ni)))}ns[rn+4]=so,ps.push(Ea/Br,na/Br,1/0,so,-1,Br),qt&&ps.push(yi)}else{for(let wr=0;wr1)for(const wr of Zn){const Ea=wr*Zs;if(!(ns[Ea+2]<=ot)){ns[Ea+2]=ot;for(let na=0;na>5}_getOriginZoom(He){return(He-this.points.length)%32}_map(He,ot,At){if(He[ot+5]>1){const Wt=this.clusterProps[He[ot+6]];return At?Object.assign({},Wt):Wt}const Ht=this.points[He[ot+3]].properties,qt=this.options.map(Ht);return At&&qt===Ht?Object.assign({},qt):qt}}function _a(Tt,He,ot){return{type:"Feature",id:Tt[He+3],properties:$o(Tt,He,ot),geometry:{type:"Point",coordinates:[(At=Tt[He],360*(At-.5)),dh(Tt[He+1])]}};var At}function $o(Tt,He,ot){const At=Tt[He+5],Ht=At>=1e4?`${Math.round(At/1e3)}k`:At>=1e3?Math.round(At/100)/10+"k":At,qt=Tt[He+6],Wt=qt===-1?{}:Object.assign({},ot[qt]);return Object.assign(Wt,{cluster:!0,cluster_id:Tt[He+3],point_count:At,point_count_abbreviated:Ht})}function jh(Tt){return Tt/360+.5}function Mu(Tt){const He=Math.sin(Tt*Math.PI/180),ot=.5-.25*Math.log((1+He)/(1-He))/Math.PI;return ot<0?0:ot>1?1:ot}function dh(Tt){const He=(180-360*Tt)*Math.PI/180;return 360*Math.atan(Math.exp(He))/Math.PI-90}function Jr(Tt,He,ot,At){let Ht=At;const qt=He+(ot-He>>1);let Wt,Xt=ot-He;const ns=Tt[He],ps=Tt[He+1],Zs=Tt[ot],rn=Tt[ot+1];for(let mn=He+3;mnHt)Wt=mn,Ht=qn;else if(qn===Ht){const Zn=Math.abs(mn-qt);ZnAt&&(Wt-He>3&&Jr(Tt,He,Wt,At),Tt[Wt+2]=Ht,ot-Wt>3&&Jr(Tt,Wt,ot,At))}function Uo(Tt,He,ot,At,Ht,qt){let Wt=Ht-ot,Xt=qt-At;if(Wt!==0||Xt!==0){const ns=((Tt-ot)*Wt+(He-At)*Xt)/(Wt*Wt+Xt*Xt);ns>1?(ot=Ht,At=qt):ns>0&&(ot+=Wt*ns,At+=Xt*ns)}return Wt=Tt-ot,Xt=He-At,Wt*Wt+Xt*Xt}function fc(Tt,He,ot,At){const Ht={id:Tt??null,type:He,geometry:ot,tags:At,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0};if(He==="Point"||He==="MultiPoint"||He==="LineString")Lc(Ht,ot);else if(He==="Polygon")Lc(Ht,ot[0]);else if(He==="MultiLineString")for(const qt of ot)Lc(Ht,qt);else if(He==="MultiPolygon")for(const qt of ot)Lc(Ht,qt[0]);return Ht}function Lc(Tt,He){for(let ot=0;ot0&&(Wt+=At?(Ht*Zs-ps*qt)/2:Math.sqrt(Math.pow(ps-Ht,2)+Math.pow(Zs-qt,2))),Ht=ps,qt=Zs}const Xt=He.length-3;He[2]=1,Jr(He,0,Xt,ot),He[Xt+2]=1,He.size=Math.abs(Wt),He.start=0,He.end=He.size}function fa(Tt,He,ot,At){for(let Ht=0;Ht1?1:ot}function ja(Tt,He,ot,At,Ht,qt,Wt,Xt){if(At/=He,qt>=(ot/=He)&&Wt=At)return null;const ns=[];for(const ps of Tt){const Zs=ps.geometry;let rn=ps.type;const mn=Ht===0?ps.minX:ps.minY,qn=Ht===0?ps.maxX:ps.maxY;if(mn>=ot&&qn=At)continue;let Zn=[];if(rn==="Point"||rn==="MultiPoint")Il(Zs,Zn,ot,At,Ht);else if(rn==="LineString")zo(Zs,Zn,ot,At,Ht,!1,Xt.lineMetrics);else if(rn==="MultiLineString")Cf(Zs,Zn,ot,At,Ht,!1);else if(rn==="Polygon")Cf(Zs,Zn,ot,At,Ht,!0);else if(rn==="MultiPolygon")for(const la of Zs){const Br=[];Cf(la,Br,ot,At,Ht,!0),Br.length&&Zn.push(Br)}if(Zn.length){if(Xt.lineMetrics&&rn==="LineString"){for(const la of Zn)ns.push(fc(ps.id,rn,la,ps.tags));continue}rn!=="LineString"&&rn!=="MultiLineString"||(Zn.length===1?(rn="LineString",Zn=Zn[0]):rn="MultiLineString"),rn!=="Point"&&rn!=="MultiPoint"||(rn=Zn.length===3?"Point":"MultiPoint"),ns.push(fc(ps.id,rn,Zn,ps.tags))}}return ns.length?ns:null}function Il(Tt,He,ot,At,Ht){for(let qt=0;qt=ot&&Wt<=At&&oi(He,Tt[qt],Tt[qt+1],Tt[qt+2])}}function zo(Tt,He,ot,At,Ht,qt,Wt){let Xt=Hl(Tt);const ns=Ht===0?Mo:zh;let ps,Zs,rn=Tt.start;for(let Br=0;Br=ot&&(Zs=ns(Xt,wr,Ea,yi,so,ot),Wt&&(Xt.start=rn+ps*Zs)):_i>At?Ni<=At&&(Zs=ns(Xt,wr,Ea,yi,so,At),Wt&&(Xt.start=rn+ps*Zs)):oi(Xt,wr,Ea,na),Ni=ot&&(Zs=ns(Xt,wr,Ea,yi,so,ot),vi=!0),Ni>At&&_i<=At&&(Zs=ns(Xt,wr,Ea,yi,so,At),vi=!0),!qt&&vi&&(Wt&&(Xt.end=rn+ps*Zs),He.push(Xt),Xt=Hl(Tt)),Wt&&(rn+=ps)}let mn=Tt.length-3;const qn=Tt[mn],Zn=Tt[mn+1],la=Ht===0?qn:Zn;la>=ot&&la<=At&&oi(Xt,qn,Zn,Tt[mn+2]),mn=Xt.length-3,qt&&mn>=3&&(Xt[mn]!==Xt[0]||Xt[mn+1]!==Xt[1])&&oi(Xt,Xt[0],Xt[1],Xt[2]),Xt.length&&He.push(Xt)}function Hl(Tt){const He=[];return He.size=Tt.size,He.start=Tt.start,He.end=Tt.end,He}function Cf(Tt,He,ot,At,Ht,qt){for(const Wt of Tt)zo(Wt,He,ot,At,Ht,qt,!1)}function oi(Tt,He,ot,At){Tt.push(He,ot,At)}function Mo(Tt,He,ot,At,Ht,qt){const Wt=(qt-He)/(At-He);return oi(Tt,qt,ot+(Ht-ot)*Wt,1),Wt}function zh(Tt,He,ot,At,Ht,qt){const Wt=(qt-ot)/(Ht-ot);return oi(Tt,He+(At-He)*Wt,qt,1),Wt}function Gm(Tt,He){const ot=[];for(let At=0;At0&&He.size<(Ht?Wt:At))return void(ot.numPoints+=He.length/3);const Xt=[];for(let ns=0;nsWt)&&(ot.numSimplified++,Xt.push(He[ns],He[ns+1])),ot.numPoints++;Ht&&function(ns,ps){let Zs=0;for(let rn=0,mn=ns.length,qn=mn-2;rn0===ps)for(let rn=0,mn=ns.length;rn24)throw new Error("maxZoom should be in the 0-24 range");if(ot.promoteId&&ot.generateId)throw new Error("promoteId and generateId cannot be used together.");let Ht=function(qt,Wt){const Xt=[];if(qt.type==="FeatureCollection")for(let ns=0;ns1&&console.time("creation"),qn=this.tiles[mn]=Mg(He,ot,At,Ht,ps),this.tileCoords.push({z:ot,x:At,y:Ht}),Zs)){Zs>1&&(console.log("tile z%d-%d-%d (features: %d, points: %d, simplified: %d)",ot,At,Ht,qn.numFeatures,qn.numPoints,qn.numSimplified),console.timeEnd("creation"));const vi=`z${ot}`;this.stats[vi]=(this.stats[vi]||0)+1,this.total++}if(qn.source=He,qt==null){if(ot===ps.indexMaxZoom||qn.numPoints<=ps.indexMaxPoints)continue}else{if(ot===ps.maxZoom||ot===qt)continue;if(qt!=null){const vi=qt-ot;if(At!==Wt>>vi||Ht!==Xt>>vi)continue}}if(qn.source=null,He.length===0)continue;Zs>1&&console.time("clipping");const Zn=.5*ps.buffer/ps.extent,la=.5-Zn,Br=.5+Zn,wr=1+Zn;let Ea=null,na=null,yi=null,so=null;const _i=ja(He,rn,At-Zn,At+Br,0,qn.minX,qn.maxX,ps),Ni=ja(He,rn,At+la,At+wr,0,qn.minX,qn.maxX,ps);_i&&(Ea=ja(_i,rn,Ht-Zn,Ht+Br,1,qn.minY,qn.maxY,ps),na=ja(_i,rn,Ht+la,Ht+wr,1,qn.minY,qn.maxY,ps)),Ni&&(yi=ja(Ni,rn,Ht-Zn,Ht+Br,1,qn.minY,qn.maxY,ps),so=ja(Ni,rn,Ht+la,Ht+wr,1,qn.minY,qn.maxY,ps)),Zs>1&&console.timeEnd("clipping"),ns.push(Ea||[],ot+1,2*At,2*Ht),ns.push(na||[],ot+1,2*At,2*Ht+1),ns.push(yi||[],ot+1,2*At+1,2*Ht),ns.push(so||[],ot+1,2*At+1,2*Ht+1)}}getTile(He,ot,At){He=+He,ot=+ot,At=+At;const Ht=this.options,{extent:qt,debug:Wt}=Ht;if(He<0||He>24)return null;const Xt=1<1&&console.log("drilling down to z%d-%d-%d",He,ot,At);let ps,Zs=He,rn=ot,mn=At;for(;!ps&&Zs>0;)Zs--,rn>>=1,mn>>=1,ps=this.tiles[Ef(Zs,rn,mn)];return ps&&ps.source?(Wt>1&&(console.log("found parent tile z%d-%d-%d",Zs,rn,mn),console.time("drilling down")),this.splitTile(ps.source,Zs,rn,mn,He,ot,At),Wt>1&&console.timeEnd("drilling down"),this.tiles[ns]?Zd(this.tiles[ns],qt):null):null}}function Ef(Tt,He,ot){return 32*((1<ps.tags&&"3d_elevation_id"in ps.tags&&"source"in ps.tags&&ps.tags.source==="elevation",qt=At.features.filter(ps=>Ht(ps));let Wt={_geojsonTileLayer:At.features};qt.length>0&&(Wt={_geojsonTileLayer:At.features.filter(ps=>!Ht(ps)),hd_road_elevation:qt});const Xt=new Ar(Wt),ns=function(ps){const Zs=new c.gj;for(const rn of Object.keys(ps))Zs.writeMessage(3,Ei,{name:rn,features:ps[rn]});return Zs.finish()}(Wt).buffer;He(null,{vectorTile:Xt,rawData:ns,headers:new Headers})}class rl extends Sr{constructor(He){super(He),this.loadVectorData=Wx,this._dynamicIndex=new dn}async loadData(He){const ot=He&&He.request,At=ot&&ot.collectResourceTiming;this._geoJSONIndex=null;let Ht=await new Promise((Wt,Xt)=>{this.loadGeoJSON(He,(ns,ps)=>{ns?Xt(ns):Wt(ps)})});if(!Ht)return{};if(typeof Ht!="object")throw new Error(`Input data given to '${He.source}' is not a valid GeoJSON object.`);if(He.filter){const Wt=c.c(He.filter,{type:"boolean","property-type":"data-driven",overridable:!1,transition:!1});if(Wt.result==="error")throw new Error(Wt.value.map(Xt=>`${Xt.key}: ${Xt.message}`).join(", "));Ht.features=Ht.features.filter(Xt=>Wt.value.evaluate({zoom:0},Xt))}He.dynamic?(Ht.type==="Feature"&&(Ht={type:"FeatureCollection",features:[Ht]}),He.append||(this._dynamicIndex.clear(),this.loaded={}),this._dynamicIndex.load(Ht.features,this.loaded),He.cluster&&(Ht.features=this._dynamicIndex.getFeatures())):this.loaded={},this._geoJSONIndex=He.cluster?new To(function({superclusterOptions:Wt,clusterProperties:Xt}){if(!Xt||!Wt)return Wt;const ns={},ps={},Zs={accumulated:null,zoom:0},rn={properties:null},mn=Object.keys(Xt);for(const qn of mn){const[Zn,la]=Xt[qn],Br=c.c(la),wr=c.c(typeof Zn=="string"?[Zn,["accumulated"],["get",qn]]:Zn);ns[qn]=Br.value,ps[qn]=wr.value}return Wt.map=qn=>{rn.properties=qn;const Zn={};for(const la of mn)Zn[la]=ns[la].evaluate(Zs,rn);return Zn},Wt.reduce=(qn,Zn)=>{rn.properties=Zn;for(const la of mn)Zs.accumulated=qn[la],qn[la]=ps[la].evaluate(Zs,rn)},Wt}(He)).load(Ht.features):He.dynamic?this._dynamicIndex:function(Wt,Xt){return new Gp(Wt,Xt)}(Ht,He.geojsonVtOptions);const qt={};if(At){const Wt=d(ot);Wt&&(qt.resourceTiming={},qt.resourceTiming[He.source]=JSON.parse(JSON.stringify(Wt)))}return qt}async reloadTile(He){const ot=this.loaded;return ot&&ot[He.uid]?He.partial?void 0:super.reloadTile(He):this.loadTile(He)}loadGeoJSON(He,ot){if(He.request)c.g(He.request).then(({data:At})=>ot(null,At)).catch(At=>ot(At));else{if(typeof He.data!="string")return ot(new Error(`Input data given to '${He.source}' is not a valid GeoJSON object.`));setTimeout(()=>{try{return ot(null,JSON.parse(He.data))}catch{return ot(new Error(`Input data given to '${He.source}' is not a valid GeoJSON object.`))}},0)}}getClusterExpansionZoom(He){return this._geoJSONIndex.getClusterExpansionZoom(He.clusterId)}getClusterChildren(He){return this._geoJSONIndex.getChildren(He.clusterId)}getClusterLeaves(He){return this._geoJSONIndex.getLeaves(He.clusterId,He.limit,He.offset)}}c.cA.setPbf(c.cB);class to{constructor(He){this._mrt=new c.cA(He.partial?30:1/0),this._isHeaderLoaded=!1,this.uid=He.uid,this.tileID=He.tileID,this.source=He.source}async parse(He){const ot=this._mrt;this.status="parsing",this._entireBuffer=He,ot.parseHeader(He),this._isHeaderLoaded=!0;const At=[];for(const Ht in ot.layers){const qt=ot.getLayer(Ht),Wt=qt.getDataRange(qt.getBandList()),Xt=ot.createDecodingTask(Wt),ns=He.slice(Wt.firstByte,Wt.lastByte+1);At.push(c.cA.performDecoding(ns,Xt).then(ps=>Xt.complete(null,ps)).catch(ps=>Xt.complete(ps,null)))}return await Promise.allSettled(At),ot}}class Pg{constructor({actor:He}){this.actor=He,this.loading={},this.loaded={}}async loadTile(He){const ot=He.uid,At=new AbortController,Ht=this.loading[ot]=new to(He);Ht.abort=()=>At.abort();try{const{data:qt,headers:Wt}=await c.cC(He.request,At.signal);return qt?(this.loaded[ot]=Ht,{mrt:await Ht.parse(qt),headers:Wt}):(Ht.status="done",this.loaded[ot]=Ht,null)}catch(qt){if(At.signal.aborted)return null;throw Ht.status="done",this.loaded[ot]=Ht,qt}finally{delete this.loading[ot]}}async reloadTile(He){}abortTile(He){const ot=He.uid,At=this.loading[ot];At&&(At.abort&&At.abort(),delete this.loading[ot])}removeTile(He){const ot=He.uid;this.loaded[ot]&&delete this.loaded[ot]}async decodeRasterArray(He){return c.cA.performDecoding(He.buffer,He.task)}}class Kx{constructor(He){this.self=He,this.actor=new c.aw(He,this),this.layerIndexes={},this.availableImages={},this.availableModels={},this.isSpriteLoaded={},this.rtlPluginParsingListeners=[],this.projections={},this.defaultProjection=c.gl({name:"mercator"}),this.workerSourceTypes={vector:Sr,geojson:rl,"raster-dem":Qn},this.workerSources={},this.self.registerRTLTextPlugin=ot=>{if(c.fH.isParsed())throw new Error("RTL text plugin already registered.");c.fH.setState({pluginStatus:c.gm.parsed,pluginURL:c.fH.getPluginURL()}),c.fH.applyArabicShaping=ot.applyArabicShaping,c.fH.processBidirectionalText=ot.processBidirectionalText,c.fH.processStyledBidirectionalText=ot.processStyledBidirectionalText;for(const{resolve:At}of this.rtlPluginParsingListeners)At(!0);this.rtlPluginParsingListeners=[]}}clearCaches(He,ot){delete this.layerIndexes[He],delete this.availableImages[He],delete this.availableModels[He],delete this.workerSources[He],delete this.isSpriteLoaded[He]}checkIfReady(He,ot){}spriteLoaded(He,ot){const{scope:At}=ot;if(this.isSpriteLoaded[He]||(this.isSpriteLoaded[He]={}),this.isSpriteLoaded[He][At]=!0,this.workerSources[He]&&this.workerSources[He][At])for(const Ht in this.workerSources[He][At]){const qt=this.workerSources[He][At][Ht];for(const Wt in qt){const Xt=qt[Wt];Xt instanceof Sr&&(Xt.isSpriteLoaded=!0,Xt.fire(new c.h("isSpriteLoaded")))}}}setImages(He,ot){this.availableImages[He]||(this.availableImages[He]={});const{scope:At,images:Ht}=ot;if(this.availableImages[He][At]=Ht,ot.isSpriteLoaded&&this.spriteLoaded(He,{scope:At}),this.workerSources[He]&&this.workerSources[He][At])for(const qt in this.workerSources[He][At]){const Wt=this.workerSources[He][At][qt];for(const Xt in Wt)Wt[Xt].availableImages=Ht}}setModels(He,{scope:ot,models:At}){if(this.availableModels[He]||(this.availableModels[He]={}),this.availableModels[He][ot]=At,this.workerSources[He]&&this.workerSources[He][ot])for(const Ht in this.workerSources[He][ot]){const qt=this.workerSources[He][ot][Ht];for(const Wt in qt)qt[Wt].availableModels=At}}setProjection(He,ot){this.projections[He]=c.gl(ot)}setGlobalParams(He,ot){if(this.referrer=ot.referrer,Object.assign(c.eM,ot.config),ot.contextOptions){const{maxBindingPoints:At,maxUniformBlockSizeDwords:Ht}=ot.contextOptions;this.maxUniformBufferBindings=At,this.maxUniformBlockSizeDwords=Ht}}upsertRenderParams(He,ot){ot.brightness!==void 0&&(this.brightness=ot.brightness),ot.worldview!==void 0&&(this.worldview=ot.worldview)}setLayers(He,ot){this.getLayerIndex(He,ot.scope).replace(ot.layers,ot.options)}updateLayers(He,ot){this.getLayerIndex(He,ot.scope).update(ot.layers,ot.removedIds,ot.options)}async loadTile(He,ot){if(ot.projection=this.projections[He]||this.defaultProjection,ot.type==="batched-model"&&!this.workerSourceTypes["batched-model"]){if(await c.gn(),!R)throw new Error('Could not load Standard module for "batched-model" source.');this.workerSourceTypes["batched-model"]=R}return ot.type==="raster-array"&&await this.ensureRasterArrayWorkerSource(),this.getWorkerSource(He,ot).loadTile(ot)}async ensureRasterArraySource(He,ot){await this.ensureRasterArrayWorkerSource()}async ensureRasterArrayWorkerSource(){if(!this.workerSourceTypes["raster-array"]){if(await async function(){return Promise.resolve()}(),!Pg)throw new Error('Could not load raster-array module for "raster-array" source.');this.workerSourceTypes["raster-array"]=Pg}}async decodeRasterArray(He,ot){return await this.ensureRasterArrayWorkerSource(),this.getWorkerSource(He,ot).decodeRasterArray(ot)}reloadTile(He,ot){return ot.projection=this.projections[He]||this.defaultProjection,this.getWorkerSource(He,ot).reloadTile(ot)}abortTile(He,ot){const At=this.getExistingWorkerSource(He,ot);return At?At.abortTile(ot):void 0}removeTile(He,ot){const At=this.getExistingWorkerSource(He,ot);return At?At.removeTile(ot):void 0}getExistingWorkerSource(He,ot){const{type:At,source:Ht,scope:qt}=ot,Wt=this.workerSources[He];if(Wt&&Wt[qt]&&Wt[qt][At])return Wt[qt][At][Ht]}async removeSource(He,ot){const{type:At,source:Ht,scope:qt}=ot,Wt=this.workerSources[He]&&this.workerSources[He][qt]&&this.workerSources[He][qt][At],Xt=Wt&&Wt[Ht];Xt&&(delete Wt[Ht],Xt.removeSource&&await Xt.removeSource({source:Ht}))}async loadTileProvider(He,ot){const At=new(await c.cn(ot.name,ot.url))(ot.options);return this.getWorkerSource(He,{type:ot.type,source:ot.source,scope:ot.scope},At),At.load&&ot.request?At.load({request:ot.request}):null}async syncRTLPluginState(He,ot){if(c.fH.isParsed())return!0;if(c.fH.isParsing())return new Promise((Ht,qt)=>{this.rtlPluginParsingListeners.push({resolve:Ht,reject:qt})});c.fH.setState(ot);const At=c.fH.getPluginURL();if(!c.fH.isLoaded()||c.fH.isParsed()||c.fH.isParsing())return!1;c.fH.setState({pluginStatus:c.gm.parsing,pluginURL:At});try{return await self.__mapboxImport(At),!!c.fH.isParsed()||new Promise((Ht,qt)=>{this.rtlPluginParsingListeners.push({resolve:Ht,reject:qt})})}catch(Ht){c.fH.setState({pluginStatus:c.gm.error,pluginURL:At});for(const{reject:qt}of this.rtlPluginParsingListeners)qt(Ht);throw this.rtlPluginParsingListeners=[],Ht}}getAvailableImages(He,ot){this.availableImages[He]||(this.availableImages[He]={});let At=this.availableImages[He][ot];return At||(At=[]),At}getAvailableModels(He,ot){this.availableModels[He]||(this.availableModels[He]={});let At=this.availableModels[He][ot];return At||(At={}),At}getLayerIndex(He,ot){this.layerIndexes[He]||(this.layerIndexes[He]={});let At=this.layerIndexes[He][ot];return At||(At=this.layerIndexes[He][ot]=new G,At.scope=ot),At}getWorkerSource(He,ot,At){const{type:Ht,source:qt,scope:Wt}=ot,Xt=this.workerSources;if(Xt[He]||(Xt[He]={}),Xt[He][Wt]||(Xt[He][Wt]={}),Xt[He][Wt][Ht]||(Xt[He][Wt][Ht]={}),this.isSpriteLoaded[He]||(this.isSpriteLoaded[He]={}),this.getExistingWorkerSource(He,ot))At&&(Xt[He][Wt][Ht][qt].tileProvider=At);else{const ns=this.actor.getWorkerSourceActor(He),ps=this.workerSourceTypes[Ht];if(!ps)throw new Error(`Unknown worker source type "${Ht}".`);Xt[He][Wt][Ht][qt]=new ps({actor:ns,layerIndex:this.getLayerIndex(He,Wt),availableImages:this.getAvailableImages(He,Wt),availableModels:this.getAvailableModels(He,Wt),isSpriteLoaded:this.isSpriteLoaded[He][Wt],tileProvider:At,brightness:this.brightness,worldview:this.worldview,maxUniformBufferBindings:this.maxUniformBufferBindings,maxUniformBlockSizeDwords:this.maxUniformBlockSizeDwords})}return Xt[He][Wt][Ht][qt]}enforceCacheSizeLimit(He,ot){c.go(ot)}}return c.gk(self)&&(self.worker=new Kx(self)),Kx}),i(["./shared"],function(o){const c={antialias:!1,alpha:!0,stencil:!0,depth:!0};let d,u;function h(L){const N=document.createElement("canvas"),E=Object.create(c);E.failIfMajorPerformanceCaveat=L;const z=N.getContext("webgl2",E);if(!z)return!1;let W;try{W=z.createShader(z.VERTEX_SHADER)}catch{return!1}return!(!W||z.isContextLost())&&(z.shaderSource(W,"void main() {}"),z.compileShader(W),z.getShaderParameter(W,z.COMPILE_STATUS)===!0)}const m=/firefox/i,p=/macintosh/i;function g(L,N,E){const z=document.createElement(L);return N!=null&&(z.className=N),E&&E.appendChild(z),z}function x(L,N,E){const z=document.createElementNS("http://www.w3.org/2000/svg",L);for(const W of Object.keys(N))z.setAttributeNS(null,W,String(N[W]));return E&&E.appendChild(z),z}const y=typeof document<"u"?document.documentElement&&document.documentElement.style:null,v=y&&y.userSelect!==void 0?"userSelect":"WebkitUserSelect";let _;function j(){y&&v&&(_=y[v],y[v]="none")}function C(){y&&v&&(y[v]=_)}function A(L){L.preventDefault(),L.stopPropagation(),window.removeEventListener("click",A,!0)}function M(){window.addEventListener("click",A,!0),window.setTimeout(()=>{window.removeEventListener("click",A,!0)},0)}function I(L,N){const E=L.getBoundingClientRect();return O(L,E,N)}function P(L,N){const E=L.getBoundingClientRect(),z=[];for(let W=0;W>16&255)/255,(L>>8&255)/255,(255&L)/255,1)}function Te(L,N){const E={spread_method:1,stops:[],x1:0,y1:0,x2:1,y2:0};let z;for(;z=L.nextField(N);)z===1?E.transform=fe(L,L.readVarint()+L.pos):z===2?E.spread_method=L.readVarint():z===3?E.stops.push(Ie(L,L.readVarint()+L.pos)):z===4?E.x1=L.readFloat():z===5?E.y1=L.readFloat():z===6?E.x2=L.readFloat():z===7&&(E.y2=L.readFloat());return E}function Ie(L,N){const E={offset:0,opacity:255,rgb_color:H};let z;for(;z=L.nextField(N);)z===1?E.offset=L.readFloat():z===2?E.opacity=L.readVarint():z===3&&(E.rgb_color=Se(L.readVarint()));return E}function Ue(L,N){const E={spread_method:1,stops:[],cx:.5,cy:.5,r:.5,fx:.5,fy:.5,fr:0};let z;for(;z=L.nextField(N);)z===1?E.transform=fe(L,L.readVarint()+L.pos):z===2?E.spread_method=L.readVarint():z===3?E.stops.push(Ie(L,L.readVarint()+L.pos)):z===4?E.cx=L.readFloat():z===5?E.cy=L.readFloat():z===6?E.r=L.readFloat():z===7?E.fx=L.readFloat():z===8?E.fy=L.readFloat():z===9&&(E.fr=L.readFloat());return E}function Be(L,N){const E={children:[]};let z;for(;z=L.nextField(N);)z===1?E.transform=fe(L,L.readVarint()+L.pos):z===2?E.clip_path_idx=L.readVarint():z===3&&E.children.push(te(L,L.readVarint()+L.pos));return E}function je(L,N){const E={left:0,width:20,mask_type:1,children:[]};let z;for(;z=L.nextField(N);)z===1?E.left=E.top=L.readFloat():z===2?E.width=E.height=L.readFloat():z===3?E.top=L.readFloat():z===4?E.height=L.readFloat():z===5?E.mask_type=L.readVarint():z===6?E.mask_idx=L.readVarint():z===7&&E.children.push(te(L,L.readVarint()+L.pos));return E.height??(E.height=E.width),E.top??(E.top=E.left),E}class Ye{static calculate(N={},E=[]){const z=new Map,W=new Map;if(Object.keys(N).length===0)return z;E.forEach(Z=>{W.set(Z.name,Z.rgb_color||new o.C(0,0,0))});for(const[Z,ne]of Object.entries(N))W.has(Z)?z.set(W.get(Z).toString(),ne):console.warn(`Ignoring unknown image variable "${Z}"`);return z}}function Ee(L,N=255,E){const z=E.get(L.toString())||L;return N===255?z.toString():new o.C(z.r,z.g,z.b,z.a*N/255).toString()}const Re=[];let ke=0;function Fe(L,N){if(ke>=Re.length){const z=o.o()?new OffscreenCanvas(L,N).getContext("2d",{willReadFrequently:!0}):document.createElement("canvas").getContext("2d",{willReadFrequently:!0});Re.push(z)}const E=Re[ke++];return E.canvas.width=L,E.canvas.height=N,E}function Oe(){ke--}function Ge(L,N,E,z,W){for(const Z of z.children)yt(L,N,E,Z,W)}function yt(L,N,E,z,W){z.group?(L.save(),function(Z,ne,de,ye,Ce){const Pe=ye.mask_idx!=null?de.masks[ye.mask_idx]:null,Ke=ye.clip_path_idx!=null?de.clip_paths[ye.clip_path_idx]:null;if(ye.transform&&(ne=Ut(ye.transform).preMultiplySelf(ne)),!function(mt,vt,bt){return mt.opacity!==255||vt||bt}(ye,Ke!=null,Pe!=null))return void Ge(Z,ne,de,ye,Ce);const Ze=Fe(Z.canvas.width,Z.canvas.height);Ge(Ze,ne,de,ye,Ce),Ke&&rt(Ze,ne,de,Ke),Pe&&Ft(Ze,ne,de,Pe,Ce),Z.globalAlpha=ye.opacity/255,Z.drawImage(Ze.canvas,0,0),Oe()}(L,N,E,z.group,W),L.restore()):z.path&&(L.save(),function(Z,ne,de,ye,Ce){Z.setTransform(ne),ye.paint_order===1?(tt(Z,de,ye,Ce),nt(Z,de,ye,Ce)):(nt(Z,de,ye,Ce),tt(Z,de,ye,Ce))}(L,N,E,z.path,W),L.restore())}function tt(L,N,E,z){const W=E.fill;if(!W)return;const Z=W.opacity/255;switch(L.save(),L.beginPath(),Is(E,L),W.paint){case"rgb_color":L.fillStyle=Ee(W.rgb_color,W.opacity,z);break;case"linear_gradient_idx":{const ne=N.linear_gradients[W.linear_gradient_idx];ne.transform&&L.setTransform(Ut(ne.transform).preMultiplySelf(L.getTransform())),L.fillStyle=et(L,ne,Z,z);break}case"radial_gradient_idx":{const ne=N.radial_gradients[W.radial_gradient_idx];ne.transform&&L.setTransform(Ut(ne.transform).preMultiplySelf(L.getTransform())),L.fillStyle=at(L,ne,Z,z)}}L.fill(ut(E)),L.restore()}function ut(L){return L.rule===1?"nonzero":L.rule===2?"evenodd":void 0}function nt(L,N,E,z){const W=E.stroke;if(!W)return;const Z=xs(E);L.lineWidth=W.width,L.miterLimit=W.miterlimit,L.setLineDash(W.dasharray),L.lineDashOffset=W.dashoffset;const ne=W.opacity/255;switch(W.paint){case"rgb_color":L.strokeStyle=Ee(W.rgb_color,W.opacity,z);break;case"linear_gradient_idx":L.strokeStyle=et(L,N.linear_gradients[W.linear_gradient_idx],ne,z,!0);break;case"radial_gradient_idx":L.strokeStyle=at(L,N.radial_gradients[W.radial_gradient_idx],ne,z,!0)}switch(W.linejoin){case 2:case 1:L.lineJoin="miter";break;case 3:L.lineJoin="round";break;case 4:L.lineJoin="bevel"}switch(W.linecap){case 1:L.lineCap="butt";break;case 2:L.lineCap="round";break;case 3:L.lineCap="square"}L.stroke(Z)}function et(L,N,E,z,W=!1){if(N.stops.length===1){const Ze=N.stops[0];return Ee(Ze.rgb_color,Ze.opacity*E,z)}const{x1:Z,y1:ne,x2:de,y2:ye}=N;let Ce=new DOMPoint(Z,ne),Pe=new DOMPoint(de,ye);if(W){const Ze=Ut(N.transform);Ce=Ze.transformPoint(Ce),Pe=Ze.transformPoint(Pe)}const Ke=L.createLinearGradient(Ce.x,Ce.y,Pe.x,Pe.y);for(const Ze of N.stops)Ke.addColorStop(Ze.offset,Ee(Ze.rgb_color,Ze.opacity*E,z));return Ke}function at(L,N,E,z,W=!1){if(N.stops.length===1){const Pt=N.stops[0];return Ee(Pt.rgb_color,Pt.opacity*E,z)}const Z=Ut(N.transform),{fx:ne,fy:de,fr:ye,cx:Ce,cy:Pe,r:Ke}=N;let Ze=new DOMPoint(ne,de),mt=new DOMPoint(Ce,Pe),vt=ye,bt=Ke;if(W){Ze=Z.transformPoint(Ze),mt=Z.transformPoint(mt);const Pt=(Z.a+Z.d)/2;vt=ye*Pt,bt=N.r*Pt}const St=L.createRadialGradient(Ze.x,Ze.y,vt,mt.x,mt.y,bt);for(const Pt of N.stops)St.addColorStop(Pt.offset,Ee(Pt.rgb_color,Pt.opacity*E,z));return St}function wt(L,N,E,z){const W=z.transform?Ut(z.transform).preMultiplySelf(N):N,Z=Fe(L.canvas.width,L.canvas.height);for(const de of z.children)if(de.group)wt(Z,W,E,de.group);else if(de.path){const ye=de.path,Ce=new Path2D;Ce.addPath(xs(ye),W),Z.fill(Ce,ut(ye))}const ne=z.clip_path_idx!=null?E.clip_paths[z.clip_path_idx]:null;ne&&rt(Z,W,E,ne),L.globalCompositeOperation="source-over",L.drawImage(Z.canvas,0,0),Oe()}function rt(L,N,E,z){const W=Fe(L.canvas.width,L.canvas.height);wt(W,N,E,z),L.globalCompositeOperation="destination-in",L.drawImage(W.canvas,0,0),Oe()}function Ft(L,N,E,z,W){if(z.children.length===0)return;const Z=z.mask_idx!=null?E.masks[z.mask_idx]:null;Z&&Ft(L,N,E,Z,W);const ne=L.canvas.width,de=L.canvas.height,ye=Fe(ne,de),Ce=z.width,Pe=z.height,Ke=z.left,Ze=z.top,mt=new Path2D,vt=new Path2D;vt.rect(Ke,Ze,Ce,Pe),mt.addPath(vt,N),ye.clip(mt);for(const Pt of z.children)yt(ye,N,E,Pt,W);const bt=ye.getImageData(0,0,ne,de),St=bt.data;if(z.mask_type===1)for(let Pt=0;Pto.I.from(E))}getImageVersions(N){return this.imageVersions.get(N)||new Map}hasImageProviderForSource(N,E){const z=this.imageProviders.get(E);if(!z)return!1;for(const W of z.values())if(W.sourceCache.getSource().id===N)return!0;return!1}getImages(N,E,z){const W=[],Z=[],ne=this.imageProviders.get(E);for(const Pe of N){if(!Pe.iconsetId){W.push(Pe);continue}const Ke=ne.get(Pe.iconsetId);Ke&&(this.getImage(Pe,E)?Z.push(Pe):Ke.addPendingRequest(Pe))}if(W.length===0)return void this._notify(Z,E,z);let de=!0;const ye=!!this.loaded.get(E),Ce=this.images.get(E);if(!ye)for(const Pe of W)Ce.has(Pe.toString())||(de=!1);ye||de?this._notify(W,E,z):this.requestors.push({ids:W,scope:E,callback:z})}rasterizeImages(N,E){const z=new Map,{iconTasks:W,patternTasks:Z,scope:ne}=N;for(const de of[W,Z])for(const[ye,Ce]of de.entries()){const Pe=this.getImage(Ce.id,ne);Pe&&z.set(ye,{image:Pe,imageVariant:Ce})}E(null,this._rasterizeImages(ne,z))}_rasterizeImages(N,E){const z=new Map;for(const[W,{image:Z,imageVariant:ne}]of E.entries())z.set(W,this.imageRasterizer.rasterize(ne,Z,N,0));return z}getUpdatedImages(N){return this.updatedImages.get(N)||new Set}_notify(N,E,z){const W=this.images.get(E),Z=new Map;for(const ne of N){if(!W.get(ne.toString())){if(ne.iconsetId)continue;this.fire(new o.h("styleimagemissing",{id:ne.name}))}const de=W.get(ne.toString());if(!de){o.w(`Image "${ne.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 ye={data:de.usvg?null:de.data.clone(),pixelRatio:de.pixelRatio,sdf:de.sdf,usvg:de.usvg,stretchX:de.stretchX,stretchY:de.stretchY,content:de.content,hasRenderCallback:!!(de.userImage&&de.userImage.render)};de.usvg&&Object.assign(ye,{width:de.icon.usvg_tree.width,height:de.icon.usvg_tree.height}),Z.set(o.I.toString(ne),ye)}z(null,{images:Z,versions:this.getImageVersions(E)})}getPixelSize(N){const{width:E,height:z}=this.atlasImage.get(N);return{width:E,height:z}}getPattern(N,E,z){const W=N.toString(),Z=this.patterns.get(E),ne=Z.get(W),de=this.getImage(N,E);if(!de)return null;if(ne){if(ne.position.version===de.version)return ne.position;ne.position.version=de.version}else{if(de.usvg&&!de.data){const ye=this.getPatternInFlightId(W,E);if(this.patternsInFlight.has(ye))return null;this.patternsInFlight.add(ye);const Ce=new o.i(N).scaleSelf(o.e.devicePixelRatio),Pe=new Map([[Ce.toString(),{image:de,imageVariant:Ce}]]),Ke=this._rasterizeImages(E,Pe);return this.storePatternImage(Ce,E,de,z,Ke),null}this.storePattern(N,E,de)}return this._updatePatternAtlas(E,z),Z.get(W).position}getPatternInFlightId(N,E){return o.m(N,E)}hasPatternsInFlight(){return this.patternsInFlight.size!==0}storePatternImage(N,E,z,W,Z){const ne=N.toString(),de=Z?Z.get(ne):void 0;de&&(z.data=de,this.storePattern(N.id,E,z),this._updatePatternAtlas(E,W),this.patternsInFlight.delete(this.getPatternInFlightId(N.id.toString(),E)))}storePattern(N,E,z){const W={w:z.data.width+2*o.j,h:z.data.height+2*o.j,x:0,y:0},Z=new o.k(W,z,o.j);this.patterns.get(E).set(N.toString(),{bin:W,position:Z})}destroyAtlasTextures(){for(const N of this.atlasTexture.values())N&&N.destroy();this.atlasTexture.clear()}bind(N,E){const z=N.gl;let W=this.atlasTexture.get(E);W?this.dirty&&(W.update(this.atlasImage.get(E)),this.dirty=!1):(W=new o.T(N,this.atlasImage.get(E),z.RGBA8),this.atlasTexture.set(E,W)),W.bind(z.LINEAR,z.CLAMP_TO_EDGE)}_updatePatternAtlas(N,E){const z=this.patterns.get(N),W=Array.from(z.values()).map(({bin:Ce})=>Ce),{w:Z,h:ne}=o.p(W),de=this.atlasImage.get(N);de.resize({width:Z||1,height:ne||1});const ye=this.images.get(N);for(const[Ce,{bin:Pe,position:Ke}]of z.entries()){let Ze=Ke.padding;const mt=Pe.x+Ze,vt=Pe.y+Ze,bt=ye.get(Ce).data,St=bt.width,Pt=bt.height;Ze=Ze>1?Ze-1:Ze,o.b.copy(bt,de,{x:0,y:0},{x:mt,y:vt},{width:St,height:Pt},E),o.b.copy(bt,de,{x:0,y:Pt-Ze},{x:mt,y:vt-Ze},{width:St,height:Ze},E),o.b.copy(bt,de,{x:0,y:0},{x:mt,y:vt+Pt},{width:St,height:Ze},E),o.b.copy(bt,de,{x:St-Ze,y:0},{x:mt-Ze,y:vt},{width:Ze,height:Pt},E),o.b.copy(bt,de,{x:0,y:0},{x:mt+St,y:vt},{width:Ze,height:Pt},E),o.b.copy(bt,de,{x:St-Ze,y:Pt-Ze},{x:mt-Ze,y:vt-Ze},{width:Ze,height:Ze},E),o.b.copy(bt,de,{x:0,y:Pt-Ze},{x:mt+St,y:vt-Ze},{width:Ze,height:Ze},E),o.b.copy(bt,de,{x:0,y:0},{x:mt+St,y:vt+Pt},{width:Ze,height:Ze},E),o.b.copy(bt,de,{x:St-Ze,y:0},{x:mt-Ze,y:vt+Pt},{width:Ze,height:Ze},E)}this.dirty=!0}beginFrame(){for(const N of this.images.keys())this.callbackDispatchedThisFrame.set(N,new Set);this.imageAtlasCache.beginFrame()}dispatchRenderCallbacks(N,E){const z=this.images.get(E);for(const W of N){if(this.callbackDispatchedThisFrame.get(E).has(W.toString()))continue;this.callbackDispatchedThisFrame.get(E).add(W.toString());const Z=z.get(W.toString());G(Z)&&this.updateImage(W,E,Z)}}}class jt{constructor(N,E,z,W){this.message=(N?`${N}: `:"")+z,W&&(this.identifier=W),E!=null&&E.__line__&&(this.line=E.__line__)}}class gt extends jt{}function rs(L){const N=L.value,E=L.valueSpec,z=L.style,W=L.styleSpec,Z=L.key,ne=L.arrayElementValidator||Ur;if(!Array.isArray(N))return[new jt(Z,N,`array expected, ${o.n(N)} found`)];if(E.length&&N.length!==E.length)return[new jt(Z,N,`array length ${E.length} expected, length ${N.length} found`)];if(E["min-length"]&&N.lengthW)return[new jt(N,E,`${E} is greater than the maximum value ${W}`)]}return[]}function us(L){const N=L.key,E=L.value;if(!o.l(E))return[new jt(N,E,`object expected, ${o.n(E)} found`)];const z=L.valueSpec,W=o.u(E.type);let Z,ne,de,ye={};const Ce=W!=="categorical"&&E.property===void 0,Pe=!Ce,Ke=function(bt){const St=bt.stops;return Array.isArray(St)&&Array.isArray(St[0])&&o.l(St[0][0])}(E),Ze=Ei({key:L.key,value:L.value,valueSpec:L.styleSpec.function,style:L.style,styleSpec:L.styleSpec,objectElementValidators:{stops:function(bt){if(W==="identity")return[new jt(bt.key,bt.value,'identity function may not have a "stops" property')];let St=[];const Pt=bt.value;return St=St.concat(rs({key:bt.key,value:Pt,valueSpec:bt.valueSpec,style:bt.style,styleSpec:bt.styleSpec,arrayElementValidator:mt})),Array.isArray(Pt)&&Pt.length===0&&St.push(new jt(bt.key,Pt,"array must have at least one stop")),St},default:function(bt){return Ur({key:bt.key,value:bt.value,valueSpec:z,style:bt.style,styleSpec:bt.styleSpec})}}});return W==="identity"&&Ce&&Ze.push(new jt(L.key,L.value,'missing required property "property"')),W==="identity"||E.stops||Ze.push(new jt(L.key,L.value,'missing required property "stops"')),W==="exponential"&&z.expression&&!o.r(z)&&Ze.push(new jt(L.key,L.value,"exponential functions not supported")),L.styleSpec.$version>=8&&(Pe&&!o.t(z)?Ze.push(new jt(L.key,L.value,"property functions not supported")):Ce&&!o.v(z)&&Ze.push(new jt(L.key,L.value,"zoom functions not supported"))),W!=="categorical"&&!Ke||E.property!==void 0||Ze.push(new jt(L.key,L.value,'"property" property is required')),Ze;function mt(bt){let St=[];const Pt=bt.value,Gt=bt.key;if(!Array.isArray(Pt))return[new jt(Gt,Pt,`array expected, ${o.n(Pt)} found`)];if(Pt.length!==2)return[new jt(Gt,Pt,`array length 2 expected, length ${Pt.length} found`)];if(Ke){if(!o.l(Pt[0]))return[new jt(Gt,Pt,`object expected, ${o.n(Pt[0])} found`)];const as=Pt[0];if(as.zoom===void 0)return[new jt(Gt,Pt,"object stop key must have zoom")];if(as.value===void 0)return[new jt(Gt,Pt,"object stop key must have value")];const ms=o.u(as.zoom);if(typeof ms!="number")return[new jt(Gt,as.zoom,"stop zoom values must be numbers")];if(de&&de>ms)return[new jt(Gt,as.zoom,"stop zoom values must appear in ascending order")];ms!==de&&(de=ms,ne=void 0,ye={}),St=St.concat(Ei({key:`${Gt}[0]`,value:Pt[0],valueSpec:{zoom:{}},style:bt.style,styleSpec:bt.styleSpec,objectElementValidators:{zoom:Ns,value:vt}}))}else St=St.concat(vt({key:`${Gt}[0]`,value:Pt[0],style:bt.style,styleSpec:bt.styleSpec},Pt));return o.x(o.y(Pt[1]))?St.concat([new jt(`${Gt}[1]`,Pt[1],"expressions are not allowed in function stops.")]):St.concat(Ur({key:`${Gt}[1]`,value:Pt[1],valueSpec:z,style:bt.style,styleSpec:bt.styleSpec}))}function vt(bt,St){const Pt=o.n(bt.value),Gt=o.u(bt.value),as=bt.value!==null?bt.value:St;if(Z){if(Pt!==Z)return[new jt(bt.key,as,`${Pt} stop domain type must match previous stop domain type ${Z}`)]}else Z=Pt;if(Pt!=="number"&&Pt!=="string"&&Pt!=="boolean"&&typeof Gt!="number"&&typeof Gt!="string"&&typeof Gt!="boolean")return[new jt(bt.key,as,"stop domain value must be a number, string, or boolean")];if(Pt!=="number"&&W!=="categorical"){let ms=`number expected, ${Pt} found`;return o.t(z)&&W===void 0&&(ms+='\nIf you intended to use a categorical function, specify `"type": "categorical"`.'),[new jt(bt.key,as,ms)]}return W!=="categorical"||Pt!=="number"||typeof Gt=="number"&&isFinite(Gt)&&Math.floor(Gt)===Gt?W!=="categorical"&&Pt==="number"&&typeof Gt=="number"&&typeof ne=="number"&&ne!==void 0&&Gtnew jt(`${L.key}${z.key}`,L.value,z.message));const E=N.value.expression||N.value._styleExpression.expression;if(L.expressionContext==="property"&&L.propertyKey==="text-font"&&!E.outputDefined())return[new jt(L.key,L.value,`Invalid data expression for "${L.propertyKey}". Output values must be contained as literals within the expression.`)];if(L.expressionContext==="property"&&L.propertyType==="layout"&&!o.A(E))return[new jt(L.key,L.value,'"feature-state" data expressions are not supported with layout properties.')];if(L.expressionContext==="filter")return Ts(E,L);if(L.expressionContext==="appearance")return js(E,L);if(L.expressionContext&&L.expressionContext.indexOf("cluster")===0){if(!o.B(E,["zoom","feature-state"]))return[new jt(L.key,L.value,'"zoom" and "feature-state" expressions are not supported with cluster properties.')];if(L.expressionContext==="cluster-initial"&&!o.D(E))return[new jt(L.key,L.value,"Feature data expressions are not supported with initial expression part of cluster properties.")]}return[]}function Ts(L,N){const E=new Set(["zoom","feature-state","pitch","distance-from-center"]);if(N.valueSpec&&N.valueSpec.expression)for(const W of N.valueSpec.expression.parameters)E.delete(W);if(E.size===0)return[];const z=[];return L instanceof o.F&&E.has(L.name)?[new jt(N.key,N.value,`["${L.name}"] expression is not supported in a filter for a ${N.object.type} layer with id: ${N.object.id}`)]:(L.eachChild(W=>{z.push(...Ts(W,N))}),z)}const Fn=new Set(["get","has","properties","geometry-type","id"]),An=new Set(["zoom","pitch","distance-from-center","feature","feature-state","measure-light","heatmap-density","line-progress","raster-value","raster-particle-speed","sky-radial-progress"]);function js(L,N){if(N.valueSpec&&N.valueSpec.expression)for(const z of N.valueSpec.expression.parameters)An.delete(z);if(An.size===0)return[];const E=[];if(L instanceof o.F){const z=Fn.has(L.name)?"feature":L.name;if(An.has(z))return[new jt(N.key,N.value,`["${L.name}"] is not an allowed parameter`)]}return L.eachChild(z=>{E.push(...js(z,N))}),E}function In(L){const N=L.key,E=L.value,z=L.valueSpec,W=[];return Array.isArray(z.values)?z.values.includes(o.u(E))||W.push(new jt(N,E,`expected one of [${z.values.join(", ")}], ${JSON.stringify(E)} found`)):Object.keys(z.values).includes(o.u(E))||W.push(new jt(N,E,`expected one of [${Object.keys(z.values).join(", ")}], ${JSON.stringify(E)} found`)),W}function un(L){if(o.J(o.y(L.value))){const N=L.layerType||"fill";return Bs({...L,expressionContext:"filter",valueSpec:L.styleSpec[`filter_${N}`]})}return jr(L)}function jr(L){const N=L.value,E=L.key;if(!Array.isArray(N))return[new jt(E,N,`array expected, ${o.n(N)} found`)];if(N.length<1)return[new jt(E,N,"filter array must have at least 1 element")];const z=L.styleSpec;let W=In({key:`${E}[0]`,value:N[0],valueSpec:z.filter_operator});const Z=()=>{N.length>=2&&(o.H(N[1])||W.push(new jt(`${E}[1]`,N[1],`string expected, ${o.n(N[1])} found`)));for(let ne=2;ne":case">=":N.length>=2&&o.u(N[1])==="$type"&&W.push(new jt(E,N,`"$type" cannot be use with operator "${N[0]}"`)),N.length!==3&&W.push(new jt(E,N,`filter array for operator "${N[0]}" must have 3 elements`)),Z();break;case"==":case"!=":N.length!==3&&W.push(new jt(E,N,`filter array for operator "${N[0]}" must have 3 elements`)),Z();break;case"in":case"!in":Z();break;case"any":case"all":case"none":for(let ne=1;ne{Ce in E&&N.push(new jt(z,E[Ce],`"${Ce}" is prohibited for ref layers`))}),W.layers.forEach(Ce=>{o.u(Ce.id)===de&&(ye=Ce)}),ye?ye.ref?N.push(new jt(z,E.ref,"ref cannot reference another ref layer")):ne=o.u(ye.type):typeof de=="string"&&N.push(new jt(z,E.ref,`ref layer "${de}" not found`))}else if(ne!=="background"&&ne!=="sky"&&ne!=="slot")if(E.source)if(o.H(E.source)){const ye=W.sources&&Object.hasOwn(W.sources,E.source)?W.sources[E.source]:void 0,Ce=ye&&o.u(ye.type);ye?Ce==="vector"&&ne==="raster"?N.push(new jt(z,E.source,`layer "${E.id}" requires a raster source`)):Ce==="raster"&&ne!=="raster"?N.push(new jt(z,E.source,`layer "${E.id}" requires a vector source`)):Ce!=="vector"||E["source-layer"]?Ce==="raster-dem"&&ne!=="hillshade"?N.push(new jt(z,E.source,"raster-dem source can only be used with layer type 'hillshade'.")):Ce!=="raster-array"||["raster","raster-particle"].includes(ne)?ne==="line"&&E.paint&&E.paint["line-gradient"]&&Ce==="geojson"&&!ye.lineMetrics?N.push(new jt(z,E,`layer "${E.id}" specifies a line-gradient, which requires the GeoJSON source to have \`lineMetrics\` enabled.`)):ne==="line"&&E.paint&&E.paint["line-trim-offset"]&&Ce==="geojson"&&!ye.lineMetrics?N.push(new jt(z,E,`layer "${E.id}" specifies a line-trim-offset, which requires the GeoJSON source to have \`lineMetrics\` enabled.`)):ne==="raster-particle"&&Ce!=="raster-array"&&N.push(new jt(z,E.source,`layer "${E.id}" requires a 'raster-array' source.`)):N.push(new jt(z,E.source,"raster-array source can only be used with layer type 'raster'.")):N.push(new jt(z,E,`layer "${E.id}" must specify a "source-layer"`)):N.push(new jt(z,E.source,`source "${E.source}" not found`))}else N.push(new jt(`${z}.source`,E.source,'"source" must be a string'));else N.push(new jt(z,E,'missing required property "source"'));return N=N.concat(Ei({key:z,value:E,valueSpec:Z.layer,style:L.style,styleSpec:L.styleSpec,objectElementValidators:{"*":()=>[],type:()=>Ur({key:`${z}.type`,value:E.type,valueSpec:Z.layer.type,style:L.style,styleSpec:L.styleSpec,object:E,objectKey:"type"}),filter:ye=>un({layerType:ne,...ye}),layout:ye=>Ei({layer:E,key:ye.key,value:ye.value,valueSpec:{},style:ye.style,styleSpec:ye.styleSpec,objectElementValidators:{"*":Ce=>En({layerType:ne,...Ce})}}),paint:ye=>Ei({layer:E,key:ye.key,value:ye.value,valueSpec:{},style:ye.style,styleSpec:ye.styleSpec,objectElementValidators:{"*":Ce=>Qn({layerType:ne,layer:E,...Ce})}}),appearances(ye){const Ce=rs({key:ye.key,value:ye.value,valueSpec:ye.valueSpec,style:ye.style,styleSpec:ye.styleSpec,arrayElementValidator:Ze=>function(mt){const{key:vt,layer:bt,layerType:St}=mt,Pt=o.u(mt.value),Gt=o.u(Pt.name),as=o.u(Pt.condition),ms=Ei({key:vt,value:Pt,valueSpec:mt.styleSpec.appearance,style:mt.style,styleSpec:mt.styleSpec,objectElementValidators:{condition:Gs=>function(Ms){const Js=[];return Js.push(...Bs({key:Ms.key,value:Ms.object.condition,valueSpec:o.s.appearance.condition,expressionContext:"appearance"})),Js}({...Gs}),properties:Gs=>function(Ms){const Js=[],{styleSpec:Os,layer:Ks,layerType:_n}=Ms,ln=Os[`paint_${_n}`],an=Os[`layout_${_n}`],bn=Ms.object[Ms.objectKey];for(const Sn in bn){const lr=Sn in ln?"paint":Sn in an?"layout":void 0;if(!lr){Js.push(new jt(Ms.key,Sn,`unknown property "${Sn}" for layer type "${_n}"`));continue}const Mn={...Ms,key:`${Ms.key}.${Sn}`,objectKey:Sn,layer:Ks,layerType:_n,value:bn[Sn],valueSpec:lr==="paint"?ln[Sn]:an[Sn]};Js.push(...Sr(Mn,lr))}return Js}({layer:bt,layerType:St,...Gs})}});return Gt!=="hidden"&&as===void 0&&ms.push(new jt(mt.key,"name",'Appearance with name different than "hidden" must have a condition')),ms}({layerType:ne,layer:E,...Ze})}),Pe=Array.isArray(ye.value)?ye.value:[],Ke=new Set;return Pe.forEach((Ze,mt)=>{const vt=o.u(Ze.name);if(vt)if(Ke.has(vt)){const bt=o.u(E.id);Ce.push(new jt(ye.key,vt,`Duplicated appearance name "${vt}" for layer "${bt}"`))}else Ke.add(vt)}),Ce}}})),N}function xn({key:L,value:N}){return o.H(N)?[]:[new jt(L,N,`string expected, ${o.n(N)} found`)]}const Ar={promoteId:function L({key:N,value:E}){if(o.H(E))return xn({key:N,value:E});if(Array.isArray(E)){const W=[],Z=o.y(E),ne=o.c(Z);return ne.result==="error"?(ne.value.forEach(de=>{W.push(new jt(`${N}${de.key}`,null,`${de.message}`))}),W):(o.B(ne.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"])||W.push(new jt(`${N}`,null,"promoteId expression should be only feature dependent")),W)}if(!o.l(E))return[new jt(N,E,`string, expression or object expected, "${o.n(E)}" found`)];const z=[];for(const W in E)z.push(...L({key:`${N}.${W}`,value:E[W]}));return z}};function Zr(L){const N=L.value,E=L.key,z=L.styleSpec,W=L.style;if(!o.l(N))return[new jt(E,N,`object expected, ${o.n(N)} found`)];if(!("type"in N))return[new jt(E,N,'"type" is required')];const Z=o.u(N.type);let ne=[];switch(["vector","raster","raster-dem","raster-array"].includes(Z)&&("url"in N||"tiles"in N||ne.push(new gt(E,N,'Either "url" or "tiles" is required.'))),Z){case"vector":case"raster":case"raster-dem":case"raster-array":return ne=ne.concat(Ei({key:E,value:N,valueSpec:z[`source_${Z.replace("-","_")}`],style:L.style,styleSpec:z,objectElementValidators:Ar})),ne;case"geojson":if(ne=Ei({key:E,value:N,valueSpec:z.source_geojson,style:W,styleSpec:z,objectElementValidators:Ar}),"cluster"in N&&"clusterProperties"in N){if(!o.l(N.clusterProperties))return[new jt(`${E}.clusterProperties`,N,`object expected, ${o.n(N)} found`)];for(const de in N.clusterProperties){const ye=N.clusterProperties[de];if(!Array.isArray(ye))return[new jt(`${E}.clusterProperties.${de}`,ye,"array expected")];const[Ce,Pe]=ye,Ke=typeof Ce=="string"?[Ce,["accumulated"],["get",de]]:Ce;ne.push(...Bs({key:`${E}.${de}.map`,value:Pe,expressionContext:"cluster-map"})),ne.push(...Bs({key:`${E}.${de}.reduce`,value:Ke,expressionContext:"cluster-reduce"}))}}return ne;case"video":return Ei({key:E,value:N,valueSpec:z.source_video,style:W,styleSpec:z});case"image":return Ei({key:E,value:N,valueSpec:z.source_image,style:W,styleSpec:z});case"canvas":return[new jt(E,null,"Please use runtime APIs to add canvas sources, rather than including them in stylesheets.","source.canvas")];default:return In({key:`${E}.type`,value:N.type,valueSpec:{values:dn(z)}})}}function dn(L){return L.source.reduce((N,E)=>{const z=L[E];return z.type.type==="enum"&&(N=N.concat(Object.keys(z.type.values||{}))),N},[])}function Kt(L,N){const E=!L.includes("://");try{return new URL(L,E&&N?"http://example.com":void 0),!0}catch{return!1}}function Er(L){const N=L.value;return N?o.H(N)?Kt(N,!0)?[]:[new jt(L.key,N,`invalid url "${N}"`)]:[new jt(L.key,N,`string expected, "${o.n(N)}" found`)]:[]}function ti(L){const N=L.value,E=L.styleSpec,z=E.light,W=L.style;if(N===void 0)return[];if(!o.l(N))return[new jt("light",N,`object expected, ${o.n(N)} found`)];let Z=[];for(const ne in N){const de=ne.match(o.K),ye=ne.match(o.U);Z=Z.concat(ye&&z[ye[1]]?Ur({key:ne,value:N[ne],valueSpec:{type:"string"},style:W,styleSpec:E}):de&&z[de[1]]&&z[de[1]].transition?Ur({key:ne,value:N[ne],valueSpec:E.transition,style:W,styleSpec:E}):z[ne]?Ur({key:ne,value:N[ne],valueSpec:z[ne],style:W,styleSpec:E}):[new jt(ne,N[ne],`unknown property "${ne}"`)])}return Z}function Ba(L){const N=L.value;if(!N)return[];const E=L.key;if(!o.l(N))return[new jt(E,N,`object expected, ${o.n(N)} found`)];let z=[];const W=L.styleSpec,Z=W["light-3d"],ne=L.style,de=L.style.lights;for(const Pe of["type","id"])if(!(Pe in N))return z=z.concat([new jt(E,N,`missing property "${Pe}"`)]),z;if(!o.H(N.type))return z=z.concat([new jt(`${E}.type`,N.type,"string expected")]),z;if(de)for(let Pe=0;Pe[],array:rs,boolean:function(L){const N=L.value,E=L.key;return o.G(N)?[]:[new jt(E,N,`boolean expected, ${o.n(N)} found`)]},number:Ns,color:function({key:L,value:N}){return o.H(N)?o.C.parse(o.u(N))===void 0?[new jt(L,N,`color expected, "${N}" found`)]:[]:[new jt(L,N,`color expected, ${o.n(N)} found`)]},enum:In,filter:un,function:us,layer:pr,object:Ei,source:Zr,model:Er,light:ti,"light-3d":Ba,terrain:lo,fog:Yn,string:xn,formatted:function(L){return xn(L).length===0?[]:Bs(L)},resolvedImage:function(L){return xn(L).length===0?[]:Bs(L)},projection:function(L){const N=L.value,E=L.styleSpec,z=E.projection,W=L.style;if(o.l(N)){let Z=[];for(const ne in N)Z=Z.concat(Ur({key:ne,value:N[ne],valueSpec:z[ne],style:W,styleSpec:E}));return Z}return o.H(N)?[]:[new jt("projection",N,`object or string expected, ${o.n(N)} found`)]},import:function(L){const N=L.key,{value:E,styleSpec:z}=L;if(!o.l(E))return[new jt(N,E,"import must be an object")];const{data:W,...Z}=E;Object.defineProperty(Z,"__line__",{value:E.__line__,enumerable:!1});let ne=Ei({...L,value:Z,valueSpec:z.import});o.u(Z.id)===""&&ne.push(new jt(`${L.key}.id`,Z,"import id can't be an empty string"));const de=o.u(Z.id);return de!=="__proto__"&&de!=="constructor"&&de!=="prototype"||ne.push(new jt(`${L.key}.id`,Z,`import id can't be "${String(de)}"`)),W&&(ne=ne.concat(co(W,z,{key:`${L.key}.data`}))),ne},iconset:function(L){const N=L.value,E=L.key,z=L.styleSpec,W=L.style;if(!o.l(N))return[new jt(E,N,"object expected")];if(!N.type)return[new jt(E,N,'"type" is required')];const Z=o.u(N.type);let ne=[];if(ne=ne.concat(Ei({key:E,value:N,valueSpec:z[`iconset_${Z}`],style:W,styleSpec:z})),function(de,ye){return!(de!=="source"||!ye.source)}(Z,N)){const de=W.sources&&Object.hasOwn(W.sources,N.source)?W.sources[N.source]:void 0,ye=de&&o.u(de.type);de?ye!=="raster-array"&&ne.push(new jt(E,N.source,`iconset cannot be used with a source of type ${String(ye)}, it only be used with a "raster-array" source type`)):ne.push(new jt(E,N.source,`source "${N.source}" not found`))}return ne},option:function(L){const N=L.styleSpec,E=L.value,z=o.l(E)&&o.u(E.array)===!0||!o.l(E)?void 0:o.u(E.type);return Ei({...L,valueSpec:N.option,objectElementValidators:{default:W=>{const Z=W.value;return o.l(Z)?Ur({...W,valueSpec:{...W.valueSpec,type:"*",expression:void 0}}):z&&Array.isArray(Z)?Ur({...W,valueSpec:{...W.valueSpec,type:z}}):Ur(W)}}})}};function Ur(L,N=!1){const E=L.value,z=L.valueSpec,W=L.styleSpec;if(z.expression){if(o.M(o.u(E)))return us(L);if(o.x(o.y(E)))return Bs(L)}if(z.type&&Hr[z.type]){const Z=Hr[z.type](L);return N===!0&&Z.length>0&&Array.isArray(L.value)?Bs(L):Z}return Ei({...L,valueSpec:z.type?W[z.type]:z})}function Ei(L){const N=L.key,E=L.value,z=L.valueSpec||{},W=L.objectElementValidators||{},Z=L.style,ne=L.styleSpec;if(!o.l(E))return[new jt(N,E,`object expected, ${o.n(E)} found`)];let de=[];for(const ye in E){if(!Object.hasOwn(E,ye))continue;const Ce=ye.split(".")[0],Pe=Object.hasOwn(z,Ce),Ke=Object.hasOwn(z,"*"),Ze=Pe?z[Ce]:Ke?z["*"]:void 0;let mt;Object.hasOwn(W,Ce)?mt=W[Ce]:Pe?mt=Ur:Object.hasOwn(W,"*")?mt=W["*"]:Ke&&(mt=Ur),mt?de=de.concat(mt({key:(N&&`${N}.`)+ye,value:E[ye],valueSpec:Ze,style:Z,styleSpec:ne,object:E,objectKey:ye},E)):de.push(new gt(N,E[ye],`unknown property "${ye}"`))}for(const ye in z){if(!Object.hasOwn(z,ye)||Object.hasOwn(W,ye))continue;const Ce=z[ye];!Ce.required||Ce.default!==void 0||Object.hasOwn(E,ye)&&E[ye]!==void 0||de.push(new jt(N,E,`missing required property "${ye}"`))}return de}function fo({key:L,value:N}){const E=xn({key:L,value:N});if(E.length)return E;const z=N;return z.includes("{fontstack}")||E.push(new jt(L,N,'"glyphs" url must include a "{fontstack}" token')),z.includes("{range}")||E.push(new jt(L,N,'"glyphs" url must include a "{range}" token')),E}function co(L,N=o.s,E={}){return Ei({key:E.key||"",value:L,valueSpec:{...N.$root,"*":{type:"*"}},styleSpec:N,style:L,objectElementValidators:{glyphs:fo}})}function Tn(L){return L.slice().sort((N,E)=>N.line&&E.line?N.line-E.line:0)}const Mr="setStyle",Aa="addLayer",Lo="removeLayer",Ac="setPaintProperty",vl="setLayerProperty",Ol="setTerrain",To="removeImport",_a="addIconset",$o="removeIconset";function jh(L,N,E){E.push({command:"addSource",args:[L,N[L]]})}function Mu(L,N,E){N.push({command:"removeSource",args:[L]}),E[L]=!0}function dh(L,N,E,z){Mu(L,E,z),jh(L,N,E)}function Jr(L,N,E){let z;for(z in L[E])if(Object.hasOwn(L[E],z)&&z!=="data"&&!o.O(L[E][z],N[E][z]))return!1;for(z in N[E])if(Object.hasOwn(N[E],z)&&z!=="data"&&!o.O(L[E][z],N[E][z]))return!1;return!0}function Uo(L,N,E,z,W,Z){let ne;for(ne in N=N||{},L=L||{})Object.hasOwn(L,ne)&&(o.O(L[ne],N[ne])||E.push({command:Z,args:[z,ne,N[ne],W]}));for(ne in N)Object.hasOwn(N,ne)&&!Object.hasOwn(L,ne)&&(o.O(L[ne],N[ne])||E.push({command:Z,args:[z,ne,N[ne],W]}))}function fc(L){return L.id}function Lc(L,N){return L[N.id]=N,L}const Ss=new o.C(1,0,0,1),wa=new o.C(0,1,0,1),Ci=new o.C(0,0,1,1),fa=new o.C(1,0,1,1),zn=new o.C(0,1,1,1);function Rr(L,N,E,z,W,Z,ne){const de=L.context,ye=L.transform,Ce=de.gl,Pe=ye.projection.name==="globe",Ke=Pe?["PROJECTION_GLOBE_VIEW"]:[];let Ze=o.Q(E.projMatrix);if(Pe&&o.S(ye.zoom)>0){const an=o.V(E.canonical,ye),bn=o.W(an);Ze=o.X(new Float32Array(16),ye.globeMatrix,bn),o.X(Ze,ye.projMatrix,Ze)}const mt=o.Y();mt[12]+=2*W/(o.e.devicePixelRatio*ye.width),mt[13]+=2*Z/(o.e.devicePixelRatio*ye.height),o.X(Ze,mt,Ze);const vt=L.getOrCreateProgram("debug",{defines:Ke}),bt=N.getTileByID(E.key);L.terrain&&L.terrain.setupElevationDraw(bt,vt);const St=o.Z.disabled,Pt=o._.disabled,Gt=L.colorModeForRenderPass(),as="$debug";de.activeTexture.set(Ce.TEXTURE0),L.emptyTexture.bind(Ce.LINEAR,Ce.CLAMP_TO_EDGE),Pe?bt._makeGlobeTileDebugBuffers(L.context,ye):bt._makeDebugTileBoundsBuffers(L.context,ye.projection);const ms=bt._tileDebugBuffer||L.debugBuffer,Gs=bt._tileDebugIndexBuffer||L.debugIndexBuffer,Ms=bt._tileDebugSegments||L.debugSegments;if(vt.draw(L,Ce.LINE_STRIP,St,Pt,Gt,o.$.disabled,o.a0(Ze,z.toPremultipliedRenderColor(null)),as,ms,Gs,Ms,null,null,null,[bt._globeTileDebugBorderBuffer]),ne){const an=bt.latestRawTileData,bn=Math.floor((an&&an.byteLength||0)/1024);let Sn=E.canonical.toString();E.overscaledZ!==E.canonical.z&&(Sn+=` => ${E.overscaledZ}`),Sn+=` ${bt.state}`,Sn+=` ${bn}kb`,function(lr,Mn){lr.initDebugOverlayCanvas();const Hn=lr.debugOverlayCanvas,Tr=lr.context.gl,oa=lr.debugOverlayCanvas.getContext("2d");oa.clearRect(0,0,Hn.width,Hn.height),oa.shadowColor="white",oa.shadowBlur=2,oa.lineWidth=1.5,oa.strokeStyle="white",oa.textBaseline="top",oa.font="bold 36px Open Sans, sans-serif",oa.fillText(Mn,5,5),oa.strokeText(Mn,5,5),lr.debugOverlayTexture.update(Hn),lr.debugOverlayTexture.bind(Tr.LINEAR,Tr.CLAMP_TO_EDGE)}(L,Sn)}const Js=N.getTile(E).tileSize,Os=512/Math.min(Js,512)*(E.overscaledZ/ye.zoom)*.5,Ks=bt._tileDebugTextBuffer||L.debugBuffer,_n=bt._tileDebugTextIndexBuffer||L.quadTriangleIndexBuffer,ln=bt._tileDebugTextSegments||L.debugSegments;vt.draw(L,Ce.TRIANGLES,St,Pt,o.a1.alphaBlended,o.$.disabled,o.a0(Ze,o.C.transparent.toPremultipliedRenderColor(null),Os),as,Ks,_n,ln,null,null,null,[bt._globeTileDebugTextBuffer])}function ja(L,N,E,z){zo(L,0,N+E/2,L.transform.width,E,z)}function Il(L,N,E,z){zo(L,N-E/2,0,E,L.transform.height,z)}function zo(L,N,E,z,W,Z){const ne=L.context,de=ne.gl;de.enable(de.SCISSOR_TEST),de.scissor(N*o.e.devicePixelRatio,E*o.e.devicePixelRatio,z*o.e.devicePixelRatio,W*o.e.devicePixelRatio),ne.clear({color:Z}),de.disable(de.SCISSOR_TEST)}function Hl(L,N,E){const z=L.context,W=z.gl,Z=E.projMatrix,ne=L.getOrCreateProgram("debug"),de=N.getTileByID(E.key);L.terrain&&L.terrain.setupElevationDraw(de,ne);const ye=o.Z.disabled,Ce=o._.disabled,Pe=L.colorModeForRenderPass(),Ke="$debug";z.activeTexture.set(W.TEXTURE0),L.emptyTexture.bind(W.LINEAR,W.CLAMP_TO_EDGE);const Ze=de.queryGeometryDebugViz,mt=de.queryBoundsDebugViz;if(Ze&&Ze.vertices.length>0){Ze.lazyUpload(z);const vt=Ze.vertexBuffer,bt=Ze.indexBuffer,St=Ze.segments;vt!=null&&bt!=null&&St!=null&&ne.draw(L,W.LINE_STRIP,ye,Ce,Pe,o.$.disabled,o.a0(Z,Ze.color.toPremultipliedRenderColor(null)),Ke,vt,bt,St)}if(mt&&mt.vertices.length>0){mt.lazyUpload(z);const vt=mt.vertexBuffer,bt=mt.indexBuffer,St=mt.segments;vt!=null&&bt!=null&&St!=null&&ne.draw(L,W.LINE_STRIP,ye,Ce,Pe,o.$.disabled,o.a0(Z,mt.color.toPremultipliedRenderColor(null)),Ke,vt,bt,St)}}const Cf=(L,N,E,z,W,Z,ne,de)=>{const ye=o.a2/Z.tileSize;return{u_matrix:L,u_inv_rot_matrix:N,u_camera_to_center_distance:E.getCameraToCenterDistance(de),u_extrude_scale:[E.pixelsToGLUnits[0]/ye,E.pixelsToGLUnits[1]/ye],u_zoom_transition:z,u_tile_id:ne,u_merc_center:W}},oi=(L,N,E,z)=>({u_matrix:L,u_inv_matrix:N,u_camera_to_center_distance:E.getCameraToCenterDistance(z),u_viewport_size:[E.width,E.height]});function Mo(L,N,E){const z=N.createTileMatrix(L,L.worldSize,E.toUnwrapped());return o.X(new Float32Array(16),L.projMatrix,z)}function zh(L,N,E){if(N.projection.name===E.projection.name)return L.projMatrix;const z=E.clone();return z.setProjection(N.projection),Mo(z,N.getProjection(),L)}function Gm(L,N,E){return N.name===E.projection.name?L.projMatrix:Mo(E,N,L)}let Gu;const Zd={loaded:!0,validateStyle:function(L,N=o.s){return Tn(co(L,N))},validateSource:L=>Tn(Zr(L)),validateLight:L=>Tn(ti(L)),validateLights:L=>Tn(Ba(L)),validateTerrain:L=>Tn(lo(L)),validateFog:L=>Tn(Yn(L)),validateSnow:L=>Tn(function(N){const E=N.value,z=N.style,W=N.styleSpec,Z=W.snow;if(E===void 0)return[];if(!o.l(E))return[new jt("snow",E,`object expected, ${o.n(E)} found`)];let ne=[];for(const de in E){const ye=de.match(o.K);ne=ne.concat(ye&&Z[ye[1]]&&Z[ye[1]].transition?Ur({key:de,value:E[de],valueSpec:W.transition,style:z,styleSpec:W}):Z[de]?Ur({key:de,value:E[de],valueSpec:Z[de],style:z,styleSpec:W}):[new gt(de,E[de],`unknown property "${de}"`)])}return ne}(L)),validateRain:L=>Tn(function(N){const E=N.value,z=N.style,W=N.styleSpec,Z=W.rain;if(E===void 0)return[];if(!o.l(E))return[new jt("rain",E,`object expected, ${o.n(E)} found`)];let ne=[];for(const de in E){const ye=de.match(o.K);ne=ne.concat(ye&&Z[ye[1]]&&Z[ye[1]].transition?Ur({key:de,value:E[de],valueSpec:W.transition,style:z,styleSpec:W}):Z[de]?Ur({key:de,value:E[de],valueSpec:Z[de],style:z,styleSpec:W}):[new gt(de,E[de],`unknown property "${de}"`)])}return ne}(L)),validateLayer:L=>Tn(pr(L)),validateFilter:L=>Tn(un(L)),validatePaintProperty:L=>Tn(Qn(L)),validateLayoutProperty:L=>Tn(En(L)),validateModel:L=>Tn(Er(L)),diffStyles:function(L,N){if(!L)return[{command:Mr,args:[N]}];let E=[];try{if(!o.O(L.version,N.version))return[{command:Mr,args:[N]}];if(o.O(L.center,N.center)||E.push({command:"setCenter",args:[N.center]}),o.O(L.zoom,N.zoom)||E.push({command:"setZoom",args:[N.zoom]}),o.O(L.bearing,N.bearing)||E.push({command:"setBearing",args:[N.bearing]}),o.O(L.pitch,N.pitch)||E.push({command:"setPitch",args:[N.pitch]}),o.O(L.sprite,N.sprite)||E.push({command:"setSprite",args:[N.sprite]}),o.O(L.glyphs,N.glyphs)||E.push({command:"setGlyphs",args:[N.glyphs]}),o.O(L.imports,N.imports)||function(de=[],ye=[],Ce){ye=ye||[];const Pe=(de=de||[]).map(fc),Ke=ye.map(fc),Ze=de.reduce(Lc,{}),mt=ye.reduce(Lc,{}),vt=Pe.slice();let bt,St,Pt,Gt;for(bt=0,St=0;bt{de.source&&z[de.source]?E.push({command:Lo,args:[de.id]}):Z.push(de)});let ne=L.terrain;ne&&z[ne.source]&&(E.push({command:Ol,args:[void 0]}),ne=void 0),E=E.concat(W),o.O(ne,N.terrain)||E.push({command:Ol,args:[N.terrain]}),function(de,ye,Ce){ye=ye||[];const Pe=(de=de||[]).map(fc),Ke=ye.map(fc),Ze=de.reduce(Lc,{}),mt=ye.reduce(Lc,{}),vt=Pe.slice(),bt=Object.create(null);let St,Pt,Gt,as,ms,Gs,Ms;for(St=0,Pt=0;St0){const ta=o.Y(),Ta=Nr;o.a9(ta,ln.placementInvProjMatrix,Ce.glCoordMatrix),o.a9(ta,ta,ln.placementViewportMatrix),St.push({circleArray:Fr,circleOffset:Gt,transform:Ta,invTransform:ta,projection:ln.getProjection()}),Pt+=Fr.length/4,Gt=Pt}if(!cr)continue;L.terrain&&L.terrain.setupElevationDraw(_n,qa);const Fa=Qr?[Ks.canonical.x,Ks.canonical.y,1<{const E=Zd[L];return E?E(...N):[]}}const $h=Sd("validateStyle"),Af=Sd("validateSource"),Gp=Sd("validateLight"),Ef=Sd("validateLights"),Wx=Sd("validateTerrain"),rl=Sd("validateFog"),to=Sd("validateSnow"),Pg=Sd("validateRain"),Kx=Sd("validateLayer"),Tt=Sd("validateFilter"),He=Sd("validatePaintProperty"),ot=Sd("validateLayoutProperty"),At=Sd("validateModel"),Ht=o.s.light;let qt;class Wt extends o.E{constructor(N,E="flat"){super(),this._transitionable=new o.ae(qt||(qt=new o.af({anchor:new o.ag(Ht.anchor),position:new o.ah(Ht.position),color:new o.ag(Ht.color),intensity:new o.ag(Ht.intensity)}))),this.setLight(N,E),this._transitioning=this._transitionable.untransitioned()}getLight(){return this._transitionable.serialize()}setLight(N,E,z={}){this._validate(Gp,N,z)||(this._transitionable.setTransitionOrValue(N),this.id=E)}updateTransitions(N){this._transitioning=this._transitionable.transitioned(N,this._transitioning)}hasTransition(){return this._transitioning.hasTransition()}recalculate(N){this.properties=this._transitioning.possiblyEvaluate(N)}_validate(N,E,z){return(!z||z.validate!==!1)&&Mg(this,N.call($h,{value:E,style:{glyphs:!0,sprite:!0},styleSpec:o.s}))}}const Xt=o.s.terrain;let ns=class extends o.E{constructor(L,N,E,z,W){super(),this.scope=E,this._transitionable=new o.ae(new o.af({source:new o.ag(Xt.source),exaggeration:new o.ag(Xt.exaggeration)}),E,z),this._transitionable.setTransitionOrValue(L,z),this._transitioning=this._transitionable.untransitioned(),this.drapeRenderMode=N,this.worldview=W}get(){return this._transitionable.serialize()}set(L,N){this._transitionable.setTransitionOrValue(L,N)}updateTransitions(L){this._transitioning=this._transitionable.transitioned(L,this._transitioning)}hasTransition(){return this._transitioning.hasTransition()}recalculate(L){this.properties=this._transitioning.possiblyEvaluate(L)}getExaggeration(L){return this._transitioning.possiblyEvaluate(new o.ai(L,{worldview:this.worldview})).get("exaggeration")}getAttenuationRange(){if(!this.isZoomDependent())return null;const L=this._transitionable._values.exaggeration;if(!L)return null;const N=L.value.expression;if(!N)return null;let E=-1,z=-1,W=1;for(const Z of N.zoomStops)W=N.evaluate(new o.ai(Z,{worldview:this.worldview})),W>.01?(E=Z,z=-1):z=Z;return W<.01&&E>0&&z>E?[E,z]:null}isZoomDependent(){const L=this._transitionable._values.exaggeration;return L!=null&&L.value!=null&&L.value.expression!=null&&L.value.expression instanceof o.aj}};function ps(L,N){const E=L?L.terrain:null;return!!E&&(!N||!!N.projection.requiresDraping||!E.isZoomDependent()||E.getExaggeration(N.zoom)>0)}const Zs=o.s.fog;class rn extends o.E{constructor(N,E,z,W){super();const Z=new o.af({range:new o.ag(Zs.range),color:new o.ag(Zs.color),"color-use-theme":new o.ag({type:"string","property-type":"data-constant",default:"default"}),"high-color":new o.ag(Zs["high-color"]),"high-color-use-theme":new o.ag({type:"string","property-type":"data-constant",default:"default"}),"space-color":new o.ag(Zs["space-color"]),"space-color-use-theme":new o.ag({type:"string","property-type":"data-constant",default:"default"}),"horizon-blend":new o.ag(Zs["horizon-blend"]),"star-intensity":new o.ag(Zs["star-intensity"]),"vertical-range":new o.ag(Zs["vertical-range"])});this._transitionable=new o.ae(Z,z,W),this.set(N,W),this._transitioning=this._transitionable.untransitioned(),this._transform=E,this.properties=new o.ak(Z),this.scope=z}get state(){const N=this._transform,E=N.projection.name==="globe",z=o.S(N.zoom),W=this.properties.get("range"),Z=[2,4.5],ne=.5/Math.tan(.5*N._fov),de=[W[0]+ne,W[1]+ne];return{range:E?[o.al(Z[0],de[0],z),o.al(Z[1],de[1],z)]:de,horizonBlend:this.properties.get("horizon-blend"),alpha:this.properties.get("color").a}}get(){return this._transitionable.serialize()}set(N,E,z={}){if(this._validate(rl,N,z))return;const W={...N};for(const Z of Object.keys(Zs))W[Z]===void 0&&(W[Z]=Zs[Z].default);this._options=W,this._transitionable.setTransitionOrValue(this._options,E)}getOpacity(N){if(!this._transform.projection.supportsFog)return 0;const E=this.properties&&this.properties.get("color")||1;return(this._transform.projection.name==="globe"?1:o.am(o.ao,o.an,N))*E.a}getOpacityAtLatLng(N,E){return this._transform.projection.supportsFog?o.ap(this.state,N,E):0}getOpacityForTile(N){if(!this._transform.projection.supportsFog)return[1,1];const E=this._transform.calculateFogTileMatrix(N.toUnwrapped());return o.aq(this.state,E,0,0,o.a2,o.a2,this._transform)}getOpacityForBounds(N,E,z,W,Z){return this._transform.projection.supportsFog?o.aq(this.state,N,E,z,W,Z,this._transform):[1,1]}getRangeForProjection(){return this._transform.projection.supportsFog?this.state.range:[0,1]}isVisibleOnFrustum(N){if(!this._transform.projection.supportsFog)return!1;const E=[4,5,6,7];for(const z of E){const W=N.points[z];let Z;if(W[2]>=0)Z=W;else{const ne=N.points[z-4];Z=o.ar(ne,W,ne[2]/(ne[2]-W[2]))}if(o.as(this.state,Z[0],Z[1],0,this._transform)>=o.at)return!0}return!1}updateConfig(N){this._transitionable.setTransitionOrValue(this._options,N)}updateTransitions(N){this._transitioning=this._transitionable.transitioned(N,this._transitioning)}hasTransition(){return this._transitioning.hasTransition()}recalculate(N){this.properties=this._transitioning.possiblyEvaluate(N)}_validate(N,E,z){return(!z||z.validate!==!1)&&Mg(this,N.call($h,{value:E,style:{glyphs:!0,sprite:!0},styleSpec:o.s}))}}let mn,qn,Zn=class extends o.E{constructor(L,N,E,z){super();const W=mn||(mn=new o.af({density:new o.ag(o.s.snow.density),intensity:new o.ag(o.s.snow.intensity),color:new o.ag(o.s.snow.color),opacity:new o.ag(o.s.snow.opacity),vignette:new o.ag(o.s.snow.vignette),"vignette-color":new o.ag(o.s.snow["vignette-color"]),"center-thinning":new o.ag(o.s.snow["center-thinning"]),direction:new o.ag(o.s.snow.direction),"flake-size":new o.ag(o.s.snow["flake-size"])}));this._transitionable=new o.ae(W,E,z),this.set(L,z),this._transitioning=this._transitionable.untransitioned(),this.properties=new o.ak(W),this.scope=E}get state(){const L=this.properties.get("opacity"),N=this.properties.get("color"),E=this.properties.get("direction"),z=o.au(E[0]),W=-Math.max(o.au(E[1]),.01),Z=[Math.cos(z)*Math.cos(W),Math.sin(z)*Math.cos(W),Math.sin(W)],ne=this.properties.get("vignette"),de=this.properties.get("vignette-color"),ye=new o.C(de.r,de.g,de.b,ne);return{density:this.properties.get("density"),intensity:this.properties.get("intensity"),color:new o.C(N.r,N.g,N.b,N.a*L),direction:Z,centerThinning:this.properties.get("center-thinning"),flakeSize:this.properties.get("flake-size"),vignetteColor:ye}}get(){return this._transitionable.serialize()}set(L,N,E={}){if(this._validate(to,L,E))return;const z={...L},W=o.s.snow;for(const Z of Object.keys(W))z[Z]===void 0&&(z[Z]=W[Z].default);this._options=z,this._transitionable.setTransitionOrValue(this._options,N)}updateConfig(L){this._transitionable.setTransitionOrValue(this._options,L)}updateTransitions(L){this._transitioning=this._transitionable.transitioned(L,this._transitioning)}hasTransition(){return this._transitioning.hasTransition()}recalculate(L){this.properties=this._transitioning.possiblyEvaluate(L)}_validate(L,N,E){return(!E||E.validate!==!1)&&Mg(this,L.call($h,{value:N,style:{glyphs:!0,sprite:!0},styleSpec:o.s}))}},la=class extends o.E{constructor(L,N,E,z){super();const W=qn||(qn=new o.af({density:new o.ag(o.s.rain.density),intensity:new o.ag(o.s.rain.intensity),color:new o.ag(o.s.rain.color),opacity:new o.ag(o.s.rain.opacity),vignette:new o.ag(o.s.rain.vignette),"vignette-color":new o.ag(o.s.rain["vignette-color"]),"center-thinning":new o.ag(o.s.rain["center-thinning"]),direction:new o.ag(o.s.rain.direction),"droplet-size":new o.ag(o.s.rain["droplet-size"]),"distortion-strength":new o.ag(o.s.rain["distortion-strength"])}));this._transitionable=new o.ae(W,E,z),this.set(L,z),this._transitioning=this._transitionable.untransitioned(),this.properties=new o.ak(W),this.scope=E}get state(){const L=this.properties.get("opacity"),N=this.properties.get("color"),E=this.properties.get("direction"),z=o.au(E[0]),W=-Math.max(o.au(E[1]),.01),Z=[Math.cos(z)*Math.cos(W),Math.sin(z)*Math.cos(W),Math.sin(W)],ne=this.properties.get("vignette-color"),de=new o.C(ne.r,ne.g,ne.b,this.properties.get("vignette"));return{density:this.properties.get("density"),intensity:this.properties.get("intensity"),color:new o.C(N.r,N.g,N.b,N.a*L),direction:Z,centerThinning:this.properties.get("center-thinning"),dropletSize:this.properties.get("droplet-size"),distortionStrength:this.properties.get("distortion-strength"),vignetteColor:de}}get(){return this._transitionable.serialize()}set(L,N,E={}){if(this._validate(Pg,L,E))return;const z={...L},W=o.s.rain;for(const Z of Object.keys(W))z[Z]===void 0&&(z[Z]=W[Z].default);this._options=z,this._transitionable.setTransitionOrValue(this._options,N)}updateConfig(L){this._transitionable.setTransitionOrValue(this._options,L)}updateTransitions(L){this._transitioning=this._transitionable.transitioned(L,this._transitioning)}hasTransition(){return this._transitioning.hasTransition()}recalculate(L){this.properties=this._transitioning.possiblyEvaluate(L)}_validate(L,N,E){return(!E||E.validate!==!1)&&Mg(this,L.call($h,{value:N,style:{glyphs:!0,sprite:!0},styleSpec:o.s}))}};const Br={workerUrl:"",workerClass:null,workerParams:void 0};function wr(L){return Br.workerClass!=null?new Br.workerClass:new self.Worker(Br.workerUrl,{name:L,type:"module",...Br.workerParams})}const Ea="mapboxgl_preloaded_worker_pool";class na{constructor(N){this.active={},this.workers=null,this.name=N}acquire(N,E=na.workerCount){if(!this.workers)for(this.workers=[];this.workers.length{E.terminate()}),this.workers=null)}isPreloaded(){return!!this.active[Ea]}numActive(){return Object.keys(this.active).length}}na.workerCount=2;class yi{constructor(N,E,z="Worker",W=na.workerCount){this.workerPool=N,this.actors=[],this.currentActor=0,this.id=o.av();const Z=this.workerPool.acquire(this.id,W);for(let ne=0;ne{this.ready=!0}).catch(()=>{})}send(N,E,z){return Promise.all(this.actors.map(W=>W.send(N,E,z)))}broadcast(N,E){for(const z of this.actors)z.notify(N,E)}getActor(){return this.currentActor=(this.currentActor+1)%this.actors.length,this.actors[this.currentActor]}remove(){this.actors.forEach(N=>{N.remove()}),this.actors=[],this.workerPool.release(this.id)}}yi.Actor=o.aw;class so extends o.E{constructor(N,E,z,W){super(),this.scope=z,this._options=N,this.properties=new o.ak(E),this._transitionable=new o.ae(E,z,W),this._transitionable.setTransitionOrValue(N.properties),this._transitioning=this._transitionable.untransitioned()}updateConfig(N){this._transitionable.setTransitionOrValue(this._options.properties,N)}updateTransitions(N){this._transitioning=this._transitionable.transitioned(N,this._transitioning)}hasTransition(){return this._transitioning.hasTransition()}recalculate(N){this.properties=this._transitioning.possiblyEvaluate(N)}get(){return this._options.properties=this._transitionable.serialize(),this._options}set(N,E){this._options=N,this._transitionable.setTransitionOrValue(N.properties,E)}shadowsEnabled(){return!!this.properties&&this.properties.get("cast-shadows")===!0}}let _i;const Ni=()=>_i||(_i=new o.af({color:new o.ag(o.s.properties_light_ambient.color),"color-use-theme":new o.ag({type:"string",default:"default","property-type":"data-constant"}),intensity:new o.ag(o.s.properties_light_ambient.intensity)}));let vi;const qo=()=>vi||(vi=new o.af({direction:new o.ax(o.s.properties_light_directional.direction),color:new o.ag(o.s.properties_light_directional.color),"color-use-theme":new o.ag({type:"string",default:"default","property-type":"data-constant"}),intensity:new o.ag(o.s.properties_light_directional.intensity),"cast-shadows":new o.ag(o.s.properties_light_directional["cast-shadows"]),"shadow-quality":new o.ag(o.s.properties_light_directional["shadow-quality"]),"shadow-intensity":new o.ag(o.s.properties_light_directional["shadow-intensity"]),"shadow-draw-before-layer":new o.ag(o.s.properties_light_directional["shadow-draw-before-layer"])})),Ro=(L,N,E,z,W,Z,ne,de,ye,Ce=[0,0,1])=>({u_matrix:L,u_normal_matrix:N,u_opacity:E,u_faux_facade_ao_intensity:z,u_camera_pos:W,u_tile_to_meter:Z,u_facade_emissive_chance:ne,u_flood_light_color:de,u_flood_light_intensity:ye,u_front_cutoff_params:Ce}),Ti=L=>({u_matrix:L}),jo=L=>({u_matrix:L}),Xe=o.ay;async function Bt(){return Promise.resolve()}function As(L,N,E,z,W,Z,ne,de){E.resetLayerRenderingStats(L);const ye=L.context,Ce=ye.gl,Pe=L.transform,Ke=E.paint.get("fill-extrusion-pattern"),Ze=E.paint.get("fill-extrusion-pattern-cross-fade"),mt=Ke.constantOr(null),vt=Ke.constantOr(1),bt=E.paint.get("fill-extrusion-opacity"),St=L.style.enable3dLights(),Pt=E.paint.get(St&&!vt?"fill-extrusion-ambient-occlusion-wall-radius":"fill-extrusion-ambient-occlusion-radius"),Gt=[E.paint.get("fill-extrusion-ambient-occlusion-intensity"),Pt],as=E.layout.get("fill-extrusion-edge-radius"),ms=as>0&&!E.paint.get("fill-extrusion-rounded-roof"),Gs=ms?0:as,Ms=Pe.projection.name==="globe"?o.aD():0,Js=Pe.projection.name==="globe",Os=Js?o.S(Pe.zoom):0,Ks=[o.a7(Pe.center.lng),o.a8(Pe.center.lat)],_n=E.paint.get("fill-extrusion-flood-light-color-use-theme").constantOr("default")==="none",ln=E.paint.get("fill-extrusion-flood-light-color").toNonPremultipliedRenderColor(_n?null:E.lut).toArray01().slice(0,3),an=E.paint.get("fill-extrusion-flood-light-intensity"),bn=E.paint.get("fill-extrusion-vertical-scale"),Sn=E.paint.get("fill-extrusion-line-width").constantOr(1)!==0,lr=E.paint.get("fill-extrusion-height-alignment"),Mn=E.paint.get("fill-extrusion-base-alignment"),Hn=o.aE(L,E.paint.get("fill-extrusion-cutoff-fade-range")),Tr=E.paint.get("fill-extrusion-front-cutoff"),oa=cn(Pe.pitch,Tr,!!L.terrain),Qr=oa[2]<1;Qr&&(L.maxFrontCutoffRawStart=Math.max(L.maxFrontCutoffRawStart,Tr[0]));const Lr=[];let qa;Js&&Lr.push("PROJECTION_GLOBE_VIEW"),Gt[0]>0&&Lr.push("FAUX_AO"),ms&&Lr.push("ZERO_ROOF_RADIUS"),de&&Lr.push("HAS_CENTROID"),an>0&&Lr.push("FLOOD_LIGHT"),Hn.shouldRenderCutoff&&Lr.push("RENDER_CUTOFF"),Qr&&Lr.push("RENDER_FRONT_CUTOFF"),Sn&&Lr.push("RENDER_WALL_MODE");const Nr=L.renderPass==="shadow",cr=L.shadowRenderer,Fr=Nr&&!!cr,Fa=Nr?o.$.disabled:o.$.backCCW;L.shadowRenderer&&(L.shadowRenderer.useNormalOffset=!0);let ta=[0,0,0];if(cr){const uo=L.style.directionalLight,ao=L.style.ambientLight;uo&&ao&&(ta=o.aF(L.style,uo,ao)),Nr||(Lr.push("RENDER_SHADOWS"),cr.useNormalOffset&&Lr.push("NORMAL_OFFSET")),qa=Lr.concat(["SHADOWS_SINGLE_CASCADE"])}const Ta=Fr?"fillExtrusionDepth":vt?"fillExtrusionPattern":"fillExtrusion",ci=E.getLayerRenderingStats();for(const uo of z){const ao=N.getTile(uo),Io=ao.getBucket(E);if(!Io||Io.projection.name!==Pe.projection.name)continue;let qc=!1;cr&&(qc=cr.getMaxCascadeForTile(uo.toUnwrapped())===0);const Tc=L.isTileAffectedByFog(uo),Wo=Io.programConfigurations.get(E.id);let Va=!1;if(mt&&ao.imageAtlas){const gl=ao.imageAtlas,Hc=o.aG.from(mt),Fu=Hc.getPrimary().scaleSelf(o.e.devicePixelRatio).toString(),Yl=Hc.getSecondary(),zl=gl.patternPositions.get(Fu),Ud=Yl?gl.patternPositions.get(Yl.scaleSelf(o.e.devicePixelRatio).toString()):null;Va=!!zl&&!!Ud,zl&&Wo.setConstantPatternPositions(zl,Ud)}Ze>0&&(Va||Wo.getPatternTransitionVertexBuffer("fill-extrusion-pattern"))&&Lr.push("FILL_EXTRUSION_PATTERN_TRANSITION");const Vc=L.getOrCreateProgram(Ta,{config:Wo,defines:qc?qa:Lr,overrideFog:Tc});if(L.terrain&&L.terrain.setupElevationDraw(ao,Vc,{useMeterToDem:!0}),!Io.centroidVertexBuffer){const gl=Vc.getAttributeLocation(Ce,"a_centroid_pos");gl!==-1&&Ce.vertexAttribI4ui(gl,0,0,0,0)}!Nr&&cr&&cr.setupShadows(ao.tileID.toUnwrapped(),Vc,"vector-tile"),vt&&(L.context.activeTexture.set(Ce.TEXTURE0),ao.imageAtlasTexture&&ao.imageAtlasTexture.bind(Ce.LINEAR,Ce.CLAMP_TO_EDGE),Wo.updatePaintBuffers());const Ju=E.paint.get("fill-extrusion-vertical-gradient"),du=1/Io.tileToMeter;let bl;if(Nr&&cr){if(tn(ao.tileID,Io.maxHeight,L))continue;const gl=cr.calculateShadowPassMatrixFromTile(ao.tileID.toUnwrapped());bl=o.aM(gl,Gs,du,bn,lr,Mn)}else{const gl=L.translatePosMatrix(uo.expandedProjMatrix,ao,E.paint.get("fill-extrusion-translate"),E.paint.get("fill-extrusion-translate-anchor")),Hc=Pe.projection.createInversionMatrix(Pe,uo.canonical),Fu=Vc.fixedDefines.includes("LIGHTING_3D_MODE");bl=vt?o.aH(gl,L,Ju,bt,Gt,Gs,du,uo,ao,Ms,lr,Mn,Os,Ks,Hc,ln,bn,Ze,Fu):o.aI(gl,L,Ju,bt,Gt,Gs,du,uo,Ms,lr,Mn,Os,Ks,Hc,ln,bn,an,ta,oa,Fu)}L.uploadCommonUniforms(ye,Vc,uo.toUnwrapped(),null,Hn);let uu=Io.segments;if(Pe.projection.name==="mercator"&&!Nr&&(uu=Io.getVisibleSegments(ao.tileID,L.terrain,L.transform.getFrustum(0)),!uu.get().length))continue;if(ci)if(Nr)for(const gl of uu.get())ci.numRenderedVerticesInShadowPass+=gl.primitiveLength;else for(const gl of uu.get())ci.numRenderedVerticesInTransparentPass+=gl.primitiveLength;const dd=[];(L.terrain||de)&&dd.push(Io.centroidVertexBuffer),Js&&dd.push(Io.layoutVertexExtBuffer),Sn&&dd.push(Io.wallVertexBuffer),Vc.draw(L,ye.gl.TRIANGLES,W,Z,ne,Fa,bl,E.id,Io.layoutVertexBuffer,Io.indexBuffer,uu,E.paint,L.transform.zoom,Wo,dd)}L.shadowRenderer&&(L.shadowRenderer.useNormalOffset=!1)}class Hs{constructor(){this.translate=[0,0],this.translateAnchor="map",this.edgeRadius=0,this.cutoffFadeRange=0}}function cn(L,N,E){if(!(N[2]<1)||E)return[0,0,1];const z=180*L/Math.PI;if(z<15)return[-.5,N[1],N[2]];const W=Math.min(1,Math.max(0,(z-15)/5)),Z=W*W*(3-2*W);return[-.5*(1-Z)+N[0]*Z,N[1],N[2]]}function gr(L,N,E,z,W,Z,ne){z.centroidVertexArray.length===0&&z.createCentroidsBuffer();const de=Z?Z.findDEMTileFor(E):null;if(!(de&&de.dem||ne))return;Z&&de&&de.dem&&z.selfDEMTileTimestamp!==de.dem._timestamp&&(z.borderDoneWithNeighborZ=[-1,-1,-1,-1],z.selfDEMTileTimestamp=de.dem._timestamp);const ye=(Pt,Gt)=>{(Pt.flags|Gt.flags)&o.aJ?(Pt.flags|=o.aJ,Gt.flags|=o.aJ):(Pt.flags&=~o.aJ,Gt.flags&=~o.aJ)},Ce=Pt=>new o.P(Math.ceil((Pt+o.aK)*o.aL),0),Pe=(Pt,Gt,as)=>{const ms=Math.ceil((Pt+o.aK)*o.aL),Gs=Math.floor(Math.max(0,Math.min(o.a2-1,as))/4);return new o.P(ms,Gs<<5|(3&Gt)<<3|7)},Ke=Pt=>{const Gt=N.getSource().minzoom,as=Gs=>{const Ms=N.getTileByID(Gs);if(Ms&&Ms.hasData())return Ms.getBucket(W)},ms=[0,-1,1];for(const Gs of ms){if(Pt.overscaledZ+Gs(Ze[0]=Math.min(Pt.min.y,Gt.min.y),Ze[1]=Math.max(Pt.max.y,Gt.max.y),Ze[2]=o.a2-Gt.min.x>Pt.max.x?Gt.min.x-o.a2:Pt.max.x,Ze),vt=(Pt,Gt)=>(Ze[0]=Math.min(Pt.min.x,Gt.min.x),Ze[1]=Math.max(Pt.max.x,Gt.max.x),Ze[2]=o.a2-Gt.min.y>Pt.max.y?Gt.min.y-o.a2:Pt.max.y,Ze),bt=[(Pt,Gt)=>mt(Pt,Gt),(Pt,Gt)=>mt(Gt,Pt),(Pt,Gt)=>vt(Pt,Gt),(Pt,Gt)=>vt(Gt,Pt)],St=(Pt,Gt,as,ms,Gs,Ms,Js)=>{if(!Z)return 0;const Os=[[Ms?as:Pt,Ms?Pt:as,0],[Ms?as:Gt,Ms?Gt:as,0]],Ks=Js<0?o.a2+Js:Js,_n=[Ms?Ks:(Pt+Gt)/2,Ms?(Pt+Gt)/2:Ks,0];return as===0&&Js<0||as!==0&&Js>0?Z.getForTilePoints(Gs,[_n],!0,ms):Os.push(_n),Z.getForTilePoints(E,Os,!0,de),Math.max(Os[0][2],Os[1][2],_n[2])/Z.exaggeration()};for(let Pt=0;Pt<4;Pt++){const Gt=z.borderFeatureIndices[Pt];if(Gt.length===0)continue;const as=o.aB[Pt](E),ms=Ke(as);if(!(ms&&ms instanceof o.aC))continue;const Gs=Z?Z.findDEMTileFor(as):null;if(!(Gs&&Gs.dem||ne)||(Z&&Gs&&Gs.dem&&z.borderDEMTileTimestamp[Pt]!==Gs.dem._timestamp&&(z.borderDoneWithNeighborZ[Pt]=-1,z.borderDEMTileTimestamp[Pt]=Gs.dem._timestamp),z.borderDoneWithNeighborZ[Pt]===ms.canonical.z))continue;ms.centroidVertexArray.length===0&&ms.createCentroidsBuffer();const Ms=(Pt<2?1:5)-Pt,Js=ms.borderDoneWithNeighborZ[Ms]!==z.canonical.z,Os=ms.borderFeatureIndices[Ms];let Ks=0;if(z.canonical.z!==ms.canonical.z){for(const bn of Gt)z.showCentroid(z.featuresOnBorder[bn]);if(Js)for(const bn of Os)ms.showCentroid(ms.featuresOnBorder[bn]);z.borderDoneWithNeighborZ[Pt]=ms.canonical.z,ms.borderDoneWithNeighborZ[Ms]=z.canonical.z;continue}const _n=new Map,ln=new Set,an=new Set;for(let bn=0;bn1||Hn.intersectsCount()>1;{let Nr=0;if(Gs&&Gs.dem&&!qa){const cr=bt[Pt](lr,Tr),Fr=Pt%2?o.a2-1:0;Nr=St(cr[0],Math.min(o.a2-1,cr[1]),Fr,Gs,as,Pt<2,cr[2])}lr.centroidXY=Pe(Nr,Pt,Lr),Tr.centroidXY=Pe(Nr,Ms,Lr)}if(z.writeCentroidToBuffer(lr),ms.writeCentroidToBuffer(Tr),Sn.buildingId!==void 0){for(const Nr of z.centroidData)Nr.buildingId===Sn.buildingId&&Nr!==lr&&(Nr.centroidXY=lr.centroidXY,z.writeCentroidToBuffer(Nr));for(const Nr of ms.centroidData)Nr.buildingId===Sn.buildingId&&Nr!==Tr&&(Nr.centroidXY=Tr.centroidXY,ms.writeCentroidToBuffer(Nr))}}for(const bn of Gt){if(ln.has(bn))continue;const Sn=z.featuresOnBorder[bn],lr=z.centroidData.get(Sn.centroidDataIndex),Mn=Sn.borders[Pt];let Hn;for(;KsMn[0]+3||Tr[0]>Mn[0]-3)break;ms.showCentroid(Hn),Ks++}if(Hn&&KsMn[1]-3||(oa++,++Ks===Os.length))break;Hn=ms.featuresOnBorder[Os[Ks]]}for(;Tr=Os.length){z.showCentroid(Sn);continue}Hn=ms.featuresOnBorder[Os[Tr]];let Qr=!1;if(oa>=1){const Nr=Hn.borders[Ms];Math.abs(Mn[0]-Nr[0])<3&&Math.abs(Mn[1]-Nr[1])<3&&(oa=1,Qr=!0,Ks=Tr+1)}else if(oa===0){z.showCentroid(Sn);continue}const Lr=ms.centroidData.get(Hn.centroidDataIndex);ne&&Qr&&ye(lr,Lr);const qa=Sn.intersectsCount()>1||Hn.intersectsCount()>1;if(oa>1)Ks=Tr,lr.centroidXY=Lr.centroidXY=new o.P(0,0);else if(Gs&&Gs.dem&&!qa){const Nr=bt[Pt](lr,Lr),cr=Pt%2?o.a2-1:0,Fr=St(Nr[0],Math.min(o.a2-1,Nr[1]),cr,Gs,as,Pt<2,Nr[2]);lr.centroidXY=Lr.centroidXY=Ce(Fr)}else qa?lr.centroidXY=Lr.centroidXY=new o.P(0,0):(lr.centroidXY=z.encodeBorderCentroid(Sn),Lr.centroidXY=ms.encodeBorderCentroid(Hn));z.writeCentroidToBuffer(lr),ms.writeCentroidToBuffer(Lr)}else z.showCentroid(Sn)}z.borderDoneWithNeighborZ[Pt]=ms.canonical.z,ms.borderDoneWithNeighborZ[Ms]=z.canonical.z}(z.needsCentroidUpdate||!z.centroidVertexBuffer&&z.centroidVertexArray.length!==0)&&z.uploadCentroid(L)}const fr=[1,0,0],za=[0,1,0],Rt=[0,0,1];function tn(L,N,E){const z=E.transform,W=E.shadowRenderer;if(!W)return!0;const Z=E.frameCounter,ne=E.currentShadowCascade;let de=E._shadowCullCache;if(!de||de.frame!==Z||de.cascade!==ne){const Pt=z.tileSize*W._cascades[ne].scale,Gt=z.scaleZoom(Pt),as=W.shadowDirection,ms=[as[0],as[1],-as[2]],Gs=[fr,za,Rt,ms,[ms[0],0,ms[2]],[0,ms[1],ms[2]]];de={frame:Z,cascade:ne,cameraFrustum:o.az.fromInvProjectionMatrix(z.invProjMatrix,z.worldSize,Gt,z.projection.name!=="globe"),edges:Gs,shadowDir:ms,ws:Pt,zoom:Gt},E._shadowCullCache=de}const{cameraFrustum:ye,edges:Ce,shadowDir:Pe,ws:Ke,zoom:Ze}=de;let mt=N;if(z.elevation){const Pt=z.elevation.getMinMaxForTile(L);Pt&&(mt+=Pt.max)}mt/=o.aA(z.center.lat,Ze);const vt=W.computeSimplifiedTileShadowVolume(L.toUnwrapped(),mt,Ke,Pe);if(!vt)return!1;const{vertices:bt,planes:St}=vt;return ye.intersectsPrecise(bt,St,Ce)===0||W.getCurrentCascadeFrustum().intersectsPrecise(bt,St,Ce)===0}const yn=new Float32Array(16),xr=new Float32Array(16);function $r(L){const{painter:N,source:E,layer:z,coords:W}=L;let Z=L.defines;const ne=N.context,de=N.renderPass==="shadow",ye=N.renderPass==="light-beam",Ce=N.shadowRenderer,Pe=o.aA(N.transform.center.lat,N.transform.zoom),Ke=o.aE(N,z.paint.get("building-cutoff-fade-range"));Ke.shouldRenderCutoff&&(Z=Z.concat("RENDER_CUTOFF"));const Ze=z.paint.get("building-front-cutoff"),mt=Ze[2]<1&&!N.terrain,vt=cn(N.transform.pitch,Ze,!!N.terrain);mt&&(Z=Z.concat("RENDER_FRONT_CUTOFF"),N.maxFrontCutoffRawStart=Math.max(N.maxFrontCutoffRawStart,Ze[0])),L.floodLightIntensity>0&&(Z=Z.concat("FLOOD_LIGHT"));for(const bt of W){const St=E.getTile(bt),Pt=St.getBucket(z);if(!Pt)continue;Ce&&Ce.getMaxCascadeForTile(bt.toUnwrapped())===0&&(Z=Z.concat("SHADOWS_SINGLE_CASCADE"));const Gt=Pt.programConfigurations.get(z.id);let as,ms;const Gs=N.translatePosMatrix(bt.expandedProjMatrix,St,[0,0],"map");o.aN(yn,Gs,[1,1,L.verticalScale]);const Ms=yn;let Js;if(de&&Ce){if(tn(St.tileID,Pt.maxHeight*Pe,N))continue;const Ks=Ce.calculateShadowPassMatrixFromTile(St.tileID.toUnwrapped());o.aN(Ks,Ks,[1,1,L.verticalScale]),Js=jo(Ks),as=ms=N.getOrCreateProgram("buildingDepth",{config:Gt,defines:Z,overrideFog:!1})}else if(ye)as=ms=N.getOrCreateProgram("buildingBloom",{config:Gt,defines:Z,overrideFog:!1}),Js=Ti(Ms);else{const Ks=N.transform.calculatePosMatrix(bt.toUnwrapped(),N.transform.worldSize);o.aN(Ks,Ks,[1,1,L.verticalScale]),o.aN(xr,Ks,[1,-1,1/Pe]),o.aO(xr,xr),o.aP(xr,xr);const _n=xr,ln=N.transform.getFreeCameraOptions().position,an=1<{if(ye){const ln=Ks.entranceBloom;_n.draw(N,ne.gl.TRIANGLES,L.depthMode,o._.disabled,L.blendMode,o.$.disabled,Js,z.id,ln.layoutVertexBuffer,ln.indexBuffer,ln.segmentsBucket,z.paint,N.transform.zoom,Gt,[ln.layoutAttenuationBuffer,ln.layoutColorBuffer])}else{const ln=Ks.segmentsBucket;let an=[Ks.layoutNormalBuffer,Ks.layoutCentroidBuffer,Ks.layoutColorBuffer,Ks.layoutFloodLightDataBuffer];Ks.layoutFacadePaintBuffer&&(an=an.concat([Ks.layoutFacadeDataBuffer,Ks.layoutFacadeVerticalRangeBuffer,Ks.layoutFacadePaintBuffer])),_n.draw(N,ne.gl.TRIANGLES,L.depthMode,o._.disabled,L.blendMode,de?o.$.disabled:o.$.backCW,Js,z.id,Ks.layoutVertexBuffer,Ks.indexBuffer,ln,z.paint,N.transform.zoom,Gt,an)}};N.uploadCommonUniforms(ne,ms,bt.toUnwrapped(),null,Ke),Pt.buildingWithoutFacade&&Os(Pt.buildingWithoutFacade,ms),Pt.buildingWithFacade&&(as!==ms&&N.uploadCommonUniforms(ne,as,bt.toUnwrapped(),null,Ke),Os(Pt.buildingWithFacade,as))}}function Ca(L,N,E,z,W,Z,ne,de,ye,Ce,Pe,Ke,Ze,mt){const vt=L.context.gl,bt=L.depthModeForSublayer(1,o.Z.ReadOnly,vt.LEQUAL,!0),St=o.al(.1,3,Pe),Pt=L._showOverdrawInspector,Gt=Ke,as=new Hs;if(!Pt){const ms=new o._({func:vt.ALWAYS,mask:255},255,255,vt.KEEP,vt.KEEP,vt.REPLACE),Gs=new o.a1([vt.ONE,vt.ONE,vt.ONE,vt.ONE],o.C.transparent,[!1,!1,!1,!0],vt.MIN);o.aQ(as,L,N,E,z,bt,ms,Gs,o.$.disabled,W,"sdf",Z,ne,de,ye,Ce,St,Gt,!1,void 0)}{const ms=Pt?o._.disabled:new o._({func:vt.EQUAL,mask:255},255,255,vt.KEEP,vt.DECR,vt.DECR),Gs=Pt?L.colorModeForRenderPass():new o.a1([vt.ONE_MINUS_DST_ALPHA,vt.DST_ALPHA,vt.ONE,vt.ONE],o.C.transparent,[!0,!0,!0,!0]);o.aQ(as,L,N,E,z,bt,ms,Gs,o.$.disabled,W,"color",Z,ne,de,ye,Ce,St,Gt,!1,void 0)}}class xa{constructor(){this._previousClosestBuildingId=null,this._hysteresisRatio=.8,this._indoorMinimumZoom=16}findClosestBuilding(N,E,z,W,Z){if(zye*this._hysteresisRatio&&(ne=this._previousClosestBuildingId):Ce&&!ne&&(ne=this._previousClosestBuildingId),this._previousClosestBuildingId=ne,ne}_calculateDistance(N,E){if(!E.center)return Number.MAX_VALUE;const z=N.lat-E.center[1],W=N.lng-E.center[0];return z*z+W*W}_isBuildingVisible(N,E,z){if(!z)return!1;for(const W of N.floorIds){const Z=N.floors[W];if(!Z.geometry)continue;const ne=Z.geometry;if(ne.type==="Polygon"){const de=this._convertRingToPoints(ne.coordinates[0]);if(o.aT(de,z))return!0}else if(ne.type==="MultiPolygon"){const de=this._convertMultiPolygonToPoints(ne.coordinates);if(o.aU(z,de))return!0}}return!1}_convertRingToPoints(N){return N.map(E=>new o.P(E[0],E[1]))}_convertMultiPolygonToPoints(N){return N.map(E=>E.length===0?[]:E[0].map(z=>new o.P(z[0],z[1])))}}const Oa=.05,jl=(L,N,E,z,W,Z,ne,de,ye,Ce,Pe,Ke)=>({u_matrix:L,u_normalize_matrix:N,u_globe_matrix:E,u_merc_matrix:z,u_grid_matrix:W,u_tl_parent:Z,u_scale_parent:Ce,u_fade_t:Pe.mix,u_opacity:Pe.opacity,u_image0:0,u_image1:1,u_raster_elevation:Ke,u_zoom_transition:ne,u_merc_center:de,u_cutoff_params:ye}),Ri=(L,N,E,z,W,Z,ne,de,ye,Ce)=>({u_particle_texture:L,u_particle_texture_side_len:N,u_tile_offset:E,u_velocity:z,u_color_ramp:Z,u_velocity_res:W,u_max_speed:ne,u_uv_offset:de,u_data_scale:[255*ye[0],255*ye[1]],u_data_offset:Ce,u_particle_pos_scale:1.1,u_particle_pos_offset:[Oa,Oa]}),Ki=(L,N,E,z,W,Z,ne,de,ye,Ce)=>({u_particle_texture:L,u_particle_texture_side_len:N,u_velocity:E,u_velocity_res:z,u_max_speed:W,u_speed_factor:Z,u_reset_rate:ne,u_rand_seed:Math.random(),u_uv_offset:de,u_data_scale:[255*ye[0],255*ye[1]],u_data_offset:Ce,u_particle_pos_scale:1.1,u_particle_pos_offset:[Oa,Oa]});function Rc(L,[N,E,z,W],[Z,ne]){if(Z===ne)return[0,0,0,0];const de=255*(L-1)/(L*(ne-Z));return[N*de,E*de,z*de,W*de]}function xd(L,N,[E,z]){return E===z?0:.5/L+(N-E)*(L-1)/(L*(z-E))}var ro=o.a_([{name:"a_index",type:"Int16",components:1}]);class pc{constructor(N,E,z,W){const Z={width:z[0],height:z[1],data:null},ne=N.gl;this.targetColorTexture=new o.T(N,Z,ne.RGBA8,{useMipmap:!1}),this.backgroundColorTexture=new o.T(N,Z,ne.RGBA8,{useMipmap:!1}),this.context=N,this.updateParticleTexture(E,W),this.lastInvalidatedAt=0}updateParticleTexture(N,E){if(this.particleTextureDimension===E.width)return;(this.particleTexture0||this.particleTexture1||this.particleIndexBuffer||this.particleSegment)&&(this.particleTexture0.destroy(),this.particleTexture1.destroy(),this.particleIndexBuffer.destroy(),this.particleSegment.destroy());const z=this.context.gl,W=E.width*E.height;this.particleTexture0=new o.T(this.context,E,z.RGBA8,{premultiply:!1,useMipmap:!1}),this.particleTexture1=new o.T(this.context,E,z.RGBA8,{premultiply:!1,useMipmap:!1});const Z=new o.a$;Z.reserve(W);for(let ne=0;ne0){const Z=o.e.now(),ne=(Z-L.timeAdded)/W,de=N?(Z-N.timeAdded)/W:-1,ye=E.getSource(),Ce=z.coveringZoomLevel({tileSize:ye.tileSize,roundZoom:ye.roundZoom}),Pe=!N||Math.abs(N.tileID.overscaledZ-Ce)>Math.abs(L.tileID.overscaledZ-Ce),Ke=Pe&&L.refreshedUponExpiration?1:o.b0(Pe?ne:1-de,0,1);return N?{opacity:1,mix:1-Ke,isFading:ne<1}:{opacity:Ke,mix:0,isFading:ne<1}}return{opacity:1,mix:0,isFading:!1}}function Nh(L,N,E){if(!L)return null;const z=N.getTextureDescriptor(L,E,!0);if(!z)return null;let{texture:W,mix:Z,offset:ne,tileSize:de,buffer:ye,format:Ce}=z;if(!W||!Ce)return null;let Pe=!1;return Ce==="uint32"&&(Pe=!0,Z[3]=0,Z=Rc(o.b9,Z,[0,E.paint.get("raster-particle-max-speed")]),ne=xd(o.b9,ne,[0,E.paint.get("raster-particle-max-speed")])),{texture:W,textureOffset:[ye/(de+2*ye),de/(de+2*ye)],tileSize:de,scalarData:Pe,scale:Z,offset:ne,defines:["RASTER_ARRAY",{uint8:"DATA_FORMAT_UINT8",uint16:"DATA_FORMAT_UINT16",uint32:"DATA_FORMAT_UINT32"}[Ce]]}}function xu(L){const N=L._nearZ,E=L.projection.farthestPixelDistance(L),z=E-N,W=.2*L.height,Z=N+W;return[N,E,(Z-W-N)/z,(Z-N)/z]}var Dd=`#ifdef RASTER_ARRAY uniform sampler2D u_velocity;uniform mediump vec2 u_velocity_res;uniform mediump float u_max_speed;const vec4 NO_DATA=vec4(1);const vec2 INVALID_VELOCITY=vec2(-1);uniform highp vec2 u_uv_offset;uniform highp float u_data_offset;uniform highp vec2 u_data_scale;ivec4 rasterArrayLinearCoord(highp vec2 texCoord,highp vec2 texResolution,out highp vec2 fxy) {texCoord=texCoord*texResolution-0.5;fxy=fract(texCoord);texCoord-=fxy;return ivec4(texCoord.xxyy+vec2(1.5,0.5).xyxy);}highp vec2 lookup_velocity(highp vec2 uv) {uv=u_uv_offset.x+u_uv_offset.y*uv;highp vec2 fxy;ivec4 c=rasterArrayLinearCoord(uv,u_velocity_res,fxy);highp vec4 tl=texelFetch(u_velocity,c.yz,0);highp vec4 tr=texelFetch(u_velocity,c.xz,0);highp vec4 bl=texelFetch(u_velocity,c.yw,0);highp vec4 br=texelFetch(u_velocity,c.xw,0);if (tl==NO_DATA) {return INVALID_VELOCITY;}if (tr==NO_DATA) {return INVALID_VELOCITY;}if (bl==NO_DATA) {return INVALID_VELOCITY;}if (br==NO_DATA) {return INVALID_VELOCITY;}highp vec4 t=mix(mix(bl,br,fxy.x),mix(tl,tr,fxy.x),fxy.y);highp vec2 velocity=u_data_offset+vec2(dot(t.rg,u_data_scale),dot(t.ba,u_data_scale));velocity.y=-velocity.y;velocity/=max(u_max_speed,length(velocity));return velocity;} #endif uniform highp float u_particle_pos_scale;uniform highp vec2 u_particle_pos_offset;highp vec4 pack_pos_to_rgba(highp vec2 p) {highp vec2 v=(p+u_particle_pos_offset)/u_particle_pos_scale;highp vec4 r=vec4(v.x,fract(v.x*255.0),v.y,fract(v.y*255.0));return vec4(r.x-r.y/255.0,r.y,r.z-r.w/255.0,r.w);}highp vec2 unpack_pos_from_rgba(highp vec4 v) {v=floor(v*255.0+0.5)/255.0;highp vec2 p=vec2(v.x+(v.y/255.0),v.z+(v.w/255.0));return u_particle_pos_scale*p-u_particle_pos_offset;}`;o.ba["_prelude_raster_particle.glsl"]||(o.ba["_prelude_raster_particle.glsl"]=Dd);var td={building:o.bb(`#include "_prelude_fog.fragment.glsl" #include "_prelude_shadow.fragment.glsl" #include "_prelude_lighting.glsl" #include "_prelude_indicator_cutout.fragment.glsl" #include "_prelude_feature_cutout.fragment.glsl" const float window_depth=0.5;const float ao_radius=0.2;in vec4 v_color;in highp vec3 v_normal;in highp vec3 v_pos; #ifdef RENDER_FRONT_CUTOFF in float v_front_cutoff_opacity; #endif #ifdef INDICATOR_CUTOUT #ifdef FEATURE_CUTOUT in vec4 v_ground_roof; #endif #endif #ifdef BUILDING_FAUX_FACADE in lowp float v_faux_facade;in highp float v_faux_facade_ed;in highp vec2 v_faux_facade_window;in highp vec2 v_faux_facade_floor;in highp vec2 v_faux_facade_range;in highp float v_aspect;in highp vec3 v_tbn_0;in highp vec3 v_tbn_1;in highp vec3 v_tbn_2;in highp vec4 v_faux_color_emissive;uniform float u_faux_facade_ao_intensity; #endif #ifdef RENDER_SHADOWS in highp vec4 v_pos_light_view_0;in highp vec4 v_pos_light_view_1; #endif #ifdef FLOOD_LIGHT in highp float v_flood_radius;in float v_has_flood_light; #endif uniform lowp float u_opacity;uniform vec3 u_camera_pos;uniform highp float u_tile_to_meter;uniform float u_facade_emissive_chance;uniform vec3 u_flood_light_color;uniform float u_flood_light_intensity;vec3 linearTosRGB(in vec3 color) {return pow(color,vec3(1./2.2));} #ifdef BUILDING_FAUX_FACADE highp float hash12(in highp vec2 p) {highp vec3 p3 =fract(vec3(p.xyx)*0.1031);p3+=dot(p3,p3.yzx+33.33);return fract((p3.x+p3.y)*p3.z);}float min3(in vec3 v) {return min(min(v.x,v.y),v.z);}highp vec2 get_uv_mask_id(in highp vec2 q,out highp float mask,out highp vec2 id) {highp vec2 p=q;mask=step(v_faux_facade_range.x,p.y)*step(p.y,v_faux_facade_range.y);p.y=p.y-v_faux_facade_range.x;highp vec2 uv=modf(p/v_faux_facade_floor,id);highp vec4 d=(v_faux_facade_floor.xyxy+vec4(-v_faux_facade_window,v_faux_facade_window))*0.5;highp vec4 edge=d/v_faux_facade_floor.xyxy;highp vec2 m=step(edge.xy,uv)*step(uv,edge.zw);mask*=m.x*m.y;uv-=vec2(0.5);uv*=vec2(0.5)/(vec2(0.5)-edge.xy);uv+=vec2(0.5);return uv;}highp float ray_unit_box(in highp vec3 ray_o,in highp vec3 ray_d,in highp vec3 bmin,in highp vec3 bmax) {highp vec3 planes=mix(bmin,bmax,step(0.0,ray_d));highp vec3 t=(planes-ray_o)/ray_d;return min3(t);}float get_emissive(in vec2 id) {if (u_facade_emissive_chance > 0.0) {return (step(hash12(id),u_facade_emissive_chance)+0.05)*v_faux_color_emissive.a;}return 0.0;}vec3 get_shade_info(in highp vec3 v,in highp vec3 v_normalized,in vec3 color,in vec2 id,in mat3 tbn,inout vec3 out_normal,inout float out_emissive) {vec3 out_color=color;highp vec3 abs_v=abs(v_normalized);bool x_major=abs_v.x >=abs_v.y && abs_v.x >=abs_v.z;bool y_major=abs_v.y >=abs_v.x && abs_v.y >=abs_v.z;bool z_major=abs_v.z >=abs_v.x && abs_v.z >=abs_v.y; #if 0 if (x_major) {out_color=v.x > 0.0 ? vec3(1.0,0.0,0.0) : vec3(0.0,1.0,1.0);} else if (y_major) {out_color=v.y > 0.0 ? vec3(0.0,1.0,0.0) : vec3(1.0,0.0,1.0);} else if (z_major) {out_color=v.z > 0.0 ? vec3(0.0,0.0,1.0) : vec3(1.0,1.0,0.0);}out_emissive=1.0; #else if (x_major) {out_normal=-sign(v.x)*tbn[0];} else if (y_major) {out_normal=vec3(0.0,0.0,-sign(v.y));} else if (z_major) {out_color=v_faux_color_emissive.rgb;out_emissive=v.z <=0.0 ? get_emissive(id) : out_emissive;}float ao=1.0;if (u_faux_facade_ao_intensity > 0.0) {vec4 ao_range=v_faux_facade_window.xxyy*0.5-vec4(0,ao_radius,0,ao_radius);vec2 ao_range_z=vec2(window_depth*0.5)-vec2(0.0,ao_radius);if (x_major || y_major) {ao*=smoothstep(-ao_range_z.x,-ao_range_z.y,v.z);} else if (z_major) {ao*=smoothstep(-ao_range.x,-ao_range.y,v.x)*(1.0-smoothstep(ao_range.y,ao_range.x,v.x));ao*=smoothstep(-ao_range.z,-ao_range.w,v.y)*(1.0-smoothstep(ao_range.w,ao_range.z,v.y));}ao=mix(1.0,min(1.0,ao+0.25),u_faux_facade_ao_intensity);}out_color*=ao; #endif return out_color;} #endif vec3 apply_lighting_linear(in vec3 color,in vec3 normal,in float dir_factor) {float ambient_directional_factor=calculate_ambient_directional_factor(normal);vec3 ambient_contrib=ambient_directional_factor*u_lighting_ambient_color;vec3 directional_contrib=u_lighting_directional_color*dir_factor;return color*(ambient_contrib+directional_contrib);}void main() {vec3 normal=normalize(v_normal);vec3 base_color=v_color.rgb;float emissive=v_color.a; #ifdef BUILDING_FAUX_FACADE if (v_faux_facade > 0.0) {highp mat3 tbn=mat3(v_tbn_0,v_tbn_1,v_tbn_2);highp vec3 v=vec3(v_pos.xy,v_pos.z/u_tile_to_meter)-u_camera_pos;highp vec3 view_tangent=transpose(tbn)*v;highp vec2 q=vec2(v_faux_facade_ed,v_pos.z);float mask=0.0;vec2 id=vec2(0.0);highp vec2 uv=get_uv_mask_id(q,mask,id);uv*=v_faux_facade_window;highp vec3 bmin=vec3(0.0,0.0,-window_depth);highp vec3 bmax=bmin+vec3(v_faux_facade_window,window_depth);highp vec3 ray_o=vec3(uv,0.0);highp vec3 ray_d=normalize(view_tangent);highp float t_min=ray_unit_box(ray_o,ray_d,bmin,bmax);highp vec3 hit=ray_o+t_min*ray_d;highp vec3 r=vec3(v_faux_facade_window,-window_depth);hit-=r*0.5;highp vec3 normalized=hit/r;vec3 out_normal=normal;float out_emissive=emissive;vec3 room_color=get_shade_info(hit,normalized,base_color,id,tbn,out_normal,out_emissive);base_color=mix(base_color,room_color,mask);normal=mix(normal,out_normal,mask);emissive=mix(emissive,out_emissive,mask);} #endif vec4 color=vec4(base_color,1.0);vec3 xy_flipped_normal=vec3(-normal.xy,normal.z);float shadowed_lighting_factor=0.0; #ifdef RENDER_SHADOWS #ifdef RENDER_CUTOFF shadowed_lighting_factor=shadowed_light_factor_normal_opacity(xy_flipped_normal,v_pos_light_view_0,v_pos_light_view_1,1.0/gl_FragCoord.w,v_cutoff_opacity);if (v_cutoff_opacity==0.0) {discard;} #else shadowed_lighting_factor=shadowed_light_factor_normal(xy_flipped_normal,v_pos_light_view_0,v_pos_light_view_1,1.0/gl_FragCoord.w); #endif #else shadowed_lighting_factor=max(0.0,dot(xy_flipped_normal,u_lighting_directional_dir)); #endif color.rgb=apply_lighting_linear(color.rgb,xy_flipped_normal,shadowed_lighting_factor);color.rgb=linearTosRGB(color.rgb); #ifdef FLOOD_LIGHT float flood_radiance=(1.0-min(v_pos.z/v_flood_radius,1.0))*u_flood_light_intensity*v_has_flood_light;color.rgb=mix(color.rgb,u_flood_light_color,flood_radiance); #endif color.rgb=mix(color.rgb,linearTosRGB(base_color.rgb),emissive); #ifdef FOG color=fog_dither(fog_apply_premultiplied(color,v_fog_pos,v_pos.z)); #endif color*=u_opacity; #ifdef INDICATOR_CUTOUT #ifdef FEATURE_CUTOUT {float ditherOpacity=cutoutGroundRoofOpacity(v_ground_roof);if (ditherOpacity < 1.0) {int index=viewport_dither_index(gl_FragCoord.xy);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=viewport_dither_index(gl_FragCoord.xy);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,0.0); #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:o.bb(`in vec4 v_color_emissive; #pragma mapbox: define-attribute highp vec4 bloom_attenuation float saturate(float val) {return clamp(val,0.0,1.0);}void main() { #pragma mapbox: initialize-attribute highp vec4 bloom_attenuation 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:o.bb("void main() {}","in vec3 a_pos_3f;uniform mat4 u_matrix;void main() {gl_Position=u_matrix*vec4(a_pos_3f,1.0);}"),rasterParticle:o.bb(`#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; #ifdef VIEWPORT_ORIGIN_TOP_LEFT v_pos0.y=1.0-v_pos0.y; #endif v_pos1=(v_pos0*u_scale_parent)+u_tl_parent;}`),rasterParticleDraw:o.bb("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:o.bb("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; #ifdef VIEWPORT_ORIGIN_TOP_LEFT v_tex_pos.y=1.0-v_tex_pos.y; #endif gl_Position=vec4(a_pos,0.0,1.0);}`),rasterParticleUpdate:o.bb(`#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:o.bb("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:o.bb("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:o.bb("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);}"),elevatedStructuresDepth:o.bb("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;}"),elevatedStructures:o.bb(`#include "_prelude_fog.fragment.glsl" #include "_prelude_lighting.glsl" #include "_prelude_shadow.fragment.glsl" #include "_prelude_indicator_cutout.fragment.glsl" #include "_prelude_feature_cutout.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;uniform float u_opacity_multiplier; #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,v_height); #endif out_color*=u_opacity_multiplier;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 }`),elevatedStructuresDepthReconstruct:o.bb(`#include "_prelude_feature_cutout.fragment.glsl" #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,0.0); #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;}`)};o.bb(Dd,"");const Uh=o.a_([{type:"Float32",name:"a_pos_3f",components:3},{type:"Float32",name:"a_uv",components:2},{type:"Float32",name:"a_rainParticleData",components:4}]),Nl=o.a_([{type:"Float32",name:"a_pos_2f",components:2}]);class ld{destroy(){this.vignetteVx&&this.vignetteVx.destroy(),this.vignetteIdx&&this.vignetteIdx.destroy()}draw(N,E){const z=N.getOrCreateProgram("vignette");if(!this.vignetteVx||!this.vignetteIdx){const ne=new o.bc,de=new o.ad;ne.emplaceBack(-1,-1),ne.emplaceBack(1,-1),ne.emplaceBack(1,1),ne.emplaceBack(-1,1),de.emplaceBack(0,1,2),de.emplaceBack(0,2,3),this.vignetteVx=N.context.createVertexBuffer(ne,Nl.members),this.vignetteIdx=N.context.createIndexBuffer(de)}const W=o.ac.simpleSegment(0,0,4,6);if(this.vignetteVx&&this.vignetteIdx){N.uploadCommonUniforms(N.context,z);const ne={u_vignetteShape:(Z={vignetteShape:[E.start,E.range,Math.pow(10,E.fadePower)],vignetteColor:[E.color.r,E.color.g,E.color.b,E.color.a*E.strength]}).vignetteShape,u_vignetteColor:Z.vignetteColor};z.draw(N,N.context.gl.TRIANGLES,o.Z.disabled,o._.disabled,o.a1.alphaBlended,o.$.disabled,ne,"vignette",this.vignetteVx,this.vignetteIdx,W)}var Z}}class cd{constructor(){this._accumulatedOffsetX=0,this._accumulatedOffsetY=0,this._accumulatedElevation=0}update(N,E){const z=N.getFreeCameraOptions().position,W=z.toAltitude(),Z=z.toLngLat(),ne=o.au(Z.lng),de=o.au(Z.lat),ye=N.pixelsPerMeter/E,Ce=ne*o.bj,Pe=o.bj*Math.log(Math.tan(Math.PI/4+de/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 Ke=-this._offsetYPrev+Pe,Ze=-this._elevationPrev+W;this._accumulatedOffsetX+=(-this._offsetXPrev+Ce)*ye,this._accumulatedOffsetY+=Ke*ye,this._accumulatedElevation+=Ze*ye,this._offsetXPrev=Ce,this._offsetYPrev=Pe,this._elevationPrev=W}}getPosition(){return[this._accumulatedOffsetX,this._accumulatedOffsetY,this._accumulatedElevation]}}function yd(L,N){return[-(L[0]-Math.floor(L[0]/N)*N),-(L[1]-Math.floor(L[1]/N)*N),-(L[2]-Math.floor(L[2]/N)*N)]}function Wu(L){const N=o.bi(1323123451230),E=[];for(let z=0;z({u_matrix:L,u_depth_bias:N}),lu=(L,N)=>({u_matrix:L,u_ground_shadow_factor:N,u_opacity_multiplier:1}),rc=(L,N,E,z,W)=>({u_matrix:L,u_camera_pos:[N[0],N[1],N[2]],u_depth_bias:E,u_height_scale:z,u_reset_depth:W}),Ku={building:L=>({u_matrix:new o.a5(L),u_normal_matrix:new o.a5(L),u_opacity:new o.a4(L),u_faux_facade_ao_intensity:new o.a4(L),u_camera_pos:new o.a6(L),u_tile_to_meter:new o.a4(L),u_facade_emissive_chance:new o.a4(L),u_flood_light_color:new o.a6(L),u_flood_light_intensity:new o.a4(L),u_front_cutoff_params:new o.a6(L)}),buildingBloom:L=>({u_matrix:new o.a5(L)}),buildingDepth:L=>({u_matrix:new o.a5(L)}),elevatedStructuresDepth:L=>({u_matrix:new o.a5(L),u_depth_bias:new o.a4(L)}),elevatedStructures:L=>({u_matrix:new o.a5(L),u_ground_shadow_factor:new o.a6(L),u_opacity_multiplier:new o.a4(L)}),elevatedStructuresDepthReconstruct:L=>({u_matrix:new o.a5(L),u_camera_pos:new o.a6(L),u_depth_bias:new o.a4(L),u_height_scale:new o.a4(L),u_reset_depth:new o.a4(L)}),rasterParticle:L=>({u_matrix:new o.a5(L),u_normalize_matrix:new o.a5(L),u_globe_matrix:new o.a5(L),u_merc_matrix:new o.a5(L),u_grid_matrix:new o.aZ(L),u_tl_parent:new o.a3(L),u_scale_parent:new o.a4(L),u_fade_t:new o.a4(L),u_opacity:new o.a4(L),u_image0:new o.aX(L),u_image1:new o.aX(L),u_raster_elevation:new o.a4(L),u_zoom_transition:new o.a4(L),u_merc_center:new o.a3(L),u_cutoff_params:new o.aY(L)}),rasterParticleTexture:L=>({u_texture:new o.aX(L),u_opacity:new o.a4(L)}),rasterParticleDraw:L=>({u_particle_texture:new o.aX(L),u_particle_texture_side_len:new o.a4(L),u_tile_offset:new o.a3(L),u_velocity:new o.aX(L),u_color_ramp:new o.aX(L),u_velocity_res:new o.a3(L),u_max_speed:new o.a4(L),u_uv_offset:new o.a3(L),u_data_scale:new o.a3(L),u_data_offset:new o.a4(L),u_particle_pos_scale:new o.a4(L),u_particle_pos_offset:new o.a3(L)}),rasterParticleUpdate:L=>({u_particle_texture:new o.aX(L),u_particle_texture_side_len:new o.a4(L),u_velocity:new o.aX(L),u_velocity_res:new o.a3(L),u_max_speed:new o.a4(L),u_speed_factor:new o.a4(L),u_reset_rate:new o.a4(L),u_rand_seed:new o.a4(L),u_uv_offset:new o.a3(L),u_data_scale:new o.a3(L),u_data_offset:new o.a4(L),u_particle_pos_scale:new o.a4(L),u_particle_pos_offset:new o.a3(L)}),snowParticle:L=>({u_modelview:new o.a5(L),u_projection:new o.a5(L),u_time:new o.a4(L),u_cam_pos:new o.a6(L),u_velocityConeAperture:new o.a4(L),u_velocity:new o.a4(L),u_horizontalOscillationRadius:new o.a4(L),u_horizontalOscillationRate:new o.a4(L),u_boxSize:new o.a4(L),u_billboardSize:new o.a4(L),u_simpleShapeParameters:new o.a3(L),u_screenSize:new o.a3(L),u_thinningCenterPos:new o.a3(L),u_thinningShape:new o.a6(L),u_thinningAffectedRatio:new o.a4(L),u_thinningParticleOffset:new o.a4(L),u_particleColor:new o.aY(L),u_direction:new o.a6(L)}),rainParticle:L=>({u_modelview:new o.a5(L),u_projection:new o.a5(L),u_time:new o.a4(L),u_cam_pos:new o.a6(L),u_texScreen:new o.aX(L),u_velocityConeAperture:new o.a4(L),u_velocity:new o.a4(L),u_boxSize:new o.a4(L),u_rainDropletSize:new o.a3(L),u_distortionStrength:new o.a4(L),u_rainDirection:new o.a6(L),u_color:new o.aY(L),u_screenSize:new o.a3(L),u_thinningCenterPos:new o.a3(L),u_thinningShape:new o.a6(L),u_thinningAffectedRatio:new o.a4(L),u_thinningParticleOffset:new o.a4(L),u_shapeDirectionalPower:new o.a4(L),u_shapeNormalPower:new o.a4(L),u_mode:new o.a4(L)}),vignette:L=>({u_vignetteShape:new o.a6(L),u_vignetteColor:new o.aY(L)})};function gc(L,N){const E=1<0;--E){const z=Math.floor(N.x/(1<0;--Ke){const Ze=Math.floor(N.x/(1<de[Gt]!=bt>de[Gt]&&ne[Gt]z&&(St|=2),mtW&&(St|=8),vtz&&(Pt|=2),btW&&(Pt|=8),!(St&Pt)&&(St===0||Pt===0||Pu(Ze,mt,vt,bt,N,E,z,W)))return!1}}for(let ye=0;ye<4;++ye)if(!(1&Z[ye]))return!1;return!0}function Pu(L,N,E,z,W,Z,ne,de){const ye=(Ce,Pe,Ke,Ze,mt,vt,bt,St)=>{const Pt=(Ke-Ce)*(vt-Pe)-(Ze-Pe)*(mt-Ce),Gt=(Ke-Ce)*(St-Pe)-(Ze-Pe)*(bt-Ce);if(Pt>0&&Gt>0||Pt<0&&Gt<0)return!1;const as=(bt-mt)*(Pe-vt)-(St-vt)*(Ce-mt),ms=(bt-mt)*(Ze-vt)-(St-vt)*(Ke-mt);return!(as>0&&ms>0||as<0&&ms<0)};return!!(ye(L,N,E,z,W,Z,ne,Z)||ye(L,N,E,z,ne,Z,ne,de)||ye(L,N,E,z,W,de,ne,de)||ye(L,N,E,z,W,Z,W,de))}class up{constructor(){this._tileCoverages=[],this._snapshot=new sd}clear(){this._tileCoverages=[]}addTileCoverage(N,E){this._tileCoverages.push({tileId:N,polygons:E,frcMask:kl(E)})}empty(){return this._tileCoverages.length===0}updateSnapshotIfNeeded(){if(this._snapshot.equals(this._tileCoverages))return this._snapshot;const N=this._tileCoverages.map(E=>({tileId:E.tileId,polygons:E.polygons,frcMask:E.frcMask}));return this._snapshot=new sd(N),this._snapshot}}function Km(L,N){const E={};if(!N)return E;for(const z of L){const W=z.layerIds.map(Z=>N.getLayer(Z)).filter(Boolean);if(W.length!==0){z.layers=W,z.stateDependentLayerIds&&(z.stateDependentLayers=z.stateDependentLayerIds.map(Z=>W.filter(ne=>ne.id===Z)[0])),z.updateExpressions&&z.updateExpressions(W);for(const Z of W)E[Z.fqid]=z}}return E}const vu=32,Fl=33,Mf=new Uint16Array(8184);for(let L=0;L<2046;L++){let N=L+2,E=0,z=0,W=0,Z=0,ne=0,de=0;for(1&N?W=Z=ne=vu:E=z=de=vu;(N>>=1)>1;){const Ce=E+W>>1,Pe=z+Z>>1;1&N?(W=E,Z=z,E=ne,z=de):(E=W,z=Z,W=ne,Z=de),ne=Ce,de=Pe}const ye=4*L;Mf[ye+0]=E,Mf[ye+1]=z,Mf[ye+2]=W,Mf[ye+3]=Z}const Fd=new Uint16Array(2178),Gl=new Uint8Array(1089),km=new Uint16Array(1089);function Sm(L){return L===0?-.03125:L===32?.03125:0}var Ig=o.a_([{name:"a_pos",type:"Int16",components:2},{name:"a_texture_pos",type:"Uint16",components:2}]);const da={type:2,extent:o.a2,loadGeometry:()=>[[new o.P(0,0),new o.P(o.a2+1,0),new o.P(o.a2+1,o.a2+1),new o.P(0,o.a2+1),new o.P(0,0)]]};let Ec,Mi=0;class Ym{constructor(N,E,z,W,Z,ne){this.tileID=N,this.uid=o.av(),this.uses=0,this.tileSize=E,this.tileZoom=z,this.dashIdealZ=N.overscaledZ,this.buckets={},this.expirationTime=null,this.queryPadding=0,this.hasSymbolBuckets=!1,this.hasTunnelGeometry=!1,this.hasRTLText=!1,this.dependencies={},this.isRaster=Z,W&&W.style&&(this._lastUpdatedBrightness=W.style.getBrightness()),this._lastAvailableImagesCount=0,this._firstPrepareComplete=!1,this.expiredRequestCount=0,this.state="loading",W&&W.transform&&(this.projection=W.transform.projection),this.worldview=ne,this._hasAppearances=null}registerFadeDuration(N){const E=N+this.timeAdded;E0&&(this.frcCoveragePolygons=N.frcCoveragePolygons),this.hasDeferredRoadStructure=!!N.hasDeferredRoadStructure,N.parsedElevationFeatures!==void 0&&(this.parsedElevationFeatures=N.parsedElevationFeatures,this.parsedElevationGeneration=++Mi),this.hasDeferredElevationFeatures=!!N.hasDeferredElevationFeatures,this.hasSymbolBuckets=!1,this.hasTunnelGeometry=!!N.hasTunnelGeometry;for(const W in this.buckets){const Z=this.buckets[W];if(Z instanceof o.bu){if(this.hasSymbolBuckets=!0,!z)break;Z.justReloaded=!0}}if(this.hasRTLText=!1,this.hasSymbolBuckets)for(const W in this.buckets){const Z=this.buckets[W];if(Z instanceof o.bu&&Z.hasRTLText){this.hasRTLText=!0,o.bN();break}}this.queryPadding=0;for(const W in this.buckets){const Z=this.buckets[W],ne=E.style.getOwnLayer(W);if(!ne)continue;const de=ne.queryRadius(Z)||0;this.queryPadding=Math.max(this.queryPadding,de)}N.imageAtlas&&(this.imageAtlas=E.style.imageManager.imageAtlasCache.getOrCache(N.imageAtlas)),N.glyphAtlasImage&&(this.glyphAtlasImage=N.glyphAtlasImage),N.lineAtlas&&(this.lineAtlas=N.lineAtlas),this._lastUpdatedBrightness=N.brightness}else this.collisionBoxArray=new o.bt}unloadVectorData(){if(this.hasData()){for(const N in this.buckets)this.buckets[N].destroy();this.buckets={},this.imageAtlas&&(this.imageAtlas=null),this.lineAtlas&&(this.lineAtlas=null),this.imageAtlasTexture&&(this.imageAtlasTexture=null),this.glyphAtlasTexture&&this.glyphAtlasTexture.destroy(),this.lineAtlasTexture&&this.lineAtlasTexture.destroy(),this._tileBoundsBuffer&&(this._tileBoundsBuffer.destroy(),this._tileBoundsIndexBuffer.destroy(),this._tileBoundsSegments.destroy(),this._tileBoundsBuffer=null),this._tileDebugBuffer&&(this._tileDebugBuffer.destroy(),this._tileDebugSegments.destroy(),this._tileDebugBuffer=null),this._tileDebugIndexBuffer&&(this._tileDebugIndexBuffer.destroy(),this._tileDebugIndexBuffer=null),this._globeTileDebugBorderBuffer&&(this._globeTileDebugBorderBuffer.destroy(),this._globeTileDebugBorderBuffer=null),this._tileDebugTextBuffer&&(this._tileDebugTextBuffer.destroy(),this._tileDebugTextSegments.destroy(),this._tileDebugTextIndexBuffer.destroy(),this._tileDebugTextBuffer=null),this._globeTileDebugTextBuffer&&(this._globeTileDebugTextBuffer.destroy(),this._globeTileDebugTextBuffer=null),this.latestFeatureIndex=null,this.state="unloaded"}}loadModelData(N,E,z){N&&(N.resourceTiming&&(this.resourceTiming=N.resourceTiming),this.buckets={...this.buckets,...Km(N.buckets,E.style)},N.featureIndex&&(this.latestFeatureIndex=N.featureIndex))}getBucket(N){return this.buckets[N.fqid]}upload(N,E){for(const Z in this.buckets){const ne=this.buckets[Z];if(ne.uploadPending()){let de={},ye=[],Ce={zoom:0,pitch:0,brightness:0,worldview:""};if(E){if(E.style){ye=E.style.listImages();const Pe=ne.layers[0],Ke=Pe.sourceLayer||"_geojsonTileLayer",Ze=E.style.getLayerSourceCache(Pe);Ze&&(de=Ze._state.getState(Ke,void 0))}Ce={zoom:E.transform.zoom||0,pitch:E.transform.pitch||0,brightness:E.style.getBrightness()||0,worldview:E.worldview||""}}ne.upload(N,this.tileID.canonical,de,ye,Ce)}}const z=N.gl,W=this.imageAtlas;W&&E&&(this.imageAtlasTexture=E.style.imageManager.imageAtlasCache.getTextureForAtlas(W,N,z.RGBA8),W.uploaded=!0),this.glyphAtlasImage&&(this.glyphAtlasTexture=new o.T(N,this.glyphAtlasImage,z.R8),this.glyphAtlasImage=null),this.lineAtlas&&!this.lineAtlas.uploaded&&(this.lineAtlasTexture=new o.T(N,this.lineAtlas.image,z.R8),this.lineAtlas.uploaded=!0)}prepare(N,E,z){if(this.imageAtlas&&this.imageAtlasTexture&&E){const Ze=E.style.getLut(z);this.imageAtlas.patchUpdatedImages(N,this.imageAtlasTexture,z,Ze)}if(!E||!this.latestFeatureIndex||!this.latestFeatureIndex.rawTileData)return;const W=E.style.getBrightness(),Z=E.style.listImages(),ne=Z.length,de=E.style._changes.getUpdatedPaintProperties(),ye=Object.keys(this.buckets).some(Ze=>this.buckets[Ze].layers.some(mt=>de.has(mt.fqid))),Ce=Object.keys(this.buckets).some(Ze=>this.buckets[Ze].layers.some(mt=>mt.hasTransition&&mt.hasTransition())),Pe=this._firstPrepareComplete&&ne!==this._lastAvailableImagesCount;this._hasAppearances===null&&(this._hasAppearances=this.hasAppearances(E));const Ke=this._lastUpdatedBrightness!==W;this._lastAvailableImagesCount=ne,this._firstPrepareComplete=!0,(this._lastUpdatedBrightness||W||this._hasAppearances||ye||Ce||Pe)&&(!(this._hasAppearances||ye||Ce||Pe)&&this._lastUpdatedBrightness&&W&&Math.abs(this._lastUpdatedBrightness-W)<.001||(this.updateBuckets(E,Ke,void 0,Pe||ye||Ce,de,Z),this._lastUpdatedBrightness=W))}evaluateQueryRenderedFeaturePadding(){let N=0;for(const E in this.buckets){const z=this.buckets[E];z.evaluateQueryRenderedFeaturePadding&&(N=Math.max(N,z.evaluateQueryRenderedFeaturePadding()))}return N}queryRenderedFeatures(N,E,z,W,Z,ne,de){if(!this.latestFeatureIndex||!this.latestFeatureIndex.rawTileData&&!this.latestFeatureIndex.is3DTile)return{};const ye=this.evaluateQueryRenderedFeaturePadding(),Ce=function(Pe,Ke){const Ze=o.bL([],[.5*Pe.width,.5*-Pe.height,1]);return o.bM(Ze,Ze,[1,-1,0]),o.X(Ze,Ze,Pe.calculateProjMatrix(Ke.toUnwrapped())),Float32Array.from(Ze)}(Z,this.tileID);return this.latestFeatureIndex.query(N,{tilespaceGeometry:E,pixelPosMatrix:Ce,transform:W,availableImages:z,tileTransform:this.tileTransform,worldview:this.worldview,queryRadius:ye,scope:de})}querySourceFeatures(N,E){const z=this.latestFeatureIndex;if(!z||!z.rawTileData)return;const W=z.loadVTLayers(),Z=E?E.sourceLayer:"",ne=W._geojsonTileLayer||W[Z];if(!ne)return;const de=o.bv(E&&E.filter),{z:ye,x:Ce,y:Pe}=this.tileID.canonical,Ke={z:ye,x:Ce,y:Pe};for(let Ze=0;Zez)W=!1;else if(E)if(this.expirationTimez.appearances&&z.appearances.length>0))return!0;return!1}updateBuckets(N,E,z,W,Z,ne){if(!this.latestFeatureIndex||!N.style)return;const de=ne||N.style.listImages(),ye=N.style.getBrightness(),Ce=Z||new Set;for(const Pe in this.buckets){if(!N.style.hasLayer(Pe))continue;const Ke=this.buckets[Pe],Ze=Ke.layers[0],mt=Ze.sourceLayer||"_geojsonTileLayer",vt=N.style.getLayerSourceCache(Ze),bt=Ke.layers.some(Ms=>Ce.has(Ms.fqid)),St=(W||bt)&&Ke instanceof o.bu?N.style.getOwnLayer(Pe):void 0;let Pt=z&&z[mt]||{};vt&&!z&&(Pt=vt._state.getState(mt,void 0));const Gt=this.imageAtlas?Object.fromEntries(this.imageAtlas.patternPositions):{},as=Object.keys(Pt).length>0&&!E;Ke.hasAppearances=Ke.layers.some(Ms=>Ms.appearances&&Ms.appearances.length>0);const ms=as?Ke.stateDependentLayers:Ke.layers;if(as&&Ke.stateDependentLayers.length!==0||E||bt||W){const Ms=this.latestFeatureIndex.loadVTLayers()[mt];if(Ke.update(Pt,Ms,de,Gt,ms,E,ye,this.tileID.canonical),(W||bt)&&(!E||E&&Ke instanceof o.bu&&(!Ke.text.uboBinder||Ke.text.uboBinder.isLightConstant||!Ke.icon.uboBinder||Ke.icon.uboBinder.isLightConstant))&&Ke instanceof o.bu&&St&&St.type==="symbol"){const Js=Ke;Js.text&&Js.text.uboBinder&&Js.text.uboBinder.updateDynamicExpressions(St,Ms,this.tileID.canonical,de,Pt,ye),Js.icon&&Js.icon.uboBinder&&Js.icon.uboBinder.updateDynamicExpressions(St,Ms,this.tileID.canonical,de,Pt,ye)}if(Ke instanceof o.bu){const Js=Ke,Os=N.context;Js.text&&Js.text.uboBinder&&Js.text.uboBinder.upload(Os),Js.icon&&Js.icon.uboBinder&&Js.icon.uboBinder.upload(Os)}}if(as&&Ke.stateDependentLayers.length!==0||E||Ke.hasAppearances){const Ms={zoom:N.transform.zoom,pitch:N.transform.pitch,brightness:N.style.getBrightness()||0,worldview:N.worldview},Js=Ke.updateAppearances(this.tileID.canonical,Pt,de,Ms,N.imageManager,as&&Ke.stateDependentLayers.length!==0);if(Js&&Js.hasUboChanges){const Os=N.context;Ke instanceof o.bu&&Ke.text&&Ke.text.uboBinder&&Ke.text.uboBinder.upload(Os),Ke instanceof o.bu&&Ke.icon&&Ke.icon.uboBinder&&Ke.icon.uboBinder.upload(Os)}}(Ke instanceof o.bz||Ke instanceof o.bA)&&N._terrain&&N._terrain.enabled&&vt&&Ke.uploadPending()&&N._terrain._clearRenderCacheForTile(vt.id,this.tileID);const Gs=N&&N.style&&N.style.getOwnLayer(Pe);Gs&&(this.queryPadding=Math.max(this.queryPadding,Gs.queryRadius(Ke)||0))}}holdingForFade(){return this.symbolFadeHoldUntil!==void 0}symbolFadeFinished(){return!this.symbolFadeHoldUntil||this.symbolFadeHoldUntil=0;St--){const Pt=4*St,Gt=Mf[Pt+0],as=Mf[Pt+1],ms=Mf[Pt+2],Gs=Mf[Pt+3],Ms=Gt+ms>>1,Js=as+Gs>>1,Os=Ms+Js-as,Ks=Js+Gt-Ms,_n=as*Fl+Gt,ln=Gs*Fl+ms,an=Js*Fl+Ms,bn=Math.hypot((Fd[2*_n+0]+Fd[2*ln+0])/2-Fd[2*an+0],(Fd[2*_n+1]+Fd[2*ln+1])/2-Fd[2*an+1])>=16;Gl[an]=Gl[an]||(bn?1:0),St<1022&&(Gl[an]=Gl[an]||Gl[(as+Ks>>1)*Fl+(Gt+Os>>1)]||Gl[(Gs+Ks>>1)*Fl+(ms+Os>>1)])}const Ke=new o.bs,Ze=new o.ad;let mt=0;function vt(St,Pt){const Gt=Pt*Fl+St;return km[Gt]===0&&(Ke.emplaceBack(Fd[2*Gt+0],Fd[2*Gt+1],St*o.a2/vu,Pt*o.a2/vu),km[Gt]=++mt),km[Gt]-1}function bt(St,Pt,Gt,as,ms,Gs){const Ms=St+Gt>>1,Js=Pt+as>>1;if(Math.abs(St-ms)+Math.abs(Pt-Gs)>1&&Gl[Js*Fl+Ms])bt(ms,Gs,St,Pt,Ms,Js),bt(Gt,as,ms,Gs,Ms,Js);else{const Os=vt(St,Pt),Ks=vt(Gt,as),_n=vt(ms,Gs);Ze.emplaceBack(Os,Ks,_n)}}return bt(0,0,vu,vu,vu,0),bt(vu,vu,0,0,0,vu),{vertices:Ke,indices:Ze}}(this.tileID.canonical,E);W=ne.vertices,Z=ne.indices}else{W=new o.bs,Z=new o.ad;for(const{x:de,y:ye}of z)W.emplaceBack(de,ye,0,0);const ne=o.bF(W.int16.subarray(0,4*W.length),void 0,4);for(let de=0;de0&&(ye=o.aO(new Float64Array(16),E.globeMatrix)),this._makeGlobeTileDebugBorderBuffer(N,W,E,ne,ye,de),this._makeGlobeTileDebugTextBuffer(N,W,E,ne,ye,de)}_globePoint(N,E,z,W,Z,ne,de){let ye=o.bG(N,E,z);if(ne){const Ce=1<.5?mt=-1:Ze<-.5&&(mt=1);let vt=(N/o.a2+z.x)/Ce+mt,bt=(E/o.a2+z.y)/Ce;vt=(vt-Pe)*W._pixelsPerMercatorPixel+Pe,bt=(bt-Ke)*W._pixelsPerMercatorPixel+Ke;const St=[vt*W.worldSize,bt*W.worldSize,0];o.bH(St,St,ne),ye=o.bI(ye,St,de)}return o.bH(ye,ye,Z)}_makeGlobeTileDebugBorderBuffer(N,E,z,W,Z,ne){const de=new o.bC,ye=new o.bD,Ce=new o.bJ,Pe=(Ze,mt,vt,bt,St)=>{const Pt=(vt-Ze)/(St-1),Gt=(bt-mt)/(St-1),as=de.length;for(let ms=0;msKe*mt+vt;for(let mt=0;mt{this.remove(N,Z)},z)),this.data[W].push(Z),this.order.push(W),this.order.length>this.max){const ne=this._getAndRemoveByKey(this.order[0]);ne&&this.onRemove(ne)}return this}has(N){return N.wrapped().key in this.data}getAndRemove(N){return this.has(N)?this._getAndRemoveByKey(N.wrapped().key):null}_getAndRemoveByKey(N){const E=this.data[N].shift();return E.timeout&&clearTimeout(E.timeout),this.data[N].length===0&&delete this.data[N],this.order.splice(this.order.indexOf(N),1),E.value}getByKey(N){const E=this.data[N];return E?E[0].value:null}get(N){return this.has(N)?this.data[N.wrapped().key][0].value:null}remove(N,E){if(!this.has(N))return this;const z=N.wrapped().key,W=E===void 0?0:this.data[z].indexOf(E),Z=this.data[z][W];return this.data[z].splice(W,1),Z.timeout&&clearTimeout(Z.timeout),this.data[z].length===0&&delete this.data[z],this.onRemove(Z.value),this.order.splice(this.order.indexOf(z),1),this}setMaxSize(N){for(this.max=N;this.order.length>this.max;){const E=this._getAndRemoveByKey(this.order[0]);E&&this.onRemove(E)}return this}filter(N){const E=[];for(const z in this.data)for(const W of this.data[z])N(W.value)||E.push(W);for(const z of E)this.remove(z.value.tileID,z)}}class hx{constructor(){this.state=Object.create(null),this.stateChanges=Object.create(null),this.deletedStates=Object.create(null)}updateState(N,E,z){const W=String(E);if(this.stateChanges[N]=this.stateChanges[N]||Object.create(null),this.stateChanges[N][W]=this.stateChanges[N][W]||Object.create(null),Object.assign(this.stateChanges[N][W],z),this.deletedStates[N]===null){this.deletedStates[N]=Object.create(null);for(const Z in this.state[N])Z!==W&&(this.deletedStates[N][Z]=null)}else if(this.deletedStates[N]&&this.deletedStates[N][W]===null){this.deletedStates[N][W]=Object.create(null);for(const Z in this.state[N][W])z[Z]||(this.deletedStates[N][W][Z]=null)}else for(const Z in z)this.deletedStates[N]&&this.deletedStates[N][W]&&this.deletedStates[N][W][Z]===null&&delete this.deletedStates[N][W][Z]}removeFeatureState(N,E,z){if(this.deletedStates[N]===null)return;const W=String(E);if(this.deletedStates[N]=this.deletedStates[N]||Object.create(null),z&&E!==void 0)this.deletedStates[N][W]!==null&&(this.deletedStates[N][W]=this.deletedStates[N][W]||Object.create(null),this.deletedStates[N][W][z]=null);else if(E!==void 0)if(this.stateChanges[N]&&this.stateChanges[N][W])for(z in this.deletedStates[N][W]=Object.create(null),this.stateChanges[N][W])this.deletedStates[N][W][z]=null;else this.deletedStates[N][W]=null;else this.deletedStates[N]=null}getState(N,E){const z=this.state[N]||Object.create(null),W=this.stateChanges[N]||Object.create(null),Z=this.deletedStates[N];if(Z===null)return Object.create(null);if(E!==void 0){const de=String(E),ye=Object.assign(Object.create(null),z[de],W[de]);if(Z){const Ce=Z[E];if(Ce===null)return Object.create(null);for(const Pe in Ce)delete ye[Pe]}return ye}const ne=Object.assign(Object.create(null),z,W);if(Z)for(const de in Z)delete ne[de];return ne}initializeTileState(N,E){N.refreshFeatureState(E)}coalesceChanges(N,E){const z=Object.create(null);for(const W in this.stateChanges){this.state[W]=this.state[W]||Object.create(null);const Z=Object.create(null);for(const ne in this.stateChanges[W])this.state[W][ne]||(this.state[W][ne]=Object.create(null)),Object.assign(this.state[W][ne],this.stateChanges[W][ne]),Z[ne]=this.state[W][ne];z[W]=Z}for(const W in this.deletedStates){this.state[W]=this.state[W]||Object.create(null);const Z=Object.create(null);if(this.deletedStates[W]===null)for(const ne in this.state[W])Z[ne]=Object.create(null),this.state[W][ne]=Object.create(null);else for(const ne in this.deletedStates[W]){if(this.deletedStates[W][ne]===null)this.state[W][ne]=Object.create(null);else if(this.state[W][ne])for(const de of Object.keys(this.deletedStates[W][ne]))delete this.state[W][ne][de];Z[ne]=this.state[W][ne]}z[W]=z[W]||Object.create(null),Object.assign(z[W],Z)}if(this.stateChanges=Object.create(null),this.deletedStates=Object.create(null),Object.keys(z).length!==0)for(const W in N)N[W].refreshFeatureState(E,z)}}class uh extends o.E{constructor(N,E,z){super(),this.id=N,this._renderSourceType=z,this._maxzoomOverride=null,this.setSource(E),this._tiles={},this._cache=new ux(0,this._unloadTile.bind(this)),this._timers={},this._cacheTimers={},this._minTileCacheSize=E.minTileCacheSize,this._maxTileCacheSize=E.maxTileCacheSize,this._loadedParentTiles={},this.castsShadows=!1,this.tileCoverLift=0,this._coveredTiles={},this._shadowCasterTiles={},this._state=new hx,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(N){this.map=N,this._minTileCacheSize=this._minTileCacheSize===void 0&&N?N._minTileCacheSize:this._minTileCacheSize,this._maxTileCacheSize=this._maxTileCacheSize===void 0&&N?N._maxTileCacheSize:this._maxTileCacheSize}setSource(N){N.on("data",E=>{E.dataType==="source"&&E.sourceDataType==="metadata"&&(this._sourceLoaded=!0),this._sourceLoaded&&!this._paused&&E.dataType==="source"&&E.sourceDataType==="content"&&(this.reload(),this.transform&&this.update(this.transform))}),N.on("error",()=>{this._sourceErrored=!0}),this._source=N}loaded(){if(this._sourceErrored)return!0;if(!this._sourceLoaded||!this._source.loaded())return!1;for(const N in this._tiles)if(!this._tiles[N].loaded())return!1;return!0}getSource(){return this._source}pause(){this._paused=!0}resume(){if(!this._paused)return;const N=this._shouldReloadOnResume;this._paused=!1,this._shouldReloadOnResume=!1,N&&this.reload(),this.transform&&this.update(this.transform)}setMaxzoomOverride(N){this._maxzoomOverride=N}_loadTile(N,E){return N.renderSourceType=this._renderSourceType,N.isExtraShadowCaster=this._shadowCasterTiles[N.tileID.key],this._source.loadTile(N,E)}_unloadTile(N){if(this._source.unloadTile)return this._source.unloadTile(N)}_abortTile(N){if(this._source.abortTile)return this._source.abortTile(N)}serialize(){return this._source.serialize()}prepare(N){this._source.prepare&&this._source.prepare(),this._state.coalesceChanges(this._tiles,this.map?this.map.painter:null);for(const E in this._tiles){const z=this._tiles[E];z.upload(N,this.map?this.map.painter:void 0),z.prepare(this.map.style.imageManager,this.map?this.map.painter:null,this._source.scope)}}getIds(){return Object.values(this._tiles).map(N=>N.tileID).sort(Xd).map(N=>N.key)}getRenderableIds(N,E){const z=[];for(const W in this._tiles)this._isIdRenderable(+W,N,E)&&z.push(this._tiles[W]);return N?z.sort((W,Z)=>{const ne=W.tileID,de=Z.tileID,ye=new o.P(ne.canonical.x,ne.canonical.y)._rotate(this.transform.angle),Ce=new o.P(de.canonical.x,de.canonical.y)._rotate(this.transform.angle);return ne.overscaledZ-de.overscaledZ||Ce.y-ye.y||Ce.x-ye.x}).map(W=>W.tileID.key):z.map(W=>W.tileID).sort(Xd).map(W=>W.key)}hasRenderableParent(N){const E=this.findLoadedParent(N,0);return!!E&&this._isIdRenderable(E.tileID.key)}_isIdRenderable(N,E,z){return this._tiles[N]&&this._tiles[N].hasData()&&!this._coveredTiles[N]&&(E||!this._tiles[N].holdingForFade())&&(z||!this._shadowCasterTiles[N])}reload(){if(this._paused)this._shouldReloadOnResume=!0;else{this._cache.reset();for(const N in this._tiles)this._tiles[N].state!=="errored"&&this._reloadTile(+N,"reloading")}}_reloadTile(N,E){const z=this._tiles[N];z&&(z.state!=="loading"&&(z.state=E),this._loadTile(z,this._tileLoaded.bind(this,z,N,E)))}_tileLoaded(N,E,z,W,Z){if(W){if(N.state="errored",o.bO(W)){if(this._source.fire(new o.h("data",{dataType:"source",sourceDataType:"error",sourceId:this._source.id,tile:N})),!(N.tileID.key in this._loadedParentTiles))return;if(this._source.type==="raster-dem"&&this.usedForTerrain&&this.map.painter.terrain){const de=this.map.painter.terrain;this.update(this.transform,de.getScaledDemTileSize(),!0),de.resetTileLookupCache(this.id)}else this.update(this.transform)}else this._source.fire(new o.f(W,{tile:N}));return}N.timeAdded=o.e.now(),z==="expired"&&(N.refreshedUponExpiration=!0),this._setTileReloadTimer(E,N),this._source.type==="raster-dem"&&N.dem&&this._backfillDEM(N),this._state.initializeTileState(N,this.map?this.map.painter:null);let ne=new Headers;Z&&Z.headers&&(ne=Z.headers),this._source.fire(new o.h("data",{dataType:"source",tile:N,coord:N.tileID,sourceCacheId:this.id,responseHeaders:ne}))}_hasTunnelGeometry(){for(const N in this._tiles){const E=this._tiles[N];if(E&&E.hasTunnelGeometry)return!0}return!1}_backfillDEM(N){const E=this.getRenderableIds();for(let W=0;W1||(Math.abs(ne)>1&&(Math.abs(ne+ye)===1?ne+=ye:Math.abs(ne-ye)===1&&(ne-=ye)),Z.dem&&W.dem&&(W.dem.backfillBorder(Z.dem,ne,de),W.neighboringTiles&&W.neighboringTiles[Ce]&&(W.neighboringTiles[Ce].backfilled=!0)))}}getTile(N){return this.getTileByID(N.key)}getTileByID(N){return this._tiles[N]}_retainLoadedChildren(N,E,z,W){for(const Z in this._tiles){let ne=this._tiles[Z];if(W[Z]||!ne.hasData()||ne.tileID.overscaledZ<=E||ne.tileID.overscaledZ>z)continue;let de=ne.tileID;for(;ne&&ne.tileID.overscaledZ>E+1;){const Ce=ne.tileID.scaledTo(ne.tileID.overscaledZ-1);ne=this._tiles[Ce.key],ne&&ne.hasData()&&(de=Ce)}let ye=de;for(;ye.overscaledZ>E;)if(ye=ye.scaledTo(ye.overscaledZ-1),N[ye.key]){W[de.key]=de;const Ce=this._tiles[de.key];Ce&&(Ce.dashIdealZ=ye.overscaledZ);break}}}findLoadedParent(N,E){if(N.key in this._loadedParentTiles){const z=this._loadedParentTiles[N.key];return z&&z.tileID.overscaledZ>=E?z:null}for(let z=N.overscaledZ-1;z>=E;z--){const W=N.scaledTo(z),Z=this._getLoadedTile(W);if(Z)return Z}}_getLoadedTile(N){const E=this._tiles[N.key];return E&&E.hasData()?E:this._cache.getByKey(this._source.reparseOverscaled?N.wrapped().key:N.canonical.key)}updateCacheSize(N,E){E=E||this._source.tileSize;const z=Math.ceil(N.width/E)+1,W=Math.ceil(N.height/E)+1,Z=Math.floor(z*W*5),ne=typeof this._minTileCacheSize=="number"?Math.max(this._minTileCacheSize,Z):Z,de=typeof this._maxTileCacheSize=="number"?Math.min(this._maxTileCacheSize,ne):ne;this._cache.setMaxSize(de)}handleWrapJump(N){const E=Math.round((N-(this._prevLng===void 0?N:this._prevLng))/360);if(this._prevLng=N,E){const z={};for(const W in this._tiles){const Z=this._tiles[W];Z.tileID=Z.tileID.unwrapTo(Z.tileID.wrap+E),z[Z.tileID.key]=Z}this._tiles=z;for(const W in this._timers)clearTimeout(this._timers[W]),delete this._timers[W];for(const W in this._tiles)this._setTileReloadTimer(+W,this._tiles[W])}}update(N,E,z,W,Z){if(this.transform=N,!this._sourceLoaded||this._paused||this.transform.freezeTileCoverage||this.usedForTerrain&&!z)return;this.updateCacheSize(N,E),this.transform.projection.name!=="globe"&&this.handleWrapJump(this.transform.center.lng),this._shadowCasterTiles={},this._coveredTiles={};const ne=this._source.type==="batched-model";let de,ye=this._source.maxzoom;this._maxzoomOverride!==null&&(ye=Math.min(ye,this._maxzoomOverride));const Ce=this.map&&this.map.painter?this.map.painter._terrain:null;if(Ce&&Ce.sourceCache===this&&Ce.attenuationRange()){const mt=Ce.attenuationRange()[0],vt=Math.floor(mt)-Math.log2(Ce.getDemUpscale());ye>vt&&(ye=vt)}const Pe=this._maxzoomOverride===null&&this._source.reparseOverscaled;if(this.used||this.usedForTerrain){if(this._source.tileID)de=N.getVisibleUnwrappedCoordinates(this._source.tileID).map(mt=>new o.bP(mt.canonical.z,mt.wrap,mt.canonical.z,mt.canonical.x,mt.canonical.y));else if(this.tileCoverLift!==0){const mt=N.clone();mt.tileCoverLift=this.tileCoverLift,de=mt.coveringTiles({tileSize:E||this._source.tileSize,minzoom:this._source.minzoom,maxzoom:ye,roundZoom:this._source.roundZoom&&!z,reparseOverscaled:Pe,isTerrainDEM:this.usedForTerrain,calculateQuadrantVisibility:ne}),this._source.minzoom<=1&&N.projection.name==="globe"&&(de.push(new o.bP(1,0,1,0,0)),de.push(new o.bP(1,0,1,1,0)),de.push(new o.bP(1,0,1,0,1)),de.push(new o.bP(1,0,1,1,1)))}else if(de=N.coveringTiles({tileSize:E||this._source.tileSize,minzoom:this._source.minzoom,maxzoom:ye,roundZoom:this._source.roundZoom&&!z,reparseOverscaled:Pe,isTerrainDEM:this.usedForTerrain,calculateQuadrantVisibility:ne}),this._source.hasTile){const mt=this._source.hasTile.bind(this._source);de=de.filter(vt=>mt(vt))}}else de=[];if(de.length>0&&this.transform.projection.name!=="globe"&&!this.usedForTerrain&&!this._supportsFading){const mt=N.coveringZoomLevel({tileSize:E||this._source.tileSize,roundZoom:this._source.roundZoom&&!z}),vt=Math.min(mt,ye);if(ne){const bt=N.extendTileCover(de,vt);for(const St of bt)de.push(St)}else if(Z){const bt=this.transform.getFrustum(vt),St=N.extendTileCoverToNearPlane(de,bt,vt);for(const Pt of St)de.push(Pt);if(vt>=18&&this._hasTunnelGeometry()){const Pt=N.extendTileCoverForTunnels(de,bt,vt,20);for(const Gt of Pt)de.push(Gt)}}else if(this.castsShadows&&W){const bt=N.extendTileCover(de,vt,W,16);for(const St of bt)this._shadowCasterTiles[St.key]=!0,de.push(St)}}for(const mt in this._tiles){const vt=this._tiles[mt];vt.dashIdealZ=vt.tileID.overscaledZ}const Ke=this._updateRetainedTiles(de);if(this._supportsFading&&de.length!==0){const mt={},vt={},bt=o.e.now(),St=Object.keys(Ke);for(const Gt of St){const as=Ke[Gt],ms=this._tiles[Gt];if(!ms||ms.fadeEndTime!==void 0&&ms.fadeEndTime<=bt)continue;const Gs=this.findLoadedParent(as,Math.max(as.overscaledZ-uh.maxOverzooming,this._source.minzoom));Gs&&(this._addTile(Gs.tileID),mt[Gs.tileID.key]=Gs.tileID),vt[Gt]=as}const Pt=de.at(-1).overscaledZ;for(const Gt in this._tiles){const as=this._tiles[Gt];if(Ke[Gt]||!as.hasData())continue;let ms=as.tileID;for(;ms.overscaledZ>Pt;){ms=ms.scaledTo(ms.overscaledZ-1);const Gs=this._tiles[ms.key];if(Gs&&Gs.hasData()&&vt[ms.key]){Ke[Gt]=as.tileID;break}}}for(const Gt in mt)Ke[Gt]||(this._coveredTiles[Gt]=!0,Ke[Gt]=mt[Gt])}for(const mt in Ke)this._tiles[mt].clearFadeHold();const Ze=o.bQ(this._tiles,Ke);for(const mt of Ze){const vt=this._tiles[mt];vt.hasSymbolBuckets&&!vt.holdingForFade()?vt.setHoldDuration(this.map._fadeDuration):vt.hasSymbolBuckets&&!vt.symbolFadeFinished()||this._removeTile(+mt)}this._updateLoadedParentTileCache(),this._renderSourceType===o.bR.Symbol&&this._source.afterUpdate&&this._source.afterUpdate()}releaseSymbolFadeTiles(){for(const N in this._tiles)this._tiles[N].holdingForFade()&&this._removeTile(+N)}_updateRetainedTiles(N){const E={};if(N.length===0)return E;const z={},W=N.reduce((Ce,Pe)=>Math.min(Ce,Pe.overscaledZ),1/0),Z=N[0].overscaledZ,ne=Math.max(Z-uh.maxOverzooming,this._source.minzoom),de=Math.max(Z+uh.maxUnderzooming,this._source.minzoom),ye={};for(const Ce of N){const Pe=this._addTile(Ce);E[Ce.key]=Ce,Pe.hasData()||W=this._source.maxzoom){const Ze=Ce.children(this._source.maxzoom)[0],mt=this.getTile(Ze);if(mt&&mt.hasData()){E[Ze.key]=Ze,mt.dashIdealZ=Ce.overscaledZ;continue}}else{const Ze=Ce.children(this._source.maxzoom);if(E[Ze[0].key]&&E[Ze[1].key]&&E[Ze[2].key]&&E[Ze[3].key])continue}let Ke=Pe.wasRequested();for(let Ze=Ce.overscaledZ-1;Ze>=ne;--Ze){const mt=Ce.scaledTo(Ze);if(z[mt.key]||(z[mt.key]=!0,Pe=this.getTile(mt),!Pe&&Ke&&(Pe=this._addTile(mt)),Pe&&(E[mt.key]=mt,Pe.dashIdealZ=Ce.overscaledZ,Ke=Pe.wasRequested(),Pe.hasData())))break}}return E}_updateLoadedParentTileCache(){this._loadedParentTiles={};for(const N in this._tiles){const E=[];let z,W=this._tiles[N].tileID;for(;W.overscaledZ>0;){if(W.key in this._loadedParentTiles){z=this._loadedParentTiles[W.key];break}E.push(W.key);const Z=W.scaledTo(W.overscaledZ-1);if(z=this._getLoadedTile(Z),z)break;W=Z}for(const Z of E)this._loadedParentTiles[Z]=z}}_addTile(N){let E=this._tiles[N.key];if(E)return E.isExtraShadowCaster!==!0||this._shadowCasterTiles[N.key]||this._reloadTile(N.key,"reloading"),E;E=this._cache.getAndRemove(N),E&&(this._setTileReloadTimer(N.key,E),E.tileID=N,this._state.initializeTileState(E,this.map?this.map.painter:null),this._cacheTimers[N.key]&&(clearTimeout(this._cacheTimers[N.key]),delete this._cacheTimers[N.key],this._setTileReloadTimer(N.key,E)));const z=!!E;if(!z){const W=this.map?this.map.painter:null,Z=this._source.tileSize*N.overscaleFactor();E=this._source.type==="raster-array"?function(ne,de,ye,Ce,Pe){if(!Ec)throw new Error("Raster-array module is not loaded.");return Ec(ne,de,ye,Ce,Pe)}(N,Z,this.transform.tileZoom,W,this._isRaster):new Ym(N,Z,this.transform.tileZoom,W,this._isRaster,this._source.worldview),this._loadTile(E,this._tileLoaded.bind(this,E,N.key,E.state))}return E.uses++,this._tiles[N.key]=E,z||this._source.fire(new o.h("dataloading",{tile:E,coord:E.tileID,dataType:"source"})),E}_setTileReloadTimer(N,E){N in this._timers&&(clearTimeout(this._timers[N]),delete this._timers[N]);const z=E.getExpiryTimeout();z&&(this._timers[N]=setTimeout(()=>{this._reloadTile(N,"expired"),delete this._timers[N]},z))}_removeTile(N){const E=this._tiles[N];E&&(E.uses--,delete this._tiles[N],this._timers[N]&&(clearTimeout(this._timers[N]),delete this._timers[N]),E.uses>0||(E.hasData()&&E.state!=="reloading"||E.state==="empty"?this._cache.add(E.tileID,E,E.getExpiryTimeout()):(E.aborted=!0,this._abortTile(E),this._unloadTile(E))))}clearTiles(){this._shouldReloadOnResume=!1,this._paused=!1;for(const N in this._tiles)this._removeTile(+N);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(N,E,z){const W=[],Z=this.transform;if(!Z)return W;const ne=Z.projection.name==="globe",de=o.a7(Z.center.lng),ye=Z.getFreeCameraOptions().position||new o.bS(0,0,0);for(const Ce in this._tiles){const Pe=this._tiles[Ce];if(z&&Pe.clearQueryDebugViz(),Pe.holdingForFade())continue;let Ke;if(ne){const Ze=Pe.tileID.canonical;if(Ze.z===0){const mt=[Math.abs(o.b0(de,...al(Ze,-1))-de),Math.abs(o.b0(de,...al(Ze,1))-de)];Ke=[0,2*mt.indexOf(Math.min(...mt))-1]}else{const mt=[Math.abs(o.b0(de,...al(Ze,-1))-de),Math.abs(o.b0(de,...al(Ze,0))-de),Math.abs(o.b0(de,...al(Ze,1))-de)];Ke=[mt.indexOf(Math.min(...mt))-1]}}else Ke=[0];for(const Ze of Ke){const mt=N.containsTile(Pe,Z,E,Ze,ye);mt&&W.push(mt)}}return W}getShadowCasterCoordinates(){return this._getRenderableCoordinates(!1,!0)}getVisibleCoordinates(N){return this._getRenderableCoordinates(N)}_getRenderableCoordinates(N,E){if(!this.transform)return[];const z=this.getRenderableIds(N,E).map(Z=>this._tiles[Z].tileID),W=this.transform.projection.name==="globe";for(const Z of z)Z.projMatrix=this.transform.calculateProjMatrix(Z.toUnwrapped()),Z.expandedProjMatrix=W?this.transform.calculateProjMatrix(Z.toUnwrapped(),!1,!0):Z.projMatrix;return z}sortCoordinatesByDistance(N){if(!this.transform)return N.slice();const E=N.slice(),z=this.transform._camera.position,W=this.transform._camera.forward(),Z={};for(const ne of E){const de=1/(1<Z[ne.key]-Z[de.key]),E}hasTransition(){if(this._source.hasTransition())return!0;if(this._supportsFading){const N=o.e.now();for(const E in this._tiles){const z=this._tiles[E];if(z.fadeEndTime!==void 0&&z.fadeEndTime>=N)return!0}}return!1}setFeatureState(N,E,z){this._state.updateState(N=N||"_geojsonTileLayer",E,z)}removeFeatureState(N,E,z){this._state.removeFeatureState(N=N||"_geojsonTileLayer",E,z)}getFeatureState(N,E){return this._state.getState(N=N||"_geojsonTileLayer",E)}setDependencies(N,E,z){const W=this._tiles[N];W&&W.setDependencies(E,z)}reloadTilesForDependencies(N,E){for(const z in this._tiles)this._tiles[z].hasDependency(N,E)&&this._reloadTile(+z,"reloading");this._cache.filter(z=>!z.hasDependency(N,E))}_preloadTiles(N,E){if(!this._sourceLoaded){const ye=()=>{this._sourceLoaded&&(this._source.off("data",ye),this._preloadTiles(N,E))};return void this._source.on("data",ye)}const z=new Map,W=Array.isArray(N)?N:[N],Z=this.map.painter.terrain,ne=this.usedForTerrain&&Z?Z.getScaledDemTileSize():this._source.tileSize;for(const ye of W){const Ce=ye.coveringTiles({tileSize:ne,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 Ce)z.set(Pe.key,Pe);this.usedForTerrain&&ye.updateElevation(!1)}const de=Array.from(z.values());o.bT(de,(ye,Ce)=>{const Pe=new Ym(ye,this._source.tileSize*ye.overscaleFactor(),this.transform.tileZoom,this.map.painter,this._isRaster,this._source.worldview);this._loadTile(Pe,Ke=>{this._source.type==="raster-dem"&&Pe.dem&&this._backfillDEM(Pe),Ce(Ke,Pe)})},E)}}function Xd(L,N){const E=Math.abs(2*L.wrap)-+(L.wrap<0),z=Math.abs(2*N.wrap)-+(N.wrap<0);return L.overscaledZ-N.overscaledZ||z-E||N.canonical.y-L.canonical.y||N.canonical.x-L.canonical.x}function al(L,N){const E=1<>z===L.x&&N.y>>z===L.y}const E=L.z-N.z;return L.x>>E===N.x&&L.y>>E===N.y}function sl(L,N){return L.sourceFQID!==N.sourceFQID?L.sourceFQID{return!!de.hasDeferredElevationFeatures||ne&&(ye=W,Qi(z,Ce=de.tileID.canonical)!==Qi(ye,Ce));var ye,Ce})}const Yu=L=>({u_matrix:L});function Kp(L,N){const E=L.context.gl;return new o._({func:E.EQUAL,mask:255},L._tileClippingMaskIDs[N.key]||0,0,E.KEEP,E.KEEP,E.KEEP)}function rm(L,N){const E=L.context.gl;return new o._({func:E.EQUAL,mask:255},255&~(L._tileClippingMaskIDs[N.key]||0),0,E.KEEP,E.KEEP,E.KEEP)}function S1(L,N){if(!L.frcCoverageSnapshot||!L.frcCoverageRenderer)return null;const E=L.frcCoverageSnapshot.getTileOrParent(N.canonical);if(!E||E.frcMask===0)return null;const z=L.frcCoverageRenderer.getBuffers(E.tileId);if(!z)return null;const W=new o.bX(E.tileId.z,E.tileId.x,E.tileId.y),Z=new o.bY(N.wrap,W);return{buffers:z,projMatrix:L.transform.calculateProjMatrix(Z),coverageTile:E}}function Zu(L,N,E){if(!L.frcCoverageSnapshot)return;const z=L.context,W=z.gl,Z=L.getOrCreateProgram("clippingMask");z.setColorMode(o.a1.disabled),z.setDepthMode(o.Z.disabled);for(const ne of N){const de=S1(L,ne);if(!de)continue;const ye=de.buffers.frcLevelSegments[E];ye&&Z.draw(L,W.TRIANGLES,o.Z.disabled,new o._({func:W.EQUAL,mask:255},L._tileClippingMaskIDs[ne.key]||0,255,W.KEEP,W.KEEP,W.INVERT),o.a1.disabled,o.$.disabled,Yu(de.projMatrix),`$frc_coverage_${E}`,de.buffers.vertexBuffer,de.buffers.indexBuffer,ye)}}function rd(L,N,E){if(!L.frcCoverageSnapshot)return;const z=L.context,W=z.gl,Z=L.getOrCreateProgram("clippingMask");z.setColorMode(o.a1.disabled),z.setDepthMode(o.Z.disabled);for(const ne of N){const de=S1(L,ne);if(!de)continue;const ye=de.buffers.frcLevelSegments[E];ye&&Z.draw(L,W.TRIANGLES,o.Z.disabled,new o._({func:W.EQUAL,mask:255},255&~(L._tileClippingMaskIDs[ne.key]||0),255,W.KEEP,W.KEEP,W.INVERT),o.a1.disabled,o.$.disabled,Yu(de.projMatrix),`$frc_coverage_restore_${E}`,de.buffers.vertexBuffer,de.buffers.indexBuffer,ye)}}function Xm(L,N,E,z,W){if(N.length===0)return;let Z=0;for(const de of N)Z|=de.frcMask;const ne=N.map(de=>de.coord);for(let de=0;de<9;++de)if(Z&1<0&&W)for(const ye of N)ye.frcMask&1<0&&N.rings[0].length>0)return!0;return!1}function Iu(L){const N=L.frcCoverageFadeRange;return!N||N[1]<=N[0]?0:1-Math.max(0,Math.min(1,(L.transform.zoom-N[0])/(N[1]-N[0])))}const E0={loaded:!0,drawBuilding:function(L,N,E,z){L.currentLayer0&&Z>0,Ce=!0;const Pe=E.paint.get("building-vertical-scale");if(Pe<=0)return;L.shadowRenderer||(Ce=!1);const Ke=L.conflationActive&&L.style.isLayerClipped(E,N.getSource()),Ze=L.style.order.indexOf(E.fqid);if(function(mt,vt,bt,St,Pt,Gt){for(const as of Gt){const ms=vt.getTile(as).getBucket(bt);ms&&(Pt&&ms.updateReplacement(as,mt.replacementSource,St),ms.uploadUpdatedIndexBuffer(mt.context))}}(L,N,E,Ze,Ke,z),function(mt,vt,bt,St){for(const Pt of St){const Gt=vt.getTile(Pt).getBucket(bt);Gt&&Gt.needsEvaluation()&&Gt.uploadUpdatedColorBuffer(mt.context)}}(L,N,E,z),E.resetLayerRenderingStats(L),L.shadowRenderer&&(L.shadowRenderer.useNormalOffset=!0),L.renderPass==="shadow"&&L.shadowRenderer){const mt=[],vt=L.shadowRenderer.getShadowPassDepthMode();$r({painter:L,source:N,layer:E,coords:z,defines:mt,blendMode:o.a1.disabled,depthMode:vt,opacity:de,verticalScale:Pe,facadeEmissiveChance:0,facadeAOIntensity:0,floodLightIntensity:0,floodLightColor:[0,0,0]})}else if(L.renderPass==="translucent"){let mt=["HAS_ATTRIBUTE_a_part_color_emissive","LIGHTING_3D_MODE"];Ce&&(mt=mt.concat("RENDER_SHADOWS")),L.shadowRenderer&&L.shadowRenderer.useNormalOffset&&(mt=mt.concat("NORMAL_OFFSET"));const vt=E.paint.get("building-facade-emissive-chance"),bt=E.paint.get("building-ambient-occlusion-intensity"),St=E.paint.get("building-flood-light-intensity"),Pt=E.paint.get("building-flood-light-color-use-theme").constantOr("default")==="none",Gt=E.paint.get("building-flood-light-color").toNonPremultipliedRenderColor(Pt?null:E.lut).toArray01().slice(0,3),as=E.paint.get("building-flood-light-ground-attenuation"),ms=St>0,Gs=new o.Z(L.context.gl.LEQUAL,o.Z.ReadWrite,L.depthRangeFor3D);de<1&&$r({painter:L,source:N,layer:E,coords:z,defines:mt,blendMode:o.a1.disabled,depthMode:Gs,opacity:de,verticalScale:Pe,facadeEmissiveChance:vt,facadeAOIntensity:bt,floodLightIntensity:St,floodLightColor:Gt,depthOnly:!0});const Ms=L.colorModeForRenderPass();$r({painter:L,source:N,layer:E,coords:z,defines:mt,blendMode:Ms,depthMode:Gs,opacity:de,verticalScale:Pe,facadeEmissiveChance:vt,facadeAOIntensity:bt,floodLightIntensity:St,floodLightColor:Gt});const Js=E.paint.get("building-front-cutoff");cn(L.transform.pitch,Js,!!L.terrain),ye&&Ca(L,N,E,z,!0,de,W,Z,St,Gt,ne,Ke),ms&&Ca(L,N,E,z,!1,de,W,Z,St,Gt,as,Ke)}else if(L.renderPass==="light-beam"){const mt=["HAS_ATTRIBUTE_a_part_color_emissive","HAS_ATTRIBUTE_a_bloom_attenuation"],vt=new o.Z(L.context.gl.LEQUAL,o.Z.ReadOnly,L.depthRangeFor3D);$r({painter:L,source:N,layer:E,coords:z,defines:mt,blendMode:o.a1.alphaBlended,depthMode:vt,opacity:de,verticalScale:Pe,facadeEmissiveChance:0,facadeAOIntensity:0,floodLightIntensity:0,floodLightColor:[0,0,0]})}L.shadowRenderer&&(L.shadowRenderer.useNormalOffset=!1),L.resetStencilClippingMasks()},BuildingTileBorderManager:class{constructor(){this.visibleTiles=[]}updateBorders(L,N){const E=[],z=[],W=L._getRenderableCoordinates(!1,!0);for(const de of W){const ye=L.getTile(de);if(!ye.hasData())continue;const Ce=ye.getBucket(N);Ce&&(Ce.isEmpty()||(E.push(de.key),z.push({bucket:Ce,tileID:de.canonical})))}let Z=E.length!==this.visibleTiles.length;if(!Z){E.sort();for(let de=0;dede.tileID.z-ye.tileID.z||de.tileID.x-ye.tileID.x||de.tileID.y-ye.tileID.y);for(const de of z){const ye=new Array,Ce=new Array,Pe=de.bucket;for(const Ke of Pe.featuresOnBorder)Pe.footprints[Ke.footprintIndex].hiddenFlags&o.aR||(ne.has(Ke.featureId)?Ce.push(Ke.footprintIndex):(ne.add(Ke.featureId),ye.push(Ke.footprintIndex)));Pe.updateFootprintHiddenFlags(ye,o.aS,!1),Pe.updateFootprintHiddenFlags(Ce,o.aS,!0)}}},drawRasterParticle:function(L,N,E,z,W,Z){L.renderPass==="offscreen"&&function(ne,de,ye,Ce){if(!Ce.length)return;const Pe=ne.context,Ke=Pe.gl,Ze=de.getSource();if(Ze.type!=="raster-array")return;const mt=Math.ceil(Math.sqrt(ye.paint.get("raster-particle-count")));let vt=ye.particlePositionRGBAImage;if(!vt||vt.width!==mt){const as=function(ms){const Gs=ms*ms,Ms=new Uint8Array(4*Gs),Js=.9090909090909091;for(let Os=0;Oso.aB[Qr](bn));Hn.push(bn);const Tr=bn.canonical.x,oa=bn.canonical.y;for(const Qr of Hn){const Lr=ms.getTile(_n?Qr.wrapped():Qr);if(!Lr)continue;const qa=Lr.rasterParticleState;if(!qa)continue;const Nr=Qr.canonical.x+(1<N.getTileByID(de));for(const de of ne)de.updateNeeded(L.id,Z)&&z.prepareTile(de,W,L.id,Z)},Rain:class extends Od{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(L){const N=L.context;if(!this.particlesVx){const E=Wu(this.particlesCount),z=new o.bk,W=new o.ad;let Z=0;const ne=o.bi(1323123451230);for(let de=0;dene)return;const de=$c(0,1,z.revealStart,z.revealStart+z.revealRange,ne);if(!this.particlesVx||!this.particlesIdx)return;Z.strength*=de;const ye=this.updateOnRender(L,E.timeFactor),Ce=L.context,Pe=Ce.gl,Ke=L.transform;this.screenTexture&&this.screenTexture.size[0]===L.width&&this.screenTexture.size[1]===L.height||(this.screenTexture=new o.T(Ce,{width:L.width,height:L.height,data:null},Pe.RGBA8)),E.distortionStrength>0&&(Ce.activeTexture.set(Pe.TEXTURE0),this.screenTexture.bind(Pe.LINEAR,Pe.CLAMP_TO_EDGE),Pe.copyTexSubImage2D(Pe.TEXTURE_2D,0,0,0,0,0,L.width,L.height));const Ze=L.getOrCreateProgram("rainParticle");L.uploadCommonUniforms(Ce,Ze),Ce.activeTexture.set(Pe.TEXTURE0),this.screenTexture.bind(Pe.LINEAR,Pe.CLAMP_TO_EDGE);const mt=[E.color.r,E.color.g,E.color.b,E.color.a],vt=(bt,St)=>{const Pt=yd(this._movement.getPosition(),bt),Gt=E.dropletSizeX,as=E.dropletSizeX*E.dropletSizeYScale,ms=L.width/2,Gs=L.height/2,Ms=$c(0,E.screenThinning.start,0,1,E.screenThinning.intensity),Js=$c(.001,E.screenThinning.range,0,1,E.screenThinning.intensity),Os=$c(0,E.screenThinning.particleOffset,0,1,E.screenThinning.intensity),Ks=(_n={modelview:ye.modelviewMatrix,projection:ye.projectionMatrix,time:this._accumulatedTimeFromStart,camPos:Pt,velocityConeAperture:E.velocityConeAperture,velocity:E.velocity,boxSize:bt,rainDropletSize:[Gt,as],distortionStrength:E.distortionStrength,rainDirection:W,color:mt,screenSize:[Ke.width,Ke.height],thinningCenterPos:[ms,Gs],thinningShape:[Ms,Js,Math.pow(10,E.screenThinning.fadePower)],thinningAffectedRatio:E.screenThinning.affectedRatio,thinningParticleOffset:Os,shapeDirectionalPower:E.shapeDirPower,shapeNormalPower:E.shapeNormalPower,mode:St?0:1},{u_modelview:Float32Array.from(_n.modelview),u_projection:Float32Array.from(_n.projection),u_time:_n.time,u_cam_pos:_n.camPos,u_texScreen:0,u_velocityConeAperture:_n.velocityConeAperture,u_velocity:_n.velocity,u_boxSize:_n.boxSize,u_rainDropletSize:_n.rainDropletSize,u_distortionStrength:_n.distortionStrength,u_rainDirection:_n.rainDirection,u_color:_n.color,u_screenSize:_n.screenSize,u_thinningCenterPos:_n.thinningCenterPos,u_thinningShape:_n.thinningShape,u_thinningAffectedRatio:_n.thinningAffectedRatio,u_thinningParticleOffset:_n.thinningParticleOffset,u_shapeDirectionalPower:_n.shapeDirectionalPower,u_shapeNormalPower:_n.shapeNormalPower,u_mode:_n.mode});var _n;const ln=Math.round(E.intensity*this.particlesCount),an=o.ac.simpleSegment(0,0,4*ln,2*ln);Ze.draw(L,Pe.TRIANGLES,o.Z.disabled,o._.disabled,o.a1.alphaBlended,o.$.disabled,Ks,"rain_particles",this.particlesVx,this.particlesIdx,an)};E.distortionStrength>0&&vt(E.boxSize,!0),vt(E.boxSize,!1),this._vignette.draw(L,Z)}},Snow:class extends Od{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(L){const N=L.context;if(!this.particlesVx){const E=Wu(this.particlesCount),z=new o.bl,W=new o.ad;let Z=0;const ne=o.bi(1323123451230);for(let de=0;dene)return;const de=$c(0,1,z.revealStart,z.revealStart+z.revealRange,ne);Z.strength*=de;const ye=this.updateOnRender(L,E.timeFactor);if(!this.particlesVx||!this.particlesIdx)return;const Ce=L.context,Pe=Ce.gl,Ke=L.transform,Ze=L.getOrCreateProgram("snowParticle");L.uploadCommonUniforms(Ce,Ze),((mt,vt,bt)=>{const St=yd(this._movement.getPosition(),mt),Pt=Ke.width/2,Gt=Ke.height/2,as=$c(0,bt.screenThinning.start,0,1,bt.screenThinning.intensity),ms=$c(.001,bt.screenThinning.range,0,1,bt.screenThinning.intensity),Gs=$c(0,bt.screenThinning.particleOffset,0,1,bt.screenThinning.intensity),Ms=(Js={modelview:ye.modelviewMatrix,projection:ye.projectionMatrix,time:this._accumulatedTimeFromStart,camPos:St,velocityConeAperture:bt.velocityConeAperture,velocity:bt.velocity,horizontalOscillationRadius:bt.horizontalOscillationRadius,horizontalOscillationRate:bt.horizontalOscillationRate,boxSize:mt,billboardSize:1*bt.billboardSize,simpleShapeParameters:[bt.shapeFadeStart,bt.shapeFadePower],screenSize:[Ke.width,Ke.height],thinningCenterPos:[Pt,Gt],thinningShape:[as,ms,Math.pow(10,bt.screenThinning.fadePower)],thinningAffectedRatio:bt.screenThinning.affectedRatio,thinningParticleOffset:Gs,color:[bt.color.r,bt.color.g,bt.color.b,bt.color.a],direction:W},{u_modelview:Float32Array.from(Js.modelview),u_projection:Float32Array.from(Js.projection),u_time:Js.time,u_cam_pos:Js.camPos,u_velocityConeAperture:Js.velocityConeAperture,u_velocity:Js.velocity,u_horizontalOscillationRadius:Js.horizontalOscillationRadius,u_horizontalOscillationRate:Js.horizontalOscillationRate,u_boxSize:Js.boxSize,u_billboardSize:Js.billboardSize,u_simpleShapeParameters:Js.simpleShapeParameters,u_screenSize:Js.screenSize,u_thinningCenterPos:Js.thinningCenterPos,u_thinningShape:Js.thinningShape,u_thinningAffectedRatio:Js.thinningAffectedRatio,u_thinningParticleOffset:Js.thinningParticleOffset,u_particleColor:Js.color,u_direction:Js.direction});var Js;const Os=Math.round(bt.intensity*this.particlesCount),Ks=o.ac.simpleSegment(0,0,4*Os,2*Os);this.particlesVx&&this.particlesIdx&&Ze.draw(L,Pe.TRIANGLES,o.Z.disabled,o._.disabled,o.a1.alphaBlended,o.$.disabled,Ms,"snow_particles",this.particlesVx,this.particlesIdx,Ks)})(E.boxSize,0,E),this._vignette.draw(L,Z)}},shaders:td,programUniforms:Ku,drawElevatedStructures:function(L){const{painter:N,sourceCache:E,layer:z,coords:W,colorMode:Z}=L,ne=N.context.gl,de=L.painter.shadowRenderer,ye=!!de&&de.enabled,Ce=new o.Z(N.context.gl.LEQUAL,o.Z.ReadOnly,N.depthRangeFor3D);let Pe=[0,0,0];if(ye){const Ze=N.style.directionalLight,mt=N.style.ambientLight;Ze&&mt&&(Pe=o.aF(N.style,Ze,mt))}const Ke=Ze=>{for(const mt of W){const vt=E.getTile(mt),bt=vt.getBucket(z);if(!bt)continue;const St=bt.hdExt?bt.hdExt.elevatedStructures:void 0;if(!St)continue;let Pt,Gt;if(Ze?(Pt=St.renderableBridgeSegments,Gt=St.bridgeProgramConfigurations.get(z.id)):(Pt=St.renderableTunnelSegments,Gt=St.tunnelProgramConfigurations.get(z.id)),!Pt||Pt.segments[0].primitiveLength===0)continue;Gt.updatePaintBuffers(),N.prepareDrawTile();const as=N.isTileAffectedByFog(mt),ms=[];ye&&ms.push("RENDER_SHADOWS","NORMAL_OFFSET");const Gs=N.getOrCreateProgram("elevatedStructures",{config:Gt,overrideFog:as,defines:ms}),Ms=N.translatePosMatrix(mt.projMatrix,vt,z.paint.get("fill-translate"),z.paint.get("fill-translate-anchor"));ye&&de.setupShadows(vt.tileID.toUnwrapped(),Gs,"vector-tile");const Js=lu(Ms,Pe);N.uploadCommonUniforms(N.context,Gs,mt.toUnwrapped()),Gs.draw(N,ne.TRIANGLES,Ce,o._.disabled,Z,o.$.backCCW,Js,z.id,St.vertexBuffer,St.indexBuffer,Pt,z.paint,N.transform.zoom,Gt,[St.vertexBufferNormal])}};Ke(!0),Ke(!1)},drawElevatedFillShadows:function(L){const{painter:N,sourceCache:E,layer:z,coords:W}=L,Z=N.context.gl,ne=L.painter.shadowRenderer;for(const de of W){const ye=E.getTile(de),Ce=ye.getBucket(z);if(!Ce)continue;const Pe=Ce.hdExt?Ce.hdExt.elevatedStructures:void 0;if(!Pe||!Pe.shadowCasterSegments||Pe.shadowCasterSegments.segments[0].primitiveLength===0)continue;N.prepareDrawTile();const Ke=Ce.bufferData.programConfigurations.get(z.id),Ze=N.isTileAffectedByFog(de),mt=N.getOrCreateProgram("elevatedStructuresDepth",{config:Ke,overrideFog:Ze}),vt=ne.calculateShadowPassMatrixFromTile(ye.tileID.toUnwrapped());N.uploadCommonUniforms(N.context,mt,de.toUnwrapped());const bt=Wm(vt,0);mt.draw(N,Z.TRIANGLES,ne.getShadowPassDepthMode(),o._.disabled,o.a1.disabled,o.$.disabled,bt,z.id,Pe.vertexBuffer,Pe.indexBuffer,Pe.shadowCasterSegments,z.paint,N.transform.zoom,Ke)}},drawDepthPrepass:function(L,N,E,z,W){if(!N||!E.layout||E.layout.get("fill-elevation-reference")==="none"||E.paint.get("fill-opacity").constantOr(1)===0)return;const Z=L.context.gl,ne=new o.Z(L.context.gl.LEQUAL,o.Z.ReadWrite,L.depthRangeFor3D),de=new o.Z(L.context.gl.GREATER,o.Z.ReadWrite,L.depthRangeFor3D),ye=function(mt){let vt=.01;return mt.isOrthographic&&(vt=o.al(1e-4,vt,o.bo(mt.pitch>=o.bn?1:mt.pitch/o.bn))),2*vt}(L.transform),Ce=L.transform.getFreeCameraOptions().position,Pe="elevatedStructuresDepthReconstruct",Ke=L.getOrCreateProgram(Pe,{defines:["DEPTH_RECONSTRUCTION"]}),Ze=L.getOrCreateProgram(Pe);for(const mt of z){const vt=N.getTile(mt),bt=vt.getBucket(E);if(!bt||!bt.hdExt)continue;const St=bt.hdExt.elevatedStructures,Pt=bt.hdExt.elevationBufferData;if(!St||!St.depthSegments||!Pt)continue;const Gt=Pt.heightRange,as=gc(mt.toUnwrapped(),Ce),ms=L.translatePosMatrix(mt.projMatrix,vt,E.paint.get("fill-translate"),E.paint.get("fill-translate-anchor"));let Gs,Ms,Js,Os;if(W==="initialize"){if(!Gt||Gt.min>=1||St.depthSegments.segments[0].primitiveLength===0)continue;Gs=rc(ms,as,ye,1,0),Ms=ne,Js=St.depthSegments,Os=Ke}else if(W==="reset"){if(!Gt||Gt.min>=0||St.maskSegments.segments[0].primitiveLength===0)continue;Gs=rc(ms,as,0,0,1),Ms=de,Js=St.maskSegments,Os=Ke}else if(W==="geometry"){if(St.depthSegments.segments[0].primitiveLength===0)continue;Gs=rc(ms,as,ye,1,0),Ms=ne,Js=St.depthSegments,Os=Ze}Os.draw(L,Z.TRIANGLES,Ms,o._.disabled,o.a1.disabled,o.$.disabled,Gs,E.id,St.vertexBuffer,St.indexBuffer,Js,E.paint,L.transform.zoom)}},drawGroundShadowMask:function(L,N,E,z){if(!N||!E.layout||E.layout.get("fill-elevation-reference")==="none"||E.paint.get("fill-opacity").constantOr(1)===0)return;const W=L.context.gl,Z=new o.Z(W.LEQUAL,o.Z.ReadOnly,L.depthRangeFor3D),ne=new o._({func:W.ALWAYS,mask:255},255,255,W.KEEP,W.KEEP,W.REPLACE),de=L.transform.getFreeCameraOptions().position,ye=L.getOrCreateProgram("elevatedStructuresDepthReconstruct");for(const Ce of z){const Pe=N.getTile(Ce),Ke=Pe.getBucket(E);if(!Ke)continue;const Ze=Ke.hdExt?Ke.hdExt.elevatedStructures:void 0;if(!Ze||!Ze.depthSegments||Ze.depthSegments.segments[0].primitiveLength===0)continue;const mt=gc(Ce.toUnwrapped(),de),vt=L.translatePosMatrix(Ce.projMatrix,Pe,E.paint.get("fill-translate"),E.paint.get("fill-translate-anchor")),bt=rc(vt,mt,0,1,0);ye.draw(L,W.TRIANGLES,Z,ne,o.a1.disabled,o.$.disabled,bt,E.id,Ze.vertexBuffer,Ze.indexBuffer,Ze.depthSegments,E.paint,L.transform.zoom)}},IndoorManager:class extends o.E{constructor(L,N=!1){super(),this._style=L,this._buildings={},this._activeFloors=new Set,this._closestBuildingId=null,this._indoorState={selectedFloorId:null,activeFloorsVisible:!0,activeFloors:this._activeFloors},this._buildingDetectionStrategy=new xa,this._initialLoadDone=!1,o.aV(["_updateUI"],this);const E=()=>{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))};N?(this._initialLoadDone=!0,E()):this._style.on("style.load",E)}destroy(){this._buildings={},this._activeFloors=new Set,this._indoorState=null}selectFloor(L){L===this._selectedFloorId&&this._indoorState&&this._indoorState.activeFloorsVisible||(this._selectedFloorId=L,this._recalculateActiveFloors())}setActiveFloorsVisibility(L){this._updateActiveFloors(L),this._updateIndoorSelector()}setIndoorData(L){let N=!1;for(const[E,z]of Object.entries(L.buildings))if(this._buildings[E])for(const W of z.floorIds)this._buildings[E].floorIds.add(W),this._buildings[E].floors[W]?this._mergeFloors(this._buildings[E].floors[W],z.floors[W]):(this._buildings[E].floors[W]=z.floors[W],N=!0);else this._buildings[E]=z,N=!0;N&&this._recalculateActiveFloors()}getIndoorTileOptions(L,N){return this._indoorState?{sourceLayers:this._style.getIndoorSourceLayers(L,N),indoorState:this._indoorState}:null}getControlState(){const L=this._buildings,N=this._closestBuildingId,E=N&&L?L[N]:void 0;if(!E)return{selectedFloorId:null,activeFloorsVisible:!!this._indoorState&&this._indoorState.activeFloorsVisible,floors:[]};let z=null;for(const Z of E.floorIds)if(this._activeFloors&&this._activeFloors.has(Z)){z=Z;break}const W=Array.from(E.floorIds).map(Z=>({id:Z,name:E.floors[Z].name,zIndex:E.floors[Z].zIndex})).sort((Z,ne)=>ne.zIndex-Z.zIndex).filter((Z,ne,de)=>ne===0||Z.zIndex!==de[ne-1].zIndex);return{selectedFloorId:z,activeFloorsVisible:!!this._indoorState&&this._indoorState.activeFloorsVisible,floors:W}}_updateUI(){this._initialLoadDone=!0;const L=this._style.map.transform,N=this._buildingDetectionStrategy.findClosestBuilding(this._buildings,L.center,L.zoom,L.getBounds(),this._makeViewportPolygon());if(N!==this._closestBuildingId){const E=this._closestBuildingId;this._closestBuildingId=N,this._onBuildingTransition(E,N),this._updateIndoorSelector()}}_onBuildingTransition(L,N){if(!this._indoorState)return;!N&&L?(this._indoorState.activeFloors=new Set,this._indoorState.activeFloorsVisible=!1,this._style.updateIndoorDependentLayers()):!!N&&!L&&(this._recalculateActiveFloors(),this._updateActiveFloors(!0))}_updateIndoorSelector(){this.fire(new o.h("selector-update",this.getControlState()))}_updateActiveFloors(L){this._indoorState={selectedFloorId:this._selectedFloorId,activeFloorsVisible:L,activeFloors:this._activeFloors},this._initialLoadDone?this._style.updateIndoorDependentLayers():this._indoorState.needsUpdate=!0}_recalculateActiveFloors(){if(!this._buildings)return;const L=o.aW.calculate(this._buildings,this._selectedFloorId,this._activeFloors);(function(N,E){if(N===E)return!0;if(!N||!E||N.size!==E.size)return!1;for(const z of N)if(!E.has(z))return!1;return!0})(L,this._activeFloors)||(this._activeFloors=L,this._updateActiveFloors(!!this._indoorState&&this._indoorState.activeFloorsVisible),this._updateIndoorSelector())}_mergeFloors(L,N){N.geometry&&(L.geometry?(L.geometry.type==="Polygon"&&(L.geometry={type:"MultiPolygon",coordinates:[L.geometry.coordinates]}),N.geometry.type==="Polygon"?L.geometry.coordinates.push(N.geometry.coordinates):N.geometry.type==="MultiPolygon"&&L.geometry.coordinates.push(...N.geometry.coordinates)):L.geometry=N.geometry)}_makeViewportPolygon(){const L=this._style.map.transform,N=L.width,E=L.height;return[L.pointLocation(new o.P(0,0)),L.pointLocation(new o.P(N,0)),L.pointLocation(new o.P(N,E)),L.pointLocation(new o.P(0,E))].map(z=>new o.P(z.lng,z.lat))}},HdCoverageState:class{constructor(){this.coverageSourceCaches={},this.manager=new up}},updateFrcCoverage:function(L,N){N.manager.clear();for(const z in L._mergedHdRoadCoverageSourceCaches){const W=L._mergedHdRoadCoverageSourceCaches[z]._tiles;for(const Z in W){const ne=W[Z];if(!ne||!ne.loaded())continue;const de=ne.frcCoveragePolygons;N.manager.addTileCoverage(ne.tileID.canonical,de&&de.length>0?de:[])}}const E=N.manager.updateSnapshotIfNeeded();if(L.map.painter&&(L.map.painter.frcCoverageSnapshot=E.empty()?null:E),!E.empty()){const z=[L._mergedOtherSourceCaches,L._mergedSymbolSourceCaches];for(const W of z)for(const Z in W){const ne=W[Z];for(const de in ne._tiles){const ye=ne._tiles[de];ye&&ye.hasDeferredRoadStructure&&(ye.hasDeferredRoadStructure=!1,ne._reloadTile(+de,"reloading"))}}}},updateHdCoverageSourceCache:function(L,N,E){if(E.type!=="fill"||E.sourceLayer!==o.bU||N.coverageSourceCaches[E.source])return;const z=L.getOwnSource(E.source);if(!z||z.type!=="vector")return;const W=`hd-road-coverage:${E.source}`,Z=o.m(W,L.scope),ne=L._sourceCaches[W]=new uh(Z,z,o.bR.HdRoadCoverage);N.coverageSourceCaches[E.source]=ne,ne.setMaxzoomOverride(14),ne.onAdd(L.map);const de=L._otherSourceCaches[E.source];de&&de._sourceLoaded&&(ne._sourceLoaded=!0)},updateFrcCoverageFadeRange:function(L,N){let E=null,z=null;const W={globals:{zoom:0}};L.forEachFragmentStyle(Z=>{if(E)return;const ne=Z.stylesheet?Z.stylesheet.schema:null;if(!ne||!ne.sdCoverageFadeRange)return;const de=o.m("sdCoverageFadeRange",Z.scope),ye=Z.options?Z.options.get(de):void 0,Ce=ye?ye.value||ye.default:null;if(Ce){const mt=Ce.evaluate(W);Array.isArray(mt)&&mt.length===2&&(mt[0]>0||mt[1]>0)&&(E=[mt[0],mt[1]])}const Pe=o.m("sdCoverageSourceLayers",Z.scope),Ke=Z.options?Z.options.get(Pe):void 0,Ze=Ke?Ke.value||Ke.default:null;if(Ze){const mt=Ze.evaluate(W);Array.isArray(mt)&&mt.length>0&&(z=mt)}else{const mt=L.stylesheet&&L.stylesheet.imports||[];for(const vt of mt)if(vt.id===Z.scope){const bt=vt.config?vt.config.sdCoverageSourceLayers:void 0;Array.isArray(bt)&&bt.length>0&&(z=bt);break}}}),N.frcCoverageFadeRange=E,N.frcCoverageSourceLayers=E!=null?z||["road","structure"]:[]},HdElevationState:Zm,setupAndUpdateElevationCoverage:function(L){if(!function(Z){for(const ne in Z._mergedLayers)if(hp(Z._mergedLayers[ne]))return!0;return!1}(L))return void k1(L);const N=ps(L,L.map&&L.map.transform);L._hdElevation||(L._hdElevation=new Zm);const E=L._hdElevation._terrainActiveLast;if(L._hdElevation._terrainActiveLast=N,E!==void 0&&E!==N&&Wp(L,void 0,!0),N)return void(L.map.painter&&(L.map.painter.elevationCoverageSnapshot=null));if(!Sl(L))return void k1(L);E===void 0&&Wp(L,void 0,!0);const z=L._hdElevation;z._needsCrossSourceElevation=!0,L._crossSourceElevationActive=!0,z._ingestFQIDs=Wl(L);const W=Pf(L);L.forEachFragmentStyle(Z=>{for(const ne of W){if(!kh(ne,Z.scope))continue;const de=o.bV(ne);if(Z._otherSourceCaches[de]||Z._symbolSourceCaches[de])continue;const ye=Z.getOwnSource(de);ye&&ye.type==="vector"&&(Z._hdElevation||(Z._hdElevation=new Zm),Ib(Z,Z._hdElevation,ye))}}),L.mergeSources(),_v(L,z)},updateElevationCoverage:_v,updateHdElevationSourceCache:Ib,markElevationIngestSourceCachesUsed:function(L){if(!L._hdElevation||!L._hdElevation._needsCrossSourceElevation)return;const N=L._hdElevation._ingestFQIDs;if(N)for(const E of N){const z=nd(L,E);z&&(z.used=!0)}},updateCrossSourceElevationGate:function(L){L._crossSourceElevationActive=Sl(L);const N=L._mergedHdRoadElevationSourceCaches;N&&Object.keys(N).length!==0&&(L._hdElevation||(L._hdElevation=new Zm),L._hdElevation._needsCrossSourceElevation=L._crossSourceElevationActive)},buildElevationRequestParams:function(L,N,E){if(N.renderSourceType===o.bR.HdRoadElevation||ps(L.style,L.transform)||!E)return null;const z=L.painter?L.painter.elevationCoverageSnapshot:null,W=!(!L.painter||!L.painter.elevationProvidersReady);return z?function(Z,ne,de){const ye=Z.getTilesIntersecting(ne);if(ye.length===0)return{registry:[],hasCoveringTile:!1,allProvidersReady:de};const Ce=[];for(const Pe of ye)for(const Ke of Pe.features)Ce.push({tileId:Pe.tileId,feature:Ke});return Ce.sort((Pe,Ke)=>Pe.feature.id-Ke.feature.id),{registry:Ce,hasCoveringTile:!0,allProvidersReady:de}}(z,N.tileID.canonical,W):{registry:[],hasCoveringTile:!1,allProvidersReady:W}},FrcCoverageRenderer:class{constructor(){this.tileBuffers=new Map,this._context=null}update(L,N){this._context=L;const E=new Set;for(const z of N){if(z.frcMask===0)continue;let W=!1;for(const ne of z.polygons)if(ne.hasGeometry()){W=!0;break}if(!W)continue;const Z=`${z.tileId.z}/${z.tileId.x}/${z.tileId.y}`;if(E.add(Z),!this.tileBuffers.has(Z)){const ne=this._createBuffers(L,z);ne&&this.tileBuffers.set(Z,ne)}}for(const z of this.tileBuffers.keys())if(!E.has(z)){const W=this.tileBuffers.get(z);W.vertexBuffer.destroy(),W.indexBuffer.destroy();for(const Z of W.frcLevelSegments)Z&&Z.destroy();this.tileBuffers.delete(z)}}getBuffers(L){return this.tileBuffers.get(`${L.z}/${L.x}/${L.y}`)||null}destroy(){for(const L of this.tileBuffers.values()){L.vertexBuffer.destroy(),L.indexBuffer.destroy();for(const N of L.frcLevelSegments)N&&N.destroy()}this.tileBuffers.clear()}_createBuffers(L,N){const E=new o.bC,z=new o.ad,W=[];for(const ne of N.polygons){if(!ne.hasGeometry()||ne.rings.length===0)continue;const de=E.length,ye=z.length,Ce=E.length,Pe=[],Ke=[];let Ze=0;for(let vt=0;vt0&&Ke.push(Ze);for(const St of bt)E.emplaceBack(St.x,St.y),Pe.push(St.x,St.y),Ze++}}const mt=o.bF(Pe,Ke.length>0?Ke:void 0);for(let vt=0;vt0&&L.program.draw(N,L.drawMode,L.depthMode,L.stencilMode,L.colorMode,o.$.disabled,L.uniformValues,L.layer.id,L.bufferData.layoutVertexBuffer,L.indexBuffer,ye.frcNonRoadSegments,L.layer.paint,Ze,L.programConfiguration,L.dynamicBuffers),"drawn"}return"fallthrough"},drawFillFrcCoverageSecondPass:function(L,N,E,z,W){if(E.length===0)return;const Z=Iu(L),ne=L.transform.zoom,de=(ye,Ce,Pe)=>{Pe!==1&&(ye.uniformValues.u_opacity_multiplier=Pe),ye.program.draw(L,z,ye.depthMode,Ce,W,o.$.disabled,ye.uniformValues,N.id,ye.bufferData.layoutVertexBuffer,ye.indexBuffer,ye.segments,N.paint,ne,ye.programConfiguration,ye.dynamicBuffers),Pe!==1&&(ye.uniformValues.u_opacity_multiplier=1)};Xm(L,E,Z,(ye,Ce,Pe)=>de(ye,Pe,1),(ye,Ce,Pe)=>de(ye,Pe,Z))},drawLineFrcCoverageDetect:function(L,N,E,z,W,Z,ne,de,ye,Ce){const Pe=N.hdExt&&N.hdExt.frcData;if(!Pe||Pe.frcPerLevel.size===0||!L.frcCoverageSnapshot||z)return null;const Ke=L.frcCoverageSnapshot.getTileOrParent(E.canonical);if(!Ke||Ke.frcMask===0)return null;const Ze=If(Ke.polygons),mt=L.frcCoverageFadeRange,vt=mt!=null&&L.transform.zoom>=mt[0];if(Ze&&vt){let bt=!1;for(const St of Pe.frcPerLevel.keys())if(Ke.frcMask&1<0&&z(E,ne)},drawLineFrcFadePass:function(L,N,E,z,W,Z,ne){if(z.hasPolygonGeometry)return;const de=N.hdExt&&N.hdExt.frcData;if(!de||!L.frcCoverageFadeRange)return;const[ye,Ce]=L.frcCoverageFadeRange;if(ye>=Ce)return;const Pe=1-Math.max(0,Math.min(1,(L.transform.zoom-ye)/(Ce-ye)));if(Pe<=0)return;const Ke=W?Z:L.stencilModeForClipping(E),Ze=z.frcMask;for(const[mt,vt]of de.frcPerLevel)Ze&1<{const Ke=de.bucket.hdExt&&de.bucket.hdExt.frcData,Ze=Ke&&Ke.frcPerLevel.get(ye);Ze&&Ze.segments.length!==0&&(Pe!==1&&(de.uniformValues.u_opacity_multiplier=Pe),de.program.draw(L,z.TRIANGLES,de.depthMode,Ce,de.colorMode,o.$.disabled,de.uniformValues,N.id,de.bucket.layoutVertexBuffer,de.bucket.indexBuffer,Ze,N.paint,Z,de.programConfiguration,[de.bucket.layoutVertexBuffer2,de.bucket.patternVertexBuffer,de.bucket.zOffsetVertexBuffer,de.bucket.elevationIdColVertexBuffer,de.bucket.elevationGroundScaleVertexBuffer]),Pe!==1&&(de.uniformValues.u_opacity_multiplier=1))};Xm(L,E,W,(de,ye,Ce)=>ne(de,ye,Ce,1),(de,ye,Ce)=>ne(de,ye,Ce,W))}},wi=E0;async function Lf(){return Promise.resolve()}class wv{constructor(N,E,z){this.screenBounds=N,this.cameraPoint=z.getCameraPoint(),this._screenRaycastCache={},this._cameraRaycastCache={},this.isAboveHorizon=E,this.screenGeometry=this.bufferedScreenGeometry(0),this.screenGeometryMercator=this._bufferedScreenMercator(0,z)}static createFromScreenPoints(N,E){let z,W;if(N instanceof o.P||typeof N[0]=="number"){const Z=o.P.convert(N);z=[Z],W=E.isPointAboveHorizon(Z)}else{const Z=o.P.convert(N[0]),ne=o.P.convert(N[1]),de=Z.add(ne)._div(2);z=[Z,ne],W=o.bZ(Z,ne).every(ye=>E.isPointAboveHorizon(ye))&&E.isPointAboveHorizon(de)}return new wv(z,W,E)}isPointQuery(){return this.screenBounds.length===1}bufferedScreenGeometry(N){return o.bZ(this.screenBounds[0],this.screenBounds.length===1?this.screenBounds[0]:this.screenBounds[1],N)}bufferedCameraGeometry(N){const E=this.screenBounds[0],z=this.screenBounds.length===1?this.screenBounds[0].add(new o.P(1,1)):this.screenBounds[1],W=o.bZ(E,z,0,!1);return this.cameraPoint.y>z.y&&(this.cameraPoint.x>E.x&&this.cameraPoint.x=z.x?W[2]=this.cameraPoint:this.cameraPoint.x<=E.x&&(W[3]=this.cameraPoint)),o.b_(W,N)}bufferedCameraGeometryGlobe(N){const E=this.screenBounds[0],z=this.screenBounds.length===1?this.screenBounds[0].add(new o.P(1,1)):this.screenBounds[1],W=o.bZ(E,z,N),Z=this.cameraPoint.clone(),ne=+(Z.x>E.x)+ +(Z.x>z.x);switch(3*(+(Z.y>E.y)+ +(Z.y>z.y))+ne){case 0:W[0]=Z,W[4]=Z.clone();break;case 1:W.splice(1,0,Z);break;case 2:W[1]=Z;break;case 3:W.splice(4,0,Z);break;case 5:W.splice(2,0,Z);break;case 6:W[3]=Z;break;case 7:W.splice(3,0,Z);break;case 8:W[2]=Z}return W}containsTile(N,E,z,W=0,Z){const ne=Math.max(N.queryPadding,N.evaluateQueryRenderedFeaturePadding())/E._pixelsPerMercatorPixel+1,de=z?this._bufferedCameraMercator(ne,E):this._bufferedScreenMercator(ne,E);let ye=N.tileID.wrap+(de.unwrapped?W:0);const Ce=de.polygon.map(St=>o.b$(N.tileTransform,St,ye));if(!o.c0(Ce,0,0,o.a2,o.a2))return;ye=N.tileID.wrap+(this.screenGeometryMercator.unwrapped?W:0);const Pe=this.screenGeometryMercator.polygon.map(St=>o.c1(N.tileTransform,St,ye)),Ke=Pe.map(St=>new o.P(St[0],St[1])),Ze=o.c1(N.tileTransform,Z,ye),mt=Pe.map(St=>{const Pt=o.c2(St,St,Ze);return o.c3(Pt,Pt),new o.c4(Ze,Pt)}),vt=o.c5(N,1,E.zoom)*E._pixelsPerMercatorPixel;return{queryGeometry:this,tilespaceGeometry:Ke,tilespaceRays:mt,bufferedTilespaceGeometry:Ce,bufferedTilespaceBounds:(bt=o.c6(Ce),bt.min.x=o.b0(bt.min.x,0,o.a2),bt.min.y=o.b0(bt.min.y,0,o.a2),bt.max.x=o.b0(bt.max.x,0,o.a2),bt.max.y=o.b0(bt.max.y,0,o.a2),bt),tile:N,tileID:N.tileID,pixelToTileUnitsFactor:vt};var bt}_bufferedScreenMercator(N,E){const z=Nv(N);if(this._screenRaycastCache[z])return this._screenRaycastCache[z];{let W;return W=E.projection.name==="globe"?this._projectAndResample(this.bufferedScreenGeometry(N),E):{polygon:this.bufferedScreenGeometry(N).map(Z=>E.pointCoordinate3D(Z)),unwrapped:!0},this._screenRaycastCache[z]=W,W}}_bufferedCameraMercator(N,E){const z=Nv(N);if(this._cameraRaycastCache[z])return this._cameraRaycastCache[z];{let W;return W=E.projection.name==="globe"?this._projectAndResample(this.bufferedCameraGeometryGlobe(N),E):{polygon:this.bufferedCameraGeometry(N).map(Z=>E.pointCoordinate3D(Z)),unwrapped:!0},this._cameraRaycastCache[z]=W,W}}_projectAndResample(N,E){const z=function(Z,ne){const de=o.X([],ne.pixelMatrix,ne.globeMatrix),ye=[0,-o.c8,0,1],Ce=[0,o.c8,0,1],Pe=[0,0,0,1];o.c7(ye,ye,de),o.c7(Ce,Ce,de),o.c7(Pe,Pe,de);const Ke=new o.P(ye[0]/ye[3],ye[1]/ye[3]),Ze=new o.P(Ce[0]/Ce[3],Ce[1]/Ce[3]),mt=o.c9(Z,Ke)&&ye[3]1?jv(Z.slice(0,St),ne):[],as=Stnew o.P(Ry(Os.x),Os.y)),as=as.map(Os=>new o.P(Ry(Os.x),Os.y));const ms=[...Gt];ms.length===0&&ms.push(as.at(-1));const Gs=ms.at(-1),Ms=o.al(Gs.y,(as.length===0?Gt[0]:as[0]).y,Pt);let Js;return Js=mt?[new o.P(0,Ms),new o.P(0,0),new o.P(1,0),new o.P(1,Ms)]:[new o.P(1,Ms),new o.P(1,1),new o.P(0,1),new o.P(0,Ms)],ms.push(...Js),as.length===0?ms.push(Gt[0]):ms.push(...as),{polygon:ms.map(Os=>new o.bS(Os.x,Os.y)),unwrapped:!1}}(N,E);if(z)return z;const W=function(Z,ne){let de=!1,ye=-1/0,Ce=0;for(let Ke=0;Keye&&(ye=Z[Ke].x,Ce=Ke);for(let Ke=0;Ke.5&&(mt.x{Ke.x-=1}),{polygon:Z,unwrapped:de}}(jv(N,E).map(Z=>new o.P(Ry(Z.x),Z.y)),E);return{polygon:W.polygon.map(Z=>new o.bS(Z.x,Z.y)),unwrapped:W.unwrapped}}}function jv(L,N){return o.ca(L,E=>{const z=N.pointCoordinate3D(E);E.x=z.x,E.y=z.y},1/256)}function Ry(L){return L<0?1+L%1:L%1}function Nv(L){return 100*L|0}class T0 extends o.E{constructor(N,E,z,W){if(super(),this.id=N,this.dispatcher=z,this.type="vector",this.provider=E.provider,this.minzoom=0,this.maxzoom=22,this.scheme="xyz",this.tileSize=512,this.reparseOverscaled=!0,this.isTileClipped=!0,this._loaded=!1,Object.assign(this,o.cb(E,["url","scheme","tileSize","promoteId"])),this._options={type:"vector",...E},this._collectResourceTiming=!!E.collectResourceTiming,this.tileSize!==512)throw new Error("vector tile sources must have a tileSize of 512");this.setEventedParent(W),this._tileWorkers={},this._deduped=new o.cc}load(N){this._loaded=!1,this.fire(new o.h("dataloading",{dataType:"source"}));const E=Array.isArray(this.map._language)?this.map._language.join():this.map._language,z=this.map.getWorldview(),W=(ne,de)=>{this._tileJSONRequest=null,this._loaded=!0,ne?(E&&console.warn(`Ensure that your requested language string is a valid BCP-47 code or list of codes. Found: ${E}`),z&&console.warn(`Requested worldview strings must be a valid ISO alpha-2 code. Found: ${z}`),this.fire(new o.f(ne))):de&&(this._setTileJSON(de),wi.updateCrossSourceElevationGate&&this.map.style&&wi.updateCrossSourceElevationGate(this.map.style),o.ck(de.tiles,this.map._requestManager._customAccessToken),this.fire(new o.h("data",{dataType:"source",sourceDataType:"metadata"})),this.fire(new o.h("data",{dataType:"source",sourceDataType:"content"}))),N&&N(ne)};this.provider=this._options.provider;const Z=o.cd(this._options);return Z instanceof Error?(this._loaded=!0,this.fire(new o.f(Z)),void(N&&N())):this.provider&&!Z?(this._loaded=!0,this.fire(new o.f(new Error(`TileProvider "${this.provider}" is not registered`))),void(N&&N())):void(this._tileJSONRequest=Z?this.loadTileJSONWithProvider(Z,W):o.ce(this._options,this.map._requestManager,E,z,W))}loadTileJSONWithProvider(N,E){this.provider=N.name;const z=new AbortController;return(async()=>{const{request:W,options:Z}=await o.cl(this._options,this.map._requestManager,z.signal);if(z.signal.aborted)return;const ne=await this.dispatcher.send("loadTileProvider",{name:N.name,url:N.url,source:this.id,scope:this.scope,type:this.type,options:Z,request:W},{signal:z.signal});if(z.signal.aborted)return;const de=ne?ne.find(Ce=>Ce!=null):null,ye=o.cm(this._options,de,this.map._requestManager);ye instanceof Error?E(ye):E(null,ye)})().catch(W=>{z.signal.aborted||E(W)}),{cancel:()=>z.abort()}}_setTileJSON(N){if(Object.assign(this,N),this.hasWorldviews=!!N.worldview_options,N.worldview_default&&(this.worldviewDefault=N.worldview_default),N.vector_layers){this.vectorLayers=N.vector_layers,this.vectorLayerIds=[],this.localizableLayerIds=new Set;for(const E of N.vector_layers)this.vectorLayerIds.push(E.id),N.worldview&&N.worldview[E.source]&&this.localizableLayerIds.add(E.id)}this.tileBounds=o.cf.fromTileJSON(N)}loaded(){return this._loaded}hasTile(N){return!this.tileBounds||this.tileBounds.contains(N.canonical)}onAdd(N){this.map=N,this.load()}reload(){this.cancelTileJSONRequest();const N=o.m(this.id,this.scope);this.load(()=>this.map.style.clearSource(N))}setTiles(N){return this._options.tiles=N,this.reload(),this}setUrl(N){return this.url=N,this._options.url=N,this.reload(),this}onRemove(N){this.cancelTileJSONRequest()}serialize(){return{...this._options}}async loadTile(N,E){const z=N.tileID.canonical.url(this.tiles,this.scheme),W=this.map._requestManager.normalizeTileURL(z),Z=!N.actor||N.state==="expired";if(!Z&&N.state==="loading")return void(N.reloadCallback=E);Z&&(N.actor=this._tileWorkers[W]=this._tileWorkers[W]||this.dispatcher.getActor());const ne=new AbortController;N.request=ne;try{const de=await this.map._requestManager.transformRequest(W,o.R.Tile,ne.signal);if(ne.signal.aborted)return E(null);this.dispatchTile(N,W,z,de,ne,Z,E)}catch(de){if(ne.signal.aborted)return E(null);E(de)}}dispatchTile(N,E,z,W,Z,ne,de){const ye=this.map.style?this.map.style.getLut(this.scope):null,Ce=ye?{image:ye.image.clone()}:null,Pe=!(!this.map.style||!this.map.style._crossSourceElevationActive),Ke=!(!this.map.style||!Pe),Ze={request:W,data:void 0,uid:N.uid,tileID:N.tileID,tileZoom:N.tileZoom,zoom:N.tileID.overscaledZ,maxZoom:this.maxzoom,lut:Ce,tileSize:this.tileSize*N.tileID.overscaleFactor(),type:this.type,source:this.id,scope:this.scope,pixelRatio:o.e.devicePixelRatio,showCollisionBoxes:this.map.showCollisionBoxes,showElevationIdDebug:!!this.map.painter&&this.map.painter._debugParams.showElevationIdDebug,promoteId:this.promoteId,renderSourceType:N.renderSourceType,frcCoverage:(()=>{const vt=this.map.painter,bt=vt?vt.frcCoverageFadeRange:null;if(bt==null)return null;const St=vt?vt.frcCoverageSnapshot:null,Pt=this.map.transform.zoom=Math.ceil(bt[1]),ms=St&&as?St.getFullCoverageMask(N.tileID.canonical):null;return{frcMask:as?ms??null:null,resolved:Pt||St!=null,polygons:Gt&&Gt.frcMask!==0?Gt.polygons:null,tileZoom:Gt&&Gt.frcMask!==0?Gt.tileId.z:null,sourceLayers:vt?vt.frcCoverageSourceLayers:["road","structure"]}})(),terrainEnabled:ps(this.map.style,this.map.transform),crossSourceElevationEnabled:Ke,elevation:wi.buildElevationRequestParams?wi.buildElevationRequestParams(this.map,N,Pe):null,brightness:this.map.style&&this.map.style.getBrightness()||0,extraShadowCaster:N.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.cg(z)&&(Ze.localizableLayerIds=this.localizableLayerIds),Ze.request.collectResourceTiming=this._collectResourceTiming,ne)if(this.dispatcher.ready||this.provider)N.request=N.actor.sendCancelable("loadTile",Ze,{},mt.bind(this));else{const vt=o.ch.call({deduped:this._deduped},Ze,(bt,St)=>{N.aborted||(bt||!St?mt.call(this,bt):(Ze.data={rawData:St.rawData.slice(0),headers:St.headers},N.actor&&(N.request=N.actor.sendCancelable("loadTile",Ze,{},mt.bind(this)))))},!0);Z.signal.addEventListener("abort",vt,{once:!0})}else N.request=N.actor.sendCancelable("reloadTile",Ze,{},mt.bind(this));function mt(vt,bt){return delete N.request,N.aborted?de(null):vt?de(vt):(bt&&bt.resourceTiming&&(N.resourceTiming=bt.resourceTiming),this.map._refreshExpiredTiles&&bt&&N.setExpiryData(o.ci(bt.headers)),void(function(){if(N.aborted)return de(null);N.loadVectorData(bt,this.map.painter),o.cj(this.dispatcher),de(null,bt),N.reloadCallback&&(this.loadTile(N,N.reloadCallback),N.reloadCallback=null)}).call(this))}}abortTile(N){N.request&&(N.request.abort(),delete N.request),N.actor&&N.actor.notify("abortTile",{uid:N.uid,type:this.type,source:this.id,scope:this.scope})}unloadTile(N,E){N.actor&&N.actor.notify("removeTile",{uid:N.uid,type:this.type,source:this.id,scope:this.scope}),N.destroy()}hasTransition(){return!1}afterUpdate(){this._tileWorkers={}}cancelTileJSONRequest(){this._tileJSONRequest&&(this._tileJSONRequest.cancel(),this._tileJSONRequest=null)}}class Nj extends o.E{constructor(N,E,z,W){super(),this.id=N,this.dispatcher=z,this.setEventedParent(W),this.type="raster",this.minzoom=0,this.maxzoom=22,this.roundZoom=!0,this.scheme="xyz",this.tileSize=512,this._loaded=!1,this._options={type:"raster",...E},Object.assign(this,o.cb(E,["url","scheme","tileSize"]))}load(N){this._loaded=!1,this.fire(new o.h("dataloading",{dataType:"source"}));const E=this.map.getWorldview(),z=(Z,ne)=>{this._tileJSONRequest=null,this._loaded=!0,Z?this.fire(new o.f(Z)):ne&&(Object.assign(this,ne),ne.raster_layers&&(this.rasterLayers=ne.raster_layers,this.rasterLayerIds=this.rasterLayers.map(de=>de.id)),this.tileBounds=o.cf.fromTileJSON(ne),o.ck(ne.tiles),this.fire(new o.h("data",{dataType:"source",sourceDataType:"metadata"})),this.fire(new o.h("data",{dataType:"source",sourceDataType:"content"}))),N&&N(Z)};this.provider=typeof this._options.provider=="string"?this._options.provider:void 0,this._tileProvider=void 0;const W=o.cd(this._options);return W instanceof Error?(this._loaded=!0,this.fire(new o.f(W)),void(N&&N())):this.provider&&!W?(this._loaded=!0,this.fire(new o.f(new Error(`TileProvider "${this.provider}" is not registered`))),void(N&&N())):void(this._tileJSONRequest=W?this.loadTileJSONWithProvider(W,z):o.ce(this._options,this.map._requestManager,null,E,z))}loadTileJSONWithProvider(N,E){this.provider=N.name;const z=new AbortController;return(async()=>{const{request:W,options:Z}=await o.cl(this._options,this.map._requestManager,z.signal);if(z.signal.aborted)return;const ne=await o.cn(N.name,N.url);if(z.signal.aborted)return;const de=new ne(Z);let ye=null;if(de.load&&W&&(ye=await de.load({request:W}),z.signal.aborted))return;this._tileProvider=de;const Ce=o.cm(this._options,ye,this.map._requestManager);Ce instanceof Error?E(Ce):E(null,Ce)})().catch(W=>{z.signal.aborted||E(new Error(`Could not load tile provider ${N.name}`,{cause:W}))}),{cancel:()=>z.abort()}}loaded(){return this._loaded}onAdd(N){this.map=N,this.load()}reload(){this.cancelTileJSONRequest();const N=o.m(this.id,this.scope);this.load(()=>this.map.style.clearSource(N))}setTiles(N){return this._options.tiles=N,this.reload(),this}setUrl(N){return this.url=N,this._options.url=N,this.reload(),this}onRemove(N){this.cancelTileJSONRequest()}serialize(){return{...this._options}}hasTile(N){return!this.tileBounds||this.tileBounds.contains(N.canonical)}async loadTile(N,E){const z=o.e.devicePixelRatio>=2,W=this.map._requestManager.normalizeTileURL(N.tileID.canonical.url(this.tiles,this.scheme),z,this.tileSize),Z=new AbortController;if(N.request=Z,this._tileProvider)this.loadTileWithProvider(N,this._tileProvider,W,Z,E);else try{const ne=await this.map._requestManager.transformRequest(W,o.R.Tile,Z.signal);if(Z.signal.aborted)return delete N.request,E(null);const{data:de,headers:ye}=await o.a(ne,Z.signal);if(delete N.request,N.aborted)return E(null);const Ce=o.ci(ye);this.map._refreshExpiredTiles&&N.setExpiryData(Ce),N.setTexture(de,this.map.painter),N.state="loaded",o.cj(this.dispatcher),E(null)}catch(ne){if(delete N.request,Z.signal.aborted)return E(null);N.state="errored",E(ne)}}async loadTileWithProvider(N,E,z,W,Z){const{z:ne,x:de,y:ye}=N.tileID.canonical;try{const Ce=await this.map._requestManager.transformRequest(z,o.R.Tile,W.signal);if(W.signal.aborted)return Z(null);const Pe=await E.loadTile({z:ne,x:de,y:ye},{request:Ce,signal:W.signal});if(W.signal.aborted)return Z(null);if(Pe==null){const Ze=new Error("Tile not found");return Ze.status=404,N.state="errored",Z(Ze)}if(Pe.data==null)return N.state="loaded",Z(null);const Ke=Pe.data instanceof ImageBitmap?Pe.data:await createImageBitmap(new Blob([Pe.data]));if(W.signal.aborted)return Z(null);N.setTexture(Ke,this.map.painter),N.state="loaded",this.map._refreshExpiredTiles&&N.setExpiryData({cacheControl:Pe.cacheControl,expires:Pe.expires}),Z(null)}catch(Ce){if(W.signal.aborted)return Z(null);N.state="errored",Z(new Error(`Could not load tile from ${z}`,{cause:Ce}))}finally{delete N.request}}abortTile(N,E){N.request&&(N.request.abort(),delete N.request),E&&E()}unloadTile(N,E){N.texture&&N.texture instanceof o.T?(N.destroy(!1),N.texture&&N.texture instanceof o.T&&this.map.painter.saveTileTexture(N.texture)):N.destroy(),E&&E()}hasTransition(){return!1}cancelTileJSONRequest(){this._tileJSONRequest&&(this._tileJSONRequest.cancel(),this._tileJSONRequest=null)}}function Ok(L,N,E,z,W,Z,ne,de){const ye=[L,N,1,E,z,1,W,Z,1],Ce=[ne,de,1],Pe=o.cu([],ye),[Ke,Ze,mt]=o.ct(Ce,Ce,Pe);return o.cv(ye,ye,[Ke,0,0,0,Ze,0,0,0,mt])}function Dy(L,N,E,z,W,Z,ne,de){const ye=function(Ce,Pe,Ke,Ze,mt,vt,bt,St){const Pt=Ok(0,0,1,0,1,1,0,1),Gt=Ok(Ce,Pe,Ke,Ze,mt,vt,bt,St),as=o.cu([],Pt);return o.cv(Gt,Gt,as)}(L,N,E,z,W,Z,ne,de);return[ye[2]/ye[8]/o.a2,ye[5]/ye[8]/o.a2]}function Fk(L){return[L[0],Math.min(Math.max(L[1],-o.cp),o.cp)]}class fx extends o.E{constructor(N,E,z,W){super(),this.id=N,this.dispatcher=z,this.coordinates=E.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(W),this.options=E,this._dirty=!1}async load(N,E){if(this._loaded=E||!1,this.fire(new o.h("dataloading",{dataType:"source"})),this.url=this.options.url,!this.url)return N&&(this.coordinates=N),this._loaded=!0,void this._finishLoading();const z=new AbortController;this._imageRequest=z;try{const W=await this.map._requestManager.transformRequest(this.url,o.R.Image,z.signal),{data:Z}=await o.a(W,z.signal);this._imageRequest=null,this._loaded=!0,this.image=Z,this._dirty=!0,this.width=this.image.width,this.height=this.image.height,N&&(this.coordinates=N),this._finishLoading()}catch(W){if(z.signal.aborted)return;this._imageRequest=null,this._loaded=!0,this.fire(new o.f(W))}}loaded(){return this._loaded}updateImage(N){return N.url?(this._imageRequest&&N.url!==this.options.url&&(this._imageRequest.abort(),this._imageRequest=null),this.options.url=N.url,this.load(N.coordinates,this._loaded),this):this}setTexture(N){if(!(N.handle instanceof WebGLTexture))throw new Error("The provided handle is not a WebGLTexture instance");return this.texture=new o.co(this.map.painter.context,N.handle),this.width=N.dimensions[0],this.height=N.dimensions[1],this._dirty=!1,this._loaded=!0,this._finishLoading(),this}_finishLoading(){this.map&&(this.setCoordinates(this.coordinates),this.fire(new o.h("data",{dataType:"source",sourceDataType:"metadata"})))}onAdd(N){this.map=N,this.load()}onRemove(N){this._imageRequest&&(this._imageRequest.abort(),this._imageRequest=null),!this.texture||this.texture instanceof o.co||this.texture.destroy(),this.boundsBuffer&&(this.boundsBuffer.destroy(),this.elevatedGlobeVertexBuffer&&this.elevatedGlobeVertexBuffer.destroy(),this.elevatedGlobeIndexBuffer&&this.elevatedGlobeIndexBuffer.destroy())}setCoordinates(N){if(this.coordinates=N,this._boundsArray=void 0,this._unsupportedCoords=!1,!N.length)return this;this.onNorthPole=!1,this.onSouthPole=!1;let E=N[0][1],z=N[0][1];for(const Z of N)Z[1]>z&&(z=Z[1]),Z[1]o.cp?this.onNorthPole=!0:W<-o.cp&&(this.onSouthPole=!0),!this.onNorthPole&&!this.onSouthPole){const Z=N.map(o.bS.fromLngLat);this.tileID=function(ne){let de=1/0,ye=1/0,Ce=-1/0,Pe=-1/0;for(const bt of ne)de=Math.min(de,bt.x),ye=Math.min(ye,bt.y),Ce=Math.max(Ce,bt.x),Pe=Math.max(Pe,bt.y);const Ke=Math.max(Ce-de,Pe-ye),Ze=Math.max(0,Math.floor(-Math.log2(Ke))),mt=Math.pow(2,Ze);let vt=Math.floor((de+Ce)/2*mt);return vt>1&&(vt-=1),new o.bX(Ze,vt,Math.floor((ye+Pe)/2*mt))}(Z),this.minzoom=this.maxzoom=this.tileID.z}return this.fire(new o.h("data",{dataType:"source",sourceDataType:"content"})),this}_clear(){!this.texture||this.texture instanceof o.co||(this.texture.destroy(),this._dirty=!0),this.texture=null,this._boundsArray=void 0,this._unsupportedCoords=!1}_prepareData(N){for(const Gs in this.tiles){const Ms=this.tiles[Gs];Ms.state!=="loaded"&&(Ms.state="loaded",Ms.texture=this.texture)}if(this._boundsArray||this.onNorthPole||this.onSouthPole||this._unsupportedCoords)return;const E=o.bp(new o.bX(0,0,0),this.map.transform.projection),z=[E.projection.project(this.coordinates[0][0],this.coordinates[0][1]),E.projection.project(this.coordinates[1][0],this.coordinates[1][1]),E.projection.project(this.coordinates[2][0],this.coordinates[2][1]),E.projection.project(this.coordinates[3][0],this.coordinates[3][1])];if(!function(Gs){const Ms=Gs[1].x-Gs[0].x,Js=Gs[1].y-Gs[0].y,Os=Gs[2].x-Gs[1].x,Ks=Gs[2].y-Gs[1].y,_n=Gs[3].x-Gs[2].x,ln=Gs[3].y-Gs[2].y,an=Gs[0].x-Gs[3].x,bn=Gs[0].y-Gs[3].y,Sn=Ms*Ks-Os*Js,lr=Os*ln-_n*Ks,Mn=_n*bn-an*ln,Hn=an*Js-Ms*bn;return Sn>0&&lr>0&&Mn>0&&Hn>0||Sn<0&&lr<0&&Mn<0&&Hn<0}(z))return console.warn("Image source coordinates are defining non-convex area in the Mercator projection"),void(this._unsupportedCoords=!0);const W=o.bp(this.tileID,this.map.transform.projection),[Z,ne,de,ye]=this.coordinates.map(Gs=>{const Ms=W.projection.project(Gs[0],Gs[1]);return o.b$(W,Ms)._round()});this.perspectiveTransform=Dy(Z.x,Z.y,ne.x,ne.y,de.x,de.y,ye.x,ye.y);const Ce=this._boundsArray=new o.bs;Ce.emplaceBack(Z.x,Z.y,0,0),Ce.emplaceBack(ne.x,ne.y,o.a2,0),Ce.emplaceBack(ye.x,ye.y,0,o.a2),Ce.emplaceBack(de.x,de.y,o.a2,o.a2),this.boundsBuffer&&(this.boundsBuffer.destroy(),this.elevatedGlobeVertexBuffer&&this.elevatedGlobeVertexBuffer.destroy(),this.elevatedGlobeIndexBuffer&&this.elevatedGlobeIndexBuffer.destroy()),this.boundsBuffer=N.createVertexBuffer(Ce,Ig.members),this.boundsSegments=o.ac.simpleSegment(0,0,4,2);const Pe=o.cs,Ke=Pe+1,Ze=Pe+1,mt=Ke*Ze,vt=Pe*Pe*2,bt=[],St=function(Gs){return[Fk(Gs[0]),Fk(Gs[1]),Fk(Gs[2]),Fk(Gs[3])]}(this.coordinates),[Pt,Gt,as,ms]=function(Gs){let Ms=Gs[0][0],Js=Ms,Os=Gs[0][1],Ks=Os;for(let _n=1;_nJs&&(Js=Gs[_n][0]),Gs[_n][1]Ks&&(Ks=Gs[_n][1]);return[Ms,Os,Js-Ms,Ks-Os]}(St);{const Gs=new o.bs,[Ms,Js,Os,Ks]=function(Lr){let qa=Lr[0].x,Nr=qa,cr=Lr[0].y,Fr=cr;for(let Fa=1;FaNr&&(Nr=Lr[Fa].x),Lr[Fa].yFr&&(Fr=Lr[Fa].y);return[qa,cr,Nr-qa,Fr-cr]}(z),_n=Lr=>[(Lr.x-Ms)/Os,(Lr.y-Js)/Ks],[ln,an,bn,Sn]=z.map(_n),lr=function(Lr,qa,Nr,cr,Fr,Fa,ta,Ta){const ci=Ok(0,0,1,0,1,1,0,1),uo=Ok(Lr,qa,Nr,cr,Fr,Fa,ta,Ta),ao=o.cu([],uo);return o.cv(ci,ci,ao)}(ln[0],ln[1],an[0],an[1],bn[0],bn[1],Sn[0],Sn[1]);this.elevatedGlobePerspectiveTransform=Dy(ln[0],ln[1],an[0],an[1],bn[0],bn[1],Sn[0],Sn[1]);const Mn=(Lr,qa)=>{bt.push(Lr.lng);const Nr=Math.round((Lr.lng-Pt)/as*o.a2),cr=Math.round((Lr.lat-Gt)/ms*o.a2),Fr=_n(qa),Fa=o.ct([],[Fr[0],Fr[1],1],lr),ta=Math.round(Fa[0]/Fa[2]*o.a2),Ta=Math.round(Fa[1]/Fa[2]*o.a2);Gs.emplaceBack(Nr,cr,ta,Ta)},Hn=z[3].x-z[0].x,Tr=z[3].y-z[0].y,oa=z[2].x-z[1].x,Qr=z[2].y-z[1].y;for(let Lr=0;Lr{Ms.emplaceBack(Os,Ks,_n);const ln=bt[Os],an=bt[Ks],bn=bt[_n],Sn=Math.min(Math.min(ln,an),bn),lr=Math.max(Math.max(ln,an),bn)-Sn;lr>this.maxLongitudeTriangleSize&&(this.maxLongitudeTriangleSize=lr),Gs.push(Sn+lr/2)};for(let Os=0;OsSn);_n.sort((bn,Sn)=>Os[bn]-Os[Sn]);const ln=[],an=new o.ad;for(let bn=0;bn<_n.length;bn++){const Sn=_n[bn];ln.push(Os[Sn]);const lr=3*Sn,Mn=lr+1;an.emplaceBack(Ks.uint16[lr],Ks.uint16[Mn],Ks.uint16[Mn+1])}return[ln,an]}(Gs,Ms),this.elevatedGlobeTrianglesCenterLongitudes=Gs,this.elevatedGlobeIndexBuffer=N.createIndexBuffer(Ms)}this.elevatedGlobeSegments=o.ac.simpleSegment(0,0,mt,vt),this.elevatedGlobeGridMatrix=new Float32Array([0,as/o.a2,0,ms/o.a2,0,0,Gt,Pt,0])}prepare(){const N=Object.keys(this.tiles).length!==0;if(this.tileID&&!N)return;const E=this.map.painter.context,z=E.gl;!this._dirty||this.texture instanceof o.co||(this.texture?this.texture.update(this.image):(this.texture=new o.T(E,this.image,z.RGBA8),this.texture.bind(z.LINEAR,z.CLAMP_TO_EDGE)),this._dirty=!1),N&&this._prepareData(E)}loadTile(N,E){this.tileID&&this.tileID.equals(N.tileID.canonical)?(this.tiles[String(N.tileID.wrap)]=N,N.buckets={},E(null)):(N.state="errored",E(null))}serialize(){return{type:"image",url:this.options.url,coordinates:this.coordinates}}hasTransition(){return!1}getSegmentsForLongitude(N){const E=this.elevatedGlobeSegments;if(!this.elevatedGlobeTrianglesCenterLongitudes||!E)return null;const z=this.elevatedGlobeTrianglesCenterLongitudes;let W=(Z=N+180)+360*Math.round((z[0]-Z)/360);var Z;const ne=new o.ac,de=(Ke,Ze)=>{ne.segments.push({vertexOffset:0,primitiveOffset:Ke,vertexLength:E.segments[0].vertexLength,primitiveLength:Ze,sortKey:void 0,vaos:{}})},ye=.51*this.maxLongitudeTriangleSize;if(Math.abs(z[0]-W)<=ye){const Ke=o.cq(z,0,z.length,W+ye);return Ke===z.length||de(Ke,o.cr(z,Ke+1,z.length,W+360-ye)-Ke),ne}W{const{request:z,options:W}=await o.cl(this._options,this.map._requestManager,E.signal);if(E.signal.aborted)return;const Z=await this.dispatcher.send("loadTileProvider",{name:L.name,url:L.url,source:this.id,scope:this.scope,type:this.type,options:W,request:z},{signal:E.signal});if(E.signal.aborted)return;const ne=Z?Z.find(ye=>ye!=null):null,de=o.cm(this._options,ne,this.map._requestManager);de instanceof Error?N(de):N(null,de)})().catch(z=>{E.signal.aborted||N(z)}),{cancel:()=>E.abort()}}async loadTile(L,N){if(L.actor&&L.state!=="expired")return;const E=this.map._requestManager.normalizeTileURL(L.tileID.canonical.url(this.tiles,this.scheme),!1,this.tileSize);L.actor=this.dispatcher.getActor();const z=new AbortController;L.request=z;try{const W=await this.map._requestManager.transformRequest(E,o.R.Tile,z.signal);if(z.signal.aborted)return N(null);L.request=L.actor.sendCancelable("loadTile",{uid:L.uid,tileID:L.tileID,source:this.id,type:this.type,scope:this.scope,request:W,encoding:this.encoding},{},(function(Z,ne){return delete L.request,L.aborted?N(null):Z?(L.state="errored",N(Z)):(ne&&(this.map._refreshExpiredTiles&&L.setExpiryData(o.ci(ne.headers)),ne.borderReady||L.neighboringTiles||(L.neighboringTiles=this._getNeighboringTiles(L.tileID)),L.dem=ne.dem,L.dem.onDeserialize(),L.needsHillshadePrepare=!0,L.needsDEMTextureUpload=!0),L.state="loaded",void N(null))}).bind(this))}catch(W){if(z.signal.aborted)return N(null);L.state="errored",N(W)}}abortTile(L,N){L.request&&(L.request.abort(),delete L.request),L.actor&&L.actor.notify("abortTile",{uid:L.uid,type:this.type,source:this.id,scope:this.scope}),N&&N()}_getNeighboringTiles(L){const N=L.canonical,E=Math.pow(2,N.z),z=(N.x-1+E)%E,W=N.x===0?L.wrap-1:L.wrap,Z=(N.x+1+E)%E,ne=N.x+1===E?L.wrap+1:L.wrap,de={};return de[new o.bP(L.overscaledZ,W,N.z,z,N.y).key]={backfilled:!1},de[new o.bP(L.overscaledZ,ne,N.z,Z,N.y).key]={backfilled:!1},N.y>0&&(de[new o.bP(L.overscaledZ,W,N.z,z,N.y-1).key]={backfilled:!1},de[new o.bP(L.overscaledZ,L.wrap,N.z,N.x,N.y-1).key]={backfilled:!1},de[new o.bP(L.overscaledZ,ne,N.z,Z,N.y-1).key]={backfilled:!1}),N.y+1N(null,E)).catch(E=>N(E)),this}getClusterChildren(L,N){return this.actor.send("geojson.getClusterChildren",{clusterId:L,source:this.id,scope:this.scope}).then(E=>N(null,E)).catch(E=>N(E)),this}getClusterLeaves(L,N,E,z){return this.actor.send("geojson.getClusterLeaves",{source:this.id,scope:this.scope,clusterId:L,limit:N,offset:E}).then(W=>z(null,W)).catch(W=>z(W)),this}async _updateWorkerData(L=!1){if(this._pendingLoad)return void(this._coalesce=!0);this.fire(new o.h("dataloading",{dataType:"source"})),this._loaded=!1;const N={append:L,...this.workerOptions};N.scope=this.scope;const E=this._data,z=new AbortController;this._pendingLoad=z;try{if(typeof E=="string"){if(N.request=await this.map._requestManager.transformRequest(o.e.resolveURL(E),o.R.Source,z.signal),z.signal.aborted)return this._pendingLoad=null,void(this._coalesce=!1);N.request.collectResourceTiming=this._collectResourceTiming}else N.data=JSON.stringify(E);const W=await this.actor.send(`${this.type}.loadData`,N,{signal:z.signal});this._loaded=!0,this._pendingLoad=null;const Z={dataType:"source",sourceDataType:this._metadataFired?"content":"metadata"};this._collectResourceTiming&&W&&W.resourceTiming&&W.resourceTiming[this.id]&&(Z.resourceTiming=W.resourceTiming[this.id]),L&&(this._partialReload=!0),this.fire(new o.h("data",Z)),this._partialReload=!1,this._metadataFired=!0}catch(W){if(z.signal.aborted)return this._pendingLoad=null,void(this._coalesce=!1);this._loaded=!0,this._pendingLoad=null,this.fire(new o.f(W))}this._coalesce&&(this._updateWorkerData(L),this._coalesce=!1)}loaded(){return this._loaded}reload(){const L=o.m(this.id,this.scope);this.map.style.clearSource(L),this._updateWorkerData()}loadTile(L,N){const E=L.actor?"reloadTile":"loadTile";L.actor=this.actor;const z=this.map.style?this.map.style.getLut(this.scope):null,W=z?{image:z.image.clone()}:null,Z=this._partialReload,ne={type:this.type,uid:L.uid,tileID:L.tileID,tileZoom:L.tileZoom,zoom:L.tileID.overscaledZ,maxZoom:this.maxzoom,tileSize:this.tileSize,source:this.id,lut:W,scope:this.scope,pixelRatio:o.e.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:L.isExtraShadowCaster,scaleFactor:this.map.getScaleFactor(),partial:Z,worldview:this.map.getWorldview(),indoor:this.map.getIndoorTileOptions(this.id,this.scope)};L.request=this.actor.sendCancelable(E,ne,{},(de,ye)=>Z&&!ye?(L.state="loaded",N(null)):(delete L.request,L.destroy(!1),L.aborted?N(null):de?N(de):(L.loadVectorData(ye,this.map.painter,E==="reloadTile"),void N(null))))}abortTile(L){L.request&&(L.request.abort(),delete L.request),L.aborted=!0}unloadTile(L,N){this.actor.notify("removeTile",{uid:L.uid,type:this.type,source:this.id,scope:this.scope}),L.destroy()}onRemove(L){this._pendingLoad&&this._pendingLoad.abort()}serialize(){return{...this._options,type:this.type,data:this._data}}hasTransition(){return!1}},video:class extends fx{constructor(L,N,E,z){super(L,N,E,z),this.roundZoom=!0,this.type="video",this.options=N}async load(){this._loaded=!1;const L=this.options,N=new AbortController;this._imageRequest=N;try{const E=await Promise.all(L.urls.map(async W=>(await this.map._requestManager.transformRequest(W,o.R.Source,N.signal)).url));if(N.signal.aborted)return;this.urls=E;const z=await o.cw(E);if(N.signal.aborted)return;this._imageRequest=null,this.video=z,this.video.loop=!0,this.video.setAttribute("playsinline",""),this.video.addEventListener("playing",()=>{this.map.triggerRepaint()}),this.map&&this.video.play(),this._finishLoading()}catch(E){if(N.signal.aborted)return;this.fire(new o.f(E))}finally{this._loaded=!0}}pause(){this.video&&this.video.pause()}play(){this.video&&this.video.play()}seek(L){if(this.video){const N=this.video.seekable;LN.end(0)?this.fire(new o.f(new jt(`sources.${this.id}`,null,`Playback for this video can be set only between the ${N.start(0)} and ${N.end(0)}-second mark.`))):this.video.currentTime=L}}getVideo(){return this.video}onAdd(L){this.map||(this.map=L,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 L=this.map.painter.context,N=L.gl;this.texture?this.video.paused||(this.texture.bind(N.LINEAR,N.CLAMP_TO_EDGE),N.texSubImage2D(N.TEXTURE_2D,0,0,0,N.RGBA,N.UNSIGNED_BYTE,this.video)):(this.texture=new o.T(L,this.video,N.RGBA8),this.texture.bind(N.LINEAR,N.CLAMP_TO_EDGE),this.width=this.video.videoWidth,this.height=this.video.videoHeight),this._prepareData(L)}serialize(){return{type:"video",urls:this.options.urls,coordinates:this.coordinates}}hasTransition(){return this.video&&!this.video.paused}},image:fx,canvas:class extends fx{constructor(L,N,E,z){super(L,N,E,z),N.coordinates?Array.isArray(N.coordinates)&&N.coordinates.length===4&&!N.coordinates.some(W=>!Array.isArray(W)||W.length!==2||W.some(Z=>typeof Z!="number"))||this.fire(new o.f(new jt(`sources.${L}`,null,'"coordinates" property must be an array of 4 longitude/latitude array pairs'))):this.fire(new o.f(new jt(`sources.${L}`,null,'missing required property "coordinates"'))),N.animate&&typeof N.animate!="boolean"&&this.fire(new o.f(new jt(`sources.${L}`,null,'optional "animate" property must be a boolean value'))),N.canvas?typeof N.canvas=="string"||N.canvas instanceof HTMLCanvasElement||this.fire(new o.f(new jt(`sources.${L}`,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.f(new jt(`sources.${L}`,null,'missing required property "canvas"'))),this.options=N,this.animate=N.animate===void 0||N.animate}async 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.f(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(L){this.map=L,this.load(),this.canvas&&this.animate&&this.play()}onRemove(L){this.pause()}prepare(){let L=!1;if(this.canvas.width!==this.width&&(this.width=this.canvas.width,L=!0),this.canvas.height!==this.height&&(this.height=this.canvas.height,L=!0),this._hasInvalidDimensions()||Object.keys(this.tiles).length===0)return;const N=this.map.painter.context;this.texture?!L&&!this._playing||this.texture instanceof o.co||this.texture.update(this.canvas,{premultiply:!0}):this.texture=new o.T(N,this.canvas,N.gl.RGBA8,{premultiply:!0}),this._prepareData(N)}serialize(){return{type:"canvas",coordinates:this.coordinates}}hasTransition(){return this._playing}_hasInvalidDimensions(){for(const L of[this.canvas.width,this.canvas.height])if(isNaN(L)||L<=0)return!0;return!1}},custom:class extends o.E{constructor(L,N,E,z){super(),this.id=L,this.type="custom",this._dataType="raster",this._dispatcher=E,this._implementation=N,this.setEventedParent(z),this.scheme="xyz",this.minzoom=0,this.maxzoom=22,this.tileSize=512,this._loaded=!1,this.roundZoom=!0,this._implementation||this.fire(new o.f(new Error(`Missing implementation for ${this.id} custom source`))),this._implementation.loadTile||this.fire(new o.f(new Error(`Missing loadTile implementation for ${this.id} custom source`))),this._implementation.bounds&&(this.tileBounds=new o.cf(this._implementation.bounds,this.minzoom,this.maxzoom));const W=N;W.update=this._update.bind(this),W.clearTiles=this._clearTiles.bind(this),W.coveringTiles=this._coveringTiles.bind(this),Object.assign(this,o.cb(N,["dataType","scheme","minzoom","maxzoom","tileSize","attribution","minTileCacheSize","maxTileCacheSize"]))}serialize(){return o.cb(this,["type","scheme","minzoom","maxzoom","tileSize","attribution"])}load(){this._loaded=!0,this.fire(new o.h("data",{dataType:"source",sourceDataType:"metadata"})),this.fire(new o.h("data",{dataType:"source",sourceDataType:"content"}))}loaded(){return this._loaded}onAdd(L){this.map=L,this._loaded=!1,this.fire(new o.h("dataloading",{dataType:"source"})),this._implementation.onAdd&&this._implementation.onAdd(L),this.load()}onRemove(L){this._implementation.onRemove&&this._implementation.onRemove(L)}hasTile(L){if(this._implementation.hasTile){const{x:N,y:E,z}=L.canonical;return this._implementation.hasTile({x:N,y:E,z})}return!this.tileBounds||this.tileBounds.contains(L.canonical)}async loadTile(L,N){const{x:E,y:z,z:W}=L.tileID.canonical,Z=new AbortController;L.request=Z;try{const ne=await this._implementation.loadTile({x:E,y:z,z:W},{signal:Z.signal});if(delete L.request,L.aborted)return L.state="unloaded",N(null);if(ne===void 0)return L.state="errored",N(null);if(ne===null)return this.loadTileData(L,{width:this.tileSize,height:this.tileSize,data:null}),L.state="loaded",N(null);if(!function(de){return de instanceof ImageData||de instanceof HTMLCanvasElement||de instanceof ImageBitmap||de instanceof HTMLImageElement}(ne))return L.state="errored",N(new Error(`Can't infer data type for ${this.id}, only raster data supported at the moment`));this.loadTileData(L,ne),L.state="loaded",N(null)}catch(ne){if(Z.signal.aborted)return;L.state="errored",N(ne)}}loadTileData(L,N){L.setTexture(N,this.map.painter)}unloadTile(L,N){if(L.texture&&L.texture instanceof o.T?(L.destroy(!1),L.texture&&L.texture instanceof o.T&&this.map.painter.saveTileTexture(L.texture)):L.destroy(),this._implementation.unloadTile){const{x:E,y:z,z:W}=L.tileID.canonical;this._implementation.unloadTile({x:E,y:z,z:W})}N&&N()}abortTile(L,N){L.request&&(L.request.abort(),delete L.request),N&&N()}hasTransition(){return!1}_coveringTiles(){return this.map.transform.coveringTiles({tileSize:this.tileSize,minzoom:this.minzoom,maxzoom:this.maxzoom,roundZoom:this.roundZoom}).map(L=>({x:L.canonical.x,y:L.canonical.y,z:L.canonical.z}))}_clearTiles(){const L=o.m(this.id,this.scope);this.map.style.clearSource(L)}_update(){this.fire(new o.h("data",{dataType:"source",sourceDataType:"content"}))}}},Z2=function(L,N,E,z){const W=C1(N.type);if(!W)throw new Error(`Unknown source type "${N.type}"`);const Z=new W(L,N,E,z);if(Z.id!==L)throw new Error(`Expected Source id to be ${L} instead of ${Z.id}`);return o.aV(["load","abort","unload","serialize","prepare"],Z),Z},C1=function(L){return Object.hasOwn(Rf,L)?Rf[L]:void 0};function Qm([L,N],E,z,{scaled:W=!0}={}){const{tileSize:Z,buffer:ne}=z,{x:de,y:ye,z:Ce}=E;if(!isFinite(de)||!isFinite(ye)||!isFinite(Ce))throw new Error("Invalid MRT header");const Pe=2**Ce,Ke=Pe*o.a7(L),Ze=Pe*o.a8(N);return function([mt,vt],bt,{scaled:St=!0}={}){if(!bt)throw new Error("bandView is undefined");const{data:Pt,tileSize:Gt,buffer:as,offset:ms,scale:Gs,dimension:Ms}=bt;if(mt<-as||mt>Gt+as||vt<-as||vt>Gt+as)throw new Error(`Point (${mt}, ${vt}) out of bounds for tileSize=${Gt}, buffer=${as}`);const Js=(vt+as)*(Gt+2*as)+(mt+as);if(new Uint32Array(Pt.buffer)[Js]===4294967295)return null;let Os=[];Os=St?[]:new bt.data.constructor(Ms);for(let Ks=0;Ks{try{const ye=z.getHeaderLength(ne);if(ye>N)return void(this.request=this.fetchHeader(ye,E));z.parseHeader(ne),this._isHeaderLoaded=!0;let Ce=0;for(const Pe of Object.values(z.layers))Ce=Math.max(Ce,Pe.dataIndex.at(-1).lastByte);ne.byteLength>=Ce&&(this.entireBuffer=ne),E(null,this.entireBuffer||ne,de)}catch(ye){E(ye)}}).catch(ne=>{Z.signal.aborted||E(ne)}),this.request}fetchBandForRender(N,E,z,W){this.fetchBand(N,E,z,Z=>{if(Z)return void W(Z);this.updateTextureDescriptor(N,E,z);const ne=this.textureDescriptorPerLayer.get(E);W(null,ne?ne.img:null)})}fetchBand(N,E,z,W){const Z=this._mrt;if(!this._isHeaderLoaded||!Z)return void W(new Error("Tile header is not ready"));const ne=this.actor;if(!ne)return void W(new Error("Can't fetch tile band without an actor"));let de;const ye=o.m(String(z),o.m(this.tileID.key,N));let Ce=this._taskQueue.get(ye);Ce?Ce.add(W):(Ce=new Set,Ce.add(W),this._taskQueue.set(ye,Ce));const Pe=(vt,bt)=>{de.complete(vt,bt),vt?W(vt):(Ce.forEach(St=>St(null,bt)),this._taskQueue.delete(ye))},Ke=(vt,bt)=>{if(vt)return W(vt);let St,Pt=!1;if(E!==null){const as=this._workQueuePerLayer.get(E)||[];as.push(()=>{Pt=!0,St&&St.abort(),de.cancel()}),this._workQueuePerLayer.has(E)||this._workQueuePerLayer.set(E,as)}const Gt=()=>{Pt||(St=ne.sendCancelable("decodeRasterArray",{type:"raster-array",source:this.source,scope:this.scope,tileID:this.tileID,uid:this.uid,buffer:bt,task:de},{},Pe))};this.workerReady!==void 0?this.workerReady.then(Gt).catch(as=>W(as)):Gt()};let Ze;try{Ze=Z.getLayer(N)}catch(vt){if(this.state==="reloading")return;throw vt}if(!Ze)return void W(new Error(`Unknown sourceLayer "${N}"`));if(Ze.hasDataForBand(z))return Ce.forEach(vt=>vt(null,null)),void this._taskQueue.delete(ye);const mt=Ze.getDataRange([z]);if(de=Z.createDecodingTask(mt),!de||de.tasks.length)if(E!==null&&this.flushQueues(E),this.entireBuffer)Ke(null,this.entireBuffer.slice(mt.firstByte,mt.lastByte+1));else{const vt={...this.requestParams,headers:{Range:`bytes=${mt.firstByte}-${mt.lastByte}`}},bt=new AbortController;if(o.cC(vt,bt.signal).then(({data:St})=>Ke(null,St)).catch(St=>{bt.signal.aborted||Ke(St)}),E!==null){const St=this._fetchQueuePerLayer.get(E)||[];St.push(()=>{bt.abort(),de.cancel()}),this._fetchQueuePerLayer.has(E)||this._fetchQueuePerLayer.set(E,St)}}}updateNeeded(N,E){return(!this.textureDescriptorPerLayer.get(N)||this.textureDescriptorPerLayer.get(N).band!==E||this.refreshedUponExpiration)&&this.state!=="errored"}updateTextureDescriptor(N,E,z){if(!this._mrt)return;const W=this._mrt.getLayer(N);if(!W||!W.hasBand(z)||!W.hasDataForBand(z))return;const{bytes:Z,tileSize:ne,buffer:de,offset:ye,scale:Ce}=W.getBandView(z),Pe=ne+2*de,Ke=new o.b({width:Pe,height:Pe},Z),Ze=this.texturePerLayer.get(E);Ze&&Ze instanceof o.T&&Ze.update(Ke,{premultiply:!1}),this.textureDescriptorPerLayer.set(E,{layer:N,band:z,img:Ke,buffer:de,offset:ye,tileSize:ne,format:W.pixelFormat,mix:[Ce,256*Ce,65536*Ce,16777216*Ce]})}destroy(N=!1){if(super.destroy(N),delete this._mrt,!N)for(const E of this.texturePerLayer.values())E&&E instanceof o.T&&E.destroy();this.texturePerLayer.clear(),this.textureDescriptorPerLayer.clear(),this.fbo&&(this.fbo.destroy(),delete this.fbo),delete this.request,delete this.requestParams,this._isHeaderLoaded=!1}}Ec=(L,N,E,z,W)=>new mp(L,N,E,z,W);const Jm={RasterArrayTileSource:class extends Nj{get partial(){return!this.map.style.imageManager.hasImageProviderForSource(this.id,this.scope)}constructor(L,N,E,z){super(L,N,E,z),this.type="raster-array",this.maxzoom=22,this._loadTilePending={},this._loadTileLoaded={},this._options={type:"raster-array",...N}}triggerRepaint(L){const N=this.map.painter._terrain,E=this.map.style.getSourceCache(this.id);N&&N.enabled&&E&&N._clearRenderCacheForTile(E.id,L.tileID),this.map.triggerRepaint()}async loadTile(L,N){const E=this.map._requestManager.normalizeTileURL(L.tileID.canonical.url(this.tiles,this.scheme),!1,this.tileSize);L.source=this.id,L.scope=this.scope,this._workerReady===void 0&&(this._workerReady=this.dispatcher.send("ensureRasterArraySource",void 0).then(()=>{}),this._workerReady.catch(()=>{})),L.workerReady=this._workerReady,L.actor||(L.actor=this.dispatcher.getActor());const z=new AbortController;L.request=z;const W=(Z,ne,de)=>{if(delete L.request,L.aborted)return N(null);if(Z)return L.state="errored",N(Z);if(this.map._refreshExpiredTiles&&ne&&L.setExpiryData(o.ci(de)),this.partial&&L.state!=="expired")L.state="empty";else if(!this.partial){if(!ne)return N(null);L.state="loaded",L._isHeaderLoaded=!0,L._mrt=ne}N(null)};try{const Z=await this.map._requestManager.transformRequest(E,o.R.Tile,z.signal);if(z.signal.aborted)return N(null);L.requestParams=Z;const ne={request:Z,uid:L.uid,tileID:L.tileID,type:this.type,source:this.id,scope:this.scope,partial:this.partial};L.request=this.partial?L.fetchHeader(void 0,(de,ye,Ce)=>{W(de,ye,Ce)}):L.actor.sendCancelable("loadTile",ne,{},(de,ye)=>de?W(de):ye?void W(null,ye.mrt,ye.headers):W(null,null))}catch(Z){if(z.signal.aborted)return N(null);L.state="errored",N(Z)}}abortTile(L){L.request&&(L.request.abort(),delete L.request),L.actor&&L.actor.notify("abortTile",{uid:L.uid,type:this.type,source:this.id,scope:this.scope})}unloadTile(L,N){const E=L.texturePerLayer;if(L.flushAllQueues(),E.size){L.destroy(!1);for(const z of E.values())this.map.painter.saveTileTexture(z)}else L.destroy()}prepareTile(L,N,E,z){L._isHeaderLoaded&&(L.state!=="empty"&&(L.state="reloading"),L.fetchBandForRender(N,E,z,(W,Z)=>{W?(L.state="errored",this.fire(new o.f(W))):Z&&(L._isHeaderLoaded=!0,L.setTexturePerLayer(E,Z,this.map.painter),L.state="loaded"),this.triggerRepaint(L)}))}getInitialBand(L){if(!this.rasterLayers)return 0;const N=this.rasterLayers.find(({id:W})=>W===L),E=N&&N.fields,z=E&&E.bands&&E.bands;return z?z[0]:0}getTextureDescriptor(L,N,E){if(!L)return;const z=N.sourceLayer||this.rasterLayerIds&&this.rasterLayerIds[0];if(!z)return;let W=null;N instanceof o.cx?W=N.paint.get("raster-array-band"):N instanceof o.cy&&(W=N.paint.get("raster-particle-array-band"));const Z=W||this.getInitialBand(z);if(Z!=null)if(L.textureDescriptorPerLayer.get(N.id)){if(!L.updateNeeded(N.id,Z)||E)return{...L.textureDescriptorPerLayer.get(N.id),texture:L.texturePerLayer.get(N.id)}}else this.prepareTile(L,z,N.id,Z)}getImages(L,N){const E=new Map;for(const z of L)for(const W of N){const[Z,ne]=W.split("/"),de=z.getLayer(Z);if(!de||!de.hasBand(ne)||!de.hasDataForBand(ne))continue;const{bytes:ye,tileSize:Ce,buffer:Pe}=de.getBandView(ne),Ke=Ce+2*Pe,Ze={data:new o.b({width:Ke,height:Ke},ye),pixelRatio:2,sdf:!1,usvg:!1,version:0};E.set(W,Ze)}return E}queryRasterArrayValueByBandId(L,N,E){const z=N._mrt;return new Promise(W=>{const Z={},ne=new Set;for(const[de,ye]of Object.entries(z.layers)){if(E.layerName&&de!==E.layerName)continue;const Ce={};Z[de]=Ce;for(const{bands:Pe}of ye.dataIndex)for(const Ke of Pe)E.bands&&!E.bands.includes(Ke)||(ne.add(o.m(de,Ke)),N.fetchBand(de,null,Ke,Ze=>{o.e.frame(()=>{Ce[Ke]=Ze?null:Qm([L.lng,L.lat],z,ye.getBandView(Ke)),ne.delete(o.m(de,Ke)),ne.size===0&&W(Z)})}))}ne.size===0&&W(Z)})}_loadTileForQuery(L){if(this._loadTileLoaded[L.uid])return Promise.resolve(L._mrt);if(L.uid in this._loadTilePending)return this._loadTilePending[L.uid];const N=this._fetchTileForQuery(L);return this._loadTilePending[L.uid]=N,N}async _fetchTileForQuery(L){const N=this.map._requestManager.normalizeTileURL(L.tileID.canonical.url(this.tiles,this.scheme),!1,this.tileSize);try{const E={request:await this.map._requestManager.transformRequest(N,o.R.Tile),uid:L.uid,tileID:L.tileID,type:this.type,source:this.id,scope:this.scope,partial:!1},z=await L.actor.send("loadTile",E);if(!z)return null;const W=z.mrt;return this.map._refreshExpiredTiles&&L.setExpiryData(o.ci(z.headers)),L._mrt=W,L._isHeaderLoaded=!0,L.state="loaded",this._loadTileLoaded[L.uid]=!0,W}finally{delete this._loadTilePending[L.uid]}}async queryRasterArrayValueByAllBands(L,N,E){return await this._loadTileForQuery(N)?this.queryRasterArrayValueByBandId(L,N,E):null}queryRasterArrayValue(L,N){const E=o.cz.convert(L),z=this.findLoadedParent(E);return z&&z._mrt?N.bands||!this.partial?this.queryRasterArrayValueByBandId(E,z,N):this.queryRasterArrayValueByAllBands(E,z,N):Promise.resolve(null)}findLoadedParent(L){const N=o.bS.fromLngLat(L,this.map.transform.tileSize),E=this.maxzoom+1,z=1<=z||ne<0||ne>=z)return null;const de=this.map.style.getSourceCache(this.id),ye=new o.bP(E,W,E,Z,ne);return de.findLoadedParent(ye,this.minzoom)}}},hh=Jm,ef={model:()=>Bt().then(()=>Xe.ModelSource),"batched-model":()=>Bt().then(()=>Xe.Tiled3dModelSource),"raster-array":()=>async function(){return Promise.resolve()}().then(()=>hh.RasterArrayTileSource)};class zk extends o.E{constructor(N,E,z,W){super(),this.id=N,this.type=E.type,this._options=E,this.minzoom=0,this.maxzoom=22,this.tileSize=512,this.setEventedParent(W)}hasTransition(){return!1}loaded(){return!1}onAdd(N){}onRemove(N){}loadTile(N,E){}serialize(){return this._options}}function X2(L,N,E=""){return`${E}:${N.id||""}:${N.layer.id}:${function(z){if("layerId"in z)return`layer:${z.layerId}`;{const{featuresetId:W,importId:Z}=z;return`featureset:${W}${Z?`:import:${Z}`:""}`}}(L.target)}`}function g4(L,N,E,z=""){if(L.uniqueFeatureID){const W=X2(L,N,z);if(E.has(W))return!0;E.add(W)}return!1}function x4(L,N,E,z,W=!1,Z=void 0){const ne=N.sourceCache.transform,de=N.sourceCache.tilesIn(L,N.has3DLayers,W);de.sort(Df);const ye=[];for(const Ce of de){const Pe=Ce.tile.queryRenderedFeatures(N,Ce,E,z,ne,W,Z);Object.keys(Pe).length&&ye.push({wrappedTileID:Ce.tile.tileID.wrapped().key,queryResults:Pe})}for(const Ce in N.layers){const Pe=N.layers[Ce];if(Pe.styleLayer){const Ke=Pe.styleLayer.queryRenderedFeatures(L,N.sourceCache,z);Object.keys(Ke).length&&ye.push({wrappedTileID:0,queryResults:Ke})}}return ye.length===0?{}:function(Ce){const Pe={},Ke={};for(const Ze of Ce){const mt=Ze.queryResults,vt=Ze.wrappedTileID,bt=Ke[vt]=Ke[vt]||{};for(const St in mt){const Pt=mt[St],Gt=bt[St]=bt[St]||{},as=Pe[St]=Pe[St]||[];for(const ms of Pt)Gt[ms.featureIndex]||(Gt[ms.featureIndex]=!0,as.push(ms))}}return Pe}(ye)}function fA(L,N,E,z,W,Z){const ne={},de=z.queryRenderedSymbols(L),ye=[];for(const Ce of Object.keys(de).map(Number))ye.push(W[Ce]);ye.sort(Df);for(const Ce of ye){const Pe=Ce.featureIndex.lookupSymbolFeatures(de[Ce.bucketInstanceId],Ce.bucketIndex,Ce.sourceLayerIndex,N,E,Z);for(const Ke in Pe){const Ze=ne[Ke]=ne[Ke]||[],mt=Pe[Ke];mt.sort((vt,bt)=>{const St=Ce.featureSortOrder;if(St){const Pt=St.indexOf(vt.featureIndex);return St.indexOf(bt.featureIndex)-Pt}return bt.featureIndex-vt.featureIndex});for(const vt of mt)Ze.push(vt)}}return ne}function Oy(L,N){const E=L.getRenderableIds().map(Z=>L.getTileByID(Z)),z=[],W={};for(let Z=0;Z0:z.type==="building"?W=!z.isHidden(N)&&z.paint.get("building-opacity")>0:z.type==="model"&&(W=!z.isHidden(N)&&z.paint.get("model-opacity").constantOr(1)>0),this.layersGotHidden=this.layersGotHidden||!W&&E.visible,E.visible=W}}updateZOffset(N,E){this.currentBuildingBuckets=[];for(const W of this.layers){const Z=W.layer,ne=this.style.getLayerSourceCache(Z);let de=1;Z.type==="fill-extrusion"?de=W.visible?Z.paint.get("fill-extrusion-vertical-scale"):0:Z.type==="building"&&(de=W.visible?Z.paint.get("building-vertical-scale"):0);let ye=ne?ne.getTile(E):null;if(!ye&&ne)for(const Ce in ne._tiles){const Pe=ne._tiles[Ce];if(E.canonical.isChildOf(Pe.tileID.canonical)){ye=Pe;break}}this.currentBuildingBuckets.push({bucket:ye?ye.getBucket(Z):null,tileID:ye?ye.tileID:E,verticalScale:de})}N.hasAnyZOffset=!1;let z=!1;for(let W=0;W{ne in W&&(Z[ne]=W[ne])}),E}function fp(L){L=L.slice();const N=Object.create(null);for(const E of L)N[E.id]=E;for(let E=0;Ez.collisionGroupID===E}}return this.collisionGroups[N]}}function A1(L,N,E,z,W){const{horizontalAlign:Z,verticalAlign:ne}=o.cM(L),de=-(Z-.5)*N,ye=-(ne-.5)*E,Ce=o.cN(L,z);return new o.P(de+Ce[0]*W,ye+Ce[1]*W)}function E1(L,N,E,z,W){const Z=new o.P(L,N);return E&&Z._rotate(z?W:-W),Z}function Yp(L,N,E,z){const{leftJustifiedTextSymbolIndex:W,centerJustifiedTextSymbolIndex:Z,rightJustifiedTextSymbolIndex:ne,verticalPlacedTextSymbolIndex:de,crossTileID:ye}=E,Ce=o.cO(N),Pe=z===o.cL.vertical?de:Ce==="left"?W:Ce==="center"?Z:Ce==="right"?ne:-1;W>=0&&(L.text.placedSymbolArray.get(W).crossTileID=Pe>=0&&W!==Pe?0:ye),Z>=0&&(L.text.placedSymbolArray.get(Z).crossTileID=Pe>=0&&Z!==Pe?0:ye),ne>=0&&(L.text.placedSymbolArray.get(ne).crossTileID=Pe>=0&&ne!==Pe?0:ye),de>=0&&(L.text.placedSymbolArray.get(de).crossTileID=Pe>=0&&de!==Pe?0:ye)}function kv(L,N,E){const z=N===o.cL.horizontal||N===o.cL.horizontalOnly?N:0,W=N===o.cL.vertical?N:0,{leftJustifiedTextSymbolIndex:Z,centerJustifiedTextSymbolIndex:ne,rightJustifiedTextSymbolIndex:de,verticalPlacedTextSymbolIndex:ye}=E,Ce=L.text.placedSymbolArray;Z>=0&&(Ce.get(Z).placedOrientation=z),ne>=0&&(Ce.get(ne).placedOrientation=z),de>=0&&(Ce.get(de).placedOrientation=z),ye>=0&&(Ce.get(ye).placedOrientation=W)}class Q2{constructor(N,E,z,W,Z,ne,de,ye){this.transform=N.clone(),this.projection=N.projection.name,this.algorithm=W,this.collisionIndex=this.algorithm.createCollisionDetector(this.transform,ne,ye),this.buildingIndex=de,this.frontCutoffStart=0,this.placements={},this.opacities={},this.variableOffsets={},this.stale=!1,this.commitTime=0,this.fadeDuration=E,this.retainedQueryData={},this.collisionGroups=new qh(z),this.collisionCircleArrays={},this.prevPlacement=Z,Z&&(Z.prevPlacement=void 0),this.placedOrientations={},this.lastReplacementSourceUpdateTime=0}getBucketParts(N,E,z,W,Z=1){const ne=z.getBucket(E),de=z.latestFeatureIndex;if(!ne||!de||E.fqid!==ne.layerIds[0])return;const ye=ne.layers[0].layout,Ce=ne.layers[0].paint,Pe=z.collisionBoxArray,Ke=Math.pow(2,this.transform.zoom-z.tileID.overscaledZ),Ze=z.tileSize/o.a2,mt=z.tileID.toUnwrapped();this.transform.setProjection(ne.projection);const vt=(bt=z.tileID,St=ne.getProjection(),Pt=this.transform,St.name===this.projection?Pt.calculateProjMatrix(bt.toUnwrapped()):Mo(Pt,St,bt));var bt,St,Pt;const Gt=ye.get("text-pitch-alignment")==="map",as=ye.get("text-rotation-alignment")==="map";E.compileFilter(E.options);const ms=E.dynamicFilter(),Gs=E.dynamicFilterNeedsFeature(),Ms=E.dynamicFilterNeedsGeometry(),Js=this.transform.calculatePixelsToTileUnitsMatrix(z),Os=o.cE(vt,z.tileID.canonical,Gt,as,this.transform,ne.getProjection(),Js);let Ks=null;const _n=ne.getProjection().createInversionMatrix(this.transform,z.tileID.canonical);if(Gt){const oa=o.cF(vt,z.tileID.canonical,Gt,as,this.transform,ne.getProjection(),Js);Ks=o.X([],this.transform.labelPlaneMatrix,oa)}let ln=null;ms&&z.latestFeatureIndex&&(ln={unwrappedTileID:mt,dynamicFilter:ms,dynamicFilterNeedsFeature:Gs,needGeometry:Ms}),this.retainedQueryData[ne.bucketInstanceId]=new Cm(ne.bucketInstanceId,de,ne.sourceLayerIndex,ne.index,z.tileID);const[an,bn]=ne.layers[0].layout.get("text-size-scale-range"),Sn=o.b0(Z,an,bn),[lr,Mn]=ye.get("icon-size-scale-range"),Hn=o.b0(Z,lr,Mn),Tr={bucket:ne,layout:ye,paint:Ce,posMatrix:vt,invMatrix:_n,mercatorCenter:[o.a7(this.transform.center.lng),o.a8(this.transform.center.lat)],textLabelPlaneMatrix:Os,labelToScreenMatrix:Ks,clippingData:ln,scale:Ke,textPixelRatio:Ze,holdingForFade:z.holdingForFade(),collisionBoxArray:Pe,partiallyEvaluatedTextSize:o.cG(ne.textSizeData,this.transform.zoom,Sn),partiallyEvaluatedIconSize:o.cG(ne.iconSizeData,this.transform.zoom,Hn),collisionGroup:this.collisionGroups.get(ne.sourceID),latestFeatureIndex:z.latestFeatureIndex};if(W)for(const oa of ne.sortKeyRanges){const{sortKey:Qr,symbolInstanceStart:Lr,symbolInstanceEnd:qa}=oa;N.push({sortKey:Qr,symbolInstanceStart:Lr,symbolInstanceEnd:qa,parameters:Tr})}else N.push({symbolInstanceStart:0,symbolInstanceEnd:ne.symbolInstances.length,parameters:Tr})}placeLayerBucketPart(N,E,z,W=1){this.algorithm.placeLayerBucketPart(this,N,E,z,W)}commit(N){this.commitTime=N,this.zoomAtLastRecencyCheck=this.transform.zoom;const E=this.prevPlacement;let z=!1;this.prevZoomAdjustment=E?E.zoomAdjustment(this.transform.zoom):0;const W=E?E.symbolFadeChange(N):1,Z=E?E.opacities:{},ne=E?E.variableOffsets:{},de=E?E.placedOrientations:{};for(const ye in this.placements){const Ce=this.placements[ye],Pe=Z[ye];Pe?(this.opacities[ye]=new V_(Pe,W,Ce.text,Ce.icon,null,Ce.clipped),z=z||Ce.text!==Pe.text.placed||Ce.icon!==Pe.icon.placed):(this.opacities[ye]=new V_(null,W,Ce.text,Ce.icon,Ce.skipFade,Ce.clipped),z=z||Ce.text||Ce.icon)}for(const ye in Z){const Ce=Z[ye];if(!this.opacities[ye]){const Pe=new V_(Ce,W,!1,!1);Pe.isHidden()||(this.opacities[ye]=Pe,z=z||Ce.text.placed||Ce.icon.placed)}}for(const ye in ne)this.variableOffsets[ye]||!this.opacities[ye]||this.opacities[ye].isHidden()||(this.variableOffsets[ye]=ne[ye]);for(const ye in de)this.placedOrientations[ye]||!this.opacities[ye]||this.opacities[ye].isHidden()||(this.placedOrientations[ye]=de[ye]);z?this.lastPlacementChangeTime=N:typeof this.lastPlacementChangeTime!="number"&&(this.lastPlacementChangeTime=E?E.lastPlacementChangeTime:N)}updateLayerOpacities(N,E,z,W,Z=!1,ne=1){W&&(this.lastReplacementSourceUpdateTime=W.updateTime);const de=new Set;for(const ye of E){const Ce=ye.getBucket(N);if(Ce&&ye.latestFeatureIndex&&N.fqid===Ce.layerIds[0]&&(this.updateBucketOpacities(Ce,de,ye,ye.collisionBoxArray,z,W,ye.tileID,N.scope),Ce.elevationType==="offset"&&this.buildingIndex&&this.buildingIndex.updateZOffset(Ce,ye.tileID),Ce.elevationType==="road"&&Ce.hdExt&&Ce.hdExt.updateRoadElevation(Ce,ye.tileID.canonical),Ce.updateZOffset(),Z&&ye.collisionBoxArray)){const Pe=Ce.layers[0].layout,[Ke,Ze]=Pe.get("text-size-scale-range"),[mt,vt]=Pe.get("icon-size-scale-range"),bt=o.b0(ne,Ke,Ze),St=o.b0(ne,mt,vt);Ce.updateCollisionDebugBuffers(this.transform.zoom,ye.collisionBoxArray,bt,St)}}}updateBucketOpacities(N,E,z,W,Z,ne,de,ye){N.hasTextData()&&N.text.opacityVertexArray.clear(),N.hasIconData()&&N.icon.opacityVertexArray.clear(),N.hasIconCollisionBoxData()&&N.iconCollisionBox.collisionVertexArray.clear(),N.hasTextCollisionBoxData()&&N.textCollisionBox.collisionVertexArray.clear();const Ce=N.layers[0].layout,Pe=N.layers[0].paint,Ke=!!N.layers[0].dynamicFilter(),Ze=new V_(null,0,!1,!1,!0),mt=Ce.get("text-allow-overlap"),vt=Ce.get("icon-allow-overlap"),bt=Ce.get("text-variable-anchor"),St=Ce.get("text-rotation-alignment")==="map",Pt=Ce.get("text-pitch-alignment")==="map",Gt=Pe.get("symbol-z-offset"),as=Ce.get("symbol-elevation-reference")==="sea",ms=!Gt.isConstant(),Gs=new V_(null,0,mt&&(vt||!N.hasIconData()||Ce.get("icon-optional")),vt&&(mt||!N.hasTextData()||Ce.get("text-optional")),!0);!N.collisionArrays&&W&&(N.hasIconCollisionBoxData()||N.hasTextCollisionBoxData())&&N.deserializeCollisionBoxes(W);const Ms=(Os,Ks,_n)=>{for(let ln=0;ln0||ln>0,qa=bn>0,Nr=this.placedOrientations[an],cr=Nr===o.cL.vertical,Fr=Nr===o.cL.horizontal||Nr===o.cL.horizontalOnly;!Lr&&!qa||Qr.isHidden()||Js++;let Fa=!1;if((Lr||qa)&&ne)for(const ta of N.activeReplacements){if(o.cH(ta,Z,o.cI.Symbol,ye)||ta.min.x>Sn||Sn>ta.max.x||ta.min.y>lr||lr>ta.max.y)continue;const Ta=o.cJ(Sn,lr,de.canonical,ta.footprintTileId.canonical);if(Fa=o.cK(Ta,ta.footprint),Fa)break}if(Fa&&this.collisionIndex.markSymbolAsClipped(N.bucketInstanceId,Ks.featureIndex),Lr){const ta=Fa?px:Yx(Qr.text);Ms(N.text,_n,cr?px:ta),Ms(N.text,ln,Fr?px:ta);const Ta=Qr.text.isHidden(),{leftJustifiedTextSymbolIndex:ci,centerJustifiedTextSymbolIndex:uo,rightJustifiedTextSymbolIndex:ao,verticalPlacedTextSymbolIndex:Io}=Ks,qc=N.text.placedSymbolArray,Tc=Ta||cr?1:0;ci>=0&&(qc.get(ci).hidden=Tc),uo>=0&&(qc.get(uo).hidden=Tc),ao>=0&&(qc.get(ao).hidden=Tc),Io>=0&&(qc.get(Io).hidden=Ta||Fr?1:0);const Wo=this.variableOffsets[an];Wo&&Yp(N,Wo.anchor,Ks,Nr);const Va=this.placedOrientations[an];Va&&(Yp(N,"left",Ks,Va),kv(N,Va,Ks))}if(qa){const ta=Fa?px:Yx(Qr.icon),{placedIconSymbolIndex:Ta,verticalPlacedIconSymbolIndex:ci}=Ks,uo=N.icon.placedSymbolArray,ao=Qr.icon.isHidden()?1:0;Ta>=0&&(Ms(N.icon,bn,cr?px:ta),uo.get(Ta).hidden=ao),ci>=0&&(Ms(N.icon,Ks.numVerticalIconVertices,Fr?px:ta),uo.get(ci).hidden=ao)}if(N.hasIconCollisionBoxData()||N.hasTextCollisionBoxData()){const ta=N.collisionArrays[Os];if(ta){let Ta=new o.P(0,0),ci=!0;if(ta.textBox||ta.verticalTextBox){if(bt){const ao=this.variableOffsets[an];ao?(Ta=A1(ao.anchor,ao.width,ao.height,ao.textOffset,ao.textScale),St&&Ta._rotate(Pt?this.transform.angle:-this.transform.angle)):ci=!1}Ke&&(ci=!Qr.clipped),ta.textBox&&H_(N.textCollisionBox.collisionVertexArray,Qr.text.placed,!ci||cr,Tr,as,Ta.x,Ta.y),ta.verticalTextBox&&H_(N.textCollisionBox.collisionVertexArray,Qr.text.placed,!ci||Fr,Tr,as,Ta.x,Ta.y)}const uo=ci&&!!(!Fr&&ta.verticalIconBox);ta.iconBox&&H_(N.iconCollisionBox.collisionVertexArray,Qr.icon.placed,uo,Tr,as,Ks.hasIconTextFit?Ta.x:0,Ks.hasIconTextFit?Ta.y:0),ta.verticalIconBox&&H_(N.iconCollisionBox.collisionVertexArray,Qr.icon.placed,!uo,Tr,as,Ks.hasIconTextFit?Ta.x:0,Ks.hasIconTextFit?Ta.y:0)}}}if(N.fullyClipped=Js===0,N.sortFeatures(this.transform.angle),this.retainedQueryData[N.bucketInstanceId]&&(this.retainedQueryData[N.bucketInstanceId].featureSortOrder=N.featureSortOrder),N.hasTextData()&&N.text.opacityVertexBuffer&&N.text.opacityVertexBuffer.updateData(N.text.opacityVertexArray),N.hasIconData()&&N.icon.opacityVertexBuffer&&N.icon.opacityVertexBuffer.updateData(N.icon.opacityVertexArray),N.hasIconCollisionBoxData()&&N.iconCollisionBox.collisionVertexBuffer&&N.iconCollisionBox.collisionVertexBuffer.updateData(N.iconCollisionBox.collisionVertexArray),N.hasTextCollisionBoxData()&&N.textCollisionBox.collisionVertexBuffer&&N.textCollisionBox.collisionVertexBuffer.updateData(N.textCollisionBox.collisionVertexArray),N.bucketInstanceId in this.collisionCircleArrays){const Os=this.collisionCircleArrays[N.bucketInstanceId];N.placementInvProjMatrix=Os.invProjMatrix,N.placementViewportMatrix=Os.viewportMatrix,N.collisionCircleArray=Os.circles,delete this.collisionCircleArrays[N.bucketInstanceId]}}symbolFadeChange(N){return this.fadeDuration===0?1:(N-this.commitTime)/this.fadeDuration+this.prevZoomAdjustment}zoomAdjustment(N){return Math.max(0,(this.transform.zoom-N)/1.5)}hasTransitions(N){return N-this.lastPlacementChangeTimeN}isStale(){return this.stale}setStale(){this.stale=!0}}function H_(L,N,E,z,W,Z,ne){L.emplaceBack(N?1:0,E?1:0,Z||0,ne||0,z,W?1:0),L.emplaceBack(N?1:0,E?1:0,Z||0,ne||0,z,W?1:0),L.emplaceBack(N?1:0,E?1:0,Z||0,ne||0,z,W?1:0),L.emplaceBack(N?1:0,E?1:0,Z||0,ne||0,z,W?1:0)}const J2=Math.pow(2,25),T1=Math.pow(2,24),kj=Math.pow(2,17),Sj=Math.pow(2,16),$k=Math.pow(2,9),Uk=Math.pow(2,8),eN=Math.pow(2,1);function Yx(L){if(L.opacity===0&&!L.placed)return 0;if(L.opacity===1&&L.placed)return 4294967295;const N=L.placed?1:0,E=Math.floor(127*L.opacity);return E*J2+N*T1+E*kj+N*Sj+E*$k+N*Uk+E*eN+N}const px=0;class G_{constructor(N,E){this.reset(N,E)}reset(N,E){this.points=N||[],this._distances=[0];for(let z=1;z0?(W-ne)/de:0;return this.points[Z].mult(1-ye).add(this.points[E].mult(ye))}}const gx=100;class Sv{constructor(N,E){this.gridRightBoundary=0,this.gridBottomBoundary=0,this.clippedSymbols=new Map,this.reset(N,E)}reset(N,E){const z=N.width+200,W=N.height+200;z!==this.gridRightBoundary||W!==this.gridBottomBoundary?(this.grid=new o.cP(z,W,25),this.ignoredGrid=new o.cP(z,W,25)):(this.grid.clear(),this.ignoredGrid.clear()),this.transform=N,this.fogState=E,this.pitchfactor=Math.cos(N._pitch)*N.cameraToCenterDistance,this.screenRightBoundary=N.width+gx,this.screenBottomBoundary=N.height+gx,this.gridRightBoundary=z,this.gridBottomBoundary=W,this.clippedSymbols.clear()}clearClippedSymbolsForBucket(N){this.clippedSymbols.delete(N)}markSymbolAsClipped(N,E){let z=this.clippedSymbols.get(N);z||(z=new Set,this.clippedSymbols.set(N,z)),z.add(E)}placeCollisionBox(N,E,z,W,Z,ne,de,ye,Ce,Pe,Ke){let Ze=z.projectedAnchorX,mt=z.projectedAnchorY,vt=z.projectedAnchorZ;const bt=z.tileAnchorX,St=z.tileAnchorY,Pt=z.elevation,Gt=z.tileID,as=N.getProjection();if(Pt&&Gt){const[bn,Sn,lr]=as.upVector(Gt.canonical,z.tileAnchorX,z.tileAnchorY),Mn=as.upVectorScale(Gt.canonical,this.transform.center.lat,this.transform.worldSize).metersToTile;Ze+=bn*Pt*Mn,mt+=Sn*Pt*Mn,vt+=lr*Pt*Mn}const ms=N.projection.name==="globe",Gs=N.projection.name==="globe"?o.S(this.transform.zoom):0;if(Gt&&ms&&Gs<1&&!ne){const bn=1<0,as),Js=Ce*Ms.perspectiveRatio,Os=(z.x1*E+de.x-z.padding)*Js+Ms.point.x,Ks=(z.y1*E+de.y-z.padding)*Js+Ms.point.y,_n=(z.x2*E+de.x+z.padding)*Js+Ms.point.x,ln=(z.y2*E+de.y+z.padding)*Js+Ms.point.y,an=Ms.perspectiveRatio<=.55||Ms.occluded;return!this.isInsideGrid(Os,Ks,_n,ln)||!ye&&this.grid.hitTest(Os,Ks,_n,ln,Ke)||an?{box:[],offscreen:!1,occluded:Ms.occluded}:{box:[Os,Ks,_n,ln],offscreen:this.isOffscreen(Os,Ks,_n,ln),occluded:!1}}placeCollisionCircles(N,E,z,W,Z,ne,de,ye,Ce,Pe,Ke,Ze,mt,vt,bt,St){const Pt=[],Gt=this.transform.elevation,as=N.getProjection(),ms=N.elevationType==="road",Gs=!!Gt||ms,Ms=o.cW.getAtTileOffsetFunc(St,this.transform.center.lat,this.transform.worldSize,as),Js=new o.P(z.tileAnchorX,z.tileAnchorY),Os=new o.P(z.tileAnchorX,z.tileAnchorY);let{x:Ks,y:_n,z:ln}=as.projectTilePoint(Os.x,Os.y,St.canonical),an=null;if(Gs){an=ms&&N.hdExt?N.hdExt.makeRoadSymbolElevationParams(N,N.text,W,St,Ms,Gt,as,this.transform.center.lat,this.transform.worldSize):{getElevation:Ms,elevation:Gt,elevationFeature:null};const[Fa,ta,Ta]=an.getElevation(Js,Gt,an.elevationFeature);Ks+=Fa,_n+=ta,ln+=Ta}const bn=as.name==="globe",Sn=this.projectAndGetPerspectiveRatio(ye,Ks,_n,ln,St,bn||!!Gt||this.transform.pitch>0,as),{perspectiveRatio:lr}=Sn,Mn=(Ze?de/lr:de*lr)/o.d1,Hn=o.cX(Ks,_n,ln,Ce),Tr=z.lineOffsetX*Mn,oa=z.lineOffsetY*Mn,Qr=o.au(N.layers[0].layout.get("text-max-angle")),Lr=Math.cos(Qr),qa=Sn.signedDistanceFromCamera>0?o.cY(Mn,ne,Tr,oa,ms&&z.flipState===1,Hn,Os,z,Z,Ce,{},Gs&&!Ze?an:null,Ze&&Gs,as,St,Ze,Lr):null;let Nr=!1,cr=!1,Fr=!0;if(qa&&!Sn.occluded){const Fa=.5*vt*lr+bt,ta=new o.P(-100,-100),Ta=new o.P(this.screenRightBoundary,this.screenBottomBoundary),ci=new G_,{first:uo,last:ao}=qa,Io=uo.path.length;let qc=[];for(let Va=Io-1;Va>=1;Va--)qc.push(uo.path[Va]);for(let Va=1;Va(Gs&&!bn&&(Ju=an.getElevation(duVa[3]<=0)&&(qc=[]));let Wo=[];if(qc.length>0){let Va=1/0,Vc=-1/0,Ju=1/0,du=-1/0;for(const bl of qc)Va=Math.min(Va,bl[0]),Ju=Math.min(Ju,bl[1]),Vc=Math.max(Vc,bl[0]),du=Math.max(du,bl[1]);Vc>=ta.x&&Va<=Ta.x&&du>=ta.y&&Ju<=Ta.y&&(Wo=[qc.map(bl=>new o.P(bl[0],bl[1]))],(VaTa.x||JuTa.y)&&(Wo=o.cZ(Wo,ta.x,ta.y,Ta.x,Ta.y)))}for(const Va of Wo){ci.reset(Va,.25*Fa);let Vc=0;Vc=ci.length<=.5*Fa?1:Math.ceil(ci.paddedLength/Tc)+1;for(let Ju=0;Ju0?(o.c7(ye,ye,N),this.fogState&&Z&&de.name!=="globe"&&(Ce=o.c_(this.fogState,E,z,W,Z.toUnwrapped(),this.transform)>o.d2)):o.c$(ye,ye,N);const Pe=ye[3];return{point:new o.P((ye[0]/Pe+1)/2*this.transform.width+gx,(-ye[1]/Pe+1)/2*this.transform.height+gx),perspectiveRatio:Math.min(.5+this.transform.getCameraToCenterDistance(de)/Pe*.5,1.5),signedDistanceFromCamera:Pe,occluded:ne&&ye[2]>Pe||Ce}}isOffscreen(N,E,z,W){return z=this.screenRightBoundary||Wthis.screenBottomBoundary}isInsideGrid(N,E,z,W){return z>=0&&N=0&&E2}placeLayerBucketPart(L,N,E,z,W=1){const{bucket:Z,layout:ne,paint:de,posMatrix:ye,textLabelPlaneMatrix:Ce,labelToScreenMatrix:Pe,clippingData:Ke,textPixelRatio:Ze,mercatorCenter:mt,invMatrix:vt,holdingForFade:bt,collisionBoxArray:St,partiallyEvaluatedTextSize:Pt,partiallyEvaluatedIconSize:Gt,collisionGroup:as,latestFeatureIndex:ms}=N.parameters,Gs=ne.get("text-optional"),Ms=ne.get("icon-optional"),Js=ne.get("text-allow-overlap"),Os=ne.get("icon-allow-overlap"),Ks=ne.get("text-rotation-alignment")==="map",_n=ne.get("icon-rotation-alignment")==="map",ln=ne.get("text-pitch-alignment")==="map",an=de.get("symbol-z-offset"),bn=ne.get("symbol-elevation-reference")==="sea",Sn=ne.get("symbol-placement"),lr=ne.get("text-variable-anchor"),Mn=Ks&&Sn!=="point",Hn=_n&&Sn!=="point",Tr=lr&&Z.hasTextData(),oa=Z.hasIconTextFit()&&Tr&&Z.hasIconData();L.transform.setProjection(Z.projection);const Qr=Tr||Mn,Lr=Hn||oa;let qa=Js&&(Os||!Z.hasIconData()||Ms),Nr=Os&&(Js||!Z.hasTextData()||Gs);const cr=!an.isConstant();!Z.collisionArrays&&St&&Z.deserializeCollisionBoxes(St);const Fr=(ta,Ta,ci)=>{const{crossTileID:uo,numVerticalGlyphVertices:ao}=ta;let Io=null;if(Ke&&Ke.dynamicFilterNeedsFeature||cr){const Ad=L.retainedQueryData[Z.bucketInstanceId],jc=ms.loadFeature({featureIndex:ta.featureIndex,bucketIndex:Ad.bucketIndex,sourceLayerIndex:Ad.sourceLayerIndex,layoutVertexArrayOffset:0}),Zl=jc.properties?jc.properties.worldview:null;if(Z.localizable&&Z.worldview&&typeof Zl=="string")if(Zl==="all")jc.properties.$localized=!0;else{if(!Zl.split(",").includes(Z.worldview))return;jc.properties.$localized=!0,jc.properties.worldview=Z.worldview}Io=Ke&&Ke.needGeometry?o.bw(jc,!0):jc}if(Ke&&!(0,Ke.dynamicFilter)({zoom:L.transform.zoom,pitch:L.transform.pitch,worldview:Z.worldview},Io,L.retainedQueryData[Z.bucketInstanceId].tileID.canonical,new o.P(ta.tileAnchorX,ta.tileAnchorY),L.transform.calculateDistanceTileData(Ke.unwrappedTileID)))return L.placements[uo]=new Rb(!1,!1,!1,!0),void E.add(uo);const qc=an.evaluate(Io,{});if((ta.zOffset||0)+(qc||0)>0&&L.frontCutoffStart>0){const Ad=2*L.frontCutoffStart-1,jc=[ta.tileAnchorX,ta.tileAnchorY,0,1],Zl=o.c7(o.d3(),jc,ye);if(Zl[1]/Zl[3]{Ad.tileID=L.retainedQueryData[Z.bucketInstanceId].tileID;const jc=L.transform.elevation;if(Z.elevationType==="road")Ad.elevation=bn?qc:qc+o.cW.getAtTileOffset(Ad.tileID,new o.P(Ad.tileAnchorX,Ad.tileAnchorY),jc,null);else{const Zl=Z.hdExt?Z.hdExt.elevationFeatures[ta.elevationFeatureIndex]:void 0;Ad.elevation=bn?qc:qc+o.cW.getAtTileOffset(Ad.tileID,new o.P(Ad.tileAnchorX,Ad.tileAnchorY),jc,Zl)}Ad.elevation+=ta.zOffset},af=ci.textBox;if(af){Ud(af);const Ad=Zl=>{let zu=o.cL.horizontal;if(Z.allowVerticalPlacement&&!Zl&&L.prevPlacement){const bp=L.prevPlacement.placedOrientations[uo];bp&&(L.placedOrientations[uo]=bp,zu=bp,kv(Z,zu,ta))}return zu},jc=(Zl,zu)=>{if(Z.allowVerticalPlacement&&ao>0&&ci.verticalTextBox){for(const bp of Z.writingModes)if(bp===o.cL.vertical?(bl=zu(),uu=bl):bl=Zl(),bl&&bl.box&&bl.box.length)break}else bl=Zl()};if(lr){let Zl=lr;if(L.prevPlacement&&L.prevPlacement.variableOffsets[uo]){const qd=L.prevPlacement.variableOffsets[uo];Zl.indexOf(qd.anchor)>0&&(Zl=Zl.filter(_l=>_l!==qd.anchor),Zl.unshift(qd.anchor))}const zu=(qd,_l,of)=>{const Bf=Z.getSymbolInstanceTextSize(Pt,ta,L.transform.zoom,Ta),Bb=(qd.x2-qd.x1)*Bf+2*qd.padding,$b=(qd.y2-qd.y1)*Bf+2*qd.padding,Ej=ta.hasIconTextFit&&!Os?_l:null;Ej&&Ud(Ej);let F1={box:[],offscreen:!1,occluded:!1};const Kk=Js?2*Zl.length:Zl.length;for(let tw=0;tw=Zl.length,ta,Ta,Z,of,Ej,Pt,Gt);if(lc&&(F1=lc.placedGlyphBoxes,F1&&F1.box&&F1.box.length)){Tc=!0,du=lc.shift;break}}return F1};jc(()=>zu(af,ci.iconBox,o.cL.horizontal),()=>{const qd=ci.verticalTextBox;return qd&&Ud(qd),Z.allowVerticalPlacement&&!(bl&&bl.box&&bl.box.length)&&ao>0&&qd?zu(qd,ci.verticalIconBox,o.cL.vertical):{box:null,offscreen:null,occluded:null}}),bl&&(Tc=bl.box,Va=bl.offscreen,Vc=bl.occluded);const bp=Ad(!(!bl||!bl.box));if(!Tc&&L.prevPlacement){const qd=L.prevPlacement.variableOffsets[uo];qd&&(L.variableOffsets[uo]=qd,Yp(Z,qd.anchor,ta,bp))}}else{const Zl=(zu,bp)=>{const qd=Z.getSymbolInstanceTextSize(Pt,ta,L.transform.zoom,Ta),_l=L.collisionIndex.placeCollisionBox(Z,qd,zu,mt,vt,Qr,new o.P(0,0),Js,Ze,ye,as.predicate);return _l&&_l.box&&_l.box.length&&(kv(Z,bp,ta),L.placedOrientations[uo]=bp),_l};jc(()=>Zl(af,o.cL.horizontal),()=>{const zu=ci.verticalTextBox;return Z.allowVerticalPlacement&&ao>0&&zu?(Ud(zu),Zl(zu,o.cL.vertical)):{box:null,offscreen:null,occluded:null}}),Ad(!!(bl&&bl.box&&bl.box.length))}}if(dd=bl,Tc=dd&&dd.box&&dd.box.length>0,Va=dd&&dd.offscreen,Vc=dd&&dd.occluded,ta.useRuntimeCollisionCircles){const Ad=ta.centerJustifiedTextSymbolIndex>=0?ta.centerJustifiedTextSymbolIndex:ta.verticalPlacedTextSymbolIndex,jc=Z.text.placedSymbolArray.get(Ad),Zl=o.d4(Z.textSizeData,Pt,jc),zu=ne.get("text-padding");gl=L.collisionIndex.placeCollisionCircles(Z,Js,jc,Ad,Z.lineVertexArray,Z.glyphOffsetArray,Zl,ye,Ce,Pe,z,ln,as.predicate,ta.collisionCircleDiameter*Zl/o.d1,zu,L.retainedQueryData[Z.bucketInstanceId].tileID),Tc=Js||gl.circles.length>0&&!gl.collisionDetected,Va=Va&&gl.offscreen,Vc=gl.occluded}if(ci.iconFeatureIndex&&(zl=ci.iconFeatureIndex),ci.iconBox){const Ad=jc=>{Ud(jc);const Zl=ta.hasIconTextFit&&du?E1(du.x,du.y,Ks,ln,L.transform.angle):new o.P(0,0),zu=Z.getSymbolInstanceIconSize(Gt,L.transform.zoom,ta.placedIconSymbolIndex);return L.collisionIndex.placeCollisionBox(Z,zu,jc,mt,vt,Lr,Zl,Os,Ze,ye,as.predicate)};uu&&uu.box&&uu.box.length&&ci.verticalIconBox?(Hc=Ad(ci.verticalIconBox),Wo=Hc.box.length>0):(Hc=Ad(ci.iconBox),Wo=Hc.box.length>0),Va=Va&&Hc.offscreen,Ju=Hc.occluded}const Pv=Gs||ta.numHorizontalGlyphVertices===0&&ao===0,ty=Ms||ta.numIconVertices===0;if(Pv||ty?ty?Pv||(Wo=Wo&&Tc):Tc=Wo&&Tc:Wo=Tc=Wo&&Tc,Tc&&dd&&dd.box&&L.collisionIndex.insertCollisionBox(dd.box,ne.get("text-ignore-placement"),Z.bucketInstanceId,uu&&uu.box&&Yl?Yl:Fu,as.ID),Wo&&Hc&&L.collisionIndex.insertCollisionBox(Hc.box,ne.get("icon-ignore-placement"),Z.bucketInstanceId,zl,as.ID),gl&&(Tc&&L.collisionIndex.insertCollisionCircles(gl.circles,ne.get("text-ignore-placement"),Z.bucketInstanceId,Fu,as.ID),z)){const Ad=Z.bucketInstanceId;let jc=L.collisionCircleArrays[Ad];jc===void 0&&(jc=L.collisionCircleArrays[Ad]=new y4);for(let Zl=0;Zl=0;--Ta){const ci=ta[Ta];Fr(Z.symbolInstances.get(ci),ci,Z.collisionArrays[ci])}Z.hasAnyZOffset&&o.w(`${Z.layerIds[0]} layer symbol-z-elevate: symbols are not sorted by elevation if symbol-z-order is evaluated to viewport-y`)}else if(Z.hasAnyZOffset){const ta=Z.getSortedIndexesByZOffset();for(let Ta=0;Ta0){let an;return L.prevPlacement&&L.prevPlacement.variableOffsets[Os]&&L.prevPlacement.placements[Os]&&L.prevPlacement.placements[Os].text&&(an=L.prevPlacement.variableOffsets[Os].anchor),L.variableOffsets[Os]={textOffset:Ks,width:ne,height:de,anchor:N,textScale:ye,prevAnchor:an},Yp(Pt,N,bt,Gt),Pt.allowVerticalPlacement&&(kv(Pt,Gt,bt),L.placedOrientations[Os]=Gt),{shift:_n,placedGlyphBoxes:ln}}}}};class $e{constructor(N){this._sortAcrossTiles=N.layout.get("symbol-z-order")!=="viewport-y"&&N.layout.get("symbol-sort-key").constantOr(1)!==void 0,this._currentTileIndex=0,this._currentPartIndex=0,this._seenCrossTileIDs=new Set,this._bucketParts=[]}continuePlacement(N,E,z,W,Z,ne){const de=this._bucketParts;for(;this._currentTileIndexye.sortKey-Ce.sortKey));this._currentPartIndex!this.isFullPlacementRequested()&&this._fadeDuration!==0&&this.placement.algorithm.shouldPause(o.e.now()-ne);for(;this._currentPlacementIndex>=0;){const ye=E[N[this._currentPlacementIndex]],Ce=this.placement.collisionIndex.transform.zoom;if(ye.type==="symbol"&&ye.visibility!=="none"&&(!ye.minzoom||ye.minzoom<=Ce)&&(!ye.maxzoom||ye.maxzoom>Ce)){const Pe=ye,Ke=Pe.layout.get("symbol-z-elevate"),Ze=Pe.layout.get("symbol-sort-key").constantOr(1)!==void 0,mt=Pe.layout.get("symbol-z-order"),vt=mt==="viewport-y"||mt==="auto"&&!(mt!=="viewport-y"&&Ze),bt=Pe.layout.get("text-allow-overlap")||Pe.layout.get("icon-allow-overlap")||Pe.layout.get("text-ignore-placement")||Pe.layout.get("icon-ignore-placement"),St=vt&&bt,Pt=this._inProgressLayer=this._inProgressLayer||new $e(Pe),Gt=o.m(ye.source,ye.scope);if(Pt.continuePlacement(Ke||St?W[Gt]:z[Gt],this.placement,this._showCollisionBoxes,ye,de,Z))return;delete this._inProgressLayer}this._currentPlacementIndex--}this._forceFullPlacement=!1,this._done=!0}commit(N){return this._retiredCI=this.placement.prevPlacement?this.placement.prevPlacement.collisionIndex:null,this.placement.commit(N),this.placement}}const Et=512/o.a2/2;class ts{constructor(N,E,z){this.tileID=N,this.bucketInstanceId=z,this.index=new o.d5(E.length,16,Int32Array),this.keys=[],this.crossTileIDs=[];const W=N.canonical.x*o.a2,Z=N.canonical.y*o.a2;for(let ne=0;neSt-Pt);for(const St of bt){const Pt=this.crossTileIDs[St];if(this.keys[St]===Pe&&!z.has(Pt)){z.add(Pt),Ce.crossTileID=Pt;break}}}}}class hs{constructor(){this.maxCrossTileID=0}generate(){return++this.maxCrossTileID}}class gs{constructor(){this.indexes={},this.usedCrossTileIDs={},this.lng=0}handleWrapJump(N){const E=Math.round((N-this.lng)/360);if(E!==0)for(const z in this.indexes){const W=this.indexes[z],Z={};for(const ne in W){const de=W[ne];de.tileID=de.tileID.unwrapTo(de.tileID.wrap+E),Z[de.tileID.key]=de}this.indexes[z]=Z}this.lng=N}addBucket(N,E,z){if(this.indexes[N.overscaledZ]&&this.indexes[N.overscaledZ][N.key]){if(this.indexes[N.overscaledZ][N.key].bucketInstanceId===E.bucketInstanceId)return!1;this.removeBucketCrossTileIDs(N.overscaledZ,this.indexes[N.overscaledZ][N.key])}for(let Z=0;ZN.overscaledZ)for(const de in ne){const ye=ne[de];ye.tileID.isChildOf(N)&&ye.findMatches(E.symbolInstances,N,W)}else{const de=ne[N.scaledTo(Number(Z)).key];de&&de.findMatches(E.symbolInstances,N,W)}}for(let Z=0;Z{E[z]=!0});for(const z in this.layerIndexes)E[z]||delete this.layerIndexes[z]}}class Ps extends o.E{constructor(N){super(),this.requestManager=N,this.models=Object.create(null),this.models[""]=Object.create(null),this.modelUris=Object.create(null),this.modelUris[""]=Object.create(null),this.modelByURL=Object.create(null),this.numModelsLoading=Object.create(null)}async loadModel(N,E){try{const z=await this.requestManager.transformRequest(E,o.R.Model);return this.modelByURL[E]?(await Bt(),Xe.loadModel?await Xe.loadModel(z.url,N,E):null):null}catch(z){if(z.status===404)return null;this.fire(new o.f(new Error(`Could not load model ${N} from ${E}`,{cause:z})))}}load(N,E,z={forceReload:!1}){this.models[E]||(this.models[E]=Object.create(null));const W=Object.keys(N),Z=[],ne=[];for(const de of W){const ye=N[de];this.hasURLBeenRequested(ye)&&!z.forceReload||(this.modelByURL[ye]={modelId:de,scope:E},Z.push(this.loadModel(de,ye)),ne.push(de)),this.models[E][de]||(this.models[E][de]={model:null,numReferences:1})}this.numModelsLoading[E]=(this.numModelsLoading[E]||0)+ne.length,Promise.allSettled(Z).then(de=>{for(let ye=0;ye{this.fire(new o.f(new Error(`Could not load models: ${de.message}`)))})}isLoaded(){for(const N in this.numModelsLoading)if(this.numModelsLoading[N]>0)return!1;return!0}hasModel(N,E,z={exactIdMatch:!1}){return!!(z.exactIdMatch?this.getModel(N,E):this.getModelByURL(this.modelUris[E][N]))}getModel(N,E){return this.models[E]||(this.models[E]=Object.create(null)),this.models[E][N]?this.models[E][N].model:void 0}getModelByURL(N){if(!N)return null;const E=this.modelByURL[N];return E?this.models[E.scope][E.modelId].model:null}hasModelBeenAdded(N,E){return this.models[E]&&this.models[E][N]!==void 0}getModelURIs(N){return this.modelUris[N]||Object.create(null)}addModel(N,E,z){this.models[z]||(this.models[z]=Object.create(null)),this.modelUris[z]||(this.modelUris[z]=Object.create(null));const W=this.requestManager.normalizeModelURL(E);if((this.hasModel(N,z,{exactIdMatch:!0})||this.hasModelBeenAdded(N,z))&&this.modelUris[z][N]===W)this.models[z][N].numReferences++;else if(this.hasURLBeenRequested(W)){const{scope:Z,modelId:ne}=this.modelByURL[W];this.models[Z][ne].numReferences++}else this.modelUris[z][N]=W,this.load({[N]:this.modelUris[z][N]},z)}addModelURLs(N,E){this.models[E]||(this.models[E]=Object.create(null)),this.modelUris[E]||(this.modelUris[E]=Object.create(null));const z=this.modelUris[E];for(const W of Object.keys(N))z[W]=this.requestManager.normalizeModelURL(N[W])}reloadModels(N){this.load(this.modelUris[N],N,{forceReload:!0})}addModelsFromBucket(N,E){this.models[E]||(this.models[E]=Object.create(null)),this.modelUris[E]||(this.modelUris[E]=Object.create(null));const z=Object.create(null);for(const W of N)this.hasModel(W,E,{exactIdMatch:!0})||this.hasURLBeenRequested(W)?this.models[E][W].numReferences++:this.modelUris[E][W]&&!this.hasURLBeenRequested(W)?z[W]=this.modelUris[E][W]:!this.hasURLBeenRequested(W)&&Kt(W,!1)&&(this.modelUris[E][W]=this.requestManager.normalizeModelURL(W),z[W]=this.modelUris[E][W]);this.load(z,E)}hasURLBeenRequested(N){return this.modelByURL[N]!==void 0}removeModel(N,E,z=!1,W=!1){if(this.models[E]&&this.models[E][N]&&(this.models[E][N].numReferences--,this.models[E][N].numReferences===0||W)){const Z=this.modelUris[E][N];z||delete this.modelUris[E][N],delete this.modelByURL[Z];const ne=this.models[E][N].model;if(!ne)return;delete this.models[E][N],ne.destroy()}}destroy(){for(const N of Object.keys(this.models))for(const E of Object.keys(this.models[N])){const z=this.models[N][E].model;delete this.models[N][E],z&&z.destroy()}this.models=Object.create(null),this.models[""]=Object.create(null),this.modelUris=Object.create(null),this.modelUris[""]=Object.create(null),this.modelByURL=Object.create(null),this.numModelsLoading=Object.create(null)}listModels(N){return this.models[N]||(this.models[N]=Object.create(null)),Object.keys(this.models[N])}upload(N,E){this.models[E]||(this.models[E]=Object.create(null));for(const z in this.models[E])this.models[E][z].model&&this.models[E][z].model.upload(N.context)}}const Qs=["RENDER_SHADOWS","NORMAL_OFFSET"],Dn=new Set(["symbol","circle"]),dr=class w7e{constructor(){this._queue=[],this._needsBuild=!0,this._idleHandle=null}needsBuild(){return this._needsBuild}buildQueue(N,E,z){this._idleHandle!=null&&typeof cancelIdleCallback<"u"&&cancelIdleCallback(this._idleHandle),this._idleHandle=null,this._queue=[],this._needsBuild=!1;const W=!!z.fog,Z=z.hasTerrain(),ne=!(!z.projection||z.projection.name!=="globe"),de=Z||ne,ye=!(!z.directionalLight||!z.directionalLight.shadowsEnabled()),Ce=z.map&&z.map.painter,Pe=!Ce||!Ce.context.extParallelShaderCompile,Ke=!!Ce&&Ce.emissiveMode==="mrt-fallback",Ze=(mt,vt=[],bt={})=>{this._queue.push({programId:mt,params:{...bt.params,defines:vt,overrideFog:!!bt.fog,overrideTerrain:!!bt.terrain,overrideGlobe:!!bt.globe,overrideRtt:!!bt.rtt,precompiled:!0}})};for(const mt of N){if(mt.visibility==="none")continue;const vt=mt.getProgramIds();if(vt)for(const bt of vt){if(Dn.has(bt))continue;const St=mt.getDefaultProgramParams(bt,E.zoom,z._styleColorTheme.lut);if(!St)continue;const Pt=Ce?Ce.getShaderSource(bt):null,Gt=de&&(!Pt||Pt.usedDefines.has("RENDER_TO_TEXTURE")),as=Ke&&Gt?(St.defines||[]).concat("USE_MRT1"):St.defines;if(Pe){Ze(bt,St.defines,{params:St}),Gt&&Ze(bt,as,{params:St,rtt:!0});continue}const ms=W&&(!Pt||Pt.usedDefines.has("FOG")),Gs=Z&&!mt.isDraped()&&(!Pt||Pt.usedDefines.has("TERRAIN")),Ms=ne&&(!Pt||Pt.usedDefines.has("GLOBE")),Js=ye&&mt.hasElevation()&&(!Pt||Pt.usedDefines.has("RENDER_SHADOWS"));for(const Os of Js?[!1,!0]:[!1]){const Ks=Os?(St.defines||[]).concat(Qs):St.defines||[];for(const _n of Gs?[!1,!0]:[!1])for(const ln of Ms?[!1,!0]:[!1])for(const an of ms?[!1,!0]:[!1])Ze(bt,Ks,{params:St,fog:an,terrain:_n,globe:ln})}Gt&&Ze(bt,as,{params:St,rtt:!0})}}if(Ze("clippingMask"),Z)for(const mt of[!1,!0])Ze("terrainRaster",mt?["TERRAIN_VERTEX_MORPHING"]:[],{terrain:!0,fog:W});if(!Pe){if(N.some(mt=>mt.type==="hillshade")&&Ze("hillshadePrepare"),ye)for(const mt of[!1,!0])for(const vt of[!1,!0]){const bt=[];mt&&bt.push("RENDER_CUTOFF"),bt.push("RENDER_SHADOWS"),vt&&bt.push("NORMAL_OFFSET"),Ze("groundShadow",bt),W&&Ze("groundShadow",bt,{fog:!0})}if(ne){for(const mt of[[],["TERRAIN_VERTEX_MORPHING"],["GLOBE_POLES"]])for(const vt of[!1,!0]){const bt=[...mt,"PROJECTION_GLOBE_VIEW"];vt&&bt.push("CUSTOM_ANTIALIASING"),Ze("globeRaster",bt,{terrain:Z,globe:!0,fog:W})}for(const mt of[!1,!0]){const vt=mt?["PROJECTION_GLOBE_VIEW","FOG"]:["FOG"];Ze("globeAtmosphere",vt,{fog:!0,terrain:Z,globe:mt}),Ze("globeAtmosphere",[...vt,"ALPHA_PASS"],{fog:!0,terrain:Z,globe:mt})}Ze("stars",[],{fog:W,terrain:Z,globe:!0})}}}_executeBatch(N,E,z){if(z.map&&z.map.isMoving())return void(this._idleHandle=o.e.requestIdleCallback(de=>this._executeBatch(de,E,z)));E.context.sweepPendingPrograms();const W=E.context.extParallelShaderCompile?w7e.DEADLINE_MARGIN_KHR_MS:w7e.DEADLINE_MARGIN_SYNC_MS;let Z=0;for(;this._queue.length>0;){const de=this._queue.shift();if(!de||(E.style=z,E._fogVisible=!!de.params.overrideFog,E.getOrCreateProgram(de.programId,de.params),Z++,N.timeRemaining()<=W))break}const ne=this._queue.length===0||N.timeRemaining()>W;Z>0&&ne&&E.context.gl.flush(),this._idleHandle=this._queue.length>0||E.context._pendingPrograms.size>0?o.e.requestIdleCallback(de=>this._executeBatch(de,E,z)):null}processQueue(N,E){this._queue.length!==0&&(this._idleHandle!=null&&typeof cancelIdleCallback<"u"&&cancelIdleCallback(this._idleHandle),this._idleHandle=o.e.requestIdleCallback(z=>this._executeBatch(z,N,E)))}reset(){this._idleHandle!=null&&typeof cancelIdleCallback<"u"&&cancelIdleCallback(this._idleHandle),this._queue=[],this._idleHandle=null,this._needsBuild=!0}};dr.DEADLINE_MARGIN_KHR_MS=5,dr.DEADLINE_MARGIN_SYNC_MS=25;let Ws=dr;const Vn=o.s.colorTheme,or=new o.af({data:new o.ag(Vn.data)});function zr(L){if(!L.metadata||!L.metadata.content_area)return;const N=o.e.devicePixelRatio,{left:E,top:z,width:W,height:Z}=L.metadata.content_area,ne=E*N,de=z*N;return[ne,de,ne+W*N,de+Z*N]}function rr(L){if(L)return L.map(([N,E])=>[N*o.e.devicePixelRatio,E*o.e.devicePixelRatio])}class Xr{constructor(N,E,z){this.id=N,this.scope=E,this.sourceCache=z,this.pendingRequests=new Set,this.missingRequests=new Set}addPendingRequest(N){this.missingRequests.has(N.name)||this.pendingRequests.has(N.name)||this.pendingRequests.add(N.name)}hasPendingRequests(){return this.pendingRequests.size>0}resolvePendingRequests(){const N=new Map;if(!this.sourceCache.loaded())return N;const E=this.sourceCache.getVisibleCoordinates();if(E.length===0)return N;const z=this.sourceCache.getSource();if(z.type!=="raster-array")return N;const W=E.map(ne=>this.sourceCache.getTile(ne)),Z=z.getImages(W,Array.from(this.pendingRequests));for(const[ne,de]of Z)N.set(o.I.from({name:ne,iconsetId:this.id}),de),this.pendingRequests.delete(ne);for(const ne of this.pendingRequests)this.missingRequests.add(ne);return this.pendingRequests.clear(),N}}const Gn=(L,N)=>Mg(L,N&&N.filter(E=>E.identifier!=="source.canvas")),Na=new Set(["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"]),pa=new Set(["setCenter","setZoom","setBearing","setPitch"]),Yi=new Set(["background","sky","slot","custom"]),Ui={version:8,layers:[],sources:{}},il={duration:300,delay:0};class zi extends o.E{constructor(N,E={}){super(),this.map=N,this.scope=E.scope||"",this.globalId=null,this.fragments=[],this.importDepth=E.importDepth||0,this.importsCache=E.importsCache||new Map,this.resolvedImports=E.resolvedImports||new Set,this.transition={...il},this._buildingIndex=new Fy(this),this.crossTileSymbolIndex=new Es,this._mergedOrder=[],this._drapedFirstOrder=[],this._mergedLayers=Object.create(null),this._mergedIndoor={},this._indoorEnabled=!1,this._mergedSourceCaches={},this._mergedOtherSourceCaches=Object.create(null),this._mergedSymbolSourceCaches=Object.create(null),this._mergedFillExtrusionSourceCaches=Object.create(null),this._mergedHdRoadCoverageSourceCaches=Object.create(null),this._mergedHdRoadElevationSourceCaches=Object.create(null),this._hdCoverage=null,this._hdElevation=null,this._crossSourceElevationActive=!1,this._clipLayerPresent=!1,this._hasAppearances=!1,this._has3DLayers=!1,this._hasCircleLayers=!1,this._hasSymbolLayers=!1,this._importedAsBasemap=!1,this._changes=E.styleChanges||new B,this._hasDataDrivenEmissive=!1,this.indoorManager=null,this.dispatcher=E.dispatcher?E.dispatcher:new yi(Bk(),this);const z={referrer:o.d7(),config:o.dp()};if(this.map.painter&&this.map.painter.context){const Z=this.map.painter.context.maxUniformBufferBindings,ne=Math.floor(this.map.painter.context.maxUniformBlockSize/4);z.contextOptions={maxBindingPoints:Z,maxUniformBlockSizeDwords:ne}}this.isRootStyle()&&this.dispatcher.broadcast("setGlobalParams",z),E.imageManager?this.imageManager=E.imageManager:(this.imageManager=new dt(this.map._spriteFormat),this.imageManager.setEventedParent(this)),this.imageManager.addScope(this.scope),this.glyphManager=E.glyphManager?E.glyphManager:new o.d8(N._requestManager,E.localFontFamily?o.d9.all:E.localIdeographFontFamily?o.d9.ideographs:o.d9.none,E.localFontFamily||E.localIdeographFontFamily,E.fontstackCompositing),E.modelManager?this.modelManager=E.modelManager:(this.modelManager=new Ps(N._requestManager),this.modelManager.setEventedParent(this)),this._layers=Object.create(null),this._sourceCaches={},this._otherSourceCaches=Object.create(null),this._symbolSourceCaches=Object.create(null),this._fillExtrusionSourceCaches=Object.create(null),this._hdCoverage=null,this._hdElevation=null,this._crossSourceElevationActive=!1,this._loaded=!1,this._initialBroadcastDone=!1,this._programPrecompiler=this.map._precompilePrograms&&this.isRootStyle()?new Ws:null,this._availableImages=[],this._availableModels={},this._order=[],this._markersNeedUpdate=!1,this.options=E.configOptions?E.configOptions:new Map,this._layerExpressionDependencies=E.layerExpressionDependencies?E.layerExpressionDependencies:new Map,this._config=E.config,this._styleColorTheme={lut:null,lutLoading:!1,lutLoadingCorrelationID:0,colorTheme:null,colorThemeOverride:E.colorThemeOverride},this._styleColorThemeForScope={},this._initialConfig=E.initialConfig;const W=this;this._rtlTextPluginCallback=zi.registerForPluginStateChange(Z=>{W.dispatcher.send("syncRTLPluginState",{pluginStatus:Z.pluginStatus,pluginURL:Z.pluginURL}).then(ne=>{if(o.da(null),ne.every(de=>de))for(const de in W._sourceCaches){const ye=W._sourceCaches[de],Ce=ye.getSource().type;Ce!=="vector"&&Ce!=="geojson"||ye.reload()}}).catch(ne=>{o.da(ne)})}),this.on("data",Z=>{if(Z.dataType!=="source"||Z.sourceDataType!=="metadata")return;const ne=this.getOwnSource(Z.sourceId);if(ne&&ne.vectorLayerIds)for(const de in this._layers){const ye=this._layers[de];ye.source===ne.id&&this._validateLayer(ye)}})}load(N){return N?(typeof N=="string"?this.loadURL(N):this.loadJSON(N),this):this}_getGlobalId(N){if(!N)return null;if(typeof N=="string"){if(o.cg(N))return N;const E=o.db(N);if(!E.startsWith("http"))try{return new URL(E,location.href).toString()}catch{return E}return E}return`json://${o.dc(JSON.stringify(N))}`}_diffStyle(N,E,z){this.globalId=this._getGlobalId(N),Bh();const W=(Z,ne)=>{try{ne(null,this.setState(Z,z))}catch(de){ne(de,!1)}};if(typeof N=="string"){const Z=this.map._requestManager.normalizeStyleURL(N),ne=new AbortController;this._request={cancel:()=>ne.abort()},(async()=>{const de=await this.map._requestManager.transformRequest(Z,o.R.Style,ne.signal),{data:ye}=await o.g(de,ne.signal);this._request=null,W(ye,E)})().catch(de=>{this._request=null,ne.signal.aborted||this.fire(new o.f(de))})}else typeof N=="object"&&W(N,E)}loadURL(N,E={}){this.fire(new o.h("dataloading",{dataType:"style"}));const z=typeof E.validate=="boolean"?E.validate:!o.cg(N);z&&Bh(),this.globalId=this._getGlobalId(N),N=this.map._requestManager.normalizeStyleURL(N,E.accessToken),this.resolvedImports.add(N);const W=this.importsCache.get(N);if(W)return void this._load(W,z);const Z=new AbortController;this._request={cancel:()=>Z.abort()},(async()=>{const ne=await this.map._requestManager.transformRequest(N,o.R.Style,Z.signal),{data:de}=await o.g(ne,Z.signal);this._request=null,this.importsCache.set(N,de),this._load(de,z)})().catch(ne=>{this._request=null,Z.signal.aborted||this.fire(new o.f(ne))})}loadJSON(N,E={}){this.fire(new o.h("dataloading",{dataType:"style"}));const z=E.validate!==!1;z&&Bh(),this.globalId=this._getGlobalId(N),this._request=o.e.frame(()=>{this._request=null,this._load(N,z)})}loadEmpty(){this.fire(new o.h("dataloading",{dataType:"style"})),this._load(Ui,!1)}_loadImports(N,E,z){if(this.importDepth>=4)return o.w("Style doesn't support nesting deeper than 5"),Promise.resolve();const W=[];for(const Z of N){const ne=this._createFragmentStyle(Z),de=new Promise(Pe=>{ne.once("style.import.load",Pe),ne.once("error",Pe)}).then(()=>{this.mergeAll(),this.fire(new o.h("data",{dataType:"style"}))});if(W.push(de),this.resolvedImports.has(Z.url)){ne.loadEmpty();continue}const ye=Z.data||this.importsCache.get(Z.url);ye?(Z.data?(ne.fire(new o.h("dataloading",{dataType:"style"})),ne.globalId=ne._getGlobalId(ye),E&&Bh(),queueMicrotask(()=>{ne._load(ye,E)})):ne.loadJSON(ye,{validate:E}),this._isInternalStyle(ye)&&(ne.globalId=null)):Z.url?ne.loadURL(Z.url,{validate:E}):ne.loadEmpty();const Ce={style:ne,id:Z.id,config:Z.config};if(z){const Pe=this.fragments.findIndex(({id:Ke})=>Ke===z);this.fragments=this.fragments.slice(0,Pe).concat(Ce).concat(this.fragments.slice(Pe))}else this.fragments.push(Ce)}return Promise.allSettled(W)}getImportGlobalIds(N=this,E=new Set){for(const z of N.fragments)z.style.globalId&&E.add(z.style.globalId),this.getImportGlobalIds(z.style,E);return[...E.values()]}_createFragmentStyle(N){const E=this.scope?o.m(N.id,this.scope):N.id;let z;const W=this._initialConfig&&this._initialConfig[E];(N.config||W)&&(z={...N.config,...W});const Z=new zi(this.map,{scope:E,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:z,configOptions:this.options,colorThemeOverride:N["color-theme"],layerExpressionDependencies:this._layerExpressionDependencies});return Z.setEventedParent(this.map,{style:Z}),Z}_reloadImports(N=!1){this.mergeAll(),this._updateMapProjection(),N||this.updateConfigDependencies(),this._updateLayers(this._dependentLayerIds(E=>E.isIndoorDependent)),this.map._triggerCameraUpdate(this.camera),(!N||this.isRootStyle()||this.map.style._initialBroadcastDone)&&(N&&this.isRootStyle()?(this.forEachFragmentStyle(E=>{this.dispatcher.broadcast("setLayers",{layers:E._serializeLayers(E._order),scope:E.scope,options:E.options})}),this._initialBroadcastDone=!0):this.dispatcher.broadcast("setLayers",{layers:this._serializeLayers(this._order),scope:this.scope,options:this.options}))}_isInternalStyle(N){return this.isRootStyle()&&(N.fragment||!!N.schema&&N.fragment!==!1)}async _load(N,E){if(this._isInternalStyle(N)){const Z={id:"basemap",data:N,url:""},ne={...Ui,imports:[Z],...N.center?{center:N.center}:{},...N.bearing?{bearing:N.bearing}:{},...N.pitch?{pitch:N.pitch}:{},...N.zoom?{zoom:N.zoom}:{},...N.light?{light:N.light}:{}};return this._importedAsBasemap=!0,void this._load(ne,E)}if(this.updateConfig(this._config,N.schema),E&&(await Bh(),!this.dispatcher.actors.length||Gn(this,$h(N))))return;this._loaded=!0;for(const Z in N.sources)this.addSource(Z,N.sources[Z],{validate:!1,isInitialLoad:!0});this.stylesheet=o.dd(N);const z=()=>{if(N.iconsets)for(const Ce in N.iconsets)this.addIconset(Ce,N.iconsets[Ce]);N.sprite?this._loadIconset(N.sprite):(this.imageManager.setLoaded(!0,this.scope),this.dispatcher.broadcast("spriteLoaded",{scope:this.scope})),!this.glyphManager.url&&N.glyphs&&this.glyphManager.setURL(N.glyphs);const Z=fp(this.stylesheet.layers);if(this._order=Z.map(Ce=>Ce.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 Ce=this.stylesheet.lights[0];this.light=new Wt(Ce.properties,Ce.id)}else this.setLights(this.stylesheet.lights);this.light||(this.light=new Wt(this.stylesheet.light)),this._layers=Object.create(null);let ne=!1;for(const Ce of Z){const Pe=o.dj(Ce,this.scope,this._styleColorTheme.lut,this.options);this._layerExpressionDependencies.set(Pe.fqid,new U(Pe)),this._hasAppearances=this._hasAppearances||Pe.getAppearances().length!==0,Pe.setEventedParent(this,{layer:{id:Pe.id}}),this._layers[Pe.id]=Pe,this._updateHdCoverageSourceCache(Pe)&&(ne=!0);const Ke=this.getOwnLayerSourceCache(Pe),Ze=!!this.directionalLight&&this.directionalLight.shadowsEnabled();Ke&&Pe.canCastShadows()&&Ze&&(Ke.castsShadows=!0)}if(ne&&Lf().then(()=>{if(!this.map)return;for(const Pe in this._layers)this._updateHdCoverageSourceCache(this._layers[Pe]);this.map.style.mergeAll();const Ce=this.map.transform;for(const Pe in this.map.style._mergedHdRoadCoverageSourceCaches){const Ke=this.map.style._mergedHdRoadCoverageSourceCaches[Pe];Ke.used=!0,Ce&&Ke.update(Ce)}this.map._update()}),this.glyphManager.url){const Ce=new Set;for(const Pe in this._layers){const Ke=this._layers[Pe];if(Ke.type==="symbol"&&Ke.layout){const Ze=Ke.layout.get("text-font");Ze&&Ze.value&&Ze.value.kind==="constant"&&Ce.add(Ze.value.value.join(","))}}for(const Pe of Ce)this.glyphManager.prefetchRange(Pe,0)}this.stylesheet.featuresets&&this.setFeaturesetSelectors(this.stylesheet.featuresets),this.stylesheet.models&&this.addModelURLs(this.stylesheet.models);const de=this.stylesheet.terrain;de&&(this.checkCanvasFingerprintNoise(),this.disableElevatedTerrain||this.terrainSetForDrapingOnly()||this._createTerrain(de,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.h("data",{dataType:"style"}));const ye=this.isRootStyle();N.imports?this._loadImports(N.imports,E).then(()=>{this._reloadImports(!0),this.fire(new o.h(ye?"style.load":"style.import.load"))}).catch(Ce=>{this.fire(new o.f(new Error("Failed to load imports",Ce))),this.fire(new o.h(ye?"style.load":"style.import.load"))}):(this._reloadImports(!0),this.fire(new o.h(ye?"style.load":"style.import.load")))};this._styleColorTheme.colorTheme=this.stylesheet["color-theme"];const W=this._styleColorTheme.colorThemeOverride?this._styleColorTheme.colorThemeOverride:this._styleColorTheme.colorTheme;if(W){const Z=this._evaluateColorThemeData(W);this._loadColorTheme(Z).then(()=>{z()}).catch(ne=>{o.w(`Couldn't load color theme from the stylesheet: ${ne}`),z()})}else this._styleColorTheme.lut=null,z()}isRootStyle(){return this.importDepth===0}hasAppearances(){return this._hasAppearances||this.fragments.some(N=>N.style.hasAppearances())}mergeAll(){let N,E,z,W,Z,ne,de,ye,Ce,Pe;const Ke={};this.terrain&&this.terrain.scope!==this.scope&&delete this.terrain,this.forEachFragmentStyle(Ze=>{if(Ze.stylesheet){if(Ze.disableElevatedTerrain&&(this.disableElevatedTerrain=!0),Ze.light!=null&&(N=Ze.light),Ze.stylesheet.lights)for(const mt of Ze.stylesheet.lights)mt.type==="ambient"&&Ze.ambientLight!=null&&(E=Ze.ambientLight),mt.type==="directional"&&Ze.directionalLight!=null&&(z=Ze.directionalLight);W=this._prioritizeTerrain(W,Ze.terrain,Ze.stylesheet.terrain),Ze.stylesheet.fog&&Ze.fog!=null&&(Z=Ze.fog),Ze.stylesheet.snow&&Ze.snow!=null&&(ne=Ze.snow),Ze.stylesheet.rain&&Ze.rain!=null&&(de=Ze.rain),Ze.stylesheet.camera!=null&&(Pe=Ze.stylesheet.camera),Ze.stylesheet.projection!=null&&(ye=Ze.stylesheet.projection),Ze.stylesheet.transition!=null&&(Ce=Ze.stylesheet.transition),Ke[Ze.scope]=Ze._styleColorTheme}}),this.light=N,this.ambientLight=E,this.directionalLight=z,this.fog=Z,this.snow=ne,this.rain=de,this._styleColorThemeForScope=Ke,W===null?delete this.terrain:this.terrain=W,this.camera=Pe||{"camera-projection":"perspective"},this.projection=ye||{name:"mercator"},this.transition={...il,...Ce},this.mergeSources(),this.mergeLayers(),this.mergeIndoor(),this._programPrecompiler&&this._programPrecompiler.reset()}forEachFragmentStyle(N){const E=z=>{for(const W of z.fragments)E(W.style);N(z)};E(this)}_prioritizeTerrain(N,E,z){const W=N&&N.drapeRenderMode===0;return z===null?E&&E.drapeRenderMode===0?E:W?N:null:E!=null&&(!N||W||E&&E.drapeRenderMode===1)?E:N}mergeTerrain(){let N;this.terrain&&this.terrain.scope!==this.scope&&delete this.terrain,this.forEachFragmentStyle(E=>{N=this._prioritizeTerrain(N,E.terrain,E.stylesheet.terrain)}),N===null?delete this.terrain:this.terrain=N,this._programPrecompiler&&this._programPrecompiler.reset()}mergeProjection(){let N;this.forEachFragmentStyle(E=>{E.stylesheet.projection!=null&&(N=E.stylesheet.projection)}),this.projection=N||{name:"mercator"},this._programPrecompiler&&this._programPrecompiler.reset()}mergeSources(){const N={},E=Object.create(null),z=Object.create(null),W=Object.create(null),Z=Object.create(null),ne=Object.create(null);this.forEachFragmentStyle(de=>{for(const ye in de._sourceCaches){const Ce=o.m(ye,de.scope);N[Ce]=de._sourceCaches[ye]}for(const ye in de._otherSourceCaches){const Ce=o.m(ye,de.scope);E[Ce]=de._otherSourceCaches[ye]}for(const ye in de._symbolSourceCaches){const Ce=o.m(ye,de.scope);z[Ce]=de._symbolSourceCaches[ye]}for(const ye in de._fillExtrusionSourceCaches){const Ce=o.m(ye,de.scope);W[Ce]=de._fillExtrusionSourceCaches[ye]}if(de._hdCoverage){const ye=de._hdCoverage.coverageSourceCaches;for(const Ce in ye)Z[o.m(Ce,de.scope)]=ye[Ce]}if(de._hdElevation){const ye=de._hdElevation.elevationSourceCaches;for(const Ce in ye)ne[Ce]=ye[Ce]}}),this._mergedSourceCaches=N,this._mergedOtherSourceCaches=E,this._mergedSymbolSourceCaches=z,this._mergedFillExtrusionSourceCaches=W,this._mergedHdRoadCoverageSourceCaches=Z,this._mergedHdRoadElevationSourceCaches=ne,Object.keys(Z).length>0&&!this._hdCoverage&&wi.HdCoverageState&&(this._hdCoverage=new wi.HdCoverageState),wi.updateCrossSourceElevationGate&&wi.updateCrossSourceElevationGate(this)}mergeIndoor(){this._mergedIndoor={},this.forEachFragmentStyle(N=>{if(N.stylesheet&&N.stylesheet.indoor)for(const E of Object.values(N.stylesheet.indoor)){const z=E,W=o.m(z.sourceId,N.scope);this._mergedIndoor[W]=new Set(z.sourceLayers||[])}}),this._updateIndoorEnabled()}_updateIndoorEnabled(){const N=this._indoorEnabled;if(this._indoorEnabled=!1,Object.keys(this._mergedIndoor).length>0)for(const E of this._mergedOrder){const z=this._mergedLayers[E];if(z.visibility!=="none"&&this._mergedIndoor[o.m(z.source,z.scope)]){this._indoorEnabled=!0;break}}!this._indoorEnabled||N||this.indoorManager||Lf().then(()=>{this._initIndoorManager()})}_initIndoorManager(){if(!this.indoorManager&&wi.IndoorManager&&this.isRootStyle()&&Object.keys(this._mergedIndoor).length!==0&&(this.indoorManager=new wi.IndoorManager(this,this._loaded),this._loaded))for(const N of Object.keys(this._mergedIndoor)){const E=this._mergedSourceCaches[N]||this._mergedOtherSourceCaches[N];E&&E.reload()}}mergeLayers(){const N={},E=[],z=Object.create(null);this._mergedSlots=[],this._has3DLayers=!1,this._hasCircleLayers=!1,this._hasSymbolLayers=!1,this.forEachFragmentStyle(ne=>{for(const de of ne._order){const ye=ne._layers[de];if(ye.type==="slot"){const Ce=o.bV(de);if(N[Ce])continue;N[Ce]=[]}ye.slot&&N[ye.slot]?N[ye.slot].push(ye):E.push(ye)}}),this._mergedOrder=[];let W=-1;const Z=(ne=[])=>{for(const de of ne)if(de.type==="slot"){const ye=o.bV(de.id);N[ye]&&Z(N[ye]),this._mergedSlots.push(ye)}else{const ye=o.m(de.id,de.scope);this._mergedOrder.push(ye),z[ye]=de,de.is3D(!!this.terrain)&&(this._has3DLayers=!0,W=this._mergedOrder.length-1),de.type==="circle"&&(this._hasCircleLayers=!0),de.type==="symbol"&&(this._hasSymbolLayers=!0),de.type==="clip"&&(this._clipLayerPresent=!0)}};if(Z(E),this._has3DLayers){const ne={};for(let de=0;dene[de]-ne[ye])}this._mergedLayers=z,this.updateDrapeFirstLayers(),this._buildingIndex.processLayersChanged(),this._updateDataDrivenEmissiveStrength()}terrainSetForDrapingOnly(){return!!this.terrain&&this.terrain.drapeRenderMode===0}getCamera(){return this.stylesheet.camera}setCamera(N){return this.stylesheet.camera={...this.stylesheet.camera,...N},this.camera=this.stylesheet.camera,this}_evaluateColorThemeData(N){return N.data?function(E,z,W){const Z={...z};for(const de of Object.keys(Vn))Z[de]===void 0&&(Z[de]=Vn[de].default);const ne=new o.ae(or,E,new Map(W));return ne.setTransitionOrValue(Z,W),ne.untransitioned().possiblyEvaluate(new o.ai(0,{worldview:void 0}))}(this.scope,N,this.options).get("data"):null}_loadColorTheme(N){this._styleColorTheme.lutLoading=!0,this._styleColorTheme.lutLoadingCorrelationID+=1;const E=this._styleColorTheme.lutLoadingCorrelationID;return new Promise((z,W)=>{const Z="data:image/png;base64,";if(!N||N.length===0)return this._styleColorTheme.lut=null,this._styleColorTheme.lutLoading=!1,void z();let ne=N;ne.startsWith(Z)||(ne=Z+ne);const de=o.I.from("mapbox-reserved-lut"),ye=new Image;ye.src=ne,ye.onerror=()=>{this._styleColorTheme.lutLoading=!1,W(new Error("Failed to load image data"))},ye.onload=()=>{if(this._styleColorTheme.lutLoadingCorrelationID!==E)return void z();this._styleColorTheme.lutLoading=!1;const{width:Ce,height:Pe,data:Ke}=o.e.getImageData(ye);if(Pe>32)return void W(new Error("The height of the image must be less than or equal to 32 pixels."));if(Ce!==Pe*Pe)return void W(new Error("The width of the image must be equal to the height squared."));this.getImage(de)&&this.removeImage(de),this.addImage(de,{data:new o.b({width:Ce,height:Pe},Ke),pixelRatio:1,sdf:!1,usvg:!1,version:0});const Ze=this.imageManager.getImage(de,this.scope);Ze?(this._styleColorTheme.lut={image:Ze.data,data:N},z()):W(new Error("Missing LUT image."))}})}getLut(N){const E=this._styleColorThemeForScope[N];return E?E.lut:null}setProjection(N){N?this.stylesheet.projection=N: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.hasTerrain()||this.setTerrainForDraping():this.terrainSetForDrapingOnly()&&this.setTerrain(null,0))}_updateMapProjection(){this.isRootStyle()&&(this.map._useExplicitProjection?this.applyProjectionUpdate():this.map._prioritizeAndUpdateProjection(null,this.projection))}_loadSprite(N){const E=new AbortController;this._spriteRequest=E,function(z,W,Z,ne){let de,ye,Ce;const Pe=o.e.devicePixelRatio>1?"@2x":"";function Ke(Ze){Ce||Ze&&Z.aborted||(Ze&&(Ce=Ze),function(){if(Ce)ne(Ce);else if(de&&ye){const mt=o.e.getImageData(ye),vt={};for(const bt in de){const{width:St,height:Pt,x:Gt,y:as,sdf:ms,pixelRatio:Gs,stretchX:Ms,stretchY:Js,content:Os}=de[bt],Ks=new o.b({width:St,height:Pt});o.b.copy(mt,Ks,{x:Gt,y:as},{x:0,y:0},{width:St,height:Pt},null),vt[bt]={data:Ks,pixelRatio:Gs!==void 0?Gs:1,sdf:ms!==void 0&&ms,stretchX:Ms,stretchY:Js,content:Os,usvg:!1,version:0}}ne(null,vt)}}())}(async function(){const Ze=await W.transformRequest(W.normalizeSpriteURL(z,Pe,".json"),o.R.SpriteJSON,Z),{data:mt}=await o.g(Ze,Z);Ce||(de=mt)})().then(()=>Ke(void 0),Ze=>Ke(Ze)),async function(){const Ze=await W.transformRequest(W.normalizeSpriteURL(z,Pe,".png"),o.R.SpriteImage,Z),{data:mt}=await o.a(Ze,Z);Ce||(ye=mt)}().then(()=>Ke(void 0),Ze=>Ke(Ze))}(N,this.map._requestManager,E.signal,(z,W)=>{if(this._spriteRequest=null,z)this.dispatcher.broadcast("spriteLoaded",{scope:this.scope}),this.fire(new o.f(z));else if(W){const Z=new Map;for(const ne in W)Z.set(o.I.from(ne),W[ne]);this.addImages(Z,!0)}this.imageManager.setLoaded(!0,this.scope),this.fire(new o.h("data",{dataType:"style"}))})}addIconset(N,E){if(E.type==="sprite")return void this._loadSprite(E.url);const z=this.getOwnSourceCache(E.source);if(!z)return void this.fire(new o.f(new Error(`Source "${E.source}" as specified by iconset "${N}" does not exist and cannot be used as an iconset source`)));if(z.getSource().type!=="raster-array")return void this.fire(new o.f(new Error(`Source "${E.source}" as specified by iconset "${N}" is not a "raster-array" source and cannot be used as an iconset source`)));const W=new Xr(N,this.scope,z);this.imageManager.addImageProvider(W,this.scope)}removeIconset(N){this.imageManager.removeImageProvider(N,this.scope)}_loadIconset(N){if(!o.cg(N)&&this.map._spriteFormat!=="icon_set"||this.map._spriteFormat==="raster")return void this._loadSprite(N);const E=this.map._spriteFormat==="auto",z=new AbortController;this._spriteRequest=z,async function(W,Z,ne,de){try{const ye=await Z.transformRequest(Z.normalizeIconsetURL(W),o.R.Iconset,ne),{data:Ce}=await o.cC(ye,ne),Pe={},Ke=function(Ze){const mt={icons:[]};let vt;for(;vt=Ze.nextField(void 0);)vt===1&&mt.icons.push(se(Ze,Ze.readVarint()+Ze.pos));return mt}(new o.cB(Ce));for(const Ze of Ke.icons){const mt={version:1,pixelRatio:o.e.devicePixelRatio,content:zr(Ze),stretchX:Ze.metadata?rr(Ze.metadata.stretch_x_areas):void 0,stretchY:Ze.metadata?rr(Ze.metadata.stretch_y_areas):void 0,sdf:!1,usvg:!0,icon:Ze};Pe[Ze.name]=mt}de(null,Pe)}catch(ye){ne.aborted||de(ye)}}(N,this.map._requestManager,z.signal,(W,Z)=>{if(this._spriteRequest=null,W)E?this._loadSprite(N):(this.dispatcher.broadcast("spriteLoaded",{scope:this.scope}),this.fire(new o.f(W)));else if(Z){const ne=new Map;for(const de in Z)ne.set(o.I.from(de),Z[de]);this.addImages(ne,!0)}this.imageManager.setLoaded(!0,this.scope),this.fire(new o.h("data",{dataType:"style"}))})}_validateLayer(N){const E=this.getOwnSource(N.source);if(!E)return;const z=N.sourceLayer;z&&(E.type==="geojson"||E.vectorLayerIds&&!E.vectorLayerIds.includes(z))&&this.fire(new o.f(new Error(`Source layer "${z}" does not exist on source "${E.id}" as specified by style layer "${N.id}"`)))}loaded(){if(!this._loaded||Object.keys(this._changes.getUpdatedSourceCaches()).length)return!1;for(const N in this._sourceCaches)if(!this._sourceCaches[N].loaded())return!1;if(!this.imageManager.isLoaded()||this.imageManager.hasPatternsInFlight()||!this.modelManager.isLoaded()||this._styleColorTheme.lutLoading)return!1;for(const{style:N}of this.fragments)if(!N.loaded())return!1;return!0}_serializeImports(){if(this.stylesheet.imports)return this.stylesheet.imports.map((N,E)=>{const z=this.fragments[E];return z&&z.style&&(N.data=z.style.serialize()),N})}_serializeSources(){const N={};for(const E in this._sourceCaches){const z=this._sourceCaches[E].getSource();N[z.id]||(N[z.id]=z.serialize())}return N}_serializeLayers(N){const E=[];for(const z of N){const W=this._layers[z];W&&W.type!=="custom"&&E.push(W.serialize())}return E}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 N in this._sourceCaches)if(this._sourceCaches[N].hasTransition())return!0;for(const N in this._layers)if(this._layers[N].hasTransition())return!0;return!1}_updateDataDrivenEmissiveStrength(){for(const N in this._mergedLayers){const E=this._mergedLayers[N];if(E._transitionablePaint&&E._transitionablePaint._values){const z=E._transitionablePaint._values["line-emissive-strength"];if(z&&z.value&&z.value.isDataDriven())return void(this._hasDataDrivenEmissive=!0)}}this._hasDataDrivenEmissive=!1}hasDataDrivenEmissiveStrength(){return this._hasDataDrivenEmissive}get order(){return this.terrain?this._drapedFirstOrder:this._mergedOrder}_getOrder(N){return N?this.order:this._mergedOrder}isLayerDraped(N){return!!this.terrain&&N.isDraped(this.getLayerSourceCache(N))}_checkLoaded(){if(!this._loaded)throw new Error("Style is not done loading")}_checkLayer(N){const E=this.getOwnLayer(N);if(E)return E;this.fire(new o.f(new Error(`The layer '${N}' does not exist in the map's style.`)))}_checkSource(N){const E=this.getOwnSource(N);if(E)return E;this.fire(new o.f(new Error(`The source '${N}' does not exist in the map's style.`)))}_resolveLayerFragment(N){const E=this.getLayer(N);if(!E)return void this.fire(new o.f(new Error(`The layer '${N}' does not exist in the map's style.`)));const z=this.getFragmentStyle(E.scope);return z?{layer:E,fragment:z}:void 0}handleIdle(){const N=this.map.painter;N&&(N.context.sweepPendingPrograms(),this._programPrecompiler&&this._programPrecompiler.processQueue(N,this))}handleContextLost(){this._programPrecompiler&&this._programPrecompiler.reset()}update(N){if(!this._loaded)return;this.ambientLight&&this.ambientLight.recalculate(N),this.directionalLight&&this.directionalLight.recalculate(N);const E=this.calculateLightsBrightness();N.brightness=E||0;let z=!1;E!==this._brightness&&(this._brightness=E,z=!0),N.worldview!==this._worldview&&(this._worldview=N.worldview,z=!0),z&&this.dispatcher.broadcast("upsertRenderParams",{brightness:this._brightness,worldview:this._worldview});const W=this._changes.isDirty();let Z=!1;if(this._changes.isDirty()){const Ce=this._changes.getLayerUpdatesByScope();for(const Pe in Ce){const{updatedIds:Ke,removedIds:Ze}=Ce[Pe];(Ke||Ze)&&(this._updateWorkerLayers(Pe,Ke,Ze),Z=!0)}this.updateSourceCaches(),this._updateTilesForChangedImages(),this.updateLayers(N),this.light&&this.light.updateTransitions(N),this.ambientLight&&this.ambientLight.updateTransitions(N),this.directionalLight&&this.directionalLight.updateTransitions(N),this.fog&&this.fog.updateTransitions(N),this.snow&&this.snow.updateTransitions(N),this.rain&&this.rain.updateTransitions(N),this._changes.reset()}const ne={};for(const Ce in this._mergedSourceCaches){const Pe=this._mergedSourceCaches[Ce];ne[Ce]=Pe.used,Pe.used=!1,Pe.tileCoverLift=0}const de={};for(const Ce of this._mergedOrder){const Pe=this._mergedLayers[Ce];if((Pe.visibility!=="none"||Pe.hasTransition())&&Pe.recalculate(N,this._availableImages),!Pe.isHidden(N.zoom)){Pe.mayUse("HD")&&(Pe.prepare(),Lf()),Pe.mayUse("Standard")&&(Pe.prepare(),Bt());const Ke=this.getLayerSourceCache(Pe);Ke&&(Ke.used=!0,Ke.tileCoverLift=Math.max(Ke.tileCoverLift,Pe.tileCoverLift()))}if(Pe.source){const Ke=o.m(Pe.source,Pe.scope),Ze=this._mergedHdRoadCoverageSourceCaches[Ke];Ze&&!Ze.used&&(Ze.used=!0)}if(Pe.type==="fill-extrusion"){const Ke=o.m(Pe.source,Pe.scope);if(Ke in this._mergedFillExtrusionSourceCaches){const Ze=Pe.layout&&Pe.layout.get("source-max-zoom");if(Ze!=null){const mt=de[Ke];de[Ke]=mt==null?Ze:Math.min(mt,Ze)}}}}if(this._programPrecompiler&&this._programPrecompiler.needsBuild()){const Ce=this._mergedOrder.map(Pe=>this._mergedLayers[Pe]);this._programPrecompiler.buildQueue(Ce,N,this)}for(const Ce in this._mergedFillExtrusionSourceCaches)this._mergedFillExtrusionSourceCaches[Ce].setMaxzoomOverride(de[Ce]??null);this.terrain&&Z&&this.mergeLayers();const ye=this.imageManager.getPendingImageProviders();for(const Ce of ye)Ce.sourceCache.used=!0;for(const Ce in ne){const Pe=this._mergedSourceCaches[Ce];ne[Ce]!==Pe.used&&Pe.getSource().fire(new o.h("data",{sourceDataType:"visibility",dataType:"source",sourceId:Pe.getSource().id}))}this.light&&this.light.recalculate(N),this.terrain&&this.terrain.recalculate(N),this.fog&&this.fog.recalculate(N),this.snow&&this.snow.recalculate(N),this.rain&&this.rain.recalculate(N),this.z=N.zoom,this._markersNeedUpdate&&(this._updateMarkersOpacity(),this._markersNeedUpdate=!1),this.imageManager.clearUpdatedImages(this.scope),W&&this.fire(new o.h("data",{dataType:"style"}))}updateImageProviders(){const N=this.imageManager.getPendingImageProviders();for(const E of N){const z=E.resolvePendingRequests(),W=this.getFragmentStyle(E.scope);W&&W.addImages(z)}}_updateTilesForChangedImages(){const N={};for(const E in this._mergedSourceCaches){const z=this._mergedSourceCaches[E].getSource().scope;N[z]=N[z]||this._changes.getUpdatedImages(z),N[z].length!==0&&this._mergedSourceCaches[E].reloadTilesForDependencies(["icons","patterns"],N[z])}for(const E in N)this._changes.resetUpdatedImages(E)}_updateWorkerLayers(N,E,z){const W=this.getFragmentStyle(N);W&&this.dispatcher.broadcast("updateLayers",{layers:E?W._serializeLayers(E):[],scope:N,removedIds:z||[],options:W.options})}setState(N,E){if(this._checkLoaded(),Gn(this,$h(N)))return!1;if((N=o.dd(N)).layers=fp(N.layers),!Zd.diffStyles)throw new Error("Debug module not loaded; cannot diff style.");const z=Zd.diffStyles(this.serialize(),N).filter(ne=>!pa.has(ne.command));if(z.length===0)return!1;const W=z.filter(ne=>!Na.has(ne.command));if(W.length>0)throw new Error(`Unimplemented: ${W.map(ne=>ne.command).join(", ")}.`);const Z=[];return z.forEach(ne=>{Z.push(this[ne.command](...ne.args))}),E&&Promise.all(Z).then(E).catch(E),this.stylesheet=N,this.mergeAll(),this.dispatcher.broadcast("setLayers",{layers:this._serializeLayers(this._order),scope:this.scope,options:this.options}),!0}_updateWorkerImages(N=!1){this._availableImages=this.imageManager.listImages(this.scope);const E={scope:this.scope,images:this._availableImages};N&&(E.isSpriteLoaded=!0),this.dispatcher.broadcast("setImages",E)}_updateWorkerModels(){this._availableModels=this.modelManager.getModelURIs(this.scope),this.dispatcher.broadcast("setModels",{scope:this.scope,models:this._availableModels})}addImages(N,E){if(N.size===0)return E&&this.dispatcher.broadcast("spriteLoaded",{scope:this.scope}),this;for(const[z,W]of N.entries()){if(this.getImage(z))return this.fire(new o.f(new Error(`An image with the name "${z.name}" already exists.`)));this.imageManager.addImage(z,this.scope,W),this._changes.updateImage(z,this.scope)}return this._updateWorkerImages(E),this.fire(new o.h("data",{dataType:"style"})),this}addImage(N,E){return this.getImage(N)?this.fire(new o.f(new Error(`An image with the name "${N.name}" already exists.`))):(this.imageManager.addImage(N,this.scope,E),this._changes.updateImage(N,this.scope),this._updateWorkerImages(),this.fire(new o.h("data",{dataType:"style"})),this)}updateImage(N,E,z=!1){this.imageManager.updateImage(N,this.scope,E),z&&(this._changes.updateImage(N,this.scope),this._updateWorkerImages(),this.fire(new o.h("data",{dataType:"style"})))}getImage(N){return this.imageManager.getImage(N,this.scope)}removeImage(N){return this.getImage(N)?(this.imageManager.removeImage(N,this.scope),this._changes.updateImage(N,this.scope),this._updateWorkerImages(),this.fire(new o.h("data",{dataType:"style"})),this):this.fire(new o.f(new Error("No image with this name exists.")))}listImages(){return this._checkLoaded(),this._availableImages.slice()}getActualScope(){return this._importedAsBasemap?"basemap":this.scope}addModelURLs(N){return this.modelManager.addModelURLs(N,this.getActualScope()),this._updateWorkerModels(),this.fire(new o.h("data",{dataType:"style"})),this}addModel(N,E,z={}){return this._checkLoaded(),this._validate(At,`models.${N}`,E,null,z)||(this.modelManager.addModel(N,E,this.getActualScope()),this.fire(new o.h("data",{dataType:"style"}))),this}hasModel(N){return this.modelManager.hasModel(N,this.getActualScope())}removeModel(N){return this.hasModel(N)?(this.modelManager.removeModel(N,this.getActualScope(),!1,!0),this.fire(new o.h("data",{dataType:"style"})),this):this.fire(new o.f(new Error("No model with this ID exists.")))}listModels(){return this._checkLoaded(),this.modelManager.listModels(this.getActualScope())}addSource(N,E,z={}){if(this._checkLoaded(),this.getOwnSource(N)!==void 0)throw new Error(`There is already a source with ID "${N}".`);if(!E.type)throw new Error(`The type property must be defined, but only the following properties were given: ${Object.keys(E).join(", ")}.`);if(["vector","raster","geojson","video","image"].includes(E.type)&&this._validate(Af,`sources.${N}`,E,null,z))return;this.map&&this.map._collectResourceTiming&&(E.collectResourceTiming=!0);const W=Object.hasOwn(ef,E.type)&&!C1(E.type),Z=W?new zk(N,E,this.dispatcher,this):Z2(N,E,this.dispatcher,this);Z.scope=this.scope;const ne=ye=>{ye.setEventedParent(this,()=>({isSourceLoaded:this._isSourceCacheLoaded(ye.id),source:ye.serialize(),sourceId:ye.id}))};ne(Z);const de=ye=>{const Ce=(ye===o.bR.Symbol?"symbol:":ye===o.bR.FillExtrusion?"fill-extrusion:":"other:")+Z.id,Pe=o.m(Ce,this.scope),Ke=this._sourceCaches[Ce]=new uh(Pe,Z,ye);ye===o.bR.Symbol?this._symbolSourceCaches[Z.id]=Ke:ye===o.bR.FillExtrusion?this._fillExtrusionSourceCaches[Z.id]=Ke:this._otherSourceCaches[Z.id]=Ke,Ke.onAdd(this.map)};de(o.bR.Other),E.type!=="vector"&&E.type!=="geojson"||(de(o.bR.Symbol),E.type==="vector"&&de(o.bR.FillExtrusion)),Z.onAdd&&Z.onAdd(this.map),W&&async function(ye){if(C1(ye))return;const Ce=ef[ye];if(!Ce)throw new Error(`Unknown source type "${ye}"`);const Pe=await Ce();Pe&&!C1(ye)&&function(Ke,Ze){Rf[Ke]=Ze}(ye,Pe)}(E.type).then(()=>{const ye=C1(E.type),Ce=this._otherSourceCaches[N];if(!Ce||Ce.getSource()!==Z)return;if(!ye)return void this.fire(new o.f(new Error(`Could not load module for source type "${E.type}".`)));const Pe=Z2(N,E,this.dispatcher,this);Pe.scope=this.scope,ne(Pe),Ce.setSource(Pe),Pe.onAdd&&Pe.onAdd(this.map),this._changes.setDirty()}),z.isInitialLoad||(this.mergeSources(),this._changes.setDirty())}removeSource(N){this._checkLoaded();const E=this.getOwnSource(N);if(!E)throw new Error("There is no source with this ID");for(const W in this._layers)if(this._layers[W].source===N)return this.fire(new o.f(new Error(`Source "${N}" cannot be removed while layer "${W}" is using it.`)));if(this.terrain&&this.terrain.scope===this.scope&&this.terrain.get().source===N)return this.fire(new o.f(new Error(`Source "${N}" cannot be removed while terrain is using it.`)));if(this.stylesheet.iconsets){const W=Object.entries(this.stylesheet.iconsets).find(([Z,ne])=>ne.type==="source"&&ne.source===N);if(W)return this.fire(new o.f(new Error(`Source "${N}" cannot be removed while iconset "${W[0]}" is using it.`)))}const z=this.getOwnSourceCaches(N);for(const W of z){const Z=o.bV(W.id);delete this._sourceCaches[Z],this._changes.discardSourceCacheUpdate(W.id),W.fire(new o.h("data",{sourceDataType:"metadata",dataType:"source",sourceId:W.getSource().id})),W.setEventedParent(null),W.clearTiles()}return delete this._otherSourceCaches[N],delete this._symbolSourceCaches[N],delete this._fillExtrusionSourceCaches[N],this._hdCoverage&&delete this._hdCoverage.coverageSourceCaches[N],this._hdElevation&&delete this._hdElevation.elevationSourceCaches[o.m(N,this.scope)],this.mergeSources(),E.setEventedParent(null),E.onRemove&&E.onRemove(this.map),this.dispatcher.broadcast("removeSource",{type:E.type,source:N,scope:E.scope}),this._changes.setDirty(),this}setGeoJSONSourceData(N,E){this._checkLoaded(),this.getOwnSource(N).setData(E),this._changes.setDirty()}getOwnSource(N){const E=this.getOwnSourceCache(N);return E&&E.getSource()}getOwnSources(){const N=[];for(const E in this._otherSourceCaches){const z=this.getOwnSourceCache(E);z&&N.push(z.getSource())}return N}areTilesLoaded(){const N=this._mergedSourceCaches;for(const E in N){const z=N[E]._tiles;for(const W in z){const Z=z[W];if(Z.state!=="loaded"&&Z.state!=="errored")return!1}}return!0}setLights(N){if(this._checkLoaded(),this._programPrecompiler&&this._programPrecompiler.reset(),!N)return delete this.ambientLight,void delete this.directionalLight;const E=this._getTransitionParameters();for(const Z of N){if(this._validate(Ef,"lights",Z))return;switch(Z.type){case"ambient":if(this.ambientLight){const ne=this.ambientLight;ne.set(Z),ne.updateTransitions(E)}else this.ambientLight=new so(Z,Ni(),this.scope,this.options);break;case"directional":if(this.directionalLight){const ne=this.directionalLight;ne.set(Z),ne.updateTransitions(E)}else this.directionalLight=new so(Z,qo(),this.scope,this.options)}}const z=Object.assign(E,{worldview:this.map.getWorldview()}),W=new o.ai(this.z||0,z);this.ambientLight&&this.ambientLight.recalculate(W),this.directionalLight&&this.directionalLight.recalculate(W),this._brightness=this.calculateLightsBrightness(),this.dispatcher.broadcast("upsertRenderParams",{brightness:this._brightness})}calculateLightsBrightness(){const N=this.directionalLight,E=this.ambientLight;if(!N||!E)return;const z=Ze=>.2126*(Ze[0]<=.03928?Ze[0]/12.92:Math.pow((Ze[0]+.055)/1.055,2.4))+.7152*(Ze[1]<=.03928?Ze[1]/12.92:Math.pow((Ze[1]+.055)/1.055,2.4))+.0722*(Ze[2]<=.03928?Ze[2]/12.92:Math.pow((Ze[2]+.055)/1.055,2.4)),W=N.properties.get("color").toNonPremultipliedRenderColor(null).toArray01(),Z=N.properties.get("intensity"),ne=N.properties.get("direction"),de=1-o.de(ne.x,ne.y,ne.z)[2]/90,ye=z(W)*Z*de,Ce=E.properties.get("color").toNonPremultipliedRenderColor(null).toArray01(),Pe=E.properties.get("intensity"),Ke=z(Ce)*Pe;return Number(((ye+Ke)/2).toFixed(6))}getBrightness(){return this._brightness}getLights(){if(!this.enable3dLights())return null;const N=[];return this.directionalLight&&N.push(this.directionalLight.get()),this.ambientLight&&N.push(this.ambientLight.get()),N}enable3dLights(){return!!this.ambientLight&&!!this.directionalLight}getFragmentStyle(N){if(N==null||N===""&&this.isRootStyle())return this;if(o.df(N)){const E=o.dg(N),z=this.fragments.find(({id:Z})=>Z===E);if(!z)return;const W=o.bV(N);return z.style.getFragmentStyle(W)}{const E=this.fragments.find(({id:z})=>z===N);return E?E.style:void 0}}setFeaturesetSelectors(N){if(!N)return;const E=(z,W="")=>`${z}::${W}`;this._featuresetSelectors={};for(const z in N){const W={},Z=this._featuresetSelectors[z]=[];for(const ne of N[z].selectors){if(ne.featureNamespace){const ye=this.getOwnLayer(ne.layer);if(!ye){o.w(`Layer is undefined for selector: ${ne.layer}`);continue}const Ce=E(ye.source,ye.sourceLayer);if(Ce in W&&W[Ce]!==ne.featureNamespace){o.w(`"featureNamespace ${ne.featureNamespace} of featureset ${z}'s selector is not associated to the same source, skip this selector`);continue}W[Ce]=ne.featureNamespace}let de;if(ne.properties)for(const ye in ne.properties){const Ce=o.c(ne.properties[ye]);Ce.result==="success"&&(de=de||{},de[ye]=Ce.value)}Z.push({layerId:ne.layer,namespace:ne.featureNamespace,properties:de,uniqueFeatureID:ne._uniqueFeatureID})}}}getFeaturesetDescriptors(N){const E=this.getFragmentStyle(N);if(!E||!E.stylesheet.featuresets)return[];const z=[];for(const W in E.stylesheet.featuresets)z.push({featuresetId:W,importId:E.scope?E.scope:void 0});return z}getFeaturesetLayers(N,E){const z=this.getFragmentStyle(E),W=z.stylesheet.featuresets;if(!W||!W[N])return this.fire(new o.f(new Error(`The featureset '${N}' does not exist in the map's style and cannot be queried.`))),[];const Z=[];for(const ne of W[N].selectors){const de=z.getOwnLayer(ne.layer);de&&Z.push(de)}return Z}getConfigProperty(N,E){const z=this.getFragmentStyle(N);if(!z)return null;const W=o.m(E,z.scope),Z=z.options.get(W),ne=Z?Z.value||Z.default:null;return ne?ne.serialize():null}isIndoorEnabled(){return this._indoorEnabled}getIndoorSourceLayers(N,E){const z=o.m(N,E);return this._mergedIndoor[z]}setIndoorData(N,E){this.indoorManager&&this.indoorManager.setIndoorData(E)}updateIndoorDependentLayers(){this._updateLayers(this._dependentLayerIds(N=>N.isIndoorDependent)),this.map._styleDirty=!0,this.map.triggerRepaint()}setConfigProperty(N,E,z){const W=this.getFragmentStyle(N);if(!W)return;const Z=W.stylesheet.schema;if(!Z||!Z[E])return;const ne=o.dh(z,Z[E]);if(ne.result!=="success")return void Gn(this,ne.value);const de=ne.value.expression,ye=o.m(E,W.scope),Ce=W.options.get(ye);if(!Ce)return;let Pe;const{minValue:Ke,maxValue:Ze,stepValue:mt,type:vt,values:bt}=Z[E],St=o.dh(Z[E].default,Z[E]);St.result==="success"&&(Pe=St.value.expression),Pe?(this.options.set(ye,{...Ce,value:de,default:Pe,minValue:Ke,maxValue:Ze,stepValue:mt,type:vt,values:bt}),this.updateConfigDependencies(E)):this.fire(new o.f(new Error(`No schema defined for the config option "${E}" in the "${N}" fragment.`)))}getConfig(N){const E=this.getFragmentStyle(N);if(!E)return null;const z=E.stylesheet.schema;if(!z)return null;const W={};for(const Z in z){const ne=o.m(Z,E.scope),de=E.options.get(ne),ye=de?de.value||de.default:null;W[Z]=ye?ye.serialize():null}return W}setConfig(N,E){const z=this.getFragmentStyle(N);z&&(z.updateConfig(E,z.stylesheet.schema),this.updateConfigDependencies())}getSchema(N){const E=this.getFragmentStyle(N);return E?E.stylesheet.schema:null}setSchema(N,E){const z=this.getFragmentStyle(N);z&&(z.stylesheet.schema=E,z.updateConfig(z._config,E),this.updateConfigDependencies())}updateConfig(N,E){if(this._config=N,N||E)if(E)for(const z in E){let W,Z;const ne=o.dh(E[z].default,E[z]);if(ne.result==="success"&&(W=ne.value.expression),N&&N[z]!==void 0){const Ze=o.dh(N[z],E[z]);Ze.result==="success"&&(Z=Ze.value.expression)}const{minValue:de,maxValue:ye,stepValue:Ce,type:Pe,values:Ke}=E[z];if(W){const Ze=o.m(z,this.scope);this.options.set(Ze,{default:W,value:Z,minValue:de,maxValue:ye,stepValue:Ce,type:Pe,values:Ke})}else this.fire(new o.f(new Error(`No schema defined for config option "${z}".`)))}else this.fire(new o.f(new Error("Attempting to set config for a style without schema.")))}_updateLayers(N){for(const E of N){const z=this.getLayer(E);z&&(z.possiblyEvaluateVisibility(),this._updateLayer(z),this._changes.setDirty())}}_dependentLayerIds(N){const E=[];for(const[z,W]of this._layerExpressionDependencies)N(W)&&E.push(z);return E}updateConfigDependencies(N){this._updateLayers(this._dependentLayerIds(E=>N?E.hasConfigDependency(N):E.isConfigDependent)),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(E=>{const z=E._styleColorTheme.colorThemeOverride?E._styleColorTheme.colorThemeOverride:E._styleColorTheme.colorTheme;if(z){const W=E._evaluateColorThemeData(z);(!E._styleColorTheme.lut&&W!==""||E._styleColorTheme.lut&&W!==E._styleColorTheme.lut.data)&&E.setColorTheme(z)}}),this._updateIndoorEnabled(),this._changes.setDirty()}addLayer(N,E,z={}){this._checkLoaded();const W=N.id;if(this._layers[W])return void this.fire(new o.f(new Error(`Layer with id "${W}" already exists on this map`)));let Z;if(N.type==="custom"){if(Gn(this,o.di(N)))return;Z=o.dj(N,this.scope,this._styleColorTheme.lut,this.options)}else{if(typeof N.source=="object"&&(this.addSource(W,N.source),N=o.dd(N),N=Object.assign(N,{source:W})),this._validate(Kx,`layers.${W}`,N,{arrayIndex:-1},z))return;Z=o.dj(N,this.scope,this._styleColorTheme.lut,this.options),this._validateLayer(Z),Z.setEventedParent(this,{layer:{id:W}})}this._layerExpressionDependencies.set(Z.fqid,new U(Z));let ne=this._order.length;if(E){const Pe=this._order.indexOf(E);if(Pe===-1)return void this.fire(new o.f(new Error(`Layer with id "${E}" does not exist on this map.`)));Z.slot&&Z.slot!==this._layers[E].slot?o.w(`Layer with id "${E}" has a different slot. Layers can only be rearranged within the same slot.`):ne=Pe}this._order.splice(ne,0,W),this._handleLayerOrderChange(),this._layers[W]=Z;const de=this.getOwnLayerSourceCache(Z),ye=!!this.directionalLight&&this.directionalLight.shadowsEnabled();de&&Z.canCastShadows()&&ye&&(de.castsShadows=!0);const Ce=this._changes.getRemovedLayer(Z);if(Ce&&Z.source&&de&&Z.type!=="custom"){this._changes.discardLayerRemoval(Z);const Pe=o.m(Z.source,Z.scope);Ce.type!==Z.type?this._changes.updateSourceCache(Pe,"clear"):(this._changes.updateSourceCache(Pe,"reload"),de.pause())}this._updateLayer(Z),Z.onAdd&&Z.onAdd(this.map),Z.scope=this.scope,this.mergeLayers()}moveLayer(N,E){this._checkLoaded();const z=this._checkLayer(N);if(!z||N===E)return;const W=this._order.indexOf(N);this._order.splice(W,1);let Z=this._order.length;if(E){const ne=this._order.indexOf(E);if(ne===-1)return void this.fire(new o.f(new Error(`Layer with id "${E}" does not exist on this map.`)));z.slot&&z.slot!==this._layers[E].slot?o.w(`Layer with id "${E}" has a different slot. Layers can only be rearranged within the same slot.`):Z=ne}this._order.splice(Z,0,N),this._changes.setDirty(),this._handleLayerOrderChange(),this.mergeLayers()}removeLayer(N){this._checkLoaded();const E=this._checkLayer(N);if(!E)return;E.setEventedParent(null);const z=this._order.indexOf(N);this._order.splice(z,1),delete this._layers[N],this._changes.setDirty(),this._handleLayerOrderChange(),this._layerExpressionDependencies.delete(E.fqid),this._changes.removeLayer(E);const W=this.getOwnLayerSourceCache(E);if(W&&W.castsShadows){let Z=!1;for(const ne in this._layers)if(this._layers[ne].source===E.source&&this._layers[ne].canCastShadows()){Z=!0;break}W.castsShadows=Z}E.onRemove&&E.onRemove(this.map),this.mergeLayers()}getOwnLayer(N){return this._layers[N]}hasLayer(N){return N in this._mergedLayers}hasLayerType(N){for(const E in this._layers)if(this._layers[E].type===N)return!0;return!1}setLayerZoomRange(N,E,z){this._checkLoaded();const W=this._checkLayer(N);W&&(W.minzoom===E&&W.maxzoom===z||(E!=null&&(W.minzoom=E),z!=null&&(W.maxzoom=z),this._updateLayer(W)))}getSlots(){return this._checkLoaded(),this._mergedSlots}setSlot(N,E){this._checkLoaded();const z=this._checkLayer(N);z&&z.slot!==E&&(z.slot=E,this._updateLayer(z))}setFilter(N,E,z={}){this._checkLoaded();const W=this._checkLayer(N);if(!W||o.O(W.filter,E))return;const Z=this._layerExpressionDependencies.get(W.fqid);if(E==null)return W.filter=void 0,Z&&Z.invalidateFilter(),void this._updateLayer(W);this._validate(Tt,`layers.${W.id}.filter`,E,{layerType:W.type},z)||(W.filter=o.dd(E),Z&&Z.invalidateFilter(),this._updateLayer(W))}getFilter(N){const E=this._checkLayer(N);if(E)return o.dd(E.filter)}setLayoutProperty(N,E,z,W={}){this._checkLoaded();const Z=this._checkLayer(N);if(Z&&!o.O(Z.getLayoutProperty(E),z)){if(z!=null&&(!W||W.validate!==!1)&&Gn(Z,ot.call($h,{key:`layers.${N}.layout.${E}`,layerType:Z.type,objectKey:E,value:z,styleSpec:o.s,style:{glyphs:!0,sprite:!0}})))return;Z.setLayoutProperty(E,z),this._updateLayer(Z)}}getLayerProperty(N,E){const z=this._checkLayer(N);if(z){switch(E){case"minzoom":return z.minzoom;case"maxzoom":return z.maxzoom;case"filter":return this.getFilter(N);case"slot":return z.slot;case"appearances":return z.getAppearances().map(W=>W.serialize())}return z.isPaintProperty(E)?this.getPaintProperty(N,E):this.getLayoutProperty(N,E)}}setLayerProperty(N,E,z,W={}){this._checkLoaded();const Z=this._checkLayer(N);if(Z){switch(E){case"appearances":return Z.setAppearances(z),void this._updateLayer(Z);case"minzoom":return this.setLayerZoomRange(N,z);case"maxzoom":return this.setLayerZoomRange(N,null,z);case"filter":return this.setFilter(N,z,W);case"slot":return this.setSlot(N,z)}Z.isPaintProperty(E)?this.setPaintProperty(N,E,z,W):this.setLayoutProperty(N,E,z,W)}}getLayoutProperty(N,E){const z=this._checkLayer(N);if(z)return z.getLayoutProperty(E)}setPaintProperty(N,E,z,W={}){this._checkLoaded();const Z=this._checkLayer(N);Z&&(o.O(Z.getPaintProperty(E),z)||(z==null||W&&W.validate===!1||!Gn(Z,He.call($h,{key:`layers.${N}.paint.${E}`,layerType:Z.type,objectKey:E,value:z,styleSpec:o.s})))&&(Z.setPaintProperty(E,z)&&this._updateLayer(Z),this._changes.updatePaintProperties(Z)))}getPaintProperty(N,E){const z=this._checkLayer(N);if(z)return z.getPaintProperty(E)}setFeatureState(N,E){if(this._checkLoaded(),"target"in N){if("featuresetId"in N.target){const{featuresetId:ye,importId:Ce}=N.target,Pe=this.getFragmentStyle(Ce),Ke=Pe.getFeaturesetLayers(ye);for(const{source:Ze,sourceLayer:mt}of Ke)Pe.setFeatureState({id:N.id,source:Ze,sourceLayer:mt},E)}else if("layerId"in N.target){const ye=this._resolveLayerFragment(N.target.layerId);ye==null||ye.fragment.setFeatureState({id:N.id,source:ye.layer.source,sourceLayer:ye.layer.sourceLayer},E)}return}const z=N.source,W=N.sourceLayer,Z=this._checkSource(z);if(!Z)return;const ne=Z.type;if(ne==="geojson"&&W)return void this.fire(new o.f(new Error("GeoJSON sources cannot have a sourceLayer parameter.")));if(ne==="vector"&&!W)return void this.fire(new o.f(new Error("The sourceLayer parameter must be provided for vector source types.")));N.id===void 0&&this.fire(new o.f(new Error("The feature id parameter must be provided.")));const de=this.getOwnSourceCaches(z);for(const ye of de)ye.setFeatureState(W,N.id,E)}removeFeatureState(N,E){if(this._checkLoaded(),"target"in N){if("featuresetId"in N.target){const{featuresetId:ye,importId:Ce}=N.target,Pe=this.getFragmentStyle(Ce),Ke=Pe.getFeaturesetLayers(ye);for(const{source:Ze,sourceLayer:mt}of Ke)Pe.removeFeatureState({id:N.id,source:Ze,sourceLayer:mt},E)}else if("layerId"in N.target){const ye=this._resolveLayerFragment(N.target.layerId);ye==null||ye.fragment.removeFeatureState({id:N.id,source:ye.layer.source,sourceLayer:ye.layer.sourceLayer},E)}return}const z=N.source,W=this._checkSource(z);if(!W)return;const Z=W.type,ne=Z==="vector"?N.sourceLayer:void 0;if(Z==="vector"&&!ne)return void this.fire(new o.f(new Error("The sourceLayer parameter must be provided for vector source types.")));if(E&&typeof N.id!="string"&&typeof N.id!="number")return void this.fire(new o.f(new Error("A feature id is required to remove its specific state property.")));const de=this.getOwnSourceCaches(z);for(const ye of de)ye.removeFeatureState(ne,N.id,E)}getFeatureState(N){if(this._checkLoaded(),"target"in N){let Z;if("featuresetId"in N.target){const{featuresetId:ne,importId:de}=N.target,ye=this.getFragmentStyle(de),Ce=ye.getFeaturesetLayers(ne);for(const{source:Pe,sourceLayer:Ke}of Ce){const Ze=ye.getFeatureState({id:N.id,source:Pe,sourceLayer:Ke});if(Ze&&!Z)Z=Ze;else if(!o.O(Z,Ze))return void this.fire(new o.f(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 N.target){const ne=this._resolveLayerFragment(N.target.layerId);Z=ne==null?void 0:ne.fragment.getFeatureState({id:N.id,source:ne.layer.source,sourceLayer:ne.layer.sourceLayer})}return Z}const E=N.source,z=N.sourceLayer,W=this._checkSource(E);if(W){if(W.type!=="vector"||z)return N.id===void 0&&this.fire(new o.f(new Error("The feature id parameter must be provided."))),this.getOwnSourceCaches(E)[0].getFeatureState(z,N.id);this.fire(new o.f(new Error("The sourceLayer parameter must be provided for vector source types.")))}}resetFeatureStates(N){if(this._checkLoaded(),"featuresetId"in N){const{featuresetId:E,importId:z}=N,W=this.getFragmentStyle(z);if(!W)return;const Z=W.getFeaturesetLayers(E);for(const{source:ne,sourceLayer:de}of Z)W.removeFeatureState({source:ne,sourceLayer:de})}else{const E=this._resolveLayerFragment(N.layerId);E==null||E.fragment.removeFeatureState({source:E.layer.source,sourceLayer:E.layer.sourceLayer})}}setTransition(N){return this.stylesheet.transition={...this.stylesheet.transition,...N},this.transition=this.stylesheet.transition,this}getTransition(){return{...this.stylesheet.transition}}setWorldview(N){N!==this._worldview&&(this._worldview=N,this.dispatcher.broadcast("upsertRenderParams",{worldview:this._worldview}),this.reloadSources())}serialize(){this._checkLoaded();const N=this.getTerrain(),E=N&&this.terrain&&this.terrain.scope===this.scope?N:this.stylesheet.terrain;return o.dk({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:E,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)},z=>z!==void 0)}_updateFilteredLayers(N){for(const E of Object.values(this._mergedLayers))N(E)&&this._updateLayer(E)}_updateLayer(N){this._changes.updateLayer(N);const E=this.getLayerSourceCache(N),z=o.m(N.source,N.scope),W=this._changes.getUpdatedSourceCaches();N.source&&!W[z]&&E&&E.getSource().type!=="raster"&&(this._changes.updateSourceCache(z,"reload"),E.pause()),N.invalidateCompiledFilter()}_flattenAndSortRenderedFeatures(N){const E=de=>this._mergedLayers[de].is3D(!!this.terrain),z=this.order,W={},Z=[];for(let de=z.length-1;de>=0;de--){const ye=z[de];if(E(ye)){W[ye]=de;for(const Ce of N){const Pe=Ce[ye];if(Pe)for(const Ke of Pe)Z.push(Ke)}}}Z.sort((de,ye)=>ye.intersectionZ-de.intersectionZ);const ne=[];for(let de=z.length-1;de>=0;de--){const ye=z[de];if(E(ye))for(let Ce=Z.length-1;Ce>=0;Ce--){const Pe=Z[Ce].feature;if(Pe.layer&&W[Pe.layer.id]{if(Yi.has(Pe.type))return;const Ke=this.getOwnLayerSourceCache(Pe),Ze=Z[Ke.id]=Z[Ke.id]||{sourceCache:Ke,layers:{},has3DLayers:!1};Pe.is3D(!!this.terrain)&&(Ze.has3DLayers=!0),Ze.layers[Pe.fqid]=Ze.layers[Pe.fqid]||{styleLayer:Pe,targets:[]},Ze.layers[Pe.fqid].targets.push({filter:W})};if(E&&E.layers){if(!Array.isArray(E.layers))return this.fire(new o.f(new Error("parameters.layers must be an Array."))),[];for(const Pe of E.layers){const Ke=this._layers[Pe];if(!Ke)return this.fire(new o.f(new Error(`The layer '${Pe}' does not exist in the map's style and cannot be queried for features.`))),[];ne(Ke)}}else for(const Pe in this._layers)ne(this._layers[Pe]);const de=this._queryRenderedFeatures(N,Z,z),ye=this._flattenAndSortRenderedFeatures(de),Ce=[];for(const Pe of ye)o.bW(Pe.layer.id)===this.scope&&Ce.push(Pe);return Ce}queryRenderedFeatureset(N,E,z){let W;E&&!Array.isArray(E)&&E.filter&&(this._validate(Tt,"queryRenderedFeatures.filter",E.filter,null,E),W=o.bv(E.filter));const Z="mock",ne=[];if(E&&E.target)ne.push({...E,targetId:Z,filter:W});else{const Pe=this.getFeaturesetDescriptors();for(const Ke of Pe)ne.push({targetId:Z,filter:W,target:Ke});for(const{style:Ke}of this.fragments){const Ze=Ke.getFeaturesetDescriptors();for(const mt of Ze)ne.push({targetId:Z,filter:W,target:mt})}}const de=this.queryRenderedTargets(N,ne,z),ye=[],Ce=new Set;for(const Pe of de)for(const Ke of Pe.variants[Z])g4(Ke,Pe,Ce)||ye.push(new o.dl(Pe,Ke));return ye}queryRenderedTargets(N,E,z){const W={},Z=(de,ye,Ce,Pe)=>{const Ke=W[ye.id]=W[ye.id]||{sourceCache:ye,layers:{},has3DLayers:!1};if(Ke.layers[de.fqid]=Ke.layers[de.fqid]||{styleLayer:de,targets:[]},de.is3D(!!this.terrain)&&(Ke.has3DLayers=!0),!Pe)return Ce.uniqueFeatureID=!1,void Ke.layers[de.fqid].targets.push(Ce);Ke.layers[de.fqid].targets.push({...Ce,namespace:Pe.namespace,properties:Pe.properties,uniqueFeatureID:Pe.uniqueFeatureID})};for(const de of E)if("featuresetId"in de.target){const{featuresetId:ye,importId:Ce}=de.target,Pe=this.getFragmentStyle(Ce);if(!Pe||!Pe._featuresetSelectors)continue;const Ke=Pe._featuresetSelectors[ye];if(!Ke){this.fire(new o.f(new Error(`The featureset '${ye}' does not exist in the map's style and cannot be queried for features.`)));continue}for(const Ze of Ke){const mt=Pe.getOwnLayer(Ze.layerId);mt&&!Yi.has(mt.type)&&Z(mt,Pe.getOwnLayerSourceCache(mt),de,Ze)}}else if("layerId"in de.target){const{layerId:ye}=de.target,Ce=this.getLayer(ye);if(!Ce||Yi.has(Ce.type))continue;Z(Ce,this.getLayerSourceCache(Ce),de)}const ne=this._queryRenderedFeatures(N,W,z);return this._flattenAndSortRenderedFeatures(ne)}_queryRenderedFeatures(N,E,z){const W=[],Z=!!this.map._showQueryGeometry,ne=wv.createFromScreenPoints(N,z);for(const de in E){const ye=x4(ne,E[de],this._availableImages,z,Z,this.getActualScope());Object.keys(ye).length&&W.push(ye)}if(this.placement)for(const de in E){if(E[de].sourceCache._renderSourceType!==o.bR.Symbol)continue;const ye=fA(ne.screenGeometry,E[de],this._availableImages,this.placement.collisionIndex,this.placement.retainedQueryData,this.map.getWorldview());Object.keys(ye).length&&W.push(ye)}return W}querySourceFeatures(N,E){const z=E&&E.filter;z&&this._validate(Tt,"querySourceFeatures.filter",z,null,E);let W=[];const Z=this.getOwnSourceCaches(N);for(const ne of Z)W=W.concat(Oy(ne,E));return W}getFlatLight(){return this.light.getLight()}setFlatLight(N,E,z={}){this._checkLoaded();const W=this.light.getLight();let Z=!1;for(const de in N)if(!o.O(N[de],W[de])){Z=!0;break}if(!Z)return;const ne=this._getTransitionParameters();this.light.setLight(N,E,z),this.light.updateTransitions(ne)}hasTerrain(){return!!this.terrain&&this.terrain.drapeRenderMode===1}getTerrain(){return this.hasTerrain()?this.terrain.get():null}setTerrainForDraping(){this.setTerrain({source:"",exaggeration:0},0)}checkCanvasFingerprintNoise(){this.disableElevatedTerrain===void 0&&(this.disableElevatedTerrain=o.e.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(N,E=1){if(this._checkLoaded(),!N)return this.terrainSetForDrapingOnly()||(delete this.terrain,this.map.transform.projection.requiresDraping&&this.setTerrainForDraping()),E===0&&delete this.terrain,N===null?this.stylesheet.terrain=null:delete this.stylesheet.terrain,this._force3DLayerUpdate(),void(this._markersNeedUpdate=!0);this.checkCanvasFingerprintNoise();let z=N;const W=!("source"in N)||N.source==null;if(E===1){if(this.disableElevatedTerrain)return;if("source"in z&&typeof z.source=="object"){const de="terrain-dem-src";this.addSource(de,z.source),z=o.dd(z),z=Object.assign(z,{source:de})}const Z={...z},ne={};if(this.terrain&&W){Z.source=this.terrain.get().source;const de=this.terrain?this.getFragmentStyle(this.terrain.scope):null;de&&(ne.style=de.serialize())}if(this._validate(Wx,"terrain",Z,ne))return}if(!this.terrain||this.terrain.scope!==this.scope&&!W||this.terrain&&E!==this.terrain.drapeRenderMode){if(!z)return;this._createTerrain(z,E),this.fire(new o.h("data",{dataType:"style"}))}else{const Z=this.terrain,ne=Z.get();for(const de of Object.keys(o.s.terrain))!Object.hasOwn(z,de)&&o.s.terrain[de].default&&(z[de]=o.s.terrain[de].default);for(const de in N)if(!o.O(N[de],ne[de])){Z.set(N,this.options),this.stylesheet.terrain=N;const ye=this._getTransitionParameters({duration:0});Z.updateTransitions(ye),this.fire(new o.h("data",{dataType:"style"}));break}}this.mergeTerrain(),this.updateDrapeFirstLayers(),this._markersNeedUpdate=!0}_createFog(N){const E=this.fog=new rn(N,this.map.transform,this.scope,this.options);this.stylesheet.fog=E.get();const z=this._getTransitionParameters({duration:0});E.updateTransitions(z)}_createSnow(N){const E=this.snow=new Zn(N,this.map.transform,this.scope,this.options);this.stylesheet.snow=E.get();const z=this._getTransitionParameters({duration:0});E.updateTransitions(z)}_createRain(N){const E=this.rain=new la(N,this.map.transform,this.scope,this.options);this.stylesheet.rain=E.get();const z=this._getTransitionParameters({duration:0});E.updateTransitions(z)}_updateMarkersOpacity(){this.map._markers.length!==0&&this.map._requestDomTask(()=>{for(const N of this.map._markers)N._evaluateOpacity()})}getFog(){return this.fog?this.fog.get():null}setFog(N){if(this._checkLoaded(),N)if(this.fog){const E=this.fog;if(!o.O(E.get(),N)){E.set(N,this.options),this.stylesheet.fog=E.get();const z=this._getTransitionParameters({duration:0});E.updateTransitions(z)}}else this._createFog(N);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(N){if(this._checkLoaded(),!N)return delete this.snow,void delete this.stylesheet.snow;if(this.snow){const E=this.snow;if(!o.O(E.get(),N)){E.set(N,this.options),this.stylesheet.snow=E.get();const z=this._getTransitionParameters({duration:0});E.updateTransitions(z)}}else this._createSnow(N);this._markersNeedUpdate=!0}getRain(){return this.rain?this.rain.get():null}setRain(N){if(this._checkLoaded(),!N)return delete this.rain,void delete this.stylesheet.rain;if(this.rain){const E=this.rain;if(!o.O(E.get(),N)){E.set(N,this.options),this.stylesheet.rain=E.get();const z=this._getTransitionParameters({duration:0});E.updateTransitions(z)}}else this._createRain(N);this._markersNeedUpdate=!0}_reloadColorTheme(){const N=()=>{for(const W in this._layers)this._layers[W].lut=this._styleColorTheme.lut;for(const W in this._sourceCaches)this._sourceCaches[W].clearTiles()},E=this._styleColorTheme.colorThemeOverride?this._styleColorTheme.colorThemeOverride:this._styleColorTheme.colorTheme;if(!E)return this._styleColorTheme.lut=null,void N();const z=this._evaluateColorThemeData(E);this._loadColorTheme(z).then(()=>{this.fire(new o.h("colorthemeset")),N()}).catch(W=>{o.w(`Couldn't set color theme: ${W}`)})}setColorTheme(N){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=N,this._reloadColorTheme()}setImportColorTheme(N,E){const z=this.getFragmentStyle(N);z&&(z._styleColorTheme.colorThemeOverride=E,z._reloadColorTheme())}_getTransitionParameters(N){return{now:o.e.now(),transition:Object.assign(this.transition,N)}}updateDrapeFirstLayers(){if(!this.terrain)return;const N=[],E=[];for(const z of this._mergedOrder)this.isLayerDraped(this._mergedLayers[z])?N.push(z):E.push(z);this._drapedFirstOrder=[],this._drapedFirstOrder.push(...N),this._drapedFirstOrder.push(...E)}_createTerrain(N,E){const z=this.terrain=new ns(N,E,this.scope,this.options,this.map.getWorldview());E===1&&(this.stylesheet.terrain=N),this.mergeTerrain(),this.updateDrapeFirstLayers(),this._force3DLayerUpdate();const W=this._getTransitionParameters({duration:0});z.updateTransitions(W)}_force3DLayerUpdate(){for(const N in this._layers){const E=this._layers[N];E.type==="fill-extrusion"&&this._updateLayer(E)}}_forceSymbolLayerUpdate(){for(const N in this._layers){const E=this._layers[N];E.type==="symbol"&&this._updateLayer(E)}}_validate(N,E,z,W,Z={}){if(Z&&Z.validate===!1)return!1;const ne={...this.serialize()};return Gn(this,N.call($h,{key:E,style:ne,value:z,styleSpec:o.s,...W}))}_remove(){this._programPrecompiler&&(this._programPrecompiler.reset(),this._programPrecompiler=null),this._request&&(this._request.cancel(),this._request=null),this._spriteRequest&&(this._spriteRequest.abort(),this._spriteRequest=null),o.dm.off("pluginStateChange",this._rtlTextPluginCallback);for(const N in this._mergedLayers)this._mergedLayers[N].setEventedParent(null);for(const N in this._mergedSourceCaches){const E=this._mergedSourceCaches[N];E.clearTiles(),E.setEventedParent(null);const z=E.getSource();z&&z.onRemove&&z.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&&this.indoorManager.destroy(),this.isRootStyle()&&(this.imageManager.setEventedParent(null),this.modelManager.setEventedParent(null),this.modelManager.destroy(),this.dispatcher.remove())}clearSource(N){const E=this.getSourceCaches(N);for(const z of E)z.clearTiles()}clearSources(){for(const N in this._mergedSourceCaches)this._mergedSourceCaches[N].clearTiles()}clearLayers(){for(const N in this._mergedLayers){const E=this._mergedLayers[N];E._clear&&E._clear()}}reloadSource(N){const E=this.getSourceCaches(N);for(const z of E)z.resume(),z.reload()}reloadSources(){for(const N of this.getSources())N.reload&&N.reload()}reloadModels(){this.modelManager.reloadModels(""),this.forEachFragmentStyle(N=>{N.modelManager.reloadModels(N.scope)})}updateSources(N){let E;this.directionalLight&&(E=o.dn(this.directionalLight));const z=new Set,W=new Set,Z=new Set;for(const ne in this._mergedLayers){const de=this._mergedLayers[ne];de.type==="building"?z.add(de.source):de.type!=="raster"||!de.paint||de.paint.get("raster-elevation-reference")!=="ground"&&de.paint.get("raster-allow-draping")!==!1||Z.add(de.source),de.hasElevation()&&!W.has(de.source)&&W.add(de.source)}this.updateFrcCoverageFadeRange();for(const ne in this._mergedSourceCaches){const de=this._mergedSourceCaches[ne],ye=W.has(de._source.id);de._isRasterElevatedOverTerrain=Z.has(de._source.id),z.has(de._source.id)&&(de._source.reparseOverscaled=!1),de.update(N,void 0,void 0,E,ye)}this.updateFrcCoverage(),this.updateElevationCoverage(),wi.markElevationIngestSourceCachesUsed&&wi.markElevationIngestSourceCachesUsed(this)}_reloadSources(){for(const N in this._sourceCaches){const E=this._sourceCaches[N];E.resume(),E.reload()}}updateFrcCoverageFadeRange(){this.map.painter&&wi.updateFrcCoverageFadeRange&&wi.updateFrcCoverageFadeRange(this,this.map.painter)}updateFrcCoverage(){this._hdCoverage&&wi.updateFrcCoverage&&wi.updateFrcCoverage(this,this._hdCoverage)}updateElevationCoverage(){this.isRootStyle()&&wi.setupAndUpdateElevationCoverage&&wi.setupAndUpdateElevationCoverage(this)}_handleLayerOrderChange(){this._requestFullLabelPlacement(),this.fire(new o.h("neworder"))}_requestFullLabelPlacement(){this.pauseablePlacement||(this.pauseablePlacement=new ft),this.pauseablePlacement.requestFullPlacement()}_setLabelPlacementStale(){this.placement&&this.placement.setStale()}_updatePlacement(N,E,z,W,Z,ne){this.pauseablePlacement||(this.pauseablePlacement=new ft);let de=!1,ye=!1;const Ce={},Pe={};for(const St of this._mergedOrder){const Pt=this._mergedLayers[St];if(Pt.type!=="symbol")continue;const Gt=o.m(Pt.source,Pt.scope);let as=Ce[Gt];if(!as){const Gs=this.getLayerSourceCache(Pt);if(!Gs)continue;const Ms=Gs.getRenderableIds(!0).map(Js=>Gs.getTileByID(Js));Pe[Gt]=Ms.slice(),as=Ce[Gt]=Ms.sort((Js,Os)=>Os.tileID.overscaledZ-Js.tileID.overscaledZ||(Js.tileID.isLessThan(Os.tileID)?-1:1))}const ms=this.crossTileSymbolIndex.addLayer(Pt,as,N.center.lng,N.projection);de=de||ms}this.crossTileSymbolIndex.pruneUnusedLayers(this._mergedOrder);const Ke=!!(this.placement&&!N.equals(this.placement.transform)),Ze=!!(this.placement&&(this.placement.lastReplacementSourceUpdateTime!==0&&!Z||this.placement.lastReplacementSourceUpdateTime!==Z.updateTime)),mt=Ke||Ze||de,vt=(mt||this.pauseablePlacement.isStale())&&z===0,bt=this.pauseablePlacement.isDone()&&!this.placement.stillRecent(o.e.now(),N.zoom)&&z!==0;if((this.pauseablePlacement.isFullPlacementRequested()||!this.pauseablePlacement.placement||vt||bt)&&(this.pauseablePlacement=this.pauseablePlacement.startNewPlacement(N,this._mergedOrder,E,z,W,this.placement,this.fog&&N.projection.supportsFog?this.fog.state:null,this._buildingIndex,ne),this.map.painter)){const St=this.map.painter.maxFrontCutoffRawStart;if(St>0){const Pt=180*N.pitch/Math.PI;if(Pt>=15){const Gt=Math.min(1,Math.max(0,(Pt-15)/5)),as=Gt*Gt*(3-2*Gt);this.pauseablePlacement.placement.frontCutoffStart=-.5*(1-as)+St*as}}}if(this.pauseablePlacement.isDone()?mt&&z!==0&&this.pauseablePlacement.setStale():(this.pauseablePlacement.continuePlacement(this._mergedOrder,this._mergedLayers,Ce,Pe,this.map.painter.scaleFactor),this.pauseablePlacement.isDone()&&(this.placement=this.pauseablePlacement.commit(o.e.now()),ye=!0),de&&this.pauseablePlacement.setStale()),ye||de){this._buildingIndex.onNewFrame(N.zoom);for(let St=0;StZ===N.id)!==-1)return void this.fire(new o.f(new Error(`Import with id '${N.id}' already exists in the map's style.`)));if(!E)return z.push(N),this._loadImports([N],!0);const W=z.findIndex(({id:Z})=>Z===E);return W===-1&&this.fire(new o.f(new Error(`Import with id "${E}" does not exist on this map.`))),this.stylesheet.imports=z.slice(0,W).concat(N).concat(z.slice(W)),this._loadImports([N],!0,E)}updateImport(N,E){this._checkLoaded();const z=this.stylesheet.imports||[],W=this.getImportIndex(N);return W===-1?this:typeof E=="string"?(this.setImportUrl(N,E),this):(E.url&&E.url!==z[W].url&&this.setImportUrl(N,E.url),o.O(E.config,z[W].config)||this.setImportConfig(N,E.config,E.data.schema),o.O(E.data,z[W].data)||this.setImportData(N,E.data),this)}moveImport(N,E){this._checkLoaded();let z=this.stylesheet.imports||[];const W=this.getImportIndex(N);if(W===-1)return this;const Z=this.getImportIndex(E);if(Z===-1)return this;const ne=z[W],de=this.fragments[W];return z=z.filter(({id:ye})=>ye!==N),this.fragments=this.fragments.filter(({id:ye})=>ye!==N),this.stylesheet.imports=z.slice(0,Z).concat(ne).concat(z.slice(Z)),this.fragments=this.fragments.slice(0,Z).concat(de).concat(this.fragments.slice(Z)),this.mergeLayers(),this}setImportUrl(N,E){this._checkLoaded();const z=this.stylesheet.imports||[],W=this.getImportIndex(N);if(W===-1)return this;z[W].url=E;const Z=this.fragments[W];return Z.style=this._createFragmentStyle(z[W]),Z.style.on("style.import.load",()=>this.mergeAll()),Z.style.loadURL(E),this}setImportData(N,E){this._checkLoaded();const z=this.getImportIndex(N),W=this.stylesheet.imports||[];return z===-1?this:E?(this.fragments[z].style.setState(E),this._reloadImports(),this):(delete W[z].data,this.setImportUrl(N,W[z].url))}setImportConfig(N,E,z){this._checkLoaded();const W=this.getImportIndex(N),Z=this.stylesheet.imports||[];if(W===-1)return this;E?Z[W].config=E:delete Z[W].config;const ne=this.fragments[W];z&&ne.style.stylesheet&&(ne.style.stylesheet.schema=z);const de=ne.style.stylesheet&&ne.style.stylesheet.schema;return ne.config=E,ne.style.updateConfig(E,de),this.updateConfigDependencies(),this}removeImport(N){this._checkLoaded();const E=this.stylesheet.imports||[],z=this.getImportIndex(N);z!==-1&&(E.splice(z,1),this.fragments[z].style._remove(),this.fragments.splice(z,1),this._reloadImports())}getImportIndex(N){const E=(this.stylesheet.imports||[]).findIndex(z=>z.id===N);return E===-1&&this.fire(new o.f(new Error(`Import '${N}' does not exist in the map's style and cannot be updated.`))),E}getLayer(N){return this._mergedLayers[N]}getSources(){const N=[];for(const E in this._mergedOtherSourceCaches){const z=this._mergedOtherSourceCaches[E];z&&N.push(z.getSource())}return N}getSource(N,E){const z=this.getSourceCache(N,E);return z&&z.getSource()}getLayerSource(N){const E=this.getLayerSourceCache(N);return E&&E.getSource()}getSourceCache(N,E){const z=o.m(N,E);return this._mergedOtherSourceCaches[z]}getLayerSourceCache(N){const E=o.m(N.source,N.scope);return N.type==="symbol"?this._mergedSymbolSourceCaches[E]:N.type==="fill-extrusion"?this._mergedFillExtrusionSourceCaches[E]||this._mergedOtherSourceCaches[E]:N.type==="fill"&&N.sourceLayer===o.bU&&this._mergedHdRoadCoverageSourceCaches[E]?this._mergedHdRoadCoverageSourceCaches[E]:this._mergedOtherSourceCaches[E]}getSourceCaches(N){return N==null?Object.values(this._mergedSourceCaches):[this._mergedOtherSourceCaches[N],this._mergedSymbolSourceCaches[N],this._mergedFillExtrusionSourceCaches[N],this._mergedHdRoadCoverageSourceCaches[N],this._mergedHdRoadElevationSourceCaches[N]].filter(Boolean)}updateSourceCaches(){const N=this._changes.getUpdatedSourceCaches();for(const E in N){const z=N[E];z==="reload"?this.reloadSource(E):z==="clear"&&this.clearSource(E)}}updateLayers(N){const E=this._changes.getUpdatedPaintProperties();for(const z of E){const W=this.getLayer(z);W&&W.updateTransitions(N)}}getGlyphsUrl(){return this.stylesheet.glyphs}setGlyphsUrl(N){this.stylesheet.glyphs=N,this.glyphManager.setURL(N)}getOwnSourceCache(N){return this._otherSourceCaches[N]}getOwnLayerSourceCache(N){return N.type==="symbol"?this._symbolSourceCaches[N.source]:N.type==="fill-extrusion"&&this._fillExtrusionSourceCaches[N.source]||this._otherSourceCaches[N.source]}getOwnSourceCaches(N){return[this._otherSourceCaches[N],this._symbolSourceCaches[N],this._fillExtrusionSourceCaches[N],this._hdCoverage&&this._hdCoverage.coverageSourceCaches[N],this._hdElevation&&this._hdElevation.elevationSourceCaches[o.m(N,this.scope)]].filter(Boolean)}_updateHdCoverageSourceCache(N){return wi.HdCoverageState&&wi.updateHdCoverageSourceCache?(this._hdCoverage||(this._hdCoverage=new wi.HdCoverageState),wi.updateHdCoverageSourceCache(this,this._hdCoverage,N),!1):N.type==="fill"&&N.sourceLayer===o.bU}_isSourceCacheLoaded(N){const E=this.getOwnSourceCaches(N);return E.length===0?(this.fire(new o.f(new Error(`There is no source with ID '${N}'`))),!1):E.every(z=>z.loaded())}has3DLayers(){return this._has3DLayers}hasSymbolLayers(){return this._hasSymbolLayers}hasCircleLayers(){return this._hasCircleLayers}isLayerClipped(N,E){if(!this._clipLayerPresent&&N.type!=="fill-extrusion"&&N.type!=="building")return!1;const z=N.type==="fill-extrusion"&&(N.sourceLayer==="building"||N.sourceLayer==="procedural_buildings"),W=N.type==="building";if(N.is3D(!!this.terrain)){if(z||W||E&&E.type==="batched-model"||N.type==="model")return!0}else if(N.type==="symbol")return!0;return!1}_clearWorkerCaches(){this.dispatcher.broadcast("clearCaches")}getBOMObject(){}destroy(){this._clearWorkerCaches(),this.imageManager.imageAtlasCache.clear(),this.fragments.forEach(N=>{N.style._remove()}),this.terrainSetForDrapingOnly()&&(delete this.terrain,delete this.stylesheet.terrain)}async getImages(N,E){const z=new Promise((ye,Ce)=>{this.imageManager.getImages(E.icons.concat(E.patterns),E.scope,(Pe,Ke)=>{Pe?Ce(Pe):ye(Ke)})});this._updateTilesForChangedImages();const W=E.icons.map(ye=>o.I.toString(ye)),Z=E.patterns.map(ye=>o.I.toString(ye)),ne=ye=>{ye&&(ye.setDependencies(E.tileID.key,"icons",W),ye.setDependencies(E.tileID.key,"patterns",Z))},de=o.m(E.source,E.scope);return ne(this._mergedOtherSourceCaches[de]),ne(this._mergedSymbolSourceCaches[de]),(E.icons.some(ye=>ye.iconsetId)||E.patterns.some(ye=>ye.iconsetId))&&this.fire(new o.h("data",{dataType:"style"})),z}async rasterizeImages(N,E){return new Promise((z,W)=>{this.imageManager.rasterizeImages(E,(Z,ne)=>{Z?W(Z):z(ne)})})}async checkAtlasCache(N,E){const z=this.imageManager.imageAtlasCache.findCachedAtlas(E.descriptor);return z&&z.contentDescriptor?{iconPositions:z.iconPositions,patternPositions:z.patternPositions,sourceHash:z.contentDescriptor.hash}:null}async getGlyphs(N,E){return new Promise((z,W)=>{this.glyphManager.getGlyphs(E.stacks,(Z,ne)=>{Z?W(Z):z(ne)})})}}zi.registerForPluginStateChange=o.d6;class _c{constructor(){this.boundProgram=null,this.boundLayoutVertexBuffer=null,this.boundPaintVertexBuffers=[],this.boundIndexBuffer=null,this.boundVertexOffset=null,this.boundDynamicVertexBuffers=[],this.vao=null}bind(N,E,z,W,Z,ne,de,ye){this.context=N;let Ce=this.boundPaintVertexBuffers.length!==W.length;for(let Ke=0;!Ce&&Ke{const Gs=as.paint.get("hillshade-shadow-color"),Ms=as.paint.get("hillshade-shadow-color-use-theme").constantOr("default")==="none",Js=as.paint.get("hillshade-highlight-color"),Os=as.paint.get("hillshade-highlight-color-use-theme").constantOr("default")==="none",Ks=as.paint.get("hillshade-accent-color"),_n=as.paint.get("hillshade-accent-color-use-theme").constantOr("default")==="none",ln=as.paint.get("hillshade-emissive-strength");let an=o.au(as.paint.get("hillshade-illumination-direction"));if(as.paint.get("hillshade-illumination-anchor")==="viewport")an-=Pt.transform.angle;else if(Pt.style&&Pt.style.enable3dLights()&&Pt.style.directionalLight){const Sn=Pt.style.directionalLight.properties.get("direction"),lr=o.de(Sn.x,Sn.y,Sn.z);an=o.au(lr[1])}const bn=!Pt.options.moving;return{u_matrix:ms||Pt.transform.calculateProjMatrix(Gt.tileID.toUnwrapped(),bn),u_image:0,u_latrange:Vh(0,Gt.tileID),u_light:[as.paint.get("hillshade-exaggeration"),an],u_shadow:Gs.toPremultipliedRenderColor(Ms?null:as.lut),u_highlight:Js.toPremultipliedRenderColor(Os?null:as.lut),u_emissive_strength:ln,u_accent:Ks.toPremultipliedRenderColor(_n?null:as.lut)}})(L,E,z,L.terrain?N.projMatrix:null);L.uploadCommonUniforms(de,Ze,N.toUnwrapped());const{tileBoundsBuffer:vt,tileBoundsIndexBuffer:bt,tileBoundsSegments:St}=L.getTileBoundsBuffers(E);Ze.draw(L,ye.TRIANGLES,W,Z,ne,o.$.disabled,mt,z.id,vt,bt,St)}function Hi(L,N,E){if(!N.needsDEMTextureUpload)return;const z=L.context,W=z.gl;z.pixelStoreUnpackPremultiplyAlpha.set(!1),N.demTexture=N.demTexture||L.getTileTexture(E.stride);const Z=E.getPixels();N.demTexture?N.demTexture.update(Z,{premultiply:!1}):N.demTexture=new o.T(z,Z,W.R32F,{premultiply:!1}),N.needsDEMTextureUpload=!1}function li(L,N,E){const z=L.context,W=z.gl;if(!N.dem)return;const Z=N.dem;if(z.activeTexture.set(W.TEXTURE1),Hi(L,N,Z),!N.demTexture)return;N.demTexture.bind(W.NEAREST,W.CLAMP_TO_EDGE);const ne=Z.dim;z.activeTexture.set(W.TEXTURE0);let de=N.hillshadeFBO;if(!de){const Ze=new o.T(z,{width:ne,height:ne,data:null},W.RGBA8);Ze.bind(W.LINEAR,W.CLAMP_TO_EDGE),de=N.hillshadeFBO=z.createFramebuffer(ne,ne,1,"renderbuffer"),de.colorAttachment0.set(Ze.texture)}z.bindFramebuffer.set(de.framebuffer),z.viewport.set([0,0,ne,ne]);const{tileBoundsBuffer:ye,tileBoundsIndexBuffer:Ce,tileBoundsSegments:Pe}=L.getMercatorTileBoundsBuffers(),Ke=[];L.linearFloatFilteringSupported()&&Ke.push("TERRAIN_DEM_FLOAT_FORMAT"),L.terrain&&L.terrain.renderingToTexture&&L.emissiveMode==="mrt-fallback"&&Ke.push("USE_MRT1"),L.getOrCreateProgram("hillshadePrepare",{defines:Ke}).draw(L,W.TRIANGLES,o.Z.disabled,o._.disabled,o.a1.unblended,o.$.disabled,((Ze,mt)=>{const vt=mt.stride,bt=o.Y();return o.dr(bt,0,o.a2,-o.a2,0,0,1),o.bM(bt,bt,[0,-o.a2,0]),{u_matrix:bt,u_image:1,u_dimension:[vt,vt],u_zoom:Ze.overscaledZ}})(N.tileID,Z),E.id,ye,Ce,Pe),N.needsHillshadePrepare=!1}class Do{constructor(N){this.gl=N.gl,this.default=this.getDefault(),this.current=this.default,this.dirty=!1}get(){return this.current}set(N){}getDefault(){return this.default}setDefault(){this.set(this.default)}}class po extends Do{getDefault(){return o.C.transparent.toNonPremultipliedRenderColor(null)}set(N){const E=this.current;(N.r!==E.r||N.g!==E.g||N.b!==E.b||N.a!==E.a||this.dirty)&&(this.gl.clearColor(N.r,N.g,N.b,N.a),this.current=N,this.dirty=!1)}}class ol extends Do{getDefault(){return 1}set(N){(N!==this.current||this.dirty)&&(this.gl.clearDepth(N),this.current=N,this.dirty=!1)}}class Uc extends Do{getDefault(){return 0}set(N){(N!==this.current||this.dirty)&&(this.gl.clearStencil(N),this.current=N,this.dirty=!1)}}class tf extends Do{getDefault(){return[!0,!0,!0,!0]}set(N){const E=this.current;(N[0]!==E[0]||N[1]!==E[1]||N[2]!==E[2]||N[3]!==E[3]||this.dirty)&&(this.gl.colorMask(N[0],N[1],N[2],N[3]),this.current=N,this.dirty=!1)}}class Zp extends Do{getDefault(){return!0}set(N){(N!==this.current||this.dirty)&&(this.gl.depthMask(N),this.current=N,this.dirty=!1)}}class vd extends Do{getDefault(){return 255}set(N){(N!==this.current||this.dirty)&&(this.gl.stencilMask(N),this.current=N,this.dirty=!1)}}class sf extends Do{getDefault(){return{func:this.gl.ALWAYS,ref:0,mask:255}}set(N){const E=this.current;(N.func!==E.func||N.ref!==E.ref||N.mask!==E.mask||this.dirty)&&(this.gl.stencilFunc(N.func,N.ref,N.mask),this.current=N,this.dirty=!1)}}class Lu extends Do{getDefault(){const N=this.gl;return[N.KEEP,N.KEEP,N.KEEP]}set(N){const E=this.current;(N[0]!==E[0]||N[1]!==E[1]||N[2]!==E[2]||this.dirty)&&(this.gl.stencilOp(N[0],N[1],N[2]),this.current=N,this.dirty=!1)}}class am extends Do{getDefault(){return!1}set(N){if(N===this.current&&!this.dirty)return;const E=this.gl;N?E.enable(E.STENCIL_TEST):E.disable(E.STENCIL_TEST),this.current=N,this.dirty=!1}}class Dc extends Do{getDefault(){return[0,1]}set(N){const E=this.current;(N[0]!==E[0]||N[1]!==E[1]||this.dirty)&&(this.gl.depthRange(N[0],N[1]),this.current=N,this.dirty=!1)}}class Cd extends Do{getDefault(){return!1}set(N){if(N===this.current&&!this.dirty)return;const E=this.gl;N?E.enable(E.DEPTH_TEST):E.disable(E.DEPTH_TEST),this.current=N,this.dirty=!1}}class mh extends Do{getDefault(){return this.gl.LESS}set(N){(N!==this.current||this.dirty)&&(this.gl.depthFunc(N),this.current=N,this.dirty=!1)}}class zd extends Do{getDefault(){return!1}set(N){if(N===this.current&&!this.dirty)return;const E=this.gl;N?E.enable(E.BLEND):E.disable(E.BLEND),this.current=N,this.dirty=!1}}class fh extends Do{getDefault(){const N=this.gl;return[N.ONE,N.ZERO,N.ONE,N.ZERO]}set(N){const E=this.current;(N[0]!==E[0]||N[1]!==E[1]||N[2]!==E[2]||N[3]!==E[3]||this.dirty)&&(this.gl.blendFuncSeparate(N[0],N[1],N[2],N[3]),this.current=N,this.dirty=!1)}}class Of extends Do{getDefault(){return o.C.transparent.toNonPremultipliedRenderColor(null)}set(N){const E=this.current;(N.r!==E.r||N.g!==E.g||N.b!==E.b||N.a!==E.a||this.dirty)&&(this.gl.blendColor(N.r,N.g,N.b,N.a),this.current=N,this.dirty=!1)}}class Xu extends Do{getDefault(){return this.gl.FUNC_ADD}set(N){(N!==this.current||this.dirty)&&(this.gl.blendEquationSeparate(N,N),this.current=N,this.dirty=!1)}}class Qd extends Do{getDefault(){return!1}set(N){if(N===this.current&&!this.dirty)return;const E=this.gl;N?E.enable(E.CULL_FACE):E.disable(E.CULL_FACE),this.current=N,this.dirty=!1}}class bd extends Do{getDefault(){return this.gl.BACK}set(N){(N!==this.current||this.dirty)&&(this.gl.cullFace(N),this.current=N,this.dirty=!1)}}class Ru extends Do{getDefault(){return this.gl.CCW}set(N){(N!==this.current||this.dirty)&&(this.gl.frontFace(N),this.current=N,this.dirty=!1)}}let Rg=class extends Do{getDefault(){return null}set(L){(L!==this.current||this.dirty)&&(this.gl.useProgram(L),this.current=L,this.dirty=!1)}};class Am extends Do{getDefault(){return this.gl.TEXTURE0}set(N){(N!==this.current||this.dirty)&&(this.gl.activeTexture(N),this.current=N,this.dirty=!1)}}class pp extends Do{getDefault(){const N=this.gl;return[0,0,N.drawingBufferWidth,N.drawingBufferHeight]}set(N){const E=this.current;(N[0]!==E[0]||N[1]!==E[1]||N[2]!==E[2]||N[3]!==E[3]||this.dirty)&&(this.gl.viewport(N[0],N[1],N[2],N[3]),this.current=N,this.dirty=!1)}}class Xp extends Do{getDefault(){return null}set(N){if(N===this.current&&!this.dirty)return;const E=this.gl;E.bindFramebuffer(E.FRAMEBUFFER,N),this.current=N,this.dirty=!1}}class Ff extends Do{getDefault(){return null}set(N){if(N===this.current&&!this.dirty)return;const E=this.gl;E.bindRenderbuffer(E.RENDERBUFFER,N),this.current=N,this.dirty=!1}}class Dg extends Do{getDefault(){return null}set(N){if(N===this.current&&!this.dirty)return;const E=this.gl;E.bindTexture(E.TEXTURE_2D,N),this.current=N,this.dirty=!1}}class _d extends Do{getDefault(){return null}set(N){if(N===this.current&&!this.dirty)return;const E=this.gl;E.bindBuffer(E.ARRAY_BUFFER,N),this.current=N,this.dirty=!1}}class Qp extends Do{getDefault(){return null}set(N){const E=this.gl;E.bindBuffer(E.ELEMENT_ARRAY_BUFFER,N),this.current=N,this.dirty=!1}}class wd extends Do{getDefault(){return null}set(N){this.gl&&(N!==this.current||this.dirty)&&(this.gl.bindVertexArray(N),this.current=N,this.dirty=!1)}}class ll extends Do{getDefault(){return 4}set(N){if(N===this.current&&!this.dirty)return;const E=this.gl;E.pixelStorei(E.UNPACK_ALIGNMENT,N),this.current=N,this.dirty=!1}}class Du extends Do{getDefault(){return!1}set(N){if(N===this.current&&!this.dirty)return;const E=this.gl;E.pixelStorei(E.UNPACK_PREMULTIPLY_ALPHA_WEBGL,N),this.current=N,this.dirty=!1}}class Oc extends Do{getDefault(){return!1}set(N){if(N===this.current&&!this.dirty)return;const E=this.gl;E.pixelStorei(E.UNPACK_FLIP_Y_WEBGL,N),this.current=N,this.dirty=!1}}class Hh extends Do{constructor(N,E){super(N),this.context=N,this.parent=E}getDefault(){return null}}class zf extends Hh{constructor(N,E,z=0){super(N,E),this.attachmentPoint=N.gl.COLOR_ATTACHMENT0+z}setDirty(){this.dirty=!0}set(N){if(N===this.current&&!this.dirty)return;this.context.bindFramebuffer.set(this.parent);const E=this.gl;E.framebufferTexture2D(E.FRAMEBUFFER,this.attachmentPoint,E.TEXTURE_2D,N,0),this.current=N,this.dirty=!1}}class Cv extends Hh{attachment(){return this.gl.DEPTH_ATTACHMENT}set(N){if(N===this.current&&!this.dirty)return;this.context.bindFramebuffer.set(this.parent);const E=this.gl;E.framebufferRenderbuffer(E.FRAMEBUFFER,this.attachment(),E.RENDERBUFFER,N),this.current=N,this.dirty=!1}}class Sh extends Hh{attachment(){return this.gl.DEPTH_ATTACHMENT}set(N){if(N===this.current&&!this.dirty)return;this.context.bindFramebuffer.set(this.parent);const E=this.gl;E.framebufferTexture2D(E.FRAMEBUFFER,this.attachment(),E.TEXTURE_2D,N,0),this.current=N,this.dirty=!1}}class W_ extends Cv{attachment(){return this.gl.DEPTH_STENCIL_ATTACHMENT}}const M1=(L,N,E,z)=>({u_matrix:L,u_image0:0,u_image1:1,u_skirt_height:N,u_ground_shadow_factor:E,u_emissive_texture_available:z}),P1=(L,N,E,z,W,Z,ne,de,ye,Ce,Pe,Ke,Ze,mt,vt,bt,St)=>({u_proj_matrix:Float32Array.from(L),u_globe_matrix:N,u_normalize_matrix:Float32Array.from(z),u_merc_matrix:E,u_zoom_transition:W,u_merc_center:Z,u_image0:0,u_image1:1,u_frustum_tl:ne,u_frustum_tr:de,u_frustum_br:ye,u_frustum_bl:Ce,u_globe_pos:Pe,u_globe_radius:Ke,u_viewport:Ze,u_grid_matrix:St?Float32Array.from(St):new Float32Array(9),u_skirt_height:mt,u_far_z_cutoff:vt,u_emissive_texture_available:bt});function Jp(L,N){return L!=null&&N!=null&&!(!L.hasData()||!N.hasData())&&L.demTexture!=null&&N.demTexture!=null&&L.tileID.key!==N.tileID.key}const M0=new class{constructor(){this.operations={}}newMorphing(L,N,E,z,W){if(L in this.operations){const Z=this.operations[L];Z.to.tileID.key!==E.tileID.key&&(Z.queued=E)}else this.operations[L]={startTime:z,phase:0,duration:W,from:N,to:E,queued:null}}getMorphValuesForProxy(L){if(!(L in this.operations))return null;const N=this.operations[L];return{from:N.from,to:N.to,phase:N.phase}}update(L){for(const N in this.operations){const E=this.operations[N];for(E.phase=(L-E.startTime)/E.duration;E.phase>=1||!this._validOp(E);)if(!this._nextOp(E,L)){delete this.operations[N];break}}}_nextOp(L,N){return!!L.queued&&(L.from=L.to,L.to=L.queued,L.queued=null,L.phase=0,L.startTime=N,!0)}_validOp(L){return L.from.hasData()&&L.to.hasData()}};function eg(L,N,E){if(N===0)return 0;const z=N<1&&E===514?.25/N:1;return 6*Math.pow(1.5,22-L)*Math.max(N,1)*z}function qk(L,N){const E=1<{if(Z[ne.key]="",!this._tiles[ne.key]){const de=new Ym(ne,this._source.tileSize*ne.overscaleFactor(),N.tileZoom,void 0,void 0,this._source.worldview);de.state="loaded",this._tiles[ne.key]=de}return Z},{});for(const Z in this._tiles)Z in W||(this.freeFBO(Z),this._tiles[Z].unloadVectorData(),delete this._tiles[Z])}freeFBO(N){const E=this.proxyCachedFBO[N];if(E!==void 0){const z=Object.values(E);this.renderCachePool.push(...z),delete this.proxyCachedFBO[N]}}deallocRenderCache(){this.renderCache.forEach(N=>N.fb.destroy()),this.renderCache=[],this.renderCachePool=[],this.proxyCachedFBO={}}}class L1 extends o.bP{constructor(N,E,z){super(N.overscaledZ,N.wrap,N.canonical.z,N.canonical.x,N.canonical.y),this.proxyTileKey=E,this.projMatrix=z}}class Av extends o.cW{constructor(N,E){super(),this.painter=N,this.terrainTileForTile={},this.prevTerrainTileForTile={};const[z,W,Z]=function(){const ye=new o.bC,Ce=new o.ad,Pe=131;ye.reserve(17161),Ce.reserve(33800);const Ke=o.a2/128,Ze=o.a2+Ke/2,mt=Ze+Ke;for(let bt=-Ke;btZe||bt<0||bt>Ze?24575:0,Gt=o.b0(Math.round(St),0,o.a2),as=o.b0(Math.round(bt),0,o.a2);ye.emplaceBack(Gt+Pt,as)}const vt=(bt,St)=>{const Pt=St*Pe+bt;Ce.emplaceBack(Pt+1,Pt,Pt+Pe),Ce.emplaceBack(Pt+Pe,Pt+Pe+1,Pt+1)};for(let bt=1;bt<129;bt++)for(let St=1;St<129;St++)vt(St,bt);return[0,129].forEach(bt=>{for(let St=0;St<130;St++)vt(St,bt),vt(bt,St)}),[ye,Ce,32768]}(),ne=N.context;this.gridBuffer=ne.createVertexBuffer(z,o.bE.members),this.gridIndexBuffer=ne.createIndexBuffer(W),this.gridSegments=o.ac.simpleSegment(0,0,z.length,W.length),this.gridNoSkirtSegments=o.ac.simpleSegment(0,0,z.length,Z),this.proxyCoords=[],this.proxiedCoords={},this._visibleDemTiles=[],this._drapedRenderBatches=[],this._sourceTilesOverlap={},this.proxySourceCache=new I1(E.map),this.orthoMatrix=o.Y(),o.dr(this.orthoMatrix,this.painter.transform.projection.name==="globe"?.015:0,o.a2,0,o.a2,0,1);const de=ne.gl;this._overlapStencilMode=new o._({func:de.GEQUAL,mask:255},0,255,de.KEEP,de.KEEP,de.REPLACE),this._previousZoom=N.transform.zoom,this.pool=[],this._findCoveringTileCache={},this._tilesDirty={},this.style=E,this._useVertexMorphing=!0,this._exaggeration=1,this._mockSourceCache=new nf(E.map),this._pendingGroundEffectLayers=[],this._emissiveTexture=!1,this._devtoolsFolder=null}set style(N){N.on("data",this._onStyleDataEvent.bind(this)),this._style=N,this._style.map.on("moveend",()=>{this._clearLineLayersFromRenderCache()})}update(N,E,z){if(N&&N.terrain){this._style!==N&&(this.style=N,this._evaluationZoom=void 0);const W=N.terrain.properties,Z=N.terrain.drapeRenderMode===0,ne=N.terrain.isZoomDependent();this._previousUpdateTimestamp=this.enabled?this._updateTimestamp:void 0,this._updateTimestamp=o.e.now();const de=N.terrain&&N.terrain.scope,ye=W.get("source"),Ce=Z?this._mockSourceCache:N.getSourceCache(ye,de);if(!Ce)return void o.w(`Couldn't find terrain source "${ye}".`);if(this.sourceCache=Ce,this._attenuationRange=N.terrain.getAttenuationRange(),this._exaggeration=ne?this.calculateExaggeration(E):W.get("exaggeration"),!E.projection.requiresDraping&&ne&&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 Ke=this.getScaledDemTileSize();this.sourceCache.update(E,Ke,!0),this.resetTileLookupCache(this.sourceCache.id)};this.sourceCache.usedForTerrain||(this.resetTileLookupCache(this.sourceCache.id),this.sourceCache.usedForTerrain=!0,Pe(),this._initializing=!0),Pe(),E.updateElevation(!0,z),this.resetTileLookupCache(this.proxySourceCache.id),this.proxySourceCache.update(E),this._emptyDEMTextureDirty=!0,this._previousZoom=E.zoom}else this._disable()}calculateExaggeration(N){if(this._attenuationRange&&N.zoom>=Math.ceil(this._attenuationRange[1]))return this._style.terrain.getExaggeration(N.zoom);const E=this._previousCameraAltitude,z=N.getFreeCameraOptions().position.z/N.pixelsPerMeter*N.worldSize;this._previousCameraAltitude=z;const W=E!=null?z-E:Number.MAX_VALUE;if(Math.abs(W)<2)return this._exaggeration;const Z=N.zoom,ne=this._style.terrain;if(!this._previousUpdateTimestamp)return ne.getExaggeration(Z);let de=Z-this._previousZoom;const ye=this._previousUpdateTimestamp;let Ce=Z;this._evaluationZoom!=null&&(Ce=this._evaluationZoom,Math.abs(Z-Ce)>.5&&(de=.5*(Z-Ce+de)),de*W<0&&(Ce+=de)),this._evaluationZoom=Ce;const Pe=ne.getExaggeration(Ce),Ke=Pe===ne.getExaggeration(Math.max(0,Ce-.1));if(Ke&&Math.abs(Pe-this._exaggeration)<.01)return Pe;let Ze=Math.min(.1,.00375*(this._updateTimestamp-ye));return(Ke||Pe<.1||Math.abs(de)<1e-4)&&(Ze=Math.min(.2,4*Ze)),o.al(this._exaggeration,Pe,Ze)}resetTileLookupCache(N){this._findCoveringTileCache[N]={}}attenuationRange(){return this._attenuationRange}getDemUpscale(){return this.proxySourceCache.getSource().tileSize/128}getScaledDemTileSize(){return this.sourceCache.getSource().tileSize/128*this.proxySourceCache.getSource().tileSize}_onStyleDataEvent(N){N.dataType==="source"&&N.coord?this._clearRenderCacheForTile(N.sourceCacheId,N.coord):N.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 N in this._style._mergedSourceCaches)this._style._mergedSourceCaches[N].usedForTerrain=!1}destroy(){this._disable(),this._emptyDEMTexture&&this._emptyDEMTexture.destroy(),this.pool.forEach(N=>N.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 N=2*this.proxySourceCache.getSource().tileSize;return[N,N]}set useVertexMorphing(N){this._useVertexMorphing=N}updateTileBinding(N){if(!this.enabled)return;this.prevTerrainTileForTile=this.terrainTileForTile;const E=this.proxySourceCache,z=this.painter.transform;this._initializing&&(this._initializing=z._centerAltitude===0&&this.getAtPointOrZero(o.bS.fromLngLat(z.center),-1)===-1,this._emptyDEMTextureDirty=!this._initializing);const W=this.proxyCoords=E.getIds().map(ye=>{const Ce=E.getTileByID(ye).tileID;return Ce.projMatrix=z.calculateProjMatrix(Ce.toUnwrapped()),Ce});(function(ye,Ce){const Pe=Ce.transform.pointCoordinate(Ce.transform.getCameraPoint()),Ke=new o.P(Pe.x,Pe.y);ye.sort((Ze,mt)=>{if(mt.overscaledZ-Ze.overscaledZ)return mt.overscaledZ-Ze.overscaledZ;const vt=new o.P(Ze.canonical.x+(1<{this.proxyToSource[ye.key]={}}),this.terrainTileForTile={};const ne=this._style._mergedSourceCaches;for(const ye in ne){const Ce=ne[ye];if(!Ce.used||!Ce.transform||(Ce!==this.sourceCache&&this.resetTileLookupCache(Ce.id),this._setupProxiedCoordsForOrtho(Ce,N[ye],Z),Ce.usedForTerrain))continue;const Pe=N[ye];(Ce.getSource().reparseOverscaled||Ce._isRasterElevatedOverTerrain)&&this._assignTerrainTiles(Pe)}this.proxiedCoords[E.id]=W.map(ye=>new L1(ye,ye.key,this.orthoMatrix)),this._assignTerrainTiles(W),this._prepareDEMTextures(),this._setupDrapedRenderBatches(),this._initFBOPool(),this._setupRenderCache(Z),this.renderingToTexture=!1;const de={};this._visibleDemTiles=[];for(const ye of this.proxyCoords){const Ce=this.terrainTileForTile[ye.key];if(!Ce)continue;const Pe=Ce.tileID.key;Pe in de||(this._visibleDemTiles.push(Ce),de[Pe]=Pe)}}_assignTerrainTiles(N){this._initializing||N.forEach(E=>{if(this.terrainTileForTile[E.key])return;const z=this._findTileCoveringTileID(E,this.sourceCache);z&&(this.terrainTileForTile[E.key]=z)})}_prepareDEMTextures(){const N=this.painter.context,E=N.gl;for(const z in this.terrainTileForTile){const W=this.terrainTileForTile[z],Z=W.dem;!Z||W.demTexture&&!W.needsDEMTextureUpload||(N.activeTexture.set(E.TEXTURE1),Hi(this.painter,W,Z))}}_prepareDemTileUniforms(N,E,z,W){if(!E||E.demTexture==null)return!1;const Z=N.tileID.canonical,ne=Math.pow(2,E.tileID.canonical.z-Z.z),de=W||"";return z[`u_dem_tl${de}`]=[Z.x*ne%1,Z.y*ne%1],z[`u_dem_scale${de}`]=ne,!0}get emptyDEMTexture(){return!this._emptyDEMTextureDirty&&this._emptyDEMTexture?this._emptyDEMTexture:this._updateEmptyDEMTexture()}_getLoadedAreaMinimum(){if(!this.enabled)return 0;let N=0;const E=this._visibleDemTiles.reduce((z,W)=>{if(!W.dem)return z;const Z=W.dem.tree.minimums[0];return Z>0&&N++,z+Z},0);return N?E/N:0}_updateEmptyDEMTexture(){const N=this.painter.context,E=N.gl;N.activeTexture.set(E.TEXTURE2);const z=this._getLoadedAreaMinimum(),W=new o.dv({width:1,height:1},new Float32Array([z]));this._emptyDEMTextureDirty=!1;let Z=this._emptyDEMTexture;return Z?Z.update(W,{premultiply:!1}):Z=this._emptyDEMTexture=new o.T(N,W,E.R32F,{premultiply:!1}),Z}setupElevationDraw(N,E,z){const W=this.painter.context,Z=W.gl,ne={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};ne.u_exaggeration=this.exaggeration();let de=null,ye=null,Ce=1;if(z&&z.morphing&&this._useVertexMorphing){const mt=z.morphing.srcDemTile,vt=z.morphing.dstDemTile;Ce=z.morphing.phase,mt&&vt&&(this._prepareDemTileUniforms(N,mt,ne,"_prev")&&(ye=mt),this._prepareDemTileUniforms(N,vt,ne)&&(de=vt))}const Pe=mt=>mt&&mt.demTexture&&this.painter.linearFloatFilteringSupported()?Z.LINEAR:Z.NEAREST;let Ke=null;var Ze;if(this.enabled?ye&&de?(Ke=de.demTexture,W.activeTexture.set(Z.TEXTURE4),ye.demTexture.bind(Pe(ye),Z.CLAMP_TO_EDGE),ne.u_dem_lerp=Ce):(de=this.terrainTileForTile[N.tileID.key],Ke=this._prepareDemTileUniforms(N,de,ne)?de.demTexture:this.emptyDEMTexture):Ke=this.emptyDEMTexture,W.activeTexture.set(Z.TEXTURE2),Ke&&(ne.u_dem_size=(Ze=Ke).size[0]===1?1:Ze.size[0]-2,Ke.bind(Pe(de),Z.CLAMP_TO_EDGE)),this.painter.setupDepthForOcclusion(z&&z.useDepthForOcclusion,E,ne),z&&z.useMeterToDem&&de){const mt=(1<{if(Pt===Sn)return;const lr=[];Sn===1&&lr.push("TERRAIN_VERTEX_MORPHING"),lr.push("PROJECTION_GLOBE_VIEW"),as&&lr.push("CUSTOM_ANTIALIASING");const Mn=Ce.isTileAffectedByFog(bn);St=Ce.getOrCreateProgram("globeRaster",{defines:lr,overrideFog:Mn}),Pt=Sn},Gs=Ce.colorModeForRenderPass(),Ms=new o.Z(bt.LEQUAL,o.Z.ReadWrite,Ce.depthRangeFor3D);M0.update(mt);const Js=o.b6(Gt),Os=[o.a7(Gt.center.lng),o.a8(Gt.center.lat)],Ks=Ce.globeSharedBuffers,_n=[Gt.width*o.e.devicePixelRatio,Gt.height*o.e.devicePixelRatio],ln=Float32Array.from(Gt.globeMatrix),an={useDenormalizedUpVectorScale:!0};{const bn=Ce.transform,Sn=eg(bn.zoom,Pe.exaggeration(),Pe.sourceCache._source.tileSize);Pt=-1;const lr=bt.TRIANGLES;for(const Mn of Ze){const Hn=Ke.getTile(Mn),Tr=o._.disabled,oa=Pe.prevTerrainTileForTile[Mn.key],Qr=Pe.terrainTileForTile[Mn.key];Jp(oa,Qr)&&M0.newMorphing(Mn.key,oa,Qr,mt,250),Db(Ce,Hn.emissiveTexture),vt.activeTexture.set(bt.TEXTURE0),Hn.texture&&Hn.texture.bind(bt.LINEAR,bt.CLAMP_TO_EDGE);const Lr=M0.getMorphValuesForProxy(Mn.key),qa=Lr?1:0;Lr&&Object.assign(an,{morphing:{srcDemTile:Lr.from,dstDemTile:Lr.to,phase:o.ds(Lr.phase)}});const Nr=o.b2(Mn.canonical),cr=o.b3(Nr.getCenter().lat),Fr=o.b7(Mn.canonical,Nr,cr,bn.worldSize/bn._pixelsPerMercatorPixel),Fa=o.b4(o.b5(Mn.canonical)),ta=Ce.emissiveMode==="mrt-fallback"?1:0,Ta=P1(bn.expandedFarZProjMatrix,ln,Js,Fa,o.S(bn.zoom),Os,bn.frustumCorners.TL,bn.frustumCorners.TR,bn.frustumCorners.BR,bn.frustumCorners.BL,bn.globeCenterInViewSpace,bn.globeRadius,_n,Sn,bn._farZ,ta,Fr);if(ms(Mn,qa),St&&(Pe.setupElevationDraw(Hn,St,an),Ce.uploadCommonUniforms(vt,St,Mn.toUnwrapped()),Ks)){const[ci,uo,ao]=Ks.getGridBuffers(cr,Sn!==0);St.draw(Ce,lr,Ms,Tr,Gs,o.$.backCCW,Ta,"globe_raster",ci,uo,ao)}}}if(Ks&&(Ce.renderDefaultNorthPole||Ce.renderDefaultSouthPole)){const bn=["GLOBE_POLES","PROJECTION_GLOBE_VIEW"];as&&bn.push("CUSTOM_ANTIALIASING"),St=Ce.getOrCreateProgram("globeRaster",{defines:bn});for(const Sn of Ze){const{x:lr,y:Mn,z:Hn}=Sn.canonical,Tr=Mn===0,oa=Mn===(1<ci.draw(Ce,bt.TRIANGLES,Ms,o._.disabled,Gs,o.$.disabled,P1(Gt.expandedFarZProjMatrix,Fr,Fr,Fa,0,Os,Gt.frustumCorners.TL,Gt.frustumCorners.TR,Gt.frustumCorners.BR,Gt.frustumCorners.BL,Gt.globeCenterInViewSpace,Gt.globeRadius,_n,0,Gt._farZ,ta),"globe_pole_raster",uo,qa,Nr);Pe.setupElevationDraw(cr,St,an),Ce.uploadCommonUniforms(vt,St,Sn.toUnwrapped()),Tr&&Ce.renderDefaultNorthPole&&Ta(St,Qr),oa&&Ce.renderDefaultSouthPole&&(Fr=o.aN(o.Y(),Fr,[1,-1,1]),Ta(St,Lr))}}}})(W,Z,ne,de,ye);else{const Ce=W.context,Pe=Ce.gl;let Ke,Ze;const mt=W.shadowRenderer,vt=o.aE(W,W.longestCutoffRange),bt=Gs=>{if(Ze===Gs)return;const Ms=[];Gs===1&&Ms.push("TERRAIN_VERTEX_MORPHING"),vt.shouldRenderCutoff&&Ms.push("RENDER_CUTOFF"),mt&&(Ms.push("RENDER_SHADOWS"),mt.useNormalOffset&&Ms.push("NORMAL_OFFSET")),Ke=W.getOrCreateProgram("terrainRaster",{defines:Ms}),Ze=Gs},St=W.colorModeForRenderPass(),Pt=new o.Z(Pe.LEQUAL,o.Z.ReadWrite,W.depthRangeFor3D);M0.update(ye);const Gt=W.transform,as=eg(Gt.zoom,Z.exaggeration(),Z.sourceCache._source.tileSize);let ms=[0,0,0];if(mt){const Gs=W.style.directionalLight,Ms=W.style.ambientLight;Gs&&Ms&&(ms=o.aF(W.style,Gs,Ms))}{Ze=-1;const Gs=Pe.TRIANGLES,[Ms,Js]=[Z.gridIndexBuffer,Z.gridSegments];for(const Os of de){const Ks=ne.getTile(Os),_n=o._.disabled,ln=Z.prevTerrainTileForTile[Os.key],an=Z.terrainTileForTile[Os.key];Jp(ln,an)&&M0.newMorphing(Os.key,ln,an,ye,250),Db(W,Ks.emissiveTexture),Ce.activeTexture.set(Pe.TEXTURE0),Ks.texture&&Ks.texture.bind(Pe.LINEAR,Pe.CLAMP_TO_EDGE);const bn=M0.getMorphValuesForProxy(Os.key),Sn=bn?1:0;let lr;bn&&(lr={morphing:{srcDemTile:bn.from,dstDemTile:bn.to,phase:o.ds(bn.phase)}});const Mn=W.emissiveMode==="mrt-fallback"?1:0,Hn=M1(Os.projMatrix,qk(Os.canonical,Gt.renderWorldCopies)?as/10:as,ms,Mn);if(bt(Sn),!Ke)continue;Z.setupElevationDraw(Ks,Ke,lr);const Tr=Os.toUnwrapped();mt&&mt.setupShadows(Tr,Ke),W.uploadCommonUniforms(Ce,Ke,Tr,null,vt),Ke.draw(W,Gs,Pt,_n,St,o.$.backCCW,Hn,"terrain_raster",Z.gridBuffer,Ms,Js)}}}}(E,this,this.proxySourceCache,N,this._updateTimestamp),this.renderingToTexture=!0,E.gpuTimingDeferredRenderEnd(),N.splice(0,N.length))}renderBatch(N){if(this._drapedRenderBatches.length===0)return N+1;this.renderingToTexture=!0;const E=this.painter,z=this.painter.context,W=this.proxySourceCache,Z=this.proxiedCoords[W.id],ne=this._drapedRenderBatches.shift(),de=E.style.order,ye=[];this._updateFBOs(E.emissiveMode==="mrt-fallback");let Ce=0;for(const Pe of Z){const Ke=W.getTileByID(Pe.proxyTileKey),Ze=W.proxyCachedFBO[Pe.key]?W.proxyCachedFBO[Pe.key][N]:void 0,mt=Ze!==void 0?W.renderCache[Ze]:this.pool[Ce++],vt=Ze!==void 0;if(Ke.texture=mt.tex,Ke.emissiveTexture=mt.emissiveTex,vt&&!mt.dirty){ye.push(Ke.tileID);continue}z.bindFramebuffer.set(mt.fb.framebuffer);const bt=z.gl;let St;bt.drawBuffers(E.emissiveMode==="mrt-fallback"?[bt.COLOR_ATTACHMENT0,bt.COLOR_ATTACHMENT1]:[bt.COLOR_ATTACHMENT0]),this.renderedToTile=!1,mt.dirty&&(z.clear({color:o.C.transparent,stencil:0}),mt.dirty=!1);for(let Pt=ne.start;Pt<=ne.end;++Pt){const Gt=E.style._mergedLayers[de[Pt]];if(Gt.isHidden(E.transform.zoom))continue;const as=E.style.getLayerSourceCache(Gt),ms=as?this.proxyToSource[Pe.key][as.id]:[Pe];if(!ms)continue;const Gs=ms;z.viewport.set([0,0,mt.fb.width,mt.fb.height]),St!==(as?as.id:null)&&(this._setupStencil(mt,ms,Gt,as),St=as?as.id:null),E.renderLayer(E,as,Gt,Gs)}if(bt.drawBuffers([bt.COLOR_ATTACHMENT0]),this._drapedRenderBatches.length===0)for(const Pt of this._pendingGroundEffectLayers){const Gt=E.style._mergedLayers[de[Pt]];if(Gt.isHidden(E.transform.zoom))continue;const as=E.style.getLayerSourceCache(Gt),ms=as?this.proxyToSource[Pe.key][as.id]:[Pe];if(!ms)continue;const Gs=ms;z.viewport.set([0,0,mt.fb.width,mt.fb.height]),St!==(as?as.id:null)&&(this._setupStencil(mt,ms,Gt,as),St=as?as.id:null),E.renderLayer(E,as,Gt,Gs)}this.renderedToTile?(mt.dirty=!0,ye.push(Ke.tileID)):vt||--Ce,Ce===5&&(Ce=0,this.renderToBackBuffer(ye))}return this.renderToBackBuffer(ye),this.renderingToTexture=!1,z.bindFramebuffer.set(null),z.viewport.set([0,0,E.width,E.height]),ne.end+1}postRender(){}isLayerOrderingCorrect(N){const E=N.order.length;let z=-1,W=E;for(let Z=0;Zz}getMinElevationBelowMSL(){let N=0;return this._visibleDemTiles.filter(E=>E.dem).forEach(E=>{N=Math.min(N,E.dem.tree.minimums[0])}),N===0?N:(N-30)*this._exaggeration}raycast(N,E,z){if(!this._visibleDemTiles)return null;const W=this._visibleDemTiles.filter(Z=>Z.dem).map(Z=>{const ne=Z.tileID,de=1<(Z.t!==null?Z.t:Number.MAX_VALUE)-(ne.t!==null?ne.t:Number.MAX_VALUE));for(const Z of W){if(Z.t==null)return null;const ne=Z.tile.dem.tree.raycast(Z.minx,Z.miny,Z.maxx,Z.maxy,N,E,z);if(ne!=null)return ne}return null}_createFBO(){const N=this.painter.context,E=N.gl,z=this.drapeBufferSize;N.activeTexture.set(E.TEXTURE0);const W=new o.T(N,{width:z[0],height:z[1],data:null},E.RGBA8);W.bind(E.LINEAR,E.CLAMP_TO_EDGE);const Z=N.createFramebuffer(z[0],z[1],1,null);let ne;return Z.colorAttachment0.set(W.texture),this._emissiveTexture&&(ne=new o.T(N,{width:z[0],height:z[1],data:null},E.R8),ne.bind(E.LINEAR,E.CLAMP_TO_EDGE),Z.createColorAttachment(N,1),Z.colorAttachment1.set(ne.texture)),Z.depthAttachment=new W_(N,Z.framebuffer),this._sharedDepthStencil===void 0?(this._sharedDepthStencil=N.createRenderbuffer(N.gl.DEPTH_STENCIL,z[0],z[1]),this._stencilRef=0,Z.depthAttachment.set(this._sharedDepthStencil),N.clear({stencil:0})):Z.depthAttachment.set(this._sharedDepthStencil),N.extTextureFilterAnisotropic&&E.texParameterf(E.TEXTURE_2D,N.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,N.extTextureFilterAnisotropicMax),{fb:Z,tex:W,emissiveTex:ne,dirty:!1}}_updateFBOs(N){if(this._emissiveTexture!==N){for(const E of this.pool)this._updateFBO(E,N);for(const E of this.proxySourceCache.renderCache)this._updateFBO(E,N);this._emissiveTexture=N}}_updateFBO(N,E){const z=N.fb,W=this.painter.context,Z=W.gl,ne=this.drapeBufferSize;if(E){const de=new o.T(W,{width:ne[0],height:ne[1],data:null},Z.R8);de.bind(Z.LINEAR,Z.CLAMP_TO_EDGE),N.emissiveTex=de,z.createColorAttachment(W,1),z.colorAttachment1.set(de.texture)}else N.emissiveTex=void 0,z.removeColorAttachment(W,1);N.dirty=!0}_initFBOPool(){for(;this.pool.length{const E=this._style._mergedLayers[N],z=E.isHidden(this.painter.transform.zoom);return E.type==="hillshade"||E.type==="custom"?!z&&E.shouldRedrape():!z&&E.hasTransition()})}_clearLineLayersFromRenderCache(){let N=!1;for(const z of this._style.getSources())if(z instanceof T0){N=!0;break}if(!N)return;const E={};for(let z=0;zye>de.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=z}_setupRenderCache(N){const E=this.proxySourceCache;if(this._shouldDisableRenderCache()||this.invalidateRenderCache){if(this.invalidateRenderCache=!1,E.renderCache.length>E.renderCachePool.length){const ne=Object.values(E.proxyCachedFBO);E.proxyCachedFBO={};for(let de=0;de=0;ne--){const de=z[ne];if(E.getTileByID(de.key),E.proxyCachedFBO[de.key]!==void 0){const ye=N[de.key],Ce=this.proxyToSource[de.key];let Pe=0;for(const Ke in Ce){const Ze=Ce[Ke],mt=ye[Ke];if(!mt||mt.length!==Ze.length||Ze.some((vt,bt)=>vt!==mt[bt]||W[Ke]&&Object.hasOwn(W[Ke],vt.key))){Pe=-1;break}++Pe}for(const Ke in E.proxyCachedFBO[de.key])E.renderCache[E.proxyCachedFBO[de.key][Ke]].dirty=Pe<0||Pe!==Object.values(ye).length}}const Z=[...this._drapedRenderBatches];Z.sort((ne,de)=>de.end-de.start-(ne.end-ne.start));for(const ne of Z)for(const de of z){if(E.proxyCachedFBO[de.key])continue;let ye=E.renderCachePool.pop();ye===void 0&&E.renderCache.length<50&&(ye=E.renderCache.length,E.renderCache.push(this._createFBO())),ye!==void 0&&(E.proxyCachedFBO[de.key]={},E.proxyCachedFBO[de.key][ne.start]=ye,E.renderCache[ye].dirty=!0)}this._tilesDirty={}}_setupStencil(N,E,z,W){if(!W||!this._sourceTilesOverlap[W.id])return void(this._overlapStencilType&&(this._overlapStencilType=!1));const Z=this.painter.context,ne=Z.gl;if(E.length<=1)return void(this._overlapStencilType=!1);let de;if(z.isTileClipped())de=E.length,this._overlapStencilMode.test={func:ne.EQUAL,mask:255},this._overlapStencilType="Clip";else{if(!(E[0].overscaledZ>E.at(-1).overscaledZ))return void(this._overlapStencilType=!1);de=1,this._overlapStencilMode.test={func:ne.GREATER,mask:255},this._overlapStencilType="Mask"}this._stencilRef+de>255&&(Z.clear({stencil:0}),this._stencilRef=0),this._stencilRef+=de,this._overlapStencilMode.ref=this._stencilRef,z.isTileClipped()&&this._renderTileClippingMasks(E,this._overlapStencilMode.ref)}clipOrMaskOverlapStencilType(){return this._overlapStencilType==="Clip"||this._overlapStencilType==="Mask"}stencilModeForRTTOverlap(N){return this.renderingToTexture&&this._overlapStencilType?(this._overlapStencilType==="Clip"&&(this._overlapStencilMode.ref=this.painter._tileClippingMaskIDs[N.key]),this._overlapStencilMode):o._.disabled}_renderTileClippingMasks(N,E){const z=this.painter,W=this.painter.context,Z=W.gl;z._tileClippingMaskIDs={},W.setColorMode(o.a1.disabled),W.setDepthMode(o.Z.disabled);const ne=z.getOrCreateProgram("clippingMask");for(const de of N){const ye=z._tileClippingMaskIDs[de.key]=--E;ne.draw(z,Z.TRIANGLES,o.Z.disabled,new o._({func:Z.ALWAYS,mask:0},ye,255,Z.KEEP,Z.KEEP,Z.REPLACE),o.a1.disabled,o.$.disabled,Yu(de.projMatrix),"$clipping",z.tileExtentBuffer,z.quadTriangleIndexBuffer,z.tileExtentSegments)}}pointCoordinate(N){const E=this.painter.transform;if(N.x<0||N.x>E.width||N.y<0||N.y>E.height)return null;const z=[N.x,N.y,1,1];o.c7(z,z,E.pixelMatrixInverse),o.dy(z,z,1/z[3]),z[0]/=E.worldSize,z[1]/=E.worldSize;const W=E._camera.position,Z=o.dw(1,E.center.lat),ne=[W[0],W[1],W[2]/Z,0],de=o.dz([],z.slice(0,3),ne);o.c3(de,de);const ye=this.raycast(ne,de,this._exaggeration);return ye!==null&&ye?(o.dA(ne,ne,de,ye),ne[3]=ne[2],ne[2]*=Z,ne):null}_setupProxiedCoordsForOrtho(N,E,z){if(N.getSource()instanceof fx)return this._setupProxiedCoordsForImageSource(N,E,z);this._findCoveringTileCache[N.id]=this._findCoveringTileCache[N.id]||{};const W=this.proxiedCoords[N.id]=[],Z=this.proxyCoords;for(let ye=0;yePe.overscaledZ-Ce.overscaledZ)}_setupProxiedCoordsForImageSource(N,E,z){if(!N.getSource().loaded())return;const W=this.proxiedCoords[N.id]=[],Z=this.proxyCoords,ne=N.getSource(),de=ne.tileID;if(!de)return;const ye=new o.P(de.x,de.y)._div(1<(Ke.min.x=Math.min(Ke.min.x,Ze.x-ye.x),Ke.min.y=Math.min(Ke.min.y,Ze.y-ye.y),Ke.max.x=Math.max(Ke.max.x,Ze.x-ye.x),Ke.max.y=Math.max(Ke.max.y,Ze.y-ye.y),Ke),{min:new o.P(Number.MAX_VALUE,Number.MAX_VALUE),max:new o.P(-Number.MAX_VALUE,-Number.MAX_VALUE)}),Pe=(Ke,Ze)=>{const mt=Ke.wrap+Ke.canonical.x/(1<St+Ce.max.x||vt+btPt+Ce.max.y};for(let Ke=0;Kene.key===E.tileID.key);if(Z)return Z}if(E.tileID.key!==N.key){const Z=N.canonical.z-E.tileID.canonical.z;let ne,de,ye;W=o.Y();const Ce=E.tileID.wrap-N.wrap<0?(ne=o.a2>>Z,de=ne*((E.tileID.canonical.x<=Ke){const Ze=N.canonical.z-Ke;E.getSource().reparseOverscaled?(de=Math.max(N.canonical.z+2,E.transform.tileZoom),ne=new o.bP(de,N.wrap,Ke,N.canonical.x>>Ze,N.canonical.y>>Ze)):Ze!==0&&(de=Ke,ne=new o.bP(de,N.wrap,Ke,N.canonical.x>>Ze,N.canonical.y>>Ze))}ne.key!==N.key&&(Ce.push(ne.key),z=E.getTile(ne))}const Pe=Ke=>{Ce.forEach(Ze=>{W[Ze]=Ke}),Ce.length=0};for(de-=1;de>=ye&&(!z||!z.hasData());de--){z&&Pe(z.tileID.key);const Ke=ne.calculateScaledKey(de);if(z=E.getTileByID(Ke),z&&z.hasData())break;const Ze=W[Ke];if(Ze===null)break;Ze===void 0?Ce.push(Ke):z=E.getTileByID(Ze)}return Pe(z?z.tileID.key:null),z&&z.hasData()?z:null}findDEMTileFor(N){return this.enabled?this._findTileCoveringTileID(N,this.sourceCache):null}prepareDrawTile(){this.renderedToTile=!0}_clearRenderCacheForTile(N,E){let z=this._tilesDirty[N];z||(z=this._tilesDirty[N]={}),z[E.key]=!0}}function P0(L,N,E){const z=function(de,ye,Ce){const Pe=o.dF(ye,de),Ke=o.dF(Ce,[.2126,.7152,.0722]),Ze=1-.3*Math.min(Ke,1),mt=o.al(Ze,1,Math.min(Pe+1,1));return o.al(.92,1,Math.asin(o.b0(ye[2],-1,1))/Math.PI+.5)*mt}(L,[0,0,1],N),W=[0,0,0];o.dC(W,E.slice(0,3),z);const Z=[0,0,0];o.dC(Z,N.slice(0,3),L[2]);const ne=[0,0,0];return o.dD(ne,W,Z),o.dE(ne)}const Og=["fill","fillOutline","fillPattern","line","linePattern","background","backgroundPattern","hillshade","raster"],I0=["stars","rainParticle","snowParticle","fillExtrusion","fillExtrusionGroundEffect","building","buildingBloom","elevatedStructures","model","symbol"];class Ob{static cacheKey(N,E,z,W){const Z=[E];W&&Z.push(W.cacheKey);for(const ne of z)(typeof ne=="string"&&ne.includes(" ")||N.usedDefines.has(ne))&&Z.push(ne);return Z.join("/")}constructor(N,E,z,W,Z,ne,de=!1){const ye=N.gl;this.program=ye.createProgram(),this._context=N,this._fixedUniformsFn=Z,this._pending=!0,this._precompiled=de,this.attributes={},this.configuration=W,this.name=E,this.fixedDefines=[...ne],de?N._compileStats.precompiled++:N._compileStats.onDemand++;const Ce=`#version 300 es ${(W?W.defines():[]).concat(ne.map(St=>`#define ${St}`)).join(` `)}`,Pe=[Ce,o.dG];for(const St of z.fragmentIncludes)Pe.push(o.ba[St]);Pe.push(z.fragmentSource);const Ke=Pe.join(` `),Ze=[Ce,o.dH];for(const St of z.vertexIncludes)Ze.push(o.ba[St]);this.forceManualRenderingForInstanceIDShaders=N.forceManualRenderingForInstanceIDShaders&&z.vertexSource.includes("gl_InstanceID"),this.forceManualRenderingForInstanceIDShaders&&Ze.push("uniform int u_instanceID;"),Ze.push(z.vertexSource);let mt=Ze.join(` `);this.forceManualRenderingForInstanceIDShaders&&(mt=mt.replaceAll("gl_InstanceID","u_instanceID"));const vt=ye.createShader(ye.FRAGMENT_SHADER);if(ye.isContextLost())return this.failedToCreate=!0,void(this._pending=!1);ye.shaderSource(vt,Ke),ye.compileShader(vt),ye.attachShader(this.program,vt);const bt=ye.createShader(ye.VERTEX_SHADER);if(ye.isContextLost())return this.failedToCreate=!0,void(this._pending=!1);ye.shaderSource(bt,mt),ye.compileShader(bt),ye.attachShader(this.program,bt),ye.linkProgram(this.program),this._fragmentShader=vt,this._vertexShader=bt,N.extParallelShaderCompile?N._pendingPrograms.add(this):this._finalize()}_finalize(){if(!this._pending)return;this._pending=!1;const N=this._context,E=N.gl;N._pendingPrograms.delete(this);const z=o.e.now(),W=E.getProgramParameter(this.program,E.LINK_STATUS),Z=o.e.now()-z,ne=N._compileStats;if(ne.totalStallMs+=Z,Z>ne.maxStallMs&&(ne.maxStallMs=Z),Z>1){ne.framesMissed+=Math.floor(60*Z/1e3);const Ce=this.fixedDefines.join(",");ne.stalls.push({name:`${this.name}${Ce?"/":""}${Ce}`,ms:Z,timestamp:z})}if(this._fragmentShader&&(W||o.w(`Fragment shader '${this.name}': ${E.getShaderInfoLog(this._fragmentShader)}`),E.deleteShader(this._fragmentShader),this._fragmentShader=null),this._vertexShader&&(W||o.w(`Vertex shader '${this.name}': ${E.getShaderInfoLog(this._vertexShader)}`),E.deleteShader(this._vertexShader),this._vertexShader=null),!W)return o.w(`Failed to link program '${this.name}': ${E.getProgramInfoLog(this.program)}`),void(this.failedToCreate=!0);this.fixedUniforms=this._fixedUniformsFn(N),this.fixedUniformsEntries=Object.entries(this.fixedUniforms),this.binderUniforms=this.configuration?this.configuration.getUniforms(N):[],this.forceManualRenderingForInstanceIDShaders&&(this.instancingUniforms=(Ce=>({u_instanceID:new o.aX(Ce)}))(N));const de=this.fixedDefines,ye=this.name;(de.includes("TERRAIN")||de.includes("ELEVATED")||ye.includes("symbol")||ye.includes("circle"))&&(this.terrainUniforms=(Ce=>({u_dem:new o.aX(Ce),u_dem_prev:new o.aX(Ce),u_dem_tl:new o.a3(Ce),u_dem_scale:new o.a4(Ce),u_dem_tl_prev:new o.a3(Ce),u_dem_scale_prev:new o.a4(Ce),u_dem_size:new o.a4(Ce),u_dem_lerp:new o.a4(Ce),u_exaggeration:new o.a4(Ce),u_depth:new o.aX(Ce),u_depth_size_inv:new o.a3(Ce),u_depth_range_unpack:new o.a3(Ce),u_occluder_half_size:new o.a4(Ce),u_occlusion_depth_offset:new o.a4(Ce),u_meter_to_dem:new o.a4(Ce),u_label_plane_matrix_inv:new o.a5(Ce)}))(N)),de.includes("GLOBE")&&(this.globeUniforms=(Ce=>({u_tile_tl_up:new o.a6(Ce),u_tile_tr_up:new o.a6(Ce),u_tile_br_up:new o.a6(Ce),u_tile_bl_up:new o.a6(Ce),u_tile_up_scale:new o.a4(Ce)}))(N)),de.includes("FOG")&&(this.fogUniforms=(Ce=>({u_fog_matrix:new o.a5(Ce),u_fog_range:new o.a3(Ce),u_fog_color:new o.aY(Ce),u_fog_horizon_blend:new o.a4(Ce),u_fog_vertical_limit:new o.a3(Ce),u_fog_temporal_offset:new o.a4(Ce),u_frustum_tl:new o.a6(Ce),u_frustum_tr:new o.a6(Ce),u_frustum_br:new o.a6(Ce),u_frustum_bl:new o.a6(Ce),u_globe_pos:new o.a6(Ce),u_globe_radius:new o.a4(Ce),u_globe_transition:new o.a4(Ce),u_is_globe:new o.aX(Ce),u_viewport:new o.a3(Ce)}))(N)),de.includes("RENDER_CUTOFF")&&(this.cutoffUniforms=o.dI(N)),de.includes("LIGHTING_3D_MODE")&&(this.lightsUniforms=(Ce=>({u_lighting_ambient_color:new o.a6(Ce),u_lighting_directional_dir:new o.a6(Ce),u_lighting_directional_color:new o.a6(Ce),u_ground_radiance:new o.a6(Ce)}))(N)),de.includes("RENDER_SHADOWS")&&(this.shadowUniforms=o.dJ(N))}maybeFinalize(){if(!this._pending)return;const N=this._context.extParallelShaderCompile;N&&!this._context.gl.getProgramParameter(this.program,N.COMPLETION_STATUS_KHR)||this._finalize()}_ensureReady(){this._pending&&(this._finalize(),this._context.sweepPendingPrograms())}getAttributeLocation(N,E){this._ensureReady();let z=this.attributes[E];return z===void 0&&(z=this.attributes[E]=N.getAttribLocation(this.program,E)),z}_setUniformGroup(N,E,z){this._ensureReady();const W=this[E];if(!this.failedToCreate&&W){N.program.set(this.program);for(const Z in z){const ne=W[Z];ne&&ne.set(this.program,Z,z[Z])}}}setTerrainUniformValues(N,E){this._setUniformGroup(N,"terrainUniforms",E)}setGlobeUniformValues(N,E){this._setUniformGroup(N,"globeUniforms",E)}setFogUniformValues(N,E){this._setUniformGroup(N,"fogUniforms",E)}setCutoffUniformValues(N,E){this._setUniformGroup(N,"cutoffUniforms",E)}setLightsUniformValues(N,E){this._setUniformGroup(N,"lightsUniforms",E)}setShadowUniformValues(N,E){this._setUniformGroup(N,"shadowUniforms",E)}_drawDebugWireframe(N,E,z,W,Z,ne,de,ye,Ce,Pe){const Ke=N.options.wireframe;if(Ke.terrain===!1&&Ke.layers2D===!1&&Ke.layers3D===!1)return;const Ze=N.context;if(!(!(!Ke.terrain||this.name!=="terrainRaster"&&this.name!=="globeRaster")||!(!Ke.layers2D||N._terrain&&N._terrain.renderingToTexture||!Og.includes(this.name))||!(!Ke.layers3D||!I0.includes(this.name))))return;const mt=Ze.gl,vt=N.wireframeDebugCache.getLinesFromTrianglesBuffer(N.frameCounter,Z,Ze);if(!vt)return;const bt=[...this.fixedDefines,"DEBUG_WIREFRAME"],St=N.getOrCreateProgram(this.name,{config:this.configuration,defines:bt});St._ensureReady(),Ze.program.set(St.program);const Pt=(ms,Gs,Ms)=>{if(Gs[ms]&&Ms[ms])for(const Js in Gs[ms])Ms[ms][Js]&&Ms[ms][Js].set(Ms.program,Js,Gs[ms][Js].current)};Ce&&Ce.setUniforms(St.program,Ze,St.binderUniforms,de,{zoom:ye}),Pt("fixedUniforms",this,St),Pt("terrainUniforms",this,St),Pt("globeUniforms",this,St),Pt("fogUniforms",this,St),Pt("lightsUniforms",this,St),Pt("shadowUniforms",this,St),vt.bind(),Ze.setColorMode(new o.a1([mt.ONE,mt.ONE_MINUS_SRC_ALPHA,mt.ZERO,mt.ONE],o.C.transparent,[!0,!0,!0,!1])),Ze.setDepthMode(new o.Z(E.func===mt.LESS?mt.LEQUAL:E.func,o.Z.ReadOnly,E.range)),Ze.setStencilMode(o._.disabled);const Gt=3*ne.primitiveLength*2,as=3*ne.primitiveOffset*2*2;if(this.forceManualRenderingForInstanceIDShaders){const ms=Pe||1;for(let Gs=0;Gs1?mt.drawElementsInstanced(mt.LINES,Gt,mt.UNSIGNED_SHORT,as,Pe):mt.drawElements(mt.LINES,Gt,mt.UNSIGNED_SHORT,as);Z.bind(),Ze.program.set(this.program),Ze.setDepthMode(E),Ze.setStencilMode(z),Ze.setColorMode(W)}checkUniforms(N,E,z){if(this.fixedDefines.includes(E)){for(const W of Object.keys(z))if(!z[W].initialized)throw new Error(`Program '${this.name}', from draw '${N}': uniform ${W} not set but required by ${E} being defined`)}}draw(N,E,z,W,Z,ne,de,ye,Ce,Pe,Ke,Ze,mt,vt,bt,St){const Pt=N.context,Gt=Pt.gl;if(this._ensureReady(),this.failedToCreate)return;Pt.program.set(this.program),Pt.setDepthMode(z),Pt.setStencilMode(W),Pt.setColorMode(Z),Pt.setCullFace(ne);for(const[Os,Ks]of this.fixedUniformsEntries)Ks.set(this.program,Os,de[Os]);vt&&vt.setUniforms(this.program,Pt,this.binderUniforms,Ze,{zoom:mt});const as={[Gt.POINTS]:1,[Gt.LINES]:2,[Gt.TRIANGLES]:3,[Gt.LINE_STRIP]:1}[E];this.checkUniforms(ye,"RENDER_SHADOWS",this.shadowUniforms);const ms=bt||[],Gs=vt?vt.getPaintVertexBuffers():[],Ms=E===Gt.TRIANGLES&&Pe,Js=St&&St>0?1:void 0;for(const Os of Ke.get()){const Ks=Os.vaos||(Os.vaos={});if((Ks[ye]||(Ks[ye]=new _c)).bind(Pt,this,Ce,Gs,Pe,Os.vertexOffset,ms,Js),this.forceManualRenderingForInstanceIDShaders){const _n=St||1;for(let ln=0;ln<_n;++ln)this.instancingUniforms.u_instanceID.set(this.program,"u_instanceID",ln),Pe?Gt.drawElements(E,Os.primitiveLength*as,Gt.UNSIGNED_SHORT,Os.primitiveOffset*as*2):Gt.drawArrays(E,Os.vertexOffset,Os.vertexLength)}else St&&St>1?Gt.drawElementsInstanced(E,Os.primitiveLength*as,Gt.UNSIGNED_SHORT,Os.primitiveOffset*as*2,St):Pe?Gt.drawElements(E,Os.primitiveLength*as,Gt.UNSIGNED_SHORT,Os.primitiveOffset*as*2):Gt.drawArrays(E,Os.vertexOffset,Os.vertexLength);Ms&&this._drawDebugWireframe(N,z,W,Z,Pe,Os,Ze,mt,vt,St)}}}const Ev=(L,N,E)=>({u_matrix:L,u_emissive_strength:N,u_ground_shadow_factor:E,u_opacity_multiplier:1}),Cj=(L,N,E,z,W,Z=0)=>Object.assign(Ev(L,N,W),o.dK(E,z,Z)),Fb=(L,N,E,z)=>({u_matrix:L,u_world:E,u_emissive_strength:N,u_ground_shadow_factor:z,u_opacity_multiplier:1}),Zx=(L,N,E,z,W,Z,ne=0)=>Object.assign(Cj(L,N,E,z,Z,ne),{u_world:W}),gp=(L,N,E)=>({u_image:L,u_texel_size:N,u_first_pass:E?1:0}),Tv=o.Y(),tg=(L,N,E,z,W,Z,ne)=>{const de=L.transform,ye=de.projection.name==="globe",Ce=ye?o.dL(de.zoom,N.canonical)*de._pixelsPerMercatorPixel:o.c5(E,1,Z),Pe={u_matrix:N.projMatrix,u_extrude_scale:Ce,u_intensity:ne,u_inv_rot_matrix:Tv,u_merc_center:[0,0],u_tile_id:[0,0,0],u_zoom_transition:0,u_up_dir:[0,0,0]};if(ye){Pe.u_inv_rot_matrix=z,Pe.u_merc_center=W,Pe.u_tile_id=[N.canonical.x,N.canonical.y,1<({u_matrix:N,u_normalize_matrix:E,u_globe_matrix:z,u_merc_matrix:W,u_grid_matrix:Z,u_tl_parent:ne,u_scale_parent:Pe,u_fade_t:Ke.mix,u_opacity:Ke.opacity*Ze.paint.get("raster-opacity"),u_image0:0,u_image1:1,u_brightness_low:Ze.paint.get("raster-brightness-min"),u_brightness_high:Ze.paint.get("raster-brightness-max"),u_saturation_factor:o.dO(Ze.paint.get("raster-saturation")),u_contrast_factor:o.dN(Ze.paint.get("raster-contrast")),u_spin_weights:Vk(Ze.paint.get("raster-hue-rotate")),u_perspective_transform:mt,u_raster_elevation:vt,u_zoom_transition:de,u_merc_center:ye,u_cutoff_params:Ce,u_colorization_mix:Rc(o.dM,St,Gt),u_colorization_offset:xd(o.dM,Pt,Gt),u_color_ramp:bt,u_color_ramp_size:o.dM,u_texture_offset:[ms/(as+2*ms),as/(as+2*ms)],u_texture_res:[as+2*ms,as+2*ms],u_emissive_strength:Gs,u_zbias_factor:Fg(L)});function Vk(L){L*=Math.PI/180;const N=Math.sin(L),E=Math.cos(L);return[(2*E+1)/3,(-Math.sqrt(3)*N-E+1)/3,(Math.sqrt(3)*N-E+1)/3]}const tN=o.Y(),Hk=(L,N,E,z,W,Z,ne,de,ye,Ce,Pe,Ke,Ze,mt,vt,bt,St,Pt,Gt,as,ms,Gs,Ms,Js,Os)=>{const Ks=W.transform,_n={u_is_size_zoom_constant:+(L==="constant"||L==="source"),u_is_size_feature_constant:+(L==="constant"||L==="camera"),u_size_t:N?N.uSizeT:0,u_size:N?N.uSize:0,u_camera_to_center_distance:Ks.getCameraToCenterDistance(as),u_rotate_symbol:+E,u_aspect_ratio:Ks.width/Ks.height,u_fade_change:W.options.fadeDuration?W.symbolFadeChange:1,u_matrix:Z,u_label_plane_matrix:ne,u_coord_matrix:de,u_is_text:+Ce,u_is_sdf:+Pe,u_elevation_from_sea:ye?1:0,u_pitch_with_map:+z,u_texsize:Ke,u_texsize_icon:Ze,u_texture:0,u_texture_icon:1,u_tile_id:[0,0,0],u_zoom_transition:0,u_inv_rot_matrix:tN,u_merc_center:[0,0],u_camera_forward:[0,0,0],u_ecef_origin:[0,0,0],u_tile_matrix:tN,u_up_vector:[0,-1,0],u_color_adj_mat:Ms,u_icon_transition:Js||0,u_gamma_scale:Pe?z?W.transform.getCameraToCenterDistance(as)*Math.cos(W.terrain?0:W.transform._pitch):1:0,u_device_pixel_ratio:o.e.devicePixelRatio,u_is_halo:1,u_scale_factor:Os||1,u_ground_shadow_factor:ms,u_inv_matrix:o.aO(o.Y(),ne),u_normal_scale:Gs,u_lutTexture:o.dQ.LUT,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],u_spp_zoom_fraction:0,u_opacity_multiplier:1};return as.name==="globe"&&(_n.u_tile_id=[vt.canonical.x,vt.canonical.y,1<({u_matrix:L,u_emissive_strength:N,u_opacity:E,u_color:z}),R1=(L,N,E,z,W,Z,ne,de,ye)=>Object.assign(o.dR(W,Z,ne,z,de,ye),{u_matrix:L,u_emissive_strength:N,u_opacity:E}),D1={fillExtrusion:o.dX,fillExtrusionPattern:o.dW,fill:L=>({u_matrix:new o.a5(L),u_emissive_strength:new o.a4(L),u_ground_shadow_factor:new o.a6(L),u_opacity_multiplier:new o.a4(L)}),fillPattern:L=>({u_matrix:new o.a5(L),u_emissive_strength:new o.a4(L),u_image:new o.aX(L),u_texsize:new o.a3(L),u_pixel_coord_upper:new o.a3(L),u_pixel_coord_lower:new o.a3(L),u_tile_units_to_pixels:new o.a4(L),u_ground_shadow_factor:new o.a6(L),u_pattern_transition:new o.a4(L),u_opacity_multiplier:new o.a4(L)}),fillOutline:L=>({u_matrix:new o.a5(L),u_emissive_strength:new o.a4(L),u_world:new o.a3(L),u_ground_shadow_factor:new o.a6(L),u_opacity_multiplier:new o.a4(L)}),fillOutlinePattern:L=>({u_matrix:new o.a5(L),u_emissive_strength:new o.a4(L),u_world:new o.a3(L),u_image:new o.aX(L),u_texsize:new o.a3(L),u_pixel_coord_upper:new o.a3(L),u_pixel_coord_lower:new o.a3(L),u_tile_units_to_pixels:new o.a4(L),u_ground_shadow_factor:new o.a6(L),u_pattern_transition:new o.a4(L),u_opacity_multiplier:new o.a4(L)}),lineBlendComposite:L=>({u_image:new o.aX(L),u_opacity:new o.a4(L),u_blend_mode:new o.aX(L),u_max_density:new o.a4(L)}),lineBlendReduce:L=>({u_image:new o.aX(L),u_texel_size:new o.a3(L),u_first_pass:new o.aX(L)}),circle:o.dV,collisionBox:L=>({u_matrix:new o.a5(L),u_inv_rot_matrix:new o.a5(L),u_camera_to_center_distance:new o.a4(L),u_extrude_scale:new o.a3(L),u_zoom_transition:new o.a4(L),u_merc_center:new o.a3(L),u_tile_id:new o.a6(L)}),collisionCircle:L=>({u_matrix:new o.a5(L),u_inv_matrix:new o.a5(L),u_camera_to_center_distance:new o.a4(L),u_viewport_size:new o.a3(L)}),debug:o.dU,clippingMask:L=>({u_matrix:new o.a5(L)}),heatmap:L=>({u_extrude_scale:new o.a4(L),u_intensity:new o.a4(L),u_matrix:new o.a5(L),u_inv_rot_matrix:new o.a5(L),u_merc_center:new o.a3(L),u_tile_id:new o.a6(L),u_zoom_transition:new o.a4(L),u_up_dir:new o.a6(L)}),heatmapTexture:L=>({u_image:new o.aX(L),u_color_ramp:new o.aX(L),u_opacity:new o.a4(L)}),hillshade:L=>({u_matrix:new o.a5(L),u_image:new o.aX(L),u_latrange:new o.a3(L),u_light:new o.a3(L),u_shadow:new o.dq(L),u_highlight:new o.dq(L),u_emissive_strength:new o.a4(L),u_accent:new o.dq(L)}),hillshadePrepare:L=>({u_matrix:new o.a5(L),u_image:new o.aX(L),u_dimension:new o.a3(L),u_zoom:new o.a4(L)}),line:o.dT,linePattern:o.dS,raster:L=>({u_matrix:new o.a5(L),u_normalize_matrix:new o.a5(L),u_globe_matrix:new o.a5(L),u_merc_matrix:new o.a5(L),u_grid_matrix:new o.aZ(L),u_tl_parent:new o.a3(L),u_scale_parent:new o.a4(L),u_fade_t:new o.a4(L),u_opacity:new o.a4(L),u_image0:new o.aX(L),u_image1:new o.aX(L),u_brightness_low:new o.a4(L),u_brightness_high:new o.a4(L),u_saturation_factor:new o.a4(L),u_contrast_factor:new o.a4(L),u_spin_weights:new o.a6(L),u_perspective_transform:new o.a3(L),u_raster_elevation:new o.a4(L),u_zoom_transition:new o.a4(L),u_merc_center:new o.a3(L),u_cutoff_params:new o.aY(L),u_colorization_mix:new o.aY(L),u_colorization_offset:new o.a4(L),u_color_ramp:new o.aX(L),u_color_ramp_size:new o.a4(L),u_texture_offset:new o.a3(L),u_texture_res:new o.a3(L),u_emissive_strength:new o.a4(L),u_zbias_factor:new o.a4(L)}),symbol:L=>({u_is_size_zoom_constant:new o.aX(L),u_is_size_feature_constant:new o.aX(L),u_size_t:new o.a4(L),u_size:new o.a4(L),u_camera_to_center_distance:new o.a4(L),u_rotate_symbol:new o.aX(L),u_aspect_ratio:new o.a4(L),u_fade_change:new o.a4(L),u_matrix:new o.a5(L),u_label_plane_matrix:new o.a5(L),u_coord_matrix:new o.a5(L),u_is_text:new o.aX(L),u_is_sdf:new o.aX(L),u_elevation_from_sea:new o.aX(L),u_pitch_with_map:new o.aX(L),u_texsize:new o.a3(L),u_texsize_icon:new o.a3(L),u_texture:new o.aX(L),u_texture_icon:new o.aX(L),u_gamma_scale:new o.a4(L),u_device_pixel_ratio:new o.a4(L),u_tile_id:new o.a6(L),u_zoom_transition:new o.a4(L),u_inv_rot_matrix:new o.a5(L),u_merc_center:new o.a3(L),u_camera_forward:new o.a6(L),u_tile_matrix:new o.a5(L),u_up_vector:new o.a6(L),u_ecef_origin:new o.a6(L),u_is_halo:new o.aX(L),u_icon_transition:new o.a4(L),u_color_adj_mat:new o.a5(L),u_scale_factor:new o.a4(L),u_ground_shadow_factor:new o.a6(L),u_inv_matrix:new o.a5(L),u_normal_scale:new o.a4(L),u_lutTexture:new o.aX(L),u_spp_fill_np_color:new o.aY(L),u_spp_halo_np_color:new o.aY(L),u_spp_opacity:new o.a4(L),u_spp_halo_width:new o.a4(L),u_spp_halo_blur:new o.a4(L),u_spp_emissive_strength:new o.a4(L),u_spp_occlusion_opacity:new o.a4(L),u_spp_z_offset:new o.a4(L),u_spp_translate_rotation:new o.a3(L),u_spp_zoom_fraction:new o.a4(L),u_opacity_multiplier:new o.a4(L)}),background:L=>({u_matrix:new o.a5(L),u_emissive_strength:new o.a4(L),u_opacity:new o.a4(L),u_color:new o.dq(L)}),backgroundPattern:L=>({u_matrix:new o.a5(L),u_emissive_strength:new o.a4(L),u_opacity:new o.a4(L),u_image:new o.aX(L),u_pattern_tl:new o.a3(L),u_pattern_br:new o.a3(L),u_texsize:new o.a3(L),u_pattern_size:new o.a3(L),u_pixel_coord_upper:new o.a3(L),u_pixel_coord_lower:new o.a3(L),u_pattern_units_to_pixels:new o.a3(L)}),terrainRaster:L=>({u_matrix:new o.a5(L),u_image0:new o.aX(L),u_image1:new o.aX(L),u_skirt_height:new o.a4(L),u_ground_shadow_factor:new o.a6(L),u_emissive_texture_available:new o.a4(L)}),skybox:L=>({u_matrix:new o.a5(L),u_sun_direction:new o.a6(L),u_cubemap:new o.aX(L),u_opacity:new o.a4(L),u_temporal_offset:new o.a4(L)}),skyboxGradient:L=>({u_matrix:new o.a5(L),u_color_ramp:new o.aX(L),u_center_direction:new o.a6(L),u_radius:new o.a4(L),u_opacity:new o.a4(L),u_temporal_offset:new o.a4(L)}),skyboxCapture:L=>({u_matrix_3f:new o.aZ(L),u_sun_direction:new o.a6(L),u_sun_intensity:new o.a4(L),u_color_tint_r:new o.aY(L),u_color_tint_m:new o.aY(L),u_luminance:new o.a4(L)}),globeRaster:L=>({u_proj_matrix:new o.a5(L),u_globe_matrix:new o.a5(L),u_normalize_matrix:new o.a5(L),u_merc_matrix:new o.a5(L),u_zoom_transition:new o.a4(L),u_merc_center:new o.a3(L),u_image0:new o.aX(L),u_image1:new o.aX(L),u_grid_matrix:new o.aZ(L),u_skirt_height:new o.a4(L),u_far_z_cutoff:new o.a4(L),u_frustum_tl:new o.a6(L),u_frustum_tr:new o.a6(L),u_frustum_br:new o.a6(L),u_frustum_bl:new o.a6(L),u_globe_pos:new o.a6(L),u_globe_radius:new o.a4(L),u_viewport:new o.a3(L),u_emissive_texture_available:new o.a4(L)}),globeAtmosphere:L=>({u_frustum_tl:new o.a6(L),u_frustum_tr:new o.a6(L),u_frustum_br:new o.a6(L),u_frustum_bl:new o.a6(L),u_horizon:new o.a4(L),u_transition:new o.a4(L),u_fadeout_range:new o.a4(L),u_atmosphere_fog_color:new o.aY(L),u_high_color:new o.aY(L),u_space_color:new o.aY(L),u_temporal_offset:new o.a4(L),u_horizon_angle:new o.a4(L)}),stars:L=>({u_matrix:new o.a5(L),u_up:new o.a6(L),u_right:new o.a6(L),u_intensity_multiplier:new o.a4(L)}),occlusion:L=>({u_matrix:new o.a5(L),u_anchorPos:new o.a6(L),u_screenSizePx:new o.a3(L),u_occluderSizePx:new o.a3(L),u_color:new o.aY(L)})};class xp{constructor(N,E,z,W){this.id=xp.uniqueIdxCounter,xp.uniqueIdxCounter++,this.context=N;const Z=N.gl;this.buffer=Z.createBuffer(),this.dynamicDraw=!!z,this.context.unbindVAO(),N.bindElementBuffer.set(this.buffer),Z.bufferData(Z.ELEMENT_ARRAY_BUFFER,E.arrayBuffer,this.dynamicDraw?Z.DYNAMIC_DRAW:Z.STATIC_DRAW),this.dynamicDraw||W||E.destroy()}bind(){this.context.bindElementBuffer.set(this.buffer)}updateData(N){this.id=xp.uniqueIdxCounter,xp.uniqueIdxCounter++;const E=this.context.gl;this.context.unbindVAO(),this.bind(),E.bufferSubData(E.ELEMENT_ARRAY_BUFFER,0,N.arrayBuffer)}destroy(){this.buffer&&(this.context.gl.deleteBuffer(this.buffer),delete this.buffer)}}xp.uniqueIdxCounter=0;const L0={Int8:"BYTE",Uint8:"UNSIGNED_BYTE",Int16:"SHORT",Uint16:"UNSIGNED_SHORT",Int32:"INT",Uint32:"UNSIGNED_INT",Float32:"FLOAT"};class Qx{constructor(N,E,z,W,Z,ne){this.length=E.length,this.attributes=z,this.itemSize=E.bytesPerElement,this.dynamicDraw=W,this.instanceCount=ne,this.context=N;const de=N.gl;this.buffer=de.createBuffer(),N.bindVertexBuffer.set(this.buffer),de.bufferData(de.ARRAY_BUFFER,E.arrayBuffer,this.dynamicDraw?de.DYNAMIC_DRAW:de.STATIC_DRAW),this.dynamicDraw||Z||E.destroy()}bind(){this.context.bindVertexBuffer.set(this.buffer)}updateData(N){const E=this.context.gl;this.bind(),E.bufferSubData(E.ARRAY_BUFFER,0,N.arrayBuffer)}enableAttributes(N,E){for(const z of this.attributes){const W=E.getAttributeLocation(N,z.name);W!==-1&&N.enableVertexAttribArray(W)}}setVertexAttribPointers(N,E,z){for(const W of this.attributes){const Z=E.getAttributeLocation(N,W.name);if(Z!==-1){const ne=W.offset+this.itemSize*(z||0);W.type==="Float32"?N.vertexAttribPointer(Z,W.components,N.FLOAT,!1,this.itemSize,ne):N.vertexAttribIPointer(Z,W.components,N[L0[W.type]],this.itemSize,ne)}}}setVertexAttribDivisor(N,E,z){for(let W=0;W0&&N.vertexAttribDivisor(Z,z)}}destroy(){this.buffer&&(this.context.gl.deleteBuffer(this.buffer),delete this.buffer)}}class yp{constructor(N,E,z,W,Z){this.context=N,this.width=E,this.height=z;const ne=this.framebuffer=N.gl.createFramebuffer();W>0&&(this.colorAttachment0=new zf(N,ne,0)),W>1&&(this.colorAttachment1=new zf(N,ne,1)),Z&&(this.depthAttachmentType=Z,this.depthAttachment=Z==="renderbuffer"?new Cv(N,ne):new Sh(N,ne))}static createWithTexture(N,E,z,W,Z){const ne=N.gl;if(N.activeTexture.set(ne.TEXTURE1),N.viewport.set([0,0,z,W]),E&&E.width===z&&E.height===W)return ne.bindTexture(ne.TEXTURE_2D,E.colorAttachment0.get()),N.bindFramebuffer.set(E.framebuffer),E;E&&E.destroy();const de=N.extRenderToTextureHalfFloat||N.extColorBufferFloat?N.gl.RGBA16F:N.gl.RGBA8,ye=new o.T(N,{width:z,height:W,data:null},de);ye.bind(ne.LINEAR,ne.CLAMP_TO_EDGE);const Ce=N.createFramebuffer(z,W,1,null);if(Ce.format=de,Ce.colorAttachment0.set(ye.texture),Z){const Pe=N.createRenderbuffer(ne.DEPTH24_STENCIL8,z,W);N.bindFramebuffer.set(Ce.framebuffer),ne.framebufferRenderbuffer(ne.FRAMEBUFFER,ne.DEPTH_STENCIL_ATTACHMENT,ne.RENDERBUFFER,Pe),Ce._stencilRbo=Pe}return Ce}createColorAttachment(N,E){E===0?this.colorAttachment0=new zf(N,this.framebuffer,0):E===1&&(this.colorAttachment1=new zf(N,this.framebuffer,1))}removeColorAttachment(N,E){const z=this.context.gl;let W;E===0?(W=this.colorAttachment0.get(),this.colorAttachment0=void 0):E===1&&(W=this.colorAttachment1.get(),this.colorAttachment1=void 0),W&&z.deleteTexture(W)}destroy(){const N=this.context.gl;if(this.colorAttachment0){const E=this.colorAttachment0.get();E&&N.deleteTexture(E)}if(this.colorAttachment1){const E=this.colorAttachment1.get();E&&N.deleteTexture(E)}if(this.depthAttachment&&this.depthAttachmentType)if(this.depthAttachmentType==="renderbuffer"){const E=this.depthAttachment.get();E&&N.deleteRenderbuffer(E)}else{const E=this.depthAttachment.get();E&&N.deleteTexture(E)}this._stencilRbo&&(N.deleteRenderbuffer(this._stencilRbo),this._stencilRbo=null),N.deleteFramebuffer(this.framebuffer)}}class xx{constructor(N,E){this.gl=N,this._pendingPrograms=new Set,this._compileStats={precompiled:0,onDemand:0,totalStallMs:0,maxStallMs:0,framesMissed:0,stalls:[]},this.clearColor=new po(this),this.clearDepth=new ol(this),this.clearStencil=new Uc(this),this.colorMask=new tf(this),this.depthMask=new Zp(this),this.stencilMask=new vd(this),this.stencilFunc=new sf(this),this.stencilOp=new Lu(this),this.stencilTest=new am(this),this.depthRange=new Dc(this),this.depthTest=new Cd(this),this.depthFunc=new mh(this),this.blend=new zd(this),this.blendFunc=new fh(this),this.blendColor=new Of(this),this.blendEquation=new Xu(this),this.cullFace=new Qd(this),this.cullFaceSide=new bd(this),this.frontFace=new Ru(this),this.program=new Rg(this),this.activeTexture=new Am(this),this.viewport=new pp(this),this.bindFramebuffer=new Xp(this),this.bindRenderbuffer=new Ff(this),this.bindTexture=new Dg(this),this.bindVertexBuffer=new _d(this),this.bindElementBuffer=new Qp(this),this.bindVertexArrayOES=new wd(this),this.pixelStoreUnpack=new ll(this),this.pixelStoreUnpackPremultiplyAlpha=new Du(this),this.pixelStoreUnpackFlipY=new Oc(this),this.options=E?{...E}:{},this.options.extTextureFilterAnisotropicForceOff||(this.extTextureFilterAnisotropic=N.getExtension("EXT_texture_filter_anisotropic")||N.getExtension("MOZ_EXT_texture_filter_anisotropic")||N.getExtension("WEBKIT_EXT_texture_filter_anisotropic"),this.extTextureFilterAnisotropic&&(this.extTextureFilterAnisotropicMax=N.getParameter(this.extTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT))),this.extDebugRendererInfo=N.getExtension("WEBGL_debug_renderer_info"),this.extDebugRendererInfo&&(this.renderer=N.getParameter(this.extDebugRendererInfo.UNMASKED_RENDERER_WEBGL),this.vendor=N.getParameter(this.extDebugRendererInfo.UNMASKED_VENDOR_WEBGL)),this.forceManualRenderingForInstanceIDShaders=E&&!!E.forceManualRenderingForInstanceIDShaders||this.renderer&&this.renderer.includes("PowerVR"),this.options.extTextureFloatLinearForceOff||(this.extTextureFloatLinear=N.getExtension("OES_texture_float_linear")),this.extRenderToTextureHalfFloat=N.getExtension("EXT_color_buffer_half_float"),this.extColorBufferFloat=N.getExtension("EXT_color_buffer_float"),this.extTimerQuery=N.getExtension("EXT_disjoint_timer_query_webgl2"),this.maxTextureSize=N.getParameter(N.MAX_TEXTURE_SIZE),this.maxUniformBlockSize=Math.min(N.getParameter(N.MAX_UNIFORM_BLOCK_SIZE),32768),this.maxUniformBufferBindings=N.getParameter(N.MAX_UNIFORM_BUFFER_BINDINGS),this.extBlendFuncExtended=N.getExtension("WEBGL_blend_func_extended"),this.extParallelShaderCompile=N.getExtension("KHR_parallel_shader_compile")}sweepPendingPrograms(){if(this._pendingPrograms.size!==0)for(const N of this._pendingPrograms)N.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(N,E,z){return new xp(this,N,E,z)}createVertexBuffer(N,E,z,W,Z){return new Qx(this,N,E,z,W,Z)}createRenderbuffer(N,E,z){const W=this.gl,Z=W.createRenderbuffer();return this.bindRenderbuffer.set(Z),W.renderbufferStorage(W.RENDERBUFFER,N,E,z),this.bindRenderbuffer.set(null),Z}createFramebuffer(N,E,z,W){return new yp(this,N,E,z,W)}clear({color:N,depth:E,stencil:z,colorMask:W}){const Z=this.gl;let ne=0;N&&(ne|=Z.COLOR_BUFFER_BIT,this.clearColor.set(N.toNonPremultipliedRenderColor(null)),this.colorMask.set(W||[!0,!0,!0,!0])),E!==void 0&&(ne|=Z.DEPTH_BUFFER_BIT,this.depthRange.set([0,1]),this.clearDepth.set(E),this.depthMask.set(!0)),z!==void 0&&(ne|=Z.STENCIL_BUFFER_BIT,this.clearStencil.set(z),this.stencilMask.set(255)),Z.clear(ne)}setCullFace(N){N.enable===!1?this.cullFace.set(!1):(this.cullFace.set(!0),this.cullFaceSide.set(N.mode),this.frontFace.set(N.frontFace))}setDepthMode(N){N.func!==this.gl.ALWAYS||N.mask?(this.depthTest.set(!0),this.depthFunc.set(N.func),this.depthMask.set(N.mask),this.depthRange.set(N.range)):this.depthTest.set(!1)}setStencilMode(N){N.test.func!==this.gl.ALWAYS||N.mask?(this.stencilTest.set(!0),this.stencilMask.set(N.mask),this.stencilOp.set([N.fail,N.depthFail,N.pass]),this.stencilFunc.set({func:N.test.func,ref:N.ref,mask:N.test.mask})):this.stencilTest.set(!1)}setColorMode(N){o.O(N.blendFunction,o.a1.Replace)?this.blend.set(!1):(this.blend.set(!0),this.blendFunc.set(N.blendFunction),this.blendColor.set(N.blendColor),N.blendEquation?this.blendEquation.set(N.blendEquation):this.blendEquation.setDefault()),this.colorMask.set(N.mask)}unbindVAO(){this.bindVertexArrayOES.set(null)}}const Jx=o.Y();function Vr(L){const N=L._camera.getWorldToCamera(L.worldSize,1),E=o.X([],N,L.globeMatrix);o.aO(E,E);const z=[0,0,0],W=[0,1,0,0];return o.c7(W,W,E),z[0]=W[0],z[1]=W[1],z[2]=W[2],o.c3(z,z),z}function v4({width:L,height:N,anchor:E,textOffset:z,textScale:W},Z){const{horizontalAlign:ne,verticalAlign:de}=o.cM(E),ye=-(ne-.5)*L,Ce=-(de-.5)*N,Pe=o.cN(E,z);return new o.P((ye/W+Pe[0])*Z,(Ce/W+Pe[1])*Z)}function b4(L,N,E,z,W,Z,ne,de,ye,Ce){const Pe=L.text.placedSymbolArray,Ke=L.text.dynamicLayoutVertexArray,Ze=L.icon.dynamicLayoutVertexArray,mt={},vt=L.getProjection(),bt=Gm(ne,vt,W),St=W.elevation,Pt=vt.upVectorScale(ne.canonical,W.center.lat,W.worldSize).metersToTile;Ke.clear();for(let Gt=0;Gt=0&&(mt[as.associatedIconIndex]={x:an,y:bn,z:Sn,angle:oa})}else o.dZ(Ms,Ke)}if(Ce){Ze.clear();const Gt=L.icon.placedSymbolArray;for(let as=0;as{let zl=[0,0,0];if(Yl){const Ud=L.style.directionalLight,af=L.style.ambientLight;Ud&&af&&(zl=o.aF(L.style,Ud,af))}return zl},Wo=Yl=>{const zl=Math.floor(L.context.maxUniformBlockSize/4),Ud=Math.floor(zl/4);Yl.push(`MAX_UBO_SIZE_VEC4 ${Ud}u`)},Va=Yl=>{Ks.depthOcclusionForSymbolsAndCircles&&(E.hasOcclusionOpacityProperties||L.terrain)&&(Yl.push("DEPTH_D24"),Yl.push("DEPTH_OCCLUSION"))},Vc=Yl=>{E.lut&&!Ms&&(E.lut.texture||(E.lut.texture=new o.e1(L.context,E.lut.image,[E.lut.image.height,E.lut.image.height,E.lut.image.height],Js.gl.RGBA8)),Js.activeTexture.set(Js.gl.TEXTURE0+o.dQ.LUT),E.lut.texture&&E.lut.texture.bind(Js.gl.LINEAR,Js.gl.CLAMP_TO_EDGE),Yl.push("APPLY_LUT_ON_GPU"))},Ju=()=>{const Yl=_n&&E.layout.get("symbol-placement")!=="point",zl=[];Va(zl),Vc(zl);const Ud=Yl||ao,af=Fr.elevationType==="road",Pv=L.shadowRenderer,ty=af&&an&&!!Pv&&Pv.enabled,ew=Tc(ty),Ad=af&&an&&!L.terrain?Hn:Mn,jc=E.paint.get("icon-image-cross-fade");L.terrainRenderModeElevated()&&an&&zl.push("PITCH_WITH_MAP_TERRAIN"),Fa&&(zl.push("PROJECTION_GLOBE_VIEW"),Ud&&zl.push("PROJECTED_POS_ON_VIEWPORT")),jc>0&&Fr.hasAnySecondaryIcon&&zl.push("ICON_TRANSITION"),!Fr.icon.zOffsetVertexBuffer||af&&L.terrain||zl.push("Z_OFFSET"),Pt===0&&Gt===0&&as===0&&ms===1||zl.push("COLOR_ADJUSTMENT"),ty&&zl.push("RENDER_SHADOWS","NORMAL_OFFSET"),af&&an&&!L.terrain&&Fr.icon.orientationVertexBuffer&&zl.push("ELEVATED_ROADS"),Wo(zl);const Zl=L.getOrCreateProgram("symbol",{defines:zl}),zu=cr.imageAtlasTexture?cr.imageAtlasTexture.size:[0,0],bp=Fr.iconSizeData,qd=o.cG(bp,Ks.zoom),_l=an||!Ks.isOrthographic,of=o.dY(Ta,cr.tileID.canonical,an,_n,Ks,Fr.getProjection(),ci),Bf=o.cF(Ta,cr.tileID.canonical,an,_n,Ks,Fr.getProjection(),ci),Bb=Fr.icon.uboBinder&&Fr.icon.uboBinder.hasPerFeatureTranslate()?[0,0]:de,$b=L.translatePosMatrix(Bf,cr,Bb,Ce,!0),Ej=L.translatePosMatrix(Ta,cr,Bb,Ce),F1=Ud?Jx:of,Kk=_n&&!an&&!Yl;let tw=qa;!Qr&&!Ks.mercatorFromTransition||_n||(tw=Vr(Ks));const lc=Fa?tw:qa,Yk=E.getColorAdjustmentMatrix(Pt,Gt,as,ms),d7=Hk(bp.kind,qd,Kk,an,L,Ej,F1,$b,Gs,!1,Fr.sdfIcons,zu,[0,0],0,Nr,ta,Tr,Io,lc,Fr.getProjection(),ew,qc,Yk,jc,null),rH=cr.imageAtlasTexture?cr.imageAtlasTexture:null,aH=E.layout.get("icon-size").constantOr(0)!==1||Fr.iconsNeedLinear,M4=Fr.sdfIcons||L.options.rotating||L.options.zooming||aH||_l?Os.LINEAR:Os.NEAREST,u7=Fr.sdfIcons&&E.paint.get("icon-halo-width").constantOr(1)!==0,U6=L.terrain&&an&&Yl?o.aO(o.Y(),of):Jx;if(Yl&&Fr.icon){const vA=o.cW.getAtTileOffsetFunc(Nr,Ks.center.lat,Ks.worldSize,Fr.getProjection()),Ub=o.cE(Ta,cr.tileID.canonical,an,_n,Ks,Fr.getProjection(),ci),im=E.layout.get("icon-size-scale-range"),Zi=o.b0(L.scaleFactor,im[0],im[1]);o.e0(Fr,Ta,L,!1,Ub,Bf,an,bt,vA,Nr,Zi)}return{program:Zl,buffers:Fr.icon,uniformValues:d7,atlasTexture:rH,atlasTextureIcon:null,atlasInterpolation:M4,atlasInterpolationIcon:null,isSDF:Fr.sdfIcons,hasHalo:u7,depthMode:Ad,tile:cr,renderWithShadows:ty,labelPlaneMatrixInv:U6}},du=()=>{const Yl=ln&&E.layout.get("symbol-placement")!=="point",zl=[],Ud=Yl||oa||ao,af=Fr.elevationType==="road",Pv=L.shadowRenderer,ty=af&&bn&&!!Pv&&Pv.enabled,ew=Tc(ty),Ad=af&&bn&&!L.terrain?Hn:Mn;L.terrainRenderModeElevated()&&bn&&zl.push("PITCH_WITH_MAP_TERRAIN"),Fa&&(zl.push("PROJECTION_GLOBE_VIEW"),Ud&&zl.push("PROJECTED_POS_ON_VIEWPORT")),!Fr.text.zOffsetVertexBuffer||af&&L.terrain||zl.push("Z_OFFSET"),Fr.iconsInText&&zl.push("RENDER_TEXT_AND_SYMBOL"),ty&&zl.push("RENDER_SHADOWS","NORMAL_OFFSET"),af&&bn&&!L.terrain&&Fr.text.orientationVertexBuffer&&zl.push("ELEVATED_ROADS"),Va(zl),Wo(zl);const jc=L.getOrCreateProgram("symbol",{defines:zl});let Zl,zu=[0,0],bp=null;const qd=Fr.textSizeData;Fr.iconsInText&&(zu=cr.imageAtlasTexture?cr.imageAtlasTexture.size:[0,0],bp=cr.imageAtlasTexture?cr.imageAtlasTexture:null,Zl=bn||!Ks.isOrthographic||L.options.rotating||L.options.zooming||qd.kind==="composite"||qd.kind==="camera"?Os.LINEAR:Os.NEAREST);const _l=cr.glyphAtlasTexture?cr.glyphAtlasTexture.size:[0,0],of=E.layout.get("text-size-scale-range"),Bf=o.b0(L.scaleFactor,of[0],of[1]),Bb=o.cG(qd,Ks.zoom,Bf),$b=o.dY(Ta,cr.tileID.canonical,bn,ln,Ks,Fr.getProjection(),ci),Ej=o.cF(Ta,cr.tileID.canonical,bn,ln,Ks,Fr.getProjection(),ci),F1=Fr.text.uboBinder&&Fr.text.uboBinder.hasPerFeatureTranslate()?[0,0]:ye,Kk=L.translatePosMatrix(Ej,cr,F1,Pe,!0),tw=L.translatePosMatrix(Ta,cr,F1,Pe),lc=Ud?Jx:$b,Yk=ln&&!bn&&!Yl;let d7=qa;!Qr&&!Ks.mercatorFromTransition||ln||(d7=Vr(Ks));const rH=Hk(qd.kind,Bb,Yk,bn,L,tw,lc,Kk,Gs,!0,!0,_l,zu,0,Nr,ta,Tr,Io,Fa?d7:qa,Fr.getProjection(),ew,qc,null,null,Bf),aH=cr.glyphAtlasTexture?cr.glyphAtlasTexture:null,M4=Os.LINEAR,u7=E.paint.get("text-halo-width").constantOr(1)!==0,U6=L.terrain&&bn&&Yl?o.aO(o.Y(),$b):Jx;if(Yl&&Fr.text){const vA=o.cW.getAtTileOffsetFunc(Nr,Ks.center.lat,Ks.worldSize,Fr.getProjection()),Ub=o.cE(Ta,cr.tileID.canonical,bn,ln,Ks,Fr.getProjection(),ci);o.e0(Fr,Ta,L,!0,Ub,Ej,bn,St,vA,Nr,Bf)}return{program:jc,buffers:Fr.text,uniformValues:rH,atlasTexture:aH,atlasTextureIcon:bp,atlasInterpolation:M4,atlasInterpolationIcon:Zl,isSDF:!0,hasHalo:u7,depthMode:Ad,tile:cr,renderWithShadows:ty,labelPlaneMatrixInv:U6}},bl=Fr.icon.segments.get().length,uu=Fr.text.segments.get().length,dd=bl&&!ne.onlyText?Ju():null,gl=uu&&!ne.onlyIcons?du():null,Hc=E.paint.get("icon-opacity").constantOr(1),Fu=E.paint.get("text-opacity").constantOr(1);if(Sn&&Fr.canOverlap){lr=!0;const Yl=Hc&&!ne.onlyText?Fr.icon.segments.get():[],zl=Fu&&!ne.onlyIcons?Fr.text.segments.get():[];for(const Ud of Yl)Lr.push({segments:new o.ac([Ud]),sortKey:Ud.sortKey,state:dd});for(const Ud of zl)Lr.push({segments:new o.ac([Ud]),sortKey:Ud.sortKey,state:gl})}else ne.onlyText||Lr.push({segments:Hc?Fr.icon.segments:new o.ac([]),sortKey:0,state:dd}),ne.onlyIcons||Lr.push({segments:Fu?Fr.text.segments:new o.ac([]),sortKey:0,state:gl})}lr&&Lr.sort((Nr,cr)=>Nr.sortKey-cr.sortKey);for(const Nr of Lr){const cr=Nr.state;if(cr)if(L.terrain?L.terrain.setupElevationDraw(cr.tile,cr.program,{useDepthForOcclusion:Ks.depthOcclusionForSymbolsAndCircles,labelPlaneMatrixInv:cr.labelPlaneMatrixInv}):L.setupDepthForOcclusion(Ks.depthOcclusionForSymbolsAndCircles,cr.program),Js.activeTexture.set(Os.TEXTURE0),cr.atlasTexture&&cr.atlasTexture.bind(cr.atlasInterpolation,Os.CLAMP_TO_EDGE,!0),cr.atlasTextureIcon&&(Js.activeTexture.set(Os.TEXTURE1),cr.atlasTextureIcon&&cr.atlasTextureIcon.bind(cr.atlasInterpolationIcon,Os.CLAMP_TO_EDGE,!0)),cr.renderWithShadows&&L.shadowRenderer.setupShadows(cr.tile.tileID.toUnwrapped(),cr.program,"vector-tile"),L.uploadCommonLightUniforms(L.context,cr.program),cr.hasHalo){const Fr=cr.uniformValues;Fr.u_is_halo=1,Gh(cr.buffers,Nr.segments,E,L,cr.program,cr.depthMode,W,Z,Fr,2),Fr.u_is_halo=0}else{if(cr.isSDF){const Fr=cr.uniformValues;cr.hasHalo&&(Fr.u_is_halo=1,Gh(cr.buffers,Nr.segments,E,L,cr.program,cr.depthMode,W,Z,Fr,1)),Fr.u_is_halo=0}Gh(cr.buffers,Nr.segments,E,L,cr.program,cr.depthMode,W,Z,cr.uniformValues,1)}}}function Gh(L,N,E,z,W,Z,ne,de,ye,Ce){const Pe=z.context,Ke=Pe.gl,Ze=[L.dynamicLayoutVertexBuffer,L.opacityVertexBuffer,L.iconTransitioningVertexBuffer,L.globeExtVertexBuffer,L.zOffsetVertexBuffer,L.orientationVertexBuffer];L.featureIdBuffer&&Ze.push(L.featureIdBuffer);const mt=L.uboBinder?null:L.programConfigurations.get(E.id);if(L.uboBinder){L.uboBinder.layer=E;const St=z.transform.zoom,Pt=z.style.getBrightness?z.style.getBrightness():null,Gt=L.uboBinder.getConstantUniformValues(St,Pt);ye.u_spp_fill_np_color=Gt.fill_np_color,ye.u_spp_halo_np_color=Gt.halo_np_color,ye.u_spp_opacity=Gt.opacity,ye.u_spp_halo_width=Gt.halo_width,ye.u_spp_halo_blur=Gt.halo_blur,ye.u_spp_emissive_strength=Gt.emissive_strength,ye.u_spp_occlusion_opacity=Gt.occlusion_opacity,ye.u_spp_z_offset=Gt.z_offset,ye.u_spp_zoom_fraction=St-L.uboBinder._floorZoom;const as=E.paint.get(L.uboBinder.isText?"text-translate-anchor":"icon-translate-anchor"),ms=L.uboBinder.hasPerFeatureTranslate()&&as==="map"?z.transform.angle:0;ye.u_spp_translate_rotation=[Math.cos(ms),Math.sin(ms)]}const{batchIndices:vt,batchSegments:bt}=L.getBatchGrouping(N);for(const St of vt){const Pt=bt.get(St);L.uboBinder&&L.uboBinder.bind(Pe,W.program,St),W.draw(z,Ke.TRIANGLES,Z,ne,de,o.$.disabled,ye,E.id,L.layoutVertexBuffer,L.indexBuffer,Pt,E.paint,z.transform.zoom,mt,Ze,Ce)}}function R0(L,N,E,z,W,Z){const ne=E.paint.get("line-width"),de=E.paint.get("line-emissive-strength").isConstant(),ye=E.paint.get("line-emissive-strength").constantOr(0),Ce=E.paint.get("line-occlusion-opacity"),Pe=E.layout.get("line-elevation-reference"),Ke=E.layout.get("line-width-unit")==="meters",Ze=Pe==="sea",mt=!(!L.terrain||!L.terrain.enabled),vt=L.context,bt=vt.gl;if(E.hasElevatedBuckets&&L.transform.projection.name==="globe")return;const St=E.layout.get("line-cross-slope"),Pt=St!==void 0,Gt=St<1,as=W||L.colorModeForDrapableLayerRenderPass(de?ye:null),ms=L.terrain&&L.terrain.renderingToTexture||Z,Gs=ms?1:o.e.devicePixelRatio,Ms=E.paint.get("line-dasharray"),Js=Ms.constantOr(1),Os=E.layout.get("line-cap"),Ks=Ms.constantOr(null),_n=Os.constantOr(null),ln=E.paint.get("line-pattern"),an=ln.constantOr(1),bn=E.paint.get("line-pattern-cross-fade"),Sn=ln.constantOr(null),lr=E.paint.get("line-opacity").constantOr(1);let Mn=!an&&lr!==1||L.depthOcclusion&&Ce>0&&Ce<1;const Hn=E.paint.get("line-gradient"),Tr=E.paint.get("line-border-width").constantOr(1)!==0?E.paint.get("line-border-gradient"):null,oa=an?"linePattern":"line",Qr=o.e4(E);let Lr;if(ms&&L.terrain&&L.terrain.clipOrMaskOverlapStencilType()&&(Mn=!1),Ce!==0&&L.depthOcclusion){const Ta=E.paint._values["line-opacity"];Ta&&Ta.value&&Ta.value.kind==="constant"?Lr=Ta.value:o.w(`Occlusion opacity for layer ${E.id} is supported only when line-opacity isn't data-driven.`)}ne.value.kind!=="constant"&&ne.value.isLineProgressConstant===!1&&Qr.push("VARIABLE_LINE_WIDTH");const qa=E.paint.get("line-emissive-strength");an||qa.value.kind==="constant"||qa.value.isLineProgressConstant!==!1||Qr.push("VARIABLE_LINE_EMISSIVE_STRENGTH"),L._debugParams.showElevationIdDebug&&Qr.push("DEBUG_ELEVATION_ID"),ms&&(L.emissiveMode!=="dual-source-blending"||de?L.emissiveMode==="mrt-fallback"&&Qr.push("USE_MRT1"):Qr.push("DUAL_SOURCE_BLENDING"));const Nr={},cr=[],Fr=(Ta,ci,uo,ao,Io,qc)=>{for(const Tc of Ta){const Wo=N.getTile(Tc);if(an&&!Wo.patternsLoaded())continue;const Va=Wo.getBucket(E);if(!Va||Va.elevationType!=="none"&&!Io||Va.elevationType==="none"&&Io)continue;L.prepareDrawTile();const Vc=[...ci],Ju=Va.elevationType==="road",du=L.shadowRenderer,bl=Ju&&!!du&&du.enabled;let uu=[0,0,0];if(bl){const _l=L.style.directionalLight,of=L.style.ambientLight;_l&&of&&(uu=o.aF(L.style,_l,of)),Vc.push("RENDER_SHADOWS","NORMAL_OFFSET")}const dd=Va.programConfigurations.get(E.id);let gl=!1;if(Sn&&Wo.imageAtlas){const _l=o.aG.from(Sn),of=_l.getPrimary().scaleSelf(Gs).toString(),Bf=Wo.imageAtlas.patternPositions.get(of),Bb=_l.getSecondary(),$b=Bb?Wo.imageAtlas.patternPositions.get(Bb.scaleSelf(Gs).toString()):null;gl=!!Bf&&!!$b,Bf&&dd.setConstantPatternPositions(Bf,$b)}bn>0&&(gl||dd.getPatternTransitionVertexBuffer("line-pattern"))&&Vc.push("LINE_PATTERN_TRANSITION"),Va.elevationGroundScaleVertexBuffer&&Vc.push("ELEVATION_GROUND_SCALE");const Hc=L.isTileAffectedByFog(Tc),Fu=L.getOrCreateProgram(oa,{config:dd,defines:Vc,overrideFog:Hc});if(!an&&Ks&&_n&&Wo.lineAtlas){const _l=Wo.lineAtlas.getDash(Ks,_n);_l&&dd.setConstantPatternPositions(_l)}bl&&du.setupShadows(Wo.tileID.toUnwrapped(),Fu,"vector-tile");let[Yl,zl]=E.paint.get("line-trim-offset");(_n==="round"||_n==="square")&&Yl!==zl&&(Yl===0&&(Yl-=1),zl===1&&(zl+=1));const Ud=ms?Tc.projMatrix:null,af=Ke?1/Va.tileToMeter/o.c5(Wo,1,L.transform.zoom):1,Pv=Ke?1/Va.tileToMeter/o.c5(Wo,1,Math.floor(L.transform.zoom)):1,ty=Js?E.paint._values["line-floorwidth"]:null;let ew;const Ad=Wo.dashIdealZ;if(ty&&ty.value.kind==="constant"&&Ad!==Wo.tileID.overscaledZ){const _l=Va.zoom;_l in Nr||(Nr[_l]=Math.max(.01,E.widthExpression().evaluate({zoom:_l}))),ew=ty.value.value,ty.value.value=Nr[_l]*Math.pow(2,Ad-_l)}const jc=an?o.e5(L,Wo,E,Ud,Gs,af,Pv,[Yl,zl],uu,bn):o.e6(L,Wo,E,Ud,Va.lineClipsArray.length,Gs,af,Pv,[Yl,zl],uu),Zl=(_l,of,Bf,Bb,$b,Ej)=>{let F1=_l.texture;if(of!==_l.version){let Kk=256;if(Bf){const tw=N.getSource().maxzoom,lc=Tc.canonical.z===tw?Math.ceil(1<{of&&of.get().length!==0&&(Lr!=null&&(Lr.value=lr*Ce),Bf!==void 0&&(jc.u_opacity_multiplier=Bf),Fu.draw(L,bt.TRIANGLES,uo,_l,as,o.$.disabled,jc,E.id,Va.layoutVertexBuffer,Va.indexBuffer,of,E.paint,L.transform.zoom,dd,[Va.layoutVertexBuffer2,Va.patternVertexBuffer,Va.zOffsetVertexBuffer,Va.elevationIdColVertexBuffer,Va.elevationGroundScaleVertexBuffer]),Bf!==void 0&&(jc.u_opacity_multiplier=1),Lr!=null&&(Lr.value=lr))},qd=_l=>{zu&&zu.active&&wi.drawLineFrcRenderLine?wi.drawLineFrcRenderLine(Va,zu,_l,bp):bp(_l,Va.segments)};if(Mn&&!Io){const _l=L.stencilModeForClipping(Tc).ref;_l===0&&ms&&vt.clear({stencil:0});const of={func:bt.EQUAL,mask:255};jc.u_alpha_discard_threshold=.8,qd(new o._(of,_l,255,bt.KEEP,bt.KEEP,bt.INVERT)),jc.u_alpha_discard_threshold=0,qd(new o._(of,_l,255,bt.KEEP,bt.KEEP,bt.KEEP))}else jc.u_alpha_discard_threshold=Mn&&Io&&qc?.8:0,qd(Io?ao:L.stencilModeForClipping(Tc));zu&&wi.drawLineFrcFadePass&&wi.drawLineFrcFadePass(L,Va,Tc,zu,Io,ao,bp),ew!==void 0&&(ty.value.value=ew)}};let Fa=L.depthModeForSublayer(0,o.Z.ReadOnly);const ta=new o.Z(L.depthOcclusion?bt.GREATER:bt.LEQUAL,o.Z.ReadOnly,L.depthRangeFor3D);if(E.hasNonElevatedBuckets){const Ta=!ms&&L.terrain;Ce!==0&&Ta?o.w(`Occlusion opacity for layer ${E.id} is supported on terrain only if the layer has line-z-offset enabled.`):Ta?o.w(`Cannot render non-elevated lines in immediate mode when terrain is enabled. Layer: ${E.id}.`):Fr(z,Qr,Fa,o._.disabled,!1,!0)}if(E.hasElevatedBuckets){Pe==="hd-road-markup"?mt||(Fa=ta,Qr.push("ELEVATED_ROADS")):(Qr.push("ELEVATED"),Fa=ta,Pt&&Qr.push(Gt?"CROSS_SLOPE_HORIZONTAL":"CROSS_SLOPE_VERTICAL"),Ze&&Qr.push("ELEVATION_REFERENCE_SEA"));const Ta=Mn?L.stencilModeFor3D():o._.disabled;Pe!=="hd-road-markup"&&(L.forceTerrainMode=!0),Fr(z,Qr,Fa,Ta,!0,!0),Mn&&Fr(z,Qr,Fa,Ta,!0,!1),Pe!=="hd-road-markup"&&(L.forceTerrainMode=!1)}wi.drawLineFrcCoverageSecondPass&&wi.drawLineFrcCoverageSecondPass(L,E,cr),Mn&&(L.resetStencilClippingMasks(),ms&&vt.clear({stencil:0})),Ce===0||L.depthOcclusion||ms||L.layersWithOcclusionOpacity.push(L.currentLayer)}class Y_{destroy(){this.fbo&&(this.fbo.destroy(),this.fbo=null),this.drapeFbo&&(this.drapeFbo.destroy(),this.drapeFbo=null)}}class C6{constructor(N){this.pbo=N.createBuffer(),this.sync=null,this.fboA=null,this.fboB=null,this.maxDensity=0}destroy(N){this.sync&&(N.deleteSync(this.sync),this.sync=null),N.deleteBuffer(this.pbo),this.fboA&&(this.fboA.destroy(),this.fboA=null),this.fboB&&(this.fboB.destroy(),this.fboB=null)}}const Ou={additive:{clearColor:new o.C(0,0,0,0),colorMode:o.a1.additiveAlphaWeighted,compositeUniformValue:1},multiply:{clearColor:new o.C(1,1,1,1),colorMode:o.a1.multiply,compositeUniformValue:0}};function _4(L){return!(!L.extRenderToTextureHalfFloat&&!L.extColorBufferFloat)}function w4(L,N){return L==="additive"&&_4(N)?o.a1.additiveAlphaWeightedUnboundedAlpha:Ou[L].colorMode}function A6(L,N,E){const z=L.context,W=z.gl;let Z=E.width,ne=E.height,de=E.colorAttachment0.get();N.lineBlendDensityReadback||(N.lineBlendDensityReadback=new C6(W));const ye=N.lineBlendDensityReadback;let Ce=0,Pe=!0;for(;Z>1||ne>1;){const mt=Math.max(1,Math.floor(Z/2)),vt=Math.max(1,Math.floor(ne/2)),bt=Ce===0?"fboA":"fboB";ye[bt]=yp.createWithTexture(z,ye[bt],mt,vt,!1);const St=ye[bt];z.bindFramebuffer.set(St.framebuffer),z.viewport.set([0,0,mt,vt]),z.activeTexture.set(W.TEXTURE0),W.bindTexture(W.TEXTURE_2D,de),L.getOrCreateProgram("lineBlendReduce").draw(L,W.TRIANGLES,o.Z.disabled,o._.disabled,o.a1.unblended,o.$.disabled,gp(0,[1/Z,1/ne],Pe),N.id,L.viewportBuffer,L.quadTriangleIndexBuffer,L.viewportSegments,N.paint,L.transform.zoom),Z=mt,ne=vt,de=St.colorAttachment0.get(),Ce=1-Ce,Pe=!1}const Ke=_4(z),Ze=Ke?16:4;ye.sync&&(W.deleteSync(ye.sync),ye.sync=null),W.bindBuffer(W.PIXEL_PACK_BUFFER,ye.pbo),W.bufferData(W.PIXEL_PACK_BUFFER,Ze,W.STREAM_READ),W.readPixels(0,0,1,1,W.RGBA,Ke?W.FLOAT:W.UNSIGNED_BYTE,0),W.bindBuffer(W.PIXEL_PACK_BUFFER,null),ye.sync=W.fenceSync(W.SYNC_GPU_COMMANDS_COMPLETE,0),z.viewport.set([0,0,L.width,L.height])}function j4(L,N,E){if(!_4(L.context))return;const z=N.lineBlendDensityReadback;z&&z.sync?(function(W,Z,ne){if(W.sync&&Z.getSyncParameter(W.sync,Z.SYNC_STATUS)===Z.SIGNALED){if(Z.deleteSync(W.sync),W.sync=null,Z.bindBuffer(Z.PIXEL_PACK_BUFFER,W.pbo),_4(ne)){const de=new Float32Array(4);Z.getBufferSubData(Z.PIXEL_PACK_BUFFER,0,de);const ye=de[1];W.maxDensity=Math.max(2*(ye>0?de[0]/ye:0),1)}else W.maxDensity=1;Z.bindBuffer(Z.PIXEL_PACK_BUFFER,null)}}(z,L.context.gl,L.context),z.sync||(A6(L,N,E),L.style.map.triggerRepaint())):(A6(L,N,E),L.style.map.triggerRepaint())}function N4(L,N,E,z,W,Z){const ne=L.context,de=ne.gl,ye=E==="additive"?1:N.paint.get("line-opacity").constantOr(1),Ce=E==="additive"?function(Ke,Ze){const mt=Ze.paint.get("line-blend-additive-clamp");if(mt>0)return mt;const vt=Ze.lineBlendDensityReadback;return vt&&vt.maxDensity!==0?vt.maxDensity:null}(0,N):1;if(Ce===null)return;ne.bindFramebuffer.set(W),Z&&ne.viewport.set([0,0,Z[0],Z[1]]),ne.activeTexture.set(de.TEXTURE0),de.bindTexture(de.TEXTURE_2D,z.colorAttachment0.get());const Pe=w4(E,L.context);L.getOrCreateProgram("lineBlendComposite").draw(L,de.TRIANGLES,o.Z.disabled,o._.disabled,Pe,o.$.disabled,((Ke,Ze,mt,vt)=>({u_image:0,u_opacity:Ze,u_blend_mode:mt,u_max_density:vt}))(0,ye,Ou[E].compositeUniformValue,Ce),N.id,L.viewportBuffer,L.quadTriangleIndexBuffer,L.viewportSegments,N.paint,L.transform.zoom)}function sN(L,N,E,z){const{painter:W,sourceCache:Z,layer:ne,coords:de,colorMode:ye,elevationType:Ce,terrainEnabled:Pe,pass:Ke}=L,Ze=W.context.gl,mt=ne.paint.get("fill-pattern"),vt=ne.paint.get("fill-pattern-cross-fade"),bt=mt.constantOr(null);let St=Ce;Ce!=="road"||N&&!Pe||(St="none");const Pt=St==="road",Gt=L.painter.shadowRenderer,as=Pt&&!!Gt&&Gt.enabled,ms=new o.Z(W.context.gl.LEQUAL,o.Z.ReadOnly,W.depthRangeFor3D);let Gs=[0,0,0];if(as){const Ks=W.style.directionalLight,_n=W.style.ambientLight;Ks&&_n&&(Gs=o.aF(W.style,Ks,_n))}const Ms=mt&&mt.constantOr(1),Js=W.terrain&&W.terrain.renderingToTexture,Os=(Ks,_n)=>{let ln,an,bn,Sn,lr;_n?(ln=Ms&&!ne.getPaintProperty("fill-outline-color")?"fillOutlinePattern":"fillOutline",bn=Ze.LINES):(ln=Ms?"fillPattern":"fill",bn=Ze.TRIANGLES);const Mn=[];for(const Hn of de){const Tr=Z.getTile(Hn);if(Ms&&!Tr.patternsLoaded())continue;const oa=Tr.getBucket(ne);if(!oa)continue;const Qr=N?oa.hdExt&&oa.hdExt.elevationBufferData:oa.bufferData;if(!Qr||Qr.isEmpty())continue;W.prepareDrawTile();const Lr=Qr.programConfigurations.get(ne.id),qa=W.isTileAffectedByFog(Hn),Nr=[],cr=[];Pt&&(Nr.push("ELEVATED_ROADS"),cr.push(Qr.elevatedLayoutVertexBuffer)),as&&Nr.push("RENDER_SHADOWS","NORMAL_OFFSET"),Js&&E&&Nr.push("USE_MRT1"),Ms&&(W.context.activeTexture.set(Ze.TEXTURE0),Tr.imageAtlasTexture&&Tr.imageAtlasTexture.bind(Ze.LINEAR,Ze.CLAMP_TO_EDGE),Lr.updatePaintBuffers());let Fr=!1;if(bt&&Tr.imageAtlas){const Io=Tr.imageAtlas,qc=o.aG.from(bt),Tc=qc.getPrimary().scaleSelf(o.e.devicePixelRatio).toString(),Wo=qc.getSecondary(),Va=Io.patternPositions.get(Tc),Vc=Wo?Io.patternPositions.get(Wo.scaleSelf(o.e.devicePixelRatio).toString()):null;Fr=!!Va&&!!Vc,Va&&Lr.setConstantPatternPositions(Va,Vc)}vt>0&&(Fr||Lr.getPatternTransitionVertexBuffer("fill-pattern"))&&Nr.push("FILL_PATTERN_TRANSITION");const Fa=W.getOrCreateProgram(ln,{config:Lr,overrideFog:qa,defines:Nr}),ta=W.translatePosMatrix(Hn.projMatrix,Tr,ne.paint.get("fill-translate"),ne.paint.get("fill-translate-anchor"));as&&Gt.setupShadows(Tr.tileID.toUnwrapped(),Fa,"vector-tile");const Ta=ne.paint.get("fill-emissive-strength");if(_n){Sn=Qr.lineIndexBuffer,lr=Qr.lineSegments;const Io=W.terrain&&W.terrain.renderingToTexture?W.terrain.drapeBufferSize:[Ze.drawingBufferWidth,Ze.drawingBufferHeight];an=ln==="fillOutlinePattern"&&Ms?Zx(ta,Ta,W,Tr,Io,Gs,vt):Fb(ta,Ta,Io,Gs)}else Sn=Qr.indexBuffer,lr=Qr.triangleSegments,an=Ms?Cj(ta,Ta,W,Tr,Gs,vt):Ev(ta,Ta,Gs);W.uploadCommonUniforms(W.context,Fa,Hn.toUnwrapped());let ci=Ks;if((Ce==="road"&&!Pe||Ce==="offset")&&(ci=ms),!lr||lr.get&&lr.get().length===0)continue;const uo=z||W.stencilModeForClipping(Hn);let ao="fallthrough";!_n&&wi.drawFillFrcCoverageFirstPass&&(ao=wi.drawFillFrcCoverageFirstPass({painter:W,layer:ne,bucket:oa,coord:Hn,elevatedGeometry:N,program:Fa,programConfiguration:Lr,uniformValues:an,drawMode:bn,depthMode:ci,stencilMode:uo,colorMode:ye,bufferData:Qr,indexBuffer:Sn,segments:lr,dynamicBuffers:cr,polygonCoverageTiles:Mn})),ao==="fallthrough"&&Fa.draw(W,bn,ci,uo,ye,o.$.disabled,an,ne.id,Qr.layoutVertexBuffer,Sn,lr,ne.paint,W.transform.zoom,Lr,cr)}!_n&&wi.drawFillFrcCoverageSecondPass&&wi.drawFillFrcCoverageSecondPass(W,ne,Mn,bn,ye)};W.renderPass===Ke&&Os(W.depthModeForSublayer(1,W.renderPass==="opaque"?o.Z.ReadWrite:o.Z.ReadOnly),!1),St==="none"&&W.renderPass==="translucent"&&ne.paint.get("fill-antialias")&&Os(W.depthModeForSublayer(ne.getPaintProperty("fill-outline-color")?2:0,o.Z.ReadOnly),!0)}function E6(L){return[L[0]*o.ea,L[1]*o.ea,L[2]*o.ea,0]}function ey(L,N,E,z,W,Z,ne,de,ye,Ce){const Pe=W.getSource(),Ke=z.globeSharedBuffers;if(!Ke)return;let Ze,mt,vt;if(E&&(Ze=W.getTile(E)),Pe instanceof fx?(mt=Pe.texture,vt=o.du(0,0,z.transform)):Ze&&E&&(mt=Ze.texture,vt=o.du(E.canonical.z,E.canonical.x,z.transform)),!mt||!vt)return;N||(vt=o.aN(o.Y(),vt,[1,-1,1]));const bt=z.context,St=bt.gl,Pt=Z.paint.get("raster-resampling")==="nearest"?St.NEAREST:St.LINEAR,Gt=z.colorModeForDrapableLayerRenderPass(ne),as=de.defines;as.push("GLOBE_POLES");const ms=new o.Z(St.LEQUAL,o.Z.ReadWrite,z.depthRangeFor3D),Gs=z.transform.expandedFarZProjMatrix,Ms=Float32Array.from(o.b4(o.b5(new o.bX(0,0,0))));z.terrain&&z.terrain.prepareDrawTile(),bt.activeTexture.set(St.TEXTURE0),mt.bind(Pt,St.CLAMP_TO_EDGE),bt.activeTexture.set(St.TEXTURE1),mt.bind(Pt,St.CLAMP_TO_EDGE),"useMipmap"in mt&&bt.extTextureFilterAnisotropic&&z.transform.pitch>20&&St.texParameterf(St.TEXTURE_2D,bt.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,bt.extTextureFilterAnisotropicMax);const[Js,Os,Ks,_n]=E?Ke.getPoleBuffers(E.canonical.z,!1):Ke.getPoleBuffers(0,!0),ln=L;let an;N?(an=Js,z.renderDefaultNorthPole=ln!==0):(an=Os,z.renderDefaultSouthPole=ln!==0);const bn=E6(de.mix),Sn=((Mn,Hn,Tr,oa,Qr,Lr,qa,Nr,cr,Fr,Fa,ta,Ta,ci)=>zb(Mn,Hn,Tr,oa,new Float32Array(16),new Float32Array(9),[0,0],Qr,[0,0],[0,0,0,0],1,{opacity:1,mix:0},qa,[0,0],cr,2,Fa,ta,Ta,1,0,ci))(z,Gs,Ms,vt,o.S(z.transform.zoom),0,Z,0,ln,0,bn,de.offset,de.range,ne),lr=z.getOrCreateProgram("raster",{defines:as});z.uploadCommonUniforms(bt,lr,null),lr.draw(z,St.TRIANGLES,ms,Ce,Gt,ye,Sn,Z.id,an,Ks,_n)}function pA(L){if(L.isOrthographic)return[0,0,0,0];const N=L._nearZ,E=L.projection.farthestPixelDistance(L),z=E-N,W=.2*L.height,Z=N+W;return[N,E,(Z-W-N)/z,(Z-N)/z]}function e7(L,N,E,z){if(L)return N.type==="raster-array"?N.getTextureDescriptor(L,E,!0):{texture:L.texture,mix:E6(z.mix),offset:z.offset,buffer:0,tileSize:1}}const Z_=o.d0(new Float32Array(16)),k4=o.a_([{name:"a_pos_3f",components:3,type:"Float32"}]),{members:X_}=k4;function D0(L,N,E,z){L.emplaceBack(N,E,z)}class S4{constructor(N){this.vertexArray=new o.eb,this.indices=new o.ad,D0(this.vertexArray,-1,-1,1),D0(this.vertexArray,1,-1,1),D0(this.vertexArray,-1,1,1),D0(this.vertexArray,1,1,1),D0(this.vertexArray,-1,-1,-1),D0(this.vertexArray,1,-1,-1),D0(this.vertexArray,-1,1,-1),D0(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=N.createVertexBuffer(this.vertexArray,X_),this.indexBuffer=N.createIndexBuffer(this.indices),this.segment=o.ac.simpleSegment(0,0,36,12)}}function Q_(L,N,E,z,W,Z){const ne=L.context.gl,de=N.paint.get("sky-atmosphere-color"),ye=N.paint.get("sky-atmosphere-halo-color"),Ce=N.paint.get("sky-atmosphere-sun-intensity"),Pe=((Ke,Ze,mt,vt,bt)=>({u_matrix_3f:Ke,u_sun_direction:Ze,u_sun_intensity:mt,u_color_tint_r:[vt.r,vt.g,vt.b,vt.a],u_color_tint_m:[bt.r,bt.g,bt.b,bt.a],u_luminance:5e-5}))(o.ee(o.ef(),z),W,Ce,de.toPremultipliedRenderColor(null),ye.toPremultipliedRenderColor(null));ne.framebufferTexture2D(ne.FRAMEBUFFER,ne.COLOR_ATTACHMENT0,ne.TEXTURE_CUBE_MAP_POSITIVE_X+Z,N.skyboxTexture,0),E.draw(L,ne.TRIANGLES,o.Z.disabled,o._.disabled,o.a1.unblended,o.$.frontCW,Pe,"skyboxCapture",N.skyboxGeometry.vertexBuffer,N.skyboxGeometry.indexBuffer,N.skyboxGeometry.segment)}const t7=o.a_([{type:"Float32",name:"a_pos",components:3},{type:"Float32",name:"a_uv",components:2}]);class T6{constructor(N){const E=new o.eg;E.emplaceBack(-1,1,1,0,0),E.emplaceBack(1,1,1,1,0),E.emplaceBack(1,-1,1,1,1),E.emplaceBack(-1,-1,1,0,1);const z=new o.ad;z.emplaceBack(0,1,2),z.emplaceBack(2,3,0),this.vertexBuffer=N.createVertexBuffer(E,t7.members),this.indexBuffer=N.createIndexBuffer(z),this.segments=o.ac.simpleSegment(0,0,4,2)}destroy(){this.vertexBuffer.destroy(),this.indexBuffer.destroy(),this.segments.destroy()}}const gA=o.a_([{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 M6{constructor(){this.colorModeAlphaBlendedWriteRGB=new o.a1([o.eh,o.ei,o.eh,o.ei],o.C.transparent,[!0,!0,!0,!1]),this.colorModeWriteAlpha=new o.a1([o.eh,o.ej,o.eh,o.ej],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(N){this._painter=N;const E=N.context;if(!this.atmosphereBuffer||this.updateNeeded){this.updateNeeded=!1,this.atmosphereBuffer=new T6(E);let z=this.params;const W=z.sizeRange,Z=z.intensityRange,ne=function(Ke){const Ze=o.bi(30),mt=[];for(let vt=0;vt{const Os=Z.projection.name==="globe"?["PROJECTION_GLOBE_VIEW","FOG"]:["FOG"];Js&&Os.push("ALPHA_PASS");const Ks=N.getOrCreateProgram("globeAtmosphere",{defines:Os}),_n=((an,bn,Sn,lr,Mn,Hn,Tr,oa,Qr,Lr,qa,Nr)=>({u_frustum_tl:an,u_frustum_tr:bn,u_frustum_br:Sn,u_frustum_bl:lr,u_horizon:Mn,u_transition:Hn,u_fadeout_range:Tr,u_atmosphere_fog_color:oa.toArray01(),u_high_color:Qr.toArray01(),u_space_color:Lr.toArray01(),u_temporal_offset:qa,u_horizon_angle:Nr}))(Z.frustumCorners.TL,Z.frustumCorners.TR,Z.frustumCorners.BR,Z.frustumCorners.BL,Z.frustumCorners.horizon,de,St,Pe,Ze,vt,Gt,Gs);N.uploadCommonUniforms(z,Ks);const ln=this.atmosphereBuffer;ln&&Ks.draw(N,W.TRIANGLES,ne,o._.disabled,Js?this.colorModeWriteAlpha:this.colorModeAlphaBlendedWriteRGB,o.$.backCW,_n,Js?"atmosphere_glow_alpha":"atmosphere_glow",ln.vertexBuffer,ln.indexBuffer,ln.segments)};Ms(!1),Ms(!0)}drawStars(N,E){const z=o.b0(E.properties.get("star-intensity"),0,1);if(z===0)return;const W=N.context,Z=W.gl,ne=N.transform,de=N.getOrCreateProgram("stars"),ye=o.bd([]);o.be(ye,ye,-ne._pitch),o.bf(ye,ye,-ne.angle),o.be(ye,ye,o.au(ne._center.lat)),o.en(ye,ye,-o.au(ne._center.lng));const Ce=o.bg(new Float32Array(16),ye),Pe=o.X([],ne.starsProjMatrix,Ce),Ke=o.ee([],Ce),Ze=o.eo([],Ke);let mt=this.params.sizeMultiplier;const vt=[0,1,0];o.ct(vt,vt,Ze),o.dC(vt,vt,mt);const bt=[1,0,0];o.ct(bt,bt,Ze),o.dC(bt,bt,mt);const St=(Pt=vt,Gt=bt,as=z,{u_matrix:Float32Array.from(Pe),u_up:Pt,u_right:Gt,u_intensity_multiplier:as});var Pt,Gt,as;N.uploadCommonUniforms(W,de),this.starsVx&&this.starsIdx&&de.draw(N,Z.TRIANGLES,o.Z.disabled,o._.disabled,this.colorModeAlphaBlendedWriteRGB,o.$.disabled,St,"atmosphere_stars",this.starsVx,this.starsIdx,this.starsSegments)}}class xA{}class C4{constructor(){this._storage=new Map}getLinesFromTrianglesBuffer(N,E,z){{const Ke=this._storage.get(E.id);if(Ke)return Ke.lastUsedFrameIdx=N,Ke.buf}const W=z.gl,Z=W.getBufferParameter(W.ELEMENT_ARRAY_BUFFER,W.BUFFER_SIZE),ne=new ArrayBuffer(Z),de=new Int16Array(ne);W.getBufferSubData(W.ELEMENT_ARRAY_BUFFER,0,new Int16Array(ne));const ye=new o.ep;for(let Ke=0;Ke30&&(z.buf.destroy(),this._storage.delete(E))}destroy(){for(const[N,E]of this._storage)E.buf.destroy(),this._storage.delete(N)}}class P6{constructor(){this.occluderSize=30,this.depthOffset=-1e-4}}const nN={symbol:function(L,N,E,z,W){if(L.renderPass!=="translucent")return;const Z=o._.disabled,ne=L.colorModeForRenderPass(),de=E.layout.get("text-variable-anchor"),ye=E.layout.get("text-size-scale-range"),Ce=o.b0(L.scaleFactor,ye[0],ye[1]);de&&function(Ze,mt,vt,bt,St,Pt,Gt,as){const ms=mt.transform,Gs=St==="map",Ms=Pt==="map";for(const Js of Ze){const Os=bt.getTile(Js),Ks=Os.getBucket(vt);if(!Ks||!Ks.text||!Ks.text.segments.get().length)continue;const _n=o.cG(Ks.textSizeData,ms.zoom,as),ln=Gm(Js,Ks.getProjection(),ms),an=ms.calculatePixelsToTileUnitsMatrix(Os),bn=o.dY(ln,Os.tileID.canonical,Ms,Gs,ms,Ks.getProjection(),an),Sn=Ks.hasIconTextFit()&&Ks.hasIconData();_n&&b4(Ks,Gs,Ms,Gt,ms,bn,Js,Math.pow(2,ms.zoom-Os.tileID.overscaledZ),_n,Sn)}}(z,L,E,N,E.layout.get("text-rotation-alignment"),E.layout.get("text-pitch-alignment"),W,Ce);const Pe=E.paint.get("icon-opacity").constantOr(1)!==0,Ke=E.paint.get("text-opacity").constantOr(1)!==0;E.layout.get("symbol-sort-key").constantOr(1)!==void 0&&(Pe||Ke)?K_(L,N,E,z,Z,ne):(Pe&&K_(L,N,E,z,Z,ne,{onlyIcons:!0}),Ke&&K_(L,N,E,z,Z,ne,{onlyText:!0})),N.map.showCollisionBoxes&&Zd.drawCollisionDebug&&(Zd.drawCollisionDebug(L,N,E,z,E.paint.get("text-translate"),E.paint.get("text-translate-anchor"),!0),Zd.drawCollisionDebug(L,N,E,z,E.paint.get("icon-translate"),E.paint.get("icon-translate-anchor"),!1))},circle:function(L,N,E,z){if(L.renderPass!=="translucent")return;const W=E.paint.get("circle-opacity"),Z=E.paint.get("circle-stroke-width"),ne=E.paint.get("circle-stroke-opacity"),de=E.layout.get("circle-sort-key").constantOr(1)!==void 0,ye=E.paint.get("circle-emissive-strength");if(W.constantOr(1)===0&&(Z.constantOr(1)===0||ne.constantOr(1)===0))return;const Ce=L.context,Pe=Ce.gl,Ke=L.transform,Ze=!(!L.terrain||!L.terrain.enabled),mt=E.layout.get("circle-elevation-reference"),vt=L.depthModeForSublayer(0,o.Z.ReadOnly),bt=new o.Z(L.context.gl.LEQUAL,o.Z.ReadOnly,L.depthRangeFor3D),St=mt==="none"||Ze?vt:bt,Pt=o._.disabled,Gt=L.colorModeForDrapableLayerRenderPass(ye),as=Ke.projection.name==="globe",ms=[o.a7(Ke.center.lng),o.a8(Ke.center.lat)],Gs=[];for(let Js=0;JsJs.sortKey-Os.sortKey);const Ms={useDepthForOcclusion:Ke.depthOcclusionForSymbolsAndCircles};for(const Js of Gs){const{programConfiguration:Os,program:Ks,layoutVertexBuffer:_n,dynamicBuffers:ln,indexBuffer:an,uniformValues:bn,tile:Sn}=Js.state,lr=Js.segments;L.terrain&&L.terrain.setupElevationDraw(Sn,Ks,Ms),L.uploadCommonUniforms(Ce,Ks,Sn.tileID.toUnwrapped()),Ks.draw(L,Pe.TRIANGLES,St,Pt,Gt,o.$.disabled,bn,E.id,_n,an,lr,E.paint,Ke.zoom,Os,ln)}},heatmap:function(L,N,E,z){if(E.paint.get("heatmap-opacity")!==0)if(L.renderPass==="offscreen"){const W=L.context,Z=W.gl,ne=o._.disabled,de=new o.a1([Z.ONE,Z.ONE,Z.ONE,Z.ONE],o.C.transparent,[!0,!0,!0,!0]),ye=L.transform.projection.name==="globe"?.5:.25;E.heatmapFbo=yp.createWithTexture(W,E.heatmapFbo,L.width*ye,L.height*ye),W.clear({color:o.C.transparent});const Ce=L.transform,Pe=Ce.projection.name==="globe",Ke=Pe?["PROJECTION_GLOBE_VIEW"]:[],Ze=Pe?o.$.frontCCW:o.$.disabled,mt=[o.a7(Ce.center.lng),o.a8(Ce.center.lat)];for(let vt=0;vt({u_image:0,u_color_ramp:1,u_opacity:Ke.paint.get("heatmap-opacity")}))(0,Z),Z.id,W.viewportBuffer,W.quadTriangleIndexBuffer,W.viewportSegments,Z.paint,W.transform.zoom)}(L,E))},line:function(L,N,E,z){const W=E.paint.get("line-opacity"),Z=E.paint.get("line-width");if(W.constantOr(1)===0||Z.constantOr(1)===0)return;const ne=E.paint.get("line-blend-mode"),de=L.terrain&&L.terrain.renderingToTexture;if(ne==="default"||L.transform.projection.name==="globe")L.renderPass==="translucent"&&R0(L,N,E,z);else{if(de)return void function(ye,Ce,Pe,Ke,Ze){if(ye.renderPass!=="translucent")return;const mt=ye.context,vt=mt.gl,bt=ye.terrain;if(!bt)return;const St=mt.bindFramebuffer.current,Pt=ye.emissiveMode==="mrt-fallback",Gt=bt.drapeBufferSize[0],as=bt.drapeBufferSize[1];Pe.lineBlendFbos||(Pe.lineBlendFbos=new Y_),Pe.lineBlendFbos.drapeFbo=yp.createWithTexture(mt,Pe.lineBlendFbos.drapeFbo,Gt,as,!0),Pt&&vt.drawBuffers([vt.COLOR_ATTACHMENT0]),mt.clear({color:Ou[Ze].clearColor,depth:1,stencil:0});const ms=ye.currentStencilSource,Gs=ye._tileClippingMaskIDs,Ms=ye.nextStencilID;ye.currentStencilSource=void 0,ye._tileClippingMaskIDs={},ye.nextStencilID=1;const Js=ye._terrain;ye._terrain=null,ye._renderTileClippingMasks(Pe,Ce,Ke),R0(ye,Ce,Pe,Ke,w4(Ze,ye.context),!0),ye._terrain=Js,ye.currentStencilSource=ms,ye._tileClippingMaskIDs=Gs,ye.nextStencilID=Ms,Pt&&vt.drawBuffers([vt.COLOR_ATTACHMENT0,vt.COLOR_ATTACHMENT1]);const Os=bt.drapeBufferSize,Ks=Pe.lineBlendFbos&&Pe.lineBlendFbos.drapeFbo;Ks&&(Ze==="additive"&&j4(ye,Pe,Ks),N4(ye,Pe,Ze,Ks,St,Os))}(L,N,E,z,ne);if(L.renderPass==="offscreen")return void function(ye,Ce,Pe,Ke,Ze){const mt=ye.context,vt=Math.ceil(ye.width),bt=Math.ceil(ye.height);Pe.lineBlendFbos||(Pe.lineBlendFbos=new Y_),Pe.lineBlendFbos.fbo=yp.createWithTexture(mt,Pe.lineBlendFbos.fbo,vt,bt,!0),mt.clear({color:Ou[Ze].clearColor,depth:1,stencil:0});const St=ye.currentStencilSource,Pt=ye._tileClippingMaskIDs,Gt=ye.nextStencilID;ye.currentStencilSource=void 0,ye._tileClippingMaskIDs={},ye.nextStencilID=1,ye._renderTileClippingMasks(Pe,Ce,Ke);const as=ye.renderPass;ye.renderPass="translucent",R0(ye,Ce,Pe,Ke,w4(Ze,ye.context)),ye.renderPass=as,ye.currentStencilSource=St,ye._tileClippingMaskIDs=Pt,ye.nextStencilID=Gt,mt.viewport.set([0,0,ye.width,ye.height]),Ze==="additive"&&j4(ye,Pe,Pe.lineBlendFbos.fbo)}(L,N,E,z,ne);if(L.renderPass==="translucent"){const ye=E.lineBlendFbos&&E.lineBlendFbos.fbo;return void(ye&&N4(L,E,ne,ye,null))}}},fill:function(L,N,E,z){const W=E.paint.get("fill-color"),Z=E.paint.get("fill-opacity");if(Z.constantOr(1)===0)return;const ne=E.paint.get("fill-emissive-strength"),de=L.colorModeForDrapableLayerRenderPass(ne),ye=E.paint.get("fill-pattern"),Ce=L.opaquePassEnabledForLayer()&&!ye.constantOr(1)&&W.constantOr(o.C.transparent).a===1&&Z.constantOr(0)===1?"opaque":"translucent";let Pe="none";E.layout.get("fill-elevation-reference")!=="none"?Pe="road":E.paint.get("fill-z-offset").constantOr(1)!==0&&(Pe="offset");const Ke=!(!L.terrain||!L.terrain.enabled),Ze={painter:L,sourceCache:N,layer:E,coords:z,colorMode:de,elevationType:Pe,terrainEnabled:Ke,pass:Ce};if(L.renderPass==="shadow")return void(L.shadowRenderer&&Pe==="road"&&!Ke&&wi.drawElevatedFillShadows&&wi.drawElevatedFillShadows(Ze));const mt=L.emissiveMode==="mrt-fallback";if(Pe!=="offset"){if(sN(Ze,!1,mt),Pe==="road"){const vt=!Ke&&L.renderPass==="translucent";vt&&wi.drawDepthPrepass&&wi.drawDepthPrepass(L,N,E,z,"geometry"),sN(Ze,!0,mt,o._.disabled),vt&&wi.drawElevatedStructures&&wi.drawElevatedStructures(Ze)}}else sN(Ze,!1,mt,L.stencilModeFor3D())},"fill-extrusion":function(L,N,E,z){const W=E.paint.get("fill-extrusion-opacity"),Z=L.context,ne=Z.gl,de=L.terrain,ye=de&&de.renderingToTexture;if(W===0)return;const Ce=L.emissiveMode==="mrt-fallback",Pe=L.conflationActive&&L.style.isLayerClipped(E,N.getSource()),Ke=L.style.order.indexOf(E.fqid);if(Pe&&function(Ze,mt,vt,bt,St){for(const Pt of bt){const Gt=mt.getTile(Pt).getBucket(vt);Gt&&(Gt.updateReplacement(Pt,Ze.replacementSource,St),Gt.uploadCentroid(Ze.context))}}(L,N,E,z,Ke),de||Pe)for(const Ze of z){const mt=N.getTile(Ze).getBucket(E);mt&&gr(L.context,N,Ze,mt,E,de,Pe)}if(L.renderPass==="shadow"&&L.shadowRenderer){if(de&&W<.65&&E._transitionablePaint._values["fill-extrusion-opacity"].value.expression instanceof o.aj)return;const Ze=L.shadowRenderer.getShadowPassDepthMode();As(L,N,E,z,Ze,o._.disabled,o.a1.disabled,Pe)}else if(L.renderPass==="translucent"){const Ze=!E.paint.get("fill-extrusion-pattern").constantOr(1),mt=E.paint.get("fill-extrusion-color").constantOr(o.C.white);if(!ye&&mt.a!==0){const bt=new o.Z(L.context.gl.LEQUAL,o.Z.ReadWrite,L.depthRangeFor3D);W===1&&Ze?As(L,N,E,z,bt,o._.disabled,o.a1.unblended,Pe):(As(L,N,E,z,bt,o._.disabled,o.a1.disabled,Pe),As(L,N,E,z,bt,L.stencilModeFor3D(),L.colorModeForRenderPass(),Pe),L.resetStencilClippingMasks())}const vt=L.style.enable3dLights()&&Ze&&(!de&&L.transform.projection.name!=="globe"||ye);if(vt&&!Xe.drawGroundEffect&&Bt(),vt&&Xe.drawGroundEffect){const bt=E.paint.get("fill-extrusion-opacity"),St=E.paint.get("fill-extrusion-ambient-occlusion-intensity"),Pt=E.paint.get("fill-extrusion-ambient-occlusion-ground-radius"),Gt=E.paint.get("fill-extrusion-flood-light-intensity"),as=E.paint.get("fill-extrusion-flood-light-color-use-theme").constantOr("default")==="none",ms=E.paint.get("fill-extrusion-flood-light-color").toNonPremultipliedRenderColor(as?null:E.lut).toArray01().slice(0,3),Gs=St>0&&Pt>0,Ms=Gt>0,Js=new Hs;Js.translate=E.paint.get("fill-extrusion-translate"),Js.translateAnchor=E.paint.get("fill-extrusion-translate-anchor"),Js.edgeRadius=E.layout.get("fill-extrusion-edge-radius"),Js.cutoffFadeRange=E.paint.get("fill-extrusion-cutoff-fade-range");const Os=Ks=>{const _n=L.depthModeForSublayer(1,o.Z.ReadOnly,ne.LEQUAL,!0),ln=E.paint.get(Ks?"fill-extrusion-ambient-occlusion-ground-attenuation":"fill-extrusion-flood-light-ground-attenuation"),an=o.al(.1,3,ln),bn=L._showOverdrawInspector;if(!bn){const Sn=new o._({func:ne.ALWAYS,mask:255},255,255,ne.KEEP,ne.KEEP,ne.REPLACE),lr=new o.a1([ne.ONE,ne.ONE,ne.ONE,ne.ONE],o.C.transparent,[!1,!1,!1,!0],ne.MIN);Xe.drawGroundEffect(Js,L,N,E,z,_n,Sn,lr,o.$.disabled,Ks,"sdf",bt,St,Pt,Gt,ms,an,Pe,!1)}{const Sn=bn?o._.disabled:new o._({func:ne.EQUAL,mask:255},255,255,ne.KEEP,ne.DECR,ne.DECR),lr=bn?L.colorModeForRenderPass():new o.a1([ne.ONE_MINUS_DST_ALPHA,ne.DST_ALPHA,ne.ONE,ne.ONE],o.C.transparent,[!0,!0,!0,!0]);Xe.drawGroundEffect(Js,L,N,E,z,_n,Sn,lr,o.$.disabled,Ks,"color",bt,St,Pt,Gt,ms,an,Pe,!1)}};if(ye){const Ks=()=>{const ln=de.drapeBufferSize[0],an=de.drapeBufferSize[1];let bn=de.framebufferCopyTexture;return bn&&(!bn||bn.size[0]===ln&&bn.size[1]===an)||(bn&&bn.destroy(),bn=de.framebufferCopyTexture=new o.T(Z,new o.b({width:ln,height:an}),ne.RGBA8)),bn.bind(ne.LINEAR,ne.CLAMP_TO_EDGE),ne.copyTexSubImage2D(ne.TEXTURE_2D,0,0,0,0,0,ln,an),bn},_n=(ln,an,bn)=>{const Sn=L.depthModeForSublayer(1,o.Z.ReadOnly,ne.LEQUAL,!1),lr=E.paint.get(ln?"fill-extrusion-ambient-occlusion-ground-attenuation":"fill-extrusion-flood-light-ground-attenuation"),Mn=o.al(.1,3,lr);{const Hn=new o.a1([ne.ONE,ne.ONE,ne.ONE,ne.ONE],o.C.transparent,[!1,!1,!1,!0]);Xe.drawGroundEffect(Js,L,N,E,z,Sn,o._.disabled,Hn,o.$.disabled,ln,"clear",bt,St,Pt,Gt,ms,Mn,Pe,an)}{const Hn=new o._({func:ne.ALWAYS,mask:255},255,255,ne.KEEP,ne.KEEP,ne.REPLACE),Tr=new o.a1([ne.ONE,ne.ONE,ne.ONE,ne.ONE],o.C.transparent,[!1,!1,!1,!0],ne.MIN);Xe.drawGroundEffect(Js,L,N,E,z,Sn,Hn,Tr,o.$.disabled,ln,"sdf",bt,St,Pt,Gt,ms,Mn,Pe,an)}Ce&&!ln&&(bn=Ks());{const Hn=ln?ne.ZERO:ne.ONE_MINUS_DST_ALPHA,Tr=new o._({func:ne.EQUAL,mask:255},255,255,ne.KEEP,ne.DECR,ne.DECR),oa=new o.a1([Hn,ne.DST_ALPHA,ne.ONE_MINUS_DST_ALPHA,ne.ZERO],o.C.transparent,[!0,!0,!0,!0]);Xe.drawGroundEffect(Js,L,N,E,z,Sn,Tr,oa,o.$.disabled,ln,"color",bt,St,Pt,Gt,ms,Mn,Pe,an)}if(!Ce||ln){const Hn=new o.a1([ne.ONE,ne.ONE,ne.ONE,ln?ne.ZERO:ne.ONE],o.C.transparent,[!1,!1,!1,!0],ln?ne.FUNC_ADD:ne.MAX);Xe.drawGroundEffect(Js,L,N,E,z,Sn,o._.disabled,Hn,o.$.disabled,ln,"clear",bt,St,Pt,Gt,ms,Mn,Pe,an,bn)}else{ne.drawBuffers([ne.NONE,ne.COLOR_ATTACHMENT1]);const Hn=new o._({func:ne.EQUAL,mask:255},254,255,ne.KEEP,ne.DECR,ne.DECR),Tr=new o.a1([ne.ONE,ne.ONE,ne.ONE,ne.ONE],o.C.transparent,[!0,!1,!1,!1],ne.MAX);Xe.drawGroundEffect(Js,L,N,E,z,Sn,Hn,Tr,o.$.disabled,ln,"emissive",bt,St,Pt,Gt,ms,Mn,Pe,an,bn),ne.drawBuffers([ne.COLOR_ATTACHMENT0])}};if(Gs||Ms){let ln;L.prepareDrawTile(),Ce&&!Gs||(ln=Ks()),Gs&&_n(!0,!1,ln),Ms&&_n(!1,!0,ln)}}else Gs&&Os(!0),Ms&&Os(!1),(Gs||Ms)&&L.resetStencilClippingMasks()}}},hillshade:function(L,N,E,z){if(L.renderPass!=="offscreen"&&L.renderPass!=="translucent"||L.style.disableElevatedTerrain)return;const W=L.context,Z=L.terrain&&L.terrain.renderingToTexture,[ne,de]=L.renderPass!=="translucent"||Z?[{},z]:L.stencilConfigForOverlap(z);for(const ye of de){const Ce=N.getTile(ye);if(Ce.needsHillshadePrepare&&L.renderPass==="offscreen")li(L,Ce,E);else if(L.renderPass==="translucent"){const Pe=L.depthModeForSublayer(0,o.Z.ReadOnly),Ke=E.paint.get("hillshade-emissive-strength"),Ze=L.colorModeForDrapableLayerRenderPass(Ke),mt=Z&&L.terrain?L.terrain.stencilModeForRTTOverlap(ye):ne[ye.overscaledZ];Cl(L,ye,Ce,E,Pe,mt,Ze)}}W.viewport.set([0,0,L.width,L.height]),L.resetStencilClippingMasks()},raster:function(L,N,E,z,W,Z){if(L.renderPass!=="translucent")return;const ne=E.paint.get("raster-opacity");if(ne===0)return;const de=E.paint.get("raster-allow-draping"),ye=L.transform.projection.name==="globe";let Ce=E.paint.get("raster-elevation"),Pe=E.paint.get("raster-elevation-reference")==="ground";de||Ce!==0||(Ce=.001,Pe=!0);const Ke=Ce>0,Ze=L.terrain&&L.terrain.exaggeration()>0&&Ke&&Pe,mt=Ke&&ye,vt=!ye&&Ze;if(L.renderElevatedRasterBackface&&!mt)return;const bt=L.context,St=bt.gl,Pt=N.getSource(),Gt=function(an,bn,Sn,lr,Mn){const Hn=bn.paint.get("raster-color"),Tr=an.type==="raster-array",oa=[],Qr=bn.paint.get("raster-resampling"),Lr=bn.paint.get("raster-color-mix");let qa=bn.paint.get("raster-color-range");const Nr=[Lr[0],Lr[1],Lr[2],0],cr=Lr[3];let Fr=Qr==="nearest"?lr.NEAREST:lr.LINEAR;if(Tr&&(oa.push("RASTER_ARRAY"),Hn||oa.push("RASTER_COLOR"),Qr==="linear"&&oa.push("RASTER_ARRAY_LINEAR"),Fr=lr.NEAREST,Hn&&bn.paint.get("raster-color-scale")==="log"&&oa.push("RASTER_COLOR_SCALE_LOG"),!qa&&an.rasterLayers)){const Fa=an.rasterLayers.find(({id:ta})=>ta===bn.sourceLayer);Fa&&Fa.fields&&Fa.fields.range&&(qa=Fa.fields.range)}if(qa=qa||[0,1],Hn){oa.push("RASTER_COLOR"),Sn.activeTexture.set(lr.TEXTURE2),bn.updateColorRamp(qa);let Fa=bn.colorRampTexture;Fa||(Fa=bn.colorRampTexture=new o.T(Sn,bn.colorRamp,lr.RGBA8)),Fa.bind(Fr,lr.CLAMP_TO_EDGE)}return Mn&&oa.push("USE_MRT1"),{mix:Nr,range:qa,offset:cr,defines:oa,resampling:Fr}}(Pt,E,bt,St,L.terrain&&L.terrain.renderingToTexture&&L.emissiveMode==="mrt-fallback");if(Pt instanceof fx&&!z.length&&!ye)return;const as=E.paint.get("raster-emissive-strength"),ms=L.colorModeForDrapableLayerRenderPass(as),Gs=L.terrain&&L.terrain.renderingToTexture,Ms=!L.options.moving,Js=E.paint.get("raster-resampling")==="nearest"?St.NEAREST:St.LINEAR;if(Pt instanceof fx&&!z.length&&(Pt.onNorthPole||Pt.onSouthPole)){const an=Ke?L.stencilModeFor3D():o._.disabled;return void ey(Ce,!!Pt.onNorthPole,null,L,N,E,as,Gt,o.$.disabled,an)}if(!z.length)return;const[Os,Ks]=Pt instanceof fx||Gs?[{},z]:L.stencilConfigForOverlap(z),_n=Ks.at(-1).overscaledZ;mt&&Gt.defines.push("PROJECTION_GLOBE_VIEW"),Ke&&Gt.defines.push("RENDER_CUTOFF","ELEVATED"),Ze&&Gt.defines.push("ELEVATION_REFERENCE_GROUND");const ln=(an,bn,Sn)=>{for(const lr of an){const Mn=lr.toUnwrapped(),Hn=N.getTile(lr);if(Gs&&(!Hn||!Hn.hasData()))continue;bt.activeTexture.set(St.TEXTURE0);const Tr=e7(Hn,Pt,E,Gt);if(!Tr||!Tr.texture)continue;const{texture:oa,mix:Qr,offset:Lr,tileSize:qa,buffer:Nr}=Tr;let cr,Fr;Gs?(cr=o.Z.disabled,Fr=lr.projMatrix):Ke?(cr=new o.Z(St.LEQUAL,o.Z.ReadWrite,L.depthRangeFor3D),Fr=ye?L.transform.expandedFarZProjMatrix:L.transform.calculateProjMatrix(Mn,Ms)):(cr=L.depthModeForSublayer(lr.overscaledZ-_n,ne===1?o.Z.ReadWrite:o.Z.ReadOnly,St.LESS),Fr=L.transform.calculateProjMatrix(Mn,Ms));const Fa=L.terrain&&Gs?L.terrain.stencilModeForRTTOverlap(lr):Os[lr.overscaledZ],ta=Z?0:E.paint.get("raster-fade-duration");Hn.registerFadeDuration(ta);const Ta=N.findLoadedParent(lr,0),ci=ed(Hn,Ta,N,L.transform,ta);let uo,ao;!ci.isFading&&Hn.refreshedUponExpiration&&(Hn.refreshedUponExpiration=!1),L.terrain&&L.terrain.prepareDrawTile(),bt.activeTexture.set(St.TEXTURE0),oa.bind(Js,St.CLAMP_TO_EDGE),bt.activeTexture.set(St.TEXTURE1),Ta?(Ta.texture&&Ta.texture.bind(Js,St.CLAMP_TO_EDGE),uo=Math.pow(2,Ta.tileID.overscaledZ-Hn.tileID.overscaledZ),ao=[Hn.tileID.canonical.x*uo%1,Hn.tileID.canonical.y*uo%1]):oa.bind(Js,St.CLAMP_TO_EDGE),"useMipmap"in oa&&bt.extTextureFilterAnisotropic&&L.transform.pitch>20&&St.texParameterf(St.TEXTURE_2D,bt.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,bt.extTextureFilterAnisotropicMax);const Io=L.transform;let qc;const Tc=Ke?pA(Io):[0,0,0,0];let Wo,Va,Vc,Ju,du,bl=0;if(mt&&Pt instanceof fx&&Pt.coordinates.length>3)Wo=Float32Array.from(o.b4(o.b5(new o.bX(0,0,0)))),Va=Float32Array.from(Io.globeMatrix),Vc=Float32Array.from(o.b6(Io)),Ju=[o.a7(Io.center.lng),o.a8(Io.center.lat)],qc=Pt.elevatedGlobePerspectiveTransform,du=Pt.elevatedGlobeGridMatrix||new Float32Array(9);else if(mt){const Hc=o.b2(lr.canonical);bl=o.b3(Hc.getCenter().lat),Wo=Float32Array.from(o.b4(o.b5(lr.canonical))),Va=Float32Array.from(Io.globeMatrix),Vc=Float32Array.from(o.b6(Io)),Ju=[o.a7(Io.center.lng),o.a8(Io.center.lat)],qc=[0,0],du=Float32Array.from(o.b7(lr.canonical,Hc,bl,Io.worldSize/Io._pixelsPerMercatorPixel))}else qc=Pt instanceof fx?Pt.perspectiveTransform:[0,0],Wo=new Float32Array(16),Va=new Float32Array(9),Vc=new Float32Array(16),Ju=[0,0],du=new Float32Array(9);const uu=zb(L,Fr,Wo,Va,Vc,du,ao||[0,0],o.S(L.transform.zoom),Ju,Tc,uo||1,ci,E,qc,Ce,2,Qr,Lr,Gt.range,qa,Nr,as),dd=L.isTileAffectedByFog(lr),gl=L.getOrCreateProgram("raster",{defines:Gt.defines,overrideFog:dd});if(L.uploadCommonUniforms(bt,gl,Mn),Pt instanceof fx){const Hc=Pt.elevatedGlobeVertexBuffer,Fu=Pt.elevatedGlobeIndexBuffer;if(Gs||!ye)Pt.boundsBuffer&&Pt.boundsSegments&&gl.draw(L,St.TRIANGLES,cr,o._.disabled,ms,o.$.disabled,uu,E.id,Pt.boundsBuffer,L.quadTriangleIndexBuffer,Pt.boundsSegments);else if(Hc&&Fu){const Yl=Io.zoom<=o.e9?Pt.elevatedGlobeSegments:Pt.getSegmentsForLongitude(Io.center.lng);Yl&&gl.draw(L,St.TRIANGLES,cr,o._.disabled,ms,bn,uu,E.id,Hc,Fu,Yl)}}else if(mt){cr=new o.Z(St.LEQUAL,o.Z.ReadOnly,L.depthRangeFor3D);const Hc=L.globeSharedBuffers;if(Hc){Ze&&(L.terrain.setupElevationDraw(Hn,gl),L.uploadCommonUniforms(bt,gl,Hn.tileID.toUnwrapped()));const[Fu,Yl,zl]=Hc.getGridBuffers(bl,!1),Ud=gl.getAttributeLocation(St,"a_texture_pos");Ud!==-1&&St.vertexAttribI4ui(Ud,0,0,0,0),gl.draw(L,St.TRIANGLES,cr,Sn||Fa,L.colorModeForRenderPass(),bn,uu,E.id,Fu,Yl,zl)}}else if(vt)cr=new o.Z(St.LEQUAL,o.Z.ReadOnly,L.depthRangeFor3D),L.terrain.setupElevationDraw(Hn,gl),L.uploadCommonUniforms(bt,gl,Hn.tileID.toUnwrapped()),Io.pitch>20&&gl.draw(L,St.TRIANGLES,cr,o._.disabled,o.a1.disabled,o.$.frontCCW,uu,E.id,L.terrain.gridBuffer,L.terrain.gridIndexBuffer,L.terrain.gridSegments),gl.draw(L,St.TRIANGLES,cr,Fa,ms,o.$.backCCW,uu,E.id,L.terrain.gridBuffer,L.terrain.gridIndexBuffer,L.terrain.gridSegments);else{const{tileBoundsBuffer:Hc,tileBoundsIndexBuffer:Fu,tileBoundsSegments:Yl}=L.getTileBoundsBuffers(Hn);gl.draw(L,St.TRIANGLES,cr,Fa,ms,o.$.disabled,uu,E.id,Hc,Fu,Yl)}}if(!(Pt instanceof fx)&&mt)for(const lr of an){const Mn=lr.canonical.y===(1<Js.tileID)),mt&&(Ce.activeTexture.set(Pe.TEXTURE0),L.imageManager.bind(L.context,E.scope));const Ms=[];if(L.terrain&&L.terrain.renderingToTexture&&L.emissiveMode==="mrt-fallback"&&Ms.push("USE_MRT1"),ye){const Js=L.getOrCreateProgram(as,{overrideFog:!1,overrideRtt:!0,defines:Ms}),Os=Z_,Ks=new o.bP(0,0,0,0,0),_n=mt?R1(Os,de,ne,L,mt,E.scope,vt,ye,{tileID:Ks,tileSize:Ze}):Xx(Os,de,ne,W.toPremultipliedRenderColor(Z?null:E.lut));return void Js.draw(L,Pe.TRIANGLES,Pt,St,Gt,o.$.disabled,_n,E.id,L.viewportBuffer,L.quadTriangleIndexBuffer,L.viewportSegments)}for(const Js of Gs){const Os=L.isTileAffectedByFog(Js),Ks=L.getOrCreateProgram(as,{overrideFog:Os,defines:Ms}),_n=Js.toUnwrapped(),ln=z?Js.projMatrix:L.transform.calculateProjMatrix(_n);L.prepareDrawTile();const an=N?N.getTile(Js):ms?ms[Js.key]:new Ym(Js,Ze,Ke.zoom,L),bn=mt?R1(ln,de,ne,L,mt,E.scope,vt,ye,{tileID:Js,tileSize:Ze}):Xx(ln,de,ne,W.toPremultipliedRenderColor(Z?null:E.lut));L.uploadCommonUniforms(Ce,Ks,_n);const{tileBoundsBuffer:Sn,tileBoundsIndexBuffer:lr,tileBoundsSegments:Mn}=L.getTileBoundsBuffers(an);Ks.draw(L,Pe.TRIANGLES,Pt,St,Gt,o.$.disabled,bn,E.id,Sn,lr,Mn)}},sky:function(L,N,E){const z=L._atmosphere?o.S(L.transform.zoom):1,W=E.paint.get("sky-opacity")*z;if(W===0)return;const Z=L.context,ne=E.paint.get("sky-type"),de=new o.Z(Z.gl.LEQUAL,o.Z.ReadOnly,[0,1]),ye=L.frameCounter/1e3%1;ne==="atmosphere"?L.renderPass==="offscreen"?E.needsSkyboxCapture(L)&&(function(Ce,Pe){const Ke=Ce.context,Ze=Ke.gl;let mt=Pe.skyboxFbo;if(!mt){mt=Pe.skyboxFbo=Ke.createFramebuffer(32,32,1,null),Pe.skyboxGeometry=new S4(Ke),Pe.skyboxTexture=Ke.gl.createTexture(),Ze.bindTexture(Ze.TEXTURE_CUBE_MAP,Pe.skyboxTexture),Ze.texParameteri(Ze.TEXTURE_CUBE_MAP,Ze.TEXTURE_WRAP_S,Ze.CLAMP_TO_EDGE),Ze.texParameteri(Ze.TEXTURE_CUBE_MAP,Ze.TEXTURE_WRAP_T,Ze.CLAMP_TO_EDGE),Ze.texParameteri(Ze.TEXTURE_CUBE_MAP,Ze.TEXTURE_MIN_FILTER,Ze.LINEAR),Ze.texParameteri(Ze.TEXTURE_CUBE_MAP,Ze.TEXTURE_MAG_FILTER,Ze.LINEAR);for(let Pt=0;Pt<6;++Pt)Ze.texImage2D(Ze.TEXTURE_CUBE_MAP_POSITIVE_X+Pt,0,Ze.RGBA,32,32,0,Ze.RGBA,Ze.UNSIGNED_BYTE,null)}Ke.bindFramebuffer.set(mt.framebuffer),Ke.viewport.set([0,0,32,32]);const vt=Pe.getCenter(Ce,!0),bt=Ce.getOrCreateProgram("skyboxCapture"),St=new Float64Array(16);o.ec(St,.5*-Math.PI),Q_(Ce,Pe,bt,St,vt,0),o.ec(St,.5*Math.PI),Q_(Ce,Pe,bt,St,vt,1),o.ed(St,.5*-Math.PI),Q_(Ce,Pe,bt,St,vt,2),o.ed(St,.5*Math.PI),Q_(Ce,Pe,bt,St,vt,3),o.d0(St),Q_(Ce,Pe,bt,St,vt,4),o.ec(St,Math.PI),Q_(Ce,Pe,bt,St,vt,5),Ke.viewport.set([0,0,Ce.width,Ce.height])}(L,E),E.markSkyboxValid(L)):L.renderPass==="sky"&&function(Ce,Pe,Ke,Ze,mt){const vt=Ce.context,bt=vt.gl,St=Ce.transform,Pt=Ce.getOrCreateProgram("skybox");vt.activeTexture.set(bt.TEXTURE0),bt.bindTexture(bt.TEXTURE_CUBE_MAP,Pe.skyboxTexture);const Gt=((as,ms,Gs,Ms,Js)=>({u_matrix:as,u_sun_direction:ms,u_cubemap:0,u_opacity:Ms,u_temporal_offset:Js}))(St.skyboxMatrix,Pe.getCenter(Ce,!1),0,Ze,mt);Ce.uploadCommonUniforms(vt,Pt),Pt.draw(Ce,bt.TRIANGLES,Ke,o._.disabled,Ce.colorModeForRenderPass(),o.$.backCW,Gt,"skybox",Pe.skyboxGeometry.vertexBuffer,Pe.skyboxGeometry.indexBuffer,Pe.skyboxGeometry.segment)}(L,E,de,W,ye):ne==="gradient"&&L.renderPass==="sky"&&function(Ce,Pe,Ke,Ze,mt){const vt=Ce.context,bt=vt.gl,St=Ce.transform,Pt=Ce.getOrCreateProgram("skyboxGradient");Pe.skyboxGeometry||(Pe.skyboxGeometry=new S4(vt)),vt.activeTexture.set(bt.TEXTURE0);let Gt=Pe.colorRampTexture;Gt||(Gt=Pe.colorRampTexture=new o.T(vt,Pe.colorRamp,bt.RGBA8)),Gt.bind(bt.LINEAR,bt.CLAMP_TO_EDGE);const as=((ms,Gs,Ms,Js,Os)=>({u_matrix:ms,u_color_ramp:0,u_center_direction:Gs,u_radius:o.au(Ms),u_opacity:Js,u_temporal_offset:Os}))(St.skyboxMatrix,Pe.getCenter(Ce,!1),Pe.paint.get("sky-gradient-radius"),Ze,mt);Ce.uploadCommonUniforms(vt,Pt),Pt.draw(Ce,bt.TRIANGLES,Ke,o._.disabled,Ce.colorModeForRenderPass(),o.$.backCW,as,"skyboxGradient",Pe.skyboxGeometry.vertexBuffer,Pe.skyboxGeometry.indexBuffer,Pe.skyboxGeometry.segment)}(L,E,de,W,ye)},custom:function(L,N,E,z){const W=L.context,Z=E.implementation;if(!L.transform.projection.unsupportedLayers||!L.transform.projection.unsupportedLayers.includes("custom")||L.terrain&&(L.terrain.renderingToTexture||L.renderPass==="offscreen")&&E.isDraped(N)){if(L.renderPass==="offscreen"){const ne=Z.prerender;if(ne){if(L.setCustomLayerDefaults(),W.setColorMode(L.colorModeForRenderPass()),L.transform.projection.name==="globe"){const de=L.transform.pointMerc;ne.call(Z,W.gl,L.transform.customLayerMatrix(),L.transform.getProjection(),L.transform.globeToMercatorMatrix(),o.S(L.transform.zoom),[de.x,de.y],L.transform.pixelsPerMeterRatio)}else ne.call(Z,W.gl,L.transform.customLayerMatrix());W.setDirty(),L.setBaseState()}}else if(L.renderPass==="translucent"){if(L.terrain&&L.terrain.renderingToTexture){const de=Z.renderToTile;if(de){const ye=z[0].canonical,Ce={x:ye.x+z[0].wrap*(Z.wrapTileId?0:1<N.getTileByID(de));for(const de of ne)de.updateNeeded(L.id,Z)&&z.prepareTile(de,W,L.id,Z)}};async function ie(L){if(await Bt(),Object.assign(nN,{model:Xe.drawModels}),Object.assign(J,{model:Xe.prepare}),L&&!L._destroyed&&!L._shadowRenderer){const N=Xe.ShadowRenderer;N&&(L._shadowRenderer=new N(L))}}class Le{constructor(N,E,z,W,Z){this.context=new xx(N,E),this.transform=z,this._tileTextures={},this.frameCopies=[],this.loadTimeStamps=[],this.frcCoverageSnapshot=null,this.elevationCoverageSnapshot=null,this.elevationProvidersReady=void 0,this.frcCoverageFadeRange=null,this.frcCoverageSourceLayers=[],this.frcCoverageRenderer=wi.FrcCoverageRenderer?new wi.FrcCoverageRenderer:null,this._debugParams={averageFPS:0,fpsHistory:[],fpsWindow:30,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:-1,lodSwitchFadeDuration:.5},this.occlusionParams=new P6,this.setup(),this.numSublayers=uh.maxUnderzooming+uh.maxOverzooming+1,this.depthEpsilon=1/Math.pow(2,16),this.deferredRenderGpuTimeQueries=[],this.gpuTimers={},this.frameCounter=0,this.frameTimeDelta=0,this.lastPaintStartTimeStamp=0,this._shadowCullCache=null,this._backgroundTiles={},this.conflationActive=!1,this.replacementSource=new o.eq,this.longestCutoffRange=0,this.minCutoffZoom=0,this._fogVisible=!1,this._cachedTileFogOpacities={},this._wireframeDebugCache=new C4,this.renderDefaultNorthPole=!0,this.renderDefaultSouthPole=!0,this.layersWithOcclusionOpacity=[];const ne=new o.b({width:1,height:1},Uint8Array.of(0,0,0,0));this.emptyDepthTexture=new o.T(this.context,ne,N.RGBA8),this._clippingActiveLastFrame=!1,this.scaleFactor=W,this.maxFrontCutoffRawStart=0,this.worldview=Z,this._forceEmissiveMode=!1,this.emissiveMode="constant"}updateTerrain(N,E){const z=!!N&&!!N.terrain&&this.transform.projection.supportsTerrain;if(!(z||this._terrain&&this._terrain.enabled))return;this._terrain||(this._terrain=new Av(this,N));const W=this._terrain;this.transform.elevation=z?W:null,W.update(N,this.transform,E),this.transform.elevation&&!W.enabled&&(this.transform.elevation=null)}_updateFog(N){const E=N.fog;if(!E||this.transform.projection.name==="globe"||E.getOpacity(this.transform.pitch)<1||E.properties.get("horizon-blend")<.03)return void(this.transform.fogCullDistSq=null);const[z,W]=E.getRangeForProjection();if(z>W)return void(this.transform.fogCullDistSq=null);const Z=z+.78*(W-z);this.transform.fogCullDistSq=Z*Z}get terrain(){return this.transform._terrainEnabled()&&this._terrain&&this._terrain.enabled||this._forceTerrainMode?this._terrain:null}get forceTerrainMode(){return this._forceTerrainMode}set forceTerrainMode(N){N&&!this._terrain&&(this._terrain=new Av(this,this.style)),this._forceTerrainMode=N}get shadowRenderer(){return this._shadowRenderer&&this._shadowRenderer.enabled?this._shadowRenderer:null}get wireframeDebugCache(){return this._wireframeDebugCache}resize(N,E){if(this.width=N*o.e.devicePixelRatio,this.height=E*o.e.devicePixelRatio,this.context.viewport.set([0,0,this.width,this.height]),this.style)for(const z of this.style.order)this.style._mergedLayers[z].resize()}setup(){const N=this.context,E=new o.bC;E.emplaceBack(0,0),E.emplaceBack(o.a2,0),E.emplaceBack(0,o.a2),E.emplaceBack(o.a2,o.a2),this.tileExtentBuffer=N.createVertexBuffer(E,o.bE.members),this.tileExtentSegments=o.ac.simpleSegment(0,0,4,2);const z=new o.bC;z.emplaceBack(0,0),z.emplaceBack(o.a2,0),z.emplaceBack(0,o.a2),z.emplaceBack(o.a2,o.a2),this.debugBuffer=N.createVertexBuffer(z,o.bE.members),this.debugSegments=o.ac.simpleSegment(0,0,4,5);const W=new o.bC;W.emplaceBack(-1,-1),W.emplaceBack(1,-1),W.emplaceBack(-1,1),W.emplaceBack(1,1),this.viewportBuffer=N.createVertexBuffer(W,o.bE.members),this.viewportSegments=o.ac.simpleSegment(0,0,4,2);const Z=new o.bs;Z.emplaceBack(0,0,0,0),Z.emplaceBack(o.a2,0,o.a2,0),Z.emplaceBack(0,o.a2,0,o.a2),Z.emplaceBack(o.a2,o.a2,o.a2,o.a2),this.mercatorBoundsBuffer=N.createVertexBuffer(Z,Ig.members),this.mercatorBoundsSegments=o.ac.simpleSegment(0,0,4,2);const ne=new o.ad;ne.emplaceBack(0,1,2),ne.emplaceBack(2,1,3),this.quadTriangleIndexBuffer=N.createIndexBuffer(ne);const de=new o.bD;for(const Ce of[0,1,3,2,0])de.emplaceBack(Ce);this.debugIndexBuffer=N.createIndexBuffer(de),this.emptyTexture=new o.T(N,new o.b({width:1,height:1},Uint8Array.of(0,0,0,0)),N.gl.RGBA8),this.identityMat=o.Y();const ye=this.context.gl;this.stencilClearMode=new o._({func:ye.ALWAYS,mask:0},0,255,ye.ZERO,ye.ZERO,ye.ZERO),this.loadTimeStamps.push(performance.now())}getMercatorTileBoundsBuffers(){return{tileBoundsBuffer:this.mercatorBoundsBuffer,tileBoundsIndexBuffer:this.quadTriangleIndexBuffer,tileBoundsSegments:this.mercatorBoundsSegments}}getTileBoundsBuffers(N){return N._makeTileBoundsBuffers(this.context,this.transform.projection),N._tileBoundsBuffer?{tileBoundsBuffer:N._tileBoundsBuffer,tileBoundsIndexBuffer:N._tileBoundsIndexBuffer,tileBoundsSegments:N._tileBoundsSegments}:this.getMercatorTileBoundsBuffers()}clearStencil(){const N=this.context.gl;this.nextStencilID=1,this.currentStencilSource=void 0,this._tileClippingMaskIDs={},this.getOrCreateProgram("clippingMask").draw(this,N.TRIANGLES,o.Z.disabled,this.stencilClearMode,o.a1.disabled,o.$.disabled,Yu(this.identityMat),"$clipping",this.viewportBuffer,this.quadTriangleIndexBuffer,this.viewportSegments)}resetStencilClippingMasks(){this.terrain||(this.currentStencilSource=void 0,this._tileClippingMaskIDs={})}_renderTileClippingMasks(N,E,z){if(!E||this.currentStencilSource===E.id||!N.isTileClipped()||!z||z.length===0)return;if(this._tileClippingMaskIDs&&!this.terrain){let de=!1;for(const ye of z)if(this._tileClippingMaskIDs[ye.key]===void 0){de=!0;break}if(!de)return}this.currentStencilSource=E.id;const W=this.context,Z=W.gl;this.nextStencilID+z.length>256&&this.clearStencil(),W.setColorMode(o.a1.disabled),W.setDepthMode(o.Z.disabled);const ne=this.getOrCreateProgram("clippingMask");this._tileClippingMaskIDs={};for(const de of z){const ye=E.getTile(de),Ce=this._tileClippingMaskIDs[de.key]=this.nextStencilID++,{tileBoundsBuffer:Pe,tileBoundsIndexBuffer:Ke,tileBoundsSegments:Ze}=this.getTileBoundsBuffers(ye);ne.draw(this,Z.TRIANGLES,o.Z.disabled,new o._({func:Z.ALWAYS,mask:0},Ce,255,Z.KEEP,Z.KEEP,Z.REPLACE),o.a1.disabled,o.$.disabled,Yu(de.projMatrix),"$clipping",Pe,Ke,Ze)}}stencilModeFor3D(){this.currentStencilSource=void 0,this.nextStencilID+1>256&&this.clearStencil();const N=this.nextStencilID++,E=this.context.gl;return new o._({func:E.NOTEQUAL,mask:255},N,255,E.KEEP,E.KEEP,E.REPLACE)}stencilModeForClipping(N){if(this.terrain)return this.terrain.stencilModeForRTTOverlap(N);const E=this.context.gl;return new o._({func:E.EQUAL,mask:255},this._tileClippingMaskIDs[N.key],0,E.KEEP,E.KEEP,E.REPLACE)}stencilConfigForOverlap(N){const E=this.context.gl,z=N.sort((ne,de)=>de.overscaledZ-ne.overscaledZ),W=z.at(-1).overscaledZ,Z=z[0].overscaledZ-W+1;if(Z>1){this.currentStencilSource=void 0,this.nextStencilID+Z>256&&this.clearStencil();const ne={};for(let de=0;dethis.style._getOrder(W);let ne=Z(),de=!1,ye=!1,Ce=null,Pe=0,Ke=!1;for(const Mn of ne){const Hn=z[Mn];Hn.visibility!=="none"&&(Hn.type==="circle"?de=!0:Hn.type==="building"?(Ce=Hn,++Pe):Hn.type==="symbol"&&(Hn.hasOcclusionOpacityProperties?ye=!0:de=!0))}this.updateEmissiveMode();let Ze=ne.map(Mn=>z[Mn]);const mt=this.style._mergedSourceCaches;this.imageManager=N.imageManager,this.modelManager=N.modelManager,this.symbolFadeChange=N.placement.symbolFadeChange(o.e.now()),this.imageManager.beginFrame();for(const Mn in mt){const Hn=mt[Mn];Hn.used&&(Hn.prepare(this.context),Hn.getSource().usedInConflation&&++Pe)}let vt=!1;for(const Mn of Ze)Mn.isHidden(this.transform.zoom)||(Mn.type==="clip"&&(vt=!0),this.prepareLayer(Mn));const bt={},St={},Pt={},Gt={},as={};for(const Mn in mt){const Hn=mt[Mn];bt[Mn]=Hn.getVisibleCoordinates(),St[Mn]=bt[Mn].slice().reverse(),Pt[Mn]=Hn.getVisibleCoordinates(!0).reverse(),Gt[Mn]=Hn.getShadowCasterCoordinates(),as[Mn]=Hn.sortCoordinatesByDistance(bt[Mn])}const ms=Mn=>{const Hn=this.style.getLayerSourceCache(Mn);return Hn&&Hn.used?Hn.getSource():null};if(Pe||vt||this._clippingActiveLastFrame){const Mn=[],Hn=[];let Tr=0;for(const oa of Ze)this.isSourceForClippingOrConflation(oa,ms(oa))&&(Mn.push(oa),Hn.push(Tr)),Tr++;if(Mn&&(vt||Mn.length>1)||this._clippingActiveLastFrame){vt=!1;const oa=[];for(let Qr=0;Qr0){const oa=ms(Hn);oa&&(this.minCutoffZoom=Math.max(oa.minzoom,this.minCutoffZoom)),Hn.minzoom&&(this.minCutoffZoom=Math.max(Hn.minzoom,this.minCutoffZoom))}Hn.is3D(W)&&(this.opaquePassCutoff===1/0&&(this.opaquePassCutoff=Mn),this._lastOcclusionLayer=Mn)}const Gs=this.style&&this.style.fog;Gs?(this._fogVisible=Gs.getOpacity(this.transform.pitch)!==0,this._fogVisible&&this.transform.projection.name!=="globe"&&(this._fogVisible=Gs.isVisibleOnFrustum(this.transform.cameraFrustum))):this._fogVisible=!1,this._cachedTileFogOpacities={},this.terrain&&(this.terrain.updateTileBinding(Pt),this.opaquePassCutoff=0,ne=Z(),Ze=ne.map(Mn=>z[Mn])),this.style.enable3dLights()&&!this._shadowRenderer&&ie(this);const Ms=this._shadowRenderer;if(Ms){Ms.updateShadowParameters(this.transform,this.style.directionalLight);for(const Mn in mt)for(const Hn of bt[Mn]){let Tr={min:0,max:0};this.terrain&&(Tr=this.terrain.getMinMaxForTile(Hn)||Tr),Ms.addShadowReceiver(Hn.toUnwrapped(),Tr.min,Tr.max)}}this.transform.projection.name!=="globe"||this.globeSharedBuffers||(this.globeSharedBuffers=new o.es(this.context)),this.style.fog&&this.transform.projection.supportsFog?(this._atmosphere||(this._atmosphere=new M6),this._atmosphere.update(this)):this._atmosphere&&(this._atmosphere.destroy(),this._atmosphere=void 0);let Js=!(!this.style||!this.style.snow),Os=!(!this.style||!this.style.rain);if(Js&&!this._snow&&wi.Snow&&(this._snow=new wi.Snow),!Js&&this._snow&&(this._snow.destroy(),delete this._snow),Os&&!this._rain&&wi.Rain&&(this._rain=new wi.Rain),!Os&&this._rain&&(this._rain.destroy(),delete this._rain),this._snow&&this._snow.update(this),this._rain&&this._rain.update(this),Ce&&(!this.buildingTileBorderManager&&wi.BuildingTileBorderManager&&(this.buildingTileBorderManager=new wi.BuildingTileBorderManager),this.buildingTileBorderManager)){const Mn=this.style.getLayerSourceCache(Ce);this.buildingTileBorderManager.updateBorders(Mn,Ce)}if(!o.et(this.context.gl))return;this.renderPass="offscreen";for(const Mn of Ze){const Hn=N.getLayerSourceCache(Mn);if(!Mn.hasOffscreenPass()||Mn.isHidden(this.transform.zoom))continue;const Tr=Hn?St[Hn.id]:void 0;(Mn.type==="custom"||Mn.type==="raster"||Mn.type==="raster-particle"||Mn.isSky()||Tr&&Tr.length)&&this.renderLayer(this,Hn,Mn,Tr)}this.depthRangeFor3D=[0,1-(Ze.length+2)*this.numSublayers*this.depthEpsilon],this._shadowRenderer&&(this.renderPass="shadow",this._shadowRenderer.drawShadowPass(this.style,Gt)),this.context.bindFramebuffer.set(null),this.context.viewport.set([0,0,this.width,this.height]);const Ks=this.transform.projection.name==="globe"||this.transform.isHorizonVisible(),_n=(()=>{if(E.showOverdrawInspector)return o.C.black;const Mn=this.style.fog;if(Mn&&this.transform.projection.supportsFog){const Hn=this.style.getLut(Mn.scope);if(!Ks){const Tr=Mn.properties.get("color-use-theme")==="none",oa=Mn.properties.get("color").toNonPremultipliedRenderColor(Tr?null:Hn).toArray01();return new o.C(...oa)}if(Ks){const Tr=Mn.properties.get("space-color-use-theme")==="none",oa=Mn.properties.get("space-color").toNonPremultipliedRenderColor(Tr?null:Hn).toArray01();return new o.C(...oa)}}return o.C.transparent})();if(this.context.clear({color:_n,depth:1}),this.clearStencil(),this._showOverdrawInspector=E.showOverdrawInspector,this.renderPass="opaque",this.style.fog&&this.transform.projection.supportsFog&&this._atmosphere&&!this._showOverdrawInspector&&Ks&&this._atmosphere.drawStars(this,this.style.fog),!this.terrain)for(this.currentLayer=ne.length-1;this.currentLayer>=0;this.currentLayer--){const Mn=Ze[this.currentLayer],Hn=N.getLayerSourceCache(Mn);if(Mn.isSky())continue;const Tr=Hn?(Mn.is3D(W)?as:St)[Hn.id]:void 0;this._renderTileClippingMasks(Mn,Hn,Tr),this.renderLayer(this,Hn,Mn,Tr)}if(this.style.fog&&this.transform.projection.supportsFog&&this._atmosphere&&!this._showOverdrawInspector&&Ks&&this._atmosphere.drawAtmosphereGlow(this,this.style.fog),this.renderPass="sky",(!this._atmosphere||o.S(this.transform.zoom)>0)&&(this.transform.projection.name==="globe"||this.transform.isHorizonVisible()))for(this.currentLayer=0;this.currentLayer{for(this.currentLayer=0;this.currentLayer=this._lastOcclusionLayer&&this.layersWithOcclusionOpacity.length>0){const Tr=this.currentLayer;this.depthOcclusion=!0;for(const oa of this.layersWithOcclusionOpacity){this.currentLayer=oa;const Qr=Ze[this.currentLayer],Lr=N.getLayerSourceCache(Qr),qa=Lr?St[Lr.id]:void 0;this.terrain||this._renderTileClippingMasks(Qr,Lr,Lr?bt[Lr.id]:void 0),this.renderLayer(this,Lr,Qr,qa)}this.depthOcclusion=!1,this.currentLayer=Tr,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 Mn=null;Ze.forEach(Hn=>{const Tr=N.getLayerSourceCache(Hn);Tr&&!Hn.isHidden(this.transform.zoom)&&Tr.getVisibleCoordinates().length&&(!Mn||Mn.getSource().maxzoom0?E.pop():null}terrainRenderModeElevated(){return this.style&&this.style.hasTerrain()&&!!this.terrain&&!this.terrain.renderingToTexture||this.forceTerrainMode}linearFloatFilteringSupported(){return this.context.extTextureFloatLinear!=null}currentGlobalDefines(N,E,z,W,Z){const ne=z===void 0?this.terrain&&this.terrain.renderingToTexture:z,de=W===void 0?this.terrainRenderModeElevated():W,ye=Z===void 0?this.transform.projection.name==="globe":Z,Ce=[];return this.style&&this.style.enable3dLights()&&(N==="globeRaster"||N==="terrainRaster"?(Ce.push("LIGHTING_3D_MODE"),Ce.push("LIGHTING_3D_ALPHA_EMISSIVENESS")):ne||Ce.push("LIGHTING_3D_MODE")),de&&(Ce.push("TERRAIN"),this.linearFloatFilteringSupported()&&Ce.push("TERRAIN_DEM_FLOAT_FORMAT")),ye&&Ce.push("GLOBE"),!this._fogVisible||ne||E!==void 0&&!E||Ce.push("FOG"),ne&&Ce.push("RENDER_TO_TEXTURE"),this._showOverdrawInspector&&Ce.push("OVERDRAW_INSPECTOR"),Ce}getOrCreateProgram(N,E){this.cache=this.cache||{};const{defines:z,config:W,overrideFog:Z,overrideRtt:ne,overrideTerrain:de,overrideGlobe:ye,precompiled:Ce}=E||{},Pe=this.currentGlobalDefines(N,Z,ne,de,ye).concat(z||[]),Ke=this.getShaderSource(N),Ze=wi.programUniforms,mt=Xe.programUniforms,vt=D1[N]||Ze&&Ze[N]||mt&&mt[N],bt=Ob.cacheKey(Ke,N,Pe,W);return this.cache[bt]||(this.cache[bt]=new Ob(this.context,N,Ke,W,vt,Pe,Ce)),this.cache[bt]}getShaderSource(N){const E=wi.shaders,z=Xe.shaders;return o.eu[N]||E&&E[N]||z&&z[N]}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 N=this.context.gl;this.context.cullFace.set(!1),this.context.viewport.set([0,0,this.width,this.height]),this.context.blendEquation.set(N.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(),this._destroyed=!0}prepareDrawTile(){this.terrain&&this.terrain.prepareDrawTile()}uploadCommonLightUniforms(N,E,z){if(this.style.enable3dLights()){const W=this.style.directionalLight,Z=this.style.ambientLight;if(W&&Z){const ne=((de,ye,Ce,Pe)=>{const Ke=de.properties.get("direction"),Ze=de.properties.get("color-use-theme")==="none",mt=de.properties.get("color").toNonPremultipliedRenderColor(Ze?null:Ce.getLut(de.scope)).toArray01();let vt=de.properties.get("intensity");const bt=ye.properties.get("color-use-theme")==="none",St=ye.properties.get("color").toNonPremultipliedRenderColor(bt?null:Ce.getLut(ye.scope)).toArray01();let Pt=ye.properties.get("intensity");const Gt=[Ke.x,Ke.y,Ke.z];Pe&&(Pe.ambientIntensity!==void 0&&(Pt=Pe.ambientIntensity),Pe.directionalIntensity!==void 0&&(vt=Pe.directionalIntensity),Pe.ambientColor!==void 0&&(St[0]=Pe.ambientColor[0],St[1]=Pe.ambientColor[1],St[2]=Pe.ambientColor[2]),Pe.directionalColor!==void 0&&(mt[0]=Pe.directionalColor[0],mt[1]=Pe.directionalColor[1],mt[2]=Pe.directionalColor[2]));const as=o.dB(St,Pt),ms=o.dB(mt,vt);return{u_lighting_ambient_color:as,u_lighting_directional_dir:Gt,u_lighting_directional_color:ms,u_ground_radiance:P0(Gt,ms,as)}})(W,Z,this.style,z);E.setLightsUniformValues(N,ne)}}}uploadCommonUniforms(N,E,z,W,Z,ne){if(this.uploadCommonLightUniforms(N,E,ne),this.terrain&&this.terrain.renderingToTexture)return;const de=this.style.fog;if(de){const ye=de.getOpacity(this.transform.pitch),Ce=((Pe,Ke,Ze,mt,vt,bt,St,Pt,Gt,as,ms,Gs)=>{const Ms=Pe.transform,Js=Ke.properties.get("color-use-theme")==="none",Os=Ke.properties.get("color").toNonPremultipliedRenderColor(Js?null:Pe.style.getLut(Ke.scope)).toArray01();Os[3]=mt;const Ks=Pe.frameCounter/1e3%1,[_n,ln]=Ke.properties.get("vertical-range");return{u_fog_matrix:Ze?Ms.calculateFogTileMatrix(Ze):Gs||Pe.identityMat,u_fog_range:Ke.getRangeForProjection(),u_fog_color:Os,u_fog_horizon_blend:Ke.properties.get("horizon-blend"),u_fog_vertical_limit:[Math.min(_n,ln),ln],u_fog_temporal_offset:Ks,u_frustum_tl:vt,u_frustum_tr:bt,u_frustum_br:St,u_frustum_bl:Pt,u_globe_pos:Gt,u_globe_radius:as,u_viewport:ms,u_globe_transition:o.S(Ms.zoom),u_is_globe:+(Ms.projection.name==="globe")}})(this,de,z,ye,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.e.devicePixelRatio,this.transform.height*o.e.devicePixelRatio],W);E.setFogUniformValues(N,Ce)}Z&&E.setCutoffUniformValues(N,Z.uniformValues)}setTileLoadedFlag(N){this.tileLoaded=N}saveCanvasCopy(){const N=this.canvasCopy();N&&(this.frameCopies.push(N),this.tileLoaded=!1)}canvasCopy(){const N=this.context.gl,E=N.createTexture();return N.bindTexture(N.TEXTURE_2D,E),N.copyTexImage2D(N.TEXTURE_2D,0,N.RGBA,0,0,N.drawingBufferWidth,N.drawingBufferHeight,0),E}getCanvasCopiesAndTimestamps(){return{canvasCopies:this.frameCopies,timeStamps:this.loadTimeStamps}}averageElevationNeedsEasing(){if(!this.transform._elevation)return!1;const N=this.style&&this.style.fog;return!!N&&N.getOpacity(this.transform.pitch)!==0}getBackgroundTiles(){const N=this._backgroundTiles,E=this._backgroundTiles={},z=this.transform.coveringTiles({tileSize:512});for(const W of z)E[W.key]=N[W.key]||new Ym(W,512,this.transform.tileZoom,this,void 0,this.worldview);return E}clearBackgroundTiles(){this._backgroundTiles={}}isSourceForClippingOrConflation(N,E){return!(!N.is3D(!(!this.terrain||!this.terrain.enabled))||N.type!=="clip"&&N.type!=="building"&&(N.minzoom&&N.minzoom>this.transform.zoom||(this.style._clipLayerPresent||N.sourceLayer!=="building"&&N.sourceLayer!=="procedural_buildings")&&(!E||E.type!=="batched-model")))}isTileAffectedByFog(N){if(!this.style||!this.style.fog)return!1;if(this.transform.projection.name==="globe")return!0;let E=this._cachedTileFogOpacities[N.key];return E||(this._cachedTileFogOpacities[N.key]=E=this.style.fog.getOpacityForTile(N)),E[0]>=o.at||E[1]>=o.at}setupDepthForOcclusion(N,E,z){const W=this.context,Z=W.gl,ne=!!z;var de;z||(z={u_dem:2,u_dem_prev:4,u_dem_tl:[0,0],u_dem_tl_prev:[0,0],u_dem_scale:0,u_dem_scale_prev:0,u_dem_size:0,u_dem_lerp:1,u_depth:3,u_depth_size_inv:[0,0],u_depth_range_unpack:[0,1],u_occluder_half_size:16,u_occlusion_depth_offset:-1e-4,u_exaggeration:0}),W.activeTexture.set(Z.TEXTURE3),N&&this.depthFBO&&this.depthTexture?(this.depthTexture.bind(Z.NEAREST,Z.CLAMP_TO_EDGE),z.u_depth_size_inv=[1/this.depthFBO.width,1/this.depthFBO.height],z.u_depth_range_unpack=[2/((de=this.depthRangeFor3D)[1]-de[0]),-1-2*de[0]/(de[1]-de[0])],z.u_occluder_half_size=.5*this.occlusionParams.occluderSize,z.u_occlusion_depth_offset=this.occlusionParams.depthOffset):this.emptyDepthTexture.bind(Z.NEAREST,Z.CLAMP_TO_EDGE),W.activeTexture.set(Z.TEXTURE0),ne||E.setTerrainUniformValues(W,z)}updateEmissiveMode(){if(this._forceEmissiveMode)return;const N=this.style.hasDataDrivenEmissiveStrength();this.emissiveMode=N?this.context.extBlendFuncExtended?"dual-source-blending":"mrt-fallback":"constant"}}function Qe(L,N){let E=!1,z=null;const W=()=>{z=null,E&&(L(),z=setTimeout(W,N),E=!1)};return()=>(E=!0,z||W(),z)}const it=/(#.+)?$/;class It{constructor(N){this._hashName=N&&encodeURIComponent(N),o.aV(["_getCurrentHash","_onHashChange","_updateHash"],this),this._updateHash=Qe(this._updateHashUnthrottled.bind(this),300)}addTo(N){return this._map=N,window.addEventListener("hashchange",this._onHashChange,!1),N.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 N=this._map;if(!N)return"";const E=Ds(N);if(this._hashName){const z=this._hashName;let W=!1;const Z=location.hash.slice(1).split("&").map(ne=>{const de=ne.split("=")[0];return de===z?(W=!0,`${de}=${E}`):ne}).filter(ne=>ne);return W||Z.push(`${z}=${E}`),`#${Z.join("&")}`}return`#${E}`}_getCurrentHash(){const N=location.hash.replace("#","");if(this._hashName){let E;return N.split("&").map(z=>z.split("=")).forEach(z=>{z[0]===this._hashName&&(E=z)}),(E&&E[1]||"").split("/")}return N.split("/")}_onHashChange(){const N=this._map;if(!N)return!1;const E=this._getCurrentHash();if(E.length>=3&&!E.some(z=>isNaN(Number(z)))){const z=N.dragRotate.isEnabled()&&N.touchZoomRotate.isEnabled()?+(E[3]||0):N.getBearing();return N.jumpTo({center:[+E[2],+E[1]],zoom:+E[0],bearing:z,pitch:+(E[4]||0)}),!0}return!1}_updateHashUnthrottled(){history.replaceState(history.state,"",location.href.replace(it,this.getHashString()))}}function Ds(L,N){const E=L.getCenter(),z=Math.round(100*L.getZoom())/100,W=Math.ceil((z*Math.LN2+Math.log(512/360/.5))/Math.LN10),Z=Math.pow(10,W),ne=Math.round(E.lng*Z)/Z,de=Math.round(E.lat*Z)/Z,ye=L.getBearing(),Ce=L.getPitch();let Pe=N?`/${ne}/${de}/${z}`:`${z}/${de}/${ne}`;return(ye||Ce)&&(Pe+="/"+Math.round(10*ye)/10),Ce&&(Pe+=`/${Math.round(Ce)}`),Pe}const $n={linearity:.3,easing:o.ew(0,0,.3,1)},Pr={deceleration:2500,maxSpeed:1400,...$n},Sa={deceleration:20,maxSpeed:1400,...$n},qi={deceleration:1e3,maxSpeed:360,...$n},Kl={deceleration:1e3,maxSpeed:90,...$n};class Di{constructor(N){this._map=N,this.clear()}clear(){this._inertiaBuffer=[]}record(N){this._drainInertiaBuffer(),this._inertiaBuffer.push({time:o.e.now(),settings:N})}_drainInertiaBuffer(){const N=this._inertiaBuffer,E=o.e.now();for(;N.length>0&&E-N[0].time>160;)N.shift()}_onMoveEnd(N){if(this._map._prefersReducedMotion()||(this._drainInertiaBuffer(),this._inertiaBuffer.length<2))return;const E={zoom:0,bearing:0,pitch:0,pan:new o.P(0,0),pinchAround:void 0,around:void 0};for(const{settings:Z}of this._inertiaBuffer)E.zoom+=Z.zoomDelta||0,E.bearing+=Z.bearingDelta||0,E.pitch+=Z.pitchDelta||0,Z.panDelta&&E.pan._add(Z.panDelta),Z.around&&(E.around=Z.around),Z.pinchAround&&(E.pinchAround=Z.pinchAround);const z=this._inertiaBuffer.at(-1).time-this._inertiaBuffer[0].time,W={};if(E.pan.mag()){const Z=Bd(E.pan.mag(),z,{...Pr,...N||{}});W.offset=E.pan.mult(Z.amount/E.pan.mag()),W.center=this._map.transform.center,cu(W,Z)}if(E.zoom){const Z=Bd(E.zoom,z,Sa);W.zoom=this._map.transform.zoom+Z.amount,cu(W,Z)}if(E.bearing){const Z=Bd(E.bearing,z,qi);W.bearing=this._map.transform.bearing+o.b0(Z.amount,-179,179),cu(W,Z)}if(E.pitch){const Z=Bd(E.pitch,z,Kl);W.pitch=this._map.transform.pitch+Z.amount,cu(W,Z)}if(W.zoom||W.bearing){const Z=E.pinchAround===void 0?E.around:E.pinchAround;W.around=Z?this._map.unproject(Z):this._map.getCenter()}return this.clear(),W.noMoveStart=!0,W}}function cu(L,N){(!L.duration||L.durationE.unproject(ye)),de=Z.reduce((ye,Ce,Pe,Ke)=>ye.add(Ce.div(Ke.length)),new o.P(0,0));super(N,{points:Z,point:de,lngLats:ne,lngLat:E.unproject(de),originalEvent:z}),this._defaultPrevented=!1}}class tr extends o.h{preventDefault(){this._defaultPrevented=!0}get defaultPrevented(){return this._defaultPrevented}constructor(N,E){super("wheel",{originalEvent:E}),this._defaultPrevented=!1}}class ar{constructor(N,E){this._map=N,this._clickTolerance=E.clickTolerance}reset(){this._mousedownPos=void 0}wheel(N){return this._firePreventable(new tr(this._map,N))}mousedown(N,E){return this._mousedownPos=E,this._firePreventable(new Qu(N.type,this._map,N))}mouseup(N){this._map.fire(new Qu(N.type,this._map,N))}preclick(N){const E=new MouseEvent("preclick",N);this._map.fire(new Qu(E.type,this._map,E))}click(N,E){this._mousedownPos&&this._mousedownPos.dist(E)>=this._clickTolerance||(this.preclick(N),this._map.fire(new Qu(N.type,this._map,N)))}dblclick(N){return this._firePreventable(new Qu(N.type,this._map,N))}mouseover(N){this._map.fire(new Qu(N.type,this._map,N))}mouseout(N){this._map.fire(new Qu(N.type,this._map,N))}touchstart(N){return this._firePreventable(new vp(N.type,this._map,N))}touchmove(N){this._map.fire(new vp(N.type,this._map,N))}touchend(N){this._map.fire(new vp(N.type,this._map,N))}touchcancel(N){this._map.fire(new vp(N.type,this._map,N))}_firePreventable(N){if(this._map.fire(N),N.defaultPrevented)return{}}isEnabled(){return!0}isActive(){return!1}enable(){}disable(){}}class qr{constructor(N){this._map=N}reset(){this._delayContextMenu=!1,this._contextMenuEvent=void 0}mousemove(N){this._map.fire(new Qu(N.type,this._map,N))}mousedown(){this._delayContextMenu=!0}mouseup(){this._delayContextMenu=!1,this._contextMenuEvent&&(this._map.fire(new Qu("contextmenu",this._map,this._contextMenuEvent)),delete this._contextMenuEvent)}contextmenu(N){this._delayContextMenu?this._contextMenuEvent=N:this._map.fire(new Qu(N.type,this._map,N)),this._map.listens("contextmenu")&&N.preventDefault()}isEnabled(){return!0}isActive(){return!1}enable(){}disable(){}}class Vi{constructor(N,E){this._map=N,this._el=N.getCanvasContainer(),this._container=N.getContainer(),this._clickTolerance=E.clickTolerance||1}isEnabled(){return!!this._enabled}isActive(){return!!this._active}enable(){this.isEnabled()||(this._enabled=!0)}disable(){this.isEnabled()&&(this._enabled=!1)}mousedown(N,E){this.isEnabled()&&N.shiftKey&&N.button===0&&(j(),this._startPos=this._lastPos=E,this._active=!0)}mousemoveWindow(N,E){if(!this._active)return;const z=E,W=this._startPos,Z=this._lastPos;if(!W||!Z||Z.equals(z)||!this._box&&z.dist(W){this._box&&(this._box.style.transform=`translate(${ne}px,${ye}px)`,this._box.style.width=de-ne+"px",this._box.style.height=Ce-ye+"px")})}mouseupWindow(N,E){if(!this._active)return;const z=this._startPos,W=E;if(z&&N.button===0){if(this.reset(),M(),z.x!==W.x||z.y!==W.y)return this._map.fire(new o.h("boxzoomend",{originalEvent:N})),{cameraAnimation:Z=>Z.fitScreenCoordinates(z,W,this._map.getBearing(),{linear:!1})};this._fireEvent("boxzoomcancel",N)}}keydown(N){this._active&&N.keyCode===27&&(this.reset(),this._fireEvent("boxzoomcancel",N))}blur(){this.reset()}reset(){this._active=!1,this._container.classList.remove("mapboxgl-crosshair"),this._box&&(this._box.remove(),this._box=null),C(),delete this._startPos,delete this._lastPos}_fireEvent(N,E){return this._map.fire(new o.h(N,{originalEvent:E}))}}function Vo(L,N){const E={};for(let z=0;zthis.numTouches)&&(this.aborted=!0),this.aborted||(this.startTime===0&&(this.startTime=N.timeStamp),z.length===this.numTouches&&(this.centroid=function(W){const Z=new o.P(0,0);for(const ne of W)Z._add(ne);return Z.div(W.length)}(E),this.touches=Vo(z,E)))}touchmove(N,E,z){if(this.aborted||!this.centroid)return;const W=Vo(z,E);for(const Z in this.touches){const ne=W[Z];(!ne||ne.dist(this.touches[Z])>30)&&(this.aborted=!0)}}touchend(N,E,z){if((!this.centroid||N.timeStamp-this.startTime>500)&&(this.aborted=!0),z.length===0){const W=!this.aborted&&this.centroid;if(this.reset(),W)return W}}}class Al{constructor(N){this.singleTap=new xc(N),this.numTaps=N.numTaps,this.reset()}reset(){this.lastTime=1/0,this.lastTap=void 0,this.count=0,this.singleTap.reset()}touchstart(N,E,z){this.singleTap.touchstart(N,E,z)}touchmove(N,E,z){this.singleTap.touchmove(N,E,z)}touchend(N,E,z){const W=this.singleTap.touchend(N,E,z);if(W){const Z=N.timeStamp-this.lastTime<500,ne=!this.lastTap||this.lastTap.dist(W)<30;if(Z&&ne||this.reset(),this.count++,this.lastTime=N.timeStamp,this.lastTap=W,this.count===this.numTaps)return this.reset(),W}}}class wc{constructor(){this._zoomIn=new Al({numTouches:1,numTaps:2}),this._zoomOut=new Al({numTouches:2,numTaps:1}),this.reset()}reset(){this._active=!1,this._zoomIn.reset(),this._zoomOut.reset()}touchstart(N,E,z){this._zoomIn.touchstart(N,E,z),this._zoomOut.touchstart(N,E,z)}touchmove(N,E,z){this._zoomIn.touchmove(N,E,z),this._zoomOut.touchmove(N,E,z)}touchend(N,E,z){const W=this._zoomIn.touchend(N,E,z),Z=this._zoomOut.touchend(N,E,z);return W?(this._active=!0,N.preventDefault(),setTimeout(()=>this.reset(),0),{cameraAnimation:ne=>ne.easeTo({duration:300,zoom:ne.getZoom()+1,around:ne.unproject(W)},{originalEvent:N})}):Z?(this._active=!0,N.preventDefault(),setTimeout(()=>this.reset(),0),{cameraAnimation:ne=>ne.easeTo({duration:300,zoom:ne.getZoom()-1,around:ne.unproject(Z)},{originalEvent:N})}):void 0}touchcancel(){this.reset()}enable(){this._enabled=!0}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}}const Ch=0,Bn=2,hr={[Ch]:1,[Bn]:2},Aj={Control:"ctrlKey",Alt:"altKey",Shift:"shiftKey",Meta:"metaKey"};class $d{constructor(N){this.reset(),this._clickTolerance=N.clickTolerance||1}blur(){this.reset()}reset(){this._active=!1,this._moved=!1,this._lastPoint=void 0,this._eventButton=void 0}_correctButton(N,E){return!1}_move(N,E){return{}}mousedown(N,E){if(this._lastPoint)return;const z=R(N);this._correctButton(N,z)&&(this._lastPoint=E,this._eventButton=z)}mousemoveWindow(N,E){const z=this._lastPoint;if(z){if(N.preventDefault(),this._eventButton!=null&&function(W,Z){const ne=hr[Z];return W.buttons===void 0||(W.buttons&ne)!==ne}(N,this._eventButton))this.reset();else if(this._moved||!(E.dist(z)0&&(this._active=!0);const W=Vo(z,E),Z=new o.P(0,0),ne=new o.P(0,0);let de=0;for(const Ce in W){const Pe=W[Ce],Ke=this._touches[Ce];Ke&&(Z._add(Pe),ne._add(Pe.sub(Ke)),de++,W[Ce]=Pe)}if(this._touches=W,de{this._alertContainer.classList.remove("mapboxgl-touch-pan-blocker-show"),this._alertContainer.removeAttribute("role")},500)}}class L6{constructor(){this.reset()}reset(){this._active=!1,this._firstTwoTouches=void 0}_start(N){}_move(N,E,z){return{}}touchstart(N,E,z){this._firstTwoTouches||z.length<2||(this._firstTwoTouches=[z[0].identifier,z[1].identifier],this._start([E[0],E[1]]))}touchmove(N,E,z){const W=this._firstTwoTouches;if(!W)return;N.preventDefault();const[Z,ne]=W,de=R6(z,E,Z),ye=R6(z,E,ne);if(!de||!ye)return;const Ce=this._aroundCenter?null:de.add(ye).div(2);return this._move([de,ye],Ce,N)}touchend(N,E,z){if(!this._firstTwoTouches)return;const[W,Z]=this._firstTwoTouches,ne=R6(z,E,W),de=R6(z,E,Z);ne&&de||(this._active&&M(),this.reset())}touchcancel(){this.reset()}enable(N){this._enabled=!0,this._aroundCenter=!!N&&N.around==="center"}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}}function R6(L,N,E){for(let z=0;zMath.abs(L.x)}class n7 extends L6{constructor(N){super(),this._map=N}reset(){super.reset(),this._valid=void 0,this._firstMove=void 0,this._lastPoints=void 0}_start(N){this._lastPoints=N,s7(N[0].sub(N[1]))&&(this._valid=!1)}_move(N,E,z){const W=this._lastPoints;if(!W)return;const Z=N[0].sub(W[0]),ne=N[1].sub(W[1]);return this._map._cooperativeGestures&&!o.ex()&&z.touches.length<3||(this._valid=this.gestureBeginsVertically(Z,ne,z.timeStamp),!this._valid)?void 0:(this._lastPoints=N,this._active=!0,{pitchDelta:(Z.y+ne.y)/2*-.5})}gestureBeginsVertically(N,E,z){if(this._valid!==void 0)return this._valid;const W=N.mag()>=2,Z=E.mag()>=2;if(!W&&!Z)return;if(!W||!Z)return this._firstMove??(this._firstMove=z),z-this._firstMove<100&&void 0;const ne=N.y>0==E.y>0;return s7(N)&&s7(E)&&ne}}const eH={panStep:100,bearingStep:15,pitchStep:10};class Ete{constructor(){const N=eH;this._panStep=N.panStep,this._bearingStep=N.bearingStep,this._pitchStep=N.pitchStep,this._bearingDisabled=!1,this._pitchDisabled=!1,this._panDisabled=!1,this._zoomDisabled=!1}blur(){this.reset()}reset(){this._active=!1}keydown(N){if(N.altKey||N.ctrlKey||N.metaKey||!this.isEnabled())return;let E=0,z=0,W=0,Z=0,ne=0;switch(N.keyCode){case 61:case 107:case 171:case 187:E=1;break;case 189:case 109:case 173:E=-1;break;case 37:N.shiftKey?z=-1:(N.preventDefault(),Z=-1);break;case 39:N.shiftKey?z=1:(N.preventDefault(),Z=1);break;case 38:N.shiftKey?W=1:(N.preventDefault(),ne=-1);break;case 40:N.shiftKey?W=-1:(N.preventDefault(),ne=1);break;default:return}return this._bearingDisabled&&(z=0),this._pitchDisabled&&(W=0),this._panDisabled&&(Z=0,ne=0),this._zoomDisabled&&(E=0),{cameraAnimation:de=>{const ye=de.getZoom();de.easeTo({duration:300,easeId:"keyboardHandler",easing:Tte,zoom:E?Math.round(ye)+E*(N.shiftKey?2:1):ye,bearing:de.getBearing()+z*this._bearingStep,pitch:de.getPitch()+W*this._pitchStep,offset:[-Z*this._panStep,-ne*this._panStep],center:de.getCenter()},{originalEvent:N})}}}enable(){this._enabled=!0}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled&&!(this._bearingDisabled&&this._pitchDisabled&&this._panDisabled&&this._zoomDisabled)}isActive(){return this._active}disableRotation(){this._pitchDisabled=!0,this._bearingDisabled=!0}enableRotation(){this._pitchDisabled=!1,this._bearingDisabled=!1}isRotationEnabled(){return!this._pitchDisabled&&!this._bearingDisabled}disablePan(){this._panDisabled=!0}enablePan(){this._panDisabled=!1}isPanEnabled(){return!this._panDisabled}disableZoom(){this._zoomDisabled=!0}enableZoom(){this._zoomDisabled=!1}isZoomEnabled(){return!this._zoomDisabled}disablePitch(){this._pitchDisabled=!0}enablePitch(){this._pitchDisabled=!1}isPitchEnabled(){return!this._pitchDisabled}disableBearing(){this._bearingDisabled=!0}enableBearing(){this._bearingDisabled=!1}isBearingEnabled(){return!this._bearingDisabled}}function Tte(L){return L*(2-L)}const D6=4.000244140625,O6=1/450,r7=/(Mac|iPad)/i;class Mte{constructor(N,E){this._map=N,this._el=N.getCanvasContainer(),this._handler=E,this._delta=0,this._lastDelta=0,this._defaultZoomRate=.01,this._wheelZoomRate=O6,o.aV(["_onTimeout","_addScrollZoomBlocker","_showBlockerAlert"],this)}setZoomRate(N){this._defaultZoomRate=N}setWheelZoomRate(N){this._wheelZoomRate=N}isEnabled(){return!!this._enabled}isActive(){return this._active||this._finishTimeout!==void 0}isZooming(){return!!this._zooming}enable(N){this.isEnabled()||(this._enabled=!0,this._aroundCenter=!!N&&N.around==="center",this._map._cooperativeGestures&&this._addScrollZoomBlocker())}disable(){this.isEnabled()&&(this._enabled=!1,this._map._cooperativeGestures&&(clearTimeout(this._alertTimer),this._alertContainer.remove()))}wheel(N){if(!this.isEnabled())return;if(this._map._cooperativeGestures){if(!(N.ctrlKey||N.metaKey||this.isZooming()||o.ex()))return void this._showBlockerAlert();this._alertContainer.style.visibility!=="hidden"&&(this._alertContainer.style.visibility="hidden",clearTimeout(this._alertTimer))}let E=N.deltaMode===WheelEvent.DOM_DELTA_LINE?40*N.deltaY:N.deltaY;const z=o.e.now(),W=z-(this._lastWheelEventTime||0);this._lastWheelEventTime=z,E!==0&&E%D6===0?this._type="wheel":E!==0&&Math.abs(E)<4?this._type="trackpad":W>400?(this._type=null,this._lastValue=E,this._timeout=window.setTimeout(this._onTimeout,40,N)):this._type||(this._type=Math.abs(W*E)<200?"trackpad":"wheel",this._timeout&&(clearTimeout(this._timeout),this._timeout=null,E+=this._lastValue)),N.shiftKey&&E&&(E/=4),this._type&&(this._lastWheelEvent=N,this._delta-=E,this._active||this._start(N)),N.preventDefault()}_onTimeout(N){this._type="wheel",this._delta-=this._lastValue,this._active||this._start(N)}_start(N){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 E=I(this._el,N);this._aroundPoint=this._aroundCenter?this._map.transform.centerPoint:E,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 N=this._map.transform;this._type==="wheel"&&N.projection.wrap&&(N._center.lng>=180||N._center.lng<=-180)&&(this._prevEase=null,this._easing=null,this._lastWheelEvent=null,this._lastWheelEventTime=0);const E=()=>N._terrainEnabled()&&this._aroundCoord?N.computeZoomRelativeTo(this._aroundCoord):N.zoom;if(this._delta!==0){const Ce=this._type==="wheel"&&Math.abs(this._delta)>D6?this._wheelZoomRate:this._defaultZoomRate;let Pe=2/(1+Math.exp(-Math.abs(this._delta*Ce)));this._delta<0&&Pe!==0&&(Pe=1/Pe);const Ke=E(),Ze=Math.pow(2,Ke),mt=typeof this._targetZoom=="number"?N.zoomScale(this._targetZoom):Ze;this._targetZoom=Math.min(N.maxZoom,Math.max(N.minZoom,N.scaleZoom(mt*Pe))),this._type==="wheel"&&(this._startZoom=Ke,this._easing=this._smoothOutEasing(200)),this._lastDelta=this._delta,this._delta=0}const z=typeof this._targetZoom=="number"?this._targetZoom:E(),W=this._startZoom,Z=this._easing;let ne,de=!1;if(this._type==="wheel"&&W&&Z){const Ce=Math.min((o.e.now()-this._lastWheelEventTime)/200,1),Pe=Z(Ce);ne=o.al(W,z,Pe),Ce<1?this._frameId||(this._frameId=!0):de=!0}else ne=z,de=!0;this._active=!0,de&&(this._active=!1,this._finishTimeout=window.setTimeout(()=>{this._zooming=!1,this._handler._triggerRenderFrame(),delete this._targetZoom,delete this._finishTimeout},200));let ye=ne-E();return ye*this._lastDelta<0&&(ye=0),{noInertia:!0,needsRenderFrame:!de,zoomDelta:ye,around:this._aroundPoint,aroundCoord:this._aroundCoord,originalEvent:this._lastWheelEvent}}_smoothOutEasing(N){let E=o.ey;if(this._prevEase){const z=this._prevEase,W=(o.e.now()-z.start)/z.duration,Z=z.easing(W+.01)-z.easing(W),ne=.27/Math.sqrt(Z*Z+1e-4)*.01,de=Math.sqrt(.0729-ne*ne);E=o.ew(ne,de,.25,1)}return this._prevEase={start:o.e.now(),duration:N,easing:E},E}blur(){this.reset()}reset(){this._active=!1}_addScrollZoomBlocker(){this._map&&!this._alertContainer&&(this._alertContainer=g("div","mapboxgl-scroll-zoom-blocker",this._map._container),this._alertContainer.textContent=r7.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 Pte{constructor(N,E){this._clickZoom=N,this._tapZoom=E}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 Ite{constructor(){this.reset()}reset(){this._active=!1}blur(){this.reset()}dblclick(N,E){return N.preventDefault(),{cameraAnimation:z=>{z.easeTo({duration:300,zoom:z.getZoom()+(N.shiftKey?-1:1),around:z.unproject(E)},{originalEvent:N})}}}enable(){this._enabled=!0}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}}class Lte{constructor(){this._tap=new Al({numTouches:1,numTaps:1}),this.reset()}reset(){this._active=!1,this._swipePoint=void 0,this._swipeTouch=0,this._tapTime=0,this._tap.reset()}touchstart(N,E,z){this._swipePoint||(this._tapTime&&N.timeStamp-this._tapTime>500&&this.reset(),this._tapTime?z.length>0&&(this._swipePoint=E[0],this._swipeTouch=z[0].identifier):this._tap.touchstart(N,E,z))}touchmove(N,E,z){if(this._tapTime){if(this._swipePoint){if(z[0].identifier!==this._swipeTouch)return;const W=E[0],Z=W.y-this._swipePoint.y;return this._swipePoint=W,N.preventDefault(),this._active=!0,{zoomDelta:Z/128}}}else this._tap.touchmove(N,E,z)}touchend(N,E,z){this._tapTime?this._swipePoint&&z.length===0&&this.reset():this._tap.touchend(N,E,z)&&(this._tapTime=N.timeStamp)}touchcancel(){this.reset()}enable(){this._enabled=!0}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}}class Rte{constructor(N,E,z){this._el=N,this._mousePan=E,this._touchPan=z}enable(N){this._inertiaOptions=N||{},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 cMe{constructor(N,E,z){this._pitchWithRotate=N.pitchWithRotate,this._mouseRotate=E,this._mousePitch=z,this._pitchDisabled=!1,this._rotationDisabled=!1}enable(){this._rotationDisabled||this._mouseRotate.enable(),this._pitchWithRotate&&!this._pitchDisabled&&this._mousePitch.enable()}disable(){this._mouseRotate.disable(),this._mousePitch.disable()}isEnabled(){return this._pitchWithRotate?!this._rotationDisabled&&this._mouseRotate.isEnabled()||!this._pitchDisabled&&this._mousePitch.isEnabled():!this._rotationDisabled&&this._mouseRotate.isEnabled()}isActive(){return this._mouseRotate.isActive()||this._mousePitch.isActive()}disablePitch(){this._pitchDisabled=!0,this._mousePitch.disable()}enablePitch(){this._pitchDisabled=!1,this._pitchWithRotate&&this._mouseRotate.isEnabled()&&this._mousePitch.enable()}isPitchEnabled(){return!this._pitchDisabled&&this._mousePitch.isEnabled()}disableRotation(){this._rotationDisabled=!0,this._mouseRotate.disable()}enableRotation(){this._rotationDisabled=!1,this._mouseRotate.enable()}isRotationEnabled(){return!this._rotationDisabled&&this._mouseRotate.isEnabled()}}class Dte{constructor(N,E,z,W){this._el=N,this._touchZoom=E,this._touchRotate=z,this._tapDragZoom=W,this._rotationDisabled=!1,this._tapDragZoomDisabled=!1,this._enabled=!0}enable(N){this._touchZoom.enable(N),this._rotationDisabled||this._touchRotate.enable(N),this._tapDragZoomDisabled||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._tapDragZoomDisabled&&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()}isRotationEnabled(){return!this._rotationDisabled}disableTapDragZoom(){this._tapDragZoomDisabled=!0,this._tapDragZoom.disable()}enableTapDragZoom(){this._tapDragZoomDisabled=!1,this._touchZoom.isEnabled()&&this._tapDragZoom.enable()}isTapDragZoomEnabled(){return!this._tapDragZoomDisabled}}const a7=L=>L.zoom||L.drag||L.pitch||L.rotate;class zy extends o.h{}class i7{constructor(){this.constants=[1,1,.01],this.radius=0}setup(N,E){const z=o.c2([],E,N);this.radius=o.em(z[2]<0?o.eA([],z,this.constants):[z[0],z[1],0])}projectRay(N){o.eA(N,N,this.constants),o.c3(N,N),o.eB(N,N,this.constants);const E=o.dC([],N,this.radius);if(E[2]>0){const z=o.dC([],[0,0,1],o.dF(E,[0,0,1])),W=o.dC([],o.c3([],[E[0],E[1],0]),this.radius),Z=o.dD([],E,o.dC([],o.c2([],o.dD([],W,z),E),2));E[0]=Z[0],E[1]=Z[1]}return E}}function rN(L){return L.panDelta&&L.panDelta.mag()||L.zoomDelta||L.bearingDelta||L.pitchDelta}class Ote{constructor(N,E){this._map=N,this._el=this._map.getCanvasContainer(),this._handlers=[],this._handlersById={},this._changes=[],this._inertia=new Di(N),this._bearingSnap=E.bearingSnap,this._previousActiveHandlers={},this._trackingEllipsoid=new i7,this._dragOrigin=null,this._mouseBeingPressed=!1,this._activeTouchCount=0,this._eventsInProgress={},this._addDefaultHandlers(E),o.aV(["handleEvent","handleWindowEvent"],this);const z=this._el;this._listeners=[[z,"touchstart",{passive:!0}],[z,"touchmove",{passive:!1}],[z,"touchend",void 0],[z,"touchcancel",void 0],[z,"mousedown",void 0],[z,"mousemove",void 0],[z,"mouseup",void 0],[document,"mousemove",{capture:!0}],[document,"mouseup",void 0],[z,"mouseover",void 0],[z,"mouseout",void 0],[z,"dblclick",void 0],[z,"click",void 0],[z,"keydown",{capture:!1}],[z,"keyup",void 0],[z,"wheel",{passive:!1}],[z,"contextmenu",void 0],[window,"blur",void 0]];for(const[W,Z,ne]of this._listeners){const de=W===document?this.handleWindowEvent:this.handleEvent;W.addEventListener(Z,de,ne)}}destroy(){for(const[N,E,z]of this._listeners){const W=N===document?this.handleWindowEvent:this.handleEvent;N.removeEventListener(E,W,z)}}_addDefaultHandlers(N){const E=this._map,z=E.getCanvasContainer();this._add("mapEvent",new ar(E,N));const W=E.boxZoom=new Vi(E,N);this._add("boxZoom",W);const Z=new wc,ne=new Ite;E.doubleClickZoom=new Pte(ne,Z),this._add("tapZoom",Z),this._add("clickZoom",ne);const de=new Lte;this._add("tapDragZoom",de);const ye=E.touchPitch=new n7(E);this._add("touchPitch",ye);const Ce=new XV(N),Pe=new I6(N);E.dragRotate=new cMe(N,Ce,Pe),this._add("mouseRotate",Ce,["mousePitch"]),this._add("mousePitch",Pe,["mouseRotate"]);const Ke=new Us(N),Ze=new QV(E,N);E.dragPan=new Rte(z,Ke,Ze),this._add("mousePan",Ke),this._add("touchPan",Ze,["touchZoom","touchRotate"]);const mt=new lMe,vt=new yA;E.touchZoomRotate=new Dte(z,vt,mt,de),this._add("touchRotate",mt,["touchPan","touchZoom"]),this._add("touchZoom",vt,["touchPan","touchRotate"]),this._add("blockableMapEvent",new qr(E));const bt=E.scrollZoom=new Mte(E,this);this._add("scrollZoom",bt,["mousePan"]);const St=E.keyboard=new Ete;this._add("keyboard",St);for(const Pt of["boxZoom","doubleClickZoom","tapDragZoom","touchPitch","dragRotate","dragPan","touchZoomRotate","scrollZoom","keyboard"])N.interactive&&N[Pt]&&E[Pt].enable(N[Pt])}_add(N,E,z){this._handlers.push({handlerName:N,handler:E,allowed:z}),this._handlersById[N]=E}stop(N="never"){if(!this._updatingCamera&&!(N==="always"||N==="ifPointerDown"&&this._isPointerDown())){for(const{handler:E}of this._handlers)E.reset();this._inertia.clear(),this._fireEvents({},{},!1),this._changes=[],this._originalZoom=void 0}}isActive(){for(const{handler:N}of this._handlers)if(N.isActive())return!0;return!1}isZooming(){return!!this._eventsInProgress.zoom||this._map.scrollZoom.isZooming()}isRotating(){return!!this._eventsInProgress.rotate}isMoving(){return!!a7(this._eventsInProgress)||this.isZooming()}_isDragging(){return!!this._eventsInProgress.drag}_blockedByActive(N,E,z){for(const W in N)if(!(W===z||E&&E.includes(W)))return!0;return!1}handleWindowEvent(N){this.handleEvent(N,`${N.type}Window`)}_getMapTouches(N){const E=[];for(const z of N)this._el.contains(z.target)&&E.push(z);return E}_updatePointerLiveness(N){switch(N.type){case"mousedown":this._mouseBeingPressed=!0;break;case"mousemove":N.buttons===0&&(this._mouseBeingPressed=!1);break;case"mouseup":this._mouseBeingPressed=!1;break;case"touchstart":case"touchmove":case"touchend":case"touchcancel":this._activeTouchCount=N.touches?N.touches.length:0;break;case"blur":this._mouseBeingPressed=!1,this._activeTouchCount=0}}_isPointerDown(){return this._mouseBeingPressed||this._activeTouchCount>0}handleEvent(N,E){this._updatePointerLiveness(N),this._updatingCamera=!0;const z=N.type==="renderFrame",W=z?void 0:N,Z={needsRenderFrame:!1},ne={},de={},ye=N.touches?this._getMapTouches(N.touches):void 0,Ce=ye?P(this._el,ye):z?void 0:I(this._el,N);for(const{handlerName:Ze,handler:mt,allowed:vt}of this._handlers){if(!mt.isEnabled())continue;let bt;this._blockedByActive(de,vt,Ze)?mt.reset():mt[E||N.type]&&(bt=mt[E||N.type](N,Ce,ye),this.mergeHandlerResult(Z,ne,bt,Ze,W),bt&&bt.needsRenderFrame&&this._triggerRenderFrame()),(bt||mt.isActive())&&(de[Ze]=mt)}const Pe={};for(const Ze in this._previousActiveHandlers)de[Ze]||(Pe[Ze]=W);this._previousActiveHandlers=de,(Object.keys(Pe).length||rN(Z))&&(this._changes.push([Z,ne,Pe]),this._triggerRenderFrame()),(Object.keys(de).length||rN(Z))&&this._map._stop({keepGesture:"always"}),this._updatingCamera=!1;const{cameraAnimation:Ke}=Z;Ke&&(this._inertia.clear(),this._fireEvents({},{},!0),this._changes=[],Ke(this._map))}mergeHandlerResult(N,E,z,W,Z){if(!z)return;Object.assign(N,z);const ne={handlerName:W,originalEvent:z.originalEvent||Z};z.zoomDelta!==void 0&&(E.zoom=ne),z.panDelta!==void 0&&(E.drag=ne),z.pitchDelta!==void 0&&(E.pitch=ne),z.bearingDelta!==void 0&&(E.rotate=ne)}_applyChanges(){const N={},E={},z={};for(const[W,Z,ne]of this._changes)W.panDelta&&(N.panDelta=(N.panDelta||new o.P(0,0))._add(W.panDelta)),W.zoomDelta&&(N.zoomDelta=(N.zoomDelta||0)+W.zoomDelta),W.bearingDelta&&(N.bearingDelta=(N.bearingDelta||0)+W.bearingDelta),W.pitchDelta&&(N.pitchDelta=(N.pitchDelta||0)+W.pitchDelta),W.around!==void 0&&(N.around=W.around),W.aroundCoord!==void 0&&(N.aroundCoord=W.aroundCoord),W.pinchAround!==void 0&&(N.pinchAround=W.pinchAround),W.noInertia&&(N.noInertia=W.noInertia),Object.assign(E,Z),Object.assign(z,ne);this._updateMapTransform(N,E,z),this._changes=[]}_updateMapTransform(N,E,z){const W=this._map,Z=W.transform,ne=Gt=>[Gt.x,Gt.y,Gt.z];if((()=>{const Gt=this._eventsInProgress.drag;return Gt&&!this._handlersById[Gt.handlerName].isActive()})()&&!rN(N)){const Gt=Z.zoom;Z.cameraElevationReference="sea",this._originalZoom!=null&&Z._orthographicProjectionAtLowPitch&&Z.projection.name!=="globe"&&Z.pitch===0?(Z.cameraElevationReference="ground",Z.zoom=this._originalZoom):(Z.recenterOnTerrain(),Z.cameraElevationReference="ground"),Gt!==Z.zoom&&this._map._update(!0)}if(Z._isCameraConstrained&&W._stop({keepGesture:"always"}),!rN(N))return void this._fireEvents(E,z,!0);let{panDelta:de,zoomDelta:ye,bearingDelta:Ce,pitchDelta:Pe,around:Ke,aroundCoord:Ze,pinchAround:mt}=N;Z._isCameraConstrained&&(ye>0&&(ye=0),Z._isCameraConstrained=!1),mt!==void 0&&(Ke=mt),(ye||(Gt=>E[Gt]&&!this._eventsInProgress[Gt])("drag"))&&Ke&&(this._dragOrigin=ne(Z.pointCoordinate3D(Ke)),this._originalZoom=Z.zoom,this._trackingEllipsoid.setup(Z._camera.position,this._dragOrigin)),Z.cameraElevationReference="sea",W._stop({keepGesture:"always"}),Ke=Ke||W.transform.centerPoint,Ce&&(Z.bearing+=Ce),Pe&&(Z.pitch+=Pe),Z._updateCameraState();const vt=[0,0,0];if(de)if(Z.projection.name==="mercator"){const Gt=this._trackingEllipsoid.projectRay(Z.screenPointToMercatorRay(Ke).dir),as=this._trackingEllipsoid.projectRay(Z.screenPointToMercatorRay(Ke.sub(de)).dir);vt[0]=as[0]-Gt[0],vt[1]=as[1]-Gt[1]}else{const Gt=Z.pointCoordinate(Ke);if(Z.projection.name==="globe"){de=de.rotate(-Z.angle);const as=Z._pixelsPerMercatorPixel/Z.worldSize;vt[0]=-de.x*o.ez(o.br(Gt.y))*as,vt[1]=-de.y*o.ez(Z.center.lat)*as}else{const as=Z.pointCoordinate(Ke.sub(de));Gt&&as&&(vt[0]=as.x-Gt.x,vt[1]=as.y-Gt.y)}}const bt=Z.zoom,St=[0,0,0];if(ye){const Gt=ne(Ze||Z.pointCoordinate3D(Ke)),as={dir:o.c3([],o.c2([],Gt,Z._camera.position))};if(as.dir[2]<0){const ms=Z.zoomDeltaToMovement(Gt,ye);o.dC(St,as.dir,ms)}}const Pt=o.dD(vt,vt,St);Z._translateCameraConstrained(Pt),ye&&Math.abs(Z.zoom-bt)>1e-4&&Z.recenterOnTerrain(),Z.cameraElevationReference="ground",this._map._update(),N.noInertia||this._inertia.record(N),this._fireEvents(E,z,!0)}_fireEvents(N,E,z){const W=a7(this._eventsInProgress),Z=a7(N),ne={};for(const Pe in N){const{originalEvent:Ke}=N[Pe];this._eventsInProgress[Pe]||(ne[`${Pe}start`]=Ke),this._eventsInProgress[Pe]=N[Pe]}!W&&Z&&this._fireEvent("movestart",Z.originalEvent);for(const Pe in ne)this._fireEvent(Pe,ne[Pe]);Z&&this._fireEvent("move",Z.originalEvent);for(const Pe in N){const{originalEvent:Ke}=N[Pe];this._fireEvent(Pe,Ke)}const de={};let ye;for(const Pe in this._eventsInProgress){const{handlerName:Ke,originalEvent:Ze}=this._eventsInProgress[Pe];this._handlersById[Ke].isActive()||(delete this._eventsInProgress[Pe],ye=E[Ke]||Ze,de[`${Pe}end`]=ye)}for(const Pe in de)this._fireEvent(Pe,de[Pe]);const Ce=a7(this._eventsInProgress);if(z&&(W||Z)&&!Ce){this._updatingCamera=!0;const Pe=this._inertia._onMoveEnd(this._map.dragPan._inertiaOptions),Ke=Ze=>Ze!==0&&-this._bearingSnap{this._frameId=void 0,this.handleEvent(new zy("renderFrame",{timeStamp:N})),this._applyChanges()})}_triggerRenderFrame(){this._frameId===void 0&&(this._frameId=this._requestFrame())}}const Gk="map.setFreeCameraOptions(...) and map.getFreeCameraOptions() are not yet supported for non-mercator projections.";class F6 extends o.E{constructor(N,E){super(),this._moving=!1,this._zooming=!1,this.transform=N,this._bearingSnap=E.bearingSnap,this._respectPrefersReducedMotion=E.respectPrefersReducedMotion!==!1,o.aV(["_renderFrameCallback"],this)}getCenter(){return new o.cz(this.transform.center.lng,this.transform.center.lat)}setCenter(N,E){return this.jumpTo({center:N},E)}panBy(N,E,z){return N=o.P.convert(N).mult(-1),this.panTo(this.transform.center,{offset:N,...E},z)}panTo(N,E,z){return this.easeTo({center:N,...E},z)}getZoom(){return this.transform.zoom}setZoom(N,E){return this.jumpTo({zoom:N},E),this}zoomTo(N,E,z){return this.easeTo({zoom:N,...E},z)}zoomIn(N,E){return this.zoomTo(this.getZoom()+1,N,E),this}zoomOut(N,E){return this.zoomTo(this.getZoom()-1,N,E),this}getBearing(){return this.transform.bearing}setBearing(N,E){return this.jumpTo({bearing:N},E),this}getPadding(){return this.transform.padding}setPadding(N,E){return this.jumpTo({padding:N},E),this}rotateTo(N,E,z){return this.easeTo({bearing:N,...E},z)}resetNorth(N,E){return this.rotateTo(0,{duration:1e3,...N},E),this}resetNorthPitch(N,E){return this.easeTo({bearing:0,pitch:0,duration:1e3,...N},E),this}snapToNorth(N,E){return Math.abs(this.getBearing())N.aspect?z/(2*Math.tan(.5*N.fovX)*N.aspect):W/(2*Math.tan(.5*N.fovY)*N.aspect)}_cameraForBoundsOnGlobe(N,E,z,W,Z,ne){const de=N.clone(),ye=this._extendCameraOptions(ne);de.bearing=W,de.pitch=Z;const Ce=o.cz.convert(E),Pe=o.cz.convert(z),Ke=.5*(Ce.lat+Pe.lat),Ze=.5*(Ce.lng+Pe.lng),mt=o.eD(Ke,Ze),vt=o.c3([],mt),bt=o.c3([],o.eE([],vt,[0,1,0])),St=o.eE([],bt,vt),Pt=[bt[0],bt[1],bt[2],0,St[0],St[1],St[2],0,vt[0],vt[1],vt[2],0,0,0,0,1],Gt=[mt,o.eD(Ce.lat,Ce.lng),o.eD(Pe.lat,Ce.lng),o.eD(Pe.lat,Pe.lng),o.eD(Ce.lat,Pe.lng),o.eD(Ke,Ce.lng),o.eD(Ke,Pe.lng),o.eD(Ce.lat,Ze),o.eD(Pe.lat,Ze)];let as=o.eF.fromPoints(Gt.map(Qr=>[o.dF(bt,Qr),o.dF(St,Qr),o.dF(vt,Qr)]));const ms=o.bH([],as.center,Pt);o.eG(ms)===0&&o.eH(ms,0,0,1),o.c3(ms,ms),o.dC(ms,ms,o.c8),de.center=o.eI(ms);const Gs=de.getWorldToCameraMatrix(),Ms=o.aO(new Float64Array(16),Gs);as=o.eF.applyTransform(as,o.X([],Gs,Pt));const Js=this._extendAABB(as,de,ye,W);if(!Js)return void o.w("Map cannot fit within canvas with the given bounds, padding, and/or offset.");as=Js,o.bH(ms,ms,Gs);const Os=.5*(as.max[2]-as.min[2]),Ks=this._minimumAABBFrustumDistance(de,as),_n=o.dC([],[0,0,1],Os),ln=o.dD(_n,ms,_n),an=Ks+(de.pitch===0?0:o.eJ(ms,ln)),bn=de.globeCenterInViewSpace,Sn=o.c2([],ms,[bn[0],bn[1],bn[2]]);o.c3(Sn,Sn),o.dC(Sn,Sn,an);const lr=o.dD([],ms,Sn);o.bH(lr,lr,Ms);const Mn=o.bj/o.c8,Hn=o.em(lr),Tr=o.dw(Math.max(Hn*Mn-o.bj,Number.EPSILON),0),oa=Math.min(de.zoomFromMercatorZAdjusted(Tr),ye.maxZoom);return oa>.5*(o.e9+o.b1)?(de.setProjection({name:"mercator"}),de.zoom=oa,this._cameraForBounds(de,E,z,W,Z,ne)):{center:de.center,zoom:oa,bearing:W,pitch:Z}}_extendAABB(N,E,z,W){const Z=.5*((z.padding.left||0)+(z.padding.right||0)),ne=.5*((z.padding.top||0)+(z.padding.bottom||0)),de=ne,ye=Z,Ce=Z,Pe=ne,Ke=E.width-(ye+Ce),Ze=E.height-(de+Pe),mt=o.c2([],N.max,N.min),vt=Math.min(Ke/mt[0],Ze/mt[1]),bt=Math.min(E.scaleZoom(E.scale*vt),z.maxZoom);if(isNaN(bt))return null;const St=E.scale/E.zoomScale(bt),Pt=new o.eF([N.min[0]-ye*St,N.min[1]-Pe*St,N.min[2]],[N.max[0]+Ce*St,N.max[1]+de*St,N.max[2]]),Gt=(typeof z.offset.x=="number"&&typeof z.offset.y=="number"?new o.P(z.offset.x,z.offset.y):o.P.convert(z.offset)).rotate(-o.au(W));return Pt.center[0]-=Gt.x*St,Pt.center[1]+=Gt.y*St,Pt}queryTerrainElevation(N,E){const z=this.transform.elevation;return z?(E={exaggerated:!0,...E},z.getAtPoint(o.bS.fromLngLat(N),null,E.exaggerated)):null}_cameraForBounds(N,E,z,W,Z,ne){if(N.projection.name==="globe")return this._cameraForBoundsOnGlobe(N,E,z,W,Z,ne);const de=N.clone(),ye=this._extendCameraOptions(ne);de.bearing=W,de.pitch=Z;const Ce=o.cz.convert(E),Pe=o.cz.convert(z),Ke=new o.cz(Ce.lng,Pe.lat),Ze=new o.cz(Pe.lng,Ce.lat),mt=de.project(Ce),vt=de.project(Pe),bt=this.queryTerrainElevation(Ce),St=this.queryTerrainElevation(Pe),Pt=this.queryTerrainElevation(Ke),Gt=this.queryTerrainElevation(Ze),as=[[mt.x,mt.y,Math.min(bt||0,St||0,Pt||0,Gt||0)],[vt.x,vt.y,Math.max(bt||0,St||0,Pt||0,Gt||0)]];let ms=o.eF.fromPoints(as);const Gs=de.getWorldToCameraMatrix(),Ms=o.aO(new Float64Array(16),Gs);ms=o.eF.applyTransform(ms,Gs);const Js=this._extendAABB(ms,de,ye,W);if(!Js)return void o.w("Map cannot fit within canvas with the given bounds, padding, and/or offset.");ms=Js;const Os=.5*o.c2([],ms.max,ms.min)[2],Ks=this._minimumAABBFrustumDistance(de,ms),_n=[0,0,1,0];o.c7(_n,_n,Gs),o.eK(_n,_n);const ln=o.dC([],_n,Ks+Os),an=o.dD([],ms.center,ln);o.bH(ms.center,ms.center,Ms),o.bH(an,an,Ms);const bn=de.unproject(new o.P(ms.center[0],ms.center[1])),Sn=o.eL(de.projection,bn),lr=Math.pow(2,Sn),Mn=Math.min(de._zoomFromMercatorZ(an[2]*de.pixelsPerMeter*lr/de.worldSize),ye.maxZoom);return de.mercatorFromTransition&&Mn<.5*(o.e9+o.b1)?(de.setProjection({name:"globe"}),de.zoom=Mn,this._cameraForBounds(de,E,z,W,Z,ne)):{center:bn,zoom:Mn,bearing:W,pitch:Z}}fitBounds(N,E,z){const W=this.cameraForBounds(N,E);return this._fitInternal(W,E,z)}fitScreenCoordinates(N,E,z,W,Z){const ne=o.P.convert(N),de=o.P.convert(E),ye=new o.P(Math.min(ne.x,de.x),Math.min(ne.y,de.y)),Ce=new o.P(Math.max(ne.x,de.x),Math.max(ne.y,de.y));if(this.transform.projection.name==="mercator"&&this.transform.anyCornerOffEdge(ne,de))return this;const Pe=this.transform.pointLocation3D(ye),Ke=this.transform.pointLocation3D(Ce),Ze=this.transform.pointLocation3D(new o.P(ye.x,Ce.y)),mt=this.transform.pointLocation3D(new o.P(Ce.x,ye.y)),vt=[Math.min(Pe.lng,Ke.lng,Ze.lng,mt.lng),Math.min(Pe.lat,Ke.lat,Ze.lat,mt.lat)],bt=[Math.max(Pe.lng,Ke.lng,Ze.lng,mt.lng),Math.max(Pe.lat,Ke.lat,Ze.lat,mt.lat)],St=W&&W.pitch?W.pitch:this.getPitch(),Pt=this._cameraForBounds(this.transform,vt,bt,z,St,W);return this._fitInternal(Pt,W,Z)}_fitInternal(N,E,z){return N?(E=Object.assign(N,E)).linear?this.easeTo(E,z):this.flyTo(E,z):this}jumpTo(N,E){this._stop({keepGesture:"ifPointerDown"});const z=N.preloadOnly?this.transform.clone():this.transform;let W=!1,Z=!1,ne=!1;"zoom"in N&&z.zoom!==+N.zoom&&(W=!0,z.zoom=+N.zoom),N.center!==void 0&&(z.center=o.cz.convert(N.center)),"bearing"in N&&z.bearing!==+N.bearing&&(Z=!0,z.bearing=+N.bearing),"pitch"in N&&z.pitch!==+N.pitch&&(ne=!0,z.pitch=+N.pitch),"fov"in N&&(z.fov=+N.fov);const de=typeof N.padding=="number"?this._extendPadding(N.padding):N.padding;if(N.padding!=null&&!z.isPaddingEqual(de))if(N.retainPadding===!1){const ye=z.clone();ye.padding=de,z.setLocationAtPoint(z.center,ye.centerPoint)}else z.padding=de;return N.preloadOnly?(this._preloadTiles(z),this):(this.fire(new o.h("movestart",E)).fire(new o.h("move",E)),W&&this.fire(new o.h("zoomstart",E)).fire(new o.h("zoom",E)).fire(new o.h("zoomend",E)),Z&&this.fire(new o.h("rotatestart",E)).fire(new o.h("rotate",E)).fire(new o.h("rotateend",E)),ne&&this.fire(new o.h("pitchstart",E)).fire(new o.h("pitch",E)).fire(new o.h("pitchend",E)),this.fire(new o.h("moveend",E)))}getFreeCameraOptions(){return this.transform.projection.supportsFreeCamera||o.w(Gk),this.transform.getFreeCameraOptions()}setFreeCameraOptions(N,E){const z=this.transform;if(!z.projection.supportsFreeCamera)return o.w(Gk),this;this.stop();const W=z.zoom,Z=z.pitch,ne=z.bearing;z.setFreeCameraOptions(N);const de=W!==z.zoom,ye=Z!==z.pitch,Ce=ne!==z.bearing;return this.fire(new o.h("movestart",E)).fire(new o.h("move",E)),de&&this.fire(new o.h("zoomstart",E)).fire(new o.h("zoom",E)).fire(new o.h("zoomend",E)),Ce&&this.fire(new o.h("rotatestart",E)).fire(new o.h("rotate",E)).fire(new o.h("rotateend",E)),ye&&this.fire(new o.h("pitchstart",E)).fire(new o.h("pitch",E)).fire(new o.h("pitchend",E)),this.fire(new o.h("moveend",E)),this}easeTo(N,E){this._stop({easeId:N.easeId}),((N={offset:[0,0],duration:500,easing:o.ey,...N}).animate===!1||this._prefersReducedMotion(N))&&(N.duration=0);const z=this.transform,W=this.getZoom(),Z=this.getBearing(),ne=this.getPitch(),de=this.getPadding(),ye=this.getVerticalFieldOfView(),Ce="zoom"in N?+N.zoom:W,Pe="bearing"in N?this._normalizeBearing(N.bearing,Z):Z,Ke="pitch"in N?+N.pitch:ne,Ze="fov"in N?+N.fov:ye,mt=this._extendPadding(N.padding),vt=o.P.convert(N.offset);let bt,St,Pt;if(z.projection.name==="globe"){const bn=o.bS.fromLngLat(z.center),Sn=vt.rotate(-z.angle);bn.x+=Sn.x/z.worldSize,bn.y+=Sn.y/z.worldSize;const lr=bn.toLngLat(),Mn=o.cz.convert(N.center||lr);this._normalizeCenter(Mn),bt=z.centerPoint.add(Sn),St=new o.P(bn.x,bn.y).mult(z.worldSize),Pt=new o.P(o.a7(Mn.lng),o.a8(Mn.lat)).mult(z.worldSize).sub(St)}else{bt=z.centerPoint.add(vt);const bn=z.pointLocation(bt),Sn=o.cz.convert(N.center||bn);this._normalizeCenter(Sn),St=z.project(bn),Pt=z.project(Sn).sub(St)}const Gt=z.zoomScale(Ce-W);let as,ms;N.around&&(as=o.cz.convert(N.around),ms=z.locationPoint(as));const Gs=this._zooming||Ce!==W,Ms=this._rotating||Z!==Pe,Js=this._pitching||Ke!==ne,Os=Ze!==ye,Ks=!z.isPaddingEqual(mt),_n=N.retainPadding===!1?z.clone():z,ln=bn=>Sn=>{if(Gs&&(bn.zoom=o.al(W,Ce,Sn)),Ms&&(bn.bearing=o.al(Z,Pe,Sn)),Js&&(bn.pitch=o.al(ne,Ke,Sn)),Os&&(bn.fov=o.al(ye,Ze,Sn)),Ks&&(_n.interpolatePadding(de,mt,Sn),bt=_n.centerPoint.add(vt)),as)bn.setLocationAtPoint(as,ms);else{const lr=bn.zoomScale(bn.zoom-W),Mn=Ce>W?Math.min(2,Gt):Math.max(.5,Gt),Hn=Math.pow(Mn,1-Sn),Tr=bn.unproject(St.add(Pt.mult(Sn*Hn)).mult(lr));bn.setLocationAtPoint(bn.renderWorldCopies?Tr.wrap():Tr,bt)}return N.preloadOnly||this._fireMoveEvents(E),bn};if(N.preloadOnly){const bn=this._emulate(ln,N.duration,z);return this._preloadTiles(bn),this}const an={moving:this._moving,zooming:this._zooming,rotating:this._rotating,pitching:this._pitching};return this._zooming=Gs,this._rotating=Ms,this._pitching=Js,this._padding=Ks,this._easeId=N.easeId,this._prepareEase(E,N.noMoveStart,an),this._ease(ln(z),bn=>{z.cameraElevationReference==="sea"&&z.recenterOnTerrain(),this._afterEase(E,bn)},N),this}_prepareEase(N,E,z={}){this._moving=!0,this.transform.cameraElevationReference="sea",this.transform._orthographicProjectionAtLowPitch&&this.transform.pitch===0&&this.transform.projection.name!=="globe"&&(this.transform.cameraElevationReference="ground"),E||z.moving||this.fire(new o.h("movestart",N)),this._zooming&&!z.zooming&&this.fire(new o.h("zoomstart",N)),this._rotating&&!z.rotating&&this.fire(new o.h("rotatestart",N)),this._pitching&&!z.pitching&&this.fire(new o.h("pitchstart",N))}_fireMoveEvents(N){this.fire(new o.h("move",N)),this._zooming&&this.fire(new o.h("zoom",N)),this._rotating&&this.fire(new o.h("rotate",N)),this._pitching&&this.fire(new o.h("pitch",N))}_afterEase(N,E){if(this._easeId&&E&&this._easeId===E)return;this._easeId=void 0,this.transform.cameraElevationReference="ground";const z=this._zooming,W=this._rotating,Z=this._pitching;this._moving=!1,this._zooming=!1,this._rotating=!1,this._pitching=!1,this._padding=!1,z&&this.fire(new o.h("zoomend",N)),W&&this.fire(new o.h("rotateend",N)),Z&&this.fire(new o.h("pitchend",N)),this.fire(new o.h("moveend",N))}flyTo(N,E){if(this._prefersReducedMotion(N)){const Nr=o.cb(N,["center","zoom","bearing","pitch","fov","around","padding","retainPadding"]);return this.jumpTo(Nr,E)}this.stop(),N={offset:[0,0],speed:1.2,curve:1.42,easing:o.ey,...N};const z=this.transform,W=this.getZoom(),Z=this.getBearing(),ne=this.getPitch(),de=this.getPadding(),ye=this.getVerticalFieldOfView(),Ce="zoom"in N?o.b0(+N.zoom,z.minZoom,z.maxZoom):W,Pe="bearing"in N?this._normalizeBearing(N.bearing,Z):Z,Ke="pitch"in N?+N.pitch:ne,Ze="fov"in N?+N.fov:ye,mt=Ze!==ye,vt=this._extendPadding(N.padding),bt=z.zoomScale(Ce-W),St=o.P.convert(N.offset);let Pt=z.centerPoint.add(St);const Gt=z.pointLocation(Pt),as=o.cz.convert(N.center||Gt);this._normalizeCenter(as);const ms=z.project(Gt),Gs=z.project(as).sub(ms);let Ms=N.curve;const Js=Math.max(z.width,z.height),Os=Js/bt,Ks=Gs.mag();if("minZoom"in N){const Nr=o.b0(Math.min(N.minZoom,W,Ce),z.minZoom,z.maxZoom),cr=Js/z.zoomScale(Nr-W);Ms=Math.sqrt(cr/Ks*2)}const _n=Ms*Ms;function ln(Nr){const cr=(Os*Os-Js*Js+(Nr?-1:1)*_n*_n*Ks*Ks)/(2*(Nr?Os:Js)*_n*Ks);return Math.log(Math.sqrt(cr*cr+1)-cr)}function an(Nr){return(Math.exp(Nr)-Math.exp(-Nr))/2}function bn(Nr){return(Math.exp(Nr)+Math.exp(-Nr))/2}const Sn=ln(0);let lr=function(Nr){return bn(Sn)/bn(Sn+Ms*Nr)},Mn=function(Nr){return Js*((bn(Sn)*(an(cr=Sn+Ms*Nr)/bn(cr))-an(Sn))/_n)/Ks;var cr},Hn=(ln(1)-Sn)/Ms;if(Math.abs(Ks)<1e-6||!isFinite(Hn)){if(Math.abs(Js-Os)<1e-6)return this.easeTo(N,E);const Nr=OsN.maxDuration&&(N.duration=0);const Tr=Z!==Pe,oa=Ke!==ne,Qr=!z.isPaddingEqual(vt),Lr=N.retainPadding===!1?z.clone():z,qa=Nr=>cr=>{const Fr=cr*Hn,Fa=1/lr(Fr);Nr.zoom=cr===1?Ce:W+Nr.scaleZoom(Fa),Tr&&(Nr.bearing=o.al(Z,Pe,cr)),oa&&(Nr.pitch=o.al(ne,Ke,cr)),mt&&(Nr.fov=o.al(ye,Ze,cr)),Qr&&(Lr.interpolatePadding(de,vt,cr),Pt=Lr.centerPoint.add(St));const ta=cr===1?as:Nr.unproject(ms.add(Gs.mult(Mn(Fr))).mult(Fa));return Nr.setLocationAtPoint(Nr.renderWorldCopies?ta.wrap():ta,Pt),Nr._updateCameraOnTerrain(),N.preloadOnly||this._fireMoveEvents(E),Nr};if(N.preloadOnly){const Nr=this._emulate(qa,N.duration,z);return this._preloadTiles(Nr),this}return this._zooming=!0,this._rotating=Tr,this._pitching=oa,this._padding=Qr,this._prepareEase(E,!1),this._ease(qa(z),()=>this._afterEase(E),N),this}isEasing(){return!!this._easeFrameId}stop(){return this._stop()}_requestRenderFrame(N){}_cancelRenderFrame(N){}_stop({easeId:N,keepGesture:E}={}){if(this._easeFrameId&&(this._cancelRenderFrame(this._easeFrameId),this._easeFrameId=void 0,this._onEaseFrame=void 0),this._onEaseEnd){const W=this._onEaseEnd;this._onEaseEnd=void 0,W.call(this,N)}const z=this.handlers;return z&&z.stop(E),this}_ease(N,E,z){z.animate===!1||z.duration===0?(N(1),E()):(this._easeStart=o.e.now(),this._easeOptions=z,this._onEaseFrame=N,this._onEaseEnd=E,this._easeFrameId=this._requestRenderFrame(this._renderFrameCallback))}_renderFrameCallback(){const N=Math.min((o.e.now()-this._easeStart)/this._easeOptions.duration,1),E=this._onEaseFrame;E&&E(this._easeOptions.easing(N)),N<1?this._easeFrameId=this._requestRenderFrame(this._renderFrameCallback):this.stop()}_normalizeBearing(N,E){N=o.cU(N,-180,180);const z=Math.abs(N-E);return Math.abs(N-360-E)180?-360:z<-180?360:0}_prefersReducedMotion(N){return this._respectPrefersReducedMotion&&o.e.prefersReducedMotion&&!(N&&N.essential)}_emulate(N,E,z){const W=Math.ceil(15*E/1e3),Z=[],ne=N(z.clone());for(let de=0;de<=W;de++){const ye=ne(de/W);Z.push(ye.clone())}return Z}_preloadTiles(N,E){}}const dMe=/^(https?:|mailto:)/i;class Fte{constructor(N={}){this.options=N,o.aV(["_toggleAttribution","_updateEditLink","_updateData","_updateCompact"],this)}getDefaultPosition(){return"bottom-right"}onAdd(N){const E=this.options&&this.options.compact,z=N._getUIString("AttributionControl.ToggleAttribution");this._map=N,this._container=g("div","mapboxgl-ctrl mapboxgl-ctrl-attrib"),this._compactButton=g("button","mapboxgl-ctrl-attrib-button",this._container),this._compactButton.type="button",this._compactButton.addEventListener("click",this._toggleAttribution),this._compactButton.setAttribute("aria-label",z);const W=g("span","mapboxgl-ctrl-icon",this._compactButton);return W.setAttribute("aria-hidden","true"),W.setAttribute("title",z),this._innerContainer=g("div","mapboxgl-ctrl-attrib-inner",this._container),E&&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),E===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 N=this._editLink;N||(N=this._editLink=this._container.querySelector(".mapbox-improve-map"));const E=[{key:"owner",value:this.styleOwner},{key:"id",value:this.styleId},{key:"access_token",value:this._map._requestManager._customAccessToken||o.eM.ACCESS_TOKEN}];if(N){const z=E.reduce((W,Z,ne)=>(Z.value&&(W+=`${Z.key}=${Z.value}${neW.length-Z.length),N=N.filter((W,Z)=>{for(let ne=Z+1;nefunction(Z){const ne=new DOMParser().parseFromString(Z,"text/html");return Array.from(ne.body.querySelectorAll("*")).reverse().forEach(de=>{const ye=de.textContent||"";if(de.tagName!=="A")return void de.replaceWith(...de.childNodes);const Ce=de.getAttribute("href");if(!Ce||!dMe.test(Ce))return void de.replaceWith(ne.createTextNode(ye));const Pe=ne.createElement("a");Pe.href=Ce,Pe.textContent=ye,Pe.rel="noopener nofollow";const Ke=de.getAttribute("class");Ke&&(Pe.className=Ke),de.replaceWith(Pe)}),ne.body.innerHTML}(W)).join(" | ");z!==this._attribHTML&&(this._attribHTML=z,N.length?(this._innerContainer.innerHTML=z,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 zte{constructor(){o.aV(["_updateLogo","_updateCompact"],this)}onAdd(N){this._map=N,this._container=g("div","mapboxgl-ctrl");const E=g("a","mapboxgl-ctrl-logo");return E.target="_blank",E.rel="noopener nofollow",E.href="https://www.mapbox.com/",E.setAttribute("aria-label",this._map._getUIString("LogoControl.Title")),E.setAttribute("rel","noopener nofollow"),this._container.appendChild(E),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(N){N&&N.sourceDataType!=="metadata"||(this._container.style.display=this._logoRequired()?"block":"none")}_logoRequired(){if(!this._map.style)return!0;const N=this._map.style._sourceCaches;if(Object.entries(N).length===0)return!0;for(const E in N){const z=N[E].getSource();if(Object.hasOwn(z,"mapbox_logo")&&!z.mapbox_logo)return!1}return!0}_updateCompact(){const N=this._container.children;if(N.length){const E=N[0];this._map.getCanvasContainer().offsetWidth<250?E.classList.add("mapboxgl-compact"):E.classList.remove("mapboxgl-compact")}}}class Bte{constructor(){this._queue=[],this._id=0,this._cleared=!1,this._currentlyRunning=!1}add(N){const E=++this._id;return this._queue.push({callback:N,id:E,cancelled:!1}),E}remove(N){const E=this._currentlyRunning,z=E?this._queue.concat(E):this._queue;for(const W of z)if(W.id===N)return void(W.cancelled=!0)}run(N=0){const E=this._currentlyRunning=this._queue;this._queue=[];for(const z of E)if(!z.cancelled&&(z.callback(N),this._cleared))break;this._cleared=!1,this._currentlyRunning=!1}clear(){this._currentlyRunning&&(this._cleared=!0),this._queue=[]}}class uMe{constructor(N){this.jumpTo(N)}getValue(N){if(N<=this._startTime)return this._start;if(N>=this._endTime)return this._end;const E=o.ds((N-this._startTime)/(this._endTime-this._startTime));return this._start*(1-E)+this._end*E}isEasing(N){return N>=this._startTime&&N<=this._endTime}jumpTo(N){this._startTime=-1/0,this._endTime=-1/0,this._start=N,this._end=N}easeTo(N,E,z){this._start=this.getValue(E),this._end=N,this._startTime=E,this._endTime=E+z}}const hMe={"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 $te extends o.h{constructor(N,E,z,W){const{point:Z,lngLat:ne,originalEvent:de,target:ye}=N;super(N.type,{point:Z,lngLat:ne,originalEvent:de,target:ye}),this.preventDefault=()=>{N.preventDefault()},this.id=E,this.interaction=z,this.feature=W}}class tH{constructor(N){this.map=N,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(N,E){if(this.typeById.has(N))throw new Error(`Interaction id "${N}" already exists.`);const z=E.filter;let W=E.type;z&&this.filters.set(N,o.bv(z)),W==="mouseover"&&(W="mouseenter"),W==="mouseout"&&(W="mouseleave");const Z=this.interactionsByType.get(W)||new Map;W==="mouseenter"||W==="mouseleave"?(this.delegatedInteractions.size===0&&(this.map.on("mousemove",this.handleMove),this.map.on("mouseout",this.handleOut)),this.delegatedInteractions.set(N,E)):Z.size===0&&this.map.on(W,this.handleType),Z.size===0&&this.interactionsByType.set(W,Z),Z.set(N,E),this.typeById.set(N,W)}get(N){const E=this.typeById.get(N);if(!E)return;const z=this.interactionsByType.get(E);return z?z.get(N):void 0}remove(N){const E=this.typeById.get(N);if(!E)return;this.typeById.delete(N),this.filters.delete(N);const z=this.interactionsByType.get(E);z&&(z.delete(N),E==="mouseenter"||E==="mouseleave"?(this.delegatedInteractions.delete(N),this.delegatedInteractions.size===0&&(this.map.off("mousemove",this.handleMove),this.map.off("mouseout",this.handleOut))):z.size===0&&this.map.off(E,this.handleType))}queryTargets(N,E){const z=[];for(const[W,Z]of E)Z.target&&z.push({targetId:W,target:Z.target,filter:this.filters.get(W)});return this.map.style.queryRenderedTargets(N,z,this.map.transform)}handleMove(N){this.prevHoveredFeatures=this.hoveredFeatures,this.hoveredFeatures=new Map;const E=this.queryTargets(N.point,Array.from(this.delegatedInteractions).reverse());E.length&&(N.type="mouseenter",this.handleType(N,E));const z=new Map;for(const[W,{feature:Z}]of this.prevHoveredFeatures)this.hoveredFeatures.has(W)||z.set(Z.id,Z);z.size&&(N.type="mouseleave",this.handleType(N,Array.from(z.values())))}handleOut(N){const E=Array.from(this.hoveredFeatures.values()).map(({feature:z})=>z);E.length&&(N.type="mouseleave",this.handleType(N,E)),this.hoveredFeatures.clear()}handleType(N,E){const z=N.type==="mouseenter";if(z&&!this.interactionsByType.has(N.type))return void o.w("mouseenter interaction required for mouseleave to work.");const W=Array.from(this.interactionsByType.get(N.type)).reverse(),Z=!!E;E=E||this.queryTargets(N.point,W);let ne=!1;const de=new Set;for(const ye of E){for(const[Ce,Pe]of W){if(!Pe.target)continue;const Ke=ye.variants?ye.variants[Ce]:null;if(Ke){for(const Ze of Ke){if(g4(Ze,ye,de,Ce))continue;const mt=new o.dl(ye,Ze),vt=X2(Ze,ye,Ce);Z&&mt.id!==void 0&&(mt.state=this.map.getFeatureState(mt));const bt=z?this.prevHoveredFeatures.get(vt):null,St=new $te(N,Ce,Pe,mt),Pt=bt?bt.stop:Pe.handler(St);if(z&&this.hoveredFeatures.set(vt,{feature:ye,stop:Pt}),Pt!==!1){ne=!0;break}}if(ne)break}}if(ne)break}if(!ne)for(const[ye,Ce]of W){const{handler:Pe,target:Ke}=Ce;if(!Ke&&Pe(new $te(N,ye,Ce,null))!==!1)break}}}function mMe(L,N){if(Array.isArray(L)&&Array.isArray(N)){const E=new Set(L),z=new Set(N);return E.size===z.size&&L.every(W=>z.has(W))}return o.O(L,N)}const Ute=/matrix.*\((.+)\)/,z6={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},fMe={showCompass:!0,showZoom:!0,visualizePitch:!1};class rf{constructor(N,E,z=!1){this._clickTolerance=10,this.element=E,this.mouseRotate=new XV({clickTolerance:N.dragRotate._mouseRotate._clickTolerance}),this.map=N,z&&(this.mousePitch=new I6({clickTolerance:N.dragRotate._mousePitch._clickTolerance})),o.aV(["mousedown","mousemove","mouseup","touchstart","touchmove","touchend","reset"],this),E.addEventListener("mousedown",this.mousedown),E.addEventListener("touchstart",this.touchstart,{passive:!1}),E.addEventListener("touchmove",this.touchmove),E.addEventListener("touchend",this.touchend),E.addEventListener("touchcancel",this.reset)}down(N,E){this.mouseRotate.mousedown(N,E),this.mousePitch&&this.mousePitch.mousedown(N,E),j()}move(N,E){const z=this.map,W=this.mouseRotate.mousemoveWindow(N,E),Z=W&&W.bearingDelta;if(Z&&z.setBearing(z.getBearing()+Z),this.mousePitch){const ne=this.mousePitch.mousemoveWindow(N,E),de=ne&&ne.pitchDelta;de&&z.setPitch(z.getPitch()+de)}}off(){const N=this.element;N.removeEventListener("mousedown",this.mousedown),N.removeEventListener("touchstart",this.touchstart),N.removeEventListener("touchmove",this.touchmove),N.removeEventListener("touchend",this.touchend),N.removeEventListener("touchcancel",this.reset),this.offTemp()}offTemp(){C(),window.removeEventListener("mousemove",this.mousemove),window.removeEventListener("mouseup",this.mouseup)}mousedown(N){this.down({...N,button:N.button,type:N.type,ctrlKey:!0,preventDefault:()=>N.preventDefault()},I(this.element,N)),window.addEventListener("mousemove",this.mousemove),window.addEventListener("mouseup",this.mouseup)}mousemove(N){this.move(N,I(this.element,N))}mouseup(N){this.mouseRotate.mouseupWindow(N),this.mousePitch&&this.mousePitch.mouseupWindow(N),this.offTemp()}touchstart(N){N.targetTouches.length!==1?this.reset():(this._startPos=this._lastPos=P(this.element,N.targetTouches)[0],this.down({type:"mousedown",button:0,ctrlKey:!0,preventDefault:()=>N.preventDefault()},this._startPos))}touchmove(N){N.targetTouches.length!==1?this.reset():(this._lastPos=P(this.element,N.targetTouches)[0],this.move({buttons:1,preventDefault:()=>N.preventDefault()},this._lastPos))}touchend(N){N.targetTouches.length===0&&this._startPos&&this._lastPos&&this._startPos.dist(this._lastPos)E.width||N.y>E.height;E.locationPoint3D(z).distSqr(N)180;){const z=E.locationPoint3D(L);if(z.x>=0&&z.y>=0&&z.x<=E.width&&z.y<=E.height)break;L.lng>E.center.lng?L.lng-=360:L.lng+=360}return L}const o7={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%)"},l7=/\s+/,O1={rotation:0,rotationAlignment:"auto",pitchAlignment:"auto",occludedOpacity:.2,altitude:0};class E4 extends o.E{constructor(N,E){super(),(N instanceof HTMLElement||E)&&(N={element:N,...E}),o.aV(["_update","_onMove","_onUp","_addDragHandler","_onMapClick","_onKeyPress","_clearFadeTimer"],this);const{anchor:z="center",color:W="#3FB1CE",scale:Z=1,draggable:ne=!1,clickTolerance:de=0,rotation:ye=O1.rotation,rotationAlignment:Ce=O1.rotationAlignment,pitchAlignment:Pe=O1.pitchAlignment,occludedOpacity:Ke=O1.occludedOpacity,altitude:Ze=O1.altitude}=N||{};this._anchor=z,this._color=W,this._scale=Z,this._draggable=ne,this._clickTolerance=de,this._rotation=ye,this._rotationAlignment=Ce,this._pitchAlignment=Pe,this._occludedOpacity=Ke,this._altitude=Ze,this._state="inactive",this._isDragging=!1,this._pointerEvents=null,this._updateMoving=()=>this._update(!0),N&&N.element?(this._element=N.element,this._offset=o.P.convert(N&&N.offset||[0,0])):(this._defaultMarker=!0,this._element=this._createDefaultMarker(),this._offset=o.P.convert(N&&N.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",vt=>{vt.preventDefault()}),this._element.addEventListener("mousedown",vt=>{vt.preventDefault()});const mt=this._element.classList;for(const vt in o7)mt.remove(`mapboxgl-marker-anchor-${vt}`);mt.add(`mapboxgl-marker-anchor-${this._anchor}`),N&&N.className&&mt.add(...N.className.trim().split(l7)),this._popup=null}_createDefaultMarker(){const N=g("div"),E=x("svg",{display:"block",height:41*this._scale+"px",width:27*this._scale+"px",viewBox:"0 0 27 41"},N);this._svgElement=E;const z=x("radialGradient",{id:"shadowGradient"},x("defs",{},E));x("stop",{offset:"10%","stop-opacity":.4},z),x("stop",{offset:"100%","stop-opacity":.05},z);const W=x("ellipse",{cx:13.5,cy:34.8,rx:10.5,ry:5.25,fill:"url(#shadowGradient)"});return this._shadowElement=W,this._altitude===0&&E.insertBefore(W,E.firstChild),x("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"},E),x("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"},E),x("circle",{fill:"white",cx:13.5,cy:13.5,r:5.5},E),N}addTo(N){return N===this._map||(this.remove(),this._map=N,N.getCanvasContainer().appendChild(this._element),N.on("move",this._updateMoving),N.on("moveend",this._update),N.on("remove",this._clearFadeTimer),N._addMarker(this),this.setDraggable(this._draggable),this._update(),N.on("click",this._onMapClick)),this}remove(){const N=this._map;return N&&(N.off("click",this._onMapClick),N.off("move",this._updateMoving),N.off("moveend",this._update),N.off("mousedown",this._addDragHandler),N.off("touchstart",this._addDragHandler),N.off("mouseup",this._onUp),N.off("touchend",this._onUp),N.off("mousemove",this._onMove),N.off("touchmove",this._onMove),N.off("remove",this._clearFadeTimer),N._removeMarker(this),this._map=void 0),this._clearFadeTimer(),this._element.remove(),this._popup&&this._popup.remove(),this}getLngLat(){return this._lngLat}setLngLat(N){return this._lngLat=o.cz.convert(N),this._pos=null,this._popup&&this._popup.setLngLat(this._lngLat),this._update(!0),this}setAltitude(N){if(N===this._altitude)return this;const E=this._altitude;return this._altitude=N||O1.altitude,this._defaultMarker&&E===0!=(this._altitude===0)&&(this._altitude===0?this._svgElement.insertBefore(this._shadowElement,this._svgElement.firstChild):this._shadowElement.remove()),this._update(),this}getAltitude(){return this._altitude}getElement(){return this._element}setPopup(N){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")),N){if(!("offset"in N.options)){const W=Math.sqrt(Math.pow(13.5,2)/2);N.options.offset=this._defaultMarker?{top:[0,0],"top-left":[0,0],"top-right":[0,0],bottom:[0,-38.1],"bottom-left":[W,-1*(38.1-13.5+W)],"bottom-right":[-W,-1*(38.1-13.5+W)],left:[13.5,-1*(38.1-13.5)],right:[-13.5,-1*(38.1-13.5)]}:this._offset}this._popup=N,N._marker=this,N._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(N){const E=N.code,z=N.charCode||N.keyCode;E!=="Space"&&E!=="Enter"&&z!==32&&z!==13||this.togglePopup()}_onMapClick(N){const E=N.originalEvent.target,z=this._element;this._popup&&(E===z||z.contains(E))&&this.togglePopup()}getPopup(){return this._popup}togglePopup(){const N=this._popup;return N?(N.isOpen()?(N.remove(),this._element.setAttribute("aria-expanded","false")):this._map&&(N.addTo(this._map),this._element.setAttribute("aria-expanded","true")),this):this}_behindTerrain(){const N=this._map,E=this._pos;if(!N||!E)return!1;const z=N.unproject(E,this._altitude),W=N.getFreeCameraOptions();if(!W.position)return!1;const Z=W.position.toLngLat();return Z.distanceTo(z)<.9*Z.distanceTo(this._lngLat)}_evaluateOpacity(){const N=this._map;if(!N)return;const E=this._pos;if(!E||E.x<0||E.x>N.transform.width||E.y<0||E.y>N.transform.height)return void this._clearFadeTimer();const z=N.unproject(E,this._altitude);let W;N._showingGlobe()&&o.f3(N.transform,this._lngLat)?W=0:(W=1-N._queryFogOpacity(z),N.transform._terrainEnabled()&&N.style&&N.style.hasTerrain()&&this._behindTerrain()&&(W*=this._occludedOpacity)),this._element.style.opacity=`${W}`;const Z=this._element.style.pointerEvents;(this._pointerEvents===null?Z==="":Z===this._pointerEvents)&&(this._pointerEvents=W>0?"auto":"none",this._element.style.pointerEvents=this._pointerEvents),this._popup&&this._popup._setOpacity(W),this._fadeTimer=null}_clearFadeTimer(){this._fadeTimer&&(clearTimeout(this._fadeTimer),this._fadeTimer=null)}_updateDOM(){const N=this._pos;if(!N||!this._map)return;const E=this._offset.mult(this._scale);this._element.style.transform=` translate(${N.x}px,${N.y}px) ${o7[this._anchor]} ${this._calculateXYTransform()} ${this._calculateZTransform()} translate(${E.x}px,${E.y}px) `}_calculateXYTransform(){const N=this._pos,E=this._map,z=this.getPitchAlignment();if(!E||!N||z!=="map")return"";if(!E._showingGlobe()){const ye=E.getPitch();return ye?`rotateX(${ye}deg)`:""}const W=o.f4(o.f5(E.transform,this._lngLat)),Z=N.sub(o.f6(E.transform)),ne=Math.abs(Z.x)+Math.abs(Z.y);if(ne===0)return"";const de=W/ne;return`rotateX(${-Z.y*de}deg) rotateY(${Z.x*de}deg)`}_calculateZTransform(){const N=this._pos,E=this._map;if(!E||!N)return"";let z=0;const W=this.getRotationAlignment();if(W==="map")if(E._showingGlobe()){const Z=E.project(new o.cz(this._lngLat.lng,this._lngLat.lat+.001),this._altitude),ne=E.project(new o.cz(this._lngLat.lng,this._lngLat.lat-.001),this._altitude).sub(Z);z=o.f4(Math.atan2(ne.y,ne.x))-90}else z=-E.getBearing();else if(W==="horizon"){const Z=o.am(4,6,E.getZoom()),ne=o.f6(E.transform);ne.y+=Z*E.transform.height;const de=N.sub(ne),ye=o.f4(Math.atan2(de.y,de.x));z=(ye>90?ye-270:ye+90)*(1-Z)}return z+=this._rotation,z?`rotateZ(${z}deg)`:""}_update(N){cancelAnimationFrame(this._updateFrameId);const E=this._map;E&&(E.transform.renderWorldCopies&&(this._lngLat=A4(this._lngLat,this._pos,E.transform)),this._pos=E.project(this._lngLat,this._altitude),N===!0?this._updateFrameId=requestAnimationFrame(()=>{this._element&&this._pos&&this._anchor&&(this._pos=this._pos.round(),this._updateDOM())}):this._pos=this._pos.round(),E._requestDomTask(()=>{this._map&&(this._element&&this._pos&&this._anchor&&this._updateDOM(),(E._showingGlobe()||E.style&&E.style.hasTerrain()||E.getFog())&&!this._fadeTimer&&(this._fadeTimer=window.setTimeout(this._evaluateOpacity.bind(this),60)))}))}getOffset(){return this._offset}setOffset(N){return this._offset=o.P.convert(N),this._update(),this}addClassName(N){return this._element.classList.add(N),this}removeClassName(N){return this._element.classList.remove(N),this}toggleClassName(N){return this._element.classList.toggle(N)}_onMove(N){const E=this._map;if(!E)return;const z=this._pointerdownPos,W=this._positionDelta;if(z&&W){if(!this._isDragging){const Z=this._clickTolerance||E._clickTolerance;if(N.point.dist(z)`mapboxgl-ctrl-geolocate-${L}`,$6=["waiting","active","active-error","background","background-error"].map(B6),Wk={positionOptions:{enableHighAccuracy:!1,maximumAge:0,timeout:6e3},fitBoundsOptions:{maxZoom:15},trackUserLocation:!1,showAccuracyCircle:!0,showUserLocation:!0,showUserHeading:!1,showButton:!0,followUserLocation:!0},Vte={maxWidth:100,unit:"metric"},sH={kilometer:"km",meter:"m",mile:"mi",foot:"ft","nautical-mile":"nm"},nH=/\s+/,By={closeButton:!0,closeOnClick:!0,focusAfterOpen:!0,className:"",maxWidth:"240px",altitude:0},T4=["a[href]","[tabindex]:not([tabindex='-1'])","[contenteditable]:not([contenteditable='false'])","button:not([disabled])","input:not([disabled])","select:not([disabled])","textarea:not([disabled])"].join(", ");function c7(L=new o.P(0,0),N="bottom"){if(typeof L=="number"){const E=Math.round(Math.sqrt(.5*Math.pow(L,2)));switch(N){case"top":return new o.P(0,L);case"top-left":return new o.P(E,E);case"top-right":return new o.P(-E,E);case"bottom":return new o.P(0,-L);case"bottom-left":return new o.P(E,-E);case"bottom-right":return new o.P(-E,-E);case"left":return new o.P(L,0);case"right":return new o.P(-L,0)}return new o.P(0,0)}return L instanceof o.P||Array.isArray(L)?o.P.convert(L):o.P.convert(L[N]||[0,0])}const Mv=typeof document<"u"?document.currentScript:null;return o.f7(Mv&&Mv.src&&o.f8(Mv.src)?"cdn":"other"),{version:o.f2,supported:function(L){return!function(N){return typeof window<"u"&&typeof document<"u"?Object.hasOwn?function(){const E=document.createElement("canvas");E.width=E.height=1;const z=E.getContext("2d");return!!z&&z.getImageData(0,0,1,1).width===E.width}()?function(E){return E?(u===void 0&&(u=h(!0)),u):(d===void 0&&(d=h(!1)),d)}(N)?"":"insufficient WebGL2 support":"insufficient Canvas/getImageData support":"Object.hasOwn not supported":"not a browser"}(L)},setRTLTextPlugin:o.fd,getRTLTextPluginStatus:o.fc,setSdkInfo:o.fb,addTileProvider:o.fa,Map:class extends F6{constructor(L){o.eN.mark(o.eO.create);const N=L;if((L={...z6,...L}).minZoom!=null&&L.maxZoom!=null&&L.minZoom>L.maxZoom)throw new Error("maxZoom must be greater than or equal to minZoom");if(L.minPitch!=null&&L.maxPitch!=null&&L.minPitch>L.maxPitch)throw new Error("maxPitch must be greater than or equal to minPitch");if(L.minPitch!=null&&L.minPitch<0)throw new Error("minPitch must be greater than or equal to 0");if(L.maxPitch!=null&&L.maxPitch>85)throw new Error("maxPitch must be less than or equal to 85");super(new o.eP(L.minZoom,L.maxZoom,L.minPitch,L.maxPitch,L.renderWorldCopies,null,null),L),this._repaint=!!L.repaint,this._interactive=L.interactive,this._minTileCacheSize=L.minTileCacheSize,this._maxTileCacheSize=L.maxTileCacheSize,this._failIfMajorPerformanceCaveat=L.failIfMajorPerformanceCaveat,this._preserveDrawingBuffer=L.preserveDrawingBuffer,this._antialias=L.antialias,this._trackResize=L.trackResize,this._bearingSnap=L.bearingSnap,this._refreshExpiredTiles=L.refreshExpiredTiles,this._fadeDuration=L.fadeDuration,this._placementAlgorithm=L.placementAlgorithm||"default",this._isInitialLoad=!0,this._crossSourceCollisions=L.crossSourceCollisions,this._collectResourceTiming=L.collectResourceTiming,this._language=this._parseLanguage(L.language),this._worldview=L.worldview,this._renderTaskQueue=new Bte,this._domRenderTaskQueue=new Bte,this._controls=[],this._markers=[],this._popups=[],this._mapId=o.av(),this._locale={...hMe,...L.locale},this._clickTolerance=L.clickTolerance,this._cooperativeGestures=L.cooperativeGestures,this._performanceMetricsCollection=L.performanceMetricsCollection,this._tessellationStep=L.tessellationStep,this._containerWidth=0,this._containerHeight=0,this._showParseStatus=!0,this._precompilePrograms=L.precompilePrograms,this._averageElevationLastSampledAt=-1/0,this._averageElevationExaggeration=0,this._averageElevation=new uMe(0),this._interactionRange=[1/0,-1/0],this._visibilityHidden=0,this._useExplicitProjection=!1,this._frameId=0,this._scaleFactor=L.scaleFactor,this._requestManager=new o.eQ(L.transformRequest,L.accessToken,L.testMode);const E=o.eR(L.accessToken||o.eM.ACCESS_TOKEN);if(E&&"atlas"in E&&typeof E.atlas=="number"&&(this._tokenExpiration=E.atlas),this._silenceAuthErrors=!!L.testMode,this._contextCreateOptions=L.contextCreateOptions?{...L.contextCreateOptions}:{},typeof L.container=="string"){const z=document.getElementById(L.container);if(!z)throw new Error(`Container '${L.container.toString()}' not found.`);this._container=z}else{if(!(L.container instanceof HTMLElement))throw new Error("Invalid type: 'container' must be a String or HTMLElement.");this._container=L.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."),L.maxBounds&&this.setMaxBounds(L.maxBounds),this._spriteFormat="auto",o.aV(["_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 Ote(this,L),this._localFontFamily=L.localFontFamily,this._localIdeographFontFamily=L.localIdeographFontFamily,this._fontstackCompositing=L.fontstackCompositing,(L.style||!L.testMode)&&this.setStyle(L.style||o.eM.DEFAULT_STYLE,{config:L.config,localFontFamily:this._localFontFamily,localIdeographFontFamily:this._localIdeographFontFamily,fontstackCompositing:this._fontstackCompositing}),L.projection&&this.setProjection(L.projection),L.hash&&(this._hash=new It(typeof L.hash=="string"&&L.hash||void 0).addTo(this)),!this._hash||!this._hash._onHashChange()){N.center==null&&N.zoom==null||(this.transform._unmodified=!1),this.jumpTo({center:L.center,zoom:L.zoom,bearing:L.bearing,pitch:L.pitch});const z=L.bounds;z&&(this.resize(),this.fitBounds(z,{...L.fitBoundsOptions,duration:0}))}this.resize(),L.attributionControl&&this.addControl(new Fte({customAttribution:L.customAttribution})),this._logoControl=new zte,this.addControl(this._logoControl,L.logoPosition),this.on("style.load",()=>{this.transform.unmodified&&this.jumpTo(this.style.stylesheet),this._postStyleLoadEvent(),this._postStyleWithAppearanceEvent()}),this.on("data",z=>{this._update(z.dataType==="style"),this.fire(new o.h(`${z.dataType}data`,z))}),this.on("dataloading",z=>{this.fire(new o.h(`${z.dataType}dataloading`,z))}),this._interactions=new tH(this)}_getMapId(){return this._mapId}addControl(L,N){if(N===void 0&&(N=L.getDefaultPosition?L.getDefaultPosition():"top-right"),!L||!L.onAdd)return this.fire(new o.f(new Error("Invalid argument to map.addControl(). Argument must be a control with onAdd and onRemove methods.")));const E=L.onAdd(this);this._controls.push(L);const z=this._controlPositions[N];return N.includes("bottom")?z.insertBefore(E,z.firstChild):z.appendChild(E),this}removeControl(L){if(!L||!L.onRemove)return this.fire(new o.f(new Error("Invalid argument to map.removeControl(). Argument must be a control with onAdd and onRemove methods.")));const N=this._controls.indexOf(L);return N>-1&&this._controls.splice(N,1),L.onRemove(this),this}hasControl(L){return this._controls.includes(L)}getContainer(){return this._container}getCanvasContainer(){return this._canvasContainer}getCanvas(){return this._canvas}resize(L){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 N=!this._moving;return N&&this.fire(new o.h("movestart",L)).fire(new o.h("move",L)),this.fire(new o.h("resize",L)),N&&this.fire(new o.h("moveend",L)),this}getBounds(){return this.transform.getBounds()}getMaxBounds(){return this.transform.getMaxBounds()||null}setMaxBounds(L){return this.transform.setMaxBounds(o.eC.convert(L)),this._update()}setMinZoom(L){if((L=L??-2)>=-2&&L<=this.transform.maxZoom)return this.transform.minZoom=L,this._update(),this.getZoom()=this.transform.minZoom)return this.transform.maxZoom=L,this._update(),this.getZoom()>L?this.setZoom(L):this.fire(new o.h("zoomstart")).fire(new o.h("zoom")).fire(new o.h("zoomend")),this;throw new Error("maxZoom must be greater than the current minZoom")}getMaxZoom(){return this.transform.maxZoom}setMinPitch(L){if((L=L??0)<0)throw new Error("minPitch must be greater than or equal to 0");if(L>=0&&L<=this.transform.maxPitch)return this.transform.minPitch=L,this._update(),this.getPitch()85)throw new Error("maxPitch must be less than or equal to 85");if(L>=this.transform.minPitch)return this.transform.maxPitch=L,this._update(),this.getPitch()>L?this.setPitch(L):this.fire(new o.h("pitchstart")).fire(new o.h("pitch")).fire(new o.h("pitchend")),this;throw new Error("maxPitch must be greater than or equal to minPitch")}getMaxPitch(){return this.transform.maxPitch}getScaleFactor(){return this._scaleFactor}setScaleFactor(L){return this._scaleFactor=L,this.painter.scaleFactor=L,this.style&&this.style._setLabelPlacementStale(),this.style._updateFilteredLayers(N=>N.type==="symbol"),this._update(!0),this}getRenderWorldCopies(){return this.transform.renderWorldCopies}setRenderWorldCopies(L){return this.transform.renderWorldCopies=L,this.transform.renderWorldCopies||this._forceMarkerAndPopupUpdate(!0),this._update()}getLanguage(){return this._language}_parseLanguage(L){return L==="auto"?navigator.language:Array.isArray(L)?L.length===0?void 0:L.map(N=>N==="auto"?navigator.language:N):L}setLanguage(L){const N=this._parseLanguage(L);if(!this.style||N===this._language)return this;this._language=N,this.style.reloadSources();for(const E of this._controls)E._setLanguage&&E._setLanguage(this._language);return this}getWorldview(){return this._worldview}setWorldview(L){return this.style&&L!==this._worldview?(this._worldview=L,this._styleDirty=!0,this.style.setWorldview(L),this):this}getProjection(){return this.transform.mercatorFromTransition?{name:"globe",center:[0,0]}:this.transform.getProjection()}_showingGlobe(){return this.transform.projection.name==="globe"}setProjection(L){return this._lazyInitEmptyStyle(),L?typeof L=="string"&&(L={name:L}):L=null,this._useExplicitProjection=!!L,this._prioritizeAndUpdateProjection(L,this.style.projection)}_updateProjectionTransition(){if(this.getProjection().name!=="globe")return;const L=this.transform,N=L.projection.name;let E;N==="globe"&&L.zoom>=o.b1?(L.setMercatorFromTransition(),E=!0):N==="mercator"&&L.zoom=o.b1?this.transform.setMercatorFromTransition():this.transform.setProjection(L),this.style.applyProjectionUpdate();const z=this.transform.getProjection().name==="mercator"&&E!==this.transform.mercatorFromTransition;return(N||z)&&(this.painter.clearBackgroundTiles(),this.style.clearSources(),this._update(!0),this._forceMarkerAndPopupUpdate(!0)),this}project(L,N){return this.transform.locationPoint3D(o.cz.convert(L),N)}unproject(L,N){return this.transform.pointLocation3D(o.P.convert(L),N)}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(L,N,E){const z=W=>{let Z=[];if(Array.isArray(N)){const ne=N.filter(de=>this.getLayer(de));Z=ne.length?this.queryRenderedFeatures(W,{layers:ne}):[]}else Z=this.queryRenderedFeatures(W,{target:N});return Z};if(L==="mouseenter"||L==="mouseover"){let W=!1;return{listener:E,targets:N,delegates:{mousemove:ne=>{const de=z(ne.point);de.length?W||(W=!0,E.call(this,new Qu(L,this,ne.originalEvent,{features:de}))):W=!1},mouseout:()=>{W=!1}}}}if(L==="mouseleave"||L==="mouseout"){let W=!1;return{listener:E,targets:N,delegates:{mousemove:de=>{z(de.point).length?W=!0:W&&(W=!1,E.call(this,new Qu(L,this,de.originalEvent)))},mouseout:de=>{W&&(W=!1,E.call(this,new Qu(L,this,de.originalEvent)))}}}}{const W=Z=>{const ne=z(Z.point);ne.length&&(Z.features=ne,E.call(this,Z),delete Z.features)};return{listener:E,targets:N,delegates:{[L]:W}}}}on(L,N,E){if(typeof N=="function"||E===void 0)return super.on(L,N);if(typeof N=="string"&&(N=[N]),!this._areTargetsValid(N))return this;const z=this._createDelegatedListener(L,N,E);this._delegatedListeners=this._delegatedListeners||{},this._delegatedListeners[L]=this._delegatedListeners[L]||[],this._delegatedListeners[L].push(z);for(const W in z.delegates)this.on(W,z.delegates[W]);return this}once(L,N,E){if(typeof N=="function"||E===void 0)return super.once(L,N);if(typeof N=="string"&&(N=[N]),!this._areTargetsValid(N))return this;const z=this._createDelegatedListener(L,N,E);for(const W in z.delegates)this.once(W,z.delegates[W]);return this}off(L,N,E){if(typeof N=="function"||E===void 0)return super.off(L,N);if(typeof N=="string"&&(N=[N]),!this._areTargetsValid(N))return this;const z=this._delegatedListeners?this._delegatedListeners[L]:void 0;return z&&(W=>{for(let Z=0;Z{if(E){const W=typeof E=="string"?E:E instanceof Error?E.message:E.error;o.w(`Unable to perform style diff: ${W}. Rebuilding the style from scratch.`),this._updateStyle(L,N)}else z&&this._update(!0)},()=>this._postStyleLoadEvent()),this):(this._localIdeographFontFamily=N.localIdeographFontFamily,this._localFontFamily=N.localFontFamily,this._fontstackCompositing=N.fontstackCompositing,this._updateStyle(L,N))}_getUIString(L){const N=this._locale[L];if(N==null)throw new Error(`Missing UI string '${L}'`);return N}_updateStyle(L,N){if(this.style&&(this.style.setEventedParent(null),this.style._remove(),this.style=void 0),L){const E={...N};N&&N.config&&(E.initialConfig=N.config,delete E.config),this.style=new zi(this,E).load(L),this.style.setEventedParent(this,{style:this.style})}return this._updateTerrain(),this}_lazyInitEmptyStyle(){this.style||(this.style=new zi(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(L){return L==null?(this.fire(new o.f(new Error("IDs can't be empty."))),!1):o.df(L)?(this.fire(new o.f(new Error(`IDs can't contain special symbols: "${L}".`))),!1):L!=="__proto__"&&L!=="constructor"&&L!=="prototype"||(this.fire(new o.f(new Error(`IDs can't be "${L}".`))),!1)}_isTargetValid(L){return"featuresetId"in L?this._isValidId("importId"in L?L.importId:L.featuresetId):"layerId"in L&&this._isValidId(L.layerId)}_areTargetsValid(L){if(Array.isArray(L)){for(const N of L)if(!this._isValidId(N))return!1;return!0}return this._isTargetValid(L)}addSource(L,N){return this._isValidId(L)?(this._lazyInitEmptyStyle(),this.style.addSource(L,N),this._update(!0)):this}isSourceLoaded(L){return!!this._isValidId(L)&&!!this.style&&this.style._isSourceCacheLoaded(L)}areTilesLoaded(){return this.style.areTilesLoaded()}removeSource(L){return this._isValidId(L)?(this.style.removeSource(L),this._updateTerrain(),this._update(!0)):this}getSource(L){return this._isValidId(L)?this.style.getOwnSource(L):null}addImage(L,N,{pixelRatio:E=1,sdf:z=!1,stretchX:W,stretchY:Z,content:ne}={}){this._lazyInitEmptyStyle();const de=o.I.from(L);if(N instanceof HTMLImageElement||ImageBitmap&&N instanceof ImageBitmap){const{width:ye,height:Ce,data:Pe}=o.e.getImageData(N);this.style.addImage(de,{data:new o.b({width:ye,height:Ce},Pe),pixelRatio:E,stretchX:W,stretchY:Z,content:ne,sdf:z,version:0,usvg:!1})}else if(N.width===void 0||N.height===void 0)this.fire(new o.f(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:ye,height:Ce}=N,Pe=N;this.style.addImage(de,{data:new o.b({width:ye,height:Ce},new Uint8Array(Pe.data)),pixelRatio:E,stretchX:W,stretchY:Z,content:ne,sdf:z,usvg:!1,version:0,userImage:Pe}),Pe.onAdd&&Pe.onAdd(this,L)}}updateImage(L,N){this._lazyInitEmptyStyle();const E=o.I.from(L),z=this.style.getImage(E);if(!z)return void this.fire(new o.f(new Error("The map has no image with that id. If you are adding a new image use `map.addImage(...)` instead.")));const W=N instanceof HTMLImageElement||ImageBitmap&&N instanceof ImageBitmap?o.e.getImageData(N):N,{width:Z,height:ne,data:de}=W;if(Z===void 0||ne===void 0)return void this.fire(new o.f(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(Z!==(z.usvg?z.icon.usvg_tree.width:z.data.width)||ne!==(z.usvg?z.icon.usvg_tree.height:z.data.height))return void this.fire(new o.f(new Error(`The width and height of the updated image (${Z}, ${ne}) must be that same as the previous version of the image (${z.data.width}, ${z.data.height})`)));const ye=!(N instanceof HTMLImageElement||ImageBitmap&&N instanceof ImageBitmap);let Ce=!1;z.usvg?(z.data=new o.b({width:Z,height:ne},new Uint8Array(de)),z.usvg=!1,z.icon=void 0,Ce=!0):z.data.replace(de,ye),this.style.updateImage(E,z,Ce)}hasImage(L){return L?!!this.style&&!!this.style.getImage(o.I.from(L)):(this.fire(new o.f(new Error("Missing required image id"))),!1)}removeImage(L){this.style.removeImage(o.I.from(L))}loadImage(L,N){(async()=>{const E=await this._requestManager.transformRequest(L,o.R.Image),{data:z}=await o.a(E);return z})().then(E=>N(null,E)).catch(N)}listImages(){return this.style.listImages().map(L=>L.name)}addModel(L,N){this._lazyInitEmptyStyle(),this.style.addModel(L,N)}hasModel(L){return L?this.style.hasModel(L):(this.fire(new o.f(new Error("Missing required model id"))),!1)}removeModel(L){this.style.removeModel(L)}listModels(){return this.style.listModels()}addLayer(L,N){return this._isValidId(L.id)?(this._lazyInitEmptyStyle(),this.style.addLayer(L,N),this._update(!0)):this}getSlot(L){const N=this.getLayer(L);return N&&N.slot||null}setSlot(L,N){return this.style.setSlot(L,N),this.style.mergeLayers(),this._update(!0)}addImport(L,N){return this._isValidId(L.id)?(this.style.addImport(L,N).catch(E=>this.fire(new o.f(new Error("Failed to add import",E)))),this):this}updateImport(L,N){return typeof N!="string"&&N.id!==L?(this.removeImport(L),this.addImport(N)):(this.style.updateImport(L,N),this._update(!0))}removeImport(L){return this.style.removeImport(L),this}moveImport(L,N){return this.style.moveImport(L,N),this._update(!0)}moveLayer(L,N){return this._isValidId(L)?(this.style.moveLayer(L,N),this._update(!0)):this}removeLayer(L){return this._isValidId(L)?(this.style.removeLayer(L),this._update(!0)):this}getLayer(L){if(!this._isValidId(L))return null;const N=this.style.getOwnLayer(L);return N?N.type==="custom"?N.implementation:N.serialize():void 0}getSlots(){return this.style.getSlots()}setLayerZoomRange(L,N,E){return this._isValidId(L)?(this.style.setLayerZoomRange(L,N,E),this._update(!0)):this}setFilter(L,N,E={}){return this._isValidId(L)?(this.style.setFilter(L,N,E),this._update(!0)):this}getFilter(L){return this._isValidId(L)?this.style.getFilter(L):null}setPaintProperty(L,N,E,z={}){return this._isValidId(L)?(this.style.setPaintProperty(L,N,E,z),this._update(!0)):this}getPaintProperty(L,N){return this._isValidId(L)?this.style.getPaintProperty(L,N):null}setLayoutProperty(L,N,E,z={}){return this._isValidId(L)?(this.style.setLayoutProperty(L,N,E,z),this._update(!0)):this}getLayoutProperty(L,N){return this._isValidId(L)?this.style.getLayoutProperty(L,N):null}getLayerProperty(L,N){return this._isValidId(L)?this.style.getLayerProperty(L,N):null}setLayerProperty(L,N,E,z={}){return this._isValidId(L)?(N==="appearances"&&this._postAddingAppearancesToStyleEvent(),this.style.setLayerProperty(L,N,E,z),this._update(!0)):this}getGlyphsUrl(){return this.style.getGlyphsUrl()}setGlyphsUrl(L){return this.style.setGlyphsUrl(L),this._update(!0)}getSchema(L){return this.style.getSchema(L)}setSchema(L,N){return this.style.setSchema(L,N),this._update(!0)}getConfig(L){return this.style.getConfig(L)}setConfig(L,N){return this.style.setConfig(L,N),this._update(!0)}getConfigProperty(L,N){return this.style.getConfigProperty(L,N)}setConfigProperty(L,N,E){return this.style.setConfigProperty(L,N,E),this._update(!0)}getFeaturesetDescriptors(L){return this.style.getFeaturesetDescriptors(L)}setLights(L){if(this._lazyInitEmptyStyle(),L&&L.length===1&&L[0].type==="flat"){const N=L[0];N.properties?this.style.setFlatLight(N.properties,N.id,{}):this.style.setFlatLight({},"flat")}else this.style.setLights(L),this.painter.terrain&&(this.painter.terrain.invalidateRenderCache=!0);return this._update(!0)}getLights(){const L=this.style.getLights()||[];return L.length===0&&L.push({id:this.style.light.id,type:"flat",properties:this.style.getFlatLight()}),L}setLight(L,N={}){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:L}])}getLight(){return console.log("The `map.getLight` function is deprecated, prefer using `map.getLights` instead."),this.style.getFlatLight()}setTerrain(L){return this._lazyInitEmptyStyle(),!L&&this.transform.projection.requiresDraping?this.style.setTerrainForDraping():this.style.setTerrain(L),this._averageElevationLastSampledAt=-1/0,this._update(!0)}getTerrain(){return this.style?this.style.getTerrain():null}setFog(L){return this._lazyInitEmptyStyle(),this.style.setFog(L),this._update(!0)}getFog(){return this.style?this.style.getFog():null}setSnow(L){return this._lazyInitEmptyStyle(),this.style.setSnow(L),this._update(!0)}getSnow(){return this.style?this.style.getSnow():null}setRain(L){return this._lazyInitEmptyStyle(),this.style.setRain(L),this._update(!0)}getRain(){return this.style?this.style.getRain():null}setColorTheme(L){return this._lazyInitEmptyStyle(),this.style.setColorTheme(L),this._update(!0)}setImportColorTheme(L,N){return this._lazyInitEmptyStyle(),this.style.setImportColorTheme(L,N),this._update(!0)}setCamera(L){return this.style.setCamera(L),this._triggerCameraUpdate(L)}getNearClipOffset(){return this.transform.nearClipOffset}setNearClipOffset(L){const N=this.transform.nearClipOffset!==L;return this.transform.nearClipOffset=L,this._update(N)}_triggerCameraUpdate(L){return this._update(this.transform.setOrthographicProjectionAtLowPitch(L["camera-projection"]==="orthographic"))}getCamera(){return this.style.camera}_queryFogOpacity(L){return this.style&&this.style.fog?this.style.fog.getOpacityAtLatLng(o.cz.convert(L),this.transform):0}setFeatureState(L,N){return L.source&&!this._isValidId(L.source)?this:(this.style.setFeatureState(L,N),this._update())}removeFeatureState(L,N){return L.source&&!this._isValidId(L.source)?this:(this.style.removeFeatureState(L,N),this._update())}getFeatureState(L){return L.source&&!this._isValidId(L.source)?null:this.style.getFeatureState(L)}resetFeatureStates(L){return this.style.resetFeatureStates(L),this._update()}_selectIndoorFloor(L){this.style.indoorManager&&this.style.indoorManager.selectFloor(L)}_setIndoorActiveFloorsVisibility(L){this.style.indoorManager&&this.style.indoorManager.setActiveFloorsVisibility(L)}getIndoorTileOptions(L,N){return this.style&&this.style.isIndoorEnabled()&&this.style.indoorManager?this.style.indoorManager.getIndoorTileOptions(L,N):null}_updateContainerDimensions(){if(!this._container)return;const L=this._container.getBoundingClientRect().width||400,N=this._container.getBoundingClientRect().height||300;let E,z,W,Z=this._container;for(;Z&&(!z||!W);){const ne=window.getComputedStyle(Z).transform;ne&&ne!=="none"&&(E=ne.match(Ute)[1].split(", "),E[0]&&E[0]!=="0"&&E[0]!=="1"&&(z=E[0]),E[3]&&E[3]!=="0"&&E[3]!=="1"&&(W=E[3])),Z=Z.parentElement}this._containerWidth=z?Math.abs(L/z):L,this._containerHeight=W?Math.abs(N/W):N}_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 L=this._container;L.classList.add("mapboxgl-map"),(this._missingCSSCanary=g("div","mapboxgl-canary",L)).style.visibility="hidden",this._detectMissingCSS();const N=this._canvasContainer=g("div","mapboxgl-canvas-container",L);this._canvas=g("canvas","mapboxgl-canvas",N),this._interactive&&(N.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 E=this._controlContainer=g("div","mapboxgl-control-container",L),z=this._controlPositions={};["top-left","top","top-right","right","bottom-right","bottom","bottom-left","left"].forEach(W=>{z[W]=g("div",`mapboxgl-ctrl-${W}`,E)}),this._container.addEventListener("scroll",this._onMapScroll,!1)}_resizeCanvas(L,N){const E=o.e.devicePixelRatio||1;this._canvas.width=E*Math.ceil(L),this._canvas.height=E*Math.ceil(N),this._canvas.style.width=`${L}px`,this._canvas.style.height=`${N}px`}_addMarker(L){this._markers.push(L)}_removeMarker(L){const N=this._markers.indexOf(L);N!==-1&&this._markers.splice(N,1)}_addPopup(L){this._popups.push(L)}_removePopup(L){const N=this._popups.indexOf(L);N!==-1&&this._popups.splice(N,1)}_setupPainter(){const L={...c,failIfMajorPerformanceCaveat:this._failIfMajorPerformanceCaveat,preserveDrawingBuffer:this._preserveDrawingBuffer,antialias:this._antialias||!1},N=this._canvas.getContext("webgl2",L);N?(o.eS(N,!0),this.painter=new Le(N,this._contextCreateOptions,this.transform,this._scaleFactor,this._worldview),this.on("data",E=>{if(E.dataType==="source"){const z=this.transform.elevation?this.transform.elevation._source():null;z&&E.sourceCacheId===z.id&&this.style&&this.style._setLabelPlacementStale(),this.style&&E.sourceCacheId&&this.style._buildingIndex.hasLayerForSourceCache(E.sourceCacheId)&&this.style._requestFullLabelPlacement(),this.painter.setTileLoadedFlag(!0)}})):this.fire(new o.f(new Error("Failed to initialize WebGL")))}_contextLost(L){L.preventDefault(),this._frame&&(this._frame.cancel(),this._frame=null),this.style&&this.style.handleContextLost(),this.fire(new o.h("webglcontextlost",{originalEvent:L}))}_contextRestored(L){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.h("webglcontextrestored",{originalEvent:L}))}_onMapScroll(L){if(L.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(L){return this.style?(this._styleDirty=this._styleDirty||L,this._sourcesDirty=!0,this.triggerRepaint(),this):this}_requestRenderFrame(L){return this._update(),this._renderTaskQueue.add(L)}_cancelRenderFrame(L){this._renderTaskQueue.remove(L)}_requestDomTask(L){!this.loaded()||this.loaded()&&!this.isMoving()?L():this._domRenderTaskQueue.add(L)}_render(L){let N;this.fire(new o.h("renderstart")),++this._frameId;const E=this.painter.context.extTimerQuery,z=o.e.now(),W=this.painter.context.gl;if(this.listens("gpu-timing-frame")&&(N=W.createQuery(),W.beginQuery(E.TIME_ELAPSED_EXT,N)),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(L),this._domRenderTaskQueue.run(L),this._removed)return;this._updateProjectionTransition();const Z=this._isInitialLoad?0:this._fadeDuration;if(this.style&&this._styleDirty){this._styleDirty=!1;const ye=this.transform.zoom,Ce=this.transform.pitch,Pe=o.e.now(),Ke=new o.ai(ye,{now:Pe,fadeDuration:Z,pitch:Ce,transition:this._loaded?this.style.transition:{duration:0,delay:0},worldview:this._worldview});this.style.update(Ke)}this.style&&this.style.hasFogTransition()&&(this.style._markersNeedUpdate=!0,this._sourcesDirty=!0);let ne=!1;if(this.style&&this._sourcesDirty?(this._sourcesDirty=!1,this.painter._updateFog(this.style),this._updateTerrain(),ne=this._updateAverageElevation(z),this.style.updateSources(this.transform),this.style.updateImageProviders(),this.isMoving()||this._forceMarkerAndPopupUpdate()):ne=this._updateAverageElevation(z),this.style&&(this._placementDirty=this.style._updatePlacement(this.painter.transform,this.showCollisionBoxes,Z,this._crossSourceCollisions,this.painter.replacementSource,this._placementAlgorithm)),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:Z,isInitialLoad:this._isInitialLoad,showPadding:this.showPadding,gpuTiming:!!this.listens("gpu-timing-layer"),gpuTimingDeferredRender:!!this.listens("gpu-timing-deferred-render"),speedIndexTiming:this.speedIndexTiming,paintStartTimeStamp:L}),this.fire(new o.h("render")),this.loaded()&&!this._loaded&&(this._loaded=!0,o.eN.mark(o.eO.load),this.fire(new o.h("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._placementDirty&&this.style._releaseSymbolFadeTiles(),N){const ye=o.e.now()-z;W.endQuery(E.TIME_ELAPSED_EXT),setTimeout(()=>{const Ce=W.getQueryParameter(N,W.QUERY_RESULT)/1e6;W.deleteQuery(N),this.fire(new o.h("gpu-timing-frame",{cpuTime:ye,gpuTime:Ce}))},50)}if(this.listens("gpu-timing-layer")){const ye=this.painter.collectGpuTimers();setTimeout(()=>{const Ce=this.painter.queryGpuTimers(ye);this.fire(new o.h("gpu-timing-layer",{layerTimes:Ce}))},50)}if(this.listens("gpu-timing-deferred-render")){const ye=this.painter.collectDeferredRenderGpuQueries();setTimeout(()=>{const Ce=this.painter.queryGpuTimeDeferredRender(ye);this.fire(new o.h("gpu-timing-deferred-render",{gpuTime:Ce}))},50)}const de=this._sourcesDirty||this._styleDirty||this._placementDirty||ne;if(de||this._repaint)this.triggerRepaint();else{const ye=this.idle();if(ye&&(ne=this._updateAverageElevation(z,!0)),ne)this.triggerRepaint();else{if(this._triggerFrame(!1),ye&&(this.fire(new o.h("idle")),this._isInitialLoad=!1,this.speedIndexTiming)){const Ce=this._calculateSpeedIndex();this.fire(new o.h("speedindexcompleted",{speedIndex:Ce})),this.speedIndexTiming=!1}ye&&this.style&&this.style.handleIdle()}}!this._loaded||this._fullyLoaded||de||(this._fullyLoaded=!0,o.eN.mark(o.eO.fullLoad),this._performanceMetricsCollection&&o.eT(this._requestManager._customAccessToken,{width:this.painter.width,height:this.painter.height,interactionRange:this._interactionRange,visibilityHidden:this._visibilityHidden,terrainEnabled:this.painter.style.hasTerrain(),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(L){for(const N of this._markers)L&&!this.getRenderWorldCopies()&&(N._lngLat=N._lngLat.wrap()),N._update();for(const N of this._popups)!L||this.getRenderWorldCopies()||N._trackPointer||(N._lngLat=N._lngLat.wrap()),N._update()}_updateAverageElevation(L,N=!1){const E=W=>(this.transform.averageElevation=W,this._update(!1),!0);if(!this.painter.averageElevationNeedsEasing())return this.transform.averageElevation!==0&&E(0);const z=this.transform.elevation&&this.transform.elevation.exaggeration()!==this._averageElevationExaggeration;if(z||(N||L-this._averageElevationLastSampledAt>500)&&!this._averageElevation.isEasing(L)){const W=this.transform.averageElevation;let Z=this.transform.sampleAverageElevation();this.transform.elevation!=null&&(this._averageElevationExaggeration=this.transform.elevation.exaggeration()),isNaN(Z)?Z=0:this._averageElevationLastSampledAt=L;const ne=Math.abs(W-Z);if(ne>1){if(this._isInitialLoad||z)return this._averageElevation.jumpTo(Z),E(Z);this._averageElevation.easeTo(Z,L,300)}else if(ne>1e-4)return this._averageElevation.jumpTo(Z),E(Z)}return!!this._averageElevation.isEasing(L)&&E(this._averageElevation.getValue(L))}_isTokenExpired(){return this._tokenExpiration!=null&&Date.now()>this._tokenExpiration}_revokeAuth(){const L=this.painter.context.gl;o.eS(L,!1),this._logoControl instanceof zte&&this._logoControl._updateLogo(),L&&L.clear(L.DEPTH_BUFFER_BIT|L.COLOR_BUFFER_BIT|L.STENCIL_BUFFER_BIT),this._silenceAuthErrors||this.fire(new o.f(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(){o.eU(this._getMapId(),this._requestManager._skuToken,this._requestManager._customAccessToken,L=>{L&&(L.message!==o.eV&&L.status!==401||this._revokeAuth())}),this._isTokenExpired()&&this._revokeAuth(),o.eW(this._getMapId(),this._requestManager._skuToken,this._requestManager._customAccessToken,()=>{})}_postStyleLoadEvent(){this.style.globalId&&o.eX(this._requestManager._customAccessToken,{map:this,style:this.style.globalId,importedStyles:this.style.getImportGlobalIds()})}_postStyleWithAppearanceEvent(){this.style.globalId&&this.style.hasAppearances()&&o.eY(this._requestManager._customAccessToken)}_postAddingAppearancesToStyleEvent(){o.eZ(this._requestManager._customAccessToken)}_updateTerrain(){const L=this._isDragging();this.painter.updateTerrain(this.style,L)}_calculateSpeedIndex(){const L=this.painter.canvasCopy(),N=this.painter.getCanvasCopiesAndTimestamps();N.timeStamps.push(performance.now());const E=this.painter.context.gl,z=E.createFramebuffer();function W(Z){E.framebufferTexture2D(E.FRAMEBUFFER,E.COLOR_ATTACHMENT0,E.TEXTURE_2D,Z,0);const ne=new Uint8Array(E.drawingBufferWidth*E.drawingBufferHeight*4);return E.readPixels(0,0,E.drawingBufferWidth,E.drawingBufferHeight,E.RGBA,E.UNSIGNED_BYTE,ne),ne}return E.bindFramebuffer(E.FRAMEBUFFER,z),this._canvasPixelComparison(W(L),N.canvasCopies.map(W),N.timeStamps)}_canvasPixelComparison(L,N,E){let z=E[1]-E[0];const W=L.length/4;for(let Z=0;Z{const E=!!this._renderNextFrame;this._frame=null,this._renderNextFrame=null,E&&this._render(N)}))}_preloadTiles(L){const N=this.style?this.style.getSourceCaches():[];return o.bT(N,(E,z)=>E._preloadTiles(L,z),()=>{this.triggerRepaint()}),this}_onWindowOnline(){this._update()}_onWindowResize(L){this._trackResize&&this.resize({originalEvent:L})._update()}_onVisibilityChange(){document.visibilityState==="hidden"&&this._visibilityHidden++}get showTileBoundaries(){return!!this._showTileBoundaries}set showTileBoundaries(L){this._showTileBoundaries!==L&&(this._showTileBoundaries=L,L&&Bh(),this._update())}get showParseStatus(){return!!this._showParseStatus}set showParseStatus(L){this._showParseStatus!==L&&(this._showParseStatus=L,this._update())}get showTerrainWireframe(){return!!this._showTerrainWireframe}set showTerrainWireframe(L){this._showTerrainWireframe!==L&&(this._showTerrainWireframe=L,this._update())}get showLayers2DWireframe(){return!!this._showLayers2DWireframe}set showLayers2DWireframe(L){this._showLayers2DWireframe!==L&&(this._showLayers2DWireframe=L,this._update())}get showLayers3DWireframe(){return!!this._showLayers3DWireframe}set showLayers3DWireframe(L){this._showLayers3DWireframe!==L&&(this._showLayers3DWireframe=L,this._update())}get showElevationIdDebug(){return!!this.painter&&this.painter._debugParams.showElevationIdDebug}set showElevationIdDebug(L){this.painter&&this.painter._debugParams.showElevationIdDebug!==L&&(this.painter._debugParams.showElevationIdDebug=L,this.style&&L?this.style._reloadSources():this._update())}get speedIndexTiming(){return!!this._speedIndexTiming}set speedIndexTiming(L){this._speedIndexTiming!==L&&(this._speedIndexTiming=L,this._update())}get showPadding(){return!!this._showPadding}set showPadding(L){this._showPadding!==L&&(this._showPadding=L,L&&Bh(),this._update())}get showCollisionBoxes(){return!!this._showCollisionBoxes}set showCollisionBoxes(L){this._showCollisionBoxes!==L&&(this._showCollisionBoxes=L,L&&Bh(),this.style&&L?this.style._reloadSources():this._update())}get showOverdrawInspector(){return!!this._showOverdrawInspector}set showOverdrawInspector(L){this._showOverdrawInspector!==L&&(this._showOverdrawInspector=L,this._update())}get repaint(){return!!this._repaint}set repaint(L){this._repaint!==L&&(this._repaint=L,this.triggerRepaint())}get vertices(){return!!this._vertices}set vertices(L){this._vertices=L,this._update()}get showTileAABBs(){return!!this._showTileAABBs}set showTileAABBs(L){this._showTileAABBs!==L&&(this._showTileAABBs=L,L&&this._update())}_setCacheLimits(L,N){o.f1(L,N)}get version(){return o.f2}},NavigationControl:class{constructor(L={}){this.options={...fMe,...L},this._container=g("div","mapboxgl-ctrl mapboxgl-ctrl-group"),this._container.addEventListener("contextmenu",N=>N.preventDefault()),this.options.showZoom&&(o.aV(["_setButtonTitle","_updateZoomButtons"],this),this._zoomInButton=this._createButton("mapboxgl-ctrl-zoom-in",N=>{this._map&&this._map.zoomIn({},{originalEvent:N})}),g("span","mapboxgl-ctrl-icon",this._zoomInButton).setAttribute("aria-hidden","true"),this._zoomOutButton=this._createButton("mapboxgl-ctrl-zoom-out",N=>{this._map&&this._map.zoomOut({},{originalEvent:N})}),g("span","mapboxgl-ctrl-icon",this._zoomOutButton).setAttribute("aria-hidden","true")),this.options.showCompass&&(o.aV(["_rotateCompassArrow"],this),this._compass=this._createButton("mapboxgl-ctrl-compass",N=>{const E=this._map;E&&(this.options.visualizePitch?E.resetNorthPitch({},{originalEvent:N}):E.resetNorth({},{originalEvent:N}))}),this._compassIcon=g("span","mapboxgl-ctrl-icon",this._compass),this._compassIcon.setAttribute("aria-hidden","true"))}_updateZoomButtons(){const L=this._map;if(!L)return;const N=L.getZoom(),E=N===L.getMaxZoom(),z=N===L.getMinZoom();this._zoomInButton.disabled=E,this._zoomOutButton.disabled=z,this._zoomInButton.setAttribute("aria-disabled",E.toString()),this._zoomOutButton.setAttribute("aria-disabled",z.toString())}_rotateCompassArrow(){const L=this._map;if(!L)return;const N=this.options.visualizePitch?`scale(${1/Math.pow(Math.cos(L.transform.pitch*(Math.PI/180)),.5)}) rotateX(${L.transform.pitch}deg) rotateZ(${L.transform.angle*(180/Math.PI)}deg)`:`rotate(${L.transform.angle*(180/Math.PI)}deg)`;L._requestDomTask(()=>{this._compassIcon&&(this._compassIcon.style.transform=N)})}onAdd(L){return this._map=L,this.options.showZoom&&(this._setButtonTitle(this._zoomInButton,"ZoomIn"),this._setButtonTitle(this._zoomOutButton,"ZoomOut"),L.on("zoom",this._updateZoomButtons),this._updateZoomButtons()),this.options.showCompass&&(this._setButtonTitle(this._compass,"ResetBearing"),this.options.visualizePitch&&L.on("pitch",this._rotateCompassArrow),L.on("rotate",this._rotateCompassArrow),this._rotateCompassArrow(),this._handler=new rf(L,this._compass,this.options.visualizePitch)),this._container}onRemove(){const L=this._map;L&&(this._container.remove(),this.options.showZoom&&L.off("zoom",this._updateZoomButtons),this.options.showCompass&&(this.options.visualizePitch&&L.off("pitch",this._rotateCompassArrow),L.off("rotate",this._rotateCompassArrow),this._handler&&this._handler.off(),this._handler=void 0),this._map=void 0)}_createButton(L,N){const E=g("button",L,this._container);return E.type="button",E.addEventListener("click",N),E}_setButtonTitle(L,N){if(!this._map)return;const E=this._map._getUIString(`NavigationControl.${N}`);L.setAttribute("aria-label",E),L.firstElementChild&&L.firstElementChild.setAttribute("title",E)}},GeolocateControl:class extends o.E{constructor(L={}){super();const N=navigator.geolocation;this.options={geolocation:N,...Wk,...L},o.aV(["_onSuccess","_onError","_onZoom","_finish","_setupUI","_updateCamera","_updateMarker","_updateMarkerRotation","_onDeviceOrientation"],this),this._updateMarkerRotationThrottled=Qe(this._updateMarkerRotation,20),this._numberOfWatches=0}onAdd(L){return this._map=L,this._container=g("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(L){const N=(E=!!this.options.geolocation)=>{this._supportsGeolocation=E,L(E)};this._supportsGeolocation!==void 0?L(this._supportsGeolocation):navigator.permissions!==void 0?navigator.permissions.query({name:"geolocation"}).then(E=>N(E.state!=="denied")).catch(()=>N()):N()}_isOutOfMapMaxBounds(L){const N=this._map.getMaxBounds(),E=L.coords;return!!N&&(E.longitudeN.getEast()||E.latitudeN.getNorth())}_setWatchState(L){this._watchState=L;const N=this._geolocateButton.classList;N.remove(...$6);for(const E of qte[L])N.add(B6(E))}_setButtonTitle(L){const N=this._map._getUIString(L);this._geolocateButton.setAttribute("aria-label",N),this._geolocateButton.firstElementChild&&this._geolocateButton.firstElementChild.setAttribute("title",N)}_setErrorState(){switch(this._watchState){case"WAITING_ACTIVE":case"ACTIVE_LOCK":this._setWatchState("ACTIVE_ERROR");break;case"BACKGROUND":this._setWatchState("BACKGROUND_ERROR")}}_onSuccess(L){if(this._map){if(this._clearRequestTimeout(),this._isOutOfMapMaxBounds(L))return this._setErrorState(),this.fire(new o.h("outofmaxbounds",L)),this._updateMarker(),void this._finish();if(this._lastKnownPosition=L,this.options.trackUserLocation)switch(this._watchState){case"WAITING_ACTIVE":case"ACTIVE_LOCK":case"ACTIVE_ERROR":this._setWatchState(this.options.followUserLocation?"ACTIVE_LOCK":"BACKGROUND");break;case"BACKGROUND":case"BACKGROUND_ERROR":this._setWatchState("BACKGROUND")}this.options.showUserLocation&&this._watchState!=="OFF"&&this._updateMarker(L),this.options.followUserLocation&&(!this.options.trackUserLocation||this._watchState==="ACTIVE_LOCK")&&this._updateCamera(L),this.options.showUserLocation&&this._userLocationDotMarker.removeClassName("mapboxgl-user-location-dot-stale"),this.fire(new o.h("geolocate",{coords:L.coords,timestamp:L.timestamp,...L.toJSON?{toJSON:L.toJSON.bind(L)}:{}})),this._finish()}}_updateCamera(L){const N=new o.cz(L.coords.longitude,L.coords.latitude),E=L.coords.accuracy,z={bearing:this._map.getBearing(),...this.options.fitBoundsOptions};this._map.fitBounds(N.toBounds(E),z,{geolocateSource:!0})}_updateMarker(L){if(L){const N=new o.cz(L.coords.longitude,L.coords.latitude);this.options.showAccuracyCircle?this._accuracyCircleMarker.setLngLat(N).addTo(this._map):this._accuracyCircleMarker.remove(),this._userLocationDotMarker.setLngLat(N).addTo(this._map),this._accuracy=L.coords.accuracy,this.options.showUserLocation&&this.options.showAccuracyCircle&&this._updateCircleRadius()}else this._userLocationDotMarker.remove(),this._accuracyCircleMarker.remove()}_updateCircleRadius(){const L=this._map.transform,N=o.dw(1,L._center.lat)*L.worldSize,E=Math.ceil(2*this._accuracy*N);this._circleElement.style.width=`${E}px`,this._circleElement.style.height=`${E}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(L){if(this._map){if(this._clearRequestTimeout(),this.options.trackUserLocation)if(L.code===1)this._setWatchState("OFF"),this._geolocateButton.disabled=!0,this._setButtonTitle("GeolocateControl.LocationNotAvailable"),this._geolocationWatchID!==void 0&&this._clearWatch();else{if(L.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.h("error",{code:L.code,message:L.message,PERMISSION_DENIED:L.PERMISSION_DENIED,POSITION_UNAVAILABLE:L.POSITION_UNAVAILABLE,TIMEOUT:L.TIMEOUT})),this._finish()}}_finish(){this._timeoutId&&clearTimeout(this._timeoutId),this._timeoutId=void 0}_startRequestTimeout(){this._clearRequestTimeout();const L=this.options.positionOptions.timeout;L&&(this._requestTimeoutId=window.setTimeout(()=>{this._onError({code:3,message:"Geolocation request timed out"})},L))}_clearRequestTimeout(){this._requestTimeoutId!==void 0&&(clearTimeout(this._requestTimeoutId),this._requestTimeoutId=void 0)}_setupUI(L){this._map!==void 0&&(this._container.addEventListener("contextmenu",N=>N.preventDefault()),this._geolocateButton=g("button","mapboxgl-ctrl-geolocate",this._container),g("span","mapboxgl-ctrl-icon",this._geolocateButton).setAttribute("aria-hidden","true"),this._geolocateButton.type="button",L===!1?(o.w("Geolocation support is not available so the GeolocateControl will be disabled."),this._geolocateButton.disabled=!0,this._setButtonTitle("GeolocateControl.LocationNotAvailable")):this._setButtonTitle("GeolocateControl.FindMyLocation"),this.options.trackUserLocation&&(this._geolocateButton.setAttribute("aria-pressed","false"),this._watchState="OFF"),this.options.showUserLocation&&(this._createUserLocationMarkers(),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",N=>{N.geolocateSource||this._watchState!=="ACTIVE_LOCK"||N.originalEvent&&N.originalEvent.type==="resize"||(this._setWatchState("BACKGROUND"),this.fire(new o.h("trackuserlocationend")))}),this.fire(new o.h("ready")))}_onDeviceOrientation(L){this._userLocationDotMarker&&(L.webkitCompassHeading?this._heading=L.webkitCompassHeading:L.absolute===!0&&(this._heading=-1*L.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._setWatchState("WAITING_ACTIVE"),this.fire(new o.h("trackuserlocationstart"));break;case"WAITING_ACTIVE":case"ACTIVE_LOCK":case"ACTIVE_ERROR":case"BACKGROUND_ERROR":this._numberOfWatches--,this._noTimeout=!1,this._setWatchState("OFF"),this.fire(new o.h("trackuserlocationend"));break;case"BACKGROUND":this._setWatchState("ACTIVE_LOCK"),this._lastKnownPosition&&this._updateCamera(this._lastKnownPosition),this.fire(new o.h("trackuserlocationstart"))}if(this._watchState==="OFF"&&this._geolocationWatchID!==void 0)this._clearWatch();else if(this._geolocationWatchID===void 0){let L;this._geolocateButton.classList.add(B6("waiting")),this._geolocateButton.setAttribute("aria-pressed","true"),this._numberOfWatches++,this._numberOfWatches>1?(L={maximumAge:6e5,timeout:0},this._noTimeout=!0):(L=this.options.positionOptions,this._noTimeout=!1),this._geolocationWatchID=this.options.geolocation.watchPosition(this._onSuccess,this._onError,L),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(L){return this.options.followUserLocation=L??Wk.followUserLocation,this.options.trackUserLocation&&this._watchState!=="OFF"&&(this.options.followUserLocation?this._watchState!=="BACKGROUND"&&this._watchState!=="BACKGROUND_ERROR"||(this._setWatchState("ACTIVE_LOCK"),this._lastKnownPosition&&this._updateCamera(this._lastKnownPosition),this.fire(new o.h("trackuserlocationstart"))):this._watchState!=="ACTIVE_LOCK"&&this._watchState!=="ACTIVE_ERROR"||(this._setWatchState("BACKGROUND"),this.fire(new o.h("trackuserlocationend")))),this}setShowAccuracyCircle(L){if(this.options.showAccuracyCircle=L??Wk.showAccuracyCircle,!this._accuracyCircleMarker)return this;if(this.options.showAccuracyCircle){if(this.options.showUserLocation&&this._lastKnownPosition){const{longitude:N,latitude:E,accuracy:z}=this._lastKnownPosition.coords;this._accuracy=z,this._accuracyCircleMarker.setLngLat(new o.cz(N,E)).addTo(this._map),this._updateCircleRadius()}}else this._accuracyCircleMarker.remove();return this}setShowUserHeading(L){return this.options.showUserHeading=L??Wk.showUserHeading,this._setup?(this.options.showUserHeading?this._geolocationWatchID!==void 0&&this._addDeviceOrientationListener():(this._removeDeviceOrientationListener(),this._heading=void 0,this._userLocationDotMarker&&this._updateMarkerRotation()),this):this}setFitBoundsOptions(L){return this.options.fitBoundsOptions=L??Wk.fitBoundsOptions,this}setShowUserLocation(L){return this.options.showUserLocation=L??Wk.showUserLocation,this._setup?(this.options.showUserLocation?(this._userLocationDotMarker||(this._createUserLocationMarkers(),this._map.on("zoom",this._onZoom)),!this._lastKnownPosition||this._watchState!==void 0&&this._watchState==="OFF"||this._updateMarker(this._lastKnownPosition)):(this._userLocationDotMarker&&this._userLocationDotMarker.remove(),this._accuracyCircleMarker&&this._accuracyCircleMarker.remove()),this):this}_addDeviceOrientationListener(){const L=()=>{const N="ondeviceorientationabsolute"in window?"deviceorientationabsolute":"deviceorientation";window.addEventListener(N,this._onDeviceOrientation)};typeof DeviceOrientationEvent.requestPermission=="function"?DeviceOrientationEvent.requestPermission().then(N=>{N==="granted"&&L()}).catch(console.error):L()}_removeDeviceOrientationListener(){window.removeEventListener("deviceorientation",this._onDeviceOrientation),window.removeEventListener("deviceorientationabsolute",this._onDeviceOrientation)}_createUserLocationMarkers(){this._dotElement=g("div","mapboxgl-user-location"),this._dotElement.appendChild(g("div","mapboxgl-user-location-dot")),this._dotElement.appendChild(g("div","mapboxgl-user-location-heading")),this._userLocationDotMarker=new E4({element:this._dotElement,rotationAlignment:"map",pitchAlignment:"map"}),this._circleElement=g("div","mapboxgl-user-location-accuracy-circle"),this._accuracyCircleMarker=new E4({element:this._circleElement,pitchAlignment:"map"})}_clearWatch(){this._clearRequestTimeout(),this.options.geolocation.clearWatch(this._geolocationWatchID),this._removeDeviceOrientationListener(),this._geolocationWatchID=void 0,this._geolocateButton.classList.remove(B6("waiting")),this._geolocateButton.setAttribute("aria-pressed","false"),this.options.showUserLocation&&this._updateMarker(null)}},AttributionControl:Fte,ScaleControl:class{constructor(L={}){this.options={...Vte,...L},o.aV(["_update","_setScale","setUnit"],this)}getDefaultPosition(){return"bottom-left"}_update(){const L=this.options.maxWidth||100,N=this._map,E=N._containerHeight/2,z=N._containerWidth/2-L/2,W=N.unproject([z,E]),Z=N.unproject([z+L,E]),ne=W.distanceTo(Z);if(this.options.unit==="imperial"){const de=3.2808*ne;de>5280?this._setScale(L,de/5280,"mile"):this._setScale(L,de,"foot")}else this.options.unit==="nautical"?this._setScale(L,ne/1852,"nautical-mile"):ne>=1e3?this._setScale(L,ne/1e3,"kilometer"):this._setScale(L,ne,"meter")}_setScale(L,N,E){this._map._requestDomTask(()=>{const z=function(Z){const ne=Math.pow(10,`${Math.floor(Z)}`.length-1);let de=Z/ne;return de=de>=10?10:de>=5?5:de>=3?3:de>=2?2:de>=1?1:function(ye){const Ce=Math.pow(10,Math.ceil(-Math.log(ye)/Math.LN10));return Math.round(ye*Ce)/Ce}(de),ne*de}(N),W=z/N;this._container.innerHTML=E!=="nautical-mile"?new Intl.NumberFormat(this._language,{style:"unit",unitDisplay:"short",unit:E}).format(z):`${z} ${sH[E]}`,this._container.style.width=L*W+"px"})}onAdd(L){return this._map=L,this._language=L.getLanguage(),this._container=g("div","mapboxgl-ctrl mapboxgl-ctrl-scale",L.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(L){this._language=L,this._update()}setUnit(L){this.options.unit=L,this._update()}},FullscreenControl:class{constructor(L={}){this._fullscreen=!1,L&&L.container&&(L.container instanceof HTMLElement?this._container=L.container:o.w("Full screen control 'container' must be a DOM element.")),o.aV(["_onClickFullscreen","_changeIcon"],this),"onfullscreenchange"in document?this._fullscreenchange="fullscreenchange":"onwebkitfullscreenchange"in document&&(this._fullscreenchange="webkitfullscreenchange")}onAdd(L){return this._map=L,this._container||(this._container=this._map.getContainer()),this._controlContainer=g("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 L=this._fullscreenButton=g("button","mapboxgl-ctrl-fullscreen",this._controlContainer);g("span","mapboxgl-ctrl-icon",L).setAttribute("aria-hidden","true"),L.type="button",this._updateTitle(),this._fullscreenButton.addEventListener("click",this._onClickFullscreen),document.addEventListener(this._fullscreenchange,this._changeIcon)}_updateTitle(){const L=this._getTitle();this._fullscreenButton.setAttribute("aria-label",L),this._fullscreenButton.firstElementChild&&this._fullscreenButton.firstElementChild.setAttribute("title",L)}_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.aV(["_onIndoorUpdate","_onStyleData","_scrollUp","_scrollDown","_toggleIndoor"],this),this._visibleFloorStart=0,this._lastSelectedFloorId=null}onAdd(L){return this._map=L,this._container=g("div","mapboxgl-ctrl mapboxgl-ctrl-group"),this._container.style.display="none",this._map.on("styledata",this._onStyleData),this._map.on("idle",this._onStyleData),this._updateConnection(),this._container}_onStyleData(){this._updateConnection()}_updateConnection(){if(this._map&&this._map.style&&this._map.style.indoorManager){const L=this._map.style.indoorManager;L.off("selector-update",this._onIndoorUpdate),L.on("selector-update",this._onIndoorUpdate),this._onIndoorUpdate(L.getControlState()),this._map.off("idle",this._onStyleData)}}_createButton(L,N){const E=g("button",L,this._container);return E.type="button",E.addEventListener("click",N),E}_setButtonTitle(L,N){L.setAttribute("aria-label",N),L.textContent=N}onRemove(){this._container&&this._container.remove(),this._map&&(this._map.off("styledata",this._onStyleData),this._map.off("idle",this._onStyleData),this._map.style&&this._map.style.indoorManager&&this._map.style.indoorManager.off("selector-update",this._onIndoorUpdate),this._map=null)}getDefaultPosition(){return"top-right"}_onIndoorUpdate(L){if(!L||!L.floors||L.floors.length===0)return this._model=L,void(this._container.style.display="none");const N=this._model;this._model=L,this._container.style.display="inline-block";const E=!N||N.floors.length!==L.floors.length||N.floors.some((z,W)=>z.id!==L.floors[W].id);if(E&&(this._visibleFloorStart=0,this._lastSelectedFloorId=null),L.selectedFloorId){if(L.selectedFloorId!==this._lastSelectedFloorId||E){const z=L.floors.findIndex(W=>W.id===L.selectedFloorId);if(z!==-1){const W=L.floors.length;let Z,ne;W<=5?(Z=0,ne=W-1):this._visibleFloorStart===0?(Z=0,ne=3):this._visibleFloorStart>=W-3?(Z=W-3-1,ne=W-1):(Z=this._visibleFloorStart,ne=this._visibleFloorStart+3-1),zne&&(this._visibleFloorStart=z-2)}}this._lastSelectedFloorId=L.selectedFloorId}this._render()}_render(){if(!this._container||!this._model||!this._model.floors)return;this._container.innerHTML="";const L=this._createButton("mapboxgl-ctrl-indoor-toggle",this._toggleIndoor);g("span","mapboxgl-ctrl-icon",L).setAttribute("aria-hidden","true"),this._model.activeFloorsVisible||L.classList.add("mapboxgl-ctrl-level-button-selected"),this._container.appendChild(L);const N=this._model.floors,E=N.length;if(E<=5)return void N.forEach(ne=>this._createFloorButton(ne));const z=this._visibleFloorStart===0,W=this._visibleFloorStart>=E-3;if(z)this._createFloorButton(N[0]);else{const ne=this._createButton("mapboxgl-ctrl-arrow-up",this._scrollUp);g("span","mapboxgl-ctrl-icon",ne).setAttribute("aria-hidden","true"),this._container.appendChild(ne)}let Z=[];if(Z=z?N.slice(1,4):W?N.slice(this._visibleFloorStart-1,this._visibleFloorStart+3-1):N.slice(this._visibleFloorStart,this._visibleFloorStart+3),Z.forEach(ne=>this._createFloorButton(ne)),W)this._createFloorButton(N[E-1]);else{const ne=this._createButton("mapboxgl-ctrl-arrow-down",this._scrollDown);g("span","mapboxgl-ctrl-icon",ne).setAttribute("aria-hidden","true"),this._container.appendChild(ne)}}_createFloorButton(L){const N=this._createButton("mapboxgl-ctrl-level-button",()=>{const Z=L.id;this._model&&this._model.selectedFloorId===Z&&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(Z))}),E=(L.name||"").trim(),z=L.zIndex.toString(),W=E?Array.from(E).slice(0,3).join(""):z;this._setButtonTitle(N,W),this._model&&this._model.activeFloorsVisible&&L.id===this._model.selectedFloorId&&N.classList.add("mapboxgl-ctrl-level-button-selected"),this._container&&this._container.appendChild(N)}_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 L=this._model&&this._model.floors||[];if(L.length>3){const N=L.length-3;this._visibleFloorStart===N-1&&(this._visibleFloorStart=N-2)}this._render()}}_scrollDown(){if(this._model&&this._model.floors){const L=this._model.floors.length-3;this._visibleFloorStartL&&(this._visibleFloorStart=L),this._render())}}},Popup:class extends o.E{constructor(L){super(),this.options=Object.assign(Object.create(By),L),this._altitude=this.options.altitude,o.aV(["_update","_onClose","remove","_onMouseEvent"],this),this._classList=new Set(L&&L.className?L.className.trim().split(nH):[])}addTo(L){return this._map&&this.remove(),this._map=L,this.options.closeOnClick&&L.on("preclick",this._onClose),this.options.closeOnMove&&L.on("move",this._onClose),L.on("remove",this.remove),this._update(),L._addPopup(this),this._focusFirstElement(),this._trackPointer?(L.on("mousemove",this._onMouseEvent),L.on("mouseup",this._onMouseEvent),L._canvasContainer.classList.add("mapboxgl-track-pointer")):L.on("move",this._update),this.fire(new o.h("open")),this}isOpen(){return!!this._map}remove(){this._content&&this._content.remove(),this._container&&(this._container.remove(),this._container=void 0);const L=this._map;return L&&(L.off("move",this._update),L.off("move",this._onClose),L.off("preclick",this._onClose),L.off("click",this._onClose),L.off("remove",this.remove),L.off("mousemove",this._onMouseEvent),L.off("mouseup",this._onMouseEvent),L.off("drag",this._onMouseEvent),L._canvasContainer&&L._canvasContainer.classList.remove("mapboxgl-track-pointer"),L._removePopup(this),this._map=void 0),this.fire(new o.h("close")),this}getLngLat(){return this._lngLat}setLngLat(L){this._lngLat=o.cz.convert(L),this._pos=null,this._trackPointer=!1,this._update();const N=this._map;return N&&(N.on("move",this._update),N.off("mousemove",this._onMouseEvent),N._canvasContainer.classList.remove("mapboxgl-track-pointer")),this}getAltitude(){return this._altitude}setAltitude(L){return this._altitude=L,this._update(),this}trackPointer(){this._trackPointer=!0,this._pos=null,this._update();const L=this._map;return L&&(L.off("move",this._update),L.on("mousemove",this._onMouseEvent),L.on("drag",this._onMouseEvent),L._canvasContainer.classList.add("mapboxgl-track-pointer")),this}getElement(){return this._container}setText(L){return this.setDOMContent(document.createTextNode(L))}setHTML(L){const N=document.createDocumentFragment(),E=document.createElement("body");let z;for(E.innerHTML=L;z=E.firstChild,z;)N.appendChild(z);return this.setDOMContent(N)}getMaxWidth(){return this._container&&this._container.style.maxWidth}setMaxWidth(L){return this.options.maxWidth=L,this._update(),this}setDOMContent(L){let N=this._content;if(N)for(;N.hasChildNodes();)N.firstChild&&N.removeChild(N.firstChild);else N=this._content=g("div","mapboxgl-popup-content",this._container||void 0);if(N.appendChild(L),this.options.closeButton){const E=this._closeButton=g("button","mapboxgl-popup-close-button",N);E.type="button",E.setAttribute("aria-label","Close popup"),E.innerHTML='',E.addEventListener("click",this._onClose)}return this._update(),this._focusFirstElement(),this}addClassName(L){return this._classList.add(L),this._updateClassList(),this}removeClassName(L){return this._classList.delete(L),this._updateClassList(),this}setOffset(L){return this.options.offset=L,this._update(),this}toggleClassName(L){let N;return this._classList.delete(L)?N=!1:(this._classList.add(L),N=!0),this._updateClassList(),N}_onMouseEvent(L){this._update(L.point)}_getAnchor(L){if(this.options.anchor)return this.options.anchor;const N=this._map,E=this._container,z=this._pos;if(!N||!E||!z)return"bottom";const W=E.offsetWidth,Z=E.offsetHeight,ne=z.xN.transform.width-W/2;if(z.y+LN.transform.height-Z){if(ne)return"bottom-left";if(de)return"bottom-right"}return ne?"left":de?"right":"bottom"}_updateClassList(){const L=this._container;if(!L)return;const N=[...this._classList];N.push("mapboxgl-popup"),this._anchor&&N.push(`mapboxgl-popup-anchor-${this._anchor}`),this._trackPointer&&N.push("mapboxgl-popup-track-pointer"),L.className=N.join(" ")}_update(L){const N=this._map,E=this._content;if(!N||!this._lngLat&&!this._trackPointer||!E)return;let z=this._container;if(z||(z=this._container=g("div","mapboxgl-popup",N.getContainer()),this._tip=g("div","mapboxgl-popup-tip",z),z.appendChild(E)),this.options.maxWidth&&z.style.maxWidth!==this.options.maxWidth&&(z.style.maxWidth=this.options.maxWidth),N.transform.renderWorldCopies&&!this._trackPointer&&(this._lngLat=A4(this._lngLat,this._pos,N.transform)),!this._trackPointer||L){const W=this._pos=this._trackPointer&&L instanceof o.P?L:N.project(this._lngLat,this._altitude),Z=c7(this.options.offset),ne=this._anchor=this._getAnchor(Z.y),de=c7(this.options.offset,ne),ye=W.add(de).round();N._requestDomTask(()=>{this._container&&ne&&(this._container.style.transform=`${o7[ne]} translate(${ye.x}px,${ye.y}px)`)})}if(!this._marker&&N._showingGlobe()){const W=o.f3(N.transform,this._lngLat)?0:1;this._setOpacity(W)}this._updateClassList()}_focusFirstElement(){if(!this.options.focusAfterOpen||!this._container)return;const L=this._container.querySelector(T4);L&&L.focus()}_onClose(){this.remove()}_setOpacity(L){this._container&&(this._container.style.opacity=`${L}`),this._content&&(this._content.style.pointerEvents=L?"auto":"none")}},Marker:E4,Style:zi,LngLat:o.cz,LngLatBounds:o.eC,Point:o.P,MercatorCoordinate:o.bS,FreeCameraOptions:o.f9,Evented:o.E,config:o.eM,prewarm:function(){Bk().acquire(Ea)},clearPrewarmedResources:function(){const L=Lb;L&&(L.isPreloaded()&&L.numActive()===1?(L.release(Ea),Lb=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.eM.ACCESS_TOKEN},set accessToken(L){o.fn(L)},get baseApiUrl(){return o.eM.API_URL},set baseApiUrl(L){o.fm(L)},get workerCount(){return na.workerCount},set workerCount(L){(function(N){na.workerCount=N})(L)},get maxParallelImageRequests(){return o.eM.MAX_PARALLEL_IMAGE_REQUESTS},set maxParallelImageRequests(L){o.fl(L)},clearStorage(L){o.fk(L)},get workerUrl(){return Br.workerUrl},set workerUrl(L){Br.workerUrl=L},get workerClass(){return Br.workerClass},set workerClass(L){Br.workerClass=L},get dracoUrl(){return o.fj()},set dracoUrl(L){o.fi(L)},get meshoptUrl(){return o.fh()},set meshoptUrl(L){o.fg(L)},get buildingGenUrl(){return o.ff()},set buildingGenUrl(L){o.fe(L)},setNow:o.e.setNow,restoreNow:o.e.restoreNow}});var l=a;return l})})(ZAt);var Bws=ZAt.exports;const Td=kd(Bws),olt={coming_soon:"#3B82F6",office_exclusive:"#6366F1",pre_market:"#06B6D4",active:"#10B981",price_improvement:"#F97316",under_contract:"#8B5CF6",sold:"#6B7280"},llt={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 $ws(s){return s>=1e6?`$${(s/1e6).toFixed(1)}M`:`$${(s/1e3).toFixed(0)}K`}function Uws({listings:s,isLoading:t}){const n=Jn(),r=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:m}=await V.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle();m!=null&&m.value&&o(m.value)}catch(m){console.error("Error fetching mapbox token:",m)}d(!1)})()},[]),k.useEffect(()=>{if(!r.current||!l||a.current)return;Td.accessToken=l;const h=s.filter(g=>g.latitude!=null&&g.longitude!=null);let m=[-98.5795,39.8283],p=4;if(h.length>0){const g=h.reduce((y,v)=>y+v.longitude,0)/h.length,x=h.reduce((y,v)=>y+v.latitude,0)/h.length;m=[g,x],p=h.length===1?12:10}return a.current=new Td.Map({container:r.current,style:"mapbox://styles/mapbox/light-v11",zoom:p,center:m}),a.current.addControl(new Td.NavigationControl,"top-right"),()=>{var g;(g=a.current)==null||g.remove(),a.current=null}},[l]),k.useEffect(()=>{if(!a.current||!l)return;i.current.forEach(m=>m.remove()),i.current=[];const h=s.filter(m=>m.latitude!=null&&m.longitude!=null);if(h.forEach(m=>{var C,A,M;const p=olt[m.status]||"#10B981",g=((C=m.photos)==null?void 0:C.find(I=>I.is_primary))||((A=m.photos)==null?void 0:A[0]),y=window.location.hostname==="listings.relevelup.com"||window.location.hostname.startsWith("listings.")?`/${m.slug||m.id}`:`/public/listing/${m.slug||m.id}`,v=document.createElement("div");v.className="cursor-pointer",v.innerHTML=`
`;const _=new Td.Popup({offset:25,closeButton:!0,maxWidth:"280px"}).setHTML(`
${g!=null&&g.photo_url?``:""}
${$ws(m.price)}
${m.property_address||""}
${m.city}, ${m.state}
${llt[m.status]||m.status} ${m.bedrooms?`${m.bedrooms} bed`:""} ${m.bathrooms?`${m.bathrooms} bath`:""}
${(M=m.agent)!=null&&M.name?`
Listed by ${m.agent.name}
`:""}
Click to view details →
`),j=new Td.Marker(v).setLngLat([m.longitude,m.latitude]).setPopup(_).addTo(a.current);i.current.push(j)}),h.length>1){const m=new Td.LngLatBounds;h.forEach(p=>m.extend([p.longitude,p.latitude])),a.current.fitBounds(m,{padding:60,maxZoom:13})}else h.length===1&&a.current.flyTo({center:[h[0].longitude,h[0].latitude],zoom:12})},[s,l]),k.useEffect(()=>(window.__navigateToPublicListing__=h=>{n(h)},()=>{delete window.__navigateToPublicListing__}),[n]),c||t?e.jsx(fn,{className:"w-full h-[500px] rounded-lg"}):!l||s.filter(h=>h.latitude!=null&&h.longitude!=null).length===0?null:e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"flex flex-wrap items-center gap-3 text-sm",children:Object.entries(olt).map(([h,m])=>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:m}}),e.jsx("span",{className:"text-xs text-gray-600",children:llt[h]})]},h))}),e.jsx("div",{ref:r,className:"w-full h-[500px] rounded-lg shadow-lg border border-gray-200"})]})}const CIe={active:"Active",coming_soon:"Coming Soon",office_exclusive:"Office Exclusive",pre_market:"Pre-Market",price_improvement:"Price Improvement",under_contract:"Under Contract",sold:"Sold"},qws={single_family:"Single Family",condo:"Condo",townhouse:"Townhouse",land:"Land",multi_family:"Multi-Family",luxury:"Luxury",commercial:"Commercial",other:"Other"},V7="#0d0d0d",clt="#1a1a1a",Vd="#c9a84c",FA="#f0d78c";function QAt(){const[s,t]=k.useState(""),[n,r]=k.useState(!1),[a,i]=k.useState(!1),[l,o]=k.useState(!1),[c,d]=k.useState(-1),u=k.useRef(null),[h,m]=k.useState({status:"",propertyType:"",minPrice:"",maxPrice:""}),{data:p}=Iws(),g=k.useMemo(()=>{if(!p)return[];const B=s.trim().toLowerCase(),U=[...p.cities.map(H=>({label:H.label,value:H.city,type:"city",count:H.count})),...p.neighborhoods.map(H=>({label:H.label,value:H.neighborhood,type:"neighborhood",count:H.count})),...p.zips.map(H=>({label:`ZIP ${H.label}`,value:H.zip,type:"zip",count:H.count}))];return(B?U.filter(H=>H.label.toLowerCase().includes(B)||H.value.toLowerCase().includes(B)):U).slice(0,8)},[p,s]);k.useEffect(()=>{const B=U=>{u.current&&!u.current.contains(U.target)&&o(!1)};return document.addEventListener("mousedown",B),()=>document.removeEventListener("mousedown",B)},[]);const{data:x,isLoading:y}=Pws({city:s||void 0,status:h.status||void 0,propertyType:h.propertyType||void 0,minPrice:h.minPrice?Number(h.minPrice):void 0,maxPrice:h.maxPrice?Number(h.maxPrice):void 0}),v=B=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(B),_=()=>{m({status:"",propertyType:"",minPrice:"",maxPrice:""}),t("")},j=s||h.status||h.propertyType||h.minPrice||h.maxPrice,C=typeof window<"u"&&(window.location.hostname==="listings.relevelup.com"||window.location.hostname.startsWith("listings.")),A=B=>C?`/${B.slug||B.id}`:`/public/listing/${B.slug||B.id}`,{featured:M,restListings:I,luxeCount:P,cities:R,activeCount:O}=k.useMemo(()=>{const B=x||[],U=B.filter(_e=>_e.status==="active"),G=U.length>0?U:B,H=new Intl.DateTimeFormat("en-CA",{timeZone:"America/New_York",year:"numeric",month:"2-digit",day:"2-digit"}).format(new Date),[Y,se,ee]=H.split("-").map(Number),oe=Math.floor(Date.UTC(Y,se-1,ee)/864e5),me=G.length>0?G[oe%G.length]:void 0,Q=B.filter(_e=>!me||_e.id!==me.id),te=Array.from(new Set(B.map(_e=>_e.city).filter(Boolean))).slice(0,8),le=B.filter(_e=>(_e.price||0)>=1e6).length,fe=U.length;return{featured:me,restListings:Q,luxeCount:le,cities:te,activeCount:fe}},[x]);return e.jsxs(e.Fragment,{children:[e.jsxs(Sc,{children:[e.jsx("title",{children:"LevelUp Listings — Curated Homes for Sale"}),e.jsx("meta",{name:"description",content:"A curated collection of exclusive properties from LevelUp real estate agents. Discover luxury homes, coming soon listings, and market-defining architecture."}),e.jsx("link",{rel:"canonical",href:"https://listings.relevelup.com"}),e.jsx("meta",{property:"og:title",content:"LevelUp Listings — Curated Homes for Sale"}),e.jsx("meta",{property:"og:description",content:"A curated collection of exclusive properties from LevelUp real estate agents."}),e.jsx("meta",{property:"og:type",content:"website"}),e.jsx("meta",{property:"og:url",content:"https://listings.relevelup.com"}),e.jsx("meta",{name:"twitter:card",content:"summary_large_image"}),e.jsx("script",{type:"application/ld+json",children:JSON.stringify({"@context":"https://schema.org","@type":"WebSite",name:"LevelUp Listings",url:"https://listings.relevelup.com"})})]}),e.jsxs("div",{className:"min-h-screen text-white",style:{backgroundColor:V7,fontFamily:"'Fira Sans', system-ui, sans-serif"},children:[e.jsx("style",{children:` .lu-serif { font-family: 'DM Serif Display', Georgia, serif; font-weight: 400; letter-spacing: -0.01em; } .lu-eyebrow { font-family: 'Fira Sans', sans-serif; font-weight: 500; letter-spacing: 0.3em; text-transform: uppercase; font-size: 11px; } .lu-gold { color: ${Vd}; } .lu-gold-line { background: linear-gradient(90deg, transparent, ${Vd}, transparent); } .lu-card-hover { transition: transform .6s cubic-bezier(.2,.7,.2,1), box-shadow .6s; } .lu-card-hover:hover { transform: translateY(-6px); } .lu-img-zoom { transition: transform 1.2s cubic-bezier(.2,.7,.2,1); } .group:hover .lu-img-zoom { transform: scale(1.06); } .lu-hero-title { animation: luFadeUp 1.1s cubic-bezier(.2,.7,.2,1) both; } .lu-hero-sub { animation: luFadeUp 1.1s .15s cubic-bezier(.2,.7,.2,1) both; } .lu-hero-search { animation: luFadeUp 1.1s .3s cubic-bezier(.2,.7,.2,1) both; } .lu-hero-stats { animation: luFadeUp 1.1s .45s cubic-bezier(.2,.7,.2,1) both; } @keyframes luFadeUp { from { opacity: 0; transform: translateY(24px); } to { opacity: 1; transform: none; } } .lu-grain::after { content: ''; position: absolute; inset: 0; pointer-events: none; opacity: .18; background-image: url("data:image/svg+xml;utf8,"); } .lu-marquee { display: flex; gap: 3rem; animation: luMarquee 40s linear infinite; } @keyframes luMarquee { to { transform: translateX(-50%); } } .lu-input-dark { background: rgba(255,255,255,0.06) !important; border-color: rgba(201,168,76,0.25) !important; color: #fff !important; } .lu-input-dark::placeholder { color: rgba(255,255,255,0.5) !important; } `}),e.jsxs("header",{className:"sticky top-0 z-50 backdrop-blur-md",style:{backgroundColor:"rgba(13,13,13,0.75)",borderBottom:"1px solid rgba(201,168,76,0.15)"},children:[e.jsxs("div",{className:"max-w-7xl mx-auto px-6 py-4 flex items-center justify-between",children:[e.jsxs(nr,{to:"/",className:"flex items-center gap-3",children:[e.jsx("img",{src:mSe,alt:"LevelUp",className:"h-7"}),e.jsx("span",{className:"hidden sm:inline-block h-5 w-px",style:{background:"rgba(255,255,255,0.2)"}}),e.jsx("span",{className:"hidden sm:inline lu-eyebrow lu-gold",children:"Listings"})]}),e.jsxs("nav",{className:"hidden md:flex items-center gap-8",children:[e.jsx("a",{href:"#featured",className:"text-sm text-white/80 hover:text-white transition",children:"Featured"}),e.jsx("a",{href:"#collection",className:"text-sm text-white/80 hover:text-white transition",children:"Collection"}),e.jsx("a",{href:"#map",className:"text-sm text-white/80 hover:text-white transition",children:"Map"}),e.jsx(nr,{to:"/home-value",className:"text-sm text-white/80 hover:text-white transition",children:"Home Value"}),e.jsx("a",{href:"https://relevelup.com",target:"_blank",rel:"noopener noreferrer",className:"text-sm px-4 py-2 rounded-full transition",style:{border:`1px solid ${Vd}`,color:Vd},children:"About LevelUp"})]}),e.jsx("button",{type:"button",onClick:()=>i(B=>!B),className:"md:hidden inline-flex items-center justify-center w-10 h-10 rounded-full",style:{border:`1px solid ${Vd}`,color:Vd},"aria-label":"Toggle menu","aria-expanded":a,children:a?e.jsx(mr,{className:"w-5 h-5"}):e.jsx(WT,{className:"w-5 h-5"})})]}),a&&e.jsx("div",{className:"md:hidden border-t",style:{borderColor:"rgba(201,168,76,0.15)"},children:e.jsxs("nav",{className:"max-w-7xl mx-auto px-6 py-4 flex flex-col gap-1",children:[e.jsx("a",{href:"#featured",onClick:()=>i(!1),className:"py-3 text-white/85 hover:text-white transition border-b",style:{borderColor:"rgba(255,255,255,0.06)"},children:"Featured"}),e.jsx("a",{href:"#collection",onClick:()=>i(!1),className:"py-3 text-white/85 hover:text-white transition border-b",style:{borderColor:"rgba(255,255,255,0.06)"},children:"Collection"}),e.jsx("a",{href:"#map",onClick:()=>i(!1),className:"py-3 text-white/85 hover:text-white transition border-b",style:{borderColor:"rgba(255,255,255,0.06)"},children:"Map"}),e.jsx(nr,{to:"/home-value",onClick:()=>i(!1),className:"py-3 text-white/85 hover:text-white transition border-b",style:{borderColor:"rgba(255,255,255,0.06)"},children:"Home Value"}),e.jsx("a",{href:"https://relevelup.com",target:"_blank",rel:"noopener noreferrer",onClick:()=>i(!1),className:"mt-3 text-center text-sm px-4 py-3 rounded-full",style:{border:`1px solid ${Vd}`,color:Vd},children:"About LevelUp"})]})})]}),e.jsxs("section",{className:"relative overflow-hidden lu-grain",style:{minHeight:"92vh"},children:[e.jsxs("div",{className:"absolute inset-0",children:[e.jsx("img",{src:zws,alt:"Luxury home at dusk",className:"w-full h-full object-cover",style:{filter:"brightness(0.55) contrast(1.05)"}}),e.jsx("div",{className:"absolute inset-0",style:{background:"linear-gradient(180deg, rgba(13,13,13,0.55) 0%, rgba(13,13,13,0.25) 40%, rgba(13,13,13,0.9) 100%)"}})]}),e.jsxs("div",{className:"relative max-w-7xl mx-auto px-6 pt-24 md:pt-32 pb-16 flex flex-col justify-center",style:{minHeight:"92vh"},children:[e.jsxs("div",{className:"max-w-4xl",children:[e.jsxs("div",{className:"lu-hero-title flex items-center gap-3 mb-6",children:[e.jsx("span",{className:"h-px w-10",style:{background:Vd}}),e.jsx("span",{className:"lu-eyebrow lu-gold",children:"The LevelUp Collection"})]}),e.jsxs("h1",{className:"lu-serif lu-hero-title text-white text-5xl sm:text-6xl md:text-7xl lg:text-8xl leading-[1.02] mb-6",children:["Homes with a",e.jsx("br",{}),e.jsx("span",{className:"italic",style:{color:FA},children:"quiet"})," kind of luxury."]}),e.jsx("p",{className:"lu-hero-sub text-white/75 text-lg md:text-xl max-w-2xl mb-10 leading-relaxed",children:"A private, hand-picked collection of properties represented by LevelUp agents — from waterfront estates to architectural landmarks and everything in between."}),e.jsxs("div",{className:"lu-hero-search max-w-3xl",ref:u,children:[e.jsxs("div",{className:"flex items-stretch rounded-full overflow-hidden shadow-2xl relative",style:{background:"rgba(13,13,13,0.7)",border:`1px solid ${Vd}`,backdropFilter:"blur(12px)"},children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Yr,{className:"absolute left-6 top-1/2 -translate-y-1/2 h-5 w-5",style:{color:Vd}}),e.jsx(be,{placeholder:"City, neighborhood, or ZIP",value:s,onChange:B=>{t(B.target.value),o(!0),d(-1)},onFocus:()=>o(!0),onKeyDown:B=>{if(!(!l||g.length===0))if(B.key==="ArrowDown")B.preventDefault(),d(U=>Math.min(U+1,g.length-1));else if(B.key==="ArrowUp")B.preventDefault(),d(U=>Math.max(U-1,0));else if(B.key==="Enter"&&c>=0){B.preventDefault();const U=g[c];t(U.value),o(!1)}else B.key==="Escape"&&o(!1)},className:"pl-16 h-16 text-base md:text-lg border-0 bg-transparent text-white placeholder:text-white/50 focus-visible:ring-0 rounded-none"})]}),e.jsxs("button",{onClick:()=>r(!n),className:"hidden sm:flex items-center gap-2 px-6 border-l text-sm text-white/80 hover:text-white transition",style:{borderColor:"rgba(201,168,76,0.3)"},children:[e.jsx(tM,{className:"h-4 w-4"}),"Filters"]}),e.jsxs("button",{className:"px-8 flex items-center gap-2 font-medium transition hover:brightness-110",style:{background:Vd,color:V7},onClick:()=>o(!1),children:[e.jsx(Yr,{className:"h-5 w-5"}),e.jsx("span",{className:"hidden md:inline",children:"Search"})]})]}),l&&g.length>0&&e.jsxs("div",{className:"mt-2 rounded-2xl overflow-hidden shadow-2xl animate-fade-in",style:{background:"rgba(13,13,13,0.96)",border:"1px solid rgba(201,168,76,0.35)",backdropFilter:"blur(12px)"},children:[e.jsx("div",{className:"px-5 pt-3 pb-2 text-[10px] tracking-[0.2em] uppercase",style:{color:Vd},children:"Suggestions"}),e.jsx("ul",{className:"max-h-80 overflow-y-auto",children:g.map((B,U)=>e.jsx("li",{children:e.jsxs("button",{type:"button",onMouseEnter:()=>d(U),onClick:()=>{t(B.value),o(!1)},className:"w-full flex items-center justify-between gap-3 px-5 py-3 text-left transition",style:{background:c===U?"rgba(201,168,76,0.12)":"transparent"},children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[B.type==="city"&&e.jsx(Si,{className:"h-4 w-4 shrink-0",style:{color:Vd}}),B.type==="neighborhood"&&e.jsx(Gi,{className:"h-4 w-4 shrink-0",style:{color:Vd}}),B.type==="zip"&&e.jsx(ua,{className:"h-4 w-4 shrink-0",style:{color:Vd}}),e.jsx("span",{className:"text-white/90 truncate",children:B.label})]}),e.jsxs("span",{className:"text-xs text-white/50 shrink-0",children:[B.count," ",B.count===1?"listing":"listings"]})]})},`${B.type}-${B.value}-${U}`))})]}),l&&s.trim()&&g.length===0&&e.jsx("div",{className:"mt-2 rounded-2xl px-5 py-4 text-sm text-white/70",style:{background:"rgba(13,13,13,0.96)",border:"1px solid rgba(201,168,76,0.25)"},children:"No matches yet — try a nearby city or ZIP."}),n&&e.jsxs("div",{className:"mt-4 p-6 rounded-2xl grid sm:grid-cols-2 md:grid-cols-4 gap-4 animate-fade-in",style:{background:"rgba(26,26,26,0.9)",border:"1px solid rgba(201,168,76,0.25)"},children:[e.jsxs("div",{children:[e.jsx("label",{className:"lu-eyebrow text-white/60 mb-2 block",children:"Status"}),e.jsxs(bs,{value:h.status||"all",onValueChange:B=>m({...h,status:B==="all"?"":B}),children:[e.jsx(ys,{className:"lu-input-dark",children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"all",children:"Any status"}),Object.entries(CIe).map(([B,U])=>e.jsx(We,{value:B,children:U},B))]})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"lu-eyebrow text-white/60 mb-2 block",children:"Type"}),e.jsxs(bs,{value:h.propertyType||"all",onValueChange:B=>m({...h,propertyType:B==="all"?"":B}),children:[e.jsx(ys,{className:"lu-input-dark",children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"all",children:"Any type"}),Object.entries(qws).map(([B,U])=>e.jsx(We,{value:B,children:U},B))]})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"lu-eyebrow text-white/60 mb-2 block",children:"Min Price"}),e.jsx(be,{type:"number",placeholder:"No min",value:h.minPrice,onChange:B=>m({...h,minPrice:B.target.value}),className:"lu-input-dark"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"lu-eyebrow text-white/60 mb-2 block",children:"Max Price"}),e.jsx(be,{type:"number",placeholder:"No max",value:h.maxPrice,onChange:B=>m({...h,maxPrice:B.target.value}),className:"lu-input-dark"})]}),j&&e.jsx("div",{className:"sm:col-span-2 md:col-span-4 flex justify-end",children:e.jsxs($,{variant:"ghost",size:"sm",onClick:_,className:"text-white/70 hover:text-white gap-1",children:[e.jsx(mr,{className:"h-4 w-4"})," Clear all"]})})]})]}),e.jsx("div",{className:"lu-hero-stats mt-14 grid grid-cols-3 gap-6 max-w-2xl",children:[{label:"Listings",value:((x==null?void 0:x.length)??0).toString()},{label:"Active Now",value:O.toString()},{label:"Luxury $1M+",value:P.toString()}].map(B=>e.jsxs("div",{children:[e.jsx("div",{className:"lu-serif text-4xl md:text-5xl",style:{color:FA},children:B.value}),e.jsx("div",{className:"lu-eyebrow text-white/60 mt-1",children:B.label})]},B.label))})]}),e.jsxs("div",{className:"absolute bottom-6 left-1/2 -translate-x-1/2 flex flex-col items-center gap-2 text-white/60",children:[e.jsx("span",{className:"lu-eyebrow",children:"Scroll"}),e.jsx(Go,{className:"h-4 w-4 animate-bounce"})]})]})]}),R.length>0&&e.jsx("section",{className:"py-8 overflow-hidden",style:{background:clt,borderTop:"1px solid rgba(201,168,76,0.15)",borderBottom:"1px solid rgba(201,168,76,0.15)"},children:e.jsx("div",{className:"lu-marquee whitespace-nowrap",children:[...R,...R,...R].map((B,U)=>e.jsxs("span",{className:"flex items-center gap-3 lu-serif text-2xl md:text-3xl text-white/40",children:[B,e.jsx("span",{className:"h-1.5 w-1.5 rounded-full",style:{background:Vd}})]},U))})}),M&&e.jsx("section",{id:"featured",className:"py-20 md:py-28",children:e.jsxs("div",{className:"max-w-7xl mx-auto px-6",children:[e.jsxs("div",{className:"flex items-end justify-between mb-10 md:mb-14",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[e.jsx(kn,{className:"h-4 w-4",style:{color:Vd}}),e.jsx("span",{className:"lu-eyebrow lu-gold",children:"Today's Featured Residence"})]}),e.jsxs("h2",{className:"lu-serif text-4xl md:text-5xl lg:text-6xl",children:["Today's ",e.jsx("span",{className:"italic",style:{color:FA},children:"standout"}),"."]})]}),e.jsx("div",{className:"hidden md:block h-px flex-1 mx-8 lu-gold-line"})]}),e.jsx(nr,{to:A(M),className:"group block",children:e.jsxs("div",{className:"grid lg:grid-cols-5 gap-6 lg:gap-10 items-stretch",children:[e.jsxs("div",{className:"lg:col-span-3 relative overflow-hidden rounded-2xl aspect-[4/3] bg-black",children:[(()=>{var U,G;const B=((U=M.photos)==null?void 0:U.find(H=>H.is_primary))||((G=M.photos)==null?void 0:G[0]);return B?e.jsx("img",{src:B.photo_url,alt:M.property_address||M.city,className:"w-full h-full object-cover lu-img-zoom"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(ua,{className:"h-16 w-16 text-white/20"})})})(),e.jsx("div",{className:"absolute top-5 left-5 px-4 py-1.5 rounded-full lu-eyebrow",style:{background:Vd,color:V7},children:CIe[M.status]||"Featured"})]}),e.jsxs("div",{className:"lg:col-span-2 flex flex-col justify-center",children:[e.jsxs("div",{className:"lu-eyebrow text-white/60 mb-4 flex items-center gap-2",children:[e.jsx(Si,{className:"h-3.5 w-3.5",style:{color:Vd}}),M.city,M.state?`, ${M.state}`:""]}),M.property_address&&e.jsx("h3",{className:"lu-serif text-3xl md:text-4xl mb-4 leading-tight",children:M.property_address}),e.jsx("div",{className:"lu-serif text-5xl md:text-6xl mb-6",style:{color:FA},children:v(M.price)}),e.jsxs("div",{className:"flex items-center gap-6 text-white/70 mb-8",children:[M.bedrooms&&e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(Yw,{className:"h-4 w-4",style:{color:Vd}}),M.bedrooms," bd"]}),M.bathrooms&&e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(p0,{className:"h-4 w-4",style:{color:Vd}}),M.bathrooms," ba"]}),M.square_footage&&e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(w_,{className:"h-4 w-4",style:{color:Vd}}),M.square_footage.toLocaleString()," sf"]})]}),M.description&&e.jsx("p",{className:"text-white/60 leading-relaxed mb-8 line-clamp-4",children:M.description}),e.jsxs("div",{className:"inline-flex items-center gap-3 lu-eyebrow group-hover:gap-5 transition-all",style:{color:Vd},children:["View Residence ",e.jsx(xi,{className:"h-4 w-4"})]})]})]})})]})}),e.jsx("section",{id:"collection",className:"py-20 md:py-28",style:{background:clt},children:e.jsxs("div",{className:"max-w-7xl mx-auto px-6",children:[e.jsxs("div",{className:"text-center mb-14",children:[e.jsxs("div",{className:"flex items-center justify-center gap-3 mb-4",children:[e.jsx("span",{className:"h-px w-10",style:{background:Vd}}),e.jsx("span",{className:"lu-eyebrow lu-gold",children:"The Collection"}),e.jsx("span",{className:"h-px w-10",style:{background:Vd}})]}),e.jsxs("h2",{className:"lu-serif text-4xl md:text-5xl lg:text-6xl mb-4",children:["Every home, ",e.jsx("span",{className:"italic",style:{color:FA},children:"carefully considered"}),"."]}),e.jsx("p",{className:"text-white/60 max-w-2xl mx-auto",children:"Browse the full catalogue of LevelUp-represented properties. Filter, refine, and find the one that feels like yours."})]}),y?e.jsx("div",{className:"grid sm:grid-cols-2 lg:grid-cols-3 gap-8",children:[...Array(6)].map((B,U)=>e.jsxs("div",{className:"space-y-3",children:[e.jsx(fn,{className:"aspect-[4/5] bg-white/5"}),e.jsx(fn,{className:"h-6 w-32 bg-white/5"}),e.jsx(fn,{className:"h-4 w-full bg-white/5"})]},U))}):I.length>0?e.jsx("div",{className:"grid sm:grid-cols-2 lg:grid-cols-3 gap-x-8 gap-y-14",children:I.map(B=>{var G,H,Y,se,ee;const U=((G=B.photos)==null?void 0:G.find(oe=>oe.is_primary))||((H=B.photos)==null?void 0:H[0]);return e.jsxs(nr,{to:A(B),className:"group lu-card-hover block",children:[e.jsxs("div",{className:"relative aspect-[4/5] overflow-hidden bg-black mb-5 rounded-lg",children:[U?e.jsx("img",{src:U.photo_url,alt:B.property_address||B.city,className:"w-full h-full object-cover lu-img-zoom"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(ua,{className:"h-12 w-12 text-white/20"})}),e.jsx("div",{className:"absolute inset-0 opacity-0 group-hover:opacity-100 transition-opacity",style:{background:"linear-gradient(180deg, transparent 40%, rgba(13,13,13,0.85) 100%)"}}),e.jsx("div",{className:"absolute top-4 left-4 px-3 py-1 lu-eyebrow rounded-full",style:{background:"rgba(13,13,13,0.75)",color:Vd,border:`1px solid ${Vd}`},children:CIe[B.status]}),e.jsxs("div",{className:"absolute bottom-4 left-4 right-4 flex items-center gap-4 text-white/90 text-sm opacity-0 group-hover:opacity-100 translate-y-2 group-hover:translate-y-0 transition-all",children:[B.bedrooms&&e.jsxs("span",{children:[B.bedrooms," bd"]}),B.bathrooms&&e.jsxs("span",{children:[B.bathrooms," ba"]}),B.square_footage&&e.jsxs("span",{children:[B.square_footage.toLocaleString()," sf"]})]})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"lu-eyebrow text-white/50 mb-2 flex items-center gap-2",children:[e.jsx(Si,{className:"h-3 w-3",style:{color:Vd}}),B.city,B.state?`, ${B.state}`:""]}),e.jsx("div",{className:"lu-serif text-2xl md:text-3xl mb-1",style:{color:FA},children:v(B.price)}),B.property_address&&e.jsx("p",{className:"text-white/70 text-sm truncate",children:B.property_address}),((Y=B.agent)==null?void 0:Y.name)&&e.jsxs("p",{className:"text-white/40 text-xs mt-3 flex items-center gap-2",children:[e.jsx(Gi,{className:"h-3 w-3"}),B.agent.name,(((se=B.agent.brokerage)==null?void 0:se.name)||B.agent.brokerage_name)&&e.jsxs("span",{className:"truncate",children:["· ",((ee=B.agent.brokerage)==null?void 0:ee.name)||B.agent.brokerage_name]})]})]})]},B.id)})}):e.jsxs("div",{className:"text-center py-20",children:[e.jsx("div",{className:"w-20 h-20 mx-auto mb-6 rounded-full flex items-center justify-center",style:{border:`1px solid ${Vd}`},children:e.jsx(ua,{className:"h-8 w-8",style:{color:Vd}})}),e.jsx("h3",{className:"lu-serif text-2xl mb-2",children:"No listings match yet"}),e.jsx("p",{className:"text-white/60 mb-6",children:"Adjust your search — or check back soon for new arrivals."}),j&&e.jsx($,{onClick:_,style:{background:Vd,color:V7},className:"hover:brightness-110",children:"Clear filters"})]})]})}),x&&x.length>0&&e.jsx("section",{id:"map",className:"py-20 md:py-28",children:e.jsxs("div",{className:"max-w-7xl mx-auto px-6",children:[e.jsx("div",{className:"flex flex-col md:flex-row md:items-end md:justify-between gap-4 mb-10",children:e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[e.jsx("span",{className:"h-px w-10",style:{background:Vd}}),e.jsx("span",{className:"lu-eyebrow lu-gold",children:"Explore"})]}),e.jsxs("h2",{className:"lu-serif text-4xl md:text-5xl",children:["Every listing, ",e.jsx("span",{className:"italic",style:{color:FA},children:"on the map"}),"."]})]})}),e.jsx("div",{className:"rounded-2xl overflow-hidden",style:{border:"1px solid rgba(201,168,76,0.2)"},children:e.jsx(Uws,{listings:x,isLoading:y})})]})}),e.jsxs("section",{className:"relative py-24 md:py-32 overflow-hidden lu-grain",children:[e.jsx("div",{className:"absolute inset-0",style:{background:`radial-gradient(ellipse at center, rgba(201,168,76,0.15) 0%, ${V7} 70%)`}}),e.jsxs("div",{className:"relative max-w-4xl mx-auto px-6 text-center",children:[e.jsxs("div",{className:"flex items-center justify-center gap-3 mb-6",children:[e.jsx("span",{className:"h-px w-10",style:{background:Vd}}),e.jsx("span",{className:"lu-eyebrow lu-gold",children:"For Agents"}),e.jsx("span",{className:"h-px w-10",style:{background:Vd}})]}),e.jsxs("h2",{className:"lu-serif text-4xl md:text-6xl mb-6 leading-tight",children:["Your listings deserve a",e.jsx("br",{}),e.jsx("span",{className:"italic",style:{color:FA},children:"stage this good"}),"."]}),e.jsx("p",{className:"text-white/70 text-lg mb-10 max-w-2xl mx-auto",children:"Join LevelUp and get every listing published to this collection — with a cinematic microsite, lead capture, and marketing tools that do the heavy lifting."}),e.jsxs("a",{href:"https://relevelup.com",target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-3 px-8 py-4 rounded-full font-medium transition hover:brightness-110",style:{background:Vd,color:V7},children:["Explore LevelUp",e.jsx(xi,{className:"h-4 w-4"})]})]})]}),e.jsx("footer",{className:"py-14",style:{background:"#080808",borderTop:"1px solid rgba(201,168,76,0.15)"},children:e.jsxs("div",{className:"max-w-7xl mx-auto px-6 flex flex-col md:flex-row items-center justify-between gap-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("img",{src:mSe,alt:"LevelUp",className:"h-6"}),e.jsx("span",{className:"h-4 w-px bg-white/20"}),e.jsx("span",{className:"lu-eyebrow lu-gold",children:"Listings"})]}),e.jsxs("p",{className:"text-white/40 text-sm",children:["© ",new Date().getFullYear()," LevelUp. All rights reserved."]}),e.jsx("a",{href:"https://relevelup.com",target:"_blank",rel:"noopener noreferrer",className:"text-white/60 hover:text-white text-sm transition",children:"relevelup.com →"})]})})]}),e.jsx(uws,{}),e.jsx(hws,{})]})}const Vws=k.lazy(()=>Ai(()=>import("./PublicHomeValue-C5rFSBIz.js"),[]));function Hws(){const s=Tu(),t=window.location.hostname;if(!(t==="listings.relevelup.com"||t.startsWith("listings.")))return null;const r=s.pathname.slice(1);return!r||r===""?e.jsx(QAt,{}):r==="home-value"||r==="whats-my-home-worth"?e.jsx(k.Suspense,{fallback:e.jsx("div",{}),children:e.jsx(Vws,{})}):r.startsWith("public/")?null:e.jsx(YAt,{slugOverride:r})}function nAe({card:s,variant:t}){const n=s.brokerage_display_name||s.brokerage_logo_url,r=s.team_name||s.team_logo_url;if(!n&&!r)return null;const a={standard:{container:"bg-slate-50 border border-slate-100",text:"text-slate-600",subtext:"text-slate-400"},luxury:{container:"bg-[#1e2636] border border-[#c9a84c]/10",text:"text-[#e2e8f0]",subtext:"text-[#4a5568]"},bold:{container:"bg-gray-50 border border-gray-100",text:"text-[#1a1a2e]",subtext:"text-gray-400"},classic:{container:"bg-white border border-[#d4cfc5] shadow-sm",text:"text-[#1b3a4b]",subtext:"text-[#a0aec0]"}}[t];return e.jsx("div",{className:`rounded-2xl p-4 mb-6 ${a.container}`,children:e.jsxs("div",{className:`flex flex-col items-center gap-3 ${n&&r?"divide-y divide-current/10":""}`,children:[n&&e.jsxs("div",{className:"flex flex-col items-center gap-1.5 w-full",children:[s.brokerage_logo_url&&e.jsx("img",{src:s.brokerage_logo_url,alt:s.brokerage_display_name||"Brokerage",style:{height:`${s.brokerage_logo_size||56}px`},className:"max-w-[280px] object-contain"}),s.brokerage_display_name&&!s.brokerage_logo_url&&e.jsx("p",{className:`text-sm font-medium ${a.text}`,children:s.brokerage_display_name})]}),r&&e.jsxs("div",{className:`flex flex-col items-center gap-1.5 w-full ${n?"pt-3":""}`,children:[s.team_logo_url&&e.jsx("img",{src:s.team_logo_url,alt:s.team_name||"Team",style:{height:`${s.team_logo_size||56}px`},className:"max-w-[280px] object-contain"}),s.team_name&&!s.team_logo_url&&e.jsx("p",{className:`text-sm font-medium ${a.text}`,children:s.team_name})]})]})})}const JAt=s=>pt({queryKey:["agent-card-public",s],queryFn:async()=>{if(!s)throw new Error("No slug provided");const{data:t,error:n}=await V.from("agent_cards").select("*").eq("slug",s).eq("is_published",!0).single();if(n)throw n;const{data:r}=await V.from("profiles").select("name, email, phone, brokerage_id").eq("id",t.user_id).single();let a=null;if(r!=null&&r.brokerage_id){const{data:o}=await V.from("brokerages").select("name").eq("id",r.brokerage_id).single();a=(o==null?void 0:o.name)||null}let i=null;try{const{data:o}=await V.from("profiles").select("avatar_url").eq("id",t.user_id).single();if(o!=null&&o.avatar_url)i=o.avatar_url;else{const{data:c}=await V.storage.from("avatars").list(`${t.user_id}`);if(c&&c.length>0){const{data:d}=V.storage.from("avatars").getPublicUrl(`${t.user_id}/${c[0].name}`);i=`${d.publicUrl}?t=${Date.now()}`}}}catch{}const l={...r||{name:null,email:null,phone:null,brokerage_id:null},email:t.display_email||(r==null?void 0:r.email)||null};return{...t,social_links:t.social_links||[],profile:l,brokerage_name:t.brokerage_display_name||a,avatar_url:i}},enabled:!!s}),Gws=()=>pt({queryKey:["agent-cards-admin"],queryFn:async()=>{const{data:s,error:t}=await V.from("agent_cards").select("*").order("created_at",{ascending:!1});if(t)throw t;return s}}),Wws=s=>pt({queryKey:["agent-card",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await V.from("agent_cards").select("*").eq("user_id",s).maybeSingle();if(n)throw n;return t},enabled:!!s}),eEt=()=>{const s=ls();return Nt({mutationFn:async t=>{const{data:n,error:r}=await V.from("agent_cards").insert(t).select().single();if(r)throw r;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["agent-cards-admin"]}),s.invalidateQueries({queryKey:["agent-card"]}),ae.success("Agent card created")},onError:t=>ae.error(t.message)})},tEt=()=>{const s=ls();return Nt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await V.from("agent_cards").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["agent-cards-admin"]}),s.invalidateQueries({queryKey:["agent-card"]}),ae.success("Agent card updated")},onError:t=>ae.error(t.message)})},Md=async(s,t,n,r)=>{const a=new URLSearchParams(window.location.search);await V.from("agent_card_interactions").insert({card_id:s,interaction_type:t,interaction_detail:n||null,referrer:document.referrer||null,user_agent:navigator.userAgent||null,utm_source:a.get("utm_source")||null,utm_medium:a.get("utm_medium")||null,utm_campaign:a.get("utm_campaign")||null,metadata:{}})},Kws=async(s,t)=>{const{error:n}=await V.from("agent_card_leads").insert({card_id:s,...t});if(n)throw n},sEt=s=>pt({queryKey:["agent-card-analytics",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await V.from("agent_card_interactions").select("interaction_type, interaction_detail, created_at").eq("card_id",s).order("created_at",{ascending:!1}).limit(500);if(n)throw n;const{data:r,error:a}=await V.from("agent_card_leads").select("*").eq("card_id",s).order("created_at",{ascending:!1});if(a)throw a;const i=(t==null?void 0:t.filter(c=>c.interaction_type==="card_view").length)||0,l=(t==null?void 0:t.filter(c=>c.interaction_type==="button_click").length)||0,o=(t==null?void 0:t.filter(c=>c.interaction_type==="contact_saved").length)||0;return{views:i,clicks:l,saves:o,leads:r||[],interactions:t||[]}},enabled:!!s});function rAe({open:s,onOpenChange:t,cardId:n,type:r,agentName:a}){const[i,l]=k.useState(""),[o,c]=k.useState(""),[d,u]=k.useState(""),[h,m]=k.useState(""),[p,g]=k.useState(""),[x,y]=k.useState(!1),v=async _=>{if(_.preventDefault(),!i.trim()){ae.error("Please enter your name");return}y(!0);try{await Kws(n,{lead_type:r,name:i.trim(),email:o.trim()||void 0,phone:d.trim()||void 0,message:p.trim()||void 0,intent:h||void 0}),Md(n,"lead_submitted",r),V.functions.invoke("card-lead-notify",{body:{cardId:n,leadType:r,name:i.trim(),email:o.trim()||void 0,phone:d.trim()||void 0,message:p.trim()||void 0,intent:h||void 0}}).catch(j=>console.error("Card lead notify failed:",j)),ae.success(r==="booking"?"Request sent! They'll be in touch soon.":r==="connect"?"Info shared! They'll be in touch soon.":"Referral submitted! Thank you."),t(!1),l(""),c(""),u(""),m(""),g("")}catch{ae.error("Something went wrong. Please try again.")}finally{y(!1)}};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"sm:max-w-md rounded-2xl",children:[e.jsxs(Vs,{children:[e.jsx($s,{children:r==="booking"?"Book a Call":r==="connect"?"Connect with Me":"Refer a Friend"}),e.jsx(Cr,{children:r==="booking"?`Let ${a} know you'd like to connect.`:r==="connect"?`Share your info and ${a} will reach out.`:`Know someone who could use ${a}'s help?`})]}),e.jsxs("form",{onSubmit:v,className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(re,{htmlFor:"lead-name",children:"Name *"}),e.jsx(be,{id:"lead-name",value:i,onChange:_=>l(_.target.value),placeholder:"Your name",required:!0})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"lead-phone",children:"Phone"}),e.jsx(be,{id:"lead-phone",type:"tel",value:d,onChange:_=>u(_.target.value),placeholder:"(555) 123-4567"})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"lead-email",children:"Email"}),e.jsx(be,{id:"lead-email",type:"email",value:o,onChange:_=>c(_.target.value),placeholder:"you@example.com"})]}),r==="booking"&&e.jsxs("div",{children:[e.jsx(re,{htmlFor:"lead-intent",children:"I'm looking to..."}),e.jsxs(bs,{value:h,onValueChange:m,children:[e.jsx(ys,{children:e.jsx(_s,{placeholder:"Select one"})}),e.jsxs(vs,{children:[e.jsx(We,{value:"buy",children:"Buy a home"}),e.jsx(We,{value:"sell",children:"Sell my home"}),e.jsx(We,{value:"both",children:"Buy & Sell"}),e.jsx(We,{value:"other",children:"Something else"})]})]})]}),r!=="connect"&&e.jsxs("div",{children:[e.jsx(re,{htmlFor:"lead-message",children:r==="referral"?"Tell us about them":"Message (optional)"}),e.jsx(be,{id:"lead-message",value:p,onChange:_=>g(_.target.value),placeholder:r==="referral"?"Their name, phone, situation...":"Anything you'd like us to know"})]}),e.jsx($,{type:"submit",className:"w-full rounded-2xl",disabled:x,children:x?"Sending...":"Submit"})]})]})})}const Yws=s=>pt({queryKey:["card-blocks",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await V.from("card_blocks").select("*").eq("card_id",s).eq("is_visible",!0).order("sort_order",{ascending:!0});if(n)throw n;return t||[]},enabled:!!s}),Zws=s=>pt({queryKey:["card-blocks-all",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await V.from("card_blocks").select("*").eq("card_id",s).order("sort_order",{ascending:!0});if(n)throw n;return t||[]},enabled:!!s}),Xws=()=>{const s=ls();return Nt({mutationFn:async t=>{const{data:n,error:r}=await V.from("card_blocks").insert(t).select().single();if(r)throw r;return n},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["card-blocks",n.card_id]}),s.invalidateQueries({queryKey:["card-blocks-all",n.card_id]}),ae.success("Block added")},onError:t=>ae.error(t.message)})},Qws=()=>{const s=ls();return Nt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await V.from("card_blocks").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["card-blocks"]}),s.invalidateQueries({queryKey:["card-blocks-all"]}),ae.success("Block updated")},onError:t=>ae.error(t.message)})},Jws=()=>{const s=ls();return Nt({mutationFn:async t=>{const{error:n}=await V.from("card_blocks").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["card-blocks"]}),s.invalidateQueries({queryKey:["card-blocks-all"]}),ae.success("Block removed")},onError:t=>ae.error(t.message)})};function ejs(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 tjs(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 sjs={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 njs({block:s,variant:t}){const n=s.config;if(!n.video_url)return null;const r=n.video_url.includes("mediadelivery.net")||n.video_url.includes("bunnycdn.com"),a=tjs(n.video_url),i=r||!!a,l=r?ejs(n.video_url):a||n.video_url;return e.jsx("div",{className:sjs[t],children:i?e.jsx("div",{style:{position:"relative",paddingTop:"56.25%"},children:e.jsx("iframe",{src:l,loading:"lazy",style:{border:0,position:"absolute",top:0,left:0,width:"100%",height:"100%"},allow:"accelerometer; gyroscope; autoplay; encrypted-media; picture-in-picture",allowFullScreen:!0})}):e.jsx("video",{src:n.video_url,controls:!0,className:"w-full",preload:"metadata"})})}const rjs={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 ajs({block:s,variant:t}){const r=s.config.testimonials||[],[a,i]=k.useState(0);if(r.length===0)return null;const l=rjs[t],o=r[a];return e.jsxs("div",{className:l.container,children:[e.jsxs("div",{className:l.card,children:[e.jsx(ik,{className:"h-4 w-4 mb-2 opacity-30"}),e.jsxs("p",{className:`${l.quote} mb-3`,children:['"',o.quote,'"']}),e.jsxs("div",{children:[e.jsx("p",{className:l.name,children:o.name}),o.role&&e.jsx("p",{className:l.role,children:o.role})]})]}),r.length>1&&e.jsxs("div",{className:"flex items-center justify-center gap-3 mt-3",children:[e.jsx("button",{onClick:()=>i(c=>(c-1+r.length)%r.length),className:l.nav,children:e.jsx(Ld,{className:"h-4 w-4"})}),e.jsx("div",{className:"flex gap-1.5",children:r.map((c,d)=>e.jsx("div",{className:`h-1.5 w-1.5 rounded-full transition-colors cursor-pointer ${d===a?l.dot:l.dotInactive}`,onClick:()=>i(d)},d))}),e.jsx("button",{onClick:()=>i(c=>(c+1)%r.length),className:l.nav,children:e.jsx(fi,{className:"h-4 w-4"})})]})]})}const ijs={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 ojs({block:s,variant:t}){const r=s.config.tags||[];if(r.length===0)return null;const a=ijs[t];return e.jsx("div",{className:a.container,children:r.map((i,l)=>e.jsx("span",{className:a.tag,children:i},l))})}const ljs={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 cjs({block:s,cardId:t,variant:n}){const a=s.config.links||[];if(a.length===0)return null;const i=ljs[n];return e.jsx("div",{className:i.container,children:a.map((l,o)=>e.jsxs("a",{href:l.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>Md(t,"button_click",`custom_link_${l.label}`),className:i.link,children:[e.jsx("span",{children:l.label}),e.jsx(Ir,{className:`h-4 w-4 ${i.icon}`})]},o))})}const j7e={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 djs({path:s,color:t,size:n=20}){return e.jsx("svg",{viewBox:"0 0 24 24",width:n,height:n,fill:t,children:e.jsx("path",{d:s})})}const ujs={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 hjs({block:s,cardId:t,variant:n}){const a=s.config.platforms||[],i=ujs[n];return a.length===0?null:e.jsxs("div",{className:i.container,children:[e.jsx("h3",{className:i.title,children:"Follow Me"}),e.jsx("div",{className:"flex flex-wrap gap-3 justify-center",children:a.map((l,o)=>{const c=j7e[l.platform.toLowerCase()];return!c||!l.url?null:e.jsx("a",{href:l.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>Md(t,"button_click",`social_${l.platform}`),className:i.linkClass,title:c.label,children:e.jsx(djs,{path:c.icon,color:c.color})},o)})})]})}function aAe({cardId:s,variant:t}){const{data:n}=Yws(s);if(!n||n.length===0)return null;const r=n.filter(l=>l.block_type==="social_media"&&l.is_visible),a=n.filter(l=>l.block_type!=="social_media"),i=r.length>0?{...r[0],config:{platforms:r.flatMap(l=>l.config.platforms||[])}}:null;return n.findIndex(l=>l.block_type==="social_media"),e.jsxs(e.Fragment,{children:[a.map(l=>{switch(l.block_type){case"video_intro":return e.jsx(njs,{block:l,variant:t},l.id);case"testimonials":return e.jsx(ajs,{block:l,variant:t},l.id);case"specialties":return e.jsx(ojs,{block:l,variant:t},l.id);case"custom_links":return e.jsx(cjs,{block:l,cardId:s,variant:t},l.id);default:return null}}),i&&e.jsx(hjs,{block:i,cardId:s,variant:t})]})}async function mjs(s){try{const t=await fetch(s);if(!t.ok)return null;const n=await t.blob(),r=n.type||"image/jpeg";return new Promise(a=>{const i=new FileReader;i.onloadend=()=>{const o=i.result.split(",")[1];a({base64:o,mimeType:r})},i.onerror=()=>a(null),i.readAsDataURL(n)})}catch{return null}}function fjs(s){const t=s.trim().split(/\s+/);if(t.length<=1)return{first:t[0]||"",last:""};const n=t.pop();return{first:t.join(" "),last:n}}async function iAe(s){const{first:t,last:n}=fjs(s.name),r=["BEGIN:VCARD","VERSION:3.0",`FN:${s.name}`,`N:${n};${t};;;`];if(s.phone&&r.push(`TEL;TYPE=CELL:${s.phone}`),s.email&&r.push(`EMAIL;TYPE=INTERNET:${s.email}`),s.brokerage&&r.push(`ORG:${s.brokerage}`),r.push(`URL:${s.cardUrl}`),s.avatarUrl){const o=await mjs(s.avatarUrl);if(o){const d={"image/jpeg":"JPEG","image/jpg":"JPEG","image/png":"PNG","image/gif":"GIF","image/webp":"JPEG"}[o.mimeType]||"JPEG";r.push(`PHOTO;ENCODING=b;TYPE=${d}:${o.base64}`)}}r.push("END:VCARD");const a=new Blob([r.join(`\r `)],{type:"text/vcard"}),i=URL.createObjectURL(a),l=document.createElement("a");l.href=i,l.download=`${s.name.replace(/\s+/g,"_")}.vcf`,l.click(),URL.revokeObjectURL(i),ae.success("Contact saved!")}function pjs({card:s}){var v;const[t,n]=k.useState(!1),[r,a]=k.useState("booking"),i=((v=s.profile)==null?void 0:v.name)||"Agent",l=i.split(" ").map(_=>_[0]).join("").toUpperCase().slice(0,2),o=(_,j)=>{Md(s.id,"button_click",_),j()},c=()=>o("call",()=>{var _;(_=s.profile)!=null&&_.phone?window.location.href=`tel:${s.profile.phone}`:ae.error("Phone number not available")}),d=()=>o("text",()=>{var _;(_=s.profile)!=null&&_.phone?window.location.href=`sms:${s.profile.phone}`:ae.error("Phone number not available")}),u=()=>o("email",()=>{var _;(_=s.profile)!=null&&_.email?window.location.href=`mailto:${s.profile.email}`:ae.error("Email not available")}),h=()=>{s.booking_url?o("book",()=>window.open(s.booking_url,"_blank")):(a("booking"),n(!0),Md(s.id,"button_click","book"))},m=()=>{var _,j;Md(s.id,"contact_saved"),iAe({name:i,phone:(_=s.profile)==null?void 0:_.phone,email:(j=s.profile)==null?void 0:j.email,brokerage:s.brokerage_name,avatarUrl:s.avatar_url,cardUrl:window.location.href})},p=async()=>{Md(s.id,"share_event");const _=`https://cards.relevelup.com/${s.slug}`,j="Here's my contact card — save it so we can stay in touch.";if(navigator.share)try{await navigator.share({title:`${i}`,text:j,url:_})}catch{}else await navigator.clipboard.writeText(_),ae.success("Link copied!")},g=()=>{a("referral"),n(!0),Md(s.id,"button_click","refer")},x=()=>{a("connect"),n(!0),Md(s.id,"button_click","connect")},y={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(Wa,{className:"h-28 w-28 mx-auto mb-4 ring-4 ring-white shadow-lg",children:[e.jsx(eo,{src:s.avatar_url||void 0,alt:i}),e.jsx(Ka,{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($,{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(ka,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs font-medium",children:"Call"})]}),e.jsxs($,{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(bo,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs font-medium",children:"Text"})]}),e.jsxs($,{onClick:u,className:"flex flex-col items-center gap-1.5 h-auto py-4 bg-primary hover:bg-primary/90 text-primary-foreground rounded-2xl shadow-sm",children:[e.jsx(pn,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs font-medium",children:"Email"})]})]}),e.jsxs($,{onClick:h,className:"w-full h-12 text-base font-semibold rounded-2xl shadow-sm mb-6",variant:"outline",children:[e.jsx(ha,{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(ri,{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(nAe,{card:s,variant:"standard"}),e.jsx(aAe,{cardId:s.id,variant:"standard"}),e.jsxs("div",{className:"space-y-2 mb-6",children:[s.show_save_contact&&e.jsxs($,{variant:"ghost",onClick:m,className:"w-full justify-start h-12 rounded-2xl text-slate-700 hover:bg-slate-100",children:[e.jsx(ji,{className:"h-4 w-4 mr-3 text-primary"}),"Save Contact"]}),s.show_leave_review&&s.review_source_url&&e.jsxs($,{variant:"ghost",onClick:()=>{Md(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(ri,{className:"h-4 w-4 mr-3 text-amber-500"}),"Leave a Review"]}),s.show_refer_friend&&e.jsxs($,{variant:"ghost",onClick:g,className:"w-full justify-start h-12 rounded-2xl text-slate-700 hover:bg-slate-100",children:[e.jsx(Xn,{className:"h-4 w-4 mr-3 text-primary"}),"Refer a Friend"]}),e.jsxs($,{variant:"ghost",onClick:x,className:"w-full justify-start h-12 rounded-2xl text-slate-700 hover:bg-slate-100",children:[e.jsx(Pl,{className:"h-4 w-4 mr-3 text-primary"}),"Connect with Me"]}),e.jsxs($,{variant:"ghost",onClick:p,className:"w-full justify-start h-12 rounded-2xl text-slate-700 hover:bg-slate-100",children:[e.jsx(ou,{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((_,j)=>e.jsx("a",{href:_.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>Md(s.id,"button_click",`social_${_.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:y[_.platform.toLowerCase()]||"🔗"},j))}),e.jsx("div",{className:"text-center",children:e.jsx("p",{className:"text-xs text-slate-400",children:"Powered by LevelUp"})})]}),e.jsx(rAe,{open:t,onOpenChange:n,cardId:s.id,type:r,agentName:i})]})}function gjs({card:s}){var v;const[t,n]=k.useState(!1),[r,a]=k.useState("booking"),i=((v=s.profile)==null?void 0:v.name)||"Agent",l=i.split(" ").map(_=>_[0]).join("").toUpperCase().slice(0,2),o=(_,j)=>{Md(s.id,"button_click",_),j()},c=()=>o("call",()=>{var _;(_=s.profile)!=null&&_.phone?window.location.href=`tel:${s.profile.phone}`:ae.error("Phone number not available")}),d=()=>o("text",()=>{var _;(_=s.profile)!=null&&_.phone?window.location.href=`sms:${s.profile.phone}`:ae.error("Phone number not available")}),u=()=>o("email",()=>{var _;(_=s.profile)!=null&&_.email?window.location.href=`mailto:${s.profile.email}`:ae.error("Email not available")}),h=()=>{s.booking_url?o("book",()=>window.open(s.booking_url,"_blank")):(a("booking"),n(!0),Md(s.id,"button_click","book"))},m=()=>{var _,j;Md(s.id,"contact_saved"),iAe({name:i,phone:(_=s.profile)==null?void 0:_.phone,email:(j=s.profile)==null?void 0:j.email,brokerage:s.brokerage_name,avatarUrl:s.avatar_url,cardUrl:window.location.href})},p=async()=>{Md(s.id,"share_event");const _=`https://cards.relevelup.com/${s.slug}`,j="Here's my contact card — save it so we can stay in touch.";if(navigator.share)try{await navigator.share({title:`${i}`,text:j,url:_})}catch{}else await navigator.clipboard.writeText(_),ae.success("Link copied!")},g=()=>{a("referral"),n(!0),Md(s.id,"button_click","refer")},x=()=>{a("connect"),n(!0),Md(s.id,"button_click","connect")},y={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(Wa,{className:"h-32 w-32 mx-auto mb-5 ring-2 ring-[#c9a84c]/40 shadow-2xl",children:[e.jsx(eo,{src:s.avatar_url||void 0,alt:i}),e.jsx(Ka,{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:ka,label:"Call",handler:c},{icon:bo,label:"Text",handler:d},{icon:pn,label:"Email",handler:u}].map(({icon:_,label:j,handler:C})=>e.jsxs("button",{onClick:C,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(_,{className:"h-5 w-5 text-[#c9a84c]"}),e.jsx("span",{className:"text-xs font-medium text-[#e2e8f0]",children:j})]},j))}),e.jsxs("button",{onClick:h,className:"w-full h-12 text-base font-semibold rounded-xl mb-6 bg-gradient-to-r from-[#c9a84c] to-[#e8d48b] text-[#0f1419] hover:opacity-90 transition-opacity flex items-center justify-center gap-2",children:[e.jsx(ha,{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(ri,{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(nAe,{card:s,variant:"luxury"}),e.jsx(aAe,{cardId:s.id,variant:"luxury"}),e.jsxs("div",{className:"space-y-1 mb-6",children:[s.show_save_contact&&e.jsxs("button",{onClick:m,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(ji,{className:"h-4 w-4 text-[#c9a84c]"})," Save Contact"]}),s.show_leave_review&&s.review_source_url&&e.jsxs("button",{onClick:()=>{Md(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(ri,{className:"h-4 w-4 text-[#c9a84c]"})," Leave a Review"]}),s.show_refer_friend&&e.jsxs("button",{onClick:g,className:"w-full flex items-center gap-3 h-12 px-4 rounded-xl text-[#e2e8f0] hover:bg-[#1e2636] transition-colors text-sm",children:[e.jsx(Xn,{className:"h-4 w-4 text-[#c9a84c]"})," Refer a Friend"]}),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(Pl,{className:"h-4 w-4 text-[#c9a84c]"})," Connect with Me"]}),e.jsxs("button",{onClick:p,className:"w-full flex items-center gap-3 h-12 px-4 rounded-xl text-[#e2e8f0] hover:bg-[#1e2636] transition-colors text-sm",children:[e.jsx(ou,{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((_,j)=>e.jsx("a",{href:_.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>Md(s.id,"button_click",`social_${_.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:y[_.platform.toLowerCase()]||"🔗"},j))}),e.jsx("div",{className:"text-center",children:e.jsx("p",{className:"text-xs text-[#4a5568]",children:"Powered by LevelUp"})})]}),e.jsx(rAe,{open:t,onOpenChange:n,cardId:s.id,type:r,agentName:i})]})}function xjs({card:s}){var j,C,A,M;const[t,n]=k.useState(!1),[r,a]=k.useState("booking"),i=((j=s.profile)==null?void 0:j.name)||"Agent",l=i.split(" ").map(I=>I[0]).join("").toUpperCase().slice(0,2),o={accent:((C=s.bold_theme_colors)==null?void 0:C.accent)||"#ff5722",dark:((A=s.bold_theme_colors)==null?void 0:A.dark)||"#1a1a2e",button:((M=s.bold_theme_colors)==null?void 0:M.button)||"#ff5722"},c=(I,P)=>{const R=parseInt(I.replace("#",""),16),O=Math.max(0,(R>>16)-P),B=Math.max(0,(R>>8&255)-P),U=Math.max(0,(R&255)-P);return`#${(O<<16|B<<8|U).toString(16).padStart(6,"0")}`};c(o.accent,25),c(o.dark,-20),c(o.button,25);const d=(I,P)=>{Md(s.id,"button_click",I),P()},u=()=>d("call",()=>{var I;(I=s.profile)!=null&&I.phone?window.location.href=`tel:${s.profile.phone}`:ae.error("Phone number not available")}),h=()=>d("text",()=>{var I;(I=s.profile)!=null&&I.phone?window.location.href=`sms:${s.profile.phone}`:ae.error("Phone number not available")}),m=()=>d("email",()=>{var I;(I=s.profile)!=null&&I.email?window.location.href=`mailto:${s.profile.email}`:ae.error("Email not available")}),p=()=>{s.booking_url?d("book",()=>window.open(s.booking_url,"_blank")):(a("booking"),n(!0),Md(s.id,"button_click","book"))},g=()=>{var I,P;Md(s.id,"contact_saved"),iAe({name:i,phone:(I=s.profile)==null?void 0:I.phone,email:(P=s.profile)==null?void 0:P.email,brokerage:s.brokerage_name,avatarUrl:s.avatar_url,cardUrl:window.location.href})},x=async()=>{Md(s.id,"share_event");const I=`https://cards.relevelup.com/${s.slug}`,P="Here's my contact card — save it so we can stay in touch.";if(navigator.share)try{await navigator.share({title:`${i}`,text:P,url:I})}catch{}else await navigator.clipboard.writeText(I),ae.success("Link copied!")},y=()=>{a("referral"),n(!0),Md(s.id,"button_click","refer")},v=()=>{a("connect"),n(!0),Md(s.id,"button_click","connect")},_={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(Wa,{className:"h-28 w-28 mx-auto mb-4 shadow-2xl",style:{boxShadow:`0 0 0 4px ${o.accent}`},children:[e.jsx(eo,{src:s.avatar_url||void 0,alt:i}),e.jsx(Ka,{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:ka,label:"Call",handler:u},{icon:bo,label:"Text",handler:h},{icon:pn,label:"Email",handler:m}].map(({icon:I,label:P,handler:R})=>e.jsxs("button",{onClick:R,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(I,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs",children:P})]},P))}),e.jsxs("button",{onClick:p,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(ha,{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(ri,{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(nAe,{card:s,variant:"bold"}),e.jsx(aAe,{cardId:s.id,variant:"bold"}),e.jsxs("div",{className:"space-y-1 mb-6",children:[s.show_save_contact&&e.jsxs("button",{onClick:g,className:"w-full flex items-center gap-3 h-12 px-4 rounded-2xl hover:bg-gray-100 transition-colors text-sm font-bold",style:{color:o.dark},children:[e.jsx(ji,{className:"h-4 w-4",style:{color:o.accent}})," Save Contact"]}),s.show_leave_review&&s.review_source_url&&e.jsxs("button",{onClick:()=>{Md(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(ri,{className:"h-4 w-4",style:{color:o.accent}})," Leave a Review"]}),s.show_refer_friend&&e.jsxs("button",{onClick:y,className:"w-full flex items-center gap-3 h-12 px-4 rounded-2xl hover:bg-gray-100 transition-colors text-sm font-bold",style:{color:o.dark},children:[e.jsx(Xn,{className:"h-4 w-4",style:{color:o.accent}})," Refer a Friend"]}),e.jsxs("button",{onClick:v,className:"w-full flex items-center gap-3 h-12 px-4 rounded-2xl hover:bg-gray-100 transition-colors text-sm font-bold",style:{color:o.dark},children:[e.jsx(Pl,{className:"h-4 w-4",style:{color:o.accent}})," Connect with Me"]}),e.jsxs("button",{onClick:x,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(ou,{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((I,P)=>e.jsx("a",{href:I.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>Md(s.id,"button_click",`social_${I.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:_[I.platform.toLowerCase()]||"🔗"},P))})]}),e.jsx("div",{className:"text-center py-6",children:e.jsx("p",{className:"text-xs text-white/50",children:"Powered by LevelUp"})})]}),e.jsx(rAe,{open:t,onOpenChange:n,cardId:s.id,type:r,agentName:i})]})}function yjs({card:s}){var v;const[t,n]=k.useState(!1),[r,a]=k.useState("booking"),i=((v=s.profile)==null?void 0:v.name)||"Agent",l=i.split(" ").map(_=>_[0]).join("").toUpperCase().slice(0,2),o=(_,j)=>{Md(s.id,"button_click",_),j()},c=()=>o("call",()=>{var _;(_=s.profile)!=null&&_.phone?window.location.href=`tel:${s.profile.phone}`:ae.error("Phone number not available")}),d=()=>o("text",()=>{var _;(_=s.profile)!=null&&_.phone?window.location.href=`sms:${s.profile.phone}`:ae.error("Phone number not available")}),u=()=>o("email",()=>{var _;(_=s.profile)!=null&&_.email?window.location.href=`mailto:${s.profile.email}`:ae.error("Email not available")}),h=()=>{s.booking_url?o("book",()=>window.open(s.booking_url,"_blank")):(a("booking"),n(!0),Md(s.id,"button_click","book"))},m=()=>{var _,j;Md(s.id,"contact_saved"),iAe({name:i,phone:(_=s.profile)==null?void 0:_.phone,email:(j=s.profile)==null?void 0:j.email,brokerage:s.brokerage_name,avatarUrl:s.avatar_url,cardUrl:window.location.href})},p=async()=>{Md(s.id,"share_event");const _=`https://cards.relevelup.com/${s.slug}`,j="Here's my contact card — save it so we can stay in touch.";if(navigator.share)try{await navigator.share({title:`${i}`,text:j,url:_})}catch{}else await navigator.clipboard.writeText(_),ae.success("Link copied!")},g=()=>{a("referral"),n(!0),Md(s.id,"button_click","refer")},x=()=>{a("connect"),n(!0),Md(s.id,"button_click","connect")},y={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(Wa,{className:"h-28 w-28 mx-auto mb-4 ring-4 ring-white shadow-lg",children:[e.jsx(eo,{src:s.avatar_url||void 0,alt:i}),e.jsx(Ka,{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:ka,label:"Call",handler:c},{icon:bo,label:"Text",handler:d},{icon:pn,label:"Email",handler:u}].map(({icon:_,label:j,handler:C})=>e.jsxs("button",{onClick:C,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(_,{className:"h-5 w-5 text-[#1b3a4b]"}),e.jsx("span",{className:"text-xs font-semibold text-[#1b3a4b]",children:j})]},j))}),e.jsxs("button",{onClick:h,className:"w-full h-12 text-base font-semibold rounded-lg mb-6 bg-[#1b3a4b] hover:bg-[#264d61] text-white transition-colors flex items-center justify-center gap-2 shadow-sm",children:[e.jsx(ha,{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(ri,{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(nAe,{card:s,variant:"classic"}),e.jsx(aAe,{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:m,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(ji,{className:"h-4 w-4 text-[#5a7a6f]"})," Save Contact"]}),s.show_leave_review&&s.review_source_url&&e.jsxs("button",{onClick:()=>{Md(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(ri,{className:"h-4 w-4 text-[#d4a843]"})," Leave a Review"]}),s.show_refer_friend&&e.jsxs("button",{onClick:g,className:"w-full flex items-center gap-3 h-12 px-4 text-[#1b3a4b] hover:bg-[#f5f1eb] transition-colors text-sm font-medium",children:[e.jsx(Xn,{className:"h-4 w-4 text-[#5a7a6f]"})," Refer a Friend"]}),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(Pl,{className:"h-4 w-4 text-[#5a7a6f]"})," Connect with Me"]}),e.jsxs("button",{onClick:p,className:"w-full flex items-center gap-3 h-12 px-4 text-[#1b3a4b] hover:bg-[#f5f1eb] transition-colors text-sm font-medium",children:[e.jsx(ou,{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((_,j)=>e.jsx("a",{href:_.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>Md(s.id,"button_click",`social_${_.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:y[_.platform.toLowerCase()]||"🔗"},j))}),e.jsx("div",{className:"text-center",children:e.jsx("p",{className:"text-xs text-[#a0aec0]",children:"Powered by LevelUp"})})]}),e.jsx(rAe,{open:t,onOpenChange:n,cardId:s.id,type:r,agentName:i})]})}function EGe({card:s}){switch(s.theme){case"luxury":return e.jsx(gjs,{card:s});case"bold":return e.jsx(xjs,{card:s});case"classic":return e.jsx(yjs,{card:s});case"standard":default:return e.jsx(pjs,{card:s})}}function vjs(){const s=Tu();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(bjs,{slug:t})}function bjs({slug:s}){return e.jsx(_js,{slug:s})}function _js({slug:s}){var i;const{data:t,isLoading:n,error:r}=JAt(s);if(k.useEffect(()=>{t!=null&&t.id&&Md(t.id,"card_view")},[t==null?void 0:t.id]),n)return e.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white flex items-center justify-center",children:e.jsxs("div",{className:"w-full max-w-md mx-auto p-6 space-y-6",children:[e.jsxs("div",{className:"flex flex-col items-center gap-4",children:[e.jsx(fn,{className:"h-28 w-28 rounded-full"}),e.jsx(fn,{className:"h-6 w-48"}),e.jsx(fn,{className:"h-4 w-36"})]}),e.jsx(fn,{className:"h-12 w-full"}),e.jsx(fn,{className:"h-12 w-full"})]})});if(r||!t)return e.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white flex items-center justify-center p-6",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"text-2xl font-bold text-slate-800 mb-2",children:"Card Not Found"}),e.jsx("p",{className:"text-slate-500",children:"This agent card doesn't exist or isn't published yet."})]})});const a=((i=t.profile)==null?void 0:i.name)||"Agent";return e.jsxs(e.Fragment,{children:[e.jsxs(Sc,{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(EGe,{card:t})]})}function nEt({presentationId:s,ctaLabel:t,agentName:n,prefillName:r,prefillEmail:a,prefillPhone:i}){const[l,o]=k.useState(r||""),[c,d]=k.useState(a||""),[u,h]=k.useState(i||""),[m,p]=k.useState(""),[g,x]=k.useState(""),[y,v]=k.useState(!1),[_,j]=k.useState(!1),C=async A=>{if(A.preventDefault(),!l.trim()){ae.error("Please enter your name");return}v(!0);try{const{error:M}=await V.from("smart_presentation_leads").insert({presentation_id:s,name:l.trim(),email:c.trim()||null,phone:u.trim()||null,intent:m||null,message:g.trim()||null});if(M)throw M;try{await V.rpc("log_presentation_view",{p_presentation_id:s,p_section_index:null,p_cta_clicked:!0,p_ip_hash:null,p_user_agent:navigator.userAgent,p_referrer:null})}catch{}V.functions.invoke("presentation-lead-notify",{body:{presentationId:s,name:l.trim(),email:c.trim()||void 0,phone:u.trim()||void 0,intent:m||void 0,message:g.trim()||void 0}}).catch(I=>console.error("Presentation lead notify failed:",I)),j(!0)}catch{ae.error("Something went wrong. Please try again.")}finally{v(!1)}};return _?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(ma,{className:"h-8 w-8 text-emerald-600"})}),e.jsx("h3",{className:"text-xl font-semibold text-gray-900 mb-2",children:"Thank you!"}),e.jsx("p",{className:"text-gray-500",children:n?`${n} will be in touch soon.`:"We'll be in touch soon."})]}):e.jsxs("form",{onSubmit:C,className:"space-y-4 max-w-md mx-auto",children:[e.jsxs("div",{children:[e.jsx(re,{htmlFor:"pres-lead-name",children:"Name *"}),e.jsx(be,{id:"pres-lead-name",value:l,onChange:A=>o(A.target.value),placeholder:"Your name",required:!0})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"pres-lead-phone",children:"Phone"}),e.jsx(be,{id:"pres-lead-phone",type:"tel",value:u,onChange:A=>h(A.target.value),placeholder:"(555) 123-4567"})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"pres-lead-email",children:"Email"}),e.jsx(be,{id:"pres-lead-email",type:"email",value:c,onChange:A=>d(A.target.value),placeholder:"you@example.com"})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"pres-lead-intent",children:"I'm looking to..."}),e.jsxs(bs,{value:m,onValueChange:p,children:[e.jsx(ys,{children:e.jsx(_s,{placeholder:"Select one"})}),e.jsxs(vs,{children:[e.jsx(We,{value:"buy",children:"Buy a home"}),e.jsx(We,{value:"sell",children:"Sell my home"}),e.jsx(We,{value:"both",children:"Buy & Sell"}),e.jsx(We,{value:"other",children:"Something else"})]})]})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"pres-lead-message",children:"Message (optional)"}),e.jsx(be,{id:"pres-lead-message",value:g,onChange:A=>x(A.target.value),placeholder:"Anything you'd like us to know"})]}),e.jsx($,{type:"submit",className:"w-full text-lg py-6 rounded-xl bg-blue-600 hover:bg-blue-700 text-white shadow-lg",disabled:y,children:y?"Sending...":t})]})}function wjs(){const s=Tu();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(jjs,{shareToken:t})}function jjs({shareToken:s}){var g;const[t,n]=k.useState(null),[r,a]=k.useState(!0),[i,l]=k.useState(0),[o,c]=k.useState(!1);k.useEffect(()=>{d()},[s]);const d=async()=>{const{data:x,error:y}=await V.from("smart_presentations").select("*").eq("share_token",s).eq("status","published").single();if(y||!x){c(!0),a(!1);return}const{data:v}=await V.from("profiles").select("name, email, phone, avatar_url, title, brokerage_id").eq("id",x.owner_user_id).single();let _;if(v!=null&&v.brokerage_id){const{data:C}=await V.from("brokerages").select("name").eq("id",v.brokerage_id).single();_=(C==null?void 0:C.name)||void 0}let j=null;if(x.contact_id){const{data:C}=await V.from("innercircle_contacts").select("first_name, last_name, email, phone").eq("id",x.contact_id).single();j=C}n({...x,owner_name:v==null?void 0:v.name,owner_email:v==null?void 0:v.email,owner_phone:v==null?void 0:v.phone,owner_avatar:v==null?void 0:v.avatar_url,owner_title:(v==null?void 0:v.title)||void 0,brokerage_name:_,contact_name:j?[j.first_name,j.last_name].filter(Boolean).join(" "):void 0,contact_email:(j==null?void 0:j.email)||void 0,contact_phone:(j==null?void 0:j.phone)||void 0}),a(!1);try{await V.rpc("log_presentation_view",{p_presentation_id:x.id,p_section_index:0,p_cta_clicked:!1,p_ip_hash:null,p_user_agent:navigator.userAgent,p_referrer:document.referrer||null})}catch{}},u=async()=>{if(t){try{await V.rpc("log_presentation_view",{p_presentation_id:t.id,p_section_index:null,p_cta_clicked:!0,p_ip_hash:null,p_user_agent:navigator.userAgent,p_referrer:null})}catch{}t.cta_url&&window.open(t.cta_url,"_blank")}},h=x=>{const y=x.match(/(?:youtube\.com\/watch\?v=|youtu\.be\/)([a-zA-Z0-9_-]+)/);if(y)return`https://www.youtube.com/embed/${y[1]}?rel=0`;if(x.includes("iframe.mediadelivery.net/play/")){const j=x.replace("/play/","/embed/"),C=j.includes("?")?"&":"?";return`${j}${C}responsive=true`}if(x.includes("iframe.mediadelivery.net")){const j=x.includes("?")?"&":"?";return`${x}${j}responsive=true`}const v=x.match(/loom\.com\/share\/([a-zA-Z0-9]+)/);if(v)return`https://www.loom.com/embed/${v[1]}`;const _=x.match(/video\.bunnycdn\.com\/play\/(\d+)\/([a-f0-9-]+)/);return _?`https://iframe.mediadelivery.net/embed/${_[1]}/${_[2]}?responsive=true`:x};if(r)return e.jsx("div",{className:"min-h-screen bg-white flex items-center justify-center",children:e.jsxs("div",{className:"space-y-4 w-full max-w-2xl px-4",children:[e.jsx(fn,{className:"h-12 w-3/4 mx-auto"}),e.jsx(fn,{className:"h-64 w-full"}),e.jsx(fn,{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(x=>x.is_visible!==!1),p=m[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:[p!=null&&p.video_url?e.jsx("div",{className:"relative w-full rounded-xl overflow-hidden shadow-lg bg-gray-900",style:{paddingTop:"56.25%"},children:e.jsx("iframe",{src:h(p.video_url),className:"absolute inset-0 w-full h-full border-0",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0,loading:"lazy"})}):p!=null&&p.image_url?e.jsx("div",{className:"rounded-xl overflow-hidden shadow-lg",children:e.jsx("img",{src:p.image_url,alt:p.title,className:"w-full h-auto object-cover",loading:"lazy"})}):e.jsxs("div",{className:"aspect-video bg-gradient-to-br from-blue-50 to-slate-100 rounded-xl flex flex-col items-center justify-center shadow-lg",children:[e.jsx("span",{className:"text-5xl mb-3",children:p==null?void 0:p.icon}),e.jsx("h3",{className:"text-xl font-semibold text-gray-800",children:p==null?void 0:p.title}),e.jsx("p",{className:"text-gray-500 mt-1 text-sm",children:p==null?void 0:p.description})]}),(p==null?void 0:p.text)&&e.jsx("div",{className:"mt-4 p-4 bg-white rounded-lg border text-gray-700 text-sm leading-relaxed prose prose-sm max-w-none",dangerouslySetInnerHTML:{__html:p.text}})]}),e.jsx("div",{className:"md:col-span-2 space-y-3",children:m.map((x,y)=>e.jsx("button",{onClick:()=>l(y),className:Ot("w-full text-left p-4 rounded-xl border transition-all",i===y?"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(y+1).padStart(2,"0"),"."]}),e.jsxs("div",{children:[e.jsx("span",{className:"mr-2",children:x.icon}),e.jsx("span",{className:"font-semibold text-gray-900",children:x.title}),e.jsx("p",{className:"text-xs text-gray-500 mt-0.5",children:x.description})]})]})},y))})]}),e.jsxs("div",{className:"mt-12 max-w-md mx-auto bg-white rounded-2xl border border-gray-200 shadow-sm p-6 text-center",children:[t.owner_avatar&&e.jsx("img",{src:t.owner_avatar,alt:t.owner_name||"Agent",className:"h-20 w-20 rounded-full object-cover mx-auto mb-3 border-2 border-gray-100"}),e.jsx("h3",{className:"text-lg font-bold text-gray-900",children:t.owner_name}),t.owner_title&&e.jsx("p",{className:"text-sm text-gray-500",children:t.owner_title}),t.brokerage_name&&e.jsx("p",{className:"text-sm text-gray-500",children:t.brokerage_name}),e.jsxs("div",{className:"mt-3 flex flex-col items-center gap-1 text-sm text-gray-600",children:[t.owner_phone&&e.jsx("a",{href:`tel:${t.owner_phone}`,className:"hover:text-blue-600 transition-colors",children:t.owner_phone}),t.owner_email&&e.jsx("a",{href:`mailto:${t.owner_email}`,className:"hover:text-blue-600 transition-colors",children:t.owner_email})]})]}),t.cta_label&&e.jsxs("div",{className:"text-center mt-8 py-8",children:[e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-4",children:"Ready to Get Started?"}),(g=t.cta_url)!=null&&g.trim()?e.jsxs($,{size:"lg",onClick:u,className:"text-lg px-8 py-6 rounded-xl bg-blue-600 hover:bg-blue-700 text-white shadow-lg",children:[t.cta_label,e.jsx(Ir,{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(nEt,{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 Njs(){const{user:s}=ks(),t=ai(),{data:n}=gj();return pt({queryKey:["open-houses",t,n==null?void 0:n.teamId,n==null?void 0:n.role],queryFn:async()=>{const{data:r,error:a}=await V.from("open_houses").select("*").eq("agent_id",t).order("event_date",{ascending:!1});if(a)throw a;let i=r||[];if((n==null?void 0:n.role)==="team_leader"&&n.teamId){const{data:l,error:o}=await V.rpc("get_team_open_houses",{_user_id:t});if(!o&&l){const c=[...new Set(l.map(h=>h.agent_id))],d={};if(c.length>0){const{data:h}=await V.from("profiles").select("id, name").in("id",c);h==null||h.forEach(m=>{m.name&&(d[m.id]=m.name)})}const u=l.map(h=>({...h,agent_name:d[h.agent_id]||void 0}));i=[...i,...u]}}return i.sort((l,o)=>o.event_date.localeCompare(l.event_date)),i},enabled:!!s&&!!t})}function FQn(s){const{user:t}=ks();return pt({queryKey:["open-house",s],queryFn:async()=>{const{data:n,error:r}=await V.from("open_houses").select("*").eq("id",s).single();if(r)throw r;return n},enabled:!!t&&!!s})}function rEt(s){const{user:t}=ks(),n=ls();return k.useEffect(()=>{if(!s)return;const r=`visitors-${s}-${Math.random().toString(36).slice(2,10)}`,a=V.channel(r).on("postgres_changes",{event:"*",schema:"public",table:"open_house_visitors",filter:`open_house_id=eq.${s}`},()=>{n.invalidateQueries({queryKey:["open-house-visitors",s]}),n.invalidateQueries({queryKey:["open-houses"]})}).subscribe();return()=>{V.removeChannel(a)}},[s,n]),pt({queryKey:["open-house-visitors",s],queryFn:async()=>{const{data:r,error:a}=await V.from("open_house_visitors").select("*").eq("open_house_id",s).order("created_at",{ascending:!1});if(a)throw a;return r},enabled:!!t&&!!s})}function kjs(){const s=ls(),t=ai();return Nt({mutationFn:async n=>{const{data:r,error:a}=await V.from("open_houses").insert({...n,agent_id:t}).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["open-houses"]}),Ma({title:"Open house created!"})},onError:n=>{Ma({title:"Error",description:n.message,variant:"destructive"})}})}function aEt(){const s=ls();return Nt({mutationFn:async({id:t,...n})=>{const{error:r}=await V.from("open_houses").update(n).eq("id",t);if(r)throw r},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["open-houses"]}),s.invalidateQueries({queryKey:["open-house",n.id]})}})}function Sjs(){const s=ls();return Nt({mutationFn:async t=>{const{error:n}=await V.from("open_houses").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["open-houses"]}),Ma({title:"Open house deleted"})}})}function Cjs(s){return pt({queryKey:["public-open-house",s],queryFn:async()=>{const{data:t,error:n}=await V.from("open_houses").select("*, profiles:agent_id(name, avatar_url, title, email, phone)").eq("slug",s).eq("is_active",!0).single();if(n)throw n;let r=null;if(t.agent_id){const{data:a}=await V.from("agent_cards").select("slug").eq("user_id",t.agent_id).eq("is_published",!0).maybeSingle();a&&(r=a.slug)}return{...t,agent_card_slug:r}},enabled:!!s})}function Ajs(s){const{user:t}=ks();return pt({queryKey:["survey-questions",s],queryFn:async()=>{const{data:n,error:r}=await V.from("open_house_survey_questions").select("*").eq("open_house_id",s).order("sort_order");if(r)throw r;return n},enabled:!!t&&!!s})}function Ejs(s){return pt({queryKey:["public-survey-questions",s],queryFn:async()=>{const{data:t,error:n}=await V.from("open_house_survey_questions").select("*").eq("open_house_id",s).eq("is_active",!0).order("sort_order");if(n)throw n;return t},enabled:!!s})}function Tjs(){return Nt({mutationFn:async s=>{const{error:t}=await V.from("open_house_survey_responses").insert(s);if(t)throw t}})}function Mjs(s){const{user:t}=ks();return pt({queryKey:["survey-responses",s],queryFn:async()=>{const{data:n,error:r}=await V.from("open_house_survey_questions").select("*").eq("open_house_id",s).order("sort_order");if(r)throw r;const a=(n||[]).map(o=>o.id);if(a.length===0)return{questions:[],responses:[]};const{data:i,error:l}=await V.from("open_house_survey_responses").select("*").in("question_id",a).order("created_at",{ascending:!1});if(l)throw l;return{questions:n,responses:i||[]}},enabled:!!t&&!!s})}function Pjs(){const s=ls();return Nt({mutationFn:async t=>{const{data:n,error:r}=await V.from("open_house_survey_questions").insert(t).select().single();if(r)throw r;return n},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["survey-questions",n.open_house_id]})}})}function Ijs(){const s=ls();return Nt({mutationFn:async({id:t,open_house_id:n,...r})=>{const{error:a}=await V.from("open_house_survey_questions").update(r).eq("id",t);if(a)throw a},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["survey-questions",n.open_house_id]})}})}function Ljs(){const s=ls();return Nt({mutationFn:async({id:t,open_house_id:n})=>{const{error:r}=await V.from("open_house_survey_questions").delete().eq("id",t);if(r)throw r},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["survey-questions",n.open_house_id]})}})}function Rjs(){const s=ls();return Nt({mutationFn:async t=>{const{error:n}=await V.rpc("seed_default_survey_questions",{_open_house_id:t});if(n)throw n},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["survey-questions",n]})}})}function Djs(){return Nt({mutationFn:async s=>{const{data:t,error:n}=await V.from("open_house_visitors").insert(s).select("id").single();if(n)throw n;return t}})}function Ojs(){return Nt({mutationFn:async({visitor_id:s,...t})=>{const{error:n}=await V.from("open_house_visitors").update(t).eq("id",s);if(n)throw n}})}function Fjs(){return Nt({mutationFn:async s=>{await V.rpc("increment_open_house_scan",{_slug:s})}})}async function iEt(s){const{data:t,error:n}=await V.from("open_house_rooms").select("*").eq("open_house_id",s).order("sort_order");if(n)throw n;const r=t||[];if(r.length===0)return[];const a=r.map(c=>c.id),{data:i,error:l}=await V.from("open_house_room_media").select("*").in("room_id",a).order("sort_order");if(l)throw l;const o={};return(i||[]).forEach(c=>{var u;const d=c;(o[u=d.room_id]||(o[u]=[])).push(d)}),r.map(c=>({...c,media:o[c.id]||[]}))}function zjs(s){const{user:t}=ks();return pt({queryKey:["open-house-rooms",s],queryFn:()=>iEt(s),enabled:!!t&&!!s})}function Bjs(s){return pt({queryKey:["public-open-house-rooms",s],queryFn:()=>iEt(s),enabled:!!s})}function $js(){const s=ls();return Nt({mutationFn:async t=>{const{data:n,error:r}=await V.from("open_house_rooms").insert(t).select().single();if(r)throw r;return n},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["open-house-rooms",n.open_house_id]})}})}function Ujs(){const s=ls();return Nt({mutationFn:async({id:t,open_house_id:n,...r})=>{const{error:a}=await V.from("open_house_rooms").update(r).eq("id",t);if(a)throw a},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["open-house-rooms",n.open_house_id]})}})}function qjs(){const s=ls();return Nt({mutationFn:async({id:t,open_house_id:n})=>{const{error:r}=await V.from("open_house_rooms").delete().eq("id",t);if(r)throw r},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["open-house-rooms",n.open_house_id]})}})}function Vjs(){const s=ls();return Nt({mutationFn:async({open_house_id:t,...n})=>{const{data:r,error:a}=await V.from("open_house_room_media").insert(n).select().single();if(a)throw a;return r},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["open-house-rooms",n.open_house_id]})}})}function Hjs(){const s=ls();return Nt({mutationFn:async({id:t,open_house_id:n})=>{const{error:r}=await V.from("open_house_room_media").delete().eq("id",t);if(r)throw r},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["open-house-rooms",n.open_house_id]})}})}function Gjs(s){const{user:t}=ks();return pt({queryKey:["open-house-leads",s],queryFn:async()=>{const{data:n,error:r}=await V.from("open_house_leads").select("*").eq("open_house_id",s).order("created_at",{ascending:!1});if(r)throw r;return n||[]},enabled:!!t&&!!s})}function Wjs(){const s=ls();return Nt({mutationFn:async({id:t,status:n,open_house_id:r})=>{const{error:a}=await V.from("open_house_leads").update({status:n}).eq("id",t);if(a)throw a;return{open_house_id:r}},onSuccess:t=>{s.invalidateQueries({queryKey:["open-house-leads",t.open_house_id]})}})}var Kjs=Object.defineProperty,SM=(s,t)=>Kjs(s,"name",{value:t,configurable:!0}),TGe="Switch",[Yjs,zQn]=qm(TGe),[Zjs,MGe]=Yjs(TGe);function oEt(s){const{__scopeSwitch:t,checked:n,children:r,defaultChecked:a,disabled:i,form:l,name:o,onCheckedChange:c,required:d,value:u="on",internal_do_not_use_render:h}=s,[m,p]=ox({prop:n,defaultProp:a??!1,onChange:c,caller:TGe}),[g,x]=k.useState(null),[y,v]=k.useState(null),_=k.useRef(!1),[j,C]=k.useReducer(I=>I+1,0),A=g?!!l||!!g.closest("form"):!0,M={checked:m,setChecked:p,disabled:i,control:g,setControl:x,name:o,form:l,value:u,hasConsumerStoppedPropagationRef:_,userInteractionCount:j,onUserInteraction:C,required:d,defaultChecked:a,isFormControl:A,bubbleInput:y,setBubbleInput:v};return e.jsx(Zjs,{scope:t,...M,children:cEt(h)?h(M):r})}SM(oEt,"SwitchProvider");var Xjs="SwitchTrigger",Qjs=k.forwardRef(SM(function({__scopeSwitch:t,onClick:n,...r},a){const{control:i,form:l,value:o,disabled:c,checked:d,required:u,setControl:h,setChecked:m,hasConsumerStoppedPropagationRef:p,onUserInteraction:g,isFormControl:x,bubbleInput:y}=MGe(Xjs,t),v=Ao(a,h),_=k.useRef(d);return k.useEffect(()=>{const j=l?i==null?void 0:i.ownerDocument.getElementById(l):i==null?void 0:i.form;if(j instanceof HTMLFormElement){const C=SM(()=>m(_.current),"reset");return j.addEventListener("reset",C),()=>j.removeEventListener("reset",C)}},[i,l,m]),e.jsx(hi.button,{type:"button",role:"switch","aria-checked":d,"aria-required":u,"data-state":PGe(d),"data-disabled":c?"":void 0,disabled:c,value:o,...r,ref:v,onClick:ga(n,j=>{g(),m(C=>!C),y&&x&&(p.current=j.isPropagationStopped(),p.current||j.stopPropagation())})})},"SwitchTrigger")),lEt=k.forwardRef(SM(function(t,n){const{__scopeSwitch:r,name:a,checked:i,defaultChecked:l,required:o,disabled:c,value:d,onCheckedChange:u,form:h,...m}=t;return e.jsx(oEt,{__scopeSwitch:r,checked:i,defaultChecked:l,disabled:c,required:o,onCheckedChange:u,name:a,form:h,value:d,internal_do_not_use_render:({isFormControl:p})=>e.jsxs(e.Fragment,{children:[e.jsx(Qjs,{...m,ref:n,__scopeSwitch:r}),p&&e.jsx(s2s,{__scopeSwitch:r})]})})},"Switch")),Jjs="SwitchThumb",e2s=k.forwardRef(SM(function(t,n){const{__scopeSwitch:r,...a}=t,i=MGe(Jjs,r);return e.jsx(hi.span,{"data-state":PGe(i.checked),"data-disabled":i.disabled?"":void 0,...a,ref:n})},"SwitchThumb")),t2s="SwitchBubbleInput",s2s=k.forwardRef(SM(function({__scopeSwitch:t,onClick:n,...r},a){const{control:i,hasConsumerStoppedPropagationRef:l,userInteractionCount:o,checked:c,defaultChecked:d,required:u,disabled:h,name:m,value:p,form:g,bubbleInput:x,setBubbleInput:y}=MGe(t2s,t),v=Ao(a,y),_=Dq(i),j=k.useRef(!1),C=k.useRef(c),A=k.useRef(o);k.useEffect(()=>{const I=x;if(!I)return;const P=window.HTMLInputElement.prototype,O=Object.getOwnPropertyDescriptor(P,"checked").set,B=o!==A.current;A.current=o;const U=C.current!==c;C.current=c;const G=!(B&&l.current);if(U&&O){j.current=!B;const H=new Event("click",{bubbles:G});O.call(I,c),I.dispatchEvent(H),j.current=!1}},[x,c,l,o]);const M=k.useRef(c);return e.jsx(hi.input,{type:"checkbox","aria-hidden":!0,defaultChecked:d??M.current,required:u,disabled:h,name:m,value:p,form:g,...r,tabIndex:-1,ref:v,onClick:ga(n,I=>{j.current&&I.stopPropagation()}),style:{...r.style,..._,position:"absolute",pointerEvents:"none",opacity:0,margin:0,transform:"translateX(-100%)"}})},"SwitchBubbleInput"));function cEt(s){return typeof s=="function"}SM(cEt,"isFunction");function PGe(s){return s?"checked":"unchecked"}SM(PGe,"getState");const On=k.forwardRef(({className:s,...t},n)=>e.jsx(lEt,{className:Ot("peer inline-flex h-6 w-11 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors data-[state=checked]:bg-primary data-[state=unchecked]:bg-input focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50",s),...t,ref:n,children:e.jsx(e2s,{className:Ot("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")})}));On.displayName=lEt.displayName;const n2s=["Excellent","Good","Neutral","Bad","Very Bad"],r2s=[5,4,3,2,1];function a2s({questions:s,visitorId:t,onComplete:n,onSkip:r}){const a=Tjs(),[i,l]=k.useState({}),o=s.filter(m=>m.question_type==="rating"),c=s.filter(m=>m.question_type!=="rating"),d=(m,p)=>{l(g=>({...g,[m]:{rating_value:p}}))},u=(m,p)=>{l(g=>({...g,[m]:{text_value:p}}))},h=async()=>{const m=Object.entries(i).filter(([,p])=>p.rating_value!=null||p.text_value&&p.text_value.trim()).map(([p,g])=>{var x;return{visitor_id:t,question_id:p,rating_value:g.rating_value??null,text_value:((x=g.text_value)==null?void 0:x.trim())||null}});if(m.length>0)try{await a.mutateAsync(m)}catch{}n()};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("h2",{className:"text-lg font-bold text-slate-900",children:"Quick Feedback"}),e.jsx("button",{onClick:r,className:"text-sm text-slate-400 hover:text-slate-600 underline",children:"Skip"})]}),e.jsx("p",{className:"text-sm text-slate-500 -mt-2",children:"Your feedback helps the agent — totally optional!"}),o.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("div",{className:"flex-1"}),n2s.map(m=>e.jsx("div",{className:"w-12 text-center",children:e.jsx("span",{className:"text-[10px] text-slate-400 leading-tight block",children:m})},m))]}),o.map(m=>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:m.question_text}),r2s.map(p=>{var g;return e.jsx("div",{className:"w-12 flex justify-center",children:e.jsx("button",{type:"button",onClick:()=>d(m.id,p),className:`w-6 h-6 rounded-full border-2 transition-all ${((g=i[m.id])==null?void 0:g.rating_value)===p?"bg-slate-900 border-slate-900":"border-slate-300 hover:border-slate-500"}`})},p)})]},m.id))]}),c.map(m=>{var p;return e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium text-slate-700 block mb-1",children:m.question_text}),e.jsx(Ls,{value:((p=i[m.id])==null?void 0:p.text_value)||"",onChange:g=>u(m.id,g.target.value),placeholder:"Your thoughts...",className:"h-16 text-sm resize-none rounded-xl border-slate-200"})]},m.id)}),e.jsx($,{onClick:h,disabled:a.isPending,className:"w-full h-12 text-base bg-slate-900 hover:bg-slate-800 text-white rounded-xl",children:a.isPending?e.jsx(Jt,{className:"h-5 w-5 animate-spin"}):"Submit Feedback"})]})}function N7e(s){return/iframe\.mediadelivery\.net\/embed\//.test(s)}function i2s({rooms:s}){var h;const[t,n]=k.useState(((h=s[0])==null?void 0:h.id)||""),[r,a]=k.useState(null),i=s.find(m=>m.id===t)||s[0],l=r!==null?i==null?void 0:i.media[r]:null,o=(i==null?void 0:i.media.length)??0,c=()=>a(null),d=()=>a(m=>m===null||o===0?m:(m-1+o)%o),u=()=>a(m=>m===null||o===0?m:(m+1)%o);return k.useEffect(()=>{if(r===null)return;const m=p=>{p.key==="Escape"?c():p.key==="ArrowLeft"?d():p.key==="ArrowRight"&&u()};return window.addEventListener("keydown",m),()=>window.removeEventListener("keydown",m)},[r,o]),s.length?e.jsxs("div",{className:"hidden md:block",children:[e.jsx("div",{className:"sticky top-0 z-20 -mx-5 px-5 py-3 bg-slate-950/80 backdrop-blur-md border-b border-white/10 overflow-x-auto",children:e.jsx("div",{className:"flex gap-2 min-w-max",children:s.map(m=>e.jsxs("button",{onClick:()=>n(m.id),className:Ot("px-4 py-2 rounded-full text-sm font-medium whitespace-nowrap transition",t===m.id?"bg-white text-slate-900":"bg-white/5 text-white/70 hover:bg-white/10"),children:[m.name,e.jsx("span",{className:"ml-1.5 text-xs opacity-60",children:m.media.length})]},m.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((m,p)=>e.jsx("button",{onClick:()=>a(p),className:"relative aspect-[4/3] rounded-xl overflow-hidden bg-white/5 group",children:m.kind==="video"?e.jsxs(e.Fragment,{children:[N7e(m.url)?e.jsx("div",{className:"absolute inset-0 bg-slate-900"}):e.jsx("video",{src:m.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(ia,{className:"h-5 w-5 text-slate-900"})})})]}):e.jsx("img",{src:m.url,alt:i.name,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-500"})},m.id))})]}),l&&i&&e.jsxs("div",{className:"fixed inset-0 z-50 bg-black/95 flex items-center justify-center p-6 cursor-zoom-out",onClick:c,children:[e.jsxs("div",{className:"absolute top-5 left-1/2 -translate-x-1/2 px-3 py-1.5 rounded-full bg-white/10 backdrop-blur-sm text-white/80 text-xs font-medium",children:[i.name," — ",(r??0)+1," / ",o]}),e.jsx("button",{onClick:m=>{m.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:m=>{m.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(Ld,{className:"h-6 w-6"})}),l.kind==="video"?N7e(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:m=>m.stopPropagation()},l.url):e.jsx("video",{src:l.url,controls:!0,autoPlay:!0,className:"max-w-full max-h-full rounded-lg",onClick:m=>m.stopPropagation()},l.url):e.jsx("img",{src:l.url,alt:"",className:"max-w-full max-h-full rounded-lg cursor-default",onClick:m=>m.stopPropagation()}),o>1&&e.jsx("button",{onClick:m=>{m.stopPropagation(),u()},className:"absolute right-5 top-1/2 -translate-y-1/2 h-12 w-12 rounded-full bg-white/10 hover:bg-white/20 text-white flex items-center justify-center transition","aria-label":"Next",children:e.jsx(fi,{className:"h-6 w-6"})})]})]}):null}function o2s({rooms:s}){var o;const t=[];s.forEach(c=>{t.push({type:"cover",roomId:c.id,roomName:c.name,description:c.description,mediaCount:c.media.length}),c.media.forEach((d,u)=>{t.push({type:"media",roomId:c.id,roomName:c.name,url:d.url,kind:d.kind,index:u,total:c.media.length})})});const n=k.useRef(null),[r,a]=k.useState(0);k.useEffect(()=>{const c=n.current;if(!c)return;let d=0;const u=()=>{cancelAnimationFrame(d),d=requestAnimationFrame(()=>{const h=Math.round(c.scrollLeft/c.clientWidth);a(h)})};return c.addEventListener("scroll",u,{passive:!0}),()=>{c.removeEventListener("scroll",u),cancelAnimationFrame(d)}},[]);const i=c=>{const d=n.current;d&&d.scrollTo({left:c*d.clientWidth,behavior:"smooth"})};if(!t.length)return null;const l=(o=t[r])==null?void 0:o.roomId;return e.jsxs("div",{className:"md:hidden -mx-5",children:[e.jsx("div",{className:"px-5 py-3 overflow-x-auto sticky top-0 z-20 bg-slate-950/80 backdrop-blur-md border-b border-white/10",children:e.jsx("div",{className:"flex gap-2 min-w-max",children:s.map(c=>{const d=t.findIndex(h=>h.roomId===c.id),u=l===c.id;return e.jsx("button",{onClick:()=>i(d),className:Ot("px-3.5 py-1.5 rounded-full text-xs font-medium whitespace-nowrap transition",u?"bg-white text-slate-900":"bg-white/10 text-white/80"),children:c.name},c.id)})})}),e.jsx("div",{ref:n,className:"flex overflow-x-auto snap-x snap-mandatory scroll-smooth no-scrollbar",style:{scrollSnapType:"x mandatory"},children:t.map((c,d)=>e.jsx("div",{className:"shrink-0 w-screen snap-center",children:e.jsxs("div",{className:"w-full aspect-[9/16] max-h-[75vh] bg-slate-900 relative",children:[c.type==="cover"?e.jsxs("div",{className:"w-full h-full flex flex-col items-center justify-center p-8 text-center bg-gradient-to-br from-slate-800 to-slate-950",children:[e.jsx("p",{className:"text-xs uppercase tracking-widest text-white/40 mb-2",children:"Next room"}),e.jsx("h3",{className:"text-3xl font-bold",children:c.roomName}),c.description&&e.jsx("p",{className:"text-white/70 text-sm mt-3 max-w-xs",children:c.description}),e.jsxs("p",{className:"text-white/40 text-xs mt-5",children:[c.mediaCount," ",c.mediaCount===1?"item":"items"," — swipe to view →"]})]}):c.kind==="video"?N7e(c.url)?e.jsx("iframe",{src:c.url,allow:"accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0,className:"w-full h-full"}):e.jsx("video",{src:c.url,controls:!0,playsInline:!0,className:"w-full h-full object-cover"}):e.jsx("img",{src:c.url,alt:c.roomName,className:"w-full h-full object-cover"}),c.type==="media"&&e.jsxs("div",{className:"absolute top-3 left-3 right-3 flex items-center justify-between pointer-events-none",children:[e.jsx("div",{className:"px-3 py-1 rounded-full bg-black/50 backdrop-blur-sm text-xs text-white font-medium",children:c.roomName}),e.jsxs("div",{className:"px-2.5 py-1 rounded-full bg-black/50 backdrop-blur-sm text-[10px] text-white/80",children:[c.index+1," / ",c.total]})]})]})},d))}),e.jsxs("div",{className:"flex items-center justify-between px-5 mt-3",children:[e.jsxs("button",{onClick:()=>i(Math.max(0,r-1)),disabled:r===0,className:"flex items-center gap-1 text-sm text-white/70 disabled:opacity-30",children:[e.jsx(Ld,{className:"h-4 w-4"})," Prev"]}),e.jsxs("span",{className:"text-xs text-white/50",children:[r+1," / ",t.length]}),e.jsxs("button",{onClick:()=>i(Math.min(t.length-1,r+1)),disabled:r===t.length-1,className:"flex items-center gap-1 text-sm text-white/70 disabled:opacity-30",children:["Next ",e.jsx(fi,{className:"h-4 w-4"})]})]})]})}const AIe={question:{label:"Ask a Question",title:"Ask the agent",placeholder:"What would you like to know about the home?",icon:bo},showing:{label:"Schedule a Showing",title:"Request a private showing",placeholder:"Anything specific to focus on during the showing? (optional)",icon:ha},disclosure:{label:"Request Disclosures",title:"Request seller disclosures",placeholder:"Any specific documents? (optional)",icon:ea},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:Su}},l2s=["Seller's Property Disclosure","HOA Documents & Bylaws","Inspection Reports","Title / CC&Rs","Utility & Tax History"];function c2s(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 d2s({openHouse:s,visitorId:t,visitorName:n,visitorEmail:r,visitorPhone:a,previewMode:i=!1}){var Be;const l=s.profiles,o=((Be=l==null?void 0:l.name)==null?void 0:Be.split(" ").map(je=>je[0]).join("").slice(0,2))||"?",c=s.brand_color_override||null,[d,u]=k.useState(null),[h,m]=k.useState(""),[p,g]=k.useState(r||""),[x,y]=k.useState(a||""),[v,_]=k.useState(!1),[j,C]=k.useState(null),[A,M]=k.useState(""),[I,P]=k.useState(""),[R,O]=k.useState(""),[B,U]=k.useState([]),[G,H]=k.useState(""),[Y,se]=k.useState(""),[ee,oe]=k.useState(""),[me,Q]=k.useState(""),te=c2s(s.price),le=s.tour_mode==="rooms",{data:fe=[]}=Bjs(le?s.id:void 0),_e=[s.enable_question&&"question",s.enable_showing&&"showing",s.enable_disclosures&&"disclosure",s.enable_offer&&"offer"].filter(Boolean),ve=je=>{u(je),m(""),M(""),P(""),O(""),U([]),H(""),se(""),oe(""),Q("")},he=()=>{u(null)},Se=je=>{U(Ye=>Ye.includes(je)?Ye.filter(Ee=>Ee!==je):[...Ye,je])},Te=je=>je==="showing"?{preferred_date:A||null,preferred_time:I||null,alternate_date:R||null}:je==="disclosure"?{requested_documents:B}:je==="offer"?{offer_amount:G||null,financing:Y||null,timeline:ee||null,pre_approved:me||null}:{},Ie=d?d==="showing"?!!A:d==="question"?h.trim().length>0:!0:!1,Ue=async()=>{if(d){if(i){Ma({title:"Preview mode",description:"Lead not sent — this is just a preview."}),C(d),setTimeout(()=>{u(null),C(null)},1500);return}_(!0);try{const je=Te(d),{error:Ye}=await V.from("open_house_leads").insert({open_house_id:s.id,visitor_id:t,action_type:d,payload:{message:h.trim()||null,email:p.trim()||null,phone:x.trim()||null,visitor_name:n,...je}});if(Ye)throw Ye;V.functions.invoke("send-virtual-open-house-lead",{body:{open_house_id:s.id,visitor_id:t,action_type:d,message:h.trim()||null,visitor_name:n,visitor_email:p.trim()||null,visitor_phone:x.trim()||null,extras:je}}).catch(()=>{}),C(d),Ma({title:"Sent!",description:"The agent has been notified."}),setTimeout(()=>{he(),C(null)},1400)}catch(je){Ma({title:"Something went wrong",description:je.message,variant:"destructive"})}finally{_(!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(Si,{className:"h-3.5 w-3.5"}),s.city,s.state?`, ${s.state}`:""," ",s.zip]}),te&&e.jsx("p",{className:"text-3xl font-bold text-white mt-3",children:te}),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(Yw,{className:"h-4 w-4"}),s.beds," bd"]}),s.baths!=null&&e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(p0,{className:"h-4 w-4"}),s.baths," ba"]}),s.sqft!=null&&e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(w_,{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(Wa,{className:"h-12 w-12 ring-2 ring-white/20",style:c?{boxShadow:`0 0 0 2px ${c}`}:void 0,children:[e.jsx(eo,{src:l.avatar_url||"",alt:l.name||""}),e.jsx(Ka,{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(ka,{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(pn,{className:"h-4 w-4"})})]})]}),le&&fe.length>0&&e.jsxs("div",{className:"mt-8",children:[e.jsx(i2s,{rooms:fe}),e.jsx(o2s,{rooms:fe})]}),_e.length>0&&e.jsx("div",{className:"mt-5 grid grid-cols-1 sm:grid-cols-2 gap-3",children:_e.map(je=>{const Ye=AIe[je],Ee=Ye.icon;return e.jsxs("button",{onClick:()=>ve(je),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(Ee,{className:"h-5 w-5"})}),e.jsx("span",{className:"font-medium text-sm",children:Ye.label})]},je)})}),e.jsx("p",{className:"text-center text-white/30 text-xs mt-8",children:"Powered by LevelUp Virtual Open House"})]}),e.jsx(D_,{open:!!d,onOpenChange:je=>!je&&he(),children:e.jsx(Mb,{side:"bottom",className:"rounded-t-2xl max-h-[92vh] overflow-y-auto",children:d&&e.jsxs(e.Fragment,{children:[e.jsxs(xj,{className:"text-left",children:[e.jsx(yj,{children:AIe[d].title}),e.jsxs(hee,{children:[(l==null?void 0:l.name)||"The agent"," will be notified by email."]})]}),j===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(Gr,{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(re,{className:"text-xs",children:"Email"}),e.jsx(be,{type:"email",value:p,onChange:je=>g(je.target.value),placeholder:"you@example.com",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Phone"}),e.jsx(be,{type:"tel",value:x,onChange:je=>y(je.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(re,{className:"text-xs",children:"Preferred date *"}),e.jsx(be,{type:"date",value:A,onChange:je=>M(je.target.value),className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Preferred time"}),e.jsx(be,{type:"time",value:I,onChange:je=>P(je.target.value),className:"mt-1"})]})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Alternate date (optional)"}),e.jsx(be,{type:"date",value:R,onChange:je=>O(je.target.value),className:"mt-1"})]})]}),d==="disclosure"&&e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Which documents? (select all that apply)"}),e.jsx("div",{className:"mt-2 space-y-2",children:l2s.map(je=>e.jsxs("label",{className:"flex items-center gap-2 text-sm cursor-pointer",children:[e.jsx(Li,{checked:B.includes(je),onCheckedChange:()=>Se(je)}),e.jsx("span",{children:je})]},je))})]}),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(re,{className:"text-xs",children:"Estimated offer"}),e.jsx(be,{value:G,onChange:je=>H(je.target.value),placeholder:"$",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Financing"}),e.jsxs(bs,{value:Y,onValueChange:se,children:[e.jsx(ys,{className:"mt-1",children:e.jsx(_s,{placeholder:"Select..."})}),e.jsxs(vs,{children:[e.jsx(We,{value:"Cash",children:"Cash"}),e.jsx(We,{value:"Conventional",children:"Conventional"}),e.jsx(We,{value:"FHA",children:"FHA"}),e.jsx(We,{value:"VA",children:"VA"}),e.jsx(We,{value:"Other",children:"Other"})]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Timeline"}),e.jsxs(bs,{value:ee,onValueChange:oe,children:[e.jsx(ys,{className:"mt-1",children:e.jsx(_s,{placeholder:"Select..."})}),e.jsxs(vs,{children:[e.jsx(We,{value:"ASAP",children:"ASAP"}),e.jsx(We,{value:"30 days",children:"30 days"}),e.jsx(We,{value:"60 days",children:"60 days"}),e.jsx(We,{value:"90+ days",children:"90+ days"})]})]})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Pre-approved?"}),e.jsxs(bs,{value:me,onValueChange:Q,children:[e.jsx(ys,{className:"mt-1",children:e.jsx(_s,{placeholder:"Select..."})}),e.jsxs(vs,{children:[e.jsx(We,{value:"Yes",children:"Yes"}),e.jsx(We,{value:"No",children:"No"}),e.jsx(We,{value:"In progress",children:"In progress"})]})]})]})]})]}),e.jsxs("div",{children:[e.jsxs(re,{className:"text-xs",children:["Message",d==="question"?" *":" (optional)"]}),e.jsx(Ls,{value:h,onChange:je=>m(je.target.value),placeholder:AIe[d].placeholder,rows:4,className:"mt-1"})]}),e.jsx($,{onClick:Ue,disabled:v||!Ie,className:"w-full h-12 text-white hover:opacity-90",style:c?{backgroundColor:c}:void 0,children:v?e.jsx(Jt,{className:"h-4 w-4 animate-spin"}):"Send to agent"})]})]})})})]})}const u2s=t4({first_name:uc().trim().min(1,"First name is required").max(50),last_name:uc().trim().max(50).optional(),email:uc().trim().email("Please enter a valid email").max(255).optional().or(c0("")),phone:uc().trim().max(20).optional().or(c0(""))}),h2s=[{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 dEt({slug:s}={}){var Oe;const t=oo(),n=s||t.slug,[r]=Jc(),a=r.get("kiosk")==="1"||r.get("mode")==="kiosk",i=8,{data:l,isLoading:o,error:c}=Cjs(n),d=Djs(),u=Ojs(),h=Fjs(),m=k.useRef(!1),[p,g]=k.useState("welcome"),[x,y]=k.useState(null),[v,_]=k.useState({first_name:"",last_name:"",email:"",phone:"",visitor_address:""}),[j,C]=k.useState(""),[A,M]=k.useState(!1),[I,P]=k.useState(!1),[R,O]=k.useState(""),[B,U]=k.useState(""),[G,H]=k.useState(i),Y=k.useCallback(()=>{y(null),_({first_name:"",last_name:"",email:"",phone:"",visitor_address:""}),C(""),M(!1),P(!1),O(""),U(""),H(i),g(a?"info":"welcome")},[a]),se=k.useCallback((Ge,yt)=>{l!=null&&l.id&&V.functions.invoke("guestbook-lead-notify",{body:{open_house_id:l.id,visitor_id:Ge,first_name:yt.first_name??v.first_name,last_name:yt.last_name??v.last_name,email:yt.email??v.email,phone:yt.phone??v.phone,visitor_intent:yt.visitor_intent??j,message:yt.message,wants_market_updates:yt.wants_market_updates??A,has_agent:yt.has_agent??I,working_with_agent_name:yt.working_with_agent_name??R,visitor_address:yt.visitor_address??v.visitor_address}}).catch(tt=>console.error("Guest book lead notify failed:",tt))},[l==null?void 0:l.id,v,j,A,I,R]);k.useEffect(()=>{if(!a||p!=="done")return;H(i);const Ge=setInterval(()=>{H(yt=>yt<=1?(clearInterval(Ge),Y(),0):yt-1)},1e3);return()=>clearInterval(Ge)},[a,p,Y]),k.useEffect(()=>{if(!a)return;g(yt=>yt==="welcome"?"info":yt);let Ge=null;return(async()=>{var yt,tt;try{Ge=await((tt=(yt=navigator.wakeLock)==null?void 0:yt.request)==null?void 0:tt.call(yt,"screen"))}catch{}})(),()=>{var yt;try{(yt=Ge==null?void 0:Ge.release)==null||yt.call(Ge)}catch{}}},[a]);const ee=k.useCallback(()=>{var yt;const Ge=document.documentElement;document.fullscreenElement||(yt=Ge.requestFullscreen||Ge.webkitRequestFullscreen)==null||yt.call(Ge).catch(()=>{})},[]),{data:oe,isLoading:me}=Ejs(l==null?void 0:l.id),Q=!!(l!=null&&l.enable_survey),te=(l==null?void 0:l.ask_visitor_intent)!==!1,le=(l==null?void 0:l.ask_visitor_address)===!0;k.useEffect(()=>{if(!n||!(l!=null&&l.id)||m.current)return;const Ge=`oh_scan_${l.id}`;if(sessionStorage.getItem(Ge)){m.current=!0;return}m.current=!0,sessionStorage.setItem(Ge,"1"),h.mutate(n)},[n,l==null?void 0:l.id]),k.useEffect(()=>{p==="pending_survey"&&(me||g(Q&&((oe==null?void 0:oe.length)??0)>0?"survey":"done"))},[p,me,Q,oe]);const fe=Ge=>{if(!Ge)return"";const[yt,tt]=Ge.split(":"),ut=parseInt(yt),nt=ut>=12?"PM":"AM";return`${ut>12?ut-12:ut||12}:${tt} ${nt}`},_e=async()=>{U("");const Ge=u2s.safeParse(v);if(!Ge.success){U(Ge.error.issues[0].message);return}if(!v.email&&!v.phone){U("Please provide either an email or phone number");return}const yt=(l==null?void 0:l.kind)==="virtual";let tt=null;if(!x&&(l!=null&&l.id))try{const ut=await d.mutateAsync({open_house_id:l.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_address:le&&v.visitor_address.trim()?v.visitor_address.trim():void 0,wants_market_updates:A,has_agent:I,working_with_agent_name:I&&R.trim()?R.trim():void 0,partial_signin:yt?!1:te});tt=ut.id,y(ut.id)}catch{if(yt){U("We could not start the virtual tour. Please try again.");return}}if(yt){te?g("intent"):(tt&&se(tt,{}),g("done"));return}if(!te){tt&&se(tt,{}),Q?!me&&oe&&oe.length>0?g("survey"):g("pending_survey"):g("done");return}g("intent")},ve=async Ge=>{C(Ge);try{let yt=x;if(yt?await u.mutateAsync({visitor_id:yt,visitor_intent:Ge,wants_market_updates:A,has_agent:I,working_with_agent_name:I&&R.trim()?R.trim():null,partial_signin:!1}):(yt=(await d.mutateAsync({open_house_id:l.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_address:le&&v.visitor_address.trim()?v.visitor_address.trim():void 0,visitor_intent:Ge,wants_market_updates:A,has_agent:I,working_with_agent_name:I&&R.trim()?R.trim():void 0,partial_signin:!1})).id,y(yt)),yt&&se(yt,{visitor_intent:Ge,wants_market_updates:A,has_agent:I,working_with_agent_name:I&&R.trim()?R.trim():null}),(l==null?void 0:l.kind)==="virtual"){g("done");return}Q?!me&&oe&&oe.length>0?g("survey"):g("pending_survey"):g("done")}catch{U("Something went wrong. Please try again.")}};if(o)return e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900 flex items-center justify-center",children:e.jsx("div",{className:"w-10 h-10 border-4 border-white/20 border-t-white rounded-full animate-spin"})});if(c||!l)return e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900 flex items-center justify-center p-6",children:e.jsxs("div",{className:"text-center text-white",children:[e.jsx(ua,{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 he=l.profiles,Se=((Oe=he==null?void 0:he.name)==null?void 0:Oe.split(" ").map(Ge=>Ge[0]).join("").slice(0,2))||"?",Te=l.event_type==="community",Ie=l.kind==="virtual",Ue=typeof window<"u"&&new URLSearchParams(window.location.search).get("preview")==="1";if(Ie&&(Ue||p==="done"))return!Ue&&!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(Sc,{children:[e.jsxs("title",{children:["Virtual Tour | ",l.property_address]}),e.jsx("meta",{name:"description",content:`Take a virtual tour of ${l.property_address}`}),e.jsx("meta",{name:"robots",content:"noindex, nofollow"})]}),Ue&&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(d2s,{openHouse:l,visitorId:Ue?"preview":x,visitorName:Ue?"Preview Visitor":`${v.first_name} ${v.last_name}`.trim(),visitorEmail:Ue?"":v.email,visitorPhone:Ue?"":v.phone,previewMode:Ue})]});const je=`${Ie?"Virtual Open House":Te?"Community Event":"Open House"} — ${l.property_address}`,Ee=[[l.city,l.state].filter(Boolean).join(", "),l.event_date?Ys(new Date(l.event_date+"T00:00:00"),"EEE, MMM d"):null,he!=null&&he.name?`Hosted by ${he.name}`:null].filter(Boolean).join(" · "),Re=l.photo_url||"",ke=Re&&Re.includes("/storage/v1/object/public/")?Re.replace("/object/public/","/render/image/public/")+"?width=1200&height=630&resize=cover":Re||"https://dashboard.relevelup.com/og-image.png",Fe=typeof window<"u"?window.location.href:`https://guestbook.relevelup.com/${n}`;return e.jsxs(e.Fragment,{children:[e.jsxs(Sc,{children:[e.jsx("title",{children:je}),e.jsx("meta",{name:"description",content:Ee||`Sign in to ${l.property_address}`}),e.jsx("meta",{property:"og:type",content:"website"}),e.jsx("meta",{property:"og:title",content:je}),e.jsx("meta",{property:"og:description",content:Ee||`Sign in to ${l.property_address}`}),e.jsx("meta",{property:"og:image",content:ke}),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:Fe}),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:je}),e.jsx("meta",{name:"twitter:description",content:Ee||`Sign in to ${l.property_address}`}),e.jsx("meta",{name:"twitter:image",content:ke}),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(Wa,{className:"h-16 w-16 mx-auto mb-3 ring-2 ring-white/20",children:[e.jsx(eo,{src:(he==null?void 0:he.avatar_url)||"",alt:(he==null?void 0:he.name)||""}),e.jsx(Ka,{className:"bg-white/10 text-white text-lg",children:Se})]}),e.jsx("p",{className:"text-white/60 text-sm",children:he==null?void 0:he.name}),(he==null?void 0:he.title)&&e.jsx("p",{className:"text-white/40 text-xs",children:he.title})]}),e.jsxs("div",{className:"bg-white rounded-2xl shadow-2xl overflow-hidden",children:[l.photo_url&&e.jsxs("div",{className:"relative h-44 sm:h-52 overflow-hidden",children:[e.jsx("img",{src:l.photo_url,alt:l.property_address,className:"w-full h-full object-cover"}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-slate-900/80 via-slate-900/20 to-transparent"}),e.jsxs("div",{className:"absolute bottom-0 left-0 right-0 px-6 pb-4",children:[e.jsx("h1",{className:"text-white font-bold text-lg leading-tight drop-shadow-md",children:l.property_address}),e.jsxs("div",{className:"flex flex-wrap gap-3 mt-1.5 text-white/70 text-xs",children:[l.city&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Si,{className:"h-3 w-3"}),l.city,l.state?`, ${l.state}`:""," ",l.zip]}),!Ie&&e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ha,{className:"h-3 w-3"}),Ys(new Date(l.event_date+"T00:00:00"),"MMM d, yyyy")]}),l.start_time&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(sa,{className:"h-3 w-3"}),fe(l.start_time),l.end_time?` – ${fe(l.end_time)}`:""]})]})]})]})]}),!l.photo_url&&e.jsx("div",{className:"bg-gradient-to-r from-slate-800 to-slate-700 px-6 py-5",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-xl bg-white/10 flex items-center justify-center shrink-0 mt-0.5",children:Te?e.jsx(Gi,{className:"h-5 w-5 text-white"}):e.jsx(ua,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-white font-bold text-lg leading-tight",children:l.property_address}),e.jsxs("div",{className:"flex flex-wrap gap-3 mt-2 text-white/60 text-xs",children:[l.city&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Si,{className:"h-3 w-3"}),l.city,l.state?`, ${l.state}`:""," ",l.zip]}),!Ie&&e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ha,{className:"h-3 w-3"}),Ys(new Date(l.event_date+"T00:00:00"),"MMM d, yyyy")]}),l.start_time&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(sa,{className:"h-3 w-3"}),fe(l.start_time),l.end_time?` – ${fe(l.end_time)}`:""]})]})]})]})]})}),e.jsxs("div",{className:"p-6",children:[p==="welcome"&&e.jsxs("div",{className:"text-center space-y-6",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-xl font-bold text-slate-900 mb-2",children:"Welcome!"}),e.jsx("p",{className:"text-slate-500 text-sm",children:l.agent_greeting||"Please sign in below."})]}),e.jsxs($,{onClick:()=>g("info"),className:"w-full h-14 text-base bg-slate-900 hover:bg-slate-800 text-white rounded-xl",children:["Sign In ",e.jsx(xi,{className:"h-5 w-5 ml-2"})]}),e.jsx("p",{className:"text-xs text-slate-400",children:"Quick & easy — takes 30 seconds"})]}),p==="info"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("button",{onClick:()=>g("welcome"),className:"text-slate-400 hover:text-slate-600",children:e.jsx(Ia,{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(re,{className:"text-slate-600 text-xs",children:"First Name *"}),e.jsx(be,{value:v.first_name,onChange:Ge=>_(yt=>({...yt,first_name:Ge.target.value})),placeholder:"First",className:"mt-1 h-12 rounded-xl border-slate-200 text-base",autoFocus:!0})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-slate-600 text-xs",children:"Last Name"}),e.jsx(be,{value:v.last_name,onChange:Ge=>_(yt=>({...yt,last_name:Ge.target.value})),placeholder:"Last",className:"mt-1 h-12 rounded-xl border-slate-200 text-base"})]})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-slate-600 text-xs",children:"Email"}),e.jsx(be,{type:"email",value:v.email,onChange:Ge=>_(yt=>({...yt,email:Ge.target.value})),placeholder:"your@email.com",className:"mt-1 h-12 rounded-xl border-slate-200 text-base"})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-slate-600 text-xs",children:"Phone"}),e.jsx(be,{type:"tel",value:v.phone,onChange:Ge=>_(yt=>({...yt,phone:Ge.target.value})),placeholder:"(555) 123-4567",className:"mt-1 h-12 rounded-xl border-slate-200 text-base"})]}),le&&e.jsxs("div",{children:[e.jsx(re,{className:"text-slate-600 text-xs",children:"Your Home Address"}),e.jsx(be,{value:v.visitor_address,onChange:Ge=>_(yt=>({...yt,visitor_address:Ge.target.value})),placeholder:"Street, City, State ZIP",className:"mt-1 h-12 rounded-xl border-slate-200 text-base",autoComplete:"street-address"})]}),e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer pt-1",children:[e.jsx("input",{type:"checkbox",checked:A,onChange:Ge=>M(Ge.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:I?"Yes":"No"}),e.jsx(On,{checked:I,onCheckedChange:P})]})]}),I&&e.jsx(be,{value:R,onChange:Ge=>O(Ge.target.value),placeholder:"Agent's name",className:"mt-1 h-10 rounded-xl border-slate-200 text-sm"})]}),B&&e.jsx("p",{className:"text-destructive text-sm",children:B}),e.jsxs($,{onClick:_e,className:"w-full h-14 text-base bg-slate-900 hover:bg-slate-800 text-white rounded-xl",children:["Continue ",e.jsx(xi,{className:"h-5 w-5 ml-2"})]})]}),p==="intent"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("button",{onClick:()=>g("info"),className:"text-slate-400 hover:text-slate-600",children:e.jsx(Ia,{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:h2s.map(Ge=>e.jsxs("button",{onClick:()=>ve(Ge.value),disabled:d.isPending,className:"flex flex-col items-center gap-2 p-5 rounded-xl border-2 border-slate-200 hover:border-slate-900 hover:bg-slate-50 transition-all text-center group",children:[e.jsx("span",{className:"text-2xl",children:Ge.emoji}),e.jsx("span",{className:"text-sm font-medium text-slate-700 group-hover:text-slate-900",children:Ge.label})]},Ge.value))}),B&&e.jsx("p",{className:"text-destructive text-sm text-center",children:B})]}),p==="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..."})]}),p==="survey"&&x&&oe&&e.jsx(a2s,{questions:oe,visitorId:x,onComplete:()=>g("done"),onSkip:()=>g("done")}),p==="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(Gr,{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,". ",Te?"Enjoy the event!":"Enjoy the open house!"]})]}),(l==null?void 0:l.disclosure_pdf_url)&&e.jsxs("a",{href:`https://docs.google.com/gview?url=${encodeURIComponent(l.disclosure_pdf_url)}&embedded=true`,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-2 px-5 py-3 rounded-xl bg-slate-100 hover:bg-slate-200 text-slate-800 font-medium text-sm transition-colors",children:[e.jsx(ea,{className:"h-4 w-4"}),"View Seller's Disclosures"]}),(he==null?void 0:he.name)&&e.jsxs("p",{className:"text-sm text-slate-400",children:["Your host today: ",e.jsx("strong",{className:"text-slate-600",children:he.name})]}),a&&e.jsxs("div",{className:"pt-4 space-y-3",children:[e.jsx($,{onClick:Y,className:"w-full h-14 text-base font-semibold rounded-xl",children:"Sign in next visitor"}),e.jsxs("p",{className:"text-xs text-slate-400",children:["Ready for the next visitor in ",G,"s…"]})]})]})]})]}),e.jsx("p",{className:"text-center text-white/30 text-xs mt-6",children:"Powered by LevelUp Guest Book"}),a&&e.jsxs("div",{className:"fixed top-3 right-3 flex items-center gap-2 z-50",children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-full bg-white/10 backdrop-blur-sm text-white/80 text-[11px] px-2.5 py-1 border border-white/10",children:[e.jsx(fB,{className:"h-3 w-3"})," Tablet Mode"]}),e.jsx("button",{onClick:ee,className:"inline-flex items-center gap-1 rounded-full bg-white/10 backdrop-blur-sm text-white/80 text-[11px] px-2.5 py-1 border border-white/10 hover:bg-white/20",title:"Enter full screen",children:e.jsx(FK,{className:"h-3 w-3"})})]})]})})]})}function BQn(s){const{user:t}=ks();return pt({queryKey:["cohost-tokens",s],queryFn:async()=>{const{data:n,error:r}=await V.from("open_house_cohost_tokens").select("*").eq("open_house_id",s).order("created_at",{ascending:!1});if(r)throw r;return n},enabled:!!t&&!!s})}function $Qn(){const s=ls(),{user:t}=ks();return Nt({mutationFn:async({openHouseId:n,label:r})=>{const{data:a,error:i}=await V.from("open_house_cohost_tokens").insert({open_house_id:n,label:r||null,created_by:t.id,expires_at:new Date(Date.now()+864e5).toISOString()}).select().single();if(i)throw i;return a},onSuccess:(n,r)=>{s.invalidateQueries({queryKey:["cohost-tokens",r.openHouseId]})}})}function UQn(){const s=ls();return Nt({mutationFn:async({id:t,openHouseId:n})=>{const{error:r}=await V.from("open_house_cohost_tokens").update({is_active:!1}).eq("id",t);if(r)throw r},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["cohost-tokens",n.openHouseId]})}})}function m2s(s){return pt({queryKey:["cohost-validate",s],queryFn:async()=>{const{data:t,error:n}=await V.from("open_house_cohost_tokens").select("*, open_houses(*)").eq("token",s).eq("is_active",!0).single();if(n)throw n;if(t.expires_at&&new Date(t.expires_at)-1&&s.splice(n,1)}const H5=(s,t,n)=>n>t?t:n{};const CM={},uEt=s=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(s),hEt=s=>typeof s=="object"&&s!==null,mEt=s=>/^0[^.\s]+$/u.test(s);function fEt(s){let t;return()=>(t===void 0&&(t=s()),t)}const C2=s=>s,wee=(...s)=>s.reduce((t,n)=>r=>n(t(r))),ZZ=(s,t,n)=>{const r=t-s;return r?(n-s)/r:1};class OGe{constructor(){this.subscriptions=[]}add(t){return DGe(this.subscriptions,t),()=>fSe(this.subscriptions,t)}notify(t,n,r){const a=this.subscriptions.length;if(a)if(a===1)this.subscriptions[0](t,n,r);else for(let i=0;is*1e3,m2=s=>s/1e3,pEt=(s,t)=>t?s*(1e3/t):0,gEt=(s,t,n)=>(((1-3*n+3*t)*s+(3*n-6*t))*s+3*t)*s,p2s=1e-7,g2s=12;function x2s(s,t,n,r,a){let i,l,o=0;do l=t+(n-t)/2,i=gEt(l,r,a)-s,i>0?n=l:t=l;while(Math.abs(i)>p2s&&++ox2s(i,0,1,s,n);return i=>i===0||i===1?i:gEt(a(i),t,r)}const xEt=s=>t=>t<=.5?s(2*t)/2:(2-s(2*(1-t)))/2,yEt=s=>t=>1-s(1-t),vEt=jee(.33,1.53,.69,.99),FGe=yEt(vEt),bEt=xEt(FGe),_Et=s=>s>=1?1:(s*=2)<1?.5*FGe(s):.5*(2-Math.pow(2,-10*(s-1))),zGe=s=>1-Math.sin(Math.acos(s)),wEt=yEt(zGe),jEt=xEt(zGe),y2s=jee(.42,0,1,1),v2s=jee(0,0,.58,1),NEt=jee(.42,0,.58,1),b2s=s=>Array.isArray(s)&&typeof s[0]!="number",kEt=s=>Array.isArray(s)&&typeof s[0]=="number",_2s={linear:C2,easeIn:y2s,easeInOut:NEt,easeOut:v2s,circIn:zGe,circInOut:jEt,circOut:wEt,backIn:FGe,backInOut:bEt,backOut:vEt,anticipate:_Et},w2s=s=>typeof s=="string",dlt=s=>{if(kEt(s)){lAe(s.length===4);const[t,n,r,a]=s;return jee(t,n,r,a)}else if(w2s(s))return _2s[s];return s},sre=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"];function j2s(s){let t=new Set,n=new Set,r=!1,a=!1;const i=new WeakSet;let l={delta:0,timestamp:0,isProcessing:!1};function o(d){i.has(d)&&(c.schedule(d),s()),d(l)}const c={schedule:(d,u=!1,h=!1)=>{const p=h&&r?t:n;return u&&i.add(d),p.add(d),d},cancel:d=>{n.delete(d),i.delete(d)},process:d=>{if(l=d,r){a=!0;return}r=!0;const u=t;t=n,n=u,t.forEach(o),t.clear(),r=!1,a&&(a=!1,c.process(d))}};return c}const N2s=40;function SEt(s,t){let n=!1,r=!0;const a={delta:0,timestamp:0,isProcessing:!1},i=()=>n=!0,l=sre.reduce((j,C)=>(j[C]=j2s(i),j),{}),{setup:o,read:c,resolveKeyframes:d,preUpdate:u,update:h,preRender:m,render:p,postRender:g}=l,x=()=>{const j=CM.useManualTiming,C=j?a.timestamp:performance.now();n=!1,j||(a.delta=r?1e3/60:Math.max(Math.min(C-a.timestamp,N2s),1)),a.timestamp=C,a.isProcessing=!0,o.process(a),c.process(a),d.process(a),u.process(a),h.process(a),m.process(a),p.process(a),g.process(a),a.isProcessing=!1,n&&t&&(r=!1,s(x))},y=()=>{n=!0,r=!0,a.isProcessing||s(x)};return{schedule:sre.reduce((j,C)=>{const A=l[C];return j[C]=(M,I=!1,P=!1)=>(n||y(),A.schedule(M,I,P)),j},{}),cancel:j=>{for(let C=0;C(sNe===void 0&&ob.set(K0.isProcessing||CM.useManualTiming?K0.timestamp:performance.now()),sNe),set:s=>{sNe=s,queueMicrotask(k2s)}},CEt=s=>t=>typeof t=="string"&&t.startsWith(s),AEt=CEt("--"),S2s=CEt("var(--"),BGe=s=>S2s(s)?C2s.test(s.split("/*")[0].trim()):!1,C2s=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu;function ult(s){return typeof s!="string"?!1:s.split("/*")[0].includes("var(--")}const Gq={test:s=>typeof s=="number",parse:parseFloat,transform:s=>s},XZ={...Gq,transform:s=>H5(0,1,s)},nre={...Gq,default:1},bY=s=>Math.round(s*1e5)/1e5,$Ge=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function A2s(s){return s==null}const E2s=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,UGe=(s,t)=>n=>!!(typeof n=="string"&&E2s.test(n)&&n.startsWith(s)||t&&!A2s(n)&&Object.prototype.hasOwnProperty.call(n,t)),EEt=(s,t,n)=>r=>{if(typeof r!="string")return r;const[a,i,l,o]=r.match($Ge);return{[s]:parseFloat(a),[t]:parseFloat(i),[n]:parseFloat(l),alpha:o!==void 0?parseFloat(o):1}},T2s=s=>H5(0,255,s),TIe={...Gq,transform:s=>Math.round(T2s(s))},rD={test:UGe("rgb","red"),parse:EEt("red","green","blue"),transform:({red:s,green:t,blue:n,alpha:r=1})=>"rgba("+TIe.transform(s)+", "+TIe.transform(t)+", "+TIe.transform(n)+", "+bY(XZ.transform(r))+")"};function M2s(s){let t="",n="",r="",a="";return s.length>5?(t=s.substring(1,3),n=s.substring(3,5),r=s.substring(5,7),a=s.substring(7,9)):(t=s.substring(1,2),n=s.substring(2,3),r=s.substring(3,4),a=s.substring(4,5),t+=t,n+=n,r+=r,a+=a),{red:parseInt(t,16),green:parseInt(n,16),blue:parseInt(r,16),alpha:a?parseInt(a,16)/255:1}}const k7e={test:UGe("#"),parse:M2s,transform:rD.transform},Nee=s=>({test:t=>typeof t=="string"&&t.endsWith(s)&&t.split(" ").length===1,parse:parseFloat,transform:t=>`${t}${s}`}),oC=Nee("deg"),D5=Nee("%"),No=Nee("px"),P2s=Nee("vh"),I2s=Nee("vw"),hlt={...D5,parse:s=>D5.parse(s)/100,transform:s=>D5.transform(s*100)},hz={test:UGe("hsl","hue"),parse:EEt("hue","saturation","lightness"),transform:({hue:s,saturation:t,lightness:n,alpha:r=1})=>"hsla("+Math.round(s)+", "+D5.transform(bY(t))+", "+D5.transform(bY(n))+", "+bY(XZ.transform(r))+")"},Ex={test:s=>rD.test(s)||k7e.test(s)||hz.test(s),parse:s=>rD.test(s)?rD.parse(s):hz.test(s)?hz.parse(s):k7e.parse(s),transform:s=>typeof s=="string"?s:s.hasOwnProperty("red")?rD.transform(s):hz.transform(s),getAnimatableNone:s=>{const t=Ex.parse(s);return t.alpha=0,Ex.transform(t)}},L2s=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function R2s(s){var t,n;return isNaN(s)&&typeof s=="string"&&(((t=s.match($Ge))==null?void 0:t.length)||0)+(((n=s.match(L2s))==null?void 0:n.length)||0)>0}const TEt="number",MEt="color",D2s="var",O2s="var(",mlt="${}",F2s=/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 jU(s){const t=s.toString(),n=[],r={color:[],number:[],var:[]},a=[];let i=0;const o=t.replace(F2s,c=>(Ex.test(c)?(r.color.push(i),a.push(MEt),n.push(Ex.parse(c))):c.startsWith(O2s)?(r.var.push(i),a.push(D2s),n.push(c)):(r.number.push(i),a.push(TEt),n.push(parseFloat(c))),++i,mlt)).split(mlt);return{values:n,split:o,indexes:r,types:a}}function z2s(s){return jU(s).values}function PEt({split:s,types:t}){const n=s.length;return r=>{let a="";for(let i=0;itypeof s=="number"?0:Ex.test(s)?Ex.getAnimatableNone(s):s,U2s=(s,t)=>typeof s=="number"?t!=null&&t.trim().endsWith("/")?s:0:$2s(s);function q2s(s){const t=jU(s);return PEt(t)(t.values.map((r,a)=>U2s(r,t.split[a])))}const uk={test:R2s,parse:z2s,createTransformer:B2s,getAnimatableNone:q2s};function MIe(s,t,n){return n<0&&(n+=1),n>1&&(n-=1),n<1/6?s+(t-s)*6*n:n<1/2?t:n<2/3?s+(t-s)*(2/3-n)*6:s}function V2s({hue:s,saturation:t,lightness:n,alpha:r}){s/=360,t/=100,n/=100;let a=0,i=0,l=0;if(!t)a=i=l=n;else{const o=n<.5?n*(1+t):n+t-n*t,c=2*n-o;a=MIe(c,o,s+1/3),i=MIe(c,o,s),l=MIe(c,o,s-1/3)}return{red:Math.round(a*255),green:Math.round(i*255),blue:Math.round(l*255),alpha:r}}function pSe(s,t){return n=>n>0?t:s}const pm=(s,t,n)=>s+(t-s)*n,PIe=(s,t,n)=>{const r=s*s,a=n*(t*t-r)+r;return a<0?0:Math.sqrt(a)},H2s=[k7e,rD,hz],G2s=s=>H2s.find(t=>t.test(s));function flt(s){const t=G2s(s);if(!t)return!1;let n=t.parse(s);return t===hz&&(n=V2s(n)),n}const plt=(s,t)=>{const n=flt(s),r=flt(t);if(!n||!r)return pSe(s,t);const a={...n};return i=>(a.red=PIe(n.red,r.red,i),a.green=PIe(n.green,r.green,i),a.blue=PIe(n.blue,r.blue,i),a.alpha=pm(n.alpha,r.alpha,i),rD.transform(a))},S7e=new Set(["none","hidden"]);function W2s(s,t){return S7e.has(s)?n=>n<=0?s:t:n=>n>=1?t:s}function K2s(s,t){return n=>pm(s,t,n)}function qGe(s){return typeof s=="number"?K2s:typeof s=="string"?BGe(s)?pSe:Ex.test(s)?plt:X2s:Array.isArray(s)?IEt:typeof s=="object"?Ex.test(s)?plt:Y2s:pSe}function IEt(s,t){const n=[...s],r=n.length,a=s.map((i,l)=>qGe(i)(i,t[l]));return i=>{for(let l=0;l{for(const i in r)n[i]=r[i](a);return n}}function Z2s(s,t){const n=[],r={color:0,var:0,number:0};for(let a=0;a{const n=uk.createTransformer(t),r=jU(s),a=jU(t);return r.indexes.var.length===a.indexes.var.length&&r.indexes.color.length===a.indexes.color.length&&r.indexes.number.length>=a.indexes.number.length?S7e.has(s)&&!a.values.length||S7e.has(t)&&!r.values.length?W2s(s,t):wee(IEt(Z2s(r,a),a.values),n):pSe(s,t)};function LEt(s,t,n){return typeof s=="number"&&typeof t=="number"&&typeof n=="number"?pm(s,t,n):qGe(s)(s,t)}const Q2s=s=>{const t=({timestamp:n})=>s(n);return{start:(n=!0)=>ym.update(t,n),stop:()=>AM(t),now:()=>K0.isProcessing?K0.timestamp:ob.now()}},REt=(s,t,n=10)=>{let r="";const a=Math.max(Math.round(t/n),2);for(let i=0;i=gSe?1/0:t}function J2s(s,t=100,n){const r=n({...s,keyframes:[0,t]}),a=Math.min(VGe(r),gSe);return{type:"keyframes",ease:i=>r.next(a*i).value/t,duration:m2(a)}}const mg={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 C7e(s,t){return s*Math.sqrt(1-t*t)}const eNs=12;function tNs(s,t,n){let r=n;for(let a=1;a{const u=d*l,h=u*s,m=u-n,p=C7e(d,l),g=Math.exp(-h);return IIe-m/p*g},i=d=>{const h=d*l*s,m=h*n+n,p=Math.pow(l,2)*Math.pow(d,2)*s,g=Math.exp(-h),x=C7e(Math.pow(d,2),l);return(-a(d)+IIe>0?-1:1)*((m-p)*g)/x}):(a=d=>{const u=Math.exp(-d*s),h=(d-n)*s+1;return-IIe+u*h},i=d=>{const u=Math.exp(-d*s),h=(n-d)*(s*s);return u*h});const o=5/s,c=tNs(a,i,o);if(s=Qw(s),isNaN(c))return{stiffness:mg.stiffness,damping:mg.damping,duration:s};{const d=Math.pow(c,2)*r;return{stiffness:d,damping:l*2*Math.sqrt(r*d),duration:s}}}const nNs=["duration","bounce"],rNs=["stiffness","damping","mass"];function glt(s,t){return t.some(n=>s[n]!==void 0)}function aNs(s){let t={velocity:mg.velocity,stiffness:mg.stiffness,damping:mg.damping,mass:mg.mass,isResolvedFromDuration:!1,...s};if(!glt(s,rNs)&&glt(s,nNs))if(t.velocity=0,s.visualDuration){const n=s.visualDuration,r=2*Math.PI/(n*1.2),a=r*r,i=2*H5(.05,1,1-(s.bounce||0))*Math.sqrt(a);t={...t,mass:mg.mass,stiffness:a,damping:i}}else{const n=sNs({...s,velocity:0});t={...t,...n,mass:mg.mass},t.isResolvedFromDuration=!0}return t}function xSe(s=mg.visualDuration,t=mg.bounce){const n=typeof s!="object"?{visualDuration:s,keyframes:[0,1],bounce:t}:s;let{restSpeed:r,restDelta:a}=n;const i=n.keyframes[0],l=n.keyframes[n.keyframes.length-1],o={done:!1,value:i},{stiffness:c,damping:d,mass:u,duration:h,velocity:m,isResolvedFromDuration:p}=aNs({...n,velocity:-m2(n.velocity||0)}),g=m||0,x=d/(2*Math.sqrt(c*u)),y=l-i,v=m2(Math.sqrt(c/u)),_=Math.abs(y)<5;r||(r=_?mg.restSpeed.granular:mg.restSpeed.default),a||(a=_?mg.restDelta.granular:mg.restDelta.default);let j,C,A,M,I,P;if(x<1)A=C7e(v,x),M=(g+x*v*y)/A,j=O=>{const B=Math.exp(-x*v*O);return l-B*(M*Math.sin(A*O)+y*Math.cos(A*O))},I=x*v*M+y*A,P=x*v*y-M*A,C=O=>Math.exp(-x*v*O)*(I*Math.sin(A*O)+P*Math.cos(A*O));else if(x===1){j=B=>l-Math.exp(-v*B)*(y+(g+v*y)*B);const O=g+v*y;C=B=>Math.exp(-v*B)*(v*O*B-g)}else{const O=v*Math.sqrt(x*x-1);j=H=>{const Y=Math.exp(-x*v*H),se=Math.min(O*H,300);return l-Y*((g+x*v*y)*Math.sinh(se)+O*y*Math.cosh(se))/O};const B=(g+x*v*y)/O,U=x*v*B-y*O,G=x*v*y-B*O;C=H=>{const Y=Math.exp(-x*v*H),se=Math.min(O*H,300);return Y*(U*Math.sinh(se)+G*Math.cosh(se))}}const R={calculatedDuration:p&&h||null,velocity:O=>Qw(C(O)),next:O=>{if(!p&&x<1){const U=Math.exp(-x*v*O),G=Math.sin(A*O),H=Math.cos(A*O),Y=l-U*(M*G+y*H),se=Qw(U*(I*G+P*H));return o.done=Math.abs(se)<=r&&Math.abs(l-Y)<=a,o.value=o.done?l:Y,o}const B=j(O);if(p)o.done=O>=h;else{const U=Qw(C(O));o.done=Math.abs(U)<=r&&Math.abs(l-B)<=a}return o.value=o.done?l:B,o},toString:()=>{const O=Math.min(VGe(R),gSe),B=REt(U=>R.next(O*U).value,O,30);return O+"ms "+B},toTransition:()=>{}};return R}xSe.applyToOptions=s=>{const t=J2s(s,100,xSe);return s.ease=t.ease,s.duration=Qw(t.duration),s.type="keyframes",s};const iNs=5;function DEt(s,t,n){const r=Math.max(t-iNs,0);return pEt(n-s(r),t-r)}function A7e({keyframes:s,velocity:t=0,power:n=.8,timeConstant:r=325,bounceDamping:a=10,bounceStiffness:i=500,modifyTarget:l,min:o,max:c,restDelta:d=.5,restSpeed:u}){const h=s[0],m={done:!1,value:h},p=P=>o!==void 0&&Pc,g=P=>o===void 0?c:c===void 0||Math.abs(o-P)-x*Math.exp(-P/r),j=P=>v+_(P),C=P=>{const R=_(P),O=j(P);m.done=Math.abs(R)<=d,m.value=m.done?v:O};let A,M;const I=P=>{p(m.value)&&(A=P,M=xSe({keyframes:[m.value,g(m.value)],velocity:DEt(j,P,m.value),damping:a,stiffness:i,restDelta:d,restSpeed:u}))};return I(0),{calculatedDuration:null,next:P=>{let R=!1;return!M&&A===void 0&&(R=!0,C(P),I(P)),A!==void 0&&P>=A?M.next(P-A):(!R&&C(P),m)}}}function oNs(s,t,n){const r=[],a=n||CM.mix||LEt,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=oNs(t,r,a),c=o.length,d=u=>{if(l&&u1)for(;hd(H5(s[0],s[i-1],u)):d}function cNs(s,t){const n=s[s.length-1];for(let r=1;r<=t;r++){const a=ZZ(0,t,r);s.push(pm(n,1,a))}}function dNs(s){const t=[0];return cNs(t,s.length-1),t}function uNs(s,t){return s.map(n=>n*t)}function hNs(s,t){return s.map(()=>t||NEt).splice(0,s.length-1)}function _Y({duration:s=300,keyframes:t,times:n,ease:r="easeInOut"}){const a=b2s(r)?r.map(dlt):dlt(r),i={done:!1,value:t[0]},l=uNs(n&&n.length===t.length?n:dNs(t),s),o=lNs(l,t,{ease:Array.isArray(a)?a:hNs(t,a)});return{calculatedDuration:s,next:c=>(i.value=o(c),i.done=c>=s,i)}}const mNs=s=>s!==null;function cAe(s,{repeat:t,repeatType:n="loop"},r,a=1){const i=s.filter(mNs),o=a<0||t&&n!=="loop"&&t%2===1?0:i.length-1;return!o||r===void 0?i[o]:r}const fNs={decay:A7e,inertia:A7e,tween:_Y,keyframes:_Y,spring:xSe};function OEt(s){typeof s.type=="string"&&(s.type=fNs[s.type])}class HGe{constructor(){this.updateFinished()}get finished(){return this._finished}updateFinished(){this._finished=new Promise(t=>{this.resolve=t})}notifyFinished(){this.resolve()}then(t,n){return this.finished.then(t,n)}}const pNs=s=>s/100;class ySe extends HGe{constructor(t){super(),this.state="idle",this.startTime=null,this.isStopped=!1,this.currentTime=0,this.holdTime=null,this.playbackSpeed=1,this.delayState={done:!1,value:void 0},this.stop=()=>{var r,a;const{motionValue:n}=this.options;n&&n.updatedAt!==ob.now()&&this.tick(ob.now()),this.isStopped=!0,this.state!=="idle"&&(this.teardown(),(a=(r=this.options).onStop)==null||a.call(r))},this.options=t,this.initAnimation(),this.play(),t.autoplay===!1&&this.pause()}initAnimation(){const{options:t}=this;OEt(t);const{type:n=_Y,repeat:r=0,repeatDelay:a=0,repeatType:i,velocity:l=0}=t;let{keyframes:o}=t;const c=n||_Y;c!==_Y&&typeof o[0]!="number"&&(this.mixKeyframes=wee(pNs,LEt(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=VGe(d));const{calculatedDuration:u}=d;this.calculatedDuration=u,this.resolvedDuration=u+a,this.totalDuration=this.resolvedDuration*(r+1)-a,this.generator=d}updateTime(t){const n=Math.round(t-this.startTime)*this.playbackSpeed;this.holdTime!==null?this.currentTime=this.holdTime:this.currentTime=n}tick(t,n=!1){const{generator:r,totalDuration:a,mixKeyframes:i,mirroredGenerator:l,resolvedDuration:o,calculatedDuration:c}=this;if(this.startTime===null)return r.next(0);const{delay:d=0,keyframes:u,repeat:h,repeatType:m,repeatDelay:p,type:g,onUpdate:x,finalKeyframe:y}=this.options;this.speed>0?this.startTime=Math.min(this.startTime,t):this.speed<0&&(this.startTime=Math.min(t-a/this.speed,this.startTime)),n?this.currentTime=t:this.updateTime(t);const v=this.currentTime-d*(this.playbackSpeed>=0?1:-1),_=this.playbackSpeed>=0?v<0:v>a;this.currentTime=Math.max(v,0),this.state==="finished"&&this.holdTime===null&&(this.currentTime=a);let j=this.currentTime,C=r;if(h){const P=Math.min(this.currentTime,a)/o;let R=Math.floor(P),O=P%1;!O&&P>=1&&(O=1),O===1&&R--,R=Math.min(R,h+1),!!(R%2)&&(m==="reverse"?(O=1-O,p&&(O-=p/o)):m==="mirror"&&(C=l)),j=H5(0,1,O)*o}let A;_?(this.delayState.value=u[0],A=this.delayState):A=C.next(j),i&&!_&&(A.value=i(A.value));let{done:M}=A;!_&&c!==null&&(M=this.playbackSpeed>=0?this.currentTime>=a:this.currentTime<=0);const I=this.holdTime===null&&(this.state==="finished"||this.state==="running"&&M);return I&&g!==A7e&&(A.value=cAe(u,this.options,y,this.speed)),x&&x(A.value),I&&this.finish(),A}then(t,n){return this.finished.then(t,n)}get duration(){return m2(this.calculatedDuration)}get iterationDuration(){const{delay:t=0}=this.options||{};return this.duration+m2(t)}get time(){return m2(this.currentTime)}set time(t){t=Qw(t),this.currentTime=t,this.startTime===null||this.holdTime!==null||this.playbackSpeed===0?this.holdTime=t:this.driver&&(this.startTime=this.driver.now()-t/this.playbackSpeed),this.driver?this.driver.start(!1):(this.startTime=0,this.state="paused",this.holdTime=t,this.tick(t))}getGeneratorVelocity(){const t=this.currentTime;if(t<=0)return this.options.velocity||0;if(this.generator.velocity)return this.generator.velocity(t);const n=this.generator.next(t).value;return DEt(r=>this.generator.next(r).value,t,n)}get speed(){return this.playbackSpeed}set speed(t){const n=this.playbackSpeed!==t;n&&this.driver&&this.updateTime(ob.now()),this.playbackSpeed=t,n&&this.driver&&(this.time=m2(this.currentTime))}play(){var a,i;if(this.isStopped)return;const{driver:t=Q2s,startTime:n}=this.options;this.driver||(this.driver=t(l=>this.tick(l))),(i=(a=this.options).onPlay)==null||i.call(a);const r=this.driver.now();this.state==="finished"?(this.updateFinished(),this.startTime=r):this.holdTime!==null?this.startTime=r-this.holdTime:this.startTime||(this.startTime=n??r),this.state==="finished"&&this.speed<0&&(this.startTime+=this.calculatedDuration),this.holdTime=null,this.state="running",this.driver.start()}pause(){this.state="paused",this.updateTime(ob.now()),this.holdTime=this.currentTime}complete(){this.state!=="running"&&this.play(),this.state="finished",this.holdTime=null}finish(){var t,n;this.notifyFinished(),this.teardown(),this.state="finished",(n=(t=this.options).onComplete)==null||n.call(t)}cancel(){var t,n;this.holdTime=null,this.startTime=0,this.tick(0),this.teardown(),(n=(t=this.options).onCancel)==null||n.call(t)}teardown(){this.state="idle",this.stopDriver(),this.startTime=this.holdTime=null}stopDriver(){this.driver&&(this.driver.stop(),this.driver=void 0)}sample(t){return this.startTime=0,this.tick(t,!0)}attachTimeline(t){var n;return this.options.allowFlatten&&(this.options.type="keyframes",this.options.ease="linear",this.initAnimation()),(n=this.driver)==null||n.stop(),t.observe(this)}}function gNs(s){for(let t=1;ts*180/Math.PI,E7e=s=>{const t=aD(Math.atan2(s[1],s[0]));return T7e(t)},xNs={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:s=>(Math.abs(s[0])+Math.abs(s[3]))/2,rotate:E7e,rotateZ:E7e,skewX:s=>aD(Math.atan(s[1])),skewY:s=>aD(Math.atan(s[2])),skew:s=>(Math.abs(s[1])+Math.abs(s[2]))/2},T7e=s=>(s=s%360,s<0&&(s+=360),s),xlt=E7e,ylt=s=>Math.sqrt(s[0]*s[0]+s[1]*s[1]),vlt=s=>Math.sqrt(s[4]*s[4]+s[5]*s[5]),yNs={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:ylt,scaleY:vlt,scale:s=>(ylt(s)+vlt(s))/2,rotateX:s=>T7e(aD(Math.atan2(s[6],s[5]))),rotateY:s=>T7e(aD(Math.atan2(-s[2],s[0]))),rotateZ:xlt,rotate:xlt,skewX:s=>aD(Math.atan(s[4])),skewY:s=>aD(Math.atan(s[1])),skew:s=>(Math.abs(s[1])+Math.abs(s[4]))/2};function M7e(s){return s.includes("scale")?1:0}function P7e(s,t){if(!s||s==="none")return M7e(t);const n=s.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);let r,a;if(n)r=yNs,a=n;else{const o=s.match(/^matrix\(([-\d.e\s,]+)\)$/u);r=xNs,a=o}if(!a)return M7e(t);const i=r[t],l=a[1].split(",").map(bNs);return typeof i=="function"?i(l):l[i]}const vNs=(s,t)=>{const{transform:n="none"}=getComputedStyle(s);return P7e(n,t)};function bNs(s){return parseFloat(s.trim())}const Wq=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],Kq=new Set([...Wq,"pathRotation"]),blt=s=>s===Gq||s===No,_Ns=new Set(["x","y","z"]),wNs=Wq.filter(s=>!_Ns.has(s));function jNs(s){const t=[];return wNs.forEach(n=>{const r=s.getValue(n);r!==void 0&&(t.push([n,r.get()]),r.set(n.startsWith("scale")?1:0))}),t}const bT={width:({x:s},{paddingLeft:t="0",paddingRight:n="0",boxSizing:r})=>{const a=s.max-s.min;return r==="border-box"?a:a-parseFloat(t)-parseFloat(n)},height:({y:s},{paddingTop:t="0",paddingBottom:n="0",boxSizing:r})=>{const a=s.max-s.min;return r==="border-box"?a:a-parseFloat(t)-parseFloat(n)},top:(s,{top:t})=>parseFloat(t),left:(s,{left:t})=>parseFloat(t),bottom:({y:s},{top:t})=>parseFloat(t)+(s.max-s.min),right:({x:s},{left:t})=>parseFloat(t)+(s.max-s.min),x:(s,{transform:t})=>P7e(t,"x"),y:(s,{transform:t})=>P7e(t,"y")};bT.translateX=bT.x;bT.translateY=bT.y;const J8=new Set;let I7e=!1,L7e=!1,R7e=!1;function FEt(){if(L7e){const s=Array.from(J8).filter(r=>r.needsMeasurement),t=new Set(s.map(r=>r.element)),n=new Map;t.forEach(r=>{const a=jNs(r);a.length&&(n.set(r,a),r.render())}),s.forEach(r=>r.measureInitialState()),t.forEach(r=>{r.render();const a=n.get(r);a&&a.forEach(([i,l])=>{var o;(o=r.getValue(i))==null||o.set(l)})}),s.forEach(r=>r.measureEndState()),s.forEach(r=>{r.suspendedScrollY!==void 0&&window.scrollTo(0,r.suspendedScrollY)})}L7e=!1,I7e=!1,J8.forEach(s=>s.complete(R7e)),J8.clear()}function zEt(){J8.forEach(s=>{s.readKeyframes(),s.needsMeasurement&&(L7e=!0)})}function NNs(){R7e=!0,zEt(),FEt(),R7e=!1}class GGe{constructor(t,n,r,a,i,l=!1){this.state="pending",this.isAsync=!1,this.needsMeasurement=!1,this.unresolvedKeyframes=[...t],this.onComplete=n,this.name=r,this.motionValue=a,this.element=i,this.isAsync=l}scheduleResolve(){this.state="scheduled",this.isAsync?(J8.add(this),I7e||(I7e=!0,ym.read(zEt),ym.resolveKeyframes(FEt))):(this.readKeyframes(),this.complete())}readKeyframes(){const{unresolvedKeyframes:t,name:n,element:r,motionValue:a}=this;if(t[0]===null){const i=a==null?void 0:a.get(),l=t[t.length-1];if(i!==void 0)t[0]=i;else if(r&&n){const o=r.readValue(n,l);o!=null&&(t[0]=o)}t[0]===void 0&&(t[0]=l),a&&i===void 0&&a.set(t[0])}gNs(t)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(t=!1){this.state="complete",this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,t),J8.delete(this)}cancel(){this.state==="scheduled"&&(J8.delete(this),this.state="pending")}resume(){this.state==="pending"&&this.scheduleResolve()}}const kNs=s=>s.startsWith("--");function BEt(s,t,n){kNs(t)?s.style.setProperty(t,n):s.style[t]=n}const SNs={};function $Et(s,t){const n=fEt(s);return()=>SNs[t]??n()}const CNs=$Et(()=>window.ScrollTimeline!==void 0,"scrollTimeline"),UEt=$Et(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch{return!1}return!0},"linearEasing"),NW=([s,t,n,r])=>`cubic-bezier(${s}, ${t}, ${n}, ${r})`,_lt={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:NW([0,.65,.55,1]),circOut:NW([.55,0,1,.45]),backIn:NW([.31,.01,.66,-.59]),backOut:NW([.33,1.53,.69,.99])};function qEt(s,t){if(s)return typeof s=="function"?UEt()?REt(s,t):"ease-out":kEt(s)?NW(s):Array.isArray(s)?s.map(n=>qEt(n,t)||_lt.easeOut):_lt[s]}function ANs(s,t,n,{delay:r=0,duration:a=300,repeat:i=0,repeatType:l="loop",ease:o="easeOut",times:c}={},d=void 0){const u={[t]:n};c&&(u.offset=c);const h=qEt(o,a);Array.isArray(h)&&(u.easing=h);const m={delay:r,duration:a,easing:Array.isArray(h)?"linear":h,fill:"both",iterations:i+1,direction:l==="reverse"?"alternate":"normal"};return d&&(m.pseudoElement=d),s.animate(u,m)}function VEt(s){return typeof s=="function"&&"applyToOptions"in s}function ENs({type:s,...t}){return VEt(s)&&UEt()?s.applyToOptions(t):(t.duration??(t.duration=300),t.ease??(t.ease="easeOut"),t)}class HEt extends HGe{constructor(t){if(super(),this.finishedTime=null,this.isStopped=!1,this.manualStartTime=null,!t)return;const{element:n,name:r,keyframes:a,pseudoElement:i,allowFlatten:l=!1,finalKeyframe:o,onComplete:c}=t;this.isPseudoElement=!!i,this.allowFlatten=l,this.options=t,lAe(typeof t.type!="string");const d=ENs(t);this.animation=ANs(n,r,a,d,i),d.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!i){const u=cAe(a,this.options,o,this.speed);this.updateMotionValue&&this.updateMotionValue(u),BEt(n,r,u),this.animation.cancel()}c==null||c(),this.notifyFinished()}}play(){this.isStopped||(this.manualStartTime=null,this.animation.play(),this.state==="finished"&&this.updateFinished())}pause(){this.animation.pause()}complete(){var t,n;(n=(t=this.animation).finish)==null||n.call(t)}cancel(){try{this.animation.cancel()}catch{}}stop(){if(this.isStopped)return;this.isStopped=!0;const{state:t}=this;t==="idle"||t==="finished"||(this.updateMotionValue?this.updateMotionValue():this.commitStyles(),this.isPseudoElement||this.cancel())}commitStyles(){var n,r,a;const t=(n=this.options)==null?void 0:n.element;!this.isPseudoElement&&(t!=null&&t.isConnected)&&((a=(r=this.animation).commitStyles)==null||a.call(r))}get duration(){var n,r;const t=((r=(n=this.animation.effect)==null?void 0:n.getComputedTiming)==null?void 0:r.call(n).duration)||0;return m2(Number(t))}get iterationDuration(){const{delay:t=0}=this.options||{};return this.duration+m2(t)}get time(){return m2(Number(this.animation.currentTime)||0)}set time(t){const n=this.finishedTime!==null;this.manualStartTime=null,this.finishedTime=null,this.animation.currentTime=Qw(t),n&&this.animation.pause()}get speed(){return this.animation.playbackRate}set speed(t){t<0&&(this.finishedTime=null),this.animation.playbackRate=t}get state(){return this.finishedTime!==null?"finished":this.animation.playState}get startTime(){return this.manualStartTime??Number(this.animation.startTime)}set startTime(t){this.manualStartTime=this.animation.startTime=t}attachTimeline({timeline:t,rangeStart:n,rangeEnd:r,observe:a}){var i;return this.allowFlatten&&((i=this.animation.effect)==null||i.updateTiming({easing:"linear"})),this.animation.onfinish=null,t&&CNs()?(this.animation.timeline=t,n&&(this.animation.rangeStart=n),r&&(this.animation.rangeEnd=r),C2):a(this)}}const GEt={anticipate:_Et,backInOut:bEt,circInOut:jEt};function TNs(s){return s in GEt}function MNs(s){typeof s.ease=="string"&&TNs(s.ease)&&(s.ease=GEt[s.ease])}const LIe=10;class PNs extends HEt{constructor(t){MNs(t),OEt(t),super(t),t.startTime!==void 0&&t.autoplay!==!1&&(this.startTime=t.startTime),this.options=t}updateMotionValue(t){const{motionValue:n,onUpdate:r,onComplete:a,element:i,...l}=this.options;if(!n)return;if(t!==void 0){n.set(t);return}const o=new ySe({...l,autoplay:!1}),c=Math.max(LIe,ob.now()-this.startTime),d=H5(0,LIe,c-LIe),u=o.sample(c).value,{name:h}=this.options;i&&h&&BEt(i,h,u),n.setWithVelocity(o.sample(Math.max(0,c-d)).value,u,d),o.stop()}}const wlt=(s,t)=>t==="zIndex"?!1:!!(typeof s=="number"||Array.isArray(s)||typeof s=="string"&&(uk.test(s)||s==="0")&&!s.startsWith("url("));function INs(s){const t=s[0];if(s.length===1)return!0;for(let n=0;nObject.hasOwnProperty.call(Element.prototype,"animate"));function zNs(s){var h;const{motionValue:t,name:n,repeatDelay:r,repeatType:a,damping:i,type:l,keyframes:o}=s,c=(h=t==null?void 0:t.owner)==null?void 0:h.current;if(!(c instanceof HTMLElement)&&!(c instanceof SVGElement))return!1;const{onUpdate:d,transformTemplate:u}=t.owner.getProps();return FNs()&&n&&(WEt.has(n)||ONs.has(n)&&DNs(o))&&(n!=="transform"||!u)&&!d&&!r&&a!=="mirror"&&i!==0&&l!=="inertia"}const BNs=40;class $Ns extends HGe{constructor({autoplay:t=!0,delay:n=0,type:r="keyframes",repeat:a=0,repeatDelay:i=0,repeatType:l="loop",keyframes:o,name:c,motionValue:d,element:u,...h}){var g;super(),this.stop=()=>{var x,y;this._animation&&(this._animation.stop(),(x=this.stopTimeline)==null||x.call(this)),(y=this.keyframeResolver)==null||y.cancel()},this.createdAt=ob.now();const m={autoplay:t,delay:n,type:r,repeat:a,repeatDelay:i,repeatType:l,name:c,motionValue:d,element:u,...h},p=(u==null?void 0:u.KeyframeResolver)||GGe;this.keyframeResolver=new p(o,(x,y,v)=>this.onKeyframesResolved(x,y,m,!v),c,d,u),(g=this.keyframeResolver)==null||g.scheduleResolve()}onKeyframesResolved(t,n,r,a){var v,_;this.keyframeResolver=void 0;const{name:i,type:l,velocity:o,delay:c,isHandoff:d,onUpdate:u}=r;this.resolvedAt=ob.now();let h=!0;LNs(t,i,l,o)||(h=!1,(CM.instantAnimations||!c)&&(u==null||u(cAe(t,r,n))),t[0]=t[t.length-1],D7e(r),r.repeat=0);const p={startTime:a?this.resolvedAt?this.resolvedAt-this.createdAt>BNs?this.resolvedAt:this.createdAt:this.createdAt:void 0,finalKeyframe:n,...r,keyframes:t},g=h&&!d&&zNs(p),x=(_=(v=p.motionValue)==null?void 0:v.owner)==null?void 0:_.current;let y;if(g)try{y=new PNs({...p,element:x})}catch{y=new ySe(p)}else y=new ySe(p);y.finished.then(()=>{this.notifyFinished()}).catch(C2),this.pendingTimeline&&(this.stopTimeline=y.attachTimeline(this.pendingTimeline),this.pendingTimeline=void 0),this._animation=y}get finished(){return this._animation?this.animation.finished:this._finished}then(t,n){return this.finished.finally(t).then(()=>{})}get animation(){var t;return this._animation||((t=this.keyframeResolver)==null||t.resume(),NNs()),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 KEt(s,t,n,r=0,a=1){const i=Array.from(s).sort((d,u)=>d.sortNodePosition(u)).indexOf(t),l=s.size,o=(l-1)*r;return typeof n=="function"?n(i,l):a===1?i*r:o-i*r}const jlt=30,UNs=s=>!isNaN(parseFloat(s));class qNs{constructor(t,n={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=r=>{var i;const a=ob.now();if(this.updatedAt!==a&&this.setPrevFrameValue(),this.prev=this.current,this.setCurrent(r),this.current!==this.prev&&((i=this.events.change)==null||i.notify(this.current),this.dependents))for(const l of this.dependents)l.dirty()},this.hasAnimated=!1,this.setCurrent(t),this.owner=n.owner}setCurrent(t){this.current=t,this.updatedAt=ob.now(),this.canTrackVelocity===null&&t!==void 0&&(this.canTrackVelocity=UNs(this.current))}setPrevFrameValue(t=this.current){this.prevFrameValue=t,this.prevUpdatedAt=this.updatedAt}onChange(t){return this.on("change",t)}on(t,n){this.events[t]||(this.events[t]=new OGe);const r=this.events[t].add(n);return t==="change"?()=>{r(),ym.read(()=>{this.events.change.getSize()||this.stop()})}:r}clearListeners(){for(const t in this.events)this.events[t].clear()}attach(t,n){this.passiveEffect=t,this.stopPassiveEffect=n}set(t){this.passiveEffect?this.passiveEffect(t,this.updateAndNotify):this.updateAndNotify(t)}setWithVelocity(t,n,r){this.set(n),this.prev=void 0,this.prevFrameValue=t,this.prevUpdatedAt=this.updatedAt-r}jump(t,n=!0){this.updateAndNotify(t),this.prev=t,this.prevUpdatedAt=this.prevFrameValue=void 0,n&&this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}dirty(){var t;(t=this.events.change)==null||t.notify(this.current)}addDependent(t){this.dependents||(this.dependents=new Set),this.dependents.add(t)}removeDependent(t){this.dependents&&this.dependents.delete(t)}get(){return this.current}getPrevious(){return this.prev}getVelocity(){const t=ob.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||t-this.updatedAt>jlt)return 0;const n=Math.min(this.updatedAt-this.prevUpdatedAt,jlt);return pEt(parseFloat(this.current)-parseFloat(this.prevFrameValue),n)}start(t){return this.stop(),new Promise(n=>{this.hasAnimated=!0,this.animation=t(n),this.events.animationStart&&this.events.animationStart.notify()}).then(()=>{this.events.animationComplete&&this.events.animationComplete.notify(),this.clearAnimation()})}stop(){this.animation&&(this.animation.stop(),this.events.animationCancel&&this.events.animationCancel.notify()),this.clearAnimation()}isAnimating(){return!!this.animation}clearAnimation(){delete this.animation}destroy(){var t,n;(t=this.dependents)==null||t.clear(),(n=this.events.destroy)==null||n.notify(),this.clearListeners(),this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}}function NU(s,t){return new qNs(s,t)}function YEt(s,t){if(s!=null&&s.inherit&&t){const{inherit:n,...r}=s;return{...t,...r}}return s}function WGe(s,t){const n=(s==null?void 0:s[t])??(s==null?void 0:s.default)??s;return n!==s?YEt(n,s):n}const VNs={type:"spring",stiffness:500,damping:25,restSpeed:10},HNs=s=>({type:"spring",stiffness:550,damping:s===0?2*Math.sqrt(550):30,restSpeed:10}),GNs={type:"keyframes",duration:.8},WNs={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},KNs=(s,{keyframes:t})=>t.length>2?GNs:Kq.has(s)?s.startsWith("scale")?HNs(t[1]):VNs:WNs,YNs=new Set(["when","delay","delayChildren","staggerChildren","staggerDirection","repeat","repeatType","repeatDelay","from","elapsed"]);function ZNs(s){for(const t in s)if(!YNs.has(t))return!0;return!1}const KGe=(s,t,n,r={},a,i)=>l=>{const o=WGe(r,s)||{},c=o.delay||r.delay||0;let{elapsed:d=0}=r;d=d-Qw(c);const u={keyframes:Array.isArray(n)?n:[null,n],ease:"easeOut",velocity:t.getVelocity(),...o,delay:-d,onUpdate:m=>{t.set(m),o.onUpdate&&o.onUpdate(m)},onComplete:()=>{l(),o.onComplete&&o.onComplete()},name:s,motionValue:t,element:i?void 0:a};ZNs(o)||Object.assign(u,KNs(s,u)),u.duration&&(u.duration=Qw(u.duration)),u.repeatDelay&&(u.repeatDelay=Qw(u.repeatDelay)),u.from!==void 0&&(u.keyframes[0]=u.from);let h=!1;if((u.type===!1||u.duration===0&&!u.repeatDelay)&&(D7e(u),u.delay===0&&(h=!0)),(CM.instantAnimations||CM.skipAnimations||a!=null&&a.shouldSkipAnimations||o.skipAnimations)&&(h=!0,D7e(u),u.delay=0),u.allowFlatten=!o.type&&!o.ease,h&&!i&&t.get()!==void 0){const m=cAe(u.keyframes,o);if(m!==void 0){ym.update(()=>{u.onUpdate(m),u.onComplete()});return}}return o.isSync?new ySe(u):new $Ns(u)},XNs=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function QNs(s){const t=XNs.exec(s);if(!t)return[,];const[,n,r,a]=t;return[`--${n??r}`,a]}function ZEt(s,t,n=1){const[r,a]=QNs(s);if(!r)return;const i=window.getComputedStyle(t).getPropertyValue(r);if(i){const l=i.trim();return uEt(l)?parseFloat(l):l}return BGe(a)?ZEt(a,t,n+1):a}function Nlt(s){const t=[{},{}];return s==null||s.values.forEach((n,r)=>{t[0][r]=n.get(),t[1][r]=n.getVelocity()}),t}function YGe(s,t,n,r){if(typeof t=="function"){const[a,i]=Nlt(r);t=t(n!==void 0?n:s.custom,a,i)}if(typeof t=="string"&&(t=s.variants&&s.variants[t]),typeof t=="function"){const[a,i]=Nlt(r);t=t(n!==void 0?n:s.custom,a,i)}return t}function eO(s,t,n){const r=s.getProps();return YGe(r,t,n!==void 0?n:r.custom,s)}const XEt=new Set(["width","height","top","left","right","bottom",...Wq]),O7e=s=>Array.isArray(s);function JNs(s,t,n){s.hasValue(t)?s.getValue(t).set(n):s.addValue(t,NU(n))}function eks(s){return O7e(s)?s[s.length-1]||0:s}function tks(s,t){const n=eO(s,t);let{transitionEnd:r={},transition:a={},...i}=n||{};i={...i,...r};for(const l in i){const o=eks(i[l]);JNs(s,l,o)}}const av=s=>!!(s&&s.getVelocity);function sks(s){return!!(av(s)&&s.add)}function F7e(s,t){const n=s.getValue("willChange");if(sks(n))return n.add(t);if(!n&&CM.WillChange){const r=new CM.WillChange("auto");s.addValue("willChange",r),r.add(t)}}function ZGe(s){return s.replace(/([A-Z])/g,t=>`-${t.toLowerCase()}`)}const nks="framerAppearId",QEt="data-"+ZGe(nks);function JEt(s){return s.props[QEt]}function rks({protectedKeys:s,needsAnimating:t},n){const r=s.hasOwnProperty(n)&&t[n]!==!0;return t[n]=!1,r}function eTt(s,t,{delay:n=0,transitionOverride:r,type:a}={}){let{transition:i,transitionEnd:l,...o}=t;const c=s.getDefaultTransition();i=i?YEt(i,c):c;const d=i==null?void 0:i.reduceMotion,u=i==null?void 0:i.skipAnimations;r&&(i=r);const h=[],m=a&&s.animationState&&s.animationState.getState()[a],p=i==null?void 0:i.path;p&&p.animateVisualElement(s,o,i,n,h);for(const g in o){const x=s.getValue(g,s.latestValues[g]??null),y=o[g];if(y===void 0||m&&rks(m,g))continue;const v={delay:n,...WGe(i||{},g)};u&&(v.skipAnimations=!0);const _=x.get();if(_!==void 0&&!x.isAnimating()&&!Array.isArray(y)&&y===_&&!v.velocity){ym.update(()=>x.set(y));continue}let j=!1;if(window.MotionHandoffAnimation){const M=JEt(s);if(M){const I=window.MotionHandoffAnimation(M,g,ym);I!==null&&(v.startTime=I,j=!0)}}F7e(s,g);const C=d??s.shouldReduceMotion;x.start(KGe(g,x,y,C&&XEt.has(g)?{type:!1}:v,s,j));const A=x.animation;A&&h.push(A)}if(l){const g=()=>ym.update(()=>{l&&tks(s,l)});h.length?Promise.all(h).then(g):g()}return h}function z7e(s,t,n={}){var c;const r=eO(s,t,n.type==="exit"?(c=s.presenceContext)==null?void 0:c.custom:void 0);let{transition:a=s.getDefaultTransition()||{}}=r||{};n.transitionOverride&&(a=n.transitionOverride);const i=r?()=>Promise.all(eTt(s,r,n)):()=>Promise.resolve(),l=s.variantChildren&&s.variantChildren.size?(d=0)=>{const{delayChildren:u=0,staggerChildren:h,staggerDirection:m}=a;return aks(s,t,d,u,h,m,n)}:()=>Promise.resolve(),{when:o}=a;if(o){const[d,u]=o==="beforeChildren"?[i,l]:[l,i];return d().then(()=>u())}else return Promise.all([i(),l(n.delay)])}function aks(s,t,n=0,r=0,a=0,i=1,l){const o=[];for(const c of s.variantChildren)c.notify("AnimationStart",t),o.push(z7e(c,t,{...l,delay:n+(typeof r=="function"?0:r)+KEt(s.variantChildren,c,r,a,i)}).then(()=>c.notify("AnimationComplete",t)));return Promise.all(o)}function iks(s,t,n={}){s.notify("AnimationStart",t);let r;if(Array.isArray(t)){const a=t.map(i=>z7e(s,i,n));r=Promise.all(a)}else if(typeof t=="string")r=z7e(s,t,n);else{const a=typeof t=="function"?eO(s,t,n.custom):t;r=Promise.all(eTt(s,a,n))}return r.then(()=>{s.notify("AnimationComplete",t)})}const oks={test:s=>s==="auto",parse:s=>s},tTt=s=>t=>t.test(s),sTt=[Gq,No,D5,oC,I2s,P2s,oks],klt=s=>sTt.find(tTt(s));function lks(s){return typeof s=="number"?s===0:s!==null?s==="none"||s==="0"||mEt(s):!0}const cks=new Set(["brightness","contrast","saturate","opacity"]);function dks(s){const[t,n]=s.slice(0,-1).split("(");if(t==="drop-shadow")return s;const[r]=n.match($Ge)||[];if(!r)return s;const a=n.replace(r,"");let i=cks.has(t)?1:0;return r!==n&&(i*=100),t+"("+i+a+")"}const uks=/\b([a-z-]*)\(.*?\)/gu,B7e={...uk,getAnimatableNone:s=>{const t=s.match(uks);return t?t.map(dks).join(" "):s}},$7e={...uk,getAnimatableNone:s=>{const t=uk.parse(s);return uk.createTransformer(s)(t.map(r=>typeof r=="number"?0:typeof r=="object"?{...r,alpha:1}:r))}},Slt={...Gq,transform:Math.round},hks={rotate:oC,pathRotation:oC,rotateX:oC,rotateY:oC,rotateZ:oC,scale:nre,scaleX:nre,scaleY:nre,scaleZ:nre,skew:oC,skewX:oC,skewY:oC,distance:No,translateX:No,translateY:No,translateZ:No,x:No,y:No,z:No,perspective:No,transformPerspective:No,opacity:XZ,originX:hlt,originY:hlt,originZ:No},vSe={borderWidth:No,borderTopWidth:No,borderRightWidth:No,borderBottomWidth:No,borderLeftWidth:No,borderRadius:No,borderTopLeftRadius:No,borderTopRightRadius:No,borderBottomRightRadius:No,borderBottomLeftRadius:No,width:No,maxWidth:No,height:No,maxHeight:No,top:No,right:No,bottom:No,left:No,inset:No,insetBlock:No,insetBlockStart:No,insetBlockEnd:No,insetInline:No,insetInlineStart:No,insetInlineEnd:No,padding:No,paddingTop:No,paddingRight:No,paddingBottom:No,paddingLeft:No,paddingBlock:No,paddingBlockStart:No,paddingBlockEnd:No,paddingInline:No,paddingInlineStart:No,paddingInlineEnd:No,margin:No,marginTop:No,marginRight:No,marginBottom:No,marginLeft:No,marginBlock:No,marginBlockStart:No,marginBlockEnd:No,marginInline:No,marginInlineStart:No,marginInlineEnd:No,fontSize:No,backgroundPositionX:No,backgroundPositionY:No,...hks,zIndex:Slt,fillOpacity:XZ,strokeOpacity:XZ,numOctaves:Slt},mks={...vSe,color:Ex,backgroundColor:Ex,outlineColor:Ex,fill:Ex,stroke:Ex,borderColor:Ex,borderTopColor:Ex,borderRightColor:Ex,borderBottomColor:Ex,borderLeftColor:Ex,filter:B7e,WebkitFilter:B7e,mask:$7e,WebkitMask:$7e},nTt=s=>mks[s],fks=new Set([B7e,$7e]);function rTt(s,t){let n=nTt(s);return fks.has(n)||(n=uk),n.getAnimatableNone?n.getAnimatableNone(t):void 0}const pks=new Set(["auto","none","0"]);function gks(s,t,n){let r=0,a;for(;r{t.getValue(c).set(d)}),this.resolveNoneKeyframes()}}const XGe=["borderTopLeftRadius","borderTopRightRadius","borderBottomRightRadius","borderBottomLeftRadius"];function QGe(s,t,n){if(s==null)return[];if(s instanceof EventTarget)return[s];if(typeof s=="string"){const a=document.querySelectorAll(s);return a?Array.from(a):[]}return Array.from(s).filter(r=>r!=null)}const U7e=(s,t)=>t&&typeof s=="number"?t.transform(s):s;function nNe(s){return hEt(s)&&"offsetHeight"in s&&!("ownerSVGElement"in s)}const{schedule:JGe}=SEt(queueMicrotask,!1),bN={x:!1,y:!1};function aTt(){return bN.x||bN.y}function yks(s){return s==="x"||s==="y"?bN[s]?null:(bN[s]=!0,()=>{bN[s]=!1}):bN.x||bN.y?null:(bN.x=bN.y=!0,()=>{bN.x=bN.y=!1})}function iTt(s,t){const n=QGe(s),r=new AbortController,a={passive:!0,...t,signal:r.signal};return[n,a,()=>r.abort()]}function vks(s){return!(s.pointerType==="touch"||aTt())}function bks(s,t,n={}){const[r,a,i]=iTt(s,n);return r.forEach(l=>{let o=!1,c=!1,d;const u=()=>{l.removeEventListener("pointerleave",g)},h=y=>{d&&(d(y),d=void 0),u()},m=y=>{o=!1,window.removeEventListener("pointerup",m),window.removeEventListener("pointercancel",m),c&&(c=!1,h(y))},p=()=>{o=!0,window.addEventListener("pointerup",m,a),window.addEventListener("pointercancel",m,a)},g=y=>{if(y.pointerType!=="touch"){if(o){c=!0;return}h(y)}},x=y=>{if(!vks(y))return;c=!1;const v=t(l,y);typeof v=="function"&&(d=v,l.addEventListener("pointerleave",g,a))};l.addEventListener("pointerenter",x,a),l.addEventListener("pointerdown",p,a)}),i}const oTt=(s,t)=>t?s===t?!0:oTt(s,t.parentElement):!1,eWe=s=>s.pointerType==="mouse"?typeof s.button!="number"||s.button<=0:s.isPrimary!==!1,_ks=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);function wks(s){return _ks.has(s.tagName)||s.isContentEditable===!0}const jks=new Set(["INPUT","SELECT","TEXTAREA"]);function Nks(s){return jks.has(s.tagName)||s.isContentEditable===!0}const rNe=new WeakSet;function Clt(s){return t=>{t.key==="Enter"&&s(t)}}function RIe(s,t){s.dispatchEvent(new PointerEvent("pointer"+t,{isPrimary:!0,bubbles:!0}))}const kks=(s,t)=>{const n=s.currentTarget;if(!n)return;const r=Clt(()=>{if(rNe.has(n))return;RIe(n,"down");const a=Clt(()=>{RIe(n,"up")}),i=()=>RIe(n,"cancel");n.addEventListener("keyup",a,t),n.addEventListener("blur",i,t)});n.addEventListener("keydown",r,t),n.addEventListener("blur",()=>n.removeEventListener("keydown",r),t)};function Alt(s){return eWe(s)&&!aTt()}const Elt=new WeakSet;function Sks(s,t,n={}){const[r,a,i]=iTt(s,n),l=o=>{const c=o.currentTarget;if(!Alt(o)||Elt.has(o))return;rNe.add(c),n.stopPropagation&&Elt.add(o);const d=t(c,o),u={...a,capture:!0},h=(g,x)=>{window.removeEventListener("pointerup",m,u),window.removeEventListener("pointercancel",p,u),rNe.has(c)&&rNe.delete(c),Alt(g)&&typeof d=="function"&&d(g,{success:x})},m=g=>{h(g,c===window||c===document||n.useGlobalTarget||oTt(c,g.target))},p=g=>{h(g,!1)};window.addEventListener("pointerup",m,u),window.addEventListener("pointercancel",p,u)};return r.forEach(o=>{(n.useGlobalTarget?window:o).addEventListener("pointerdown",l,a),nNe(o)&&(o.addEventListener("focus",d=>kks(d,a)),!wks(o)&&!o.hasAttribute("tabindex")&&(o.tabIndex=0))}),i}function tWe(s){return hEt(s)&&"ownerSVGElement"in s}const aNe=new WeakMap;let sE;const lTt=(s,t,n)=>(r,a)=>a&&a[0]?a[0][s+"Size"]:tWe(r)&&"getBBox"in r?r.getBBox()[t]:r[n],Cks=lTt("inline","width","offsetWidth"),Aks=lTt("block","height","offsetHeight");function Eks({target:s,borderBoxSize:t}){var n;(n=aNe.get(s))==null||n.forEach(r=>{r(s,{get width(){return Cks(s,t)},get height(){return Aks(s,t)}})})}function Tks(s){s.forEach(Eks)}function Mks(){typeof ResizeObserver>"u"||(sE=new ResizeObserver(Tks))}function Pks(s,t){sE||Mks();const n=QGe(s);return n.forEach(r=>{let a=aNe.get(r);a||(a=new Set,aNe.set(r,a)),a.add(t),sE==null||sE.observe(r)}),()=>{n.forEach(r=>{const a=aNe.get(r);a==null||a.delete(t),a!=null&&a.size||sE==null||sE.unobserve(r)})}}const iNe=new Set;let mz;function Iks(){mz=()=>{const s={get width(){return window.innerWidth},get height(){return window.innerHeight}};iNe.forEach(t=>t(s))},window.addEventListener("resize",mz)}function Lks(s){return iNe.add(s),mz||Iks(),()=>{iNe.delete(s),!iNe.size&&typeof mz=="function"&&(window.removeEventListener("resize",mz),mz=void 0)}}function Tlt(s,t){return typeof s=="function"?Lks(s):Pks(s,t)}function Rks(s){return tWe(s)&&s.tagName==="svg"}const Dks=[...sTt,Ex,uk],Oks=s=>Dks.find(tTt(s)),Mlt=()=>({translate:0,scale:1,origin:0,originPoint:0}),fz=()=>({x:Mlt(),y:Mlt()}),Plt=()=>({min:0,max:0}),uy=()=>({x:Plt(),y:Plt()}),Fks=new WeakMap;function dAe(s){return s!==null&&typeof s=="object"&&typeof s.start=="function"}function QZ(s){return typeof s=="string"||Array.isArray(s)}const sWe=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],nWe=["initial",...sWe];function uAe(s){return dAe(s.animate)||nWe.some(t=>QZ(s[t]))}function cTt(s){return!!(uAe(s)||s.variants)}function zks(s,t,n){for(const r in t){const a=t[r],i=n[r];if(av(a))s.addValue(r,a);else if(av(i))s.addValue(r,NU(a,{owner:s}));else if(i!==a)if(s.hasValue(r)){const l=s.getValue(r);l.liveStyle===!0?l.jump(a):l.hasAnimated||l.set(a)}else{const l=s.getStaticValue(r);s.addValue(r,NU(l!==void 0?l:a,{owner:s}))}}for(const r in n)t[r]===void 0&&s.removeValue(r);return t}const q7e={current:null},dTt={current:!1},Bks=typeof window<"u";function $ks(){if(dTt.current=!0,!!Bks)if(window.matchMedia){const s=window.matchMedia("(prefers-reduced-motion)"),t=()=>q7e.current=s.matches;s.addEventListener("change",t),t()}else q7e.current=!1}const Ilt=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];let bSe={};function uTt(s){bSe=s}function Uks(){return bSe}class qks{scrapeMotionValuesFromProps(t,n,r){return{}}constructor({parent:t,props:n,presenceContext:r,reducedMotionConfig:a,skipAnimations:i,blockInitialAnimation:l,visualState:o},c={}){this.current=null,this.children=new Set,this.isVariantNode=!1,this.isControllingVariants=!1,this.shouldReduceMotion=null,this.shouldSkipAnimations=!1,this.values=new Map,this.KeyframeResolver=GGe,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 p=ob.now();this.renderScheduledAtthis.bindToMotionValue(i,a)),this.reducedMotionConfig==="never"?this.shouldReduceMotion=!1:this.reducedMotionConfig==="always"?this.shouldReduceMotion=!0:(dTt.current||$ks(),this.shouldReduceMotion=q7e.current),this.shouldSkipAnimations=this.skipAnimationsConfig??!1,(r=this.parent)==null||r.addChild(this),this.update(this.props,this.presenceContext),this.hasBeenMounted=!0}unmount(){var t;this.projection&&this.projection.unmount(),AM(this.notifyUpdate),AM(this.render),this.valueSubscriptions.forEach(n=>n()),this.valueSubscriptions.clear(),this.removeFromVariantTree&&this.removeFromVariantTree(),(t=this.parent)==null||t.removeChild(this);for(const n in this.events)this.events[n].clear();for(const n in this.features){const r=this.features[n];r&&(r.unmount(),r.isMounted=!1)}this.current=null}addChild(t){this.children.add(t),this.enteringChildren??(this.enteringChildren=new Set),this.enteringChildren.add(t)}removeChild(t){this.children.delete(t),this.enteringChildren&&this.enteringChildren.delete(t)}bindToMotionValue(t,n){if(this.valueSubscriptions.has(t)&&this.valueSubscriptions.get(t)(),n.accelerate&&WEt.has(t)&&this.current instanceof HTMLElement){const{factory:l,keyframes:o,times:c,ease:d,duration:u}=n.accelerate,h=new HEt({element:this.current,name:t,keyframes:o,times:c,ease:d,duration:Qw(u)}),m=l(h);this.valueSubscriptions.set(t,()=>{m(),h.cancel()});return}const r=Kq.has(t);r&&this.onBindTransform&&this.onBindTransform();const a=n.on("change",l=>{this.latestValues[t]=l,this.props.onUpdate&&ym.preRender(this.notifyUpdate),r&&this.projection&&(this.projection.isTransformDirty=!0),this.scheduleRender()});let i;typeof window<"u"&&window.MotionCheckAppearSync&&(i=window.MotionCheckAppearSync(this,t,n)),this.valueSubscriptions.set(t,()=>{a(),i&&i()})}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 bSe){const n=bSe[t];if(!n)continue;const{isEnabled:r,Feature:a}=n;if(!this.features[t]&&a&&r(this.props)&&(this.features[t]=new a(this)),this.features[t]){const i=this.features[t];i.isMounted?i.update():(i.mount(),i.isMounted=!0)}}}triggerBuild(){this.build(this.renderState,this.latestValues,this.props)}measureViewportBox(){return this.current?this.measureInstanceViewportBox(this.current,this.props):uy()}getStaticValue(t){return this.latestValues[t]}setStaticValue(t,n){this.latestValues[t]=n}update(t,n){(t.transformTemplate||this.props.transformTemplate)&&this.scheduleRender(),this.prevProps=this.props,this.props=t,this.prevPresenceContext=this.presenceContext,this.presenceContext=n;for(let r=0;rn.variantChildren.delete(t)}addValue(t,n){const r=this.values.get(t);n!==r&&(r&&this.removeValue(t),this.bindToMotionValue(t,n),this.values.set(t,n),this.latestValues[t]=n.get())}removeValue(t){this.values.delete(t);const n=this.valueSubscriptions.get(t);n&&(n(),this.valueSubscriptions.delete(t)),delete this.latestValues[t],this.removeValueFromRenderState(t,this.renderState)}hasValue(t){return this.values.has(t)}getValue(t,n){if(this.props.values&&this.props.values[t])return this.props.values[t];let r=this.values.get(t);return r===void 0&&n!==void 0&&(r=NU(n===null?void 0:n,{owner:this}),this.addValue(t,r)),r}readValue(t,n){let r=this.latestValues[t]!==void 0||!this.current?this.latestValues[t]:this.getBaseTargetFromProps(this.props,t)??this.readValueFromInstance(this.current,t,this.options);return r!=null&&(typeof r=="string"&&(uEt(r)||mEt(r))?r=parseFloat(r):!Oks(r)&&uk.test(n)&&(r=rTt(t,n)),this.setBaseTarget(t,av(r)?r.get():r)),av(r)?r.get():r}setBaseTarget(t,n){this.baseTarget[t]=n}getBaseTarget(t){var i;const{initial:n}=this.props;let r;if(typeof n=="string"||typeof n=="object"){const l=YGe(this.props,n,(i=this.presenceContext)==null?void 0:i.custom);l&&(r=l[t])}if(n&&r!==void 0)return r;const a=this.getBaseTargetFromProps(this.props,t);return a!==void 0&&!av(a)?a:this.initialValues[t]!==void 0&&r===void 0?void 0:this.baseTarget[t]}on(t,n){return this.events[t]||(this.events[t]=new OGe),this.events[t].add(n)}notify(t,...n){this.events[t]&&this.events[t].notify(...n)}scheduleRenderMicrotask(){JGe.render(this.render)}}class hTt extends qks{constructor(){super(...arguments),this.KeyframeResolver=xks}sortInstanceNodePosition(t,n){return t.compareDocumentPosition(n)&2?1:-1}getBaseTargetFromProps(t,n){const r=t.style;return r?r[n]:void 0}removeValueFromRenderState(t,{vars:n,style:r}){delete n[t],delete r[t]}handleChildMotionValue(){this.childSubscription&&(this.childSubscription(),delete this.childSubscription);const{children:t}=this.props;av(t)&&(this.childSubscription=t.on("change",n=>{this.current&&(this.current.textContent=`${n}`)}))}}class e6{constructor(t){this.isMounted=!1,this.node=t}update(){}}function mTt({top:s,left:t,right:n,bottom:r}){return{x:{min:t,max:n},y:{min:s,max:r}}}function Vks({x:s,y:t}){return{top:t.min,right:s.max,bottom:t.max,left:s.min}}function Hks(s,t){if(!t)return s;const n=t({x:s.left,y:s.top}),r=t({x:s.right,y:s.bottom});return{top:n.y,left:n.x,bottom:r.y,right:r.x}}function DIe(s){return s===void 0||s===1}function V7e({scale:s,scaleX:t,scaleY:n}){return!DIe(s)||!DIe(t)||!DIe(n)}function MR(s){return V7e(s)||fTt(s)||s.z||s.rotate||s.rotateX||s.rotateY||s.skewX||s.skewY}function fTt(s){return Llt(s.x)||Llt(s.y)}function Llt(s){return s&&s!=="0%"}function _Se(s,t,n){const r=s-n,a=t*r;return n+a}function Rlt(s,t,n,r,a){return a!==void 0&&(s=_Se(s,a,r)),_Se(s,n,r)+t}function H7e(s,t=0,n=1,r,a){s.min=Rlt(s.min,t,n,r,a),s.max=Rlt(s.max,t,n,r,a)}function pTt(s,{x:t,y:n}){H7e(s.x,t.translate,t.scale,t.originPoint),H7e(s.y,n.translate,n.scale,n.originPoint)}const Dlt=.999999999999,Olt=1.0000000000001;function Gks(s,t,n,r=!1){var o;const a=n.length;if(!a)return;t.x=t.y=1;let i,l;for(let c=0;cDlt&&(t.x=1),t.yDlt&&(t.y=1)}function a5(s,t){s.min+=t,s.max+=t}function Flt(s,t,n,r,a=.5){const i=pm(s.min,s.max,a);H7e(s,t,n,i,r)}function zlt(s,t){return typeof s=="string"?parseFloat(s)/100*(t.max-t.min):s}function oNe(s,t,n){const r=n??s;Flt(s.x,zlt(t.x,r.x),t.scaleX,t.scale,t.originX),Flt(s.y,zlt(t.y,r.y),t.scaleY,t.scale,t.originY)}function gTt(s,t){return mTt(Hks(s.getBoundingClientRect(),t))}function Wks(s,t,n){const r=gTt(s,n),{scroll:a}=t;return a&&(a5(r.x,a.offset.x),a5(r.y,a.offset.y)),r}const Kks={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},Yks=Wq.length;function Zks(s,t,n){let r="",a=!0;for(let l=0;l{if(!t.target)return s;if(typeof s=="string")if(No.test(s))s=parseFloat(s);else return s;const n=Blt(s,t.target.x),r=Blt(s,t.target.y);return`${n}% ${r}%`}},Xks={correct:(s,{treeScale:t,projectionDelta:n})=>{const r=s,a=uk.parse(s);if(a.length>5)return r;const i=uk.createTransformer(s),l=typeof a[0]!="number"?1:0,o=n.x.scale*t.x,c=n.y.scale*t.y;a[0+l]/=o,a[1+l]/=c;const d=pm(o,c,.5);return typeof a[2+l]=="number"&&(a[2+l]/=d),typeof a[3+l]=="number"&&(a[3+l]/=d),i(a)}},G7e={borderRadius:{...cG,applyTo:[...XGe]},borderTopLeftRadius:cG,borderTopRightRadius:cG,borderBottomLeftRadius:cG,borderBottomRightRadius:cG,boxShadow:Xks};function yTt(s,{layout:t,layoutId:n}){return Kq.has(s)||s.startsWith("origin")||(t||n!==void 0)&&(!!G7e[s]||s==="opacity")}function aWe(s,t,n){var l;const r=s.style,a=t==null?void 0:t.style,i={};if(!r)return i;for(const o in r)(av(r[o])||a&&av(a[o])||yTt(o,s)||((l=n==null?void 0:n.getValue(o))==null?void 0:l.liveStyle)!==void 0)&&(i[o]=r[o]);return i}function Qks(s){return window.getComputedStyle(s)}class Jks extends hTt{constructor(){super(...arguments),this.type="html",this.renderInstance=xTt}mount(t){lAe(!!t.style),super.mount(t)}readValueFromInstance(t,n){var r;if(Kq.has(n))return(r=this.projection)!=null&&r.isProjecting?M7e(n):vNs(t,n);{const a=Qks(t),i=(AEt(n)?a.getPropertyValue(n):a[n])||0;return typeof i=="string"?i.trim():i}}measureInstanceViewportBox(t,{transformPagePoint:n}){return gTt(t,n)}build(t,n,r){rWe(t,n,r.transformTemplate)}scrapeMotionValuesFromProps(t,n,r){return aWe(t,n,r)}}const eSs={offset:"stroke-dashoffset",array:"stroke-dasharray"},tSs={offset:"strokeDashoffset",array:"strokeDasharray"};function sSs(s,t,n=1,r=0,a=!0){s.pathLength=1;const i=a?eSs:tSs;s[i.offset]=`${-r}`,s[i.array]=`${t} ${n}`}const nSs=["offsetDistance","offsetPath","offsetRotate","offsetAnchor"];function vTt(s,{attrX:t,attrY:n,attrScale:r,pathLength:a,pathSpacing:i=1,pathOffset:l=0,...o},c,d,u){if(rWe(s,o,d),c){s.style.viewBox&&(s.attrs.viewBox=s.style.viewBox);return}s.attrs=s.style,s.style={};const{attrs:h,style:m}=s;h.transform&&(m.transform=h.transform,delete h.transform),(m.transform||h.transformOrigin)&&(m.transformOrigin=h.transformOrigin??"50% 50%",delete h.transformOrigin),m.transform&&(m.transformBox=(u==null?void 0:u.transformBox)??"fill-box",delete h.transformBox);for(const p of nSs)h[p]!==void 0&&(m[p]=h[p],delete h[p]);t!==void 0&&(h.x=t),n!==void 0&&(h.y=n),r!==void 0&&(h.scale=r),a!==void 0&&sSs(h,a,i,l,!1)}const bTt=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"]),_Tt=s=>typeof s=="string"&&s.toLowerCase()==="svg";function rSs(s,t,n,r){xTt(s,t,void 0,r);for(const a in t.attrs)s.setAttribute(bTt.has(a)?a:ZGe(a),t.attrs[a])}function wTt(s,t,n){const r=aWe(s,t,n);for(const a in s)if(av(s[a])||av(t[a])){const i=Wq.indexOf(a)!==-1?"attr"+a.charAt(0).toUpperCase()+a.substring(1):a;r[i]=s[a]}return r}class aSs extends hTt{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=uy}getBaseTargetFromProps(t,n){return t[n]}readValueFromInstance(t,n){if(Kq.has(n)){const r=nTt(n);return r&&r.default||0}return n=bTt.has(n)?n:ZGe(n),t.getAttribute(n)}scrapeMotionValuesFromProps(t,n,r){return wTt(t,n,r)}build(t,n,r){vTt(t,n,this.isSVGTag,r.transformTemplate,r.style)}renderInstance(t,n,r,a){rSs(t,n,r,a)}mount(t){this.isSVGTag=_Tt(t.tagName),super.mount(t)}}const iSs=nWe.length;function jTt(s){if(!s)return;if(!s.isControllingVariants){const n=s.parent?jTt(s.parent)||{}:{};return s.props.initial!==void 0&&(n.initial=s.props.initial),n}const t={};for(let n=0;nPromise.all(t.map(({animation:n,options:r})=>iks(s,n,r)))}function dSs(s){let t=cSs(s),n=$lt(),r=!0,a=!1;const i=d=>(u,h)=>{var p;const m=eO(s,h,d==="exit"?(p=s.presenceContext)==null?void 0:p.custom:void 0);if(m){const{transition:g,transitionEnd:x,...y}=m;u={...u,...y,...x}}return u};function l(d){t=d(s)}function o(d){const{props:u}=s,h=jTt(s.parent)||{},m=[],p=new Set;let g={},x=1/0;for(let v=0;vx&&A,O=!1;const B=Array.isArray(C)?C:[C];let U=B.reduce(i(_),{});M===!1&&(U={});const{prevResolvedValues:G={}}=j,H={...G,...U},Y=oe=>{R=!0,p.has(oe)&&(O=!0,p.delete(oe)),j.needsAnimating[oe]=!0;const me=s.getValue(oe);me&&(me.liveStyle=!1)};for(const oe in H){const me=U[oe],Q=G[oe];if(g.hasOwnProperty(oe))continue;let te=!1;O7e(me)&&O7e(Q)?te=!NTt(me,Q)||P:te=me!==Q,te?me!=null?Y(oe):p.add(oe):me!==void 0&&p.has(oe)?Y(oe):j.protectedKeys[oe]=!0}j.prevProp=C,j.prevResolvedValues=U,j.isActive&&(g={...g,...U}),(r||a)&&s.blockInitialAnimation&&(R=!1);const se=I&&P;R&&(!se||O)&&m.push(...B.map(oe=>{const me={type:_};if(typeof oe=="string"&&(r||a)&&!se&&s.manuallyAnimateOnMount&&s.parent){const{parent:Q}=s,te=eO(Q,oe);if(Q.enteringChildren&&te){const{delayChildren:le}=te.transition||{};me.delay=KEt(Q.enteringChildren,s,le)}}return{animation:oe,options:me}}))}if(p.size){const v={};if(typeof u.initial!="boolean"){const _=eO(s,Array.isArray(u.initial)?u.initial[0]:u.initial);_&&_.transition&&(v.transition=_.transition)}p.forEach(_=>{const j=s.getBaseTarget(_),C=s.getValue(_);C&&(C.liveStyle=!0),v[_]=j??null}),m.push({animation:v})}let y=!!m.length;return r&&(u.initial===!1||u.initial===u.animate)&&!s.manuallyAnimateOnMount&&(y=!1),r=!1,a=!1,y?t(m):Promise.resolve()}function c(d,u){var m;if(n[d].isActive===u)return Promise.resolve();(m=s.variantChildren)==null||m.forEach(p=>{var g;return(g=p.animationState)==null?void 0:g.setActive(d,u)}),n[d].isActive=u;const h=o(d);for(const p in n)n[p].protectedKeys={};return h}return{animateChanges:o,setActive:c,setAnimateFunction:l,getState:()=>n,reset:()=>{n=$lt(),a=!0}}}function uSs(s,t){return typeof t=="string"?t!==s:Array.isArray(t)?!NTt(t,s):!1}function aP(s=!1){return{isActive:s,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function $lt(){return{animate:aP(!0),whileInView:aP(),whileHover:aP(),whileTap:aP(),whileDrag:aP(),whileFocus:aP(),exit:aP()}}function W7e(s,t){s.min=t.min,s.max=t.max}function uN(s,t){W7e(s.x,t.x),W7e(s.y,t.y)}function Ult(s,t){s.translate=t.translate,s.scale=t.scale,s.originPoint=t.originPoint,s.origin=t.origin}const kTt=1e-4,hSs=1-kTt,mSs=1+kTt,STt=.01,fSs=0-STt,pSs=0+STt;function lb(s){return s.max-s.min}function gSs(s,t,n){return Math.abs(s-t)<=n}function qlt(s,t,n,r=.5){s.origin=r,s.originPoint=pm(t.min,t.max,s.origin),s.scale=lb(n)/lb(t),s.translate=pm(n.min,n.max,s.origin)-s.originPoint,(s.scale>=hSs&&s.scale<=mSs||isNaN(s.scale))&&(s.scale=1),(s.translate>=fSs&&s.translate<=pSs||isNaN(s.translate))&&(s.translate=0)}function wY(s,t,n,r){qlt(s.x,t.x,n.x,r?r.originX:void 0),qlt(s.y,t.y,n.y,r?r.originY:void 0)}function Vlt(s,t,n,r=0){const a=r?pm(n.min,n.max,r):n.min;s.min=a+t.min,s.max=s.min+lb(t)}function xSs(s,t,n,r){Vlt(s.x,t.x,n.x,r==null?void 0:r.x),Vlt(s.y,t.y,n.y,r==null?void 0:r.y)}function Hlt(s,t,n,r=0){const a=r?pm(n.min,n.max,r):n.min;s.min=t.min-a,s.max=s.min+lb(t)}function wSe(s,t,n,r){Hlt(s.x,t.x,n.x,r==null?void 0:r.x),Hlt(s.y,t.y,n.y,r==null?void 0:r.y)}function Glt(s,t,n,r,a){return s-=t,s=_Se(s,1/n,r),a!==void 0&&(s=_Se(s,1/a,r)),s}function ySs(s,t=0,n=1,r=.5,a,i=s,l=s){if(D5.test(t)&&(t=parseFloat(t),t=pm(l.min,l.max,t/100)-l.min),typeof t!="number")return;let o=pm(i.min,i.max,r);s===i&&(o-=t),s.min=Glt(s.min,t,n,o,a),s.max=Glt(s.max,t,n,o,a)}function Wlt(s,t,[n,r,a],i,l){ySs(s,t[n],t[r],t[a],t.scale,i,l)}const vSs=["x","scaleX","originX"],bSs=["y","scaleY","originY"];function Klt(s,t,n,r){Wlt(s.x,t,vSs,n?n.x:void 0,r?r.x:void 0),Wlt(s.y,t,bSs,n?n.y:void 0,r?r.y:void 0)}function Ylt(s){return s.translate===0&&s.scale===1}function CTt(s){return Ylt(s.x)&&Ylt(s.y)}function Zlt(s,t){return s.min===t.min&&s.max===t.max}function _Ss(s,t){return Zlt(s.x,t.x)&&Zlt(s.y,t.y)}function Xlt(s,t){return Math.round(s.min)===Math.round(t.min)&&Math.round(s.max)===Math.round(t.max)}function ATt(s,t){return Xlt(s.x,t.x)&&Xlt(s.y,t.y)}function Qlt(s){return lb(s.x)/lb(s.y)}function Jlt(s,t){return s.translate===t.translate&&s.scale===t.scale&&s.originPoint===t.originPoint}function kS(s){return[s("x"),s("y")]}function wSs(s,t,n){let r="";const a=s.x.translate/t.x,i=s.y.translate/t.y,l=(n==null?void 0:n.z)||0;if((a||i||l)&&(r=`translate3d(${a}px, ${i}px, ${l}px) `),(t.x!==1||t.y!==1)&&(r+=`scale(${1/t.x}, ${1/t.y}) `),n){const{transformPerspective:d,rotate:u,pathRotation:h,rotateX:m,rotateY:p,skewX:g,skewY:x}=n;d&&(r=`perspective(${d}px) ${r}`),u&&(r+=`rotate(${u}deg) `),h&&(r+=`rotate(${h}deg) `),m&&(r+=`rotateX(${m}deg) `),p&&(r+=`rotateY(${p}deg) `),g&&(r+=`skewX(${g}deg) `),x&&(r+=`skewY(${x}deg) `)}const o=s.x.scale*t.x,c=s.y.scale*t.y;return(o!==1||c!==1)&&(r+=`scale(${o}, ${c})`),r||"none"}const jSs=XGe.length,ect=s=>typeof s=="string"?parseFloat(s):s,tct=s=>typeof s=="number"||No.test(s);function NSs(s,t,n,r,a,i){a?(s.opacity=pm(0,n.opacity??1,kSs(r)),s.opacityExit=pm(t.opacity??1,0,SSs(r))):i&&(s.opacity=pm(t.opacity??1,n.opacity??1,r));for(let l=0;lrt?1:n(ZZ(s,t,r))}function CSs(s,t,n){const r=av(s)?s:NU(s);return r.start(KGe("",r,t,n)),r.animation}function JZ(s,t,n,r={passive:!0}){return s.addEventListener(t,n,r),()=>s.removeEventListener(t,n,r)}const ASs=(s,t)=>s.depth-t.depth;class ESs{constructor(){this.children=[],this.isDirty=!1}add(t){DGe(this.children,t),this.isDirty=!0}remove(t){fSe(this.children,t),this.isDirty=!0}forEach(t){this.isDirty&&this.children.sort(ASs),this.isDirty=!1,this.children.forEach(t)}}function TSs(s,t){const n=ob.now(),r=({timestamp:a})=>{const i=a-n;i>=t&&(AM(r),s(i-t))};return ym.setup(r,!0),()=>AM(r)}function lNe(s){return av(s)?s.get():s}class MSs{constructor(){this.members=[]}add(t){DGe(this.members,t);for(let n=this.members.length-1;n>=0;n--){const r=this.members[n];if(r===t||r===this.lead||r===this.prevLead)continue;const a=r.instance;(!a||a.isConnected===!1)&&!r.snapshot&&(fSe(this.members,r),r.unmount())}t.scheduleRender()}remove(t){if(fSe(this.members,t),t===this.prevLead&&(this.prevLead=void 0),t===this.lead){const n=this.members[this.members.length-1];n&&this.promote(n)}}relegate(t){var n;for(let r=this.members.indexOf(t)-1;r>=0;r--){const a=this.members[r];if(a.isPresent!==!1&&((n=a.instance)==null?void 0:n.isConnected)!==!1)return this.promote(a),!0}return!1}promote(t,n){var a;const r=this.lead;if(t!==r&&(this.prevLead=r,this.lead=t,t.show(),r)){r.updateSnapshot(),t.scheduleRender();const{layoutDependency:i}=r.options,{layoutDependency:l}=t.options;(i===void 0||i!==l)&&(t.resumeFrom=r,n&&(r.preserveOpacity=!0),r.snapshot&&(t.snapshot=r.snapshot,t.snapshot.latestValues=r.animationValues||r.latestValues),(a=t.root)!=null&&a.isUpdating&&(t.isLayoutDirty=!0)),t.options.crossfade===!1&&r.hide()}}exitAnimationComplete(){this.members.forEach(t=>{var n,r,a,i,l;(r=(n=t.options).onExitComplete)==null||r.call(n),(l=(a=t.resumingFrom)==null?void 0:(i=a.options).onExitComplete)==null||l.call(i)})}scheduleRender(){this.members.forEach(t=>t.instance&&t.scheduleRender(!1))}removeLeadSnapshot(){var t;(t=this.lead)!=null&&t.snapshot&&(this.lead.snapshot=void 0)}}const cNe={hasAnimatedSinceResize:!0,hasEverUpdated:!1},OIe=["","X","Y","Z"],PSs=1e3;let ISs=0;function FIe(s,t,n,r){const{latestValues:a}=t;a[s]&&(n[s]=a[s],t.setStaticValue(s,0),r&&(r[s]=0))}function TTt(s){if(s.hasCheckedOptimisedAppear=!0,s.root===s)return;const{visualElement:t}=s.options;if(!t)return;const n=JEt(t);if(window.MotionHasOptimisedAnimation(n,"transform")){const{layout:a,layoutId:i}=s.options;window.MotionCancelOptimisedAnimation(n,"transform",ym,!(a||i))}const{parent:r}=s;r&&!r.hasCheckedOptimisedAppear&&TTt(r)}function MTt({attachResizeListener:s,defaultParent:t,measureScroll:n,checkIsScrollRoot:r,resetTransform:a}){return class{constructor(l={},o=t==null?void 0:t()){this.id=ISs++,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(DSs),this.nodes.forEach(USs),this.nodes.forEach(qSs),this.nodes.forEach(OSs)},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;ym.read(()=>{h=window.innerWidth}),s(l,()=>{const p=window.innerWidth;p!==h&&(h=p,this.root.updateBlockedByResize=!0,u&&u(),u=TSs(m,250),cNe.hasAnimatedSinceResize&&(cNe.hasAnimatedSinceResize=!1,this.nodes.forEach(act)))})}o&&this.root.registerSharedNode(o,this),this.options.animate!==!1&&d&&(o||c)&&this.addEventListener("didUpdate",({delta:u,hasLayoutChanged:h,hasRelativeLayoutChanged:m,layout:p})=>{if(this.isTreeAnimationBlocked()){this.target=void 0,this.relativeTarget=void 0;return}const g=this.options.transition||d.getDefaultTransition()||KSs,{onLayoutAnimationStart:x,onLayoutAnimationComplete:y}=d.getProps(),v=!this.targetLayout||!ATt(this.targetLayout,p),_=!h&&m;if(this.options.layoutRoot||this.resumeFrom||_||h&&(v||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);const j={...WGe(g,"layout"),onPlay:x,onComplete:y};(d.shouldReduceMotion||this.options.layoutRoot)&&(j.delay=0,j.type=!1),this.startAnimation(j),this.setAnimationOrigin(u,_,j.path)}else h||act(this),this.isLead()&&this.options.onExitComplete&&this.options.onExitComplete();this.targetLayout=p})}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(),AM(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(VSs),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&&TTt(this),!this.root.isUpdating&&this.root.startUpdate(),this.isLayoutDirty)return;this.isLayoutDirty=!0;for(let u=0;u{this.isLayoutDirty?this.root.didUpdate():this.root.checkUpdateFailed()})}updateSnapshot(){this.snapshot||!this.instance||(this.snapshot=this.measure(),this.snapshot&&!lb(this.snapshot.measuredBox.x)&&!lb(this.snapshot.measuredBox.y)&&(this.snapshot=void 0))}updateLayout(){if(!this.instance||(this.updateScroll(),!(this.options.alwaysMeasureLayout&&this.isLead())&&!this.isLayoutDirty))return;if(this.resumeFrom&&!this.resumeFrom.instance)for(let c=0;c{const I=M/1e3,P=A==null?void 0:A(I);P?(m.x.translate=P.x,m.x.scale=pm(l.x.scale,1,I),m.x.origin=l.x.origin,m.x.originPoint=l.x.originPoint,m.y.translate=P.y,m.y.scale=pm(l.y.scale,1,I),m.y.origin=l.y.origin,m.y.originPoint=l.y.originPoint):(ict(m.x,l.x,I),ict(m.y,l.y,I)),this.setTargetDelta(m),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(wSe(p,this.layout.layoutBox,this.relativeParent.layout.layoutBox,this.options.layoutAnchor||void 0),GSs(this.relativeTarget,this.relativeTargetOrigin,p,I),C&&_Ss(this.relativeTarget,C)&&(this.isProjectionDirty=!1),C||(C=uy()),uN(C,this.relativeTarget)),y&&(this.animationValues=h,NSs(h,u,this.latestValues,I,j,_)),P&&P.rotate!==void 0&&(this.animationValues||(this.animationValues=h),this.animationValues.pathRotation=P.rotate),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=I},this.mixTargetDelta(this.options.layoutRoot?1e3:0)}startAnimation(l){var o,c,d;this.notifyListeners("animationStart"),(o=this.currentAnimation)==null||o.stop(),(d=(c=this.resumingFrom)==null?void 0:c.currentAnimation)==null||d.stop(),this.pendingAnimation&&(AM(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=ym.update(()=>{cNe.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=NU(0)),this.motionValue.jump(0,!1),this.currentAnimation=CSs(this.motionValue,[0,1e3],{...l,velocity:0,isSync:!0,onUpdate:u=>{this.mixTargetDelta(u),l.onUpdate&&l.onUpdate(u)},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(PSs),this.currentAnimation.stop()),this.completeAnimation()}applyTransformsToTarget(){const l=this.getLead();let{targetWithTransforms:o,target:c,layout:d,latestValues:u}=l;if(!(!o||!c||!d)){if(this!==l&&this.layout&&d&&PTt(this.options.animationType,this.layout.layoutBox,d.layoutBox)){c=this.target||uy();const h=lb(this.layout.layoutBox.x);c.x.min=l.target.x.min,c.x.max=c.x.min+h;const m=lb(this.layout.layoutBox.y);c.y.min=l.target.y.min,c.y.max=c.y.min+m}uN(o,c),oNe(o,u),wY(this.projectionDeltaWithTransform,this.layoutCorrected,o,u)}}registerSharedNode(l,o){this.sharedNodes.has(l)||this.sharedNodes.set(l,new MSs),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&&FIe("z",l,d,this.animationValues);for(let u=0;u{var o;return(o=l.currentAnimation)==null?void 0:o.stop()}),this.root.nodes.forEach(nct),this.root.sharedNodes.clear()}}}function LSs(s){s.updateLayout()}function RSs(s){var n;const t=((n=s.resumeFrom)==null?void 0:n.snapshot)||s.snapshot;if(s.isLead()&&s.layout&&t&&s.hasListeners("didUpdate")){const{layoutBox:r,measuredBox:a}=s.layout,{animationType:i}=s.options,l=t.source!==s.layout.source;if(i==="size")kS(h=>{const m=l?t.measuredBox[h]:t.layoutBox[h],p=lb(m);m.min=r[h].min,m.max=m.min+p});else if(i==="x"||i==="y"){const h=i==="x"?"y":"x";W7e(l?t.measuredBox[h]:t.layoutBox[h],r[h])}else PTt(i,t.layoutBox,r)&&kS(h=>{const m=l?t.measuredBox[h]:t.layoutBox[h],p=lb(r[h]);m.max=m.min+p,s.relativeTarget&&!s.currentAnimation&&(s.isProjectionDirty=!0,s.relativeTarget[h].max=s.relativeTarget[h].min+p)});const o=fz();wY(o,r,t.layoutBox);const c=fz();l?wY(c,s.applyTransform(a,!0),t.measuredBox):wY(c,r,t.layoutBox);const d=!CTt(o);let u=!1;if(!s.resumeFrom){const h=s.getClosestProjectingParent();if(h&&!h.resumeFrom){const{snapshot:m,layout:p}=h;if(m&&p){const g=s.options.layoutAnchor||void 0,x=uy();wSe(x,t.layoutBox,m.layoutBox,g);const y=uy();wSe(y,r,p.layoutBox,g),ATt(x,y)||(u=!0),h.options.layoutRoot&&(s.relativeTarget=y,s.relativeTargetOrigin=x,s.relativeParent=h)}}}s.notifyListeners("didUpdate",{layout:r,snapshot:t,delta:c,layoutDelta:o,hasLayoutChanged:d,hasRelativeLayoutChanged:u})}else if(s.isLead()){const{onExitComplete:r}=s.options;r&&r()}s.options.transition=void 0}function DSs(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 OSs(s){s.isProjectionDirty=s.isSharedProjectionDirty=s.isTransformDirty=!1}function FSs(s){s.clearSnapshot()}function nct(s){s.clearMeasurements()}function zSs(s){s.isLayoutDirty=!0,s.updateLayout()}function rct(s){s.isLayoutDirty=!1}function BSs(s){s.isAnimationBlocked&&s.layout&&!s.isLayoutDirty&&(s.snapshot=s.layout,s.isLayoutDirty=!0)}function $Ss(s){const{visualElement:t}=s.options;t&&t.getProps().onBeforeLayoutMeasure&&t.notify("BeforeLayoutMeasure"),s.resetTransform()}function act(s){s.finishAnimation(),s.targetDelta=s.relativeTarget=s.target=void 0,s.isProjectionDirty=!0}function USs(s){s.resolveTargetDelta()}function qSs(s){s.calcProjection()}function VSs(s){s.resetSkewAndRotation()}function HSs(s){s.removeLeadSnapshot()}function ict(s,t,n){s.translate=pm(t.translate,0,n),s.scale=pm(t.scale,1,n),s.origin=t.origin,s.originPoint=t.originPoint}function oct(s,t,n,r){s.min=pm(t.min,n.min,r),s.max=pm(t.max,n.max,r)}function GSs(s,t,n,r){oct(s.x,t.x,n.x,r),oct(s.y,t.y,n.y,r)}function WSs(s){return s.animationValues&&s.animationValues.opacityExit!==void 0}const KSs={duration:.45,ease:[.4,0,.1,1]},lct=s=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(s),cct=lct("applewebkit/")&&!lct("chrome/")?Math.round:C2;function dct(s){s.min=cct(s.min),s.max=cct(s.max)}function YSs(s){dct(s.x),dct(s.y)}function PTt(s,t,n){return s==="position"||s==="preserve-aspect"&&!gSs(Qlt(t),Qlt(n),.2)}function ZSs(s){var t;return s!==s.root&&((t=s.scroll)==null?void 0:t.wasRoot)}const XSs=MTt({attachResizeListener:(s,t)=>JZ(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}),zIe={current:void 0},ITt=MTt({measureScroll:s=>({x:s.scrollLeft,y:s.scrollTop}),defaultParent:()=>{if(!zIe.current){const s=new XSs({});s.mount(window),s.setOptions({layoutScroll:!0}),zIe.current=s}return zIe.current},resetTransform:(s,t)=>{s.style.transform=t!==void 0?t:"none"},checkIsScrollRoot:s=>window.getComputedStyle(s).position==="fixed"}),iWe=k.createContext({transformPagePoint:s=>s,isStatic:!1,reducedMotion:"never"});function uct(s,t){if(typeof s=="function")return s(t);s!=null&&(s.current=t)}function QSs(...s){return t=>{let n=!1;const r=s.map(a=>{const i=uct(a,t);return!n&&typeof i=="function"&&(n=!0),i});if(n)return()=>{for(let a=0;a{const{width:p,height:g,top:x,left:y,right:v,bottom:_,direction:j}=c.current;if(t||i===!1||!o.current||!p||!g)return;const C=j==="rtl",A=n==="left"?C?`right: ${v}`:`left: ${y}`:C?`left: ${y}`:`right: ${v}`,M=r==="bottom"?`bottom: ${_}`:`top: ${x}`;o.current.dataset.motionPopId=l;const I=document.createElement("style");d&&(I.nonce=d);const P=a??document.head;return P.appendChild(I),I.sheet&&I.sheet.insertRule(` [data-motion-pop-id="${l}"] { position: absolute !important; width: ${p}px !important; height: ${g}px !important; ${A}px !important; ${M}px !important; } `),()=>{var R;(R=o.current)==null||R.removeAttribute("data-motion-pop-id"),P.contains(I)&&P.removeChild(I)}},[t]),e.jsx(e5s,{isPresent:t,childRef:o,sizeRef:c,pop:i,children:i===!1?s:k.cloneElement(s,{ref:h})})}const s5s=({children:s,initial:t,isPresent:n,onExitComplete:r,custom:a,presenceAffectsLayout:i,mode:l,anchorX:o,anchorY:c,root:d})=>{const u=LGe(n5s),h=k.useId(),m=k.useRef(n),p=k.useRef(r);RGe(()=>{m.current=n,p.current=r});let g=!0,x=k.useMemo(()=>(g=!1,{id:h,initial:t,isPresent:n,custom:a,onExitComplete:y=>{u.set(y,!0);for(const v of u.values())if(!v)return;r&&r()},register:y=>(u.set(y,!1),()=>{var v;u.delete(y),!m.current&&!u.size&&((v=p.current)==null||v.call(p))})}),[n,u,r]);return i&&g&&(x={...x}),k.useMemo(()=>{u.forEach((y,v)=>u.set(v,!1))},[n]),k.useEffect(()=>{!n&&!u.size&&r&&r()},[n]),s=e.jsx(t5s,{pop:l==="popLayout",isPresent:n,anchorX:o,anchorY:c,root:d,children:s}),e.jsx(oAe.Provider,{value:x,children:s})};function n5s(){return new Map}function LTt(s=!0){const t=k.useContext(oAe);if(t===null)return[!0,null];const{isPresent:n,onExitComplete:r,register:a}=t,i=k.useId();k.useEffect(()=>{if(s)return a(i)},[s]);const l=k.useCallback(()=>s&&r&&r(i),[i,r,s]);return!n&&r?[!1,l]:[!0]}const rre=s=>s.key||"";function hct(s){const t=[];return k.Children.forEach(s,n=>{k.isValidElement(n)&&t.push(n)}),t}const Yq=({children:s,custom:t,initial:n=!0,onExitComplete:r,presenceAffectsLayout:a=!0,mode:i="sync",propagate:l=!1,anchorX:o="left",anchorY:c="top",root:d})=>{const[u,h]=LTt(l),m=k.useMemo(()=>hct(s),[s]),p=l&&!u?[]:m.map(rre),g=k.useRef(!0),x=k.useRef(m),y=LGe(()=>new Map),v=k.useRef(new Set),[_,j]=k.useState(m),[C,A]=k.useState(m);RGe(()=>{g.current=!1,x.current=m;for(let P=0;P{const R=rre(P),O=l&&!u?!1:m===C||p.includes(R),B=()=>{if(v.current.has(R))return;if(y.has(R))v.current.add(R),y.set(R,!0);else return;let U=!0;y.forEach(G=>{G||(U=!1)}),U&&(I==null||I(),A(x.current),l&&(h==null||h()),r&&r())};return e.jsx(s5s,{isPresent:O,initial:!g.current||n?void 0:!1,custom:t,presenceAffectsLayout:a,mode:i,root:d,onExitComplete:O?void 0:B,anchorX:o,anchorY:c,children:P},R)})})},RTt=k.createContext({strict:!1}),mct={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 fct=!1;function r5s(){if(fct)return;const s={};for(const t in mct)s[t]={isEnabled:n=>mct[t].some(r=>!!n[r])};uTt(s),fct=!0}function DTt(){return r5s(),Uks()}function a5s(s){const t=DTt();for(const n in s)t[n]={...t[n],...s[n]};uTt(t)}const i5s=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 jSe(s){return s.startsWith("while")||s.startsWith("drag")&&s!=="draggable"||s.startsWith("layout")||s.startsWith("onTap")||s.startsWith("onPan")||s.startsWith("onLayout")||i5s.has(s)}let OTt=s=>!jSe(s);function o5s(s){typeof s=="function"&&(OTt=t=>t.startsWith("on")?!jSe(t):s(t))}try{o5s(require("@emotion/is-prop-valid").default)}catch{}function l5s(s,t,n){const r={};for(const a in s)a==="values"&&typeof s.values=="object"||av(s[a])||(OTt(a)||n===!0&&jSe(a)||!t&&!jSe(a)||s.draggable&&a.startsWith("onDrag"))&&(r[a]=s[a]);return r}const hAe=k.createContext({});function c5s(s,t){if(uAe(s)){const{initial:n,animate:r}=s;return{initial:n===!1||QZ(n)?n:void 0,animate:QZ(r)?r:void 0}}return s.inherit!==!1?t:{}}function d5s(s){const{initial:t,animate:n}=c5s(s,k.useContext(hAe));return k.useMemo(()=>({initial:t,animate:n}),[pct(t),pct(n)])}function pct(s){return Array.isArray(s)?s.join(" "):s}const oWe=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function FTt(s,t,n){for(const r in t)!av(t[r])&&!yTt(r,n)&&(s[r]=t[r])}function u5s({transformTemplate:s},t){return k.useMemo(()=>{const n=oWe();return rWe(n,t,s),Object.assign({},n.vars,n.style)},[t])}function h5s(s,t){const n=s.style||{},r={};return FTt(r,n,s),Object.assign(r,u5s(s,t)),r}function m5s(s,t){const n={},r=h5s(s,t);return s.drag&&s.dragListener!==!1&&(n.draggable=!1,r.userSelect=r.WebkitUserSelect=r.WebkitTouchCallout="none",r.touchAction=s.drag===!0?"none":`pan-${s.drag==="x"?"y":"x"}`),s.tabIndex===void 0&&(s.onTap||s.onTapStart||s.whileTap)&&(n.tabIndex=0),n.style=r,n}const zTt=()=>({...oWe(),attrs:{}});function f5s(s,t,n,r){const a=k.useMemo(()=>{const i=zTt();return vTt(i,t,_Tt(r),s.transformTemplate,s.style),{...i.attrs,style:{...i.style}}},[t]);if(s.style){const i={};FTt(i,s.style,s),a.style={...i,...a.style}}return a}const p5s=["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 lWe(s){return typeof s!="string"||s.includes("-")?!1:!!(p5s.indexOf(s)>-1||/[A-Z]/u.test(s))}function g5s(s,t,n,{latestValues:r},a,i=!1,l){const c=(l??lWe(s)?f5s:m5s)(t,r,a,s),d=l5s(t,typeof s=="string",i),u=s!==k.Fragment?{...d,...c,ref:n}:{},{children:h}=t,m=k.useMemo(()=>av(h)?h.get():h,[h]);return k.createElement(s,{...u,children:m})}function x5s({scrapeMotionValuesFromProps:s,createRenderState:t},n,r,a){return{latestValues:y5s(n,r,a,s),renderState:t()}}function y5s(s,t,n,r){const a={},i=r(s,{});for(const m in i)a[m]=lNe(i[m]);let{initial:l,animate:o}=s;const c=uAe(s),d=cTt(s);t&&d&&!c&&s.inherit!==!1&&(l===void 0&&(l=t.initial),o===void 0&&(o=t.animate));let u=n?n.initial===!1:!1;u=u||l===!1;const h=u?o:l;if(h&&typeof h!="boolean"&&!dAe(h)){const m=Array.isArray(h)?h:[h];for(let p=0;p(t,n)=>{const r=k.useContext(hAe),a=k.useContext(oAe),i=()=>x5s(s,t,r,a);return n?i():LGe(i)},v5s=BTt({scrapeMotionValuesFromProps:aWe,createRenderState:oWe}),b5s=BTt({scrapeMotionValuesFromProps:wTt,createRenderState:zTt}),_5s=Symbol.for("motionComponentSymbol");function w5s(s,t,n){const r=k.useRef(n);k.useInsertionEffect(()=>{r.current=n});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=r.current;if(typeof l=="function")if(i){const c=l(i);typeof c=="function"&&(a.current=c)}else a.current?(a.current(),a.current=null):l(i);else l&&(l.current=i)},[t])}const $Tt=k.createContext({});function L9(s){return s&&typeof s=="object"&&Object.prototype.hasOwnProperty.call(s,"current")}function j5s(s,t,n,r,a,i){var j,C;const{visualElement:l}=k.useContext(hAe),o=k.useContext(RTt),c=k.useContext(oAe),d=k.useContext(iWe),u=d.reducedMotion,h=d.skipAnimations,m=k.useRef(null),p=k.useRef(!1);r=r||o.renderer,!m.current&&r&&(m.current=r(s,{visualState:t,parent:l,props:n,presenceContext:c,blockInitialAnimation:c?c.initial===!1:!1,reducedMotionConfig:u,skipAnimations:h,isSVG:i}),p.current&&m.current&&(m.current.manuallyAnimateOnMount=!0));const g=m.current,x=k.useContext($Tt);g&&!g.projection&&a&&(g.type==="html"||g.type==="svg")&&N5s(m.current,n,a,x);const y=k.useRef(!1);k.useInsertionEffect(()=>{g&&y.current&&g.update(n,c)});const v=n[QEt],_=k.useRef(!!v&&typeof window<"u"&&!((j=window.MotionHandoffIsComplete)!=null&&j.call(window,v))&&((C=window.MotionHasOptimisedAnimation)==null?void 0:C.call(window,v)));return RGe(()=>{p.current=!0,g&&(y.current=!0,window.MotionIsMounted=!0,g.updateFeatures(),g.scheduleRenderMicrotask(),_.current&&g.animationState&&g.animationState.animateChanges())}),k.useEffect(()=>{g&&(!_.current&&g.animationState&&g.animationState.animateChanges(),_.current&&(queueMicrotask(()=>{var A;(A=window.MotionHandoffMarkAsComplete)==null||A.call(window,v)}),_.current=!1),g.enteringChildren=void 0)}),g}function N5s(s,t,n,r){const{layoutId:a,layout:i,drag:l,dragConstraints:o,layoutScroll:c,layoutRoot:d,layoutAnchor:u,layoutCrossfade:h}=t;s.projection=new n(s.latestValues,t["data-framer-portal-id"]?void 0:UTt(s.parent)),s.projection.setOptions({layoutId:a,layout:i,alwaysMeasureLayout:!!l||o&&L9(o),visualElement:s,animationType:typeof i=="string"?i:"both",initialPromotionConfig:r,crossfade:h,layoutScroll:c,layoutRoot:d,layoutAnchor:u})}function UTt(s){if(s)return s.options.allowProjection!==!1?s.projection:UTt(s.parent)}function BIe(s,{forwardMotionProps:t=!1,type:n}={},r,a){r&&a5s(r);const i=n?n==="svg":lWe(s),l=i?b5s:v5s;function o(d,u){let h;const m={...k.useContext(iWe),...d,layoutId:k5s(d)},{isStatic:p}=m,g=d5s(d),x=l(d,p);if(!p&&typeof window<"u"){S5s();const y=C5s(m);h=y.MeasureLayout,g.visualElement=j5s(s,x,m,a,y.ProjectionNode,i)}return e.jsxs(hAe.Provider,{value:g,children:[h&&g.visualElement?e.jsx(h,{visualElement:g.visualElement,...m}):null,g5s(s,d,w5s(x,g.visualElement,u),x,p,t,i)]})}o.displayName=`motion.${typeof s=="string"?s:`create(${s.displayName??s.name??""})`}`;const c=k.forwardRef(o);return c[_5s]=s,c}function k5s({layoutId:s}){const t=k.useContext(IGe).id;return t&&s!==void 0?t+"-"+s:s}function S5s(s,t){k.useContext(RTt).strict}function C5s(s){const t=DTt(),{drag:n,layout:r}=t;if(!n&&!r)return{};const a={...n,...r};return{MeasureLayout:n!=null&&n.isEnabled(s)||r!=null&&r.isEnabled(s)?a.MeasureLayout:void 0,ProjectionNode:a.ProjectionNode}}function A5s(s,t){if(typeof Proxy>"u")return BIe;const n=new Map,r=(i,l)=>BIe(i,l,s,t),a=(i,l)=>r(i,l);return new Proxy(a,{get:(i,l)=>l==="create"?r:(n.has(l)||n.set(l,BIe(l,void 0,s,t)),n.get(l))})}const E5s=(s,t)=>t.isSVG??lWe(s)?new aSs(t):new Jks(t,{allowProjection:s!==k.Fragment});class T5s extends e6{constructor(t){super(t),t.animationState||(t.animationState=dSs(t))}updateAnimationControlsSubscription(){const{animate:t}=this.node.getProps();dAe(t)&&(this.unmountControls=t.subscribe(this.node))}mount(){this.updateAnimationControlsSubscription()}update(){const{animate:t}=this.node.getProps(),{animate:n}=this.node.prevProps||{};t!==n&&this.updateAnimationControlsSubscription()}unmount(){var t;this.node.animationState.reset(),(t=this.unmountControls)==null||t.call(this)}}let M5s=0;class P5s extends e6{constructor(){super(...arguments),this.id=M5s++,this.isExitComplete=!1}update(){var i;if(!this.node.presenceContext)return;const{isPresent:t,onExitComplete:n}=this.node.presenceContext,{isPresent:r}=this.node.prevPresenceContext||{};if(!this.node.animationState||t===r)return;if(t&&r===!1){if(this.isExitComplete){const{initial:l,custom:o}=this.node.getProps();if(typeof l=="string"||typeof l=="object"&&l!==null&&!Array.isArray(l)){const c=eO(this.node,l,o);if(c){const{transition:d,transitionEnd:u,...h}=c;for(const m in h)(i=this.node.getValue(m))==null||i.jump(h[m])}}this.node.animationState.reset(),this.node.animationState.animateChanges()}else this.node.animationState.setActive("exit",!1);this.isExitComplete=!1;return}const a=this.node.animationState.setActive("exit",!t);n&&!t&&a.then(()=>{this.isExitComplete=!0,n(this.id)})}mount(){const{register:t,onExitComplete:n}=this.node.presenceContext||{};n&&n(this.id),t&&(this.unmount=t(this.id))}unmount(){}}const I5s={animation:{Feature:T5s},exit:{Feature:P5s}};function kee(s){return{point:{x:s.pageX,y:s.pageY}}}const L5s=s=>t=>eWe(t)&&s(t,kee(t));function jY(s,t,n,r){return JZ(s,t,L5s(n),r)}const qTt=({current:s})=>s?s.ownerDocument.defaultView:null,gct=(s,t)=>Math.abs(s-t);function R5s(s,t){const n=gct(s.x,t.x),r=gct(s.y,t.y);return Math.sqrt(n**2+r**2)}const xct=new Set(["auto","scroll"]);class VTt{constructor(t,n,{transformPagePoint:r,contextWindow:a=window,dragSnapToOrigin:i=!1,distanceThreshold:l=3,element:o}={}){if(this.startEvent=null,this.lastMoveEvent=null,this.lastMoveEventInfo=null,this.lastRawMoveEventInfo=null,this.handlers={},this.contextWindow=window,this.scrollPositions=new Map,this.removeScrollListeners=null,this.onElementScroll=g=>{this.handleScroll(g.target)},this.onWindowScroll=()=>{this.handleScroll(window)},this.updatePoint=()=>{if(!(this.lastMoveEvent&&this.lastMoveEventInfo))return;this.lastRawMoveEventInfo&&(this.lastMoveEventInfo=are(this.lastRawMoveEventInfo,this.transformPagePoint));const g=$Ie(this.lastMoveEventInfo,this.history),x=this.startEvent!==null,y=R5s(g.offset,{x:0,y:0})>=this.distanceThreshold;if(!x&&!y)return;const{point:v}=g,{timestamp:_}=K0;this.history.push({...v,timestamp:_});const{onStart:j,onMove:C}=this.handlers;x||(j&&j(this.lastMoveEvent,g),this.startEvent=this.lastMoveEvent),C&&C(this.lastMoveEvent,g)},this.handlePointerMove=(g,x)=>{this.lastMoveEvent=g,this.lastRawMoveEventInfo=x,this.lastMoveEventInfo=are(x,this.transformPagePoint),ym.update(this.updatePoint,!0)},this.handlePointerUp=(g,x)=>{this.end();const{onEnd:y,onSessionEnd:v,resumeAnimation:_}=this.handlers;if((this.dragSnapToOrigin||!this.startEvent)&&_&&_(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const j=$Ie(g.type==="pointercancel"?this.lastMoveEventInfo:are(x,this.transformPagePoint),this.history);this.startEvent&&y&&y(g,j),v&&v(g,j)},!eWe(t))return;this.dragSnapToOrigin=i,this.handlers=n,this.transformPagePoint=r,this.distanceThreshold=l,this.contextWindow=a||window;const c=kee(t),d=are(c,this.transformPagePoint),{point:u}=d,{timestamp:h}=K0;this.history=[{...u,timestamp:h}];const{onSessionStart:m}=n;m&&m(t,$Ie(d,this.history));const p={passive:!0,capture:!0};this.removeListeners=wee(jY(this.contextWindow,"pointermove",this.handlePointerMove,p),jY(this.contextWindow,"pointerup",this.handlePointerUp,p),jY(this.contextWindow,"pointercancel",this.handlePointerUp,p)),o&&this.startScrollTracking(o)}startScrollTracking(t){let n=t.parentElement;for(;n;){const r=getComputedStyle(n);(xct.has(r.overflowX)||xct.has(r.overflowY))&&this.scrollPositions.set(n,{x:n.scrollLeft,y:n.scrollTop}),n=n.parentElement}this.scrollPositions.set(window,{x:window.scrollX,y:window.scrollY}),window.addEventListener("scroll",this.onElementScroll,{capture:!0}),window.addEventListener("scroll",this.onWindowScroll),this.removeScrollListeners=()=>{window.removeEventListener("scroll",this.onElementScroll,{capture:!0}),window.removeEventListener("scroll",this.onWindowScroll)}}handleScroll(t){const n=this.scrollPositions.get(t);if(!n)return;const r=t===window,a=r?{x:window.scrollX,y:window.scrollY}:{x:t.scrollLeft,y:t.scrollTop},i={x:a.x-n.x,y:a.y-n.y};i.x===0&&i.y===0||(r?this.lastMoveEventInfo&&(this.lastMoveEventInfo.point.x+=i.x,this.lastMoveEventInfo.point.y+=i.y):this.history.length>0&&(this.history[0].x-=i.x,this.history[0].y-=i.y),this.scrollPositions.set(t,a),ym.update(this.updatePoint,!0))}updateHandlers(t){this.handlers=t}end(){this.removeListeners&&this.removeListeners(),this.removeScrollListeners&&this.removeScrollListeners(),this.scrollPositions.clear(),AM(this.updatePoint)}}function are(s,t){return t?{point:t(s.point)}:s}function yct(s,t){return{x:s.x-t.x,y:s.y-t.y}}function $Ie({point:s},t){return{point:s,delta:yct(s,HTt(t)),offset:yct(s,D5s(t)),velocity:O5s(t,.1)}}function D5s(s){return s[0]}function HTt(s){return s[s.length-1]}function O5s(s,t){if(s.length<2)return{x:0,y:0};let n=s.length-1,r=null;const a=HTt(s);for(;n>=0&&(r=s[n],!(a.timestamp-r.timestamp>Qw(t)));)n--;if(!r)return{x:0,y:0};r===s[0]&&s.length>2&&a.timestamp-r.timestamp>Qw(t)*2&&(r=s[1]);const i=m2(a.timestamp-r.timestamp);if(i===0)return{x:0,y:0};const l={x:(a.x-r.x)/i,y:(a.y-r.y)/i};return l.x===1/0&&(l.x=0),l.y===1/0&&(l.y=0),l}function F5s(s,{min:t,max:n},r){return t!==void 0&&sn&&(s=r?pm(n,s,r.max):Math.min(s,n)),s}function vct(s,t,n){return{min:t!==void 0?s.min+t:void 0,max:n!==void 0?s.max+n-(s.max-s.min):void 0}}function z5s(s,{top:t,left:n,bottom:r,right:a}){return{x:vct(s.x,n,a),y:vct(s.y,t,r)}}function bct(s,t){let n=t.min-s.min,r=t.max-s.max;return t.max-t.minr?n=ZZ(t.min,t.max-r,s.min):r>a&&(n=ZZ(s.min,s.max-a,t.min)),H5(0,1,n)}function U5s(s,t){const n={};return t.min!==void 0&&(n.min=t.min-s.min),t.max!==void 0&&(n.max=t.max-s.min),n}const K7e=.35;function q5s(s=K7e){return s===!1?s=0:s===!0&&(s=K7e),{x:_ct(s,"left","right"),y:_ct(s,"top","bottom")}}function _ct(s,t,n){return{min:wct(s,t),max:wct(s,n)}}function wct(s,t){return typeof s=="number"?s:s[t]||0}const V5s=new WeakMap;class H5s{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=uy(),this.latestPointerEvent=null,this.latestPanInfo=null,this.visualElement=t}start(t,{snapToCursor:n=!1,distanceThreshold:r}={}){const{presenceContext:a}=this.visualElement;if(a&&a.isPresent===!1)return;const i=h=>{n&&this.snapToCursor(kee(h).point),this.stopAnimation()},l=(h,m)=>{const{drag:p,dragPropagation:g,onDragStart:x}=this.getProps();if(p&&!g&&(this.openDragLock&&this.openDragLock(),this.openDragLock=yks(p),!this.openDragLock))return;this.latestPointerEvent=h,this.latestPanInfo=m,this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),kS(v=>{let _=this.getAxisMotionValue(v).get()||0;if(D5.test(_)){const{projection:j}=this.visualElement;if(j&&j.layout){const C=j.layout.layoutBox[v];C&&(_=lb(C)*(parseFloat(_)/100))}}this.originPoint[v]=_}),x&&ym.update(()=>x(h,m),!1,!0),F7e(this.visualElement,"transform");const{animationState:y}=this.visualElement;y&&y.setActive("whileDrag",!0)},o=(h,m)=>{this.latestPointerEvent=h,this.latestPanInfo=m;const{dragPropagation:p,dragDirectionLock:g,onDirectionLock:x,onDrag:y}=this.getProps();if(!p&&!this.openDragLock)return;const{offset:v}=m;if(g&&this.currentDirection===null){this.currentDirection=W5s(v),this.currentDirection!==null&&x&&x(this.currentDirection);return}this.updateAxis("x",m.point,v),this.updateAxis("y",m.point,v),this.visualElement.render(),y&&ym.update(()=>y(h,m),!1,!0)},c=(h,m)=>{this.latestPointerEvent=h,this.latestPanInfo=m,this.stop(h,m),this.latestPointerEvent=null,this.latestPanInfo=null},d=()=>{const{dragSnapToOrigin:h}=this.getProps();(h||this.constraints)&&this.startAnimation({x:0,y:0})},{dragSnapToOrigin:u}=this.getProps();this.panSession=new VTt(t,{onSessionStart:i,onStart:l,onMove:o,onSessionEnd:c,resumeAnimation:d},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:u,distanceThreshold:r,contextWindow:qTt(this.visualElement),element:this.visualElement.current})}stop(t,n){const r=t||this.latestPointerEvent,a=n||this.latestPanInfo,i=this.isDragging;if(this.cancel(),!i||!a||!r)return;const{velocity:l}=a;this.startAnimation(l);const{onDragEnd:o}=this.getProps();o&&ym.postRender(()=>o(r,a))}cancel(){this.isDragging=!1;const{projection:t,animationState:n}=this.visualElement;t&&(t.isAnimationBlocked=!1),this.endPanSession();const{dragPropagation:r}=this.getProps();!r&&this.openDragLock&&(this.openDragLock(),this.openDragLock=null),n&&n.setActive("whileDrag",!1)}endPanSession(){this.panSession&&this.panSession.end(),this.panSession=void 0}updateAxis(t,n,r){const{drag:a}=this.getProps();if(!r||!ire(t,a,this.currentDirection))return;const i=this.getAxisMotionValue(t);let l=this.originPoint[t]+r[t];this.constraints&&this.constraints[t]&&(l=F5s(l,this.constraints[t],this.elastic[t])),i.set(l)}resolveConstraints(){var i;const{dragConstraints:t,dragElastic:n}=this.getProps(),r=this.visualElement.projection&&!this.visualElement.projection.layout?this.visualElement.projection.measure(!1):(i=this.visualElement.projection)==null?void 0:i.layout,a=this.constraints;t&&L9(t)?this.constraints||(this.constraints=this.resolveRefConstraints()):t&&r?this.constraints=z5s(r.layoutBox,t):this.constraints=!1,this.elastic=q5s(n),a!==this.constraints&&!L9(t)&&r&&this.constraints&&!this.hasMutatedConstraints&&kS(l=>{this.constraints!==!1&&this.getAxisMotionValue(l)&&(this.constraints[l]=U5s(r.layoutBox[l],this.constraints[l]))})}resolveRefConstraints(){const{dragConstraints:t,onMeasureDragConstraints:n}=this.getProps();if(!t||!L9(t))return!1;const r=t.current,{projection:a}=this.visualElement;if(!a||!a.layout)return!1;a.root&&(a.root.scroll=void 0,a.root.updateScroll());const i=Wks(r,a.root,this.visualElement.getTransformPagePoint());let l=B5s(a.layout.layoutBox,i);if(n){const o=n(Vks(l));this.hasMutatedConstraints=!!o,o&&(l=mTt(o))}return l}startAnimation(t){const{drag:n,dragMomentum:r,dragElastic:a,dragTransition:i,dragSnapToOrigin:l,onDragTransitionEnd:o}=this.getProps(),c=this.constraints||{},d=kS(u=>{if(!ire(u,n,this.currentDirection))return;let h=c&&c[u]||{};(l===!0||l===u)&&(h={min:0,max:0});const m=a?200:1e6,p=a?40:1e7,g={type:"inertia",velocity:r?t[u]:0,bounceStiffness:m,bounceDamping:p,timeConstant:750,restDelta:1,restSpeed:10,...i,...h};return this.startAxisValueAnimation(u,g)});return Promise.all(d).then(o)}startAxisValueAnimation(t,n){const r=this.getAxisMotionValue(t);return F7e(this.visualElement,t),r.start(KGe(t,r,0,n,this.visualElement,!1))}stopAnimation(){kS(t=>this.getAxisMotionValue(t).stop())}getAxisMotionValue(t){const n=`_drag${t.toUpperCase()}`,a=this.visualElement.getProps()[n];return a||this.visualElement.getValue(t,this.visualElement.latestValues[t]??0)}snapToCursor(t){kS(n=>{const{drag:r}=this.getProps();if(!ire(n,r,this.currentDirection))return;const{projection:a}=this.visualElement,i=this.getAxisMotionValue(n);if(a&&a.layout){const{min:l,max:o}=a.layout.layoutBox[n],c=i.get()||0;i.set(t[n]-pm(l,o,.5)+c)}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:t,dragConstraints:n}=this.getProps(),{projection:r}=this.visualElement;if(!L9(n)||!r||!this.constraints)return;this.stopAnimation();const a={x:0,y:0};kS(l=>{const o=this.getAxisMotionValue(l);if(o&&this.constraints!==!1){const c=o.get();a[l]=$5s({min:c,max:c},this.constraints[l])}});const{transformTemplate:i}=this.visualElement.getProps();this.visualElement.current.style.transform=i?i({},""):"none",r.root&&r.root.updateScroll(),r.updateLayout(),this.constraints=!1,this.resolveConstraints(),kS(l=>{if(!ire(l,t,null))return;const o=this.getAxisMotionValue(l),{min:c,max:d}=this.constraints[l];o.set(pm(c,d,a[l]))}),this.visualElement.render()}addListeners(){if(!this.visualElement.current)return;V5s.set(this.visualElement,this);const t=this.visualElement.current,n=jY(t,"pointerdown",d=>{const{drag:u,dragListener:h=!0}=this.getProps(),m=d.target,p=m!==t&&Nks(m);u&&h&&!p&&this.start(d)});let r;const a=()=>{const{dragConstraints:d}=this.getProps();L9(d)&&d.current&&(this.constraints=this.resolveRefConstraints(),r||(r=G5s(t,d.current,()=>this.scalePositionWithinConstraints())))},{projection:i}=this.visualElement,l=i.addEventListener("measure",a);i&&!i.layout&&(i.root&&i.root.updateScroll(),i.updateLayout()),ym.read(a);const o=JZ(window,"resize",()=>this.scalePositionWithinConstraints()),c=i.addEventListener("didUpdate",({delta:d,hasLayoutChanged:u})=>{this.isDragging&&u&&(kS(h=>{const m=this.getAxisMotionValue(h);m&&(this.originPoint[h]+=d[h].translate,m.set(m.get()+d[h].translate))}),this.visualElement.render())});return()=>{o(),n(),l(),c&&c(),r&&r()}}getProps(){const t=this.visualElement.getProps(),{drag:n=!1,dragDirectionLock:r=!1,dragPropagation:a=!1,dragConstraints:i=!1,dragElastic:l=K7e,dragMomentum:o=!0}=t;return{...t,drag:n,dragDirectionLock:r,dragPropagation:a,dragConstraints:i,dragElastic:l,dragMomentum:o}}}function jct(s){let t=!0;return()=>{if(t){t=!1;return}s()}}function G5s(s,t,n){const r=Tlt(s,jct(n)),a=Tlt(t,jct(n));return()=>{r(),a()}}function ire(s,t,n){return(t===!0||t===s)&&(n===null||n===s)}function W5s(s,t=10){let n=null;return Math.abs(s.y)>t?n="y":Math.abs(s.x)>t&&(n="x"),n}class K5s extends e6{constructor(t){super(t),this.removeGroupControls=C2,this.removeListeners=C2,this.controls=new H5s(t)}mount(){const{dragControls:t}=this.node.getProps();t&&(this.removeGroupControls=t.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||C2}update(){const{dragControls:t}=this.node.getProps(),{dragControls:n}=this.node.prevProps||{};t!==n&&(this.removeGroupControls(),t&&(this.removeGroupControls=t.subscribe(this.controls)))}unmount(){this.removeGroupControls(),this.removeListeners(),this.controls.isDragging||this.controls.endPanSession()}}const UIe=s=>(t,n)=>{s&&ym.update(()=>s(t,n),!1,!0)};class Y5s extends e6{constructor(){super(...arguments),this.removePointerDownListener=C2}onPointerDown(t){this.session=new VTt(t,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:qTt(this.node)})}createPanHandlers(){const{onPanSessionStart:t,onPanStart:n,onPan:r,onPanEnd:a}=this.node.getProps();return{onSessionStart:UIe(t),onStart:UIe(n),onMove:UIe(r),onEnd:(i,l)=>{delete this.session,a&&ym.postRender(()=>a(i,l))}}}mount(){this.removePointerDownListener=jY(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 qIe=!1;class Z5s extends k.Component{componentDidMount(){const{visualElement:t,layoutGroup:n,switchLayoutGroup:r,layoutId:a}=this.props,{projection:i}=t;i&&(n.group&&n.group.add(i),r&&r.register&&a&&r.register(i),qIe&&i.root.didUpdate(),i.addEventListener("animationComplete",()=>{this.safeToRemove()}),i.setOptions({...i.options,layoutDependency:this.props.layoutDependency,onExitComplete:()=>this.safeToRemove()})),cNe.hasEverUpdated=!0}getSnapshotBeforeUpdate(t){const{layoutDependency:n,visualElement:r,drag:a,isPresent:i}=this.props,{projection:l}=r;return l&&(l.isPresent=i,t.layoutDependency!==n&&l.setOptions({...l.options,layoutDependency:n}),qIe=!0,a||t.layoutDependency!==n||n===void 0||t.isPresent!==i?l.willUpdate():this.safeToRemove(),t.isPresent!==i&&(i?l.promote():l.relegate()||ym.postRender(()=>{const o=l.getStack();(!o||!o.members.length)&&this.safeToRemove()}))),null}componentDidUpdate(){const{visualElement:t,layoutAnchor:n}=this.props,{projection:r}=t;r&&(r.options.layoutAnchor=n,r.root.didUpdate(),JGe.postRender(()=>{!r.currentAnimation&&r.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:t,layoutGroup:n,switchLayoutGroup:r}=this.props,{projection:a}=t;qIe=!0,a&&(a.scheduleCheckAfterUnmount(),n&&n.group&&n.group.remove(a),r&&r.deregister&&r.deregister(a))}safeToRemove(){const{safeToRemove:t}=this.props;t&&t()}render(){return null}}function GTt(s){const[t,n]=LTt(),r=k.useContext(IGe);return e.jsx(Z5s,{...s,layoutGroup:r,switchLayoutGroup:k.useContext($Tt),isPresent:t,safeToRemove:n})}const X5s={pan:{Feature:Y5s},drag:{Feature:K5s,ProjectionNode:ITt,MeasureLayout:GTt}};function Nct(s,t,n){const{props:r}=s;s.animationState&&r.whileHover&&s.animationState.setActive("whileHover",n==="Start");const a="onHover"+n,i=r[a];i&&ym.postRender(()=>i(t,kee(t)))}class Q5s extends e6{mount(){const{current:t}=this.node;t&&(this.unmount=bks(t,(n,r)=>(Nct(this.node,r,"Start"),a=>Nct(this.node,a,"End"))))}unmount(){}}class J5s extends e6{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=wee(JZ(this.node.current,"focus",()=>this.onFocus()),JZ(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function kct(s,t,n){const{props:r}=s;if(s.current instanceof HTMLButtonElement&&s.current.disabled)return;s.animationState&&r.whileTap&&s.animationState.setActive("whileTap",n==="Start");const a="onTap"+(n==="End"?"":n),i=r[a];i&&ym.postRender(()=>i(t,kee(t)))}class e4s extends e6{mount(){const{current:t}=this.node;if(!t)return;const{globalTapTarget:n,propagate:r}=this.node.props;this.unmount=Sks(t,(a,i)=>(kct(this.node,i,"Start"),(l,{success:o})=>kct(this.node,l,o?"End":"Cancel")),{useGlobalTarget:n,stopPropagation:(r==null?void 0:r.tap)===!1})}unmount(){}}const Y7e=new WeakMap,VIe=new WeakMap,t4s=s=>{const t=Y7e.get(s.target);t&&t(s)},s4s=s=>{s.forEach(t4s)};function n4s({root:s,...t}){const n=s||document;VIe.has(n)||VIe.set(n,{});const r=VIe.get(n),a=JSON.stringify(t);return r[a]||(r[a]=new IntersectionObserver(s4s,{root:s,...t})),r[a]}function r4s(s,t,n){const r=n4s(t);return Y7e.set(s,n),r.observe(s),()=>{Y7e.delete(s),r.unobserve(s)}}const a4s={some:0,all:1};class i4s extends e6{constructor(){super(...arguments),this.hasEnteredView=!1,this.isInView=!1}startObserver(){var c;(c=this.stopObserver)==null||c.call(this);const{viewport:t={}}=this.node.getProps(),{root:n,margin:r,amount:a="some",once:i}=t,l={root:n?n.current:void 0,rootMargin:r,threshold:typeof a=="number"?a:a4s[a]},o=d=>{const{isIntersecting:u}=d;if(this.isInView===u||(this.isInView=u,i&&!u&&this.hasEnteredView))return;u&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive("whileInView",u);const{onViewportEnter:h,onViewportLeave:m}=this.node.getProps(),p=u?h:m;p&&p(d)};this.stopObserver=r4s(this.node.current,l,o)}mount(){this.startObserver()}update(){if(typeof IntersectionObserver>"u")return;const{props:t,prevProps:n}=this.node;["amount","margin","root"].some(o4s(t,n))&&this.startObserver()}unmount(){var t;(t=this.stopObserver)==null||t.call(this),this.hasEnteredView=!1,this.isInView=!1}}function o4s({viewport:s={}},{viewport:t={}}={}){return n=>s[n]!==t[n]}const l4s={inView:{Feature:i4s},tap:{Feature:e4s},focus:{Feature:J5s},hover:{Feature:Q5s}},c4s={layout:{ProjectionNode:ITt,MeasureLayout:GTt}},d4s={...I5s,...l4s,...X5s,...c4s},_r=A5s(d4s,E5s),u4s={some:0,all:1};function h4s(s,t,{root:n,margin:r,amount:a="some"}={}){const i=QGe(s),l=new WeakMap,o=d=>{d.forEach(u=>{const h=l.get(u.target);if(u.isIntersecting!==!!h)if(u.isIntersecting){const m=t(u.target,u);typeof m=="function"?l.set(u.target,m):c.unobserve(u.target)}else typeof h=="function"&&(h(u),l.delete(u.target))})},c=new IntersectionObserver(o,{root:n,rootMargin:r,threshold:typeof a=="number"?a:u4s[a]});return i.forEach(d=>c.observe(d)),()=>c.disconnect()}function m4s(s,{root:t,margin:n,amount:r,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:n,amount:r};return h4s(s.current,c,d)},[t,s,n,a,r]),l}function f4s(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 Sct(s){return s.visitor_intent==="buying"&&!s.has_agent}function p4s({token:s}={}){var g;const t=oo(),n=s||t.token,{data:r,isLoading:a,isError:i}=m2s(n),l=ls(),o=(g=r==null?void 0:r.open_houses)==null?void 0:g.id,{data:c}=pt({queryKey:["cohost-visitors",o],queryFn:async()=>{const{data:x,error:y}=await V.from("open_house_visitors").select("*").eq("open_house_id",o).order("created_at",{ascending:!1});if(y)throw y;return x},enabled:!!o});if(k.useEffect(()=>{if(!o)return;const x=V.channel(`cohost-visitors-${o}`).on("postgres_changes",{event:"INSERT",schema:"public",table:"open_house_visitors",filter:`open_house_id=eq.${o}`},()=>{l.invalidateQueries({queryKey:["cohost-visitors",o]})}).subscribe();return()=>{V.removeChannel(x)}},[o,l]),a)return e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-slate-950 via-slate-900 to-slate-950 flex items-center justify-center",children:e.jsx("div",{className:"animate-pulse text-white/40",children:"Validating access..."})});if(i||!r)return e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-slate-950 via-slate-900 to-slate-950 flex items-center justify-center p-6",children:e.jsxs("div",{className:"text-center text-white",children:[e.jsx("h1",{className:"text-xl font-bold mb-2",children:"Link Expired or Invalid"}),e.jsx("p",{className:"text-white/40 text-sm",children:"This co-host link is no longer active. Ask the host for a new one."})]})});const d=r.open_houses,u=(c==null?void 0:c.length)||0,h=(c==null?void 0:c.filter(x=>x.visitor_intent==="buying").length)||0,m=(c==null?void 0:c.filter(Sct).length)||0,p=x=>{if(!x)return"";const[y,v]=x.split(":"),_=parseInt(y);return`${_>12?_-12:_||12}:${v} ${_>=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(Xn,{className:"h-4 w-4"}),e.jsx("span",{className:"font-bold text-white",children:u})]}),e.jsxs("div",{className:"flex items-center gap-1.5 text-orange-400",children:[e.jsx(iu,{className:"h-4 w-4"}),e.jsx("span",{className:"font-bold text-white",children:m})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(ua,{className:"h-4 w-4"}),e.jsx("span",{className:"font-bold text-white",children:h})]})]})]}),e.jsxs("div",{className:"px-4 sm:px-6 py-2 flex items-center gap-4 text-xs text-white/40 border-b border-white/5",children:[e.jsx("span",{children:Ys(new Date(d.event_date+"T00:00:00"),"EEEE, MMMM d, yyyy")}),d.start_time&&e.jsxs("span",{children:[p(d.start_time),d.end_time?` – ${p(d.end_time)}`:""]})]}),e.jsx(Eo,{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(Yq,{children:c.map((x,y)=>{var j;const v=f4s(x.visitor_intent),_=Sct(x);return e.jsxs(_r.div,{initial:{opacity:0,x:-40,scale:.95},animate:{opacity:1,x:0,scale:1},transition:{duration:.4,delay:y*.05},className:`flex items-center gap-4 p-4 rounded-xl border ${_?"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 ${_?"bg-gradient-to-br from-orange-500 to-amber-500 text-white":"bg-white/10 text-white/80"}`,children:(j=x.first_name[0])==null?void 0:j.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:[x.first_name," ",x.last_name||""]}),_&&e.jsx(qe,{className:"bg-orange-500/20 text-orange-300 border-orange-500/40 text-[10px] px-1.5 py-0",children:"🔥 HOT"}),x.has_agent&&e.jsx(qe,{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(qe,{variant:"outline",className:`text-[10px] px-1.5 py-0 ${v.color}`,children:[v.emoji," ",v.label]}),e.jsx("span",{className:"text-white/30 text-xs",children:Ys(new Date(x.created_at),"h:mm a")})]})]})]},x.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(Cy,{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 g4s(){const t=Tu().pathname.slice(1);if(k.useEffect(()=>(document.body.classList.add("guestbook-page"),()=>{document.body.classList.remove("guestbook-page")}),[]),t.startsWith("live/")){const n=t.slice(5);if(n)return e.jsx(p4s,{token:n})}return!t||t===""?e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900 flex items-center justify-center p-6",children:e.jsxs("div",{className:"text-center text-white",children:[e.jsx("h1",{className:"text-2xl font-bold mb-2",children:"Guest Book"}),e.jsx("p",{className:"text-white/60",children:"The modern open house sign-in experience."}),e.jsx("p",{className:"text-white/40 text-sm mt-2",children:"Visit a specific open house link to sign in."})]})}):e.jsx(dEt,{slug:t})}function x4s({dealData:s,agentProfile:t,welcomeMessage:n,isWon:r,branding:a}){var d;const i=s!=null&&s.property_address?`${s.property_address}, ${s.city||""}, ${s.state||""}`.replace(/,\s*,/g,",").replace(/,\s*$/,""):null,l=(a==null?void 0:a.logo_url)||null,o=(a==null?void 0:a.cover_photo_url)||null,c=(a==null?void 0:a.tagline)||"Your Real Estate Concierge";return e.jsxs("div",{className:"relative overflow-hidden",children:[e.jsxs("div",{className:"relative px-4 pt-10 pb-20",children:[o&&e.jsx("div",{className:"absolute inset-0",style:{backgroundImage:`url(${o})`,backgroundSize:"cover",backgroundPosition:"center",filter:"var(--portal-hero-filter-mobile)"}}),e.jsx("div",{className:"absolute inset-0",style:{background:o?"var(--portal-hero-scrim-mobile)":"radial-gradient(ellipse 100% 70% at 50% 0%, hsl(var(--portal-gold) / 0.12), transparent 60%), linear-gradient(180deg, hsl(0 0% 7%), hsl(0 0% 4%))"}}),e.jsx("div",{className:"absolute inset-0 opacity-[0.05]",style:{backgroundImage:"radial-gradient(circle at 25% 25%, hsl(var(--portal-gold)) 1px, transparent 1px)",backgroundSize:"32px 32px"}}),e.jsxs("div",{className:"relative text-center max-w-lg mx-auto",children:[l&&e.jsx(_r.div,{initial:{opacity:0,y:-8},animate:{opacity:1,y:0},transition:{duration:.5},className:"mb-6 flex justify-center",children:e.jsx("div",{className:"rounded-xl px-4 py-2.5",style:{background:"hsl(0 0% 100% / 0.06)",backdropFilter:"blur(8px)",border:"1px solid hsl(var(--portal-gold) / 0.2)"},children:e.jsx("img",{src:l,alt:"Brand",className:"h-9 max-w-[160px] object-contain"})})}),t&&e.jsxs(_r.div,{initial:{opacity:0,y:8},animate:{opacity:1,y:0},transition:{duration:.5,delay:.05},className:"mb-6",children:[t.avatar_url?e.jsx("div",{className:"w-20 h-20 mx-auto mb-3 relative",children:e.jsx("div",{className:"absolute inset-0 rounded-full",style:{background:"var(--portal-gradient-gold)",padding:"2px"},children:e.jsx("img",{src:t.avatar_url,alt:t.name,className:"w-full h-full rounded-full object-cover",style:{background:"hsl(var(--portal-surface))"}})})}):e.jsx("div",{className:"w-20 h-20 mx-auto mb-3 rounded-full flex items-center justify-center portal-serif text-3xl",style:{background:"hsl(var(--portal-surface-2))",border:"1px solid hsl(var(--portal-gold) / 0.3)",color:"var(--portal-hero-accent)"},children:((d=t.name)==null?void 0:d.charAt(0))||"?"}),e.jsx("p",{className:"portal-serif text-lg",style:{color:"var(--portal-hero-ink)"},children:t.name}),e.jsx("p",{className:"text-[10px] mt-1 tracking-[0.22em] uppercase",style:{color:"var(--portal-hero-ink-dim)"},children:c})]}),e.jsxs(_r.div,{initial:{opacity:0,y:8},animate:{opacity:1,y:0},transition:{duration:.6,delay:.1},children:[e.jsxs("div",{className:"inline-flex items-center gap-1.5 rounded-full px-3 py-1 text-[10px] tracking-[0.2em] uppercase mb-4",style:{background:"hsl(var(--portal-gold) / 0.08)",border:"1px solid hsl(var(--portal-gold) / 0.25)",color:"var(--portal-hero-accent)"},children:[e.jsx(ua,{className:"w-3 h-3"}),(s==null?void 0:s.deal_type)==="listing"?"Sale":(s==null?void 0:s.deal_type)==="buy-side"?"Purchase":"Transaction",r&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"opacity-50",children:"·"}),"Complete"]})]}),e.jsx("h1",{className:"portal-serif text-[2.5rem] leading-[1.05] mb-3",style:{color:"var(--portal-hero-ink)"},children:(s==null?void 0:s.deal_name)||"Your Transaction"}),e.jsx("div",{className:"portal-hairline w-24 mx-auto mb-4"}),i&&e.jsxs("div",{className:"flex items-center justify-center gap-1.5 text-sm",style:{color:"var(--portal-hero-ink-muted)"},children:[e.jsx(Si,{className:"w-3.5 h-3.5",style:{color:"var(--portal-hero-accent)"}}),e.jsx("span",{children:i})]}),n&&e.jsxs("p",{className:"mt-6 text-sm leading-relaxed max-w-md mx-auto italic portal-serif",style:{color:"var(--portal-hero-ink-muted)",fontSize:"1.05rem"},children:["“",n,"”"]})]})]})]}),t&&e.jsx("div",{className:"max-w-lg mx-auto px-4 -mt-10 relative z-10",children:e.jsx("div",{className:"rounded-2xl p-3",style:{background:"hsl(var(--portal-surface))",border:"1px solid hsl(var(--portal-gold) / 0.2)",boxShadow:"var(--portal-shadow-tile)"},children:e.jsxs("div",{className:"flex items-center justify-center gap-2",children:[t.phone&&e.jsxs("a",{href:`tel:${t.phone}`,className:"flex-1 flex items-center justify-center gap-2 px-3 py-2.5 rounded-xl transition-colors",style:{background:"hsl(var(--portal-gold) / 0.06)",color:"var(--portal-hero-accent)",border:"1px solid hsl(var(--portal-gold) / 0.15)"},children:[e.jsx(ka,{className:"w-4 h-4"}),e.jsx("span",{className:"text-sm font-medium",children:"Call"})]}),t.email&&e.jsxs("a",{href:`mailto:${t.email}`,className:"flex-1 flex items-center justify-center gap-2 px-3 py-2.5 rounded-xl transition-colors",style:{background:"hsl(var(--portal-gold) / 0.06)",color:"var(--portal-hero-accent)",border:"1px solid hsl(var(--portal-gold) / 0.15)"},children:[e.jsx(pn,{className:"w-4 h-4"}),e.jsx("span",{className:"text-sm font-medium",children:"Email"})]}),t.phone&&e.jsxs("a",{href:`sms:${t.phone}`,className:"flex-1 flex items-center justify-center gap-2 px-3 py-2.5 rounded-xl transition-colors",style:{background:"hsl(var(--portal-gold) / 0.06)",color:"var(--portal-hero-accent)",border:"1px solid hsl(var(--portal-gold) / 0.15)"},children:[e.jsx(Vu,{className:"w-4 h-4"}),e.jsx("span",{className:"text-sm font-medium",children:"Text"})]})]})})})]})}function WTt({targetCloseDate:s,actualCloseDate:t,clientName:n}){if(t||!s)return null;const r=s.split(/[-/T]/),a=new Date(Number(r[0]),Number(r[1])-1,Number(r[2])),l=I2(a,new Date);if(R5(a)&&!m0(a))return null;const o=m0(a),c=o?"0":String(Math.max(0,l)),d=Math.max(4,Math.min(100,(60-Math.min(60,l))/60*100));return e.jsxs("div",{className:"portal-tile p-8 text-center",children:[e.jsx("p",{className:"portal-eyebrow mb-4",children:o?"The Moment Has Arrived":"Countdown to Closing"}),o?e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"portal-serif text-5xl mb-2",style:{color:"hsl(var(--portal-gold))"},children:"Closing Day"}),e.jsxs("p",{className:"text-sm mt-3",style:{color:"hsl(var(--portal-ink-muted))"},children:["Congratulations",n?`, ${n.split(" ")[0]}`:"","."]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-baseline justify-center gap-3",children:[e.jsx(_r.span,{initial:{opacity:0,y:8},animate:{opacity:1,y:0},transition:{duration:.6},className:"portal-serif tabular-nums leading-none",style:{fontSize:"5.5rem",color:"hsl(var(--portal-gold))",textShadow:"0 0 40px hsl(var(--portal-gold) / 0.4)"},children:c}),e.jsx("span",{className:"portal-serif",style:{fontSize:"1.5rem",color:"hsl(var(--portal-ink-muted))"},children:l===1?"day":"days"})]}),e.jsx("div",{className:"portal-hairline w-16 mx-auto my-4"}),e.jsx("p",{className:"text-xs tracking-[0.2em] uppercase",style:{color:"hsl(var(--portal-ink-muted))"},children:"Until you hold the keys"}),e.jsx("div",{className:"mt-6 mx-auto max-w-[260px]",children:e.jsx("div",{className:"h-[2px] rounded-full overflow-hidden",style:{background:"hsl(var(--portal-gold) / 0.15)"},children:e.jsx(_r.div,{initial:{width:0},animate:{width:`${d}%`},transition:{duration:1.2,ease:"easeOut"},className:"h-full rounded-full",style:{background:"var(--portal-gradient-gold)",boxShadow:"0 0 12px hsl(var(--portal-gold) / 0.6)"}})})})]})]})}function KTt({journeyStages:s,currentIndex:t}){return s.length===0?null:e.jsxs("div",{children:[e.jsx("p",{className:"portal-eyebrow mb-2",children:"The Journey"}),e.jsx("h2",{className:"portal-serif text-2xl mb-6",style:{color:"hsl(var(--portal-ink))"},children:"Your path to the keys"}),e.jsx("div",{className:"relative",children:s.map((n,r)=>{const a=rt;return e.jsxs(_r.div,{initial:{opacity:0,x:-6},animate:{opacity:1,x:0},transition:{duration:.35,delay:r*.05},className:"flex items-start gap-4 relative",children:[r{var l,o;if(i.includes("youtube.com/watch")){const c=new URL(i).searchParams.get("v");return c?`https://www.youtube.com/embed/${c}`:null}if(i.includes("youtu.be/")){const c=(l=i.split("youtu.be/")[1])==null?void 0:l.split("?")[0];return c?`https://www.youtube.com/embed/${c}`:null}if(i.includes("loom.com/share/")){const c=(o=i.split("loom.com/share/")[1])==null?void 0:o.split("?")[0];return c?`https://www.loom.com/embed/${c}`:null}return i};return e.jsxs("div",{children:[e.jsx("p",{className:"portal-eyebrow mb-2",children:"Right Now"}),e.jsx("h4",{className:"portal-serif text-3xl mb-2 portal-gold-underline",style:{color:"hsl(var(--portal-ink))"},children:s.label}),e.jsx("p",{className:"text-sm leading-relaxed mt-4",style:{color:"hsl(var(--portal-ink-muted))"},children:s.description}),t&&e.jsxs("div",{className:"mt-5 rounded-xl p-4",style:{background:"hsl(var(--portal-surface-2))",border:"1px solid hsl(var(--portal-gold) / 0.15)"},children:[e.jsx("p",{className:"portal-eyebrow mb-2",children:"Note From Your Agent"}),e.jsxs("p",{className:"text-sm leading-relaxed portal-serif italic",style:{color:"hsl(var(--portal-ink))",fontSize:"1rem"},children:["“",t,"”"]})]}),n&&e.jsxs("div",{className:"mt-5 rounded-xl p-4",style:{background:"linear-gradient(135deg, hsl(var(--portal-gold) / 0.08), hsl(var(--portal-gold) / 0.02))",border:"1px solid hsl(var(--portal-gold) / 0.25)"},children:[e.jsx("p",{className:"portal-eyebrow mb-2",children:"What’s Next"}),e.jsx("p",{className:"text-sm leading-relaxed",style:{color:"hsl(var(--portal-ink))"},children:n})]}),r&&e.jsx("div",{className:"mt-5 rounded-xl overflow-hidden aspect-video relative group",style:{background:"hsl(var(--portal-bg))",border:"1px solid hsl(var(--portal-gold) / 0.2)"},children:e.jsx("iframe",{src:a(r)||r,className:"w-full h-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0,title:"Next step video"})})]})}function ih(s){const t=s.split(/[-/T]/);if(t.length>=3){const n=Number(t[0]);return n>99?new Date(n,Number(t[1])-1,Number(t[2])):new Date(Number(t[2]),Number(t[0])-1,Number(t[1]))}return new Date(`${s}T12:00:00`)}const y4s=[{key:"contract_date",label:"Contract Accepted",icon:A5},{key:"earnest_money_due_date",label:"Earnest Money",icon:Su},{key:"inspection_date",label:"Inspection",icon:Yr},{key:"inspection_contingency_date",label:"Inspection Deadline",icon:ea},{key:"appraisal_date",label:"Appraisal",icon:ua},{key:"loan_approval_date",label:"Loan Approval",icon:Gz},{key:"title_docs_due_date",label:"Title & Disclosures",icon:ea},{key:"final_walkthrough_date",label:"Final Walkthrough",icon:x3},{key:"target_close_date",label:"Target Close",icon:ha}];function v4s(s,t){const n=Ys(t,"yyyyMMdd");return`https://calendar.google.com/calendar/render?${new URLSearchParams({action:"TEMPLATE",text:s,dates:`${n}/${n}`,details:"Added from your Client Portal"}).toString()}`}function b4s(s,t){const n=Ys(t,"yyyyMMdd");return`data:text/calendar;charset=utf-8,${encodeURIComponent(`BEGIN:VCALENDAR VERSION:2.0 BEGIN:VEVENT DTSTART;VALUE=DATE:${n} DTEND;VALUE=DATE:${n} SUMMARY:${s} DESCRIPTION:Added from your Client Portal END:VEVENT END:VCALENDAR`)}`}function ZTt({deal:s,portal:t,targetCloseDate:n,contractDate:r,inspectionDate:a,appraisalDate:i,actualCloseDate:l}){const o={...s||{},contract_date:(s==null?void 0:s.contract_date)??r??null,inspection_date:(s==null?void 0:s.inspection_date)??(t==null?void 0:t.inspection_date)??a??null,appraisal_date:(s==null?void 0:s.appraisal_date)??(t==null?void 0:t.appraisal_date)??i??null,target_close_date:(s==null?void 0:s.target_close_date)??n??null},c=(s==null?void 0:s.actual_close_date)??l??null,d=Array.isArray(s==null?void 0:s.completed_key_dates)?s.completed_key_dates:[],u=y4s.map(p=>p.key==="target_close_date"&&c?{...p,label:"Closed",date:c,done:!0}:{...p,date:o[p.key],done:d.includes(p.key)}).filter(p=>!!p.date);if(u.length===0)return null;const h=(p,g,x)=>{const y=ih(g);if(x==="google")window.open(v4s(p,y),"_blank");else{const v=b4s(p,y),_=document.createElement("a");_.href=v,_.download=`${p.replace(/\s+/g,"-").toLowerCase()}.ics`,_.click()}},m=u.filter(p=>p.done).length;return e.jsxs("div",{children:[e.jsx("p",{className:"portal-eyebrow mb-2",children:"Milestones"}),e.jsxs("div",{className:"flex items-baseline justify-between gap-3 mb-5 flex-wrap",children:[e.jsx("h2",{className:"portal-serif text-2xl",style:{color:"hsl(var(--portal-ink))"},children:"Key dates"}),e.jsxs("span",{className:"text-[11px] tracking-[0.18em] uppercase",style:{color:"hsl(var(--portal-ink-dim))"},children:[m," of ",u.length," complete"]})]}),e.jsxs("div",{className:"space-y-4 relative",children:[e.jsx("div",{className:"absolute left-[10px] top-2 bottom-2 w-[1px]",style:{background:"hsl(var(--portal-gold) / 0.18)"}}),u.map(({label:p,date:g,done:x,icon:y})=>{const v=ih(g),_=R5(v)&&!m0(v),j=m0(v),C=!_&&!j,A=x?"Completed":j?"Today":_?"In progress":"Upcoming";return e.jsxs("div",{className:"flex items-start gap-3 relative",children:[e.jsx("div",{className:"w-[21px] h-[21px] rounded-full mt-0.5 flex-shrink-0 relative z-10 flex items-center justify-center",style:{background:x?"hsl(var(--portal-gold))":j?"hsl(var(--portal-gold) / 0.25)":"hsl(var(--portal-surface-2))",border:"1px solid hsl(var(--portal-gold) / 0.7)",boxShadow:j?"0 0 12px hsl(var(--portal-gold) / 0.5)":"none"},children:x?e.jsx(ma,{className:"w-3 h-3",style:{color:"hsl(var(--portal-surface))"}}):e.jsx(y,{className:"w-3 h-3",style:{color:"hsl(var(--portal-gold))"}})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-[10px] tracking-[0.22em] uppercase",style:{color:"hsl(var(--portal-ink-dim))"},children:p}),e.jsx("p",{className:"portal-serif mt-0.5",style:{fontSize:"1.15rem",color:x?"hsl(var(--portal-ink-muted))":"hsl(var(--portal-ink))"},children:Ys(v,"MMM d, yyyy")}),e.jsx("span",{className:"inline-block mt-1 text-[9px] tracking-[0.2em] uppercase px-2 py-0.5 rounded-full",style:{color:x||j?"hsl(var(--portal-gold))":"hsl(var(--portal-ink-dim))",border:`1px solid hsl(var(--portal-gold) / ${x||j?.5:.18})`},children:A})]}),C&&e.jsxs("div",{className:"flex items-center gap-1 mt-1",children:[e.jsx("button",{onClick:()=>h(p,g,"google"),className:"p-1.5 rounded transition-colors",style:{color:"hsl(var(--portal-ink-dim))"},onMouseEnter:M=>{M.currentTarget.style.color="hsl(var(--portal-gold))"},onMouseLeave:M=>{M.currentTarget.style.color="hsl(var(--portal-ink-dim))"},title:"Add to Google Calendar",children:e.jsx(i1,{className:"w-3.5 h-3.5"})}),e.jsx("button",{onClick:()=>h(p,g,"apple"),className:"text-[9px] tracking-widest px-1.5 py-1 rounded",style:{color:"hsl(var(--portal-ink-dim))"},title:"Download .ics",children:".ICS"})]})]},p)})]})]})}function XTt({documents:s}){const t=r=>r<1024?`${r} B`:r<1048576?`${(r/1024).toFixed(0)} KB`:`${(r/1048576).toFixed(1)} MB`,n=async r=>{const{data:a}=await V.storage.from("deal-files").createSignedUrl(r.storage_path,300);a!=null&&a.signedUrl&&window.open(a.signedUrl,"_blank")};return e.jsxs("div",{children:[e.jsx("p",{className:"portal-eyebrow mb-2",children:"Paperwork"}),e.jsx("h2",{className:"portal-serif text-2xl mb-5",style:{color:"hsl(var(--portal-ink))"},children:"Documents"}),e.jsx("div",{className:"space-y-2",children:s.map(r=>e.jsxs("button",{onClick:()=>n(r),className:"w-full flex items-center gap-3 p-3 rounded-xl transition-all text-left group",style:{background:"hsl(var(--portal-surface-2))",border:"1px solid hsl(var(--portal-gold) / 0.08)"},onMouseEnter:a=>{a.currentTarget.style.borderColor="hsl(var(--portal-gold) / 0.35)"},onMouseLeave:a=>{a.currentTarget.style.borderColor="hsl(var(--portal-gold) / 0.08)"},children:[e.jsx("div",{className:"w-10 h-10 rounded-lg flex items-center justify-center flex-shrink-0",style:{background:"hsl(var(--portal-gold) / 0.08)",border:"1px solid hsl(var(--portal-gold) / 0.2)"},children:e.jsx(ea,{className:"w-4 h-4",style:{color:"hsl(var(--portal-gold))"}})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm portal-serif truncate",style:{color:"hsl(var(--portal-ink))",fontSize:"1rem"},children:r.file_name}),e.jsx("p",{className:"text-[10px] tracking-widest uppercase mt-0.5",style:{color:"hsl(var(--portal-ink-dim))"},children:t(r.file_size)})]}),e.jsx(ji,{className:"w-4 h-4 flex-shrink-0",style:{color:"hsl(var(--portal-gold) / 0.5)"}})]},r.id))})]})}function QTt({updates:s}){const t=n=>{var r,a;if(n.includes("youtube.com/watch")){const i=new URL(n).searchParams.get("v");return i?`https://www.youtube.com/embed/${i}`:null}if(n.includes("youtu.be/")){const i=(r=n.split("youtu.be/")[1])==null?void 0:r.split("?")[0];return i?`https://www.youtube.com/embed/${i}`:null}if(n.includes("loom.com/share/")){const i=(a=n.split("loom.com/share/")[1])==null?void 0:a.split("?")[0];return i?`https://www.loom.com/embed/${i}`:null}return n};return e.jsxs("div",{children:[e.jsx("p",{className:"portal-eyebrow mb-2",children:"Dispatch"}),e.jsx("h2",{className:"portal-serif text-2xl mb-5",style:{color:"hsl(var(--portal-ink))"},children:"Updates from your agent"}),e.jsx("div",{className:"space-y-6",children:s.map((n,r)=>e.jsx("div",{className:r>0?"pt-6":"",style:r>0?{borderTop:"1px solid hsl(var(--portal-gold) / 0.1)"}:void 0,children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-8 h-8 rounded-full flex items-center justify-center flex-shrink-0 mt-0.5",style:{background:n.is_stage_change?"hsl(var(--portal-gold) / 0.15)":"hsl(var(--portal-surface-3))",border:"1px solid hsl(var(--portal-gold) / 0.25)"},children:n.is_stage_change?e.jsx(Ix,{className:"w-3.5 h-3.5",style:{color:"hsl(var(--portal-gold))"}}):e.jsx(Fx,{className:"w-3.5 h-3.5",style:{color:"hsl(var(--portal-gold))"}})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-baseline justify-between gap-2",children:[e.jsx("h3",{className:"portal-serif",style:{fontSize:r===0?"1.4rem":"1.15rem",color:"hsl(var(--portal-ink))"},children:n.title}),e.jsx("span",{className:"text-[10px] tracking-[0.2em] uppercase flex-shrink-0",style:{color:"hsl(var(--portal-ink-dim))"},children:Ys(new Date(n.created_at),"MMM d")})]}),n.content&&e.jsx("p",{className:`text-sm mt-2 leading-relaxed ${r===0?"italic portal-serif":""}`,style:{color:"hsl(var(--portal-ink-muted))",fontSize:r===0?"1rem":"0.875rem"},children:r===0?`“${n.content}”`:n.content}),n.video_url&&e.jsx("div",{className:"mt-3 rounded-xl overflow-hidden aspect-video",style:{background:"hsl(var(--portal-bg))",border:"1px solid hsl(var(--portal-gold) / 0.15)"},children:e.jsx("iframe",{src:t(n.video_url)||n.video_url,className:"w-full h-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0,title:n.title})})]})]})},n.id))})]})}const Zq=[{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"}],_4s=[{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 w4s(s){return pt({queryKey:["vendors","brokerage",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await V.from("vendors").select("*").eq("owner_type","brokerage").eq("owner_brokerage_id",s).order("sort_order",{ascending:!0}).order("name",{ascending:!0});if(n)throw n;return t||[]},enabled:!!s})}function j4s(){const s=ai(),{brokerageId:t}=ks();return pt({queryKey:["vendors","library",s,t],queryFn:async()=>{if(!s)return{vendors:[],selections:[]};let n=V.from("vendors").select("*");t?n=n.or(`and(owner_type.eq.agent,owner_user_id.eq.${s}),and(owner_type.eq.brokerage,owner_brokerage_id.eq.${t})`):n=n.eq("owner_type","agent").eq("owner_user_id",s);const[{data:r,error:a},{data:i,error:l}]=await Promise.all([n.order("sort_order",{ascending:!0}).order("name",{ascending:!0}),V.from("agent_vendor_selections").select("*").eq("agent_user_id",s)]);if(a)throw a;if(l)throw l;return{vendors:r||[],selections:i||[]}},enabled:!!s})}function N4s(){const s=ls();return Nt({mutationFn:async t=>{if(t.id){const{id:n,created_at:r,...a}=t,{data:i,error:l}=await V.from("vendors").update(a).eq("id",n).select().single();if(l)throw l;return i}else{const{data:n,error:r}=await V.from("vendors").insert(t).select().single();if(r)throw r;return n}},onSuccess:()=>s.invalidateQueries({queryKey:["vendors"]})})}function JTt(){const s=ls();return Nt({mutationFn:async t=>{const{error:n}=await V.from("vendors").delete().eq("id",t);if(n)throw n},onSuccess:()=>s.invalidateQueries({queryKey:["vendors"]})})}function k4s(){const s=ai(),t=ls();return Nt({mutationFn:async({vendorId:n,isVisible:r})=>{if(!s)throw new Error("No user");const{data:a}=await V.from("agent_vendor_selections").select("id").eq("agent_user_id",s).eq("vendor_id",n).maybeSingle();if(a){const{error:i}=await V.from("agent_vendor_selections").update({is_visible:r}).eq("id",a.id);if(i)throw i}else{const{error:i}=await V.from("agent_vendor_selections").insert({agent_user_id:s,vendor_id:n,is_visible:r});if(i)throw i}},onSuccess:()=>t.invalidateQueries({queryKey:["vendors"]})})}function eMt(s){return pt({queryKey:["portal-vendors",s==null?void 0:s.id,s==null?void 0:s.owner_user_id],queryFn:async()=>{if(!(s!=null&&s.id)||!(s!=null&&s.owner_user_id))return[];const t=s.owner_user_id,{data:n}=await V.from("profiles").select("brokerage_id").eq("id",t).maybeSingle(),r=n==null?void 0:n.brokerage_id,a=V.from("vendors").select("*").eq("is_active",!0),i=r?a.or(`and(owner_type.eq.agent,owner_user_id.eq.${t}),and(owner_type.eq.brokerage,owner_brokerage_id.eq.${r})`):a.eq("owner_type","agent").eq("owner_user_id",t),[{data:l,error:o},{data:c},{data:d}]=await Promise.all([i.order("sort_order",{ascending:!0}).order("name",{ascending:!0}),V.from("agent_vendor_selections").select("vendor_id, display_order, is_visible").eq("agent_user_id",t),V.from("portal_vendor_overrides").select("vendor_id, is_visible").eq("portal_id",s.id)]);if(o)throw o;const u=new Map;(c||[]).forEach(p=>u.set(p.vendor_id,{display_order:p.display_order,is_visible:p.is_visible}));const h=new Map;return(d||[]).forEach(p=>h.set(p.vendor_id,p.is_visible)),(l||[]).filter(p=>{if(h.get(p.id)===!1)return!1;const g=u.get(p.id);return!(g&&g.is_visible===!1&&!p.is_required)}).map(p=>{var g;return{...p,display_order:((g=u.get(p.id))==null?void 0:g.display_order)??p.sort_order??0}}).sort((p,g)=>(p.display_order||0)-(g.display_order||0))},enabled:!!(s!=null&&s.id)&&!!(s!=null&&s.owner_user_id)})}async function Cct(s){try{await V.from("vendor_clicks").insert({vendor_id:s.vendorId,portal_id:s.portalId||null,agent_user_id:s.agentUserId||null,action_taken:s.actionTaken||null,user_agent:typeof navigator<"u"?navigator.userAgent.slice(0,500):null})}catch(t){console.warn("vendor click track failed",t)}}function tMt(s,t){return pt({queryKey:["vendor-clicks",s,t],queryFn:async()=>{if(!t)return{};const{data:n}=await V.from("vendors").select("id").eq(s==="agent"?"owner_user_id":"owner_brokerage_id",t).eq("owner_type",s),r=(n||[]).map(l=>l.id);if(r.length===0)return{};const{data:a}=await V.from("vendor_clicks").select("vendor_id").in("vendor_id",r),i={};return(a||[]).forEach(l=>{i[l.vendor_id]=(i[l.vendor_id]||0)+1}),i},enabled:!!t})}function sMt({portalId:s,ownerUserId:t,currentStage:n,brandingColor:r,layout:a="list"}){const{data:i=[],isLoading:l}=eMt({id:s,owner_user_id:t});if(l||i.length===0)return null;const o=i.filter(_=>!_.stage_filter||_.stage_filter.length===0||!n?!0:_.stage_filter.includes(n));if(o.length===0)return null;const c=r||"#406E71",d=(_,j)=>{switch(j){case"book":return _.booking_url;case"website":return _.website;case"call":return _.phone?`tel:${_.phone.replace(/[^\d+]/g,"")}`:null;case"email":case"quote":return _.email?`mailto:${_.email}`:null}},u=_=>{const j=d(_,_.action_type);Cct({vendorId:_.id,portalId:s,agentUserId:t,actionTaken:_.action_type}),j&&window.open(j,_.action_type==="call"||_.action_type==="email"||_.action_type==="quote"?"_self":"_blank")},h=_=>{const j=d(_,_.action_type);return[{action:"website",label:"Website",icon:e.jsx(kc,{className:"w-3.5 h-3.5"})},{action:"email",label:"Email",icon:e.jsx(pn,{className:"w-3.5 h-3.5"})},{action:"call",label:"Call",icon:e.jsx(ka,{className:"w-3.5 h-3.5"})},{action:"book",label:"Book",icon:e.jsx(ha,{className:"w-3.5 h-3.5"})}].filter(A=>A.action!==_.action_type).map(A=>{const M=d(_,A.action);return!M||M===j?null:e.jsxs("button",{onClick:()=>{Cct({vendorId:_.id,portalId:s,agentUserId:t,actionTaken:A.action}),window.open(M,A.action==="call"||A.action==="email"?"_self":"_blank")},className:"inline-flex items-center gap-1 text-slate-500 hover:text-slate-700 hover:underline",title:A.label,children:[A.icon,e.jsx("span",{className:"text-xs",children:A.label})]},A.action)}).filter(Boolean)},m=_=>{switch(_.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"}},p=_=>{switch(_.action_type){case"book":return e.jsx(ha,{className:"w-3.5 h-3.5"});case"call":return e.jsx(ka,{className:"w-3.5 h-3.5"});case"email":case"quote":return e.jsx(pn,{className:"w-3.5 h-3.5"});case"website":return e.jsx(kc,{className:"w-3.5 h-3.5"})}},g=_=>{var j;return((j=Zq.find(C=>C.value===_))==null?void 0:j.label)||_},x=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(kn,{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"})]})]}),y=o.some(_=>_.disclosure_text)&&e.jsx("div",{className:"mt-4 pt-3 border-t border-slate-100 space-y-1",children:o.filter(_=>_.disclosure_text).map(_=>e.jsxs("p",{className:"text-[10px] text-slate-400",children:[e.jsxs("span",{className:"font-medium",children:[_.company||_.name,":"]})," ",_.disclosure_text]},_.id))});if(a==="grid")return e.jsxs(we,{className:"p-5 sm:p-6 rounded-2xl border-slate-200/80 shadow-sm bg-white/70 backdrop-blur",children:[x,e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3",children:o.map(_=>e.jsxs("div",{className:"group flex flex-col p-4 rounded-xl border border-slate-200/70 bg-white hover:shadow-md hover:-translate-y-0.5 transition-all",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-12 h-12 rounded-lg bg-slate-50 border border-slate-200 flex items-center justify-center overflow-hidden shrink-0",children:_.logo_url?e.jsx("img",{src:_.logo_url,alt:_.name,className:"w-full h-full object-cover"}):e.jsx("span",{className:"text-base font-semibold text-slate-500",children:(_.company||_.name).charAt(0)})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"font-semibold text-sm text-slate-800 truncate",children:_.company||_.name}),_.company&&_.name&&e.jsx("p",{className:"text-xs text-slate-500 truncate",children:_.name}),e.jsx("span",{className:"inline-block mt-1 text-[10px] font-medium px-1.5 py-0.5 rounded",style:{backgroundColor:`${c}12`,color:c},children:g(_.category)})]})]}),_.description&&e.jsx("p",{className:"text-xs text-slate-500 mt-3 line-clamp-2",children:_.description}),e.jsxs("div",{className:"mt-auto pt-4 flex flex-col gap-2",children:[e.jsxs($,{size:"sm",onClick:()=>u(_),style:{backgroundColor:c},className:"text-white hover:opacity-90 w-full",children:[p(_),e.jsx("span",{className:"ml-1.5 text-xs",children:m(_)})]}),h(_).length>0&&e.jsx("div",{className:"flex flex-wrap items-center justify-center gap-3",children:h(_)})]})]},_.id))}),y]});const v=o.reduce((_,j)=>((_[j.category]=_[j.category]||[]).push(j),_),{});return e.jsxs(we,{className:"p-5 rounded-2xl border-slate-200/80 shadow-sm",children:[x,e.jsx("div",{className:"space-y-4",children:Object.entries(v).map(([_,j])=>e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] uppercase tracking-wide text-slate-400 font-medium mb-2",children:g(_)}),e.jsx("div",{className:"space-y-2",children:j.map(C=>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:C.logo_url?e.jsx("img",{src:C.logo_url,alt:C.name,className:"w-full h-full object-cover"}):e.jsx("span",{className:"text-sm font-semibold text-slate-500",children:C.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:C.company||C.name}),C.company&&C.name&&e.jsx("p",{className:"text-xs text-slate-500 truncate",children:C.name}),C.description&&e.jsx("p",{className:"text-xs text-slate-500 truncate mt-0.5",children:C.description})]}),e.jsxs($,{size:"sm",onClick:()=>u(C),style:{backgroundColor:c},className:"text-white hover:opacity-90 shrink-0",children:[p(C),e.jsx("span",{className:"ml-1.5 text-xs",children:m(C)})]})]},C.id))})]},_))}),y]})}function S4s(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 C4s(s){if(!s)return null;const t=s.match(/(?:youtube\.com\/(?:watch\?v=|embed\/)|youtu\.be\/)([\w-]+)/);if(t)return`https://www.youtube.com/embed/${t[1]}`;const n=s.match(/loom\.com\/share\/([\w-]+)/);return n?`https://www.loom.com/embed/${n[1]}`:(s.match(/\.(mp4|webm|mov)(\?|$)/i),s)}function nMt({portalId:s,portalSlug:t,ownerUserId:n,rewardText:r,ctaHeadline:a,agentName:i,clientName:l,reviewUrl:o,hubVideoUrl:c}){const[d,u]=k.useState(!1),h=k.useRef(!1),m=S4s(t);k.useEffect(()=>{h.current||(h.current=!0,V.from("portal_referral_clicks").insert({portal_id:s,owner_user_id:n,click_type:"card_view",user_agent:navigator.userAgent.slice(0,500)}).then(()=>{}))},[s,n]);const p=async M=>{await V.from("portal_referral_clicks").insert({portal_id:s,owner_user_id:n,click_type:M,user_agent:navigator.userAgent.slice(0,500)})},g=()=>`${l?`Hey, it's ${l}!`:"Hey!"} I just had an amazing experience working with ${i||"my real estate agent"} on my home. If you or someone you know is thinking about buying or selling, here's their referral link: ${m}`,x=async()=>{await navigator.clipboard.writeText(m),u(!0),p("copy_link"),setTimeout(()=>u(!1),2e3)},y=()=>{p("share_sms");const M=encodeURIComponent(g());window.location.href=`sms:?&body=${M}`},v=()=>{p("share_email");const M=encodeURIComponent("A referral you'll thank me for"),I=encodeURIComponent(g());window.location.href=`mailto:?subject=${M}&body=${I}`},_=()=>{p("open_form"),window.open(m,"_blank")},j=a||"Know someone buying or selling?",C=c?C4s(c):null,A=C==null?void 0:C.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."})]}),C&&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(kn,{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:A?e.jsx("video",{src:C,controls:!0,className:"w-full h-full",playsInline:!0}):e.jsx("iframe",{src:C,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(Zo,{className:"w-3 h-3"}),"Referral Program"]}),e.jsx("h3",{className:"text-xl font-bold leading-tight mb-2 font-serif",children:j}),r&&e.jsxs("p",{className:"text-sm text-white/85 mb-1",children:[e.jsx("span",{className:"font-semibold text-white",children:"Your reward:"})," ",r]}),e.jsxs("p",{className:"text-sm text-white/70 mb-5 leading-relaxed",children:["The biggest compliment you can give ",i||"us"," is sending a friend or family member."]}),e.jsxs("button",{onClick:_,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(xi,{className:"w-4 h-4"})]}),e.jsxs("div",{className:"mt-4 grid grid-cols-3 gap-2",children:[e.jsxs("button",{onClick:y,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(Vu,{className:"w-3.5 h-3.5"}),"Text"]}),e.jsxs("button",{onClick:v,className:"flex items-center justify-center gap-1.5 bg-white/10 hover:bg-white/20 backdrop-blur-sm rounded-lg py-2.5 text-xs font-medium transition-colors",children:[e.jsx(pn,{className:"w-3.5 h-3.5"}),"Email"]}),e.jsxs("button",{onClick:x,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(ma,{className:"w-3.5 h-3.5"}):e.jsx(Da,{className:"w-3.5 h-3.5"}),d?"Copied":"Copy"]})]})]})]}),o&&e.jsx("a",{href:o,target:"_blank",rel:"noopener noreferrer",onClick:()=>p("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(xi,{className:"w-4 h-4 text-slate-400"})]})})]})}function A4s(s){return s==="buy-side"?"Home Search in Progress":s==="listing"?"Your Home Is On The Market":"Active Phase"}function E4s(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 T4s={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. 🎉"}},rMt=["Lead","Consultation","Agreement Signed","Active","Under Contract","Closing","Closed Won"];function mAe(s){return rMt.map(t=>{if(t==="Active")return{key:"Active",label:A4s(s),description:E4s(s)};const n=T4s[t];return{key:t,label:n.label,description:n.description}})}function NSe(s){if(!s)return 0;const t=rMt.indexOf(s);return t>=0?t:0}function M4s({portal:s,linkedPortal:t,activePortal:n,activeTab:r,onTabChange:a,agentProfile:i,branding:l,updates:o,documents:c}){var Y,se,ee;const d=(l==null?void 0:l.cover_photo_url)||null,u=(l==null?void 0:l.logo_url)||null,h=(l==null?void 0:l.tagline)||"Your Real Estate Concierge",m=n==null?void 0:n.deal_pipeline,p=m==null?void 0:m.deal_pipeline_stages,g=p==null?void 0:p.is_won_stage,x=m==null?void 0:m.deal_type,y=n==null?void 0:n.stage_mapping;let v=mAe(x);y&&y.length>0&&(v=y.map((oe,me)=>{var Q,te;return{key:`custom-${me}`,label:oe.label||((Q=v[me])==null?void 0:Q.label)||`Stage ${me+1}`,description:oe.description||((te=v[me])==null?void 0:te.description)||"",video_url:oe.video_url||void 0}}));const _=y&&y.length>0?Math.min(NSe(p==null?void 0:p.name),v.length-1):NSe(p==null?void 0:p.name),j=v[_],C=j==null?void 0:j.video_url,A=g&&n.show_post_close_tips!==!1&&n.referral_enabled!==!1,M=m!=null&&m.property_address?`${m.property_address}, ${m.city||""}, ${m.state||""}`.replace(/,\s*,/g,",").replace(/,\s*$/,""):null,I=!!t,P=(Y=s==null?void 0:s.deal_pipeline)==null?void 0:Y.deal_type,R=(se=t==null?void 0:t.deal_pipeline)==null?void 0:se.deal_type,O=oe=>oe==="listing"?"Your Sale":oe==="buy-side"?"Your Purchase":"Transaction",B=v.length>1?Math.round((_+1)/v.length*100):0,{data:U=[]}=eMt({id:n==null?void 0:n.id,owner_user_id:n==null?void 0:n.owner_user_id}),G=U.some(oe=>!oe.stage_filter||oe.stage_filter.length===0||!(p!=null&&p.name)?!0:oe.stage_filter.includes(p.name)),H=()=>{var oe;(oe=document.getElementById("trusted-vendors"))==null||oe.scrollIntoView({behavior:"smooth",block:"start"})};return e.jsxs("div",{className:"min-h-screen relative",style:{background:"var(--portal-gradient-noir)"},children:[e.jsx("div",{className:"pointer-events-none absolute inset-x-0 top-0 h-[600px] opacity-70",style:{background:"radial-gradient(ellipse 70% 100% at 50% 0%, hsl(var(--portal-gold) / 0.08), transparent 60%)"}}),e.jsxs("div",{className:"relative max-w-[1400px] mx-auto px-8 py-8",children:[e.jsxs(_r.div,{initial:{opacity:0,y:-6},animate:{opacity:1,y:0},transition:{duration:.4},className:"flex items-center justify-between mb-8",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[u?e.jsx("div",{className:"rounded-lg px-3 py-1.5",style:{background:"hsl(0 0% 100% / 0.04)",border:"1px solid hsl(var(--portal-gold) / 0.2)"},children:e.jsx("img",{src:u,alt:"Brand",className:"h-8 max-w-[140px] object-contain"})}):e.jsx("div",{className:"w-10 h-10 rounded-lg flex items-center justify-center portal-serif text-xl",style:{background:"var(--portal-gradient-gold)",color:"hsl(var(--portal-bg))"},children:"✦"}),e.jsxs("div",{children:[e.jsx("p",{className:"portal-eyebrow",children:"Private Client Portal"}),e.jsx("p",{className:"portal-serif mt-0.5",style:{fontSize:"1.1rem",color:"hsl(var(--portal-ink))"},children:n!=null&&n.client_name?`Welcome, ${n.client_name.split(" ")[0]}`:"Your transaction"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-[10px] tracking-[0.22em] uppercase",style:{color:"hsl(var(--portal-ink-dim))"},children:[e.jsx(Ng,{className:"w-3 h-3",style:{color:"hsl(var(--portal-gold))"}}),"Secure & Encrypted"]})]}),e.jsxs(_r.div,{initial:{opacity:0,y:12},animate:{opacity:1,y:0},transition:{duration:.6,ease:"easeOut"},className:"relative overflow-hidden rounded-3xl mb-8",style:{minHeight:380,border:"1px solid hsl(var(--portal-gold) / 0.25)",boxShadow:"var(--portal-shadow-luxe)"},children:[d?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"absolute inset-0",style:{backgroundImage:`url(${d})`,backgroundSize:"cover",backgroundPosition:"center",filter:"var(--portal-hero-filter)"}}),e.jsx("div",{className:"absolute inset-0",style:{background:"var(--portal-hero-scrim)"}})]}):e.jsx("div",{className:"absolute inset-0",style:{background:"var(--portal-hero-fallback)"}}),e.jsx("div",{className:"absolute top-0 left-0 right-0 h-[1px]",style:{background:"linear-gradient(90deg, transparent, hsl(var(--portal-gold) / 0.6), transparent)"}}),e.jsxs("div",{className:"relative grid grid-cols-3 gap-8 p-12",children:[e.jsxs("div",{className:"col-span-2 flex flex-col justify-end",children:[e.jsxs("div",{className:"inline-flex items-center gap-1.5 rounded-full px-3 py-1 text-[10px] tracking-[0.22em] uppercase mb-6 self-start",style:{background:"hsl(0 0% 0% / 0.28)",backdropFilter:"blur(6px)",border:"1px solid var(--portal-hero-accent)",color:"var(--portal-hero-accent)"},children:[e.jsx(ua,{className:"w-3 h-3"}),x==="listing"?"Sale":x==="buy-side"?"Purchase":"Transaction",g&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"opacity-50 mx-1",children:"·"}),"Complete"]})]}),e.jsx("h1",{className:"portal-serif leading-[0.95] mb-4",style:{fontSize:"4.5rem",color:"var(--portal-hero-ink)",textShadow:"var(--portal-hero-text-shadow)"},children:(m==null?void 0:m.deal_name)||"Your Transaction"}),e.jsx("div",{className:"portal-hairline w-32 mb-5"}),M&&e.jsxs("div",{className:"flex items-center gap-2",style:{color:"var(--portal-hero-ink-muted)",textShadow:"var(--portal-hero-text-shadow)"},children:[e.jsx(Si,{className:"w-4 h-4",style:{color:"var(--portal-hero-accent)"}}),e.jsx("span",{className:"text-base",children:M})]}),(n==null?void 0:n.welcome_message)&&e.jsxs("p",{className:"mt-6 portal-serif italic leading-relaxed max-w-2xl",style:{color:"var(--portal-hero-ink-muted)",fontSize:"1.15rem",textShadow:"var(--portal-hero-text-shadow)"},children:["“",n.welcome_message,"”"]})]}),e.jsxs("div",{className:"flex flex-col items-center justify-center",children:[e.jsx(P4s,{pct:B}),e.jsx("p",{className:"portal-eyebrow mt-4",style:{color:"var(--portal-hero-accent)"},children:"Journey Progress"}),e.jsxs("p",{className:"portal-serif mt-1",style:{fontSize:"1.1rem",color:"var(--portal-hero-ink)",textShadow:"var(--portal-hero-text-shadow)"},children:["Stage ",_+1," of ",v.length]})]})]}),e.jsx("div",{className:"absolute bottom-0 left-0 right-0 h-[1px]",style:{background:"linear-gradient(90deg, transparent, hsl(var(--portal-gold) / 0.4), transparent)"}})]}),I&&e.jsx("div",{className:"inline-flex gap-1 rounded-xl p-1 mb-8",style:{background:"hsl(var(--portal-surface))",border:"1px solid hsl(var(--portal-gold) / 0.15)"},children:["primary","linked"].map(oe=>{const me=oe==="primary"?P:R,Q=r===oe;return e.jsx("button",{onClick:()=>a(oe),className:"portal-serif px-5 py-2 rounded-lg transition-all",style:{fontSize:"1rem",background:Q?"hsl(var(--portal-surface-3))":"transparent",color:Q?"hsl(var(--portal-gold))":"hsl(var(--portal-ink-muted))",borderBottom:Q?"1px solid hsl(var(--portal-gold))":"1px solid transparent"},children:O(me)},oe)})}),e.jsxs(_r.div,{initial:"hidden",animate:"show",variants:{hidden:{},show:{transition:{staggerChildren:.06}}},className:"grid grid-cols-12 gap-5",children:[e.jsx("aside",{className:"col-span-3 space-y-5",children:e.jsxs("div",{className:"sticky top-6 space-y-5",children:[e.jsxs(zA,{children:[e.jsxs("div",{className:"text-center pt-2 pb-1",children:[i!=null&&i.avatar_url?e.jsx("div",{className:"w-24 h-24 mx-auto relative",children:e.jsx("div",{className:"absolute inset-0 rounded-full",style:{background:"var(--portal-gradient-gold)",padding:"2px"},children:e.jsx("img",{src:i.avatar_url,alt:i.name,className:"w-full h-full rounded-full object-cover",style:{background:"hsl(var(--portal-surface))"}})})}):e.jsx("div",{className:"w-24 h-24 rounded-full mx-auto flex items-center justify-center portal-serif text-3xl",style:{background:"hsl(var(--portal-surface-2))",border:"1px solid hsl(var(--portal-gold) / 0.4)",color:"hsl(var(--portal-gold))"},children:((ee=i==null?void 0:i.name)==null?void 0:ee.charAt(0))||"?"}),e.jsx("h3",{className:"mt-4 portal-serif",style:{fontSize:"1.5rem",color:"hsl(var(--portal-ink))"},children:i==null?void 0:i.name}),e.jsx("div",{className:"portal-hairline w-12 mx-auto my-2"}),e.jsx("p",{className:"text-[10px] tracking-[0.22em] uppercase",style:{color:"hsl(var(--portal-ink-dim))"},children:h})]}),e.jsxs("div",{className:"mt-5 space-y-2",children:[(i==null?void 0:i.phone)&&e.jsx(HIe,{href:`tel:${i.phone}`,icon:ka,label:"Call",sub:i.phone}),(i==null?void 0:i.phone)&&e.jsx(HIe,{href:`sms:${i.phone}`,icon:Vu,label:"Text message"}),(i==null?void 0:i.email)&&e.jsx(HIe,{href:`mailto:${i.email}`,icon:pn,label:"Email",sub:i.email})]})]}),e.jsxs(zA,{children:[e.jsx("p",{className:"portal-eyebrow mb-4",children:"At a Glance"}),e.jsxs("div",{className:"space-y-4",children:[(m==null?void 0:m.target_close_date)&&e.jsx(GIe,{icon:ha,label:"Target close",value:Act(m.target_close_date)}),(m==null?void 0:m.contract_date)&&e.jsx(GIe,{icon:sa,label:"Under contract",value:Act(m.contract_date)}),e.jsx(GIe,{icon:Go,label:"Progress",value:`${B}%`})]})]})]})}),e.jsxs("main",{className:"col-span-6 space-y-5",children:[A&&e.jsx(nMt,{portalId:n.id,portalSlug:n.slug,ownerUserId:n.owner_user_id,rewardText:n.referral_reward_text,ctaHeadline:n.referral_cta_headline,agentName:i==null?void 0:i.name,clientName:n.client_name,reviewUrl:n.review_url,hubVideoUrl:n.homeowner_hub_video_url}),e.jsx(WTt,{targetCloseDate:m==null?void 0:m.target_close_date,actualCloseDate:m==null?void 0:m.actual_close_date,clientName:n.client_name}),j&&e.jsx(zA,{children:e.jsx(YTt,{currentStage:j,nextStepText:n.next_step_text,nextStepVideoUrl:C||n.next_step_video_url})}),e.jsx(zA,{children:e.jsx(KTt,{journeyStages:v,currentIndex:_})}),o&&o.length>0&&e.jsx(zA,{children:e.jsx(QTt,{updates:o})})]}),e.jsxs("aside",{className:"col-span-3 space-y-5",children:[e.jsx(zA,{children:e.jsx(ZTt,{deal:m,portal:n})}),c&&c.length>0&&e.jsx(zA,{children:e.jsx(XTt,{documents:c})}),G&&e.jsx(zA,{children:e.jsxs("button",{onClick:H,className:"w-full flex items-center gap-3 rounded-xl px-3 py-3 transition-all text-left group",style:{background:"hsl(var(--portal-gold) / 0.06)",border:"1px solid hsl(var(--portal-gold) / 0.2)"},onMouseEnter:oe=>{oe.currentTarget.style.background="hsl(var(--portal-gold) / 0.12)"},onMouseLeave:oe=>{oe.currentTarget.style.background="hsl(var(--portal-gold) / 0.06)"},children:[e.jsx("div",{className:"w-10 h-10 rounded-lg flex items-center justify-center shrink-0",style:{background:"hsl(var(--portal-gold) / 0.15)",color:"hsl(var(--portal-gold))"},children:e.jsx(uB,{className:"w-4 h-4"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"portal-serif",style:{fontSize:"1.05rem",color:"hsl(var(--portal-ink))"},children:"Trusted Vendors"}),e.jsx("p",{className:"text-[10px] tracking-[0.2em] uppercase mt-0.5",style:{color:"hsl(var(--portal-ink-dim))"},children:"My hand-picked network"})]}),e.jsx(Go,{className:"w-4 h-4",style:{color:"hsl(var(--portal-gold))"}})]})}),e.jsxs("div",{className:"text-center pt-2 space-y-2",children:[e.jsx("div",{className:"portal-hairline w-12 mx-auto"}),e.jsx("p",{className:"text-[10px] tracking-[0.25em] uppercase",style:{color:"hsl(var(--portal-ink-dim))"},children:"Powered by ReLevelUp"})]})]})]}),(n==null?void 0:n.id)&&(n==null?void 0:n.owner_user_id)&&e.jsx("div",{id:"trusted-vendors",className:"mt-8 scroll-mt-10",children:e.jsx(sMt,{portalId:n.id,ownerUserId:n.owner_user_id,currentStage:p==null?void 0:p.name,brandingColor:"hsl(var(--portal-gold))",layout:"grid"})})]})]})}function zA({children:s}){return e.jsx(_r.div,{variants:{hidden:{opacity:0,y:10},show:{opacity:1,y:0,transition:{duration:.45,ease:"easeOut"}}},className:"portal-tile p-6",children:s})}function HIe({href:s,icon:t,label:n,sub:r}){return e.jsxs("a",{href:s,className:"flex items-center gap-3 rounded-xl px-3 py-2.5 transition-all",style:{background:"hsl(var(--portal-gold) / 0.05)",border:"1px solid hsl(var(--portal-gold) / 0.12)"},onMouseEnter:a=>{a.currentTarget.style.background="hsl(var(--portal-gold) / 0.1)",a.currentTarget.style.borderColor="hsl(var(--portal-gold) / 0.3)"},onMouseLeave:a=>{a.currentTarget.style.background="hsl(var(--portal-gold) / 0.05)",a.currentTarget.style.borderColor="hsl(var(--portal-gold) / 0.12)"},children:[e.jsx("div",{className:"w-9 h-9 rounded-lg flex items-center justify-center shrink-0",style:{background:"hsl(var(--portal-gold) / 0.15)",color:"hsl(var(--portal-gold))"},children:e.jsx(t,{className:"w-4 h-4"})}),e.jsxs("div",{className:"min-w-0 text-left",children:[e.jsx("p",{className:"text-sm portal-serif",style:{color:"hsl(var(--portal-ink))",fontSize:"1rem"},children:n}),r&&e.jsx("p",{className:"text-[10px] tracking-[0.15em] uppercase truncate mt-0.5",style:{color:"hsl(var(--portal-ink-dim))"},children:r})]})]})}function GIe({icon:s,label:t,value:n}){return e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-8 h-8 rounded-lg flex items-center justify-center shrink-0",style:{background:"hsl(var(--portal-gold) / 0.1)",color:"hsl(var(--portal-gold))"},children:e.jsx(s,{className:"w-4 h-4"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-[10px] tracking-[0.2em] uppercase",style:{color:"hsl(var(--portal-ink-dim))"},children:t}),e.jsx("p",{className:"portal-serif truncate",style:{fontSize:"1.05rem",color:"hsl(var(--portal-ink))"},children:n})]})]})}function P4s({pct:s}){const a=2*Math.PI*78,i=a-s/100*a;return e.jsxs("div",{className:"relative",style:{width:170,height:170},children:[e.jsxs("svg",{width:170,height:170,className:"-rotate-90",children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"portal-progress-gold",x1:"0%",y1:"0%",x2:"100%",y2:"100%",children:[e.jsx("stop",{offset:"0%",stopColor:"var(--portal-hero-accent)"}),e.jsx("stop",{offset:"100%",stopColor:"var(--portal-hero-ink)"})]})}),e.jsx("circle",{cx:170/2,cy:170/2,r:78,stroke:"hsl(0 0% 100% / 0.22)",strokeWidth:2,fill:"none"}),e.jsx(_r.circle,{cx:170/2,cy:170/2,r:78,stroke:"url(#portal-progress-gold)",strokeWidth:3,strokeLinecap:"round",fill:"none",initial:{strokeDashoffset:a},animate:{strokeDashoffset:i},transition:{duration:1.4,ease:"easeOut"},strokeDasharray:a,style:{filter:"drop-shadow(0 0 6px hsl(0 0% 0% / 0.45))"}})]}),e.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center",children:[e.jsx("span",{className:"portal-serif tabular-nums leading-none",style:{fontSize:"3rem",color:"var(--portal-hero-ink)",textShadow:"var(--portal-hero-text-shadow)"},children:s}),e.jsx("span",{className:"text-[10px] tracking-[0.25em] uppercase mt-1",style:{color:"var(--portal-hero-ink-dim)",textShadow:"var(--portal-hero-text-shadow)"},children:"percent"})]})]})}function Act(s){const t=s.split(/[-/T]/),n=new Date(Number(t[0]),Number(t[1])-1,Number(t[2]));return new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric",year:"numeric",timeZone:"America/New_York"}).format(n)}function I4s({portal:s,dealData:t,agentProfile:n,customQuestions:r,deviceFingerprint:a,onComplete:i}){var y,v;const[l,o]=k.useState({first_name:((y=s.client_name)==null?void 0:y.split(" ")[0])||"",last_name:((v=s.client_name)==null?void 0:v.split(" ").slice(1).join(" "))||"",email:s.client_email||"",phone:s.client_phone||"",preferred_contact_method:"email",client_role:"buyer",notes:"",spouse_first_name:"",spouse_last_name:"",spouse_email:"",spouse_phone:""}),[c,d]=k.useState({}),[u,h]=k.useState(!1),m=Nt({mutationFn:async()=>{const{error:_}=await V.from("portal_onboarding_submissions").insert({portal_id:s.id,first_name:l.first_name,last_name:l.last_name||null,email:l.email||null,phone:l.phone||null,preferred_contact_method:l.preferred_contact_method,client_role:l.client_role,notes:l.notes||null,device_fingerprint:a,custom_answers:Object.keys(c).length>0?c:null,spouse_first_name:u&&l.spouse_first_name||null,spouse_last_name:u&&l.spouse_last_name||null,spouse_email:u&&l.spouse_email||null,spouse_phone:u&&l.spouse_phone||null});if(_)throw _},onSuccess:i,onError:_=>{console.error("[PortalOnboarding] Submit failed:",_),ae.error("Something went wrong. Please try again.")}}),p=t!=null&&t.property_address?`${t.property_address}, ${t.city||""}, ${t.state||""}`:null,g="mt-1 rounded-xl bg-white text-slate-900 placeholder:text-slate-400 border-slate-200 focus-visible:ring-slate-400",x="mt-1 w-full rounded-xl border border-slate-200 bg-white text-slate-900 placeholder:text-slate-400 px-3 py-2 text-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-slate-400";return e.jsx("div",{className:"max-w-md mx-auto px-4 py-10",children:e.jsxs("div",{className:"bg-white rounded-2xl shadow-xl ring-1 ring-slate-200 p-6 sm:p-8",children:[e.jsxs("div",{className:"text-center mb-8",children:[(n==null?void 0:n.avatar_url)&&e.jsx("img",{src:n.avatar_url,alt:n.name,className:"w-16 h-16 rounded-full border-2 border-slate-200 mx-auto mb-3 object-cover"}),e.jsx("h1",{className:"text-2xl font-bold text-slate-900",children:"Welcome to Your Portal"}),p&&e.jsxs("div",{className:"flex items-center justify-center gap-1 text-slate-500 text-sm mt-1",children:[e.jsx(Si,{className:"w-3.5 h-3.5"}),e.jsx("span",{children:p.replace(/,\s*,/g,",").replace(/,\s*$/,"")})]}),e.jsx("p",{className:"text-sm text-slate-600 mt-2",children:"Please fill in your details to access your transaction portal."})]}),e.jsxs("form",{onSubmit:_=>{_.preventDefault(),m.mutate()},className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(re,{className:"text-xs font-medium text-slate-700",children:"First Name *"}),e.jsx(be,{required:!0,value:l.first_name,onChange:_=>o(j=>({...j,first_name:_.target.value})),className:g,placeholder:"John"})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs font-medium text-slate-700",children:"Last Name"}),e.jsx(be,{value:l.last_name,onChange:_=>o(j=>({...j,last_name:_.target.value})),className:g,placeholder:"Doe"})]})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs font-medium text-slate-700",children:"Email"}),e.jsx(be,{type:"email",value:l.email,onChange:_=>o(j=>({...j,email:_.target.value})),className:g,placeholder:"john@example.com"})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs font-medium text-slate-700",children:"Phone"}),e.jsx(be,{type:"tel",value:l.phone,onChange:_=>o(j=>({...j,phone:_.target.value})),className:g,placeholder:"(555) 123-4567"})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs font-medium text-slate-700",children:"Preferred Contact Method"}),e.jsx("div",{className:"flex gap-2 mt-1.5",children:[{value:"email",label:"Email"},{value:"call",label:"Phone"},{value:"text",label:"Text"}].map(_=>e.jsx("button",{type:"button",onClick:()=>o(j=>({...j,preferred_contact_method:_.value})),className:`px-3.5 py-1.5 rounded-full text-xs font-medium border transition-colors ${l.preferred_contact_method===_.value?"bg-slate-800 text-white border-slate-800":"bg-white text-slate-600 border-slate-200 hover:border-slate-300"}`,children:_.label},_.value))})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs font-medium text-slate-700",children:"Your Role"}),e.jsx("div",{className:"flex gap-2 mt-1.5",children:["buyer","seller","both"].map(_=>e.jsx("button",{type:"button",onClick:()=>o(j=>({...j,client_role:_})),className:`px-3.5 py-1.5 rounded-full text-xs font-medium border transition-colors ${l.client_role===_?"bg-slate-800 text-white border-slate-800":"bg-white text-slate-600 border-slate-200 hover:border-slate-300"}`,children:_.charAt(0).toUpperCase()+_.slice(1)},_))})]}),r.map(_=>e.jsxs("div",{children:[e.jsxs(re,{className:"text-xs font-medium text-slate-700",children:[_.question_text," ",_.is_required&&"*"]}),_.field_type==="text"&&e.jsx(be,{required:_.is_required,value:c[_.id]||"",onChange:j=>d(C=>({...C,[_.id]:j.target.value})),className:g}),_.field_type==="textarea"&&e.jsx("textarea",{required:_.is_required,value:c[_.id]||"",onChange:j=>d(C=>({...C,[_.id]:j.target.value})),className:`${x} min-h-[80px]`}),_.field_type==="dropdown"&&e.jsxs("select",{required:_.is_required,value:c[_.id]||"",onChange:j=>d(C=>({...C,[_.id]:j.target.value})),className:`${x} h-10`,children:[e.jsx("option",{value:"",children:"Select..."}),(_.options||[]).map(j=>e.jsx("option",{value:j,children:j},j))]}),_.field_type==="toggle"&&e.jsx("div",{className:"mt-1.5 flex gap-2",children:["Yes","No"].map(j=>e.jsx("button",{type:"button",onClick:()=>d(C=>({...C,[_.id]:j})),className:`px-3.5 py-1.5 rounded-full text-xs font-medium border transition-colors ${c[_.id]===j?"bg-slate-800 text-white border-slate-800":"bg-white text-slate-600 border-slate-200"}`,children:j},j))})]},_.id)),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs font-medium text-slate-700",children:"Notes for your agent"}),e.jsx("textarea",{value:l.notes,onChange:_=>o(j=>({...j,notes:_.target.value})),className:`${x} min-h-[60px]`,placeholder:"Anything you'd like your agent to know..."})]}),s.allow_spouse&&e.jsxs("div",{children:[e.jsx("button",{type:"button",onClick:()=>h(!u),className:"text-sm text-blue-600 hover:text-blue-700 font-medium",children:u?"− Remove spouse/partner":"+ Add spouse/partner"}),u&&e.jsxs("div",{className:"mt-3 p-4 bg-slate-50 rounded-xl border border-slate-200 space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(re,{className:"text-xs font-medium text-slate-700",children:"First Name"}),e.jsx(be,{value:l.spouse_first_name,onChange:_=>o(j=>({...j,spouse_first_name:_.target.value})),className:g})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs font-medium text-slate-700",children:"Last Name"}),e.jsx(be,{value:l.spouse_last_name,onChange:_=>o(j=>({...j,spouse_last_name:_.target.value})),className:g})]})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs font-medium text-slate-700",children:"Email"}),e.jsx(be,{type:"email",value:l.spouse_email,onChange:_=>o(j=>({...j,spouse_email:_.target.value})),className:g})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs font-medium text-slate-700",children:"Phone"}),e.jsx(be,{type:"tel",value:l.spouse_phone,onChange:_=>o(j=>({...j,spouse_phone:_.target.value})),className:g})]})]})]}),e.jsx($,{type:"submit",disabled:m.isPending||!l.first_name,className:"w-full h-12 rounded-full text-sm font-semibold bg-slate-900 hover:bg-slate-800",children:m.isPending?"Submitting...":"Access My Portal"})]})]})})}function L4s(s,t){const n=(r,a)=>a!=null&&a!==""?a:r!=null&&r!==""?r:null;return{logo_url:n(s==null?void 0:s.logo_url,t==null?void 0:t.logo_url),cover_photo_url:n(s==null?void 0:s.cover_photo_url,t==null?void 0:t.cover_photo_url),brand_color:n(s==null?void 0:s.brand_color,t==null?void 0:t.brand_color),accent_color:n(s==null?void 0:s.accent_color,t==null?void 0:t.accent_color),tagline:n(s==null?void 0:s.tagline,t==null?void 0:t.tagline),welcome_message:n(s==null?void 0:s.welcome_message,t==null?void 0:t.welcome_message),portal_theme:n(s==null?void 0:s.portal_theme,t==null?void 0:t.portal_theme)||"noir"}}function aMt(){const s=ai();return pt({queryKey:["agent-portal-branding",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await V.from("agent_portal_branding").select("*").eq("user_id",s).maybeSingle();if(n)throw n;return t},enabled:!!s})}function R4s(s){return pt({queryKey:["agent-portal-branding-public",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await V.from("agent_portal_branding").select("logo_url, cover_photo_url, brand_color, accent_color, tagline, welcome_message, portal_theme").eq("user_id",s).maybeSingle();if(n)throw n;return t},enabled:!!s})}function D4s(){const s=ai(),t=ls();return Nt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r,error:a}=await V.from("agent_portal_branding").upsert({user_id:s,...n},{onConflict:"user_id"}).select().single();if(a)throw a;return r},onSuccess:()=>{t.invalidateQueries({queryKey:["agent-portal-branding",s]}),t.invalidateQueries({queryKey:["agent-portal-branding-public",s]})}})}async function iMt(s,t,n){var o;const r=((o=t.name.split(".").pop())==null?void 0:o.toLowerCase())||"png",a=`${s}/${n}-${Date.now()}.${r}`,{error:i}=await V.storage.from("portal-branding").upload(a,t,{upsert:!0,cacheControl:"3600"});if(i)throw i;const{data:l}=V.storage.from("portal-branding").getPublicUrl(a);return l.publicUrl}function O4s(s,t){return pt({queryKey:["client-portal-public",s],queryFn:async()=>{if(!s)return null;const{data:n,error:r}=await V.from("client_portals").select(` *, deal_pipeline ( id, deal_name, property_address, city, state, deal_type, target_close_date, contract_date, expected_price, actual_close_date, earnest_money_due_date, inspection_date, inspection_contingency_date, appraisal_date, loan_approval_date, title_docs_due_date, final_walkthrough_date, completed_key_dates, stage_id, owner_user_id, deal_pipeline_stages (id, name, color, icon, sort_order, is_won_stage, is_lost_stage) ) `).eq("slug",s).eq("is_enabled",!0).maybeSingle();if(r)throw r;return n},enabled:t})}function F4s(s){return pt({queryKey:["client-portal-by-id",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await V.from("client_portals").select(` *, deal_pipeline ( id, deal_name, property_address, city, state, deal_type, target_close_date, contract_date, expected_price, actual_close_date, earnest_money_due_date, inspection_date, inspection_contingency_date, appraisal_date, loan_approval_date, title_docs_due_date, final_walkthrough_date, completed_key_dates, stage_id, owner_user_id, deal_pipeline_stages (id, name, color, icon, sort_order, is_won_stage, is_lost_stage) ) `).eq("id",s).eq("is_enabled",!0).maybeSingle();if(n)throw n;return t},enabled:!!s})}function oMt({slug:s}){var me,Q,te,le,fe,_e;const[t,n]=k.useState(!1),[r,a]=k.useState("primary"),[i]=k.useState(()=>{const ve=`portal_fp_${s}`;let he=localStorage.getItem(ve);return he||(he=localStorage.getItem("portal_fp"),he?localStorage.setItem(ve,he):(he=crypto.randomUUID(),localStorage.setItem(ve,he),localStorage.setItem("portal_fp",he))),he});k.useEffect(()=>(document.body.classList.add("client-portal-page"),()=>document.body.classList.remove("client-portal-page")),[]);const{data:l,isLoading:o,error:c}=O4s(s,!0),d=l==null?void 0:l.linked_portal_id,{data:u}=F4s(d),h=(me=l==null?void 0:l.deal_pipeline)==null?void 0:me.owner_user_id,{data:m}=pt({queryKey:["portal-stages",h],queryFn:async()=>{const{data:ve,error:he}=await V.from("deal_pipeline_stages").select("*").eq("owner_user_id",h).order("sort_order",{ascending:!0});if(he)throw he;return ve},enabled:!!h}),{data:p}=pt({queryKey:["portal-agent",h],queryFn:async()=>{const{data:ve,error:he}=await V.from("profiles").select("id, name, avatar_url, phone, email").eq("id",h).single();if(he)throw he;return ve},enabled:!!h}),{data:g}=R4s(h),x=r==="linked"&&u?u:l,y=x==null?void 0:x.id,v=L4s(g,x==null?void 0:x.branding_override),_=v.portal_theme==="azure"?"azure":"noir";k.useEffect(()=>{const ve=`portal-theme-${_}`;return document.body.classList.add(ve),()=>document.body.classList.remove(ve)},[_]);const{data:j}=pt({queryKey:["portal-updates-public",y],queryFn:async()=>{const{data:ve,error:he}=await V.from("portal_updates").select("*").eq("portal_id",y).order("created_at",{ascending:!1});if(he)throw he;return ve},enabled:!!y}),C=(Q=x==null?void 0:x.deal_pipeline)==null?void 0:Q.id,{data:A}=pt({queryKey:["portal-documents",C],queryFn:async()=>{const{data:ve,error:he}=await V.from("deal_files").select("*").eq("deal_id",C).eq("visible_on_portal",!0).order("created_at",{ascending:!1});if(he)throw he;return ve},enabled:!!C}),M=l==null?void 0:l.id,I=M?`portal_onboarded_${M}_${i}`:null,P=I?localStorage.getItem(I)==="1":!1,{data:R,isLoading:O}=pt({queryKey:["portal-onboarding-check",M,i],queryFn:async()=>{const{data:ve,error:he}=await V.from("portal_onboarding_submissions").select("id").eq("portal_id",M).eq("device_fingerprint",i).maybeSingle();if(he)throw he;return ve&&I&&localStorage.setItem(I,"1"),ve},enabled:!!M&&!!(l!=null&&l.require_onboarding)&&!P,staleTime:5*60*1e3}),B=!!(l!=null&&l.require_onboarding)&&!P&&!R&&!t,{data:U}=pt({queryKey:["portal-custom-questions-public",h],queryFn:async()=>{const{data:ve,error:he}=await V.from("portal_custom_questions").select("*").eq("owner_user_id",h).eq("is_active",!0).order("sort_order",{ascending:!0});if(he)throw he;return ve},enabled:!!h&&B}),G=P||!!R||t||!(l!=null&&l.require_onboarding);if(o||l!=null&&l.require_onboarding&&!P&&O)return e.jsx("div",{className:"min-h-screen flex items-center justify-center",style:{background:"hsl(var(--portal-bg))"},children:e.jsx(Jt,{className:"w-6 h-6 animate-spin",style:{color:"hsl(var(--portal-gold))"}})});if(c||!l)return e.jsx("div",{className:"min-h-screen flex items-center justify-center p-6",style:{background:"var(--portal-gradient-noir)"},children:e.jsxs("div",{className:"text-center max-w-md",children:[e.jsx("div",{className:"w-16 h-16 rounded-full flex items-center justify-center mx-auto mb-6",style:{background:"hsl(var(--portal-surface-2))",border:"1px solid hsl(var(--portal-gold) / 0.3)"},children:e.jsx(Ng,{className:"w-6 h-6",style:{color:"hsl(var(--portal-gold))"}})}),e.jsx("h1",{className:"portal-serif text-4xl mb-3",style:{color:"hsl(var(--portal-ink))"},children:"Portal Not Available"}),e.jsx("div",{className:"portal-hairline mx-auto w-24 mb-4"}),e.jsx("p",{className:"text-sm",style:{color:"hsl(var(--portal-ink-muted))"},children:"This portal is no longer active or doesn't exist."})]})});if(!G){const ve=l==null?void 0:l.deal_pipeline;return e.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-slate-100",children:e.jsx(I4s,{portal:l,dealData:ve,agentProfile:p,customQuestions:U||[],deviceFingerprint:i,onComplete:()=>{I&&localStorage.setItem(I,"1"),n(!0)}})})}const H=(te=l==null?void 0:l.deal_pipeline)==null?void 0:te.deal_type,Y=(le=u==null?void 0:u.deal_pipeline)==null?void 0:le.deal_type,se=!!u,ee=ve=>ve==="listing"?"Your Sale":ve==="buy-side"?"Your Purchase":"Transaction",oe=ve=>ve==="listing"?e.jsx(ua,{className:"w-3.5 h-3.5"}):e.jsx(__,{className:"w-3.5 h-3.5"});return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"hidden lg:block",children:e.jsx(M4s,{portal:l,linkedPortal:u,activePortal:x,activeTab:r,onTabChange:a,agentProfile:p,branding:v,updates:j,documents:A})}),e.jsxs("div",{className:"lg:hidden min-h-screen pb-16",style:{background:"var(--portal-gradient-noir)"},children:[e.jsx(x4s,{dealData:x==null?void 0:x.deal_pipeline,agentProfile:p,welcomeMessage:(x==null?void 0:x.welcome_message)||v.welcome_message,isWon:(_e=(fe=x==null?void 0:x.deal_pipeline)==null?void 0:fe.deal_pipeline_stages)==null?void 0:_e.is_won_stage,branding:v}),e.jsxs("div",{className:"max-w-lg mx-auto px-4 space-y-5 mt-8",children:[se&&e.jsx("div",{className:"flex gap-1 rounded-xl p-1",style:{background:"hsl(var(--portal-surface-2))",border:"1px solid hsl(var(--portal-gold) / 0.15)"},children:["primary","linked"].map(ve=>{const he=r===ve,Se=ve==="primary"?H:Y;return e.jsxs("button",{onClick:()=>a(ve),className:"flex-1 flex items-center justify-center gap-1.5 rounded-lg py-2.5 text-sm font-medium transition-all portal-serif",style:{background:he?"hsl(var(--portal-surface-3))":"transparent",color:he?"hsl(var(--portal-gold))":"hsl(var(--portal-ink-muted))",boxShadow:he?"0 1px 0 hsl(var(--portal-gold) / 0.3) inset":"none"},children:[oe(Se),e.jsx("span",{style:{fontSize:"1rem"},children:ee(Se)})]},ve)})}),e.jsx(z4s,{portal:x,updates:j,documents:A,agentProfile:p}),e.jsxs("div",{className:"text-center pt-8 pb-2 space-y-3",children:[e.jsx("div",{className:"portal-hairline w-16 mx-auto"}),e.jsxs("div",{className:"flex items-center justify-center gap-1.5",style:{color:"hsl(var(--portal-ink-dim))"},children:[e.jsx(Ng,{className:"w-3 h-3"}),e.jsx("span",{className:"text-[10px] tracking-[0.2em] uppercase",children:"Secure Client Portal"})]}),p&&e.jsxs("p",{className:"text-xs",style:{color:"hsl(var(--portal-ink-muted))"},children:["Curated by ",e.jsx("span",{className:"portal-serif",style:{color:"hsl(var(--portal-gold))",fontSize:"0.95rem"},children:p.name})]})]})]})]})]})}function z4s({portal:s,updates:t,documents:n,agentProfile:r}){const a=s,i=a==null?void 0:a.deal_pipeline,l=i==null?void 0:i.deal_pipeline_stages,o=l==null?void 0:l.is_won_stage,c=i==null?void 0:i.deal_type,d=s.stage_mapping;let u=mAe(c);d&&d.length>0&&(u=d.map((x,y)=>{var v,_;return{key:`custom-${y}`,label:x.label||((v=u[y])==null?void 0:v.label)||`Stage ${y+1}`,description:x.description||((_=u[y])==null?void 0:_.description)||"",video_url:x.video_url||void 0}}));const h=d&&d.length>0?Math.min(NSe(l==null?void 0:l.name),u.length-1):NSe(l==null?void 0:l.name),m=u[h],p=m==null?void 0:m.video_url,g=o&&s.show_post_close_tips!==!1&&s.referral_enabled!==!1;return e.jsxs(e.Fragment,{children:[g&&e.jsx(nMt,{portalId:s.id,portalSlug:s.slug,ownerUserId:s.owner_user_id,rewardText:s.referral_reward_text,ctaHeadline:s.referral_cta_headline,agentName:r==null?void 0:r.name,clientName:s.client_name,reviewUrl:s.review_url,hubVideoUrl:s.homeowner_hub_video_url}),e.jsx(WTt,{targetCloseDate:i==null?void 0:i.target_close_date,actualCloseDate:i==null?void 0:i.actual_close_date,clientName:s.client_name}),e.jsx(KTt,{journeyStages:u,currentIndex:h}),m&&e.jsx(YTt,{currentStage:m,nextStepText:s.next_step_text,nextStepVideoUrl:p||s.next_step_video_url}),e.jsx(ZTt,{deal:i,portal:s}),n&&n.length>0&&e.jsx(XTt,{documents:n}),(s==null?void 0:s.id)&&(s==null?void 0:s.owner_user_id)&&e.jsx(sMt,{portalId:s.id,ownerUserId:s.owner_user_id,currentStage:l==null?void 0:l.name}),t&&t.length>0&&e.jsx(QTt,{updates:t})]})}function lMt({slug:s}){const t=oo(),n=s||t.slug,[r,a]=k.useState(!1),[i,l]=k.useState(!1),[o,c]=k.useState(""),[d,u]=k.useState(""),[h,m]=k.useState(""),[p,g]=k.useState(""),[x,y]=k.useState(""),[v,_]=k.useState("buying"),[j,C]=k.useState("");k.useEffect(()=>(document.body.classList.add("client-portal-page"),()=>document.body.classList.remove("client-portal-page")),[]);const{data:A,isLoading:M,error:I}=pt({queryKey:["portal-referral-target",n],queryFn:async()=>{if(!n)return null;const{data:O,error:B}=await V.from("client_portals").select(` id, slug, owner_user_id, client_name, referral_enabled, referral_reward_text, referral_cta_headline, is_enabled `).eq("slug",n).eq("is_enabled",!0).maybeSingle();if(B)throw B;return O},enabled:!!n}),{data:P}=pt({queryKey:["portal-referral-agent",A==null?void 0:A.owner_user_id],queryFn:async()=>{const{data:O}=await V.from("profiles").select("id, name, avatar_url").eq("id",A.owner_user_id).single();return O},enabled:!!(A!=null&&A.owner_user_id)}),R=async O=>{if(O.preventDefault(),!A||!h.trim()){ae.error("Please enter your friend's name");return}if(!p.trim()&&!x.trim()){ae.error("Please add at least an email or phone for your friend");return}a(!0);try{const{error:B}=await V.from("portal_referrals").insert({portal_id:A.id,owner_user_id:A.owner_user_id,referrer_name:o.trim()||A.client_name||null,referrer_email:d.trim()||null,friend_name:h.trim(),friend_email:p.trim()||null,friend_phone:x.trim()||null,friend_interest:v,friend_message:j.trim()||null});if(B)throw B;l(!0)}catch(B){ae.error(B.message||"Could not submit referral")}finally{a(!1)}};return M?e.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white flex items-center justify-center",children:e.jsx(fn,{className:"h-96 w-full max-w-lg rounded-2xl mx-4"})}):I||!A||!A.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(ma,{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 ",(P==null?void 0:P.name)||"your agent",". They'll reach out to"," ",e.jsx("span",{className:"font-semibold text-slate-800",children:h})," personally and treat them like family."]}),e.jsxs("button",{onClick:()=>window.history.back(),className:"inline-flex items-center gap-2 text-sm text-[#406E71] hover:text-[#2a4c64] font-medium",children:[e.jsx(Ia,{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:[P!=null&&P.avatar_url?e.jsx("img",{src:P.avatar_url,alt:P.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(Zo,{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(Zo,{className:"w-3 h-3"})," Referral"]}),e.jsx("h1",{className:"text-2xl font-bold tracking-tight mb-1 font-serif",children:A.referral_cta_headline||"Refer a Friend"}),e.jsxs("p",{className:"text-sm text-white/70",children:["Send ",(P==null?void 0:P.name)||"your agent"," someone you trust."]}),A.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:A.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:R,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(re,{htmlFor:"friend_name",className:"text-sm",children:["Their name ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(be,{id:"friend_name",value:h,onChange:O=>m(O.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(re,{htmlFor:"friend_email",className:"text-sm",children:"Email"}),e.jsx(be,{id:"friend_email",type:"email",value:p,onChange:O=>g(O.target.value),placeholder:"jane@email.com",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"friend_phone",className:"text-sm",children:"Phone"}),e.jsx(be,{id:"friend_phone",type:"tel",value:x,onChange:O=>y(O.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(re,{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(O=>e.jsx("button",{type:"button",onClick:()=>_(O.v),className:`rounded-lg border px-3 py-2 text-sm font-medium transition-colors ${v===O.v?"bg-[#406E71] text-white border-[#406E71]":"bg-white text-slate-600 border-slate-200 hover:border-slate-300"}`,children:O.l},O.v))})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"friend_message",className:"text-sm",children:"A note (optional)"}),e.jsx("textarea",{id:"friend_message",value:j,onChange:O=>C(O.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(re,{htmlFor:"referrer_name",className:"text-sm",children:"Your name"}),e.jsx(be,{id:"referrer_name",value:o,onChange:O=>c(O.target.value),placeholder:A.client_name||"Your name",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"referrer_email",className:"text-sm",children:"Your email"}),e.jsx(be,{id:"referrer_email",type:"email",value:d,onChange:O=>u(O.target.value),placeholder:"So we can thank you!",className:"mt-1"})]})]})]}),e.jsxs("button",{type:"submit",disabled:r,className:"w-full bg-[#406E71] hover:bg-[#345e7a] disabled:opacity-60 text-white font-semibold rounded-xl py-3.5 px-4 flex items-center justify-center gap-2 transition-colors",children:[r?e.jsx(Jt,{className:"w-4 h-4 animate-spin"}):e.jsx(Zo,{className:"w-4 h-4"}),r?"Sending...":"Send Referral"]}),e.jsx("p",{className:"text-[11px] text-center text-slate-400",children:"By submitting, you confirm your friend has agreed to be contacted."})]})})]})}function B4s(){const t=Tu().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 n=t.match(/^([^/]+)\/refer$/);return n?e.jsx(lMt,{slug:n[1]}):t.includes("/")?e.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white flex items-center justify-center p-6",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"text-2xl font-bold text-slate-800 mb-2",children:"Page Not Found"}),e.jsx("p",{className:"text-slate-500",children:"This portal link doesn't look right."})]})}):e.jsx(oMt,{slug:t})}function $4s(s){const t=[],n=r=>{r&&!t.includes(r)&&t.push(r)};for(const r of s.filter(Boolean)){n(r);try{const a=new URL(r),i=a.searchParams.get("u");i&&/\/functions\/v1\/trestle-media/i.test(a.pathname)&&n(i)}catch{}}return t}function kSe({photos:s,alt:t="",className:n="w-full h-full",imgClassName:r="w-full h-full object-cover",iconClassName:a="w-8 h-8"}){const i=k.useMemo(()=>$4s(Array.isArray(s)?s:[]),[s]),[l,o]=k.useState(0);return k.useEffect(()=>{o(0)},[i.join("|")]),!i.length||l>=i.length?e.jsx("div",{className:`${n} bg-muted flex items-center justify-center text-muted-foreground`,children:e.jsx(ua,{className:`${a} opacity-40`})}):e.jsx("div",{className:`${n} overflow-hidden bg-muted`,children:e.jsx("img",{src:i[l],alt:t,className:r,onError:()=>o(c=>c+1)})})}function cMt({comp:s,open:t,onClose:n}){var d;const[r,a]=k.useState(0);if(!s)return null;const i=Array.isArray(s.photos)?s.photos.filter(Boolean):[],l=s.soldPrice||s.price,o=s.sqft&&l?Math.round(l/s.sqft):null,c=u=>{if(!u)return null;const[h,m,p]=u.split(/[-/T]/);return h?`${m}/${p}/${h}`:null};return e.jsx(zs,{open:t,onOpenChange:u=>{u||n()},children:e.jsxs(Rs,{className:"max-w-4xl max-h-[90vh] overflow-y-auto p-0",children:[e.jsxs(Vs,{className:"px-6 pt-6 pb-2",children:[e.jsx($s,{className:"text-xl",children:s.address}),e.jsxs("div",{className:"text-sm text-muted-foreground flex items-center gap-1",children:[e.jsx(Si,{className:"w-3.5 h-3.5"}),s.city,", ",s.state," ",s.zip]})]}),i.length>0?e.jsxs("div",{className:"px-6",children:[e.jsx(kSe,{photos:i.slice(r),className:"rounded-lg aspect-[16/10]"}),i.length>1&&e.jsx("div",{className:"flex gap-2 mt-2 overflow-x-auto pb-2",children:i.slice(0,24).map((u,h)=>e.jsx("button",{onClick:()=>a(h),className:`flex-none w-20 h-16 rounded overflow-hidden border-2 transition ${h===r?"border-primary":"border-transparent opacity-70 hover:opacity-100"}`,children:e.jsx(kSe,{photos:[u],iconClassName:"w-5 h-5"})},h))})]}):e.jsx("div",{className:"px-6",children:e.jsx("div",{className:"rounded-lg bg-muted aspect-[16/10] flex items-center justify-center text-muted-foreground",children:e.jsx(ua,{className:"w-12 h-12 opacity-40"})})}),e.jsxs("div",{className:"px-6 pt-4 flex items-center justify-between flex-wrap gap-2",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"text-3xl font-bold flex items-center gap-1",children:[e.jsx(Su,{className:"w-6 h-6 text-muted-foreground"}),(l||0).toLocaleString()]}),o&&e.jsxs("div",{className:"text-xs text-muted-foreground",children:["$",o,"/sqft"]})]}),e.jsxs("div",{className:"flex flex-col items-end gap-1",children:[e.jsx(qe,{variant:"outline",children:s.status}),s.daysOnMarket!=null&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:[s.daysOnMarket," DOM"]})]})]}),(s.listDate||s.statusChangeDate||s.soldDate)&&e.jsxs("div",{className:"px-6 pt-4",children:[e.jsx("div",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground mb-2",children:"Timeline"}),e.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[e.jsx(WIe,{label:"Active",date:c(s.listDate),active:!0}),e.jsx(WIe,{label:"Pending",date:/Pending|Contingent|Under Contract|Backup/i.test(String(s.status||""))?c(s.statusChangeDate):null,active:/Pending|Contingent|Under Contract|Backup/i.test(String(s.status||""))}),e.jsx(WIe,{label:"Closed",date:c(s.soldDate)||(/Closed|Sold/i.test(String(s.status||""))?c(s.statusChangeDate):null),active:/Closed|Sold/i.test(String(s.status||""))})]})]}),e.jsxs("div",{className:"px-6 pt-4 grid grid-cols-2 md:grid-cols-4 gap-3",children:[e.jsx(ore,{icon:e.jsx(Yw,{className:"w-4 h-4"}),label:"Beds",value:s.bedrooms??"—"}),e.jsx(ore,{icon:e.jsx(p0,{className:"w-4 h-4"}),label:"Baths",value:s.bathrooms??"—"}),e.jsx(ore,{icon:e.jsx(b3,{className:"w-4 h-4"}),label:"SqFt",value:((d=s.sqft)==null?void 0:d.toLocaleString())??"—"}),e.jsx(ore,{icon:e.jsx(ha,{className:"w-4 h-4"}),label:"Year Built",value:s.yearBuilt??"—"})]}),e.jsxs("div",{className:"px-6 pt-4 grid sm:grid-cols-2 gap-x-6 gap-y-2 text-sm",children:[e.jsx(V1,{label:"MLS #",value:s.mlsNumber}),e.jsx(V1,{label:"Property Type",value:s.propertySubType||s.propertyType}),e.jsx(V1,{label:"Lot Size",value:s.lotSize}),e.jsx(V1,{label:"Garage",value:s.garageSpaces}),e.jsx(V1,{label:"Stories",value:s.stories}),e.jsx(V1,{label:"HOA",value:s.hoaFee?`$${s.hoaFee}/${(s.hoaFrequency||"mo").toLowerCase()}`:null}),e.jsx(V1,{label:"Tax (annual)",value:s.taxAmount?`$${s.taxAmount.toLocaleString()}`:null}),e.jsx(V1,{label:"Heating",value:s.heating}),e.jsx(V1,{label:"Cooling",value:s.cooling}),e.jsx(V1,{label:"Parking",value:s.parking}),e.jsx(V1,{label:"Elementary",value:s.elementarySchool}),e.jsx(V1,{label:"Middle",value:s.middleSchool}),e.jsx(V1,{label:"High",value:s.highSchool}),e.jsx(V1,{label:"Listed By",value:s.listAgentFullName}),e.jsx(V1,{label:"Office",value:s.listOfficeName})]}),s.description&&e.jsxs("div",{className:"px-6 pt-4",children:[e.jsx("div",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground mb-1",children:"Description"}),e.jsx("p",{className:"text-sm leading-relaxed whitespace-pre-wrap",children:s.description})]}),e.jsx("div",{className:"px-6 py-4"})]})})}function ore({icon:s,label:t,value:n}){return e.jsxs("div",{className:"rounded-lg border bg-card p-3",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-muted-foreground",children:[s,t]}),e.jsx("div",{className:"text-lg font-semibold mt-0.5",children:n})]})}function V1({label:s,value:t}){return t==null||t===""||t===0?null:e.jsxs("div",{className:"flex justify-between border-b border-dashed py-1",children:[e.jsx("span",{className:"text-muted-foreground",children:s}),e.jsx("span",{className:"font-medium text-right ml-3 truncate",children:String(t)})]})}function WIe({label:s,date:t,active:n}){return e.jsxs("div",{className:`rounded-lg border p-2 text-center ${n?"bg-primary/5 border-primary/30":"bg-muted/30"}`,children:[e.jsx("div",{className:"text-[10px] uppercase tracking-wide text-muted-foreground",children:s}),e.jsx("div",{className:`text-sm font-medium mt-0.5 ${t?"":"text-muted-foreground/60"}`,children:t||"—"})]})}function lre({to:s,durationMs:t=1400,prefix:n="",suffix:r="",className:a,delayMs:i=0}){const[l,o]=k.useState(0),c=k.useRef(null);return k.useEffect(()=>{if(!Number.isFinite(s))return;let d=0;const u=0,h=p=>1-Math.pow(1-p,3),m=setTimeout(()=>{const p=g=>{d||(d=g);const x=g-d,y=Math.min(1,x/t);o(Math.round(u+(s-u)*h(y))),y<1&&(c.current=requestAnimationFrame(p))};c.current=requestAnimationFrame(p)},i);return()=>{clearTimeout(m),c.current&&cancelAnimationFrame(c.current)}},[s,t,i]),e.jsxs("span",{className:a,children:[n,l.toLocaleString(),r]})}function U4s({low:s,likely:t,high:n,defaultMortgage:r=0,defaultCommissionPct:a=6,defaultClosingPct:i=1}){const[l,o]=k.useState(t),[c,d]=k.useState(r),[u,h]=k.useState(a),[m,p]=k.useState(i),{commission:g,closing:x,net:y}=k.useMemo(()=>{const j=Math.round(l*u/100),C=Math.round(l*m/100);return{commission:j,closing:C,net:Math.max(0,l-j-C-(c||0))}},[l,u,m,c]),v=j=>`$${j.toLocaleString()}`,_=n>s?(l-s)/(n-s)*100:50;return e.jsxs(we,{className:"overflow-hidden border-primary/20",children:[e.jsxs("div",{className:"bg-gradient-to-br from-primary/5 to-primary/10 px-6 pt-6 pb-4 border-b border-primary/10",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(mc,{className:"w-4 h-4 text-primary"}),e.jsx("span",{className:"text-xs uppercase tracking-widest font-semibold text-primary",children:"Your Price Story"})]}),e.jsx("h2",{className:"text-2xl md:text-3xl font-bold",children:"What if you priced it at…"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Drag the price. Watch your estimated walk-away update in real-time."})]}),e.jsxs(De,{className:"p-6 space-y-6",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-end justify-between mb-3",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"List price"}),e.jsx("span",{className:"text-3xl font-bold tabular-nums",children:v(l)})]}),e.jsxs("div",{className:"relative",children:[e.jsx(sx,{value:[l],min:s,max:n,step:1e3,onValueChange:([j])=>o(j)}),e.jsxs("div",{className:"flex justify-between text-[10px] text-muted-foreground mt-2",children:[e.jsx("span",{children:v(s)}),e.jsxs("span",{children:["Suggested ",v(t)]}),e.jsx("span",{children:v(n)})]})]}),e.jsx("div",{className:"mt-2 h-1.5 rounded-full bg-muted overflow-hidden",children:e.jsx("div",{className:"h-full bg-gradient-to-r from-emerald-500 via-primary to-amber-500 transition-all",style:{width:`${Math.min(100,Math.max(0,_))}%`}})})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-3",children:[e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Mortgage payoff"}),e.jsx(be,{type:"number",inputMode:"numeric",value:c||"",placeholder:"$0",onChange:j=>d(Number(j.target.value)||0)})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Commission %"}),e.jsx(be,{type:"number",step:"0.25",value:u,onChange:j=>h(Number(j.target.value)||0)})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Closing costs %"}),e.jsx(be,{type:"number",step:"0.25",value:m,onChange:j=>p(Number(j.target.value)||0)})]})]}),e.jsxs("div",{className:"rounded-xl border bg-card overflow-hidden",children:[e.jsxs("div",{className:"px-5 py-4 grid grid-cols-2 gap-y-2 text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Sale price"}),e.jsx("span",{className:"text-right tabular-nums font-medium",children:v(l)}),e.jsxs("span",{className:"text-muted-foreground",children:["Commission (",u,"%)"]}),e.jsxs("span",{className:"text-right tabular-nums text-rose-600",children:["−",v(g)]}),e.jsxs("span",{className:"text-muted-foreground",children:["Closing (",m,"%)"]}),e.jsxs("span",{className:"text-right tabular-nums text-rose-600",children:["−",v(x)]}),c>0&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-muted-foreground",children:"Mortgage payoff"}),e.jsxs("span",{className:"text-right tabular-nums text-rose-600",children:["−",v(c)]})]})]}),e.jsxs("div",{className:"bg-gradient-to-r from-emerald-500/10 to-primary/10 px-5 py-4 border-t flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(cY,{className:"w-5 h-5 text-emerald-600"}),e.jsx("span",{className:"font-semibold",children:"Your estimated walk-away"})]}),e.jsx("span",{className:"text-2xl font-bold tabular-nums text-emerald-700",children:v(y)})]})]}),e.jsx("p",{className:"text-[11px] text-muted-foreground leading-relaxed",children:"This is a rough estimate to help you think through pricing. Actual proceeds depend on title fees, prorations, repairs, and other items your agent will walk through in detail."})]})]})}function dMt({tokenOverride:s}={}){var Ue,Be,je,Ye,Ee,Re,ke,Fe,Oe,Ge,yt,tt;const t=oo(),n=s??t.token,[r,a]=k.useState(null),[i,l]=k.useState(null),[o,c]=k.useState([]),[d,u]=k.useState(!0),[h,m]=k.useState(""),[p,g]=k.useState(""),[x,y]=k.useState(""),[v,_]=k.useState(!1),[j,C]=k.useState(!1),[A,M]=k.useState(null),[I,P]=k.useState(null),[R,O]=k.useState(!1),{toast:B}=Fi();k.useEffect(()=>{n&&(async()=>{const{data:ut}=await V.from("cmas").select("*").eq("share_token",n).eq("status","shared").maybeSingle();if(!ut){u(!1);return}a(ut);const[{data:nt},{data:et}]=await Promise.all([V.from("cma_comps").select("*").eq("cma_id",ut.id).order("position"),V.from("profiles").select("id,name,email,phone,avatar_url,brokerage_name,website_url,title,bio").eq("id",ut.agent_id).maybeSingle()]);c((nt||[]).filter(wt=>wt.selected)),l(et);const at=localStorage.getItem("cma_visitor_token")||crypto.randomUUID();localStorage.setItem("cma_visitor_token",at),await V.from("cma_views").insert({cma_id:ut.id,visitor_token:at,user_agent:navigator.userAgent}),u(!1)})()},[n]);const U=async ut=>{if(!r)return;const nt=localStorage.getItem("cma_visitor_token")||"";await V.from("cma_views").insert({cma_id:r.id,visitor_token:nt,reactions:{[ut]:!0}}),V.functions.invoke("cma-reply-notify",{body:{shareToken:n,reaction:ut,visitorToken:nt}}).catch(()=>{}),B({title:"Thanks — your agent just got notified ✨"})},G=!(r!=null&&r.contact_id),H=async()=>{if(!r||!h.trim())return;if(G&&(!p.trim()||!x.trim())){B({title:"Please add your name and email",variant:"destructive"});return}_(!0);const ut=localStorage.getItem("cma_visitor_token")||"",{data:nt,error:et}=await V.functions.invoke("cma-reply-notify",{body:{shareToken:n,message:h,visitorToken:ut,viewerName:p.trim()||void 0,viewerEmail:x.trim()||void 0}});if(_(!1),et||!(nt!=null&&nt.success)){B({title:"Could not send",description:(et==null?void 0:et.message)||(nt==null?void 0:nt.error),variant:"destructive"});return}m(""),C(!0),B({title:"Message sent to your agent"})},Y=k.useMemo(()=>{const ut=o.map(nt=>{const et=nt.snapshot,at=(et==null?void 0:et.soldPrice)||(et==null?void 0:et.price);return at&&(et!=null&&et.sqft)?at/et.sqft:null}).filter(nt=>!!nt).sort((nt,et)=>nt-et);return ut.length?Math.round(ut[Math.floor(ut.length/2)]):null},[o]);if(d)return e.jsx("div",{className:"min-h-screen flex items-center justify-center",children:e.jsx(Jt,{className:"w-8 h-8 animate-spin"})});if(!r)return e.jsx("div",{className:"min-h-screen flex items-center justify-center text-center p-6",children:e.jsxs("div",{children:[e.jsx(ua,{className:"w-12 h-12 mx-auto text-muted-foreground mb-4"}),e.jsx("h1",{className:"text-xl font-semibold",children:"CMA not found"}),e.jsx("p",{className:"text-muted-foreground",children:"This report may have been removed or unpublished."})]})});const se=r.subject||{},ee=(Ue=r.settings)==null?void 0:Ue.personalVideo,oe=(Be=se.photos)==null?void 0:Be[0],me=r.contact_first_name?r.contact_first_name:null,Q=((i==null?void 0:i.name)||"A").split(" ").map(ut=>ut[0]).slice(0,2).join("").toUpperCase(),te=i!=null&&i.phone?`tel:${String(i.phone).replace(/[^\d+]/g,"")}`:null,le=i!=null&&i.email?`mailto:${i.email}`:null,fe=i!=null&&i.phone?`sms:${String(i.phone).replace(/[^\d+]/g,"")}`:null,_e=r.price_low??null,ve=r.price_likely??null,he=r.price_high??null,Se=_e&&ve&&he,Te=ve&&se.sqft?Math.round(ve/se.sqft):null,Ie=Te&&Y?Math.round((Te-Y)/Y*100):null;return e.jsxs("div",{className:"min-h-screen bg-background pb-28 md:pb-0",children:[i&&e.jsx("div",{className:"border-b bg-card sticky top-0 z-40 backdrop-blur supports-[backdrop-filter]:bg-card/80",children:e.jsxs("div",{className:"container mx-auto max-w-6xl px-4 md:px-6 py-3 flex items-center gap-3",children:[i.avatar_url?e.jsx("img",{src:i.avatar_url,alt:i.name,className:"w-10 h-10 rounded-full object-cover ring-2 ring-primary/20"}):e.jsx("div",{className:"w-10 h-10 rounded-full bg-primary/10 flex items-center justify-center font-semibold text-primary text-sm",children:Q}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"font-semibold leading-tight truncate text-sm",children:i.name}),(i.title||i.brokerage_name)&&e.jsxs("div",{className:"text-[11px] text-muted-foreground flex items-center gap-1 truncate",children:[i.brokerage_name&&e.jsx(Gi,{className:"w-3 h-3 shrink-0"}),e.jsx("span",{className:"truncate",children:[i.title,i.brokerage_name].filter(Boolean).join(" · ")})]})]}),e.jsxs("div",{className:"hidden md:flex items-center gap-2",children:[te&&e.jsx($,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("a",{href:te,children:[e.jsx(ka,{className:"w-4 h-4 mr-1"}),"Call"]})}),le&&e.jsx($,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("a",{href:le,children:[e.jsx(pn,{className:"w-4 h-4 mr-1"}),"Email"]})})]})]})}),e.jsxs("div",{className:"relative overflow-hidden",children:[oe?e.jsxs("div",{className:"absolute inset-0",children:[e.jsx("img",{src:oe,alt:se.address,className:"w-full h-full object-cover scale-110 animate-[kenburns_18s_ease-out_infinite_alternate]",style:{animation:"kenburns 22s ease-in-out infinite alternate"}}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-slate-950/85 via-slate-900/75 to-primary/60"}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-background via-background/20 to-transparent"})]}):e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-primary/30 via-primary/10 to-background"}),e.jsx("style",{children:` @keyframes kenburns { 0% { transform: scale(1.08) translate(0, 0); } 100% { transform: scale(1.18) translate(-1.5%, -1%); } } `}),e.jsx("div",{className:"relative container mx-auto max-w-6xl px-4 md:px-8 pt-12 md:pt-20 pb-16 md:pb-24",children:e.jsxs("div",{className:"grid md:grid-cols-5 gap-8 items-center",children:[e.jsxs("div",{className:`${ee!=null&&ee.url?"md:col-span-3":"md:col-span-5"} text-white animate-fade-in`,children:[e.jsxs(qe,{className:"mb-4 bg-white/15 text-white border-white/20 backdrop-blur-sm hover:bg-white/20",children:[e.jsx(kn,{className:"w-3 h-3 mr-1"}),me?`Prepared for ${me}`:r.buyer_mode?"Your Buyer Analysis":"Your Market Analysis"]}),e.jsx("h1",{className:"text-3xl md:text-5xl lg:text-6xl font-bold leading-[1.05] tracking-tight",children:se.address}),e.jsxs("p",{className:"text-white/70 mt-2 text-base md:text-lg flex items-center gap-2",children:[e.jsx(Si,{className:"w-4 h-4"}),se.city,", ",se.state," ",se.zip]}),Se&&e.jsxs("div",{className:"mt-8 md:mt-10",children:[e.jsx("p",{className:"text-xs uppercase tracking-[0.2em] text-white/60 mb-2",children:"Estimated Value"}),e.jsx("div",{className:"flex items-baseline gap-4 flex-wrap",children:e.jsx("div",{className:"text-5xl md:text-7xl font-bold tabular-nums",children:e.jsx(lre,{to:ve,prefix:"$",durationMs:1600,delayMs:250})})}),e.jsxs("div",{className:"mt-4 flex items-center gap-3 md:gap-6 text-sm text-white/80",children:[e.jsxs("div",{children:[e.jsx("span",{className:"block text-[11px] uppercase tracking-wider text-white/50",children:"Low"}),e.jsx("span",{className:"tabular-nums font-medium",children:e.jsx(lre,{to:_e,prefix:"$",delayMs:500})})]}),e.jsx("div",{className:"h-8 w-px bg-white/20"}),e.jsxs("div",{children:[e.jsx("span",{className:"block text-[11px] uppercase tracking-wider text-white/50",children:"Likely"}),e.jsx("span",{className:"tabular-nums font-medium",children:e.jsx(lre,{to:ve,prefix:"$",delayMs:650})})]}),e.jsx("div",{className:"h-8 w-px bg-white/20"}),e.jsxs("div",{children:[e.jsx("span",{className:"block text-[11px] uppercase tracking-wider text-white/50",children:"High"}),e.jsx("span",{className:"tabular-nums font-medium",children:e.jsx(lre,{to:he,prefix:"$",delayMs:800})})]})]})]})]}),(ee==null?void 0:ee.url)&&e.jsx("div",{className:"md:col-span-2 animate-scale-in",children:e.jsxs("button",{onClick:()=>O(!0),className:"group relative w-full aspect-[4/5] md:aspect-[4/5] rounded-2xl overflow-hidden shadow-2xl ring-1 ring-white/20 bg-black",children:[ee.thumb?e.jsx("img",{src:ee.thumb,alt:"",className:"w-full h-full object-cover"}):e.jsx("video",{src:ee.url,className:"w-full h-full object-cover",muted:!0,playsInline:!0,preload:"metadata"}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-black/60 to-black/10 group-hover:from-black/40 transition-colors"}),e.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center text-white",children:[e.jsx("div",{className:"w-16 h-16 md:w-20 md:h-20 rounded-full bg-white/95 text-primary flex items-center justify-center shadow-2xl group-hover:scale-110 transition-transform",children:e.jsx(pu,{className:"w-7 h-7 md:w-8 md:h-8 ml-1",fill:"currentColor"})}),e.jsxs("p",{className:"mt-4 text-sm font-medium tracking-wide",children:["A message from ",((je=i==null?void 0:i.name)==null?void 0:je.split(" ")[0])||"your agent"]})]})]})})]})})]}),R&&(ee==null?void 0:ee.url)&&e.jsx("div",{className:"fixed inset-0 z-50 bg-black/90 flex items-center justify-center p-4 animate-fade-in",onClick:()=>O(!1),children:e.jsxs("div",{className:"relative w-full max-w-4xl",onClick:ut=>ut.stopPropagation(),children:[e.jsx("video",{src:ee.url,controls:!0,autoPlay:!0,className:"w-full rounded-xl"}),e.jsx($,{variant:"ghost",className:"absolute -top-12 right-0 text-white hover:bg-white/10",onClick:()=>O(!1),children:"Close"})]})}),e.jsxs("div",{className:"container mx-auto max-w-6xl px-4 md:px-8 py-10 md:py-16 space-y-10 md:space-y-14",children:[e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3 md:gap-4 -mt-20 md:-mt-24 relative z-10",children:[{label:"Beds",value:se.bedrooms??"—"},{label:"Baths",value:se.bathrooms??"—"},{label:"Sq Ft",value:((Ye=se.sqft)==null?void 0:Ye.toLocaleString())??"—"},{label:"Year Built",value:se.yearBuilt??"—"}].map((ut,nt)=>e.jsx(we,{className:"shadow-lg animate-fade-in",style:{animationDelay:`${nt*80}ms`},children:e.jsxs(De,{className:"p-4 md:p-6 text-center",children:[e.jsx("div",{className:"text-2xl md:text-3xl font-bold",children:ut.value}),e.jsx("div",{className:"text-xs text-muted-foreground mt-1 uppercase tracking-wider",children:ut.label})]})},nt))}),((Re=(Ee=r.settings)==null?void 0:Ee.priceOverride)==null?void 0:Re.enabled)&&((Fe=(ke=r.settings)==null?void 0:ke.priceOverride)==null?void 0:Fe.note)&&e.jsx(we,{className:"border-primary/30 bg-gradient-to-br from-primary/5 to-transparent",children:e.jsxs(De,{className:"p-6 md:p-8",children:[e.jsx("p",{className:"text-xs uppercase tracking-widest text-primary font-semibold mb-2",children:"A note from your agent"}),e.jsx("p",{className:"text-base md:text-lg leading-relaxed whitespace-pre-wrap text-foreground/90",children:r.settings.priceOverride.note})]})}),Se&&e.jsx(U4s,{low:_e,likely:ve,high:he}),Y&&Te&&e.jsxs("div",{className:"grid md:grid-cols-3 gap-4",children:[e.jsx(we,{className:"md:col-span-2",children:e.jsxs(De,{className:"p-6 md:p-8",children:[e.jsx("p",{className:"text-xs uppercase tracking-widest text-primary font-semibold mb-2",children:"Why this price"}),e.jsx("h2",{className:"text-2xl md:text-3xl font-bold mb-3",children:"The market is talking."}),e.jsxs("p",{className:"text-muted-foreground leading-relaxed",children:["Based on ",e.jsxs("strong",{className:"text-foreground",children:[o.length," comparable ",o.length===1?"home":"homes"]})," in ",se.city,", the median sale rate is ",e.jsxs("strong",{className:"text-foreground",children:["$",Y,"/sqft"]}),". Applied to your home's ",(Oe=se.sqft)==null?void 0:Oe.toLocaleString()," sqft, the comps support a value near ",e.jsxs("strong",{className:"text-foreground",children:["$",(Y*(se.sqft||0)).toLocaleString()]}),". Your agent's suggested price reflects local nuance and condition."]})]})}),e.jsx(we,{className:"bg-gradient-to-br from-primary/10 to-primary/5 border-primary/20",children:e.jsxs(De,{className:"p-6 md:p-8 h-full flex flex-col justify-center",children:[e.jsx("p",{className:"text-xs uppercase tracking-widest text-muted-foreground mb-1",children:"Your home"}),e.jsxs("div",{className:"text-3xl font-bold tabular-nums",children:["$",Te,e.jsx("span",{className:"text-base font-normal text-muted-foreground",children:"/sqft"})]}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-3",children:["Neighborhood avg: ",e.jsxs("span",{className:"font-medium text-foreground",children:["$",Y,"/sqft"]})]}),Ie!==null&&Ie!==0&&e.jsxs("p",{className:`text-sm font-medium mt-1 ${Ie>0?"text-emerald-600":"text-rose-600"}`,children:[Ie>0?"▲":"▼"," ",Math.abs(Ie),"% ",Ie>0?"above":"below"," the median"]})]})})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-baseline justify-between mb-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs uppercase tracking-widest text-primary font-semibold",children:"Homes like yours"}),e.jsx("h2",{className:"text-2xl md:text-3xl font-bold",children:"The Comparables"})]}),e.jsxs(qe,{variant:"outline",className:"text-xs",children:[o.length," comps"]})]}),e.jsx("div",{className:"grid md:grid-cols-2 lg:grid-cols-3 gap-4",children:o.map((ut,nt)=>{var wt;const et=ut.snapshot,at=et.soldPrice||et.price;return e.jsxs(we,{className:`overflow-hidden cursor-pointer transition-all duration-300 hover:shadow-xl hover:-translate-y-1 animate-fade-in ${I===nt?"ring-2 ring-primary":""}`,style:{animationDelay:`${nt*60}ms`},onClick:()=>M(nt),onMouseEnter:()=>P(nt),onMouseLeave:()=>P(null),children:[e.jsxs("div",{className:"relative",children:[e.jsx(kSe,{photos:et.photos,className:"w-full h-44"}),e.jsxs(qe,{className:"absolute top-2 left-2 bg-black/70 text-white border-0 backdrop-blur-sm",children:["#",nt+1]}),e.jsx(qe,{variant:"outline",className:"absolute top-2 right-2 bg-white/95 border-0",children:et.status})]}),e.jsxs(De,{className:"p-4",children:[e.jsx("div",{className:"font-semibold leading-tight truncate",children:et.address}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[et.city,", ",et.state]}),e.jsx("div",{className:"flex justify-between items-center mt-3 text-sm",children:e.jsxs("span",{className:"text-muted-foreground",children:[et.bedrooms??"?","bd · ",et.bathrooms??"?","ba · ",((wt=et.sqft)==null?void 0:wt.toLocaleString())??"?"," sqft"]})}),e.jsxs("div",{className:"flex justify-between items-center mt-3 pt-3 border-t",children:[e.jsxs("span",{className:"text-xl font-bold tabular-nums",children:["$",at==null?void 0:at.toLocaleString()]}),et.sqft&&at?e.jsxs("span",{className:"text-xs text-muted-foreground tabular-nums",children:["$",Math.round(at/et.sqft),"/sqft"]}):null]})]})]},nt)})})]}),e.jsx(cMt,{comp:A!==null?(Ge=o[A])==null?void 0:Ge.snapshot:null,open:A!==null,onClose:()=>M(null)}),e.jsx(we,{className:"border-primary/20 bg-gradient-to-br from-primary/5 via-background to-background overflow-hidden",children:e.jsxs(De,{className:"p-6 md:p-8 space-y-5",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs uppercase tracking-widest text-primary font-semibold mb-1",children:"Your turn"}),e.jsxs("h2",{className:"text-2xl md:text-3xl font-bold",children:["What do you think",me?`, ${me}`:"","?"]}),e.jsxs("p",{className:"text-sm text-muted-foreground mt-1",children:["One tap. ",((yt=i==null?void 0:i.name)==null?void 0:yt.split(" ")[0])||"Your agent"," hears you instantly."]})]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:[{kind:"love",icon:Bo,label:"I love this price"},{kind:"fair",icon:Ay,label:"Seems fair"},{kind:"lower",icon:lk,label:"I'd price lower"},{kind:"higher",icon:mc,label:"I'd price higher"},{kind:"ready_to_list",icon:E5,label:"Ready to list"},{kind:"want_walkthrough",icon:ba,label:"Want a walkthrough"},{kind:"need_time",icon:ha,label:"Need more time"},{kind:"have_questions",icon:_C,label:"I have questions"}].map(({kind:ut,icon:nt,label:et})=>e.jsxs($,{variant:"outline",className:"bg-card hover:bg-primary hover:text-primary-foreground hover:scale-105 transition-all",onClick:()=>U(ut),children:[e.jsx(nt,{className:"w-4 h-4 mr-2"}),et]},ut))}),e.jsxs("div",{className:"pt-4 border-t",children:[e.jsxs("p",{className:"text-sm font-medium mb-2 flex items-center gap-1",children:[e.jsx(Vu,{className:"w-4 h-4"}),"Ask your agent a question"]}),j?e.jsxs("div",{className:"rounded-md bg-emerald-50 border border-emerald-200 p-4 text-sm text-emerald-800 animate-fade-in",children:["✓ Sent! ",((tt=i==null?void 0:i.name)==null?void 0:tt.split(" ")[0])||"Your agent"," was notified and will get back to you shortly."]}):e.jsxs(e.Fragment,{children:[G&&e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2 mb-2",children:[e.jsx("input",{className:"border rounded-md p-2 text-sm bg-background",placeholder:"Your name",value:p,onChange:ut=>g(ut.target.value)}),e.jsx("input",{type:"email",className:"border rounded-md p-2 text-sm bg-background",placeholder:"Your email",value:x,onChange:ut=>y(ut.target.value)})]}),e.jsx("textarea",{className:"w-full border rounded-md p-3 text-sm min-h-[100px] bg-background",placeholder:"What questions do you have about this analysis?",value:h,onChange:ut=>m(ut.target.value)}),e.jsx($,{onClick:H,disabled:!h.trim()||v,className:"mt-2",children:v?"Sending…":"Send to agent"})]})]})]})}),i&&e.jsx(we,{className:"overflow-hidden border-primary/20",children:e.jsx("div",{className:"bg-gradient-to-br from-primary/10 to-primary/5 p-6 md:p-10",children:e.jsxs("div",{className:"flex flex-col md:flex-row gap-6 items-start",children:[i.avatar_url?e.jsx("img",{src:i.avatar_url,alt:i.name,className:"w-24 h-24 md:w-32 md:h-32 rounded-2xl object-cover ring-4 ring-background shadow-lg"}):e.jsx("div",{className:"w-24 h-24 md:w-32 md:h-32 rounded-2xl bg-primary/20 flex items-center justify-center text-3xl font-bold text-primary ring-4 ring-background shadow-lg",children:Q}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-xs uppercase tracking-widest text-muted-foreground",children:"Prepared by"}),e.jsx("h2",{className:"text-2xl md:text-3xl font-bold mt-1",children:i.name}),(i.title||i.brokerage_name)&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:[i.title,i.brokerage_name].filter(Boolean).join(" · ")}),i.bio&&e.jsx("p",{className:"text-sm text-muted-foreground mt-3 leading-relaxed",children:i.bio}),e.jsxs("div",{className:"flex flex-wrap gap-2 mt-4",children:[te&&e.jsx($,{asChild:!0,children:e.jsxs("a",{href:te,children:[e.jsx(ka,{className:"w-4 h-4 mr-2"}),i.phone]})}),le&&e.jsx($,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:le,children:[e.jsx(pn,{className:"w-4 h-4 mr-2"}),"Email"]})}),i.website_url&&e.jsx($,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:i.website_url,target:"_blank",rel:"noreferrer",children:[e.jsx(kc,{className:"w-4 h-4 mr-2"}),"Website"]})})]})]})]})})})]}),i&&(te||fe||le)&&e.jsxs("div",{className:"md:hidden fixed bottom-0 left-0 right-0 bg-card/95 backdrop-blur border-t shadow-2xl z-50 px-3 py-3 flex gap-2",style:{paddingBottom:"calc(0.75rem + env(safe-area-inset-bottom))"},children:[te&&e.jsx($,{className:"flex-1",asChild:!0,children:e.jsxs("a",{href:te,children:[e.jsx(ka,{className:"w-4 h-4 mr-1.5"}),"Call"]})}),fe&&e.jsx($,{variant:"outline",className:"flex-1",asChild:!0,children:e.jsxs("a",{href:fe,children:[e.jsx(Vu,{className:"w-4 h-4 mr-1.5"}),"Text"]})}),le&&e.jsx($,{variant:"outline",className:"flex-1",asChild:!0,children:e.jsxs("a",{href:le,children:[e.jsx(pn,{className:"w-4 h-4 mr-1.5"}),"Email"]})})]})]})}function q4s(){const t=Tu().pathname.slice(1).replace(/\/$/,"");return!t||t.includes("/")?e.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white flex items-center justify-center p-6",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"text-2xl font-bold text-slate-800 mb-2",children:"CMA Portal"}),e.jsx("p",{className:"text-slate-500",children:"Open your CMA link to view your personalized market analysis."})]})}):e.jsx(dMt,{tokenOverride:t})}const Z7e="levelup_affiliate_ref",V4s=30,H4s=()=>{const[s]=Jc();k.useEffect(()=>{const t=s.get("ref");if(t){const n={code:t.toUpperCase(),timestamp:Date.now()};localStorage.setItem(Z7e,JSON.stringify(n)),console.log("[Affiliate] Stored referral code:",t)}},[s])},G4s=()=>{try{const s=localStorage.getItem(Z7e);if(!s)return null;const t=JSON.parse(s),n=V4s*24*60*60*1e3;return Date.now()-t.timestamp>n?(localStorage.removeItem(Z7e),console.log("[Affiliate] Referral code expired"),null):t.code}catch{return null}},SSe="/assets/levelup-logo-header-_ZX7DvlA.png",W4s="/assets/scale-your-team-ku4MPatU.png";function K4s({open:s,onOpenChange:t}){return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"max-w-3xl max-h-[90vh] overflow-hidden",children:[e.jsx(Vs,{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(Gi,{className:"h-5 w-5 text-[#4a6b6d]"})}),e.jsxs("div",{children:[e.jsx($s,{children:"Schedule a Brokerage Interest Meeting"}),e.jsx(Cr,{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 Gy={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"]}},Y4s=[{icon:mm,title:"Academy Training",description:"Access a library of on-demand video training covering lead generation, marketing, technology, and more."},{icon:gd,title:"300+ Templates",description:"Professional Canva templates for social media, flyers, postcards, and marketing materials."},{icon:ha,title:"Live Events",description:"Weekly live training sessions, workshops, and Q&A events with industry experts."},{icon:Vu,title:"Agent Community",description:"Connect with fellow agents, share wins, ask questions, and network in our private community."},{icon:ea,title:"Resource Kits",description:"Downloadable toolkits with scripts, checklists, guides, and everything you need to close more deals."},{icon:Zo,title:"Social Swag",description:"Fresh social media content and designs updated regularly to help you stand out online."}],Z4s=[{icon:Xn,title:"Contact Management",description:"Organize your sphere into relationship tiers—Top 25, Past Clients, Referral Partners, and more."},{icon:kn,title:"Smart Touchpoint Plans",description:"Automated action plans that tell you exactly who to contact and how, based on relationship type."},{icon:ka,title:"One-Tap Actions",description:"Call, text, or email contacts directly with pre-written scripts tailored to each relationship."},{icon:ip,title:"Birthday & Anniversary Alerts",description:"Never miss an important date—get reminders for birthdays and home anniversaries."},{icon:Si,title:"Pop-by Map",description:"See all your contacts on a map and plan efficient pop-by routes in your area."},{icon:Ul,title:"Momentum Tracking",description:"Track your touch streaks, weekly goals, and relationship health scores."},{icon:Bo,title:"Relationship Health",description:"Visual dashboard showing which contacts need attention based on last touch date."},{icon:ix,title:"Daily Action Cards",description:"Wake up to a prioritized list of exactly who to reach out to today."}],X4s=[{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."}],Q4s=()=>{const{user:s,loading:t}=ks(),n=Jn(),[r]=Jc();k.useEffect(()=>{const I=window.location.host==="listings.relevelup.com",P=window.location.pathname==="/";if(I&&P){n("/public/listings",{replace:!0});return}},[n]);const[a,i]=k.useState(null),[l,o]=k.useState(null),[c,d]=k.useState(!1),[u,h]=k.useState(""),[m,p]=k.useState(""),[g,x]=k.useState(""),[y,v]=k.useState(!1),[_,j]=k.useState(!1),C=(I,P=!1)=>{o({tier:I,skipTrial:P}),d(!0)};H4s(),k.useEffect(()=>{const I=window.location.host==="listings.relevelup.com",P=location.pathname.startsWith("/public/");!t&&s&&!I&&!P&&n("/dashboard")},[s,t,n,location.pathname]),k.useEffect(()=>{r.get("canceled")==="true"&&ae.error("Checkout was canceled. Feel free to try again when you're ready!")},[r]);const A=async(I,P=!1)=>{if(!u){ae.error("Please enter your email address");return}if(!m.trim()){ae.error("Please enter your full name");return}v(!0),i(I+(P?"_direct":""));const R=G4s();try{const{data:O,error:B}=await V.functions.invoke("create-checkout",{body:{tier:I,email:u,name:m.trim(),couponCode:g.trim()||void 0,skipTrial:P,referralCode:R}});if(B)throw B;if(O!=null&&O.url)window.open(O.url,"_blank","noopener,noreferrer"),ae.success("Checkout opened in a new tab");else throw new Error("No checkout URL returned")}catch(O){console.error("Checkout error:",O),ae.error(O.message||"Failed to start checkout. Please try again.")}finally{v(!1),i(null),d(!1),o(null)}},M=()=>{l&&A(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:SSe,alt:"LevelUp",className:"h-8 md:h-10"})}),e.jsxs("div",{className:"flex items-center gap-2 md:gap-4",children:[e.jsx($,{variant:"ghost",className:"text-white/90 hover:text-white hover:bg-white/10 hidden sm:inline-flex",onClick:()=>{var I;return(I=document.getElementById("features"))==null?void 0:I.scrollIntoView({behavior:"smooth"})},children:"Features"}),e.jsx($,{variant:"ghost",className:"text-white/90 hover:text-white hover:bg-white/10 hidden sm:inline-flex",onClick:()=>{var I;return(I=document.getElementById("pricing"))==null?void 0:I.scrollIntoView({behavior:"smooth"})},children:"Pricing"}),e.jsx($,{onClick:()=>n("/auth"),className:"bg-white text-[#4a6b6d] hover:bg-gray-100 font-medium shadow-md",children:"Sign In"})]})]})}),e.jsxs("section",{className:"relative pt-24 pb-20 bg-gradient-to-br from-[#1e3a4c] via-[#2a4f5f] to-[#3d6b6b] overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0 opacity-10",children:e.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiNmZmZmZmYiIGZpbGwtb3BhY2l0eT0iMC40Ij48cGF0aCBkPSJNMzYgMzRoLTJ2LTRoMnY0em0wLTZ2LTRoLTJ2NGgyem0tNiA2aC0ydi00aDJ2NHptMC02di00aC0ydjRoMnoiLz48L2c+PC9nPjwvc3ZnPg==')]"})}),e.jsx("div",{className:"container mx-auto px-4 relative",children:e.jsxs("div",{className:"max-w-5xl mx-auto text-center space-y-8",children:[e.jsx("div",{className:"flex justify-center mb-8",children:e.jsx("img",{alt:"LevelUp Consulting Group",className:"h-[136px] md:h-[164px] drop-shadow-lg",src:"/lovable-uploads/3a0c7ef9-9e79-411f-a9af-6f2a99e8bd7b.webp"})}),e.jsxs("p",{className:"text-lg text-white/80 max-w-3xl mx-auto leading-relaxed font-sans font-bold md:text-4xl",children:["The tools you need to get it done.",e.jsx("br",{}),e.jsx("em",{children:"The platform you need to keep it going."})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4 justify-center items-center pt-4",children:[e.jsxs($,{size:"lg",onClick:()=>{var I;return(I=document.getElementById("free-trial"))==null?void 0:I.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(xi,{className:"ml-2 w-5 h-5 group-hover:translate-x-1 transition-transform"})]}),e.jsx($,{size:"lg",variant:"outline",onClick:()=>{var I;return(I=document.getElementById("features"))==null?void 0:I.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($,{size:"lg",variant:"outline",onClick:()=>{var I;return(I=document.getElementById("brokerage"))==null?void 0:I.scrollIntoView({behavior:"smooth"})},className:"border-[#4a6b6d] text-[#4a6b6d] hover:bg-[#4a6b6d]/5",children:[e.jsx(Gi,{className:"mr-2 h-5 w-5"}),"Brokerage Partnership"]}),e.jsxs($,{size:"lg",onClick:()=>{var I;return(I=document.getElementById("pricing"))==null?void 0:I.scrollIntoView({behavior:"smooth"})},className:"bg-[#4a6b6d] hover:bg-[#3d5a5c]",children:[e.jsx(el,{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:Y4s.map((I,P)=>e.jsxs(we,{className:"group relative overflow-hidden border hover:border-[#4a6b6d]/50 transition-all duration-300 hover:shadow-lg bg-background",children:[e.jsxs(Vt,{children:[e.jsx("div",{className:"w-14 h-14 rounded-2xl bg-[#4a6b6d]/10 flex items-center justify-center mb-4",children:e.jsx(I.icon,{className:"w-7 h-7 text-[#4a6b6d]"})}),e.jsx(Yt,{className:"text-xl font-sans",children:I.title})]}),e.jsx(De,{children:e.jsx("p",{className:"text-muted-foreground leading-relaxed",children:I.description})})]},P))})]})}),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(kn,{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:Z4s.map((I,P)=>e.jsxs(we,{className:"group relative overflow-hidden border-0 bg-white/10 backdrop-blur-sm hover:bg-white/20 transition-all duration-300",children:[e.jsxs(Vt,{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(I.icon,{className:"w-6 h-6 text-white"})}),e.jsx(Yt,{className:"text-lg font-semibold text-white",children:I.title})]}),e.jsx(De,{children:e.jsx("p",{className:"text-white/70 text-sm leading-relaxed",children:I.description})})]},P))}),e.jsx("div",{className:"text-center mt-12",children:e.jsxs($,{size:"lg",onClick:()=>{var I;return(I=document.getElementById("pricing"))==null?void 0:I.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(xi,{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(Gi,{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((I,P)=>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(ma,{className:"w-4 h-4 text-[#4a6b6d]"})}),e.jsx("span",{className:"text-foreground",children:I})]},P))}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3 mt-4",children:[e.jsxs($,{size:"lg",onClick:()=>{var I;return(I=document.getElementById("pricing"))==null?void 0:I.scrollIntoView({behavior:"smooth"})},className:"bg-[#4a6b6d] hover:bg-[#3d5a5c]",children:["See Brokerage Plans",e.jsx(fi,{className:"ml-2 w-5 h-5"})]}),e.jsxs($,{size:"lg",variant:"outline",onClick:()=>j(!0),className:"border-[#4a6b6d] text-[#4a6b6d] hover:bg-[#4a6b6d]/10",children:[e.jsx(ha,{className:"mr-2 w-5 h-5"}),"Schedule Info Session"]})]})]}),e.jsx("div",{className:"relative hidden md:block",children:e.jsx("img",{src:W4s,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:X4s.map((I,P)=>e.jsx(we,{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(R=>e.jsx(ri,{className:"w-5 h-5 fill-yellow-400 text-yellow-400"},R))}),e.jsxs("p",{className:"text-lg mb-6 italic text-muted-foreground",children:['"',I.quote,'"']}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold",children:I.name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:I.role})]})]})},P))})]})}),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($,{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:()=>C("individual_agent"),children:["Start Free Trial",e.jsx(xi,{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(we,{className:"relative flex flex-col border hover:border-[#4a6b6d]/50 transition-all hover:shadow-xl bg-background",children:[e.jsxs(Vt,{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(el,{className:"w-5 h-5 text-[#4a6b6d]"})}),e.jsx(Yt,{className:"text-xl font-sans",children:Gy.individual_agent.name})]}),e.jsxs("div",{className:"flex items-baseline gap-1 mt-4",children:[e.jsx("span",{className:"text-5xl font-bold",children:Gy.individual_agent.price}),e.jsx("span",{className:"text-muted-foreground text-lg",children:Gy.individual_agent.period})]}),e.jsx(vr,{className:"text-base mt-2",children:Gy.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(sa,{className:"w-4 h-4"}),Gy.individual_agent.trial]})]}),e.jsx(De,{className:"flex-1 pt-0",children:e.jsx("ul",{className:"space-y-3",children:Gy.individual_agent.features.map((I,P)=>e.jsxs("li",{className:"flex items-center gap-3",children:[e.jsx(ma,{className:"w-5 h-5 text-[#4a6b6d] flex-shrink-0"}),e.jsx("span",{children:I})]},P))})}),e.jsxs(pY,{className:"flex flex-col gap-3 pt-4",children:[e.jsx($,{className:"w-full py-6 text-lg bg-[#4a6b6d] hover:bg-[#3d5a5c]",onClick:()=>C("individual_agent"),children:"Start Free Trial"}),e.jsx($,{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:()=>C("individual_agent",!0),children:"Skip Trial, Subscribe Now"})]})]}),e.jsxs(we,{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(Vt,{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(Gi,{className:"w-5 h-5 text-[#4a6b6d]"})}),e.jsxs("div",{children:[e.jsx(Yt,{className:"text-xl font-sans",children:Gy.brokerage_under_25.name}),e.jsx("span",{className:"text-sm text-muted-foreground",children:Gy.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:Gy.brokerage_under_25.price}),e.jsx("span",{className:"text-muted-foreground text-lg",children:Gy.brokerage_under_25.period})]}),e.jsx(vr,{className:"text-base mt-2",children:Gy.brokerage_under_25.description})]}),e.jsx(De,{className:"flex-1 pt-0",children:e.jsx("ul",{className:"space-y-3",children:Gy.brokerage_under_25.features.map((I,P)=>e.jsxs("li",{className:"flex items-center gap-3",children:[e.jsx(ma,{className:"w-5 h-5 text-[#4a6b6d] flex-shrink-0"}),e.jsx("span",{children:I})]},P))})}),e.jsx(pY,{className:"pt-4",children:e.jsx($,{className:"w-full py-6 text-lg shadow-lg bg-[#4a6b6d] hover:bg-[#3d5a5c]",onClick:()=>C("brokerage_under_25"),children:"Get Started"})})]}),e.jsxs(we,{className:"relative flex flex-col border hover:border-[#4a6b6d]/50 transition-all hover:shadow-xl bg-background",children:[e.jsxs(Vt,{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(Gi,{className:"w-5 h-5 text-[#4a6b6d]"})}),e.jsxs("div",{children:[e.jsx(Yt,{className:"text-xl font-sans",children:Gy.brokerage_over_25.name}),e.jsx("span",{className:"text-sm text-muted-foreground",children:Gy.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:Gy.brokerage_over_25.price}),e.jsx("span",{className:"text-muted-foreground text-lg",children:Gy.brokerage_over_25.period})]}),e.jsx(vr,{className:"text-base mt-2",children:Gy.brokerage_over_25.description})]}),e.jsx(De,{className:"flex-1 pt-0",children:e.jsx("ul",{className:"space-y-3",children:Gy.brokerage_over_25.features.map((I,P)=>e.jsxs("li",{className:"flex items-center gap-3",children:[e.jsx(ma,{className:"w-5 h-5 text-[#4a6b6d] flex-shrink-0"}),e.jsx("span",{children:I})]},P))})}),e.jsx(pY,{className:"pt-4",children:e.jsx($,{className:"w-full py-6 text-lg bg-[#4a6b6d] hover:bg-[#3d5a5c]",onClick:()=>C("brokerage_over_25"),children:"Get Started"})})]})]})]})}),e.jsx("section",{id:"neutrality",className:"py-20 bg-background",children:e.jsx("div",{className:"container mx-auto px-4",children:e.jsxs("div",{className:"max-w-4xl mx-auto",children:[e.jsxs("div",{className:"text-center mb-12",children:[e.jsxs("div",{className:"inline-flex items-center gap-2 px-4 py-2 rounded-full bg-[#4a6b6d]/10 text-[#4a6b6d] text-sm font-medium mb-4",children:[e.jsx(Ng,{className:"w-4 h-4"}),"Our Commitment"]}),e.jsxs("h2",{className:"text-3xl md:text-4xl font-sans font-bold",children:["LevelUp Brokerage ",e.jsx("span",{className:"italic text-[#4a6b6d]",children:"Neutrality Policy"})]}),e.jsx("p",{className:"text-lg text-muted-foreground mt-4 max-w-2xl mx-auto",children:"We are committed to being a trusted, independent partner for every agent and brokerage."})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[e.jsx(we,{className:"border-[#4a6b6d]/20 bg-[#4a6b6d]/[0.03]",children:e.jsxs(De,{className:"p-6 flex items-start gap-4",children:[e.jsx("div",{className:"w-10 h-10 rounded-lg bg-[#4a6b6d]/10 flex items-center justify-center shrink-0",children:e.jsx(Gi,{className:"w-5 h-5 text-[#4a6b6d]"})}),e.jsx("p",{className:"text-foreground font-medium leading-relaxed",children:"LevelUp serves all brokerages."})]})}),e.jsx(we,{className:"border-[#4a6b6d]/20 bg-[#4a6b6d]/[0.03]",children:e.jsxs(De,{className:"p-6 flex items-start gap-4",children:[e.jsx("div",{className:"w-10 h-10 rounded-lg bg-[#4a6b6d]/10 flex items-center justify-center shrink-0",children:e.jsx(fu,{className:"w-5 h-5 text-[#4a6b6d]"})}),e.jsx("p",{className:"text-foreground font-medium leading-relaxed",children:"LevelUp does not share member information with any brokerage."})]})}),e.jsx(we,{className:"border-[#4a6b6d]/20 bg-[#4a6b6d]/[0.03]",children:e.jsxs(De,{className:"p-6 flex items-start gap-4",children:[e.jsx("div",{className:"w-10 h-10 rounded-lg bg-[#4a6b6d]/10 flex items-center justify-center shrink-0",children:e.jsx(ck,{className:"w-5 h-5 text-[#4a6b6d]"})}),e.jsx("p",{className:"text-foreground font-medium leading-relaxed",children:"LevelUp does not recruit brokerage partners' agents."})]})}),e.jsx(we,{className:"border-[#4a6b6d]/20 bg-[#4a6b6d]/[0.03]",children:e.jsxs(De,{className:"p-6 flex items-start gap-4",children:[e.jsx("div",{className:"w-10 h-10 rounded-lg bg-[#4a6b6d]/10 flex items-center justify-center shrink-0",children:e.jsx(ea,{className:"w-5 h-5 text-[#4a6b6d]"})}),e.jsx("p",{className:"text-foreground font-medium leading-relaxed",children:"LevelUp does not use LevelUp events, trainings, webinars, CRM data, or member lists for recruiting purposes."})]})})]})]})})}),e.jsxs("section",{className:"py-20 bg-gradient-to-br from-[#1e3a4c] via-[#2a4f5f] to-[#3d6b6b] relative overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0 opacity-10",children:e.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiNmZmZmZmYiIGZpbGwtb3BhY2l0eT0iMC40Ij48cGF0aCBkPSJNMzYgMzRoLTJ2LTRoMnY0em0wLTZ2LTRoLTJ2NGgyem0tNiA2aC0ydi00aDJ2NHptMC02di00aC0ydjRoMnoiLz48L2c+PC9nPjwvc3ZnPg==')]"})}),e.jsx("div",{className:"container mx-auto px-4 relative",children:e.jsxs("div",{className:"max-w-4xl mx-auto text-center space-y-8",children:[e.jsx("h2",{className:"text-3xl text-white font-sans md:text-5xl",children:"Ready to Level Up?"}),e.jsx("p",{className:"text-lg text-white/80 max-w-2xl mx-auto",children:"Join thousands of agents who are closing more deals, saving time, and growing their business with LevelUp."}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4 justify-center",children:[e.jsxs($,{size:"lg",onClick:()=>{var I;return(I=document.getElementById("pricing"))==null?void 0:I.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(xi,{className:"ml-2 w-5 h-5"})]}),e.jsx($,{size:"lg",onClick:()=>n("/auth"),className:"px-10 py-7 text-lg font-semibold border-2 border-white text-white bg-transparent hover:bg-white hover:text-[#4a6b6d]",children:"Sign In"})]})]})})]}),e.jsx("footer",{className:"py-12 bg-[#3d5a5c] text-white/80",children:e.jsx("div",{className:"container mx-auto px-4",children:e.jsxs("div",{className:"flex flex-col md:flex-row items-center justify-between gap-4",children:[e.jsx("img",{src:SSe,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(K4s,{open:_,onOpenChange:j}),e.jsx(zs,{open:c,onOpenChange:d,children:e.jsxs(Rs,{className:"sm:max-w-md",children:[e.jsxs(Vs,{children:[e.jsx($s,{className:"text-xl font-sans font-semibold",children:"Enter your details to get started"}),e.jsx(Cr,{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(re,{htmlFor:"dialog-name",children:["Full Name ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(be,{id:"dialog-name",type:"text",placeholder:"John Smith",value:m,onChange:I=>p(I.target.value),className:"mt-1",required:!0})]}),e.jsxs("div",{children:[e.jsxs(re,{htmlFor:"dialog-email",children:["Email Address ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(be,{id:"dialog-email",type:"email",placeholder:"you@example.com",value:u,onChange:I=>h(I.target.value),className:"mt-1",required:!0})]}),e.jsxs("div",{children:[e.jsxs(re,{htmlFor:"dialog-coupon",children:["Discount Code ",e.jsx("span",{className:"text-muted-foreground",children:"(Optional)"})]}),e.jsx(be,{id:"dialog-coupon",type:"text",placeholder:"Enter discount code",value:g,onChange:I=>x(I.target.value),className:"mt-1"})]})]}),e.jsx($,{className:"w-full py-6 text-lg bg-[#4a6b6d] hover:bg-[#3d5a5c]",onClick:M,disabled:y,children:y?"Loading...":"Continue to Checkout"})]})})]})},Ect=()=>e.jsxs(e.Fragment,{children:[e.jsxs(Sc,{children:[e.jsx("title",{children:"Privacy Policy | LevelUp"}),e.jsx("meta",{name:"description",content:"Privacy Policy for LevelUp platform"})]}),e.jsx("div",{className:"min-h-screen bg-background py-12 px-4 sm:px-6 lg:px-8",children:e.jsxs("div",{className:"max-w-3xl mx-auto",children:[e.jsx("h1",{className:"text-3xl font-bold text-foreground mb-8",children:"Privacy Policy"}),e.jsxs("div",{className:"prose prose-sm max-w-none text-muted-foreground space-y-6",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Last updated: January 17, 2026"}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"1. Introduction"}),e.jsx("p",{children:'Welcome to LevelUp ("we," "our," or "us"). We are committed to protecting your personal information and your right to privacy. This Privacy Policy explains how we collect, use, disclose, and safeguard your information when you use our platform.'})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"2. Information We Collect"}),e.jsx("p",{children:"We collect information that you provide directly to us, including:"}),e.jsxs("ul",{className:"list-disc pl-6 mt-2 space-y-1",children:[e.jsx("li",{children:"Name and contact information (email address, phone number)"}),e.jsx("li",{children:"Account credentials"}),e.jsx("li",{children:"Profile information"}),e.jsx("li",{children:"Transaction and billing information"}),e.jsx("li",{children:"Communications you send to us"})]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"3. How We Use Your Information"}),e.jsx("p",{children:"We use the information we collect to:"}),e.jsxs("ul",{className:"list-disc pl-6 mt-2 space-y-1",children:[e.jsx("li",{children:"Provide, maintain, and improve our services"}),e.jsx("li",{children:"Process transactions and send related information"}),e.jsx("li",{children:"Send you technical notices and support messages"}),e.jsx("li",{children:"Respond to your comments and questions"}),e.jsx("li",{children:"Communicate with you about products, services, and events"})]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"4. Information Sharing"}),e.jsx("p",{children:"We do not sell, trade, or otherwise transfer your personal information to third parties without your consent, except as described in this policy or as required by law."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"5. Data Security"}),e.jsx("p",{children:"We implement appropriate technical and organizational measures to protect the security of your personal information. However, no method of transmission over the Internet is 100% secure."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"6. Your Rights"}),e.jsx("p",{children:"You have the right to:"}),e.jsxs("ul",{className:"list-disc pl-6 mt-2 space-y-1",children:[e.jsx("li",{children:"Access your personal information"}),e.jsx("li",{children:"Correct inaccurate data"}),e.jsx("li",{children:"Request deletion of your data"}),e.jsx("li",{children:"Opt-out of marketing communications"})]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"7. SMS / Text Messaging Program & Mobile Information"}),e.jsx("p",{children:"Your privacy is important to us. This section outlines how we collect, use, and protect your information when you use our services, including our SMS/text messaging program."}),e.jsxs("p",{className:"mt-3",children:[e.jsx("strong",{className:"text-foreground",children:"Information We Collect:"})," We collect personal information you provide, including your name, email address, phone number, and mobile number when you opt in to receive text messages from us."]}),e.jsxs("p",{className:"mt-3",children:[e.jsx("strong",{className:"text-foreground",children:"How We Use Your Information:"})," If you opt in, we use your mobile number to send SMS account notifications, real-time lead alerts, service updates, and customer support communications related to your LevelUp account."]}),e.jsxs("p",{className:"mt-3",children:[e.jsx("strong",{className:"text-foreground",children:"No Sharing of Mobile Information:"})," No mobile information will be shared with third parties/affiliates for marketing/promotional purposes. All the above categories exclude text messaging originator opt-in data and consent; this information will not be shared with any third parties."]}),e.jsxs("p",{className:"mt-3",children:[e.jsx("strong",{className:"text-foreground",children:"Your Rights:"})," You have the right to access, modify, or delete your personal information at any time. You may opt out of text messages at any time by replying STOP to any message. Reply HELP for help. Message and data rates may apply. Message frequency varies."]}),e.jsxs("p",{className:"mt-3",children:["For questions about this policy, contact us at"," ",e.jsx("a",{href:"mailto:support@relevelup.com",className:"text-primary hover:underline",children:"support@relevelup.com"}),"."]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"8. Third-Party Services"}),e.jsx("p",{children:"Our platform may integrate with third-party services such as Facebook and Instagram for social media posting features. When you connect these accounts, you are subject to their respective privacy policies."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"10. SMS Privacy Policy"}),e.jsx("p",{children:"We collect contact information you provide to us, including your name, email address, phone number, and business details, in order to provide our services, respond to inquiries, and deliver requested communications."}),e.jsx("p",{className:"mt-3",children:"If you choose to opt in to SMS communications from LevelUp, we may send you text messages including account notifications, real-time lead alerts, service updates, and customer support communications related to your LevelUp account."}),e.jsx("p",{className:"mt-3",children:"SMS consent is not shared with third parties or affiliates for marketing purposes. Mobile information will not be shared with third parties or affiliates for marketing or promotional purposes. Text messaging originator opt-in data and consent will not be shared with any third parties, except with vendors, aggregators, and providers that help us deliver these text messages."}),e.jsx("p",{className:"mt-3",children:"Message frequency may vary depending on your activity and use of our services. Message and data rates may apply."}),e.jsxs("p",{className:"mt-3",children:["You can opt out at any time by replying STOP. For help, reply HELP or contact us at"," ",e.jsx("a",{href:"mailto:hello@relevelup.com",className:"text-primary hover:underline",children:"hello@relevelup.com"}),"."]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"11. Contact Us"}),e.jsxs("p",{children:["If you have questions about this Privacy Policy, please contact us at"," ",e.jsx("a",{href:"mailto:support@relevelup.com",className:"text-primary hover:underline",children:"support@relevelup.com"})]})]})]})]})})]}),Tct=()=>e.jsxs(e.Fragment,{children:[e.jsxs(Sc,{children:[e.jsx("title",{children:"Terms of Service | LevelUp"}),e.jsx("meta",{name:"description",content:"Terms of Service for LevelUp platform"})]}),e.jsx("div",{className:"min-h-screen bg-background py-12 px-4 sm:px-6 lg:px-8",children:e.jsxs("div",{className:"max-w-3xl mx-auto",children:[e.jsx("h1",{className:"text-3xl font-bold text-foreground mb-8",children:"Terms of Service"}),e.jsxs("div",{className:"prose prose-sm max-w-none text-muted-foreground space-y-6",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Last updated: January 17, 2026"}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"1. Acceptance of Terms"}),e.jsx("p",{children:'By accessing or using the LevelUp platform ("Service"), you agree to be bound by these Terms of Service. If you do not agree to these terms, please do not use our Service.'})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"2. Description of Service"}),e.jsx("p",{children:"LevelUp provides a platform for real estate professionals to access training, resources, marketing tools, and community features. We reserve the right to modify or discontinue the Service at any time."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"3. User Accounts"}),e.jsx("p",{children:"To use certain features, you must create an account. You agree to:"}),e.jsxs("ul",{className:"list-disc pl-6 mt-2 space-y-1",children:[e.jsx("li",{children:"Provide accurate and complete information"}),e.jsx("li",{children:"Maintain the security of your account credentials"}),e.jsx("li",{children:"Notify us immediately of any unauthorized access"}),e.jsx("li",{children:"Accept responsibility for all activities under your account"})]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"4. Acceptable Use"}),e.jsx("p",{children:"You agree not to:"}),e.jsxs("ul",{className:"list-disc pl-6 mt-2 space-y-1",children:[e.jsx("li",{children:"Violate any applicable laws or regulations"}),e.jsx("li",{children:"Infringe on the rights of others"}),e.jsx("li",{children:"Upload malicious code or interfere with the Service"}),e.jsx("li",{children:"Attempt to gain unauthorized access to any part of the Service"}),e.jsx("li",{children:"Use the Service for any unlawful purpose"})]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"5. Intellectual Property"}),e.jsx("p",{children:"The Service and its original content, features, and functionality are owned by LevelUp and are protected by international copyright, trademark, and other intellectual property laws."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"6. Third-Party Integrations"}),e.jsx("p",{children:"Our Service may integrate with third-party platforms such as Facebook and Instagram. Your use of these integrations is subject to the terms and policies of those third parties. We are not responsible for the content or practices of any third-party services."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"7. Payment Terms"}),e.jsx("p",{children:"Certain features may require payment. By subscribing to paid features, you agree to pay all applicable fees. All payments are non-refundable unless otherwise specified."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"8. Limitation of Liability"}),e.jsx("p",{children:"To the maximum extent permitted by law, LevelUp shall not be liable for any indirect, incidental, special, consequential, or punitive damages resulting from your use of the Service."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"9. Termination"}),e.jsx("p",{children:"We may terminate or suspend your account at any time, without prior notice, for conduct that we believe violates these Terms or is harmful to other users, us, or third parties."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"10. Changes to Terms"}),e.jsx("p",{children:"We reserve the right to modify these Terms at any time. We will notify you of significant changes by posting a notice on our platform. Continued use of the Service constitutes acceptance of the modified terms."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"11. SMS / Text Messaging Terms"}),e.jsxs("div",{className:"rounded-lg border border-primary/30 bg-primary/5 p-4 mb-4 text-sm",children:[e.jsx("strong",{children:"To opt in:"})," Submit our public SMS opt-in form at"," ",e.jsx("a",{href:"/sms-opt-in",className:"text-primary hover:underline font-medium",children:"/sms-opt-in"})," ","— consent is captured with timestamp and the exact disclosure text shown below."]}),e.jsx("p",{children:"By opting in to receive text messages from LevelUp, you agree to the following terms:"}),e.jsx("p",{className:"mt-2",children:"You consent to receive recurring SMS/MMS messages from LevelUp, including account notifications, real-time lead alerts, service updates, and customer support communications. Message frequency varies. Message and data rates may apply. Consent is not a condition of purchase."}),e.jsxs("p",{className:"mt-2",children:["You may opt out at any time by replying STOP to any message. After opting out, you will receive a confirmation message and no further messages will be sent. For assistance, reply HELP or contact us at"," ",e.jsx("a",{href:"mailto:support@relevelup.com",className:"text-primary hover:underline",children:"support@relevelup.com"}),"."]}),e.jsxs("p",{className:"mt-2",children:["No mobile information will be shared with third parties or affiliates for marketing or promotional purposes. Text messaging originator opt-in data and consent will not be shared with any third parties. See our"," ",e.jsx("a",{href:"/privacy-policy",className:"text-primary hover:underline",children:"Privacy Policy"})," ","for full details."]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"12. Contact Us"}),e.jsxs("p",{children:["If you have questions about these Terms, please contact us at"," ",e.jsx("a",{href:"mailto:support@relevelup.com",className:"text-primary hover:underline",children:"support@relevelup.com"})]})]})]})]})})]}),J4s=()=>e.jsxs(e.Fragment,{children:[e.jsxs(Sc,{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"})]})]})]})]})})]}),Mct="I agree to receive recurring SMS/MMS messages from LevelUp, including account notifications, real-time lead alerts, service updates, and customer support communications. Message frequency varies. Message and data rates may apply. Reply STOP to opt out and HELP for help. Consent is not a condition of purchase.",eCs=t4({name:uc().trim().min(1,"Name is required").max(200),phone:uc().trim().min(10,"Enter a valid mobile number").max(30).regex(/^[+\d\s()\-.]+$/,"Enter a valid mobile number"),email:uc().trim().email("Enter a valid email").max(320).optional().or(c0(""))});function tCs(){const[s,t]=k.useState(""),[n,r]=k.useState(""),[a,i]=k.useState(""),[l,o]=k.useState(!1),[c,d]=k.useState(!1),[u,h]=k.useState(!1),[m,p]=k.useState(!1),g=Jn(),x=async y=>{var j;if(y.preventDefault(),!l){ae.error("Please check the consent box to opt in.");return}const v=eCs.safeParse({name:s,phone:n,email:a});if(!v.success){ae.error(((j=v.error.issues[0])==null?void 0:j.message)??"Please check your inputs.");return}d(!0);const{error:_}=await V.from("sms_opt_in_consents").insert({name:v.data.name,phone:v.data.phone,email:v.data.email||null,consent_text:Mct,source:"web_form",user_agent:navigator.userAgent.slice(0,500)});if(d(!1),_){ae.error("Something went wrong. Please try again.");return}h(!0)};return e.jsxs("div",{className:"min-h-screen bg-gradient-to-br from-background via-background to-muted/30 py-10 px-4",children:[e.jsxs(Sc,{children:[e.jsx("title",{children:"SMS Opt-In | LevelUp"}),e.jsx("meta",{name:"description",content:"Opt in to receive SMS account notifications and real-time lead alerts from LevelUp. Review consent terms, message frequency, and STOP/HELP instructions."}),e.jsx("link",{rel:"canonical",href:"https://dashboard.relevelup.com/sms-opt-in"})]}),e.jsxs("div",{className:"max-w-2xl mx-auto",children:[e.jsxs("header",{className:"text-center mb-8",children:[e.jsx("div",{className:"inline-flex items-center justify-center w-14 h-14 rounded-2xl bg-primary/10 text-primary mb-4",children:e.jsx(bo,{className:"w-7 h-7"})}),e.jsx("h1",{className:"text-3xl md:text-4xl font-bold tracking-tight",children:"LevelUp — SMS Opt-In"}),e.jsx("p",{className:"text-muted-foreground mt-3 max-w-xl mx-auto",children:"Sign up to receive SMS account notifications and real-time lead alerts from LevelUp. These messages help subscribed real estate agents review and respond to new consumer inquiries submitted through their websites."})]}),e.jsx("div",{className:"mb-6 rounded-lg border border-primary/30 bg-primary/5 p-4 text-center",children:e.jsx("p",{className:"text-sm font-medium",children:"SMS notifications are optional. You may use LevelUp without providing a mobile number or consenting to text messages."})}),m?e.jsxs(we,{className:"p-8 text-center",children:[e.jsx(Gr,{className:"w-14 h-14 text-primary mx-auto mb-4"}),e.jsx("h2",{className:"text-2xl font-semibold mb-2",children:"No text messages — you're all set"}),e.jsx("p",{className:"text-muted-foreground",children:"You declined SMS notifications. No mobile number or consent was recorded, and you can continue using LevelUp normally."}),e.jsx($,{className:"mt-6",onClick:()=>g("/auth"),children:"Continue to LevelUp"})]}):u?e.jsxs(we,{className:"p-8 text-center",children:[e.jsx(Gr,{className:"w-14 h-14 text-primary mx-auto mb-4"}),e.jsx("h2",{className:"text-2xl font-semibold mb-2",children:"You're opted in!"}),e.jsxs("p",{className:"text-muted-foreground",children:["You'll now receive SMS account notifications and real-time lead alerts from LevelUp. Reply ",e.jsx("strong",{children:"STOP"})," at any time to opt out, or ",e.jsx("strong",{children:"HELP"})," for assistance."]})]}):e.jsx(we,{className:"p-6 md:p-8",children:e.jsxs("form",{onSubmit:x,className:"space-y-5",children:[e.jsxs("div",{children:[e.jsx(re,{htmlFor:"name",children:"Full Name (only if you opt in to SMS)"}),e.jsx(be,{id:"name",value:s,onChange:y=>t(y.target.value),maxLength:200,autoComplete:"name",className:"mt-1.5"})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"phone",children:"Mobile Number (only if you opt in to SMS)"}),e.jsx(be,{id:"phone",type:"tel",value:n,onChange:y=>r(y.target.value),maxLength:30,placeholder:"(555) 123-4567",autoComplete:"tel",className:"mt-1.5"})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"email",children:"Email (optional)"}),e.jsx(be,{id:"email",type:"email",value:a,onChange:y=>i(y.target.value),maxLength:320,autoComplete:"email",className:"mt-1.5"})]}),e.jsx("div",{className:"rounded-lg border bg-muted/30 p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Li,{id:"consent",checked:l,onCheckedChange:y=>o(y===!0),className:"mt-0.5"}),e.jsx(re,{htmlFor:"consent",className:"text-sm leading-relaxed font-normal cursor-pointer",children:Mct})]})}),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(nr,{to:"/terms-of-service",className:"text-primary underline underline-offset-2",children:"SMS Terms & Conditions"})," ","and"," ",e.jsx(nr,{to:"/privacy-policy",className:"text-primary underline underline-offset-2",children:"Privacy Policy"}),"."]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Message types:"})," account notifications, real-time lead alerts, service updates, customer support."," ",e.jsx("strong",{children:"Frequency:"})," varies."," ",e.jsx("strong",{children:"Msg & data rates may apply."})," ","Reply ",e.jsx("strong",{children:"STOP"})," to opt out, ",e.jsx("strong",{children:"HELP"})," for help."]}),e.jsx("p",{children:"No mobile information will be shared with third parties or affiliates for marketing or promotional purposes. Text messaging originator opt-in data and consent will not be shared with any third parties."})]}),e.jsx($,{type:"submit",disabled:!l||c,className:"w-full",size:"lg",children:c?"Submitting…":"Opt in to SMS"}),e.jsx($,{type:"button",variant:"outline",size:"lg",className:"w-full",disabled:c,onClick:()=>p(!0),children:"Skip SMS / Continue without text alerts"}),e.jsx("p",{className:"text-xs text-center text-muted-foreground",children:"Skipping records no consent and does not limit your access to LevelUp."}),e.jsxs("div",{className:"flex items-center justify-center gap-2 text-xs text-muted-foreground pt-2",children:[e.jsx(b0,{className:"w-3.5 h-3.5"}),"Secure consent record stored for compliance."]})]})}),e.jsx("footer",{className:"text-center mt-8 text-xs text-muted-foreground",children:e.jsxs("p",{children:["LevelUp · Questions? Email"," ",e.jsx("a",{href:"mailto:support@relevelup.com",className:"text-primary hover:underline",children:"support@relevelup.com"})]})})]})]})}const uMt="/assets/levelup-logo-horizontal-DEFNc0ms.png",sCs=t4({email:uc().email("Invalid email address"),password:uc().min(6,"Password must be at least 6 characters")}),nCs="https://dashboard.relevelup.com",cre="/oauth-connect",dNe="levelupOAuthRouteHistory";function Pct(s){return s.startsWith("/")&&!s.startsWith("//")&&!s.includes("://")}function rCs(s){const t=Date.now(),n=15e3;try{const i=[...JSON.parse(sessionStorage.getItem(dNe)??"[]").filter(o=>t-o.ato.route));return i.length>=6&&l.has("auth")&&l.has("consent")}catch{return sessionStorage.setItem(dNe,JSON.stringify([{route:s,at:t}])),!1}}function aCs(){sessionStorage.removeItem(dNe)}const iCs=()=>{const{signIn:s,user:t,loading:n}=ks(),r=(t==null?void 0:t.id)??null,a=Jn(),[i]=Jc(),l=i.get("authorization_id")??"",o=i.get("next")??"",[c,d]=k.useState(!1),[u,h]=k.useState({}),[m,p]=k.useState(""),[g,x]=k.useState(!1),[y,v]=k.useState(!1),[_,j]=k.useState(null),C=k.useRef(!1);k.useEffect(()=>{if(l&&window.location.hostname==="tile-portal.lovable.app"){const I=new URL("/auth",nCs);I.searchParams.set("next",`${cre}?authorization_id=${encodeURIComponent(l)}`),window.location.replace(I.toString());return}if(l){const I=`${cre}?authorization_id=${encodeURIComponent(l)}`;sessionStorage.setItem("redirectAfterLogin",I);return}o&&Pct(o)&&sessionStorage.setItem("redirectAfterLogin",o)},[l,o]),k.useEffect(()=>{if(n||!r||C.current)return;const I=l?`${cre}?authorization_id=${encodeURIComponent(l)}`:sessionStorage.getItem("redirectAfterLogin")||"/dashboard";if(!Pct(I)){sessionStorage.removeItem("redirectAfterLogin"),C.current=!0,a("/dashboard",{replace:!0});return}const P=I.startsWith(cre)||I.startsWith("/oauth/consent")||I.startsWith("/.lovable/oauth/consent");if(P&&rCs("auth")){j("We couldn't complete the OAuth sign-in handoff because the browser kept bouncing between sign-in and consent. Please refresh this page and try Connect again.");return}C.current=!0,P||(aCs(),sessionStorage.removeItem("redirectAfterLogin")),a(I,{replace:!0})},[l,n,a,r]);const A=async I=>{I.preventDefault(),h({}),d(!0);const P=new FormData(I.currentTarget),R=P.get("email"),O=P.get("password");try{sCs.parse({email:R,password:O}),await s(R,O)}catch(B){if(B instanceof Qxs){const U={};B.issues.forEach(G=>{G.path[0]&&(U[G.path[0]]=G.message)}),h(U)}}finally{d(!1)}},M=async()=>{if(!m){ae.error("Please enter your email address");return}x(!0);try{const{error:I}=await V.functions.invoke("send-password-reset",{body:{email:m,redirectTo:"https://dashboard.relevelup.com/profile?reset=true"}});if(I)throw I;ae.success("Password reset email sent! Check your inbox."),v(!1),p("")}catch(I){ae.error(I instanceof Error?I.message:"Failed to send reset email")}finally{x(!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(nr,{to:"/",className:"inline-flex items-center gap-2 text-sm text-white/80 hover:text-white transition-colors",children:[e.jsx(Ia,{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:uMt,alt:"LevelUp",className:"h-12 w-auto"})})}),e.jsxs(we,{className:"border-0 shadow-2xl bg-white/95 backdrop-blur-sm",children:[e.jsxs(Vt,{className:"space-y-1 text-center pb-4",children:[e.jsx(Yt,{className:"text-3xl font-bold text-[#2a4347]",style:{fontFamily:"'Libre Baskerville', serif"},children:"Welcome Back"}),e.jsx(vr,{className:"text-gray-600",children:_||"Sign in to access your dashboard"})]}),e.jsx(De,{children:e.jsxs("form",{onSubmit:A,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"signin-email",className:"text-gray-700",children:"Email"}),e.jsx(be,{id:"signin-email",name:"email",type:"email",placeholder:"your@email.com",required:!0,className:"border-gray-300 focus:border-[#4a6b6d] focus:ring-[#4a6b6d]"}),u.email&&e.jsx("p",{className:"text-sm text-red-600",children:u.email})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"signin-password",className:"text-gray-700",children:"Password"}),e.jsx(be,{id:"signin-password",name:"password",type:"password",required:!0,className:"border-gray-300 focus:border-[#4a6b6d] focus:ring-[#4a6b6d]"}),u.password&&e.jsx("p",{className:"text-sm text-red-600",children:u.password})]}),e.jsx($,{type:"submit",className:"w-full bg-[#4a6b6d] hover:bg-[#3d5a5c] text-white font-semibold py-6 text-lg transition-all duration-200 shadow-lg hover:shadow-xl",disabled:c,children:c?"Signing in...":"Sign In"}),e.jsxs(zs,{open:y,onOpenChange:v,children:[e.jsx(yl,{asChild:!0,children:e.jsx($,{variant:"link",className:"w-full text-sm text-[#4a6b6d] hover:text-[#3d5a5c]",children:"Forgot password?"})}),e.jsxs(Rs,{className:"bg-white",children:[e.jsxs(Vs,{children:[e.jsx($s,{className:"text-[#2a4347]",style:{fontFamily:"'Libre Baskerville', serif"},children:"Reset Password"}),e.jsx(Cr,{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(re,{htmlFor:"reset-email",className:"text-gray-700",children:"Email"}),e.jsx(be,{id:"reset-email",type:"email",placeholder:"your@email.com",value:m,onChange:I=>p(I.target.value),className:"border-gray-300 focus:border-[#4a6b6d] focus:ring-[#4a6b6d]"})]}),e.jsx($,{onClick:M,className:"w-full bg-[#4a6b6d] hover:bg-[#3d5a5c] text-white",disabled:g,children:g?"Sending...":"Send Reset Link"})]})]})]})]})})]}),e.jsxs("p",{className:"text-center text-white/70 text-sm mt-6",children:["Don't have an account?"," ",e.jsx(nr,{to:"/",className:"text-white hover:underline font-medium",children:"View Plans"})]})]})})]})]})},Ict=()=>V.auth.oauth,oCs="https://dashboard.relevelup.com",lCs="/oauth-connect",uNe="levelupOAuthRouteHistory",cCs="https://relzejiswnotikjgvjhz.supabase.co/auth/v1",dCs="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InJlbHplamlzd25vdGlramd2amh6Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjE5NTAzNDQsImV4cCI6MjA3NzUyNjM0NH0.dzIkIr_oFSbFE3oWS0ktIr83iKHHkZxt40Gc7SpC_mM";function uCs(s){return s.startsWith("/")&&!s.startsWith("//")&&!s.includes("://")}function hCs(s){const t=Date.now(),n=15e3;try{const i=[...JSON.parse(sessionStorage.getItem(uNe)??"[]").filter(o=>t-o.ato.route));return i.length>=6&&l.has("auth")&&l.has("consent")}catch{return sessionStorage.setItem(uNe,JSON.stringify([{route:s,at:t}])),!1}}function mCs(){sessionStorage.removeItem(uNe)}async function Lct(s,t,n){const r=await fetch(`${cCs}${s}`,{...n,headers:{Authorization:`Bearer ${t}`,apikey:dCs,"Content-Type":"application/json",...(n==null?void 0:n.headers)??{}}}),a=await r.json().catch(()=>null);return r.ok?{data:a,error:null}:{data:null,error:{message:(a==null?void 0:a.msg)??(a==null?void 0:a.message)??(a==null?void 0:a.error_description)??(a==null?void 0:a.error)??"Authorization request failed."}}}function KIe(){var x;const{user:s,session:t,loading:n}=ks(),r=(s==null?void 0:s.id)??null,a=(t==null?void 0:t.access_token)??null,[i]=Jc(),l=i.get("authorization_id")??"",[o,c]=k.useState(null),[d,u]=k.useState(null),[h,m]=k.useState(!1);k.useEffect(()=>{let y=!0;return(async()=>{if(!l){u("Missing authorization_id");return}const v=`${lCs}?authorization_id=${encodeURIComponent(l)}`;if(window.location.hostname==="tile-portal.lovable.app"){window.location.href=`${oCs}${v}`;return}if(n)return;if(!r){if(hCs("consent")){u("We couldn't complete the OAuth sign-in handoff because the browser kept bouncing between sign-in and consent. Please refresh this page and try Connect again.");return}uCs(v)&&sessionStorage.setItem("redirectAfterLogin",v),window.location.replace(`/auth?next=${encodeURIComponent(v)}`);return}if(!a)return;mCs(),sessionStorage.removeItem("redirectAfterLogin");const _=Ict(),{data:j,error:C}=_?await _.getAuthorizationDetails(l):await Lct(`/oauth/authorizations/${encodeURIComponent(l)}`,a);if(!y)return;if(C){u(C.message);return}const A=(j==null?void 0:j.redirect_url)??(j==null?void 0:j.redirect_to);if(A&&!(j!=null&&j.client)){window.location.href=A;return}c(j)})(),()=>{y=!1}},[a,l,n,r]);async function p(y){if(!(t!=null&&t.access_token)){u("Your sign-in session is not ready yet. Please refresh and try again.");return}m(!0);const v=Ict(),{data:_,error:j}=v?y?await v.approveAuthorization(l,{skipBrowserRedirect:!0}):await v.denyAuthorization(l,{skipBrowserRedirect:!0}):await Lct(`/oauth/authorizations/${encodeURIComponent(l)}/consent`,t.access_token,{method:"POST",body:JSON.stringify({action:y?"approve":"deny"})});if(j){m(!1),u(j.message);return}const C=(_==null?void 0:_.redirect_url)??(_==null?void 0:_.redirect_to);if(!C){m(!1),u("No redirect returned by the authorization server.");return}window.location.href=C}if(d)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background p-4",children:e.jsx(we,{className:"w-full max-w-md",children:e.jsxs(Vt,{children:[e.jsx(Yt,{children:"Authorization error"}),e.jsx(vr,{children:d})]})})});if(!o)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background",children:e.jsx(Jt,{className:"h-8 w-8 animate-spin text-primary"})});const g=((x=o.client)==null?void 0:x.name)??"An app";return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background p-4",children:e.jsxs(we,{className:"w-full max-w-md",children:[e.jsxs(Vt,{children:[e.jsxs(Yt,{children:["Connect ",g," to LevelUp"]}),e.jsxs(vr,{children:[g," is requesting access to use LevelUp tools on your behalf. You can revoke access at any time."]})]}),e.jsxs(De,{className:"flex gap-3 justify-end",children:[e.jsx($,{variant:"outline",disabled:h,onClick:()=>p(!1),children:"Deny"}),e.jsx($,{disabled:h,onClick:()=>p(!0),children:h?e.jsx(Jt,{className:"h-4 w-4 animate-spin"}):"Approve"})]})]})})}const Rct="https://relzejiswnotikjgvjhz.supabase.co/functions/v1/mcp",fCs="https://tile-portal.lovable.app/mcp-oauth-bridge.html",pCs=[{label:"Open ChatGPT",description:"You need ChatGPT Plus, Pro, or Team to add custom MCP connectors."},{label:"Add a new connector",description:"Settings → Connectors → Add. Choose 'Custom / MCP Server'."},{label:"Fill in the basics",description:"Name it LevelUp and add a short description like 'Tools for the LevelUp real estate platform.'"},{label:"Paste the server URL",description:"Paste the MCP server URL below into the Server URL field. Do not paste the tile-portal bridge URL."},{label:"Confirm OAuth",description:"Authentication should be OAuth. Check the 'I understand' box, then tap Create."},{label:"Sign in to LevelUp",description:"ChatGPT will open a LevelUp consent page. Sign in with your LevelUp account and tap Approve."},{label:"Start chatting",description:"Ask ChatGPT to 'list my upcoming LevelUp trainings' or 'summarize my contacts'."}];function gCs(){const[s,t]=k.useState(!1),n=async()=>{try{await navigator.clipboard.writeText(Rct),t(!0),ae.success("MCP URL copied to clipboard"),setTimeout(()=>t(!1),2e3)}catch{ae.error("Could not copy URL")}};return e.jsx(Xs,{children:e.jsxs("div",{className:"space-y-6 p-4 md:p-8 max-w-3xl mx-auto",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 rounded-lg bg-primary/10",children:e.jsx(S5,{className:"h-6 w-6 text-primary"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold tracking-tight",children:"Connect ChatGPT to LevelUp"}),e.jsx("p",{className:"text-muted-foreground",children:"Let ChatGPT use LevelUp tools while you are signed in."})]})]}),e.jsxs(we,{children:[e.jsxs(Vt,{children:[e.jsx(Yt,{children:"Use this exact MCP server URL"}),e.jsx(vr,{children:"Paste only this URL into ChatGPT's Server URL field."})]}),e.jsx(De,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("code",{className:"flex-1 block rounded-md bg-muted px-3 py-2 text-sm break-all",children:Rct}),e.jsx($,{variant:"outline",size:"icon",onClick:n,"aria-label":"Copy MCP URL",children:s?e.jsx(nl,{className:"h-4 w-4 text-green-600"}):e.jsx(Da,{className:"h-4 w-4"})})]})})]}),e.jsx(we,{className:"border-destructive/30 bg-destructive/5",children:e.jsx(De,{className:"pt-6",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsx(Gd,{className:"h-5 w-5 text-destructive shrink-0 mt-0.5"}),e.jsxs("div",{className:"space-y-2 text-sm",children:[e.jsx("p",{className:"font-semibold text-destructive",children:"Do not use the bridge URL as the Server URL."}),e.jsx("p",{className:"text-muted-foreground",children:"If ChatGPT shows “does not implement OAuth,” it means this wrong URL was pasted:"}),e.jsx("code",{className:"block rounded-md bg-background px-3 py-2 break-all text-xs",children:fCs}),e.jsx("p",{className:"text-muted-foreground",children:"Delete that plugin attempt and create a new one with the MCP server URL above."})]})]})})}),e.jsxs(we,{children:[e.jsxs(Vt,{children:[e.jsx(Yt,{children:"Quick steps"}),e.jsx(vr,{children:"ChatGPT adds MCP servers as a new plugin / custom tool. Share these steps with any agent who wants to connect."})]}),e.jsx(De,{children:e.jsx("ol",{className:"space-y-4",children:pCs.map((r,a)=>e.jsxs("li",{className:"flex gap-3",children:[e.jsx("span",{className:"flex h-6 w-6 shrink-0 items-center justify-center rounded-full bg-primary/10 text-xs font-medium text-primary",children:a+1}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:r.label}),e.jsx("p",{className:"text-sm text-muted-foreground",children:r.description})]})]},a))})})]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(Ir,{className:"h-4 w-4"}),e.jsx("span",{children:"Only basic tools are exposed today. More LevelUp actions will be added over time."})]})]})})}const xCs=()=>{const[s]=Jc(),t=s.get("tier"),n=t==null?void 0:t.includes("brokerage");return e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-background via-primary/5 to-secondary/10 flex items-center justify-center p-4",children:e.jsxs(we,{className:"max-w-lg w-full",children:[e.jsxs(Vt,{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(nl,{className:"w-10 h-10 text-green-500"})}),e.jsx(Yt,{className:"text-2xl",children:"Welcome to LevelUp!"}),e.jsx(vr,{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(pn,{className:"w-5 h-5"}),e.jsx("span",{className:"font-semibold",children:"Check your email to sign in"})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"We've sent you an email with a secure link to access your account. Click the link in your email to get started."})]}),n?e.jsxs("div",{className:"space-y-3",children:[e.jsx("h3",{className:"font-semibold",children:"What's next?"}),e.jsxs("ul",{className:"space-y-2 text-sm text-muted-foreground",children:[e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"font-bold text-primary",children:"1."}),"Click the link in your email to sign in"]}),e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"font-bold text-primary",children:"2."}),"Create and name your brokerage"]}),e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"font-bold text-primary",children:"3."}),"Set your password and complete your profile"]}),e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"font-bold text-primary",children:"4."}),"Start inviting agents to join your team"]})]})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsx("h3",{className:"font-semibold",children:"What's next?"}),e.jsxs("ul",{className:"space-y-2 text-sm text-muted-foreground",children:[e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"font-bold text-primary",children:"1."}),"Click the link in your email to sign in"]}),e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"font-bold text-primary",children:"2."}),"Set your password and complete your profile"]}),e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"font-bold text-primary",children:"3."}),"Start exploring templates, training videos, and more!"]})]}),e.jsx("p",{className:"text-sm text-green-600 font-medium mt-4",children:"🎉 Your 7-day free trial has started!"})]}),e.jsx("div",{className:"p-3 rounded-lg bg-muted/50 text-center",children:e.jsx("p",{className:"text-sm text-muted-foreground",children:"Didn't receive the email? Check your spam folder or contact support."})})]})]})})},yCs=()=>{const{user:s}=ks(),[t,n]=k.useState(!1),[r,a]=k.useState(null),[i,l]=k.useState(""),o=async h=>{var m;if(!(s!=null&&s.email)){ae.error("Please sign in to upgrade");return}n(!0),a(h);try{const{data:p,error:g}=await V.functions.invoke("create-checkout",{body:{tier:h,email:s.email,name:((m=s.user_metadata)==null?void 0:m.full_name)||s.email,couponCode:i.trim()||void 0,skipTrial:!0}});if(g)throw g;if(p!=null&&p.url)window.open(p.url,"_blank","noopener,noreferrer"),ae.success("Checkout opened in a new tab");else throw new Error("No checkout URL returned")}catch(p){console.error("Checkout error:",p),ae.error(p.message||"Failed to start checkout. Please try again.")}finally{n(!1),a(null)}},c=["Unlimited access to all marketing templates","Complete Academy training library","AI-powered tools and resources","Community forums and support","Exclusive member events and workshops","Deal pipeline & scorecard tracking","Listing exchange access","Social media content library"],d=["Everything in Individual plan","Up to 25 agent seats","Brokerage admin dashboard","Team performance analytics","Custom branding options","Priority support","Agent onboarding tools","Brokerage-wide announcements"],u=["Everything in Brokerage plan","Unlimited agent seats","Dedicated account manager","Advanced analytics & reporting","White-label options","API access","Custom integrations","Enterprise-level support"];return e.jsx(Xs,{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(re,{htmlFor:"coupon",className:"text-sm font-medium",children:"Have a discount code?"}),e.jsx(be,{id:"coupon",placeholder:"Enter discount code",value:i,onChange:h=>l(h.target.value),className:"mt-1"})]}),e.jsxs("div",{className:"grid md:grid-cols-3 gap-6 mb-8",children:[e.jsxs(we,{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(Vt,{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(Xn,{className:"h-7 w-7 text-primary"})}),e.jsx(Yt,{className:"text-xl",children:"Individual Agent"}),e.jsx(vr,{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((h,m)=>e.jsxs("li",{className:"flex items-start gap-2 text-sm",children:[e.jsx(ma,{className:"h-4 w-4 text-primary mt-0.5 shrink-0"}),e.jsx("span",{children:h})]},m))}),e.jsxs($,{className:"w-full",size:"lg",onClick:()=>o("individual_agent"),disabled:t,children:[t&&r==="individual_agent"?e.jsx(Jt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(kn,{className:"h-4 w-4 mr-2"}),"Get Started"]})]})]}),e.jsxs(we,{className:"border-2 border-amber-500/20 hover:border-amber-500/50 transition-colors",children:[e.jsxs(Vt,{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(Gi,{className:"h-7 w-7 text-amber-600"})}),e.jsx(Yt,{className:"text-xl",children:"Brokerage"}),e.jsx(vr,{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((h,m)=>e.jsxs("li",{className:"flex items-start gap-2 text-sm",children:[e.jsx(ma,{className:"h-4 w-4 text-amber-600 mt-0.5 shrink-0"}),e.jsx("span",{children:h})]},m))}),e.jsxs($,{variant:"outline",className:"w-full border-amber-500 text-amber-600 hover:bg-amber-50",size:"lg",onClick:()=>o("brokerage_under_25"),disabled:t,children:[t&&r==="brokerage_under_25"?e.jsx(Jt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Gi,{className:"h-4 w-4 mr-2"}),"Get Started"]})]})]}),e.jsxs(we,{className:"border-2 border-purple-500/20 hover:border-purple-500/50 transition-colors",children:[e.jsxs(Vt,{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(Gi,{className:"h-7 w-7 text-purple-600"})}),e.jsx(Yt,{className:"text-xl",children:"Brokerage 25+"}),e.jsx(vr,{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:u.map((h,m)=>e.jsxs("li",{className:"flex items-start gap-2 text-sm",children:[e.jsx(ma,{className:"h-4 w-4 text-purple-600 mt-0.5 shrink-0"}),e.jsx("span",{children:h})]},m))}),e.jsxs($,{variant:"outline",className:"w-full border-purple-500 text-purple-600 hover:bg-purple-50",size:"lg",onClick:()=>o("brokerage_over_25"),disabled:t,children:[t&&r==="brokerage_over_25"?e.jsx(Jt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Gi,{className:"h-4 w-4 mr-2"}),"Get Started"]})]})]})]}),e.jsx(we,{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(ka,{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(pn,{className:"h-4 w-4"}),e.jsx("span",{children:"support@relevelup.com"})]})]})]})})]})})},vCs=()=>{const{user:s,loading:t,isBrokerageManager:n,brokerageId:r}=ks(),a=Jn(),[i,l]=k.useState(""),[o,c]=k.useState(!1),[d,u]=k.useState(!1);k.useEffect(()=>{!t&&!s&&a("/auth")},[s,t,a]),k.useEffect(()=>{!t&&s&&r&&a("/profile?setup=true")},[s,t,r,a]);const h=async()=>{if(!i.trim()){ae.error("Please enter a brokerage name");return}const{data:m}=await V.auth.getSession(),p=m.session;if(!s||!p){ae.error("Please sign in again to create your brokerage."),a("/auth");return}c(!0);try{console.log("[SetupBrokerage] Creating brokerage…",{hasUser:!!s,hasSession:!!p,userId:s==null?void 0:s.id});const{data:g,error:x}=await V.functions.invoke("create-brokerage",{body:{name:i.trim()}});if(console.log("[SetupBrokerage] create-brokerage response",{data:g,error:x}),x)throw x;if(!(g!=null&&g.ok))throw new Error((g==null?void 0:g.error)||"Failed to create brokerage");c(!1),u(!0),ae.success("Brokerage created! Setting up your account..."),setTimeout(()=>{a("/profile?setup=true")},2e3)}catch(g){console.error("Error creating brokerage:",g),ae.error(g.message||"Failed to create brokerage"),c(!1)}};return t?e.jsx("div",{className:"flex min-h-screen items-center justify-center bg-background",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):d?e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-background via-primary/5 to-secondary/10 flex items-center justify-center p-4",children:e.jsxs(we,{className:"max-w-lg w-full",children:[e.jsxs(Vt,{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(Jt,{className:"w-10 h-10 text-primary animate-spin"})}),e.jsx(Yt,{className:"text-2xl",children:"Setting Up Your Brokerage"}),e.jsx(vr,{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(nl,{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(Jt,{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(we,{className:"max-w-lg w-full",children:[e.jsxs(Vt,{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(Gi,{className:"w-10 h-10 text-primary"})}),e.jsx(Yt,{className:"text-2xl",children:"Set Up Your Brokerage"}),e.jsx(vr,{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(re,{htmlFor:"brokerage-name",children:"Brokerage Name"}),e.jsx(be,{id:"brokerage-name",placeholder:"Enter your brokerage name",value:i,onChange:m=>l(m.target.value),onKeyDown:m=>m.key==="Enter"&&h()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"This is how your brokerage will appear to your agents"})]}),e.jsxs("div",{className:"p-4 rounded-lg bg-muted/50 space-y-3",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2",children:[e.jsx(Xn,{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(nl,{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(nl,{className:"w-4 h-4 text-green-500"}),"Access exclusive brokerage resources"]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx(nl,{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(nl,{className:"w-4 h-4 text-green-500"}),"Share resources with your agents"]})]})]}),e.jsxs($,{onClick:h,className:"w-full",disabled:o||!i.trim(),children:[o?"Creating...":"Create Brokerage",e.jsx(xi,{className:"w-4 h-4 ml-2"})]})]})]})})},Dct=()=>{const s=Jn(),[t,n]=k.useState("verifying"),[r,a]=k.useState("");k.useEffect(()=>{(async()=>{try{const{data:{session:o},error:c}=await V.auth.getSession();if(c)throw c;if(o!=null&&o.user){const{data:d}=await V.from("profiles").select("login_count").eq("id",o.user.id).single();if(((d==null?void 0:d.login_count)||0)>1){console.log("Account already claimed, redirecting to dashboard"),n("already_claimed");return}console.log("User logged in successfully:",o.user.email),n("success");try{await V.functions.invoke("trial-claim-hook",{body:{userId:o.user.id}})}catch(u){console.log("Trial claim hook (non-critical):",u)}setTimeout(()=>{s("/profile?setup=true")},1500)}else setTimeout(()=>{n("already_claimed")},2e3)}catch(o){console.error("Claim error:",o),n("already_claimed")}})()},[s]);const i=()=>{window.location.href="https://dashboard.relevelup.com/auth"};return e.jsx("div",{className:"flex min-h-screen items-center justify-center bg-background p-4",children:e.jsxs(we,{className:"w-full max-w-md",children:[e.jsxs(Vt,{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(Yt,{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(vr,{children:[t==="verifying"&&"Please wait while we verify your account...",t==="success"&&"Redirecting you to complete your profile...",t==="already_claimed"&&"This account has already been set up. Please log in to access your dashboard.",t==="error"&&r]})]}),(t==="already_claimed"||t==="error")&&e.jsx(De,{children:e.jsx($,{onClick:i,className:"w-full",children:"Go to Login"})})]})})},bCs=()=>{const[s,t]=k.useState(!1),n=k.useMemo(()=>new URLSearchParams(window.location.search).get("link"),[]),r=k.useMemo(()=>{if(!n)return!1;try{const i=new URL(n);return i.hostname.endsWith(".supabase.co")&&i.pathname.startsWith("/auth/v1/verify")}catch{return!1}},[n]);k.useEffect(()=>{document.title="Reset Your Password"},[]);const a=()=>{!r||!n||(t(!0),window.location.href=n)};return e.jsxs("div",{className:"min-h-screen relative overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-[#4a6b6d] via-[#3d5a5c] to-[#2a4347]"}),e.jsx("div",{className:"relative z-10 flex flex-col min-h-screen items-center justify-center p-4",children:e.jsxs("div",{className:"w-full max-w-md",children:[e.jsx("div",{className:"flex justify-center mb-8",children:e.jsx("div",{className:"bg-white rounded-xl p-4 shadow-2xl",children:e.jsx("img",{src:uMt,alt:"LevelUp",className:"h-12 w-auto"})})}),e.jsxs(we,{className:"border-0 shadow-2xl bg-white/95 backdrop-blur-sm",children:[e.jsxs(Vt,{className:"text-center",children:[e.jsx(Yt,{className:"text-2xl font-bold text-[#2a4347]",style:{fontFamily:"'Libre Baskerville', serif"},children:"Reset Your Password"}),e.jsx(vr,{className:"text-gray-600 pt-2",children:r?"Click the button below to continue resetting your password.":"This link is invalid or has expired. Please request a new password reset email."})]}),e.jsxs(De,{className:"space-y-4",children:[r?e.jsx($,{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($,{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."})]})]})]})})]})},_Cs=()=>{const s=Jn(),[t]=Jc(),[n,r]=k.useState(t.get("code")||""),[a,i]=k.useState(""),[l,o]=k.useState(""),[c,d]=k.useState(""),[u,h]=k.useState(!1),[m,p]=k.useState(!1),[g,x]=k.useState(!1),[y,v]=k.useState(!1),[_,j]=k.useState(null),[C,A]=k.useState(null),[M,I]=k.useState(null),[P,R]=k.useState(null);k.useEffect(()=>{const G=t.get("code");G&&(r(G),O(G))},[t]);const O=async G=>{x(!0);const{data:H,error:Y}=await V.from("invite_codes").select("id, code, max_uses, uses_count, expires_at, is_active, brokerage_id, trial_days").eq("code",G.toUpperCase().trim()).single();if(Y||!H){ae.error("Invalid invite code"),x(!1);return}if(!H.is_active){ae.error("This invite code is no longer active"),x(!1);return}if(H.max_uses&&H.uses_count>=H.max_uses){ae.error("This invite code has reached its maximum uses"),x(!1);return}if(H.expires_at&&new Date(H.expires_at){G.preventDefault(),O(n)},U=async G=>{var H;if(G.preventDefault(),!c.trim()){ae.error("Please enter your name");return}if(l.length<6){ae.error("Password must be at least 6 characters");return}p(!0);try{const Y=`${window.location.origin}/`,{data:se,error:ee}=await V.auth.signUp({email:a.trim(),password:l,options:{emailRedirectTo:Y,data:{name:c.trim()}}});if(ee){ee.message.includes("already registered")?ae.error("This email is already registered. Please sign in instead."):ae.error(ee.message);return}if(se.user){await V.rpc("add_default_signup_tag",{user_id:se.user.id});const oe=n.toUpperCase().trim();C?await V.functions.invoke("assign-brokerage",{body:{userId:se.user.id,brokerageId:C,inviteCode:oe}}):P?await V.functions.invoke("assign-brokerage",{body:{userId:se.user.id,trialDays:P,inviteCode:oe}}):await V.functions.invoke("assign-brokerage",{body:{userId:se.user.id,grandfathered:!0,inviteCode:oe}}),_&&await V.from("invite_codes").update({uses_count:((H=(await V.from("invite_codes").select("uses_count").eq("id",_).single()).data)==null?void 0:H.uses_count)+1}).eq("id",_),ae.success("Account created! You can now access the dashboard."),s("/dashboard")}}catch(Y){console.error("Signup error:",Y),ae.error("An unexpected error occurred")}finally{p(!1)}};return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background p-4",children:e.jsxs(we,{className:"w-full max-w-md",children:[e.jsxs(Vt,{className:"text-center",children:[e.jsx(Yt,{className:"text-2xl font-bold text-primary",children:M?`Join ${M}`:"Join LevelUp"}),e.jsx(vr,{children:y?M?`Create your account to join ${M}`:"Create your account to get started":"Enter your invite code to continue"})]}),e.jsx(De,{children:y?e.jsxs("form",{onSubmit:U,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"name",children:"Full Name"}),e.jsx(be,{id:"name",type:"text",placeholder:"John Doe",value:c,onChange:G=>d(G.target.value),required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"email",children:"Email"}),e.jsx(be,{id:"email",type:"email",placeholder:"you@example.com",value:a,onChange:G=>i(G.target.value),required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"password",children:"Password"}),e.jsxs("div",{className:"relative",children:[e.jsx(be,{id:"password",type:u?"text":"password",placeholder:"••••••••",value:l,onChange:G=>o(G.target.value),required:!0,minLength:6}),e.jsx("button",{type:"button",className:"absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground",onClick:()=>h(!u),children:u?e.jsx(x0,{className:"h-4 w-4"}):e.jsx(ba,{className:"h-4 w-4"})})]})]}),e.jsx($,{type:"submit",className:"w-full",disabled:m,children:m?e.jsxs(e.Fragment,{children:[e.jsx(Jt,{className:"mr-2 h-4 w-4 animate-spin"}),"Creating Account..."]}):"Create Account"})]}):e.jsxs("form",{onSubmit:B,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"inviteCode",children:"Invite Code"}),e.jsx(be,{id:"inviteCode",type:"text",placeholder:"Enter your invite code",value:n,onChange:G=>r(G.target.value),required:!0,autoFocus:!0})]}),e.jsx($,{type:"submit",className:"w-full",disabled:g,children:g?e.jsxs(e.Fragment,{children:[e.jsx(Jt,{className:"mr-2 h-4 w-4 animate-spin"}),"Verifying..."]}):"Verify Code"})]})})]})})},See=()=>{const{user:s,isCoach:t}=ks();return pt({queryKey:["my-coach-profile",s==null?void 0:s.id],enabled:!!s&&t,queryFn:async()=>{const{data:n,error:r}=await V.from("coaches").select("*").eq("user_id",s.id).maybeSingle();if(r)throw r;return n}})},wCs=()=>{const{data:s}=See();return pt({queryKey:["coach-roster",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await V.from("coaching_assignments").select("*").eq("coach_id",s.id).order("started_at",{ascending:!1});if(n)throw n;const r=t||[];if(r.length===0)return[];const a=r.map(o=>o.agent_id),{data:i}=await V.from("profiles").select("id, name, email, avatar_url").in("id",a),l=new Map((i||[]).map(o=>[o.id,o]));return r.map(o=>({...o,agent:l.get(o.agent_id)||null}))}})},hMt=()=>{const{user:s}=ks();return pt({queryKey:["my-coaching-assignment",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await V.from("coaching_assignments").select("*").eq("agent_id",s.id).eq("status","active").order("started_at",{ascending:!1}).limit(1);if(n)throw n;const r=(t||[])[0];if(!r)return null;const{data:a}=await V.from("coaches").select("*").eq("id",r.coach_id).maybeSingle();let i=null;if(a!=null&&a.user_id){const{data:l}=await V.from("profiles").select("id, name, email, avatar_url").eq("id",a.user_id).maybeSingle();i=l}return{...r,coach:a,coachProfile:i}}})},jCs=s=>pt({queryKey:["coaching-assignment",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await V.from("coaching_assignments").select("*").eq("id",s).maybeSingle();if(n)throw n;if(!t)return null;const{data:r}=await V.from("profiles").select("id, name, email, avatar_url").eq("id",t.agent_id).maybeSingle();return{...t,agent:r}}}),mMt=s=>pt({queryKey:["coaching-sessions",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await V.from("coaching_sessions").select("*").eq("assignment_id",s).order("scheduled_at",{ascending:!1});if(n)throw n;return t||[]}}),fMt=s=>pt({queryKey:["coaching-action-items",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await V.from("coaching_action_items").select("*").eq("assignment_id",s).order("due_date",{ascending:!0,nullsFirst:!1});if(n)throw n;return t||[]}}),NCs=[{key:"onboarding",label:"Onboarding"},{key:"active",label:"Active"},{key:"thriving",label:"Thriving"},{key:"at_risk",label:"At Risk"},{key:"graduated",label:"Graduated"}];function kCs(){const s=Jn(),{data:t,isLoading:n}=See(),{data:r=[],isLoading:a}=wCs();if(n)return e.jsx(Xs,{title:"Coaching",children:e.jsx("div",{className:"p-8",children:"Loading…"})});if(!t)return e.jsx(Xs,{title:"Coaching",children:e.jsxs("div",{className:"max-w-2xl mx-auto p-8 text-center",children:[e.jsx(Bm,{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."})]})});NCs.map(l=>({...l,items:r.filter(o=>(o.pipeline_stage||"active")===l.key)}));const i=r.filter(l=>l.status==="active").length;return e.jsx(Xs,{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(kn,{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(YIe,{icon:Bm,label:"Active agents",value:i}),e.jsx(YIe,{icon:fd,label:"This month",value:"—"}),e.jsx(YIe,{icon:iu,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($,{size:"sm",variant:"outline",onClick:()=>s("/coaching/waitlist"),children:"Waitlist"}),e.jsx($,{size:"sm",variant:"outline",onClick:()=>s("/coaching/settings"),children:"Profile Settings"}),e.jsx($,{size:"sm",variant:"outline",onClick:()=>s("/coaching/billing"),children:"Billing & Packages"})]})]}),a?e.jsx("div",{className:"text-muted-foreground",children:"Loading roster…"}):r.length===0?e.jsx(we,{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:r.map(l=>{var o,c,d,u;return e.jsx(we,{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(Wa,{className:"h-14 w-14",children:[e.jsx(eo,{src:((o=l.agent)==null?void 0:o.avatar_url)||void 0}),e.jsx(Ka,{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(xi,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:(u=l.agent)==null?void 0:u.email}),e.jsxs("div",{className:"flex items-center gap-2 mt-3",children:[e.jsx(qe,{variant:"secondary",className:"capitalize",children:(l.pipeline_stage||"active").replace("_"," ")}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["Started ",Zc(new Date(l.started_at),{addSuffix:!0})]})]})]})]})})},l.id)})})]})]})})}function YIe({icon:s,label:t,value:n}){return e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-lg bg-white/15 flex items-center justify-center",children:e.jsx(s,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold leading-none",children:n}),e.jsx("div",{className:"text-xs text-white/70 mt-1",children:t})]})]})}function pMt({assignmentId:s}){const{user:t}=ks(),n=ls(),[r,a]=k.useState(""),[i,l]=k.useState(!1),o=k.useRef(null),{data:c=[]}=pt({queryKey:["coaching-messages",s],enabled:!!s,queryFn:async()=>{const{data:u,error:h}=await V.from("coaching_messages").select("*").eq("assignment_id",s).order("created_at",{ascending:!0});if(h)throw h;return u||[]}});k.useEffect(()=>{if(!s)return;const u=V.channel(`coaching-messages-${s}`).on("postgres_changes",{event:"INSERT",schema:"public",table:"coaching_messages",filter:`assignment_id=eq.${s}`},()=>n.invalidateQueries({queryKey:["coaching-messages",s]})).subscribe();return()=>{V.removeChannel(u)}},[s,n]),k.useEffect(()=>{var u;(u=o.current)==null||u.scrollTo({top:o.current.scrollHeight,behavior:"smooth"})},[c]);const d=async()=>{const u=r.trim();if(!u||!t)return;l(!0);const{error:h}=await V.from("coaching_messages").insert({assignment_id:s,sender_id:t.id,body:u});l(!1),h||a("")};return e.jsxs(we,{className:"flex flex-col h-[60vh] min-h-[400px]",children:[e.jsx("div",{ref:o,className:"flex-1 overflow-y-auto p-4 space-y-3",children:c.length===0?e.jsx("div",{className:"h-full flex items-center justify-center text-sm text-muted-foreground",children:"No messages yet. Say hi 👋"}):c.map(u=>{const h=u.sender_id===(t==null?void 0:t.id);return e.jsxs("div",{className:Ot("flex gap-2",h?"justify-end":"justify-start"),children:[!h&&e.jsx(Wa,{className:"h-8 w-8 mt-1",children:e.jsx(Ka,{className:"text-xs",children:(u.sender_id||"?").charAt(0).toUpperCase()})}),e.jsxs("div",{className:Ot("max-w-[75%] rounded-2xl px-3 py-2 text-sm",h?"bg-[#406E71] text-white rounded-br-sm":"bg-muted rounded-bl-sm"),children:[e.jsx("p",{className:"whitespace-pre-wrap break-words",children:u.body}),e.jsx("p",{className:Ot("text-[10px] mt-1",h?"text-white/70":"text-muted-foreground"),children:Zc(new Date(u.created_at),{addSuffix:!0})})]})]},u.id)})}),e.jsx(De,{className:"border-t p-3",children:e.jsxs("div",{className:"flex gap-2 items-end",children:[e.jsx(Ls,{value:r,onChange:u=>a(u.target.value),onKeyDown:u=>{u.key==="Enter"&&!u.shiftKey&&(u.preventDefault(),d())},placeholder:"Type a message…",rows:1,className:"resize-none min-h-[40px]"}),e.jsx($,{onClick:d,disabled:i||!r.trim(),size:"icon",className:"bg-[#406E71] hover:bg-[#2a4c64]",children:e.jsx(Wr,{className:"h-4 w-4"})})]})})]})}var SCs=Object.defineProperty,iA=(s,t)=>SCs(s,"name",{value:t,configurable:!0}),gMt="Progress",cWe=100,[CCs,VQn]=qm(gMt),[ACs,ECs]=CCs(gMt),TCs=k.forwardRef(iA(function(t,n){const{__scopeProgress:r,value:a=null,max:i,getValueLabel:l=xMt,...o}=t;(i||i===0)&&!X7e(i)&&console.error(yMt(`${i}`,"Progress"));const c=X7e(i)?i:cWe;a!==null&&!Q7e(a,c)&&console.error(vMt(`${a}`,"Progress"));const d=Q7e(a,c)?a:null,u=eX(d)?l(d,c):void 0;return e.jsx(ACs,{scope:r,value:d,max:c,children:e.jsx(hi.div,{"aria-valuemax":c,"aria-valuemin":0,"aria-valuenow":eX(d)?d:void 0,"aria-valuetext":u,role:"progressbar","data-state":dWe(d,c),"data-value":d??void 0,"data-max":c,...o,ref:n})})},"Progress")),MCs="ProgressIndicator",PCs=k.forwardRef(iA(function(t,n){const{__scopeProgress:r,...a}=t,i=ECs(MCs,r);return e.jsx(hi.div,{"data-state":dWe(i.value,i.max),"data-value":i.value??void 0,"data-max":i.max,...a,ref:n})},"ProgressIndicator"));function xMt(s,t){return`${Math.round(s/t*100)}%`}iA(xMt,"defaultGetValueLabel");function dWe(s,t){return s==null?"indeterminate":s===t?"complete":"loading"}iA(dWe,"getProgressState");function eX(s){return typeof s=="number"}iA(eX,"isNumber");function X7e(s){return eX(s)&&!isNaN(s)&&s>0}iA(X7e,"isValidMaxNumber");function Q7e(s,t){return eX(s)&&!isNaN(s)&&s<=t&&s>=0}iA(Q7e,"isValidValueNumber");function yMt(s,t){return`Invalid prop \`max\` of value \`${s}\` supplied to \`${t}\`. Only numbers greater than 0 are valid max values. Defaulting to \`${cWe}\`.`}iA(yMt,"getInvalidMaxError");function vMt(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 ${cWe} if no \`max\` prop is set) - \`null\` or \`undefined\` if the progress is indeterminate. Defaulting to \`null\`.`}iA(vMt,"getInvalidValueError");var bMt=TCs,ICs=PCs;const ho=k.forwardRef(({className:s,value:t,...n},r)=>e.jsx(bMt,{ref:r,className:Ot("relative h-4 w-full overflow-hidden rounded-full bg-secondary",s),...n,children:e.jsx(ICs,{className:"h-full w-full flex-1 bg-primary transition-all",style:{transform:`translateX(-${100-(t||0)}%)`}})}));ho.displayName=bMt.displayName;function _Mt({agentUserId:s}){const t=new Date().getFullYear(),n=`${t}-01-01`,r=`${t}-12-31`,{data:a=[]}=pt({queryKey:["coaching-kpi-txns",s,t],enabled:!!s,queryFn:async()=>{const{data:x,error:y}=await V.from("scorecard_transactions").select("id, sale_price, commission_amount, close_date, is_win").eq("owner_user_id",s).gte("close_date",n).lte("close_date",r);if(y)throw y;return x||[]}}),{data:i}=pt({queryKey:["coaching-kpi-goal",s,t],enabled:!!s,queryFn:async()=>{const{data:x}=await V.from("scorecard_goals").select("*").eq("owner_user_id",s).eq("year",t).maybeSingle();return x}}),l=a.filter(x=>x.is_win),o=l.length,c=l.reduce((x,y)=>x+(Number(y.sale_price)||0),0),d=l.reduce((x,y)=>x+(Number(y.commission_amount)||0),0),u=i,h=(u==null?void 0:u.transactions_goal)||0,m=(u==null?void 0:u.volume_goal)||0,p=(u==null?void 0:u.gci_goal)||0,g=x=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(x);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(mc,{className:"h-5 w-5"})," ",t," KPIs"]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-3",children:[e.jsx(ZIe,{icon:oh,label:"Transactions",value:o.toString(),goal:h,current:o,suffix:h?`/ ${h}`:""}),e.jsx(ZIe,{icon:mc,label:"Volume",value:g(c),goal:m,current:c,suffix:m?`of ${g(m)}`:""}),e.jsx(ZIe,{icon:Su,label:"GCI",value:g(d),goal:p,current:d,suffix:p?`of ${g(p)}`:""})]}),o===0&&e.jsx(we,{children:e.jsxs(De,{className:"p-4 text-sm text-muted-foreground text-center",children:["No transactions logged for ",t," yet."]})})]})}function ZIe({icon:s,label:t,value:n,goal:r,current:a,suffix:i}){const l=r>0?Math.min(100,a/r*100):0;return e.jsx(we,{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:n}),r>0&&e.jsxs("div",{className:"mt-2 space-y-1",children:[e.jsx(ho,{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 wMt({assignmentId:s,canEdit:t}){const n=ls(),[r,a]=k.useState(!1),[i,l]=k.useState(null),{data:o=[]}=pt({queryKey:["coaching-goals",s],enabled:!!s,queryFn:async()=>{const{data:d,error:u}=await V.from("coaching_goals").select("*").eq("assignment_id",s).order("created_at",{ascending:!1});if(u)throw u;return d||[]}}),c=()=>n.invalidateQueries({queryKey:["coaching-goals",s]});return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsxs("h2",{className:"text-lg font-semibold flex items-center gap-2",children:[e.jsx(_h,{className:"h-5 w-5"})," Goals"]}),t&&e.jsxs($,{size:"sm",onClick:()=>{l(null),a(!0)},children:[e.jsx(nn,{className:"h-4 w-4 mr-1"})," New Goal"]})]}),o.length===0?e.jsx(we,{children:e.jsx(De,{className:"p-6 text-center text-muted-foreground",children:"No goals yet."})}):o.map(d=>{const u=Number(d.target_value||0),h=Number(d.current_value||0),m=u>0?Math.min(100,h/u*100):0;return e.jsx(we,{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(qe,{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($,{variant:"ghost",size:"icon",onClick:()=>{l(d),a(!0)},children:e.jsx(ui,{className:"h-4 w-4"})})]}),u>0&&e.jsxs("div",{className:"mt-3 space-y-1",children:[e.jsxs("div",{className:"flex justify-between text-xs text-muted-foreground",children:[e.jsxs("span",{children:[h.toLocaleString()," / ",u.toLocaleString()," ",d.target_metric||""]}),e.jsxs("span",{children:[m.toFixed(0),"%"]})]}),e.jsx(ho,{value:m})]}),d.due_date&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-2",children:["Due ",Ys(new Date(d.due_date),"PP")]})]})},d.id)}),t&&e.jsx(LCs,{open:r,onOpenChange:a,assignmentId:s,goal:i,onSaved:c})]})}function LCs({open:s,onOpenChange:t,assignmentId:n,goal:r,onSaved:a}){var C,A;const[i,l]=k.useState((r==null?void 0:r.title)||""),[o,c]=k.useState((r==null?void 0:r.description)||""),[d,u]=k.useState((r==null?void 0:r.target_metric)||""),[h,m]=k.useState(((C=r==null?void 0:r.target_value)==null?void 0:C.toString())||""),[p,g]=k.useState(((A=r==null?void 0:r.current_value)==null?void 0:A.toString())||"0"),[x,y]=k.useState((r==null?void 0:r.due_date)||""),[v,_]=k.useState(!1);k.useState(()=>{var M,I;l((r==null?void 0:r.title)||""),c((r==null?void 0:r.description)||""),u((r==null?void 0:r.target_metric)||""),m(((M=r==null?void 0:r.target_value)==null?void 0:M.toString())||""),g(((I=r==null?void 0:r.current_value)==null?void 0:I.toString())||"0"),y((r==null?void 0:r.due_date)||"")});const j=async()=>{if(!i.trim())return;_(!0);const M={assignment_id:n,title:i,description:o||null,target_metric:d||null,target_value:h?Number(h):null,current_value:p?Number(p):0,due_date:x||null},{error:I}=r!=null&&r.id?await V.from("coaching_goals").update(M).eq("id",r.id):await V.from("coaching_goals").insert(M);if(_(!1),I)return ae.error(I.message);ae.success(r!=null&&r.id?"Goal updated":"Goal created"),a==null||a(),t(!1)};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Rs,{children:[e.jsx(Vs,{children:e.jsx($s,{children:r!=null&&r.id?"Edit Goal":"New Goal"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(be,{placeholder:"Title",value:i,onChange:M=>l(M.target.value)}),e.jsx(Ls,{placeholder:"Description (optional)",rows:2,value:o,onChange:M=>c(M.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(be,{placeholder:"transactions",value:d,onChange:M=>u(M.target.value)})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Target"}),e.jsx(be,{type:"number",value:h,onChange:M=>m(M.target.value)})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Current"}),e.jsx(be,{type:"number",value:p,onChange:M=>g(M.target.value)})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Due date"}),e.jsx(be,{type:"date",value:x,onChange:M=>y(M.target.value)})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx($,{onClick:j,disabled:v,children:r!=null&&r.id?"Save":"Create"})]})]})})}function jMt({assignmentId:s}){const t=ls(),{user:n}=ks(),r=k.useRef(null),[a,i]=k.useState(!1),{data:l=[]}=pt({queryKey:["coaching-files",s],enabled:!!s,queryFn:async()=>{const{data:h,error:m}=await V.from("coaching_shared_files").select("*").eq("assignment_id",s).order("created_at",{ascending:!1});if(m)throw m;return h||[]}}),o=()=>t.invalidateQueries({queryKey:["coaching-files",s]}),c=async h=>{var p;const m=(p=h.target.files)==null?void 0:p[0];if(!(!m||!n)){i(!0);try{const g=`${s}/${Date.now()}-${m.name}`,{error:x}=await V.storage.from("coaching-files").upload(g,m);if(x)throw x;const{error:y}=await V.from("coaching_shared_files").insert({assignment_id:s,uploaded_by:n.id,file_url:g,file_name:m.name,file_size_bytes:m.size,mime_type:m.type});if(y)throw y;ae.success("File uploaded"),o()}catch(g){ae.error(g.message||"Upload failed")}finally{i(!1),r.current&&(r.current.value="")}}},d=async h=>{const{data:m,error:p}=await V.storage.from("coaching-files").createSignedUrl(h.file_url,60);if(p||!m)return ae.error("Could not get download link");window.open(m.signedUrl,"_blank")},u=async h=>{await io("Delete this file?")&&(await V.storage.from("coaching-files").remove([h.file_url]),await V.from("coaching_shared_files").delete().eq("id",h.id),o())};return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Shared Files"}),e.jsxs($,{size:"sm",onClick:()=>{var h;return(h=r.current)==null?void 0:h.click()},disabled:a,children:[e.jsx(gi,{className:"h-4 w-4 mr-1"})," ",a?"Uploading…":"Upload"]}),e.jsx("input",{ref:r,type:"file",hidden:!0,onChange:c})]}),l.length===0?e.jsx(we,{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(h=>e.jsx(we,{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(ea,{className:"h-5 w-5 text-muted-foreground"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"font-medium truncate",children:h.file_name}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[h.file_size_bytes?`${(h.file_size_bytes/1024).toFixed(0)} KB · `:"",Ys(new Date(h.created_at),"PP")]})]}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>d(h),children:e.jsx(ji,{className:"h-4 w-4"})}),h.uploaded_by===(n==null?void 0:n.id)&&e.jsx($,{variant:"ghost",size:"icon",onClick:()=>u(h),children:e.jsx(Un,{className:"h-4 w-4"})})]})},h.id))})]})}function RCs(){var m,p,g,x;const{id:s}=oo(),t=Jn(),n=ls(),{data:r,isLoading:a}=jCs(s),{data:i=[]}=mMt(s),{data:l=[]}=fMt(s),[o,c]=k.useState(!1),[d,u]=k.useState(!1);if(a)return e.jsx(Xs,{title:"Coaching",children:e.jsx("div",{className:"p-8",children:"Loading…"})});if(!r)return e.jsx(Xs,{title:"Coaching",children:e.jsx("div",{className:"p-8",children:"Assignment not found."})});const h=r;return e.jsxs(Xs,{title:"Coaching",children:[e.jsxs("div",{className:"p-4 md:p-8 max-w-6xl mx-auto space-y-6",children:[e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>t("/coaching"),children:[e.jsx(Ia,{className:"h-4 w-4 mr-2"})," Back to roster"]}),e.jsxs(we,{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(Wa,{className:"h-24 w-24 ring-4 ring-background",children:[e.jsx(eo,{src:((m=h.agent)==null?void 0:m.avatar_url)||void 0}),e.jsx(Ka,{className:"text-2xl",children:(((p=h.agent)==null?void 0:p.name)||"?").charAt(0)})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h1",{className:"text-2xl font-bold",children:((g=h.agent)==null?void 0:g.name)||"Unknown"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:(x=h.agent)==null?void 0:x.email}),e.jsxs("div",{className:"flex items-center gap-2 mt-2",children:[e.jsx(qe,{variant:"secondary",className:"capitalize",children:(h.pipeline_stage||"active").replace("_"," ")}),e.jsx(qe,{variant:"outline",className:"capitalize",children:h.status})]})]}),e.jsx("div",{className:"flex gap-2",children:e.jsx(OCs,{value:h.pipeline_stage||"active",onChange:async y=>{await V.from("coaching_assignments").update({pipeline_stage:y}).eq("id",h.id),n.invalidateQueries({queryKey:["coaching-assignment",h.id]}),n.invalidateQueries({queryKey:["coach-roster"]})}})})]})})]}),e.jsx(DCs,{assignment:h}),e.jsxs(ya,{defaultValue:"sessions",children:[e.jsxs(va,{className:"w-full flex flex-wrap justify-start h-auto",children:[e.jsxs(is,{value:"sessions",children:[e.jsx(ha,{className:"h-4 w-4 mr-2"}),"Sessions"]}),e.jsxs(is,{value:"actions",children:[e.jsx(op,{className:"h-4 w-4 mr-2"}),"Actions"]}),e.jsxs(is,{value:"goals",children:[e.jsx(_h,{className:"h-4 w-4 mr-2"}),"Goals"]}),e.jsxs(is,{value:"kpis",children:[e.jsx(mc,{className:"h-4 w-4 mr-2"}),"KPIs"]}),e.jsxs(is,{value:"messages",children:[e.jsx(bo,{className:"h-4 w-4 mr-2"}),"Messages"]}),e.jsxs(is,{value:"files",children:[e.jsx(d1,{className:"h-4 w-4 mr-2"}),"Files"]}),e.jsxs(is,{value:"notes",children:[e.jsx(ea,{className:"h-4 w-4 mr-2"}),"Private Notes"]})]}),e.jsxs(cs,{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($,{size:"sm",onClick:()=>c(!0),children:[e.jsx(nn,{className:"h-4 w-4 mr-1"})," New Session"]})]}),i.length===0?e.jsx(we,{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(y=>e.jsx(we,{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:Ys(new Date(y.scheduled_at),"PPp")}),e.jsx(qe,{variant:"outline",className:"capitalize",children:y.status}),y.template&&e.jsx(qe,{variant:"secondary",children:y.template}),y.zoom_join_url&&e.jsx("a",{href:y.zoom_join_url,target:"_blank",rel:"noopener noreferrer",className:"text-xs text-primary underline",children:"Join Zoom"})]}),y.agenda&&e.jsxs("p",{className:"text-sm mb-1",children:[e.jsx("span",{className:"text-muted-foreground",children:"Agent's agenda:"})," ",y.agenda]}),y.summary&&e.jsx("p",{className:"text-sm text-muted-foreground whitespace-pre-wrap",children:y.summary}),y.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(fu,{className:"h-3 w-3"})," Private"]}),e.jsx("p",{className:"whitespace-pre-wrap",children:y.private_notes})]})]})})})},y.id))})]}),e.jsxs(cs,{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($,{size:"sm",onClick:()=>u(!0),children:[e.jsx(nn,{className:"h-4 w-4 mr-1"})," Add"]})]}),l.length===0?e.jsx(we,{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(y=>e.jsx(we,{children:e.jsxs(De,{className:"p-3 flex items-center gap-3",children:[e.jsx(Li,{checked:y.status==="done",onCheckedChange:async v=>{await V.from("coaching_action_items").update({status:v?"done":"open",completed_at:v?new Date().toISOString():null}).eq("id",y.id),n.invalidateQueries({queryKey:["coaching-action-items",h.id]})}}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:y.status==="done"?"line-through text-muted-foreground":"font-medium",children:y.title}),y.description&&e.jsx("div",{className:"text-xs text-muted-foreground",children:y.description})]}),y.due_date&&e.jsx(qe,{variant:"outline",children:Ys(new Date(y.due_date),"MMM d")}),e.jsx(qe,{variant:"secondary",className:"capitalize",children:y.priority})]})},y.id))})]}),e.jsx(cs,{value:"goals",children:e.jsx(wMt,{assignmentId:h.id,canEdit:!0})}),e.jsx(cs,{value:"kpis",children:h.agent_id&&e.jsx(_Mt,{agentUserId:h.agent_id})}),e.jsx(cs,{value:"messages",children:e.jsx(pMt,{assignmentId:h.id})}),e.jsx(cs,{value:"files",children:e.jsx(jMt,{assignmentId:h.id})}),e.jsx(cs,{value:"notes",className:"space-y-4",children:e.jsx(we,{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(FCs,{open:o,onOpenChange:c,assignmentId:h.id,onSaved:()=>n.invalidateQueries({queryKey:["coaching-sessions",h.id]})}),e.jsx(zCs,{open:d,onOpenChange:u,assignmentId:h.id,onSaved:()=>n.invalidateQueries({queryKey:["coaching-action-items",h.id]})})]})}function DCs({assignment:s}){const t=ls(),[n,r]=k.useState(s.sessions_per_month==null?"":String(s.sessions_per_month)),[a,i]=k.useState(!1),l=async()=>{i(!0);const o=n.trim()===""?null:Math.max(1,parseInt(n,10)||1),{error:c}=await V.from("coaching_assignments").update({sessions_per_month:o}).eq("id",s.id);if(i(!1),c)return ae.error(c.message);ae.success("Session allowance updated"),t.invalidateQueries({queryKey:["coaching-assignment",s.id]})};return e.jsx(we,{children:e.jsxs(De,{className:"p-4 flex flex-wrap items-end gap-3",children:[e.jsxs("div",{className:"flex-1 min-w-[220px]",children:[e.jsxs("div",{className:"font-medium flex items-center gap-2",children:[e.jsx(ha,{className:"h-4 w-4"})," Monthly session allowance"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Leave blank to use your coach default. This agent books these on their My Coach page."})]}),e.jsx(be,{type:"number",min:1,max:31,placeholder:"Default",value:n,onChange:o=>r(o.target.value),className:"w-28"}),e.jsxs($,{size:"sm",variant:"outline",onClick:l,disabled:a,children:[e.jsx(Ml,{className:"h-4 w-4 mr-1"})," Save"]})]})})}function OCs({value:s,onChange:t}){return e.jsxs(bs,{value:s,onValueChange:t,children:[e.jsx(ys,{className:"w-40",children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"onboarding",children:"Onboarding"}),e.jsx(We,{value:"active",children:"Active"}),e.jsx(We,{value:"thriving",children:"Thriving"}),e.jsx(We,{value:"at_risk",children:"At Risk"}),e.jsx(We,{value:"graduated",children:"Graduated"})]})]})}function FCs({open:s,onOpenChange:t,assignmentId:n,onSaved:r}){const[a,i]=k.useState(()=>new Date().toISOString().slice(0,16)),[l,o]=k.useState(60),[c,d]=k.useState("weekly_1on1"),[u,h]=k.useState(""),[m,p]=k.useState(""),[g,x]=k.useState(!1),[y,v]=k.useState(!0),[_,j]=k.useState(null),[C,A]=k.useState(!1),M=async()=>{A(!0);const{data:P,error:R}=await V.functions.invoke("coaching-prep-brief",{body:{assignmentId:n}});if(A(!1),R||P!=null&&P.error)return ae.error((P==null?void 0:P.error)||(R==null?void 0:R.message)||"Failed to generate brief");j(P.brief||"No brief returned.")},I=async()=>{x(!0);const{data:P,error:R}=await V.from("coaching_sessions").insert({assignment_id:n,scheduled_at:new Date(a).toISOString(),duration_minutes:l,template:c,summary:u,private_notes:m,status:"completed"}).select("id").maybeSingle();if(R)return x(!1),ae.error(R.message);if(ae.success("Session saved"),y&&u.trim()&&(P!=null&&P.id)){const{error:O}=await V.functions.invoke("coaching-send-recap",{body:{sessionId:P.id}});O?ae.error("Saved, but recap email failed: "+O.message):ae.success("Recap emailed to agent")}x(!1),r==null||r(),t(!1),h(""),p(""),j(null)};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Vs,{children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx($s,{children:"New Session"}),e.jsxs($,{size:"sm",variant:"outline",onClick:M,disabled:C,children:[C?e.jsx(Jt,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(kn,{className:"h-4 w-4 mr-1"}),"Pre-session brief"]})]})}),e.jsxs("div",{className:"space-y-3",children:[_&&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(kn,{className:"h-3 w-3"})," AI Brief"]}),_]}),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(be,{type:"datetime-local",value:a,onChange:P=>i(P.target.value)})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Duration (min)"}),e.jsx(be,{type:"number",value:l,onChange:P=>o(Number(P.target.value))})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Template"}),e.jsxs(bs,{value:c,onValueChange:d,children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"weekly_1on1",children:"Weekly 1:1"}),e.jsx(We,{value:"grow",children:"GROW Model"}),e.jsx(We,{value:"goal_review",children:"Goal Review"}),e.jsx(We,{value:"breakthrough",children:"Breakthrough Session"})]})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Summary (agent sees this)"}),e.jsx(Ls,{rows:4,value:u,onChange:P=>h(P.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(fu,{className:"h-3 w-3"})," Private notes (only you)"]}),e.jsx(Ls,{rows:3,value:m,onChange:P=>p(P.target.value),placeholder:"Your private observations…"})]}),e.jsxs("label",{className:"flex items-center gap-2 text-sm pt-1",children:[e.jsx(Li,{checked:y,onCheckedChange:P=>v(!!P)}),e.jsx(Wr,{className:"h-3.5 w-3.5 text-muted-foreground"}),"Email recap to agent on save"]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs($,{onClick:I,disabled:g,children:[e.jsx(Ml,{className:"h-4 w-4 mr-1"})," Save Session"]})]})]})})}function zCs({open:s,onOpenChange:t,assignmentId:n,onSaved:r}){const[a,i]=k.useState(""),[l,o]=k.useState(""),[c,d]=k.useState(""),[u,h]=k.useState("medium"),[m,p]=k.useState(!1),g=async()=>{if(!a.trim())return;p(!0);const{error:x}=await V.from("coaching_action_items").insert({assignment_id:n,title:a,description:l||null,due_date:c||null,priority:u});if(p(!1),x)return ae.error(x.message);ae.success("Action item added"),r==null||r(),t(!1),i(""),o(""),d("")};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Rs,{children:[e.jsx(Vs,{children:e.jsx($s,{children:"New Action Item"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(be,{placeholder:"Title",value:a,onChange:x=>i(x.target.value)}),e.jsx(Ls,{rows:3,placeholder:"Description (optional)",value:l,onChange:x=>o(x.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(be,{type:"date",value:c,onChange:x=>d(x.target.value)})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Priority"}),e.jsxs(bs,{value:u,onValueChange:h,children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"low",children:"Low"}),e.jsx(We,{value:"medium",children:"Medium"}),e.jsx(We,{value:"high",children:"High"})]})]})]})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx($,{onClick:g,disabled:m,children:"Add"})]})]})})}function J7e({value:s,size:t=16,onChange:n}){return e.jsx("div",{className:"flex items-center gap-0.5",children:[1,2,3,4,5].map(r=>e.jsx("button",{type:"button",onClick:()=>n==null?void 0:n(r),disabled:!n,className:n?"cursor-pointer":"cursor-default",children:e.jsx(ri,{style:{width:t,height:t},className:r<=s?"fill-yellow-400 text-yellow-400":"text-muted-foreground/40"})},r))})}function BCs({coachId:s}){const[t,n]=k.useState([]),[r,a]=k.useState(!0);k.useEffect(()=>{(async()=>{const{data:l}=await V.from("coaching_reviews").select("*").eq("coach_id",s).eq("is_published",!0).order("created_at",{ascending:!1}),o=l||[];if(o.length){const c=o.map(h=>h.agent_id),{data:d}=await V.from("profiles").select("id, name, avatar_url").in("id",c),u=new Map((d||[]).map(h=>[h.id,h]));o.forEach(h=>h.profile=u.get(h.agent_id))}n(o),a(!1)})()},[s]);const i=t.length?t.reduce((l,o)=>l+o.rating,0)/t.length:0;return r||!t.length?null:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("h2",{className:"text-xl font-semibold",children:"Reviews"}),e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(J7e,{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(we,{children:e.jsx(De,{className:"p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsxs(Wa,{className:"h-9 w-9",children:[e.jsx(eo,{src:((o=l.profile)==null?void 0:o.avatar_url)||void 0}),e.jsx(Ka,{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(J7e,{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 $Cs({coachId:s,assignmentId:t}){const{user:n}=ks(),[r,a]=k.useState(null),[i,l]=k.useState(0),[o,c]=k.useState(""),[d,u]=k.useState(""),[h,m]=k.useState(!1);k.useEffect(()=>{n&&(async()=>{const{data:g}=await V.from("coaching_reviews").select("*").eq("coach_id",s).eq("agent_id",n.id).maybeSingle();g&&(a(g),l(g.rating),c(g.title||""),u(g.body||""))})()},[n,s]);const p=async()=>{if(!n)return;if(!i)return ae.error("Pick a rating");m(!0);const g={coach_id:s,agent_id:n.id,assignment_id:t||null,rating:i,title:o||null,body:d||null},{error:x}=r?await V.from("coaching_reviews").update(g).eq("id",r.id):await V.from("coaching_reviews").insert(g);if(m(!1),x)return ae.error(x.message);ae.success("Thanks for your review!"),a({...g,id:r==null?void 0:r.id})};return e.jsx(we,{children:e.jsxs(De,{className:"p-5 space-y-3",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold",children:r?"Your review":"Leave a review"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Help other agents find a great coach."})]}),e.jsx(J7e,{value:i,size:28,onChange:l}),e.jsx(be,{placeholder:"Title (optional)",value:o,onChange:g=>c(g.target.value)}),e.jsx(Ls,{rows:4,placeholder:"What was your experience like?",value:d,onChange:g=>u(g.target.value)}),e.jsx($,{onClick:p,disabled:h,className:"bg-[#406E71] hover:bg-[#2a4c64]",children:h?"Saving…":r?"Update review":"Submit review"})]})})}const dre=async s=>{var r,a;const{data:t,error:n}=await V.functions.invoke("coaching-booking",{body:s});if(n){const i=(r=n==null?void 0:n.context)!=null&&r.text?await n.context.text():n.message;let l=i;try{l=((a=JSON.parse(i))==null?void 0:a.error)||i}catch{}throw new Error(l)}if(t!=null&&t.error)throw new Error(t.error);return t},XIe=s=>Ys(s,"yyyy-MM-dd"),Oct=s=>{const[t,n]=s.split(":").map(Number),r=t>=12?"PM":"AM";return`${t%12||12}:${String(n).padStart(2,"0")} ${r}`};function UCs({assignmentId:s,upcoming:t=[]}){const n=ls(),[r,a]=k.useState(null),[i,l]=k.useState(null),[o,c]=k.useState(null),[d,u]=k.useState(""),[h,m]=k.useState(!1),{data:p,isLoading:g}=pt({queryKey:["coaching-booking-context",s],queryFn:()=>dre({action:"context"})});k.useEffect(()=>{var oe;!r&&((oe=p==null?void 0:p.booking_types)!=null&&oe.length)&&a(p.booking_types[0].id)},[p,r]);const x=k.useMemo(()=>new Date,[]),[y,v]=k.useState(()=>Ih(new Date)),_=(p==null?void 0:p.max_advance_days)||30,j=k.useMemo(()=>wu(np(x),_-1),[x,_]),C=k.useMemo(()=>{const oe=Ih(y);return oe{const oe=eb(y);return oe>j?j:oe},[y,j]),M=Math.max(0,o1(A,C)+1),{data:I={},isFetching:P}=pt({queryKey:["coaching-availability",r,XIe(C),M],enabled:!!r&&M>0,queryFn:async()=>(await dre({action:"availability",booking_type_id:r,start:XIe(C),days:M})).availability||{}}),R=k.useMemo(()=>{const oe=Ih(y),me=eb(y).getDate(),Q=oe.getDay(),te=Array.from({length:Q},()=>null);for(let le=0;leObject.entries(I).filter(([,oe])=>oe.length>0),[I]),B=i?I[i]||[]:[],U=P,G=k.useMemo(()=>{const oe=[{label:"Morning",items:[]},{label:"Afternoon",items:[]},{label:"Evening",items:[]}];for(const me of B){const Q=Number(me.split(":")[0]);Q<12?oe[0].items.push(me):Q<17?oe[1].items.push(me):oe[2].items.push(me)}return oe.filter(me=>me.items.length>0)},[B]),H=(p==null?void 0:p.booking_types.find(oe=>oe.id===r))||null,Y=((p==null?void 0:p.sessions_remaining)??0)<=0,se=async()=>{if(!(!r||!i||!o)){m(!0);try{await dre({action:"book",booking_type_id:r,date:i,time:o,agenda:d||null}),ae.success("Session booked — check your Zoom link below."),c(null),u(""),n.invalidateQueries({queryKey:["coaching-booking-context",s]}),n.invalidateQueries({queryKey:["coaching-availability"]}),n.invalidateQueries({queryKey:["coaching-sessions",s]})}catch(oe){ae.error(oe.message||"Could not book that session")}finally{m(!1)}}},ee=async oe=>{if(await io("Cancel this coaching session?"))try{await dre({action:"cancel",session_id:oe}),ae.success("Session cancelled"),n.invalidateQueries({queryKey:["coaching-booking-context",s]}),n.invalidateQueries({queryKey:["coaching-sessions",s]})}catch(me){ae.error(me.message||"Could not cancel")}};return g?e.jsx(we,{children:e.jsxs(De,{className:"p-8 flex items-center justify-center text-muted-foreground gap-2",children:[e.jsx(Jt,{className:"h-4 w-4 animate-spin"})," Loading your coach's calendar…"]})}):p!=null&&p.scheduler_ready?e.jsxs("div",{className:"space-y-4",children:[e.jsx(we,{children:e.jsxs(De,{className:"p-4 flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-lg bg-primary/10 flex items-center justify-center",children:e.jsx(fd,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsxs("div",{className:"font-medium",children:[p.sessions_remaining," of ",p.sessions_limit," sessions left this month"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Your allowance resets on the 1st."})]})]}),Y&&e.jsx(qe,{variant:"secondary",children:"All booked up"})]})}),t.length>0&&e.jsx(we,{children:e.jsxs(De,{className:"p-4 space-y-3",children:[e.jsx("h3",{className:"font-semibold",children:"Upcoming sessions"}),t.map(oe=>e.jsxs("div",{className:"flex flex-wrap items-center gap-3 p-3 rounded-lg border",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"font-medium",children:Ys(new Date(oe.scheduled_at),"EEE, MMM d · p")}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[oe.duration_minutes||30," minutes"]})]}),oe.zoom_join_url&&e.jsx($,{size:"sm",variant:"outline",asChild:!0,children:e.jsxs("a",{href:oe.zoom_join_url,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(ia,{className:"h-4 w-4 mr-1"})," Join"]})}),e.jsxs($,{size:"sm",variant:"ghost",onClick:()=>ee(oe.id),children:[e.jsx(ju,{className:"h-4 w-4 mr-1"})," Cancel"]})]},oe.id))]})}),e.jsx(we,{children:e.jsxs(De,{className:"p-4 md:p-6 space-y-5",children:[e.jsxs("div",{children:[e.jsx(re,{className:"mb-2 block",children:"Session type"}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:p.booking_types.map(oe=>e.jsxs("button",{onClick:()=>{a(oe.id),c(null)},className:`text-left p-3 rounded-lg border transition-colors ${r===oe.id?"border-primary bg-primary/5":"hover:bg-muted/50"}`,children:[e.jsx("div",{className:"font-medium",children:oe.name}),e.jsxs("div",{className:"text-xs text-muted-foreground flex items-center gap-1 mt-1",children:[e.jsx(sa,{className:"h-3 w-3"})," ",oe.duration_minutes," min"]}),oe.description&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:oe.description})]},oe.id))})]}),e.jsxs("div",{className:"grid gap-5 lg:grid-cols-[minmax(0,1fr)_minmax(0,1fr)]",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(re,{className:"block",children:"Pick a day"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx($,{size:"icon",variant:"ghost",className:"h-7 w-7",disabled:Vq(y,x),onClick:()=>v(Ux(y,-1)),"aria-label":"Previous month",children:e.jsx(Ld,{className:"h-4 w-4"})}),e.jsx("span",{className:"text-sm font-medium w-28 text-center",children:Ys(y,"MMMM yyyy")}),e.jsx($,{size:"icon",variant:"ghost",className:"h-7 w-7",disabled:Ih(Ux(y,1))>j,onClick:()=>v(Ux(y,1)),"aria-label":"Next month",children:e.jsx(fi,{className:"h-4 w-4"})})]})]}),e.jsx("div",{className:"grid grid-cols-7 gap-1 mb-1",children:["S","M","T","W","T","F","S"].map((oe,me)=>e.jsx("div",{className:"text-[11px] text-muted-foreground text-center py-1",children:oe},me))}),e.jsx("div",{className:"grid grid-cols-7 gap-1",children:R.map((oe,me)=>{if(!oe)return e.jsx("div",{},`b${me}`);const Q=XIe(oe),te=(I[Q]||[]).length,fe=oe>=np(x)&&oe<=j&&te>0,_e=i===Q;return e.jsxs("button",{disabled:!fe,onClick:()=>{l(Q),c(null)},className:`aspect-square rounded-lg border text-sm flex flex-col items-center justify-center gap-1 transition-colors ${_e?"border-primary bg-primary text-primary-foreground":fe?"border-primary/30 bg-primary/5 hover:bg-primary/10 font-medium":"border-transparent text-muted-foreground/50 cursor-not-allowed"}`,title:fe?`${te} opening${te===1?"":"s"}`:"No openings",children:[e.jsx("span",{className:"leading-none",children:Ys(oe,"d")}),e.jsx("span",{className:`h-1.5 w-1.5 rounded-full ${_e?"bg-primary-foreground":fe?"bg-primary":"bg-transparent"}`})]},Q)})}),e.jsx("div",{className:"mt-3 flex items-center gap-2 text-xs text-muted-foreground",children:P?e.jsxs(e.Fragment,{children:[e.jsx(Jt,{className:"h-3 w-3 animate-spin"})," Loading your coach's openings…"]}):e.jsxs(e.Fragment,{children:[e.jsx(kn,{className:"h-3 w-3 text-primary"}),O.length===0?"No openings this month — try the next month.":`${O.length} day${O.length===1?"":"s"} with openings this month`]})})]}),e.jsxs("div",{children:[e.jsx(re,{className:"mb-2 block",children:i?`Available times · ${Ys(new Date(`${i}T12:00:00`),"EEE, MMM d")}`:"Available times"}),i?U?e.jsxs("div",{className:"text-sm text-muted-foreground flex items-center gap-2",children:[e.jsx(Jt,{className:"h-4 w-4 animate-spin"})," Checking availability…"]}):B.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No openings on this day — try another date."}):e.jsx("div",{className:"space-y-3 max-h-[320px] overflow-y-auto pr-1",children:G.map(oe=>e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wide text-muted-foreground mb-1",children:oe.label}),e.jsx("div",{className:"grid grid-cols-3 gap-2",children:oe.items.map(me=>e.jsx("button",{onClick:()=>c(me),className:`py-2 rounded-lg border text-sm transition-colors ${o===me?"border-primary bg-primary/10 font-medium":"hover:bg-muted/50"}`,children:Oct(me)},me))})]},oe.label))}):e.jsx("div",{className:"rounded-lg border border-dashed p-6 text-sm text-muted-foreground text-center",children:"Select a highlighted day to see open times."}),!P&&O.length>0&&e.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:O.slice(0,3).map(([oe,me])=>e.jsxs($,{size:"sm",variant:"outline",onClick:()=>{l(oe),c(null)},children:[Ys(new Date(`${oe}T12:00:00`),"EEE MMM d")," · ",me.length," open"]},oe))})]})]}),o&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(re,{htmlFor:"agenda",children:"What do you want to work on? (optional)"}),e.jsx(Ls,{id:"agenda",rows:3,value:d,onChange:oe=>u(oe.target.value),placeholder:"Share context so your coach can prep."})]}),e.jsxs($,{onClick:se,disabled:h||Y,className:"bg-[#406E71] hover:bg-[#2a4c64]",children:[h?e.jsx(Jt,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Gr,{className:"h-4 w-4 mr-1"}),"Book ",H==null?void 0:H.name," — ",i&&Ys(new Date(`${i}T12:00:00`),"MMM d")," at ",Oct(o)]}),Y&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"You've used your sessions for this month. Message your coach if you need more."})]})]})})]}):e.jsx(we,{children:e.jsx(De,{className:"p-8 text-center text-muted-foreground",children:"Your coach hasn't opened their coaching calendar yet. Check back soon."})})}function qCs(){const{user:s}=ks(),{isMember:t,pkg:n}=rA(),{data:r}=pt({queryKey:["coaching-prep-member",s==null?void 0:s.id,n==null?void 0:n.id],enabled:!!(s!=null&&s.id)&&!!(n!=null&&n.id),queryFn:async()=>{const[{data:l},{data:o},{data:c}]=await Promise.all([V.from("coaching_onboarding_forms").select("submitted_at").eq("user_id",s.id).maybeSingle(),V.from("coaching_prep_checklist_items").select("*").eq("package_id",n.id).eq("is_active",!0).order("sort_order"),V.from("coaching_prep_checklist_state").select("item_id").eq("user_id",s.id)]),d=new Set((c||[]).map(u=>u.item_id));return{submitted:!!(l!=null&&l.submitted_at),items:(o||[]).map(u=>({...u,done:d.has(u.id)}))}}});if(!t||!(n!=null&&n.includes_coaching))return null;const a=(r==null?void 0:r.items)||[],i=a.filter(l=>l.done).length;return e.jsxs(we,{children:[e.jsxs(Vt,{className:"flex flex-row items-center justify-between gap-2 space-y-0",children:[e.jsxs(Yt,{className:"text-base flex items-center gap-2",children:[e.jsx(lv,{className:"h-4 w-4 text-primary"})," Coaching prep"]}),a.length>0&&e.jsxs(qe,{variant:"secondary",children:[i,"/",a.length," done"]})]}),e.jsxs(De,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-lg border border-border/60 p-3",children:[e.jsxs("div",{className:"text-sm",children:[e.jsx("div",{className:"font-medium",children:"Onboarding questionnaire"}),e.jsx("div",{className:"text-muted-foreground text-xs",children:r!=null&&r.submitted?"Submitted — your coach has it.":"Complete this before session one."})]}),e.jsx($,{asChild:!0,size:"sm",variant:r!=null&&r.submitted?"outline":"default",children:e.jsx(nr,{to:"/coaching/onboarding",children:r!=null&&r.submitted?"Review":"Start"})})]}),a.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"What we're setting up for you"}),a.map(l=>e.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[l.done?e.jsx(Gr,{className:"h-4 w-4 mt-0.5 text-primary"}):e.jsx(rx,{className:"h-4 w-4 mt-0.5 text-muted-foreground/50"}),e.jsxs("span",{children:[e.jsx("span",{className:l.done?"text-muted-foreground line-through":"",children:l.title}),l.description&&e.jsx("span",{className:"block text-xs text-muted-foreground",children:l.description})]})]},l.id))]})]})]})}function VCs(){var m,p,g,x,y,v;const{user:s}=ks(),{data:t,isLoading:n,refetch:r}=hMt(),a=ls(),i=t==null?void 0:t.id,{data:l=[]}=mMt(i),{data:o=[]}=fMt(i);if(k.useEffect(()=>{new URLSearchParams(window.location.search).get("subscribed")==="1"&&V.functions.invoke("coaching-verify-checkout").then(()=>{r(),a.invalidateQueries({queryKey:["my-coaching-assignment"]})})},[r,a]),n)return e.jsx(Xs,{title:"My Coach",children:e.jsx("div",{className:"p-8",children:"Loading…"})});if(!t)return e.jsx(Xs,{title:"My Coach",children:e.jsxs("div",{className:"max-w-2xl mx-auto p-8 text-center",children:[e.jsx(Bm,{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(_=>_.status!=="done"),u=o.length-d.length,h=l.filter(_=>_.status!=="cancelled"&&new Date(_.scheduled_at).getTime()>Date.now());return e.jsx(Xs,{title:"My Coach",children:e.jsxs("div",{className:"p-4 md:p-8 max-w-5xl mx-auto space-y-6",children:[e.jsx(we,{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(Wa,{className:"h-24 w-24 ring-4 ring-white/20",children:[e.jsx(eo,{src:((m=c.coachProfile)==null?void 0:m.avatar_url)||void 0}),e.jsx(Ka,{className:"text-2xl bg-white/20 text-white",children:(((p=c.coachProfile)==null?void 0:p.name)||"C").charAt(0)})]}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 text-white/80 mb-1",children:[e.jsx(kn,{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"}),((x=c.coach)==null?void 0:x.headline)&&e.jsx("p",{className:"text-white/80 mt-1",children:c.coach.headline}),e.jsxs("div",{className:"flex gap-2 mt-3",children:[((y=c.coach)==null?void 0:y.is_certified)&&e.jsx(qe,{className:"bg-yellow-400/20 text-yellow-100 border-yellow-300/30",children:"LevelUp Certified"}),e.jsx(qe,{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(QIe,{icon:op,label:"Open action items",value:d.length}),e.jsx(QIe,{icon:_h,label:"Completed",value:u}),e.jsx(QIe,{icon:ha,label:"Sessions",value:l.length})]}),e.jsx(qCs,{}),((v=c.coach)==null?void 0:v.id)&&e.jsx($Cs,{coachId:c.coach.id,assignmentId:i}),e.jsxs(ya,{defaultValue:"book",children:[e.jsxs(va,{className:"flex flex-wrap h-auto w-full justify-start",children:[e.jsxs(is,{value:"book",children:[e.jsx(i1,{className:"h-4 w-4 mr-1 md:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Book"})]}),e.jsxs(is,{value:"actions",children:[e.jsx(op,{className:"h-4 w-4 mr-1 md:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Actions"})]}),e.jsxs(is,{value:"sessions",children:[e.jsx(ha,{className:"h-4 w-4 mr-1 md:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Recaps"})]}),e.jsxs(is,{value:"goals",children:[e.jsx(_h,{className:"h-4 w-4 mr-1 md:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Goals"})]}),e.jsxs(is,{value:"kpis",children:[e.jsx(mc,{className:"h-4 w-4 mr-1 md:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"KPIs"})]}),e.jsxs(is,{value:"messages",children:[e.jsx(bo,{className:"h-4 w-4 mr-1 md:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Messages"})]}),e.jsxs(is,{value:"files",children:[e.jsx(d1,{className:"h-4 w-4 mr-1 md:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Files"})]})]}),e.jsx(cs,{value:"book",children:e.jsx(UCs,{assignmentId:i,upcoming:h})}),e.jsx(cs,{value:"actions",className:"space-y-2",children:o.length===0?e.jsx(we,{children:e.jsx(De,{className:"p-6 text-center text-muted-foreground",children:"Your coach hasn't assigned any action items yet."})}):o.map(_=>e.jsx(we,{children:e.jsxs(De,{className:"p-3 flex items-center gap-3",children:[e.jsx(Li,{checked:_.status==="done",onCheckedChange:async j=>{await V.from("coaching_action_items").update({status:j?"done":"open",completed_at:j?new Date().toISOString():null}).eq("id",_.id),a.invalidateQueries({queryKey:["coaching-action-items",i]})}}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:_.status==="done"?"line-through text-muted-foreground":"font-medium",children:_.title}),_.description&&e.jsx("div",{className:"text-xs text-muted-foreground",children:_.description})]}),_.due_date&&e.jsx(qe,{variant:"outline",children:Ys(new Date(_.due_date),"MMM d")}),e.jsx(qe,{variant:"secondary",className:"capitalize",children:_.priority})]})},_.id))}),e.jsx(cs,{value:"sessions",className:"space-y-3",children:l.length===0?e.jsx(we,{children:e.jsx(De,{className:"p-6 text-center text-muted-foreground",children:"No sessions logged yet."})}):l.map(_=>e.jsx(we,{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:Ys(new Date(_.scheduled_at),"PPp")}),e.jsx(qe,{variant:"outline",className:"capitalize",children:_.status})]}),_.summary?e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:_.summary}):e.jsx("p",{className:"text-sm text-muted-foreground italic",children:"Recap coming soon."})]})},_.id))}),e.jsx(cs,{value:"goals",children:e.jsx(wMt,{assignmentId:i,canEdit:!1})}),e.jsx(cs,{value:"kpis",children:s&&e.jsx(_Mt,{agentUserId:s.id})}),e.jsx(cs,{value:"messages",children:e.jsx(pMt,{assignmentId:i})}),e.jsx(cs,{value:"files",children:e.jsx(jMt,{assignmentId:i})})]})]})})}function QIe({icon:s,label:t,value:n}){return e.jsx(we,{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:n}),e.jsx("div",{className:"text-xs text-muted-foreground mt-1",children:t})]})]})})}const Fct="coaching_access",JIe=s=>((s==null?void 0:s.name)||(s==null?void 0:s.email)||"?").trim().slice(0,2).toUpperCase(),eLe=s=>!!s.expires_at&&new Date(s.expires_at).getTime()<=Date.now();function HCs(){const s=ls(),[t,n]=k.useState(""),[r,a]=k.useState([]),[i,l]=k.useState(!1),[o,c]=k.useState(null),[d,u]=k.useState(""),{data:h=[],isLoading:m}=pt({queryKey:["coaching-entitlements"],queryFn:async()=>{const{data:O,error:B}=await V.from("feature_entitlements").select("id, user_id, enabled, expires_at, tier, notes, enabled_at").eq("feature_key",Fct).order("enabled_at",{ascending:!1});if(B)throw B;return O||[]}}),{data:p=[]}=pt({queryKey:["coaching-assigned-agents"],queryFn:async()=>{const{data:O,error:B}=await V.from("coaching_assignments").select("agent_id, coach_id, status").eq("status","active");if(B)throw B;return O||[]}}),g=k.useMemo(()=>{const O=new Set;return h.forEach(B=>O.add(B.user_id)),p.forEach(B=>O.add(B.agent_id)),Array.from(O)},[h,p]),{data:x={}}=pt({queryKey:["coaching-access-profiles",g.join(",")],enabled:g.length>0,queryFn:async()=>{const O={};for(let B=0;B{O[G.id]=G})}return O}});k.useEffect(()=>{const O=t.trim();if(O.length<2){a([]),l(!1);return}l(!0);const B=setTimeout(async()=>{const{data:U}=await V.from("profiles").select("id, name, email, avatar_url").or(`email.ilike.%${O}%,name.ilike.%${O}%`).limit(12);a(U||[]),l(!1)},250);return()=>clearTimeout(B)},[t]);const y=k.useMemo(()=>{const O=new Map;return h.forEach(B=>O.set(B.user_id,B)),O},[h]),v=k.useMemo(()=>new Set(p.map(O=>O.agent_id)),[p]),_=()=>{s.invalidateQueries({queryKey:["coaching-entitlements"]}),s.invalidateQueries({queryKey:["coaching-access-profiles"]}),s.invalidateQueries({queryKey:["coaching-access"]})},j=async(O,B={})=>{var H;const{data:U}=await V.auth.getUser(),{error:G}=await V.from("feature_entitlements").upsert({user_id:O,feature_key:Fct,enabled:B.enabled??!0,expires_at:B.expires_at??null,notes:B.notes??null,tier:B.tier??null,enabled_by:((H=U==null?void 0:U.user)==null?void 0:H.id)??null,enabled_at:new Date().toISOString(),updated_at:new Date().toISOString()},{onConflict:"user_id,feature_key"});return G?(ae.error(G.message),!1):(_(),!0)},C=async O=>{await j(O.id)&&ae.success(`Coaching access granted to ${O.name||O.email}`),n(""),a([])},A=async(O,B)=>{const{error:U}=await V.from("feature_entitlements").update({enabled:B,updated_at:new Date().toISOString()}).eq("id",O.id);if(U)return ae.error(U.message);ae.success(B?"Access enabled":"Access paused"),_()},M=async O=>{if(!await io({title:"Revoke coaching access?",description:`${O.profile.name||O.profile.email||"This member"} will lose access to the coaching area unless they're assigned to a coach.`,confirmText:"Revoke access",destructive:!0}))return;const{error:U}=await V.from("feature_entitlements").delete().eq("id",O.entitlement.id);if(U)return ae.error(U.message);ae.success("Coaching access revoked"),_()},I=k.useMemo(()=>{const O=d.trim().toLowerCase(),B=h.map(U=>({entitlement:U,profile:x[U.user_id]}));return O?B.filter(({profile:U})=>`${(U==null?void 0:U.name)||""} ${(U==null?void 0:U.email)||""}`.toLowerCase().includes(O)):B},[h,x,d]),P=h.filter(O=>O.enabled&&!eLe(O)).length,R=p.filter(O=>!y.has(O.agent_id));return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-3",children:[e.jsx(tLe,{icon:b0,label:"Granted access",value:P,hint:"Standalone entitlements"}),e.jsx(tLe,{icon:Xn,label:"Coached members",value:v.size,hint:"Active coach assignments"}),e.jsx(tLe,{icon:kn,label:"Total with access",value:new Set([...h.filter(O=>O.enabled&&!eLe(O)).map(O=>O.user_id),...v]).size,hint:"Unique members"})]}),e.jsx(we,{children:e.jsxs(De,{className:"p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(x3,{className:"h-5 w-5 text-primary"}),e.jsx("h2",{className:"text-lg font-semibold",children:"Grant Coaching Access"})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Give any member access to the coaching area — meeting notes, one-on-one scheduling and their coach workspace — even before a coach is assigned."}),e.jsxs("div",{className:"relative",children:[e.jsx(Yr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{className:"pl-9",placeholder:"Search members by name or email…",value:t,onChange:O=>n(O.target.value)})]}),t.trim().length>=2&&e.jsx("div",{className:"border rounded-lg divide-y max-h-80 overflow-auto",children:i?e.jsxs("div",{className:"p-3 text-sm text-muted-foreground flex items-center gap-2",children:[e.jsx(Jt,{className:"h-4 w-4 animate-spin"})," Searching…"]}):r.length===0?e.jsx("div",{className:"p-3 text-sm text-muted-foreground",children:"No members found"}):r.map(O=>{const B=y.get(O.id),U=v.has(O.id);return e.jsxs("div",{className:"flex items-center gap-3 p-2.5 hover:bg-muted/40",children:[e.jsxs(Wa,{className:"h-8 w-8",children:[e.jsx(eo,{src:O.avatar_url||void 0}),e.jsx(Ka,{className:"text-xs",children:JIe(O)})]}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"font-medium truncate",children:O.name||O.email}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:O.email})]}),B?e.jsx(qe,{variant:"outline",className:"shrink-0",children:"Already granted"}):U?e.jsxs(qe,{variant:"outline",className:"shrink-0",children:[e.jsx(pd,{className:"h-3 w-3 mr-1"}),"Has coach"]}):e.jsxs("div",{className:"flex gap-1.5 shrink-0",children:[e.jsx($,{size:"sm",variant:"outline",onClick:()=>c({profile:O}),children:"Options"}),e.jsxs($,{size:"sm",className:"bg-[#406E71] hover:bg-[#2a4c64]",onClick:()=>C(O),children:[e.jsx(Pl,{className:"h-4 w-4 mr-1"})," Grant"]})]})]},O.id)})})]})}),e.jsx(we,{children:e.jsxs(De,{className:"p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx(b0,{className:"h-5 w-5 text-primary"}),e.jsx("h2",{className:"text-lg font-semibold",children:"Members with granted access"}),e.jsx(qe,{variant:"outline",children:h.length}),e.jsx("div",{className:"ml-auto w-full sm:w-64",children:e.jsx(be,{placeholder:"Filter list…",value:d,onChange:O=>u(O.target.value)})})]}),m?e.jsxs("div",{className:"p-6 text-sm text-muted-foreground flex items-center gap-2",children:[e.jsx(Jt,{className:"h-4 w-4 animate-spin"})," Loading…"]}):I.length===0?e.jsx("div",{className:"p-8 text-center text-sm text-muted-foreground border rounded-lg",children:"No standalone grants yet. Search above to give a member access."}):e.jsx("div",{className:"border rounded-lg divide-y",children:I.map(({entitlement:O,profile:B})=>{const U=eLe(O);return e.jsxs("div",{className:"flex items-center gap-3 p-3 flex-wrap",children:[e.jsxs(Wa,{className:"h-9 w-9",children:[e.jsx(eo,{src:(B==null?void 0:B.avatar_url)||void 0}),e.jsx(Ka,{className:"text-xs",children:JIe(B)})]}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"font-medium truncate",children:(B==null?void 0:B.name)||(B==null?void 0:B.email)||O.user_id}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:B==null?void 0:B.email}),e.jsxs("div",{className:"flex items-center gap-2 mt-1 flex-wrap",children:[U?e.jsx(qe,{className:"bg-rose-500/15 text-rose-700 border-rose-300/40",children:"Expired"}):O.enabled?e.jsx(qe,{className:"bg-emerald-500/15 text-emerald-700 border-emerald-300/40",children:"Active"}):e.jsx(qe,{variant:"outline",children:"Paused"}),v.has(O.user_id)&&e.jsxs(qe,{variant:"outline",children:[e.jsx(pd,{className:"h-3 w-3 mr-1"}),"Has coach"]}),O.tier&&e.jsx(qe,{variant:"outline",children:O.tier}),O.expires_at&&e.jsxs("span",{className:"text-xs text-muted-foreground inline-flex items-center gap-1",children:[e.jsx(wm,{className:"h-3 w-3"}),U?"Expired":"Expires"," ",new Date(O.expires_at).toLocaleDateString()]})]}),O.notes&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1 italic truncate",children:O.notes})]}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.jsx(On,{checked:O.enabled&&!U,onCheckedChange:G=>A(O,G)}),e.jsx($,{size:"sm",variant:"outline",onClick:()=>c({profile:B||{id:O.user_id,name:null,email:null},entitlement:O}),children:"Edit"}),e.jsx($,{size:"sm",variant:"ghost",className:"text-rose-600 hover:bg-rose-50",onClick:()=>M({profile:B||{id:O.user_id,name:null,email:null},entitlement:O}),children:e.jsx(mr,{className:"h-4 w-4"})})]})]},O.id)})})]})}),e.jsx(we,{children:e.jsxs(De,{className:"p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Xn,{className:"h-5 w-5 text-primary"}),e.jsx("h2",{className:"text-lg font-semibold",children:"Access through a coach assignment"}),e.jsx(qe,{variant:"outline",children:R.length})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"These members already reach coaching because they're assigned to a coach — no entitlement needed."}),R.length===0?e.jsx("div",{className:"p-6 text-center text-sm text-muted-foreground border rounded-lg",children:"No active assignments."}):e.jsx("div",{className:"flex flex-wrap gap-2",children:R.map(O=>{const B=x[O.agent_id];return e.jsxs("div",{className:"flex items-center gap-2 border rounded-full pl-1 pr-3 py-1",children:[e.jsxs(Wa,{className:"h-6 w-6",children:[e.jsx(eo,{src:(B==null?void 0:B.avatar_url)||void 0}),e.jsx(Ka,{className:"text-[10px]",children:JIe(B)})]}),e.jsx("span",{className:"text-sm",children:(B==null?void 0:B.name)||(B==null?void 0:B.email)||O.agent_id})]},O.agent_id)})})]})}),e.jsx(GCs,{state:o,onClose:()=>c(null),onSave:async O=>{if(!o)return;await j(o.profile.id,O)&&(ae.success("Coaching access saved"),c(null))}})]})}function tLe({icon:s,label:t,value:n,hint:r}){return e.jsx(we,{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:n}),e.jsx("div",{className:"text-sm font-medium",children:t}),e.jsx("div",{className:"text-xs text-muted-foreground",children:r})]})]})})}function GCs({state:s,onClose:t,onSave:n}){const[r,a]=k.useState(""),[i,l]=k.useState(""),[o,c]=k.useState(""),[d,u]=k.useState(!0),[h,m]=k.useState(!1);k.useEffect(()=>{if(!s)return;const g=s.entitlement;a(g!=null&&g.expires_at?g.expires_at.slice(0,10):""),l((g==null?void 0:g.notes)||""),c((g==null?void 0:g.tier)||""),u(g?g.enabled:!0)},[s]);const p=async()=>{m(!0),await n({expires_at:r?new Date(`${r}T23:59:59`).toISOString():null,notes:i.trim()||null,tier:o.trim()||null,enabled:d}),m(!1)};return e.jsx(zs,{open:!!s,onOpenChange:g=>!g&&t(),children:e.jsxs(Rs,{children:[e.jsx(Vs,{children:e.jsx($s,{children:s!=null&&s.entitlement?"Edit coaching access":"Grant coaching access"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"text-sm",children:[e.jsx("div",{className:"font-medium",children:(s==null?void 0:s.profile.name)||(s==null?void 0:s.profile.email)}),e.jsx("div",{className:"text-xs text-muted-foreground",children:s==null?void 0:s.profile.email})]}),e.jsxs("div",{className:"flex items-center justify-between border rounded-lg p-3",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Access enabled"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Turn off to pause without removing the grant."})]}),e.jsx(On,{checked:d,onCheckedChange:u})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Expires on (optional)"}),e.jsx(be,{type:"date",value:r,onChange:g=>a(g.target.value)}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Leave blank for ongoing access."})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Tier / plan label (optional)"}),e.jsx(be,{value:o,onChange:g=>c(g.target.value),placeholder:"e.g. Premium, Beta, Comp"})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Internal notes"}),e.jsx(Ls,{value:i,onChange:g=>l(g.target.value),rows:3,placeholder:"Why this member has access…"})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:t,children:"Cancel"}),e.jsx($,{onClick:p,disabled:h,className:"bg-[#406E71] hover:bg-[#2a4c64]",children:h?"Saving…":"Save access"})]})]})})}function WCs(){const s=ls(),[t,n]=k.useState(""),[r,a]=k.useState("active"),{data:i=[]}=pt({queryKey:["admin-coaches-lite"],queryFn:async()=>{const{data:p,error:g}=await V.from("coaches").select("id, user_id");if(g)throw g;const x=(p||[]).map(_=>_.user_id);if(!x.length)return[];const{data:y}=await V.from("profiles").select("id, name, email").in("id",x),v=new Map((y||[]).map(_=>[_.id,_]));return(p||[]).map(_=>{var j,C;return{id:_.id,label:((j=v.get(_.user_id))==null?void 0:j.name)||((C=v.get(_.user_id))==null?void 0:C.email)||_.user_id}})}}),{data:l=[],isLoading:o}=pt({queryKey:["admin-coaching-assignments"],queryFn:async()=>{const{data:p,error:g}=await V.from("coaching_assignments").select("*").order("created_at",{ascending:!1});if(g)throw g;const x=[...new Set((p||[]).map(_=>_.agent_id))],{data:y}=x.length?await V.from("profiles").select("id, name, email").in("id",x):{data:[]},v=new Map((y||[]).map(_=>[_.id,_]));return(p||[]).map(_=>({..._,agent:v.get(_.agent_id)}))}}),c=p=>{var g;return((g=i.find(x=>x.id===p))==null?void 0:g.label)||"—"},d=k.useMemo(()=>{const p=t.trim().toLowerCase();return l.filter(g=>{var x,y;return r!=="all"&&g.status!==r?!1:p?(((x=g.agent)==null?void 0:x.name)||"").toLowerCase().includes(p)||(((y=g.agent)==null?void 0:y.email)||"").toLowerCase().includes(p)||c(g.coach_id).toLowerCase().includes(p):!0})},[l,t,r,i]),u=()=>{s.invalidateQueries({queryKey:["admin-coaching-assignments"]}),s.invalidateQueries({queryKey:["coach-roster"]})},h=async(p,g)=>{var v,_;if(g===p.coach_id||!await io({title:"Switch coach?",description:`${((v=p.agent)==null?void 0:v.name)||((_=p.agent)==null?void 0:_.email)} will move from ${c(p.coach_id)} to ${c(g)}. Session history stays with the assignment.`,confirmText:"Switch coach"}))return;const{error:y}=await V.from("coaching_assignments").update({coach_id:g}).eq("id",p.id);if(y)return ae.error(y.message);ae.success("Coach switched"),u()},m=async(p,g)=>{var y,v;if(g==="ended"&&!await io({title:"End assignment?",description:`${((y=p.agent)==null?void 0:y.name)||((v=p.agent)==null?void 0:v.email)} will lose access to the coaching workspace unless they have standalone access.`,confirmText:"End assignment",destructive:!0}))return;const{error:x}=await V.from("coaching_assignments").update({status:g,ended_at:g==="ended"?new Date().toISOString():null}).eq("id",p.id);if(x)return ae.error(x.message);ae.success(g==="ended"?"Assignment ended":"Assignment reactivated"),u()};return e.jsx(we,{children:e.jsxs(De,{className:"p-4 space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Xn,{className:"h-5 w-5 text-primary"}),e.jsx("h2",{className:"text-lg font-semibold",children:"Coach assignments"}),e.jsx(qe,{variant:"secondary",className:"ml-auto",children:d.length})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Switch an agent to a different coach, end an assignment, or reactivate a past one."}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-2",children:[e.jsx(be,{placeholder:"Search by agent or coach…",value:t,onChange:p=>n(p.target.value)}),e.jsxs(bs,{value:r,onValueChange:p=>a(p),children:[e.jsx(ys,{className:"sm:w-40",children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"active",children:"Active"}),e.jsx(We,{value:"ended",children:"Ended"}),e.jsx(We,{value:"all",children:"All"})]})]})]}),o?e.jsx("div",{className:"text-sm text-muted-foreground",children:"Loading…"}):d.length===0?e.jsx("div",{className:"text-sm text-muted-foreground py-6 text-center",children:"No assignments found."}):e.jsx("div",{className:"divide-y border rounded-md",children:d.map(p=>{var g,x,y;return e.jsxs("div",{className:"p-3 flex flex-col md:flex-row md:items-center gap-3",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"font-medium truncate",children:((g=p.agent)==null?void 0:g.name)||((x=p.agent)==null?void 0:x.email)||p.agent_id}),e.jsxs("div",{className:"text-xs text-muted-foreground truncate",children:[(y=p.agent)==null?void 0:y.email," · ",p.pipeline_stage||"onboarding",p.status==="ended"&&" · ended"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(bK,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsxs(bs,{value:p.coach_id,onValueChange:v=>h(p,v),children:[e.jsx(ys,{className:"w-full md:w-56 h-9",children:e.jsx(_s,{})}),e.jsx(vs,{children:i.map(v=>e.jsx(We,{value:v.id,children:v.label},v.id))})]}),p.status==="active"?e.jsxs($,{variant:"outline",size:"sm",onClick:()=>m(p,"ended"),children:[e.jsx(gB,{className:"h-4 w-4 mr-1"})," End"]}):e.jsxs($,{variant:"outline",size:"sm",onClick:()=>m(p,"active"),children:[e.jsx(jm,{className:"h-4 w-4 mr-1"})," Reactivate"]})]})]},p.id)})})]})})}function KCs(){const s=ls(),[t,n]=k.useState(""),[r,a]=k.useState([]),[i,l]=k.useState(null),{data:o=[],isLoading:c}=pt({queryKey:["admin-coaches"],queryFn:async()=>{const{data:h,error:m}=await V.from("coaches").select("*").order("created_at",{ascending:!1});if(m)throw m;if(!(h!=null&&h.length))return[];const p=h.map(y=>y.user_id),{data:g}=await V.from("profiles").select("id, name, email, avatar_url").in("id",p),x=new Map((g||[]).map(y=>[y.id,y]));return h.map(y=>({...y,profile:x.get(y.user_id)}))}});k.useEffect(()=>{const h=t.trim();if(h.length<2){a([]);return}const m=setTimeout(async()=>{const{data:p}=await V.from("profiles").select("id, email, name, avatar_url").or(`email.ilike.%${h}%,name.ilike.%${h}%`).limit(10);a(p||[])},250);return()=>clearTimeout(m)},[t]);const d=async h=>{const{error:m}=await V.functions.invoke("manage-user-roles",{body:{userId:h.id,role:"coach",action:"add"}});if(m)return ae.error(m.message);const{error:p}=await V.from("coaches").insert({user_id:h.id});if(p&&!String(p.message).includes("duplicate"))return ae.error(p.message);ae.success(`${h.name||h.email} is now a coach`),n(""),a([]),s.invalidateQueries({queryKey:["admin-coaches"]})},u=async(h,m)=>{const{error:p}=await V.from("coaches").update({is_certified:m}).eq("id",h);if(p)return ae.error(p.message);ae.success(m?"Marked Certified":"Removed certification"),s.invalidateQueries({queryKey:["admin-coaches"]})};return e.jsxs(Xs,{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(Bm,{className:"h-7 w-7 text-primary"}),e.jsx("h1",{className:"text-2xl font-bold",children:"LevelUp Coaching"})]}),e.jsxs(ya,{defaultValue:"coaches",className:"space-y-6",children:[e.jsxs(va,{className:"flex-wrap h-auto",children:[e.jsx(is,{value:"coaches",children:"Coaches"}),e.jsx(is,{value:"assignments",children:"Assignments"}),e.jsx(is,{value:"access",children:"Coaching Access"}),e.jsx(is,{value:"applications",children:"Applications"}),e.jsx(is,{value:"settings",children:"Settings"})]}),e.jsx(cs,{value:"assignments",className:"space-y-6",children:e.jsx(WCs,{})}),e.jsx(cs,{value:"access",className:"space-y-6",children:e.jsx(HCs,{})}),e.jsx(cs,{value:"applications",className:"space-y-6",children:e.jsx(XCs,{})}),e.jsx(cs,{value:"settings",className:"space-y-6",children:e.jsx(YCs,{})}),e.jsxs(cs,{value:"coaches",className:"space-y-6",children:[e.jsx(we,{children:e.jsxs(De,{className:"p-4 space-y-3",children:[e.jsx(be,{placeholder:"Search by user email or name…",value:t,onChange:h=>n(h.target.value)}),t.trim().length>=2&&e.jsx("div",{className:"border rounded-md divide-y max-h-72 overflow-auto",children:r.length===0?e.jsx("div",{className:"p-3 text-sm text-muted-foreground",children:"No users found"}):r.map(h=>e.jsxs("div",{className:"flex items-center justify-between p-2 hover:bg-muted/40",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-medium truncate",children:h.name||h.email}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:h.email})]}),e.jsxs($,{size:"sm",onClick:()=>d(h),children:[e.jsx(nn,{className:"h-4 w-4 mr-1"})," Make Coach"]})]},h.id))})]})}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-semibold mb-3",children:"Coaches"}),c?e.jsx("div",{children:"Loading…"}):o.length===0?e.jsx(we,{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(h=>{var m,p,g;return e.jsx(we,{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:((m=h.profile)==null?void 0:m.name)||((p=h.profile)==null?void 0:p.email)||h.user_id}),e.jsx("div",{className:"text-xs text-muted-foreground",children:(g=h.profile)==null?void 0:g.email}),e.jsxs("div",{className:"flex gap-2 mt-2 flex-wrap",children:[h.is_certified&&e.jsxs(qe,{className:"bg-yellow-500/15 text-yellow-700 border-yellow-300/40",children:[e.jsx(kn,{className:"h-3 w-3 mr-1"}),"Certified"]}),h.accepting_clients&&e.jsx(qe,{variant:"outline",children:"Accepting clients"})]})]}),e.jsxs($,{size:"sm",variant:"outline",onClick:()=>l(h.id),children:[e.jsx(Pl,{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(On,{checked:h.is_certified,onCheckedChange:x=>u(h.id,x)})]})]})},h.id)})})]})]})]})]}),e.jsx(ZCs,{coachId:i,onClose:()=>l(null)})]})}function YCs(){const[s,t]=k.useState("1500"),[n,r]=k.useState(!1),[a,i]=k.useState(!1);k.useEffect(()=>{(async()=>{const{data:c}=await V.from("settings").select("value").eq("key","coaching_platform_fee_bps").maybeSingle();c!=null&&c.value&&t(String(c.value)),i(!0)})()},[]);const l=async()=>{const c=parseInt(s,10);if(isNaN(c)||c<0||c>5e3)return ae.error("Enter a value between 0 and 5000 bps (0–50%)");r(!0);const{error:d}=await V.from("settings").upsert({key:"coaching_platform_fee_bps",value:String(c)});if(r(!1),d)return ae.error(d.message);ae.success("Platform fee updated")};if(!a)return null;const o=(parseInt(s,10)/100).toFixed(2);return e.jsx(we,{children:e.jsxs(De,{className:"p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ZT,{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(re,{children:"Fee (bps)"}),e.jsx(be,{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($,{onClick:l,disabled:n,className:"bg-[#406E71] hover:bg-[#2a4c64] self-end",children:n?"Saving…":"Save"})]})]})})}function ZCs({coachId:s,onClose:t}){const[n,r]=k.useState(""),[a,i]=k.useState([]),[l,o]=k.useState(!1),c=ls();k.useEffect(()=>{if(!s){r(""),i([]);return}},[s]),k.useEffect(()=>{const u=n.trim();if(u.length<2){i([]);return}o(!0);const h=setTimeout(async()=>{const{data:m}=await V.from("profiles").select("id, name, email").or(`email.ilike.%${u}%,name.ilike.%${u}%`).limit(15);i(m||[]),o(!1)},250);return()=>clearTimeout(h)},[n]);const d=async u=>{const{error:h}=await V.from("coaching_assignments").insert({coach_id:s,agent_id:u,status:"active",source:"admin",pipeline_stage:"onboarding"});if(h)return ae.error(h.message);ae.success("Agent assigned"),c.invalidateQueries({queryKey:["coach-roster"]}),t()};return e.jsx(zs,{open:!!s,onOpenChange:u=>!u&&t(),children:e.jsxs(Rs,{children:[e.jsx(Vs,{children:e.jsx($s,{children:"Assign Agent"})}),e.jsx(be,{placeholder:"Search agents by name or email…",value:n,onChange:u=>r(u.target.value),autoFocus:!0}),e.jsx("div",{className:"space-y-1 max-h-72 overflow-auto border rounded-md",children:n.trim().length<2?e.jsx("div",{className:"p-3 text-sm text-muted-foreground",children:"Type at least 2 characters to search…"}):l?e.jsx("div",{className:"p-3 text-sm text-muted-foreground",children:"Searching…"}):a.length===0?e.jsx("div",{className:"p-3 text-sm text-muted-foreground",children:"No agents found"}):a.map(u=>e.jsxs("button",{onClick:()=>d(u.id),className:"w-full text-left p-2 hover:bg-muted",children:[e.jsx("div",{className:"font-medium",children:u.name||u.email}),e.jsx("div",{className:"text-xs text-muted-foreground",children:u.email})]},u.id))}),e.jsx(kr,{children:e.jsx($,{variant:"outline",onClick:t,children:"Close"})})]})})}function XCs(){const s=ls(),[t,n]=k.useState("pending"),[r,a]=k.useState(null),{data:i=[],isLoading:l}=pt({queryKey:["coach-applications",t],queryFn:async()=>{let u=V.from("coach_applications").select("*").order("created_at",{ascending:!1});t!=="all"&&(u=u.eq("status",t));const{data:h,error:m}=await u;if(m)throw m;return h||[]}}),{data:o=0}=pt({queryKey:["coach-applications-pending-count"],queryFn:async()=>{const{count:u}=await V.from("coach_applications").select("id",{count:"exact",head:!0}).eq("status","pending");return u||0}}),c=async(u,h)=>{const{error:m}=await V.from("coach_applications").update({status:h,reviewed_at:new Date().toISOString()}).eq("id",u);if(m)return ae.error(m.message);ae.success(`Marked ${h}`),s.invalidateQueries({queryKey:["coach-applications"]}),s.invalidateQueries({queryKey:["coach-applications-pending-count"]}),a(null)},d=u=>u==="approved"?e.jsxs(qe,{className:"bg-emerald-500/15 text-emerald-700 border-emerald-300/40",children:[e.jsx(ma,{className:"h-3 w-3 mr-1"}),"Approved"]}):u==="rejected"?e.jsxs(qe,{className:"bg-rose-500/15 text-rose-700 border-rose-300/40",children:[e.jsx(mr,{className:"h-3 w-3 mr-1"}),"Rejected"]}):e.jsxs(qe,{className:"bg-yellow-500/15 text-yellow-700 border-yellow-300/40",children:[e.jsx(sa,{className:"h-3 w-3 mr-1"}),"Pending"]});return e.jsxs(we,{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(HT,{className:"h-5 w-5 text-primary"}),e.jsx("h2",{className:"text-lg font-semibold",children:"Coach Applications"}),o>0&&e.jsxs(qe,{className:"bg-yellow-500/15 text-yellow-700 border-yellow-300/40",children:[o," pending"]}),e.jsx("div",{className:"ml-auto flex gap-1 flex-wrap",children:["pending","approved","rejected","all"].map(u=>e.jsx($,{size:"sm",variant:t===u?"default":"outline",onClick:()=>n(u),className:t===u?"bg-[#406E71] hover:bg-[#2a4c64]":"",children:u.charAt(0).toUpperCase()+u.slice(1)},u))})]}),l?e.jsx("div",{className:"text-sm text-muted-foreground",children:"Loading…"}):i.length===0?e.jsxs("div",{className:"text-sm text-muted-foreground p-6 text-center border rounded-md",children:["No applications ",t!=="all"?`with status "${t}"`:"yet","."]}):e.jsx("div",{className:"divide-y border rounded-md",children:i.map(u=>e.jsx("button",{onClick:()=>a(u),className:"w-full text-left p-3 hover:bg-muted/40 transition-colors",children:e.jsxs("div",{className:"flex items-center justify-between gap-3 flex-wrap",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-medium",children:u.full_name}),e.jsxs("div",{className:"text-xs text-muted-foreground flex items-center gap-3 mt-0.5",children:[e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(pn,{className:"h-3 w-3"}),u.email]}),u.brokerage&&e.jsxs("span",{children:["· ",u.brokerage]}),u.years_experience&&e.jsxs("span",{children:["· ",u.years_experience," yrs"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[d(u.status),e.jsx("span",{className:"text-xs text-muted-foreground",children:new Date(u.created_at).toLocaleDateString()})]})]})},u.id))})]}),e.jsx(zs,{open:!!r,onOpenChange:u=>!u&&a(null),children:e.jsx(Rs,{className:"max-w-2xl max-h-[85vh] overflow-y-auto",children:r&&e.jsxs(e.Fragment,{children:[e.jsx(Vs,{children:e.jsxs($s,{className:"flex items-center gap-3",children:[r.full_name,d(r.status)]})}),e.jsxs("div",{className:"space-y-4 text-sm",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(H7,{icon:pn,label:"Email",value:r.email,link:`mailto:${r.email}`}),r.phone&&e.jsx(H7,{icon:ka,label:"Phone",value:r.phone,link:`tel:${r.phone}`}),r.brokerage&&e.jsx(H7,{label:"Brokerage",value:r.brokerage}),r.years_experience&&e.jsx(H7,{label:"Years",value:r.years_experience}),r.website_url&&e.jsx(H7,{icon:Ir,label:"Website",value:r.website_url,link:r.website_url}),r.linkedin_url&&e.jsx(H7,{icon:Ir,label:"LinkedIn",value:r.linkedin_url,link:r.linkedin_url})]}),r.specialties&&e.jsx(sLe,{label:"Specialties",children:r.specialties}),e.jsx(sLe,{label:"Why they want to coach",children:r.why_coach}),r.results_story&&e.jsx(sLe,{label:"Results story",children:r.results_story}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs font-semibold uppercase text-muted-foreground",children:"Admin notes"}),e.jsx(Ls,{defaultValue:r.admin_notes||"",rows:3,onBlur:async u=>{const h=u.target.value;h!==(r.admin_notes||"")&&(await V.from("coach_applications").update({admin_notes:h}).eq("id",r.id),s.invalidateQueries({queryKey:["coach-applications"]}))},placeholder:"Internal notes (saved on blur)…"})]})]}),e.jsxs(kr,{className:"gap-2 flex-wrap",children:[r.status!=="rejected"&&e.jsxs($,{variant:"outline",onClick:()=>c(r.id,"rejected"),className:"text-rose-600 border-rose-200 hover:bg-rose-50",children:[e.jsx(mr,{className:"h-4 w-4 mr-1"})," Reject"]}),r.status!=="pending"&&e.jsxs($,{variant:"outline",onClick:()=>c(r.id,"pending"),children:[e.jsx(sa,{className:"h-4 w-4 mr-1"})," Move to pending"]}),r.status!=="approved"&&e.jsxs($,{onClick:()=>c(r.id,"approved"),className:"bg-emerald-600 hover:bg-emerald-700",children:[e.jsx(ma,{className:"h-4 w-4 mr-1"})," Approve"]})]})]})})})]})}function H7({icon:s,label:t,value:n,link:r}){const a=e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[s&&e.jsx(s,{className:"h-3.5 w-3.5"}),n]});return e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] font-semibold uppercase text-muted-foreground tracking-wide",children:t}),e.jsx("div",{className:"text-sm",children:r?e.jsx("a",{href:r,target:"_blank",rel:"noreferrer",className:"text-[#406E71] hover:underline break-all",children:a}):a})]})}function sLe({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 QCs(){const s=Jn(),{data:t}=See(),n=ls(),[r,a]=k.useState(!1),[i,l]=k.useState(!1),[o,c]=k.useState(null),{data:d,refetch:u}=pt({queryKey:["coach-stripe-status",t==null?void 0:t.id],enabled:!!t,queryFn:async()=>{const{data:y}=await V.functions.invoke("coach-stripe-status");return y}}),{data:h=[]}=pt({queryKey:["coach-packages",t==null?void 0:t.id],enabled:!!t,queryFn:async()=>{const{data:y}=await V.from("coaching_packages").select("*").eq("coach_id",t.id).order("sort_order");return y||[]}});k.useEffect(()=>{const y=new URLSearchParams(window.location.search);(y.get("onboarded")||y.get("refresh"))&&u()},[u]);const m=async()=>{var j,C;a(!0);const{data:y,error:v}=await V.functions.invoke("coach-stripe-connect");a(!1);let _=y==null?void 0:y.error;if(!_&&v)try{const A=await((C=(j=v==null?void 0:v.context)==null?void 0:j.json)==null?void 0:C.call(j));_=(A==null?void 0:A.error)||v.message}catch{_=v.message}if(_)return ae.error(_,{duration:1e4});y!=null&&y.url&&(window.location.href=y.url)},p=d||{},g=!!(t!=null&&t.use_platform_stripe),x=g||p.connected&&p.charges_enabled;return e.jsx(Xs,{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($,{variant:"ghost",size:"icon",onClick:()=>s("/coaching"),children:e.jsx(Ia,{className:"h-5 w-5"})}),e.jsx("h1",{className:"text-2xl font-bold",children:"Billing & Packages"})]}),e.jsx(we,{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(cv,{className:"h-5 w-5"})," Stripe Connect"]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:g?"Your coaching sales are billed through the main LevelUp Stripe account.":"Payouts go directly to your bank. LevelUp takes a small platform fee from each charge."})]}),x?e.jsxs(qe,{className:"bg-emerald-500/15 text-emerald-700 border-emerald-300/40 flex items-center gap-1",children:[e.jsx(Gr,{className:"h-3 w-3"})," ",g?"Using LevelUp billing":"Connected"]}):p.connected?e.jsxs(qe,{variant:"secondary",className:"flex items-center gap-1",children:[e.jsx(Ho,{className:"h-3 w-3"})," Setup incomplete"]}):e.jsx(qe,{variant:"outline",children:"Not connected"})]}),!g&&e.jsxs($,{onClick:m,disabled:r,className:"bg-[#406E71] hover:bg-[#2a4c64]",children:[x?"Update Stripe details":p.connected?"Finish Stripe setup":"Connect Stripe",e.jsx(Ir,{className:"h-4 w-4 ml-1"})]})]})}),e.jsx(we,{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($,{size:"sm",onClick:()=>{c(null),l(!0)},disabled:!x,children:[e.jsx(nn,{className:"h-4 w-4 mr-1"})," New Package"]})]}),!x&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Connect Stripe before creating packages."}),h.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-6",children:"No packages yet."}):e.jsx("div",{className:"space-y-2",children:h.map(y=>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:[y.name,y.is_active&&y.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:["$",(y.price_cents/100).toFixed(0)," / ",y.billing_interval,!y.is_active&&" · Inactive"]})]}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>{c(y),l(!0)},children:e.jsx(ui,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:async()=>{await io("Delete this package?")&&(await V.from("coaching_packages").delete().eq("id",y.id),n.invalidateQueries({queryKey:["coach-packages",t==null?void 0:t.id]}))},children:e.jsx(Un,{className:"h-4 w-4"})})]},y.id))})]})}),e.jsx(JCs,{open:i,onOpenChange:l,coachId:t==null?void 0:t.id,pkg:o,onSaved:()=>n.invalidateQueries({queryKey:["coach-packages",t==null?void 0:t.id]})})]})})}function JCs({open:s,onOpenChange:t,coachId:n,pkg:r,onSaved:a}){const[i,l]=k.useState(""),[o,c]=k.useState(""),[d,u]=k.useState(""),[h,m]=k.useState("month"),[p,g]=k.useState(!0),[x,y]=k.useState(!0),[v,_]=k.useState(!1);k.useEffect(()=>{s&&(l((r==null?void 0:r.name)||""),c((r==null?void 0:r.description)||""),u(r?(r.price_cents/100).toString():""),m((r==null?void 0:r.billing_interval)||"month"),g((r==null?void 0:r.is_active)??!0),y((r==null?void 0:r.accepting_clients)??!0))},[s,r]);const j=async()=>{if(!i.trim()||!d)return ae.error("Name and price required");_(!0);const C={coach_id:n,name:i,description:o||null,price_cents:Math.round(Number(d)*100),billing_interval:h,is_active:p,accepting_clients:x},{error:A}=r!=null&&r.id?await V.from("coaching_packages").update(C).eq("id",r.id):await V.from("coaching_packages").insert(C);if(_(!1),A)return ae.error(A.message);ae.success("Saved"),a==null||a(),t(!1)};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Rs,{children:[e.jsx(Vs,{children:e.jsx($s,{children:r!=null&&r.id?"Edit Package":"New Package"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(be,{placeholder:"Name (e.g. Accelerator)",value:i,onChange:C=>l(C.target.value)}),e.jsx(Ls,{rows:3,placeholder:"What's included",value:o,onChange:C=>c(C.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(be,{type:"number",value:d,onChange:C=>u(C.target.value)})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Interval"}),e.jsxs(bs,{value:h,onValueChange:m,children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"month",children:"Monthly"}),e.jsx(We,{value:"year",children:"Yearly"}),e.jsx(We,{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:p,onChange:C=>g(C.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:x,onChange:C=>y(C.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(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx($,{onClick:j,disabled:v,children:r!=null&&r.id?"Save":"Create"})]})]})})}function zct({kind:s,value:t,onChange:n}){const r=k.useRef(null),[a,i]=k.useState(!1),[l,o]=k.useState(!1),[c,d]=k.useState(null),u=k.useRef(null),h=k.useRef(null),m=k.useRef(null),p=k.useRef([]),[g,x]=k.useState(!1),y=s==="photo"?"image/*":"video/*",v=s==="photo"?10*1024*1024:200*1024*1024,_=async(P,R)=>{var Y;const{data:O}=await V.auth.getUser(),B=(Y=O.user)==null?void 0:Y.id;if(!B)return ae.error("Not signed in");if(P.size>v)return ae.error(`File too large. Max ${s==="photo"?"10MB":"200MB"}.`);i(!0);const U=`${B}/${s}-${Date.now()}.${R}`,{error:G}=await V.storage.from("coach-media").upload(U,P,{upsert:!0,contentType:P.type||(s==="photo"?"image/jpeg":"video/webm")});if(G)return i(!1),ae.error(G.message);const{data:H}=await V.storage.from("coach-media").createSignedUrl(U,60*60*24*365*10);i(!1),H!=null&&H.signedUrl&&(n(H.signedUrl),ae.success("Uploaded"),d(null))},j=async P=>{const R=P.name.split(".").pop()||(s==="photo"?"jpg":"webm");await _(P,R)},C=async()=>{try{const P=await navigator.mediaDevices.getUserMedia({video:!0,audio:!0});h.current=P,x(!0),setTimeout(()=>{u.current&&(u.current.srcObject=P,u.current.play())},50);const R=new MediaRecorder(P,{mimeType:"video/webm"});p.current=[],R.ondataavailable=O=>O.data.size>0&&p.current.push(O.data),R.onstop=()=>{const O=new Blob(p.current,{type:"video/webm"});d(O),P.getTracks().forEach(B=>B.stop())},m.current=R,R.start(),o(!0)}catch(P){ae.error(P.message||"Could not access camera")}},A=()=>{var P;(P=m.current)==null||P.stop(),o(!1)},M=()=>{var P;(P=h.current)==null||P.getTracks().forEach(R=>R.stop()),x(!1),o(!1),d(null)},I=async()=>{c&&(await _(c,"webm"),M())};return k.useEffect(()=>()=>{var P;return(P=h.current)==null?void 0:P.getTracks().forEach(R=>R.stop())},[]),e.jsxs("div",{className:"space-y-2",children:[t&&e.jsx("div",{className:"rounded-lg overflow-hidden border bg-muted/30",children:s==="photo"?e.jsx("img",{src:t,alt:"Profile",className:"w-32 h-32 object-cover"}):e.jsx("video",{src:t,controls:!0,className:"w-full max-h-64"})}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx("input",{ref:r,type:"file",accept:y,className:"hidden",onChange:P=>{var O;const R=(O=P.target.files)==null?void 0:O[0];R&&j(R),P.target.value=""}}),e.jsxs($,{type:"button",variant:"outline",size:"sm",disabled:a,onClick:()=>{var P;return(P=r.current)==null?void 0:P.click()},children:[a?e.jsx(Jt,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(gi,{className:"h-4 w-4 mr-1"}),s==="photo"?"Upload photo":"Upload video"]}),s==="video"&&e.jsxs($,{type:"button",variant:"outline",size:"sm",onClick:C,disabled:a||g,children:[e.jsx(g0,{className:"h-4 w-4 mr-1"})," Record intro"]}),t&&e.jsxs($,{type:"button",variant:"ghost",size:"sm",onClick:()=>n(""),children:[e.jsx(Un,{className:"h-4 w-4 mr-1"})," Remove"]})]}),g&&e.jsxs("div",{className:"rounded-lg border p-3 space-y-3 bg-background",children:[c?e.jsx("video",{src:URL.createObjectURL(c),controls:!0,className:"w-full max-h-64 rounded bg-black"}):e.jsx("video",{ref:u,muted:!0,playsInline:!0,className:"w-full max-h-64 rounded bg-black"}),e.jsxs("div",{className:"flex gap-2",children:[!c&&l&&e.jsxs($,{type:"button",size:"sm",onClick:A,className:"bg-red-600 hover:bg-red-700",children:[e.jsx(w_,{className:"h-4 w-4 mr-1"})," Stop"]}),!c&&!l&&e.jsxs($,{type:"button",size:"sm",onClick:()=>{var P;return(P=m.current)==null?void 0:P.start()},children:[e.jsx(ia,{className:"h-4 w-4 mr-1"})," Start"]}),c&&e.jsxs(e.Fragment,{children:[e.jsxs($,{type:"button",size:"sm",onClick:I,disabled:a,className:"bg-[#406E71] hover:bg-[#2a4c64]",children:[a?e.jsx(Jt,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(gi,{className:"h-4 w-4 mr-1"}),"Use this recording"]}),e.jsx($,{type:"button",size:"sm",variant:"outline",onClick:()=>{d(null),C()},children:"Re-record"})]}),e.jsx($,{type:"button",size:"sm",variant:"ghost",onClick:M,children:"Cancel"})]})]})]})}function NMt(){const{user:s}=ks(),t=ls(),n=pt({queryKey:["booking-settings",s==null?void 0:s.id],queryFn:async()=>{const{data:y,error:v}=await V.from("agent_booking_settings").select("*").eq("user_id",s.id).maybeSingle();if(v)throw v;return y},enabled:!!s}),r=pt({queryKey:["booking-types",s==null?void 0:s.id],queryFn:async()=>{const{data:y,error:v}=await V.from("agent_booking_types").select("*").eq("user_id",s.id).order("sort_order");if(v)throw v;return y},enabled:!!s}),a=pt({queryKey:["availability-slots",s==null?void 0:s.id],queryFn:async()=>{const{data:y,error:v}=await V.from("agent_availability_slots").select("*").eq("user_id",s.id).order("day_of_week").order("start_time");if(v)throw v;return y},enabled:!!s}),i=pt({queryKey:["blocked-dates",s==null?void 0:s.id],queryFn:async()=>{const{data:y,error:v}=await V.from("agent_blocked_dates").select("*").eq("user_id",s.id).order("blocked_date");if(v)throw v;return y},enabled:!!s}),l=pt({queryKey:["bookings",s==null?void 0:s.id],queryFn:async()=>{const{data:y,error:v}=await V.from("bookings").select("*, booking_type:agent_booking_types(*)").eq("agent_user_id",s.id).order("booking_date",{ascending:!1});if(v)throw v;return y},enabled:!!s}),o=Nt({mutationFn:async()=>{const{data:y,error:v}=await V.from("agent_booking_settings").insert({user_id:s.id,slug:""}).select().single();if(v)throw v;const _=[{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:j}=await V.from("agent_booking_types").insert(_.map(M=>({...M,user_id:s.id})));if(j)throw j;const C=[1,2,3,4,5].map(M=>({user_id:s.id,day_of_week:M,start_time:"09:00",end_time:"17:00"})),{error:A}=await V.from("agent_availability_slots").insert(C);if(A)throw A;return y},onSuccess:()=>{t.invalidateQueries({queryKey:["booking-settings"]}),t.invalidateQueries({queryKey:["booking-types"]}),t.invalidateQueries({queryKey:["availability-slots"]}),ae.success("Scheduler set up successfully!")},onError:y=>ae.error(y.message)}),c=Nt({mutationFn:async y=>{const{error:v}=await V.from("agent_booking_settings").update(y).eq("user_id",s.id);if(v)throw v},onSuccess:()=>{t.invalidateQueries({queryKey:["booking-settings"]}),ae.success("Settings updated")},onError:y=>ae.error(y.message)}),d=Nt({mutationFn:async y=>{const v={...y,user_id:s.id};if(y.id){const{error:_}=await V.from("agent_booking_types").update(v).eq("id",y.id);if(_)throw _}else{const{error:_}=await V.from("agent_booking_types").insert(v);if(_)throw _}},onSuccess:()=>{t.invalidateQueries({queryKey:["booking-types"]}),ae.success("Booking type saved")},onError:y=>ae.error(y.message)}),u=Nt({mutationFn:async y=>{const{error:v}=await V.from("agent_booking_types").delete().eq("id",y);if(v)throw v},onSuccess:()=>{t.invalidateQueries({queryKey:["booking-types"]}),ae.success("Booking type deleted")},onError:y=>ae.error(y.message)}),h=Nt({mutationFn:async y=>{const v={...y,user_id:s.id};if(y.id){const{error:_}=await V.from("agent_availability_slots").update(v).eq("id",y.id);if(_)throw _}else{const{error:_}=await V.from("agent_availability_slots").insert(v);if(_)throw _}},onSuccess:()=>{t.invalidateQueries({queryKey:["availability-slots"]})},onError:y=>ae.error(y.message)}),m=Nt({mutationFn:async y=>{const{error:v}=await V.from("agent_availability_slots").delete().eq("id",y);if(v)throw v},onSuccess:()=>{t.invalidateQueries({queryKey:["availability-slots"]})},onError:y=>ae.error(y.message)}),p=Nt({mutationFn:async y=>{const{error:v}=await V.from("agent_blocked_dates").insert({...y,user_id:s.id});if(v)throw v},onSuccess:()=>{t.invalidateQueries({queryKey:["blocked-dates"]}),ae.success("Date blocked")},onError:y=>ae.error(y.message)}),g=Nt({mutationFn:async y=>{const{error:v}=await V.from("agent_blocked_dates").delete().eq("id",y);if(v)throw v},onSuccess:()=>{t.invalidateQueries({queryKey:["blocked-dates"]})},onError:y=>ae.error(y.message)}),x=Nt({mutationFn:async({id:y,reason:v})=>{const{error:_}=await V.from("bookings").update({status:"cancelled",cancelled_at:new Date().toISOString(),cancel_reason:v}).eq("id",y);if(_)throw _;await V.functions.invoke("agent-booking",{body:{action:"cancel",booking_id:y}}).catch(j=>console.error("Google calendar cleanup failed:",j))},onSuccess:()=>{t.invalidateQueries({queryKey:["bookings"]}),ae.success("Booking cancelled")},onError:y=>ae.error(y.message)});return{settings:n.data,bookingTypes:r.data??[],availability:a.data??[],blockedDates:i.data??[],bookings:l.data??[],isLoading:n.isLoading,initializeSettings:o,updateSettings:c,upsertBookingType:d,deleteBookingType:u,upsertAvailability:h,deleteAvailability:m,addBlockedDate:p,removeBlockedDate:g,cancelBooking:x}}const Bct=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];function kMt({slots:s,onSave:t,onDelete:n}){const[r,a]=k.useState(null),[i,l]=k.useState("09:00"),[o,c]=k.useState("17:00"),d=Bct.map((h,m)=>s.filter(p=>p.day_of_week===m)),u=()=>{r!==null&&(t({day_of_week:r,start_time:i,end_time:o,is_active:!0}),a(null),l("09:00"),c("17:00"))};return e.jsxs(we,{children:[e.jsxs(Vt,{children:[e.jsxs(Yt,{className:"flex items-center gap-2",children:[e.jsx(sa,{className:"h-5 w-5"}),"Weekly Availability"]}),e.jsx(vr,{children:"Set your available hours for each day"})]}),e.jsx(De,{className:"space-y-2",children:Bct.map((h,m)=>{const p=d[m];return e.jsxs("div",{className:"flex items-start gap-3 py-2 border-b last:border-0",children:[e.jsx("div",{className:"w-24 pt-1",children:e.jsx("p",{className:"text-sm font-medium",children:h})}),e.jsxs("div",{className:"flex-1 space-y-1",children:[p.length===0?e.jsx("p",{className:"text-sm text-muted-foreground py-1",children:"Unavailable"}):p.map(g=>{var x,y;return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(be,{type:"time",className:"w-28 h-8 text-sm",defaultValue:(x=g.start_time)==null?void 0:x.slice(0,5),onBlur:v=>t({id:g.id,start_time:v.target.value})}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"to"}),e.jsx(be,{type:"time",className:"w-28 h-8 text-sm",defaultValue:(y=g.end_time)==null?void 0:y.slice(0,5),onBlur:v=>t({id:g.id,end_time:v.target.value})}),e.jsx(On,{checked:g.is_active,onCheckedChange:v=>t({id:g.id,is_active:v})}),e.jsx($,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>n(g.id),children:e.jsx(Un,{className:"h-3.5 w-3.5 text-muted-foreground"})})]},g.id)}),r===m?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(be,{type:"time",className:"w-28 h-8 text-sm",value:i,onChange:g=>l(g.target.value)}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"to"}),e.jsx(be,{type:"time",className:"w-28 h-8 text-sm",value:o,onChange:g=>c(g.target.value)}),e.jsx($,{size:"sm",className:"h-8",onClick:u,children:"Add"}),e.jsx($,{variant:"ghost",size:"sm",className:"h-8",onClick:()=>a(null),children:"Cancel"})]}):e.jsxs($,{variant:"ghost",size:"sm",className:"h-7 text-xs text-muted-foreground",onClick:()=>a(m),children:[e.jsx(nn,{className:"h-3 w-3 mr-1"})," Add hours"]})]})]},h)})})]})}function SMt({blockedDates:s,onAdd:t,onRemove:n}){const[r,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(we,{children:[e.jsxs(Vt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(Yt,{className:"flex items-center gap-2",children:[e.jsx(zz,{className:"h-5 w-5"}),"Blocked Dates"]}),e.jsx(vr,{children:"Block specific dates (vacations, holidays, etc.)"})]}),e.jsxs($,{size:"sm",variant:"outline",onClick:()=>a(!0),children:[e.jsx(nn,{className:"h-4 w-4 mr-1"})," Block Date"]})]}),e.jsxs(De,{children:[r&&e.jsxs("div",{className:"flex items-center gap-2 mb-3 p-3 rounded-lg border bg-muted/30",children:[e.jsx(be,{type:"date",value:i,onChange:u=>l(u.target.value),className:"w-40"}),e.jsx(be,{placeholder:"Reason (optional)",value:o,onChange:u=>c(u.target.value),className:"flex-1"}),e.jsx($,{size:"sm",onClick:d,children:"Add"}),e.jsx($,{size:"sm",variant:"ghost",onClick:()=>a(!1),children:"Cancel"})]}),s.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No blocked dates"}):e.jsx("div",{className:"flex flex-wrap gap-2",children:s.map(u=>e.jsxs("div",{className:"flex items-center gap-1.5 px-3 py-1.5 rounded-full border bg-muted/50 text-sm",children:[e.jsx("span",{children:Ys(new Date(u.blocked_date+"T00:00:00"),"MMM d, yyyy")}),u.reason&&e.jsxs("span",{className:"text-muted-foreground",children:["(",u.reason,")"]}),e.jsx("button",{onClick:()=>n(u.id),className:"ml-1 text-muted-foreground hover:text-destructive",children:e.jsx(mr,{className:"h-3.5 w-3.5"})})]},u.id))})]})]})}function e3s(){const{settings:s,bookingTypes:t,availability:n,blockedDates:r,isLoading:a,initializeSettings:i,updateSettings:l,upsertBookingType:o,deleteBookingType:c,upsertAvailability:d,deleteAvailability:u,addBlockedDate:h,removeBlockedDate:m}=NMt(),[p,g]=k.useState("1-on-1 Coaching Session"),[x,y]=k.useState(45),v=k.useMemo(()=>t.filter(j=>j.is_coaching_only),[t]);if(a)return e.jsx(we,{children:e.jsxs(De,{className:"p-6 flex items-center gap-2 text-muted-foreground",children:[e.jsx(Jt,{className:"h-4 w-4 animate-spin"})," Loading your calendar…"]})});if(!s)return e.jsxs(we,{children:[e.jsxs(Vt,{children:[e.jsxs(Yt,{className:"flex items-center gap-2",children:[e.jsx(wm,{className:"h-5 w-5"})," Coaching calendar"]}),e.jsx(vr,{children:"Set up your scheduler once, then open availability for the members assigned to you."})]}),e.jsx(De,{children:e.jsxs($,{onClick:()=>i.mutate(),disabled:i.isPending,children:[i.isPending&&e.jsx(Jt,{className:"h-4 w-4 mr-2 animate-spin"}),"Set up my calendar"]})})]});const _=()=>{p.trim()&&(o.mutate({name:p.trim(),description:"Private coaching session",duration_minutes:x,color:"#406E71",icon:"Video",is_active:!0,qualification_enabled:!1,is_coaching_only:!0,sort_order:99}),g("1-on-1 Coaching Session"),y(45))};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs(we,{children:[e.jsxs(Vt,{children:[e.jsxs(Yt,{className:"flex items-center gap-2",children:[e.jsx(ia,{className:"h-5 w-5"})," Coaching session types"]}),e.jsx(vr,{children:"Only assigned members can book these. They stay hidden from your public booking page."})]}),e.jsxs(De,{className:"space-y-3",children:[v.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No coaching session type yet — add one below so members can book you."}):v.map(j=>e.jsxs("div",{className:"flex flex-wrap items-center gap-3 rounded-lg border p-3",children:[e.jsx(be,{className:"h-9 max-w-[240px]",defaultValue:j.name,onBlur:C=>C.target.value!==j.name&&o.mutate({id:j.id,name:C.target.value})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(be,{type:"number",min:10,max:240,step:5,className:"h-9 w-20",defaultValue:j.duration_minutes,onBlur:C=>o.mutate({id:j.id,duration_minutes:parseInt(C.target.value)||30})}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"min"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(On,{checked:j.is_active,onCheckedChange:C=>o.mutate({id:j.id,is_active:C})}),e.jsx("span",{className:"text-sm text-muted-foreground",children:j.is_active?"Bookable":"Paused"})]}),e.jsx(qe,{variant:"secondary",children:"Coaching only"}),e.jsx($,{variant:"ghost",size:"sm",className:"ml-auto h-8 w-8 p-0",onClick:async()=>{await io({title:"Delete session type?",description:`"${j.name}" will no longer be bookable.`,confirmText:"Delete",destructive:!0})&&c.mutate(j.id)},children:e.jsx(Un,{className:"h-3.5 w-3.5 text-muted-foreground"})})]},j.id)),e.jsxs("div",{className:"flex flex-wrap items-end gap-2 pt-2 border-t",children:[e.jsxs("div",{className:"flex-1 min-w-[200px]",children:[e.jsx(re,{className:"text-xs",children:"New session type"}),e.jsx(be,{value:p,onChange:j=>g(j.target.value),className:"h-9"})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Minutes"}),e.jsx(be,{type:"number",min:10,max:240,step:5,className:"h-9 w-24",value:x,onChange:j=>y(parseInt(j.target.value)||30)})]}),e.jsxs($,{onClick:_,disabled:o.isPending,children:[e.jsx(nn,{className:"h-4 w-4 mr-1"})," Add"]})]})]})]}),e.jsx(kMt,{slots:n,onSave:j=>d.mutate(j),onDelete:j=>u.mutate(j)}),e.jsx(SMt,{blockedDates:r,onAdd:j=>h.mutate(j),onRemove:j=>m.mutate(j)}),e.jsxs(we,{children:[e.jsxs(Vt,{children:[e.jsx(Yt,{children:"Scheduling rules"}),e.jsx(vr,{children:"Applies to coaching bookings on your calendar."})]}),e.jsxs(De,{className:"grid gap-4 sm:grid-cols-3",children:[e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Buffer between sessions (min)"}),e.jsx(be,{type:"number",min:0,max:120,step:5,className:"h-9",defaultValue:s.buffer_minutes,onBlur:j=>l.mutate({buffer_minutes:parseInt(j.target.value)||0})})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Minimum notice (hours)"}),e.jsx(be,{type:"number",min:0,max:168,className:"h-9",defaultValue:s.min_notice_hours,onBlur:j=>l.mutate({min_notice_hours:parseInt(j.target.value)||0})})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Bookable up to (days out)"}),e.jsx(be,{type:"number",min:1,max:365,className:"h-9",defaultValue:s.max_advance_days,onBlur:j=>l.mutate({max_advance_days:parseInt(j.target.value)||30})})]})]})]})]})}async function dG(s,t){const n=s==="agent"?"agent-google-calendar":"coach-google-calendar",{data:r,error:a}=await V.functions.invoke(n,{body:t});if(a){let i=a.message;try{const l=a.context;if(l!=null&&l.json){const o=await l.json();o!=null&&o.error&&(i=o.error)}}catch{}throw new Error(i)}if(r!=null&&r.error)throw new Error(r.error);return r}function t3s(s=!0,t="coach"){const n=ls(),r=pt({queryKey:["google-calendar-connection",t],enabled:s,queryFn:async()=>await dG(t,{action:"status"})}),a=()=>n.invalidateQueries({queryKey:["google-calendar-connection",t]}),i=Nt({mutationFn:async()=>{const d=await dG(t,{action:"start",origin:window.location.origin}),u=d==null?void 0:d.authorizationUrl;if(!u)throw new Error("Google did not return an authorization link.");try{sessionStorage.setItem("googleCalendarReturnTo",window.location.pathname),sessionStorage.setItem("googleCalendarScope",t)}catch{}window.location.assign(u),await new Promise(h=>setTimeout(h,4e3))},onSuccess:a}),l=Nt({mutationFn:()=>dG(t,{action:"disconnect"}),onSuccess:a}),o=Nt({mutationFn:d=>dG(t,{action:"settings",...d}),onSuccess:a}),c=Nt({mutationFn:()=>dG(t,{action:"refresh_calendars"}),onSuccess:a});return{status:r,connect:i,disconnect:l,updateSettings:o,refreshCalendars:c}}function CMt({scope:s="coach"}){const{status:t,connect:n,disconnect:r,updateSettings:a,refreshCalendars:i}=t3s(!0,s),l=s==="agent";k.useEffect(()=>{const d=new URLSearchParams(window.location.search),u=d.get("google_calendar");if(!u)return;u==="connected"?(ae.success("Google Calendar connected"),t.refetch()):ae.error(d.get("google_calendar_error")||"Google connection failed."),d.delete("google_calendar"),d.delete("google_calendar_error");const h=d.toString();window.history.replaceState({},"",window.location.pathname+(h?`?${h}`:""))},[]);const o=t.data,c=t.error;return e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs(Yt,{className:"flex items-center gap-2",children:[e.jsx(fb,{className:"h-5 w-5"})," Google Calendar"]}),e.jsx(vr,{children:l?"Hide times you're already booked on Google, and push every new booking straight onto your calendar.":"Hide times you're already booked on Google, and push new coaching sessions straight onto your calendar."})]}),(o==null?void 0:o.connected)&&e.jsxs(qe,{className:"bg-emerald-600 hover:bg-emerald-600 shrink-0",children:[e.jsx(Gr,{className:"h-3.5 w-3.5 mr-1"})," Connected"]})]})}),e.jsxs(De,{className:"space-y-4",children:[t.isLoading&&e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(Jt,{className:"h-4 w-4 animate-spin"})," Checking your connection…"]}),c&&e.jsxs("div",{className:"flex items-start gap-2 rounded-lg border border-destructive/40 bg-destructive/5 p-3 text-sm",children:[e.jsx(Ho,{className:"h-4 w-4 mt-0.5 text-destructive shrink-0"}),e.jsx("span",{children:c.message})]}),o&&!o.configured&&e.jsxs("div",{className:"flex items-start gap-2 rounded-lg border border-amber-400/50 bg-amber-50 dark:bg-amber-950/20 p-3 text-sm",children:[e.jsx(Ho,{className:"h-4 w-4 mt-0.5 text-amber-600 shrink-0"}),e.jsx("span",{children:"Google Calendar isn't switched on for LevelUp yet. Once an admin finishes the one-time Google setup, you'll be able to connect right here."})]}),(o==null?void 0:o.configured)&&!o.connected&&e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Not connected. Your availability comes only from the hours you set in LevelUp."}),e.jsxs($,{onClick:()=>n.mutate(void 0,{onSuccess:()=>ae.success("Google Calendar connected"),onError:d=>ae.error(d.message)}),disabled:n.isPending,className:"bg-[#406E71] hover:bg-[#2a4c64]",children:[n.isPending?e.jsx(Jt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(fb,{className:"h-4 w-4 mr-2"}),n.isPending?"Connecting…":"Connect Google Calendar"]}),n.isError&&e.jsx("p",{className:"text-sm text-destructive",children:n.error.message})]}),(o==null?void 0:o.connected)&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"rounded-lg border bg-muted/30 p-3 text-sm",children:[e.jsx("div",{className:"font-medium",children:o.account_email||"Google account"}),o.connected_at&&e.jsxs("div",{className:"text-muted-foreground text-xs",children:["Connected ",new Date(o.connected_at).toLocaleDateString()]})]}),e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx(re,{className:"text-sm",children:"Two-way sync"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:l?"Block busy times and add new bookings to Google.":"Block busy times and add booked sessions to Google."})]}),e.jsx(On,{checked:o.sync_enabled,onCheckedChange:d=>a.mutate({sync_enabled:d},{onError:u=>ae.error(u.message)})})]}),l&&e.jsxs("div",{className:"flex items-center justify-between gap-3 rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx(re,{className:"text-sm",children:"Invite the guest"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Send a Google invite when they leave an email address."})]}),e.jsx(On,{checked:o.invite_guest!==!1,onCheckedChange:d=>a.mutate({invite_guest:d},{onError:u=>ae.error(u.message)})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{className:"text-xs",children:"Calendar to use"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(bs,{value:o.selected_calendar_id||"primary",onValueChange:d=>a.mutate({calendar_id:d},{onError:u=>ae.error(u.message)}),children:[e.jsx(ys,{className:"h-9",children:e.jsx(_s,{placeholder:"Primary calendar"})}),e.jsxs(vs,{children:[e.jsx(We,{value:"primary",children:"Primary calendar"}),o.calendars.filter(d=>!d.primary).map(d=>e.jsx(We,{value:d.id,children:d.summary||d.id},d.id))]})]}),e.jsx($,{variant:"outline",size:"icon",className:"h-9 w-9 shrink-0",onClick:()=>i.mutate(void 0,{onSuccess:()=>ae.success("Calendars refreshed"),onError:d=>ae.error(d.message)}),disabled:i.isPending,children:e.jsx(yo,{className:`h-4 w-4 ${i.isPending?"animate-spin":""}`})})]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2 pt-1",children:[e.jsxs($,{variant:"outline",size:"sm",onClick:()=>n.mutate(void 0,{onSuccess:()=>ae.success("Google Calendar reconnected"),onError:d=>ae.error(d.message)}),disabled:n.isPending,children:[n.isPending?e.jsx(Jt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(yo,{className:"h-4 w-4 mr-2"}),"Reconnect"]}),e.jsxs($,{variant:"ghost",size:"sm",className:"text-destructive",disabled:r.isPending,onClick:async()=>{await io({title:"Disconnect Google Calendar?",description:"Busy times will stop hiding and new sessions won't be added to Google.",confirmText:"Disconnect",destructive:!0})&&r.mutate(void 0,{onSuccess:()=>ae.success("Google Calendar disconnected"),onError:u=>ae.error(u.message)})},children:[e.jsx(aY,{className:"h-4 w-4 mr-2"})," Disconnect"]})]})]})]})]})}function s3s(){const s=Jn(),{data:t,isLoading:n}=See(),r=ls(),[a,i]=k.useState(""),[l,o]=k.useState(""),[c,d]=k.useState(""),[u,h]=k.useState(""),[m,p]=k.useState(""),[g,x]=k.useState(!1),[y,v]=k.useState([]),[_,j]=k.useState(""),[C,A]=k.useState(2),[M,I]=k.useState(!1);k.useEffect(()=>{if(!t)return;const U=t;i(U.slug||""),o(U.headline||""),d(U.bio||""),h(U.photo_url||""),p(U.intro_video_url||""),x(!!U.accepting_clients),v(U.specialties||[]),A(U.default_sessions_per_month??2)},[t]);const P=async()=>{if(!t)return;I(!0);const{error:U}=await V.from("coaches").update({slug:a.trim()||null,headline:l||null,bio:c||null,photo_url:u||null,intro_video_url:m||null,accepting_clients:g,specialties:y,default_sessions_per_month:C}).eq("id",t.id);if(I(!1),U)return ae.error(U.message);ae.success("Profile saved"),r.invalidateQueries({queryKey:["my-coach-profile"]})},R=()=>{const U=_.trim();if(U){if(y.includes(U))return j("");v([...y,U]),j("")}};if(n)return e.jsx(Xs,{title:"Coach Settings",children:e.jsx("div",{className:"p-8",children:"Loading…"})});if(!t)return e.jsx(Xs,{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 O=t,B=O.slug?`${window.location.origin}/coaches/${O.slug}`:null;return e.jsx(Xs,{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($,{variant:"ghost",size:"icon",onClick:()=>s("/coaching"),children:e.jsx(Ia,{className:"h-5 w-5"})}),e.jsx("h1",{className:"text-2xl font-bold",children:"Coach Profile"})]}),e.jsxs("div",{className:"flex gap-2",children:[B&&e.jsxs($,{variant:"outline",size:"sm",onClick:()=>window.open(B,"_blank"),children:[e.jsx(Ir,{className:"h-4 w-4 mr-1"})," View public"]}),e.jsxs($,{onClick:P,disabled:M,className:"bg-[#406E71] hover:bg-[#2a4c64]",children:[e.jsx(Ml,{className:"h-4 w-4 mr-1"})," ",M?"Saving…":"Save"]})]})]}),O.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(we,{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(On,{checked:g,onCheckedChange:x})]}),e.jsxs("div",{children:[e.jsx(re,{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(be,{value:a,onChange:U=>i(U.target.value.toLowerCase().replace(/[^a-z0-9-]/g,"")),placeholder:"your-name"})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Headline"}),e.jsx(be,{value:l,onChange:U=>o(U.target.value),placeholder:"e.g. Helping new agents close their first 10 deals",maxLength:140})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Bio"}),e.jsx(Ls,{rows:6,value:c,onChange:U=>d(U.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(re,{children:"Profile photo"}),e.jsx(zct,{kind:"photo",value:u,onChange:h})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Intro video"}),e.jsx(zct,{kind:"video",value:m,onChange:p})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Specialties"}),e.jsx("div",{className:"flex flex-wrap gap-2 mb-2",children:y.map(U=>e.jsxs(qe,{variant:"secondary",className:"gap-1",children:[U,e.jsx("button",{onClick:()=>v(y.filter(G=>G!==U)),children:e.jsx(mr,{className:"h-3 w-3"})})]},U))}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(be,{value:_,onChange:U=>j(U.target.value),placeholder:"Add a specialty…",onKeyDown:U=>{U.key==="Enter"&&(U.preventDefault(),R())}}),e.jsx($,{type:"button",variant:"outline",onClick:R,children:e.jsx(nn,{className:"h-4 w-4"})})]})]})]})}),e.jsx(we,{children:e.jsxs(De,{className:"p-6 space-y-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Coaching calendar"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Open availability right here — assigned members book you from their ",e.jsx("strong",{children:"My Coach → Book"})," tab. These session types never show on your public booking page."]})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-end gap-4",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx(re,{children:"Sessions each agent can book per month"}),e.jsx(be,{type:"number",min:1,max:31,value:C,onChange:U=>A(Math.max(1,parseInt(U.target.value)||1)),className:"max-w-[140px]"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"You can override this for individual agents on their workspace page."})]}),e.jsx($,{variant:"outline",onClick:()=>s("/mission-control/scheduler"),children:"Open full Scheduler"})]})]})}),e.jsx(CMt,{}),e.jsx(e3s,{}),e.jsx(we,{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($,{variant:"outline",onClick:()=>s("/coaching/billing"),children:"Go to Billing"})]})})}),e.jsx(n3s,{coachId:O.id})]})})}function n3s({coachId:s}){const[t,n]=k.useState("");ls();const{data:r=[],refetch:a}=pt({queryKey:["coach-invites",s],queryFn:async()=>{const{data:c}=await V.from("coaching_invites").select("*").eq("coach_id",s).order("created_at",{ascending:!1});return c||[]}}),i=async()=>{const c=t.trim().toLowerCase();if(!c)return ae.error("Email required");const{error:d}=await V.from("coaching_invites").insert({coach_id:s,email:c});if(d)return ae.error(d.message);n(""),ae.success("Invite created"),a()},l=c=>{const d=`${window.location.origin}/auth?coach_invite=${c}`;navigator.clipboard.writeText(d),ae.success("Link copied")},o=async c=>{await io("Revoke this invite?")&&(await V.from("coaching_invites").delete().eq("id",c),a())};return e.jsx(we,{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(od,{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(be,{placeholder:"agent@email.com",value:t,onChange:c=>n(c.target.value),onKeyDown:c=>c.key==="Enter"&&i()}),e.jsxs($,{onClick:i,children:[e.jsx(nn,{className:"h-4 w-4 mr-1"})," Create"]})]}),e.jsxs("div",{className:"space-y-2",children:[r.map(c=>e.jsxs("div",{className:"flex items-center gap-2 p-3 border rounded-lg",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"font-medium truncate",children:c.email}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[c.status," · expires ",new Date(c.expires_at).toLocaleDateString()]})]}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>l(c.token),children:e.jsx(Da,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>o(c.id),children:e.jsx(Un,{className:"h-4 w-4"})})]},c.id)),r.length===0&&e.jsx("div",{className:"text-sm text-muted-foreground text-center py-4",children:"No invites yet."})]})]})})}const r3s="google_calendar";function a3s(){const[s,t]=k.useState("Finishing your Google Calendar connection…"),n=k.useRef(!1);return k.useEffect(()=>{if(n.current)return;n.current=!0;const r=new URLSearchParams(window.location.search),a=(()=>{try{return!!window.opener&&!window.opener.closed}catch{return!1}})(),i=(()=>{try{return sessionStorage.getItem("googleCalendarReturnTo")||"/coaching/settings"}catch{return"/coaching/settings"}})(),l=(u,h)=>{try{sessionStorage.removeItem("googleCalendarReturnTo")}catch{}const m=new URL(i,window.location.origin);m.searchParams.set("google_calendar",u),h&&m.searchParams.set("google_calendar_error",h),window.location.replace(m.toString())},o=(u,h)=>{var m;if(a){(m=window.opener)==null||m.postMessage({type:u,connectorId:r3s,reason:h},window.location.origin),u==="appUserConnectorOAuthComplete"&&window.close();return}l(u==="appUserConnectorOAuthComplete"?"connected":"failed",h)};if(r.get("success")!=="true"){const u=r.get("error")||"Google did not complete the connection.";t(u),o("appUserConnectorOAuthFailed",u);return}const c=r.get("code");if(!c){const u=r.get("offline_access_allowed")==="false"?"This connection cannot be used yet: a workspace admin must enable offline access on the Google Calendar App User Connector client.":"Google finished, but no exchange code was returned.";t(u),o("appUserConnectorOAuthFailed",u);return}const d=(()=>{try{return sessionStorage.getItem("googleCalendarScope")==="agent"?"agent":"coach"}catch{return"coach"}})();V.functions.invoke(d==="agent"?"agent-google-calendar":"coach-google-calendar",{body:{action:"complete",code:c}}).then(({data:u,error:h})=>{if(h)throw h;if(u!=null&&u.error)throw new Error(u.error);t("Connected! You can close this window."),o("appUserConnectorOAuthComplete")}).catch(u=>{const h=(u==null?void 0:u.message)||"Could not finish the connection.";t(h),o("appUserConnectorOAuthFailed",h)})},[]),e.jsx("div",{className:"min-h-screen flex items-center justify-center p-8 text-center",children:e.jsxs("div",{className:"space-y-3 max-w-sm",children:[e.jsx(Jt,{className:"h-6 w-6 animate-spin mx-auto text-[#406E71]"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:s})]})})}const ure=[{value:"pending",label:"Pending",tone:"bg-amber-100 text-amber-800"},{value:"invited",label:"Invited",tone:"bg-blue-100 text-blue-800"},{value:"converted",label:"Converted",tone:"bg-emerald-100 text-emerald-800"},{value:"declined",label:"Declined",tone:"bg-rose-100 text-rose-800"},{value:"archived",label:"Archived",tone:"bg-slate-100 text-slate-700"}];function i3s(){const s=Jn(),t=ls(),{data:n,isLoading:r}=See(),[a,i]=k.useState("pending"),[l,o]=k.useState(""),[c,d]=k.useState(null),[u,h]=k.useState(!1),[m,p]=k.useState(""),[g,x]=k.useState(!1),[y,v]=k.useState(""),{data:_=[],isLoading:j}=pt({queryKey:["coaching-waitlist",n==null?void 0:n.id],enabled:!!(n!=null&&n.id),queryFn:async()=>{const{data:O,error:B}=await V.from("coaching_waitlist").select("*").eq("coach_id",n.id).order("created_at",{ascending:!1});if(B)throw B;return O||[]}}),C=k.useMemo(()=>_.filter(O=>{if(a!=="all"&&O.status!==a)return!1;if(l){const B=l.toLowerCase();return(O.name||"").toLowerCase().includes(B)||(O.email||"").toLowerCase().includes(B)||(O.brokerage||"").toLowerCase().includes(B)}return!0}),[_,a,l]),A=k.useMemo(()=>{const O={all:_.length};for(const B of ure)O[B.value]=0;for(const B of _)O[B.status]=(O[B.status]||0)+1;return O},[_]),M=async(O,B)=>{const{error:U}=await V.from("coaching_waitlist").update(B).eq("id",O);if(U)return ae.error(U.message);t.invalidateQueries({queryKey:["coaching-waitlist",n==null?void 0:n.id]}),(c==null?void 0:c.id)===O&&d(G=>({...G,...B}))},I=async O=>{if(!await io("Remove this person from the waitlist?"))return;const{error:B}=await V.from("coaching_waitlist").delete().eq("id",O);if(B)return ae.error(B.message);ae.success("Removed"),t.invalidateQueries({queryKey:["coaching-waitlist",n==null?void 0:n.id]}),d(null)},P=async()=>{if(!c)return;const{data:O,error:B}=await V.functions.invoke("coaching-waitlist-invite",{body:{waitlistId:c.id,message:m}});if(B||O!=null&&O.error)return ae.error((O==null?void 0:O.error)||(B==null?void 0:B.message)||"Could not send invite");ae.success(`Invite sent to ${c.name}`),h(!1),p(""),t.invalidateQueries({queryKey:["coaching-waitlist",n==null?void 0:n.id]})},R=async()=>{if(!n)return;const{data:O,error:B}=await V.functions.invoke("coaching-waitlist-invite",{body:{coachId:n.id,notifyAll:!0,message:y}});if(B||O!=null&&O.error)return ae.error((O==null?void 0:O.error)||(B==null?void 0:B.message)||"Could not notify");ae.success(`Notified ${(O==null?void 0:O.count)||0} agents`),x(!1),v(""),t.invalidateQueries({queryKey:["coaching-waitlist",n==null?void 0:n.id]})};return r?e.jsx(Xs,{title:"Waitlist",children:e.jsx("div",{className:"p-8",children:"Loading…"})}):n?e.jsxs(Xs,{title:"Coaching Waitlist",children:[e.jsxs("div",{className:"p-4 md:p-8 max-w-7xl mx-auto space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 flex-wrap",children:[e.jsxs("div",{children:[e.jsxs($,{variant:"ghost",size:"sm",className:"mb-2 -ml-2",onClick:()=>s("/coaching"),children:[e.jsx(Ia,{className:"h-4 w-4 mr-1"})," Back to Coaching"]}),e.jsxs("h1",{className:"text-2xl font-bold flex items-center gap-2",children:[e.jsx(lv,{className:"h-6 w-6 text-[#406E71]"}),"Waitlist"]}),e.jsx("p",{className:"text-muted-foreground text-sm mt-1",children:"Agents waiting for a spot to open up with you."})]}),e.jsxs($,{variant:"outline",onClick:()=>x(!0),disabled:!A.pending,title:A.pending?"":"No pending applicants",children:[e.jsx(Zz,{className:"h-4 w-4 mr-2"}),"Notify all pending (",A.pending||0,")"]})]}),e.jsxs("div",{className:"flex gap-2 flex-wrap",children:[e.jsxs("button",{onClick:()=>i("all"),className:`px-3 py-1.5 rounded-full text-sm border ${a==="all"?"bg-[#406E71] text-white border-[#406E71]":"bg-white hover:bg-muted"}`,children:["All (",A.all,")"]}),ure.map(O=>e.jsxs("button",{onClick:()=>i(O.value),className:`px-3 py-1.5 rounded-full text-sm border ${a===O.value?"bg-[#406E71] text-white border-[#406E71]":"bg-white hover:bg-muted"}`,children:[O.label," (",A[O.value]||0,")"]},O.value))]}),e.jsx(be,{placeholder:"Search by name, email, brokerage…",value:l,onChange:O=>o(O.target.value),className:"max-w-md"}),j?e.jsx("div",{className:"text-muted-foreground",children:"Loading…"}):C.length===0?e.jsx(we,{children:e.jsx(De,{className:"p-10 text-center text-muted-foreground",children:"No entries here yet."})}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:C.map(O=>{const B=ure.find(U=>U.value===O.status);return e.jsx(we,{className:"cursor-pointer hover:shadow-md transition-shadow",onClick:()=>d(O),children:e.jsxs(De,{className:"p-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-semibold truncate",children:O.name}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:O.email}),O.brokerage&&e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:O.brokerage})]}),e.jsx(qe,{className:(B==null?void 0:B.tone)||"",children:(B==null?void 0:B.label)||O.status})]}),e.jsxs("div",{className:"flex items-center justify-between mt-3 text-xs text-muted-foreground",children:[e.jsxs("span",{children:["Joined ",Zc(new Date(O.created_at),{addSuffix:!0})]}),O.preferred_package&&e.jsxs("span",{className:"truncate ml-2",children:["→ ",O.preferred_package]})]})]})},O.id)})})]}),e.jsx(zs,{open:!!c,onOpenChange:O=>!O&&d(null),children:e.jsx(Rs,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:c&&e.jsxs(e.Fragment,{children:[e.jsxs(Vs,{children:[e.jsx($s,{children:c.name}),e.jsxs(Cr,{children:["Joined ",Zc(new Date(c.created_at),{addSuffix:!0})]})]}),e.jsxs("div",{className:"space-y-3 text-sm",children:[e.jsx(uG,{label:"Email",value:c.email}),e.jsx(uG,{label:"Phone",value:c.phone}),e.jsx(uG,{label:"Brokerage",value:c.brokerage}),e.jsx(uG,{label:"Years",value:c.years_in_business}),e.jsx(uG,{label:"Preferred package",value:c.preferred_package}),c.biggest_challenge&&e.jsxs("div",{children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground",children:"Biggest challenge"}),e.jsx("p",{className:"whitespace-pre-wrap",children:c.biggest_challenge})]}),c.message&&e.jsxs("div",{children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground",children:"Message"}),e.jsx("p",{className:"whitespace-pre-wrap",children:c.message})]}),c.invited_at&&e.jsxs("div",{className:"text-xs text-blue-700",children:["Invite sent ",Zc(new Date(c.invited_at),{addSuffix:!0})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground mb-1",children:"Status"}),e.jsxs(bs,{value:c.status,onValueChange:O=>M(c.id,{status:O}),children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsx(vs,{children:ure.map(O=>e.jsx(We,{value:O.value,children:O.label},O.value))})]})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground mb-1",children:"Private notes"}),e.jsx(Ls,{rows:3,defaultValue:c.coach_notes||"",onBlur:O=>{O.target.value!==(c.coach_notes||"")&&M(c.id,{coach_notes:O.target.value})}})]})]}),e.jsxs(kr,{className:"flex-wrap gap-2",children:[e.jsxs($,{variant:"outline",className:"text-destructive",onClick:()=>I(c.id),children:[e.jsx(Un,{className:"h-4 w-4 mr-1"})," Remove"]}),e.jsx($,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:`mailto:${c.email}`,children:[e.jsx(pn,{className:"h-4 w-4 mr-1"})," Email directly"]})}),e.jsxs($,{className:"bg-[#406E71] hover:bg-[#2a4c64]",onClick:()=>{p(""),h(!0)},children:[e.jsx(Wr,{className:"h-4 w-4 mr-1"})," Invite to subscribe"]})]})]})})}),e.jsx(zs,{open:u,onOpenChange:h,children:e.jsxs(Rs,{children:[e.jsxs(Vs,{children:[e.jsx($s,{children:"Invite to subscribe"}),e.jsxs(Cr,{children:["We'll email ",c==null?void 0:c.name," a link to your coaching page so they can pick a package."]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Personal note (optional)"}),e.jsx(Ls,{rows:4,placeholder:"Hey! A spot just opened up and I'd love to work with you…",value:m,onChange:O=>p(O.target.value)})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>h(!1),children:"Cancel"}),e.jsxs($,{className:"bg-[#406E71] hover:bg-[#2a4c64]",onClick:P,children:[e.jsx(Wr,{className:"h-4 w-4 mr-1"})," Send invite"]})]})]})}),e.jsx(zs,{open:g,onOpenChange:x,children:e.jsxs(Rs,{children:[e.jsxs(Vs,{children:[e.jsx($s,{children:"Notify all pending applicants"}),e.jsx(Cr,{children:"Send everyone with status “Pending” an email letting them know spots are opening up. They'll each be marked “Invited”."})]}),e.jsx(Ls,{rows:4,placeholder:"Good news — I just opened up new coaching spots…",value:y,onChange:O=>v(O.target.value)}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>x(!1),children:"Cancel"}),e.jsxs($,{className:"bg-[#406E71] hover:bg-[#2a4c64]",onClick:R,children:[e.jsx(Zz,{className:"h-4 w-4 mr-1"})," Send to ",A.pending||0," agents"]})]})]})})]}):e.jsx(Xs,{title:"Waitlist",children:e.jsx("div",{className:"p-8 text-center text-muted-foreground",children:"You need a coach profile to view this page."})})}function uG({label:s,value:t}){return t?e.jsxs("div",{className:"flex justify-between gap-3 border-b pb-1",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:s}),e.jsx("span",{className:"text-right",children:t})]}):null}function o3s(){const{data:s=[],isLoading:t}=pt({queryKey:["coaches-directory"],queryFn:async()=>{const{data:n,error:r}=await V.from("coaches").select("id, slug, headline, bio, specialties, photo_url, is_certified, accepting_clients, user_id").not("slug","is",null);if(r)throw r;const a=(n||[]).map(o=>o.user_id);if(a.length===0)return[];const{data:i}=await V.from("profiles").select("id, name, avatar_url").in("id",a),l=new Map((i||[]).map(o=>[o.id,o]));return(n||[]).map(o=>({...o,profile:l.get(o.user_id)}))}});return e.jsxs("div",{className:"min-h-screen bg-white",children:[e.jsxs("section",{className:"relative overflow-hidden bg-gradient-to-br from-[#1c3447] via-[#2a4c64] to-[#406E71] text-white",children:[e.jsx("div",{className:"absolute -top-32 -left-24 h-96 w-96 rounded-full bg-[#5a9ea2]/20 blur-3xl"}),e.jsx("div",{className:"absolute -bottom-32 -right-24 h-96 w-96 rounded-full bg-yellow-400/10 blur-3xl"}),e.jsx("div",{className:"absolute inset-0 opacity-[0.04]",style:{backgroundImage:"radial-gradient(white 1px, transparent 1px)",backgroundSize:"22px 22px"}}),e.jsxs("div",{className:"relative max-w-6xl mx-auto px-4 py-20 md:py-28 text-center",children:[e.jsxs("div",{className:"inline-flex items-center gap-2 px-3 py-1.5 rounded-full bg-white/10 backdrop-blur-sm border border-white/15 text-xs uppercase tracking-[0.18em] font-semibold mb-6",children:[e.jsx(kn,{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(Gr,{className:"h-4 w-4 text-yellow-300"})," Vetted by LevelUp"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ql,{className:"h-4 w-4 text-yellow-300"})," Top-producer experience"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ri,{className:"h-4 w-4 text-yellow-300"})," Real, measurable results"]})]})]}),e.jsx("svg",{className:"block w-full text-white",viewBox:"0 0 1440 60",preserveAspectRatio:"none","aria-hidden":!0,children:e.jsx("path",{fill:"currentColor",d:"M0,40 C360,80 1080,0 1440,40 L1440,60 L0,60 Z"})})]}),e.jsxs("section",{className:"max-w-6xl mx-auto px-4 py-16 md:py-20",children:[t?e.jsx("div",{className:"text-center text-muted-foreground",children:"Loading coaches…"}):s.length===0?e.jsx("div",{className:"text-center text-muted-foreground",children:"No coaches available yet. Check back soon."}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6",children:s.map(n=>{var i,l;const r=((i=n.profile)==null?void 0:i.name)||"Coach",a=n.photo_url||((l=n.profile)==null?void 0:l.avatar_url);return e.jsx(nr,{to:`/coaches/${n.slug||n.id}`,className:"group",children:e.jsx("article",{className:"relative h-full rounded-2xl bg-[#1c3447] overflow-hidden transition-all duration-300 hover:-translate-y-1 hover:shadow-[0_24px_60px_-20px_rgba(42,76,100,0.5)]",children:e.jsxs("div",{className:"relative aspect-[3/4] w-full overflow-hidden",children:[a?e.jsx("img",{src:a,alt:r,className:"absolute inset-0 h-full w-full object-cover object-top group-hover:scale-105 transition-transform duration-700"}):e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-gradient-to-br from-[#2a4c64] to-[#406E71] text-white text-6xl font-bold",children:r.charAt(0)}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-[#0d1f2d] via-[#0d1f2d]/70 to-transparent"}),e.jsxs("div",{className:"absolute top-3 left-3 right-3 flex items-start justify-between gap-2",children:[n.is_certified?e.jsxs("div",{className:"inline-flex items-center gap-1 px-2.5 py-1 rounded-full bg-gradient-to-r from-yellow-400 to-yellow-300 text-[#2a4c64] text-[11px] font-semibold shadow-md",children:[e.jsx(kn,{className:"h-3 w-3"})," Certified"]}):e.jsx("span",{}),e.jsxs("div",{className:`inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-[11px] font-medium backdrop-blur-md ${n.accepting_clients?"bg-emerald-500/90 text-white":"bg-white/85 text-[#2a4c64]"}`,children:[e.jsx("span",{className:`h-1.5 w-1.5 rounded-full ${n.accepting_clients?"bg-white":"bg-amber-500"}`}),n.accepting_clients?"Accepting":"Waitlist"]})]}),e.jsxs("div",{className:"absolute inset-x-0 bottom-0 p-5 text-white",children:[e.jsx("h3",{className:"text-xl font-bold leading-tight drop-shadow-sm",children:r}),n.headline&&e.jsx("p",{className:"text-sm text-yellow-200/90 font-medium mt-1 line-clamp-1",children:n.headline}),n.bio&&e.jsx("p",{className:"text-[13px] text-white/80 mt-2 line-clamp-2 leading-relaxed",children:n.bio}),n.specialties&&n.specialties.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1.5 mt-3",children:n.specialties.slice(0,2).map(o=>e.jsx("span",{className:"text-[10px] px-2 py-0.5 rounded-full bg-white/15 backdrop-blur-sm text-white border border-white/20",children:o},o))}),e.jsxs("div",{className:"flex items-center justify-between mt-4 pt-3 border-t border-white/15",children:[e.jsx("span",{className:"text-sm font-semibold text-white",children:"View profile"}),e.jsx("span",{className:"inline-flex items-center justify-center h-8 w-8 rounded-full bg-white/15 backdrop-blur-sm text-white group-hover:bg-yellow-300 group-hover:text-[#1c3447] transition-colors",children:e.jsx(xi,{className:"h-4 w-4"})})]})]})]})})},n.id)})}),e.jsxs("div",{className:"mt-20 rounded-3xl bg-gradient-to-br from-[#1c3447] via-[#2a4c64] to-[#406E71] text-white p-10 md:p-14 relative overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0 opacity-[0.06]",style:{backgroundImage:"radial-gradient(white 1px, transparent 1px)",backgroundSize:"18px 18px"}}),e.jsx("div",{className:"absolute -top-24 -right-24 h-72 w-72 rounded-full bg-yellow-300/15 blur-3xl"}),e.jsxs("div",{className:"relative md:flex items-center gap-10",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"inline-flex items-center gap-2 px-3 py-1.5 rounded-full bg-white/10 border border-white/15 text-[11px] uppercase tracking-[0.18em] font-semibold mb-5",children:[e.jsx(kn,{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(Gr,{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(Gr,{className:"h-4 w-4 text-yellow-300"})," Recurring revenue"]}),e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx(Gr,{className:"h-4 w-4 text-yellow-300"})," Certified status"]})]})]}),e.jsxs("div",{className:"mt-8 md:mt-0",children:[e.jsxs(nr,{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(xi,{className:"h-5 w-5"})]}),e.jsx("p",{className:"text-xs text-white/60 mt-3 text-center md:text-left",children:"By application only."})]})]})]})]})]})}const l3s=t4({name:uc().trim().min(1,"Name required").max(120),email:uc().trim().email("Invalid email").max(255),phone:uc().trim().max(40).optional().or(c0("")),brokerage:uc().trim().max(160).optional().or(c0("")),years_in_business:uc().max(40).optional().or(c0("")),biggest_challenge:uc().trim().max(1e3).optional().or(c0("")),preferred_package:uc().max(120).optional().or(c0("")),message:uc().trim().max(1500).optional().or(c0(""))});function c3s({open:s,onOpenChange:t,coachId:n,coachName:r,packages:a=[]}){const{user:i}=ks(),[l,o]=k.useState(!1),[c,d]=k.useState({name:"",email:(i==null?void 0:i.email)||"",phone:"",brokerage:"",years_in_business:"",biggest_challenge:"",preferred_package:"",message:""}),u=(m,p)=>d(g=>({...g,[m]:p})),h=async()=>{var g;const m=l3s.safeParse(c);if(!m.success){ae.error(((g=m.error.issues[0])==null?void 0:g.message)||"Please check your entries");return}o(!0);const{error:p}=await V.from("coaching_waitlist").insert({coach_id:n,agent_user_id:(i==null?void 0:i.id)||null,name:c.name.trim(),email:c.email.trim().toLowerCase(),phone:c.phone||null,brokerage:c.brokerage||null,years_in_business:c.years_in_business||null,biggest_challenge:c.biggest_challenge||null,preferred_package:c.preferred_package||null,message:c.message||null,status:"pending"});if(o(!1),p){ae.error(p.message||"Could not join waitlist");return}ae.success(`You're on the waitlist${r?` for ${r}`:""}. We'll be in touch when a spot opens.`),t(!1),d({...c,biggest_challenge:"",message:""})};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsxs(Vs,{children:[e.jsxs($s,{children:["Join the waitlist",r?` — ${r}`:""]}),e.jsx(Cr,{children:"Tell us a bit about you. The coach will reach out as soon as a spot opens."})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Name *"}),e.jsx(be,{value:c.name,onChange:m=>u("name",m.target.value)})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Email *"}),e.jsx(be,{type:"email",value:c.email,onChange:m=>u("email",m.target.value)})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Phone"}),e.jsx(be,{value:c.phone,onChange:m=>u("phone",m.target.value)})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Brokerage"}),e.jsx(be,{value:c.brokerage,onChange:m=>u("brokerage",m.target.value)})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Years in business"}),e.jsxs(bs,{value:c.years_in_business,onValueChange:m=>u("years_in_business",m),children:[e.jsx(ys,{children:e.jsx(_s,{placeholder:"Select…"})}),e.jsxs(vs,{children:[e.jsx(We,{value:"< 1 year",children:"Less than 1 year"}),e.jsx(We,{value:"1-3 years",children:"1-3 years"}),e.jsx(We,{value:"4-7 years",children:"4-7 years"}),e.jsx(We,{value:"8-15 years",children:"8-15 years"}),e.jsx(We,{value:"15+ years",children:"15+ years"})]})]})]}),a.length>0&&e.jsxs("div",{children:[e.jsx(re,{children:"Preferred package"}),e.jsxs(bs,{value:c.preferred_package,onValueChange:m=>u("preferred_package",m),children:[e.jsx(ys,{children:e.jsx(_s,{placeholder:"Any"})}),e.jsx(vs,{children:a.map(m=>e.jsx(We,{value:m.name,children:m.name},m.id))})]})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Biggest challenge right now"}),e.jsx(Ls,{rows:2,value:c.biggest_challenge,onChange:m=>u("biggest_challenge",m.target.value)})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Anything else?"}),e.jsx(Ls,{rows:2,value:c.message,onChange:m=>u("message",m.target.value)})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),disabled:l,children:"Cancel"}),e.jsx($,{className:"bg-[#406E71] hover:bg-[#2a4c64]",onClick:h,disabled:l,children:l?"Submitting…":"Join Waitlist"})]})]})})}function d3s(){var x;const{slug:s}=oo(),t=Jn(),{user:n}=ks(),[r,a]=k.useState(null),[i,l]=k.useState(!1),{data:o,isLoading:c}=pt({queryKey:["coach-public",s],enabled:!!s,queryFn:async()=>{const y=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(s||""),v=V.from("coaches").select("*"),{data:_}=y?await v.eq("id",s).maybeSingle():await v.eq("slug",s).maybeSingle();if(!_)return null;const[{data:j},{data:C}]=await Promise.all([V.from("profiles").select("id, name, avatar_url").eq("id",_.user_id).maybeSingle(),V.from("coaching_packages").select("*").eq("coach_id",_.id).eq("is_active",!0).order("sort_order")]);return{coach:_,profile:j,packages:C||[]}}}),d=async y=>{if(!n){ae.error("Please sign in to subscribe"),t(`/auth?redirect=/coaches/${s}`);return}a(y);const{data:v,error:_}=await V.functions.invoke("create-coaching-checkout",{body:{packageId:y}});if(a(null),_||v!=null&&v.error){ae.error((v==null?void 0:v.error)||(_==null?void 0:_.message)||"Checkout failed");return}v!=null&&v.url&&(window.location.href=v.url)};if(c)return e.jsx("div",{className:"p-12 text-center",children:"Loading…"});if(!(o!=null&&o.coach))return e.jsx("div",{className:"p-12 text-center",children:"Coach not found."});const{coach:u,profile:h,packages:m}=o,p=u,g=(y,v)=>{const _=(y/100).toLocaleString("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0});return v==="one_time"?_:`${_} / ${v}`};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($,{variant:"ghost",size:"sm",className:"text-white/80 hover:text-white hover:bg-white/10 mb-6",onClick:()=>t("/coaches"),children:[e.jsx(Ia,{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(Wa,{className:"h-28 w-28 ring-4 ring-white/20",children:[e.jsx(eo,{src:p.photo_url||(h==null?void 0:h.avatar_url)}),e.jsx(Ka,{className:"text-3xl bg-white/20",children:((h==null?void 0:h.name)||"C").charAt(0)})]}),e.jsxs("div",{className:"flex-1",children:[p.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(kn,{className:"h-3 w-3"})," LevelUp Certified"]}),e.jsx("h1",{className:"text-3xl md:text-4xl font-bold",children:(h==null?void 0:h.name)||"Coach"}),p.headline&&e.jsx("p",{className:"text-white/80 text-lg mt-2",children:p.headline}),((x=p.specialties)==null?void 0:x.length)>0&&e.jsx("div",{className:"flex flex-wrap gap-2 mt-4",children:p.specialties.map(y=>e.jsx(qe,{className:"bg-white/15 text-white border-white/20",children:y},y))})]})]})]})}),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:[p.intro_video_url&&e.jsx("div",{className:"aspect-video rounded-xl overflow-hidden bg-black",children:e.jsx("video",{src:p.intro_video_url,controls:!0,className:"w-full h-full"})}),p.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:p.bio})]}),e.jsx(BCs,{coachId:p.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"}),m.length===0?e.jsx(we,{children:e.jsx(De,{className:"p-6 text-sm text-muted-foreground text-center",children:"No packages available yet."})}):m.map(y=>{const v=y.accepting_clients===!1;return e.jsx(we,{className:`border-2 transition-colors ${v?"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:y.name}),v&&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"})]}),y.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:y.description}),e.jsx("div",{className:"text-2xl font-bold mt-3",children:g(y.price_cents,y.billing_interval)}),v?e.jsxs("div",{className:"mt-4 space-y-2",children:[e.jsx("div",{className:"rounded-md bg-amber-100 border border-amber-200 text-amber-900 px-3 py-2.5 text-sm text-center",children:"Currently not accepting new clients."}),e.jsxs($,{variant:"outline",className:"w-full",onClick:()=>l(!0),children:[e.jsx(lv,{className:"h-4 w-4 mr-1"})," Join Waitlist"]})]}):e.jsxs($,{className:"w-full mt-4 bg-[#406E71] hover:bg-[#2a4c64]",onClick:()=>d(y.id),disabled:r===y.id,children:[r===y.id?"Loading…":"Get Started",e.jsx(ma,{className:"h-4 w-4 ml-1"})]})]})},y.id)}),e.jsx("p",{className:"text-xs text-muted-foreground text-center",children:"Secure checkout powered by Stripe."}),e.jsxs($,{variant:"ghost",size:"sm",className:"w-full text-muted-foreground",onClick:()=>l(!0),children:[e.jsx(lv,{className:"h-4 w-4 mr-1"})," Join the waitlist instead"]})]})]}),e.jsx(c3s,{open:i,onOpenChange:l,coachId:p.id,coachName:h==null?void 0:h.name,packages:m.map(y=>({id:y.id,name:y.name}))})]})}const u3s=t4({full_name:uc().trim().min(2,"Please enter your full name").max(100),email:uc().trim().email("Enter a valid email").max(255),phone:uc().trim().max(40).optional().or(c0("")),brokerage:uc().trim().max(150).optional().or(c0("")),years_experience:uc().trim().max(40).optional().or(c0("")),specialties:uc().trim().max(500).optional().or(c0("")),why_coach:uc().trim().min(20,"Tell us a bit more — at least 20 characters").max(2e3),results_story:uc().trim().max(2e3).optional().or(c0("")),website_url:uc().trim().max(300).optional().or(c0("")),linkedin_url:uc().trim().max(300).optional().or(c0(""))});function h3s(){const s=Jn(),[t,n]=k.useState(!1),[r,a]=k.useState(!1),[i,l]=k.useState({full_name:"",email:"",phone:"",brokerage:"",years_experience:"",specialties:"",why_coach:"",results_story:"",website_url:"",linkedin_url:""}),o=(d,u)=>l(h=>({...h,[d]:u})),c=async d=>{var m;d.preventDefault();const u=u3s.safeParse(i);if(!u.success){const p=(m=Object.values(u.error.flatten().fieldErrors)[0])==null?void 0:m[0];return ae.error(p||"Please check the form and try again")}n(!0);const{error:h}=await V.from("coach_applications").insert(u.data);if(n(!1),h)return ae.error(h.message||"Could not submit application");a(!0),window.scrollTo({top:0,behavior:"smooth"})};return r?e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-[#1c3447] via-[#2a4c64] to-[#406E71] text-white flex items-center justify-center p-6",children:e.jsxs("div",{className:"max-w-xl text-center",children:[e.jsx("div",{className:"inline-flex items-center justify-center h-20 w-20 rounded-full bg-gradient-to-br from-yellow-400 to-yellow-300 text-[#1c3447] mb-6 shadow-2xl",children:e.jsx(Gr,{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($,{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(nr,{to:"/coaches",className:"inline-flex items-center gap-2 text-white/70 hover:text-white text-sm mb-8",children:[e.jsx(Ia,{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(kn,{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(Xn,{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(mc,{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(oh,{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(Gr,{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(ql,{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(ri,{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(cS,{label:"Full name *",children:e.jsx(be,{value:i.full_name,onChange:d=>o("full_name",d.target.value),required:!0,maxLength:100})}),e.jsx(cS,{label:"Email *",children:e.jsx(be,{type:"email",value:i.email,onChange:d=>o("email",d.target.value),required:!0,maxLength:255})}),e.jsx(cS,{label:"Phone",children:e.jsx(be,{value:i.phone,onChange:d=>o("phone",d.target.value),maxLength:40})}),e.jsx(cS,{label:"Current brokerage",children:e.jsx(be,{value:i.brokerage,onChange:d=>o("brokerage",d.target.value),maxLength:150})}),e.jsx(cS,{label:"Years in real estate",children:e.jsx(be,{value:i.years_experience,onChange:d=>o("years_experience",d.target.value),placeholder:"e.g. 8",maxLength:40})}),e.jsx(cS,{label:"Coaching specialties",children:e.jsx(be,{value:i.specialties,onChange:d=>o("specialties",d.target.value),placeholder:"Lead gen, listings, luxury, teams…",maxLength:500})}),e.jsx(cS,{label:"Website",children:e.jsx(be,{value:i.website_url,onChange:d=>o("website_url",d.target.value),placeholder:"https://",maxLength:300})}),e.jsx(cS,{label:"LinkedIn",children:e.jsx(be,{value:i.linkedin_url,onChange:d=>o("linkedin_url",d.target.value),placeholder:"https://linkedin.com/in/",maxLength:300})})]}),e.jsx(cS,{label:"Why do you want to coach with LevelUp? *",children:e.jsx(Ls,{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(cS,{label:"Tell us about results you've created — for yourself or other agents.",children:e.jsx(Ls,{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($,{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 cS({label:s,children:t}){return e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{className:"text-sm font-semibold text-[#1c3447]",children:s}),t]})}const m3s="/assets/testimonial-avatar-1-BsCQFauB.jpg",f3s="/assets/testimonial-avatar-2-B6VPVc2t.jpg",p3s="/assets/testimonial-avatar-3-GuEFwYUE.jpg",g3s="/assets/testimonial-avatar-4-98iKMtkB.jpg",x3s="/assets/testimonial-avatar-5-ZsZfyxMX.jpg",y3s=[m3s,f3s,p3s,g3s,x3s],v3s=t4({name:uc().trim().min(2,"Name must be at least 2 characters").max(100),email:uc().trim().email("Please enter a valid email address").max(255),phone:uc().trim().min(10,"Please enter a valid phone number").max(20).optional().or(c0("")),brokerage:uc().trim().max(200).optional().or(c0(""))}),b3s=[{icon:mm,title:"Academy Training",description:"Access a library of on-demand video training covering lead generation, marketing, technology, and more."},{icon:gd,title:"300+ Templates",description:"Professional Canva templates for social media, flyers, postcards, and marketing materials."},{icon:ha,title:"Live Events",description:"Weekly live training sessions, workshops, and Q&A events with industry experts."},{icon:Vu,title:"Agent Community",description:"Connect with fellow agents, share wins, ask questions, and network in our private community."},{icon:ea,title:"Resource Kits",description:"Downloadable toolkits with scripts, checklists, guides, and everything you need to close more deals."},{icon:Zo,title:"Social Swag",description:"Fresh social media content and designs updated regularly to help you stand out online."}],_3s=[{icon:Xn,title:"Contact Management",description:"Organize your sphere into relationship tiers—Top 25, Past Clients, Referral Partners, and more."},{icon:kn,title:"Smart TouchPlans",description:"Automated action plans that tell you exactly who to contact and how, based on relationship type."},{icon:ka,title:"One-Tap Actions",description:"Call, text, or email contacts directly with pre-written scripts tailored to each relationship."},{icon:ip,title:"Birthday Alerts",description:"Never miss an important date—get reminders for birthdays and home anniversaries."},{icon:Si,title:"Pop-by Map",description:"See all your contacts on a map and plan efficient pop-by routes in your area."},{icon:Ul,title:"Momentum Tracking",description:"Track your touch streaks, weekly goals, and relationship health scores."},{icon:Bo,title:"Relationship Health",description:"Visual dashboard showing which contacts need attention based on last touch date."},{icon:ix,title:"Daily Action Cards",description:"Wake up to a prioritized list of exactly who to reach out to today."}],w3s=[{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."}],j3s=()=>{const s=Jn(),[t,n]=k.useState(!1),[r,a]=k.useState({name:"",email:"",phone:"",brokerage:""}),[i,l]=k.useState({}),o=async c=>{var u,h;c.preventDefault(),l({});const d=v3s.safeParse(r);if(!d.success){const m={};d.error.issues.forEach(p=>{p.path[0]&&(m[p.path[0]]=p.message)}),l(m);return}n(!0);try{const m=typeof window<"u"&&localStorage.getItem("levelup_referral_code")||void 0,{data:p,error:g}=await V.functions.invoke("create-trial-signup",{body:{name:r.name.trim(),email:r.email.trim().toLowerCase(),phone:((u=r.phone)==null?void 0:u.trim())||void 0,brokerage:((h=r.brokerage)==null?void 0:h.trim())||void 0,referral_code:m}});if(g){console.error("Trial signup error:",g),ae.error(g.message||"Something went wrong. Please try again.");return}if(p!=null&&p.error){ae.error(p.error);return}ae.success("🎉 Welcome aboard! Check your email to claim your account."),typeof window<"u"&&window.oaiq&&window.oaiq("measure","trial_started",{type:"plan_enrollment"}),typeof window<"u"&&window.fbq&&window.fbq("track","Lead",{content_name:"Trial Signup",value:0,currency:"USD"}),s("/trial/success")}catch(m){console.error("Trial signup error:",m),ae.error("Something went wrong. Please try again.")}finally{n(!1)}};return e.jsxs(e.Fragment,{children:[e.jsxs(Sc,{children:[e.jsx("title",{children:"Start Your Free 7-Day Trial | LevelUp Dashboard"}),e.jsx("meta",{name:"description",content:"Take LevelUp for a free 7-day test drive. No credit card required. The all-in-one platform for real estate agents and brokerages."}),e.jsx("meta",{property:"og:title",content:"Start Your Free 7-Day Trial | LevelUp"}),e.jsx("meta",{property:"og:description",content:"Take LevelUp for a free 7-day test drive. No credit card required."}),e.jsx("meta",{property:"og:type",content:"website"}),e.jsx("script",{children:"!function(f,b,e,v,n,t,s){if(f.fbq)return;n=f.fbq=function(){n.callMethod?n.callMethod.apply(n,arguments):n.queue.push(arguments)};if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';n.queue=[];t=b.createElement(e);t.async=!0;t.src=v;s=b.getElementsByTagName(e)[0];s.parentNode.insertBefore(t,s)}(window,document,'script','https://connect.facebook.net/en_US/fbevents.js'); fbq('init', '1388750291887997'); fbq('track', 'PageView');"})]}),e.jsx("noscript",{dangerouslySetInnerHTML:{__html:''}}),e.jsxs("div",{className:"min-h-screen bg-background overflow-hidden",children:[e.jsx("nav",{className:"fixed top-0 left-0 right-0 z-50 bg-[#4a6b6d] shadow-md",children:e.jsxs("div",{className:"container mx-auto px-4 py-3 flex items-center justify-between",children:[e.jsx("div",{className:"flex items-center",children:e.jsx("img",{src:SSe,alt:"LevelUp",className:"h-8 md:h-10"})}),e.jsxs("div",{className:"flex items-center gap-2 md:gap-4",children:[e.jsx($,{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($,{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(kn,{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(Gr,{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(Gr,{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:y3s.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(ri,{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(we,{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(v0,{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(re,{htmlFor:"name",children:"Full Name *"}),e.jsx(be,{id:"name",type:"text",placeholder:"John Smith",value:r.name,onChange:c=>a({...r,name:c.target.value}),required:!0}),i.name&&e.jsx("p",{className:"text-sm text-destructive",children:i.name})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"email",children:"Email Address *"}),e.jsx(be,{id:"email",type:"email",placeholder:"john@example.com",value:r.email,onChange:c=>a({...r,email:c.target.value}),required:!0}),i.email&&e.jsx("p",{className:"text-sm text-destructive",children:i.email})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"phone",children:"Phone Number"}),e.jsx(be,{id:"phone",type:"tel",placeholder:"(555) 123-4567",value:r.phone,onChange:c=>a({...r,phone:c.target.value})}),i.phone&&e.jsx("p",{className:"text-sm text-destructive",children:i.phone})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"brokerage",children:"Brokerage Name"}),e.jsx(be,{id:"brokerage",type:"text",placeholder:"Your brokerage or team name",value:r.brokerage,onChange:c=>a({...r,brokerage:c.target.value})}),i.brokerage&&e.jsx("p",{className:"text-sm text-destructive",children:i.brokerage})]}),e.jsx($,{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(Jt,{className:"mr-2 h-5 w-5 animate-spin"}),"Creating Your Account..."]}):e.jsxs(e.Fragment,{children:["Start My Free Trial",e.jsx(xi,{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:b3s.map((c,d)=>e.jsxs(we,{className:"group relative overflow-hidden border hover:border-[#4a6b6d]/50 transition-all duration-300 hover:shadow-lg bg-background",children:[e.jsxs(Vt,{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(Yt,{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(kn,{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:_3s.map((c,d)=>e.jsxs(we,{className:"group relative overflow-hidden border-0 bg-white/10 backdrop-blur-sm hover:bg-white/20 transition-all duration-300",children:[e.jsxs(Vt,{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(Yt,{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:w3s.map((c,d)=>e.jsx(we,{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(u=>e.jsx(ri,{className:"h-4 w-4 fill-yellow-400 text-yellow-400"},u))}),e.jsxs("p",{className:"text-muted-foreground mb-4 italic",children:['"',c.quote,'"']}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold",children:c.name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:c.role})]})]})},d))})]})}),e.jsx("section",{className:"py-16 bg-muted/30",children:e.jsx("div",{className:"container mx-auto px-4",children:e.jsxs("div",{className:"flex flex-wrap justify-center gap-8 md:gap-16",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-12 h-12 rounded-full bg-[#4a6b6d]/10 flex items-center justify-center",children:e.jsx(Ng,{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(ix,{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(Xn,{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(we,{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($,{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(xi,{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:mSe,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."})]})})})]})]})},N3s=()=>{const s=Jn();return e.jsxs(e.Fragment,{children:[e.jsx(Sc,{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:SSe,alt:"LevelUp",className:"h-8 md:h-10"})}),e.jsx($,{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(we,{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(Gr,{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(jg,{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(pn,{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($,{onClick:()=>s("/auth"),className:"bg-[#4a6b6d] hover:bg-[#3d5a5c]",children:["Go to Sign In",e.jsx(xi,{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:mSe,alt:"LevelUp",className:"h-8"}),e.jsxs("p",{className:"text-sm text-white/40",children:["© ",new Date().getFullYear()," LevelUp Consulting Group. All rights reserved."]})]})})})]})]})},k3s=t4({viewerName:uc().min(1,"Name is required").max(100,"Name must be less than 100 characters"),viewerEmail:uc().email("Please enter a valid email").max(255,"Email must be less than 255 characters"),viewerPhone:uc().max(20,"Phone must be less than 20 characters").optional(),message:uc().min(1,"Message is required").max(1e3,"Message must be less than 1000 characters")});function S3s({shareToken:s,agentName:t,hasContact:n}){const[r,a]=k.useState(!1),[i,l]=k.useState(!1),[o,c]=k.useState(null),d=D3e({resolver:O3e(k3s),defaultValues:{viewerName:"",viewerEmail:"",viewerPhone:"",message:""}}),u=async h=>{a(!0),c(null);try{const{data:m,error:p}=await V.functions.invoke("video-reply-notify",{body:{shareToken:s,viewerName:h.viewerName,viewerEmail:h.viewerEmail,viewerPhone:h.viewerPhone||void 0,message:h.message}});if(p)throw new Error(p.message);if(!(m!=null&&m.success))throw new Error((m==null?void 0:m.error)||"Failed to send reply");l(!0)}catch(m){console.error("Failed to submit reply:",m),c(m.message||"Something went wrong. Please try again.")}finally{a(!1)}};return i?e.jsx(we,{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(Gr,{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(we,{children:[e.jsxs(Vt,{className:"pb-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(Vu,{className:"h-5 w-5 text-primary"}),e.jsx(Yt,{className:"text-lg",children:"Reply to this video"})]}),e.jsx(vr,{children:n?`Have a question or want to connect? Send ${t||"them"} a message.`:`Interested? Share your info and ${t||"your agent"} will be in touch.`})]}),e.jsx(De,{children:e.jsx($3e,{...d,children:e.jsxs("form",{onSubmit:d.handleSubmit(u),className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsx(Sp,{control:d.control,name:"viewerName",render:({field:h})=>e.jsxs(Zf,{children:[e.jsx(Xf,{children:"Your Name *"}),e.jsx(Qf,{children:e.jsx(be,{placeholder:"John Smith",...h})}),e.jsx(ib,{})]})}),e.jsx(Sp,{control:d.control,name:"viewerEmail",render:({field:h})=>e.jsxs(Zf,{children:[e.jsx(Xf,{children:"Email *"}),e.jsx(Qf,{children:e.jsx(be,{type:"email",placeholder:"john@example.com",...h})}),e.jsx(ib,{})]})})]}),!n&&e.jsx(Sp,{control:d.control,name:"viewerPhone",render:({field:h})=>e.jsxs(Zf,{children:[e.jsx(Xf,{children:"Phone (optional)"}),e.jsx(Qf,{children:e.jsx(be,{type:"tel",placeholder:"(555) 123-4567",...h})}),e.jsx(ib,{})]})}),e.jsx(Sp,{control:d.control,name:"message",render:({field:h})=>e.jsxs(Zf,{children:[e.jsx(Xf,{children:"Message *"}),e.jsx(Qf,{children:e.jsx(Ls,{placeholder:n?"Thanks for the video! I had a question about...":"I'm interested in learning more about...",className:"min-h-[100px] resize-none",...h})}),e.jsx(ib,{})]})}),o&&e.jsx("p",{className:"text-sm text-destructive",children:o}),e.jsx($,{type:"submit",className:"w-full gap-2",disabled:r,children:r?e.jsxs(e.Fragment,{children:[e.jsx(Jt,{className:"h-4 w-4 animate-spin"}),"Sending..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Wr,{className:"h-4 w-4"}),"Send Message"]})})]})})})]})}const C3s=()=>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(ri,{className:"absolute top-[5%] left-[8%] w-6 h-6 text-blue-600/30 fill-blue-600/20"}),e.jsx(ri,{className:"absolute top-[15%] left-[20%] w-4 h-4 text-blue-600/25 fill-blue-600/15"}),e.jsx(ri,{className:"absolute top-[8%] left-[28%] w-5 h-5 text-blue-600/30 fill-blue-600/20"}),e.jsx(ri,{className:"absolute top-[25%] left-[12%] w-4 h-4 text-blue-600/20 fill-blue-600/10"}),e.jsx(ri,{className:"absolute top-[20%] right-[15%] w-5 h-5 text-red-500/25 fill-red-500/15 animate-pulse"}),e.jsx(g3,{className:"absolute bottom-[20%] right-[10%] w-12 h-12 text-blue-600/15 rotate-12"})]}),A3s=()=>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(kn,{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(ri,{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(kn,{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(ri,{className:"absolute bottom-[25%] left-[10%] w-6 h-6 text-blue-500/25 fill-blue-500/15 animate-pulse"}),e.jsx(ri,{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(g3,{className:"absolute top-[8%] left-[5%] w-10 h-10 text-red-500/20 rotate-12"})]}),E3s=()=>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(QN,{className:"w-20 h-20 text-pink-400 rotate-12"})}),e.jsx("div",{className:"absolute top-[2%] right-[8%] opacity-15",children:e.jsx(QN,{className:"w-16 h-16 text-rose-400 -rotate-12"})}),e.jsx("div",{className:"absolute bottom-[15%] left-[8%] opacity-15",children:e.jsx(QN,{className:"w-14 h-14 text-purple-400 rotate-45"})}),e.jsx("div",{className:"absolute bottom-[20%] right-[5%] opacity-20",children:e.jsx(QN,{className:"w-16 h-16 text-pink-300 -rotate-6"})}),e.jsx(Bo,{className:"absolute top-[15%] left-[30%] w-5 h-5 text-rose-300/40 fill-rose-300/20 animate-pulse"}),e.jsx(Bo,{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(Bo,{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"})]}),T3s=()=>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(oh,{className:"absolute top-[8%] left-[12%] w-12 h-12 text-blue-600/15"}),e.jsx(ri,{className:"absolute top-[15%] left-[22%] w-5 h-5 text-amber-500/25 fill-amber-500/15"}),e.jsx(oh,{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(ri,{className:"absolute bottom-[25%] left-[15%] w-6 h-6 text-blue-500/20 fill-blue-500/10 animate-pulse"}),e.jsx(ri,{className:"absolute top-[20%] right-[22%] w-5 h-5 text-indigo-400/20 fill-indigo-400/10 animate-pulse",style:{animationDelay:"0.5s"}})]}),M3s=()=>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(QN,{className:"absolute top-[20%] left-[32%] w-7 h-7 text-purple-400/30"}),e.jsx(QN,{className:"absolute top-[12%] right-[28%] w-6 h-6 text-pink-400/30"}),e.jsx($z,{className:"absolute top-[18%] left-[52%] w-5 h-5 text-sky-400/35"})]}),P3s=()=>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(F8,{className:"absolute top-[5%] left-[10%] w-16 h-16 text-orange-400/25"}),e.jsx(F8,{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(kn,{className:"absolute top-[8%] left-[55%] w-6 h-6 text-purple-400/35 animate-pulse"}),e.jsx(kn,{className:"absolute bottom-[28%] right-[25%] w-5 h-5 text-orange-400/30 animate-pulse",style:{animationDelay:"0.5s"}})]}),I3s=()=>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(nM,{className:"absolute bottom-[8%] left-[5%] w-20 h-20 text-green-600/18"}),e.jsx(nM,{className:"absolute bottom-[12%] right-[8%] w-16 h-16 text-emerald-600/15"}),e.jsx(nM,{className:"absolute bottom-[10%] left-[28%] w-12 h-12 text-green-500/12"}),e.jsx(Hw,{className:"absolute top-[5%] left-[15%] w-10 h-10 text-sky-300/30 animate-pulse"}),e.jsx(Hw,{className:"absolute top-[10%] right-[20%] w-8 h-8 text-blue-300/25 animate-pulse",style:{animationDelay:"0.3s"}}),e.jsx(Hw,{className:"absolute top-[18%] left-[45%] w-6 h-6 text-sky-200/25 animate-pulse",style:{animationDelay:"0.6s"}}),e.jsx(Hw,{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(ri,{className:"absolute top-[3%] left-[50%] -translate-x-1/2 w-10 h-10 text-amber-400/35 fill-amber-400/25"})]}),L3s=()=>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(Bo,{className:"absolute top-[8%] left-[55%] w-6 h-6 text-red-400/22 fill-red-400/12"}),e.jsx(Bo,{className:"absolute top-[20%] right-[25%] w-5 h-5 text-orange-400/22 fill-orange-400/12"})]}),R3s=()=>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(ri,{className:"absolute top-[5%] left-[15%] w-12 h-12 text-yellow-400/35 fill-yellow-400/25 animate-pulse"}),e.jsx(ri,{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(ri,{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(ri,{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(kn,{className:"absolute top-[3%] left-[50%] w-10 h-10 text-yellow-400/40"}),e.jsx(jg,{className:"absolute bottom-[18%] left-[10%] w-12 h-12 text-purple-400/18 rotate-12"}),e.jsx(jg,{className:"absolute bottom-[20%] right-[12%] w-10 h-10 text-amber-400/15 -rotate-12"})]}),D3s=()=>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(ri,{className:"absolute top-[8%] left-[50%] -translate-x-1/2 w-14 h-14 text-yellow-400/28 fill-yellow-400/18"}),e.jsx(kn,{className:"absolute top-[5%] left-[20%] w-7 h-7 text-blue-400/35"}),e.jsx(kn,{className:"absolute top-[10%] right-[18%] w-6 h-6 text-sky-400/30"})]}),O3s=()=>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(n3,{className:"absolute top-[5%] left-[10%] w-16 h-16 text-green-500/25"}),e.jsx(n3,{className:"absolute top-[8%] right-[12%] w-12 h-12 text-emerald-500/20"}),e.jsx(n3,{className:"absolute bottom-[18%] left-[12%] w-14 h-14 text-green-400/22"}),e.jsx(n3,{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"})]})]})]}),F3s=()=>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(ri,{className:"absolute top-[5%] left-[42%] w-10 h-10 text-amber-400/30 fill-amber-400/20"}),e.jsx(ri,{className:"absolute top-[15%] right-[25%] w-7 h-7 text-yellow-400/25 fill-yellow-400/15"}),e.jsx(oh,{className:"absolute bottom-[20%] right-[12%] w-12 h-12 text-blue-500/18"}),e.jsx(oh,{className:"absolute top-[18%] left-[28%] w-8 h-8 text-indigo-400/15"}),e.jsx(g3,{className:"absolute top-[8%] left-[60%] w-10 h-10 text-indigo-400/18"})]}),z3s=()=>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(ip,{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(jg,{className:"absolute top-[8%] left-[45%] w-10 h-10 text-purple-400/22 rotate-12"}),e.jsx(Zo,{className:"absolute bottom-[18%] right-[15%] w-12 h-12 text-rose-400/18"})]}),B3s=()=>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(Bo,{className:"absolute top-[5%] left-[10%] w-16 h-16 text-rose-400/28 fill-rose-400/18"}),e.jsx(Bo,{className:"absolute top-[8%] right-[12%] w-14 h-14 text-pink-400/25 fill-pink-400/15"}),e.jsx(Bo,{className:"absolute bottom-[15%] left-[12%] w-12 h-12 text-red-400/22 fill-red-400/12"}),e.jsx(Bo,{className:"absolute bottom-[18%] right-[10%] w-13 h-13 text-rose-300/25 fill-rose-300/15"}),e.jsx(Bo,{className:"absolute top-[15%] left-[30%] w-6 h-6 text-pink-300/35 fill-pink-300/20 animate-pulse"}),e.jsx(Bo,{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(Bo,{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(Bo,{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"})]}),$3s=()=>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(S2,{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(S2,{className:"absolute top-[15%] left-[18%] w-10 h-10 text-yellow-400/30"}),e.jsx(kn,{className:"absolute top-[10%] left-[42%] w-7 h-7 text-amber-400/35"}),e.jsx(S2,{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"})]}),U3s=()=>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(ua,{className:"absolute top-[8%] left-[10%] w-14 h-14 text-teal-500/22"}),e.jsx(ua,{className:"absolute bottom-[15%] right-[8%] w-16 h-16 text-emerald-500/18"}),e.jsx(__,{className:"absolute top-[12%] right-[18%] w-10 h-10 text-amber-400/25"}),e.jsx(__,{className:"absolute bottom-[22%] left-[22%] w-8 h-8 text-yellow-400/22"}),e.jsx(Bo,{className:"absolute top-[18%] left-[40%] w-6 h-6 text-rose-400/22 fill-rose-400/12"}),e.jsx(Bo,{className:"absolute top-[22%] right-[35%] w-5 h-5 text-teal-400/20 fill-teal-400/10"}),e.jsx(kn,{className:"absolute top-[5%] left-[55%] w-8 h-8 text-teal-400/30"}),e.jsx(jg,{className:"absolute bottom-[20%] left-[48%] w-10 h-10 text-cyan-400/18 rotate-12"})]}),q3s=()=>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(jg,{className:"absolute top-[5%] left-[12%] w-14 h-14 text-emerald-400/25 rotate-12"}),e.jsx(jg,{className:"absolute top-[8%] right-[10%] w-12 h-12 text-teal-400/22 -rotate-12"}),e.jsx(__,{className:"absolute bottom-[18%] left-[18%] w-12 h-12 text-amber-400/25"}),e.jsx(ua,{className:"absolute bottom-[15%] right-[12%] w-14 h-14 text-teal-500/18"}),e.jsx(kn,{className:"absolute top-[15%] left-[42%] w-10 h-10 text-emerald-400/35"}),e.jsx(kn,{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"})]}),V3s=()=>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(__,{className:"absolute bottom-[12%] left-[50%] -translate-x-1/2 w-24 h-24 text-amber-400/25 rotate-45"}),e.jsx(__,{className:"absolute top-[10%] left-[12%] w-10 h-10 text-yellow-400/30"}),e.jsx(__,{className:"absolute top-[12%] right-[15%] w-9 h-9 text-amber-300/25"}),e.jsx(ua,{className:"absolute top-[8%] left-[42%] w-12 h-12 text-teal-500/18"}),e.jsx(jg,{className:"absolute bottom-[22%] right-[18%] w-12 h-12 text-orange-400/18 rotate-12"}),e.jsx(kn,{className:"absolute top-[5%] right-[35%] w-8 h-8 text-yellow-400/35"}),e.jsx(ri,{className:"absolute top-[18%] left-[28%] w-6 h-6 text-amber-400/25 fill-amber-400/15"})]}),H3s=()=>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(ua,{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(__,{className:"absolute top-[10%] right-[12%] w-10 h-10 text-amber-400/28"}),e.jsx(Bo,{className:"absolute top-[8%] left-[18%] w-8 h-8 text-rose-400/25 fill-rose-400/15"}),e.jsx(kn,{className:"absolute top-[12%] left-[45%] w-8 h-8 text-teal-400/30"}),e.jsx(x2,{className:"absolute top-[15%] right-[28%] w-10 h-10 text-emerald-400/20"})]}),$ct=()=>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"})]}),G3s=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx(Bo,{className:"absolute top-6 left-[12%] w-4 h-4 text-rose-300/50 fill-rose-300/30 animate-pulse"}),e.jsx(Bo,{className:"absolute top-10 right-[18%] w-3 h-3 text-pink-300/50 fill-pink-300/30 animate-pulse delay-150"}),e.jsx(Bo,{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(Bo,{className:"absolute top-14 right-[35%] w-3.5 h-3.5 text-pink-300/40 fill-pink-300/20 animate-pulse delay-200"})]}),W3s=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx(x2,{className:"absolute top-5 left-[10%] w-4 h-4 text-blue-400/50 animate-pulse"}),e.jsx(kn,{className:"absolute top-10 right-[15%] w-3 h-3 text-amber-400/50 animate-pulse delay-100"}),e.jsx(ua,{className:"absolute top-8 left-[38%] w-3 h-3 text-teal-300/40 animate-pulse delay-200"})]}),K3s=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx(b_,{className:"absolute top-5 left-[12%] w-4 h-4 text-amber-500/50 animate-pulse"}),e.jsx(Jz,{className:"absolute top-10 right-[15%] w-3 h-3 text-rose-400/50 animate-pulse delay-100"}),e.jsx(b_,{className:"absolute top-8 left-[40%] w-3 h-3 text-amber-400/40 animate-pulse delay-200"})]}),hG=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx(kn,{className:"absolute top-5 left-[10%] w-4 h-4 text-emerald-400/50 animate-pulse"}),e.jsx(jg,{className:"absolute top-10 right-[12%] w-5 h-5 text-amber-400/50 animate-pulse delay-150"}),e.jsx(kn,{className:"absolute top-8 left-[45%] w-3 h-3 text-sky-400/40 animate-pulse delay-300"})]}),Uct=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx(ua,{className:"absolute top-6 left-[12%] w-4 h-4 text-teal-400/40 animate-pulse"}),e.jsx(kn,{className:"absolute top-10 right-[15%] w-3 h-3 text-emerald-400/50 animate-pulse delay-100"}),e.jsx(ua,{className:"absolute top-4 right-[40%] w-3 h-3 text-cyan-400/30 animate-pulse delay-200"})]}),e9e=[{id:"default",name:"Classic",description:"Clean, professional look for any occasion",icon:e.jsx(kn,{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(Bo,{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(G3s,{})},{id:"thinking_of_you",name:"Thinking of You",description:"Let them know they're on your mind",icon:e.jsx(jK,{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(hG,{})},{id:"check_in",name:"Check-in",description:"Touch base with your contacts",icon:e.jsx(b_,{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(K3s,{})},{id:"market_update",name:"Market Update",description:"Share real estate market insights",icon:e.jsx(Ul,{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(Xn,{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(hG,{})},{id:"congratulations",name:"Congratulations",description:"Celebrate their achievements",icon:e.jsx(oh,{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($ct,{})},{id:"welcome_neighborhood",name:"Welcome to the Neighborhood",description:"Greet new neighbors",icon:e.jsx(Si,{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(Uct,{})},{id:"just_because",name:"Just Because",description:"No reason needed to connect",icon:e.jsx(Jz,{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(hG,{})},{id:"birthday",name:"Birthday",description:"Celebrate their special day",icon:e.jsx(ip,{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(z3s,{})},{id:"valentines_day",name:"Valentine's Day",description:"Show appreciation on this special day",icon:e.jsx(Bo,{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(B3s,{})},{id:"groundhog_day",name:"Groundhog Day",description:"A fun seasonal greeting",icon:e.jsx(S2,{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($3s,{})},{id:"new_years",name:"New Year's Day",description:"Ring in the new year",icon:e.jsx(ri,{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(R3s,{})},{id:"easter",name:"Easter",description:"Celebrate the spring season",icon:e.jsx($z,{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(M3s,{})},{id:"mothers_day",name:"Mother's Day",description:"Celebrate the amazing moms",icon:e.jsx(QN,{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(E3s,{})},{id:"fathers_day",name:"Father's Day",description:"Celebrate the amazing dads",icon:e.jsx(oh,{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(T3s,{})},{id:"memorial_day",name:"Memorial Day",description:"Honor those who served",icon:e.jsx(g3,{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(C3s,{})},{id:"independence_day",name:"4th of July",description:"Celebrate Independence Day",icon:e.jsx(iu,{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(A3s,{})},{id:"labor_day",name:"Labor Day",description:"Celebrate the workers",icon:e.jsx(oh,{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(F3s,{})},{id:"halloween",name:"Halloween",description:"Spooky seasonal greetings",icon:e.jsx(F8,{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(P3s,{})},{id:"thanksgiving",name:"Thanksgiving",description:"Express gratitude this season",icon:e.jsx(Bo,{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(L3s,{})},{id:"christmas",name:"Christmas",description:"Spread holiday cheer",icon:e.jsx(nM,{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(I3s,{})},{id:"hanukkah",name:"Hanukkah",description:"Celebrate the Festival of Lights",icon:e.jsx(kn,{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(D3s,{})},{id:"st_patricks_day",name:"St. Patrick's Day",description:"Celebrate the luck of the Irish",icon:e.jsx(n3,{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(O3s,{})},{id:"home_anniversary",name:"Home Anniversary",description:"Celebrate their home ownership milestone",icon:e.jsx(ua,{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(U3s,{})},{id:"under_contract",name:"Under Contract",description:"Celebrate this exciting milestone",icon:e.jsx(jg,{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(q3s,{})},{id:"just_listed",name:"Just Listed",description:"Announce a new listing",icon:e.jsx(ha,{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(Uct,{})},{id:"just_sold",name:"Just Sold",description:"Celebrate a successful sale",icon:e.jsx(Su,{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(hG,{})},{id:"price_reduction",name:"Price Reduction",description:"Notify about a price change",icon:e.jsx(lk,{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(x2,{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(W3s,{})},{id:"closing_day",name:"Closing Day",description:"Celebrate their closing day",icon:e.jsx(__,{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(V3s,{})},{id:"move_in_day",name:"Move-in Day",description:"Welcome them to their new home",icon:e.jsx(ua,{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(H3s,{})},{id:"offer_accepted",name:"Offer Accepted",description:"Celebrate their accepted offer",icon:e.jsx(Ay,{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(hG,{})},{id:"pre_approval",name:"Pre-Approval Congrats",description:"Congratulate on pre-approval",icon:e.jsx(oh,{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($ct,{})}],Y3s=[{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 Z3s(s){return e9e.filter(t=>t.category===s)}function SB(s){return e9e.find(t=>t.id===s)||e9e[0]}function qct(){const{shareToken:s,recipientToken:t}=oo(),[n,r]=k.useState(null),[a,i]=k.useState(null),[l,o]=k.useState(null),[c,d]=k.useState(!0),[u,h]=k.useState(null),[m,p]=k.useState(!0),g=k.useRef(null),x=k.useRef(0),y=k.useRef(0),v=(()=>{const U=new URLSearchParams(window.location.search);return t||U.get("rt")||null})(),_=k.useCallback((U,G=!1)=>{if(!v||U<=0)return;const H=Math.max(1,Math.round(U));if(H<=y.current)return;const se=`https://relzejiswnotikjgvjhz.supabase.co/functions/v1/track-video-share?t=${encodeURIComponent(v)}&e=watch&ws=${H}`;G&&navigator.sendBeacon?navigator.sendBeacon(se):fetch(se,{method:"GET",keepalive:G}).catch(()=>{}),y.current=Math.max(y.current,H)},[v]);k.useEffect(()=>{var oe;if(!m||!(n!=null&&n.playback_url)||!v)return;let U=!1;const G=()=>{x.current>0&&_(x.current,!0)},H=()=>{document.visibilityState==="hidden"&&G()},Y=()=>{G()},se=()=>{var Q;if(U||!g.current||!((Q=window.playerjs)!=null&&Q.Player))return;const me=new window.playerjs.Player(g.current);me.on("timeupdate",te=>{const le=Math.floor(Number((te==null?void 0:te.seconds)??0));!Number.isFinite(le)||le<=0||(x.current=Math.max(x.current,le))}),me.on("pause",()=>{x.current>0&&_(x.current)}),me.on("ended",()=>{x.current>0&&_(x.current,!0)})},ee=document.querySelector('script[data-bunny-playerjs="true"]');if((oe=window.playerjs)!=null&&oe.Player)se();else if(ee)ee.addEventListener("load",se,{once:!0});else{const me=document.createElement("script");me.src="https://assets.mediadelivery.net/playerjs/playerjs-latest.min.js",me.async=!0,me.defer=!0,me.dataset.bunnyPlayerjs="true",me.onload=se,document.body.appendChild(me)}return document.addEventListener("visibilitychange",H),window.addEventListener("beforeunload",Y),()=>{U=!0,document.removeEventListener("visibilitychange",H),window.removeEventListener("beforeunload",Y),G()}},[m,n==null?void 0:n.playback_url,v,_]),k.useEffect(()=>{x.current=0,y.current=0},[v,s]),k.useEffect(()=>{const U=()=>{['[id*="lc_text_widget"]','[class*="lc-text-widget"]','[id*="chat-widget"]','[class*="chat-widget"]','iframe[src*="widgets.leadconnectorhq"]','iframe[src*="msgsndr"]',"[data-chat-widget]"].forEach(se=>{document.querySelectorAll(se).forEach(ee=>{ee.style.display="none"})})};U();const G=[setTimeout(U,500),setTimeout(U,1500),setTimeout(U,3e3)],H=new MutationObserver(U);return H.observe(document.body,{childList:!0,subtree:!0}),()=>{G.forEach(clearTimeout),H.disconnect()}},[]),k.useEffect(()=>{(async()=>{if(!s){h("Invalid share link"),d(!1);return}const{data:G,error:H}=await V.from("agent_videos").select("id, title, playback_url, thumbnail_url, preview_url, duration_seconds, share_token, owner_user_id, contact_id, page_template, recipient_name").eq("share_token",s).eq("is_deleted",!1).single();if(H||!G){h("Video not found or has been removed"),d(!1);return}r(G);try{await V.rpc("log_video_view",{p_video_id:G.id,p_user_agent:navigator.userAgent,p_referrer:document.referrer||null})}catch(Y){console.warn("Failed to log video view:",Y)}if(G.owner_user_id){const{data:Y}=await V.from("profiles").select("id, name, email, phone").eq("id",G.owner_user_id).single();if(Y){i(Y);try{const{data:se}=await V.storage.from("avatars").list(`${G.owner_user_id}`);if(se&&se.length>0){const{data:ee}=V.storage.from("avatars").getPublicUrl(`${G.owner_user_id}/${se[0].name}`);o(ee.publicUrl)}}catch{}}}d(!1)})()},[s]);const j=U=>{if(!U)return"0:00";const G=Math.floor(U/60),H=U%60;return`${G}:${H.toString().padStart(2,"0")}`},C=U=>U.includes("iframe.mediadelivery.net/play/")?U.replace("/play/","/embed/")+"?autoplay=true&responsive=true":U,A=U=>{if(!U)return"?";const G=U.split(" ");return G.length>=2?`${G[0][0]}${G[1][0]}`.toUpperCase():U.substring(0,2).toUpperCase()},M=SB((n==null?void 0:n.page_template)||"default"),I=(n==null?void 0:n.recipient_name)||null,P=M.headerText(I),O=`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(Jt,{className:"h-8 w-8 animate-spin text-primary"})});if(u||!n)return e.jsx("div",{className:"min-h-screen bg-background flex items-center justify-center p-4",children:e.jsx(we,{className:"max-w-md w-full",children:e.jsxs(De,{className:"py-12 text-center",children:[e.jsx(ia,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("h2",{className:"text-xl font-semibold mb-2",children:"Video Not Found"}),e.jsx("p",{className:"text-muted-foreground",children:u||"This video is no longer available."})]})})});const B=M.id!=="default";return e.jsxs(e.Fragment,{children:[e.jsxs(Sc,{children:[e.jsx("title",{children:P}),e.jsx("meta",{name:"description",content:M.subText}),e.jsx("meta",{property:"og:title",content:P}),e.jsx("meta",{property:"og:description",content:M.subText}),e.jsx("meta",{property:"og:type",content:"video.other"}),e.jsx("meta",{property:"og:url",content:O}),n.preview_url&&e.jsx("meta",{property:"og:image",content:n.preview_url}),!n.preview_url&&n.thumbnail_url&&e.jsx("meta",{property:"og:image",content:n.thumbnail_url}),n.playback_url&&e.jsxs(e.Fragment,{children:[e.jsx("meta",{property:"og:video",content:n.playback_url}),e.jsx("meta",{property:"og:video:type",content:"text/html"}),e.jsx("meta",{property:"og:video:width",content:"1280"}),e.jsx("meta",{property:"og:video:height",content:"720"})]}),e.jsx("meta",{name:"twitter:card",content:"player"}),e.jsx("meta",{name:"twitter:title",content:P}),e.jsx("meta",{name:"twitter:description",content:M.subText}),n.preview_url&&e.jsx("meta",{name:"twitter:image",content:n.preview_url}),n.playback_url&&e.jsxs(e.Fragment,{children:[e.jsx("meta",{name:"twitter:player",content:n.playback_url}),e.jsx("meta",{name:"twitter:player:width",content:"1280"}),e.jsx("meta",{name:"twitter:player:height",content:"720"})]})]}),e.jsxs("div",{className:Ot("min-h-screen flex items-center justify-center p-4 bg-gradient-to-b relative",M.gradientClasses),children:[B&&M.decorativeElement,e.jsxs("div",{className:"max-w-2xl w-full space-y-6 relative z-10",children:[B&&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:Ot("w-14 h-14 rounded-full flex items-center justify-center shadow-sm",M.accentColor==="primary"&&"bg-primary/10 text-primary",M.accentColor==="amber"&&"bg-amber-100 text-amber-600 dark:bg-amber-900/50 dark:text-amber-400",M.accentColor==="teal"&&"bg-teal-100 text-teal-600 dark:bg-teal-900/50 dark:text-teal-400",M.accentColor==="rose"&&"bg-rose-100 text-rose-600 dark:bg-rose-900/50 dark:text-rose-400",M.accentColor==="emerald"&&"bg-emerald-100 text-emerald-600 dark:bg-emerald-900/50 dark:text-emerald-400",M.accentColor==="yellow"&&"bg-yellow-100 text-yellow-600 dark:bg-yellow-900/50 dark:text-yellow-400",M.accentColor==="pink"&&"bg-pink-100 text-pink-600 dark:bg-pink-900/50 dark:text-pink-400",M.accentColor==="blue"&&"bg-blue-100 text-blue-600 dark:bg-blue-900/50 dark:text-blue-400",M.accentColor==="red"&&"bg-red-100 text-red-600 dark:bg-red-900/50 dark:text-red-400",M.accentColor==="orange"&&"bg-orange-100 text-orange-600 dark:bg-orange-900/50 dark:text-orange-400",M.accentColor==="green"&&"bg-green-100 text-green-600 dark:bg-green-900/50 dark:text-green-400",M.accentColor==="violet"&&"bg-violet-100 text-violet-600 dark:bg-violet-900/50 dark:text-violet-400",M.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:M.icon})})}),e.jsx("h1",{className:"text-2xl sm:text-3xl font-bold mb-2",children:P}),e.jsx("p",{className:"text-muted-foreground",children:M.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(Wa,{className:"h-14 w-14 border-2 border-primary/20",children:[e.jsx(eo,{src:l||void 0,alt:a.name||"Agent"}),e.jsx(Ka,{className:"bg-primary/10 text-primary font-semibold",children:A(a.name)})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:B?"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($,{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(ka,{className:"h-4 w-4"})})}),a.email&&e.jsx($,{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(pn,{className:"h-4 w-4"})})})]})]}),e.jsx(we,{className:"overflow-hidden shadow-lg",children:m&&n.playback_url?e.jsx("div",{className:"relative w-full",style:{paddingBottom:"56.25%"},children:e.jsx("iframe",{ref:g,src:C(n.playback_url),title:n.title||"Video message",className:"absolute top-0 left-0 w-full h-full",style:{border:0},allow:"accelerometer; gyroscope; autoplay; encrypted-media; picture-in-picture",allowFullScreen:!0})}):e.jsxs("div",{className:"relative aspect-video bg-muted cursor-pointer group",onClick:()=>p(!0),children:[n.preview_url||n.thumbnail_url?e.jsx("img",{src:n.preview_url||n.thumbnail_url||"",alt:n.title?`${n.title} video preview`:"Video message preview",className:"w-full h-full object-cover",onError:U=>{var H;U.currentTarget.style.display="none";const G=(H=U.currentTarget.parentElement)==null?void 0:H.querySelector(".video-fallback");G&&(G.style.display="flex")}}):null,e.jsx("div",{className:"video-fallback w-full h-full items-center justify-center bg-gradient-to-br from-primary/20 to-primary/5",style:{display:n.preview_url||n.thumbnail_url?"none":"flex"},children:e.jsx(ia,{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(pu,{className:"h-10 w-10 text-primary ml-1"})})}),n.duration_seconds&&e.jsx("div",{className:"absolute bottom-3 right-3 bg-black/70 text-white text-sm px-2 py-1 rounded",children:j(n.duration_seconds)})]})}),!B&&e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"text-2xl font-bold",children:n.title||"Video Message"}),e.jsx("p",{className:"text-muted-foreground mt-2",children:m?"Enjoy the video!":"Click to play the video"})]}),!m&&e.jsx("div",{className:"flex justify-center",children:e.jsxs($,{size:"lg",onClick:()=>p(!0),className:"gap-2",children:[e.jsx(pu,{className:"h-5 w-5"}),"Watch Video"]})}),e.jsx(S3s,{shareToken:s,agentName:(a==null?void 0:a.name)||null,hasContact:!!n.contact_id})]})]})]})}function X3s(){return k.useEffect(()=>(document.body.classList.add("video-landing-page"),()=>{document.body.classList.remove("video-landing-page")}),[]),e.jsx(V5t,{})}function Q3s(){const{token:s}=oo();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(Jt,{className:"h-5 w-5 animate-spin"}),e.jsx("span",{children:"Loading video preview…"})]})})}const J3s={office_exclusive:"Office Exclusive",coming_soon:"Coming Soon",pre_market:"Pre-Market",active:"Active"},eAs=s=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s||0);function tAs(){var le;const[s]=Jc(),t=s.get("r"),n=s.get("m"),[r,a]=k.useState(null),[i,l]=k.useState(null),[o,c]=k.useState(!0),[d,u]=k.useState(0),[h,m]=k.useState(!1),[p,g]=k.useState(""),[x,y]=k.useState(""),[v,_]=k.useState(""),[j,C]=k.useState(""),[A,M]=k.useState("tour"),[I,P]=k.useState(!1),[R,O]=k.useState(!1),B=async()=>{if(!p.trim()||!x.trim()){ae.error("Please enter your name and email");return}P(!0);try{const _e=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/private-listing-lead",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({r:t,m:n,name:p.trim(),email:x.trim(),phone:v.trim()||null,message:j.trim()||null,intent:A})}),ve=await _e.json();if(!_e.ok||!(ve!=null&&ve.success))throw new Error((ve==null?void 0:ve.error)||"Could not send");O(!0),ae.success("Sent! The agent will be in touch shortly.")}catch(fe){ae.error((fe==null?void 0:fe.message)||"Could not send")}finally{P(!1)}};if(k.useEffect(()=>{if(!t||!n){l("Invalid link"),c(!1);return}const fe=`https://relzejiswnotikjgvjhz.supabase.co/functions/v1/private-listing-view?r=${encodeURIComponent(t)}&m=${encodeURIComponent(n)}`;fetch(fe).then(_e=>_e.json()).then(_e=>{_e.error?l("This private listing link is no longer valid."):a({listing:_e.listing,agent:_e.agent})}).catch(()=>l("Unable to load listing.")).finally(()=>c(!1))},[t,n]),o)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-slate-50",children:e.jsx("div",{className:"text-slate-500",children:"Loading…"})});if(i||!r)return e.jsxs(e.Fragment,{children:[e.jsx(Sc,{children:e.jsx("meta",{name:"robots",content:"noindex,nofollow,noarchive"})}),e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-slate-50 px-6 text-center",children:e.jsxs("div",{children:[e.jsx(fu,{className:"h-10 w-10 text-slate-400 mx-auto mb-3"}),e.jsx("h1",{className:"text-xl font-semibold text-slate-900",children:"Private listing unavailable"}),e.jsx("p",{className:"text-slate-600 mt-2",children:i||"This link has expired or was not shared with you."})]})})]});const{listing:U,agent:G}=r,H=(le=U.photos)!=null&&le.length?U.photos:[],Y=H[0],se=J3s[U.status]||U.status,ee=(G==null?void 0:G.sender_name)||(G==null?void 0:G.name)||"Your Agent",oe=(G==null?void 0:G.sender_email)||null,me=encodeURIComponent(`Interested in ${U.address}`),Q=encodeURIComponent(`Hi ${ee}, I'd love to learn more about ${U.address}, ${U.city}. Thanks!`),te=G!=null&&G.booking_slug?`https://dashboard.relevelup.com/book/${G.booking_slug}`:null;return e.jsxs(e.Fragment,{children:[e.jsxs(Sc,{children:[e.jsxs("title",{children:["Private Listing · ",U.address]}),e.jsx("meta",{name:"robots",content:"noindex,nofollow,noarchive,nosnippet"}),e.jsx("meta",{name:"googlebot",content:"noindex,nofollow,noarchive,nosnippet"})]}),e.jsxs("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white",children:[e.jsxs("div",{className:"bg-gradient-to-r from-indigo-600 to-indigo-500 text-white text-center text-xs sm:text-sm py-2 px-4 flex items-center justify-center gap-2",children:[e.jsx(fu,{className:"h-3.5 w-3.5"}),e.jsxs("span",{className:"font-medium tracking-wide uppercase",children:["Private listing · Shared by ",ee]})]}),e.jsxs("div",{className:"relative",children:[Y?e.jsx("button",{type:"button",className:"block w-full",onClick:()=>{u(0),m(!0)},children:e.jsx("img",{src:Y,alt:U.address,className:"w-full h-[42vh] md:h-[60vh] object-cover"})}):e.jsx("div",{className:"w-full h-[42vh] md:h-[60vh] bg-slate-200 flex items-center justify-center text-slate-400",children:"No photos available"}),e.jsx("div",{className:"absolute top-4 left-4",children:e.jsx(qe,{className:"bg-indigo-600 text-white border-0 text-xs px-2.5 py-1 shadow",children:se})}),H.length>1&&e.jsxs("div",{className:"absolute bottom-4 right-4 bg-black/60 text-white text-xs px-2.5 py-1 rounded-full",children:[H.length," photos"]})]}),e.jsxs("div",{className:"max-w-5xl mx-auto px-4 sm:px-6 -mt-10 relative z-10",children:[e.jsx(we,{className:"shadow-xl border-slate-200",children:e.jsxs(De,{className:"p-6 sm:p-8",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-start sm:justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl sm:text-3xl font-bold text-slate-900",children:U.address}),e.jsxs("p",{className:"text-slate-600 mt-1 flex items-center gap-1.5",children:[e.jsx(Si,{className:"h-4 w-4"}),U.city,", ",U.state," ",U.zip]})]}),e.jsx("div",{className:"text-right",children:e.jsx("p",{className:"text-3xl sm:text-4xl font-bold text-indigo-600",children:eAs(U.price)})})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3 mt-6",children:[U.bedrooms?e.jsxs("div",{className:"bg-slate-50 rounded-lg p-3 text-center",children:[e.jsx(Yw,{className:"h-5 w-5 mx-auto text-slate-500 mb-1"}),e.jsx("p",{className:"text-lg font-semibold text-slate-900",children:U.bedrooms}),e.jsx("p",{className:"text-xs text-slate-500",children:"Beds"})]}):null,U.bathrooms?e.jsxs("div",{className:"bg-slate-50 rounded-lg p-3 text-center",children:[e.jsx(p0,{className:"h-5 w-5 mx-auto text-slate-500 mb-1"}),e.jsx("p",{className:"text-lg font-semibold text-slate-900",children:U.bathrooms}),e.jsx("p",{className:"text-xs text-slate-500",children:"Baths"})]}):null,U.sqft?e.jsxs("div",{className:"bg-slate-50 rounded-lg p-3 text-center",children:[e.jsx(w_,{className:"h-5 w-5 mx-auto text-slate-500 mb-1"}),e.jsx("p",{className:"text-lg font-semibold text-slate-900",children:U.sqft.toLocaleString()}),e.jsx("p",{className:"text-xs text-slate-500",children:"Sq Ft"})]}):null]}),U.description&&e.jsxs("div",{className:"mt-8",children:[e.jsx("h2",{className:"text-lg font-semibold text-slate-900 mb-2",children:"About this property"}),e.jsx("p",{className:"text-slate-700 leading-relaxed whitespace-pre-line",children:U.description})]}),H.length>1&&e.jsxs("div",{className:"mt-8",children:[e.jsx("h2",{className:"text-lg font-semibold text-slate-900 mb-3",children:"Photos"}),e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-2",children:H.slice(0,9).map((fe,_e)=>e.jsx("button",{type:"button",onClick:()=>{u(_e),m(!0)},className:"aspect-[4/3] overflow-hidden rounded-lg bg-slate-100",children:e.jsx("img",{src:fe,alt:"",className:"w-full h-full object-cover hover:scale-105 transition"})},_e))})]})]})}),e.jsxs(we,{className:"mt-6 shadow-lg border-slate-200 overflow-hidden",children:[e.jsxs("div",{className:"bg-gradient-to-r from-indigo-600 to-indigo-500 px-6 py-4 text-white",children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Request more info or a private tour"}),e.jsxs("p",{className:"text-indigo-100 text-sm",children:[ee," will get back to you personally."]})]}),e.jsx(De,{className:"p-6 sm:p-8",children:R?e.jsxs("div",{className:"flex flex-col items-center text-center py-6",children:[e.jsx(Gr,{className:"h-12 w-12 text-emerald-500 mb-3"}),e.jsx("h3",{className:"text-lg font-semibold text-slate-900",children:"Message sent"}),e.jsxs("p",{className:"text-slate-600 mt-1",children:[ee," just got your request and will reach out shortly."]})]}):e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-2",children:[{id:"tour",label:"Private tour"},{id:"info",label:"More info"},{id:"offer",label:"Make an offer"}].map(fe=>e.jsx("button",{type:"button",onClick:()=>M(fe.id),className:`px-3 py-2 rounded-lg border text-sm font-medium transition ${A===fe.id?"bg-indigo-600 text-white border-indigo-600":"bg-white text-slate-700 border-slate-200 hover:border-indigo-300"}`,children:fe.label},fe.id))}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(re,{htmlFor:"pl-name",children:"Your name *"}),e.jsx(be,{id:"pl-name",value:p,onChange:fe=>g(fe.target.value),placeholder:"Jane Doe",maxLength:120})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"pl-email",children:"Email *"}),e.jsx(be,{id:"pl-email",type:"email",value:x,onChange:fe=>y(fe.target.value),placeholder:"you@email.com",maxLength:255})]})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"pl-phone",children:"Phone (optional)"}),e.jsx(be,{id:"pl-phone",value:v,onChange:fe=>_(fe.target.value),placeholder:"(555) 555-5555",maxLength:40})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"pl-msg",children:"Message (optional)"}),e.jsx(Ls,{id:"pl-msg",value:j,onChange:fe=>C(fe.target.value),placeholder:`I'd love to see ${U.address}…`,rows:4,maxLength:2e3})]}),e.jsx($,{onClick:B,disabled:I,className:"w-full bg-indigo-600 hover:bg-indigo-700 h-11 text-base",children:I?"Sending…":"Send to "+ee.split(" ")[0]}),e.jsx("p",{className:"text-xs text-slate-500 text-center",children:"By submitting, you agree to be contacted about this property."})]})})]}),e.jsx(we,{className:"mt-6 mb-12 shadow-lg border-slate-200",children:e.jsxs(De,{className:"p-6 sm:p-8",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row items-center sm:items-start gap-5",children:[G!=null&&G.avatar_url?e.jsx("img",{src:G.avatar_url,alt:ee,className:"h-20 w-20 rounded-full object-cover ring-2 ring-indigo-100"}):e.jsx("div",{className:"h-20 w-20 rounded-full bg-indigo-100 flex items-center justify-center text-indigo-600 text-2xl font-bold",children:ee.charAt(0)}),e.jsxs("div",{className:"flex-1 text-center sm:text-left",children:[e.jsx("p",{className:"text-xs uppercase tracking-wider text-slate-500",children:"Shared by"}),e.jsx("h3",{className:"text-xl font-bold text-slate-900",children:ee}),(G==null?void 0:G.brokerage_name)&&e.jsx("p",{className:"text-slate-600 text-sm",children:G.brokerage_name}),e.jsx("p",{className:"text-slate-600 text-sm mt-2",children:"Want a private tour or more info? Reach out — I'm happy to help."})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-2 mt-6",children:[oe&&e.jsx($,{asChild:!0,className:"bg-indigo-600 hover:bg-indigo-700",children:e.jsxs("a",{href:`mailto:${oe}?subject=${me}&body=${Q}`,children:[e.jsx(pn,{className:"h-4 w-4 mr-1.5"}),"Email"]})}),(G==null?void 0:G.phone)&&e.jsx($,{asChild:!0,variant:"outline",children:e.jsxs("a",{href:`tel:${G.phone}`,children:[e.jsx(ka,{className:"h-4 w-4 mr-1.5"}),G.phone]})}),te&&e.jsx($,{asChild:!0,variant:"outline",children:e.jsxs("a",{href:te,target:"_blank",rel:"noreferrer",children:[e.jsx(wm,{className:"h-4 w-4 mr-1.5"}),"Book a tour"]})})]})]})})]}),h&&H.length>0&&e.jsxs("div",{className:"fixed inset-0 z-50 bg-black/95 flex items-center justify-center",children:[e.jsx("button",{className:"absolute top-4 right-4 text-white p-2 hover:bg-white/10 rounded-full",onClick:()=>m(!1),"aria-label":"Close",children:e.jsx(mr,{className:"h-6 w-6"})}),e.jsx("button",{className:"absolute left-4 text-white p-2 hover:bg-white/10 rounded-full",onClick:()=>u(fe=>(fe-1+H.length)%H.length),"aria-label":"Previous",children:e.jsx(Ld,{className:"h-8 w-8"})}),e.jsx("img",{src:H[d],alt:"",className:"max-w-[90vw] max-h-[85vh] object-contain"}),e.jsx("button",{className:"absolute right-4 text-white p-2 hover:bg-white/10 rounded-full",onClick:()=>u(fe=>(fe+1)%H.length),"aria-label":"Next",children:e.jsx(fi,{className:"h-8 w-8"})}),e.jsxs("p",{className:"absolute bottom-4 left-1/2 -translate-x-1/2 text-white/80 text-sm",children:[d+1," / ",H.length]})]})]})]})}function sAs(){var i;const{slug:s}=oo(),{data:t,isLoading:n,error:r}=JAt(s);if(k.useEffect(()=>(document.body.classList.add("agent-card-page"),()=>{document.body.classList.remove("agent-card-page")}),[]),k.useEffect(()=>{t!=null&&t.id&&Md(t.id,"card_view")},[t==null?void 0:t.id]),n)return e.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white flex items-center justify-center",children:e.jsxs("div",{className:"w-full max-w-md mx-auto p-6 space-y-6",children:[e.jsxs("div",{className:"flex flex-col items-center gap-4",children:[e.jsx(fn,{className:"h-28 w-28 rounded-full"}),e.jsx(fn,{className:"h-6 w-48"}),e.jsx(fn,{className:"h-4 w-36"})]}),e.jsx(fn,{className:"h-12 w-full"}),e.jsx(fn,{className:"h-12 w-full"})]})});if(r||!t)return e.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white flex items-center justify-center p-6",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"text-2xl font-bold text-slate-800 mb-2",children:"Card Not Found"}),e.jsx("p",{className:"text-slate-500",children:"This agent card doesn't exist or isn't published yet."})]})});const a=((i=t.profile)==null?void 0:i.name)||"Agent";return e.jsxs(e.Fragment,{children:[e.jsxs(Sc,{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(EGe,{card:t})]})}const nAs="https://images.unsplash.com/photo-1507525428034-b723cf961d3e?w=1600&q=80",rAs="https://images.unsplash.com/photo-1616486338812-3dadae4b4ace?w=1600&q=80",aAs="https://images.unsplash.com/photo-1500534314209-a25ddb2bd429?w=1600&q=80",iAs="https://images.unsplash.com/photo-1600585154340-be6161a56a0c?w=1600&q=80",oAs="https://images.unsplash.com/photo-1519741497674-611481863552?w=1600&q=80",lAs="https://images.unsplash.com/photo-1494526585095-c41746248156?w=1600&q=80",hNe={"minimal-mono":{key:"minimal-mono",label:"Minimal Mono",description:"Clean paper white, restrained.",bg:"#f7f7f5",surface:"#ffffff",border:"#e6e5e0",text:"#111111",textMuted:"#6b6b6b",accent:"#111111",accentText:"#ffffff",headingFont:'"Fraunces", ui-serif, Georgia, serif',bodyFont:'"Inter", system-ui, sans-serif',swatch:["#f7f7f5","#111111","#6b6b6b","#e6e5e0"],defaultCover:lAs},"warm-coastal":{key:"warm-coastal",label:"Warm Coastal",description:"Sand and soft teal.",bg:"linear-gradient(180deg,#faf6ef 0%,#f2ece1 100%)",surface:"#ffffff",border:"#e6dfd1",text:"#2b2a26",textMuted:"#7a746a",accent:"#2f7a7d",accentText:"#ffffff",headingFont:'"Cormorant Garamond", ui-serif, Georgia, serif',bodyFont:'"Karla", system-ui, sans-serif',swatch:["#faf6ef","#2f7a7d","#c9b99a","#2b2a26"],defaultCover:nAs},"deep-luxe":{key:"deep-luxe",label:"Deep Luxe",description:"Charcoal with gold.",bg:"linear-gradient(180deg,#161616 0%,#0d0d0d 100%)",surface:"#1e1e1e",border:"#2c2c2c",text:"#f5f0e0",textMuted:"#a49a80",accent:"#c9a84c",accentText:"#111111",headingFont:'"Instrument Serif", ui-serif, Georgia, serif',bodyFont:'"Work Sans", system-ui, sans-serif',swatch:["#0d0d0d","#c9a84c","#f5f0e0","#2c2c2c"],defaultCover:rAs},sunset:{key:"sunset",label:"Sunset",description:"Peach into magenta.",bg:"linear-gradient(160deg,#ffe4d1 0%,#ffc9b0 40%,#f2a1c5 100%)",surface:"#ffffff",border:"#f6d5ce",text:"#2a1a2f",textMuted:"#7a5a70",accent:"#d84a7a",accentText:"#ffffff",headingFont:'"Sora", system-ui, sans-serif',bodyFont:'"Manrope", system-ui, sans-serif',swatch:["#ffe4d1","#ffc9b0","#f2a1c5","#d84a7a"],defaultCover:aAs},editorial:{key:"editorial",label:"Editorial",description:"Ink black on paper white.",bg:"#f5f3ee",surface:"#ffffff",border:"#d9d6ce",text:"#0d0d0d",textMuted:"#5a564d",accent:"#0d0d0d",accentText:"#f5f3ee",headingFont:'"DM Serif Display", ui-serif, Georgia, serif',bodyFont:'"Fira Sans", system-ui, sans-serif',swatch:["#f5f3ee","#0d0d0d","#d9d6ce","#5a564d"],defaultCover:iAs},playful:{key:"playful",label:"Playful",description:"Blush and lavender.",bg:"linear-gradient(180deg,#fdf3f7 0%,#efe5ff 100%)",surface:"#ffffff",border:"#ecd7e6",text:"#3a2450",textMuted:"#7c6a94",accent:"#9b72cf",accentText:"#ffffff",headingFont:'"Outfit", system-ui, sans-serif',bodyFont:'"Figtree", system-ui, sans-serif',swatch:["#fdf3f7","#efe5ff","#c9a0dc","#9b72cf"],defaultCover:oAs}},cAs=["#111111","#2f7a7d","#c9a84c","#d84a7a","#3b6fa0","#9b72cf","#e85d3a","#4a6741"];function AMt(s){return s&&s in hNe?hNe[s]:hNe["minimal-mono"]}function dAs(s,t){const n=t||s.accent;return{background:s.bg,color:s.text,fontFamily:s.bodyFont,"--c-bg":s.bg,"--c-surface":s.surface,"--c-border":s.border,"--c-text":s.text,"--c-text-muted":s.textMuted,"--c-accent":n,"--c-accent-text":s.accentText,"--c-heading-font":s.headingFont,"--c-body-font":s.bodyFont}}function EMt({slugOverride:s}={}){var Bs;const{slug:t}=oo(),n=s||t,[r]=Jc(),a=r.get("t"),[i,l]=k.useState(!0),[o,c]=k.useState(null),[d,u]=k.useState(null),h=k.useRef(null),m=k.useRef(null),[p,g]=k.useState(null),[x,y]=k.useState(null),[v,_]=k.useState(!1),[j,C]=k.useState(!1),[A,M]=k.useState(0),[I,P]=k.useState(!1),[R,O]=k.useState(""),[B,U]=k.useState(""),[G,H]=k.useState(""),[Y,se]=k.useState(""),[ee,oe]=k.useState(""),[me,Q]=k.useState(""),[te,le]=k.useState(""),[fe,_e]=k.useState(""),[ve,he]=k.useState(""),[Se,Te]=k.useState(""),[Ie,Ue]=k.useState(""),[Be,je]=k.useState(""),[Ye,Ee]=k.useState(""),[Re,ke]=k.useState([]),[Fe,Oe]=k.useState([]),[Ge,yt]=k.useState(""),[tt,ut]=k.useState(""),[nt,et]=k.useState(""),[at,wt]=k.useState([]);k.useEffect(()=>{rt()},[n,a]);const rt=async()=>{if(!n)return;l(!0);const{data:Ts,error:Fn}=await V.from("contact_intake_pages").select("*").eq("slug",n).eq("is_active",!0).maybeSingle();if(Fn||!Ts){P(!0),l(!1);return}u(Ts),m.current=Ts;const{data:An}=await V.from("profiles").select("name, avatar_url, title, phone, email, brokerage_id").eq("id",Ts.user_id).single();if(An){let js;if(An.brokerage_id){const{data:jr}=await V.from("brokerages").select("name").eq("id",An.brokerage_id).single();js=(jr==null?void 0:jr.name)||void 0}let In=An.avatar_url||null;if(!In){const{data:jr}=V.storage.from("avatars").getPublicUrl(`${Ts.user_id}/avatar.jpg`);jr!=null&&jr.publicUrl&&(In=`${jr.publicUrl}?t=${Date.now()}`)}const un={...An,avatar_url:In,brokerage_name:js};c(un),h.current=un}if(a)try{console.log("[ConnectPage] Resolving token:",a,"for page:",Ts.id);const{data:js,error:In}=await V.functions.invoke("process-intake-submissions",{body:{action:"resolve_token",token:a,page_id:Ts.id}});if(console.log("[ConnectPage] Resolve result:",{resolved:js,resolveErr:In}),!In&&(js!=null&&js.contact_id)){y(js.contact_id);const un=js.contact;un&&(g(un),O(un.first_name||""),U(un.last_name||""),H(un.email||""),se(un.phone||""),oe(un.address||""),Q(un.city||""),le(un.state||""),_e(un.zip||""),he(un.birthday||""),Te(un.home_anniversary||""))}}catch(js){console.error("Failed to resolve token:",js)}l(!1)},Ft=async()=>{var Ts,Fn;if(!R.trim()){ae.error("Please enter your first name");return}if(!n){ae.error("Invalid page. Please refresh.");return}C(!0);try{let An=(Ts=m.current)==null?void 0:Ts.id,js=(Fn=m.current)==null?void 0:Fn.user_id;if(!An||!js){const{data:jr}=await V.from("contact_intake_pages").select("id, user_id").eq("slug",n).eq("is_active",!0).maybeSingle();if(!jr){ae.error("This page is no longer active. Please contact the agent directly."),C(!1);return}An=jr.id,js=jr.user_id}const In={intake_page_id:An,agent_user_id:js,existing_contact_id:x,first_name:R.trim(),last_name:B.trim()||null,email:G.trim()||null,phone:Y.trim()||null,address:ee.trim()||null,city:me.trim()||null,state:te.trim()||null,zip:fe.trim()||null,birthday:ve||null,home_anniversary:Se||null,real_estate_interest:Ie||null,message:Be.trim()||null,life_events:{spouse_name:Ye.trim()||null,kids:Re.filter(jr=>jr.name.trim()),pets:Fe.filter(jr=>jr.name.trim()),favorite_spots:Ge.trim()||null,dream_neighborhood:tt.trim()||null,wedding_anniversary:nt||null},referrals:at.filter(jr=>jr.name.trim()&&jr.contact.trim())},{error:un}=await V.from("contact_intake_submissions").insert(In);if(console.log("[ConnectPage] Insert result:",{error:un}),un)throw un;a&&await V.from("contact_intake_tokens").update({used_at:new Date().toISOString()}).eq("token",a);try{const jr=[R.trim(),B.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:js,contactName:jr,contactEmail:G.trim()||null,contactPhone:Y.trim()||null,slug:n})})}catch(jr){console.warn("Connect page notification failed (non-blocking):",jr)}_(!0)}catch(An){console.error(An),ae.error("Something went wrong. Please try again.")}finally{C(!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(Jt,{className:"h-8 w-8 animate-spin text-slate-400"})});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.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(v)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(Sc,{children:e.jsxs("title",{children:["Thank You | ",o==null?void 0:o.name]})}),e.jsxs(_r.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(_r.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(Gr,{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(Bo,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"Powered by ReLevelUp"})]})]})]});const Ut=!!a&&!!p,Is=(d==null?void 0:d.show_little_things)??!0,xs=[{title:Ut?"Confirm Your Info":"Let's Get Connected",fields:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"First Name *"}),e.jsx("input",{type:"text",value:R,onChange:Ts=>O(Ts.target.value),placeholder:"Jane",className:"connect-input",required:!0})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"Last Name"}),e.jsx("input",{type:"text",value:B,onChange:Ts=>U(Ts.target.value),placeholder:"Smith",className:"connect-input"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"Email"}),e.jsx("input",{type:"email",value:G,onChange:Ts=>H(Ts.target.value),placeholder:"jane@email.com",className:"connect-input"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"Phone"}),e.jsx("input",{type:"tel",value:Y,onChange:Ts=>se(Ts.target.value),placeholder:"(555) 123-4567",className:"connect-input"})]})]})},{title:"A Little More About You",fields:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"Street Address"}),e.jsx("input",{type:"text",value:ee,onChange:Ts=>oe(Ts.target.value),placeholder:"123 Main St",className:"connect-input"})]}),e.jsxs("div",{className:"grid grid-cols-5 gap-3",children:[e.jsxs("div",{className:"col-span-2",children:[e.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"City"}),e.jsx("input",{type:"text",value:me,onChange:Ts=>Q(Ts.target.value),placeholder:"Austin",className:"connect-input"})]}),e.jsxs("div",{className:"col-span-1",children:[e.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"State"}),e.jsx("input",{type:"text",value:te,onChange:Ts=>le(Ts.target.value),placeholder:"TX",maxLength:2,className:"connect-input"})]}),e.jsxs("div",{className:"col-span-2",children:[e.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"Zip"}),e.jsx("input",{type:"text",value:fe,onChange:Ts=>_e(Ts.target.value),placeholder:"78701",className:"connect-input"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"Birthday"}),e.jsx("input",{type:"date",value:ve,onChange:Ts=>he(Ts.target.value),className:"connect-input"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"Home Anniversary"}),e.jsx("input",{type:"date",value:Se,onChange:Ts=>Te(Ts.target.value),className:"connect-input"})]})]})]})},...Is?[{title:"The Little Things",subtitle:"Optional — helps me remember what matters to you.",fields:e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"Spouse / partner's name"}),e.jsx("input",{type:"text",value:Ye,onChange:Ts=>Ee(Ts.target.value),placeholder:"Alex",className:"connect-input"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"Wedding anniversary"}),e.jsx("input",{type:"date",value:nt,onChange:Ts=>et(Ts.target.value),className:"connect-input"})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[e.jsx("label",{className:"block text-sm font-medium",style:{color:"var(--c-text-muted)"},children:"Kids"}),e.jsxs("button",{type:"button",onClick:()=>ke(Ts=>[...Ts,{name:"",age:""}]),className:"text-xs inline-flex items-center gap-1",style:{color:"var(--c-accent)"},children:[e.jsx(nn,{className:"h-3 w-3"})," Add"]})]}),e.jsxs("div",{className:"space-y-2",children:[Re.length===0&&e.jsx("p",{className:"text-xs",style:{color:"var(--c-text-muted)"},children:"None to add? Skip this."}),Re.map((Ts,Fn)=>e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx("input",{type:"text",value:Ts.name,onChange:An=>ke(js=>js.map((In,un)=>un===Fn?{...In,name:An.target.value}:In)),placeholder:"Child's name",className:"connect-input min-w-0",style:{flex:"1 1 0%"}}),e.jsx("input",{type:"text",value:Ts.age,onChange:An=>ke(js=>js.map((In,un)=>un===Fn?{...In,age:An.target.value}:In)),placeholder:"Age",className:"connect-input shrink-0",style:{width:"5rem"}}),e.jsx("button",{type:"button",onClick:()=>ke(An=>An.filter((js,In)=>In!==Fn)),className:"p-2 rounded-md hover:bg-black/5 shrink-0","aria-label":"Remove",children:e.jsx(mr,{className:"h-3.5 w-3.5",style:{color:"var(--c-text-muted)"}})})]},Fn))]})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[e.jsx("label",{className:"block text-sm font-medium",style:{color:"var(--c-text-muted)"},children:"Pets"}),e.jsxs("button",{type:"button",onClick:()=>Oe(Ts=>[...Ts,{name:"",kind:""}]),className:"text-xs inline-flex items-center gap-1",style:{color:"var(--c-accent)"},children:[e.jsx(nn,{className:"h-3 w-3"})," Add"]})]}),e.jsxs("div",{className:"space-y-2",children:[Fe.length===0&&e.jsx("p",{className:"text-xs",style:{color:"var(--c-text-muted)"},children:"None to add? Skip this."}),Fe.map((Ts,Fn)=>e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx("input",{type:"text",value:Ts.name,onChange:An=>Oe(js=>js.map((In,un)=>un===Fn?{...In,name:An.target.value}:In)),placeholder:"Pet's name",className:"connect-input min-w-0",style:{flex:"1 1 0%"}}),e.jsx("input",{type:"text",value:Ts.kind,onChange:An=>Oe(js=>js.map((In,un)=>un===Fn?{...In,kind:An.target.value}:In)),placeholder:"Dog, cat…",className:"connect-input shrink-0",style:{width:"7rem"}}),e.jsx("button",{type:"button",onClick:()=>Oe(An=>An.filter((js,In)=>In!==Fn)),className:"p-2 rounded-md hover:bg-black/5 shrink-0","aria-label":"Remove",children:e.jsx(mr,{className:"h-3.5 w-3.5",style:{color:"var(--c-text-muted)"}})})]},Fn))]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"Favorite local spots"}),e.jsx("input",{type:"text",value:Ge,onChange:Ts=>yt(Ts.target.value),placeholder:"That coffee shop on Main, Town Lake…",className:"connect-input"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"Dream neighborhood"}),e.jsx("input",{type:"text",value:tt,onChange:Ts=>ut(Ts.target.value),placeholder:"Where you'd love to live someday",className:"connect-input"})]}),e.jsxs("div",{className:"rounded-xl p-4",style:{background:"color-mix(in srgb, var(--c-accent) 8%, transparent)"},children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",style:{color:"var(--c-text)"},children:"Know someone who'd love an agent like me?"}),e.jsx("p",{className:"text-xs",style:{color:"var(--c-text-muted)"},children:"Refer a friend — up to 3."})]}),at.length<3&&e.jsxs("button",{type:"button",onClick:()=>wt(Ts=>[...Ts,{name:"",contact:""}]),className:"text-xs inline-flex items-center gap-1 px-2 py-1 rounded-md",style:{background:"var(--c-accent)",color:"var(--c-accent-text)"},children:[e.jsx(nn,{className:"h-3 w-3"})," Add"]})]}),e.jsx("div",{className:"space-y-2",children:at.map((Ts,Fn)=>e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx("input",{type:"text",value:Ts.name,onChange:An=>wt(js=>js.map((In,un)=>un===Fn?{...In,name:An.target.value}:In)),placeholder:"Their name",className:"connect-input min-w-0",style:{flex:"1 1 0%"}}),e.jsx("input",{type:"text",value:Ts.contact,onChange:An=>wt(js=>js.map((In,un)=>un===Fn?{...In,contact:An.target.value}:In)),placeholder:"Phone or email",className:"connect-input min-w-0",style:{flex:"1 1 0%"}}),e.jsx("button",{type:"button",onClick:()=>wt(An=>An.filter((js,In)=>In!==Fn)),className:"p-2 rounded-md hover:bg-black/5","aria-label":"Remove",children:e.jsx(mr,{className:"h-3.5 w-3.5",style:{color:"var(--c-text-muted)"}})})]},Fn))})]})]})}]:[],{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(Ts=>e.jsxs("button",{type:"button",onClick:()=>Ue(Ie===Ts.value?"":Ts.value),className:`p-3.5 rounded-xl border-2 text-left transition-all ${Ie===Ts.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:Ts.label}),e.jsx("span",{className:"block text-xs text-slate-500 mt-0.5",children:Ts.desc})]},Ts.value))})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:["Anything else you'd like to share? ",e.jsx("span",{className:"text-slate-400 font-normal",children:"(optional)"})]}),e.jsx("textarea",{value:Be,onChange:Ts=>je(Ts.target.value),placeholder:"Feel free to drop a note...",rows:3,className:"connect-input resize-none"})]})]})}],st=xs.length,dt=AMt(d==null?void 0:d.theme),jt=dAs(dt,(d==null?void 0:d.accent_color)||null),gt=(d==null?void 0:d.cover_image_url)||dt.defaultCover,rs=(d==null?void 0:d.headline)||"Let's stay connected",Ns=(d==null?void 0:d.subheadline)||(o!=null&&o.brokerage_name?`${o==null?void 0:o.name} · ${o.brokerage_name}`:(o==null?void 0:o.name)||""),us=["deep-luxe"].includes((d==null?void 0:d.theme)||"");return e.jsxs("div",{className:"min-h-screen connect-shell",style:jt,children:[e.jsxs(Sc,{children:[e.jsxs("title",{children:["Connect with ",(o==null?void 0:o.name)||"Agent"]}),e.jsx("meta",{name:"description",content:`${rs} — ${(o==null?void 0:o.name)||"your agent"}`}),gt&&e.jsx("meta",{property:"og:image",content:gt}),e.jsx("meta",{property:"og:title",content:`Connect with ${(o==null?void 0:o.name)||"me"}`}),e.jsx("meta",{property:"og:description",content:rs}),e.jsx("meta",{name:"twitter:card",content:"summary_large_image"})]}),e.jsx("style",{children:` .connect-shell { font-family: var(--c-body-font); color: var(--c-text); } .connect-shell h1, .connect-shell h2 { font-family: var(--c-heading-font); } .connect-input { width: 100%; padding: 0.75rem 1rem; border-radius: 0.75rem; border: 1px solid var(--c-border); background: var(--c-surface); color: var(--c-text); font-family: var(--c-body-font); font-size: 0.95rem; transition: border-color 150ms, box-shadow 150ms; } .connect-input::placeholder { color: var(--c-text-muted); opacity: 0.7; } .connect-input:focus { outline: none; border-color: var(--c-accent); box-shadow: 0 0 0 3px color-mix(in srgb, var(--c-accent) 25%, transparent); } `}),e.jsxs("div",{className:"relative w-full overflow-hidden",style:{height:"clamp(200px, 30vh, 320px)"},children:[e.jsx(_r.img,{src:gt,alt:"",initial:{scale:1.08},animate:{scale:1},transition:{duration:1.4,ease:"easeOut"},className:"absolute inset-0 w-full h-full object-cover"}),e.jsx("div",{className:"absolute inset-0",style:{background:"linear-gradient(180deg, rgba(0,0,0,0) 20%, rgba(0,0,0,0.55) 100%)"}}),e.jsxs("div",{className:"absolute inset-x-0 bottom-0 p-6 pb-16 text-center",children:[e.jsx(_r.h1,{initial:{opacity:0,y:12},animate:{opacity:1,y:0},transition:{delay:.15,duration:.6},style:{color:"#fff",fontFamily:dt.headingFont,fontWeight:500,letterSpacing:"-0.01em"},className:"text-3xl sm:text-4xl leading-tight",children:rs}),Ns&&e.jsx(_r.p,{initial:{opacity:0},animate:{opacity:.9},transition:{delay:.35,duration:.6},style:{color:"#fff"},className:"text-sm mt-2",children:Ns})]})]}),e.jsxs("div",{className:"max-w-lg mx-auto px-4 pb-12 -mt-12 relative",children:[e.jsxs(_r.div,{initial:{opacity:0,y:12},animate:{opacity:1,y:0},transition:{delay:.25},className:"text-center mb-6",children:[o!=null&&o.avatar_url?e.jsx("img",{src:o.avatar_url,alt:o.name,className:"w-24 h-24 rounded-full object-cover mx-auto shadow-xl",style:{border:"4px solid var(--c-surface)"}}):e.jsx("div",{className:"w-24 h-24 rounded-full mx-auto flex items-center justify-center shadow-xl",style:{background:dt.accent,color:dt.accentText,border:"4px solid var(--c-surface)"},children:e.jsx("span",{className:"text-3xl font-bold",children:((Bs=o==null?void 0:o.name)==null?void 0:Bs.charAt(0))||"?"})}),(o==null?void 0:o.title)&&e.jsx("p",{className:"text-sm mt-3",style:{color:"var(--c-text-muted)"},children:o.title}),((o==null?void 0:o.phone)||(o==null?void 0:o.email))&&e.jsxs("div",{className:"flex items-center justify-center gap-2 mt-3",children:[(o==null?void 0:o.phone)&&e.jsx("a",{href:`tel:${o.phone}`,className:"flex items-center justify-center w-10 h-10 rounded-full transition-opacity hover:opacity-80",style:{background:"color-mix(in srgb, var(--c-accent) 12%, transparent)",color:"var(--c-accent)"},"aria-label":"Call agent",children:e.jsx(ka,{className:"h-4 w-4"})}),(o==null?void 0:o.email)&&e.jsx("a",{href:`mailto:${o.email}`,className:"flex items-center justify-center w-10 h-10 rounded-full transition-opacity hover:opacity-80",style:{background:"color-mix(in srgb, var(--c-accent) 12%, transparent)",color:"var(--c-accent)"},"aria-label":"Email agent",children:e.jsx(pn,{className:"h-4 w-4"})})]})]}),e.jsx(_r.p,{initial:{opacity:0},animate:{opacity:1},transition:{delay:.35},className:"text-center mb-6 px-2 leading-relaxed text-sm",style:{color:"var(--c-text-muted)"},children:(d==null?void 0:d.welcome_message)||"I'd love to stay in touch — just a few quick details."}),e.jsx("div",{className:"flex gap-1.5 mb-6 px-2",children:Array.from({length:st}).map((Ts,Fn)=>e.jsx("div",{className:"h-1 flex-1 rounded-full transition-all duration-500",style:{background:Fn<=A?"var(--c-accent)":"color-mix(in srgb, var(--c-text) 12%, transparent)"}},Fn))}),e.jsxs(_r.div,{initial:{opacity:0,y:12},animate:{opacity:1,y:0},transition:{delay:.4},className:"rounded-2xl p-6 sm:p-8",style:{background:"var(--c-surface)",border:"1px solid var(--c-border)",boxShadow:us?"0 20px 40px -20px rgba(0,0,0,0.5)":"0 20px 40px -20px rgba(0,0,0,0.15)"},children:[e.jsx(Yq,{mode:"wait",children:e.jsxs(_r.div,{initial:{opacity:0,x:20},animate:{opacity:1,x:0},exit:{opacity:0,x:-20},transition:{duration:.25},children:[e.jsxs("div",{className:"mb-6",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(kn,{className:"h-4 w-4",style:{color:"var(--c-accent)"}}),e.jsx("h2",{className:"text-lg font-semibold",style:{color:"var(--c-text)"},children:xs[A].title})]}),xs[A].subtitle&&e.jsx("p",{className:"text-xs mt-1 ml-6",style:{color:"var(--c-text-muted)"},children:xs[A].subtitle})]}),xs[A].fields]},A)}),e.jsxs("div",{className:"flex justify-between mt-8",children:[A>0?e.jsx("button",{type:"button",onClick:()=>M(Ts=>Ts-1),className:"px-5 py-2.5 text-sm font-medium transition-opacity hover:opacity-70",style:{color:"var(--c-text-muted)"},children:"Back"}):e.jsx("div",{}),A{if(A===0&&!R.trim()){ae.error("Please enter your first name");return}M(Ts=>Ts+1)},className:"px-6 py-2.5 text-sm font-medium rounded-xl transition-transform hover:scale-[1.02] shadow-sm",style:{background:"var(--c-accent)",color:"var(--c-accent-text)"},children:"Continue"}):e.jsx("button",{type:"button",onClick:()=>Ft(),disabled:j,className:"px-6 py-2.5 text-sm font-medium rounded-xl transition-transform hover:scale-[1.02] shadow-sm disabled:opacity-50 flex items-center gap-2",style:{background:"var(--c-accent)",color:"var(--c-accent-text)"},children:j?e.jsxs(e.Fragment,{children:[e.jsx(Jt,{className:"h-4 w-4 animate-spin"}),"Sending..."]}):"Submit"})]}),A>0&&AM(Ts=>Ts+1),className:"text-xs transition-opacity hover:opacity-80",style:{color:"var(--c-text-muted)"},children:"Skip this step"})})]}),e.jsx("div",{className:"text-center mt-8",children:e.jsxs("div",{className:"flex items-center justify-center gap-1 text-xs",style:{color:"var(--c-text-muted)"},children:[e.jsx(Bo,{className:"h-3 w-3"}),e.jsx("span",{children:"Powered by ReLevelUp"})]})})]})]})}const Xq=()=>({trackEngagement:k.useCallback(async(t,n,r,a="view")=>{try{const{data:{user:i}}=await V.auth.getUser();if(!i)return;await V.from("content_engagement_logs").insert({user_id:i.id,resource_type:t,resource_id:n,resource_title:r,action_type:a})}catch(i){console.error("Error tracking engagement:",i)}},[])});function mG({banners:s,autoPlayInterval:t=5e3,className:n}){const[r,a]=k.useState(0),[i,l]=k.useState(!1),{trackEngagement:o}=Xq(),c=k.useCallback(p=>{o("newsletter",p.id,p.title,"click_link")},[o]),d=k.useCallback(()=>{a(p=>(p+1)%s.length)},[s.length]),u=k.useCallback(()=>{a(p=>(p-1+s.length)%s.length)},[s.length]),h=k.useCallback(p=>{a(p)},[]);if(k.useEffect(()=>{if(s.length<=1||i)return;const p=setInterval(d,t);return()=>clearInterval(p)},[s.length,i,t,d]),!s||s.length===0)return null;const m=s[r];return e.jsxs("div",{className:Ot("relative w-full overflow-hidden rounded-xl",n),onMouseEnter:()=>l(!0),onMouseLeave:()=>l(!1),children:[e.jsxs("div",{className:"relative aspect-[21/9] md:aspect-[3/1] w-full",children:[e.jsx("img",{src:m.image_url,alt:m.title,className:"w-full h-full object-cover rounded-t-xl"}),s.length>1&&e.jsxs(e.Fragment,{children:[e.jsx($,{variant:"ghost",size:"icon",className:Ot("absolute left-2 top-1/2 -translate-y-1/2 bg-black/30 hover:bg-black/50 text-white rounded-full","opacity-0 transition-opacity",i&&"opacity-100"),onClick:u,children:e.jsx(Ld,{className:"h-6 w-6"})}),e.jsx($,{variant:"ghost",size:"icon",className:Ot("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(fi,{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((p,g)=>e.jsx("button",{onClick:()=>h(g),className:Ot("w-2 h-2 rounded-full transition-all duration-300",g===r?"bg-white w-6":"bg-white/50 hover:bg-white/70"),"aria-label":`Go to slide ${g+1}`},g))})]}),e.jsxs("div",{className:"bg-foreground rounded-b-xl px-5 py-3 flex items-center justify-between gap-4",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("h2",{className:"text-sm md:text-base font-semibold text-background truncate",children:m.title}),m.description&&e.jsx("p",{className:"text-xs text-background/70 truncate",children:m.description})]}),m.link_url&&e.jsx("a",{href:m.link_url,target:"_blank",rel:"noopener noreferrer",className:"shrink-0",onClick:()=>c(m),children:e.jsx($,{size:"sm",className:"bg-primary text-primary-foreground font-semibold transition-colors hover:bg-background hover:text-foreground",children:m.link_text||"Learn More"})})]})]})}const uAs=["reserved","scheduled_for_charge","paid","payment_failed","completed"],kU=s=>!!s&&(s.access_override||uAs.includes(s.status)),Tp=(s,t="usd")=>new Intl.NumberFormat("en-US",{style:"currency",currency:t.toUpperCase(),maximumFractionDigits:s%100===0?0:2}).format(s/100),tX=s=>{if(!s||s<=0)return"full program";const t=Math.round(s/4.345);return t>=1?`full ${t}-month program`:`full ${s}-week program`},t9e=(s,t="usd",n)=>`One-time payment: ${Tp(s,t)} for the ${tX(n)}`,uWe=[{key:"full_name",label:"Full name",step:0},{key:"phone",label:"Mobile number",step:0},{key:"instagram_handle",label:"Instagram handle",step:0},{key:"city",label:"Primary city / market",step:0},{key:"service_areas",label:"Neighborhoods or areas served",step:0},{key:"years_experience",label:"Years in real estate",step:0},{key:"specialty",label:"Specialty or niche",step:0},{key:"target_audience",label:"Who they want to reach",step:1},{key:"video_comfort",label:"Comfort on camera",step:1},{key:"posting_frequency",label:"Current posting frequency",step:1},{key:"content_style",label:"Content style",step:1},{key:"personal_interests",label:"Interests / hobbies",step:1},{key:"primary_goal",label:"#1 goal for the program",step:2},{key:"topics_to_avoid",label:"Topics to avoid",step:2},{key:"timezone",label:"Time zone",step:2},{key:"consent_public_profile",label:"Content-sharing consent",step:2}],sX=s=>{var n;const t=((n=s==null?void 0:s.sales_copy)==null?void 0:n.intake)||{};return{intro:typeof t.intro=="string"?t.intro:"",hidden:Array.isArray(t.hidden)?t.hidden:[],required:Array.isArray(t.required)?t.required:[],custom:Array.isArray(t.custom)?t.custom:[]}},hAs=(s,t)=>!s.hidden.includes(t),Vct=(s,t)=>s.required.includes(t)&&!s.hidden.includes(t),ru=(s,t=!1)=>s?new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",month:"short",day:"numeric",year:"numeric",...t?{hour:"numeric",minute:"2-digit",timeZoneName:"short"}:{}}).format(new Date(s)):null,fAe=s=>{const t=Date.now(),n=s!=null&&s.enrollment_open_at?new Date(s.enrollment_open_at).getTime():null,r=s!=null&&s.enrollment_close_at?new Date(s.enrollment_close_at).getTime():null;return{notOpenYet:!!n&&n>t,closed:!!r&&rpt({queryKey:["programs"],queryFn:async()=>{const{data:s,error:t}=await V.from("programs").select("*").eq("status","published").order("is_featured",{ascending:!1}).order("sort_order",{ascending:!0});if(t)throw t;return s||[]}}),hWe=s=>pt({queryKey:["program",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await V.from("programs").select("*").eq("slug",s).maybeSingle();if(n)throw n;return t||null}}),MMt=s=>pt({queryKey:["program-seats",s],enabled:!!s,refetchInterval:6e4,queryFn:async()=>{const{data:t,error:n}=await V.rpc("program_seats_remaining",{_program_id:s});if(n)throw n;return t??0}}),mWe=()=>{const{user:s}=ks();return pt({queryKey:["program-enrollments",s==null?void 0:s.id],enabled:!!(s!=null&&s.id),queryFn:async()=>{const{data:t,error:n}=await V.from("program_enrollments").select("*").eq("user_id",s.id);if(n)throw n;return t||[]}})},fWe=s=>{const{data:t=[],...n}=mWe();return{...n,data:s&&t.find(r=>r.program_id===s)||null}},mAs=()=>{const{user:s}=ks(),t=ls();return Nt({mutationFn:async n=>{const{data:r,error:a}=await V.from("program_intake_responses").upsert({...n,user_id:s.id},{onConflict:"program_id,user_id"}).select("*").single();if(a)throw a;return r},onSuccess:()=>t.invalidateQueries({queryKey:["program-intake"]}),onError:n=>ae.error(n.message||"Could not save your answers")})},PMt=s=>{const{user:t}=ks();return pt({queryKey:["program-intake",s,t==null?void 0:t.id],enabled:!!s&&!!(t!=null&&t.id),queryFn:async()=>{const{data:n,error:r}=await V.from("program_intake_responses").select("*").eq("program_id",s).eq("user_id",t.id).maybeSingle();if(r)throw r;return n}})},fAs=()=>{const s=ls();return Nt({mutationFn:async t=>{const{data:n,error:r}=await V.rpc("program_claim_seat",{_program_id:t});if(r)throw r;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["program-enrollments"]}),s.invalidateQueries({queryKey:["program-seats"]})}})},pAs=(s,t)=>{const{user:n}=ks(),r=t||(n==null?void 0:n.id);return pt({queryKey:["program-workspace",s,r],enabled:!!s&&!!r,queryFn:async()=>{const a=r,[i,l,o,c,d,u,h,m,p,g,x]=await Promise.all([V.from("program_weeks").select("*").eq("program_id",s).order("week_number"),V.from("program_lessons").select("*").eq("program_id",s).order("sort_order"),V.from("program_resources").select("*").eq("program_id",s).order("sort_order"),V.from("program_events").select("*").eq("program_id",s).order("starts_at"),V.from("program_announcements").select("*").eq("program_id",s).order("published_at",{ascending:!1}),V.from("program_lesson_completions").select("*").eq("program_id",s).eq("user_id",a),V.from("program_weekly_progress").select("*").eq("program_id",s).eq("user_id",a).order("week_number"),V.from("program_video_logs").select("*").eq("program_id",s).eq("user_id",a).order("posted_at",{ascending:!1}),V.from("program_badge_awards").select("*").eq("program_id",s).eq("user_id",a),V.from("program_profile_analyses").select("*").eq("program_id",s).eq("user_id",a).maybeSingle(),V.from("program_member_resources").select("*").eq("program_id",s).eq("user_id",a).order("sort_order")]);return{weeks:i.data||[],lessons:l.data||[],resources:o.data||[],myResources:x.data||[],events:c.data||[],announcements:d.data||[],completions:u.data||[],progress:h.data||[],videoLogs:m.data||[],badges:p.data||[],analysis:g.data||null}}})},gAs=s=>{const{user:t}=ks(),n=ls();return Nt({mutationFn:async({lessonId:r,done:a})=>{if(a){const{error:i}=await V.from("program_lesson_completions").insert({lesson_id:r,program_id:s,user_id:t.id});if(i&&!i.message.includes("duplicate"))throw i}else{const{error:i}=await V.from("program_lesson_completions").delete().eq("lesson_id",r).eq("user_id",t.id);if(i)throw i}},onSuccess:()=>n.invalidateQueries({queryKey:["program-workspace"]}),onError:r=>ae.error(r.message||"Could not update progress")})},xAs=s=>{const{user:t}=ks(),n=ls();return Nt({mutationFn:async r=>{const{error:a}=await V.from("program_video_logs").insert({...r,program_id:s,user_id:t.id});if(a)throw a},onSuccess:()=>{ae.success("Video logged — nice work"),n.invalidateQueries({queryKey:["program-workspace"]})},onError:r=>ae.error(r.message||"Could not log the video")})},yAs=s=>{const{user:t}=ks(),n=ls();return Nt({mutationFn:async r=>{const{error:a}=await V.from("program_weekly_progress").upsert({...r,program_id:s,user_id:t.id},{onConflict:"program_id,user_id,week_number"});if(a)throw a},onSuccess:()=>{ae.success("Weekly check-in saved"),n.invalidateQueries({queryKey:["program-workspace"]})},onError:r=>ae.error(r.message||"Could not save your check-in")})},vAs=s=>{const{user:t}=ks(),n=ls();return Nt({mutationFn:async({eventId:r,optIn:a})=>{const{error:i}=await V.from("program_event_attendance").upsert({event_id:r,program_id:s,user_id:t.id,reminder_opt_in:a},{onConflict:"event_id,user_id"});if(i)throw i},onSuccess:()=>n.invalidateQueries({queryKey:["program-workspace"]}),onError:r=>ae.error(r.message||"Could not update your RSVP")})},bAs=s=>pt({queryKey:["program-discount-codes",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await V.from("program_discount_codes").select("*").eq("program_id",s).order("created_at",{ascending:!1});if(n)throw n;return t||[]}}),_As=s=>{const t=ls();return Nt({mutationFn:async n=>{const r={program_id:s,code:(n.code||"").trim().toUpperCase(),label:n.label||null,percent_off:n.percent_off??null,amount_off_cents:n.amount_off_cents??null,max_redemptions:n.max_redemptions??null,starts_at:n.starts_at||null,expires_at:n.expires_at||null,is_active:n.is_active??!0};if(n.id){const{error:a}=await V.from("program_discount_codes").update(r).eq("id",n.id);if(a)throw a}else{const{error:a}=await V.from("program_discount_codes").insert(r);if(a)throw a}},onSuccess:()=>{ae.success("Discount code saved"),t.invalidateQueries({queryKey:["program-discount-codes"]})},onError:n=>{var r;return ae.error((r=n.message)!=null&&r.includes("duplicate")?"That code already exists for this program":n.message||"Could not save the code")}})},wAs=()=>{const s=ls();return Nt({mutationFn:async t=>{const{error:n}=await V.from("program_discount_codes").delete().eq("id",t);if(n)throw n},onSuccess:()=>{ae.success("Discount code deleted"),s.invalidateQueries({queryKey:["program-discount-codes"]})},onError:t=>ae.error(t.message||"Could not delete the code")})},jAs=()=>Nt({mutationFn:async({enrollmentId:s,code:t})=>{const{data:n,error:r}=await V.rpc("program_apply_discount",{_enrollment_id:s,_code:t});if(r)throw r;const a=n;if(!(a!=null&&a.ok))throw new Error((a==null?void 0:a.error)||"That code could not be applied");return a}}),NAs=()=>Nt({mutationFn:async s=>{const{error:t}=await V.rpc("program_clear_discount",{_enrollment_id:s});if(t)throw t}}),kAs=s=>pt({queryKey:["admin-program-events",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await V.from("program_events").select("*").eq("program_id",s).order("starts_at",{ascending:!0});if(n)throw n;return t||[]}}),SAs=s=>{const t=ls();return Nt({mutationFn:async n=>{const r={program_id:s,title:(n.title||"").trim(),description:n.description||null,event_kind:n.event_kind||"mastermind",starts_at:n.starts_at,duration_minutes:n.duration_minutes??60,speaker:n.speaker||null,meeting_link:n.meeting_link||null,replay_url:n.replay_url||null,is_published:n.is_published??!0};if(n.id){const{error:a}=await V.from("program_events").update(r).eq("id",n.id);if(a)throw a}else{const{error:a}=await V.from("program_events").insert(r);if(a)throw a}},onSuccess:()=>{ae.success("Session saved"),t.invalidateQueries({queryKey:["admin-program-events"]}),t.invalidateQueries({queryKey:["program-workspace"]})},onError:n=>ae.error(n.message||"Could not save the session")})},CAs=()=>{const s=ls();return Nt({mutationFn:async t=>{const{error:n}=await V.from("program_events").delete().eq("id",t);if(n)throw n},onSuccess:()=>{ae.success("Session removed"),s.invalidateQueries({queryKey:["admin-program-events"]}),s.invalidateQueries({queryKey:["program-workspace"]})},onError:t=>ae.error(t.message||"Could not remove the session")})},AAs=s=>pt({queryKey:["admin-program-lessons",s],enabled:!!s,queryFn:async()=>{const[t,n]=await Promise.all([V.from("program_lessons").select("*").eq("program_id",s).order("sort_order"),V.from("program_weeks").select("id, week_number, title").eq("program_id",s).order("week_number")]);if(t.error)throw t.error;return{lessons:t.data||[],weeks:n.data||[]}}}),EAs=s=>{const t=ls();return Nt({mutationFn:async n=>{const r={program_id:s,week_id:n.week_id||null,title:(n.title||"").trim(),summary:n.summary||null,duration_minutes:n.duration_minutes??null,video_url:n.video_url||null,worksheet_url:n.worksheet_url||null,action_assignment:n.action_assignment||null,status:n.status||"published",publish_at:n.publish_at||null,sort_order:n.sort_order??0};if(n.id){const{error:a}=await V.from("program_lessons").update(r).eq("id",n.id);if(a)throw a}else{const{error:a}=await V.from("program_lessons").insert(r);if(a)throw a}},onSuccess:()=>{ae.success("Video saved"),t.invalidateQueries({queryKey:["admin-program-lessons"]}),t.invalidateQueries({queryKey:["program-workspace"]})},onError:n=>ae.error(n.message||"Could not save the video")})},TAs=()=>{const s=ls();return Nt({mutationFn:async t=>{const{error:n}=await V.from("program_lessons").delete().eq("id",t);if(n)throw n},onSuccess:()=>{ae.success("Video removed"),s.invalidateQueries({queryKey:["admin-program-lessons"]}),s.invalidateQueries({queryKey:["program-workspace"]})},onError:t=>ae.error(t.message||"Could not remove the video")})},IMt=s=>{if(!s)return null;const t=s.match(/(?:youtu\.be\/|youtube\.com\/(?:watch\?v=|embed\/|live\/|shorts\/))([\w-]{6,})/);if(t)return`https://www.youtube.com/embed/${t[1]}`;const n=s.match(/vimeo\.com\/(?:video\/)?(\d+)/);if(n)return`https://player.vimeo.com/video/${n[1]}`;const r=s.match(/loom\.com\/(?:share|embed)\/([\w-]+)/);return r?`https://www.loom.com/embed/${r[1]}`:null},NY=s=>!!s&&/\.(mp4|webm|mov|m4v)(\?|$)/i.test(s),LMt=[{value:"pdf",label:"PDF"},{value:"document",label:"Document"},{value:"checklist",label:"Checklist"},{value:"template_link",label:"Template"},{value:"video",label:"Video"},{value:"external",label:"Link"}],Qq="event-images",Cee=s=>{if(s.file_path){const{data:t}=V.storage.from(Qq).getPublicUrl(s.file_path);return t.publicUrl}return s.url||null},kY=async(s,t="open")=>{if(!s.file_path){const c=s.url;c&&window.open(c,"_blank","noopener,noreferrer");return}const{data:n,error:r}=await V.storage.from(Qq).download(s.file_path);if(r||!n){const c=Cee(s);c&&window.open(c,"_blank","noopener,noreferrer");return}const a=s.file_path.split("/").pop()||s.title||"resource",i=a.toLowerCase().endsWith(".pdf")||n.type==="application/pdf",l=i?new Blob([n],{type:"application/pdf"}):n,o=URL.createObjectURL(l);if(t==="open"&&i){if(!window.open(o,"_blank","noopener,noreferrer")){const d=document.createElement("a");d.href=o,d.download=a,d.click()}}else{const c=document.createElement("a");c.href=o,c.download=a,document.body.appendChild(c),c.click(),c.remove()}setTimeout(()=>URL.revokeObjectURL(o),6e4)},RMt=s=>pt({queryKey:["admin-program-resources",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await V.from("program_resources").select("*").eq("program_id",s).order("sort_order");if(n)throw n;return t||[]}}),MAs=s=>{const t=ls();return Nt({mutationFn:async n=>{const r={program_id:s,title:(n.title||"").trim(),description:n.description||null,category:(n.category||"Resources").trim()||"Resources",resource_kind:n.resource_kind||"pdf",url:n.url||null,file_path:n.file_path||null,status:n.status||"published",sort_order:n.sort_order??0};if(n.id){const{error:a}=await V.from("program_resources").update(r).eq("id",n.id);if(a)throw a}else{const{error:a}=await V.from("program_resources").insert(r);if(a)throw a}},onSuccess:()=>{ae.success("Resource saved"),t.invalidateQueries({queryKey:["admin-program-resources"]}),t.invalidateQueries({queryKey:["program-workspace"]})},onError:n=>ae.error(n.message||"Could not save the resource")})},PAs=()=>{const s=ls();return Nt({mutationFn:async t=>{t.file_path&&await V.storage.from(Qq).remove([t.file_path]);const{error:n}=await V.from("program_resources").delete().eq("id",t.id);if(n)throw n},onSuccess:()=>{ae.success("Resource removed"),s.invalidateQueries({queryKey:["admin-program-resources"]}),s.invalidateQueries({queryKey:["program-workspace"]})},onError:t=>ae.error(t.message||"Could not remove the resource")})},IAs=(s,t)=>pt({queryKey:["admin-program-member-resources",s,t],enabled:!!s&&!!t,queryFn:async()=>{const{data:n,error:r}=await V.from("program_member_resources").select("*").eq("program_id",s).eq("user_id",t).order("sort_order");if(r)throw r;return n||[]}}),LAs=(s,t)=>{const n=ls(),{user:r}=ks();return Nt({mutationFn:async a=>{const i={program_id:s,user_id:t,uploaded_by:(r==null?void 0:r.id)??null,title:(a.title||"").trim(),description:a.description||null,category:(a.category||"Personal").trim()||"Personal",resource_kind:a.resource_kind||"pdf",url:a.url||null,file_path:a.file_path||null,status:a.status||"published",sort_order:a.sort_order??0};if(a.id){const{error:l}=await V.from("program_member_resources").update(i).eq("id",a.id);if(l)throw l}else{const{error:l}=await V.from("program_member_resources").insert(i);if(l)throw l}},onSuccess:()=>{ae.success("Personal resource saved"),n.invalidateQueries({queryKey:["admin-program-member-resources"]}),n.invalidateQueries({queryKey:["program-workspace"]})},onError:a=>ae.error(a.message||"Could not save the resource")})},RAs=()=>{const s=ls();return Nt({mutationFn:async t=>{t.file_path&&await V.storage.from(Qq).remove([t.file_path]);const{error:n}=await V.from("program_member_resources").delete().eq("id",t.id);if(n)throw n},onSuccess:()=>{ae.success("Personal resource removed"),s.invalidateQueries({queryKey:["admin-program-member-resources"]}),s.invalidateQueries({queryKey:["program-workspace"]})},onError:t=>ae.error(t.message||"Could not remove the resource")})},DAs=s=>{const{user:t}=ks();return pt({queryKey:["program-interest",s,t==null?void 0:t.id],enabled:!!s&&!!(t!=null&&t.id),queryFn:async()=>{const{data:n,error:r}=await V.from("program_interest").select("*").eq("program_id",s).eq("user_id",t.id).maybeSingle();if(r)throw r;return n||null}})},OAs=s=>{const t=ls(),{user:n}=ks();return Nt({mutationFn:async r=>{if(!(n!=null&&n.id)||!s)throw new Error("You need to be signed in.");if(r){const{error:a}=await V.from("program_interest").upsert({program_id:s,user_id:n.id,source:"program_detail"},{onConflict:"program_id,user_id"});if(a)throw a}else{const{error:a}=await V.from("program_interest").delete().eq("program_id",s).eq("user_id",n.id);if(a)throw a}return r},onSuccess:r=>{ae.success(r?"You're on the list — we'll email you when enrollment opens.":"Removed from the notify list"),t.invalidateQueries({queryKey:["program-interest"]}),t.invalidateQueries({queryKey:["admin-program-interest"]})},onError:r=>ae.error(r.message||"Could not update your notify preference")})},FAs=s=>pt({queryKey:["admin-program-interest",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await V.from("program_interest").select("*").eq("program_id",s).order("created_at",{ascending:!1});if(n)throw n;const r=t||[];if(!r.length)return[];const a=Array.from(new Set(r.map(o=>o.user_id))),{data:i}=await V.from("profiles").select("id, name, email, phone, brokerage_name").in("id",a),l=new Map((i||[]).map(o=>[o.id,o]));return r.map(o=>{const c=l.get(o.user_id)||{};return{...o,full_name:c.name??null,email:c.email??null,phone:c.phone??null,brokerage:c.brokerage_name??null}})}}),zAs=s=>{if(!s)return null;const t=new Intl.DateTimeFormat("en-CA",{timeZone:"America/New_York",year:"numeric",month:"2-digit",day:"2-digit"}),n=r=>{const[a,i,l]=t.format(r).split(/[-/T]/).map(Number);return Date.UTC(a,i-1,l)};return Math.round((n(new Date(s))-n(new Date))/864e5)},BAs=()=>{const{data:s=[]}=TMt(),{data:t=[]}=mWe(),n=new Set(t.filter(kU).map(a=>a.program_id)),r=s.filter(a=>n.has(a.id));return r.length===0?null:e.jsx("div",{className:"mb-6 space-y-3",children:r.map(a=>{const i=zAs(a.kickoff_at),l=i===null?null:i>1?`Kicks off in ${i} days`:i===1?"Kicks off tomorrow":i===0?"Kicks off today":"In progress";return e.jsxs("div",{className:"flex flex-col gap-4 rounded-2xl border border-primary/30 bg-gradient-to-r from-primary/12 via-primary/5 to-background p-5 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"flex h-12 w-12 shrink-0 items-center justify-center rounded-xl bg-primary/15",children:e.jsx(v0,{className:"h-6 w-6 text-primary"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("h3",{className:"text-lg font-semibold leading-tight",children:a.name}),l&&e.jsx(qe,{variant:"secondary",children:l})]}),e.jsxs("p",{className:"mt-0.5 text-sm text-muted-foreground",children:[a.kickoff_at?`Starts ${ru(a.kickoff_at)} · `:"","Your program dashboard is live — lessons, resources and sessions inside."]})]})]}),e.jsx($,{asChild:!0,size:"lg",className:"shrink-0",children:e.jsxs(nr,{to:`/programs/${a.slug}/workspace`,children:["Open program dashboard",e.jsx(xi,{className:"ml-1.5 h-4 w-4"})]})})]},a.id)})})};function $As(s){return"EST"}function nX(s){const n=new Intl.DateTimeFormat("en-US",{hour:"numeric",minute:"2-digit",hour12:!0,timeZone:"America/New_York"}).format(s),r=$As();return`${n} ${r}`}function iD(s){const t=new Date,n=new Date(s),r=zot(n,-15),a=zot(n,30);return t>a?"ended":$N(t,{start:n,end:a})?"live":$N(t,{start:r,end:n})?"starting_soon":"upcoming"}function pWe(s){const t=iD(s);return t==="starting_soon"||t==="live"}const UAs=pWe,qAs=({events:s,registrations:t,onNavigateToEvents:n})=>{const[r,a]=k.useState(new Date);k.useEffect(()=>{const p=setInterval(()=>{a(new Date)},3e4);return()=>clearInterval(p)},[]);const i=s.filter(p=>pWe(p.event_date));if(i.length===0)return null;const l=i[0],o=iD(l.event_date),c=t.find(p=>p.event_id===l.id),d=(c==null?void 0:c.zoom_join_url)||l.zoom_link,u=!!c,h=o==="live",m=h?{container:"from-red-500/10 via-red-500/5 to-primary/10 border-red-500/30",pulse:"from-red-500/5",indicator:"bg-red-500",text:"text-red-500",button:"bg-red-500 hover:bg-red-600",outlineButton:"border-red-500/50 text-red-500 hover:bg-red-500/10"}:{container:"from-amber-500/10 via-amber-500/5 to-primary/10 border-amber-500/30",pulse:"from-amber-500/5",indicator:"bg-amber-500",text:"text-amber-500",button:"bg-amber-500 hover:bg-amber-600",outlineButton:"border-amber-500/50 text-amber-500 hover:bg-amber-500/10"};return e.jsxs("div",{className:`relative mb-8 overflow-hidden rounded-xl bg-gradient-to-r ${m.container} border`,children:[e.jsx("div",{className:`absolute inset-0 bg-gradient-to-r ${m.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 ${m.indicator} opacity-75`}),e.jsx("span",{className:`relative flex h-3 w-3 rounded-full ${m.indicator}`})]}),e.jsx("div",{className:`flex items-center gap-2 ${m.text} font-bold text-sm uppercase tracking-wider`,children:h?e.jsxs(e.Fragment,{children:[e.jsx(Cy,{className:"h-4 w-4"}),"Live Now"]}):e.jsxs(e.Fragment,{children:[e.jsx(sa,{className:"h-4 w-4"}),"Starting Soon"]})})]}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h3",{className:"font-semibold text-lg text-foreground line-clamp-1",children:l.title}),e.jsx("p",{className:"text-sm text-muted-foreground",children:h?`Started at ${nX(new Date(l.event_date))}`:`Starts at ${nX(new Date(l.event_date))}`})]}),e.jsx("div",{className:"flex items-center gap-2",children:u?e.jsxs($,{onClick:()=>window.open(d,"_blank"),className:`${m.button} text-white gap-2`,children:[e.jsx(Ir,{className:"h-4 w-4"}),h?"Join Now":"Join When Live"]}):e.jsxs($,{variant:"outline",onClick:n,className:`${m.outlineButton} gap-2`,children:[e.jsx(Xn,{className:"h-4 w-4"}),"Register & Join"]})})]})})]})};function dx(){const{user:s}=ks(),{data:t,isLoading:n}=pt({queryKey:["gmail-integration",s==null?void 0:s.id],enabled:!!(s!=null&&s.id),queryFn:async()=>{const{data:h,error:m}=await V.from("gmail_integrations").select("*").eq("user_id",s.id).maybeSingle();if(m)throw m;return h}}),{data:r,isLoading:a}=pt({queryKey:["user-verified-ses-sender",s==null?void 0:s.id],enabled:!!s,staleTime:60*1e3,queryFn:async()=>{const{data:h}=await V.from("user_verified_senders").select("email, status").eq("user_id",s.id).eq("status","verified").order("verified_at",{ascending:!1}).limit(1).maybeSingle();return h}}),i=!!(t!=null&&t.is_active),l=(t==null?void 0:t.gmail_email)||null,o=!!(r!=null&&r.email),c=(r==null?void 0:r.email)||null;return{isGmailConnected:i,gmailEmail:l,hasVerifiedSes:o,sesEmail:c,canSendEmail:i||o,sendMethod:i?"gmail":o?"mass_email":"none",isLoading:n||a}}function VAs(){var A;const{user:s}=ks(),{isGmailConnected:t,hasVerifiedSes:n,isLoading:r}=dx(),a=rA(),i=a.isMember&&!!((A=a.pkg)!=null&&A.includes_coaching),l=a.isMember&&!i,[o,c]=k.useState(!1),[d,u]=k.useState(!1);k.useEffect(()=>{s!=null&&s.id&&V.from("onboarding_checklist_dismissed").select("id").eq("user_id",s.id).maybeSingle().then(({data:M})=>{c(!!M),u(!0)})},[s==null?void 0:s.id]);const{data:h,isLoading:m}=pt({queryKey:["new-agent-onboarding",s==null?void 0:s.id],enabled:!!(s!=null&&s.id),staleTime:3e4,queryFn:async()=>{const[M,I,P,R,O,B]=await Promise.all([V.from("profiles").select("avatar_url, phone, bio, name").eq("id",s.id).maybeSingle(),V.from("innercircle_contacts").select("id",{count:"exact",head:!0}).eq("owner_user_id",s.id),V.from("event_registrations").select("id",{count:"exact",head:!0}).eq("user_id",s.id),V.from("community_posts").select("id",{count:"exact",head:!0}).eq("user_id",s.id),V.from("events").select("id, title, event_date, image_url").eq("is_published",!0).gte("event_date",new Date().toISOString()).or("title.ilike.%onboarding%,title.ilike.%new member%,title.ilike.%welcome%,description.ilike.%new member onboarding%").order("event_date",{ascending:!0}).limit(1).maybeSingle(),V.from("coaching_assignments").select("id").eq("agent_id",s.id).eq("status","active").limit(1)]),U=(B.data||[]).map(me=>me.id);let G=!1;if(U.length){const{count:me}=await V.from("coaching_sessions").select("id",{count:"exact",head:!0}).in("assignment_id",U);G=(me||0)>0}const H=M.data,Y=!!(H!=null&&H.avatar_url&&(H!=null&&H.phone)&&(H!=null&&H.bio)),se=I.count||0,ee=(P.count||0)>0,oe=R.count||0;return{profile:H,profileComplete:Y,contactsCount:se,contactsComplete:se>=5,eventsRegistered:ee,communityComplete:oe>0,nextOnboardingEvent:O.data||null,coachingBooked:G}}}),p=t||n,g=[{id:"profile",complete:!!(h!=null&&h.profileComplete)},{id:"email",complete:p},{id:"contacts",complete:!!(h!=null&&h.contactsComplete)},{id:"event",complete:!!(h!=null&&h.eventsRegistered)},{id:"community",complete:!!(h!=null&&h.communityComplete)}],x=l?g.filter(M=>M.id!=="community"&&M.id!=="event"):g;i&&x.push({id:"coaching",complete:!!(h!=null&&h.coachingBooked)});const y=x.filter(M=>M.complete).length,v=x.length;return{steps:x,completedCount:y,totalCount:v,allComplete:y===v,dismissed:o,dismiss:async()=>{s!=null&&s.id&&(c(!0),await V.from("onboarding_checklist_dismissed").insert({user_id:s.id}))},reopen:async()=>{s!=null&&s.id&&(c(!1),await V.from("onboarding_checklist_dismissed").delete().eq("user_id",s.id))},data:h,isGmailConnected:t,hasVerifiedSes:n,loading:m||r||!d||a.isLoading}}const HAs={profile:{title:"Complete Your Profile",description:"Add your headshot, phone, and short bio so contacts recognize you.",icon:el,accent:"from-[#2a4c64] to-[#406E71]",cta:"Edit Profile"},email:{title:"Set Up Email Sending",description:"Connect Gmail (recommended) or verify a Mass Email sender to send from your address.",icon:pn,accent:"from-[#406E71] to-[#5b9ea1]",cta:"Connect Email"},contacts:{title:"Add Your First Contacts",description:"Import your database or add contacts one at a time to start building your Inner Circle.",icon:Xn,accent:"from-[#c9a84c] to-[#e8c76f]",cta:"Add Contacts"},event:{title:"Register for New Member Onboarding",description:"Join our live LevelUp onboarding session to hit the ground running.",icon:ha,accent:"from-[#8b5cf6] to-[#a78bfa]",cta:"Register"},community:{title:"Say Hi in the Community",description:"Introduce yourself and connect with other LevelUp agents.",icon:bo,accent:"from-[#ec4899] to-[#f472b6]",cta:"Visit Community"},coaching:{title:"Schedule Your Coaching Session",description:"Book your first 1:1 session with your LevelUp coach.",icon:Bm,accent:"from-[#0ea5e9] to-[#38bdf8]",cta:"Book Session"}};function GAs(){var x,y;const s=Jn(),{user:t}=ks(),{steps:n,completedCount:r,totalCount:a,allComplete:i,dismissed:l,dismiss:o,data:c,loading:d}=VAs(),[u,h]=k.useState(!0);if(d||l||i)return null;const m=(((x=c==null?void 0:c.profile)==null?void 0:x.name)||((y=t==null?void 0:t.user_metadata)==null?void 0:y.name)||"there").split(" ")[0],p=r/a*100,g=async v=>{switch(v){case"profile":s("/profile");break;case"email":s("/mission-control/integrations");break;case"contacts":s("/mission-control/contacts");break;case"event":{const _=c==null?void 0:c.nextOnboardingEvent;if(!_){s("/events");return}if(!(t!=null&&t.id))return;const{error:j}=await V.from("event_registrations").insert({user_id:t.id,event_id:_.id});j&&!String(j.message).toLowerCase().includes("duplicate")?(ae.error("Could not register — opening events page."),s("/events")):ae.success(`You're registered for ${_.title}!`);break}case"community":s("/community");break;case"coaching":s("/my-coach");break}};return e.jsxs(we,{className:"mb-6 overflow-hidden border-0 shadow-lg",children:[e.jsxs("div",{className:"relative bg-gradient-to-br from-[#2a4c64] via-[#345a75] to-[#406E71] p-6 md:p-8 text-white",children:[e.jsx("button",{onClick:o,className:"absolute top-4 right-4 p-1.5 rounded-full hover:bg-white/10 transition","aria-label":"Dismiss",children:e.jsx(mr,{className:"h-4 w-4"})}),e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"hidden sm:flex h-12 w-12 rounded-xl bg-white/15 backdrop-blur items-center justify-center shrink-0",children:e.jsx(kn,{className:"h-6 w-6 text-[#f5f0e0]"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("h2",{className:"text-xl md:text-2xl font-bold",children:["Welcome to LevelUp, ",m,"! 👋"]}),e.jsx("p",{className:"text-white/80 mt-1 text-sm md:text-base",children:"Let's get you set up in under 10 minutes."}),e.jsxs("div",{className:"mt-4 max-w-md",children:[e.jsxs("div",{className:"flex items-center justify-between text-xs mb-1.5 text-white/90",children:[e.jsxs("span",{className:"font-medium",children:[r," of ",a," complete"]}),e.jsxs("span",{children:[a-r," steps left"]})]}),e.jsx(ho,{value:p,className:"h-2 bg-white/20 [&>div]:bg-[#f5f0e0]"})]}),e.jsxs("div",{className:"mt-5 flex flex-wrap items-center gap-3",children:[e.jsxs($,{onClick:()=>h(!0),className:"bg-[#f5f0e0] text-[#2a4c64] hover:bg-white font-semibold",children:["Continue Setup ",e.jsx(xi,{className:"h-4 w-4 ml-1.5"})]}),e.jsx("button",{onClick:()=>h(v=>!v),className:"text-sm text-white/80 hover:text-white flex items-center gap-1",children:u?e.jsxs(e.Fragment,{children:["Hide steps ",e.jsx(Ny,{className:"h-4 w-4"})]}):e.jsxs(e.Fragment,{children:["Show steps ",e.jsx(Go,{className:"h-4 w-4"})]})})]})]})]})]}),u&&e.jsx(De,{className:"p-4 md:p-6 bg-gradient-to-b from-background to-muted/30",children:e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:n.map(v=>{const _=HAs[v.id],j=_.icon;return e.jsx("div",{className:Ot("relative rounded-xl border p-4 transition-all group",v.complete?"bg-muted/40 border-muted":"bg-card hover:shadow-md hover:border-primary/40 cursor-pointer"),onClick:()=>!v.complete&&g(v.id),children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:Ot("h-10 w-10 rounded-lg flex items-center justify-center shrink-0 bg-gradient-to-br text-white",v.complete?"from-emerald-500 to-emerald-600":_.accent),children:v.complete?e.jsx(Gr,{className:"h-5 w-5"}):e.jsx(j,{className:"h-5 w-5"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("h3",{className:Ot("font-semibold text-sm",v.complete&&"text-muted-foreground line-through"),children:_.title})}),e.jsx("p",{className:Ot("text-xs text-muted-foreground mt-1 leading-relaxed",v.complete&&"line-through"),children:_.description}),v.id==="event"&&!v.complete&&(c==null?void 0:c.nextOnboardingEvent)&&e.jsxs("div",{className:"mt-2 text-xs font-medium text-primary",children:[new Date(c.nextOnboardingEvent.event_date).toLocaleDateString("en-US",{weekday:"short",month:"short",day:"numeric",hour:"numeric",minute:"2-digit",timeZone:"America/New_York"})," ","ET"]}),!v.complete&&e.jsxs($,{size:"sm",variant:"ghost",className:"mt-2 h-7 px-2 -ml-2 text-primary hover:text-primary hover:bg-primary/10",onClick:C=>{C.stopPropagation(),g(v.id)},children:[_.cta," ",e.jsx(xi,{className:"h-3 w-3 ml-1"})]})]}),v.complete&&e.jsx("span",{className:"text-xs font-medium text-emerald-600 shrink-0",children:"✓ Done"})]})},v.id)})})})]})}function WAs(s){return pt({queryKey:["brokerage-content-categories",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await V.from("brokerage_content_categories").select("*").eq("brokerage_id",s).order("sort_order");if(n)throw n;return t},enabled:!!s})}function KAs(s,t){return pt({queryKey:["brokerage-content",s,t],queryFn:async()=>{if(!s)return[];let n=V.from("brokerage_content").select("*, category:brokerage_content_categories(*)").eq("brokerage_id",s).order("created_at",{ascending:!1});t&&(n=n.eq("category_id",t));const{data:r,error:a}=await n;if(a)throw a;return r},enabled:!!s})}function YAs(s,t=4){return pt({queryKey:["brokerage-content-recent",s,t],queryFn:async()=>{if(!s)return[];const{data:n,error:r}=await V.from("brokerage_content").select("*, category:brokerage_content_categories(*)").eq("brokerage_id",s).order("created_at",{ascending:!1}).limit(t);if(r)throw r;return n},enabled:!!s})}function ZAs(s){const t=ls();return Nt({mutationFn:async n=>{const{data:r,error:a}=await V.from("brokerage_content").insert(n).select().single();if(a)throw a;return r},onSuccess:()=>{t.invalidateQueries({queryKey:["brokerage-content"]}),t.invalidateQueries({queryKey:["brokerage-content-recent"]})}})}function XAs(){const s=ls();return Nt({mutationFn:async t=>{const{error:n}=await V.from("brokerage_content").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["brokerage-content"]}),s.invalidateQueries({queryKey:["brokerage-content-recent"]})}})}function QAs(s){const t=ls();return Nt({mutationFn:async n=>{const{data:r,error:a}=await V.from("brokerage_content_categories").insert({...n,brokerage_id:s}).select().single();if(a)throw a;return r},onSuccess:()=>{t.invalidateQueries({queryKey:["brokerage-content-categories"]})}})}function JAs(){const s=ls();return Nt({mutationFn:async t=>{const{error:n}=await V.from("brokerage_content_categories").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["brokerage-content-categories"]})}})}function eEs(s){const t=ls();return Nt({mutationFn:async()=>{const n=[{name:"Events",icon:"📅",sort_order:0,is_default:!0,brokerage_id:s},{name:"Videos",icon:"🎥",sort_order:1,is_default:!0,brokerage_id:s},{name:"Documents",icon:"📄",sort_order:2,is_default:!0,brokerage_id:s},{name:"Resources",icon:"🔗",sort_order:3,is_default:!0,brokerage_id:s},{name:"Graphics",icon:"🎨",sort_order:4,is_default:!0,brokerage_id:s}],{error:r}=await V.from("brokerage_content_categories").upsert(n,{onConflict:"brokerage_id,name"});if(r)throw r},onSuccess:()=>{t.invalidateQueries({queryKey:["brokerage-content-categories"]})}})}const tEs={video:pu,pdf:ea,link:pd,event:ha,graphic:gd},sEs={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 nEs(s){if(!s)return null;try{const t=new URL(s),n=t.hostname.replace("www.","");let r=null;if(n==="youtube.com"||n==="m.youtube.com"?r=t.searchParams.get("v"):n==="youtu.be"&&(r=t.pathname.slice(1)),r)return`https://img.youtube.com/vi/${r}/hqdefault.jpg`}catch{}return null}function rEs(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 aEs({item:s}){const t=Jn(),n=tEs[s.content_type]||pd,r=sEs[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"?nEs(s.url):null);k.useEffect(()=>{l||!s.url||s.content_type!=="video"||!rEs(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(we,{className:"group cursor-pointer overflow-hidden transition-all duration-200 hover:shadow-lg hover:border-primary/30",onClick:()=>t(`/brokerage-content/${s.id}`),children:[o?e.jsx("div",{className:"aspect-video bg-muted/50 overflow-hidden",children:e.jsx("img",{src:o,alt:s.title,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-300",referrerPolicy:"no-referrer"})}):e.jsx("div",{className:"aspect-video bg-muted/20 flex items-center justify-center",children:e.jsx(n,{className:"h-8 w-8 text-muted-foreground/30"})}),e.jsxs(De,{className:"p-3",children:[e.jsx("div",{className:"flex items-center gap-1.5 mb-1.5",children:e.jsxs(qe,{variant:"secondary",className:`text-[10px] px-1.5 py-0 ${r}`,children:[e.jsx(n,{className:"h-3 w-3 mr-0.5"}),s.content_type]})}),e.jsx("h4",{className:"font-medium text-sm text-foreground truncate group-hover:text-primary transition-colors",children:s.title}),s.content_type==="event"&&s.event_date&&e.jsx("p",{className:"text-xs text-primary mt-1 font-medium",children:Ys(new Date(s.event_date),"MMM d · h:mm a")})]})]})}function iEs(){const{brokerageId:s}=ks(),t=Jn(),{data:n=[],isLoading:r}=YAs(s,4);return!s||r||n.length===0?null:e.jsxs("section",{className:"mb-10",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Gi,{className:"h-5 w-5 text-primary"}),e.jsx("h3",{className:"text-lg font-semibold text-foreground",children:"Brokerage Content"})]}),e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>t("/brokerage-content"),className:"gap-1 text-muted-foreground hover:text-foreground",children:["View All ",e.jsx(xi,{className:"h-4 w-4"})]})]}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4",children:n.map(a=>e.jsx(aEs,{item:a},a.id))})]})}const DMt=()=>pt({queryKey:["listing-exchange-enabled"],queryFn:async()=>{const{data:s,error:t}=await V.from("feature_flags").select("enabled").eq("key","listing_exchange_enabled").maybeSingle();if(t)throw t;return(s==null?void 0:s.enabled)??!1}}),OMt=s=>{const{user:t,brokerageId:n}=ks();return pt({queryKey:["listings",s,n],queryFn:async()=>{let r=V.from("listings").select(` *, photos:listing_photos(*), agent:profiles!listings_agent_id_fkey(id, name, email, brokerage_id, brokerage:brokerages(name)) `).eq("is_approved",!0).eq("is_public",!0);s!=null&&s.status&&(r=r.eq("status",s.status)),s!=null&&s.propertyType&&(r=r.eq("property_type",s.propertyType)),s!=null&&s.city&&(r=r.ilike("city",`%${s.city}%`)),s!=null&&s.minPrice&&(r=r.gte("price",s.minPrice)),s!=null&&s.maxPrice&&(r=r.lte("price",s.maxPrice)),s!=null&&s.openToReferrals&&(r=r.eq("open_to_referrals",!0));const{data:a,error:i}=await r;if(i)throw i;let l=a||[];if(n){const{data:o}=await V.from("profiles").select("id").eq("brokerage_id",n);if(o&&o.length>0){const c=o.map(h=>h.id);let d=V.from("listings").select(` *, photos:listing_photos(*), agent:profiles!listings_agent_id_fkey(id, name, email, brokerage_id, brokerage:brokerages(name)) `).eq("is_approved",!0).eq("share_with_brokerage",!0).eq("is_public",!1).eq("site_only",!1).in("agent_id",c);s!=null&&s.status&&(d=d.eq("status",s.status)),s!=null&&s.propertyType&&(d=d.eq("property_type",s.propertyType)),s!=null&&s.city&&(d=d.ilike("city",`%${s.city}%`)),s!=null&&s.minPrice&&(d=d.gte("price",s.minPrice)),s!=null&&s.maxPrice&&(d=d.lte("price",s.maxPrice)),s!=null&&s.openToReferrals&&(d=d.eq("open_to_referrals",!0));const{data:u}=await d;if(u){const h=new Set(l.map(p=>p.id)),m=u.filter(p=>!h.has(p.id));l=[...l,...m]}}}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}})},FMt=()=>{const{user:s}=ks();return pt({queryKey:["my-listings",s==null?void 0:s.id],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await V.from("listings").select(` *, photos:listing_photos(*) `).eq("agent_id",s.id).order("created_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})},gWe=s=>{const{user:t}=ks();return pt({queryKey:["listing",s],queryFn:async()=>{const{data:n,error:r}=await V.from("listings").select(` *, photos:listing_photos(*), agent:profiles!listings_agent_id_fkey(id, name, email, brokerage_id, brokerage:brokerages(name)), video:agent_videos!listings_video_id_fkey(id, playback_url, thumbnail_url, title, duration_seconds) `).eq("id",s).single();if(r)throw r;return t&&await V.from("listing_views").insert({listing_id:s,viewer_id:t.id}),n},enabled:!!s})},oEs=()=>{const s=ls(),{user:t}=ks();return Nt({mutationFn:async n=>{if(!t)throw new Error("Not authenticated");const{data:r,error:a}=await V.from("listings").insert({...n,agent_id:t.id}).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["listings"]}),s.invalidateQueries({queryKey:["my-listings"]})}})},lEs=()=>{const s=ls();return Nt({mutationFn:async({agentId:t,...n})=>{const{data:r,error:a}=await V.from("listings").insert({...n,agent_id:t}).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["listings"]}),s.invalidateQueries({queryKey:["my-listings"]}),s.invalidateQueries({queryKey:["brokerage-listings"]})}})},cEs=()=>{const s=ls();return Nt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await V.from("listings").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:t=>{s.invalidateQueries({queryKey:["listings"]}),s.invalidateQueries({queryKey:["my-listings"]}),s.invalidateQueries({queryKey:["listing",t.id]})}})},zMt=()=>{const s=ls();return Nt({mutationFn:async t=>{const{error:n}=await V.from("listings").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["listings"]}),s.invalidateQueries({queryKey:["my-listings"]})}})},dEs=()=>{const s=ls();return Nt({mutationFn:async({listingId:t,photoUrl:n,isPrimary:r=!1})=>{const{data:a,error:i}=await V.from("listing_photos").insert({listing_id:t,photo_url:n,is_primary:r}).select().single();if(i)throw i;return a},onSuccess:t=>{s.invalidateQueries({queryKey:["listing",t.listing_id]}),s.invalidateQueries({queryKey:["my-listings"]})}})},uEs=()=>{const s=ls();return Nt({mutationFn:async({photoId:t,listingId:n})=>{const{error:r}=await V.from("listing_photos").delete().eq("id",t);if(r)throw r;return n},onSuccess:t=>{s.invalidateQueries({queryKey:["listing",t]}),s.invalidateQueries({queryKey:["my-listings"]})}})},hEs=()=>{const s=ls();return Nt({mutationFn:async({photos:t})=>{var i;const n=t.map(l=>V.from("listing_photos").update({sort_order:l.sort_order,is_primary:l.is_primary}).eq("id",l.id)),a=(i=(await Promise.all(n)).find(l=>l.error))==null?void 0:i.error;if(a)throw a;return t},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["listing"]}),s.invalidateQueries({queryKey:["my-listings"]})}})},mEs=()=>{const s=ls();return Nt({mutationFn:async({photoId:t,listingId:n})=>{const{error:r}=await V.from("listing_photos").update({is_primary:!1}).eq("listing_id",n);if(r)throw r;const{error:a}=await V.from("listing_photos").update({is_primary:!0}).eq("id",t);if(a)throw a;return n},onSuccess:t=>{s.invalidateQueries({queryKey:["listing",t]}),s.invalidateQueries({queryKey:["my-listings"]})}})},fEs=()=>{const{user:s}=ks();return pt({queryKey:["saved-listings",s==null?void 0:s.id],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await V.from("listing_saves").select(` *, listing:listings( *, photos:listing_photos(*), agent:profiles!listings_agent_id_fkey(id, name, email, brokerage_id) ) `).eq("agent_id",s.id);if(n)throw n;return t},enabled:!!s})},BMt=()=>{const s=ls(),{user:t}=ks();return Nt({mutationFn:async n=>{if(!t)throw new Error("Not authenticated");const{data:r}=await V.from("listing_saves").select("id").eq("listing_id",n).eq("agent_id",t.id).maybeSingle();return r?(await V.from("listing_saves").delete().eq("id",r.id),{saved:!1}):(await V.from("listing_saves").insert({listing_id:n,agent_id:t.id}),{saved:!0})},onSuccess:()=>{s.invalidateQueries({queryKey:["saved-listings"]}),s.invalidateQueries({queryKey:["listings"]})}})},$Mt=s=>{const{user:t}=ks();return pt({queryKey:["listing-saved",s,t==null?void 0:t.id],queryFn:async()=>{if(!t)return!1;const{data:n}=await V.from("listing_saves").select("id").eq("listing_id",s).eq("agent_id",t.id).maybeSingle();return!!n},enabled:!!t&&!!s})},pEs=()=>{const s=ls(),{user:t}=ks();return Nt({mutationFn:async n=>{if(!t)throw new Error("Not authenticated");const{data:r}=await V.from("listing_follows").select("id").eq("listing_id",n).eq("agent_id",t.id).maybeSingle();return r?(await V.from("listing_follows").delete().eq("id",r.id),{following:!1}):(await V.from("listing_follows").insert({listing_id:n,agent_id:t.id}),{following:!0})},onSuccess:()=>{s.invalidateQueries({queryKey:["listing-following"]})}})},gEs=s=>{const{user:t}=ks();return pt({queryKey:["listing-following",s,t==null?void 0:t.id],queryFn:async()=>{if(!t)return!1;const{data:n}=await V.from("listing_follows").select("id").eq("listing_id",s).eq("agent_id",t.id).maybeSingle();return!!n},enabled:!!t&&!!s})},xEs=()=>{const{user:s}=ks();return Nt({mutationFn:async({listingId:t,shareType:n})=>{if(!s)throw new Error("Not authenticated");const{error:r}=await V.from("listing_shares").insert({listing_id:t,sharing_agent_id:s.id,share_type:n});if(r)throw r}})},yEs=()=>{const{user:s}=ks();return pt({queryKey:["my-referrals",s==null?void 0:s.id],queryFn:async()=>{if(!s)return{sent:[],received:[]};const[t,n]=await Promise.all([V.from("listing_referrals").select(` *, listing:listings(*,photos:listing_photos(*)) `).eq("sender_agent_id",s.id).order("created_at",{ascending:!1}),V.from("listing_referrals").select(` *, sender:profiles!listing_referrals_sender_agent_id_fkey(id, name, email), listing:listings(*,photos:listing_photos(*)) `).eq("listing_agent_id",s.id).order("created_at",{ascending:!1})]);return{sent:t.data||[],received:n.data||[]}},enabled:!!s})},vEs=()=>{const s=ls(),{user:t}=ks();return Nt({mutationFn:async({listingId:n,listingAgentId:r,buyerName:a,buyerType:i,notes:l})=>{if(!t)throw new Error("Not authenticated");const{data:o,error:c}=await V.from("listing_referrals").insert({listing_id:n,sender_agent_id:t.id,listing_agent_id:r,buyer_name:a,buyer_type:i,notes:l}).select().single();if(c)throw c;return o},onSuccess:()=>{s.invalidateQueries({queryKey:["my-referrals"]})}})},bEs=()=>pt({queryKey:["listing-leaderboard"],queryFn:async()=>{const{data:s}=await V.from("listing_shares").select("sharing_agent_id, profiles!listing_shares_agent_id_fkey(name)").order("created_at",{ascending:!1}),t=new Map;s==null||s.forEach(l=>{var d;const o=l.sharing_agent_id;if(!o)return;const c=t.get(o);c?c.count++:t.set(o,{name:((d=l.profiles)==null?void 0:d.name)||"Unknown",count:1})});const n=Array.from(t.entries()).map(([l,o])=>({agentId:l,...o})).sort((l,o)=>o.count-l.count).slice(0,10),{data:r}=await V.from("listings").select("agent_id, agent:profiles!listings_agent_id_fkey(name)").eq("is_approved",!0),a=new Map;r==null||r.forEach(l=>{var c;const o=a.get(l.agent_id);o?o.count++:a.set(l.agent_id,{name:((c=l.agent)==null?void 0:c.name)||"Unknown",count:1})});const i=Array.from(a.entries()).map(([l,o])=>({agentId:l,...o})).sort((l,o)=>o.count-l.count).slice(0,10);return{topSharers:n,topListers:i}}}),_Es=()=>{const{user:s,brokerageId:t}=ks();return pt({queryKey:["brokerage-listings",t],queryFn:async()=>{if(!s||!t)return[];const{data:n}=await V.from("profiles").select("id").eq("brokerage_id",t);if(!n||n.length===0)return[];const r=n.map(l=>l.id),{data:a,error:i}=await V.from("listings").select(` *, photos:listing_photos(*), agent:profiles!listings_agent_id_fkey(id, name, email, brokerage_id, brokerage:brokerages(name)) `).in("agent_id",r).eq("is_approved",!0).order("created_at",{ascending:!1});if(i)throw i;return a},enabled:!!s&&!!t})},UMt=({className:s,variant:t="default"})=>e.jsx(qe,{variant:"outline",className:Ot("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"}),wEs={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"},jEs={coming_soon:"Coming Soon",office_exclusive:"Office Exclusive",pre_market:"Pre-Market",active:"Active",under_contract:"Under Contract",sold:"Sold",withdrawn:"Withdrawn"};function NEs(s){return s>=1e6?`$${(s/1e6).toFixed(1)}M`:`$${(s/1e3).toFixed(0)}K`}function kEs(){const s=Jn(),{data:t,isLoading:n}=DMt(),{data:r,isLoading:a}=OMt({status:void 0,propertyType:void 0,sortBy:"newest"}),i=(r==null?void 0:r.filter(u=>u.is_approved&&u.is_public))||[],l=i.filter(u=>u.is_featured),o=i.filter(u=>!u.is_featured),c=[...l,...o].slice(0,6),d=n||a;return!d&&!t?null:d?e.jsx(we,{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(UMt,{})]}),e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>s("/mission-control/listings"),className:"gap-1 text-muted-foreground hover:text-foreground",children:["View All ",e.jsx(xi,{className:"h-4 w-4"})]})]}),c.length===0?e.jsx(we,{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(ua,{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($,{variant:"link",size:"sm",onClick:()=>s("/mission-control/listings/new"),className:"mt-2",children:"Add the first listing"})]})})}):e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-3",children:c.map(u=>{var m,p;const h=((m=u.photos)==null?void 0:m.find(g=>g.is_primary))||((p=u.photos)==null?void 0:p[0]);return e.jsxs("div",{onClick:()=>s(`/mission-control/listings/${u.id}`),className:"group cursor-pointer bg-card rounded-xl border border-border overflow-hidden transition-all duration-200 hover:shadow-lg hover:border-primary/30",children:[e.jsxs("div",{className:"aspect-[4/3] bg-muted/50 overflow-hidden relative",children:[h!=null&&h.photo_url?e.jsx("img",{src:h.photo_url,alt:`${u.city}, ${u.state}`,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(ua,{className:"h-8 w-8 text-muted-foreground/50"})}),u.is_featured&&e.jsx("div",{className:"absolute top-1.5 left-1.5",children:e.jsxs(qe,{className:"gap-1 bg-amber-500 text-white border-0 text-[10px] px-1.5 py-0.5",children:[e.jsx(ri,{className:"h-2.5 w-2.5 fill-current"}),"Featured"]})}),e.jsx("div",{className:"absolute top-1.5 right-1.5",children:e.jsx(qe,{className:`text-[10px] px-1.5 py-0.5 ${wEs[u.status]}`,children:jEs[u.status]})})]}),e.jsxs("div",{className:"p-2",children:[e.jsx("p",{className:"font-bold text-sm text-foreground",children:NEs(u.price)}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[u.city,", ",u.state]}),(u.bedrooms||u.bathrooms)&&e.jsxs("p",{className:"text-[10px] text-muted-foreground mt-0.5",children:[u.bedrooms&&`${u.bedrooms} bed`,u.bedrooms&&u.bathrooms&&" · ",u.bathrooms&&`${u.bathrooms} bath`]})]})]},u.id)})})]})}function qMt(s=10,t){return pt({queryKey:["event-leaderboard",s,t],queryFn:async()=>{const{data:n}=await V.from("user_roles").select("user_id").eq("role","admin"),r=new Set((n==null?void 0:n.map(m=>m.user_id))||[]);let a=null;if(t){const{data:m}=await V.from("profiles").select("id").eq("brokerage_id",t);a=new Set((m==null?void 0:m.map(p=>p.id))||[])}const{data:i,error:l}=await V.from("agent_attendance_stats").select("user_id, total_points, total_events_attended, current_streak").order("total_points",{ascending:!1}).limit(s+r.size+50);if(l)throw l;if(!i||i.length===0)return[];let o=i.filter(m=>!r.has(m.user_id));a&&(o=o.filter(m=>a.has(m.user_id)));const c=o.slice(0,s),d=c.map(m=>m.user_id),{data:u}=await V.from("profiles").select("id, name").in("id",d),h=new Map((u==null?void 0:u.map(m=>[m.id,{name:m.name}]))||[]);return c.map(m=>({user_id:m.user_id,total_points:m.total_points,total_events_attended:m.total_events_attended,current_streak:m.current_streak,profile:h.get(m.user_id)||null}))}})}function VMt(s){return pt({queryKey:["user-attendance-stats",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await V.from("agent_attendance_stats").select("*").eq("user_id",s).single();if(n&&n.code!=="PGRST116")throw n;return t},enabled:!!s})}function HMt(s){return pt({queryKey:["user-badges",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await V.from("agent_badges").select("*").eq("user_id",s).order("earned_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function GMt(s,t){return pt({queryKey:["user-rank",s,t],queryFn:async()=>{if(!s)return null;const{data:n}=await V.from("agent_attendance_stats").select("total_points").eq("user_id",s).single();if(!n)return null;const{data:r}=await V.from("user_roles").select("user_id").eq("role","admin"),a=new Set((r==null?void 0:r.map(c=>c.user_id))||[]),{data:i,error:l}=await V.from("agent_attendance_stats").select("user_id, total_points").gt("total_points",n.total_points);if(l)throw l;let o=(i==null?void 0:i.filter(c=>!a.has(c.user_id)))||[];if(t){const{data:c}=await V.from("profiles").select("id").eq("brokerage_id",t),d=new Set((c==null?void 0:c.map(u=>u.id))||[]);o=o.filter(u=>d.has(u.user_id))}return o.length+1},enabled:!!s})}function SEs(){const{user:s,brokerageId:t,isAdmin:n}=ks();Jn();const r=!!t,[a,i]=k.useState("brokerage"),l=()=>{if(n)return null;if(r)return a==="global"?null:t},{data:o,isLoading:c}=qMt(5,l()),{data:d}=VMt(s==null?void 0:s.id),{data:u}=GMt(s==null?void 0:s.id,l()),{data:h}=HMt(s==null?void 0:s.id),m=n||r,p=()=>n?"Agent Leaderboard":r?a==="global"?"All LevelUp":"My Brokerage":"My Points";if(c)return e.jsxs(we,{children:[e.jsx(Vt,{className:"pb-2",children:e.jsxs(Yt,{className:"text-base flex items-center gap-2",children:[e.jsx(ql,{className:"h-4 w-4 text-yellow-500"}),p()]})}),e.jsx(De,{children:e.jsx("div",{className:"space-y-2",children:[...Array(m?5:3)].map((x,y)=>e.jsx(fn,{className:"h-10 w-full"},y))})})]});const g=x=>x===0?e.jsx(ql,{className:"h-4 w-4 text-yellow-500 mx-auto"}):x===1?e.jsx("span",{className:"text-sm font-medium text-gray-400",children:"2"}):x===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:x+1});if(m){const x=(o==null?void 0:o.slice(0,5))||[];return e.jsxs(we,{children:[e.jsxs(Vt,{className:"pb-2",children:[e.jsxs(Yt,{className:"text-base flex items-center gap-2",children:[e.jsx(ql,{className:"h-4 w-4 text-yellow-500"}),p()]}),!n&&r&&e.jsxs("div",{className:"flex gap-1 mt-2",children:[e.jsx($,{variant:a==="brokerage"?"default":"outline",size:"sm",className:"text-xs h-7 flex-1",onClick:()=>i("brokerage"),children:"My Brokerage"}),e.jsx($,{variant:a==="global"?"default":"outline",size:"sm",className:"text-xs h-7 flex-1",onClick:()=>i("global"),children:"All LevelUp"})]})]}),e.jsxs(De,{children:[!n&&d&&e.jsx("div",{className:"mb-3 p-2 rounded-lg bg-primary/5 border border-primary/10",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Your Rank:"}),e.jsxs("span",{className:"font-bold text-primary",children:["#",u||"-"]})]}),e.jsxs("div",{className:"flex items-center gap-3 text-sm",children:[e.jsxs("span",{children:[e.jsx("strong",{className:"text-primary",children:d.total_points})," pts"]}),e.jsxs("span",{children:[e.jsx("strong",{children:d.total_events_attended})," events"]})]})]})}),e.jsxs("div",{className:"space-y-2",children:[x.map((y,v)=>{var _,j,C;return e.jsxs("div",{className:`flex items-center gap-2 p-2 rounded-lg ${y.user_id===(s==null?void 0:s.id)?"bg-primary/10 border border-primary/20":v===0?"bg-yellow-500/10":""}`,children:[e.jsx("div",{className:"w-5 text-center",children:g(v)}),e.jsx(Wa,{className:"h-6 w-6",children:e.jsx(Ka,{className:"text-xs",children:((j=(_=y.profile)==null?void 0:_.name)==null?void 0:j.charAt(0))||"?"})}),e.jsx("span",{className:"flex-1 text-sm font-medium truncate",children:((C=y.profile)==null?void 0:C.name)||"Unknown"}),e.jsx("span",{className:"text-sm font-bold text-primary",children:y.total_points})]},y.user_id)}),x.length===0&&e.jsx("div",{className:"text-center text-muted-foreground py-2 text-sm",children:"No data yet"})]}),e.jsxs(nr,{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(Zo,{className:"h-4 w-4"}),"Spend Points in Reward Store",e.jsx(fi,{className:"h-4 w-4"})]})]})]})}return e.jsxs(we,{children:[e.jsx(Vt,{className:"pb-2",children:e.jsxs(Yt,{className:"text-base flex items-center gap-2",children:[e.jsx(ql,{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(iu,{className:"h-4 w-4 text-orange-500"}),e.jsx("span",{className:"text-sm font-medium",children:"Current Streak"})]}),e.jsxs("span",{className:"font-bold text-orange-500",children:[d.current_streak," 🔥"]})]}),h&&h.length>0&&e.jsxs("div",{className:"pt-2 border-t",children:[e.jsxs("div",{className:"flex items-center gap-1 mb-2",children:[e.jsx(oh,{className:"h-3 w-3 text-muted-foreground"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"Badges"})]}),e.jsxs("div",{className:"flex flex-wrap gap-1",children:[h.slice(0,4).map(x=>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:x.badge_name},x.id)),h.length>4&&e.jsxs("span",{className:"text-xs text-muted-foreground px-2 py-1",children:["+",h.length-4," more"]})]})]}),e.jsxs(nr,{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(Zo,{className:"h-4 w-4"}),"Spend Points in Reward Store",e.jsx(fi,{className:"h-4 w-4"})]})]}):e.jsxs("div",{className:"text-center text-muted-foreground py-4 text-sm",children:[e.jsx(ri,{className:"h-8 w-8 mx-auto mb-2 text-muted-foreground/50"}),e.jsx("p",{children:"Attend events to earn points!"}),e.jsxs(nr,{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(Zo,{className:"h-4 w-4"}),"Visit Reward Store",e.jsx(fi,{className:"h-4 w-4"})]})]})})]})}const vj=()=>pt({queryKey:["relationship-types"],queryFn:async()=>{const{data:s,error:t}=await V.from("relationship_types").select("*").order("sort_order");if(t)throw t;return s}}),vv=s=>{const t=ai(),n=1e3,r=async a=>{const i=[];let l=0;for(;;){const{data:o,error:c}=await a.range(l,l+n-1);if(c)throw c;const d=o??[];if(i.push(...d),d.length{let a=V.from("innercircle_contacts").select(` *, lead_source_ref:lead_sources(id, name), tags:innercircle_contact_tags( id, contact_id, relationship_type_id, relationship_type:relationship_types(*) ) `).eq("owner_user_id",t).order("created_at",{ascending:!1}).order("first_name");return await r(a)},enabled:!!t})},CEs=s=>pt({queryKey:["innercircle-contact",s],queryFn:async()=>{const{data:t,error:n}=await V.from("innercircle_contacts").select(` *, lead_source_ref:lead_sources(id, name), tags:innercircle_contact_tags( id, contact_id, relationship_type_id, relationship_type:relationship_types(*) ) `).eq("id",s).maybeSingle();if(n)throw n;return t},enabled:!!s}),WMt=()=>{const s=ai();return pt({queryKey:["innercircle-contact-counts",s],queryFn:async()=>{const{data:t,error:n}=await V.from("innercircle_contacts").select(` id, tags:innercircle_contact_tags(relationship_type_id) `);if(n)throw n;const r={};return t==null||t.forEach(a=>{var i;(i=a.tags)==null||i.forEach(l=>{r[l.relationship_type_id]=(r[l.relationship_type_id]||0)+1})}),r},enabled:!!s})},pAe=()=>{const s=ls(),t=ai();return Nt({mutationFn:async n=>{const{tagIds:r,...a}=n,i={...a,birthday:a.birthday||null,home_anniversary:a.home_anniversary||null,spouse_birthday:a.spouse_birthday||null,owner_user_id:t},{data:l,error:o}=await V.from("innercircle_contacts").insert(i).select().single();if(o)throw o;if(r&&r.length>0){const{error:c}=await V.from("innercircle_contact_tags").insert(r.map(d=>({contact_id:l.id,relationship_type_id:d})));if(c)throw c}return l},onSuccess:()=>{s.invalidateQueries({queryKey:["innercircle-contacts"]}),s.invalidateQueries({queryKey:["innercircle-contact-counts"]}),Ma({title:"Contact created successfully"})},onError:n=>{Ma({title:"Error creating contact",description:n.message,variant:"destructive"})}})},xWe=()=>{const s=ls();return Nt({mutationFn:async({id:t,...n})=>{const{tagIds:r,tags:a,...i}=n,l=["birthday","home_anniversary","spouse_birthday","wedding_anniversary","last_contacted_at","next_touch_date"],o={...i};for(const u of Object.keys(o)){const h=o[u];(h===""||typeof h=="string"&&l.includes(u)&&h.trim()==="")&&(o[u]=null)}const{data:c,error:d}=await V.from("innercircle_contacts").update(o).eq("id",t).select().single();if(d)throw d;if(r!==void 0&&(await V.from("innercircle_contact_tags").delete().eq("contact_id",t),r.length>0)){const{error:u}=await V.from("innercircle_contact_tags").insert(r.map(h=>({contact_id:t,relationship_type_id:h})));if(u)throw u}return c},onSuccess:()=>{s.invalidateQueries({queryKey:["innercircle-contacts"]}),s.invalidateQueries({queryKey:["innercircle-contact"]}),s.invalidateQueries({queryKey:["innercircle-contact-counts"]}),Ma({title:"Contact updated successfully"})},onError:t=>{Ma({title:"Error updating contact",description:t.message,variant:"destructive"})}})},KMt=()=>{const s=ls();return Nt({mutationFn:async({contactId:t,spouseContactId:n})=>{if(n){const{error:r}=await V.from("innercircle_contacts").update({spouse_contact_id:n}).eq("id",t);if(r)throw r;const{error:a}=await V.from("innercircle_contacts").update({spouse_contact_id:t}).eq("id",n);if(a)throw a}else{const{data:r}=await V.from("innercircle_contacts").select("spouse_contact_id").eq("id",t).single(),a=r==null?void 0:r.spouse_contact_id,{error:i}=await V.from("innercircle_contacts").update({spouse_contact_id:null}).eq("id",t);if(i)throw i;if(a){const{error:l}=await V.from("innercircle_contacts").update({spouse_contact_id:null}).eq("id",a);if(l)throw l}}},onSuccess:()=>{s.invalidateQueries({queryKey:["innercircle-contacts"]}),s.invalidateQueries({queryKey:["innercircle-contact"]}),s.invalidateQueries({queryKey:["innercircle-contact-spouse"]}),Ma({title:"Spouse link updated"})},onError:t=>{Ma({title:"Error linking spouse",description:t.message,variant:"destructive"})}})},yWe=()=>{const s=ls();return Nt({mutationFn:async t=>{const{error:n}=await V.from("innercircle_contacts").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["innercircle-contacts"]}),s.invalidateQueries({queryKey:["innercircle-contact-counts"]}),Ma({title:"Contact deleted successfully"})},onError:t=>{Ma({title:"Error deleting contact",description:t.message,variant:"destructive"})}})},Aee=()=>pt({queryKey:["action-types"],queryFn:async()=>{const{data:s,error:t}=await V.from("action_types").select("*").order("sort_order");if(t)throw t;return s}}),AEs=s=>pt({queryKey:["action-scripts",s],queryFn:async()=>{let t=V.from("action_scripts").select("*, action_type:action_types(*)");const{data:n,error:r}=await t;if(r)throw r;return n}}),EEs=()=>pt({queryKey:["touchpoint-plans"],queryFn:async()=>{const{data:s,error:t}=await V.from("touchpoint_plans").select(` *, items:touchpoint_plan_items( *, action_type:action_types(*), default_script:action_scripts(*) ) `).order("name");if(t)throw t;return s}}),TEs=()=>{const s=ls(),t=ai();return Nt({mutationFn:async({name:n,description:r})=>{const{data:a,error:i}=await V.from("touchpoint_plans").insert({name:n,description:r,owner_user_id:t,active:!0,is_template:!1}).select().single();if(i)throw i;return a},onSuccess:()=>{s.invalidateQueries({queryKey:["touchpoint-plans"]}),Ma({title:"Plan created successfully"})},onError:n=>{Ma({title:"Error creating plan",description:n.message,variant:"destructive"})}})},MEs=()=>{const s=ls(),t=ai();return Nt({mutationFn:async({sourcePlanId:n,newName:r})=>{const{data:a,error:i}=await V.from("touchpoint_plans").select(` *, items:touchpoint_plan_items(*) `).eq("id",n).single();if(i)throw i;if(!a)throw new Error("Source plan not found");const{data:l,error:o}=await V.from("touchpoint_plans").insert({name:r,description:a.description,owner_user_id:t,active:!0,is_template:!1}).select().single();if(o)throw o;if(a.items&&a.items.length>0){const c=a.items.map(u=>({plan_id:l.id,month_number:u.month_number,action_type_id:u.action_type_id,default_script_id:u.default_script_id,notes:u.notes})),{error:d}=await V.from("touchpoint_plan_items").insert(c);if(d)throw d}return l},onSuccess:()=>{s.invalidateQueries({queryKey:["touchpoint-plans"]}),Ma({title:"Plan duplicated successfully",description:"You can now edit your copy of this plan."})},onError:n=>{Ma({title:"Error duplicating plan",description:n.message,variant:"destructive"})}})},PEs=()=>{const s=ls();return Nt({mutationFn:async({id:t,name:n,description:r})=>{const{data:a,error:i}=await V.from("touchpoint_plans").update({name:n,description:r}).eq("id",t).select().single();if(i)throw i;return a},onSuccess:()=>{s.invalidateQueries({queryKey:["touchpoint-plans"]}),Ma({title:"Plan updated successfully"})}})},IEs=()=>{const s=ls();return Nt({mutationFn:async t=>{const{error:n}=await V.from("touchpoint_plans").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["touchpoint-plans"]}),Ma({title:"Plan deleted successfully"})}})},LEs=()=>{const s=ls();return Nt({mutationFn:async({planId:t,items:n})=>{if(await V.from("touchpoint_plan_items").delete().eq("plan_id",t),n.length>0){const{error:r}=await V.from("touchpoint_plan_items").insert(n.map(a=>({plan_id:t,month_number:a.month_number,action_type_id:a.action_type_id,default_script_id:a.default_script_id||null,notes:a.notes})));if(r)throw r}},onSuccess:()=>{s.invalidateQueries({queryKey:["touchpoint-plans"]}),Ma({title:"Plan schedule updated"})}})},REs=()=>{const s=ls();return Nt({mutationFn:async({actionTypeId:t,title:n,scriptBody:r,emailSubject:a,tone:i})=>{const{data:{user:l}}=await V.auth.getUser(),{data:o,error:c}=await V.from("action_scripts").insert({action_type_id:t,title:n,script_body:r,email_subject:a||null,tone:i||null,active:!0,user_id:l==null?void 0:l.id}).select().single();if(c)throw c;return o},onSuccess:()=>{s.invalidateQueries({queryKey:["action-scripts"]}),Ma({title:"Script created successfully"})},onError:t=>{Ma({title:"Error creating script",description:t.message,variant:"destructive"})}})},DEs=()=>{const s=ai();return pt({queryKey:["user-plan-enrollments",s],queryFn:async()=>{const{data:t,error:n}=await V.from("user_plan_enrollments").select(` *, plan:touchpoint_plans(*), relationship_type:relationship_types(*) `);if(n)throw n;return t},enabled:!!s})},OEs=()=>{const s=ls(),t=ai();return Nt({mutationFn:async({planId:n,relationshipTypeId:r,active:a})=>{const{data:i}=await V.from("user_plan_enrollments").select("id").eq("plan_id",n).eq("relationship_type_id",r).maybeSingle();if(i){const{error:l}=await V.from("user_plan_enrollments").update({active:a}).eq("id",i.id);if(l)throw l}else if(a){const{error:l}=await V.from("user_plan_enrollments").insert({owner_user_id:t,plan_id:n,relationship_type_id:r,active:!0,start_date:new Date().toISOString().split("T")[0]});if(l)throw l}},onSuccess:()=>{s.invalidateQueries({queryKey:["user-plan-enrollments"]}),Ma({title:"Plan enrollment updated"})}})},Jq=(s=7)=>{const t=ai();return pt({queryKey:["contact-touch-logs",t,s],queryFn:async()=>{const n=new Date;n.setDate(n.getDate()-s);const{data:r,error:a}=await V.from("contact_touch_logs").select(` *, contact:innercircle_contacts(*), action_type:action_types(*) `).eq("owner_user_id",t).gte("completed_at",n.toISOString()).order("completed_at",{ascending:!1});if(a)throw a;return r},enabled:!!t})},YMt=()=>{const s=ai();return pt({queryKey:["contacts-last-touch",s],queryFn:async()=>{const{data:t,error:n}=await V.from("contact_touch_logs").select("contact_id, completed_at").eq("owner_user_id",s).order("completed_at",{ascending:!1});if(n)throw n;const r={};return t==null||t.forEach(a=>{r[a.contact_id]||(r[a.contact_id]=a.completed_at)}),r},enabled:!!s})},FEs=(s=90)=>{const{data:t}=vv(),{data:n}=YMt();if(!t||!n)return{contacts:[],count:0};const r=new Date;r.setDate(r.getDate()-s);const a=t.filter(i=>{const l=n[i.id];return l?new Date(l){const s=ls(),t=ai();return Nt({mutationFn:async({contactId:n,actionTypeId:r,scriptUsedId:a,notes:i,completedAt:l})=>{const{data:o,error:c}=await V.from("contact_touch_logs").insert({owner_user_id:t,contact_id:n,action_type_id:r,script_used_id:a,notes:i,completed_at:l||new Date().toISOString()}).select().single();if(c)throw c;return o},onSuccess:async(n,r)=>{var a,i;s.invalidateQueries({queryKey:["contact-touch-logs"]}),s.invalidateQueries({queryKey:["contacts-last-touch"]}),s.invalidateQueries({queryKey:["today-actions"]}),s.invalidateQueries({queryKey:["popby-logs"]}),Ma({title:"Action completed!"});try{const[l,o]=await Promise.all([V.from("innercircle_contacts").select("email").eq("id",r.contactId).single(),V.from("action_types").select("name").eq("id",r.actionTypeId).single()]),c=(a=l.data)==null?void 0:a.email,d=((i=o.data)==null?void 0:i.name)||"Touch";/pop[\s-]?by/i.test(d)&&V.from("popby_logs").insert({owner_user_id:t,contact_id:r.contactId,notes:r.notes??null,completed_at:r.completedAt||n.completed_at}).then(()=>{s.invalidateQueries({queryKey:["popby-logs"]})}),c&&V.functions.invoke("boldtrail-sync",{body:{action:"push_touch",contact_email:c,touch_type:d,touch_notes:r.notes||null,touch_date:r.completedAt||n.completed_at}}).catch(()=>{})}catch{}}})},ZMt="agentos_weekly_touch_goal",Hct=20,XMt=()=>{if(typeof window>"u")return Hct;const s=localStorage.getItem(ZMt);if(s){const t=parseInt(s,10);if(!isNaN(t)&&t>0)return t}return Hct},zEs=s=>{localStorage.setItem(ZMt,s.toString())},xAe=()=>{const{data:s}=Jq(7),t=new Date;t.setHours(0,0,0,0);const n=new Date(t);n.setDate(t.getDate()-t.getDay());const r=(s==null?void 0:s.filter(l=>new Date(l.completed_at)>=n).length)||0;let a=0;if(s&&s.length>0){const l=new Set(s.map(c=>new Date(c.completed_at).toDateString()));let o=new Date(t);for(;l.has(o.toDateString());)a++,o.setDate(o.getDate()-1)}const i=XMt();return{actionsThisWeek:r,weeklyGoal:i,streak:a,progress:Math.min(r/i*100,100)}},BEs=()=>{const s=ai();return pt({queryKey:["contact-plan-cycles",s],queryFn:async()=>{const{data:t,error:n}=await V.from("contact_plan_cycles").select(` *, contact:innercircle_contacts(*), plan:touchpoint_plans( *, items:touchpoint_plan_items( *, action_type:action_types(*), default_script:action_scripts(*) ) ) `);if(n)throw n;return t},enabled:!!s})},$Es=()=>{const s=ls();return ai(),Nt({mutationFn:async()=>{var c;const{data:t}=await V.from("user_plan_enrollments").select("*").eq("active",!0);if(!t||t.length===0)return;const{data:n}=await V.auth.getUser(),r=(c=n==null?void 0:n.user)==null?void 0:c.id;if(!r)return;const{data:a}=await V.from("innercircle_contacts").select(` id, tags:innercircle_contact_tags(relationship_type_id) `).eq("owner_user_id",r);if(!a)return;const{data:i}=await V.from("contact_plan_cycles").select("contact_id, plan_id"),l=new Set((i==null?void 0:i.map(d=>`${d.contact_id}-${d.plan_id}`))||[]),o=[];for(const d of a)for(const u of d.tags||[]){const h=t.find(m=>m.relationship_type_id===u.relationship_type_id);h&&!l.has(`${d.id}-${h.plan_id}`)&&o.push({contact_id:d.id,plan_id:h.plan_id,relationship_type_id:u.relationship_type_id})}if(o.length>0){const{error:d}=await V.from("contact_plan_cycles").insert(o);if(d)throw d}return o.length},onSuccess:t=>{s.invalidateQueries({queryKey:["contact-plan-cycles"]}),t&&t>0&&Ma({title:`${t} contact(s) enrolled in plans`})}})},vWe=()=>{const s=ai(),{data:t}=BEs(),{data:n}=Jq(30);return pt({queryKey:["today-actions",s,t==null?void 0:t.length,n==null?void 0:n.length],queryFn:async()=>{var g;if(!t||t.length===0)return[];const{data:r}=await V.from("contact_snoozes").select("contact_id").gte("snoozed_until",new Date().toISOString()),a=new Set((r==null?void 0:r.map(x=>x.contact_id))||[]),i=new Date,l=[],o=new Date(i.getFullYear(),i.getMonth(),1),c=new Set((n==null?void 0:n.filter(x=>new Date(x.completed_at)>=o).map(x=>`${x.contact_id}-${x.action_type_id}`))||[]);for(const x of t){if(!((g=x.plan)!=null&&g.items)||x.plan.items.length===0||!x.contact||a.has(x.contact_id))continue;const y=new Date(x.cycle_start_date),_=Math.floor((i.getTime()-y.getTime())/(30.44*24*60*60*1e3))%12+1,j=x.plan.items.find(C=>C.month_number===_);if(j&&j.action_type){const C=`${x.contact_id}-${j.action_type_id}`;if(!c.has(C)){const{data:A}=await V.from("relationship_types").select("name").eq("id",x.relationship_type_id).single();l.push({contact:x.contact,actionType:j.action_type,script:j.default_script||void 0,planName:x.plan.name,relationshipTypeName:(A==null?void 0:A.name)||"",monthNumber:_})}}}const d=5,u=i.getDate(),h=l.sort((x,y)=>x.contact.first_name.localeCompare(y.contact.first_name)),m=(u-1)%Math.max(1,h.length);return[...h.slice(m),...h.slice(0,m)].slice(0,d)},enabled:!!s&&!!t})},NF=()=>pt({queryKey:["lead-sources"],queryFn:async()=>{const{data:s,error:t}=await V.from("lead_sources").select("*").eq("is_active",!0).order("sort_order");if(t)throw t;return s}}),bWe=()=>{const s=ls(),{user:t}=ks();return Nt({mutationFn:async n=>{const{data:r}=await V.from("lead_sources").select("id, name").eq("is_active",!0).ilike("name",n.trim()),a=(r||[]).find(o=>o.name.toLowerCase()===n.trim().toLowerCase()&&!0);if(a)throw new Error(`Lead source "${a.name}" already exists`);const{data:i,error:l}=await V.from("lead_sources").insert({name:n,owner_user_id:t==null?void 0:t.id,sort_order:100}).select().single();if(l)throw l;return i},onSuccess:()=>{s.invalidateQueries({queryKey:["lead-sources"]}),ae.success("Lead source added")},onError:n=>{ae.error("Failed to add lead source"),console.error(n)}})},UEs=()=>{const s=ls();return Nt({mutationFn:async({id:t,name:n})=>{const{error:r}=await V.from("lead_sources").update({name:n}).eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["lead-sources"]}),ae.success("Lead source updated")},onError:t=>{ae.error(t.message||"Failed to update lead source")}})},qEs=()=>{const s=ls();return Nt({mutationFn:async t=>{const{error:n}=await V.from("lead_sources").update({is_active:!1}).eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["lead-sources"]}),ae.success("Lead source removed")},onError:t=>{ae.error(t.message||"Failed to remove lead source")}})},_We=(s,t)=>{const{user:n,isAdmin:r}=ks(),a=r&&t?t:n==null?void 0:n.id;return pt({queryKey:["scorecard-transactions",s,a],queryFn:async()=>{let i=V.from("scorecard_transactions").select(` *, lead_source:lead_sources(id, name), client_type:relationship_types(id, name), contact:innercircle_contacts(id, first_name, last_name) `).eq("owner_user_id",a).order("close_date",{ascending:!1});s&&(i=i.gte("close_date",`${s}-01-01`).lte("close_date",`${s}-12-31`));const{data:l,error:o}=await i;if(o)throw o;return l},enabled:!!a})},wWe=s=>{const{user:t,isAdmin:n}=ks(),r=n&&s?s:t==null?void 0:t.id;return pt({queryKey:["scorecard-transactions-all",r],queryFn:async()=>{const{data:a,error:i}=await V.from("scorecard_transactions").select(` *, lead_source:lead_sources(id, name), client_type:relationship_types(id, name), contact:innercircle_contacts(id, first_name, last_name) `).eq("owner_user_id",r).order("close_date",{ascending:!1});if(i)throw i;return a},enabled:!!r})},yAe=()=>{const s=ls(),{user:t}=ks();return Nt({mutationFn:async n=>{const{data:r,error:a}=await V.from("scorecard_transactions").insert({...n,owner_user_id:t.id}).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["scorecard-transactions"]}),s.invalidateQueries({queryKey:["scorecard-transactions-all"]}),ae.success("Transaction added")},onError:n=>{ae.error("Failed to add transaction"),console.error(n)}})},VEs=()=>{const s=ls();return Nt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await V.from("scorecard_transactions").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["scorecard-transactions"]}),s.invalidateQueries({queryKey:["scorecard-transactions-all"]}),ae.success("Transaction updated")},onError:t=>{ae.error("Failed to update transaction"),console.error(t)}})},HEs=()=>{const s=ls();return Nt({mutationFn:async t=>{const{error:n}=await V.from("scorecard_transactions").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["scorecard-transactions"]}),s.invalidateQueries({queryKey:["scorecard-transactions-all"]}),ae.success("Transaction deleted")},onError:t=>{ae.error("Failed to delete transaction"),console.error(t)}})},QMt=(s,t)=>{const{user:n,isAdmin:r}=ks(),a=r&&t?t:n==null?void 0:n.id;return pt({queryKey:["scorecard-goals",s,a],queryFn:async()=>{const{data:i,error:l}=await V.from("scorecard_goals").select("*").eq("owner_user_id",a).eq("year",s).maybeSingle();if(l)throw l;return i},enabled:!!a})},GEs=()=>{const s=ls(),{user:t}=ks();return Nt({mutationFn:async n=>{const{data:r,error:a}=await V.from("scorecard_goals").upsert({...n,owner_user_id:t.id},{onConflict:"owner_user_id,year"}).select().single();if(a)throw a;return r},onSuccess:(n,r)=>{s.invalidateQueries({queryKey:["scorecard-goals",r.year]}),ae.success("Goals saved")},onError:n=>{ae.error("Failed to save goals"),console.error(n)}})},vAe=()=>{const{user:s}=ks();return pt({queryKey:["scorecard-settings",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await V.from("scorecard_settings").select("*").eq("user_id",s.id).maybeSingle();if(n)throw n;return t},enabled:!!(s!=null&&s.id)})},WEs=()=>{const s=ls(),{user:t}=ks();return Nt({mutationFn:async n=>{const{data:r,error:a}=await V.from("scorecard_settings").upsert({...n,user_id:t.id},{onConflict:"user_id"}).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["scorecard-settings"]}),ae.success("Settings saved")},onError:n=>{ae.error("Failed to save settings"),console.error(n)}})},JMt=(s,t)=>{const{data:n,isLoading:r}=_We(s,t),{data:a,isLoading:i}=wWe(t),{data:l}=vAe(),o=(l==null?void 0:l.show_commission)??!0,c=d=>{if(!d||d.length===0)return{totalTransactions:0,buyerCount:0,sellerCount:0,totalVolume:0,averagePrice:0,totalCommission:0,totalNetToAgent:0,topLeadSource:null,transactionsByMonth:[],leadSourceBreakdown:[]};const u=d.filter(A=>A.transaction_type==="buyer").length,h=d.filter(A=>A.transaction_type==="seller").length,m=d.reduce((A,M)=>A+Number(M.sale_price),0),p=d.reduce((A,M)=>A+(Number(M.commission_amount)||0),0),g=d.reduce((A,M)=>{const I=Number(M.commission_amount)||0;if(!I)return A;let P=I;return M.brokerage_split_pct&&(P-=I*(M.brokerage_split_pct/100)),M.team_split_pct&&(P-=I*(M.team_split_pct/100)),M.franchise_fee_pct&&(P-=I*(M.franchise_fee_pct/100)),M.referral_fee_pct&&(P-=I*(M.referral_fee_pct/100)),M.transaction_fee&&(P-=M.transaction_fee),A+Math.max(0,P)},0),x={};d.forEach(A=>{var I;const M=((I=A.lead_source)==null?void 0:I.name)||"Unknown";x[M]=(x[M]||0)+1});const y=Object.entries(x).map(([A,M])=>({name:A,count:M})).sort((A,M)=>M.count-A.count),v=y[0]||null,_={};d.forEach(A=>{const M=ih(A.close_date).toLocaleString("default",{month:"short"});_[M]=(_[M]||0)+1});const C=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"].map(A=>({month:A,count:_[A]||0}));return{totalTransactions:d.length,buyerCount:u,sellerCount:h,totalVolume:m,averagePrice:d.length>0?m/d.length:0,totalCommission:o?p:0,totalNetToAgent:o?g:0,topLeadSource:v,transactionsByMonth:C,leadSourceBreakdown:y}};return{yearStats:c(n),lifetimeStats:c(a),isLoading:r||i,showCommission:o}},KEs=()=>{const{isAdmin:s}=ks();return pt({queryKey:["agents-with-transactions"],queryFn:async()=>{const{data:t,error:n}=await V.from("scorecard_transactions").select("owner_user_id").order("owner_user_id");if(n)throw n;const r=[...new Set(t.map(l=>l.owner_user_id))],{data:a,error:i}=await V.from("profiles").select("id, name, email").in("id",r);if(i)throw i;return a},enabled:s})},fE={recency:40,touchpoints:30,transactions:20},Gct={warm:70,cooling:40};function YEs(s){return s===null?0:s<=14?fE.recency:s<=30?fE.recency*.85:s<=60?fE.recency*.65:s<=90?fE.recency*.4:s<=180?fE.recency*.2:fE.recency*.05}function ZEs(s){const t=Math.min(s/12,1);return Math.round(fE.touchpoints*t)}function XEs(s){return s?fE.transactions:0}function QEs(){return 0}function JEs(s){return s>=Gct.warm?"warm":s>=Gct.cooling?"cooling":"at-risk"}function Eee(){const{data:s,isLoading:t}=vv(),{data:n}=YMt(),{data:r}=Jq(365),{data:a}=wWe(),i=k.useMemo(()=>{if(!s)return[];const o=new Date,c=nD(o,12),d={};r==null||r.forEach(h=>{new Date(h.completed_at)>=c&&(d[h.contact_id]=(d[h.contact_id]||0)+1)});const u=new Set((a==null?void 0:a.filter(h=>h.contact_id).map(h=>h.contact_id))||[]);return s.map(h=>{const m=(n==null?void 0:n[h.id])||null,p=m?I2(o,new Date(m)):null,g=d[h.id]||0,x=u.has(h.id),y=YEs(p),v=ZEs(g),_=XEs(x),j=QEs(),C=Math.round(y+v+_+j),A={score:C,status:JEs(C),breakdown:{recency:Math.round(y),touchpoints:Math.round(v),transactions:Math.round(_),referrals:Math.round(j)},lastTouchDate:m,daysSinceTouch:p,touchCountLast12Months:g,hasTransaction:x};return{...h,relationshipScore:A}})},[s,n,r,a]),l=k.useMemo(()=>{const o=i.filter(m=>m.relationshipScore.status==="warm").length,c=i.filter(m=>m.relationshipScore.status==="cooling").length,d=i.filter(m=>m.relationshipScore.status==="at-risk").length,u=i.length,h=u>0?Math.round(i.reduce((m,p)=>m+p.relationshipScore.score,0)/u):0;return{warm:o,cooling:c,atRisk:d,total:u,averageScore:h}},[i]);return{contactsWithScores:i,stats:l,isLoading:t}}function eTs(s){const{contactsWithScores:t,isLoading:n}=Eee(),r=k.useMemo(()=>t.find(a=>a.id===s),[t,s]);return{score:r==null?void 0:r.relationshipScore,isLoading:n}}function e6t(){const s=Jn(),{stats:t,contactsWithScores:n,isLoading:r}=Eee();if(r)return e.jsxs(we,{children:[e.jsx(Vt,{className:"pb-2",children:e.jsx(fn,{className:"h-5 w-40"})}),e.jsxs(De,{className:"space-y-4",children:[e.jsx(fn,{className:"h-20 w-full"}),e.jsx(fn,{className:"h-16 w-full"})]})]});if(t.total===0)return e.jsxs(we,{children:[e.jsx(Vt,{className:"pb-2",children:e.jsxs(Yt,{className:"text-lg flex items-center gap-2",children:[e.jsx(Xn,{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($,{variant:"outline",size:"sm",className:"mt-3",onClick:()=>s("/mission-control/contacts?new=true"),children:"Add Your First Contact"})]})]});const a=Math.round(t.warm/t.total*100),i=Math.round(t.cooling/t.total*100),l=Math.round(t.atRisk/t.total*100),o=n.filter(c=>c.relationshipScore.status==="at-risk").sort((c,d)=>c.relationshipScore.score-d.relationshipScore.score).slice(0,3);return e.jsxs(we,{children:[e.jsxs(Vt,{className:"pb-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(Yt,{className:"text-lg flex items-center gap-2",children:[e.jsx(mc,{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(ho,{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(ho,{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(ho,{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(lk,{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(fi,{className:"h-3 w-3"})]})]},c.id))})]}),e.jsxs($,{variant:"outline",size:"sm",className:"w-full",onClick:()=>s("/mission-control/contacts?filter=at-risk"),children:["View All At-Risk Contacts",e.jsx(fi,{className:"h-4 w-4 ml-1"})]})]})]})}const tTs=()=>{const s=Number(new Intl.DateTimeFormat("en-US",{hour:"numeric",hour12:!1,timeZone:"America/New_York"}).format(new Date));return s<12?"Good morning":s<17?"Good afternoon":"Good evening"},sTs=()=>new Intl.DateTimeFormat("en-US",{weekday:"long",month:"long",day:"numeric",timeZone:"America/New_York"}).format(new Date);function nTs({value:s,goal:t}){const n=Math.min(t>0?s/t*100:0,100),r=30,a=2*Math.PI*r;return e.jsxs("div",{className:"relative h-[86px] w-[86px] shrink-0",children:[e.jsxs("svg",{viewBox:"0 0 72 72",className:"h-full w-full -rotate-90",children:[e.jsx("circle",{cx:"36",cy:"36",r,fill:"none",strokeWidth:"7",className:"stroke-current opacity-20"}),e.jsx("circle",{cx:"36",cy:"36",r,fill:"none",strokeWidth:"7",strokeLinecap:"round",stroke:"hsl(var(--hub-glow))",strokeDasharray:a,strokeDashoffset:a-a*n/100,style:{transition:"stroke-dashoffset .6s ease"}})]}),e.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center leading-none",children:[e.jsx("span",{className:"text-lg font-bold",children:s}),e.jsxs("span",{className:"text-[10px] hub-ink-muted",children:["of ",t]})]})]})}function rTs({name:s,eventsThisWeek:t=0}){const n=Jn(),{user:r}=ks(),{data:a}=vWe(),{data:i}=vv(),l=xAe(),{hasAccess:o,hasAssignment:c}=nAt(),{hasFeature:d}=rA(),{data:u}=pt({queryKey:["hub-active-listings",r==null?void 0:r.id],enabled:!!(r!=null&&r.id),queryFn:async()=>{const{count:j,error:C}=await V.from("listings").select("id",{count:"exact",head:!0}).eq("agent_id",r.id);return C?0:j||0}}),h=k.useMemo(()=>{if(!i)return 0;const j=Date.now()-7*24*60*60*1e3;return i.filter(C=>C.created_at&&new Date(C.created_at).getTime()>=j).length},[i]),m=(a==null?void 0:a.length)||0,p=(l==null?void 0:l.streak)||0,g=(l==null?void 0:l.actionsThisWeek)||0,x=(l==null?void 0:l.weeklyGoal)||20,y=[m>0?`${m} ${m===1?"person":"people"} to reach out to`:"no follow-ups queued",t>0?`${t} ${t===1?"event":"events"} coming up`:null].filter(Boolean).join(" • "),v=[{label:"New leads (7d)",value:h,to:"/mission-control/contacts"},{label:"Follow-ups due",value:m,to:"/mission-control"},...d("listing_exchange")?[{label:"My listings",value:u??0,to:"/mission-control/listings"}]:[],{label:"Day streak",value:p,to:"/mission-control",icon:iu}],_=[{label:"Add Contact",icon:Pl,to:"/mission-control/contacts?new=true"},...d("social")?[{label:"Create Post",icon:ou,to:"/social-swag-2"}]:[],...d("presentations")?[{label:"Listing Presentation",icon:hv,to:"/mission-control/listing-presentations"}]:[],...o?[{label:"Book Coaching",icon:wm,to:c?"/my-coach":"/coaching"}]:[],{label:"Ask AI",icon:kn,to:"/ask-ai"}];return e.jsxs("section",{className:"hub-ink relative overflow-hidden rounded-2xl p-5 sm:p-7 mb-6",children:[e.jsxs("div",{className:"relative flex flex-col gap-6 lg:flex-row lg:items-start lg:justify-between",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"text-xs uppercase tracking-wider hub-ink-muted",children:sTs()}),e.jsxs("h1",{className:"mt-1 text-2xl sm:text-3xl font-bold",children:[tTs(),", ",s]}),e.jsx("p",{className:"mt-1 text-sm hub-ink-muted",children:y?`Today: ${y}.`:"You're all clear today — go create some momentum."}),e.jsx("div",{className:"mt-5 grid grid-cols-2 gap-2 sm:grid-cols-4",children:v.map(j=>e.jsxs("button",{onClick:()=>n(j.to),className:"hub-glass rounded-xl px-3 py-2.5 text-left transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[j.icon&&e.jsx(j.icon,{className:"h-4 w-4",style:{color:"hsl(var(--hub-glow))"}}),e.jsx("span",{className:"text-xl font-bold",children:j.value})]}),e.jsx("p",{className:"mt-0.5 text-[11px] hub-ink-muted",children:j.label})]},j.label))})]}),e.jsxs("div",{className:"hub-glass flex items-center gap-4 rounded-2xl px-4 py-3 lg:self-center",children:[e.jsx(nTs,{value:g,goal:x}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-semibold",children:"Weekly touches"}),e.jsx("p",{className:"text-xs hub-ink-muted",children:g>=x?"Goal crushed 🎉":`${x-g} to hit your goal`}),e.jsxs("button",{onClick:()=>n("/mission-control"),className:"mt-2 inline-flex items-center gap-1 text-xs font-medium underline-offset-2 hover:underline",children:["Open Agent OS ",e.jsx(xi,{className:"h-3 w-3"})]})]})]})]}),e.jsx("div",{className:"hub-scroll relative mt-5 flex gap-2 overflow-x-auto pb-1",children:_.map(j=>e.jsxs("button",{onClick:()=>n(j.to),className:"hub-glass flex shrink-0 items-center gap-2 rounded-full px-3.5 py-2 text-sm font-medium transition-colors",children:[e.jsx(j.icon,{className:"h-4 w-4",style:{color:"hsl(var(--hub-glow))"}}),j.label]},j.label))})]})}const pz=24*60*60*1e3,aTs=s=>{if(!s)return null;const t=String(s).split(/[-/T]/);if(t.length<3)return null;const n=parseInt(t[1],10)-1,r=parseInt(t[2],10);return isNaN(n)||isNaN(r)?null:{month:n,day:r}},hre=s=>{const t=aTs(s);if(!t)return null;const n=new Date,r=new Date(n.getFullYear(),n.getMonth(),n.getDate());let a=new Date(n.getFullYear(),t.month,t.day);return a.getTime()s!==null&&s>=0&&s<=t,oTs=s=>s===0?"today":s===1?"tomorrow":`in ${s} days`,lTs={hot_lead_listings:{reason:"Viewing your listings repeatedly",action:"Call now",priority:20},listing_email_click:{reason:"Clicked a listing in your email",action:"Call",priority:21},listing_email_open:{reason:"Opened your listing email",action:"Text",priority:24},open_house_visitor:{reason:"Visited your open house",action:"Follow up",priority:22},email_clicked:{reason:"Clicked a link in your email",action:"Call",priority:23},active_email_thread:{reason:"Active email conversation",action:"Reply",priority:23},email_opened:{reason:"Opened your recent email",action:"Text",priority:26},long_term_homeowner:{reason:"Owned their home 7+ years",action:"Send equity check-in",priority:28},birthday_soon:{reason:"Birthday coming up",action:"Send wishes",priority:12},home_anniversary_soon:{reason:"Home anniversary coming up",action:"Send wishes",priority:13}},cTs=(s=5)=>{const t=ai(),{data:n,isLoading:r}=vWe(),{data:a,isLoading:i}=vv(),l=pt({queryKey:["smart-queue",t,n==null?void 0:n.length,a==null?void 0:a.length],queryFn:async()=>{var I;const o=[],c=new Set,d=P=>{var R;!((R=P.contact)!=null&&R.id)||c.has(P.contact.id)||(c.add(P.contact.id),o.push(P))};if((n||[]).forEach((P,R)=>{var O;d({key:`plan-${P.contact.id}-${R}`,contact:P.contact,kind:"plan",actionLabel:((O=P.actionType)==null?void 0:O.name)||"Touch",reason:P.planName?`${P.planName}${P.relationshipTypeName?` · ${P.relationshipTypeName}`:""}`:"Scheduled touch",priority:0,planAction:P})}),o.length>=s)return o.slice(0,s);const u=a||[],h=new Map(u.map(P=>[P.id,P])),[{data:m},{data:p},{data:g}]=await Promise.all([V.from("contact_snoozes").select("contact_id").gte("snoozed_until",new Date().toISOString()),V.from("contact_touch_logs").select("contact_id").eq("owner_user_id",t).gte("completed_at",new Date(Date.now()-14*pz).toISOString()),V.from("contact_touch_logs").select("contact_id").eq("owner_user_id",t).gte("completed_at",new Date(Date.now()-90*pz).toISOString())]),x=new Set([...(m||[]).map(P=>P.contact_id),...(p||[]).map(P=>P.contact_id)]),y=new Set((g||[]).map(P=>P.contact_id)),v=P=>!x.has(P)&&!c.has(P);for(const P of u){if(!v(P.id))continue;const O=[{days:hre(P.birthday),label:"Birthday"},{days:hre(P.home_anniversary),label:"Home anniversary"},{days:hre(P.wedding_anniversary),label:"Wedding anniversary"},{days:hre(P.spouse_birthday),label:`${P.spouse_name||"Spouse"}'s birthday`}].find(B=>iTs(B.days,7));O&&d({key:`milestone-${P.id}`,contact:P,kind:"milestone",actionLabel:"Send wishes",reason:`${O.label} ${oTs(O.days)}`,priority:O.days===0?1:5+O.days})}const{data:_}=await V.from("contact_signals").select("contact_id, signal_type, title, weight, detected_at").eq("owner_user_id",t).or(`expires_at.is.null,expires_at.gt.${new Date().toISOString()}`).order("weight",{ascending:!1}).order("detected_at",{ascending:!1}).limit(200);for(const P of _||[]){const R=h.get(P.contact_id);if(!R||!v(P.contact_id))continue;const O=lTs[P.signal_type]||{reason:P.title||"Recent activity",action:"Follow up",priority:27};d({key:`signal-${P.contact_id}`,contact:R,kind:"signal",actionLabel:O.action,reason:O.reason,priority:O.priority})}const{data:j}=await V.from("deal_pipeline").select("contact_id, deal_name, property_address, updated_at").eq("owner_user_id",t).is("actual_close_date",null).not("contact_id","is",null).order("updated_at",{ascending:!0}).limit(50);for(const P of j||[]){const R=h.get(P.contact_id);!R||!v(P.contact_id)||d({key:`deal-${P.contact_id}`,contact:R,kind:"deal",actionLabel:"Check in",reason:`Open deal with no contact in 2 weeks${P.property_address?` · ${P.property_address}`:""}`,priority:30})}const C=Date.now()-3*pz;for(const P of u)v(P.id)&&(y.has(P.id)||new Date(P.created_at).getTime()v(P.id)&&!y.has(P.id)&&new Date(P.created_at).getTime()P.id.localeCompare(R.id));if(M.length>0){const P=new Date().getDate()*7%M.length;for(let R=0;RP.priority-R.priority).slice(0,s)},enabled:!!t&&!r&&!i});return{...l,isLoading:l.isLoading||r||i}},dTs=()=>{const s=ai(),t=ls();return Nt({mutationFn:async n=>{const r=new Date(Date.now()+14*pz).toISOString(),{error:a}=await V.from("contact_snoozes").insert({contact_id:n,owner_user_id:s,snoozed_until:r});if(a)throw a},onSuccess:()=>{t.invalidateQueries({queryKey:["smart-queue"]}),t.invalidateQueries({queryKey:["today-actions"]}),Ma({title:"Snoozed for 14 days"})},onError:n=>Ma({title:"Could not snooze",description:n.message,variant:"destructive"})})},uTs=s=>(s||"?").split(" ").map(t=>t[0]).slice(0,2).join("").toUpperCase(),hTs={plan:{icon:fb,tint:"var(--nav-crm)"},milestone:{icon:ip,tint:"var(--nav-events)"},signal:{icon:iu,tint:"var(--nav-marketing)"},deal:{icon:zx,tint:"var(--nav-listings)"},new:{icon:kn,tint:"var(--nav-apps)"},cold:{icon:Hw,tint:"var(--nav-more)"}};function mTs(){const s=Jn(),{data:t,isLoading:n}=cTs(5),r=dTs(),a=xAe(),i=(a==null?void 0:a.actionsThisWeek)||0,l=(a==null?void 0:a.weeklyGoal)||20,o=t||[];return e.jsxs("section",{className:"hub-card p-5",children:[e.jsxs("div",{className:"mb-4 flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs("h2",{className:"flex items-center gap-2 text-lg font-semibold text-foreground",children:[e.jsx("span",{className:"flex h-8 w-8 items-center justify-center rounded-full",style:{background:"hsl(var(--nav-crm) / 0.12)"},children:e.jsx(_h,{className:"h-4 w-4",style:{color:"hsl(var(--nav-crm))"}})}),"Today's Top 5"]}),e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:o.length>0?"Picked for you from your plans, milestones and live activity.":"Your queue is clear."})]}),e.jsxs($,{variant:"ghost",size:"sm",className:"gap-1",onClick:()=>s("/mission-control"),children:["Agent OS ",e.jsx(fi,{className:"h-4 w-4"})]})]}),n?e.jsx("div",{className:"space-y-2",children:[0,1,2].map(c=>e.jsx(fn,{className:"h-16 w-full rounded-xl"},c))}):o.length===0?e.jsxs("div",{className:"rounded-xl border border-dashed border-border bg-muted/30 p-6 text-center",children:[e.jsx(Gr,{className:"mx-auto mb-2 h-7 w-7 text-muted-foreground/50"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Nothing due today. Add a new contact to your database to keep the pipeline full."}),e.jsxs($,{size:"sm",variant:"outline",className:"mt-3 gap-1.5",onClick:()=>s("/mission-control/contacts?new=true"),children:[e.jsx(Pl,{className:"h-3.5 w-3.5"})," Add Contact"]})]}):e.jsx(Sk,{delayDuration:200,children:e.jsx("div",{className:"space-y-2",children:o.map(c=>{const d=c.contact,u=d.first_name?`${d.first_name} ${d.last_name||""}`.trim():d.name||"Contact",h=hTs[c.kind],m=h.icon;return e.jsxs("div",{className:"group flex items-center gap-3 rounded-xl border border-border p-3 transition-colors hover:bg-muted/40",children:[e.jsx("span",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-full text-sm font-semibold",style:{background:`hsl(${h.tint} / 0.12)`,color:`hsl(${h.tint})`},children:uTs(u)}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"truncate text-sm font-medium text-foreground",children:u}),e.jsxs("div",{className:"mt-0.5 flex flex-wrap items-center gap-1.5",children:[e.jsxs(qe,{variant:"secondary",className:"gap-1 text-[10px]",style:{background:`hsl(${h.tint} / 0.12)`,color:`hsl(${h.tint})`},children:[e.jsx(m,{className:"h-3 w-3"}),c.actionLabel]}),e.jsx("span",{className:"truncate text-xs text-muted-foreground",children:c.reason})]})]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-1",children:[e.jsx(fTs,{contact:d,onOpen:()=>s(`/mission-control/contacts/${d.id}`)}),e.jsxs(Lx,{children:[e.jsx(Rx,{asChild:!0,children:e.jsx($,{size:"icon",variant:"ghost",className:"h-8 w-8 text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100 focus-visible:opacity-100","aria-label":"Not now",disabled:r.isPending,onClick:()=>r.mutate(d.id),children:e.jsx(mr,{className:"h-4 w-4"})})}),e.jsx(Jg,{children:"Not now — hide for 14 days"})]})]})]},c.key)})})}),e.jsxs("div",{className:"mt-4 border-t border-border pt-4",children:[e.jsxs("div",{className:"mb-2 flex items-center justify-between text-sm",children:[e.jsx("span",{className:"font-medium text-foreground",children:"Weekly goal"}),e.jsxs("span",{className:"text-muted-foreground",children:[e.jsx("span",{className:"font-semibold text-primary",children:i})," / ",l," touches"]})]}),e.jsx(ho,{value:Math.min(i/l*100,100),className:"h-2"})]})]})}function fTs({contact:s,onOpen:t}){const n=(s==null?void 0:s.phone)||(s==null?void 0:s.mobile_phone),r=s==null?void 0:s.email;return e.jsxs(e.Fragment,{children:[n&&e.jsx($,{asChild:!0,size:"icon",variant:"ghost",className:"h-8 w-8","aria-label":"Call",children:e.jsx("a",{href:`tel:${n}`,onClick:a=>a.stopPropagation(),children:e.jsx(ka,{className:"h-4 w-4"})})}),n&&e.jsx($,{asChild:!0,size:"icon",variant:"ghost",className:"h-8 w-8","aria-label":"Text",children:e.jsx("a",{href:`sms:${n}`,onClick:a=>a.stopPropagation(),children:e.jsx(bo,{className:"h-4 w-4"})})}),r&&e.jsx($,{asChild:!0,size:"icon",variant:"ghost",className:"h-8 w-8","aria-label":"Email",children:e.jsx("a",{href:`mailto:${r}`,onClick:a=>a.stopPropagation(),children:e.jsx(pn,{className:"h-4 w-4"})})}),e.jsx($,{size:"icon",variant:"ghost",className:"h-8 w-8","aria-label":"Open contact",onClick:t,children:e.jsx(fi,{className:"h-4 w-4"})})]})}const pTs=s=>{const t=i=>new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric",timeZone:"America/New_York"}).format(i),n=t(new Date),r=t(new Date(Date.now()+864e5)),a=t(s);return a===n?"Today":a===r?"Tomorrow":a};function gTs({events:s,registrations:t}){const n=Jn(),{data:r}=hMt(),{data:a}=pt({queryKey:["hub-upcoming-sessions",r==null?void 0:r.id],enabled:!!(r!=null&&r.id),queryFn:async()=>{const{data:l,error:o}=await V.from("coaching_sessions").select("id, scheduled_at, zoom_join_url, status, agenda").eq("assignment_id",r.id).gte("scheduled_at",new Date().toISOString()).neq("status","cancelled").order("scheduled_at",{ascending:!0}).limit(3);return o?[]:l||[]}}),i=k.useMemo(()=>{const l=(s||[]).map(c=>{const d=t==null?void 0:t.find(u=>u.event_id===c.id);return{id:`event-${c.id}`,title:c.title,subtitle:"LevelUp Event",date:new Date(c.event_date),kind:"event",live:UAs(c.event_date),joinUrl:d?d.zoom_join_url||c.zoom_link:null,onClick:()=>n("/events")}}),o=(a||[]).map(c=>({id:`session-${c.id}`,title:"Coaching Session",subtitle:"Coaching",date:new Date(c.scheduled_at),kind:"coaching",joinUrl:c.zoom_join_url||null,onClick:()=>n("/coaching")}));return[...l,...o].sort((c,d)=>c.date.getTime()-d.date.getTime()).slice(0,5)},[s,t,a,n]);return e.jsxs("section",{className:"hub-card p-5",children:[e.jsxs("div",{className:"mb-4 flex items-center justify-between",children:[e.jsxs("h2",{className:"flex items-center gap-2 text-lg font-semibold text-foreground",children:[e.jsx("span",{className:"flex h-8 w-8 items-center justify-center rounded-full",style:{background:"hsl(var(--nav-events) / 0.14)"},children:e.jsx(fd,{className:"h-4 w-4",style:{color:"hsl(var(--nav-events))"}})}),"Up Next"]}),e.jsxs($,{variant:"ghost",size:"sm",className:"gap-1",onClick:()=>n("/events"),children:["All ",e.jsx(fi,{className:"h-4 w-4"})]})]}),i.length===0?e.jsxs("div",{className:"rounded-xl border border-dashed border-border bg-muted/30 p-6 text-center",children:[e.jsx(fd,{className:"mx-auto mb-2 h-7 w-7 text-muted-foreground/50"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Nothing scheduled yet."}),e.jsx($,{size:"sm",variant:"outline",className:"mt-3",onClick:()=>n("/events"),children:"Browse Events"})]}):e.jsx("ol",{className:"relative space-y-1",children:i.map(l=>e.jsx("li",{children:e.jsxs("button",{onClick:l.onClick,className:"group flex w-full items-start gap-3 rounded-xl p-2.5 text-left transition-colors hover:bg-muted/50",children:[e.jsx("span",{className:"mt-0.5 flex h-9 w-9 shrink-0 items-center justify-center rounded-lg",style:{background:l.kind==="coaching"?"hsl(var(--nav-academy) / 0.14)":"hsl(var(--nav-events) / 0.14)"},children:l.live?e.jsx(Cy,{className:"h-4 w-4 text-destructive"}):l.kind==="coaching"?e.jsx(Bm,{className:"h-4 w-4",style:{color:"hsl(var(--nav-academy))"}}):e.jsx(ia,{className:"h-4 w-4",style:{color:"hsl(var(--nav-events))"}})}),e.jsxs("span",{className:"min-w-0 flex-1",children:[e.jsx("span",{className:"block truncate text-sm font-medium text-foreground group-hover:text-primary",children:l.title}),e.jsxs("span",{className:"block text-xs text-muted-foreground",children:[l.live?"Live now":`${pTs(l.date)} · ${nX(l.date)}`," ·"," ",l.subtitle]})]}),l.joinUrl&&e.jsxs($,{size:"sm",variant:l.live?"destructive":"secondary",className:"h-7 shrink-0 gap-1 px-2 text-xs",onClick:o=>{o.stopPropagation(),window.open(l.joinUrl,"_blank")},children:[e.jsx(Ir,{className:"h-3 w-3"})," Join"]})]})},l.id))})]})}const Wct=s=>s>=1e6?`$${(s/1e6).toFixed(1)}M`:s>=1e3?`$${Math.round(s/1e3)}K`:`$${s}`;function xTs(){const s=Jn(),{data:t,isLoading:n}=pt({queryKey:["hub-pipeline-snapshot"],queryFn:async()=>{const{data:r,error:a}=await V.from("deal_pipeline").select("id, expected_price, sale_price, stage:deal_pipeline_stages(id, name, color, is_won_stage, is_lost_stage)");if(a)throw a;const i=(r||[]).filter(u=>{var h,m;return!((h=u.stage)!=null&&h.is_won_stage)&&!((m=u.stage)!=null&&m.is_lost_stage)}),l=(r||[]).filter(u=>{var h;return(h=u.stage)==null?void 0:h.is_won_stage}),o=i.reduce((u,h)=>u+Number(h.expected_price||0),0),c=l.reduce((u,h)=>u+Number(h.sale_price||h.expected_price||0),0),d={};return i.forEach(u=>{var m,p,g;const h=((m=u.stage)==null?void 0:m.id)||"none";d[h]||(d[h]={name:((p=u.stage)==null?void 0:p.name)||"Unassigned",color:((g=u.stage)==null?void 0:g.color)||null,count:0}),d[h].count+=1}),{openCount:i.length,wonCount:l.length,volume:o,wonVolume:c,stages:Object.values(d).sort((u,h)=>h.count-u.count).slice(0,4)}}});return e.jsxs("section",{className:"hub-card flex flex-col p-5",children:[e.jsxs("div",{className:"mb-3 flex items-center justify-between",children:[e.jsxs("h3",{className:"flex items-center gap-2 text-base font-semibold text-foreground",children:[e.jsx("span",{className:"flex h-8 w-8 items-center justify-center rounded-full",style:{background:"hsl(var(--nav-listings) / 0.14)"},children:e.jsx(M5,{className:"h-4 w-4",style:{color:"hsl(var(--nav-listings))"}})}),"Pipeline"]}),e.jsxs($,{variant:"ghost",size:"sm",className:"gap-1",onClick:()=>s("/mission-control/pipeline"),children:["Open ",e.jsx(fi,{className:"h-4 w-4"})]})]}),n?e.jsxs("div",{className:"space-y-2",children:[e.jsx(fn,{className:"h-12 w-full"}),e.jsx(fn,{className:"h-16 w-full"})]}):!t||t.openCount+t.wonCount===0?e.jsxs("div",{className:"flex flex-1 flex-col items-center justify-center rounded-xl border border-dashed border-border bg-muted/30 p-5 text-center",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"No deals yet. Start tracking your buyers and sellers."}),e.jsx($,{size:"sm",variant:"outline",className:"mt-3",onClick:()=>s("/mission-control/pipeline"),children:"Create a Deal"})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"rounded-xl bg-muted/40 p-3",children:[e.jsx("p",{className:"text-2xl font-bold text-foreground",children:t.openCount}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Open deals"})]}),e.jsxs("div",{className:"rounded-xl bg-muted/40 p-3",children:[e.jsx("p",{className:"text-2xl font-bold text-foreground",children:Wct(t.volume)}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Pipeline volume"})]})]}),e.jsx("div",{className:"mt-4 space-y-2",children:t.stages.map(r=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"h-2 w-2 shrink-0 rounded-full",style:{background:r.color||"hsl(var(--primary))"}}),e.jsx("span",{className:"min-w-0 flex-1 truncate text-sm text-muted-foreground",children:r.name}),e.jsx("span",{className:"text-sm font-medium text-foreground",children:r.count})]},r.name))}),t.wonCount>0&&e.jsxs("p",{className:"mt-4 border-t border-border pt-3 text-xs text-muted-foreground",children:[e.jsx("span",{className:"font-semibold text-foreground",children:t.wonCount})," closed ·"," ",e.jsx("span",{className:"font-semibold text-foreground",children:Wct(t.wonVolume)})," volume"]})]})]})}function yTs(){const s=Jn(),{user:t}=ks(),{hasFeature:n}=rA(),{data:r}=pt({queryKey:["hub-jump-back-in",t==null?void 0:t.id],enabled:!!(t!=null&&t.id),queryFn:async()=>{const i=[],l=V,o=async u=>{try{const h=await u();return(h==null?void 0:h.data)||[]}catch{return[]}},[c,d]=await Promise.all([o(()=>l.from("listing_presentations").select("id, title, updated_at").eq("owner_user_id",t.id).order("updated_at",{ascending:!1}).limit(2)),o(()=>l.from("listings").select("id, property_address, updated_at").eq("agent_id",t.id).order("updated_at",{ascending:!1}).limit(2))]);return c.forEach(u=>i.push({id:`preso-${u.id}`,label:u.title||"Listing Presentation",sub:"Presentation Studio",icon:hv,hue:"--nav-listings",to:`/apps/listing-presentation-studio/${u.id}`})),d.forEach(u=>i.push({id:`listing-${u.id}`,label:u.property_address||"Listing",sub:"My Listings",icon:ua,hue:"--nav-websites",to:`/mission-control/listings/${u.id}`})),i.push({id:"marketing",label:"Create a post",sub:"Marketing Studio",icon:xm,hue:"--nav-marketing",to:"/marketing-studio"}),i.slice(0,8)}}),a=(r||[]).filter(i=>{const l=pCt(i.to);return!l||n(l)});return a.length<=1?null:e.jsxs("section",{className:"mb-8",children:[e.jsxs("div",{className:"mb-3 flex items-center gap-2",children:[e.jsx(sa,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("h3",{className:"text-sm font-semibold uppercase tracking-wide text-muted-foreground",children:"Jump back in"})]}),e.jsx("div",{className:"hub-scroll flex gap-3 overflow-x-auto pb-1",children:a.map(i=>e.jsxs("button",{onClick:()=>s(i.to),className:"hub-card group flex w-[230px] shrink-0 items-center gap-3 p-3 text-left",children:[e.jsx("span",{className:"flex h-10 w-10 shrink-0 items-center justify-center rounded-xl",style:{background:`hsl(var(${i.hue}) / 0.14)`},children:e.jsx(i.icon,{className:"h-5 w-5",style:{color:`hsl(var(${i.hue}))`}})}),e.jsxs("span",{className:"min-w-0 flex-1",children:[e.jsx("span",{className:"block truncate text-sm font-medium text-foreground group-hover:text-primary",children:i.label}),e.jsx("span",{className:"block text-xs text-muted-foreground",children:i.sub})]}),e.jsx(xi,{className:"h-4 w-4 shrink-0 text-muted-foreground opacity-0 transition-opacity group-hover:opacity-100"})]},i.id))})]})}function vTs({videos:s,kits:t,templates:n,services:r}){const a=Jn(),i=[{id:"videos",label:"Academy",icon:mm,hue:"--nav-academy",items:s,viewAll:"/academy",emptyText:"No new videos yet."},{id:"kits",label:"Resource Kits",icon:d1,hue:"--nav-apps",items:t,viewAll:"/toolbox",emptyText:"No resource kits yet."},{id:"templates",label:"Templates",icon:UT,hue:"--nav-marketing",items:n,viewAll:"/templates",emptyText:"No new templates yet.",fit:"contain"},{id:"services",label:"Services",icon:kn,hue:"--nav-crm",items:r,viewAll:"/additional-services",emptyText:"No additional services yet."}],[l,o]=k.useState(i[0].id),c=i.find(d=>d.id===l)||i[0];return e.jsxs("section",{className:"mb-10",children:[e.jsxs("div",{className:"mb-4 flex flex-wrap items-center justify-between gap-3",children:[e.jsx("h3",{className:"text-lg font-semibold text-foreground",children:"Fresh for you"}),e.jsxs($,{variant:"ghost",size:"sm",className:"gap-1 text-muted-foreground hover:text-foreground",onClick:()=>a(c.viewAll),children:["View All ",e.jsx(xi,{className:"h-4 w-4"})]})]}),e.jsx("div",{className:"hub-scroll mb-4 flex gap-2 overflow-x-auto pb-1",children:i.map(d=>{const u=d.id===c.id;return e.jsxs("button",{onClick:()=>o(d.id),className:`flex shrink-0 items-center gap-2 rounded-full border px-3.5 py-1.5 text-sm font-medium transition-colors ${u?"border-transparent text-foreground":"border-border text-muted-foreground hover:text-foreground"}`,style:u?{background:`hsl(var(${d.hue}) / 0.14)`}:void 0,children:[e.jsx(d.icon,{className:"h-4 w-4",style:{color:`hsl(var(${d.hue}))`}}),d.label,d.items.length>0&&e.jsx("span",{className:"rounded-full bg-muted px-1.5 text-[11px] text-muted-foreground",children:d.items.length})]},d.id)})}),c.items.length===0?e.jsxs("div",{className:"rounded-2xl border border-dashed border-border bg-muted/30 p-8 text-center",children:[e.jsx(c.icon,{className:"mx-auto mb-2 h-7 w-7 text-muted-foreground/50"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:c.emptyText})]}):e.jsx("div",{className:"grid grid-cols-2 gap-4 md:grid-cols-4",children:c.items.map(d=>e.jsxs("button",{onClick:d.onOpen,className:"hub-card group overflow-hidden text-left",children:[e.jsxs("div",{className:"relative aspect-[3/2] overflow-hidden bg-muted/50",children:[d.image?e.jsx("img",{src:d.image,alt:d.title,loading:"lazy",className:`h-full w-full ${c.fit==="contain"?"object-contain":"object-cover"} transition-transform duration-300 group-hover:scale-105`}):e.jsx("div",{className:"flex h-full w-full items-center justify-center",children:e.jsx(c.icon,{className:"h-8 w-8 text-muted-foreground/40"})}),d.meta&&e.jsx("span",{className:"absolute bottom-2 right-2 rounded bg-foreground/75 px-1.5 py-0.5 text-xs text-background",children:d.meta})]}),e.jsx("div",{className:"p-3",children:e.jsx("h4",{className:"line-clamp-2 text-sm font-medium text-foreground group-hover:text-primary",children:d.title})})]},d.id))})]})}const bTs=()=>{var Q;const{user:s,isAdmin:t}=ks(),n=Jn(),{hasFeature:r}=rA(),[a,i]=k.useState([]),[l,o]=k.useState([]),[c,d]=k.useState([]),[u,h]=k.useState([]),[m,p]=k.useState([]),[g,x]=k.useState([]),[y,v]=k.useState(new Set),[_,j]=k.useState([]),[C,A]=k.useState([]),[M,I]=k.useState([]),[P,R]=k.useState(null),[O,B]=k.useState(!0);k.useEffect(()=>{U()},[s]);const U=async()=>{var te,le,fe,_e,ve;try{const[he,Se,Te,Ie,Ue,Be,je,Ye,Ee,Re,ke]=await Promise.all([V.from("user_tags").select("tag").eq("user_id",s==null?void 0:s.id),V.from("app_tiles").select("*").order("name"),V.from("user_favorites").select("app_id").eq("user_id",s==null?void 0:s.id),V.from("events").select("*").order("event_date",{ascending:!0}),V.from("event_registrations").select("event_id, zoom_join_url").eq("user_id",s==null?void 0:s.id),V.from("canva_templates").select("id, name, preview_image_url, publish_date").order("publish_date",{ascending:!1}).limit(4),V.from("resource_kits").select("id, name, description, featured_image_url, publish_date").eq("is_published",!0).order("publish_date",{ascending:!1}).limit(4),V.from("academy_videos").select("id, title, description, thumbnail_url, duration, publish_date").eq("is_published",!0).order("publish_date",{ascending:!1}).limit(4),V.from("additional_services").select("id, name, description, preview_image_url, signup_link_url, publish_date").eq("is_published",!0).order("publish_date",{ascending:!1}).limit(4),V.from("dashboard_banners").select("id, title, description, image_url, link_url, link_text, placement, section_after").eq("is_active",!0).order("sort_order"),V.from("profiles").select("name").eq("id",s==null?void 0:s.id).single()]);(te=ke.data)!=null&&te.name&&R(ke.data.name);const Fe=((le=he.data)==null?void 0:le.map(nt=>nt.tag))||[],Oe=new Set(((fe=Te.data)==null?void 0:fe.map(nt=>nt.app_id))||[]);v(Oe);const yt=(((_e=Se.data)==null?void 0:_e.filter(nt=>!nt.required_tags||nt.required_tags.length===0?!0:nt.required_tags.some(et=>Fe.includes(et))))||[]).sort((nt,et)=>nt.name==="LevelUp Members Portal"?-1:et.name==="LevelUp Members Portal"?1:0);i(yt.slice(0,6));const tt=((ve=Ie.data)==null?void 0:ve.filter(nt=>iD(nt.event_date)!=="ended"))||[];o(tt.slice(0,4)),j(Ue.data||[]),d(Be.data||[]),h(je.data||[]),p(Ye.data||[]),x(Ee.data||[]);const ut=Re.data||[];A(ut.filter(nt=>nt.placement==="top")),I(ut.filter(nt=>nt.placement==="between"))}catch(he){console.error("Error loading dashboard:",he),ae.error("Failed to load dashboard data")}finally{B(!1)}},G=async te=>{var fe;const le=window.open("about:blank","_blank");try{await V.from("activity_logs").insert({user_id:s==null?void 0:s.id,app_id:te.app_id,app_name:te.name,user_agent:navigator.userAgent});const{data:_e,error:ve}=await V.functions.invoke("sso-launch",{body:{app_id:te.app_id}});if(ve)throw ve;_e!=null&&_e.redirect_url?le&&!le.closed?(le.location.href=_e.redirect_url,(fe=le.focus)==null||fe.call(le)):window.location.assign(_e.redirect_url):(le==null||le.close(),ae.error("Launch link unavailable"))}catch(_e){le==null||le.close(),console.error("Error launching app:",_e),ae.error("Failed to launch app")}},H={"Newsletter Pro":"newsletter","Social AutoPilot":"social","Staging Studio":"marketing_studio",SigFlow:"marketing_studio","Agent Review":"marketing_studio",AgentReview:"marketing_studio"},Y=a.filter(te=>{const le=H[te.name]||H[te.app_id];return!le||r(le)}),se=te=>M.filter(le=>le.section_after===te),ee=(P||((Q=s==null?void 0:s.user_metadata)==null?void 0:Q.name)||"there").split(" ")[0],oe=Date.now()+7*24*60*60*1e3,me=l.filter(te=>new Date(te.event_date).getTime()<=oe).length;return e.jsxs(Xs,{title:"Dashboard",children:[r("learn")&&e.jsx(qAs,{events:l,registrations:_,onNavigateToEvents:()=>n("/events")}),e.jsx(BAs,{}),e.jsx(rTs,{name:ee,eventsThisWeek:me}),e.jsx(GAs,{}),e.jsxs("div",{className:"grid grid-cols-1 gap-4 mb-6 lg:grid-cols-3",children:[e.jsx("div",{className:"lg:col-span-2",children:e.jsx(mTs,{})}),r("learn")&&e.jsx(gTs,{events:l,registrations:_})]}),e.jsxs("div",{className:"grid grid-cols-1 gap-4 mb-8 lg:grid-cols-3",children:[e.jsx(e6t,{}),r("deals")&&e.jsx(xTs,{}),r("learn")&&e.jsx(SEs,{})]}),e.jsx(yTs,{}),C.length>0&&e.jsx("div",{className:"mb-8",children:e.jsx(mG,{banners:C})}),e.jsx(iEs,{}),O?e.jsx("div",{className:"mb-10 grid grid-cols-2 gap-4 md:grid-cols-4",children:[0,1,2,3].map(te=>e.jsx("div",{className:"h-44 rounded-2xl bg-muted/40 animate-pulse"},te))}):e.jsx(vTs,{videos:(r("learn")?m:[]).map(te=>({id:te.id,title:te.title,image:te.thumbnail_url,meta:te.duration,onOpen:()=>n(`/academy/${te.id}`)})),kits:(r("learn")?u:[]).map(te=>({id:te.id,title:te.name,image:te.featured_image_url,onOpen:()=>n(`/toolbox/${te.id}`)})),templates:(r("marketing_studio")?c:[]).map(te=>({id:te.id,title:te.name,image:te.preview_image_url,onOpen:()=>n("/templates")})),services:g.map(te=>({id:te.id,title:te.name,image:te.preview_image_url,onOpen:()=>window.open(te.signup_link_url,"_blank")}))}),se("academy").length>0&&e.jsx("div",{className:"mb-10",children:e.jsx(mG,{banners:se("academy")})}),r("listing_exchange")&&e.jsx("div",{className:"mb-10",children:e.jsx(kEs,{})}),Y.length>0&&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:"Your Apps"}),e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>n("/apps"),className:"gap-1 text-muted-foreground hover:text-foreground",children:["View All ",e.jsx(xi,{className:"h-4 w-4"})]})]}),Y.length===0?e.jsx(we,{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(jy,{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:Y.map(te=>{const le=y.has(te.id);return e.jsxs("div",{onClick:()=>G(te),className:"hub-card group flex items-start gap-4 p-5 cursor-pointer",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:te.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:te.name}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1 line-clamp-2",children:te.description})]}),le&&e.jsx(jy,{className:"h-5 w-5 text-primary fill-current flex-shrink-0"})]},te.id)})})]}),se("templates").length>0&&e.jsx("div",{className:"mb-10",children:e.jsx(mG,{banners:se("templates")})}),se("events").length>0&&e.jsx("div",{className:"mb-10",children:e.jsx(mG,{banners:se("events")})}),se("toolbox").length>0&&e.jsx("div",{className:"mb-10",children:e.jsx(mG,{banners:se("toolbox")})})]})},_Ts=[{key:"contacts",label:"Contacts",icon:ka,description:"View, add, and edit contacts"},{key:"pipeline",label:"Deal Pipeline",icon:$8,description:"View, add, and move deals"},{key:"client_portal",label:"Client Portals",icon:d1,description:"Manage client portals on deals"},{key:"videos",label:"Videos",icon:ia,description:"View and upload videos"},{key:"listings",label:"Listings",icon:ua,description:"View, create, and edit listings"},{key:"scorecard",label:"Scorecard",icon:lv,description:"View and add transactions"},{key:"popbys",label:"Pop-bys",icon:Si,description:"View and log pop-bys"},{key:"digital_card",label:"Digital Card",icon:cv,description:"Create and edit digital business card"},{key:"guest_book",label:"Guest Book",icon:wg,description:"Manage open house guest books"},{key:"presentations",label:"Presentations",icon:hv,description:"Create and manage smart presentations"}];function wTs(){var I;const{user:s}=ks(),[t,n]=k.useState([]),[r,a]=k.useState(!0),[i,l]=k.useState(!1),[o,c]=k.useState(!1),[d,u]=k.useState(null),[h,m]=k.useState({email:"",name:"",password:""}),[p,g]=k.useState("create"),[x,y]=k.useState(!1),[v,_]=k.useState(null);k.useEffect(()=>{s&&j()},[s]);const j=async()=>{if(s){a(!0);try{const{data:P,error:R}=await V.from("agent_assistant_assignments").select("id, assistant_id, permissions, created_at").eq("agent_id",s.id);if(R)throw R;if(P&&P.length>0){const O=P.map(G=>G.assistant_id),{data:B}=await V.from("profiles").select("id, name, email").in("id",O),U=P.map(G=>{const H=B==null?void 0:B.find(Y=>Y.id===G.assistant_id);return{...G,permissions:G.permissions,assistant_profile:H?{name:H.name||"",email:H.email||""}:void 0}});n(U)}else n([])}catch(P){console.error("Error loading assistants:",P)}finally{a(!1)}}},C=async()=>{if(s){if(p==="link"){if(!h.email.trim()){ae.error("Please enter the assistant's email");return}y(!0);try{const{data:{session:P}}=await V.auth.getSession();if(!P)throw new Error("Not authenticated");const{data:R,error:O}=await V.from("profiles").select("id, name, email").eq("email",h.email.trim().toLowerCase()).single();if(O||!R){ae.error("No account found with that email. Try creating a new assistant instead.");return}const{data:B}=await V.from("agent_assistant_assignments").select("id").eq("agent_id",s.id).eq("assistant_id",R.id);if(B&&B.length>0){ae.error("This assistant is already assigned to you");return}const U=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/manage-user-roles",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${P.access_token}`},body:JSON.stringify({userId:R.id,role:"assistant",action:"add",agentId:s.id})}),G=await U.json();if(!U.ok)throw new Error(G.error||"Failed to assign assistant role");const{error:H}=await V.from("agent_assistant_assignments").insert({agent_id:s.id,assistant_id:R.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(H)throw H;ae.success(`${R.name||R.email} linked as your assistant`),l(!1),m({email:"",name:"",password:""}),j()}catch(P){console.error("Error linking assistant:",P),ae.error(P.message||"Failed to link assistant")}finally{y(!1)}return}if(!h.email.trim()||!h.name.trim()||!h.password.trim()){ae.error("Please fill in all fields");return}if(h.password.length<6){ae.error("Password must be at least 6 characters");return}y(!0);try{const{data:{session:P}}=await V.auth.getSession();if(!P)throw new Error("Not authenticated");const R=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/create-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${P.access_token}`},body:JSON.stringify({email:h.email.trim(),password:h.password,name:h.name.trim(),purpose:"assistant"})}),O=await R.json();if(!R.ok)throw new Error(O.error||"Failed to create assistant account");const B=O.userId||O.id;if(!B)throw new Error("No user ID returned");const U=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/manage-user-roles",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${P.access_token}`},body:JSON.stringify({userId:B,role:"assistant",action:"add",agentId:s.id})}),G=await U.json();if(!U.ok)throw new Error(G.error||"Failed to assign assistant role");const{error:H}=await V.from("agent_assistant_assignments").insert({agent_id:s.id,assistant_id:B,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(H)throw H;ae.success(`Assistant account created for ${h.name.trim()}`),l(!1),m({email:"",name:"",password:""}),j()}catch(P){console.error("Error adding assistant:",P),ae.error(P.message||"Failed to add assistant")}finally{y(!1)}}},A=async()=>{if(!(!d||!s))try{const{data:{session:P}}=await V.auth.getSession();if(!P)throw new Error("Not authenticated");const{error:R}=await V.from("agent_assistant_assignments").delete().eq("id",d.id);if(R)throw R;const{data:O}=await V.from("agent_assistant_assignments").select("id").eq("assistant_id",d.assistant_id);(!O||O.length===0)&&await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/manage-user-roles",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${P.access_token}`},body:JSON.stringify({userId:d.assistant_id,role:"assistant",action:"remove"})}),ae.success("Assistant removed"),c(!1),u(null),j()}catch(P){console.error("Error removing assistant:",P),ae.error(P.message||"Failed to remove assistant")}},M=async(P,R,O)=>{_(P);try{const B=t.find(H=>H.id===P);if(!B)return;const U={...B.permissions,[R]:O},{error:G}=await V.from("agent_assistant_assignments").update({permissions:U}).eq("id",P);if(G)throw G;n(H=>H.map(Y=>Y.id===P?{...Y,permissions:U}:Y))}catch(B){console.error("Error updating permissions:",B),ae.error("Failed to update permissions")}finally{_(null)}};return r?e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsxs(Yt,{className:"flex items-center gap-2",children:[e.jsx(Xn,{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(Jt,{className:"h-6 w-6 animate-spin text-muted-foreground"})})})]}):e.jsxs(e.Fragment,{children:[e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(Yt,{className:"flex items-center gap-2",children:[e.jsx(Xn,{className:"h-5 w-5"}),"My Assistants"]}),e.jsx(vr,{children:"Add assistants to help manage your Agent OS"})]}),e.jsxs($,{size:"sm",onClick:()=>{g("create"),l(!0)},children:[e.jsx(nn,{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(P=>{var R,O,B,U;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(Wa,{className:"h-10 w-10",children:e.jsx(Ka,{children:((O=(R=P.assistant_profile)==null?void 0:R.name)==null?void 0:O.split(" ").map(G=>G[0]).join("").toUpperCase())||"A"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:((B=P.assistant_profile)==null?void 0:B.name)||"Unknown"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:((U=P.assistant_profile)==null?void 0:U.email)||""})]}),e.jsxs(qe,{variant:"secondary",className:"ml-2",children:[e.jsx(Ng,{className:"h-3 w-3 mr-1"}),"Assistant"]})]}),e.jsx($,{variant:"ghost",size:"sm",className:"text-destructive hover:text-destructive",onClick:()=>{u(P),c(!0)},children:e.jsx(Un,{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:_Ts.map(G=>{const H=G.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(H,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:G.label}),e.jsx("p",{className:"text-xs text-muted-foreground",children:G.description})]})]}),e.jsx(On,{checked:P.permissions[G.key]||!1,onCheckedChange:Y=>M(P.id,G.key,Y),disabled:v===P.id})]},G.key)})})]})]},P.id)})})})]}),e.jsx(zs,{open:i,onOpenChange:l,children:e.jsxs(Rs,{children:[e.jsxs(Vs,{children:[e.jsx($s,{children:"Add Assistant"}),e.jsx(Cr,{children:p==="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($,{variant:p==="create"?"default":"outline",size:"sm",onClick:()=>g("create"),children:[e.jsx(nn,{className:"h-3 w-3 mr-1"}),"Create New"]}),e.jsxs($,{variant:p==="link"?"default":"outline",size:"sm",onClick:()=>g("link"),children:[e.jsx(od,{className:"h-3 w-3 mr-1"}),"Link Existing"]})]}),e.jsxs("div",{className:"space-y-4 py-2",children:[p==="create"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"assistant-name",children:"Name"}),e.jsx(be,{id:"assistant-name",value:h.name,onChange:P=>m({...h,name:P.target.value}),placeholder:"Assistant's full name"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"assistant-email",children:"Email"}),e.jsx(be,{id:"assistant-email",type:"email",value:h.email,onChange:P=>m({...h,email:P.target.value}),placeholder:"assistant@email.com"})]}),p==="create"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"assistant-password",children:"Temporary Password"}),e.jsx(be,{id:"assistant-password",type:"password",value:h.password,onChange:P=>m({...h,password:P.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(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsxs($,{onClick:C,disabled:x,children:[x&&e.jsx(Jt,{className:"h-4 w-4 mr-2 animate-spin"}),p==="create"?"Create Assistant":"Link Assistant"]})]})]})}),e.jsx(oc,{open:o,onOpenChange:c,children:e.jsxs(Ql,{children:[e.jsxs(Jl,{children:[e.jsx(tc,{children:"Remove Assistant?"}),e.jsxs(sc,{children:["This will remove ",(I=d==null?void 0:d.assistant_profile)==null?void 0:I.name,"'s access to your Agent OS. Their account will remain active but they won't be able to manage your data."]})]}),e.jsxs(ec,{children:[e.jsx(nc,{children:"Cancel"}),e.jsx(Vl,{onClick:A,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Remove"})]})]})})]})}function W0(s){this.content=s}W0.prototype={constructor:W0,find:function(s){for(var t=0;t>1}};W0.from=function(s){if(s instanceof W0)return s;var t=[];if(s)for(var n in s)t.push(n,s[n]);return new W0(t)};function t6t(s,t,n){for(let r=0;;r++){if(r==s.childCount||r==t.childCount)return s.childCount==t.childCount?null:n;let a=s.child(r),i=t.child(r);if(a==i){n+=a.nodeSize;continue}if(!a.sameMarkup(i))return n;if(a.isText&&a.text!=i.text){let l=a.text,o=i.text,c=0;for(;l[c]==o[c];c++)n++;return c&&c0&&m>0&&d[h-1]==u[m-1];)h--,m--,n--,r--;return h&&m&&h=56320&&s<57344}function r6t(s){return s>=55296&&s<56320}let Ua=class G1{constructor(t,n){if(this.content=t,this.size=n||0,n==null)for(let r=0;rt&&r(c,a+o,i||null,l)!==!1&&c.content.size){let u=o+1;c.nodesBetween(Math.max(0,t-u),Math.min(c.content.size,n-u),r,a+u)}o=d}}descendants(t){this.nodesBetween(0,this.size,t)}textBetween(t,n,r,a){let i="",l=!0;return this.nodesBetween(t,n,(o,c)=>{let d=o.isText?o.text.slice(Math.max(t,c)-c,n-c):o.isLeaf?a?typeof a=="function"?a(o):a:o.type.spec.leafText?o.type.spec.leafText(o):"":"";o.isBlock&&(o.isLeaf&&d||o.isTextblock)&&r&&(l?l=!1:i+=r),i+=d},0),i}append(t){if(!t.size)return this;if(!this.size)return t;let n=this.lastChild,r=t.firstChild,a=this.content.slice(),i=0;for(n.isText&&n.sameMarkup(r)&&(a[a.length-1]=n.withText(n.text+r.text),i=1);it)for(let i=0,l=0;lt&&((ln)&&(o.isText?o=o.cut(Math.max(0,t-l),Math.min(o.text.length,n-l)):o=o.cut(Math.max(0,t-l-1),Math.min(o.content.size,n-l-1))),r.push(o),a+=o.nodeSize),l=c}return new G1(r,a)}cutByIndex(t,n){return t==n?G1.empty:t==0&&n==this.content.length?this:new G1(this.content.slice(t,n))}replaceChild(t,n){let r=this.content[t];if(r==n)return this;let a=this.content.slice(),i=this.size+n.nodeSize-r.nodeSize;return a[t]=n,new G1(a,i)}addToStart(t){return new G1([t].concat(this.content),this.size+t.nodeSize)}addToEnd(t){return new G1(this.content.concat(t),this.size+t.nodeSize)}eq(t){if(this.content.length!=t.content.length)return!1;for(let n=0;nthis.size||t<0)throw new RangeError(`Position ${t} outside of fragment (${this})`);for(let n=0,r=0;;n++){let a=this.child(n),i=r+a.nodeSize;if(i>=t)return i==t?mre(n+1,i):mre(n,r);r=i}}toString(){return"<"+this.toStringInner()+">"}toStringInner(){return this.content.join(", ")}toJSON(){return this.content.length?this.content.map(t=>t.toJSON()):null}static fromJSON(t,n){if(!n)return G1.empty;if(!Array.isArray(n))throw new RangeError("Invalid input for Fragment.fromJSON");return G1.fromArray(n.map(t.nodeFromJSON))}static fromArray(t){if(!t.length)return G1.empty;let n,r=0;for(let a=0;athis.type.rank&&(n||(n=t.slice(0,a)),n.push(this),r=!0),n&&n.push(i)}}return n||(n=t.slice()),r||n.push(this),n}removeFromSet(t){for(let n=0;nr.type.rank-a.type.rank),n}};gm.none=[];class rX extends Error{}class Ii{constructor(t,n,r){this.content=t,this.openStart=n,this.openEnd=r}get size(){return this.content.size-this.openStart-this.openEnd}insertAt(t,n){let r=i6t(this.content,t+this.openStart,n,this.openStart+1,this.openEnd+1);return r&&new Ii(r,this.openStart,this.openEnd)}removeBetween(t,n){return new Ii(a6t(this.content,t+this.openStart,n+this.openStart),this.openStart,this.openEnd)}eq(t){return this.content.eq(t.content)&&this.openStart==t.openStart&&this.openEnd==t.openEnd}toString(){return this.content+"("+this.openStart+","+this.openEnd+")"}toJSON(){if(!this.content.size)return null;let t={content:this.content.toJSON()};return this.openStart>0&&(t.openStart=this.openStart),this.openEnd>0&&(t.openEnd=this.openEnd),t}static fromJSON(t,n){if(!n)return Ii.empty;let r=n.openStart||0,a=n.openEnd||0;if(typeof r!="number"||typeof a!="number")throw new RangeError("Invalid input for Slice.fromJSON");return new Ii(Ua.fromJSON(t,n.content),r,a)}static maxOpen(t,n=!0){let r=0,a=0;for(let i=t.firstChild;i&&!i.isLeaf&&(n||!i.type.spec.isolating);i=i.firstChild)r++;for(let i=t.lastChild;i&&!i.isLeaf&&(n||!i.type.spec.isolating);i=i.lastChild)a++;return new Ii(t,r,a)}}Ii.empty=new Ii(Ua.empty,0,0);function a6t(s,t,n){let{index:r,offset:a}=s.findIndex(t),i=s.maybeChild(r),{index:l,offset:o}=s.findIndex(n);if(a==t||i.isText){if(o!=n&&!s.child(l).isText)throw new RangeError("Removing non-flat range");return s.cut(0,t).append(s.cut(n))}if(r!=l)throw new RangeError("Removing non-flat range");return s.replaceChild(r,i.copy(a6t(i.content,t-a-1,n-a-1)))}function i6t(s,t,n,r,a,i){let{index:l,offset:o}=s.findIndex(t),c=s.maybeChild(l);if(o==t||c.isText)return i&&r<=0&&a<=0&&!i.canReplace(l,l,n)?null:s.cut(0,t).append(n).append(s.cut(t));let d=i6t(c.content,t-o-1,n,l==0?r-1:0,l==s.childCount-1?a-1:0,c);return d&&s.replaceChild(l,c.copy(d))}function jTs(s,t,n){if(n.openStart>s.depth)throw new rX("Inserted content deeper than insertion position");if(s.depth-n.openStart!=t.depth-n.openEnd)throw new rX("Inconsistent open depths");return o6t(s,t,n,0)}function o6t(s,t,n,r){let a=s.index(r),i=s.node(r);if(a==t.index(r)&&r=0&&s.isText&&s.sameMarkup(t[n])?t[n]=s.withText(t[n].text+s.text):t.push(s)}function SY(s,t,n,r){let a=(t||s).node(n),i=0,l=t?t.index(n):a.childCount;s&&(i=s.index(n),s.depth>n?i++:s.textOffset&&(tO(s.nodeAfter,r),i++));for(let o=i;oa&&n9e(s,t,a+1),l=r.depth>a&&n9e(n,r,a+1),o=[];return SY(null,s,a,o),i&&l&&t.index(a)==n.index(a)?(l6t(i,l),tO(sO(i,c6t(s,t,n,r,a+1)),o)):(i&&tO(sO(i,ASe(s,t,a+1)),o),SY(t,n,a,o),l&&tO(sO(l,ASe(n,r,a+1)),o)),SY(r,null,a,o),new Ua(o)}function ASe(s,t,n){let r=[];if(SY(null,s,n,r),s.depth>n){let a=n9e(s,t,n+1);tO(sO(a,ASe(s,t,n+1)),r)}return SY(t,null,n,r),new Ua(r)}function NTs(s,t){let n=t.depth-s.openStart,a=t.node(n).copy(s.content);for(let i=n-1;i>=0;i--)a=t.node(i).copy(Ua.from(a));return{start:a.resolveNoCache(s.openStart+n),end:a.resolveNoCache(a.content.size-s.openEnd-n)}}class aX{constructor(t,n,r){this.pos=t,this.path=n,this.parentOffset=r,this.depth=n.length/3-1}resolveDepth(t){return t==null?this.depth:t<0?this.depth+t:t}get parent(){return this.node(this.depth)}get doc(){return this.node(0)}node(t){return this.path[this.resolveDepth(t)*3]}index(t){return this.path[this.resolveDepth(t)*3+1]}indexAfter(t){return t=this.resolveDepth(t),this.index(t)+(t==this.depth&&!this.textOffset?0:1)}start(t){return t=this.resolveDepth(t),t==0?0:this.path[t*3-1]+1}end(t){return t=this.resolveDepth(t),this.start(t)+this.node(t).content.size}before(t){if(t=this.resolveDepth(t),!t)throw new RangeError("There is no position before the top-level node");return t==this.depth+1?this.pos:this.path[t*3-1]}after(t){if(t=this.resolveDepth(t),!t)throw new RangeError("There is no position after the top-level node");return t==this.depth+1?this.pos:this.path[t*3-1]+this.path[t*3].nodeSize}get textOffset(){return this.pos-this.path[this.path.length-1]}get nodeAfter(){let t=this.parent,n=this.index(this.depth);if(n==t.childCount)return null;let r=this.pos-this.path[this.path.length-1],a=t.child(n);return r?t.child(n).cut(r):a}get nodeBefore(){let t=this.index(this.depth),n=this.pos-this.path[this.path.length-1];return n?this.parent.child(t).cut(0,n):t==0?null:this.parent.child(t-1)}posAtIndex(t,n){n=this.resolveDepth(n);let r=this.path[n*3],a=n==0?0:this.path[n*3-1]+1;for(let i=0;i0;n--)if(this.start(n)<=t&&this.end(n)>=t)return n;return 0}blockRange(t=this,n){if(t.pos=0;r--)if(t.pos<=this.end(r)&&(!n||n(this.node(r))))return new ESe(this,t,r);return null}sameParent(t){return this.pos-this.parentOffset==t.pos-t.parentOffset}max(t){return t.pos>this.pos?t:this}min(t){return t.pos=0&&n<=t.content.size))throw new RangeError("Position "+n+" out of range");let r=[],a=0,i=n;for(let l=t;;){let{index:o,offset:c}=l.content.findIndex(i),d=i-c;if(r.push(l,o,a+c),!d||(l=l.child(o),l.isText))break;i=d-1,a+=c+1}return new aX(n,r,i)}static resolveCached(t,n){let r=Kct.get(t);if(r)for(let i=0;it&&this.nodesBetween(t,n,i=>(r.isInSet(i.marks)&&(a=!0),!a)),a}get isBlock(){return this.type.isBlock}get isTextblock(){return this.type.isTextblock}get inlineContent(){return this.type.inlineContent}get isInline(){return this.type.isInline}get isText(){return this.type.isText}get isLeaf(){return this.type.isLeaf}get isAtom(){return this.type.isAtom}toString(){if(this.type.spec.toDebugString)return this.type.spec.toDebugString(this);let t=this.type.name;return this.content.size&&(t+="("+this.content.toStringInner()+")"),d6t(this.marks,t)}contentMatchAt(t){let n=this.type.contentMatch.matchFragment(this.content,0,t);if(!n)throw new Error("Called contentMatchAt on a node with invalid content");return n}canReplace(t,n,r=Ua.empty,a=0,i=r.childCount){let l=this.contentMatchAt(t).matchFragment(r,a,i),o=l&&l.matchFragment(this.content,n);if(!o||!o.validEnd)return!1;for(let c=a;cn.type.name)}`);this.content.forEach(n=>n.check())}toJSON(){let t={type:this.type.name};for(let n in this.attrs){t.attrs=this.attrs;break}return this.content.size&&(t.content=this.content.toJSON()),this.marks.length&&(t.marks=this.marks.map(n=>n.toJSON())),t}static fromJSON(t,n){if(!n)throw new RangeError("Invalid input for Node.fromJSON");let r;if(n.marks){if(!Array.isArray(n.marks))throw new RangeError("Invalid mark data for Node.fromJSON");r=n.marks.map(t.markFromJSON)}if(n.type=="text"){if(typeof n.text!="string")throw new RangeError("Invalid text node in JSON");return t.text(n.text,r)}let a=Ua.fromJSON(t,n.content),i=t.nodeType(n.type).create(n.attrs,a,r);return i.type.checkAttrs(i.attrs),i}};cM.prototype.text=void 0;class TSe extends cM{constructor(t,n,r,a){if(super(t,n,null,a),!r)throw new RangeError("Empty text nodes are not allowed");this.text=r}toString(){return this.type.spec.toDebugString?this.type.spec.toDebugString(this):d6t(this.marks,JSON.stringify(this.text))}get textContent(){return this.text}textBetween(t,n){return this.text.slice(t,n)}get nodeSize(){return this.text.length}mark(t){return t==this.marks?this:new TSe(this.type,this.attrs,this.text,t)}withText(t){return t==this.text?this:new TSe(this.type,this.attrs,t,this.marks)}cut(t=0,n=this.text.length){return t==0&&n==this.text.length?this:this.withText(this.text.slice(t,n))}eq(t){return this.sameMarkup(t)&&this.text==t.text}toJSON(){let t=super.toJSON();return t.text=this.text,t}}function d6t(s,t){for(let n=s.length-1;n>=0;n--)t=s[n].type.name+"("+t+")";return t}class DO{constructor(t){this.validEnd=t,this.next=[],this.wrapCache=[]}static parse(t,n){let r=new ATs(t,n);if(r.next==null)return DO.empty;let a=u6t(r);r.next&&r.err("Unexpected trailing text");let i=RTs(LTs(a));return DTs(i,r),i}matchType(t){for(let n=0;nd.createAndFill()));for(let d=0;d=this.next.length)throw new RangeError(`There's no ${t}th edge in this content match`);return this.next[t]}toString(){let t=[];function n(r){t.push(r);for(let a=0;a{let i=a+(r.validEnd?"*":" ")+" ";for(let l=0;l"+t.indexOf(r.next[l].next);return i}).join(` `)}}DO.empty=new DO(!0);class ATs{constructor(t,n){this.string=t,this.nodeTypes=n,this.inline=null,this.pos=0,this.tokens=t.split(/\s*(?=\b|\W|$)/),this.tokens[this.tokens.length-1]==""&&this.tokens.pop(),this.tokens[0]==""&&this.tokens.shift()}get next(){return this.tokens[this.pos]}eat(t){return this.next==t&&(this.pos++||!0)}err(t){throw new SyntaxError(t+" (in content expression '"+this.string+"')")}}function u6t(s){let t=[];do t.push(ETs(s));while(s.eat("|"));return t.length==1?t[0]:{type:"choice",exprs:t}}function ETs(s){let t=[];do t.push(TTs(s));while(s.next&&s.next!=")"&&s.next!="|");return t.length==1?t[0]:{type:"seq",exprs:t}}function TTs(s){let t=ITs(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=MTs(s,t);else break;return t}function Yct(s){/\D/.test(s.next)&&s.err("Expected number, got '"+s.next+"'");let t=Number(s.next);return s.pos++,t}function MTs(s,t){let n=Yct(s),r=n;return s.eat(",")&&(s.next!="}"?r=Yct(s):r=-1),s.eat("}")||s.err("Unclosed braced range"),{type:"range",min:n,max:r,expr:t}}function PTs(s,t){let n=s.nodeTypes,r=n[t];if(r)return[r];let a=[];for(let i in n){let l=n[i];l.isInGroup(t)&&a.push(l)}return a.length==0&&s.err("No node type or group '"+t+"' found"),a}function ITs(s){if(s.eat("(")){let t=u6t(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=PTs(s,s.next).map(n=>(s.inline==null?s.inline=n.isInline:s.inline!=n.isInline&&s.err("Mixing inline and block content"),{type:"name",value:n}));return s.pos++,t.length==1?t[0]:{type:"choice",exprs:t}}}function LTs(s){let t=[[]];return a(i(s,0),n()),t;function n(){return t.push([])-1}function r(l,o,c){let d={term:c,to:o};return t[l].push(d),d}function a(l,o){l.forEach(c=>c.to=o)}function i(l,o){if(l.type=="choice")return l.exprs.reduce((c,d)=>c.concat(i(d,o)),[]);if(l.type=="seq")for(let c=0;;c++){let d=i(l.exprs[c],o);if(c==l.exprs.length-1)return d;a(d,o=n())}else if(l.type=="star"){let c=n();return r(o,c),a(i(l.expr,c),c),[r(c)]}else if(l.type=="plus"){let c=n();return a(i(l.expr,o),c),a(i(l.expr,c),c),[r(c)]}else{if(l.type=="opt")return[r(o)].concat(i(l.expr,o));if(l.type=="range"){let c=o;for(let d=0;d{s[l].forEach(({term:o,to:c})=>{if(!o)return;let d;for(let u=0;u{d||a.push([o,d=[]]),d.indexOf(u)==-1&&d.push(u)})})});let i=t[r.join(",")]=new DO(r.indexOf(s.length-1)>-1);for(let l=0;l-1}get whitespace(){return this.spec.whitespace||(this.spec.code?"pre":"normal")}hasRequiredAttrs(){for(let t in this.attrs)if(this.attrs[t].isRequired)return!0;return!1}compatibleContent(t){return this==t||this.contentMatch.compatible(t.contentMatch)}computeAttrs(t){return!t&&this.defaultAttrs?this.defaultAttrs:f6t(this.attrs,t)}create(t=null,n,r){if(this.isText)throw new Error("NodeType.create can't construct text nodes");return new cM(this,this.computeAttrs(t),Ua.from(n),gm.setFrom(r))}createChecked(t=null,n,r){return n=Ua.from(n),this.checkContent(n),new cM(this,this.computeAttrs(t),n,gm.setFrom(r))}createAndFill(t=null,n,r){if(t=this.computeAttrs(t),n=Ua.from(n),n.size){let l=this.contentMatch.fillBefore(n);if(!l)return null;n=l.append(n)}let a=this.contentMatch.matchFragment(n),i=a&&a.fillBefore(Ua.empty,!0);return i?new cM(this,t,n.append(i),gm.setFrom(r)):null}validContent(t){let n=this.contentMatch.matchFragment(t);if(!n||!n.validEnd)return!1;for(let r=0;r-1}allowsMarks(t){if(this.markSet==null)return!0;for(let n=0;nr[i]=new x6t(i,n,l));let a=n.spec.topNode||"doc";if(!r[a])throw new RangeError("Schema is missing its top node type ('"+a+"')");if(!r.text)throw new RangeError("Every schema needs a 'text' type");for(let i in r.text.attrs)throw new RangeError("The text node type should not have attributes");return r}};function OTs(s,t,n){let r=n.split("|");return a=>{let i=a===null?"null":typeof a;if(r.indexOf(i)<0)throw new RangeError(`Expected value of type ${r} for attribute ${t} on type ${s}, got ${i}`)}}class FTs{constructor(t,n,r){this.hasDefault=Object.prototype.hasOwnProperty.call(r,"default"),this.default=r.default,this.validate=typeof r.validate=="string"?OTs(t,n,r.validate):r.validate}get isRequired(){return!this.hasDefault}}class bAe{constructor(t,n,r,a){this.name=t,this.rank=n,this.schema=r,this.spec=a,this.attrs=g6t(t,a.attrs),this.excluded=null;let i=m6t(this.attrs);this.instance=i?new gm(this,i):null}create(t=null){return!t&&this.instance?this.instance:new gm(this,f6t(this.attrs,t))}static compile(t,n){let r=Object.create(null),a=0;return t.forEach((i,l)=>r[i]=new bAe(i,a++,n,l)),r}removeFromSet(t){for(var n=0;n-1}}let y6t=class{constructor(t){this.linebreakReplacement=null,this.cached=Object.create(null);let n=this.spec={};for(let a in t)n[a]=t[a];n.nodes=W0.from(t.nodes),n.marks=W0.from(t.marks||{}),this.nodes=Xct.compile(this.spec.nodes,this),this.marks=bAe.compile(this.spec.marks,this);let r=Object.create(null);for(let a in this.nodes){if(a in this.marks)throw new RangeError(a+" can not be both a node and a mark");let i=this.nodes[a],l=i.spec.content||"",o=i.spec.marks;if(i.contentMatch=r[l]||(r[l]=DO.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?Qct(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==""?[]:Qct(this,l.split(" "))}this.nodeFromJSON=a=>cM.fromJSON(this,a),this.markFromJSON=a=>gm.fromJSON(this,a),this.topNodeType=this.nodes[this.spec.topNode||"doc"],this.cached.wrappings=Object.create(null)}node(t,n=null,r,a){if(typeof t=="string")t=this.nodeType(t);else if(t instanceof Xct){if(t.schema!=this)throw new RangeError("Node type from different schema used ("+t.name+")")}else throw new RangeError("Invalid node type: "+t);return t.createChecked(n,r,a)}text(t,n){let r=this.nodes.text;return new TSe(r,r.defaultAttrs,t,gm.setFrom(n))}mark(t,n){return typeof t=="string"&&(t=this.marks[t]),t.create(n)}nodeType(t){let n=this.nodes[t];if(!n)throw new RangeError("Unknown node type: "+t);return n}};function Qct(s,t){let n=[];for(let r=0;r-1)&&n.push(l=c)}if(!l)throw new SyntaxError("Unknown mark type: '"+t[r]+"'")}return n}function zTs(s){return s.tag!=null}function BTs(s){return s.style!=null}let CY=class a9e{constructor(t,n){this.schema=t,this.rules=n,this.tags=[],this.styles=[];let r=this.matchedStyles=[];n.forEach(a=>{if(zTs(a))this.tags.push(a);else if(BTs(a)){let i=/[^=]*/.exec(a.style)[0];r.indexOf(i)<0&&r.push(i),this.styles.push(a)}}),this.normalizeLists=!this.tags.some(a=>{if(!/^(ul|ol)\b/.test(a.tag)||!a.node)return!1;let i=t.nodes[a.node];return i.contentMatch.matchType(i)})}parse(t,n={}){let r=new edt(this,n,!1);return r.addAll(t,gm.none,n.from,n.to),r.finish()}parseSlice(t,n={}){let r=new edt(this,n,!0);return r.addAll(t,gm.none,n.from,n.to),Ii.maxOpen(r.finish())}matchTag(t,n,r){for(let a=r?this.tags.indexOf(r)+1:0;at.length&&(o.charCodeAt(t.length)!=61||o.slice(t.length+1)!=n))){if(l.getAttrs){let c=l.getAttrs(n);if(c===!1)continue;l.attrs=c||void 0}return l}}}static schemaRules(t){let n=[];function r(a){let i=a.priority==null?50:a.priority,l=0;for(;l{r(l=tdt(l)),l.mark||l.ignore||l.clearMark||(l.mark=a)})}for(let a in t.nodes){let i=t.nodes[a].spec.parseDOM;i&&i.forEach(l=>{r(l=tdt(l)),l.node||l.ignore||l.mark||(l.node=a)})}return n}static fromSchema(t){return t.cached.domParser||(t.cached.domParser=new a9e(t,a9e.schemaRules(t)))}};const v6t={address:!0,article:!0,aside:!0,blockquote:!0,body:!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},$Ts={head:!0,noscript:!0,object:!0,script:!0,style:!0,title:!0},b6t={ol:!0,ul:!0},iX=1,i9e=2,AY=4;function Jct(s,t,n){return t!=null?(t?iX:0)|(t==="full"?i9e:0):s&&s.whitespace=="pre"?iX|i9e:n&~AY}class fre{constructor(t,n,r,a,i,l){this.type=t,this.attrs=n,this.marks=r,this.solid=a,this.options=l,this.content=[],this.activeMarks=gm.none,this.match=i||(l&AY?null:t.contentMatch)}findWrapping(t){if(!this.match){if(!this.type)return[];let n=this.type.contentMatch.fillBefore(Ua.from(t));if(n)this.match=this.type.contentMatch.matchFragment(n);else{let r=this.type.contentMatch,a;return(a=r.findWrapping(t.type))?(this.match=r,a):null}}return this.match.findWrapping(t.type)}finish(t){if(!(this.options&iX)){let r=this.content[this.content.length-1],a;if(r&&r.isText&&(a=/[ \t\r\n\u000c]+$/.exec(r.text))){let i=r;r.text.length==a[0].length?this.content.pop():this.content[this.content.length-1]=i.withText(i.text.slice(0,i.text.length-a[0].length))}}let n=Ua.from(this.content);return!t&&this.match&&(n=n.append(this.match.fillBefore(Ua.empty,!0))),this.type?this.type.create(this.attrs,n,this.marks):n}inlineContext(t){return this.type?this.type.inlineContent:this.content.length?this.content[0].isInline:t.parentNode&&!v6t.hasOwnProperty(t.parentNode.nodeName.toLowerCase())}}class edt{constructor(t,n,r){this.parser=t,this.options=n,this.isOpen=r,this.open=0,this.localPreserveWS=!1;let a=n.topNode,i,l=Jct(null,n.preserveWhitespace,0)|(r?AY:0);a?i=new fre(a.type,a.attrs,gm.none,!0,n.topMatch||a.type.contentMatch,l):r?i=new fre(null,null,gm.none,!0,null,l):i=new fre(t.schema.topNodeType,null,gm.none,!0,null,l),this.nodes=[i],this.find=n.findPositions,this.needsBlock=!1}get top(){return this.nodes[this.open]}addDOM(t,n){t.nodeType==3?this.addTextNode(t,n):t.nodeType==1&&this.addElement(t,n)}addTextNode(t,n){let r=t.nodeValue,a=this.top,i=a.options&i9e?"full":this.localPreserveWS||(a.options&iX)>0,{schema:l}=this.parser;if(i==="full"||a.inlineContext(t)||/[^ \t\r\n\u000c]/.test(r)){if(i)if(i==="full")r=r.replace(/\r\n?/g,` `);else if(l.linebreakReplacement&&/[\r\n]/.test(r)&&this.top.findWrapping(l.linebreakReplacement.create())){let o=r.split(/\r?\n|\r/);for(let c=0;c!c.clearMark(d)):n=n.concat(this.parser.schema.marks[c.mark].create(c.attrs)),c.consuming===!1)o=c;else break}}return n}addElementByRule(t,n,r,a){let i,l;if(n.node)if(l=this.parser.schema.nodes[n.node],l.isLeaf)this.insertNode(l.create(n.attrs),r,t.nodeName=="BR")||this.leafFallback(t,r);else{let c=this.enter(l,n.attrs||null,r,n.preserveWhitespace);c&&(i=!0,r=c)}else{let c=this.parser.schema.marks[n.mark];r=r.concat(c.create(n.attrs))}let o=this.top;if(l&&l.isLeaf)this.findInside(t);else if(a)this.addElement(t,r,a);else if(n.getContent)this.findInside(t),n.getContent(t,this.parser.schema).forEach(c=>this.insertNode(c,r,!1));else{let c=t;typeof n.contentElement=="string"?c=t.querySelector(n.contentElement):typeof n.contentElement=="function"?c=n.contentElement(t):n.contentElement&&(c=n.contentElement),this.findAround(t,c,!0),this.addAll(c,r),this.findAround(t,c,!1)}i&&this.sync(o)&&this.open--}addAll(t,n,r,a){let i=r||0;for(let l=r?t.childNodes[r]:t.firstChild,o=a==null?null:t.childNodes[a];l!=o;l=l.nextSibling,++i)this.findAtPoint(t,i),this.addDOM(l,n);this.findAtPoint(t,i)}findPlace(t,n,r){let a,i;for(let l=this.open,o=0;l>=0;l--){let c=this.nodes[l],d=c.findWrapping(t);if(d&&(!a||a.length>d.length+o)&&(a=d,i=c,!d.length))break;if(c.solid){if(r)break;o+=2}}if(!a)return null;this.sync(i);for(let l=0;l(l.type?l.type.allowsMarkType(d.type):sdt(d.type,t))?(c=d.addToSet(c),!1):!0),this.nodes.push(new fre(t,n,c,a,null,o)),this.open++,r}closeExtra(t=!1){let n=this.nodes.length-1;if(n>this.open){for(;n>this.open;n--)this.nodes[n-1].content.push(this.nodes[n].finish(t));this.nodes.length=this.open+1}}finish(){return this.open=0,this.closeExtra(this.isOpen),this.nodes[0].finish(!!(this.isOpen||this.options.topOpen))}sync(t){for(let n=this.open;n>=0;n--){if(this.nodes[n]==t)return this.open=n,!0;this.localPreserveWS&&(this.nodes[n].options|=iX)}return!1}get currentPos(){this.closeExtra();let t=0;for(let n=this.open;n>=0;n--){let r=this.nodes[n].content;for(let a=r.length-1;a>=0;a--)t+=r[a].nodeSize;n&&t++}return t}findAtPoint(t,n){if(this.find)for(let r=0;r-1)return t.split(/\s*\|\s*/).some(this.matchesContext,this);let n=t.split("/"),r=this.options.context,a=!this.isOpen&&(!r||r.parent.type==this.nodes[0].type),i=-(r?r.depth+1:0)+(a?0:1),l=(o,c)=>{for(;o>=0;o--){let d=n[o];if(d==""){if(o==n.length-1||o==0)continue;for(;c>=i;c--)if(l(o-1,c))return!0;return!1}else{let u=c>0||c==0&&a?this.nodes[c].type:r&&c>=i?r.node(c-i).type:null;if(!u||u.name!=d&&!u.isInGroup(d))return!1;c--}}return!0};return l(n.length-1,this.open)}textblockFromContext(){let t=this.options.context;if(t)for(let n=t.depth;n>=0;n--){let r=t.node(n).contentMatchAt(t.indexAfter(n)).defaultType;if(r&&r.isTextblock&&r.defaultAttrs)return r}for(let n in this.parser.schema.nodes){let r=this.parser.schema.nodes[n];if(r.isTextblock&&r.defaultAttrs)return r}}}function UTs(s){for(let t=s.firstChild,n=null;t;t=t.nextSibling){let r=t.nodeType==1?t.nodeName.toLowerCase():null;r&&b6t.hasOwnProperty(r)&&n?(n.appendChild(t),t=n):r=="li"?n=t:r&&(n=null)}}function qTs(s,t){return(s.matches||s.msMatchesSelector||s.webkitMatchesSelector||s.mozMatchesSelector).call(s,t)}function tdt(s){let t={};for(let n in s)t[n]=s[n];return t}function sdt(s,t){let n=t.schema.nodes;for(let r in n){let a=n[r];if(!a.allowsMarkType(s))continue;let i=[],l=o=>{i.push(o);for(let c=0;c{if(i.length||l.marks.length){let o=0,c=0;for(;o=0;a--){let i=this.serializeMark(t.marks[a],t.isInline,n);i&&((i.contentDOM||i.dom).appendChild(r),r=i.dom)}return r}serializeMark(t,n,r={}){let a=this.marks[t.type.name];return a&&mNe(pre(r),a(t,n),null,t.attrs)}static renderSpec(t,n,r=null,a){return typeof n=="string"?{dom:t.createTextNode(n)}:mNe(t,n,r,a)}static fromSchema(t){return t.cached.domSerializer||(t.cached.domSerializer=new kF(this.nodesFromSchema(t),this.marksFromSchema(t)))}static nodesFromSchema(t){let n=ndt(t.nodes);return n.text||(n.text=r=>r.text),n}static marksFromSchema(t){return ndt(t.marks)}}function ndt(s){let t={};for(let n in s){let r=s[n].spec.toDOM;r&&(t[n]=r)}return t}function pre(s){return s.document||window.document}const rdt=new WeakMap;function VTs(s){let t=rdt.get(s);return t===void 0&&rdt.set(s,t=HTs(s)),t}function HTs(s){let t=null;function n(r){if(r&&typeof r=="object")if(Array.isArray(r))if(typeof r[0]=="string")t||(t=[]),t.push(r);else for(let a=0;a-1)throw new RangeError("Using an array from an attribute object as a DOM spec. This may be an attempted cross site scripting attack.");let l=a.indexOf(" ");l>0&&(n=a.slice(0,l),a=a.slice(l+1));let o,c=n?s.createElementNS(n,a):s.createElement(a),d=t[1],u=1;if(d&&typeof d=="object"&&d.nodeType==null&&!Array.isArray(d)){u=2;for(let h in d)if(d[h]!=null){let m=h.indexOf(" ");m>0?c.setAttributeNS(h.slice(0,m),h.slice(m+1),d[h]):h=="style"&&c.style?c.style.cssText=d[h]:c.setAttribute(h,d[h])}}for(let h=u;hu)throw new RangeError("Content hole must be the only child of its parent node");return{dom:c,contentDOM:c}}else if(typeof m=="string")c.appendChild(s.createTextNode(m));else{let{dom:p,contentDOM:g}=mNe(s,m,n,r);if(c.appendChild(p),g){if(o)throw new RangeError("Multiple content holes");o=g}}}return{dom:c,contentDOM:o}}const _6t=65535,w6t=Math.pow(2,16);function GTs(s,t){return s+t*w6t}function adt(s){return s&_6t}function WTs(s){return(s-(s&_6t))/w6t}const j6t=1,N6t=2,fNe=4,k6t=8;class o9e{constructor(t,n,r){this.pos=t,this.delInfo=n,this.recover=r}get deleted(){return(this.delInfo&k6t)>0}get deletedBefore(){return(this.delInfo&(j6t|fNe))>0}get deletedAfter(){return(this.delInfo&(N6t|fNe))>0}get deletedAcross(){return(this.delInfo&fNe)>0}}class Bw{constructor(t,n=!1){if(this.ranges=t,this.inverted=n,!t.length&&Bw.empty)return Bw.empty}recover(t){let n=0,r=adt(t);if(!this.inverted)for(let a=0;at)break;let d=this.ranges[o+i],u=this.ranges[o+l],h=c+d;if(t<=h){let m=d?t==c?-1:t==h?1:n:n,p=c+a+(m<0?0:u);if(r)return p;let g=t==(n<0?c:h)?null:GTs(o/3,t-c),x=t==c?N6t:t==h?j6t:fNe;return(n<0?t!=c:t!=h)&&(x|=k6t),new o9e(p,x,g)}a+=u-d}return r?t+a:new o9e(t+a,0,null)}touches(t,n){let r=0,a=adt(n),i=this.inverted?2:1,l=this.inverted?1:2;for(let o=0;ot)break;let d=this.ranges[o+i],u=c+d;if(t<=u&&o==a*3)return!0;r+=this.ranges[o+l]-d}return!1}forEach(t){let n=this.inverted?2:1,r=this.inverted?1:2;for(let a=0,i=0;a=0;n--){let a=t.getMirror(n);this.appendMap(t._maps[n].invert(),a!=null&&a>n?r-a-1:void 0)}}invert(){let t=new oX;return t.appendMappingInverted(this),t}map(t,n=1){if(this.mirror)return this._map(t,n,!0);for(let r=this.from;ri&&c!l.isAtom||!o.type.allowsMarkType(this.mark.type)?l:l.mark(this.mark.addToSet(l.marks)),a),n.openStart,n.openEnd);return Dx.fromReplace(t,this.from,this.to,i)}invert(){return new f5(this.from,this.to,this.mark)}map(t){let n=t.mapResult(this.from,1),r=t.mapResult(this.to,-1);return n.deleted&&r.deleted||n.pos>=r.pos?null:new _T(n.pos,r.pos,this.mark)}merge(t){return t instanceof _T&&t.mark.eq(this.mark)&&this.from<=t.to&&this.to>=t.from?new _T(Math.min(this.from,t.from),Math.max(this.to,t.to),this.mark):null}toJSON(){return{stepType:"addMark",mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(t,n){if(typeof n.from!="number"||typeof n.to!="number")throw new RangeError("Invalid input for AddMarkStep.fromJSON");return new _T(n.from,n.to,t.markFromJSON(n.mark))}}v1.jsonID("addMark",_T);class f5 extends v1{constructor(t,n,r){super(),this.from=t,this.to=n,this.mark=r}apply(t){let n=t.slice(this.from,this.to),r=new Ii(jWe(n.content,a=>a.mark(this.mark.removeFromSet(a.marks)),t),n.openStart,n.openEnd);return Dx.fromReplace(t,this.from,this.to,r)}invert(){return new _T(this.from,this.to,this.mark)}map(t){let n=t.mapResult(this.from,1),r=t.mapResult(this.to,-1);return n.deleted&&r.deleted||n.pos>=r.pos?null:new f5(n.pos,r.pos,this.mark)}merge(t){return t instanceof f5&&t.mark.eq(this.mark)&&this.from<=t.to&&this.to>=t.from?new f5(Math.min(this.from,t.from),Math.max(this.to,t.to),this.mark):null}toJSON(){return{stepType:"removeMark",mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(t,n){if(typeof n.from!="number"||typeof n.to!="number")throw new RangeError("Invalid input for RemoveMarkStep.fromJSON");return new f5(n.from,n.to,t.markFromJSON(n.mark))}}v1.jsonID("removeMark",f5);class wT extends v1{constructor(t,n){super(),this.pos=t,this.mark=n}apply(t){let n=t.nodeAt(this.pos);if(!n)return Dx.fail("No node at mark step's position");let r=n.type.create(n.attrs,null,this.mark.addToSet(n.marks));return Dx.fromReplace(t,this.pos,this.pos+1,new Ii(Ua.from(r),0,n.isLeaf?0:1))}invert(t){let n=t.nodeAt(this.pos);if(n){let r=this.mark.addToSet(n.marks);if(r.length==n.marks.length){for(let a=0;ar.pos?null:new _0(n.pos,r.pos,a,i,this.slice,this.insert,this.structure)}toJSON(){let t={stepType:"replaceAround",from:this.from,to:this.to,gapFrom:this.gapFrom,gapTo:this.gapTo,insert:this.insert};return this.slice.size&&(t.slice=this.slice.toJSON()),this.structure&&(t.structure=!0),t}static fromJSON(t,n){if(typeof n.from!="number"||typeof n.to!="number"||typeof n.gapFrom!="number"||typeof n.gapTo!="number"||typeof n.insert!="number")throw new RangeError("Invalid input for ReplaceAroundStep.fromJSON");return new _0(n.from,n.to,n.gapFrom,n.gapTo,Ii.fromJSON(t,n.slice),n.insert,!!n.structure)}}v1.jsonID("replaceAround",_0);function l9e(s,t,n){let r=s.resolve(t),a=n-t,i=r.depth;for(;a>0&&i>0&&r.indexAfter(i)==r.node(i).childCount;)i--,a--;if(a>0){let l=r.node(i).maybeChild(r.indexAfter(i));for(;a>0;){if(!l||l.isLeaf)return!0;l=l.firstChild,a--}}return!1}function KTs(s,t,n,r){let a=[],i=[],l,o;s.doc.nodesBetween(t,n,(c,d,u)=>{if(!c.isInline)return;let h=c.marks;if(!r.isInSet(h)&&u.type.allowsMarkType(r.type)){let m=Math.max(d,t),p=Math.min(d+c.nodeSize,n),g=r.addToSet(h);for(let x=0;xs.step(c)),i.forEach(c=>s.step(c))}function YTs(s,t,n,r){let a=[],i=0;s.doc.nodesBetween(t,n,(l,o)=>{if(!l.isInline)return;i++;let c=null;if(r instanceof bAe){let d=l.marks,u;for(;u=r.isInSet(d);)(c||(c=[])).push(u),d=u.removeFromSet(d)}else r?r.isInSet(l.marks)&&(c=[r]):c=l.marks;if(c&&c.length){let d=Math.min(o+l.nodeSize,n);for(let u=0;us.step(new f5(l.from,l.to,l.style)))}function NWe(s,t,n,r=n.contentMatch,a=!0){let i=s.doc.nodeAt(t),l=[],o=t+1;for(let c=0;c=0;c--)s.step(l[c])}function ZTs(s,t,n){return(t==0||s.canReplace(t,s.childCount))&&(n==s.childCount||s.canReplace(0,n))}function eV(s){let n=s.parent.content.cutByIndex(s.startIndex,s.endIndex);for(let r=s.depth,a=0,i=0;;--r){let l=s.$from.node(r),o=s.$from.index(r)+a,c=s.$to.indexAfter(r)-i;if(rn;g--)x||r.index(g)>0?(x=!0,u=Ua.from(r.node(g).copy(u)),h++):c--;let m=Ua.empty,p=0;for(let g=i,x=!1;g>n;g--)x||a.after(g+1)=0;l--){if(r.size){let o=n[l].type.contentMatch.matchFragment(r);if(!o||!o.validEnd)throw new RangeError("Wrapper type given to Transform.wrap does not form valid content of its parent wrapper")}r=Ua.from(n[l].type.create(n[l].attrs,r))}let a=t.start,i=t.end;s.step(new _0(a,i,a,i,new Ii(r,0,0),n.length,!0))}function tMs(s,t,n,r,a){if(!r.isTextblock)throw new RangeError("Type given to setBlockType should be a textblock");let i=s.steps.length;s.doc.nodesBetween(t,n,(l,o)=>{let c=typeof a=="function"?a(l):a;if(l.isTextblock&&!l.hasMarkup(r,c)&&sMs(s.doc,s.mapping.slice(i).map(o),r)){let d=null;if(r.schema.linebreakReplacement){let p=r.whitespace=="pre",g=!!r.contentMatch.matchType(r.schema.linebreakReplacement);p&&!g?d=!1:!p&&g&&(d=!0)}d===!1&&C6t(s,l,o,i),NWe(s,s.mapping.slice(i).map(o,1),r,void 0,d===null);let u=s.mapping.slice(i),h=u.map(o,1),m=u.map(o+l.nodeSize,1);return s.step(new _0(h,m,h+1,m-1,new Ii(Ua.from(r.create(c,null,l.marks)),0,0),1,!0)),d===!0&&S6t(s,l,o,i),!1}})}function S6t(s,t,n,r){t.forEach((a,i)=>{if(a.isText){let l,o=/\r?\n|\r/g;for(;l=o.exec(a.text);){let c=s.mapping.slice(r).map(n+1+i+l.index);s.replaceWith(c,c+1,t.type.schema.linebreakReplacement.create())}}})}function C6t(s,t,n,r){t.forEach((a,i)=>{if(a.type==a.type.schema.linebreakReplacement){let l=s.mapping.slice(r).map(n+1+i);s.replaceWith(l,l+1,t.type.schema.text(` `))}})}function sMs(s,t,n){let r=s.resolve(t),a=r.index();return r.parent.canReplaceWith(a,a+1,n)}function nMs(s,t,n,r,a){let i=s.doc.nodeAt(t);if(!i)throw new RangeError("No node at given position");n||(n=i.type);let l=n.create(r,null,a||i.marks);if(i.isLeaf)return s.replaceWith(t,t+i.nodeSize,l);if(!n.validContent(i.content))throw new RangeError("Invalid content for node type "+n.name);s.step(new _0(t,t+i.nodeSize,t+1,t+i.nodeSize-1,new Ii(Ua.from(l),0,0),1,!0))}function k3(s,t,n=1,r){let a=s.resolve(t),i=a.depth-n,l=r&&r[r.length-1]||a.parent;if(i<0||a.parent.type.spec.isolating||!a.parent.canReplace(a.index(),a.parent.childCount)||!l.type.validContent(a.parent.content.cutByIndex(a.index(),a.parent.childCount)))return!1;for(let d=a.depth-1,u=n-2;d>i;d--,u--){let h=a.node(d),m=a.index(d);if(h.type.spec.isolating)return!1;let p=h.content.cutByIndex(m,h.childCount),g=r&&r[u+1];g&&(p=p.replaceChild(0,g.type.create(g.attrs)));let x=r&&r[u]||h;if(!h.canReplace(m+1,h.childCount)||!x.type.validContent(p))return!1}let o=a.indexAfter(i),c=r&&r[0];return a.node(i).canReplaceWith(o,o,c?c.type:a.node(i+1).type)}function rMs(s,t,n=1,r){let a=s.doc.resolve(t),i=Ua.empty,l=Ua.empty;for(let o=a.depth,c=a.depth-n,d=n-1;o>c;o--,d--){i=Ua.from(a.node(o).copy(i));let u=r&&r[d];l=Ua.from(u?u.type.create(u.attrs,l):a.node(o).copy(l))}s.step(new Tx(t,t,new Ii(i.append(l),n,n),!0))}function t6(s,t){let n=s.resolve(t),r=n.index();return A6t(n.nodeBefore,n.nodeAfter)&&n.parent.canReplace(r,r+1)}function aMs(s,t){t.content.size||s.type.compatibleContent(t.type);let n=s.contentMatchAt(s.childCount),{linebreakReplacement:r}=s.type.schema;for(let a=0;a0?(i=r.node(a+1),o++,l=r.node(a).maybeChild(o)):(i=r.node(a).maybeChild(o-1),l=r.node(a+1)),i&&!i.isTextblock&&A6t(i,l)&&r.node(a).canReplace(o,o+1))return t;if(a==0)break;t=n<0?r.before(a):r.after(a)}}function iMs(s,t,n){let r=null,{linebreakReplacement:a}=s.doc.type.schema,i=s.doc.resolve(t-n),l=i.node().type;if(a&&l.inlineContent){let u=l.whitespace=="pre",h=!!l.contentMatch.matchType(a);u&&!h?r=!1:!u&&h&&(r=!0)}let o=s.steps.length;if(r===!1){let u=s.doc.resolve(t+n);C6t(s,u.node(),u.before(),o)}l.inlineContent&&NWe(s,t+n-1,l,i.node().contentMatchAt(i.index()),r==null);let c=s.mapping.slice(o),d=c.map(t-n);if(s.step(new Tx(d,c.map(t+n,-1),Ii.empty,!0)),r===!0){let u=s.doc.resolve(d);S6t(s,u.node(),u.before(),s.steps.length)}return s}function oMs(s,t,n){let r=s.resolve(t);if(r.parent.canReplaceWith(r.index(),r.index(),n))return t;if(r.parentOffset==0)for(let a=r.depth-1;a>=0;a--){let i=r.index(a);if(r.node(a).canReplaceWith(i,i,n))return r.before(a+1);if(i>0)return null}if(r.parentOffset==r.parent.content.size)for(let a=r.depth-1;a>=0;a--){let i=r.indexAfter(a);if(r.node(a).canReplaceWith(i,i,n))return r.after(a+1);if(i=0;l--){let o=l==r.depth?0:r.pos<=(r.start(l+1)+r.end(l+1))/2?-1:1,c=r.index(l)+(o>0?1:0),d=r.node(l),u=!1;if(i==1)u=d.canReplace(c,c,a);else{let h=d.contentMatchAt(c).findWrapping(a.firstChild.type);u=h&&d.canReplaceWith(c,c,h[0])}if(u)return o==0?r.pos:o<0?r.before(l+1):r.after(l+1)}return null}function wAe(s,t,n=t,r=Ii.empty){if(t==n&&!r.size)return null;let a=s.resolve(t),i=s.resolve(n);return T6t(a,i,r)?new Tx(t,n,r):new lMs(a,i,r).fit()}function T6t(s,t,n){return!n.openStart&&!n.openEnd&&s.start()==t.start()&&s.parent.canReplace(s.index(),t.index(),n.content)}class lMs{constructor(t,n,r){this.$from=t,this.$to=n,this.unplaced=r,this.frontier=[],this.placed=Ua.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=Ua.from(t.node(a).copy(this.placed))}get depth(){return this.frontier.length-1}fit(){for(;this.unplaced.size;){let d=this.findFittable();d?this.placeNodes(d):this.openMore()||this.dropNode()}let t=this.mustMoveInline(),n=this.placed.size-this.depth-this.$from.depth,r=this.$from,a=this.close(t<0?this.$to:r.doc.resolve(t));if(!a)return null;let i=this.placed,l=r.depth,o=a.depth;for(;l&&o&&i.childCount==1;)i=i.firstChild.content,l--,o--;let c=new Ii(i,l,o);return t>-1?new _0(r.pos,t,this.$to.pos,this.$to.end(),c,n):c.size||r.pos!=this.$to.pos?new Tx(r.pos,a.pos,c):null}findFittable(){let t=this.unplaced.openStart;for(let n=this.unplaced.content,r=0,a=this.unplaced.openEnd;r1&&(a=0),i.type.spec.isolating&&a<=r){t=r;break}n=i.content}for(let n=1;n<=2;n++)for(let r=n==1?t:this.unplaced.openStart;r>=0;r--){let a,i=null;r?(i=aLe(this.unplaced.content,r-1).firstChild,a=i.content):a=this.unplaced.content;let l=a.firstChild;for(let o=this.depth;o>=0;o--){let{type:c,match:d}=this.frontier[o],u,h=null;if(n==1&&(l?d.matchType(l.type)||(h=d.fillBefore(Ua.from(l),!1)):i&&c.compatibleContent(i.type)))return{sliceDepth:r,frontierDepth:o,parent:i,inject:h};if(n==2&&l&&(u=d.findWrapping(l.type)))return{sliceDepth:r,frontierDepth:o,parent:i,wrap:u};if(i&&d.matchType(i.type))break}}}openMore(){let{content:t,openStart:n,openEnd:r}=this.unplaced,a=aLe(t,n);return!a.childCount||a.firstChild.isLeaf?!1:(this.unplaced=new Ii(t,n+1,Math.max(r,a.size+n>=t.size-r?n+1:0)),!0)}dropNode(){let{content:t,openStart:n,openEnd:r}=this.unplaced,a=aLe(t,n);if(a.childCount<=1&&n>0){let i=t.size-n<=n+a.size;this.unplaced=new Ii(kW(t,n-1,1),n-1,i?n-1:r)}else this.unplaced=new Ii(kW(t,n,1),n,r)}placeNodes({sliceDepth:t,frontierDepth:n,parent:r,inject:a,wrap:i}){for(;this.depth>n;)this.closeFrontierNode();if(i)for(let x=0;x1||c==0||x.content.size)&&(h=y,u.push(M6t(x.mark(m.allowedMarks(x.marks)),d==1?c:0,d==o.childCount?p:-1)))}let g=d==o.childCount;g||(p=-1),this.placed=SW(this.placed,n,Ua.from(u)),this.frontier[n].match=h,g&&p<0&&r&&r.type==this.frontier[this.depth].type&&this.frontier.length>1&&this.closeFrontierNode();for(let x=0,y=o;x1&&a==this.$to.end(--r);)++a;return a}findCloseLevel(t){e:for(let n=Math.min(this.depth,t.depth);n>=0;n--){let{match:r,type:a}=this.frontier[n],i=n=0;o--){let{match:c,type:d}=this.frontier[o],u=iLe(t,o,d,c,!0);if(!u||u.childCount)continue e}return{depth:n,fit:l,move:i?t.doc.resolve(t.after(n+1)):t}}}}close(t){let n=this.findCloseLevel(t);if(!n)return null;for(;this.depth>n.depth;)this.closeFrontierNode();n.fit.childCount&&(this.placed=SW(this.placed,n.depth,n.fit)),t=n.move;for(let r=n.depth+1;r<=t.depth;r++){let a=t.node(r),i=a.type.contentMatch.fillBefore(a.content,!0,t.index(r));this.openFrontierNode(a.type,a.attrs,i)}return t}openFrontierNode(t,n=null,r){let a=this.frontier[this.depth];a.match=a.match.matchType(t),this.placed=SW(this.placed,this.depth,Ua.from(t.create(n,r))),this.frontier.push({type:t,match:t.contentMatch})}closeFrontierNode(){let n=this.frontier.pop().match.fillBefore(Ua.empty,!0);n.childCount&&(this.placed=SW(this.placed,this.frontier.length,n))}}function kW(s,t,n){return t==0?s.cutByIndex(n,s.childCount):s.replaceChild(0,s.firstChild.copy(kW(s.firstChild.content,t-1,n)))}function SW(s,t,n){return t==0?s.append(n):s.replaceChild(s.childCount-1,s.lastChild.copy(SW(s.lastChild.content,t-1,n)))}function aLe(s,t){for(let n=0;n1&&(r=r.replaceChild(0,M6t(r.firstChild,t-1,r.childCount==1?n-1:0))),t>0&&(r=s.type.contentMatch.fillBefore(r).append(r),n<=0&&(r=r.append(s.type.contentMatch.matchFragment(r).fillBefore(Ua.empty,!0)))),s.copy(r)}function iLe(s,t,n,r,a){let i=s.node(t),l=a?s.indexAfter(t):s.index(t);if(l==i.childCount&&!n.compatibleContent(i.type))return null;let o=r.fillBefore(i.content,!0,l);return o&&!cMs(n,i.content,l)?o:null}function cMs(s,t,n){for(let r=n;r0;m--,p--){let g=a.node(m).type.spec;if(g.defining||g.definingAsContext||g.isolating)break;l.indexOf(m)>-1?o=m:a.before(m)==p&&l.splice(1,0,-m)}let c=l.indexOf(o),d=[],u=r.openStart;for(let m=r.content,p=0;;p++){let g=m.firstChild;if(d.push(g),p==r.openStart)break;m=g.content}for(let m=u-1;m>=0;m--){let p=d[m],g=dMs(p.type);if(g&&!p.sameMarkup(a.node(Math.abs(o)-1)))u=m;else if(g||!p.type.isTextblock)break}for(let m=r.openStart;m>=0;m--){let p=(m+u+1)%(r.openStart+1),g=d[p];if(g)for(let x=0;x=0&&(s.replace(t,n,r),!(s.steps.length>h));m--){let p=l[m];p<0||(t=a.before(p),n=i.after(p))}}function P6t(s,t,n,r,a){if(tr){let i=a.contentMatchAt(0),l=i.fillBefore(s).append(s);s=l.append(i.matchFragment(l).fillBefore(Ua.empty,!0))}return s}function hMs(s,t,n,r){if(!r.isInline&&t==n&&s.doc.resolve(t).parent.content.size){let a=oMs(s.doc,t,r.type);a!=null&&(t=n=a)}s.replaceRange(t,n,new Ii(Ua.from(r),0,0))}function mMs(s,t,n){let r=s.doc.resolve(t),a=s.doc.resolve(n);if(r.parent.isTextblock&&a.parent.isTextblock&&r.start()!=a.start()&&r.parentOffset==0&&a.parentOffset==0){let l=r.sharedDepth(n),o=!1;for(let c=r.depth;c>l;c--)r.node(c).type.spec.isolating&&(o=!0);for(let c=a.depth;c>l;c--)a.node(c).type.spec.isolating&&(o=!0);if(!o){for(let c=r.depth;c>0&&t==r.start(c);c--)t=r.before(c);for(let c=a.depth;c>0&&n==a.start(c);c--)n=a.before(c);r=s.doc.resolve(t),a=s.doc.resolve(n)}}let i=I6t(r,a);for(let l=0;l0&&(c||r.node(o-1).canReplace(r.index(o-1),a.indexAfter(o-1))))return s.delete(r.before(o),a.after(o))}for(let l=1;l<=r.depth&&l<=a.depth;l++)if(t-r.start(l)==r.depth-l&&n>r.end(l)&&a.end(l)-n!=a.depth-l&&r.start(l-1)==a.start(l-1)&&r.node(l-1).canReplace(r.index(l-1),a.index(l-1)))return s.delete(r.before(l),n);s.delete(t,n)}function I6t(s,t){let n=[],r=Math.min(s.depth,t.depth);for(let a=r;a>=0;a--){let i=s.start(a);if(it.pos+(t.depth-a)||s.node(a).type.spec.isolating||t.node(a).type.spec.isolating)break;(i==t.start(a)||a==s.depth&&a==t.depth&&s.parent.inlineContent&&t.parent.inlineContent&&a&&t.start(a-1)==i-1)&&n.push(a)}return n}class CB extends v1{constructor(t,n,r){super(),this.pos=t,this.attr=n,this.value=r}apply(t){let n=t.nodeAt(this.pos);if(!n)return Dx.fail("No node at attribute step's position");let r=Object.create(null);for(let i in n.attrs)r[i]=n.attrs[i];r[this.attr]=this.value;let a=n.type.create(r,null,n.marks);return Dx.fromReplace(t,this.pos,this.pos+1,new Ii(Ua.from(a),0,n.isLeaf?0:1))}getMap(){return Bw.empty}invert(t){return new CB(this.pos,this.attr,t.nodeAt(this.pos).attrs[this.attr])}map(t){let n=t.mapResult(this.pos,1);return n.deletedAfter?null:new CB(n.pos,this.attr,this.value)}toJSON(){return{stepType:"attr",pos:this.pos,attr:this.attr,value:this.value}}static fromJSON(t,n){if(typeof n.pos!="number"||typeof n.attr!="string")throw new RangeError("Invalid input for AttrStep.fromJSON");return new CB(n.pos,n.attr,n.value)}}v1.jsonID("attr",CB);class lX extends v1{constructor(t,n){super(),this.attr=t,this.value=n}apply(t){let n=Object.create(null);for(let a in t.attrs)n[a]=t.attrs[a];n[this.attr]=this.value;let r=t.type.create(n,t.content,t.marks);return Dx.ok(r)}getMap(){return Bw.empty}invert(t){return new lX(this.attr,t.attrs[this.attr])}map(t){return this}toJSON(){return{stepType:"docAttr",attr:this.attr,value:this.value}}static fromJSON(t,n){if(typeof n.attr!="string")throw new RangeError("Invalid input for DocAttrStep.fromJSON");return new lX(n.attr,n.value)}}v1.jsonID("docAttr",lX);let SU=class extends Error{};SU=function s(t){let n=Error.call(this,t);return n.__proto__=s.prototype,n};SU.prototype=Object.create(Error.prototype);SU.prototype.constructor=SU;SU.prototype.name="TransformError";let SWe=class{constructor(t){this.doc=t,this.steps=[],this.docs=[],this.mapping=new oX}get before(){return this.docs.length?this.docs[0]:this.doc}step(t){let n=this.maybeStep(t);if(n.failed)throw new SU(n.failed);return this}maybeStep(t){let n=t.apply(this.doc);return n.failed||this.addStep(t,n.doc),n}get docChanged(){return this.steps.length>0}changedRange(){let t=1e9,n=-1e9;for(let r=0;r{t=Math.min(t,o),n=Math.max(n,c)})}return t==1e9?null:{from:t,to:n}}addStep(t,n){this.docs.push(this.doc),this.steps.push(t),this.mapping.appendMap(t.getMap()),this.doc=n}replace(t,n=t,r=Ii.empty){let a=wAe(this.doc,t,n,r);return a&&this.step(a),this}replaceWith(t,n,r){return this.replace(t,n,new Ii(Ua.from(r),0,0))}delete(t,n){return this.replace(t,n,Ii.empty)}insert(t,n){return this.replaceWith(t,t,n)}replaceRange(t,n,r){return uMs(this,t,n,r),this}replaceRangeWith(t,n,r){return hMs(this,t,n,r),this}deleteRange(t,n){return mMs(this,t,n),this}lift(t,n){return XTs(this,t,n),this}join(t,n=1){return iMs(this,t,n),this}wrap(t,n){return eMs(this,t,n),this}setBlockType(t,n=t,r,a=null){return tMs(this,t,n,r,a),this}setNodeMarkup(t,n,r=null,a){return nMs(this,t,n,r,a),this}setNodeAttribute(t,n,r){return this.step(new CB(t,n,r)),this}setDocAttribute(t,n){return this.step(new lX(t,n)),this}addNodeMark(t,n){return this.step(new wT(t,n)),this}removeNodeMark(t,n){let r=this.doc.nodeAt(t);if(!r)throw new RangeError("No node at position "+t);if(n instanceof gm)n.isInSet(r.marks)&&this.step(new OO(t,n));else{let a=r.marks,i,l=[];for(;i=n.isInSet(a);)l.push(new OO(t,i)),a=i.removeFromSet(a);for(let o=l.length-1;o>=0;o--)this.step(l[o])}return this}split(t,n=1,r){return rMs(this,t,n,r),this}addMark(t,n,r){return KTs(this,t,n,r),this}removeMark(t,n,r){return YTs(this,t,n,r),this}clearIncompatible(t,n,r){return NWe(this,t,n,r),this}};const oLe=Object.create(null);class $l{constructor(t,n,r){this.$anchor=t,this.$head=n,this.ranges=r||[new L6t(t.min(n),t.max(n))]}get anchor(){return this.$anchor.pos}get head(){return this.$head.pos}get from(){return this.$from.pos}get to(){return this.$to.pos}get $from(){return this.ranges[0].$from}get $to(){return this.ranges[0].$to}get empty(){let t=this.ranges;for(let n=0;n=0;i--){let l=n<0?R9(t.node(0),t.node(i),t.before(i+1),t.index(i),n,r):R9(t.node(0),t.node(i),t.after(i+1),t.index(i)+1,n,r);if(l)return l}return null}static near(t,n=1){return this.findFrom(t,n)||this.findFrom(t,-n)||new Jw(t.node(0))}static atStart(t){return R9(t,t,0,0,1)||new Jw(t)}static atEnd(t){return R9(t,t,t.content.size,t.childCount,-1)||new Jw(t)}static fromJSON(t,n){if(!n||!n.type)throw new RangeError("Invalid input for Selection.fromJSON");let r=oLe[n.type];if(!r)throw new RangeError(`No selection type ${n.type} defined`);return r.fromJSON(t,n)}static jsonID(t,n){if(t in oLe)throw new RangeError("Duplicate use of selection JSON ID "+t);return oLe[t]=n,n.prototype.jsonID=t,n}getBookmark(){return ul.between(this.$anchor,this.$head).getBookmark()}}$l.prototype.visible=!0;class L6t{constructor(t,n){this.$from=t,this.$to=n}}let odt=!1;function ldt(s){!odt&&!s.parent.inlineContent&&(odt=!0,console.warn("TextSelection endpoint not pointing into a node with inline content ("+s.parent.type.name+")"))}class ul extends $l{constructor(t,n=t){ldt(t),ldt(n),super(t,n)}get $cursor(){return this.$anchor.pos==this.$head.pos?this.$head:null}map(t,n){let r=t.resolve(n.map(this.head));if(!r.parent.inlineContent)return $l.near(r);let a=t.resolve(n.map(this.anchor));return new ul(a.parent.inlineContent?a:r,r)}replace(t,n=Ii.empty){if(super.replace(t,n),n==Ii.empty){let r=this.$from.marksAcross(this.$to);r&&t.ensureMarks(r)}}eq(t){return t instanceof ul&&t.anchor==this.anchor&&t.head==this.head}getBookmark(){return new jAe(this.anchor,this.head)}toJSON(){return{type:"text",anchor:this.anchor,head:this.head}}static fromJSON(t,n){if(typeof n.anchor!="number"||typeof n.head!="number")throw new RangeError("Invalid input for TextSelection.fromJSON");return new ul(t.resolve(n.anchor),t.resolve(n.head))}static create(t,n,r=n){let a=t.resolve(n);return new this(a,r==n?a:t.resolve(r))}static between(t,n,r){let a=t.pos-n.pos;if((!r||a)&&(r=a>=0?1:-1),!n.parent.inlineContent){let i=$l.findFrom(n,r,!0)||$l.findFrom(n,-r,!0);if(i)n=i.$head;else return $l.near(n,r)}return t.parent.inlineContent||(a==0?t=n:(t=($l.findFrom(t,-r,!0)||$l.findFrom(t,r,!0)).$anchor,t.pos0?0:1);a>0?l=0;l+=a){let o=t.child(l);if(o.isAtom){if(!i&&hl.isSelectable(o))return hl.create(s,n-(a<0?o.nodeSize:0))}else{let c=R9(s,o,n+a,a<0?o.childCount:0,a,i);if(c)return c}n+=o.nodeSize*a}return null}function cdt(s,t,n){let r=s.steps.length-1;if(r{l==null&&(l=u)}),s.setSelection($l.near(s.doc.resolve(l),n))}const ddt=1,gre=2,udt=4;class pMs extends SWe{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|=gre,this}ensureMarks(t){return gm.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&gre)>0}addStep(t,n){super.addStep(t,n),this.updated=this.updated&~gre,this.storedMarks=null}setTime(t){return this.time=t,this}replaceSelection(t){return this.selection.replace(this,t),this}replaceSelectionWith(t,n=!0){let r=this.selection;return n&&(t=t.mark(this.storedMarks||(r.empty?r.$from.marks():r.$from.marksAcross(r.$to)||gm.none))),r.replaceWith(this,t),this}deleteSelection(){return this.selection.replace(this),this}insertText(t,n,r){let a=this.doc.type.schema;if(n==null)return t?this.replaceSelectionWith(a.text(t),!0):this.deleteSelection();{if(r==null&&(r=n),!t)return this.deleteRange(n,r);let i=this.storedMarks;if(!i){let l=this.doc.resolve(n);i=r==n?l.marks():l.marksAcross(this.doc.resolve(r))}return this.replaceRangeWith(n,r,a.text(t,i)),!this.selection.empty&&this.selection.to==n+t.length&&this.setSelection($l.near(this.selection.$to)),this}}setMeta(t,n){return this.meta[typeof t=="string"?t:t.key]=n,this}getMeta(t){return this.meta[typeof t=="string"?t:t.key]}get isGeneric(){for(let t in this.meta)return!1;return!0}scrollIntoView(){return this.updated|=udt,this}get scrolledIntoView(){return(this.updated&udt)>0}}function hdt(s,t){return!t||!s?s:s.bind(t)}class CW{constructor(t,n,r){this.name=t,this.init=hdt(n.init,r),this.apply=hdt(n.apply,r)}}const gMs=[new CW("doc",{init(s){return s.doc||s.schema.topNodeType.createAndFill()},apply(s){return s.doc}}),new CW("selection",{init(s,t){return s.selection||$l.atStart(t.doc)},apply(s){return s.selection}}),new CW("storedMarks",{init(s){return s.storedMarks||null},apply(s,t,n,r){return r.selection.$cursor?s.storedMarks:null}}),new CW("scrollToSelection",{init(){return 0},apply(s,t){return s.scrolledIntoView?t+1:t}})];class lLe{constructor(t,n){this.schema=t,this.plugins=[],this.pluginsByKey=Object.create(null),this.fields=gMs.slice(),n&&n.forEach(r=>{if(this.pluginsByKey[r.key])throw new RangeError("Adding different instances of a keyed plugin ("+r.key+")");this.plugins.push(r),this.pluginsByKey[r.key]=r,r.spec.state&&this.fields.push(new CW(r.key,r.spec.state,r))})}}class gz{constructor(t){this.config=t}get schema(){return this.config.schema}get plugins(){return this.config.plugins}apply(t){return this.applyTransaction(t).state}filterTransaction(t,n=-1){for(let r=0;rr.toJSON())),t&&typeof t=="object")for(let r in t){if(r=="doc"||r=="selection")throw new RangeError("The JSON fields `doc` and `selection` are reserved");let a=t[r],i=a.spec.state;i&&i.toJSON&&(n[r]=i.toJSON.call(a,this[a.key]))}return n}static fromJSON(t,n,r){if(!n)throw new RangeError("Invalid input for EditorState.fromJSON");if(!t.schema)throw new RangeError("Required config field 'schema' missing");let a=new lLe(t.schema,t.plugins),i=new gz(a);return a.fields.forEach(l=>{if(l.name=="doc")i.doc=cM.fromJSON(t.schema,n.doc);else if(l.name=="selection")i.selection=$l.fromJSON(i.doc,n.selection);else if(l.name=="storedMarks")n.storedMarks&&(i.storedMarks=n.storedMarks.map(t.schema.markFromJSON));else{if(r)for(let o in r){let c=r[o],d=c.spec.state;if(c.key==l.name&&d&&d.fromJSON&&Object.prototype.hasOwnProperty.call(n,o)){i[l.name]=d.fromJSON.call(c,t,n[o],i);return}}i[l.name]=l.init(t,i)}}),i}}function R6t(s,t,n){for(let r in s){let a=s[r];a instanceof Function?a=a.bind(t):r=="handleDOMEvents"&&(a=R6t(a,t,{})),n[r]=a}return n}class Iy{constructor(t){this.spec=t,this.props={},t.props&&R6t(t.props,this,this.props),this.key=t.key?t.key.key:D6t("plugin")}getState(t){return t[this.key]}}const cLe=Object.create(null);function D6t(s){return s in cLe?s+"$"+ ++cLe[s]:(cLe[s]=0,s+"$")}class b1{constructor(t="key"){this.key=D6t(t)}get(t){return t.config.pluginsByKey[this.key]}getState(t){return t[this.key]}}const Q0=function(s){for(var t=0;;t++)if(s=s.previousSibling,!s)return t},CU=function(s){let t=s.assignedSlot||s.parentNode;return t&&t.nodeType==11?t.host:t};let c9e=null;const gC=function(s,t,n){let r=c9e||(c9e=document.createRange());return r.setEnd(s,n??s.nodeValue.length),r.setStart(s,t||0),r},xMs=function(){c9e=null},FO=function(s,t,n,r){return n&&(mdt(s,t,n,r,-1)||mdt(s,t,n,r,1))},yMs=/^(img|br|input|textarea|hr)$/i;function mdt(s,t,n,r,a){for(var i;;){if(s==n&&t==r)return!0;if(t==(a<0?0:a2(s))){let l=s.parentNode;if(!l||l.nodeType!=1||Tee(s)||yMs.test(s.nodeName)||s.contentEditable=="false")return!1;t=Q0(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?a2(s):0}else return!1}}function a2(s){return s.nodeType==3?s.nodeValue.length:s.childNodes.length}function vMs(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=a2(s)}else if(s.parentNode&&!Tee(s))t=Q0(s),s=s.parentNode;else return null}}function bMs(s,t){for(;;){if(s.nodeType==3&&t2),Qj=AU||(G5?/Mac/.test(G5.platform):!1),z6t=G5?/Win/.test(G5.platform):!1,i3=/Android \d/.test(s6),Mee=!!fdt&&"webkitFontSmoothing"in fdt.documentElement.style,NMs=Mee?+(/\bAppleWebKit\/(\d+)/.exec(navigator.userAgent)||[0,0])[1]:0;function kMs(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 G4(s,t){return typeof s=="number"?s:s[t]}function SMs(s){let t=s.getBoundingClientRect(),n=t.width/s.offsetWidth||1,r=t.height/s.offsetHeight||1;return{left:t.left,right:t.left+s.clientWidth*n,top:t.top,bottom:t.top+s.clientHeight*r}}function pdt(s,t,n){if(!m9e(t)&&t.left==0)return;let r=s.someProp("scrollThreshold")||0,a=s.someProp("scrollMargin")||5,i=s.dom.ownerDocument;for(let l=n||s.dom;l;){if(l.nodeType!=1){l=CU(l);continue}let o=l,c=o==i.body,d=c?kMs(i):SMs(o),u=0,h=0;if(t.topd.bottom-G4(r,"bottom")&&(h=t.bottom-t.top>d.bottom-d.top?t.top+G4(a,"top")-d.top:t.bottom-d.bottom+G4(a,"bottom")),t.leftd.right-G4(r,"right")&&(u=t.right-d.right+G4(a,"right")),u||h)if(c)i.defaultView.scrollBy(u,h);else{let p=o.scrollLeft,g=o.scrollTop;h&&(o.scrollTop+=h),u&&(o.scrollLeft+=u);let x=o.scrollLeft-p,y=o.scrollTop-g;t={left:t.left-x,top:t.top-y,right:t.right-x,bottom:t.bottom-y}}let m=c?"fixed":getComputedStyle(l).position;if(/^(fixed|sticky)$/.test(m))break;l=m=="absolute"?l.offsetParent:CU(l)}}function CMs(s){let t=s.dom.getBoundingClientRect(),n=Math.max(0,t.top),r,a;for(let i=(t.left+t.right)/2,l=n+1;l=n-20){r=o,a=c.top;break}}return{refDOM:r,refTop:a,stack:B6t(s.dom)}}function B6t(s){let t=[],n=s.ownerDocument;for(let r=s;r&&(t.push({dom:r,top:r.scrollTop,left:r.scrollLeft}),s!=n);r=CU(r));return t}function AMs({refDOM:s,refTop:t,stack:n}){let r=s?s.getBoundingClientRect().top:0;$6t(n,r==0?0:r-t)}function $6t(s,t){for(let n=0;n=o){l=Math.max(g.bottom,l),o=Math.min(g.top,o);let x=g.left>t.left?g.left-t.left:g.right=(g.left+g.right)/2?1:0));continue}}else g.top>t.top&&!c&&g.left<=t.left&&g.right>=t.left&&(c=u,d={left:Math.max(g.left,Math.min(g.right,t.left)),top:g.top});!n&&(t.left>=g.right&&t.top>=g.top||t.left>=g.left&&t.top>=g.bottom)&&(i=h+1)}}return!n&&c&&(n=c,a=d,r=0),n&&n.nodeType==3?TMs(n,a):!n||r&&n.nodeType==1?{node:s,offset:i}:U6t(n,a)}function TMs(s,t){let n=s.nodeValue.length,r=document.createRange(),a;for(let i=0;i=(l.left+l.right)/2?1:0)};break}}return r.detach(),a||{node:s,offset:0}}function AWe(s,t){return s.left>=t.left-1&&s.left<=t.right+1&&s.top>=t.top-1&&s.top<=t.bottom+1}function MMs(s,t){let n=s.parentNode;return n&&/^li$/i.test(n.nodeName)&&t.left(l.left+l.right)/2?1:-1}return s.docView.posFromDOM(r,a,i)}function IMs(s,t,n,r){let a=-1;for(let i=t,l=!1;i!=s.dom;){let o=s.docView.nearestDesc(i,!0),c;if(!o)return null;if(o.dom.nodeType==1&&(o.node.isBlock&&o.parent||!o.contentDOM)&&((c=o.dom.getBoundingClientRect()).width||c.height)&&(o.node.isBlock&&o.parent&&!/^T(R|BODY|HEAD|FOOT)$/.test(o.dom.nodeName)&&(!l&&c.left>r.left||c.top>r.top?a=o.posBefore:(!l&&c.right-1?a:s.docView.posFromDOM(t,n,-1)}function q6t(s,t,n){let r=s.childNodes.length;if(r&&n.topt.top&&a++}let d;Mee&&a&&r.nodeType==1&&(d=r.childNodes[a-1]).nodeType==1&&d.contentEditable=="false"&&d.getBoundingClientRect().top>=t.top&&a--,r==s.dom&&a==r.childNodes.length-1&&r.lastChild.nodeType==1&&t.top>r.lastChild.getBoundingClientRect().bottom?o=s.state.doc.content.size:(a==0||r.nodeType!=1||r.childNodes[a-1].nodeName!="BR")&&(o=IMs(s,r,a,t))}o==null&&(o=PMs(s,l,t));let c=s.docView.nearestDesc(l,!0);return{pos:o,inside:c?c.posAtStart-c.border:-1}}function m9e(s){return s.top=0&&a==r.nodeValue.length?(c--,u=1):n<0?c--:d++,fG(nE(gC(r,c,d),u),u<0)}if(!s.state.doc.resolve(t-(i||0)).parent.inlineContent){if(i==null&&a&&(n<0||a==a2(r))){let c=r.childNodes[a-1];if(c.nodeType==1)return dLe(c.getBoundingClientRect(),!1)}if(i==null&&a=0)}if(i==null&&a&&(n<0||a==a2(r))){let c=r.childNodes[a-1],d=c.nodeType==3?gC(c,a2(c)-(l?0:1)):c.nodeType==1&&(c.nodeName!="BR"||!c.nextSibling)?c:null;if(d)return fG(nE(d,1),!1)}if(i==null&&a=0)}function fG(s,t){if(s.width==0)return s;let n=t?s.left:s.right;return{top:s.top,bottom:s.bottom,left:n,right:n}}function dLe(s,t){if(s.height==0)return s;let n=t?s.top:s.bottom;return{top:n,bottom:n,left:s.left,right:s.right}}function H6t(s,t,n){let r=s.state,a=s.root.activeElement;r!=t&&s.updateState(t),a!=s.dom&&s.focus();try{return n()}finally{r!=t&&s.updateState(r),a!=s.dom&&a&&a.focus()}}function DMs(s,t,n){let r=t.selection,a=n=="up"?r.$from:r.$to;return H6t(s,t,()=>{let{node:i}=s.docView.domFromPos(a.pos,n=="up"?-1:1);for(;;){let o=s.docView.nearestDesc(i,!0);if(!o)break;if(o.node.isBlock){i=o.contentDOM||o.dom;break}i=o.dom.parentNode}let l=V6t(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=gC(o,0,o.nodeValue.length).getClientRects();else continue;for(let d=0;du.top+1&&(n=="up"?l.top-u.top>(u.bottom-l.top)*2:u.bottom-l.bottom>(l.bottom-u.top)*2))return!1}}return!0})}const OMs=/[\u0590-\u08ac]/;function FMs(s,t,n){let{$head:r}=t.selection;if(!r.parent.isTextblock)return!1;let a=r.parentOffset,i=!a,l=a==r.parent.content.size,o=s.domSelection();return o?!OMs.test(r.parent.textContent)||!o.modify?n=="left"||n=="backward"?i:l:H6t(s,t,()=>{let{focusNode:c,focusOffset:d,anchorNode:u,anchorOffset:h}=s.domSelectionRange(),m=o.caretBidiLevel;o.modify("move",n,"character");let p=r.depth?s.docView.domAfterPos(r.before()):s.dom,{focusNode:g,focusOffset:x}=s.domSelectionRange(),y=g&&!p.contains(g.nodeType==1?g:g.parentNode)||c==g&&d==x;try{o.collapse(u,h),c&&(c!=u||d!=h)&&o.extend&&o.extend(c,d)}catch{}return m!=null&&(o.caretBidiLevel=m),y}):r.pos==r.start()||r.pos==r.end()}let gdt=null,xdt=null,ydt=!1;function zMs(s,t,n){return gdt==t&&xdt==n?ydt:(gdt=t,xdt=n,ydt=n=="up"||n=="down"?DMs(s,t,n):FMs(s,t,n))}const E2=0,vdt=1,oD=2,hk=3;class Pee{constructor(t,n,r,a){this.parent=t,this.children=n,this.dom=r,this.contentDOM=a,this.dirty=E2,r.pmViewDesc=this}matchesWidget(t){return!1}matchesMark(t){return!1}matchesNode(t,n,r){return!1}matchesHack(t){return!1}parseRule(t){return null}stopEvent(t){return!1}get size(){let t=0;for(let n=0;nQ0(this.contentDOM);else if(this.contentDOM&&this.contentDOM!=this.dom&&this.dom.contains(this.contentDOM))a=t.compareDocumentPosition(this.contentDOM)&2;else if(this.dom.firstChild){if(n==0)for(let i=t;;i=i.parentNode){if(i==this.dom){a=!1;break}if(i.previousSibling)break}if(a==null&&n==t.childNodes.length)for(let i=t;;i=i.parentNode){if(i==this.dom){a=!0;break}if(i.nextSibling)break}}return a??r>0?this.posAtEnd:this.posAtStart}nearestDesc(t,n=!1){for(let r=!0,a=t;a;a=a.parentNode){let i=this.getDesc(a),l;if(i&&(!n||i.node))if(r&&(l=i.nodeDOM)&&!(l.nodeType==1?l.contains(t.nodeType==1?t:t.parentNode):l==t))r=!1;else return i}}getDesc(t){let n=t.pmViewDesc;for(let r=n;r;r=r.parent)if(r==this)return n}posFromDOM(t,n,r){for(let a=t;a;a=a.parentNode){let i=this.getDesc(a);if(i)return i.localPosFromDOM(t,n,r)}return-1}descAt(t){for(let n=0,r=0;nt||l instanceof W6t){a=t-i;break}i=o}if(a)return this.children[r].domFromPos(a-this.children[r].border,n);for(let i;r&&!(i=this.children[r-1]).size&&i instanceof G6t&&i.side>=0;r--);if(n<=0){let i,l=!0;for(;i=r?this.children[r-1]:null,!(!i||i.dom.parentNode==this.contentDOM);r--,l=!1);return i&&n&&l&&!i.border&&!i.domAtom?i.domFromPos(i.size,n):{node:this.contentDOM,offset:i?Q0(i.dom)+1:0}}else{let i,l=!0;for(;i=r=u&&n<=d-c.border&&c.node&&c.contentDOM&&this.contentDOM.contains(c.contentDOM))return c.parseRange(t,n,u);t=l;for(let h=o;h>0;h--){let m=this.children[h-1];if(m.size&&m.dom.parentNode==this.contentDOM&&!m.emptyChildAt(1)){a=Q0(m.dom)+1;break}t-=m.size}a==-1&&(a=0)}if(a>-1&&(d>n||o==this.children.length-1)){n=d;for(let u=o+1;ug&&ln){let g=o;o=c,c=g}let p=document.createRange();p.setEnd(c.node,c.offset),p.setStart(o.node,o.offset),d.removeAllRanges(),d.addRange(p)}}ignoreMutation(t){return!this.contentDOM&&t.type!="selection"}get contentLost(){return this.contentDOM&&this.contentDOM!=this.dom&&!this.dom.contains(this.contentDOM)}markDirty(t,n){for(let r=0,a=0;a=r:tr){let o=r+i.border,c=l-i.border;if(t>=o&&n<=c){this.dirty=t==r||n==l?oD:vdt,t==o&&n==c&&(i.contentLost||i.dom.parentNode!=this.contentDOM)?i.dirty=hk:i.markDirty(t-o,n-o);return}else i.dirty=i.dom==i.contentDOM&&i.dom.parentNode==this.contentDOM&&!i.children.length?oD:hk}r=l}this.dirty=oD}markParentsDirty(){let t=1;for(let n=this.parent;n;n=n.parent,t++){let r=t==1?oD:vdt;n.dirty{if(!i)return a;if(i.parent)return i.parent.posBeforeChild(i)})),!n.type.spec.raw){if(l.nodeType!=1){let o=document.createElement("span");o.appendChild(l),l=o}l.contentEditable="false",l.classList.add("ProseMirror-widget")}super(t,[],l,null),this.widget=n,this.widget=n,i=this}matchesWidget(t){return this.dirty==E2&&t.type.eq(this.widget.type)}parseRule(){return{ignore:!0}}stopEvent(t){let n=this.widget.spec.stopEvent;return n?n(t):!1}ignoreMutation(t){return t.type!="selection"||this.widget.spec.ignoreSelection}destroy(){this.widget.type.destroy(this.dom),super.destroy()}get domAtom(){return!0}get ignoreForSelection(){return!!this.widget.type.spec.relaxedSide}get side(){return this.widget.type.side}}class BMs extends Pee{constructor(t,n,r,a){super(t,[],n,null),this.textDOM=r,this.text=a}get size(){return this.text.length}localPosFromDOM(t,n){return t!=this.textDOM?this.posAtStart+(n?this.size:0):this.posAtStart+n}domFromPos(t){return{node:this.textDOM,offset:t}}ignoreMutation(t){return t.type==="characterData"&&t.target.nodeValue==t.oldValue}}class uM extends Pee{constructor(t,n,r,a,i){super(t,[],r,a),this.mark=n,this.spec=i}static create(t,n,r,a){let i=a.nodeViews[n.type.name],l=i&&i(n,a,r);return(!l||!l.dom)&&(l=kF.renderSpec(document,n.type.spec.toDOM(n,r),null,n.attrs)),new uM(t,n,l.dom,l.contentDOM||l.dom,l)}parseRule(){return this.dirty&hk||this.mark.type.spec.reparseInView?null:{mark:this.mark.type.name,attrs:this.mark.attrs,contentElement:this.contentDOM}}matchesMark(t){return this.dirty!=hk&&this.mark.eq(t)}markDirty(t,n){if(super.markDirty(t,n),this.dirty!=E2){let r=this.parent;for(;!r.node;)r=r.parent;r.dirty0&&(i=p9e(i,0,t,r));for(let o=0;o{if(!c)return l;if(c.parent)return c.parent.posBeforeChild(c)},r,a),u=d&&d.dom,h=d&&d.contentDOM;if(n.isText){if(!u)u=document.createTextNode(n.text);else if(u.nodeType!=3)throw new RangeError("Text must be rendered as a DOM text node")}else u||({dom:u,contentDOM:h}=kF.renderSpec(document,n.type.spec.toDOM(n),null,n.attrs));!h&&!n.isText&&u.nodeName!="BR"&&(u.hasAttribute("contenteditable")||(u.contentEditable="false"),n.type.spec.draggable&&(u.draggable=!0));let m=u;return u=Z6t(u,r,n),d?c=new $Ms(t,n,r,a,u,h||null,m,d):n.isText?new kAe(t,n,r,a,u,m):new hM(t,n,r,a,u,h||null,m)}parseRule(t){if(this.node.type.spec.reparseInView)return null;let n={node:this.node.type.name,attrs:this.node.attrs};if(this.node.type.whitespace=="pre"&&(n.preserveWhitespace="full"),!this.contentDOM)n.getContent=()=>this.node.content;else if(!this.contentLost)n.contentElement=this.contentDOM;else{for(let r=this.children.length-1;r>=0;r--){let a=this.children[r];if(this.dom.contains(a.dom.parentNode)){n.contentElement=a.dom.parentNode;break}}if(!n.contentElement){let r=t&&t.find(a=>a.nodeType==1&&t.indexOf(a.parentNode)<0&&this.dom.contains(a));r?n.contentElement=r:n.getContent=()=>Ua.empty}}return n}matchesNode(t,n,r){return this.dirty==E2&&t.eq(this.node)&&MSe(n,this.outerDeco)&&r.eq(this.innerDeco)}get size(){return this.node.nodeSize}get border(){return this.node.isLeaf?0:1}updateChildren(t,n){let r=this.node.inlineContent,a=n,i=t.composing?this.localCompositionInfo(t,n):null,l=i&&i.pos>-1?i:null,o=i&&i.pos<0,c=new qMs(this,l&&l.node,t);GMs(this.node,this.innerDeco,(d,u,h)=>{d.spec.marks?c.syncToMarks(d.spec.marks,r,t,u):d.type.side>=0&&!h&&c.syncToMarks(u==this.node.childCount?gm.none:this.node.child(u).marks,r,t,u),c.placeWidget(d,t,a)},(d,u,h,m)=>{c.syncToMarks(d.marks,r,t,m);let p;c.findNodeMatch(d,u,h,m)||o&&t.state.selection.from>a&&t.state.selection.to-1&&c.updateNodeAt(d,u,h,p,t)||c.updateNextNode(d,u,h,t,m,a)||c.addNode(d,u,h,t,a),a+=d.nodeSize}),c.syncToMarks([],r,t,0),this.node.isTextblock&&c.addTextblockHacks(),c.destroyRest(),(c.changed||this.dirty==oD)&&(l&&this.protectLocalComposition(t,l),K6t(this.contentDOM,this.children,t),AU&&WMs(this.dom))}localCompositionInfo(t,n){let{from:r,to:a}=t.state.selection;if(!(t.state.selection instanceof ul)||rn+this.node.content.size)return null;let i=t.input.compositionNode;if(!i||!this.dom.contains(i.parentNode))return null;if(this.node.inlineContent){let l=i.nodeValue,o=KMs(this.node.content,l,r-n,a-n);return o<0?null:{node:i,pos:o,text:l}}else return{node:i,pos:-1,text:""}}protectLocalComposition(t,{node:n,pos:r,text:a}){if(this.getDesc(n))return;let i=n;for(;i.parentNode!=this.contentDOM;i=i.parentNode){for(;i.previousSibling;)i.parentNode.removeChild(i.previousSibling);for(;i.nextSibling;)i.parentNode.removeChild(i.nextSibling);i.pmViewDesc&&(i.pmViewDesc=void 0)}let l=new BMs(this,i,n,a);t.input.compositionNodes.push(l),this.children=p9e(this.children,r,r+a.length,t,l)}update(t,n,r,a){return this.dirty==hk||!t.sameMarkup(this.node)?!1:(this.updateInner(t,n,r,a),!0)}updateInner(t,n,r,a){this.updateOuterDeco(n),this.node=t,this.innerDeco=r,this.contentDOM&&this.updateChildren(a,this.posAtStart),this.dirty=E2}updateOuterDeco(t){if(MSe(t,this.outerDeco))return;let n=this.nodeDOM.nodeType!=1,r=this.dom;this.dom=Y6t(this.dom,this.nodeDOM,f9e(this.outerDeco,this.node,n),f9e(t,this.node,n)),this.dom!=r&&(r.pmViewDesc=void 0,this.dom.pmViewDesc=this),this.outerDeco=t}selectNode(){this.nodeDOM.nodeType==1&&(this.nodeDOM.classList.add("ProseMirror-selectednode"),(this.contentDOM||!this.node.type.spec.draggable)&&(this.nodeDOM.draggable=!0))}deselectNode(){this.nodeDOM.nodeType==1&&(this.nodeDOM.classList.remove("ProseMirror-selectednode"),(this.contentDOM||!this.node.type.spec.draggable)&&this.nodeDOM.removeAttribute("draggable"))}get domAtom(){return this.node.isAtom}}function bdt(s,t,n,r,a){Z6t(r,t,s);let i=new hM(void 0,s,t,n,r,r,r);return i.contentDOM&&i.updateChildren(a,0),i}class kAe extends hM{constructor(t,n,r,a,i,l){super(t,n,r,a,i,null,l)}parseRule(){let t=this.nodeDOM.parentNode;for(;t&&t!=this.dom&&!t.pmIsDeco;)t=t.parentNode;return{skip:t||!0}}update(t,n,r,a){return this.dirty==hk||this.dirty!=E2&&!this.inParent()||!t.sameMarkup(this.node)?!1:(this.updateOuterDeco(n),(this.dirty!=E2||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=E2,!0)}inParent(){let t=this.parent.contentDOM;for(let n=this.nodeDOM;n;n=n.parentNode)if(n==t)return!0;return!1}domFromPos(t){return{node:this.nodeDOM,offset:t}}localPosFromDOM(t,n,r){return t==this.nodeDOM?this.posAtStart+Math.min(n,this.node.text.length):super.localPosFromDOM(t,n,r)}ignoreMutation(t){return t.type!="characterData"&&t.type!="selection"}slice(t,n,r){let a=this.node.cut(t,n),i=document.createTextNode(a.text);return new kAe(this.parent,a,this.outerDeco,this.innerDeco,i,i)}markDirty(t,n){super.markDirty(t,n),this.dom!=this.nodeDOM&&(t==0||n==this.nodeDOM.nodeValue.length)&&(this.dirty=hk)}get domAtom(){return!1}isText(t){return this.node.text==t}}class W6t extends Pee{parseRule(){return{ignore:!0}}matchesHack(t){return this.dirty==E2&&this.dom.nodeName==t}get domAtom(){return!0}get ignoreForCoords(){return this.dom.nodeName=="IMG"}}class $Ms extends hM{constructor(t,n,r,a,i,l,o,c){super(t,n,r,a,i,l,o),this.spec=c}update(t,n,r,a){if(this.dirty==hk)return!1;if(this.spec.update&&(this.node.type==t.type||this.spec.multiType)){let i=this.spec.update(t,n,r);return i&&this.updateInner(t,n,r,a),i}else return!this.contentDOM&&!t.isLeaf?!1:super.update(t,n,r,a)}selectNode(){this.spec.selectNode?this.spec.selectNode():super.selectNode()}deselectNode(){this.spec.deselectNode?this.spec.deselectNode():super.deselectNode()}setSelection(t,n,r,a){this.spec.setSelection?this.spec.setSelection(t,n,r.root):super.setSelection(t,n,r,a)}destroy(){this.spec.destroy&&this.spec.destroy(),super.destroy()}stopEvent(t){return this.spec.stopEvent?this.spec.stopEvent(t):!1}ignoreMutation(t){return this.spec.ignoreMutation?this.spec.ignoreMutation(t):super.ignoreMutation(t)}}function K6t(s,t,n){let r=s.firstChild,a=!1;for(let i=0;i>1,o=Math.min(l,t.length);for(;i-1)c>this.index&&(this.changed=!0,this.destroyBetween(this.index,c)),this.top=this.top.children[this.index];else{let u=uM.create(this.top,t[l],n,r);this.top.children.splice(this.index,0,u),this.top=u,this.changed=!0}this.index=0,l++}}findNodeMatch(t,n,r,a){let i=-1,l;if(a>=this.preMatch.index&&(l=this.preMatch.matches[a-this.preMatch.index]).parent==this.top&&l.matchesNode(t,n,r))i=this.top.children.indexOf(l,this.index);else for(let o=this.index,c=Math.min(this.top.children.length,o+5);o0;){let o;for(;;)if(r){let d=n.children[r-1];if(d instanceof uM)n=d,r=d.children.length;else{o=d,r--;break}}else{if(n==t)break e;r=n.parent.children.indexOf(n),n=n.parent}let c=o.node;if(c){if(c!=s.child(a-1))break;--a,i.set(o,a),l.push(o)}}return{index:a,matched:i,matches:l.reverse()}}function HMs(s,t){return s.type.side-t.type.side}function GMs(s,t,n,r){let a=t.locals(s),i=0;if(a.length==0){for(let d=0;di;)o.push(a[l++]);let g=i+m.nodeSize;if(m.isText){let y=g;l!y.inline):o.slice();r(m,x,t.forChild(i,m),p),i=g}}function WMs(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 KMs(s,t,n,r){for(let a=0,i=0;a=n){if(i>=r&&c.slice(r-t.length-o,r-o)==t)return r-t.length;let d=o=0&&d+t.length+o>=n)return o+d;if(n==r&&c.length>=r+t.length-o&&c.slice(r-o,r-o+t.length)==t)return r}}return-1}function p9e(s,t,n,r,a){let i=[];for(let l=0,o=0;l=n||u<=t?i.push(c):(dn&&i.push(c.slice(n-d,c.size,r)))}return i}function EWe(s,t=null){let n=s.domSelectionRange(),r=s.state.doc;if(!n.focusNode)return null;let a=s.docView.nearestDesc(n.focusNode),i=a&&a.size==0,l=s.docView.posFromDOM(n.focusNode,n.focusOffset,1);if(l<0)return null;let o=r.resolve(l),c,d;if(NAe(n)){for(c=l;a&&!a.node;)a=a.parent;let h=a.node;if(a&&h.isAtom&&hl.isSelectable(h)&&a.parent&&!(h.isInline&&_Ms(n.focusNode,n.focusOffset,a.dom))){let m=a.posBefore;d=new hl(l==m?o:r.resolve(m))}}else{if(n instanceof s.dom.ownerDocument.defaultView.Selection&&n.rangeCount>1){let h=l,m=l;for(let p=0;p{(n.anchorNode!=r||n.anchorOffset!=a)&&(t.removeEventListener("selectionchange",s.input.hideSelectionGuard),setTimeout(()=>{(!X6t(s)||s.state.selection.visible)&&s.dom.classList.remove("ProseMirror-hideselection")},20))})}function ZMs(s){let t=s.domSelection();if(!t)return;let n=s.cursorWrapper.dom,r=n.nodeName=="IMG";r?t.collapse(n.parentNode,Q0(n)+1):t.collapse(n,0),!r&&!s.state.selection.visible&&k_&&dM<=11&&(n.disabled=!0,n.disabled=!1)}function Q6t(s,t){if(t instanceof hl){let n=s.docView.descAt(t.from);n!=s.lastSelectedViewDesc&&(kdt(s),n&&n.selectNode(),s.lastSelectedViewDesc=n)}else kdt(s)}function kdt(s){s.lastSelectedViewDesc&&(s.lastSelectedViewDesc.parent&&s.lastSelectedViewDesc.deselectNode(),s.lastSelectedViewDesc=void 0)}function TWe(s,t,n,r){return s.someProp("createSelectionBetween",a=>a(s,t,n))||ul.between(t,n,r)}function Sdt(s){return s.editable&&!s.hasFocus()?!1:J6t(s)}function J6t(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 XMs(s){let t=s.docView.domFromPos(s.state.selection.anchor,0),n=s.domSelectionRange();return FO(t.node,t.offset,n.anchorNode,n.anchorOffset)}function g9e(s,t){let{$anchor:n,$head:r}=s.selection,a=t>0?n.max(r):n.min(r),i=a.parent.inlineContent?a.depth?s.doc.resolve(t>0?a.after():a.before()):null:a;return i&&$l.findFrom(i,t)}function pE(s,t){return s.dispatch(s.state.tr.setSelection(t).scrollIntoView()),!0}function Cdt(s,t,n){let r=s.state.selection;if(r instanceof ul)if(n.indexOf("s")>-1){let{$head:a}=r,i=a.textOffset?null:t<0?a.nodeBefore:a.nodeAfter;if(!i||i.isText||!i.isLeaf)return!1;let l=s.state.doc.resolve(a.pos+i.nodeSize*(t<0?-1:1));return pE(s,new ul(r.$anchor,l))}else if(r.empty){if(s.endOfTextblock(t>0?"forward":"backward")){let a=g9e(s.state,t);return a&&a instanceof hl?pE(s,a):!1}else if(!(Qj&&n.indexOf("m")>-1)){let a=r.$head,i=a.textOffset?null:t<0?a.nodeBefore:a.nodeAfter,l;if(!i||i.isText)return!1;let o=t<0?a.pos-i.nodeSize:a.pos;return i.isAtom||(l=s.docView.descAt(o))&&!l.contentDOM?hl.isSelectable(i)?pE(s,new hl(t<0?s.state.doc.resolve(a.pos-i.nodeSize):a)):Mee?pE(s,new ul(s.state.doc.resolve(t<0?o:o+i.nodeSize))):!1:!1}}else return!1;else{if(r instanceof hl&&r.node.isInline)return pE(s,new ul(t>0?r.$to:r.$from));{let a=g9e(s.state,t);return a?pE(s,a):!1}}}function PSe(s){return s.nodeType==3?s.nodeValue.length:s.childNodes.length}function TY(s,t){let n=s.pmViewDesc;return n&&n.size==0&&(t<0||s.nextSibling||s.nodeName!="BR")}function W7(s,t){return t<0?QMs(s):JMs(s)}function QMs(s){let t=s.domSelectionRange(),n=t.focusNode,r=t.focusOffset;if(!n)return;let a,i,l=!1;for(A2&&n.nodeType==1&&r0){if(n.nodeType!=1)break;{let o=n.childNodes[r-1];if(TY(o,-1))a=n,i=--r;else if(o.nodeType==3)n=o,r=n.nodeValue.length;else break}}else{if(ePt(n))break;{let o=n.previousSibling;for(;o&&TY(o,-1);)a=n.parentNode,i=Q0(o),o=o.previousSibling;if(o)n=o,r=PSe(n);else{if(n=n.parentNode,n==s.dom)break;r=0}}}l?x9e(s,n,r):a&&x9e(s,a,i)}function JMs(s){let t=s.domSelectionRange(),n=t.focusNode,r=t.focusOffset;if(!n)return;let a=PSe(n),i,l;for(;;)if(r{s.state==a&&S3(s)},50)}function Adt(s,t){let n=s.state.doc.resolve(t);if(!(iv||z6t)&&n.parent.inlineContent){let a=s.coordsAtPos(t);if(t>n.start()){let i=s.coordsAtPos(t-1),l=(i.top+i.bottom)/2;if(l>a.top&&l1)return i.lefta.top&&l1)return i.left>a.left?"ltr":"rtl"}}return getComputedStyle(s.dom).direction=="rtl"?"rtl":"ltr"}function Edt(s,t,n){let r=s.state.selection;if(r instanceof ul&&!r.empty||n.indexOf("s")>-1||Qj&&n.indexOf("m")>-1)return!1;let{$from:a,$to:i}=r;if(!a.parent.inlineContent||s.endOfTextblock(t<0?"up":"down")){let l=g9e(s.state,t);if(l&&l instanceof hl)return pE(s,l)}if(!a.parent.inlineContent){let l=t<0?a:i,o=r instanceof Jw?$l.near(l,t):$l.findFrom(l,t);return o?pE(s,o):!1}return!1}function Tdt(s,t){if(!(s.state.selection instanceof ul))return!0;let{$head:n,$anchor:r,empty:a}=s.state.selection;if(!n.sameParent(r))return!0;if(!a)return!1;if(s.endOfTextblock(t>0?"forward":"backward"))return!0;let i=!n.textOffset&&(t<0?n.nodeBefore:n.nodeAfter);if(i&&!i.isText){let l=s.state.tr;return t<0?l.delete(n.pos-i.nodeSize,n.pos):l.delete(n.pos,n.pos+i.nodeSize),s.dispatch(l),!0}return!1}function Mdt(s,t,n){s.domObserver.stop(),t.contentEditable=n,s.domObserver.start()}function s6s(s){if(!g1||s.state.selection.$head.parentOffset>0)return!1;let{focusNode:t,focusOffset:n}=s.domSelectionRange();if(t&&t.nodeType==1&&n==0&&t.firstChild&&t.firstChild.contentEditable=="false"){let r=t.firstChild;Mdt(s,r,"true"),setTimeout(()=>Mdt(s,r,"false"),20)}return!1}function n6s(s){let t="";return s.ctrlKey&&(t+="c"),s.metaKey&&(t+="m"),s.altKey&&(t+="a"),s.shiftKey&&(t+="s"),t}function r6s(s,t){let n=t.keyCode,r=n6s(t);if(n==8||Qj&&n==72&&r=="c")return Tdt(s,-1)||W7(s,-1);if(n==46&&!t.shiftKey||Qj&&n==68&&r=="c")return Tdt(s,1)||W7(s,1);if(n==13||n==27)return!0;if(n==37||Qj&&n==66&&r=="c"){let a=n==37?Adt(s,s.state.selection.from)=="ltr"?-1:1:-1;return Cdt(s,a,r)||W7(s,a)}else if(n==39||Qj&&n==70&&r=="c"){let a=n==39?Adt(s,s.state.selection.from)=="ltr"?1:-1:1;return Cdt(s,a,r)||W7(s,a)}else{if(n==38||Qj&&n==80&&r=="c")return Edt(s,-1,r)||W7(s,-1);if(n==40||Qj&&n==78&&r=="c")return s6s(s)||Edt(s,1,r)||W7(s,1);if(r==(Qj?"m":"c")&&(n==66||n==73||n==89||n==90))return!0}return!1}function MWe(s,t){s.someProp("transformCopied",p=>{t=p(t,s)});let n=[],{content:r,openStart:a,openEnd:i}=t;for(;a>1&&i>1&&r.childCount==1&&r.firstChild.childCount==1;){a--,i--;let p=r.firstChild;n.push(p.type.name,p.attrs!=p.type.defaultAttrs?p.attrs:null),r=p.content}let l=s.someProp("clipboardSerializer")||kF.fromSchema(s.state.schema),o=iPt(),c=o.createElement("div");c.appendChild(l.serializeFragment(r,{document:o}));let d=c.firstChild,u,h=0;for(;d&&d.nodeType==1&&(u=aPt[d.nodeName.toLowerCase()]);){for(let p=u.length-1;p>=0;p--){let g=o.createElement(u[p]);for(;c.firstChild;)g.appendChild(c.firstChild);c.appendChild(g),h++}d=c.firstChild}d&&d.nodeType==1&&d.setAttribute("data-pm-slice",`${a} ${i}${h?` -${h}`:""} ${JSON.stringify(n)}`);let m=s.someProp("clipboardTextSerializer",p=>p(t,s))||t.content.textBetween(0,t.content.size,` `);return{dom:c,text:m,slice:t}}function tPt(s,t,n,r,a){let i=a.parent.type.spec.code,l,o;if(!n&&!t)return null;let c=!!t&&(r||i||!n);if(c){if(s.someProp("transformPastedText",m=>{t=m(t,i||r,s)}),i)return o=new Ii(Ua.from(s.state.schema.text(t.replace(/\r\n?/g,` `))),0,0),s.someProp("transformPasted",m=>{o=m(o,s,!0)}),o;let h=s.someProp("clipboardTextParser",m=>m(t,a,r,s));if(h)o=h;else{let m=a.marks(),{schema:p}=s.state,g=kF.fromSchema(p);l=document.createElement("div"),t.split(/(?:\r\n?|\n)+/).forEach(x=>{let y=l.appendChild(document.createElement("p"));x&&y.appendChild(g.serializeNode(p.text(x,m)))})}}else s.someProp("transformPastedHTML",h=>{n=h(n,s)}),l=l6s(n),Mee&&c6s(l);let d=l&&l.querySelector("[data-pm-slice]"),u=d&&/^(\d+) (\d+)(?: -(\d+))? (.*)/.exec(d.getAttribute("data-pm-slice")||"");if(u&&u[3])for(let h=+u[3];h>0;h--){let m=l.firstChild;for(;m&&m.nodeType!=1;)m=m.nextSibling;if(!m)break;l=m}if(o||(o=(s.someProp("clipboardParser")||s.someProp("domParser")||CY.fromSchema(s.state.schema)).parseSlice(l,{preserveWhitespace:!!(c||u),context:a,ruleFromNode(m){return m.nodeName=="BR"&&!m.nextSibling&&m.parentNode&&!a6s.test(m.parentNode.nodeName)?{ignore:!0}:null}})),u)o=d6s(Pdt(o,+u[1],+u[2]),u[4]);else if(o=Ii.maxOpen(i6s(o.content,a),!0),o.openStart||o.openEnd){let h=0,m=0;for(let p=o.content.firstChild;h{o=h(o,s,c)}),o}const a6s=/^(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 i6s(s,t){if(s.childCount<2)return s;for(let n=t.depth;n>=0;n--){let a=t.node(n).contentMatchAt(t.index(n)),i,l=[];if(s.forEach(o=>{if(!l)return;let c=a.findWrapping(o.type),d;if(!c)return l=null;if(d=l.length&&i.length&&nPt(c,i,o,l[l.length-1],0))l[l.length-1]=d;else{l.length&&(l[l.length-1]=rPt(l[l.length-1],i.length));let u=sPt(o,c);l.push(u),a=a.matchType(u.type),i=c}}),l)return Ua.from(l)}return s}function sPt(s,t,n=0){for(let r=t.length-1;r>=n;r--)s=t[r].create(null,Ua.from(s));return s}function nPt(s,t,n,r,a){if(a1&&(i=0),a=n&&(o=t<0?l.contentMatchAt(0).fillBefore(o,i<=a).append(o):o.append(l.contentMatchAt(l.childCount).fillBefore(Ua.empty,!0))),s.replaceChild(t<0?0:s.childCount-1,l.copy(o))}function Pdt(s,t,n){return tn})),hLe.createHTML(s)):s}function l6s(s){let t=/^(\s*]*>)*/.exec(s);t&&(s=s.slice(t[0].length));let n=iPt(),r=n.body,a=/<([a-z][^>\s]+)/i.exec(s),i;if((i=a&&aPt[a[1].toLowerCase()])&&(s=i.map(l=>"<"+l+">").join("")+s+i.map(l=>"").reverse().join("")),r.innerHTML=o6s(s),i)for(let l=0;l=0;o-=2){let c=n.nodes[r[o]];if(!c||c.hasRequiredAttrs())break;a=Ua.from(c.create(r[o+1],a)),i++,l++}return new Ii(a,i,l)}const kb={},Sb={},u6s={touchstart:!0,touchmove:!0};class h6s{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 m6s(s){for(let t in kb){let n=kb[t];s.dom.addEventListener(t,s.input.eventHandlers[t]=r=>{p6s(s,r)&&!PWe(s,r)&&(s.editable||!(r.type in Sb))&&n(s,r)},u6s[t]?{passive:!0}:void 0)}g1&&s.dom.addEventListener("input",()=>null),v9e(s)}function o3(s,t){s.input.lastSelectionOrigin=t,s.input.lastSelectionTime=Date.now()}function f6s(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 v9e(s){s.someProp("handleDOMEvents",t=>{for(let n in t)s.input.eventHandlers[n]||s.dom.addEventListener(n,s.input.eventHandlers[n]=r=>PWe(s,r))})}function PWe(s,t){return s.someProp("handleDOMEvents",n=>{let r=n[t.type];return r?r(s,t)||t.defaultPrevented:!1})}function p6s(s,t){if(!t.bubbles)return!0;if(t.defaultPrevented)return!1;for(let n=t.target;n!=s.dom;n=n.parentNode)if(!n||n.nodeType==11||n.pmViewDesc&&n.pmViewDesc.stopEvent(t))return!1;return!0}function g6s(s,t){!PWe(s,t)&&kb[t.type]&&(s.editable||!(t.type in Sb))&&kb[t.type](s,t)}Sb.keydown=(s,t)=>{let n=t;if(s.input.shiftKey=n.keyCode==16||n.shiftKey,!dPt(s)&&(s.input.lastKeyCode=n.keyCode,s.input.lastKeyCodeTime=Date.now(),!(i3&&iv&&n.keyCode==13)))if(n.keyCode!=229&&s.domObserver.forceFlush(),AU&&n.keyCode==13&&!n.ctrlKey&&!n.altKey&&!n.metaKey){let r=Date.now();s.input.lastIOSEnter=r,s.input.lastIOSEnterFallbackTimeout=setTimeout(()=>{s.input.lastIOSEnter==r&&(s.someProp("handleKeyDown",a=>a(s,GR(13,"Enter"))),s.input.lastIOSEnter=0)},200)}else s.someProp("handleKeyDown",r=>r(s,n))||r6s(s,n)?n.preventDefault():o3(s,"key")};Sb.keyup=(s,t)=>{t.keyCode==16&&(s.input.shiftKey=!1)};Sb.keypress=(s,t)=>{let n=t;if(dPt(s)||!n.charCode||n.ctrlKey&&!n.altKey||Qj&&n.metaKey)return;if(s.someProp("handleKeyPress",a=>a(s,n))){n.preventDefault();return}let r=s.state.selection;if(!(r instanceof ul)||!r.$from.sameParent(r.$to)){let a=String.fromCharCode(n.charCode),i=()=>s.state.tr.insertText(a).scrollIntoView();!/[\r\n]/.test(a)&&!s.someProp("handleTextInput",l=>l(s,r.$from.pos,r.$to.pos,a,i))&&s.dispatch(i()),n.preventDefault()}};function Iee(s){return{left:s.clientX,top:s.clientY}}function x6s(s,t){let n=t.x-s.clientX,r=t.y-s.clientY;return n*n+r*r<100}function IWe(s,t,n,r,a){if(r==-1)return!1;let i=s.state.doc.resolve(r);for(let l=i.depth+1;l>0;l--)if(s.someProp(t,o=>l>i.depth?o(s,n,i.nodeAfter,i.before(l),a,!0):o(s,n,i.node(l),i.before(l),a,!1)))return!0;return!1}function Lee(s,t,n){if(s.focused||s.focus(),s.state.selection.eq(t))return;let r=s.state.tr.setSelection(t);r.setMeta("pointer",!0),s.dispatch(r)}function y6s(s,t){if(t==-1)return!1;let n=s.state.doc.resolve(t),r=n.nodeAfter;return r&&r.isAtom&&hl.isSelectable(r)?(Lee(s,new hl(n)),!0):!1}function v6s(s,t){if(t==-1)return!1;let n=s.state.selection,r,a;n instanceof hl&&(r=n.node);let i=s.state.doc.resolve(t);for(let l=i.depth+1;l>0;l--){let o=l>i.depth?i.nodeAfter:i.node(l);if(hl.isSelectable(o)){r&&n.$from.depth>0&&l>=n.$from.depth&&i.before(n.$from.depth+1)==n.$from.pos?a=i.before(n.$from.depth):a=i.before(l);break}}return a!=null?(Lee(s,hl.create(s.state.doc,a)),!0):!1}function b6s(s,t,n,r,a){return IWe(s,"handleClickOn",t,n,r)||s.someProp("handleClick",i=>i(s,t,r))||(a?v6s(s,n):y6s(s,n))}function _6s(s,t,n,r){return IWe(s,"handleDoubleClickOn",t,n,r)||s.someProp("handleDoubleClick",a=>a(s,t,r))}function w6s(s,t,n,r){return IWe(s,"handleTripleClickOn",t,n,r)||s.someProp("handleTripleClick",a=>a(s,t,r))||j6s(s,n,r)}function j6s(s,t,n){if(n.button!=0)return!1;let r=oPt(s,t,!0),a=s.state.doc;return r?(Lee(s,r),r instanceof ul&&a.eq(s.state.doc)&&(s.input.mouseDown=new k6s(s,r)),!0):!1}function oPt(s,t,n){let r=s.state.doc;if(t==-1)return r.inlineContent?ul.create(r,0,r.content.size):null;let a=r.resolve(t);for(let i=a.depth+1;i>0;i--){let l=i>a.depth?a.nodeAfter:a.node(i),o=a.before(i);if(l.inlineContent)return ul.create(r,o+1,o+1+l.content.size);if(n&&hl.isSelectable(l))return hl.create(r,o)}return null}function LWe(s){return ISe(s)}const lPt=Qj?"metaKey":"ctrlKey";kb.mousedown=(s,t)=>{let n=t;s.input.shiftKey=n.shiftKey;let r=LWe(s),a=Date.now(),i="singleClick";a-s.input.lastClick.time<500&&x6s(n,s.input.lastClick)&&!n[lPt]&&s.input.lastClick.button==n.button&&(s.input.lastClick.type=="singleClick"?i="doubleClick":s.input.lastClick.type=="doubleClick"&&(i="tripleClick")),s.input.lastClick={time:a,x:n.clientX,y:n.clientY,type:i,button:n.button},s.input.mouseDown&&s.input.mouseDown.done();let l=s.posAtCoords(Iee(n));l&&(i=="singleClick"?s.input.mouseDown=new N6s(s,l,n,!!r):(i=="doubleClick"?_6s:w6s)(s,l.pos,l.inside,n)?n.preventDefault():o3(s,"pointer"))};class cPt{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 N6s extends cPt{constructor(t,n,r,a){super(t),this.pos=n,this.event=r,this.flushed=a,this.delayedSelectionSync=!1,this.startDoc=t.state.doc,this.selectNode=!!r[lPt],this.allowDefault=r.shiftKey;let i,l;if(n.inside>-1)i=t.state.doc.nodeAt(n.inside),l=n.inside;else{let u=t.state.doc.resolve(n.pos);i=u.parent,l=u.depth?u.before():0}const o=a?null:r.target,c=o?t.docView.nearestDesc(o,!0):null;this.target=c&&c.nodeDOM.nodeType==1?c.nodeDOM:null;let{selection:d}=t.state;r.button==0&&(i.type.spec.draggable&&i.type.spec.selectable!==!1||d instanceof hl&&d.from<=l&&d.to>l)&&(this.mightDrag={node:i,pos:l,addAttr:!!(this.target&&!this.target.draggable),setUneditable:!!(this.target&&A2&&!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()),o3(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||S3(this.view)})}up(t){if(this.done(),!this.view.dom.contains(t.target))return;let n=this.pos;this.view.state.doc!=this.startDoc&&(n=this.view.posAtCoords(Iee(t))),this.updateAllowDefault(t),this.allowDefault||!n?o3(this.view,"pointer"):b6s(this.view,n.pos,n.inside,t,this.selectNode)?t.preventDefault():t.button==0&&(this.flushed||g1&&this.mightDrag&&!this.mightDrag.node.isAtom||iv&&!this.view.state.selection.visible&&Math.min(Math.abs(n.pos-this.view.state.selection.from),Math.abs(n.pos-this.view.state.selection.to))<=2)?(Lee(this.view,$l.near(this.view.state.doc.resolve(n.pos))),t.preventDefault()):o3(this.view,"pointer")}move(t){this.updateAllowDefault(t),o3(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 k6s extends cPt{constructor(t,n){super(t),this.startSelection=n,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(),o3(this.view,"pointer");let n=this.view.posAtCoords(Iee(t)),r=n&&oPt(this.view,n.inside,!1);if(!r)return;let{doc:a}=this.view.state,i=this.startSelection,[l,o]=r.from{s.input.lastTouch=Date.now(),LWe(s),o3(s,"pointer")};kb.touchmove=s=>{s.input.lastTouch=Date.now(),o3(s,"pointer")};kb.contextmenu=s=>LWe(s);function dPt(s,t){return s.composing?!0:g1&&Math.abs(Date.now()-s.input.compositionEndedAt)<500?(s.input.compositionEndedAt=-2e8,!0):!1}const S6s=i3?5e3:-1;Sb.compositionstart=Sb.compositionupdate=s=>{if(!s.composing){s.domObserver.flush();let{state:t}=s,n=t.selection.$to;if(t.selection instanceof ul&&(t.storedMarks||!n.textOffset&&n.parentOffset&&n.nodeBefore.marks.some(r=>r.type.spec.inclusive===!1)||iv&&z6t&&C6s(s)))s.markCursor=s.state.storedMarks||n.marks(),ISe(s,!0),s.markCursor=null;else if(ISe(s,!t.selection.empty),A2&&t.selection.empty&&n.parentOffset&&!n.textOffset&&n.nodeBefore.marks.length){let r=s.domSelectionRange();for(let a=r.focusNode,i=r.focusOffset;a&&a.nodeType==1&&i!=0;){let l=i<0?a.lastChild:a.childNodes[i-1];if(!l)break;if(l.nodeType==3){let o=s.domSelection();o&&o.collapse(l,l.nodeValue.length);break}else a=l,i=-1}}s.input.composing=!0}uPt(s,S6s)};function C6s(s){let{focusNode:t,focusOffset:n}=s.domSelectionRange();if(!t||t.nodeType!=1||n>=t.childNodes.length)return!1;let r=t.childNodes[n];return r.nodeType==1&&r.contentEditable=="false"}Sb.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++,uPt(s,20))};function uPt(s,t){clearTimeout(s.input.composingTimeout),t>-1&&(s.input.composingTimeout=setTimeout(()=>ISe(s),t))}function hPt(s){for(s.composing&&(s.input.composing=!1,s.input.compositionEndedAt=Date.now());s.input.compositionNodes.length>0;)s.input.compositionNodes.pop().markParentsDirty()}function A6s(s){let t=s.domSelectionRange();if(!t.focusNode)return null;let n=vMs(t.focusNode,t.focusOffset),r=bMs(t.focusNode,t.focusOffset);if(n&&r&&n!=r){let a=r.pmViewDesc,i=s.domObserver.lastChangedTextNode;if(n==i||r==i)return i;if(!a||!a.isText(r.nodeValue))return r;if(s.input.compositionNode==r){let l=n.pmViewDesc;if(!(!l||!l.isText(n.nodeValue)))return r}}return n||r}function ISe(s,t=!1){if(!(i3&&s.domObserver.flushingSoon>=0)){if(s.domObserver.forceFlush(),hPt(s),t||s.docView&&s.docView.dirty){let n=EWe(s),r=s.state.selection;return n&&!n.eq(r)?s.dispatch(s.state.tr.setSelection(n)):(s.markCursor||t)&&!r.$from.node(r.$from.sharedDepth(r.to)).inlineContent?s.dispatch(s.state.tr.deleteSelection()):s.updateState(s.state),!0}return!1}}function E6s(s,t){if(!s.dom.parentNode)return;let n=s.dom.parentNode.appendChild(document.createElement("div"));n.appendChild(t),n.style.cssText="position: fixed; left: -10000px; top: 10px";let r=getSelection(),a=document.createRange();a.selectNodeContents(t),s.dom.blur(),r.removeAllRanges(),r.addRange(a),setTimeout(()=>{n.parentNode&&n.parentNode.removeChild(n),s.focus()},50)}const cX=k_&&dM<15||AU&&NMs<604;kb.copy=Sb.cut=(s,t)=>{let n=t,r=s.state.selection,a=n.type=="cut";if(r.empty)return;let i=cX?null:n.clipboardData,l=r.content(),{dom:o,text:c}=MWe(s,l);i?(n.preventDefault(),i.clearData(),i.setData("text/html",o.innerHTML),i.setData("text/plain",c)):E6s(s,o),a&&s.dispatch(s.state.tr.deleteSelection().scrollIntoView().setMeta("uiEvent","cut"))};function T6s(s){return s.openStart==0&&s.openEnd==0&&s.content.childCount==1?s.content.firstChild:null}function M6s(s,t){if(!s.dom.parentNode)return;let n=s.input.shiftKey||s.state.selection.$from.parent.type.spec.code,r=s.dom.parentNode.appendChild(document.createElement(n?"textarea":"div"));n||(r.contentEditable="true"),r.style.cssText="position: fixed; left: -10000px; top: 10px",r.focus();let a=s.input.shiftKey&&s.input.lastKeyCode!=45;setTimeout(()=>{s.focus(),r.parentNode&&r.parentNode.removeChild(r),n?dX(s,r.value,null,a,t):dX(s,r.textContent,r.innerHTML,a,t)},50)}function dX(s,t,n,r,a){let i=tPt(s,t,n,r,s.state.selection.$from);if(s.someProp("handlePaste",c=>c(s,a,i||Ii.empty)))return!0;if(!i)return!1;let l=T6s(i),o=l?s.state.tr.replaceSelectionWith(l,r):s.state.tr.replaceSelection(i);return s.dispatch(o.scrollIntoView().setMeta("paste",!0).setMeta("uiEvent","paste")),!0}function mPt(s){let t=s.getData("text/plain")||s.getData("Text");if(t)return t;let n=s.getData("text/uri-list");return n?n.replace(/\r?\n/g," "):""}Sb.paste=(s,t)=>{let n=t;if(s.composing&&!i3)return;let r=cX?null:n.clipboardData,a=s.input.shiftKey&&s.input.lastKeyCode!=45;r&&dX(s,mPt(r),r.getData("text/html"),a,n)?n.preventDefault():M6s(s,n)};class fPt{constructor(t,n,r){this.slice=t,this.move=n,this.node=r}}const P6s=Qj?"altKey":"ctrlKey";function pPt(s,t){let n;return s.someProp("dragCopies",r=>{n=n||r(t)}),n!=null?!n:!t[P6s]}kb.dragstart=(s,t)=>{let n=t,r=s.input.mouseDown;if(r&&r.done(),!n.dataTransfer)return;let a=s.state.selection,i=a.empty?null:s.posAtCoords(Iee(n)),l;if(!(i&&i.pos>=a.from&&i.pos<=(a instanceof hl?a.to-1:a.to))){if(r&&r.mightDrag)l=hl.create(s.state.doc,r.mightDrag.pos);else if(n.target&&n.target.nodeType==1){let h=s.docView.nearestDesc(n.target,!0);h&&h.node.type.spec.draggable&&h!=s.docView&&(l=hl.create(s.state.doc,h.posBefore))}}let o=(l||s.state.selection).content(),{dom:c,text:d,slice:u}=MWe(s,o);(!n.dataTransfer.files.length||!iv||F6t>120)&&n.dataTransfer.clearData(),n.dataTransfer.setData(cX?"Text":"text/html",c.innerHTML),n.dataTransfer.effectAllowed="copyMove",cX||n.dataTransfer.setData("text/plain",d),s.dragging=new fPt(u,pPt(s,n),l)};kb.dragend=s=>{let t=s.dragging;window.setTimeout(()=>{s.dragging==t&&(s.dragging=null)},50)};Sb.dragover=Sb.dragenter=(s,t)=>t.preventDefault();Sb.drop=(s,t)=>{try{I6s(s,t,s.dragging)}finally{s.dragging=null}};function I6s(s,t,n){if(!t.dataTransfer)return;let r=s.posAtCoords(Iee(t));if(!r)return;let a=s.state.doc.resolve(r.pos),i=n&&n.slice;i?s.someProp("transformPasted",p=>{i=p(i,s,!1)}):i=tPt(s,mPt(t.dataTransfer),cX?null:t.dataTransfer.getData("text/html"),!1,a);let l=!!(n&&pPt(s,t));if(s.someProp("handleDrop",p=>p(s,t,i||Ii.empty,l))){t.preventDefault();return}if(!i)return;t.preventDefault();let o=i?E6t(s.state.doc,a.pos,i):a.pos;o==null&&(o=a.pos);let c=s.state.tr;if(l){let{node:p}=n;p?p.replace(c):c.deleteSelection()}let d=c.mapping.map(o),u=i.openStart==0&&i.openEnd==0&&i.content.childCount==1,h=c.doc;if(u?c.replaceRangeWith(d,d,i.content.firstChild):c.replaceRange(d,d,i),c.doc.eq(h))return;let m=c.doc.resolve(d);if(u&&hl.isSelectable(i.content.firstChild)&&m.nodeAfter&&m.nodeAfter.sameMarkup(i.content.firstChild))c.setSelection(new hl(m));else{let p=c.mapping.map(o);c.mapping.maps[c.mapping.maps.length-1].forEach((g,x,y,v)=>p=v),c.setSelection(TWe(s,m,c.doc.resolve(p)))}s.focus(),s.dispatch(c.setMeta("uiEvent","drop"))}kb.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())&&S3(s)},20))};kb.blur=(s,t)=>{let n=t;s.focused&&(s.domObserver.stop(),s.dom.classList.remove("ProseMirror-focused"),s.domObserver.start(),n.relatedTarget&&s.dom.contains(n.relatedTarget)&&s.domObserver.currentSelection.clear(),s.focused=!1)};kb.beforeinput=(s,t)=>{if(i3&&t.inputType=="deleteContentBackward"){s.domObserver.flushSoon();let{domChangeCount:r}=s.input;setTimeout(()=>{if(s.input.domChangeCount!=r||(s.dom.blur(),s.focus(),s.someProp("handleKeyDown",i=>i(s,GR(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 Sb)kb[s]=Sb[s];function uX(s,t){if(s==t)return!0;for(let n in s)if(s[n]!==t[n])return!1;for(let n in t)if(!(n in s))return!1;return!0}class LSe{constructor(t,n){this.toDOM=t,this.spec=n||nO,this.side=this.spec.side||0}map(t,n,r,a){let{pos:i,deleted:l}=t.mapResult(n.from+a,this.side<0?-1:1);return l?null:new cb(i-r,i-r,this)}valid(){return!0}eq(t){return this==t||t instanceof LSe&&(this.spec.key&&this.spec.key==t.spec.key||this.toDOM==t.toDOM&&uX(this.spec,t.spec))}destroy(t){this.spec.destroy&&this.spec.destroy(t)}}class mM{constructor(t,n){this.attrs=t,this.spec=n||nO}map(t,n,r,a){let i=t.map(n.from+a,this.spec.inclusiveStart?-1:1)-r,l=t.map(n.to+a,this.spec.inclusiveEnd?1:-1)-r;return i>=l?null:new cb(i,l,this)}valid(t,n){return n.from=t&&(!i||i(o.spec))&&r.push(o.copy(o.from+a,o.to+a))}for(let l=0;lt){let o=this.children[l]+1;this.children[l+2].findInner(t-o,n-o,r,a+o,i)}}map(t,n,r){return this==Jv||t.maps.length==0?this:this.mapInner(t,n,0,0,r||nO)}mapInner(t,n,r,a,i){let l;for(let o=0;o{let d=c+r,u;if(u=xPt(n,o,d)){for(a||(a=this.children.slice());io&&h.to=t){this.children[o]==t&&(r=this.children[o+2]);break}let i=t+1,l=i+n.content.size;for(let o=0;oi&&c.type instanceof mM){let d=Math.max(i,c.from)-i,u=Math.min(l,c.to)-i;da.map(t,n,nO));return EE.from(r)}forChild(t,n){if(n.isLeaf)return xg.empty;let r=[];for(let a=0;an instanceof xg)?t:t.reduce((n,r)=>n.concat(r instanceof xg?r:r.members),[]))}}forEachSet(t){for(let n=0;n{let y=x-g-(p-m);for(let v=0;v_+u-h)continue;let j=o[v]+u-h;p>=j?o[v+1]=m<=j?-2:-1:m>=u&&y&&(o[v]+=y,o[v+1]+=y)}h+=y}),u=n.maps[d].map(u,-1)}let c=!1;for(let d=0;d=r.content.size){c=!0;continue}let m=n.map(s[d+1]+i,-1),p=m-a,{index:g,offset:x}=r.content.findIndex(h),y=r.maybeChild(g);if(y&&x==h&&x+y.nodeSize==p){let v=o[d+2].mapInner(n,y,u+1,s[d]+i+1,l);v!=Jv?(o[d]=h,o[d+1]=p,o[d+2]=v):(o[d+1]=-2,c=!0)}else c=!0}if(c){let d=R6s(o,s,t,n,a,i,l),u=RSe(d,r,0,l);t=u.local;for(let h=0;hn&&l.to{let d=xPt(s,o,c+n);if(d){i=!0;let u=RSe(d,o,n+c+1,r);u!=Jv&&a.push(c,c+o.nodeSize,u)}});let l=gPt(i?yPt(s):s,-n).sort(rO);for(let o=0;o0;)t++;s.splice(t,0,n)}function mLe(s){let t=[];return s.someProp("decorations",n=>{let r=n(s.state);r&&r!=Jv&&t.push(r)}),s.cursorWrapper&&t.push(xg.create(s.state.doc,[s.cursorWrapper.deco])),EE.from(t)}const D6s={childList:!0,characterData:!0,characterDataOldValue:!0,attributes:!0,attributeOldValue:!0,subtree:!0},O6s=k_&&dM<=11;class F6s{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 z6s{constructor(t,n){this.view=t,this.handleDOMChange=n,this.queue=[],this.flushingSoon=-1,this.observer=null,this.currentSelection=new F6s,this.onCharData=null,this.suppressingSelectionUpdates=!1,this.lastChangedTextNode=null,this.observer=window.MutationObserver&&new window.MutationObserver(r=>{for(let a=0;aa.type=="childList"&&a.removedNodes.length||a.type=="characterData"&&a.oldValue.length>a.target.nodeValue.length)?this.flushSoon():g1&&t.composing&&r.some(a=>a.type=="childList"&&a.target.nodeName=="TR")?(t.input.badSafariComposition=!0,this.flushSoon()):this.flush()}),O6s&&(this.onCharData=r=>{this.queue.push({target:r.target,type:"characterData",oldValue:r.prevValue}),this.flushSoon()}),this.onSelectionChange=this.onSelectionChange.bind(this)}flushSoon(){this.flushingSoon<0&&(this.flushingSoon=window.setTimeout(()=>{this.flushingSoon=-1,this.flush()},20))}forceFlush(){this.flushingSoon>-1&&(window.clearTimeout(this.flushingSoon),this.flushingSoon=-1,this.flush())}start(){this.observer&&(this.observer.takeRecords(),this.observer.observe(this.view.dom,D6s)),this.onCharData&&this.view.dom.addEventListener("DOMCharacterDataModified",this.onCharData),this.connectSelection()}stop(){if(this.observer){let t=this.observer.takeRecords();if(t.length){for(let n=0;nthis.flush(),20)}this.observer.disconnect()}this.onCharData&&this.view.dom.removeEventListener("DOMCharacterDataModified",this.onCharData),this.disconnectSelection()}connectSelection(){this.view.dom.ownerDocument.addEventListener("selectionchange",this.onSelectionChange)}disconnectSelection(){this.view.dom.ownerDocument.removeEventListener("selectionchange",this.onSelectionChange)}suppressSelectionUpdates(){this.suppressingSelectionUpdates=!0,setTimeout(()=>this.suppressingSelectionUpdates=!1,50)}onSelectionChange(){if(Sdt(this.view)){if(this.suppressingSelectionUpdates)return S3(this.view);if(k_&&dM<=11&&!this.view.state.selection.empty){let t=this.view.domSelectionRange();if(t.focusNode&&FO(t.focusNode,t.focusOffset,t.anchorNode,t.anchorOffset))return this.flushSoon()}this.flush()}}setCurSelection(){this.currentSelection.set(this.view.domSelectionRange())}ignoreSelectionChange(t){if(!t.focusNode)return!0;let n=new Set,r;for(let i=t.focusNode;i;i=CU(i))n.add(i);for(let i=t.anchorNode;i;i=CU(i))if(n.has(i)){r=i;break}let a=r&&this.view.docView.nearestDesc(r);if(a&&a.ignoreMutation({type:"selection",target:r.nodeType==3?r.parentNode:r}))return this.setCurSelection(),!0}pendingRecords(){if(this.observer)for(let t of this.observer.takeRecords())this.queue.push(t);return this.queue}flush(){let{view:t}=this;if(!t.docView||this.flushingSoon>-1)return;let n=this.pendingRecords();n.length&&(this.queue=[]);let r=t.domSelectionRange(),a=!this.suppressingSelectionUpdates&&!this.currentSelection.eq(r)&&Sdt(t)&&!this.ignoreSelectionChange(r),i=-1,l=-1,o=!1,c=[];if(t.editable)for(let u=0;uu.nodeName=="BR")&&(t.input.lastKeyCode==8||t.input.lastKeyCode==46||iv&&(t.composing||t.input.compositionEndedAt>Date.now()-50)&&n.some(u=>u.type=="childList"&&u.removedNodes.length))){for(let u of c)if(u.nodeName=="BR"&&u.parentNode){let h=u.nextSibling;for(;h&&h.nodeType==1;){if(h.contentEditable=="false"){u.parentNode.removeChild(u);break}h=h.firstChild}}}else if(A2&&c.length){let u=c.filter(h=>h.nodeName=="BR");if(u.length==2){let[h,m]=u;h.parentNode&&h.parentNode.parentNode==m.parentNode?m.remove():h.remove()}else{let{focusNode:h}=this.currentSelection;for(let m of u){let p=m.parentNode;p&&p.nodeName=="LI"&&(!h||U6s(t,h)!=p)&&m.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),B6s(t)),t.input.badSafariComposition&&(t.input.badSafariComposition=!1,q6s(t,c)),this.handleDOMChange(i,l,o,c),t.docView&&t.docView.dirty?t.updateState(t.state):this.currentSelection.eq(r)||S3(t),this.currentSelection.set(r))}registerMutation(t,n){if(n.indexOf(t.target)>-1)return null;let r=this.view.docView.nearestDesc(t.target);if(t.type=="attributes"&&(r==this.view.docView||t.attributeName=="contenteditable"||t.attributeName=="style"&&!t.oldValue&&!t.target.getAttribute("style"))||!r||r.ignoreMutation(t))return null;if(t.type=="childList"){for(let u=0;ui;v--){let _=a.childNodes[v-1],j=_.pmViewDesc;if(_.nodeName=="BR"&&!j){l=v;break}if(!j||j.size)break}let m=s.state.doc,p=s.someProp("domParser")||CY.fromSchema(s.state.schema),g=m.resolve(o),x=null,y=p.parse(a,{topNode:g.parent,topMatch:g.parent.contentMatchAt(g.index()),topOpen:!0,from:i,to:l,preserveWhitespace:g.parent.type.whitespace=="pre"?"full":!0,findPositions:u,ruleFromNode:H6s(r),context:g});if(u&&u[0].pos!=null){let v=u[0].pos,_=u[1]&&u[1].pos;_==null&&(_=v),x={anchor:v+o,head:_+o}}return{doc:y,sel:x,from:o,to:c}}const H6s=s=>t=>{let n=t.pmViewDesc;if(n)return n.parseRule(s);if(t.nodeName=="BR"&&t.parentNode){if(g1&&/^(ul|ol)$/i.test(t.parentNode.nodeName)){let r=document.createElement("div");return r.appendChild(document.createElement("li")),{skip:r}}else if(t.parentNode.lastChild==t||g1&&/^(tr|table)$/i.test(t.parentNode.nodeName))return{ignore:!0}}else if(t.nodeName=="IMG"&&t.getAttribute("mark-placeholder"))return{ignore:!0};return null},G6s=/^(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 W6s(s,t,n,r,a){let i=s.input.compositionPendingChanges||(s.composing?s.input.compositionID:0);if(s.input.compositionPendingChanges=0,t<0){let I=s.input.lastSelectionTime>Date.now()-50?s.input.lastSelectionOrigin:null,P=EWe(s,I);if(P&&!s.state.selection.eq(P)){if(iv&&i3&&s.input.lastKeyCode===13&&Date.now()-100O(s,GR(13,"Enter"))))return;let R=s.state.tr.setSelection(P);I=="pointer"?R.setMeta("pointer",!0):I=="key"&&R.scrollIntoView(),i&&R.setMeta("composition",i),s.dispatch(R)}return}let l=s.state.doc.resolve(t),o=l.sharedDepth(n);t=l.before(o+1),n=s.state.doc.resolve(n).after(o+1);let c=s.state.selection,d=V6s(s,t,n,a),u=s.state.doc,h=u.slice(d.from,d.to),m,p;s.input.lastKeyCode===8&&Date.now()-100Date.now()-225||i3)&&a.some(I=>I.nodeType==1&&!G6s.test(I.nodeName))&&(!g||g.endA>=g.endB)&&s.someProp("handleKeyDown",I=>I(s,GR(13,"Enter")))){s.input.lastIOSEnter=0;return}if(!g)if(r&&c instanceof ul&&!c.empty&&c.$head.sameParent(c.$anchor)&&!s.composing&&!(d.sel&&d.sel.anchor!=d.sel.head))g={start:c.from,endA:c.to,endB:c.to};else{if(d.sel){let I=Odt(s,s.state.doc,d.sel);if(I&&!I.eq(s.state.selection)){let P=s.state.tr.setSelection(I);i&&P.setMeta("composition",i),s.dispatch(P)}}return}s.state.selection.froms.state.selection.from&&g.start<=s.state.selection.from+2&&s.state.selection.from>=d.from?g.start=s.state.selection.from:g.endA=s.state.selection.to-2&&s.state.selection.to<=d.to&&(g.endB+=s.state.selection.to-g.endA,g.endA=s.state.selection.to)),k_&&dM<=11&&g.endB==g.start+1&&g.endA==g.start&&g.start>d.from&&d.doc.textBetween(g.start-d.from-1,g.start-d.from+1)=="  "&&(g.start--,g.endA--,g.endB--);let x=d.doc.resolveNoCache(g.start-d.from),y=d.doc.resolveNoCache(g.endB-d.from),v=u.resolve(g.start),_=x.sameParent(y)&&x.parent.inlineContent&&v.end()>=g.endA;if((AU&&s.input.lastIOSEnter>Date.now()-225&&(!_||a.some(I=>I.nodeName=="DIV"||I.nodeName=="P"))||!_&&x.posI(s,GR(13,"Enter")))){s.input.lastIOSEnter=0;return}if(s.state.selection.anchor>g.start&&Y6s(u,g.start,g.endA,x,y)&&s.someProp("handleKeyDown",I=>I(s,GR(8,"Backspace")))){i3&&iv&&s.domObserver.suppressSelectionUpdates();return}iv&&g.endB==g.start&&(s.input.lastChromeDelete=Date.now()),i3&&!_&&x.start()!=y.start()&&y.parentOffset==0&&x.depth==y.depth&&d.sel&&d.sel.anchor==d.sel.head&&d.sel.head==g.endA&&(g.endB-=2,y=d.doc.resolveNoCache(g.endB-d.from),setTimeout(()=>{s.someProp("handleKeyDown",function(I){return I(s,GR(13,"Enter"))})},20));let j=g.start,C=g.endA,A=I=>{let P=I||s.state.tr.replace(j,C,d.doc.slice(g.start-d.from,g.endB-d.from));if(d.sel){let R=Odt(s,P.doc,d.sel);R&&!(iv&&s.composing&&R.empty&&(g.start!=g.endB||s.input.lastChromeDeleteS3(s),20));let I=A(s.state.tr.delete(j,C)),P=u.resolve(g.start).marksAcross(u.resolve(g.endA));P&&I.ensureMarks(P),s.dispatch(I)}else if(g.endA==g.endB&&(M=K6s(x.parent.content.cut(x.parentOffset,y.parentOffset),v.parent.content.cut(v.parentOffset,g.endA-v.start())))){let I=A(s.state.tr);M.type=="add"?I.addMark(j,C,M.mark):I.removeMark(j,C,M.mark),s.dispatch(I)}else if(x.parent.child(x.index()).isText&&x.index()==y.index()-(y.textOffset?0:1)){let I=x.parent.textBetween(x.parentOffset,y.parentOffset),P=()=>A(s.state.tr.insertText(I,j,C));s.someProp("handleTextInput",R=>R(s,j,C,I,P))||s.dispatch(P())}else s.dispatch(A());else s.dispatch(A())}function Odt(s,t,n){return Math.max(n.anchor,n.head)>t.content.size?null:TWe(s,t.resolve(n.anchor),t.resolve(n.head))}function K6s(s,t){let n=s.firstChild.marks,r=t.firstChild.marks,a=n,i=r,l,o,c;for(let u=0;uu.mark(o.addToSet(u.marks));else if(a.length==0&&i.length==1)o=i[0],l="remove",c=u=>u.mark(o.removeFromSet(u.marks));else return null;let d=[];for(let u=0;un||fLe(l,!0,!1)0&&(t||s.indexAfter(r)==s.node(r).childCount);)r--,a++,t=!1;if(n){let i=s.node(r).maybeChild(s.indexAfter(r));for(;i&&!i.isLeaf;)i=i.firstChild,a++}return a}function Z6s(s,t,n,r,a){let i=s.findDiffStart(t,n),l=n+s.size,o=n+t.size;if(i==null)return null;let{a:c,b:d}=s.findDiffEnd(t,l,o);if(a=="end"){let u=Math.max(0,i-Math.min(c,d));r-=c+u-i}if(c=c?i-r:0;i-=u,d=i+(d-c),c=i}else if(d=d?i-r:0;i-=u,c=i+(c-d),d=i}return{start:i,endA:c,endB:d}}class vPt{constructor(t,n){this._root=null,this.focused=!1,this.trackWrites=null,this.mounted=!1,this.markCursor=null,this.cursorWrapper=null,this.lastSelectedViewDesc=void 0,this.input=new h6s,this.prevDirectPlugins=[],this.pluginViews=[],this.requiresGeckoHackNode=!1,this.dragging=null,this._props=n,this.state=n.state,this.directPlugins=n.plugins||[],this.directPlugins.forEach(Udt),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=Bdt(this),zdt(this),this.nodeViews=$dt(this),this.docView=bdt(this.state.doc,Fdt(this),mLe(this),this.dom,this),this.domObserver=new z6s(this,(r,a,i,l)=>W6s(this,r,a,i,l)),this.domObserver.start(),m6s(this),this.updatePluginViews()}get composing(){return this.input.composing}get props(){if(this._props.state!=this.state){let t=this._props;this._props={};for(let n in t)this._props[n]=t[n];this._props.state=this.state}return this._props}update(t){t.handleDOMEvents!=this._props.handleDOMEvents&&v9e(this);let n=this._props;this._props=t,t.plugins&&(t.plugins.forEach(Udt),this.directPlugins=t.plugins),this.updateStateInner(t.state,n)}setProps(t){let n={};for(let r in this._props)n[r]=this._props[r];n.state=this.state;for(let r in t)n[r]=t[r];this.update(n)}updateState(t){this.updateStateInner(t,this._props)}updateStateInner(t,n){var r;let a=this.state,i=!1,l=!1;t.storedMarks&&this.composing&&(hPt(this),l=!0),this.state=t;let o=a.plugins!=t.plugins||this._props.plugins!=n.plugins;if(o||this._props.plugins!=n.plugins||this._props.nodeViews!=n.nodeViews){let p=$dt(this);Q6s(p,this.nodeViews)&&(this.nodeViews=p,i=!0)}(o||n.handleDOMEvents!=this._props.handleDOMEvents)&&v9e(this),this.editable=Bdt(this),zdt(this);let c=mLe(this),d=Fdt(this),u=a.plugins!=t.plugins&&!a.doc.eq(t.doc)?"reset":t.scrollToSelection>a.scrollToSelection?"to selection":"preserve",h=i||!this.docView.matchesNode(t.doc,d,c);(h||!t.selection.eq(a.selection))&&(l=!0);let m=u=="preserve"&&l&&this.dom.style.overflowAnchor==null&&CMs(this);if(l){this.domObserver.stop();let p=h&&(k_||iv)&&!this.composing&&!a.selection.empty&&!t.selection.empty&&X6s(a.selection,t.selection);if(h){let x=iv?this.trackWrites=this.domSelectionRange().focusNode:null;this.composing&&(this.input.compositionNode=A6s(this)),(i||!this.docView.update(t.doc,d,c,this))&&(this.docView.updateOuterDeco(d),this.docView.destroy(),this.docView=bdt(t.doc,d,c,this.dom,this)),x&&(!this.trackWrites||!this.dom.contains(this.trackWrites))&&(p=!0)}let g=this.input.mouseDown;p||!(g&&this.domObserver.currentSelection.eq(this.domSelectionRange())&&XMs(this)&&g.delaySelUpdate())?S3(this,p):(Q6t(this,t.selection),this.domObserver.setCurSelection()),this.domObserver.start()}this.updatePluginViews(a),!((r=this.dragging)===null||r===void 0)&&r.node&&!a.doc.eq(t.doc)&&this.updateDraggedNode(this.dragging,a),u=="reset"?this.dom.scrollTop=0:u=="to selection"?this.scrollToSelection():m&&AMs(m)}scrollToSelection(){let t=this.domSelectionRange().focusNode;if(!(!t||!this.dom.contains(t.nodeType==1?t:t.parentNode))){if(!this.someProp("handleScrollToSelection",n=>n(this)))if(this.state.selection instanceof hl){let n=this.docView.domAfterPos(this.state.selection.from);n.nodeType==1&&pdt(this,n.getBoundingClientRect(),t)}else pdt(this,this.coordsAtPos(this.state.selection.head,1),t)}}destroyPluginViews(){let t;for(;t=this.pluginViews.pop();)t.destroy&&t.destroy()}updatePluginViews(t){if(!t||t.plugins!=this.state.plugins||this.directPlugins!=this.prevDirectPlugins){this.prevDirectPlugins=this.directPlugins,this.destroyPluginViews();for(let n=0;n0&&in.ownerDocument.getSelection()),this._root=n}return t||document}updateRoot(){this._root=null}posAtCoords(t){return LMs(this,t)}coordsAtPos(t,n=1){return V6t(this,t,n)}domAtPos(t,n=0){return this.docView.domFromPos(t,n)}nodeDOM(t){let n=this.docView.descAt(t);return n?n.nodeDOM:null}posAtDOM(t,n,r=-1){let a=this.docView.posFromDOM(t,n,r);if(a==null)throw new RangeError("DOM position not inside the editor");return a}endOfTextblock(t,n){return zMs(this,n||this.state,t)}pasteHTML(t,n){return dX(this,"",t,!1,n||new ClipboardEvent("paste"))}pasteText(t,n){return dX(this,t,null,!0,n||new ClipboardEvent("paste"))}serializeForClipboard(t){return MWe(this,t)}destroy(){this.docView&&(f6s(this),this.destroyPluginViews(),this.mounted?(this.docView.update(this.state.doc,[],mLe(this),this),this.dom.textContent=""):this.dom.parentNode&&this.dom.parentNode.removeChild(this.dom),this.docView.destroy(),this.docView=null,xMs())}get isDestroyed(){return this.docView==null}dispatchEvent(t){return g6s(this,t)}domSelectionRange(){let t=this.domSelection();return t?g1&&this.root.nodeType===11&&wMs(this.dom.ownerDocument)==this.dom&&$6s(this,t)||t:{focusNode:null,focusOffset:0,anchorNode:null,anchorOffset:0}}domSelection(){return this.root.getSelection()}}vPt.prototype.dispatch=function(s){let t=this._props.dispatchTransaction;t?t.call(this,s):this.updateState(this.state.apply(s))};function Fdt(s){let t=Object.create(null);return t.class="ProseMirror",t.contenteditable=String(s.editable),s.someProp("attributes",n=>{if(typeof n=="function"&&(n=n(s.state)),n)for(let r in n)r=="class"?t.class+=" "+n[r]:r=="style"?t.style=(t.style?t.style+";":"")+n[r]:!t[r]&&r!="contenteditable"&&r!="nodeName"&&(t[r]=String(n[r]))}),t.translate||(t.translate="no"),[cb.node(0,s.state.doc.content.size,t)]}function zdt(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:cb.widget(s.state.selection.from,t,{raw:!0,marks:s.markCursor})}}else s.cursorWrapper=null}function Bdt(s){return!s.someProp("editable",t=>t(s.state)===!1)}function X6s(s,t){let n=Math.min(s.$anchor.sharedDepth(s.head),t.$anchor.sharedDepth(t.head));return s.$anchor.start(n)!=t.$anchor.start(n)}function $dt(s){let t=Object.create(null);function n(r){for(let a in r)Object.prototype.hasOwnProperty.call(t,a)||(t[a]=r[a])}return s.someProp("nodeViews",n),s.someProp("markViews",n),t}function Q6s(s,t){let n=0,r=0;for(let a in s){if(s[a]!=t[a])return!0;n++}for(let a in t)r++;return n!=r}function Udt(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 EM={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:"'"},DSe={48:")",49:"!",50:"@",51:"#",52:"$",53:"%",54:"^",55:"&",56:"*",57:"(",59:":",61:"+",173:"_",186:":",187:"+",188:"<",189:"_",190:">",191:"?",192:"~",219:"{",220:"|",221:"}",222:'"'},J6s=typeof navigator<"u"&&/Mac/.test(navigator.platform),ePs=typeof navigator<"u"&&/MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent);for(var J0=0;J0<10;J0++)EM[48+J0]=EM[96+J0]=String(J0);for(var J0=1;J0<=24;J0++)EM[J0+111]="F"+J0;for(var J0=65;J0<=90;J0++)EM[J0]=String.fromCharCode(J0+32),DSe[J0]=String.fromCharCode(J0);for(var pLe in EM)DSe.hasOwnProperty(pLe)||(DSe[pLe]=EM[pLe]);function tPs(s){var t=J6s&&s.metaKey&&s.shiftKey&&!s.ctrlKey&&!s.altKey||ePs&&s.shiftKey&&s.key&&s.key.length==1||s.key=="Unidentified",n=!t&&s.key||(s.shiftKey?DSe:EM)[s.keyCode]||s.key||"Unidentified";return n=="Esc"&&(n="Escape"),n=="Del"&&(n="Delete"),n=="Left"&&(n="ArrowLeft"),n=="Up"&&(n="ArrowUp"),n=="Right"&&(n="ArrowRight"),n=="Down"&&(n="ArrowDown"),n}const sPs=typeof navigator<"u"&&/Mac|iP(hone|[oa]d)/.test(navigator.platform),nPs=typeof navigator<"u"&&/Win/.test(navigator.platform);function rPs(s){let t=s.split(/-(?!$)/),n=t[t.length-1];n=="Space"&&(n=" ");let r,a,i,l;for(let o=0;os.selection.empty?!1:(t&&t(s.tr.deleteSelection().scrollIntoView()),!0);function bPt(s,t){let{$cursor:n}=s.selection;return!n||(t?!t.endOfTextblock("backward",s):n.parentOffset>0)?null:n}const _Pt=(s,t,n)=>{let r=bPt(s,n);if(!r)return!1;let a=zWe(r);if(!a){let l=r.blockRange(),o=l&&eV(l);return o==null?!1:(t&&t(s.tr.lift(l,o).scrollIntoView()),!0)}let i=a.nodeBefore;if(TPt(s,a,t,-1))return!0;if(r.parent.content.size==0&&(EU(i,"end")||hl.isSelectable(i)))for(let l=r.depth;;l--){let o=wAe(s.doc,r.before(l),r.after(l),Ii.empty);if(o&&o.slice.size1)break}return i.isAtom&&a.depth==r.depth-1?(t&&t(s.tr.delete(a.pos-i.nodeSize,a.pos).scrollIntoView()),!0):!1},oPs=(s,t,n)=>{let r=bPt(s,n);if(!r)return!1;let a=zWe(r);return a?wPt(s,a,t):!1},lPs=(s,t,n)=>{let r=NPt(s,n);if(!r)return!1;let a=BWe(r);return a?wPt(s,a,t):!1};function wPt(s,t,n){let r=t.nodeBefore,a=r,i=t.pos-1;for(;!a.isTextblock;i--){if(a.type.spec.isolating)return!1;let u=a.lastChild;if(!u)return!1;a=u}let l=t.nodeAfter,o=l,c=t.pos+1;for(;!o.isTextblock;c++){if(o.type.spec.isolating)return!1;let u=o.firstChild;if(!u)return!1;o=u}let d=wAe(s.doc,i,c,Ii.empty);if(!d||d.from!=i||d instanceof Tx&&d.slice.size>=c-i)return!1;if(n){let u=s.tr.step(d);u.setSelection(ul.create(u.doc,i)),n(u.scrollIntoView())}return!0}function EU(s,t,n=!1){for(let r=s;r;r=t=="start"?r.firstChild:r.lastChild){if(r.isTextblock)return!0;if(n&&r.childCount!=1)return!1}return!1}const jPt=(s,t,n)=>{let{$head:r,empty:a}=s.selection,i=r;if(!a)return!1;if(r.parent.isTextblock){if(n?!n.endOfTextblock("backward",s):r.parentOffset>0)return!1;i=zWe(r)}let l=i&&i.nodeBefore;return!l||!hl.isSelectable(l)?!1:(t&&t(s.tr.setSelection(hl.create(s.doc,i.pos-l.nodeSize)).scrollIntoView()),!0)};function zWe(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 NPt(s,t){let{$cursor:n}=s.selection;return!n||(t?!t.endOfTextblock("forward",s):n.parentOffset{let r=NPt(s,n);if(!r)return!1;let a=BWe(r);if(!a)return!1;let i=a.nodeAfter;if(TPt(s,a,t,1))return!0;if(r.parent.content.size==0&&(EU(i,"start")||hl.isSelectable(i))){let l=wAe(s.doc,r.before(),r.after(),Ii.empty);if(l&&l.slice.size{let{$head:r,empty:a}=s.selection,i=r;if(!a)return!1;if(r.parent.isTextblock){if(n?!n.endOfTextblock("forward",s):r.parentOffset=0;t--){let n=s.node(t);if(s.index(t)+1{let n=s.selection,r=n instanceof hl,a;if(r){if(n.node.isTextblock||!t6(s.doc,n.from))return!1;a=n.from}else if(a=_Ae(s.doc,n.from,-1),a==null)return!1;if(t){let i=s.tr.join(a);r&&i.setSelection(hl.create(i.doc,a-s.doc.resolve(a).nodeBefore.nodeSize)),t(i.scrollIntoView())}return!0},dPs=(s,t)=>{let n=s.selection,r;if(n instanceof hl){if(n.node.isTextblock||!t6(s.doc,n.to))return!1;r=n.to}else if(r=_Ae(s.doc,n.to,1),r==null)return!1;return t&&t(s.tr.join(r).scrollIntoView()),!0},uPs=(s,t)=>{let{$from:n,$to:r}=s.selection,a=n.blockRange(r),i=a&&eV(a);return i==null?!1:(t&&t(s.tr.lift(a,i).scrollIntoView()),!0)},CPt=(s,t)=>{let{$head:n,$anchor:r}=s.selection;return!n.parent.type.spec.code||!n.sameParent(r)?!1:(t&&t(s.tr.insertText(` `).scrollIntoView()),!0)};function $We(s){for(let t=0;t{let{$head:n,$anchor:r}=s.selection;if(!n.parent.type.spec.code||!n.sameParent(r))return!1;let a=n.node(-1),i=n.indexAfter(-1),l=$We(a.contentMatchAt(i));if(!l||!a.canReplaceWith(i,i,l))return!1;if(t){let o=n.after(),c=s.tr.replaceWith(o,o,l.createAndFill());c.setSelection($l.near(c.doc.resolve(o),1)),t(c.scrollIntoView())}return!0},APt=(s,t)=>{let n=s.selection,{$from:r,$to:a}=n;if(n instanceof Jw||r.parent.inlineContent||a.parent.inlineContent)return!1;let i=$We(a.parent.contentMatchAt(a.indexAfter()));if(!i||!i.isTextblock)return!1;if(t){let l=(!r.parentOffset&&a.index(){let{$cursor:n}=s.selection;if(!n||n.parent.content.size)return!1;if(n.depth>1&&n.after()!=n.end(-1)){let i=n.before();if(k3(s.doc,i))return t&&t(s.tr.split(i).scrollIntoView()),!0}let r=n.blockRange(),a=r&&eV(r);return a==null?!1:(t&&t(s.tr.lift(r,a).scrollIntoView()),!0)};function mPs(s){return(t,n)=>{if(t.selection instanceof hl&&t.selection.node.isBlock){let{$from:p}=t.selection;return!p.parentOffset||!k3(t.doc,p.pos)?!1:(n&&n(t.tr.split(p.pos).scrollIntoView()),!0)}if(!t.selection.$from.depth)return!1;let r=t.tr;!t.selection.empty&&(t.selection instanceof ul||t.selection instanceof Jw)&&r.deleteSelection();let{$from:a}=r.selection,i=r.steps.length,l=[],o,c,d=!1,u=!1;for(let p=a.depth;;p--)if(a.node(p).isBlock){d=a.end(p)==a.pos+(a.depth-p),u=a.start(p)==a.pos-(a.depth-p),c=$We(a.node(p-1).contentMatchAt(a.indexAfter(p-1))),l.unshift(d&&c?{type:c}:null),o=p;break}else{if(p==1)return!1;l.unshift(null)}let h=a.pos,m=k3(r.doc,h,l.length,l);if(m||(l[0]=c?{type:c}:null,m=k3(r.doc,h,l.length,l)),!m)return!1;if(r.split(h,l.length,l),!d&&u&&a.node(o).type!=c){let p=r.mapping.slice(i),g=p.map(a.before(o)),x=r.doc.resolve(g);c&&a.node(o-1).canReplaceWith(x.index(),x.index()+1,c)&&r.setNodeMarkup(p.map(a.before(o)),c)}return n&&n(r.scrollIntoView()),!0}}const fPs=mPs(),pPs=(s,t)=>{let{$from:n,to:r}=s.selection,a,i=n.sharedDepth(r);return i==0?!1:(a=n.before(i),t&&t(s.tr.setSelection(hl.create(s.doc,a))),!0)};function gPs(s,t,n){let r=t.nodeBefore,a=t.nodeAfter,i=t.index();return!r||!a||!r.type.compatibleContent(a.type)?!1:!r.content.size&&t.parent.canReplace(i-1,i)?(n&&n(s.tr.delete(t.pos-r.nodeSize,t.pos).scrollIntoView()),!0):!t.parent.canReplace(i,i+1)||!(a.isTextblock||t6(s.doc,t.pos))?!1:(n&&n(s.tr.join(t.pos).scrollIntoView()),!0)}function TPt(s,t,n,r){let a=t.nodeBefore,i=t.nodeAfter,l,o,c=a.type.spec.isolating||i.type.spec.isolating;if(!c&&gPs(s,t,n))return!0;let d=!c&&t.parent.canReplace(t.index(),t.index()+1);if(d&&(l=(o=a.contentMatchAt(a.childCount)).findWrapping(i.type))&&o.matchType(l[0]||i.type).validEnd){if(n){let p=t.pos+i.nodeSize,g=Ua.empty;for(let v=l.length-1;v>=0;v--)g=Ua.from(l[v].create(null,g));g=Ua.from(a.copy(g));let x=s.tr.step(new _0(t.pos-1,p,t.pos,p,new Ii(g,1,0),l.length,!0)),y=x.doc.resolve(p+2*l.length);y.nodeAfter&&y.nodeAfter.type==a.type&&t6(x.doc,y.pos)&&x.join(y.pos),n(x.scrollIntoView())}return!0}let u=i.type.spec.isolating||r>0&&c?null:$l.findFrom(t,1),h=u&&u.$from.blockRange(u.$to),m=h&&eV(h);if(m!=null&&m>=t.depth)return n&&n(s.tr.lift(h,m).scrollIntoView()),!0;if(d&&EU(i,"start",!0)&&EU(a,"end")){let p=a,g=[];for(;g.push(p),!p.isTextblock;)p=p.lastChild;let x=i,y=1;for(;!x.isTextblock;x=x.firstChild)y++;if(p.canReplace(p.childCount,p.childCount,x.content)){if(n){let v=Ua.empty;for(let j=g.length-1;j>=0;j--)v=Ua.from(g[j].copy(v));let _=s.tr.step(new _0(t.pos-g.length,t.pos+i.nodeSize,t.pos+y,t.pos+i.nodeSize-y,new Ii(v,g.length,0),0,!0));n(_.scrollIntoView())}return!0}}return!1}function MPt(s){return function(t,n){let r=t.selection,a=s<0?r.$from:r.$to,i=a.depth;for(;a.node(i).isInline;){if(!i)return!1;i--}return a.node(i).isTextblock?(n&&n(t.tr.setSelection(ul.create(t.doc,s<0?a.start(i):a.end(i)))),!0):!1}}const xPs=MPt(-1),yPs=MPt(1);function vPs(s,t=null){return function(n,r){let{$from:a,$to:i}=n.selection,l=a.blockRange(i),o=l&&kWe(l,s,t);return o?(r&&r(n.tr.wrap(l,o).scrollIntoView()),!0):!1}}function qdt(s,t=null){return function(n,r){let a=!1;for(let i=0;i{if(a)return!1;if(!(!c.isTextblock||c.hasMarkup(s,t)))if(c.type==s)a=!0;else{let u=n.doc.resolve(d),h=u.index();a=u.parent.canReplaceWith(h,h+1,s)}})}if(!a)return!1;if(r){let i=n.tr;for(let l=0;l=2&&t.$from.node(t.depth-1).type.compatibleContent(n)&&t.startIndex==0){if(t.$from.index(t.depth-1)==0)return!1;let c=l.resolve(t.start-2);i=new ESe(c,c,t.depth),t.endIndex=0;u--)i=Ua.from(n[u].type.create(n[u].attrs,i));s.step(new _0(t.start-(r?2:0),t.end,t.start,t.end,new Ii(i,0,0),n.length,!0));let l=0;for(let u=0;ul.childCount>0&&l.firstChild.type==s);return i?n?r.node(i.depth-1).type==s?NPs(t,n,s,i):kPs(t,n,i):!0:!1}}function NPs(s,t,n,r){let a=s.tr,i=r.end,l=r.$to.end(r.depth);ix;g--)p-=a.child(g).nodeSize,r.delete(p-1,p+1);let i=r.doc.resolve(n.start),l=i.nodeAfter;if(r.mapping.map(n.end)!=n.start+i.nodeAfter.nodeSize)return!1;let o=n.startIndex==0,c=n.endIndex==a.childCount,d=i.node(-1),u=i.index(-1);if(!d.canReplace(u+(o?0:1),u+1,l.content.append(c?Ua.empty:Ua.from(a))))return!1;let h=i.pos,m=h+l.nodeSize;return r.step(new _0(h-(o?1:0),m+(c?1:0),h+1,m-1,new Ii((o?Ua.empty:Ua.from(a.copy(Ua.empty))).append(c?Ua.empty:Ua.from(a.copy(Ua.empty))),o?0:1,c?0:1),o?0:1)),t(r.scrollIntoView()),!0}function SPs(s){return function(t,n){let{$from:r,$to:a}=t.selection,i=r.blockRange(a,d=>d.childCount>0&&d.firstChild.type==s);if(!i)return!1;let l=i.startIndex;if(l==0)return!1;let o=i.parent,c=o.child(l-1);if(c.type!=s)return!1;if(n){let d=c.lastChild&&c.lastChild.type==o.type,u=Ua.from(d?s.create():null),h=new Ii(Ua.from(s.create(null,Ua.from(o.type.create(null,u)))),d?3:1,0),m=i.start,p=i.end;n(t.tr.step(new _0(m-(d?3:1),p,m,p,h,1,!0)).scrollIntoView())}return!0}}function SAe(s){const{state:t,transaction:n}=s;let{selection:r}=n,{doc:a}=n,{storedMarks:i}=n;return{...t,apply:t.apply.bind(t),applyTransaction:t.applyTransaction.bind(t),plugins:t.plugins,schema:t.schema,reconfigure:t.reconfigure.bind(t),toJSON:t.toJSON.bind(t),get storedMarks(){return i},get selection(){return r},get doc(){return a},get tr(){return r=n.selection,a=n.doc,i=n.storedMarks,n}}}let CAe=class{constructor(t){this.editor=t.editor,this.rawCommands=this.editor.extensionManager.commands,this.customState=t.state}get hasCustomState(){return!!this.customState}get state(){return this.customState||this.editor.state}get commands(){const{rawCommands:t,editor:n,state:r}=this,{view:a}=n,{tr:i}=r,l=this.buildProps(i);return Object.fromEntries(Object.entries(t).map(([o,c])=>[o,(...u)=>{const h=c(...u)(l);return!i.getMeta("preventDispatch")&&!this.hasCustomState&&a.dispatch(i),h}]))}get chain(){return()=>this.createChain()}get can(){return()=>this.createCan()}createChain(t,n=!0){const{rawCommands:r,editor:a,state:i}=this,{view:l}=a,o=[],c=!!t,d=t||i.tr,u=()=>(!c&&n&&!d.getMeta("preventDispatch")&&!this.hasCustomState&&l.dispatch(d),o.every(m=>m===!0)),h={...Object.fromEntries(Object.entries(r).map(([m,p])=>[m,(...x)=>{const y=this.buildProps(d,n),v=p(...x)(y);return o.push(v),h}])),run:u};return h}createCan(t){const{rawCommands:n,state:r}=this,a=!1,i=t||r.tr,l=this.buildProps(i,a);return{...Object.fromEntries(Object.entries(n).map(([c,d])=>[c,(...u)=>d(...u)({...l,dispatch:void 0})])),chain:()=>this.createChain(i,a)}}buildProps(t,n=!0){const{rawCommands:r,editor:a,state:i}=this,{view:l}=a,o={tr:t,editor:a,view:l,state:SAe({state:i,transaction:t}),dispatch:n?()=>{}:void 0,chain:()=>this.createChain(t,n),can:()=>this.createCan(t),get commands(){return Object.fromEntries(Object.entries(r).map(([c,d])=>[c,(...u)=>d(...u)(o)]))}};return o}},CPs=class{constructor(){this.callbacks={}}on(t,n){return this.callbacks[t]||(this.callbacks[t]=[]),this.callbacks[t].push(n),this}emit(t,...n){const r=this.callbacks[t];return r&&r.forEach(a=>a.apply(this,n)),this}off(t,n){const r=this.callbacks[t];return r&&(n?this.callbacks[t]=r.filter(a=>a!==n):delete this.callbacks[t]),this}once(t,n){const r=(...a)=>{this.off(t,r),n.apply(this,a)};return this.on(t,r)}removeAllListeners(){this.callbacks={}}};function So(s,t,n){return s.config[t]===void 0&&s.parent?So(s.parent,t,n):typeof s.config[t]=="function"?s.config[t].bind({...n,parent:s.parent?So(s.parent,t,n):null}):s.config[t]}function AAe(s){const t=s.filter(a=>a.type==="extension"),n=s.filter(a=>a.type==="node"),r=s.filter(a=>a.type==="mark");return{baseExtensions:t,nodeExtensions:n,markExtensions:r}}function PPt(s){const t=[],{nodeExtensions:n,markExtensions:r}=AAe(s),a=[...n,...r],i={default:null,rendered:!0,renderHTML:null,parseHTML:null,keepOnSplit:!0,isRequired:!1};return s.forEach(l=>{const o={name:l.name,options:l.options,storage:l.storage,extensions:a},c=So(l,"addGlobalAttributes",o);if(!c)return;c().forEach(u=>{u.types.forEach(h=>{Object.entries(u.attributes).forEach(([m,p])=>{t.push({type:h,name:m,attribute:{...i,...p}})})})})}),a.forEach(l=>{const o={name:l.name,options:l.options,storage:l.storage},c=So(l,"addAttributes",o);if(!c)return;const d=c();Object.entries(d).forEach(([u,h])=>{const m={...i,...h};typeof(m==null?void 0:m.default)=="function"&&(m.default=m.default()),m!=null&&m.isRequired&&(m==null?void 0:m.default)===void 0&&delete m.default,t.push({type:l.name,name:u,attribute:m})})}),t}function N0(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 cp(...s){return s.filter(t=>!!t).reduce((t,n)=>{const r={...t};return Object.entries(n).forEach(([a,i])=>{if(!r[a]){r[a]=i;return}if(a==="class"){const o=i?String(i).split(" "):[],c=r[a]?r[a].split(" "):[],d=o.filter(u=>!c.includes(u));r[a]=[...c,...d].join(" ")}else if(a==="style"){const o=i?i.split(";").map(u=>u.trim()).filter(Boolean):[],c=r[a]?r[a].split(";").map(u=>u.trim()).filter(Boolean):[],d=new Map;c.forEach(u=>{const[h,m]=u.split(":").map(p=>p.trim());d.set(h,m)}),o.forEach(u=>{const[h,m]=u.split(":").map(p=>p.trim());d.set(h,m)}),r[a]=Array.from(d.entries()).map(([u,h])=>`${u}: ${h}`).join("; ")}else r[a]=i}),r},{})}function b9e(s,t){return t.filter(n=>n.type===s.type.name).filter(n=>n.attribute.rendered).map(n=>n.attribute.renderHTML?n.attribute.renderHTML(s.attrs)||{}:{[n.name]:s.attrs[n.name]}).reduce((n,r)=>cp(n,r),{})}function IPt(s){return typeof s=="function"}function ad(s,t=void 0,...n){return IPt(s)?t?s.bind(t)(...n):s(...n):s}function APs(s={}){return Object.keys(s).length===0&&s.constructor===Object}function EPs(s){return typeof s!="string"?s:s.match(/^[+-]?(?:\d*\.)?\d+$/)?Number(s):s==="true"?!0:s==="false"?!1:s}function Vdt(s,t){return"style"in s?s:{...s,getAttrs:n=>{const r=s.getAttrs?s.getAttrs(n):s.attrs;if(r===!1)return!1;const a=t.reduce((i,l)=>{const o=l.attribute.parseHTML?l.attribute.parseHTML(n):EPs(n.getAttribute(l.name));return o==null?i:{...i,[l.name]:o}},{});return{...r,...a}}}}function Hdt(s){return Object.fromEntries(Object.entries(s).filter(([t,n])=>t==="attrs"&&APs(n)?!1:n!=null))}function TPs(s,t){var n;const r=PPt(s),{nodeExtensions:a,markExtensions:i}=AAe(s),l=(n=a.find(d=>So(d,"topNode")))===null||n===void 0?void 0:n.name,o=Object.fromEntries(a.map(d=>{const u=r.filter(v=>v.type===d.name),h={name:d.name,options:d.options,storage:d.storage,editor:t},m=s.reduce((v,_)=>{const j=So(_,"extendNodeSchema",h);return{...v,...j?j(d):{}}},{}),p=Hdt({...m,content:ad(So(d,"content",h)),marks:ad(So(d,"marks",h)),group:ad(So(d,"group",h)),inline:ad(So(d,"inline",h)),atom:ad(So(d,"atom",h)),selectable:ad(So(d,"selectable",h)),draggable:ad(So(d,"draggable",h)),code:ad(So(d,"code",h)),whitespace:ad(So(d,"whitespace",h)),linebreakReplacement:ad(So(d,"linebreakReplacement",h)),defining:ad(So(d,"defining",h)),isolating:ad(So(d,"isolating",h)),attrs:Object.fromEntries(u.map(v=>{var _;return[v.name,{default:(_=v==null?void 0:v.attribute)===null||_===void 0?void 0:_.default}]}))}),g=ad(So(d,"parseHTML",h));g&&(p.parseDOM=g.map(v=>Vdt(v,u)));const x=So(d,"renderHTML",h);x&&(p.toDOM=v=>x({node:v,HTMLAttributes:b9e(v,u)}));const y=So(d,"renderText",h);return y&&(p.toText=y),[d.name,p]})),c=Object.fromEntries(i.map(d=>{const u=r.filter(y=>y.type===d.name),h={name:d.name,options:d.options,storage:d.storage,editor:t},m=s.reduce((y,v)=>{const _=So(v,"extendMarkSchema",h);return{...y,..._?_(d):{}}},{}),p=Hdt({...m,inclusive:ad(So(d,"inclusive",h)),excludes:ad(So(d,"excludes",h)),group:ad(So(d,"group",h)),spanning:ad(So(d,"spanning",h)),code:ad(So(d,"code",h)),attrs:Object.fromEntries(u.map(y=>{var v;return[y.name,{default:(v=y==null?void 0:y.attribute)===null||v===void 0?void 0:v.default}]}))}),g=ad(So(d,"parseHTML",h));g&&(p.parseDOM=g.map(y=>Vdt(y,u)));const x=So(d,"renderHTML",h);return x&&(p.toDOM=y=>x({mark:y,HTMLAttributes:b9e(y,u)})),[d.name,p]}));return new y6t({topNode:l,nodes:o,marks:c})}function xLe(s,t){return t.nodes[s]||t.marks[s]||null}function Gdt(s,t){return Array.isArray(t)?t.some(n=>(typeof n=="string"?n:n.name)===s.name):t}function qWe(s,t){const n=kF.fromSchema(t).serializeFragment(s),a=document.implementation.createHTMLDocument().createElement("div");return a.appendChild(n),a.innerHTML}const MPs=(s,t=500)=>{let n="";const r=s.parentOffset;return s.parent.nodesBetween(Math.max(0,r-t),r,(a,i,l,o)=>{var c,d;const u=((d=(c=a.type.spec).toText)===null||d===void 0?void 0:d.call(c,{node:a,pos:i,parent:l,index:o}))||a.textContent||"%leaf%";n+=a.isAtom&&!a.isText?u:u.slice(0,Math.max(0,r-i))}),n};function VWe(s){return Object.prototype.toString.call(s)==="[object RegExp]"}class EAe{constructor(t){this.find=t.find,this.handler=t.handler}}const PPs=(s,t)=>{if(VWe(t))return t.exec(s);const n=t(s);if(!n)return null;const r=[n.text];return r.index=n.index,r.input=s,r.data=n.data,n.replaceWith&&(n.text.includes(n.replaceWith)||console.warn('[tiptap warn]: "inputRuleMatch.replaceWith" must be part of "inputRuleMatch.text".'),r.push(n.replaceWith)),r};function xre(s){var t;const{editor:n,from:r,to:a,text:i,rules:l,plugin:o}=s,{view:c}=n;if(c.composing)return!1;const d=c.state.doc.resolve(r);if(d.parent.type.spec.code||!((t=d.nodeBefore||d.nodeAfter)===null||t===void 0)&&t.marks.find(m=>m.type.spec.code))return!1;let u=!1;const h=MPs(d)+i;return l.forEach(m=>{if(u)return;const p=PPs(h,m.find);if(!p)return;const g=c.state.tr,x=SAe({state:c.state,transaction:g}),y={from:r-(p[0].length-i.length),to:a},{commands:v,chain:_,can:j}=new CAe({editor:n,state:x});m.handler({state:x,range:y,match:p,commands:v,chain:_,can:j})===null||!g.steps.length||(g.setMeta(o,{transform:g,from:r,to:a,text:i}),c.dispatch(g),u=!0)}),u}function IPs(s){const{editor:t,rules:n}=s,r=new Iy({state:{init(){return null},apply(a,i,l){const o=a.getMeta(r);if(o)return o;const c=a.getMeta("applyInputRules");return!!c&&setTimeout(()=>{let{text:u}=c;typeof u=="string"?u=u:u=qWe(Ua.from(u),l.schema);const{from:h}=c,m=h+u.length;xre({editor:t,from:h,to:m,text:u,rules:n,plugin:r})}),a.selectionSet||a.docChanged?null:i}},props:{handleTextInput(a,i,l,o){return xre({editor:t,from:i,to:l,text:o,rules:n,plugin:r})},handleDOMEvents:{compositionend:a=>(setTimeout(()=>{const{$cursor:i}=a.state.selection;i&&xre({editor:t,from:i.pos,to:i.pos,text:"",rules:n,plugin:r})}),!1)},handleKeyDown(a,i){if(i.key!=="Enter")return!1;const{$cursor:l}=a.state.selection;return l?xre({editor:t,from:l.pos,to:l.pos,text:` `,rules:n,plugin:r}):!1}},isInputRules:!0});return r}function LPs(s){return Object.prototype.toString.call(s).slice(8,-1)}function yre(s){return LPs(s)!=="Object"?!1:s.constructor===Object&&Object.getPrototypeOf(s)===Object.prototype}function TAe(s,t){const n={...s};return yre(s)&&yre(t)&&Object.keys(t).forEach(r=>{yre(t[r])&&yre(s[r])?n[r]=TAe(s[r],t[r]):n[r]=t[r]}),n}class yk{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=ad(So(this,"addOptions",{name:this.name}))),this.storage=ad(So(this,"addStorage",{name:this.name,options:this.options}))||{}}static create(t={}){return new yk(t)}configure(t={}){const n=this.extend({...this.config,addOptions:()=>TAe(this.options,t)});return n.name=this.name,n.parent=this.parent,n}extend(t={}){const n=new yk(t);return n.parent=this,this.child=n,n.name=t.name?t.name:n.parent.name,t.defaultOptions&&Object.keys(t.defaultOptions).length>0&&console.warn(`[tiptap warn]: BREAKING CHANGE: "defaultOptions" is deprecated. Please use "addOptions" instead. Found in extension: "${n.name}".`),n.options=ad(So(n,"addOptions",{name:n.name})),n.storage=ad(So(n,"addStorage",{name:n.name,options:n.options})),n}static handleExit({editor:t,mark:n}){const{tr:r}=t.state,a=t.state.selection.$from;if(a.pos===a.end()){const l=a.marks();if(!!!l.find(d=>(d==null?void 0:d.type.name)===n.name))return!1;const c=l.find(d=>(d==null?void 0:d.type.name)===n.name);return c&&r.removeStoredMark(c),r.insertText(" ",a.pos),t.view.dispatch(r),!0}return!1}}function RPs(s){return typeof s=="number"}class DPs{constructor(t){this.find=t.find,this.handler=t.handler}}const OPs=(s,t,n)=>{if(VWe(t))return[...s.matchAll(t)];const r=t(s,n);return r?r.map(a=>{const i=[a.text];return i.index=a.index,i.input=s,i.data=a.data,a.replaceWith&&(a.text.includes(a.replaceWith)||console.warn('[tiptap warn]: "pasteRuleMatch.replaceWith" must be part of "pasteRuleMatch.text".'),i.push(a.replaceWith)),i}):[]};function FPs(s){const{editor:t,state:n,from:r,to:a,rule:i,pasteEvent:l,dropEvent:o}=s,{commands:c,chain:d,can:u}=new CAe({editor:t,state:n}),h=[];return n.doc.nodesBetween(r,a,(p,g)=>{if(!p.isTextblock||p.type.spec.code)return;const x=Math.max(r,g),y=Math.min(a,g+p.content.size),v=p.textBetween(x-g,y-g,void 0,"");OPs(v,i.find,l).forEach(j=>{if(j.index===void 0)return;const C=x+j.index+1,A=C+j[0].length,M={from:n.tr.mapping.map(C),to:n.tr.mapping.map(A)},I=i.handler({state:n,range:M,match:j,commands:c,chain:d,can:u,pasteEvent:l,dropEvent:o});h.push(I)})}),h.every(p=>p!==null)}let vre=null;const zPs=s=>{var t;const n=new ClipboardEvent("paste",{clipboardData:new DataTransfer});return(t=n.clipboardData)===null||t===void 0||t.setData("text/html",s),n};function BPs(s){const{editor:t,rules:n}=s;let r=null,a=!1,i=!1,l=typeof ClipboardEvent<"u"?new ClipboardEvent("paste"):null,o;try{o=typeof DragEvent<"u"?new DragEvent("drop"):null}catch{o=null}const c=({state:u,from:h,to:m,rule:p,pasteEvt:g})=>{const x=u.tr,y=SAe({state:u,transaction:x});if(!(!FPs({editor:t,state:y,from:Math.max(h-1,0),to:m.b-1,rule:p,pasteEvent:g,dropEvent:o})||!x.steps.length)){try{o=typeof DragEvent<"u"?new DragEvent("drop"):null}catch{o=null}return l=typeof ClipboardEvent<"u"?new ClipboardEvent("paste"):null,x}};return n.map(u=>new Iy({view(h){const m=g=>{var x;r=!((x=h.dom.parentElement)===null||x===void 0)&&x.contains(g.target)?h.dom.parentElement:null,r&&(vre=t)},p=()=>{vre&&(vre=null)};return window.addEventListener("dragstart",m),window.addEventListener("dragend",p),{destroy(){window.removeEventListener("dragstart",m),window.removeEventListener("dragend",p)}}},props:{handleDOMEvents:{drop:(h,m)=>{if(i=r===h.dom.parentElement,o=m,!i){const p=vre;p!=null&&p.isEditable&&setTimeout(()=>{const g=p.state.selection;g&&p.commands.deleteRange({from:g.from,to:g.to})},10)}return!1},paste:(h,m)=>{var p;const g=(p=m.clipboardData)===null||p===void 0?void 0:p.getData("text/html");return l=m,a=!!(g!=null&&g.includes("data-pm-slice")),!1}}},appendTransaction:(h,m,p)=>{const g=h[0],x=g.getMeta("uiEvent")==="paste"&&!a,y=g.getMeta("uiEvent")==="drop"&&!i,v=g.getMeta("applyPasteRules"),_=!!v;if(!x&&!y&&!_)return;if(_){let{text:A}=v;typeof A=="string"?A=A:A=qWe(Ua.from(A),p.schema);const{from:M}=v,I=M+A.length,P=zPs(A);return c({rule:u,state:p,from:M,to:{b:I},pasteEvt:P})}const j=m.doc.content.findDiffStart(p.doc.content),C=m.doc.content.findDiffEnd(p.doc.content);if(!(!RPs(j)||!C||j===C.b))return c({rule:u,state:p,from:j,to:C,pasteEvt:l})}}))}function $Ps(s){const t=s.filter((n,r)=>s.indexOf(n)!==r);return Array.from(new Set(t))}class xz{constructor(t,n){this.splittableMarks=[],this.editor=n,this.extensions=xz.resolve(t),this.schema=TPs(this.extensions,n),this.setupExtensions()}static resolve(t){const n=xz.sort(xz.flatten(t)),r=$Ps(n.map(a=>a.name));return r.length&&console.warn(`[tiptap warn]: Duplicate extension names found: [${r.map(a=>`'${a}'`).join(", ")}]. This can lead to issues.`),n}static flatten(t){return t.map(n=>{const r={name:n.name,options:n.options,storage:n.storage},a=So(n,"addExtensions",r);return a?[n,...this.flatten(a())]:n}).flat(10)}static sort(t){return t.sort((r,a)=>{const i=So(r,"priority")||100,l=So(a,"priority")||100;return i>l?-1:i{const r={name:n.name,options:n.options,storage:n.storage,editor:this.editor,type:xLe(n.name,this.schema)},a=So(n,"addCommands",r);return a?{...t,...a()}:t},{})}get plugins(){const{editor:t}=this,n=xz.sort([...this.extensions].reverse()),r=[],a=[],i=n.map(l=>{const o={name:l.name,options:l.options,storage:l.storage,editor:t,type:xLe(l.name,this.schema)},c=[],d=So(l,"addKeyboardShortcuts",o);let u={};if(l.type==="mark"&&So(l,"exitable",o)&&(u.ArrowRight=()=>yk.handleExit({editor:t,mark:l})),d){const x=Object.fromEntries(Object.entries(d()).map(([y,v])=>[y,()=>v({editor:t})]));u={...u,...x}}const h=iPs(u);c.push(h);const m=So(l,"addInputRules",o);Gdt(l,t.options.enableInputRules)&&m&&r.push(...m());const p=So(l,"addPasteRules",o);Gdt(l,t.options.enablePasteRules)&&p&&a.push(...p());const g=So(l,"addProseMirrorPlugins",o);if(g){const x=g();c.push(...x)}return c}).flat();return[IPs({editor:t,rules:r}),...BPs({editor:t,rules:a}),...i]}get attributes(){return PPt(this.extensions)}get nodeViews(){const{editor:t}=this,{nodeExtensions:n}=AAe(this.extensions);return Object.fromEntries(n.filter(r=>!!So(r,"addNodeView")).map(r=>{const a=this.attributes.filter(c=>c.type===r.name),i={name:r.name,options:r.options,storage:r.storage,editor:t,type:N0(r.name,this.schema)},l=So(r,"addNodeView",i);if(!l)return[];const o=(c,d,u,h,m)=>{const p=b9e(c,a);return l()({node:c,view:d,getPos:u,decorations:h,innerDecorations:m,editor:t,extension:r,HTMLAttributes:p})};return[r.name,o]}))}setupExtensions(){this.extensions.forEach(t=>{var n;this.editor.extensionStorage[t.name]=t.storage;const r={name:t.name,options:t.options,storage:t.storage,editor:this.editor,type:xLe(t.name,this.schema)};t.type==="mark"&&(!((n=ad(So(t,"keepOnSplit",r)))!==null&&n!==void 0)||n)&&this.splittableMarks.push(t.name);const a=So(t,"onBeforeCreate",r),i=So(t,"onCreate",r),l=So(t,"onUpdate",r),o=So(t,"onSelectionUpdate",r),c=So(t,"onTransaction",r),d=So(t,"onFocus",r),u=So(t,"onBlur",r),h=So(t,"onDestroy",r);a&&this.editor.on("beforeCreate",a),i&&this.editor.on("create",i),l&&this.editor.on("update",l),o&&this.editor.on("selectionUpdate",o),c&&this.editor.on("transaction",c),d&&this.editor.on("focus",d),u&&this.editor.on("blur",u),h&&this.editor.on("destroy",h)})}}class xv{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=ad(So(this,"addOptions",{name:this.name}))),this.storage=ad(So(this,"addStorage",{name:this.name,options:this.options}))||{}}static create(t={}){return new xv(t)}configure(t={}){const n=this.extend({...this.config,addOptions:()=>TAe(this.options,t)});return n.name=this.name,n.parent=this.parent,n}extend(t={}){const n=new xv({...this.config,...t});return n.parent=this,this.child=n,n.name=t.name?t.name:n.parent.name,t.defaultOptions&&Object.keys(t.defaultOptions).length>0&&console.warn(`[tiptap warn]: BREAKING CHANGE: "defaultOptions" is deprecated. Please use "addOptions" instead. Found in extension: "${n.name}".`),n.options=ad(So(n,"addOptions",{name:n.name})),n.storage=ad(So(n,"addStorage",{name:n.name,options:n.options})),n}}function LPt(s,t,n){const{from:r,to:a}=t,{blockSeparator:i=` `,textSerializers:l={}}=n||{};let o="";return s.nodesBetween(r,a,(c,d,u,h)=>{var m;c.isBlock&&d>r&&(o+=i);const p=l==null?void 0:l[c.type.name];if(p)return u&&(o+=p({node:c,pos:d,parent:u,index:h,range:t})),!1;c.isText&&(o+=(m=c==null?void 0:c.text)===null||m===void 0?void 0:m.slice(Math.max(r,d)-d,a-d))}),o}function RPt(s){return Object.fromEntries(Object.entries(s.nodes).filter(([,t])=>t.spec.toText).map(([t,n])=>[t,n.spec.toText]))}const UPs=xv.create({name:"clipboardTextSerializer",addOptions(){return{blockSeparator:void 0}},addProseMirrorPlugins(){return[new Iy({key:new b1("clipboardTextSerializer"),props:{clipboardTextSerializer:()=>{const{editor:s}=this,{state:t,schema:n}=s,{doc:r,selection:a}=t,{ranges:i}=a,l=Math.min(...i.map(u=>u.$from.pos)),o=Math.max(...i.map(u=>u.$to.pos)),c=RPt(n);return LPt(r,{from:l,to:o},{...this.options.blockSeparator!==void 0?{blockSeparator:this.options.blockSeparator}:{},textSerializers:c})}}})]}}),qPs=()=>({editor:s,view:t})=>(requestAnimationFrame(()=>{var n;s.isDestroyed||(t.dom.blur(),(n=window==null?void 0:window.getSelection())===null||n===void 0||n.removeAllRanges())}),!0),VPs=(s=!1)=>({commands:t})=>t.setContent("",s),HPs=()=>({state:s,tr:t,dispatch:n})=>{const{selection:r}=t,{ranges:a}=r;return n&&a.forEach(({$from:i,$to:l})=>{s.doc.nodesBetween(i.pos,l.pos,(o,c)=>{if(o.type.isText)return;const{doc:d,mapping:u}=t,h=d.resolve(u.map(c)),m=d.resolve(u.map(c+o.nodeSize)),p=h.blockRange(m);if(!p)return;const g=eV(p);if(o.type.isTextblock){const{defaultType:x}=h.parent.contentMatchAt(h.index());t.setNodeMarkup(p.start,x)}(g||g===0)&&t.lift(p,g)})}),!0},GPs=s=>t=>s(t),WPs=()=>({state:s,dispatch:t})=>APt(s,t),KPs=(s,t)=>({editor:n,tr:r})=>{const{state:a}=n,i=a.doc.slice(s.from,s.to);r.deleteRange(s.from,s.to);const l=r.mapping.map(t);return r.insert(l,i.content),r.setSelection(new ul(r.doc.resolve(Math.max(l-1,0)))),!0},YPs=()=>({tr:s,dispatch:t})=>{const{selection:n}=s,r=n.$anchor.node();if(r.content.size>0)return!1;const a=s.selection.$anchor;for(let i=a.depth;i>0;i-=1)if(a.node(i).type===r.type){if(t){const o=a.before(i),c=a.after(i);s.delete(o,c).scrollIntoView()}return!0}return!1},ZPs=s=>({tr:t,state:n,dispatch:r})=>{const a=N0(s,n.schema),i=t.selection.$anchor;for(let l=i.depth;l>0;l-=1)if(i.node(l).type===a){if(r){const c=i.before(l),d=i.after(l);t.delete(c,d).scrollIntoView()}return!0}return!1},XPs=s=>({tr:t,dispatch:n})=>{const{from:r,to:a}=s;return n&&t.delete(r,a),!0},QPs=()=>({state:s,dispatch:t})=>FWe(s,t),JPs=()=>({commands:s})=>s.keyboardShortcut("Enter"),eIs=()=>({state:s,dispatch:t})=>hPs(s,t);function OSe(s,t,n={strict:!0}){const r=Object.keys(t);return r.length?r.every(a=>n.strict?t[a]===s[a]:VWe(t[a])?t[a].test(s[a]):t[a]===s[a]):!0}function DPt(s,t,n={}){return s.find(r=>r.type===t&&OSe(Object.fromEntries(Object.keys(n).map(a=>[a,r.attrs[a]])),n))}function Wdt(s,t,n={}){return!!DPt(s,t,n)}function HWe(s,t,n){var r;if(!s||!t)return;let a=s.parent.childAfter(s.parentOffset);if((!a.node||!a.node.marks.some(u=>u.type===t))&&(a=s.parent.childBefore(s.parentOffset)),!a.node||!a.node.marks.some(u=>u.type===t)||(n=n||((r=a.node.marks[0])===null||r===void 0?void 0:r.attrs),!DPt([...a.node.marks],t,n)))return;let l=a.index,o=s.start()+a.offset,c=l+1,d=o+a.node.nodeSize;for(;l>0&&Wdt([...s.parent.child(l-1).marks],t,n);)l-=1,o-=s.parent.child(l).nodeSize;for(;c({tr:n,state:r,dispatch:a})=>{const i=n6(s,r.schema),{doc:l,selection:o}=n,{$from:c,from:d,to:u}=o;if(a){const h=HWe(c,i,t);if(h&&h.from<=d&&h.to>=u){const m=ul.create(l,h.from,h.to);n.setSelection(m)}}return!0},sIs=s=>t=>{const n=typeof s=="function"?s(t):s;for(let r=0;r({editor:n,view:r,tr:a,dispatch:i})=>{t={scrollIntoView:!0,...t};const l=()=>{(FSe()||Kdt())&&r.dom.focus(),requestAnimationFrame(()=>{n.isDestroyed||(r.focus(),nIs()&&!FSe()&&!Kdt()&&r.dom.focus({preventScroll:!0}))})};if(r.hasFocus()&&s===null||s===!1)return!0;if(i&&s===null&&!OPt(n.state.selection))return l(),!0;const o=FPt(a.doc,s)||n.state.selection,c=n.state.selection.eq(o);return i&&(c||a.setSelection(o),c&&a.storedMarks&&a.setStoredMarks(a.storedMarks),l()),!0},aIs=(s,t)=>n=>s.every((r,a)=>t(r,{...n,index:a})),iIs=(s,t)=>({tr:n,commands:r})=>r.insertContentAt({from:n.selection.from,to:n.selection.to},s,t),zPt=s=>{const t=s.childNodes;for(let n=t.length-1;n>=0;n-=1){const r=t[n];r.nodeType===3&&r.nodeValue&&/^(\n\s\s|\n)$/.test(r.nodeValue)?s.removeChild(r):r.nodeType===1&&zPt(r)}return s};function bre(s){const t=`${s}`,n=new window.DOMParser().parseFromString(t,"text/html").body;return zPt(n)}function hX(s,t,n){if(s instanceof cM||s instanceof Ua)return s;n={slice:!0,parseOptions:{},...n};const r=typeof s=="object"&&s!==null,a=typeof s=="string";if(r)try{if(Array.isArray(s)&&s.length>0)return Ua.fromArray(s.map(o=>t.nodeFromJSON(o)));const l=t.nodeFromJSON(s);return n.errorOnInvalidContent&&l.check(),l}catch(i){if(n.errorOnInvalidContent)throw new Error("[tiptap error]: Invalid JSON content",{cause:i});return console.warn("[tiptap warn]: Invalid content.","Passed value:",s,"Error:",i),hX("",t,n)}if(a){if(n.errorOnInvalidContent){let l=!1,o="";const c=new y6t({topNode:t.spec.topNode,marks:t.spec.marks,nodes:t.spec.nodes.append({__tiptap__private__unknown__catch__all__node:{content:"inline*",group:"block",parseDOM:[{tag:"*",getAttrs:d=>(l=!0,o=typeof d=="string"?d:d.outerHTML,null)}]}})});if(n.slice?CY.fromSchema(c).parseSlice(bre(s),n.parseOptions):CY.fromSchema(c).parse(bre(s),n.parseOptions),n.errorOnInvalidContent&&l)throw new Error("[tiptap error]: Invalid HTML content",{cause:new Error(`Invalid element found: ${o}`)})}const i=CY.fromSchema(t);return n.slice?i.parseSlice(bre(s),n.parseOptions).content:i.parse(bre(s),n.parseOptions)}return hX("",t,n)}function oIs(s,t,n){const r=s.steps.length-1;if(r{l===0&&(l=u)}),s.setSelection($l.near(s.doc.resolve(l),n))}const lIs=s=>!("type"in s),cIs=(s,t,n)=>({tr:r,dispatch:a,editor:i})=>{var l;if(a){n={parseOptions:i.options.parseOptions,updateSelection:!0,applyInputRules:!1,applyPasteRules:!1,...n};let o;const c=y=>{i.emit("contentError",{editor:i,error:y,disableCollaboration:()=>{i.storage.collaboration&&(i.storage.collaboration.isDisabled=!0)}})},d={preserveWhitespace:"full",...n.parseOptions};if(!n.errorOnInvalidContent&&!i.options.enableContentCheck&&i.options.emitContentError)try{hX(t,i.schema,{parseOptions:d,errorOnInvalidContent:!0})}catch(y){c(y)}try{o=hX(t,i.schema,{parseOptions:d,errorOnInvalidContent:(l=n.errorOnInvalidContent)!==null&&l!==void 0?l:i.options.enableContentCheck})}catch(y){return c(y),!1}let{from:u,to:h}=typeof s=="number"?{from:s,to:s}:{from:s.from,to:s.to},m=!0,p=!0;if((lIs(o)?o:[o]).forEach(y=>{y.check(),m=m?y.isText&&y.marks.length===0:!1,p=p?y.isBlock:!1}),u===h&&p){const{parent:y}=r.doc.resolve(u);y.isTextblock&&!y.type.spec.code&&!y.childCount&&(u-=1,h+=1)}let x;if(m){if(Array.isArray(t))x=t.map(y=>y.text||"").join("");else if(t instanceof Ua){let y="";t.forEach(v=>{v.text&&(y+=v.text)}),x=y}else typeof t=="object"&&t&&t.text?x=t.text:x=t;r.insertText(x,u,h)}else x=o,r.replaceWith(u,h,x);n.updateSelection&&oIs(r,r.steps.length-1,-1),n.applyInputRules&&r.setMeta("applyInputRules",{from:u,text:x}),n.applyPasteRules&&r.setMeta("applyPasteRules",{from:u,text:x})}return!0},dIs=()=>({state:s,dispatch:t})=>cPs(s,t),uIs=()=>({state:s,dispatch:t})=>dPs(s,t),hIs=()=>({state:s,dispatch:t})=>_Pt(s,t),mIs=()=>({state:s,dispatch:t})=>kPt(s,t),fIs=()=>({state:s,dispatch:t,tr:n})=>{try{const r=_Ae(s.doc,s.selection.$from.pos,-1);return r==null?!1:(n.join(r,2),t&&t(n),!0)}catch{return!1}},pIs=()=>({state:s,dispatch:t,tr:n})=>{try{const r=_Ae(s.doc,s.selection.$from.pos,1);return r==null?!1:(n.join(r,2),t&&t(n),!0)}catch{return!1}},gIs=()=>({state:s,dispatch:t})=>oPs(s,t),xIs=()=>({state:s,dispatch:t})=>lPs(s,t);function BPt(){return typeof navigator<"u"?/Mac/.test(navigator.platform):!1}function yIs(s){const t=s.split(/-(?!$)/);let n=t[t.length-1];n==="Space"&&(n=" ");let r,a,i,l;for(let o=0;o({editor:t,view:n,tr:r,dispatch:a})=>{const i=yIs(s).split(/-(?!$)/),l=i.find(d=>!["Alt","Ctrl","Meta","Shift"].includes(d)),o=new KeyboardEvent("keydown",{key:l==="Space"?" ":l,altKey:i.includes("Alt"),ctrlKey:i.includes("Ctrl"),metaKey:i.includes("Meta"),shiftKey:i.includes("Shift"),bubbles:!0,cancelable:!0}),c=t.captureTransaction(()=>{n.someProp("handleKeyDown",d=>d(n,o))});return c==null||c.steps.forEach(d=>{const u=d.map(r.mapping);u&&a&&r.maybeStep(u)}),!0};function mX(s,t,n={}){const{from:r,to:a,empty:i}=s.selection,l=t?N0(t,s.schema):null,o=[];s.doc.nodesBetween(r,a,(h,m)=>{if(h.isText)return;const p=Math.max(r,m),g=Math.min(a,m+h.nodeSize);o.push({node:h,from:p,to:g})});const c=a-r,d=o.filter(h=>l?l.name===h.node.type.name:!0).filter(h=>OSe(h.node.attrs,n,{strict:!1}));return i?!!d.length:d.reduce((h,m)=>h+m.to-m.from,0)>=c}const bIs=(s,t={})=>({state:n,dispatch:r})=>{const a=N0(s,n.schema);return mX(n,a,t)?uPs(n,r):!1},_Is=()=>({state:s,dispatch:t})=>EPt(s,t),wIs=s=>({state:t,dispatch:n})=>{const r=N0(s,t.schema);return jPs(r)(t,n)},jIs=()=>({state:s,dispatch:t})=>CPt(s,t);function MAe(s,t){return t.nodes[s]?"node":t.marks[s]?"mark":null}function Ydt(s,t){const n=typeof t=="string"?[t]:t;return Object.keys(s).reduce((r,a)=>(n.includes(a)||(r[a]=s[a]),r),{})}const NIs=(s,t)=>({tr:n,state:r,dispatch:a})=>{let i=null,l=null;const o=MAe(typeof s=="string"?s:s.name,r.schema);return o?(o==="node"&&(i=N0(s,r.schema)),o==="mark"&&(l=n6(s,r.schema)),a&&n.selection.ranges.forEach(c=>{r.doc.nodesBetween(c.$from.pos,c.$to.pos,(d,u)=>{i&&i===d.type&&n.setNodeMarkup(u,void 0,Ydt(d.attrs,t)),l&&d.marks.length&&d.marks.forEach(h=>{l===h.type&&n.addMark(u,u+d.nodeSize,l.create(Ydt(h.attrs,t)))})})}),!0):!1},kIs=()=>({tr:s,dispatch:t})=>(t&&s.scrollIntoView(),!0),SIs=()=>({tr:s,dispatch:t})=>{if(t){const n=new Jw(s.doc);s.setSelection(n)}return!0},CIs=()=>({state:s,dispatch:t})=>jPt(s,t),AIs=()=>({state:s,dispatch:t})=>SPt(s,t),EIs=()=>({state:s,dispatch:t})=>pPs(s,t),TIs=()=>({state:s,dispatch:t})=>yPs(s,t),MIs=()=>({state:s,dispatch:t})=>xPs(s,t);function _9e(s,t,n={},r={}){return hX(s,t,{slice:!1,parseOptions:n,errorOnInvalidContent:r.errorOnInvalidContent})}const PIs=(s,t=!1,n={},r={})=>({editor:a,tr:i,dispatch:l,commands:o})=>{var c,d;const{doc:u}=i;if(n.preserveWhitespace!=="full"){const h=_9e(s,a.schema,n,{errorOnInvalidContent:(c=r.errorOnInvalidContent)!==null&&c!==void 0?c:a.options.enableContentCheck});return l&&i.replaceWith(0,u.content.size,h).setMeta("preventUpdate",!t),!0}return l&&i.setMeta("preventUpdate",!t),o.insertContentAt({from:0,to:u.content.size},s,{parseOptions:n,errorOnInvalidContent:(d=r.errorOnInvalidContent)!==null&&d!==void 0?d:a.options.enableContentCheck})};function $Pt(s,t){const n=n6(t,s.schema),{from:r,to:a,empty:i}=s.selection,l=[];i?(s.storedMarks&&l.push(...s.storedMarks),l.push(...s.selection.$head.marks())):s.doc.nodesBetween(r,a,c=>{l.push(...c.marks)});const o=l.find(c=>c.type.name===n.name);return o?{...o.attrs}:{}}function IIs(s,t){const n=new SWe(s);return t.forEach(r=>{r.steps.forEach(a=>{n.step(a)})}),n}function LIs(s){for(let t=0;t{n(a)&&r.push({node:a,pos:i})}),r}function UPt(s,t){for(let n=s.depth;n>0;n-=1){const r=s.node(n);if(t(r))return{pos:n>0?s.before(n):0,start:s.start(n),depth:n,node:r}}}function GWe(s){return t=>UPt(t.$from,s)}function DIs(s,t){const n={from:0,to:s.content.size};return LPt(s,n,t)}function OIs(s,t){const n=N0(t,s.schema),{from:r,to:a}=s.selection,i=[];s.doc.nodesBetween(r,a,o=>{i.push(o)});const l=i.reverse().find(o=>o.type.name===n.name);return l?{...l.attrs}:{}}function qPt(s,t){const n=MAe(typeof t=="string"?t:t.name,s.schema);return n==="node"?OIs(s,t):n==="mark"?$Pt(s,t):{}}function FIs(s,t=JSON.stringify){const n={};return s.filter(r=>{const a=t(r);return Object.prototype.hasOwnProperty.call(n,a)?!1:n[a]=!0})}function zIs(s){const t=FIs(s);return t.length===1?t:t.filter((n,r)=>!t.filter((i,l)=>l!==r).some(i=>n.oldRange.from>=i.oldRange.from&&n.oldRange.to<=i.oldRange.to&&n.newRange.from>=i.newRange.from&&n.newRange.to<=i.newRange.to))}function BIs(s){const{mapping:t,steps:n}=s,r=[];return t.maps.forEach((a,i)=>{const l=[];if(a.ranges.length)a.forEach((o,c)=>{l.push({from:o,to:c})});else{const{from:o,to:c}=n[i];if(o===void 0||c===void 0)return;l.push({from:o,to:c})}l.forEach(({from:o,to:c})=>{const d=t.slice(i).map(o,-1),u=t.slice(i).map(c),h=t.invert().map(d,-1),m=t.invert().map(u);r.push({oldRange:{from:h,to:m},newRange:{from:d,to:u}})})}),zIs(r)}function WWe(s,t,n){const r=[];return s===t?n.resolve(s).marks().forEach(a=>{const i=n.resolve(s),l=HWe(i,a.type);l&&r.push({mark:a,...l})}):n.nodesBetween(s,t,(a,i)=>{!a||(a==null?void 0:a.nodeSize)===void 0||r.push(...a.marks.map(l=>({from:i,to:i+a.nodeSize,mark:l})))}),r}function pNe(s,t,n){return Object.fromEntries(Object.entries(n).filter(([r])=>{const a=s.find(i=>i.type===t&&i.name===r);return a?a.attribute.keepOnSplit:!1}))}function w9e(s,t,n={}){const{empty:r,ranges:a}=s.selection,i=t?n6(t,s.schema):null;if(r)return!!(s.storedMarks||s.selection.$from.marks()).filter(h=>i?i.name===h.type.name:!0).find(h=>OSe(h.attrs,n,{strict:!1}));let l=0;const o=[];if(a.forEach(({$from:h,$to:m})=>{const p=h.pos,g=m.pos;s.doc.nodesBetween(p,g,(x,y)=>{if(!x.isText&&!x.marks.length)return;const v=Math.max(p,y),_=Math.min(g,y+x.nodeSize),j=_-v;l+=j,o.push(...x.marks.map(C=>({mark:C,from:v,to:_})))})}),l===0)return!1;const c=o.filter(h=>i?i.name===h.mark.type.name:!0).filter(h=>OSe(h.mark.attrs,n,{strict:!1})).reduce((h,m)=>h+m.to-m.from,0),d=o.filter(h=>i?h.mark.type!==i&&h.mark.type.excludes(i):!0).reduce((h,m)=>h+m.to-m.from,0);return(c>0?c+d:c)>=l}function $Is(s,t,n={}){if(!t)return mX(s,null,n)||w9e(s,null,n);const r=MAe(t,s.schema);return r==="node"?mX(s,t,n):r==="mark"?w9e(s,t,n):!1}function Zdt(s,t){const{nodeExtensions:n}=AAe(t),r=n.find(l=>l.name===s);if(!r)return!1;const a={name:r.name,options:r.options,storage:r.storage},i=ad(So(r,"group",a));return typeof i!="string"?!1:i.split(" ").includes("list")}function KWe(s,{checkChildren:t=!0,ignoreWhitespace:n=!1}={}){var r;if(n){if(s.type.name==="hardBreak")return!0;if(s.isText)return/^\s*$/m.test((r=s.text)!==null&&r!==void 0?r:"")}if(s.isText)return!s.text;if(s.isAtom||s.isLeaf)return!1;if(s.content.childCount===0)return!0;if(t){let a=!0;return s.content.forEach(i=>{a!==!1&&(KWe(i,{ignoreWhitespace:n,checkChildren:t})||(a=!1))}),a}return!1}function UIs(s){return s instanceof hl}function qIs(s,t,n){var r;const{selection:a}=t;let i=null;if(OPt(a)&&(i=a.$cursor),i){const o=(r=s.storedMarks)!==null&&r!==void 0?r:i.marks();return!!n.isInSet(o)||!o.some(c=>c.type.excludes(n))}const{ranges:l}=a;return l.some(({$from:o,$to:c})=>{let d=o.depth===0?s.doc.inlineContent&&s.doc.type.allowsMarkType(n):!1;return s.doc.nodesBetween(o.pos,c.pos,(u,h,m)=>{if(d)return!1;if(u.isInline){const p=!m||m.type.allowsMarkType(n),g=!!n.isInSet(u.marks)||!u.marks.some(x=>x.type.excludes(n));d=p&&g}return!d}),d})}const VIs=(s,t={})=>({tr:n,state:r,dispatch:a})=>{const{selection:i}=n,{empty:l,ranges:o}=i,c=n6(s,r.schema);if(a)if(l){const d=$Pt(r,c);n.addStoredMark(c.create({...d,...t}))}else o.forEach(d=>{const u=d.$from.pos,h=d.$to.pos;r.doc.nodesBetween(u,h,(m,p)=>{const g=Math.max(p,u),x=Math.min(p+m.nodeSize,h);m.marks.find(v=>v.type===c)?m.marks.forEach(v=>{c===v.type&&n.addMark(g,x,c.create({...v.attrs,...t}))}):n.addMark(g,x,c.create(t))})});return qIs(r,n,c)},HIs=(s,t)=>({tr:n})=>(n.setMeta(s,t),!0),GIs=(s,t={})=>({state:n,dispatch:r,chain:a})=>{const i=N0(s,n.schema);let l;return n.selection.$anchor.sameParent(n.selection.$head)&&(l=n.selection.$anchor.parent.attrs),i.isTextblock?a().command(({commands:o})=>qdt(i,{...l,...t})(n)?!0:o.clearNodes()).command(({state:o})=>qdt(i,{...l,...t})(o,r)).run():(console.warn('[tiptap warn]: Currently "setNode()" only supports text block nodes.'),!1)},WIs=s=>({tr:t,dispatch:n})=>{if(n){const{doc:r}=t,a=cD(s,0,r.content.size),i=hl.create(r,a);t.setSelection(i)}return!0},KIs=s=>({tr:t,dispatch:n})=>{if(n){const{doc:r}=t,{from:a,to:i}=typeof s=="number"?{from:s,to:s}:s,l=ul.atStart(r).from,o=ul.atEnd(r).to,c=cD(a,l,o),d=cD(i,l,o),u=ul.create(r,c,d);t.setSelection(u)}return!0},YIs=s=>({state:t,dispatch:n})=>{const r=N0(s,t.schema);return SPs(r)(t,n)};function Xdt(s,t){const n=s.storedMarks||s.selection.$to.parentOffset&&s.selection.$from.marks();if(n){const r=n.filter(a=>t==null?void 0:t.includes(a.type.name));s.tr.ensureMarks(r)}}const ZIs=({keepMarks:s=!0}={})=>({tr:t,state:n,dispatch:r,editor:a})=>{const{selection:i,doc:l}=t,{$from:o,$to:c}=i,d=a.extensionManager.attributes,u=pNe(d,o.node().type.name,o.node().attrs);if(i instanceof hl&&i.node.isBlock)return!o.parentOffset||!k3(l,o.pos)?!1:(r&&(s&&Xdt(n,a.extensionManager.splittableMarks),t.split(o.pos).scrollIntoView()),!0);if(!o.parent.isBlock)return!1;const h=c.parentOffset===c.parent.content.size,m=o.depth===0?void 0:LIs(o.node(-1).contentMatchAt(o.indexAfter(-1)));let p=h&&m?[{type:m,attrs:u}]:void 0,g=k3(t.doc,t.mapping.map(o.pos),1,p);if(!p&&!g&&k3(t.doc,t.mapping.map(o.pos),1,m?[{type:m}]:void 0)&&(g=!0,p=m?[{type:m,attrs:u}]:void 0),r){if(g&&(i instanceof ul&&t.deleteSelection(),t.split(t.mapping.map(o.pos),1,p),m&&!h&&!o.parentOffset&&o.parent.type!==m)){const x=t.mapping.map(o.before()),y=t.doc.resolve(x);o.node(-1).canReplaceWith(y.index(),y.index()+1,m)&&t.setNodeMarkup(t.mapping.map(o.before()),m)}s&&Xdt(n,a.extensionManager.splittableMarks),t.scrollIntoView()}return g},XIs=(s,t={})=>({tr:n,state:r,dispatch:a,editor:i})=>{var l;const o=N0(s,r.schema),{$from:c,$to:d}=r.selection,u=r.selection.node;if(u&&u.isBlock||c.depth<2||!c.sameParent(d))return!1;const h=c.node(-1);if(h.type!==o)return!1;const m=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 v=Ua.empty;const _=c.index(-1)?1:c.index(-2)?2:3;for(let P=c.depth-_;P>=c.depth-3;P-=1)v=Ua.from(c.node(P).copy(v));const j=c.indexAfter(-1){if(I>-1)return!1;P.isTextblock&&P.content.size===0&&(I=R+1)}),I>-1&&n.setSelection(ul.near(n.doc.resolve(I))),n.scrollIntoView()}return!0}const p=d.pos===c.end()?h.contentMatchAt(0).defaultType:null,g={...pNe(m,h.type.name,h.attrs),...t},x={...pNe(m,c.node().type.name,c.node().attrs),...t};n.delete(c.pos,d.pos);const y=p?[{type:o,attrs:g},{type:p,attrs:x}]:[{type:o,attrs:g}];if(!k3(n.doc,c.pos,2))return!1;if(a){const{selection:v,storedMarks:_}=r,{splittableMarks:j}=i.extensionManager,C=_||v.$to.parentOffset&&v.$from.marks();if(n.split(c.pos,2,y).scrollIntoView(),!C||!a)return!0;const A=C.filter(M=>j.includes(M.type.name));n.ensureMarks(A)}return!0},yLe=(s,t)=>{const n=GWe(l=>l.type===t)(s.selection);if(!n)return!0;const r=s.doc.resolve(Math.max(0,n.pos-1)).before(n.depth);if(r===void 0)return!0;const a=s.doc.nodeAt(r);return n.node.type===(a==null?void 0:a.type)&&t6(s.doc,n.pos)&&s.join(n.pos),!0},vLe=(s,t)=>{const n=GWe(l=>l.type===t)(s.selection);if(!n)return!0;const r=s.doc.resolve(n.start).after(n.depth);if(r===void 0)return!0;const a=s.doc.nodeAt(r);return n.node.type===(a==null?void 0:a.type)&&t6(s.doc,r)&&s.join(r),!0},QIs=(s,t,n,r={})=>({editor:a,tr:i,state:l,dispatch:o,chain:c,commands:d,can:u})=>{const{extensions:h,splittableMarks:m}=a.extensionManager,p=N0(s,l.schema),g=N0(t,l.schema),{selection:x,storedMarks:y}=l,{$from:v,$to:_}=x,j=v.blockRange(_),C=y||x.$to.parentOffset&&x.$from.marks();if(!j)return!1;const A=GWe(M=>Zdt(M.type.name,h))(x);if(j.depth>=1&&A&&j.depth-A.depth<=1){if(A.node.type===p)return d.liftListItem(g);if(Zdt(A.node.type.name,h)&&p.validContent(A.node.content)&&o)return c().command(()=>(i.setNodeMarkup(A.pos,p),!0)).command(()=>yLe(i,p)).command(()=>vLe(i,p)).run()}return!n||!C||!o?c().command(()=>u().wrapInList(p,r)?!0:d.clearNodes()).wrapInList(p,r).command(()=>yLe(i,p)).command(()=>vLe(i,p)).run():c().command(()=>{const M=u().wrapInList(p,r),I=C.filter(P=>m.includes(P.type.name));return i.ensureMarks(I),M?!0:d.clearNodes()}).wrapInList(p,r).command(()=>yLe(i,p)).command(()=>vLe(i,p)).run()},JIs=(s,t={},n={})=>({state:r,commands:a})=>{const{extendEmptyMarkRange:i=!1}=n,l=n6(s,r.schema);return w9e(r,l,t)?a.unsetMark(l,{extendEmptyMarkRange:i}):a.setMark(l,t)},eLs=(s,t,n={})=>({state:r,commands:a})=>{const i=N0(s,r.schema),l=N0(t,r.schema),o=mX(r,i,n);let c;return r.selection.$anchor.sameParent(r.selection.$head)&&(c=r.selection.$anchor.parent.attrs),o?a.setNode(l,c):a.setNode(i,{...c,...n})},tLs=(s,t={})=>({state:n,commands:r})=>{const a=N0(s,n.schema);return mX(n,a,t)?r.lift(a):r.wrapIn(a,t)},sLs=()=>({state:s,dispatch:t})=>{const n=s.plugins;for(let r=0;r=0;c-=1)l.step(o.steps[c].invert(o.docs[c]));if(i.text){const c=l.doc.resolve(i.from).marks();l.replaceWith(i.from,i.to,s.schema.text(i.text,c))}else l.delete(i.from,i.to)}return!0}}return!1},nLs=()=>({tr:s,dispatch:t})=>{const{selection:n}=s,{empty:r,ranges:a}=n;return r||t&&a.forEach(i=>{s.removeMark(i.$from.pos,i.$to.pos)}),!0},rLs=(s,t={})=>({tr:n,state:r,dispatch:a})=>{var i;const{extendEmptyMarkRange:l=!1}=t,{selection:o}=n,c=n6(s,r.schema),{$from:d,empty:u,ranges:h}=o;if(!a)return!0;if(u&&l){let{from:m,to:p}=o;const g=(i=d.marks().find(y=>y.type===c))===null||i===void 0?void 0:i.attrs,x=HWe(d,c,g);x&&(m=x.from,p=x.to),n.removeMark(m,p,c)}else h.forEach(m=>{n.removeMark(m.$from.pos,m.$to.pos,c)});return n.removeStoredMark(c),!0},aLs=(s,t={})=>({tr:n,state:r,dispatch:a})=>{let i=null,l=null;const o=MAe(typeof s=="string"?s:s.name,r.schema);return o?(o==="node"&&(i=N0(s,r.schema)),o==="mark"&&(l=n6(s,r.schema)),a&&n.selection.ranges.forEach(c=>{const d=c.$from.pos,u=c.$to.pos;let h,m,p,g;n.selection.empty?r.doc.nodesBetween(d,u,(x,y)=>{i&&i===x.type&&(p=Math.max(y,d),g=Math.min(y+x.nodeSize,u),h=y,m=x)}):r.doc.nodesBetween(d,u,(x,y)=>{y=d&&y<=u&&(i&&i===x.type&&n.setNodeMarkup(y,void 0,{...x.attrs,...t}),l&&x.marks.length&&x.marks.forEach(v=>{if(l===v.type){const _=Math.max(y,d),j=Math.min(y+x.nodeSize,u);n.addMark(_,j,l.create({...v.attrs,...t}))}}))}),m&&(h!==void 0&&n.setNodeMarkup(h,void 0,{...m.attrs,...t}),l&&m.marks.length&&m.marks.forEach(x=>{l===x.type&&n.addMark(p,g,l.create({...x.attrs,...t}))}))}),!0):!1},iLs=(s,t={})=>({state:n,dispatch:r})=>{const a=N0(s,n.schema);return vPs(a,t)(n,r)},oLs=(s,t={})=>({state:n,dispatch:r})=>{const a=N0(s,n.schema);return bPs(a,t)(n,r)};var lLs=Object.freeze({__proto__:null,blur:qPs,clearContent:VPs,clearNodes:HPs,command:GPs,createParagraphNear:WPs,cut:KPs,deleteCurrentNode:YPs,deleteNode:ZPs,deleteRange:XPs,deleteSelection:QPs,enter:JPs,exitCode:eIs,extendMarkRange:tIs,first:sIs,focus:rIs,forEach:aIs,insertContent:iIs,insertContentAt:cIs,joinBackward:hIs,joinDown:uIs,joinForward:mIs,joinItemBackward:fIs,joinItemForward:pIs,joinTextblockBackward:gIs,joinTextblockForward:xIs,joinUp:dIs,keyboardShortcut:vIs,lift:bIs,liftEmptyBlock:_Is,liftListItem:wIs,newlineInCode:jIs,resetAttributes:NIs,scrollIntoView:kIs,selectAll:SIs,selectNodeBackward:CIs,selectNodeForward:AIs,selectParentNode:EIs,selectTextblockEnd:TIs,selectTextblockStart:MIs,setContent:PIs,setMark:VIs,setMeta:HIs,setNode:GIs,setNodeSelection:WIs,setTextSelection:KIs,sinkListItem:YIs,splitBlock:ZIs,splitListItem:XIs,toggleList:QIs,toggleMark:JIs,toggleNode:eLs,toggleWrap:tLs,undoInputRule:sLs,unsetAllMarks:nLs,unsetMark:rLs,updateAttributes:aLs,wrapIn:iLs,wrapInList:oLs});const cLs=xv.create({name:"commands",addCommands(){return{...lLs}}}),dLs=xv.create({name:"drop",addProseMirrorPlugins(){return[new Iy({key:new b1("tiptapDrop"),props:{handleDrop:(s,t,n,r)=>{this.editor.emit("drop",{editor:this.editor,event:t,slice:n,moved:r})}}})]}}),uLs=xv.create({name:"editable",addProseMirrorPlugins(){return[new Iy({key:new b1("editable"),props:{editable:()=>this.editor.options.editable}})]}}),hLs=new b1("focusEvents"),mLs=xv.create({name:"focusEvents",addProseMirrorPlugins(){const{editor:s}=this;return[new Iy({key:hLs,props:{handleDOMEvents:{focus:(t,n)=>{s.isFocused=!0;const r=s.state.tr.setMeta("focus",{event:n}).setMeta("addToHistory",!1);return t.dispatch(r),!1},blur:(t,n)=>{s.isFocused=!1;const r=s.state.tr.setMeta("blur",{event:n}).setMeta("addToHistory",!1);return t.dispatch(r),!1}}}})]}}),fLs=xv.create({name:"keymap",addKeyboardShortcuts(){const s=()=>this.editor.commands.first(({commands:l})=>[()=>l.undoInputRule(),()=>l.command(({tr:o})=>{const{selection:c,doc:d}=o,{empty:u,$anchor:h}=c,{pos:m,parent:p}=h,g=h.parent.isTextblock&&m>0?o.doc.resolve(m-1):h,x=g.parent.type.spec.isolating,y=h.pos-h.parentOffset,v=x&&g.parent.childCount===1?y===h.pos:$l.atStart(d).from===m;return!u||!p.type.isTextblock||p.textContent.length||!v||v&&h.parent.type.name==="paragraph"?!1:l.clearNodes()}),()=>l.deleteSelection(),()=>l.joinBackward(),()=>l.selectNodeBackward()]),t=()=>this.editor.commands.first(({commands:l})=>[()=>l.deleteSelection(),()=>l.deleteCurrentNode(),()=>l.joinForward(),()=>l.selectNodeForward()]),r={Enter:()=>this.editor.commands.first(({commands:l})=>[()=>l.newlineInCode(),()=>l.createParagraphNear(),()=>l.liftEmptyBlock(),()=>l.splitBlock()]),"Mod-Enter":()=>this.editor.commands.exitCode(),Backspace:s,"Mod-Backspace":s,"Shift-Backspace":s,Delete:t,"Mod-Delete":t,"Mod-a":()=>this.editor.commands.selectAll()},a={...r},i={...r,"Ctrl-h":s,"Alt-Backspace":s,"Ctrl-d":t,"Ctrl-Alt-Backspace":t,"Alt-Delete":t,"Alt-d":t,"Ctrl-a":()=>this.editor.commands.selectTextblockStart(),"Ctrl-e":()=>this.editor.commands.selectTextblockEnd()};return FSe()||BPt()?i:a},addProseMirrorPlugins(){return[new Iy({key:new b1("clearDocument"),appendTransaction:(s,t,n)=>{if(s.some(x=>x.getMeta("composition")))return;const r=s.some(x=>x.docChanged)&&!t.doc.eq(n.doc),a=s.some(x=>x.getMeta("preventClearDocument"));if(!r||a)return;const{empty:i,from:l,to:o}=t.selection,c=$l.atStart(t.doc).from,d=$l.atEnd(t.doc).to;if(i||!(l===c&&o===d)||!KWe(n.doc))return;const m=n.tr,p=SAe({state:n,transaction:m}),{commands:g}=new CAe({editor:this.editor,state:p});if(g.clearNodes(),!!m.steps.length)return m}})]}}),pLs=xv.create({name:"paste",addProseMirrorPlugins(){return[new Iy({key:new b1("tiptapPaste"),props:{handlePaste:(s,t,n)=>{this.editor.emit("paste",{editor:this.editor,event:t,slice:n})}}})]}}),gLs=xv.create({name:"tabindex",addProseMirrorPlugins(){return[new Iy({key:new b1("tabindex"),props:{attributes:()=>this.editor.isEditable?{tabindex:"0"}:{}}})]}});class WR{get name(){return this.node.type.name}constructor(t,n,r=!1,a=null){this.currentNode=null,this.actualDepth=null,this.isBlock=r,this.resolvedPos=t,this.editor=n,this.currentNode=a}get node(){return this.currentNode||this.resolvedPos.node()}get element(){return this.editor.view.domAtPos(this.pos).node}get depth(){var t;return(t=this.actualDepth)!==null&&t!==void 0?t:this.resolvedPos.depth}get pos(){return this.resolvedPos.pos}get content(){return this.node.content}set content(t){let n=this.from,r=this.to;if(this.isBlock){if(this.content.size===0){console.error(`You can’t set content on a block node. Tried to set content on ${this.name} at ${this.pos}`);return}n=this.from+1,r=this.to-1}this.editor.commands.insertContentAt({from:n,to:r},t)}get attributes(){return this.node.attrs}get textContent(){return this.node.textContent}get size(){return this.node.nodeSize}get from(){return this.isBlock?this.pos:this.resolvedPos.start(this.resolvedPos.depth)}get range(){return{from:this.from,to:this.to}}get to(){return this.isBlock?this.pos+this.size:this.resolvedPos.end(this.resolvedPos.depth)+(this.node.isText?0:1)}get parent(){if(this.depth===0)return null;const t=this.resolvedPos.start(this.resolvedPos.depth-1),n=this.resolvedPos.doc.resolve(t);return new WR(n,this.editor)}get before(){let t=this.resolvedPos.doc.resolve(this.from-(this.isBlock?1:2));return t.depth!==this.depth&&(t=this.resolvedPos.doc.resolve(this.from-3)),new WR(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 WR(t,this.editor)}get children(){const t=[];return this.node.content.forEach((n,r)=>{const a=n.isBlock&&!n.isTextblock,i=n.isAtom&&!n.isText,l=this.pos+r+(i?0:1);if(l<0||l>this.resolvedPos.doc.nodeSize-2)return;const o=this.resolvedPos.doc.resolve(l);if(!a&&o.depth<=this.depth)return;const c=new WR(o,this.editor,a,a?n:null);a&&(c.actualDepth=this.depth+1),t.push(new WR(o,this.editor,a,a?n:null))}),t}get firstChild(){return this.children[0]||null}get lastChild(){const t=this.children;return t[t.length-1]||null}closest(t,n={}){let r=null,a=this.parent;for(;a&&!r;){if(a.node.type.name===t)if(Object.keys(n).length>0){const i=a.node.attrs,l=Object.keys(n);for(let o=0;o{r&&a.length>0||(l.node.type.name===t&&i.every(c=>n[c]===l.node.attrs[c])&&a.push(l),!(r&&a.length>0)&&(a=a.concat(l.querySelectorAll(t,n,r))))}),a}setAttribute(t){const{tr:n}=this.editor.state;n.setNodeMarkup(this.from,void 0,{...this.node.attrs,...t}),this.editor.view.dispatch(n)}}const xLs=`.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 yLs(s,t,n){const r=document.querySelector("style[data-tiptap-style]");if(r!==null)return r;const a=document.createElement("style");return t&&a.setAttribute("nonce",t),a.setAttribute("data-tiptap-style",""),a.innerHTML=s,document.getElementsByTagName("head")[0].appendChild(a),a}class vLs extends CPs{constructor(t={}){super(),this.isFocused=!1,this.isInitialized=!1,this.extensionStorage={},this.options={element:document.createElement("div"),content:"",injectCSS:!0,injectNonce:void 0,extensions:[],autofocus:!1,editable:!0,editorProps:{},parseOptions:{},coreExtensionOptions:{},enableInputRules:!0,enablePasteRules:!0,enableCoreExtensions:!0,enableContentCheck:!1,emitContentError:!1,onBeforeCreate:()=>null,onCreate:()=>null,onUpdate:()=>null,onSelectionUpdate:()=>null,onTransaction:()=>null,onFocus:()=>null,onBlur:()=>null,onDestroy:()=>null,onContentError:({error:n})=>{throw n},onPaste:()=>null,onDrop:()=>null},this.isCapturingTransaction=!1,this.capturedTransaction=null,this.setOptions(t),this.createExtensionManager(),this.createCommandManager(),this.createSchema(),this.on("beforeCreate",this.options.onBeforeCreate),this.emit("beforeCreate",{editor:this}),this.on("contentError",this.options.onContentError),this.createView(),this.injectCSS(),this.on("create",this.options.onCreate),this.on("update",this.options.onUpdate),this.on("selectionUpdate",this.options.onSelectionUpdate),this.on("transaction",this.options.onTransaction),this.on("focus",this.options.onFocus),this.on("blur",this.options.onBlur),this.on("destroy",this.options.onDestroy),this.on("drop",({event:n,slice:r,moved:a})=>this.options.onDrop(n,r,a)),this.on("paste",({event:n,slice:r})=>this.options.onPaste(n,r)),window.setTimeout(()=>{this.isDestroyed||(this.commands.focus(this.options.autofocus),this.emit("create",{editor:this}),this.isInitialized=!0)},0)}get storage(){return this.extensionStorage}get commands(){return this.commandManager.commands}chain(){return this.commandManager.chain()}can(){return this.commandManager.can()}injectCSS(){this.options.injectCSS&&document&&(this.css=yLs(xLs,this.options.injectNonce))}setOptions(t={}){this.options={...this.options,...t},!(!this.view||!this.state||this.isDestroyed)&&(this.options.editorProps&&this.view.setProps(this.options.editorProps),this.view.updateState(this.state))}setEditable(t,n=!0){this.setOptions({editable:t}),n&&this.emit("update",{editor:this,transaction:this.state.tr})}get isEditable(){return this.options.editable&&this.view&&this.view.editable}get state(){return this.view.state}registerPlugin(t,n){const r=IPt(n)?n(t,[...this.state.plugins]):[...this.state.plugins,t],a=this.state.reconfigure({plugins:r});return this.view.updateState(a),a}unregisterPlugin(t){if(this.isDestroyed)return;const n=this.state.plugins;let r=n;if([].concat(t).forEach(i=>{const l=typeof i=="string"?`${i}$`:i.key;r=r.filter(o=>!o.key.startsWith(l))}),n.length===r.length)return;const a=this.state.reconfigure({plugins:r});return this.view.updateState(a),a}createExtensionManager(){var t,n;const a=[...this.options.enableCoreExtensions?[uLs,UPs.configure({blockSeparator:(n=(t=this.options.coreExtensionOptions)===null||t===void 0?void 0:t.clipboardTextSerializer)===null||n===void 0?void 0:n.blockSeparator}),cLs,mLs,fLs,gLs,dLs,pLs].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 xz(a,this)}createCommandManager(){this.commandManager=new CAe({editor:this})}createSchema(){this.schema=this.extensionManager.schema}createView(){var t;let n;try{n=_9e(this.options.content,this.schema,this.options.parseOptions,{errorOnInvalidContent:this.options.enableContentCheck})}catch(l){if(!(l instanceof Error)||!["[tiptap error]: Invalid JSON content","[tiptap error]: Invalid HTML content"].includes(l.message))throw l;this.emit("contentError",{editor:this,error:l,disableCollaboration:()=>{this.storage.collaboration&&(this.storage.collaboration.isDisabled=!0),this.options.extensions=this.options.extensions.filter(o=>o.name!=="collaboration"),this.createExtensionManager()}}),n=_9e(this.options.content,this.schema,this.options.parseOptions,{errorOnInvalidContent:!1})}const r=FPt(n,this.options.autofocus);this.view=new vPt(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:gz.create({doc:n,selection:r||void 0})});const a=this.state.reconfigure({plugins:this.extensionManager.plugins});this.view.updateState(a),this.createNodeViews(),this.prependClass();const i=this.view.dom;i.editor=this}createNodeViews(){this.view.isDestroyed||this.view.setProps({nodeViews:this.extensionManager.nodeViews})}prependClass(){this.view.dom.className=`tiptap ${this.view.dom.className}`}captureTransaction(t){this.isCapturingTransaction=!0,t(),this.isCapturingTransaction=!1;const n=this.capturedTransaction;return this.capturedTransaction=null,n}dispatchTransaction(t){if(this.view.isDestroyed)return;if(this.isCapturingTransaction){if(!this.capturedTransaction){this.capturedTransaction=t;return}t.steps.forEach(l=>{var o;return(o=this.capturedTransaction)===null||o===void 0?void 0:o.step(l)});return}const n=this.state.apply(t),r=!this.state.selection.eq(n.selection);this.emit("beforeTransaction",{editor:this,transaction:t,nextState:n}),this.view.updateState(n),this.emit("transaction",{editor:this,transaction:t}),r&&this.emit("selectionUpdate",{editor:this,transaction:t});const a=t.getMeta("focus"),i=t.getMeta("blur");a&&this.emit("focus",{editor:this,event:a.event,transaction:t}),i&&this.emit("blur",{editor:this,event:i.event,transaction:t}),!(!t.docChanged||t.getMeta("preventUpdate"))&&this.emit("update",{editor:this,transaction:t})}getAttributes(t){return qPt(this.state,t)}isActive(t,n){const r=typeof t=="string"?t:null,a=typeof t=="string"?n:t;return $Is(this.state,r,a)}getJSON(){return this.state.doc.toJSON()}getHTML(){return qWe(this.state.doc.content,this.schema)}getText(t){const{blockSeparator:n=` `,textSerializers:r={}}=t||{};return DIs(this.state.doc,{blockSeparator:n,textSerializers:{...RPt(this.schema),...r}})}get isEmpty(){return KWe(this.state.doc)}getCharacterCount(){return console.warn('[tiptap warn]: "editor.getCharacterCount()" is deprecated. Please use "editor.storage.characterCount.characters()" instead.'),this.state.doc.content.size-2}destroy(){if(this.emit("destroy"),this.view){const t=this.view.dom;t&&t.editor&&delete t.editor,this.view.destroy()}this.removeAllListeners()}get isDestroyed(){var t;return!(!((t=this.view)===null||t===void 0)&&t.docView)}$node(t,n){var r;return((r=this.$doc)===null||r===void 0?void 0:r.querySelector(t,n))||null}$nodes(t,n){var r;return((r=this.$doc)===null||r===void 0?void 0:r.querySelectorAll(t,n))||null}$pos(t){const n=this.state.doc.resolve(t);return new WR(n,this)}get $doc(){return this.$pos(0)}}function TU(s){return new EAe({find:s.find,handler:({state:t,range:n,match:r})=>{const a=ad(s.getAttributes,void 0,r);if(a===!1||a===null)return null;const{tr:i}=t,l=r[r.length-1],o=r[0];if(l){const c=o.search(/\S/),d=n.from+o.indexOf(l),u=d+l.length;if(WWe(n.from,n.to,t.doc).filter(p=>p.mark.type.excluded.find(x=>x===s.type&&x!==p.mark.type)).filter(p=>p.to>d).length)return null;un.from&&i.delete(n.from+c,d);const m=n.from+c+l.length;i.addMark(n.from+c,m,s.type.create(a||{})),i.removeStoredMark(s.type)}}})}function VPt(s){return new EAe({find:s.find,handler:({state:t,range:n,match:r})=>{const a=ad(s.getAttributes,void 0,r)||{},{tr:i}=t,l=n.from;let o=n.to;const c=s.type.create(a);if(r[1]){const d=r[0].lastIndexOf(r[1]);let u=l+d;u>o?u=o:o=u+r[1].length;const h=r[0][r[0].length-1];i.insertText(h,l+r[0].length-1),i.replaceWith(u,o,c)}else if(r[0]){const d=s.type.isInline?l:l-1;i.insert(d,s.type.create(a)).delete(i.mapping.map(l),i.mapping.map(o))}i.scrollIntoView()}})}function j9e(s){return new EAe({find:s.find,handler:({state:t,range:n,match:r})=>{const a=t.doc.resolve(n.from),i=ad(s.getAttributes,void 0,r)||{};if(!a.node(-1).canReplaceWith(a.index(-1),a.indexAfter(-1),s.type))return null;t.tr.delete(n.from,n.to).setBlockType(n.from,n.from,s.type,i)}})}function fX(s){return new EAe({find:s.find,handler:({state:t,range:n,match:r,chain:a})=>{const i=ad(s.getAttributes,void 0,r)||{},l=t.tr.delete(n.from,n.to),c=l.doc.resolve(n.from).blockRange(),d=c&&kWe(c,s.type,i);if(!d)return null;if(l.wrap(c,d),s.keepMarks&&s.editor){const{selection:h,storedMarks:m}=t,{splittableMarks:p}=s.editor.extensionManager,g=m||h.$to.parentOffset&&h.$from.marks();if(g){const x=g.filter(y=>p.includes(y.type.name));l.ensureMarks(x)}}if(s.keepAttributes){const h=s.type.name==="bulletList"||s.type.name==="orderedList"?"listItem":"taskList";a().updateAttributes(h,i).run()}const u=l.doc.resolve(n.from-1).nodeBefore;u&&u.type===s.type&&t6(l.doc,n.from-1)&&(!s.joinPredicate||s.joinPredicate(r,u))&&l.join(n.from-1)}})}let _1=class N9e{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=ad(So(this,"addOptions",{name:this.name}))),this.storage=ad(So(this,"addStorage",{name:this.name,options:this.options}))||{}}static create(t={}){return new N9e(t)}configure(t={}){const n=this.extend({...this.config,addOptions:()=>TAe(this.options,t)});return n.name=this.name,n.parent=this.parent,n}extend(t={}){const n=new N9e(t);return n.parent=this,this.child=n,n.name=t.name?t.name:n.parent.name,t.defaultOptions&&Object.keys(t.defaultOptions).length>0&&console.warn(`[tiptap warn]: BREAKING CHANGE: "defaultOptions" is deprecated. Please use "addOptions" instead. Found in extension: "${n.name}".`),n.options=ad(So(n,"addOptions",{name:n.name})),n.storage=ad(So(n,"addStorage",{name:n.name,options:n.options})),n}};function zO(s){return new DPs({find:s.find,handler:({state:t,range:n,match:r,pasteEvent:a})=>{const i=ad(s.getAttributes,void 0,r,a);if(i===!1||i===null)return null;const{tr:l}=t,o=r[r.length-1],c=r[0];let d=n.to;if(o){const u=c.search(/\S/),h=n.from+c.indexOf(o),m=h+o.length;if(WWe(n.from,n.to,t.doc).filter(g=>g.mark.type.excluded.find(y=>y===s.type&&y!==g.mark.type)).filter(g=>g.to>h).length)return null;mn.from&&l.delete(n.from+u,h),d=n.from+u+o.length,l.addMark(n.from+u,d,s.type.create(i||{})),l.removeStoredMark(s.type)}}})}function bLs(s,t){const{selection:n}=s,{$from:r}=n;if(n instanceof hl){const i=r.index();return r.parent.canReplaceWith(i,i+1,t)}let a=r.depth;for(;a>=0;){const i=r.index(a);if(r.node(a).contentMatchAt(i).matchType(t))return!0;a-=1}return!1}function _Ls(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}var HPt={exports:{}},bLe={};/** * @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 Qdt;function wLs(){if(Qdt)return bLe;Qdt=1;var s=zt;function t(h,m){return h===m&&(h!==0||1/h===1/m)||h!==h&&m!==m}var n=typeof Object.is=="function"?Object.is:t,r=s.useState,a=s.useEffect,i=s.useLayoutEffect,l=s.useDebugValue;function o(h,m){var p=m(),g=r({inst:{value:p,getSnapshot:m}}),x=g[0].inst,y=g[1];return i(function(){x.value=p,x.getSnapshot=m,c(x)&&y({inst:x})},[h,p,m]),a(function(){return c(x)&&y({inst:x}),h(function(){c(x)&&y({inst:x})})},[h]),l(p),p}function c(h){var m=h.getSnapshot;h=h.value;try{var p=m();return!n(h,p)}catch{return!0}}function d(h,m){return m()}var u=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?d:o;return bLe.useSyncExternalStore=s.useSyncExternalStore!==void 0?s.useSyncExternalStore:u,bLe}HPt.exports=wLs();var YWe=HPt.exports;const jLs=(...s)=>t=>{s.forEach(n=>{typeof n=="function"?n(t):n&&(n.current=t)})},NLs=({contentComponent:s})=>{const t=YWe.useSyncExternalStore(s.subscribe,s.getSnapshot,s.getServerSnapshot);return zt.createElement(zt.Fragment,null,Object.values(t))};function kLs(){const s=new Set;let t={};return{subscribe(n){return s.add(n),()=>{s.delete(n)}},getSnapshot(){return t},getServerSnapshot(){return t},setRenderer(n,r){t={...t,[n]:bkt.createPortal(r.reactElement,r.element,n)},s.forEach(a=>a())},removeRenderer(n){const r={...t};delete r[n],t=r,s.forEach(a=>a())}}}class SLs extends zt.Component{constructor(t){var n;super(t),this.editorContentRef=zt.createRef(),this.initialized=!1,this.state={hasContentComponentInitialized:!!(!((n=t.editor)===null||n===void 0)&&n.contentComponent)}}componentDidMount(){this.init()}componentDidUpdate(){this.init()}init(){const t=this.props.editor;if(t&&!t.isDestroyed&&t.options.element){if(t.contentComponent)return;const n=this.editorContentRef.current;n.append(...t.options.element.childNodes),t.setOptions({element:n}),t.contentComponent=kLs(),this.state.hasContentComponentInitialized||(this.unsubscribeToContentComponent=t.contentComponent.subscribe(()=>{this.setState(r=>r.hasContentComponentInitialized?r:{hasContentComponentInitialized:!0}),this.unsubscribeToContentComponent&&this.unsubscribeToContentComponent()})),t.createNodeViews(),this.initialized=!0}}componentWillUnmount(){const t=this.props.editor;if(!t||(this.initialized=!1,t.isDestroyed||t.view.setProps({nodeViews:{}}),this.unsubscribeToContentComponent&&this.unsubscribeToContentComponent(),t.contentComponent=null,!t.options.element.firstChild))return;const n=document.createElement("div");n.append(...t.options.element.childNodes),t.setOptions({element:n})}render(){const{editor:t,innerRef:n,...r}=this.props;return zt.createElement(zt.Fragment,null,zt.createElement("div",{ref:jLs(n,this.editorContentRef),...r}),(t==null?void 0:t.contentComponent)&&zt.createElement(NLs,{contentComponent:t.contentComponent}))}}const CLs=k.forwardRef((s,t)=>{const n=zt.useMemo(()=>Math.floor(Math.random()*4294967295).toString(),[s.editor]);return zt.createElement(SLs,{key:n,innerRef:t,...s})}),ZWe=zt.memo(CLs);var ALs=function s(t,n){if(t===n)return!0;if(t&&n&&typeof t=="object"&&typeof n=="object"){if(t.constructor!==n.constructor)return!1;var r,a,i;if(Array.isArray(t)){if(r=t.length,r!=n.length)return!1;for(a=r;a--!==0;)if(!s(t[a],n[a]))return!1;return!0}if(t instanceof Map&&n instanceof Map){if(t.size!==n.size)return!1;for(a of t.entries())if(!n.has(a[0]))return!1;for(a of t.entries())if(!s(a[1],n.get(a[0])))return!1;return!0}if(t instanceof Set&&n instanceof Set){if(t.size!==n.size)return!1;for(a of t.entries())if(!n.has(a[0]))return!1;return!0}if(ArrayBuffer.isView(t)&&ArrayBuffer.isView(n)){if(r=t.length,r!=n.length)return!1;for(a=r;a--!==0;)if(t[a]!==n[a])return!1;return!0}if(t.constructor===RegExp)return t.source===n.source&&t.flags===n.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===n.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===n.toString();if(i=Object.keys(t),r=i.length,r!==Object.keys(n).length)return!1;for(a=r;a--!==0;)if(!Object.prototype.hasOwnProperty.call(n,i[a]))return!1;for(a=r;a--!==0;){var l=i[a];if(!(l==="_owner"&&t.$$typeof)&&!s(t[l],n[l]))return!1}return!0}return t!==t&&n!==n},ELs=_Ls(ALs),GPt={exports:{}},_Le={};/** * @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 Jdt;function TLs(){if(Jdt)return _Le;Jdt=1;var s=zt,t=YWe;function n(d,u){return d===u&&(d!==0||1/d===1/u)||d!==d&&u!==u}var r=typeof Object.is=="function"?Object.is:n,a=t.useSyncExternalStore,i=s.useRef,l=s.useEffect,o=s.useMemo,c=s.useDebugValue;return _Le.useSyncExternalStoreWithSelector=function(d,u,h,m,p){var g=i(null);if(g.current===null){var x={hasValue:!1,value:null};g.current=x}else x=g.current;g=o(function(){function v(M){if(!_){if(_=!0,j=M,M=m(M),p!==void 0&&x.hasValue){var I=x.value;if(p(I,M))return C=I}return C=M}if(I=C,r(j,M))return I;var P=m(M);return p!==void 0&&p(I,P)?I:(j=M,C=P)}var _=!1,j,C,A=h===void 0?null:h;return[function(){return v(u())},A===null?void 0:function(){return v(A())}]},[u,h,m,p]);var y=a(d,g[0],g[1]);return l(function(){x.hasValue=!0,x.value=y},[y]),c(y),y},_Le}GPt.exports=TLs();var MLs=GPt.exports;const PLs=typeof window<"u"?k.useLayoutEffect:k.useEffect;class ILs{constructor(t){this.transactionNumber=0,this.lastTransactionNumber=0,this.subscribers=new Set,this.editor=t,this.lastSnapshot={editor:t,transactionNumber:0},this.getSnapshot=this.getSnapshot.bind(this),this.getServerSnapshot=this.getServerSnapshot.bind(this),this.watch=this.watch.bind(this),this.subscribe=this.subscribe.bind(this)}getSnapshot(){return this.transactionNumber===this.lastTransactionNumber?this.lastSnapshot:(this.lastTransactionNumber=this.transactionNumber,this.lastSnapshot={editor:this.editor,transactionNumber:this.transactionNumber},this.lastSnapshot)}getServerSnapshot(){return{editor:null,transactionNumber:0}}subscribe(t){return this.subscribers.add(t),()=>{this.subscribers.delete(t)}}watch(t){if(this.editor=t,this.editor){const n=()=>{this.transactionNumber+=1,this.subscribers.forEach(a=>a())},r=this.editor;return r.on("transaction",n),()=>{r.off("transaction",n)}}}}function LLs(s){var t;const[n]=k.useState(()=>new ILs(s.editor)),r=MLs.useSyncExternalStoreWithSelector(n.subscribe,n.getSnapshot,n.getServerSnapshot,s.selector,(t=s.equalityFn)!==null&&t!==void 0?t:ELs);return PLs(()=>n.watch(s.editor),[s.editor,n]),k.useDebugValue(r),r}const RLs=!1,k9e=typeof window>"u",DLs=k9e||!!(typeof window<"u"&&window.next);class XWe{constructor(t){this.editor=null,this.subscriptions=new Set,this.isComponentMounted=!1,this.previousDeps=null,this.instanceId="",this.options=t,this.subscriptions=new Set,this.setEditor(this.getInitialEditor()),this.scheduleDestroy(),this.getEditor=this.getEditor.bind(this),this.getServerSnapshot=this.getServerSnapshot.bind(this),this.subscribe=this.subscribe.bind(this),this.refreshEditorInstance=this.refreshEditorInstance.bind(this),this.scheduleDestroy=this.scheduleDestroy.bind(this),this.onRender=this.onRender.bind(this),this.createEditor=this.createEditor.bind(this)}setEditor(t){this.editor=t,this.instanceId=Math.random().toString(36).slice(2,9),this.subscriptions.forEach(n=>n())}getInitialEditor(){return this.options.current.immediatelyRender===void 0?k9e||DLs?null:this.createEditor():(this.options.current.immediatelyRender,this.options.current.immediatelyRender?this.createEditor():null)}createEditor(){const t={...this.options.current,onBeforeCreate:(...r)=>{var a,i;return(i=(a=this.options.current).onBeforeCreate)===null||i===void 0?void 0:i.call(a,...r)},onBlur:(...r)=>{var a,i;return(i=(a=this.options.current).onBlur)===null||i===void 0?void 0:i.call(a,...r)},onCreate:(...r)=>{var a,i;return(i=(a=this.options.current).onCreate)===null||i===void 0?void 0:i.call(a,...r)},onDestroy:(...r)=>{var a,i;return(i=(a=this.options.current).onDestroy)===null||i===void 0?void 0:i.call(a,...r)},onFocus:(...r)=>{var a,i;return(i=(a=this.options.current).onFocus)===null||i===void 0?void 0:i.call(a,...r)},onSelectionUpdate:(...r)=>{var a,i;return(i=(a=this.options.current).onSelectionUpdate)===null||i===void 0?void 0:i.call(a,...r)},onTransaction:(...r)=>{var a,i;return(i=(a=this.options.current).onTransaction)===null||i===void 0?void 0:i.call(a,...r)},onUpdate:(...r)=>{var a,i;return(i=(a=this.options.current).onUpdate)===null||i===void 0?void 0:i.call(a,...r)},onContentError:(...r)=>{var a,i;return(i=(a=this.options.current).onContentError)===null||i===void 0?void 0:i.call(a,...r)},onDrop:(...r)=>{var a,i;return(i=(a=this.options.current).onDrop)===null||i===void 0?void 0:i.call(a,...r)},onPaste:(...r)=>{var a,i;return(i=(a=this.options.current).onPaste)===null||i===void 0?void 0:i.call(a,...r)}};return new vLs(t)}getEditor(){return this.editor}getServerSnapshot(){return null}subscribe(t){return this.subscriptions.add(t),()=>{this.subscriptions.delete(t)}}static compareOptions(t,n){return Object.keys(t).every(r=>["onCreate","onBeforeCreate","onDestroy","onUpdate","onTransaction","onFocus","onBlur","onSelectionUpdate","onContentError","onDrop","onPaste"].includes(r)?!0:r==="extensions"&&t.extensions&&n.extensions?t.extensions.length!==n.extensions.length?!1:t.extensions.every((a,i)=>{var l;return a===((l=n.extensions)===null||l===void 0?void 0:l[i])}):t[r]===n[r])}onRender(t){return()=>(this.isComponentMounted=!0,clearTimeout(this.scheduledDestructionTimeout),this.editor&&!this.editor.isDestroyed&&t.length===0?XWe.compareOptions(this.options.current,this.editor.options)||this.editor.setOptions({...this.options.current,editable:this.editor.isEditable}):this.refreshEditorInstance(t),()=>{this.isComponentMounted=!1,this.scheduleDestroy()})}refreshEditorInstance(t){if(this.editor&&!this.editor.isDestroyed){if(this.previousDeps===null){this.previousDeps=t;return}if(this.previousDeps.length===t.length&&this.previousDeps.every((r,a)=>r===t[a]))return}this.editor&&!this.editor.isDestroyed&&this.editor.destroy(),this.setEditor(this.createEditor()),this.previousDeps=t}scheduleDestroy(){const t=this.instanceId,n=this.editor;this.scheduledDestructionTimeout=setTimeout(()=>{if(this.isComponentMounted&&this.instanceId===t){n&&n.setOptions(this.options.current);return}n&&!n.isDestroyed&&(n.destroy(),this.instanceId===t&&this.setEditor(null))},1)}}function QWe(s={},t=[]){const n=k.useRef(s);n.current=s;const[r]=k.useState(()=>new XWe(n)),a=YWe.useSyncExternalStore(r.subscribe,r.getEditor,r.getServerSnapshot);return k.useDebugValue(a),k.useEffect(r.onRender(t)),LLs({editor:a,selector:({transactionNumber:i})=>s.shouldRerenderOnTransaction===!1?null:s.immediatelyRender&&i===0?0:i+1}),a}const OLs=k.createContext({editor:null});OLs.Consumer;const FLs=k.createContext({onDragStart:void 0}),zLs=()=>k.useContext(FLs);zt.forwardRef((s,t)=>{const{onDragStart:n}=zLs(),r=s.as||"div";return zt.createElement(r,{...s,ref:t,"data-node-view-wrapper":"",onDragStart:n,style:{whiteSpace:"normal",...s.style}})});const BLs=/^\s*>\s$/,$Ls=_1.create({name:"blockquote",addOptions(){return{HTMLAttributes:{}}},content:"block+",group:"block",defining:!0,parseHTML(){return[{tag:"blockquote"}]},renderHTML({HTMLAttributes:s}){return["blockquote",cp(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[fX({find:BLs,type:this.type})]}}),ULs=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))$/,qLs=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))/g,VLs=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))$/,HLs=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))/g,GLs=yk.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",cp(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[TU({find:ULs,type:this.type}),TU({find:VLs,type:this.type})]},addPasteRules(){return[zO({find:qLs,type:this.type}),zO({find:HLs,type:this.type})]}}),WLs="listItem",eut="textStyle",tut=/^\s*([-+*])\s$/,KLs=_1.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",cp(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(WLs,this.editor.getAttributes(eut)).run():s.toggleList(this.name,this.options.itemTypeName,this.options.keepMarks)}},addKeyboardShortcuts(){return{"Mod-Shift-8":()=>this.editor.commands.toggleBulletList()}},addInputRules(){let s=fX({find:tut,type:this.type});return(this.options.keepMarks||this.options.keepAttributes)&&(s=fX({find:tut,type:this.type,keepMarks:this.options.keepMarks,keepAttributes:this.options.keepAttributes,getAttributes:()=>this.editor.getAttributes(eut),editor:this.editor})),[s]}}),YLs=/(^|[^`])`([^`]+)`(?!`)/,ZLs=/(^|[^`])`([^`]+)`(?!`)/g,XLs=yk.create({name:"code",addOptions(){return{HTMLAttributes:{}}},excludes:"_",code:!0,exitable:!0,parseHTML(){return[{tag:"code"}]},renderHTML({HTMLAttributes:s}){return["code",cp(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[TU({find:YLs,type:this.type})]},addPasteRules(){return[zO({find:ZLs,type:this.type})]}}),QLs=/^```([a-z]+)?[\s\n]$/,JLs=/^~~~([a-z]+)?[\s\n]$/,eRs=_1.create({name:"codeBlock",addOptions(){return{languageClassPrefix:"language-",exitOnTripleEnter:!0,exitOnArrowDown:!0,defaultLanguage:null,HTMLAttributes:{}}},content:"text*",marks:"",group:"block",code:!0,defining:!0,addAttributes(){return{language:{default:this.options.defaultLanguage,parseHTML:s=>{var t;const{languageClassPrefix:n}=this.options,i=[...((t=s.firstElementChild)===null||t===void 0?void 0:t.classList)||[]].filter(l=>l.startsWith(n)).map(l=>l.replace(n,""))[0];return i||null},rendered:!1}}},parseHTML(){return[{tag:"pre",preserveWhitespace:"full"}]},renderHTML({node:s,HTMLAttributes:t}){return["pre",cp(this.options.HTMLAttributes,t),["code",{class:s.attrs.language?this.options.languageClassPrefix+s.attrs.language:null},0]]},addCommands(){return{setCodeBlock:s=>({commands:t})=>t.setNode(this.name,s),toggleCodeBlock:s=>({commands:t})=>t.toggleNode(this.name,"paragraph",s)}},addKeyboardShortcuts(){return{"Mod-Alt-c":()=>this.editor.commands.toggleCodeBlock(),Backspace:()=>{const{empty:s,$anchor:t}=this.editor.state.selection,n=t.pos===1;return!s||t.parent.type.name!==this.name?!1:n||!t.parent.textContent.length?this.editor.commands.clearNodes():!1},Enter:({editor:s})=>{if(!this.options.exitOnTripleEnter)return!1;const{state:t}=s,{selection:n}=t,{$from:r,empty:a}=n;if(!a||r.parent.type!==this.type)return!1;const i=r.parentOffset===r.parent.nodeSize-2,l=r.parent.textContent.endsWith(` `);return!i||!l?!1:s.chain().command(({tr:o})=>(o.delete(r.pos-2,r.pos),!0)).exitCode().run()},ArrowDown:({editor:s})=>{if(!this.options.exitOnArrowDown)return!1;const{state:t}=s,{selection:n,doc:r}=t,{$from:a,empty:i}=n;if(!i||a.parent.type!==this.type||!(a.parentOffset===a.parent.nodeSize-2))return!1;const o=a.after();return o===void 0?!1:r.nodeAt(o)?s.commands.command(({tr:d})=>(d.setSelection($l.near(r.resolve(o))),!0)):s.commands.exitCode()}}},addInputRules(){return[j9e({find:QLs,type:this.type,getAttributes:s=>({language:s[1]})}),j9e({find:JLs,type:this.type,getAttributes:s=>({language:s[1]})})]},addProseMirrorPlugins(){return[new Iy({key:new b1("codeBlockVSCodeHandler"),props:{handlePaste:(s,t)=>{if(!t.clipboardData||this.editor.isActive(this.type.name))return!1;const n=t.clipboardData.getData("text/plain"),r=t.clipboardData.getData("vscode-editor-data"),a=r?JSON.parse(r):void 0,i=a==null?void 0:a.mode;if(!n||!i)return!1;const{tr:l,schema:o}=s.state,c=o.text(n.replace(/\r\n?/g,` `));return l.replaceSelectionWith(this.type.create({language:i},c)),l.selection.$from.parent.type!==this.type&&l.setSelection(ul.near(l.doc.resolve(Math.max(0,l.selection.from-2)))),l.setMeta("paste",!0),s.dispatch(l),!0}}})]}}),tRs=_1.create({name:"doc",topNode:!0,content:"block+"});function sRs(s={}){return new Iy({view(t){return new nRs(t,s)}})}class nRs{constructor(t,n){var r;this.editorView=t,this.cursorPos=null,this.element=null,this.timeout=-1,this.lastDragEvent=null,this.width=(r=n.width)!==null&&r!==void 0?r:1,this.color=n.color===!1?void 0:n.color||"black",this.class=n.class,this.handlers=["dragover","dragend","drop","dragleave"].map(a=>{let i=l=>{this[a](l)};return t.dom.addEventListener(a,i),{name:a,handler:i}})}destroy(){this.handlers.forEach(({name:t,handler:n})=>this.editorView.dom.removeEventListener(t,n))}update(t,n){if(this.cursorPos!=null&&n.doc!=t.state.doc)if(this.lastDragEvent){let r=this.computeTarget(this.lastDragEvent);r==this.cursorPos?this.updateOverlay():this.setCursor(r)}else this.updateOverlay()}setCursor(t){t!=this.cursorPos&&(this.cursorPos=t,t==null?(this.element.parentNode.removeChild(this.element),this.element=null):this.updateOverlay())}updateOverlay(){let t=this.editorView.state.doc.resolve(this.cursorPos),n=!t.parent.inlineContent,r,a=this.editorView.dom,i=a.getBoundingClientRect(),l=i.width/a.offsetWidth,o=i.height/a.offsetHeight;if(n){let h=t.nodeBefore,m=t.nodeAfter;if(h||m){let p=this.editorView.nodeDOM(this.cursorPos-(h?h.nodeSize:0));if(p){let g=p.getBoundingClientRect(),x=h?g.bottom:g.top;h&&m&&(x=(x+this.editorView.nodeDOM(this.cursorPos).getBoundingClientRect().top)/2);let y=this.width/2*o;r={left:g.left,right:g.right,top:x-y,bottom:x+y}}}}if(!r){let h=this.editorView.coordsAtPos(this.cursorPos),m=this.width/2*l;r={left:h.left-m,right:h.left+m,top:h.top,bottom:h.bottom}}let c=this.editorView.dom.offsetParent;this.element||(this.element=c.appendChild(document.createElement("div")),this.class&&(this.element.className=this.class),this.element.style.cssText="position: absolute; z-index: 50; pointer-events: none;",this.color&&(this.element.style.backgroundColor=this.color)),this.element.classList.toggle("prosemirror-dropcursor-block",n),this.element.classList.toggle("prosemirror-dropcursor-inline",!n);let d,u;if(!c||c==document.body&&getComputedStyle(c).position=="static")d=-pageXOffset,u=-pageYOffset;else{let h=c.getBoundingClientRect(),m=h.width/c.offsetWidth,p=h.height/c.offsetHeight;d=h.left-c.scrollLeft*m,u=h.top-c.scrollTop*p}this.element.style.left=(r.left-d)/l+"px",this.element.style.top=(r.top-u)/o+"px",this.element.style.width=(r.right-r.left)/l+"px",this.element.style.height=(r.bottom-r.top)/o+"px"}scheduleRemoval(t){clearTimeout(this.timeout),this.timeout=setTimeout(()=>this.setCursor(null),t)}computeTarget(t){let n=this.editorView.posAtCoords({left:t.clientX,top:t.clientY}),r=n&&n.inside>=0&&this.editorView.state.doc.nodeAt(n.inside),a=r&&r.type.spec.disableDropCursor,i=typeof a=="function"?a(this.editorView,n,t):a;if(!n||i)return null;let l=n.pos;if(this.editorView.dragging&&this.editorView.dragging.slice){let o=E6t(this.editorView.state.doc,l,this.editorView.dragging.slice);o!=null&&(l=o)}return l}dragover(t){if(!this.editorView.editable)return;this.lastDragEvent=t;let n=this.computeTarget(t);n!=null&&(this.setCursor(n),this.scheduleRemoval(5e3))}dragend(){this.scheduleRemoval(20)}drop(){this.scheduleRemoval(20)}dragleave(t){this.editorView.dom.contains(t.relatedTarget)||this.setCursor(null)}}const rRs=xv.create({name:"dropCursor",addOptions(){return{color:"currentColor",width:1,class:void 0}},addProseMirrorPlugins(){return[sRs(this.options)]}});class yg extends $l{constructor(t){super(t,t)}map(t,n){let r=t.resolve(n.map(this.head));return yg.valid(r)?new yg(r):$l.near(r)}content(){return Ii.empty}eq(t){return t instanceof yg&&t.head==this.head}toJSON(){return{type:"gapcursor",pos:this.head}}static fromJSON(t,n){if(typeof n.pos!="number")throw new RangeError("Invalid input for GapCursor.fromJSON");return new yg(t.resolve(n.pos))}getBookmark(){return new JWe(this.anchor)}static valid(t){let n=t.parent;if(n.inlineContent||!aRs(t)||!iRs(t))return!1;let r=n.type.spec.allowGapCursor;if(r!=null)return r;let a=n.contentMatchAt(t.index()).defaultType;return a&&a.isTextblock}static findGapCursorFrom(t,n,r=!1){e:for(;;){if(!r&&yg.valid(t))return t;let a=t.pos,i=null;for(let l=t.depth;;l--){let o=t.node(l);if(n>0?t.indexAfter(l)0){i=o.child(n>0?t.indexAfter(l):t.index(l)-1);break}else if(l==0)return null;a+=n;let c=t.doc.resolve(a);if(yg.valid(c))return c}for(;;){let l=n>0?i.firstChild:i.lastChild;if(!l){if(i.isAtom&&!i.isText&&!hl.isSelectable(i)){t=t.doc.resolve(a+i.nodeSize*n),r=!1;continue e}break}i=l,a+=n;let o=t.doc.resolve(a);if(yg.valid(o))return o}return null}}}yg.prototype.visible=!1;yg.findFrom=yg.findGapCursorFrom;$l.jsonID("gapcursor",yg);class JWe{constructor(t){this.pos=t}map(t){return new JWe(t.map(this.pos))}resolve(t){let n=t.resolve(this.pos);return yg.valid(n)?new yg(n):$l.near(n)}}function WPt(s){return s.isAtom||s.spec.isolating||s.spec.createGapCursor}function aRs(s){for(let t=s.depth;t>=0;t--){let n=s.index(t),r=s.node(t);if(n==0){if(r.type.spec.isolating)return!0;continue}for(let a=r.child(n-1);;a=a.lastChild){if(a.childCount==0&&!a.inlineContent||WPt(a.type))return!0;if(a.inlineContent)return!1}}return!0}function iRs(s){for(let t=s.depth;t>=0;t--){let n=s.indexAfter(t),r=s.node(t);if(n==r.childCount){if(r.type.spec.isolating)return!0;continue}for(let a=r.child(n);;a=a.firstChild){if(a.childCount==0&&!a.inlineContent||WPt(a.type))return!0;if(a.inlineContent)return!1}}return!0}function oRs(){return new Iy({props:{decorations:uRs,createSelectionBetween(s,t,n){return t.pos==n.pos&&yg.valid(n)?new yg(n):null},handleClick:cRs,handleKeyDown:lRs,handleDOMEvents:{beforeinput:dRs}}})}const lRs=OWe({ArrowLeft:_re("horiz",-1),ArrowRight:_re("horiz",1),ArrowUp:_re("vert",-1),ArrowDown:_re("vert",1)});function _re(s,t){const n=s=="vert"?t>0?"down":"up":t>0?"right":"left";return function(r,a,i){let l=r.selection,o=t>0?l.$to:l.$from,c=l.empty;if(l instanceof ul){if(!i.endOfTextblock(n)||o.depth==0)return!1;c=!1,o=r.doc.resolve(t>0?o.after():o.before())}let d=yg.findGapCursorFrom(o,t,c);return d?(a&&a(r.tr.setSelection(new yg(d))),!0):!1}}function cRs(s,t,n){if(!s||!s.editable)return!1;let r=s.state.doc.resolve(t);if(!yg.valid(r))return!1;let a=s.posAtCoords({left:n.clientX,top:n.clientY});return a&&a.inside>-1&&hl.isSelectable(s.state.doc.nodeAt(a.inside))?!1:(s.dispatch(s.state.tr.setSelection(new yg(r))),!0)}function dRs(s,t){if(t.inputType!="insertCompositionText"||!(s.state.selection instanceof yg))return!1;let{$from:n}=s.state.selection,r=n.parent.contentMatchAt(n.index()).findWrapping(s.state.schema.nodes.text);if(!r)return!1;let a=Ua.empty;for(let l=r.length-1;l>=0;l--)a=Ua.from(r[l].createAndFill(null,a));let i=s.state.tr.replace(n.pos,n.pos,new Ii(a,0,0));return i.setSelection(ul.near(i.doc.resolve(n.pos+1))),s.dispatch(i),!1}function uRs(s){if(!(s.selection instanceof yg))return null;let t=document.createElement("div");return t.className="ProseMirror-gapcursor",xg.create(s.doc,[cb.widget(s.selection.head,t,{key:"gapcursor"})])}const hRs=xv.create({name:"gapCursor",addProseMirrorPlugins(){return[oRs()]},extendNodeSchema(s){var t;const n={name:s.name,options:s.options,storage:s.storage};return{allowGapCursor:(t=ad(So(s,"allowGapCursor",n)))!==null&&t!==void 0?t:null}}}),mRs=_1.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",cp(this.options.HTMLAttributes,s)]},renderText(){return` `},addCommands(){return{setHardBreak:()=>({commands:s,chain:t,state:n,editor:r})=>s.first([()=>s.exitCode(),()=>s.command(()=>{const{selection:a,storedMarks:i}=n;if(a.$from.parent.type.spec.isolating)return!1;const{keepMarks:l}=this.options,{splittableMarks:o}=r.extensionManager,c=i||a.$to.parentOffset&&a.$from.marks();return t().insertContent({type:this.name}).command(({tr:d,dispatch:u})=>{if(u&&c&&l){const h=c.filter(m=>o.includes(m.type.name));d.ensureMarks(h)}return!0}).run()})])}},addKeyboardShortcuts(){return{"Mod-Enter":()=>this.editor.commands.setHardBreak(),"Shift-Enter":()=>this.editor.commands.setHardBreak()}}}),fRs=_1.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]}`,cp(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=>j9e({find:new RegExp(`^(#{${Math.min(...this.options.levels)},${s}})\\s$`),type:this.type,getAttributes:{level:s}}))}});var zSe=200,w0=function(){};w0.prototype.append=function(t){return t.length?(t=w0.from(t),!this.length&&t||t.length=n?w0.empty:this.sliceInner(Math.max(0,t),Math.min(this.length,n))};w0.prototype.get=function(t){if(!(t<0||t>=this.length))return this.getInner(t)};w0.prototype.forEach=function(t,n,r){n===void 0&&(n=0),r===void 0&&(r=this.length),n<=r?this.forEachInner(t,n,r,0):this.forEachInvertedInner(t,n,r,0)};w0.prototype.map=function(t,n,r){n===void 0&&(n=0),r===void 0&&(r=this.length);var a=[];return this.forEach(function(i,l){return a.push(t(i,l))},n,r),a};w0.from=function(t){return t instanceof w0?t:t&&t.length?new KPt(t):w0.empty};var KPt=function(s){function t(r){s.call(this),this.values=r}s&&(t.__proto__=s),t.prototype=Object.create(s&&s.prototype),t.prototype.constructor=t;var n={length:{configurable:!0},depth:{configurable:!0}};return t.prototype.flatten=function(){return this.values},t.prototype.sliceInner=function(a,i){return a==0&&i==this.length?this:new t(this.values.slice(a,i))},t.prototype.getInner=function(a){return this.values[a]},t.prototype.forEachInner=function(a,i,l,o){for(var c=i;c=l;c--)if(a(this.values[c],o+c)===!1)return!1},t.prototype.leafAppend=function(a){if(this.length+a.length<=zSe)return new t(this.values.concat(a.flatten()))},t.prototype.leafPrepend=function(a){if(this.length+a.length<=zSe)return new t(a.flatten().concat(this.values))},n.length.get=function(){return this.values.length},n.depth.get=function(){return 0},Object.defineProperties(t.prototype,n),t}(w0);w0.empty=new KPt([]);var pRs=function(s){function t(n,r){s.call(this),this.left=n,this.right=r,this.length=n.length+r.length,this.depth=Math.max(n.depth,r.depth)+1}return s&&(t.__proto__=s),t.prototype=Object.create(s&&s.prototype),t.prototype.constructor=t,t.prototype.flatten=function(){return this.left.flatten().concat(this.right.flatten())},t.prototype.getInner=function(r){return ro&&this.right.forEachInner(r,Math.max(a-o,0),Math.min(this.length,i)-o,l+o)===!1)return!1},t.prototype.forEachInvertedInner=function(r,a,i,l){var o=this.left.length;if(a>o&&this.right.forEachInvertedInner(r,a-o,Math.max(i,o)-o,l+o)===!1||i=i?this.right.slice(r-i,a-i):this.left.slice(r,i).append(this.right.slice(0,a-i))},t.prototype.leafAppend=function(r){var a=this.right.leafAppend(r);if(a)return new t(this.left,a)},t.prototype.leafPrepend=function(r){var a=this.left.leafPrepend(r);if(a)return new t(a,this.right)},t.prototype.appendInner=function(r){return this.left.depth>=Math.max(this.right.depth,r.depth)+1?new t(this.left,new t(this.right,r)):new t(this,r)},t}(w0);const gRs=500;class ZN{constructor(t,n){this.items=t,this.eventCount=n}popEvent(t,n){if(this.eventCount==0)return null;let r=this.items.length;for(;;r--)if(this.items.get(r-1).selection){--r;break}let a,i;n&&(a=this.remapping(r,this.items.length),i=a.maps.length);let l=t.tr,o,c,d=[],u=[];return this.items.forEach((h,m)=>{if(!h.step){a||(a=this.remapping(r,m+1),i=a.maps.length),i--,u.push(h);return}if(a){u.push(new BA(h.map));let p=h.step.map(a.slice(i)),g;p&&l.maybeStep(p).doc&&(g=l.mapping.maps[l.mapping.maps.length-1],d.push(new BA(g,void 0,void 0,d.length+u.length))),i--,g&&a.appendMap(g,i)}else l.maybeStep(h.step);if(h.selection)return o=a?h.selection.map(a.slice(i)):h.selection,c=new ZN(this.items.slice(0,r).append(u.reverse().concat(d)),this.eventCount-1),!1},this.items.length,0),{remaining:c,transform:l,selection:o}}addTransform(t,n,r,a){let i=[],l=this.eventCount,o=this.items,c=!a&&o.length?o.get(o.length-1):null;for(let u=0;uyRs&&(o=xRs(o,d),l-=d),new ZN(o.append(i),l)}remapping(t,n){let r=new oX;return this.items.forEach((a,i)=>{let l=a.mirrorOffset!=null&&i-a.mirrorOffset>=t?r.maps.length-a.mirrorOffset:void 0;r.appendMap(a.map,l)},t,n),r}addMaps(t){return this.eventCount==0?this:new ZN(this.items.append(t.map(n=>new BA(n))),this.eventCount)}rebased(t,n){if(!this.eventCount)return this;let r=[],a=Math.max(0,this.items.length-n),i=t.mapping,l=t.steps.length,o=this.eventCount;this.items.forEach(m=>{m.selection&&o--},a);let c=n;this.items.forEach(m=>{let p=i.getMirror(--c);if(p==null)return;l=Math.min(l,p);let g=i.maps[p];if(m.step){let x=t.steps[p].invert(t.docs[p]),y=m.selection&&m.selection.map(i.slice(c+1,p));y&&o++,r.push(new BA(g,x,y))}else r.push(new BA(g))},a);let d=[];for(let m=n;mgRs&&(h=h.compress(this.items.length-r.length)),h}emptyItemCount(){let t=0;return this.items.forEach(n=>{n.step||t++}),t}compress(t=this.items.length){let n=this.remapping(0,t),r=n.maps.length,a=[],i=0;return this.items.forEach((l,o)=>{if(o>=t)a.push(l),l.selection&&i++;else if(l.step){let c=l.step.map(n.slice(r)),d=c&&c.getMap();if(r--,d&&n.appendMap(d,r),c){let u=l.selection&&l.selection.map(n.slice(r));u&&i++;let h=new BA(d.invert(),c,u),m,p=a.length-1;(m=a.length&&a[p].merge(h))?a[p]=m:a.push(h)}}else l.map&&r--},this.items.length,0),new ZN(w0.from(a.reverse()),i)}}ZN.empty=new ZN(w0.empty,0);function xRs(s,t){let n;return s.forEach((r,a)=>{if(r.selection&&t--==0)return n=a,!1}),s.slice(n)}let BA=class YPt{constructor(t,n,r,a){this.map=t,this.step=n,this.selection=r,this.mirrorOffset=a}merge(t){if(this.step&&t.step&&!t.selection){let n=t.step.merge(this.step);if(n)return new YPt(n.getMap().invert(),n,this.selection)}}};class gE{constructor(t,n,r,a,i){this.done=t,this.undone=n,this.prevRanges=r,this.prevTime=a,this.prevComposition=i}}const yRs=20;function vRs(s,t,n,r){let a=n.getMeta(aO),i;if(a)return a.historyState;n.getMeta(wRs)&&(s=new gE(s.done,s.undone,null,0,-1));let l=n.getMeta("appendedTransaction");if(n.steps.length==0)return s;if(l&&l.getMeta(aO))return l.getMeta(aO).redo?new gE(s.done.addTransform(n,void 0,r,gNe(t)),s.undone,sut(n.mapping.maps),s.prevTime,s.prevComposition):new gE(s.done,s.undone.addTransform(n,void 0,r,gNe(t)),null,s.prevTime,s.prevComposition);if(n.getMeta("addToHistory")!==!1&&!(l&&l.getMeta("addToHistory")===!1)){let o=n.getMeta("composition"),c=s.prevTime==0||!l&&s.prevComposition!=o&&(s.prevTime<(n.time||0)-r.newGroupDelay||!bRs(n,s.prevRanges)),d=l?wLe(s.prevRanges,n.mapping):sut(n.mapping.maps);return new gE(s.done.addTransform(n,c?t.selection.getBookmark():void 0,r,gNe(t)),ZN.empty,d,n.time,o??s.prevComposition)}else return(i=n.getMeta("rebased"))?new gE(s.done.rebased(n,i),s.undone.rebased(n,i),wLe(s.prevRanges,n.mapping),s.prevTime,s.prevComposition):new gE(s.done.addMaps(n.mapping.maps),s.undone.addMaps(n.mapping.maps),wLe(s.prevRanges,n.mapping),s.prevTime,s.prevComposition)}function bRs(s,t){if(!t)return!1;if(!s.docChanged)return!0;let n=!1;return s.mapping.maps[0].forEach((r,a)=>{for(let i=0;i=t[i]&&(n=!0)}),n}function sut(s){let t=[];for(let n=s.length-1;n>=0&&t.length==0;n--)s[n].forEach((r,a,i,l)=>t.push(i,l));return t}function wLe(s,t){if(!s)return null;let n=[];for(let r=0;r{let a=aO.getState(n);if(!a||(s?a.undone:a.done).eventCount==0)return!1;if(r){let i=_Rs(a,n,s);i&&r(t?i.scrollIntoView():i)}return!0}}const XPt=ZPt(!1,!0),QPt=ZPt(!0,!0),NRs=xv.create({name:"history",addOptions(){return{depth:100,newGroupDelay:500}},addCommands(){return{undo:()=>({state:s,dispatch:t})=>XPt(s,t),redo:()=>({state:s,dispatch:t})=>QPt(s,t)}},addProseMirrorPlugins(){return[jRs(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()}}}),kRs=_1.create({name:"horizontalRule",addOptions(){return{HTMLAttributes:{}}},group:"block",parseHTML(){return[{tag:"hr"}]},renderHTML({HTMLAttributes:s}){return["hr",cp(this.options.HTMLAttributes,s)]},addCommands(){return{setHorizontalRule:()=>({chain:s,state:t})=>{if(!bLs(t,t.schema.nodes[this.name]))return!1;const{selection:n}=t,{$from:r,$to:a}=n,i=s();return r.parentOffset===0?i.insertContentAt({from:Math.max(r.pos-1,0),to:a.pos},{type:this.name}):UIs(n)?i.insertContentAt(a.pos,{type:this.name}):i.insertContent({type:this.name}),i.command(({tr:l,dispatch:o})=>{var c;if(o){const{$to:d}=l.selection,u=d.end();if(d.nodeAfter)d.nodeAfter.isTextblock?l.setSelection(ul.create(l.doc,d.pos+1)):d.nodeAfter.isBlock?l.setSelection(hl.create(l.doc,d.pos)):l.setSelection(ul.create(l.doc,d.pos));else{const h=(c=d.parent.type.contentMatch.defaultType)===null||c===void 0?void 0:c.create();h&&(l.insert(u,h),l.setSelection(ul.create(l.doc,u+1)))}l.scrollIntoView()}return!0}).run()}}},addInputRules(){return[VPt({find:/^(?:---|—-|___\s|\*\*\*\s)$/,type:this.type})]}}),SRs=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))$/,CRs=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))/g,ARs=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))$/,ERs=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))/g,TRs=yk.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",cp(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[TU({find:SRs,type:this.type}),TU({find:ARs,type:this.type})]},addPasteRules(){return[zO({find:CRs,type:this.type}),zO({find:ERs,type:this.type})]}}),MRs=_1.create({name:"listItem",addOptions(){return{HTMLAttributes:{},bulletListTypeName:"bulletList",orderedListTypeName:"orderedList"}},content:"paragraph block*",defining:!0,parseHTML(){return[{tag:"li"}]},renderHTML({HTMLAttributes:s}){return["li",cp(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)}}}),PRs="listItem",rut="textStyle",aut=/^(\d+)\.\s$/,IRs=_1.create({name:"orderedList",addOptions(){return{itemTypeName:"listItem",HTMLAttributes:{},keepMarks:!1,keepAttributes:!1}},group:"block list",content(){return`${this.options.itemTypeName}+`},addAttributes(){return{start:{default:1,parseHTML:s=>s.hasAttribute("start")?parseInt(s.getAttribute("start")||"",10):1},type:{default:null,parseHTML:s=>s.getAttribute("type")}}},parseHTML(){return[{tag:"ol"}]},renderHTML({HTMLAttributes:s}){const{start:t,...n}=s;return t===1?["ol",cp(this.options.HTMLAttributes,n),0]:["ol",cp(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(PRs,this.editor.getAttributes(rut)).run():s.toggleList(this.name,this.options.itemTypeName,this.options.keepMarks)}},addKeyboardShortcuts(){return{"Mod-Shift-7":()=>this.editor.commands.toggleOrderedList()}},addInputRules(){let s=fX({find:aut,type:this.type,getAttributes:t=>({start:+t[1]}),joinPredicate:(t,n)=>n.childCount+n.attrs.start===+t[1]});return(this.options.keepMarks||this.options.keepAttributes)&&(s=fX({find:aut,type:this.type,keepMarks:this.options.keepMarks,keepAttributes:this.options.keepAttributes,getAttributes:t=>({start:+t[1],...this.editor.getAttributes(rut)}),joinPredicate:(t,n)=>n.childCount+n.attrs.start===+t[1],editor:this.editor})),[s]}}),LRs=_1.create({name:"paragraph",priority:1e3,addOptions(){return{HTMLAttributes:{}}},group:"block",content:"inline*",parseHTML(){return[{tag:"p"}]},renderHTML({HTMLAttributes:s}){return["p",cp(this.options.HTMLAttributes,s),0]},addCommands(){return{setParagraph:()=>({commands:s})=>s.setNode(this.name)}},addKeyboardShortcuts(){return{"Mod-Alt-0":()=>this.editor.commands.setParagraph()}}}),RRs=/(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))$/,DRs=/(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))/g,ORs=yk.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",cp(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[TU({find:RRs,type:this.type})]},addPasteRules(){return[zO({find:DRs,type:this.type})]}}),FRs=_1.create({name:"text",group:"inline"}),eKe=xv.create({name:"starterKit",addExtensions(){const s=[];return this.options.bold!==!1&&s.push(GLs.configure(this.options.bold)),this.options.blockquote!==!1&&s.push($Ls.configure(this.options.blockquote)),this.options.bulletList!==!1&&s.push(KLs.configure(this.options.bulletList)),this.options.code!==!1&&s.push(XLs.configure(this.options.code)),this.options.codeBlock!==!1&&s.push(eRs.configure(this.options.codeBlock)),this.options.document!==!1&&s.push(tRs.configure(this.options.document)),this.options.dropcursor!==!1&&s.push(rRs.configure(this.options.dropcursor)),this.options.gapcursor!==!1&&s.push(hRs.configure(this.options.gapcursor)),this.options.hardBreak!==!1&&s.push(mRs.configure(this.options.hardBreak)),this.options.heading!==!1&&s.push(fRs.configure(this.options.heading)),this.options.history!==!1&&s.push(NRs.configure(this.options.history)),this.options.horizontalRule!==!1&&s.push(kRs.configure(this.options.horizontalRule)),this.options.italic!==!1&&s.push(TRs.configure(this.options.italic)),this.options.listItem!==!1&&s.push(MRs.configure(this.options.listItem)),this.options.orderedList!==!1&&s.push(IRs.configure(this.options.orderedList)),this.options.paragraph!==!1&&s.push(LRs.configure(this.options.paragraph)),this.options.strike!==!1&&s.push(ORs.configure(this.options.strike)),this.options.text!==!1&&s.push(FRs.configure(this.options.text)),s}}),zRs="aaa1rp3bb0ott3vie4c1le2ogado5udhabi7c0ademy5centure6ountant0s9o1tor4d0s1ult4e0g1ro2tna4f0l1rica5g0akhan5ency5i0g1rbus3force5tel5kdn3l0ibaba4pay4lfinanz6state5y2sace3tom5m0azon4ericanexpress7family11x2fam3ica3sterdam8nalytics7droid5quan4z2o0l2partments8p0le4q0uarelle8r0ab1mco4chi3my2pa2t0e3s0da2ia2sociates9t0hleta5torney7u0ction5di0ble3o3spost5thor3o0s4w0s2x0a2z0ure5ba0by2idu3namex4d1k2r0celona5laycard4s5efoot5gains6seball5ketball8uhaus5yern5b0c1t1va3cg1n2d1e0ats2uty4er2rlin4st0buy5t2f1g1h0arti5i0ble3d1ke2ng0o3o1z2j1lack0friday9ockbuster8g1omberg7ue3m0s1w2n0pparibas9o0ats3ehringer8fa2m1nd2o0k0ing5sch2tik2on4t1utique6x2r0adesco6idgestone9oadway5ker3ther5ussels7s1t1uild0ers6siness6y1zz3v1w1y1z0h3ca0b1fe2l0l1vinklein9m0era3p2non3petown5ital0one8r0avan4ds2e0er0s4s2sa1e1h1ino4t0ering5holic7ba1n1re3c1d1enter4o1rn3f0a1d2g1h0anel2nel4rity4se2t2eap3intai5ristmas6ome4urch5i0priani6rcle4sco3tadel4i0c2y3k1l0aims4eaning6ick2nic1que6othing5ud3ub0med6m1n1o0ach3des3ffee4llege4ogne5m0mbank4unity6pany2re3uter5sec4ndos3struction8ulting7tact3ractors9oking4l1p2rsica5untry4pon0s4rses6pa2r0edit0card4union9icket5own3s1uise0s6u0isinella9v1w1x1y0mru3ou3z2dad1nce3ta1e1ing3sun4y2clk3ds2e0al0er2s3gree4livery5l1oitte5ta3mocrat6ntal2ist5si0gn4v2hl2iamonds6et2gital5rect0ory7scount3ver5h2y2j1k1m1np2o0cs1tor4g1mains5t1wnload7rive4tv2ubai3pont4rban5vag2r2z2earth3t2c0o2deka3u0cation8e1g1mail3erck5nergy4gineer0ing9terprises10pson4quipment8r0icsson6ni3s0q1tate5t1u0rovision8s2vents5xchange6pert3osed4ress5traspace10fage2il1rwinds6th3mily4n0s2rm0ers5shion4t3edex3edback6rrari3ero6i0delity5o2lm2nal1nce1ial7re0stone6mdale6sh0ing5t0ness6j1k1lickr3ghts4r2orist4wers5y2m1o0o0d1tball6rd1ex2sale4um3undation8x2r0ee1senius7l1ogans4ntier7tr2ujitsu5n0d2rniture7tbol5yi3ga0l0lery3o1up4me0s3p1rden4y2b0iz3d0n2e0a1nt0ing5orge5f1g0ee3h1i0ft0s3ves2ing5l0ass3e1obal2o4m0ail3bh2o1x2n1odaddy5ld0point6f2odyear5g0le4p1t1v2p1q1r0ainger5phics5tis4een3ipe3ocery4up4s1t1u0cci3ge2ide2tars5ru3w1y2hair2mburg5ngout5us3bo2dfc0bank7ealth0care8lp1sinki6re1mes5iphop4samitsu7tachi5v2k0t2m1n1ockey4ldings5iday5medepot5goods5s0ense7nda3rse3spital5t0ing5t0els3mail5use3w2r1sbc3t1u0ghes5yatt3undai7ibm2cbc2e1u2d1e0ee3fm2kano4l1m0amat4db2mo0bilien9n0c1dustries8finiti5o2g1k1stitute6urance4e4t0ernational10uit4vestments10o1piranga7q1r0ish4s0maili5t0anbul7t0au2v3jaguar4va3cb2e0ep2tzt3welry6io2ll2m0p2nj2o0bs1urg4t1y2p0morgan6rs3uegos4niper7kaufen5ddi3e0rryhotels6properties14fh2g1h1i0a1ds2m1ndle4tchen5wi3m1n1oeln3matsu5sher5p0mg2n2r0d1ed3uokgroup8w1y0oto4z2la0caixa5mborghini8er3nd0rover6xess5salle5t0ino3robe5w0yer5b1c1ds2ease3clerc5frak4gal2o2xus4gbt3i0dl2fe0insurance9style7ghting6ke2lly3mited4o2ncoln4k2ve1ing5k1lc1p2oan0s3cker3us3l1ndon4tte1o3ve3pl0financial11r1s1t0d0a3u0ndbeck6xe1ury5v1y2ma0drid4if1son4keup4n0agement7go3p1rket0ing3s4riott5shalls7ttel5ba2c0kinsey7d1e0d0ia3et2lbourne7me1orial6n0u2rck0msd7g1h1iami3crosoft7l1ni1t2t0subishi9k1l0b1s2m0a2n1o0bi0le4da2e1i1m1nash3ey2ster5rmon3tgage6scow4to0rcycles9v0ie4p1q1r1s0d2t0n1r2u0seum3ic4v1w1x1y1z2na0b1goya4me2vy3ba2c1e0c1t0bank4flix4work5ustar5w0s2xt0direct7us4f0l2g0o2hk2i0co2ke1on3nja3ssan1y5l1o0kia3rton4w0ruz3tv4p1r0a1w2tt2u1yc2z2obi1server7ffice5kinawa6layan0group9lo3m0ega4ne1g1l0ine5oo2pen3racle3nge4g0anic5igins6saka4tsuka4t2vh3pa0ge2nasonic7ris2s1tners4s1y3y2ccw3e0t2f0izer5g1h0armacy6d1ilips5one2to0graphy6s4ysio5ics1tet2ures6d1n0g1k2oneer5zza4k1l0ace2y0station9umbing5s3m1n0c2ohl2ker3litie5rn2st3r0axi3ess3ime3o0d0uctions8f1gressive8mo2perties3y5tection8u0dential9s1t1ub2w0c2y2qa1pon3uebec3st5racing4dio4e0ad1lestate6tor2y4cipes5d0umbrella9hab3ise0n3t2liance6n0t0als5pair3ort3ublican8st0aurant8view0s5xroth6ich0ardli6oh3l1o1p2o0cks3deo3gers4om3s0vp3u0gby3hr2n2w0e2yukyu6sa0arland6fe0ty4kura4le1on3msclub4ung5ndvik0coromant12ofi4p1rl2s1ve2xo3b0i1s2c0b1haeffler7midt4olarships8ol3ule3warz5ience5ot3d1e0arch3t2cure1ity6ek2lect4ner3rvices6ven3w1x0y3fr2g1h0angrila6rp3ell3ia1ksha5oes2p0ping5uji3w3i0lk2na1gles5te3j1k0i0n2y0pe4l0ing4m0art3ile4n0cf3o0ccer3ial4ftbank4ware6hu2lar2utions7ng1y2y2pa0ce3ort2t3r0l2s1t0ada2ples4r1tebank4farm7c0group6ockholm6rage3e3ream4udio2y3yle4u0cks3pplies3y2ort5rf1gery5zuki5v1watch4iss4x1y0dney4stems6z2tab1ipei4lk2obao4rget4tamotors6r2too4x0i3c0i2d0k2eam2ch0nology8l1masek5nnis4va3f1g1h0d1eater2re6iaa2ckets5enda4ps2res2ol4j0maxx4x2k0maxx5l1m0all4n1o0day3kyo3ols3p1ray3shiba5tal3urs3wn2yota3s3r0ade1ing4ining5vel0ers0insurance16ust3v2t1ube2i1nes3shu4v0s2w1z2ua1bank3s2g1k1nicom3versity8o2ol2ps2s1y1z2va0cations7na1guard7c1e0gas3ntures6risign5mögensberater2ung14sicherung10t2g1i0ajes4deo3g1king4llas4n1p1rgin4sa1ion4va1o3laanderen9n1odka3lvo3te1ing3o2yage5u2wales2mart4ter4ng0gou5tch0es6eather0channel12bcam3er2site5d0ding5ibo2r3f1hoswho6ien2ki2lliamhill9n0dows4e1ners6me2oodside6rk0s2ld3w2s1tc1f3xbox3erox4ihuan4n2xx2yz3yachts4hoo3maxun5ndex5e1odobashi7ga2kohama6u0tube6t1un3za0ppos4ra3ero3ip2m1one3uerich6w2",BRs="ελ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",S9e="numeric",C9e="ascii",A9e="alpha",MY="asciinumeric",AW="alphanumeric",E9e="domain",JPt="emoji",$Rs="scheme",URs="slashscheme",NLe="whitespace";function qRs(s,t){return s in t||(t[s]=[]),t[s]}function dD(s,t,n){t[S9e]&&(t[MY]=!0,t[AW]=!0),t[C9e]&&(t[MY]=!0,t[A9e]=!0),t[MY]&&(t[AW]=!0),t[A9e]&&(t[AW]=!0),t[AW]&&(t[E9e]=!0),t[JPt]&&(t[E9e]=!0);for(const r in t){const a=qRs(r,n);a.indexOf(s)<0&&a.push(s)}}function VRs(s,t){const n={};for(const r in t)t[r].indexOf(s)>=0&&(n[r]=!0);return n}function u_(s=null){this.j={},this.jr=[],this.jd=null,this.t=s}u_.groups={};u_.prototype={accepts(){return!!this.t},go(s){const t=this,n=t.j[s];if(n)return n;for(let r=0;rs.ta(t,n,r,a),ig=(s,t,n,r,a)=>s.tr(t,n,r,a),iut=(s,t,n,r,a)=>s.ts(t,n,r,a),Za=(s,t,n,r,a)=>s.tt(t,n,r,a),lC="WORD",T9e="UWORD",eIt="ASCIINUMERICAL",tIt="ALPHANUMERICAL",pX="LOCALHOST",M9e="TLD",P9e="UTLD",xNe="SCHEME",O9="SLASH_SCHEME",tKe="NUM",I9e="WS",sKe="NL",PY="OPENBRACE",IY="CLOSEBRACE",BSe="OPENBRACKET",$Se="CLOSEBRACKET",USe="OPENPAREN",qSe="CLOSEPAREN",VSe="OPENANGLEBRACKET",HSe="CLOSEANGLEBRACKET",GSe="FULLWIDTHLEFTPAREN",WSe="FULLWIDTHRIGHTPAREN",KSe="LEFTCORNERBRACKET",YSe="RIGHTCORNERBRACKET",ZSe="LEFTWHITECORNERBRACKET",XSe="RIGHTWHITECORNERBRACKET",QSe="FULLWIDTHLESSTHAN",JSe="FULLWIDTHGREATERTHAN",e5e="AMPERSAND",t5e="APOSTROPHE",s5e="ASTERISK",xE="AT",n5e="BACKSLASH",r5e="BACKTICK",a5e="CARET",uD="COLON",nKe="COMMA",i5e="DOLLAR",SS="DOT",o5e="EQUALS",rKe="EXCLAMATION",Vj="HYPHEN",LY="PERCENT",l5e="PIPE",c5e="PLUS",d5e="POUND",RY="QUERY",aKe="QUOTE",sIt="FULLWIDTHMIDDLEDOT",iKe="SEMI",CS="SLASH",DY="TILDE",u5e="UNDERSCORE",nIt="EMOJI",h5e="SYM";var rIt=Object.freeze({__proto__:null,ALPHANUMERICAL:tIt,AMPERSAND:e5e,APOSTROPHE:t5e,ASCIINUMERICAL:eIt,ASTERISK:s5e,AT:xE,BACKSLASH:n5e,BACKTICK:r5e,CARET:a5e,CLOSEANGLEBRACKET:HSe,CLOSEBRACE:IY,CLOSEBRACKET:$Se,CLOSEPAREN:qSe,COLON:uD,COMMA:nKe,DOLLAR:i5e,DOT:SS,EMOJI:nIt,EQUALS:o5e,EXCLAMATION:rKe,FULLWIDTHGREATERTHAN:JSe,FULLWIDTHLEFTPAREN:GSe,FULLWIDTHLESSTHAN:QSe,FULLWIDTHMIDDLEDOT:sIt,FULLWIDTHRIGHTPAREN:WSe,HYPHEN:Vj,LEFTCORNERBRACKET:KSe,LEFTWHITECORNERBRACKET:ZSe,LOCALHOST:pX,NL:sKe,NUM:tKe,OPENANGLEBRACKET:VSe,OPENBRACE:PY,OPENBRACKET:BSe,OPENPAREN:USe,PERCENT:LY,PIPE:l5e,PLUS:c5e,POUND:d5e,QUERY:RY,QUOTE:aKe,RIGHTCORNERBRACKET:YSe,RIGHTWHITECORNERBRACKET:XSe,SCHEME:xNe,SEMI:iKe,SLASH:CS,SLASH_SCHEME:O9,SYM:h5e,TILDE:DY,TLD:M9e,UNDERSCORE:u5e,UTLD:P9e,UWORD:T9e,WORD:lC,WS:I9e});const W4=/[a-z]/,pG=new RegExp("\\p{L}","u"),kLe=new RegExp("\\p{Emoji}","u"),K4=/\d/,SLe=/\s/,out="\r",CLe=` `,HRs="️",GRs="‍",ALe="";let wre=null,jre=null;function WRs(s=[]){const t={};u_.groups=t;const n=new u_;wre==null&&(wre=lut(zRs)),jre==null&&(jre=lut(BRs)),Za(n,"'",t5e),Za(n,"{",PY),Za(n,"}",IY),Za(n,"[",BSe),Za(n,"]",$Se),Za(n,"(",USe),Za(n,")",qSe),Za(n,"<",VSe),Za(n,">",HSe),Za(n,"(",GSe),Za(n,")",WSe),Za(n,"「",KSe),Za(n,"」",YSe),Za(n,"『",ZSe),Za(n,"』",XSe),Za(n,"<",QSe),Za(n,">",JSe),Za(n,"&",e5e),Za(n,"*",s5e),Za(n,"@",xE),Za(n,"`",r5e),Za(n,"^",a5e),Za(n,":",uD),Za(n,",",nKe),Za(n,"$",i5e),Za(n,".",SS),Za(n,"=",o5e),Za(n,"!",rKe),Za(n,"-",Vj),Za(n,"%",LY),Za(n,"|",l5e),Za(n,"+",c5e),Za(n,"#",d5e),Za(n,"?",RY),Za(n,'"',aKe),Za(n,"/",CS),Za(n,";",iKe),Za(n,"~",DY),Za(n,"_",u5e),Za(n,"\\",n5e),Za(n,"・",sIt);const r=ig(n,K4,tKe,{[S9e]:!0});ig(r,K4,r);const a=ig(r,W4,eIt,{[MY]:!0}),i=ig(r,pG,tIt,{[AW]:!0}),l=ig(n,W4,lC,{[C9e]:!0});ig(l,K4,a),ig(l,W4,l),ig(a,K4,a),ig(a,W4,a);const o=ig(n,pG,T9e,{[A9e]:!0});ig(o,W4),ig(o,K4,i),ig(o,pG,o),ig(i,K4,i),ig(i,W4),ig(i,pG,i);const c=Za(n,CLe,sKe,{[NLe]:!0}),d=Za(n,out,I9e,{[NLe]:!0}),u=ig(n,SLe,I9e,{[NLe]:!0});Za(n,ALe,u),Za(d,CLe,c),Za(d,ALe,u),ig(d,SLe,u),Za(u,out),Za(u,CLe),ig(u,SLe,u),Za(u,ALe,u);const h=ig(n,kLe,nIt,{[JPt]:!0});Za(h,"#"),ig(h,kLe,h),Za(h,HRs,h);const m=Za(h,GRs);Za(m,"#"),ig(m,kLe,h);const p=[[W4,l],[K4,a]],g=[[W4,null],[pG,o],[K4,i]];for(let x=0;xx[0]>y[0]?1:-1);for(let x=0;x=0?_[E9e]=!0:W4.test(y)?K4.test(y)?_[MY]=!0:_[C9e]=!0:_[S9e]=!0,iut(n,y,y,_)}return iut(n,"localhost",pX,{ascii:!0}),n.jd=new u_(h5e),{start:n,tokens:Object.assign({groups:t},rIt)}}function aIt(s,t){const n=KRs(t.replace(/[A-Z]/g,o=>o.toLowerCase())),r=n.length,a=[];let i=0,l=0;for(;l=0&&(h+=n[l].length,m++),d+=n[l].length,i+=n[l].length,l++;i-=h,l-=m,d-=h,a.push({t:u.t,v:t.slice(i-d,i),s:i-d,e:i})}return a}function KRs(s){const t=[],n=s.length;let r=0;for(;r56319||r+1===n||(i=s.charCodeAt(r+1))<56320||i>57343?s[r]:s.slice(r,r+2);t.push(l),r+=l.length}return t}function $A(s,t,n,r,a){let i;const l=t.length;for(let o=0;o=0;)i++;if(i>0){t.push(n.join(""));for(let l=parseInt(s.substring(r,r+i),10);l>0;l--)n.pop();r+=i}else n.push(s[r]),r++}return t}const gX={defaultProtocol:"http",events:null,format:cut,formatHref:cut,nl2br:!1,tagName:"a",target:null,rel:null,validate:!0,truncate:1/0,className:null,attributes:null,ignoreTags:[],render:null};function oKe(s,t=null){let n=Object.assign({},gX);s&&(n=Object.assign(n,s instanceof oKe?s.o:s));const r=n.ignoreTags,a=[];for(let i=0;in?r.substring(0,n)+"…":r},toFormattedHref(s){return s.get("formatHref",this.toHref(s.get("defaultProtocol")),this)},startIndex(){return this.tk[0].s},endIndex(){return this.tk[this.tk.length-1].e},toObject(s=gX.defaultProtocol){return{type:this.t,value:this.toString(),isLink:this.isLink,href:this.toHref(s),start:this.startIndex(),end:this.endIndex()}},toFormattedObject(s){return{type:this.t,value:this.toFormattedString(s),isLink:this.isLink,href:this.toFormattedHref(s),start:this.startIndex(),end:this.endIndex()}},validate(s){return s.get("validate",this.toString(),this)},render(s){const t=this,n=this.toHref(s.get("defaultProtocol")),r=s.get("formatHref",n,this),a=s.get("tagName",n,t),i=this.toFormattedString(s),l={},o=s.get("className",n,t),c=s.get("target",n,t),d=s.get("rel",n,t),u=s.getObj("attributes",n,t),h=s.getObj("events",n,t);return l.href=r,o&&(l.class=o),c&&(l.target=c),d&&(l.rel=d),u&&Object.assign(l,u),{tagName:a,attributes:l,content:i,eventListeners:h}}};function PAe(s,t){class n extends iIt{constructor(a,i){super(a,i),this.t=s}}for(const r in t)n.prototype[r]=t[r];return n.t=s,n}const YRs=PAe("email",{isLink:!0,toHref(){return"mailto:"+this.toString()}}),dut=PAe("text"),ZRs=PAe("nl"),Nre=PAe("url",{isLink:!0,toHref(s=gX.defaultProtocol){return this.hasProtocol()?this.v:`${s}://${this.v}`},hasProtocol(){const s=this.tk;return s.length>=2&&s[0].t!==pX&&s[1].t===uD}}),Mj=s=>new u_(s);function XRs({groups:s}){const t=s.domain.concat([e5e,s5e,xE,n5e,r5e,a5e,i5e,o5e,Vj,tKe,LY,l5e,c5e,d5e,CS,h5e,DY,u5e]),n=[t5e,uD,nKe,SS,rKe,LY,RY,aKe,iKe,VSe,HSe,PY,IY,$Se,BSe,USe,qSe,GSe,WSe,KSe,YSe,ZSe,XSe,QSe,JSe],r=[e5e,t5e,s5e,n5e,r5e,a5e,i5e,o5e,Vj,PY,IY,LY,l5e,c5e,d5e,RY,CS,h5e,DY,u5e],a=Mj(),i=Za(a,DY);ud(i,r,i),ud(i,s.domain,i);const l=Mj(),o=Mj(),c=Mj();ud(a,s.domain,l),ud(a,s.scheme,o),ud(a,s.slashscheme,c),ud(l,r,i),ud(l,s.domain,l);const d=Za(l,xE);Za(i,xE,d),Za(o,xE,d),Za(c,xE,d);const u=Za(i,SS);ud(u,r,i),ud(u,s.domain,i);const h=Mj();ud(d,s.domain,h),ud(h,s.domain,h);const m=Za(h,SS);ud(m,s.domain,h);const p=Mj(YRs);ud(m,s.tld,p),ud(m,s.utld,p),Za(d,pX,p);const g=Za(h,Vj);Za(g,Vj,g),ud(g,s.domain,h),ud(p,s.domain,h),Za(p,SS,m),Za(p,Vj,g);const x=Za(l,Vj),y=Za(l,SS);Za(x,Vj,x),ud(x,s.domain,l),ud(y,r,i),ud(y,s.domain,l);const v=Mj(Nre);ud(y,s.tld,v),ud(y,s.utld,v),ud(v,s.domain,l),ud(v,r,i),Za(v,SS,y),Za(v,Vj,x),Za(v,xE,d);const _=Za(v,uD),j=Mj(Nre);ud(_,s.numeric,j);const C=Mj(Nre),A=Mj();ud(C,t,C),ud(C,n,A),ud(A,t,C),ud(A,n,A),Za(v,CS,C),Za(j,CS,C);const M=Za(o,uD),I=Za(c,uD),P=Za(I,CS),R=Za(P,CS);ud(o,s.domain,l),Za(o,SS,y),Za(o,Vj,x),ud(c,s.domain,l),Za(c,SS,y),Za(c,Vj,x),ud(M,s.domain,C),Za(M,CS,C),Za(M,RY,C),ud(R,s.domain,C),ud(R,t,C),Za(R,CS,C);const O=[[PY,IY],[BSe,$Se],[USe,qSe],[VSe,HSe],[GSe,WSe],[KSe,YSe],[ZSe,XSe],[QSe,JSe]];for(let B=0;B=0&&m++,a++,u++;if(m<0)a-=u,a0&&(i.push(ELe(dut,t,l)),l=[]),a-=m,u-=m;const p=h.t,g=n.slice(a-u,a);i.push(ELe(p,t,g))}}return l.length>0&&i.push(ELe(dut,t,l)),i}function ELe(s,t,n){const r=n[0].s,a=n[n.length-1].e,i=t.slice(r,a);return new s(i,n)}const JRs=typeof console<"u"&&console&&console.warn||(()=>{}),eDs="until manual call of linkify.init(). Register all schemes and plugins before invoking linkify the first time.",gf={scanner:null,parser:null,tokenQueue:[],pluginQueue:[],customSchemes:[],initialized:!1};function tDs(){return u_.groups={},gf.scanner=null,gf.parser=null,gf.tokenQueue=[],gf.pluginQueue=[],gf.customSchemes=[],gf.initialized=!1,gf}function uut(s,t=!1){if(gf.initialized&&JRs(`linkifyjs: already initialized - will not register custom scheme "${s}" ${eDs}`),!/^[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`);gf.customSchemes.push([s,t])}function sDs(){gf.scanner=WRs(gf.customSchemes);for(let s=0;s{const a=t.some(d=>d.docChanged)&&!n.doc.eq(r.doc),i=t.some(d=>d.getMeta("preventAutolink"));if(!a||i)return;const{tr:l}=r,o=IIs(n.doc,[...t]);if(BIs(o).forEach(({newRange:d})=>{const u=RIs(r.doc,d,p=>p.isTextblock);let h,m;if(u.length>1)h=u[0],m=r.doc.textBetween(h.pos,h.pos+h.node.nodeSize,void 0," ");else if(u.length){const p=r.doc.textBetween(d.from,d.to," "," ");if(!rDs.test(p))return;h=u[0],m=r.doc.textBetween(h.pos,d.to,void 0," ")}if(h&&m){const p=m.split(nDs).filter(Boolean);if(p.length<=0)return!1;const g=p[p.length-1],x=h.pos+m.lastIndexOf(g);if(!g)return!1;const y=lKe(g).map(v=>v.toObject(s.defaultProtocol));if(!iDs(y))return!1;y.filter(v=>v.isLink).map(v=>({...v,from:x+v.start+1,to:x+v.end+1})).filter(v=>r.schema.marks.code?!r.doc.rangeHasMark(v.from,v.to,r.schema.marks.code):!0).filter(v=>s.validate(v.value)).filter(v=>s.shouldAutoLink(v.value)).forEach(v=>{WWe(v.from,v.to,r.doc).some(_=>_.mark.type===s.type)||l.addMark(v.from,v.to,s.type.create({href:v.href}))})}}),!!l.steps.length)return l}})}function lDs(s){return new Iy({key:new b1("handleClickLink"),props:{handleClick:(t,n,r)=>{var a,i;if(r.button!==0||!t.editable)return!1;let l=r.target;const o=[];for(;l.nodeName!=="DIV";)o.push(l),l=l.parentNode;if(!o.find(m=>m.nodeName==="A"))return!1;const c=qPt(t.state,s.type.name),d=r.target,u=(a=d==null?void 0:d.href)!==null&&a!==void 0?a:c.href,h=(i=d==null?void 0:d.target)!==null&&i!==void 0?i:c.target;return d&&u?(window.open(u,h),!0):!1}}})}function cDs(s){return new Iy({key:new b1("handlePasteLink"),props:{handlePaste:(t,n,r)=>{const{state:a}=t,{selection:i}=a,{empty:l}=i;if(l)return!1;let o="";r.content.forEach(d=>{o+=d.textContent});const c=oIt(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 iP(s,t){const n=["http","https","ftp","ftps","mailto","tel","callto","sms","cid","xmpp"];return t&&t.forEach(r=>{const a=typeof r=="string"?r:r.scheme;a&&n.push(a)}),!s||s.replace(aDs,"").match(new RegExp(`^(?:(?:${n.join("|")}):|[^a-z]|[a-z0-9+.-]+(?:[^a-z+.-:]|$))`,"i"))}const dKe=yk.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"){uut(s);return}uut(s.scheme,s.optionalSlashes)})},onDestroy(){tDs()},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)=>!!iP(s,t.protocols),validate:s=>!!s,shouldAutoLink:s=>!!s}},addAttributes(){return{href:{default:null,parseHTML(s){return s.getAttribute("href")}},target:{default:this.options.HTMLAttributes.target},rel:{default:this.options.HTMLAttributes.rel},class:{default:this.options.HTMLAttributes.class}}},parseHTML(){return[{tag:"a[href]",getAttrs:s=>{const t=s.getAttribute("href");return!t||!this.options.isAllowedUri(t,{defaultValidate:n=>!!iP(n,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol})?!1:null}}]},renderHTML({HTMLAttributes:s}){return this.options.isAllowedUri(s.href,{defaultValidate:t=>!!iP(t,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol})?["a",cp(this.options.HTMLAttributes,s),0]:["a",cp(this.options.HTMLAttributes,{...s,href:""}),0]},addCommands(){return{setLink:s=>({chain:t})=>{const{href:n}=s;return this.options.isAllowedUri(n,{defaultValidate:r=>!!iP(r,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol})?t().setMark(this.name,s).setMeta("preventAutolink",!0).run():!1},toggleLink:s=>({chain:t})=>{const{href:n}=s;return this.options.isAllowedUri(n,{defaultValidate:r=>!!iP(r,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol})?t().toggleMark(this.name,s,{extendEmptyMarkRange:!0}).setMeta("preventAutolink",!0).run():!1},unsetLink:()=>({chain:s})=>s().unsetMark(this.name,{extendEmptyMarkRange:!0}).setMeta("preventAutolink",!0).run()}},addPasteRules(){return[zO({find:s=>{const t=[];if(s){const{protocols:n,defaultProtocol:r}=this.options,a=oIt(s).filter(i=>i.isLink&&this.options.isAllowedUri(i.value,{defaultValidate:l=>!!iP(l,n),protocols:n,defaultProtocol:r}));a.length&&a.forEach(i=>t.push({text:i.value,data:{href:i.href},index:i.start}))}return t},type:this.type,getAttributes:s=>{var t;return{href:(t=s.data)===null||t===void 0?void 0:t.href}}})]},addProseMirrorPlugins(){const s=[],{protocols:t,defaultProtocol:n}=this.options;return this.options.autolink&&s.push(oDs({type:this.type,defaultProtocol:this.options.defaultProtocol,validate:r=>this.options.isAllowedUri(r,{defaultValidate:a=>!!iP(a,t),protocols:t,defaultProtocol:n}),shouldAutoLink:this.options.shouldAutoLink})),this.options.openOnClick===!0&&s.push(lDs({type:this.type})),this.options.linkOnPaste&&s.push(cDs({editor:this.editor,defaultProtocol:this.options.defaultProtocol,type:this.type})),s}}),uKe=xv.create({name:"textAlign",addOptions(){return{types:[],alignments:["left","center","right","justify"],defaultAlignment:null}},addGlobalAttributes(){return[{types:this.options.types,attributes:{textAlign:{default:this.options.defaultAlignment,parseHTML:s=>{const t=s.style.textAlign;return this.options.alignments.includes(t)?t:this.options.defaultAlignment},renderHTML:s=>s.textAlign?{style:`text-align: ${s.textAlign}`}:{}}}}]},addCommands(){return{setTextAlign:s=>({commands:t})=>this.options.alignments.includes(s)?this.options.types.map(n=>t.updateAttributes(n,{textAlign:s})).every(n=>n):!1,unsetTextAlign:()=>({commands:s})=>this.options.types.map(t=>s.resetAttributes(t,"textAlign")).every(t=>t),toggleTextAlign:s=>({editor:t,commands:n})=>this.options.alignments.includes(s)?t.isActive({textAlign:s})?n.unsetTextAlign():n.setTextAlign(s):!1}},addKeyboardShortcuts(){return{"Mod-Shift-l":()=>this.editor.commands.setTextAlign("left"),"Mod-Shift-e":()=>this.editor.commands.setTextAlign("center"),"Mod-Shift-r":()=>this.editor.commands.setTextAlign("right"),"Mod-Shift-j":()=>this.editor.commands.setTextAlign("justify")}}}),dDs=s=>{if(!s.children.length)return;const t=s.querySelectorAll("span");t&&t.forEach(n=>{var r,a;const i=n.getAttribute("style"),l=(a=(r=n.parentElement)===null||r===void 0?void 0:r.closest("span"))===null||a===void 0?void 0:a.getAttribute("style");n.setAttribute("style",`${l};${i}`)})},hKe=yk.create({name:"textStyle",priority:101,addOptions(){return{HTMLAttributes:{},mergeNestedSpanStyles:!1}},parseHTML(){return[{tag:"span",getAttrs:s=>s.hasAttribute("style")?(this.options.mergeNestedSpanStyles&&dDs(s),{}):!1}]},renderHTML({HTMLAttributes:s}){return["span",cp(this.options.HTMLAttributes,s),0]},addCommands(){return{removeEmptyTextStyle:()=>({tr:s})=>{const{selection:t}=s;return s.doc.nodesBetween(t.from,t.to,(n,r)=>{if(n.isTextblock)return!0;n.marks.filter(a=>a.type===this.type).some(a=>Object.values(a.attrs).some(i=>!!i))||s.removeMark(r,r+n.nodeSize,this.type)}),!0}}}}),uDs=/(?:^|\s)(!\[(.+|:?)]\((\S+)(?:(?:\s+)["'](\S+)["'])?\))$/,hDs=_1.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",cp(this.options.HTMLAttributes,s)]},addCommands(){return{setImage:s=>({commands:t})=>t.insertContent({type:this.name,attrs:s})}},addInputRules(){return[VPt({find:uDs,type:this.type,getAttributes:s=>{const[,,t,n,r]=s;return{src:n,alt:t,title:r}}})]}});let L9e,R9e;if(typeof WeakMap<"u"){let s=new WeakMap;L9e=t=>s.get(t),R9e=(t,n)=>(s.set(t,n),n)}else{const s=[];let n=0;L9e=r=>{for(let a=0;a(n==10&&(n=0),s[n++]=r,s[n++]=a)}var bg=class{constructor(s,t,n,r){this.width=s,this.height=t,this.map=n,this.problems=r}findCell(s){for(let t=0;t=n){(i||(i=[])).push({type:"overlong_rowspan",pos:u,n:v-j});break}const C=a+j*t;for(let A=0;Ar&&(i+=d.attrs.colspan)}}for(let l=0;l1&&(n=!0)}t==-1?t=i:t!=i&&(t=Math.max(t,i))}return t}function pDs(s,t,n){s.problems||(s.problems=[]);const r={};for(let a=0;a0;t--)if(s.node(t).type.spec.tableRole=="row")return s.node(0).resolve(s.before(t+1));return null}function xDs(s){for(let t=s.depth;t>0;t--){const n=s.node(t).type.spec.tableRole;if(n==="cell"||n==="header_cell")return s.node(t)}return null}function Ck(s){const t=s.selection.$head;for(let n=t.depth;n>0;n--)if(t.node(n).type.spec.tableRole=="row")return!0;return!1}function IAe(s){const t=s.selection;if("$anchorCell"in t&&t.$anchorCell)return t.$anchorCell.pos>t.$headCell.pos?t.$anchorCell:t.$headCell;if("node"in t&&t.node&&t.node.type.spec.tableRole=="cell")return t.$anchor;const n=BO(t.$head)||yDs(t.$head);if(n)return n;throw new RangeError(`No cell found around position ${t.head}`)}function yDs(s){for(let t=s.nodeAfter,n=s.pos;t;t=t.firstChild,n++){const r=t.type.spec.tableRole;if(r=="cell"||r=="header_cell")return s.doc.resolve(n)}for(let t=s.nodeBefore,n=s.pos;t;t=t.lastChild,n--){const r=t.type.spec.tableRole;if(r=="cell"||r=="header_cell")return s.doc.resolve(n-t.nodeSize)}}function D9e(s){return s.parent.type.spec.tableRole=="row"&&!!s.nodeAfter}function vDs(s){return s.node(0).resolve(s.pos+s.nodeAfter.nodeSize)}function mKe(s,t){return s.depth==t.depth&&s.pos>=t.start(-1)&&s.pos<=t.end(-1)}function lIt(s,t,n){const r=s.node(-1),a=bg.get(r),i=s.start(-1),l=a.nextCell(s.pos-i,t,n);return l==null?null:s.node(0).resolve(i+l)}function $O(s,t,n=1){const r={...s,colspan:s.colspan-n};return r.colwidth&&(r.colwidth=r.colwidth.slice(),r.colwidth.splice(t,n),r.colwidth.some(a=>a>0)||(r.colwidth=null)),r}function cIt(s,t,n=1){const r={...s,colspan:s.colspan+n};if(r.colwidth){r.colwidth=r.colwidth.slice();for(let a=0;au!=n.pos-i);c.unshift(n.pos-i);const d=c.map(u=>{const h=r.nodeAt(u);if(!h)throw new RangeError(`No cell with offset ${u} found`);const m=i+u+1;return new L6t(o.resolve(m),o.resolve(m+h.content.size))});super(d[0].$from,d[0].$to,d),this.$anchorCell=t,this.$headCell=n}map(t,n){const r=t.resolve(n.map(this.$anchorCell.pos)),a=t.resolve(n.map(this.$headCell.pos));if(D9e(r)&&D9e(a)&&mKe(r,a)){const i=this.$anchorCell.node(-1)!=r.node(-1);return i&&this.isRowSelection()?cC.rowSelection(r,a):i&&this.isColSelection()?cC.colSelection(r,a):new cC(r,a)}return ul.between(r,a)}content(){const t=this.$anchorCell.node(-1),n=bg.get(t),r=this.$anchorCell.start(-1),a=n.rectBetween(this.$anchorCell.pos-r,this.$headCell.pos-r),i={},l=[];for(let c=a.top;c0||y>0){let v=g.attrs;if(x>0&&(v=$O(v,0,x)),y>0&&(v=$O(v,v.colspan-y,y)),p.lefta.bottom){const v={...g.attrs,rowspan:Math.min(p.bottom,a.bottom)-Math.max(p.top,a.top)};p.top0)return!1;const r=t+this.$anchorCell.nodeAfter.attrs.rowspan,a=n+this.$headCell.nodeAfter.attrs.rowspan;return Math.max(r,a)==this.$headCell.node(-1).childCount}static colSelection(t,n=t){const r=t.node(-1),a=bg.get(r),i=t.start(-1),l=a.findCell(t.pos-i),o=a.findCell(n.pos-i),c=t.node(0);return l.top<=o.top?(l.top>0&&(t=c.resolve(i+a.map[l.left])),o.bottom0&&(n=c.resolve(i+a.map[o.left])),l.bottom0)return!1;const l=a+this.$anchorCell.nodeAfter.attrs.colspan,o=i+this.$headCell.nodeAfter.attrs.colspan;return Math.max(l,o)==n.width}eq(t){return t instanceof cC&&t.$anchorCell.pos==this.$anchorCell.pos&&t.$headCell.pos==this.$headCell.pos}static rowSelection(t,n=t){const r=t.node(-1),a=bg.get(r),i=t.start(-1),l=a.findCell(t.pos-i),o=a.findCell(n.pos-i),c=t.node(0);return l.left<=o.left?(l.left>0&&(t=c.resolve(i+a.map[l.top*a.width])),o.right0&&(n=c.resolve(i+a.map[o.top*a.width])),l.right{t.push(cb.node(r,r+n.nodeSize,{class:"selectedCell"}))}),xg.create(s.doc,t)}function jDs({$from:s,$to:t}){if(s.pos==t.pos||s.pos=0&&!(s.after(a+1)=0&&!(t.before(i+1)>t.start(i));i--,r--);return n==r&&/row|table/.test(s.node(a).type.spec.tableRole)}function NDs({$from:s,$to:t}){let n,r;for(let a=s.depth;a>0;a--){const i=s.node(a);if(i.type.spec.tableRole==="cell"||i.type.spec.tableRole==="header_cell"){n=i;break}}for(let a=t.depth;a>0;a--){const i=t.node(a);if(i.type.spec.tableRole==="cell"||i.type.spec.tableRole==="header_cell"){r=i;break}}return n!==r&&t.parentOffset===0}function kDs(s,t,n){const r=(t||s).selection,a=(t||s).doc;let i,l;if(r instanceof hl&&(l=r.node.type.spec.tableRole)){if(l=="cell"||l=="header_cell")i=$m.create(a,r.from);else if(l=="row"){const o=a.resolve(r.from+1);i=$m.rowSelection(o,o)}else if(!n){const o=bg.get(r.node),c=r.from+1,d=c+o.map[o.width*o.height-1];i=$m.create(a,c+1,d)}}else r instanceof ul&&jDs(r)?i=ul.create(a,r.from):r instanceof ul&&NDs(r)&&(i=ul.create(a,r.$from.start(),r.$from.end()));return i&&(t||(t=s.tr)).setSelection(i),t}const SDs=new b1("fix-tables");function uIt(s,t,n,r){const a=s.childCount,i=t.childCount;e:for(let l=0,o=0;l{a.type.spec.tableRole=="table"&&(n=CDs(s,a,i,n))};return t?t.doc!=s.doc&&uIt(t.doc,s.doc,0,r):s.doc.descendants(r),n}function CDs(s,t,n,r){const a=bg.get(t);if(!a.problems)return r;r||(r=s.tr);const i=[];for(let c=0;c0){let p="cell";u.firstChild&&(p=u.firstChild.type.spec.tableRole);const g=[];for(let y=0;y0?-1:0;bDs(t,r,a+i)&&(i=a==0||a==t.width?null:0);for(let l=0;l0&&a0&&t.map[o-1]==c||a0?-1:0;PDs(t,r,a+o)&&(o=a==0||a==t.height?null:0);for(let d=0,u=t.width*a;d0&&a0&&h==t.map[u-t.width]){const m=n.nodeAt(h).attrs;s.setNodeMarkup(s.mapping.slice(o).map(h+r),null,{...m,rowspan:m.rowspan-1}),d+=m.colspan-1}else if(a0&&n[i]==n[i-1]||r.right0&&n[a]==n[a-s]||r.bottom0){const u=c+1+d.content.size,h=hut(d)?c+1:u;i.replaceWith(h+r.tableStart,u+r.tableStart,o)}i.setSelection(new $m(i.doc.resolve(c+r.tableStart))),t(i)}return!0}function fut(s,t){const n=x1(s.schema);return FDs(({node:r})=>n[r.type.spec.tableRole])(s,t)}function FDs(s){return(t,n)=>{const r=t.selection;let a,i;if(r instanceof $m){if(r.$anchorCell.pos!=r.$headCell.pos)return!1;a=r.$anchorCell.nodeAfter,i=r.$anchorCell.pos}else{var l;if(a=xDs(r.$from),!a)return!1;i=(l=BO(r.$from))===null||l===void 0?void 0:l.pos}if(a==null||i==null||a.attrs.colspan==1&&a.attrs.rowspan==1)return!1;if(n){let o=a.attrs;const c=[],d=o.colwidth;o.rowspan>1&&(o={...o,rowspan:1}),o.colspan>1&&(o={...o,colspan:1});const u=s4(t),h=t.tr;for(let p=0;p{l.attrs[s]!==t&&i.setNodeMarkup(o,null,{...l.attrs,[s]:t})}):i.setNodeMarkup(a.pos,null,{...a.nodeAfter.attrs,[s]:t}),r(i)}return!0}}function BDs(s){return function(t,n){if(!Ck(t))return!1;if(n){const r=x1(t.schema),a=s4(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 p=m+i.tableStart,g=l.doc.nodeAt(p);g&&l.setNodeMarkup(p,h,g.attrs)}),r(l)}return!0}}xX("row",{useDeprecatedLogic:!0});xX("column",{useDeprecatedLogic:!0});const $Ds=xX("cell",{useDeprecatedLogic:!0});function UDs(s,t){if(t<0){const n=s.nodeBefore;if(n)return s.pos-n.nodeSize;for(let r=s.index(-1)-1,a=s.before();r>=0;r--){const i=s.node(-1).child(r),l=i.lastChild;if(l)return a-1-l.nodeSize;a-=i.nodeSize}}else{if(s.index()0;r--)if(n.node(r).type.spec.tableRole=="table")return t&&t(s.tr.delete(n.before(r),n.after(r)).scrollIntoView()),!0;return!1}function kre(s,t){const n=s.selection;if(!(n instanceof $m))return!1;if(t){const r=s.tr,a=x1(s.schema).cell.createAndFill().content;n.forEachCell((i,l)=>{i.content.eq(a)||r.replace(r.mapping.map(l+1),r.mapping.map(l+i.nodeSize-1),new Ii(a,0,0))}),r.docChanged&&t(r)}return!0}function VDs(s){if(s.size===0)return null;let{content:t,openStart:n,openEnd:r}=s;for(;t.childCount==1&&(n>0&&r>0||t.child(0).type.spec.tableRole=="table");)n--,r--,t=t.child(0).content;const a=t.child(0),i=a.type.spec.tableRole,l=a.type.schema,o=[];if(i=="row")for(let c=0;c=0;l--){const{rowspan:o,colspan:c}=i.child(l).attrs;for(let d=a;d=t.length&&t.push(Ua.empty),n[a]r&&(m=m.type.createChecked($O(m.attrs,m.attrs.colspan,u+m.attrs.colspan-r),m.content)),d.push(m),u+=m.attrs.colspan;for(let p=1;pa&&(h=h.type.create({...h.attrs,rowspan:Math.max(1,a-h.attrs.rowspan)},h.content)),c.push(h)}i.push(Ua.from(c))}n=i,t=a}return{width:s,height:t,rows:n}}function WDs(s,t,n,r,a,i,l){const o=s.doc.type.schema,c=x1(o);let d,u;if(a>t.width)for(let h=0,m=0;ht.height){const h=[];for(let g=0,x=(t.height-1)*t.width;g=t.width?!1:n.nodeAt(t.map[x+g]).type==c.header_cell;h.push(y?u||(u=c.header_cell.createAndFill()):d||(d=c.cell.createAndFill()))}const m=c.row.create(null,Ua.from(h)),p=[];for(let g=t.height;g{if(!a)return!1;const i=n.selection;if(i instanceof $m)return yNe(n,r,$l.near(i.$headCell,t));if(s!="horiz"&&!i.empty)return!1;const l=pIt(a,s,t);if(l==null)return!1;if(s=="horiz")return yNe(n,r,$l.near(n.doc.resolve(i.head+t),t));{const o=n.doc.resolve(l),c=lIt(o,s,t);let d;return c?d=$l.near(c,1):t<0?d=$l.near(n.doc.resolve(o.before(-1)),-1):d=$l.near(n.doc.resolve(o.after(-1)),1),yNe(n,r,d)}}}function Cre(s,t){return(n,r,a)=>{if(!a)return!1;const i=n.selection;let l;if(i instanceof $m)l=i;else{const c=pIt(a,s,t);if(c==null)return!1;l=new $m(n.doc.resolve(c))}const o=lIt(l.$headCell,s,t);return o?yNe(n,r,new $m(l.$anchorCell,o)):!1}}function YDs(s,t){const n=s.state.doc,r=BO(n.resolve(t));return r?(s.dispatch(s.state.tr.setSelection(new $m(r))),!0):!1}function ZDs(s,t,n){if(!Ck(s.state))return!1;let r=VDs(n);const a=s.state.selection;if(a instanceof $m){r||(r={width:1,height:1,rows:[Ua.from(O9e(x1(s.state.schema).cell,n))]});const i=a.$anchorCell.node(-1),l=a.$anchorCell.start(-1),o=bg.get(i).rectBetween(a.$anchorCell.pos-l,a.$headCell.pos-l);return r=GDs(r,o.right-o.left,o.bottom-o.top),vut(s.state,s.dispatch,l,o,r),!0}else if(r){const i=IAe(s.state),l=i.start(-1);return vut(s.state,s.dispatch,l,bg.get(i.node(-1)).findCell(i.pos-l),r),!0}else return!1}function XDs(s,t){var n;if(t.button!=0||t.ctrlKey||t.metaKey)return;const r=but(s,t.target);let a;if(t.shiftKey&&s.state.selection instanceof $m)i(s.state.selection.$anchorCell,t),t.preventDefault();else if(t.shiftKey&&r&&(a=BO(s.state.selection.$anchor))!=null&&((n=TLe(s,t))===null||n===void 0?void 0:n.pos)!=a.pos)i(a,t),t.preventDefault();else if(!r)return;function i(c,d){let u=TLe(s,d);const h=TE.getState(s.state)==null;if(!u||!mKe(c,u))if(h)u=c;else return;const m=new $m(c,u);if(h||!s.state.selection.eq(m)){const p=s.state.tr.setSelection(m);h&&p.setMeta(TE,c.pos),s.dispatch(p)}}function l(){s.root.removeEventListener("mouseup",l),s.root.removeEventListener("dragstart",l),s.root.removeEventListener("mousemove",o),TE.getState(s.state)!=null&&s.dispatch(s.state.tr.setMeta(TE,-1))}function o(c){const d=c,u=TE.getState(s.state);let h;if(u!=null)h=s.state.doc.resolve(u);else if(but(s,d.target)!=r&&(h=TLe(s,t),!h))return l();h&&i(h,d)}s.root.addEventListener("mouseup",l),s.root.addEventListener("dragstart",l),s.root.addEventListener("mousemove",o)}function pIt(s,t,n){if(!(s.state.selection instanceof ul))return null;const{$head:r}=s.state.selection;for(let a=r.depth-1;a>=0;a--){const i=r.node(a);if((n<0?r.index(a):r.indexAfter(a))!=(n<0?0:i.childCount))return null;if(i.type.spec.tableRole=="cell"||i.type.spec.tableRole=="header_cell"){const l=r.before(a),o=t=="vert"?n>0?"down":"up":n>0?"right":"left";return s.endOfTextblock(o)?l:null}}return null}function but(s,t){for(;t&&t!=s.dom;t=t.parentNode)if(t.nodeName=="TD"||t.nodeName=="TH")return t;return null}function TLe(s,t){const n=s.posAtCoords({left:t.clientX,top:t.clientY});if(!n)return null;let{inside:r,pos:a}=n;return r>=0&&BO(s.state.doc.resolve(r))||BO(s.state.doc.resolve(a))}var QDs=class{constructor(t,n){this.node=t,this.defaultCellMinWidth=n,this.dom=document.createElement("div"),this.dom.className="tableWrapper",this.table=this.dom.appendChild(document.createElement("table")),this.table.style.setProperty("--default-cell-min-width",`${n}px`),this.colgroup=this.table.appendChild(document.createElement("colgroup")),F9e(t,this.colgroup,this.table,n),this.contentDOM=this.table.appendChild(document.createElement("tbody"))}update(t){return t.type!=this.node.type?!1:(this.node=t,F9e(t,this.colgroup,this.table,this.defaultCellMinWidth),!0)}ignoreMutation(t){return t.type=="attributes"&&(t.target==this.table||this.colgroup.contains(t.target))}};function F9e(s,t,n,r,a,i){let l=0,o=!0,c=t.firstChild;const d=s.firstChild;if(d){for(let h=0,m=0;hnew r(h,n,m)),new e8s(-1,!1)},apply(l,o){return o.apply(l)}},props:{attributes:l=>{const o=$w.getState(l);return o&&o.activeHandle>-1?{class:"resize-cursor"}:{}},handleDOMEvents:{mousemove:(l,o)=>{t8s(l,o,s,a)},mouseleave:l=>{s8s(l)},mousedown:(l,o)=>{n8s(l,o,t,n)}},decorations:l=>{const o=$w.getState(l);if(o&&o.activeHandle>-1)return l8s(l,o.activeHandle)},nodeViews:{}}});return i}var e8s=class vNe{constructor(t,n){this.activeHandle=t,this.dragging=n}apply(t){const n=this,r=t.getMeta($w);if(r&&r.setHandle!=null)return new vNe(r.setHandle,!1);if(r&&r.setDragging!==void 0)return new vNe(n.activeHandle,r.setDragging);if(n.activeHandle>-1&&t.docChanged){let a=t.mapping.map(n.activeHandle,-1);return D9e(t.doc.resolve(a))||(a=-1),new vNe(a,n.dragging)}return n}};function t8s(s,t,n,r){if(!s.editable)return;const a=$w.getState(s.state);if(a&&!a.dragging){const i=a8s(t.target);let l=-1;if(i){const{left:o,right:c}=i.getBoundingClientRect();t.clientX-o<=n?l=_ut(s,t,"left",n):c-t.clientX<=n&&(l=_ut(s,t,"right",n))}if(l!=a.activeHandle){if(!r&&l!==-1){const o=s.state.doc.resolve(l),c=o.node(-1),d=bg.get(c),u=o.start(-1);if(d.colCount(o.pos-u)+o.nodeAfter.attrs.colspan-1==d.width-1)return}gIt(s,l)}}}function s8s(s){if(!s.editable)return;const t=$w.getState(s.state);t&&t.activeHandle>-1&&!t.dragging&&gIt(s,-1)}function n8s(s,t,n,r){var a;if(!s.editable)return!1;const i=(a=s.dom.ownerDocument.defaultView)!==null&&a!==void 0?a:window,l=$w.getState(s.state);if(!l||l.activeHandle==-1||l.dragging)return!1;const o=s.state.doc.nodeAt(l.activeHandle),c=r8s(s,l.activeHandle,o.attrs);s.dispatch(s.state.tr.setMeta($w,{setDragging:{startX:t.clientX,startWidth:c}}));function d(h){i.removeEventListener("mouseup",d),i.removeEventListener("mousemove",u);const m=$w.getState(s.state);m!=null&&m.dragging&&(i8s(s,m.activeHandle,wut(m.dragging,h,n)),s.dispatch(s.state.tr.setMeta($w,{setDragging:null})))}function u(h){if(!h.which)return d(h);const m=$w.getState(s.state);if(m&&m.dragging){const p=wut(m.dragging,h,n);jut(s,m.activeHandle,p,r)}}return jut(s,l.activeHandle,c,r),i.addEventListener("mouseup",d),i.addEventListener("mousemove",u),t.preventDefault(),!0}function r8s(s,t,{colspan:n,colwidth:r}){const a=r&&r[r.length-1];if(a)return a;const i=s.domAtPos(t);let l=i.node.childNodes[i.offset].offsetWidth,o=n;if(r)for(let c=0;c{const r=s.nodes[n];r.spec.tableRole&&(t[r.spec.tableRole]=r)}),s.cached.tableNodeTypes=t,t}function m8s(s,t,n,r,a){const i=h8s(s),l=[],o=[];for(let d=0;d{const{selection:t}=s.state;if(!f8s(t))return!1;let n=0;const r=UPt(t.ranges[0].$from,i=>i.type.name==="table");return r==null||r.node.descendants(i=>{if(i.type.name==="table")return!1;["tableCell","tableHeader"].includes(i.type.name)&&(n+=1)}),n===t.ranges.length?(s.commands.deleteTable(),!0):!1},p8s=_1.create({name:"table",addOptions(){return{HTMLAttributes:{},resizable:!1,renderWrapper:!1,handleWidth:5,cellMinWidth:25,View:d8s,lastColumnResizable:!0,allowTableNodeSelection:!1}},content:"tableRow+",tableRole:"table",isolating:!0,group:"block",parseHTML(){return[{tag:"table"}]},renderHTML({node:s,HTMLAttributes:t}){const{colgroup:n,tableWidth:r,tableMinWidth:a}=u8s(s,this.options.cellMinWidth),i=["table",cp(this.options.HTMLAttributes,t,{style:r?`width: ${r}`:`min-width: ${a}`}),n,["tbody",0]];return this.options.renderWrapper?["div",{class:"tableWrapper"},i]:i},addCommands(){return{insertTable:({rows:s=3,cols:t=3,withHeaderRow:n=!0}={})=>({tr:r,dispatch:a,editor:i})=>{const l=m8s(i.schema,s,t,n);if(a){const o=r.selection.from+1;r.replaceSelectionWith(l).scrollIntoView().setSelection(ul.near(r.doc.resolve(o)))}return!0},addColumnBefore:()=>({state:s,dispatch:t})=>ADs(s,t),addColumnAfter:()=>({state:s,dispatch:t})=>EDs(s,t),deleteColumn:()=>({state:s,dispatch:t})=>MDs(s,t),addRowBefore:()=>({state:s,dispatch:t})=>IDs(s,t),addRowAfter:()=>({state:s,dispatch:t})=>LDs(s,t),deleteRow:()=>({state:s,dispatch:t})=>DDs(s,t),deleteTable:()=>({state:s,dispatch:t})=>qDs(s,t),mergeCells:()=>({state:s,dispatch:t})=>mut(s,t),splitCell:()=>({state:s,dispatch:t})=>fut(s,t),toggleHeaderColumn:()=>({state:s,dispatch:t})=>xX("column")(s,t),toggleHeaderRow:()=>({state:s,dispatch:t})=>xX("row")(s,t),toggleHeaderCell:()=>({state:s,dispatch:t})=>$Ds(s,t),mergeOrSplit:()=>({state:s,dispatch:t})=>mut(s,t)?!0:fut(s,t),setCellAttribute:(s,t)=>({state:n,dispatch:r})=>zDs(s,t)(n,r),goToNextCell:()=>({state:s,dispatch:t})=>gut(1)(s,t),goToPreviousCell:()=>({state:s,dispatch:t})=>gut(-1)(s,t),fixTables:()=>({state:s,dispatch:t})=>(t&&hIt(s),!0),setCellSelection:s=>({tr:t,dispatch:n})=>{if(n){const r=$m.create(t.doc,s.anchorCell,s.headCell);t.setSelection(r)}return!0}}},addKeyboardShortcuts(){return{Tab:()=>this.editor.commands.goToNextCell()?!0:this.editor.can().addRowAfter()?this.editor.chain().addRowAfter().goToNextCell().run():!1,"Shift-Tab":()=>this.editor.commands.goToPreviousCell(),Backspace:Are,"Mod-Backspace":Are,Delete:Are,"Mod-Delete":Are}},addProseMirrorPlugins(){return[...this.options.resizable&&this.editor.isEditable?[JDs({handleWidth:this.options.handleWidth,cellMinWidth:this.options.cellMinWidth,defaultCellMinWidth:this.options.cellMinWidth,View:this.options.View,lastColumnResizable:this.options.lastColumnResizable})]:[],c8s({allowTableNodeSelection:this.options.allowTableNodeSelection})]},extendNodeSchema(s){const t={name:s.name,options:s.options,storage:s.storage};return{tableRole:ad(So(s,"tableRole",t))}}}),g8s=_1.create({name:"tableRow",addOptions(){return{HTMLAttributes:{}}},content:"(tableCell | tableHeader)*",tableRole:"row",parseHTML(){return[{tag:"tr"}]},renderHTML({HTMLAttributes:s}){return["tr",cp(this.options.HTMLAttributes,s),0]}}),x8s=_1.create({name:"tableCell",addOptions(){return{HTMLAttributes:{}}},content:"block+",addAttributes(){return{colspan:{default:1},rowspan:{default:1},colwidth:{default:null,parseHTML:s=>{const t=s.getAttribute("colwidth");return t?t.split(",").map(r=>parseInt(r,10)):null}}}},tableRole:"cell",isolating:!0,parseHTML(){return[{tag:"td"}]},renderHTML({HTMLAttributes:s}){return["td",cp(this.options.HTMLAttributes,s),0]}}),y8s=_1.create({name:"tableHeader",addOptions(){return{HTMLAttributes:{}}},content:"block+",addAttributes(){return{colspan:{default:1},rowspan:{default:1},colwidth:{default:null,parseHTML:s=>{const t=s.getAttribute("colwidth");return t?t.split(",").map(r=>parseInt(r,10)):null}}}},tableRole:"header_cell",isolating:!0,parseHTML(){return[{tag:"th"}]},renderHTML({HTMLAttributes:s}){return["th",cp(this.options.HTMLAttributes,s),0]}});function V2({content:s,onChange:t,placeholder:n="Enter content...",minHeight:r="150px",compact:a=!1}){const[i,l]=k.useState(!1),[o,c]=k.useState(""),[d,u]=k.useState(!0),h=QWe({extensions:[eKe,dKe.configure({openOnClick:!1,HTMLAttributes:{class:"text-primary underline"}}),uKe.configure({types:["heading","paragraph"]}),hKe,hDs.extend({addAttributes(){var x;return{...(x=this.parent)==null?void 0:x.call(this),width:{default:null},height:{default:null},style:{default:null}}}}).configure({inline:!0,allowBase64:!0}),p8s.extend({addAttributes(){var x;return{...(x=this.parent)==null?void 0:x.call(this),style:{default:null},width:{default:null},cellpadding:{default:null},cellspacing:{default:null},border:{default:null}}}}).configure({resizable:!1}),g8s.extend({addAttributes(){var x;return{...(x=this.parent)==null?void 0:x.call(this),style:{default:null}}}}),x8s.extend({addAttributes(){var x;return{...(x=this.parent)==null?void 0:x.call(this),style:{default:null},width:{default:null},colspan:{default:1},rowspan:{default:1},valign:{default:null}}}}),y8s.extend({addAttributes(){var x;return{...(x=this.parent)==null?void 0:x.call(this),style:{default:null},width:{default:null},colspan:{default:1},rowspan:{default:1}}}})],content:s,onUpdate:({editor:x})=>{t(x.getHTML())},editorProps:{attributes:{class:"outline-none","data-placeholder":n},handlePaste:(x,y)=>{var _;const v=(_=y.clipboardData)==null?void 0:_.items;if(!v)return!1;for(const j of Array.from(v))if(j.type.startsWith("image/")){y.preventDefault();const C=j.getAsFile();if(!C)continue;const A=new FileReader;return A.onload=M=>{var P;const I=(P=M.target)==null?void 0:P.result;x.dispatch(x.state.tr.replaceSelectionWith(x.state.schema.nodes.image.create({src:I})))},A.readAsDataURL(C),!0}return!1}}});k.useEffect(()=>{h&&s!==h.getHTML()&&h.commands.setContent(s)},[s,h]);const m=()=>{if(!h)return;const x=h.getAttributes("link").href||"",y=h.getAttributes("link").target;c(x),u(y==="_blank"),l(!0)},p=()=>{h&&(o===""?h.chain().focus().extendMarkRange("link").unsetLink().run():h.chain().focus().extendMarkRange("link").setLink({href:o,target:d?"_blank":null,rel:d?"noopener noreferrer nofollow":null}).run(),l(!1),c(""))},g=()=>{h&&h.chain().focus().extendMarkRange("link").unsetLink().run()};return h?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"border rounded-lg overflow-hidden",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-0.5 p-2 border-b bg-muted/30",children:[e.jsx($,{type:"button",variant:"ghost",size:"sm",onClick:()=>h.chain().focus().toggleHeading({level:1}).run(),className:h.isActive("heading",{level:1})?"bg-muted":"",title:"Heading 1",children:e.jsx(Vz,{className:"h-4 w-4"})}),e.jsx($,{type:"button",variant:"ghost",size:"sm",onClick:()=>h.chain().focus().toggleHeading({level:2}).run(),className:h.isActive("heading",{level:2})?"bg-muted":"",title:"Heading 2",children:e.jsx(Hz,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx($,{type:"button",variant:"ghost",size:"sm",onClick:()=>h.chain().focus().toggleBold().run(),className:h.isActive("bold")?"bg-muted":"",title:"Bold",children:e.jsx(zT,{className:"h-4 w-4"})}),e.jsx($,{type:"button",variant:"ghost",size:"sm",onClick:()=>h.chain().focus().toggleItalic().run(),className:h.isActive("italic")?"bg-muted":"",title:"Italic",children:e.jsx(GT,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx($,{type:"button",variant:"ghost",size:"sm",onClick:()=>h.chain().focus().toggleBulletList().run(),className:h.isActive("bulletList")?"bg-muted":"",title:"Bullet List",children:e.jsx(Sy,{className:"h-4 w-4"})}),e.jsx($,{type:"button",variant:"ghost",size:"sm",onClick:()=>h.chain().focus().toggleOrderedList().run(),className:h.isActive("orderedList")?"bg-muted":"",title:"Numbered List",children:e.jsx(_2,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx($,{type:"button",variant:"ghost",size:"sm",onClick:()=>h.chain().focus().setTextAlign("left").run(),className:h.isActive({textAlign:"left"})?"bg-muted":"",title:"Align Left",children:e.jsx(M8,{className:"h-4 w-4"})}),e.jsx($,{type:"button",variant:"ghost",size:"sm",onClick:()=>h.chain().focus().setTextAlign("center").run(),className:h.isActive({textAlign:"center"})?"bg-muted":"",title:"Align Center",children:e.jsx(T8,{className:"h-4 w-4"})}),e.jsx($,{type:"button",variant:"ghost",size:"sm",onClick:()=>h.chain().focus().setTextAlign("right").run(),className:h.isActive({textAlign:"right"})?"bg-muted":"",title:"Align Right",children:e.jsx(P8,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx($,{type:"button",variant:"ghost",size:"sm",onClick:m,className:h.isActive("link")?"bg-muted":"",title:"Add Link",children:e.jsx(od,{className:"h-4 w-4"})}),h.isActive("link")&&e.jsx($,{type:"button",variant:"ghost",size:"sm",onClick:g,title:"Remove Link",children:e.jsx(od,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx($,{type:"button",variant:"ghost",size:"sm",onClick:()=>h.chain().focus().undo().run(),disabled:!h.can().undo(),title:"Undo",children:e.jsx(rM,{className:"h-4 w-4"})}),e.jsx($,{type:"button",variant:"ghost",size:"sm",onClick:()=>h.chain().focus().redo().run(),disabled:!h.can().redo(),title:"Redo",children:e.jsx(JT,{className:"h-4 w-4"})})]}),e.jsx(ZWe,{editor:h,className:"prose prose-sm max-w-none p-3 focus:outline-none [&_.ProseMirror]:outline-none [&_.ProseMirror_img]:max-w-none [&_.ProseMirror_table]:border-none [&_.ProseMirror_table]:border-collapse [&_.ProseMirror_td]:border-none [&_.ProseMirror_td]:p-0 [&_.ProseMirror_td]:align-top [&_.ProseMirror_th]:border-none [&_.ProseMirror_th]:p-0 [&_.ProseMirror_tr]:border-none",style:{minHeight:r}})]}),e.jsx(zs,{open:i,onOpenChange:l,children:e.jsxs(Rs,{className:"sm:max-w-md",children:[e.jsx(Vs,{children:e.jsx($s,{children:"Insert Link"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"link-url",children:"URL"}),e.jsx(be,{id:"link-url",value:o,onChange:x=>c(x.target.value),placeholder:"https://example.com"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(On,{id:"link-new-tab",checked:d,onCheckedChange:u}),e.jsx(re,{htmlFor:"link-new-tab",children:"Open in new tab"})]})]}),e.jsxs(kr,{children:[e.jsx($,{type:"button",variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsx($,{type:"button",onClick:p,children:o?"Apply Link":"Remove Link"})]})]})})]}):null}var fKe={x:0,y:0,width:0,height:0,unit:"px"},K7=(s,t,n)=>Math.min(Math.max(s,t),n),v8s=(...s)=>s.filter(t=>t&&typeof t=="string").join(" "),Sut=(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 b8s(s,t,n,r){let a=AS(s,n,r);return s.width&&(a.height=a.width/t),s.height&&(a.width=a.height*t),a.y+a.height>r&&(a.height=r-a.y,a.width=a.height*t),a.x+a.width>n&&(a.width=n-a.x,a.height=a.width/t),s.unit==="%"?yE(a,n,r):a}function _8s(s,t,n){let r=AS(s,t,n);return r.x=(t-r.width)/2,r.y=(n-r.height)/2,s.unit==="%"?yE(r,t,n):r}function yE(s,t,n){return s.unit==="%"?{...fKe,...s,unit:"%"}:{unit:"%",x:s.x?s.x/t*100:0,y:s.y?s.y/n*100:0,width:s.width?s.width/t*100:0,height:s.height?s.height/n*100:0}}function AS(s,t,n){return!s.unit||s.unit==="px"?{...fKe,...s,unit:"px"}:{unit:"px",x:s.x?s.x*t/100:0,y:s.y?s.y*n/100:0,width:s.width?s.width*t/100:0,height:s.height?s.height*n/100:0}}function Cut(s,t,n,r,a,i=0,l=0,o=r,c=a){let d={...s},u=Math.min(i,r),h=Math.min(l,a),m=Math.min(o,r),p=Math.min(c,a);t&&(t>1?(u=l?l*t:u,h=u/t,m=o*t):(h=i?i/t:h,u=h*t,p=c/t)),d.y<0&&(d.height=Math.max(d.height+d.y,h),d.y=0),d.x<0&&(d.width=Math.max(d.width+d.x,u),d.x=0);let g=r-(d.x+d.width);g<0&&(d.x=Math.min(d.x,r-u),d.width+=g);let x=a-(d.y+d.height);if(x<0&&(d.y=Math.min(d.y,a-h),d.height+=x),d.widthm&&((n==="sw"||n=="nw")&&(d.x-=m-d.width),d.width=m),d.height>p&&((n==="nw"||n=="ne")&&(d.y-=p-d.height),d.height=p),t){let y=d.width/d.height;if(yt){let v=Math.max(d.height*t,u);(n==="sw"||n=="nw")&&(d.x-=v-d.width),d.width=v}}return d}function w8s(s,t,n,r){let a={...s};return t==="ArrowLeft"?r==="nw"?(a.x-=n,a.y-=n,a.width+=n,a.height+=n):r==="w"?(a.x-=n,a.width+=n):r==="sw"?(a.x-=n,a.width+=n,a.height+=n):r==="ne"?(a.y+=n,a.width-=n,a.height-=n):r==="e"?a.width-=n:r==="se"&&(a.width-=n,a.height-=n):t==="ArrowRight"&&(r==="nw"?(a.x+=n,a.y+=n,a.width-=n,a.height-=n):r==="w"?(a.x+=n,a.width-=n):r==="sw"?(a.x+=n,a.width-=n,a.height-=n):r==="ne"?(a.y-=n,a.width+=n,a.height+=n):r==="e"?a.width+=n:r==="se"&&(a.width+=n,a.height+=n)),t==="ArrowUp"?r==="nw"?(a.x-=n,a.y-=n,a.width+=n,a.height+=n):r==="n"?(a.y-=n,a.height+=n):r==="ne"?(a.y-=n,a.width+=n,a.height+=n):r==="sw"?(a.x+=n,a.width-=n,a.height-=n):r==="s"?a.height-=n:r==="se"&&(a.width-=n,a.height-=n):t==="ArrowDown"&&(r==="nw"?(a.x+=n,a.y+=n,a.width-=n,a.height-=n):r==="n"?(a.y+=n,a.height-=n):r==="ne"?(a.y+=n,a.width-=n,a.height-=n):r==="sw"?(a.x-=n,a.width+=n,a.height+=n):r==="s"?a.height+=n:r==="se"&&(a.width+=n,a.height+=n)),a}var Y7={capture:!0,passive:!1},j8s=0,fg,N8s=(fg=class extends k.PureComponent{constructor(){super(...arguments);ur(this,"docMoveBound",!1);ur(this,"mouseDownOnCrop",!1);ur(this,"dragStarted",!1);ur(this,"evData",{startClientX:0,startClientY:0,startCropX:0,startCropY:0,clientX:0,clientY:0,isResize:!0});ur(this,"componentRef",k.createRef());ur(this,"mediaRef",k.createRef());ur(this,"resizeObserver");ur(this,"initChangeCalled",!1);ur(this,"instanceId",`rc-${j8s++}`);ur(this,"state",{cropIsActive:!1,newCropIsBeingDrawn:!1});ur(this,"onCropPointerDown",n=>{let{crop:r,disabled:a}=this.props,i=this.getBox();if(!r)return;let l=AS(r,i.width,i.height);if(a)return;n.cancelable&&n.preventDefault(),this.bindDocMove(),this.componentRef.current.focus({preventScroll:!0});let o=n.target.dataset.ord,c=!!o,d=n.clientX,u=n.clientY,h=l.x,m=l.y;if(o){let p=n.clientX-i.x,g=n.clientY-i.y,x=0,y=0;o==="ne"||o=="e"?(x=p-(l.x+l.width),y=g-l.y,h=l.x,m=l.y+l.height):o==="se"||o==="s"?(x=p-(l.x+l.width),y=g-(l.y+l.height),h=l.x,m=l.y):o==="sw"||o=="w"?(x=p-l.x,y=g-(l.y+l.height),h=l.x+l.width,m=l.y):(o==="nw"||o=="n")&&(x=p-l.x,y=g-l.y,h=l.x+l.width,m=l.y+l.height),d=h+i.x+x,u=m+i.y+y}this.evData={startClientX:d,startClientY:u,startCropX:h,startCropY:m,clientX:n.clientX,clientY:n.clientY,isResize:c,ord:o},this.mouseDownOnCrop=!0,this.setState({cropIsActive:!0})});ur(this,"onComponentPointerDown",n=>{let{crop:r,disabled:a,locked:i,keepSelection:l,onChange:o}=this.props,c=this.getBox();if(a||i||l&&r)return;n.cancelable&&n.preventDefault(),this.bindDocMove(),this.componentRef.current.focus({preventScroll:!0});let d=n.clientX-c.x,u=n.clientY-c.y,h={unit:"px",x:d,y:u,width:0,height:0};this.evData={startClientX:n.clientX,startClientY:n.clientY,startCropX:d,startCropY:u,clientX:n.clientX,clientY:n.clientY,isResize:!0},this.mouseDownOnCrop=!0,o(AS(h,c.width,c.height),yE(h,c.width,c.height)),this.setState({cropIsActive:!0,newCropIsBeingDrawn:!0})});ur(this,"onDocPointerMove",n=>{let{crop:r,disabled:a,onChange:i,onDragStart:l}=this.props,o=this.getBox();if(a||!r||!this.mouseDownOnCrop)return;n.cancelable&&n.preventDefault(),this.dragStarted||(this.dragStarted=!0,l&&l(n));let{evData:c}=this;c.clientX=n.clientX,c.clientY=n.clientY;let d;d=c.isResize?this.resizeCrop():this.dragCrop(),Sut(r,d)||i(AS(d,o.width,o.height),yE(d,o.width,o.height))});ur(this,"onComponentKeyDown",n=>{let{crop:r,disabled:a,onChange:i,onComplete:l}=this.props;if(a)return;let o=n.key,c=!1;if(!r)return;let d=this.getBox(),u=this.makePixelCrop(d),h=(navigator.platform.match("Mac")?n.metaKey:n.ctrlKey)?fg.nudgeStepLarge:n.shiftKey?fg.nudgeStepMedium:fg.nudgeStep;if(o==="ArrowLeft"?(u.x-=h,c=!0):o==="ArrowRight"?(u.x+=h,c=!0):o==="ArrowUp"?(u.y-=h,c=!0):o==="ArrowDown"&&(u.y+=h,c=!0),c){n.cancelable&&n.preventDefault(),u.x=K7(u.x,0,d.width-u.width),u.y=K7(u.y,0,d.height-u.height);let m=AS(u,d.width,d.height),p=yE(u,d.width,d.height);i(m,p),l&&l(m,p)}});ur(this,"onHandlerKeyDown",(n,r)=>{let{aspect:a=0,crop:i,disabled:l,minWidth:o=0,minHeight:c=0,maxWidth:d,maxHeight:u,onChange:h,onComplete:m}=this.props,p=this.getBox();if(l||!i)return;if(n.key==="ArrowUp"||n.key==="ArrowDown"||n.key==="ArrowLeft"||n.key==="ArrowRight")n.stopPropagation(),n.preventDefault();else return;let g=(navigator.platform.match("Mac")?n.metaKey:n.ctrlKey)?fg.nudgeStepLarge:n.shiftKey?fg.nudgeStepMedium:fg.nudgeStep,x=Cut(w8s(AS(i,p.width,p.height),n.key,g,r),a,r,p.width,p.height,o,c,d,u);if(!Sut(i,x)){let y=yE(x,p.width,p.height);h(x,y),m&&m(x,y)}});ur(this,"onDocPointerDone",n=>{let{crop:r,disabled:a,onComplete:i,onDragEnd:l}=this.props,o=this.getBox();this.unbindDocMove(),!(a||!r)&&this.mouseDownOnCrop&&(this.mouseDownOnCrop=!1,this.dragStarted=!1,l&&l(n),i&&i(AS(r,o.width,o.height),yE(r,o.width,o.height)),this.setState({cropIsActive:!1,newCropIsBeingDrawn:!1}))});ur(this,"onDragFocus",()=>{var n;(n=this.componentRef.current)==null||n.scrollTo(0,0)})}get document(){return document}getBox(){let n=this.mediaRef.current;if(!n)return{x:0,y:0,width:0,height:0};let{x:r,y:a,width:i,height:l}=n.getBoundingClientRect();return{x:r,y:a,width:i,height:l}}componentDidUpdate(n){let{crop:r,onComplete:a}=this.props;if(a&&!n.crop&&r){let{width:i,height:l}=this.getBox();i&&l&&a(AS(r,i,l),yE(r,i,l))}}componentWillUnmount(){this.resizeObserver&&this.resizeObserver.disconnect(),this.unbindDocMove()}bindDocMove(){this.docMoveBound||(this.docMoveBound=(this.document.addEventListener("pointermove",this.onDocPointerMove,Y7),this.document.addEventListener("pointerup",this.onDocPointerDone,Y7),this.document.addEventListener("pointercancel",this.onDocPointerDone,Y7),!0))}unbindDocMove(){this.docMoveBound&&(this.docMoveBound=(this.document.removeEventListener("pointermove",this.onDocPointerMove,Y7),this.document.removeEventListener("pointerup",this.onDocPointerDone,Y7),this.document.removeEventListener("pointercancel",this.onDocPointerDone,Y7),!1))}getCropStyle(){let{crop:n}=this.props;if(n)return{top:`${n.y}${n.unit}`,left:`${n.x}${n.unit}`,width:`${n.width}${n.unit}`,height:`${n.height}${n.unit}`}}dragCrop(){let{evData:n}=this,r=this.getBox(),a=this.makePixelCrop(r),i=n.clientX-n.startClientX,l=n.clientY-n.startClientY;return a.x=K7(n.startCropX+i,0,r.width-a.width),a.y=K7(n.startCropY+l,0,r.height-a.height),a}getPointRegion(n,r,a,i){let{evData:l}=this,o=l.clientX-n.x,c=l.clientY-n.y,d;d=i&&r?r==="nw"||r==="n"||r==="ne":c1?l?[l,l/r]:[o*r,o]:o?[o*r,o]:[l,l/r]}resizeCrop(){let{evData:n}=this,{aspect:r=0,maxWidth:a,maxHeight:i}=this.props,l=this.getBox(),[o,c]=this.resolveMinDimensions(l,r,this.props.minWidth,this.props.minHeight),d=this.makePixelCrop(l),u=this.getPointRegion(l,n.ord,o,c),h=n.ord||u,m=n.clientX-n.startClientX,p=n.clientY-n.startClientY;(o&&h==="nw"||h==="w"||h==="sw")&&(m=Math.min(m,-o)),(c&&h==="nw"||h==="n"||h==="ne")&&(p=Math.min(p,-c));let g={unit:"px",x:0,y:0,width:0,height:0};u==="ne"?(g.x=n.startCropX,g.width=m,r?(g.height=g.width/r,g.y=n.startCropY-g.height):(g.height=Math.abs(p),g.y=n.startCropY-g.height)):u==="se"?(g.x=n.startCropX,g.y=n.startCropY,g.width=m,r?g.height=g.width/r:g.height=p):u==="sw"?(g.x=n.startCropX+m,g.y=n.startCropY,g.width=Math.abs(m),r?g.height=g.width/r:g.height=p):u==="nw"&&(g.x=n.startCropX+m,g.width=Math.abs(m),r?(g.height=g.width/r,g.y=n.startCropY-g.height):(g.height=Math.abs(p),g.y=n.startCropY+p));let x=Cut(g,r,u,l.width,l.height,o,c,a,i);return r||fg.xyOrds.indexOf(h)>-1?d=x:fg.xOrds.indexOf(h)>-1?(d.x=x.x,d.width=x.width):fg.yOrds.indexOf(h)>-1&&(d.y=x.y,d.height=x.height),d.x=K7(d.x,0,l.width-d.width),d.y=K7(d.y,0,l.height-d.height),d}renderCropSelection(){let{ariaLabels:n=fg.defaultProps.ariaLabels,disabled:r,locked:a,renderSelectionAddon:i,ruleOfThirds:l,crop:o}=this.props,c=this.getCropStyle();if(o)return zt.createElement("div",{style:c,className:"ReactCrop__crop-selection",onPointerDown:this.onCropPointerDown,"aria-label":n.cropArea,tabIndex:0,onKeyDown:this.onComponentKeyDown,role:"group"},!r&&!a&&zt.createElement("div",{className:"ReactCrop__drag-elements",onFocus:this.onDragFocus},zt.createElement("div",{className:"ReactCrop__drag-bar ord-n","data-ord":"n"}),zt.createElement("div",{className:"ReactCrop__drag-bar ord-e","data-ord":"e"}),zt.createElement("div",{className:"ReactCrop__drag-bar ord-s","data-ord":"s"}),zt.createElement("div",{className:"ReactCrop__drag-bar ord-w","data-ord":"w"}),zt.createElement("div",{className:"ReactCrop__drag-handle ord-nw","data-ord":"nw",tabIndex:0,"aria-label":n.nwDragHandle,onKeyDown:d=>this.onHandlerKeyDown(d,"nw"),role:"button"}),zt.createElement("div",{className:"ReactCrop__drag-handle ord-n","data-ord":"n",tabIndex:0,"aria-label":n.nDragHandle,onKeyDown:d=>this.onHandlerKeyDown(d,"n"),role:"button"}),zt.createElement("div",{className:"ReactCrop__drag-handle ord-ne","data-ord":"ne",tabIndex:0,"aria-label":n.neDragHandle,onKeyDown:d=>this.onHandlerKeyDown(d,"ne"),role:"button"}),zt.createElement("div",{className:"ReactCrop__drag-handle ord-e","data-ord":"e",tabIndex:0,"aria-label":n.eDragHandle,onKeyDown:d=>this.onHandlerKeyDown(d,"e"),role:"button"}),zt.createElement("div",{className:"ReactCrop__drag-handle ord-se","data-ord":"se",tabIndex:0,"aria-label":n.seDragHandle,onKeyDown:d=>this.onHandlerKeyDown(d,"se"),role:"button"}),zt.createElement("div",{className:"ReactCrop__drag-handle ord-s","data-ord":"s",tabIndex:0,"aria-label":n.sDragHandle,onKeyDown:d=>this.onHandlerKeyDown(d,"s"),role:"button"}),zt.createElement("div",{className:"ReactCrop__drag-handle ord-sw","data-ord":"sw",tabIndex:0,"aria-label":n.swDragHandle,onKeyDown:d=>this.onHandlerKeyDown(d,"sw"),role:"button"}),zt.createElement("div",{className:"ReactCrop__drag-handle ord-w","data-ord":"w",tabIndex:0,"aria-label":n.wDragHandle,onKeyDown:d=>this.onHandlerKeyDown(d,"w"),role:"button"})),i&&zt.createElement("div",{className:"ReactCrop__selection-addon",onPointerDown:d=>d.stopPropagation()},i(this.state)),l&&zt.createElement(zt.Fragment,null,zt.createElement("div",{className:"ReactCrop__rule-of-thirds-hz"}),zt.createElement("div",{className:"ReactCrop__rule-of-thirds-vt"})))}makePixelCrop(n){return AS({...fKe,...this.props.crop||{}},n.width,n.height)}render(){let{aspect:n,children:r,circularCrop:a,className:i,crop:l,disabled:o,locked:c,style:d,ruleOfThirds:u}=this.props,{cropIsActive:h,newCropIsBeingDrawn:m}=this.state,p=l?this.renderCropSelection():null,g=v8s("ReactCrop",i,h&&"ReactCrop--active",o&&"ReactCrop--disabled",c&&"ReactCrop--locked",m&&"ReactCrop--new-crop",l&&n&&"ReactCrop--fixed-aspect",l&&a&&"ReactCrop--circular-crop",l&&u&&"ReactCrop--rule-of-thirds",!this.dragStarted&&l&&!l.width&&!l.height&&"ReactCrop--invisible-crop",a&&"ReactCrop--no-animate");return zt.createElement("div",{ref:this.componentRef,className:g,style:d},zt.createElement("div",{ref:this.mediaRef,className:"ReactCrop__child-wrapper",onPointerDown:this.onComponentPointerDown},r),l?zt.createElement("svg",{className:"ReactCrop__crop-mask",width:"100%",height:"100%"},zt.createElement("defs",null,zt.createElement("mask",{id:`hole-${this.instanceId}`},zt.createElement("rect",{width:"100%",height:"100%",fill:"white"}),a?zt.createElement("ellipse",{cx:`${l.x+l.width/2}${l.unit}`,cy:`${l.y+l.height/2}${l.unit}`,rx:`${l.width/2}${l.unit}`,ry:`${l.height/2}${l.unit}`,fill:"black"}):zt.createElement("rect",{x:`${l.x}${l.unit}`,y:`${l.y}${l.unit}`,width:`${l.width}${l.unit}`,height:`${l.height}${l.unit}`,fill:"black"}))),zt.createElement("rect",{fill:"black",fillOpacity:.5,width:"100%",height:"100%",mask:`url(#hole-${this.instanceId})`})):void 0,p)}},ur(fg,"xOrds",["e","w"]),ur(fg,"yOrds",["n","s"]),ur(fg,"xyOrds",["nw","ne","se","sw"]),ur(fg,"nudgeStep",1),ur(fg,"nudgeStepMedium",10),ur(fg,"nudgeStepLarge",100),ur(fg,"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"}}),fg);function k8s(s,t,n){return _8s(b8s({unit:"%",width:90},n,s,t),s,t)}const pKe=({open:s,onClose:t,imageSrc:n,onCropComplete:r,aspectRatio:a=1})=>{const i=k.useRef(null),[l,o]=k.useState(),[c,d]=k.useState(),[u,h]=k.useState(1),[m,p]=k.useState(0),g=k.useCallback(v=>{const{width:_,height:j}=v.currentTarget;o(k8s(_,j,a))},[a]),x=k.useCallback(async()=>{const v=i.current;if(!v||!c)return;const _=document.createElement("canvas"),j=_.getContext("2d");if(!j)return;const C=v.naturalWidth/v.width,A=v.naturalHeight/v.height,M=400;_.width=M,_.height=M,j.imageSmoothingQuality="high";const I=c.x*C,P=c.y*A,R=c.width*C,O=c.height*A,B=m*Math.PI/180,U=_.width/2,G=_.height/2;return j.save(),j.translate(U,G),j.rotate(B),j.scale(u,u),j.translate(-U,-G),j.drawImage(v,I,P,R,O,0,0,M,M),j.restore(),new Promise((H,Y)=>{_.toBlob(se=>{se?H(se):Y(new Error("Canvas is empty"))},"image/jpeg",.95)})},[c,u,m]),y=async()=>{try{const v=await x();v&&(r(v),t())}catch(v){console.error("Error cropping image:",v)}};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"max-w-lg",children:[e.jsx(Vs,{children:e.jsx($s,{children:"Crop Your Photo"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"relative max-h-[400px] overflow-hidden rounded-lg bg-muted flex items-center justify-center",children:e.jsx(N8s,{crop:l,onChange:(v,_)=>o(_),onComplete:v=>d(v),aspect:a,circularCrop:!0,className:"max-h-[400px]",children:e.jsx("img",{ref:i,src:n,alt:"Crop preview",style:{transform:`scale(${u}) rotate(${m}deg)`,maxHeight:"400px",width:"auto"},onLoad:g})})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(yB,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(sx,{value:[u],min:.5,max:3,step:.1,onValueChange:([v])=>h(v),className:"flex-1"}),e.jsx(aM,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(W8,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(sx,{value:[m],min:-180,max:180,step:1,onValueChange:([v])=>p(v),className:"flex-1"}),e.jsxs("span",{className:"text-sm text-muted-foreground w-12",children:[m,"°"]})]})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:t,children:"Cancel"}),e.jsx($,{onClick:y,children:"Save Photo"})]})]})})},Aut="I agree to receive recurring SMS/MMS text messages from LevelUp, including new lead alerts, account notifications, service updates, and customer support. Message frequency varies. Message and data rates may apply. Reply STOP to opt out and HELP for help. Consent is not a condition of purchase.";function S8s(s){const t=s.replace(/\D/g,"");return s.trim().startsWith("+")?t.length>=8?`+${t}`:null:t.length===10?`+1${t}`:t.length===11&&t.startsWith("1")?`+${t}`:null}function C8s(){const{user:s}=ks(),{toast:t}=Fi(),[n,r]=k.useState(!0),[a,i]=k.useState(!1),[l,o]=k.useState(""),[c,d]=k.useState(!1),[u,h]=k.useState(!1),[m,p]=k.useState(null),[g,x]=k.useState(!1);k.useEffect(()=>{s!=null&&s.id&&(async()=>{const{data:_}=await V.from("profiles").select("phone, phone_e164, sms_consent, sms_consent_at").eq("id",s.id).maybeSingle(),j=_;j&&(o(j.phone_e164||j.phone||""),h(!!j.sms_consent),d(!!j.sms_consent),p(j.sms_consent_at||null)),r(!1)})()},[s==null?void 0:s.id]);const y=async()=>{const _=S8s(l);if(!_){t({title:"Invalid number",description:"Enter a valid mobile number, e.g. (555) 123-4567.",variant:"destructive"});return}if(!c){t({title:"Consent required",description:"Please check the consent box to opt in to text messages.",variant:"destructive"});return}i(!0);const{error:j}=await V.from("profiles").update({phone_e164:_,sms_consent:!0,sms_consent_at:new Date().toISOString(),sms_consent_text:Aut,sms_consent_source:"profile_page",sms_opted_out_at:null}).eq("id",s.id);if(i(!1),j){t({title:"Error",description:j.message,variant:"destructive"});return}h(!0),p(new Date().toISOString()),t({title:"You're opted in",description:"You'll now receive text alerts for new leads and account notifications."})},v=async()=>{i(!0);const{error:_}=await V.from("profiles").update({sms_consent:!1,sms_opted_out_at:new Date().toISOString()}).eq("id",s.id);if(i(!1),_){t({title:"Error",description:_.message,variant:"destructive"});return}h(!1),d(!1),t({title:"Opted out",description:"You will no longer receive text messages from LevelUp."})};return e.jsxs(we,{children:[e.jsxs(Vt,{children:[e.jsxs(Yt,{className:"flex items-center gap-2",children:[e.jsx(bo,{className:"h-5 w-5"}),"Text Message (SMS) Alerts",u&&e.jsx(qe,{variant:"secondary",children:"Opted in"})]}),e.jsx(vr,{children:"Get a text the moment a new lead comes in, plus important account notifications."})]}),e.jsx(De,{className:"space-y-4",children:n?e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(Jt,{className:"h-4 w-4 animate-spin"})," Loading…"]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"rounded-lg border border-primary/30 bg-primary/5 p-3",children:e.jsx("p",{className:"text-sm font-medium",children:"SMS is completely optional. It is not required to create an account, save your profile, purchase, access, or use LevelUp. You may leave this blank or decline."})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"sms-mobile",children:"Mobile Number (optional)"}),e.jsx(be,{id:"sms-mobile",type:"tel",value:l,onChange:_=>o(_.target.value),placeholder:"(555) 123-4567",maxLength:30,autoComplete:"tel"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Only needed if you choose to opt in. Must be a mobile number that can receive text messages."})]}),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(Li,{id:"sms-consent",checked:c,onCheckedChange:_=>d(_===!0),disabled:u,className:"mt-0.5"}),e.jsx(re,{htmlFor:"sms-consent",className:"text-sm font-normal leading-relaxed cursor-pointer",children:Aut})]})}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Message types: new lead alerts, account notifications, service updates, customer support. Frequency varies. Msg & data rates may apply. Reply STOP to opt out, HELP for help. No mobile information will be shared with third parties or affiliates for marketing purposes."}),u&&m&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Consent recorded on ",new Date(m).toLocaleString("en-US",{timeZone:"America/New_York"}),"."]}),g&&!u&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"You chose not to enroll in text alerts. Nothing was saved and your account is unaffected."}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs($,{onClick:y,disabled:a||u&&!l,children:[a&&e.jsx(Jt,{className:"mr-2 h-4 w-4 animate-spin"}),u?"Update Number":"Opt in to SMS"]}),u?e.jsx($,{variant:"outline",onClick:v,disabled:a,children:"Opt out"}):e.jsx($,{variant:"outline",type:"button",disabled:a,onClick:()=>{o(""),d(!1),x(!0),t({title:"SMS skipped",description:"No consent was recorded. You can keep using LevelUp normally."})},children:"Skip SMS / Continue without text alerts"})]})]})})]})}const Eut="#2a4c64",Tut="#B8965A",Mut="Inter",Put="Inter";function F9(s){if(typeof s!="string")return null;const t=s.trim();return t.length?t:null}function Gb(s,t=null){for(const[n,r]of s){const a=F9(r);if(a)return{value:a,source:n}}return{value:t,source:"default"}}function A8s(s){const t=s.agent??{},n=s.brokerage??{},r=s.legacy??{},a=!!n.lock_colors,i=!!n.lock_logo,l=(M,I,P)=>a?[["brokerage",I],["agent",M],["legacy",P]]:[["agent",M],["brokerage",I],["legacy",P]],o=Gb(l(t.brand_color,n.primary_color,r.brand_color),Eut),c=Gb(l(t.accent_color,n.accent_color,r.accent_color),Tut),d=Gb([["brokerage",n.secondary_color]]),u=i?[["brokerage",n.logo_url],["agent",t.logo_url],["legacy",r.brokerage_logo_url||r.team_logo_url]]:[["agent",t.logo_url],["legacy",r.team_logo_url],["brokerage",n.logo_url],["legacy",r.brokerage_logo_url]],h=Gb(u),m=Gb([["brokerage",n.logo_url],["legacy",r.brokerage_logo_url]]),p=Gb([["agent",t.headshot_url],["legacy",r.avatar_url]]),g=Gb([["agent",t.tagline],["legacy",r.tagline||r.title]]),x=Gb([["agent",t.preferred_font],["brokerage",n.heading_font]],Mut),y=Gb([["brokerage",n.body_font]],Put),v=Gb([["agent",t.license_number],["legacy",r.license_number]]),_=Gb([["agent",t.license_state],["legacy",r.license_state],["brokerage",n.license_state]]),j=Gb([["agent",t.website_url],["legacy",r.website_url]]),C=Gb([["brokerage",n.legal_name],["legacy",r.brokerage_name]]),A=Gb([["brokerage",n.compliance_line]]);return{agent_name:F9(r.name),brokerage_name:C.value,brand_color:o.value??Eut,secondary_color:d.value,accent_color:c.value??Tut,heading_font:x.value??Mut,body_font:y.value??Put,logo_url:h.value,logo_dark_url:F9(n.logo_dark_url),brokerage_logo_url:m.value,icon_mark_url:F9(n.icon_mark_url),headshot_url:p.value,tagline:g.value,license_number:v.value,license_state:_.value,website_url:j.value,email:F9(r.email),phone:F9(r.phone),compliance_line:A.value,show_equal_housing:!!n.show_equal_housing,show_realtor_logo:!!n.show_realtor_logo,locked:{colors:a,logo:i},sources:{brand_color:o.source,accent_color:c.source,secondary_color:d.source,logo_url:h.source,brokerage_logo_url:m.source,headshot_url:p.source,tagline:g.source,heading_font:x.source,body_font:y.source,license_number:v.source,license_state:_.source,website_url:j.source,brokerage_name:C.source,compliance_line:A.source}}}function E8s(){const{user:s}=ks();return pt({queryKey:["agent-brand-profile",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await V.from("agent_brand_profiles").select("*").eq("user_id",s.id).maybeSingle();if(n)throw n;return t??null}})}function T8s(){const{user:s}=ks(),t=ls();return Nt({mutationFn:async n=>{if(!s)throw new Error("Not signed in");const{data:r,error:a}=await V.from("agent_brand_profiles").upsert({user_id:s.id,...n},{onConflict:"user_id"}).select().single();if(a)throw a;return r},onSuccess:()=>{t.invalidateQueries({queryKey:["agent-brand-profile",s==null?void 0:s.id]}),t.invalidateQueries({queryKey:["brand-kit",s==null?void 0:s.id]})}})}function M8s(s){return pt({queryKey:["brokerage-brand-profile",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await V.from("brokerage_brand_profiles").select("*").eq("brokerage_id",s).maybeSingle();if(n)throw n;return t??null}})}function P8s(s){const{user:t}=ks(),n=ls();return Nt({mutationFn:async r=>{if(!s)throw new Error("No brokerage selected");const{data:a,error:i}=await V.from("brokerage_brand_profiles").upsert({brokerage_id:s,updated_by:(t==null?void 0:t.id)??null,...r},{onConflict:"brokerage_id"}).select().single();if(i)throw i;return a},onSuccess:()=>{n.invalidateQueries({queryKey:["brokerage-brand-profile",s]}),n.invalidateQueries({queryKey:["brand-kit"]})}})}function I8s(){const{user:s}=ks();return pt({queryKey:["brand-kit",s==null?void 0:s.id],enabled:!!s,staleTime:6e4,queryFn:async()=>{var m;const t=s.id,[n,r,a,i]=await Promise.all([V.from("profiles").select("name, email, phone, avatar_url, website_url, title, brokerage_name, brokerage_id").eq("id",t).maybeSingle(),V.from("agent_brand_profiles").select("*").eq("user_id",t).maybeSingle(),V.from("agent_cards").select("brokerage_display_name, brokerage_logo_url, team_logo_url, display_email, title, positioning_statement").eq("user_id",t).maybeSingle(),V.from("lead_sites").select("brand_color, accent_color, agent_license_number, license_state, brokerage_legal_name, team_logo_url, is_active, created_at").eq("agent_id",t).order("created_at",{ascending:!0}).limit(5)]),l=n.data??{},o=a.data??{},c=i.data??[],d=c.find(p=>p.is_active)??c[0]??{};let u=null,h=null;if(l.brokerage_id){const[p,g]=await Promise.all([V.from("brokerage_brand_profiles").select("*").eq("brokerage_id",l.brokerage_id).maybeSingle(),V.from("brokerages").select("name").eq("id",l.brokerage_id).maybeSingle()]);u=p.data??null,h=((m=g.data)==null?void 0:m.name)??null}return A8s({agent:r.data??null,brokerage:u,legacy:{name:l.name??null,email:o.display_email||l.email||s.email||null,phone:l.phone??null,avatar_url:l.avatar_url??null,website_url:l.website_url??null,title:l.title??null,brokerage_name:l.brokerage_name||o.brokerage_display_name||d.brokerage_legal_name||h,brokerage_logo_url:o.brokerage_logo_url??null,team_logo_url:o.team_logo_url||d.team_logo_url||null,brand_color:d.brand_color??null,accent_color:d.accent_color??null,license_number:d.agent_license_number??null,license_state:d.license_state??null,tagline:o.positioning_statement??null}})}})}async function xIt(s,t,n){var l;const r=((l=t.name.split(".").pop())==null?void 0:l.toLowerCase())||"png",a=`${s}/brand-${n}-${Date.now()}.${r}`,{error:i}=await V.storage.from("card-logos").upload(a,t,{upsert:!0,cacheControl:"3600"});if(i)throw i;return V.storage.from("card-logos").getPublicUrl(a).data.publicUrl}const L8s=["Inter","Playfair Display","Montserrat","Poppins","Lora","Work Sans"];function R8s(){const{user:s}=ks(),{toast:t}=Fi(),{data:n,isLoading:r}=E8s(),{data:a}=I8s(),i=T8s(),l=k.useRef(null),[o,c]=k.useState(!1),[d,u]=k.useState({brand_color:"",accent_color:"",logo_url:"",tagline:"",preferred_font:"",license_number:"",license_state:"",website_url:""});k.useEffect(()=>{n&&u({brand_color:n.brand_color||"",accent_color:n.accent_color||"",logo_url:n.logo_url||"",tagline:n.tagline||"",preferred_font:n.preferred_font||"",license_number:n.license_number||"",license_state:n.license_state||"",website_url:n.website_url||""})},[n]);const h=!!(a!=null&&a.locked.colors),m=!!(a!=null&&a.locked.logo),p=(y,v)=>u(_=>({..._,[y]:v})),g=async y=>{if(s){c(!0);try{const v=await xIt(s.id,y,"logo");p("logo_url",v),t({title:"Logo uploaded"})}catch(v){t({title:"Upload failed",description:v.message,variant:"destructive"})}finally{c(!1)}}},x=async()=>{try{await i.mutateAsync({brand_color:d.brand_color||null,accent_color:d.accent_color||null,logo_url:d.logo_url||null,tagline:d.tagline||null,preferred_font:d.preferred_font||null,license_number:d.license_number||null,license_state:d.license_state||null,website_url:d.website_url||null}),t({title:"Brand kit saved"})}catch(y){t({title:"Could not save",description:y.message,variant:"destructive"})}};return e.jsxs(we,{children:[e.jsxs(Vt,{children:[e.jsxs(Yt,{className:"flex items-center gap-2",children:[e.jsx(gd,{className:"h-5 w-5"}),"Brand Kit"]}),e.jsx(vr,{children:"Used by AI tools (ChatGPT via the LevelUp connector), flyers, presentations and your public pages. Anything you leave blank falls back to your brokerage's brand, then LevelUp defaults."})]}),e.jsx(De,{className:"space-y-6",children:r?e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground text-sm",children:[e.jsx(Jt,{className:"h-4 w-4 animate-spin"})," Loading…"]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(re,{className:"flex items-center gap-2",children:["Brand color",h&&e.jsxs(qe,{variant:"secondary",className:"gap-1",children:[e.jsx(fu,{className:"h-3 w-3"})," Set by brokerage"]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(be,{type:"color",className:"h-10 w-14 p-1",value:d.brand_color||(a==null?void 0:a.brand_color)||"#2a4c64",disabled:h,onChange:y=>p("brand_color",y.target.value)}),e.jsx(be,{value:d.brand_color,placeholder:(a==null?void 0:a.brand_color)||"#2a4c64",disabled:h,onChange:y=>p("brand_color",y.target.value)})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Accent color"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(be,{type:"color",className:"h-10 w-14 p-1",value:d.accent_color||(a==null?void 0:a.accent_color)||"#B8965A",disabled:h,onChange:y=>p("accent_color",y.target.value)}),e.jsx(be,{value:d.accent_color,placeholder:(a==null?void 0:a.accent_color)||"#B8965A",disabled:h,onChange:y=>p("accent_color",y.target.value)})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(re,{className:"flex items-center gap-2",children:["Personal / team logo",m&&e.jsxs(qe,{variant:"secondary",className:"gap-1",children:[e.jsx(fu,{className:"h-3 w-3"})," Brokerage logo required"]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[d.logo_url&&e.jsx("img",{src:d.logo_url,alt:"Your logo",className:"h-12 w-auto rounded border bg-background p-1"}),e.jsx("input",{ref:l,type:"file",accept:"image/*",className:"hidden",onChange:y=>{var v;return((v=y.target.files)==null?void 0:v[0])&&g(y.target.files[0])}}),e.jsxs($,{type:"button",variant:"outline",disabled:o||m,onClick:()=>{var y;return(y=l.current)==null?void 0:y.click()},children:[o?e.jsx(Jt,{className:"h-4 w-4 animate-spin"}):e.jsx(gi,{className:"h-4 w-4"}),e.jsx("span",{className:"ml-2",children:"Upload logo"})]}),d.logo_url&&e.jsx($,{type:"button",variant:"ghost",onClick:()=>p("logo_url",""),disabled:m,children:"Remove"})]})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"brand-tagline",children:"Tagline"}),e.jsx(be,{id:"brand-tagline",value:d.tagline,placeholder:(a==null?void 0:a.tagline)||"Your positioning statement",onChange:y=>p("tagline",y.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"brand-font",children:"Preferred font"}),e.jsx(be,{id:"brand-font",list:"brand-font-options",value:d.preferred_font,placeholder:(a==null?void 0:a.heading_font)||"Inter",onChange:y=>p("preferred_font",y.target.value)}),e.jsx("datalist",{id:"brand-font-options",children:L8s.map(y=>e.jsx("option",{value:y},y))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"brand-license",children:"License number"}),e.jsx(be,{id:"brand-license",value:d.license_number,placeholder:(a==null?void 0:a.license_number)||"DRE #01234567",onChange:y=>p("license_number",y.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"brand-license-state",children:"License state"}),e.jsx(be,{id:"brand-license-state",value:d.license_state,placeholder:(a==null?void 0:a.license_state)||"CA",onChange:y=>p("license_state",y.target.value)})]}),e.jsxs("div",{className:"space-y-2 sm:col-span-2",children:[e.jsx(re,{htmlFor:"brand-website",children:"Website"}),e.jsx(be,{id:"brand-website",value:d.website_url,placeholder:(a==null?void 0:a.website_url)||"https://yoursite.com",onChange:y=>p("website_url",y.target.value)})]})]}),(a==null?void 0:a.compliance_line)&&e.jsxs("div",{className:"rounded-md border bg-muted/40 p-3 text-sm text-muted-foreground",children:[e.jsx("span",{className:"font-medium text-foreground",children:"Required disclaimer from your brokerage: "}),a.compliance_line]}),e.jsxs($,{onClick:x,disabled:i.isPending,children:[i.isPending?e.jsx(Jt,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(Ml,{className:"mr-2 h-4 w-4"}),"Save brand kit"]})]})})]})}const D8s=()=>{const{user:s}=ks(),{toast:t}=Fi(),[n,r]=k.useState(!1),[a,i]=k.useState(!1),[l,o]=k.useState(null);k.useEffect(()=>{s&&c()},[s]);const c=async()=>{r(!0);try{const{data:h}=await V.from("profiles").select("subscription_status, subscription_product_id, subscription_end_date, is_grandfathered").eq("id",s==null?void 0:s.id).single();h&&o({status:h.subscription_status||"none",productId:h.subscription_product_id,endDate:h.subscription_end_date,isGrandfathered:h.is_grandfathered||!1})}catch(h){console.error("Error loading subscription:",h)}finally{r(!1)}},d=async()=>{i(!0);try{const{data:{session:h}}=await V.auth.getSession();if(!h)throw new Error("Not authenticated");const{data:m,error:p}=await V.functions.invoke("customer-portal",{headers:{Authorization:`Bearer ${h.access_token}`}});if(p)throw p;m!=null&&m.url&&window.open(m.url,"_blank")}catch(h){console.error("Error opening customer portal:",h),t({title:"Error",description:h.message||"Failed to open billing portal",variant:"destructive"})}finally{i(!1)}},u=()=>{if(l!=null&&l.isGrandfathered)return e.jsx(qe,{className:"bg-amber-500",children:"Grandfathered"});switch(l==null?void 0:l.status){case"active":return e.jsx(qe,{className:"bg-green-500",children:"Active"});case"trialing":return e.jsx(qe,{className:"bg-blue-500",children:"Trial"});case"past_due":return e.jsx(qe,{variant:"destructive",children:"Past Due"});case"canceled":return e.jsx(qe,{variant:"secondary",children:"Canceled"});default:return e.jsx(qe,{variant:"outline",children:"No Subscription"})}};return n?e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsxs(Yt,{className:"flex items-center gap-2",children:[e.jsx(cv,{className:"h-5 w-5"}),"Subscription"]})}),e.jsx(De,{children:e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(Jt,{className:"h-6 w-6 animate-spin text-muted-foreground"})})})]}):e.jsxs(we,{children:[e.jsxs(Vt,{children:[e.jsxs(Yt,{className:"flex items-center gap-2",children:[e.jsx(cv,{className:"h-5 w-5"}),"Subscription"]}),e.jsx(vr,{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:u()})]}),(l==null?void 0:l.endDate)&&l.status==="active"&&e.jsxs("div",{className:"text-right",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Next billing date"}),e.jsx("p",{className:"font-medium",children:new Date(l.endDate).toLocaleDateString()})]})]}),l!=null&&l.isGrandfathered?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Your account was upgraded from LevelUp 1.0. To update/manage your subscription please reach out to support."}):(l==null?void 0:l.status)==="active"||(l==null?void 0:l.status)==="trialing"?e.jsxs(e.Fragment,{children:[(l==null?void 0:l.status)==="trialing"&&(l==null?void 0:l.endDate)&&e.jsxs("p",{className:"text-sm text-muted-foreground mb-3",children:["Your trial ends on ",new Date(l.endDate).toLocaleDateString(),". After the trial, you'll be charged automatically."]}),e.jsxs($,{onClick:d,variant:"outline",disabled:a,children:[a?e.jsx(Jt,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(Ir,{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."})]})]})},O8s=()=>{const{user:s}=ks(),t=Jn(),{toast:n}=Fi(),[r]=Jc(),a=r.get("setup")==="true",i=r.get("reset")==="true",{isSupported:l,isSubscribed:o,isLoading:c,subscribe:d,unsubscribe:u}=SAt(),[h,m]=k.useState(!1),[p,g]=k.useState(""),[x,y]=k.useState(!1),[v,_]=k.useState(!1),[j,C]=k.useState(""),[A,M]=k.useState({name:"",email:"",phone:"",title:"",bio:"",areas_served:"",years_experience:"",brokerage_name:"",instagram_url:"",facebook_url:"",linkedin_url:"",email_signature:"",use_email_signature:!1}),[I,P]=k.useState(!1),[R,O]=k.useState(!1),[B,U]=k.useState(!1),[G,H]=k.useState(!1),[Y,se]=k.useState(!1),[ee,oe]=k.useState({newPassword:"",confirmPassword:""});k.useEffect(()=>{s&&me()},[s]),k.useEffect(()=>{i&&s&&setTimeout(()=>{var _e;(_e=document.getElementById("change-password-section"))==null||_e.scrollIntoView({behavior:"smooth",block:"center"})},500)},[i,s]);const me=async()=>{var _e,ve,he,Se;if(!(s!=null&&s.id)){console.log("No user ID available yet");return}try{console.log("Loading profile for user:",s.id);const{data:Te,error:Ie}=await V.from("profiles").select("name, email, phone, digest_opt_out, event_invite_opt_out, title, bio, areas_served, years_experience, brokerage_id, brokerage_name, instagram_url, facebook_url, linkedin_url, email_signature, use_email_signature, brokerages(name)").eq("id",s.id).maybeSingle();if(Ie)throw console.error("Profile query error:",Ie),Ie;if(Te){console.log("Profile loaded successfully:",Te);const Be=((_e=Te.brokerages)==null?void 0:_e.name)||"";P(!!Te.brokerage_id),M({name:Te.name||"",email:Te.email||"",phone:Te.phone||"",title:Te.title||"",bio:Te.bio||"",areas_served:Te.areas_served||"",years_experience:((ve=Te.years_experience)==null?void 0:ve.toString())||"",brokerage_name:Te.brokerage_id?Be:Te.brokerage_name||"",instagram_url:Te.instagram_url||"",facebook_url:Te.facebook_url||"",linkedin_url:Te.linkedin_url||"",email_signature:Te.email_signature||"",use_email_signature:Te.use_email_signature||!1}),O(Te.digest_opt_out||!1),H(Te.event_invite_opt_out||!1)}else console.warn("No profile found for user"),M({name:((he=s.user_metadata)==null?void 0:he.name)||((Se=s.email)==null?void 0:Se.split("@")[0])||"",email:s.email||"",phone:"",title:"",bio:"",areas_served:"",years_experience:"",brokerage_name:"",instagram_url:"",facebook_url:"",linkedin_url:"",email_signature:"",use_email_signature:!1});const{data:Ue}=await V.storage.from("avatars").list(`${s.id}`);if(Ue&&Ue.length>0){const{data:Be}=V.storage.from("avatars").getPublicUrl(`${s.id}/${Ue[0].name}`);g(Be.publicUrl)}}catch(Te){console.error("Error loading profile:",Te),n({title:"Error",description:Te.message||"Failed to load profile",variant:"destructive"})}},Q=_e=>{var Se;const ve=(Se=_e.target.files)==null?void 0:Se[0];if(!ve)return;const he=new FileReader;he.onloadend=()=>{C(he.result),_(!0)},he.readAsDataURL(ve),_e.target.value=""},te=async _e=>{if(s){y(!0);try{const{data:ve}=await V.storage.from("avatars").list(`${s.id}`);ve&&ve.length>0&&await V.storage.from("avatars").remove(ve.map(Be=>`${s.id}/${Be.name}`));const Se=`${s.id}/avatar.jpg`,{error:Te}=await V.storage.from("avatars").upload(Se,_e,{upsert:!0,contentType:"image/jpeg"});if(Te)throw Te;const{data:Ie}=V.storage.from("avatars").getPublicUrl(Se),Ue=Ie.publicUrl;g(`${Ue}?t=${Date.now()}`),await V.from("profiles").update({avatar_url:Ue}).eq("id",s.id),n({title:"Success",description:"Profile photo updated successfully"})}catch(ve){console.error("Error uploading avatar:",ve),n({title:"Error",description:ve.message||"Failed to upload photo",variant:"destructive"})}finally{y(!1)}}},le=async()=>{if(!A.name.trim()||!A.email.trim()){n({title:"Error",description:"Name and email are required",variant:"destructive"});return}m(!0);try{const{error:_e}=await V.from("profiles").update({name:A.name.trim(),email:A.email.trim(),phone:A.phone.trim()||null,title:A.title.trim()||null,bio:A.bio.trim()||null,areas_served:A.areas_served.trim()||null,years_experience:A.years_experience?parseInt(A.years_experience):null,...I?{}:{brokerage_name:A.brokerage_name.trim()||null},instagram_url:A.instagram_url.trim()||null,facebook_url:A.facebook_url.trim()||null,linkedin_url:A.linkedin_url.trim()||null,email_signature:A.email_signature||"",use_email_signature:A.use_email_signature}).eq("id",s==null?void 0:s.id);if(_e)throw _e;n({title:"Success",description:"Profile updated successfully"})}catch(_e){console.error("Error updating profile:",_e),n({title:"Error",description:_e.message||"Failed to update profile",variant:"destructive"})}finally{m(!1)}},fe=async()=>{if(!ee.newPassword){n({title:"Error",description:"Please enter a new password",variant:"destructive"});return}if(ee.newPassword.length<6){n({title:"Error",description:"Password must be at least 6 characters",variant:"destructive"});return}if(ee.newPassword!==ee.confirmPassword){n({title:"Error",description:"Passwords do not match",variant:"destructive"});return}m(!0);try{const{error:_e}=await V.auth.updateUser({password:ee.newPassword});if(_e)throw _e;n({title:"Success",description:"Password updated successfully"}),oe({newPassword:"",confirmPassword:""}),a&&setTimeout(()=>t("/dashboard"),1e3)}catch(_e){console.error("Error updating password:",_e),n({title:"Error",description:_e.message||"Failed to update password",variant:"destructive"})}finally{m(!1)}};return e.jsx(Xs,{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($,{variant:"outline",onClick:()=>{var _e;(_e=document.getElementById("change-password-section"))==null||_e.scrollIntoView({behavior:"smooth",block:"center"})},className:"gap-2",children:[e.jsx(x3,{className:"h-4 w-4"}),"Change Password"]})}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs(we,{children:[e.jsxs(Vt,{children:[e.jsx(Yt,{children:"Profile Photo"}),e.jsx(vr,{children:"Upload a professional photo for your profile"})]}),e.jsxs(De,{className:"flex items-center gap-6",children:[e.jsxs(Wa,{className:"h-24 w-24",children:[e.jsx(eo,{src:p}),e.jsx(Ka,{className:"text-2xl",children:A.name.split(" ").map(_e=>_e[0]).join("").toUpperCase()||"U"})]}),e.jsxs("div",{className:"flex-1",children:[e.jsx("input",{type:"file",id:"avatar-upload",accept:"image/*",className:"hidden",onChange:Q,disabled:x}),e.jsxs($,{variant:"outline",onClick:()=>{var _e;return(_e=document.getElementById("avatar-upload"))==null?void 0:_e.click()},disabled:x,children:[e.jsx(gi,{className:"mr-2 h-4 w-4"}),x?"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(we,{children:[e.jsxs(Vt,{children:[e.jsx(Yt,{children:"Personal Information"}),e.jsx(vr,{children:"Update your profile details"})]}),e.jsxs(De,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"name",children:"Name"}),e.jsx(be,{id:"name",value:A.name,onChange:_e=>M({...A,name:_e.target.value}),maxLength:100})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"email",children:"Email"}),e.jsx(be,{id:"email",type:"email",value:A.email,onChange:_e=>M({...A,email:_e.target.value}),maxLength:255})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"phone",children:"Phone Number"}),e.jsx(be,{id:"phone",type:"tel",value:A.phone,onChange:_e=>M({...A,phone:_e.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(re,{htmlFor:"title",children:"Job Title"}),e.jsx(be,{id:"title",value:A.title,onChange:_e=>M({...A,title:_e.target.value}),placeholder:"e.g., Broker Associate, Team Lead",maxLength:100})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"bio",children:"Bio"}),e.jsx(Ls,{id:"bio",value:A.bio,onChange:_e=>M({...A,bio:_e.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(re,{htmlFor:"areas_served",children:"Areas Served"}),e.jsx(be,{id:"areas_served",value:A.areas_served,onChange:_e=>M({...A,areas_served:_e.target.value}),placeholder:"e.g., Downtown, Suburbs"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"years_experience",children:"Years Experience"}),e.jsx(be,{id:"years_experience",type:"number",min:"0",value:A.years_experience,onChange:_e=>M({...A,years_experience:_e.target.value}),placeholder:"e.g., 5"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(re,{htmlFor:"brokerage_name",children:["Brokerage ",I&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"(managed)"})]}),e.jsx(be,{id:"brokerage_name",value:A.brokerage_name,onChange:_e=>M({...A,brokerage_name:_e.target.value}),placeholder:"e.g., Keller Williams Realty",disabled:I,maxLength:150}),e.jsx("p",{className:"text-xs text-muted-foreground",children:I?"Your brokerage is managed by your office and can't be changed here.":"Used as your brokerage name across ReelFlow, branding, and email signatures."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Social Links"}),e.jsxs("div",{className:"grid grid-cols-1 gap-3",children:[e.jsx(be,{value:A.linkedin_url,onChange:_e=>M({...A,linkedin_url:_e.target.value}),placeholder:"LinkedIn URL"}),e.jsx(be,{value:A.instagram_url,onChange:_e=>M({...A,instagram_url:_e.target.value}),placeholder:"Instagram URL"}),e.jsx(be,{value:A.facebook_url,onChange:_e=>M({...A,facebook_url:_e.target.value}),placeholder:"Facebook URL"})]})]}),e.jsxs($,{onClick:le,disabled:h,children:[e.jsx(Ml,{className:"mr-2 h-4 w-4"}),"Save Changes"]})]})]}),e.jsxs(we,{children:[e.jsxs(Vt,{children:[e.jsxs(Yt,{className:"flex items-center gap-2",children:[e.jsx(WN,{className:"h-5 w-5"}),"Email Signature"]}),e.jsx(vr,{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:A.use_email_signature?"Your signature will be added to every email sent via Gmail":"Signature is currently disabled"})]}),e.jsx(On,{checked:A.use_email_signature,onCheckedChange:_e=>M({...A,use_email_signature:_e})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Signature"}),e.jsx(V2,{content:A.email_signature,onChange:_e=>M({...A,email_signature:_e}),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($,{onClick:le,disabled:h,children:[e.jsx(Ml,{className:"mr-2 h-4 w-4"}),"Save Signature"]})]})]}),e.jsx(R8s,{}),e.jsxs(we,{id:"change-password-section",children:[e.jsxs(Vt,{children:[e.jsx(Yt,{children:a?"Set Your Password":"Change Password"}),e.jsx(vr,{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(re,{htmlFor:"newPassword",children:"New Password"}),e.jsx(be,{id:"newPassword",type:"password",value:ee.newPassword,onChange:_e=>oe({...ee,newPassword:_e.target.value}),placeholder:"Min 6 characters"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"confirmPassword",children:"Confirm Password"}),e.jsx(be,{id:"confirmPassword",type:"password",value:ee.confirmPassword,onChange:_e=>oe({...ee,confirmPassword:_e.target.value}),placeholder:"Re-enter your new password"})]}),e.jsxs($,{onClick:fe,disabled:h,children:[e.jsx(Ml,{className:"mr-2 h-4 w-4"}),a?"Complete Setup":"Update Password"]}),a&&e.jsx($,{variant:"outline",onClick:()=>t("/dashboard"),className:"ml-2",children:"Skip for Now"})]})]}),e.jsxs(we,{children:[e.jsxs(Vt,{children:[e.jsxs(Yt,{className:"flex items-center gap-2",children:[o?e.jsx(Fx,{className:"h-5 w-5"}):e.jsx(k5,{className:"h-5 w-5"}),"Push Notifications"]}),e.jsx(vr,{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(On,{checked:o,onCheckedChange:_e=>{_e?d():u()},disabled:c})]}):e.jsxs("div",{className:"text-sm text-muted-foreground space-y-2",children:[e.jsx("p",{children:"Push notifications are not available in this browser."}),e.jsxs("p",{className:"text-xs space-y-1",children:[e.jsx("strong",{children:"Desktop:"})," Use Chrome, Firefox, or Edge.",e.jsx("br",{}),e.jsx("strong",{children:"Android:"})," Use Chrome or Firefox.",e.jsx("br",{}),e.jsx("strong",{children:"iPhone/iPad:"})," Push notifications on iOS ",e.jsx("em",{children:"only"})," work when this site is installed as an app from ",e.jsx("strong",{children:"Safari"}),". Open this site in Safari → tap the ",e.jsx("strong",{children:"Share"})," button → ",e.jsx("strong",{children:"Add to Home Screen"}),". Other browsers (Chrome, Firefox, etc.) on iOS do not support push notifications due to Apple restrictions."]})]})})]}),e.jsx(C8s,{}),e.jsxs(we,{children:[e.jsxs(Vt,{children:[e.jsxs(Yt,{className:"flex items-center gap-2",children:[R?e.jsx(Qz,{className:"h-5 w-5"}):e.jsx(pn,{className:"h-5 w-5"}),"Email Preferences"]}),e.jsx(vr,{children:"Manage your email subscription settings"})]}),e.jsxs(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:R?"You won't receive weekly digest emails":"Receive a weekly summary of new content, events, and your progress"})]}),e.jsx(On,{checked:!R,onCheckedChange:async _e=>{U(!0);try{const{error:ve}=await V.from("profiles").update({digest_opt_out:!_e}).eq("id",s==null?void 0:s.id);if(ve)throw ve;O(!_e),n({title:_e?"Subscribed":"Unsubscribed",description:_e?"You will now receive weekly digest emails":"You will no longer receive weekly digest emails"})}catch(ve){n({title:"Error",description:ve.message||"Failed to update preference",variant:"destructive"})}finally{U(!1)}},disabled:B})]}),e.jsxs("div",{className:"flex items-center justify-between pt-4 mt-4 border-t",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Event Invite Emails"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:G?"You won't receive event invite emails (weekly digest is unaffected)":"Get invited to LevelUp live trainings and special events"})]}),e.jsx(On,{checked:!G,onCheckedChange:async _e=>{se(!0);try{const{error:ve}=await V.from("profiles").update({event_invite_opt_out:!_e}).eq("id",s==null?void 0:s.id);if(ve)throw ve;H(!_e),n({title:_e?"Subscribed":"Unsubscribed",description:_e?"You will now receive event invite emails":"You will no longer receive event invite emails"})}catch(ve){n({title:"Error",description:ve.message||"Failed to update preference",variant:"destructive"})}finally{se(!1)}},disabled:Y})]})]})]}),e.jsx(wTs,{}),e.jsx(D8s,{})]}),e.jsx(pKe,{open:v,onClose:()=>_(!1),imageSrc:j,onCropComplete:te,aspectRatio:1})]})})};var F8s=Object.defineProperty,z8s=(s,t)=>F8s(s,"name",{value:t,configurable:!0}),B8s=k.forwardRef(z8s(function(t,n){const{ratio:r=1/1,style:a,...i}=t;return e.jsx("div",{style:{position:"relative",width:"100%",paddingBottom:`${100/r}%`},"data-radix-aspect-ratio-wrapper":"",children:e.jsx(hi.div,{...i,ref:n,style:{...a,position:"absolute",top:0,right:0,bottom:0,left:0}})})},"AspectRatio")),$8s=B8s;const U8s=$8s;function q8s(){const{user:s}=ks(),t=ls(),[n,r]=k.useState(!1),[a,i]=k.useState(!1),{data:l,isLoading:o}=pt({queryKey:["calendar-token",s==null?void 0:s.id],queryFn:async()=>{const{data:g,error:x}=await V.from("profiles").select("calendar_token").eq("id",s==null?void 0:s.id).single();if(x)throw x;return g},enabled:!!s&&a}),c=Nt({mutationFn:async()=>{const g=new Uint8Array(12);crypto.getRandomValues(g);const x=btoa(String.fromCharCode(...g)).replace(/\+/g,"x").replace(/\//g,"y").replace(/=/g,"").substring(0,16),{error:y}=await V.from("profiles").update({calendar_token:x}).eq("id",s==null?void 0:s.id);if(y)throw y;return x},onSuccess:()=>{t.invalidateQueries({queryKey:["calendar-token",s==null?void 0:s.id]}),ae.success("Calendar subscription URL generated!")},onError:g=>{ae.error("Failed to generate calendar URL: "+g.message)}}),d=l!=null&&l.calendar_token?`https://dashboard.relevelup.com/api/calendar/${l.calendar_token}.ics`:null,u=async()=>{d&&(await navigator.clipboard.writeText(d),r(!0),ae.success("Calendar URL copied to clipboard!"),setTimeout(()=>r(!1),2e3))},h=()=>{d&&(window.location.href=d.replace("https://","webcal://"))},m=()=>{if(d){const g=d.replace("https://","webcal://"),x=`https://calendar.google.com/calendar/r?cid=${encodeURIComponent(g)}`;window.open(x,"_blank")}},p=()=>{if(d){const g=`https://outlook.live.com/calendar/0/addfromweb?url=${encodeURIComponent(d)}&name=Level%20Up%20Events`;window.open(g,"_blank")}};return e.jsxs(zs,{open:a,onOpenChange:i,children:[e.jsx(yl,{asChild:!0,children:e.jsxs($,{variant:"outline",className:"gap-2",children:[e.jsx(ha,{className:"h-4 w-4"}),"Subscribe to Calendar"]})}),e.jsxs(Rs,{className:"sm:max-w-md",children:[e.jsxs(Vs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(ha,{className:"h-5 w-5 text-primary"}),"Subscribe to Events Calendar"]}),e.jsx(Cr,{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(Jt,{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(be,{value:d,readOnly:!0,className:"text-xs font-mono"}),e.jsx($,{variant:"outline",size:"icon",onClick:u,children:n?e.jsx(ma,{className:"h-4 w-4 text-green-500"}):e.jsx(Da,{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($,{variant:"outline",className:"w-full justify-start gap-2",onClick:h,children:[e.jsx("svg",{className:"h-4 w-4",viewBox:"0 0 24 24",fill:"currentColor",children:e.jsx("path",{d:"M18.71 19.5c-.83 1.24-1.71 2.45-3.05 2.47-1.34.03-1.77-.79-3.29-.79-1.53 0-2 .77-3.27.82-1.31.05-2.3-1.32-3.14-2.53C4.25 17 2.94 12.45 4.7 9.39c.87-1.52 2.43-2.48 4.12-2.51 1.28-.02 2.5.87 3.29.87.78 0 2.26-1.07 3.81-.91.65.03 2.47.26 3.64 1.98-.09.06-2.17 1.28-2.15 3.81.03 3.02 2.65 4.03 2.68 4.04-.03.07-.42 1.44-1.38 2.83M13 3.5c.73-.83 1.94-1.46 2.94-1.5.13 1.17-.34 2.35-1.04 3.19-.69.85-1.83 1.51-2.95 1.42-.15-1.15.41-2.35 1.05-3.11z"})}),"Add to Apple Calendar",e.jsx(Ir,{className:"h-3 w-3 ml-auto opacity-50"})]}),e.jsxs($,{variant:"outline",className:"w-full justify-start gap-2",onClick:m,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(Ir,{className:"h-3 w-3 ml-auto opacity-50"})]}),e.jsxs($,{variant:"outline",className:"w-full justify-start gap-2",onClick:p,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(Ir,{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($,{onClick:()=>c.mutate(),disabled:c.isPending,className:"w-full",children:c.isPending?e.jsxs(e.Fragment,{children:[e.jsx(Jt,{className:"h-4 w-4 mr-2 animate-spin"}),"Generating..."]}):e.jsxs(e.Fragment,{children:[e.jsx(ha,{className:"h-4 w-4 mr-2"}),"Generate Calendar URL"]})})]})})]})]})}const V8s={first_timer:ri,regular:y3,dedicated:oh,veteran:ql,streak_master:iu,century:ql},H8s={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 Iut(s){return s===1?e.jsx(ql,{className:"h-5 w-5 text-yellow-500"}):s===2?e.jsx(y3,{className:"h-5 w-5 text-gray-400"}):s===3?e.jsx(oh,{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 yIt({showUserStats:s=!0,compact:t=!1,brokerageId:n,title:r="Event Leaderboard"}){const{user:a}=ks(),{data:i,isLoading:l}=qMt(t?5:10,n),{data:o}=VMt(a==null?void 0:a.id),{data:c}=GMt(a==null?void 0:a.id),{data:d}=HMt(a==null?void 0:a.id);return l?e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsxs(Yt,{className:"flex items-center gap-2",children:[e.jsx(ql,{className:"h-5 w-5 text-yellow-500"}),r]})}),e.jsx(De,{children:e.jsx("div",{className:"space-y-3",children:[...Array(5)].map((u,h)=>e.jsx(fn,{className:"h-12 w-full"},h))})})]}):e.jsxs(we,{children:[e.jsx(Vt,{className:"pb-3",children:e.jsxs(Yt,{className:"flex items-center gap-2",children:[e.jsx(ql,{className:"h-5 w-5 text-yellow-500"}),r]})}),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(qe,{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(iu,{className:"h-4 w-4 text-orange-500"}),e.jsx("div",{className:"text-lg font-bold",children:o.current_streak}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Streak"})]})]}),d&&d.length>0&&e.jsxs("div",{className:"mt-3 flex flex-wrap gap-1",children:[d.slice(0,4).map(u=>{const h=V8s[u.badge_type]||ri;return e.jsxs(qe,{variant:"outline",className:`text-xs ${H8s[u.badge_type]||""}`,title:u.badge_description||"",children:[e.jsx(h,{className:"h-3 w-3 mr-1"}),u.badge_name]},u.id)}),d.length>4&&e.jsxs(qe,{variant:"outline",className:"text-xs",children:["+",d.length-4," more"]})]})]}),e.jsxs(ya,{defaultValue:"points",className:"w-full",children:[e.jsxs(va,{className:"w-full mb-3",children:[e.jsx(is,{value:"points",className:"flex-1",children:"By Points"}),e.jsx(is,{value:"events",className:"flex-1",children:"By Events"})]}),e.jsx(cs,{value:"points",className:"mt-0",children:e.jsxs("div",{className:"space-y-2",children:[i==null?void 0:i.map((u,h)=>{var m,p,g;return e.jsxs("div",{className:`flex items-center gap-3 p-2 rounded-lg ${u.user_id===(a==null?void 0:a.id)?"bg-primary/5 border border-primary/10":""} ${h===0?"bg-yellow-500/5":""}`,children:[e.jsx("div",{className:"w-6 flex justify-center",children:Iut(h+1)}),e.jsx(Wa,{className:"h-8 w-8",children:e.jsx(Ka,{className:"text-xs",children:((p=(m=u.profile)==null?void 0:m.name)==null?void 0:p.charAt(0))||"?"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"font-medium text-sm truncate",children:[((g=u.profile)==null?void 0:g.name)||"Unknown",u.user_id===(a==null?void 0:a.id)&&e.jsx("span",{className:"text-xs text-muted-foreground ml-1",children:"(You)"})]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[u.total_events_attended," events"]})]}),e.jsxs("div",{className:"text-right",children:[e.jsx("div",{className:"font-bold text-primary",children:u.total_points}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"pts"})]})]},u.user_id)}),(!i||i.length===0)&&e.jsx("div",{className:"text-center text-muted-foreground py-4 text-sm",children:"No attendance data yet. Attend an event to get on the leaderboard!"})]})}),e.jsx(cs,{value:"events",className:"mt-0",children:e.jsx("div",{className:"space-y-2",children:[...i||[]].sort((u,h)=>h.total_events_attended-u.total_events_attended).map((u,h)=>{var m,p,g;return e.jsxs("div",{className:`flex items-center gap-3 p-2 rounded-lg ${u.user_id===(a==null?void 0:a.id)?"bg-primary/5 border border-primary/10":""} ${h===0?"bg-yellow-500/5":""}`,children:[e.jsx("div",{className:"w-6 flex justify-center",children:Iut(h+1)}),e.jsx(Wa,{className:"h-8 w-8",children:e.jsx(Ka,{className:"text-xs",children:((p=(m=u.profile)==null?void 0:m.name)==null?void 0:p.charAt(0))||"?"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"font-medium text-sm truncate",children:[((g=u.profile)==null?void 0:g.name)||"Unknown",u.user_id===(a==null?void 0:a.id)&&e.jsx("span",{className:"text-xs text-muted-foreground ml-1",children:"(You)"})]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[u.total_points," points"]})]}),e.jsxs("div",{className:"text-right",children:[e.jsx("div",{className:"font-bold",children:u.total_events_attended}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"events"})]})]},u.user_id)})})})]})]})]})}function G8s(){const s=Jn(),{user:t,isAdmin:n}=ks(),r=ls(),[a,i]=k.useState(!1),[l,o]=k.useState(!1),{data:c,isLoading:d}=pt({queryKey:["public-events"],queryFn:async()=>{const{data:M,error:I}=await V.from("events").select("*").order("event_date",{ascending:!0});if(I)throw I;return M}}),{data:u}=pt({queryKey:["my-registrations"],queryFn:async()=>{if(!t)return[];const{data:M,error:I}=await V.from("event_registrations").select("event_id, zoom_join_url").eq("user_id",t.id);if(I)throw I;return M},enabled:!!t}),{data:h}=pt({queryKey:["event-registration-counts"],queryFn:async()=>{let M=[],I=0;const P=1e3;for(;;){const{data:O,error:B}=await V.from("event_registrations").select("event_id").range(I,I+P-1);if(B)throw B;if(!O||O.length===0||(M=M.concat(O),O.length{R[O.event_id]=(R[O.event_id]||0)+1}),R}}),m=Nt({mutationFn:async M=>{await V.auth.refreshSession();const{data:I,error:P}=await V.functions.invoke("zoom-register",{body:{event_id:M}});if(P)throw P;if(I!=null&&I.error)throw new Error(I.error);return I},onSuccess:M=>{r.invalidateQueries({queryKey:["my-registrations"]}),r.invalidateQueries({queryKey:["event-registration-counts"]}),M!=null&&M.join_url?ae.success("Successfully registered! You'll receive a Zoom confirmation email."):ae.success("Successfully registered for the event!")},onError:M=>{ae.error("Failed to register: "+M.message)}}),p=Nt({mutationFn:async M=>{const{data:I,error:P}=await V.functions.invoke("zoom-unregister",{body:{event_id:M}});if(P)throw P;if(I!=null&&I.error)throw new Error(I.error);return I},onSuccess:()=>{r.invalidateQueries({queryKey:["my-registrations"]}),r.invalidateQueries({queryKey:["event-registration-counts"]}),ae.success("Registration cancelled and removed from Zoom")},onError:M=>{ae.error("Failed to cancel: "+M.message)}}),g=M=>u==null?void 0:u.some(I=>I.event_id===M),x=M=>{const I=u==null?void 0:u.find(P=>P.event_id===M);return I==null?void 0:I.zoom_join_url},y=M=>M.capacity?((h==null?void 0:h[M.id])||0)>=M.capacity:!1,v=(c==null?void 0:c.filter(M=>iD(M.event_date)!=="ended"))||[],_=(c==null?void 0:c.filter(M=>iD(M.event_date)==="ended"))||[],j=v.filter(M=>iD(M.event_date)==="live").length,C=v.filter(M=>g(M.id)).length,A=l?_:_.slice(0,6);return e.jsx(Xs,{title:"Events",children:e.jsxs("div",{className:"mx-auto max-w-6xl space-y-6",children:[e.jsx("section",{className:"hub-ink relative overflow-hidden rounded-2xl p-5 sm:p-6",children:e.jsxs("div",{className:"relative flex flex-col gap-5",children:[e.jsxs("div",{className:"flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-xs uppercase tracking-wider hub-ink-muted",children:"LevelUp Live"}),e.jsx("h1",{className:"mt-1 text-2xl font-bold sm:text-3xl",children:"Events"}),e.jsx("p",{className:"mt-1 text-sm hub-ink-muted",children:j>0?"An event is live right now — jump in.":v.length>0?`Next up: ${v[0].title}`:"No upcoming events scheduled — replays are below."})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(q8s,{}),n&&e.jsxs("button",{onClick:()=>s("/admin/events"),className:"hub-glass inline-flex items-center gap-2 rounded-full px-4 py-2 text-sm font-medium transition-colors",children:[e.jsx(Yc,{className:"h-4 w-4",style:{color:"hsl(var(--hub-glow))"}}),"Manage Events"]})]})]}),e.jsx("div",{className:"grid grid-cols-2 gap-2 sm:grid-cols-4",children:[{label:"Upcoming",value:v.length,icon:ha},{label:"You're registered",value:C,icon:ma},{label:"Live now",value:j,icon:Cy},{label:"Past events",value:_.length,icon:b2}].map(M=>e.jsxs("div",{className:"hub-glass rounded-xl px-3 py-2.5",children:[e.jsx("span",{className:"text-xl font-bold",children:M.value}),e.jsxs("p",{className:"mt-0.5 flex items-center gap-1 text-[11px] hub-ink-muted",children:[e.jsx(M.icon,{className:"h-3 w-3"}),M.label]})]},M.label))})]})}),e.jsxs("div",{className:`grid grid-cols-1 gap-6 ${n?"lg:grid-cols-3":""}`,children:[e.jsxs("div",{className:`space-y-6 ${n?"lg:col-span-2":""}`,children:[d?e.jsx("div",{className:"grid gap-6 md:grid-cols-2",children:[0,1].map(M=>e.jsx("div",{className:"h-72 animate-pulse rounded-2xl border bg-muted/40"},M))}):v.length===0?e.jsx(we,{className:"rounded-2xl border-dashed py-12 text-center",children:e.jsxs(De,{className:"space-y-2",children:[e.jsx(ha,{className:"mx-auto h-10 w-10 text-muted-foreground"}),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:v.map(M=>{const I=iD(M.event_date),P=pWe(M.event_date),R=I==="live",O=I==="starting_soon";return e.jsxs(we,{className:`group flex flex-col overflow-hidden rounded-2xl cursor-pointer transition-all hover:shadow-lg ${R?"border-red-500 ring-2 ring-red-500/20":O?"border-amber-500 ring-2 ring-amber-500/20":"hover:border-primary/50"}`,onClick:()=>s(`/events/${M.id}`),children:[P&&e.jsxs("div",{className:`${R?"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"})]}),R?e.jsxs(e.Fragment,{children:[e.jsx(Cy,{className:"h-3.5 w-3.5"}),"LIVE NOW"]}):e.jsxs(e.Fragment,{children:[e.jsx(sa,{className:"h-3.5 w-3.5"}),"STARTING SOON"]})]}),M.image_url&&e.jsxs(U8s,{ratio:16/9,className:"overflow-hidden relative bg-neutral-900",children:[e.jsx("img",{src:M.image_url,alt:"","aria-hidden":"true",className:"absolute inset-0 w-full h-full object-cover blur-2xl scale-110 opacity-60"}),e.jsx("img",{src:M.image_url,alt:M.title,className:"relative w-full h-full object-contain transition-transform group-hover:scale-[1.03]"})]}),e.jsxs(Vt,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full bg-primary/10 px-2.5 py-1 text-[11px] font-semibold text-primary",children:[e.jsx(ha,{className:"h-3 w-3"}),new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric",timeZone:"America/New_York"}).format(new Date(M.event_date))]}),g(M.id)&&e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full bg-emerald-500/10 px-2.5 py-1 text-[11px] font-semibold text-emerald-600 dark:text-emerald-400",children:[e.jsx(ma,{className:"h-3 w-3"}),"Registered"]})]}),e.jsx(Yt,{className:"line-clamp-2 pt-1",children:M.title}),M.description&&e.jsx(vr,{className:"line-clamp-2",children:M.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(ha,{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(M.event_date))]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(sa,{className:"h-4 w-4"}),nX(new Date(M.event_date))]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(Xn,{className:"h-4 w-4"}),(h==null?void 0:h[M.id])||0," registered",M.capacity&&` / ${M.capacity} spots`]})]}),e.jsx(pY,{className:"flex gap-2",onClick:B=>B.stopPropagation(),children:g(M.id)?e.jsxs(e.Fragment,{children:[e.jsxs($,{variant:"outline",className:"flex-1",onClick:()=>p.mutate(M.id),disabled:p.isPending,children:[e.jsx(mr,{className:"h-4 w-4 mr-2"}),"Cancel"]}),e.jsxs($,{className:"flex-1",onClick:()=>window.open(x(M.id)||M.zoom_link,"_blank"),children:[e.jsx(Ir,{className:"h-4 w-4 mr-2"}),"Join Zoom"]})]}):e.jsx($,{className:"w-full",onClick:()=>m.mutate(M.id),disabled:m.isPending||y(M),children:y(M)?"Event Full":e.jsxs(e.Fragment,{children:[e.jsx(ma,{className:"h-4 w-4 mr-2"}),"Register"]})})})]},M.id)})}),_.length>0&&e.jsxs(we,{className:"rounded-2xl",children:[e.jsxs("button",{type:"button",onClick:()=>i(M=>!M),className:"flex w-full items-center justify-between gap-3 px-5 py-4 text-left",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"flex h-9 w-9 items-center justify-center rounded-xl bg-muted",children:e.jsx(b2,{className:"h-4 w-4 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-semibold",children:"Past Events"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[_.length," previous ",_.length===1?"session":"sessions"," — open one to watch the replay"]})]})]}),e.jsx(Go,{className:`h-4 w-4 text-muted-foreground transition-transform ${a?"rotate-180":""}`})]}),a&&e.jsxs("div",{className:"border-t",children:[e.jsx("ul",{className:"divide-y",children:A.map(M=>e.jsx("li",{children:e.jsxs("button",{type:"button",onClick:()=>s(`/events/${M.id}`),className:"flex w-full items-center gap-3 px-5 py-3 text-left transition-colors hover:bg-muted/50",children:[e.jsxs("div",{className:"flex w-12 shrink-0 flex-col items-center rounded-lg border bg-muted/40 py-1",children:[e.jsx("span",{className:"text-[10px] font-semibold uppercase text-muted-foreground",children:new Intl.DateTimeFormat("en-US",{month:"short",timeZone:"America/New_York"}).format(new Date(M.event_date))}),e.jsx("span",{className:"text-sm font-bold leading-none",children:new Intl.DateTimeFormat("en-US",{day:"numeric",timeZone:"America/New_York"}).format(new Date(M.event_date))})]}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"truncate text-sm font-medium",children:M.title}),e.jsx("p",{className:"text-xs text-muted-foreground",children:new Intl.DateTimeFormat("en-US",{year:"numeric",month:"long",day:"numeric",timeZone:"America/New_York"}).format(new Date(M.event_date))})]}),e.jsx(mm,{className:"h-4 w-4 shrink-0 text-muted-foreground"})]})},M.id))}),_.length>6&&e.jsx("div",{className:"border-t px-5 py-3",children:e.jsx($,{variant:"ghost",size:"sm",className:"w-full",onClick:()=>o(M=>!M),children:l?"Show less":`Show all ${_.length}`})})]})]})]}),n&&e.jsx("div",{className:"lg:col-span-1",children:e.jsx(yIt,{showUserStats:!0})})]})]})})}const MLe=[{value:"all",label:"All Roles",icon:Xn},{value:"newest",label:"Newest Members",icon:sa},{value:"brokerage_manager",label:"Brokerage Managers",icon:iY},{value:"admin",label:"Admins",icon:Ng}];function W8s({open:s,onOpenChange:t,resourceType:n,resourceId:r,resourceTitle:a}){var Ue,Be;const{user:i,isAdmin:l,isBrokerageManager:o}=ks(),[c,d]=k.useState([]),[u,h]=k.useState([]),[m,p]=k.useState([]),[g,x]=k.useState([]),[y,v]=k.useState(""),[_,j]=k.useState(""),[C,A]=k.useState(""),[M,I]=k.useState(!1),[P,R]=k.useState(!1),[O,B]=k.useState("agents"),[U,G]=k.useState("all"),[H,Y]=k.useState({}),se=l||o;k.useEffect(()=>{s&&i&&(l?ee():oe())},[s,i,l]),k.useEffect(()=>{s||(p([]),x([]),v(""),j(""),A(""),B("agents"),G("all"))},[s]);const ee=async()=>{if(i){I(!0);try{const{data:je,error:Ye}=await V.from("brokerages").select("id, name").order("name");if(Ye)throw Ye;const Ee=1e3,Re={};let ke=0,Fe=!0;for(;Fe;){const{data:yt,error:tt}=await V.from("profiles").select("brokerage_id").range(ke*Ee,(ke+1)*Ee-1);if(tt)throw tt;yt==null||yt.forEach(ut=>{ut.brokerage_id&&(Re[ut.brokerage_id]=(Re[ut.brokerage_id]||0)+1)}),Fe=(yt==null?void 0:yt.length)===Ee,ke++}h((je==null?void 0:je.map(yt=>({...yt,agent_count:Re[yt.id]||0})))||[]);const Oe=[];for(ke=0,Fe=!0;Fe;){const{data:yt,error:tt}=await V.from("profiles").select("id, name, email, brokerage_id, created_at, brokerages(name)").neq("id",i.id).order("name").range(ke*Ee,(ke+1)*Ee-1);if(tt)throw tt;yt&&Oe.push(...yt),Fe=(yt==null?void 0:yt.length)===Ee,ke++}const Ge={};for(ke=0,Fe=!0;Fe;){const{data:yt,error:tt}=await V.from("user_roles").select("user_id, role").range(ke*Ee,(ke+1)*Ee-1);if(tt)throw tt;yt==null||yt.forEach(ut=>{Ge[ut.user_id]||(Ge[ut.user_id]=[]),Ge[ut.user_id].push(ut.role)}),Fe=(yt==null?void 0:yt.length)===Ee,ke++}Y(Ge),d(Oe.map(yt=>{var tt;return{id:yt.id,name:yt.name,email:yt.email,brokerage_name:((tt=yt.brokerages)==null?void 0:tt.name)||"No Brokerage",roles:Ge[yt.id]||[],created_at:yt.created_at}}))}catch(je){console.error("Error loading data:",je),ae.error("Failed to load agents and brokerages")}finally{I(!1)}}},oe=async()=>{if(i){I(!0);try{const{data:je}=await V.from("profiles").select("brokerage_id").eq("id",i.id).single();if(!(je!=null&&je.brokerage_id)){ae.error("You must be part of a brokerage to share resources"),t(!1);return}const{data:Ye,error:Ee}=await V.from("profiles").select("id, name, email").eq("brokerage_id",je.brokerage_id).neq("id",i.id).order("name");if(Ee)throw Ee;d(Ye||[])}catch(je){console.error("Error loading agents:",je),ae.error("Failed to load agents")}finally{I(!1)}}},me=c.filter(je=>{var Ee;const Ye=je.name.toLowerCase().includes(y.toLowerCase())||je.email.toLowerCase().includes(y.toLowerCase())||((Ee=je.brokerage_name)==null?void 0:Ee.toLowerCase().includes(y.toLowerCase()));if(l&&U!=="all"&&U!=="newest"){const Re=H[je.id]||[];return Ye&&Re.includes(U)}return Ye}).sort((je,Ye)=>U==="newest"?(Ye.created_at||"").localeCompare(je.created_at||""):0),Q=u.filter(je=>je.name.toLowerCase().includes(_.toLowerCase())),te=()=>{m.length===me.length?p([]):p(me.map(je=>je.id))},le=()=>{g.length===Q.length?x([]):x(Q.map(je=>je.id))},fe=je=>{if(!se){p([je]);return}p(Ye=>Ye.includes(je)?Ye.filter(Ee=>Ee!==je):[...Ye,je])},_e=je=>{x(Ye=>Ye.includes(je)?Ye.filter(Ee=>Ee!==je):[...Ye,je])},ve=async()=>{if(!(m.length>0||g.length>0)){ae.error("Please select at least one agent or brokerage to share with");return}R(!0);try{const{data:Ye,error:Ee}=await V.functions.invoke("send-share-notification",{body:{recipientIds:m,brokerageIds:g,resourceType:n,resourceId:r,resourceTitle:a,message:C.trim()||void 0}});if(Ee)throw Ee;const Re=(Ye==null?void 0:Ye.sharesCreated)||m.length;ae.success(`Shared with ${Re} agent${Re!==1?"s":""}`),t(!1)}catch(Ye){console.error("Error sharing resource:",Ye),ae.error("Failed to share resource")}finally{R(!1)}},he=je=>je.split(" ").map(Ye=>Ye[0]).join("").toUpperCase().slice(0,2),Se=je=>{const Ye=H[je]||[];return Ye.includes("admin")?e.jsx(qe,{variant:"secondary",className:"text-[10px] px-1.5 py-0",children:"Admin"}):Ye.includes("brokerage_manager")?e.jsx(qe,{variant:"outline",className:"text-[10px] px-1.5 py-0",children:"Manager"}):null},Te=m.length+g.length,Ie=U!=="all"&&U!=="newest"?me.length:null;return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"sm:max-w-lg max-h-[90vh] overflow-hidden flex flex-col",children:[e.jsxs(Vs,{className:"flex-shrink-0",children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(Wr,{className:"h-5 w-5 text-primary"}),"Share Resource"]}),e.jsxs(Cr,{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(ya,{value:O,onValueChange:B,className:"flex-1 flex flex-col overflow-hidden",children:[e.jsxs(va,{className:"grid w-full grid-cols-2 flex-shrink-0",children:[e.jsxs(is,{value:"agents",className:"flex items-center gap-2",children:[e.jsx(Xn,{className:"h-4 w-4"}),e.jsx("span",{children:"Agents"}),m.length>0&&e.jsx(qe,{variant:"default",className:"h-5 min-w-5 px-1.5 text-xs",children:m.length})]}),e.jsxs(is,{value:"brokerages",className:"flex items-center gap-2",children:[e.jsx(Gi,{className:"h-4 w-4"}),e.jsx("span",{children:"Brokerages"}),g.length>0&&e.jsx(qe,{variant:"default",className:"h-5 min-w-5 px-1.5 text-xs",children:g.length})]})]}),e.jsxs(cs,{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(Yr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search by name, email, or brokerage...",value:y,onChange:je=>v(je.target.value),className:"pl-9"})]}),e.jsxs(bs,{value:U,onValueChange:G,children:[e.jsxs(ys,{className:"w-[180px]",children:[e.jsx(v2,{className:"h-4 w-4 mr-2 text-muted-foreground"}),e.jsx(_s,{placeholder:"Filter by role"})]}),e.jsx(vs,{children:MLe.map(je=>e.jsx(We,{value:je.value,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(je.icon,{className:"h-4 w-4"}),e.jsx("span",{children:je.label})]})},je.value))})]})]}),e.jsxs("div",{className:"flex items-center justify-between px-1 flex-shrink-0",children:[e.jsxs($,{variant:"ghost",size:"sm",onClick:te,className:"text-xs h-8",disabled:me.length===0,children:[e.jsx(Xn,{className:"h-3.5 w-3.5 mr-1.5"}),m.length===me.length&&me.length>0?"Deselect All":"Select All"]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[Ie!==null&&e.jsxs("span",{className:"text-primary font-medium",children:[Ie," ",(Ue=MLe.find(je=>je.value===U))==null?void 0:Ue.label]}),e.jsxs("span",{className:"font-medium",children:[m.length," selected"]})]})]}),e.jsx(Eo,{className:"h-[300px] border rounded-lg",children:M?e.jsx("div",{className:"flex items-center justify-center h-[200px]",children:e.jsx(Jt,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):me.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center h-[200px] text-muted-foreground",children:[e.jsx(Xn,{className:"h-8 w-8 mb-2 opacity-50"}),e.jsx("p",{className:"text-sm",children:U!=="all"?`No ${(Be=MLe.find(je=>je.value===U))==null?void 0:Be.label.toLowerCase()} found`:"No agents found"})]}):e.jsx("div",{className:"p-2 space-y-1",children:me.map(je=>e.jsxs("div",{className:`flex items-center gap-3 p-2.5 rounded-lg cursor-pointer hover:bg-accent/50 transition-colors ${m.includes(je.id)?"bg-accent":""}`,onClick:()=>fe(je.id),children:[e.jsx(Li,{checked:m.includes(je.id),onCheckedChange:()=>fe(je.id),className:"flex-shrink-0"}),e.jsx(Wa,{className:"h-9 w-9 flex-shrink-0",children:e.jsx(Ka,{className:"text-xs bg-primary/10 text-primary",children:he(je.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:je.name}),Se(je.id)]}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[je.email,je.brokerage_name&&e.jsxs("span",{className:"ml-1 opacity-75",children:["• ",je.brokerage_name]})]})]})]},je.id))})})]}),e.jsxs(cs,{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(Yr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search brokerages...",value:_,onChange:je=>j(je.target.value),className:"pl-9"})]}),e.jsxs("div",{className:"flex items-center justify-between px-1 flex-shrink-0",children:[e.jsxs($,{variant:"ghost",size:"sm",onClick:le,className:"text-xs h-8",disabled:Q.length===0,children:[e.jsx(Gi,{className:"h-3.5 w-3.5 mr-1.5"}),g.length===Q.length&&Q.length>0?"Deselect All":"Select All"]}),e.jsxs("span",{className:"text-xs text-muted-foreground font-medium",children:[g.length," selected"]})]}),e.jsx("p",{className:"text-xs text-muted-foreground px-1 flex-shrink-0",children:"Selecting a brokerage will send to all agents in that brokerage."}),e.jsx(Eo,{className:"h-[250px] border rounded-lg",children:M?e.jsx("div",{className:"flex items-center justify-center h-[180px]",children:e.jsx(Jt,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):Q.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center h-[180px] text-muted-foreground",children:[e.jsx(Gi,{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:Q.map(je=>e.jsxs("div",{className:`flex items-center gap-3 p-2.5 rounded-lg cursor-pointer hover:bg-accent/50 transition-colors ${g.includes(je.id)?"bg-accent":""}`,onClick:()=>_e(je.id),children:[e.jsx(Li,{checked:g.includes(je.id),onCheckedChange:()=>_e(je.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(Gi,{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:je.name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[je.agent_count," agent",je.agent_count!==1?"s":""]})]})]},je.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(Yr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search agents...",value:y,onChange:je=>v(je.target.value),className:"pl-9"})]}),se&&e.jsxs("div",{className:"flex items-center justify-between px-1 flex-shrink-0",children:[e.jsxs($,{variant:"ghost",size:"sm",onClick:te,className:"text-xs h-8",disabled:me.length===0,children:[e.jsx(Xn,{className:"h-3.5 w-3.5 mr-1.5"}),m.length===me.length&&me.length>0?"Deselect All":"Select All"]}),e.jsxs("span",{className:"text-xs text-muted-foreground font-medium",children:[m.length," selected"]})]}),e.jsx(Eo,{className:"h-[300px] border rounded-lg",children:M?e.jsx("div",{className:"flex items-center justify-center h-[200px]",children:e.jsx(Jt,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):me.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center h-[200px] text-muted-foreground",children:[e.jsx(Xn,{className:"h-8 w-8 mb-2 opacity-50"}),e.jsx("p",{className:"text-sm",children:"No agents found"})]}):e.jsx("div",{className:"p-2 space-y-1",children:me.map(je=>e.jsxs("div",{className:`flex items-center gap-3 p-2.5 rounded-lg cursor-pointer hover:bg-accent/50 transition-colors ${m.includes(je.id)?"bg-accent":""}`,onClick:()=>fe(je.id),children:[e.jsx(Li,{checked:m.includes(je.id),onCheckedChange:()=>fe(je.id),className:"flex-shrink-0"}),e.jsx(Wa,{className:"h-9 w-9 flex-shrink-0",children:e.jsx(Ka,{className:"text-xs bg-primary/10 text-primary",children:he(je.name)})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:je.name}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:je.email})]})]},je.id))})})]}),e.jsxs("div",{className:"space-y-2 flex-shrink-0",children:[e.jsx(re,{htmlFor:"message",className:"text-sm font-medium",children:"Add a message (optional)"}),e.jsx(Ls,{id:"message",placeholder:"I thought you might find this useful...",value:C,onChange:je=>A(je.target.value),rows:2,className:"resize-none"})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2 flex-shrink-0",children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx($,{onClick:ve,disabled:Te===0||P,children:P?e.jsxs(e.Fragment,{children:[e.jsx(Jt,{className:"h-4 w-4 mr-2 animate-spin"}),"Sharing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Wr,{className:"h-4 w-4 mr-2"}),"Share"]})})]})]})]})})}function tV({resourceType:s,resourceId:t,resourceTitle:n,variant:r="outline",size:a="sm",className:i=""}){const[l,o]=k.useState(!1),{user:c}=ks();return c?e.jsxs(e.Fragment,{children:[e.jsxs($,{variant:r,size:a,onClick:()=>o(!0),className:i,children:[e.jsx(ou,{className:"h-4 w-4 mr-2"}),"Share"]}),e.jsx(W8s,{open:l,onOpenChange:o,resourceType:s,resourceId:t,resourceTitle:n})]}):null}function K8s(){const{eventId:s}=oo(),t=Jn(),{user:n}=ks(),[r,a]=k.useState(null),[i,l]=k.useState(null),[o,c]=k.useState(0),[d,u]=k.useState(!0),[h,m]=k.useState(!1);k.useEffect(()=>{s&&p()},[s,n]);const p=async()=>{try{const{data:j,error:C}=await V.from("events").select("*").eq("id",s).single();if(C)throw C;a(j);const{count:A}=await V.from("event_registrations").select("*",{count:"exact",head:!0}).eq("event_id",s);if(c(A||0),n){const{data:M}=await V.from("event_registrations").select("id, zoom_join_url").eq("event_id",s).eq("user_id",n.id).maybeSingle();l(M)}}catch(j){console.error("Error loading event:",j),ae.error("Failed to load event"),t("/events")}finally{u(!1)}},g=async()=>{if(!(!n||!r)){m(!0);try{const{error:j}=await V.auth.refreshSession();if(j){console.error("Session refresh failed:",j),ae.error("Your session has expired. Please log in again.");return}if(i){const{error:C}=await V.functions.invoke("zoom-unregister",{body:{event_id:r.id}});if(C)throw C;ae.success("Successfully cancelled registration"),l(null),c(A=>A-1)}else{const{data:C,error:A}=await V.functions.invoke("zoom-register",{body:{event_id:r.id}});if(A)throw A;ae.success("Successfully registered for event!"),l({id:C.registration_id,zoom_join_url:C.zoom_join_url}),c(M=>M+1)}}catch(j){console.error("Registration error:",j),ae.error(i?"Failed to cancel registration":"Failed to register for event")}finally{m(!1)}}},x=j=>{var C,A,M;if(j.includes("iframe.mediadelivery.net")||j.includes("video.bunnycdn.com")){const I=j.match(/embed\/(\d+)\/([a-f0-9-]+)/);if(I)return`https://iframe.mediadelivery.net/embed/${I[1]}/${I[2]}?autoplay=false&preload=true`}if(j.includes("youtube.com")||j.includes("youtu.be")){const I=j.includes("youtu.be")?(C=j.split("youtu.be/")[1])==null?void 0:C.split("?")[0]:(A=j.split("v=")[1])==null?void 0:A.split("&")[0];if(I)return`https://www.youtube.com/embed/${I}`}if(j.includes("vimeo.com")){const I=(M=j.split("vimeo.com/")[1])==null?void 0:M.split("?")[0];if(I)return`https://player.vimeo.com/video/${I}`}return j};if(d)return e.jsx(Xs,{title:"Event",children:e.jsx("div",{className:"flex items-center justify-center py-16",children:e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent mx-auto mb-4"}),e.jsx("p",{className:"text-muted-foreground",children:"Loading event..."})]})})});if(!r)return e.jsx(Xs,{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($,{onClick:()=>t("/events"),className:"mt-4",children:"Back to Events"})]})});const y=R5(new Date(r.event_date)),v=r.capacity&&o>=r.capacity,_=(i==null?void 0:i.zoom_join_url)||r.zoom_link;return e.jsx(Xs,{title:r.title,children:e.jsxs("div",{className:"max-w-4xl mx-auto",children:[e.jsxs($,{variant:"ghost",className:"mb-6 gap-2",onClick:()=>t("/events"),children:[e.jsx(Ia,{className:"h-4 w-4"}),"Back to Events"]}),r.image_url&&e.jsxs("div",{className:"relative aspect-video rounded-xl overflow-hidden mb-6",children:[e.jsx("img",{src:r.image_url,alt:r.title,className:"w-full h-full object-cover"}),y&&e.jsx("div",{className:"absolute inset-0 bg-black/50 flex items-center justify-center",children:e.jsx(qe,{variant:"secondary",className:"text-lg px-4 py-2",children:"Event Ended"})})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-6",children:[e.jsxs("div",{className:"lg:col-span-2 space-y-6",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-start justify-between gap-4 mb-4",children:[e.jsx("h1",{className:"text-3xl font-bold text-foreground",children:r.title}),e.jsx(tV,{resourceType:"event",resourceId:r.id,resourceTitle:r.title})]}),r.description&&e.jsx("div",{className:"prose prose-sm max-w-none text-muted-foreground dark:prose-invert",dangerouslySetInnerHTML:{__html:r.description}})]}),r.video_url&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("h3",{className:"text-lg font-semibold flex items-center gap-2",children:[e.jsx(mm,{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:x(r.video_url),className:"absolute inset-0 w-full h-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0,title:"Event Preview Video"})})]})]}),e.jsx("div",{className:"space-y-4",children:e.jsx(we,{children:e.jsxs(De,{className:"p-6 space-y-4",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(ha,{className:"h-5 w-5 text-primary mt-0.5"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:new Intl.DateTimeFormat("en-US",{weekday:"long",year:"numeric",month:"long",day:"numeric",timeZone:"America/New_York"}).format(new Date(r.event_date))}),e.jsx("p",{className:"text-sm text-muted-foreground",children:nX(new Date(r.event_date))})]})]}),r.capacity&&e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Xn,{className:"h-5 w-5 text-primary mt-0.5"}),e.jsxs("div",{children:[e.jsxs("p",{className:"font-medium",children:[o," / ",r.capacity]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Registered"})]})]}),i&&e.jsxs("div",{className:"flex items-center gap-2 p-3 bg-green-500/10 rounded-lg",children:[e.jsx(nl,{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:[!y&&e.jsx(e.Fragment,{children:i?e.jsxs(e.Fragment,{children:[e.jsxs($,{className:"w-full gap-2",onClick:()=>window.open(_,"_blank"),children:[e.jsx(Ir,{className:"h-4 w-4"}),"Join Event"]}),e.jsxs($,{variant:"outline",className:"w-full",onClick:g,disabled:h,children:[h?e.jsx(Jt,{className:"h-4 w-4 animate-spin mr-2"}):null,"Cancel Registration"]})]}):e.jsx($,{className:"w-full gap-2",onClick:g,disabled:h||(v??!1),children:h?e.jsx(Jt,{className:"h-4 w-4 animate-spin"}):v?"Event Full":"Register Now"})}),y&&i&&e.jsxs($,{variant:"outline",className:"w-full gap-2",onClick:()=>window.open(r.zoom_link,"_blank"),children:[e.jsx(Ir,{className:"h-4 w-4"}),"View Recording"]})]})]})})})]})]})})}const Y8s=[{to:"/apps",label:"Home",end:!0},{to:"/apps/my-apps",label:"My Apps"},{to:"/apps/browse",label:"Browse Apps"},{to:"/apps/workflows",label:"Workflows",adminOnly:!0},{to:"/apps/connected",label:"Connected Apps"}];function Z8s(){const{isAdmin:s}=ks(),t=Y8s.filter(n=>!n.adminOnly||s);return e.jsx("div",{className:"-mx-4 px-4 sm:mx-0 sm:px-0 overflow-x-auto scrollbar-hide",children:e.jsx("nav",{className:"inline-flex gap-1 bg-muted/60 p-1 rounded-xl min-w-max",children:t.map(n=>e.jsx(JA,{to:n.to,end:n.end,className:({isActive:r})=>Ot("px-4 py-2 rounded-lg text-sm font-medium whitespace-nowrap transition-colors",r?"bg-card text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"),children:n.label},n.to))})})}const m5e=[{id:"market-listing",title:"Market a Listing",blurb:"Presentations, copy, pages and video",icon:ua,color:"bg-violet-500/15 text-violet-600"},{id:"follow-up",title:"Follow Up With My Database",blurb:"Emails, cards, mail and check-ins",icon:pn,color:"bg-emerald-500/15 text-emerald-600"},{id:"social-content",title:"Create Social Content",blurb:"Reels, posts and captions",icon:xm,color:"bg-rose-500/15 text-rose-600"},{id:"open-house",title:"Host an Open House",blurb:"Promote, sign in and follow up",icon:x2,color:"bg-sky-500/15 text-sky-600"},{id:"new-business",title:"Generate New Business",blurb:"Leads, expireds and by-owner sellers",icon:mc,color:"bg-amber-500/15 text-amber-600"},{id:"brand",title:"Build My Brand",blurb:"Your card, site, reviews and presence",icon:gd,color:"bg-teal-500/15 text-teal-600"}];m5e.reduce((s,t)=>({...s,[t.id]:t}),{});const X8s=[{id:"listings",label:"Listings"},{id:"database",label:"Database & Follow-Up"},{id:"leads",label:"Leads & Conversion"},{id:"social",label:"Social & Content"},{id:"open-houses",label:"Open Houses"},{id:"brand",label:"Brand & Presence"},{id:"ai",label:"AI Assistants"}],vIt=[{id:"scheduler",name:"LevelUp Scheduler",description:"Share your booking link, sync Google Calendar and let clients book you",icon:wm,path:"/mission-control/scheduler",color:"bg-blue-500/15 text-blue-600",adminOnly:!0,isNew:!0,goals:["follow-up","new-business","brand"],categories:["database","leads","brand"],keywords:["scheduler","calendar","booking link","book a meeting","appointments","calendly","availability"]},{id:"quickvid",name:"QuickVid",description:"Record and share personalized video messages",icon:ia,path:"/mission-control/video/record",color:"bg-rose-500/15 text-rose-600",popular:!0,goals:["follow-up","social-content","open-house"],categories:["database","social","open-houses"],keywords:["video","record a video","send a video","video email","screen record"]},{id:"smart-card",name:"Smart Card",description:"Your digital business card in one shareable link",icon:cv,path:"/mission-control/my-card",color:"bg-sky-500/15 text-sky-600",goals:["brand"],categories:["brand"],keywords:["business card","digital card","share my info","contact card"]},{id:"smart-presentations",name:"Smart Presentations",description:"Beautiful listing and buyer presentations",icon:hv,path:"/mission-control/presentations",color:"bg-amber-500/15 text-amber-600",goals:["market-listing","brand"],categories:["listings","brand"],keywords:["buyer presentation","listing presentation","pitch","slides"]},{id:"landing-pages",name:"Landing Pages",description:"Custom landing pages that capture leads",icon:ea,path:"/mission-control/landing-pages",color:"bg-emerald-500/15 text-emerald-600",goals:["market-listing","new-business","open-house"],categories:["listings","leads","open-houses"],keywords:["landing page","capture leads","promote an open house","single property site"]},{id:"guest-book",name:"Guest Book",description:"Digital open house sign-in that captures visitors",icon:wg,path:"/mission-control/guest-book",color:"bg-orange-500/15 text-orange-600",popular:!0,goals:["open-house","new-business"],categories:["open-houses","leads"],keywords:["open house sign in","sign-in sheet","visitors","host an open house"]},{id:"card-studio",name:"Card Studio",description:"Animated cards for birthdays and milestones",icon:kn,path:"/mission-control/card-studio",color:"bg-pink-500/15 text-pink-600",goals:["follow-up","social-content"],categories:["database","social"],keywords:["birthday card","anniversary","greeting","thank you card"]},{id:"direct-mail",name:"Direct Mail",description:"Send professional postcards to your contacts",icon:pn,path:"/mission-control/direct-mail",color:"bg-indigo-500/15 text-indigo-600",adminOnly:!0,beta:!0,goals:["follow-up","open-house"],categories:["database","open-houses"],keywords:["postcard","mailer","farming","direct mail"]},{id:"reelflow",name:"ReelFlow",description:"Turn property photos into cinematic reels with AI",icon:em,path:"/admin/beta/homereel",color:"bg-violet-500/15 text-violet-600",beta:!0,isNew:!0,goals:["market-listing","social-content"],categories:["listings","social","ai"],keywords:["create a reel","video from photos","instagram","cinematic"]},{id:"mass-emails",name:"Mass Emails",description:"Send bulk email campaigns to your contacts",icon:Wr,path:"/admin/email-campaigns",color:"bg-teal-500/15 text-teal-600",beta:!0,goals:["follow-up","open-house"],categories:["database","open-houses"],keywords:["email my database","bulk email","campaign","blast","invite"]},{id:"listing-studio",name:"Listing Studio",description:"AI MLS descriptions, luxury copy and open house blurbs",icon:WN,path:"/mission-control/listing-studio",color:"bg-fuchsia-500/15 text-fuchsia-600",isNew:!0,goals:["market-listing","social-content"],categories:["listings","social","ai"],keywords:["mls description","write listing copy","captions","ai writing"]},{id:"website-apps",name:"Website Apps",description:"Drop-in conversion widgets for your website",icon:nB,path:"/website-apps",color:"bg-cyan-500/15 text-cyan-600",isNew:!0,goals:["new-business","brand"],categories:["leads","brand"],keywords:["website widget","video greeter","lead magnet","pop up"]},{id:"newsletter-pro",name:"Newsletter Pro",description:"Branded newsletters for your database",icon:N2,path:"/newsletters",color:"bg-yellow-500/15 text-yellow-600",goals:["follow-up"],categories:["database"],keywords:["newsletter","monthly email","market update"]},{id:"weekly-reels",name:"Weekly Reels",description:"5 personalized Reel scripts every Monday morning",icon:em,path:"/weekly-reels",color:"bg-orange-500/15 text-orange-600",isNew:!0,requiresWeeklyReels:!0,goals:["social-content"],categories:["social","ai"],keywords:["reel scripts","instagram","content ideas","social posts"]},{id:"cma",name:"CMA Reports",description:"Interactive CMAs with live comps you can share",icon:Ul,path:"/mission-control/cma",color:"bg-blue-500/15 text-blue-600",isNew:!0,requiresLeadSiteMLS:!0,goals:["market-listing","new-business"],categories:["listings","leads"],keywords:["cma","comps","home value","pricing"]},{id:"listing-presentation-studio",name:"Listing Presentation Studio",description:"A branded 12-page seller presentation in minutes",icon:hv,path:"/apps/listing-presentation-studio",color:"bg-emerald-500/15 text-emerald-600",isNew:!0,popular:!0,goals:["market-listing"],categories:["listings"],keywords:["make a listing presentation","seller presentation","pdf","pre-listing"]},{id:"listing-revival",name:"Listing Revival",description:"Turn expired listings into appointments",icon:kn,path:"/apps/listing-revival",color:"bg-amber-500/15 text-amber-600",isNew:!0,goals:["new-business"],categories:["leads","listings","ai"],keywords:["expired listing","expired","withdrawn","revival letter"]},{id:"fsbo-breakthrough",name:"By-Owner Breakthrough",description:"Convert FSBO sellers with letters, guides and pages",icon:ua,path:"/apps/fsbo-breakthrough",color:"bg-[#5b8a5c]/15 text-[#5b8a5c]",isNew:!0,goals:["new-business"],categories:["leads","ai"],keywords:["fsbo","for sale by owner","by owner","convert fsbo"]}],Lut=vIt.reduce((s,t)=>({...s,[t.id]:t}),{}),Q8s={agent_review:{goals:["brand","new-business"],categories:["brand","leads"],keywords:["reviews","get more reviews","testimonials","reputation"]},sigflow:{goals:["brand","follow-up"],categories:["brand","database"],keywords:["email signature","signature","branding"]},social_autopilot:{goals:["social-content","brand"],categories:["social","brand"],keywords:["social posts","schedule posts","autopilot","facebook","instagram"]}};function J8s(s){return Q8s[s]??{goals:[],categories:[],keywords:[]}}const gKe=[{id:"new-listing-launch",title:"New Listing Launch",description:"Everything you need to take a new listing to market.",outcome:"A listing that is presented, promoted and seen",namePrompt:"What listing is this for?",namePlaceholder:"520 Harlan Drive",icon:ua,color:"bg-violet-500/15 text-violet-600",steps:[{key:"presentation",title:"Build the listing presentation",detail:"Create your branded seller presentation.",toolId:"listing-presentation-studio"},{key:"copy",title:"Write the listing copy",detail:"Generate the MLS description and marketing copy.",toolId:"listing-studio"},{key:"page",title:"Create the property page",detail:"Publish a landing page for the listing.",toolId:"landing-pages"},{key:"reel",title:"Make a reel",detail:"Turn the photos into a cinematic video.",toolId:"reelflow"},{key:"email",title:"Email your database",detail:"Announce the listing to your contacts.",toolId:"mass-emails"},{key:"video",title:"Send a personal video",detail:"Record a quick note for your top contacts.",toolId:"quickvid"}]},{id:"open-house-success",title:"Open House Success Kit",description:"Plan, promote, capture visitors, and follow up.",outcome:"A full open house with every visitor captured",namePrompt:"Which open house is this for?",namePlaceholder:"Sunday open house — 12 Oak St",icon:x2,color:"bg-sky-500/15 text-sky-600",steps:[{key:"page",title:"Build the open house page",detail:"Create a page with the date, time and details.",toolId:"landing-pages"},{key:"invite",title:"Invite your database",detail:"Send the invitation email.",toolId:"mass-emails"},{key:"signin",title:"Set up sign-in",detail:"Turn on the digital guest book for the event.",toolId:"guest-book"},{key:"followup",title:"Follow up with visitors",detail:"Send a personal video to everyone who came.",toolId:"quickvid"}]},{id:"database-touchpoint",title:"Database Touchpoint",description:"Get a valuable message in front of your whole database.",outcome:"Your sphere hears from you this month",namePrompt:"What month or theme is this for?",namePlaceholder:"August market update",icon:Xn,color:"bg-emerald-500/15 text-emerald-600",steps:[{key:"pick",title:"Pick your message",detail:"Start from a newsletter or market update.",toolId:"newsletter-pro"},{key:"personal",title:"Add a personal touch",detail:"Record a short video intro.",toolId:"quickvid"},{key:"send",title:"Send it out",detail:"Deliver it to your contacts.",toolId:"mass-emails"},{key:"cards",title:"Celebrate milestones",detail:"Send cards to anyone with a milestone this month.",toolId:"card-studio"}]}],UO=gKe.reduce((s,t)=>({...s,[t.id]:t}),{});function eOs({goal:s,onSelect:t}){const n=s.icon;return e.jsxs("button",{type:"button",onClick:()=>t(s),className:"group text-left bg-card border border-border rounded-2xl p-5 transition-all hover:border-primary/40 hover:shadow-md focus:outline-none focus-visible:ring-2 focus-visible:ring-primary",children:[e.jsx("div",{className:Ot("w-12 h-12 rounded-xl flex items-center justify-center mb-4",s.color),children:e.jsx(n,{className:"h-6 w-6"})}),e.jsx("h3",{className:"font-semibold text-foreground group-hover:text-primary transition-colors",children:s.title}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:s.blurb})]})}function tOs({item:s,isFavorite:t,onOpen:n,onToggleFavorite:r}){const a=typeof s.icon=="string"?null:s.icon,i=!!s.lockedFeature,l=i?{label:"Upgrade",className:"bg-muted text-muted-foreground"}:s.isNew?{label:"New",className:"bg-primary/10 text-primary"}:s.beta?{label:"Beta",className:"bg-amber-500/15 text-amber-600"}:s.popular?{label:"Popular",className:"bg-emerald-500/15 text-emerald-600"}:s.kind==="app"?{label:"Connected",className:"bg-muted text-muted-foreground"}:null;return e.jsxs("div",{role:"button",tabIndex:0,onClick:()=>n(s),onKeyDown:o=>{(o.key==="Enter"||o.key===" ")&&(o.preventDefault(),n(s))},className:Ot("group h-full text-left bg-card border border-border rounded-2xl p-5 flex flex-col gap-3 cursor-pointer transition-all hover:border-primary/40 hover:shadow-md focus:outline-none focus-visible:ring-2 focus-visible:ring-primary",i&&"opacity-80"),children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:Ot("flex-shrink-0 w-12 h-12 rounded-xl flex items-center justify-center text-2xl",s.color),children:i?e.jsx(fu,{className:"h-5 w-5"}):a?e.jsx(a,{className:"h-6 w-6"}):e.jsx("span",{children:s.icon})}),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-foreground group-hover:text-primary transition-colors",children:s.name}),l&&e.jsx("span",{className:Ot("text-[11px] font-medium px-2 py-0.5 rounded-full",l.className),children:l.label})]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1 line-clamp-2",children:s.description})]}),e.jsx("button",{type:"button","aria-label":t?`Remove ${s.name} from favorites`:`Add ${s.name} to favorites`,onClick:o=>{o.stopPropagation(),r(s)},className:Ot("flex-shrink-0 p-2 -m-1 rounded-lg transition-colors",t?"text-primary":"text-muted-foreground/40 hover:text-primary"),children:e.jsx(jy,{className:Ot("h-5 w-5",t&&"fill-current")})})]}),e.jsx("div",{className:"mt-auto pt-1",children:e.jsx("span",{className:"text-sm font-medium text-primary",children:i?"Request access →":"Open →"})})]})}function iO({items:s,isFavorite:t,onOpen:n,onToggleFavorite:r}){return e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4",children:s.map(a=>e.jsx(tOs,{item:a,isFavorite:t(a),onOpen:n,onToggleFavorite:r},a.key))})}const sOs="bg-primary/10 text-primary";function Ree(){const{user:s,isAdmin:t}=ks(),n=rA(),r=Jn(),{hasAccess:a}=I3e(),[i,l]=k.useState([]),[o,c]=k.useState(!0),[d,u]=k.useState(new Set),[h,m]=k.useState(new Set),[p,g]=k.useState(!1),[x,y]=k.useState([]),[v,_]=k.useState(""),j=k.useCallback(async()=>{if(s!=null&&s.id)try{const[{data:H},{data:Y},{data:se},{data:ee},{data:oe},{data:me},{data:Q}]=await Promise.all([V.from("user_tags").select("tag").eq("user_id",s.id),V.from("app_tiles").select("*").order("name"),V.from("user_favorites").select("app_id").eq("user_id",s.id),V.from("user_tool_favorites").select("tool_id").eq("user_id",s.id),V.from("lead_sites").select("id, mls_provider_id, no_mls_mode, is_active").eq("agent_id",s.id),V.from("activity_logs").select("app_id, app_name, launched_at").eq("user_id",s.id).order("launched_at",{ascending:!1}).limit(40),V.from("profiles").select("name").eq("id",s.id).maybeSingle()]),te=(H||[]).map(he=>he.tag);g((oe||[]).some(he=>he.is_active&&he.mls_provider_id&&!he.no_mls_mode)),u(new Set((se||[]).map(he=>he.app_id))),m(new Set((ee||[]).map(he=>he.tool_id)));const le=(Y||[]).filter(he=>he.app_id==="newsletter_studio"?!1:!he.required_tags||he.required_tags.length===0?!0:he.required_tags.some(Se=>te.includes(Se)));l(le.sort((he,Se)=>he.name==="LevelUp Members Portal"?-1:Se.name==="LevelUp Members Portal"?1:0));const fe=new Set,_e=[];for(const he of me||[])if(!(!he.app_id||fe.has(he.app_id))&&(fe.add(he.app_id),_e.push({appId:he.app_id,name:he.app_name,at:he.launched_at}),_e.length>=8))break;y(_e);const ve=Q==null?void 0:Q.name;_(ve?ve.trim().split(" ")[0]:"")}catch(H){console.error("Error loading app catalog:",H),ae.error("Failed to load apps")}finally{c(!1)}},[s==null?void 0:s.id]);k.useEffect(()=>{j()},[j]);const C=k.useMemo(()=>{const H=oe=>{if(!n.isRestricted)return null;const me=yms(oe);return me&&!n.hasFeature(me)?me:null},Y=vIt.filter(oe=>!(oe.adminOnly&&!t||oe.requiresLeadSiteMLS&&!p&&!t||oe.requiresWeeklyReels&&!a)).map(oe=>({key:`tool:${oe.id}`,kind:"tool",id:oe.id,name:oe.name,description:oe.description,icon:oe.icon,color:oe.color,isNew:oe.isNew,beta:oe.beta,popular:oe.popular,goals:oe.goals,categories:oe.categories,keywords:oe.keywords,lockedFeature:H(oe.id),tool:oe})),se={AgentReview:"marketing_studio",SigFlow:"marketing_studio",Staging_Studio:"marketing_studio",social_autopilot:"social",newsletter_studio:"newsletter"},ee=i.map(oe=>{const me=J8s(oe.app_id),Q=se[oe.app_id];return{key:`app:${oe.app_id}`,kind:"app",id:oe.app_id,name:oe.name,description:oe.description,icon:oe.icon,color:sOs,goals:me.goals,categories:me.categories,keywords:me.keywords,lockedFeature:n.isRestricted&&Q&&!n.hasFeature(Q)?Q:null,tile:oe}});return[...Y,...ee]},[i,t,p,a,n.isRestricted,n.features]),A=k.useCallback(H=>{var Y;return H.kind==="tool"?h.has(H.id):d.has(((Y=H.tile)==null?void 0:Y.id)??"")},[h,d]),M=k.useMemo(()=>C.filter(A),[C,A]),I=k.useMemo(()=>{const H=new Map(C.map(Y=>[Y.id,Y]));return x.map(Y=>H.get(Y.appId)).filter(Boolean)},[C,x]),P=k.useMemo(()=>C.filter(H=>H.kind==="app"),[C]),R=k.useCallback(async(H,Y)=>{try{await V.from("activity_logs").insert({user_id:s==null?void 0:s.id,app_id:H,app_name:Y,user_agent:navigator.userAgent})}catch{}},[s==null?void 0:s.id]),O=k.useCallback(async H=>{var se;try{const ee=new URL(H.target_url);if(new Set([window.location.hostname,"dashboard.relevelup.com"]).has(ee.hostname)){await R(H.app_id,H.name),r(ee.pathname+ee.search+ee.hash);return}}catch{}const Y=window.open("about:blank","_blank");try{const{data:ee,error:oe}=await V.auth.getSession();if(oe||!ee.session){Y==null||Y.close(),ae.error("Session expired. Please refresh the page and try again.");return}await R(H.app_id,H.name);const{data:me,error:Q}=await V.functions.invoke("sso-launch",{body:{app_id:H.app_id},headers:{Authorization:`Bearer ${ee.session.access_token}`}});if(Q)throw Q;me!=null&&me.redirect_url?Y&&!Y.closed?(Y.location.href=me.redirect_url,(se=Y.focus)==null||se.call(Y)):window.location.assign(me.redirect_url):(Y==null||Y.close(),ae.error("Launch link unavailable"))}catch(ee){Y==null||Y.close(),console.error("Error launching app:",ee),ae.error("Failed to launch app. Please try again.")}},[R,r]),B=k.useCallback(H=>{if(H.lockedFeature){r(`/upgrade/${H.lockedFeature}`);return}if(H.kind==="app"&&H.tile){O(H.tile);return}H.tool&&(R(H.tool.id,H.tool.name),r(H.tool.path))},[O,R,r]),U=k.useCallback(async H=>{var Q;if(!(s!=null&&s.id))return;const Y=A(H),se=H.kind==="tool"?"user_tool_favorites":"user_favorites",ee=H.kind==="tool"?"tool_id":"app_id",oe=H.kind==="tool"?H.id:(Q=H.tile)==null?void 0:Q.id;if(!oe)return;const me=H.kind==="tool"?m:u;me(te=>{const le=new Set(te);return Y?le.delete(oe):le.add(oe),le});try{if(Y){const{error:te}=await V.from(se).delete().eq("user_id",s.id).eq(ee,oe);if(te)throw te}else{const{error:te}=await V.from(se).insert({user_id:s.id,[ee]:oe});if(te)throw te}}catch(te){console.error("Error toggling favorite:",te),ae.error("Failed to update favorites"),me(le=>{const fe=new Set(le);return Y?fe.add(oe):fe.delete(oe),fe})}},[A,s==null?void 0:s.id]),G=k.useCallback((H,Y=C)=>{const se=H.trim().toLowerCase();if(!se)return Y;const ee=se.split(/\s+/);return Y.filter(oe=>{const me=[oe.name,oe.description,...oe.keywords,...oe.categories,...oe.goals].join(" ").toLowerCase();return ee.every(Q=>me.includes(Q))||me.includes(se)})},[C]);return{loading:o,items:C,favoriteItems:M,recentItems:I,connectedItems:P,recent:x,firstName:v,isFavorite:A,toggleFavorite:U,openItem:B,search:G,reload:j}}function PLe(s){return{id:s.id,workflow_id:s.workflow_id,run_name:s.run_name,status:s.status==="completed"?"completed":"in_progress",step_state:s.step_state??{},completed_at:s.completed_at,last_activity_at:s.last_activity_at,created_at:s.created_at}}function LAe(s){const t=UO[s.workflow_id],n=(t==null?void 0:t.steps.length)??0,r=t?t.steps.filter(a=>s.step_state[a.key]).length:Object.keys(s.step_state).length;return{touched:r,total:n,pct:n?Math.round(r/n*100):0}}function RAe(){const{user:s}=ks(),[t,n]=k.useState([]),[r,a]=k.useState(!0),i=k.useCallback(async()=>{if(s!=null&&s.id)try{const{data:m,error:p}=await V.from("workflow_runs").select("*").eq("user_id",s.id).order("last_activity_at",{ascending:!1});if(p)throw p;n((m||[]).map(PLe))}catch(m){console.error("Error loading workflow runs:",m)}finally{a(!1)}},[s==null?void 0:s.id]);k.useEffect(()=>{i()},[i]);const l=k.useCallback(async(m,p)=>{var g;if(!(s!=null&&s.id))return null;try{const{data:x,error:y}=await V.from("workflow_runs").insert({user_id:s.id,workflow_id:m,run_name:p.trim()||((g=UO[m])==null?void 0:g.title)||"Untitled"}).select("*").single();if(y)throw y;const v=PLe(x);return n(_=>[v,..._]),v}catch(x){return console.error("Error starting workflow:",x),ae.error("Could not start this workflow"),null}},[s==null?void 0:s.id]),o=k.useCallback(async(m,p)=>{const g={...p,last_activity_at:new Date().toISOString()};n(y=>y.map(v=>v.id===m?PLe({...v,...g}):v));const{error:x}=await V.from("workflow_runs").update(g).eq("id",m);x&&(console.error("Error updating workflow run:",x),ae.error("Could not save your progress"))},[]),c=k.useCallback(async(m,p,g)=>{const x={...m.step_state};g?x[p]=g:delete x[p];const y=UO[m.workflow_id],v=y?y.steps.every(_=>x[_.key]):!1;await o(m.id,{step_state:x,status:v?"completed":"in_progress",completed_at:v?new Date().toISOString():null}),v&&m.status!=="completed"&&ae.success("Workflow complete — nice work!")},[o]),d=k.useCallback((m,p)=>o(m.id,{run_name:p.trim()}),[o]),u=k.useCallback(m=>o(m.id,{status:"in_progress",completed_at:null}),[o]),h=k.useCallback(async m=>{n(g=>g.filter(x=>x.id!==m));const{error:p}=await V.from("workflow_runs").delete().eq("id",m);p&&(console.error("Error deleting workflow run:",p),ae.error("Could not delete this workflow"))},[]);return{runs:t,loading:r,activeRuns:t.filter(m=>m.status==="in_progress"),completedRuns:t.filter(m=>m.status==="completed"),startRun:l,setStep:c,renameRun:d,reopenRun:u,deleteRun:h,reload:i}}function nOs(){const s=Number(new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",hour:"numeric",hour12:!1}).format(new Date));return s<12?"Good morning":s<18?"Good afternoon":"Good evening"}function rOs(){const s=Jn(),{items:t,firstName:n,recentItems:r,favoriteItems:a,isFavorite:i,toggleFavorite:l,openItem:o,search:c}=Ree(),{isAdmin:d}=ks(),{activeRuns:u}=RAe(),h=d?u:[],[m,p]=k.useState(""),g=k.useMemo(()=>m.trim()?c(m).slice(0,8):[],[m,c]),x=k.useMemo(()=>{const v=new Set(r.map(C=>C.id)),_=[],j=C=>{for(const A of C){if(_.length>=4)break;_.some(M=>M.key===A.key)||_.push(A)}};return j(a.filter(C=>!v.has(C.id))),j(t.filter(C=>C.isNew&&!v.has(C.id))),j(t.filter(C=>C.popular&&!v.has(C.id))),_},[t,a,r]),y=v=>s(`/apps/browse?goal=${v.id}`);return e.jsxs("div",{className:"space-y-8",children:[e.jsxs("div",{children:[e.jsxs("h1",{className:"text-2xl sm:text-3xl font-bold text-foreground",children:[nOs(),n?`, ${n}`:""]}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"What do you want to accomplish today?"}),e.jsxs("div",{className:"relative mt-5 max-w-2xl",children:[e.jsx(Yr,{className:"absolute left-4 top-1/2 -translate-y-1/2 h-5 w-5 text-muted-foreground"}),e.jsx(be,{value:m,onChange:v=>p(v.target.value),onKeyDown:v=>{v.key==="Enter"&&m.trim()&&s(`/apps/browse?q=${encodeURIComponent(m.trim())}`)},placeholder:"Search apps or tell us what you want to do…",className:"pl-12 h-14 text-base rounded-2xl"})]}),m.trim()&&e.jsx("div",{className:"mt-4 max-w-2xl bg-card border border-border rounded-2xl divide-y divide-border overflow-hidden",children:g.length===0?e.jsxs("p",{className:"p-4 text-sm text-muted-foreground",children:["Nothing matched “",m,"”. Try “open house”, “email my database” or “reel”."]}):g.map(v=>{const _=typeof v.icon=="string"?null:v.icon;return e.jsxs("button",{type:"button",onClick:()=>o(v),className:"w-full flex items-center gap-3 p-4 text-left hover:bg-muted/50 transition-colors",children:[e.jsx("span",{className:Ot("w-10 h-10 rounded-lg flex items-center justify-center text-xl flex-shrink-0",v.color),children:_?e.jsx(_,{className:"h-5 w-5"}):v.icon}),e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:"block font-medium text-foreground",children:v.name}),e.jsx("span",{className:"block text-sm text-muted-foreground truncate",children:v.description})]})]},v.key)})})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-8",children:[e.jsxs("div",{className:"lg:col-span-2 space-y-8",children:[e.jsxs("section",{children:[e.jsx("h2",{className:"text-lg font-semibold text-foreground mb-4",children:"Start with a goal"}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:m5e.map(v=>e.jsx(eOs,{goal:v,onSelect:y},v.id))})]}),(h.length>0||r.length>0)&&e.jsxs("section",{children:[e.jsxs("h2",{className:"text-lg font-semibold text-foreground mb-4 flex items-center gap-2",children:[e.jsx(sa,{className:"h-4 w-4 text-muted-foreground"})," Continue working"]}),h.length>0&&e.jsx("div",{className:"space-y-3 mb-4",children:h.slice(0,2).map(v=>{const _=UO[v.workflow_id],j=LAe(v);return e.jsxs("button",{type:"button",onClick:()=>s(`/apps/workflows/${v.id}`),className:"w-full text-left bg-card border border-border rounded-2xl p-4 hover:border-primary/40 transition-colors",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium text-foreground truncate",children:v.run_name}),e.jsxs("p",{className:"text-sm text-muted-foreground truncate",children:[_==null?void 0:_.title," · Step ",Math.min(j.touched+1,j.total)," of ",j.total]})]}),e.jsx(xi,{className:"h-4 w-4 text-primary flex-shrink-0"})]}),e.jsx("div",{className:"h-1.5 rounded-full bg-muted overflow-hidden mt-3",children:e.jsx("div",{className:"h-full bg-primary",style:{width:`${j.pct}%`}})})]},v.id)})}),r.length>0&&e.jsx("div",{className:"flex gap-3 overflow-x-auto pb-2 -mx-4 px-4 sm:mx-0 sm:px-0 scrollbar-hide",children:r.slice(0,6).map(v=>{const _=typeof v.icon=="string"?null:v.icon;return e.jsxs("button",{type:"button",onClick:()=>o(v),className:"flex-shrink-0 w-44 bg-card border border-border rounded-2xl p-4 text-left hover:border-primary/40 transition-colors",children:[e.jsx("span",{className:Ot("w-10 h-10 rounded-lg flex items-center justify-center text-xl mb-3",v.color),children:_?e.jsx(_,{className:"h-5 w-5"}):v.icon}),e.jsx("span",{className:"block font-medium text-sm text-foreground truncate",children:v.name}),e.jsx("span",{className:"block text-xs text-muted-foreground",children:"Open again"})]},v.key)})})]})]}),x.length>0&&e.jsxs("aside",{className:"space-y-4",children:[e.jsxs("h2",{className:"text-lg font-semibold text-foreground flex items-center gap-2",children:[e.jsx(kn,{className:"h-4 w-4 text-primary"})," Recommended for you"]}),e.jsx("div",{className:"space-y-3",children:x.map(v=>{const _=typeof v.icon=="string"?null:v.icon;return e.jsxs("button",{type:"button",onClick:()=>o(v),className:"w-full flex items-start gap-3 bg-card border border-border rounded-2xl p-4 text-left hover:border-primary/40 transition-colors",children:[e.jsx("span",{className:Ot("w-10 h-10 rounded-lg flex items-center justify-center text-xl flex-shrink-0",v.color),children:_?e.jsx(_,{className:"h-5 w-5"}):v.icon}),e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:"block font-medium text-foreground",children:v.name}),e.jsx("span",{className:"block text-sm text-muted-foreground line-clamp-2",children:v.description})]})]},v.key)})}),e.jsx($,{variant:"outline",className:"w-full",onClick:()=>s("/apps/browse"),children:"Browse all apps"})]})]}),a.length>0&&e.jsxs("section",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("h2",{className:"text-lg font-semibold text-foreground",children:"Your favorites"}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>s("/apps/my-apps"),children:"View all"})]}),e.jsx(iO,{items:a.slice(0,6),isFavorite:i,onOpen:o,onToggleFavorite:l})]})]})}function bIt({workflow:s,activeRun:t,onStart:n,onResume:r}){const a=s.icon,i=t?LAe(t):null;return e.jsxs("div",{className:"bg-card border border-border rounded-2xl p-5 flex flex-col gap-4 h-full",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:Ot("w-12 h-12 rounded-xl flex items-center justify-center flex-shrink-0",s.color),children:e.jsx(a,{className:"h-6 w-6"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("h3",{className:"font-semibold text-foreground",children:s.title}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:s.description})]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx(Gr,{className:"h-3.5 w-3.5"}),e.jsxs("span",{children:[s.steps.length," steps · ",s.outcome]})]}),t&&i?e.jsxs("div",{className:"mt-auto space-y-3",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between text-xs text-muted-foreground mb-1",children:[e.jsx("span",{className:"truncate pr-2",children:t.run_name}),e.jsxs("span",{className:"flex-shrink-0",children:["Step ",Math.min(i.touched+1,i.total)," of ",i.total]})]}),e.jsx("div",{className:"h-2 rounded-full bg-muted overflow-hidden",children:e.jsx("div",{className:"h-full bg-primary transition-all",style:{width:`${i.pct}%`}})})]}),e.jsxs($,{className:"w-full",onClick:()=>r(t),children:["Continue ",e.jsx(xi,{className:"h-4 w-4 ml-1"})]})]}):e.jsx("div",{className:"mt-auto",children:e.jsxs($,{className:"w-full",onClick:()=>n(s),children:["Start Workflow ",e.jsx(xi,{className:"h-4 w-4 ml-1"})]})})]})}function _It({workflow:s,onClose:t,onStart:n}){const[r,a]=k.useState(""),[i,l]=k.useState(!1);k.useEffect(()=>{a(""),l(!1)},[s==null?void 0:s.id]);const o=async()=>{s&&(l(!0),await n(s,r.trim()||s.title),l(!1))};return e.jsx(zs,{open:!!s,onOpenChange:c=>!c&&t(),children:e.jsxs(Rs,{className:"sm:max-w-md",children:[e.jsxs(Vs,{children:[e.jsx($s,{children:s==null?void 0:s.title}),e.jsxs(Cr,{children:[s==null?void 0:s.steps.length," steps · your progress saves automatically so you can come back any time."]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"workflow-run-name",children:s==null?void 0:s.namePrompt}),e.jsx(be,{id:"workflow-run-name",value:r,onChange:c=>a(c.target.value),placeholder:s==null?void 0:s.namePlaceholder,onKeyDown:c=>{c.key==="Enter"&&o()},autoFocus:!0}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"This is just so you recognize it later. You can change it any time."})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:t,disabled:i,children:"Cancel"}),e.jsx($,{onClick:o,disabled:i,children:i?"Starting…":"Start workflow"})]})]})})}function aOs(){const s=Jn(),[t,n]=Jc(),{items:r,isFavorite:a,toggleFavorite:i,openItem:l,search:o}=Ree(),{isAdmin:c}=ks(),{activeRuns:d,startRun:u}=RAe(),h=t.get("goal"),m=t.get("category")??null,[p,g]=k.useState(t.get("q")??""),[x,y]=k.useState(null);k.useEffect(()=>{g(t.get("q")??"")},[t]);const v=(M,I)=>{const P=new URLSearchParams(t);I?P.set(M,I):P.delete(M),n(P,{replace:!0})},_=()=>{const M=new URLSearchParams(t);M.delete("category"),M.delete("goal"),M.delete("q"),n(M,{replace:!0}),g("")},j=k.useMemo(()=>{let M=r;return h&&(M=M.filter(I=>I.goals.includes(h))),m&&(M=M.filter(I=>I.categories.includes(m))),p.trim()&&(M=o(p,M)),M},[r,h,m,p,o]),C=k.useMemo(()=>h||m||p.trim()?null:m5e.map(M=>({goal:M,apps:r.filter(I=>I.goals.includes(M.id))})).filter(M=>M.apps.length>0),[r,h,m,p]),A=h?m5e.find(M=>M.id===h):null;return e.jsxs("div",{className:"space-y-8",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Browse apps"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Every LevelUp app in one place, grouped by what it helps you get done."})]}),e.jsxs("div",{className:"relative max-w-2xl",children:[e.jsx(Yr,{className:"absolute left-4 top-1/2 -translate-y-1/2 h-5 w-5 text-muted-foreground"}),e.jsx(be,{value:p,onChange:M=>{g(M.target.value),v("q",M.target.value||null)},placeholder:"Search apps or tell us what you want to do…",className:"pl-12 h-12 rounded-2xl"})]}),e.jsx("div",{className:"-mx-4 px-4 sm:mx-0 sm:px-0 overflow-x-auto scrollbar-hide",children:e.jsxs("div",{className:"inline-flex gap-2 min-w-max pb-1",children:[e.jsx("button",{type:"button",onClick:_,className:Ot("px-4 py-2 rounded-full text-sm font-medium border transition-colors whitespace-nowrap",!m&&!h&&!p.trim()?"bg-primary text-primary-foreground border-primary":"bg-card text-muted-foreground border-border hover:text-foreground"),children:"All"}),X8s.map(M=>e.jsx("button",{type:"button",onClick:()=>v("category",m===M.id?null:M.id),className:Ot("px-4 py-2 rounded-full text-sm font-medium border transition-colors whitespace-nowrap",m===M.id?"bg-primary text-primary-foreground border-primary":"bg-card text-muted-foreground border-border hover:text-foreground"),children:M.label},M.id))]})}),A&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Showing apps for"}),e.jsxs("button",{type:"button",onClick:()=>v("goal",null),className:"text-sm font-medium px-3 py-1.5 rounded-full bg-primary/10 text-primary",children:[A.title," ✕"]})]}),c&&!p.trim()&&!m&&e.jsxs("section",{children:[e.jsx("h2",{className:"text-lg font-semibold text-foreground mb-4",children:"Popular workflows"}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:gKe.map(M=>e.jsx(bIt,{workflow:M,activeRun:d.find(I=>I.workflow_id===M.id),onStart:y,onResume:I=>s(`/apps/workflows/${I.id}`)},M.id))})]}),C?C.map(({goal:M,apps:I})=>e.jsxs("section",{children:[e.jsx("h2",{className:"text-lg font-semibold text-foreground mb-4",children:M.title}),e.jsx(iO,{items:I,isFavorite:a,onOpen:l,onToggleFavorite:i})]},M.id)):j.length>0?e.jsx(iO,{items:j,isFavorite:a,onOpen:l,onToggleFavorite:i}):e.jsxs("div",{className:"text-center py-16 bg-card border border-border rounded-2xl",children:[e.jsx(Yr,{className:"h-10 w-10 text-muted-foreground mx-auto mb-3"}),e.jsx("p",{className:"font-medium text-foreground",children:"No apps matched that"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Try a simpler phrase, like “open house” or “email”."})]}),e.jsx(_It,{workflow:x,onClose:()=>y(null),onStart:async(M,I)=>{const P=await u(M.id,I);y(null),P&&s(`/apps/workflows/${P.id}`)}})]})}function iOs(){const s=Jn(),{favoriteItems:t,recentItems:n,connectedItems:r,isFavorite:a,toggleFavorite:i,openItem:l}=Ree(),o=t.length===0&&n.length===0;return e.jsxs("div",{className:"space-y-8",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"My apps"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Your favorites and what you've used recently."})]}),o&&e.jsxs("div",{className:"text-center py-16 bg-card border border-border rounded-2xl",children:[e.jsx(jy,{className:"h-10 w-10 text-muted-foreground mx-auto mb-3"}),e.jsx("p",{className:"font-medium text-foreground",children:"Nothing saved yet"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1 max-w-sm mx-auto",children:"Tap the bookmark on any app to pin it here for quick access."}),e.jsx($,{className:"mt-4",onClick:()=>s("/apps/browse"),children:"Browse apps"})]}),t.length>0&&e.jsxs("section",{children:[e.jsxs("h2",{className:"text-lg font-semibold text-foreground mb-4 flex items-center gap-2",children:[e.jsx(jy,{className:"h-4 w-4 text-primary"})," Favorites"]}),e.jsx(iO,{items:t,isFavorite:a,onOpen:l,onToggleFavorite:i})]}),n.length>0&&e.jsxs("section",{children:[e.jsxs("h2",{className:"text-lg font-semibold text-foreground mb-4 flex items-center gap-2",children:[e.jsx(sa,{className:"h-4 w-4 text-muted-foreground"})," Recently used"]}),e.jsx(iO,{items:n,isFavorite:a,onOpen:l,onToggleFavorite:i})]}),r.length>0&&e.jsxs("section",{children:[e.jsxs("h2",{className:"text-lg font-semibold text-foreground mb-4 flex items-center gap-2",children:[e.jsx(Tw,{className:"h-4 w-4 text-muted-foreground"})," Activated for your account"]}),e.jsx(iO,{items:r,isFavorite:a,onOpen:l,onToggleFavorite:i})]})]})}function oOs(){const{connectedItems:s,isFavorite:t,toggleFavorite:n,openItem:r}=Ree();return e.jsxs("div",{className:"space-y-8",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Connected apps"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Partner apps that are activated for your LevelUp account. Open one and you're signed in automatically."})]}),s.length===0?e.jsxs("div",{className:"text-center py-16 bg-card border border-border rounded-2xl",children:[e.jsx(pd,{className:"h-10 w-10 text-muted-foreground mx-auto mb-3"}),e.jsx("p",{className:"font-medium text-foreground",children:"No connected apps yet"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1 max-w-sm mx-auto",children:"Connected apps appear here once they're activated for your account."})]}):e.jsx(iO,{items:s,isFavorite:t,onOpen:r,onToggleFavorite:n})]})}function lOs(){const s=Jn(),{activeRuns:t,completedRuns:n,startRun:r,reopenRun:a,deleteRun:i}=RAe(),[l,o]=k.useState(null);return e.jsxs("div",{className:"space-y-8",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Workflows"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Step-by-step playbooks that walk you through the whole job. Your progress saves as you go."})]}),t.length>0&&e.jsxs("section",{children:[e.jsx("h2",{className:"text-lg font-semibold text-foreground mb-4",children:"In progress"}),e.jsx("div",{className:"space-y-3",children:t.map(c=>{const d=UO[c.workflow_id],u=LAe(c);return e.jsxs("div",{className:"bg-card border border-border rounded-2xl p-4 flex items-center gap-4",children:[e.jsxs("button",{type:"button",onClick:()=>s(`/apps/workflows/${c.id}`),className:"flex-1 min-w-0 text-left",children:[e.jsx("p",{className:"font-medium text-foreground truncate",children:c.run_name}),e.jsxs("p",{className:"text-sm text-muted-foreground truncate",children:[d==null?void 0:d.title," · Step ",Math.min(u.touched+1,u.total)," of ",u.total]}),e.jsx("div",{className:"h-1.5 rounded-full bg-muted overflow-hidden mt-3",children:e.jsx("div",{className:"h-full bg-primary",style:{width:`${u.pct}%`}})})]}),e.jsx($,{onClick:()=>s(`/apps/workflows/${c.id}`),children:"Continue"})]},c.id)})})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-lg font-semibold text-foreground mb-4",children:"Start a workflow"}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:gKe.map(c=>e.jsx(bIt,{workflow:c,onStart:o,onResume:d=>s(`/apps/workflows/${d.id}`)},c.id))})]}),n.length>0&&e.jsxs("section",{children:[e.jsxs("h2",{className:"text-lg font-semibold text-foreground mb-4 flex items-center gap-2",children:[e.jsx(Gr,{className:"h-4 w-4 text-emerald-600"})," Completed"]}),e.jsx("div",{className:"space-y-2",children:n.map(c=>{var d;return e.jsxs("div",{className:"bg-card border border-border rounded-xl p-4 flex items-center gap-3",children:[e.jsxs("button",{type:"button",onClick:()=>s(`/apps/workflows/${c.id}`),className:"flex-1 min-w-0 text-left",children:[e.jsx("p",{className:"font-medium text-foreground truncate",children:c.run_name}),e.jsx("p",{className:"text-sm text-muted-foreground truncate",children:(d=UO[c.workflow_id])==null?void 0:d.title})]}),e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>a(c),children:[e.jsx(jm,{className:"h-4 w-4 mr-1"})," Reopen"]}),e.jsx($,{variant:"ghost",size:"icon","aria-label":"Delete workflow",onClick:()=>i(c.id),children:e.jsx(Un,{className:"h-4 w-4 text-muted-foreground"})})]},c.id)})})]}),e.jsx(_It,{workflow:l,onClose:()=>o(null),onStart:async(c,d)=>{const u=await r(c.id,d);o(null),u&&s(`/apps/workflows/${u.id}`)}})]})}function cOs(){const{runId:s}=oo(),t=Jn(),{runs:n,loading:r,setStep:a,renameRun:i,reopenRun:l,deleteRun:o}=RAe(),{items:c,openItem:d}=Ree(),[u,h]=k.useState(!1),[m,p]=k.useState(""),g=k.useMemo(()=>n.find(j=>j.id===s),[n,s]),x=g?UO[g.workflow_id]:void 0;if(r)return e.jsx("p",{className:"text-muted-foreground",children:"Loading…"});if(!g||!x)return e.jsxs("div",{className:"text-center py-16 bg-card border border-border rounded-2xl",children:[e.jsx("p",{className:"font-medium text-foreground",children:"This workflow isn't available"}),e.jsx($,{className:"mt-4",onClick:()=>t("/apps/workflows"),children:"Back to workflows"})]});const y=LAe(g),v=x.icon,_=j=>{if(!j)return;const C=c.find(M=>M.kind==="tool"&&M.id===j);if(C){d(C);return}const A=Lut[j];A&&t(A.path)};return e.jsxs("div",{className:"space-y-6 max-w-3xl",children:[e.jsxs("button",{type:"button",onClick:()=>t("/apps/workflows"),className:"inline-flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground",children:[e.jsx(Ia,{className:"h-4 w-4"})," All workflows"]}),e.jsxs("div",{className:"bg-card border border-border rounded-2xl p-5",children:[e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:Ot("w-12 h-12 rounded-xl flex items-center justify-center flex-shrink-0",x.color),children:e.jsx(v,{className:"h-6 w-6"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[u?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(be,{value:m,onChange:j=>p(j.target.value),autoFocus:!0,onKeyDown:j=>{j.key==="Enter"&&(i(g,m),h(!1))}}),e.jsx($,{size:"sm",onClick:()=>{i(g,m),h(!1)},children:"Save"})]}):e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h1",{className:"text-xl font-bold text-foreground truncate",children:g.run_name}),e.jsx("button",{type:"button","aria-label":"Rename workflow",onClick:()=>{p(g.run_name),h(!0)},className:"text-muted-foreground hover:text-foreground",children:e.jsx(ui,{className:"h-4 w-4"})})]}),e.jsxs("p",{className:"text-sm text-muted-foreground mt-1",children:[x.title," · ",x.description]})]})]}),e.jsxs("div",{className:"mt-5",children:[e.jsxs("div",{className:"flex items-center justify-between text-sm text-muted-foreground mb-2",children:[e.jsxs("span",{children:[y.touched," of ",y.total," steps done"]}),e.jsxs("span",{children:[y.pct,"%"]})]}),e.jsx("div",{className:"h-2 rounded-full bg-muted overflow-hidden",children:e.jsx("div",{className:"h-full bg-primary transition-all",style:{width:`${y.pct}%`}})})]}),g.status==="completed"&&e.jsxs("div",{className:"mt-4 flex items-center justify-between gap-3 rounded-xl bg-emerald-500/10 p-3",children:[e.jsxs("p",{className:"text-sm font-medium text-emerald-700 flex items-center gap-2",children:[e.jsx(Gr,{className:"h-4 w-4"})," Workflow complete"]}),e.jsx($,{variant:"outline",size:"sm",onClick:()=>l(g),children:"Reopen"})]})]}),e.jsx("ol",{className:"space-y-3",children:x.steps.map((j,C)=>{const A=g.step_state[j.key],M=j.toolId?Lut[j.toolId]:void 0,I=A==="done",P=A==="skipped";return e.jsx("li",{className:Ot("bg-card border rounded-2xl p-4 sm:p-5 transition-colors",I?"border-emerald-500/40":P?"border-border opacity-70":"border-border"),children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:Ot("w-9 h-9 rounded-full flex items-center justify-center flex-shrink-0 text-sm font-semibold",I?"bg-emerald-500 text-white":P?"bg-muted text-muted-foreground":"bg-primary/10 text-primary"),children:I?e.jsx(ma,{className:"h-4 w-4"}):C+1}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:Ot("font-medium text-foreground",(I||P)&&"line-through decoration-muted-foreground/40"),children:j.title}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:j.detail}),M&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["Uses ",M.name]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 mt-3",children:[M&&e.jsxs($,{size:"sm",onClick:()=>_(j.toolId),children:["Open ",M.name," ",e.jsx(Ir,{className:"h-3.5 w-3.5 ml-1"})]}),e.jsxs($,{size:"sm",variant:I?"secondary":"outline",onClick:()=>a(g,j.key,I?null:"done"),children:[e.jsx(ma,{className:"h-3.5 w-3.5 mr-1"}),I?"Done":"Mark done"]}),e.jsxs($,{size:"sm",variant:"ghost",onClick:()=>a(g,j.key,P?null:"skipped"),children:[e.jsx(QK,{className:"h-3.5 w-3.5 mr-1"}),P?"Un-skip":"Skip"]})]})]})]})},j.key)})}),e.jsx("div",{className:"pt-2",children:e.jsxs($,{variant:"ghost",size:"sm",className:"text-muted-foreground",onClick:()=>{o(g.id),t("/apps/workflows")},children:[e.jsx(Un,{className:"h-4 w-4 mr-1"})," Delete this workflow"]})})]})}const dOs=()=>{const{isAdmin:s}=ks();return e.jsx(Xs,{children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Z8s,{}),e.jsxs($Z,{children:[e.jsx(fs,{index:!0,element:e.jsx(rOs,{})}),e.jsx(fs,{path:"browse",element:e.jsx(aOs,{})}),e.jsx(fs,{path:"my-apps",element:e.jsx(iOs,{})}),e.jsx(fs,{path:"connected",element:e.jsx(oOs,{})}),s&&e.jsx(fs,{path:"workflows",element:e.jsx(lOs,{})}),s&&e.jsx(fs,{path:"workflows/:runId",element:e.jsx(cOs,{})}),e.jsx(fs,{path:"*",element:e.jsx(ab,{to:"/apps",replace:!0})})]})]})})},uOs=()=>{var j;const s=Jn(),{isAdmin:t}=ks(),[n,r]=k.useState(""),[a,i]=k.useState("all"),[l,o]=k.useState("all"),[c,d]=k.useState("grid"),{data:u=[]}=pt({queryKey:["template-categories"],queryFn:async()=>{const{data:C,error:A}=await V.from("template_categories").select("*").order("name");if(A)throw A;return C}}),{data:h=[]}=pt({queryKey:["template-types"],queryFn:async()=>{const{data:C,error:A}=await V.from("template_types").select("*").order("name");if(A)throw A;return C}}),{data:m=[],isLoading:p}=pt({queryKey:["canva-templates",t],queryFn:async()=>{const{data:C,error:A}=await V.from("canva_templates").select(` *, category:template_categories(id, name), type:template_types(id, name) `).order("publish_date",{ascending:!1});if(A)throw A;const{data:M,error:I}=await V.from("template_links").select("*").order("sort_order");if(I)throw I;const P=async Y=>{let ee=0;const oe=[];for(;;){const{data:me,error:Q}=await Y().range(ee,ee+1e3-1);if(Q)throw Q;if(!me||me.length===0||(oe.push(...me),me.length<1e3))break;ee+=1e3}return oe},R=await P(()=>V.from("template_likes").select("template_id")),O=await P(()=>V.from("template_comments").select("template_id")),B=new Map;R.forEach(Y=>{B.set(Y.template_id,(B.get(Y.template_id)||0)+1)});const U=new Map;O.forEach(Y=>{U.set(Y.template_id,(U.get(Y.template_id)||0)+1)});const G=new Map;return t&&(await P(()=>V.from("content_engagement_logs").select("resource_id").eq("resource_type","template").eq("action_type","view"))).forEach(se=>{G.set(se.resource_id,(G.get(se.resource_id)||0)+1)}),(C||[]).map(Y=>({...Y,links:(M||[]).filter(se=>se.template_id===Y.id)||[],likesCount:B.get(Y.id)||0,commentsCount:U.get(Y.id)||0,viewsCount:G.get(Y.id)||0}))}}),g=m.filter(C=>{var P;const A=C.name.toLowerCase().includes(n.toLowerCase())||((P=C.description)==null?void 0:P.toLowerCase().includes(n.toLowerCase())),M=a==="all"||C.category_id===a,I=l==="all"||C.type_id===l;return A&&M&&I}),x=()=>{r(""),i("all"),o("all")},y=n||a!=="all"||l!=="all",v=(j=[...m].sort((C,A)=>new Date(A.publish_date||A.created_at).getTime()-new Date(C.publish_date||C.created_at).getTime())[0])==null?void 0:j.id,_=C=>{s(`/templates/${C}`)};return e.jsx(Xs,{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"})]}),!p&&m.filter(C=>C.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(ri,{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:m.filter(C=>C.is_featured).slice(0,4).map(C=>e.jsxs(we,{className:"group overflow-hidden hover:shadow-lg transition-all duration-200 cursor-pointer relative",onClick:()=>_(C.id),children:[e.jsxs("div",{className:"aspect-[3/2] relative overflow-hidden bg-muted",children:[C.id===v&&e.jsx(qe,{className:"absolute top-2 left-2 z-10 font-bold border-0 hover:opacity-90",style:{backgroundColor:"#e8c369",color:"#3d2f0a"},children:"NEW!"}),C.preview_image_url?e.jsx("img",{src:C.preview_image_url,alt:C.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:C.name}),C.description&&e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2 mt-1",children:IZ(C.description)})]})]},C.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(Yr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search templates...",value:n,onChange:C=>r(C.target.value),className:"pl-9"})]}),e.jsxs(bs,{value:a,onValueChange:i,children:[e.jsx(ys,{className:"w-full sm:w-48",children:e.jsx(_s,{placeholder:"All Categories"})}),e.jsxs(vs,{children:[e.jsx(We,{value:"all",children:"All Categories"}),u.map(C=>e.jsx(We,{value:C.id,children:C.name},C.id))]})]}),e.jsxs(bs,{value:l,onValueChange:o,children:[e.jsx(ys,{className:"w-full sm:w-48",children:e.jsx(_s,{placeholder:"All Types"})}),e.jsxs(vs,{children:[e.jsx(We,{value:"all",children:"All Types"}),h.map(C=>e.jsx(We,{value:C.id,children:C.name},C.id))]})]}),e.jsxs("div",{className:"flex gap-2",children:[y&&e.jsx($,{variant:"outline",size:"sm",onClick:x,children:"Clear Filters"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx($,{variant:c==="grid"?"secondary":"outline",size:"icon",onClick:()=>d("grid"),className:"rounded-full",children:e.jsx(y0,{className:"h-4 w-4"})}),e.jsx($,{variant:c==="list"?"secondary":"outline",size:"icon",onClick:()=>d("list"),className:"rounded-full",children:e.jsx(Sy,{className:"h-4 w-4"})})]})]})]}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[g.length," template",g.length!==1?"s":""," found"]}),p&&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((C,A)=>e.jsx(we,{children:e.jsxs(De,{className:"p-4",children:[e.jsx(fn,{className:"aspect-[4/3] w-full rounded-lg mb-4"}),e.jsx(fn,{className:"h-5 w-3/4 mb-2"}),e.jsx(fn,{className:"h-4 w-full mb-4"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(fn,{className:"h-5 w-16"}),e.jsx(fn,{className:"h-5 w-20"})]})]})},A))}),!p&&g.length===0&&e.jsxs("div",{className:"text-center py-12",children:[e.jsx("div",{className:"text-muted-foreground mb-4",children:y?"No templates match your filters":"No templates available yet"}),y&&e.jsx($,{variant:"outline",onClick:x,children:"Clear Filters"})]}),!p&&g.length>0&&e.jsx("div",{className:c==="grid"?"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6":"space-y-4",children:g.map(C=>e.jsxs(we,{className:`group overflow-hidden hover:shadow-lg transition-all duration-200 cursor-pointer ${c==="list"?"flex flex-row":""}`,onClick:()=>_(C.id),children:[e.jsxs("div",{className:`relative overflow-hidden bg-muted ${c==="list"?"w-48 shrink-0":"aspect-[3/2]"}`,children:[C.id===v&&e.jsx(qe,{className:"absolute top-2 left-2 z-10 font-bold border-0 hover:opacity-90",style:{backgroundColor:"#e8c369",color:"#3d2f0a"},children:"NEW!"}),C.preview_image_url?e.jsx("img",{src:C.preview_image_url,alt:C.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"}),C.links.length>1&&e.jsx("div",{className:"absolute top-2 right-2",children:e.jsxs(qe,{variant:"secondary",className:"gap-1 bg-background/90 backdrop-blur-sm !text-secondary",children:[e.jsx(od,{className:"h-3 w-3"}),C.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:C.name}),C.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2 mb-3 flex-1",children:IZ(C.description)}),e.jsxs("div",{className:"flex flex-wrap gap-2 mb-3",children:[C.category&&e.jsx(qe,{variant:"secondary",className:"text-xs",children:C.category.name}),C.type&&e.jsx(qe,{variant:"outline",className:"text-xs",children:C.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(Ay,{className:"h-3.5 w-3.5"}),C.likesCount]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Vu,{className:"h-3.5 w-3.5"}),C.commentsCount]}),t&&e.jsxs("span",{className:"flex items-center gap-1",title:"Total views (admin only)",children:[e.jsx(ba,{className:"h-3.5 w-3.5"}),C.viewsCount]})]}),e.jsxs($,{size:"sm",className:"w-full gap-2",onClick:A=>{A.stopPropagation(),_(C.id)},children:[e.jsx(Ir,{className:"h-4 w-4"}),"View Template"]})]})]},C.id))})]})})};var hOs=Object.defineProperty,wIt=(s,t)=>hOs(s,"name",{value:t,configurable:!0}),Rut="horizontal",mOs=["horizontal","vertical"],fOs=k.forwardRef(wIt(function(t,n){const{decorative:r,orientation:a=Rut,...i}=t,l=jIt(a)?a:Rut,c=r?{role:"none"}:{"aria-orientation":l==="vertical"?l:void 0,role:"separator"};return e.jsx(hi.div,{"data-orientation":l,...c,...i,ref:n})},"Separator"));function jIt(s){return mOs.includes(s)}wIt(jIt,"isValidOrientation");var NIt=fOs;const Pc=k.forwardRef(({className:s,orientation:t="horizontal",decorative:n=!0,...r},a)=>e.jsx(NIt,{ref:a,decorative:n,orientation:t,className:Ot("shrink-0 bg-border",t==="horizontal"?"h-[1px] w-full":"h-full w-[1px]",s),...r}));Pc.displayName=NIt.displayName;const pOs=()=>{const{templateId:s}=oo(),t=Jn(),{user:n,isAdmin:r}=ks(),{toast:a}=Fi(),i=ls(),{trackEngagement:l}=Xq(),[o,c]=k.useState(""),{data:d,isLoading:u}=pt({queryKey:["template-detail",s],queryFn:async()=>{const{data:C,error:A}=await V.from("canva_templates").select(` *, category:template_categories(id, name), type:template_types(id, name) `).eq("id",s).single();if(A)throw A;const{data:M}=await V.from("template_links").select("*").eq("template_id",s).order("sort_order"),{data:I}=await V.from("template_guides").select("*").eq("template_id",s).order("sort_order");return{...C,links:M||[],guides:I||[]}},enabled:!!s}),{data:h=[]}=pt({queryKey:["template-linked-toolkits",s],queryFn:async()=>{const{data:C,error:A}=await V.from("resource_kit_templates").select("kit_id, resource_kits:kit_id(id, name, featured_image_url)").eq("template_id",s);if(A)throw A;return(C||[]).map(M=>M.resource_kits).filter(Boolean)},enabled:!!s});k.useEffect(()=>{d&&l("template",d.id,d.name,"view")},[d==null?void 0:d.id]);const{data:m=[]}=pt({queryKey:["template-likes",s],queryFn:async()=>{const{data:C,error:A}=await V.from("template_likes").select("*").eq("template_id",s);if(A)throw A;return C},enabled:!!s}),{data:p=[]}=pt({queryKey:["template-comments",s],queryFn:async()=>{const{data:C,error:A}=await V.from("template_comments").select("*").eq("template_id",s).order("created_at",{ascending:!1});if(A)throw A;const M=[...new Set(C.map(R=>R.user_id))],{data:I}=await V.from("profiles").select("id, name").in("id",M),P=new Map((I==null?void 0:I.map(R=>[R.id,R.name]))||[]);return C.map(R=>({...R,user_name:P.get(R.user_id)||"Unknown User"}))},enabled:!!s}),g=Nt({mutationFn:async C=>{const{error:A}=await V.from("template_comments").insert({template_id:s,user_id:n.id,content:C});if(A)throw A},onSuccess:()=>{i.invalidateQueries({queryKey:["template-comments",s]}),c(""),a({title:"Comment added!"})},onError:C=>{a({title:"Error adding comment",description:C.message,variant:"destructive"})}}),x=Nt({mutationFn:async C=>{const{error:A}=await V.from("template_comments").delete().eq("id",C);if(A)throw A},onSuccess:()=>{i.invalidateQueries({queryKey:["template-comments",s]}),a({title:"Comment deleted"})}}),y=Nt({mutationFn:async()=>{const C=m.find(A=>A.user_id===(n==null?void 0:n.id));if(C){const{error:A}=await V.from("template_likes").delete().eq("id",C.id);if(A)throw A}else{const{error:A}=await V.from("template_likes").insert({template_id:s,user_id:n.id});if(A)throw A}},onSuccess:()=>{i.invalidateQueries({queryKey:["template-likes",s]})}}),v=m.some(C=>C.user_id===(n==null?void 0:n.id)),_=C=>C.split(" ").map(A=>A[0]).join("").toUpperCase().slice(0,2),j=C=>{C.preventDefault(),!(!o.trim()||!n)&&g.mutate(o.trim())};return u?e.jsx(Xs,{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(Xs,{title:d.name,children:e.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[e.jsx($,{variant:"ghost",size:"sm",asChild:!0,className:"gap-2",children:e.jsxs(nr,{to:"/templates",children:[e.jsx(Ia,{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(qe,{variant:"secondary",children:d.category.name}),d.type&&e.jsx(qe,{variant:"outline",children:d.type.name})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[r&&e.jsx($,{variant:"outline",className:"gap-2 rounded-full",asChild:!0,children:e.jsxs(nr,{to:`/admin/templates?edit=${d.id}`,children:[e.jsx(ui,{className:"h-4 w-4"}),e.jsx("span",{children:"Edit"})]})}),e.jsx(tV,{resourceType:"template",resourceId:d.id,resourceTitle:d.name,size:"default",className:"rounded-full"}),e.jsxs($,{variant:v?"default":"outline",className:"gap-2 rounded-full",onClick:()=>y.mutate(),disabled:!n||y.isPending,children:[e.jsx(Ay,{className:`h-4 w-4 ${v?"fill-current":""}`}),m.length," ",m.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(we,{children:e.jsxs(De,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(od,{className:"h-4 w-4"}),d.links.length===1?"Template Link":"Template Links"]}),e.jsx("div",{className:"grid gap-2",children:d.links.map(C=>e.jsxs($,{variant:"outline",className:"w-full justify-between gap-2 h-auto py-3",onClick:()=>{l("template",d.id,d.name,"click_canva"),window.open(C.canva_share_link,"_blank")},children:[e.jsx("span",{className:"font-medium",children:C.title}),e.jsx(Ir,{className:"h-4 w-4 text-muted-foreground"})]},C.id))})]})}),d.video_url&&e.jsx(we,{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(we,{children:e.jsxs(De,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(ea,{className:"h-4 w-4"}),"Guide Files"]}),e.jsx("div",{className:"grid gap-2",children:d.guides.map(C=>e.jsxs($,{variant:"outline",className:"w-full justify-between gap-2 h-auto py-3",onClick:()=>{l("template",d.id,d.name,"click_pdf"),window.open(C.file_url,"_blank")},children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ea,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"font-medium",children:C.name}),C.file_size&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["(",(C.file_size/1024).toFixed(0)," KB)"]})]}),e.jsx(ji,{className:"h-4 w-4 text-muted-foreground"})]},C.id))})]})}),h.length>0&&e.jsx(we,{children:e.jsxs(De,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(bh,{className:"h-4 w-4"}),"Related Toolkits"]}),e.jsx("div",{className:"grid gap-2",children:h.map(C=>e.jsxs($,{variant:"outline",className:"w-full justify-start gap-3 h-auto py-3",onClick:()=>t(`/toolbox/${C.id}`),children:[C.featured_image_url?e.jsx("img",{src:C.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(bh,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx("span",{className:"font-medium",children:C.name})]},C.id))})]})}),e.jsx(Pc,{}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 text-lg",children:[e.jsx(Vu,{className:"h-5 w-5"}),"Comments (",p.length,")"]}),n?e.jsxs("form",{onSubmit:j,className:"flex gap-2",children:[e.jsx(Ls,{placeholder:"Add a comment...",value:o,onChange:C=>c(C.target.value),className:"min-h-[80px] resize-none flex-1"}),e.jsx($,{type:"submit",size:"icon",className:"h-10 w-10",disabled:!o.trim()||g.isPending,children:e.jsx(Wr,{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:p.length===0?e.jsx(we,{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!"})})}):p.map(C=>e.jsx(we,{children:e.jsx(De,{className:"pt-4 pb-4",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsx(Wa,{className:"h-10 w-10 flex-shrink-0",children:e.jsx(Ka,{className:"text-sm",children:_(C.user_name||"U")})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"font-medium",children:C.user_name}),e.jsx("span",{className:"text-sm text-muted-foreground",children:Zc(new Date(C.created_at),{addSuffix:!0})}),C.user_id===(n==null?void 0:n.id)&&e.jsx($,{variant:"ghost",size:"icon",className:"h-6 w-6 ml-auto",onClick:()=>x.mutate(C.id),children:e.jsx(Un,{className:"h-3 w-3 text-muted-foreground"})})]}),e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:C.content})]})]})})},C.id))})]})]})}):e.jsx(Xs,{title:"Templates",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(od,{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($,{asChild:!0,className:"mt-4",children:e.jsx(nr,{to:"/templates",children:"Back to Templates"})})]})})},Dut=({program:s,enrolled:t})=>{const{notOpenYet:n,closed:r,opensLabel:a}=fAe(s);return e.jsxs(we,{className:"group overflow-hidden border-border/60 transition-all hover:border-primary/40 hover:shadow-lg",children:[e.jsxs("div",{className:"relative aspect-[16/9] overflow-hidden bg-muted",children:[s.cover_image_url?e.jsx("img",{src:s.cover_image_url,alt:`${s.name} program cover`,loading:"lazy",className:"h-full w-full object-cover transition-transform duration-500 group-hover:scale-105"}):e.jsx("div",{className:"flex h-full w-full items-center justify-center bg-gradient-to-br from-primary/15 via-background to-accent/20",children:e.jsx(kn,{className:"h-10 w-10 text-primary/60"})}),e.jsxs("div",{className:"absolute left-3 top-3 flex gap-2",children:[s.is_featured&&e.jsx(qe,{className:"shadow-sm",children:"Featured"}),t&&e.jsxs(qe,{variant:"secondary",className:"shadow-sm",children:[e.jsx(Gr,{className:"mr-1 h-3 w-3"})," Enrolled"]})]})]}),e.jsxs(De,{className:"space-y-4 p-5",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("h2",{className:"text-lg font-semibold leading-tight",children:s.name}),s.subtitle&&e.jsx("p",{className:"text-sm text-muted-foreground",children:s.subtitle})]}),e.jsxs("div",{className:"flex flex-wrap gap-x-4 gap-y-1.5 text-xs text-muted-foreground",children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx(sa,{className:"h-3.5 w-3.5"}),s.duration_weeks," weeks"]}),s.kickoff_at&&e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx(fd,{className:"h-3.5 w-3.5"}),"Starts ",ru(s.kickoff_at)]}),e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx(Xn,{className:"h-3.5 w-3.5"}),s.capacity," seats"]})]}),e.jsxs("div",{className:"flex items-center justify-between border-t border-border/60 pt-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-lg font-semibold",children:s.payment_mode==="free"?"Included":Tp(s.price_cents,s.currency)}),n?e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Enrollment opens ",a]}):s.payment_mode!=="free"?e.jsxs("p",{className:"text-xs text-muted-foreground",children:["One-time payment for the ",tX(s.duration_weeks)," — no subscription",s.charge_at?` · charged ${ru(s.charge_at)}`:""]}):null]}),e.jsx($,{asChild:!0,size:"sm",children:e.jsxs(nr,{to:t?`/programs/${s.slug}/workspace`:`/programs/${s.slug}`,children:[t?"Open program":n?"Preview details":"View details",e.jsx(xi,{className:"ml-1.5 h-4 w-4"})]})})]})]})]})},gOs=()=>{const{data:s=[],isLoading:t}=TMt(),{data:n=[]}=mWe(),r=new Set(n.filter(l=>kU(l)).map(l=>l.program_id)),a=s.filter(l=>r.has(l.id)),i=s.filter(l=>!r.has(l.id));return e.jsx(Xs,{children:e.jsxs("div",{className:"mx-auto w-full max-w-6xl space-y-10 p-4 md:p-8",children:[e.jsxs("header",{className:"space-y-3",children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-[0.2em] text-primary",children:"LevelUp Programs"}),e.jsx("h1",{className:"text-3xl font-bold tracking-tight md:text-4xl",children:"Go deeper than the membership"}),e.jsx("p",{className:"max-w-2xl text-muted-foreground",children:"Time-bound coaching programs, masterminds and challenges built to move one specific part of your business forward — with a real cohort, a real roadmap and real accountability."})]}),t?e.jsx("div",{className:"grid gap-6 md:grid-cols-2 lg:grid-cols-3",children:[0,1,2].map(l=>e.jsx(fn,{className:"h-80 rounded-xl"},l))}):e.jsxs(e.Fragment,{children:[a.length>0&&e.jsxs("section",{className:"space-y-4",children:[e.jsx("h2",{className:"text-sm font-semibold uppercase tracking-wider text-muted-foreground",children:"Your programs"}),e.jsx("div",{className:"grid gap-6 md:grid-cols-2 lg:grid-cols-3",children:a.map(l=>e.jsx(Dut,{program:l,enrolled:!0},l.id))})]}),e.jsxs("section",{className:"space-y-4",children:[a.length>0&&e.jsx("h2",{className:"text-sm font-semibold uppercase tracking-wider text-muted-foreground",children:"Open for enrollment"}),i.length===0&&a.length===0?e.jsx(we,{className:"border-dashed",children:e.jsxs(De,{className:"flex flex-col items-center gap-3 p-12 text-center",children:[e.jsx(kn,{className:"h-8 w-8 text-muted-foreground"}),e.jsx("p",{className:"font-medium",children:"No programs are open right now"}),e.jsx("p",{className:"max-w-md text-sm text-muted-foreground",children:"New cohorts are announced inside the Hub. Check back soon — seats are limited when they open."})]})}):e.jsx("div",{className:"grid gap-6 md:grid-cols-2 lg:grid-cols-3",children:i.map(l=>e.jsx(Dut,{program:l,enrolled:!1},l.id))})]})]})]})})},xOs=s=>{const t=s.match(/(?:youtube\.com\/(?:watch\?v=|embed\/|shorts\/|live\/)|youtu\.be\/)([A-Za-z0-9_-]{11})/);if(t)return`https://www.youtube.com/embed/${t[1]}?autoplay=1&rel=0&modestbranding=1`;const n=s.match(/vimeo\.com\/(?:video\/)?(\d+)/);if(n)return`https://player.vimeo.com/video/${n[1]}?autoplay=1`;const r=s.match(/loom\.com\/(?:share|embed)\/([A-Za-z0-9]+)/);return r?`https://www.loom.com/embed/${r[1]}`:null},yOs=({url:s,headline:t,posterUrl:n})=>{const[r,a]=k.useState(!1),i=(s||"").trim();if(!i)return null;const l=xOs(i),o=!l&&/\.(mp4|webm|mov|m4v)(\?|$)/i.test(i);return!l&&!o?null:e.jsxs("section",{className:"space-y-3",children:[e.jsx("div",{className:"relative overflow-hidden rounded-2xl border border-border/60 bg-black shadow-lg",children:e.jsx("div",{className:"aspect-video w-full",children:r?o?e.jsx("video",{src:i,controls:!0,autoPlay:!0,className:"h-full w-full",playsInline:!0}):e.jsx("iframe",{src:l,title:t||"Program promo video",className:"h-full w-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; picture-in-picture; fullscreen",allowFullScreen:!0}):e.jsxs("button",{type:"button",onClick:()=>a(!0),className:"group relative h-full w-full","aria-label":"Play program promo video",children:[n?e.jsx("img",{src:n,alt:"",className:"h-full w-full object-cover opacity-70 transition group-hover:opacity-60"}):e.jsx("div",{className:"h-full w-full bg-gradient-to-br from-primary/30 via-black to-accent/30"}),e.jsxs("span",{className:"absolute inset-0 flex flex-col items-center justify-center gap-3",children:[e.jsx(mm,{className:"h-16 w-16 text-white/90 transition group-hover:scale-110"}),e.jsx("span",{className:"rounded-full bg-white/10 px-4 py-1 text-xs font-medium uppercase tracking-widest text-white/90 backdrop-blur",children:"Watch the program video"})]})]})})}),t&&e.jsx("p",{className:"text-center text-sm font-medium text-muted-foreground",children:t})]})};var vOs=Object.defineProperty,Dee=(s,t)=>vOs(s,"name",{value:t,configurable:!0}),xKe="Collapsible",[bOs,kIt]=qm(xKe),[_Os,yKe]=bOs(xKe),wOs=k.forwardRef(Dee(function(t,n){const{__scopeCollapsible:r,open:a,defaultOpen:i,disabled:l,onOpenChange:o,...c}=t,[d,u]=ox({prop:a,defaultProp:i??!1,onChange:o,caller:xKe});return e.jsx(_Os,{scope:r,disabled:l,contentId:$x(),open:d,onOpenToggle:k.useCallback(()=>u(h=>!h),[u]),children:e.jsx(hi.div,{"data-state":DAe(d),"data-disabled":l?"":void 0,...c,ref:n})})},"Collapsible")),jOs="CollapsibleTrigger",SIt=k.forwardRef(Dee(function(t,n){const{__scopeCollapsible:r,...a}=t,i=yKe(jOs,r);return e.jsx(hi.button,{type:"button","aria-controls":i.open?i.contentId:void 0,"aria-expanded":i.open||!1,"data-state":DAe(i.open),"data-disabled":i.disabled?"":void 0,disabled:i.disabled,...a,ref:n,onClick:ga(t.onClick,i.onOpenToggle)})},"CollapsibleTrigger")),CIt="CollapsibleContent",AIt=k.forwardRef(Dee(function(t,n){const{forceMount:r,...a}=t,i=yKe(CIt,t.__scopeCollapsible);return e.jsx(cx,{present:r||i.open,children:({present:l})=>e.jsx(NOs,{...a,ref:n,present:l})})},"CollapsibleContent")),NOs=k.forwardRef(Dee(function(t,n){const{__scopeCollapsible:r,present:a,children:i,...l}=t,o=yKe(CIt,r),[c,d]=k.useState(a),u=k.useRef(null),h=Ao(n,u),m=k.useRef(0),p=m.current,g=k.useRef(0),x=g.current,y=o.open||c,v=k.useRef(y),_=k.useRef(void 0);return k.useEffect(()=>{const j=requestAnimationFrame(()=>v.current=!1);return()=>cancelAnimationFrame(j)},[]),_m(()=>{const j=u.current;if(j){_.current=_.current||{transitionDuration:j.style.transitionDuration,animationName:j.style.animationName},j.style.transitionDuration="0s",j.style.animationName="none";const C=j.getBoundingClientRect();m.current=C.height,g.current=C.width,v.current||(j.style.transitionDuration=_.current.transitionDuration,j.style.animationName=_.current.animationName),d(a)}},[o.open,a]),e.jsx(hi.div,{"data-state":DAe(o.open),"data-disabled":o.disabled?"":void 0,id:o.contentId,hidden:!y,...l,ref:h,style:{"--radix-collapsible-content-height":p?`${p}px`:void 0,"--radix-collapsible-content-width":x?`${x}px`:void 0,...t.style},children:y&&i})},"CollapsibleContentImpl"));function DAe(s){return s?"open":"closed"}Dee(DAe,"getState");var EIt=wOs,kOs=SIt,SOs=AIt,COs=Object.defineProperty,ej=(s,t)=>COs(s,"name",{value:t,configurable:!0}),n4="Accordion",AOs=["Home","End","ArrowDown","ArrowUp","ArrowLeft","ArrowRight"],[vKe,EOs,TOs]=fF(n4),[OAe,XQn]=qm(n4,[TOs,kIt]),bKe=kIt(),MOs=k.forwardRef(ej(function(t,n){const{type:r,...a}=t,i=a,l=a;return e.jsx(vKe.Provider,{scope:t.__scopeAccordion,children:r==="multiple"?e.jsx(ROs,{...l,ref:n}):e.jsx(LOs,{...i,ref:n})})},"Accordion")),[TIt,POs]=OAe(n4),[MIt,IOs]=OAe(n4,{collapsible:!1}),LOs=k.forwardRef(ej(function(t,n){const{value:r,defaultValue:a,onValueChange:i=ej(()=>{},"onValueChange"),collapsible:l=!1,...o}=t,[c,d]=ox({prop:r,defaultProp:a??"",onChange:i,caller:n4});return e.jsx(TIt,{scope:t.__scopeAccordion,value:k.useMemo(()=>c?[c]:[],[c]),onItemOpen:d,onItemClose:k.useCallback(()=>l&&d(""),[l,d]),children:e.jsx(MIt,{scope:t.__scopeAccordion,collapsible:l,children:e.jsx(PIt,{...o,ref:n})})})},"AccordionImplSingle")),ROs=k.forwardRef(ej(function(t,n){const{value:r,defaultValue:a,onValueChange:i=ej(()=>{},"onValueChange"),...l}=t,[o,c]=ox({prop:r,defaultProp:a??[],onChange:i,caller:n4}),d=k.useCallback(h=>c((m=[])=>[...m,h]),[c]),u=k.useCallback(h=>c((m=[])=>m.filter(p=>p!==h)),[c]);return e.jsx(TIt,{scope:t.__scopeAccordion,value:o,onItemOpen:d,onItemClose:u,children:e.jsx(MIt,{scope:t.__scopeAccordion,collapsible:!0,children:e.jsx(PIt,{...l,ref:n})})})},"AccordionImplMultiple")),[DOs,FAe]=OAe(n4),PIt=k.forwardRef(ej(function(t,n){const{__scopeAccordion:r,disabled:a,dir:i,orientation:l="vertical",...o}=t,c=k.useRef(null),d=Ao(c,n),u=EOs(r),m=e4(i)==="ltr",p=ga(t.onKeyDown,g=>{var R;if(!AOs.includes(g.key))return;const x=g.target,y=u().filter(O=>{var B;return!((B=O.ref.current)!=null&&B.disabled)}),v=y.findIndex(O=>O.ref.current===x),_=y.length;if(v===-1)return;g.preventDefault();let j=v;const C=0,A=_-1,M=ej(()=>{j=v+1,j>A&&(j=C)},"moveNext"),I=ej(()=>{j=v-1,j{m?o.onItemOpen(a):o.onItemClose(a)}})})},"AccordionItem")),zOs="AccordionHeader",BOs=k.forwardRef(ej(function(t,n){const{__scopeAccordion:r,...a}=t,i=FAe(n4,r),l=_Ke(zOs,r);return e.jsx(hi.h3,{"data-orientation":i.orientation,"data-state":wKe(l.open),"data-disabled":l.disabled?"":void 0,...a,ref:n})},"AccordionHeader")),Out="AccordionTrigger",$Os=k.forwardRef(ej(function(t,n){const{__scopeAccordion:r,...a}=t,i=FAe(n4,r),l=_Ke(Out,r),o=IOs(Out,r),c=bKe(r);return e.jsx(vKe.ItemSlot,{scope:r,children:e.jsx(kOs,{"aria-disabled":l.open&&!o.collapsible||void 0,"data-orientation":i.orientation,id:l.triggerId,...c,...a,ref:n})})},"AccordionTrigger")),UOs="AccordionContent",qOs=k.forwardRef(ej(function(t,n){const{__scopeAccordion:r,...a}=t,i=FAe(n4,r),l=_Ke(UOs,r),o=bKe(r);return e.jsx(SOs,{role:"region","aria-labelledby":l.triggerId,"data-orientation":i.orientation,...o,...a,ref:n,style:{"--radix-accordion-content-height":"var(--radix-collapsible-content-height)","--radix-accordion-content-width":"var(--radix-collapsible-content-width)",...t.style}})},"AccordionContent"));function wKe(s){return s?"open":"closed"}ej(wKe,"getState");var VOs=MOs,HOs=FOs,GOs=BOs,IIt=$Os,LIt=qOs;const SF=VOs,r6=k.forwardRef(({className:s,...t},n)=>e.jsx(HOs,{ref:n,className:Ot("border-b",s),...t}));r6.displayName="AccordionItem";const a6=k.forwardRef(({className:s,children:t,...n},r)=>e.jsx(GOs,{className:"flex",children:e.jsxs(IIt,{ref:r,className:Ot("flex flex-1 items-center justify-between py-4 font-medium transition-all hover:underline [&[data-state=open]>svg]:rotate-180",s),...n,children:[t,e.jsx(Go,{className:"h-4 w-4 shrink-0 transition-transform duration-200"})]})}));a6.displayName=IIt.displayName;const i6=k.forwardRef(({className:s,children:t,...n},r)=>e.jsx(LIt,{ref:r,className:"overflow-hidden text-sm transition-all data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down",...n,children:e.jsx("div",{className:Ot("pb-4 pt-0",s),children:t})}));i6.displayName=LIt.displayName;const WOs=({programId:s,opensLabel:t})=>{const{data:n,isLoading:r}=DAs(s),a=OAs(s),i=!!n;return e.jsxs("div",{className:"flex flex-col gap-3 rounded-xl border border-primary/30 bg-primary/5 p-4 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(p3,{className:"mt-0.5 h-4 w-4 shrink-0 text-primary"}),e.jsxs("div",{className:"space-y-0.5 text-sm",children:[e.jsx("p",{className:"font-semibold",children:i?"You're on the notify list":"Want a heads-up when enrollment opens?"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:i?`We'll email you the moment seats go live${t?` (${t})`:""}.`:`Seats are limited — we'll email you the moment enrollment opens${t?` ${t}`:""}.`})]})]}),e.jsxs($,{variant:i?"outline":"default",size:"sm",disabled:r||a.isPending,onClick:()=>a.mutate(!i),className:"shrink-0",children:[a.isPending?e.jsx(Jt,{className:"mr-2 h-4 w-4 animate-spin"}):i?e.jsx(ma,{className:"mr-2 h-4 w-4"}):e.jsx(p3,{className:"mr-2 h-4 w-4"}),i?"You're on the list":"Notify me"]})]})},KOs=()=>{const{slug:s}=oo(),{data:t,isLoading:n}=hWe(s),{data:r}=MMt(t==null?void 0:t.id),{data:a}=fWe(t==null?void 0:t.id),i=kU(a),l=(t==null?void 0:t.sales_copy)||{},o=l.outcomes||[],c=l.included||[],d=l.for_who||[],u=l.not_for||[],h=l.faqs||[],m=l.phases||[];if(n)return e.jsx(Xs,{children:e.jsxs("div",{className:"mx-auto max-w-5xl space-y-6 p-8",children:[e.jsx(fn,{className:"h-64 w-full rounded-xl"}),e.jsx(fn,{className:"h-40 w-full rounded-xl"})]})});if(!t)return e.jsx(Xs,{children:e.jsxs("div",{className:"mx-auto max-w-2xl p-12 text-center",children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Program not found"}),e.jsx("p",{className:"mt-2 text-muted-foreground",children:"This program may have been closed or unpublished."}),e.jsx($,{asChild:!0,className:"mt-6",children:e.jsx(nr,{to:"/programs",children:"Back to Programs"})})]})});const p=typeof r=="number"&&r<=0&&!i,{notOpenYet:g,closed:x,opensLabel:y}=fAe(t),v=!i&&(p||x||g),_=i?"Open your program":g?`Enrollment opens ${ru(t.enrollment_open_at)}`:p?"Cohort is full":x?"Enrollment closed":t.payment_mode==="delayed"?"Reserve my seat":"Enroll now",j=i?`/programs/${t.slug}/workspace`:`/programs/${t.slug}/enroll`;return e.jsxs(Xs,{children:[e.jsxs(Sc,{children:[e.jsx("title",{children:`${t.name} | LevelUp Programs`}),e.jsx("meta",{name:"description",content:(t.short_description||t.subtitle||t.name).slice(0,155)})]}),e.jsxs("div",{className:"mx-auto w-full max-w-5xl space-y-12 p-4 md:p-8",children:[e.jsxs("section",{className:"overflow-hidden rounded-2xl border border-border/60 bg-card",children:[e.jsx("div",{className:"relative",children:t.promo_video_url?e.jsx(yOs,{url:t.promo_video_url,headline:t.promo_video_headline,posterUrl:t.hero_image_url||t.cover_image_url}):t.hero_image_url||t.cover_image_url?e.jsx("img",{src:t.hero_image_url||t.cover_image_url,alt:`${t.name} hero`,className:"h-56 w-full object-cover md:h-72"}):e.jsx("div",{className:"h-40 w-full bg-gradient-to-br from-primary/20 via-background to-accent/20 md:h-56"})}),e.jsxs("div",{className:"space-y-6 p-6 md:p-8",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(qe,{variant:"secondary",children:[t.duration_weeks,"-week program"]}),typeof r=="number"&&!i&&e.jsx(qe,{variant:r<=10?"destructive":"outline",children:r>0?`${r} of ${t.capacity} seats left`:"Full"}),i&&e.jsxs(qe,{children:[e.jsx(Gr,{className:"mr-1 h-3 w-3"})," You're enrolled"]})]}),e.jsx("h1",{className:"text-3xl font-bold tracking-tight md:text-4xl",children:t.name}),t.subtitle&&e.jsx("p",{className:"text-lg text-muted-foreground",children:t.subtitle}),t.tagline&&e.jsx("p",{className:"text-sm font-medium text-primary",children:t.tagline})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-4",children:[e.jsxs("div",{className:"rounded-lg border border-border/60 p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Investment"}),e.jsx("p",{className:"mt-1 font-semibold",children:t.payment_mode==="free"?"Included":Tp(t.price_cents,t.currency)}),t.payment_mode!=="free"&&e.jsxs("p",{className:"mt-1 text-xs text-muted-foreground",children:["One-time payment for the ",tX(t.duration_weeks)," — not a subscription"]})]}),e.jsxs("div",{className:"rounded-lg border border-border/60 p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Kickoff"}),e.jsx("p",{className:"mt-1 font-semibold",children:ru(t.kickoff_at,!0)||"To be announced"})]}),e.jsxs("div",{className:"rounded-lg border border-border/60 p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Weekly commitment"}),e.jsxs("p",{className:"mt-1 font-semibold",children:[t.weekly_video_goal," videos / week"]})]}),e.jsxs("div",{className:"rounded-lg border border-border/60 p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Cohort size"}),e.jsxs("p",{className:"mt-1 font-semibold",children:[t.capacity," agents"]})]})]}),t.payment_mode==="delayed"&&t.charge_at&&!i&&e.jsxs("div",{className:"flex items-start gap-3 rounded-lg border border-primary/30 bg-primary/5 p-4",children:[e.jsx(cv,{className:"mt-0.5 h-4 w-4 shrink-0 text-primary"}),e.jsxs("div",{className:"space-y-1 text-sm",children:[e.jsxs("p",{children:[e.jsxs("span",{className:"font-semibold",children:[t9e(t.price_cents,t.currency,t.duration_weeks),"."]})," ","We save your card today and charge it once on"," ",e.jsx("span",{className:"font-semibold",children:ru(t.charge_at)}),". Cancel any time before then and you won't be billed."]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"No recurring billing, no monthly installments, and no automatic renewal."})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx($,{asChild:!v,size:"lg",disabled:v,children:v?e.jsx("span",{children:_}):e.jsxs(nr,{to:j,children:[_,e.jsx(xi,{className:"ml-2 h-4 w-4"})]})}),e.jsx($,{asChild:!0,variant:"ghost",size:"lg",children:e.jsx(nr,{to:"/programs",children:"All programs"})})]}),g&&!i&&e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"inline-flex items-center gap-1.5 text-xs text-muted-foreground",children:[e.jsx(fd,{className:"h-3.5 w-3.5"}),"Enrollment opens ",y]}),e.jsx(WOs,{programId:t.id,opensLabel:y})]})]})]}),t.description&&e.jsxs("section",{className:"space-y-3",children:[e.jsx("h2",{className:"text-xl font-semibold",children:"What this program is"}),e.jsx("div",{className:"whitespace-pre-line text-muted-foreground",children:t.description})]}),o.length>0&&e.jsxs("section",{className:"space-y-4",children:[e.jsx("h2",{className:"text-xl font-semibold",children:"What you'll walk away with"}),e.jsx("div",{className:"grid gap-3 sm:grid-cols-2",children:o.map((C,A)=>e.jsxs("div",{className:"flex items-start gap-3 rounded-lg border border-border/60 p-4",children:[e.jsx(Gr,{className:"mt-0.5 h-4 w-4 shrink-0 text-primary"}),e.jsx("p",{className:"text-sm",children:C})]},A))})]}),m.length>0&&e.jsxs("section",{className:"space-y-4",children:[e.jsxs("h2",{className:"text-xl font-semibold",children:["How the ",t.duration_weeks," weeks flow"]}),e.jsx("div",{className:"grid gap-4 md:grid-cols-3",children:m.map((C,A)=>e.jsx(we,{className:"border-border/60",children:e.jsxs(De,{className:"space-y-2 p-5",children:[e.jsxs("p",{className:"text-xs font-semibold uppercase tracking-wider text-primary",children:["Phase ",A+1]}),e.jsx("h3",{className:"font-semibold",children:C.title}),e.jsx("p",{className:"text-sm text-muted-foreground",children:C.detail})]})},A))})]}),c.length>0&&e.jsxs("section",{className:"space-y-4",children:[e.jsx("h2",{className:"text-xl font-semibold",children:"What's included"}),e.jsx("ul",{className:"grid gap-2 sm:grid-cols-2",children:c.map((C,A)=>e.jsxs("li",{className:"flex items-start gap-2.5 text-sm",children:[e.jsx(kn,{className:"mt-0.5 h-4 w-4 shrink-0 text-primary"}),C]},A))})]}),(d.length>0||u.length>0)&&e.jsxs("section",{className:"grid gap-6 md:grid-cols-2",children:[d.length>0&&e.jsx(we,{className:"border-border/60",children:e.jsxs(De,{className:"space-y-3 p-5",children:[e.jsx("h3",{className:"font-semibold",children:"This is for you if…"}),e.jsx("ul",{className:"space-y-2 text-sm text-muted-foreground",children:d.map((C,A)=>e.jsxs("li",{className:"flex gap-2",children:[e.jsx(Gr,{className:"mt-0.5 h-4 w-4 shrink-0 text-primary"}),C]},A))})]})}),u.length>0&&e.jsx(we,{className:"border-border/60",children:e.jsxs(De,{className:"space-y-3 p-5",children:[e.jsx("h3",{className:"font-semibold",children:"This isn't for you if…"}),e.jsx("ul",{className:"space-y-2 text-sm text-muted-foreground",children:u.map((C,A)=>e.jsxs("li",{className:"flex gap-2",children:[e.jsx(sa,{className:"mt-0.5 h-4 w-4 shrink-0"}),C]},A))})]})})]}),h.length>0&&e.jsxs("section",{className:"space-y-4",children:[e.jsx("h2",{className:"text-xl font-semibold",children:"Questions"}),e.jsx(SF,{type:"single",collapsible:!0,className:"rounded-xl border border-border/60 px-4",children:h.map((C,A)=>e.jsxs(r6,{value:`faq-${A}`,children:[e.jsx(a6,{className:"text-left text-sm font-medium",children:C.q}),e.jsx(i6,{className:"text-sm text-muted-foreground",children:C.a})]},A))})]}),e.jsxs("section",{className:"rounded-2xl border border-border/60 bg-muted/40 p-6 text-center md:p-10",children:[e.jsx(ia,{className:"mx-auto h-8 w-8 text-primary"}),e.jsx("h2",{className:"mt-4 text-2xl font-bold",children:l.closing_headline||"Ready to commit?"}),e.jsx("p",{className:"mx-auto mt-2 max-w-xl text-muted-foreground",children:l.closing_body||`Seats are capped at ${t.capacity} so every member gets attention. Reserve yours and we'll take it from there.`}),e.jsxs("div",{className:"mt-6 flex flex-wrap items-center justify-center gap-3",children:[e.jsx($,{asChild:!v,size:"lg",disabled:v,children:v?e.jsx("span",{children:_}):e.jsxs(nr,{to:j,children:[_,e.jsx(xi,{className:"ml-2 h-4 w-4"})]})}),typeof r=="number"&&r>0&&!i&&e.jsxs("span",{className:"inline-flex items-center gap-1.5 text-sm text-muted-foreground",children:[e.jsx(Xn,{className:"h-4 w-4"}),r," seats remaining"]})]}),!i&&(g?e.jsxs("p",{className:"mt-3 inline-flex items-center gap-1.5 text-xs text-muted-foreground",children:[e.jsx(fd,{className:"h-3.5 w-3.5"}),"Enrollment opens ",y]}):t.enrollment_close_at?e.jsxs("p",{className:"mt-3 inline-flex items-center gap-1.5 text-xs text-muted-foreground",children:[e.jsx(fd,{className:"h-3.5 w-3.5"}),"Enrollment closes ",ru(t.enrollment_close_at)]}):null)]})]})]})},Ere=["Your business","Your content","Your goals","Reserve your seat"],YOs=()=>{const{slug:s}=oo(),t=Jn(),[n,r]=Jc(),{user:a}=ks(),{data:i,isLoading:l}=hWe(s),{data:o}=MMt(i==null?void 0:i.id),{data:c,refetch:d}=fWe(i==null?void 0:i.id),{data:u}=PMt(i==null?void 0:i.id),h=mAs(),m=fAs(),p=jAs(),g=NAs(),[x,y]=k.useState(0),[v,_]=k.useState(!1),[j,C]=k.useState(!1),[A,M]=k.useState(!1),[I,P]=k.useState(!1),[R,O]=k.useState(""),[B,U]=k.useState(null),G=k.useRef({}),[H,Y]=k.useState({}),se=k.useRef(!1),ee=(Oe,Ge)=>{G.current={...G.current,[Oe]:Ge},Y(G.current)};k.useEffect(()=>{se.current||(u?(G.current={...u},Y(G.current),se.current=!0):a&&(G.current={email:a.email,...G.current},Y(G.current)))},[u,a]),k.useEffect(()=>{const Oe=c;!i||!(Oe!=null&&Oe.discount_code)||B||U({code:Oe.discount_code,discount_cents:Oe.discount_cents||0,amount_cents:Oe.amount_cents??i.price_cents,original_cents:i.price_cents})},[c,i,B]);const oe=B?B.amount_cents:(i==null?void 0:i.price_cents)??0,me=k.useMemo(()=>sX(i),[i]),Q=Oe=>hAs(me,Oe),te=Oe=>Vct(me,Oe)?e.jsx("span",{className:"text-destructive",children:" *"}):null,le=(Oe,Ge)=>{const yt={...G.current.extra||{},[Oe]:Ge};ee("extra",yt)},fe=Oe=>me.custom.filter((Ge,yt)=>yt%3===Oe),_e=Oe=>{const Ge=fe(Oe);if(!Ge.length)return null;const yt=H.extra||{};return e.jsx("div",{className:"space-y-4",children:Ge.map(tt=>e.jsxs("div",{className:"space-y-2",children:[tt.type==="checkbox"?e.jsxs("div",{className:"flex items-start gap-3 rounded-lg border border-border/60 p-4",children:[e.jsx(Li,{id:tt.id,checked:!!yt[tt.id],onCheckedChange:ut=>le(tt.id,!!ut)}),e.jsxs(re,{htmlFor:tt.id,className:"text-sm font-normal leading-relaxed",children:[tt.label,tt.required&&e.jsx("span",{className:"text-destructive",children:" *"})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs(re,{htmlFor:tt.id,children:[tt.label,tt.required&&e.jsx("span",{className:"text-destructive",children:" *"})]}),tt.type==="long_text"?e.jsx(Ls,{id:tt.id,rows:3,value:yt[tt.id]||"",onChange:ut=>le(tt.id,ut.target.value)}):tt.type==="select"?e.jsxs(bs,{value:yt[tt.id]||"",onValueChange:ut=>le(tt.id,ut),children:[e.jsx(ys,{children:e.jsx(_s,{placeholder:"Select"})}),e.jsx(vs,{children:(tt.options||[]).map(ut=>e.jsx(We,{value:ut,children:ut},ut))})]}):e.jsx(be,{id:tt.id,value:yt[tt.id]||"",onChange:ut=>le(tt.id,ut.target.value)})]}),tt.help&&e.jsx("p",{className:"text-xs text-muted-foreground",children:tt.help})]},tt.id))})},ve=Oe=>{const Ge=G.current,yt=et=>et==null||et===""||et===!1,tt=uWe.find(et=>et.step===Oe&&Vct(me,et.key)&&yt(et.key==="timezone"?Ge.timezone||(i==null?void 0:i.timezone):Ge[et.key]));if(tt)return tt.label;const ut=Ge.extra||{},nt=fe(Oe).find(et=>et.required&&yt(ut[et.id]));return nt?nt.label:null},he=()=>{if(x<=2){const Oe=ve(x);if(Oe)return ae.error(`Please answer: ${Oe}`)}y(Oe=>Oe+1)},Se=async()=>{if(!(!i||!R.trim()))try{let Oe=c==null?void 0:c.id;(!Oe||(c==null?void 0:c.status)==="canceled")&&(Oe=await m.mutateAsync(i.id));const Ge=await p.mutateAsync({enrollmentId:Oe,code:R});U(Ge),O(""),await d(),ae.success(`Code applied — you save ${Tp(Ge.discount_cents,i.currency)}`)}catch(Oe){ae.error(Oe.message||"That code could not be applied")}},Te=async()=>{if(!(c!=null&&c.id))return U(null);try{await g.mutateAsync(c.id),U(null),await d()}catch(Oe){ae.error(Oe.message||"Could not remove the code")}},Ie=n.get("setup"),Ue=n.get("session_id"),Be=k.useRef(!1);k.useEffect(()=>{Ie!=="success"||!Ue||!(c!=null&&c.id)||Be.current||(Be.current=!0,C(!0),(async()=>{const{data:Oe,error:Ge}=await V.functions.invoke("program-enroll",{body:{action:"verify",enrollment_id:c.id,session_id:Ue}});if(C(!1),Ge||Oe!=null&&Oe.error||(Oe==null?void 0:Oe.success)===!1){ae.error((Oe==null?void 0:Oe.error)||(Ge==null?void 0:Ge.message)||"We could not confirm your card");return}await d(),n.delete("setup"),n.delete("session_id"),r(n,{replace:!0}),ae.success("Your seat is confirmed")})())},[Ie,Ue,c==null?void 0:c.id]),k.useEffect(()=>{Ie==="cancelled"&&ae.info("Checkout cancelled — your seat is held for a short while.")},[Ie]);const je=k.useMemo(()=>c&&["reserved","scheduled_for_charge","paid","completed"].includes(c.status),[c]),Ye=async()=>{if(i){if(!A||i.payment_mode!=="free"&&!I){ae.error("Please confirm the checkboxes to continue");return}_(!0);try{let Oe=c==null?void 0:c.id;(!Oe||(c==null?void 0:c.status)==="canceled")&&(Oe=await m.mutateAsync(i.id)),await h.mutateAsync({...G.current,id:void 0,program_id:i.id,enrollment_id:Oe,created_at:void 0,updated_at:void 0,user_id:void 0});const{data:Ge,error:yt}=await V.functions.invoke("program-enroll",{body:{action:"setup",enrollment_id:Oe}});if(yt||Ge!=null&&Ge.error)throw new Error((Ge==null?void 0:Ge.error)||(yt==null?void 0:yt.message));if(Ge!=null&&Ge.free){await d(),ae.success("You're in"),t(`/programs/${i.slug}/workspace`);return}Ge!=null&&Ge.url&&(window.location.href=Ge.url)}catch(Oe){ae.error(Oe.message||"Could not start enrollment")}finally{_(!1)}}};if(l)return e.jsx(Xs,{children:e.jsxs("div",{className:"mx-auto max-w-2xl space-y-4 p-8",children:[e.jsx(fn,{className:"h-10 w-1/2"}),e.jsx(fn,{className:"h-64 w-full rounded-xl"})]})});if(!i)return e.jsx(Xs,{children:e.jsxs("div",{className:"mx-auto max-w-xl p-12 text-center",children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Program not found"}),e.jsx($,{asChild:!0,className:"mt-6",children:e.jsx(nr,{to:"/programs",children:"Back to Programs"})})]})});if(kU(c)&&je&&Ie!=="success")return e.jsx(Xs,{children:e.jsxs("div",{className:"mx-auto max-w-xl space-y-4 p-12 text-center",children:[e.jsx(Gr,{className:"mx-auto h-10 w-10 text-primary"}),e.jsxs("h1",{className:"text-2xl font-bold",children:["You're enrolled in ",i.name]}),e.jsx("p",{className:"text-muted-foreground",children:(c==null?void 0:c.status)==="paid"?"Your payment is complete.":`Your card is saved. Nothing is charged until ${ru(c==null?void 0:c.charge_scheduled_at)||"the program start date"}.`}),e.jsx($,{asChild:!0,size:"lg",children:e.jsx(nr,{to:`/programs/${i.slug}/workspace`,children:"Open your program workspace"})})]})});const Ee=typeof o=="number"&&o<=0,{notOpenYet:Re,closed:ke,opensLabel:Fe}=fAe(i);return Re||ke?e.jsx(Xs,{children:e.jsxs("div",{className:"mx-auto w-full max-w-xl space-y-4 p-8 text-center",children:[e.jsx("h1",{className:"text-2xl font-bold",children:Re?"Enrollment is not open yet":"Enrollment is closed"}),e.jsx("p",{className:"text-muted-foreground",children:Re?`Enrollment for ${i.name} opens ${Fe}. Come back then to reserve your seat.`:`Enrollment for ${i.name} has closed. Watch the Hub for the next cohort.`}),e.jsx($,{asChild:!0,children:e.jsx(nr,{to:`/programs/${i.slug}`,children:"Back to program details"})})]})}):e.jsx(Xs,{children:e.jsxs("div",{className:"mx-auto w-full max-w-3xl space-y-6 p-4 md:p-8",children:[e.jsx($,{asChild:!0,variant:"ghost",size:"sm",className:"-ml-2",children:e.jsxs(nr,{to:`/programs/${i.slug}`,children:[e.jsx(Ia,{className:"mr-1.5 h-4 w-4"})," Back to program"]})}),e.jsxs("header",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-[0.2em] text-primary",children:"Enrollment"}),e.jsx("h1",{className:"text-2xl font-bold md:text-3xl",children:i.name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:i.payment_mode==="delayed"&&i.charge_at?`${t9e(i.price_cents,i.currency,i.duration_weeks)}. Your card is saved today and charged once on ${ru(i.charge_at)} — no recurring billing.`:"Complete the short intake and checkout to secure your seat."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between text-xs text-muted-foreground",children:[e.jsx("span",{className:"font-medium text-foreground",children:Ere[x]}),e.jsxs("span",{children:["Step ",x+1," of ",Ere.length]})]}),e.jsx(ho,{value:(x+1)/Ere.length*100})]}),j&&e.jsx(we,{className:"border-primary/40 bg-primary/5",children:e.jsxs(De,{className:"flex items-center gap-3 p-4 text-sm",children:[e.jsx(Jt,{className:"h-4 w-4 animate-spin text-primary"}),"Confirming your card with Stripe…"]})}),e.jsx(we,{children:e.jsxs(De,{className:"space-y-5 p-6",children:[x===0&&me.intro&&e.jsx("p",{className:"rounded-lg border border-border/60 bg-muted/30 p-4 text-sm text-muted-foreground",children:me.intro}),x===0&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[Q("full_name")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(re,{htmlFor:"full_name",children:["Full name",te("full_name")]}),e.jsx(be,{id:"full_name",value:H.full_name||"",onChange:Oe=>ee("full_name",Oe.target.value)})]}),Q("phone")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(re,{htmlFor:"phone",children:["Mobile number",te("phone")]}),e.jsx(be,{id:"phone",value:H.phone||"",onChange:Oe=>ee("phone",Oe.target.value)})]}),Q("instagram_handle")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(re,{htmlFor:"instagram_handle",children:["Instagram handle",te("instagram_handle")]}),e.jsx(be,{id:"instagram_handle",placeholder:"@yourhandle",value:H.instagram_handle||"",onChange:Oe=>ee("instagram_handle",Oe.target.value)})]}),Q("city")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(re,{htmlFor:"city",children:["Primary city / market",te("city")]}),e.jsx(be,{id:"city",value:H.city||"",onChange:Oe=>ee("city",Oe.target.value)})]})]}),Q("service_areas")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(re,{htmlFor:"service_areas",children:["Neighborhoods or areas you serve",te("service_areas")]}),e.jsx(Ls,{id:"service_areas",rows:2,value:H.service_areas||"",onChange:Oe=>ee("service_areas",Oe.target.value)})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[Q("years_experience")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(re,{children:["Years in real estate",te("years_experience")]}),e.jsxs(bs,{value:H.years_experience||"",onValueChange:Oe=>ee("years_experience",Oe),children:[e.jsx(ys,{children:e.jsx(_s,{placeholder:"Select"})}),e.jsx(vs,{children:["Less than 1","1-3","4-7","8-15","15+"].map(Oe=>e.jsx(We,{value:Oe,children:Oe},Oe))})]})]}),Q("specialty")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(re,{htmlFor:"specialty",children:["Specialty or niche",te("specialty")]}),e.jsx(be,{id:"specialty",value:H.specialty||"",onChange:Oe=>ee("specialty",Oe.target.value)})]})]}),_e(0)]}),x===1&&e.jsxs(e.Fragment,{children:[Q("target_audience")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(re,{htmlFor:"target_audience",children:["Who are you trying to reach?",te("target_audience")]}),e.jsx(Ls,{id:"target_audience",rows:2,placeholder:"First-time buyers, move-up sellers, investors…",value:H.target_audience||"",onChange:Oe=>ee("target_audience",Oe.target.value)})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[Q("video_comfort")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(re,{children:["How comfortable are you on camera?",te("video_comfort")]}),e.jsxs(bs,{value:H.video_comfort||"",onValueChange:Oe=>ee("video_comfort",Oe),children:[e.jsx(ys,{children:e.jsx(_s,{placeholder:"Select"})}),e.jsx(vs,{children:["Terrified","Nervous but willing","Getting comfortable","Very comfortable"].map(Oe=>e.jsx(We,{value:Oe,children:Oe},Oe))})]})]}),Q("posting_frequency")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(re,{children:["How often do you post today?",te("posting_frequency")]}),e.jsxs(bs,{value:H.posting_frequency||"",onValueChange:Oe=>ee("posting_frequency",Oe),children:[e.jsx(ys,{children:e.jsx(_s,{placeholder:"Select"})}),e.jsx(vs,{children:["Never","Rarely","Weekly","A few times a week","Daily"].map(Oe=>e.jsx(We,{value:Oe,children:Oe},Oe))})]})]})]}),Q("content_style")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(re,{htmlFor:"content_style",children:["What content style feels like you?",te("content_style")]}),e.jsx(Ls,{id:"content_style",rows:2,placeholder:"Educational, funny, behind-the-scenes, luxury-polished…",value:H.content_style||"",onChange:Oe=>ee("content_style",Oe.target.value)})]}),Q("personal_interests")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(re,{htmlFor:"personal_interests",children:["Interests or hobbies we can weave in",te("personal_interests")]}),e.jsx(Ls,{id:"personal_interests",rows:2,value:H.personal_interests||"",onChange:Oe=>ee("personal_interests",Oe.target.value)})]}),_e(1)]}),x===2&&e.jsxs(e.Fragment,{children:[Q("primary_goal")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(re,{htmlFor:"primary_goal",children:["Your #1 goal for this program",te("primary_goal")]}),e.jsx(Ls,{id:"primary_goal",rows:3,value:H.primary_goal||"",onChange:Oe=>ee("primary_goal",Oe.target.value)})]}),Q("topics_to_avoid")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(re,{htmlFor:"topics_to_avoid",children:["Anything you don't want to talk about",te("topics_to_avoid")]}),e.jsx(Ls,{id:"topics_to_avoid",rows:2,value:H.topics_to_avoid||"",onChange:Oe=>ee("topics_to_avoid",Oe.target.value)})]}),Q("timezone")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(re,{children:["Your time zone",te("timezone")]}),e.jsxs(bs,{value:H.timezone||i.timezone,onValueChange:Oe=>ee("timezone",Oe),children:[e.jsx(ys,{children:e.jsx(_s,{placeholder:"Select"})}),e.jsx(vs,{children:["America/New_York","America/Chicago","America/Denver","America/Phoenix","America/Los_Angeles","Pacific/Honolulu"].map(Oe=>e.jsx(We,{value:Oe,children:Oe.replace("America/","").replace("_"," ")},Oe))})]})]}),_e(2),Q("consent_public_profile")&&e.jsxs("div",{className:"flex items-start gap-3 rounded-lg border border-border/60 p-4",children:[e.jsx(Li,{id:"consent_public_profile",checked:!!H.consent_public_profile,onCheckedChange:Oe=>ee("consent_public_profile",!!Oe)}),e.jsx(re,{htmlFor:"consent_public_profile",className:"text-sm font-normal leading-relaxed",children:"I'm okay with my content being reviewed and shared as an example inside the cohort."})]})]}),x===3&&e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"rounded-lg border border-border/60 p-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:i.name}),e.jsx("span",{className:"font-semibold",children:i.payment_mode==="free"?"Included":B?e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-normal text-muted-foreground line-through",children:Tp(B.original_cents,i.currency)}),Tp(oe,i.currency)]}):Tp(i.price_cents,i.currency)})]}),i.payment_mode!=="free"&&e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:t9e(oe,i.currency,i.duration_weeks)}),i.payment_mode!=="free"&&e.jsx("div",{className:"mt-3 border-t border-border/60 pt-3",children:B?e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 rounded-md bg-primary/5 px-3 py-2 text-sm",children:[e.jsxs("span",{className:"inline-flex items-center gap-2",children:[e.jsx(kg,{className:"h-3.5 w-3.5 text-primary"}),"Code ",e.jsx("span",{className:"font-mono font-semibold",children:B.code})," applied — you save ",Tp(B.discount_cents,i.currency)]}),e.jsxs($,{variant:"ghost",size:"sm",onClick:Te,disabled:g.isPending,children:[e.jsx(mr,{className:"mr-1 h-3.5 w-3.5"})," Remove"]})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"discount_code",className:"text-xs text-muted-foreground",children:"Have a discount code?"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(be,{id:"discount_code",placeholder:"Enter code",className:"font-mono uppercase",value:R,onChange:Oe=>O(Oe.target.value.toUpperCase()),onKeyDown:Oe=>{Oe.key==="Enter"&&(Oe.preventDefault(),Se())}}),e.jsx($,{variant:"outline",onClick:Se,disabled:!R.trim()||p.isPending||m.isPending,children:p.isPending||m.isPending?e.jsx(Jt,{className:"h-4 w-4 animate-spin"}):"Apply"})]})]})}),i.payment_mode==="delayed"&&e.jsxs("div",{className:"mt-3 flex items-start gap-2.5 border-t border-border/60 pt-3 text-sm",children:[e.jsx(cv,{className:"mt-0.5 h-4 w-4 shrink-0 text-primary"}),e.jsxs("span",{children:["Charged once on"," ",e.jsx("span",{className:"font-semibold",children:ru(i.charge_at||i.kickoff_at)||"the program start date"}),". No recurring billing, installments, or renewal. Cancel any time before then at no cost."]})]}),typeof o=="number"&&e.jsx("p",{className:"mt-3 text-xs text-muted-foreground",children:o>0?`${o} of ${i.capacity} seats left`:"This cohort is full"})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Li,{id:"terms",checked:A,onCheckedChange:Oe=>M(!!Oe)}),e.jsx(re,{htmlFor:"terms",className:"text-sm font-normal leading-relaxed",children:"I agree to the program terms, including the attendance and participation expectations, and understand seats are limited."})]}),i.payment_mode!=="free"&&e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(Li,{id:"charge",checked:I,onCheckedChange:Oe=>P(!!Oe)}),e.jsx(re,{htmlFor:"charge",className:"text-sm font-normal leading-relaxed",children:i.payment_mode==="delayed"?`I authorize LevelUp to charge my saved card one time — ${Tp(oe,i.currency)} for the ${tX(i.duration_weeks)} — on ${ru(i.charge_at||i.kickoff_at)||"the program start date"} unless I cancel before then. I understand this is not a subscription and will not renew.`:`I authorize LevelUp to charge my card one time — ${Tp(oe,i.currency)} for the ${tX(i.duration_weeks)} — today. This is not a subscription and will not renew.`})]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx(b0,{className:"h-3.5 w-3.5"}),"Card details are handled by Stripe — LevelUp never sees or stores them."]})]}),e.jsxs("div",{className:"flex items-center justify-between border-t border-border/60 pt-5",children:[e.jsxs($,{variant:"ghost",onClick:()=>y(Oe=>Math.max(0,Oe-1)),disabled:x===0||v,children:[e.jsx(Ia,{className:"mr-1.5 h-4 w-4"})," Back"]}),xString(s).padStart(2,"0"),LLe=s=>s.toISOString().replace(/[-:]/g,"").split(".")[0]+"Z",ZOs=({program:s,intakeComplete:t})=>{const n=s!=null&&s.kickoff_at?new Date(s.kickoff_at).getTime():null,[r,a]=k.useState(()=>Date.now());k.useEffect(()=>{const d=setInterval(()=>a(Date.now()),1e3);return()=>clearInterval(d)},[]);const i=k.useMemo(()=>{if(!n)return null;const d=Math.max(n-r,0);return{days:Math.floor(d/864e5),hours:Math.floor(d%864e5/36e5),minutes:Math.floor(d%36e5/6e4),seconds:Math.floor(d%6e4/1e3),done:d===0}},[n,r]);if(!n||!i)return null;const l=new Intl.DateTimeFormat("en-US",{weekday:"long",month:"long",day:"numeric",hour:"numeric",minute:"2-digit",timeZoneName:"short",timeZone:"America/New_York"}).format(new Date(n)),o=()=>{const d=new Date(n),u=new Date(n+90*6e4),h=["BEGIN:VCALENDAR","VERSION:2.0","PRODID:-//LevelUp//Programs//EN","BEGIN:VEVENT",`UID:kickoff-${s.id}@levelup`,`DTSTAMP:${LLe(new Date)}`,`DTSTART:${LLe(d)}`,`DTEND:${LLe(u)}`,`SUMMARY:${s.name} — Kickoff Call`,`DESCRIPTION:The official kickoff for ${s.name}. Bring a phone and a story.`,"END:VEVENT","END:VCALENDAR"].join(`\r `),m=URL.createObjectURL(new Blob([h],{type:"text/calendar"})),p=document.createElement("a");p.href=m,p.download="program-kickoff.ics",p.click(),URL.revokeObjectURL(m)},c=[{label:"Days",value:i.days},{label:"Hours",value:ILe(i.hours)},{label:"Minutes",value:ILe(i.minutes)},{label:"Seconds",value:ILe(i.seconds)}];return e.jsxs(we,{className:"relative overflow-hidden border-primary/25",children:[e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-primary/15 via-background to-secondary/10"}),s.hero_image_url&&e.jsx("img",{src:s.hero_image_url,alt:"",className:"pointer-events-none absolute inset-0 h-full w-full object-cover opacity-10"}),e.jsxs(De,{className:"relative space-y-6 p-6 md:p-9",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(qe,{className:"gap-1.5",children:[e.jsx(kn,{className:"h-3.5 w-3.5"})," Your seat is confirmed"]}),e.jsxs(qe,{variant:"outline",className:"gap-1.5",children:[e.jsx(sa,{className:"h-3.5 w-3.5"})," ",l]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("h2",{className:"text-2xl font-bold tracking-tight md:text-3xl",children:i.done?"We're live — let's go":`${s.name} kicks off soon`}),e.jsx("p",{className:"max-w-2xl text-sm text-muted-foreground md:text-base",children:i.done?"The kickoff call is starting. Head to your sessions below to join.":"Everything unlocks on kickoff day. Until then, get your setup dialed in so week one is pure momentum."})]}),e.jsx("div",{className:"grid max-w-xl grid-cols-4 gap-2 md:gap-3",children:c.map(d=>e.jsxs("div",{className:"rounded-xl border bg-background/80 px-2 py-4 text-center backdrop-blur-sm",children:[e.jsx("div",{className:"text-2xl font-bold tabular-nums tracking-tight md:text-4xl",children:d.value}),e.jsx("div",{className:"mt-1 text-[10px] uppercase tracking-widest text-muted-foreground md:text-xs",children:d.label})]},d.label))}),e.jsx("div",{className:"flex flex-wrap gap-3",children:e.jsxs($,{onClick:o,size:"lg",children:[e.jsx(i1,{className:"mr-2 h-4 w-4"})," Add kickoff to calendar"]})}),e.jsx("div",{className:"grid gap-3 sm:grid-cols-3",children:[{title:"Intake complete",body:t?"We've got what we need to tailor your coaching.":"Finish your intake so your coach knows your market and goals.",done:!!t},{title:"Kickoff on the calendar",body:"One click above adds it to Google, Apple or Outlook.",done:!1},{title:"Set up your shooting kit",body:"Phone, clip mic, tripod. That is genuinely all you need.",done:!1}].map(d=>e.jsxs("div",{className:"rounded-xl border bg-background/70 p-4 backdrop-blur-sm",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold",children:[e.jsx(Gr,{className:`h-4 w-4 ${d.done?"text-primary":"text-muted-foreground/40"}`}),d.title]}),e.jsx("p",{className:"mt-1.5 text-xs leading-relaxed text-muted-foreground",children:d.body})]},d.title))})]})]})},RLe=s=>s.toISOString().replace(/[-:]/g,"").split(".")[0]+"Z",XOs=(s,t)=>{const n=new Date(s.starts_at),r=new Date(n.getTime()+(s.duration_minutes||60)*6e4),a=["BEGIN:VCALENDAR","VERSION:2.0","PRODID:-//LevelUp//Programs//EN","BEGIN:VEVENT",`UID:${s.id}@levelup`,`DTSTAMP:${RLe(new Date)}`,`DTSTART:${RLe(n)}`,`DTEND:${RLe(r)}`,`SUMMARY:${t} — ${s.title}`,`DESCRIPTION:${(s.description||"").replace(/\n/g,"\\n")}${s.meeting_link?`\\n\\nJoin: ${s.meeting_link}`:""}`,...s.meeting_link?[`LOCATION:${s.meeting_link}`]:[],"END:VEVENT","END:VCALENDAR"].join(`\r `),i=URL.createObjectURL(new Blob([a],{type:"text/calendar"})),l=document.createElement("a");l.href=i,l.download=`${s.title.replace(/[^a-z0-9]+/gi,"-").toLowerCase()}.ics`,l.click(),URL.revokeObjectURL(i)},QOs={pdf:ea,document:rk,checklist:op,template_link:Zw,video:em,external:pd},JOs=()=>{var fe;const{slug:s}=oo(),[t]=Jc(),{isAdmin:n}=ks(),r=n?t.get("as"):null,a=t.get("name")||"this member",i=n&&(t.get("preview")==="1"||!!r),{data:l,isLoading:o}=hWe(s),{data:c}=fWe(l==null?void 0:l.id),{data:d,isLoading:u}=pAs(l==null?void 0:l.id,r),h=gAs(l==null?void 0:l.id),m=xAs(l==null?void 0:l.id),p=yAs(l==null?void 0:l.id),g=vAs(l==null?void 0:l.id),{data:x}=PMt(l==null?void 0:l.id),y=!!(l!=null&&l.kickoff_at)&&new Date(l.kickoff_at).getTime()>Date.now(),[v,_]=k.useState(!1),[j,C]=k.useState({title:"",instagram_url:""}),[A,M]=k.useState({}),[I,P]=k.useState(null),R=k.useMemo(()=>{if(!(l!=null&&l.kickoff_at))return 1;const _e=Math.floor((Date.now()-new Date(l.kickoff_at).getTime())/864e5);return Math.min(Math.max(Math.floor(_e/7)+1,1),l.duration_weeks)},[l]),O=new Set(((d==null?void 0:d.completions)||[]).map(_e=>_e.lesson_id)),B=(d==null?void 0:d.lessons)||[],U=B.length?Math.round(O.size/B.length*100):0,G=((d==null?void 0:d.videoLogs)||[]).filter(_e=>_e.week_number===R).length,H=((d==null?void 0:d.videoLogs)||[]).length,Y=(l==null?void 0:l.weekly_video_goal)||3,se=k.useMemo(()=>{const _e=new Map;((d==null?void 0:d.videoLogs)||[]).forEach(he=>_e.set(he.week_number,(_e.get(he.week_number)||0)+1));let ve=0;for(let he=R;he>=1;he--)if((_e.get(he)||0)>=Y)ve++;else if(he!==R)break;return ve},[d==null?void 0:d.videoLogs,R,Y]);if(o||u)return e.jsx(Xs,{children:e.jsxs("div",{className:"mx-auto max-w-6xl space-y-6 p-8",children:[e.jsx(fn,{className:"h-28 w-full rounded-xl"}),e.jsx(fn,{className:"h-64 w-full rounded-xl"})]})});if(!l)return e.jsx(Xs,{children:e.jsxs("div",{className:"mx-auto max-w-xl p-12 text-center",children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Program not found"}),e.jsx($,{asChild:!0,className:"mt-6",children:e.jsx(nr,{to:"/programs",children:"Back to Programs"})})]})});if(!kU(c)&&!i)return e.jsx(Xs,{children:e.jsxs("div",{className:"mx-auto max-w-xl space-y-4 p-12 text-center",children:[e.jsx("h1",{className:"text-2xl font-bold",children:"You're not enrolled yet"}),e.jsxs("p",{className:"text-muted-foreground",children:["Reserve your seat in ",l.name," to unlock the roadmap, lessons and mastermind sessions."]}),e.jsx($,{asChild:!0,size:"lg",children:e.jsx(nr,{to:`/programs/${l.slug}`,children:"View the program"})})]})});const ee=((d==null?void 0:d.events)||[]).filter(_e=>new Date(_e.starts_at)>=new Date),oe=((d==null?void 0:d.events)||[]).filter(_e=>new Date(_e.starts_at)_e.is_pinned),te=[...(d==null?void 0:d.myResources)||[],...(d==null?void 0:d.resources)||[]].reduce((_e,ve)=>{const he=ve.user_id?`Just for you · ${ve.category}`:ve.category;return(_e[he]||(_e[he]=[])).push(ve),_e},{}),le=((d==null?void 0:d.progress)||[]).find(_e=>_e.week_number===R)||{};return e.jsx(Xs,{children:e.jsx("div",{className:"program-theme-neon relative min-h-screen",children:e.jsxs("div",{className:"relative mx-auto w-full max-w-6xl space-y-8 p-4 md:p-8",children:[i&&(r||!kU(c))&&e.jsx(we,{className:"border-primary/40 bg-primary/5",children:e.jsxs(De,{className:"flex flex-wrap items-center justify-between gap-3 p-4 text-sm",children:[e.jsx("span",{children:r?e.jsxs(e.Fragment,{children:[e.jsx("strong",{children:"Admin view"})," — you're seeing ",a,"'s dashboard exactly as they see it (progress, check-ins, videos and personal resources). It's read-only: avoid logging videos or check-ins here."]}):e.jsxs(e.Fragment,{children:[e.jsx("strong",{children:"Admin preview"})," — this is exactly what an enrollee sees. Your own progress, check-ins and video logs are empty because you're not enrolled."]})}),e.jsx($,{variant:"outline",size:"sm",asChild:!0,children:e.jsx(nr,{to:"/admin/programs",children:"Back to Programs admin"})})]})}),e.jsxs("header",{className:"space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(qe,{variant:"secondary",children:["Week ",R," of ",l.duration_weeks]}),(c==null?void 0:c.status)==="scheduled_for_charge"&&c.charge_scheduled_at&&e.jsxs(qe,{variant:"outline",children:["Billing ",ru(c.charge_scheduled_at)]}),(c==null?void 0:c.status)==="payment_failed"&&e.jsx(qe,{variant:"destructive",children:"Payment issue"})]}),e.jsx("p",{className:"neon-eyebrow font-semibold",children:"LevelUp Program"}),e.jsx("h1",{className:"neon-title w-fit text-4xl font-black uppercase tracking-tight md:text-5xl",children:l.name}),l.subtitle&&e.jsx("p",{className:"text-muted-foreground",children:l.subtitle})]}),y&&e.jsx(ZOs,{program:l,intakeComplete:!!x}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-4",children:[e.jsx(we,{className:"neon-topline",children:e.jsxs(De,{className:"space-y-1.5 p-5",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs uppercase tracking-[0.16em] text-muted-foreground",children:[e.jsx(_h,{className:"h-3.5 w-3.5 text-primary"})," This week"]}),e.jsxs("p",{className:"neon-stat text-3xl font-black",children:[G,e.jsxs("span",{className:"text-base font-normal text-muted-foreground",children:[" / ",Y]})]}),e.jsx(ho,{value:Math.min(G/Y*100,100),className:"h-1.5"})]})}),e.jsx(we,{className:"neon-topline",children:e.jsxs(De,{className:"space-y-1.5 p-5",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs uppercase tracking-[0.16em] text-muted-foreground",children:[e.jsx(em,{className:"h-3.5 w-3.5 text-primary"})," Videos posted"]}),e.jsx("p",{className:"neon-stat text-3xl font-black",children:H}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"since kickoff"})]})}),e.jsx(we,{className:"neon-topline",children:e.jsxs(De,{className:"space-y-1.5 p-5",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs uppercase tracking-[0.16em] text-muted-foreground",children:[e.jsx(iu,{className:"h-3.5 w-3.5 text-primary"})," Streak"]}),e.jsxs("p",{className:"neon-stat text-3xl font-black",children:[se," wk"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"hitting your goal"})]})}),e.jsx(we,{className:"neon-topline",children:e.jsxs(De,{className:"space-y-1.5 p-5",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs uppercase tracking-[0.16em] text-muted-foreground",children:[e.jsx(mc,{className:"h-3.5 w-3.5 text-primary"})," Curriculum"]}),e.jsxs("p",{className:"neon-stat text-3xl font-black",children:[U,"%"]}),e.jsx(ho,{value:U,className:"h-1.5"})]})})]}),e.jsxs("div",{className:"flex flex-wrap gap-3",children:[e.jsxs(zs,{open:v,onOpenChange:_,children:[e.jsx(yl,{asChild:!0,children:e.jsxs($,{children:[e.jsx(nn,{className:"mr-1.5 h-4 w-4"})," Log a video"]})}),e.jsxs(Rs,{children:[e.jsx(Vs,{children:e.jsx($s,{children:"Log a posted video"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"v-title",children:"What was it about?"}),e.jsx(be,{id:"v-title",value:j.title,onChange:_e=>C(ve=>({...ve,title:_e.target.value}))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"v-url",children:"Instagram link (optional)"}),e.jsx(be,{id:"v-url",placeholder:"https://instagram.com/reel/…",value:j.instagram_url,onChange:_e=>C(ve=>({...ve,instagram_url:_e.target.value}))})]})]}),e.jsx(kr,{children:e.jsx($,{onClick:async()=>{await m.mutateAsync({week_number:R,...j}),C({title:"",instagram_url:""}),_(!1)},children:"Log video"})})]})]}),((fe=ee[0])==null?void 0:fe.meeting_link)&&e.jsx($,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:ee[0].meeting_link,target:"_blank",rel:"noreferrer",children:[e.jsx(mm,{className:"mr-1.5 h-4 w-4"})," Join next session"]})})]}),me.length>0&&e.jsx(we,{className:"border-primary/30 bg-primary/5",children:e.jsx(De,{className:"space-y-3 p-5",children:me.map(_e=>e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(xm,{className:"mt-0.5 h-4 w-4 shrink-0 text-primary"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:_e.title}),_e.body&&e.jsx("p",{className:"text-sm text-muted-foreground",children:_e.body})]})]},_e.id))})}),e.jsxs(ya,{defaultValue:"roadmap",children:[e.jsxs(va,{className:"flex w-full flex-wrap justify-start",children:[e.jsx(is,{value:"roadmap",children:"Roadmap"}),e.jsx(is,{value:"lessons",children:"Lessons"}),e.jsx(is,{value:"checkin",children:"Weekly check-in"}),e.jsx(is,{value:"events",children:"Sessions"}),e.jsx(is,{value:"resources",children:"Resources"}),e.jsx(is,{value:"profile",children:"Profile review"})]}),e.jsxs(cs,{value:"roadmap",className:"mt-6 space-y-4",children:[((d==null?void 0:d.weeks)||[]).length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"The roadmap will appear here before kickoff."}),((d==null?void 0:d.weeks)||[]).map(_e=>{const ve=_e.release_at&&new Date(_e.release_at)>new Date;return e.jsx(we,{className:ve?"opacity-60":_e.week_number===R?"border-primary/50":"",children:e.jsxs(De,{className:"space-y-2 p-5",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(qe,{variant:"outline",children:["Week ",_e.week_number]}),e.jsx("span",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:_e.phase}),_e.week_number===R&&e.jsx(qe,{children:"Current"}),ve&&e.jsxs("span",{className:"inline-flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(sa,{className:"h-3 w-3"})," Unlocks ",ru(_e.release_at)]})]}),e.jsx("h3",{className:"font-semibold",children:_e.title}),_e.learning_goal&&e.jsx("p",{className:"text-sm text-muted-foreground",children:_e.learning_goal}),!ve&&Array.isArray(_e.tasks)&&_e.tasks.length>0&&e.jsx("ul",{className:"mt-2 space-y-1.5",children:_e.tasks.map((he,Se)=>e.jsxs("li",{className:"flex items-start gap-2 text-sm",children:[e.jsx(Gr,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-primary"}),typeof he=="string"?he:he.label]},Se))})]})},_e.id)})]}),e.jsxs(cs,{value:"lessons",className:"mt-6 space-y-3",children:[B.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Lessons unlock as the program progresses."}),B.map(_e=>{const ve=IMt(_e.video_url),he=I===_e.id;return e.jsx(we,{children:e.jsxs(De,{className:"space-y-4 p-5",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-4",children:[e.jsx(Li,{checked:O.has(_e.id),onCheckedChange:Se=>h.mutate({lessonId:_e.id,done:!!Se}),"aria-label":`Mark ${_e.title} complete`}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"font-medium",children:_e.title}),_e.summary&&e.jsx("p",{className:"text-sm text-muted-foreground",children:_e.summary}),_e.action_assignment&&e.jsxs("p",{className:"mt-1 text-xs text-primary",children:["Action: ",_e.action_assignment]})]}),_e.duration_minutes&&e.jsxs("span",{className:"inline-flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(sa,{className:"h-3 w-3"})," ",_e.duration_minutes," min"]}),e.jsxs("div",{className:"flex gap-2",children:[_e.video_url&&(ve||NY(_e.video_url))&&e.jsxs($,{size:"sm",variant:"outline",onClick:()=>P(he?null:_e.id),children:[e.jsx(mm,{className:"mr-1.5 h-3.5 w-3.5"})," ",he?"Close":"Watch"]}),_e.video_url&&!ve&&!NY(_e.video_url)&&e.jsx($,{size:"sm",variant:"outline",asChild:!0,children:e.jsxs("a",{href:_e.video_url,target:"_blank",rel:"noreferrer",children:[e.jsx(mm,{className:"mr-1.5 h-3.5 w-3.5"})," Watch"]})}),_e.worksheet_url&&e.jsx($,{size:"sm",variant:"ghost",asChild:!0,children:e.jsxs("a",{href:_e.worksheet_url,target:"_blank",rel:"noreferrer",children:[e.jsx(ji,{className:"mr-1.5 h-3.5 w-3.5"})," Worksheet"]})})]})]}),he&&ve&&e.jsx("div",{className:"overflow-hidden rounded-lg border border-border/60",children:e.jsx("iframe",{src:ve,title:_e.title,className:"aspect-video w-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; picture-in-picture",allowFullScreen:!0})}),he&&!ve&&NY(_e.video_url)&&e.jsx("div",{className:"overflow-hidden rounded-lg border border-border/60 bg-black",children:e.jsx("video",{src:_e.video_url,controls:!0,autoPlay:!0,className:"aspect-video w-full"})})]})},_e.id)})]}),e.jsx(cs,{value:"checkin",className:"mt-6",children:e.jsx(we,{children:e.jsxs(De,{className:"space-y-5 p-6",children:[e.jsxs("div",{children:[e.jsxs("h3",{className:"font-semibold",children:["Week ",R," check-in"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Two minutes of honesty here is what makes the next week better."})]}),e.jsx("div",{className:"grid gap-4 sm:grid-cols-3",children:[["videos_planned","Videos planned"],["videos_recorded","Videos recorded"],["videos_posted","Videos posted"]].map(([_e,ve])=>e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:_e,children:ve}),e.jsx(be,{id:_e,type:"number",min:0,defaultValue:le[_e]??"",onChange:he=>M(Se=>({...Se,[_e]:Number(he.target.value)}))})]},_e))}),[["biggest_win","Biggest win"],["biggest_challenge","Biggest challenge"],["what_to_improve","What you’ll change next week"]].map(([_e,ve])=>e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:_e,children:ve}),e.jsx(Ls,{id:_e,rows:2,defaultValue:le[_e]??"",onChange:he=>M(Se=>({...Se,[_e]:he.target.value}))})]},_e)),e.jsx($,{onClick:()=>p.mutate({week_number:R,goal_videos:Y,...A}),children:"Save check-in"})]})})}),e.jsxs(cs,{value:"events",className:"mt-6 space-y-4",children:[ee.length===0&&oe.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Sessions will be scheduled before kickoff."}),ee.map(_e=>e.jsx(we,{className:"border-primary/30",children:e.jsxs(De,{className:"flex flex-wrap items-center gap-4 p-5",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(qe,{variant:"secondary",className:"capitalize",children:String(_e.event_kind).replace("_"," ")}),e.jsxs("span",{className:"inline-flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(fd,{className:"h-3 w-3"})," ",ru(_e.starts_at,!0)]})]}),e.jsx("p",{className:"mt-1.5 font-medium",children:_e.title}),_e.speaker&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:["with ",_e.speaker]}),_e.description&&e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:_e.description})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx($,{size:"sm",variant:"outline",onClick:()=>g.mutate({eventId:_e.id,optIn:!0}),children:"Remind me"}),e.jsxs($,{size:"sm",variant:"ghost",onClick:()=>XOs(_e,l.name),children:[e.jsx(fd,{className:"mr-1.5 h-3.5 w-3.5"})," Add to calendar"]}),_e.meeting_link&&e.jsx($,{size:"sm",asChild:!0,children:e.jsxs("a",{href:_e.meeting_link,target:"_blank",rel:"noreferrer",children:["Join ",e.jsx(Ir,{className:"ml-1.5 h-3.5 w-3.5"})]})})]})]})},_e.id)),oe.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"pt-2 text-sm font-semibold uppercase tracking-wider text-muted-foreground",children:"Replays"}),oe.map(_e=>e.jsx(we,{children:e.jsxs(De,{className:"flex flex-wrap items-center gap-4 p-5",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"font-medium",children:_e.title}),e.jsx("p",{className:"text-xs text-muted-foreground",children:ru(_e.starts_at,!0)})]}),_e.replay_url?e.jsx($,{size:"sm",variant:"outline",asChild:!0,children:e.jsxs("a",{href:_e.replay_url,target:"_blank",rel:"noreferrer",children:[e.jsx(mm,{className:"mr-1.5 h-3.5 w-3.5"})," Watch replay"]})}):e.jsx("span",{className:"text-xs text-muted-foreground",children:"Replay coming soon"})]})},_e.id))]})]}),e.jsxs(cs,{value:"resources",className:"mt-6 space-y-8",children:[Object.keys(te).length===0&&e.jsx(we,{className:"border-dashed",children:e.jsxs(De,{className:"flex flex-col items-center gap-2 p-12 text-center",children:[e.jsx(ea,{className:"h-8 w-8 text-muted-foreground"}),e.jsx("p",{className:"font-medium",children:"Your resource library is being built"}),e.jsx("p",{className:"max-w-md text-sm text-muted-foreground",children:"Worksheets, scripts and swipe files will appear here as the program unlocks."})]})}),Object.entries(te).map(([_e,ve])=>e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("h3",{className:"text-sm font-semibold uppercase tracking-[0.18em] text-muted-foreground",children:_e}),e.jsx("span",{className:"h-px flex-1 bg-border"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[ve.length," item",ve.length===1?"":"s"]})]}),e.jsx("div",{className:"grid gap-4 md:grid-cols-2 xl:grid-cols-3",children:ve.map(he=>{const Se=Cee(he),Te=QOs[he.resource_kind]||ea;return e.jsxs("div",{role:"button",tabIndex:0,onClick:()=>Se&&kY(he),onKeyDown:Ie=>{Se&&(Ie.key==="Enter"||Ie.key===" ")&&(Ie.preventDefault(),kY(he))},className:"group relative flex cursor-pointer flex-col gap-3 overflow-hidden rounded-2xl border border-border/60 bg-card p-5 transition-all hover:-translate-y-0.5 hover:border-primary/50 hover:shadow-lg",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsx("div",{className:"flex h-11 w-11 items-center justify-center rounded-xl bg-primary/10 text-primary",children:e.jsx(Te,{className:"h-5 w-5"})}),e.jsx(qe,{variant:"secondary",className:"capitalize",children:String(he.resource_kind).replace("_"," ")})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"font-semibold leading-snug",children:he.title}),he.description&&e.jsx("p",{className:"line-clamp-3 text-sm text-muted-foreground",children:he.description})]}),e.jsxs("div",{className:"mt-auto flex items-center gap-4",children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5 text-sm font-medium text-primary",children:[e.jsx(Ir,{className:"h-3.5 w-3.5"})," Open"]}),he.file_path&&e.jsxs("button",{type:"button",onClick:Ie=>{Ie.stopPropagation(),kY(he,"download")},className:"inline-flex items-center gap-1.5 text-sm font-medium text-muted-foreground hover:text-primary",children:[e.jsx(ji,{className:"h-3.5 w-3.5"})," Download"]})]})]},he.id)})})]},_e))]}),e.jsx(cs,{value:"profile",className:"mt-6",children:e.jsx(we,{children:e.jsxs(De,{className:"space-y-4 p-6",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Sf,{className:"h-5 w-5 text-primary"}),e.jsx("h3",{className:"font-semibold",children:"Your profile review"})]}),!(d!=null&&d.analysis)||d.analysis.status==="not_submitted"?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Your Instagram review hasn't been submitted yet. Your coach will request screenshots during onboarding week."}):d.analysis.status==="in_review"?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Your profile is in review — you'll get a notification when the report is ready."}):e.jsxs("div",{className:"space-y-4",children:[d.analysis.scores&&Object.keys(d.analysis.scores).length>0&&e.jsx("div",{className:"grid gap-3 sm:grid-cols-2",children:Object.entries(d.analysis.scores).map(([_e,ve])=>e.jsxs("div",{className:"space-y-1 rounded-lg border border-border/60 p-3",children:[e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"capitalize",children:_e.replace(/_/g," ")}),e.jsxs("span",{className:"font-semibold",children:[ve,"/10"]})]}),e.jsx(ho,{value:Number(ve)*10,className:"h-1.5"})]},_e))}),Array.isArray(d.analysis.top_priorities)&&d.analysis.top_priorities.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm font-semibold",children:"Top priorities"}),e.jsx("ul",{className:"space-y-1.5",children:d.analysis.top_priorities.map((_e,ve)=>e.jsxs("li",{className:"flex items-start gap-2 text-sm",children:[e.jsx(oh,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-primary"}),typeof _e=="string"?_e:_e.label]},ve))})]}),d.analysis.member_notes&&e.jsx("div",{className:"rounded-lg border border-border/60 bg-muted/30 p-4 text-sm leading-relaxed whitespace-pre-line",children:d.analysis.member_notes}),d.analysis.report_url&&e.jsx($,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:d.analysis.report_url,target:"_blank",rel:"noreferrer",children:[e.jsx(ji,{className:"mr-1.5 h-4 w-4"})," Download full report"]})})]})]})})})]})]})})})},Qa=k.forwardRef(({className:s,...t},n)=>e.jsx("div",{className:"relative w-full overflow-auto",children:e.jsx("table",{ref:n,className:Ot("w-full caption-bottom text-sm",s),...t})}));Qa.displayName="Table";const Ja=k.forwardRef(({className:s,...t},n)=>e.jsx("thead",{ref:n,className:Ot("[&_tr]:border-b",s),...t}));Ja.displayName="TableHeader";const ei=k.forwardRef(({className:s,...t},n)=>e.jsx("tbody",{ref:n,className:Ot("[&_tr:last-child]:border-0",s),...t}));ei.displayName="TableBody";const eFs=k.forwardRef(({className:s,...t},n)=>e.jsx("tfoot",{ref:n,className:Ot("border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",s),...t}));eFs.displayName="TableFooter";const vn=k.forwardRef(({className:s,...t},n)=>e.jsx("tr",{ref:n,className:Ot("border-b transition-colors data-[state=selected]:bg-muted hover:bg-muted/50",s),...t}));vn.displayName="TableRow";const Dt=k.forwardRef(({className:s,...t},n)=>e.jsx("th",{ref:n,className:Ot("h-12 px-4 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0",s),...t}));Dt.displayName="TableHead";const _t=k.forwardRef(({className:s,...t},n)=>e.jsx("td",{ref:n,className:Ot("p-4 align-middle [&:has([role=checkbox])]:pr-0",s),...t}));_t.displayName="TableCell";const tFs=k.forwardRef(({className:s,...t},n)=>e.jsx("caption",{ref:n,className:Ot("mt-4 text-sm text-muted-foreground",s),...t}));tFs.displayName="TableCaption";const Tre=s=>{if(!s)return"";const t=new Date(s),n=r=>String(r).padStart(2,"0");return`${t.getFullYear()}-${n(t.getMonth()+1)}-${n(t.getDate())}T${n(t.getHours())}:${n(t.getMinutes())}`},Mre=s=>s?new Date(s).toISOString():null,DLe=s=>({name:s.name||"",slug:s.slug||"",subtitle:s.subtitle||"",tagline:s.tagline||"",short_description:s.short_description||"",description:s.description||"",price_cents:s.price_cents??0,currency:s.currency||"usd",capacity:s.capacity??0,duration_weeks:s.duration_weeks??13,weekly_video_goal:s.weekly_video_goal??3,payment_mode:s.payment_mode||"delayed",payment_grace_days:s.payment_grace_days??3,timezone:s.timezone||"America/New_York",accent_color:s.accent_color||"",cover_image_url:s.cover_image_url||"",hero_image_url:s.hero_image_url||"",promo_video_url:s.promo_video_url||"",promo_video_headline:s.promo_video_headline||"",enrollment_open_at:Tre(s.enrollment_open_at),enrollment_close_at:Tre(s.enrollment_close_at),kickoff_at:Tre(s.kickoff_at),charge_at:Tre(s.charge_at),status:s.status||"draft",is_public:!!s.is_public,is_featured:!!s.is_featured,sort_order:s.sort_order??0}),sFs=({program:s,onSaved:t})=>{const[n,r]=k.useState(()=>DLe(s)),[a,i]=k.useState(!1),[l,o]=k.useState(!1),[c,d]=k.useState(null),u=k.useRef(null),h=k.useRef(null);k.useEffect(()=>{r(DLe(s)),i(!1)},[s.id,s.updated_at]);const m=(y,v)=>{r(_=>({..._,[y]:v})),i(!0)},p=async(y,v)=>{if(!y.type.startsWith("image/")){ae.error("Please choose an image file");return}if(y.size>8*1024*1024){ae.error("Image must be under 8MB");return}d(v);try{const _=y.name.split(".").pop()||"jpg",j=`programs/${s.id}/${v}-${Date.now()}.${_}`,{error:C}=await V.storage.from("event-images").upload(j,y,{cacheControl:"31536000",upsert:!0});if(C)throw C;const{data:A}=V.storage.from("event-images").getPublicUrl(j);m(v==="cover"?"cover_image_url":"hero_image_url",A.publicUrl),ae.success(`${v==="cover"?"Cover":"Hero"} image uploaded — remember to save`)}catch(_){ae.error(_.message||"Upload failed")}finally{d(null)}},g=async()=>{if(!n.name.trim())return ae.error("Program name is required");if(!n.slug.trim())return ae.error("Slug is required");o(!0);try{const y={name:n.name.trim(),slug:n.slug.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,""),subtitle:n.subtitle||null,tagline:n.tagline||null,short_description:n.short_description||null,description:n.description||null,price_cents:Math.max(0,Math.round(n.price_cents)),currency:n.currency||"usd",capacity:Math.max(0,Math.round(n.capacity)),duration_weeks:Math.max(1,Math.round(n.duration_weeks)),weekly_video_goal:Math.max(0,Math.round(n.weekly_video_goal)),payment_mode:n.payment_mode,payment_grace_days:Math.max(0,Math.round(n.payment_grace_days)),timezone:n.timezone||"America/New_York",accent_color:n.accent_color||null,cover_image_url:n.cover_image_url||null,hero_image_url:n.hero_image_url||null,promo_video_url:n.promo_video_url.trim()||null,promo_video_headline:n.promo_video_headline.trim()||null,enrollment_open_at:Mre(n.enrollment_open_at),enrollment_close_at:Mre(n.enrollment_close_at),kickoff_at:Mre(n.kickoff_at),charge_at:Mre(n.charge_at),status:n.status,is_public:n.is_public,is_featured:n.is_featured,sort_order:Math.round(n.sort_order)},{error:v}=await V.from("programs").update(y).eq("id",s.id);if(v)throw v;ae.success("Program saved"),i(!1),t()}catch(y){ae.error(y.message||"Could not save the program")}finally{o(!1)}},x=({kind:y,label:v,hint:_})=>{const j=y==="cover"?n.cover_image_url:n.hero_image_url,C=y==="cover"?u:h;return e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:v}),e.jsxs("div",{className:"flex flex-wrap items-start gap-4",children:[e.jsx("div",{className:"relative h-28 w-48 shrink-0 overflow-hidden rounded-lg border border-border bg-muted/40",children:j?e.jsxs(e.Fragment,{children:[e.jsx("img",{src:j,alt:`${v} preview`,className:"h-full w-full object-cover"}),e.jsx("button",{type:"button",onClick:()=>m(y==="cover"?"cover_image_url":"hero_image_url",""),className:"absolute right-1.5 top-1.5 rounded-full bg-background/90 p-1 text-foreground shadow","aria-label":`Remove ${v}`,children:e.jsx(mr,{className:"h-3.5 w-3.5"})})]}):e.jsxs("div",{className:"flex h-full w-full flex-col items-center justify-center gap-1 text-muted-foreground",children:[e.jsx(gb,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs",children:"No image"})]})}),e.jsxs("div",{className:"min-w-[220px] flex-1 space-y-2",children:[e.jsx("input",{ref:C,type:"file",accept:"image/*",className:"hidden",onChange:A=>{var I;const M=(I=A.target.files)==null?void 0:I[0];M&&p(M,y),A.target.value=""}}),e.jsxs($,{type:"button",variant:"outline",size:"sm",onClick:()=>{var A;return(A=C.current)==null?void 0:A.click()},disabled:c===y,children:[c===y?e.jsx(Jt,{className:"mr-1.5 h-4 w-4 animate-spin"}):e.jsx(gi,{className:"mr-1.5 h-4 w-4"}),"Upload image"]}),e.jsx(be,{placeholder:"…or paste an image URL",value:j,onChange:A=>m(y==="cover"?"cover_image_url":"hero_image_url",A.target.value)}),e.jsx("p",{className:"text-xs text-muted-foreground",children:_})]})]})]})};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"sticky top-0 z-10 -mx-1 flex flex-wrap items-center justify-between gap-3 rounded-lg border border-border bg-background/95 px-4 py-3 backdrop-blur",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:a?"You have unsaved changes.":"All changes saved."}),e.jsxs("div",{className:"flex gap-2",children:[a&&e.jsx($,{variant:"ghost",onClick:()=>{r(DLe(s)),i(!1)},children:"Discard"}),e.jsxs($,{onClick:g,disabled:l||!a,children:[l?e.jsx(Jt,{className:"mr-1.5 h-4 w-4 animate-spin"}):e.jsx(Ml,{className:"mr-1.5 h-4 w-4"}),"Save changes"]})]})]}),e.jsx(we,{children:e.jsxs(De,{className:"space-y-5 p-6",children:[e.jsx("h3",{className:"text-sm font-semibold uppercase tracking-wide text-muted-foreground",children:"Basics"}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Program name"}),e.jsx(be,{value:n.name,onChange:y=>m("name",y.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Slug (public URL)"}),e.jsx(be,{value:n.slug,onChange:y=>m("slug",y.target.value)}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["/programs/",n.slug||"slug"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Subtitle"}),e.jsx(be,{value:n.subtitle,onChange:y=>m("subtitle",y.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Tagline"}),e.jsx(be,{value:n.tagline,onChange:y=>m("tagline",y.target.value)})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Short description (cards & previews)"}),e.jsx(Ls,{rows:2,value:n.short_description,onChange:y=>m("short_description",y.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Full program description (sales page)"}),e.jsx(Ls,{rows:8,value:n.description,onChange:y=>m("description",y.target.value)})]})]})}),e.jsx(we,{children:e.jsxs(De,{className:"space-y-6 p-6",children:[e.jsx("h3",{className:"text-sm font-semibold uppercase tracking-wide text-muted-foreground",children:"Imagery & branding"}),e.jsx(x,{kind:"cover",label:"Program cover image",hint:"Shown on the Programs list and enrollment cards. 1200×630 works great."}),e.jsx(x,{kind:"hero",label:"Hero banner (optional)",hint:"Wide banner used at the top of the program sales page."}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Promo video URL (optional)"}),e.jsx(be,{placeholder:"https://youtu.be/… , Vimeo, or a direct .mp4 link",value:n.promo_video_url,onChange:y=>m("promo_video_url",y.target.value)}),e.jsx(be,{placeholder:"Video headline (e.g. Watch: what 90 days inside Reel Estate looks like)",value:n.promo_video_headline,onChange:y=>m("promo_video_headline",y.target.value)}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Plays in a cinematic player near the top of the program signup page."})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Accent color"}),e.jsx(be,{placeholder:"#406E71",value:n.accent_color,onChange:y=>m("accent_color",y.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Sort order"}),e.jsx(be,{type:"number",value:n.sort_order,onChange:y=>m("sort_order",Number(y.target.value))})]})]})]})}),e.jsx(we,{children:e.jsxs(De,{className:"space-y-5 p-6",children:[e.jsx("h3",{className:"text-sm font-semibold uppercase tracking-wide text-muted-foreground",children:"Pricing & seats"}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"One-time price (USD)"}),e.jsx(be,{type:"number",min:0,step:"1",value:n.price_cents/100,onChange:y=>m("price_cents",Math.round(Number(y.target.value)*100))}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Charged one time for the full program — never recurring."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Seats (capacity)"}),e.jsx(be,{type:"number",min:0,value:n.capacity,onChange:y=>m("capacity",Number(y.target.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Billing mode"}),e.jsxs(bs,{value:n.payment_mode,onValueChange:y=>m("payment_mode",y),children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"delayed",children:"Save card, charge once later"}),e.jsx(We,{value:"immediate",children:"Charge once at checkout"}),e.jsx(We,{value:"free",children:"Free / included"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Charge date (one-time)"}),e.jsx(be,{type:"datetime-local",value:n.charge_at,onChange:y=>m("charge_at",y.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Payment grace days"}),e.jsx(be,{type:"number",min:0,value:n.payment_grace_days,onChange:y=>m("payment_grace_days",Number(y.target.value))}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Days of access kept after a failed charge before access is paused."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Currency"}),e.jsx(be,{value:n.currency,onChange:y=>m("currency",y.target.value)})]})]})]})}),e.jsx(we,{children:e.jsxs(De,{className:"space-y-5 p-6",children:[e.jsx("h3",{className:"text-sm font-semibold uppercase tracking-wide text-muted-foreground",children:"Schedule & structure"}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Enrollment opens"}),e.jsx(be,{type:"datetime-local",value:n.enrollment_open_at,onChange:y=>m("enrollment_open_at",y.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Enrollment closes"}),e.jsx(be,{type:"datetime-local",value:n.enrollment_close_at,onChange:y=>m("enrollment_close_at",y.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Kickoff"}),e.jsx(be,{type:"datetime-local",value:n.kickoff_at,onChange:y=>m("kickoff_at",y.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Length (weeks)"}),e.jsx(be,{type:"number",min:1,value:n.duration_weeks,onChange:y=>m("duration_weeks",Number(y.target.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Videos per week goal"}),e.jsx(be,{type:"number",min:0,value:n.weekly_video_goal,onChange:y=>m("weekly_video_goal",Number(y.target.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Timezone"}),e.jsx(be,{value:n.timezone,onChange:y=>m("timezone",y.target.value)})]})]})]})}),e.jsx(we,{children:e.jsxs(De,{className:"space-y-5 p-6",children:[e.jsx("h3",{className:"text-sm font-semibold uppercase tracking-wide text-muted-foreground",children:"Visibility"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Status"}),e.jsxs(bs,{value:n.status,onValueChange:y=>m("status",y),children:[e.jsx(ys,{className:"sm:max-w-xs",children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"draft",children:"Draft (hidden)"}),e.jsx(We,{value:"published",children:"Published (members can enroll)"}),e.jsx(We,{value:"archived",children:"Archived"})]})]})]}),e.jsxs("div",{className:"flex items-center justify-between gap-4 border-t border-border/60 pt-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Featured"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Pin this program to the top."})]}),e.jsx(On,{checked:n.is_featured,onCheckedChange:y=>m("is_featured",y)})]}),e.jsxs("div",{className:"flex items-center justify-between gap-4 border-t border-border/60 pt-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Visible to all members"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Turn off to keep it invite-only via a direct link."})]}),e.jsx(On,{checked:n.is_public,onCheckedChange:y=>m("is_public",y)})]})]})}),e.jsx("div",{className:"flex justify-end pb-4",children:e.jsxs($,{onClick:g,disabled:l||!a,size:"lg",children:[l?e.jsx(Jt,{className:"mr-1.5 h-4 w-4 animate-spin"}):e.jsx(Ml,{className:"mr-1.5 h-4 w-4"}),"Save changes"]})})]})},Fut={title:"",description:"",category:"Personal",resource_kind:"pdf",url:"",file_path:"",status:"published",sort_order:0},nFs=({programId:s,userId:t,memberName:n})=>{const{data:r=[],isLoading:a}=IAs(s,t),i=LAs(s,t),l=RAs(),[o,c]=k.useState(!1),[d,u]=k.useState({...Fut}),[h,m]=k.useState(!1),p=k.useRef(null),g=()=>{u({...Fut,sort_order:r.length}),c(!0)},x=_=>{u({id:_.id,title:_.title,description:_.description||"",category:_.category||"Personal",resource_kind:_.resource_kind,url:_.url||"",file_path:_.file_path||"",status:_.status,sort_order:_.sort_order}),c(!0)},y=async _=>{if(!(!_||!s||!t)){if(_.size>50*1024*1024)return ae.error("File must be under 50MB");m(!0);try{const j=_.name.split(".").pop()||"pdf",C=`programs/${s}/members/${t}/${Date.now()}-${Math.random().toString(36).slice(2,8)}.${j}`,{error:A}=await V.storage.from(Qq).upload(C,_,{contentType:_.type||"application/pdf",upsert:!1});if(A)throw A;u(M=>({...M,file_path:C,url:"",title:M.title||_.name.replace(/\.[^.]+$/,""),resource_kind:_.type==="application/pdf"?"pdf":M.resource_kind})),ae.success("File uploaded")}catch(j){ae.error(j.message||"Upload failed")}finally{m(!1),p.current&&(p.current.value="")}}},v=async()=>{if(!d.title.trim())return ae.error("Give the resource a title");if(!d.file_path&&!d.url.trim())return ae.error("Upload a file or paste a link");await i.mutateAsync({...d,sort_order:Number(d.sort_order)||0}),c(!1)};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap items-end justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs("p",{className:"flex items-center gap-1.5 font-medium",children:[e.jsx(fu,{className:"h-4 w-4 text-primary"})," Personal resources"]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Only ",n||"this member"," can see these — they appear in a “Just for you” section on their program dashboard."]})]}),e.jsxs($,{size:"sm",onClick:g,disabled:!t,children:[e.jsx(nn,{className:"mr-1.5 h-4 w-4"})," Add for this member"]})]}),a?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading…"}):r.length===0?e.jsx(we,{className:"border-dashed",children:e.jsx(De,{className:"p-6 text-center text-sm text-muted-foreground",children:"No personal resources yet. Upload their custom plan, feedback doc or scripts."})}):e.jsx("div",{className:"space-y-2",children:r.map(_=>e.jsx(we,{className:"border-border/60",children:e.jsxs(De,{className:"flex flex-wrap items-start justify-between gap-3 p-4",children:[e.jsxs("div",{className:"min-w-0 space-y-1.5",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("p",{className:"font-medium",children:_.title}),e.jsx(qe,{variant:"secondary",children:_.category}),e.jsx(qe,{variant:"outline",className:"capitalize",children:_.resource_kind.replace("_"," ")}),_.status!=="published"&&e.jsx(qe,{variant:"outline",className:"capitalize",children:_.status})]}),_.description&&e.jsx("p",{className:"max-w-xl text-sm text-muted-foreground",children:_.description}),Cee(_)&&e.jsxs("button",{type:"button",onClick:()=>kY(_),className:"inline-flex items-center gap-1 text-xs text-primary hover:underline",children:[e.jsx(Ir,{className:"h-3 w-3"})," Open"]})]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx($,{variant:"ghost",size:"icon",onClick:()=>x(_),children:e.jsx(ui,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:async()=>{await io(`Remove "${_.title}"?`)&&l.mutate(_)},children:e.jsx(Un,{className:"h-4 w-4 text-destructive"})})]})]})},_.id))}),e.jsx(zs,{open:o,onOpenChange:c,children:e.jsxs(Rs,{className:"max-w-lg",children:[e.jsx(Vs,{children:e.jsx($s,{children:d.id?"Edit personal resource":"New personal resource"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Title"}),e.jsx(be,{value:d.title,onChange:_=>u({...d,title:_.target.value}),placeholder:"Your 90-day content plan"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Description"}),e.jsx(Ls,{rows:2,value:d.description,onChange:_=>u({...d,description:_.target.value})})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Category"}),e.jsx(be,{value:d.category,onChange:_=>u({...d,category:_.target.value}),placeholder:"Personal"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Type"}),e.jsxs(bs,{value:d.resource_kind,onValueChange:_=>u({...d,resource_kind:_}),children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsx(vs,{children:LMt.map(_=>e.jsx(We,{value:_.value,children:_.label},_.value))})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"File"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs($,{type:"button",variant:"outline",size:"sm",disabled:h,onClick:()=>{var _;return(_=p.current)==null?void 0:_.click()},children:[h?e.jsx(Jt,{className:"mr-1.5 h-4 w-4 animate-spin"}):e.jsx(gi,{className:"mr-1.5 h-4 w-4"}),d.file_path?"Replace file":"Upload file"]}),d.file_path&&e.jsx("span",{className:"truncate text-xs text-muted-foreground",children:d.file_path.split("/").pop()})]}),e.jsx("input",{ref:p,type:"file",hidden:!0,onChange:_=>{var j;return y((j=_.target.files)==null?void 0:j[0])}})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"…or link"}),e.jsx(be,{value:d.url,onChange:_=>u({...d,url:_.target.value,file_path:""}),placeholder:"https://…"})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Status"}),e.jsxs(bs,{value:d.status,onValueChange:_=>u({...d,status:_}),children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"published",children:"Published"}),e.jsx(We,{value:"draft",children:"Draft"}),e.jsx(We,{value:"archived",children:"Archived"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Sort order"}),e.jsx(be,{type:"number",value:d.sort_order,onChange:_=>u({...d,sort_order:_.target.value})})]})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"ghost",onClick:()=>c(!1),children:"Cancel"}),e.jsxs($,{onClick:v,disabled:i.isPending||h,children:[i.isPending&&e.jsx(Jt,{className:"mr-1.5 h-4 w-4 animate-spin"})," Save"]})]})]})})]})},rFs=({program:s,enrollment:t,open:n,onOpenChange:r,onUpdated:a})=>{var Y,se,ee,oe,me,Q,te,le,fe,_e;const i=t==null?void 0:t.user_id,[l,o]=k.useState((t==null?void 0:t.admin_notes)||""),[c,d]=k.useState(!1),[u,h]=k.useState(""),[m,p]=k.useState(!1),[g,x]=k.useState(!1),y=k.useRef(null),{data:v,isLoading:_,refetch:j}=pt({queryKey:["admin-program-agent",s.id,i],enabled:n&&!!i,queryFn:async()=>{const[ve,he,Se,Te,Ie,Ue,Be,je]=await Promise.all([V.from("program_weekly_progress").select("*").eq("program_id",s.id).eq("user_id",i).order("week_number"),V.from("program_video_logs").select("*").eq("program_id",s.id).eq("user_id",i).order("posted_at",{ascending:!1}),V.from("program_lesson_completions").select("*").eq("program_id",s.id).eq("user_id",i),V.from("program_badge_awards").select("*").eq("program_id",s.id).eq("user_id",i),V.from("program_intake_responses").select("*").eq("program_id",s.id).eq("user_id",i).maybeSingle(),V.from("program_event_attendance").select("*").eq("program_id",s.id).eq("user_id",i),V.from("program_lessons").select("id").eq("program_id",s.id),V.from("program_profile_analyses").select("*").eq("program_id",s.id).eq("user_id",i).maybeSingle()]);return{weekly:ve.data||[],videos:he.data||[],completions:Se.data||[],badges:Te.data||[],intake:Ie.data,attendance:Ue.data||[],lessonCount:(Be.data||[]).length,analysis:je.data}}});k.useEffect(()=>{var ve;h(((ve=v==null?void 0:v.analysis)==null?void 0:ve.member_notes)||"")},[(Y=v==null?void 0:v.analysis)==null?void 0:Y.id]);const C=k.useMemo(()=>{var Se;const ve=sX(s),he=((Se=v==null?void 0:v.intake)==null?void 0:Se.extra)||{};return ve.custom.map(Te=>({label:Te.label,value:typeof he[Te.id]=="boolean"?he[Te.id]?"Yes":"No":he[Te.id]||""})).filter(Te=>!!Te.value)},[s,v==null?void 0:v.intake]),A=async ve=>i?V.from("program_profile_analyses").upsert({program_id:s.id,user_id:i,enrollment_id:(t==null?void 0:t.id)||null,...ve},{onConflict:"program_id,user_id"}):{error:{message:"Missing agent"}},M=async ve=>{if(ve.type!=="application/pdf")return ae.error("Please choose a PDF file");if(ve.size>25*1024*1024)return ae.error("PDF must be under 25MB");x(!0);try{const he=`programs/${s.id}/reviews/${i}-${Date.now()}.pdf`,{error:Se}=await V.storage.from("event-images").upload(he,ve,{contentType:"application/pdf",upsert:!0});if(Se)throw Se;const{data:Te}=V.storage.from("event-images").getPublicUrl(he),{error:Ie}=await A({report_url:Te.publicUrl,status:"ready",reviewed_at:new Date().toISOString()});if(Ie)throw Ie;ae.success("Profile review uploaded"),await j()}catch(he){ae.error(he.message||"Upload failed")}finally{x(!1)}},I=async()=>{const{error:ve}=await A({report_url:null,status:"in_review"});if(ve)return ae.error(ve.message);ae.success("Review removed"),await j()},P=async()=>{p(!0);const{error:ve}=await A({member_notes:u});if(p(!1),ve)return ae.error(ve.message);ae.success("Review notes saved"),await j()},R=async()=>{if(!t)return;d(!0);const{error:ve}=await V.from("program_enrollments").update({admin_notes:l}).eq("id",t.id);if(d(!1),ve)return ae.error(ve.message);ae.success("Notes saved"),a()},O=((v==null?void 0:v.videos)||[]).filter(ve=>ve.posted).length,B=(s.weekly_video_goal||0)*(s.duration_weeks||0),U=v!=null&&v.lessonCount?Math.round(((v==null?void 0:v.completions.length)||0)/v.lessonCount*100):0,G=B?Math.min(100,Math.round(O/B*100)):0,H=((v==null?void 0:v.attendance)||[]).filter(ve=>ve.attended).length;return e.jsx(D_,{open:n,onOpenChange:r,children:e.jsxs(Mb,{className:"w-full overflow-y-auto sm:max-w-2xl",children:[e.jsxs(xj,{className:"mb-4",children:[e.jsxs(yj,{children:[((se=t==null?void 0:t.profile)==null?void 0:se.name)||"Agent"," · ",s.name]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:(ee=t==null?void 0:t.profile)==null?void 0:ee.email}),i&&e.jsx($,{variant:"outline",size:"sm",className:"mt-3 w-fit",asChild:!0,children:e.jsxs("a",{href:`/programs/${s.slug}/workspace?preview=1&as=${i}&name=${encodeURIComponent(((oe=t==null?void 0:t.profile)==null?void 0:oe.name)||((me=t==null?void 0:t.profile)==null?void 0:me.email)||"this member")}`,target:"_blank",rel:"noreferrer",children:[e.jsx(Ir,{className:"mr-2 h-4 w-4"}),"Open their dashboard"]})})]}),t?_?e.jsx(fn,{className:"h-64 w-full rounded-xl"}):e.jsxs("div",{className:"space-y-4 pb-8",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsx(we,{children:e.jsxs(De,{className:"p-4",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Status"}),e.jsx(qe,{className:"mt-1 capitalize",children:String(t.status).replace(/_/g," ")}),e.jsxs("p",{className:"mt-2 text-xs text-muted-foreground",children:[Tp(t.amount_cents,t.currency)," ·"," ",t.charged_at?`Charged ${ru(t.charged_at)}`:`Charge ${ru(t.charge_scheduled_at)||"not set"}`]})]})}),e.jsx(we,{children:e.jsxs(De,{className:"p-4",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Last activity"}),e.jsx("p",{className:"mt-1 text-sm font-medium",children:ru(t.last_activity_at,!0)||"No activity yet"}),e.jsxs("p",{className:"mt-2 text-xs text-muted-foreground",children:["Enrolled ",ru(t.created_at)]})]})})]}),e.jsx(we,{children:e.jsxs(De,{className:"space-y-4 p-5",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"mb-1 flex items-center justify-between text-sm",children:[e.jsx("span",{className:"font-medium",children:"Videos posted"}),e.jsxs("span",{className:"text-muted-foreground",children:[O," / ",B||"—"]})]}),e.jsx(ho,{value:G})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"mb-1 flex items-center justify-between text-sm",children:[e.jsx("span",{className:"font-medium",children:"Curriculum completed"}),e.jsxs("span",{className:"text-muted-foreground",children:[(v==null?void 0:v.completions.length)||0," / ",(v==null?void 0:v.lessonCount)||0]})]}),e.jsx(ho,{value:U})]}),e.jsxs("div",{className:"flex flex-wrap gap-4 border-t border-border/60 pt-4 text-sm",children:[e.jsxs("span",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Live sessions attended: "}),H]}),e.jsxs("span",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Badges: "}),(v==null?void 0:v.badges.length)||0]}),e.jsxs("span",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Weeks reported: "}),(v==null?void 0:v.weekly.length)||0]})]})]})}),e.jsx(we,{children:e.jsxs(De,{className:"p-5",children:[e.jsx("p",{className:"mb-3 text-sm font-semibold",children:"Weekly progress"}),((v==null?void 0:v.weekly.length)||0)===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No weekly check-ins yet."}):e.jsx("div",{className:"space-y-3",children:v.weekly.map(ve=>e.jsxs("div",{className:"rounded-lg border border-border/60 p-3 text-sm",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"font-medium",children:["Week ",ve.week_number]}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[ve.videos_posted,"/",ve.goal_videos||s.weekly_video_goal," posted ·"," ",ve.stories_posted," stories"]})]}),ve.biggest_win&&e.jsxs("p",{className:"mt-1 text-muted-foreground",children:["Win: ",ve.biggest_win]}),ve.biggest_challenge&&e.jsxs("p",{className:"text-muted-foreground",children:["Challenge: ",ve.biggest_challenge]})]},ve.id))})]})}),e.jsx(we,{children:e.jsxs(De,{className:"p-5",children:[e.jsx("p",{className:"mb-3 text-sm font-semibold",children:"Video log"}),((v==null?void 0:v.videos.length)||0)===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No videos logged yet."}):e.jsx("div",{className:"space-y-2",children:v.videos.slice(0,25).map(ve=>e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(ia,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),e.jsx("span",{className:"truncate",children:ve.title||"Untitled video"}),e.jsxs("span",{className:"ml-auto shrink-0 text-xs text-muted-foreground",children:["Wk ",ve.week_number," · ",ru(ve.posted_at)]}),ve.instagram_url&&e.jsx("a",{href:ve.instagram_url,target:"_blank",rel:"noreferrer",className:"shrink-0 text-muted-foreground hover:text-foreground","aria-label":"Open post",children:e.jsx(Ir,{className:"h-3.5 w-3.5"})})]},ve.id))})]})}),(v==null?void 0:v.intake)&&e.jsx(we,{children:e.jsxs(De,{className:"space-y-1 p-5 text-sm",children:[e.jsx("p",{className:"mb-2 text-sm font-semibold",children:"Intake answers"}),[["Full name",v.intake.full_name],["Email",v.intake.email],["Phone",v.intake.phone],["Instagram",v.intake.instagram_handle],["City / market",v.intake.city],["Areas served",v.intake.service_areas],["Years in real estate",v.intake.years_experience],["Specialty",v.intake.specialty],["Target audience",v.intake.target_audience],["On camera",v.intake.video_comfort],["Posts today",v.intake.posting_frequency],["Content style",v.intake.content_style],["Interests",v.intake.personal_interests],["#1 goal",v.intake.primary_goal],["Topics to avoid",v.intake.topics_to_avoid],["Time zone",v.intake.timezone]].filter(([,ve])=>!!ve).map(([ve,he])=>e.jsxs("p",{children:[e.jsxs("span",{className:"text-muted-foreground",children:[ve,": "]}),he]},ve)),C.map(({label:ve,value:he})=>e.jsxs("p",{children:[e.jsxs("span",{className:"text-muted-foreground",children:[ve,": "]}),he]},ve)),e.jsxs("p",{className:"pt-1 text-xs text-muted-foreground",children:["Content-sharing consent: ",v.intake.consent_public_profile?"Yes":"No"]})]})}),e.jsx(we,{children:e.jsx(De,{className:"p-5",children:e.jsx(nFs,{programId:s.id,userId:i,memberName:(Q=t==null?void 0:t.profile)==null?void 0:Q.name})})}),e.jsx(we,{children:e.jsxs(De,{className:"space-y-3 p-5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-semibold",children:"Profile review PDF"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Upload this agent's personalized profile review. They see it in their workspace."})]}),((te=v==null?void 0:v.analysis)==null?void 0:te.status)&&e.jsx(qe,{variant:"secondary",className:"capitalize",children:String(v.analysis.status).replace(/_/g," ")})]}),(le=v==null?void 0:v.analysis)!=null&&le.report_url?e.jsxs("div",{className:"flex flex-wrap items-center gap-2 rounded-lg border border-border/60 p-3 text-sm",children:[e.jsx(ea,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"truncate",children:"Review uploaded"}),e.jsxs("a",{href:v.analysis.report_url,target:"_blank",rel:"noreferrer",className:"ml-auto inline-flex items-center gap-1 text-primary hover:underline",children:["View ",e.jsx(Ir,{className:"h-3.5 w-3.5"})]})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"No review uploaded yet."}),e.jsx("input",{ref:y,type:"file",accept:"application/pdf",className:"hidden",onChange:ve=>{var Se;const he=(Se=ve.target.files)==null?void 0:Se[0];he&&M(he),ve.target.value=""}}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs($,{size:"sm",variant:"outline",onClick:()=>{var ve;return(ve=y.current)==null?void 0:ve.click()},disabled:g,children:[e.jsx(gi,{className:"mr-1.5 h-3.5 w-3.5"}),g?"Uploading…":(fe=v==null?void 0:v.analysis)!=null&&fe.report_url?"Replace PDF":"Upload PDF"]}),((_e=v==null?void 0:v.analysis)==null?void 0:_e.report_url)&&e.jsx($,{size:"sm",variant:"ghost",onClick:I,children:"Remove"})]}),e.jsxs("div",{className:"space-y-2 pt-1",children:[e.jsx(re,{children:"Review summary shown to the agent (optional)"}),e.jsx(Ls,{rows:3,value:u,onChange:ve=>h(ve.target.value),placeholder:"Top 3 priorities, quick wins, what to fix first…"}),e.jsx("div",{className:"flex justify-end",children:e.jsx($,{size:"sm",variant:"outline",onClick:P,disabled:m,children:"Save review notes"})})]})]})}),e.jsx(we,{children:e.jsxs(De,{className:"space-y-3 p-5",children:[e.jsx(re,{children:"Coach notes (internal)"}),e.jsx(Ls,{rows:4,value:l,onChange:ve=>o(ve.target.value)}),e.jsx("div",{className:"flex justify-end",children:e.jsx($,{size:"sm",onClick:R,disabled:c,children:"Save notes"})})]})})]}):null]})})},zut={code:"",label:"",kind:"percent",percent_off:"20",amount_off:"",max_redemptions:"",starts_at:"",expires_at:"",is_active:!0},But=s=>{if(!s)return"";const t=new Date(s),n=t.getTimezoneOffset();return new Date(t.getTime()-n*6e4).toISOString().slice(0,16)},aFs=({program:s})=>{const{data:t=[],isLoading:n}=bAs(s.id),r=_As(s.id),a=wAs(),[i,l]=k.useState(!1),[o,c]=k.useState({...zut}),d=()=>{c({...zut}),l(!0)},u=g=>{c({id:g.id,code:g.code,label:g.label||"",kind:g.percent_off!=null?"percent":"amount",percent_off:g.percent_off!=null?String(g.percent_off):"",amount_off:g.amount_off_cents!=null?String(g.amount_off_cents/100):"",max_redemptions:g.max_redemptions!=null?String(g.max_redemptions):"",starts_at:But(g.starts_at),expires_at:But(g.expires_at),is_active:g.is_active}),l(!0)},h=k.useMemo(()=>{const g=o.kind==="percent"?Math.floor(s.price_cents*Number(o.percent_off||0)/100):Math.round(Number(o.amount_off||0)*100),x=Math.min(Math.max(g,0),s.price_cents);return{discount:x,final:s.price_cents-x}},[o,s.price_cents]),m=async()=>{if(!o.code.trim())return ae.error("Give the code a name, e.g. FOUNDER50");await r.mutateAsync({id:o.id,code:o.code,label:o.label||null,percent_off:o.kind==="percent"?Number(o.percent_off)||0:null,amount_off_cents:o.kind==="amount"?Math.round(Number(o.amount_off||0)*100):null,max_redemptions:o.max_redemptions?Number(o.max_redemptions):null,starts_at:o.starts_at?new Date(o.starts_at).toISOString():null,expires_at:o.expires_at?new Date(o.expires_at).toISOString():null,is_active:o.is_active}),l(!1)},p=g=>{const x=g.percent_off!=null?Math.floor(s.price_cents*Number(g.percent_off)/100):g.amount_off_cents||0,y=Math.max(s.price_cents-Math.min(x,s.price_cents),0);return{off:g.percent_off!=null?`${Number(g.percent_off)}% off`:`${Tp(g.amount_off_cents||0,s.currency)} off`,final:Tp(y,s.currency)}};return e.jsxs("div",{className:"space-y-4",children:[e.jsx(we,{children:e.jsxs(De,{className:"flex flex-wrap items-center justify-between gap-4 p-5",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Discount codes"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Enrollees can enter a code on the final enrollment step. The discount is applied to the one-time ",Tp(s.price_cents,s.currency)," charge."]})]}),e.jsxs(zs,{open:i,onOpenChange:l,children:[e.jsx(yl,{asChild:!0,children:e.jsxs($,{onClick:d,children:[e.jsx(nn,{className:"mr-1.5 h-4 w-4"})," New code"]})}),e.jsxs(Rs,{className:"max-h-[85vh] overflow-y-auto",children:[e.jsx(Vs,{children:e.jsx($s,{children:o.id?"Edit discount code":"Create a discount code"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Code"}),e.jsx(be,{placeholder:"FOUNDER50",value:o.code,onChange:g=>c({...o,code:g.target.value.toUpperCase()})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Internal label (optional)"}),e.jsx(be,{placeholder:"Founding cohort",value:o.label,onChange:g=>c({...o,label:g.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Discount type"}),e.jsxs(bs,{value:o.kind,onValueChange:g=>c({...o,kind:g}),children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"percent",children:"Percent off"}),e.jsx(We,{value:"amount",children:"Dollar amount off"})]})]})]}),o.kind==="percent"?e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Percent off"}),e.jsx(be,{type:"number",min:1,max:100,value:o.percent_off,onChange:g=>c({...o,percent_off:g.target.value})})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Amount off (USD)"}),e.jsx(be,{type:"number",min:0,value:o.amount_off,onChange:g=>c({...o,amount_off:g.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Max redemptions (blank = unlimited)"}),e.jsx(be,{type:"number",min:1,value:o.max_redemptions,onChange:g=>c({...o,max_redemptions:g.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Active from (optional)"}),e.jsx(be,{type:"datetime-local",value:o.starts_at,onChange:g=>c({...o,starts_at:g.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Expires (optional)"}),e.jsx(be,{type:"datetime-local",value:o.expires_at,onChange:g=>c({...o,expires_at:g.target.value})})]})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border border-border/60 p-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Code is active"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Turn off to stop new redemptions instantly."})]}),e.jsx(On,{checked:o.is_active,onCheckedChange:g=>c({...o,is_active:g})})]}),e.jsxs("div",{className:"rounded-lg border border-primary/30 bg-primary/5 p-4 text-sm",children:[e.jsx("p",{className:"font-medium",children:"Enrollee sees"}),e.jsxs("p",{className:"mt-1 text-muted-foreground",children:[Tp(s.price_cents,s.currency)," →"," ",e.jsx("span",{className:"font-semibold text-foreground",children:Tp(h.final,s.currency)})," ","(",Tp(h.discount,s.currency)," off) — charged one time."]})]})]}),e.jsx(kr,{children:e.jsxs($,{onClick:m,disabled:r.isPending,children:[r.isPending&&e.jsx(Jt,{className:"mr-1.5 h-4 w-4 animate-spin"}),o.id?"Save changes":"Create code"]})})]})]})]})}),n?e.jsx(fn,{className:"h-40 w-full rounded-xl"}):t.length===0?e.jsx(we,{className:"border-dashed",children:e.jsxs(De,{className:"flex flex-col items-center gap-3 p-12 text-center",children:[e.jsx(kg,{className:"h-8 w-8 text-muted-foreground"}),e.jsx("p",{className:"font-medium",children:"No discount codes yet"}),e.jsx("p",{className:"max-w-md text-sm text-muted-foreground",children:"Create a code for early birds, brokerage partners or a founding cohort. Codes are entered by the enrollee at checkout and change the one-time price."})]})}):e.jsx(we,{children:e.jsx(De,{className:"overflow-x-auto p-0",children:e.jsxs(Qa,{children:[e.jsx(Ja,{children:e.jsxs(vn,{children:[e.jsx(Dt,{children:"Code"}),e.jsx(Dt,{children:"Discount"}),e.jsx(Dt,{children:"Price after"}),e.jsx(Dt,{children:"Used"}),e.jsx(Dt,{children:"Window"}),e.jsx(Dt,{children:"Status"}),e.jsx(Dt,{className:"text-right",children:"Actions"})]})}),e.jsx(ei,{children:t.map(g=>{const x=p(g);return e.jsxs(vn,{children:[e.jsxs(_t,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-mono font-semibold",children:g.code}),e.jsx($,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>{navigator.clipboard.writeText(g.code),ae.success("Code copied")},children:e.jsx(Da,{className:"h-3.5 w-3.5"})})]}),g.label&&e.jsx("p",{className:"text-xs text-muted-foreground",children:g.label})]}),e.jsx(_t,{className:"whitespace-nowrap",children:e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx(ZT,{className:"h-3.5 w-3.5 text-muted-foreground"}),x.off]})}),e.jsx(_t,{className:"font-medium",children:x.final}),e.jsxs(_t,{children:[g.times_redeemed,g.max_redemptions?` / ${g.max_redemptions}`:""]}),e.jsxs(_t,{className:"text-xs text-muted-foreground",children:[g.starts_at?`From ${ru(g.starts_at)}`:"Anytime",g.expires_at?` · until ${ru(g.expires_at)}`:""]}),e.jsx(_t,{children:e.jsx(qe,{variant:g.is_active?"default":"secondary",children:g.is_active?"Active":"Paused"})}),e.jsx(_t,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-1",children:[e.jsx($,{variant:"outline",size:"sm",onClick:()=>u(g),children:"Edit"}),e.jsx($,{variant:"ghost",size:"icon",onClick:async()=>{await io(`Delete ${g.code}?`)&&a.mutate(g.id)},children:e.jsx(Un,{className:"h-4 w-4 text-destructive"})})]})})]},g.id)})})]})})})]})},dS=({ok:s,label:t,detail:n})=>e.jsxs("div",{className:"flex items-start gap-3 border-b border-border/50 py-3 last:border-0",children:[s?e.jsx(Gr,{className:"mt-0.5 h-4 w-4 shrink-0 text-primary"}):e.jsx(Gd,{className:"mt-0.5 h-4 w-4 shrink-0 text-amber-500"}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium",children:t}),n&&e.jsx("p",{className:"text-xs text-muted-foreground",children:n})]})]}),iFs=({program:s})=>{var c,d;const{data:t,isLoading:n}=pt({queryKey:["admin-program-content-counts",s.id],queryFn:async()=>{const[u,h,m,p,g]=await Promise.all([V.from("program_weeks").select("id, week_number, title").eq("program_id",s.id),V.from("program_lessons").select("id, title").eq("program_id",s.id),V.from("program_resources").select("id, title").eq("program_id",s.id),V.from("program_events").select("id, title, starts_at").eq("program_id",s.id),V.from("program_announcements").select("id, title").eq("program_id",s.id)]);return{weeks:u.data||[],lessons:h.data||[],resources:m.data||[],events:p.data||[],announcements:g.data||[]}}}),{notOpenYet:r,closed:a,opensLabel:i}=fAe(s),l=`/programs/${s.slug}`,o=[{icon:kn,title:"1 · Sales page",body:`${s.name} — hero image, ${s.subtitle?"subtitle":"no subtitle"}, description, price, dates, seats left and FAQ.`,href:l,cta:"Preview sales page"},{icon:cB,title:"2 · Enrollment intake",body:"4 steps: business profile, content style, goals, then the seat + payment summary with the discount-code field.",href:`${l}/enroll`,cta:"Preview enrollment flow"},{icon:cv,title:"3 · Checkout",body:s.payment_mode==="free"?"Free program — seat is confirmed instantly, no card collected.":s.payment_mode==="delayed"?`Stripe collects and saves the card today. The single ${Tp(s.price_cents,s.currency)} charge runs on ${ru(s.charge_at||s.kickoff_at)||"the charge date (not set)"}.`:`Stripe charges ${Tp(s.price_cents,s.currency)} once at checkout.`},{icon:pn,title:"4 · Emails",body:"Confirmation right after enrollment, then payment receipt (or a payment-failed action email) when the one-time charge runs."},{icon:nB,title:"5 · Program workspace",body:`Their home base: progress dashboard, ${s.duration_weeks}-week roadmap, lessons, resources, events, weekly check-ins and video logging (${s.weekly_video_goal}/week goal).`,href:`${l}/workspace?preview=1`,cta:"Preview workspace as an enrollee"}];return e.jsxs("div",{className:"space-y-6",children:[e.jsx(we,{children:e.jsxs(De,{className:"flex flex-wrap items-center justify-between gap-4 p-5",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"What enrollees see"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Walk the exact member journey end to end. Workspace preview opens in read-only admin mode — it does not create an enrollment."})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx($,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:l,target:"_blank",rel:"noreferrer",children:["Sales page ",e.jsx(Ir,{className:"ml-1.5 h-3.5 w-3.5"})]})}),e.jsx($,{asChild:!0,children:e.jsxs("a",{href:`${l}/workspace?preview=1`,target:"_blank",rel:"noreferrer",children:["Workspace preview ",e.jsx(Ir,{className:"ml-1.5 h-3.5 w-3.5"})]})})]})]})}),(s.status!=="published"||r||a)&&e.jsx(we,{className:"border-amber-500/40 bg-amber-500/5",children:e.jsxs(De,{className:"flex items-start gap-3 p-5 text-sm",children:[e.jsx(Gd,{className:"mt-0.5 h-4 w-4 shrink-0 text-amber-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Members can't enroll right now"}),e.jsx("p",{className:"text-muted-foreground",children:s.status!=="published"?`This program is ${s.status} — it isn't listed on the member Programs page yet.`:r?`Enrollment opens ${i}. CTAs are disabled until then.`:"Enrollment has closed for this cohort."})]})]})}),e.jsxs("div",{className:"grid gap-4 lg:grid-cols-2",children:[e.jsx(we,{children:e.jsxs(De,{className:"space-y-3 p-5",children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:"The enrollee journey"}),e.jsx("div",{className:"space-y-4",children:o.map(u=>e.jsxs("div",{className:"flex gap-3",children:[e.jsx("div",{className:"mt-0.5 flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-primary/10",children:e.jsx(u.icon,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{className:"min-w-0 space-y-1",children:[e.jsx("p",{className:"text-sm font-medium",children:u.title}),e.jsx("p",{className:"text-sm text-muted-foreground",children:u.body}),u.href&&e.jsx($,{variant:"link",size:"sm",className:"h-auto p-0",asChild:!0,children:e.jsxs("a",{href:u.href,target:"_blank",rel:"noreferrer",children:[u.cta," ",e.jsx(Ir,{className:"ml-1 h-3 w-3"})]})})]})]},u.title))})]})}),e.jsx(we,{children:e.jsxs(De,{className:"p-5",children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:"Premium-experience checklist"}),n?e.jsx(fn,{className:"mt-4 h-64 w-full rounded-lg"}):e.jsxs("div",{className:"mt-2",children:[e.jsx(dS,{ok:!!s.cover_image_url,label:"Cover image",detail:s.cover_image_url?"Set":"Missing — cards look empty on the Programs page"}),e.jsx(dS,{ok:!!s.hero_image_url,label:"Hero image on the sales page",detail:s.hero_image_url?"Set":"Missing — sales page falls back to a gradient"}),e.jsx(dS,{ok:!!s.short_description&&!!s.description,label:"Short + full description",detail:s.short_description&&s.description?"Both written":"Fill both in Details & pricing so the sales page reads well"}),e.jsx(dS,{ok:s.payment_mode==="free"||s.price_cents>0,label:"One-time price",detail:s.payment_mode==="free"?"Free / included":Tp(s.price_cents,s.currency)}),e.jsx(dS,{ok:!!s.kickoff_at&&(s.payment_mode==="free"||!!s.charge_at),label:"Kickoff and charge dates",detail:`Kickoff ${ru(s.kickoff_at)||"not set"} · charge ${ru(s.charge_at)||"not set"}`}),e.jsx(dS,{ok:((t==null?void 0:t.weeks.length)||0)>0,label:"Weekly roadmap",detail:`${(t==null?void 0:t.weeks.length)||0} of ${s.duration_weeks} weeks built`}),e.jsx(dS,{ok:((t==null?void 0:t.lessons.length)||0)>0,label:"Lessons",detail:`${(t==null?void 0:t.lessons.length)||0} lessons — the workspace Curriculum tab is empty without these`}),e.jsx(dS,{ok:((t==null?void 0:t.resources.length)||0)>0,label:"Resources / downloads",detail:`${(t==null?void 0:t.resources.length)||0} resources`}),e.jsx(dS,{ok:((t==null?void 0:t.events.length)||0)>0,label:"Live calls on the calendar",detail:`${(t==null?void 0:t.events.length)||0} events${(d=(c=t==null?void 0:t.events)==null?void 0:c[0])!=null&&d.starts_at?` · next ${ru(t.events[0].starts_at)}`:""}`}),e.jsx(dS,{ok:((t==null?void 0:t.announcements.length)||0)>0,label:"Welcome announcement",detail:`${(t==null?void 0:t.announcements.length)||0} announcements — a day-one welcome post makes the workspace feel alive`})]})]})})]}),t&&e.jsx(we,{children:e.jsx(De,{className:"grid gap-4 p-5 sm:grid-cols-2 lg:grid-cols-5",children:[{icon:fd,label:"Weeks",value:t.weeks.length},{icon:ea,label:"Lessons",value:t.lessons.length},{icon:ea,label:"Resources",value:t.resources.length},{icon:fd,label:"Events",value:t.events.length},{icon:xm,label:"Announcements",value:t.announcements.length}].map((u,h)=>e.jsxs("div",{className:"rounded-lg border border-border/60 p-4",children:[e.jsx(u.icon,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("p",{className:"mt-2 text-2xl font-bold",children:u.value}),e.jsx("p",{className:"text-xs text-muted-foreground",children:u.label})]},h))})}),e.jsx(qe,{variant:"outline",className:"text-xs",children:"Tip: preview in an incognito window as a test member to see the real enrollment flow end to end."})]})},oFs=["Step 1 · Your business","Step 2 · Your content","Step 3 · Your goals"],lFs={short_text:"Short answer",long_text:"Paragraph",select:"Dropdown",checkbox:"Yes / no checkbox"},cFs=({program:s,onSaved:t})=>{const[n,r]=k.useState(()=>sX(s)),[a,i]=k.useState(!1),[l,o]=k.useState(!1);k.useEffect(()=>{r(sX(s)),i(!1)},[s.id,s.updated_at]);const c=y=>{r(v=>({...v,...y})),i(!0)},d=(y,v)=>{const _=v?n.hidden.filter(C=>C!==y):[...new Set([...n.hidden,y])],j=v?n.required:n.required.filter(C=>C!==y);c({hidden:_,required:j})},u=(y,v)=>{c({required:v?[...new Set([...n.required,y])]:n.required.filter(_=>_!==y)})},h=()=>{const y={id:`q_${Date.now().toString(36)}`,label:"",type:"short_text",required:!1,options:[]};c({custom:[...n.custom,y]})},m=(y,v)=>c({custom:n.custom.map(_=>_.id===y?{..._,...v}:_)}),p=y=>c({custom:n.custom.filter(v=>v.id!==y)}),g=(y,v)=>{const _=[...n.custom],j=y+v;j<0||j>=_.length||([_[y],_[j]]=[_[j],_[y]],c({custom:_}))},x=async()=>{if(n.custom.find(j=>!j.label.trim()))return ae.error("Every custom question needs a label");o(!0);const v={...s.sales_copy||{},intake:n},{error:_}=await V.from("programs").update({sales_copy:v}).eq("id",s.id);if(o(!1),_)return ae.error(_.message);i(!1),ae.success("Intake form saved"),t==null||t()};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-semibold",children:"Intake form"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Controls the questions each agent answers during enrollment."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx($,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("a",{href:`/programs/${s.slug}/enroll`,target:"_blank",rel:"noreferrer",children:[e.jsx(Ir,{className:"mr-1.5 h-3.5 w-3.5"})," Preview form"]})}),e.jsxs($,{size:"sm",onClick:x,disabled:!a||l,children:[e.jsx(Ml,{className:"mr-1.5 h-3.5 w-3.5"}),l?"Saving…":"Save intake form"]})]})]}),e.jsxs(we,{children:[e.jsx(Vt,{className:"pb-3",children:e.jsx(Yt,{className:"text-sm",children:"Intro message"})}),e.jsx(De,{children:e.jsx(Ls,{rows:3,placeholder:"Shown at the top of the intake — e.g. “Answer a few questions so we can personalize your 90 days.”",value:n.intro||"",onChange:y=>c({intro:y.target.value})})})]}),[0,1,2].map(y=>e.jsxs(we,{children:[e.jsx(Vt,{className:"pb-3",children:e.jsx(Yt,{className:"text-sm",children:oFs[y]})}),e.jsxs(De,{className:"space-y-2",children:[e.jsxs("div",{className:"hidden grid-cols-[1fr,auto,auto] gap-4 pb-1 text-xs uppercase tracking-wide text-muted-foreground sm:grid",children:[e.jsx("span",{children:"Question"}),e.jsx("span",{className:"w-16 text-center",children:"Show"}),e.jsx("span",{className:"w-16 text-center",children:"Required"})]}),uWe.filter(v=>v.step===y).map(v=>{const _=!n.hidden.includes(v.key);return e.jsxs("div",{className:"grid grid-cols-[1fr,auto,auto] items-center gap-4 rounded-lg border border-border/60 px-3 py-2",children:[e.jsx("span",{className:"text-sm",children:v.label}),e.jsx("div",{className:"flex w-16 justify-center",children:e.jsx(On,{checked:_,onCheckedChange:j=>d(v.key,j),"aria-label":`Show ${v.label}`})}),e.jsx("div",{className:"flex w-16 justify-center",children:e.jsx(On,{checked:n.required.includes(v.key),disabled:!_,onCheckedChange:j=>u(v.key,j),"aria-label":`Require ${v.label}`})})]},v.key)})]})]},y)),e.jsxs(we,{children:[e.jsxs(Vt,{className:"flex-row items-center justify-between space-y-0 pb-3",children:[e.jsxs(Yt,{className:"text-sm",children:["Custom questions"," ",e.jsx(qe,{variant:"secondary",className:"ml-1",children:n.custom.length})]}),e.jsxs($,{size:"sm",variant:"outline",onClick:h,children:[e.jsx(nn,{className:"mr-1.5 h-3.5 w-3.5"})," Add question"]})]}),e.jsxs(De,{className:"space-y-3",children:[n.custom.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"No custom questions yet. Add program-specific questions here — answers appear on each agent's dashboard."}),n.custom.map((y,v)=>e.jsxs("div",{className:"space-y-3 rounded-lg border border-border/60 p-4",children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx("div",{className:"flex flex-col pt-1.5",children:e.jsx("button",{type:"button",className:"text-muted-foreground hover:text-foreground",onClick:()=>g(v,-1),"aria-label":"Move up",children:e.jsx(Bp,{className:"h-4 w-4"})})}),e.jsxs("div",{className:"grid flex-1 gap-3 sm:grid-cols-[2fr,1fr]",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{className:"text-xs",children:"Question"}),e.jsx(be,{value:y.label,placeholder:"What is your biggest content roadblock?",onChange:_=>m(y.id,{label:_.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{className:"text-xs",children:"Answer type"}),e.jsxs(bs,{value:y.type,onValueChange:_=>m(y.id,{type:_}),children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsx(vs,{children:Object.entries(lFs).map(([_,j])=>e.jsx(We,{value:_,children:j},_))})]})]})]}),e.jsx($,{size:"icon",variant:"ghost",onClick:()=>p(y.id),"aria-label":"Delete question",children:e.jsx(Un,{className:"h-4 w-4 text-destructive"})})]}),y.type==="select"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{className:"text-xs",children:"Options (one per line)"}),e.jsx(Ls,{rows:3,value:(y.options||[]).join(` `),onChange:_=>m(y.id,{options:_.target.value.split(` `).map(j=>j.trim()).filter(Boolean)})})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-[1fr,auto]",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{className:"text-xs",children:"Helper text (optional)"}),e.jsx(be,{value:y.help||"",onChange:_=>m(y.id,{help:_.target.value})})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-6",children:[e.jsx(On,{checked:!!y.required,onCheckedChange:_=>m(y.id,{required:_}),"aria-label":"Required"}),e.jsx("span",{className:"text-sm",children:"Required"})]})]})]},y.id))]})]})]})},h1=EIt,m1=SIt,f1=AIt,dFs=[zx,ea,_h],uFs=["Business profile","Content style","Goals & consent"],hFs=({fieldKey:s})=>s.includes("phone")?e.jsx(ka,{className:"h-3.5 w-3.5"}):s.includes("email")?e.jsx(pn,{className:"h-3.5 w-3.5"}):s.includes("instagram")?e.jsx(Sf,{className:"h-3.5 w-3.5"}):s.includes("city")||s.includes("area")?e.jsx(Si,{className:"h-3.5 w-3.5"}):s.includes("timezone")?e.jsx(sa,{className:"h-3.5 w-3.5"}):s.includes("consent")?s.includes("true")?e.jsx(Gr,{className:"h-3.5 w-3.5"}):e.jsx(ju,{className:"h-3.5 w-3.5"}):e.jsx(el,{className:"h-3.5 w-3.5"}),$ut=(s,t)=>s==null||s===""?"—":typeof s=="boolean"?s?e.jsxs("span",{className:"inline-flex items-center gap-1 text-emerald-600",children:[e.jsx(Gr,{className:"h-3.5 w-3.5"})," Yes"]}):e.jsxs("span",{className:"inline-flex items-center gap-1 text-muted-foreground",children:[e.jsx(ju,{className:"h-3.5 w-3.5"})," No"]}):String(s),mFs=({program:s})=>{const[t,n]=k.useState(""),[r,a]=k.useState(new Set),{data:i=[],isLoading:l}=pt({queryKey:["admin-program-intakes",s.id],queryFn:async()=>{const{data:h,error:m}=await V.from("program_intake_responses").select("*").eq("program_id",s.id).order("created_at",{ascending:!1});if(m)throw m;return h||[]}}),o=sX(s),c=uWe.filter(h=>!o.hidden.includes(h.key)),d=i.filter(h=>{const m=t.toLowerCase();return m?String(h.full_name||"").toLowerCase().includes(m)||String(h.email||"").toLowerCase().includes(m)||String(h.city||"").toLowerCase().includes(m)||Object.values(h).some(p=>String(p).toLowerCase().includes(m)):!0}),u=h=>{const m=new Set(r);m.has(h)?m.delete(h):m.add(h),a(m)};return l?e.jsx(fn,{className:"h-96 w-full rounded-xl"}):i.length===0?e.jsx(we,{className:"border-dashed",children:e.jsxs(De,{className:"p-12 text-center text-sm text-muted-foreground",children:[e.jsx(ea,{className:"mx-auto mb-3 h-6 w-6"}),e.jsx("p",{children:"No intake responses yet."}),e.jsx("p",{className:"mt-1 text-xs",children:"Responses appear here once members complete the enrollment intake form."})]})}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-semibold",children:"Intake responses"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[d.length," of ",i.length," response",i.length===1?"":"s"," · every field from the enrollment intake form"]})]}),e.jsxs("div",{className:"relative w-full sm:w-64",children:[e.jsx(Yr,{className:"absolute left-2.5 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(be,{placeholder:"Search responses…",value:t,onChange:h=>n(h.target.value),className:"pl-9"})]})]}),d.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"No responses match your search."}),e.jsx("div",{className:"space-y-3",children:d.map(h=>{const m=r.has(h.id),p=ru(h.created_at,!0);return e.jsx(we,{className:"overflow-hidden",children:e.jsxs(h1,{open:m,onOpenChange:()=>u(h.id),children:[e.jsx(m1,{asChild:!0,children:e.jsxs(Vt,{className:"flex cursor-pointer flex-row items-center justify-between gap-3 bg-muted/30 px-5 py-3 hover:bg-muted/50",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"flex h-9 w-9 items-center justify-center rounded-full bg-primary/10",children:e.jsx(el,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{children:[e.jsxs(Yt,{className:"text-sm font-semibold",children:[h.full_name||"Unnamed member",h.city&&e.jsxs("span",{className:"ml-2 font-normal text-muted-foreground",children:["· ",h.city]})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[h.email,h.email&&h.phone&&" · ",h.phone]})]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"hidden text-right sm:block",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Submitted"}),e.jsx("p",{className:"text-xs font-medium",children:p})]}),e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8 shrink-0",children:e.jsx(Go,{className:`h-4 w-4 transition-transform ${m?"rotate-180":""}`})})]})]})}),e.jsx(f1,{children:e.jsxs(De,{className:"space-y-5 p-5",children:[[0,1,2].map(g=>{const x=c.filter(v=>v.step===g),y=dFs[g];return x.length===0?null:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2 border-b border-border/40 pb-2",children:[e.jsx("div",{className:"flex h-6 w-6 items-center justify-center rounded-md bg-primary/10",children:e.jsx(y,{className:"h-3.5 w-3.5 text-primary"})}),e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:uFs[g]})]}),e.jsx("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-3",children:x.map(v=>{const _=h[v.key];return _==null||_===""?null:e.jsxs("div",{className:"rounded-lg border border-border/50 p-3",children:[e.jsxs("div",{className:"mb-1 flex items-center gap-1.5 text-xs text-muted-foreground",children:[e.jsx(hFs,{fieldKey:v.key}),v.label]}),e.jsx("p",{className:"text-sm font-medium",children:$ut(_,v.key)})]},v.key)})})]},g)}),o.custom&&o.custom.length>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2 border-b border-border/40 pb-2",children:[e.jsx("div",{className:"flex h-6 w-6 items-center justify-center rounded-md bg-primary/10",children:e.jsx(ea,{className:"h-3.5 w-3.5 text-primary"})}),e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Custom questions"})]}),e.jsx("div",{className:"grid gap-3 sm:grid-cols-2",children:o.custom.map(g=>{var y;const x=(y=h.extra)==null?void 0:y[g.id];return x==null||x===""?null:e.jsxs("div",{className:"rounded-lg border border-border/50 p-3",children:[e.jsx("p",{className:"mb-1 text-xs text-muted-foreground",children:g.label}),e.jsx("p",{className:"text-sm font-medium",children:$ut(x,g.id)})]},g.id)})})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 pt-2 text-xs text-muted-foreground",children:[e.jsx(ha,{className:"h-3.5 w-3.5"}),"Submitted ",p,h.timezone&&e.jsxs("span",{className:"ml-2",children:["· Timezone: ",h.timezone]})]})]})})]})},h.id)})})]})},fFs=[{value:"kickoff",label:"Kickoff call"},{value:"mastermind",label:"Mastermind"},{value:"workshop",label:"Workshop / training"},{value:"office_hours",label:"Office hours / Q&A"},{value:"other",label:"Other"}],pFs=s=>{if(!s)return"";const t=new Date(s),n=t.getTimezoneOffset();return new Date(t.getTime()-n*6e4).toISOString().slice(0,16)},Uut={title:"",description:"",event_kind:"mastermind",starts_at:"",duration_minutes:60,speaker:"",meeting_link:"",replay_url:"",is_published:!0},gFs=({programId:s})=>{const{data:t=[],isLoading:n}=kAs(s),r=SAs(s),a=CAs(),[i,l]=k.useState(!1),[o,c]=k.useState({...Uut}),d=()=>{c({...Uut}),l(!0)},u=y=>{c({id:y.id,title:y.title,description:y.description||"",event_kind:y.event_kind,starts_at:pFs(y.starts_at),duration_minutes:y.duration_minutes,speaker:y.speaker||"",meeting_link:y.meeting_link||"",replay_url:y.replay_url||"",is_published:y.is_published}),l(!0)},h=async()=>{if(!o.title.trim())return ae.error("Give the session a title");if(!o.starts_at)return ae.error("Pick a date and time");await r.mutateAsync({...o,starts_at:new Date(o.starts_at).toISOString(),duration_minutes:Number(o.duration_minutes)||60}),l(!1)},m=Date.now(),p=t.filter(y=>new Date(y.starts_at).getTime()>=m),g=t.filter(y=>new Date(y.starts_at).getTime()e.jsx(we,{className:"border-border/60",children:e.jsxs(De,{className:"flex flex-wrap items-start justify-between gap-4 p-5",children:[e.jsxs("div",{className:"min-w-0 space-y-1.5",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("p",{className:"font-medium",children:y.title}),e.jsx(qe,{variant:"secondary",className:"capitalize",children:y.event_kind.replace("_"," ")}),!y.is_published&&e.jsx(qe,{variant:"outline",children:"Hidden"})]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[ru(y.starts_at,!0)," · ",y.duration_minutes," min",y.speaker?` · ${y.speaker}`:""]}),y.description&&e.jsx("p",{className:"max-w-2xl text-sm text-muted-foreground",children:y.description}),e.jsxs("div",{className:"flex flex-wrap gap-3 pt-1 text-xs",children:[y.meeting_link?e.jsxs(e.Fragment,{children:[e.jsxs("a",{className:"inline-flex items-center gap-1 text-primary hover:underline",href:y.meeting_link,target:"_blank",rel:"noreferrer",children:[e.jsx(Ir,{className:"h-3 w-3"})," Join link"]}),e.jsxs("button",{className:"inline-flex items-center gap-1 text-muted-foreground hover:text-foreground",onClick:()=>{navigator.clipboard.writeText(y.meeting_link),ae.success("Join link copied")},children:[e.jsx(Da,{className:"h-3 w-3"})," Copy"]})]}):e.jsx("span",{className:"text-muted-foreground",children:"No meeting link yet"}),y.replay_url&&e.jsxs("a",{className:"inline-flex items-center gap-1 text-primary hover:underline",href:y.replay_url,target:"_blank",rel:"noreferrer",children:[e.jsx(ia,{className:"h-3 w-3"})," Replay"]})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{variant:"outline",size:"sm",onClick:()=>u(y),children:e.jsx(ui,{className:"h-3.5 w-3.5"})}),e.jsx($,{variant:"outline",size:"sm",onClick:async()=>{await io(`Remove "${y.title}"?`)&&a.mutate(y.id)},children:e.jsx(Un,{className:"h-3.5 w-3.5"})})]})]})});return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-wrap items-end justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Live sessions"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Add your Zoom (or Meet / Teams) sessions here. Enrolled members see them in the Sessions tab with the join button, RSVP reminders and an add-to-calendar link."})]}),e.jsxs($,{onClick:d,children:[e.jsx(nn,{className:"mr-1.5 h-4 w-4"})," Add session"]})]}),n?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading sessions…"}):t.length===0?e.jsx(we,{className:"border-dashed",children:e.jsxs(De,{className:"flex flex-col items-center gap-3 p-12 text-center",children:[e.jsx(wm,{className:"h-8 w-8 text-muted-foreground"}),e.jsx("p",{className:"font-medium",children:"No live sessions scheduled"}),e.jsx("p",{className:"max-w-md text-sm text-muted-foreground",children:"Paste your recurring Zoom link once for each call — kickoff, weekly masterminds, workshops and office hours."})]})}):e.jsxs(e.Fragment,{children:[e.jsxs("section",{className:"space-y-3",children:[e.jsxs("h3",{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:["Upcoming (",p.length,")"]}),p.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Nothing upcoming."}):p.map(y=>e.jsx(x,{e:y},y.id))]}),g.length>0&&e.jsxs("section",{className:"space-y-3",children:[e.jsxs("h3",{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:["Past (",g.length,") — add replay links so members can catch up"]}),g.map(y=>e.jsx(x,{e:y},y.id))]})]}),e.jsx(zs,{open:i,onOpenChange:l,children:e.jsxs(Rs,{className:"max-h-[85vh] max-w-2xl overflow-y-auto",children:[e.jsx(Vs,{children:e.jsx($s,{children:o.id?"Edit session":"Add a live session"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Title"}),e.jsx(be,{placeholder:"Week 1 Mastermind — Content that converts",value:o.title,onChange:y=>c({...o,title:y.target.value})})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Type"}),e.jsxs(bs,{value:o.event_kind,onValueChange:y=>c({...o,event_kind:y}),children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsx(vs,{children:fFs.map(y=>e.jsx(We,{value:y.value,children:y.label},y.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Host / speaker"}),e.jsx(be,{value:o.speaker,onChange:y=>c({...o,speaker:y.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Starts (your local time)"}),e.jsx(be,{type:"datetime-local",value:o.starts_at,onChange:y=>c({...o,starts_at:y.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Length (minutes)"}),e.jsx(be,{type:"number",value:o.duration_minutes,onChange:y=>c({...o,duration_minutes:y.target.value})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Zoom / meeting link"}),e.jsx(be,{placeholder:"https://us02web.zoom.us/j/1234567890?pwd=…",value:o.meeting_link,onChange:y=>c({...o,meeting_link:y.target.value})}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Members only see this after they're enrolled. A recurring Zoom link can be reused on every session."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Replay link (after the call)"}),e.jsx(be,{placeholder:"YouTube, Vimeo, Loom or Zoom cloud recording URL",value:o.replay_url,onChange:y=>c({...o,replay_url:y.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"What we'll cover"}),e.jsx(Ls,{rows:3,value:o.description,onChange:y=>c({...o,description:y.target.value})})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border border-border/60 p-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Visible to members"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Turn off to draft a session privately."})]}),e.jsx(On,{checked:o.is_published,onCheckedChange:y=>c({...o,is_published:y})})]})]}),e.jsx(kr,{children:e.jsxs($,{onClick:h,disabled:r.isPending,children:[r.isPending&&e.jsx(Jt,{className:"mr-1.5 h-4 w-4 animate-spin"}),o.id?"Save session":"Add session"]})})]})})]})},qut={title:"",summary:"",week_id:"none",duration_minutes:"",video_url:"",worksheet_url:"",action_assignment:"",status:"published",sort_order:0},xFs=({programId:s})=>{const{data:t,isLoading:n}=AAs(s),r=(t==null?void 0:t.lessons)||[],a=(t==null?void 0:t.weeks)||[],{data:i=[]}=RMt(s),l=EAs(s),o=TAs(),[c,d]=k.useState(!1),[u,h]=k.useState({...qut}),[m,p]=k.useState(!1),g=k.useRef(null),x=async A=>{if(g.current&&(g.current.value=""),!!A){if(!A.type.startsWith("video/"))return ae.error("Please choose a video file");if(A.size>500*1024*1024)return ae.error("Video must be under 500MB");p(!0);try{const M=A.name.split(".").pop()||"mp4",I=`lessons/${crypto.randomUUID()}.${M}`,{error:P}=await V.storage.from("program-assets").upload(I,A,{contentType:A.type,upsert:!1});if(P)throw P;const{data:R,error:O}=await V.storage.from("program-assets").createSignedUrl(I,60*60*24*365*5);if(O||!(R!=null&&R.signedUrl))throw O||new Error("Could not sign video URL");h(B=>({...B,video_url:R.signedUrl})),ae.success("Video uploaded")}catch(M){ae.error((M==null?void 0:M.message)||"Upload failed")}finally{p(!1)}}},y=()=>{h({...qut,sort_order:r.length}),d(!0)},v=A=>{h({id:A.id,title:A.title,summary:A.summary||"",week_id:A.week_id||"none",duration_minutes:A.duration_minutes??"",video_url:A.video_url||"",worksheet_url:A.worksheet_url||"",action_assignment:A.action_assignment||"",status:A.status,sort_order:A.sort_order}),d(!0)},_=async()=>{if(!u.title.trim())return ae.error("Give the video a title");await l.mutateAsync({...u,week_id:u.week_id==="none"?null:u.week_id,duration_minutes:u.duration_minutes===""?null:Number(u.duration_minutes),sort_order:Number(u.sort_order)||0}),d(!1)},j=A=>{const M=a.find(I=>I.id===A);return M?`Week ${M.week_number}`:"Unassigned"},C=IMt(u.video_url);return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-wrap items-end justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"On-demand videos"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Your program's video library. Paste a YouTube, Vimeo or Loom link and it plays inline in the member workspace, grouped by week, with completion tracking."})]}),e.jsxs($,{onClick:y,children:[e.jsx(nn,{className:"mr-1.5 h-4 w-4"})," Add video"]})]}),n?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading library…"}):r.length===0?e.jsx(we,{className:"border-dashed",children:e.jsxs(De,{className:"flex flex-col items-center gap-3 p-12 text-center",children:[e.jsx(em,{className:"h-8 w-8 text-muted-foreground"}),e.jsx("p",{className:"font-medium",children:"No on-demand videos yet"}),e.jsx("p",{className:"max-w-md text-sm text-muted-foreground",children:"Add training videos members can watch any time — assign each one to a week to build the roadmap."})]})}):e.jsx("div",{className:"space-y-3",children:r.map(A=>e.jsx(we,{className:"border-border/60",children:e.jsxs(De,{className:"flex flex-wrap items-start justify-between gap-4 p-5",children:[e.jsxs("div",{className:"min-w-0 space-y-1.5",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("p",{className:"font-medium",children:A.title}),e.jsx(qe,{variant:"secondary",children:j(A.week_id)}),A.status!=="published"&&e.jsx(qe,{variant:"outline",className:"capitalize",children:A.status}),A.duration_minutes?e.jsxs("span",{className:"text-xs text-muted-foreground",children:[A.duration_minutes," min"]}):null]}),A.summary&&e.jsx("p",{className:"max-w-2xl text-sm text-muted-foreground",children:A.summary}),e.jsxs("div",{className:"flex flex-wrap gap-3 pt-1 text-xs",children:[A.video_url?e.jsxs("a",{className:"inline-flex items-center gap-1 text-primary hover:underline",href:A.video_url,target:"_blank",rel:"noreferrer",children:[e.jsx(Ir,{className:"h-3 w-3"})," Video"]}):e.jsx("span",{className:"text-muted-foreground",children:"No video link"}),A.worksheet_url&&e.jsxs("a",{className:"inline-flex items-center gap-1 text-primary hover:underline",href:A.worksheet_url,target:"_blank",rel:"noreferrer",children:[e.jsx(Ir,{className:"h-3 w-3"})," Worksheet"]})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{variant:"outline",size:"sm",onClick:()=>v(A),children:e.jsx(ui,{className:"h-3.5 w-3.5"})}),e.jsx($,{variant:"outline",size:"sm",onClick:async()=>{await io(`Remove "${A.title}"?`)&&o.mutate(A.id)},children:e.jsx(Un,{className:"h-3.5 w-3.5"})})]})]})},A.id))}),e.jsx(zs,{open:c,onOpenChange:d,children:e.jsxs(Rs,{className:"max-h-[85vh] max-w-2xl overflow-y-auto",children:[e.jsx(Vs,{children:e.jsx($s,{children:u.id?"Edit video":"Add an on-demand video"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Title"}),e.jsx(be,{placeholder:"How to script a 30-second listing reel",value:u.title,onChange:A=>h({...u,title:A.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Video link"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(be,{placeholder:"https://youtu.be/… , Vimeo or Loom URL",value:u.video_url,onChange:A=>h({...u,video_url:A.target.value})}),e.jsxs($,{type:"button",variant:"outline",className:"shrink-0",disabled:m,onClick:()=>{var A;return(A=g.current)==null?void 0:A.click()},children:[m?e.jsx(Jt,{className:"mr-1.5 h-4 w-4 animate-spin"}):e.jsx(gi,{className:"mr-1.5 h-4 w-4"}),m?"Uploading…":"Upload"]}),e.jsx("input",{ref:g,type:"file",accept:"video/*",className:"hidden",onChange:A=>{var M;return x((M=A.target.files)==null?void 0:M[0])}})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Paste a YouTube / Vimeo / Loom link, or upload an MP4 (up to 500MB) hosted by LevelUp."}),u.video_url&&!C&&!NY(u.video_url)&&e.jsx("p",{className:"text-xs text-muted-foreground",children:`We can't embed this link — members will get an "Open video" button instead.`})]}),C&&e.jsx("div",{className:"overflow-hidden rounded-lg border border-border/60",children:e.jsx("iframe",{src:C,title:"Video preview",className:"aspect-video w-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; picture-in-picture",allowFullScreen:!0})}),!C&&NY(u.video_url)&&e.jsx("div",{className:"overflow-hidden rounded-lg border border-border/60 bg-black",children:e.jsx("video",{src:u.video_url,controls:!0,className:"aspect-video w-full",preload:"metadata"})}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Week"}),e.jsxs(bs,{value:u.week_id,onValueChange:A=>h({...u,week_id:A}),children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"none",children:"Unassigned (library)"}),a.map(A=>e.jsxs(We,{value:A.id,children:["Week ",A.week_number," — ",A.title]},A.id))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Length (minutes)"}),e.jsx(be,{type:"number",value:u.duration_minutes,onChange:A=>h({...u,duration_minutes:A.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Status"}),e.jsxs(bs,{value:u.status,onValueChange:A=>h({...u,status:A}),children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"published",children:"Published (visible)"}),e.jsx(We,{value:"draft",children:"Draft (hidden)"}),e.jsx(We,{value:"archived",children:"Archived"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Order"}),e.jsx(be,{type:"number",value:u.sort_order,onChange:A=>h({...u,sort_order:A.target.value})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Summary"}),e.jsx(Ls,{rows:3,value:u.summary,onChange:A=>h({...u,summary:A.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Worksheet / download link"}),i.length>0&&e.jsxs(bs,{value:"",onValueChange:A=>{const M=i.find(P=>P.id===A),I=M?Cee(M):null;I?h({...u,worksheet_url:I}):ae.error("That resource has no file or link yet")},children:[e.jsx(ys,{children:e.jsx(_s,{placeholder:"Choose an uploaded program resource…"})}),e.jsx(vs,{children:i.map(A=>e.jsx(We,{value:A.id,children:A.title},A.id))})]}),e.jsx(be,{placeholder:"Or paste a link",value:u.worksheet_url,onChange:A=>h({...u,worksheet_url:A.target.value})}),u.worksheet_url&&e.jsxs("a",{href:u.worksheet_url,target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-1 text-xs text-primary hover:underline",children:[e.jsx(Ir,{className:"h-3 w-3"})," Preview worksheet"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Action assignment"}),e.jsx(Ls,{rows:2,placeholder:"Post one reel using this hook before your next mastermind.",value:u.action_assignment,onChange:A=>h({...u,action_assignment:A.target.value})})]})]}),e.jsx(kr,{children:e.jsxs($,{onClick:_,disabled:l.isPending,children:[l.isPending&&e.jsx(Jt,{className:"mr-1.5 h-4 w-4 animate-spin"}),u.id?"Save video":"Add video"]})})]})})]})},Vut={title:"",description:"",category:"Resources",resource_kind:"pdf",url:"",file_path:"",status:"published",sort_order:0},yFs=({programId:s})=>{const{data:t=[],isLoading:n}=RMt(s),r=MAs(s),a=PAs(),[i,l]=k.useState(!1),[o,c]=k.useState({...Vut}),[d,u]=k.useState(!1),h=k.useRef(null),m=Array.from(new Set(t.map(v=>v.category))).filter(Boolean),p=()=>{c({...Vut,sort_order:t.length}),l(!0)},g=v=>{c({id:v.id,title:v.title,description:v.description||"",category:v.category||"Resources",resource_kind:v.resource_kind,url:v.url||"",file_path:v.file_path||"",status:v.status,sort_order:v.sort_order}),l(!0)},x=async v=>{if(!(!v||!s)){if(v.size>50*1024*1024)return ae.error("File must be under 50MB");u(!0);try{const _=v.name.split(".").pop()||"pdf",j=`programs/${s}/resources/${Date.now()}-${Math.random().toString(36).slice(2,8)}.${_}`,{error:C}=await V.storage.from(Qq).upload(j,v,{contentType:v.type||"application/pdf",upsert:!1});if(C)throw C;c(A=>({...A,file_path:j,url:"",title:A.title||v.name.replace(/\.[^.]+$/,""),resource_kind:v.type==="application/pdf"?"pdf":A.resource_kind})),ae.success("File uploaded")}catch(_){ae.error(_.message||"Upload failed")}finally{u(!1),h.current&&(h.current.value="")}}},y=async()=>{if(!o.title.trim())return ae.error("Give the resource a title");if(!o.file_path&&!o.url.trim())return ae.error("Upload a file or paste a link");await r.mutateAsync({...o,sort_order:Number(o.sort_order)||0}),l(!1)};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-wrap items-end justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Resources"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Upload PDFs, worksheets and checklists — or link to Canva/Google templates. Enrollees see them grouped by category in their program dashboard."})]}),e.jsxs($,{onClick:p,children:[e.jsx(nn,{className:"mr-1.5 h-4 w-4"})," Add resource"]})]}),n?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading resources…"}):t.length===0?e.jsx(we,{className:"border-dashed",children:e.jsxs(De,{className:"flex flex-col items-center gap-3 p-12 text-center",children:[e.jsx(ea,{className:"h-8 w-8 text-muted-foreground"}),e.jsx("p",{className:"font-medium",children:"No resources yet"}),e.jsx("p",{className:"max-w-md text-sm text-muted-foreground",children:"Add the swipe files, scripts and worksheets that make this program feel premium."})]})}):e.jsx("div",{className:"space-y-3",children:t.map(v=>{const _=Cee(v);return e.jsx(we,{className:"border-border/60",children:e.jsxs(De,{className:"flex flex-wrap items-start justify-between gap-4 p-5",children:[e.jsxs("div",{className:"min-w-0 space-y-1.5",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("p",{className:"font-medium",children:v.title}),e.jsx(qe,{variant:"secondary",children:v.category}),e.jsx(qe,{variant:"outline",className:"capitalize",children:v.resource_kind.replace("_"," ")}),v.status!=="published"&&e.jsx(qe,{variant:"outline",className:"capitalize",children:v.status})]}),v.description&&e.jsx("p",{className:"max-w-2xl text-sm text-muted-foreground",children:v.description}),_&&e.jsxs("button",{type:"button",onClick:()=>kY(v),className:"inline-flex items-center gap-1 text-xs text-primary hover:underline",children:[e.jsx(Ir,{className:"h-3 w-3"})," Open"]})]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx($,{variant:"ghost",size:"icon",onClick:()=>g(v),children:e.jsx(ui,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:async()=>{await io(`Remove "${v.title}"?`)&&a.mutate(v)},children:e.jsx(Un,{className:"h-4 w-4 text-destructive"})})]})]})},v.id)})}),e.jsx(zs,{open:i,onOpenChange:l,children:e.jsxs(Rs,{className:"max-w-lg",children:[e.jsx(Vs,{children:e.jsx($s,{children:o.id?"Edit resource":"Add resource"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Title"}),e.jsx(be,{value:o.title,onChange:v=>c({...o,title:v.target.value}),placeholder:"90-Day Content Calendar"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Description"}),e.jsx(Ls,{rows:2,value:o.description,onChange:v=>c({...o,description:v.target.value}),placeholder:"What this is and how to use it"})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Category"}),e.jsx(be,{value:o.category,onChange:v=>c({...o,category:v.target.value}),placeholder:"Getting started",list:"program-resource-categories"}),e.jsx("datalist",{id:"program-resource-categories",children:m.map(v=>e.jsx("option",{value:v},v))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Type"}),e.jsxs(bs,{value:o.resource_kind,onValueChange:v=>c({...o,resource_kind:v}),children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsx(vs,{children:LMt.map(v=>e.jsx(We,{value:v.value,children:v.label},v.value))})]})]})]}),e.jsxs("div",{className:"space-y-2 rounded-lg border p-3",children:[e.jsx(re,{children:"File"}),e.jsx("input",{ref:h,type:"file",className:"hidden",accept:".pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.csv,.zip,image/*",onChange:v=>{var _;return x((_=v.target.files)==null?void 0:_[0])}}),o.file_path?e.jsxs("div",{className:"flex items-center justify-between gap-2 text-sm",children:[e.jsx("span",{className:"truncate",children:o.file_path.split("/").pop()}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>c({...o,file_path:""}),children:"Remove"})]}):e.jsxs($,{variant:"outline",size:"sm",onClick:()=>{var v;return(v=h.current)==null?void 0:v.click()},disabled:d,children:[d?e.jsx(Jt,{className:"mr-1.5 h-4 w-4 animate-spin"}):e.jsx(gi,{className:"mr-1.5 h-4 w-4"}),"Upload PDF or document"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Or paste an external link instead (Canva, Google Doc, Notion…)."}),e.jsx(be,{value:o.url,onChange:v=>c({...o,url:v.target.value,file_path:""}),placeholder:"https://…",disabled:!!o.file_path})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Status"}),e.jsxs(bs,{value:o.status,onValueChange:v=>c({...o,status:v}),children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"published",children:"Published (visible)"}),e.jsx(We,{value:"draft",children:"Draft (hidden)"}),e.jsx(We,{value:"archived",children:"Archived"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Sort order"}),e.jsx(be,{type:"number",value:o.sort_order,onChange:v=>c({...o,sort_order:v.target.value})})]})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsxs($,{onClick:y,disabled:r.isPending||d,children:[r.isPending&&e.jsx(Jt,{className:"mr-1.5 h-4 w-4 animate-spin"})," Save resource"]})]})]})})]})},vFs=({programId:s})=>{const{data:t=[],isLoading:n}=FAs(s),r=k.useMemo(()=>{const l=Date.now()-6048e5;return t.filter(o=>new Date(o.created_at).getTime()>=l).length},[t]),a=t.map(l=>l.email).filter(Boolean).join(", "),i=()=>{const l=`Name,Email,Phone,Brokerage,Joined `,o=t.map(u=>[u.full_name,u.email,u.phone,u.brokerage,u.created_at].map(h=>`"${(h??"").toString().replace(/"/g,'""')}"`).join(",")).join(` `),c=URL.createObjectURL(new Blob([l+o],{type:"text/csv"})),d=document.createElement("a");d.href=c,d.download="program-interest.csv",d.click(),URL.revokeObjectURL(c)};return n?e.jsx(fn,{className:"h-64 w-full rounded-xl"}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-4 sm:grid-cols-3",children:[e.jsx(we,{children:e.jsxs(De,{className:"flex items-center gap-3 p-4",children:[e.jsx(p3,{className:"h-5 w-5 text-primary"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:t.length}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"On the notify list"})]})]})}),e.jsx(we,{children:e.jsxs(De,{className:"flex items-center gap-3 p-4",children:[e.jsx(Xn,{className:"h-5 w-5 text-primary"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:r}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Signed up in last 7 days"})]})]})}),e.jsx(we,{children:e.jsx(De,{className:"flex items-center gap-3 p-4",children:e.jsxs(qe,{variant:"secondary",children:[t.filter(l=>l.notified_at).length," notified"]})})})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs($,{variant:"outline",size:"sm",disabled:!a,onClick:()=>{navigator.clipboard.writeText(a),ae.success("Emails copied")},children:[e.jsx(Da,{className:"mr-2 h-4 w-4"})," Copy emails"]}),e.jsxs($,{variant:"outline",size:"sm",disabled:!t.length,onClick:i,children:[e.jsx(ji,{className:"mr-2 h-4 w-4"})," Export CSV"]})]}),t.length===0?e.jsx("p",{className:"rounded-lg border border-dashed p-8 text-center text-sm text-muted-foreground",children:"Nobody has asked to be notified yet."}):e.jsx("div",{className:"rounded-lg border",children:e.jsxs(Qa,{children:[e.jsx(Ja,{children:e.jsxs(vn,{children:[e.jsx(Dt,{children:"Member"}),e.jsx(Dt,{children:"Email"}),e.jsx(Dt,{children:"Phone"}),e.jsx(Dt,{children:"Brokerage"}),e.jsx(Dt,{children:"Joined"})]})}),e.jsx(ei,{children:t.map(l=>e.jsxs(vn,{children:[e.jsx(_t,{className:"font-medium",children:l.full_name||"—"}),e.jsx(_t,{children:l.email||"—"}),e.jsx(_t,{children:l.phone||"—"}),e.jsx(_t,{children:l.brokerage||"—"}),e.jsx(_t,{className:"text-muted-foreground",children:ru(l.created_at)})]},l.id))})]})})]})},Hut={name:"",slug:"",subtitle:"",short_description:"",description:"",price_cents:0,capacity:50,duration_weeks:13,weekly_video_goal:3,payment_mode:"delayed",status:"draft",kickoff_at:"",charge_at:"",enrollment_close_at:"",cover_image_url:""},bFs=()=>{const s=ls(),[t,n]=k.useState(null),[r,a]=k.useState(!1),[i,l]=k.useState({...Hut}),[o,c]=k.useState(!1),[d,u]=k.useState(!1),[h,m]=k.useState(null),{data:p=[],isLoading:g}=pt({queryKey:["admin-programs"],queryFn:async()=>{const{data:P,error:R}=await V.from("programs").select("*").order("created_at",{ascending:!1});if(R)throw R;return P||[]}}),x=p.find(P=>P.id===t)||p[0]||null,{data:y=[]}=pt({queryKey:["admin-program-enrollments",x==null?void 0:x.id],enabled:!!(x!=null&&x.id),queryFn:async()=>{const{data:P,error:R}=await V.from("program_enrollments").select("*").eq("program_id",x.id).order("created_at",{ascending:!1});if(R)throw R;const O=(P||[]).map(G=>G.user_id),{data:B}=O.length?await V.from("profiles").select("id, name, email").in("id",O):{data:[]},U=new Map((B||[]).map(G=>[G.id,G]));return(P||[]).map(G=>({...G,profile:U.get(G.user_id)}))}}),{data:v=[]}=pt({queryKey:["admin-program-intakes",x==null?void 0:x.id],enabled:!!(x!=null&&x.id),queryFn:async()=>{const{data:P,error:R}=await V.from("program_intake_responses").select("*").eq("program_id",x.id);if(R)throw R;return P||[]}}),{data:_=[]}=pt({queryKey:["admin-program-audit",x==null?void 0:x.id],enabled:!!(x!=null&&x.id),queryFn:async()=>{const{data:P,error:R}=await V.from("program_audit_logs").select("*").eq("program_id",x.id).order("created_at",{ascending:!1}).limit(100);if(R)throw R;return P||[]}}),j=async()=>{c(!0);try{const P={...i,slug:i.slug||i.name.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,""),kickoff_at:i.kickoff_at||null,charge_at:i.charge_at||null,enrollment_close_at:i.enrollment_close_at||null},{error:R}=await V.from("programs").insert(P);if(R)throw R;ae.success("Program created"),a(!1),l({...Hut}),s.invalidateQueries({queryKey:["admin-programs"]})}catch(P){ae.error(P.message||"Could not create the program")}finally{c(!1)}},C=async P=>{if(!x)return;const{error:R}=await V.from("programs").update(P).eq("id",x.id);if(R)return ae.error(R.message);s.invalidateQueries({queryKey:["admin-programs"]})},A=async(P,R)=>{const{error:O}=await V.from("program_enrollments").update(R).eq("id",P);if(O)return ae.error(O.message);ae.success("Enrollment updated"),s.invalidateQueries({queryKey:["admin-program-enrollments"]})},M=async P=>{u(!0);const{data:R,error:O}=await V.functions.invoke("program-charge-due",{body:P?{enrollment_id:P}:{}});if(u(!1),O||R!=null&&R.error)return ae.error((R==null?void 0:R.error)||(O==null?void 0:O.message));ae.success(`Processed ${(R==null?void 0:R.processed)??0} charge(s)`),s.invalidateQueries({queryKey:["admin-program-enrollments"]})},I=P=>P==="paid"||P==="completed"?"default":P==="payment_failed"?"destructive":"secondary";return e.jsx(Xs,{children:e.jsxs("div",{className:"mx-auto w-full max-w-7xl space-y-6 p-4 md:p-8",children:[e.jsxs("header",{className:"flex flex-wrap items-end justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold tracking-tight",children:"Programs"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Manage cohorts, enrollments, delayed billing and program content."})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs($,{variant:"outline",onClick:()=>M(),disabled:d,children:[d?e.jsx(Jt,{className:"mr-1.5 h-4 w-4 animate-spin"}):e.jsx(cv,{className:"mr-1.5 h-4 w-4"}),"Run due charges"]}),e.jsxs(zs,{open:r,onOpenChange:a,children:[e.jsx(yl,{asChild:!0,children:e.jsxs($,{children:[e.jsx(nn,{className:"mr-1.5 h-4 w-4"})," New program"]})}),e.jsxs(Rs,{className:"max-h-[85vh] overflow-y-auto",children:[e.jsx(Vs,{children:e.jsx($s,{children:"Create a program"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Name"}),e.jsx(be,{value:i.name,onChange:P=>l({...i,name:P.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Slug (URL)"}),e.jsx(be,{placeholder:"reel-estate-90",value:i.slug,onChange:P=>l({...i,slug:P.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Subtitle"}),e.jsx(be,{value:i.subtitle,onChange:P=>l({...i,subtitle:P.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Description"}),e.jsx(Ls,{rows:4,value:i.description,onChange:P=>l({...i,description:P.target.value})})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"One-time price (USD)"}),e.jsx(be,{type:"number",value:i.price_cents/100,onChange:P=>l({...i,price_cents:Math.round(Number(P.target.value)*100)})}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Charged one time for the full program — never recurring."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Seats"}),e.jsx(be,{type:"number",value:i.capacity,onChange:P=>l({...i,capacity:Number(P.target.value)})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Weeks"}),e.jsx(be,{type:"number",value:i.duration_weeks,onChange:P=>l({...i,duration_weeks:Number(P.target.value)})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Videos per week"}),e.jsx(be,{type:"number",value:i.weekly_video_goal,onChange:P=>l({...i,weekly_video_goal:Number(P.target.value)})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Billing"}),e.jsxs(bs,{value:i.payment_mode,onValueChange:P=>l({...i,payment_mode:P}),children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"delayed",children:"Save card, charge later"}),e.jsx(We,{value:"immediate",children:"Charge at checkout"}),e.jsx(We,{value:"free",children:"Free / included"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Kickoff"}),e.jsx(be,{type:"datetime-local",value:i.kickoff_at,onChange:P=>l({...i,kickoff_at:P.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Charge date"}),e.jsx(be,{type:"datetime-local",value:i.charge_at,onChange:P=>l({...i,charge_at:P.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Enrollment closes"}),e.jsx(be,{type:"datetime-local",value:i.enrollment_close_at,onChange:P=>l({...i,enrollment_close_at:P.target.value})})]})]})]}),e.jsx(kr,{children:e.jsxs($,{onClick:j,disabled:o||!i.name,children:[o&&e.jsx(Jt,{className:"mr-1.5 h-4 w-4 animate-spin"})," Create"]})})]})]})]})]}),g?e.jsx(fn,{className:"h-40 w-full rounded-xl"}):p.length===0?e.jsx(we,{className:"border-dashed",children:e.jsx(De,{className:"p-12 text-center text-sm text-muted-foreground",children:"No programs yet. Create your first cohort to get started."})}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"flex flex-wrap gap-2",children:p.map(P=>e.jsxs($,{variant:(x==null?void 0:x.id)===P.id?"default":"outline",size:"sm",onClick:()=>n(P.id),children:[P.name,e.jsx(qe,{variant:"secondary",className:"ml-2 capitalize",children:P.status})]},P.id))}),x&&e.jsxs(ya,{defaultValue:"overview",children:[e.jsxs(va,{className:"flex w-full flex-wrap justify-start",children:[e.jsx(is,{value:"overview",children:"Overview"}),e.jsx(is,{value:"details",children:"Details & pricing"}),e.jsx(is,{value:"sessions",children:"Live sessions"}),e.jsx(is,{value:"videos",children:"On-demand videos"}),e.jsx(is,{value:"resources",children:"Resources"}),e.jsx(is,{value:"intake-form",children:"Intake form"}),e.jsx(is,{value:"discounts",children:"Discount codes"}),e.jsx(is,{value:"experience",children:"Enrollee experience"}),e.jsx(is,{value:"interest",children:"Interest list"}),e.jsxs(is,{value:"enrollments",children:["Enrollments (",y.length,")"]}),e.jsxs(is,{value:"intake",children:["Intake (",v.length,")"]}),e.jsx(is,{value:"audit",children:"Audit"})]}),e.jsxs(cs,{value:"overview",className:"mt-6 space-y-4",children:[e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-4",children:[e.jsx(we,{children:e.jsxs(De,{className:"p-5",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Seats filled"}),e.jsxs("p",{className:"mt-1 text-2xl font-bold",children:[y.filter(P=>["reserved","scheduled_for_charge","paid","completed"].includes(P.status)).length,e.jsxs("span",{className:"text-base font-normal text-muted-foreground",children:[" / ",x.capacity]})]})]})}),e.jsx(we,{children:e.jsxs(De,{className:"p-5",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Paid"}),e.jsx("p",{className:"mt-1 text-2xl font-bold",children:y.filter(P=>P.status==="paid").length})]})}),e.jsx(we,{children:e.jsxs(De,{className:"p-5",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Failed payments"}),e.jsx("p",{className:"mt-1 text-2xl font-bold",children:y.filter(P=>P.status==="payment_failed").length})]})}),e.jsx(we,{children:e.jsxs(De,{className:"p-5",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Projected revenue (one-time)"}),e.jsx("p",{className:"mt-1 text-2xl font-bold",children:Tp(y.filter(P=>["scheduled_for_charge","paid","completed"].includes(P.status)).reduce((P,R)=>P+(R.amount_cents||0),0),x.currency)})]})})]}),e.jsx(we,{children:e.jsxs(De,{className:"space-y-5 p-6",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Publish this program"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Published programs appear on the member Programs page."})]}),e.jsx(On,{checked:x.status==="published",onCheckedChange:P=>C({status:P?"published":"draft"})})]}),e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-4 border-t border-border/60 pt-5",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Feature it"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Pins the program to the top."})]}),e.jsx(On,{checked:x.is_featured,onCheckedChange:P=>C({is_featured:P})})]}),e.jsxs("div",{className:"grid gap-4 border-t border-border/60 pt-5 sm:grid-cols-3 text-sm",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground",children:"One-time price"}),e.jsx("p",{className:"font-medium",children:Tp(x.price_cents,x.currency)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground",children:"Kickoff"}),e.jsx("p",{className:"font-medium",children:ru(x.kickoff_at)||"Not set"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground",children:"Charge date"}),e.jsx("p",{className:"font-medium",children:ru(x.charge_at)||"Not set"})]})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Edit pricing, seats, description, dates and images in the"," ",e.jsx("strong",{children:"Details"})," tab."]})]})})]}),e.jsx(cs,{value:"details",className:"mt-6",children:e.jsx(sFs,{program:x,onSaved:()=>s.invalidateQueries({queryKey:["admin-programs"]})})}),e.jsx(cs,{value:"sessions",className:"mt-6",children:e.jsx(gFs,{programId:x.id})}),e.jsx(cs,{value:"videos",className:"mt-6",children:e.jsx(xFs,{programId:x.id})}),e.jsx(cs,{value:"resources",className:"mt-6",children:e.jsx(yFs,{programId:x.id})}),e.jsx(cs,{value:"discounts",className:"mt-6",children:e.jsx(aFs,{program:x})}),e.jsx(cs,{value:"intake-form",className:"mt-6",children:e.jsx(cFs,{program:x,onSaved:()=>s.invalidateQueries({queryKey:["admin-programs"]})})}),e.jsx(cs,{value:"experience",className:"mt-6",children:e.jsx(iFs,{program:x})}),e.jsx(cs,{value:"interest",className:"mt-6",children:e.jsx(vFs,{programId:x.id})}),e.jsx(cs,{value:"enrollments",className:"mt-6",children:e.jsx(we,{children:e.jsx(De,{className:"overflow-x-auto p-0",children:e.jsxs(Qa,{children:[e.jsx(Ja,{children:e.jsxs(vn,{children:[e.jsx(Dt,{children:"Member"}),e.jsx(Dt,{children:"Status"}),e.jsx(Dt,{children:"Charge date"}),e.jsx(Dt,{children:"Amount"}),e.jsx(Dt,{children:"Access"}),e.jsx(Dt,{className:"text-right",children:"Actions"})]})}),e.jsxs(ei,{children:[y.length===0&&e.jsx(vn,{children:e.jsxs(_t,{colSpan:6,className:"py-10 text-center text-sm text-muted-foreground",children:[e.jsx(Xn,{className:"mx-auto mb-2 h-5 w-5"}),"No enrollments yet"]})}),y.map(P=>{var R,O;return e.jsxs(vn,{children:[e.jsx(_t,{children:e.jsxs("button",{type:"button",className:"text-left hover:underline",onClick:()=>m(P),children:[e.jsx("p",{className:"font-medium",children:((R=P.profile)==null?void 0:R.name)||"Unknown"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:(O=P.profile)==null?void 0:O.email})]})}),e.jsxs(_t,{children:[e.jsx(qe,{variant:I(P.status),className:"capitalize",children:String(P.status).replace(/_/g," ")}),P.last_payment_error&&e.jsx("p",{className:"mt-1 max-w-[200px] truncate text-xs text-destructive",children:P.last_payment_error})]}),e.jsx(_t,{className:"text-sm",children:ru(P.charge_scheduled_at)||"—"}),e.jsx(_t,{className:"text-sm",children:Tp(P.amount_cents,P.currency)}),e.jsx(_t,{children:e.jsx(On,{checked:P.access_override,onCheckedChange:B=>A(P.id,{access_override:B})})}),e.jsxs(_t,{className:"space-x-2 text-right",children:[["scheduled_for_charge","payment_failed"].includes(P.status)&&e.jsxs($,{size:"sm",variant:"outline",onClick:()=>M(P.id),disabled:d,children:[e.jsx(yo,{className:"mr-1.5 h-3.5 w-3.5"})," Charge now"]}),!["canceled","refunded"].includes(P.status)&&e.jsx($,{size:"sm",variant:"ghost",onClick:()=>A(P.id,{status:"canceled",canceled_at:new Date().toISOString()}),children:"Cancel"})]})]},P.id)})]})]})})})}),e.jsx(cs,{value:"intake",className:"mt-6",children:e.jsx(mFs,{program:x})}),e.jsx(cs,{value:"audit",className:"mt-6",children:e.jsx(we,{children:e.jsxs(De,{className:"space-y-2 p-5 text-sm",children:[_.length===0&&e.jsx("p",{className:"text-muted-foreground",children:"No activity yet."}),_.map(P=>e.jsxs("div",{className:"flex flex-wrap items-center gap-2 border-b border-border/40 py-2 last:border-0",children:[e.jsx(qe,{variant:"outline",className:"capitalize",children:String(P.action).replace(/_/g," ")}),e.jsx("span",{className:"text-muted-foreground",children:P.actor_label||"system"}),e.jsx("span",{className:"ml-auto text-xs text-muted-foreground",children:ru(P.created_at,!0)})]},P.id))]})})})]}),x&&e.jsx(rFs,{program:x,enrollment:h,open:!!h,onOpenChange:P=>!P&&m(null),onUpdated:()=>s.invalidateQueries({queryKey:["admin-program-enrollments"]})})]})]})})},_Fs=()=>{const{user:s}=ks(),[t,n]=k.useState(""),[r,a]=k.useState("all"),{data:i=[]}=pt({queryKey:["academy-categories"],queryFn:async()=>{const{data:m,error:p}=await V.from("academy_categories").select("*").order("sort_order",{ascending:!0});if(p)throw p;return m}}),{data:l=[],isLoading:o}=pt({queryKey:["academy-videos"],queryFn:async()=>{const{data:m,error:p}=await V.from("academy_videos").select(` *, category:academy_categories(id, name) `).eq("is_published",!0).order("publish_date",{ascending:!1});if(p)throw p;const{data:g,error:x}=await V.from("academy_resources").select("*").order("sort_order");if(x)throw x;return m.map(v=>({...v,resources:(g==null?void 0:g.filter(_=>_.video_id===v.id))||[]}))}}),{data:c=[]}=pt({queryKey:["academy-video-likes"],queryFn:async()=>{const{data:m,error:p}=await V.from("academy_video_likes").select("video_id, user_id");if(p)throw p;return m}}),d=l.filter(m=>{var x;const p=t===""||m.title.toLowerCase().includes(t.toLowerCase())||((x=m.description)==null?void 0:x.toLowerCase().includes(t.toLowerCase())),g=r==="all"||m.category_id===r;return p&&g}),u=m=>c.filter(p=>p.video_id===m).length,h=m=>c.some(p=>p.video_id===m&&p.user_id===(s==null?void 0:s.id));return e.jsx(Xs,{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(Yr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search videos...",value:t,onChange:m=>n(m.target.value),className:"pl-10"})]})}),e.jsx(ya,{value:r,onValueChange:a,children:e.jsxs(va,{className:"w-full justify-start flex-wrap h-auto gap-2 bg-transparent p-0",children:[e.jsx(is,{value:"all",className:"data-[state=active]:bg-primary data-[state=active]:text-primary-foreground",children:"All Videos"}),i.map(m=>e.jsx(is,{value:m.id,className:"data-[state=active]:bg-primary data-[state=active]:text-primary-foreground",children:m.name},m.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(we,{children:e.jsxs(De,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(ia,{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(m=>e.jsx(nr,{to:`/academy/${m.id}`,children:e.jsxs(we,{className:"overflow-hidden cursor-pointer hover:shadow-lg transition-shadow group h-full",children:[e.jsxs("div",{className:"relative aspect-video bg-muted",children:[m.thumbnail_url?e.jsx("img",{src:m.thumbnail_url,alt:m.title,className:"w-full h-full object-cover"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(ia,{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(pu,{className:"h-8 w-8 text-primary-foreground ml-1"})})}),m.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(sa,{className:"h-3 w-3"}),m.duration]})]}),e.jsxs(Vt,{className:"pb-2",children:[e.jsx("div",{className:"flex items-start justify-between gap-2",children:e.jsx(Yt,{className:"text-lg line-clamp-2",children:m.title})}),m.category&&e.jsx(qe,{variant:"secondary",className:"w-fit",children:m.category.name})]}),e.jsxs(De,{className:"pt-0",children:[m.description&&e.jsx(vr,{className:"line-clamp-2",children:m.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(Ay,{className:`h-4 w-4 ${h(m.id)?"fill-primary text-primary":""}`}),u(m.id)]}),m.resources&&m.resources.length>0&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ea,{className:"h-4 w-4"}),m.resources.length]})]})]})]})},m.id))})]})})};function RIt({resourceType:s,resourceId:t}){const{data:n=[]}=pt({queryKey:["linked-templates",s,t],queryFn:async()=>{if(s==="academy_video"){const{data:r,error:a}=await V.from("academy_video_templates").select("template_id, canva_templates:template_id(id, name, preview_image_url)").eq("video_id",t);if(a)throw a;return(r||[]).map(i=>i.canva_templates).filter(Boolean)}else{const{data:r,error:a}=await V.from("resource_kit_templates").select("template_id, canva_templates:template_id(id, name, preview_image_url)").eq("kit_id",t);if(a)throw a;return(r||[]).map(i=>i.canva_templates).filter(Boolean)}},enabled:!!t});return n.length===0?null:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 text-sm",children:[e.jsx(gd,{className:"h-4 w-4"}),"Related Templates"]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:n.map(r=>e.jsx(nr,{to:`/templates/${r.id}`,children:e.jsxs(qe,{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(gd,{className:"h-3 w-3"}),r.name]})},r.id))})]})}const wFs=(s,t)=>{if(t==="bunny_stream"){let n=s.replace("iframe.mediadelivery.net","player.mediadelivery.net");return n.includes("?")||(n+="?autoplay=false&loop=false&muted=false&preload=true&responsive=true"),n}if(t==="youtube"){const n=/(?:youtube\.com\/(?:watch\?v=|embed\/)|youtu\.be\/)([a-zA-Z0-9_-]{11})/,r=s.match(n);if(r)return`https://www.youtube.com/embed/${r[1]}`}if(t==="vimeo"){const n=/vimeo\.com\/(?:video\/)?(\d+)/,r=s.match(n);if(r)return`https://player.vimeo.com/video/${r[1]}`}if(t==="loom"){const n=/loom\.com\/share\/([a-zA-Z0-9]+)/,r=s.match(n);if(r)return`https://www.loom.com/embed/${r[1]}`}return s},jFs=()=>{const{videoId:s}=oo();Jn();const{user:t,isAdmin:n}=ks(),{toast:r}=Fi(),a=ls(),{trackEngagement:i}=Xq(),[l,o]=k.useState(""),{data:c,isLoading:d}=pt({queryKey:["academy-video",s],queryFn:async()=>{const{data:j,error:C}=await V.from("academy_videos").select(` *, category:academy_categories(id, name) `).eq("id",s).eq("is_published",!0).single();if(C)throw C;const{data:A}=await V.from("academy_resources").select("*").eq("video_id",s).order("sort_order");return{...j,resources:A||[]}},enabled:!!s});k.useEffect(()=>{c&&i("academy_video",c.id,c.title,"view")},[c==null?void 0:c.id]);const{data:u=[]}=pt({queryKey:["academy-video-likes",s],queryFn:async()=>{const{data:j,error:C}=await V.from("academy_video_likes").select("*").eq("video_id",s);if(C)throw C;return j},enabled:!!s}),{data:h=[]}=pt({queryKey:["academy-video-comments",s],queryFn:async()=>{const{data:j,error:C}=await V.from("academy_video_comments").select("*").eq("video_id",s).order("created_at",{ascending:!1});if(C)throw C;const A=[...new Set(j.map(P=>P.user_id))],{data:M}=await V.from("profiles").select("id, name").in("id",A),I=new Map((M==null?void 0:M.map(P=>[P.id,P.name]))||[]);return j.map(P=>({...P,user_name:I.get(P.user_id)||"Unknown User"}))},enabled:!!s}),m=Nt({mutationFn:async j=>{const{error:C}=await V.from("academy_video_comments").insert({video_id:s,user_id:t.id,content:j});if(C)throw C},onSuccess:()=>{a.invalidateQueries({queryKey:["academy-video-comments",s]}),o(""),r({title:"Comment added!"})},onError:j=>{r({title:"Error adding comment",description:j.message,variant:"destructive"})}}),p=Nt({mutationFn:async j=>{const{error:C}=await V.from("academy_video_comments").delete().eq("id",j);if(C)throw C},onSuccess:()=>{a.invalidateQueries({queryKey:["academy-video-comments",s]}),r({title:"Comment deleted"})}}),g=Nt({mutationFn:async()=>{const j=u.find(C=>C.user_id===(t==null?void 0:t.id));if(j){const{error:C}=await V.from("academy_video_likes").delete().eq("id",j.id);if(C)throw C}else{const{error:C}=await V.from("academy_video_likes").insert({video_id:s,user_id:t.id});if(C)throw C}},onSuccess:()=>{a.invalidateQueries({queryKey:["academy-video-likes",s]})}}),x=u.some(j=>j.user_id===(t==null?void 0:t.id)),y=j=>{switch(j==null?void 0:j.toLowerCase()){case"pdf":return"📄";case"pptx":case"ppt":return"📊";case"xlsx":case"xls":return"📈";case"docx":case"doc":return"📝";case"zip":return"📦";default:return"📁"}},v=j=>j.split(" ").map(C=>C[0]).join("").toUpperCase().slice(0,2),_=j=>{j.preventDefault(),!(!l.trim()||!t)&&m.mutate(l.trim())};return d?e.jsx(Xs,{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(Xs,{title:c.title,children:e.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[e.jsx($,{variant:"ghost",size:"sm",asChild:!0,className:"gap-2",children:e.jsxs(nr,{to:"/academy",children:[e.jsx(Ia,{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:wFs(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(ia,{className:"h-16 w-16 opacity-50"}),e.jsx($,{variant:"secondary",asChild:!0,children:e.jsxs("a",{href:c.video_url,target:"_blank",rel:"noopener noreferrer",className:"gap-2",children:[e.jsx(Ir,{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(qe,{variant:"secondary",children:c.category.name})]}),e.jsxs("div",{className:"flex gap-2",children:[n&&e.jsx($,{variant:"outline",className:"gap-2 rounded-full",asChild:!0,children:e.jsxs(nr,{to:`/admin/academy?edit=${c.id}`,children:[e.jsx(ui,{className:"h-4 w-4"}),e.jsx("span",{children:"Edit"})]})}),e.jsx(tV,{resourceType:"academy_video",resourceId:c.id,resourceTitle:c.title}),e.jsxs($,{variant:x?"default":"outline",className:"gap-2 w-fit",onClick:()=>g.mutate(),disabled:!t||g.isPending,children:[e.jsx(Ay,{className:`h-4 w-4 ${x?"fill-current":""}`}),u.length," ",u.length===1?"Like":"Likes"]})]})]}),c.description&&e.jsx("div",{className:"text-muted-foreground prose prose-sm max-w-none dark:prose-invert",dangerouslySetInnerHTML:{__html:c.description}})]}),c.resources&&c.resources.length>0&&e.jsx(we,{children:e.jsxs(De,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(ea,{className:"h-4 w-4"}),"Resources"]}),e.jsx("div",{className:"grid gap-2",children:c.resources.map(j=>e.jsxs("a",{href:j.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:y(j.file_type)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:j.title}),e.jsx("p",{className:"text-xs text-muted-foreground uppercase",children:j.file_type})]}),e.jsx(ji,{className:"h-4 w-4 text-muted-foreground"})]},j.id))})]})}),e.jsx(RIt,{resourceType:"academy_video",resourceId:c.id}),e.jsx(Pc,{}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 text-lg",children:[e.jsx(Vu,{className:"h-5 w-5"}),"Comments (",h.length,")"]}),t?e.jsxs("form",{onSubmit:_,className:"flex gap-2",children:[e.jsx(Ls,{placeholder:"Add a comment...",value:l,onChange:j=>o(j.target.value),className:"min-h-[80px] resize-none flex-1"}),e.jsx($,{type:"submit",size:"icon",className:"h-10 w-10",disabled:!l.trim()||m.isPending,children:e.jsx(Wr,{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(we,{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(j=>e.jsx(we,{children:e.jsx(De,{className:"pt-4 pb-4",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsx(Wa,{className:"h-10 w-10 flex-shrink-0",children:e.jsx(Ka,{className:"text-sm",children:v(j.user_name||"U")})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"font-medium",children:j.user_name}),e.jsx("span",{className:"text-sm text-muted-foreground",children:Zc(new Date(j.created_at),{addSuffix:!0})}),j.user_id===(t==null?void 0:t.id)&&e.jsx($,{variant:"ghost",size:"icon",className:"h-6 w-6 ml-auto",onClick:()=>p.mutate(j.id),children:e.jsx(Un,{className:"h-3 w-3 text-muted-foreground"})})]}),e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:j.content})]})]})})},j.id))})]})]})}):e.jsx(Xs,{title:"Academy",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(ia,{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($,{asChild:!0,className:"mt-4",children:e.jsx(nr,{to:"/academy",children:"Back to Academy"})})]})})},Z7="https://dashboard.relevelup.com",NFs=(s,t)=>{if(t==="bunny_stream"){let n=s.replace("iframe.mediadelivery.net","player.mediadelivery.net");return n.includes("?")||(n+="?autoplay=false&loop=false&muted=false&preload=true&responsive=true"),n}if(t==="youtube"){const n=s.match(/(?:youtube\.com\/(?:watch\?v=|embed\/)|youtu\.be\/)([a-zA-Z0-9_-]{11})/);if(n)return`https://www.youtube.com/embed/${n[1]}`}if(t==="vimeo"){const n=s.match(/vimeo\.com\/(?:video\/)?(\d+)/);if(n)return`https://player.vimeo.com/video/${n[1]}`}if(t==="loom"){const n=s.match(/loom\.com\/share\/([a-zA-Z0-9]+)/);if(n)return`https://www.loom.com/embed/${n[1]}`}return s},kFs=[{icon:mm,title:"100+ Training Videos",desc:"On-demand LevelUp Academy content covering lead gen, listings, buyer conversion, marketing, and more."},{icon:ix,title:"Marketing Studio & Tools",desc:"AI-powered marketing tools, listing videos, landing pages, and social content — done for you."},{icon:Xn,title:"Coaching & Community",desc:"Live coaching sessions, private community, and a network of top-performing agents."},{icon:ql,title:"Business Scorecard",desc:"Track your deals, GCI, and pipeline in one dashboard built for real estate."}];function SFs(){var i;const{slug:s}=oo(),{data:t,isLoading:n,error:r}=pt({queryKey:["public-academy-video",s],queryFn:async()=>{if(!s)return null;const{data:l,error:o}=await V.from("academy_videos").select("id, title, description, video_url, video_type, thumbnail_url, duration, category:academy_categories(name)").eq("public_slug",s).eq("is_public",!0).maybeSingle();if(o)throw o;return l},enabled:!!s});k.useEffect(()=>{if(t&&s){V.rpc("increment_academy_public_view",{_slug:s}),document.title=`${t.title} | LevelUp Academy`;const l=(t.description||"").replace(/<[^>]+>/g,"").slice(0,155),o=document.querySelector('meta[name="description"]');if(o&&o.setAttribute("content",l||"Free training preview from LevelUp Academy."),t.thumbnail_url){let c=document.querySelector('meta[property="og:image"]');c||(c=document.createElement("meta"),c.setAttribute("property","og:image"),document.head.appendChild(c)),c.setAttribute("content",t.thumbnail_url)}}},[t,s]);const a=k.useMemo(()=>t?NFs(t.video_url,t.video_type):"",[t]);return n?e.jsx("div",{className:"min-h-screen bg-[#0d1b26] flex items-center justify-center",children:e.jsx("div",{className:"h-10 w-10 animate-spin rounded-full border-4 border-[#5a9ea1] border-t-transparent"})}):r||!t?e.jsxs("div",{className:"min-h-screen bg-[#0d1b26] flex flex-col items-center justify-center text-center px-6",children:[e.jsx("div",{className:"text-[#e8ecf1] text-2xl font-semibold mb-2",children:"This preview isn't available"}),e.jsx("p",{className:"text-[#8ba1b3] mb-6",children:"The link may have expired or is no longer public."}),e.jsx("a",{href:Z7,children:e.jsx($,{className:"bg-[#406E71] hover:bg-[#4d8285] text-white",children:"Go to LevelUp"})})]}):e.jsxs("div",{className:"min-h-screen bg-[#0a1520] text-[#e8ecf1] overflow-x-hidden",children:[e.jsxs("div",{className:"pointer-events-none fixed inset-0 z-0",children:[e.jsx("div",{className:"absolute -top-40 -left-40 w-[600px] h-[600px] rounded-full bg-[#406E71]/20 blur-3xl"}),e.jsx("div",{className:"absolute top-1/2 -right-40 w-[500px] h-[500px] rounded-full bg-[#2a4c64]/30 blur-3xl"}),e.jsx("div",{className:"absolute bottom-0 left-1/3 w-[400px] h-[400px] rounded-full bg-[#406E71]/10 blur-3xl"})]}),e.jsx("header",{className:"relative z-10 border-b border-white/5 backdrop-blur-sm bg-[#0a1520]/70",children:e.jsxs("div",{className:"max-w-7xl mx-auto px-6 py-5 flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-9 h-9 rounded-lg bg-gradient-to-br from-[#406E71] to-[#2a4c64] flex items-center justify-center",children:e.jsx(kn,{className:"w-5 h-5 text-white"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-bold text-lg tracking-tight",children:"LevelUp"}),e.jsx("div",{className:"text-[10px] uppercase tracking-widest text-[#5a9ea1] -mt-1",children:"Academy"})]})]}),e.jsx("a",{href:Z7,children:e.jsx($,{variant:"ghost",className:"text-[#e8ecf1] hover:bg-white/5 hover:text-white",children:"Sign In"})})]})}),e.jsxs("section",{className:"relative z-10 max-w-6xl mx-auto px-6 pt-12 pb-16",children:[e.jsxs("div",{className:"text-center mb-8 space-y-4",children:[e.jsxs(qe,{className:"bg-[#406E71]/20 text-[#7ec0c3] border-[#406E71]/40 hover:bg-[#406E71]/30",children:[e.jsx(mm,{className:"w-3 h-3 mr-1.5"}),"Free Training Preview"]}),((i=t.category)==null?void 0:i.name)&&e.jsx("div",{className:"text-xs uppercase tracking-[0.2em] text-[#5a9ea1]",children:t.category.name}),e.jsx("h1",{className:"text-3xl md:text-5xl lg:text-6xl font-bold tracking-tight leading-[1.1] max-w-4xl mx-auto",children:t.title}),t.duration&&e.jsx("div",{className:"text-[#8ba1b3] text-sm",children:t.duration})]}),e.jsxs("div",{className:"relative rounded-2xl overflow-hidden shadow-2xl ring-1 ring-white/10 bg-black",children:[e.jsx("div",{className:"absolute -inset-px rounded-2xl bg-gradient-to-r from-[#406E71]/50 via-transparent to-[#2a4c64]/50 blur-xl -z-10"}),e.jsx("div",{className:"aspect-video",children:e.jsx("iframe",{src:a,title:t.title,className:"w-full h-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0})})]}),t.description&&e.jsx("div",{className:"mt-10 max-w-3xl mx-auto text-[#c5d3de] text-lg leading-relaxed prose prose-invert prose-headings:text-white prose-a:text-[#7ec0c3]",dangerouslySetInnerHTML:{__html:t.description}})]}),e.jsx("section",{className:"relative z-10 max-w-4xl mx-auto px-6 pb-16",children:e.jsxs("div",{className:"relative rounded-3xl overflow-hidden p-10 md:p-14 text-center bg-gradient-to-br from-[#2a4c64] via-[#1d3a4f] to-[#0d1b26] ring-1 ring-white/10",children:[e.jsx("div",{className:"absolute top-0 right-0 w-64 h-64 bg-[#406E71]/30 rounded-full blur-3xl"}),e.jsxs("div",{className:"relative",children:[e.jsx(v0,{className:"w-10 h-10 mx-auto mb-4 text-[#7ec0c3]"}),e.jsxs("h2",{className:"text-3xl md:text-4xl font-bold mb-3",children:["This is just ",e.jsx("span",{className:"text-[#7ec0c3]",children:"one"})," of hundreds."]}),e.jsx("p",{className:"text-[#c5d3de] text-lg mb-8 max-w-2xl mx-auto",children:"LevelUp members get unlimited access to the full Academy, AI marketing tools, coaching, and everything you need to grow your real estate business."}),e.jsxs("div",{className:"flex flex-col sm:flex-row items-center justify-center gap-3",children:[e.jsx("a",{href:Z7,className:"w-full sm:w-auto",children:e.jsxs($,{size:"lg",className:"w-full sm:w-auto bg-[#f5f0e0] hover:bg-white text-[#0d1b26] font-semibold text-base h-12 px-8 shadow-xl",children:["Start Free Trial",e.jsx(xi,{className:"w-4 h-4 ml-2"})]})}),e.jsx("a",{href:Z7,className:"w-full sm:w-auto",children:e.jsx($,{size:"lg",variant:"outline",className:"w-full sm:w-auto bg-transparent border-white/20 text-white hover:bg-white/10 hover:text-white h-12 px-8",children:"Join LevelUp"})})]}),e.jsx("p",{className:"text-xs text-[#7a8a99] mt-5",children:"No credit card required to preview the platform"})]})]})}),e.jsxs("section",{className:"relative z-10 max-w-6xl mx-auto px-6 pb-20",children:[e.jsxs("div",{className:"text-center mb-10",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.25em] text-[#5a9ea1] mb-2",children:"What's inside"}),e.jsx("h3",{className:"text-2xl md:text-3xl font-bold",children:"Built for agents who want more"})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:kFs.map(l=>e.jsx("div",{className:"group relative rounded-2xl p-6 bg-white/[0.03] hover:bg-white/[0.06] ring-1 ring-white/5 hover:ring-[#406E71]/40 transition-all",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"shrink-0 w-11 h-11 rounded-xl bg-gradient-to-br from-[#406E71] to-[#2a4c64] flex items-center justify-center",children:e.jsx(l.icon,{className:"w-5 h-5 text-white"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-semibold text-white mb-1",children:l.title}),e.jsx("div",{className:"text-[#8ba1b3] text-sm leading-relaxed",children:l.desc})]})]})},l.title))})]}),e.jsx("section",{className:"relative z-10 max-w-4xl mx-auto px-6 pb-24",children:e.jsxs("div",{className:"rounded-2xl border border-white/10 p-8 md:p-10 bg-[#0d1b26]/60 backdrop-blur",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-center gap-x-8 gap-y-3 text-sm text-[#c5d3de] mb-6",children:[e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(Gr,{className:"w-4 h-4 text-[#7ec0c3]"})," Trusted by top producers"]}),e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(Gr,{className:"w-4 h-4 text-[#7ec0c3]"})," New training weekly"]}),e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(Gr,{className:"w-4 h-4 text-[#7ec0c3]"})," Cancel anytime"]})]}),e.jsx("div",{className:"text-center",children:e.jsx("a",{href:Z7,children:e.jsxs($,{size:"lg",className:"bg-[#406E71] hover:bg-[#4d8285] text-white h-12 px-10 shadow-lg",children:["Get Started at LevelUp",e.jsx(xi,{className:"w-4 h-4 ml-2"})]})})})]})}),e.jsxs("footer",{className:"relative z-10 border-t border-white/5 py-6 text-center text-xs text-[#5a6a7a]",children:["© ",new Date().getFullYear()," LevelUp · ",e.jsx("a",{href:Z7,className:"hover:text-[#7ec0c3]",children:"dashboard.relevelup.com"})]})]})}function CFs(){const s=Jn(),[t,n]=k.useState(""),{data:r,isLoading:a}=pt({queryKey:["resource-kits-published"],queryFn:async()=>{const{data:p,error:g}=await V.from("resource_kits").select("*").eq("is_published",!0).order("publish_date",{ascending:!1});if(g)throw g;return p}}),{data:i}=pt({queryKey:["resource-kit-files-all"],queryFn:async()=>{const{data:p,error:g}=await V.from("resource_kit_files").select("*").order("sort_order",{ascending:!0});if(g)throw g;return p}}),{data:l}=pt({queryKey:["resource-kit-likes-all"],queryFn:async()=>{const{data:p,error:g}=await V.from("resource_kit_likes").select("kit_id");if(g)throw g;return p}}),{data:o}=pt({queryKey:["resource-kit-comments-all"],queryFn:async()=>{const{data:p,error:g}=await V.from("resource_kit_comments").select("kit_id");if(g)throw g;return p}}),c=r==null?void 0:r.filter(p=>{var g;return p.name.toLowerCase().includes(t.toLowerCase())||((g=p.description)==null?void 0:g.toLowerCase().includes(t.toLowerCase()))}),d=p=>(i==null?void 0:i.filter(g=>g.kit_id===p))||[],u=p=>(l==null?void 0:l.filter(g=>g.kit_id===p).length)||0,h=p=>(o==null?void 0:o.filter(g=>g.kit_id===p).length)||0,m=p=>{s(`/toolbox/${p}`)};return e.jsx(Xs,{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(Yr,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search resource kits...",value:t,onChange:p=>n(p.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((p,g)=>e.jsx(we,{children:e.jsxs(De,{className:"p-4",children:[e.jsx(fn,{className:"aspect-[4/3] w-full rounded-lg mb-4"}),e.jsx(fn,{className:"h-5 w-3/4 mb-2"}),e.jsx(fn,{className:"h-4 w-full mb-4"}),e.jsx(fn,{className:"h-4 w-2/3"})]})},g))}):(c==null?void 0:c.length)===0?e.jsxs(we,{className:"p-12 text-center",children:[e.jsx(bh,{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(p=>{const g=d(p.id).length,x=u(p.id),y=h(p.id);return e.jsxs(we,{className:"group overflow-hidden cursor-pointer hover:shadow-lg transition-all duration-200",onClick:()=>m(p.id),children:[e.jsx("div",{className:"relative overflow-hidden bg-muted aspect-[3/2]",children:p.featured_image_url?e.jsx("img",{src:p.featured_image_url,alt:p.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(bh,{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:p.name}),p.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2 mb-3",children:IZ(p.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(ea,{className:"h-4 w-4"}),g," file",g!==1?"s":""]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ay,{className:"h-3.5 w-3.5"}),x]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Vu,{className:"h-3.5 w-3.5"}),y]})]})]})]})]},p.id)})})]})})}const AFs=()=>{const{kitId:s}=oo(),{user:t,isAdmin:n}=ks(),{toast:r}=Fi(),a=ls(),{trackEngagement:i}=Xq(),[l,o]=k.useState(""),{data:c,isLoading:d}=pt({queryKey:["resource-kit-detail",s],queryFn:async()=>{const{data:j,error:C}=await V.from("resource_kits").select("*").eq("id",s).eq("is_published",!0).single();if(C)throw C;const{data:A}=await V.from("resource_kit_files").select("*").eq("kit_id",s).order("sort_order"),{data:M}=await V.from("resource_kit_links").select("*").eq("kit_id",s).order("sort_order");return{...j,files:A||[],links:M||[]}},enabled:!!s});k.useEffect(()=>{c&&i("toolbox",c.id,c.name,"view")},[c==null?void 0:c.id]);const{data:u=[]}=pt({queryKey:["resource-kit-likes",s],queryFn:async()=>{const{data:j,error:C}=await V.from("resource_kit_likes").select("*").eq("kit_id",s);if(C)throw C;return j},enabled:!!s}),{data:h=[]}=pt({queryKey:["resource-kit-comments",s],queryFn:async()=>{const{data:j,error:C}=await V.from("resource_kit_comments").select("*").eq("kit_id",s).order("created_at",{ascending:!1});if(C)throw C;const A=[...new Set(j.map(P=>P.user_id))],{data:M}=await V.from("profiles").select("id, name").in("id",A),I=new Map((M==null?void 0:M.map(P=>[P.id,P.name]))||[]);return j.map(P=>({...P,user_name:I.get(P.user_id)||"Unknown User"}))},enabled:!!s}),m=Nt({mutationFn:async j=>{const{error:C}=await V.from("resource_kit_comments").insert({kit_id:s,user_id:t.id,content:j});if(C)throw C},onSuccess:()=>{a.invalidateQueries({queryKey:["resource-kit-comments",s]}),o(""),r({title:"Comment added!"})},onError:j=>{r({title:"Error adding comment",description:j.message,variant:"destructive"})}}),p=Nt({mutationFn:async j=>{const{error:C}=await V.from("resource_kit_comments").delete().eq("id",j);if(C)throw C},onSuccess:()=>{a.invalidateQueries({queryKey:["resource-kit-comments",s]}),r({title:"Comment deleted"})}}),g=Nt({mutationFn:async()=>{const j=u.find(C=>C.user_id===(t==null?void 0:t.id));if(j){const{error:C}=await V.from("resource_kit_likes").delete().eq("id",j.id);if(C)throw C}else{const{error:C}=await V.from("resource_kit_likes").insert({kit_id:s,user_id:t.id});if(C)throw C}},onSuccess:()=>{a.invalidateQueries({queryKey:["resource-kit-likes",s]})}}),x=u.some(j=>j.user_id===(t==null?void 0:t.id)),y=j=>j.split(" ").map(C=>C[0]).join("").toUpperCase().slice(0,2),v=j=>j?j<1024?j+" B":j<1024*1024?(j/1024).toFixed(1)+" KB":(j/(1024*1024)).toFixed(1)+" MB":"",_=j=>{j.preventDefault(),!(!l.trim()||!t)&&m.mutate(l.trim())};return d?e.jsx(Xs,{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(Xs,{title:c.name,children:e.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[e.jsx($,{variant:"ghost",size:"sm",asChild:!0,className:"gap-2",children:e.jsxs(nr,{to:"/toolbox",children:[e.jsx(Ia,{className:"h-4 w-4"}),"Back to Toolbox"]})}),c.featured_image_url&&e.jsx("div",{className:"relative w-full rounded-lg overflow-hidden bg-muted",children:e.jsx("img",{src:c.featured_image_url,alt:c.name,className:"w-full max-h-[400px] object-cover"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-start sm:justify-between gap-4",children:[e.jsx("div",{className:"space-y-2",children:e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:c.name})}),e.jsxs("div",{className:"flex items-center gap-2",children:[n&&e.jsx($,{variant:"outline",className:"gap-2 rounded-full",asChild:!0,children:e.jsxs(nr,{to:`/admin/toolbox?edit=${c.id}`,children:[e.jsx(ui,{className:"h-4 w-4"}),e.jsx("span",{children:"Edit"})]})}),e.jsx(tV,{resourceType:"resource_kit",resourceId:c.id,resourceTitle:c.name,size:"default",className:"rounded-full"}),e.jsxs($,{variant:x?"default":"outline",className:"gap-2 rounded-full",onClick:()=>g.mutate(),disabled:!t||g.isPending,children:[e.jsx(Ay,{className:`h-4 w-4 ${x?"fill-current":""}`}),u.length," ",u.length===1?"Like":"Likes"]})]})]}),c.description&&e.jsx("div",{className:"text-muted-foreground prose prose-sm max-w-none dark:prose-invert",dangerouslySetInnerHTML:{__html:c.description}})]}),c.files&&c.files.length>0&&e.jsx(we,{children:e.jsxs(De,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(ea,{className:"h-4 w-4"}),"Included Resources (",c.files.length,")"]}),e.jsx("div",{className:"grid gap-2",children:c.files.map(j=>e.jsxs("a",{href:j.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(ea,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-sm",children:j.name}),j.file_size&&e.jsx("div",{className:"text-xs text-muted-foreground",children:v(j.file_size)})]})]}),e.jsx(ji,{className:"h-4 w-4 text-muted-foreground group-hover:text-primary transition-colors"})]},j.id))})]})}),c.links&&c.links.length>0&&e.jsx(we,{children:e.jsxs(De,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(Ir,{className:"h-4 w-4"}),"Canva Templates (",c.links.length,")"]}),e.jsx("div",{className:"grid gap-2",children:c.links.map(j=>e.jsxs("a",{href:j.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(Ir,{className:"h-4 w-4 text-purple-600"})}),e.jsx("div",{className:"font-medium text-sm",children:j.title})]}),e.jsx("span",{className:"text-xs text-muted-foreground group-hover:text-primary transition-colors",children:"Open in Canva"})]},j.id))})]})}),e.jsx(RIt,{resourceType:"resource_kit",resourceId:c.id}),e.jsx(Pc,{}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 text-lg",children:[e.jsx(Vu,{className:"h-5 w-5"}),"Comments (",h.length,")"]}),t?e.jsxs("form",{onSubmit:_,className:"flex gap-2",children:[e.jsx(Ls,{placeholder:"Add a comment...",value:l,onChange:j=>o(j.target.value),className:"min-h-[80px] resize-none flex-1"}),e.jsx($,{type:"submit",size:"icon",className:"h-10 w-10",disabled:!l.trim()||m.isPending,children:e.jsx(Wr,{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(we,{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(j=>e.jsx(we,{children:e.jsx(De,{className:"pt-4 pb-4",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsx(Wa,{className:"h-10 w-10 flex-shrink-0",children:e.jsx(Ka,{className:"text-sm",children:y(j.user_name||"U")})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"font-medium",children:j.user_name}),e.jsx("span",{className:"text-sm text-muted-foreground",children:Zc(new Date(j.created_at),{addSuffix:!0})}),j.user_id===(t==null?void 0:t.id)&&e.jsx($,{variant:"ghost",size:"icon",className:"h-6 w-6 ml-auto",onClick:()=>p.mutate(j.id),children:e.jsx(Un,{className:"h-3 w-3 text-muted-foreground"})})]}),e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:j.content})]})]})})},j.id))})]})]})}):e.jsx(Xs,{title:"Toolbox",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(bh,{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($,{asChild:!0,className:"mt-4",children:e.jsx(nr,{to:"/toolbox",children:"Back to Toolbox"})})]})})},EFs=()=>{const s=Jn(),[t,n]=k.useState(""),[r,a]=k.useState("grid"),{data:i=[],isLoading:l}=pt({queryKey:["social-swag"],queryFn:async()=>{const{data:d,error:u}=await V.from("social_swag").select("*").eq("is_published",!0).order("publish_date",{ascending:!1});if(u)throw u;const{data:h,error:m}=await V.from("social_swag_links").select("*").order("sort_order");if(m)throw m;const{data:p}=await V.from("social_swag_likes").select("swag_id"),{data:g}=await V.from("social_swag_comments").select("swag_id"),x=new Map;p==null||p.forEach(_=>{x.set(_.swag_id,(x.get(_.swag_id)||0)+1)});const y=new Map;return g==null||g.forEach(_=>{y.set(_.swag_id,(y.get(_.swag_id)||0)+1)}),(d||[]).map(_=>({..._,links:(h||[]).filter(j=>j.swag_id===_.id)||[],likesCount:x.get(_.id)||0,commentsCount:y.get(_.id)||0}))}}),o=i.filter(d=>{var h;return d.title.toLowerCase().includes(t.toLowerCase())||((h=d.description)==null?void 0:h.toLowerCase().includes(t.toLowerCase()))}),c=d=>{s(`/social-swag/${d}`)};return e.jsx(Xs,{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(Yr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search social swag...",value:t,onChange:d=>n(d.target.value),className:"pl-9"})]}),e.jsxs("div",{className:"flex gap-2",children:[t&&e.jsx($,{variant:"outline",size:"sm",onClick:()=>n(""),children:"Clear"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx($,{variant:r==="grid"?"secondary":"outline",size:"icon",onClick:()=>a("grid"),className:"rounded-full",children:e.jsx(y0,{className:"h-4 w-4"})}),e.jsx($,{variant:r==="list"?"secondary":"outline",size:"icon",onClick:()=>a("list"),className:"rounded-full",children:e.jsx(Sy,{className:"h-4 w-4"})})]})]})]}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[o.length," item",o.length!==1?"s":""," found"]}),l&&e.jsx("div",{className:r==="grid"?"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6":"space-y-4",children:[...Array(8)].map((d,u)=>e.jsx(we,{children:e.jsxs(De,{className:"p-4",children:[e.jsx(fn,{className:"aspect-[4/3] w-full rounded-lg mb-4"}),e.jsx(fn,{className:"h-5 w-3/4 mb-2"}),e.jsx(fn,{className:"h-4 w-full mb-4"})]})},u))}),!l&&o.length===0&&e.jsxs("div",{className:"text-center py-12",children:[e.jsx("div",{className:"text-muted-foreground mb-4",children:t?"No items match your search":"No social swag available yet"}),t&&e.jsx($,{variant:"outline",onClick:()=>n(""),children:"Clear Search"})]}),!l&&o.length>0&&e.jsx("div",{className:r==="grid"?"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6":"space-y-4",children:o.map(d=>e.jsxs(we,{className:`group overflow-hidden hover:shadow-lg transition-all duration-200 cursor-pointer ${r==="list"?"flex flex-row":""}`,onClick:()=>c(d.id),children:[e.jsxs("div",{className:`relative overflow-hidden bg-muted ${r==="list"?"w-48 shrink-0":"aspect-[3/2]"}`,children:[d.preview_image_url?e.jsx("img",{src:d.preview_image_url,alt:d.title,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center text-muted-foreground",children:"No Preview"}),d.links.length>1&&e.jsx("div",{className:"absolute top-2 right-2",children:e.jsxs(qe,{variant:"secondary",className:"gap-1 bg-background/90 backdrop-blur-sm",children:[e.jsx(od,{className:"h-3 w-3"}),d.links.length]})})]}),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: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(Ay,{className:"h-3.5 w-3.5"}),d.likesCount]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Vu,{className:"h-3.5 w-3.5"}),d.commentsCount]})]}),e.jsxs($,{size:"sm",className:"w-full gap-2",onClick:u=>{u.stopPropagation(),c(d.id)},children:[e.jsx(Ir,{className:"h-4 w-4"}),"View Details"]})]})]},d.id))})]})})};var Xl=function(){return Xl=Object.assign||function(t){for(var n,r=1,a=arguments.length;r1&&(c||!d),h=t>1&&(d||!c),m=function(){r&&i(r)},p=function(){a&&i(a)};return e.jsx(l7s,{displayMonth:s.displayMonth,hideNext:u,hidePrevious:h,nextMonth:a,previousMonth:r,onPreviousClick:m,onNextClick:p})}function c7s(s){var t,n=Vm(),r=n.classNames,a=n.disableNavigation,i=n.styles,l=n.captionLayout,o=n.components,c=(t=o==null?void 0:o.CaptionLabel)!==null&&t!==void 0?t:FIt,d;return a?d=e.jsx(c,{id:s.id,displayMonth:s.displayMonth}):l==="dropdown"?d=e.jsx(Gut,{displayMonth:s.displayMonth,id:s.id}):l==="dropdown-buttons"?d=e.jsxs(e.Fragment,{children:[e.jsx(Gut,{displayMonth:s.displayMonth,displayIndex:s.displayIndex,id:s.id}),e.jsx(Wut,{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(Wut,{displayMonth:s.displayMonth,id:s.id})]}),e.jsx("div",{className:r.caption,style:i.caption,children:d})}function d7s(s){var t=Vm(),n=t.footer,r=t.styles,a=t.classNames.tfoot;return n?e.jsx("tfoot",{className:a,style:r.tfoot,children:e.jsx("tr",{children:e.jsx("td",{colSpan:8,children:n})})}):e.jsx(e.Fragment,{})}function u7s(s,t,n){for(var r=n?U3(new Date):My(new Date,{locale:s,weekStartsOn:t}),a=[],i=0;i<7;i++){var l=wu(r,i);a.push(l)}return a}function h7s(){var s=Vm(),t=s.classNames,n=s.styles,r=s.showWeekNumber,a=s.locale,i=s.weekStartsOn,l=s.ISOWeek,o=s.formatters.formatWeekdayName,c=s.labels.labelWeekday,d=u7s(a,i,l);return e.jsxs("tr",{style:n.head_row,className:t.head_row,children:[r&&e.jsx("td",{style:n.head_cell,className:t.head_cell}),d.map(function(u,h){return e.jsx("th",{scope:"col",className:t.head_cell,style:n.head_cell,"aria-label":c(u,{locale:a}),children:o(u,{locale:a})},h)})]})}function m7s(){var s,t=Vm(),n=t.classNames,r=t.styles,a=t.components,i=(s=a==null?void 0:a.HeadRow)!==null&&s!==void 0?s:h7s;return e.jsx("thead",{style:r.head,className:n.head,children:e.jsx(i,{})})}function f7s(s){var t=Vm(),n=t.locale,r=t.formatters.formatDay;return e.jsx(e.Fragment,{children:r(s.date,{locale:n})})}var jKe=k.createContext(void 0);function p7s(s){if(!Oee(s.initialProps)){var t={selected:void 0,modifiers:{disabled:[]}};return e.jsx(jKe.Provider,{value:t,children:s.children})}return e.jsx(g7s,{initialProps:s.initialProps,children:s.children})}function g7s(s){var t=s.initialProps,n=s.children,r=t.selected,a=t.min,i=t.max,l=function(d,u,h){var m,p;(m=t.onDayClick)===null||m===void 0||m.call(t,d,u,h);var g=!!(u.selected&&a&&(r==null?void 0:r.length)===a);if(!g){var x=!!(!u.selected&&i&&(r==null?void 0:r.length)===i);if(!x){var y=r?DIt([],r):[];if(u.selected){var v=y.findIndex(function(_){return ah(d,_)});y.splice(v,1)}else y.push(d);(p=t.onSelect)===null||p===void 0||p.call(t,y,d,u,h)}}},o={disabled:[]};r&&o.disabled.push(function(d){var u=i&&r.length>i-1,h=r.some(function(m){return ah(m,d)});return!!(u&&!h)});var c={selected:r,onDayClick:l,modifiers:o};return e.jsx(jKe.Provider,{value:c,children:n})}function NKe(){var s=k.useContext(jKe);if(!s)throw new Error("useSelectMultiple must be used within a SelectMultipleProvider");return s}function x7s(s,t){var n=t||{},r=n.from,a=n.to;return r&&a?ah(a,s)&&ah(r,s)?void 0:ah(a,s)?{from:a,to:void 0}:ah(r,s)?void 0:N_(r,s)?{from:s,to:a}:{from:r,to:s}:a?N_(s,a)?{from:a,to:s}:{from:s,to:a}:r?Xw(s,r)?{from:s,to:r}:{from:r,to:s}:{from:s,to:void 0}}var kKe=k.createContext(void 0);function y7s(s){if(!Fee(s.initialProps)){var t={selected:void 0,modifiers:{range_start:[],range_end:[],range_middle:[],disabled:[]}};return e.jsx(kKe.Provider,{value:t,children:s.children})}return e.jsx(v7s,{initialProps:s.initialProps,children:s.children})}function v7s(s){var t=s.initialProps,n=s.children,r=t.selected,a=r||{},i=a.from,l=a.to,o=t.min,c=t.max,d=function(p,g,x){var y,v;(y=t.onDayClick)===null||y===void 0||y.call(t,p,g,x);var _=x7s(p,r);(v=t.onSelect)===null||v===void 0||v.call(t,_,p,g,x)},u={range_start:[],range_end:[],range_middle:[],disabled:[]};if(i?(u.range_start=[i],l?(u.range_end=[l],ah(i,l)||(u.range_middle=[{after:i,before:l}])):u.range_end=[i]):l&&(u.range_start=[l],u.range_end=[l]),o&&(i&&!l&&u.disabled.push({after:yY(i,o-1),before:wu(i,o-1)}),i&&l&&u.disabled.push({after:i,before:wu(i,o-1)}),!i&&l&&u.disabled.push({after:yY(l,o-1),before:wu(l,o-1)})),c){if(i&&!l&&(u.disabled.push({before:wu(i,-c+1)}),u.disabled.push({after:wu(i,c-1)})),i&&l){var h=o1(l,i)+1,m=c-h;u.disabled.push({before:yY(i,m)}),u.disabled.push({after:wu(l,m)})}!i&&l&&(u.disabled.push({before:wu(l,-c+1)}),u.disabled.push({after:wu(l,c-1)}))}return e.jsx(kKe.Provider,{value:{selected:r,onDayClick:d,modifiers:u},children:n})}function SKe(){var s=k.useContext(kKe);if(!s)throw new Error("useSelectRange must be used within a SelectRangeProvider");return s}function bNe(s){return Array.isArray(s)?DIt([],s):s!==void 0?[s]:[]}function b7s(s){var t={};return Object.entries(s).forEach(function(n){var r=n[0],a=n[1];t[r]=bNe(a)}),t}var vk;(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"})(vk||(vk={}));var _7s=vk.Selected,Y4=vk.Disabled,w7s=vk.Hidden,j7s=vk.Today,OLe=vk.RangeEnd,FLe=vk.RangeMiddle,zLe=vk.RangeStart,N7s=vk.Outside;function k7s(s,t,n){var r,a=(r={},r[_7s]=bNe(s.selected),r[Y4]=bNe(s.disabled),r[w7s]=bNe(s.hidden),r[j7s]=[s.today],r[OLe]=[],r[FLe]=[],r[zLe]=[],r[N7s]=[],r);return s.fromDate&&a[Y4].push({before:s.fromDate}),s.toDate&&a[Y4].push({after:s.toDate}),Oee(s)?a[Y4]=a[Y4].concat(t.modifiers[Y4]):Fee(s)&&(a[Y4]=a[Y4].concat(n.modifiers[Y4]),a[zLe]=n.modifiers[zLe],a[FLe]=n.modifiers[FLe],a[OLe]=n.modifiers[OLe]),a}var $It=k.createContext(void 0);function S7s(s){var t=Vm(),n=NKe(),r=SKe(),a=k7s(t,n,r),i=b7s(t.modifiers),l=Xl(Xl({},a),i);return e.jsx($It.Provider,{value:l,children:s.children})}function UIt(){var s=k.useContext($It);if(!s)throw new Error("useModifiers must be used within a ModifiersProvider");return s}function C7s(s){return!!(s&&typeof s=="object"&&"before"in s&&"after"in s)}function A7s(s){return!!(s&&typeof s=="object"&&"from"in s)}function E7s(s){return!!(s&&typeof s=="object"&&"after"in s)}function T7s(s){return!!(s&&typeof s=="object"&&"before"in s)}function M7s(s){return!!(s&&typeof s=="object"&&"dayOfWeek"in s)}function P7s(s,t){var n,r=t.from,a=t.to;if(r&&a){var i=o1(a,r)<0;i&&(n=[a,r],r=n[0],a=n[1]);var l=o1(s,r)>=0&&o1(a,s)>=0;return l}return a?ah(a,s):r?ah(r,s):!1}function I7s(s){return nGe(s)}function L7s(s){return Array.isArray(s)&&s.every(nGe)}function R7s(s,t){return t.some(function(n){if(typeof n=="boolean")return n;if(I7s(n))return ah(s,n);if(L7s(n))return n.includes(s);if(A7s(n))return P7s(s,n);if(M7s(n))return n.dayOfWeek.includes(s.getDay());if(C7s(n)){var r=o1(n.before,s),a=o1(n.after,s),i=r>0,l=a<0,o=N_(n.before,n.after);return o?l&&i:i||l}return E7s(n)?o1(s,n.after)>0:T7s(n)?o1(n.before,s)>0:typeof n=="function"?n(s):!1})}function CKe(s,t,n){var r=Object.keys(t).reduce(function(i,l){var o=t[l];return R7s(s,o)&&i.push(l),i},[]),a={};return r.forEach(function(i){return a[i]=!0}),n&&!Vq(s,n)&&(a.outside=!0),a}function D7s(s,t){for(var n=Ih(s[0]),r=eb(s[s.length-1]),a,i,l=n;l<=r;){var o=CKe(l,t),c=!o.disabled&&!o.hidden;if(!c){l=wu(l,1);continue}if(o.selected)return l;o.today&&!i&&(i=l),a||(a=l),l=wu(l,1)}return i||a}var O7s=365;function qIt(s,t){var n=t.moveBy,r=t.direction,a=t.context,i=t.modifiers,l=t.retry,o=l===void 0?{count:0,lastFocused:s}:l,c=a.weekStartsOn,d=a.fromDate,u=a.toDate,h=a.locale,m={day:wu,week:a3,month:Ux,year:Q0s,startOfWeek:function(y){return a.ISOWeek?U3(y):My(y,{locale:h,weekStartsOn:c})},endOfWeek:function(y){return a.ISOWeek?G3t(y):wU(y,{locale:h,weekStartsOn:c})}},p=m[n](s,r==="after"?1:-1);r==="before"&&d?p=J0s([d,p]):r==="after"&&u&&(p=evs([u,p]));var g=!0;if(i){var x=CKe(p,i);g=!x.disabled&&!x.hidden}return g?p:o.count>O7s?o.lastFocused:qIt(p,{moveBy:n,direction:r,context:a,modifiers:i,retry:Xl(Xl({},o),{count:o.count+1})})}var VIt=k.createContext(void 0);function F7s(s){var t=zee(),n=UIt(),r=k.useState(),a=r[0],i=r[1],l=k.useState(),o=l[0],c=l[1],d=D7s(t.displayMonths,n),u=a??(o&&t.isDateDisplayed(o))?o:d,h=function(){c(a),i(void 0)},m=function(y){i(y)},p=Vm(),g=function(y,v){if(a){var _=qIt(a,{moveBy:y,direction:v,context:p,modifiers:n});ah(a,_)||(t.goToDate(_,a),m(_))}},x={focusedDay:a,focusTarget:u,blur:h,focus:m,focusDayAfter:function(){return g("day","after")},focusDayBefore:function(){return g("day","before")},focusWeekAfter:function(){return g("week","after")},focusWeekBefore:function(){return g("week","before")},focusMonthBefore:function(){return g("month","before")},focusMonthAfter:function(){return g("month","after")},focusYearBefore:function(){return g("year","before")},focusYearAfter:function(){return g("year","after")},focusStartOfWeek:function(){return g("startOfWeek","before")},focusEndOfWeek:function(){return g("endOfWeek","after")}};return e.jsx(VIt.Provider,{value:x,children:s.children})}function AKe(){var s=k.useContext(VIt);if(!s)throw new Error("useFocusContext must be used within a FocusProvider");return s}function z7s(s,t){var n=UIt(),r=CKe(s,n,t);return r}var EKe=k.createContext(void 0);function B7s(s){if(!zAe(s.initialProps)){var t={selected:void 0};return e.jsx(EKe.Provider,{value:t,children:s.children})}return e.jsx($7s,{initialProps:s.initialProps,children:s.children})}function $7s(s){var t=s.initialProps,n=s.children,r=function(i,l,o){var c,d,u;if((c=t.onDayClick)===null||c===void 0||c.call(t,i,l,o),l.selected&&!t.required){(d=t.onSelect)===null||d===void 0||d.call(t,void 0,i,l,o);return}(u=t.onSelect)===null||u===void 0||u.call(t,i,i,l,o)},a={selected:t.selected,onDayClick:r};return e.jsx(EKe.Provider,{value:a,children:n})}function HIt(){var s=k.useContext(EKe);if(!s)throw new Error("useSelectSingle must be used within a SelectSingleProvider");return s}function U7s(s,t){var n=Vm(),r=HIt(),a=NKe(),i=SKe(),l=AKe(),o=l.focusDayAfter,c=l.focusDayBefore,d=l.focusWeekAfter,u=l.focusWeekBefore,h=l.blur,m=l.focus,p=l.focusMonthBefore,g=l.focusMonthAfter,x=l.focusYearBefore,y=l.focusYearAfter,v=l.focusStartOfWeek,_=l.focusEndOfWeek,j=function(ee){var oe,me,Q,te;zAe(n)?(oe=r.onDayClick)===null||oe===void 0||oe.call(r,s,t,ee):Oee(n)?(me=a.onDayClick)===null||me===void 0||me.call(a,s,t,ee):Fee(n)?(Q=i.onDayClick)===null||Q===void 0||Q.call(i,s,t,ee):(te=n.onDayClick)===null||te===void 0||te.call(n,s,t,ee)},C=function(ee){var oe;m(s),(oe=n.onDayFocus)===null||oe===void 0||oe.call(n,s,t,ee)},A=function(ee){var oe;h(),(oe=n.onDayBlur)===null||oe===void 0||oe.call(n,s,t,ee)},M=function(ee){var oe;(oe=n.onDayMouseEnter)===null||oe===void 0||oe.call(n,s,t,ee)},I=function(ee){var oe;(oe=n.onDayMouseLeave)===null||oe===void 0||oe.call(n,s,t,ee)},P=function(ee){var oe;(oe=n.onDayPointerEnter)===null||oe===void 0||oe.call(n,s,t,ee)},R=function(ee){var oe;(oe=n.onDayPointerLeave)===null||oe===void 0||oe.call(n,s,t,ee)},O=function(ee){var oe;(oe=n.onDayTouchCancel)===null||oe===void 0||oe.call(n,s,t,ee)},B=function(ee){var oe;(oe=n.onDayTouchEnd)===null||oe===void 0||oe.call(n,s,t,ee)},U=function(ee){var oe;(oe=n.onDayTouchMove)===null||oe===void 0||oe.call(n,s,t,ee)},G=function(ee){var oe;(oe=n.onDayTouchStart)===null||oe===void 0||oe.call(n,s,t,ee)},H=function(ee){var oe;(oe=n.onDayKeyUp)===null||oe===void 0||oe.call(n,s,t,ee)},Y=function(ee){var oe;switch(ee.key){case"ArrowLeft":ee.preventDefault(),ee.stopPropagation(),n.dir==="rtl"?o():c();break;case"ArrowRight":ee.preventDefault(),ee.stopPropagation(),n.dir==="rtl"?c():o();break;case"ArrowDown":ee.preventDefault(),ee.stopPropagation(),d();break;case"ArrowUp":ee.preventDefault(),ee.stopPropagation(),u();break;case"PageUp":ee.preventDefault(),ee.stopPropagation(),ee.shiftKey?x():p();break;case"PageDown":ee.preventDefault(),ee.stopPropagation(),ee.shiftKey?y():g();break;case"Home":ee.preventDefault(),ee.stopPropagation(),v();break;case"End":ee.preventDefault(),ee.stopPropagation(),_();break}(oe=n.onDayKeyDown)===null||oe===void 0||oe.call(n,s,t,ee)},se={onClick:j,onFocus:C,onBlur:A,onKeyDown:Y,onKeyUp:H,onMouseEnter:M,onMouseLeave:I,onPointerEnter:P,onPointerLeave:R,onTouchCancel:O,onTouchEnd:B,onTouchMove:U,onTouchStart:G};return se}function q7s(){var s=Vm(),t=HIt(),n=NKe(),r=SKe(),a=zAe(s)?t.selected:Oee(s)?n.selected:Fee(s)?r.selected:void 0;return a}function V7s(s){return Object.values(vk).includes(s)}function H7s(s,t){var n=[s.classNames.day];return Object.keys(t).forEach(function(r){var a=s.modifiersClassNames[r];if(a)n.push(a);else if(V7s(r)){var i=s.classNames["day_".concat(r)];i&&n.push(i)}}),n}function G7s(s,t){var n=Xl({},s.styles.day);return Object.keys(t).forEach(function(r){var a;n=Xl(Xl({},n),(a=s.modifiersStyles)===null||a===void 0?void 0:a[r])}),n}function W7s(s,t,n){var r,a,i,l=Vm(),o=AKe(),c=z7s(s,t),d=U7s(s,c),u=q7s(),h=!!(l.onDayClick||l.mode!=="default");k.useEffect(function(){var M;c.outside||o.focusedDay&&h&&ah(o.focusedDay,s)&&((M=n.current)===null||M===void 0||M.focus())},[o.focusedDay,s,n,h,c.outside]);var m=H7s(l,c).join(" "),p=G7s(l,c),g=!!(c.outside&&!l.showOutsideDays||c.hidden),x=(i=(a=l.components)===null||a===void 0?void 0:a.DayContent)!==null&&i!==void 0?i:f7s,y=e.jsx(x,{date:s,displayMonth:t,activeModifiers:c}),v={style:p,className:m,children:y,role:"gridcell"},_=o.focusTarget&&ah(o.focusTarget,s)&&!c.outside,j=o.focusedDay&&ah(o.focusedDay,s),C=Xl(Xl(Xl({},v),(r={disabled:c.disabled,role:"gridcell"},r["aria-selected"]=c.selected,r.tabIndex=j||_?0:-1,r)),d),A={isButton:h,isHidden:g,activeModifiers:c,selectedDays:u,buttonProps:C,divProps:v};return A}function K7s(s){var t=k.useRef(null),n=W7s(s.date,s.displayMonth,t);return n.isHidden?e.jsx("div",{role:"gridcell"}):n.isButton?e.jsx(f5e,Xl({name:"day",ref:t},n.buttonProps)):e.jsx("div",Xl({},n.divProps))}function Y7s(s){var t=s.number,n=s.dates,r=Vm(),a=r.onWeekNumberClick,i=r.styles,l=r.classNames,o=r.locale,c=r.labels.labelWeekNumber,d=r.formatters.formatWeekNumber,u=d(Number(t),{locale:o});if(!a)return e.jsx("span",{className:l.weeknumber,style:i.weeknumber,children:u});var h=c(Number(t),{locale:o}),m=function(p){a(t,n,p)};return e.jsx(f5e,{name:"week-number","aria-label":h,className:l.weeknumber,style:i.weeknumber,onClick:m,children:u})}function Z7s(s){var t,n,r=Vm(),a=r.styles,i=r.classNames,l=r.showWeekNumber,o=r.components,c=(t=o==null?void 0:o.Day)!==null&&t!==void 0?t:K7s,d=(n=o==null?void 0:o.WeekNumber)!==null&&n!==void 0?n:Y7s,u;return l&&(u=e.jsx("td",{className:i.cell,style:a.cell,children:e.jsx(d,{number:s.weekNumber,dates:s.dates})})),e.jsxs("tr",{className:i.row,style:a.row,children:[u,s.dates.map(function(h){return e.jsx("td",{className:i.cell,style:a.cell,role:"presentation",children:e.jsx(c,{displayMonth:s.displayMonth,date:h})},n1s(h))})]})}function Kut(s,t,n){for(var r=n!=null&&n.ISOWeek?G3t(t):wU(t,n),a=n!=null&&n.ISOWeek?U3(s):My(s,n),i=o1(r,a),l=[],o=0;o<=i;o++)l.push(wu(a,o));var c=l.reduce(function(d,u){var h=n!=null&&n.ISOWeek?rGe(u):iGe(u,n),m=d.find(function(p){return p.weekNumber===h});return m?(m.dates.push(u),d):(d.push({weekNumber:h,dates:[u]}),d)},[]);return c}function X7s(s,t){var n=Kut(Ih(s),eb(s),t);if(t!=null&&t.useFixedWeeks){var r=a1s(s,t);if(r<6){var a=n[n.length-1],i=a.dates[a.dates.length-1],l=a3(i,6-r),o=Kut(a3(i,1),l,t);n.push.apply(n,o)}}return n}function Q7s(s){var t,n,r,a=Vm(),i=a.locale,l=a.classNames,o=a.styles,c=a.hideHead,d=a.fixedWeeks,u=a.components,h=a.weekStartsOn,m=a.firstWeekContainsDate,p=a.ISOWeek,g=X7s(s.displayMonth,{useFixedWeeks:!!d,ISOWeek:p,locale:i,weekStartsOn:h,firstWeekContainsDate:m}),x=(t=u==null?void 0:u.Head)!==null&&t!==void 0?t:m7s,y=(n=u==null?void 0:u.Row)!==null&&n!==void 0?n:Z7s,v=(r=u==null?void 0:u.Footer)!==null&&r!==void 0?r:d7s;return e.jsxs("table",{id:s.id,className:l.table,style:o.table,role:"grid","aria-labelledby":s["aria-labelledby"],children:[!c&&e.jsx(x,{}),e.jsx("tbody",{className:l.tbody,style:o.tbody,children:g.map(function(_){return e.jsx(y,{displayMonth:s.displayMonth,dates:_.dates,weekNumber:_.weekNumber},_.weekNumber)})}),e.jsx(v,{displayMonth:s.displayMonth})]})}function J7s(){return!!(typeof window<"u"&&window.document&&window.document.createElement)}var e9s=J7s()?k.useLayoutEffect:k.useEffect,BLe=!1,t9s=0;function Yut(){return"react-day-picker-".concat(++t9s)}function s9s(s){var t,n=s??(BLe?Yut():null),r=k.useState(n),a=r[0],i=r[1];return e9s(function(){a===null&&i(Yut())},[]),k.useEffect(function(){BLe===!1&&(BLe=!0)},[]),(t=s??a)!==null&&t!==void 0?t:void 0}function n9s(s){var t,n,r=Vm(),a=r.dir,i=r.classNames,l=r.styles,o=r.components,c=zee().displayMonths,d=s9s(r.id?"".concat(r.id,"-").concat(s.displayIndex):void 0),u=r.id?"".concat(r.id,"-grid-").concat(s.displayIndex):void 0,h=[i.month],m=l.month,p=s.displayIndex===0,g=s.displayIndex===c.length-1,x=!p&&!g;a==="rtl"&&(t=[p,g],g=t[0],p=t[1]),p&&(h.push(i.caption_start),m=Xl(Xl({},m),l.caption_start)),g&&(h.push(i.caption_end),m=Xl(Xl({},m),l.caption_end)),x&&(h.push(i.caption_between),m=Xl(Xl({},m),l.caption_between));var y=(n=o==null?void 0:o.Caption)!==null&&n!==void 0?n:c7s;return e.jsxs("div",{className:h.join(" "),style:m,children:[e.jsx(y,{id:d,displayMonth:s.displayMonth,displayIndex:s.displayIndex}),e.jsx(Q7s,{id:u,"aria-labelledby":d,displayMonth:s.displayMonth})]},s.displayIndex)}function r9s(s){var t=Vm(),n=t.classNames,r=t.styles;return e.jsx("div",{className:n.months,style:r.months,children:s.children})}function a9s(s){var t,n,r=s.initialProps,a=Vm(),i=AKe(),l=zee(),o=k.useState(!1),c=o[0],d=o[1];k.useEffect(function(){a.initialFocus&&i.focusTarget&&(c||(i.focus(i.focusTarget),d(!0)))},[a.initialFocus,c,i.focus,i.focusTarget,i]);var u=[a.classNames.root,a.className];a.numberOfMonths>1&&u.push(a.classNames.multiple_months),a.showWeekNumber&&u.push(a.classNames.with_weeknumber);var h=Xl(Xl({},a.styles.root),a.style),m=Object.keys(r).filter(function(g){return g.startsWith("data-")}).reduce(function(g,x){var y;return Xl(Xl({},g),(y={},y[x]=r[x],y))},{}),p=(n=(t=r.components)===null||t===void 0?void 0:t.Months)!==null&&n!==void 0?n:r9s;return e.jsx("div",Xl({className:u.join(" "),style:h,dir:a.dir,id:a.id,nonce:r.nonce,title:r.title,lang:r.lang},m,{children:e.jsx(p,{children:l.displayMonths.map(function(g,x){return e.jsx(n9s,{displayIndex:x,displayMonth:g},x)})})}))}function i9s(s){var t=s.children,n=TFs(s,["children"]);return e.jsx(YFs,{initialProps:n,children:e.jsx(a7s,{children:e.jsx(B7s,{initialProps:n,children:e.jsx(p7s,{initialProps:n,children:e.jsx(y7s,{initialProps:n,children:e.jsx(S7s,{children:e.jsx(F7s,{children:t})})})})})})})}function o9s(s){return e.jsx(i9s,Xl({},s,{children:e.jsx(a9s,{initialProps:s})}))}function vb({className:s,classNames:t,showOutsideDays:n=!0,...r}){return e.jsx(o9s,{showOutsideDays:n,className:Ot("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:Ot(hU({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:Ot(hU({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(Ld,{className:"h-4 w-4"}),IconRight:({...a})=>e.jsx(fi,{className:"h-4 w-4"})},...r})}vb.displayName="Calendar";var l9s=Object.defineProperty,o6=(s,t)=>l9s(s,"name",{value:t,configurable:!0}),TKe="Popover",[GIt,QQn]=qm(TKe,[Q5]),MKe=Q5(),[c9s,sV]=GIt(TKe),d9s=o6(s=>{const{__scopePopover:t,children:n,open:r,defaultOpen:a,onOpenChange:i,modal:l=!1}=s,o=MKe(t),c=k.useRef(null),[d,u]=k.useState(!1),[h,m]=ox({prop:r,defaultProp:a??!1,onChange:i,caller:TKe});return e.jsx(ree,{...o,children:e.jsx(c9s,{scope:t,contentId:$x(),triggerRef:c,open:h,onOpenChange:m,onOpenToggle:k.useCallback(()=>m(p=>!p),[m]),hasCustomAnchor:d,onCustomAnchorAdd:k.useCallback(()=>u(!0),[]),onCustomAnchorRemove:k.useCallback(()=>u(!1),[]),modal:l,children:n})})},"Popover"),u9s="PopoverTrigger",h9s=k.forwardRef(o6(function(t,n){const{__scopePopover:r,...a}=t,i=sV(u9s,r),l=MKe(r),o=Ao(n,i.triggerRef),c=e.jsx(hi.button,{type:"button","aria-haspopup":"dialog","aria-expanded":i.open,"aria-controls":i.open?i.contentId:void 0,"data-state":PKe(i.open),...a,ref:o,onClick:ga(t.onClick,i.onOpenToggle)});return i.hasCustomAnchor?c:e.jsx(aee,{asChild:!0,...l,children:c})},"PopoverTrigger")),WIt="PopoverPortal",[m9s,f9s]=GIt(WIt,{forceMount:void 0}),p9s=o6(s=>{const{__scopePopover:t,forceMount:n,children:r,container:a}=s,i=sV(WIt,t);return e.jsx(m9s,{scope:t,forceMount:n,children:e.jsx(cx,{present:n||i.open,children:e.jsx(QJ,{asChild:!0,container:a,children:r})})})},"PopoverPortal"),yX="PopoverContent",g9s=k.forwardRef(o6(function(t,n){const r=f9s(yX,t.__scopePopover),{forceMount:a=r.forceMount,...i}=t,l=sV(yX,t.__scopePopover);return e.jsx(cx,{present:a||l.open,children:l.modal?e.jsx(y9s,{...i,ref:n}):e.jsx(v9s,{...i,ref:n})})},"PopoverContent")),x9s=xk("PopoverContent.RemoveScroll"),y9s=k.forwardRef(o6(function(t,n){const r=sV(yX,t.__scopePopover),a=k.useRef(null),i=Ao(n,a),l=k.useRef(!1);return k.useEffect(()=>{const o=a.current;if(o)return i3e(o)},[]),e.jsx(eee,{as:x9s,allowPinchZoom:!0,children:e.jsx(KIt,{...t,ref:i,trapFocus:r.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:ga(t.onCloseAutoFocus,o=>{var c;o.preventDefault(),l.current||(c=r.triggerRef.current)==null||c.focus()}),onPointerDownOutside:ga(t.onPointerDownOutside,o=>{const c=o.detail.originalEvent,d=c.button===0&&c.ctrlKey===!0,u=c.button===2||d;l.current=u},{checkForDefaultPrevented:!1}),onFocusOutside:ga(t.onFocusOutside,o=>o.preventDefault(),{checkForDefaultPrevented:!1})})})},"PopoverContentModal")),v9s=k.forwardRef(o6(function(t,n){const r=sV(yX,t.__scopePopover),a=k.useRef(!1),i=k.useRef(!1);return e.jsx(KIt,{...t,ref:n,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:l=>{var o,c;(o=t.onCloseAutoFocus)==null||o.call(t,l),l.defaultPrevented||(a.current||(c=r.triggerRef.current)==null||c.focus(),l.preventDefault()),a.current=!1,i.current=!1},onInteractOutside:l=>{var d,u;(d=t.onInteractOutside)==null||d.call(t,l),l.defaultPrevented||(a.current=!0,l.detail.originalEvent.type==="pointerdown"&&(i.current=!0));const o=l.target;((u=r.triggerRef.current)==null?void 0:u.contains(o))&&l.preventDefault(),l.detail.originalEvent.type==="focusin"&&i.current&&l.preventDefault()}})},"PopoverContentNonModal")),KIt=k.forwardRef(o6(function(t,n){const{__scopePopover:r,trapFocus:a,onOpenAutoFocus:i,onCloseAutoFocus:l,disableOutsidePointerEvents:o,onEscapeKeyDown:c,onPointerDownOutside:d,onFocusOutside:u,onInteractOutside:h,...m}=t,p=sV(yX,r),g=MKe(r);return Mq(),e.jsx(r3e,{asChild:!0,loop:!0,trapped:a,onMountAutoFocus:i,onUnmountAutoFocus:l,children:e.jsx(pF,{asChild:!0,disableOutsidePointerEvents:o,onInteractOutside:h,onEscapeKeyDown:c,onPointerDownOutside:d,onFocusOutside:u,onDismiss:()=>p.onOpenChange(!1),deferPointerDownOutside:!0,children:e.jsx(iee,{"data-state":PKe(p.open),role:"dialog",id:p.contentId,...g,...m,ref:n,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)"}})})})},"PopoverContentImpl"));function PKe(s){return s?"open":"closed"}o6(PKe,"getState");var b9s=d9s,_9s=h9s,w9s=p9s,YIt=g9s;const Xc=b9s,Qc=_9s,Bc=k.forwardRef(({className:s,align:t="center",sideOffset:n=4,...r},a)=>e.jsx(w9s,{children:e.jsx(YIt,{ref:a,align:t,sideOffset:n,className:Ot("z-50 w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",s),...r})}));Bc.displayName=YIt.displayName;async function ZIt(s){if(s instanceof J5t)try{const t=await s.context.text();try{const n=JSON.parse(t),r=(n==null?void 0:n.error)??(n==null?void 0:n.message);if(typeof r=="string"&&r.trim())return r}catch{if(t.trim())return t.trim()}}catch{}return s instanceof Error&&s.message?s.message:"Something went wrong. Please try again."}const j9s=gF("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"}}),IKe=k.forwardRef(({className:s,variant:t,...n},r)=>e.jsx("div",{ref:r,role:"alert",className:Ot(j9s({variant:t}),s),...n}));IKe.displayName="Alert";const N9s=k.forwardRef(({className:s,...t},n)=>e.jsx("h5",{ref:n,className:Ot("mb-1 font-medium leading-none tracking-tight",s),...t}));N9s.displayName="AlertTitle";const LKe=k.forwardRef(({className:s,...t},n)=>e.jsx("div",{ref:n,className:Ot("text-sm [&_p]:leading-relaxed",s),...t}));LKe.displayName="AlertDescription";function k9s({open:s,onOpenChange:t,imageUrl:n,imageId:r,defaultCaption:a="",swagItemId:i,reelId:l}){const o=ls(),{user:c}=ks(),d=(c==null?void 0:c.id)??null,[u,h]=k.useState(a),[m,p]=k.useState([]),[g,x]=k.useState(null),[y,v]=k.useState("now"),[_,j]=k.useState(Fot(Hot(new Date),1)),[C,A]=k.useState("12"),[M,I]=k.useState("00"),[P,R]=k.useState("PM");k.useEffect(()=>{if(s){h(a),v("now"),p([]);const ve=Fot(Hot(new Date),1);j(ve);const he=ve.getHours();A(String(he>12?he-12:he===0?12:he)),I("00"),R(he>=12?"PM":"AM")}},[s,a]);const O=()=>{if(!_)return null;let ve=parseInt(C);const he=parseInt(M);return P==="PM"&&ve!==12&&(ve+=12),P==="AM"&&ve===12&&(ve=0),sAt(tAt(_,ve),he)},{data:B,isLoading:U}=pt({queryKey:["social-accounts-for-post",d],queryFn:async()=>{const{data:{user:ve}}=await V.auth.getUser();if(!ve)return[];const{data:he,error:Se}=await V.from("social_accounts").select("*").eq("user_id",ve.id).eq("is_active",!0).order("platform",{ascending:!0});if(Se)throw Se;return console.log("Fetched social accounts for posting:",he),he},enabled:s,staleTime:0}),G=Nt({mutationFn:async({accountId:ve,platform:he})=>{x(ve);const{data:Se,error:Te}=await V.functions.invoke("social-post",{body:{platform:he,accountId:ve,imageUrl:n,caption:u}});if(Te)throw new Error(await ZIt(Te));if(Se!=null&&Se.error)throw new Error(Se.error);return Se},onSuccess:ve=>{const he=ve.platform==="facebook"?"Facebook":ve.platform==="instagram"?"Instagram":ve.platform==="linkedin"?"LinkedIn":"Google Business";ae.success(`Posted to ${he}!`)},onError:ve=>{ae.error(`Failed to post: ${ve.message}`)},onSettled:()=>{x(null)}}),H=Nt({mutationFn:async({accountId:ve,platform:he,scheduledFor:Se})=>{const{data:{user:Te}}=await V.auth.getUser();if(!Te)throw new Error("Not authenticated");const{error:Ie}=await V.from("scheduled_posts").insert({user_id:Te.id,social_account_id:ve,platform:he,image_url:n,caption:u,swag_item_id:i||null,reel_id:l||null,scheduled_for:Se.toISOString(),status:"scheduled"});if(Ie)throw Ie;return{platform:he}},onSuccess:ve=>{const he=ve.platform==="facebook"?"Facebook":ve.platform==="instagram"?"Instagram":"LinkedIn";ae.success(`Post scheduled for ${he}!`)},onError:ve=>{ae.error(`Failed to schedule: ${ve.message}`)}}),Y=async()=>{if(m.length===0){ae.error("Please select at least one account");return}if(y==="schedule"){const ve=O();if(!ve||ve<=new Date){ae.error("Please select a future date and time");return}for(const he of m){const Se=B==null?void 0:B.find(Te=>Te.id===he);Se&&await H.mutateAsync({accountId:he,platform:Se.platform,scheduledFor:ve})}o.invalidateQueries({queryKey:["scheduled-posts",d]}),ae.success(`${m.length} post(s) scheduled for ${Ys(ve,"PPp")}`)}else for(const ve of m){const he=B==null?void 0:B.find(Se=>Se.id===ve);he&&await G.mutateAsync({accountId:ve,platform:he.platform})}o.invalidateQueries({queryKey:["scheduled-posts",d]}),h(""),p([]),t(!1)},se=ve=>{p(he=>he.includes(ve)?he.filter(Se=>Se!==ve):[...he,ve])},ee=(B==null?void 0:B.filter(ve=>ve.platform==="facebook"))||[],oe=(B==null?void 0:B.filter(ve=>ve.platform==="instagram"))||[],me=(B==null?void 0:B.filter(ve=>ve.platform==="linkedin"))||[],Q=(B==null?void 0:B.filter(ve=>ve.platform==="google_business"))||[],te=((B==null?void 0:B.length)||0)>0,le=G.isPending||H.isPending,fe=Array.from({length:12},(ve,he)=>String(he+1)),_e=["00","15","30","45"];return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"sm:max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsxs(Vs,{children:[e.jsx($s,{children:"Create Social Post"}),e.jsx(Cr,{children:"Share this image to your connected social accounts"})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsx("div",{className:"aspect-square w-full max-w-[200px] mx-auto overflow-hidden rounded-lg border",children:e.jsx("img",{src:n,alt:"Post preview",className:"h-full w-full object-cover"})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"caption",children:"Caption"}),e.jsx(Ls,{id:"caption",placeholder:"Write a caption for your post...",value:u,onChange:ve=>h(ve.target.value),rows:3}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[u.length,"/2200 characters"]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(re,{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:()=>v("now"),className:Ot("flex-1 px-4 py-2 rounded-md text-sm font-medium transition-all",y==="now"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"),children:"Post Now"}),e.jsx("button",{type:"button",onClick:()=>v("schedule"),className:Ot("flex-1 px-4 py-2 rounded-md text-sm font-medium transition-all",y==="schedule"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"),children:"Schedule"})]})]}),y==="schedule"&&e.jsxs("div",{className:"space-y-3 p-4 border rounded-lg bg-muted/30",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium",children:[e.jsx(sa,{className:"h-4 w-4"}),"Schedule for"]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsxs(Xc,{children:[e.jsx(Qc,{asChild:!0,children:e.jsxs($,{variant:"outline",className:Ot("justify-start text-left font-normal flex-1",!_&&"text-muted-foreground"),children:[e.jsx(ha,{className:"mr-2 h-4 w-4"}),_?Ys(_,"PPP"):e.jsx("span",{children:"Pick a date"})]})}),e.jsx(Bc,{className:"w-auto p-0",align:"start",children:e.jsx(vb,{mode:"single",selected:_,onSelect:j,disabled:ve=>vee.jsx(We,{value:ve,children:ve},ve))})]}),e.jsx("span",{className:"text-muted-foreground",children:":"}),e.jsxs(bs,{value:M,onValueChange:I,children:[e.jsx(ys,{className:"w-[70px]",children:e.jsx(_s,{})}),e.jsx(vs,{children:_e.map(ve=>e.jsx(We,{value:ve,children:ve},ve))})]}),e.jsxs(bs,{value:P,onValueChange:ve=>R(ve),children:[e.jsx(ys,{className:"w-[70px]",children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"AM",children:"AM"}),e.jsx(We,{value:"PM",children:"PM"})]})]})]})]}),_&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Post will be published on ",Ys(O()||new Date,"PPP 'at' p")]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(re,{children:"Post to"}),U&&e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(Jt,{className:"h-6 w-6 animate-spin"})}),!U&&!te&&e.jsxs(IKe,{children:[e.jsx(Ho,{className:"h-4 w-4"}),e.jsxs(LKe,{className:"flex flex-col gap-2",children:[e.jsx("span",{children:"No social accounts connected yet."}),e.jsxs(nr,{to:"/social-connections",className:"inline-flex items-center gap-1.5 text-primary hover:underline font-medium",children:[e.jsx(Yc,{className:"h-3.5 w-3.5"}),"Connect your Facebook, Instagram & LinkedIn"]})]})]}),ee.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("p",{className:"text-sm font-medium text-muted-foreground flex items-center gap-2",children:[e.jsx(ax,{className:"h-4 w-4 text-blue-600"})," Facebook"]}),ee.map(ve=>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(Li,{checked:m.includes(ve.id),onCheckedChange:()=>se(ve.id),disabled:g===ve.id}),e.jsxs(Wa,{className:"h-8 w-8",children:[e.jsx(eo,{src:ve.profile_picture_url||""}),e.jsx(Ka,{children:e.jsx(ax,{className:"h-4 w-4"})})]}),e.jsx("span",{className:"flex-1 text-sm font-medium",children:ve.page_name||ve.platform_username}),g===ve.id&&e.jsx(Jt,{className:"h-4 w-4 animate-spin"})]},ve.id))]}),oe.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("p",{className:"text-sm font-medium text-muted-foreground flex items-center gap-2",children:[e.jsx(Sf,{className:"h-4 w-4 text-pink-600"})," Instagram"]}),oe.map(ve=>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(Li,{checked:m.includes(ve.id),onCheckedChange:()=>se(ve.id),disabled:g===ve.id}),e.jsxs(Wa,{className:"h-8 w-8",children:[e.jsx(eo,{src:ve.profile_picture_url||""}),e.jsx(Ka,{children:e.jsx(Sf,{className:"h-4 w-4"})})]}),e.jsxs("span",{className:"flex-1 text-sm font-medium",children:["@",ve.platform_username]}),g===ve.id&&e.jsx(Jt,{className:"h-4 w-4 animate-spin"})]},ve.id))]}),me.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(dv,{className:"h-4 w-4 text-blue-700"})," LinkedIn"]}),me.map(ve=>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(Li,{checked:m.includes(ve.id),onCheckedChange:()=>se(ve.id),disabled:g===ve.id}),e.jsxs(Wa,{className:"h-8 w-8",children:[e.jsx(eo,{src:ve.profile_picture_url||""}),e.jsx(Ka,{children:e.jsx(dv,{className:"h-4 w-4"})})]}),e.jsx("span",{className:"flex-1 text-sm font-medium",children:ve.platform_username}),g===ve.id&&e.jsx(Jt,{className:"h-4 w-4 animate-spin"})]},ve.id))]}),Q.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(Si,{className:"h-4 w-4 text-red-600"})," Google Business"]}),Q.map(ve=>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(Li,{checked:m.includes(ve.id),onCheckedChange:()=>se(ve.id),disabled:g===ve.id}),e.jsxs(Wa,{className:"h-8 w-8",children:[e.jsx(eo,{src:ve.profile_picture_url||""}),e.jsx(Ka,{children:e.jsx(Si,{className:"h-4 w-4"})})]}),e.jsx("span",{className:"flex-1 text-sm font-medium",children:ve.page_name||ve.platform_username}),g===ve.id&&e.jsx(Jt,{className:"h-4 w-4 animate-spin"})]},ve.id))]})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs($,{onClick:Y,disabled:m.length===0||le,className:"gap-2",children:[le?e.jsx(Jt,{className:"h-4 w-4 animate-spin"}):y==="schedule"?e.jsx(ha,{className:"h-4 w-4"}):e.jsx(Wr,{className:"h-4 w-4"}),y==="schedule"?`Schedule ${m.length} post${m.length!==1?"s":""}`:`Post to ${m.length} account${m.length!==1?"s":""}`]})]})]})})}function S9s(){const{user:s}=ks(),t=(s==null?void 0:s.id)??null,n=ls(),[r,a]=k.useState(void 0),[i,l]=k.useState("all"),[o,c]=k.useState(null),[d,u]=k.useState(""),[h,m]=k.useState(void 0),[p,g]=k.useState("12"),[x,y]=k.useState("00"),[v,_]=k.useState("PM"),{data:j=[],isLoading:C}=pt({queryKey:["scheduled-posts",t],enabled:!!t,queryFn:async()=>{const{data:Q,error:te}=await V.from("scheduled_posts").select(` *, social_accounts ( page_name, platform_username, profile_picture_url ) `).eq("user_id",t).order("scheduled_for",{ascending:!1});if(te)throw te;return Q}}),A=j.filter(Q=>{if(i!=="all"&&Q.status!==i)return!1;if(r&&Q.scheduled_for){const te=new Date(Q.scheduled_for);if(!ah(te,r))return!1}return!0}),M=j.filter(Q=>Q.scheduled_for).map(Q=>np(new Date(Q.scheduled_for))),I=Nt({mutationFn:async Q=>{const{error:te}=await V.from("scheduled_posts").update({caption:Q.caption,scheduled_for:Q.scheduled_for}).eq("id",Q.id);if(te)throw te},onSuccess:()=>{ae.success("Post updated!"),n.invalidateQueries({queryKey:["scheduled-posts",t]}),c(null)},onError:Q=>{ae.error(`Failed to update: ${Q.message}`)}}),P=Nt({mutationFn:async Q=>{const{error:te}=await V.from("scheduled_posts").update({status:"cancelled"}).eq("id",Q);if(te)throw te},onSuccess:()=>{ae.success("Post cancelled"),n.invalidateQueries({queryKey:["scheduled-posts",t]})},onError:Q=>{ae.error(`Failed to cancel: ${Q.message}`)}}),R=Nt({mutationFn:async Q=>{const{error:te}=await V.from("scheduled_posts").delete().eq("id",Q);if(te)throw te},onSuccess:()=>{ae.success("Post deleted"),n.invalidateQueries({queryKey:["scheduled-posts",t]})},onError:Q=>{ae.error(`Failed to delete: ${Q.message}`)}}),O=Nt({mutationFn:async Q=>{const{data:te,error:le}=await V.functions.invoke("social-post",{body:{platform:Q.platform,accountId:Q.social_account_id,imageUrl:Q.image_url,caption:Q.caption}});if(le)throw new Error(await ZIt(le));if(te!=null&&te.error)throw new Error(te.error);return await V.from("scheduled_posts").update({status:"posted",posted_at:new Date().toISOString(),post_id:te.postId}).eq("id",Q.id),te},onSuccess:Q=>{const te=Q.platform==="facebook"?"Facebook":Q.platform==="instagram"?"Instagram":"LinkedIn";ae.success(`Posted to ${te}!`),n.invalidateQueries({queryKey:["scheduled-posts",t]})},onError:Q=>{ae.error(`Failed to post: ${Q.message}`)}}),B=Q=>{if(c(Q),u(Q.caption||""),Q.scheduled_for){const te=new Date(Q.scheduled_for);m(te);const le=te.getHours();g(String(le>12?le-12:le===0?12:le)),y(String(te.getMinutes()).padStart(2,"0")),_(le>=12?"PM":"AM")}},U=()=>{if(!o||!h)return;let Q=parseInt(p);const te=parseInt(x);v==="PM"&&Q!==12&&(Q+=12),v==="AM"&&Q===12&&(Q=0);const le=sAt(tAt(h,Q),te);I.mutate({id:o.id,caption:d,scheduled_for:le.toISOString()})},G=Q=>{switch(Q){case"facebook":return e.jsx(ax,{className:"h-4 w-4 text-blue-600"});case"instagram":return e.jsx(Sf,{className:"h-4 w-4 text-pink-600"});case"linkedin":return e.jsx(dv,{className:"h-4 w-4 text-blue-700"});default:return null}},H=Q=>{switch(Q){case"scheduled":return e.jsxs(qe,{variant:"secondary",className:"gap-1",children:[e.jsx(sa,{className:"h-3 w-3"}),"Scheduled"]});case"posted":return e.jsxs(qe,{variant:"default",className:"gap-1 bg-green-600",children:[e.jsx(nl,{className:"h-3 w-3"}),"Posted"]});case"failed":return e.jsxs(qe,{variant:"destructive",className:"gap-1",children:[e.jsx(ju,{className:"h-3 w-3"}),"Failed"]});case"cancelled":return e.jsxs(qe,{variant:"outline",className:"gap-1 text-muted-foreground",children:[e.jsx(Ho,{className:"h-3 w-3"}),"Cancelled"]});default:return e.jsx(qe,{variant:"outline",children:Q})}},Y=Array.from({length:12},(Q,te)=>String(te+1)),se=["00","15","30","45"],ee=j.filter(Q=>Q.status==="scheduled").length,oe=j.filter(Q=>Q.status==="posted").length,me=j.filter(Q=>Q.status==="scheduled"&&Q.scheduled_for&&i1s(new Date(Q.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(we,{className:"p-4",children:[e.jsx("div",{className:"text-2xl font-bold",children:ee}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Scheduled"})]}),e.jsxs(we,{className:"p-4",children:[e.jsx("div",{className:"text-2xl font-bold",children:me}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Upcoming"})]}),e.jsxs(we,{className:"p-4",children:[e.jsx("div",{className:"text-2xl font-bold",children:oe}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Posted"})]}),e.jsxs(we,{className:"p-4",children:[e.jsx("div",{className:"text-2xl font-bold",children:j.length}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Total"})]})]}),e.jsxs("div",{className:"flex flex-col lg:flex-row gap-6",children:[e.jsxs(we,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[e.jsx(fd,{className:"h-5 w-5"}),e.jsx("h3",{className:"font-semibold",children:"Calendar"})]}),e.jsx(vb,{mode:"single",selected:r,onSelect:a,className:Ot("pointer-events-auto"),modifiers:{hasPost:M},modifiersStyles:{hasPost:{fontWeight:"bold",backgroundColor:"hsl(var(--primary) / 0.1)",borderRadius:"50%"}}}),r&&e.jsx($,{variant:"ghost",size:"sm",onClick:()=>a(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(v2,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("div",{className:"flex flex-wrap gap-1",children:["all","scheduled","posted","failed","cancelled"].map(Q=>e.jsx($,{variant:i===Q?"default":"outline",size:"sm",onClick:()=>l(Q),className:"capitalize",children:Q},Q))})]}),C&&e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(Jt,{className:"h-8 w-8 animate-spin text-muted-foreground"})}),!C&&A.length===0&&e.jsxs(we,{className:"p-8 text-center",children:[e.jsx(ha,{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:r?`No posts scheduled for ${Ys(r,"PPP")}`:"Schedule a post from Social Swag to get started!"})]}),e.jsx("div",{className:"space-y-4",children:A.map(Q=>{var te,le;return e.jsx(we,{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:Q.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:[G(Q.platform),e.jsx("span",{className:"font-medium",children:((te=Q.social_accounts)==null?void 0:te.page_name)||((le=Q.social_accounts)==null?void 0:le.platform_username)||"Unknown"}),H(Q.status)]}),e.jsxs("div",{className:"flex items-center gap-1",children:[Q.status==="scheduled"&&e.jsxs(Sk,{children:[e.jsxs(Lx,{children:[e.jsx(Rx,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",onClick:()=>B(Q),children:e.jsx(ui,{className:"h-4 w-4"})})}),e.jsx(Jg,{children:"Edit post"})]}),e.jsxs(Lx,{children:[e.jsx(Rx,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",onClick:()=>O.mutate(Q),disabled:O.isPending,children:O.isPending?e.jsx(Jt,{className:"h-4 w-4 animate-spin"}):e.jsx(Wr,{className:"h-4 w-4"})})}),e.jsx(Jg,{children:"Post now"})]}),e.jsxs(oc,{children:[e.jsx(_g,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:"text-destructive",children:e.jsx(Un,{className:"h-4 w-4"})})}),e.jsxs(Ql,{children:[e.jsxs(Jl,{children:[e.jsx(tc,{children:"Cancel this scheduled post?"}),e.jsx(sc,{children:"This will cancel the post. You can delete it entirely or keep it in your history."})]}),e.jsxs(ec,{children:[e.jsx(nc,{children:"Keep"}),e.jsx(Vl,{onClick:()=>P.mutate(Q.id),className:"bg-amber-600 hover:bg-amber-700",children:"Cancel Post"}),e.jsx(Vl,{onClick:()=>R.mutate(Q.id),className:"bg-destructive hover:bg-destructive/90",children:"Delete"})]})]})]})]}),(Q.status==="posted"||Q.status==="cancelled"||Q.status==="failed")&&e.jsxs(oc,{children:[e.jsx(_g,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:"text-destructive",children:e.jsx(Un,{className:"h-4 w-4"})})}),e.jsxs(Ql,{children:[e.jsxs(Jl,{children:[e.jsx(tc,{children:"Delete this post?"}),e.jsx(sc,{children:"This will permanently remove this post from your history."})]}),e.jsxs(ec,{children:[e.jsx(nc,{children:"Cancel"}),e.jsx(Vl,{onClick:()=>R.mutate(Q.id),className:"bg-destructive hover:bg-destructive/90",children:"Delete"})]})]})]})]})]}),Q.caption&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2 mb-2",children:Q.caption}),e.jsxs("div",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(sa,{className:"h-3 w-3"}),Q.status==="posted"&&Q.posted_at?`Posted ${Ys(new Date(Q.posted_at),"PPp")}`:Q.scheduled_for?`Scheduled for ${Ys(new Date(Q.scheduled_for),"PPp")}`:"Not scheduled"]}),Q.status==="failed"&&Q.error_message&&e.jsxs("p",{className:"text-xs text-destructive mt-2",children:["Error: ",Q.error_message]})]})]})},Q.id)})})]})]}),e.jsx(zs,{open:!!o,onOpenChange:Q=>!Q&&c(null),children:e.jsxs(Rs,{className:"max-w-lg",children:[e.jsxs(Vs,{children:[e.jsx($s,{children:"Edit Scheduled Post"}),e.jsx(Cr,{children:"Update the caption or reschedule this post"})]}),o&&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:o.image_url,alt:"Post preview",className:"h-full w-full object-cover"})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Caption"}),e.jsx(Ls,{value:d,onChange:Q=>u(Q.target.value),rows:3})]}),e.jsxs("div",{className:"space-y-3 p-4 border rounded-lg",children:[e.jsx(re,{children:"Schedule for"}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsxs(Xc,{children:[e.jsx(Qc,{asChild:!0,children:e.jsxs($,{variant:"outline",className:Ot("justify-start text-left font-normal flex-1",!h&&"text-muted-foreground"),children:[e.jsx(ha,{className:"mr-2 h-4 w-4"}),h?Ys(h,"PPP"):"Pick a date"]})}),e.jsx(Bc,{className:"w-auto p-0",align:"start",children:e.jsx(vb,{mode:"single",selected:h,onSelect:m,disabled:Q=>Qe.jsx(We,{value:Q,children:Q},Q))})]}),e.jsx("span",{className:"text-muted-foreground",children:":"}),e.jsxs(bs,{value:x,onValueChange:y,children:[e.jsx(ys,{className:"w-[70px]",children:e.jsx(_s,{})}),e.jsx(vs,{children:se.map(Q=>e.jsx(We,{value:Q,children:Q},Q))})]}),e.jsxs(bs,{value:v,onValueChange:Q=>_(Q),children:[e.jsx(ys,{className:"w-[70px]",children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"AM",children:"AM"}),e.jsx(We,{value:"PM",children:"PM"})]})]})]})]})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>c(null),children:"Cancel"}),e.jsxs($,{onClick:U,disabled:I.isPending,children:[I.isPending?e.jsx(Jt,{className:"h-4 w-4 animate-spin mr-2"}):null,"Save Changes"]})]})]})})]})}function Pre(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 XIt={exports:{}};/*! JSZip v3.10.1 - A JavaScript class for generating and reading zip files (c) 2009-2016 Stuart Knightley Dual licenced under the MIT license or GPLv3. See https://raw.github.com/Stuk/jszip/main/LICENSE.markdown. JSZip uses the library pako released under the MIT license : https://github.com/nodeca/pako/blob/main/LICENSE */(function(s,t){(function(n){s.exports=n()})(function(){return function n(r,a,i){function l(d,u){if(!a[d]){if(!r[d]){var h=typeof Pre=="function"&&Pre;if(!u&&h)return h(d,!0);if(o)return o(d,!0);var m=new Error("Cannot find module '"+d+"'");throw m.code="MODULE_NOT_FOUND",m}var p=a[d]={exports:{}};r[d][0].call(p.exports,function(g){var x=r[d][1][g];return l(x||g)},p,p.exports,n,r,a,i)}return a[d].exports}for(var o=typeof Pre=="function"&&Pre,c=0;c>2,p=(3&d)<<4|u>>4,g=1>6:64,x=2>4,u=(15&m)<<4|(p=o.indexOf(c.charAt(x++)))>>2,h=(3&p)<<6|(g=o.indexOf(c.charAt(x++))),_[y++]=d,p!==64&&(_[y++]=u),g!==64&&(_[y++]=h);return _}},{"./support":30,"./utils":32}],2:[function(n,r,a){var i=n("./external"),l=n("./stream/DataWorker"),o=n("./stream/Crc32Probe"),c=n("./stream/DataLengthProbe");function d(u,h,m,p,g){this.compressedSize=u,this.uncompressedSize=h,this.crc32=m,this.compression=p,this.compressedContent=g}d.prototype={getContentWorker:function(){var u=new l(i.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new c("data_length")),h=this;return u.on("end",function(){if(this.streamInfo.data_length!==h.uncompressedSize)throw new Error("Bug : uncompressed data size mismatch")}),u},getCompressedWorker:function(){return new l(i.Promise.resolve(this.compressedContent)).withStreamInfo("compressedSize",this.compressedSize).withStreamInfo("uncompressedSize",this.uncompressedSize).withStreamInfo("crc32",this.crc32).withStreamInfo("compression",this.compression)}},d.createWorkerFrom=function(u,h,m){return u.pipe(new o).pipe(new c("uncompressedSize")).pipe(h.compressWorker(m)).pipe(new c("compressedSize")).withStreamInfo("compression",h)},r.exports=d},{"./external":6,"./stream/Crc32Probe":25,"./stream/DataLengthProbe":26,"./stream/DataWorker":27}],3:[function(n,r,a){var i=n("./stream/GenericWorker");a.STORE={magic:"\0\0",compressWorker:function(){return new i("STORE compression")},uncompressWorker:function(){return new i("STORE decompression")}},a.DEFLATE=n("./flate")},{"./flate":7,"./stream/GenericWorker":28}],4:[function(n,r,a){var i=n("./utils"),l=function(){for(var o,c=[],d=0;d<256;d++){o=d;for(var u=0;u<8;u++)o=1&o?3988292384^o>>>1:o>>>1;c[d]=o}return c}();r.exports=function(o,c){return o!==void 0&&o.length?i.getTypeOf(o)!=="string"?function(d,u,h,m){var p=l,g=m+h;d^=-1;for(var x=m;x>>8^p[255&(d^u[x])];return-1^d}(0|c,o,o.length,0):function(d,u,h,m){var p=l,g=m+h;d^=-1;for(var x=m;x>>8^p[255&(d^u.charCodeAt(x))];return-1^d}(0|c,o,o.length,0):0}},{"./utils":32}],5:[function(n,r,a){a.base64=!1,a.binary=!1,a.dir=!1,a.createFolders=!0,a.date=null,a.compression=null,a.compressionOptions=null,a.comment=null,a.unixPermissions=null,a.dosPermissions=null},{}],6:[function(n,r,a){var i=null;i=typeof Promise<"u"?Promise:n("lie"),r.exports={Promise:i}},{lie:37}],7:[function(n,r,a){var i=typeof Uint8Array<"u"&&typeof Uint16Array<"u"&&typeof Uint32Array<"u",l=n("pako"),o=n("./utils"),c=n("./stream/GenericWorker"),d=i?"uint8array":"array";function u(h,m){c.call(this,"FlateWorker/"+h),this._pako=null,this._pakoAction=h,this._pakoOptions=m,this.meta={}}a.magic="\b\0",o.inherits(u,c),u.prototype.processChunk=function(h){this.meta=h.meta,this._pako===null&&this._createPako(),this._pako.push(o.transformTo(d,h.data),!1)},u.prototype.flush=function(){c.prototype.flush.call(this),this._pako===null&&this._createPako(),this._pako.push([],!0)},u.prototype.cleanUp=function(){c.prototype.cleanUp.call(this),this._pako=null},u.prototype._createPako=function(){this._pako=new l[this._pakoAction]({raw:!0,level:this._pakoOptions.level||-1});var h=this;this._pako.onData=function(m){h.push({data:m,meta:h.meta})}},a.compressWorker=function(h){return new u("Deflate",h)},a.uncompressWorker=function(){return new u("Inflate",{})}},{"./stream/GenericWorker":28,"./utils":32,pako:38}],8:[function(n,r,a){function i(p,g){var x,y="";for(x=0;x>>=8;return y}function l(p,g,x,y,v,_){var j,C,A=p.file,M=p.compression,I=_!==d.utf8encode,P=o.transformTo("string",_(A.name)),R=o.transformTo("string",d.utf8encode(A.name)),O=A.comment,B=o.transformTo("string",_(O)),U=o.transformTo("string",d.utf8encode(O)),G=R.length!==A.name.length,H=U.length!==O.length,Y="",se="",ee="",oe=A.dir,me=A.date,Q={crc32:0,compressedSize:0,uncompressedSize:0};g&&!x||(Q.crc32=p.crc32,Q.compressedSize=p.compressedSize,Q.uncompressedSize=p.uncompressedSize);var te=0;g&&(te|=8),I||!G&&!H||(te|=2048);var le=0,fe=0;oe&&(le|=16),v==="UNIX"?(fe=798,le|=function(ve,he){var Se=ve;return ve||(Se=he?16893:33204),(65535&Se)<<16}(A.unixPermissions,oe)):(fe=20,le|=function(ve){return 63&(ve||0)}(A.dosPermissions)),j=me.getUTCHours(),j<<=6,j|=me.getUTCMinutes(),j<<=5,j|=me.getUTCSeconds()/2,C=me.getUTCFullYear()-1980,C<<=4,C|=me.getUTCMonth()+1,C<<=5,C|=me.getUTCDate(),G&&(se=i(1,1)+i(u(P),4)+R,Y+="up"+i(se.length,2)+se),H&&(ee=i(1,1)+i(u(B),4)+U,Y+="uc"+i(ee.length,2)+ee);var _e="";return _e+=` \0`,_e+=i(te,2),_e+=M.magic,_e+=i(j,2),_e+=i(C,2),_e+=i(Q.crc32,4),_e+=i(Q.compressedSize,4),_e+=i(Q.uncompressedSize,4),_e+=i(P.length,2),_e+=i(Y.length,2),{fileRecord:h.LOCAL_FILE_HEADER+_e+P+Y,dirRecord:h.CENTRAL_FILE_HEADER+i(fe,2)+_e+i(B.length,2)+"\0\0\0\0"+i(le,4)+i(y,4)+P+Y+B}}var o=n("../utils"),c=n("../stream/GenericWorker"),d=n("../utf8"),u=n("../crc32"),h=n("../signature");function m(p,g,x,y){c.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=g,this.zipPlatform=x,this.encodeFileName=y,this.streamFiles=p,this.accumulate=!1,this.contentBuffer=[],this.dirRecords=[],this.currentSourceOffset=0,this.entriesCount=0,this.currentFile=null,this._sources=[]}o.inherits(m,c),m.prototype.push=function(p){var g=p.meta.percent||0,x=this.entriesCount,y=this._sources.length;this.accumulate?this.contentBuffer.push(p):(this.bytesWritten+=p.data.length,c.prototype.push.call(this,{data:p.data,meta:{currentFile:this.currentFile,percent:x?(g+100*(x-y-1))/x:100}}))},m.prototype.openedSource=function(p){this.currentSourceOffset=this.bytesWritten,this.currentFile=p.file.name;var g=this.streamFiles&&!p.file.dir;if(g){var x=l(p,g,!1,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:x.fileRecord,meta:{percent:0}})}else this.accumulate=!0},m.prototype.closedSource=function(p){this.accumulate=!1;var g=this.streamFiles&&!p.file.dir,x=l(p,g,!0,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push(x.dirRecord),g)this.push({data:function(y){return h.DATA_DESCRIPTOR+i(y.crc32,4)+i(y.compressedSize,4)+i(y.uncompressedSize,4)}(p),meta:{percent:100}});else for(this.push({data:x.fileRecord,meta:{percent:0}});this.contentBuffer.length;)this.push(this.contentBuffer.shift());this.currentFile=null},m.prototype.flush=function(){for(var p=this.bytesWritten,g=0;g=this.index;c--)d=(d<<8)+this.byteAt(c);return this.index+=o,d},readString:function(o){return i.transformTo("string",this.readData(o))},readData:function(){},lastIndexOfSignature:function(){},readAndCheckSignature:function(){},readDate:function(){var o=this.readInt(4);return new Date(Date.UTC(1980+(o>>25&127),(o>>21&15)-1,o>>16&31,o>>11&31,o>>5&63,(31&o)<<1))}},r.exports=l},{"../utils":32}],19:[function(n,r,a){var i=n("./Uint8ArrayReader");function l(o){i.call(this,o)}n("../utils").inherits(l,i),l.prototype.readData=function(o){this.checkOffset(o);var c=this.data.slice(this.zero+this.index,this.zero+this.index+o);return this.index+=o,c},r.exports=l},{"../utils":32,"./Uint8ArrayReader":21}],20:[function(n,r,a){var i=n("./DataReader");function l(o){i.call(this,o)}n("../utils").inherits(l,i),l.prototype.byteAt=function(o){return this.data.charCodeAt(this.zero+o)},l.prototype.lastIndexOfSignature=function(o){return this.data.lastIndexOf(o)-this.zero},l.prototype.readAndCheckSignature=function(o){return o===this.readData(4)},l.prototype.readData=function(o){this.checkOffset(o);var c=this.data.slice(this.zero+this.index,this.zero+this.index+o);return this.index+=o,c},r.exports=l},{"../utils":32,"./DataReader":18}],21:[function(n,r,a){var i=n("./ArrayReader");function l(o){i.call(this,o)}n("../utils").inherits(l,i),l.prototype.readData=function(o){if(this.checkOffset(o),o===0)return new Uint8Array(0);var c=this.data.subarray(this.zero+this.index,this.zero+this.index+o);return this.index+=o,c},r.exports=l},{"../utils":32,"./ArrayReader":17}],22:[function(n,r,a){var i=n("../utils"),l=n("../support"),o=n("./ArrayReader"),c=n("./StringReader"),d=n("./NodeBufferReader"),u=n("./Uint8ArrayReader");r.exports=function(h){var m=i.getTypeOf(h);return i.checkSupport(m),m!=="string"||l.uint8array?m==="nodebuffer"?new d(h):l.uint8array?new u(i.transformTo("uint8array",h)):new o(i.transformTo("array",h)):new c(h)}},{"../support":30,"../utils":32,"./ArrayReader":17,"./NodeBufferReader":19,"./StringReader":20,"./Uint8ArrayReader":21}],23:[function(n,r,a){a.LOCAL_FILE_HEADER="PK",a.CENTRAL_FILE_HEADER="PK",a.CENTRAL_DIRECTORY_END="PK",a.ZIP64_CENTRAL_DIRECTORY_LOCATOR="PK\x07",a.ZIP64_CENTRAL_DIRECTORY_END="PK",a.DATA_DESCRIPTOR="PK\x07\b"},{}],24:[function(n,r,a){var i=n("./GenericWorker"),l=n("../utils");function o(c){i.call(this,"ConvertWorker to "+c),this.destType=c}l.inherits(o,i),o.prototype.processChunk=function(c){this.push({data:l.transformTo(this.destType,c.data),meta:c.meta})},r.exports=o},{"../utils":32,"./GenericWorker":28}],25:[function(n,r,a){var i=n("./GenericWorker"),l=n("../crc32");function o(){i.call(this,"Crc32Probe"),this.withStreamInfo("crc32",0)}n("../utils").inherits(o,i),o.prototype.processChunk=function(c){this.streamInfo.crc32=l(c.data,this.streamInfo.crc32||0),this.push(c)},r.exports=o},{"../crc32":4,"../utils":32,"./GenericWorker":28}],26:[function(n,r,a){var i=n("../utils"),l=n("./GenericWorker");function o(c){l.call(this,"DataLengthProbe for "+c),this.propName=c,this.withStreamInfo(c,0)}i.inherits(o,l),o.prototype.processChunk=function(c){if(c){var d=this.streamInfo[this.propName]||0;this.streamInfo[this.propName]=d+c.data.length}l.prototype.processChunk.call(this,c)},r.exports=o},{"../utils":32,"./GenericWorker":28}],27:[function(n,r,a){var i=n("../utils"),l=n("./GenericWorker");function o(c){l.call(this,"DataWorker");var d=this;this.dataIsReady=!1,this.index=0,this.max=0,this.data=null,this.type="",this._tickScheduled=!1,c.then(function(u){d.dataIsReady=!0,d.data=u,d.max=u&&u.length||0,d.type=i.getTypeOf(u),d.isPaused||d._tickAndRepeat()},function(u){d.error(u)})}i.inherits(o,l),o.prototype.cleanUp=function(){l.prototype.cleanUp.call(this),this.data=null},o.prototype.resume=function(){return!!l.prototype.resume.call(this)&&(!this._tickScheduled&&this.dataIsReady&&(this._tickScheduled=!0,i.delay(this._tickAndRepeat,[],this)),!0)},o.prototype._tickAndRepeat=function(){this._tickScheduled=!1,this.isPaused||this.isFinished||(this._tick(),this.isFinished||(i.delay(this._tickAndRepeat,[],this),this._tickScheduled=!0))},o.prototype._tick=function(){if(this.isPaused||this.isFinished)return!1;var c=null,d=Math.min(this.max,this.index+16384);if(this.index>=this.max)return this.end();switch(this.type){case"string":c=this.data.substring(this.index,d);break;case"uint8array":c=this.data.subarray(this.index,d);break;case"array":case"nodebuffer":c=this.data.slice(this.index,d)}return this.index=d,this.push({data:c,meta:{percent:this.max?this.index/this.max*100:0}})},r.exports=o},{"../utils":32,"./GenericWorker":28}],28:[function(n,r,a){function i(l){this.name=l||"default",this.streamInfo={},this.generatedError=null,this.extraStreamInfo={},this.isPaused=!0,this.isFinished=!1,this.isLocked=!1,this._listeners={data:[],end:[],error:[]},this.previous=null}i.prototype={push:function(l){this.emit("data",l)},end:function(){if(this.isFinished)return!1;this.flush();try{this.emit("end"),this.cleanUp(),this.isFinished=!0}catch(l){this.emit("error",l)}return!0},error:function(l){return!this.isFinished&&(this.isPaused?this.generatedError=l:(this.isFinished=!0,this.emit("error",l),this.previous&&this.previous.error(l),this.cleanUp()),!0)},on:function(l,o){return this._listeners[l].push(o),this},cleanUp:function(){this.streamInfo=this.generatedError=this.extraStreamInfo=null,this._listeners=[]},emit:function(l,o){if(this._listeners[l])for(var c=0;c "+l:l}},r.exports=i},{}],29:[function(n,r,a){var i=n("../utils"),l=n("./ConvertWorker"),o=n("./GenericWorker"),c=n("../base64"),d=n("../support"),u=n("../external"),h=null;if(d.nodestream)try{h=n("../nodejs/NodejsStreamOutputAdapter")}catch{}function m(g,x){return new u.Promise(function(y,v){var _=[],j=g._internalType,C=g._outputType,A=g._mimeType;g.on("data",function(M,I){_.push(M),x&&x(I)}).on("error",function(M){_=[],v(M)}).on("end",function(){try{var M=function(I,P,R){switch(I){case"blob":return i.newBlob(i.transformTo("arraybuffer",P),R);case"base64":return c.encode(P);default:return i.transformTo(I,P)}}(C,function(I,P){var R,O=0,B=null,U=0;for(R=0;R"u")a.blob=!1;else{var i=new ArrayBuffer(0);try{a.blob=new Blob([i],{type:"application/zip"}).size===0}catch{try{var l=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);l.append(i),a.blob=l.getBlob("application/zip").size===0}catch{a.blob=!1}}}try{a.nodestream=!!n("readable-stream").Readable}catch{a.nodestream=!1}},{"readable-stream":16}],31:[function(n,r,a){for(var i=n("./utils"),l=n("./support"),o=n("./nodejsUtils"),c=n("./stream/GenericWorker"),d=new Array(256),u=0;u<256;u++)d[u]=252<=u?6:248<=u?5:240<=u?4:224<=u?3:192<=u?2:1;d[254]=d[254]=1;function h(){c.call(this,"utf-8 decode"),this.leftOver=null}function m(){c.call(this,"utf-8 encode")}a.utf8encode=function(p){return l.nodebuffer?o.newBufferFrom(p,"utf-8"):function(g){var x,y,v,_,j,C=g.length,A=0;for(_=0;_>>6:(y<65536?x[j++]=224|y>>>12:(x[j++]=240|y>>>18,x[j++]=128|y>>>12&63),x[j++]=128|y>>>6&63),x[j++]=128|63&y);return x}(p)},a.utf8decode=function(p){return l.nodebuffer?i.transformTo("nodebuffer",p).toString("utf-8"):function(g){var x,y,v,_,j=g.length,C=new Array(2*j);for(x=y=0;x>10&1023,C[y++]=56320|1023&v)}return C.length!==y&&(C.subarray?C=C.subarray(0,y):C.length=y),i.applyFromCharCode(C)}(p=i.transformTo(l.uint8array?"uint8array":"array",p))},i.inherits(h,c),h.prototype.processChunk=function(p){var g=i.transformTo(l.uint8array?"uint8array":"array",p.data);if(this.leftOver&&this.leftOver.length){if(l.uint8array){var x=g;(g=new Uint8Array(x.length+this.leftOver.length)).set(this.leftOver,0),g.set(x,this.leftOver.length)}else g=this.leftOver.concat(g);this.leftOver=null}var y=function(_,j){var C;for((j=j||_.length)>_.length&&(j=_.length),C=j-1;0<=C&&(192&_[C])==128;)C--;return C<0||C===0?j:C+d[_[C]]>j?C:j}(g),v=g;y!==g.length&&(l.uint8array?(v=g.subarray(0,y),this.leftOver=g.subarray(y,g.length)):(v=g.slice(0,y),this.leftOver=g.slice(y,g.length))),this.push({data:a.utf8decode(v),meta:p.meta})},h.prototype.flush=function(){this.leftOver&&this.leftOver.length&&(this.push({data:a.utf8decode(this.leftOver),meta:{}}),this.leftOver=null)},a.Utf8DecodeWorker=h,i.inherits(m,c),m.prototype.processChunk=function(p){this.push({data:a.utf8encode(p.data),meta:p.meta})},a.Utf8EncodeWorker=m},{"./nodejsUtils":14,"./stream/GenericWorker":28,"./support":30,"./utils":32}],32:[function(n,r,a){var i=n("./support"),l=n("./base64"),o=n("./nodejsUtils"),c=n("./external");function d(x){return x}function u(x,y){for(var v=0;v>8;this.dir=!!(16&this.externalFileAttributes),p==0&&(this.dosPermissions=63&this.externalFileAttributes),p==3&&(this.unixPermissions=this.externalFileAttributes>>16&65535),this.dir||this.fileNameStr.slice(-1)!=="/"||(this.dir=!0)},parseZIP64ExtraField:function(){if(this.extraFields[1]){var p=i(this.extraFields[1].value);this.uncompressedSize===l.MAX_VALUE_32BITS&&(this.uncompressedSize=p.readInt(8)),this.compressedSize===l.MAX_VALUE_32BITS&&(this.compressedSize=p.readInt(8)),this.localHeaderOffset===l.MAX_VALUE_32BITS&&(this.localHeaderOffset=p.readInt(8)),this.diskNumberStart===l.MAX_VALUE_32BITS&&(this.diskNumberStart=p.readInt(4))}},readExtraFields:function(p){var g,x,y,v=p.index+this.extraFieldsLength;for(this.extraFields||(this.extraFields={});p.index+4>>6:(p<65536?m[y++]=224|p>>>12:(m[y++]=240|p>>>18,m[y++]=128|p>>>12&63),m[y++]=128|p>>>6&63),m[y++]=128|63&p);return m},a.buf2binstring=function(h){return u(h,h.length)},a.binstring2buf=function(h){for(var m=new i.Buf8(h.length),p=0,g=m.length;p>10&1023,_[g++]=56320|1023&x)}return u(_,g)},a.utf8border=function(h,m){var p;for((m=m||h.length)>h.length&&(m=h.length),p=m-1;0<=p&&(192&h[p])==128;)p--;return p<0||p===0?m:p+c[h[p]]>m?p:m}},{"./common":41}],43:[function(n,r,a){r.exports=function(i,l,o,c){for(var d=65535&i|0,u=i>>>16&65535|0,h=0;o!==0;){for(o-=h=2e3>>1:l>>>1;o[c]=l}return o}();r.exports=function(l,o,c,d){var u=i,h=d+c;l^=-1;for(var m=d;m>>8^u[255&(l^o[m])];return-1^l}},{}],46:[function(n,r,a){var i,l=n("../utils/common"),o=n("./trees"),c=n("./adler32"),d=n("./crc32"),u=n("./messages"),h=0,m=4,p=0,g=-2,x=-1,y=4,v=2,_=8,j=9,C=286,A=30,M=19,I=2*C+1,P=15,R=3,O=258,B=O+R+1,U=42,G=113,H=1,Y=2,se=3,ee=4;function oe(Ee,Re){return Ee.msg=u[Re],Re}function me(Ee){return(Ee<<1)-(4Ee.avail_out&&(ke=Ee.avail_out),ke!==0&&(l.arraySet(Ee.output,Re.pending_buf,Re.pending_out,ke,Ee.next_out),Ee.next_out+=ke,Re.pending_out+=ke,Ee.total_out+=ke,Ee.avail_out-=ke,Re.pending-=ke,Re.pending===0&&(Re.pending_out=0))}function le(Ee,Re){o._tr_flush_block(Ee,0<=Ee.block_start?Ee.block_start:-1,Ee.strstart-Ee.block_start,Re),Ee.block_start=Ee.strstart,te(Ee.strm)}function fe(Ee,Re){Ee.pending_buf[Ee.pending++]=Re}function _e(Ee,Re){Ee.pending_buf[Ee.pending++]=Re>>>8&255,Ee.pending_buf[Ee.pending++]=255&Re}function ve(Ee,Re){var ke,Fe,Oe=Ee.max_chain_length,Ge=Ee.strstart,yt=Ee.prev_length,tt=Ee.nice_match,ut=Ee.strstart>Ee.w_size-B?Ee.strstart-(Ee.w_size-B):0,nt=Ee.window,et=Ee.w_mask,at=Ee.prev,wt=Ee.strstart+O,rt=nt[Ge+yt-1],Ft=nt[Ge+yt];Ee.prev_length>=Ee.good_match&&(Oe>>=2),tt>Ee.lookahead&&(tt=Ee.lookahead);do if(nt[(ke=Re)+yt]===Ft&&nt[ke+yt-1]===rt&&nt[ke]===nt[Ge]&&nt[++ke]===nt[Ge+1]){Ge+=2,ke++;do;while(nt[++Ge]===nt[++ke]&&nt[++Ge]===nt[++ke]&&nt[++Ge]===nt[++ke]&&nt[++Ge]===nt[++ke]&&nt[++Ge]===nt[++ke]&&nt[++Ge]===nt[++ke]&&nt[++Ge]===nt[++ke]&&nt[++Ge]===nt[++ke]&&Geut&&--Oe!=0);return yt<=Ee.lookahead?yt:Ee.lookahead}function he(Ee){var Re,ke,Fe,Oe,Ge,yt,tt,ut,nt,et,at=Ee.w_size;do{if(Oe=Ee.window_size-Ee.lookahead-Ee.strstart,Ee.strstart>=at+(at-B)){for(l.arraySet(Ee.window,Ee.window,at,at,0),Ee.match_start-=at,Ee.strstart-=at,Ee.block_start-=at,Re=ke=Ee.hash_size;Fe=Ee.head[--Re],Ee.head[Re]=at<=Fe?Fe-at:0,--ke;);for(Re=ke=at;Fe=Ee.prev[--Re],Ee.prev[Re]=at<=Fe?Fe-at:0,--ke;);Oe+=at}if(Ee.strm.avail_in===0)break;if(yt=Ee.strm,tt=Ee.window,ut=Ee.strstart+Ee.lookahead,nt=Oe,et=void 0,et=yt.avail_in,nt=R)for(Ge=Ee.strstart-Ee.insert,Ee.ins_h=Ee.window[Ge],Ee.ins_h=(Ee.ins_h<=R&&(Ee.ins_h=(Ee.ins_h<=R)if(Fe=o._tr_tally(Ee,Ee.strstart-Ee.match_start,Ee.match_length-R),Ee.lookahead-=Ee.match_length,Ee.match_length<=Ee.max_lazy_match&&Ee.lookahead>=R){for(Ee.match_length--;Ee.strstart++,Ee.ins_h=(Ee.ins_h<=R&&(Ee.ins_h=(Ee.ins_h<=R&&Ee.match_length<=Ee.prev_length){for(Oe=Ee.strstart+Ee.lookahead-R,Fe=o._tr_tally(Ee,Ee.strstart-1-Ee.prev_match,Ee.prev_length-R),Ee.lookahead-=Ee.prev_length-1,Ee.prev_length-=2;++Ee.strstart<=Oe&&(Ee.ins_h=(Ee.ins_h<Ee.pending_buf_size-5&&(ke=Ee.pending_buf_size-5);;){if(Ee.lookahead<=1){if(he(Ee),Ee.lookahead===0&&Re===h)return H;if(Ee.lookahead===0)break}Ee.strstart+=Ee.lookahead,Ee.lookahead=0;var Fe=Ee.block_start+ke;if((Ee.strstart===0||Ee.strstart>=Fe)&&(Ee.lookahead=Ee.strstart-Fe,Ee.strstart=Fe,le(Ee,!1),Ee.strm.avail_out===0)||Ee.strstart-Ee.block_start>=Ee.w_size-B&&(le(Ee,!1),Ee.strm.avail_out===0))return H}return Ee.insert=0,Re===m?(le(Ee,!0),Ee.strm.avail_out===0?se:ee):(Ee.strstart>Ee.block_start&&(le(Ee,!1),Ee.strm.avail_out),H)}),new Ie(4,4,8,4,Se),new Ie(4,5,16,8,Se),new Ie(4,6,32,32,Se),new Ie(4,4,16,16,Te),new Ie(8,16,32,32,Te),new Ie(8,16,128,128,Te),new Ie(8,32,128,256,Te),new Ie(32,128,258,1024,Te),new Ie(32,258,258,4096,Te)],a.deflateInit=function(Ee,Re){return Ye(Ee,Re,_,15,8,0)},a.deflateInit2=Ye,a.deflateReset=je,a.deflateResetKeep=Be,a.deflateSetHeader=function(Ee,Re){return Ee&&Ee.state?Ee.state.wrap!==2?g:(Ee.state.gzhead=Re,p):g},a.deflate=function(Ee,Re){var ke,Fe,Oe,Ge;if(!Ee||!Ee.state||5>8&255),fe(Fe,Fe.gzhead.time>>16&255),fe(Fe,Fe.gzhead.time>>24&255),fe(Fe,Fe.level===9?2:2<=Fe.strategy||Fe.level<2?4:0),fe(Fe,255&Fe.gzhead.os),Fe.gzhead.extra&&Fe.gzhead.extra.length&&(fe(Fe,255&Fe.gzhead.extra.length),fe(Fe,Fe.gzhead.extra.length>>8&255)),Fe.gzhead.hcrc&&(Ee.adler=d(Ee.adler,Fe.pending_buf,Fe.pending,0)),Fe.gzindex=0,Fe.status=69):(fe(Fe,0),fe(Fe,0),fe(Fe,0),fe(Fe,0),fe(Fe,0),fe(Fe,Fe.level===9?2:2<=Fe.strategy||Fe.level<2?4:0),fe(Fe,3),Fe.status=G);else{var yt=_+(Fe.w_bits-8<<4)<<8;yt|=(2<=Fe.strategy||Fe.level<2?0:Fe.level<6?1:Fe.level===6?2:3)<<6,Fe.strstart!==0&&(yt|=32),yt+=31-yt%31,Fe.status=G,_e(Fe,yt),Fe.strstart!==0&&(_e(Fe,Ee.adler>>>16),_e(Fe,65535&Ee.adler)),Ee.adler=1}if(Fe.status===69)if(Fe.gzhead.extra){for(Oe=Fe.pending;Fe.gzindex<(65535&Fe.gzhead.extra.length)&&(Fe.pending!==Fe.pending_buf_size||(Fe.gzhead.hcrc&&Fe.pending>Oe&&(Ee.adler=d(Ee.adler,Fe.pending_buf,Fe.pending-Oe,Oe)),te(Ee),Oe=Fe.pending,Fe.pending!==Fe.pending_buf_size));)fe(Fe,255&Fe.gzhead.extra[Fe.gzindex]),Fe.gzindex++;Fe.gzhead.hcrc&&Fe.pending>Oe&&(Ee.adler=d(Ee.adler,Fe.pending_buf,Fe.pending-Oe,Oe)),Fe.gzindex===Fe.gzhead.extra.length&&(Fe.gzindex=0,Fe.status=73)}else Fe.status=73;if(Fe.status===73)if(Fe.gzhead.name){Oe=Fe.pending;do{if(Fe.pending===Fe.pending_buf_size&&(Fe.gzhead.hcrc&&Fe.pending>Oe&&(Ee.adler=d(Ee.adler,Fe.pending_buf,Fe.pending-Oe,Oe)),te(Ee),Oe=Fe.pending,Fe.pending===Fe.pending_buf_size)){Ge=1;break}Ge=Fe.gzindexOe&&(Ee.adler=d(Ee.adler,Fe.pending_buf,Fe.pending-Oe,Oe)),Ge===0&&(Fe.gzindex=0,Fe.status=91)}else Fe.status=91;if(Fe.status===91)if(Fe.gzhead.comment){Oe=Fe.pending;do{if(Fe.pending===Fe.pending_buf_size&&(Fe.gzhead.hcrc&&Fe.pending>Oe&&(Ee.adler=d(Ee.adler,Fe.pending_buf,Fe.pending-Oe,Oe)),te(Ee),Oe=Fe.pending,Fe.pending===Fe.pending_buf_size)){Ge=1;break}Ge=Fe.gzindexOe&&(Ee.adler=d(Ee.adler,Fe.pending_buf,Fe.pending-Oe,Oe)),Ge===0&&(Fe.status=103)}else Fe.status=103;if(Fe.status===103&&(Fe.gzhead.hcrc?(Fe.pending+2>Fe.pending_buf_size&&te(Ee),Fe.pending+2<=Fe.pending_buf_size&&(fe(Fe,255&Ee.adler),fe(Fe,Ee.adler>>8&255),Ee.adler=0,Fe.status=G)):Fe.status=G),Fe.pending!==0){if(te(Ee),Ee.avail_out===0)return Fe.last_flush=-1,p}else if(Ee.avail_in===0&&me(Re)<=me(ke)&&Re!==m)return oe(Ee,-5);if(Fe.status===666&&Ee.avail_in!==0)return oe(Ee,-5);if(Ee.avail_in!==0||Fe.lookahead!==0||Re!==h&&Fe.status!==666){var tt=Fe.strategy===2?function(ut,nt){for(var et;;){if(ut.lookahead===0&&(he(ut),ut.lookahead===0)){if(nt===h)return H;break}if(ut.match_length=0,et=o._tr_tally(ut,0,ut.window[ut.strstart]),ut.lookahead--,ut.strstart++,et&&(le(ut,!1),ut.strm.avail_out===0))return H}return ut.insert=0,nt===m?(le(ut,!0),ut.strm.avail_out===0?se:ee):ut.last_lit&&(le(ut,!1),ut.strm.avail_out===0)?H:Y}(Fe,Re):Fe.strategy===3?function(ut,nt){for(var et,at,wt,rt,Ft=ut.window;;){if(ut.lookahead<=O){if(he(ut),ut.lookahead<=O&&nt===h)return H;if(ut.lookahead===0)break}if(ut.match_length=0,ut.lookahead>=R&&0ut.lookahead&&(ut.match_length=ut.lookahead)}if(ut.match_length>=R?(et=o._tr_tally(ut,1,ut.match_length-R),ut.lookahead-=ut.match_length,ut.strstart+=ut.match_length,ut.match_length=0):(et=o._tr_tally(ut,0,ut.window[ut.strstart]),ut.lookahead--,ut.strstart++),et&&(le(ut,!1),ut.strm.avail_out===0))return H}return ut.insert=0,nt===m?(le(ut,!0),ut.strm.avail_out===0?se:ee):ut.last_lit&&(le(ut,!1),ut.strm.avail_out===0)?H:Y}(Fe,Re):i[Fe.level].func(Fe,Re);if(tt!==se&&tt!==ee||(Fe.status=666),tt===H||tt===se)return Ee.avail_out===0&&(Fe.last_flush=-1),p;if(tt===Y&&(Re===1?o._tr_align(Fe):Re!==5&&(o._tr_stored_block(Fe,0,0,!1),Re===3&&(Q(Fe.head),Fe.lookahead===0&&(Fe.strstart=0,Fe.block_start=0,Fe.insert=0))),te(Ee),Ee.avail_out===0))return Fe.last_flush=-1,p}return Re!==m?p:Fe.wrap<=0?1:(Fe.wrap===2?(fe(Fe,255&Ee.adler),fe(Fe,Ee.adler>>8&255),fe(Fe,Ee.adler>>16&255),fe(Fe,Ee.adler>>24&255),fe(Fe,255&Ee.total_in),fe(Fe,Ee.total_in>>8&255),fe(Fe,Ee.total_in>>16&255),fe(Fe,Ee.total_in>>24&255)):(_e(Fe,Ee.adler>>>16),_e(Fe,65535&Ee.adler)),te(Ee),0=ke.w_size&&(Ge===0&&(Q(ke.head),ke.strstart=0,ke.block_start=0,ke.insert=0),nt=new l.Buf8(ke.w_size),l.arraySet(nt,Re,et-ke.w_size,ke.w_size,0),Re=nt,et=ke.w_size),yt=Ee.avail_in,tt=Ee.next_in,ut=Ee.input,Ee.avail_in=et,Ee.next_in=0,Ee.input=Re,he(ke);ke.lookahead>=R;){for(Fe=ke.strstart,Oe=ke.lookahead-(R-1);ke.ins_h=(ke.ins_h<>>=R=P>>>24,j-=R,(R=P>>>16&255)===0)Y[u++]=65535&P;else{if(!(16&R)){if(!(64&R)){P=C[(65535&P)+(_&(1<>>=R,j-=R),j<15&&(_+=H[c++]<>>=R=P>>>24,j-=R,!(16&(R=P>>>16&255))){if(!(64&R)){P=A[(65535&P)+(_&(1<>>=R,j-=R,(R=u-h)>3,_&=(1<<(j-=O<<3))-1,i.next_in=c,i.next_out=u,i.avail_in=c>>24&255)+(U>>>8&65280)+((65280&U)<<8)+((255&U)<<24)}function _(){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 j(U){var G;return U&&U.state?(G=U.state,U.total_in=U.total_out=G.total=0,U.msg="",G.wrap&&(U.adler=1&G.wrap),G.mode=g,G.last=0,G.havedict=0,G.dmax=32768,G.head=null,G.hold=0,G.bits=0,G.lencode=G.lendyn=new i.Buf32(x),G.distcode=G.distdyn=new i.Buf32(y),G.sane=1,G.back=-1,m):p}function C(U){var G;return U&&U.state?((G=U.state).wsize=0,G.whave=0,G.wnext=0,j(U)):p}function A(U,G){var H,Y;return U&&U.state?(Y=U.state,G<0?(H=0,G=-G):(H=1+(G>>4),G<48&&(G&=15)),G&&(G<8||15=ee.wsize?(i.arraySet(ee.window,G,H-ee.wsize,ee.wsize,0),ee.wnext=0,ee.whave=ee.wsize):(Y<(se=ee.wsize-ee.wnext)&&(se=Y),i.arraySet(ee.window,G,H-Y,se,ee.wnext),(Y-=se)?(i.arraySet(ee.window,G,H-Y,Y,0),ee.wnext=Y,ee.whave=ee.wsize):(ee.wnext+=se,ee.wnext===ee.wsize&&(ee.wnext=0),ee.whave>>8&255,H.check=o(H.check,Ge,2,0),le=te=0,H.mode=2;break}if(H.flags=0,H.head&&(H.head.done=!1),!(1&H.wrap)||(((255&te)<<8)+(te>>8))%31){U.msg="incorrect header check",H.mode=30;break}if((15&te)!=8){U.msg="unknown compression method",H.mode=30;break}if(le-=4,Ee=8+(15&(te>>>=4)),H.wbits===0)H.wbits=Ee;else if(Ee>H.wbits){U.msg="invalid window size",H.mode=30;break}H.dmax=1<>8&1),512&H.flags&&(Ge[0]=255&te,Ge[1]=te>>>8&255,H.check=o(H.check,Ge,2,0)),le=te=0,H.mode=3;case 3:for(;le<32;){if(me===0)break e;me--,te+=Y[ee++]<>>8&255,Ge[2]=te>>>16&255,Ge[3]=te>>>24&255,H.check=o(H.check,Ge,4,0)),le=te=0,H.mode=4;case 4:for(;le<16;){if(me===0)break e;me--,te+=Y[ee++]<>8),512&H.flags&&(Ge[0]=255&te,Ge[1]=te>>>8&255,H.check=o(H.check,Ge,2,0)),le=te=0,H.mode=5;case 5:if(1024&H.flags){for(;le<16;){if(me===0)break e;me--,te+=Y[ee++]<>>8&255,H.check=o(H.check,Ge,2,0)),le=te=0}else H.head&&(H.head.extra=null);H.mode=6;case 6:if(1024&H.flags&&(me<(ve=H.length)&&(ve=me),ve&&(H.head&&(Ee=H.head.extra_len-H.length,H.head.extra||(H.head.extra=new Array(H.head.extra_len)),i.arraySet(H.head.extra,Y,ee,ve,Ee)),512&H.flags&&(H.check=o(H.check,Y,ve,ee)),me-=ve,ee+=ve,H.length-=ve),H.length))break e;H.length=0,H.mode=7;case 7:if(2048&H.flags){if(me===0)break e;for(ve=0;Ee=Y[ee+ve++],H.head&&Ee&&H.length<65536&&(H.head.name+=String.fromCharCode(Ee)),Ee&&ve>9&1,H.head.done=!0),U.adler=H.check=0,H.mode=12;break;case 10:for(;le<32;){if(me===0)break e;me--,te+=Y[ee++]<>>=7&le,le-=7&le,H.mode=27;break}for(;le<3;){if(me===0)break e;me--,te+=Y[ee++]<>>=1)){case 0:H.mode=14;break;case 1:if(O(H),H.mode=20,G!==6)break;te>>>=2,le-=2;break e;case 2:H.mode=17;break;case 3:U.msg="invalid block type",H.mode=30}te>>>=2,le-=2;break;case 14:for(te>>>=7&le,le-=7≤le<32;){if(me===0)break e;me--,te+=Y[ee++]<>>16^65535)){U.msg="invalid stored block lengths",H.mode=30;break}if(H.length=65535&te,le=te=0,H.mode=15,G===6)break e;case 15:H.mode=16;case 16:if(ve=H.length){if(me>>=5,le-=5,H.ndist=1+(31&te),te>>>=5,le-=5,H.ncode=4+(15&te),te>>>=4,le-=4,286>>=3,le-=3}for(;H.have<19;)H.lens[yt[H.have++]]=0;if(H.lencode=H.lendyn,H.lenbits=7,ke={bits:H.lenbits},Re=d(0,H.lens,0,19,H.lencode,0,H.work,ke),H.lenbits=ke.bits,Re){U.msg="invalid code lengths set",H.mode=30;break}H.have=0,H.mode=19;case 19:for(;H.have>>16&255,Ue=65535&Oe,!((Te=Oe>>>24)<=le);){if(me===0)break e;me--,te+=Y[ee++]<>>=Te,le-=Te,H.lens[H.have++]=Ue;else{if(Ue===16){for(Fe=Te+2;le>>=Te,le-=Te,H.have===0){U.msg="invalid bit length repeat",H.mode=30;break}Ee=H.lens[H.have-1],ve=3+(3&te),te>>>=2,le-=2}else if(Ue===17){for(Fe=Te+3;le>>=Te)),te>>>=3,le-=3}else{for(Fe=Te+7;le>>=Te)),te>>>=7,le-=7}if(H.have+ve>H.nlen+H.ndist){U.msg="invalid bit length repeat",H.mode=30;break}for(;ve--;)H.lens[H.have++]=Ee}}if(H.mode===30)break;if(H.lens[256]===0){U.msg="invalid code -- missing end-of-block",H.mode=30;break}if(H.lenbits=9,ke={bits:H.lenbits},Re=d(u,H.lens,0,H.nlen,H.lencode,0,H.work,ke),H.lenbits=ke.bits,Re){U.msg="invalid literal/lengths set",H.mode=30;break}if(H.distbits=6,H.distcode=H.distdyn,ke={bits:H.distbits},Re=d(h,H.lens,H.nlen,H.ndist,H.distcode,0,H.work,ke),H.distbits=ke.bits,Re){U.msg="invalid distances set",H.mode=30;break}if(H.mode=20,G===6)break e;case 20:H.mode=21;case 21:if(6<=me&&258<=Q){U.next_out=oe,U.avail_out=Q,U.next_in=ee,U.avail_in=me,H.hold=te,H.bits=le,c(U,_e),oe=U.next_out,se=U.output,Q=U.avail_out,ee=U.next_in,Y=U.input,me=U.avail_in,te=H.hold,le=H.bits,H.mode===12&&(H.back=-1);break}for(H.back=0;Ie=(Oe=H.lencode[te&(1<>>16&255,Ue=65535&Oe,!((Te=Oe>>>24)<=le);){if(me===0)break e;me--,te+=Y[ee++]<>Be)])>>>16&255,Ue=65535&Oe,!(Be+(Te=Oe>>>24)<=le);){if(me===0)break e;me--,te+=Y[ee++]<>>=Be,le-=Be,H.back+=Be}if(te>>>=Te,le-=Te,H.back+=Te,H.length=Ue,Ie===0){H.mode=26;break}if(32&Ie){H.back=-1,H.mode=12;break}if(64&Ie){U.msg="invalid literal/length code",H.mode=30;break}H.extra=15&Ie,H.mode=22;case 22:if(H.extra){for(Fe=H.extra;le>>=H.extra,le-=H.extra,H.back+=H.extra}H.was=H.length,H.mode=23;case 23:for(;Ie=(Oe=H.distcode[te&(1<>>16&255,Ue=65535&Oe,!((Te=Oe>>>24)<=le);){if(me===0)break e;me--,te+=Y[ee++]<>Be)])>>>16&255,Ue=65535&Oe,!(Be+(Te=Oe>>>24)<=le);){if(me===0)break e;me--,te+=Y[ee++]<>>=Be,le-=Be,H.back+=Be}if(te>>>=Te,le-=Te,H.back+=Te,64&Ie){U.msg="invalid distance code",H.mode=30;break}H.offset=Ue,H.extra=15&Ie,H.mode=24;case 24:if(H.extra){for(Fe=H.extra;le>>=H.extra,le-=H.extra,H.back+=H.extra}if(H.offset>H.dmax){U.msg="invalid distance too far back",H.mode=30;break}H.mode=25;case 25:if(Q===0)break e;if(ve=_e-Q,H.offset>ve){if((ve=H.offset-ve)>H.whave&&H.sane){U.msg="invalid distance too far back",H.mode=30;break}he=ve>H.wnext?(ve-=H.wnext,H.wsize-ve):H.wnext-ve,ve>H.length&&(ve=H.length),Se=H.window}else Se=se,he=oe-H.offset,ve=H.length;for(QI?(R=he[Se+y[G]],le[fe+y[G]]):(R=96,0),_=1<>oe)+(j-=_)]=P<<24|R<<16|O|0,j!==0;);for(_=1<>=1;if(_!==0?(te&=_-1,te+=_):te=0,G++,--_e[U]==0){if(U===Y)break;U=h[m+y[G]]}if(se>>7)]}function fe(Oe,Ge){Oe.pending_buf[Oe.pending++]=255&Ge,Oe.pending_buf[Oe.pending++]=Ge>>>8&255}function _e(Oe,Ge,yt){Oe.bi_valid>v-yt?(Oe.bi_buf|=Ge<>v-Oe.bi_valid,Oe.bi_valid+=yt-v):(Oe.bi_buf|=Ge<>>=1,yt<<=1,0<--Ge;);return yt>>>1}function Se(Oe,Ge,yt){var tt,ut,nt=new Array(y+1),et=0;for(tt=1;tt<=y;tt++)nt[tt]=et=et+yt[tt-1]<<1;for(ut=0;ut<=Ge;ut++){var at=Oe[2*ut+1];at!==0&&(Oe[2*ut]=he(nt[at]++,at))}}function Te(Oe){var Ge;for(Ge=0;Ge>1;1<=yt;yt--)Be(Oe,nt,yt);for(ut=wt;yt=Oe.heap[1],Oe.heap[1]=Oe.heap[Oe.heap_len--],Be(Oe,nt,1),tt=Oe.heap[1],Oe.heap[--Oe.heap_max]=yt,Oe.heap[--Oe.heap_max]=tt,nt[2*ut]=nt[2*yt]+nt[2*tt],Oe.depth[ut]=(Oe.depth[yt]>=Oe.depth[tt]?Oe.depth[yt]:Oe.depth[tt])+1,nt[2*yt+1]=nt[2*tt+1]=ut,Oe.heap[1]=ut++,Be(Oe,nt,1),2<=Oe.heap_len;);Oe.heap[--Oe.heap_max]=Oe.heap[1],function(Ft,Ut){var Is,xs,st,dt,jt,gt,rs=Ut.dyn_tree,Ns=Ut.max_code,us=Ut.stat_desc.static_tree,Bs=Ut.stat_desc.has_stree,Ts=Ut.stat_desc.extra_bits,Fn=Ut.stat_desc.extra_base,An=Ut.stat_desc.max_length,js=0;for(dt=0;dt<=y;dt++)Ft.bl_count[dt]=0;for(rs[2*Ft.heap[Ft.heap_max]+1]=0,Is=Ft.heap_max+1;Is>=7;ut>>=1)if(1&rt&&at.dyn_ltree[2*wt]!==0)return l;if(at.dyn_ltree[18]!==0||at.dyn_ltree[20]!==0||at.dyn_ltree[26]!==0)return o;for(wt=32;wt>>3,(nt=Oe.static_len+3+7>>>3)<=ut&&(ut=nt)):ut=nt=yt+5,yt+4<=ut&&Ge!==-1?Fe(Oe,Ge,yt,tt):Oe.strategy===4||nt===ut?(_e(Oe,2+(tt?1:0),3),je(Oe,B,U)):(_e(Oe,4+(tt?1:0),3),function(at,wt,rt,Ft){var Ut;for(_e(at,wt-257,5),_e(at,rt-1,5),_e(at,Ft-4,4),Ut=0;Ut>>8&255,Oe.pending_buf[Oe.d_buf+2*Oe.last_lit+1]=255&Ge,Oe.pending_buf[Oe.l_buf+Oe.last_lit]=255&yt,Oe.last_lit++,Ge===0?Oe.dyn_ltree[2*yt]++:(Oe.matches++,Ge--,Oe.dyn_ltree[2*(H[yt]+h+1)]++,Oe.dyn_dtree[2*le(Ge)]++),Oe.last_lit===Oe.lit_bufsize-1},a._tr_align=function(Oe){_e(Oe,2,3),ve(Oe,j,B),function(Ge){Ge.bi_valid===16?(fe(Ge,Ge.bi_buf),Ge.bi_buf=0,Ge.bi_valid=0):8<=Ge.bi_valid&&(Ge.pending_buf[Ge.pending++]=255&Ge.bi_buf,Ge.bi_buf>>=8,Ge.bi_valid-=8)}(Oe)}},{"../utils/common":41}],53:[function(n,r,a){r.exports=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}},{}],54:[function(n,r,a){(function(i){(function(l,o){if(!l.setImmediate){var c,d,u,h,m=1,p={},g=!1,x=l.document,y=Object.getPrototypeOf&&Object.getPrototypeOf(l);y=y&&y.setTimeout?y:l,c={}.toString.call(l.process)==="[object process]"?function(C){process.nextTick(function(){_(C)})}:function(){if(l.postMessage&&!l.importScripts){var C=!0,A=l.onmessage;return l.onmessage=function(){C=!1},l.postMessage("","*"),l.onmessage=A,C}}()?(h="setImmediate$"+Math.random()+"$",l.addEventListener?l.addEventListener("message",j,!1):l.attachEvent("onmessage",j),function(C){l.postMessage(h+C,"*")}):l.MessageChannel?((u=new MessageChannel).port1.onmessage=function(C){_(C.data)},function(C){u.port2.postMessage(C)}):x&&"onreadystatechange"in x.createElement("script")?(d=x.documentElement,function(C){var A=x.createElement("script");A.onreadystatechange=function(){_(C),A.onreadystatechange=null,d.removeChild(A),A=null},d.appendChild(A)}):function(C){setTimeout(_,0,C)},y.setImmediate=function(C){typeof C!="function"&&(C=new Function(""+C));for(var A=new Array(arguments.length-1),M=0;M"u"?i===void 0?this:i:self)}).call(this,typeof jf<"u"?jf:typeof self<"u"?self:typeof window<"u"?window:{})},{}]},{},[10])(10)})})(XIt);var C9s=XIt.exports;const QIt=kd(C9s);function $Le(s,t=400,n=75){return s&&`${s.replace("/storage/v1/object/public/","/storage/v1/render/image/public/")}?width=${t}&quality=${n}&resize=contain`}const A9s=()=>{const{isAdmin:s}=ks(),[t,n]=k.useState(null),[r,a]=k.useState(null),[i,l]=k.useState("all"),[o,c]=k.useState(new Set),[d,u]=k.useState(!1),[h,m]=k.useState(!1),[p,g]=k.useState("images"),[x,y]=k.useState(null),{data:v=[],isLoading:_}=pt({queryKey:["social-swag-2"],queryFn:async()=>{const{data:me,error:Q}=await V.from("social_swag_2").select("*").order("month",{ascending:!1}).order("sort_order");if(Q)throw Q;return me}}),{data:j=[]}=pt({queryKey:["social-swag-2-months"],queryFn:async()=>{const{data:me,error:Q}=await V.from("social_swag_2_months").select("*").order("month",{ascending:!1});if(Q)throw Q;return me}}),{data:C=[]}=pt({queryKey:["social-swag-2-reels"],queryFn:async()=>{const{data:me,error:Q}=await V.from("social_swag_2_reels").select("*").order("month",{ascending:!1});if(Q)throw Q;return me}}),{data:A=[]}=pt({queryKey:["my-social-accounts-count"],queryFn:async()=>{const{data:me,error:Q}=await V.from("social_accounts").select("id, platform").eq("is_active",!0);if(Q)throw Q;return me||[]}}),M=A.length>0,I=k.useMemo(()=>i==="all"?null:C.find(me=>me.month===i)||null,[i,C]),P=k.useMemo(()=>[...new Set(v.map(Q=>Q.month))].sort((Q,te)=>te.localeCompare(Q)),[v]);k.useEffect(()=>{P.length>0&&i==="all"&&l(P[0])},[P,i]);const R=me=>{try{const Q=cGe(me,"yyyy-MM",new Date);return Ys(Q,"MMMM yyyy")}catch{return me}},O=k.useMemo(()=>i==="all"?v:v.filter(me=>me.month===i),[i,v]),B=k.useMemo(()=>{var me;return i==="all"?null:((me=j.find(Q=>Q.month===i))==null?void 0:me.canva_link)||null},[i,j]),U=async me=>{try{await navigator.clipboard.writeText(me),ae.success("Caption copied to clipboard!")}catch{ae.error("Failed to copy caption")}},G=async(me,Q)=>{try{const le=await(await fetch(me)).blob(),fe=/iPhone|iPad|iPod|Android/i.test(navigator.userAgent),_e=navigator.canShare&&navigator.canShare({files:[new File([le],"test.jpg",{type:"image/jpeg"})]});if(fe&&_e){const ve=new File([le],`social-swag-${Q}.jpg`,{type:"image/jpeg"});await navigator.share({files:[ve],title:"Social Swag Image"}),ae.success("Image ready to save!")}else{const ve=window.URL.createObjectURL(le),he=document.createElement("a");he.href=ve,he.download=`social-swag-${Q}.jpg`,document.body.appendChild(he),he.click(),document.body.removeChild(he),window.URL.revokeObjectURL(ve),ae.success("Image downloaded!")}}catch(te){te.name!=="AbortError"&&ae.error("Failed to download image")}},H=me=>{c(Q=>{const te=new Set(Q);return te.has(me)?te.delete(me):te.add(me),te})},Y=()=>{c(new Set(O.map(me=>me.id)))},se=()=>{c(new Set),u(!1)},ee=async()=>{const me=O.filter(Q=>o.has(Q.id));if(me.length===0){ae.error("No images selected");return}m(!0),ae.info(`Preparing ${me.length} images for download...`);try{const Q=new QIt,te=[...me].sort((he,Se)=>he.sort_order-Se.sort_order);for(let he=0;he{d?H(me.id):n(me)};return e.jsx(Xs,{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(qe,{variant:"secondary",className:"bg-white/20 text-white border-0 backdrop-blur-sm",children:[e.jsx(kn,{className:"h-3 w-3 mr-1"}),"New content monthly"]}),e.jsxs(qe,{variant:"secondary",className:"bg-white/20 text-white border-0 backdrop-blur-sm",children:[e.jsx(zc,{className:"h-3 w-3 mr-1"}),v.length," images"]})]}),e.jsx("h1",{className:"text-3xl md:text-4xl font-bold mb-3",children:"Social Swag 📸"}),e.jsx("p",{className:"text-lg text-primary-foreground/90 max-w-2xl",children:"Ready-to-post social media images delivered to you monthly. Just download, copy the caption, and share with your audience!"})]})]}),e.jsxs(ya,{defaultValue:"gallery",className:"space-y-6",children:[e.jsxs(va,{className:"grid w-full max-w-md grid-cols-2",children:[e.jsxs(is,{value:"gallery",className:"gap-2",children:[e.jsx(zc,{className:"h-4 w-4"}),"Gallery"]}),e.jsxs(is,{value:"scheduled",className:"gap-2",children:[e.jsx(fd,{className:"h-4 w-4"}),"Scheduled"]})]}),e.jsxs(cs,{value:"gallery",className:"space-y-6",children:[M?e.jsx(we,{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($,{variant:"outline",size:"sm",asChild:!0,className:"gap-2",children:e.jsx(nr,{to:"/mission-control/integrations",children:"Manage Accounts"})})]})})}):e.jsx(we,{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(ax,{className:"h-5 w-5 text-blue-600"})}),e.jsx("div",{className:"p-2 rounded-full bg-pink-500/10",children:e.jsx(Sf,{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($,{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(nr,{to:"/social-connections",children:[e.jsx(pd,{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:P.map(me=>e.jsx("button",{onClick:()=>l(me),className:Ot("px-4 py-2 rounded-full text-sm font-medium transition-all",i===me?"bg-primary text-primary-foreground shadow-sm":"bg-muted text-muted-foreground hover:text-foreground"),children:R(me)},me))}),i!=="all"&&(B?e.jsxs("a",{href:B,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-2 text-sm text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx("span",{className:"text-base",children:"🎨"}),"Edit ",R(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 ",R(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:()=>{g("images"),se()},className:Ot("flex items-center gap-2 px-4 py-2 rounded-full text-sm font-medium transition-all",p==="images"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"),children:[e.jsx(zc,{className:"h-4 w-4"}),"Images"]}),e.jsxs("button",{onClick:()=>{g("reels"),se()},className:Ot("flex items-center gap-2 px-4 py-2 rounded-full text-sm font-medium transition-all",p==="reels"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"),children:[e.jsx(em,{className:"h-4 w-4"}),"Reels"]})]}),p==="images"&&e.jsx("div",{className:"flex flex-wrap items-center gap-3",children:d?e.jsxs(e.Fragment,{children:[e.jsxs($,{variant:"outline",size:"sm",onClick:Y,className:"gap-2",children:["Select All (",O.length,")"]}),e.jsxs($,{variant:"outline",size:"sm",onClick:se,className:"gap-2",children:[e.jsx(mr,{className:"h-4 w-4"}),"Cancel"]}),o.size>0&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs($,{size:"sm",onClick:ee,disabled:h,className:"gap-2",children:[e.jsx(ji,{className:"h-4 w-4"}),h?"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($,{variant:"outline",size:"sm",onClick:()=>u(!0),className:"gap-2",children:[e.jsx(ma,{className:"h-4 w-4"}),"Select Images"]})})]}),_&&e.jsx("div",{className:"text-center py-12 text-muted-foreground",children:"Loading..."}),!_&&p==="images"&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4",children:O.map(me=>{const Q=o.has(me.id);return e.jsx(we,{className:Ot("group cursor-pointer overflow-hidden border-0 shadow-md hover:shadow-xl transition-all duration-300 rounded-2xl",d&&Q&&"ring-2 ring-primary ring-offset-2"),onClick:()=>oe(me),children:e.jsxs("div",{className:"relative aspect-[4/5] overflow-hidden",children:[e.jsx("img",{src:$Le(me.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"}),me.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:Ys(new Date(me.post_date+"T00:00:00"),"MMM d")})}),d&&e.jsx("div",{className:Ot("absolute top-2 right-2 w-6 h-6 rounded-full border-2 flex items-center justify-center transition-all",Q?"bg-primary border-primary text-primary-foreground":"bg-white/80 border-muted-foreground/50"),children:Q&&e.jsx(ma,{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"})})]})},me.id)})}),O.length===0&&e.jsxs("div",{className:"text-center py-12",children:[e.jsx(zc,{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."})]})]}),!_&&p==="reels"&&e.jsx(e.Fragment,{children:I?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(we,{className:"group overflow-hidden rounded-2xl cursor-pointer transition-all duration-300 hover:shadow-xl hover:scale-[1.02]",onClick:()=>a(I),children:e.jsxs("div",{className:"relative aspect-[9/16] overflow-hidden",children:[e.jsx("img",{src:$Le(I.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(qe,{variant:"secondary",className:"bg-black/50 text-white border-0 backdrop-blur-sm text-xs",children:[e.jsx(em,{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(em,{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(zs,{open:!!t,onOpenChange:()=>n(null),children:e.jsx(Rs,{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:$Le(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(ha,{className:"h-4 w-4"}),Ys(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(ha,{className:"h-3.5 w-3.5"}),"Post on ",Ys(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($,{onClick:()=>{y({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(Wr,{className:"h-4 w-4"}),"Create Post"]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsxs($,{variant:"outline",onClick:()=>U(t.caption),className:"flex-1 gap-2",children:[e.jsx(Da,{className:"h-4 w-4"}),"Copy Caption"]}),e.jsxs($,{variant:"outline",onClick:()=>G(t.image_url,t.id),className:"flex-1 gap-2",children:[e.jsx(ji,{className:"h-4 w-4"}),"Download"]})]})]})]})]})})})}),e.jsx(zs,{open:!!r,onOpenChange:()=>a(null),children:e.jsx(Rs,{className:"max-w-4xl max-h-[90vh] overflow-hidden p-0",children:e.jsx("div",{className:"max-h-[90vh] overflow-y-auto touch-pan-y",style:{WebkitOverflowScrolling:"touch"},children:r&&e.jsxs("div",{className:"flex flex-col md:flex-row",children:[e.jsx("div",{className:"md:w-1/2 bg-black flex items-center justify-center",children:e.jsx("div",{className:"aspect-[9/16] max-h-[70vh]",children:e.jsx("img",{src:r.image_url,alt:"Reel preview",className:"w-full h-full object-contain"})})}),e.jsxs("div",{className:"md:w-1/2 p-6 flex flex-col",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground mb-4",children:[e.jsx(em,{className:"h-4 w-4"}),"Monthly Reel"]}),r.caption&&e.jsxs("div",{className:"flex-1 min-h-0",children:[e.jsx("h4",{className:"text-sm font-medium text-foreground mb-2",children:"Caption"}),e.jsx("div",{className:"bg-muted/50 rounded-lg p-4 max-h-64 overflow-y-auto",children:e.jsx("p",{className:"text-sm text-foreground whitespace-pre-wrap",children:r.caption})})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3 mt-6",children:[r.caption&&e.jsxs($,{onClick:()=>U(r.caption||""),className:"flex-1 gap-2",children:[e.jsx(Da,{className:"h-4 w-4"}),"Copy Caption"]}),r.canva_link&&e.jsxs($,{variant:"outline",onClick:()=>window.open(r.canva_link,"_blank"),className:"flex-1 gap-2",children:[e.jsx(Ir,{className:"h-4 w-4"}),"Open in Canva"]})]})]})]})})})}),e.jsx(k9s,{open:!!x,onOpenChange:me=>!me&&y(null),imageUrl:(x==null?void 0:x.imageUrl)||"",imageId:(x==null?void 0:x.imageId)||"",defaultCaption:(x==null?void 0:x.caption)||"",swagItemId:x==null?void 0:x.imageId})]}),e.jsx(cs,{value:"scheduled",children:e.jsx(S9s,{})})]})]})})},E9s=[{id:"branding-bar",title:"Branding Bar Studio",description:"Drop in any image — get a branded version with your headshot, logo, and contact info.",icon:zc,to:"/marketing-studio/branding-bar",color:"from-violet-500 to-fuchsia-500"},{id:"listing-templates",title:"Listing Templates",description:"Just Listed, Just Sold, Open House, Price Drop — pulled from your MLS in one click.",icon:ua,to:"/marketing-studio/listing-templates",color:"from-blue-500 to-cyan-500"},{id:"personal-branding",title:"Personal Branding",description:'"Meet your agent", testimonials, milestones, pro tips — four editorial styles.',icon:el,to:"/marketing-studio/personal-branding",color:"from-emerald-500 to-teal-500"},{id:"market-updates",title:"Market Updates",description:"Auto-built from your MLS data — median price, days on market, year-over-year.",icon:Ul,comingSoon:!0,color:"from-orange-500 to-red-500"},{id:"milestones",title:"Client Milestones",description:"Closing day, home anniversaries, birthdays, referral thank-yous.",icon:ip,comingSoon:!0,color:"from-pink-500 to-rose-500"},{id:"holiday",title:"Holiday & Seasonal",description:"Pre-designed templates for every holiday, restyled to your brand.",icon:Hw,comingSoon:!0,color:"from-sky-500 to-indigo-500"},{id:"testimonial",title:"Testimonial Generator",description:"Paste a Zillow or Google review → branded testimonial graphic.",icon:v3,comingSoon:!0,color:"from-amber-500 to-yellow-500"}];function T9s(){return e.jsx(Xs,{title:"Marketing Studio",children:e.jsxs("div",{className:"container max-w-6xl py-8 space-y-6",children:[e.jsxs(Sc,{children:[e.jsx("title",{children:"Marketing Studio | LevelUp"}),e.jsx("meta",{name:"description",content:"Brand any image, video, listing, or milestone in seconds — no AI credits used."})]}),e.jsxs("div",{className:"flex flex-col md:flex-row md:items-end md:justify-between gap-4",children:[e.jsxs("div",{children:[e.jsxs(qe,{variant:"secondary",className:"mb-2 gap-1",children:[e.jsx(kn,{className:"h-3 w-3"})," New"]}),e.jsx("h1",{className:"text-3xl md:text-4xl font-bold tracking-tight",children:"Marketing Studio"}),e.jsx("p",{className:"text-muted-foreground max-w-2xl mt-1",children:"Your one-stop creative hub. Drop in any photo or video, and walk away with a fully branded export — no design skills, no AI credits."})]}),e.jsx($,{variant:"outline",asChild:!0,children:e.jsxs(nr,{to:"/marketing-studio/brand-kit",children:[e.jsx(gd,{className:"h-4 w-4 mr-1"})," Manage Brand Kit"]})})]}),e.jsx("div",{className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-3",children:E9s.map(s=>{const t=s.icon,n=e.jsxs(we,{className:`group relative overflow-hidden transition-all h-full ${s.comingSoon?"opacity-70":"hover:shadow-xl hover:-translate-y-0.5 cursor-pointer"}`,children:[e.jsx("div",{className:`absolute inset-x-0 top-0 h-1 bg-gradient-to-r ${s.color}`}),e.jsxs(De,{className:"p-5 space-y-3",children:[e.jsx("div",{className:`inline-flex h-10 w-10 items-center justify-center rounded-lg bg-gradient-to-br ${s.color} text-white shadow-md`,children:e.jsx(t,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"font-semibold",children:s.title}),s.comingSoon&&e.jsx(qe,{variant:"outline",className:"text-[10px]",children:"Coming soon"})]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:s.description})]})]})]});return s.to&&!s.comingSoon?e.jsx(nr,{to:s.to,className:"block",children:n},s.id):e.jsx("div",{children:n},s.id)})})]})})}function Bee(){const s=ai();return pt({queryKey:["marketing-brand-presets",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await V.from("marketing_brand_presets").select("*").eq("user_id",s).order("is_default",{ascending:!1}).order("created_at",{ascending:!0});if(n)throw n;return t||[]},enabled:!!s})}function M9s(){const{data:s,...t}=Bee();return{data:(s==null?void 0:s.find(n=>n.is_default))??(s==null?void 0:s[0])??null,...t}}function P9s(){const s=ai(),t=ls();return Nt({mutationFn:async n=>{if(!s)throw new Error("Not signed in");if(n.is_default&&await V.from("marketing_brand_presets").update({is_default:!1}).eq("user_id",s),n.id){const{id:r,...a}=n,{data:i,error:l}=await V.from("marketing_brand_presets").update(a).eq("id",r).eq("user_id",s).select().single();if(l)throw l;return i}else{const{data:r,error:a}=await V.from("marketing_brand_presets").insert({...n,user_id:s}).select().single();if(a)throw a;return r}},onSuccess:()=>t.invalidateQueries({queryKey:["marketing-brand-presets",s]})})}function I9s(){const s=ai(),t=ls();return Nt({mutationFn:async n=>{const{error:r}=await V.from("marketing_brand_presets").delete().eq("id",n);if(r)throw r},onSuccess:()=>t.invalidateQueries({queryKey:["marketing-brand-presets",s]})})}async function L9s(s,t,n){var o;const r=((o=t.name.split(".").pop())==null?void 0:o.toLowerCase())||"png",a=`${s}/${n}-${Date.now()}.${r}`,{error:i}=await V.storage.from("marketing-studio-uploads").upload(a,t,{upsert:!0,cacheControl:"3600"});if(i)throw i;const{data:l}=await V.storage.from("marketing-studio-uploads").createSignedUrl(a,60*60*24*365*5);return(l==null?void 0:l.signedUrl)??""}function R9s({preset:s,onSaved:t,onCancel:n}){var x;const r=ai(),a=P9s(),i=I9s(),l=k.useRef(null),o=k.useRef(null),[c,d]=k.useState(null),[u,h]=k.useState({name:(s==null?void 0:s.name)??"My Brand",is_default:(s==null?void 0:s.is_default)??!0,display_name:(s==null?void 0:s.display_name)??"",phone:(s==null?void 0:s.phone)??"",email:(s==null?void 0:s.email)??"",license_number:(s==null?void 0:s.license_number)??"",tagline:(s==null?void 0:s.tagline)??"",website_url:(s==null?void 0:s.website_url)??"",headshot_url:(s==null?void 0:s.headshot_url)??"",brokerage_logo_url:(s==null?void 0:s.brokerage_logo_url)??"",brand_color:(s==null?void 0:s.brand_color)??"#0f172a",accent_color:(s==null?void 0:s.accent_color)??"#3b82f6"});k.useEffect(()=>{s||(async()=>{if(!r)return;const{supabase:y}=await Ai(async()=>{const{supabase:_}=await Promise.resolve().then(()=>jus);return{supabase:_}},void 0),{data:v}=await y.from("profiles").select("name, email, phone, avatar_url, website_url, title, brokerage_id").eq("id",r).maybeSingle();v&&h(_=>({..._,display_name:_.display_name||(v.name??""),email:_.email||(v.email??""),phone:_.phone||(v.phone??""),headshot_url:_.headshot_url||(v.avatar_url??""),website_url:_.website_url||(v.website_url??""),tagline:_.tagline||(v.title??"")}))})()},[r]);const m=async(y,v)=>{if(r){d(y);try{const _=await L9s(r,v,y);h(j=>({...j,[y==="headshot"?"headshot_url":"brokerage_logo_url"]:_}))}catch(_){ae.error(_.message||"Upload failed")}finally{d(null)}}},p=async()=>{try{const y=await a.mutateAsync({id:s==null?void 0:s.id,...u});ae.success("Brand preset saved"),t==null||t(y)}catch(y){ae.error(y.message||"Save failed")}},g=async()=>{s!=null&&s.id&&await io("Delete this brand preset?")&&(await i.mutateAsync(s.id),ae.success("Preset deleted"),n==null||n())};return e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Preset name"}),e.jsx(be,{value:u.name,onChange:y=>h({...u,name:y.target.value}),placeholder:"Personal, Team, Luxury..."})]}),e.jsxs("div",{className:"flex items-end gap-3 pb-1",children:[e.jsx(On,{checked:u.is_default,onCheckedChange:y=>h({...u,is_default:y})}),e.jsx(re,{children:"Use as default"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Display name"}),e.jsx(be,{value:u.display_name,onChange:y=>h({...u,display_name:y.target.value})})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Phone"}),e.jsx(be,{value:u.phone,onChange:y=>h({...u,phone:y.target.value})})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Email"}),e.jsx(be,{value:u.email,onChange:y=>h({...u,email:y.target.value})})]}),e.jsxs("div",{children:[e.jsx(re,{children:"License #"}),e.jsx(be,{value:u.license_number,onChange:y=>h({...u,license_number:y.target.value})})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(re,{children:"Tagline"}),e.jsx(be,{value:u.tagline,onChange:y=>h({...u,tagline:y.target.value}),placeholder:"Helping families find home"})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(re,{children:"Website"}),e.jsx(be,{value:u.website_url,onChange:y=>h({...u,website_url:y.target.value})})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Headshot"}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(Wa,{className:"h-16 w-16",children:[e.jsx(eo,{src:u.headshot_url||void 0}),e.jsx(Ka,{children:((x=u.display_name)==null?void 0:x[0])??"A"})]}),e.jsxs($,{type:"button",variant:"outline",size:"sm",onClick:()=>{var y;return(y=l.current)==null?void 0:y.click()},disabled:c==="headshot",children:[c==="headshot"?e.jsx(Jt,{className:"h-4 w-4 animate-spin"}):e.jsx(gi,{className:"h-4 w-4 mr-1"}),"Upload"]}),e.jsx("input",{ref:l,type:"file",accept:"image/*",hidden:!0,onChange:y=>{var v;return((v=y.target.files)==null?void 0:v[0])&&m("headshot",y.target.files[0])}})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Brokerage logo"}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-16 w-24 bg-muted rounded flex items-center justify-center overflow-hidden border",children:u.brokerage_logo_url?e.jsx("img",{src:u.brokerage_logo_url,alt:"logo",className:"max-h-full max-w-full object-contain"}):e.jsx("span",{className:"text-xs text-muted-foreground",children:"No logo"})}),e.jsxs($,{type:"button",variant:"outline",size:"sm",onClick:()=>{var y;return(y=o.current)==null?void 0:y.click()},disabled:c==="logo",children:[c==="logo"?e.jsx(Jt,{className:"h-4 w-4 animate-spin"}):e.jsx(gi,{className:"h-4 w-4 mr-1"}),"Upload"]}),e.jsx("input",{ref:o,type:"file",accept:"image/*",hidden:!0,onChange:y=>{var v;return((v=y.target.files)==null?void 0:v[0])&&m("logo",y.target.files[0])}})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Brand color"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"color",value:u.brand_color,onChange:y=>h({...u,brand_color:y.target.value}),className:"h-10 w-14 rounded cursor-pointer border"}),e.jsx(be,{value:u.brand_color,onChange:y=>h({...u,brand_color:y.target.value})})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Accent color"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"color",value:u.accent_color,onChange:y=>h({...u,accent_color:y.target.value}),className:"h-10 w-14 rounded cursor-pointer border"}),e.jsx(be,{value:u.accent_color,onChange:y=>h({...u,accent_color:y.target.value})})]})]})]}),e.jsxs("div",{className:"flex justify-between pt-2",children:[e.jsx("div",{children:(s==null?void 0:s.id)&&e.jsxs($,{variant:"ghost",size:"sm",onClick:g,className:"text-destructive",children:[e.jsx(Un,{className:"h-4 w-4 mr-1"})," Delete"]})}),e.jsxs("div",{className:"flex gap-2",children:[n&&e.jsx($,{variant:"outline",onClick:n,children:"Cancel"}),e.jsxs($,{onClick:p,disabled:a.isPending,children:[a.isPending&&e.jsx(Jt,{className:"h-4 w-4 mr-1 animate-spin"}),"Save preset"]})]})]})]})}function D9s(){const{data:s,isLoading:t}=Bee(),[n,r]=k.useState(null);return e.jsx(Xs,{title:"Brand Kit",children:e.jsxs("div",{className:"container max-w-5xl py-6 md:py-8 space-y-6 px-4",children:[e.jsx(Sc,{children:e.jsx("title",{children:"Brand Kit | Marketing Studio"})}),e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs(nr,{to:"/marketing-studio",className:"text-sm text-muted-foreground inline-flex items-center gap-1 hover:underline",children:[e.jsx(Ia,{className:"h-3 w-3"})," Back to Marketing Studio"]}),e.jsx("h1",{className:"text-2xl md:text-3xl font-bold tracking-tight mt-1",children:"Brand Kit"}),e.jsx("p",{className:"text-sm md:text-base text-muted-foreground",children:"Save your branding once — apply it across every Marketing Studio module."})]}),e.jsxs($,{onClick:()=>r("new"),className:"w-full sm:w-auto",children:[e.jsx(nn,{className:"h-4 w-4 mr-1"})," New preset"]})]}),t&&e.jsx("div",{className:"text-sm text-muted-foreground",children:"Loading..."}),!t&&s&&s.length===0&&e.jsx(we,{className:"border-dashed",children:e.jsxs(De,{className:"py-12 text-center space-y-3",children:[e.jsx("h3",{className:"font-semibold",children:"Create your first brand preset"}),e.jsx("p",{className:"text-sm text-muted-foreground max-w-md mx-auto",children:"We'll pre-fill from your profile. You can have multiple presets — Personal, Team, Luxury division — and switch between them."}),e.jsxs($,{onClick:()=>r("new"),children:[e.jsx(nn,{className:"h-4 w-4 mr-1"})," Create preset"]})]})}),e.jsx("div",{className:"grid gap-4 md:grid-cols-2",children:s==null?void 0:s.map(a=>e.jsxs(we,{className:"overflow-hidden",children:[e.jsx("div",{className:"h-3",style:{background:`linear-gradient(90deg, ${a.brand_color}, ${a.accent_color})`}}),e.jsxs(Vt,{className:"pb-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(Yt,{className:"text-lg flex items-center gap-2",children:[a.name,a.is_default&&e.jsxs(qe,{variant:"secondary",className:"gap-1",children:[e.jsx(ri,{className:"h-3 w-3"})," Default"]})]}),e.jsx($,{size:"sm",variant:"ghost",onClick:()=>r(a),children:e.jsx(ui,{className:"h-4 w-4"})})]}),e.jsx(vr,{children:a.display_name})]}),e.jsxs(De,{className:"text-sm text-muted-foreground space-y-1",children:[a.tagline&&e.jsxs("div",{className:"italic",children:['"',a.tagline,'"']}),a.phone&&e.jsx("div",{children:a.phone}),a.email&&e.jsx("div",{children:a.email})]})]},a.id))}),e.jsx(zs,{open:n!==null,onOpenChange:a=>!a&&r(null),children:e.jsxs(Rs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto w-[calc(100vw-2rem)] sm:w-full",children:[e.jsx(Vs,{children:e.jsx($s,{children:n==="new"?"New brand preset":"Edit brand preset"})}),e.jsx(R9s,{preset:n==="new"?null:n,onSaved:()=>r(null),onCancel:()=>r(null)})]})})]})})}const $9e=[{id:"minimal-stripe",name:"Minimal Stripe",description:"Thin bottom strip with name + phone",appliesTo:["image","video"],position:"bottom",heightRatio:.085,background:"brand",fields:["headshot","name","phone"],circularHeadshot:!0,textColor:"auto"},{id:"full-footer",name:"Full Footer",description:"Generous footer with logo, tagline, and full contact",appliesTo:["image","video"],position:"bottom",heightRatio:.16,background:"brand",fields:["headshot","name","tagline","phone","email","logo"],circularHeadshot:!0,textColor:"auto"},{id:"corner-badge",name:"Corner Badge",description:"Subtle headshot + name in the bottom-right corner",appliesTo:["image","video"],position:"corner-br",heightRatio:.18,background:"gradient",fields:["headshot","name","phone"],circularHeadshot:!0,textColor:"light"},{id:"side-rail",name:"Side Rail",description:"Vertical strip on the right — great for stories",appliesTo:["image","video"],position:"side-right",heightRatio:.18,background:"brand",fields:["headshot","name","phone","logo"],circularHeadshot:!0,textColor:"auto"},{id:"letterbox",name:"Letterbox",description:"Cinematic top + bottom bars with logo and name",appliesTo:["image","video"],position:"letterbox",heightRatio:.09,background:"dark",fields:["headshot","name","phone","logo"],circularHeadshot:!0,textColor:"light"},{id:"top-banner",name:"Top Banner",description:"Bold banner across the top with logo and contact",appliesTo:["image","video"],position:"top",heightRatio:.1,background:"brand",fields:["logo","name","phone"],textColor:"auto"}],O9s=s=>$9e.find(t=>t.id===s)??$9e[0];function F9s(s){if(!s)return"#ffffff";const t=s.replace("#","");if(t.length!==6)return"#ffffff";const n=parseInt(t.slice(0,2),16),r=parseInt(t.slice(2,4),16),a=parseInt(t.slice(4,6),16);return(n*299+r*587+a*114)/1e3>=150?"#0f172a":"#ffffff"}function z9s({value:s,onChange:t,mediaType:n}){const r=$9e.filter(a=>a.appliesTo.includes(n));return e.jsx("div",{className:"grid grid-cols-2 gap-2",children:r.map(a=>e.jsxs("button",{type:"button",onClick:()=>t(a.id),className:Ot("text-left rounded-lg border p-3 transition-all hover:border-primary/50",s===a.id&&"border-primary ring-2 ring-primary/20 bg-primary/5"),children:[e.jsx(B9s,{style:a}),e.jsx("div",{className:"mt-2 text-sm font-medium",children:a.name}),e.jsx("div",{className:"text-xs text-muted-foreground line-clamp-1",children:a.description})]},a.id))})}function B9s({style:s}){const t="#cbd5e1",n="#0f172a";return e.jsxs("div",{className:"aspect-video w-full rounded relative overflow-hidden",style:{background:t},children:[s.position==="bottom"&&e.jsx("div",{className:"absolute left-0 right-0 bottom-0",style:{height:`${s.heightRatio*100}%`,background:n}}),s.position==="top"&&e.jsx("div",{className:"absolute left-0 right-0 top-0",style:{height:`${s.heightRatio*100}%`,background:n}}),s.position==="corner-br"&&e.jsx("div",{className:"absolute bottom-2 right-2 w-1/3 h-1/3 rounded",style:{background:n,opacity:.85}}),s.position==="side-right"&&e.jsx("div",{className:"absolute top-0 bottom-0 right-0",style:{width:`${s.heightRatio*100}%`,background:n}}),s.position==="letterbox"&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"absolute left-0 right-0 top-0",style:{height:`${s.heightRatio*100}%`,background:n}}),e.jsx("div",{className:"absolute left-0 right-0 bottom-0",style:{height:`${s.heightRatio*100}%`,background:n}})]})]})}const $9s=Math.PI/180;function U9s(){return typeof window<"u"&&({}.toString.call(window)==="[object Window]"||{}.toString.call(window)==="[object global]")}const hD=typeof global<"u"?global:typeof window<"u"?window:typeof WorkerGlobalScope<"u"?self:{},di={_global:hD,version:"10.3.1",isBrowser:U9s(),isUnminified:/param/.test((function(s){}).toString()),dblClickWindow:400,getAngle(s){return di.angleDeg?s*$9s:s},enableTrace:!1,pointerEventsEnabled:!0,autoDrawEnabled:!0,hitOnDragEnabled:!1,capturePointerEventsEnabled:!1,_mouseListenClick:!1,_touchListenClick:!1,_pointerListenClick:!1,_mouseInDblClickWindow:!1,_touchInDblClickWindow:!1,_pointerInDblClickWindow:!1,_mouseDblClickPointerId:null,_touchDblClickPointerId:null,_pointerDblClickPointerId:null,_renderBackend:"web",legacyTextRendering:!1,pixelRatio:typeof window<"u"&&window.devicePixelRatio||1,dragDistance:3,angleDeg:!0,showWarnings:!0,dragButtons:[0,1],isDragging(){return di.DD.isDragging},isTransforming(){var s,t;return(t=(s=di.Transformer)===null||s===void 0?void 0:s.isTransforming())!==null&&t!==void 0?t:!1},isDragReady(){return!!di.DD.node},releaseCanvasOnDestroy:!0,document:hD.document,_injectGlobal(s){typeof hD.Konva<"u"&&console.error("Several Konva instances detected. It is not recommended to use multiple Konva instances in the same environment."),hD.Konva=s}},Hp=s=>{di[s.prototype.getClassName()]=s};di._injectGlobal(di);const q9s=`Konva.js unsupported environment. Looks like you are trying to use Konva.js in Node.js environment. because "document" object is undefined. To use Konva.js in Node.js environment, you need to use the "canvas-backend" or "skia-backend" module. bash: npm install canvas js: import "konva/canvas-backend"; or bash: npm install skia-canvas js: import "konva/skia-backend"; `,Zut=()=>{if(typeof document>"u")throw new Error(q9s)};class Uw{constructor(t=[1,0,0,1,0,0]){this.dirty=!1,this.m=t&&t.slice()||[1,0,0,1,0,0]}reset(){this.m[0]=1,this.m[1]=0,this.m[2]=0,this.m[3]=1,this.m[4]=0,this.m[5]=0}copy(){return new Uw(this.m)}copyInto(t){t.m[0]=this.m[0],t.m[1]=this.m[1],t.m[2]=this.m[2],t.m[3]=this.m[3],t.m[4]=this.m[4],t.m[5]=this.m[5]}point(t){const n=this.m;return{x:n[0]*t.x+n[2]*t.y+n[4],y:n[1]*t.x+n[3]*t.y+n[5]}}translate(t,n){return this.m[4]+=this.m[0]*t+this.m[2]*n,this.m[5]+=this.m[1]*t+this.m[3]*n,this}scale(t,n){return this.m[0]*=t,this.m[1]*=t,this.m[2]*=n,this.m[3]*=n,this}rotate(t){const n=Math.cos(t),r=Math.sin(t),a=this.m[0]*n+this.m[2]*r,i=this.m[1]*n+this.m[3]*r,l=this.m[0]*-r+this.m[2]*n,o=this.m[1]*-r+this.m[3]*n;return this.m[0]=a,this.m[1]=i,this.m[2]=l,this.m[3]=o,this}getTranslation(){return{x:this.m[4],y:this.m[5]}}skew(t,n){const r=this.m[0]+this.m[2]*n,a=this.m[1]+this.m[3]*n,i=this.m[2]+this.m[0]*t,l=this.m[3]+this.m[1]*t;return this.m[0]=r,this.m[1]=a,this.m[2]=i,this.m[3]=l,this}multiply(t){const n=this.m[0]*t.m[0]+this.m[2]*t.m[1],r=this.m[1]*t.m[0]+this.m[3]*t.m[1],a=this.m[0]*t.m[2]+this.m[2]*t.m[3],i=this.m[1]*t.m[2]+this.m[3]*t.m[3],l=this.m[0]*t.m[4]+this.m[2]*t.m[5]+this.m[4],o=this.m[1]*t.m[4]+this.m[3]*t.m[5]+this.m[5];return this.m[0]=n,this.m[1]=r,this.m[2]=a,this.m[3]=i,this.m[4]=l,this.m[5]=o,this}invert(){const t=1/(this.m[0]*this.m[3]-this.m[1]*this.m[2]),n=this.m[3]*t,r=-this.m[1]*t,a=-this.m[2]*t,i=this.m[0]*t,l=t*(this.m[2]*this.m[5]-this.m[3]*this.m[4]),o=t*(this.m[1]*this.m[4]-this.m[0]*this.m[5]);return this.m[0]=n,this.m[1]=r,this.m[2]=a,this.m[3]=i,this.m[4]=l,this.m[5]=o,this}getMatrix(){return this.m}decompose(){const t=this.m[0],n=this.m[1],r=this.m[2],a=this.m[3],i=this.m[4],l=this.m[5],o=t*a-n*r,c={x:i,y:l,rotation:0,scaleX:0,scaleY:0,skewX:0,skewY:0};if(t!=0||n!=0){const d=Math.sqrt(t*t+n*n);c.rotation=n>0?Math.acos(t/d):-Math.acos(t/d),c.scaleX=d,c.scaleY=o/d,c.skewX=(t*r+n*a)/o,c.skewY=0}else if(r!=0||a!=0){const d=Math.sqrt(r*r+a*a);c.rotation=Math.PI/2-(a>0?Math.acos(-r/d):-Math.acos(r/d)),c.scaleX=o/d,c.scaleY=d,c.skewX=0,c.skewY=(t*r+n*a)/o}return c.rotation=ir._getRotation(c.rotation),c}}const V9s="[object Array]",H9s="[object Number]",G9s="[object String]",W9s="[object Boolean]",K9s=Math.PI/180,JIt=180/Math.PI,Ire="#",Y9s="",Z9s="0",X9s="Konva warning: ",Xut="Konva error: ",Q9s={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,134,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,250,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,221],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[112,128,144],slategrey:[112,128,144],snow:[255,250,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],transparent:[255,255,255,0],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,50]};let Lre=[],gG=null;const J9s=typeof requestAnimationFrame<"u"&&requestAnimationFrame||function(s){setTimeout(s,16)},Qut=new Map,Jut=s=>{const t=s.trim();return t.indexOf(",")===-1?t.split(/\s*\/\s*|\s+/):t.split(/\s*,\s*/)},eLt="[+-]?(?:\\d+\\.?\\d*|\\.\\d+)(?:e[+-]?\\d+)?",ezs=new RegExp(`^(${eLt})(%?)$`,"i"),oP=(s,t)=>{const n=ezs.exec(s);return n?n[2]?Number(n[1])/100*t:Number(n[1]):NaN},Rre=/^#[0-9a-f]+$/i,eht=s=>Math.min(Math.max(s,0),1),tzs=new RegExp(`^(${eLt})(deg|grad|rad|turn)?$`,"i"),szs={deg:1,grad:.9,rad:JIt,turn:360},ir={_isElement(s){return!!(s&&s.nodeType==1)},_isFunction(s){return!!(s&&s.constructor&&s.call&&s.apply)},_isPlainObject(s){return!!s&&s.constructor===Object},_isArray(s){return Object.prototype.toString.call(s)===V9s},_isNumber(s){return Object.prototype.toString.call(s)===H9s&&!isNaN(s)&&isFinite(s)},_isString(s){return Object.prototype.toString.call(s)===G9s},_isBoolean(s){return Object.prototype.toString.call(s)===W9s},isObject(s){return s instanceof Object},isValidSelector(s){if(typeof s!="string")return!1;const t=s[0];return t==="#"||t==="."||t===t.toUpperCase()},_sign(s){return s===0||s>0?1:-1},requestAnimFrame(s){Lre.push(s),Lre.length===1&&J9s(function(){const t=Lre;Lre=[],t.forEach(function(n){n()})})},createCanvasElement(){Zut();const s=document.createElement("canvas");try{s.style=s.style||{}}catch{}return s},createImageElement(){return Zut(),document.createElement("img")},_isInDocument(s){for(;s=s.parentNode;)if(s==document)return!0;return!1},_urlToImage(s,t){const n=ir.createImageElement();n.onload=function(){t(n)},n.src=s},_rgbToHex(s,t,n){return((1<<24)+(s<<16)+(t<<8)+n).toString(16).slice(1)},_hexToRgb(s){s=s.replace(Ire,Y9s);const t=parseInt(s,16);return{r:t>>16&255,g:t>>8&255,b:t&255}},getRandomColor(){let s=(Math.random()*16777215<<0).toString(16);for(;s.length<6;)s=Z9s+s;return Ire+s},isCanvasFarblingActive(){if(gG!==null)return gG;if(typeof document>"u")return gG=!1,!1;const s=this.createCanvasElement();s.width=10,s.height=10;const t=s.getContext("2d",{willReadFrequently:!0});t.clearRect(0,0,10,10),t.fillStyle="#282828",t.fillRect(0,0,10,10);const n=t.getImageData(0,0,10,10).data;let r=!1;for(let a=0;a<100;a++)if(n[a*4]!==40||n[a*4+1]!==40||n[a*4+2]!==40||n[a*4+3]!==255){r=!0;break}return gG=r,this.releaseCanvas(s),gG},getHitColor(){const s=this.getRandomColor();return this.isCanvasFarblingActive()?this.getSnappedHexColor(s):s},getHitColorKey(s,t,n){return this.isCanvasFarblingActive()&&(s=Math.round(s/5)*5,t=Math.round(t/5)*5,n=Math.round(n/5)*5),Ire+this._rgbToHex(s,t,n)},getSnappedHexColor(s){const t=this._hexToRgb(s);return Ire+this._rgbToHex(Math.round(t.r/5)*5,Math.round(t.g/5)*5,Math.round(t.b/5)*5)},getRGB(s){var t;const{r:n=0,g:r=0,b:a=0}=(t=ir.colorToRGBA(s))!==null&&t!==void 0?t:{};return{r:n,g:r,b:a}},colorToRGBA(s){s=(s||"").trim()||"black";const t=ir._namedColorToRBA(s)||ir._hex3ColorToRGBA(s)||ir._hex4ColorToRGBA(s)||ir._hex6ColorToRGBA(s)||ir._hex8ColorToRGBA(s)||ir._rgbColorToRGBA(s)||ir._hslColorToRGBA(s);if(t&&[t.r,t.g,t.b,t.a].every(ir._isNumber))return t},_namedColorToRBA(s){const t=Q9s[s.toLowerCase()];return t?{r:t[0],g:t[1],b:t[2],a:t.length>3?t[3]:1}:null},_rgbColorToRGBA(s){const t=/^rgba?\(([^)]*)\)$/i.exec(s);if(!t)return;const n=Jut(t[1]);if(!(n.length<3||n.length>4))return{r:oP(n[0],255),g:oP(n[1],255),b:oP(n[2],255),a:n.length>3?oP(n[3],1):1}},_hex8ColorToRGBA(s){if(s.length===9&&Rre.test(s))return{r:parseInt(s.slice(1,3),16),g:parseInt(s.slice(3,5),16),b:parseInt(s.slice(5,7),16),a:parseInt(s.slice(7,9),16)/255}},_hex6ColorToRGBA(s){if(s.length===7&&Rre.test(s))return{r:parseInt(s.slice(1,3),16),g:parseInt(s.slice(3,5),16),b:parseInt(s.slice(5,7),16),a:1}},_hex4ColorToRGBA(s){if(s.length===5&&Rre.test(s))return{r:parseInt(s[1]+s[1],16),g:parseInt(s[2]+s[2],16),b:parseInt(s[3]+s[3],16),a:parseInt(s[4]+s[4],16)/255}},_hex3ColorToRGBA(s){if(s.length===4&&Rre.test(s))return{r:parseInt(s[1]+s[1],16),g:parseInt(s[2]+s[2],16),b:parseInt(s[3]+s[3],16),a:1}},_hslColorToRGBA(s){const t=/^hsla?\(([^)]*)\)$/i.exec(s);if(!t)return;const n=Jut(t[1]);if(n.length<3||n.length>4)return;const r=tzs.exec(n[0]);if(!r)return;const a=r[2],i=Number(r[1])*(a?szs[a.toLowerCase()]:1);if(!isFinite(i))return;const l=(i%360+360)%360/360,o=eht(oP(n[1],100)/100),c=eht(oP(n[2],100)/100),d=n.length>3?oP(n[3],1):1,u=c<.5?c*(1+o):c+o-c*o,h=2*c-u,m=[0,0,0];for(let p=0;p<3;p++){let g=l+.3333333333333333*-(p-1);g<0&&g++,g>1&&g--;let x;6*g<1?x=h+(u-h)*6*g:2*g<1?x=u:3*g<2?x=h+(u-h)*(2/3-g)*6:x=h,m[p]=x*255}return{r:Math.round(m[0]),g:Math.round(m[1]),b:Math.round(m[2]),a:d}},haveIntersection(s,t){return!(t.x>s.x+s.width||t.x+t.widths.y+s.height||t.y+t.height1?(l=n,o=r,c=(n-a)*(n-a)+(r-i)*(r-i)):(l=s+u*(n-s),o=t+u*(r-t),c=(l-a)*(l-a)+(o-i)*(o-i))}return[l,o,c]},_getProjectionToLine(s,t,n){const r=ir.cloneObject(s);let a=Number.MAX_VALUE;return t.forEach(function(i,l){if(!n&&l===t.length-1)return;const o=t[(l+1)%t.length],c=ir._getProjectionToSegment(i.x,i.y,o.x,o.y,s.x,s.y),d=c[0],u=c[1],h=c[2];ht.length){const l=t;t=s,s=l}for(let l=0;l{t.width=0,t.height=0})},drawRoundedRectPath(s,t,n,r){let a=t<0?t:0,i=n<0?n:0;t=Math.abs(t),n=Math.abs(n);let l=0,o=0,c=0,d=0;typeof r=="number"?l=o=c=d=Math.min(r,t/2,n/2):(l=Math.min(r[0]||0,t/2,n/2),o=Math.min(r[1]||0,t/2,n/2),d=Math.min(r[2]||0,t/2,n/2),c=Math.min(r[3]||0,t/2,n/2)),s.moveTo(a+l,i),s.lineTo(a+t-o,i),s.arc(a+t-o,i+o,o,Math.PI*3/2,0,!1),s.lineTo(a+t,i+n-d),s.arc(a+t-d,i+n-d,d,0,Math.PI/2,!1),s.lineTo(a+c,i+n),s.arc(a+c,i+n-c,c,Math.PI/2,Math.PI,!1),s.lineTo(a,i+l),s.arc(a+l,i+l,l,Math.PI,Math.PI*3/2,!1)},drawRoundedPolygonPath(s,t,n,r,a){r=Math.abs(r);for(let i=0;itypeof u=="number"?Math.floor(u):u)),i+=rzs+d.join(tht)+azs)):(i+=o.property,t||(i+=dzs+o.val)),i+=lzs;return i}clearTrace(){this.traceArr=[]}_trace(t){let n=this.traceArr,r;n.push(t),r=n.length,r>=hzs&&n.shift()}reset(){const t=this.getCanvas().getPixelRatio();this.setTransform(1*t,0,0,1*t,0,0)}getCanvas(){return this.canvas}clear(t){const n=this.getCanvas();t?this.clearRect(t.x||0,t.y||0,t.width||0,t.height||0):this.clearRect(0,0,n.getWidth()/n.pixelRatio,n.getHeight()/n.pixelRatio)}_applyLineCap(t){const n=t.attrs.lineCap;n&&this.setAttr("lineCap",n)}_applyOpacity(t){const n=t.getAbsoluteOpacity();n!==1&&this.setAttr("globalAlpha",n)}_applyLineJoin(t){const n=t.attrs.lineJoin;n&&this.setAttr("lineJoin",n)}_applyMiterLimit(t){const n=t.attrs.miterLimit;n!=null&&this.setAttr("miterLimit",n)}setAttr(t,n){this._context[t]=n}arc(t,n,r,a,i,l){this._context.arc(t,n,r,a,i,l)}arcTo(t,n,r,a,i){this._context.arcTo(t,n,r,a,i)}beginPath(){this._context.beginPath()}bezierCurveTo(t,n,r,a,i,l){this._context.bezierCurveTo(t,n,r,a,i,l)}clearRect(t,n,r,a){this._context.clearRect(t,n,r,a)}clip(...t){this._context.clip.apply(this._context,t)}closePath(){this._context.closePath()}createImageData(t,n){const r=arguments;if(r.length===2)return this._context.createImageData(t,n);if(r.length===1)return this._context.createImageData(t)}createLinearGradient(t,n,r,a){return this._context.createLinearGradient(t,n,r,a)}createPattern(t,n){return this._context.createPattern(t,n)}createRadialGradient(t,n,r,a,i,l){return this._context.createRadialGradient(t,n,r,a,i,l)}drawImage(t,n,r,a,i,l,o,c,d){const u=arguments,h=this._context;u.length===3?h.drawImage(t,n,r):u.length===5?h.drawImage(t,n,r,a,i):u.length===9&&h.drawImage(t,n,r,a,i,l,o,c,d)}ellipse(t,n,r,a,i,l,o,c){this._context.ellipse(t,n,r,a,i,l,o,c)}isPointInPath(t,n,r,a){return r?this._context.isPointInPath(r,t,n,a):this._context.isPointInPath(t,n,a)}fill(...t){this._context.fill.apply(this._context,t)}fillRect(t,n,r,a){this._context.fillRect(t,n,r,a)}strokeRect(t,n,r,a){this._context.strokeRect(t,n,r,a)}fillText(t,n,r,a){a?this._context.fillText(t,n,r,a):this._context.fillText(t,n,r)}measureText(t){return this._context.measureText(t)}getImageData(t,n,r,a){return this._context.getImageData(t,n,r,a)}lineTo(t,n){this._context.lineTo(t,n)}moveTo(t,n){this._context.moveTo(t,n)}rect(t,n,r,a){this._context.rect(t,n,r,a)}roundRect(t,n,r,a,i){this._context.roundRect(t,n,r,a,i)}putImageData(t,n,r){this._context.putImageData(t,n,r)}quadraticCurveTo(t,n,r,a){this._context.quadraticCurveTo(t,n,r,a)}restore(){this._context.restore()}rotate(t){this._context.rotate(t)}save(){this._context.save()}scale(t,n){this._context.scale(t,n)}setLineDash(t){this._context.setLineDash?this._context.setLineDash(t):"mozDash"in this._context?this._context.mozDash=t:"webkitLineDash"in this._context&&(this._context.webkitLineDash=t)}getLineDash(){return this._context.getLineDash()}setTransform(t,n,r,a,i,l){this._context.setTransform(t,n,r,a,i,l)}stroke(t){t?this._context.stroke(t):this._context.stroke()}strokeText(t,n,r,a){this._context.strokeText(t,n,r,a)}transform(t,n,r,a,i,l){this._context.transform(t,n,r,a,i,l)}translate(t,n){this._context.translate(t,n)}_enableTrace(){let t=this,n=sht.length,r=this.setAttr,a,i;const l=function(o){let c=t[o],d;t[o]=function(){return i=nzs(Array.prototype.slice.call(arguments,0)),d=c.apply(t,arguments),t._trace({method:o,args:i}),d}};for(a=0;a{t.dragStatus==="dragging"&&(s=!0)}),s},justDragged:!1,get node(){let s;return _u._dragElements.forEach(t=>{s=t.node}),s},_dragElements:new Map,_drag(s){const t=[];_u._dragElements.forEach((n,r)=>{const{node:a}=n,i=a.getStage();i.setPointersPositions(s),n.pointerId===void 0&&(n.pointerId=ir._getFirstPointerId(s));const l=i._changedPointerPositions.find(o=>o.id===n.pointerId);if(l){if(n.dragStatus!=="dragging"){const o=a.dragDistance();if(Math.max(Math.abs(l.x-n.startPointerPos.x),Math.abs(l.y-n.startPointerPos.y)){n.getStage()&&n.fire("dragmove",{type:"dragmove",target:n,evt:s},!0)})},_endDragBefore(s){const t=[];_u._dragElements.forEach(n=>{const{node:r}=n,a=r.getStage();if(s&&a.setPointersPositions(s),!a._changedPointerPositions.find(o=>o.id===n.pointerId))return;(n.dragStatus==="dragging"||n.dragStatus==="stopped")&&(_u.justDragged=!0,di._mouseListenClick=!1,di._touchListenClick=!1,di._pointerListenClick=!1,n.dragStatus="stopped");const l=n.node.getLayer()||n.node instanceof di.Stage&&n.node;l&&t.indexOf(l)===-1&&t.push(l)}),t.forEach(n=>{n.draw()})},_endDragAfter(s){_u._dragElements.forEach((t,n)=>{t.dragStatus==="stopped"&&t.node.fire("dragend",{type:"dragend",target:t.node,evt:s},!0),t.dragStatus!=="dragging"&&_u._dragElements.delete(n)})}};di.isBrowser&&(window.addEventListener("mouseup",_u._endDragBefore,!0),window.addEventListener("touchend",_u._endDragBefore,!0),window.addEventListener("touchcancel",_u._endDragBefore,!0),window.addEventListener("mousemove",_u._drag),window.addEventListener("touchmove",_u._drag),window.addEventListener("mouseup",_u._endDragAfter,!1),window.addEventListener("touchend",_u._endDragAfter,!1),window.addEventListener("touchcancel",_u._endDragAfter,!1));function l6(s){return ir._isString(s)?'"'+s+'"':Object.prototype.toString.call(s)==="[object Number]"||ir._isBoolean(s)?s:Object.prototype.toString.call(s)}function tLt(s){return s>255?255:s<0?0:Math.round(s)}function ii(){if(di.isUnminified)return function(s,t){return ir._isNumber(s)||ir.warn(l6(s)+' is a not valid value for "'+t+'" attribute. The value should be a number.'),s}}function $Ae(s){if(di.isUnminified)return function(t,n){let r=ir._isNumber(t),a=ir._isArray(t)&&t.length==s;return!r&&!a&&ir.warn(l6(t)+' is a not valid value for "'+n+'" attribute. The value should be a number or Array('+s+")"),t}}function OKe(){if(di.isUnminified)return function(s,t){return ir._isNumber(s)||s==="auto"||ir.warn(l6(s)+' is a not valid value for "'+t+'" attribute. The value should be a number or "auto".'),s}}function CF(){if(di.isUnminified)return function(s,t){return ir._isString(s)||ir.warn(l6(s)+' is a not valid value for "'+t+'" attribute. The value should be a string.'),s}}function sLt(){if(di.isUnminified)return function(s,t){const n=ir._isString(s),r=Object.prototype.toString.call(s)==="[object CanvasGradient]"||s&&s.addColorStop;return n||r||ir.warn(l6(s)+' is a not valid value for "'+t+'" attribute. The value should be a string or a native gradient.'),s}}function gzs(){if(di.isUnminified)return function(s,t){const n=Int8Array?Object.getPrototypeOf(Int8Array):null;return n&&s instanceof n||(ir._isArray(s)?s.forEach(function(r){ir._isNumber(r)||ir.warn('"'+t+'" attribute has non numeric element '+r+". Make sure that all elements are numbers.")}):ir.warn(l6(s)+' is a not valid value for "'+t+'" attribute. The value should be a array of numbers.')),s}}function Ak(){if(di.isUnminified)return function(s,t){return s===!0||s===!1||ir.warn(l6(s)+' is a not valid value for "'+t+'" attribute. The value should be a boolean.'),s}}function xzs(s){if(di.isUnminified)return function(t,n){return t==null||ir.isObject(t)||ir.warn(l6(t)+' is a not valid value for "'+n+'" attribute. The value should be an object with properties '+s),t}}const xG="get",yG="set",gn={addGetterSetter(s,t,n,r,a){gn.addGetter(s,t,n),gn.addSetter(s,t,r,a),gn.addOverloadedGetterSetter(s,t)},addGetter(s,t,n){const r=xG+ir._capitalize(t);s.prototype[r]=s.prototype[r]||function(){const a=this.attrs[t];return a===void 0?n:a}},addSetter(s,t,n,r){const a=yG+ir._capitalize(t);s.prototype[a]||gn.overWriteSetter(s,t,n,r)},overWriteSetter(s,t,n,r){const a=yG+ir._capitalize(t);s.prototype[a]=function(i){return n&&i!==void 0&&i!==null&&(i=n.call(this,i,t)),this._setAttr(t,i),r&&r.call(this),this}},addComponentsGetterSetter(s,t,n,r,a){const i=n.length,l=ir._capitalize,o=xG+l(t),c=yG+l(t);s.prototype[o]=function(){const u={};for(let h=0;h{this._setAttr(t+l(m),void 0)}),this._fireChangeEvent(t,h,u),a&&a.call(this),this},gn.addOverloadedGetterSetter(s,t)},addOverloadedGetterSetter(s,t){const n=ir._capitalize(t),r=yG+n,a=xG+n;s.prototype[t]=function(){return arguments.length?(this[r](arguments[0]),this):this[a]()}},addDeprecatedGetterSetter(s,t,n,r){ir.error("Adding deprecated "+t);const a=xG+ir._capitalize(t),i=t+" property is deprecated and will be removed soon. Look at Konva change log for more information.";s.prototype[a]=function(){ir.error(i);const l=this.attrs[t];return l===void 0?n:l},gn.addSetter(s,t,r,function(){ir.error(i)}),gn.addOverloadedGetterSetter(s,t)},backCompat(s,t){ir.each(t,function(n,r){const a=s.prototype[r],i=xG+ir._capitalize(n),l=yG+ir._capitalize(n);function o(){a.apply(this,arguments),ir.error('"'+n+'" method is deprecated and will be removed soon. Use ""'+r+'" instead.')}s.prototype[n]=o,s.prototype[i]=o,s.prototype[l]=o})},afterSetFilter(){this._filterUpToDate=!1}};function yzs(s){const t=/(\w+)\(([^)]+)\)/g;let n;for(;(n=t.exec(s))!==null;){const[,r,a]=n;switch(r){case"blur":{const i=parseFloat(a.replace("px",""));return function(l){this.blurRadius(i*.5);const o=di.Filters;o&&o.Blur&&o.Blur.call(this,l)}}case"brightness":{const i=a.includes("%")?parseFloat(a)/100:parseFloat(a);return function(l){this.brightness(i);const o=di.Filters;o&&o.Brightness&&o.Brightness.call(this,l)}}case"contrast":{const i=parseFloat(a);return function(l){const o=100*(Math.sqrt(i)-1);this.contrast(o);const c=di.Filters;c&&c.Contrast&&c.Contrast.call(this,l)}}case"grayscale":return function(i){const l=di.Filters;l&&l.Grayscale&&l.Grayscale.call(this,i)};case"sepia":return function(i){const l=di.Filters;l&&l.Sepia&&l.Sepia.call(this,i)};case"invert":return function(i){const l=di.Filters;l&&l.Invert&&l.Invert.call(this,i)};default:ir.warn(`CSS filter "${r}" is not supported in fallback mode. Consider using function filters for better compatibility.`);break}}return()=>{}}const _Ne="absoluteOpacity",rht="allEventListeners",dC="absoluteTransform",aht="absoluteScale",lP="canvas",vzs="Change",bzs="children",_zs="konva",U9e="listening",wzs="mouseenter",jzs="mouseleave",Nzs="pointerenter",kzs="pointerleave",Szs="touchenter",Czs="touchleave",iht="set",oht="Shape",wNe=" ",lht="stage",rE="transform",Azs="Stage",q9e="visible",Ezs=["xChange.konva","yChange.konva","scaleXChange.konva","scaleYChange.konva","skewXChange.konva","skewYChange.konva","rotationChange.konva","offsetXChange.konva","offsetYChange.konva","transformsEnabledChange.konva"].join(wNe);let Tzs=1,ni=class PR{constructor(t){this._id=Tzs++,this.eventListeners={},this.attrs={},this.index=0,this._allEventListeners=null,this.parent=null,this._cache=new Map,this._attachedDepsListeners=new Map,this._lastPos=null,this._batchingTransformChange=!1,this._needClearTransformCache=!1,this._filterUpToDate=!1,this._isUnderCache=!1,this._dragEventId=null,this._shouldFireChangeEvents=!1,this.setAttrs(t),this._shouldFireChangeEvents=!0}hasChildren(){return!1}_clearCache(t){(t===rE||t===dC)&&this._cache.get(t)?this._cache.get(t).dirty=!0:t?this._cache.delete(t):this._cache.clear()}_getCache(t,n){let r=this._cache.get(t);return(r===void 0||(t===rE||t===dC)&&r.dirty===!0)&&(r=n.call(this),this._cache.set(t,r)),r}_calculate(t,n,r){if(!this._attachedDepsListeners.get(t)){const a=n.map(i=>i+"Change.konva").join(wNe);this.on(a,()=>{this._clearCache(t)}),this._attachedDepsListeners.set(t,!0)}return this._getCache(t,r)}_getCanvasCache(){return this._cache.get(lP)}_clearSelfAndDescendantCache(t){this._clearCache(t),t===dC&&this.fire("absoluteTransformChange")}static _runAfterAbsTransformCascade(t){PR._absTransformCascadeDepth>0?PR._pendingAfterCascade.push(t):t()}clearCache(){if(this._cache.has(lP)){const{scene:t,filter:n,hit:r}=this._cache.get(lP);ir.releaseCanvas(t._canvas,n._canvas,r._canvas),this._cache.delete(lP)}return this._clearSelfAndDescendantCache(),this._requestDraw(),this}cache(t){const n=t||{};let r={};(n.x===void 0||n.y===void 0||n.width===void 0||n.height===void 0)&&(r=this.getClientRect({skipTransform:!0,relativeTo:this.getParent()||void 0}));let a=Math.ceil(n.width||r.width),i=Math.ceil(n.height||r.height),l=n.pixelRatio,o=n.x===void 0?Math.floor(r.x):n.x,c=n.y===void 0?Math.floor(r.y):n.y,d=n.offset||0,u=n.drawBorder||!1,h=n.hitCanvasPixelRatio||1;if(!a||!i){ir.error("Can not cache the node. Width or height of the node equals 0. Caching is skipped.");return}const m=Math.abs(Math.round(r.x)-o)>.5?1:0,p=Math.abs(Math.round(r.y)-c)>.5?1:0;a+=d*2+m,i+=d*2+p,o-=d,c-=d;const g=new ME({pixelRatio:l,width:a,height:i}),x=new ME({pixelRatio:l,width:0,height:0,willReadFrequently:!0}),y=new DKe({pixelRatio:h,width:a,height:i}),v=g.getContext(),_=y.getContext(),j=new ME({width:g.width/g.pixelRatio+Math.abs(o),height:g.height/g.pixelRatio+Math.abs(c),pixelRatio:g.pixelRatio}),C=j.getContext();return y.isCache=!0,g.isCache=!0,this._cache.delete(lP),this._filterUpToDate=!1,n.imageSmoothingEnabled===!1&&(g.getContext()._context.imageSmoothingEnabled=!1,x.getContext()._context.imageSmoothingEnabled=!1),v.save(),_.save(),C.save(),v.translate(-o,-c),_.translate(-o,-c),C.translate(-o,-c),j.x=o,j.y=c,this._isUnderCache=!0,this._clearSelfAndDescendantCache(_Ne),this._clearSelfAndDescendantCache(aht),this.drawScene(g,this,j),this.drawHit(y,this),this._isUnderCache=!1,v.restore(),_.restore(),u&&(v.save(),v.beginPath(),v.rect(0,0,a,i),v.closePath(),v.setAttr("strokeStyle","red"),v.setAttr("lineWidth",5),v.stroke(),v.restore()),ir.releaseCanvas(j._canvas),this._cache.set(lP,{scene:g,filter:x,hit:y,x:o,y:c}),this._requestDraw(),this}isCached(){return this._cache.has(lP)}getClientRect(t){throw new Error('abstract "getClientRect" method call')}_transformedRect(t,n){const r=[{x:t.x,y:t.y},{x:t.x+t.width,y:t.y},{x:t.x+t.width,y:t.y+t.height},{x:t.x,y:t.y+t.height}];let a=1/0,i=1/0,l=-1/0,o=-1/0;const c=this.getAbsoluteTransform(n);return r.forEach(function(d){const u=c.point(d);a===void 0&&(a=l=u.x,i=o=u.y),a=Math.min(a,u.x),i=Math.min(i,u.y),l=Math.max(l,u.x),o=Math.max(o,u.y)}),{x:a,y:i,width:l-a,height:o-i}}_drawCachedSceneCanvas(t){t.save(),t._applyOpacity(this),t._applyGlobalCompositeOperation(this);const n=this._getCanvasCache();t.translate(n.x,n.y);const r=this._getCachedSceneCanvas(),a=r.pixelRatio;t.drawImage(r._canvas,0,0,r.width/a,r.height/a),t.restore()}_drawCachedHitCanvas(t){const n=this._getCanvasCache(),r=n.hit;t.save(),t.translate(n.x,n.y),t.drawImage(r._canvas,0,0,r.width/r.pixelRatio,r.height/r.pixelRatio),t.restore()}_getCachedSceneCanvas(){let t=this.filters(),n=this._getCanvasCache(),r=n.scene,a=n.filter,i=a.getContext(),l,o,c,d;if(!t||t.length===0)return r;if(this._filterUpToDate)return a;let u=!0;for(let m=0;m{this.isAncestorOf(t.node)&&_u._dragElements.delete(n)}),this._remove(),this}_clearCaches(){this._clearSelfAndDescendantCache(dC),this._clearSelfAndDescendantCache(_Ne),this._clearSelfAndDescendantCache(aht),this._clearSelfAndDescendantCache(lht),this._clearSelfAndDescendantCache(q9e),this._clearSelfAndDescendantCache(U9e)}_remove(){this._clearCaches();const t=this.getParent();t&&t.children&&(t.children.splice(this.index,1),t._setChildrenIndices(),this.parent=null)}destroy(){return this.remove(),this.clearCache(),this}getAttr(t){const n="get"+ir._capitalize(t);return ir._isFunction(this[n])?this[n]():this.attrs[t]}getAncestors(){let t=this.getParent(),n=[];for(;t;)n.push(t),t=t.getParent();return n}getAttrs(){return this.attrs||{}}setAttrs(t){return this._batchTransformChanges(()=>{let n,r;if(!t)return this;for(n in t)n!==bzs&&(r=iht+ir._capitalize(n),ir._isFunction(this[r])?this[r](t[n]):this._setAttr(n,t[n]))}),this}isListening(){return this._getCache(U9e,this._isListening)}_isListening(t){if(!this.listening())return!1;const r=this.getParent();return r&&r!==t&&this!==t?r._isListening(t):!0}isVisible(){return this._getCache(q9e,this._isVisible)}_isVisible(t){if(!this.visible())return!1;const r=this.getParent();return r&&r!==t&&this!==t?r._isVisible(t):!0}shouldDrawHit(t,n=!1){if(t)return this._isVisible(t)&&this._isListening(t);const r=this.getLayer();let a=!1;_u._dragElements.forEach(l=>{l.dragStatus==="dragging"&&(l.node.nodeType==="Stage"||l.node.getLayer()===r)&&(a=!0)});const i=!n&&!di.hitOnDragEnabled&&(a||di.isTransforming());return this.isListening()&&this.isVisible()&&!i}show(){return this.visible(!0),this}hide(){return this.visible(!1),this}getZIndex(){return this.index||0}getAbsoluteZIndex(){let t=this.getDepth(),n=this,r=0,a,i,l,o;function c(u){for(a=[],i=u.length,l=0;l0&&a[0].getDepth()<=t&&c(a)}const d=this.getStage();return n.nodeType!==Azs&&d&&c(d.getChildren()),r}getDepth(){let t=0,n=this.parent;for(;n;)t++,n=n.parent;return t}_batchTransformChanges(t){this._batchingTransformChange=!0,t(),this._batchingTransformChange=!1,this._needClearTransformCache&&(this._clearCache(rE),this._clearSelfAndDescendantCache(dC)),this._needClearTransformCache=!1}setPosition(t){return this._batchTransformChanges(()=>{this.x(t.x),this.y(t.y)}),this}getPosition(){return{x:this.x(),y:this.y()}}getRelativePointerPosition(){const t=this.getStage();if(!t)return null;const n=t.getPointerPosition();if(!n)return null;const r=this.getAbsoluteTransform().copy();return r.invert(),r.point(n)}getAbsolutePosition(t){let n=!1,r=this.parent;for(;r;){if(r.isCached()){n=!0;break}r=r.parent}n&&!t&&(t=!0);const a=this.getAbsoluteTransform(t).getMatrix(),i=new Uw,l=this.offset();return i.m=a.slice(),i.translate(l.x,l.y),i.getTranslation()}setAbsolutePosition(t){const{x:n,y:r,...a}=this._clearTransform();this.attrs.x=n,this.attrs.y=r,this._clearCache(rE);const i=this._getAbsoluteTransform().copy();return i.invert(),i.translate(t.x,t.y),t={x:this.attrs.x+i.getTranslation().x,y:this.attrs.y+i.getTranslation().y},this._setTransform(a),this.setPosition({x:t.x,y:t.y}),this._clearCache(rE),this._clearSelfAndDescendantCache(dC),this}_setTransform(t){let n;for(n in t)this.attrs[n]=t[n]}_clearTransform(){const t={x:this.x(),y:this.y(),rotation:this.rotation(),scaleX:this.scaleX(),scaleY:this.scaleY(),offsetX:this.offsetX(),offsetY:this.offsetY(),skewX:this.skewX(),skewY:this.skewY()};return this.attrs.x=0,this.attrs.y=0,this.attrs.rotation=0,this.attrs.scaleX=1,this.attrs.scaleY=1,this.attrs.offsetX=0,this.attrs.offsetY=0,this.attrs.skewX=0,this.attrs.skewY=0,t}move(t){let n=t.x,r=t.y,a=this.x(),i=this.y();return n!==void 0&&(a+=n),r!==void 0&&(i+=r),this.setPosition({x:a,y:i}),this}_eachAncestorReverse(t,n){let r=[],a=this.getParent(),i,l;if(!(n&&n._id===this._id)){for(r.unshift(this);a&&(!n||a._id!==n._id);)r.unshift(a),a=a.parent;for(i=r.length,l=0;l0?(this.parent.children.splice(t,1),this.parent.children.splice(t-1,0,this),this.parent._setChildrenIndices(),!0):!1}moveToBottom(){if(!this.parent)return ir.warn("Node has no parent. moveToBottom function is ignored."),!1;const t=this.index;return t>0?(this.parent.children.splice(t,1),this.parent.children.unshift(this),this.parent._setChildrenIndices(),!0):!1}setZIndex(t){if(!this.parent)return ir.warn("Node has no parent. zIndex parameter is ignored."),this;(t<0||t>=this.parent.children.length)&&ir.warn("Unexpected value "+t+" for zIndex property. zIndex is just index of a node in children of its parent. Expected value is from 0 to "+(this.parent.children.length-1)+".");const n=this.index;return this.parent.children.splice(n,1),this.parent.children.splice(t,0,this),this.parent._setChildrenIndices(),this}getAbsoluteOpacity(){return this._getCache(_Ne,this._getAbsoluteOpacity)}_getAbsoluteOpacity(){let t=this.opacity();const n=this.getParent();return n&&!n._isUnderCache&&(t*=n.getAbsoluteOpacity()),t}moveTo(t){return this.getParent()!==t&&(this._remove(),t.add(this)),this}toObject(){let t=this.getAttrs(),n,r,a,i,l;const o={attrs:{},className:this.getClassName()};for(n in t)r=t[n],l=ir.isObject(r)&&!ir._isPlainObject(r)&&!ir._isArray(r),!l&&(a=typeof this[n]=="function"&&this[n],delete t[n],i=a?a.call(this):null,t[n]=r,i!==r&&(o.attrs[n]=r));return ir._prepareToStringify(o)}toJSON(){return JSON.stringify(this.toObject())}getParent(){return this.parent}findAncestors(t,n,r){const a=[];n&&this._isMatch(t)&&a.push(this);let i=this.parent;for(;i;){if(i===r)return a;i._isMatch(t)&&a.push(i),i=i.parent}return a}isAncestorOf(t){return!1}findAncestor(t,n,r){return this.findAncestors(t,n,r)[0]}_isMatch(t){if(!t)return!1;if(typeof t=="function")return t(this);let n=t.replace(/ /g,"").split(","),r=n.length,a,i;for(a=0;a{try{const a=t==null?void 0:t.callback;a&&delete t.callback,ir._urlToImage(this.toDataURL(t),function(i){n(i),a==null||a(i)})}catch(a){r(a)}})}toBlob(t){return new Promise((n,r)=>{try{const a=t==null?void 0:t.callback;a&&delete t.callback,this.toCanvas(t).toBlob(i=>{n(i),a==null||a(i)},t==null?void 0:t.mimeType,t==null?void 0:t.quality)}catch(a){r(a)}})}setSize(t){return this.width(t.width),this.height(t.height),this}getSize(){return{width:this.width(),height:this.height()}}getClassName(){return this.className||this.nodeType}getType(){return this.nodeType}getDragDistance(){return this.attrs.dragDistance!==void 0?this.attrs.dragDistance:this.parent?this.parent.getDragDistance():di.dragDistance}_off(t,n,r){let a=this.eventListeners[t],i,l,o;for(i=0;i=0)||this.isDragging())return;let a=!1;_u._dragElements.forEach(i=>{this.isAncestorOf(i.node)&&(a=!0)}),a||this._createDragElement(t)})}_dragChange(){if(this.attrs.draggable)this._listenDrag();else{if(this._dragCleanup(),!this.getStage())return;const n=_u._dragElements.get(this._id),r=n&&n.dragStatus==="dragging",a=n&&n.dragStatus==="ready";r?this.stopDrag():a&&_u._dragElements.delete(this._id)}}_dragCleanup(){this.off("mousedown.konva"),this.off("touchstart.konva")}isClientRectOnScreen(t={x:0,y:0}){const n=this.getStage();if(!n)return!1;const r={x:-t.x,y:-t.y,width:n.width()+2*t.x,height:n.height()+2*t.y};return ir.haveIntersection(r,this.getClientRect())}static create(t,n){return ir._isString(t)&&(t=JSON.parse(t)),this._createNode(t,n)}static _createNode(t,n){let r=PR.prototype.getClassName.call(t),a=t.children,i,l,o;n&&(t.attrs.container=n),di[r]||(ir.warn('Can not find a node with class name "'+r+'". Fallback to "Shape".'),r="Shape");const c=di[r];if(i=new c(t.attrs),a)for(l=a.length,o=0;o0}removeChildren(){return this.getChildren().forEach(t=>{t.parent=null,t.index=0,t.remove()}),this.children=[],this._requestDraw(),this}destroyChildren(){return this.getChildren().forEach(t=>{t.parent=null,t.index=0,t.destroy()}),this.children=[],this._requestDraw(),this}add(...t){if(t.length===0)return this;if(t.length>1){for(let r=0;r0?n[0]:void 0}_generalFind(t,n){const r=[];return this._descendants(a=>{const i=a._isMatch(t);return i&&r.push(a),!!(i&&n)}),r}_descendants(t){let n=!1;const r=this.getChildren();for(const a of r){if(n=t(a),n)return!0;if(a.hasChildren()&&(n=a._descendants(t),n))return!0}return!1}toObject(){const t=ni.prototype.toObject.call(this);return t.children=[],this.getChildren().forEach(n=>{t.children.push(n.toObject())}),t}isAncestorOf(t){let n=t.getParent();for(;n;){if(n._id===this._id)return!0;n=n.getParent()}return!1}clone(t){const n=ni.prototype.clone.call(this,t);return this.getChildren().forEach(function(r){n.add(r.clone())}),n}getAllIntersections(t){const n=[];return this.find("Shape").forEach(r=>{r.isVisible()&&r.intersects(t)&&n.push(r)}),n}_clearSelfAndDescendantCache(t){var n;const r=t==="absoluteTransform";r&&ni._absTransformCascadeDepth++;try{if(super._clearSelfAndDescendantCache(t),this.isCached())return;(n=this.children)===null||n===void 0||n.forEach(function(a){a._clearSelfAndDescendantCache(t)})}finally{if(r&&--ni._absTransformCascadeDepth===0){const a=ni._pendingAfterCascade;if(a.length){ni._pendingAfterCascade=[];for(let i=0;is.indexOf("pointer")>=0?"pointer":s.indexOf("touch")>=0?"touch":"mouse",X7=s=>{const t=IW(s);if(t==="pointer")return di.pointerEventsEnabled&&qLe.pointer;if(t==="touch")return qLe.touch;if(t==="mouse")return qLe.mouse};function dht(s={}){return(s.clipFunc||s.clipWidth||s.clipHeight)&&ir.warn("Stage does not support clipping. Please use clip for Layers or Groups."),s}const Ozs="Pointer position is missing and not registered by the stage. Looks like it is outside of the stage container. You can set it manually from event: stage.setPointersPositions(event);",FY=[];let UAe=class extends tj{constructor(t){super(dht(t)),this._pointerPositions=[],this._changedPointerPositions=[],this._buildDOM(),this._bindContentEvents(),FY.push(this),this.on("widthChange.konva heightChange.konva",this._resizeDOM),this.on("visibleChange.konva",this._checkVisibility),this.on("clipWidthChange.konva clipHeightChange.konva clipFuncChange.konva",()=>{dht(this.attrs)}),this._checkVisibility()}_validateAdd(t){const n=t.getType()==="Layer",r=t.getType()==="FastLayer";n||r||ir.throw("You may only add layers to the stage.")}_checkVisibility(){if(!this.content)return;const t=this.visible()?"":"none";this.content.style.display=t}setContainer(t){if(typeof t===Pzs){let n;if(t.charAt(0)==="."){const r=t.slice(1);t=document.getElementsByClassName(r)[0]}else t.charAt(0)!=="#"?n=t:n=t.slice(1),t=document.getElementById(n);if(!t)throw"Can not find container in document with id "+n}return this._setAttr("container",t),this.content&&(this.content.parentElement&&this.content.parentElement.removeChild(this.content),t.appendChild(this.content)),this}shouldDrawHit(){return!0}clear(){const t=this.children,n=t.length;for(let r=0;r-1&&FY.splice(n,1),ir.releaseCanvas(this.bufferCanvas._canvas,this.bufferHitCanvas._canvas),this}getPointerPosition(){const t=this._pointerPositions[0]||this._changedPointerPositions[0];return t?{x:t.x,y:t.y}:(ir.warn(Ozs),null)}_getPointerById(t){return this._pointerPositions.find(n=>n.id===t)}getPointersPositions(){return this._pointerPositions}getStage(){return this}getContent(){return this.content}_toKonvaCanvas(t){t={...t},t.x=t.x||0,t.y=t.y||0,t.width=t.width||this.width(),t.height=t.height||this.height();const n=new ME({width:t.width,height:t.height,pixelRatio:t.pixelRatio||1}),r=n.getContext()._context,a=this.children;return(t.x||t.y)&&r.translate(-1*t.x,-1*t.y),a.forEach(function(i){if(!i.isVisible())return;const l=i._toKonvaCanvas(t);r.drawImage(l._canvas,t.x,t.y,l.getWidth()/l.getPixelRatio(),l.getHeight()/l.getPixelRatio())}),n}getIntersection(t){if(!t)return null;const n=this.children,r=n.length,a=r-1;for(let i=a;i>=0;i--){const l=n[i].getIntersection(t);if(l)return l}return null}_resizeDOM(){const t=this.width(),n=this.height();this.content&&(this.content.style.width=t+cht,this.content.style.height=n+cht),this.bufferCanvas.setSize(t,n),this.bufferHitCanvas.setSize(t,n),this.children.forEach(r=>{r.setSize({width:t,height:n}),r.draw()})}add(t,...n){if(arguments.length>1){for(let a=0;aRzs&&ir.warn("The stage has "+r+" layers. Recommended maximum number of layers is 3-5. Adding more layers into the stage may drop the performance. Rethink your tree structure, you can use Konva.Group."),t.setSize({width:this.width(),height:this.height()}),t.draw(),di.isBrowser&&this.content.appendChild(t.canvas._canvas),this}getParent(){return null}getLayer(){return null}hasPointerCapture(t){return rLt(t,this)}setPointerCapture(t){aLt(t,this)}releaseCapture(t){OY(t)}getLayers(){return this.children}_bindContentEvents(){di.isBrowser&&Dzs.forEach(([t,n])=>{this.content.addEventListener(t,r=>{this[n](r)},{passive:!1})})}_pointerenter(t){this.setPointersPositions(t);const n=X7(t.type);n&&this._fire(n.pointerenter,{evt:t,target:this,currentTarget:this})}_pointerover(t){this.setPointersPositions(t);const n=X7(t.type);n&&this._fire(n.pointerover,{evt:t,target:this,currentTarget:this})}_getTargetShape(t){let n=this[t+"targetShape"];return n&&!n.getStage()&&(n=null),n}_pointerleave(t){const n=X7(t.type),r=IW(t.type);if(!n)return;this.setPointersPositions(t);const a=this._getTargetShape(r),i=!(di.isDragging()||di.isTransforming())||di.hitOnDragEnabled;a&&i?(a._fireAndBubble(n.pointerout,{evt:t}),a._fireAndBubble(n.pointerleave,{evt:t}),this._fire(n.pointerleave,{evt:t,target:this,currentTarget:this}),this[r+"targetShape"]=null):i&&(this._fire(n.pointerleave,{evt:t,target:this,currentTarget:this}),this._fire(n.pointerout,{evt:t,target:this,currentTarget:this})),this.pointerPos=null,this._pointerPositions=[]}_pointerdown(t){const n=X7(t.type),r=IW(t.type);if(!n)return;this.setPointersPositions(t);let a=!1;this._changedPointerPositions.forEach(i=>{const l=this.getIntersection(i);if(_u.justDragged=!1,di["_"+r+"ListenClick"]=!0,!l||!l.isListening()){this[r+"ClickStartShape"]=void 0;return}di.capturePointerEventsEnabled&&l.setPointerCapture(i.id),this[r+"ClickStartShape"]=l,l._fireAndBubble(n.pointerdown,{evt:t,pointerId:i.id}),a=!0;const o=t.type.indexOf("touch")>=0;l.preventDefault()&&t.cancelable&&o&&t.preventDefault()}),a||this._fire(n.pointerdown,{evt:t,target:this,currentTarget:this,pointerId:this._pointerPositions[0].id})}_pointermove(t){const n=X7(t.type),r=IW(t.type);if(!n)return;const a=t.type.indexOf("touch")>=0||t.pointerType==="touch";if(di.isDragging()&&_u.node.preventDefault()&&t.cancelable&&a&&t.preventDefault(),this.setPointersPositions(t),!(!(di.isDragging()||di.isTransforming())||di.hitOnDragEnabled))return;const l={};let o=!1;const c=this._getTargetShape(r);this._changedPointerPositions.forEach(d=>{const u=ULe(d.id)||this.getIntersection(d),h=d.id,m={evt:t,pointerId:h},p=c!==u;if(p&&c&&(c._fireAndBubble(n.pointerout,{...m},u),c._fireAndBubble(n.pointerleave,{...m},u)),u){if(l[u._id])return;l[u._id]=!0}u&&u.isListening()?(o=!0,p&&(u._fireAndBubble(n.pointerover,{...m},c),u._fireAndBubble(n.pointerenter,{...m},c),this[r+"targetShape"]=u),u._fireAndBubble(n.pointermove,{...m})):c&&(this._fire(n.pointerover,{evt:t,target:this,currentTarget:this,pointerId:h}),this[r+"targetShape"]=null)}),o||this._fire(n.pointermove,{evt:t,target:this,currentTarget:this,pointerId:this._changedPointerPositions[0].id})}_pointerup(t){const n=X7(t.type),r=IW(t.type);if(!n)return;this.setPointersPositions(t);const a=this[r+"ClickStartShape"],i=this[r+"ClickEndShape"],l={};let o=!1;this._changedPointerPositions.forEach(c=>{const d=ULe(c.id)||this.getIntersection(c);if(d){if(d.releaseCapture(c.id),l[d._id])return;l[d._id]=!0}const u=c.id,h={evt:t,pointerId:u};let m=!1;di["_"+r+"InDblClickWindow"]?(m=!0,clearTimeout(this[r+"DblTimeout"])):_u.justDragged||(di["_"+r+"InDblClickWindow"]=!0,clearTimeout(this[r+"DblTimeout"])),this[r+"DblTimeout"]=setTimeout(function(){di["_"+r+"InDblClickWindow"]=!1},di.dblClickWindow),d&&d.isListening()?(o=!0,this[r+"ClickEndShape"]=d,d._fireAndBubble(n.pointerup,{...h}),di["_"+r+"ListenClick"]&&a&&a===d&&(d._fireAndBubble(n.pointerclick,{...h}),m&&i&&i===d&&d._fireAndBubble(n.pointerdblclick,{...h}))):(this[r+"ClickEndShape"]=null,o||(this._fire(n.pointerup,{evt:t,target:this,currentTarget:this,pointerId:this._changedPointerPositions[0].id}),o=!0),di["_"+r+"ListenClick"]&&this._fire(n.pointerclick,{evt:t,target:this,currentTarget:this,pointerId:u}),m&&this._fire(n.pointerdblclick,{evt:t,target:this,currentTarget:this,pointerId:u}))}),o||this._fire(n.pointerup,{evt:t,target:this,currentTarget:this,pointerId:this._changedPointerPositions[0].id}),di["_"+r+"ListenClick"]=!1,t.cancelable&&r!=="touch"&&r!=="pointer"&&t.preventDefault()}_contextmenu(t){this.setPointersPositions(t);const n=this.getIntersection(this.getPointerPosition());n&&n.isListening()?n._fireAndBubble(V9e,{evt:t}):this._fire(V9e,{evt:t,target:this,currentTarget:this})}_wheel(t){this.setPointersPositions(t);const n=this.getIntersection(this.getPointerPosition());n&&n.isListening()?n._fireAndBubble(H9e,{evt:t}):this._fire(H9e,{evt:t,target:this,currentTarget:this})}_pointercancel(t){this.setPointersPositions(t);const n=ULe(t.pointerId)||this.getIntersection(this.getPointerPosition());n&&n._fireAndBubble(yz,FKe(t)),OY(t.pointerId)}_lostpointercapture(t){OY(t.pointerId)}setPointersPositions(t){const n=this._getContentPosition();let r=null,a=null;t=t||window.event,t.touches!==void 0?(this._pointerPositions=[],this._changedPointerPositions=[],Array.prototype.forEach.call(t.touches,i=>{this._pointerPositions.push({id:i.identifier,x:(i.clientX-n.left)/n.scaleX,y:(i.clientY-n.top)/n.scaleY})}),Array.prototype.forEach.call(t.changedTouches||t.touches,i=>{this._changedPointerPositions.push({id:i.identifier,x:(i.clientX-n.left)/n.scaleX,y:(i.clientY-n.top)/n.scaleY})})):(r=(t.clientX-n.left)/n.scaleX,a=(t.clientY-n.top)/n.scaleY,this.pointerPos={x:r,y:a},this._pointerPositions=[{x:r,y:a,id:ir._getFirstPointerId(t)}],this._changedPointerPositions=[{x:r,y:a,id:ir._getFirstPointerId(t)}])}_setPointerPosition(t){ir.warn('Method _setPointerPosition is deprecated. Use "stage.setPointersPositions(event)" instead.'),this.setPointersPositions(t)}_getContentPosition(){if(!this.content||!this.content.getBoundingClientRect)return{top:0,left:0,scaleX:1,scaleY:1};const t=this.content.getBoundingClientRect();return{top:t.top,left:t.left,scaleX:t.width/this.content.clientWidth||1,scaleY:t.height/this.content.clientHeight||1}}_buildDOM(){if(this.bufferCanvas=new ME({width:this.width(),height:this.height()}),this.bufferHitCanvas=new DKe({pixelRatio:1,width:this.width(),height:this.height()}),!di.isBrowser)return;const t=this.container();if(!t)throw"Stage has no container. A container is required.";t.innerHTML="",this.content=document.createElement("div"),this.content.style.position="relative",this.content.style.userSelect="none",this.content.className="konvajs-content",this.content.setAttribute("role","presentation"),t.appendChild(this.content),this._resizeDOM()}cache(){return ir.warn("Cache function is not allowed for stage. You may use cache only for layers, groups and shapes."),this}clearCache(){return this}batchDraw(){return this.getChildren().forEach(function(t){t.batchDraw()}),this}};UAe.prototype.nodeType=Mzs;Hp(UAe);gn.addGetterSetter(UAe,"container");di.isBrowser&&document.addEventListener("visibilitychange",()=>{FY.forEach(s=>{s.batchDraw()})});const gLt="hasShadow",xLt="shadowRGBA",yLt="patternImage",vLt="linearGradient",bLt="radialGradient";let $re;function VLe(){return $re||($re=ir.createCanvasElement().getContext("2d"),$re)}const zY={};function Fzs(s){const t=this.attrs.fillRule;t?s.fill(t):s.fill()}function zzs(s){s.stroke()}function Bzs(s){const t=this.attrs.fillRule;t?s.fill(t):s.fill()}function $zs(s){s.stroke()}function Uzs(){this._clearCache(gLt)}function qzs(){this._clearCache(xLt)}function Vzs(){this._clearCache(yLt)}function Hzs(){this._clearCache(vLt)}function Gzs(){this._clearCache(bLt)}let Ya=class extends ni{constructor(t){super(t);let n,r=0;for(;n=ir.getHitColor(),!(n&&!(n in zY));)if(r++,r>=1e4){ir.warn("Failed to find a unique color key for a shape. Konva may work incorrectly. Most likely your browser is using canvas farbling. Consider disabling it."),n=ir.getRandomColor();break}this.colorKey=n,zY[n]=this}getContext(){return ir.warn("shape.getContext() method is deprecated. Please do not use it."),this.getLayer().getContext()}getCanvas(){return ir.warn("shape.getCanvas() method is deprecated. Please do not use it."),this.getLayer().getCanvas()}getSceneFunc(){return this.attrs.sceneFunc||this._sceneFunc}getHitFunc(){return this.attrs.hitFunc||this._hitFunc}hasShadow(){return this._getCache(gLt,this._hasShadow)}_hasShadow(){return this.shadowEnabled()&&this.shadowOpacity()!==0&&!!(this.shadowColor()||this.shadowBlur()||this.shadowOffsetX()||this.shadowOffsetY())}_getFillPattern(){return this._getCache(yLt,this.__getFillPattern)}__getFillPattern(){if(this.fillPatternImage()){const n=VLe().createPattern(this.fillPatternImage(),this.fillPatternRepeat()||"repeat");if(n&&n.setTransform){const r=new Uw;r.translate(this.fillPatternX(),this.fillPatternY()),r.rotate(di.getAngle(this.fillPatternRotation())),r.scale(this.fillPatternScaleX(),this.fillPatternScaleY()),r.translate(-1*this.fillPatternOffsetX(),-1*this.fillPatternOffsetY());const a=r.getMatrix(),i=typeof DOMMatrix>"u"?{a:a[0],b:a[1],c:a[2],d:a[3],e:a[4],f:a[5]}:new DOMMatrix(a);n.setTransform(i)}return n}}_getLinearGradient(){return this._getCache(vLt,this.__getLinearGradient)}__getLinearGradient(){const t=this.fillLinearGradientColorStops();if(t){const n=VLe(),r=this.fillLinearGradientStartPoint(),a=this.fillLinearGradientEndPoint(),i=n.createLinearGradient(r.x,r.y,a.x,a.y);for(let l=0;lthis.fillEnabled()&&!!(this.fill()||this.fillPatternImage()||this.fillLinearGradientColorStops()||this.fillRadialGradientColorStops()))}hasStroke(){return this._calculate("hasStroke",["strokeEnabled","strokeWidth","stroke","strokeLinearGradientColorStops"],()=>this.strokeEnabled()&&this.strokeWidth()&&!!(this.stroke()||this.strokeLinearGradientColorStops()))}hasHitStroke(){const t=this.hitStrokeWidth();return t==="auto"?this.hasStroke():this.strokeEnabled()&&!!t}intersects(t){const n=this.getStage();if(!n)return!1;const r=n.bufferHitCanvas;return r.getContext().clear(),this.drawHit(r,void 0,!0),r.context.getImageData(Math.round(t.x),Math.round(t.y),1,1).data[3]>0}destroy(){return ni.prototype.destroy.call(this),delete zY[this.colorKey],delete this.colorKey,this}_useBufferCanvas(t){var n;if(!((n=this.attrs.perfectDrawEnabled)!==null&&n!==void 0?n:!0))return!1;const a=t||this.hasFill(),i=this.hasStroke(),l=this.getAbsoluteOpacity()!==1;if(a&&i&&l)return!0;const o=this.hasShadow(),c=this.shadowForStrokeEnabled();return!!(a&&i&&o&&c)}setStrokeHitEnabled(t){ir.warn("strokeHitEnabled property is deprecated. Please use hitStrokeWidth instead."),t?this.hitStrokeWidth("auto"):this.hitStrokeWidth(0)}getStrokeHitEnabled(){return this.hitStrokeWidth()!==0}getSelfRect(){const t=this.size();return{x:this._centroid?-t.width/2:0,y:this._centroid?-t.height/2:0,width:t.width,height:t.height}}getClientRect(t={}){let n=!1,r=this.getParent();for(;r;){if(r.isCached()){n=!0;break}r=r.getParent()}const a=t.skipTransform,i=t.relativeTo||n&&this.getStage()||void 0,l=this.getSelfRect(),c=!t.skipStroke&&this.hasStroke()&&this.strokeWidth()||0,d=l.width+c,u=l.height+c,h=!t.skipShadow&&this.hasShadow(),m=h?this.shadowOffsetX():0,p=h?this.shadowOffsetY():0,g=d+Math.abs(m),x=u+Math.abs(p),y=h&&this.shadowBlur()||0,v=g+y*2,_=x+y*2,j={width:v,height:_,x:-(c/2+y)+Math.min(m,0)+l.x,y:-(c/2+y)+Math.min(p,0)+l.y};return a?j:this._transformedRect(j,i)}drawScene(t,n,r){const a=this.getLayer(),i=t||a.getCanvas(),l=i.getContext(),o=this._getCanvasCache(),c=this.getSceneFunc(),d=this.hasShadow();let u;const h=n===this;if(!this.isVisible()&&!h)return this;if(o){l.save();const m=this.getAbsoluteTransform(n).getMatrix();return l.transform(m[0],m[1],m[2],m[3],m[4],m[5]),this._drawCachedSceneCanvas(l),l.restore(),this}if(!c)return this;if(l.save(),this._useBufferCanvas()){u=this.getStage();const m=r||u.bufferCanvas,p=m.getContext();r?(p.save(),p.setTransform(1,0,0,1,0,0),p.clearRect(0,0,m.width,m.height),p.restore()):p.clear(),p.save(),p.imageSmoothingEnabled=l.imageSmoothingEnabled,p._applyLineJoin(this),p._applyMiterLimit(this);const g=this.getAbsoluteTransform(n).getMatrix();p.transform(g[0],g[1],g[2],g[3],g[4],g[5]),c.call(this,p,this),p.restore();const x=m.pixelRatio;d&&l._applyShadow(this),h||(l._applyOpacity(this),l._applyGlobalCompositeOperation(this)),l.drawImage(m._canvas,m.x||0,m.y||0,m.width/x,m.height/x)}else{if(l._applyLineJoin(this),l._applyMiterLimit(this),!h){const m=this.getAbsoluteTransform(n).getMatrix();l.transform(m[0],m[1],m[2],m[3],m[4],m[5]),l._applyOpacity(this),l._applyGlobalCompositeOperation(this)}d&&l._applyShadow(this),c.call(this,l,this)}return l.restore(),this}drawHit(t,n,r=!1){if(!this.shouldDrawHit(n,r))return this;const a=this.getLayer(),i=t||a.hitCanvas,l=i&&i.getContext(),o=this.hitFunc()||this.sceneFunc(),c=this._getCanvasCache(),d=c&&c.hit;if(this.colorKey||ir.warn("Looks like your canvas has a destroyed shape in it. Do not reuse shape after you destroyed it. If you want to reuse shape you should call remove() instead of destroy()"),d){l.save();const h=this.getAbsoluteTransform(n).getMatrix();return l.transform(h[0],h[1],h[2],h[3],h[4],h[5]),this._drawCachedHitCanvas(l),l.restore(),this}if(!o)return this;if(l.save(),l._applyLineJoin(this),l._applyMiterLimit(this),!(this===n)){const h=this.getAbsoluteTransform(n).getMatrix();l.transform(h[0],h[1],h[2],h[3],h[4],h[5])}return o.call(this,l,this),l.restore(),this}drawHitFromCache(t=0){const n=this._getCanvasCache(),r=this._getCachedSceneCanvas(),a=n.hit,i=a.getContext(),l=a.getWidth(),o=a.getHeight();i.clear(),i.drawImage(r._canvas,0,0,l,o);try{const c=i.getImageData(0,0,l,o),d=c.data,u=d.length,h=ir._hexToRgb(this.colorKey);for(let m=0;mt?(d[m]=h.r,d[m+1]=h.g,d[m+2]=h.b,d[m+3]=255):d[m+3]=0;i.putImageData(c,0,0)}catch(c){ir.error("Unable to draw hit graph from cached scene canvas. "+c.message)}return this}hasPointerCapture(t){return rLt(t,this)}setPointerCapture(t){aLt(t,this)}releaseCapture(t){OY(t)}};Ya.prototype._fillFunc=Fzs;Ya.prototype._strokeFunc=zzs;Ya.prototype._fillFuncHit=Bzs;Ya.prototype._strokeFuncHit=$zs;Ya.prototype._centroid=!1;Ya.prototype.nodeType="Shape";Hp(Ya);Ya.prototype.eventListeners={};Ya.prototype.on("shadowColorChange.konva shadowBlurChange.konva shadowOffsetChange.konva shadowOpacityChange.konva shadowEnabledChange.konva",Uzs);Ya.prototype.on("shadowColorChange.konva shadowOpacityChange.konva shadowEnabledChange.konva",qzs);Ya.prototype.on("fillPriorityChange.konva fillPatternImageChange.konva fillPatternRepeatChange.konva fillPatternScaleXChange.konva fillPatternScaleYChange.konva fillPatternOffsetXChange.konva fillPatternOffsetYChange.konva fillPatternXChange.konva fillPatternYChange.konva fillPatternRotationChange.konva",Vzs);Ya.prototype.on("fillPriorityChange.konva fillLinearGradientColorStopsChange.konva fillLinearGradientStartPointXChange.konva fillLinearGradientStartPointYChange.konva fillLinearGradientEndPointXChange.konva fillLinearGradientEndPointYChange.konva",Hzs);Ya.prototype.on("fillPriorityChange.konva fillRadialGradientColorStopsChange.konva fillRadialGradientStartPointXChange.konva fillRadialGradientStartPointYChange.konva fillRadialGradientEndPointXChange.konva fillRadialGradientEndPointYChange.konva fillRadialGradientStartRadiusChange.konva fillRadialGradientEndRadiusChange.konva",Gzs);gn.addGetterSetter(Ya,"stroke",void 0,sLt());gn.addGetterSetter(Ya,"strokeWidth",2,ii());gn.addGetterSetter(Ya,"fillAfterStrokeEnabled",!1);gn.addGetterSetter(Ya,"hitStrokeWidth","auto",OKe());gn.addGetterSetter(Ya,"strokeHitEnabled",!0,Ak());gn.addGetterSetter(Ya,"perfectDrawEnabled",!0,Ak());gn.addGetterSetter(Ya,"shadowForStrokeEnabled",!0,Ak());gn.addGetterSetter(Ya,"lineJoin");gn.addGetterSetter(Ya,"lineCap");gn.addGetterSetter(Ya,"miterLimit");gn.addGetterSetter(Ya,"sceneFunc");gn.addGetterSetter(Ya,"hitFunc");gn.addGetterSetter(Ya,"dash");gn.addGetterSetter(Ya,"dashOffset",0,ii());gn.addGetterSetter(Ya,"shadowColor",void 0,CF());gn.addGetterSetter(Ya,"shadowBlur",0,ii());gn.addGetterSetter(Ya,"shadowOpacity",1,ii());gn.addComponentsGetterSetter(Ya,"shadowOffset",["x","y"]);gn.addGetterSetter(Ya,"shadowOffsetX",0,ii());gn.addGetterSetter(Ya,"shadowOffsetY",0,ii());gn.addGetterSetter(Ya,"fillPatternImage");gn.addGetterSetter(Ya,"fill",void 0,sLt());gn.addGetterSetter(Ya,"fillPatternX",0,ii());gn.addGetterSetter(Ya,"fillPatternY",0,ii());gn.addGetterSetter(Ya,"fillLinearGradientColorStops");gn.addGetterSetter(Ya,"strokeLinearGradientColorStops");gn.addGetterSetter(Ya,"fillRadialGradientStartRadius",0);gn.addGetterSetter(Ya,"fillRadialGradientEndRadius",0);gn.addGetterSetter(Ya,"fillRadialGradientColorStops");gn.addGetterSetter(Ya,"fillPatternRepeat","repeat");gn.addGetterSetter(Ya,"fillEnabled",!0);gn.addGetterSetter(Ya,"strokeEnabled",!0);gn.addGetterSetter(Ya,"shadowEnabled",!0);gn.addGetterSetter(Ya,"dashEnabled",!0);gn.addGetterSetter(Ya,"strokeScaleEnabled",!0);gn.addGetterSetter(Ya,"fillPriority","color");gn.addComponentsGetterSetter(Ya,"fillPatternOffset",["x","y"]);gn.addGetterSetter(Ya,"fillPatternOffsetX",0,ii());gn.addGetterSetter(Ya,"fillPatternOffsetY",0,ii());gn.addComponentsGetterSetter(Ya,"fillPatternScale",["x","y"]);gn.addGetterSetter(Ya,"fillPatternScaleX",1,ii());gn.addGetterSetter(Ya,"fillPatternScaleY",1,ii());gn.addComponentsGetterSetter(Ya,"fillLinearGradientStartPoint",["x","y"]);gn.addComponentsGetterSetter(Ya,"strokeLinearGradientStartPoint",["x","y"]);gn.addGetterSetter(Ya,"fillLinearGradientStartPointX",0);gn.addGetterSetter(Ya,"strokeLinearGradientStartPointX",0);gn.addGetterSetter(Ya,"fillLinearGradientStartPointY",0);gn.addGetterSetter(Ya,"strokeLinearGradientStartPointY",0);gn.addComponentsGetterSetter(Ya,"fillLinearGradientEndPoint",["x","y"]);gn.addComponentsGetterSetter(Ya,"strokeLinearGradientEndPoint",["x","y"]);gn.addGetterSetter(Ya,"fillLinearGradientEndPointX",0);gn.addGetterSetter(Ya,"strokeLinearGradientEndPointX",0);gn.addGetterSetter(Ya,"fillLinearGradientEndPointY",0);gn.addGetterSetter(Ya,"strokeLinearGradientEndPointY",0);gn.addComponentsGetterSetter(Ya,"fillRadialGradientStartPoint",["x","y"]);gn.addGetterSetter(Ya,"fillRadialGradientStartPointX",0);gn.addGetterSetter(Ya,"fillRadialGradientStartPointY",0);gn.addComponentsGetterSetter(Ya,"fillRadialGradientEndPoint",["x","y"]);gn.addGetterSetter(Ya,"fillRadialGradientEndPointX",0);gn.addGetterSetter(Ya,"fillRadialGradientEndPointY",0);gn.addGetterSetter(Ya,"fillPatternRotation",0);gn.addGetterSetter(Ya,"fillRule",void 0,CF());gn.backCompat(Ya,{dashArray:"dash",getDashArray:"getDash",setDashArray:"getDash",drawFunc:"sceneFunc",getDrawFunc:"getSceneFunc",setDrawFunc:"setSceneFunc",drawHitFunc:"hitFunc",getDrawHitFunc:"getHitFunc",setDrawHitFunc:"setHitFunc"});const Wzs="beforeDraw",Kzs="draw",_Lt=[{x:0,y:0},{x:-1,y:-1},{x:1,y:-1},{x:1,y:1},{x:-1,y:1}],Yzs=_Lt.length;let AF=class extends tj{constructor(t){super(t),this.canvas=new ME,this.hitCanvas=new DKe({pixelRatio:1}),this._waitingForDraw=!1,this.on("visibleChange.konva",this._checkVisibility),this._checkVisibility(),this.on("imageSmoothingEnabledChange.konva",this._setSmoothEnabled),this._setSmoothEnabled()}createPNGStream(){return this.canvas._canvas.createPNGStream()}getCanvas(){return this.canvas}getNativeCanvasElement(){return this.canvas._canvas}getHitCanvas(){return this.hitCanvas}getContext(){return this.getCanvas().getContext()}clear(t){return this.getContext().clear(t),this.getHitCanvas().getContext().clear(t),this}setZIndex(t){super.setZIndex(t);const n=this.getStage();return n&&n.content&&(n.content.removeChild(this.getNativeCanvasElement()),t{this.draw(),this._waitingForDraw=!1})),this}getIntersection(t){if(!this.isListening()||!this.isVisible())return null;let n=1,r=!1;for(;;){for(let a=0;a0)return{antialiased:!0};return{}}drawScene(t,n,r){const a=this.getLayer(),i=t||a&&a.getCanvas();return this._fire(Wzs,{node:this}),this.clearBeforeDraw()&&i.getContext().clear(),tj.prototype.drawScene.call(this,i,n,r),this._fire(Kzs,{node:this}),this}drawHit(t,n){const r=this.getLayer(),a=t||r&&r.hitCanvas;return r&&r.clearBeforeDraw()&&r.getHitCanvas().getContext().clear(),tj.prototype.drawHit.call(this,a,n),this}enableHitGraph(){return this.hitGraphEnabled(!0),this}disableHitGraph(){return this.hitGraphEnabled(!1),this}setHitGraphEnabled(t){ir.warn("hitGraphEnabled method is deprecated. Please use layer.listening() instead."),this.listening(t)}getHitGraphEnabled(t){return ir.warn("hitGraphEnabled method is deprecated. Please use layer.listening() instead."),this.listening()}toggleHitCanvas(){if(!this.parent||!this.parent.content)return;const t=this.parent;!!this.hitCanvas._canvas.parentNode?t.content.removeChild(this.hitCanvas._canvas):t.content.appendChild(this.hitCanvas._canvas)}destroy(){return ir.releaseCanvas(this.getNativeCanvasElement(),this.getHitCanvas()._canvas),super.destroy()}};AF.prototype.nodeType="Layer";Hp(AF);gn.addGetterSetter(AF,"imageSmoothingEnabled",!0);gn.addGetterSetter(AF,"clearBeforeDraw",!0);gn.addGetterSetter(AF,"hitGraphEnabled",!0,Ak());class zKe extends AF{constructor(t){super(t),this.listening(!1),ir.warn('Konva.Fast layer is deprecated. Please use "new Konva.Layer({ listening: false })" instead.')}}zKe.prototype.nodeType="FastLayer";Hp(zKe);let MU=class extends tj{_validateAdd(t){const n=t.getType();n!=="Group"&&n!=="Shape"&&ir.throw("You may only add groups and shapes to groups.")}};MU.prototype.nodeType="Group";Hp(MU);const HLe=function(){return hD.performance&&hD.performance.now?function(){return hD.performance.now()}:function(){return new Date().getTime()}}();class i2{constructor(t,n){this.id=i2.animIdCounter++,this.frame={time:0,timeDiff:0,lastTime:HLe(),frameRate:0},this.func=t,this.setLayers(n)}setLayers(t){let n=[];return t&&(n=Array.isArray(t)?t:[t]),this.layers=n,this}getLayers(){return this.layers}addLayer(t){const n=this.layers,r=n.length;for(let a=0;athis.duration?this.yoyo?(this._time=this.duration,this.reverse()):this.finish():t<0?this.yoyo?(this._time=0,this.play()):this.reset():(this._time=t,this.update())}getTime(){return this._time}setPosition(t){this.prevPos=this._pos,this.propFunc(t),this._pos=t}getPosition(t){return t===void 0&&(t=this._time),this.func(t,this.begin,this._change,this.duration)}play(){this.state=uht,this._startTime=this.getTimer()-this._time,this.onEnterFrame(),this.fire("onPlay")}reverse(){this.state=hht,this._time=this.duration-this._time,this._startTime=this.getTimer()-this._time,this.onEnterFrame(),this.fire("onReverse")}seek(t){this.pause(),this._time=t,this.update(),this.fire("onSeek")}reset(){this.pause(),this._time=0,this.update(),this.fire("onReset")}finish(){this.pause(),this._time=this.duration,this.update(),this.fire("onFinish")}update(){this.setPosition(this.getPosition(this._time)),this.fire("onUpdate")}onEnterFrame(){const t=this.getTimer()-this._startTime;this.state===uht?this.setTime(t):this.state===hht&&this.setTime(this.duration-t)}pause(){this.state=Xzs,this.fire("onPause")}getTimer(){return new Date().getTime()}}class Im{constructor(t){const n=this,r=t.node,a=r._id,i=t.easing||BY.Linear,l=!!t.yoyo;let o,c;typeof t.duration>"u"?o=.3:t.duration===0?o=.001:o=t.duration,this.node=r,this._id=Qzs++;const d=r.getLayer()||(r instanceof di.Stage?r.getLayers():null);d||ir.error("Tween constructor have `node` that is not in a layer. Please add node into layer first."),this.anim=new i2(function(){n.tween.onEnterFrame()},d),this.tween=new Jzs(c,function(u){n._tweenFunc(u)},i,0,1,o*1e3,l),this._addListeners(),Im.attrs[a]||(Im.attrs[a]={}),Im.attrs[a][this._id]||(Im.attrs[a][this._id]={}),Im.tweens[a]||(Im.tweens[a]={});for(c in t)Zzs[c]===void 0&&this._addAttr(c,t[c]);this.reset(),this.onFinish=t.onFinish,this.onReset=t.onReset,this.onUpdate=t.onUpdate}_addAttr(t,n){const r=this.node,a=r._id;let i,l,o,c,d;const u=Im.tweens[a][t];u&&delete Im.attrs[a][u][t];let h=r.getAttr(t);if(ir._isArray(n))if(i=[],l=Math.max(n.length,h.length),t==="points"&&n.length!==h.length&&(n.length>h.length?(c=h,h=ir._prepareArrayForTween(h,n,r.closed())):(o=n,n=ir._prepareArrayForTween(n,h,r.closed()))),t.indexOf("fill")===0)for(let m=0;m{this.anim.start()},this.tween.onReverse=()=>{this.anim.start()},this.tween.onPause=()=>{this.anim.stop()},this.tween.onFinish=()=>{const t=this.node,n=Im.attrs[t._id][this._id];n.points&&n.points.trueEnd&&t.setAttr("points",n.points.trueEnd),this.onFinish&&this.onFinish.call(this)},this.tween.onReset=()=>{const t=this.node,n=Im.attrs[t._id][this._id];n.points&&n.points.trueStart&&t.points(n.points.trueStart),this.onReset&&this.onReset()},this.tween.onUpdate=()=>{this.onUpdate&&this.onUpdate.call(this)}}play(){return this.tween.play(),this}reverse(){return this.tween.reverse(),this}reset(){return this.tween.reset(),this}seek(t){return this.tween.seek(t*1e3),this}pause(){return this.tween.pause(),this}finish(){return this.tween.finish(),this}destroy(){const t=this.node._id,n=this._id,r=Im.tweens[t];this.pause(),this.anim&&this.anim.stop();for(const a in r)delete Im.tweens[t][a];delete Im.attrs[t][n],Im.tweens[t]&&(Object.keys(Im.tweens[t]).length===0&&delete Im.tweens[t],Object.keys(Im.attrs[t]).length===0&&delete Im.attrs[t])}}Im.attrs={};Im.tweens={};ni.prototype.to=function(s){const t=s.onFinish;s.node=this,s.onFinish=function(){this.destroy(),t&&t()},new Im(s).play()};const BY={BackEaseIn(s,t,n,r){return n*(s/=r)*s*((1.70158+1)*s-1.70158)+t},BackEaseOut(s,t,n,r){return n*((s=s/r-1)*s*((1.70158+1)*s+1.70158)+1)+t},BackEaseInOut(s,t,n,r){let a=1.70158;return(s/=r/2)<1?n/2*(s*s*(((a*=1.525)+1)*s-a))+t:n/2*((s-=2)*s*(((a*=1.525)+1)*s+a)+2)+t},ElasticEaseIn(s,t,n,r,a,i){let l=0;return s===0?t:(s/=r)===1?t+n:(i||(i=r*.3),!a||a0?t:n),h=o*n,m=c*(c>0?t:n),p=d*(d>0?n:t);return{x:u,y:r?-1*p:m,width:h-u,height:p-m}}}oA.prototype._centroid=!0;oA.prototype.className="Arc";oA.prototype._attrsAffectingSize=["innerRadius","outerRadius","angle","clockwise"];Hp(oA);gn.addGetterSetter(oA,"innerRadius",0,ii());gn.addGetterSetter(oA,"outerRadius",0,ii());gn.addGetterSetter(oA,"angle",0,ii());gn.addGetterSetter(oA,"clockwise",!1,Ak());const eBs=[[],[],[-.5773502691896257,.5773502691896257],[0,-.7745966692414834,.7745966692414834],[-.33998104358485626,.33998104358485626,-.8611363115940526,.8611363115940526],[0,-.5384693101056831,.5384693101056831,-.906179845938664,.906179845938664],[.6612093864662645,-.6612093864662645,-.2386191860831969,.2386191860831969,-.932469514203152,.932469514203152],[0,.4058451513773972,-.4058451513773972,-.7415311855993945,.7415311855993945,-.9491079123427585,.9491079123427585],[-.1834346424956498,.1834346424956498,-.525532409916329,.525532409916329,-.7966664774136267,.7966664774136267,-.9602898564975363,.9602898564975363],[0,-.8360311073266358,.8360311073266358,-.9681602395076261,.9681602395076261,-.3242534234038089,.3242534234038089,-.6133714327005904,.6133714327005904],[-.14887433898163122,.14887433898163122,-.4333953941292472,.4333953941292472,-.6794095682990244,.6794095682990244,-.8650633666889845,.8650633666889845,-.9739065285171717,.9739065285171717],[0,-.26954315595234496,.26954315595234496,-.5190961292068118,.5190961292068118,-.7301520055740494,.7301520055740494,-.8870625997680953,.8870625997680953,-.978228658146057,.978228658146057],[-.1252334085114689,.1252334085114689,-.3678314989981802,.3678314989981802,-.5873179542866175,.5873179542866175,-.7699026741943047,.7699026741943047,-.9041172563704749,.9041172563704749,-.9815606342467192,.9815606342467192],[0,-.2304583159551348,.2304583159551348,-.44849275103644687,.44849275103644687,-.6423493394403402,.6423493394403402,-.8015780907333099,.8015780907333099,-.9175983992229779,.9175983992229779,-.9841830547185881,.9841830547185881],[-.10805494870734367,.10805494870734367,-.31911236892788974,.31911236892788974,-.5152486363581541,.5152486363581541,-.6872929048116855,.6872929048116855,-.827201315069765,.827201315069765,-.9284348836635735,.9284348836635735,-.9862838086968123,.9862838086968123],[0,-.20119409399743451,.20119409399743451,-.3941513470775634,.3941513470775634,-.5709721726085388,.5709721726085388,-.7244177313601701,.7244177313601701,-.8482065834104272,.8482065834104272,-.937273392400706,.937273392400706,-.9879925180204854,.9879925180204854],[-.09501250983763744,.09501250983763744,-.2816035507792589,.2816035507792589,-.45801677765722737,.45801677765722737,-.6178762444026438,.6178762444026438,-.755404408355003,.755404408355003,-.8656312023878318,.8656312023878318,-.9445750230732326,.9445750230732326,-.9894009349916499,.9894009349916499],[0,-.17848418149584785,.17848418149584785,-.3512317634538763,.3512317634538763,-.5126905370864769,.5126905370864769,-.6576711592166907,.6576711592166907,-.7815140038968014,.7815140038968014,-.8802391537269859,.8802391537269859,-.9506755217687678,.9506755217687678,-.9905754753144174,.9905754753144174],[-.0847750130417353,.0847750130417353,-.2518862256915055,.2518862256915055,-.41175116146284263,.41175116146284263,-.5597708310739475,.5597708310739475,-.6916870430603532,.6916870430603532,-.8037049589725231,.8037049589725231,-.8926024664975557,.8926024664975557,-.9558239495713977,.9558239495713977,-.9915651684209309,.9915651684209309],[0,-.16035864564022537,.16035864564022537,-.31656409996362983,.31656409996362983,-.46457074137596094,.46457074137596094,-.600545304661681,.600545304661681,-.7209661773352294,.7209661773352294,-.8227146565371428,.8227146565371428,-.9031559036148179,.9031559036148179,-.96020815213483,.96020815213483,-.9924068438435844,.9924068438435844],[-.07652652113349734,.07652652113349734,-.22778585114164507,.22778585114164507,-.37370608871541955,.37370608871541955,-.5108670019508271,.5108670019508271,-.636053680726515,.636053680726515,-.7463319064601508,.7463319064601508,-.8391169718222188,.8391169718222188,-.912234428251326,.912234428251326,-.9639719272779138,.9639719272779138,-.9931285991850949,.9931285991850949],[0,-.1455618541608951,.1455618541608951,-.2880213168024011,.2880213168024011,-.4243421202074388,.4243421202074388,-.5516188358872198,.5516188358872198,-.6671388041974123,.6671388041974123,-.7684399634756779,.7684399634756779,-.8533633645833173,.8533633645833173,-.9200993341504008,.9200993341504008,-.9672268385663063,.9672268385663063,-.9937521706203895,.9937521706203895],[-.06973927331972223,.06973927331972223,-.20786042668822127,.20786042668822127,-.34193582089208424,.34193582089208424,-.469355837986757,.469355837986757,-.5876404035069116,.5876404035069116,-.6944872631866827,.6944872631866827,-.7878168059792081,.7878168059792081,-.8658125777203002,.8658125777203002,-.926956772187174,.926956772187174,-.9700604978354287,.9700604978354287,-.9942945854823992,.9942945854823992],[0,-.1332568242984661,.1332568242984661,-.26413568097034495,.26413568097034495,-.3903010380302908,.3903010380302908,-.5095014778460075,.5095014778460075,-.6196098757636461,.6196098757636461,-.7186613631319502,.7186613631319502,-.8048884016188399,.8048884016188399,-.8767523582704416,.8767523582704416,-.9329710868260161,.9329710868260161,-.9725424712181152,.9725424712181152,-.9947693349975522,.9947693349975522],[-.06405689286260563,.06405689286260563,-.1911188674736163,.1911188674736163,-.3150426796961634,.3150426796961634,-.4337935076260451,.4337935076260451,-.5454214713888396,.5454214713888396,-.6480936519369755,.6480936519369755,-.7401241915785544,.7401241915785544,-.820001985973903,.820001985973903,-.8864155270044011,.8864155270044011,-.9382745520027328,.9382745520027328,-.9747285559713095,.9747285559713095,-.9951872199970213,.9951872199970213]],tBs=[[],[],[1,1],[.8888888888888888,.5555555555555556,.5555555555555556],[.6521451548625461,.6521451548625461,.34785484513745385,.34785484513745385],[.5688888888888889,.47862867049936647,.47862867049936647,.23692688505618908,.23692688505618908],[.3607615730481386,.3607615730481386,.46791393457269104,.46791393457269104,.17132449237917036,.17132449237917036],[.4179591836734694,.3818300505051189,.3818300505051189,.27970539148927664,.27970539148927664,.1294849661688697,.1294849661688697],[.362683783378362,.362683783378362,.31370664587788727,.31370664587788727,.22238103445337448,.22238103445337448,.10122853629037626,.10122853629037626],[.3302393550012598,.1806481606948574,.1806481606948574,.08127438836157441,.08127438836157441,.31234707704000286,.31234707704000286,.26061069640293544,.26061069640293544],[.29552422471475287,.29552422471475287,.26926671930999635,.26926671930999635,.21908636251598204,.21908636251598204,.1494513491505806,.1494513491505806,.06667134430868814,.06667134430868814],[.2729250867779006,.26280454451024665,.26280454451024665,.23319376459199048,.23319376459199048,.18629021092773426,.18629021092773426,.1255803694649046,.1255803694649046,.05566856711617366,.05566856711617366],[.24914704581340277,.24914704581340277,.2334925365383548,.2334925365383548,.20316742672306592,.20316742672306592,.16007832854334622,.16007832854334622,.10693932599531843,.10693932599531843,.04717533638651183,.04717533638651183],[.2325515532308739,.22628318026289723,.22628318026289723,.2078160475368885,.2078160475368885,.17814598076194574,.17814598076194574,.13887351021978725,.13887351021978725,.09212149983772845,.09212149983772845,.04048400476531588,.04048400476531588],[.2152638534631578,.2152638534631578,.2051984637212956,.2051984637212956,.18553839747793782,.18553839747793782,.15720316715819355,.15720316715819355,.12151857068790319,.12151857068790319,.08015808715976021,.08015808715976021,.03511946033175186,.03511946033175186],[.2025782419255613,.19843148532711158,.19843148532711158,.1861610000155622,.1861610000155622,.16626920581699392,.16626920581699392,.13957067792615432,.13957067792615432,.10715922046717194,.10715922046717194,.07036604748810812,.07036604748810812,.03075324199611727,.03075324199611727],[.1894506104550685,.1894506104550685,.18260341504492358,.18260341504492358,.16915651939500254,.16915651939500254,.14959598881657674,.14959598881657674,.12462897125553388,.12462897125553388,.09515851168249279,.09515851168249279,.062253523938647894,.062253523938647894,.027152459411754096,.027152459411754096],[.17944647035620653,.17656270536699264,.17656270536699264,.16800410215645004,.16800410215645004,.15404576107681028,.15404576107681028,.13513636846852548,.13513636846852548,.11188384719340397,.11188384719340397,.08503614831717918,.08503614831717918,.0554595293739872,.0554595293739872,.02414830286854793,.02414830286854793],[.1691423829631436,.1691423829631436,.16427648374583273,.16427648374583273,.15468467512626524,.15468467512626524,.14064291467065065,.14064291467065065,.12255520671147846,.12255520671147846,.10094204410628717,.10094204410628717,.07642573025488905,.07642573025488905,.0497145488949698,.0497145488949698,.02161601352648331,.02161601352648331],[.1610544498487837,.15896884339395434,.15896884339395434,.15276604206585967,.15276604206585967,.1426067021736066,.1426067021736066,.12875396253933621,.12875396253933621,.11156664554733399,.11156664554733399,.09149002162245,.09149002162245,.06904454273764123,.06904454273764123,.0448142267656996,.0448142267656996,.019461788229726478,.019461788229726478],[.15275338713072584,.15275338713072584,.14917298647260374,.14917298647260374,.14209610931838204,.14209610931838204,.13168863844917664,.13168863844917664,.11819453196151841,.11819453196151841,.10193011981724044,.10193011981724044,.08327674157670475,.08327674157670475,.06267204833410907,.06267204833410907,.04060142980038694,.04060142980038694,.017614007139152118,.017614007139152118],[.14608113364969041,.14452440398997005,.14452440398997005,.13988739479107315,.13988739479107315,.13226893863333747,.13226893863333747,.12183141605372853,.12183141605372853,.10879729916714838,.10879729916714838,.09344442345603386,.09344442345603386,.0761001136283793,.0761001136283793,.057134425426857205,.057134425426857205,.036953789770852494,.036953789770852494,.016017228257774335,.016017228257774335],[.13925187285563198,.13925187285563198,.13654149834601517,.13654149834601517,.13117350478706238,.13117350478706238,.12325237681051242,.12325237681051242,.11293229608053922,.11293229608053922,.10041414444288096,.10041414444288096,.08594160621706773,.08594160621706773,.06979646842452049,.06979646842452049,.052293335152683286,.052293335152683286,.03377490158481415,.03377490158481415,.0146279952982722,.0146279952982722],[.13365457218610619,.1324620394046966,.1324620394046966,.12890572218808216,.12890572218808216,.12304908430672953,.12304908430672953,.11499664022241136,.11499664022241136,.10489209146454141,.10489209146454141,.09291576606003515,.09291576606003515,.07928141177671895,.07928141177671895,.06423242140852585,.06423242140852585,.04803767173108467,.04803767173108467,.030988005856979445,.030988005856979445,.013411859487141771,.013411859487141771],[.12793819534675216,.12793819534675216,.1258374563468283,.1258374563468283,.12167047292780339,.12167047292780339,.1155056680537256,.1155056680537256,.10744427011596563,.10744427011596563,.09761865210411388,.09761865210411388,.08619016153195327,.08619016153195327,.0733464814110803,.0733464814110803,.05929858491543678,.05929858491543678,.04427743881741981,.04427743881741981,.028531388628933663,.028531388628933663,.0123412297999872,.0123412297999872]],sBs=[[1],[1,1],[1,2,1],[1,3,3,1]],fht=(s,t,n)=>{let r,a;const l=n/2;r=0;for(let o=0;o<20;o++)a=l*eBs[20][o]+l,r+=tBs[20][o]*nBs(s,t,a);return l*r},pht=(s,t,n)=>{n===void 0&&(n=1);const r=s[0]-2*s[1]+s[2],a=t[0]-2*t[1]+t[2],i=2*s[1]-2*s[0],l=2*t[1]-2*t[0],o=4*(r*r+a*a),c=4*(r*i+a*l),d=i*i+l*l;if(o===0)return n*Math.sqrt(Math.pow(s[2]-s[0],2)+Math.pow(t[2]-t[0],2));const u=c/(2*o),h=d/o,m=n+u,p=h-u*u,g=m*m+p>0?Math.sqrt(m*m+p):0,x=u*u+p>0?Math.sqrt(u*u+p):0,y=u+Math.sqrt(u*u+p)!==0?p*Math.log(Math.abs((m+g)/(u+x))):0;return Math.sqrt(o)/2*(m*g-u*x+y)};function nBs(s,t,n){const r=G9e(1,n,s),a=G9e(1,n,t),i=r*r+a*a;return Math.sqrt(i)}const G9e=(s,t,n)=>{const r=n.length-1;let a,i;if(r===0)return 0;if(s===0){i=0;for(let l=0;l<=r;l++)i+=sBs[r][l]*Math.pow(1-t,r-l)*Math.pow(t,l)*n[l];return i}else{a=new Array(r);for(let l=0;l{let r=1,a=s/t,i=(s-n(a))/t,l=0;for(;r>.001;){const o=n(a+i),c=Math.abs(s-o)/t;if(c500)break}return a},xht=(s,t,n,r)=>{const a=1-r;return a*a*s+2*a*r*t+r*r*n},wLt=(s,t,n,r,a,i)=>{const l=[];for(const o of[[s,n,a],[t,r,i]]){const c=(o[0]-o[1])/(o[0]-2*o[1]+o[2]);c>0&&c<1&&l.push(xht(s,n,a,c),xht(t,r,i,c))}return l},yht=(s,t,n,r,a)=>{const i=1-a;return i*i*i*s+3*i*i*a*t+3*i*a*a*n+a*a*a*r},BKe=(s,t,n,r,a,i,l,o)=>{const c=[];for(const d of[[s,n,a,l],[t,r,i,o]]){const u=-3*d[0]+9*d[1]-9*d[2]+3*d[3],h=6*d[0]-12*d[1]+6*d[2],m=-3*d[0]+3*d[1],p=h*h-4*u*m;if(p<0)continue;const g=-(h+(h<0?-1:1)*Math.sqrt(p))/2;for(const x of[g/u,m/g])x>0&&x<1&&c.push(yht(s,n,a,l,x),yht(t,r,i,o,x))}return c};function W9e(s,t,n,r,a,i,l){const o=Math.sqrt(Math.pow(n-s,2)+Math.pow(r-t,2)),c=Math.sqrt(Math.pow(a-n,2)+Math.pow(i-r,2)),d=o+c;if(d===0)return[n,r,n,r];const u=l*o/d,h=l*c/d,m=n-u*(a-s),p=r-u*(i-t),g=n+h*(a-s),x=r+h*(i-t);return[m,p,g,x]}function vht(s,t){const n=s.length,r=[];for(let a=2;a4}_eachTensionSegment(t,n){const r=this.points(),a=r.length,i=this.closed(),l=this.getTensionPoints(),o=l.length;let c=r[0],d=r[1],u=i?0:4;for(i||(t(c,d,l[0],l[1],l[2],l[3]),c=l[2],d=l[3]);ut.quadraticCurveTo(d,u,h,m),(o,c,d,u,h,m,p,g)=>t.bezierCurveTo(d,u,h,m,p,g));else if(i)for(l=2;lc.push(p,g,...wLt(d,u,h,m,p,g)),(d,u,h,m,p,g,x,y)=>c.push(x,y,...BKe(d,u,h,m,p,g,x,y))),t=c}else this.bezier()&&(t=[t[0],t[1],...rBs(t)]);let n=t[0],r=t[0],a=t[1],i=t[1],l,o;for(let c=0;cu?d:u,y=d>u?1:d/u,v=d>u?u/d:1;t.translate(o,c),t.rotate(p),t.scale(y,v),t.arc(0,0,x,h,h+m,1-g),t.scale(1/y,1/v),t.rotate(-p),t.translate(-o,-c);break;case"z":r=!0,t.closePath();break}}!r&&!this.hasFill()?t.strokeShape(this):t.fillStrokeShape(this)}getSelfRect(){let t=[];this.dataArray.forEach(function(c){if(c.command==="A"){const d=c.points[4],u=c.points[5],h=c.points[4]+u;let m=Math.PI/180;if(Math.abs(d-h)h;p-=m){const g=xw.getPointOnEllipticalArc(c.points[0],c.points[1],c.points[2],c.points[3],p,0);t.push(g.x,g.y)}else for(let p=d+m;pn[a].pathLength;)t-=n[a].pathLength,++a;if(a===i){let c=a-1;for(;c>0&&n[c].points.length<2;)c--;return r=n[c].points.slice(-2),{x:r[0],y:r[1]}}if(t<.01)return n[a].command==="M"?(r=n[a].points.slice(0,2),{x:r[0],y:r[1]}):{x:n[a].start.x,y:n[a].start.y};const l=n[a],o=l.points;switch(l.command){case"L":return xw.getPointOnLine(t,l.start.x,l.start.y,o[0],o[1]);case"C":return xw.getPointOnCubicBezier(ght(t,xw.getPathLength(n),x=>fht([l.start.x,o[0],o[2],o[4]],[l.start.y,o[1],o[3],o[5]],x)),l.start.x,l.start.y,o[0],o[1],o[2],o[3],o[4],o[5]);case"Q":return xw.getPointOnQuadraticBezier(ght(t,xw.getPathLength(n),x=>pht([l.start.x,o[0],o[2]],[l.start.y,o[1],o[3]],x)),l.start.x,l.start.y,o[0],o[1],o[2],o[3]);case"A":const c=o[0],d=o[1],u=o[2],h=o[3],m=o[5],p=o[6];let g=o[4];return g+=m*t/l.pathLength,xw.getPointOnEllipticalArc(c,d,u,h,g,p)}return null}static getPointOnLine(t,n,r,a,i,l,o){l=l??n,o=o??r;const c=this.getLineLength(n,r,a,i);if(c<1e-10)return{x:n,y:r};if(a===n)return{x:l,y:o+(i>r?t:-t)};const d=(i-r)/(a-n),u=Math.sqrt(t*t/(1+d*d))*(a=0&&(x+=2,x>=7&&(x-=7));continue}if(x>=0){if(x===3){if(/^[01]{2}\d+(?:\.\d+)?$/.test(_)){g.push(parseInt(_[0],10)),g.push(parseInt(_[1],10)),g.push(parseFloat(_.slice(2))),x+=3,x>=7&&(x-=7);continue}if(_==="11"||_==="10"||_==="01"){g.push(parseInt(_[0],10)),g.push(parseInt(_[1],10)),x+=2,x>=7&&(x-=7);continue}if(_==="0"||_==="1"){g.push(parseInt(_,10)),x+=1,x>=7&&(x-=7);continue}}else if(x===4){if(/^[01]\d+(?:\.\d+)?$/.test(_)){g.push(parseInt(_[0],10)),g.push(parseFloat(_.slice(1))),x+=2,x>=7&&(x-=7);continue}if(_==="0"||_==="1"){g.push(parseInt(_,10)),x+=1,x>=7&&(x-=7);continue}}const j=parseFloat(_);isNaN(j)?g.push(0):g.push(j),x+=1,x>=7&&(x-=7)}else{const j=parseFloat(_);isNaN(j)?g.push(0):g.push(j)}}for(;g.length>0&&!isNaN(g[0]);){let y="",v=[];const _=o,j=c;let C,A,M,I,P,R,O,B,U,G;switch(p){case"l":o+=g.shift(),c+=g.shift(),y="L",v.push(o,c);break;case"L":o=g.shift(),c=g.shift(),v.push(o,c);break;case"m":const H=g.shift(),Y=g.shift();if(o+=H,c+=Y,y="M",i.length>2&&i[i.length-1].command==="z"){for(let se=i.length-2;se>=0;se--)if(i[se].command==="M"){o=i[se].points[0]+H,c=i[se].points[1]+Y;break}}v.push(o,c),p="l";break;case"M":o=g.shift(),c=g.shift(),y="M",v.push(o,c),p="L";break;case"h":o+=g.shift(),y="L",v.push(o,c);break;case"H":o=g.shift(),y="L",v.push(o,c);break;case"v":c+=g.shift(),y="L",v.push(o,c);break;case"V":c=g.shift(),y="L",v.push(o,c);break;case"C":v.push(g.shift(),g.shift(),g.shift(),g.shift()),o=g.shift(),c=g.shift(),v.push(o,c);break;case"c":v.push(o+g.shift(),c+g.shift(),o+g.shift(),c+g.shift()),o+=g.shift(),c+=g.shift(),y="C",v.push(o,c);break;case"S":A=o,M=c,C=i[i.length-1],C.command==="C"&&(A=o+(o-C.points[2]),M=c+(c-C.points[3])),v.push(A,M,g.shift(),g.shift()),o=g.shift(),c=g.shift(),y="C",v.push(o,c);break;case"s":A=o,M=c,C=i[i.length-1],C.command==="C"&&(A=o+(o-C.points[2]),M=c+(c-C.points[3])),v.push(A,M,o+g.shift(),c+g.shift()),o+=g.shift(),c+=g.shift(),y="C",v.push(o,c);break;case"Q":v.push(g.shift(),g.shift()),o=g.shift(),c=g.shift(),v.push(o,c);break;case"q":v.push(o+g.shift(),c+g.shift()),o+=g.shift(),c+=g.shift(),y="Q",v.push(o,c);break;case"T":A=o,M=c,C=i[i.length-1],C.command==="Q"&&(A=o+(o-C.points[0]),M=c+(c-C.points[1])),o=g.shift(),c=g.shift(),y="Q",v.push(A,M,o,c);break;case"t":A=o,M=c,C=i[i.length-1],C.command==="Q"&&(A=o+(o-C.points[0]),M=c+(c-C.points[1])),o+=g.shift(),c+=g.shift(),y="Q",v.push(A,M,o,c);break;case"A":I=g.shift(),P=g.shift(),R=g.shift(),O=g.shift(),B=g.shift(),U=o,G=c,o=g.shift(),c=g.shift(),y="A",v=this.convertEndpointToCenterParameterization(U,G,o,c,O,B,I,P,R);break;case"a":I=g.shift(),P=g.shift(),R=g.shift(),O=g.shift(),B=g.shift(),U=o,G=c,o+=g.shift(),c+=g.shift(),y="A",v=this.convertEndpointToCenterParameterization(U,G,o,c,O,B,I,P,R);break}i.push({command:y||p,points:v,start:{x:_,y:j},pathLength:this.calcLength(_,j,y||p,v)})}(p==="z"||p==="Z")&&i.push({command:"z",points:[],start:void 0,pathLength:0})}return i}static calcLength(t,n,r,a){let i,l,o,c;const d=xw;switch(r){case"L":return d.getLineLength(t,n,a[0],a[1]);case"C":return fht([t,a[0],a[2],a[4]],[n,a[1],a[3],a[5]],1);case"Q":return pht([t,a[0],a[2]],[n,a[1],a[3]],1);case"A":i=0;const u=a[4],h=a[5],m=a[4]+h;let p=Math.PI/180;if(Math.abs(u-m)m;c-=p)o=d.getPointOnEllipticalArc(a[0],a[1],a[2],a[3],c,0),i+=d.getLineLength(l.x,l.y,o.x,o.y),l=o;else for(c=u+p;c1&&(o*=Math.sqrt(p),c*=Math.sqrt(p));let g=Math.sqrt((o*o*(c*c)-o*o*(m*m)-c*c*(h*h))/(o*o*(m*m)+c*c*(h*h)));i===l&&(g*=-1),isNaN(g)&&(g=0);const x=g*o*m/c,y=g*-c*h/o,v=(t+r)/2+Math.cos(u)*x-Math.sin(u)*y,_=(n+a)/2+Math.sin(u)*x+Math.cos(u)*y,j=function(O){return Math.sqrt(O[0]*O[0]+O[1]*O[1])},C=function(O,B){return(O[0]*B[0]+O[1]*B[1])/(j(O)*j(B))},A=function(O,B){return(O[0]*B[1]=1&&(R=0),l===0&&R>0&&(R=R-2*Math.PI),l===1&&R<0&&(R=R+2*Math.PI),[v,_,o,c,M,R,u,l]}};o2.prototype.className="Path";o2.prototype._attrsAffectingSize=["data"];Hp(o2);gn.addGetterSetter(o2,"data");class EF extends lA{_sceneFunc(t){super._sceneFunc(t);const n=Math.PI*2,r=this.points();let a=r;const i=this.tension()!==0&&r.length>4;i&&(a=this.getTensionPoints());const l=this.pointerLength(),o=r.length;let c,d;if(i){const m=[a[a.length-4],a[a.length-3],a[a.length-2],a[a.length-1],r[o-2],r[o-1]],p=o2.calcLength(a[a.length-4],a[a.length-3],"C",m),g=o2.getPointOnQuadraticBezier(Math.min(1,1-l/p),m[0],m[1],m[2],m[3],m[4],m[5]);c=r[o-2]-g.x,d=r[o-1]-g.y}else c=r[o-2]-r[o-4],d=r[o-1]-r[o-3];const u=(Math.atan2(d,c)+n)%n,h=this.pointerWidth();this.pointerAtEnding()&&(t.save(),t.beginPath(),t.translate(r[o-2],r[o-1]),t.rotate(u),t.moveTo(0,0),t.lineTo(-l,h/2),t.lineTo(-l,-h/2),t.closePath(),t.restore(),this.__fillStroke(t)),this.pointerAtBeginning()&&(t.save(),t.beginPath(),t.translate(r[0],r[1]),i?(c=(a[0]+a[2])/2-r[0],d=(a[1]+a[3])/2-r[1]):(c=r[2]-r[0],d=r[3]-r[1]),t.rotate((Math.atan2(-d,-c)+n)%n),t.moveTo(0,0),t.lineTo(-l,h/2),t.lineTo(-l,-h/2),t.closePath(),t.restore(),this.__fillStroke(t))}__fillStroke(t){const n=this.dashEnabled();n&&(this.attrs.dashEnabled=!1,t.setLineDash([])),t.fillStrokeShape(this),n&&(this.attrs.dashEnabled=!0)}getSelfRect(){const t=super.getSelfRect(),n=this.pointerWidth()/2;return{x:t.x,y:t.y-n,width:t.width,height:t.height+n*2}}}EF.prototype.className="Arrow";Hp(EF);gn.addGetterSetter(EF,"pointerLength",10,ii());gn.addGetterSetter(EF,"pointerWidth",10,ii());gn.addGetterSetter(EF,"pointerAtBeginning",!1);gn.addGetterSetter(EF,"pointerAtEnding",!0);class nV extends Ya{_sceneFunc(t){t.beginPath(),t.arc(0,0,this.attrs.radius||0,0,Math.PI*2,!1),t.closePath(),t.fillStrokeShape(this)}getWidth(){return this.radius()*2}getHeight(){return this.radius()*2}setWidth(t){this.radius()!==t/2&&this.radius(t/2)}setHeight(t){this.radius()!==t/2&&this.radius(t/2)}}nV.prototype._centroid=!0;nV.prototype.className="Circle";nV.prototype._attrsAffectingSize=["radius"];Hp(nV);gn.addGetterSetter(nV,"radius",0,ii());class c6 extends Ya{_sceneFunc(t){const n=this.radiusX(),r=this.radiusY();t.beginPath(),t.save(),n!==r&&t.scale(1,r/n),t.arc(0,0,n,0,Math.PI*2,!1),t.restore(),t.closePath(),t.fillStrokeShape(this)}getWidth(){return this.radiusX()*2}getHeight(){return this.radiusY()*2}setWidth(t){this.radiusX(t/2)}setHeight(t){this.radiusY(t/2)}}c6.prototype.className="Ellipse";c6.prototype._centroid=!0;c6.prototype._attrsAffectingSize=["radiusX","radiusY"];Hp(c6);gn.addComponentsGetterSetter(c6,"radius",["x","y"]);gn.addGetterSetter(c6,"radiusX",0,ii());gn.addGetterSetter(c6,"radiusY",0,ii());let Ek=class jLt extends Ya{constructor(t){super(t),this._loadListener=()=>{this._requestDraw()},this.on("imageChange.konva",n=>{this._removeImageLoad(n.oldVal),this._setImageLoad()}),this._setImageLoad()}_setImageLoad(){const t=this.image();t&&t.complete||t&&t.readyState===4||t&&t.addEventListener&&t.addEventListener("load",this._loadListener)}_removeImageLoad(t){t&&t.removeEventListener&&t.removeEventListener("load",this._loadListener)}destroy(){return this._removeImageLoad(this.image()),super.destroy(),this}_useBufferCanvas(){const t=!!this.cornerRadius(),n=this.hasShadow();return t&&n?!0:super._useBufferCanvas(!0)}_sceneFunc(t){const n=this.getWidth(),r=this.getHeight(),a=this.cornerRadius(),i=this.attrs.image;let l;if(i){const o=this.attrs.cropWidth,c=this.attrs.cropHeight;o&&c?l=[i,this.cropX(),this.cropY(),o,c,0,0,n,r]:l=[i,0,0,n,r]}(this.hasFill()||this.hasStroke()||a)&&(t.beginPath(),a?ir.drawRoundedRectPath(t,n,r,a):t.rect(0,0,n,r),t.closePath(),t.fillStrokeShape(this)),i&&(a&&t.clip(),t.drawImage.apply(t,l))}_hitFunc(t){const n=this.width(),r=this.height(),a=this.cornerRadius();t.beginPath(),a?ir.drawRoundedRectPath(t,n,r,a):t.rect(0,0,n,r),t.closePath(),t.fillStrokeShape(this)}getWidth(){var t,n,r;return(r=(t=this.attrs.width)!==null&&t!==void 0?t:(n=this.image())===null||n===void 0?void 0:n.width)!==null&&r!==void 0?r:0}getHeight(){var t,n,r;return(r=(t=this.attrs.height)!==null&&t!==void 0?t:(n=this.image())===null||n===void 0?void 0:n.height)!==null&&r!==void 0?r:0}static fromURL(t,n,r=null){const a=ir.createImageElement();a.onload=function(){const i=new jLt({image:a});n(i)},a.onerror=r,a.crossOrigin="Anonymous",a.src=t}};Ek.prototype.className="Image";Ek.prototype._attrsAffectingSize=["image"];Hp(Ek);gn.addGetterSetter(Ek,"cornerRadius",0,$Ae(4));gn.addGetterSetter(Ek,"image");gn.addComponentsGetterSetter(Ek,"crop",["x","y","width","height"]);gn.addGetterSetter(Ek,"cropX",0,ii());gn.addGetterSetter(Ek,"cropY",0,ii());gn.addGetterSetter(Ek,"cropWidth",0,ii());gn.addGetterSetter(Ek,"cropHeight",0,ii());const NLt=["fontFamily","fontSize","fontStyle","padding","lineHeight","text","width","height","pointerDirection","pointerWidth","pointerHeight"],aBs="Change.konva",iBs="none",K9e="up",Y9e="right",Z9e="down",X9e="left",oBs=NLt.length;let $Ke=class extends MU{constructor(t){super(t),this.on("add.konva",function(n){this._addListeners(n.child),this._sync()})}getText(){return this.find("Text")[0]}getTag(){return this.find("Tag")[0]}_addListeners(t){let n=this,r;const a=function(){n._sync()};for(r=0;r{n=Math.min(n,l.x),r=Math.max(r,l.x),a=Math.min(a,l.y),i=Math.max(i,l.y)}),{x:n,y:a,width:r-n,height:i-a}}getWidth(){return this.radius()*2}getHeight(){return this.radius()*2}setWidth(t){this.radius(t/2)}setHeight(t){this.radius(t/2)}}d6.prototype.className="RegularPolygon";d6.prototype._centroid=!0;d6.prototype._attrsAffectingSize=["radius"];Hp(d6);gn.addGetterSetter(d6,"radius",0,ii());gn.addGetterSetter(d6,"sides",0,ii());gn.addGetterSetter(d6,"cornerRadius",0,$Ae(4));const bht=Math.PI*2;let MF=class extends Ya{_sceneFunc(t){t.beginPath(),t.arc(0,0,this.innerRadius(),0,bht,!1),t.moveTo(this.outerRadius(),0),t.arc(0,0,this.outerRadius(),bht,0,!0),t.closePath(),t.fillStrokeShape(this)}getWidth(){return this.outerRadius()*2}getHeight(){return this.outerRadius()*2}setWidth(t){this.outerRadius(t/2)}setHeight(t){this.outerRadius(t/2)}};MF.prototype.className="Ring";MF.prototype._centroid=!0;MF.prototype._attrsAffectingSize=["innerRadius","outerRadius"];Hp(MF);gn.addGetterSetter(MF,"innerRadius",0,ii());gn.addGetterSetter(MF,"outerRadius",0,ii());class r4 extends Ya{constructor(t){super(t),this._updated=!0,this.anim=new i2(()=>{const n=this._updated;return this._updated=!1,n}),this.on("animationChange.konva",function(){this.frameIndex(0)}),this.on("frameIndexChange.konva",function(){this._updated=!0}),this.on("frameRateChange.konva",function(){this.anim.isRunning()&&(clearInterval(this.interval),this._setInterval())})}_sceneFunc(t){const n=this.animation(),r=this.frameIndex(),a=r*4,i=this.animations()[n],l=this.frameOffsets(),o=i[a+0],c=i[a+1],d=i[a+2],u=i[a+3],h=this.image();if((this.hasFill()||this.hasStroke())&&(t.beginPath(),t.rect(0,0,d,u),t.closePath(),t.fillStrokeShape(this)),h)if(l){const m=l[n],p=r*2;t.drawImage(h,o,c,d,u,m[p+0],m[p+1],d,u)}else t.drawImage(h,o,c,d,u,0,0,d,u)}_hitFunc(t){const n=this.animation(),r=this.frameIndex(),a=r*4,i=this.animations()[n],l=this.frameOffsets(),o=i[a+2],c=i[a+3];if(t.beginPath(),l){const d=l[n],u=r*2;t.rect(d[u+0],d[u+1],o,c)}else t.rect(0,0,o,c);t.closePath(),t.fillShape(this)}_useBufferCanvas(){return super._useBufferCanvas(!0)}_setInterval(){const t=this;this.interval=setInterval(function(){t._updateIndex()},1e3/this.frameRate())}start(){if(this.isRunning())return;const t=this.getLayer();this.anim.setLayers(t),this._setInterval(),this.anim.start()}stop(){this.anim.stop(),clearInterval(this.interval)}isRunning(){return this.anim.isRunning()}_updateIndex(){const t=this.frameIndex(),n=this.animation(),r=this.animations(),a=r[n],i=a.length/4;t{if(new RegExp("\\p{Emoji}","u").test(n)){const i=a[r+1];i&&new RegExp("\\p{Emoji_Modifier}|\\u200D","u").test(i)?(t.push(n+i),a[r+1]=""):t.push(n)}else new RegExp("\\p{Regional_Indicator}{2}","u").test(n+(a[r+1]||""))?t.push(n+a[r+1]):r>0&&new RegExp("\\p{Mn}|\\p{Me}|\\p{Mc}","u").test(n)?t[t.length-1]+=n:n&&t.push(n);return t},[])}const Q7="auto",lBs="center",kLt="inherit",vG="justify",cBs="Change.konva",SLt="2d",_ht="-",CLt="left",dBs="text",uBs="Text",hBs="top",mBs="bottom",wht="middle",ALt="normal",fBs="px ",qre=" ",pBs="right",jht="rtl",gBs="word",xBs="char",Nht="none",GLe="…",ELt=["direction","fontFamily","fontSize","fontStyle","fontVariant","padding","align","verticalAlign","lineHeight","text","width","height","wrap","ellipsis","letterSpacing"],yBs=ELt.length;let bG=null;function vBs(){if(bG!==null)return bG;bG=!1;try{const s=document.createElement("canvas");s.width=10,s.height=10;const t=s.getContext(SLt);if(t){t.globalAlpha=0,t.shadowColor="black",t.shadowBlur=5,t.shadowOffsetX=5,t.shadowOffsetY=5,t.fillStyle="black",t.font="10px Arial",t.fillText("X",0,10);const n=t.getImageData(0,0,10,10).data;for(let r=3;r0){bG=!0;break}}}catch{}return bG}function bBs(s){return s.split(",").map(t=>{t=t.trim();const n=t.indexOf(" ")>=0,r=t.indexOf('"')>=0||t.indexOf("'")>=0;return n&&!r&&(t=`"${t}"`),t}).join(", ")}let Vre;function WLe(){return Vre||(Vre=ir.createCanvasElement().getContext(SLt),Vre)}function _Bs(s){s.fillText(this._partialText,this._partialTextX,this._partialTextY)}function wBs(s){s.setAttr("miterLimit",2),s.strokeText(this._partialText,this._partialTextX,this._partialTextY)}function jBs(s){return s=s||{},!s.fillLinearGradientColorStops&&!s.fillRadialGradientColorStops&&!s.fillPatternImage&&(s.fill=s.fill||"black"),s}let Um=class extends Ya{constructor(t){super(jBs(t)),this._partialTextX=0,this._partialTextY=0;for(let n=0;nle+LW(fe.text).length,0),te=ee+Q;x({char:oe,index:te,x:P,y:M+R,lineIndex:A,column:ee,isLastInLine:G,width:this.measureSize(oe).width,context:t})}t.fillStrokeShape(this),x&&t.restore(),P+=this.measureSize(oe).width+g}}else g!==0&&t.setAttr("letterSpacing",`${g}px`),this._partialTextX=P,this._partialTextY=M+R,this._partialText=B,t.fillStrokeShape(this);if(C){t.save(),t.beginPath();const Y=di.legacyTextRendering?0:-Math.round(o/4),se=H;t.moveTo(se,M+R+Y);const ee=m===vG&&!G?p-l*2:U;t.lineTo(se+Math.round(ee),M+R+Y),t.lineWidth=o/15;const oe=this._getLinearGradient();t.strokeStyle=oe||y,t.stroke(),t.restore()}t.restore(),i>1&&(M+=c)}}_hitFunc(t){const n=this.getWidth(),r=this.getHeight();t.beginPath(),t.rect(0,0,n,r),t.closePath(),t.fillStrokeShape(this)}setText(t){const n=ir._isString(t)?t:t==null?"":t+"";return this._setAttr(dBs,n),this}getWidth(){return this.attrs.width===Q7||this.attrs.width===void 0?this.getTextWidth()+this.padding()*2:this.attrs.width}getHeight(){return this.attrs.height===Q7||this.attrs.height===void 0?this.fontSize()*this.textArr.length*this.lineHeight()+this.padding()*2:this.attrs.height}getTextWidth(){return this.textWidth}getTextHeight(){return ir.warn("text.getTextHeight() method is deprecated. Use text.height() - for full height and text.fontSize() - for one line height."),this.textHeight}measureSize(t){var n,r,a,i,l,o,c,d,u,h,m;let p=WLe(),g=this.fontSize(),x;p.save(),p.font=this._getContextFont(),x=p.measureText(t),p.restore();const y=g/100;return{actualBoundingBoxAscent:(n=x.actualBoundingBoxAscent)!==null&&n!==void 0?n:71.58203125*y,actualBoundingBoxDescent:(r=x.actualBoundingBoxDescent)!==null&&r!==void 0?r:0,actualBoundingBoxLeft:(a=x.actualBoundingBoxLeft)!==null&&a!==void 0?a:-7.421875*y,actualBoundingBoxRight:(i=x.actualBoundingBoxRight)!==null&&i!==void 0?i:75.732421875*y,alphabeticBaseline:(l=x.alphabeticBaseline)!==null&&l!==void 0?l:0,emHeightAscent:(o=x.emHeightAscent)!==null&&o!==void 0?o:100*y,emHeightDescent:(c=x.emHeightDescent)!==null&&c!==void 0?c:-20*y,fontBoundingBoxAscent:(d=x.fontBoundingBoxAscent)!==null&&d!==void 0?d:91*y,fontBoundingBoxDescent:(u=x.fontBoundingBoxDescent)!==null&&u!==void 0?u:21*y,hangingBaseline:(h=x.hangingBaseline)!==null&&h!==void 0?h:72.80000305175781*y,ideographicBaseline:(m=x.ideographicBaseline)!==null&&m!==void 0?m:-21*y,width:x.width,height:g}}_getContextFont(){return this.fontStyle()+qre+this.fontVariant()+qre+(this.fontSize()+fBs)+bBs(this.fontFamily())}_addTextLine(t){this.align()===vG&&(t=t.trim());const r=this._getTextWidth(t);return this.textArr.push({text:t,width:r,lastInParagraph:!1})}_getTextWidth(t){const n=this.letterSpacing(),r=t.length;return WLe().measureText(t).width+n*r}_setTextData(){let t=this.text().split(` `),n=+this.fontSize(),r=0,a=this.lineHeight()*n,i=this.attrs.width,l=this.attrs.height,o=i!==Q7&&i!==void 0,c=l!==Q7&&l!==void 0,d=this.padding(),u=i-d*2,h=l-d*2,m=0,p=this.wrap(),g=p!==Nht,x=p!==xBs&&g,y=this.ellipsis();this.textArr=[],WLe().font=this._getContextFont();const v=y?this._getTextWidth(GLe):0;for(let _=0,j=t.length;_u)for(;C.length>0;){const M=LW(C);let I=0,P=M.length,R="",O=0;for(;I>>1,U=M.slice(0,B+1).join(""),G=this._getTextWidth(U);(y&&c&&m+a>h?G+v:G)<=u?(I=B+1,R=U,O=G):P=B}if(R){if(x){const U=LW(R),G=M[U.length],H=G===qre||G===_ht;let Y;if(H&&O<=u)Y=U.length;else{const se=U.lastIndexOf(qre),ee=U.lastIndexOf(_ht);Y=Math.max(se,ee)+1}Y>0&&(I=Y,R=M.slice(0,I).join(""),O=this._getTextWidth(R))}if(R=R.trimRight(),this._addTextLine(R),r=Math.max(r,O),m+=a,this._shouldHandleEllipsis(m)){this._tryToAddEllipsisToLastLine();break}if(C=M.slice(I).join("").trimLeft(),C.length>0&&(A=this._getTextWidth(C),A<=u)){this._addTextLine(C),m+=a,r=Math.max(r,A);break}}else break}else this._addTextLine(C),m+=a,r=Math.max(r,A),this._shouldHandleEllipsis(m)&&_h)break}this.textHeight=n,this.textWidth=r}_shouldHandleEllipsis(t){const n=+this.fontSize(),r=this.lineHeight()*n,a=this.attrs.height,i=a!==Q7&&a!==void 0,l=this.padding(),o=a-l*2;return!(this.wrap()!==Nht)||i&&t+r>o}_tryToAddEllipsisToLastLine(){const t=this.attrs.width,n=t!==Q7&&t!==void 0,r=this.padding(),a=t-r*2,i=this.ellipsis(),l=this.textArr[this.textArr.length-1];!l||!i||(n&&(this._getTextWidth(l.text+GLe)n?null:o2.getPointAtLengthOfDataArray(t,this.dataArray)}_readDataAttribute(){this.dataArray=o2.parsePathData(this.attrs.data),this.pathLength=this._getTextPathLength()}_sceneFunc(t){t.setAttr("font",this._getContextFont()),t.setAttr("textBaseline",this.textBaseline()),t.setAttr("textAlign","left"),t.save();const n=this.textDecoration(),r=this.fill(),a=this.fontSize(),i=this.glyphInfo,l=n.indexOf("underline")!==-1,o=n.indexOf("line-through")!==-1;l&&t.beginPath();for(let c=0;c=1){const r=n[0].p0;t.moveTo(r.x,r.y)}for(let r=0;rthis.pathLength&&v-this.pathLength<=d?this.pathLength:v);if(!_)return;const j=o2.getLineLength(g.x,g.y,_.x,_.y);let C=0;if(c)try{C=c(n[p-1].char,x)*this.fontSize()}catch{C=0}g.x+=C,_.x+=C,this.textWidth+=C;const A=o2.getPointOnLine(C+j/2,g.x,g.y,_.x,_.y),M=Math.atan2(_.y-g.y,_.x-g.x);this.glyphInfo.push({transposeX:A.x,transposeY:A.y,text:t[p],rotation:M,p0:g,p1:_,width:j}),m+=y}}getSelfRect(){if(!this.glyphInfo.length)return{x:0,y:0,width:0,height:0};const t=[];this.glyphInfo.forEach(function(d){t.push(d.p0.x),t.push(d.p0.y),t.push(d.p1.x),t.push(d.p1.y)});let n=t[0]||0,r=t[0]||0,a=t[1]||0,i=t[1]||0,l,o;for(let d=0;ds+`.${ILt}`).join(" "),kht="nodesRect",SBs=["widthChange","heightChange","scaleXChange","scaleYChange","skewXChange","skewYChange","rotationChange","offsetXChange","offsetYChange","transformsEnabledChange","strokeWidthChange","draggableChange"],CBs={"top-left":-45,"top-center":0,"top-right":45,"middle-right":-90,"middle-left":90,"bottom-left":-135,"bottom-center":180,"bottom-right":135},ABs="ontouchstart"in di._global;function EBs(s,t,n){if(s==="rotater")return n;t+=ir.degToRad(CBs[s]||0);const r=(ir.radToDeg(t)%360+360)%360;return ir._inRange(r,315+22.5,360)||ir._inRange(r,0,22.5)?"ns-resize":ir._inRange(r,45-22.5,45+22.5)?"nesw-resize":ir._inRange(r,90-22.5,90+22.5)?"ew-resize":ir._inRange(r,135-22.5,135+22.5)?"nwse-resize":ir._inRange(r,180-22.5,180+22.5)?"ns-resize":ir._inRange(r,225-22.5,225+22.5)?"nesw-resize":ir._inRange(r,270-22.5,270+22.5)?"ew-resize":ir._inRange(r,315-22.5,315+22.5)?"nwse-resize":(ir.error("Transformer has unknown angle for cursor detection: "+r),"pointer")}const p5e=["top-left","top-center","top-right","middle-right","middle-left","bottom-left","bottom-center","bottom-right"];function TBs(s){return{x:s.x+s.width/2*Math.cos(s.rotation)+s.height/2*Math.sin(-s.rotation),y:s.y+s.height/2*Math.cos(s.rotation)+s.width/2*Math.sin(s.rotation)}}function LLt(s,t,n){const r=n.x+(s.x-n.x)*Math.cos(t)-(s.y-n.y)*Math.sin(t),a=n.y+(s.x-n.x)*Math.sin(t)+(s.y-n.y)*Math.cos(t);return{...s,rotation:s.rotation+t,x:r,y:a}}function MBs(s,t){const n=TBs(s);return LLt(s,t,n)}function PBs(s,t,n){let r=t;for(let a=0;aa.isAncestorOf(this)?(ir.error("Konva.Transformer cannot be an a child of the node you are trying to attach"),!1):!0);return this._nodes=t=n,t.length===1&&this.useSingleNodeRotation()?this.rotation(t[0].getAbsoluteRotation()):this.rotation(0),this._nodes.forEach(a=>{const i=()=>{this._transforming||(this.nodes().length===1&&this.useSingleNodeRotation()&&this.rotation(this.nodes()[0].getAbsoluteRotation()),this._resetTransformCache(),this.isDragging()||this._scheduleUpdate())};if(a._attrsAffectingSize.length){const l=a._attrsAffectingSize.map(o=>o+"Change."+this._getEventNamespace()).join(" ");a.on(l,i)}a.on(SBs.map(l=>l+`.${this._getEventNamespace()}`).join(" "),i),a.on(`absoluteTransformChange.${this._getEventNamespace()}`,i),this._proxyDrag(a)}),this._resetTransformCache(),!!this.findOne(".top-left")&&this.update(),this}_proxyDrag(t){let n;t.on(`dragstart.${this._getEventNamespace()}`,r=>{n=t.getAbsolutePosition(),!this.isDragging()&&t!==this.findOne(".back")&&this.startDrag(r,!1)}),t.on(`dragmove.${this._getEventNamespace()}`,r=>{if(!n)return;const a=t.getAbsolutePosition(),i=a.x-n.x,l=a.y-n.y;this.nodes().forEach(o=>{if(o===t||o.isDragging())return;const c=o.getAbsolutePosition();o.setAbsolutePosition({x:c.x+i,y:c.y+l}),o.startDrag(r)}),n=null})}getNodes(){return this._nodes||[]}getActiveAnchor(){return this._movingAnchorName}detach(){this._nodes&&this._nodes.forEach(t=>{t.off("."+this._getEventNamespace())}),this._nodes=[],this._resetTransformCache()}_resetTransformCache(){this._clearCache(kht),this._clearCache("transform"),this._clearSelfAndDescendantCache("absoluteTransform")}_getNodeRect(){return this._getCache(kht,this.__getNodeRect)}__getNodeShape(t,n=this.rotation(),r){const a=t.getClientRect({skipTransform:!0,skipShadow:!0,skipStroke:this.ignoreStroke()}),i=t.getAbsoluteScale(r),l=t.getAbsolutePosition(r),o=a.x*i.x-t.offsetX()*i.x,c=a.y*i.y-t.offsetY()*i.y,d=(di.getAngle(t.getAbsoluteRotation())+Math.PI*2)%(Math.PI*2),u={x:l.x+o*Math.cos(d)+c*Math.sin(-d),y:l.y+c*Math.cos(d)+o*Math.sin(d),width:a.width*i.x,height:a.height*i.y,rotation:d};return LLt(u,-di.getAngle(n),{x:0,y:0})}__getNodeRect(){if(!this.getNode())return{x:-1e8,y:-1e8,width:0,height:0,rotation:0};const n=[];this.nodes().map(d=>{const u=d.getClientRect({skipTransform:!0,skipShadow:!0,skipStroke:this.ignoreStroke()}),h=[{x:u.x,y:u.y},{x:u.x+u.width,y:u.y},{x:u.x+u.width,y:u.y+u.height},{x:u.x,y:u.y+u.height}],m=d.getAbsoluteTransform();h.forEach(function(p){const g=m.point(p);n.push(g)})});const r=new Uw;r.rotate(-di.getAngle(this.rotation()));let a=1/0,i=1/0,l=-1/0,o=-1/0;n.forEach(function(d){const u=r.point(d);a===void 0&&(a=l=u.x,i=o=u.y),a=Math.min(a,u.x),i=Math.min(i,u.y),l=Math.max(l,u.x),o=Math.max(o,u.y)}),r.invert();const c=r.point({x:a,y:i});return{x:c.x,y:c.y,width:l-a,height:o-i,rotation:di.getAngle(this.rotation())}}getX(){return this._getNodeRect().x}getY(){return this._getNodeRect().y}getWidth(){return this._getNodeRect().width}getHeight(){return this._getNodeRect().height}_createElements(){this._createBack(),p5e.forEach(t=>{this._createAnchor(t)}),this._createAnchor("rotater"),this._elementsCreated=!0}_createAnchor(t){const n=new $ee({stroke:"rgb(0, 161, 255)",fill:"white",strokeWidth:1,name:t+" _anchor",dragDistance:0,draggable:!0,hitStrokeWidth:ABs?10:"auto"}),r=this;n.on("mousedown touchstart",function(a){r._handleMouseDown(a)}),n.on("dragstart",a=>{n.stopDrag(),a.cancelBubble=!0}),n.on("dragend",a=>{a.cancelBubble=!0}),n.on("mouseenter",()=>{const a=di.getAngle(this.rotation()),i=this.rotateAnchorCursor(),l=EBs(t,a,i);n.getStage().content&&(n.getStage().content.style.cursor=l),this._cursorChange=!0}),n.on("mouseout",()=>{n.getStage().content&&(n.getStage().content.style.cursor=""),this._cursorChange=!1}),this.add(n)}_createBack(){const t=new Ya({name:"back",width:0,height:0,sceneFunc(n,r){const a=r.getParent(),i=a.padding(),l=r.width(),o=r.height();if(n.beginPath(),n.rect(-i,-i,l+i*2,o+i*2),a.rotateEnabled()&&a.rotateLineVisible()){const c=a.rotateAnchorAngle(),d=a.rotateAnchorOffset(),u=ir.degToRad(c),h=Math.sin(u),m=-Math.cos(u),p=l/2,g=o/2;let x=1/0;m<0?x=Math.min(x,-g/m):m>0&&(x=Math.min(x,(o-g)/m)),h<0?x=Math.min(x,-p/h):h>0&&(x=Math.min(x,(l-p)/h));const y=p+h*x,v=g+m*x,_=ir._sign(o),j=y+h*d*_,C=v+m*d*_;n.moveTo(y,v),n.lineTo(j,C)}n.fillStrokeShape(r)},hitFunc:(n,r)=>{if(!this.shouldOverdrawWholeArea())return;const a=this.padding();n.beginPath(),n.rect(-a,-a,r.width()+a*2,r.height()+a*2),n.fillStrokeShape(r)}});this.add(t),this._proxyDrag(t),t.on("dragstart",n=>{n.cancelBubble=!0}),t.on("dragmove",n=>{n.cancelBubble=!0}),t.on("dragend",n=>{n.cancelBubble=!0}),this.on("dragmove",n=>{this.update()})}_handleMouseDown(t){if(this._transforming)return;this._movingAnchorName=t.target.name().split(" ")[0];const n=this._getNodeRect(),r=n.width,a=n.height,i=Math.sqrt(Math.pow(r,2)+Math.pow(a,2));this.sin=Math.abs(a/i),this.cos=Math.abs(r/i),typeof window<"u"&&(window.addEventListener("mousemove",this._handleMouseMove),window.addEventListener("touchmove",this._handleMouseMove),window.addEventListener("mouseup",this._handleMouseUp,!0),window.addEventListener("touchend",this._handleMouseUp,!0)),this._transforming=!0;const l=t.target.getAbsolutePosition(),o=t.target.getStage().getPointerPosition();this._anchorDragOffset={x:o.x-l.x,y:o.y-l.y},Q9e++,this._fire("transformstart",{evt:t.evt,target:this.getNode()}),this._nodes.forEach(c=>{c._fire("transformstart",{evt:t.evt,target:c})})}_handleMouseMove(t){let n,r,a;const i=this.findOne("."+this._movingAnchorName),l=i.getStage();l.setPointersPositions(t);const o=l.getPointerPosition();let c={x:o.x-this._anchorDragOffset.x,y:o.y-this._anchorDragOffset.y};const d=i.getAbsolutePosition();this.anchorDragBoundFunc()&&(c=this.anchorDragBoundFunc()(d,c,t)),i.setAbsolutePosition(c);const u=i.getAbsolutePosition();if(d.x===u.x&&d.y===u.y)return;if(this._movingAnchorName==="rotater"){const _=this._getNodeRect();n=i.x()-_.width/2,r=-i.y()+_.height/2;const j=di.getAngle(this.rotateAnchorAngle());let C=Math.atan2(-r,n)+Math.PI/2-j;_.height<0&&(C-=Math.PI);const M=di.getAngle(this.rotation())+C,I=di.getAngle(this.rotationSnapTolerance()),R=PBs(this.rotationSnaps(),M,I)-_.rotation,O=MBs(_,R);this._fitNodesInto(O,t);return}const h=this.shiftBehavior();let m;h==="inverted"?m=this.keepRatio()&&!t.shiftKey:h==="none"?m=this.keepRatio():m=this.keepRatio()||t.shiftKey;let p=this.centeredScaling()||t.altKey;if(this._movingAnchorName==="top-left"){if(m){const _=p?{x:this.width()/2,y:this.height()/2}:{x:this.findOne(".bottom-right").x(),y:this.findOne(".bottom-right").y()};a=Math.sqrt(Math.pow(_.x-i.x(),2)+Math.pow(_.y-i.y(),2));const j=this.findOne(".top-left").x()>_.x?-1:1,C=this.findOne(".top-left").y()>_.y?-1:1;n=a*this.cos*j,r=a*this.sin*C,this.findOne(".top-left").x(_.x-n),this.findOne(".top-left").y(_.y-r)}}else if(this._movingAnchorName==="top-center")this.findOne(".top-left").y(i.y());else if(this._movingAnchorName==="top-right"){if(m){const _=p?{x:this.width()/2,y:this.height()/2}:{x:this.findOne(".bottom-left").x(),y:this.findOne(".bottom-left").y()};a=Math.sqrt(Math.pow(i.x()-_.x,2)+Math.pow(_.y-i.y(),2));const j=this.findOne(".top-right").x()<_.x?-1:1,C=this.findOne(".top-right").y()>_.y?-1:1;n=a*this.cos*j,r=a*this.sin*C,this.findOne(".top-right").x(_.x+n),this.findOne(".top-right").y(_.y-r)}var g=i.position();this.findOne(".top-left").y(g.y),this.findOne(".bottom-right").x(g.x)}else if(this._movingAnchorName==="middle-left")this.findOne(".top-left").x(i.x());else if(this._movingAnchorName==="middle-right")this.findOne(".bottom-right").x(i.x());else if(this._movingAnchorName==="bottom-left"){if(m){const _=p?{x:this.width()/2,y:this.height()/2}:{x:this.findOne(".top-right").x(),y:this.findOne(".top-right").y()};a=Math.sqrt(Math.pow(_.x-i.x(),2)+Math.pow(i.y()-_.y,2));const j=_.x{var i;a._fire("transformend",{evt:t,target:a}),(i=a.getLayer())===null||i===void 0||i.batchDraw()}),this._movingAnchorName=null}}_fitNodesInto(t,n){const r=di.autoDrawEnabled;di.autoDrawEnabled=!1;try{return this._doFitNodesInto(t,n)}finally{di.autoDrawEnabled=r}}_doFitNodesInto(t,n){const r=this._getNodeRect(),a=1;if(ir._inRange(t.width,-this.padding()*2-a,a)){this.update();return}if(ir._inRange(t.height,-this.padding()*2-a,a)){this.update();return}const i=new Uw;if(i.rotate(di.getAngle(this.rotation())),this._movingAnchorName&&t.width<0&&this._movingAnchorName.indexOf("left")>=0){const p=i.point({x:-this.padding()*2,y:0});t.x+=p.x,t.y+=p.y,t.width+=this.padding()*2,this._movingAnchorName=this._movingAnchorName.replace("left","right"),this._anchorDragOffset.x-=p.x,this._anchorDragOffset.y-=p.y}else if(this._movingAnchorName&&t.width<0&&this._movingAnchorName.indexOf("right")>=0){const p=i.point({x:this.padding()*2,y:0});this._movingAnchorName=this._movingAnchorName.replace("right","left"),this._anchorDragOffset.x-=p.x,this._anchorDragOffset.y-=p.y,t.width+=this.padding()*2}if(this._movingAnchorName&&t.height<0&&this._movingAnchorName.indexOf("top")>=0){const p=i.point({x:0,y:-this.padding()*2});t.x+=p.x,t.y+=p.y,this._movingAnchorName=this._movingAnchorName.replace("top","bottom"),this._anchorDragOffset.x-=p.x,this._anchorDragOffset.y-=p.y,t.height+=this.padding()*2}else if(this._movingAnchorName&&t.height<0&&this._movingAnchorName.indexOf("bottom")>=0){const p=i.point({x:0,y:this.padding()*2});this._movingAnchorName=this._movingAnchorName.replace("bottom","top"),this._anchorDragOffset.x-=p.x,this._anchorDragOffset.y-=p.y,t.height+=this.padding()*2}if(this.boundBoxFunc()){const p=this.boundBoxFunc()(r,t);p?t=p:ir.warn("boundBoxFunc returned falsy. You should return new bound rect from it!")}const l=1e7,o=new Uw;o.translate(r.x,r.y),o.rotate(r.rotation),o.scale(r.width/l,r.height/l);const c=new Uw,d=t.width/l,u=t.height/l;this.flipEnabled()===!1?(c.translate(t.x,t.y),c.rotate(t.rotation),c.translate(t.width<0?t.width:0,t.height<0?t.height:0),c.scale(Math.abs(d),Math.abs(u))):(c.translate(t.x,t.y),c.rotate(t.rotation),c.scale(d,u));const h=c.multiply(o.invert()),m=new Set;this._nodes.forEach(p=>{if(!p.getStage())return;const g=p.getParent().getAbsoluteTransform(),x=p.getTransform().copy();x.translate(p.offsetX(),p.offsetY());const y=new Uw;y.multiply(g.copy().invert()).multiply(h).multiply(g).multiply(x);const v=y.decompose();p.setAttrs(v);const _=p.getLayer();_&&m.add(_)}),this.rotation(ir._getRotation(t.rotation)),this._nodes.forEach(p=>{this._fire("transform",{evt:n,target:p}),p._fire("transform",{evt:n,target:p})}),this._resetTransformCache(),this.update(),m.add(this.getLayer()),m.forEach(p=>p&&p.batchDraw())}_scheduleUpdate(){this._updateScheduled||(this._updateScheduled=!0,ni._runAfterAbsTransformCascade(()=>{var t;this._updateScheduled=!1,!(!(!((t=this._nodes)===null||t===void 0)&&t.length)||this._transforming||this.isDragging())&&this.update()}))}forceUpdate(){this._resetTransformCache(),this.update()}_batchChangeChild(t,n){this.findOne(t).setAttrs(n)}update(){var t;const n=this._getNodeRect();this.rotation(ir._getRotation(n.rotation));const r=n.width,a=n.height,i=this.enabledAnchors(),l=this.resizeEnabled(),o=this.padding(),c=this.anchorSize(),d=this.find("._anchor");d.forEach(M=>{M.setAttrs({width:c,height:c,offsetX:c/2,offsetY:c/2,stroke:this.anchorStroke(),strokeWidth:this.anchorStrokeWidth(),fill:this.anchorFill(),cornerRadius:this.anchorCornerRadius()})}),this._batchChangeChild(".top-left",{x:0,y:0,offsetX:c/2+o,offsetY:c/2+o,visible:l&&i.indexOf("top-left")>=0}),this._batchChangeChild(".top-center",{x:r/2,y:0,offsetY:c/2+o,visible:l&&i.indexOf("top-center")>=0}),this._batchChangeChild(".top-right",{x:r,y:0,offsetX:c/2-o,offsetY:c/2+o,visible:l&&i.indexOf("top-right")>=0}),this._batchChangeChild(".middle-left",{x:0,y:a/2,offsetX:c/2+o,visible:l&&i.indexOf("middle-left")>=0}),this._batchChangeChild(".middle-right",{x:r,y:a/2,offsetX:c/2-o,visible:l&&i.indexOf("middle-right")>=0}),this._batchChangeChild(".bottom-left",{x:0,y:a,offsetX:c/2+o,offsetY:c/2-o,visible:l&&i.indexOf("bottom-left")>=0}),this._batchChangeChild(".bottom-center",{x:r/2,y:a,offsetY:c/2-o,visible:l&&i.indexOf("bottom-center")>=0}),this._batchChangeChild(".bottom-right",{x:r,y:a,offsetX:c/2-o,offsetY:c/2-o,visible:l&&i.indexOf("bottom-right")>=0});const u=this.rotateAnchorAngle(),h=this.rotateAnchorOffset(),m=ir.degToRad(u),p=Math.sin(m),g=-Math.cos(m),x=r/2,y=a/2;let v=1/0;g<0?v=Math.min(v,-y/g):g>0&&(v=Math.min(v,(a-y)/g)),p<0?v=Math.min(v,-x/p):p>0&&(v=Math.min(v,(r-x)/p));const _=x+p*v,j=y+g*v,C=ir._sign(a);this._batchChangeChild(".rotater",{x:_+p*h*C,y:j+g*h*C-o*g,visible:this.rotateEnabled()}),this._batchChangeChild(".back",{width:r,height:a,visible:this.borderEnabled(),stroke:this.borderStroke(),strokeWidth:this.borderStrokeWidth(),dash:this.borderDash(),draggable:this.nodes().some(M=>M.draggable()),x:0,y:0});const A=this.anchorStyleFunc();A&&d.forEach(M=>{A(M)}),(t=this.getLayer())===null||t===void 0||t.batchDraw()}isTransforming(){return this._transforming}stopTransform(){if(this._transforming){this._removeEvents();const t=this.findOne("."+this._movingAnchorName);t&&t.stopDrag()}}destroy(){return this.getStage()&&this._cursorChange&&this.getStage().content&&(this.getStage().content.style.cursor=""),MU.prototype.destroy.call(this),this.detach(),this._removeEvents(),this}add(...t){return this._elementsCreated?(ir.error("You cannot add external nodes to the Transformer. Use tr.nodes([node]) instead."),this):super.add(...t)}toObject(){return ni.prototype.toObject.call(this)}clone(t){return ni.prototype.clone.call(this,t)}getClientRect(){return this.nodes().length>0?super.getClientRect():{x:0,y:0,width:0,height:0}}};Yd.isTransforming=()=>Q9e>0;function IBs(s){return s instanceof Array||ir.warn("enabledAnchors value should be an array"),s instanceof Array&&s.forEach(function(t){p5e.indexOf(t)===-1&&ir.warn("Unknown anchor name: "+t+". Available names are: "+p5e.join(", "))}),s||[]}Yd.prototype.className="Transformer";Hp(Yd);gn.addGetterSetter(Yd,"enabledAnchors",p5e,IBs);gn.addGetterSetter(Yd,"flipEnabled",!0,Ak());gn.addGetterSetter(Yd,"resizeEnabled",!0);gn.addGetterSetter(Yd,"anchorSize",10,ii());gn.addGetterSetter(Yd,"rotateEnabled",!0);gn.addGetterSetter(Yd,"rotateLineVisible",!0);gn.addGetterSetter(Yd,"rotationSnaps",[]);gn.addGetterSetter(Yd,"rotateAnchorOffset",50,ii());gn.addGetterSetter(Yd,"rotateAnchorAngle",0,ii());gn.addGetterSetter(Yd,"rotateAnchorCursor","crosshair");gn.addGetterSetter(Yd,"rotationSnapTolerance",5,ii());gn.addGetterSetter(Yd,"borderEnabled",!0);gn.addGetterSetter(Yd,"anchorStroke","rgb(0, 161, 255)");gn.addGetterSetter(Yd,"anchorStrokeWidth",1,ii());gn.addGetterSetter(Yd,"anchorFill","white");gn.addGetterSetter(Yd,"anchorCornerRadius",0,ii());gn.addGetterSetter(Yd,"borderStroke","rgb(0, 161, 255)");gn.addGetterSetter(Yd,"borderStrokeWidth",1,ii());gn.addGetterSetter(Yd,"borderDash");gn.addGetterSetter(Yd,"keepRatio",!0);gn.addGetterSetter(Yd,"shiftBehavior","default");gn.addGetterSetter(Yd,"centeredScaling",!1);gn.addGetterSetter(Yd,"ignoreStroke",!1);gn.addGetterSetter(Yd,"padding",0,ii());gn.addGetterSetter(Yd,"nodes");gn.addGetterSetter(Yd,"node");gn.addGetterSetter(Yd,"boundBoxFunc");gn.addGetterSetter(Yd,"anchorDragBoundFunc");gn.addGetterSetter(Yd,"anchorStyleFunc");gn.addGetterSetter(Yd,"shouldOverdrawWholeArea",!1);gn.addGetterSetter(Yd,"useSingleNodeRotation",!0);gn.backCompat(Yd,{lineEnabled:"borderEnabled",rotateHandlerOffset:"rotateAnchorOffset",enabledHandlers:"enabledAnchors"});class cA extends Ya{_sceneFunc(t){t.beginPath(),t.arc(0,0,this.radius(),0,di.getAngle(this.angle()),this.clockwise()),t.lineTo(0,0),t.closePath(),t.fillStrokeShape(this)}getWidth(){return this.radius()*2}getHeight(){return this.radius()*2}setWidth(t){this.radius(t/2)}setHeight(t){this.radius(t/2)}}cA.prototype.className="Wedge";cA.prototype._centroid=!0;cA.prototype._attrsAffectingSize=["radius"];Hp(cA);gn.addGetterSetter(cA,"radius",0,ii());gn.addGetterSetter(cA,"angle",0,ii());gn.addGetterSetter(cA,"clockwise",!1);gn.backCompat(cA,{angleDeg:"angle",getAngleDeg:"getAngle",setAngleDeg:"setAngle"});function Sht(){this.r=0,this.g=0,this.b=0,this.a=0,this.next=null}const LBs=[512,512,456,512,328,456,335,512,405,328,271,456,388,335,292,512,454,405,364,328,298,271,496,456,420,388,360,335,312,292,273,512,482,454,428,405,383,364,345,328,312,298,284,271,259,496,475,456,437,420,404,388,374,360,347,335,323,312,302,292,282,273,265,512,497,482,468,454,441,428,417,405,394,383,373,364,354,345,337,328,320,312,305,298,291,284,278,271,265,259,507,496,485,475,465,456,446,437,428,420,412,404,396,388,381,374,367,360,354,347,341,335,329,323,318,312,307,302,297,292,287,282,278,273,269,265,261,512,505,497,489,482,475,468,461,454,447,441,435,428,422,417,411,405,399,394,389,383,378,373,368,364,359,354,350,345,341,337,332,328,324,320,316,312,309,305,301,298,294,291,287,284,281,278,274,271,268,265,262,259,257,507,501,496,491,485,480,475,470,465,460,456,451,446,442,437,433,428,424,420,416,412,408,404,400,396,392,388,385,381,377,374,370,367,363,360,357,354,350,347,344,341,338,335,332,329,326,323,320,318,315,312,310,307,304,302,299,297,294,292,289,287,285,282,280,278,275,273,271,269,267,265,263,261,259],RBs=[9,11,12,13,13,14,14,15,15,15,15,16,16,16,16,17,17,17,17,17,17,17,18,18,18,18,18,18,18,18,18,19,19,19,19,19,19,19,19,19,19,19,19,19,19,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24];function DBs(s,t){const n=s.data,r=s.width,a=s.height;let i,l,o,c,d,u,h,m,p,g,x,y,v,_,j,C,A,M,I,P;const R=t+t+1,O=r-1,B=a-1,U=t+1,G=U*(U+1)/2,H=new Sht,Y=LBs[t],se=RBs[t];let ee=null,oe=H,me=null,Q=null;for(let te=1;te>se,I!==0?(I=255/I,n[l]=(c*Y>>se)*I,n[l+1]=(d*Y>>se)*I,n[l+2]=(u*Y>>se)*I):n[l]=n[l+1]=n[l+2]=0,c-=m,d-=p,u-=g,h-=x,m-=me.r,p-=me.g,g-=me.b,x-=me.a,i=o+((i=le+t+1)>se,I>0?(I=255/I,n[i]=(c*Y>>se)*I,n[i+1]=(d*Y>>se)*I,n[i+2]=(u*Y>>se)*I):n[i]=n[i+1]=n[i+2]=0,c-=m,d-=p,u-=g,h-=x,m-=me.r,p-=me.g,g-=me.b,x-=me.a,i=te+((i=fe+U)0&&DBs(t,n)};gn.addGetterSetter(ni,"blurRadius",0,ii(),gn.afterSetFilter);const FBs=function(s){const t=this.brightness()*255,n=s.data,r=n.length;for(let a=0;a255?255:a,i=i<0?0:i>255?255:i,l=l<0?0:l>255?255:l,n[o]=a,n[o+1]=i,n[o+2]=l};gn.addGetterSetter(ni,"contrast",0,ii(),gn.afterSetFilter);const $Bs=function(s){var t,n,r,a,i,l,o,c,d;const u=s.data,h=s.width,m=s.height,p=Math.min(1,Math.max(0,(n=(t=this.embossStrength)===null||t===void 0?void 0:t.call(this))!==null&&n!==void 0?n:.5)),g=Math.min(1,Math.max(0,(a=(r=this.embossWhiteLevel)===null||r===void 0?void 0:r.call(this))!==null&&a!==void 0?a:.5)),y=(o={"top-left":315,top:270,"top-right":225,right:180,"bottom-right":135,bottom:90,"bottom-left":45,left:0}[(l=(i=this.embossDirection)===null||i===void 0?void 0:i.call(this))!==null&&l!==void 0?l:"top-left"])!==null&&o!==void 0?o:315,v=!!((d=(c=this.embossBlend)===null||c===void 0?void 0:c.call(this))!==null&&d!==void 0&&d),_=p*10,j=g*255,C=y*Math.PI/180,A=Math.cos(C),M=Math.sin(C),I=128/1020*_,P=new Uint8ClampedArray(u),R=new Float32Array(h*m);for(let H=0,Y=0;YH<0?0:H>255?255:H;for(let H=1;Ha&&(a=i),c=t[j+1],co&&(o=c),h=t[j+2],hu&&(u=h);a===r&&(a=255,r=0),o===l&&(o=255,l=0),u===d&&(u=255,d=0);let p,g,x,y,v,_;if(m>0)p=a+m*(255-a),g=r-m*(r-0),x=o+m*(255-o),y=l-m*(l-0),v=u+m*(255-u),_=d-m*(d-0);else{const j=(a+r)*.5;p=a+m*(a-j),g=r+m*(r-j);const C=(o+l)*.5;x=o+m*(o-C),y=l+m*(l-C);const A=(u+d)*.5;v=u+m*(u-A),_=d+m*(d-A)}for(let j=0;jd?m:d;const p=l,g=i,x=360/g*Math.PI/180;for(let y=0;yd?m:d;const p=l,g=i,x=0;let y,v;for(u=0;ut&&(C=j,A=0,M=-1),a=0;a=0&&p=0&&g=0&&p=0&&g=255*4?255:0}return l}function t$s(s,t,n){const r=[.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111],a=Math.round(Math.sqrt(r.length)),i=Math.floor(a/2),l=[];for(let o=0;o=0&&p=0&&g=n))for(let j=x;j=r)continue;const C=(n*j+_)*4;d+=l[C+0],u+=l[C+1],h+=l[C+2],m+=l[C+3],v+=1}d=d/v,u=u/v,h=h/v,m=m/v;for(let _=p;_=n))for(let j=x;j=r)continue;const C=(n*j+_)*4;l[C+0]=d,l[C+1]=u,l[C+2]=h,l[C+3]=m}}};gn.addGetterSetter(ni,"pixelSize",8,ii(),gn.afterSetFilter);const a$s=function(s){const t=Math.round(this.levels()*254)+1,n=s.data,r=n.length,a=255/t;for(let i=0;i255?255:s<0?0:Math.round(s)});gn.addGetterSetter(ni,"green",0,function(s){return this._filterUpToDate=!1,s>255?255:s<0?0:Math.round(s)});gn.addGetterSetter(ni,"blue",0,tLt,gn.afterSetFilter);const o$s=function(s){const t=s.data,n=t.length,r=this.red(),a=this.green(),i=this.blue(),l=this.alpha();for(let o=0;o255?255:s<0?0:Math.round(s)});gn.addGetterSetter(ni,"green",0,function(s){return this._filterUpToDate=!1,s>255?255:s<0?0:Math.round(s)});gn.addGetterSetter(ni,"blue",0,tLt,gn.afterSetFilter);gn.addGetterSetter(ni,"alpha",1,function(s){return this._filterUpToDate=!1,s>1?1:s<0?0:s});const l$s=function(s){const t=s.data,n=t.length;for(let r=0;r=128&&(n[r]=255-a,n[r+1]=255-i,n[r+2]=255-l)}return s},d$s=function(s){const t=this.threshold()*255,n=s.data,r=n.length;for(let a=0;a$n||it[Ds]!==It[$n]){var Pr=` `+it[Ds].replace(" at new "," at ");return J.displayName&&Pr.includes("")&&(Pr=Pr.replace("",J.displayName)),Pr}while(1<=Ds&&0<=$n);break}}}finally{To=!1,Error.prepareStackTrace=Le}return(J=J?J.displayName||J.name:"")?Ol(J):""}var $o=Object.prototype.hasOwnProperty,jh=[],Mu=-1;function dh(J){return{current:J}}function Jr(J){0>Mu||(J.current=jh[Mu],jh[Mu]=null,Mu--)}function Uo(J,ie){Mu++,jh[Mu]=J.current,J.current=ie}var fc={},Lc=dh(fc),Ss=dh(!1),wa=fc;function Ci(J,ie){var Le=J.type.contextTypes;if(!Le)return fc;var Qe=J.stateNode;if(Qe&&Qe.__reactInternalMemoizedUnmaskedChildContext===ie)return Qe.__reactInternalMemoizedMaskedChildContext;var it={},It;for(It in Le)it[It]=ie[It];return Qe&&(J=J.stateNode,J.__reactInternalMemoizedUnmaskedChildContext=ie,J.__reactInternalMemoizedMaskedChildContext=it),it}function fa(J){return J=J.childContextTypes,J!=null}function zn(){Jr(Ss),Jr(Lc)}function Rr(J,ie,Le){if(Lc.current!==fc)throw Error(l(168));Uo(Lc,ie),Uo(Ss,Le)}function ja(J,ie,Le){var Qe=J.stateNode;if(ie=ie.childContextTypes,typeof Qe.getChildContext!="function")return Le;Qe=Qe.getChildContext();for(var it in Qe)if(!(it in ie))throw Error(l(108,P(J)||"Unknown",it));return i({},Le,Qe)}function Il(J){return J=(J=J.stateNode)&&J.__reactInternalMemoizedMergedChildContext||fc,wa=Lc.current,Uo(Lc,J),Uo(Ss,Ss.current),!0}function zo(J,ie,Le){var Qe=J.stateNode;if(!Qe)throw Error(l(169));Le?(J=ja(J,ie,wa),Qe.__reactInternalMemoizedMergedChildContext=J,Jr(Ss),Jr(Lc),Uo(Lc,J)):Jr(Ss),Uo(Ss,Le)}var Hl=Math.clz32?Math.clz32:Mo,Cf=Math.log,oi=Math.LN2;function Mo(J){return J>>>=0,J===0?32:31-(Cf(J)/oi|0)|0}var zh=64,Gm=4194304;function Gu(J){switch(J&-J){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 J&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return J&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return J}}function Zd(J,ie){var Le=J.pendingLanes;if(Le===0)return 0;var Qe=0,it=J.suspendedLanes,It=J.pingedLanes,Ds=Le&268435455;if(Ds!==0){var $n=Ds&~it;$n!==0?Qe=Gu($n):(It&=Ds,It!==0&&(Qe=Gu(It)))}else Ds=Le&~it,Ds!==0?Qe=Gu(Ds):It!==0&&(Qe=Gu(It));if(Qe===0)return 0;if(ie!==0&&ie!==Qe&&!(ie&it)&&(it=Qe&-Qe,It=ie&-ie,it>=It||it===16&&(It&4194240)!==0))return ie;if(Qe&4&&(Qe|=Le&16),ie=J.entangledLanes,ie!==0)for(J=J.entanglements,ie&=Qe;0Le;Le++)ie.push(J);return ie}function Gp(J,ie,Le){J.pendingLanes|=ie,ie!==536870912&&(J.suspendedLanes=0,J.pingedLanes=0),J=J.eventTimes,ie=31-Hl(ie),J[ie]=Le}function Ef(J,ie){var Le=J.pendingLanes&~ie;J.pendingLanes=ie,J.suspendedLanes=0,J.pingedLanes=0,J.expiredLanes&=ie,J.mutableReadLanes&=ie,J.entangledLanes&=ie,ie=J.entanglements;var Qe=J.eventTimes;for(J=J.expirationTimes;0>=Ds,it-=Ds,qo=1<<32-Hl(ie)+it|Le<wc?(Ch=Al,Al=null):Ch=Al.sibling;var Bn=Di(tr,Al,qr[wc],Vi);if(Bn===null){Al===null&&(Al=Ch);break}J&&Al&&Bn.alternate===null&&ie(tr,Al),ar=It(Bn,ar,wc),xc===null?Vo=Bn:xc.sibling=Bn,xc=Bn,Al=Ch}if(wc===qr.length)return Le(tr,Al),cn&&Ti(tr,wc),Vo;if(Al===null){for(;wcwc?(Ch=Al,Al=null):Ch=Al.sibling;var hr=Di(tr,Al,Bn.value,Vi);if(hr===null){Al===null&&(Al=Ch);break}J&&Al&&hr.alternate===null&&ie(tr,Al),ar=It(hr,ar,wc),xc===null?Vo=hr:xc.sibling=hr,xc=hr,Al=Ch}if(Bn.done)return Le(tr,Al),cn&&Ti(tr,wc),Vo;if(Al===null){for(;!Bn.done;wc++,Bn=qr.next())Bn=Kl(tr,Bn.value,Vi),Bn!==null&&(ar=It(Bn,ar,wc),xc===null?Vo=Bn:xc.sibling=Bn,xc=Bn);return cn&&Ti(tr,wc),Vo}for(Al=Qe(tr,Al);!Bn.done;wc++,Bn=qr.next())Bn=cu(Al,tr,wc,Bn.value,Vi),Bn!==null&&(J&&Bn.alternate!==null&&Al.delete(Bn.key===null?wc:Bn.key),ar=It(Bn,ar,wc),xc===null?Vo=Bn:xc.sibling=Bn,xc=Bn);return J&&Al.forEach(function(Aj){return ie(tr,Aj)}),cn&&Ti(tr,wc),Vo}function vp(tr,ar,qr,Vi){if(typeof qr=="object"&&qr!==null&&qr.type===u&&qr.key===null&&(qr=qr.props.children),typeof qr=="object"&&qr!==null){switch(qr.$$typeof){case c:e:{for(var Vo=qr.key,xc=ar;xc!==null;){if(xc.key===Vo){if(Vo=qr.type,Vo===u){if(xc.tag===7){Le(tr,xc.sibling),ar=it(xc,qr.props.children),ar.return=tr,tr=ar;break e}}else if(xc.elementType===Vo||typeof Vo=="object"&&Vo!==null&&Vo.$$typeof===j&&ro(Vo)===xc.type){Le(tr,xc.sibling),ar=it(xc,qr.props),ar.ref=Rc(tr,xc,qr),ar.return=tr,tr=ar;break e}Le(tr,xc);break}else ie(tr,xc);xc=xc.sibling}qr.type===u?(ar=X_(qr.props.children,tr.mode,Vi,qr.key),ar.return=tr,tr=ar):(Vi=k4(qr.type,qr.key,qr.props,null,tr.mode,Vi),Vi.ref=Rc(tr,ar,qr),Vi.return=tr,tr=Vi)}return Ds(tr);case d:e:{for(xc=qr.key;ar!==null;){if(ar.key===xc)if(ar.tag===4&&ar.stateNode.containerInfo===qr.containerInfo&&ar.stateNode.implementation===qr.implementation){Le(tr,ar.sibling),ar=it(ar,qr.children||[]),ar.return=tr,tr=ar;break e}else{Le(tr,ar);break}else ie(tr,ar);ar=ar.sibling}ar=Q_(qr,tr.mode,Vi),ar.return=tr,tr=ar}return Ds(tr);case j:return xc=qr._init,vp(tr,ar,xc(qr._payload),Vi)}if(Y(qr))return Bd(tr,ar,qr,Vi);if(M(qr))return Qu(tr,ar,qr,Vi);xd(tr,qr)}return typeof qr=="string"&&qr!==""||typeof qr=="number"?(qr=""+qr,ar!==null&&ar.tag===6?(Le(tr,ar.sibling),ar=it(ar,qr),ar.return=tr,tr=ar):(Le(tr,ar),ar=S4(qr,tr.mode,Vi),ar.return=tr,tr=ar),Ds(tr)):Le(tr,ar)}return vp}var ed=pc(!0),Nh=pc(!1),xu=dh(null),Dd=null,td=null,Uh=null;function Nl(){Uh=td=Dd=null}function ld(J,ie,Le){Ue?(Uo(xu,ie._currentValue),ie._currentValue=Le):(Uo(xu,ie._currentValue2),ie._currentValue2=Le)}function cd(J){var ie=xu.current;Jr(xu),Ue?J._currentValue=ie:J._currentValue2=ie}function yd(J,ie,Le){for(;J!==null;){var Qe=J.alternate;if((J.childLanes&ie)!==ie?(J.childLanes|=ie,Qe!==null&&(Qe.childLanes|=ie)):Qe!==null&&(Qe.childLanes&ie)!==ie&&(Qe.childLanes|=ie),J===Le)break;J=J.return}}function Wu(J,ie){Dd=J,Uh=td=null,J=J.dependencies,J!==null&&J.firstContext!==null&&(J.lanes&ie&&(Cm=!0),J.firstContext=null)}function $c(J){var ie=Ue?J._currentValue:J._currentValue2;if(Uh!==J)if(J={context:J,memoizedValue:ie,next:null},td===null){if(Dd===null)throw Error(l(308));td=J,Dd.dependencies={lanes:0,firstContext:J}}else td=td.next=J;return ie}var Od=null;function yu(J){Od===null?Od=[J]:Od.push(J)}function Wm(J,ie,Le,Qe){var it=ie.interleaved;return it===null?(Le.next=Le,yu(ie)):(Le.next=it.next,it.next=Le),ie.interleaved=Le,lu(J,Qe)}function lu(J,ie){J.lanes|=ie;var Le=J.alternate;for(Le!==null&&(Le.lanes|=ie),Le=J,J=J.return;J!==null;)J.childLanes|=ie,Le=J.alternate,Le!==null&&(Le.childLanes|=ie),Le=J,J=J.return;return Le.tag===3?Le.stateNode:null}var rc=!1;function Ku(J){J.updateQueue={baseState:J.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function gc(J,ie){J=J.updateQueue,ie.updateQueue===J&&(ie.updateQueue={baseState:J.baseState,firstBaseUpdate:J.firstBaseUpdate,lastBaseUpdate:J.lastBaseUpdate,shared:J.shared,effects:J.effects})}function kl(J,ie){return{eventTime:J,lane:ie,tag:0,payload:null,callback:null,next:null}}function sd(J,ie,Le){var Qe=J.updateQueue;if(Qe===null)return null;if(Qe=Qe.shared,ll&2){var it=Qe.pending;return it===null?ie.next=ie:(ie.next=it.next,it.next=ie),Qe.pending=ie,lu(J,Le)}return it=Qe.interleaved,it===null?(ie.next=ie,yu(Qe)):(ie.next=it.next,it.next=ie),Qe.interleaved=ie,lu(J,Le)}function Tf(J,ie,Le){if(ie=ie.updateQueue,ie!==null&&(ie=ie.shared,(Le&4194240)!==0)){var Qe=ie.lanes;Qe&=J.pendingLanes,Le|=Qe,ie.lanes=Le,Wx(J,Le)}}function Pu(J,ie){var Le=J.updateQueue,Qe=J.alternate;if(Qe!==null&&(Qe=Qe.updateQueue,Le===Qe)){var it=null,It=null;if(Le=Le.firstBaseUpdate,Le!==null){do{var Ds={eventTime:Le.eventTime,lane:Le.lane,tag:Le.tag,payload:Le.payload,callback:Le.callback,next:null};It===null?it=It=Ds:It=It.next=Ds,Le=Le.next}while(Le!==null);It===null?it=It=ie:It=It.next=ie}else it=It=ie;Le={baseState:Qe.baseState,firstBaseUpdate:it,lastBaseUpdate:It,shared:Qe.shared,effects:Qe.effects},J.updateQueue=Le;return}J=Le.lastBaseUpdate,J===null?Le.firstBaseUpdate=ie:J.next=ie,Le.lastBaseUpdate=ie}function up(J,ie,Le,Qe){var it=J.updateQueue;rc=!1;var It=it.firstBaseUpdate,Ds=it.lastBaseUpdate,$n=it.shared.pending;if($n!==null){it.shared.pending=null;var Pr=$n,Sa=Pr.next;Pr.next=null,Ds===null?It=Sa:Ds.next=Sa,Ds=Pr;var qi=J.alternate;qi!==null&&(qi=qi.updateQueue,$n=qi.lastBaseUpdate,$n!==Ds&&($n===null?qi.firstBaseUpdate=Sa:$n.next=Sa,qi.lastBaseUpdate=Pr))}if(It!==null){var Kl=it.baseState;Ds=0,qi=Sa=Pr=null,$n=It;do{var Di=$n.lane,cu=$n.eventTime;if((Qe&Di)===Di){qi!==null&&(qi=qi.next={eventTime:cu,lane:0,tag:$n.tag,payload:$n.payload,callback:$n.callback,next:null});e:{var Bd=J,Qu=$n;switch(Di=ie,cu=Le,Qu.tag){case 1:if(Bd=Qu.payload,typeof Bd=="function"){Kl=Bd.call(cu,Kl,Di);break e}Kl=Bd;break e;case 3:Bd.flags=Bd.flags&-65537|128;case 0:if(Bd=Qu.payload,Di=typeof Bd=="function"?Bd.call(cu,Kl,Di):Bd,Di==null)break e;Kl=i({},Kl,Di);break e;case 2:rc=!0}}$n.callback!==null&&$n.lane!==0&&(J.flags|=64,Di=it.effects,Di===null?it.effects=[$n]:Di.push($n))}else cu={eventTime:cu,lane:Di,tag:$n.tag,payload:$n.payload,callback:$n.callback,next:null},qi===null?(Sa=qi=cu,Pr=Kl):qi=qi.next=cu,Ds|=Di;if($n=$n.next,$n===null){if($n=it.shared.pending,$n===null)break;Di=$n,$n=Di.next,Di.next=null,it.lastBaseUpdate=Di,it.shared.pending=null}}while(!0);if(qi===null&&(Pr=Kl),it.baseState=Pr,it.firstBaseUpdate=Sa,it.lastBaseUpdate=qi,ie=it.shared.interleaved,ie!==null){it=ie;do Ds|=it.lane,it=it.next;while(it!==ie)}else It===null&&(it.shared.lanes=0);M1|=Ds,J.lanes=Ds,J.memoizedState=Kl}}function Km(J,ie,Le){if(J=ie.effects,ie.effects=null,J!==null)for(ie=0;ieLe?Le:4,J(!0);var Qe=uh.transition;uh.transition={};try{J(!1),ie()}finally{rl=Le,uh.transition=Qe}}function Dy(){return Sl().memoizedState}function Fk(J,ie,Le){var Qe=Tv(J);if(Le={lane:Qe,action:Le,hasEagerState:!1,eagerState:null,next:null},Rf(J))Z2(ie,Le);else if(Le=Wm(J,ie,Le,Qe),Le!==null){var it=gp();tg(Le,J,Qe,it),C1(Le,ie,Qe)}}function fx(J,ie,Le){var Qe=Tv(J),it={lane:Qe,action:Le,hasEagerState:!1,eagerState:null,next:null};if(Rf(J))Z2(ie,it);else{var It=J.alternate;if(J.lanes===0&&(It===null||It.lanes===0)&&(It=ie.lastRenderedReducer,It!==null))try{var Ds=ie.lastRenderedState,$n=It(Ds,Le);if(it.hasEagerState=!0,it.eagerState=$n,rn($n,Ds)){var Pr=ie.interleaved;Pr===null?(it.next=it,yu(ie)):(it.next=Pr.next,Pr.next=it),ie.interleaved=it;return}}catch{}finally{}Le=Wm(J,ie,it,Qe),Le!==null&&(it=gp(),tg(Le,J,Qe,it),C1(Le,ie,Qe))}}function Rf(J){var ie=J.alternate;return J===al||ie!==null&&ie===al}function Z2(J,ie){$i=Or=!0;var Le=J.pending;Le===null?ie.next=ie:(ie.next=Le.next,Le.next=ie),J.pending=ie}function C1(J,ie,Le){if(Le&4194240){var Qe=ie.lanes;Qe&=J.pendingLanes,Le|=Qe,ie.lanes=Le,Wx(J,Le)}}var Qm={readContext:$c,useCallback:nd,useContext:nd,useEffect:nd,useImperativeHandle:nd,useInsertionEffect:nd,useLayoutEffect:nd,useMemo:nd,useReducer:nd,useRef:nd,useState:nd,useDebugValue:nd,useDeferredValue:nd,useTransition:nd,useMutableSource:nd,useSyncExternalStore:nd,useId:nd,unstable_isNewReconciler:!1},mp={readContext:$c,useCallback:function(J,ie){return Pf().memoizedState=[J,ie===void 0?null:ie],J},useContext:$c,useEffect:Iu,useImperativeHandle:function(J,ie,Le){return Le=Le!=null?Le.concat([J]):null,Xm(4194308,4,wv.bind(null,ie,J),Le)},useLayoutEffect:function(J,ie){return Xm(4194308,4,J,ie)},useInsertionEffect:function(J,ie){return Xm(4,2,J,ie)},useMemo:function(J,ie){var Le=Pf();return ie=ie===void 0?null:ie,J=J(),Le.memoizedState=[J,ie],J},useReducer:function(J,ie,Le){var Qe=Pf();return ie=Le!==void 0?Le(ie):ie,Qe.memoizedState=Qe.baseState=ie,J={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:J,lastRenderedState:ie},Qe.queue=J,J=J.dispatch=Fk.bind(null,al,J),[Qe.memoizedState,J]},useRef:function(J){var ie=Pf();return J={current:J},ie.memoizedState=J},useState:S1,useDebugValue:Ry,useDeferredValue:function(J){return Pf().memoizedState=J},useTransition:function(){var J=S1(!1),ie=J[0];return J=Ok.bind(null,J[1]),Pf().memoizedState=J,[ie,J]},useMutableSource:function(){},useSyncExternalStore:function(J,ie,Le){var Qe=al,it=Pf();if(cn){if(Le===void 0)throw Error(l(407));Le=Le()}else{if(Le=ie(),Du===null)throw Error(l(349));Xd&30||Ib(Qe,ie,Le)}it.memoizedState=Le;var It={value:Le,getSnapshot:ie};return it.queue=It,Iu(Yu.bind(null,Qe,It,J),[J]),Qe.flags|=2048,Zu(9,_v.bind(null,Qe,It,Le,ie),void 0,null),Le},useId:function(){var J=Pf(),ie=Du.identifierPrefix;if(cn){var Le=Ro,Qe=qo;Le=(Qe&~(1<<32-Hl(Qe)-1)).toString(32)+Le,ie=":"+ie+"R"+Le,Le=Qi++,0Db&&(ie.flags|=128,Qe=!0,dr(it,!1),ie.lanes=4194304)}else{if(!Qe)if(J=Mi(It),J!==null){if(ie.flags|=128,Qe=!0,J=J.updateQueue,J!==null&&(ie.updateQueue=J,ie.flags|=4),dr(it,!0),it.tail===null&&it.tailMode==="hidden"&&!It.alternate&&!cn)return Ws(ie),null}else 2*ot()-it.renderingStartTime>Db&&Le!==1073741824&&(ie.flags|=128,Qe=!0,dr(it,!1),ie.lanes=4194304);it.isBackwards?(It.sibling=ie.child,ie.child=It):(J=it.last,J!==null?J.sibling=It:ie.child=It,it.last=It)}return it.tail!==null?(ie=it.tail,it.rendering=ie,it.tail=ie.sibling,it.renderingStartTime=ot(),ie.sibling=null,J=Ec.current,Uo(Ec,Qe?J&1|2:J&1),ie):(Ws(ie),null);case 22:case 23:return xp(),Le=ie.memoizedState!==null,J!==null&&J.memoizedState!==null!==Le&&(ie.flags|=8192),Le&&ie.mode&1?zf&1073741824&&(Ws(ie),Be&&ie.subtreeFlags&6&&(ie.flags|=8192)):Ws(ie),null;case 24:return null;case 25:return null}throw Error(l(156,ie.tag))}function or(J,ie){switch(Bt(ie),ie.tag){case 1:return fa(ie.type)&&zn(),J=ie.flags,J&65536?(ie.flags=J&-65537|128,ie):null;case 3:return Sm(),Jr(Ss),Jr(Lc),ux(),J=ie.flags,J&65536&&!(J&128)?(ie.flags=J&-65537|128,ie):null;case 5:return da(ie),null;case 13:if(Jr(Ec),J=ie.memoizedState,J!==null&&J.dehydrated!==null){if(ie.alternate===null)throw Error(l(340));xa()}return J=ie.flags,J&65536?(ie.flags=J&-65537|128,ie):null;case 19:return Jr(Ec),null;case 4:return Sm(),null;case 10:return cd(ie.type._context),null;case 22:case 23:return xp(),null;case 24:return null;default:return null}}var zr=!1,rr=!1,Xr=typeof WeakSet=="function"?WeakSet:Set,Gn=null;function Na(J,ie){var Le=J.ref;if(Le!==null)if(typeof Le=="function")try{Le(null)}catch(Qe){Ou(J,ie,Qe)}else Le.current=null}function pa(J,ie,Le){try{Le()}catch(Qe){Ou(J,ie,Qe)}}var Yi=!1;function Ui(J,ie){for(me(J.containerInfo),Gn=ie;Gn!==null;)if(J=Gn,ie=J.child,(J.subtreeFlags&1028)!==0&&ie!==null)ie.return=J,Gn=ie;else for(;Gn!==null;){J=Gn;try{var Le=J.alternate;if(J.flags&1024)switch(J.tag){case 0:case 11:case 15:break;case 1:if(Le!==null){var Qe=Le.memoizedProps,it=Le.memoizedState,It=J.stateNode,Ds=It.getSnapshotBeforeUpdate(J.elementType===J.type?Qe:ef(J.type,Qe),it);It.__reactInternalSnapshotBeforeUpdate=Ds}break;case 3:Be&&An(J.stateNode.containerInfo);break;case 5:case 6:case 4:case 17:break;default:throw Error(l(163))}}catch($n){Ou(J,J.return,$n)}if(ie=J.sibling,ie!==null){ie.return=J.return,Gn=ie;break}Gn=J.return}return Le=Yi,Yi=!1,Le}function il(J,ie,Le){var Qe=ie.updateQueue;if(Qe=Qe!==null?Qe.lastEffect:null,Qe!==null){var it=Qe=Qe.next;do{if((it.tag&J)===J){var It=it.destroy;it.destroy=void 0,It!==void 0&&pa(ie,Le,It)}it=it.next}while(it!==Qe)}}function zi(J,ie){if(ie=ie.updateQueue,ie=ie!==null?ie.lastEffect:null,ie!==null){var Le=ie=ie.next;do{if((Le.tag&J)===J){var Qe=Le.create;Le.destroy=Qe()}Le=Le.next}while(Le!==ie)}}function _c(J){var ie=J.ref;if(ie!==null){var Le=J.stateNode;switch(J.tag){case 5:J=se(Le);break;default:J=Le}typeof ie=="function"?ie(J):ie.current=J}}function Vh(J){var ie=J.alternate;ie!==null&&(J.alternate=null,Vh(ie)),J.child=null,J.deletions=null,J.sibling=null,J.tag===5&&(ie=J.stateNode,ie!==null&&Fe(ie)),J.stateNode=null,J.return=null,J.dependencies=null,J.memoizedProps=null,J.memoizedState=null,J.pendingProps=null,J.stateNode=null,J.updateQueue=null}function Cl(J){return J.tag===5||J.tag===3||J.tag===4}function Hi(J){e:for(;;){for(;J.sibling===null;){if(J.return===null||Cl(J.return))return null;J=J.return}for(J.sibling.return=J.return,J=J.sibling;J.tag!==5&&J.tag!==6&&J.tag!==18;){if(J.flags&2||J.child===null||J.tag===4)continue e;J.child.return=J,J=J.child}if(!(J.flags&2))return J.stateNode}}function li(J,ie,Le){var Qe=J.tag;if(Qe===5||Qe===6)J=J.stateNode,ie?jt(Le,J,ie):Ut(Le,J);else if(Qe!==4&&(J=J.child,J!==null))for(li(J,ie,Le),J=J.sibling;J!==null;)li(J,ie,Le),J=J.sibling}function Do(J,ie,Le){var Qe=J.tag;if(Qe===5||Qe===6)J=J.stateNode,ie?dt(Le,J,ie):Ft(Le,J);else if(Qe!==4&&(J=J.child,J!==null))for(Do(J,ie,Le),J=J.sibling;J!==null;)Do(J,ie,Le),J=J.sibling}var po=null,ol=!1;function Uc(J,ie,Le){for(Le=Le.child;Le!==null;)tf(J,ie,Le),Le=Le.sibling}function tf(J,ie,Le){if(ns&&typeof ns.onCommitFiberUnmount=="function")try{ns.onCommitFiberUnmount(Xt,Le)}catch{}switch(Le.tag){case 5:rr||Na(Le,ie);case 6:if(Be){var Qe=po,it=ol;po=null,Uc(J,ie,Le),po=Qe,ol=it,po!==null&&(ol?rs(po,Le.stateNode):gt(po,Le.stateNode))}else Uc(J,ie,Le);break;case 18:Be&&po!==null&&(ol?Mr(po,Le.stateNode):Tn(po,Le.stateNode));break;case 4:Be?(Qe=po,it=ol,po=Le.stateNode.containerInfo,ol=!0,Uc(J,ie,Le),po=Qe,ol=it):(je&&(Qe=Le.stateNode.containerInfo,it=In(Qe),Ln(Qe,it)),Uc(J,ie,Le));break;case 0:case 11:case 14:case 15:if(!rr&&(Qe=Le.updateQueue,Qe!==null&&(Qe=Qe.lastEffect,Qe!==null))){it=Qe=Qe.next;do{var It=it,Ds=It.destroy;It=It.tag,Ds!==void 0&&(It&2||It&4)&&pa(Le,ie,Ds),it=it.next}while(it!==Qe)}Uc(J,ie,Le);break;case 1:if(!rr&&(Na(Le,ie),Qe=Le.stateNode,typeof Qe.componentWillUnmount=="function"))try{Qe.props=Le.memoizedProps,Qe.state=Le.memoizedState,Qe.componentWillUnmount()}catch($n){Ou(Le,ie,$n)}Uc(J,ie,Le);break;case 21:Uc(J,ie,Le);break;case 22:Le.mode&1?(rr=(Qe=rr)||Le.memoizedState!==null,Uc(J,ie,Le),rr=Qe):Uc(J,ie,Le);break;default:Uc(J,ie,Le)}}function Zp(J){var ie=J.updateQueue;if(ie!==null){J.updateQueue=null;var Le=J.stateNode;Le===null&&(Le=J.stateNode=new Xr),ie.forEach(function(Qe){var it=j4.bind(null,J,Qe);Le.has(Qe)||(Le.add(Qe),Qe.then(it,it))})}}function vd(J,ie){var Le=ie.deletions;if(Le!==null)for(var Qe=0;Qe";case Of:return":has("+(pp(J)||"")+")";case Xu:return'[role="'+J.value+'"]';case bd:return'"'+J.value+'"';case Qd:return'[data-testname="'+J.value+'"]';default:throw Error(l(365))}}function Xp(J,ie){var Le=[];J=[J,0];for(var Qe=0;Qeit&&(it=Ds),Qe&=~It}if(Qe=it,Qe=ot()-Qe,Qe=(120>Qe?120:480>Qe?480:1080>Qe?1080:1920>Qe?1920:3e3>Qe?3e3:4320>Qe?4320:1960*Dg(Qe/1960))-Qe,10J?16:J,I0===null)var Qe=!1;else{if(J=I0,I0=null,Ob=0,ll&6)throw Error(l(331));var it=ll;for(ll|=4,Gn=J.current;Gn!==null;){var It=Gn,Ds=It.child;if(Gn.flags&16){var $n=It.deletions;if($n!==null){for(var Pr=0;Pr<$n.length;Pr++){var Sa=$n[Pr];for(Gn=Sa;Gn!==null;){var qi=Gn;switch(qi.tag){case 0:case 11:case 15:il(8,qi,It)}var Kl=qi.child;if(Kl!==null)Kl.return=qi,Gn=Kl;else for(;Gn!==null;){qi=Gn;var Di=qi.sibling,cu=qi.return;if(Vh(qi),qi===Sa){Gn=null;break}if(Di!==null){Di.return=cu,Gn=Di;break}Gn=cu}}}var Bd=It.alternate;if(Bd!==null){var Qu=Bd.child;if(Qu!==null){Bd.child=null;do{var vp=Qu.sibling;Qu.sibling=null,Qu=vp}while(Qu!==null)}}Gn=It}}if(It.subtreeFlags&2064&&Ds!==null)Ds.return=It,Gn=Ds;else e:for(;Gn!==null;){if(It=Gn,It.flags&2048)switch(It.tag){case 0:case 11:case 15:il(9,It,It.return)}var tr=It.sibling;if(tr!==null){tr.return=It.return,Gn=tr;break e}Gn=It.return}}var ar=J.current;for(Gn=ar;Gn!==null;){Ds=Gn;var qr=Ds.child;if(Ds.subtreeFlags&2064&&qr!==null)qr.return=Ds,Gn=qr;else e:for(Ds=ar;Gn!==null;){if($n=Gn,$n.flags&2048)try{switch($n.tag){case 0:case 11:case 15:zi(9,$n)}}catch(Vo){Ou($n,$n.return,Vo)}if($n===Ds){Gn=null;break e}var Vi=$n.sibling;if(Vi!==null){Vi.return=$n.return,Gn=Vi;break e}Gn=$n.return}}if(ll=it,wr(),ns&&typeof ns.onPostCommitFiberRoot=="function")try{ns.onPostCommitFiberRoot(Xt,J)}catch{}Qe=!0}return Qe}finally{rl=Le,wd.transition=ie}}return!1}function C6(J,ie,Le){ie=Df(Le,ie),ie=Lg(J,ie,1),J=sd(J,ie,1),ie=gp(),J!==null&&(Gp(J,1,ie),Fg(J,ie))}function Ou(J,ie,Le){if(J.tag===3)C6(J,J,Le);else for(;ie!==null;){if(ie.tag===3){C6(ie,J,Le);break}else if(ie.tag===1){var Qe=ie.stateNode;if(typeof ie.type.getDerivedStateFromError=="function"||typeof Qe.componentDidCatch=="function"&&(P0===null||!P0.has(Qe))){J=Df(Le,J),J=fp(ie,J,1),ie=sd(ie,J,1),J=gp(),ie!==null&&(Gp(ie,1,J),Fg(ie,J));break}}ie=ie.return}}function _4(J,ie,Le){var Qe=J.pingCache;Qe!==null&&Qe.delete(ie),ie=gp(),J.pingedLanes|=J.suspendedLanes&Le,Du===J&&(Hh&Le)===Le&&(Sh===4||Sh===3&&(Hh&130023424)===Hh&&500>ot()-qk?L0(J,0):Jp|=Le),Fg(J,ie)}function w4(J,ie){ie===0&&(J.mode&1?(ie=Gm,Gm<<=1,!(Gm&130023424)&&(Gm=4194304)):ie=1);var Le=gp();J=lu(J,ie),J!==null&&(Gp(J,ie,Le),Fg(J,Le))}function A6(J){var ie=J.memoizedState,Le=0;ie!==null&&(Le=ie.retryLane),w4(J,Le)}function j4(J,ie){var Le=0;switch(J.tag){case 13:var Qe=J.stateNode,it=J.memoizedState;it!==null&&(Le=it.retryLane);break;case 19:Qe=J.stateNode;break;default:throw Error(l(314))}Qe!==null&&Qe.delete(ie),w4(J,Le)}var N4;N4=function(J,ie,Le){if(J!==null)if(J.memoizedProps!==ie.pendingProps||Ss.current)Cm=!0;else{if(!(J.lanes&Le)&&!(ie.flags&128))return Cm=!1,Et(J,ie,Le);Cm=!!(J.flags&131072)}else Cm=!1,cn&&ie.flags&1048576&&jo(ie,so,ie.index);switch(ie.lanes=0,ie.tag){case 2:var Qe=ie.type;$e(J,ie),J=ie.pendingProps;var it=Ci(ie,Lc.current);Wu(ie,Le),it=hp(null,ie,Qe,J,it,Le);var It=mx();return ie.flags|=1,typeof it=="object"&&it!==null&&typeof it.render=="function"&&it.$$typeof===void 0?(ie.tag=1,ie.memoizedState=null,ie.updateQueue=null,fa(Qe)?(It=!0,Il(ie)):It=!1,ie.memoizedState=it.state!==null&&it.state!==void 0?it.state:null,Ku(ie),it.updater=X2,ie.stateNode=it,it._reactInternals=ie,Oy(ie,Qe,J,Le),ie=T1(null,ie,Qe,!0,It,Le)):(ie.tag=0,cn&&It&&Xe(ie),qh(null,ie,it,Le),ie=ie.child),ie;case 16:Qe=ie.elementType;e:{switch($e(J,ie),J=ie.pendingProps,it=Qe._init,Qe=it(Qe._payload),ie.type=Qe,it=ie.tag=e7(Qe),J=ef(Qe,J),it){case 0:ie=H_(null,ie,Qe,J,Le);break e;case 1:ie=J2(null,ie,Qe,J,Le);break e;case 11:ie=A1(null,ie,Qe,J,Le);break e;case 14:ie=E1(null,ie,Qe,ef(Qe.type,J),Le);break e}throw Error(l(306,Qe,""))}return ie;case 0:return Qe=ie.type,it=ie.pendingProps,it=ie.elementType===Qe?it:ef(Qe,it),H_(J,ie,Qe,it,Le);case 1:return Qe=ie.type,it=ie.pendingProps,it=ie.elementType===Qe?it:ef(Qe,it),J2(J,ie,Qe,it,Le);case 3:e:{if(kj(ie),J===null)throw Error(l(387));Qe=ie.pendingProps,It=ie.memoizedState,it=It.element,gc(J,ie),up(ie,Qe,null,Le);var Ds=ie.memoizedState;if(Qe=Ds.element,Ye&&It.isDehydrated)if(It={element:Qe,isDehydrated:!1,cache:Ds.cache,pendingSuspenseBoundaries:Ds.pendingSuspenseBoundaries,transitions:Ds.transitions},ie.updateQueue.baseState=It,ie.memoizedState=It,ie.flags&256){it=Df(Error(l(423)),ie),ie=Sj(J,ie,Qe,Le,it);break e}else if(Qe!==it){it=Df(Error(l(424)),ie),ie=Sj(J,ie,Qe,Le,it);break e}else for(Ye&&(Hs=Ba(ie.stateNode.containerInfo),As=ie,cn=!0,fr=null,gr=!1),Le=Nh(ie,null,Qe,Le),ie.child=Le;Le;)Le.flags=Le.flags&-3|4096,Le=Le.sibling;else{if(xa(),Qe===it){ie=ft(J,ie,Le);break e}qh(J,ie,Qe,Le)}ie=ie.child}return ie;case 5:return Ig(ie),J===null&&yn(ie),Qe=ie.type,it=ie.pendingProps,It=J!==null?J.memoizedProps:null,Ds=it.children,ve(Qe,it)?Ds=null:It!==null&&ve(Qe,It)&&(ie.flags|=32),Q2(J,ie),qh(J,ie,Ds,Le),ie.child;case 6:return J===null&&yn(ie),null;case 13:return eN(J,ie,Le);case 4:return km(ie,ie.stateNode.containerInfo),Qe=ie.pendingProps,J===null?ie.child=ed(ie,null,Qe,Le):qh(J,ie,Qe,Le),ie.child;case 11:return Qe=ie.type,it=ie.pendingProps,it=ie.elementType===Qe?it:ef(Qe,it),A1(J,ie,Qe,it,Le);case 7:return qh(J,ie,ie.pendingProps,Le),ie.child;case 8:return qh(J,ie,ie.pendingProps.children,Le),ie.child;case 12:return qh(J,ie,ie.pendingProps.children,Le),ie.child;case 10:e:{if(Qe=ie.type._context,it=ie.pendingProps,It=ie.memoizedProps,Ds=it.value,ld(ie,Qe,Ds),It!==null)if(rn(It.value,Ds)){if(It.children===it.children&&!Ss.current){ie=ft(J,ie,Le);break e}}else for(It=ie.child,It!==null&&(It.return=ie);It!==null;){var $n=It.dependencies;if($n!==null){Ds=It.child;for(var Pr=$n.firstContext;Pr!==null;){if(Pr.context===Qe){if(It.tag===1){Pr=kl(-1,Le&-Le),Pr.tag=2;var Sa=It.updateQueue;if(Sa!==null){Sa=Sa.shared;var qi=Sa.pending;qi===null?Pr.next=Pr:(Pr.next=qi.next,qi.next=Pr),Sa.pending=Pr}}It.lanes|=Le,Pr=It.alternate,Pr!==null&&(Pr.lanes|=Le),yd(It.return,Le,ie),$n.lanes|=Le;break}Pr=Pr.next}}else if(It.tag===10)Ds=It.type===ie.type?null:It.child;else if(It.tag===18){if(Ds=It.return,Ds===null)throw Error(l(341));Ds.lanes|=Le,$n=Ds.alternate,$n!==null&&($n.lanes|=Le),yd(Ds,Le,ie),Ds=It.sibling}else Ds=It.child;if(Ds!==null)Ds.return=It;else for(Ds=It;Ds!==null;){if(Ds===ie){Ds=null;break}if(It=Ds.sibling,It!==null){It.return=Ds.return,Ds=It;break}Ds=Ds.return}It=Ds}qh(J,ie,it.children,Le),ie=ie.child}return ie;case 9:return it=ie.type,Qe=ie.pendingProps.children,Wu(ie,Le),it=$c(it),Qe=Qe(it),ie.flags|=1,qh(J,ie,Qe,Le),ie.child;case 14:return Qe=ie.type,it=ef(Qe,ie.pendingProps),it=ef(Qe.type,it),E1(J,ie,Qe,it,Le);case 15:return Yp(J,ie,ie.type,ie.pendingProps,Le);case 17:return Qe=ie.type,it=ie.pendingProps,it=ie.elementType===Qe?it:ef(Qe,it),$e(J,ie),ie.tag=1,fa(Qe)?(J=!0,Il(ie)):J=!1,Wu(ie,Le),x4(ie,Qe,it),Oy(ie,Qe,it,Le),T1(null,ie,Qe,!0,J,Le);case 19:return Ae(J,ie,Le);case 22:return kv(J,ie,Le)}throw Error(l(156,ie.tag))};function sN(J,ie){return Pg(J,ie)}function E6(J,ie,Le,Qe){this.tag=J,this.key=Le,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=ie,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=Qe,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function ey(J,ie,Le,Qe){return new E6(J,ie,Le,Qe)}function pA(J){return J=J.prototype,!(!J||!J.isReactComponent)}function e7(J){if(typeof J=="function")return pA(J)?1:0;if(J!=null){if(J=J.$$typeof,J===x)return 11;if(J===_)return 14}return 2}function Z_(J,ie){var Le=J.alternate;return Le===null?(Le=ey(J.tag,ie,J.key,J.mode),Le.elementType=J.elementType,Le.type=J.type,Le.stateNode=J.stateNode,Le.alternate=J,J.alternate=Le):(Le.pendingProps=ie,Le.type=J.type,Le.flags=0,Le.subtreeFlags=0,Le.deletions=null),Le.flags=J.flags&14680064,Le.childLanes=J.childLanes,Le.lanes=J.lanes,Le.child=J.child,Le.memoizedProps=J.memoizedProps,Le.memoizedState=J.memoizedState,Le.updateQueue=J.updateQueue,ie=J.dependencies,Le.dependencies=ie===null?null:{lanes:ie.lanes,firstContext:ie.firstContext},Le.sibling=J.sibling,Le.index=J.index,Le.ref=J.ref,Le}function k4(J,ie,Le,Qe,it,It){var Ds=2;if(Qe=J,typeof J=="function")pA(J)&&(Ds=1);else if(typeof J=="string")Ds=5;else e:switch(J){case u:return X_(Le.children,it,It,ie);case h:Ds=8,it|=8;break;case m:return J=ey(12,Le,ie,it|2),J.elementType=m,J.lanes=It,J;case y:return J=ey(13,Le,ie,it),J.elementType=y,J.lanes=It,J;case v:return J=ey(19,Le,ie,it),J.elementType=v,J.lanes=It,J;case C:return D0(Le,it,It,ie);default:if(typeof J=="object"&&J!==null)switch(J.$$typeof){case p:Ds=10;break e;case g:Ds=9;break e;case x:Ds=11;break e;case _:Ds=14;break e;case j:Ds=16,Qe=null;break e}throw Error(l(130,J==null?J:typeof J,""))}return ie=ey(Ds,Le,ie,it),ie.elementType=J,ie.type=Qe,ie.lanes=It,ie}function X_(J,ie,Le,Qe){return J=ey(7,J,Qe,ie),J.lanes=Le,J}function D0(J,ie,Le,Qe){return J=ey(22,J,Qe,ie),J.elementType=C,J.lanes=Le,J.stateNode={isHidden:!1},J}function S4(J,ie,Le){return J=ey(6,J,null,ie),J.lanes=Le,J}function Q_(J,ie,Le){return ie=ey(4,J.children!==null?J.children:[],J.key,ie),ie.lanes=Le,ie.stateNode={containerInfo:J.containerInfo,pendingChildren:null,implementation:J.implementation},ie}function t7(J,ie,Le,Qe,it){this.tag=ie,this.containerInfo=J,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=Ie,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=Af(0),this.expirationTimes=Af(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Af(0),this.identifierPrefix=Qe,this.onRecoverableError=it,Ye&&(this.mutableSourceEagerHydrationData=null)}function T6(J,ie,Le,Qe,it,It,Ds,$n,Pr){return J=new t7(J,ie,Le,$n,Pr),ie===1?(ie=1,It===!0&&(ie|=8)):ie=0,It=ey(3,null,null,ie),J.current=It,It.stateNode=J,It.memoizedState={element:Qe,isDehydrated:Le,cache:null,transitions:null,pendingSuspenseBoundaries:null},Ku(It),J}function gA(J){if(!J)return fc;J=J._reactInternals;e:{if(R(J)!==J||J.tag!==1)throw Error(l(170));var ie=J;do{switch(ie.tag){case 3:ie=ie.stateNode.context;break e;case 1:if(fa(ie.type)){ie=ie.stateNode.__reactInternalMemoizedMergedChildContext;break e}}ie=ie.return}while(ie!==null);throw Error(l(171))}if(J.tag===1){var Le=J.type;if(fa(Le))return ja(J,Le,ie)}return ie}function M6(J){var ie=J._reactInternals;if(ie===void 0)throw typeof J.render=="function"?Error(l(188)):(J=Object.keys(J).join(","),Error(l(268,J)));return J=U(ie),J===null?null:J.stateNode}function xA(J,ie){if(J=J.memoizedState,J!==null&&J.dehydrated!==null){var Le=J.retryLane;J.retryLane=Le!==0&&Le=Sa&&It>=Kl&&it<=qi&&Ds<=Di){J.splice(ie,1);break}else if(Qe!==Sa||Le.width!==Pr.width||DiDs){if(!(It!==Kl||Le.height!==Pr.height||qiit)){Sa>Qe&&(Pr.width+=Sa-Qe,Pr.x=Qe),qiIt&&(Pr.height+=Kl-It,Pr.y=It),DiLe&&(Le=Ds)),Ds ")+` No matching component was found for: `)+J.join(" > ")}return null},n.getPublicRootInstance=function(J){if(J=J.current,!J.child)return null;switch(J.child.tag){case 5:return se(J.child.stateNode);default:return J.child.stateNode}},n.injectIntoDevTools=function(J){if(J={bundleType:J.bundleType,version:J.version,rendererPackageName:J.rendererPackageName,rendererConfig:J.rendererConfig,overrideHookState:null,overrideHookStateDeletePath:null,overrideHookStateRenamePath:null,overrideProps:null,overridePropsDeletePath:null,overridePropsRenamePath:null,setErrorHandler:null,setSuspenseHandler:null,scheduleUpdate:null,currentDispatcherRef:o.ReactCurrentDispatcher,findHostInstanceByFiber:P6,findFiberByHostInstance:J.findFiberByHostInstance||nN,findHostInstancesForRefresh:null,scheduleRefresh:null,scheduleRoot:null,setRefreshHandler:null,getCurrentFiber:null,reconcilerVersion:"18.3.1"},typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u")J=!1;else{var ie=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(ie.isDisabled||!ie.supportsFiber)J=!0;else{try{Xt=ie.inject(J),ns=ie}catch{}J=!!ie.checkDCE}}return J},n.isAlreadyRendering=function(){return!1},n.observeVisibleRects=function(J,ie,Le,Qe){if(!yt)throw Error(l(363));J=Ff(J,ie);var it=rt(J,Le,Qe).disconnect;return{disconnect:function(){it()}}},n.registerMutableSourceForHydration=function(J,ie){var Le=ie._getVersion;Le=Le(ie._source),J.mutableSourceEagerHydrationData==null?J.mutableSourceEagerHydrationData=[ie,Le]:J.mutableSourceEagerHydrationData.push(ie,Le)},n.runWithPriority=function(J,ie){var Le=rl;try{return rl=J,ie()}finally{rl=Le}},n.shouldError=function(){return null},n.shouldSuspend=function(){return!1},n.updateContainer=function(J,ie,Le,Qe){var it=ie.current,It=gp(),Ds=Tv(it);return Le=gA(Le),ie.context===null?ie.context=Le:ie.pendingContext=Le,ie=kl(It,Ds),ie.payload={element:J},Qe=Qe===void 0?null:Qe,Qe!==null&&(ie.callback=Qe),J=sd(it,ie,Ds),J!==null&&(tg(J,it,Ds,It),Tf(J,it,Ds)),Ds},n};RLt.exports=u$s;var h$s=RLt.exports;const m$s=kd(h$s);var DLt={exports:{}},PF={};/** * @license React * react-reconciler-constants.production.min.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */PF.ConcurrentRoot=1;PF.ContinuousEventPriority=4;PF.DefaultEventPriority=16;PF.DiscreteEventPriority=1;PF.IdleEventPriority=536870912;PF.LegacyRoot=0;DLt.exports=PF;var OLt=DLt.exports;const Cht={children:!0,ref:!0,key:!0,style:!0,forwardedRef:!0,unstable_applyCache:!0,unstable_applyDrawHitFromCache:!0};let Aht=!1,Eht=!1;const UKe=".react-konva-event",f$s=`ReactKonva: You have a Konva node with draggable = true and position defined but no onDragMove or onDragEnd events are handled. Position of a node will be changed during drag&drop, so you should update state of the react app as well. Consider to add onDragMove or onDragEnd events. For more info see: https://github.com/konvajs/react-konva/issues/256 `,p$s=`ReactKonva: You are using "zIndex" attribute for a Konva node. react-konva may get confused with ordering. Just define correct order of elements in your render function of a component. For more info see: https://github.com/konvajs/react-konva/issues/194 `,g$s={};function qAe(s,t,n=g$s){if(!Aht&&"zIndex"in t&&(console.warn(p$s),Aht=!0),!Eht&&t.draggable){var r=t.x!==void 0||t.y!==void 0,a=t.onDragEnd||t.onDragMove;r&&!a&&(console.warn(f$s),Eht=!0)}for(var i in n)if(!Cht[i]){var l=i.slice(0,2)==="on",o=n[i]!==t[i];if(l&&o){var c=i.substr(2).toLowerCase();c.substr(0,7)==="content"&&(c="content"+c.substr(7,1).toUpperCase()+c.substr(8)),s.off(c,n[i])}var d=!t.hasOwnProperty(i);d&&s.setAttr(i,void 0)}var u=t._useStrictMode,h={},m=!1;const p={};for(var i in t)if(!Cht[i]){var l=i.slice(0,2)==="on",g=n[i]!==t[i];if(l&&g){var c=i.substr(2).toLowerCase();c.substr(0,7)==="content"&&(c="content"+c.substr(7,1).toUpperCase()+c.substr(8)),t[i]&&(p[c]=t[i])}!l&&(t[i]!==n[i]||u&&t[i]!==s.getAttr(i))&&(m=!0,h[i]=t[i])}m&&(s.setAttrs(h),h6(s));for(var c in p)s.on(c+UKe,p[c])}function h6(s){if(!di.autoDrawEnabled){var t=s.getLayer()||s.getStage();t&&t.batchDraw()}}const FLt={},x$s={};qO.Node.prototype._applyProps=qAe;function y$s(s,t){if(typeof t=="string"){console.error(`Do not use plain text as child of Konva.Node. You are using text: ${t}`);return}s.add(t),h6(s)}function v$s(s,t,n){let r=qO[s];r||(console.error(`Konva has no node with the type ${s}. Group will be used instead. If you use minimal version of react-konva, just import required nodes into Konva: "import "konva/lib/shapes/${s}" If you want to render DOM elements as part of canvas tree take a look into this demo: https://konvajs.github.io/docs/react/DOM_Portal.html`),r=qO.Group);const a={},i={};for(var l in t){var o=l.slice(0,2)==="on";o?i[l]=t[l]:a[l]=t[l]}const c=new r(a);return qAe(c,i),c}function b$s(s,t,n){console.error(`Text components are not supported for now in ReactKonva. Your text is: "${s}"`)}function _$s(s,t,n){return!1}function w$s(s){return s}function j$s(){return null}function N$s(){return null}function k$s(s,t,n,r){return x$s}function S$s(){}function C$s(s){}function A$s(s,t){return!1}function E$s(){return FLt}function T$s(){return FLt}const M$s=setTimeout,P$s=clearTimeout,I$s=-1;function L$s(s,t){return!1}const R$s=!1,D$s=!0,O$s=!0;function F$s(s,t){t.parent===s?t.moveToTop():s.add(t),h6(s)}function z$s(s,t){t.parent===s?t.moveToTop():s.add(t),h6(s)}function zLt(s,t,n){t._remove(),s.add(t),t.setZIndex(n.getZIndex()),h6(s)}function B$s(s,t,n){zLt(s,t,n)}function $$s(s,t){t.destroy(),t.off(UKe),h6(s)}function U$s(s,t){t.destroy(),t.off(UKe),h6(s)}function q$s(s,t,n){console.error(`Text components are not yet supported in ReactKonva. You text is: "${n}"`)}function V$s(s,t,n){}function H$s(s,t,n,r,a){qAe(s,a,r)}function G$s(s){s.hide(),h6(s)}function W$s(s){}function K$s(s,t){(t.visible==null||t.visible)&&s.show()}function Y$s(s,t){}function Z$s(s){}function X$s(){}const Q$s=()=>OLt.DefaultEventPriority,J$s=Object.freeze(Object.defineProperty({__proto__:null,appendChild:F$s,appendChildToContainer:z$s,appendInitialChild:y$s,cancelTimeout:P$s,clearContainer:Z$s,commitMount:V$s,commitTextUpdate:q$s,commitUpdate:H$s,createInstance:v$s,createTextInstance:b$s,detachDeletedInstance:X$s,finalizeInitialChildren:_$s,getChildHostContext:T$s,getCurrentEventPriority:Q$s,getPublicInstance:w$s,getRootHostContext:E$s,hideInstance:G$s,hideTextInstance:W$s,idlePriority:lK.unstable_IdlePriority,insertBefore:zLt,insertInContainerBefore:B$s,isPrimaryRenderer:R$s,noTimeout:I$s,now:lK.unstable_now,prepareForCommit:j$s,preparePortalMount:N$s,prepareUpdate:k$s,removeChild:$$s,removeChildFromContainer:U$s,resetAfterCommit:S$s,resetTextContent:C$s,run:lK.unstable_runWithPriority,scheduleTimeout:M$s,shouldDeprioritizeSubtree:A$s,shouldSetTextContent:L$s,supportsMutation:O$s,unhideInstance:K$s,unhideTextInstance:Y$s,warnsIfNotActing:D$s},Symbol.toStringTag,{value:"Module"}));var eUs=Object.defineProperty,tUs=Object.defineProperties,sUs=Object.getOwnPropertyDescriptors,Tht=Object.getOwnPropertySymbols,nUs=Object.prototype.hasOwnProperty,rUs=Object.prototype.propertyIsEnumerable,Mht=(s,t,n)=>t in s?eUs(s,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):s[t]=n,Pht=(s,t)=>{for(var n in t||(t={}))nUs.call(t,n)&&Mht(s,n,t[n]);if(Tht)for(var n of Tht(t))rUs.call(t,n)&&Mht(s,n,t[n]);return s},aUs=(s,t)=>tUs(s,sUs(t)),Iht,Lht;typeof window<"u"&&((Iht=window.document)!=null&&Iht.createElement||((Lht=window.navigator)==null?void 0:Lht.product)==="ReactNative")?k.useLayoutEffect:k.useEffect;function BLt(s,t,n){if(!s)return;if(n(s)===!0)return s;let r=s.child;for(;r;){const a=BLt(r,t,n);if(a)return a;r=r.sibling}}function $Lt(s){try{return Object.defineProperties(s,{_currentRenderer:{get(){return null},set(){}},_currentRenderer2:{get(){return null},set(){}}})}catch{return s}}const Rht=console.error;console.error=function(){const s=[...arguments].join("");if(s!=null&&s.startsWith("Warning:")&&s.includes("useContext")){console.error=Rht;return}return Rht.apply(this,arguments)};const qKe=$Lt(k.createContext(null));class ULt extends k.Component{render(){return k.createElement(qKe.Provider,{value:this._reactInternals},this.props.children)}}function iUs(){const s=k.useContext(qKe);if(s===null)throw new Error("its-fine: useFiber must be called within a !");const t=k.useId();return k.useMemo(()=>{for(const r of[s,s==null?void 0:s.alternate]){if(!r)continue;const a=BLt(r,!1,i=>{let l=i.memoizedState;for(;l;){if(l.memoizedState===t)return!0;l=l.next}});if(a)return a}},[s,t])}function oUs(){const s=iUs(),[t]=k.useState(()=>new Map);t.clear();let n=s;for(;n;){if(n.type&&typeof n.type=="object"){const a=n.type._context===void 0&&n.type.Provider===n.type?n.type:n.type._context;a&&a!==qKe&&!t.has(a)&&t.set(a,k.useContext($Lt(a)))}n=n.return}return t}function lUs(){const s=oUs();return k.useMemo(()=>Array.from(s.keys()).reduce((t,n)=>r=>k.createElement(t,null,k.createElement(n.Provider,aUs(Pht({},r),{value:s.get(n)}))),t=>k.createElement(ULt,Pht({},t))),[s])}function cUs(s){const t=zt.useRef({});return zt.useLayoutEffect(()=>{t.current=s}),zt.useLayoutEffect(()=>()=>{t.current={}},[]),t.current}const dUs=s=>{const t=zt.useRef(null),n=zt.useRef(null),r=zt.useRef(null),a=cUs(s),i=lUs(),l=o=>{const{forwardedRef:c}=s;c&&(typeof c=="function"?c(o):c.current=o)};return zt.useLayoutEffect(()=>(n.current=new qO.Stage({width:s.width,height:s.height,container:t.current}),l(n.current),r.current=RW.createContainer(n.current,OLt.LegacyRoot,!1,null),RW.updateContainer(zt.createElement(i,{},s.children),r.current),()=>{qO.isBrowser&&(l(null),RW.updateContainer(null,r.current,null),n.current.destroy())}),[]),zt.useLayoutEffect(()=>{l(n.current),qAe(n.current,s,a),RW.updateContainer(zt.createElement(i,{},s.children),r.current,null)}),zt.createElement("div",{ref:t,id:s.id,accessKey:s.accessKey,className:s.className,role:s.role,style:s.style,tabIndex:s.tabIndex,title:s.title})},uUs="Layer",jT="Group",_S="Rect",vz="Image",J7="Text",dJn="Transformer",RW=m$s(J$s);RW.injectIntoDevTools({findHostInstanceByFiber:()=>null,bundleType:0,version:zt.version,rendererPackageName:"react-konva"});const hUs=zt.forwardRef((s,t)=>zt.createElement(ULt,{},zt.createElement(dUs,{...s,forwardedRef:t})));function mUs({imageUrl:s,preset:t,barStyleId:n,overrides:r,maxDisplayWidth:a=720,stageRef:i}){const l=k.useRef(null),[o,c]=k.useState(null),[d,u]=k.useState(null),[h,m]=k.useState(null),p=(t==null?void 0:t.headshot_url)??"",g=(t==null?void 0:t.brokerage_logo_url)??"";k.useEffect(()=>{if(!s){c(null);return}const G=new window.Image;G.crossOrigin="anonymous",G.onload=()=>c(G),G.onerror=()=>c(null),G.src=s},[s]),k.useEffect(()=>{if(!p){u(null);return}const G=new window.Image;G.crossOrigin="anonymous",G.onload=()=>u(G),G.onerror=()=>u(null),G.src=p},[p]),k.useEffect(()=>{if(!g){m(null);return}const G=new window.Image;G.crossOrigin="anonymous",G.onload=()=>m(G),G.onerror=()=>m(null),G.src=g},[g]);const x=O9s(n),y=(o==null?void 0:o.naturalWidth)??1080,v=(o==null?void 0:o.naturalHeight)??1080,_=k.useMemo(()=>Math.min(1,a/y),[y,a]),j=y*_,C=v*_,A=(r==null?void 0:r.brand_color)??(t==null?void 0:t.brand_color)??"#0f172a",M=(r==null?void 0:r.accent_color)??(t==null?void 0:t.accent_color)??"#3b82f6",I=(r==null?void 0:r.display_name)??(t==null?void 0:t.display_name)??"",P=(r==null?void 0:r.phone)??(t==null?void 0:t.phone)??"",R=(r==null?void 0:r.email)??(t==null?void 0:t.email)??"",O=(r==null?void 0:r.tagline)??(t==null?void 0:t.tagline)??"",B=new Set((r==null?void 0:r.hidden_fields)??(t==null?void 0:t.hidden_fields)??[]),U=G=>x.fields.includes(G)&&!B.has(G);return e.jsx("div",{className:"border rounded-lg overflow-hidden bg-muted/40 inline-block",children:e.jsx(hUs,{ref:G=>{l.current=G,i&&(i.current=G)},width:j,height:C,scaleX:_,scaleY:_,children:e.jsxs(uUs,{children:[o&&e.jsx(vz,{image:o,width:y,height:v,listening:!1}),!o&&e.jsx(_S,{x:0,y:0,width:y,height:v,fill:"#e2e8f0"}),e.jsx(fUs,{style:x,canvasW:y,canvasH:v,brandColor:A,accentColor:M,name:I,phone:P,email:R,tagline:O,headshot:d,logo:h,hidden:B,has:U})]})})})}function fUs({style:s,canvasW:t,canvasH:n,brandColor:r,accentColor:a,name:i,phone:l,email:o,tagline:c,headshot:d,logo:u,has:h}){const m=n*s.heightRatio,p=m*.18,g=s.textColor==="light"?"#ffffff":s.textColor==="dark"?"#0f172a":s.background==="dark"||s.background==="gradient"?"#ffffff":F9s(r),x=g==="#ffffff"?"rgba(255,255,255,0.78)":"rgba(15,23,42,0.7)";if(s.position==="bottom"||s.position==="top"){const y=s.position==="bottom"?n-m:0;return e.jsxs(jT,{children:[e.jsx(_S,{x:0,y,width:t,height:m,fill:r}),e.jsx(_S,{x:0,y:s.position==="bottom"?y:m-4,width:t,height:4,fill:a}),e.jsx(Gre,{x:p,y:y+p,width:t-p*2,height:m-p*2,textColor:g,subTextColor:x,name:i,phone:l,email:o,tagline:c,headshot:d,logo:u,has:h,circular:s.circularHeadshot})]})}if(s.position==="corner-br"){const y=t*.42,v=m,_=t-y-n*.025,j=n-v-n*.025;return e.jsxs(jT,{children:[e.jsx(_S,{x:_,y:j,width:y,height:v,fill:r,cornerRadius:v*.12,opacity:.92}),e.jsx(_S,{x:_,y:j+v-4,width:y,height:4,fill:a,cornerRadius:2}),e.jsx(Gre,{x:_+p,y:j+p,width:y-p*2,height:v-p*2,textColor:g,subTextColor:x,name:i,phone:l,email:o,tagline:c,headshot:d,logo:u,has:h,circular:s.circularHeadshot})]})}if(s.position==="side-right"){const y=Math.max(t*.22,Math.min(t*.3,260)),v=y*.12;return e.jsxs(jT,{children:[e.jsx(_S,{x:t-y,y:0,width:y,height:n,fill:r}),e.jsx(_S,{x:t-y,y:0,width:4,height:n,fill:a}),e.jsx(Gre,{x:t-y+v,y:n*.08,width:y-v*2,height:n*.84,textColor:g,subTextColor:x,name:i,phone:l,email:o,tagline:c,headshot:d,logo:u,has:h,circular:s.circularHeadshot,vertical:!0,railWidth:y})]})}return s.position==="letterbox"?e.jsxs(jT,{children:[e.jsx(_S,{x:0,y:0,width:t,height:m,fill:"#0a0a0a"}),e.jsx(_S,{x:0,y:n-m,width:t,height:m,fill:"#0a0a0a"}),e.jsx(_S,{x:0,y:n-m,width:t,height:3,fill:a}),e.jsx(Gre,{x:p,y:n-m+p,width:t-p*2,height:m-p*2,textColor:"#ffffff",subTextColor:"rgba(255,255,255,0.75)",name:i,phone:l,email:o,tagline:c,headshot:d,logo:u,has:h,circular:s.circularHeadshot}),u&&h("logo")&&e.jsx(vz,{image:u,x:t-p-m*.7,y:p,height:m-p*2,width:m*.7})]}):null}function Gre({x:s,y:t,width:n,height:r,textColor:a,subTextColor:i,name:l,phone:o,email:c,tagline:d,headshot:u,logo:h,has:m,circular:p,vertical:g,railWidth:x}){if(g){const G=x??n,H=Math.min(n,G*.7),Y=Math.max(14,G*.13),se=Math.max(11,G*.085),ee=G*.08,oe=G*.35;let me=t;const Q=me;me+=H+ee;const te=me,le=l.length>12?2:1;me+=Y*1.15*le+ee*.5;const fe=me;m("phone")&&o&&(me+=se*1.3+ee*.4);const _e=me;m("email")&&c&&(me+=se*1.3+ee*.4);const ve=me+ee*.5;return e.jsxs(jT,{children:[m("headshot")&&u&&e.jsx(jT,{clipFunc:p?he=>{he.beginPath(),he.arc(s+n/2,Q+H/2,H/2,0,Math.PI*2),he.closePath()}:void 0,children:e.jsx(vz,{image:u,x:s+(n-H)/2,y:Q,width:H,height:H})}),m("name")&&l&&e.jsx(J7,{text:l,x:s,y:te,width:n,align:"center",fontSize:Y,fontStyle:"bold",fill:a}),m("phone")&&o&&e.jsx(J7,{text:o,x:s,y:fe,width:n,align:"center",fontSize:se,fill:i}),m("email")&&c&&e.jsx(J7,{text:c,x:s,y:_e,width:n,align:"center",fontSize:se,fill:i,ellipsis:!0,wrap:"none"}),m("logo")&&h&&e.jsx(vz,{image:h,x:s,y:ve,width:n,height:oe})]})}const y=r*.95,v=u&&m("headshot")?s+y+r*.18:s,_=n-(v-s)-(h&&m("logo")?r*1.6:0),j=Math.max(20,r*.34),C=Math.max(13,r*.22),A=r*.06,M=m("tagline")&&d?1:0,I=m("phone")&&o?1:0,P=m("email")&&c?1:0,R=1+M+(I||P?1:0),O=R*j+(R-1)*A;let U=t+(r-O)/2;return e.jsxs(jT,{children:[m("headshot")&&u&&e.jsx(jT,{clipFunc:p?G=>{G.beginPath(),G.arc(s+y/2,t+y/2,y/2,0,Math.PI*2),G.closePath()}:void 0,children:e.jsx(vz,{image:u,x:s,y:t+(r-y)/2,width:y,height:y})}),m("name")&&l&&e.jsx(J7,{text:l,x:v,y:U,width:_,fontSize:j,fontStyle:"bold",fill:a,ellipsis:!0,wrap:"none"}),(U+=j+A,null),m("tagline")&&d&&e.jsxs(e.Fragment,{children:[e.jsx(J7,{text:d,x:v,y:U,width:_,fontSize:C*1.1,fontStyle:"italic",fill:i,ellipsis:!0,wrap:"none"}),(U+=C*1.1+A,null)]}),I||P?e.jsx(J7,{text:[o,c].filter(Boolean).join(" • "),x:v,y:U,width:_,fontSize:C,fill:i,ellipsis:!0,wrap:"none"}):null,m("logo")&&h&&e.jsx(vz,{image:h,x:s+n-r*1.4,y:t+(r-r*.8)/2,width:r*1.4,height:r*.8})]})}function pUs(){const{data:s}=Bee(),t=(s==null?void 0:s.find(U=>U.is_default))??(s==null?void 0:s[0])??null,[n,r]=k.useState(void 0),a=(s==null?void 0:s.find(U=>U.id===n))??t,[i,l]=k.useState([]),[o,c]=k.useState(0),[d,u]=k.useState("minimal-stripe"),[h,m]=k.useState({}),[p,g]=k.useState(!1),x=k.useRef(null),[y,v]=k.useState(780),_=k.useRef(null),j=U=>{if(_.current&&(_.current.disconnect(),_.current=null),!U)return;const G=()=>{const Y=U.clientWidth;Y>0&&v(Math.min(780,Y-16))};G();const H=new ResizeObserver(G);H.observe(U),_.current=H};k.useEffect(()=>()=>{var U;(U=_.current)==null||U.disconnect()},[]);const C=k.useRef(null),A=U=>{if(!U)return;const G=[];Array.from(U).forEach(H=>{H.type.startsWith("image/")&&G.push({id:crypto.randomUUID(),url:URL.createObjectURL(H),file:H,name:H.name})}),l(H=>[...H,...G])},M=U=>{l(G=>{const H=G.find(Y=>Y.id===U);return H&&URL.revokeObjectURL(H.url),G.filter(Y=>Y.id!==U)}),c(0)},I=typeof navigator<"u"&&/iPad|iPhone|iPod/.test(navigator.userAgent),P=U=>{var oe;const[G,H]=U.split(","),Y=((oe=G.match(/:(.*?);/))==null?void 0:oe[1])??"image/jpeg",se=atob(H),ee=new Uint8Array(se.length);for(let me=0;me{var U;if(C.current){g(!0);try{const G=C.current,H=G.toDataURL({pixelRatio:1/(G.scaleX()||1),mimeType:"image/jpeg",quality:.95}),se=`${((U=i[o])==null?void 0:U.name.replace(/\.[^.]+$/,""))||"branded"}-branded.jpg`,ee=P(H),oe=URL.createObjectURL(ee);if(I)window.open(oe,"_blank")||(window.location.href=oe),ae.success('Long-press the image and tap "Save to Photos"');else{const me=document.createElement("a");me.href=oe,me.download=se,document.body.appendChild(me),me.click(),me.remove(),ae.success("Image exported")}setTimeout(()=>URL.revokeObjectURL(oe),6e4)}catch(G){ae.error(G.message||"Export failed")}finally{g(!1)}}},O=async()=>{if(i.length){g(!0);try{const U=new QIt,G=i.length,H=o;for(let ee=0;eesetTimeout(le,600)),!C.current)continue;const oe=C.current,Q=oe.toDataURL({pixelRatio:1/(oe.scaleX()||1),mimeType:"image/jpeg",quality:.95}).split(",")[1],te=i[ee].name.replace(/\.[^.]+$/,"")||`image-${ee+1}`;U.file(`${te}-branded.jpg`,Q,{base64:!0})}c(H);const Y=await U.generateAsync({type:"blob"}),se=document.createElement("a");se.href=URL.createObjectURL(Y),se.download=`branded-images-${Date.now()}.zip`,se.click(),URL.revokeObjectURL(se.href),ae.success(`${G} images exported`)}catch(U){ae.error(U.message||"Batch export failed")}finally{g(!1)}}},B=i[o];return e.jsx(Xs,{title:"Branding Bar Studio",children:e.jsxs("div",{className:"container max-w-7xl py-4 md:py-6 space-y-4 px-3 md:px-6",children:[e.jsx(Sc,{children:e.jsx("title",{children:"Branding Bar Studio | Marketing Studio"})}),e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-end sm:justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs(nr,{to:"/marketing-studio",className:"text-sm text-muted-foreground inline-flex items-center gap-1 hover:underline",children:[e.jsx(Ia,{className:"h-3 w-3"})," Marketing Studio"]}),e.jsx("h1",{className:"text-2xl md:text-3xl font-bold tracking-tight mt-1",children:"Branding Bar Studio"}),e.jsx("p",{className:"text-sm md:text-base text-muted-foreground",children:"Drop in any image, get a branded export. No AI credits used."})]}),e.jsx($,{variant:"outline",asChild:!0,className:"w-full sm:w-auto",children:e.jsxs(nr,{to:"/marketing-studio/brand-kit",children:[e.jsx(gd,{className:"h-4 w-4 mr-1"})," Brand Kit"]})})]}),!a&&e.jsx(we,{className:"border-dashed border-amber-500/50 bg-amber-500/5",children:e.jsxs(De,{className:"py-5 flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold",children:"Create your brand kit first"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"We'll pre-fill it from your profile so you can be exporting in seconds."})]}),e.jsx($,{asChild:!0,className:"w-full sm:w-auto",children:e.jsx(nr,{to:"/marketing-studio/brand-kit",children:"Set up brand"})})]})}),e.jsxs("div",{className:"grid gap-6 lg:grid-cols-[1fr_360px]",children:[e.jsxs("div",{className:"space-y-4 min-w-0",children:[e.jsx(we,{className:"overflow-hidden",children:e.jsxs(De,{className:"p-4",children:[B?e.jsx("div",{ref:j,className:"flex justify-center bg-muted/30 rounded p-2 overflow-hidden",children:e.jsx(mUs,{imageUrl:B.url,preset:a,barStyleId:d,overrides:h,maxDisplayWidth:y,stageRef:C})}):e.jsxs("div",{className:"border-2 border-dashed rounded-lg p-12 text-center space-y-3 cursor-pointer hover:bg-muted/30 transition-colors",onClick:()=>{var U;return(U=x.current)==null?void 0:U.click()},onDragOver:U=>U.preventDefault(),onDrop:U=>{U.preventDefault(),A(U.dataTransfer.files)},children:[e.jsx(zc,{className:"h-12 w-12 mx-auto text-muted-foreground/60"}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-medium",children:"Drop images here or click to browse"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Add up to 50 photos at once. We'll batch-brand them all."})]}),e.jsxs($,{type:"button",children:[e.jsx(gi,{className:"h-4 w-4 mr-1"})," Choose images"]})]}),e.jsx("input",{ref:x,type:"file",accept:"image/*",multiple:!0,hidden:!0,onChange:U=>A(U.target.files)})]})}),i.length>0&&e.jsx(we,{className:"overflow-hidden",children:e.jsx(De,{className:"p-3",children:e.jsxs("div",{className:"flex gap-2 overflow-x-auto py-1",children:[i.map((U,G)=>e.jsxs("div",{className:"relative group flex-shrink-0",children:[e.jsx("button",{onClick:()=>c(G),className:`block h-16 w-16 rounded overflow-hidden border-2 transition-all ${G===o?"border-primary":"border-transparent hover:border-muted-foreground/30"}`,children:e.jsx("img",{src:U.url,alt:"",className:"h-full w-full object-cover"})}),e.jsx("button",{onClick:()=>M(U.id),className:"absolute -top-1 -right-1 bg-destructive text-destructive-foreground rounded-full p-0.5 opacity-0 group-hover:opacity-100 transition-opacity",children:e.jsx(mr,{className:"h-3 w-3"})})]},U.id)),e.jsx("button",{onClick:()=>{var U;return(U=x.current)==null?void 0:U.click()},className:"flex-shrink-0 h-16 w-16 rounded border-2 border-dashed flex items-center justify-center hover:bg-muted/40",children:e.jsx(nn,{className:"h-5 w-5 text-muted-foreground"})})]})})}),i.length>0&&e.jsxs("div",{className:"flex flex-wrap gap-2 justify-end",children:[e.jsx($,{variant:"outline",onClick:()=>{i.forEach(U=>URL.revokeObjectURL(U.url)),l([])},children:"Clear all"}),e.jsxs($,{onClick:R,disabled:p||!B,children:[p?e.jsx(Jt,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(ji,{className:"h-4 w-4 mr-1"}),"Download this image"]}),i.length>1&&e.jsxs($,{onClick:O,disabled:p,children:[p?e.jsx(Jt,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(ji,{className:"h-4 w-4 mr-1"}),"Download all (",i.length,") as ZIP"]})]})]}),e.jsxs("div",{className:"space-y-4 min-w-0",children:[e.jsxs(we,{className:"overflow-hidden",children:[e.jsx(Vt,{className:"pb-2",children:e.jsx(Yt,{className:"text-base",children:"Brand preset"})}),e.jsx(De,{children:e.jsxs(bs,{value:(a==null?void 0:a.id)??"",onValueChange:r,children:[e.jsx(ys,{children:e.jsx(_s,{placeholder:"Choose preset"})}),e.jsx(vs,{children:s==null?void 0:s.map(U=>e.jsxs(We,{value:U.id,children:[U.name," ",U.is_default?"(default)":""]},U.id))})]})})]}),e.jsxs(we,{className:"overflow-hidden",children:[e.jsx(Vt,{className:"pb-2",children:e.jsx(Yt,{className:"text-base",children:"Bar style"})}),e.jsx(De,{children:e.jsx(z9s,{value:d,onChange:u,mediaType:"image"})})]}),e.jsxs(we,{className:"overflow-hidden",children:[e.jsx(Vt,{className:"pb-2",children:e.jsx(Yt,{className:"text-base",children:"Tweak this design"})}),e.jsx(De,{children:e.jsxs(ya,{defaultValue:"text",children:[e.jsxs(va,{className:"grid grid-cols-2 w-full",children:[e.jsx(is,{value:"text",children:"Text"}),e.jsx(is,{value:"colors",children:"Colors"})]}),e.jsxs(cs,{value:"text",className:"space-y-3 pt-3",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Display name"}),e.jsx(be,{value:h.display_name??(a==null?void 0:a.display_name)??"",onChange:U=>m({...h,display_name:U.target.value})})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Phone"}),e.jsx(be,{value:h.phone??(a==null?void 0:a.phone)??"",onChange:U=>m({...h,phone:U.target.value})})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Email"}),e.jsx(be,{value:h.email??(a==null?void 0:a.email)??"",onChange:U=>m({...h,email:U.target.value})})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Tagline"}),e.jsx(be,{value:h.tagline??(a==null?void 0:a.tagline)??"",onChange:U=>m({...h,tagline:U.target.value})})]})]}),e.jsxs(cs,{value:"colors",className:"space-y-3 pt-3",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Bar color"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"color",value:h.brand_color??(a==null?void 0:a.brand_color)??"#0f172a",onChange:U=>m({...h,brand_color:U.target.value}),className:"h-10 w-14 rounded border cursor-pointer"}),e.jsx(be,{value:h.brand_color??(a==null?void 0:a.brand_color)??"#0f172a",onChange:U=>m({...h,brand_color:U.target.value})})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Accent line"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"color",value:h.accent_color??(a==null?void 0:a.accent_color)??"#3b82f6",onChange:U=>m({...h,accent_color:U.target.value}),className:"h-10 w-14 rounded border cursor-pointer"}),e.jsx(be,{value:h.accent_color??(a==null?void 0:a.accent_color)??"#3b82f6",onChange:U=>m({...h,accent_color:U.target.value})})]})]}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>m({}),children:"Reset to preset"})]})]})})]})]})]})]})})}function gUs(s,t){if(s.match(/^[a-z]+:\/\//i))return s;if(s.match(/^\/\//))return window.location.protocol+s;if(s.match(/^[a-z]+:/i))return s;const n=document.implementation.createHTMLDocument(),r=n.createElement("base"),a=n.createElement("a");return n.head.appendChild(r),n.body.appendChild(a),t&&(r.href=t),a.href=s,a.href}const xUs=(()=>{let s=0;const t=()=>`0000${(Math.random()*36**4<<0).toString(36)}`.slice(-4);return()=>(s+=1,`u${t()}${s}`)})();function fM(s){const t=[];for(let n=0,r=s.length;nlw||s.height>lw)&&(s.width>lw&&s.height>lw?s.width>s.height?(s.height*=lw/s.width,s.width=lw):(s.width*=lw/s.height,s.height=lw):s.width>lw?(s.height*=lw/s.width,s.width=lw):(s.width*=lw/s.height,s.height=lw))}function x5e(s){return new Promise((t,n)=>{const r=new Image;r.onload=()=>{r.decode().then(()=>{requestAnimationFrame(()=>t(r))})},r.onerror=n,r.crossOrigin="anonymous",r.decoding="async",r.src=s})}async function wUs(s){return Promise.resolve().then(()=>new XMLSerializer().serializeToString(s)).then(encodeURIComponent).then(t=>`data:image/svg+xml;charset=utf-8,${t}`)}async function jUs(s,t,n){const r="http://www.w3.org/2000/svg",a=document.createElementNS(r,"svg"),i=document.createElementNS(r,"foreignObject");return a.setAttribute("width",`${t}`),a.setAttribute("height",`${n}`),a.setAttribute("viewBox",`0 0 ${t} ${n}`),i.setAttribute("width","100%"),i.setAttribute("height","100%"),i.setAttribute("x","0"),i.setAttribute("y","0"),i.setAttribute("externalResourcesRequired","true"),a.appendChild(i),i.appendChild(s),wUs(a)}const S_=(s,t)=>{if(s instanceof t)return!0;const n=Object.getPrototypeOf(s);return n===null?!1:n.constructor.name===t.name||S_(n,t)};function NUs(s){const t=s.getPropertyValue("content");return`${s.cssText} content: '${t.replace(/'|"/g,"")}';`}function kUs(s,t){return qLt(t).map(n=>{const r=s.getPropertyValue(n),a=s.getPropertyPriority(n);return`${n}: ${r}${a?" !important":""};`}).join(" ")}function SUs(s,t,n,r){const a=`.${s}:${t}`,i=n.cssText?NUs(n):kUs(n,r);return document.createTextNode(`${a}{${i}}`)}function Dht(s,t,n,r){const a=window.getComputedStyle(s,n),i=a.getPropertyValue("content");if(i===""||i==="none")return;const l=xUs();try{t.className=`${t.className} ${l}`}catch{return}const o=document.createElement("style");o.appendChild(SUs(l,n,a,r)),t.appendChild(o)}function CUs(s,t,n){Dht(s,t,":before",n),Dht(s,t,":after",n)}const Oht="application/font-woff",Fht="image/jpeg",AUs={woff:Oht,woff2:Oht,ttf:"application/font-truetype",eot:"application/vnd.ms-fontobject",png:"image/png",jpg:Fht,jpeg:Fht,gif:"image/gif",tiff:"image/tiff",svg:"image/svg+xml",webp:"image/webp"};function EUs(s){const t=/\.([^./]*?)$/g.exec(s);return t?t[1]:""}function VKe(s){const t=EUs(s).toLowerCase();return AUs[t]||""}function TUs(s){return s.split(/,/)[1]}function J9e(s){return s.search(/^(data:)/)!==-1}function MUs(s,t){return`data:${t};base64,${s}`}async function HLt(s,t,n){const r=await fetch(s,t);if(r.status===404)throw new Error(`Resource "${r.url}" not found`);const a=await r.blob();return new Promise((i,l)=>{const o=new FileReader;o.onerror=l,o.onloadend=()=>{try{i(n({res:r,result:o.result}))}catch(c){l(c)}},o.readAsDataURL(a)})}const YLe={};function PUs(s,t,n){let r=s.replace(/\?.*/,"");return n&&(r=s),/ttf|otf|eot|woff2?/i.test(r)&&(r=r.replace(/.*\//,"")),t?`[${t}]${r}`:r}async function HKe(s,t,n){const r=PUs(s,t,n.includeQueryParams);if(YLe[r]!=null)return YLe[r];n.cacheBust&&(s+=(/\?/.test(s)?"&":"?")+new Date().getTime());let a;try{const i=await HLt(s,n.fetchRequestInit,({res:l,result:o})=>(t||(t=l.headers.get("Content-Type")||""),TUs(o)));a=MUs(i,t)}catch(i){a=n.imagePlaceholder||"";let l=`Failed to fetch resource: ${s}`;i&&(l=typeof i=="string"?i:i.message),l&&console.warn(l)}return YLe[r]=a,a}async function IUs(s){const t=s.toDataURL();return t==="data:,"?s.cloneNode(!1):x5e(t)}async function LUs(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 x5e(o)}const n=s.poster,r=VKe(n),a=await HKe(n,r,t);return x5e(a)}async function RUs(s,t){var n;try{if(!((n=s==null?void 0:s.contentDocument)===null||n===void 0)&&n.body)return await VAe(s.contentDocument.body,t,!0)}catch{}return s.cloneNode(!1)}async function DUs(s,t){return S_(s,HTMLCanvasElement)?IUs(s):S_(s,HTMLVideoElement)?LUs(s,t):S_(s,HTMLIFrameElement)?RUs(s,t):s.cloneNode(GLt(s))}const OUs=s=>s.tagName!=null&&s.tagName.toUpperCase()==="SLOT",GLt=s=>s.tagName!=null&&s.tagName.toUpperCase()==="SVG";async function FUs(s,t,n){var r,a;if(GLt(t))return t;let i=[];return OUs(s)&&s.assignedNodes?i=fM(s.assignedNodes()):S_(s,HTMLIFrameElement)&&(!((r=s.contentDocument)===null||r===void 0)&&r.body)?i=fM(s.contentDocument.body.childNodes):i=fM(((a=s.shadowRoot)!==null&&a!==void 0?a:s).childNodes),i.length===0||S_(s,HTMLVideoElement)||await i.reduce((l,o)=>l.then(()=>VAe(o,n)).then(c=>{c&&t.appendChild(c)}),Promise.resolve()),t}function zUs(s,t,n){const r=t.style;if(!r)return;const a=window.getComputedStyle(s);a.cssText?(r.cssText=a.cssText,r.transformOrigin=a.transformOrigin):qLt(n).forEach(i=>{let l=a.getPropertyValue(i);i==="font-size"&&l.endsWith("px")&&(l=`${Math.floor(parseFloat(l.substring(0,l.length-2)))-.1}px`),S_(s,HTMLIFrameElement)&&i==="display"&&l==="inline"&&(l="block"),i==="d"&&t.getAttribute("d")&&(l=`path(${t.getAttribute("d")})`),r.setProperty(i,l,a.getPropertyPriority(i))})}function BUs(s,t){S_(s,HTMLTextAreaElement)&&(t.innerHTML=s.value),S_(s,HTMLInputElement)&&t.setAttribute("value",s.value)}function $Us(s,t){if(S_(s,HTMLSelectElement)){const n=t,r=Array.from(n.children).find(a=>s.value===a.getAttribute("value"));r&&r.setAttribute("selected","")}}function UUs(s,t,n){return S_(t,Element)&&(zUs(s,t,n),CUs(s,t,n),BUs(s,t),$Us(s,t)),t}async function qUs(s,t){const n=s.querySelectorAll?s.querySelectorAll("use"):[];if(n.length===0)return s;const r={};for(let i=0;iDUs(r,t)).then(r=>FUs(s,r,t)).then(r=>UUs(s,r,t)).then(r=>qUs(r,t))}const WLt=/url\((['"]?)([^'"]+?)\1\)/g,VUs=/url\([^)]+\)\s*format\((["']?)([^"']+)\1\)/g,HUs=/src:\s*(?:url\([^)]+\)\s*format\([^)]+\)[,;]\s*)+/g;function GUs(s){const t=s.replace(/([.*+?^${}()|\[\]\/\\])/g,"\\$1");return new RegExp(`(url\\(['"]?)(${t})(['"]?\\))`,"g")}function WUs(s){const t=[];return s.replace(WLt,(n,r,a)=>(t.push(a),n)),t.filter(n=>!J9e(n))}async function KUs(s,t,n,r,a){try{const i=n?gUs(t,n):t,l=VKe(t);let o;return a||(o=await HKe(i,l,r)),s.replace(GUs(t),`$1${o}$3`)}catch{}return s}function YUs(s,{preferredFontFormat:t}){return t?s.replace(HUs,n=>{for(;;){const[r,,a]=VUs.exec(n)||[];if(!a)return"";if(a===t)return`src: ${r};`}}):s}function KLt(s){return s.search(WLt)!==-1}async function YLt(s,t,n){if(!KLt(s))return s;const r=YUs(s,n);return WUs(r).reduce((i,l)=>i.then(o=>KUs(o,l,t,n)),Promise.resolve(r))}async function t9(s,t,n){var r;const a=(r=t.style)===null||r===void 0?void 0:r.getPropertyValue(s);if(a){const i=await YLt(a,null,n);return t.style.setProperty(s,i,t.style.getPropertyPriority(s)),!0}return!1}async function ZUs(s,t){await t9("background",s,t)||await t9("background-image",s,t),await t9("mask",s,t)||await t9("-webkit-mask",s,t)||await t9("mask-image",s,t)||await t9("-webkit-mask-image",s,t)}async function XUs(s,t){const n=S_(s,HTMLImageElement);if(!(n&&!J9e(s.src))&&!(S_(s,SVGImageElement)&&!J9e(s.href.baseVal)))return;const r=n?s.src:s.href.baseVal,a=await HKe(r,VKe(r),t);await new Promise((i,l)=>{s.onload=i,s.onerror=t.onImageErrorHandler?(...c)=>{try{i(t.onImageErrorHandler(...c))}catch(d){l(d)}}:l;const o=s;o.decode&&(o.decode=i),o.loading==="lazy"&&(o.loading="eager"),n?(s.srcset="",s.src=a):s.href.baseVal=a})}async function QUs(s,t){const r=fM(s.childNodes).map(a=>ZLt(a,t));await Promise.all(r).then(()=>s)}async function ZLt(s,t){S_(s,Element)&&(await ZUs(s,t),await XUs(s,t),await QUs(s,t))}function JUs(s,t){const{style:n}=s;t.backgroundColor&&(n.backgroundColor=t.backgroundColor),t.width&&(n.width=`${t.width}px`),t.height&&(n.height=`${t.height}px`);const r=t.style;return r!=null&&Object.keys(r).forEach(a=>{n[a]=r[a]}),s}const zht={};async function Bht(s){let t=zht[s];if(t!=null)return t;const r=await(await fetch(s)).text();return t={url:s,cssText:r},zht[s]=t,t}async function $ht(s,t){let n=s.cssText;const r=/url\(["']?([^"')]+)["']?\)/g,i=(n.match(/url\([^)]+\)/g)||[]).map(async l=>{let o=l.replace(r,"$1");return o.startsWith("https://")||(o=new URL(o,s.url).href),HLt(o,t.fetchRequestInit,({result:c})=>(n=n.replace(l,`url(${c})`),[l,c]))});return Promise.all(i).then(()=>n)}function Uht(s){if(s==null)return[];const t=[],n=/(\/\*[\s\S]*?\*\/)/gi;let r=s.replace(n,"");const a=new RegExp("((@.*?keyframes [\\s\\S]*?){([\\s\\S]*?}\\s*?)})","gi");for(;;){const c=a.exec(r);if(c===null)break;t.push(c[0])}r=r.replace(a,"");const i=/@import[\s\S]*?url\([^)]*\)[\s\S]*?;/gi,l="((\\s*?(?:\\/\\*[\\s\\S]*?\\*\\/)?\\s*?@media[\\s\\S]*?){([\\s\\S]*?)}\\s*?})|(([\\s\\S]*?){([\\s\\S]*?)})",o=new RegExp(l,"gi");for(;;){let c=i.exec(r);if(c===null){if(c=o.exec(r),c===null)break;i.lastIndex=o.lastIndex}else o.lastIndex=i.lastIndex;t.push(c[0])}return t}async function eqs(s,t){const n=[],r=[];return s.forEach(a=>{if("cssRules"in a)try{fM(a.cssRules||[]).forEach((i,l)=>{if(i.type===CSSRule.IMPORT_RULE){let o=l+1;const c=i.href,d=Bht(c).then(u=>$ht(u,t)).then(u=>Uht(u).forEach(h=>{try{a.insertRule(h,h.startsWith("@import")?o+=1:a.cssRules.length)}catch(m){console.error("Error inserting rule from remote css",{rule:h,error:m})}})).catch(u=>{console.error("Error loading remote css",u.toString())});r.push(d)}})}catch(i){const l=s.find(o=>o.href==null)||document.styleSheets[0];a.href!=null&&r.push(Bht(a.href).then(o=>$ht(o,t)).then(o=>Uht(o).forEach(c=>{l.insertRule(c,l.cssRules.length)})).catch(o=>{console.error("Error loading remote stylesheet",o)})),console.error("Error inlining remote css file",i)}}),Promise.all(r).then(()=>(s.forEach(a=>{if("cssRules"in a)try{fM(a.cssRules||[]).forEach(i=>{n.push(i)})}catch(i){console.error(`Error while reading CSS rules from ${a.href}`,i)}}),n))}function tqs(s){return s.filter(t=>t.type===CSSRule.FONT_FACE_RULE).filter(t=>KLt(t.style.getPropertyValue("src")))}async function sqs(s,t){if(s.ownerDocument==null)throw new Error("Provided element is not within a Document");const n=fM(s.ownerDocument.styleSheets),r=await eqs(n,t);return tqs(r)}function XLt(s){return s.trim().replace(/["']/g,"")}function nqs(s){const t=new Set;function n(r){(r.style.fontFamily||getComputedStyle(r).fontFamily).split(",").forEach(i=>{t.add(XLt(i))}),Array.from(r.children).forEach(i=>{i instanceof HTMLElement&&n(i)})}return n(s),t}async function rqs(s,t){const n=await sqs(s,t),r=nqs(s);return(await Promise.all(n.filter(i=>r.has(XLt(i.style.fontFamily))).map(i=>{const l=i.parentStyleSheet?i.parentStyleSheet.href:null;return YLt(i.cssText,l,t)}))).join(` `)}async function aqs(s,t){const n=t.fontEmbedCSS!=null?t.fontEmbedCSS:t.skipFonts?null:await rqs(s,t);if(n){const r=document.createElement("style"),a=document.createTextNode(n);r.appendChild(a),s.firstChild?s.insertBefore(r,s.firstChild):s.appendChild(r)}}async function QLt(s,t={}){const{width:n,height:r}=VLt(s,t),a=await VAe(s,t,!0);return await aqs(a,t),await ZLt(a,t),JUs(a,t),await jUs(a,n,r)}async function JLt(s,t={}){const{width:n,height:r}=VLt(s,t),a=await QLt(s,t),i=await x5e(a),l=document.createElement("canvas"),o=l.getContext("2d"),c=t.pixelRatio||bUs(),d=t.canvasWidth||n,u=t.canvasHeight||r;return l.width=d*c,l.height=u*c,t.skipAutoScale||_Us(l),l.style.width=`${d}`,l.style.height=`${u}`,t.backgroundColor&&(o.fillStyle=t.backgroundColor,o.fillRect(0,0,l.width,l.height)),o.drawImage(i,0,0,l.width,l.height),l}async function PU(s,t={}){return(await JLt(s,t)).toDataURL()}const eRt=Object.freeze(Object.defineProperty({__proto__:null,toCanvas:JLt,toPng:PU,toSvg:QLt},Symbol.toStringTag,{value:"Module"})),IU=s=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s),HAe={"just-listed":"JUST LISTED","just-sold":"JUST SOLD","open-house":"OPEN HOUSE","price-drop":"PRICE DROP"},NT={"instagram-square":{width:1080,height:1080},"instagram-story":{width:1080,height:1920},"facebook-post":{width:1200,height:630}},iqs=({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})]})]}),GKe=zt.forwardRef(({listing:s,postType:t,format:n,branding:r,selectedPhotoIndex:a},i)=>{var h;const l=n==="instagram-story"?{w:1080,h:1920}:n==="facebook-post"?{w:1200,h:630}:{w:1080,h:1080},o=400/l.w,c=(h=s.photos)==null?void 0:h[a],d=HAe[t],u=[s.bedrooms?`${s.bedrooms} Bed`:null,s.bathrooms?`${s.bathrooms} Bath`:null,s.sqft?`${s.sqft.toLocaleString()} Sq Ft`:null].filter(Boolean).join(" • ");return e.jsxs("div",{ref:i,style:{width:l.w,height:l.h,transform:`scale(${o})`,transformOrigin:"top left",position:"relative",overflow:"hidden",fontFamily:"'Georgia', 'Times New Roman', serif",color:"#FFFFFF"},children:[c&&e.jsx("img",{src:c,alt:"",crossOrigin:"anonymous",style:{position:"absolute",inset:0,width:"100%",height:"100%",objectFit:"cover"}}),e.jsx("div",{style:{position:"absolute",inset:0,background:"linear-gradient(180deg, rgba(10,10,30,0.3) 0%, rgba(10,10,30,0.85) 100%)"}}),e.jsxs("div",{style:{position:"relative",height:"100%",display:"flex",flexDirection:"column",justifyContent:"space-between",padding:l.w*.06},children:[e.jsx("div",{children:e.jsx("div",{style:{display:"inline-block",background:"linear-gradient(135deg, #C9A84C, #E8D48B)",color:"#1A1A2E",padding:`${l.w*.012}px ${l.w*.035}px`,fontSize:l.w*.032,fontWeight:700,letterSpacing:"0.25em",textTransform:"uppercase"},children:d})}),e.jsxs("div",{children:[e.jsx("div",{style:{fontSize:l.w*.07,fontWeight:700,lineHeight:1.1,marginBottom:l.w*.015,textShadow:"0 2px 12px rgba(0,0,0,0.5)"},children:IU(s.price)}),t==="just-sold"&&s.soldPrice&&e.jsxs("div",{style:{fontSize:l.w*.028,color:"#C9A84C",marginBottom:l.w*.01},children:["Sold for ",IU(s.soldPrice)]}),e.jsx("div",{style:{fontSize:l.w*.028,opacity:.9,marginBottom:l.w*.008},children:s.address}),e.jsxs("div",{style:{fontSize:l.w*.022,opacity:.7,marginBottom:l.w*.02},children:[s.city,", ",s.state," ",s.zip]}),e.jsx("div",{style:{display:"flex",gap:l.w*.015,fontSize:l.w*.022,letterSpacing:"0.05em",borderTop:"1px solid rgba(201,168,76,0.4)",paddingTop:l.w*.02},children:e.jsx("span",{children:u})}),t==="open-house"&&e.jsx("div",{style:{marginTop:l.w*.02,background:"rgba(201,168,76,0.15)",border:"1px solid rgba(201,168,76,0.4)",padding:`${l.w*.01}px ${l.w*.02}px`,fontSize:l.w*.024,letterSpacing:"0.1em",display:"inline-block"},children:"SAT & SUN • 1–4 PM"}),e.jsx(iqs,{branding:r,dim:l})]})]})]})});GKe.displayName="LuxuryDarkTemplate";const oqs=({branding:s,dim:t,accentColor:n})=>!(s!=null&&s.enabled)||!s.agentName?null:e.jsxs("div",{style:{borderTop:"2px solid #E5E7EB",paddingTop:t.w*.025,display:"flex",alignItems:"center",justifyContent:"center",gap:t.w*.025},children:[s.agentPhotoUrl&&e.jsx("img",{src:s.agentPhotoUrl,alt:"",crossOrigin:"anonymous",style:{width:t.w*.14,height:t.w*.14,borderRadius:"50%",objectFit:"cover",border:`3px solid ${n}`,flexShrink:0}}),e.jsxs("div",{children:[e.jsx("div",{style:{fontSize:t.w*.042,fontWeight:800,color:"#1A1A1A"},children:s.agentName}),s.brokerage&&e.jsx("div",{style:{fontSize:t.w*.028,color:"#6B7280",marginTop:t.w*.005},children:s.brokerage})]})]}),WKe=zt.forwardRef(({listing:s,postType:t,format:n,branding:r,selectedPhotoIndex:a},i)=>{var p;const l=n==="instagram-story"?{w:1080,h:1920}:n==="facebook-post"?{w:1200,h:630}:{w:1080,h:1080},o=400/l.w,c=(p=s.photos)==null?void 0:p[a],d=HAe[t],u=n==="instagram-story",h=n==="facebook-post",m=t==="just-sold"?"#7C3AED":t==="open-house"?"#2563EB":t==="price-drop"?"#DC2626":"#059669";return e.jsxs("div",{ref:i,style:{width:l.w,height:l.h,transform:`scale(${o})`,transformOrigin:"top left",position:"relative",overflow:"hidden",fontFamily:"'Helvetica Neue', Arial, sans-serif",color:"#1A1A1A",background:"#FFFFFF",display:"flex",flexDirection:h?"row":"column"},children:[e.jsxs("div",{style:{width:h?"55%":"100%",height:h?"100%":u?"50%":"52%",position:"relative",overflow:"hidden",flexShrink:0},children:[c&&e.jsx("img",{src:c,alt:"",crossOrigin:"anonymous",style:{width:"100%",height:"100%",objectFit:"cover"}}),e.jsx("div",{style:{position:"absolute",top:l.w*.04,left:0,background:m,color:"#FFFFFF",padding:`${l.w*.012}px ${l.w*.04}px`,fontSize:l.w*.026,fontWeight:800,letterSpacing:"0.15em"},children:d})]}),e.jsxs("div",{style:{flex:1,display:"flex",flexDirection:"column",justifyContent:"center",padding:l.w*.05},children:[e.jsx("div",{style:{fontSize:l.w*(h?.055:.065),fontWeight:800,lineHeight:1.1,color:m,marginBottom:l.w*.012},children:IU(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:`${m}10`,border:`2px solid ${m}`,borderRadius:l.w*.01,padding:`${l.w*.01}px ${l.w*.02}px`,fontSize:l.w*.022,fontWeight:700,color:m,display:"inline-block",marginBottom:l.w*.015},children:"SAT & SUN • 1–4 PM"}),e.jsx(oqs,{branding:r,dim:l,accentColor:m})]})]})});WKe.displayName="ModernCleanTemplate";const lqs=({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})]})]}),KKe=zt.forwardRef(({listing:s,postType:t,format:n,branding:r,selectedPhotoIndex:a},i)=>{var m;const l=n==="instagram-story"?{w:1080,h:1920}:n==="facebook-post"?{w:1200,h:630}:{w:1080,h:1080},o=400/l.w,c=(m=s.photos)==null?void 0:m[a],d=HAe[t],u={"just-listed":"linear-gradient(135deg, #059669, #10B981)","just-sold":"linear-gradient(135deg, #7C3AED, #A855F7)","open-house":"linear-gradient(135deg, #2563EB, #3B82F6)","price-drop":"linear-gradient(135deg, #DC2626, #F43F5E)"},h=[s.bedrooms?`${s.bedrooms} BD`:null,s.bathrooms?`${s.bathrooms} BA`:null,s.sqft?`${s.sqft.toLocaleString()} SF`:null].filter(Boolean).join(" | ");return e.jsxs("div",{ref:i,style:{width:l.w,height:l.h,transform:`scale(${o})`,transformOrigin:"top left",position:"relative",overflow:"hidden",fontFamily:"'Arial Black', 'Helvetica Neue', sans-serif",color:"#FFFFFF"},children:[c&&e.jsx("img",{src:c,alt:"",crossOrigin:"anonymous",style:{position:"absolute",inset:0,width:"100%",height:"100%",objectFit:"cover"}}),e.jsx("div",{style:{position:"absolute",inset:0,background:"rgba(0,0,0,0.4)"}}),e.jsxs("div",{style:{position:"relative",height:"100%",display:"flex",flexDirection:"column",padding:l.w*.05},children:[e.jsx("div",{style:{background:u[t],padding:`${l.w*.025}px ${l.w*.04}px`,fontSize:l.w*.055,fontWeight:900,letterSpacing:"0.08em",alignSelf:"flex-start",borderRadius:l.w*.01,boxShadow:"0 8px 32px rgba(0,0,0,0.3)",transform:"rotate(-2deg)",marginBottom:l.w*.03},children:d}),e.jsx("div",{style:{flex:1}}),e.jsxs("div",{style:{background:"rgba(0,0,0,0.65)",backdropFilter:"blur(10px)",borderRadius:l.w*.015,padding:l.w*.04},children:[e.jsx("div",{style:{fontSize:l.w*.08,fontWeight:900,lineHeight:1,marginBottom:l.w*.01},children:IU(s.price)}),e.jsx("div",{style:{fontSize:l.w*.028,fontWeight:700,marginBottom:l.w*.005},children:s.address}),e.jsxs("div",{style:{fontSize:l.w*.022,opacity:.8,marginBottom:l.w*.015},children:[s.city,", ",s.state," ",s.zip]}),e.jsx("div",{style:{display:"inline-block",background:"rgba(255,255,255,0.15)",borderRadius:l.w*.008,padding:`${l.w*.01}px ${l.w*.02}px`,fontSize:l.w*.022,fontWeight:700,letterSpacing:"0.08em"},children:h}),t==="open-house"&&e.jsx("div",{style:{marginTop:l.w*.015,background:u["open-house"],borderRadius:l.w*.008,padding:`${l.w*.012}px ${l.w*.025}px`,fontSize:l.w*.024,fontWeight:800,display:"inline-block",marginLeft:l.w*.01},children:"SAT & SUN 1–4 PM"}),e.jsx(lqs,{branding:r,dim:l})]})]})]})});KKe.displayName="BoldColorfulTemplate";const cqs=({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})]})]}),YKe=zt.forwardRef(({listing:s,postType:t,format:n,branding:r,selectedPhotoIndex:a},i)=>{var h;const l=n==="instagram-story"?{w:1080,h:1920}:n==="facebook-post"?{w:1200,h:630}:{w:1080,h:1080},o=400/l.w,c=(h=s.photos)==null?void 0:h[a],d=HAe[t],u=n==="instagram-story";return e.jsx("div",{ref:i,style:{width:l.w,height:l.h,transform:`scale(${o})`,transformOrigin:"top left",position:"relative",overflow:"hidden",fontFamily:"'Georgia', 'Times New Roman', serif",color:"#1A1A1A",background:"#F5F0EB"},children:e.jsxs("div",{style:{display:"flex",flexDirection:u?"column":"row",height:"100%"},children:[e.jsxs("div",{style:{width:u?"100%":"42%",height:u?"40%":"100%",display:"flex",flexDirection:"column",justifyContent:"center",padding:l.w*.05,order:u?2:1},children:[e.jsx("div",{style:{fontSize:l.w*.016,letterSpacing:"0.3em",textTransform:"uppercase",color:"#8B7355",borderBottom:"2px solid #8B7355",paddingBottom:l.w*.01,marginBottom:l.w*.025,display:"inline-block",alignSelf:"flex-start"},children:d}),e.jsx("div",{style:{fontSize:l.w*(u?.06:.055),fontWeight:700,lineHeight:1.1,marginBottom:l.w*.015,fontStyle:"italic"},children:IU(s.price)}),t==="just-sold"&&s.soldPrice&&e.jsxs("div",{style:{fontSize:l.w*.02,color:"#8B7355",marginBottom:l.w*.01},children:["Sold: ",IU(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(cqs,{branding:r,dim:l})]}),e.jsxs("div",{style:{width:u?"100%":"58%",height:u?"60%":"100%",position:"relative",overflow:"hidden",order:u?1:2},children:[c&&e.jsx("img",{src:c,alt:"",crossOrigin:"anonymous",style:{width:"100%",height:"100%",objectFit:"cover"}}),e.jsx("div",{style:{position:"absolute",inset:l.w*.02,border:"1px solid rgba(255,255,255,0.4)",pointerEvents:"none"}})]})]})})});YKe.displayName="EditorialTemplate";const dqs=[{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:"📉"}],qht=[{value:"instagram-square",label:"IG Post",dimensions:"1080×1080",icon:e.jsx(Sf,{className:"h-4 w-4"})},{value:"instagram-story",label:"IG Story",dimensions:"1080×1920",icon:e.jsx(Sf,{className:"h-4 w-4"})},{value:"facebook-post",label:"Facebook",dimensions:"1200×630",icon:e.jsx(ax,{className:"h-4 w-4"})}],uqs=[{value:"luxury-dark",label:"Luxury Dark",description:"Black & gold, high-end",preview:"🌙"},{value:"modern-clean",label:"Modern Clean",description:"White, bold, contemporary",preview:"✨"},{value:"bold-colorful",label:"Bold & Vibrant",description:"Energetic gradients",preview:"🔥"},{value:"editorial",label:"Editorial",description:"Magazine-style",preview:"📰"}],Vht={"luxury-dark":GKe,"modern-clean":WKe,"bold-colorful":KKe,editorial:YKe},ZLe=s=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s);function hqs(s){var l;const[t,n]=s.split(","),r=((l=t.match(/:(.*?);/))==null?void 0:l[1])||"image/png",a=atob(n),i=new Uint8Array(a.length);for(let o=0;oTe.is_default))??(s==null?void 0:s[0])??null,[n,r]=k.useState(void 0),a=(s==null?void 0:s.find(Te=>Te.id===n))??t,i=ai(),[l,o]=k.useState("mine"),[c,d]=k.useState(""),[u,h]=k.useState("address"),[m,p]=k.useState(!1),[g,x]=k.useState([]),[y,v]=k.useState(null),[_,j]=k.useState(0),[C,A]=k.useState("just-listed"),[M,I]=k.useState(["instagram-square"]),[P,R]=k.useState("luxury-dark"),[O,B]=k.useState(!0),[U,G]=k.useState(!1),[H,Y]=k.useState([]),[se,ee]=k.useState("search"),oe=k.useRef({}),{data:me=[],isLoading:Q}=pt({queryKey:["marketing-studio-my-listings",i],enabled:!!i,queryFn:async()=>{const{data:Te,error:Ie}=await V.from("listings").select("id, property_address, city, state, price, status, bedrooms, bathrooms, square_footage, year_built, property_type, description, created_at, listing_photos(photo_url, sort_order, is_primary)").eq("agent_id",i).order("created_at",{ascending:!1}).limit(60);if(Ie)throw Ie;return(Te||[]).map(Ue=>{const Be=(Ue.listing_photos||[]).slice().sort((Ye,Ee)=>(Ee.is_primary?1:0)-(Ye.is_primary?1:0)||(Ye.sort_order??0)-(Ee.sort_order??0)).map(Ye=>Ye.photo_url).filter(Boolean),je=String(Ue.status||"");return{mlsNumber:Ue.id,address:Ue.property_address||"",city:Ue.city||"",state:Ue.state||"",zip:"",price:Number(Ue.price||0),status:je,bedrooms:Number(Ue.bedrooms||0),bathrooms:Number(Ue.bathrooms||0),sqft:Number(Ue.square_footage||0),lotSize:"",yearBuilt:Ue.year_built??null,propertyType:Ue.property_type||"",description:Ue.description||"",photos:Be,listDate:Ue.created_at,soldDate:je.toLowerCase().includes("sold")?Ue.created_at:null,soldPrice:null,agent:{name:"",office:""}}})}}),te=k.useMemo(()=>!O||!a?{enabled:!1}:{enabled:!0,agentName:a.display_name||"",brokerage:a.tagline||"",agentPhotoUrl:a.headshot_url||void 0},[O,a]),le=async()=>{if(c.trim()){p(!0),x([]);try{const{data:Te,error:Ie}=await V.functions.invoke("repliers-mls-search",{body:{searchType:u,query:c.trim()}});if(Ie)throw Ie;if(Te!=null&&Te.error)throw new Error(Te.error);x((Te==null?void 0:Te.listings)||[]),((Te==null?void 0:Te.listings)||[]).length===0&&ae.info("No listings found. Try a different search.")}catch(Te){ae.error(Te.message||"Search failed")}finally{p(!1)}}},fe=Te=>{var Ie;v(Te),j(0),ee("customize"),Te.soldDate||(Ie=Te.status)!=null&&Ie.toLowerCase().includes("sold")?A("just-sold"):A("just-listed")},_e=Te=>I(Ie=>Ie.includes(Te)?Ie.filter(Ue=>Ue!==Te):[...Ie,Te]),ve=y?{listing:y,postType:C,format:"instagram-square",branding:te,selectedPhotoIndex:_}:null,he=k.useCallback(async()=>{if(!(!y||M.length===0)){G(!0),Y([]),ee("generate");try{await new Promise(Ie=>setTimeout(Ie,600));const Te=[];for(const Ie of M){const Ue=`${P}-${Ie}`,Be=oe.current[Ue];if(!Be)continue;const je=NT[Ie],Ye=await PU(Be,{width:je.width,height:je.height,pixelRatio:1,cacheBust:!0,style:{transform:"none",transformOrigin:"top left"}});Te.push({format:Ie,url:Ye})}Y(Te),ae.success(`Generated ${Te.length} design${Te.length>1?"s":""}!`)}catch(Te){ae.error(Te.message||"Generation failed")}finally{G(!1)}}},[y,M,P]),Se=(Te,Ie)=>{const Ue=`${((y==null?void 0:y.address)||"listing").replace(/\s+/g,"-")}-${C}-${Ie}.png`;try{const Be=hqs(Te),je=URL.createObjectURL(Be);if(mqs)window.open(je,"_blank"),ae.message("Long-press the image to save to Photos");else{const Ye=document.createElement("a");Ye.href=je,Ye.download=Ue,document.body.appendChild(Ye),Ye.click(),document.body.removeChild(Ye)}setTimeout(()=>URL.revokeObjectURL(je),6e4)}catch{const Be=document.createElement("a");Be.href=Te,Be.download=Ue,Be.click()}};return k.useEffect(()=>{!n&&t&&r(t.id)},[t,n]),e.jsx(Xs,{title:"Listing Templates",children:e.jsxs("div",{className:"container max-w-6xl py-4 md:py-8 px-3 md:px-6 space-y-5",children:[e.jsxs(Sc,{children:[e.jsx("title",{children:"Listing Templates | Marketing Studio"}),e.jsx("meta",{name:"description",content:"Just Listed, Just Sold, Open House and Price Drop templates pulled directly from your MLS."})]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsx($,{variant:"ghost",size:"sm",asChild:!0,children:e.jsxs(nr,{to:"/marketing-studio",children:[e.jsx(Ia,{className:"h-4 w-4 mr-1"})," Marketing Studio"]})})}),e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-end sm:justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs(qe,{variant:"secondary",className:"mb-2 gap-1",children:[e.jsx(kn,{className:"h-3 w-3"})," Listing Templates"]}),e.jsx("h1",{className:"text-2xl md:text-3xl font-bold tracking-tight",children:"Just Listed. Just Stunning."}),e.jsx("p",{className:"text-sm md:text-base text-muted-foreground max-w-2xl mt-1",children:"Search any MLS listing and get pixel-perfect, on-brand graphics for Instagram, Stories and Facebook in one click."})]}),s&&s.length>0&&e.jsxs("div",{className:"min-w-0 sm:min-w-[220px]",children:[e.jsx(re,{className:"text-xs text-muted-foreground",children:"Brand preset"}),e.jsxs(bs,{value:n,onValueChange:r,children:[e.jsx(ys,{children:e.jsx(_s,{placeholder:"Default"})}),e.jsx(vs,{children:s.map(Te=>e.jsxs(We,{value:Te.id,children:[Te.name,Te.is_default?" (default)":""]},Te.id))})]})]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 text-xs sm:text-sm overflow-x-auto -mx-1 px-1 pb-1",children:[e.jsxs("button",{onClick:()=>ee("search"),className:`flex items-center gap-1.5 px-3 py-1.5 rounded-full whitespace-nowrap ${se==="search"?"bg-primary text-primary-foreground":"bg-muted text-muted-foreground"}`,children:[e.jsx(Yr,{className:"h-3.5 w-3.5"})," 1. Find listing"]}),e.jsx(fi,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsxs("button",{onClick:()=>y&&ee("customize"),disabled:!y,className:`flex items-center gap-1.5 px-3 py-1.5 rounded-full whitespace-nowrap ${se==="customize"?"bg-primary text-primary-foreground":y?"bg-muted text-muted-foreground":"bg-muted text-muted-foreground/50"}`,children:[e.jsx(kn,{className:"h-3.5 w-3.5"})," 2. Customize"]}),e.jsx(fi,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsxs("div",{className:`flex items-center gap-1.5 px-3 py-1.5 rounded-full whitespace-nowrap ${se==="generate"?"bg-primary text-primary-foreground":"bg-muted text-muted-foreground/50"}`,children:[e.jsx(ji,{className:"h-3.5 w-3.5"})," 3. Download"]})]}),se==="search"&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(ya,{value:l,onValueChange:Te=>o(Te),children:e.jsxs(va,{className:"grid grid-cols-2 w-full sm:w-auto",children:[e.jsxs(is,{value:"mine",children:[e.jsx(ua,{className:"h-4 w-4 mr-1.5"})," My Listings"]}),e.jsxs(is,{value:"mls",children:[e.jsx(Yr,{className:"h-4 w-4 mr-1.5"})," MLS Search"]})]})}),l==="mine"&&e.jsx("div",{className:"space-y-3",children:Q?e.jsx(we,{children:e.jsx(De,{className:"py-12 flex items-center justify-center",children:e.jsx(Jt,{className:"h-6 w-6 animate-spin text-muted-foreground"})})}):me.length===0?e.jsx(we,{children:e.jsxs(De,{className:"py-10 text-center space-y-2",children:[e.jsx(ua,{className:"h-10 w-10 mx-auto text-muted-foreground/40"}),e.jsx("p",{className:"text-sm font-medium",children:"No listings yet"}),e.jsx("p",{className:"text-xs text-muted-foreground max-w-sm mx-auto",children:"Add a listing to your Listing Exchange first, and it'll show up here ready to brand."}),e.jsx($,{variant:"outline",size:"sm",asChild:!0,className:"mt-2",children:e.jsx(nr,{to:"/mission-control/listings",children:"Go to Listings"})})]})}):e.jsxs(e.Fragment,{children:[e.jsxs("h3",{className:"text-sm font-medium text-muted-foreground",children:[me.length," listing",me.length!==1?"s":""," from your Listing Exchange"]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:me.map((Te,Ie)=>{var Ue;return e.jsx(we,{className:"cursor-pointer hover:border-primary/50 hover:shadow-md transition-all group overflow-hidden",onClick:()=>fe(Te),children:e.jsx(De,{className:"p-0",children:e.jsxs("div",{className:"flex",children:[e.jsx("div",{className:"w-28 h-28 sm:w-32 sm:h-28 flex-shrink-0 bg-muted overflow-hidden",children:(Ue=Te.photos)!=null&&Ue[0]?e.jsx("img",{src:Te.photos[0],alt:Te.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(ua,{className:"h-8 w-8 text-muted-foreground/40"})})}),e.jsxs("div",{className:"flex-1 p-3 min-w-0",children:[e.jsx("p",{className:"font-bold",children:Te.price>0?ZLe(Te.price):"—"}),e.jsx("p",{className:"text-sm text-muted-foreground truncate",children:Te.address}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[Te.city,Te.state?`, ${Te.state}`:""]}),e.jsxs("div",{className:"flex items-center gap-3 mt-1.5 text-xs text-muted-foreground",children:[Te.bedrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(f3,{className:"h-3 w-3"})," ",Te.bedrooms]}),Te.bathrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(p0,{className:"h-3 w-3"})," ",Te.bathrooms]}),Te.sqft>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(H8,{className:"h-3 w-3"})," ",Te.sqft.toLocaleString()]})]}),Te.status&&e.jsx("div",{className:"flex items-center gap-2 mt-1 flex-wrap",children:e.jsx(qe,{variant:"outline",className:"text-[10px]",children:Te.status})})]})]})})},Te.mlsNumber||Ie)})})]})}),l==="mls"&&e.jsxs(e.Fragment,{children:[e.jsxs(we,{className:"overflow-hidden",children:[e.jsxs(Vt,{children:[e.jsxs(Yt,{className:"flex items-center gap-2 text-base md:text-lg",children:[e.jsx(Yr,{className:"h-5 w-5 text-primary"})," Search MLS"]}),e.jsxs(vr,{children:["Search by address or MLS number. Requires an MLS data connection — if your account doesn't have one, use ",e.jsx("button",{type:"button",className:"underline",onClick:()=>o("mine"),children:"My Listings"})," instead."]})]}),e.jsxs(De,{className:"space-y-3",children:[e.jsx(ya,{value:u,onValueChange:Te=>h(Te),children:e.jsxs(va,{children:[e.jsxs(is,{value:"address",children:[e.jsx(Si,{className:"h-4 w-4 mr-1.5"})," Address"]}),e.jsxs(is,{value:"mls",children:[e.jsx(kg,{className:"h-4 w-4 mr-1.5"})," MLS #"]})]})}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-2",children:[e.jsx(be,{value:c,onChange:Te=>d(Te.target.value),placeholder:u==="mls"?"Enter MLS number...":"Enter property address...",className:"flex-1",onKeyDown:Te=>Te.key==="Enter"&&le()}),e.jsxs($,{onClick:le,disabled:m||!c.trim(),className:"sm:w-auto w-full",children:[m?e.jsx(Jt,{className:"h-4 w-4 animate-spin mr-1.5"}):e.jsx(Yr,{className:"h-4 w-4 mr-1.5"})," Search"]})]})]})]}),g.length>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("h3",{className:"text-sm font-medium text-muted-foreground",children:[g.length," listing",g.length!==1?"s":""," found"]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:g.map((Te,Ie)=>{var Ue;return e.jsx(we,{className:"cursor-pointer hover:border-primary/50 hover:shadow-md transition-all group overflow-hidden",onClick:()=>fe(Te),children:e.jsx(De,{className:"p-0",children:e.jsxs("div",{className:"flex",children:[e.jsx("div",{className:"w-28 h-28 sm:w-32 sm:h-28 flex-shrink-0 bg-muted overflow-hidden",children:(Ue=Te.photos)!=null&&Ue[0]?e.jsx("img",{src:Te.photos[0],alt:Te.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(ua,{className:"h-8 w-8 text-muted-foreground/40"})})}),e.jsxs("div",{className:"flex-1 p-3 min-w-0",children:[e.jsx("p",{className:"font-bold",children:ZLe(Te.price)}),e.jsx("p",{className:"text-sm text-muted-foreground truncate",children:Te.address}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[Te.city,", ",Te.state," ",Te.zip]}),e.jsxs("div",{className:"flex items-center gap-3 mt-1.5 text-xs text-muted-foreground",children:[Te.bedrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(f3,{className:"h-3 w-3"})," ",Te.bedrooms]}),Te.bathrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(p0,{className:"h-3 w-3"})," ",Te.bathrooms]}),Te.sqft>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(H8,{className:"h-3 w-3"})," ",Te.sqft.toLocaleString()]})]}),e.jsxs("div",{className:"flex items-center gap-2 mt-1 flex-wrap",children:[Te.mlsNumber&&e.jsx(qe,{variant:"outline",className:"text-[10px]",children:Te.mlsNumber}),Te.status&&e.jsx(qe,{variant:"outline",className:"text-[10px]",children:Te.status})]})]})]})})},Te.mlsNumber||Ie)})})]})]})]}),se==="customize"&&y&&ve&&e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-4 md:gap-6",children:[e.jsxs(we,{className:"lg:col-span-1 overflow-hidden min-w-0",children:[e.jsx(Vt,{className:"pb-3",children:e.jsx(Yt,{className:"text-base",children:"Selected listing"})}),e.jsxs(De,{className:"space-y-3",children:[y.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:y.photos[_],alt:"",className:"w-full h-full object-cover"})}),y.photos.length>1&&e.jsxs("div",{className:"flex items-center justify-between mt-2",children:[e.jsx($,{variant:"outline",size:"icon",className:"h-7 w-7",onClick:()=>j(Te=>Math.max(0,Te-1)),disabled:_===0,children:e.jsx(Ld,{className:"h-4 w-4"})}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[_+1," of ",y.photos.length]}),e.jsx($,{variant:"outline",size:"icon",className:"h-7 w-7",onClick:()=>j(Te=>Math.min(y.photos.length-1,Te+1)),disabled:_===y.photos.length-1,children:e.jsx(fi,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-bold text-lg",children:ZLe(y.price)}),e.jsx("p",{className:"text-sm text-muted-foreground",children:y.address}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[y.city,", ",y.state," ",y.zip]})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-2 text-center",children:[y.bedrooms>0&&e.jsxs("div",{className:"bg-muted/50 rounded-lg p-2",children:[e.jsx("p",{className:"text-sm font-semibold",children:y.bedrooms}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Beds"})]}),y.bathrooms>0&&e.jsxs("div",{className:"bg-muted/50 rounded-lg p-2",children:[e.jsx("p",{className:"text-sm font-semibold",children:y.bathrooms}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Baths"})]}),y.sqft>0&&e.jsxs("div",{className:"bg-muted/50 rounded-lg p-2",children:[e.jsx("p",{className:"text-sm font-semibold",children:y.sqft.toLocaleString()}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Sq Ft"})]})]}),e.jsxs($,{variant:"outline",size:"sm",className:"w-full",onClick:()=>{ee("search"),v(null)},children:[e.jsx(jm,{className:"h-3.5 w-3.5 mr-1.5"})," Choose different listing"]})]})]}),e.jsxs(we,{className:"lg:col-span-2 overflow-hidden min-w-0",children:[e.jsxs(Vt,{children:[e.jsxs(Yt,{className:"flex items-center gap-2 text-base",children:[e.jsx(kn,{className:"h-5 w-5 text-primary"})," Customize"]}),e.jsx(vr,{children:"Pick a template, post type, and output format."})]}),e.jsxs(De,{className:"space-y-5",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(re,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(gd,{className:"h-4 w-4"})," Template style"]}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-2",children:uqs.map(Te=>e.jsxs("button",{onClick:()=>R(Te.value),className:`flex flex-col items-center gap-1 px-2 py-3 rounded-lg border-2 transition-all text-center ${P===Te.value?"border-primary bg-primary/5":"border-border hover:border-primary/30"}`,children:[e.jsx("span",{className:"text-2xl",children:Te.preview}),e.jsx("span",{className:"text-sm font-medium",children:Te.label}),e.jsx("span",{className:"text-[10px] text-muted-foreground leading-tight",children:Te.description})]},Te.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-sm font-medium",children:"Post type"}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-2",children:dqs.map(Te=>e.jsxs("button",{onClick:()=>A(Te.value),className:`flex items-center justify-center gap-2 px-3 py-2.5 rounded-lg border-2 transition-all text-sm font-medium ${C===Te.value?"border-primary bg-primary/5":"border-border hover:border-primary/30"}`,children:[e.jsx("span",{className:"text-lg",children:Te.icon})," ",e.jsx("span",{className:"truncate",children:Te.label})]},Te.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-sm font-medium",children:"Output formats"}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-2",children:qht.map(Te=>e.jsxs("button",{onClick:()=>_e(Te.value),className:`flex items-center gap-2 px-3 py-2.5 rounded-lg border-2 transition-all text-sm ${M.includes(Te.value)?"border-primary bg-primary/5":"border-border hover:border-primary/30"}`,children:[Te.icon,e.jsxs("div",{className:"text-left min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:Te.label}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:Te.dimensions})]})]},Te.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(re,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(el,{className:"h-4 w-4"})," Show my branding"]}),e.jsx(On,{checked:O,onCheckedChange:B})]}),O&&!a&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["No brand preset yet. ",e.jsx(nr,{to:"/marketing-studio/brand-kit",className:"underline",children:"Create one"})," to add your headshot and name."]}),O&&a&&e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg border bg-muted/30",children:[a.headshot_url&&e.jsx("img",{src:a.headshot_url,alt:"",className:"w-10 h-10 rounded-full object-cover border"}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:a.display_name||"Unnamed agent"}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:a.tagline||a.email||""})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-sm font-medium",children:"Preview"}),e.jsx("div",{className:"bg-muted/30 rounded-lg p-3 md:p-4 flex justify-center overflow-hidden",children:e.jsx("div",{style:{width:360,maxWidth:"100%",height:360*(NT[M[0]||"instagram-square"].height/NT[M[0]||"instagram-square"].width)},children:(()=>{const Te=Vht[P],Ie=M[0]||"instagram-square";return e.jsx(Te,{...ve,format:Ie})})()})})]}),e.jsx($,{onClick:he,disabled:M.length===0||U,size:"lg",className:"w-full gap-2",children:U?e.jsxs(e.Fragment,{children:[e.jsx(Jt,{className:"h-5 w-5 animate-spin"})," Generating..."]}):e.jsxs(e.Fragment,{children:[e.jsx(kn,{className:"h-5 w-5"})," Generate ",M.length," design",M.length>1?"s":""]})})]})]})]}),se==="generate"&&e.jsxs("div",{className:"space-y-4",children:[U&&e.jsx(we,{children:e.jsxs(De,{className:"flex flex-col items-center justify-center py-16",children:[e.jsx(Jt,{className:"h-12 w-12 animate-spin text-primary mb-3"}),e.jsx("p",{className:"text-base font-medium",children:"Rendering your designs..."}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"High-resolution PNGs, no AI credits used."})]})}),H.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-2",children:[e.jsx("h3",{className:"text-lg font-semibold",children:"Your designs"}),e.jsxs($,{variant:"outline",size:"sm",onClick:()=>ee("customize"),children:[e.jsx(jm,{className:"h-3.5 w-3.5 mr-1.5"})," Tweak & regenerate"]})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:H.map((Te,Ie)=>{const Ue=qht.find(Be=>Be.value===Te.format);return e.jsxs(we,{className:"overflow-hidden",children:[e.jsx("div",{className:"bg-muted/30 p-1",children:e.jsx("img",{src:Te.url,alt:"",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:[Ue==null?void 0:Ue.icon,e.jsx("span",{className:"text-sm font-medium",children:Ue==null?void 0:Ue.label})]}),e.jsx(qe,{variant:"outline",className:"text-[10px]",children:Ue==null?void 0:Ue.dimensions})]}),e.jsxs($,{size:"sm",className:"w-full gap-1.5",onClick:()=>Se(Te.url,Te.format),children:[e.jsx(ji,{className:"h-3.5 w-3.5"})," Download"]})]})]},Ie)})})]})]}),se==="generate"&&y&&ve&&e.jsx("div",{style:{position:"fixed",left:"-99999px",top:0,pointerEvents:"none"},"aria-hidden":!0,children:M.map(Te=>{const Ie=Vht[P],Ue=NT[Te];return e.jsx("div",{style:{width:Ue.width,height:Ue.height},children:e.jsx(Ie,{ref:Be=>{oe.current[`${P}-${Te}`]=Be},...ve,format:Te})},`${P}-${Te}`)})})]})})}var pqs=Object.defineProperty,gqs=(s,t)=>pqs(s,"name",{value:t,configurable:!0}),xqs="Toggle",tRt=k.forwardRef(gqs(function(t,n){const{pressed:r,defaultPressed:a,onPressedChange:i,...l}=t,[o,c]=ox({prop:r,onChange:i,defaultProp:a??!1,caller:xqs});return e.jsx(hi.button,{type:"button","aria-pressed":o,"data-state":o?"on":"off","data-disabled":t.disabled?"":void 0,...l,ref:n,onClick:ga(t.onClick,()=>{t.disabled||c(!o)})})},"Toggle")),sRt=tRt,yqs=Object.defineProperty,TM=(s,t)=>yqs(s,"name",{value:t,configurable:!0}),rV="ToggleGroup",[nRt,uJn]=qm(rV,[YM]),rRt=YM(),aRt=k.forwardRef(TM(function(t,n){const{type:r,...a}=t;if(r==="single"){const i=a;return e.jsx(vqs,{role:"radiogroup",...i,ref:n})}if(r==="multiple"){const i=a;return e.jsx(bqs,{role:"toolbar",...i,ref:n})}throw new Error(`Missing prop \`type\` expected on \`${rV}\``)},"ToggleGroup")),[iRt,oRt]=nRt(rV),vqs=k.forwardRef(TM(function(t,n){const{value:r,defaultValue:a,onValueChange:i=TM(()=>{},"onValueChange"),...l}=t,[o,c]=ox({prop:r,defaultProp:a??"",onChange:i,caller:rV});return e.jsx(iRt,{scope:t.__scopeToggleGroup,type:"single",value:k.useMemo(()=>o?[o]:[],[o]),onItemActivate:c,onItemDeactivate:k.useCallback(()=>c(""),[c]),children:e.jsx(lRt,{...l,ref:n})})},"ToggleGroupImplSingle")),bqs=k.forwardRef(TM(function(t,n){const{value:r,defaultValue:a,onValueChange:i=TM(()=>{},"onValueChange"),...l}=t,[o,c]=ox({prop:r,defaultProp:a??[],onChange:i,caller:rV}),d=k.useCallback(h=>c((m=[])=>[...m,h]),[c]),u=k.useCallback(h=>c((m=[])=>m.filter(p=>p!==h)),[c]);return e.jsx(iRt,{scope:t.__scopeToggleGroup,type:"multiple",value:o,onItemActivate:d,onItemDeactivate:u,children:e.jsx(lRt,{...l,ref:n})})},"ToggleGroupImplMultiple")),[_qs,wqs]=nRt(rV),lRt=k.forwardRef(TM(function(t,n){const{__scopeToggleGroup:r,disabled:a=!1,rovingFocus:i=!0,orientation:l,dir:o,loop:c=!0,...d}=t,u=rRt(r),h=e4(o),m={dir:h,...d};return e.jsx(_qs,{scope:r,rovingFocus:i,disabled:a,children:i?e.jsx(E3e,{asChild:!0,...u,orientation:l,dir:h,loop:c,children:e.jsx(hi.div,{...m,ref:n})}):e.jsx(hi.div,{...m,ref:n})})},"ToggleGroupImpl")),eze="ToggleGroupItem",cRt=k.forwardRef(TM(function(t,n){const r=oRt(eze,t.__scopeToggleGroup),a=wqs(eze,t.__scopeToggleGroup),i=rRt(t.__scopeToggleGroup),l=r.value.includes(t.value),o=a.disabled||t.disabled,c={...t,pressed:l,disabled:o},d=k.useRef(null);return a.rovingFocus?e.jsx(T3e,{asChild:!0,...i,focusable:!o,active:l,ref:d,children:e.jsx(Hht,{...c,ref:n})}):e.jsx(Hht,{...c,ref:n})},"ToggleGroupItem")),Hht=k.forwardRef(TM(function(t,n){const{__scopeToggleGroup:r,value:a,...i}=t,l=oRt(eze,r),o={role:"radio","aria-checked":t.pressed,"aria-pressed":void 0},c=l.type==="single"?o:void 0;return e.jsx(tRt,{...c,...i,ref:n,onPressedChange:d=>{d?l.onItemActivate(a):l.onItemDeactivate(a)}})},"ToggleGroupItemImpl"));const dRt=gF("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"}}),jqs=k.forwardRef(({className:s,variant:t,size:n,...r},a)=>e.jsx(sRt,{ref:a,className:Ot(dRt({variant:t,size:n,className:s})),...r}));jqs.displayName=sRt.displayName;const uRt=k.createContext({size:"default",variant:"default"}),AB=k.forwardRef(({className:s,variant:t,size:n,children:r,...a},i)=>e.jsx(aRt,{ref:i,className:Ot("flex items-center justify-center gap-1",s),...a,children:e.jsx(uRt.Provider,{value:{variant:t,size:n},children:r})}));AB.displayName=aRt.displayName;const oO=k.forwardRef(({className:s,children:t,variant:n,size:r,...a},i)=>{const l=k.useContext(uRt);return e.jsx(cRt,{ref:i,className:Ot(dRt({variant:l.variant||n,size:l.size||r}),s),...a,children:t})});oO.displayName=cRt.displayName;const Nqs=[{id:"meet",label:"Meet Your Agent",icon:el,description:"Polished intro card with your headshot, story, and contact."},{id:"testimonial",label:"Testimonial",icon:ik,description:"Turn a Zillow / Google review into a branded graphic."},{id:"milestone",label:"Milestone",icon:ql,description:"Celebrate homes sold, awards, anniversaries, achievements."},{id:"tip",label:"Pro Tip",icon:P5,description:"Drop a value-bomb tip — buyer/seller advice, market insight."},{id:"quote",label:"Quote / Mantra",icon:xm,description:"Personal philosophy, mantra, or rallying call."}],XLe={square:{w:1080,h:1080,label:"1:1 Feed"},portrait:{w:1080,h:1350,label:"4:5 Portrait"},story:{w:1080,h:1920,label:"9:16 Story"}},kqs=[{id:"editorial",label:"Editorial",description:"Magazine-style with serif accents."},{id:"bold",label:"Bold",description:"Big type, high contrast, gradient."},{id:"minimal",label:"Minimal",description:"Clean white space, hairline rules."},{id:"luxury",label:"Luxury",description:"Dark, gold accents, refined."}],Ght={meet:{headline:"Meet your agent",subline:"Helping families find home, one keys-in-hand moment at a time.",body:"15 years of negotiating wins, 200+ families moved, and a love for this city that runs deep.",attribution:"",badgeText:"REALTOR®"},testimonial:{headline:"What our clients say",subline:"",body:"She made the entire process feel effortless. From first showing to closing day, every detail was handled with care and expertise. We could not have asked for a better experience.",attribution:"The Bennett Family",rating:5,badgeText:"CLIENT REVIEW"},milestone:{headline:"100 homes sold",subline:"and counting…",body:"Thank you to every client, partner, and friend who trusted me with the biggest move of their life. Here is to the next 100.",attribution:"",badgeText:"MILESTONE"},tip:{headline:`Stop guessing. Start pricing.`,subline:"Pro tip · #03",body:"Homes priced within 3% of market value sell 2.4× faster than those priced higher. Pricing strategy is leverage — not a guess.",attribution:"",badgeText:"PRO TIP"},quote:{headline:`"Real estate is not about houses. It is about people."`,subline:"",body:"",attribution:"",badgeText:"PHILOSOPHY"}};function Sqs(){const{data:s}=M9s(),{data:t}=Bee(),[n,r]=k.useState(void 0),a=k.useMemo(()=>(t==null?void 0:t.find(g=>g.id===n))??s??null,[t,n,s]),[i,l]=k.useState({template:"meet",style:"editorial",aspect:"portrait",rating:5,...Ght.meet}),o=g=>l(x=>({...x,...g})),c=g=>l(x=>({...x,template:g,...Ght[g]})),d=k.useRef(null),[u,h]=k.useState(!1),m=async()=>{if(!d.current)return;h(!0);const g=d.current,x=g.style.transform;try{g.style.transform="none",await new Promise(_=>requestAnimationFrame(()=>_(null)));const y=await PU(g,{cacheBust:!0,pixelRatio:2,width:g.offsetWidth,height:g.offsetHeight,backgroundColor:"#ffffff"}),v=document.createElement("a");v.href=y,v.download=`personal-branding-${i.template}-${Date.now()}.png`,document.body.appendChild(v),v.click(),v.remove(),ae.success("Downloaded to your device")}catch(y){ae.error((y==null?void 0:y.message)||"Export failed")}finally{g.style.transform=x,h(!1)}},p=XLe[i.aspect];return e.jsx(Xs,{title:"Personal Branding",children:e.jsxs("div",{className:"container max-w-7xl py-6 md:py-8 space-y-6 px-4",children:[e.jsxs(Sc,{children:[e.jsx("title",{children:"Personal Branding | Marketing Studio"}),e.jsx("meta",{name:"description",content:"Editorial-grade personal branding graphics — meet your agent, testimonials, milestones, and pro tips."})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-end sm:justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs(nr,{to:"/marketing-studio",className:"text-sm text-muted-foreground inline-flex items-center gap-1 hover:underline",children:[e.jsx(Ia,{className:"h-3 w-3"})," Back to Marketing Studio"]}),e.jsx("div",{className:"flex items-center gap-2 mt-1",children:e.jsxs(qe,{variant:"secondary",className:"gap-1",children:[e.jsx(kn,{className:"h-3 w-3"})," New"]})}),e.jsx("h1",{className:"text-2xl md:text-3xl font-bold tracking-tight mt-1",children:"Personal Branding"}),e.jsx("p",{className:"text-sm md:text-base text-muted-foreground max-w-2xl",children:"Five editorial-grade templates, four distinct aesthetics. Pick one, drop in your story, export in seconds."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx($,{variant:"outline",asChild:!0,children:e.jsxs(nr,{to:"/marketing-studio/brand-kit",children:[e.jsx(gd,{className:"h-4 w-4 mr-1"})," Brand Kit"]})}),e.jsxs($,{onClick:m,disabled:u,children:[e.jsx(ji,{className:"h-4 w-4 mr-1"})," ",u?"Exporting…":"Download"]})]})]}),e.jsxs("div",{className:"grid lg:grid-cols-[380px_1fr] gap-6",children:[e.jsxs("div",{className:"space-y-5",children:[e.jsx(we,{children:e.jsxs(De,{className:"p-4 space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"Template"}),e.jsx("div",{className:"grid grid-cols-2 gap-2",children:Nqs.map(g=>{const x=g.icon,y=i.template===g.id;return e.jsxs("button",{onClick:()=>c(g.id),className:`text-left rounded-lg border p-3 transition-all ${y?"border-primary bg-primary/5 ring-2 ring-primary/30":"border-border hover:border-primary/50"}`,children:[e.jsx(x,{className:"h-4 w-4 mb-1"}),e.jsx("div",{className:"text-xs font-semibold",children:g.label})]},g.id)})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"Style"}),e.jsx(AB,{type:"single",value:i.style,onValueChange:g=>g&&o({style:g}),className:"grid grid-cols-2 gap-1",children:kqs.map(g=>e.jsx(oO,{value:g.id,className:"text-xs h-9",children:g.label},g.id))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"Format"}),e.jsx(AB,{type:"single",value:i.aspect,onValueChange:g=>g&&o({aspect:g}),className:"grid grid-cols-3 gap-1",children:Object.keys(XLe).map(g=>e.jsx(oO,{value:g,className:"text-xs h-9",children:XLe[g].label},g))})]}),t&&t.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"Brand preset"}),e.jsxs(bs,{value:n??(s==null?void 0:s.id)??"",onValueChange:r,children:[e.jsx(ys,{children:e.jsx(_s,{placeholder:"Choose preset"})}),e.jsx(vs,{children:t.map(g=>e.jsx(We,{value:g.id,children:g.name},g.id))})]})]})]})}),e.jsx(we,{children:e.jsxs(De,{className:"p-4 space-y-3",children:[e.jsx(re,{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"Content"}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{htmlFor:"headline",className:"text-xs",children:"Headline"}),e.jsx(Ls,{id:"headline",value:i.headline,onChange:g=>o({headline:g.target.value}),rows:2})]}),i.template!=="quote"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{htmlFor:"subline",className:"text-xs",children:"Subline"}),e.jsx(be,{id:"subline",value:i.subline,onChange:g=>o({subline:g.target.value})})]}),i.template!=="quote"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{htmlFor:"body",className:"text-xs",children:"Body"}),e.jsx(Ls,{id:"body",value:i.body,onChange:g=>o({body:g.target.value}),rows:4})]}),(i.template==="testimonial"||i.template==="quote")&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{htmlFor:"attribution",className:"text-xs",children:"Attribution"}),e.jsx(be,{id:"attribution",value:i.attribution,onChange:g=>o({attribution:g.target.value}),placeholder:"— Client name / Source"})]}),i.template==="testimonial"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{className:"text-xs",children:"Rating"}),e.jsx(AB,{type:"single",value:String(i.rating),onValueChange:g=>g&&o({rating:Number(g)}),className:"grid grid-cols-5 gap-1",children:[1,2,3,4,5].map(g=>e.jsxs(oO,{value:String(g),className:"text-xs h-9",children:[g,"★"]},g))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{htmlFor:"badge",className:"text-xs",children:"Eyebrow tag"}),e.jsx(be,{id:"badge",value:i.badgeText,onChange:g=>o({badgeText:g.target.value})})]})]})})]}),e.jsx(Cqs,{aspect:p,canvasRef:d,children:e.jsx(Aqs,{form:i,preset:a,width:p.w,height:p.h})})]})]})})}function Cqs({aspect:s,canvasRef:t,children:n}){const r=k.useRef(null),[a,i]=k.useState(.5);return k.useEffect(()=>{const l=r.current;if(!l)return;const o=()=>{const d=l.clientWidth-32;i(Math.min(1,d/s.w))};o();const c=new ResizeObserver(o);return c.observe(l),()=>c.disconnect()},[s.w]),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{ref:r,className:"rounded-xl bg-muted/40 p-4 md:p-6 flex justify-center overflow-hidden",children:e.jsx("div",{style:{width:s.w*a,height:s.h*a,position:"relative"},className:"shadow-2xl",children:e.jsx("div",{ref:t,style:{width:s.w,height:s.h,transform:`scale(${a})`,transformOrigin:"top left",position:"absolute",top:0,left:0},children:n})})}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-2 text-center",children:["Preview scaled. Export is ",s.w,"×",s.h,"px @ 2× retina."]})]})}function Aqs({form:s,preset:t,width:n,height:r}){const a=(t==null?void 0:t.brand_color)||"#0F172A",i=(t==null?void 0:t.accent_color)||"#D4AF37",l=t==null?void 0:t.headshot_url,o=t==null?void 0:t.brokerage_logo_url,c=(t==null?void 0:t.display_name)||"Your Name",d=(t==null?void 0:t.phone)||"",u=(t==null?void 0:t.email)||"",h=(t==null?void 0:t.tagline)||"",m=(t==null?void 0:t.website_url)||"",p={form:s,brandColor:a,accentColor:i,headshot:l,logo:o,name:c,phone:d,email:u,tagline:h,website:m,width:n,height:r};return s.style==="editorial"?e.jsx(Eqs,{...p}):s.style==="bold"?e.jsx(Tqs,{...p}):s.style==="luxury"?e.jsx(Pqs,{...p}):e.jsx(Mqs,{...p})}function hRt({name:s,phone:t,email:n,website:r,color:a}){const i=[t,n,r].filter(Boolean);return e.jsxs("div",{style:{color:a,fontFamily:"Inter, system-ui, sans-serif"},children:[e.jsx("div",{style:{fontSize:22,fontWeight:700,letterSpacing:"0.02em"},children:s}),e.jsx("div",{style:{fontSize:16,opacity:.85,marginTop:4},children:i.join(" · ")})]})}function GAe({rating:s,color:t}){return e.jsx("div",{style:{display:"flex",gap:4},children:Array.from({length:5}).map((n,r)=>e.jsx(ri,{size:28,fill:r1.5;return e.jsxs("div",{style:{width:h,height:m,background:"#FAF7F2",position:"relative",fontFamily:"Georgia, serif",color:"#1a1a1a",overflow:"hidden"},children:[e.jsxs("div",{style:{position:"absolute",top:64,left:64,right:64,display:"flex",justifyContent:"space-between",alignItems:"center"},children:[e.jsx("div",{style:{fontFamily:"Inter, sans-serif",fontSize:14,letterSpacing:"0.3em",color:n},children:t.badgeText}),e.jsxs("div",{style:{fontFamily:"Inter, sans-serif",fontSize:12,letterSpacing:"0.2em",color:"#888"},children:["EST. ",new Date().getFullYear()]})]}),e.jsx("div",{style:{position:"absolute",top:100,left:64,right:64,height:1,background:"#1a1a1a",opacity:.15}}),a&&(t.template==="meet"||t.template==="milestone")&&e.jsx("div",{style:{position:"absolute",top:140,left:64,width:h-128,height:p?700:480,overflow:"hidden",borderRadius:4},children:e.jsx("img",{src:a,crossOrigin:"anonymous",style:{width:"100%",height:"100%",objectFit:"cover",objectPosition:"center top",filter:"grayscale(0.15)"}})}),e.jsxs("div",{style:{position:"absolute",left:64,right:64,bottom:220,textAlign:t.template==="quote"?"center":"left"},children:[t.template==="testimonial"&&e.jsx("div",{style:{fontSize:120,lineHeight:.7,color:r,fontFamily:"Georgia, serif"},children:'"'}),e.jsx("h1",{style:{fontSize:t.template==="quote"?76:92,lineHeight:1.05,fontWeight:400,margin:0,letterSpacing:"-0.02em",whiteSpace:"pre-wrap"},children:t.headline}),t.subline&&e.jsx("div",{style:{fontFamily:"Inter, sans-serif",fontSize:22,marginTop:16,color:"#555",fontStyle:"italic"},children:t.subline}),t.body&&e.jsx("p",{style:{fontFamily:"Inter, sans-serif",fontSize:22,lineHeight:1.5,color:"#333",marginTop:28,maxWidth:820},children:t.body}),t.template==="testimonial"&&e.jsxs("div",{style:{marginTop:24,display:"flex",alignItems:"center",gap:16},children:[e.jsx(GAe,{rating:t.rating,color:r}),t.attribution&&e.jsxs("div",{style:{fontFamily:"Inter, sans-serif",fontSize:18,color:"#555"},children:["— ",t.attribution]})]}),t.template==="quote"&&t.attribution&&e.jsxs("div",{style:{fontFamily:"Inter, sans-serif",fontSize:18,marginTop:24,color:"#555",letterSpacing:"0.1em"},children:["— ",t.attribution]})]}),e.jsxs("div",{style:{position:"absolute",left:64,right:64,bottom:64},children:[e.jsx("div",{style:{height:1,background:"#1a1a1a",opacity:.15,marginBottom:24}}),e.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[e.jsx(hRt,{name:l,phone:o,email:c,website:d,color:"#1a1a1a"}),i&&e.jsx("img",{src:i,crossOrigin:"anonymous",style:{height:56,objectFit:"contain"}})]}),u&&e.jsx("div",{style:{fontFamily:"Inter, sans-serif",fontSize:13,color:"#888",marginTop:12,fontStyle:"italic"},children:u})]})]})}function Tqs(s){const{form:t,brandColor:n,accentColor:r,headshot:a,logo:i,name:l,phone:o,email:c,website:d,width:u,height:h}=s;return e.jsxs("div",{style:{width:u,height:h,position:"relative",overflow:"hidden",fontFamily:"Inter, system-ui, sans-serif",background:`linear-gradient(135deg, ${n} 0%, ${Iqs(n,-20)} 100%)`,color:"#fff"},children:[e.jsx("div",{style:{position:"absolute",top:-200,right:-200,width:700,height:700,borderRadius:"50%",background:r,opacity:.25,filter:"blur(40px)"}}),e.jsxs("div",{style:{position:"absolute",top:64,left:64,right:64,display:"flex",justifyContent:"space-between",alignItems:"center"},children:[e.jsx("div",{style:{fontSize:14,letterSpacing:"0.4em",fontWeight:700,background:r,color:"#000",padding:"8px 16px",display:"inline-block"},children:t.badgeText}),i&&e.jsx("img",{src:i,crossOrigin:"anonymous",style:{height:48,objectFit:"contain",filter:"brightness(0) invert(1)"}})]}),a&&(t.template==="meet"||t.template==="milestone")&&e.jsx("div",{style:{position:"absolute",right:64,top:180,width:380,height:380,borderRadius:"50%",overflow:"hidden",border:`6px solid ${r}`},children:e.jsx("img",{src:a,crossOrigin:"anonymous",style:{width:"100%",height:"100%",objectFit:"cover",objectPosition:"center top"}})}),e.jsxs("div",{style:{position:"absolute",left:64,right:64,bottom:240},children:[t.template==="testimonial"&&e.jsx("div",{style:{fontSize:180,lineHeight:.6,color:r},children:'"'}),e.jsx("h1",{style:{fontSize:t.template==="quote"?110:128,lineHeight:.95,fontWeight:900,margin:0,letterSpacing:"-0.04em",textTransform:t.template==="milestone"?"uppercase":"none",whiteSpace:"pre-wrap",maxWidth:u-128},children:t.headline}),t.subline&&e.jsx("div",{style:{fontSize:28,marginTop:16,color:r,fontWeight:700,letterSpacing:"0.04em"},children:t.subline}),t.body&&e.jsx("p",{style:{fontSize:24,lineHeight:1.45,marginTop:28,maxWidth:820,opacity:.92},children:t.body}),t.template==="testimonial"&&e.jsxs("div",{style:{marginTop:24,display:"flex",alignItems:"center",gap:16},children:[e.jsx(GAe,{rating:t.rating,color:r}),t.attribution&&e.jsxs("div",{style:{fontSize:20,opacity:.9},children:["— ",t.attribution]})]})]}),e.jsxs("div",{style:{position:"absolute",left:64,right:64,bottom:64},children:[e.jsx("div",{style:{height:2,background:r,marginBottom:20,width:80}}),e.jsx(hRt,{name:l,phone:o,email:c,website:d,color:"#fff"})]})]})}function Mqs(s){const{form:t,brandColor:n,accentColor:r,headshot:a,logo:i,name:l,phone:o,email:c,website:d,width:u,height:h}=s;return e.jsxs("div",{style:{width:u,height:h,background:"#fff",position:"relative",fontFamily:"Inter, system-ui, sans-serif",color:"#0a0a0a",overflow:"hidden"},children:[e.jsx("div",{style:{position:"absolute",top:0,left:0,right:0,height:8,background:r}}),e.jsxs("div",{style:{position:"absolute",top:80,left:80,right:80,display:"flex",justifyContent:"space-between",alignItems:"center"},children:[e.jsx("div",{style:{fontSize:13,letterSpacing:"0.3em",color:n,fontWeight:600},children:t.badgeText}),i&&e.jsx("img",{src:i,crossOrigin:"anonymous",style:{height:44,objectFit:"contain"}})]}),a&&(t.template==="meet"||t.template==="milestone")&&e.jsx("div",{style:{position:"absolute",top:160,left:"50%",transform:"translateX(-50%)",width:260,height:260,borderRadius:"50%",overflow:"hidden"},children:e.jsx("img",{src:a,crossOrigin:"anonymous",style:{width:"100%",height:"100%",objectFit:"cover",objectPosition:"center top"}})}),e.jsxs("div",{style:{position:"absolute",left:80,right:80,top:a&&(t.template==="meet"||t.template==="milestone")?460:220,textAlign:"center"},children:[e.jsx("h1",{style:{fontSize:84,lineHeight:1.05,fontWeight:300,margin:0,letterSpacing:"-0.03em",whiteSpace:"pre-wrap"},children:t.headline}),t.subline&&e.jsx("div",{style:{fontSize:22,marginTop:16,color:"#666"},children:t.subline}),t.body&&e.jsx("p",{style:{fontSize:22,lineHeight:1.55,color:"#444",marginTop:32,maxWidth:760,marginLeft:"auto",marginRight:"auto"},children:t.body}),t.template==="testimonial"&&e.jsx("div",{style:{marginTop:24,display:"flex",alignItems:"center",gap:16,justifyContent:"center"},children:e.jsx(GAe,{rating:t.rating,color:r})}),t.attribution&&e.jsxs("div",{style:{fontSize:18,marginTop:16,color:"#666",letterSpacing:"0.1em"},children:["— ",t.attribution]})]}),e.jsxs("div",{style:{position:"absolute",left:80,right:80,bottom:80,textAlign:"center"},children:[e.jsx("div",{style:{width:60,height:1,background:"#0a0a0a",opacity:.3,margin:"0 auto 20px"}}),e.jsx("div",{style:{fontSize:20,fontWeight:600},children:l}),e.jsx("div",{style:{fontSize:14,color:"#666",marginTop:4},children:[o,c,d].filter(Boolean).join(" · ")})]})]})}function Pqs(s){const{form:t,accentColor:n,headshot:r,logo:a,name:i,phone:l,email:o,website:c,width:d,height:u}=s,h=n||"#D4AF37";return e.jsxs("div",{style:{width:d,height:u,background:"#0B0B0E",position:"relative",fontFamily:"Georgia, serif",color:"#EAE6DC",overflow:"hidden"},children:[e.jsx("div",{style:{position:"absolute",inset:40,border:`1px solid ${h}`,opacity:.6}}),e.jsx("div",{style:{position:"absolute",inset:50,border:`1px solid ${h}`,opacity:.25}}),e.jsxs("div",{style:{position:"absolute",top:96,left:96,right:96,textAlign:"center"},children:[e.jsx("div",{style:{fontFamily:"Inter, sans-serif",fontSize:13,letterSpacing:"0.5em",color:h},children:t.badgeText}),e.jsx("div",{style:{width:40,height:1,background:h,margin:"20px auto 0"}})]}),r&&(t.template==="meet"||t.template==="milestone")&&e.jsx("div",{style:{position:"absolute",top:200,left:"50%",transform:"translateX(-50%)",width:340,height:420,overflow:"hidden",border:`1px solid ${h}`},children:e.jsx("img",{src:r,crossOrigin:"anonymous",style:{width:"100%",height:"100%",objectFit:"cover",objectPosition:"center top",filter:"sepia(0.15) brightness(0.95)"}})}),e.jsxs("div",{style:{position:"absolute",left:96,right:96,top:r&&(t.template==="meet"||t.template==="milestone")?680:280,textAlign:"center"},children:[t.template==="testimonial"&&e.jsx("div",{style:{fontSize:100,lineHeight:.6,color:h},children:'"'}),e.jsx("h1",{style:{fontSize:t.template==="quote"?68:80,lineHeight:1.1,fontWeight:400,margin:0,letterSpacing:"-0.01em",whiteSpace:"pre-wrap",fontStyle:t.template==="quote"?"italic":"normal"},children:t.headline}),t.subline&&e.jsx("div",{style:{fontFamily:"Inter, sans-serif",fontSize:18,marginTop:16,color:h,letterSpacing:"0.3em",textTransform:"uppercase"},children:t.subline}),t.body&&e.jsx("p",{style:{fontFamily:"Inter, sans-serif",fontSize:20,lineHeight:1.65,color:"#C9C2B3",marginTop:28,maxWidth:760,marginLeft:"auto",marginRight:"auto",fontWeight:300},children:t.body}),t.template==="testimonial"&&e.jsx("div",{style:{marginTop:24,display:"flex",alignItems:"center",gap:16,justifyContent:"center"},children:e.jsx(GAe,{rating:t.rating,color:h})}),t.attribution&&e.jsxs("div",{style:{fontFamily:"Inter, sans-serif",fontSize:16,marginTop:16,color:h,letterSpacing:"0.2em",textTransform:"uppercase"},children:["— ",t.attribution]})]}),e.jsxs("div",{style:{position:"absolute",left:96,right:96,bottom:96,textAlign:"center"},children:[e.jsx("div",{style:{width:40,height:1,background:h,margin:"0 auto 20px"}}),e.jsx("div",{style:{fontFamily:"Georgia, serif",fontSize:24,letterSpacing:"0.15em",color:"#EAE6DC"},children:i.toUpperCase()}),e.jsx("div",{style:{fontFamily:"Inter, sans-serif",fontSize:13,color:"#9A9285",marginTop:8,letterSpacing:"0.2em"},children:[l,o,c].filter(Boolean).join(" · ")}),a&&e.jsx("img",{src:a,crossOrigin:"anonymous",style:{height:40,objectFit:"contain",marginTop:20,filter:"brightness(0) invert(1) opacity(0.7)"}})]})]})}function Iqs(s,t){const n=s.replace("#",""),r=parseInt(n.length===3?n.split("").map(o=>o+o).join(""):n,16);let a=(r>>16)+Math.round(t/100*255),i=(r>>8&255)+Math.round(t/100*255),l=(r&255)+Math.round(t/100*255);return a=Math.max(0,Math.min(255,a)),i=Math.max(0,Math.min(255,i)),l=Math.max(0,Math.min(255,l)),`#${(a<<16|i<<8|l).toString(16).padStart(6,"0")}`}const Lqs=()=>{const{swagId:s}=oo(),{user:t}=ks(),{toast:n}=Fi(),r=ls(),{trackEngagement:a}=Xq(),[i,l]=k.useState(""),{data:o,isLoading:c}=pt({queryKey:["social-swag-detail",s],queryFn:async()=>{const{data:v,error:_}=await V.from("social_swag").select("*").eq("id",s).single();if(_)throw _;const{data:j}=await V.from("social_swag_links").select("*").eq("swag_id",s).order("sort_order");return{...v,links:j||[]}},enabled:!!s});k.useEffect(()=>{o&&a("social_swag",o.id,o.title,"view")},[o==null?void 0:o.id]);const{data:d=[]}=pt({queryKey:["social-swag-likes",s],queryFn:async()=>{const{data:v,error:_}=await V.from("social_swag_likes").select("*").eq("swag_id",s);if(_)throw _;return v},enabled:!!s}),{data:u=[]}=pt({queryKey:["social-swag-comments",s],queryFn:async()=>{const{data:v,error:_}=await V.from("social_swag_comments").select("*").eq("swag_id",s).order("created_at",{ascending:!1});if(_)throw _;const j=[...new Set(v.map(M=>M.user_id))],{data:C}=await V.from("profiles").select("id, name").in("id",j),A=new Map((C==null?void 0:C.map(M=>[M.id,M.name]))||[]);return v.map(M=>({...M,user_name:A.get(M.user_id)||"Unknown User"}))},enabled:!!s}),h=Nt({mutationFn:async v=>{const{error:_}=await V.from("social_swag_comments").insert({swag_id:s,user_id:t.id,content:v});if(_)throw _},onSuccess:()=>{r.invalidateQueries({queryKey:["social-swag-comments",s]}),l(""),n({title:"Comment added!"})},onError:v=>{n({title:"Error adding comment",description:v.message,variant:"destructive"})}}),m=Nt({mutationFn:async v=>{const{error:_}=await V.from("social_swag_comments").delete().eq("id",v);if(_)throw _},onSuccess:()=>{r.invalidateQueries({queryKey:["social-swag-comments",s]}),n({title:"Comment deleted"})}}),p=Nt({mutationFn:async()=>{const v=d.find(_=>_.user_id===(t==null?void 0:t.id));if(v){const{error:_}=await V.from("social_swag_likes").delete().eq("id",v.id);if(_)throw _}else{const{error:_}=await V.from("social_swag_likes").insert({swag_id:s,user_id:t.id});if(_)throw _}},onSuccess:()=>{r.invalidateQueries({queryKey:["social-swag-likes",s]})}}),g=d.some(v=>v.user_id===(t==null?void 0:t.id)),x=v=>v.split(" ").map(_=>_[0]).join("").toUpperCase().slice(0,2),y=v=>{v.preventDefault(),!(!i.trim()||!t)&&h.mutate(i.trim())};return c?e.jsx(Xs,{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(Xs,{title:o.title,children:e.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[e.jsx($,{variant:"ghost",size:"sm",asChild:!0,className:"gap-2",children:e.jsxs(nr,{to:"/social-swag",children:[e.jsx(Ia,{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(tV,{resourceType:"social_swag",resourceId:o.id,resourceTitle:o.title}),e.jsxs($,{variant:g?"default":"outline",className:"gap-2 w-fit",onClick:()=>p.mutate(),disabled:!t||p.isPending,children:[e.jsx(Ay,{className:`h-4 w-4 ${g?"fill-current":""}`}),d.length," ",d.length===1?"Like":"Likes"]})]})]}),o.description&&e.jsx("div",{className:"text-muted-foreground prose prose-sm max-w-none dark:prose-invert",dangerouslySetInnerHTML:{__html:o.description}})]}),o.links.length>0&&e.jsx(we,{children:e.jsxs(De,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(od,{className:"h-4 w-4"}),o.links.length===1?"Canva Link":"Canva Links"]}),e.jsx("div",{className:"grid gap-2",children:o.links.map(v=>e.jsxs($,{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(v.canva_share_link,"_blank")},children:[e.jsx("span",{className:"font-medium",children:v.title}),e.jsx(Ir,{className:"h-4 w-4 text-muted-foreground"})]},v.id))})]})}),e.jsx(Pc,{}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 text-lg",children:[e.jsx(Vu,{className:"h-5 w-5"}),"Comments (",u.length,")"]}),t?e.jsxs("form",{onSubmit:y,className:"flex gap-2",children:[e.jsx(Ls,{placeholder:"Add a comment...",value:i,onChange:v=>l(v.target.value),className:"min-h-[80px] resize-none flex-1"}),e.jsx($,{type:"submit",size:"icon",className:"h-10 w-10",disabled:!i.trim()||h.isPending,children:e.jsx(Wr,{className:"h-4 w-4"})})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"Log in to add a comment"}),e.jsx("div",{className:"space-y-4",children:u.length===0?e.jsx(we,{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!"})})}):u.map(v=>e.jsx(we,{children:e.jsx(De,{className:"pt-4 pb-4",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsx(Wa,{className:"h-10 w-10 flex-shrink-0",children:e.jsx(Ka,{className:"text-sm",children:x(v.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:v.user_name}),e.jsx("span",{className:"text-sm text-muted-foreground",children:Zc(new Date(v.created_at),{addSuffix:!0})}),v.user_id===(t==null?void 0:t.id)&&e.jsx($,{variant:"ghost",size:"icon",className:"h-6 w-6 ml-auto",onClick:()=>m.mutate(v.id),children:e.jsx(Un,{className:"h-3 w-3 text-muted-foreground"})})]}),e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:v.content})]})]})})},v.id))})]})]})}):e.jsx(Xs,{title:"Social Swag",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(od,{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($,{asChild:!0,className:"mt-4",children:e.jsx(nr,{to:"/social-swag",children:"Back to Social Swag"})})]})})},Rqs=({categories:s,privateGroups:t,selectedFilter:n,onFilterChange:r,onlineUsers:a})=>{const[i,l]=k.useState(!0),[o,c]=k.useState(!0),[d,u]=k.useState(!0),h=m=>m.split(" ").map(p=>p[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($,{variant:n==="all"?"secondary":"ghost",className:"w-full justify-start",onClick:()=>r("all"),children:[e.jsx(VT,{className:"h-4 w-4 mr-2"}),"All Posts"]}),e.jsxs(h1,{open:i,onOpenChange:l,children:[e.jsx(m1,{asChild:!0,children:e.jsxs($,{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(Go,{className:"h-4 w-4"}):e.jsx(fi,{className:"h-4 w-4"})]})}),e.jsx(f1,{className:"space-y-1 pl-2",children:s.map(m=>e.jsxs($,{variant:n===m.id?"secondary":"ghost",size:"sm",className:"w-full justify-start h-9",onClick:()=>r(m.id),children:[e.jsx("span",{className:"mr-2",children:m.icon||"📂"}),e.jsx("span",{className:"truncate",children:m.name})]},m.id))})]}),t.length>0&&e.jsxs(h1,{open:o,onOpenChange:c,children:[e.jsx(m1,{asChild:!0,children:e.jsxs($,{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(fu,{className:"h-3 w-3"}),"Your Groups"]}),o?e.jsx(Go,{className:"h-4 w-4"}):e.jsx(fi,{className:"h-4 w-4"})]})}),e.jsx(f1,{className:"space-y-1 pl-2",children:t.map(m=>e.jsxs($,{variant:n===`group:${m.id}`?"secondary":"ghost",size:"sm",className:"w-full justify-start h-9",onClick:()=>r(`group:${m.id}`),children:[e.jsx("span",{className:"mr-2",children:m.icon||"🔒"}),e.jsx("span",{className:"truncate",children:m.name})]},m.id))})]}),e.jsxs(h1,{open:d,onOpenChange:u,children:[e.jsx(m1,{asChild:!0,children:e.jsxs($,{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(Xn,{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(Go,{className:"h-4 w-4"}):e.jsx(fi,{className:"h-4 w-4"})]})}),e.jsx(f1,{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(m=>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(Wa,{className:"h-7 w-7",children:[e.jsx(eo,{src:m.avatarUrl}),e.jsx(Ka,{className:"text-xs",children:h(m.name)})]}),e.jsx(rx,{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:m.name})]},m.id))})]})]})})})},Dqs=({categories:s,privateGroups:t,selectedFilter:n,onFilterChange:r,onlineUsers:a})=>{const[i,l]=k.useState(!1),o=d=>d.split(" ").map(u=>u[0]).join("").toUpperCase().slice(0,2),c=()=>{if(n==="all")return"All Posts";if(n.startsWith("group:")){const u=n.replace("group:",""),h=t.find(m=>m.id===u);return h?`🔒 ${h.name}`:"Private Group"}const d=s.find(u=>u.id===n);return d?`${d.icon||"📂"} ${d.name}`:"Category"};return e.jsxs("div",{className:"lg:hidden flex items-center gap-2 mb-4",children:[e.jsxs(Au,{children:[e.jsx(Eu,{asChild:!0,children:e.jsxs($,{variant:"outline",className:"flex-1 justify-between",children:[e.jsx("span",{className:"truncate",children:c()}),e.jsx(Go,{className:"h-4 w-4 ml-2 shrink-0"})]})}),e.jsxs(gu,{className:"w-56 bg-background border",children:[e.jsxs(Pa,{onClick:()=>r("all"),children:[e.jsx(VT,{className:"h-4 w-4 mr-2"}),"All Posts"]}),e.jsx(j0,{}),e.jsx(TO,{className:"text-xs text-muted-foreground",children:"Categories"}),s.map(d=>e.jsxs(Pa,{onClick:()=>r(d.id),children:[e.jsx("span",{className:"mr-2",children:d.icon||"📂"}),d.name]},d.id)),t.length>0&&e.jsxs(e.Fragment,{children:[e.jsx(j0,{}),e.jsxs(TO,{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(fu,{className:"h-3 w-3"}),"Your Groups"]}),t.map(d=>e.jsxs(Pa,{onClick:()=>r(`group:${d.id}`),children:[e.jsx("span",{className:"mr-2",children:d.icon||"🔒"}),d.name]},d.id))]})]})]}),e.jsxs(D_,{open:i,onOpenChange:l,children:[e.jsx(uee,{asChild:!0,children:e.jsxs($,{variant:"outline",size:"icon",className:"relative",children:[e.jsx(Xn,{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(Mb,{children:[e.jsx(xj,{children:e.jsxs(yj,{className:"flex items-center gap-2",children:[e.jsx(Xn,{className:"h-5 w-5"}),"Online Now (",a.length,")"]})}),e.jsx(Eo,{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(Wa,{className:"h-10 w-10",children:[e.jsx(eo,{src:d.avatarUrl}),e.jsx(Ka,{children:o(d.name)})]}),e.jsx(rx,{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 Oqs=Object.defineProperty,MM=(s,t)=>Oqs(s,"name",{value:t,configurable:!0}),QLe,ZKe="HoverCard",[mRt,hJn]=qm(ZKe,[Q5]),XKe=Q5(),[Fqs,QKe]=mRt(ZKe),zqs=MM(s=>{const{__scopeHoverCard:t,children:n,open:r,defaultOpen:a,onOpenChange:i,openDelay:l=700,closeDelay:o=300}=s,c=XKe(t),d=k.useRef(0),u=k.useRef(0),h=k.useRef(!1),m=k.useRef(!1),[p,g]=ox({prop:r,defaultProp:a??!1,onChange:i,caller:ZKe}),x=k.useCallback(()=>{clearTimeout(u.current),d.current=window.setTimeout(()=>g(!0),l)},[l,g]),y=k.useCallback(()=>{clearTimeout(d.current),!h.current&&!m.current&&(u.current=window.setTimeout(()=>g(!1),o))},[o,g]),v=k.useCallback(()=>g(!1),[g]);return k.useEffect(()=>()=>{clearTimeout(d.current),clearTimeout(u.current)},[]),e.jsx(Fqs,{scope:t,open:p,onOpenChange:g,onOpen:x,onClose:y,onDismiss:v,hasSelectionRef:h,isPointerDownOnContentRef:m,children:e.jsx(ree,{...c,children:n})})},"HoverCard"),Bqs="HoverCardTrigger",$qs=k.forwardRef(MM(function(t,n){const{__scopeHoverCard:r,...a}=t,i=QKe(Bqs,r),l=XKe(r);return e.jsx(aee,{asChild:!0,...l,children:e.jsx(hi.a,{"data-state":i.open?"open":"closed",...a,ref:n,onPointerEnter:ga(t.onPointerEnter,bX(i.onOpen)),onPointerLeave:ga(t.onPointerLeave,bX(i.onClose)),onFocus:ga(t.onFocus,i.onOpen),onBlur:ga(t.onBlur,i.onClose),onTouchStart:ga(t.onTouchStart,o=>o.preventDefault())})})},"HoverCardTrigger")),Uqs="HoverCardPortal",[mJn,qqs]=mRt(Uqs,{forceMount:void 0}),tze="HoverCardContent",Vqs=k.forwardRef(MM(function(t,n){const r=qqs(tze,t.__scopeHoverCard),{forceMount:a=r.forceMount,...i}=t,l=QKe(tze,t.__scopeHoverCard);return e.jsx(cx,{present:a||l.open,children:e.jsx(Hqs,{"data-state":l.open?"open":"closed",...i,onPointerEnter:ga(t.onPointerEnter,bX(l.onOpen)),onPointerLeave:ga(t.onPointerLeave,bX(l.onClose)),ref:n})})},"HoverCardContent")),Hqs=k.forwardRef(MM(function(t,n){const{__scopeHoverCard:r,onEscapeKeyDown:a,onPointerDownOutside:i,onFocusOutside:l,onInteractOutside:o,...c}=t,d=QKe(tze,r),u=XKe(r),h=k.useRef(null),m=Ao(n,h),[p,g]=k.useState(!1);return k.useEffect(()=>{if(p){const x=document.body;return QLe=x.style.userSelect||x.style.webkitUserSelect,x.style.userSelect="none",x.style.webkitUserSelect="none",()=>{x.style.userSelect=QLe,x.style.webkitUserSelect=QLe}}},[p]),k.useEffect(()=>{if(h.current){const x=MM(()=>{g(!1),d.isPointerDownOnContentRef.current=!1,setTimeout(()=>{var v;((v=document.getSelection())==null?void 0:v.toString())!==""&&(d.hasSelectionRef.current=!0)})},"handlePointerUp");return document.addEventListener("pointerup",x),()=>{document.removeEventListener("pointerup",x),d.hasSelectionRef.current=!1,d.isPointerDownOnContentRef.current=!1}}},[d.isPointerDownOnContentRef,d.hasSelectionRef]),k.useEffect(()=>{h.current&&fRt(h.current).forEach(y=>y.setAttribute("tabindex","-1"))}),e.jsx(pF,{asChild:!0,disableOutsidePointerEvents:!1,onInteractOutside:o,onEscapeKeyDown:a,onPointerDownOutside:i,onFocusOutside:ga(l,x=>{x.preventDefault()}),onDismiss:d.onDismiss,children:e.jsx(iee,{...u,...c,onPointerDown:ga(c.onPointerDown,x=>{x.currentTarget.contains(x.target)&&g(!0),d.hasSelectionRef.current=!1,d.isPointerDownOnContentRef.current=!0}),ref:m,style:{...c.style,userSelect:p?"text":void 0,WebkitUserSelect:p?"text":void 0,"--radix-hover-card-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-hover-card-content-available-width":"var(--radix-popper-available-width)","--radix-hover-card-content-available-height":"var(--radix-popper-available-height)","--radix-hover-card-trigger-width":"var(--radix-popper-anchor-width)","--radix-hover-card-trigger-height":"var(--radix-popper-anchor-height)"}})})},"HoverCardContentImpl"));function bX(s){return t=>t.pointerType==="touch"?void 0:s()}MM(bX,"excludeTouch");function fRt(s){const t=[],n=document.createTreeWalker(s,NodeFilter.SHOW_ELEMENT,{acceptNode:MM(r=>r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP,"acceptNode")});for(;n.nextNode();)t.push(n.currentNode);return t}MM(fRt,"getTabbableNodes");var Gqs=zqs,Wqs=$qs,pRt=Vqs;const Kqs=Gqs,Yqs=Wqs,gRt=k.forwardRef(({className:s,align:t="center",sideOffset:n=4,...r},a)=>e.jsx(pRt,{ref:a,align:t,sideOffset:n,className:Ot("z-50 w-64 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",s),...r}));gRt.displayName=pRt.displayName;const Zqs=[{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"}],Xqs=s=>s.split(" ").map(t=>t[0]).join("").toUpperCase().slice(0,2),xRt=({reactions:s,children:t})=>{if(s.length===0)return e.jsx(e.Fragment,{children:t});const n={};return s.forEach(r=>{n[r.reaction_type]||(n[r.reaction_type]=[]),n[r.reaction_type].push(r)}),e.jsxs(Kqs,{openDelay:200,closeDelay:100,children:[e.jsx(Yqs,{asChild:!0,children:e.jsx("div",{className:"cursor-pointer",children:t})}),e.jsx(gRt,{className:"w-64 p-3 bg-popover border shadow-lg z-50",side:"top",align:"start",children:e.jsx("div",{className:"space-y-3",children:Object.entries(n).map(([r,a])=>{const i=Zqs.find(l=>l.type===r);return e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("span",{className:"text-lg",children:i==null?void 0:i.emoji}),e.jsxs("span",{className:"text-sm font-medium text-foreground",children:[i==null?void 0:i.label," (",a.length,")"]})]}),e.jsxs("div",{className:"space-y-1.5",children:[a.slice(0,10).map(l=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(Wa,{className:"h-6 w-6",children:[e.jsx(eo,{src:l.user_avatar||void 0}),e.jsx(Ka,{className:"text-[10px]",children:Xqs(l.user_name||"U")})]}),e.jsx("span",{className:"text-sm text-foreground truncate",children:l.user_name||"Unknown User"})]},l.id)),a.length>10&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["+",a.length-10," more"]})]})]},r)})})})]})};function Qqs({images:s,initialIndex:t=0,open:n,onOpenChange:r}){const[a,i]=k.useState(t),[l,o]=k.useState(!1);k.useEffect(()=>{n&&(i(t),o(!1))},[n,t]);const c=()=>{i(m=>m>0?m-1:s.length-1),o(!1)},d=()=>{i(m=>m{n&&(m.key==="ArrowLeft"&&c(),m.key==="ArrowRight"&&d(),m.key==="Escape"&&r(!1))},[n,s.length]);k.useEffect(()=>(window.addEventListener("keydown",u),()=>window.removeEventListener("keydown",u)),[u]);const h=s[a];return e.jsx(zs,{open:n,onOpenChange:r,children:e.jsxs(Rs,{className:"max-w-[95vw] max-h-[95vh] w-auto h-auto p-0 border-none bg-black/95 overflow-hidden",children:[e.jsx($,{variant:"ghost",size:"icon",className:"absolute top-2 right-2 z-50 text-white hover:bg-white/20 h-10 w-10",onClick:()=>r(!1),children:e.jsx(mr,{className:"h-6 w-6"})}),s.length>1&&e.jsxs(e.Fragment,{children:[e.jsx($,{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(Ld,{className:"h-8 w-8"})}),e.jsx($,{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(fi,{className:"h-8 w-8"})})]}),s.length>1&&e.jsxs("div",{className:"absolute bottom-4 left-1/2 -translate-x-1/2 z-50 text-white text-sm bg-black/50 px-3 py-1 rounded-full",children:[a+1," / ",s.length]}),(h==null?void 0:h.type)==="image"&&e.jsx($,{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(yB,{className:"h-5 w-5"}):e.jsx(aM,{className:"h-5 w-5"})}),e.jsx("div",{className:Ot("flex items-center justify-center w-full h-full min-h-[50vh] p-4",l?"cursor-zoom-out overflow-auto":"cursor-zoom-in"),onClick:()=>(h==null?void 0:h.type)==="image"&&o(!l),children:(h==null?void 0:h.type)==="video"?e.jsx("video",{src:h.url,controls:!0,autoPlay:!0,className:"max-w-full max-h-[85vh] object-contain",onClick:m=>m.stopPropagation()}):e.jsx("img",{src:h==null?void 0:h.url,alt:"",className:Ot("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((m,p)=>e.jsx("button",{onClick:()=>{i(p),o(!1)},className:Ot("w-12 h-12 rounded overflow-hidden flex-shrink-0 border-2 transition-all",a===p?"border-white":"border-transparent opacity-60 hover:opacity-100"),children:m.type==="video"?e.jsx("video",{src:m.url,className:"w-full h-full object-cover"}):e.jsx("img",{src:m.url,alt:"",className:"w-full h-full object-cover"})},p))})]})})}const Wre=[{type:"like",emoji:"👍",label:"Like"},{type:"love",emoji:"❤️",label:"Love"}],Jqs=({commentId:s,reactions:t,currentUserId:n})=>{var d,u;const r=ls(),[a,i]=k.useState(!1),l=t.find(h=>h.user_id===n),o=Nt({mutationFn:async h=>{l?l.reaction_type===h?await V.from("community_comment_reactions").delete().eq("id",l.id):await V.from("community_comment_reactions").update({reaction_type:h}).eq("id",l.id):await V.from("community_comment_reactions").insert({comment_id:s,user_id:n,reaction_type:h})},onSuccess:()=>{r.invalidateQueries({queryKey:["community-posts"]}),i(!1)}}),c={};return t.forEach(h=>{c[h.reaction_type]=(c[h.reaction_type]||0)+1}),e.jsxs("div",{className:"flex items-center gap-2",children:[t.length>0&&e.jsx(xRt,{reactions:t,children:e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx("div",{className:"flex -space-x-0.5",children:Object.keys(c).slice(0,2).map(h=>{var m;return e.jsx("span",{className:"text-sm",children:(m=Wre.find(p=>p.type===h))==null?void 0:m.emoji},h)})}),e.jsx("span",{children:t.length})]})}),n&&e.jsxs(Xc,{open:a,onOpenChange:i,children:[e.jsx(Qc,{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=Wre.find(h=>h.type===l.reaction_type))==null?void 0:d.emoji," ",(u=Wre.find(h=>h.type===l.reaction_type))==null?void 0:u.label]}):e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Bo,{className:"h-3 w-3"}),"Like"]})})}),e.jsx(Bc,{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:Wre.map(h=>e.jsx("button",{onClick:()=>o.mutate(h.type),className:"text-xl hover:scale-125 transition-transform p-1",title:h.label,children:h.emoji},h.type))})})]})]})};function JKe({content:s,className:t}){const n=/([@#])\[([^\]]+)\]\(([^)]+)\)|(https?:\/\/[^\s<>]+)/g,r=[];let a=0,i,l=0;for(;(i=n.exec(s))!==null;){if(i.index>a&&r.push(s.substring(a,i.index)),i[1]){const o=i[1],c=i[2],d=i[3],u=o==="#";r.push(e.jsx(nr,{to:u?`/templates/${d}`:`/profile?user=${d}`,className:Ot("font-medium hover:underline",u?"text-white bg-[#2a4c64] px-1.5 py-0.5 rounded":"text-primary"),onClick:h=>h.stopPropagation(),children:u?c:`@${c}`},`mention-${l++}`))}else if(i[4]){const o=i[4],c=o.replace(/[.,;:!?)]+$/,""),d=o.slice(c.length);let u;try{const h=new URL(c);u=h.hostname+(h.pathname!=="/"?h.pathname.slice(0,20)+(h.pathname.length>20?"...":""):"")}catch{u=c.length>40?c.slice(0,40)+"...":c}r.push(e.jsx("a",{href:c,target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline break-all",onClick:h=>h.stopPropagation(),children:u},`url-${l++}`)),d&&r.push(d)}a=i.index+i[0].length}return ae.jsx(k.Fragment,{children:o},c))})}function y5e({value:s,onChange:t,placeholder:n="What's on your mind? Use @ to mention someone",className:r,minHeight:a="80px",onMentionsChange:i,onTemplatesChange:l,onKeyDown:o,mentionFormat:c="encoded",enableTemplateMentions:d=!1}){const u=k.useRef(null),h=k.useRef(null),[m,p]=k.useState(!1),[g,x]=k.useState("user"),[y,v]=k.useState(""),[_,j]=k.useState(null),[C,A]=k.useState(0),[M,I]=k.useState({top:0,left:0,width:0}),P=k.useRef(new Map),R=k.useRef(new Map),O=le=>{if(c==="plain"){const he=[];return P.current.forEach((Te,Ie)=>{le.includes(`@${Ie}`)&&he.push(Te)}),[...new Set(he)]}const fe=/@\[([^\]]+)\]\(([^)]+)\)/g,_e=[];let ve;for(;(ve=fe.exec(le))!==null;)_e.push(ve[2]);return[...new Set(_e)]},B=le=>{if(c==="plain"){const he=[];return R.current.forEach((Te,Ie)=>{le.includes(`#${Ie}`)&&he.push(Te)}),[...new Set(he)]}const fe=/#\[([^\]]+)\]\(([^)]+)\)/g,_e=[];let ve;for(;(ve=fe.exec(le))!==null;)_e.push(ve[2]);return[...new Set(_e)]};k.useEffect(()=>{if(i){const le=O(s);i(le)}if(l){const le=B(s);l(le)}},[s,i,l,c]);const{data:U=[],isLoading:G}=pt({queryKey:["mention-users",y],queryFn:async()=>{const le=V.from("profiles").select("id, name").limit(8),fe=y.length>=1?le.ilike("name",`%${y}%`):le.order("name"),{data:_e,error:ve}=await fe;if(ve)throw ve;const he=_e.map(Te=>Te.id),Se=await yCt(he);return _e.map(Te=>({id:Te.id,name:Te.name||"Unknown",avatar_url:Se.get(Te.id)}))},enabled:m&&g==="user",staleTime:3e4}),{data:H=[],isLoading:Y}=pt({queryKey:["mention-templates",y],queryFn:async()=>{let le=V.from("canva_templates").select("id, name, preview_image_url").lte("publish_date",new Date().toISOString()).order("publish_date",{ascending:!1}).limit(8);y.length>=1&&(le=le.ilike("name",`%${y}%`));const{data:fe,error:_e}=await le;if(_e)throw _e;return fe||[]},enabled:m&&g==="template"&&d,staleTime:3e4}),se=g==="user"?G:Y,ee=g==="user"?U:H,oe=le=>le.split(" ").map(fe=>fe[0]).join("").toUpperCase().slice(0,2),me=le=>{const fe=le.target.value,_e=le.target.selectionStart;t(fe);const ve=fe.substring(0,_e),he=ve.lastIndexOf("@"),Se=d?ve.lastIndexOf("#"):-1;let Te=-1,Ie="user";if(he>Se?(Te=he,Ie="user"):Se>he&&d&&(Te=Se,Ie="template"),Te!==-1){const Ue=ve.substring(Te+1),Be=Ue.includes(" "),je=Ue.includes(` `);if(!Be&&!je&&Ue.length<=30){j(Te),v(Ue),x(Ie),p(!0),A(0);return}}p(!1),j(null)},Q=le=>{if(_===null)return;const fe=s.substring(0,_),_e=s.substring(_+y.length+1),ve=g==="user"?"@":"#",he=c==="plain"?`${ve}${le.name} `:`${ve}[${le.name}](${le.id}) `;c==="plain"&&(g==="user"?P.current.set(le.name,le.id):R.current.set(le.name,le.id));const Se=fe+he+_e;t(Se),p(!1),j(null),v(""),setTimeout(()=>{if(u.current){const Te=fe.length+he.length;u.current.focus(),u.current.setSelectionRange(Te,Te)}},0)},te=le=>{if(!(!m||ee.length===0))switch(le.key){case"ArrowDown":le.preventDefault(),A(fe=>(fe+1)%ee.length);break;case"ArrowUp":le.preventDefault(),A(fe=>(fe-1+ee.length)%ee.length);break;case"Enter":ee[C]&&(le.preventDefault(),Q(ee[C]));break;case"Escape":le.preventDefault(),p(!1);break;case"Tab":ee[C]&&(le.preventDefault(),Q(ee[C]));break}};return k.useEffect(()=>{const le=fe=>{h.current&&!h.current.contains(fe.target)&&u.current&&!u.current.contains(fe.target)&&p(!1)};return document.addEventListener("mousedown",le),()=>document.removeEventListener("mousedown",le)},[]),k.useEffect(()=>{if(!m)return;const le=()=>{const fe=u.current;if(!fe)return;const _e=fe.getBoundingClientRect();I({top:_e.bottom+4,left:_e.left,width:_e.width})};return le(),window.addEventListener("resize",le),window.addEventListener("scroll",le,!0),()=>{window.removeEventListener("resize",le),window.removeEventListener("scroll",le,!0)}},[m,s]),e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Ls,{ref:u,value:s,onChange:me,onKeyDown:le=>{te(le),le.defaultPrevented||o==null||o(le)},placeholder:n,className:Ot("resize-none",r),style:{minHeight:a}}),m&&a1.createPortal(e.jsxs("div",{ref:h,className:"fixed z-[1000] max-h-[220px] overflow-hidden rounded-lg border bg-popover shadow-lg",style:{top:M.top,left:M.left,width:M.width,maxWidth:"320px"},children:[e.jsx("div",{className:"px-3 py-1.5 text-xs font-medium text-muted-foreground border-b bg-muted/30",children:g==="user"?"👤 Mention a person":"📋 Link a template"}),se?e.jsx("div",{className:"px-3 py-2 text-sm text-muted-foreground",children:"Searching..."}):ee.length===0?e.jsx("div",{className:"px-3 py-2 text-sm text-muted-foreground",children:y.length<1?`Type to search ${g==="user"?"people":"templates"}...`:`No ${g==="user"?"users":"templates"} found`}):e.jsx("ul",{className:"py-1 max-h-[180px] overflow-y-auto",children:ee.map((le,fe)=>e.jsx("li",{className:Ot("flex items-center gap-2 px-3 py-2 cursor-pointer transition-colors",fe===C?"bg-accent":"hover:bg-accent/50"),onClick:()=>Q(le),onMouseEnter:()=>A(fe),children:g==="user"?e.jsxs(e.Fragment,{children:[e.jsxs(Wa,{className:"h-6 w-6",children:[e.jsx(eo,{src:le.avatar_url}),e.jsx(Ka,{className:"text-xs",children:oe(le.name)})]}),e.jsx("span",{className:"text-sm font-medium truncate",children:le.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:le.preview_image_url?e.jsx("img",{src:le.preview_image_url,alt:"",className:"w-full h-full object-cover"}):e.jsx(gd,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx("span",{className:"text-sm font-medium truncate",children:le.name})]})},le.id))})]}),document.body)]})}function eVs(s){const t=/#\[([^\]]+)\]\(([^)]+)\)/g,n=[];let r;for(;(r=t.exec(s))!==null;)n.push(r[2]);return[...new Set(n)]}const Wht=s=>s.split(" ").map(t=>t[0]).join("").toUpperCase().slice(0,2);function yRt({comment:s,postId:t,currentUserId:n,currentUserAvatar:r,currentUserEmail:a,canModerate:i,depth:l=0}){const o=ls(),[c,d]=k.useState(!1),[u,h]=k.useState(""),[m,p]=k.useState([]),g=Nt({mutationFn:async({content:_,parentCommentId:j})=>{const{data:C,error:A}=await V.from("community_comments").insert({post_id:t,user_id:n,content:_,parent_comment_id:j}).select("id").single();if(A)throw A;const M=m;if(M.length>0&&C){const I=M.filter(P=>P!==n).map(P=>({comment_id:C.id,mentioned_user_id:P,mentioned_by_user_id:n}));I.length>0&&await V.from("community_comment_mentions").insert(I)}},onSuccess:()=>{o.invalidateQueries({queryKey:["community-posts"]}),h(""),p([]),d(!1)}}),x=Nt({mutationFn:async _=>{const{error:j}=await V.from("community_comments").delete().eq("id",_);if(j)throw j},onSuccess:()=>o.invalidateQueries({queryKey:["community-posts"]})}),y=()=>{u.trim()&&g.mutate({content:u,parentCommentId:s.id})};return e.jsxs("div",{className:l>0?"ml-8 border-l-2 border-muted pl-3":"",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(Wa,{className:"h-8 w-8 shrink-0",children:[e.jsx(eo,{src:s.user_avatar||void 0}),e.jsx(Ka,{className:"text-xs",children:Wht(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(JKe,{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:Zc(new Date(s.created_at),{addSuffix:!0})}),e.jsx(Jqs,{commentId:s.id,reactions:s.reactions,currentUserId:n}),n&&l<2&&e.jsxs("button",{onClick:()=>d(!c),className:"hover:text-primary flex items-center gap-1",children:[e.jsx(WK,{className:"h-3 w-3"}),"Reply"]}),(s.user_id===n||i)&&e.jsx("button",{onClick:()=>x.mutate(s.id),className:"hover:text-destructive",children:s.user_id!==n?"Remove":"Delete"})]}),c&&n&&e.jsxs("div",{className:"flex gap-2 mt-2",children:[e.jsxs(Wa,{className:"h-6 w-6 shrink-0 mt-1",children:[e.jsx(eo,{src:r||void 0}),e.jsx(Ka,{className:"text-xs",children:Wht((a==null?void 0:a.split("@")[0])||"U")})]}),e.jsxs("div",{className:"flex-1 flex gap-2 items-start",children:[e.jsx(y5e,{placeholder:`Reply to ${s.user_name}...`,value:u,onChange:h,onMentionsChange:p,mentionFormat:"plain",className:"text-sm min-h-0 py-1.5",minHeight:"32px"}),e.jsx($,{size:"sm",variant:"ghost",onClick:y,disabled:!u.trim()||g.isPending,className:"h-8 px-2 mt-0.5",children:e.jsx(Wr,{className:"h-3 w-3"})})]})]})]})]}),s.replies&&s.replies.length>0&&e.jsx("div",{className:"mt-2 space-y-2",children:s.replies.map(_=>e.jsx(yRt,{comment:_,postId:t,currentUserId:n,currentUserAvatar:r,currentUserEmail:a,canModerate:i,depth:l+1},_.id))})]})}const Kre=[{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"}],tVs=()=>{const{user:s,isBrokerageManager:t,managedBrokerages:n,isAdmin:r}=ks(),{avatarUrl:a}=xCt(s==null?void 0:s.id),{onlineUsers:i}=S4t(),{toast:l}=Fi(),o=ls(),c=k.useRef(null),[d,u]=k.useState("all"),[h,m]=k.useState(""),[p,g]=k.useState(""),[x,y]=k.useState(""),[v,_]=k.useState([]),[j,C]=k.useState([]),[A,M]=k.useState(""),[I,P]=k.useState(!1),[R,O]=k.useState(null),[B,U]=k.useState(""),[G,H]=k.useState(new Set),[Y,se]=k.useState({}),[ee,oe]=k.useState({}),[me,Q]=k.useState([]),[te,le]=k.useState([]),[fe,_e]=k.useState({open:!1,images:[],index:0});k.useEffect(()=>{if(d.startsWith("group:")){const rt=d.replace("group:","");y(rt),g("")}else d!=="all"?(g(d),y("")):(g(""),y(""))},[d]);const{data:ve=[]}=pt({queryKey:["community-categories"],queryFn:async()=>{const{data:rt,error:Ft}=await V.from("community_categories").select("*").order("sort_order");if(Ft)throw Ft;return rt}}),{data:he=[]}=pt({queryKey:["community-private-groups"],queryFn:async()=>{const{data:rt,error:Ft}=await V.from("community_private_groups").select("id, name, description, icon, brokerage_id, sort_order").order("sort_order");if(Ft)throw Ft;return rt}}),Se=20,{data:Te,isLoading:Ie,hasNextPage:Ue,fetchNextPage:Be,isFetchingNextPage:je}=Ios({queryKey:["community-posts",d],initialPageParam:0,queryFn:async({pageParam:rt})=>{var lo;const Ft=rt*Se,Ut=Ft+Se;let Is=V.from("community_posts").select("*").order("is_pinned",{ascending:!1}).order("pinned_at",{ascending:!1,nullsFirst:!1}).order("created_at",{ascending:!1}).range(Ft,Ut);if(d.startsWith("group:")){const Yn=d.replace("group:","");Is=Is.eq("private_group_id",Yn)}else d==="all"||(Is=Is.eq("category_id",d).is("private_group_id",null));const{data:xs,error:st}=await Is;if(st)throw st;const dt=((xs==null?void 0:xs.length)||0)>Se,jt=(xs||[]).slice(0,Se);if(jt.length===0)return{posts:[],hasMore:!1,nextPage:rt+1};const gt=jt.map(Yn=>Yn.id),rs=[...new Set(jt.filter(Yn=>Yn.category_id).map(Yn=>Yn.category_id))].filter(Boolean),[Ns,us,Bs,Ts,Fn]=await Promise.all([rs.length?V.from("community_categories").select("*").in("id",rs):Promise.resolve({data:[]}),V.from("community_post_media").select("*").in("post_id",gt).order("sort_order"),V.from("community_reactions").select("*").in("post_id",gt),V.from("community_comments").select("*").in("post_id",gt).order("created_at",{ascending:!0}),V.from("community_post_resources").select("*").in("post_id",gt)]),An=Ns==null?void 0:Ns.data,js=us==null?void 0:us.data,In=Bs==null?void 0:Bs.data,un=Ts==null?void 0:Ts.data,jr=Fn==null?void 0:Fn.data,Ln=(un||[]).map(Yn=>Yn.id),[Sr,Qn]=await Promise.all([Ln.length?V.from("community_comment_reactions").select("*").in("comment_id",Ln):Promise.resolve({data:[]}),(()=>{const Yn=(jr||[]).filter(Hr=>Hr.resource_type==="template").map(Hr=>Hr.resource_id);return Yn.length===0?Promise.resolve({data:[]}):V.from("canva_templates").select("id, name, preview_image_url").in("id",Yn)})()]),En=(Sr==null?void 0:Sr.data)||[],pr=(Qn==null?void 0:Qn.data)||[],xn=new Map(pr.map(Yn=>[Yn.id,{name:Yn.name,preview_image_url:Yn.preview_image_url}])),Ar=Array.from(new Set([...jt.map(Yn=>Yn.user_id),...(In||[]).map(Yn=>Yn.user_id),...(un||[]).map(Yn=>Yn.user_id),...En.map(Yn=>Yn.user_id)])),[Zr,dn]=await Promise.all([Ar.length?V.from("profiles").select("id, name").in("id",Ar):Promise.resolve({data:[]}),yCt(Ar)]),Kt=new Map(((lo=Zr==null?void 0:Zr.data)==null?void 0:lo.map(Yn=>[Yn.id,Yn.name]))||[]),Er=new Map((An||[]).map(Yn=>[Yn.id,Yn])),ti=Yn=>{const Hr=new Map,Ur=[];return Yn.forEach(Ei=>{Hr.set(Ei.id,{...Ei,user_name:Kt.get(Ei.user_id)||"Unknown User",user_avatar:dn.get(Ei.user_id),reactions:En.filter(fo=>fo.comment_id===Ei.id).map(fo=>({...fo,user_name:Kt.get(fo.user_id)||"Unknown User",user_avatar:dn.get(fo.user_id)})),replies:[]})}),Yn.forEach(Ei=>{const fo=Hr.get(Ei.id);if(Ei.parent_comment_id&&Hr.has(Ei.parent_comment_id)){const co=Hr.get(Ei.parent_comment_id);co.replies=co.replies||[],co.replies.push(fo)}else Ur.push(fo)}),Ur};return{posts:jt.map(Yn=>{const Hr=(jr||[]).filter(Ur=>Ur.post_id===Yn.id).map(Ur=>{let Ei="",fo=null;if(Ur.resource_type==="template"){const co=xn.get(Ur.resource_id);Ei=(co==null?void 0:co.name)||"Unknown Template",fo=(co==null?void 0:co.preview_image_url)||null}return{id:Ur.id,resource_type:Ur.resource_type,resource_id:Ur.resource_id,resource_name:Ei,resource_preview_url:fo}});return{...Yn,user_name:Kt.get(Yn.user_id)||"Unknown User",user_avatar:dn.get(Yn.user_id),category:Yn.category_id?Er.get(Yn.category_id):null,media:(js||[]).filter(Ur=>Ur.post_id===Yn.id),reactions:((In||[]).filter(Ur=>Ur.post_id===Yn.id)||[]).map(Ur=>({...Ur,user_name:Kt.get(Ur.user_id)||"Unknown User",user_avatar:dn.get(Ur.user_id)})),comments:ti((un||[]).filter(Ur=>Ur.post_id===Yn.id)),resources:Hr}}),hasMore:dt,nextPage:rt+1}},getNextPageParam:rt=>rt.hasMore?rt.nextPage:void 0}),Ye=k.useMemo(()=>(Te==null?void 0:Te.pages.flatMap(rt=>rt.posts))??[],[Te]),Ee=Nt({mutationFn:async()=>{P(!0);const{data:rt,error:Ft}=await V.from("community_posts").insert({user_id:s.id,category_id:x?null:p||null,private_group_id:x||null,content:h,link_url:A||null}).select().single();if(Ft)throw Ft;for(let Is=0;Is0){const Is=me.filter(xs=>xs!==s.id).map(xs=>({post_id:rt.id,mentioned_user_id:xs,mentioned_by_user_id:s.id}));Is.length>0&&await V.from("community_post_mentions").insert(Is)}const Ut=eVs(h);if(Ut.length>0){const Is=Ut.map(xs=>({post_id:rt.id,resource_type:"template",resource_id:xs}));await V.from("community_post_resources").insert(Is)}return rt},onSuccess:async rt=>{var Ft;o.invalidateQueries({queryKey:["community-posts"]}),m(""),Q([]),le([]),g(""),y(""),_([]),C([]),M(""),l({title:"Post created!"});try{const Ut=((Ft=s==null?void 0:s.user_metadata)==null?void 0:Ft.name)||"Someone",Is=h.replace(/@\[([^\]]+)\]\([^)]+\)/g,"@$1"),xs=Is.length>50?Is.substring(0,50)+"...":Is;await V.functions.invoke("send-push-notification",{body:{title:"New Community Post",body:`${Ut}: ${xs}`,url:"/community"}})}catch(Ut){console.error("Failed to send push notification:",Ut)}},onError:rt=>{l({title:"Error creating post",description:rt.message,variant:"destructive"})},onSettled:()=>P(!1)}),Re=Nt({mutationFn:async({postId:rt,content:Ft})=>{const{error:Ut}=await V.from("community_posts").update({content:Ft}).eq("id",rt);if(Ut)throw Ut},onSuccess:()=>{o.invalidateQueries({queryKey:["community-posts"]}),O(null),U(""),l({title:"Post updated!"})}}),ke=Nt({mutationFn:async rt=>{const{error:Ft}=await V.from("community_posts").delete().eq("id",rt);if(Ft)throw Ft},onSuccess:()=>{o.invalidateQueries({queryKey:["community-posts"]}),l({title:"Post deleted"})}}),Fe=Nt({mutationFn:async({postId:rt,isPinned:Ft})=>{const{error:Ut}=await V.from("community_posts").update({is_pinned:!Ft,pinned_at:Ft?null:new Date().toISOString(),pinned_by:Ft?null:s==null?void 0:s.id}).eq("id",rt);if(Ut)throw Ut},onSuccess:(rt,{isPinned:Ft})=>{o.invalidateQueries({queryKey:["community-posts"]}),l({title:Ft?"Post unpinned":"Post pinned to top"})}}),Oe=Nt({mutationFn:async({postId:rt,reactionType:Ft})=>{var Is;const Ut=(Is=Ye.find(xs=>xs.id===rt))==null?void 0:Is.reactions.find(xs=>xs.user_id===(s==null?void 0:s.id));Ut?Ut.reaction_type===Ft?await V.from("community_reactions").delete().eq("id",Ut.id):await V.from("community_reactions").update({reaction_type:Ft}).eq("id",Ut.id):await V.from("community_reactions").insert({post_id:rt,user_id:s.id,reaction_type:Ft})},onSuccess:()=>o.invalidateQueries({queryKey:["community-posts"]})}),Ge=Nt({mutationFn:async({postId:rt,content:Ft})=>{const{data:Ut,error:Is}=await V.from("community_comments").insert({post_id:rt,user_id:s.id,content:Ft}).select("id").single();if(Is)throw Is;const xs=ee[rt]||[];if(xs.length>0&&Ut){const st=xs.filter(dt=>dt!==s.id).map(dt=>({comment_id:Ut.id,mentioned_user_id:dt,mentioned_by_user_id:s.id}));st.length>0&&await V.from("community_comment_mentions").insert(st)}},onSuccess:(rt,{postId:Ft})=>{o.invalidateQueries({queryKey:["community-posts"]}),se(Ut=>({...Ut,[Ft]:""})),oe(Ut=>({...Ut,[Ft]:[]}))}});Nt({mutationFn:async rt=>{const{error:Ft}=await V.from("community_comments").delete().eq("id",rt);if(Ft)throw Ft},onSuccess:()=>o.invalidateQueries({queryKey:["community-posts"]})});const yt=rt=>{const Ft=Array.from(rt.target.files||[]);if(Ft.length+v.length>10){l({title:"Maximum 10 files allowed",variant:"destructive"});return}_(Ut=>[...Ut,...Ft]),Ft.forEach(Ut=>{const Is=new FileReader;Is.onloadend=()=>{C(xs=>[...xs,Is.result])},Is.readAsDataURL(Ut)})},tt=rt=>{_(Ft=>Ft.filter((Ut,Is)=>Is!==rt)),C(Ft=>Ft.filter((Ut,Is)=>Is!==rt))},ut=rt=>rt.split(" ").map(Ft=>Ft[0]).join("").toUpperCase().slice(0,2),nt=rt=>{const Ft={};return rt.forEach(Ut=>{Ft[Ut.reaction_type]=(Ft[Ut.reaction_type]||0)+1}),Ft},et=rt=>{var Ft;return(Ft=rt.find(Ut=>Ut.user_id===(s==null?void 0:s.id)))==null?void 0:Ft.reaction_type},at=rt=>rt.reduce((Ft,Ut)=>Ft+1+(Ut.replies?at(Ut.replies):0),0),wt=rt=>{if(r)return!0;if(!t||!rt.private_group_id)return!1;const Ft=he.find(Ut=>Ut.id===rt.private_group_id);return Ft!=null&&Ft.brokerage_id?n.some(Ut=>Ut.id===Ft.brokerage_id):!1};return e.jsx(Xs,{title:"Community",children:e.jsxs("div",{className:"flex gap-6 w-full isolate z-0",children:[e.jsx(Rqs,{categories:ve,privateGroups:he,selectedFilter:d,onFilterChange:u,onlineUsers:i}),e.jsxs("div",{className:"flex-1 min-w-0 max-w-2xl mx-auto lg:mx-0 space-y-6",children:[e.jsxs("div",{className:"px-1",children:[e.jsx("h1",{className:"text-4xl lg:text-5xl font-bold text-foreground",children:"Community"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Connect and share with fellow agents"})]}),e.jsx(Dqs,{categories:ve,privateGroups:he,selectedFilter:d,onFilterChange:u,onlineUsers:i}),e.jsx(we,{children:e.jsx(De,{className:"pt-6",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsxs(Wa,{className:"h-10 w-10",children:[e.jsx(eo,{src:a||void 0}),e.jsx(Ka,{children:s!=null&&s.email?ut(s.email.split("@")[0]):"U"})]}),e.jsxs("div",{className:"flex-1 space-y-3",children:[e.jsx(y5e,{placeholder:r?"What's on your mind? Use @ to mention someone, # to link a template":"What's on your mind? Use @ to mention someone",value:h,onChange:m,onMentionsChange:Q,onTemplatesChange:le,mentionFormat:"encoded",minHeight:"80px",enableTemplateMentions:r}),j.length>0&&e.jsx("div",{className:"grid grid-cols-3 gap-2",children:j.map((rt,Ft)=>{var Ut;return e.jsxs("div",{className:"relative aspect-square rounded-lg overflow-hidden bg-muted",children:[(Ut=v[Ft])!=null&&Ut.type.startsWith("video/")?e.jsx("video",{src:rt,className:"w-full h-full object-cover"}):e.jsx("img",{src:rt,alt:"",className:"w-full h-full object-cover"}),e.jsx($,{variant:"destructive",size:"icon",className:"absolute top-1 right-1 h-6 w-6",onClick:()=>tt(Ft),children:e.jsx(mr,{className:"h-3 w-3"})})]},Ft)})}),A&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(od,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(be,{value:A,onChange:rt=>M(rt.target.value),placeholder:"https://...",className:"flex-1"}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>M(""),children:e.jsx(mr,{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:yt,accept:"image/*,video/*",multiple:!0,className:"hidden"}),e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>{var rt;return(rt=c.current)==null?void 0:rt.click()},children:[e.jsx(zc,{className:"h-4 w-4 mr-1"}),"Photo"]}),e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>{var rt;return(rt=c.current)==null?void 0:rt.click()},children:[e.jsx(ia,{className:"h-4 w-4 mr-1"}),"Video"]}),e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>M("https://"),children:[e.jsx(od,{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:[he.length>0?e.jsxs(bs,{value:x||p||"none",onValueChange:rt=>{rt==="none"?(g(""),y("")):rt.startsWith("group:")?(y(rt.replace("group:","")),g("")):(g(rt),y(""))},children:[e.jsx(ys,{className:"w-[130px] sm:w-[160px] h-8 text-xs sm:text-sm",children:e.jsx(_s,{placeholder:"Select..."})}),e.jsxs(vs,{children:[e.jsx(We,{value:"none",children:"No category"}),ve.map(rt=>e.jsxs(We,{value:rt.id,children:[rt.icon," ",rt.name]},rt.id)),he.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"}),he.map(rt=>e.jsxs(We,{value:`group:${rt.id}`,children:[rt.icon||"🔒"," ",rt.name]},rt.id))]})]})]}):e.jsxs(bs,{value:p,onValueChange:g,children:[e.jsx(ys,{className:"w-[110px] sm:w-[140px] h-8 text-xs sm:text-sm",children:e.jsx(_s,{placeholder:"Category"})}),e.jsx(vs,{children:ve.map(rt=>e.jsxs(We,{value:rt.id,children:[rt.icon," ",rt.name]},rt.id))})]}),e.jsxs($,{size:"sm",onClick:()=>Ee.mutate(),disabled:!h.trim()||I,children:[e.jsx(Wr,{className:"h-4 w-4 mr-1"}),"Post"]})]})]})]})]})})}),Ie?e.jsx("div",{className:"space-y-4",children:[...Array(3)].map((rt,Ft)=>e.jsx(we,{children:e.jsx(De,{className:"pt-6",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsx(fn,{className:"h-10 w-10 rounded-full"}),e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsx(fn,{className:"h-4 w-32"}),e.jsx(fn,{className:"h-4 w-full"}),e.jsx(fn,{className:"h-4 w-3/4"})]})]})})},Ft))}):Ye.length===0?e.jsx(we,{children:e.jsxs(De,{className:"py-12 text-center",children:[e.jsx(Vu,{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:[Ye.map(rt=>{var Ft,Ut,Is,xs;return e.jsx(we,{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(Wa,{className:"h-10 w-10",children:[e.jsx(eo,{src:rt.user_avatar||void 0}),e.jsx(Ka,{children:ut(rt.user_name||"U")})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-semibold break-words",children:rt.user_name}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-sm text-muted-foreground",children:[e.jsx("span",{children:Zc(new Date(rt.created_at),{addSuffix:!0})}),rt.category&&e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"•"}),e.jsxs(qe,{variant:"secondary",className:"text-xs",children:[rt.category.icon," ",rt.category.name]})]})]})]})]}),(rt.user_id===(s==null?void 0:s.id)||wt(rt))&&e.jsxs(Au,{children:[e.jsx(Eu,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8",children:e.jsx(u0,{className:"h-4 w-4"})})}),e.jsxs(gu,{align:"end",children:[wt(rt)&&rt.private_group_id&&e.jsx(Pa,{onClick:()=>Fe.mutate({postId:rt.id,isPinned:rt.is_pinned}),children:rt.is_pinned?e.jsxs(e.Fragment,{children:[e.jsx(VK,{className:"h-4 w-4 mr-2"}),"Unpin Post"]}):e.jsxs(e.Fragment,{children:[e.jsx(XT,{className:"h-4 w-4 mr-2"}),"Pin to Top"]})}),rt.user_id===(s==null?void 0:s.id)&&e.jsxs(Pa,{onClick:()=>{O(rt),U(rt.content)},children:[e.jsx(ui,{className:"h-4 w-4 mr-2"}),"Edit"]}),e.jsxs(Pa,{className:"text-destructive",onClick:()=>ke.mutate(rt.id),children:[e.jsx(Un,{className:"h-4 w-4 mr-2"}),rt.user_id!==(s==null?void 0:s.id)?"Remove (Moderate)":"Delete"]})]})]})]}),rt.is_pinned&&e.jsxs("div",{className:"flex items-center gap-2 mb-2 text-sm text-primary",children:[e.jsx(XT,{className:"h-4 w-4"}),e.jsx("span",{className:"font-medium",children:"Pinned"})]}),e.jsx("div",{className:"mb-3",children:e.jsx(JKe,{content:rt.content})}),rt.media.length>0&&e.jsx("div",{className:`grid gap-2 mb-3 ${rt.media.length===1?"grid-cols-1":rt.media.length===2?"grid-cols-2":rt.media.length===3?"grid-cols-3":"grid-cols-2"}`,children:rt.media.slice(0,4).map((st,dt)=>{const jt=dt===3&&rt.media.length>4,gt=rt.media.length-4;return e.jsxs("div",{className:`relative rounded-lg overflow-hidden bg-muted cursor-pointer group ${rt.media.length===1?"max-h-[500px]":rt.media.length===2?"aspect-[4/3]":"aspect-square"}`,onClick:()=>_e({open:!0,images:rt.media.map(rs=>({url:rs.media_url,type:rs.media_type==="video"?"video":"image"})),index:dt}),children:[st.media_type==="video"?e.jsx("video",{src:st.media_url,className:"w-full h-full object-cover transition-transform group-hover:scale-105"}):e.jsx("img",{src:st.media_url,alt:"",className:"w-full h-full object-cover transition-transform group-hover:scale-105"}),e.jsx("div",{className:"absolute inset-0 bg-black/0 group-hover:bg-black/20 transition-colors flex items-center justify-center",children:e.jsx("div",{className:"opacity-0 group-hover:opacity-100 transition-opacity text-white",children:e.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",className:"h-8 w-8",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0zM10 7v3m0 0v3m0-3h3m-3 0H7"})})})}),jt&&e.jsx("div",{className:"absolute inset-0 bg-black/60 flex items-center justify-center",children:e.jsxs("span",{className:"text-white text-2xl font-bold",children:["+",gt]})})]},st.id)})}),rt.link_url&&e.jsxs("a",{href:rt.link_url,target:"_blank",rel:"noopener noreferrer",className:"block rounded-lg border hover:bg-muted transition-colors mb-3 overflow-hidden",children:[rt.link_image&&e.jsx("div",{className:"aspect-video bg-muted",children:e.jsx("img",{src:rt.link_image,alt:rt.link_title||"Link preview",className:"w-full h-full object-cover",onError:st=>{st.currentTarget.style.display="none"}})}),e.jsx("div",{className:"p-3",children:rt.link_title?e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"font-medium text-foreground line-clamp-2",children:rt.link_title}),rt.link_description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2 mt-1",children:rt.link_description}),e.jsx("p",{className:"text-xs text-muted-foreground mt-2 truncate",children:new URL(rt.link_url).hostname})]}):e.jsxs("div",{className:"flex items-center gap-2 text-sm text-primary",children:[e.jsx(od,{className:"h-4 w-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:rt.link_url})]})})]}),rt.reactions.length>0&&e.jsx(xRt,{reactions:rt.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(nt(rt.reactions)).slice(0,3).map(([st])=>{var dt;return e.jsx("span",{className:"text-base",children:(dt=Kre.find(jt=>jt.type===st))==null?void 0:dt.emoji},st)})}),e.jsx("span",{children:rt.reactions.length})]})}),e.jsxs("div",{className:"flex items-center gap-1 border-t border-b py-1 my-2",children:[e.jsxs(Xc,{children:[e.jsx(Qc,{asChild:!0,children:e.jsxs($,{variant:"ghost",size:"sm",className:"flex-1",children:[et(rt.reactions)?e.jsx("span",{className:"mr-1",children:(Ft=Kre.find(st=>st.type===et(rt.reactions)))==null?void 0:Ft.emoji}):e.jsx(Ay,{className:"h-4 w-4 mr-1"}),et(rt.reactions)?(Ut=Kre.find(st=>st.type===et(rt.reactions)))==null?void 0:Ut.label:"Like"]})}),e.jsx(Bc,{className:"w-auto p-2",side:"top",children:e.jsx("div",{className:"flex gap-1",children:Kre.map(st=>e.jsx("button",{onClick:()=>Oe.mutate({postId:rt.id,reactionType:st.type}),className:"text-2xl hover:scale-125 transition-transform p-1",title:st.label,children:st.emoji},st.type))})})]}),e.jsxs($,{variant:"ghost",size:"sm",className:"flex-1",onClick:()=>H(st=>{const dt=new Set(st);return dt.has(rt.id)?dt.delete(rt.id):dt.add(rt.id),dt}),children:[e.jsx(Vu,{className:"h-4 w-4 mr-1"}),(()=>{const st=at(rt.comments);return st>0?`Comment (${st})`:"Comment"})()]})]}),G.has(rt.id)&&e.jsxs("div",{className:"space-y-3 mt-3",children:[rt.comments.map(st=>e.jsx(yRt,{comment:st,postId:rt.id,currentUserId:s==null?void 0:s.id,currentUserAvatar:a,currentUserEmail:s==null?void 0:s.email,canModerate:wt(rt)},st.id)),s&&e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(Wa,{className:"h-8 w-8",children:[e.jsx(eo,{src:a||void 0}),e.jsx(Ka,{className:"text-xs",children:ut(((Is=s.email)==null?void 0:Is.split("@")[0])||"U")})]}),e.jsxs("div",{className:"flex-1 flex gap-2",children:[e.jsx(y5e,{placeholder:"Write a comment... (use @ to mention)",value:Y[rt.id]||"",onChange:st=>se(dt=>({...dt,[rt.id]:st})),onMentionsChange:st=>oe(dt=>({...dt,[rt.id]:st})),mentionFormat:"plain",onKeyDown:st=>{var dt;st.defaultPrevented||st.key==="Enter"&&!st.shiftKey&&((dt=Y[rt.id])!=null&&dt.trim())&&(st.preventDefault(),Ge.mutate({postId:rt.id,content:Y[rt.id]}))},className:"text-sm min-h-0 py-1.5",minHeight:"32px"}),e.jsx($,{size:"sm",variant:"ghost",onClick:()=>{var st;(st=Y[rt.id])!=null&&st.trim()&&Ge.mutate({postId:rt.id,content:Y[rt.id]})},disabled:!((xs=Y[rt.id])!=null&&xs.trim()),className:"h-8 px-2 mt-0.5",children:e.jsx(Wr,{className:"h-4 w-4"})})]})]})]})]})},rt.id)}),Ue&&e.jsx("div",{className:"flex justify-center pt-2",children:e.jsx($,{variant:"outline",onClick:()=>Be(),disabled:je,children:je?"Loading…":"Load more posts"})})]}),e.jsx(zs,{open:!!R,onOpenChange:()=>O(null),children:e.jsxs(Rs,{children:[e.jsx(Vs,{children:e.jsx($s,{children:"Edit Post"})}),e.jsx(Ls,{value:B,onChange:rt=>U(rt.target.value),className:"min-h-[120px]"}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx($,{variant:"outline",onClick:()=>O(null),children:"Cancel"}),e.jsx($,{onClick:()=>{R&&Re.mutate({postId:R.id,content:B})},disabled:!B.trim(),children:"Save Changes"})]})]})}),e.jsx(Qqs,{images:fe.images,initialIndex:fe.index,open:fe.open,onOpenChange:rt=>_e(Ft=>({...Ft,open:rt}))})]})]})})},sVs=50*1024*1024;function vRt({value:s,onChange:t,disabled:n}){const{user:r}=ks(),a=k.useRef(null),[i,l]=k.useState(!1),o=async d=>{if(!d||!r)return;const u=[];l(!0);try{for(const h of Array.from(d)){if(!h.type.startsWith("image/")&&!h.type.startsWith("video/")){ae.error(`${h.name}: only images and videos allowed`);continue}if(h.size>sVs){ae.error(`${h.name}: must be under 50MB`);continue}const m=h.name.split(".").pop()||"bin",p=`${r.id}/${Date.now()}-${Math.random().toString(36).slice(2,8)}.${m}`,{error:g}=await V.storage.from("support-attachments").upload(p,h,{contentType:h.type,upsert:!1});if(g){ae.error(`${h.name}: ${g.message}`);continue}u.push({path:p,type:h.type,name:h.name,size:h.size})}u.length&&t([...s,...u])}finally{l(!1),a.current&&(a.current.value="")}},c=async d=>{const u=s[d];t(s.filter((h,m)=>m!==d)),await V.storage.from("support-attachments").remove([u.path])};return e.jsxs("div",{className:"space-y-2",children:[s.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2",children:s.map((d,u)=>e.jsxs("div",{className:"flex items-center gap-2 px-2 py-1 rounded-md border bg-muted/40 text-xs",children:[d.type.startsWith("video/")?e.jsx(TK,{className:"h-3.5 w-3.5 text-muted-foreground"}):e.jsx(UT,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"max-w-[160px] truncate",children:d.name}),e.jsx("button",{type:"button",onClick:()=>c(u),className:"text-muted-foreground hover:text-foreground",children:e.jsx(mr,{className:"h-3 w-3"})})]},d.path))}),e.jsxs($,{type:"button",variant:"outline",size:"sm",onClick:()=>{var d;return(d=a.current)==null?void 0:d.click()},disabled:n||i,className:"gap-1.5",children:[i?e.jsx(Jt,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(KT,{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 bRt({attachments:s}){const[t,n]=k.useState({}),[r,a]=k.useState(!0);return k.useEffect(()=>{if(!(s!=null&&s.length)){a(!1);return}let i=!1;return(async()=>{const l=s.map(d=>d.path),{data:o}=await V.storage.from("support-attachments").createSignedUrls(l,60*60*24);if(i||!o)return;const c={};o.forEach((d,u)=>{d.signedUrl&&(c[l[u]]=d.signedUrl)}),n(c),a(!1)})(),()=>{i=!0}},[s]),s!=null&&s.length?r?e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground mt-2",children:[e.jsx(Jt,{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 s9={open:{label:"Open",icon:sa,color:"bg-yellow-500"},in_progress:{label:"In Progress",icon:Vu,color:"bg-blue-500"},resolved:{label:"Resolved",icon:nl,color:"bg-green-500"},closed:{label:"Closed",icon:ju,color:"bg-muted-foreground"}},Kht={general:"General Support",technology:"Technology Support",crm:"CRM Support",marketing:"Marketing Support"};function nVs(){const{user:s}=ks(),t=ls(),[n,r]=k.useState(null),[a,i]=k.useState(""),[l,o]=k.useState([]),{data:c=[],isLoading:d}=pt({queryKey:["support-tickets"],queryFn:async()=>{const{data:p,error:g}=await V.from("support_tickets").select("*").eq("user_id",s==null?void 0:s.id).order("created_at",{ascending:!1});if(g)throw g;return p},enabled:!!s}),{data:u=[]}=pt({queryKey:["ticket-replies",n==null?void 0:n.id],queryFn:async()=>{if(!n)return[];const{data:p,error:g}=await V.from("support_ticket_replies").select("*, profiles(name)").eq("ticket_id",n.id).order("created_at",{ascending:!0});if(g)throw g;return p},enabled:!!n}),h=Nt({mutationFn:async({content:p,attachments:g})=>{if(!n||!s)throw new Error("Missing data");const{error:x}=await V.from("support_ticket_replies").insert({ticket_id:n.id,user_id:s.id,content:p,is_admin_reply:!1,attachments:g});if(x)throw x},onSuccess:()=>{t.invalidateQueries({queryKey:["ticket-replies",n==null?void 0:n.id]}),i(""),o([]),ae.success("Reply sent!")},onError:()=>{ae.error("Failed to send reply")}}),m=()=>{!a.trim()&&l.length===0||h.mutate({content:a,attachments:l})};if(n){const p=s9[n.status].icon;return e.jsx(Xs,{children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx($,{variant:"ghost",size:"icon",onClick:()=>r(null),children:e.jsx(Ia,{className:"h-5 w-5"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h1",{className:"text-2xl font-bold",children:n.subject}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(qe,{variant:"secondary",children:Kht[n.category]}),e.jsxs(qe,{className:s9[n.status].color,children:[e.jsx(p,{className:"h-3 w-3 mr-1"}),s9[n.status].label]})]})]})]}),e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsxs(vr,{children:["Created on ",Ys(new Date(n.created_at),"MMM d, yyyy 'at' h:mm a")]})}),e.jsx(De,{children:e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:n.description})})]}),e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsx(Yt,{className:"text-lg",children:"Conversation"})}),e.jsxs(De,{children:[e.jsx(Eo,{className:"h-[300px] pr-4",children:u.length===0?e.jsx("p",{className:"text-muted-foreground text-center py-8",children:"No replies yet"}):e.jsx("div",{className:"space-y-4",children:u.map(g=>{var x;return e.jsxs("div",{className:`p-4 rounded-lg ${g.is_admin_reply?"bg-primary/10 ml-4":"bg-muted mr-4"}`,children:[e.jsxs("div",{className:"flex justify-between items-start mb-2",children:[e.jsx("span",{className:"font-medium text-sm",children:g.is_admin_reply?"Support Team":((x=g.profiles)==null?void 0:x.name)||"You"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:Ys(new Date(g.created_at),"MMM d, h:mm a")})]}),e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:g.content}),g.attachments&&g.attachments.length>0&&e.jsx(bRt,{attachments:g.attachments})]},g.id)})})}),n.status!=="closed"&&e.jsxs(e.Fragment,{children:[e.jsx(Pc,{className:"my-4"}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ls,{placeholder:"Type your reply...",value:a,onChange:g=>i(g.target.value),className:"min-h-[80px]"}),e.jsx($,{onClick:m,disabled:!a.trim()&&l.length===0||h.isPending,className:"self-end",children:e.jsx(Wr,{className:"h-4 w-4"})})]}),e.jsx(vRt,{value:l,onChange:o,disabled:h.isPending})]})]})]})]})]})})}return e.jsx(Xs,{children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(we,{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(_C,{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(m7e,{trigger:e.jsxs($,{size:"lg",className:"gap-2",children:[e.jsx(nn,{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(ka,{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(m7e,{trigger:e.jsxs($,{variant:"outline",size:"sm",className:"gap-2",children:[e.jsx(nn,{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(we,{className:"border-dashed",children:e.jsxs(De,{className:"text-center py-12",children:[e.jsx(Vu,{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(p=>{const g=s9[p.status].icon;return e.jsx(we,{className:"cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>r(p),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:p.subject}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(qe,{variant:"outline",className:"text-xs",children:Kht[p.category]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:Ys(new Date(p.created_at),"MMM d, yyyy")})]})]}),e.jsxs(qe,{className:s9[p.status].color,children:[e.jsx(g,{className:"h-3 w-3 mr-1"}),s9[p.status].label]})]})})},p.id)})})]})})}function rVs({open:s,onOpenChange:t}){return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"max-w-3xl max-h-[90vh] overflow-hidden",children:[e.jsx(Vs,{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(ha,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx($s,{children:"Schedule Agent Onboarding"}),e.jsx(Cr,{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 aVs({open:s,onOpenChange:t}){const{brokerageId:n}=ks(),[r,a]=k.useState(""),[i,l]=k.useState([]),[o,c]=k.useState(!1),{data:d,isLoading:u}=pt({queryKey:["brokerage-agents-for-onboarding",n],queryFn:async()=>{if(!n)return[];const{data:x,error:y}=await V.from("profiles").select("id, name, email").eq("brokerage_id",n).order("name",{ascending:!0});if(y)throw y;return x},enabled:s&&!!n}),h=d==null?void 0:d.filter(x=>x.name.toLowerCase().includes(r.toLowerCase())||x.email.toLowerCase().includes(r.toLowerCase())),m=x=>{l(y=>y.includes(x)?y.filter(v=>v!==x):[...y,x])},p=async()=>{if(i.length===0){ae.error("Please select at least one agent");return}c(!0);try{const{data:x,error:y}=await V.functions.invoke("send-onboarding-link",{body:{agentIds:i}});if(y)throw y;ae.success(`Onboarding link sent to ${i.length} agent${i.length>1?"s":""}`),l([]),t(!1)}catch(x){console.error("Error sending onboarding link:",x),ae.error(x.message||"Failed to send onboarding link")}finally{c(!1)}},g=x=>{x||(l([]),a("")),t(x)};return e.jsx(zs,{open:s,onOpenChange:g,children:e.jsxs(Rs,{className:"max-w-md",children:[e.jsx(Vs,{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(Wr,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx($s,{children:"Send Onboarding Link"}),e.jsx(Cr,{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(Yr,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search agents...",value:r,onChange:x=>a(x.target.value),className:"pl-10"})]}),u?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(Jt,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):(h==null?void 0:h.length)===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Xn,{className:"h-8 w-8 mx-auto mb-2 opacity-50"}),e.jsx("p",{children:"No agents found"})]}):e.jsx(Eo,{className:"h-[300px] border rounded-lg",children:e.jsx("div",{className:"p-2 space-y-1",children:h==null?void 0:h.map(x=>e.jsxs("div",{className:"flex items-center gap-3 p-2 rounded-lg hover:bg-muted cursor-pointer",onClick:()=>m(x.id),children:[e.jsx(Li,{checked:i.includes(x.id),onCheckedChange:()=>m(x.id)}),e.jsx(Wa,{className:"h-8 w-8",children:e.jsx(Ka,{className:"text-xs",children:x.name.split(" ").map(y=>y[0]).join("").toUpperCase()})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:x.name}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:x.email})]})]},x.id))})}),i.length>0&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:[i.length," agent",i.length>1?"s":""," selected"]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>g(!1),children:"Cancel"}),e.jsx($,{onClick:p,disabled:i.length===0||o,children:o?e.jsxs(e.Fragment,{children:[e.jsx(Jt,{className:"h-4 w-4 mr-2 animate-spin"}),"Sending..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Wr,{className:"h-4 w-4 mr-2"}),"Send Link"]})})]})]})})}function iVs(){const[s,t]=k.useState(!1),[n,r]=k.useState(!1);return e.jsxs(e.Fragment,{children:[e.jsxs(we,{className:"mb-8",children:[e.jsx(Vt,{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(Xn,{className:"h-6 w-6 text-primary"})}),e.jsxs("div",{children:[e.jsx(Yt,{children:"Agent Onboarding"}),e.jsx(vr,{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($,{onClick:()=>t(!0),className:"flex items-center gap-2",children:[e.jsx(ha,{className:"h-4 w-4"}),"Schedule Agent Onboarding"]}),e.jsxs($,{variant:"outline",onClick:()=>r(!0),className:"flex items-center gap-2",children:[e.jsx(Wr,{className:"h-4 w-4"}),"Send New Agent Onboarding Link"]})]})})]}),e.jsx(rVs,{open:s,onOpenChange:t}),e.jsx(aVs,{open:n,onOpenChange:r})]})}function oVs({open:s,onOpenChange:t}){return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"max-w-3xl max-h-[90vh] overflow-hidden",children:[e.jsx(Vs,{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(v0,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx($s,{children:"Schedule Launch Meeting"}),e.jsx(Cr,{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 lVs(){const[s,t]=k.useState(!1);return e.jsxs(e.Fragment,{children:[e.jsxs(we,{className:"mb-8",children:[e.jsx(Vt,{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(v0,{className:"h-6 w-6 text-primary"})}),e.jsxs("div",{children:[e.jsx(Yt,{children:"Launch or ReLaunch Meeting"}),e.jsx(vr,{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($,{onClick:()=>t(!0),className:"flex items-center gap-2",children:[e.jsx(v0,{className:"h-4 w-4"}),"Schedule Launch Meeting"]})})]}),e.jsx(oVs,{open:s,onOpenChange:t})]})}function cVs(){const s=Jn(),[t,n]=k.useState(""),[r,a]=k.useState(null),{data:i,isLoading:l}=pt({queryKey:["brokerage-resources-published"],queryFn:async()=>{const{data:x,error:y}=await V.from("brokerage_resources").select("*").eq("is_published",!0).order("publish_date",{ascending:!1});if(y)throw y;return x}}),{data:o}=pt({queryKey:["brokerage-resource-categories"],queryFn:async()=>{const{data:x,error:y}=await V.from("brokerage_resource_categories").select("*").order("sort_order",{ascending:!0});if(y)throw y;return x}}),{data:c}=pt({queryKey:["brokerage-resource-pdfs-all"],queryFn:async()=>{const{data:x,error:y}=await V.from("brokerage_resource_pdfs").select("resource_id");if(y)throw y;return x}}),{data:d}=pt({queryKey:["brokerage-resource-videos-all"],queryFn:async()=>{const{data:x,error:y}=await V.from("brokerage_resource_videos").select("resource_id");if(y)throw y;return x}}),{data:u}=pt({queryKey:["brokerage-resource-links-all"],queryFn:async()=>{const{data:x,error:y}=await V.from("brokerage_resource_links").select("resource_id");if(y)throw y;return x}}),h=i==null?void 0:i.filter(x=>{var _;const y=x.title.toLowerCase().includes(t.toLowerCase())||((_=x.description)==null?void 0:_.toLowerCase().includes(t.toLowerCase())),v=!r||x.category_id===r;return y&&v}),m=o==null?void 0:o.filter(x=>i==null?void 0:i.some(y=>y.category_id===x.id)),p=x=>{const y=(c==null?void 0:c.filter(j=>j.resource_id===x).length)||0,v=(d==null?void 0:d.filter(j=>j.resource_id===x).length)||0,_=(u==null?void 0:u.filter(j=>j.resource_id===x).length)||0;return{pdfCount:y,videoCount:v,linkCount:_}},g=x=>{s(`/brokerage-resources/${x}`)};return e.jsx(Xs,{title:"Brokerage Resources",description:"Access exclusive resources for brokerage managers",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(iVs,{}),e.jsx(lVs,{}),e.jsxs("div",{className:"relative max-w-md",children:[e.jsx(Yr,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search resources...",value:t,onChange:x=>n(x.target.value),className:"pl-10"})]}),m&&m.length>0&&e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(qe,{variant:r===null?"default":"outline",className:"cursor-pointer",onClick:()=>a(null),children:"All"}),m.map(x=>e.jsx(qe,{variant:r===x.id?"default":"outline",className:"cursor-pointer",onClick:()=>a(x.id),children:x.name},x.id))]}),!l&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:[(h==null?void 0:h.length)||0," resource",(h==null?void 0:h.length)!==1?"s":""," available"]}),l?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6",children:[...Array(6)].map((x,y)=>e.jsxs(we,{children:[e.jsx(fn,{className:"h-40 w-full"}),e.jsx(Vt,{children:e.jsx(fn,{className:"h-5 w-3/4"})}),e.jsxs(De,{children:[e.jsx(fn,{className:"h-4 w-full mb-2"}),e.jsx(fn,{className:"h-4 w-2/3"})]})]},y))}):(h==null?void 0:h.length)===0?e.jsxs(we,{className:"p-12 text-center",children:[e.jsx(zx,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-medium mb-2",children:"No resources found"}),e.jsx("p",{className:"text-muted-foreground",children:t||r?"Try adjusting your filters":"Check back later for new resources"})]}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6",children:h==null?void 0:h.map(x=>{const{pdfCount:y,videoCount:v,linkCount:_}=p(x.id),j=o==null?void 0:o.find(C=>C.id===x.category_id);return e.jsxs(we,{className:"overflow-hidden cursor-pointer hover:shadow-lg transition-shadow",onClick:()=>g(x.id),children:[x.preview_image_url?e.jsx("img",{src:x.preview_image_url,alt:x.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(zx,{className:"h-16 w-16 text-muted-foreground"})}),e.jsx(Vt,{className:"pb-2",children:e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsx(Yt,{className:"text-lg line-clamp-1",children:x.title}),j&&e.jsx(qe,{variant:"secondary",className:"shrink-0 text-xs",children:j.name})]})}),e.jsxs(De,{children:[x.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2 mb-3",children:x.description}),e.jsxs("div",{className:"flex items-center gap-4 text-sm text-muted-foreground",children:[y>0&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ea,{className:"h-4 w-4"}),y]}),v>0&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ia,{className:"h-4 w-4"}),v]}),_>0&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(od,{className:"h-4 w-4"}),_]})]})]})]},x.id)})})]})})}const dVs=()=>{const{resourceId:s}=oo(),{data:t,isLoading:n}=pt({queryKey:["brokerage-resource-detail",s],queryFn:async()=>{const{data:a,error:i}=await V.from("brokerage_resources").select("*").eq("id",s).eq("is_published",!0).single();if(i)throw i;const{data:l}=await V.from("brokerage_resource_pdfs").select("*").eq("resource_id",s).order("sort_order"),{data:o}=await V.from("brokerage_resource_videos").select("*").eq("resource_id",s).order("sort_order"),{data:c}=await V.from("brokerage_resource_links").select("*").eq("resource_id",s).order("sort_order");return{...a,pdfs:l||[],videos:o||[],links:c||[]}},enabled:!!s}),r=a=>a?a<1024?a+" B":a<1024*1024?(a/1024).toFixed(1)+" KB":(a/(1024*1024)).toFixed(1)+" MB":"";return n?e.jsx(Xs,{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(Xs,{title:t.title,children:e.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[e.jsx($,{variant:"ghost",size:"sm",asChild:!0,className:"gap-2",children:e.jsxs(nr,{to:"/brokerage-resources",children:[e.jsx(Ia,{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(we,{children:e.jsxs(De,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(ia,{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(we,{children:e.jsxs(De,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(ea,{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(ea,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-sm",children:a.name}),a.file_size&&e.jsx("div",{className:"text-xs text-muted-foreground",children:r(a.file_size)})]})]}),e.jsx(ji,{className:"h-4 w-4 text-muted-foreground group-hover:text-primary transition-colors"})]},a.id))})]})}),t.links&&t.links.length>0&&e.jsx(we,{children:e.jsxs(De,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(Ir,{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(Ir,{className:"h-4 w-4 text-primary"})}),e.jsx("div",{className:"font-medium text-sm",children:a.title})]}),e.jsx(Ir,{className:"h-4 w-4 text-muted-foreground group-hover:text-primary transition-colors"})]},a.id))})]})})]})}):e.jsx(Xs,{title:"Brokerage Resources",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(zx,{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($,{asChild:!0,className:"mt-4",children:e.jsx(nr,{to:"/brokerage-resources",children:"Back to Resources"})})]})})};function uVs(){const{onlineUsers:s,totalOnline:t}=S4t(),{user:n}=ks();return e.jsxs(we,{children:[e.jsx(Vt,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(Yt,{className:"text-base flex items-center gap-2",children:[e.jsx(Xn,{className:"h-4 w-4"}),"Online Now"]}),e.jsxs(qe,{variant:"secondary",className:"bg-green-100 text-green-700",children:[e.jsx(rx,{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 users online right now"}):e.jsx(Eo,{className:"h-[300px] pr-4",children:e.jsx("div",{className:"space-y-3",children:s.map(r=>{var a;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(Wa,{className:"h-9 w-9",children:[e.jsx(eo,{src:r.avatarUrl,alt:r.name}),e.jsx(Ka,{className:"text-xs",children:(a=r.name)==null?void 0:a.split(" ").map(i=>i[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.jsxs("p",{className:"text-sm font-medium truncate",children:[r.name,r.id===(n==null?void 0:n.id)?" (You)":""]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Online ",Zc(new Date(r.onlineSince),{addSuffix:!1})]})]})]},r.id)})})})})]})}const Yht={users:{label:"Users & Access",sections:[{title:"Member Broadcasts",description:"Email a filtered group of members (paste HTML or write it)",icon:xm,path:"/admin/broadcasts",color:"bg-rose-500/10 text-rose-600"},{title:"Members",description:"Manage users, roles, and brokerage assignments",icon:Xn,path:"/admin/members",color:"bg-blue-500/10 text-blue-600"},{title:"Partnerships",description:"Manage partnership packages, rosters, and upgrade requests",icon:Zo,path:"/admin/partnerships",color:"bg-indigo-500/10 text-indigo-600"},{title:"Invite Codes",description:"Create and manage signup invite codes",icon:X8,path:"/admin/invite-codes",color:"bg-amber-500/10 text-amber-600"},{title:"Subscriptions",description:"Track and manage user subscriptions",icon:cv,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:SK,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:kg,path:"/admin/discounts",color:"bg-red-500/10 text-red-600"},{title:"Referral Program",description:"Track brokerage referrals and discounts",icon:ou,path:"/admin/referrals",color:"bg-teal-500/10 text-teal-600"},{title:"Teams",description:"Manage agent teams across all brokerages",icon:Xn,path:"/admin/members?tab=teams",color:"bg-violet-500/10 text-violet-600"},{title:"Prospector",description:"Send free trial invites and track conversions",icon:_h,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:Pl,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:ql,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:gd,path:"/admin/templates",color:"bg-pink-500/10 text-pink-600"},{title:"Manage Programs",description:"Cohorts, enrollments and delayed billing",icon:Bm,path:"/admin/programs",color:"bg-emerald-500/10 text-emerald-600"},{title:"Manage Academy",description:"Upload videos and training content",icon:Bm,path:"/admin/academy",color:"bg-indigo-500/10 text-indigo-600"},{title:"Manage Toolbox",description:"Create and manage resource kits",icon:L5,path:"/admin/toolbox",color:"bg-orange-500/10 text-orange-600"},{title:"Social Swag",description:"Manage social media content and links",icon:kn,path:"/admin/social-swag",color:"bg-fuchsia-500/10 text-fuchsia-600"},{title:"Social Swag 2.0",description:"New monthly social media images",icon:kn,path:"/admin/social-swag-2",color:"bg-cyan-500/10 text-cyan-600"},{title:"Newsletters",description:"Manage monthly newsletter templates",icon:N2,path:"/admin/newsletters",color:"bg-violet-500/10 text-violet-600"},{title:"Newsletter Graphics",description:"Upload branded graphics agents drop into newsletters & emails",icon:N2,path:"/admin/newsletter-graphics",color:"bg-fuchsia-500/10 text-fuchsia-600"},{title:"Manage Events",description:"Create and publish events with Zoom integration",icon:fd,path:"/admin/events",color:"bg-green-500/10 text-green-600"},{title:"LevelUp Live",description:"Public streaming pages, invite links, and live leads",icon:Cy,path:"/admin/live",color:"bg-red-500/10 text-red-600"},{title:"Additional Services",description:"Manage additional service offerings",icon:zx,path:"/admin/additional-services",color:"bg-lime-500/10 text-lime-600"},{title:"Brokerage Resources",description:"Manage resources for brokerage managers",icon:zx,path:"/admin/brokerage-resources",color:"bg-slate-500/10 text-slate-600"},{title:"Agent Email Templates",description:"Manage curated email templates for agents",icon:pn,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:xm,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:$8,path:"/admin/dashboard-management",color:"bg-teal-500/10 text-teal-600"},{title:"Manage Apps",description:"Configure app tiles and access requirements",icon:Tw,path:"/admin/apps",color:"bg-purple-500/10 text-purple-600"},{title:"Email Templates",description:"Customize system email templates",icon:pn,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:xm,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:A5,path:"/admin/onboarding-checklist",color:"bg-emerald-500/10 text-emerald-600"},{title:"Marketplace",description:"Manage store categories, products, and orders",icon:I5,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:Zo,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:ql,path:"/admin/agent-points",color:"bg-amber-500/10 text-amber-600"},{title:"Integrations",description:"Connect Canva, Facebook & Instagram for platform-level features",icon:pd,path:"/admin/integrations",color:"bg-blue-500/10 text-blue-600"},{title:"Agent Cards",description:"Manage digital business cards for agents",icon:Xn,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:xm,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:bo,path:"/admin/community",color:"bg-cyan-500/10 text-cyan-600"},{title:"Support Tickets",description:"View and respond to agent support requests",icon:Kz,path:"/admin/support-tickets",color:"bg-rose-500/10 text-rose-600"},{title:"Wishlist",description:"Review and manage community feature requests",icon:P5,path:"/admin/wishlist",color:"bg-yellow-500/10 text-yellow-600"},{title:"Membership Reviews",description:"View member feedback and ratings",icon:ri,path:"/admin/membership-reviews",color:"bg-amber-500/10 text-amber-600"},{title:"Weekly Digest",description:"Configure automated weekly email digests",icon:pn,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:Ul,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:wg,path:"/admin/brokerage-content-activity",color:"bg-sky-500/10 text-sky-600"},{title:"Music Videos",description:"View all listing music videos created by agents across the platform",icon:hv,path:"/admin/music-videos",color:"bg-gradient-to-br from-pink-500/20 to-rose-500/10 text-pink-600"}]},lms:{label:"LevelUp U",sections:[{title:"Manage Courses",description:"Create and manage LMS training courses, modules, and access",icon:Bm,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:Bo,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:ua,path:"/admin/listing-exchange",color:"bg-gradient-to-br from-blue-500/20 to-sky-500/10 text-blue-600"},{title:"Listing Leads",description:"View all leads from the public listings site with property & agent assignment",icon:Pl,path:"/admin/listing-leads",color:"bg-gradient-to-br from-teal-500/20 to-emerald-500/10 text-teal-600"},{title:"Public Site Leads",description:"Alerts signups, exit-intent captures & saved-home leads from listings.relevelup.com",icon:Pl,path:"/admin/public-site-leads",color:"bg-gradient-to-br from-amber-500/20 to-orange-500/10 text-amber-600"},{title:"Presentation Analytics",description:"Track agent presentation usage, views, and leads",icon:hv,path:"/admin/presentation-analytics",color:"bg-gradient-to-br from-violet-500/20 to-indigo-500/10 text-violet-600"},{title:"Listing Presentation Studio",description:"Track every listing presentation agents build, generate, and send",icon:ea,path:"/admin/listing-presentation-studio",color:"bg-gradient-to-br from-slate-500/20 to-zinc-500/10 text-slate-600"},{title:"Listing Revival",description:"Track expired-listing campaigns, seller leads, and manage who has access",icon:kn,path:"/admin/listing-revival",color:"bg-gradient-to-br from-amber-500/20 to-yellow-500/10 text-amber-600"},{title:"Weekly Reels",description:"Manage Weekly Reels access, generation runs, and email delivery",icon:em,path:"/admin/weekly-reels",color:"bg-gradient-to-br from-pink-500/20 to-rose-500/10 text-pink-600"},{title:"Guest Book Analytics",description:"Track open house sign-in usage, visitors, and lead generation",icon:wg,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:zc,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:pn,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:qT,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:kc,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:CK,path:"/admin/mls-feeds",color:"bg-gradient-to-br from-emerald-500/20 to-green-500/10 text-emerald-600"},{title:"Free Website Offers",description:"Choose which brokerages get a free luxury website, and set their default template",icon:Zo,path:"/admin/lead-sites/offers",color:"bg-gradient-to-br from-violet-500/20 to-purple-500/10 text-violet-600"},{title:"Lead Analytics",description:"Cross-site lead capture stats, conversions, and top-performing sites",icon:mc,path:"/admin/lead-site-analytics",color:"bg-gradient-to-br from-amber-500/20 to-orange-500/10 text-amber-600"},{title:"Beta Website Requests",description:"Member requests for free beta (non-IDX) agent websites — review, build and launch",icon:ea,path:"/admin/website-requests",color:"bg-gradient-to-br from-sky-500/20 to-blue-500/10 text-sky-600"},{title:"Website Interests",description:"Track interest form submissions from TheLocalMove.com",icon:ea,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:ea,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:Su,path:"/admin/mls-fee-tracker",color:"bg-gradient-to-br from-teal-500/20 to-cyan-500/10 text-teal-600"}]}};function Zht(){const s=Jn();return console.log("[AdminDashboard] render"),e.jsx(Xs,{title:"Admin Dashboard",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{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.jsxs(ya,{defaultValue:"users",className:"w-full",children:[e.jsx(va,{className:"w-full justify-start flex-wrap h-auto gap-1 bg-muted/50 p-1 overflow-x-auto",children:Object.entries(Yht).map(([t,n])=>e.jsx(is,{value:t,className:"data-[state=active]:bg-background",children:n.label},t))}),Object.entries(Yht).map(([t,n])=>e.jsx(cs,{value:t,className:"mt-6",children:e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4",children:n.sections.map(r=>e.jsxs(we,{className:"cursor-pointer hover:shadow-md transition-all hover:border-primary/50 group",onClick:()=>s(r.path),children:[e.jsxs(Vt,{className:"pb-3",children:[e.jsx("div",{className:`w-10 h-10 rounded-lg flex items-center justify-center ${r.color} mb-2 group-hover:scale-110 transition-transform`,children:e.jsx(r.icon,{className:"h-5 w-5"})}),e.jsx(Yt,{className:"text-base",children:r.title})]}),e.jsx(De,{className:"pt-0",children:e.jsx(vr,{className:"text-sm",children:r.description})})]},r.path))})},t))]}),e.jsx(uVs,{})]})})}const hVs=()=>{const{isAdmin:s}=ks(),t=Jn(),[n,r]=k.useState([]),[a,i]=k.useState(!0),[l,o]=k.useState(!1),[c,d]=k.useState(null);k.useEffect(()=>{if(!s){t("/dashboard");return}u()},[s]);const u=async()=>{try{const{data:x,error:y}=await V.from("app_tiles").select("*").order("name");if(y)throw y;r(x||[])}catch(x){console.error("Error loading apps:",x),ae.error("Failed to load apps")}finally{i(!1)}},h=async x=>{x.preventDefault();const y=new FormData(x.currentTarget),v={name:y.get("name"),description:y.get("description"),icon:y.get("icon"),app_id:y.get("app_id"),target_url:y.get("target_url"),required_tags:y.get("required_tags").split(",").map(_=>_.trim()).filter(Boolean)};try{if(c){const{error:_}=await V.from("app_tiles").update(v).eq("id",c.id);if(_)throw _;ae.success("App updated successfully")}else{const{error:_}=await V.from("app_tiles").insert([v]);if(_)throw _;ae.success("App created successfully")}o(!1),d(null),u()}catch(_){console.error("Error saving app:",_),ae.error("Failed to save app")}},m=async x=>{if(await io("Are you sure you want to delete this app?"))try{const{error:y}=await V.from("app_tiles").delete().eq("id",x);if(y)throw y;ae.success("App deleted successfully"),u()}catch(y){console.error("Error deleting app:",y),ae.error("Failed to delete app")}},p=x=>{d(x),o(!0)},g=()=>{d(null),o(!0)};return a?e.jsx("div",{className:"flex items-center justify-center min-h-screen",children:"Loading..."}):e.jsxs("div",{className:"min-h-screen bg-background",children:[e.jsx("header",{className:"border-b bg-card",children:e.jsx("div",{className:"container mx-auto px-4 py-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>t("/dashboard"),children:[e.jsx(Ia,{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(zs,{open:l,onOpenChange:o,children:[e.jsx(yl,{asChild:!0,children:e.jsxs($,{onClick:g,children:[e.jsx(nn,{className:"mr-2 h-4 w-4"}),"Add App"]})}),e.jsxs(Rs,{className:"max-w-2xl",children:[e.jsxs(Vs,{children:[e.jsx($s,{children:c?"Edit App":"Create New App"}),e.jsx(Cr,{children:"Configure the application tile settings"})]}),e.jsxs("form",{onSubmit:h,className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"name",children:"App Name"}),e.jsx(be,{id:"name",name:"name",defaultValue:c==null?void 0:c.name,required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"app_id",children:"App ID"}),e.jsx(be,{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(re,{htmlFor:"description",children:"Description"}),e.jsx(Ls,{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(re,{htmlFor:"icon",children:"Icon (emoji)"}),e.jsx(be,{id:"icon",name:"icon",defaultValue:c==null?void 0:c.icon,placeholder:"🚀",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"target_url",children:"Target URL"}),e.jsx(be,{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(re,{htmlFor:"required_tags",children:"Required Tags (comma-separated)"}),e.jsx(be,{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($,{type:"button",variant:"outline",onClick:()=>o(!1),children:"Cancel"}),e.jsx($,{type:"submit",children:c?"Update":"Create"})]})]})]})]})]})})}),e.jsx("div",{className:"container mx-auto px-4 py-8",children:e.jsxs(we,{children:[e.jsxs(Vt,{children:[e.jsx(Yt,{children:"Application Tiles"}),e.jsx(vr,{children:"Manage the apps that appear on the member dashboard"})]}),e.jsx(De,{children:n.length===0?e.jsxs("div",{className:"text-center py-12",children:[e.jsx("p",{className:"text-muted-foreground mb-4",children:"No apps configured yet"}),e.jsxs($,{onClick:g,children:[e.jsx(nn,{className:"mr-2 h-4 w-4"}),"Create First App"]})]}):e.jsxs(Qa,{children:[e.jsx(Ja,{children:e.jsxs(vn,{children:[e.jsx(Dt,{children:"Icon"}),e.jsx(Dt,{children:"Name"}),e.jsx(Dt,{children:"App ID"}),e.jsx(Dt,{children:"Target URL"}),e.jsx(Dt,{children:"Tags"}),e.jsx(Dt,{className:"text-right",children:"Actions"})]})}),e.jsx(ei,{children:n.map(x=>e.jsxs(vn,{children:[e.jsx(_t,{className:"text-2xl",children:x.icon}),e.jsx(_t,{className:"font-medium",children:x.name}),e.jsx(_t,{className:"font-mono text-sm",children:x.app_id}),e.jsx(_t,{className:"text-sm text-muted-foreground max-w-xs truncate",children:x.target_url}),e.jsx(_t,{children:e.jsx("div",{className:"flex flex-wrap gap-1",children:x.required_tags.map(y=>e.jsx("span",{className:"text-xs bg-secondary text-secondary-foreground px-2 py-1 rounded",children:y},y))})}),e.jsx(_t,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx($,{size:"sm",variant:"ghost",onClick:()=>p(x),children:e.jsx(ui,{className:"h-4 w-4"})}),e.jsx($,{size:"sm",variant:"ghost",onClick:()=>m(x.id),children:e.jsx(Un,{className:"h-4 w-4"})})]})})]},x.id))})]})})]})})]})};function nm({title:s,description:t,children:n}){return e.jsxs("div",{className:"space-y-4",children:[e.jsx(nr,{to:"/admin",children:e.jsxs($,{variant:"ghost",size:"sm",className:"gap-2 text-muted-foreground hover:text-foreground",children:[e.jsx(Ia,{className:"h-4 w-4"}),"Back to Admin Dashboard"]})}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:s}),t&&e.jsx("p",{className:"text-muted-foreground",children:t})]}),n]})]})}const Xht=({expiresAt:s,className:t})=>{const n=new Date().getTime(),r=new Date(s).getTime(),a=Math.ceil((r-n)/(1e3*60*60*24));return a<=0?e.jsxs(qe,{variant:"destructive",className:Ot("gap-1",t),children:[e.jsx(Gd,{className:"h-3 w-3"}),"Trial Expired"]}):a<=1?e.jsxs(qe,{variant:"destructive",className:Ot("gap-1",t),children:[e.jsx(sa,{className:"h-3 w-3"}),"Trial: <1 day left"]}):a<=3?e.jsxs(qe,{className:Ot("gap-1 bg-amber-500 hover:bg-amber-600",t),children:[e.jsx(sa,{className:"h-3 w-3"}),"Trial: ",a," days left"]}):e.jsxs(qe,{variant:"secondary",className:Ot("gap-1",t),children:[e.jsx(sa,{className:"h-3 w-3"}),"Trial: ",a," days left"]})},_Rt=({open:s,onOpenChange:t,brokerages:n,fixedBrokerageId:r,onSuccess:a})=>{const{toast:i}=Fi(),l=k.useRef(null),[o,c]=k.useState([]),[d,u]=k.useState(""),[h,m]=k.useState(!1),[p,g]=k.useState("upload"),[x,y]=k.useState(null),v=()=>{c([]),u(""),g("upload"),y(null),l.current&&(l.current.value="")},_=()=>{v(),t(!1)},j=P=>{const R=P.split(` `).map(H=>H.trim()).filter(H=>H);if(R.length===0)return[];const O=R[0].toLowerCase(),U=O.includes("first")||O.includes("last")||O.includes("email")||O.includes("name")||O.includes("phone")||O.includes("sms")||O.includes("consent")?R.slice(1):R,G=[];for(const H of U){const se=(H.includes(" ")?H.split(" "):H.split(",")).map(ee=>ee.trim().replace(/^["']|["']$/g,""));if(se.length>=2){let ee="",oe="",me="",Q="",te;if(se.length===2){const _e=se[0].split(" ");ee=_e[0]||"",oe=_e.slice(1).join(" ")||"",me=se[1]}else if(se.length===3)ee=se[0],oe=se[1],me=se[2];else if(se.length===4)ee=se[0],oe=se[1],me=se[2],Q=se[3];else if(se.length>=5){ee=se[0],oe=se[1],me=se[2],Q=se[3];const _e=se[4].toLowerCase();te=_e==="true"||_e==="yes"||_e==="1"||_e==="y"}const fe=/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(me);G.push({firstName:ee.trim(),lastName:oe.trim(),email:me.trim().toLowerCase(),phone:Q.trim()||void 0,smsConsent:te,isValid:fe&&ee.trim().length>0,error:fe?ee.trim()?void 0:"Missing name":"Invalid email"})}}return G},C=P=>{var B;const R=(B=P.target.files)==null?void 0:B[0];if(!R)return;const O=new FileReader;O.onload=U=>{var Y;const G=(Y=U.target)==null?void 0:Y.result,H=j(G);if(H.length===0){i({title:"No data found",description:"The CSV file appears to be empty or in an unsupported format.",variant:"destructive"});return}c(H),g("preview")},O.readAsText(R)},A=async()=>{const P=o.filter(O=>O.isValid);if(P.length===0){i({title:"No valid users",description:"There are no valid users to import.",variant:"destructive"});return}const R=r||d||null;m(!0);try{const{data:{session:O}}=await V.auth.getSession(),B=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/bulk-create-users",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${O==null?void 0:O.access_token}`},body:JSON.stringify({users:P.map(G=>({firstName:G.firstName,lastName:G.lastName,email:G.email,phone:G.phone,smsConsent:G.smsConsent})),brokerageId:R})}),U=await B.json();if(!B.ok)throw new Error(U.error||"Failed to import users");y(U),g("result"),U.created>0&&a(),i({title:"Import Complete",description:`${U.created} user(s) created successfully.${U.failed>0?` ${U.failed} failed.`:""}`})}catch(O){console.error("Import error:",O),i({title:"Import Failed",description:O.message||"Failed to import users",variant:"destructive"})}finally{m(!1)}},M=o.filter(P=>P.isValid).length,I=o.filter(P=>!P.isValid).length;return e.jsx(zs,{open:s,onOpenChange:_,children:e.jsxs(Rs,{className:"max-w-2xl max-h-[85vh] overflow-hidden flex flex-col",children:[e.jsxs(Vs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(rk,{className:"h-5 w-5"}),"Import Agents from CSV"]}),e.jsx(Cr,{children:"Upload a CSV file with agent information. Each row should contain First Name, Last Name, and Email."})]}),p==="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:C,className:"hidden"}),e.jsx(gi,{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($,{onClick:()=>{var P;return(P=l.current)==null?void 0:P.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."})]})]}),p==="preview"&&e.jsxs("div",{className:"flex-1 overflow-hidden flex flex-col space-y-4",children:[!r&&n&&n.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Assign to Brokerage (optional)"}),e.jsxs(bs,{value:d||"none",onValueChange:P=>u(P==="none"?"":P),children:[e.jsx(ys,{children:e.jsx(_s,{placeholder:"Select a brokerage..."})}),e.jsxs(vs,{children:[e.jsx(We,{value:"none",children:"No brokerage"}),n.map(P=>e.jsx(We,{value:P.id,children:P.name},P.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(Gr,{className:"h-4 w-4 text-green-500"}),e.jsxs("span",{children:[M," valid"]})]}),I>0&&e.jsxs("div",{className:"flex items-center gap-2 text-destructive",children:[e.jsx(Ho,{className:"h-4 w-4"}),e.jsxs("span",{children:[I," invalid"]})]})]}),e.jsxs("div",{className:"flex-1 overflow-auto border rounded-lg",children:[e.jsxs(Qa,{children:[e.jsx(Ja,{children:e.jsxs(vn,{className:"bg-muted/30",children:[e.jsx(Dt,{children:"First Name"}),e.jsx(Dt,{children:"Last Name"}),e.jsx(Dt,{children:"Email"}),e.jsx(Dt,{children:"Phone"}),e.jsx(Dt,{children:"SMS"}),e.jsx(Dt,{children:"Status"})]})}),e.jsx(ei,{children:o.slice(0,100).map((P,R)=>e.jsxs(vn,{children:[e.jsx(_t,{children:P.firstName}),e.jsx(_t,{children:P.lastName}),e.jsx(_t,{children:P.email}),e.jsx(_t,{className:"text-muted-foreground",children:P.phone||"-"}),e.jsx(_t,{className:"text-muted-foreground",children:P.smsConsent===!0?"✓":P.smsConsent===!1?"✗":"-"}),e.jsx(_t,{children:P.isValid?e.jsx(qe,{variant:"default",className:"bg-green-500/10 text-green-600",children:"Valid"}):e.jsx(qe,{variant:"destructive",children:P.error||"Invalid"})})]},R))})]}),o.length>100&&e.jsxs("p",{className:"text-sm text-muted-foreground text-center py-2",children:["Showing first 100 of ",o.length," users"]})]})]}),p==="result"&&x&&e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"text-center",children:[e.jsx(Gr,{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:[x.created," agent(s) created and invited"]}),x.failed>0&&e.jsxs("p",{className:"text-destructive mt-1",children:[x.failed," failed to create"]})]}),x.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:[x.errors.slice(0,10).map((P,R)=>e.jsxs("li",{children:["• ",P]},R)),x.errors.length>10&&e.jsxs("li",{children:["...and ",x.errors.length-10," more"]})]})]})]}),e.jsxs(kr,{children:[p==="upload"&&e.jsx($,{variant:"outline",onClick:_,children:"Cancel"}),p==="preview"&&e.jsxs(e.Fragment,{children:[e.jsx($,{variant:"outline",onClick:v,children:"Back"}),e.jsx($,{onClick:A,disabled:h||M===0,children:h?e.jsxs(e.Fragment,{children:[e.jsx(Jt,{className:"mr-2 h-4 w-4 animate-spin"}),"Importing..."]}):`Import ${M} Agent${M!==1?"s":""}`})]}),p==="result"&&e.jsx($,{onClick:_,children:"Done"})]})]})})};function Dh({sortKey:s,currentSortKey:t,currentDirection:n,onSort:r,children:a,className:i,...l}){const o=t===s;return e.jsx(Dt,{className:Ot("cursor-pointer select-none",i),...l,children:e.jsxs("button",{type:"button",className:"flex items-center gap-1 font-semibold hover:text-foreground transition-colors w-full text-left",onClick:()=>r(s),children:[a,o?n==="asc"?e.jsx(ap,{className:"h-3.5 w-3.5 shrink-0"}):e.jsx(nx,{className:"h-3.5 w-3.5 shrink-0"}):e.jsx(Ix,{className:"h-3.5 w-3.5 shrink-0 opacity-40"})]})})}function Uee(s=null,t=null){const[n,r]=k.useState(s),[a,i]=k.useState(t),l=k.useCallback(c=>{n===c?a==="asc"?i("desc"):a==="desc"?(r(null),i(null)):i("asc"):(r(c),i("asc"))},[n,a]),o=k.useCallback((c,d)=>{if(!n||!a||!d[n])return c;const u=d[n];return[...c].sort((h,m)=>{const p=u(h),g=u(m);if(p==null&&g==null)return 0;if(p==null)return 1;if(g==null)return-1;let x;return typeof p=="string"&&typeof g=="string"?x=p.localeCompare(g,void 0,{sensitivity:"base"}):x=p-g,a==="asc"?x:-x})},[n,a]);return{sortKey:n,sortDirection:a,handleSort:l,sortData:o}}const mVs=[{type:"custom",title:"Great job!",message:"Keep up the amazing work!",icon:ri},{type:"custom",title:"You're on fire!",message:"Your dedication is inspiring!",icon:ql},{type:"custom",title:"Congratulations!",message:"You earned this celebration!",icon:jg}];function wRt({open:s,onOpenChange:t,userId:n,userName:r}){const[a,i]=k.useState("custom"),[l,o]=k.useState(""),[c,d]=k.useState(""),u=Z_s(),h=p=>{i(p.type),o(p.title),d(p.message)},m=async p=>{if(p.preventDefault(),!l.trim()){Ma({title:"Title required",description:"Please enter a celebration title",variant:"destructive"});return}try{await u.mutateAsync({user_id:n,celebration_type:a,title:l.trim(),message:c.trim()||void 0}),Ma({title:"Celebration sent! 🎉",description:`${r} will see confetti on their next visit!`}),t(!1),o(""),d(""),i("custom")}catch{Ma({title:"Error",description:"Failed to send celebration",variant:"destructive"})}};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"sm:max-w-md",children:[e.jsxs(Vs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(jg,{className:"h-5 w-5 text-primary"}),"Send Celebration to ",r]}),e.jsx(Cr,{children:"They'll see confetti and this message next time they log in!"})]}),e.jsxs("div",{className:"mb-4",children:[e.jsx(re,{className:"text-sm text-muted-foreground mb-2 block",children:"Quick presets:"}),e.jsx("div",{className:"flex gap-2 flex-wrap",children:mVs.map((p,g)=>e.jsxs($,{variant:"outline",size:"sm",onClick:()=>h(p),className:"text-xs",children:[e.jsx(p.icon,{className:"h-3 w-3 mr-1"}),p.title]},g))})]}),e.jsxs("form",{onSubmit:m,className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(re,{htmlFor:"type",children:"Celebration Type"}),e.jsxs(bs,{value:a,onValueChange:p=>i(p),children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"custom",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ri,{className:"h-4 w-4"})," Custom"]})}),e.jsx(We,{value:"points_earned",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ql,{className:"h-4 w-4"})," Points Earned"]})}),e.jsx(We,{value:"listing_created",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ua,{className:"h-4 w-4"})," Listing Created"]})}),e.jsx(We,{value:"deal_closed",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Su,{className:"h-4 w-4"})," Deal Closed"]})})]})]})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"title",children:"Title *"}),e.jsx(be,{id:"title",value:l,onChange:p=>o(p.target.value),placeholder:"e.g., Congratulations!",maxLength:100})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"message",children:"Message (optional)"}),e.jsx(Ls,{id:"message",value:c,onChange:p=>d(p.target.value),placeholder:"Add a personal message...",rows:3,maxLength:500})]}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx($,{type:"button",variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs($,{type:"submit",disabled:u.isPending,children:[e.jsx(jg,{className:"h-4 w-4 mr-2"}),u.isPending?"Sending...":"Send Celebration"]})]})]})]})})}const JLe={points_earned:{label:"Points Earned",icon:ql,color:"bg-yellow-500"},listing_created:{label:"Listing Created",icon:ua,color:"bg-blue-500"},deal_closed:{label:"Deal Closed",icon:Su,color:"bg-green-500"},custom:{label:"Custom",icon:kn,color:"bg-purple-500"}};function fVs(){const[s,t]=k.useState(""),[n,r]=k.useState("all"),[a,i]=k.useState("all"),{data:l=[],isLoading:o}=pt({queryKey:["admin-celebrations"],queryFn:async()=>{const{data:u,error:h}=await V.from("celebration_queue").select("*").order("created_at",{ascending:!1}).limit(500);if(h)throw h;const m=[...new Set([...u.map(x=>x.user_id),...u.map(x=>x.created_by).filter(Boolean)])],{data:p}=await V.from("profiles").select("id, name, email").in("id",m),g=new Map((p==null?void 0:p.map(x=>[x.id,x]))||[]);return u.map(x=>{var y,v,_;return{...x,user_name:((y=g.get(x.user_id))==null?void 0:y.name)||"Unknown",user_email:((v=g.get(x.user_id))==null?void 0:v.email)||"",creator_name:x.created_by?((_=g.get(x.created_by))==null?void 0:_.name)||"System":"Auto-triggered"}})}}),c=l.filter(u=>{var g,x;const h=((g=u.user_name)==null?void 0:g.toLowerCase().includes(s.toLowerCase()))||((x=u.user_email)==null?void 0:x.toLowerCase().includes(s.toLowerCase()))||u.title.toLowerCase().includes(s.toLowerCase()),m=n==="all"||u.celebration_type===n,p=a==="all"||a==="seen"&&u.seen_at||a==="unseen"&&!u.seen_at;return h&&m&&p}),d={total:l.length,seen:l.filter(u=>u.seen_at).length,unseen:l.filter(u=>!u.seen_at).length,byType:Object.keys(JLe).reduce((u,h)=>(u[h]=l.filter(m=>m.celebration_type===h).length,u),{})};return o?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(Jt,{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(we,{children:[e.jsx(Vt,{className:"pb-2",children:e.jsx(Yt,{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(we,{children:[e.jsx(Vt,{className:"pb-2",children:e.jsx(Yt,{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(we,{children:[e.jsx(Vt,{className:"pb-2",children:e.jsx(Yt,{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(we,{children:[e.jsx(Vt,{className:"pb-2",children:e.jsx(Yt,{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(we,{children:[e.jsxs(Vt,{children:[e.jsxs(Yt,{className:"flex items-center gap-2",children:[e.jsx(jg,{className:"h-5 w-5"}),"Celebration History"]}),e.jsx(vr,{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(Yr,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search by agent name, email, or title...",value:s,onChange:u=>t(u.target.value),className:"pl-9"})]}),e.jsxs(bs,{value:n,onValueChange:r,children:[e.jsx(ys,{className:"w-[180px]",children:e.jsx(_s,{placeholder:"Filter by type"})}),e.jsxs(vs,{children:[e.jsx(We,{value:"all",children:"All Types"}),Object.entries(JLe).map(([u,h])=>e.jsx(We,{value:u,children:h.label},u))]})]}),e.jsxs(bs,{value:a,onValueChange:i,children:[e.jsx(ys,{className:"w-[140px]",children:e.jsx(_s,{placeholder:"Status"})}),e.jsxs(vs,{children:[e.jsx(We,{value:"all",children:"All Status"}),e.jsx(We,{value:"seen",children:"Seen"}),e.jsx(We,{value:"unseen",children:"Pending"})]})]})]}),e.jsx("div",{className:"rounded-md border",children:e.jsxs(Qa,{children:[e.jsx(Ja,{children:e.jsxs(vn,{children:[e.jsx(Dt,{children:"Type"}),e.jsx(Dt,{children:"Agent"}),e.jsx(Dt,{children:"Title"}),e.jsx(Dt,{children:"Points"}),e.jsx(Dt,{children:"Created By"}),e.jsx(Dt,{children:"Created"}),e.jsx(Dt,{children:"Status"})]})}),e.jsx(ei,{children:c.length===0?e.jsx(vn,{children:e.jsx(_t,{colSpan:7,className:"text-center py-8 text-muted-foreground",children:"No celebrations found"})}):c.map(u=>{const h=JLe[u.celebration_type],m=h.icon;return e.jsxs(vn,{children:[e.jsx(_t,{children:e.jsxs(qe,{variant:"outline",className:"gap-1",children:[e.jsx(m,{className:"h-3 w-3"}),h.label]})}),e.jsx(_t,{children:e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:u.user_name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:u.user_email})]})}),e.jsx(_t,{children:e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:u.title}),u.message&&e.jsx("div",{className:"text-xs text-muted-foreground truncate max-w-[200px]",children:u.message})]})}),e.jsx(_t,{children:u.points_amount?e.jsxs(qe,{variant:"secondary",children:["+",u.points_amount]}):e.jsx("span",{className:"text-muted-foreground",children:"-"})}),e.jsx(_t,{children:e.jsx("span",{className:"text-sm text-muted-foreground",children:u.creator_name})}),e.jsx(_t,{children:e.jsx("span",{className:"text-sm text-muted-foreground",children:Ys(new Date(u.created_at),"MMM d, yyyy h:mm a")})}),e.jsx(_t,{children:u.seen_at?e.jsx(qe,{variant:"outline",className:"bg-green-50 text-green-700 border-green-200",children:"Seen"}):e.jsx(qe,{variant:"outline",className:"bg-orange-50 text-orange-700 border-orange-200",children:"Pending"})})]},u.id)})})]})}),c.length>0&&e.jsxs("p",{className:"text-sm text-muted-foreground text-right",children:["Showing ",c.length," of ",l.length," celebrations"]})]})]})]})}const pVs=()=>{const{user:s}=ks(),{toast:t}=Fi(),[n,r]=k.useState([]),[a,i]=k.useState(!0),[l,o]=k.useState(!1),[c,d]=k.useState("all"),[u,h]=k.useState("all"),[m,p]=k.useState("new"),[g,x]=k.useState(new Set),y=k.useCallback(async()=>{try{i(!0);const{data:G,error:H}=await V.from("profiles").select("id, name, email, phone, is_trial, trial_started_at, trial_expires_at, subscription_status, subscription_end_date, converted_from_trial_at, created_at, last_login").or("is_trial.eq.true,subscription_status.eq.trialing,converted_from_trial_at.not.is.null");if(H)throw H;const{data:Y,error:se}=await V.from("trial_email_exports").select("user_id");if(se)throw se;const ee=new Set((Y||[]).map(me=>me.user_id)),oe=(G||[]).map(me=>({...me,converted_from_trial_at:me.converted_from_trial_at??null,already_exported:ee.has(me.id)}));oe.sort((me,Q)=>new Date(Q.created_at).getTime()-new Date(me.created_at).getTime()),r(oe)}catch(G){console.error("Error loading trial users:",G),t({title:"Error",description:"Failed to load trial users",variant:"destructive"})}finally{i(!1)}},[t]);k.useEffect(()=>{y()},[y]);const v=G=>G.trial_started_at?"ghl":"stripe",_=G=>G.trial_expires_at?G.trial_expires_at:G.subscription_end_date?G.subscription_end_date:null,j=G=>G.converted_from_trial_at!==null,C=G=>{if(j(G))return!1;const H=_(G);return H?new Date(H).getTime()<=Date.now():!1},A=n.filter(G=>!(c!=="all"&&v(G)!==c||u==="active"&&(C(G)||j(G))||u==="expired"&&!C(G)||u==="converted"&&!j(G)||m==="new"&&G.already_exported||m==="exported"&&!G.already_exported)),M=()=>{g.size===A.length?x(new Set):x(new Set(A.map(G=>G.id)))},I=G=>{const H=new Set(g);H.has(G)?H.delete(G):H.add(G),x(H)},P=async()=>{if(g.size===0){t({title:"No users selected",description:"Select users to export",variant:"destructive"});return}o(!0);try{const G=n.filter(te=>g.has(te.id)),H="First Name,Last Name,Email,Phone,Trial Type,Status,Signup Date,Expiry Date",Y=G.map(te=>{const le=(te.name||"").split(" "),fe=le[0]||"",_e=le.slice(1).join(" ")||"",ve=v(te)==="stripe"?"Credit Card Trial":"Free Trial (No CC)",he=j(te)?"Converted":C(te)?"Expired":"Active",Se=te.created_at?new Date(te.created_at).toLocaleDateString():"",Te=_(te)?new Date(_(te)).toLocaleDateString():"";return`"${fe}","${_e}","${te.email}","${te.phone||""}","${ve}","${he}","${Se}","${Te}"`}),se=[H,...Y].join(` `),ee=new Blob([se],{type:"text/csv"}),oe=URL.createObjectURL(ee),me=document.createElement("a");me.href=oe,me.download=`trial-users-${new Date().toISOString().split("T")[0]}.csv`,me.click(),URL.revokeObjectURL(oe);const Q=G.filter(te=>!te.already_exported).map(te=>({user_id:te.id,exported_by:s.id}));if(Q.length>0){const{error:te}=await V.from("trial_email_exports").upsert(Q,{onConflict:"user_id"});te&&console.error("Error marking exports:",te)}t({title:"Export complete",description:`Downloaded ${G.length} trial user(s). ${Q.length} newly marked as exported.`}),x(new Set),y()}catch(G){console.error("Export error:",G),t({title:"Error",description:"Failed to export",variant:"destructive"})}finally{o(!1)}},R=n.filter(G=>!G.already_exported).length,O=n.filter(G=>G.already_exported).length,B=n.filter(G=>j(G)).length,U=n.filter(G=>!C(G)&&!j(G)).length;return a?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(Jt,{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(we,{children:e.jsxs(Vt,{className:"pb-2",children:[e.jsx(vr,{children:"Total"}),e.jsx(Yt,{className:"text-2xl",children:n.length})]})}),e.jsx(we,{children:e.jsxs(Vt,{className:"pb-2",children:[e.jsx(vr,{children:"New (Not Exported)"}),e.jsx(Yt,{className:"text-2xl text-green-600",children:R})]})}),e.jsx(we,{children:e.jsxs(Vt,{className:"pb-2",children:[e.jsx(vr,{children:"Active Trials"}),e.jsx(Yt,{className:"text-2xl",children:U})]})}),e.jsx(we,{children:e.jsxs(Vt,{className:"pb-2",children:[e.jsx(vr,{children:"Converted 🎉"}),e.jsx(Yt,{className:"text-2xl text-primary",children:B})]})}),e.jsx(we,{children:e.jsxs(Vt,{className:"pb-2",children:[e.jsx(vr,{children:"Already Exported"}),e.jsx(Yt,{className:"text-2xl text-muted-foreground",children:O})]})})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs(bs,{value:m,onValueChange:G=>p(G),children:[e.jsx(ys,{className:"w-[160px]",children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"all",children:"All Users"}),e.jsx(We,{value:"new",children:"New Only"}),e.jsx(We,{value:"exported",children:"Already Exported"})]})]}),e.jsxs(bs,{value:c,onValueChange:G=>d(G),children:[e.jsx(ys,{className:"w-[180px]",children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"all",children:"All Trial Types"}),e.jsx(We,{value:"stripe",children:"Credit Card Trial"}),e.jsx(We,{value:"ghl",children:"Free Trial (No CC)"})]})]}),e.jsxs(bs,{value:u,onValueChange:G=>h(G),children:[e.jsx(ys,{className:"w-[160px]",children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"all",children:"All Statuses"}),e.jsx(We,{value:"active",children:"Active Trial"}),e.jsx(We,{value:"expired",children:"Expired"}),e.jsx(We,{value:"converted",children:"Converted ✓"})]})]}),e.jsx("div",{className:"ml-auto",children:e.jsxs($,{onClick:P,disabled:l||g.size===0,children:[l?e.jsx(Jt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(ji,{className:"h-4 w-4 mr-2"}),"Export Selected (",g.size,")"]})})]}),e.jsx("div",{className:"border rounded-lg",children:e.jsxs(Qa,{children:[e.jsx(Ja,{children:e.jsxs(vn,{className:"bg-muted/30 hover:bg-muted/30",children:[e.jsx(Dt,{className:"w-[40px]",children:e.jsx(Li,{checked:A.length>0&&g.size===A.length,onCheckedChange:M})}),e.jsx(Dt,{children:"Name"}),e.jsx(Dt,{children:"Email"}),e.jsx(Dt,{children:"Trial Type"}),e.jsx(Dt,{children:"Status"}),e.jsx(Dt,{children:"Signup Date"}),e.jsx(Dt,{children:"Last Login"}),e.jsx(Dt,{children:"Expires / Renews"}),e.jsx(Dt,{children:"Exported"})]})}),e.jsx(ei,{children:A.length===0?e.jsx(vn,{children:e.jsx(_t,{colSpan:9,className:"text-center py-8 text-muted-foreground",children:"No trial users match the current filters"})}):A.map(G=>{const H=v(G),Y=j(G),se=C(G),ee=_(G);return e.jsxs(vn,{className:`hover:bg-muted/30 ${Y?"bg-primary/5":""}`,children:[e.jsx(_t,{children:e.jsx(Li,{checked:g.has(G.id),onCheckedChange:()=>I(G.id)})}),e.jsx(_t,{className:"font-medium",children:e.jsxs("div",{className:"flex items-center gap-2",children:[G.name,Y&&e.jsx(mc,{className:"h-3.5 w-3.5 text-primary"})]})}),e.jsx(_t,{className:"text-muted-foreground",children:G.email}),e.jsx(_t,{children:H==="stripe"?e.jsxs(qe,{variant:"outline",className:"gap-1",children:[e.jsx(cv,{className:"h-3 w-3"}),"Credit Card"]}):e.jsxs(qe,{variant:"secondary",className:"gap-1",children:[e.jsx(pn,{className:"h-3 w-3"}),"Free (No CC)"]})}),e.jsx(_t,{children:Y?e.jsxs(qe,{className:"bg-primary/10 text-primary hover:bg-primary/20 gap-1",children:[e.jsx(mc,{className:"h-3 w-3"}),"Converted"]}):se?e.jsx(qe,{variant:"destructive",children:"Expired"}):e.jsx(qe,{className:"bg-green-500/10 text-green-600 hover:bg-green-500/20",children:"Active Trial"})}),e.jsx(_t,{className:"text-sm",children:G.created_at?new Date(G.created_at).toLocaleDateString():"—"}),e.jsx(_t,{className:"text-sm",children:G.last_login?e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{children:new Date(G.last_login).toLocaleDateString()}),e.jsx("span",{className:"text-xs text-muted-foreground",children:new Date(G.last_login).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})})]}):e.jsx("span",{className:"text-muted-foreground",children:"Never"})}),e.jsx(_t,{className:"text-sm",children:Y&&ee?e.jsxs("span",{className:"text-muted-foreground",children:["Renews ",new Date(ee).toLocaleDateString()]}):ee?new Date(ee).toLocaleDateString():"—"}),e.jsx(_t,{children:G.already_exported?e.jsx(Gr,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(qe,{variant:"outline",className:"text-green-600 border-green-300",children:"New"})})]},G.id)})})]})}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Showing ",A.length," of ",n.length," trial users · ",B," converted to paid"]})]})},gVs=s=>s==null?'""':`"${String(s).replace(/"/g,'""')}"`,xVs=()=>{const[s,t]=k.useState([]),[n,r]=k.useState(!0);k.useEffect(()=>{(async()=>{const{data:l,error:o}=await V.from("user_deletion_log").select("*").order("created_at",{ascending:!1});!o&&l&&t(l),r(!1)})()},[]);const a=()=>{if(s.length===0){ae.info("No deletion records to export");return}const i=["Date","Deleted User","Deleted Email","Brokerage","Type","Deleted By"],l=s.map(h=>[Ys(new Date(h.created_at),"MMM d, yyyy h:mm a"),h.deleted_user_name||"—",h.deleted_user_email||"—",h.brokerage_name||"—",h.deletion_type==="deleted"?"Account Deleted":"Removed",h.deleted_by_name||h.deleted_by_email||"—"]),o=[i.join(","),...l.map(h=>h.map(gVs).join(","))].join(` `),c=new Blob([o],{type:"text/csv"}),d=URL.createObjectURL(c),u=document.createElement("a");u.href=d,u.download=`deletion-log-${new Date().toISOString().split("T")[0]}.csv`,u.click(),URL.revokeObjectURL(d),ae.success(`Exported ${s.length} deletion record(s)`)};return n?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(Jt,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):s.length===0?e.jsx(we,{children:e.jsxs(De,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(Un,{className:"h-10 w-10 mx-auto mb-3 opacity-40"}),e.jsx("p",{children:"No deletion records yet"})]})}):e.jsxs(we,{children:[e.jsxs(Vt,{className:"flex flex-row items-center justify-between",children:[e.jsx(Yt,{className:"text-lg",children:"User Deletion History"}),e.jsxs($,{variant:"outline",size:"sm",onClick:a,children:[e.jsx(ji,{className:"h-4 w-4 mr-2"}),"Export CSV"]})]}),e.jsx(De,{children:e.jsxs(Qa,{children:[e.jsx(Ja,{children:e.jsxs(vn,{children:[e.jsx(Dt,{children:"Date"}),e.jsx(Dt,{children:"User"}),e.jsx(Dt,{children:"Email"}),e.jsx(Dt,{children:"Brokerage"}),e.jsx(Dt,{children:"Type"}),e.jsx(Dt,{children:"Deleted By"})]})}),e.jsx(ei,{children:s.map(i=>e.jsxs(vn,{children:[e.jsx(_t,{className:"whitespace-nowrap text-sm",children:Ys(new Date(i.created_at),"MMM d, yyyy h:mm a")}),e.jsx(_t,{className:"font-medium",children:i.deleted_user_name||"—"}),e.jsx(_t,{className:"text-sm text-muted-foreground",children:i.deleted_user_email||"—"}),e.jsx(_t,{children:i.brokerage_name||"—"}),e.jsx(_t,{children:e.jsx(qe,{variant:i.deletion_type==="deleted"?"destructive":"secondary",children:i.deletion_type==="deleted"?"Account Deleted":"Removed"})}),e.jsx(_t,{className:"text-sm",children:i.deleted_by_name||i.deleted_by_email||"—"})]},i.id))})]})})]})},dA=s=>{const{user:t}=ks(),n=ls(),r=pt({queryKey:["teams",s],queryFn:async()=>{let h=V.from("teams").select("*").order("created_at",{ascending:!1});s&&(h=h.eq("brokerage_id",s));const{data:m,error:p}=await h;if(p)throw p;return m||[]},enabled:!!t}),a=h=>pt({queryKey:["team-members",h],queryFn:async()=>{const{data:m,error:p}=await V.from("team_members").select("*").eq("team_id",h).order("role",{ascending:!0});if(p)throw p;const g=(m||[]).map(v=>v.user_id),{data:x}=await V.from("profiles").select("id, name, email, avatar_url").in("id",g),y=new Map((x||[]).map(v=>[v.id,v]));return(m||[]).map(v=>({...v,profile:y.get(v.user_id)||null}))},enabled:!!h}),i=Nt({mutationFn:async h=>{const m={name:h.name,created_by:t.id,description:h.description,contact_visibility:h.contact_visibility,lead_pond_enabled:h.lead_pond_enabled,shared_assets_enabled:h.shared_assets_enabled};h.brokerage_id&&(m.brokerage_id=h.brokerage_id);const{data:p,error:g}=await V.from("teams").insert(m).select().single();if(g)throw g;return p},onSuccess:()=>{n.invalidateQueries({queryKey:["teams"]}),ae.success("Team created!")},onError:h=>{ae.error("Failed to create team: "+h.message)}}),l=Nt({mutationFn:async({id:h,...m})=>{const{data:p,error:g}=await V.from("teams").update(m).eq("id",h).select().single();if(g)throw g;return p},onSuccess:()=>{n.invalidateQueries({queryKey:["teams"]}),ae.success("Team updated")},onError:h=>{ae.error("Failed to update team: "+h.message)}}),o=Nt({mutationFn:async h=>{const{error:m}=await V.from("teams").delete().eq("id",h);if(m)throw m},onSuccess:()=>{n.invalidateQueries({queryKey:["teams"]}),ae.success("Team deleted")},onError:h=>{ae.error("Failed to delete team: "+h.message)}}),c=Nt({mutationFn:async h=>{const{data:m,error:p}=await V.from("team_members").insert({team_id:h.team_id,user_id:h.user_id,role:h.role||"team_member"}).select().single();if(p)throw p.message.includes("duplicate")||p.message.includes("unique")?new Error("This agent is already on this team."):p;return m},onSuccess:(h,m)=>{n.invalidateQueries({queryKey:["team-members",m.team_id]}),ae.success("Member added to team")},onError:h=>{ae.error(h.message)}}),d=Nt({mutationFn:async h=>{const{error:m}=await V.from("team_members").delete().eq("id",h.member_id);if(m)throw m},onSuccess:(h,m)=>{n.invalidateQueries({queryKey:["team-members",m.team_id]}),ae.success("Member removed from team")},onError:h=>{ae.error("Failed to remove member: "+h.message)}}),u=Nt({mutationFn:async h=>{const{error:m}=await V.from("team_members").update({role:h.role}).eq("id",h.member_id);if(m)throw m},onSuccess:(h,m)=>{n.invalidateQueries({queryKey:["team-members",m.team_id]}),ae.success("Member role updated")},onError:h=>{ae.error("Failed to update role: "+h.message)}});return{teams:r.data||[],isLoading:r.isLoading,createTeam:i,updateTeam:l,deleteTeam:o,addMember:c,removeMember:d,updateMemberRole:u,useTeamMembers:a}},eYe=s=>{const t=ls(),n=pt({queryKey:["team-ponds",s],queryFn:async()=>{const{data:o,error:c}=await V.rpc("get_team_ponds",{_team_id:s});if(c)throw c;return o||[]},enabled:!!s}),r=()=>{t.invalidateQueries({queryKey:["team-ponds"]}),t.invalidateQueries({queryKey:["lead-pond"]})},a=Nt({mutationFn:async o=>{const{data:c,error:d}=await V.from("team_ponds").insert({team_id:s,name:o.name,description:o.description||null}).select().single();if(d)throw d;return c},onSuccess:()=>{r(),ae.success("Pond created")},onError:o=>ae.error(o.message)}),i=Nt({mutationFn:async({id:o,...c})=>{const{error:d}=await V.from("team_ponds").update(c).eq("id",o);if(d)throw d},onSuccess:()=>{r(),ae.success("Pond updated")},onError:o=>ae.error(o.message)}),l=Nt({mutationFn:async o=>{const{error:c}=await V.from("team_ponds").delete().eq("id",o);if(c)throw c},onSuccess:()=>{r(),ae.success("Pond deleted")},onError:o=>ae.error(o.message)});return{ponds:n.data||[],isLoading:n.isLoading,createPond:a,updatePond:i,deletePond:l}},yVs=s=>{const t=ls(),n=pt({queryKey:["pond-assignments",s],queryFn:async()=>{const{data:a,error:i}=await V.from("team_pond_members").select("id, user_id").eq("pond_id",s);if(i)throw i;return a||[]},enabled:!!s}),r=Nt({mutationFn:async a=>{if(a.assigned){const{error:i}=await V.from("team_pond_members").insert({pond_id:s,user_id:a.user_id});if(i&&!i.message.includes("duplicate"))throw i}else{const{error:i}=await V.from("team_pond_members").delete().eq("pond_id",s).eq("user_id",a.user_id);if(i)throw i}},onSuccess:()=>{t.invalidateQueries({queryKey:["pond-assignments",s]}),t.invalidateQueries({queryKey:["team-ponds"]}),t.invalidateQueries({queryKey:["lead-pond"]})},onError:a=>ae.error(a.message)});return{assignedUserIds:(n.data||[]).map(a=>a.user_id),isLoading:n.isLoading,setAssigned:r}},vVs=({pond:s,teamId:t})=>{const{useTeamMembers:n}=dA(),{data:r=[],isLoading:a}=n(t),{assignedUserIds:i,isLoading:l,setAssigned:o}=yVs(s.id);return a||l?e.jsx(fn,{className:"h-16 w-full"}):e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx(Xn,{className:"h-3.5 w-3.5"}),i.length===0?"Open to everyone on the team (no agents assigned)":`${i.length} agent${i.length===1?"":"s"} assigned`]}),e.jsx("div",{className:"grid gap-2 sm:grid-cols-2",children:r.map(c=>{var u,h;const d=i.includes(c.user_id);return e.jsxs("label",{className:"flex cursor-pointer items-center gap-2 rounded-md border p-2 text-sm",children:[e.jsx(Li,{checked:d,onCheckedChange:m=>o.mutate({user_id:c.user_id,assigned:!!m})}),e.jsx("span",{className:"truncate",children:((u=c.profile)==null?void 0:u.name)||((h=c.profile)==null?void 0:h.email)||"Unknown"}),c.role==="team_leader"&&e.jsx(qe,{variant:"secondary",className:"ml-auto text-[10px]",children:"Leader"})]},c.id)})})]})},jRt=({teamId:s})=>{const{ponds:t,isLoading:n,createPond:r,updatePond:a,deletePond:i}=eYe(s),[l,o]=k.useState(!1),[c,d]=k.useState(""),[u,h]=k.useState(""),[m,p]=k.useState(null),[g,x]=k.useState(null),y=async()=>{c.trim()&&(await r.mutateAsync({name:c.trim(),description:u.trim()}),d(""),h(""),o(!1))};return e.jsxs(we,{children:[e.jsxs(Vt,{className:"flex flex-row items-start justify-between gap-4 space-y-0",children:[e.jsxs("div",{children:[e.jsx(Yt,{className:"text-lg",children:"Lead Ponds"}),e.jsx(vr,{children:"Create multiple ponds (by area, source, or specialty) and assign which agents can see each one."})]}),e.jsxs($,{size:"sm",onClick:()=>o(!0),children:[e.jsx(nn,{className:"mr-1 h-4 w-4"})," New Pond"]})]}),e.jsxs(De,{className:"space-y-3",children:[n&&e.jsx(fn,{className:"h-20 w-full"}),!n&&t.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"No ponds yet. Create your first pond to start sharing leads with the team."}),t.map(v=>e.jsxs("div",{className:"rounded-lg border p-3 space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(pb,{className:"h-4 w-4 text-primary"}),e.jsx("p",{className:"font-medium",children:v.name}),v.is_default&&e.jsx(qe,{variant:"secondary",className:"text-[10px]",children:"Default"})]}),v.description&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:v.description}),e.jsxs("div",{className:"mt-1 flex flex-wrap gap-2 text-[11px] text-muted-foreground",children:[e.jsxs("span",{children:[v.available_count," available"]}),e.jsx("span",{children:"·"}),e.jsxs("span",{children:[v.claimed_count," claimed"]})]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsxs($,{size:"sm",variant:"ghost",onClick:()=>x(g===v.id?null:v.id),children:[e.jsx(Xn,{className:"mr-1 h-3.5 w-3.5"}),g===v.id?"Hide agents":"Assign agents"]}),e.jsx($,{size:"icon",variant:"ghost",onClick:()=>p(v),children:e.jsx(ui,{className:"h-3.5 w-3.5"})}),e.jsx($,{size:"icon",variant:"ghost",onClick:()=>{confirm(`Delete "${v.name}"? Leads in this pond will no longer be shared.`)&&i.mutate(v.id)},children:e.jsx(Un,{className:"h-3.5 w-3.5 text-destructive"})})]})]}),g===v.id&&e.jsx(vVs,{pond:v,teamId:s})]},v.id))]}),e.jsx(zs,{open:l,onOpenChange:o,children:e.jsxs(Rs,{children:[e.jsxs(Vs,{children:[e.jsx($s,{children:"New Lead Pond"}),e.jsx(Cr,{children:"Leave agents unassigned to make the pond open to the whole team."})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Pond name"}),e.jsx(be,{value:c,onChange:v=>d(v.target.value),placeholder:"e.g. Northland Buyers"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Description (optional)"}),e.jsx(be,{value:u,onChange:v=>h(v.target.value),placeholder:"What kind of leads go in this pond?"})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>o(!1),children:"Cancel"}),e.jsx($,{onClick:y,disabled:!c.trim()||r.isPending,children:"Create Pond"})]})]})}),e.jsx(zs,{open:!!m,onOpenChange:v=>!v&&p(null),children:e.jsxs(Rs,{children:[e.jsx(Vs,{children:e.jsx($s,{children:"Edit Pond"})}),m&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Pond name"}),e.jsx(be,{value:m.name,onChange:v=>p({...m,name:v.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Description"}),e.jsx(be,{value:m.description||"",onChange:v=>p({...m,description:v.target.value})})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>p(null),children:"Cancel"}),e.jsx($,{onClick:async()=>{m&&(await a.mutateAsync({id:m.id,name:m.name,description:m.description||""}),p(null))},disabled:a.isPending,children:"Save"})]})]})})]})},bVs=(s,t=!0)=>pt({queryKey:["lead-pond-activity",s],queryFn:async()=>{const{data:n,error:r}=await V.rpc("get_lead_pond_activity",{_lead_pond_id:s});if(r)throw r;return n||[]},enabled:!!s&&t}),_Vs=()=>{const{user:s}=ks();return pt({queryKey:["team-contacts",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await V.rpc("get_team_contacts",{_user_id:s.id});if(n)throw n;return t||[]},enabled:!!s})},NRt=(s,t)=>{const{user:n}=ks(),r=ls(),a=pt({queryKey:["lead-pond",s,t||"all"],queryFn:async()=>{const{data:c,error:d}=await V.rpc("get_team_lead_pond",{_team_id:s,_pond_id:t||null});if(d)throw d;return(c||[]).map(u=>({id:u.id,team_id:u.team_id,pond_id:u.pond_id,pond_name:u.pond_name,contact_id:u.contact_id,added_by:u.added_by,claimed_by:u.claimed_by,claimed_at:u.claimed_at,returned_at:u.returned_at,notes:u.notes,created_at:u.created_at,status:u.claimed_by?"claimed":"available",contact:{first_name:u.first_name,last_name:u.last_name,email:u.email,phone:u.phone,address:u.address,lead_source:u.lead_source,notes:u.contact_notes},contributor:{name:u.contributor_name,avatar_url:u.contributor_avatar_url},claimer:u.claimed_by?{name:u.claimer_name,avatar_url:u.claimer_avatar_url}:null,touch_count:u.touch_count??0,last_activity_at:u.last_activity_at,can_view_activity:!!u.can_view_activity}))},enabled:!!s&&!!n}),i=Nt({mutationFn:async c=>{const{data:d,error:u}=await V.rpc("add_to_lead_pond",{_contact_id:c.contact_id,_team_id:c.team_id,_notes:c.notes||null,_pond_id:c.pond_id||null});if(u)throw u;return d},onSuccess:()=>{r.invalidateQueries({queryKey:["lead-pond"]}),ae.success("Contact added to Lead Pond")},onError:c=>{ae.error(c.message)}}),l=Nt({mutationFn:async c=>{const{error:d}=await V.rpc("claim_lead_pond_contact",{_lead_pond_id:c});if(d)throw d},onSuccess:()=>{r.invalidateQueries({queryKey:["lead-pond"]}),r.invalidateQueries({queryKey:["innercircle-contacts"]}),r.invalidateQueries({queryKey:["contacts"]}),r.invalidateQueries({queryKey:["contact-custom-tags"]}),ae.success("Lead claimed and added to your contacts, tagged with the pond name. Your notes and follow-ups stay visible to your team leader and the agent who shared it.")},onError:c=>{ae.error(c.message)}}),o=Nt({mutationFn:async c=>{const{error:d}=await V.rpc("return_lead_pond_contact",{_lead_pond_id:c});if(d)throw d},onSuccess:()=>{r.invalidateQueries({queryKey:["lead-pond"]}),ae.success("Lead returned to pond")},onError:c=>{ae.error(c.message)}});return{leadPondItems:a.data||[],isLoading:a.isLoading,addToLeadPond:i,claimLead:l,returnLead:o}},wVs=(s,t,n=100)=>pt({queryKey:["team-pond-history",s,t||"all",n],queryFn:async()=>{const{data:r,error:a}=await V.rpc("get_team_pond_history",{_team_id:s,_pond_id:t||null,_limit:n});if(a)throw a;return r||[]},enabled:!!s}),jVs=()=>{const s=ls();return Nt({mutationFn:async t=>{const{data:n,error:r}=await V.rpc("transfer_contact",{_contact_id:t.contactId,_to_user_id:t.toUserId,_notes:t.notes||null});if(r)throw r;const a=n;if(!a.success)throw new Error(a.error);return a},onSuccess:()=>{s.invalidateQueries({queryKey:["innercircle-contacts"]}),s.invalidateQueries({queryKey:["team-contacts"]}),s.invalidateQueries({queryKey:["innercircle-contact-counts"]}),ae.success("Contact transferred successfully")},onError:t=>{ae.error(t.message||"Failed to transfer contact")}})};function kRt({open:s,onOpenChange:t,contactIds:n,contactNames:r=[],onComplete:a}){var A;const{user:i}=ks(),{data:l}=gj(),{useTeamMembers:o}=dA(),{data:c=[]}=o((l==null?void 0:l.teamId)||""),d=jVs(),[u,h]=k.useState(null),[m,p]=k.useState(""),[g,x]=k.useState(!1),y=c.filter(M=>M.user_id!==(i==null?void 0:i.id)),v=async()=>{if(u){x(!0);try{for(const M of n)await d.mutateAsync({contactId:M,toUserId:u,notes:m||void 0});t(!1),h(null),p(""),a==null||a()}catch{}finally{x(!1)}}},_=y.find(M=>M.user_id===u),j=n.length>1,C=r.length>0?j?`${r.length} contacts`:r[0]:j?`${n.length} contacts`:"this contact";return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"sm:max-w-md",children:[e.jsxs(Vs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(N5,{className:"h-5 w-5"}),"Transfer ",C]}),e.jsxs(Cr,{children:["Select a team member to transfer ",j?"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(re,{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:y.length===0?e.jsx("p",{className:"text-sm text-muted-foreground py-4 text-center",children:"No other team members available"}):y.map(M=>{var I,P,R;return e.jsxs("button",{onClick:()=>h(M.user_id),className:`w-full flex items-center gap-3 p-3 rounded-lg text-left transition-colors ${u===M.user_id?"bg-primary/10 border border-primary/30":"hover:bg-accent border border-transparent"}`,children:[e.jsxs(Wa,{className:"h-8 w-8",children:[e.jsx(eo,{src:((I=M.profile)==null?void 0:I.avatar_url)||""}),e.jsx(Ka,{className:"text-xs",children:(((P=M.profile)==null?void 0:P.name)||"?").charAt(0).toUpperCase()})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:((R=M.profile)==null?void 0:R.name)||"Unknown"}),e.jsx("p",{className:"text-xs text-muted-foreground capitalize",children:M.role.replace("_"," ")})]})]},M.user_id)})})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"transfer-notes",className:"text-sm font-medium",children:"Notes (optional)"}),e.jsx(Ls,{id:"transfer-notes",value:m,onChange:M=>p(M.target.value),placeholder:"Reason for transfer...",className:"mt-1",rows:2})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs($,{onClick:v,disabled:!u||g,children:[g?e.jsx(Jt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(N5,{className:"h-4 w-4 mr-2"}),"Transfer",_?` to ${(A=_.profile)==null?void 0:A.name}`:""]})]})]})})}const tYe=()=>{const s=Jn(),{data:t,isLoading:n}=_Vs(),{data:r}=gj(),[a,i]=k.useState(""),[l,o]=k.useState("all"),[c,d]=k.useState(null),[u,h]=k.useState(""),m=(r==null?void 0:r.role)==="team_leader",p=k.useMemo(()=>{if(!t)return[];const x=new Map;return t.forEach(y=>{x.has(y.owner_user_id)||x.set(y.owner_user_id,{id:y.owner_user_id,name:y.owner_name||"Unknown",avatar:y.owner_avatar_url})}),Array.from(x.values())},[t]),g=k.useMemo(()=>{if(!t)return[];let x=t;if(l!=="all"&&(x=x.filter(y=>y.owner_user_id===l)),a.trim()){const y=a.toLowerCase();x=x.filter(v=>{var _,j,C;return(v.first_name+" "+(v.last_name||"")).toLowerCase().includes(y)||((_=v.email)==null?void 0:_.toLowerCase().includes(y))||((j=v.phone)==null?void 0:j.includes(y))||((C=v.owner_name)==null?void 0:C.toLowerCase().includes(y))})}return x},[t,a,l]);return n?e.jsxs("div",{className:"space-y-4",children:[e.jsx(fn,{className:"h-10 w-full"}),e.jsx(fn,{className:"h-64 w-full"})]}):!t||t.length===0?e.jsx(we,{children:e.jsxs(De,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Xn,{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(we,{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(Yr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search by name, email, phone, or agent...",value:a,onChange:x=>i(x.target.value),className:"pl-9"})]}),e.jsxs(bs,{value:l,onValueChange:o,children:[e.jsx(ys,{className:"w-[200px]",children:e.jsx(_s,{placeholder:"Filter by agent"})}),e.jsxs(vs,{children:[e.jsx(We,{value:"all",children:"All Team Members"}),p.map(x=>e.jsx(We,{value:x.id,children:x.name},x.id))]})]})]})})}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[g.length," contact",g.length!==1?"s":""," from ",p.length," teammate",p.length!==1?"s":""]}),e.jsx(we,{children:e.jsx(De,{className:"p-0 overflow-x-auto",children:e.jsxs(Qa,{className:"min-w-[800px]",children:[e.jsx(Ja,{children:e.jsxs(vn,{children:[e.jsx(Dt,{children:"Name"}),e.jsx(Dt,{children:"Agent"}),e.jsx(Dt,{children:"Contact Info"}),e.jsx(Dt,{children:"Address"}),e.jsx(Dt,{children:"Lead Source"}),e.jsx(Dt,{children:"Date Added"}),m&&e.jsx(Dt,{className:"w-[80px]",children:"Actions"})]})}),e.jsx(ei,{children:g.length===0?e.jsx(vn,{children:e.jsx(_t,{colSpan:m?7:6,className:"text-center py-8 text-muted-foreground",children:a||l!=="all"?"No contacts match your filters":"No team contacts available"})}):g.map(x=>e.jsxs(vn,{className:`hover:bg-accent/50 ${m?"cursor-pointer":""}`,onClick:m?()=>s(`/mission-control/contacts/${x.id}`):void 0,children:[e.jsx(_t,{className:"font-medium",children:e.jsxs("span",{className:m?"hover:text-primary hover:underline transition-colors":"",children:[x.first_name," ",x.last_name||""]})}),e.jsx(_t,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(Wa,{className:"h-6 w-6",children:[e.jsx(eo,{src:x.owner_avatar_url||""}),e.jsx(Ka,{className:"text-[10px]",children:(x.owner_name||"?").charAt(0).toUpperCase()})]}),e.jsx("span",{className:"text-sm text-muted-foreground truncate max-w-[120px]",children:x.owner_name||"Unknown"})]})}),e.jsx(_t,{children:e.jsxs("div",{className:"space-y-1 text-sm",children:[x.email&&e.jsxs("div",{className:"flex items-center gap-1 text-muted-foreground",children:[e.jsx(pn,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:"truncate",children:x.email})]}),x.phone&&e.jsxs("div",{className:"flex items-center gap-1 text-muted-foreground",children:[e.jsx(ka,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{children:x.phone})]}),!x.email&&!x.phone&&e.jsx("span",{className:"text-xs text-muted-foreground italic",children:"No contact info"})]})}),e.jsx(_t,{children:x.address?e.jsxs("div",{className:"flex items-center gap-1 text-sm text-muted-foreground",children:[e.jsx(Si,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:"truncate max-w-[180px]",children:x.address})]}):e.jsx("span",{className:"text-xs text-muted-foreground italic",children:"—"})}),e.jsx(_t,{children:x.lead_source?e.jsx(qe,{variant:"outline",className:"text-xs border-primary/30 text-primary",children:x.lead_source}):e.jsx("span",{className:"text-xs text-muted-foreground italic",children:"—"})}),e.jsx(_t,{children:e.jsx("span",{className:"text-sm text-muted-foreground",children:Ys(new Date(x.created_at),"MMM d, yyyy")})}),m&&e.jsx(_t,{children:e.jsx($,{variant:"ghost",size:"sm",className:"h-8 px-2",onClick:y=>{y.stopPropagation(),d(x.id),h(`${x.first_name} ${x.last_name||""}`.trim())},title:"Transfer to team member",children:e.jsx(N5,{className:"h-4 w-4"})})})]},x.id))})]})})}),e.jsx(kRt,{open:!!c,onOpenChange:x=>{x||d(null)},contactIds:c?[c]:[],contactNames:u?[u]:[],onComplete:()=>d(null)})]})},NVs=s=>{if(!s)return"";const t=new Date(s);return new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit"}).format(t)},kVs=({leadPondId:s})=>{const{data:t,isLoading:n,error:r}=bVs(s);return n?e.jsxs("div",{className:"space-y-2 pt-2",children:[e.jsx(fn,{className:"h-4 w-2/3"}),e.jsx(fn,{className:"h-4 w-1/2"})]}):r?e.jsx("p",{className:"pt-2 text-xs text-muted-foreground",children:"Activity isn't available for this lead."}):!t||t.length===0?e.jsx("p",{className:"pt-2 text-xs text-muted-foreground",children:"No notes or logged follow-ups yet."}):e.jsx("div",{className:"space-y-3 pt-2",children:t.map((a,i)=>e.jsxs("div",{className:"flex gap-2 border-l-2 border-muted pl-3",children:[a.kind==="note"?e.jsx(Z8,{className:"mt-0.5 h-3 w-3 shrink-0 text-muted-foreground"}):e.jsx(zp,{className:"mt-0.5 h-3 w-3 shrink-0 text-muted-foreground"}),e.jsxs("div",{className:"min-w-0 space-y-0.5",children:[e.jsxs("p",{className:"text-xs font-medium",children:[a.label,a.actor_name?e.jsxs("span",{className:"font-normal text-muted-foreground",children:[" · ",a.actor_name]}):null]}),a.notes&&e.jsx("p",{className:"whitespace-pre-wrap text-xs text-muted-foreground",children:a.notes}),a.occurred_at&&e.jsx("p",{className:"text-[10px] text-muted-foreground",children:NVs(a.occurred_at)})]})]},i))})},SVs=s=>s?new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit"}).format(new Date(s)):"",CVs=s=>{var n;const t=((n=s.contact_name)==null?void 0:n.trim())||"A lead";switch(s.event_type){case"claimed":return{icon:qz,text:e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"font-medium",children:s.actor_name||"Someone"})," claimed"," ",e.jsx("span",{className:"font-medium",children:t})]})};case"returned":return{icon:jm,text:e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"font-medium",children:s.actor_name||"Someone"})," returned"," ",e.jsx("span",{className:"font-medium",children:t})," to the pond"]})};default:return{icon:pb,text:e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"font-medium",children:s.actor_name||"Someone"})," added"," ",e.jsx("span",{className:"font-medium",children:t})," to the pond"]})}}},Qht=({teamId:s,pondId:t})=>{const{data:n,isLoading:r}=wVs(s,t),[a,i]=k.useState(!1),l=n||[],o=a?l:l.slice(0,8);return e.jsxs(we,{children:[e.jsx(Vt,{className:"pb-3",children:e.jsxs(Yt,{className:"flex items-center gap-2 text-sm",children:[e.jsx(b2,{className:"h-4 w-4"}),"Pond Activity History"]})}),e.jsx(De,{className:"space-y-3",children:r?e.jsx("div",{className:"space-y-2",children:[1,2,3].map(c=>e.jsx(fn,{className:"h-8 w-full"},c))}):l.length===0?e.jsx("p",{className:"text-xs text-muted-foreground",children:"No pond activity yet. Adding, claiming, and returning leads will show up here."}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"space-y-3",children:o.map((c,d)=>{const u=CVs(c),h=u.icon;return e.jsxs("div",{className:"flex gap-3",children:[e.jsxs(Wa,{className:"h-6 w-6 shrink-0",children:[e.jsx(eo,{src:c.actor_avatar_url||""}),e.jsx(Ka,{className:"text-[9px]",children:(c.actor_name||"?").charAt(0)})]}),e.jsxs("div",{className:"min-w-0 space-y-0.5",children:[e.jsxs("p",{className:"flex items-center gap-1.5 text-xs",children:[e.jsx(h,{className:"h-3 w-3 shrink-0 text-muted-foreground"}),e.jsx("span",{children:u.text})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"text-[10px] text-muted-foreground",children:SVs(c.occurred_at)}),c.pond_name&&e.jsx(qe,{variant:"secondary",className:"text-[9px]",children:c.pond_name})]}),c.notes&&e.jsx("p",{className:"whitespace-pre-wrap text-[11px] text-muted-foreground",children:c.notes})]})]},`${c.lead_pond_id}-${c.event_type}-${d}`)})}),l.length>8&&e.jsxs($,{size:"sm",variant:"ghost",className:"h-7 px-2 text-xs",onClick:()=>i(c=>!c),children:[a?e.jsx(Ny,{className:"mr-1 h-3 w-3"}):e.jsx(Go,{className:"mr-1 h-3 w-3"}),a?"Show less":`Show all ${l.length} events`]})]})})]})},AVs=s=>s?new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",month:"short",day:"numeric"}).format(new Date(s)):null,EVs=({item:s,isClaimer:t,onReturn:n,returning:r})=>{var o,c,d;const[a,i]=k.useState(!1),l=AVs(s.last_activity_at);return e.jsx(we,{children:e.jsxs(De,{className:"space-y-3 p-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0 space-y-1.5",children:[e.jsxs("p",{className:"text-sm font-medium",children:[(o=s.contact)==null?void 0:o.first_name," ",((c=s.contact)==null?void 0:c.last_name)||""]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(qe,{variant:"secondary",className:"text-xs",children:["Claimed by ",((d=s.claimer)==null?void 0:d.name)||"Unknown"]}),e.jsxs(qe,{variant:"outline",className:"text-[10px]",children:[s.touch_count||0," follow-up",(s.touch_count||0)===1?"":"s"]}),e.jsxs("span",{className:"flex items-center gap-1 text-[11px] text-muted-foreground",children:[e.jsx(sa,{className:"h-3 w-3"}),l?`Last activity ${l}`:"No activity yet"]})]}),t&&e.jsxs("p",{className:"flex items-center gap-1 text-[11px] text-muted-foreground",children:[e.jsx(ba,{className:"h-3 w-3"}),"Your notes and follow-ups on this lead are visible to the team leader and the agent who shared it."]})]}),t&&e.jsxs($,{size:"sm",variant:"outline",onClick:n,disabled:r,children:[e.jsx(jm,{className:"mr-1 h-3 w-3"}),"Return"]})]}),s.can_view_activity&&e.jsxs("div",{className:"border-t pt-2",children:[e.jsxs($,{size:"sm",variant:"ghost",className:"h-7 px-2 text-xs",onClick:()=>i(u=>!u),children:[a?e.jsx(Ny,{className:"mr-1 h-3 w-3"}):e.jsx(Go,{className:"mr-1 h-3 w-3"}),a?"Hide notes & activity":"View notes & activity"]}),a&&e.jsx(kVs,{leadPondId:s.id})]})]})})},sYe=({teamId:s})=>{const{user:t}=ks(),[n,r]=k.useState(null),{ponds:a}=eYe(s),i=a.filter(p=>p.has_access),{leadPondItems:l,isLoading:o,claimLead:c,returnLead:d}=NRt(s,n),u=i.length>1?e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx($,{size:"sm",variant:n===null?"default":"outline",onClick:()=>r(null),children:"All Ponds"}),i.map(p=>e.jsxs($,{size:"sm",variant:n===p.id?"default":"outline",onClick:()=>r(p.id),children:[e.jsx(pb,{className:"mr-1 h-3 w-3"}),p.name,e.jsx(qe,{variant:"secondary",className:"ml-2 text-[10px]",children:p.available_count})]},p.id))]}):null;if(console.log("[LeadPondView] render — teamId:",s,"itemCount:",l.length,"loading:",o),o)return e.jsx("div",{className:"space-y-3",children:[1,2,3].map(p=>e.jsx(fn,{className:"h-20 w-full"},p))});if(l.length===0)return e.jsxs("div",{className:"space-y-4",children:[u,e.jsx(we,{children:e.jsxs(De,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(pb,{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."})]})}),e.jsx(Qht,{teamId:s,pondId:n})]});const h=l.filter(p=>p.status==="available"),m=l.filter(p=>p.status==="claimed");return e.jsxs("div",{className:"space-y-6",children:[u,e.jsxs("div",{children:[e.jsxs("h3",{className:"text-sm font-semibold text-muted-foreground mb-3",children:["Available (",h.length,")"]}),h.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:h.map(p=>{var g,x,y,v,_,j,C,A,M,I,P;return e.jsx(we,{children:e.jsxs(De,{className:"flex flex-col gap-3 p-4 sm:flex-row sm:items-start sm:justify-between",children:[e.jsxs("div",{className:"min-w-0 space-y-1.5",children:[e.jsxs("p",{className:"font-medium text-sm",children:[((g=p.contact)==null?void 0:g.first_name)||"Unnamed"," ",((x=p.contact)==null?void 0:x.last_name)||""]}),e.jsxs("div",{className:"flex flex-wrap gap-x-4 gap-y-1",children:[((y=p.contact)==null?void 0:y.email)&&e.jsxs("span",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(pn,{className:"h-3 w-3"})," ",p.contact.email]}),((v=p.contact)==null?void 0:v.phone)&&e.jsxs("span",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(ka,{className:"h-3 w-3"})," ",p.contact.phone]}),((_=p.contact)==null?void 0:_.address)&&e.jsxs("span",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Si,{className:"h-3 w-3"})," ",p.contact.address]})]}),p.pond_name&&n===null&&i.length>1&&e.jsxs(qe,{variant:"secondary",className:"text-[10px]",children:[e.jsx(pb,{className:"mr-1 h-2.5 w-2.5"})," ",p.pond_name]}),((j=p.contact)==null?void 0:j.lead_source)&&e.jsxs(qe,{variant:"outline",className:"text-[10px]",children:["Source: ",p.contact.lead_source]}),(p.notes||((C=p.contact)==null?void 0:C.notes))&&e.jsxs("p",{className:"text-xs text-muted-foreground flex items-start gap-1 max-w-xl",children:[e.jsx(Z8,{className:"h-3 w-3 mt-0.5 shrink-0"}),e.jsx("span",{className:"whitespace-pre-wrap",children:p.notes||((A=p.contact)==null?void 0:A.notes)})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-0.5",children:[e.jsxs(Wa,{className:"h-4 w-4",children:[e.jsx(eo,{src:((M=p.contributor)==null?void 0:M.avatar_url)||""}),e.jsx(Ka,{className:"text-[8px]",children:(((I=p.contributor)==null?void 0:I.name)||"?").charAt(0)})]}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["from ",((P=p.contributor)==null?void 0:P.name)||"Unknown"]})]})]}),e.jsxs($,{size:"sm",className:"shrink-0",onClick:()=>c.mutate(p.id),disabled:c.isPending,children:[e.jsx(qz,{className:"mr-1 h-3 w-3"}),"Claim"]})]})},p.id)})})]}),m.length>0&&e.jsxs("div",{children:[e.jsxs("h3",{className:"text-sm font-semibold text-muted-foreground mb-3",children:["Claimed (",m.length,")"]}),e.jsx("div",{className:"space-y-2",children:m.map(p=>e.jsx(EVs,{item:p,isClaimer:p.claimed_by===(t==null?void 0:t.id),onReturn:()=>d.mutate(p.id),returning:d.isPending},p.id))})]}),e.jsx(Qht,{teamId:s,pondId:n})]})},SRt=({teamId:s})=>{const{useTeamMembers:t}=dA(),{data:n=[]}=t(s),r=n.map(p=>p.user_id),a=new Map(n.map(p=>[p.user_id,p.profile])),{data:i=[],isLoading:l}=pt({queryKey:["team-shared-presentations",s,r],queryFn:async()=>{if(r.length===0)return[];const{data:p,error:g}=await V.from("smart_presentations").select("id, owner_user_id, title, client_name, status, view_count, cta_clicked_count, share_token, created_at, published_at").in("owner_user_id",r).neq("status","archived").order("created_at",{ascending:!1});if(g)throw g;return p||[]},enabled:r.length>0}),{data:o=[],isLoading:c}=pt({queryKey:["team-shared-open-houses",s,r],queryFn:async()=>{if(r.length===0)return[];const{data:p,error:g}=await V.from("open_houses").select("id, agent_id, property_address, city, state, event_date, is_active, visitor_count, slug, created_at").in("agent_id",r).order("event_date",{ascending:!1});if(g)throw g;return p||[]},enabled:r.length>0}),{data:d=[],isLoading:u}=pt({queryKey:["team-shared-videos",s,r],queryFn:async()=>{if(r.length===0)return[];const{data:p,error:g}=await V.from("agent_videos").select("id, owner_user_id, title, recipient_name, status, view_count, touch_type, share_token, created_at").in("owner_user_id",r).eq("is_deleted",!1).order("created_at",{ascending:!1}).limit(50);if(g)throw g;return p||[]},enabled:r.length>0});if(l||c||u)return e.jsx("div",{className:"space-y-3",children:[1,2,3].map(p=>e.jsx(fn,{className:"h-20 w-full"},p))});const m=p=>{const g=a.get(p);return{name:(g==null?void 0:g.name)||"Unknown",avatar:(g==null?void 0:g.avatar_url)||"",initials:((g==null?void 0:g.name)||"?").charAt(0).toUpperCase()}};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-3 grid-cols-3",children:[e.jsx(we,{children:e.jsxs(De,{className:"flex items-center gap-3 p-4",children:[e.jsx(hv,{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(we,{children:e.jsxs(De,{className:"flex items-center gap-3 p-4",children:[e.jsx(ua,{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(we,{children:e.jsxs(De,{className:"flex items-center gap-3 p-4",children:[e.jsx(ia,{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(ya,{defaultValue:"presentations",className:"space-y-4",children:[e.jsxs(va,{children:[e.jsxs(is,{value:"presentations",children:["Presentations (",i.length,")"]}),e.jsxs(is,{value:"guest-books",children:["Guest Books (",o.length,")"]}),e.jsxs(is,{value:"videos",children:["Videos (",d.length,")"]})]}),e.jsx(cs,{value:"presentations",className:"space-y-2",children:i.length===0?e.jsx(eRe,{icon:e.jsx(hv,{className:"h-10 w-10"}),label:"No presentations yet"}):i.map(p=>{const g=m(p.owner_user_id);return e.jsx(we,{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(Wa,{className:"h-8 w-8 shrink-0",children:[e.jsx(eo,{src:g.avatar}),e.jsx(Ka,{className:"text-xs",children:g.initials})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:p.title||"Untitled"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[g.name," · ",Ys(new Date(p.created_at),"MMM d, yyyy")]})]})]}),e.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[e.jsx(qe,{variant:p.status==="published"?"default":"secondary",className:"text-xs capitalize",children:p.status}),e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(ba,{className:"h-3 w-3"}),p.view_count||0]})]})]})},p.id)})}),e.jsx(cs,{value:"guest-books",className:"space-y-2",children:o.length===0?e.jsx(eRe,{icon:e.jsx(ua,{className:"h-10 w-10"}),label:"No guest books yet"}):o.map(p=>{const g=m(p.agent_id);return e.jsx(we,{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(Wa,{className:"h-8 w-8 shrink-0",children:[e.jsx(eo,{src:g.avatar}),e.jsx(Ka,{className:"text-xs",children:g.initials})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:p.property_address}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[g.name," · ",Ys(new Date(p.event_date),"MMM d, yyyy")]})]})]}),e.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[p.is_active?e.jsx(qe,{className:"text-xs",children:"Active"}):e.jsx(qe,{variant:"secondary",className:"text-xs",children:"Inactive"}),e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(Xn,{className:"h-3 w-3"}),p.visitor_count||0]})]})]})},p.id)})}),e.jsx(cs,{value:"videos",className:"space-y-2",children:d.length===0?e.jsx(eRe,{icon:e.jsx(ia,{className:"h-10 w-10"}),label:"No videos yet"}):d.map(p=>{const g=m(p.owner_user_id);return e.jsx(we,{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(Wa,{className:"h-8 w-8 shrink-0",children:[e.jsx(eo,{src:g.avatar}),e.jsx(Ka,{className:"text-xs",children:g.initials})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:p.title||p.recipient_name||"Untitled Video"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[g.name," · ",Ys(new Date(p.created_at),"MMM d, yyyy")]})]})]}),e.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[e.jsx(qe,{variant:"secondary",className:"text-xs capitalize",children:p.touch_type}),e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(ba,{className:"h-3 w-3"}),p.view_count||0]})]})]})},p.id)})})]})]})},eRe=({icon:s,label:t})=>e.jsx(we,{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})]})}),CRt=({team:s,brokerageAgents:t,onBack:n,onUpdate:r,onAddMember:a,onRemoveMember:i,onUpdateRole:l,onDeleteTeam:o,isUpdating:c,isAddingMember:d})=>{var I,P;const{useTeamMembers:u}=dA(),{data:h=[],isLoading:m}=u(s.id),[p,g]=k.useState(!1),[x,y]=k.useState(""),[v,_]=k.useState("team_member"),{data:j}=pt({queryKey:["agents-on-other-teams",s.id],queryFn:async()=>{const{data:R}=await V.from("team_members").select("user_id, team_id, teams:team_id(name)").neq("team_id",s.id),O=new Map;return(R||[]).forEach(B=>{var G;const U=O.get(B.user_id)||[];U.push(((G=B.teams)==null?void 0:G.name)||"another team"),O.set(B.user_id,U)}),O}}),C=new Set(h.map(R=>R.user_id)),A=t.filter(R=>!C.has(R.id)),M=async()=>{x&&(await a(x,v),y(""),_("team_member"),g(!1))};return e.jsxs("div",{className:"space-y-6",children:[e.jsx($,{variant:"ghost",onClick:n,className:"mb-2",children:"← Back to Teams"}),e.jsxs(ya,{defaultValue:"members",className:"space-y-4",children:[e.jsxs(va,{children:[e.jsx(is,{value:"members",children:"Members"}),e.jsxs(is,{value:"contacts",children:[e.jsx(O8,{className:"mr-1 h-3.5 w-3.5"}),"Team Contacts"]}),s.lead_pond_enabled&&e.jsxs(is,{value:"lead-pond",children:[e.jsx(pb,{className:"mr-1 h-3.5 w-3.5"}),"Lead Pond"]}),s.shared_assets_enabled&&e.jsxs(is,{value:"shared-assets",children:[e.jsx(d1,{className:"mr-1 h-3.5 w-3.5"}),"Shared Assets"]}),e.jsx(is,{value:"settings",children:"Settings"})]}),e.jsxs(cs,{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(zs,{open:p,onOpenChange:g,children:[e.jsx(yl,{asChild:!0,children:e.jsxs($,{size:"sm",children:[e.jsx(Pl,{className:"mr-2 h-4 w-4"}),"Add Member"]})}),e.jsxs(Rs,{children:[e.jsxs(Vs,{children:[e.jsx($s,{children:"Add Team Member"}),e.jsxs(Cr,{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(re,{children:"Agent"}),e.jsxs(Xc,{children:[e.jsx(Qc,{asChild:!0,children:e.jsxs($,{variant:"outline",role:"combobox",className:"w-full justify-between font-normal",children:[x&&(((I=A.find(R=>R.id===x))==null?void 0:I.name)||((P=A.find(R=>R.id===x))==null?void 0:P.email))||"Select an agent",e.jsx(v_,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(Bc,{className:"w-[--radix-popover-trigger-width] p-0",align:"start",children:e.jsxs(M_,{children:[e.jsx(P_,{placeholder:"Search agents..."}),e.jsxs(I_,{children:[e.jsx(L_,{children:"No agents found."}),e.jsx(Nb,{children:A.map(R=>{const O=j==null?void 0:j.get(R.id);return e.jsxs(rv,{value:R.name||R.email||R.id,onSelect:()=>y(R.id),children:[e.jsx(ma,{className:Ot("mr-2 h-4 w-4",x===R.id?"opacity-100":"opacity-0")}),R.name||R.email,O!=null&&O.length?e.jsxs("span",{className:"text-xs text-muted-foreground ml-1",children:["(also on ",O.join(", "),")"]}):null]},R.id)})})]})]})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Role"}),e.jsxs(bs,{value:v,onValueChange:_,children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"team_leader",children:"Team Leader"}),e.jsx(We,{value:"team_member",children:"Team Member"})]})]})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>g(!1),children:"Cancel"}),e.jsx($,{onClick:M,disabled:!x||d,children:d?"Adding...":"Add to Team"})]})]})]})]}),m?e.jsx("div",{className:"space-y-3",children:[1,2,3].map(R=>e.jsx(fn,{className:"h-16 w-full"},R))}):h.length===0?e.jsx(we,{children:e.jsxs(De,{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx(Xn,{className:"h-10 w-10 text-muted-foreground mb-3"}),e.jsx("p",{className:"text-muted-foreground",children:"No members yet. Add agents to this team."})]})}):e.jsx("div",{className:"space-y-2",children:h.map(R=>{var O,B,U,G,H;return e.jsx(we,{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(Wa,{className:"h-10 w-10",children:[e.jsx(eo,{src:((O=R.profile)==null?void 0:O.avatar_url)||""}),e.jsx(Ka,{children:(((B=R.profile)==null?void 0:B.name)||"?").charAt(0).toUpperCase()})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:((U=R.profile)==null?void 0:U.name)||"Unknown"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:(G=R.profile)==null?void 0:G.email})]}),R.role==="team_leader"?e.jsxs(qe,{className:"bg-[hsl(var(--chart-4)/0.1)] text-[hsl(var(--chart-4))] border-[hsl(var(--chart-4))]",children:[e.jsx(ky,{className:"mr-1 h-3 w-3"})," Leader"]}):e.jsx(qe,{variant:"secondary",children:"Member"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(bs,{value:R.role,onValueChange:Y=>l(R.id,Y),children:[e.jsx(ys,{className:"w-[140px]",children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"team_leader",children:"Team Leader"}),e.jsx(We,{value:"team_member",children:"Team Member"})]})]}),e.jsxs(oc,{children:[e.jsx(_g,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:"text-muted-foreground hover:text-destructive",children:e.jsx(gB,{className:"h-4 w-4"})})}),e.jsxs(Ql,{children:[e.jsxs(Jl,{children:[e.jsx(tc,{children:"Remove Member?"}),e.jsxs(sc,{children:["Remove ",((H=R.profile)==null?void 0:H.name)||"this member"," from ",s.name,"?"]})]}),e.jsxs(ec,{children:[e.jsx(nc,{children:"Cancel"}),e.jsx(Vl,{onClick:()=>i(R.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Remove"})]})]})]})]})]})},R.id)})})]}),e.jsx(cs,{value:"contacts",className:"space-y-4",children:e.jsx(tYe,{})}),s.lead_pond_enabled&&e.jsx(cs,{value:"lead-pond",className:"space-y-4",children:e.jsx(sYe,{teamId:s.id})}),s.shared_assets_enabled&&e.jsx(cs,{value:"shared-assets",className:"space-y-4",children:e.jsx(SRt,{teamId:s.id})}),e.jsxs(cs,{value:"settings",className:"space-y-4",children:[e.jsxs(we,{children:[e.jsxs(Vt,{children:[e.jsx(Yt,{className:"text-lg",children:"Team Settings"}),e.jsx(vr,{children:"Configure how this team operates."})]}),e.jsxs(De,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Team Name"}),e.jsx(be,{defaultValue:s.name,onBlur:R=>{R.target.value!==s.name&&r({name:R.target.value})}})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Description"}),e.jsx(Ls,{defaultValue:s.description||"",onBlur:R=>{R.target.value!==(s.description||"")&&r({description:R.target.value||null})},rows:3})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Contact Visibility"}),e.jsxs(bs,{defaultValue:s.contact_visibility,onValueChange:R=>r({contact_visibility:R}),children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"private",children:"Private — Members keep their contacts private"}),e.jsx(We,{value:"leader_only",children:"Leader Only — Only team leaders can see member contacts"}),e.jsx(We,{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(re,{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(On,{checked:s.lead_pond_enabled,onCheckedChange:R=>r({lead_pond_enabled:R})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(re,{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(On,{checked:s.shared_assets_enabled,onCheckedChange:R=>r({shared_assets_enabled:R})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(re,{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(On,{checked:s.shared_videos_enabled??!1,onCheckedChange:R=>r({shared_videos_enabled:R})})]})]})]}),s.lead_pond_enabled&&e.jsx(jRt,{teamId:s.id}),e.jsxs(oc,{children:[e.jsx(_g,{asChild:!0,children:e.jsxs($,{variant:"destructive",size:"sm",children:[e.jsx(Un,{className:"mr-2 h-4 w-4"}),"Delete Team"]})}),e.jsxs(Ql,{children:[e.jsxs(Jl,{children:[e.jsx(tc,{children:"Delete Team?"}),e.jsxs(sc,{children:['This will permanently delete "',s.name,'" and remove all team members. This cannot be undone.']})]}),e.jsxs(ec,{children:[e.jsx(nc,{children:"Cancel"}),e.jsx(Vl,{onClick:()=>{o(),n()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete Team"})]})]})]})]})]})]})},ARt=({open:s,onOpenChange:t,onCreateTeam:n,isCreating:r,brokerageAgents:a,isAdmin:i,allBrokerages:l,activeBrokerageId:o})=>{const[c,d]=k.useState(1),[u,h]=k.useState(""),[m,p]=k.useState(""),[g,x]=k.useState(""),[y,v]=k.useState(""),[_,j]=k.useState([]),C=()=>{d(1),h(""),p(""),x(""),v(""),j([])},A=R=>{R||C(),t(R)},M=async()=>{const R=g&&g!=="none"?g:o||null;await n({name:u.trim(),description:m.trim()||void 0,brokerage_id:R,leaderId:y||void 0,memberIds:_.length>0?_:void 0}),C()},I=R=>{R!==y&&j(O=>O.includes(R)?O.filter(B=>B!==R):[...O,R])},P=a.filter(R=>R.id!==y);return e.jsx(zs,{open:s,onOpenChange:A,children:e.jsxs(Rs,{className:"sm:max-w-lg max-h-[90vh] flex flex-col",children:[e.jsxs(Vs,{children:[e.jsx($s,{children:c===1?"Create New Team":"Assign Team Members"}),e.jsx(Cr,{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:Ot("h-1.5 flex-1 rounded-full transition-colors","bg-primary")}),e.jsx("div",{className:Ot("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(re,{htmlFor:"team-name",children:"Team Name *"}),e.jsx(be,{id:"team-name",value:u,onChange:R=>h(R.target.value),placeholder:"e.g., Downtown Squad",autoFocus:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"team-desc",children:"Description"}),e.jsx(Ls,{id:"team-desc",value:m,onChange:R=>p(R.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(re,{children:"Brokerage"}),e.jsxs(bs,{value:g,onValueChange:x,children:[e.jsx(ys,{children:e.jsx(_s,{placeholder:"No brokerage (independent team)"})}),e.jsxs(vs,{children:[e.jsx(We,{value:"none",children:"No brokerage (independent)"}),l.map(R=>e.jsx(We,{value:R.id,children:R.name},R.id))]})]})]})]}):e.jsxs("div",{className:"space-y-4 py-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(re,{className:"flex items-center gap-1.5",children:[e.jsx(ky,{className:"h-3.5 w-3.5 text-[hsl(var(--chart-4))]"}),"Team Leader"]}),e.jsxs(bs,{value:y,onValueChange:R=>{v(R),j(O=>O.filter(B=>B!==R))},children:[e.jsx(ys,{children:e.jsx(_s,{placeholder:"Select a team leader (optional)"})}),e.jsxs(vs,{children:[e.jsx(We,{value:"none",children:"No leader for now"}),a.map(R=>e.jsx(We,{value:R.id,children:R.name||R.email||"Unknown"},R.id))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(re,{className:"flex items-center gap-1.5",children:[e.jsx(Pl,{className:"h-3.5 w-3.5"}),"Initial Members",_.length>0&&e.jsxs(qe,{variant:"secondary",className:"ml-1 text-xs",children:[_.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:P.length===0?e.jsxs("div",{className:"p-4 text-center text-sm text-muted-foreground",children:[e.jsx(Xn,{className:"h-8 w-8 mx-auto mb-2 opacity-50"}),"No agents available"]}):P.map(R=>{const O=_.includes(R.id);return e.jsxs("button",{type:"button",className:Ot("w-full flex items-center gap-3 p-3 text-left transition-colors hover:bg-accent/50",O&&"bg-primary/5"),onClick:()=>I(R.id),children:[e.jsxs(Wa,{className:"h-8 w-8",children:[e.jsx(eo,{src:R.avatar_url||""}),e.jsx(Ka,{className:"text-xs",children:(R.name||"?").charAt(0).toUpperCase()})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:R.name||"Unknown"}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:R.email})]}),e.jsx("div",{className:Ot("h-5 w-5 rounded-full border-2 flex items-center justify-center transition-colors shrink-0",O?"bg-primary border-primary text-primary-foreground":"border-muted-foreground/30"),children:O&&e.jsx(ma,{className:"h-3 w-3"})})]},R.id)})})]})]})}),e.jsx(kr,{className:"gap-2 sm:gap-0",children:c===1?e.jsxs(e.Fragment,{children:[e.jsx($,{variant:"outline",onClick:()=>A(!1),children:"Cancel"}),e.jsxs($,{onClick:()=>d(2),disabled:!u.trim(),children:["Next",e.jsx(xi,{className:"ml-2 h-4 w-4"})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs($,{variant:"outline",onClick:()=>d(1),children:[e.jsx(Ia,{className:"mr-2 h-4 w-4"}),"Back"]}),e.jsx($,{onClick:M,disabled:r,children:r?"Creating…":"Create Team"})]})})]})})},TVs=()=>{const{teams:s,isLoading:t,createTeam:n,updateTeam:r,deleteTeam:a,addMember:i,removeMember:l,updateMemberRole:o}=dA(),[c,d]=k.useState(!1),[u,h]=k.useState(null),[m,p]=k.useState(""),{data:g}=pt({queryKey:["all-brokerages-for-teams"],queryFn:async()=>{const{data:A,error:M}=await V.from("brokerages").select("id, name").order("name");if(M)throw M;return A||[]}}),{data:x}=pt({queryKey:["admin-team-member-info",s.map(A=>A.id).join(",")],queryFn:async()=>{var R;if(s.length===0)return{};const{data:A}=await V.from("team_members").select("team_id, user_id, role").in("team_id",s.map(O=>O.id));if(!A)return{};const M=A.filter(O=>O.role==="team_leader").map(O=>O.user_id);let I={};if(M.length>0){const{data:O}=await V.from("profiles").select("id, name").in("id",M);O&&(I=Object.fromEntries(O.map(B=>[B.id,{name:B.name}])))}const P={};for(const O of s){const B=A.filter(G=>G.team_id===O.id),U=B.find(G=>G.role==="team_leader");P[O.id]={count:B.length,leaderName:U&&((R=I[U.user_id])==null?void 0:R.name)||null}}return P},enabled:s.length>0}),y=(u==null?void 0:u.brokerage_id)||null,{data:v}=pt({queryKey:["brokerage-agents-for-teams",y],queryFn:async()=>{let A=V.from("profiles").select("id, name, email, avatar_url").order("name");y&&(A=A.eq("brokerage_id",y));const{data:M,error:I}=await A;if(I)throw I;return M||[]},enabled:!!u}),_=Object.fromEntries((g||[]).map(A=>[A.id,A.name])),j=async A=>{const M=await n.mutateAsync({name:A.name,brokerage_id:A.brokerage_id||null,description:A.description});if(A.leaderId&&A.leaderId!=="none"&&await i.mutateAsync({team_id:M.id,user_id:A.leaderId,role:"team_leader"}),A.memberIds)for(const I of A.memberIds)await i.mutateAsync({team_id:M.id,user_id:I,role:"team_member"});d(!1)};if(u)return e.jsx(CRt,{team:u,brokerageAgents:v||[],onBack:()=>h(null),onUpdate:A=>r.mutateAsync({id:u.id,...A}).then(M=>h(M)),onAddMember:(A,M)=>i.mutateAsync({team_id:u.id,user_id:A,role:M}),onRemoveMember:A=>l.mutateAsync({team_id:u.id,member_id:A}),onUpdateRole:(A,M)=>o.mutateAsync({team_id:u.id,member_id:A,role:M}),onDeleteTeam:()=>{a.mutate(u.id),h(null)},isUpdating:r.isPending,isAddingMember:i.isPending});const C=s.filter(A=>A.name.toLowerCase().includes(m.toLowerCase())||(A.description||"").toLowerCase().includes(m.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(Yr,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search teams...",value:m,onChange:A=>p(A.target.value),className:"pl-10"})]}),e.jsxs("span",{className:"text-sm text-muted-foreground whitespace-nowrap",children:[C.length," of ",s.length," teams"]})]}),e.jsxs($,{size:"sm",onClick:()=>d(!0),children:[e.jsx(nn,{className:"mr-2 h-4 w-4"}),"Create Team"]})]}),e.jsx(ARt,{open:c,onOpenChange:d,onCreateTeam:j,isCreating:n.isPending,brokerageAgents:[],isAdmin:!0,allBrokerages:g,activeBrokerageId:null}),e.jsx("div",{className:"border rounded-lg bg-card overflow-hidden",children:e.jsxs(Qa,{children:[e.jsx(Ja,{children:e.jsxs(vn,{className:"bg-muted/30 hover:bg-muted/30",children:[e.jsx(Dt,{className:"font-semibold",children:"Team Name"}),e.jsx(Dt,{className:"font-semibold",children:"Brokerage"}),e.jsx(Dt,{className:"font-semibold",children:"Leader"}),e.jsx(Dt,{className:"font-semibold",children:"Members"}),e.jsx(Dt,{className:"font-semibold",children:"Visibility"}),e.jsx(Dt,{className:"w-[100px]"})]})}),e.jsx(ei,{children:t?e.jsx(e.Fragment,{children:[1,2,3].map(A=>e.jsxs(vn,{children:[e.jsx(_t,{children:e.jsx(fn,{className:"h-4 w-32"})}),e.jsx(_t,{children:e.jsx(fn,{className:"h-4 w-24"})}),e.jsx(_t,{children:e.jsx(fn,{className:"h-4 w-28"})}),e.jsx(_t,{children:e.jsx(fn,{className:"h-4 w-12"})}),e.jsx(_t,{children:e.jsx(fn,{className:"h-4 w-20"})}),e.jsx(_t,{children:e.jsx(fn,{className:"h-4 w-16"})})]},A))}):C.length===0?e.jsx(vn,{children:e.jsx(_t,{colSpan:6,className:"text-center py-12 text-muted-foreground",children:m?"No teams match your search":"No teams found. Create one to get started."})}):C.map(A=>{const M=x==null?void 0:x[A.id];return e.jsxs(vn,{className:"hover:bg-muted/30",children:[e.jsxs(_t,{children:[e.jsx("button",{onClick:()=>h(A),className:"text-primary hover:underline font-medium",children:A.name}),A.description&&e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 line-clamp-1",children:A.description})]}),e.jsx(_t,{children:A.brokerage_id?e.jsx("span",{className:"text-sm",children:_[A.brokerage_id]||"—"}):e.jsx("span",{className:"text-sm text-muted-foreground",children:"Independent"})}),e.jsx(_t,{children:M!=null&&M.leaderName?e.jsxs("span",{className:"text-sm flex items-center gap-1",children:[e.jsx(ky,{className:"h-3 w-3 text-[hsl(var(--chart-4))]"}),M.leaderName]}):e.jsx("span",{className:"text-sm text-muted-foreground",children:"No leader"})}),e.jsx(_t,{children:e.jsxs(qe,{variant:"secondary",className:"text-xs",children:[e.jsx(Xn,{className:"h-3 w-3 mr-1"}),(M==null?void 0:M.count)??0]})}),e.jsx(_t,{children:e.jsxs("span",{className:"text-xs text-muted-foreground capitalize flex items-center gap-1",children:[e.jsx(Ng,{className:"h-3 w-3"}),A.contact_visibility.replace("_"," ")]})}),e.jsx(_t,{children:e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>h(A),title:"Edit team",children:e.jsx(ui,{className:"h-3.5 w-3.5"})}),e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive hover:text-destructive",onClick:async()=>{await io(`Delete team "${A.name}"? This cannot be undone.`)&&a.mutate(A.id)},title:"Delete team",children:e.jsx(Un,{className:"h-3.5 w-3.5"})})]})})]},A.id)})})]})})]})};function Jht(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 MVs({open:s,onOpenChange:t,recipients:n}){const{toast:r}=Fi(),[a,i]=k.useState([]),[l,o]=k.useState(!1),[c,d]=k.useState(""),[u,h]=k.useState(""),[m,p]=k.useState(""),[g,x]=k.useState(!1),[y,v]=k.useState(!1),_=k.useMemo(()=>a.find(M=>M.id===c)||null,[a,c]);k.useEffect(()=>{s&&(o(!0),(async()=>{const M=new Date().toISOString(),{data:I,error:P}=await V.from("events").select("id,title,description,event_date,zoom_link,image_url,is_published").gte("event_date",M).order("event_date",{ascending:!0}).limit(50);P?r({title:"Could not load events",description:P.message,variant:"destructive"}):i(I||[]),o(!1)})())},[s,r]);const j=k.useMemo(()=>n.filter(M=>M.email&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(M.email)),[n]),C=()=>{if(!_){r({title:"Pick an event first",variant:"destructive"});return}if(j.length===0){r({title:"No valid recipient emails",variant:"destructive"});return}v(!0)},A=async()=>{if(_){v(!1),x(!0);try{const{data:{session:M}}=await V.auth.getSession(),I=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/admin-send-event-invite",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${M==null?void 0:M.access_token}`},body:JSON.stringify({event_id:_.id,recipients:j.map(U=>({email:U.email,name:U.name,user_id:U.id})),custom_subject:u.trim()||void 0,custom_intro:m.trim()||void 0})}),P=await I.json().catch(()=>({}));if(!I.ok)throw new Error((P==null?void 0:P.error)||"Failed to send event invite");const R=(P==null?void 0:P.sent)??0,O=(P==null?void 0:P.failed)??0,B=(P==null?void 0:P.already_invited)??0;r({title:"Invites sent",description:`Sent: ${R}${B?` · Skipped (already invited): ${B}`:""}${O?` · Failed: ${O}`:""}`}),t(!1),p(""),h(""),d("")}catch(M){const I=M instanceof Error?M.message:"Send failed";r({title:"Send failed",description:I,variant:"destructive"})}finally{x(!1)}}};return e.jsxs(e.Fragment,{children:[e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(Vs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(pn,{className:"h-5 w-5 text-primary"}),"Send Event Invite"]}),e.jsxs(Cr,{children:["Send a beautiful event invitation to ",j.length," selected member",j.length===1?"":"s",".",n.length!==j.length&&e.jsxs("span",{className:"block text-amber-600 mt-1",children:[n.length-j.length," skipped (missing or invalid email)"]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(re,{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(Jt,{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(bs,{value:c,onValueChange:d,children:[e.jsx(ys,{id:"event-select",children:e.jsx(_s,{placeholder:"Pick an upcoming event..."})}),e.jsx(vs,{children:a.map(M=>e.jsx(We,{value:M.id,children:e.jsxs("div",{className:"flex flex-col text-left",children:[e.jsx("span",{className:"font-medium",children:M.title}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[Jht(M.event_date),!M.is_published&&" · (Draft)"]})]})},M.id))})]})]}),_&&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(ha,{className:"h-4 w-4 text-primary"}),_.title]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:Jht(_.event_date)}),_.description&&e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2 mt-1",children:_.description})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"subject",children:"Subject line (optional)"}),e.jsx(be,{id:"subject",placeholder:_?`You're invited: ${_.title}`:"You're invited to...",value:u,onChange:M=>h(M.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(re,{htmlFor:"intro",children:"Personal message (optional)"}),e.jsx(Ls,{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:m,onChange:M=>p(M.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 (",j.length,")"]}),e.jsxs("div",{className:"flex flex-wrap gap-1 max-h-24 overflow-y-auto",children:[j.slice(0,30).map(M=>e.jsx(qe,{variant:"secondary",className:"text-xs font-normal",children:M.name||M.email},M.id)),j.length>30&&e.jsxs(qe,{variant:"outline",className:"text-xs",children:["+",j.length-30," more"]})]})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),disabled:g,children:"Cancel"}),e.jsx($,{onClick:C,disabled:g||!c||j.length===0,children:g?e.jsxs(e.Fragment,{children:[e.jsx(Jt,{className:"h-4 w-4 mr-2 animate-spin"})," Sending..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Wr,{className:"h-4 w-4 mr-2"})," Send to ",j.length]})})]})]})}),e.jsx(oc,{open:y,onOpenChange:v,children:e.jsxs(Ql,{children:[e.jsxs(Jl,{children:[e.jsx(tc,{children:"Send event invite?"}),e.jsx(sc,{children:_?e.jsxs(e.Fragment,{children:["Send invite for ",e.jsxs("span",{className:"font-medium text-foreground",children:['"',_.title,'"']})," to"," ",e.jsxs("span",{className:"font-medium text-foreground",children:[j.length," member",j.length===1?"":"s"]}),"?"]}):null})]}),e.jsxs(ec,{children:[e.jsx(nc,{children:"Cancel"}),e.jsxs(Vl,{onClick:A,children:[e.jsx(Wr,{className:"h-4 w-4 mr-2"})," Send"]})]})]})})]})}const PVs=()=>{var za;const s=Jn(),{user:t,isAdmin:n}=ks(),{startImpersonation:r,isLoading:a}=C3e(),{toast:i}=Fi(),[l,o]=k.useState([]),[c,d]=k.useState([]),[u,h]=k.useState([]),[m,p]=k.useState({}),[g,x]=k.useState(!0),[y,v]=k.useState({}),[_,j]=k.useState(!1),[C,A]=k.useState({email:"",name:"",password:"",brokerage_id:"",role:"user",phone:"",trial_days:""}),[M,I]=k.useState(!1),[P,R]=k.useState(""),[O,B]=k.useState(1),[U,G]=k.useState(50),[H,Y]=k.useState("all"),[se,ee]=k.useState("all"),[oe,me]=k.useState("all"),[Q,te]=k.useState("all"),[le,fe]=k.useState("all"),[_e,ve]=k.useState(!1),[he,Se]=k.useState(!1),[Te,Ie]=k.useState(!1),[Ue,Be]=k.useState(null),[je,Ye]=k.useState(null),[Ee,Re]=k.useState(!1),[ke,Fe]=k.useState({name:"",email:"",brokerage_id:"",phone:""}),[Oe,Ge]=k.useState(null),[yt,tt]=k.useState(!1),[ut,nt]=k.useState(""),[et,at]=k.useState(!1),[wt,rt]=k.useState(!1),[Ft,Ut]=k.useState(null),[Is,xs]=k.useState(""),[st,dt]=k.useState(!1),[jt,gt]=k.useState(!1),[rs,Ns]=k.useState(null),[us,Bs]=k.useState(!1),[Ts,Fn]=k.useState(!1),[An,js]=k.useState(null),[In,un]=k.useState(""),[jr,Ln]=k.useState(!1),[Sr,Qn]=k.useState({email:"",name:"",password:"",phone:""}),[En,pr]=k.useState(!1),[xn,Ar]=k.useState(null),[Zr,dn]=k.useState([]),[Kt,Er]=k.useState("none"),[ti,Ba]=k.useState(!1),[lo,Yn]=k.useState(""),[Hr,Ur]=k.useState(!1),[Ei,fo]=k.useState(!1),[co,Tn]=k.useState(""),[Mr,Aa]=k.useState(new Set),[Lo,Ac]=k.useState(!1),[vl,Ol]=k.useState(!1),[To,_a]=k.useState(null),[$o,jh]=k.useState(!1),[Mu,dh]=k.useState(null),[Jr,Uo]=k.useState([]),[fc,Lc]=k.useState([]),[Ss,wa]=k.useState(!1),[Ci,fa]=k.useState({});k.useEffect(()=>{!t||!n||(Rr(),ja())},[t,n]);const zn=async()=>{try{const{data:Rt,error:tn}=await V.from("brokerage_manager_assignments").select("user_id, brokerage_id");if(tn)throw tn;const yn={};for(const xr of Rt??[])yn[xr.brokerage_id]||(yn[xr.brokerage_id]=[]),yn[xr.brokerage_id].push(xr.user_id);p(yn)}catch(Rt){console.error("Error loading brokerage manager assignments:",Rt)}},Rr=async()=>{try{x(!0);const{data:Rt,error:tn}=await V.functions.invoke("get-user-details");if(tn)throw tn;const yn=Rt.users||[];o(yn),h(Rt.brokerages||[]),await zn();const xr=yn.filter($r=>$r.roles.includes("assistant"));if(xr.length>0){const $r=xr.map(xa=>xa.id),{data:Ca}=await V.from("agent_assistant_assignments").select("agent_id, assistant_id").in("assistant_id",$r);if(Ca&&Ca.length>0){const xa=[...new Set(Ca.map(Ri=>Ri.agent_id))],{data:Oa}=await V.from("profiles").select("id, name, email").in("id",xa),jl={};for(const Ri of Ca){const Ki=Oa==null?void 0:Oa.find(Rc=>Rc.id===Ri.agent_id);Ki&&(jl[Ri.assistant_id]={agent_name:Ki.name||"",agent_email:Ki.email||""})}fa(jl)}}}catch(Rt){console.error("Error loading members:",Rt),i({title:"Error",description:"Failed to load members",variant:"destructive"})}finally{x(!1)}},ja=async()=>{try{const{data:Rt,error:tn}=await V.from("app_tiles").select("id, name, icon, app_id, required_tags").order("name");if(tn)throw tn;d(Rt||[])}catch(Rt){console.error("Error loading apps:",Rt),i({title:"Error",description:"Failed to load apps",variant:"destructive"})}},Il=async Rt=>{if(!ke.name.trim()||!ke.email.trim()){i({title:"Error",description:"Name and email are required",variant:"destructive"});return}if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(ke.email)){i({title:"Error",description:"Please enter a valid email address",variant:"destructive"});return}try{const{error:yn}=await V.from("profiles").update({name:ke.name.trim(),email:ke.email.trim(),brokerage_id:ke.brokerage_id||null,phone:ke.phone.trim()||null}).eq("id",Rt);if(yn)throw yn;i({title:"Success",description:"Member details updated successfully"}),Be(null),Rr()}catch(yn){console.error("Error updating member:",yn),i({title:"Error",description:yn.message||"Failed to update member",variant:"destructive"})}},zo=async Rt=>{try{const{data:{session:tn}}=await V.auth.getSession(),yn=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/resend-welcome-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${tn==null?void 0:tn.access_token}`},body:JSON.stringify({userId:Rt})}),xr=await yn.json();if(!yn.ok)throw new Error(xr.error||"Failed to resend welcome email");i({title:"Success",description:"Welcome email sent successfully"})}catch(tn){console.error("Error resending welcome email:",tn),i({title:"Error",description:tn.message||"Failed to resend welcome email",variant:"destructive"})}},Hl=async(Rt,tn)=>{try{const{error:yn}=await V.functions.invoke("send-password-reset",{body:{email:Rt,redirectTo:window.location.origin}});if(yn)throw yn;i({title:"Password Reset Sent",description:`Password reset email sent to ${tn}`})}catch(yn){console.error("Error sending password reset:",yn),i({title:"Error",description:yn.message||"Failed to send password reset email",variant:"destructive"})}},Cf=async(Rt,tn)=>{if(await io(`Are you sure you want to delete ${tn}? This action cannot be undone.`))try{const{data:{session:yn}}=await V.auth.getSession(),xr=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/delete-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${yn==null?void 0:yn.access_token}`},body:JSON.stringify({userId:Rt})}),$r=await xr.json();if(!xr.ok)throw new Error($r.error||"Failed to delete user");i({title:"Success",description:"User deleted successfully"}),Rr()}catch(yn){console.error("Error deleting user:",yn),i({title:"Error",description:yn.message||"Failed to delete user",variant:"destructive"})}},oi=async()=>{if(!C.email||!C.name||!C.password){i({title:"Error",description:"Please fill in all fields",variant:"destructive"});return}if(C.role==="brokerage_manager"&&!C.brokerage_id){i({title:"Error",description:"Please select a brokerage for this manager",variant:"destructive"});return}j(!0);try{const{data:{session:Rt}}=await V.auth.getSession(),tn=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/create-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Rt==null?void 0:Rt.access_token}`},body:JSON.stringify(C)}),yn=await tn.json();if(!tn.ok)throw new Error(yn.error||"Failed to create user");if(C.role&&C.role!=="user"&&yn.userId){const xr=C.role==="brokerage_manager"?C.brokerage_id:void 0;await Mo(yn.userId,C.role,"add",xr)}i({title:"Success",description:`User ${C.email} created successfully`}),A({email:"",name:"",password:"",brokerage_id:"",role:"user",phone:"",trial_days:""}),I(!1),Rr()}catch(Rt){console.error("Error creating user:",Rt),i({title:"Error",description:Rt.message||"Failed to create user",variant:"destructive"})}finally{j(!1)}},Mo=async(Rt,tn,yn,xr)=>{try{const{data:{session:$r}}=await V.auth.getSession(),Ca={userId:Rt,role:tn,action:yn};if(tn==="brokerage_manager"){if(!xr){i({title:"Error",description:"Please choose a brokerage for this manager assignment",variant:"destructive"});return}Ca.brokerageId=xr}const xa=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/manage-user-roles",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${$r==null?void 0:$r.access_token}`},body:JSON.stringify(Ca)}),Oa=await xa.json();if(!xa.ok)throw new Error(Oa.error||"Failed to manage user role");i({title:"Success",description:`Role ${yn==="add"?"added":"removed"} successfully`}),Rr()}catch($r){console.error("Error managing user role:",$r),i({title:"Error",description:$r.message||"Failed to manage user role",variant:"destructive"})}},zh=(Rt,tn)=>tn.length===0?!0:tn.some(yn=>Rt.includes(yn)),Gm=async(Rt,tn,yn)=>{const xr=`${Rt}-${tn.id}`;Ge(xr);try{if(yn){const $r=l.find(xa=>xa.id===Rt),Ca=tn.required_tags.filter(xa=>$r==null?void 0:$r.tags.includes(xa));for(const xa of Ca){const{error:Oa}=await V.from("user_tags").delete().eq("user_id",Rt).eq("tag",xa);if(Oa)throw Oa}i({title:"Access Removed",description:`Removed access to ${tn.name}`})}else if(tn.required_tags.length>0){const{error:$r}=await V.from("user_tags").insert({user_id:Rt,tag:tn.required_tags[0]});if($r)throw $r;i({title:"Access Granted",description:`Granted access to ${tn.name}`})}await Rr()}catch($r){console.error("Error toggling access:",$r),i({title:"Error",description:$r.message||"Failed to update access",variant:"destructive"})}finally{Ge(null)}},Gu=async()=>{const Rt=ut.trim();if(!Rt){i({title:"Error",description:"Brokerage name is required",variant:"destructive"});return}if(Rt.length>100){i({title:"Error",description:"Brokerage name must be less than 100 characters",variant:"destructive"});return}if(u.find(yn=>yn.name.toLowerCase()===Rt.toLowerCase())){i({title:"Error",description:"A brokerage with this name already exists",variant:"destructive"});return}at(!0);try{const{error:yn}=await V.from("brokerages").insert({name:Rt});if(yn)throw yn;i({title:"Success",description:`Brokerage "${Rt}" created successfully`}),nt(""),tt(!1),Rr()}catch(yn){console.error("Error creating brokerage:",yn),i({title:"Error",description:yn.message||"Failed to create brokerage",variant:"destructive"})}finally{at(!1)}},Zd=Rt=>{Ut(Rt),xs(Rt.name),rt(!0)},Bh=()=>{Ut(null),xs(""),rt(!1)},Mg=async()=>{if(!Ft)return;const Rt=Is.trim();if(!Rt){i({title:"Error",description:"Brokerage name is required",variant:"destructive"});return}if(Rt.length>100){i({title:"Error",description:"Brokerage name must be less than 100 characters",variant:"destructive"});return}dt(!0);try{const{error:tn}=await V.from("brokerages").update({name:Rt}).eq("id",Ft.id);if(tn)throw tn;i({title:"Success",description:"Brokerage updated successfully"}),Bh(),Rr()}catch(tn){console.error("Error updating brokerage:",tn),i({title:"Error",description:tn.message||"Failed to update brokerage",variant:"destructive"})}finally{dt(!1)}},Sd=async(Rt,tn)=>{var yn;if(!tn||typeof tn!="string"){i({title:"Error",description:"Please select a brokerage first",variant:"destructive"});return}try{const xr={userId:Rt,role:"brokerage_manager",action:"add",brokerageId:tn};console.debug("[assignManagerToBrokerage] payload",xr);const{data:{session:$r}}=await V.auth.getSession(),Ca=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/manage-user-roles",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${$r==null?void 0:$r.access_token}`},body:JSON.stringify(xr)}),xa=await Ca.json();if(!Ca.ok&&!((yn=xa.error)!=null&&yn.includes("duplicate")))throw new Error(xa.error||"Failed to add role");i({title:"Success",description:"Manager assigned to brokerage"}),await Rr()}catch(xr){console.error("Error assigning manager:",xr),i({title:"Error",description:xr.message||"Failed to assign manager",variant:"destructive"})}},$h=Rt=>{Ns(Rt),gt(!0)},Af=async()=>{if(rs){Bs(!0);try{const Rt=l.filter(xr=>xr.brokerage_id===rs.id),{data:{session:tn}}=await V.auth.getSession();for(const xr of Rt){const $r=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/delete-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${tn==null?void 0:tn.access_token}`},body:JSON.stringify({userId:xr.id})});if(!$r.ok){const Ca=await $r.json();console.error(`Failed to delete user ${xr.email}:`,Ca.error)}}const{error:yn}=await V.from("brokerages").delete().eq("id",rs.id);if(yn)throw yn;i({title:"Success",description:`Brokerage "${rs.name}" and ${Rt.length} member(s) deleted`}),gt(!1),Ns(null),Rr()}catch(Rt){console.error("Error deleting brokerage:",Rt),i({title:"Error",description:Rt.message||"Failed to delete brokerage",variant:"destructive"})}finally{Bs(!1)}}},Gp=Rt=>{js(Rt),un(""),Fn(!0)},Ef=()=>{js(null),un(""),Fn(!1)},Wx=async Rt=>{try{const{error:tn}=await V.from("profiles").update({brokerage_id:null}).eq("id",Rt);if(tn)throw tn;i({title:"Success",description:"User removed from brokerage"}),Rr()}catch(tn){console.error("Error removing user from brokerage:",tn),i({title:"Error",description:tn.message||"Failed to remove user",variant:"destructive"})}},rl=async(Rt,tn)=>{try{const{error:yn}=await V.from("profiles").update({brokerage_id:tn}).eq("id",Rt);if(yn)throw yn;i({title:"Success",description:"User added to brokerage"}),Rr()}catch(yn){console.error("Error adding user to brokerage:",yn),i({title:"Error",description:yn.message||"Failed to add user",variant:"destructive"})}};k.useEffect(()=>{(async()=>{var tn;if(!(An!=null&&An.id)){Ar(null),dn([]),Er("none");return}try{const{data:yn}=await V.from("partnership_programs").select("id, name, enabled").eq("brokerage_id",An.id).maybeSingle();if(!yn||!yn.enabled){Ar(null),dn([]),Er("none");return}const{data:xr}=await V.from("partnership_packages").select("id, name, description, sort_order").eq("program_id",yn.id).order("sort_order",{ascending:!0});Ar({id:yn.id,name:yn.name}),dn(xr||[]),Er(((tn=xr==null?void 0:xr[0])==null?void 0:tn.id)||"none")}catch(yn){console.error("Error loading partnership packages:",yn)}})()},[An==null?void 0:An.id]);const to=async()=>{if(!An||!Sr.email||!Sr.name||!Sr.password){i({title:"Error",description:"Please fill in all fields",variant:"destructive"});return}pr(!0);try{const{data:{session:Rt}}=await V.auth.getSession(),tn=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/create-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Rt==null?void 0:Rt.access_token}`},body:JSON.stringify({...Sr,brokerage_id:An.id,role:"user",partnershipPackageId:xn&&Kt!=="none"?Kt:void 0})}),yn=await tn.json();if(!tn.ok)throw new Error(yn.error||"Failed to create agent");i({title:"Success",description:`Agent ${Sr.email} created successfully`}),Qn({email:"",name:"",password:"",phone:""}),Ln(!1),Rr()}catch(Rt){console.error("Error creating agent:",Rt),i({title:"Error",description:Rt.message||"Failed to create agent",variant:"destructive"})}finally{pr(!1)}},Pg=Rt=>l.filter(tn=>tn.brokerage_id===Rt),Kx=Rt=>{const tn=Pg(Rt);if(!In)return tn;const yn=In.toLowerCase();return tn.filter(xr=>xr.name.toLowerCase().includes(yn)||xr.email.toLowerCase().includes(yn))},Tt=Rt=>l.filter(tn=>tn.brokerage_id!==Rt),He=l.filter(Rt=>{var yn;if(P){const xr=P.toLowerCase();if(!(Rt.name.toLowerCase().includes(xr)||Rt.email.toLowerCase().includes(xr)||((yn=Rt.brokerage_name)==null?void 0:yn.toLowerCase().includes(xr))))return!1}if(H==="claimed"&&!Rt.claimed||H==="unclaimed"&&Rt.claimed||se!=="all"&&!Rt.roles.includes(se))return!1;const tn=Rt.is_trial||Rt.subscription_status==="trialing";if(oe==="trial"&&!tn||oe==="non-trial"&&tn||Q==="none"&&Rt.brokerage_id||Q!=="all"&&Q!=="none"&&Rt.brokerage_id!==Q)return!1;if(le!=="all"){if(!Rt.created_at)return!1;const xr=parseInt(le,10),$r=Date.now()-xr*24*60*60*1e3;if(new Date(Rt.created_at).getTime()<$r)return!1}return!0}),{sortKey:ot,sortDirection:At,handleSort:Ht,sortData:qt}=Uee("created_at","desc"),Wt=qt(He,{name:Rt=>{var tn;return((tn=Rt.name)==null?void 0:tn.toLowerCase())||""},brokerage:Rt=>{var tn;return((tn=Rt.brokerage_name)==null?void 0:tn.toLowerCase())||""},status:Rt=>Rt.claimed?"active":"pending",role:Rt=>Rt.roles[0]||"",last_login:Rt=>Rt.last_sign_in_at?new Date(Rt.last_sign_in_at).getTime():null,created_at:Rt=>Rt.created_at?new Date(Rt.created_at).getTime():null}),Xt=Wt.length,ns=U===0,ps=ns?1:Math.ceil(Xt/U),Zs=ns?0:(O-1)*U,rn=ns?Xt:Zs+U,mn=Wt.slice(Zs,rn),qn=Rt=>{R(Rt),B(1)},Zn=Rt=>{G(Rt),B(1)},la=(Rt,tn)=>{Rt(tn),B(1)},Br=async(Rt,tn)=>{Se(!0);try{const yn=l.find(xa=>xa.id===Rt);if(!yn)return;const xr=yn.trial_expires_at?new Date(yn.trial_expires_at):new Date,$r=new Date(xr.getTime()+tn*24*60*60*1e3),{error:Ca}=await V.from("profiles").update({trial_expires_at:$r.toISOString()}).eq("id",Rt);if(Ca)throw Ca;i({title:"Trial Extended",description:`Trial extended by ${tn} days`}),Rr()}catch(yn){console.error("Error extending trial:",yn),i({title:"Error",description:yn.message||"Failed to extend trial",variant:"destructive"})}finally{Se(!1)}},wr=async Rt=>{Ie(!0);try{const{error:tn}=await V.from("profiles").update({is_trial:!1,trial_expires_at:null,trial_started_at:null,trial_claimed_at:null}).eq("id",Rt);if(tn)throw tn;i({title:"Account Converted",description:"User has been converted to a full account"}),Rr(),Ni()}catch(tn){console.error("Error converting trial:",tn),i({title:"Error",description:tn.message||"Failed to convert account",variant:"destructive"})}finally{Ie(!1)}},[Ea,na]=k.useState(!1),yi=async(Rt,tn)=>{if(await io(`Revert this user to a ${tn}-day free trial? This will clear their paid/grandfathered status. Any active Stripe subscription will need to be cancelled separately.`)){na(!0);try{const yn=new Date,xr=new Date(yn.getTime()+tn*24*60*60*1e3),{error:$r}=await V.from("profiles").update({is_trial:!0,trial_started_at:yn.toISOString(),trial_expires_at:xr.toISOString(),trial_claimed_at:yn.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",Rt);if($r)throw $r;i({title:"Reverted to Trial",description:`User is now on a ${tn}-day free trial.`}),Rr()}catch(yn){console.error("Error reverting to trial:",yn),i({title:"Error",description:yn.message||"Failed to revert to trial",variant:"destructive"})}finally{na(!1)}}},so=async Rt=>{wa(!0);try{const{data:tn}=await V.from("agent_assistant_assignments").select("id, assistant_id, permissions").eq("agent_id",Rt);if(tn&&tn.length>0){const xr=tn.map(Ca=>Ca.assistant_id),{data:$r}=await V.from("profiles").select("id, name, email").in("id",xr);Uo(tn.map(Ca=>{const xa=$r==null?void 0:$r.find(Oa=>Oa.id===Ca.assistant_id);return{id:Ca.id,assistant_id:Ca.assistant_id,assistant_name:(xa==null?void 0:xa.name)||"Unknown",assistant_email:(xa==null?void 0:xa.email)||"",permissions:Ca.permissions||{}}}))}else Uo([]);const{data:yn}=await V.from("agent_assistant_assignments").select("id, agent_id, permissions").eq("assistant_id",Rt);if(yn&&yn.length>0){const xr=yn.map(Ca=>Ca.agent_id),{data:$r}=await V.from("profiles").select("id, name, email").in("id",xr);Lc(yn.map(Ca=>{const xa=$r==null?void 0:$r.find(Oa=>Oa.id===Ca.agent_id);return{id:Ca.id,agent_id:Ca.agent_id,agent_name:(xa==null?void 0:xa.name)||"Unknown",agent_email:(xa==null?void 0:xa.email)||"",permissions:Ca.permissions||{}}}))}else Lc([])}catch(tn){console.error("Error loading assistant data:",tn)}finally{wa(!1)}},_i=Rt=>{Ye(Rt),Fe({name:Rt.name,email:Rt.email,brokerage_id:Rt.brokerage_id||"",phone:Rt.phone||""}),Re(!0),so(Rt.id)},Ni=()=>{Ye(null),Re(!1),Fe({name:"",email:"",brokerage_id:"",phone:""})},vi=async()=>{je&&(await Il(je.id),Ni())},qo=Rt=>{Aa(tn=>{const yn=new Set(tn);return yn.has(Rt)?yn.delete(Rt):yn.add(Rt),yn})},Ro=()=>{if(Mr.size===mn.length&&mn.every(Rt=>Mr.has(Rt.id))){const Rt=new Set(Mr);mn.forEach(tn=>Rt.delete(tn.id)),Aa(Rt)}else{const Rt=new Set(Mr);mn.forEach(tn=>Rt.add(tn.id)),Aa(Rt)}},Ti=()=>{Aa(new Set)},jo=async()=>{if(Mr.size===0)return;Ac(!0);let Rt=0,tn=0;try{const{data:{session:yn}}=await V.auth.getSession();for(const xr of Mr)try{(await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/resend-welcome-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${yn==null?void 0:yn.access_token}`},body:JSON.stringify({userId:xr})})).ok?Rt++:tn++}catch{tn++}i({title:"Bulk Email Complete",description:`Sent ${Rt} emails${tn>0?`, ${tn} failed`:""}`}),Ti()}catch(yn){i({title:"Error",description:yn.message||"Failed to send emails",variant:"destructive"})}finally{Ac(!1)}},Xe=async()=>{if(Mr.size===0)return;Ac(!0);let Rt=0,tn=0;try{const{data:{session:yn}}=await V.auth.getSession();for(const xr of Mr)try{(await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/send-password-reset",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${yn==null?void 0:yn.access_token}`},body:JSON.stringify({userId:xr})})).ok?Rt++:tn++}catch{tn++}i({title:"Bulk Password Reset Complete",description:`Sent ${Rt} reset emails${tn>0?`, ${tn} failed`:""}`}),Ti()}catch(yn){i({title:"Error",description:yn.message||"Failed to send password reset emails",variant:"destructive"})}finally{Ac(!1)}},Bt=async()=>{if(Mr.size===0)return;const Rt=l.filter($r=>Mr.has($r.id)).map($r=>$r.name).slice(0,5).join(", "),tn=Mr.size>5?` and ${Mr.size-5} more`:"";if(!await io(`Are you sure you want to delete ${Mr.size} users (${Rt}${tn})? This action cannot be undone.`))return;Ac(!0);let yn=0,xr=0;try{const{data:{session:$r}}=await V.auth.getSession();for(const Ca of Mr)try{(await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/delete-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${$r==null?void 0:$r.access_token}`},body:JSON.stringify({userId:Ca})})).ok?yn++:xr++}catch{xr++}i({title:"Bulk Delete Complete",description:`Deleted ${yn} users${xr>0?`, ${xr} failed`:""}`}),Ti(),Rr()}catch($r){i({title:"Error",description:$r.message||"Failed to delete users",variant:"destructive"})}finally{Ac(!1)}},As=async()=>{Ol(!0);try{const{data:{session:Rt}}=await V.auth.getSession(),tn=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/ghl-phone-sync",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Rt==null?void 0:Rt.access_token}`}});if(!tn.ok){const xr=await tn.json();throw new Error(xr.error||"Failed to sync phones")}const yn=await tn.json();i({title:"Phone Sync Complete",description:`Pulled ${yn.summary.pulledFromGHL} from GHL, pushed ${yn.summary.pushedToGHL} to GHL, ${yn.summary.alreadySynced} already synced`}),Rr()}catch(Rt){i({title:"Error",description:Rt.message||"Failed to sync phones with GHL",variant:"destructive"})}finally{Ol(!1)}},Hs=async(Rt,tn)=>{_a(Rt);try{const{data:{session:yn}}=await V.auth.getSession(),{data:xr}=await V.from("profiles").select("phone").eq("id",Rt).single(),$r=(xr==null?void 0:xr.phone)||"",Ca=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/ghl-tag-sync",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${yn==null?void 0:yn.access_token}`},body:JSON.stringify({email:tn,action:"update",phone:$r||void 0})});if(!Ca.ok){const Oa=await Ca.json();throw new Error(Oa.error||"Failed to sync with GHL")}const xa=await fetch(`https://services.leadconnectorhq.com/contacts/lookup?locationId=&email=${encodeURIComponent(tn)}`,{method:"GET",headers:{"Content-Type":"application/json"}});i({title:"Phone Synced",description:$r?`Phone ${$r} synced to GHL`:"Sync attempted - run bulk sync to pull phone from GHL"}),Rr()}catch(yn){i({title:"Error",description:yn.message||"Failed to sync phone",variant:"destructive"})}finally{_a(null)}},cn=async Rt=>{await r(Rt)},gr=()=>{if(Mr.size===0){i({title:"No members selected",description:"Please select members to export",variant:"destructive"});return}const Rt=l.filter(Oa=>Mr.has(Oa.id)),tn=["Name","Email","Phone","Brokerage","Roles","Status","Created At"],yn=Rt.map(Oa=>[Oa.name,Oa.email,Oa.phone||"",Oa.brokerage_name||"",Oa.roles.join("; "),Oa.claimed?"Claimed":"Unclaimed",new Date(Oa.created_at).toLocaleDateString()]),xr=[tn.join(","),...yn.map(Oa=>Oa.map(jl=>`"${(jl||"").replace(/"/g,'""')}"`).join(","))].join(` `),$r=new Blob([xr],{type:"text/csv"}),Ca=URL.createObjectURL($r),xa=document.createElement("a");xa.href=Ca,xa.download=`members-export-${new Date().toISOString().split("T")[0]}.csv`,xa.click(),URL.revokeObjectURL(Ca),i({title:"Export complete",description:`Exported ${Rt.length} member(s)`})},fr=()=>{if(He.length===0){i({title:"No members to export",description:"Adjust filters to include at least one member",variant:"destructive"});return}const Rt=["Name","Email","Phone","Brokerage","Roles","Status","Created At"],tn=He.map(Oa=>[Oa.name,Oa.email,Oa.phone||"",Oa.brokerage_name||"",Oa.roles.join("; "),Oa.claimed?"Claimed":"Unclaimed",Oa.created_at?new Date(Oa.created_at).toLocaleDateString():""]),yn=[Rt.join(","),...tn.map(Oa=>Oa.map(jl=>`"${(jl||"").replace(/"/g,'""')}"`).join(","))].join(` `),xr=new Blob([yn],{type:"text/csv"}),$r=URL.createObjectURL(xr),Ca=document.createElement("a"),xa=le!=="all"?`-last-${le}days`:"";Ca.href=$r,Ca.download=`members-export${xa}-${new Date().toISOString().split("T")[0]}.csv`,Ca.click(),URL.revokeObjectURL($r),i({title:"Export complete",description:`Exported ${He.length} member(s)`})};return g?e.jsx(Xs,{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(Xs,{title:"Members",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsx(nm,{title:"Member Management",description:"Manage users, roles, and permissions",children:e.jsxs($,{size:"sm",variant:"outline",onClick:()=>s("/admin/unassigned-members"),className:"gap-2",children:[e.jsx(Gd,{className:"h-4 w-4 text-amber-500"}),"Unassigned Members"]})}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs($,{size:"sm",variant:"outline",onClick:As,disabled:vl,children:[vl?e.jsx(Jt,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(ka,{className:"mr-2 h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:vl?"Syncing...":"Sync Phones with GHL"}),e.jsx("span",{className:"sm:hidden",children:vl?"Syncing...":"Sync GHL"})]}),e.jsxs($,{size:"sm",variant:"outline",onClick:()=>Ba(!0),children:[e.jsx(rk,{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(zs,{open:M,onOpenChange:I,children:[e.jsx(yl,{asChild:!0,children:e.jsxs($,{size:"sm",children:[e.jsx(Pl,{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(Rs,{children:[e.jsxs(Vs,{children:[e.jsx($s,{children:"Create New User"}),e.jsx(Cr,{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(re,{htmlFor:"name",children:"Name"}),e.jsx(be,{id:"name",placeholder:"John Doe",value:C.name,onChange:Rt=>A({...C,name:Rt.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"email",children:"Email"}),e.jsx(be,{id:"email",type:"email",placeholder:"john@example.com",value:C.email,onChange:Rt=>A({...C,email:Rt.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"password",children:"Password"}),e.jsx(be,{id:"password",type:"password",placeholder:"Min 6 characters",value:C.password,onChange:Rt=>A({...C,password:Rt.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"phone",children:"Phone (optional)"}),e.jsx(be,{id:"phone",type:"tel",placeholder:"555-123-4567",value:C.phone,onChange:Rt=>A({...C,phone:Rt.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(re,{htmlFor:"brokerage",children:["Brokerage",C.role==="brokerage_manager"?" (required)":""]}),e.jsxs(bs,{value:C.brokerage_id||"none",onValueChange:Rt=>A({...C,brokerage_id:Rt==="none"?"":Rt}),children:[e.jsx(ys,{id:"brokerage",children:e.jsx(_s,{placeholder:C.role==="brokerage_manager"?"Select brokerage":"Select brokerage (optional)"})}),e.jsxs(vs,{children:[e.jsx(We,{value:"none",children:"None"}),u.map(Rt=>e.jsx(We,{value:Rt.id,children:Rt.name},Rt.id))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"role",children:"Role"}),e.jsxs(bs,{value:C.role,onValueChange:Rt=>A({...C,role:Rt}),children:[e.jsx(ys,{id:"role",children:e.jsx(_s,{placeholder:"Select role"})}),e.jsxs(vs,{children:[e.jsx(We,{value:"user",children:"User"}),e.jsx(We,{value:"moderator",children:"Moderator"}),e.jsx(We,{value:"brokerage_manager",children:"Brokerage Manager"}),e.jsx(We,{value:"admin",children:"Admin"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"trial_days",children:"Trial Period (optional)"}),e.jsxs(bs,{value:C.trial_days||"none",onValueChange:Rt=>A({...C,trial_days:Rt==="none"?"":Rt}),children:[e.jsx(ys,{id:"trial_days",children:e.jsx(_s,{placeholder:"No trial (full access)"})}),e.jsxs(vs,{children:[e.jsx(We,{value:"none",children:"No trial (full access)"}),e.jsx(We,{value:"7",children:"7-day trial"}),e.jsx(We,{value:"30",children:"30-day trial"}),e.jsx(We,{value:"60",children:"60-day trial"}),e.jsx(We,{value:"90",children:"90-day trial"}),e.jsx(We,{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(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>I(!1),children:"Cancel"}),e.jsx($,{onClick:oi,disabled:_,children:_?"Creating...":"Create User"})]})]})]})]})]}),e.jsxs(ya,{defaultValue:new URLSearchParams(window.location.search).get("tab")||"members",className:"space-y-6",children:[e.jsxs(va,{children:[e.jsx(is,{value:"members",children:"Members"}),e.jsx(is,{value:"brokerages",children:"Brokerages"}),e.jsx(is,{value:"teams",children:"Teams"}),e.jsx(is,{value:"trials",children:"Trial Users"}),e.jsx(is,{value:"access",children:"Access Matrix"}),e.jsx(is,{value:"celebrations",children:"Celebrations"}),e.jsx(is,{value:"deletions",children:"Deletion Log"})]}),e.jsxs(cs,{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(Yr,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search members...",value:P,onChange:Rt=>qn(Rt.target.value),className:"pl-10 h-9"})]}),e.jsxs(bs,{value:H,onValueChange:Rt=>la(Y,Rt),children:[e.jsx(ys,{className:"w-[130px] h-9",children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"all",children:"All Status"}),e.jsx(We,{value:"claimed",children:"Active"}),e.jsx(We,{value:"unclaimed",children:"Pending"})]})]}),e.jsxs(bs,{value:se,onValueChange:Rt=>la(ee,Rt),children:[e.jsx(ys,{className:"w-[130px] h-9",children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"all",children:"All Roles"}),e.jsx(We,{value:"admin",children:"Admin"}),e.jsx(We,{value:"brokerage_manager",children:"Manager"}),e.jsx(We,{value:"assistant",children:"Assistant"}),e.jsx(We,{value:"user",children:"User"})]})]}),e.jsxs(bs,{value:oe,onValueChange:Rt=>la(me,Rt),children:[e.jsx(ys,{className:"w-[130px] h-9",children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"all",children:"All Users"}),e.jsx(We,{value:"trial",children:"Trial Only"}),e.jsx(We,{value:"non-trial",children:"Full Only"})]})]}),e.jsxs(bs,{value:Q,onValueChange:Rt=>la(te,Rt),children:[e.jsx(ys,{className:"w-[150px] h-9",children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"all",children:"All Brokerages"}),e.jsx(We,{value:"none",children:"No Brokerage"}),u.map(Rt=>e.jsx(We,{value:Rt.id,children:Rt.name},Rt.id))]})]}),e.jsxs(bs,{value:le,onValueChange:Rt=>la(fe,Rt),children:[e.jsx(ys,{className:"w-[150px] h-9",children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"all",children:"Any Join Date"}),e.jsx(We,{value:"30",children:"Joined Last 30 Days"}),e.jsx(We,{value:"60",children:"Joined Last 60 Days"}),e.jsx(We,{value:"90",children:"Joined Last 90 Days"})]})]}),e.jsxs($,{size:"sm",variant:"outline",className:"h-9",onClick:fr,title:"Export currently filtered members to CSV",children:[e.jsx(ji,{className:"h-4 w-4 mr-1"}),"Export Filtered"]}),(P||H!=="all"||se!=="all"||oe!=="all"||Q!=="all"||le!=="all")&&e.jsxs($,{variant:"ghost",size:"sm",className:"h-9",onClick:()=>{R(""),Y("all"),ee("all"),me("all"),te("all"),fe("all"),B(1)},children:[e.jsx(mr,{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:ns?`Showing all ${Xt} members`:`Showing ${Zs+1}-${Math.min(rn,Xt)} of ${Xt} members`}),e.jsxs(bs,{value:U.toString(),onValueChange:Rt=>Zn(Number(Rt)),children:[e.jsx(ys,{className:"h-9 w-[110px]",children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"50",children:"50 / page"}),e.jsx(We,{value:"100",children:"100 / page"}),e.jsx(We,{value:"250",children:"250 / page"}),e.jsx(We,{value:"0",children:"All"})]})]})]})]}),Mr.size>0&&e.jsxs("div",{className:"flex flex-col gap-2 p-3 bg-primary/10 border border-primary/20 rounded-lg",children:[mn.length>0&&mn.every(Rt=>Mr.has(Rt.id))&&Wt.length>Mr.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 ",Mr.size," on this page are selected."]}),e.jsxs($,{size:"sm",variant:"link",className:"h-auto p-0 text-primary",onClick:()=>Aa(new Set(Wt.map(Rt=>Rt.id))),children:["Select all ",Wt.length," filtered members"]})]}),Wt.length>0&&Mr.size===Wt.length&&e.jsxs("div",{className:"px-1 text-sm text-muted-foreground",children:["All ",Wt.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(r5,{className:"h-4 w-4 text-primary"}),e.jsxs("span",{className:"text-sm font-medium",children:[Mr.size," selected"]})]}),e.jsx("div",{className:"flex-1"}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs($,{size:"sm",variant:"outline",onClick:jo,disabled:Lo,children:[Lo?e.jsx(Jt,{className:"h-4 w-4 animate-spin mr-1"}):e.jsx(pn,{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($,{size:"sm",variant:"outline",onClick:Xe,disabled:Lo,children:[Lo?e.jsx(Jt,{className:"h-4 w-4 animate-spin mr-1"}):e.jsx(__,{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($,{size:"sm",variant:"outline",onClick:()=>ve(!0),disabled:Lo,className:"bg-primary/5 border-primary/30 text-primary hover:bg-primary/10",children:[e.jsx(nk,{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($,{size:"sm",variant:"outline",onClick:gr,children:[e.jsx(ji,{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($,{size:"sm",variant:"destructive",onClick:Bt,disabled:Lo,children:[Lo?e.jsx(Jt,{className:"h-4 w-4 animate-spin mr-1"}):e.jsx(Un,{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($,{size:"sm",variant:"ghost",onClick:Ti,disabled:Lo,children:e.jsx(mr,{className:"h-4 w-4"})})]})]})]}),e.jsx("div",{className:"border rounded-lg bg-card overflow-hidden",children:e.jsxs(Qa,{children:[e.jsx(Ja,{children:e.jsxs(vn,{className:"bg-muted/30 hover:bg-muted/30",children:[e.jsx(Dt,{className:"w-[50px]",children:e.jsx(Li,{checked:mn.length>0&&mn.every(Rt=>Mr.has(Rt.id)),onCheckedChange:Ro,"aria-label":"Select all on page"})}),e.jsx(Dh,{sortKey:"name",currentSortKey:ot,currentDirection:At,onSort:Ht,children:"Name"}),e.jsx(Dh,{sortKey:"brokerage",currentSortKey:ot,currentDirection:At,onSort:Ht,children:"Brokerage"}),e.jsx(Dh,{sortKey:"status",currentSortKey:ot,currentDirection:At,onSort:Ht,children:"Status"}),e.jsx(Dh,{sortKey:"role",currentSortKey:ot,currentDirection:At,onSort:Ht,children:"Role"}),e.jsx(Dh,{sortKey:"last_login",currentSortKey:ot,currentDirection:At,onSort:Ht,children:"Last Login"}),e.jsx(Dh,{sortKey:"created_at",currentSortKey:ot,currentDirection:At,onSort:Ht,children:"Member Since"}),e.jsx(Dt,{className:"w-[100px]"})]})}),e.jsx(ei,{children:mn.length===0?e.jsx(vn,{children:e.jsx(_t,{colSpan:8,className:"text-center py-12 text-muted-foreground",children:"No members found"})}):mn.map(Rt=>e.jsxs(vn,{className:`hover:bg-muted/30 ${Mr.has(Rt.id)?"bg-primary/5":""}`,children:[e.jsx(_t,{children:e.jsx(Li,{checked:Mr.has(Rt.id),onCheckedChange:()=>qo(Rt.id),"aria-label":`Select ${Rt.name}`})}),e.jsx(_t,{children:e.jsxs("div",{children:[e.jsx("button",{onClick:()=>_i(Rt),className:"text-primary hover:underline font-medium text-left",children:Rt.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:Rt.email})]})}),e.jsx(_t,{className:"text-muted-foreground",children:Rt.brokerage_name||"—"}),e.jsx(_t,{children:e.jsx("div",{className:"flex flex-col",children:(()=>{const tn=Rt.trial_expires_at||Rt.subscription_end_date;if((Rt.is_trial||Rt.subscription_status==="trialing")&&tn){const xr=Math.ceil((new Date(tn).getTime()-Date.now())/864e5),$r=xr<=0,Ca=xr<=3;return e.jsx(qe,{variant:"outline",className:Ot("w-fit",$r?"border-destructive text-destructive":Ca?"border-amber-500 text-amber-600":"border-violet-300 text-violet-700 bg-violet-50"),children:$r?"Trial Expired":`Trial · ${xr}d left`})}return e.jsx(qe,{variant:Rt.claimed?"default":"secondary",className:Rt.claimed?"bg-primary text-primary-foreground w-fit":"w-fit",children:Rt.claimed?"Active":"Pending"})})()})}),e.jsx(_t,{children:e.jsxs("div",{className:"flex flex-col",children:[Rt.roles.length>0?e.jsx("span",{className:"text-sm capitalize",children:Rt.roles[0]}):e.jsx("span",{className:"text-muted-foreground",children:"—"}),Rt.roles.includes("assistant")&&Ci[Rt.id]&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["→ ",Ci[Rt.id].agent_name||Ci[Rt.id].agent_email]})]})}),e.jsx(_t,{className:"text-muted-foreground",children:Rt.last_sign_in_at?new Date(Rt.last_sign_in_at).toLocaleDateString():"—"}),e.jsx(_t,{className:"text-muted-foreground",children:Rt.created_at?new Date(Rt.created_at).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}):"—"}),e.jsx(_t,{children:e.jsxs("div",{className:"flex gap-1 justify-end",children:[e.jsx($,{size:"icon",variant:"ghost",className:"h-8 w-8 text-yellow-500 hover:text-yellow-600 hover:bg-yellow-50",onClick:()=>{dh(Rt),jh(!0)},title:"Send celebration",children:e.jsx(jg,{className:"h-4 w-4"})}),e.jsx($,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>_i(Rt),title:"Edit member",children:e.jsx(ui,{className:"h-4 w-4"})}),e.jsx($,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>Hs(Rt.id,Rt.email),disabled:To===Rt.id,title:"Sync phone with GHL",children:To===Rt.id?e.jsx(Jt,{className:"h-4 w-4 animate-spin"}):e.jsx(ka,{className:"h-4 w-4"})}),e.jsx($,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>zo(Rt.id),title:"Resend welcome email",children:e.jsx(pn,{className:"h-4 w-4"})}),e.jsx($,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>Hl(Rt.email,Rt.name),title:"Send password reset",children:e.jsx(x3,{className:"h-4 w-4"})}),e.jsx($,{size:"icon",variant:"ghost",className:"h-8 w-8 text-blue-600 hover:text-blue-700 hover:bg-blue-50",onClick:()=>cn(Rt.id),disabled:a||Rt.id===(t==null?void 0:t.id),title:Rt.id===(t==null?void 0:t.id)?"Cannot impersonate yourself":`Login as ${Rt.name}`,children:a?e.jsx(Jt,{className:"h-4 w-4 animate-spin"}):e.jsx(U8,{className:"h-4 w-4"})}),e.jsx($,{size:"icon",variant:"ghost",className:"h-8 w-8 text-destructive hover:text-destructive hover:bg-destructive/10",onClick:()=>Cf(Rt.id,Rt.name),title:"Delete user",children:e.jsx(Un,{className:"h-4 w-4"})})]})})]},Rt.id))})]})}),ps>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 ",O," of ",ps]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx($,{variant:"outline",size:"sm",onClick:()=>B(1),disabled:O===1,children:"First"}),e.jsx($,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>B(Rt=>Math.max(1,Rt-1)),disabled:O===1,children:e.jsx(Ld,{className:"h-4 w-4"})}),e.jsx("div",{className:"flex items-center gap-1",children:Array.from({length:Math.min(5,ps)},(Rt,tn)=>{let yn;return ps<=5||O<=3?yn=tn+1:O>=ps-2?yn=ps-4+tn:yn=O-2+tn,e.jsx($,{variant:O===yn?"default":"outline",size:"sm",className:"h-8 w-8 p-0",onClick:()=>B(yn),children:yn},yn)})}),e.jsx($,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>B(Rt=>Math.min(ps,Rt+1)),disabled:O===ps,children:e.jsx(fi,{className:"h-4 w-4"})}),e.jsx($,{variant:"outline",size:"sm",onClick:()=>B(ps),disabled:O===ps,children:"Last"})]})]})]}),e.jsx(zs,{open:Ee,onOpenChange:Re,children:e.jsxs(Rs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(Vs,{children:[e.jsx($s,{children:"Edit Member"}),e.jsx(Cr,{children:"Update member details, roles, and app access"})]}),je&&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(re,{htmlFor:"edit-name",children:"Name"}),e.jsx(be,{id:"edit-name",value:ke.name,onChange:Rt=>Fe({...ke,name:Rt.target.value}),maxLength:100})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"edit-email",children:"Email"}),e.jsx(be,{id:"edit-email",type:"email",value:ke.email,onChange:Rt=>Fe({...ke,email:Rt.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(re,{htmlFor:"edit-phone",children:"Phone"}),e.jsx(be,{id:"edit-phone",type:"tel",value:ke.phone,onChange:Rt=>Fe({...ke,phone:Rt.target.value}),placeholder:"555-123-4567"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"edit-brokerage",children:"Brokerage"}),e.jsxs(bs,{value:ke.brokerage_id||"none",onValueChange:Rt=>Fe({...ke,brokerage_id:Rt==="none"?"":Rt}),children:[e.jsx(ys,{id:"edit-brokerage",children:e.jsx(_s,{placeholder:"Select brokerage"})}),e.jsxs(vs,{children:[e.jsx(We,{value:"none",children:"None"}),u.map(Rt=>e.jsx(We,{value:Rt.id,children:Rt.name},Rt.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:[je.roles.map(Rt=>e.jsxs(qe,{variant:"default",className:"gap-1",children:[e.jsx(Ng,{className:"h-3 w-3"}),Rt,Rt==="brokerage_manager"?e.jsx("span",{className:"text-xs text-muted-foreground ml-1",children:"(manage in Brokerages tab)"}):e.jsx("button",{onClick:()=>Mo(je.id,Rt,"remove"),className:"ml-1 rounded-full hover:bg-destructive/20",title:"Remove role",children:e.jsx(mr,{className:"h-3 w-3"})})]},Rt)),je.roles.length===0&&e.jsx("span",{className:"text-sm text-muted-foreground",children:"No roles assigned"})]}),e.jsxs(bs,{onValueChange:Rt=>Mo(je.id,Rt,"add"),children:[e.jsx(ys,{className:"w-[200px]",children:e.jsx(_s,{placeholder:"Add role..."})}),e.jsxs(vs,{children:[!je.roles.includes("admin")&&e.jsx(We,{value:"admin",children:"Admin"}),!je.roles.includes("user")&&e.jsx(We,{value:"user",children:"User"})]})]}),!je.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"})]}),(Jr.length>0||fc.length>0||je.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(Xn,{className:"h-4 w-4"}),"Assistant Relationships"]}),Ss?e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(Jt,{className:"h-4 w-4 animate-spin"}),"Loading..."]}):e.jsxs("div",{className:"space-y-3",children:[Jr.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:"}),Jr.map(Rt=>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:Rt.assistant_name}),e.jsx(qe,{variant:"outline",className:"text-xs",children:"Assistant"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:Rt.assistant_email}),e.jsx("div",{className:"flex flex-wrap gap-1 mt-1",children:Object.entries(Rt.permissions).filter(([,tn])=>tn).map(([tn])=>e.jsx(qe,{variant:"secondary",className:"text-[10px] capitalize",children:tn},tn))})]},Rt.id))]}),fc.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:"}),fc.map(Rt=>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:Rt.agent_name}),e.jsx(qe,{variant:"outline",className:"text-xs",children:"Agent"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:Rt.agent_email}),e.jsx("div",{className:"flex flex-wrap gap-1 mt-1",children:Object.entries(Rt.permissions).filter(([,tn])=>tn).map(([tn])=>e.jsx(qe,{variant:"secondary",className:"text-[10px] capitalize",children:tn},tn))})]},Rt.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(Rt=>{const tn=zh(je.tags,Rt.required_tags),yn=`${je.id}-${Rt.id}`,xr=Oe===yn,$r=Rt.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:Rt.icon}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-sm",children:Rt.name}),$r&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"Available to all members"})]})]}),e.jsx("div",{className:"flex items-center gap-2",children:xr?e.jsx(Jt,{className:"h-4 w-4 animate-spin text-muted-foreground"}):$r?e.jsx(qe,{variant:"secondary",className:"text-xs",children:"Always On"}):e.jsx(On,{checked:tn,onCheckedChange:()=>Gm(je.id,Rt,tn)})})]},Rt.id)})})]}),(je.is_trial||je.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(sa,{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:[je.trial_expires_at&&e.jsx(Xht,{expiresAt:je.trial_expires_at}),!je.trial_expires_at&&je.subscription_status==="trialing"&&je.subscription_end_date&&e.jsx(Xht,{expiresAt:je.subscription_end_date})]}),(je.trial_expires_at||je.subscription_end_date)&&e.jsxs("span",{className:"text-sm text-muted-foreground",children:["Expires: ",new Date(je.trial_expires_at||je.subscription_end_date).toLocaleDateString()]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs($,{size:"sm",variant:"outline",onClick:()=>Br(je.id,7),disabled:he,children:[e.jsx(i1,{className:"h-4 w-4 mr-1"}),"+7 Days"]}),e.jsxs($,{size:"sm",variant:"outline",onClick:()=>Br(je.id,14),disabled:he,children:[e.jsx(i1,{className:"h-4 w-4 mr-1"}),"+14 Days"]}),e.jsxs($,{size:"sm",variant:"outline",onClick:()=>Br(je.id,30),disabled:he,children:[e.jsx(i1,{className:"h-4 w-4 mr-1"}),"+30 Days"]}),e.jsxs($,{size:"sm",variant:"default",onClick:()=>wr(je.id),disabled:Te,className:"bg-green-600 hover:bg-green-700",children:[e.jsx(ck,{className:"h-4 w-4 mr-1"}),"Convert to Full Account"]})]}),je.trial_started_at&&e.jsxs("div",{className:"mt-3 text-xs text-muted-foreground",children:["Trial started: ",new Date(je.trial_started_at).toLocaleDateString(),je.trial_claimed_at&&e.jsxs("span",{children:[" • Claimed: ",new Date(je.trial_claimed_at).toLocaleDateString()]})]})]})]}),!(je.is_trial||je.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(sa,{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(Rt=>e.jsxs($,{size:"sm",variant:"outline",onClick:()=>yi(je.id,Rt),disabled:Ea,children:[e.jsx(i1,{className:"h-4 w-4 mr-1"}),Rt,"-day trial"]},Rt))})]})]}),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:[je.email_confirmed_at&&e.jsxs("div",{children:["Claimed: ",new Date(je.email_confirmed_at).toLocaleString()]}),je.last_sign_in_at&&e.jsxs("div",{children:["Last login: ",new Date(je.last_sign_in_at).toLocaleString()]}),e.jsxs("div",{children:["Created: ",new Date(je.created_at).toLocaleString()]})]})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:Ni,children:"Cancel"}),e.jsx($,{onClick:vi,children:"Save Changes"})]})]})}),e.jsxs(cs,{value:"access",children:[c.length===0?e.jsx(we,{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($,{onClick:()=>s("/admin/apps"),children:"Configure Apps"})]})}):e.jsxs(we,{children:[e.jsxs(Vt,{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4 space-y-0",children:[e.jsxs("div",{children:[e.jsx(Yt,{children:"Member Access Matrix"}),e.jsx(vr,{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(Yr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search agents by name or email...",value:P,onChange:Rt=>{R(Rt.target.value),B(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(Rt=>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:Rt.icon}),e.jsx("span",{className:"text-sm",children:Rt.name})]})},Rt.id))]})}),e.jsxs("tbody",{children:[mn.map(Rt=>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:Rt.name}),e.jsx("div",{className:"text-sm text-muted-foreground",children:Rt.email})]})}),c.map(tn=>{const yn=zh(Rt.tags,tn.required_tags),xr=`${Rt.id}-${tn.id}`,$r=Oe===xr;return e.jsx("td",{className:"p-4 text-center",children:e.jsx("div",{className:"flex items-center justify-center",children:$r?e.jsx(Jt,{className:"h-5 w-5 animate-spin text-muted-foreground"}):e.jsx(On,{checked:yn,onCheckedChange:()=>Gm(Rt.id,tn,yn),disabled:tn.required_tags.length===0})})},tn.id)})]},Rt.id)),mn.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"})})]})]})}),ps>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 ",Zs+1,"-",Math.min(rn,Xt)," of ",Xt," • Page ",O," of ",ps]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx($,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>B(Rt=>Math.max(1,Rt-1)),disabled:O===1,children:e.jsx(Ld,{className:"h-4 w-4"})}),e.jsx($,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>B(Rt=>Math.min(ps,Rt+1)),disabled:O===ps,children:e.jsx(fi,{className:"h-4 w-4"})})]})]})]})]}),e.jsx("div",{className:"mt-6",children:e.jsx($,{variant:"outline",onClick:()=>s("/admin/apps"),children:"Manage Apps"})})]}),e.jsxs(cs,{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(Yr,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search brokerages...",value:lo,onChange:Rt=>Yn(Rt.target.value),className:"pl-10"})]}),e.jsxs("span",{className:"text-sm text-muted-foreground whitespace-nowrap",children:[u.filter(Rt=>Rt.name.toLowerCase().includes(lo.toLowerCase())).length," of ",u.length," brokerages"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs($,{size:"sm",variant:"outline",onClick:()=>{const Rt=[];for(const xa of u){const Oa=m[xa.id]??[];for(const jl of Oa){const Ri=l.find(Ki=>Ki.id===jl);if(Ri){const Ki=(Ri.name||"").trim().split(/\s+/),Rc=Ki[0]||"",xd=Ki.slice(1).join(" ")||"";Rt.push({firstName:Rc,lastName:xd,email:Ri.email,brokerageName:xa.name})}}}if(Rt.length===0){i({title:"No managers found to export"});return}const yn=[["First Name","Last Name","Email","Brokerage Name"].join(","),...Rt.map(xa=>[xa.firstName,xa.lastName,xa.email,xa.brokerageName].map(Oa=>`"${(Oa||"").replace(/"/g,'""')}"`).join(","))].join(` `),xr=new Blob([yn],{type:"text/csv"}),$r=URL.createObjectURL(xr),Ca=document.createElement("a");Ca.href=$r,Ca.download=`brokerage-managers-${new Date().toISOString().slice(0,10)}.csv`,Ca.click(),URL.revokeObjectURL($r),i({title:`Exported ${Rt.length} managers`})},children:[e.jsx(ji,{className:"mr-2 h-4 w-4"}),"Export Managers"]}),e.jsxs(zs,{open:yt,onOpenChange:tt,children:[e.jsx(yl,{asChild:!0,children:e.jsxs($,{size:"sm",children:[e.jsx(Gi,{className:"mr-2 h-4 w-4"}),"Add Brokerage"]})}),e.jsxs(Rs,{children:[e.jsxs(Vs,{children:[e.jsx($s,{children:"Create New Brokerage"}),e.jsx(Cr,{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(re,{htmlFor:"brokerage-name",children:"Brokerage Name"}),e.jsx(be,{id:"brokerage-name",placeholder:"Enter brokerage name",value:ut,onChange:Rt=>nt(Rt.target.value),maxLength:100})]})}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>tt(!1),children:"Cancel"}),e.jsx($,{onClick:Gu,disabled:et,children:et?"Creating...":"Create Brokerage"})]})]})]})]})]}),e.jsx("div",{className:"border rounded-lg bg-card overflow-hidden",children:e.jsxs(Qa,{children:[e.jsx(Ja,{children:e.jsxs(vn,{className:"bg-muted/30 hover:bg-muted/30",children:[e.jsx(Dt,{className:"font-semibold",children:"Brokerage Name"}),e.jsx(Dt,{className:"font-semibold",children:"Manager(s)"}),e.jsx(Dt,{className:"font-semibold",children:"Agents"}),e.jsx(Dt,{className:"w-[150px]"})]})}),e.jsx(ei,{children:(()=>{const Rt=u.filter(tn=>tn.name.toLowerCase().includes(lo.toLowerCase()));return Rt.length===0?e.jsx(vn,{children:e.jsx(_t,{colSpan:4,className:"text-center py-12 text-muted-foreground",children:lo?"No brokerages match your search":"No brokerages found"})}):Rt.map(tn=>{const yn=l.filter(xa=>xa.brokerage_id===tn.id),$r=(m[tn.id]??[]).map(xa=>l.find(Oa=>Oa.id===xa)).filter(Boolean),Ca=yn.length;return e.jsxs(vn,{className:"hover:bg-muted/30",children:[e.jsx(_t,{children:e.jsx("button",{onClick:()=>Zd(tn),className:"text-primary hover:underline font-medium",children:tn.name})}),e.jsx(_t,{children:$r.length>0?e.jsx("div",{className:"flex flex-wrap gap-1",children:$r.map(xa=>e.jsx(qe,{variant:"secondary",className:"text-xs",children:xa.name},xa.id))}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"No manager"})}),e.jsxs(_t,{children:[Ca," member",Ca!==1?"s":""]}),e.jsx(_t,{children:e.jsxs("div",{className:"flex gap-1 justify-end",children:[e.jsxs($,{size:"sm",variant:"outline",className:"h-8",onClick:()=>Gp(tn),children:[e.jsx(Xn,{className:"h-4 w-4 mr-1"}),"Manage"]}),e.jsx($,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>Zd(tn),title:"Edit brokerage",children:e.jsx(ui,{className:"h-4 w-4"})}),e.jsx($,{size:"icon",variant:"ghost",className:"h-8 w-8 text-destructive hover:text-destructive hover:bg-destructive/10",onClick:()=>$h(tn),title:"Delete brokerage",children:e.jsx(Un,{className:"h-4 w-4"})})]})})]},tn.id)})})()})]})}),e.jsx(zs,{open:wt,onOpenChange:rt,children:e.jsxs(Rs,{className:"max-w-lg",children:[e.jsxs(Vs,{children:[e.jsx($s,{children:"Edit Brokerage"}),e.jsx(Cr,{children:"Update brokerage details and manage managers"})]}),Ft&&e.jsxs("div",{className:"space-y-6 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"edit-brokerage-name",children:"Brokerage Name"}),e.jsx(be,{id:"edit-brokerage-name",value:Is,onChange:Rt=>xs(Rt.target.value),maxLength:100})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(re,{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 tn=(m[Ft.id]??[]).map(yn=>l.find(xr=>xr.id===yn)).filter(Boolean);return tn.length===0?e.jsx("span",{className:"text-sm text-muted-foreground",children:"No managers assigned"}):tn.map(yn=>e.jsxs(qe,{variant:"default",className:"gap-1",children:[e.jsx(Ng,{className:"h-3 w-3"}),yn.name,e.jsx("button",{onClick:()=>Mo(yn.id,"brokerage_manager","remove",Ft.id),className:"ml-1 rounded-full hover:bg-destructive/20",title:"Remove manager from this brokerage",children:e.jsx(mr,{className:"h-3 w-3"})})]},yn.id))})()}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-sm text-muted-foreground",children:"Assign manager from existing members:"}),e.jsxs(Xc,{open:Hr,onOpenChange:Ur,children:[e.jsx(Qc,{asChild:!0,children:e.jsxs($,{variant:"outline",role:"combobox","aria-expanded":Hr,className:"w-full justify-between",children:["Search for a member...",e.jsx(Yr,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(Bc,{className:"w-full p-0",align:"start",children:e.jsxs(M_,{children:[e.jsx(P_,{placeholder:"Search by name or email..."}),e.jsxs(I_,{className:"max-h-[200px]",children:[e.jsx(L_,{children:"No members found."}),e.jsx(Nb,{children:(()=>{const Rt=new Set(m[Ft.id]??[]);return l.filter(tn=>!Rt.has(tn.id)&&(n||tn.brokerage_id===Ft.id)).map(tn=>e.jsxs(rv,{value:`${tn.name} ${tn.email}`,onSelect:()=>{Sd(tn.id,Ft.id),Ur(!1)},children:[tn.name," (",tn.email,")"]},tn.id))})()})]})]})})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Members in this Brokerage"}),e.jsx("div",{className:"max-h-32 overflow-y-auto border rounded p-2",children:l.filter(Rt=>Rt.brokerage_id===Ft.id).length===0?e.jsx("span",{className:"text-sm text-muted-foreground",children:"No members"}):l.filter(Rt=>Rt.brokerage_id===Ft.id).map(Rt=>e.jsxs("div",{className:"text-sm py-1 flex items-center justify-between",children:[e.jsx("span",{children:Rt.name}),Rt.roles.includes("brokerage_manager")&&e.jsx(qe,{variant:"outline",className:"text-xs",children:"Manager"})]},Rt.id))})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:Bh,children:"Cancel"}),e.jsx($,{onClick:Mg,disabled:st,children:st?"Saving...":"Save Changes"})]})]})}),e.jsx(zs,{open:jt,onOpenChange:gt,children:e.jsxs(Rs,{children:[e.jsxs(Vs,{children:[e.jsx($s,{className:"text-destructive",children:"Delete Brokerage"}),e.jsxs(Cr,{children:['Are you sure you want to delete "',rs==null?void 0:rs.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 "',rs==null?void 0:rs.name,'"']}),e.jsxs("li",{children:["All ",l.filter(Rt=>Rt.brokerage_id===(rs==null?void 0:rs.id)).length," member(s) assigned to this brokerage"]}),e.jsx("li",{children:"All their data, roles, and access"})]})]})}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>gt(!1),children:"Cancel"}),e.jsx($,{variant:"destructive",onClick:Af,disabled:us,children:us?"Deleting...":"Yes, Delete Brokerage"})]})]})}),e.jsx(zs,{open:Ts,onOpenChange:Fn,children:e.jsxs(Rs,{className:"max-w-4xl max-h-[85vh] overflow-hidden flex flex-col",children:[e.jsxs(Vs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(Gi,{className:"h-5 w-5"}),"Manage ",An==null?void 0:An.name]}),e.jsx(Cr,{children:"Add, remove, or manage users in this brokerage"})]}),An&&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(Yr,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search members...",value:In,onChange:Rt=>un(Rt.target.value),className:"pl-10 h-9"})]}),e.jsxs(zs,{open:jr,onOpenChange:Ln,children:[e.jsx(yl,{asChild:!0,children:e.jsxs($,{size:"sm",children:[e.jsx(Pl,{className:"h-4 w-4 mr-1"}),"Add New Agent"]})}),e.jsxs(Rs,{children:[e.jsxs(Vs,{children:[e.jsx($s,{children:"Add New Agent"}),e.jsxs(Cr,{children:["Create a new agent for ",An.name]})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"agent-name",children:"Name"}),e.jsx(be,{id:"agent-name",placeholder:"John Doe",value:Sr.name,onChange:Rt=>Qn({...Sr,name:Rt.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"agent-email",children:"Email"}),e.jsx(be,{id:"agent-email",type:"email",placeholder:"john@example.com",value:Sr.email,onChange:Rt=>Qn({...Sr,email:Rt.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"agent-password",children:"Password"}),e.jsx(be,{id:"agent-password",type:"password",placeholder:"Min 6 characters",value:Sr.password,onChange:Rt=>Qn({...Sr,password:Rt.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"agent-phone",children:"Phone (optional)"}),e.jsx(be,{id:"agent-phone",type:"tel",placeholder:"555-123-4567",value:Sr.phone,onChange:Rt=>Qn({...Sr,phone:Rt.target.value})})]}),xn&&Zr.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(re,{htmlFor:"agent-package",children:[xn.name," Package"]}),e.jsxs(bs,{value:Kt,onValueChange:Er,children:[e.jsx(ys,{id:"agent-package",children:e.jsx(_s,{placeholder:"Select a package"})}),e.jsxs(vs,{children:[Zr.map(Rt=>e.jsx(We,{value:Rt.id,children:Rt.name},Rt.id)),e.jsx(We,{value:"none",children:"No package (full access)"})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:Kt==="none"?"Agent gets unrestricted access; welcome email has no package block.":((za=Zr.find(Rt=>Rt.id===Kt))==null?void 0:za.description)||"Entitlements and the welcome email reflect this package."})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>Ln(!1),children:"Cancel"}),e.jsx($,{onClick:to,disabled:En,children:En?"Creating...":"Create Agent"})]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(re,{className:"text-sm text-muted-foreground whitespace-nowrap",children:"Add existing user:"}),e.jsxs(Xc,{open:Ei,onOpenChange:fo,children:[e.jsx(Qc,{asChild:!0,children:e.jsxs($,{variant:"outline",role:"combobox","aria-expanded":Ei,className:"w-[300px] justify-between",children:["Select a user to add...",e.jsx(Yr,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(Bc,{className:"w-[300px] p-0",align:"start",children:e.jsxs(M_,{children:[e.jsx(P_,{placeholder:"Search users...",value:co,onValueChange:Tn}),e.jsxs(I_,{children:[e.jsx(L_,{children:"No users found."}),e.jsx(Nb,{children:Tt(An.id).filter(Rt=>co===""||Rt.name.toLowerCase().includes(co.toLowerCase())||Rt.email.toLowerCase().includes(co.toLowerCase())).map(Rt=>e.jsxs(rv,{value:`${Rt.name} ${Rt.email}`,onSelect:()=>{rl(Rt.id,An.id),fo(!1),Tn("")},children:[Rt.name," (",Rt.email,")"]},Rt.id))})]})]})})]})]}),e.jsx("div",{className:"flex-1 overflow-auto border rounded-lg",children:e.jsxs(Qa,{children:[e.jsx(Ja,{children:e.jsxs(vn,{className:"bg-muted/30 hover:bg-muted/30",children:[e.jsx(Dt,{className:"font-semibold",children:"Name"}),e.jsx(Dt,{className:"font-semibold",children:"Email"}),e.jsx(Dt,{className:"font-semibold",children:"Status"}),e.jsx(Dt,{className:"font-semibold",children:"Role"}),e.jsx(Dt,{className:"w-[120px]"})]})}),e.jsx(ei,{children:Kx(An.id).length===0?e.jsx(vn,{children:e.jsx(_t,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:In?"No matching members found":"No members in this brokerage"})}):Kx(An.id).map(Rt=>e.jsxs(vn,{className:"hover:bg-muted/30",children:[e.jsx(_t,{className:"font-medium",children:Rt.name}),e.jsx(_t,{className:"text-muted-foreground",children:Rt.email}),e.jsx(_t,{children:Rt.claimed?e.jsx(qe,{variant:"default",className:"bg-green-500/10 text-green-600 hover:bg-green-500/20",children:"Active"}):e.jsx(qe,{variant:"secondary",children:"Pending"})}),e.jsx(_t,{children:Rt.roles.includes("brokerage_manager")?e.jsxs(qe,{variant:"outline",className:"gap-1",children:[e.jsx(Ng,{className:"h-3 w-3"}),"Manager"]}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"Agent"})}),e.jsx(_t,{children:e.jsxs("div",{className:"flex gap-1 justify-end",children:[!Rt.claimed&&e.jsx($,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>zo(Rt.id),title:"Resend welcome email",children:e.jsx(pn,{className:"h-4 w-4"})}),e.jsx($,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>Wx(Rt.id),title:"Remove from brokerage",children:e.jsx(mr,{className:"h-4 w-4"})}),e.jsx($,{size:"icon",variant:"ghost",className:"h-8 w-8 text-blue-600 hover:text-blue-700 hover:bg-blue-50",onClick:()=>cn(Rt.id),disabled:a||Rt.id===(t==null?void 0:t.id),title:Rt.id===(t==null?void 0:t.id)?"Cannot impersonate yourself":`Login as ${Rt.name}`,children:a?e.jsx(Jt,{className:"h-4 w-4 animate-spin"}):e.jsx(U8,{className:"h-4 w-4"})}),e.jsx($,{size:"icon",variant:"ghost",className:"h-8 w-8 text-destructive hover:text-destructive hover:bg-destructive/10",onClick:()=>Cf(Rt.id,Rt.name),title:"Delete user",children:e.jsx(Un,{className:"h-4 w-4"})})]})})]},Rt.id))})]})}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[Pg(An.id).length," total member",Pg(An.id).length!==1?"s":""," •",Pg(An.id).filter(Rt=>Rt.roles.includes("brokerage_manager")).length," manager",Pg(An.id).filter(Rt=>Rt.roles.includes("brokerage_manager")).length!==1?"s":""]})]}),e.jsx(kr,{children:e.jsx($,{variant:"outline",onClick:Ef,children:"Close"})})]})})]}),e.jsx(cs,{value:"teams",children:e.jsx(TVs,{})}),e.jsx(cs,{value:"trials",children:e.jsx(pVs,{})}),e.jsx(cs,{value:"celebrations",children:e.jsx(fVs,{})}),e.jsx(cs,{value:"deletions",children:e.jsx(xVs,{})})]})]}),e.jsx(_Rt,{open:ti,onOpenChange:Ba,brokerages:u,onSuccess:Rr}),Mu&&e.jsx(wRt,{open:$o,onOpenChange:Rt=>{jh(Rt),Rt||dh(null)},userId:Mu.id,userName:Mu.name}),e.jsx(MVs,{open:_e,onOpenChange:ve,recipients:l.filter(Rt=>Mr.has(Rt.id)).map(Rt=>({id:Rt.id,name:Rt.name,email:Rt.email}))})]})};function IVs(){const{toast:s}=Fi(),t=ls(),[n,r]=k.useState(""),[a,i]=k.useState(new Set),[l,o]=k.useState({}),[c,d]=k.useState({}),[u,h]=k.useState(""),[m,p]=k.useState(!1),{data:g=[],isLoading:x}=pt({queryKey:["unassigned-members"],queryFn:async()=>{const{data:P,error:R}=await V.from("profiles").select("id, name, email, phone, created_at, subscription_status").is("brokerage_id",null).or("subscription_status.is.null,subscription_status.eq.none").order("created_at",{ascending:!1});if(R)throw R;return P||[]}}),{data:y=[]}=pt({queryKey:["brokerages-all"],queryFn:async()=>{const{data:P,error:R}=await V.from("brokerages").select("id, name").order("name");if(R)throw R;return P||[]}}),v=k.useMemo(()=>{const P=n.toLowerCase().trim();return P?g.filter(R=>(R.name||"").toLowerCase().includes(P)||(R.email||"").toLowerCase().includes(P)||(R.phone||"").toLowerCase().includes(P)):g},[g,n]),_=k.useMemo(()=>{var R;const P=new Map;for(const O of g){const B=(R=(O.email||"").split("@")[1])==null?void 0:R.toLowerCase();B&&(["gmail.com","yahoo.com","hotmail.com","outlook.com","icloud.com","aol.com","me.com","comcast.net"].includes(B)||P.set(B,(P.get(B)||0)+1))}return Array.from(P.entries()).sort((O,B)=>B[1]-O[1]).slice(0,10)},[g]),j=P=>{i(R=>{const O=new Set(R);return O.has(P)?O.delete(P):O.add(P),O})},C=()=>{a.size===v.length?i(new Set):i(new Set(v.map(P=>P.id)))},A=async(P,R)=>{if(R){d(O=>({...O,[P]:!0}));try{const{data:O,error:B}=await V.functions.invoke("assign-brokerage",{body:{userId:P,brokerageId:R}});if(B)throw B;if(O!=null&&O.error)throw new Error(O.error);s({title:"Assigned",description:"Member added to brokerage."}),t.invalidateQueries({queryKey:["unassigned-members"]}),i(U=>{const G=new Set(U);return G.delete(P),G})}catch(O){s({title:"Failed",description:O.message,variant:"destructive"})}finally{d(O=>({...O,[P]:!1}))}}},M=async()=>{if(!u||a.size===0)return;p(!0);let P=0,R=0;for(const O of a)try{const{data:B,error:U}=await V.functions.invoke("assign-brokerage",{body:{userId:O,brokerageId:u}});if(U||B!=null&&B.error)throw new Error((U==null?void 0:U.message)||B.error);P++}catch{R++}p(!1),s({title:`Assigned ${P}${R?`, ${R} failed`:""}`,description:"Bulk assignment complete.",variant:R?"destructive":"default"}),i(new Set),h(""),t.invalidateQueries({queryKey:["unassigned-members"]})},I=(P,R)=>{const O={...l};for(const B of g)(B.email||"").toLowerCase().endsWith(`@${P}`)&&(O[B.id]=R);o(O),s({title:"Suggestions applied",description:`Pre-filled brokerage for @${P}`})};return e.jsx(Xs,{children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(nm,{title:"Unassigned Members",description:"Members with no brokerage and no active subscription — likely missed brokerage invites."}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsxs(we,{children:[e.jsx(Vt,{className:"pb-2",children:e.jsxs(Yt,{className:"text-sm font-medium text-muted-foreground flex items-center gap-2",children:[e.jsx(Xn,{className:"h-4 w-4"})," Orphan members"]})}),e.jsx(De,{children:e.jsx("div",{className:"text-3xl font-bold",children:g.length})})]}),e.jsxs(we,{children:[e.jsx(Vt,{className:"pb-2",children:e.jsxs(Yt,{className:"text-sm font-medium text-muted-foreground flex items-center gap-2",children:[e.jsx(Gi,{className:"h-4 w-4"})," Selected"]})}),e.jsx(De,{children:e.jsx("div",{className:"text-3xl font-bold",children:a.size})})]}),e.jsxs(we,{children:[e.jsx(Vt,{className:"pb-2",children:e.jsxs(Yt,{className:"text-sm font-medium text-muted-foreground flex items-center gap-2",children:[e.jsx(kn,{className:"h-4 w-4"})," Top email domains"]})}),e.jsx(De,{children:e.jsx("div",{className:"text-3xl font-bold",children:_.length})})]})]}),_.length>0&&e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsx(Yt,{className:"text-base",children:"Domain suggestions"})}),e.jsx(De,{children:e.jsx("div",{className:"flex flex-wrap gap-2",children:_.map(([P,R])=>{const O=y.find(B=>B.name.toLowerCase().replace(/[^a-z0-9]/g,"").includes(P.split(".")[0].toLowerCase()));return e.jsxs("div",{className:"flex items-center gap-2 rounded-md border bg-muted/30 px-3 py-2",children:[e.jsxs("span",{className:"font-mono text-sm",children:["@",P]}),e.jsx(qe,{variant:"secondary",children:R}),e.jsxs(bs,{onValueChange:B=>I(P,B),defaultValue:O==null?void 0:O.id,children:[e.jsx(ys,{className:"h-8 w-[220px]",children:e.jsx(_s,{placeholder:"Apply brokerage…"})}),e.jsx(vs,{children:y.map(B=>e.jsx(We,{value:B.id,children:B.name},B.id))})]})]},P)})})})]}),e.jsxs(we,{children:[e.jsxs(Vt,{className:"flex flex-col md:flex-row md:items-center md:justify-between gap-4",children:[e.jsxs("div",{className:"relative w-full md:w-96",children:[e.jsx(Yr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{value:n,onChange:P=>r(P.target.value),placeholder:"Search name, email, phone…",className:"pl-9"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(bs,{value:u,onValueChange:h,children:[e.jsx(ys,{className:"w-[240px]",children:e.jsx(_s,{placeholder:"Bulk assign to brokerage…"})}),e.jsx(vs,{children:y.map(P=>e.jsx(We,{value:P.id,children:P.name},P.id))})]}),e.jsxs($,{onClick:M,disabled:!u||a.size===0||m,children:[m&&e.jsx(Jt,{className:"h-4 w-4 mr-2 animate-spin"}),"Assign ",a.size||""]})]})]}),e.jsx(De,{children:x?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(Jt,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):v.length===0?e.jsx("div",{className:"py-12 text-center text-muted-foreground",children:"🎉 No unassigned members."}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(Qa,{children:[e.jsx(Ja,{children:e.jsxs(vn,{children:[e.jsx(Dt,{className:"w-10",children:e.jsx(Li,{checked:a.size===v.length&&v.length>0,onCheckedChange:C})}),e.jsx(Dt,{children:"Name"}),e.jsx(Dt,{children:"Email"}),e.jsx(Dt,{children:"Signed up"}),e.jsx(Dt,{children:"Status"}),e.jsx(Dt,{children:"Assign to brokerage"}),e.jsx(Dt,{className:"w-24"})]})}),e.jsx(ei,{children:v.map(P=>{const R=l[P.id]||"";return e.jsxs(vn,{children:[e.jsx(_t,{children:e.jsx(Li,{checked:a.has(P.id),onCheckedChange:()=>j(P.id)})}),e.jsx(_t,{className:"font-medium",children:P.name||"—"}),e.jsx(_t,{className:"text-sm text-muted-foreground",children:P.email}),e.jsx(_t,{className:"text-sm text-muted-foreground",children:Zc(new Date(P.created_at),{addSuffix:!0})}),e.jsx(_t,{children:e.jsx(qe,{variant:"outline",children:P.subscription_status||"none"})}),e.jsx(_t,{children:e.jsxs(bs,{value:R,onValueChange:O=>o(B=>({...B,[P.id]:O})),children:[e.jsx(ys,{className:"h-9 w-[240px]",children:e.jsx(_s,{placeholder:"Pick brokerage…"})}),e.jsx(vs,{children:y.map(O=>e.jsx(We,{value:O.id,children:O.name},O.id))})]})}),e.jsx(_t,{children:e.jsx($,{size:"sm",disabled:!R||c[P.id],onClick:()=>A(P.id,R),children:c[P.id]?e.jsx(Jt,{className:"h-4 w-4 animate-spin"}):"Assign"})})]},P.id)})})]})})})]})]})})}const LVs=()=>{const[s,t]=k.useState([]),[n,r]=k.useState(!0),[a,i]=k.useState(!1),[l,o]=k.useState(""),[c,d]=k.useState(""),[u,h]=k.useState(""),[m,p]=k.useState("");k.useEffect(()=>{g()},[]);const g=async()=>{const{data:A,error:M}=await V.from("invite_codes").select("*").order("created_at",{ascending:!1});M?(ae.error("Failed to load invite codes"),console.error(M)):t(A||[]),r(!1)},x=async A=>{if(A.preventDefault(),!l.trim()){ae.error("Please enter a code");return}i(!0);const{error:M}=await V.from("invite_codes").insert({code:l.trim().toUpperCase(),description:c.trim()||null,max_uses:u?parseInt(u):null,trial_days:m?parseInt(m):null});M?M.code==="23505"?ae.error("This code already exists"):(ae.error("Failed to create invite code"),console.error(M)):(ae.success("Invite code created"),o(""),d(""),h(""),p(""),g()),i(!1)},y=async(A,M)=>{const{error:I}=await V.from("invite_codes").update({is_active:!M}).eq("id",A);I?ae.error("Failed to update code"):t(s.map(P=>P.id===A?{...P,is_active:!M}:P))},v=async A=>{const{error:M}=await V.from("invite_codes").delete().eq("id",A);M?ae.error("Failed to delete code"):(ae.success("Code deleted"),t(s.filter(I=>I.id!==A)))},_="https://dashboard.relevelup.com",j=A=>{const M=`${_}/join?code=${A}`;navigator.clipboard.writeText(M),ae.success("Link copied to clipboard")},C=`${_}/join`;return e.jsx(Xs,{title:"Invite Codes",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(nm,{title:"Invite Codes",description:"Manage signup invite codes"}),e.jsxs(we,{children:[e.jsxs(Vt,{children:[e.jsx(Yt,{children:"Create New Code"}),e.jsxs(vr,{children:["Share link: ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded text-sm",children:C})]})]}),e.jsx(De,{children:e.jsxs("form",{onSubmit:x,className:"flex flex-wrap gap-4 items-end",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"code",children:"Code"}),e.jsx(be,{id:"code",placeholder:"WELCOME2024",value:l,onChange:A=>o(A.target.value),className:"w-40"})]}),e.jsxs("div",{className:"space-y-2 flex-1 min-w-[200px]",children:[e.jsx(re,{htmlFor:"description",children:"Description (optional)"}),e.jsx(be,{id:"description",placeholder:"For marketing campaign",value:c,onChange:A=>d(A.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"maxUses",children:"Max Uses"}),e.jsx(be,{id:"maxUses",type:"number",placeholder:"Unlimited",value:u,onChange:A=>h(A.target.value),className:"w-28"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"trialDays",children:"Trial Days"}),e.jsx(be,{id:"trialDays",type:"number",placeholder:"None",value:m,onChange:A=>p(A.target.value),className:"w-28"})]}),e.jsxs($,{type:"submit",disabled:a,children:[a?e.jsx(Jt,{className:"h-4 w-4 animate-spin"}):e.jsx(nn,{className:"h-4 w-4 mr-2"}),"Create"]})]})})]}),e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsx(Yt,{children:"Active Codes"})}),e.jsx(De,{children:n?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(Jt,{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(Qa,{children:[e.jsx(Ja,{children:e.jsxs(vn,{children:[e.jsx(Dt,{children:"Code"}),e.jsx(Dt,{children:"Description"}),e.jsx(Dt,{children:"Uses"}),e.jsx(Dt,{children:"Trial"}),e.jsx(Dt,{children:"Created"}),e.jsx(Dt,{children:"Active"}),e.jsx(Dt,{className:"w-24",children:"Actions"})]})}),e.jsx(ei,{children:s.map(A=>e.jsxs(vn,{children:[e.jsx(_t,{className:"font-mono font-medium",children:A.code}),e.jsx(_t,{className:"text-muted-foreground",children:A.description||"—"}),e.jsxs(_t,{children:[A.uses_count,A.max_uses&&` / ${A.max_uses}`]}),e.jsx(_t,{children:A.trial_days?e.jsxs("span",{className:"text-amber-600 dark:text-amber-400 font-medium",children:[A.trial_days," days"]}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx(_t,{className:"text-muted-foreground",children:Ys(new Date(A.created_at),"MMM d, yyyy")}),e.jsx(_t,{children:e.jsx(On,{checked:A.is_active,onCheckedChange:()=>y(A.id,A.is_active)})}),e.jsx(_t,{children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx($,{variant:"ghost",size:"icon",onClick:()=>j(A.code),title:"Copy invite link",children:e.jsx(Da,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>v(A.id),className:"text-destructive hover:text-destructive",title:"Delete code",children:e.jsx(Un,{className:"h-4 w-4"})})]})})]},A.id))})]})})]})]})})},l3=V;function fJn(s){if(!s)return null;const t=s.trim();if(!t)return null;if(/^[\w-]{8,20}$/.test(t))return t;const n=[/youtu\.be\/([\w-]{8,20})/,/[?&]v=([\w-]{8,20})/,/youtube\.com\/live\/([\w-]{8,20})/,/youtube\.com\/embed\/([\w-]{8,20})/];for(const r of n){const a=t.match(r);if(a)return a[1]}return null}function RVs(s){return s.toLowerCase().replace(/[^a-z0-9\s-]/g,"").trim().replace(/\s+/g,"-").slice(0,70)}const DVs="https://dashboard.relevelup.com";function pJn(s,t){const r=`${typeof window<"u"&&window.location.hostname==="localhost"?window.location.origin:DVs}/live/${s}`;return t?`${r}?i=${t}`:r}function gJn(){const s=ls(),t=pt({queryKey:["live-events"],queryFn:async()=>{const{data:i,error:l}=await l3.from("live_events").select("*").order("starts_at",{ascending:!1});if(l)throw l;return i||[]}}),n=Nt({mutationFn:async i=>{var d;const{data:l}=await V.auth.getUser(),{data:o,error:c}=await l3.from("live_events").insert({...i,created_by:(d=l.user)==null?void 0:d.id}).select().single();if(c)throw c;return o},onSuccess:()=>{s.invalidateQueries({queryKey:["live-events"]}),ae.success("Live event created")},onError:i=>ae.error((i==null?void 0:i.message)||"Could not create event")}),r=Nt({mutationFn:async({id:i,...l})=>{const{error:o}=await l3.from("live_events").update(l).eq("id",i);if(o)throw o},onSuccess:(i,l)=>{s.invalidateQueries({queryKey:["live-events"]}),s.invalidateQueries({queryKey:["live-event",l.id]}),ae.success("Saved")},onError:i=>ae.error((i==null?void 0:i.message)||"Could not save")}),a=Nt({mutationFn:async i=>{const{error:l}=await l3.from("live_events").delete().eq("id",i);if(l)throw l},onSuccess:()=>{s.invalidateQueries({queryKey:["live-events"]}),ae.success("Event deleted")},onError:i=>ae.error((i==null?void 0:i.message)||"Could not delete")});return{list:t,create:n,update:r,remove:a}}function xJn(s){return pt({queryKey:["live-event",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await l3.from("live_events").select("*").eq("id",s).maybeSingle();if(n)throw n;return t}})}function yJn(s){return pt({queryKey:["live-registrations",s],enabled:!!s,refetchInterval:2e4,queryFn:async()=>{const{data:t,error:n}=await l3.from("live_registrations").select("*").eq("event_id",s).order("created_at",{ascending:!1});if(n)throw n;return t||[]}})}function vJn(s){const t=ls(),n=pt({queryKey:["live-invites",s],enabled:!!s,queryFn:async()=>{const{data:i,error:l}=await l3.from("live_invites").select("*").eq("event_id",s).order("created_at",{ascending:!1});if(l)throw l;return i||[]}}),r=Nt({mutationFn:async i=>{const{data:l}=await V.auth.getUser(),o=i.map(u=>{var h;return{event_id:s,code:crypto.randomUUID().replace(/-/g,"").slice(0,12),name:u.name||null,email:u.email||null,phone:u.phone||null,brokerage:u.brokerage||null,created_by:(h=l.user)==null?void 0:h.id}}),{data:c,error:d}=await l3.from("live_invites").insert(o).select();if(d)throw d;return c||[]},onSuccess:i=>{t.invalidateQueries({queryKey:["live-invites",s]}),ae.success(`${i.length} invite link${i.length===1?"":"s"} created`)},onError:i=>ae.error((i==null?void 0:i.message)||"Could not create invites")}),a=Nt({mutationFn:async i=>{const{error:l}=await l3.from("live_invites").delete().eq("id",i);if(l)throw l},onSuccess:()=>t.invalidateQueries({queryKey:["live-invites",s]})});return{list:n,createMany:r,remove:a}}const qee=async s=>{try{const{data:t,error:n}=await V.from("push_notification_settings").select("is_enabled").eq("setting_key",s).maybeSingle();return n?(console.error("Error checking notification setting:",n),!0):(t==null?void 0:t.is_enabled)??!0}catch(t){return console.error("Error checking notification setting:",t),!0}},aV=async s=>{try{const{data:t,error:n}=await V.functions.invoke("send-push-notification",{body:s});return n?(console.error("Error sending notification:",n),{success:!1,error:n}):(console.log("Notification sent:",t),{success:!0,data:t})}catch(t){return console.error("Error sending notification:",t),{success:!1,error:t}}},OVs=async(s,t)=>await qee("new_templates")?aV({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}),FVs=async(s,t)=>aV({title:"New Academy Video",body:`New video added: ${s}`,url:`/academy/${t}`}),zVs=async(s,t)=>await qee("new_events")?aV({title:"New Event",body:`New event: ${s}`,url:`/events/${t}`}):(console.log("New event notifications are disabled"),{success:!1,skipped:!0}),BVs=async(s,t)=>await qee("new_toolbox")?aV({title:"New Resource Kit",body:`New resource kit available: ${s}`,url:`/toolbox/${t}`}):(console.log("New toolbox notifications are disabled"),{success:!1,skipped:!0}),sze=async(s,t)=>await qee("new_social_swag")?aV({title:"New Social Swag",body:`New social swag available: ${s}`,url:"/social-swag-2"}):(console.log("New social swag notifications are disabled"),{success:!1,skipped:!0}),$Vs=async(s,t)=>await qee("new_newsletters")?aV({title:"New Newsletter",body:`New newsletter available: ${s}`,url:`/newsletters/${t}`}):(console.log("New newsletter notifications are disabled"),{success:!1,skipped:!0}),tRe=400;function UVs(s){const t=new Date(s);return new Intl.DateTimeFormat("en-US",{weekday:"long",month:"short",day:"numeric",hour:"numeric",minute:"2-digit",timeZone:"America/New_York"}).format(t)+" ET"}async function qVs(){const s=[];let t=0;const n=1e3;for(;;){const{data:r,error:a}=await V.from("profiles").select("id, name, email, event_invite_opt_out").not("email","is",null).neq("email","").eq("event_invite_opt_out",!1).order("created_at",{ascending:!1}).range(t,t+n-1);if(a)throw a;if(!r||r.length===0)break;for(const i of r)i.email&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(i.email)&&s.push({id:i.id,name:i.name||"",email:i.email});if(r.length{if(!s||!n)return;let se=!1;return(async()=>{h(!0);try{const[ee,oe,me]=await Promise.all([qVs(),emt("event_registrations",n.id),emt("event_attendees",n.id)]);if(se)return;p(ee),x(oe),v(me)}catch(ee){se||r({title:"Could not load audience",description:ee instanceof Error?ee.message:"Unknown error",variant:"destructive"})}finally{se||h(!1)}})(),()=>{se=!0}},[s,n,r]),k.useEffect(()=>{s||(A(null),d(""),o(""),i("not_registered"))},[s]);const O=k.useMemo(()=>a==="all"?m:a==="not_registered"?m.filter(se=>!g.has(se.id)):m.filter(se=>g.has(se.id)&&!y.has(se.id)),[a,m,g,y]),B={all:m.length,not_registered:m.filter(se=>!g.has(se.id)).length,registered_never_attended:m.filter(se=>g.has(se.id)&&!y.has(se.id)).length},U=async(se,ee=!1)=>{const{data:{session:oe}}=await V.auth.getSession(),me=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/admin-send-event-invite",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${oe==null?void 0:oe.access_token}`},body:JSON.stringify({event_id:n.id,recipients:se.map(te=>({email:te.email,name:te.name,user_id:te.id})),custom_subject:l.trim()||void 0,custom_intro:c.trim()||void 0,force_resend:ee||void 0})}),Q=await me.json().catch(()=>({}));if(!me.ok)throw new Error((Q==null?void 0:Q.error)||`HTTP ${me.status}`);return{sent:(Q==null?void 0:Q.sent)??0,failed:(Q==null?void 0:Q.failed)??0,alreadyInvited:(Q==null?void 0:Q.already_invited)??0}},G=async()=>{var se;if(n){R(!0);try{const{data:{session:ee}}=await V.auth.getSession(),oe=ee==null?void 0:ee.user;if(!(oe!=null&&oe.email))throw new Error("No signed-in email found");const me=await U([{id:oe.id,name:((se=oe.user_metadata)==null?void 0:se.name)||"",email:oe.email}],!0);r({title:"Test sent",description:`Sent to ${oe.email} · Sent: ${me.sent} · Failed: ${me.failed}`})}catch(ee){r({title:"Test failed",description:ee instanceof Error?ee.message:"Unknown error",variant:"destructive"})}finally{R(!1)}}},H=async()=>{if(!(!n||O.length===0)){I(!1),j(!0),A({done:0,total:O.length,sent:0,failed:0});try{let se=0,ee=0,oe=0;for(let me=0;me!_&&t(se),children:e.jsxs(Rs,{className:"max-w-2xl max-h-[92vh] overflow-y-auto",children:[e.jsxs(Vs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(kn,{className:"h-5 w-5 text-primary"}),"Invite Members to Event"]}),e.jsx(Cr,{children:n?e.jsxs("span",{className:"flex items-center gap-2 text-sm",children:[e.jsx(wm,{className:"h-4 w-4"}),e.jsx("span",{className:"font-medium text-foreground",children:n.title}),e.jsx("span",{children:"·"}),e.jsx("span",{children:UVs(n.event_date)})]}):"Send a beautiful branded invite to members."})]}),e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(re,{className:"flex items-center gap-2",children:[e.jsx(Xn,{className:"h-4 w-4"})," Audience"]}),u?e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground py-2",children:[e.jsx(Jt,{className:"h-4 w-4 animate-spin"})," Loading members..."]}):e.jsxs(m_,{value:a,onValueChange:se=>i(se),className:"space-y-2",children:[e.jsxs("label",{htmlFor:"aud-not-reg",className:"flex items-start gap-3 rounded-lg border p-3 cursor-pointer hover:bg-muted/40 transition",children:[e.jsx(Yh,{value:"not_registered",id:"aud-not-reg",className:"mt-1"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"font-medium text-sm",children:"Members not yet registered"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Skip anyone already registered for this event. Best for weekly boost sends."})]}),e.jsx("span",{className:"text-sm font-semibold text-primary",children:B.not_registered.toLocaleString()})]}),e.jsxs("label",{htmlFor:"aud-all",className:"flex items-start gap-3 rounded-lg border p-3 cursor-pointer hover:bg-muted/40 transition",children:[e.jsx(Yh,{value:"all",id:"aud-all",className:"mt-1"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"font-medium text-sm",children:"All members with an email"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Everyone in the system. Use sparingly to avoid inbox fatigue."})]}),e.jsx("span",{className:"text-sm font-semibold text-primary",children:B.all.toLocaleString()})]}),e.jsxs("label",{htmlFor:"aud-reg-noatt",className:"flex items-start gap-3 rounded-lg border p-3 cursor-pointer hover:bg-muted/40 transition",children:[e.jsx(Yh,{value:"registered_never_attended",id:"aud-reg-noatt",className:"mt-1"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"font-medium text-sm",children:"Registered but haven't attended"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Nudge people who signed up but didn't join the Zoom."})]}),e.jsx("span",{className:"text-sm font-semibold text-primary",children:B.registered_never_attended.toLocaleString()})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{htmlFor:"ev-inv-subject",children:"Subject line (optional)"}),e.jsx(be,{id:"ev-inv-subject",placeholder:n?`You're invited: ${n.title}`:"You're invited to...",value:l,onChange:se=>o(se.target.value),disabled:_}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Leave blank for the default."})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{htmlFor:"ev-inv-intro",children:"Personal message (optional)"}),e.jsx(Ls,{id:"ev-inv-intro",placeholder:"e.g. Our Wednesday live training this week is on lead conversion. Grab your seat — it's a game-changer.",value:c,onChange:se=>d(se.target.value),rows:4,disabled:_}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Appears at the top of the email above the event details."})]}),C&&e.jsxs("div",{className:"rounded-lg border bg-muted/30 p-3 space-y-2",children:[e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsxs("span",{className:"text-muted-foreground",children:["Sending ",C.done.toLocaleString()," / ",C.total.toLocaleString()]}),e.jsxs("span",{className:"font-medium",children:["✓ ",C.sent.toLocaleString(),C.failed>0&&e.jsxs("span",{className:"text-destructive",children:[" · ✗ ",C.failed.toLocaleString()]})]})]}),e.jsx(ho,{value:Y})]})]}),e.jsxs(kr,{className:"gap-2 sm:gap-2",children:[e.jsx($,{variant:"outline",onClick:G,disabled:_||P||u,children:P?e.jsxs(e.Fragment,{children:[e.jsx(Jt,{className:"h-4 w-4 mr-2 animate-spin"})," Sending test..."]}):e.jsxs(e.Fragment,{children:[e.jsx(pn,{className:"h-4 w-4 mr-2"})," Send test to me"]})}),e.jsx($,{variant:"ghost",onClick:()=>t(!1),disabled:_,children:"Cancel"}),e.jsx($,{onClick:()=>I(!0),disabled:_||u||O.length===0,children:_?e.jsxs(e.Fragment,{children:[e.jsx(Jt,{className:"h-4 w-4 mr-2 animate-spin"})," Sending..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Wr,{className:"h-4 w-4 mr-2"})," Send to ",O.length.toLocaleString()]})})]})]})}),e.jsx(oc,{open:M,onOpenChange:I,children:e.jsxs(Ql,{children:[e.jsxs(Jl,{children:[e.jsx(tc,{children:"Send event invite?"}),e.jsxs(sc,{children:["This will send a branded invite to"," ",e.jsxs("span",{className:"font-semibold text-foreground",children:[O.length.toLocaleString()," member",O.length===1?"":"s"]})," ","for"," ",e.jsxs("span",{className:"font-semibold text-foreground",children:['"',n==null?void 0:n.title,'"']}),". This can't be undone."]})]}),e.jsxs(ec,{children:[e.jsx(nc,{children:"Cancel"}),e.jsxs(Vl,{onClick:H,children:[e.jsx(Wr,{className:"h-4 w-4 mr-2"})," Send now"]})]})]})})]})}const Yre={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 HVs(){const s=Jn(),t=ls(),[n,r]=k.useState(!1),[a,i]=k.useState(null),[l,o]=k.useState(Yre),[c,d]=k.useState(null),[u,h]=k.useState(null),[m,p]=k.useState(!1),g=k.useRef(null),[x,y]=k.useState(!1),[v,_]=k.useState(null),[j,C]=k.useState(!1),[A,M]=k.useState(null),[I,P]=k.useState(null),[R,O]=k.useState(!0),[B,U]=k.useState(""),[G,H]=k.useState(!1),[Y,se]=k.useState(null),{data:ee,isLoading:oe}=pt({queryKey:["admin-events"],queryFn:async()=>{const{data:et,error:at}=await V.from("events").select("*").order("event_date",{ascending:!0});if(at)throw at;return et}}),{data:me}=pt({queryKey:["event-registrations-count"],queryFn:async()=>{let et=[],at=0;const wt=1e3;for(;;){const{data:Ft,error:Ut}=await V.from("event_registrations").select("event_id").range(at,at+wt-1);if(Ut)throw Ut;if(!Ft||Ft.length===0||(et=et.concat(Ft),Ft.length{rt[Ft.event_id]=(rt[Ft.event_id]||0)+1}),rt}}),{data:Q,isLoading:te}=pt({queryKey:["event-registrations-details",v==null?void 0:v.id],queryFn:async()=>{if(!v)return[];const{data:et,error:at}=await V.from("event_registrations").select("id, user_id, registered_at, zoom_join_url, zoom_name, zoom_email").eq("event_id",v.id).order("registered_at",{ascending:!1});if(at)throw at;if(!et||et.length===0)return[];const wt=et.map(Ut=>Ut.user_id).filter(Boolean);let rt=[];if(wt.length>0){const{data:Ut,error:Is}=await V.from("profiles").select("id, name, email").in("id",wt);if(Is)throw Is;rt=Ut||[]}const Ft=new Map((rt==null?void 0:rt.map(Ut=>[Ut.id,Ut]))||[]);return et.map(Ut=>({...Ut,profiles:Ut.user_id&&Ft.get(Ut.user_id)||null}))},enabled:!!v}),{data:le,isLoading:fe}=pt({queryKey:["event-attendees-details",v==null?void 0:v.id],queryFn:async()=>{if(!v)return[];const{data:et,error:at}=await V.from("event_attendees").select("id, user_id, zoom_email, zoom_name, join_time, leave_time, duration_minutes, manually_added, created_at").eq("event_id",v.id).order("created_at",{ascending:!1});if(at)throw at;if(!et||et.length===0)return[];const wt=et.map(xs=>xs.user_id).filter(Boolean);let rt=[];if(wt.length>0){const{data:xs,error:st}=await V.from("profiles").select("id, name, email").in("id",wt);if(st)throw st;rt=xs||[]}const{data:Ft}=await V.from("agent_points").select("user_id").eq("event_id",v.id),Ut=new Set((Ft==null?void 0:Ft.map(xs=>xs.user_id))||[]),Is=new Map((rt==null?void 0:rt.map(xs=>[xs.id,xs]))||[]);return et.map(xs=>({...xs,profiles:xs.user_id&&Is.get(xs.user_id)||null,points_awarded:xs.user_id?Ut.has(xs.user_id):!1}))},enabled:!!v}),_e=et=>{_(et),y(!0)},ve=Nt({mutationFn:async et=>{const{data:{session:at}}=await V.auth.getSession();if(!at)throw new Error("Not authenticated");const wt=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/zoom-sync-registrations",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${at.access_token}`},body:JSON.stringify({event_id:et})}),rt=await wt.json();if(!wt.ok){const Ft=new Error(rt.error||"Failed to sync");throw Ft.scopeError=!!rt.scope_error,Ft.details=rt.scope_error?"In Zoom, make sure meeting:read:list_registrants:admin is not marked Optional, then Continue/Activate. If it already is required, update the saved Zoom credentials because the backend is using a different app.":void 0,Ft}return rt},onSuccess:et=>{if(t.invalidateQueries({queryKey:["event-registrations-details",v==null?void 0:v.id]}),t.invalidateQueries({queryKey:["event-registrations-count"]}),et!=null&&et.scope_error||(et==null?void 0:et.success)===!1){ae.error("Zoom needs one more authorization step",{description:et!=null&&et.scope_error?"The app is working, but Zoom is still issuing a token without meeting:read:list_registrants:admin. Make that scope required, not Optional, then Continue/Activate/Save in Zoom and retry. If it still shows 7 scopes, update the saved Zoom credentials to the app you edited.":(et==null?void 0:et.message)||"Zoom registration sync could not complete.",duration:2e4});return}ae.success(et.message)},onError:et=>{ae.error("Failed to sync Zoom registrations",{description:et.scopeError&&et.details||et.message,duration:et.scopeError?2e4:5e3})}}),he=Nt({mutationFn:async et=>{const{data:{session:at}}=await V.auth.getSession();if(!at)throw new Error("Not authenticated");const wt=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/zoom-sync-attendees",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${at.access_token}`},body:JSON.stringify({event_id:et})}),rt=await wt.json();if(!wt.ok)throw new Error(rt.error||"Failed to sync attendees");return rt},onSuccess:et=>{if(t.invalidateQueries({queryKey:["event-attendees-details",v==null?void 0:v.id]}),t.invalidateQueries({queryKey:["event-leaderboard"]}),t.invalidateQueries({queryKey:["admin-agent-points"]}),et!=null&&et.scope_error||(et==null?void 0:et.success)===!1){ae.error((et==null?void 0:et.message)||"Zoom sync failed",{description:et!=null&&et.scope_error?"Zoom must be re-authorized after adding the missing report scope.":void 0,duration:15e3});return}et!=null&&et.message?ae.success(et.message):ae.success(`Synced ${et.synced||0} attendees. ${et.points_awarded||0} points awarded!`)},onError:et=>{ae.error("Failed to sync attendees: "+et.message)}}),Se=Nt({mutationFn:async()=>{const{data:et,error:at}=await V.functions.invoke("zoom-retry-registrations",{body:{}});if(at)throw at;return et},onSuccess:et=>{t.invalidateQueries({queryKey:["event-registrations-details",v==null?void 0:v.id]}),t.invalidateQueries({queryKey:["event-registrations-count"]}),ae.success(`Retry complete: ${(et==null?void 0:et.successCount)??0} fixed, ${(et==null?void 0:et.failCount)??0} still failing, ${(et==null?void 0:et.rateLimitedCount)??0} rate-limited`)},onError:et=>{ae.error("Retry failed: "+et.message)}}),Te=Nt({mutationFn:async({eventId:et,testMode:at})=>{const{data:{session:wt}}=await V.auth.getSession();if(!wt)throw new Error("Not authenticated");const rt=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/send-event-reminder",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${wt.access_token}`},body:JSON.stringify({event_id:et,test_mode:at})}),Ft=await rt.json();if(!rt.ok)throw new Error(Ft.error||"Failed to send reminders");return Ft},onSuccess:et=>{et.test?ae.success(et.message||"Test email sent!"):ae.success(et.message||`Reminder emails sent to ${et.sent} registrants!`)},onError:et=>{ae.error("Failed to send reminders: "+et.message)}}),{data:Ie}=pt({queryKey:["all-profiles-for-linking"],queryFn:async()=>{let et=[],at=0;const wt=1e3;for(;;){const{data:rt,error:Ft}=await V.from("profiles").select("id, name, email").order("name",{ascending:!0}).range(at,at+wt-1);if(Ft)throw Ft;if(!rt||rt.length===0||(et=[...et,...rt],rt.length{const{error:Ft}=await V.from("event_attendees").update({user_id:at}).eq("id",et);if(Ft)throw Ft;if(rt&&wt){const{error:Is}=await V.from("zoom_email_aliases").upsert({user_id:at,zoom_email:wt.toLowerCase()},{onConflict:"zoom_email"});Is&&console.error("Failed to save alias:",Is)}const Ut=v==null?void 0:v.id;if(Ut){const{data:Is}=await V.from("user_roles").select("id").eq("user_id",at).eq("role","admin").single();if(!Is){const{data:xs}=await V.from("agent_points").select("id").eq("user_id",at).eq("event_id",Ut).single();xs||(await V.rpc("award_attendance_points",{p_user_id:at,p_event_id:Ut,p_points:10,p_reason:"Event Attendance (Manual Link)"}),await V.rpc("check_and_award_badges",{p_user_id:at}))}}return{userId:at,zoomEmail:wt,shouldSaveAlias:rt}},onSuccess:et=>{t.invalidateQueries({queryKey:["event-attendees-details",v==null?void 0:v.id]}),t.invalidateQueries({queryKey:["event-leaderboard"]}),t.invalidateQueries({queryKey:["admin-agent-points"]});let at="Attendee linked and points awarded!";et.shouldSaveAlias&&et.zoomEmail&&(at+=` Email "${et.zoomEmail}" will be auto-matched in the future.`),ae.success(at),C(!1),M(null),P(null),U("")},onError:et=>{ae.error("Failed to link attendee: "+et.message)}}),Be=et=>{M(et),P(null),O(!0),U(""),C(!0)},je=()=>{!A||!I||Ue.mutate({attendeeId:A.id,userId:I,zoomEmail:A.zoom_email,shouldSaveAlias:R})},Ye=(Ie==null?void 0:Ie.filter(et=>{var wt,rt;if(!B)return!0;const at=B.toLowerCase();return((wt=et.name)==null?void 0:wt.toLowerCase().includes(at))||((rt=et.email)==null?void 0:rt.toLowerCase().includes(at))}))||[],Ee=async et=>{const at=et.name.split(".").pop(),rt=`${`${crypto.randomUUID()}.${at}`}`,{error:Ft}=await V.storage.from("event-images").upload(rt,et);if(Ft)throw Ft;const{data:{publicUrl:Ut}}=V.storage.from("event-images").getPublicUrl(rt);return Ut},Re=et=>{var wt;const at=(wt=et.target.files)==null?void 0:wt[0];if(at){if(at.size>5*1024*1024){ae.error("Image must be less than 5MB");return}d(at),h(URL.createObjectURL(at))}},ke=()=>{d(null),h(null),o({...l,image_url:""}),g.current&&(g.current.value="")},Fe=Nt({mutationFn:async et=>{p(!0);let at=et.image_url;c&&(at=await Ee(c)||"");const wt=new Date(et.event_date),[rt,Ft]=et.event_time.split(":");wt.setHours(parseInt(rt),parseInt(Ft));const Ut=[new Date(wt)];if(et.is_recurring&&et.recurrence_end_date){let dt=new Date(wt);for(;et.recurrence_pattern==="weekly"?dt=a3(dt,1):et.recurrence_pattern==="biweekly"?dt=a3(dt,2):dt=Ux(dt,1),!(dt>et.recurrence_end_date);)Ut.push(new Date(dt))}const Is=Ut.map(dt=>({title:et.title,description:et.description||null,image_url:at||null,video_url:et.video_url||null,event_date:dt.toISOString(),zoom_link:et.zoom_link,zoom_meeting_id:et.zoom_meeting_id||null,capacity:et.capacity?parseInt(et.capacity):null,is_published:et.is_published})),{data:xs,error:st}=await V.from("events").insert(Is).select();if(st)throw st;return xs&&xs.length>0&&zVs(et.title,xs[0].id),Ut.length},onSuccess:et=>{t.invalidateQueries({queryKey:["admin-events"]}),ae.success(et>1?`${et} recurring events created successfully`:"Event created successfully"),r(!1),o(Yre),d(null),h(null),p(!1)},onError:et=>{ae.error("Failed to create event: "+et.message),p(!1)}}),Oe=Nt({mutationFn:async({id:et,data:at})=>{p(!0);let wt=at.image_url;c&&(wt=await Ee(c)||"");const rt=new Date(at.event_date),[Ft,Ut]=at.event_time.split(":");rt.setHours(parseInt(Ft),parseInt(Ut));const{error:Is}=await V.from("events").update({title:at.title,description:at.description||null,image_url:wt||null,video_url:at.video_url||null,event_date:rt.toISOString(),zoom_link:at.zoom_link,zoom_meeting_id:at.zoom_meeting_id||null,capacity:at.capacity?parseInt(at.capacity):null,is_published:at.is_published}).eq("id",et);if(Is)throw Is},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-events"]}),ae.success("Event updated successfully"),r(!1),i(null),o(Yre),d(null),h(null),p(!1)},onError:et=>{ae.error("Failed to update event: "+et.message),p(!1)}}),Ge=Nt({mutationFn:async et=>{const{error:at}=await V.from("events").delete().eq("id",et);if(at)throw at},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-events"]}),ae.success("Event deleted successfully")},onError:et=>{ae.error("Failed to delete event: "+et.message)}}),yt=Nt({mutationFn:async et=>{var dt;const{data:at}=await V.auth.getUser(),wt=new Date(et.event_date),rt=new Date(wt.getTime()+60*60*1e3),Ft=RVs(et.title),Ut=Math.random().toString(36).slice(2,7),Is=`${Ft}-${Ut}`,{data:xs,error:st}=await V.from("live_events").insert({slug:Is,title:et.title,description:et.description||null,hero_image_url:et.image_url||null,starts_at:et.event_date,ends_at:rt.toISOString(),timezone:"America/New_York",status:"scheduled",is_published:!1,require_registration:!0,invite_only:!1,chat_enabled:!0,questions_mode:!1,replay_enabled:!0,auto_go_live:!0,auto_end:!0,zoom_meeting_id:et.zoom_meeting_id||null,cta_label:"Join the training",cta_url:et.zoom_link||"https://dashboard.relevelup.com/trial",created_by:(dt=at.user)==null?void 0:dt.id,agenda:[],offer_bullets:[]}).select().single();if(st)throw st;return xs},onSuccess:et=>{t.invalidateQueries({queryKey:["live-events"]}),ae.success("Cloned to LevelUp Live — configure stream next"),s(`/admin/live/${et.id}`)},onError:et=>{ae.error("Failed to clone to LevelUp Live: "+et.message)}}),tt=et=>{var wt;const at=new Date(et.event_date);i(et),o({title:et.title,description:et.description||"",image_url:et.image_url||"",video_url:et.video_url||"",event_date:at,event_time:Ys(at,"HH:mm"),zoom_link:et.zoom_link,zoom_meeting_id:et.zoom_meeting_id||"",capacity:((wt=et.capacity)==null?void 0:wt.toString())||"",is_published:et.is_published,is_recurring:!1,recurrence_pattern:"weekly",recurrence_end_date:void 0}),h(et.image_url||null),d(null),r(!0)},ut=et=>{if(et.preventDefault(),!l.event_date){ae.error("Please select a date");return}if(l.is_recurring&&!l.recurrence_end_date){ae.error("Please select an end date for recurring events");return}a?Oe.mutate({id:a.id,data:l}):Fe.mutate(l)},nt=()=>{r(!1),i(null),o(Yre),d(null),h(null)};return e.jsx("div",{className:"min-h-screen bg-background p-6",children:e.jsxs("div",{className:"max-w-6xl mx-auto space-y-6",children:[e.jsx(nm,{title:"Event Management",description:"Create and manage upcoming events"}),e.jsxs(we,{className:"mb-6",children:[e.jsxs(Vt,{className:"flex flex-row items-center justify-between",children:[e.jsx(Yt,{children:"All Events"}),e.jsxs(zs,{open:n,onOpenChange:et=>!et&&nt(),children:[e.jsx(yl,{asChild:!0,children:e.jsxs($,{onClick:()=>r(!0),children:[e.jsx(nn,{className:"h-4 w-4 mr-2"}),"Add Event"]})}),e.jsxs(Rs,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(Vs,{children:e.jsx($s,{children:a?"Edit Event":"Create New Event"})}),e.jsxs("form",{onSubmit:ut,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"title",children:"Title *"}),e.jsx(be,{id:"title",value:l.title,onChange:et=>o({...l,title:et.target.value}),placeholder:"Event title",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Description"}),e.jsx(V2,{content:l.description,onChange:et=>o({...l,description:et}),placeholder:"Event description",minHeight:"120px"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Event Image"}),e.jsx("input",{type:"file",ref:g,accept:"image/*",onChange:Re,className:"hidden"}),u?e.jsxs("div",{className:"relative",children:[e.jsx("img",{src:u,alt:"Event preview",className:"w-full h-32 object-cover rounded-lg border"}),e.jsx($,{type:"button",variant:"destructive",size:"icon",className:"absolute top-2 right-2 h-6 w-6",onClick:ke,children:e.jsx(mr,{className:"h-4 w-4"})})]}):e.jsxs($,{type:"button",variant:"outline",className:"w-full h-32 border-dashed flex flex-col gap-2",onClick:()=>{var et;return(et=g.current)==null?void 0:et.click()},children:[e.jsx(gi,{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(re,{children:"Date *"}),e.jsxs(Xc,{children:[e.jsx(Qc,{asChild:!0,children:e.jsxs($,{variant:"outline",className:Ot("w-full justify-start text-left font-normal",!l.event_date&&"text-muted-foreground"),children:[e.jsx(ha,{className:"mr-2 h-4 w-4"}),l.event_date?Ys(l.event_date,"PPP"):"Pick a date"]})}),e.jsx(Bc,{className:"w-auto p-0",align:"start",children:e.jsx(vb,{mode:"single",selected:l.event_date,onSelect:et=>o({...l,event_date:et}),initialFocus:!0,className:"p-3 pointer-events-auto"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"time",children:"Time *"}),e.jsx(be,{id:"time",type:"time",value:l.event_time,onChange:et=>o({...l,event_time:et.target.value}),required:!0})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"zoom_link",children:"Zoom Link *"}),e.jsx(be,{id:"zoom_link",value:l.zoom_link,onChange:et=>o({...l,zoom_link:et.target.value}),placeholder:"https://zoom.us/j/...",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"zoom_meeting_id",children:"Zoom Meeting ID (for API registration)"}),e.jsx(be,{id:"zoom_meeting_id",value:l.zoom_meeting_id,onChange:et=>o({...l,zoom_meeting_id:et.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(re,{htmlFor:"video_url",children:"Promo Video URL (optional)"}),e.jsx(be,{id:"video_url",value:l.video_url,onChange:et=>o({...l,video_url:et.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(re,{htmlFor:"capacity",children:"Capacity (optional)"}),e.jsx(be,{id:"capacity",type:"number",value:l.capacity,onChange:et=>o({...l,capacity:et.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(lB,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(re,{htmlFor:"is_recurring",children:"Recurring Event"})]}),e.jsx(On,{id:"is_recurring",checked:l.is_recurring,onCheckedChange:et=>o({...l,is_recurring:et})})]}),l.is_recurring&&e.jsxs("div",{className:"space-y-3 pt-1",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Frequency"}),e.jsxs(bs,{value:l.recurrence_pattern,onValueChange:et=>o({...l,recurrence_pattern:et}),children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"weekly",children:"Weekly"}),e.jsx(We,{value:"biweekly",children:"Every 2 Weeks"}),e.jsx(We,{value:"monthly",children:"Monthly"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Repeat Until"}),e.jsxs(Xc,{children:[e.jsx(Qc,{asChild:!0,children:e.jsxs($,{variant:"outline",className:Ot("w-full justify-start text-left font-normal",!l.recurrence_end_date&&"text-muted-foreground"),children:[e.jsx(ha,{className:"mr-2 h-4 w-4"}),l.recurrence_end_date?Ys(l.recurrence_end_date,"PPP"):"Pick end date"]})}),e.jsx(Bc,{className:"w-auto p-0",align:"start",children:e.jsx(vb,{mode:"single",selected:l.recurrence_end_date,onSelect:et=>o({...l,recurrence_end_date:et}),disabled:et=>et<(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 et=1,at=new Date(l.event_date);for(;at=l.recurrence_pattern==="weekly"?a3(at,1):l.recurrence_pattern==="biweekly"?a3(at,2):Ux(at,1),!(at>l.recurrence_end_date);)et++;return et})()," events with the same Zoom link"]})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(re,{htmlFor:"is_published",children:"Published"}),e.jsx(On,{id:"is_published",checked:l.is_published,onCheckedChange:et=>o({...l,is_published:et})})]}),e.jsxs("div",{className:"flex gap-2 pt-4",children:[e.jsx($,{type:"button",variant:"outline",onClick:nt,className:"flex-1",children:"Cancel"}),e.jsx($,{type:"submit",className:"flex-1",disabled:Fe.isPending||Oe.isPending||m,children:m?"Uploading...":a?"Update Event":l.is_recurring&&l.event_date&&l.recurrence_end_date?"Create Recurring Events":"Create Event"})]})]})]})]})]}),e.jsx(De,{children:oe?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"Loading events..."}):(ee==null?void 0:ee.length)===0?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"No events yet. Create your first event!"}):(()=>{const et=new Date,at=[...ee||[]],wt=at.filter(xs=>new Date(xs.event_date)>=et).sort((xs,st)=>new Date(xs.event_date).getTime()-new Date(st.event_date).getTime()),rt=at.filter(xs=>new Date(xs.event_date)new Date(st.event_date).getTime()-new Date(xs.event_date).getTime()),Ft=wt[0],Ut=xs=>e.jsxs(vn,{children:[e.jsx(_t,{className:"font-medium",children:xs.title}),e.jsx(_t,{className:"whitespace-nowrap",children:Ys(new Date(xs.event_date),"PPP p")}),e.jsx(_t,{children:e.jsxs($,{variant:"ghost",size:"sm",className:"gap-1",onClick:()=>_e(xs),children:[e.jsx(Xn,{className:"h-4 w-4"}),(me==null?void 0:me[xs.id])||0,xs.capacity&&` / ${xs.capacity}`]})}),e.jsx(_t,{children:e.jsx("span",{className:Ot("px-2 py-1 rounded-full text-xs font-medium",xs.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:xs.is_published?"Published":"Draft"})}),e.jsx(_t,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsxs($,{variant:"outline",size:"sm",className:"gap-1.5",onClick:()=>{se(xs),H(!0)},title:"Send invite email to members",children:[e.jsx(Wr,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"hidden sm:inline",children:"Invite Members"})]}),e.jsxs($,{variant:"outline",size:"sm",className:"gap-1.5 border-primary/50 text-primary hover:bg-primary/10",onClick:()=>yt.mutate(xs),disabled:yt.isPending,title:"Clone to LevelUp Live",children:[e.jsx(Cy,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"hidden sm:inline",children:"LevelUp Live"})]}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>window.open(xs.zoom_link,"_blank"),title:"Open Zoom Link",children:e.jsx(Ir,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>tt(xs),children:e.jsx(ui,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:async()=>{await io("Are you sure you want to delete this event?")&&Ge.mutate(xs.id)},children:e.jsx(Un,{className:"h-4 w-4 text-destructive"})})]})})]},xs.id),Is=(xs,st)=>xs.length===0?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:st}):e.jsxs(Qa,{children:[e.jsx(Ja,{children:e.jsxs(vn,{children:[e.jsx(Dt,{children:"Title"}),e.jsx(Dt,{children:"Date & Time"}),e.jsx(Dt,{children:"Registrations"}),e.jsx(Dt,{children:"Status"}),e.jsx(Dt,{className:"text-right",children:"Actions"})]})}),e.jsx(ei,{children:xs.map(Ut)})]});return e.jsxs("div",{className:"space-y-6",children:[Ft&&e.jsx("div",{className:"rounded-xl border bg-gradient-to-br from-primary/10 via-primary/5 to-transparent p-5",children:e.jsxs("div",{className:"flex items-start justify-between gap-4 flex-wrap",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs font-semibold uppercase tracking-wide text-primary mb-1",children:[e.jsx(sa,{className:"h-3.5 w-3.5"}),"Next Upcoming Event"]}),e.jsx("h3",{className:"text-xl font-bold truncate",children:Ft.title}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:Ys(new Date(Ft.event_date),"EEEE, PPP 'at' p")}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[(me==null?void 0:me[Ft.id])||0," registered",Ft.capacity?` of ${Ft.capacity}`:""]})]}),e.jsxs("div",{className:"flex gap-2 flex-wrap",children:[e.jsxs($,{size:"sm",className:"gap-1.5",onClick:()=>{se(Ft),H(!0)},children:[e.jsx(Wr,{className:"h-4 w-4"}),"Invite Members"]}),e.jsxs($,{size:"sm",variant:"outline",className:"gap-1.5",onClick:()=>_e(Ft),children:[e.jsx(Xn,{className:"h-4 w-4"}),"Registrations"]}),e.jsxs($,{size:"sm",variant:"outline",className:"gap-1.5 border-primary/50 text-primary hover:bg-primary/10",onClick:()=>yt.mutate(Ft),disabled:yt.isPending,children:[e.jsx(Cy,{className:"h-4 w-4"}),"LevelUp Live"]}),e.jsxs($,{size:"sm",variant:"outline",className:"gap-1.5",onClick:()=>window.open(Ft.zoom_link,"_blank"),children:[e.jsx(Ir,{className:"h-4 w-4"}),"Zoom"]})]})]})}),e.jsxs(ya,{defaultValue:"upcoming",className:"w-full",children:[e.jsxs(va,{children:[e.jsxs(is,{value:"upcoming",className:"gap-2",children:[e.jsx(sa,{className:"h-4 w-4"}),"Upcoming",e.jsx("span",{className:"ml-1 rounded-full bg-muted px-2 py-0.5 text-xs",children:wt.length})]}),e.jsxs(is,{value:"past",className:"gap-2",children:[e.jsx(Gr,{className:"h-4 w-4"}),"Past",e.jsx("span",{className:"ml-1 rounded-full bg-muted px-2 py-0.5 text-xs",children:rt.length})]})]}),e.jsx(cs,{value:"upcoming",className:"mt-4",children:Is(wt,"No upcoming events scheduled.")}),e.jsx(cs,{value:"past",className:"mt-4",children:Is(rt,"No past events.")})]})]})})()})]}),e.jsx(VVs,{open:G,onOpenChange:H,event:Y}),e.jsx(zs,{open:x,onOpenChange:y,children:e.jsxs(Rs,{className:"max-w-3xl max-h-[80vh] overflow-y-auto",children:[e.jsxs(Vs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(Xn,{className:"h-5 w-5"}),v==null?void 0:v.title]}),e.jsx(Cr,{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($,{variant:"ghost",size:"sm",onClick:()=>Te.mutate({eventId:v.id,testMode:!0}),disabled:Te.isPending,children:[e.jsx(pn,{className:Ot("h-4 w-4 mr-2",Te.isPending&&"animate-spin")}),"Send Test to Me"]}),e.jsxs($,{variant:"outline",size:"sm",onClick:()=>Te.mutate({eventId:v.id}),disabled:Te.isPending||!(Q!=null&&Q.length),children:[e.jsx(pn,{className:Ot("h-4 w-4 mr-2",Te.isPending&&"animate-spin")}),Te.isPending?"Sending...":"Send Reminder to All"]}),(v==null?void 0:v.zoom_meeting_id)&&e.jsxs(e.Fragment,{children:[e.jsxs($,{variant:"outline",size:"sm",onClick:()=>ve.mutate(v.id),disabled:ve.isPending,children:[e.jsx(yo,{className:Ot("h-4 w-4 mr-2",ve.isPending&&"animate-spin")}),ve.isPending?"Syncing...":"Sync Registrations"]}),e.jsxs($,{variant:"outline",size:"sm",onClick:()=>Se.mutate(),disabled:Se.isPending,children:[e.jsx(yo,{className:Ot("h-4 w-4 mr-2",Se.isPending&&"animate-spin")}),Se.isPending?"Retrying...":"Retry Failed Registrations"]}),e.jsxs($,{variant:"default",size:"sm",onClick:()=>he.mutate(v.id),disabled:he.isPending,children:[e.jsx(ql,{className:Ot("h-4 w-4 mr-2",he.isPending&&"animate-spin")}),he.isPending?"Syncing...":"Sync Attendees & Award Points"]})]})]}),e.jsxs(ya,{defaultValue:"registrations",className:"w-full",children:[e.jsxs(va,{className:"grid w-full grid-cols-2",children:[e.jsxs(is,{value:"registrations",className:"gap-2",children:[e.jsx(Xn,{className:"h-4 w-4"}),"Registrations (",(Q==null?void 0:Q.length)||0,")"]}),e.jsxs(is,{value:"attendees",className:"gap-2",children:[e.jsx(Gr,{className:"h-4 w-4"}),"Attendees (",(le==null?void 0:le.length)||0,")"]})]}),e.jsx(cs,{value:"registrations",className:"mt-4",children:te?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"Loading registrations..."}):(Q==null?void 0:Q.length)===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx("p",{children:"No registrations yet for this event."}),(v==null?void 0:v.zoom_meeting_id)&&e.jsx("p",{className:"text-xs mt-2",children:'Click "Sync Registrations" to import from Zoom.'})]}):e.jsxs(Qa,{children:[e.jsx(Ja,{children:e.jsxs(vn,{children:[e.jsx(Dt,{children:"Name"}),e.jsx(Dt,{children:"Email"}),e.jsx(Dt,{children:"Registered"}),e.jsx(Dt,{children:"Status"})]})}),e.jsx(ei,{children:Q==null?void 0:Q.map(et=>{var Ft,Ut;const at=((Ft=et.profiles)==null?void 0:Ft.name)||et.zoom_name||"Unknown",wt=((Ut=et.profiles)==null?void 0:Ut.email)||et.zoom_email||null,rt=!et.user_id;return e.jsxs(vn,{children:[e.jsx(_t,{className:"font-medium",children:e.jsxs("div",{className:"flex items-center gap-2",children:[at,rt&&e.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded bg-muted text-muted-foreground",children:"External"})]})}),e.jsx(_t,{children:wt?e.jsxs("a",{href:`mailto:${wt}`,className:"flex items-center gap-1 text-primary hover:underline",children:[e.jsx(pn,{className:"h-3 w-3"}),wt]}):e.jsx("span",{className:"text-muted-foreground",children:"No email"})}),e.jsx(_t,{className:"text-muted-foreground text-sm",children:Ys(new Date(et.registered_at),"MMM d, yyyy h:mm a")}),e.jsx(_t,{children:et.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"})})]},et.id)})})]})}),e.jsx(cs,{value:"attendees",className:"mt-4",children:fe?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"Loading attendees..."}):(le==null?void 0:le.length)===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx("p",{children:"No attendees recorded yet."}),(v==null?void 0:v.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:[(le==null?void 0:le.filter(et=>!et.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(Ho,{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 (",le==null?void 0:le.filter(et=>!et.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:le==null?void 0:le.filter(et=>!et.user_id).map(et=>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:et.zoom_name||"Unknown"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:et.zoom_email||"No email"})]}),e.jsxs($,{variant:"outline",size:"sm",onClick:()=>Be(et),className:"gap-1",children:[e.jsx(pd,{className:"h-3 w-3"}),"Link to Profile"]})]},et.id))})]}),e.jsxs(Qa,{children:[e.jsx(Ja,{children:e.jsxs(vn,{children:[e.jsx(Dt,{children:"Name"}),e.jsx(Dt,{children:"Email"}),e.jsx(Dt,{children:"Duration"}),e.jsx(Dt,{children:"Points"})]})}),e.jsx(ei,{children:le==null?void 0:le.filter(et=>et.user_id).map(et=>{var rt,Ft;const at=((rt=et.profiles)==null?void 0:rt.name)||et.zoom_name||"Unknown",wt=((Ft=et.profiles)==null?void 0:Ft.email)||et.zoom_email||null;return e.jsxs(vn,{children:[e.jsx(_t,{className:"font-medium",children:e.jsxs("div",{className:"flex items-center gap-2",children:[at,et.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(_t,{children:wt?e.jsxs("a",{href:`mailto:${wt}`,className:"flex items-center gap-1 text-primary hover:underline",children:[e.jsx(pn,{className:"h-3 w-3"}),wt]}):e.jsx("span",{className:"text-muted-foreground",children:"No email"})}),e.jsx(_t,{children:et.duration_minutes?e.jsxs("span",{className:"flex items-center gap-1 text-muted-foreground text-sm",children:[e.jsx(sa,{className:"h-3 w-3"}),et.duration_minutes," min"]}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"—"})}),e.jsx(_t,{children:et.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(ql,{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"})})]},et.id)})})]})]})})]})]})}),e.jsx(zs,{open:j,onOpenChange:C,children:e.jsxs(Rs,{className:"max-w-md",children:[e.jsxs(Vs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(pd,{className:"h-5 w-5"}),"Link Attendee to Profile"]}),e.jsx(Cr,{children:"Link this Zoom attendee to an existing member profile to award them points."})]}),A&&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:A.zoom_name||"Unknown"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:A.zoom_email||"No email"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Search for a profile"}),e.jsxs("div",{className:"relative",children:[e.jsx(Yr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search by name or email...",value:B,onChange:et=>U(et.target.value),className:"pl-9"})]})]}),e.jsx("div",{className:"max-h-48 overflow-y-auto border rounded-md",children:Ye.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:Ye.slice(0,20).map(et=>e.jsxs("button",{type:"button",onClick:()=>P(et.id),className:Ot("w-full p-3 text-left hover:bg-muted/50 transition-colors",I===et.id&&"bg-primary/10 border-l-2 border-primary"),children:[e.jsx("p",{className:"text-sm font-medium",children:et.name||"Unnamed"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:et.email})]},et.id))})}),A.zoom_email&&e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Li,{id:"save-alias",checked:R,onCheckedChange:et=>O(et)}),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($,{variant:"outline",onClick:()=>C(!1),children:"Cancel"}),e.jsx($,{onClick:je,disabled:!I||Ue.isPending,children:Ue.isPending?"Linking...":"Link & Award Points"})]})]})]})})]})})}const GVs={ok:"bg-emerald-500/10 text-emerald-700 dark:text-emerald-400",error:"bg-red-500/10 text-red-700 dark:text-red-400",denied:"bg-amber-500/10 text-amber-700 dark:text-amber-400",rate_limited:"bg-orange-500/10 text-orange-700 dark:text-orange-400"};function WVs(){const[s,t]=k.useState([]),[n,r]=k.useState(!0),[a,i]=k.useState("issues");async function l(){r(!0);let o=V.from("mcp_audit_log").select("id, user_id, tool_name, outcome, error_message, duration_ms, client_id, created_at").order("created_at",{ascending:!1}).limit(200);a==="issues"&&(o=o.in("outcome",["denied","rate_limited","error"]));const{data:c,error:d}=await o;d||t(c??[]),r(!1)}return k.useEffect(()=>{l()},[a]),e.jsx(Xs,{title:"MCP Audit Log",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(nm,{title:"MCP Audit Log",description:"Recent LevelUp MCP tool calls — ChatGPT / Claude / Codex activity, denials, and rate limits."}),e.jsxs(we,{children:[e.jsxs(Vt,{className:"flex flex-row items-center justify-between",children:[e.jsxs(Yt,{className:"flex items-center gap-2",children:[e.jsx(dB,{className:"h-5 w-5"}),"Recent activity"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{variant:a==="issues"?"default":"outline",size:"sm",onClick:()=>i("issues"),children:"Issues only"}),e.jsx($,{variant:a==="all"?"default":"outline",size:"sm",onClick:()=>i("all"),children:"All calls"}),e.jsx($,{variant:"ghost",size:"sm",onClick:l,disabled:n,children:e.jsx(yo,{className:`h-4 w-4 ${n?"animate-spin":""}`})})]})]}),e.jsx(De,{children:n?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading…"}):s.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No entries."}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"border-b text-left text-muted-foreground",children:e.jsxs("tr",{children:[e.jsx("th",{className:"py-2 pr-4",children:"When"}),e.jsx("th",{className:"py-2 pr-4",children:"Tool"}),e.jsx("th",{className:"py-2 pr-4",children:"Outcome"}),e.jsx("th",{className:"py-2 pr-4",children:"User"}),e.jsx("th",{className:"py-2 pr-4",children:"Client"}),e.jsx("th",{className:"py-2 pr-4",children:"ms"}),e.jsx("th",{className:"py-2 pr-4",children:"Error"})]})}),e.jsx("tbody",{children:s.map(o=>e.jsxs("tr",{className:"border-b last:border-0",children:[e.jsx("td",{className:"py-2 pr-4 whitespace-nowrap",children:new Date(o.created_at).toLocaleString()}),e.jsx("td",{className:"py-2 pr-4 font-mono text-xs",children:o.tool_name}),e.jsx("td",{className:"py-2 pr-4",children:e.jsx(qe,{className:GVs[o.outcome]??"",variant:"secondary",children:o.outcome})}),e.jsx("td",{className:"py-2 pr-4 font-mono text-xs",children:o.user_id?o.user_id.slice(0,8):"—"}),e.jsx("td",{className:"py-2 pr-4 font-mono text-xs",children:o.client_id?o.client_id.slice(0,12):"—"}),e.jsx("td",{className:"py-2 pr-4",children:o.duration_ms??"—"}),e.jsx("td",{className:"py-2 pr-4 text-xs text-muted-foreground max-w-[24rem] truncate",children:o.error_message??""})]},o.id))})]})})})]})]})})}function KVs({selectedKitIds:s,onChange:t}){const[n,r]=k.useState(""),[a,i]=k.useState(!1),{data:l=[]}=pt({queryKey:["all-resource-kits-picker"],queryFn:async()=>{const{data:h,error:m}=await V.from("resource_kits").select("id, name, featured_image_url").eq("is_published",!0).order("name");if(m)throw m;return h}}),o=l.filter(h=>s.includes(h.id)),c=l.filter(h=>!s.includes(h.id)&&h.name.toLowerCase().includes(n.toLowerCase())),d=h=>{t([...s,h])},u=h=>{t(s.filter(m=>m!==h))};return e.jsxs("div",{className:"space-y-2",children:[e.jsxs(re,{className:"flex items-center gap-2",children:[e.jsx(bh,{className:"h-4 w-4"}),"Linked Toolkits"]}),o.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1.5",children:o.map(h=>e.jsxs(qe,{variant:"secondary",className:"gap-1 pr-1",children:[h.name,e.jsx("button",{type:"button",onClick:()=>u(h.id),className:"ml-1 rounded-full hover:bg-muted-foreground/20 p-0.5",children:e.jsx(mr,{className:"h-3 w-3"})})]},h.id))}),e.jsxs(Xc,{open:a,onOpenChange:i,children:[e.jsx(Qc,{asChild:!0,children:e.jsxs($,{type:"button",variant:"outline",size:"sm",className:"gap-1",children:[e.jsx(bh,{className:"h-3.5 w-3.5"}),"Add Toolkit"]})}),e.jsxs(Bc,{className:"w-80 p-2",align:"start",children:[e.jsxs("div",{className:"relative mb-2",children:[e.jsx(Yr,{className:"absolute left-2 top-2.5 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(be,{placeholder:"Search toolkits...",value:n,onChange:h=>r(h.target.value),className:"pl-7 h-8 text-sm"})]}),e.jsx("div",{className:"max-h-48 overflow-y-auto space-y-0.5",children:c.length===0?e.jsx("p",{className:"text-xs text-muted-foreground text-center py-3",children:n?"No toolkits found":"All toolkits selected"}):c.map(h=>e.jsxs("button",{type:"button",onClick:()=>{d(h.id),r("")},className:"w-full flex items-center gap-2 px-2 py-1.5 rounded-md hover:bg-muted text-left text-sm transition-colors",children:[h.featured_image_url?e.jsx("img",{src:h.featured_image_url,alt:"",className:"w-8 h-8 rounded object-cover flex-shrink-0"}):e.jsx("div",{className:"w-8 h-8 rounded bg-muted flex items-center justify-center flex-shrink-0",children:e.jsx(bh,{className:"h-3.5 w-3.5 text-muted-foreground"})}),e.jsx("span",{className:"truncate",children:h.name})]},h.id))})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Link toolkits that agents can download alongside this template."})]})}const YVs=()=>{const{user:s}=ks(),{toast:t}=Fi(),n=ls(),[r,a]=Jc(),[i,l]=k.useState(!1),[o,c]=k.useState(null),[d,u]=k.useState({name:"",description:"",category_id:"",type_id:"",publish_date:new Date().toISOString().split("T")[0],links:[{title:"",canva_share_link:"",sort_order:0}],guides:[],video_url:""}),[h,m]=k.useState(null),[p,g]=k.useState(0),[x,y]=k.useState(!1),[v,_]=k.useState(null),[j,C]=k.useState(""),[A,M]=k.useState([]),[I,P]=k.useState(""),[R,O]=k.useState(""),[B,U]=k.useState(!1),[G,H]=k.useState(!1),{data:Y=[]}=pt({queryKey:["template-categories"],queryFn:async()=>{const{data:ke,error:Fe}=await V.from("template_categories").select("*").order("name");if(Fe)throw Fe;return ke}}),{data:se=[]}=pt({queryKey:["template-types"],queryFn:async()=>{const{data:ke,error:Fe}=await V.from("template_types").select("*").order("name");if(Fe)throw Fe;return ke}}),{data:ee=[],isLoading:oe}=pt({queryKey:["canva-templates-admin"],queryFn:async()=>{const{data:ke,error:Fe}=await V.from("canva_templates").select(` *, category:template_categories(id, name), type:template_types(id, name) `).order("publish_date",{ascending:!1});if(Fe)throw Fe;const{data:Oe,error:Ge}=await V.from("template_links").select("*").order("sort_order");if(Ge)throw Ge;const{data:yt,error:tt}=await V.from("template_guides").select("*").order("sort_order");if(tt)throw tt;return ke.map(nt=>({...nt,links:(Oe==null?void 0:Oe.filter(et=>et.template_id===nt.id))||[],guides:(yt==null?void 0:yt.filter(et=>et.template_id===nt.id))||[]}))}});k.useEffect(()=>{const ke=r.get("edit");if(ke&&ee.length>0){const Fe=ee.find(Oe=>Oe.id===ke);Fe&&(ve(Fe),a({},{replace:!0}))}},[ee,r]);const me=Nt({mutationFn:async ke=>{const{data:Fe,error:Oe}=await V.from("template_categories").insert({name:ke}).select().single();if(Oe)throw Oe;return Fe},onSuccess:ke=>{n.invalidateQueries({queryKey:["template-categories"]}),u({...d,category_id:ke.id}),P(""),U(!1),t({title:"Category added"})},onError:ke=>{t({title:"Error adding category",description:ke.message,variant:"destructive"})}}),Q=Nt({mutationFn:async ke=>{const{data:Fe,error:Oe}=await V.from("template_types").insert({name:ke}).select().single();if(Oe)throw Oe;return Fe},onSuccess:ke=>{n.invalidateQueries({queryKey:["template-types"]}),u({...d,type_id:ke.id}),O(""),H(!1),t({title:"Type added"})},onError:ke=>{t({title:"Error adding type",description:ke.message,variant:"destructive"})}}),te=Nt({mutationFn:async ke=>{var tt;let Fe=ke.existingImageUrl;if(ke.image){const ut=ke.image.name.split(".").pop(),nt=`${Date.now()}-${Math.random().toString(36).substring(7)}.${ut}`,{error:et}=await V.storage.from("template-previews").upload(nt,ke.image);if(et)throw et;const{data:at}=V.storage.from("template-previews").getPublicUrl(nt);Fe=at.publicUrl}const Oe={name:ke.template.name,description:ke.template.description||null,category_id:ke.template.category_id||null,type_id:ke.template.type_id||null,preview_image_url:Fe,video_url:ke.videoUrl||null,publish_date:ke.template.publish_date?new Date(ke.template.publish_date).toISOString():new Date().toISOString(),created_by:s==null?void 0:s.id};let Ge=ke.templateId;if(Ge){const{error:ut}=await V.from("canva_templates").update(Oe).eq("id",Ge);if(ut)throw ut;const{error:nt}=await V.from("template_links").delete().eq("template_id",Ge);if(nt)throw nt;const et=((tt=ke.existingGuides)==null?void 0:tt.map(rt=>rt.id).filter(Boolean))||[],at=ke.template.guides.map(rt=>rt.id).filter(Boolean),wt=et.filter(rt=>!at.includes(rt));wt.length>0&&await V.from("template_guides").delete().in("id",wt)}else{const{data:ut,error:nt}=await V.from("canva_templates").insert(Oe).select().single();if(nt)throw nt;Ge=ut.id,OVs(ke.template.name,ut.id)}const yt=ke.template.links.filter(ut=>ut.title.trim()&&ut.canva_share_link.trim());if(yt.length>0){const ut=yt.map((et,at)=>({template_id:Ge,title:et.title.trim(),canva_share_link:et.canva_share_link.trim(),sort_order:at})),{error:nt}=await V.from("template_links").insert(ut);if(nt)throw nt}for(let ut=0;ut0)){const{error:ut}=await V.from("resource_kit_templates").insert(ke.linkedKitIds.map(nt=>({template_id:Ge,kit_id:nt})));if(ut)throw ut}},onSuccess:()=>{n.invalidateQueries({queryKey:["canva-templates-admin"]}),n.invalidateQueries({queryKey:["canva-templates"]}),_e(),l(!1),t({title:o?"Template updated":"Template created"})},onError:ke=>{t({title:"Error saving template",description:ke.message,variant:"destructive"})}}),le=Nt({mutationFn:async ke=>{const{error:Fe}=await V.from("canva_templates").delete().eq("id",ke);if(Fe)throw Fe},onSuccess:()=>{n.invalidateQueries({queryKey:["canva-templates-admin"]}),n.invalidateQueries({queryKey:["canva-templates"]}),t({title:"Template deleted"})},onError:ke=>{t({title:"Error deleting template",description:ke.message,variant:"destructive"})}}),fe=Nt({mutationFn:async({id:ke,is_featured:Fe})=>{const{error:Oe}=await V.from("canva_templates").update({is_featured:Fe}).eq("id",ke);if(Oe)throw Oe},onSuccess:()=>{n.invalidateQueries({queryKey:["canva-templates-admin"]}),n.invalidateQueries({queryKey:["canva-templates"]})},onError:ke=>{t({title:"Error updating featured",description:ke.message,variant:"destructive"})}}),_e=()=>{u({name:"",description:"",category_id:"",type_id:"",publish_date:new Date().toISOString().split("T")[0],links:[{title:"",canva_share_link:"",sort_order:0}],guides:[],video_url:""}),_(null),C(""),c(null),U(!1),H(!1),P(""),O(""),m(null),g(0),y(!1),M([])},ve=async ke=>{var Oe;c(ke),u({name:ke.name,description:ke.description||"",category_id:ke.category_id||"",type_id:ke.type_id||"",publish_date:ke.publish_date?new Date(ke.publish_date).toISOString().split("T")[0]:new Date().toISOString().split("T")[0],links:ke.links&&ke.links.length>0?ke.links.map(Ge=>({id:Ge.id,title:Ge.title,canva_share_link:Ge.canva_share_link,sort_order:Ge.sort_order})):[{title:"",canva_share_link:"",sort_order:0}],guides:((Oe=ke.guides)==null?void 0:Oe.map(Ge=>({id:Ge.id,name:Ge.name,file_url:Ge.file_url,file_type:Ge.file_type,file_size:Ge.file_size,sort_order:Ge.sort_order})))||[],video_url:ke.video_url||""}),C(ke.preview_image_url||""),m(null);const{data:Fe}=await V.from("resource_kit_templates").select("kit_id").eq("template_id",ke.id);M((Fe||[]).map(Ge=>Ge.kit_id)),l(!0)},he=ke=>{var Oe;const Fe=(Oe=ke.target.files)==null?void 0:Oe[0];Fe&&(_(Fe),C(URL.createObjectURL(Fe)))},Se=()=>{u({...d,links:[...d.links,{title:"",canva_share_link:"",sort_order:d.links.length}]})},Te=ke=>{if(d.links.length<=1)return;const Fe=d.links.filter((Oe,Ge)=>Ge!==ke);u({...d,links:Fe})},Ie=(ke,Fe,Oe)=>{const Ge=[...d.links];Ge[ke]={...Ge[ke],[Fe]:Oe},u({...d,links:Ge})},Ue=ke=>{const Fe=ke.target.files;if(!Fe)return;const Oe=Array.from(Fe).map((Ge,yt)=>({name:Ge.name.replace(/\.[^/.]+$/,""),file_url:"",file_type:Ge.type,file_size:Ge.size,sort_order:d.guides.length+yt,file:Ge}));u({...d,guides:[...d.guides,...Oe]}),ke.target.value=""},Be=ke=>{const Fe=d.guides.filter((Oe,Ge)=>Ge!==ke);u({...d,guides:Fe})},je=(ke,Fe)=>{const Oe=[...d.guides];Oe[ke]={...Oe[ke],name:Fe},u({...d,guides:Oe})},Ye=async()=>{if(!h)return null;y(!0),g(0);try{const{data:ke,error:Fe}=await V.functions.invoke("bunny-upload",{body:{action:"create",title:d.name||h.name}});if(Fe)throw new Error(Fe.message);const{videoId:Oe,libraryId:Ge}=ke,{data:yt,error:tt}=await V.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:Oe}});if(tt)throw new Error(tt.message);const ut=new XMLHttpRequest;return await new Promise((et,at)=>{ut.upload.addEventListener("progress",wt=>{if(wt.lengthComputable){const rt=Math.round(wt.loaded/wt.total*100);g(rt)}}),ut.addEventListener("load",()=>{ut.status>=200&&ut.status<300?et():at(new Error(`Upload failed with status ${ut.status}`))}),ut.addEventListener("error",()=>at(new Error("Upload failed"))),ut.open("PUT",yt.uploadUrl),ut.setRequestHeader("AccessKey",yt.apiKey),ut.send(h)}),`https://player.mediadelivery.net/embed/${Ge}/${Oe}`}catch(ke){return console.error("Bunny upload error:",ke),t({title:"Video upload failed",description:ke instanceof Error?ke.message:"Unknown error",variant:"destructive"}),null}finally{y(!1)}},Ee=ke=>{var Oe;const Fe=(Oe=ke.target.files)==null?void 0:Oe[0];Fe&&m(Fe),ke.target.value=""},Re=async ke=>{if(ke.preventDefault(),!d.name.trim()){t({title:"Please enter a template name",variant:"destructive"});return}if(d.links.filter(Ge=>Ge.title.trim()&&Ge.canva_share_link.trim()).length===0){t({title:"Please add at least one Canva link",variant:"destructive"});return}let Oe=d.video_url;if(h){const Ge=await Ye();if(!Ge)return;Oe=Ge}te.mutate({template:d,image:v,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:Oe,linkedKitIds:A})};return e.jsx(Xs,{title:"Manage Templates",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(nm,{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(we,{children:[e.jsx(Vt,{className:"pb-2",children:e.jsx(Yt,{className:"text-sm font-medium text-muted-foreground",children:"Total Templates"})}),e.jsx(De,{children:e.jsx("div",{className:"text-2xl font-bold",children:ee.length})})]}),e.jsxs(we,{children:[e.jsx(Vt,{className:"pb-2",children:e.jsx(Yt,{className:"text-sm font-medium text-muted-foreground",children:"Categories"})}),e.jsx(De,{children:e.jsx("div",{className:"text-2xl font-bold",children:Y.length})})]}),e.jsxs(we,{children:[e.jsx(Vt,{className:"pb-2",children:e.jsx(Yt,{className:"text-sm font-medium text-muted-foreground",children:"Template Types"})}),e.jsx(De,{children:e.jsx("div",{className:"text-2xl font-bold",children:se.length})})]})]}),e.jsxs(zs,{open:i,onOpenChange:ke=>{l(ke),ke||_e()},children:[e.jsx(yl,{asChild:!0,children:e.jsxs($,{className:"gap-2",children:[e.jsx(nn,{className:"h-4 w-4"}),"Add Template"]})}),e.jsxs(Rs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Vs,{children:e.jsx($s,{children:o?"Edit Template":"Add New Template"})}),e.jsxs("form",{onSubmit:Re,className:"space-y-6 pt-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"name",children:"Name *"}),e.jsx(be,{id:"name",value:d.name,onChange:ke=>u({...d,name:ke.target.value}),placeholder:"Template name",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Description"}),e.jsx(V2,{content:d.description,onChange:ke=>u({...d,description:ke}),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(re,{children:"Canva Links *"}),e.jsxs($,{type:"button",variant:"outline",size:"sm",onClick:Se,className:"gap-1",children:[e.jsx(nn,{className:"h-3 w-3"}),"Add Link"]})]}),e.jsx("div",{className:"space-y-3",children:d.links.map((ke,Fe)=>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(be,{value:ke.title,onChange:Oe=>Ie(Fe,"title",Oe.target.value),placeholder:"Link title (e.g., Instagram Post, Story)"}),e.jsx(be,{value:ke.canva_share_link,onChange:Oe=>Ie(Fe,"canva_share_link",Oe.target.value),placeholder:"https://www.canva.com/design/..."})]}),d.links.length>1&&e.jsx($,{type:"button",variant:"ghost",size:"icon",className:"shrink-0 text-muted-foreground hover:text-destructive",onClick:()=>Te(Fe),children:e.jsx(mr,{className:"h-4 w-4"})})]},Fe))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Category"}),B?e.jsxs("div",{className:"flex gap-2",children:[e.jsx(be,{value:I,onChange:ke=>P(ke.target.value),placeholder:"New category name",className:"flex-1"}),e.jsx($,{type:"button",size:"sm",onClick:()=>I.trim()&&me.mutate(I.trim()),disabled:me.isPending,children:"Add"}),e.jsx($,{type:"button",size:"sm",variant:"ghost",onClick:()=>{U(!1),P("")},children:e.jsx(mr,{className:"h-4 w-4"})})]}):e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(bs,{value:d.category_id,onValueChange:ke=>u({...d,category_id:ke}),children:[e.jsx(ys,{className:"flex-1",children:e.jsx(_s,{placeholder:"Select category"})}),e.jsx(vs,{children:Y.map(ke=>e.jsx(We,{value:ke.id,children:ke.name},ke.id))})]}),e.jsx($,{type:"button",variant:"outline",size:"icon",onClick:()=>U(!0),children:e.jsx(nn,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Template Type"}),G?e.jsxs("div",{className:"flex gap-2",children:[e.jsx(be,{value:R,onChange:ke=>O(ke.target.value),placeholder:"New type name",className:"flex-1"}),e.jsx($,{type:"button",size:"sm",onClick:()=>R.trim()&&Q.mutate(R.trim()),disabled:Q.isPending,children:"Add"}),e.jsx($,{type:"button",size:"sm",variant:"ghost",onClick:()=>{H(!1),O("")},children:e.jsx(mr,{className:"h-4 w-4"})})]}):e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(bs,{value:d.type_id,onValueChange:ke=>u({...d,type_id:ke}),children:[e.jsx(ys,{className:"flex-1",children:e.jsx(_s,{placeholder:"Select type"})}),e.jsx(vs,{children:se.map(ke=>e.jsx(We,{value:ke.id,children:ke.name},ke.id))})]}),e.jsx($,{type:"button",variant:"outline",size:"icon",onClick:()=>H(!0),children:e.jsx(nn,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"publish_date",children:"Publish Date"}),e.jsx(be,{id:"publish_date",type:"date",value:d.publish_date,onChange:ke=>u({...d,publish_date:ke.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(re,{children:"Preview Image"}),e.jsxs("div",{className:"flex items-start gap-4",children:[j?e.jsxs("div",{className:"relative w-32 h-24 rounded-lg overflow-hidden border bg-muted",children:[e.jsx("img",{src:j,alt:"Preview",className:"w-full h-full object-cover"}),e.jsx($,{type:"button",size:"icon",variant:"destructive",className:"absolute top-1 right-1 h-6 w-6",onClick:()=>{_(null),C("")},children:e.jsx(mr,{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(zc,{className:"h-8 w-8 text-muted-foreground/50"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx(be,{type:"file",accept:"image/*",onChange:he,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(re,{children:"Video (Optional)"}),d.video_url&&!h?e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 p-3 border rounded-lg bg-muted/30",children:[e.jsx(ia,{className:"h-5 w-5 text-primary shrink-0"}),e.jsx("span",{className:"text-sm flex-1 truncate",children:"Video uploaded"}),e.jsx($,{type:"button",variant:"ghost",size:"sm",onClick:()=>u({...d,video_url:""}),className:"text-destructive hover:text-destructive",children:"Remove"})]}),e.jsx("div",{className:"aspect-video max-w-md rounded-lg overflow-hidden border",children:e.jsx("iframe",{src:d.video_url,className:"w-full h-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0})})]}):x?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(Jt,{className:"h-4 w-4 animate-spin"}),e.jsxs("span",{className:"text-sm",children:["Uploading video... ",p,"%"]})]}),e.jsx(ho,{value:p,className:"h-2"})]}):h?e.jsxs("div",{className:"flex items-center gap-2 p-3 border rounded-lg bg-muted/30",children:[e.jsx(ia,{className:"h-5 w-5 text-muted-foreground shrink-0"}),e.jsx("span",{className:"text-sm flex-1 truncate",children:h.name}),e.jsxs("span",{className:"text-xs text-muted-foreground shrink-0",children:[(h.size/1024/1024).toFixed(1)," MB"]}),e.jsx($,{type:"button",variant:"ghost",size:"icon",className:"shrink-0 text-muted-foreground hover:text-destructive h-8 w-8",onClick:()=>m(null),children:e.jsx(mr,{className:"h-4 w-4"})})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"cursor-pointer",children:[e.jsx(be,{type:"file",accept:"video/*",onChange:Ee,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(ia,{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(re,{children:"Guide Files (PDFs)"}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx(be,{type:"file",accept:".pdf,.doc,.docx",multiple:!0,onChange:Ue,className:"hidden"}),e.jsx($,{type:"button",variant:"outline",size:"sm",className:"gap-1",asChild:!0,children:e.jsxs("span",{children:[e.jsx(gi,{className:"h-3 w-3"}),"Add Files"]})})]})]}),d.guides.length>0?e.jsx("div",{className:"space-y-2",children:d.guides.map((ke,Fe)=>e.jsxs("div",{className:"flex gap-2 items-center p-3 border rounded-lg bg-muted/30",children:[e.jsx(ea,{className:"h-5 w-5 text-muted-foreground shrink-0"}),e.jsx(be,{value:ke.name,onChange:Oe=>je(Fe,Oe.target.value),placeholder:"Guide name",className:"flex-1"}),ke.file_size&&e.jsxs("span",{className:"text-xs text-muted-foreground shrink-0",children:[(ke.file_size/1024).toFixed(0)," KB"]}),e.jsx($,{type:"button",variant:"ghost",size:"icon",className:"shrink-0 text-muted-foreground hover:text-destructive h-8 w-8",onClick:()=>Be(Fe),children:e.jsx(mr,{className:"h-4 w-4"})})]},ke.id||Fe))}):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(KVs,{selectedKitIds:A,onChange:M}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx($,{type:"button",variant:"outline",onClick:()=>{l(!1),_e()},children:"Cancel"}),e.jsx($,{type:"submit",disabled:te.isPending,children:te.isPending?"Saving...":o?"Update":"Create"})]})]})]})]})]}),e.jsx(we,{children:e.jsx(De,{className:"p-0",children:oe?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"Loading..."}):ee.length===0?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"No templates yet. Add your first template!"}):e.jsxs(Qa,{children:[e.jsx(Ja,{children:e.jsxs(vn,{children:[e.jsx(Dt,{children:"Preview"}),e.jsx(Dt,{children:"Name"}),e.jsx(Dt,{children:"Links"}),e.jsx(Dt,{children:"Category"}),e.jsx(Dt,{children:"Type"}),e.jsx(Dt,{children:"Publish Date"}),e.jsx(Dt,{className:"w-[72px] text-center",children:"Featured"}),e.jsx(Dt,{className:"text-right",children:"Actions"})]})}),e.jsx(ei,{children:ee.map(ke=>{var Fe,Oe,Ge,yt,tt;return e.jsxs(vn,{children:[e.jsx(_t,{children:e.jsx("div",{className:"w-16 h-12 rounded overflow-hidden bg-muted",children:ke.preview_image_url?e.jsx("img",{src:ke.preview_image_url,alt:ke.name,className:"w-full h-full object-cover"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(zc,{className:"h-4 w-4 text-muted-foreground"})})})}),e.jsx(_t,{className:"font-medium",children:ke.name}),e.jsx(_t,{children:e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsxs(qe,{variant:"secondary",children:[((Fe=ke.links)==null?void 0:Fe.length)||0," link",(((Oe=ke.links)==null?void 0:Oe.length)||0)!==1?"s":""]}),(((Ge=ke.guides)==null?void 0:Ge.length)||0)>0&&e.jsxs(qe,{variant:"outline",className:"gap-1",children:[e.jsx(ea,{className:"h-3 w-3"}),(yt=ke.guides)==null?void 0:yt.length," guide",(((tt=ke.guides)==null?void 0:tt.length)||0)!==1?"s":""]})]})}),e.jsx(_t,{children:ke.category?e.jsx(qe,{variant:"secondary",children:ke.category.name}):e.jsx("span",{className:"text-muted-foreground",children:"-"})}),e.jsx(_t,{children:ke.type?e.jsx(qe,{variant:"outline",children:ke.type.name}):e.jsx("span",{className:"text-muted-foreground",children:"-"})}),e.jsx(_t,{className:"text-muted-foreground",children:new Date(ke.publish_date).toLocaleDateString()}),e.jsx(_t,{className:"text-center",children:e.jsx($,{type:"button",size:"icon",variant:"ghost",className:"mx-auto",title:ke.is_featured?"Remove from featured templates":"Add to featured templates",onClick:()=>fe.mutate({id:ke.id,is_featured:!ke.is_featured}),children:e.jsx(ri,{className:`h-4 w-4 ${ke.is_featured?"fill-yellow-400 text-yellow-400":"text-muted-foreground"}`})})}),e.jsx(_t,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx($,{size:"icon",variant:"ghost",onClick:()=>ve(ke),children:e.jsx(ui,{className:"h-4 w-4"})}),e.jsx($,{size:"icon",variant:"ghost",className:"text-destructive hover:text-destructive",onClick:async()=>{await io("Delete this template?")&&le.mutate(ke.id)},children:e.jsx(Un,{className:"h-4 w-4"})})]})})]},ke.id)})})]})})})]})})};function ERt({selectedTemplateIds:s,onChange:t}){const[n,r]=k.useState(""),[a,i]=k.useState(!1),{data:l=[]}=pt({queryKey:["all-canva-templates-picker"],queryFn:async()=>{const{data:h,error:m}=await V.from("canva_templates").select("id, name, preview_image_url").order("name");if(m)throw m;return h}}),o=l.filter(h=>s.includes(h.id)),c=l.filter(h=>!s.includes(h.id)&&h.name.toLowerCase().includes(n.toLowerCase())),d=h=>{t([...s,h])},u=h=>{t(s.filter(m=>m!==h))};return e.jsxs("div",{className:"space-y-2",children:[e.jsxs(re,{className:"flex items-center gap-2",children:[e.jsx(Zw,{className:"h-4 w-4"}),"Linked Templates"]}),o.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1.5",children:o.map(h=>e.jsxs(qe,{variant:"secondary",className:"gap-1 pr-1",children:[h.name,e.jsx("button",{type:"button",onClick:()=>u(h.id),className:"ml-1 rounded-full hover:bg-muted-foreground/20 p-0.5",children:e.jsx(mr,{className:"h-3 w-3"})})]},h.id))}),e.jsxs(Xc,{open:a,onOpenChange:i,children:[e.jsx(Qc,{asChild:!0,children:e.jsxs($,{type:"button",variant:"outline",size:"sm",className:"gap-1",children:[e.jsx(Zw,{className:"h-3.5 w-3.5"}),"Add Template"]})}),e.jsxs(Bc,{className:"w-80 p-2",align:"start",children:[e.jsxs("div",{className:"relative mb-2",children:[e.jsx(Yr,{className:"absolute left-2 top-2.5 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(be,{placeholder:"Search templates...",value:n,onChange:h=>r(h.target.value),className:"pl-7 h-8 text-sm"})]}),e.jsx("div",{className:"max-h-48 overflow-y-auto space-y-0.5",children:c.length===0?e.jsx("p",{className:"text-xs text-muted-foreground text-center py-3",children:n?"No templates found":"All templates selected"}):c.map(h=>e.jsxs("button",{type:"button",onClick:()=>{d(h.id),r("")},className:"w-full flex items-center gap-2 px-2 py-1.5 rounded-md hover:bg-muted text-left text-sm transition-colors",children:[h.preview_image_url?e.jsx("img",{src:h.preview_image_url,alt:"",className:"w-8 h-8 rounded object-cover flex-shrink-0"}):e.jsx("div",{className:"w-8 h-8 rounded bg-muted flex items-center justify-center flex-shrink-0",children:e.jsx(Zw,{className:"h-3.5 w-3.5 text-muted-foreground"})}),e.jsx("span",{className:"truncate",children:h.name})]},h.id))})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Link templates that agents can use alongside this content."})]})}const ZVs=[{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"}],XVs=()=>{const{user:s}=ks(),[t,n]=Jc(),{toast:r}=Fi(),a=ls(),[i,l]=k.useState(!1),[o,c]=k.useState(null),[d,u]=k.useState({title:"",description:"",video_url:"",video_type:"youtube",duration:"",category_id:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1}),[h,m]=k.useState(null),[p,g]=k.useState(""),[x,y]=k.useState([]),[v,_]=k.useState([]),[j,C]=k.useState([]),[A,M]=k.useState([]),[I,P]=k.useState(""),[R,O]=k.useState(!1),[B,U]=k.useState(null),[G,H]=k.useState(0),[Y,se]=k.useState(!1),[ee,oe]=k.useState(null),{data:me=[]}=pt({queryKey:["academy-categories"],queryFn:async()=>{const{data:ke,error:Fe}=await V.from("academy_categories").select("*").order("sort_order",{ascending:!0});if(Fe)throw Fe;return ke}}),{data:Q=[],isLoading:te}=pt({queryKey:["academy-videos-admin"],queryFn:async()=>{const{data:ke,error:Fe}=await V.from("academy_videos").select(` *, category:academy_categories(id, name) `).order("publish_date",{ascending:!1});if(Fe)throw Fe;const{data:Oe,error:Ge}=await V.from("academy_resources").select("*").order("sort_order");if(Ge)throw Ge;return ke.map(tt=>({...tt,resources:(Oe==null?void 0:Oe.filter(ut=>ut.video_id===tt.id))||[]}))}});k.useEffect(()=>{const ke=t.get("edit");if(ke&&Q.length>0){const Fe=Q.find(Oe=>Oe.id===ke);Fe&&(Ie(Fe),n({},{replace:!0}))}},[Q,t]);const le=Nt({mutationFn:async ke=>{const{data:Fe,error:Oe}=await V.from("academy_categories").insert({name:ke,sort_order:me.length}).select().single();if(Oe)throw Oe;return Fe},onSuccess:ke=>{a.invalidateQueries({queryKey:["academy-categories"]}),u({...d,category_id:ke.id}),P(""),O(!1),r({title:"Category added"})},onError:ke=>{r({title:"Error adding category",description:ke.message,variant:"destructive"})}}),fe=Nt({mutationFn:async ke=>{let Fe=ke.existingThumbnailUrl;if(ke.thumbnail){const yt=ke.thumbnail.name.split(".").pop(),tt=`thumbnails/${Date.now()}-${Math.random().toString(36).substring(7)}.${yt}`,{error:ut}=await V.storage.from("academy-resources").upload(tt,ke.thumbnail);if(ut)throw ut;const{data:nt}=V.storage.from("academy-resources").getPublicUrl(tt);Fe=nt.publicUrl}const Oe={title:ke.video.title,description:ke.video.description||null,video_url:ke.video.video_url,video_type:ke.video.video_type,duration:ke.video.duration||null,thumbnail_url:Fe,category_id:ke.video.category_id||null,publish_date:ke.video.publish_date?new Date(ke.video.publish_date).toISOString():new Date().toISOString(),is_published:ke.video.is_published,created_by:s==null?void 0:s.id};let Ge=ke.videoId;if(Ge){const{error:yt}=await V.from("academy_videos").update(Oe).eq("id",Ge);if(yt)throw yt}else{const{data:yt,error:tt}=await V.from("academy_videos").insert(Oe).select().single();if(tt)throw tt;Ge=yt.id,FVs(ke.video.title,yt.id)}if(ke.resourcesToDelete.length>0){const{error:yt}=await V.from("academy_resources").delete().in("id",ke.resourcesToDelete);if(yt)throw yt}for(let yt=0;yt0){const{error:yt}=await V.from("academy_video_templates").insert(A.map(tt=>({video_id:Ge,template_id:tt})));if(yt)throw yt}},onSuccess:()=>{a.invalidateQueries({queryKey:["academy-videos-admin"]}),a.invalidateQueries({queryKey:["academy-videos"]}),Te(),l(!1),r({title:o?"Video updated":"Video created"})},onError:ke=>{r({title:"Error saving video",description:ke.message,variant:"destructive"})}}),_e=Nt({mutationFn:async ke=>{const{error:Fe}=await V.from("academy_videos").delete().eq("id",ke);if(Fe)throw Fe},onSuccess:()=>{a.invalidateQueries({queryKey:["academy-videos-admin"]}),a.invalidateQueries({queryKey:["academy-videos"]}),r({title:"Video deleted"})},onError:ke=>{r({title:"Error deleting video",description:ke.message,variant:"destructive"})}}),ve=Nt({mutationFn:async({id:ke,is_published:Fe})=>{const{error:Oe}=await V.from("academy_videos").update({is_published:Fe}).eq("id",ke);if(Oe)throw Oe},onSuccess:()=>{a.invalidateQueries({queryKey:["academy-videos-admin"]}),a.invalidateQueries({queryKey:["academy-videos"]})},onError:ke=>{r({title:"Error updating video",description:ke.message,variant:"destructive"})}}),he=async ke=>{try{let Fe=ke.public_slug||null,Oe=!!ke.is_public;if(!Fe||!Oe){const yt=(ke.title||"video").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60)||"video";if(!Fe){let ut=yt;const{data:nt}=await V.from("academy_videos").select("id").eq("public_slug",ut).maybeSingle();nt&&nt.id!==ke.id&&(ut=`${yt}-${ke.id.slice(0,6)}`),Fe=ut}const{error:tt}=await V.from("academy_videos").update({public_slug:Fe,is_public:!0}).eq("id",ke.id);if(tt)throw tt;a.invalidateQueries({queryKey:["academy-videos-admin"]})}const Ge=`${window.location.origin}/watch/${Fe}`;await navigator.clipboard.writeText(Ge),r({title:"Public link copied",description:Ge})}catch(Fe){r({title:"Could not copy link",description:Fe.message,variant:"destructive"})}},Se=async ke=>{if(!await io("Disable the public teaser link for this video?"))return;const{error:Fe}=await V.from("academy_videos").update({is_public:!1}).eq("id",ke.id);if(Fe){r({title:"Error",description:Fe.message,variant:"destructive"});return}a.invalidateQueries({queryKey:["academy-videos-admin"]}),r({title:"Public link disabled"})},Te=()=>{u({title:"",description:"",video_url:"",video_type:"bunny_stream",duration:"",category_id:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1}),m(null),g(""),y([]),_([]),C([]),c(null),M([]),P(""),U(null),H(0),se(!1),oe(null)},Ie=async ke=>{c(ke),u({title:ke.title,description:ke.description||"",video_url:ke.video_url,video_type:ke.video_type,duration:ke.duration||"",category_id:ke.category_id||"",publish_date:ke.publish_date?new Date(ke.publish_date).toISOString().split("T")[0]:new Date().toISOString().split("T")[0],is_published:ke.is_published}),g(ke.thumbnail_url||""),_(ke.resources||[]),y([]),C([]);const{data:Fe}=await V.from("academy_video_templates").select("template_id").eq("video_id",ke.id);M((Fe||[]).map(Oe=>Oe.template_id)),l(!0)},Ue=ke=>{var Oe;const Fe=(Oe=ke.target.files)==null?void 0:Oe[0];Fe&&(m(Fe),g(URL.createObjectURL(Fe)))},Be=ke=>{const Fe=ke.target.files;if(Fe){const Oe=Array.from(Fe).map(Ge=>({file:Ge,title:Ge.name.replace(/\.[^/.]+$/,"")}));y([...x,...Oe])}ke.target.value=""},je=ke=>{y(x.filter((Fe,Oe)=>Oe!==ke))},Ye=ke=>{C([...j,ke]),_(v.filter(Fe=>Fe.id!==ke))},Ee=async()=>{if(!B)return null;se(!0),H(0);try{const{data:ke,error:Fe}=await V.functions.invoke("bunny-upload",{body:{action:"create",title:d.title||B.name}});if(Fe)throw new Error(Fe.message);const{videoId:Oe,libraryId:Ge}=ke;oe(Oe);const{data:yt,error:tt}=await V.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:Oe}});if(tt)throw new Error(tt.message);const ut=new XMLHttpRequest;return await new Promise((et,at)=>{ut.upload.addEventListener("progress",wt=>{if(wt.lengthComputable){const rt=Math.round(wt.loaded/wt.total*100);H(rt)}}),ut.addEventListener("load",()=>{ut.status>=200&&ut.status<300?et():at(new Error(`Upload failed with status ${ut.status}`))}),ut.addEventListener("error",()=>at(new Error("Upload failed"))),ut.open("PUT",yt.uploadUrl),ut.setRequestHeader("AccessKey",yt.apiKey),ut.send(B)}),`https://player.mediadelivery.net/embed/${Ge}/${Oe}`}catch(ke){return console.error("Bunny upload error:",ke),r({title:"Video upload failed",description:ke instanceof Error?ke.message:"Unknown error",variant:"destructive"}),null}finally{se(!1)}},Re=async ke=>{if(ke.preventDefault(),!d.title.trim()){r({title:"Please enter a video title",variant:"destructive"});return}let Fe=d.video_url;if(d.video_type==="bunny_stream"&&B&&!o){const Oe=await Ee();if(!Oe)return;Fe=Oe}else if(!d.video_url.trim()&&d.video_type!=="bunny_stream"){r({title:"Please enter a video URL",variant:"destructive"});return}else if(d.video_type==="bunny_stream"&&!B&&!d.video_url&&!o){r({title:"Please select a video file to upload",variant:"destructive"});return}fe.mutate({video:{...d,video_url:Fe},thumbnail:h,existingThumbnailUrl:(o==null?void 0:o.thumbnail_url)||null,videoId:o==null?void 0:o.id,newResources:x,resourcesToDelete:j})};return e.jsx(Xs,{title:"Manage Academy",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(nm,{title:"Manage Academy",description:"Create and manage training videos and resources"}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsxs(we,{children:[e.jsx(Vt,{className:"pb-2",children:e.jsx(Yt,{className:"text-sm font-medium text-muted-foreground",children:"Total Videos"})}),e.jsx(De,{children:e.jsx("div",{className:"text-2xl font-bold",children:Q.length})})]}),e.jsxs(we,{children:[e.jsx(Vt,{className:"pb-2",children:e.jsx(Yt,{className:"text-sm font-medium text-muted-foreground",children:"Published"})}),e.jsx(De,{children:e.jsx("div",{className:"text-2xl font-bold",children:Q.filter(ke=>ke.is_published).length})})]}),e.jsxs(we,{children:[e.jsx(Vt,{className:"pb-2",children:e.jsx(Yt,{className:"text-sm font-medium text-muted-foreground",children:"Public Teasers"})}),e.jsx(De,{children:e.jsx("div",{className:"text-2xl font-bold",children:Q.filter(ke=>ke.is_public).length})})]}),e.jsxs(we,{children:[e.jsx(Vt,{className:"pb-2",children:e.jsx(Yt,{className:"text-sm font-medium text-muted-foreground",children:"Total Public Views"})}),e.jsx(De,{children:e.jsx("div",{className:"text-2xl font-bold",children:Q.reduce((ke,Fe)=>ke+(Fe.public_view_count||0),0).toLocaleString()})})]})]}),e.jsxs(zs,{open:i,onOpenChange:ke=>{l(ke),ke||Te()},children:[e.jsx(yl,{asChild:!0,children:e.jsxs($,{className:"gap-2",children:[e.jsx(nn,{className:"h-4 w-4"}),"Add Video"]})}),e.jsxs(Rs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Vs,{children:e.jsx($s,{children:o?"Edit Video":"Add New Video"})}),e.jsxs("form",{onSubmit:Re,className:"space-y-6 pt-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"title",children:"Title *"}),e.jsx(be,{id:"title",value:d.title,onChange:ke=>u({...d,title:ke.target.value}),placeholder:"Video title",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Description"}),e.jsx(V2,{content:d.description,onChange:ke=>u({...d,description:ke}),placeholder:"Brief description of the video",minHeight:"120px"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Video Type"}),e.jsxs(bs,{value:d.video_type,onValueChange:ke=>{u({...d,video_type:ke,video_url:""}),U(null)},disabled:Y,children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsx(vs,{children:ZVs.map(ke=>e.jsx(We,{value:ke.value,children:ke.label},ke.value))})]})]}),d.video_type==="bunny_stream"?e.jsxs("div",{className:"space-y-3",children:[e.jsxs(re,{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(be,{type:"file",accept:"video/*",onChange:ke=>{var Oe;const Fe=(Oe=ke.target.files)==null?void 0:Oe[0];Fe&&U(Fe)},disabled:Y}),B&&e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(ia,{className:"h-4 w-4"}),B.name," (",(B.size/(1024*1024)).toFixed(1)," MB)"]}),Y&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Jt,{className:"h-4 w-4 animate-spin"}),e.jsx("span",{className:"text-sm",children:"Uploading to Bunny.net..."})]}),e.jsx(ho,{value:G,className:"h-2"}),e.jsxs("p",{className:"text-xs text-muted-foreground text-right",children:[G,"%"]})]})]})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"video_url",children:"Video URL *"}),e.jsx(be,{id:"video_url",value:d.video_url,onChange:ke=>u({...d,video_url:ke.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(re,{htmlFor:"duration",children:"Duration"}),e.jsx(be,{id:"duration",value:d.duration,onChange:ke=>u({...d,duration:ke.target.value}),placeholder:"e.g., 45:30"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"publish_date",children:"Publish Date"}),e.jsx(be,{id:"publish_date",type:"date",value:d.publish_date,onChange:ke=>u({...d,publish_date:ke.target.value})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Category"}),R?e.jsxs("div",{className:"flex gap-2",children:[e.jsx(be,{value:I,onChange:ke=>P(ke.target.value),placeholder:"New category name",className:"flex-1"}),e.jsx($,{type:"button",size:"sm",onClick:()=>I.trim()&&le.mutate(I.trim()),disabled:le.isPending,children:"Add"}),e.jsx($,{type:"button",size:"sm",variant:"ghost",onClick:()=>{O(!1),P("")},children:e.jsx(mr,{className:"h-4 w-4"})})]}):e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(bs,{value:d.category_id,onValueChange:ke=>u({...d,category_id:ke}),children:[e.jsx(ys,{className:"flex-1",children:e.jsx(_s,{placeholder:"Select category"})}),e.jsx(vs,{children:me.map(ke=>e.jsx(We,{value:ke.id,children:ke.name},ke.id))})]}),e.jsx($,{type:"button",variant:"outline",size:"sm",onClick:()=>O(!0),children:e.jsx(nn,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Thumbnail Image"}),e.jsxs("div",{className:"flex items-start gap-4",children:[p&&e.jsx("img",{src:p,alt:"Thumbnail preview",className:"w-32 h-20 object-cover rounded-md border"}),e.jsxs("div",{className:"flex-1",children:[e.jsx(be,{type:"file",accept:"image/*",onChange:Ue,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(re,{children:"Resource Files"}),e.jsx($,{type:"button",variant:"outline",size:"sm",asChild:!0,children:e.jsxs("label",{className:"cursor-pointer gap-1",children:[e.jsx(gi,{className:"h-3 w-3"}),"Add Files",e.jsx("input",{type:"file",multiple:!0,accept:".pdf,.pptx,.ppt,.xlsx,.xls,.docx,.doc,.zip",onChange:Be,className:"hidden"})]})})]}),(v.length>0||x.length>0)&&e.jsxs("div",{className:"space-y-2 mt-2",children:[v.map(ke=>e.jsxs("div",{className:"flex items-center gap-2 p-2 border rounded-md bg-muted/30",children:[e.jsx(ea,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"flex-1 text-sm truncate",children:ke.title}),e.jsx(qe,{variant:"outline",className:"text-xs",children:ke.file_type}),e.jsx($,{type:"button",variant:"ghost",size:"sm",onClick:()=>Ye(ke.id),className:"text-destructive hover:text-destructive",children:e.jsx(mr,{className:"h-4 w-4"})})]},ke.id)),x.map((ke,Fe)=>e.jsxs("div",{className:"flex items-center gap-2 p-2 border rounded-md bg-muted/30",children:[e.jsx(ea,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(be,{value:ke.title,onChange:Oe=>{const Ge=[...x];Ge[Fe].title=Oe.target.value,y(Ge)},className:"flex-1 h-8",placeholder:"Resource title"}),e.jsx(qe,{variant:"secondary",className:"text-xs",children:"New"}),e.jsx($,{type:"button",variant:"ghost",size:"sm",onClick:()=>je(Fe),className:"text-destructive hover:text-destructive",children:e.jsx(mr,{className:"h-4 w-4"})})]},Fe))]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Supported: PDF, PowerPoint, Excel, Word, ZIP"})]}),e.jsx(ERt,{selectedTemplateIds:A,onChange:M}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(On,{id:"is_published",checked:d.is_published,onCheckedChange:ke=>u({...d,is_published:ke})}),e.jsx(re,{htmlFor:"is_published",children:"Published"})]}),e.jsxs(kr,{children:[e.jsx($,{type:"button",variant:"outline",onClick:()=>l(!1),disabled:Y,children:"Cancel"}),e.jsx($,{type:"submit",disabled:fe.isPending||Y,children:Y?e.jsxs(e.Fragment,{children:[e.jsx(Jt,{className:"h-4 w-4 mr-2 animate-spin"}),"Uploading..."]}):fe.isPending?"Saving...":o?"Update Video":"Add Video"})]})]})]})]})]}),e.jsx(we,{children:e.jsx(De,{className:"p-0",children:te?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"})}):Q.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(ia,{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(Qa,{children:[e.jsx(Ja,{children:e.jsxs(vn,{children:[e.jsx(Dt,{children:"Title"}),e.jsx(Dt,{children:"Category"}),e.jsx(Dt,{children:"Duration"}),e.jsx(Dt,{children:"Resources"}),e.jsx(Dt,{children:"Publish Date"}),e.jsx(Dt,{children:"Status"}),e.jsx(Dt,{children:"Public Views"}),e.jsx(Dt,{className:"w-[120px]",children:"Actions"})]})}),e.jsx(ei,{children:Q.map(ke=>e.jsxs(vn,{children:[e.jsx(_t,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[ke.thumbnail_url?e.jsx("img",{src:ke.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(ia,{className:"h-4 w-4 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:ke.title}),e.jsx("p",{className:"text-xs text-muted-foreground capitalize",children:ke.video_type.replace("_"," ")})]})]})}),e.jsx(_t,{children:ke.category?e.jsx(qe,{variant:"outline",children:ke.category.name}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"-"})}),e.jsx(_t,{children:ke.duration||"-"}),e.jsx(_t,{children:ke.resources&&ke.resources.length>0?e.jsxs(qe,{variant:"secondary",children:[ke.resources.length," file(s)"]}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"-"})}),e.jsx(_t,{children:new Date(ke.publish_date).toLocaleDateString()}),e.jsx(_t,{children:e.jsx(On,{checked:ke.is_published,onCheckedChange:Fe=>ve.mutate({id:ke.id,is_published:Fe})})}),e.jsx(_t,{children:ke.is_public?e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(ba,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"text-sm font-medium",children:(ke.public_view_count||0).toLocaleString()})]}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"-"})}),e.jsx(_t,{children:e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx($,{variant:"ghost",size:"sm",title:ke.is_public?"Copy public teaser link":"Make public & copy teaser link",onClick:()=>he(ke),children:ke.is_public?e.jsx(Da,{className:"h-4 w-4 text-primary"}):e.jsx(ou,{className:"h-4 w-4"})}),ke.is_public&&e.jsx($,{variant:"ghost",size:"sm",title:"Disable public link",onClick:()=>Se(ke),children:e.jsx(kc,{className:"h-4 w-4 text-emerald-500"})}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>Ie(ke),children:e.jsx(ui,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>_e.mutate(ke.id),className:"text-destructive hover:text-destructive",children:e.jsx(Un,{className:"h-4 w-4"})})]})})]},ke.id))})]})})})]})})};function QVs(){var fe,_e,ve;const s=ls(),[t,n]=Jc(),[r,a]=k.useState(!1),[i,l]=k.useState(null),[o,c]=k.useState({name:"",description:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1}),[d,u]=k.useState(null),[h,m]=k.useState(""),[p,g]=k.useState([]),[x,y]=k.useState([]),[v,_]=k.useState([]),[j,C]=k.useState(null),{data:A,isLoading:M}=pt({queryKey:["resource-kits"],queryFn:async()=>{const{data:he,error:Se}=await V.from("resource_kits").select("*").order("publish_date",{ascending:!1});if(Se)throw Se;return he}}),{data:I}=pt({queryKey:["resource-kit-files"],queryFn:async()=>{const{data:he,error:Se}=await V.from("resource_kit_files").select("*").order("sort_order",{ascending:!0});if(Se)throw Se;return he}}),{data:P}=pt({queryKey:["resource-kit-links"],queryFn:async()=>{const{data:he,error:Se}=await V.from("resource_kit_links").select("*").order("sort_order",{ascending:!0});if(Se)throw Se;return he}});k.useEffect(()=>{const he=t.get("edit");if(he&&A&&A.length>0&&I&&P){const Se=A.find(Te=>Te.id===he);Se&&(O(Se),n({},{replace:!0}))}},[A,I,P,t]);const R=()=>{c({name:"",description:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1}),u(null),m(""),g([]),y([]),_([]),l(null)},O=async he=>{l(he),c({name:he.name,description:he.description||"",publish_date:he.publish_date.split("T")[0],is_published:he.is_published}),m(he.featured_image_url||"");const Se=(I==null?void 0:I.filter(Ue=>Ue.kit_id===he.id))||[];g(Se.map(Ue=>({id:Ue.id,name:Ue.name,file_url:Ue.file_url,file_type:Ue.file_type,file_size:Ue.file_size,sort_order:Ue.sort_order})));const Te=(P==null?void 0:P.filter(Ue=>Ue.kit_id===he.id))||[];y(Te.map(Ue=>({id:Ue.id,title:Ue.title,canva_share_link:Ue.canva_share_link,sort_order:Ue.sort_order})));const{data:Ie}=await V.from("resource_kit_templates").select("template_id").eq("kit_id",he.id);_((Ie||[]).map(Ue=>Ue.template_id)),a(!0)},B=he=>{var Te;const Se=(Te=he.target.files)==null?void 0:Te[0];Se&&(u(Se),m(URL.createObjectURL(Se)))},U=()=>{g([...p,{name:"",file_url:"",sort_order:p.length}])},G=he=>{g(p.filter((Se,Te)=>Te!==he))},H=(he,Se,Te)=>{const Ie=[...p];Ie[he]={...Ie[he],[Se]:Te},g(Ie)},Y=()=>{y([...x,{title:"",canva_share_link:"",sort_order:x.length}])},se=he=>{y(x.filter((Se,Te)=>Te!==he))},ee=(he,Se,Te)=>{const Ie=[...x];Ie[he]={...Ie[he],[Se]:Te},y(Ie)},oe=(he,Se)=>{var Ie;const Te=(Ie=Se.target.files)==null?void 0:Ie[0];if(Te){const Ue=[...p],Be=Te.name.replace(/\.[^/.]+$/,"");Ue[he]={...Ue[he],file:Te,file_type:Te.type,file_size:Te.size,name:Ue[he].name||Be},g(Ue)}},me=Nt({mutationFn:async()=>{let he=(i==null?void 0:i.featured_image_url)||null;if(d){const Be=d.name.split(".").pop(),je=`${Date.now()}.${Be}`,{error:Ye}=await V.storage.from("resource-kits").upload(`featured/${je}`,d);if(Ye)throw Ye;const{data:Ee}=V.storage.from("resource-kits").getPublicUrl(`featured/${je}`);he=Ee.publicUrl}const Se={name:o.name,description:o.description||null,featured_image_url:he,publish_date:o.publish_date,is_published:o.is_published};let Te;const Ie=!i,Ue=(i==null?void 0:i.is_published)||!1;if(i){const{error:Be}=await V.from("resource_kits").update(Se).eq("id",i.id);if(Be)throw Be;Te=i.id;const je=(I==null?void 0:I.filter(Oe=>Oe.kit_id===i.id).map(Oe=>Oe.id))||[],Ye=p.filter(Oe=>Oe.id).map(Oe=>Oe.id),Ee=je.filter(Oe=>!Ye.includes(Oe));Ee.length>0&&await V.from("resource_kit_files").delete().in("id",Ee);const Re=(P==null?void 0:P.filter(Oe=>Oe.kit_id===i.id).map(Oe=>Oe.id))||[],ke=x.filter(Oe=>Oe.id).map(Oe=>Oe.id),Fe=Re.filter(Oe=>!ke.includes(Oe));Fe.length>0&&await V.from("resource_kit_links").delete().in("id",Fe)}else{const{data:Be,error:je}=await V.from("resource_kits").insert(Se).select().single();if(je)throw je;Te=Be.id}for(let Be=0;Be0){const{error:Be}=await V.from("resource_kit_templates").insert(v.map(je=>({kit_id:Te,template_id:je})));if(Be)throw Be}return{kitId:Te,kitName:o.name,isNewKit:Ie,wasPublished:Ue,isPublished:o.is_published}},onSuccess:he=>{s.invalidateQueries({queryKey:["resource-kits"]}),s.invalidateQueries({queryKey:["resource-kit-files"]}),s.invalidateQueries({queryKey:["resource-kit-links"]}),ae.success(i?"Resource kit updated":"Resource kit created"),he.isPublished&&(he.isNewKit||!he.wasPublished)&&BVs(he.kitName,he.kitId),a(!1),R()},onError:he=>{ae.error("Failed to save resource kit: "+he.message)}}),Q=Nt({mutationFn:async he=>{const{error:Se}=await V.from("resource_kits").delete().eq("id",he);if(Se)throw Se},onSuccess:()=>{s.invalidateQueries({queryKey:["resource-kits"]}),s.invalidateQueries({queryKey:["resource-kit-files"]}),ae.success("Resource kit deleted")},onError:he=>{ae.error("Failed to delete: "+he.message)}}),te=he=>{if(he.preventDefault(),!o.name){ae.error("Please enter a name");return}me.mutate()},le=he=>(I==null?void 0:I.filter(Se=>Se.kit_id===he).length)||0;return e.jsx(Xs,{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(we,{children:[e.jsx(Vt,{className:"pb-2",children:e.jsx(Yt,{className:"text-sm font-medium text-muted-foreground",children:"Total Kits"})}),e.jsx(De,{children:e.jsx("div",{className:"text-2xl font-bold",children:(A==null?void 0:A.length)||0})})]}),e.jsxs(we,{children:[e.jsx(Vt,{className:"pb-2",children:e.jsx(Yt,{className:"text-sm font-medium text-muted-foreground",children:"Published"})}),e.jsx(De,{children:e.jsx("div",{className:"text-2xl font-bold",children:(A==null?void 0:A.filter(he=>he.is_published).length)||0})})]})]}),e.jsxs($,{onClick:()=>{R(),a(!0)},children:[e.jsx(nn,{className:"h-4 w-4 mr-2"}),"Add Resource Kit"]})]}),e.jsx(we,{children:e.jsx(De,{className:"p-0",children:e.jsxs(Qa,{children:[e.jsx(Ja,{children:e.jsxs(vn,{children:[e.jsx(Dt,{children:"Name"}),e.jsx(Dt,{children:"Files"}),e.jsx(Dt,{children:"Publish Date"}),e.jsx(Dt,{children:"Status"}),e.jsx(Dt,{className:"text-right",children:"Actions"})]})}),e.jsx(ei,{children:M?e.jsx(vn,{children:e.jsx(_t,{colSpan:5,className:"text-center py-8",children:"Loading..."})}):(A==null?void 0:A.length)===0?e.jsx(vn,{children:e.jsx(_t,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No resource kits yet. Create your first one!"})}):A==null?void 0:A.map(he=>e.jsxs(vn,{children:[e.jsx(_t,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[he.featured_image_url?e.jsx("img",{src:he.featured_image_url,alt:he.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(bh,{className:"h-5 w-5 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:he.name}),he.description&&e.jsx("div",{className:"text-sm text-muted-foreground line-clamp-1",children:he.description})]})]})}),e.jsx(_t,{children:e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(ea,{className:"h-4 w-4 text-muted-foreground"}),le(he.id)]})}),e.jsx(_t,{children:Ys(new Date(he.publish_date),"MMM d, yyyy")}),e.jsx(_t,{children:e.jsx("span",{className:`inline-flex items-center px-2 py-1 rounded-full text-xs font-medium ${he.is_published?"bg-green-100 text-green-800":"bg-yellow-100 text-yellow-800"}`,children:he.is_published?"Published":"Draft"})}),e.jsx(_t,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx($,{variant:"ghost",size:"icon",onClick:()=>{const Se=(I==null?void 0:I.filter(Ie=>Ie.kit_id===he.id))||[],Te=(P==null?void 0:P.filter(Ie=>Ie.kit_id===he.id))||[];C({...he,files:Se,links:Te})},children:e.jsx(ba,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>O(he),children:e.jsx(ui,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:async()=>{await io("Delete this resource kit?")&&Q.mutate(he.id)},children:e.jsx(Un,{className:"h-4 w-4 text-destructive"})})]})})]},he.id))})]})})}),e.jsx(zs,{open:r,onOpenChange:a,children:e.jsxs(Rs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Vs,{children:e.jsx($s,{children:i?"Edit Resource Kit":"Add Resource Kit"})}),e.jsxs("form",{onSubmit:te,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Featured Image"}),e.jsxs("div",{className:"flex items-center gap-4",children:[h?e.jsx("img",{src:h,alt:"Preview",className:"w-24 h-24 rounded object-cover"}):e.jsx("div",{className:"w-24 h-24 rounded bg-muted flex items-center justify-center",children:e.jsx(bh,{className:"h-8 w-8 text-muted-foreground"})}),e.jsx(be,{type:"file",accept:"image/*",onChange:B})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"name",children:"Name *"}),e.jsx(be,{id:"name",value:o.name,onChange:he=>c({...o,name:he.target.value}),placeholder:"Resource Kit Name"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Description"}),e.jsx(V2,{content:o.description,onChange:he=>c({...o,description:he}),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(re,{htmlFor:"publish_date",children:"Publish Date"}),e.jsx(be,{id:"publish_date",type:"date",value:o.publish_date,onChange:he=>c({...o,publish_date:he.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Published"}),e.jsxs("div",{className:"flex items-center space-x-2 pt-2",children:[e.jsx(On,{checked:o.is_published,onCheckedChange:he=>c({...o,is_published:he})}),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(re,{children:"Resource Files"}),e.jsxs($,{type:"button",variant:"outline",size:"sm",onClick:U,children:[e.jsx(nn,{className:"h-4 w-4 mr-1"}),"Add File"]})]}),p.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:p.map((he,Se)=>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 ",Se+1]}),e.jsx($,{type:"button",variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>G(Se),children:e.jsx(mr,{className:"h-4 w-4"})})]}),e.jsx(be,{placeholder:"File name (e.g., Getting Started Guide)",value:he.name,onChange:Te=>H(Se,"name",Te.target.value)}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(be,{type:"file",onChange:Te=>oe(Se,Te),className:"flex-1"}),he.file_url&&!he.file&&e.jsx("a",{href:he.file_url,target:"_blank",rel:"noopener noreferrer",className:"text-sm text-primary hover:underline whitespace-nowrap",children:"Current file"}),he.file&&e.jsx("span",{className:"text-sm text-green-600 whitespace-nowrap",children:"New file selected"})]})]},Se))})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx(re,{children:"Canva Links"}),e.jsxs($,{type:"button",variant:"outline",size:"sm",onClick:Y,children:[e.jsx(nn,{className:"h-4 w-4 mr-1"}),"Add Canva Link"]})]}),x.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:x.map((he,Se)=>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 ",Se+1]}),e.jsx($,{type:"button",variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>se(Se),children:e.jsx(mr,{className:"h-4 w-4"})})]}),e.jsx(be,{placeholder:"Link title (e.g., Social Media Post Template)",value:he.title,onChange:Te=>ee(Se,"title",Te.target.value)}),e.jsx(be,{placeholder:"Canva share link (e.g., https://www.canva.com/design/...)",value:he.canva_share_link,onChange:Te=>ee(Se,"canva_share_link",Te.target.value)})]},Se))})]}),e.jsx(ERt,{selectedTemplateIds:v,onChange:_}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx($,{type:"button",variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx($,{type:"submit",disabled:me.isPending,children:me.isPending?"Saving...":i?"Update":"Create"})]})]})]})}),e.jsx(zs,{open:!!j,onOpenChange:()=>C(null),children:e.jsxs(Rs,{className:"max-w-lg",children:[e.jsx(Vs,{children:e.jsx($s,{children:j==null?void 0:j.name})}),e.jsxs("div",{className:"space-y-4",children:[(j==null?void 0:j.featured_image_url)&&e.jsx("img",{src:j.featured_image_url,alt:j.name,className:"w-full h-48 object-cover rounded-lg"}),(j==null?void 0:j.description)&&e.jsx("p",{className:"text-muted-foreground",children:j.description}),e.jsxs("div",{children:[e.jsxs("h4",{className:"font-medium mb-2",children:["Resource Files (",((fe=j==null?void 0:j.files)==null?void 0:fe.length)||0,")"]}),((_e=j==null?void 0:j.files)==null?void 0:_e.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:(ve=j==null?void 0:j.files)==null?void 0:ve.map(he=>e.jsxs("a",{href:he.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(ea,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"text-sm",children:he.name})]},he.id))})]}),(j==null?void 0:j.links)&&j.links.length>0&&e.jsxs("div",{children:[e.jsxs("h4",{className:"font-medium mb-2",children:["Canva Links (",j.links.length,")"]}),e.jsx("div",{className:"space-y-2",children:j.links.map(he=>e.jsxs("a",{href:he.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(od,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"text-sm",children:he.title})]},he.id))})]})]})]})})]})})}const JVs=()=>{const{user:s}=ks(),{toast:t}=Fi(),n=ls(),[r,a]=k.useState(!1),[i,l]=k.useState(null),[o,c]=k.useState({title:"",description:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1,links:[{title:"",canva_share_link:"",sort_order:0}]}),[d,u]=k.useState(null),[h,m]=k.useState(""),{data:p=[],isLoading:g}=pt({queryKey:["social-swag-admin"],queryFn:async()=>{const{data:P,error:R}=await V.from("social_swag").select("*").order("publish_date",{ascending:!1});if(R)throw R;const{data:O,error:B}=await V.from("social_swag_links").select("*").order("sort_order");if(B)throw B;return P.map(G=>({...G,links:(O==null?void 0:O.filter(H=>H.swag_id===G.id))||[]}))}}),x=Nt({mutationFn:async P=>{let R=P.existingImageUrl;if(P.image){const Y=P.image.name.split(".").pop(),se=`${Date.now()}-${Math.random().toString(36).substring(7)}.${Y}`,{error:ee}=await V.storage.from("template-previews").upload(se,P.image);if(ee)throw ee;const{data:oe}=V.storage.from("template-previews").getPublicUrl(se);R=oe.publicUrl}const O={title:P.item.title,description:P.item.description||null,preview_image_url:R,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};let B=P.itemId;const U=!B,G=(i==null?void 0:i.is_published)||!1;if(B){const{error:Y}=await V.from("social_swag").update(O).eq("id",B);if(Y)throw Y;await V.from("social_swag_links").delete().eq("swag_id",B)}else{const{data:Y,error:se}=await V.from("social_swag").insert(O).select().single();if(se)throw se;B=Y.id}const H=P.item.links.filter(Y=>Y.title.trim()&&Y.canva_share_link.trim());if(H.length>0){const Y=H.map((ee,oe)=>({swag_id:B,title:ee.title.trim(),canva_share_link:ee.canva_share_link.trim(),sort_order:oe})),{error:se}=await V.from("social_swag_links").insert(Y);if(se)throw se}return{itemId:B,itemTitle:P.item.title,isNewItem:U,wasPublished:G,isPublished:P.item.is_published}},onSuccess:P=>{n.invalidateQueries({queryKey:["social-swag-admin"]}),n.invalidateQueries({queryKey:["social-swag"]}),t({title:i?"Item updated":"Item created"}),P.isPublished&&(P.isNewItem||!P.wasPublished)&&sze(P.itemTitle,P.itemId),a(!1),v()},onError:P=>{t({title:"Error saving item",description:P.message,variant:"destructive"})}}),y=Nt({mutationFn:async P=>{const{error:R}=await V.from("social_swag").delete().eq("id",P);if(R)throw R},onSuccess:()=>{n.invalidateQueries({queryKey:["social-swag-admin"]}),n.invalidateQueries({queryKey:["social-swag"]}),t({title:"Item deleted"})},onError:P=>{t({title:"Error deleting item",description:P.message,variant:"destructive"})}}),v=()=>{c({title:"",description:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1,links:[{title:"",canva_share_link:"",sort_order:0}]}),u(null),m(""),l(null)},_=P=>{l(P),c({title:P.title,description:P.description||"",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,links:P.links&&P.links.length>0?P.links.map(R=>({id:R.id,title:R.title,canva_share_link:R.canva_share_link,sort_order:R.sort_order})):[{title:"",canva_share_link:"",sort_order:0}]}),m(P.preview_image_url||""),a(!0)},j=P=>{var O;const R=(O=P.target.files)==null?void 0:O[0];R&&(u(R),m(URL.createObjectURL(R)))},C=()=>{c({...o,links:[...o.links,{title:"",canva_share_link:"",sort_order:o.links.length}]})},A=P=>{if(o.links.length<=1)return;const R=o.links.filter((O,B)=>B!==P);c({...o,links:R})},M=(P,R,O)=>{const B=[...o.links];B[P]={...B[P],[R]:O},c({...o,links:B})},I=P=>{if(P.preventDefault(),!o.title.trim()){t({title:"Title is required",variant:"destructive"});return}x.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(Xs,{title:"Manage Social Swag",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(nm,{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(we,{children:[e.jsx(Vt,{className:"pb-2",children:e.jsx(Yt,{className:"text-sm font-medium text-muted-foreground",children:"Total Items"})}),e.jsx(De,{children:e.jsx("div",{className:"text-2xl font-bold",children:p.length})})]}),e.jsxs(we,{children:[e.jsx(Vt,{className:"pb-2",children:e.jsx(Yt,{className:"text-sm font-medium text-muted-foreground",children:"Published"})}),e.jsx(De,{children:e.jsx("div",{className:"text-2xl font-bold",children:p.filter(P=>P.is_published).length})})]})]}),e.jsxs(zs,{open:r,onOpenChange:P=>{a(P),P||v()},children:[e.jsx(yl,{asChild:!0,children:e.jsxs($,{className:"gap-2",children:[e.jsx(nn,{className:"h-4 w-4"}),"Add Item"]})}),e.jsxs(Rs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Vs,{children:e.jsx($s,{children:i?"Edit Item":"Add New Item"})}),e.jsxs("form",{onSubmit:I,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"title",children:"Title *"}),e.jsx(be,{id:"title",value:o.title,onChange:P=>c({...o,title:P.target.value}),placeholder:"Enter title"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Description"}),e.jsx(V2,{content:o.description,onChange:P=>c({...o,description:P}),placeholder:"Enter description",minHeight:"120px"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"publish_date",children:"Publish Date"}),e.jsx(be,{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(On,{id:"is_published",checked:o.is_published,onCheckedChange:P=>c({...o,is_published:P})}),e.jsx(re,{htmlFor:"is_published",children:"Published"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Preview Image"}),h?e.jsxs("div",{className:"relative",children:[e.jsx("img",{src:h,alt:"Preview",className:"w-full max-h-48 object-contain rounded-lg border"}),e.jsx($,{type:"button",variant:"destructive",size:"icon",className:"absolute top-2 right-2 h-6 w-6",onClick:()=>{u(null),m("")},children:e.jsx(mr,{className:"h-3 w-3"})})]}):e.jsxs("div",{className:"border-2 border-dashed rounded-lg p-4 text-center",children:[e.jsx(zc,{className:"h-8 w-8 mx-auto text-muted-foreground mb-2"}),e.jsx(be,{type:"file",accept:"image/*",onChange:j,className:"cursor-pointer"})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(re,{children:"Canva Links"}),e.jsxs($,{type:"button",variant:"outline",size:"sm",onClick:C,children:[e.jsx(nn,{className:"h-3 w-3 mr-1"}),"Add Link"]})]}),o.links.map((P,R)=>e.jsx(we,{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 ",R+1]}),o.links.length>1&&e.jsx($,{type:"button",variant:"ghost",size:"icon",className:"h-6 w-6 ml-auto",onClick:()=>A(R),children:e.jsx(mr,{className:"h-3 w-3"})})]}),e.jsx(be,{placeholder:"Link title (e.g., Instagram Post)",value:P.title,onChange:O=>M(R,"title",O.target.value)}),e.jsx(be,{placeholder:"Canva share link",value:P.canva_share_link,onChange:O=>M(R,"canva_share_link",O.target.value)})]})},R))]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx($,{type:"button",variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx($,{type:"submit",disabled:x.isPending,children:x.isPending?"Saving...":i?"Update":"Create"})]})]})]})]})]}),e.jsx(we,{children:e.jsx(De,{className:"p-0",children:g?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):p.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(Qa,{children:[e.jsx(Ja,{children:e.jsxs(vn,{children:[e.jsx(Dt,{className:"w-16",children:"Preview"}),e.jsx(Dt,{children:"Title"}),e.jsx(Dt,{children:"Links"}),e.jsx(Dt,{children:"Publish Date"}),e.jsx(Dt,{children:"Status"}),e.jsx(Dt,{className:"text-right",children:"Actions"})]})}),e.jsx(ei,{children:p.map(P=>{var R;return e.jsxs(vn,{children:[e.jsx(_t,{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(zc,{className:"h-4 w-4 text-muted-foreground"})})}),e.jsx(_t,{className:"font-medium",children:P.title}),e.jsxs(_t,{children:[((R=P.links)==null?void 0:R.length)||0," links"]}),e.jsx(_t,{children:new Date(P.publish_date).toLocaleDateString()}),e.jsx(_t,{children:e.jsx(qe,{variant:P.is_published?"default":"secondary",children:P.is_published?"Published":"Draft"})}),e.jsx(_t,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx($,{variant:"ghost",size:"icon",onClick:()=>window.open(`/social-swag/${P.id}`,"_blank"),children:e.jsx(ba,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>_(P),children:e.jsx(ui,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:async()=>{await io("Are you sure you want to delete this item?")&&y.mutate(P.id)},children:e.jsx(Un,{className:"h-4 w-4"})})]})})]},P.id)})})]})})})]})})};function eHs(){for(var s=arguments.length,t=new Array(s),n=0;nr=>{t.forEach(a=>a(r))},t)}const WAe=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";function iV(s){const t=Object.prototype.toString.call(s);return t==="[object Window]"||t==="[object global]"}function nYe(s){return"nodeType"in s}function z_(s){var t,n;return s?iV(s)?s:nYe(s)&&(t=(n=s.ownerDocument)==null?void 0:n.defaultView)!=null?t:window:window}function rYe(s){const{Document:t}=z_(s);return s instanceof t}function Vee(s){return iV(s)?!1:s instanceof z_(s).HTMLElement}function TRt(s){return s instanceof z_(s).SVGElement}function oV(s){return s?iV(s)?s.document:nYe(s)?rYe(s)?s:Vee(s)||TRt(s)?s.ownerDocument:document:document:document}const W5=WAe?k.useLayoutEffect:k.useEffect;function aYe(s){const t=k.useRef(s);return W5(()=>{t.current=s}),k.useCallback(function(){for(var n=arguments.length,r=new Array(n),a=0;a{s.current=setInterval(r,a)},[]),n=k.useCallback(()=>{s.current!==null&&(clearInterval(s.current),s.current=null)},[]);return[t,n]}function _X(s,t){t===void 0&&(t=[s]);const n=k.useRef(s);return W5(()=>{n.current!==s&&(n.current=s)},t),n}function Hee(s,t){const n=k.useRef();return k.useMemo(()=>{const r=s(n.current);return n.current=r,r},[...t])}function v5e(s){const t=aYe(s),n=k.useRef(null),r=k.useCallback(a=>{a!==n.current&&(t==null||t(a,n.current)),n.current=a},[]);return[n,r]}function nze(s){const t=k.useRef();return k.useEffect(()=>{t.current=s},[s]),t.current}let sRe={};function Gee(s,t){return k.useMemo(()=>{if(t)return t;const n=sRe[s]==null?0:sRe[s]+1;return sRe[s]=n,s+"-"+n},[s,t])}function MRt(s){return function(t){for(var n=arguments.length,r=new Array(n>1?n-1:0),a=1;a{const o=Object.entries(l);for(const[c,d]of o){const u=i[c];u!=null&&(i[c]=u+s*d)}return i},{...t})}}const EB=MRt(1),wX=MRt(-1);function sHs(s){return"clientX"in s&&"clientY"in s}function iYe(s){if(!s)return!1;const{KeyboardEvent:t}=z_(s.target);return t&&s instanceof t}function nHs(s){if(!s)return!1;const{TouchEvent:t}=z_(s.target);return t&&s instanceof t}function rze(s){if(nHs(s)){if(s.touches&&s.touches.length){const{clientX:t,clientY:n}=s.touches[0];return{x:t,y:n}}else if(s.changedTouches&&s.changedTouches.length){const{clientX:t,clientY:n}=s.changedTouches[0];return{x:t,y:n}}}return sHs(s)?{x:s.clientX,y:s.clientY}:null}const PM=Object.freeze({Translate:{toString(s){if(!s)return;const{x:t,y:n}=s;return"translate3d("+(t?Math.round(t):0)+"px, "+(n?Math.round(n):0)+"px, 0)"}},Scale:{toString(s){if(!s)return;const{scaleX:t,scaleY:n}=s;return"scaleX("+t+") scaleY("+n+")"}},Transform:{toString(s){if(s)return[PM.Translate.toString(s),PM.Scale.toString(s)].join(" ")}},Transition:{toString(s){let{property:t,duration:n,easing:r}=s;return t+" "+n+"ms "+r}}}),tmt="a,frame,iframe,input:not([type=hidden]):not(:disabled),select:not(:disabled),textarea:not(:disabled),button:not(:disabled),*[tabindex]";function rHs(s){return s.matches(tmt)?s:s.querySelector(tmt)}const aHs={display:"none"};function iHs(s){let{id:t,value:n}=s;return zt.createElement("div",{id:t,style:aHs},n)}function oHs(s){let{id:t,announcement:n,ariaLiveType:r="assertive"}=s;const a={position:"fixed",top:0,left:0,width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(100%)",whiteSpace:"nowrap"};return zt.createElement("div",{id:t,style:a,role:"status","aria-live":r,"aria-atomic":!0},n)}function lHs(){const[s,t]=k.useState("");return{announce:k.useCallback(r=>{r!=null&&t(r)},[]),announcement:s}}const PRt=k.createContext(null);function cHs(s){const t=k.useContext(PRt);k.useEffect(()=>{if(!t)throw new Error("useDndMonitor must be used within a children of ");return t(s)},[s,t])}function dHs(){const[s]=k.useState(()=>new Set),t=k.useCallback(r=>(s.add(r),()=>s.delete(r)),[s]);return[k.useCallback(r=>{let{type:a,event:i}=r;s.forEach(l=>{var o;return(o=l[a])==null?void 0:o.call(l,i)})},[s]),t]}const uHs={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. `},hHs={onDragStart(s){let{active:t}=s;return"Picked up draggable item "+t.id+"."},onDragOver(s){let{active:t,over:n}=s;return n?"Draggable item "+t.id+" was moved over droppable area "+n.id+".":"Draggable item "+t.id+" is no longer over a droppable area."},onDragEnd(s){let{active:t,over:n}=s;return n?"Draggable item "+t.id+" was dropped over droppable area "+n.id:"Draggable item "+t.id+" was dropped."},onDragCancel(s){let{active:t}=s;return"Dragging was cancelled. Draggable item "+t.id+" was dropped."}};function mHs(s){let{announcements:t=hHs,container:n,hiddenTextDescribedById:r,screenReaderInstructions:a=uHs}=s;const{announce:i,announcement:l}=lHs(),o=Gee("DndLiveRegion"),[c,d]=k.useState(!1);if(k.useEffect(()=>{d(!0)},[]),cHs(k.useMemo(()=>({onDragStart(h){let{active:m}=h;i(t.onDragStart({active:m}))},onDragMove(h){let{active:m,over:p}=h;t.onDragMove&&i(t.onDragMove({active:m,over:p}))},onDragOver(h){let{active:m,over:p}=h;i(t.onDragOver({active:m,over:p}))},onDragEnd(h){let{active:m,over:p}=h;i(t.onDragEnd({active:m,over:p}))},onDragCancel(h){let{active:m,over:p}=h;i(t.onDragCancel({active:m,over:p}))}}),[i,t])),!c)return null;const u=zt.createElement(zt.Fragment,null,zt.createElement(iHs,{id:r,value:a.draggable}),zt.createElement(oHs,{id:o,announcement:l}));return n?a1.createPortal(u,n):u}var py;(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"})(py||(py={}));function b5e(){}function LU(s,t){return k.useMemo(()=>({sensor:s,options:t??{}}),[s,t])}function KAe(){for(var s=arguments.length,t=new Array(s),n=0;n[...t].filter(r=>r!=null),[...t])}const bk=Object.freeze({x:0,y:0});function IRt(s,t){return Math.sqrt(Math.pow(s.x-t.x,2)+Math.pow(s.y-t.y,2))}function LRt(s,t){let{data:{value:n}}=s,{data:{value:r}}=t;return n-r}function fHs(s,t){let{data:{value:n}}=s,{data:{value:r}}=t;return r-n}function smt(s){let{left:t,top:n,height:r,width:a}=s;return[{x:t,y:n},{x:t+a,y:n},{x:t,y:n+r},{x:t+a,y:n+r}]}function RRt(s,t){if(!s||s.length===0)return null;const[n]=s;return n[t]}function nmt(s,t,n){return t===void 0&&(t=s.left),n===void 0&&(n=s.top),{x:t+s.width*.5,y:n+s.height*.5}}const YAe=s=>{let{collisionRect:t,droppableRects:n,droppableContainers:r}=s;const a=nmt(t,t.left,t.top),i=[];for(const l of r){const{id:o}=l,c=n.get(o);if(c){const d=IRt(nmt(c),a);i.push({id:o,data:{droppableContainer:l,value:d}})}}return i.sort(LRt)},pHs=s=>{let{collisionRect:t,droppableRects:n,droppableContainers:r}=s;const a=smt(t),i=[];for(const l of r){const{id:o}=l,c=n.get(o);if(c){const d=smt(c),u=a.reduce((m,p,g)=>m+IRt(d[g],p),0),h=Number((u/4).toFixed(4));i.push({id:o,data:{droppableContainer:l,value:h}})}}return i.sort(LRt)};function gHs(s,t){const n=Math.max(t.top,s.top),r=Math.max(t.left,s.left),a=Math.min(t.left+t.width,s.left+s.width),i=Math.min(t.top+t.height,s.top+s.height),l=a-r,o=i-n;if(r{let{collisionRect:t,droppableRects:n,droppableContainers:r}=s;const a=[];for(const i of r){const{id:l}=i,o=n.get(l);if(o){const c=gHs(o,t);c>0&&a.push({id:l,data:{droppableContainer:i,value:c}})}}return a.sort(fHs)};function yHs(s,t,n){return{...s,scaleX:t&&n?t.width/n.width:1,scaleY:t&&n?t.height/n.height:1}}function DRt(s,t){return s&&t?{x:s.left-t.left,y:s.top-t.top}:bk}function vHs(s){return function(n){for(var r=arguments.length,a=new Array(r>1?r-1:0),i=1;i({...l,top:l.top+s*o.y,bottom:l.bottom+s*o.y,left:l.left+s*o.x,right:l.right+s*o.x}),{...n})}}const bHs=vHs(1);function _Hs(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 wHs(s,t,n){const r=_Hs(t);if(!r)return s;const{scaleX:a,scaleY:i,x:l,y:o}=r,c=s.left-l-(1-a)*parseFloat(n),d=s.top-o-(1-i)*parseFloat(n.slice(n.indexOf(" ")+1)),u=a?s.width/a:s.width,h=i?s.height/i:s.height;return{width:u,height:h,top:d,right:c+u,bottom:d+h,left:c}}const jHs={ignoreTransform:!1};function lV(s,t){t===void 0&&(t=jHs);let n=s.getBoundingClientRect();if(t.ignoreTransform){const{transform:d,transformOrigin:u}=z_(s).getComputedStyle(s);d&&(n=wHs(n,d,u))}const{top:r,left:a,width:i,height:l,bottom:o,right:c}=n;return{top:r,left:a,width:i,height:l,bottom:o,right:c}}function rmt(s){return lV(s,{ignoreTransform:!0})}function NHs(s){const t=s.innerWidth,n=s.innerHeight;return{top:0,left:0,right:t,bottom:n,width:t,height:n}}function kHs(s,t){return t===void 0&&(t=z_(s).getComputedStyle(s)),t.position==="fixed"}function SHs(s,t){t===void 0&&(t=z_(s).getComputedStyle(s));const n=/(auto|scroll|overlay)/;return["overflow","overflowX","overflowY"].some(a=>{const i=t[a];return typeof i=="string"?n.test(i):!1})}function ZAe(s,t){const n=[];function r(a){if(t!=null&&n.length>=t||!a)return n;if(rYe(a)&&a.scrollingElement!=null&&!n.includes(a.scrollingElement))return n.push(a.scrollingElement),n;if(!Vee(a)||TRt(a)||n.includes(a))return n;const i=z_(s).getComputedStyle(a);return a!==s&&SHs(a,i)&&n.push(a),kHs(a,i)?n:r(a.parentNode)}return s?r(s):n}function ORt(s){const[t]=ZAe(s,1);return t??null}function nRe(s){return!WAe||!s?null:iV(s)?s:nYe(s)?rYe(s)||s===oV(s).scrollingElement?window:Vee(s)?s:null:null}function FRt(s){return iV(s)?s.scrollX:s.scrollLeft}function zRt(s){return iV(s)?s.scrollY:s.scrollTop}function aze(s){return{x:FRt(s),y:zRt(s)}}var i0;(function(s){s[s.Forward=1]="Forward",s[s.Backward=-1]="Backward"})(i0||(i0={}));function BRt(s){return!WAe||!s?!1:s===document.scrollingElement}function $Rt(s){const t={x:0,y:0},n=BRt(s)?{height:window.innerHeight,width:window.innerWidth}:{height:s.clientHeight,width:s.clientWidth},r={x:s.scrollWidth-n.width,y:s.scrollHeight-n.height},a=s.scrollTop<=t.y,i=s.scrollLeft<=t.x,l=s.scrollTop>=r.y,o=s.scrollLeft>=r.x;return{isTop:a,isLeft:i,isBottom:l,isRight:o,maxScroll:r,minScroll:t}}const CHs={x:.2,y:.2};function AHs(s,t,n,r,a){let{top:i,left:l,right:o,bottom:c}=n;r===void 0&&(r=10),a===void 0&&(a=CHs);const{isTop:d,isBottom:u,isLeft:h,isRight:m}=$Rt(s),p={x:0,y:0},g={x:0,y:0},x={height:t.height*a.y,width:t.width*a.x};return!d&&i<=t.top+x.height?(p.y=i0.Backward,g.y=r*Math.abs((t.top+x.height-i)/x.height)):!u&&c>=t.bottom-x.height&&(p.y=i0.Forward,g.y=r*Math.abs((t.bottom-x.height-c)/x.height)),!m&&o>=t.right-x.width?(p.x=i0.Forward,g.x=r*Math.abs((t.right-x.width-o)/x.width)):!h&&l<=t.left+x.width&&(p.x=i0.Backward,g.x=r*Math.abs((t.left+x.width-l)/x.width)),{direction:p,speed:g}}function EHs(s){if(s===document.scrollingElement){const{innerWidth:i,innerHeight:l}=window;return{top:0,left:0,right:i,bottom:l,width:i,height:l}}const{top:t,left:n,right:r,bottom:a}=s.getBoundingClientRect();return{top:t,left:n,right:r,bottom:a,width:s.clientWidth,height:s.clientHeight}}function URt(s){return s.reduce((t,n)=>EB(t,aze(n)),bk)}function THs(s){return s.reduce((t,n)=>t+FRt(n),0)}function MHs(s){return s.reduce((t,n)=>t+zRt(n),0)}function PHs(s,t){if(t===void 0&&(t=lV),!s)return;const{top:n,left:r,bottom:a,right:i}=t(s);ORt(s)&&(a<=0||i<=0||n>=window.innerHeight||r>=window.innerWidth)&&s.scrollIntoView({block:"center",inline:"center"})}const IHs=[["x",["left","right"],THs],["y",["top","bottom"],MHs]];class oYe{constructor(t,n){this.rect=void 0,this.width=void 0,this.height=void 0,this.top=void 0,this.bottom=void 0,this.right=void 0,this.left=void 0;const r=ZAe(n),a=URt(r);this.rect={...t},this.width=t.width,this.height=t.height;for(const[i,l,o]of IHs)for(const c of l)Object.defineProperty(this,c,{get:()=>{const d=o(r),u=a[i]-d;return this.rect[c]+u},enumerable:!0});Object.defineProperty(this,"rect",{enumerable:!1})}}class $Y{constructor(t){this.target=void 0,this.listeners=[],this.removeAll=()=>{this.listeners.forEach(n=>{var r;return(r=this.target)==null?void 0:r.removeEventListener(...n)})},this.target=t}add(t,n,r){var a;(a=this.target)==null||a.addEventListener(t,n,r),this.listeners.push([t,n,r])}}function LHs(s){const{EventTarget:t}=z_(s);return s instanceof t?s:oV(s)}function rRe(s,t){const n=Math.abs(s.x),r=Math.abs(s.y);return typeof t=="number"?Math.sqrt(n**2+r**2)>t:"x"in t&&"y"in t?n>t.x&&r>t.y:"x"in t?n>t.x:"y"in t?r>t.y:!1}var Jj;(function(s){s.Click="click",s.DragStart="dragstart",s.Keydown="keydown",s.ContextMenu="contextmenu",s.Resize="resize",s.SelectionChange="selectionchange",s.VisibilityChange="visibilitychange"})(Jj||(Jj={}));function amt(s){s.preventDefault()}function RHs(s){s.stopPropagation()}var su;(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"})(su||(su={}));const qRt={start:[su.Space,su.Enter],cancel:[su.Esc],end:[su.Space,su.Enter,su.Tab]},DHs=(s,t)=>{let{currentCoordinates:n}=t;switch(s.code){case su.Right:return{...n,x:n.x+25};case su.Left:return{...n,x:n.x-25};case su.Down:return{...n,y:n.y+25};case su.Up:return{...n,y:n.y-25}}};class XAe{constructor(t){this.props=void 0,this.autoScrollEnabled=!1,this.referenceCoordinates=void 0,this.listeners=void 0,this.windowListeners=void 0,this.props=t;const{event:{target:n}}=t;this.props=t,this.listeners=new $Y(oV(n)),this.windowListeners=new $Y(z_(n)),this.handleKeyDown=this.handleKeyDown.bind(this),this.handleCancel=this.handleCancel.bind(this),this.attach()}attach(){this.handleStart(),this.windowListeners.add(Jj.Resize,this.handleCancel),this.windowListeners.add(Jj.VisibilityChange,this.handleCancel),setTimeout(()=>this.listeners.add(Jj.Keydown,this.handleKeyDown))}handleStart(){const{activeNode:t,onStart:n}=this.props,r=t.node.current;r&&PHs(r),n(bk)}handleKeyDown(t){if(iYe(t)){const{active:n,context:r,options:a}=this.props,{keyboardCodes:i=qRt,coordinateGetter:l=DHs,scrollBehavior:o="smooth"}=a,{code:c}=t;if(i.end.includes(c)){this.handleEnd(t);return}if(i.cancel.includes(c)){this.handleCancel(t);return}const{collisionRect:d}=r.current,u=d?{x:d.left,y:d.top}:bk;this.referenceCoordinates||(this.referenceCoordinates=u);const h=l(t,{active:n,context:r.current,currentCoordinates:u});if(h){const m=wX(h,u),p={x:0,y:0},{scrollableAncestors:g}=r.current;for(const x of g){const y=t.code,{isTop:v,isRight:_,isLeft:j,isBottom:C,maxScroll:A,minScroll:M}=$Rt(x),I=EHs(x),P={x:Math.min(y===su.Right?I.right-I.width/2:I.right,Math.max(y===su.Right?I.left:I.left+I.width/2,h.x)),y:Math.min(y===su.Down?I.bottom-I.height/2:I.bottom,Math.max(y===su.Down?I.top:I.top+I.height/2,h.y))},R=y===su.Right&&!_||y===su.Left&&!j,O=y===su.Down&&!C||y===su.Up&&!v;if(R&&P.x!==h.x){const B=x.scrollLeft+m.x,U=y===su.Right&&B<=A.x||y===su.Left&&B>=M.x;if(U&&!m.y){x.scrollTo({left:B,behavior:o});return}U?p.x=x.scrollLeft-B:p.x=y===su.Right?x.scrollLeft-A.x:x.scrollLeft-M.x,p.x&&x.scrollBy({left:-p.x,behavior:o});break}else if(O&&P.y!==h.y){const B=x.scrollTop+m.y,U=y===su.Down&&B<=A.y||y===su.Up&&B>=M.y;if(U&&!m.x){x.scrollTo({top:B,behavior:o});return}U?p.y=x.scrollTop-B:p.y=y===su.Down?x.scrollTop-A.y:x.scrollTop-M.y,p.y&&x.scrollBy({top:-p.y,behavior:o});break}}this.handleMove(t,EB(wX(h,this.referenceCoordinates),p))}}}handleMove(t,n){const{onMove:r}=this.props;t.preventDefault(),r(n)}handleEnd(t){const{onEnd:n}=this.props;t.preventDefault(),this.detach(),n()}handleCancel(t){const{onCancel:n}=this.props;t.preventDefault(),this.detach(),n()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll()}}XAe.activators=[{eventName:"onKeyDown",handler:(s,t,n)=>{let{keyboardCodes:r=qRt,onActivation:a}=t,{active:i}=n;const{code:l}=s.nativeEvent;if(r.start.includes(l)){const o=i.activatorNode.current;return o&&s.target!==o?!1:(s.preventDefault(),a==null||a({event:s.nativeEvent}),!0)}return!1}}];function imt(s){return!!(s&&"distance"in s)}function omt(s){return!!(s&&"delay"in s)}class lYe{constructor(t,n,r){var a;r===void 0&&(r=LHs(t.event.target)),this.props=void 0,this.events=void 0,this.autoScrollEnabled=!0,this.document=void 0,this.activated=!1,this.initialCoordinates=void 0,this.timeoutId=null,this.listeners=void 0,this.documentListeners=void 0,this.windowListeners=void 0,this.props=t,this.events=n;const{event:i}=t,{target:l}=i;this.props=t,this.events=n,this.document=oV(l),this.documentListeners=new $Y(this.document),this.listeners=new $Y(r),this.windowListeners=new $Y(z_(l)),this.initialCoordinates=(a=rze(i))!=null?a:bk,this.handleStart=this.handleStart.bind(this),this.handleMove=this.handleMove.bind(this),this.handleEnd=this.handleEnd.bind(this),this.handleCancel=this.handleCancel.bind(this),this.handleKeydown=this.handleKeydown.bind(this),this.removeTextSelection=this.removeTextSelection.bind(this),this.attach()}attach(){const{events:t,props:{options:{activationConstraint:n,bypassActivationConstraint:r}}}=this;if(this.listeners.add(t.move.name,this.handleMove,{passive:!1}),this.listeners.add(t.end.name,this.handleEnd),t.cancel&&this.listeners.add(t.cancel.name,this.handleCancel),this.windowListeners.add(Jj.Resize,this.handleCancel),this.windowListeners.add(Jj.DragStart,amt),this.windowListeners.add(Jj.VisibilityChange,this.handleCancel),this.windowListeners.add(Jj.ContextMenu,amt),this.documentListeners.add(Jj.Keydown,this.handleKeydown),n){if(r!=null&&r({event:this.props.event,activeNode:this.props.activeNode,options:this.props.options}))return this.handleStart();if(omt(n)){this.timeoutId=setTimeout(this.handleStart,n.delay),this.handlePending(n);return}if(imt(n)){this.handlePending(n);return}}this.handleStart()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll(),setTimeout(this.documentListeners.removeAll,50),this.timeoutId!==null&&(clearTimeout(this.timeoutId),this.timeoutId=null)}handlePending(t,n){const{active:r,onPending:a}=this.props;a(r,t,this.initialCoordinates,n)}handleStart(){const{initialCoordinates:t}=this,{onStart:n}=this.props;t&&(this.activated=!0,this.documentListeners.add(Jj.Click,RHs,{capture:!0}),this.removeTextSelection(),this.documentListeners.add(Jj.SelectionChange,this.removeTextSelection),n(t))}handleMove(t){var n;const{activated:r,initialCoordinates:a,props:i}=this,{onMove:l,options:{activationConstraint:o}}=i;if(!a)return;const c=(n=rze(t))!=null?n:bk,d=wX(a,c);if(!r&&o){if(imt(o)){if(o.tolerance!=null&&rRe(d,o.tolerance))return this.handleCancel();if(rRe(d,o.distance))return this.handleStart()}if(omt(o)&&rRe(d,o.tolerance))return this.handleCancel();this.handlePending(o,d);return}t.cancelable&&t.preventDefault(),l(c)}handleEnd(){const{onAbort:t,onEnd:n}=this.props;this.detach(),this.activated||t(this.props.active),n()}handleCancel(){const{onAbort:t,onCancel:n}=this.props;this.detach(),this.activated||t(this.props.active),n()}handleKeydown(t){t.code===su.Esc&&this.handleCancel()}removeTextSelection(){var t;(t=this.document.getSelection())==null||t.removeAllRanges()}}const OHs={cancel:{name:"pointercancel"},move:{name:"pointermove"},end:{name:"pointerup"}};class cV extends lYe{constructor(t){const{event:n}=t,r=oV(n.target);super(t,OHs,r)}}cV.activators=[{eventName:"onPointerDown",handler:(s,t)=>{let{nativeEvent:n}=s,{onActivation:r}=t;return!n.isPrimary||n.button!==0?!1:(r==null||r({event:n}),!0)}}];const FHs={move:{name:"mousemove"},end:{name:"mouseup"}};var ize;(function(s){s[s.RightClick=2]="RightClick"})(ize||(ize={}));class zHs extends lYe{constructor(t){super(t,FHs,oV(t.event.target))}}zHs.activators=[{eventName:"onMouseDown",handler:(s,t)=>{let{nativeEvent:n}=s,{onActivation:r}=t;return n.button===ize.RightClick?!1:(r==null||r({event:n}),!0)}}];const aRe={cancel:{name:"touchcancel"},move:{name:"touchmove"},end:{name:"touchend"}};class BHs extends lYe{constructor(t){super(t,aRe)}static setup(){return window.addEventListener(aRe.move.name,t,{capture:!1,passive:!1}),function(){window.removeEventListener(aRe.move.name,t)};function t(){}}}BHs.activators=[{eventName:"onTouchStart",handler:(s,t)=>{let{nativeEvent:n}=s,{onActivation:r}=t;const{touches:a}=n;return a.length>1?!1:(r==null||r({event:n}),!0)}}];var UY;(function(s){s[s.Pointer=0]="Pointer",s[s.DraggableRect=1]="DraggableRect"})(UY||(UY={}));var _5e;(function(s){s[s.TreeOrder=0]="TreeOrder",s[s.ReversedTreeOrder=1]="ReversedTreeOrder"})(_5e||(_5e={}));function $Hs(s){let{acceleration:t,activator:n=UY.Pointer,canScroll:r,draggingRect:a,enabled:i,interval:l=5,order:o=_5e.TreeOrder,pointerCoordinates:c,scrollableAncestors:d,scrollableAncestorRects:u,delta:h,threshold:m}=s;const p=qHs({delta:h,disabled:!i}),[g,x]=tHs(),y=k.useRef({x:0,y:0}),v=k.useRef({x:0,y:0}),_=k.useMemo(()=>{switch(n){case UY.Pointer:return c?{top:c.y,bottom:c.y,left:c.x,right:c.x}:null;case UY.DraggableRect:return a}},[n,a,c]),j=k.useRef(null),C=k.useCallback(()=>{const M=j.current;if(!M)return;const I=y.current.x*v.current.x,P=y.current.y*v.current.y;M.scrollBy(I,P)},[]),A=k.useMemo(()=>o===_5e.TreeOrder?[...d].reverse():d,[o,d]);k.useEffect(()=>{if(!i||!d.length||!_){x();return}for(const M of A){if((r==null?void 0:r(M))===!1)continue;const I=d.indexOf(M),P=u[I];if(!P)continue;const{direction:R,speed:O}=AHs(M,P,_,t,m);for(const B of["x","y"])p[B][R[B]]||(O[B]=0,R[B]=0);if(O.x>0||O.y>0){x(),j.current=M,g(C,l),y.current=O,v.current=R;return}}y.current={x:0,y:0},v.current={x:0,y:0},x()},[t,C,r,x,i,l,JSON.stringify(_),JSON.stringify(p),g,d,A,u,JSON.stringify(m)])}const UHs={x:{[i0.Backward]:!1,[i0.Forward]:!1},y:{[i0.Backward]:!1,[i0.Forward]:!1}};function qHs(s){let{delta:t,disabled:n}=s;const r=nze(t);return Hee(a=>{if(n||!r||!a)return UHs;const i={x:Math.sign(t.x-r.x),y:Math.sign(t.y-r.y)};return{x:{[i0.Backward]:a.x[i0.Backward]||i.x===-1,[i0.Forward]:a.x[i0.Forward]||i.x===1},y:{[i0.Backward]:a.y[i0.Backward]||i.y===-1,[i0.Forward]:a.y[i0.Forward]||i.y===1}}},[n,t,r])}function VHs(s,t){const n=t!=null?s.get(t):void 0,r=n?n.node.current:null;return Hee(a=>{var i;return t==null?null:(i=r??a)!=null?i:null},[r,t])}function HHs(s,t){return k.useMemo(()=>s.reduce((n,r)=>{const{sensor:a}=r,i=a.activators.map(l=>({eventName:l.eventName,handler:t(l.handler,r)}));return[...n,...i]},[]),[s,t])}var jX;(function(s){s[s.Always=0]="Always",s[s.BeforeDragging=1]="BeforeDragging",s[s.WhileDragging=2]="WhileDragging"})(jX||(jX={}));var oze;(function(s){s.Optimized="optimized"})(oze||(oze={}));const lmt=new Map;function GHs(s,t){let{dragging:n,dependencies:r,config:a}=t;const[i,l]=k.useState(null),{frequency:o,measure:c,strategy:d}=a,u=k.useRef(s),h=y(),m=_X(h),p=k.useCallback(function(v){v===void 0&&(v=[]),!m.current&&l(_=>_===null?v:_.concat(v.filter(j=>!_.includes(j))))},[m]),g=k.useRef(null),x=Hee(v=>{if(h&&!n)return lmt;if(!v||v===lmt||u.current!==s||i!=null){const _=new Map;for(let j of s){if(!j)continue;if(i&&i.length>0&&!i.includes(j.id)&&j.rect.current){_.set(j.id,j.rect.current);continue}const C=j.node.current,A=C?new oYe(c(C),C):null;j.rect.current=A,A&&_.set(j.id,A)}return _}return v},[s,i,n,h,c]);return k.useEffect(()=>{u.current=s},[s]),k.useEffect(()=>{h||p()},[n,h]),k.useEffect(()=>{i&&i.length>0&&l(null)},[JSON.stringify(i)]),k.useEffect(()=>{h||typeof o!="number"||g.current!==null||(g.current=setTimeout(()=>{p(),g.current=null},o))},[o,h,p,...r]),{droppableRects:x,measureDroppableContainers:p,measuringScheduled:i!=null};function y(){switch(d){case jX.Always:return!1;case jX.BeforeDragging:return n;default:return!n}}}function VRt(s,t){return Hee(n=>s?n||(typeof t=="function"?t(s):s):null,[t,s])}function WHs(s,t){return VRt(s,t)}function KHs(s){let{callback:t,disabled:n}=s;const r=aYe(t),a=k.useMemo(()=>{if(n||typeof window>"u"||typeof window.MutationObserver>"u")return;const{MutationObserver:i}=window;return new i(r)},[r,n]);return k.useEffect(()=>()=>a==null?void 0:a.disconnect(),[a]),a}function QAe(s){let{callback:t,disabled:n}=s;const r=aYe(t),a=k.useMemo(()=>{if(n||typeof window>"u"||typeof window.ResizeObserver>"u")return;const{ResizeObserver:i}=window;return new i(r)},[n]);return k.useEffect(()=>()=>a==null?void 0:a.disconnect(),[a]),a}function YHs(s){return new oYe(lV(s),s)}function cmt(s,t,n){t===void 0&&(t=YHs);const[r,a]=k.useState(null);function i(){a(c=>{if(!s)return null;if(s.isConnected===!1){var d;return(d=c??n)!=null?d:null}const u=t(s);return JSON.stringify(c)===JSON.stringify(u)?c:u})}const l=KHs({callback(c){if(s)for(const d of c){const{type:u,target:h}=d;if(u==="childList"&&h instanceof HTMLElement&&h.contains(s)){i();break}}}}),o=QAe({callback:i});return W5(()=>{i(),s?(o==null||o.observe(s),l==null||l.observe(document.body,{childList:!0,subtree:!0})):(o==null||o.disconnect(),l==null||l.disconnect())},[s]),r}function ZHs(s){const t=VRt(s);return DRt(s,t)}const dmt=[];function XHs(s){const t=k.useRef(s),n=Hee(r=>s?r&&r!==dmt&&s&&t.current&&s.parentNode===t.current.parentNode?r:ZAe(s):dmt,[s]);return k.useEffect(()=>{t.current=s},[s]),n}function QHs(s){const[t,n]=k.useState(null),r=k.useRef(s),a=k.useCallback(i=>{const l=nRe(i.target);l&&n(o=>o?(o.set(l,aze(l)),new Map(o)):null)},[]);return k.useEffect(()=>{const i=r.current;if(s!==i){l(i);const o=s.map(c=>{const d=nRe(c);return d?(d.addEventListener("scroll",a,{passive:!0}),[d,aze(d)]):null}).filter(c=>c!=null);n(o.length?new Map(o):null),r.current=s}return()=>{l(s),l(i)};function l(o){o.forEach(c=>{const d=nRe(c);d==null||d.removeEventListener("scroll",a)})}},[a,s]),k.useMemo(()=>s.length?t?Array.from(t.values()).reduce((i,l)=>EB(i,l),bk):URt(s):bk,[s,t])}function umt(s,t){t===void 0&&(t=[]);const n=k.useRef(null);return k.useEffect(()=>{n.current=null},t),k.useEffect(()=>{const r=s!==bk;r&&!n.current&&(n.current=s),!r&&n.current&&(n.current=null)},[s]),n.current?wX(s,n.current):bk}function JHs(s){k.useEffect(()=>{if(!WAe)return;const t=s.map(n=>{let{sensor:r}=n;return r.setup==null?void 0:r.setup()});return()=>{for(const n of t)n==null||n()}},s.map(t=>{let{sensor:n}=t;return n}))}function eGs(s,t){return k.useMemo(()=>s.reduce((n,r)=>{let{eventName:a,handler:i}=r;return n[a]=l=>{i(l,t)},n},{}),[s,t])}function HRt(s){return k.useMemo(()=>s?NHs(s):null,[s])}const hmt=[];function tGs(s,t){t===void 0&&(t=lV);const[n]=s,r=HRt(n?z_(n):null),[a,i]=k.useState(hmt);function l(){i(()=>s.length?s.map(c=>BRt(c)?r:new oYe(t(c),c)):hmt)}const o=QAe({callback:l});return W5(()=>{o==null||o.disconnect(),l(),s.forEach(c=>o==null?void 0:o.observe(c))},[s]),a}function sGs(s){if(!s)return null;if(s.children.length>1)return s;const t=s.children[0];return Vee(t)?t:s}function nGs(s){let{measure:t}=s;const[n,r]=k.useState(null),a=k.useCallback(d=>{for(const{target:u}of d)if(Vee(u)){r(h=>{const m=t(u);return h?{...h,width:m.width,height:m.height}:m});break}},[t]),i=QAe({callback:a}),l=k.useCallback(d=>{const u=sGs(d);i==null||i.disconnect(),u&&(i==null||i.observe(u)),r(u?t(u):null)},[t,i]),[o,c]=v5e(l);return k.useMemo(()=>({nodeRef:o,rect:n,setRef:c}),[n,o,c])}const rGs=[{sensor:cV,options:{}},{sensor:XAe,options:{}}],aGs={current:{}},jNe={draggable:{measure:rmt},droppable:{measure:rmt,strategy:jX.WhileDragging,frequency:oze.Optimized},dragOverlay:{measure:lV}};class qY extends Map{get(t){var n;return t!=null&&(n=super.get(t))!=null?n:void 0}toArray(){return Array.from(this.values())}getEnabled(){return this.toArray().filter(t=>{let{disabled:n}=t;return!n})}getNodeFor(t){var n,r;return(n=(r=this.get(t))==null?void 0:r.node.current)!=null?n:void 0}}const iGs={activatorEvent:null,active:null,activeNode:null,activeNodeRect:null,collisions:null,containerNodeRect:null,draggableNodes:new Map,droppableRects:new Map,droppableContainers:new qY,over:null,dragOverlay:{nodeRef:{current:null},rect:null,setRef:b5e},scrollableAncestors:[],scrollableAncestorRects:[],measuringConfiguration:jNe,measureDroppableContainers:b5e,windowRect:null,measuringScheduled:!1},oGs={activatorEvent:null,activators:[],active:null,activeNodeRect:null,ariaDescribedById:{draggable:""},dispatch:b5e,draggableNodes:new Map,over:null,measureDroppableContainers:b5e},JAe=k.createContext(oGs),GRt=k.createContext(iGs);function lGs(){return{draggable:{active:null,initialCoordinates:{x:0,y:0},nodes:new Map,translate:{x:0,y:0}},droppable:{containers:new qY}}}function cGs(s,t){switch(t.type){case py.DragStart:return{...s,draggable:{...s.draggable,initialCoordinates:t.initialCoordinates,active:t.active}};case py.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 py.DragEnd:case py.DragCancel:return{...s,draggable:{...s.draggable,active:null,initialCoordinates:{x:0,y:0},translate:{x:0,y:0}}};case py.RegisterDroppable:{const{element:n}=t,{id:r}=n,a=new qY(s.droppable.containers);return a.set(r,n),{...s,droppable:{...s.droppable,containers:a}}}case py.SetDroppableDisabled:{const{id:n,key:r,disabled:a}=t,i=s.droppable.containers.get(n);if(!i||r!==i.key)return s;const l=new qY(s.droppable.containers);return l.set(n,{...i,disabled:a}),{...s,droppable:{...s.droppable,containers:l}}}case py.UnregisterDroppable:{const{id:n,key:r}=t,a=s.droppable.containers.get(n);if(!a||r!==a.key)return s;const i=new qY(s.droppable.containers);return i.delete(n),{...s,droppable:{...s.droppable,containers:i}}}default:return s}}function dGs(s){let{disabled:t}=s;const{active:n,activatorEvent:r,draggableNodes:a}=k.useContext(JAe),i=nze(r),l=nze(n==null?void 0:n.id);return k.useEffect(()=>{if(!t&&!r&&i&&l!=null){if(!iYe(i)||document.activeElement===i.target)return;const o=a.get(l);if(!o)return;const{activatorNode:c,node:d}=o;if(!c.current&&!d.current)return;requestAnimationFrame(()=>{for(const u of[c.current,d.current]){if(!u)continue;const h=rHs(u);if(h){h.focus();break}}})}},[r,t,a,l,i]),null}function uGs(s,t){let{transform:n,...r}=t;return s!=null&&s.length?s.reduce((a,i)=>i({transform:a,...r}),n):n}function hGs(s){return k.useMemo(()=>({draggable:{...jNe.draggable,...s==null?void 0:s.draggable},droppable:{...jNe.droppable,...s==null?void 0:s.droppable},dragOverlay:{...jNe.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 mGs(s){let{activeNode:t,measure:n,initialRect:r,config:a=!0}=s;const i=k.useRef(!1),{x:l,y:o}=typeof a=="boolean"?{x:a,y:a}:a;W5(()=>{if(!l&&!o||!t){i.current=!1;return}if(i.current||!r)return;const d=t==null?void 0:t.node.current;if(!d||d.isConnected===!1)return;const u=n(d),h=DRt(u,r);if(l||(h.x=0),o||(h.y=0),i.current=!0,Math.abs(h.x)>0||Math.abs(h.y)>0){const m=ORt(d);m&&m.scrollBy({top:h.y,left:h.x})}},[t,l,o,r,n])}const WRt=k.createContext({...bk,scaleX:1,scaleY:1});var vE;(function(s){s[s.Uninitialized=0]="Uninitialized",s[s.Initializing=1]="Initializing",s[s.Initialized=2]="Initialized"})(vE||(vE={}));const eEe=k.memo(function(t){var n,r,a,i;let{id:l,accessibility:o,autoScroll:c=!0,children:d,sensors:u=rGs,collisionDetection:h=xHs,measuring:m,modifiers:p,...g}=t;const x=k.useReducer(cGs,void 0,lGs),[y,v]=x,[_,j]=dHs(),[C,A]=k.useState(vE.Uninitialized),M=C===vE.Initialized,{draggable:{active:I,nodes:P,translate:R},droppable:{containers:O}}=y,B=I!=null?P.get(I):null,U=k.useRef({initial:null,translated:null}),G=k.useMemo(()=>{var An;return I!=null?{id:I,data:(An=B==null?void 0:B.data)!=null?An:aGs,rect:U}:null},[I,B]),H=k.useRef(null),[Y,se]=k.useState(null),[ee,oe]=k.useState(null),me=_X(g,Object.values(g)),Q=Gee("DndDescribedBy",l),te=k.useMemo(()=>O.getEnabled(),[O]),le=hGs(m),{droppableRects:fe,measureDroppableContainers:_e,measuringScheduled:ve}=GHs(te,{dragging:M,dependencies:[R.x,R.y],config:le.droppable}),he=VHs(P,I),Se=k.useMemo(()=>ee?rze(ee):null,[ee]),Te=Fn(),Ie=WHs(he,le.draggable.measure);mGs({activeNode:I!=null?P.get(I):null,config:Te.layoutShiftCompensation,initialRect:Ie,measure:le.draggable.measure});const Ue=cmt(he,le.draggable.measure,Ie),Be=cmt(he?he.parentElement:null),je=k.useRef({activatorEvent:null,active:null,activeNode:he,collisionRect:null,collisions:null,droppableRects:fe,draggableNodes:P,draggingNode:null,draggingNodeRect:null,droppableContainers:O,over:null,scrollableAncestors:[],scrollAdjustedTranslate:null}),Ye=O.getNodeFor((n=je.current.over)==null?void 0:n.id),Ee=nGs({measure:le.dragOverlay.measure}),Re=(r=Ee.nodeRef.current)!=null?r:he,ke=M?(a=Ee.rect)!=null?a:Ue:null,Fe=!!(Ee.nodeRef.current&&Ee.rect),Oe=ZHs(Fe?null:Ue),Ge=HRt(Re?z_(Re):null),yt=XHs(M?Ye??he:null),tt=tGs(yt),ut=uGs(p,{transform:{x:R.x-Oe.x,y:R.y-Oe.y,scaleX:1,scaleY:1},activatorEvent:ee,active:G,activeNodeRect:Ue,containerNodeRect:Be,draggingNodeRect:ke,over:je.current.over,overlayNodeRect:Ee.rect,scrollableAncestors:yt,scrollableAncestorRects:tt,windowRect:Ge}),nt=Se?EB(Se,R):null,et=QHs(yt),at=umt(et),wt=umt(et,[Ue]),rt=EB(ut,at),Ft=ke?bHs(ke,ut):null,Ut=G&&Ft?h({active:G,collisionRect:Ft,droppableRects:fe,droppableContainers:te,pointerCoordinates:nt}):null,Is=RRt(Ut,"id"),[xs,st]=k.useState(null),dt=Fe?ut:EB(ut,wt),jt=yHs(dt,(i=xs==null?void 0:xs.rect)!=null?i:null,Ue),gt=k.useRef(null),rs=k.useCallback((An,js)=>{let{sensor:In,options:un}=js;if(H.current==null)return;const jr=P.get(H.current);if(!jr)return;const Ln=An.nativeEvent,Sr=new In({active:H.current,activeNode:jr,event:Ln,options:un,context:je,onAbort(En){if(!P.get(En))return;const{onDragAbort:xn}=me.current,Ar={id:En};xn==null||xn(Ar),_({type:"onDragAbort",event:Ar})},onPending(En,pr,xn,Ar){if(!P.get(En))return;const{onDragPending:dn}=me.current,Kt={id:En,constraint:pr,initialCoordinates:xn,offset:Ar};dn==null||dn(Kt),_({type:"onDragPending",event:Kt})},onStart(En){const pr=H.current;if(pr==null)return;const xn=P.get(pr);if(!xn)return;const{onDragStart:Ar}=me.current,Zr={activatorEvent:Ln,active:{id:pr,data:xn.data,rect:U}};a1.unstable_batchedUpdates(()=>{Ar==null||Ar(Zr),A(vE.Initializing),v({type:py.DragStart,initialCoordinates:En,active:pr}),_({type:"onDragStart",event:Zr}),se(gt.current),oe(Ln)})},onMove(En){v({type:py.DragMove,coordinates:En})},onEnd:Qn(py.DragEnd),onCancel:Qn(py.DragCancel)});gt.current=Sr;function Qn(En){return async function(){const{active:xn,collisions:Ar,over:Zr,scrollAdjustedTranslate:dn}=je.current;let Kt=null;if(xn&&dn){const{cancelDrop:Er}=me.current;Kt={activatorEvent:Ln,active:xn,collisions:Ar,delta:dn,over:Zr},En===py.DragEnd&&typeof Er=="function"&&await Promise.resolve(Er(Kt))&&(En=py.DragCancel)}H.current=null,a1.unstable_batchedUpdates(()=>{v({type:En}),A(vE.Uninitialized),st(null),se(null),oe(null),gt.current=null;const Er=En===py.DragEnd?"onDragEnd":"onDragCancel";if(Kt){const ti=me.current[Er];ti==null||ti(Kt),_({type:Er,event:Kt})}})}}},[P]),Ns=k.useCallback((An,js)=>(In,un)=>{const jr=In.nativeEvent,Ln=P.get(un);if(H.current!==null||!Ln||jr.dndKit||jr.defaultPrevented)return;const Sr={active:Ln};An(In,js.options,Sr)===!0&&(jr.dndKit={capturedBy:js.sensor},H.current=un,rs(In,js))},[P,rs]),us=HHs(u,Ns);JHs(u),W5(()=>{Ue&&C===vE.Initializing&&A(vE.Initialized)},[Ue,C]),k.useEffect(()=>{const{onDragMove:An}=me.current,{active:js,activatorEvent:In,collisions:un,over:jr}=je.current;if(!js||!In)return;const Ln={active:js,activatorEvent:In,collisions:un,delta:{x:rt.x,y:rt.y},over:jr};a1.unstable_batchedUpdates(()=>{An==null||An(Ln),_({type:"onDragMove",event:Ln})})},[rt.x,rt.y]),k.useEffect(()=>{const{active:An,activatorEvent:js,collisions:In,droppableContainers:un,scrollAdjustedTranslate:jr}=je.current;if(!An||H.current==null||!js||!jr)return;const{onDragOver:Ln}=me.current,Sr=un.get(Is),Qn=Sr&&Sr.rect.current?{id:Sr.id,rect:Sr.rect.current,data:Sr.data,disabled:Sr.disabled}:null,En={active:An,activatorEvent:js,collisions:In,delta:{x:jr.x,y:jr.y},over:Qn};a1.unstable_batchedUpdates(()=>{st(Qn),Ln==null||Ln(En),_({type:"onDragOver",event:En})})},[Is]),W5(()=>{je.current={activatorEvent:ee,active:G,activeNode:he,collisionRect:Ft,collisions:Ut,droppableRects:fe,draggableNodes:P,draggingNode:Re,draggingNodeRect:ke,droppableContainers:O,over:xs,scrollableAncestors:yt,scrollAdjustedTranslate:rt},U.current={initial:ke,translated:Ft}},[G,he,Ut,Ft,P,Re,ke,fe,O,xs,yt,rt]),$Hs({...Te,delta:R,draggingRect:Ft,pointerCoordinates:nt,scrollableAncestors:yt,scrollableAncestorRects:tt});const Bs=k.useMemo(()=>({active:G,activeNode:he,activeNodeRect:Ue,activatorEvent:ee,collisions:Ut,containerNodeRect:Be,dragOverlay:Ee,draggableNodes:P,droppableContainers:O,droppableRects:fe,over:xs,measureDroppableContainers:_e,scrollableAncestors:yt,scrollableAncestorRects:tt,measuringConfiguration:le,measuringScheduled:ve,windowRect:Ge}),[G,he,Ue,ee,Ut,Be,Ee,P,O,fe,xs,_e,yt,tt,le,ve,Ge]),Ts=k.useMemo(()=>({activatorEvent:ee,activators:us,active:G,activeNodeRect:Ue,ariaDescribedById:{draggable:Q},dispatch:v,draggableNodes:P,over:xs,measureDroppableContainers:_e}),[ee,us,G,Ue,v,Q,P,xs,_e]);return zt.createElement(PRt.Provider,{value:j},zt.createElement(JAe.Provider,{value:Ts},zt.createElement(GRt.Provider,{value:Bs},zt.createElement(WRt.Provider,{value:jt},d)),zt.createElement(dGs,{disabled:(o==null?void 0:o.restoreFocus)===!1})),zt.createElement(mHs,{...o,hiddenTextDescribedById:Q}));function Fn(){const An=(Y==null?void 0:Y.autoScrollEnabled)===!1,js=typeof c=="object"?c.enabled===!1:c===!1,In=M&&!An&&!js;return typeof c=="object"?{...c,enabled:In}:{enabled:In}}}),fGs=k.createContext(null),mmt="button",pGs="Draggable";function gGs(s){let{id:t,data:n,disabled:r=!1,attributes:a}=s;const i=Gee(pGs),{activators:l,activatorEvent:o,active:c,activeNodeRect:d,ariaDescribedById:u,draggableNodes:h,over:m}=k.useContext(JAe),{role:p=mmt,roleDescription:g="draggable",tabIndex:x=0}=a??{},y=(c==null?void 0:c.id)===t,v=k.useContext(y?WRt:fGs),[_,j]=v5e(),[C,A]=v5e(),M=eGs(l,t),I=_X(n);W5(()=>(h.set(t,{id:t,key:i,node:_,activatorNode:C,data:I}),()=>{const R=h.get(t);R&&R.key===i&&h.delete(t)}),[h,t]);const P=k.useMemo(()=>({role:p,tabIndex:x,"aria-disabled":r,"aria-pressed":y&&p===mmt?!0:void 0,"aria-roledescription":g,"aria-describedby":u.draggable}),[r,p,x,y,g,u.draggable]);return{active:c,activatorEvent:o,activeNodeRect:d,attributes:P,isDragging:y,listeners:r?void 0:M,node:_,over:m,setNodeRef:j,setActivatorNodeRef:A,transform:v}}function xGs(){return k.useContext(GRt)}const yGs="Droppable",vGs={timeout:25};function bGs(s){let{data:t,disabled:n=!1,id:r,resizeObserverConfig:a}=s;const i=Gee(yGs),{active:l,dispatch:o,over:c,measureDroppableContainers:d}=k.useContext(JAe),u=k.useRef({disabled:n}),h=k.useRef(!1),m=k.useRef(null),p=k.useRef(null),{disabled:g,updateMeasurementsFor:x,timeout:y}={...vGs,...a},v=_X(x??r),_=k.useCallback(()=>{if(!h.current){h.current=!0;return}p.current!=null&&clearTimeout(p.current),p.current=setTimeout(()=>{d(Array.isArray(v.current)?v.current:[v.current]),p.current=null},y)},[y]),j=QAe({callback:_,disabled:g||!l}),C=k.useCallback((P,R)=>{j&&(R&&(j.unobserve(R),h.current=!1),P&&j.observe(P))},[j]),[A,M]=v5e(C),I=_X(t);return k.useEffect(()=>{!j||!A.current||(j.disconnect(),h.current=!1,j.observe(A.current))},[A,j]),k.useEffect(()=>(o({type:py.RegisterDroppable,element:{id:r,key:i,disabled:n,node:A,rect:m,data:I}}),()=>o({type:py.UnregisterDroppable,key:i,id:r})),[r]),k.useEffect(()=>{n!==u.current.disabled&&(o({type:py.SetDroppableDisabled,id:r,key:i,disabled:n}),u.current.disabled=n)},[r,i,n,o]),{active:l,rect:m,isOver:(c==null?void 0:c.id)===r,node:A,over:c,setNodeRef:M}}function tEe(s,t,n){const r=s.slice();return r.splice(n<0?r.length+n:n,0,r.splice(t,1)[0]),r}function _Gs(s,t){return s.reduce((n,r,a)=>{const i=t.get(r);return i&&(n[a]=i),n},Array(s.length))}function Zre(s){return s!==null&&s>=0}function wGs(s,t){if(s===t)return!0;if(s.length!==t.length)return!1;for(let n=0;n{var t;let{rects:n,activeNodeRect:r,activeIndex:a,overIndex:i,index:l}=s;const o=(t=n[a])!=null?t:r;if(!o)return null;const c=NGs(n,l,a);if(l===a){const d=n[i];return d?{x:aa&&l<=i?{x:-o.width-c,y:0,...Xre}:l=i?{x:o.width+c,y:0,...Xre}:{x:0,y:0,...Xre}};function NGs(s,t,n){const r=s[t],a=s[t-1],i=s[t+1];return!r||!a&&!i?0:n{let{rects:t,activeIndex:n,overIndex:r,index:a}=s;const i=tEe(t,r,n),l=t[a],o=i[a];return!o||!l?null:{x:o.left-l.left,y:o.top-l.top,scaleX:o.width/l.width,scaleY:o.height/l.height}},Qre={scaleX:1,scaleY:1},kGs=s=>{var t;let{activeIndex:n,activeNodeRect:r,index:a,rects:i,overIndex:l}=s;const o=(t=i[n])!=null?t:r;if(!o)return null;if(a===n){const d=i[l];return d?{x:0,y:nn&&a<=l?{x:0,y:-o.height-c,...Qre}:a=l?{x:0,y:o.height+c,...Qre}:{x:0,y:0,...Qre}};function SGs(s,t,n){const r=s[t],a=s[t-1],i=s[t+1];return r?nr.map(M=>typeof M=="object"&&"id"in M?M.id:M),[r]),g=l!=null,x=l?p.indexOf(l.id):-1,y=d?p.indexOf(d.id):-1,v=k.useRef(p),_=!wGs(p,v.current),j=y!==-1&&x===-1||_,C=jGs(i);W5(()=>{_&&g&&u(p)},[_,p,g,u]),k.useEffect(()=>{v.current=p},[p]);const A=k.useMemo(()=>({activeIndex:x,containerId:h,disabled:C,disableTransforms:j,items:p,overIndex:y,useDragOverlay:m,sortedRects:_Gs(p,c),strategy:a}),[x,h,C.draggable,C.droppable,j,p,y,c,m,a]);return zt.createElement(YRt.Provider,{value:A},t)}const CGs=s=>{let{id:t,items:n,activeIndex:r,overIndex:a}=s;return tEe(n,r,a).indexOf(t)},AGs=s=>{let{containerId:t,isSorting:n,wasDragging:r,index:a,items:i,newIndex:l,previousItems:o,previousContainerId:c,transition:d}=s;return!d||!r||o!==i&&a===l?!1:n?!0:l!==a&&t===c},EGs={duration:200,easing:"ease"},ZRt="transform",TGs=PM.Transition.toString({property:ZRt,duration:0,easing:"linear"}),MGs={roleDescription:"sortable"};function PGs(s){let{disabled:t,index:n,node:r,rect:a}=s;const[i,l]=k.useState(null),o=k.useRef(n);return W5(()=>{if(!t&&n!==o.current&&r.current){const c=a.current;if(c){const d=lV(r.current,{ignoreTransform:!0}),u={x:c.left-d.left,y:c.top-d.top,scaleX:c.width/d.width,scaleY:c.height/d.height};(u.x||u.y)&&l(u)}}n!==o.current&&(o.current=n)},[t,n,r,a]),k.useEffect(()=>{i&&l(null)},[i]),i}function nEe(s){let{animateLayoutChanges:t=AGs,attributes:n,disabled:r,data:a,getNewIndex:i=CGs,id:l,strategy:o,resizeObserverConfig:c,transition:d=EGs}=s;const{items:u,containerId:h,activeIndex:m,disabled:p,disableTransforms:g,sortedRects:x,overIndex:y,useDragOverlay:v,strategy:_}=k.useContext(YRt),j=IGs(r,p),C=u.indexOf(l),A=k.useMemo(()=>({sortable:{containerId:h,index:C,items:u},...a}),[h,a,C,u]),M=k.useMemo(()=>u.slice(u.indexOf(l)),[u,l]),{rect:I,node:P,isOver:R,setNodeRef:O}=bGs({id:l,data:A,disabled:j.droppable,resizeObserverConfig:{updateMeasurementsFor:M,...c}}),{active:B,activatorEvent:U,activeNodeRect:G,attributes:H,setNodeRef:Y,listeners:se,isDragging:ee,over:oe,setActivatorNodeRef:me,transform:Q}=gGs({id:l,data:A,attributes:{...MGs,...n},disabled:j.draggable}),te=eHs(O,Y),le=!!B,fe=le&&!g&&Zre(m)&&Zre(y),_e=!v&&ee,ve=_e&&fe?Q:null,Se=fe?ve??(o??_)({rects:x,activeNodeRect:G,activeIndex:m,overIndex:y,index:C}):null,Te=Zre(m)&&Zre(y)?i({id:l,items:u,activeIndex:m,overIndex:y}):C,Ie=B==null?void 0:B.id,Ue=k.useRef({activeId:Ie,items:u,newIndex:Te,containerId:h}),Be=u!==Ue.current.items,je=t({active:B,containerId:h,isDragging:ee,isSorting:le,id:l,index:C,items:u,newIndex:Ue.current.newIndex,previousItems:Ue.current.items,previousContainerId:Ue.current.containerId,transition:d,wasDragging:Ue.current.activeId!=null}),Ye=PGs({disabled:!je,index:C,node:P,rect:I});return k.useEffect(()=>{le&&Ue.current.newIndex!==Te&&(Ue.current.newIndex=Te),h!==Ue.current.containerId&&(Ue.current.containerId=h),u!==Ue.current.items&&(Ue.current.items=u)},[le,Te,h,u]),k.useEffect(()=>{if(Ie===Ue.current.activeId)return;if(Ie!=null&&Ue.current.activeId==null){Ue.current.activeId=Ie;return}const Re=setTimeout(()=>{Ue.current.activeId=Ie},50);return()=>clearTimeout(Re)},[Ie]),{active:B,activeIndex:m,attributes:H,data:A,rect:I,index:C,newIndex:Te,items:u,isOver:R,isSorting:le,isDragging:ee,listeners:se,node:P,overIndex:y,over:oe,setNodeRef:te,setActivatorNodeRef:me,setDroppableNodeRef:O,setDraggableNodeRef:Y,transform:Ye??Se,transition:Ee()};function Ee(){if(Ye||Be&&Ue.current.newIndex===C)return TGs;if(!(_e&&!iYe(U)||!d)&&(le||je))return PM.Transition.toString({...d,property:ZRt})}}function IGs(s,t){var n,r;return typeof s=="boolean"?{draggable:s,droppable:!1}:{draggable:(n=s==null?void 0:s.draggable)!=null?n:t.draggable,droppable:(r=s==null?void 0:s.droppable)!=null?r:t.droppable}}function w5e(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 LGs=[su.Down,su.Right,su.Up,su.Left],XRt=(s,t)=>{let{context:{active:n,collisionRect:r,droppableRects:a,droppableContainers:i,over:l,scrollableAncestors:o}}=t;if(LGs.includes(s.code)){if(s.preventDefault(),!n||!r)return;const c=[];i.getEnabled().forEach(h=>{if(!h||h!=null&&h.disabled)return;const m=a.get(h.id);if(m)switch(s.code){case su.Down:r.topm.top&&c.push(h);break;case su.Left:r.left>m.left&&c.push(h);break;case su.Right:r.left1&&(u=d[1].id),u!=null){const h=i.get(n.id),m=i.get(u),p=m?a.get(m.id):null,g=m==null?void 0:m.node.current;if(g&&p&&h&&m){const y=ZAe(g).some((M,I)=>o[I]!==M),v=QRt(h,m),_=RGs(h,m),j=y||!v?{x:0,y:0}:{x:_?r.width-p.width:0,y:_?r.height-p.height:0},C={x:p.left,y:p.top};return j.x&&j.y?C:wX(C,j)}}}};function QRt(s,t){return!w5e(s)||!w5e(t)?!1:s.data.current.sortable.containerId===t.data.current.sortable.containerId}function RGs(s,t){return!w5e(s)||!w5e(t)||!QRt(s,t)?!1:s.data.current.sortable.indext(s),children:e.jsx(ui,{className:"h-3.5 w-3.5"})}),e.jsx($,{variant:"destructive",size:"icon",className:"h-7 w-7",onClick:()=>n(s),children:e.jsx(Un,{className:"h-3.5 w-3.5"})})]}),s.post_date&&e.jsx("div",{className:"absolute bottom-2 left-2",children:e.jsxs(qe,{className:"bg-primary/90 text-primary-foreground text-[10px] gap-1 backdrop-blur-sm px-1.5 py-0.5",children:[e.jsx(ha,{className:"h-2.5 w-2.5"}),Ys(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(Xc,{children:[e.jsx(Qc,{asChild:!0,children:e.jsxs($,{variant:"outline",size:"sm",className:Ot("w-full h-7 text-[11px] gap-1 justify-start font-normal",!s.post_date&&"text-muted-foreground"),children:[e.jsx(ha,{className:"h-3 w-3"}),s.post_date?Ys(new Date(s.post_date+"T00:00:00"),"MMM d, yyyy"):"Set post date"]})}),e.jsxs(Bc,{className:"w-auto p-0",align:"start",children:[e.jsx(vb,{mode:"single",selected:s.post_date?new Date(s.post_date+"T00:00:00"):void 0,onSelect:h=>r(s.id,h?Ys(h,"yyyy-MM-dd"):null),className:"p-3 pointer-events-auto"}),s.post_date&&e.jsx("div",{className:"p-2 border-t",children:e.jsx($,{variant:"ghost",size:"sm",className:"w-full text-xs text-muted-foreground",onClick:()=>r(s.id,null),children:"Clear date"})})]})]})]})]})})}const OGs=()=>{const s=ls(),[t,n]=k.useState("all"),[r,a]=k.useState(!1),[i,l]=k.useState(Ys(new Date,"yyyy-MM")),[o,c]=k.useState([]),[d,u]=k.useState(!1),[h,m]=k.useState(null),[p,g]=k.useState(null),[x,y]=k.useState(""),[v,_]=k.useState(null),[j,C]=k.useState(!1),[A,M]=k.useState(!1),[I,P]=k.useState(Ys(new Date,"yyyy-MM")),[R,O]=k.useState(null),[B,U]=k.useState(""),[G,H]=k.useState(""),[Y,se]=k.useState(""),[ee,oe]=k.useState(!1),me=KAe(LU(cV,{activationConstraint:{distance:5}}),LU(XAe,{coordinateGetter:XRt})),{data:Q=[],isLoading:te}=pt({queryKey:["admin-social-swag-2"],queryFn:async()=>{const{data:nt,error:et}=await V.from("social_swag_2").select("*").order("month",{ascending:!1}).order("sort_order");if(et)throw et;return nt}}),{data:le=[]}=pt({queryKey:["admin-social-swag-2-months"],queryFn:async()=>{const{data:nt,error:et}=await V.from("social_swag_2_months").select("*").order("month",{ascending:!1});if(et)throw et;return nt}}),{data:fe=[]}=pt({queryKey:["admin-social-swag-2-reels"],queryFn:async()=>{const{data:nt,error:et}=await V.from("social_swag_2_reels").select("*").order("month",{ascending:!1});if(et)throw et;return nt}}),_e=[...new Set(Q.map(nt=>nt.month))].sort((nt,et)=>et.localeCompare(nt)),ve=t==="all"?Q:Q.filter(nt=>nt.month===t),he=nt=>{const et=cGe(nt,"yyyy-MM",new Date);return Ys(et,"MMMM yyyy")},Se=nt=>{g(nt),y(nt.caption),_(nt.post_date)},Te=async()=>{if(p){C(!0);try{const{error:nt}=await V.from("social_swag_2").update({caption:x,post_date:v}).eq("id",p.id);if(nt)throw nt;ae.success("Image updated"),g(null),s.invalidateQueries({queryKey:["admin-social-swag-2"]}),s.invalidateQueries({queryKey:["social-swag-2"]})}catch{ae.error("Failed to update image")}finally{C(!1)}}},Ie=async nt=>{const{active:et,over:at}=nt;if(!at||et.id===at.id)return;const wt=ve,rt=wt.findIndex(Is=>Is.id===et.id),Ft=wt.findIndex(Is=>Is.id===at.id);if(rt===-1||Ft===-1)return;const Ut=tEe(wt,rt,Ft);s.setQueryData(["admin-social-swag-2"],Is=>{if(!Is)return Is;const xs={};return Ut.forEach((st,dt)=>{xs[st.id]=dt}),Is.map(st=>xs[st.id]!==void 0?{...st,sort_order:xs[st.id]}:st).sort((st,dt)=>st.month!==dt.month?dt.month.localeCompare(st.month):st.sort_order-dt.sort_order)});try{await Promise.all(Ut.map((Is,xs)=>V.from("social_swag_2").update({sort_order:xs}).eq("id",Is.id)))}catch{ae.error("Failed to save order"),s.invalidateQueries({queryKey:["admin-social-swag-2"]})}},Ue=nt=>{const at=Array.from(nt.target.files||[]).sort((wt,rt)=>wt.name.localeCompare(rt.name,void 0,{numeric:!0,sensitivity:"base"})).slice(0,16-o.length).map(wt=>({file:wt,preview:URL.createObjectURL(wt),caption:""}));c(wt=>[...wt,...at].slice(0,16))},Be=nt=>{c(et=>{const at=[...et];return URL.revokeObjectURL(at[nt].preview),at.splice(nt,1),at})},je=(nt,et)=>{c(at=>{const wt=[...at];return wt[nt]={...wt[nt],caption:et},wt})},Ye=async()=>{var et;if(o.length===0){ae.error("Please add at least one image");return}if(o.filter(at=>!at.caption.trim()).length>0){ae.error("Please add captions to all images");return}u(!0);try{const{data:at}=await V.from("social_swag_2").select("sort_order").eq("month",i).order("sort_order",{ascending:!1}).limit(1),wt=(((et=at==null?void 0:at[0])==null?void 0:et.sort_order)??-1)+1;for(let rt=0;rt{const et=nt.image_url.split("/social-swag-2/");et[1]&&await V.storage.from("social-swag-2").remove([et[1]]);const{error:at}=await V.from("social_swag_2").delete().eq("id",nt.id);if(at)throw at},onSuccess:()=>{ae.success("Image deleted"),s.invalidateQueries({queryKey:["admin-social-swag-2"]})},onError:()=>ae.error("Failed to delete image")}),Re=Nt({mutationFn:async({id:nt,postDate:et})=>{const{error:at}=await V.from("social_swag_2").update({post_date:et}).eq("id",nt);if(at)throw at},onSuccess:()=>{ae.success("Post date updated"),s.invalidateQueries({queryKey:["admin-social-swag-2"]}),s.invalidateQueries({queryKey:["social-swag-2"]})},onError:()=>ae.error("Failed to update post date")}),ke=Nt({mutationFn:async({month:nt,link:et})=>{const{error:at}=await V.from("social_swag_2_months").upsert({month:nt,canva_link:et||null},{onConflict:"month"});if(at)throw at},onSuccess:()=>{ae.success("Canva link updated"),m(null),s.invalidateQueries({queryKey:["admin-social-swag-2-months"]})},onError:()=>ae.error("Failed to update Canva link")}),Fe=nt=>{var et;return((et=le.find(at=>at.month===nt))==null?void 0:et.canva_link)||""},Oe=nt=>fe.find(et=>et.month===nt)||null,Ge=nt=>{var at;const et=(at=nt.target.files)==null?void 0:at[0];et&&(O(et),U(URL.createObjectURL(et)))},yt=()=>{B&&URL.revokeObjectURL(B),O(null),U(""),H(""),se("")},tt=async()=>{if(!R){ae.error("Please select an image");return}oe(!0);try{const nt=R.name.split(".").pop(),et=`reels/${I}-${Date.now()}.${nt}`,{error:at}=await V.storage.from("social-swag-2").upload(et,R);if(at)throw at;const{data:{publicUrl:wt}}=V.storage.from("social-swag-2").getPublicUrl(et),{error:rt}=await V.from("social_swag_2_reels").upsert({month:I,image_url:wt,canva_link:Y||null,caption:G||null},{onConflict:"month"});if(rt)throw rt;ae.success("Reel uploaded successfully!"),sze(`${he(I)} Reel`,"social-swag-2"),yt(),M(!1),s.invalidateQueries({queryKey:["admin-social-swag-2-reels"]})}catch(nt){console.error("Reel upload error:",nt),ae.error("Failed to upload reel")}finally{oe(!1)}},ut=Nt({mutationFn:async nt=>{const et=nt.image_url.split("/social-swag-2/");et[1]&&await V.storage.from("social-swag-2").remove([et[1]]);const{error:at}=await V.from("social_swag_2_reels").delete().eq("id",nt.id);if(at)throw at},onSuccess:()=>{ae.success("Reel deleted"),s.invalidateQueries({queryKey:["admin-social-swag-2-reels"]})},onError:()=>ae.error("Failed to delete reel")});return e.jsxs(Xs,{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(zs,{open:r,onOpenChange:a,children:[e.jsx(yl,{asChild:!0,children:e.jsxs($,{className:"gap-2",children:[e.jsx(nn,{className:"h-4 w-4"}),"Upload Images"]})}),e.jsxs(Rs,{className:"max-w-4xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Vs,{children:e.jsx($s,{children:"Upload Social Swag Images"})}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Month"}),e.jsx(be,{type:"month",value:i,onChange:nt=>l(nt.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(re,{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:Ue,className:"hidden",id:"swag-upload",disabled:o.length>=16}),e.jsxs("label",{htmlFor:"swag-upload",className:"cursor-pointer",children:[e.jsx(gi,{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((nt,et)=>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:nt.preview,alt:`Upload ${et+1}`,className:"w-full h-full object-cover"}),e.jsx($,{variant:"destructive",size:"icon",className:"absolute top-1 right-1 h-6 w-6",onClick:()=>Be(et),children:e.jsx(mr,{className:"h-3 w-3"})})]}),e.jsx(Ls,{placeholder:"Caption...",value:nt.caption,onChange:at=>je(et,at.target.value),className:"text-xs h-20"})]},et))}),e.jsx($,{onClick:Ye,disabled:d||o.length===0,className:"w-full gap-2",children:d?e.jsxs(e.Fragment,{children:[e.jsx(Jt,{className:"h-4 w-4 animate-spin"}),"Uploading..."]}):e.jsxs(e.Fragment,{children:[e.jsx(gi,{className:"h-4 w-4"}),"Upload ",o.length," Images"]})})]})]})]}),e.jsxs(zs,{open:A,onOpenChange:nt=>{M(nt),nt||yt()},children:[e.jsx(yl,{asChild:!0,children:e.jsxs($,{variant:"outline",className:"gap-2",children:[e.jsx(em,{className:"h-4 w-4"}),"Upload Reel"]})}),e.jsxs(Rs,{className:"max-w-lg max-h-[85vh] overflow-y-auto",children:[e.jsx(Vs,{children:e.jsx($s,{children:"Upload Monthly Reel"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Month"}),e.jsx(be,{type:"month",value:I,onChange:nt=>P(nt.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Reel Preview Image"}),B?e.jsxs("div",{className:"relative aspect-[9/16] max-w-[120px] mx-auto rounded-lg overflow-hidden bg-muted",children:[e.jsx("img",{src:B,alt:"Reel preview",className:"w-full h-full object-cover"}),e.jsx($,{variant:"destructive",size:"icon",className:"absolute top-2 right-2 h-6 w-6",onClick:()=>{URL.revokeObjectURL(B),O(null),U("")},children:e.jsx(mr,{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:Ge,className:"hidden",id:"reel-upload"}),e.jsxs("label",{htmlFor:"reel-upload",className:"cursor-pointer",children:[e.jsx(em,{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(re,{children:"Canva Download Link"}),e.jsx(be,{value:Y,onChange:nt=>se(nt.target.value),placeholder:"https://www.canva.com/..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Caption"}),e.jsx(Ls,{value:G,onChange:nt=>H(nt.target.value),placeholder:"Enter caption for this reel...",className:"h-24"})]}),e.jsx($,{onClick:tt,disabled:ee||!R,className:"w-full gap-2",children:ee?e.jsxs(e.Fragment,{children:[e.jsx(Jt,{className:"h-4 w-4 animate-spin"}),"Uploading..."]}):e.jsxs(e.Fragment,{children:[e.jsx(gi,{className:"h-4 w-4"}),"Upload Reel"]})})]})]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsx(we,{children:e.jsxs(De,{className:"p-4",children:[e.jsx("div",{className:"text-2xl font-bold",children:Q.length}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Total Images"})]})}),e.jsx(we,{children:e.jsxs(De,{className:"p-4",children:[e.jsx("div",{className:"text-2xl font-bold",children:_e.length}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Months"})]})})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx(ya,{value:t,onValueChange:n,children:e.jsxs(va,{children:[e.jsx(is,{value:"all",children:"All"}),_e.map(nt=>e.jsx(is,{value:nt,children:he(nt)},nt))]})}),t!=="all"&&e.jsx(we,{children:e.jsx(De,{className:"p-4",children:e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(od,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("div",{className:"flex-1",children:[e.jsxs(re,{className:"text-sm text-muted-foreground",children:["Canva Edit Link for ",he(t)]}),(h==null?void 0:h.month)===t?e.jsxs("div",{className:"flex gap-2 mt-1",children:[e.jsx(be,{value:h.link,onChange:nt=>m({...h,link:nt.target.value}),placeholder:"https://www.canva.com/..."}),e.jsx($,{size:"sm",onClick:()=>ke.mutate(h),children:"Save"}),e.jsx($,{size:"sm",variant:"outline",onClick:()=>m(null),children:"Cancel"})]}):e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx("span",{className:"text-sm",children:Fe(t)||"No link set"}),e.jsx($,{size:"sm",variant:"outline",onClick:()=>m({month:t,link:Fe(t)}),children:"Edit"})]})]})]})})}),t!=="all"&&e.jsx(we,{children:e.jsx(De,{className:"p-4",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx(em,{className:"h-4 w-4 text-muted-foreground mt-1"}),e.jsxs("div",{className:"flex-1",children:[e.jsxs(re,{className:"text-sm text-muted-foreground",children:["Reel for ",he(t)]}),(()=>{const nt=Oe(t);return nt?e.jsxs("div",{className:"flex items-center gap-4 mt-2",children:[e.jsx("img",{src:nt.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:nt.caption||"No caption"}),nt.canva_link&&e.jsx("a",{href:nt.canva_link,target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline text-xs",children:"View Canva Link"})]}),e.jsx($,{variant:"destructive",size:"sm",onClick:()=>ut.mutate(nt),children:e.jsx(Un,{className:"h-4 w-4"})})]}):e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"No reel uploaded for this month"})})()]})]})})})]}),te?e.jsx("div",{className:"text-center py-12 text-muted-foreground",children:"Loading..."}):ve.length===0?e.jsxs("div",{className:"text-center py-12",children:[e.jsx(zc,{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(eEe,{sensors:me,collisionDetection:YAe,onDragEnd:Ie,children:e.jsx(sEe,{items:ve.map(nt=>nt.id),strategy:Wee,children:e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-4",children:ve.map(nt=>e.jsx(DGs,{item:nt,onEdit:Se,onDelete:et=>Ee.mutate(et),onDateChange:(et,at)=>Re.mutate({id:et,postDate:at})},nt.id))})})})]}),e.jsx(zs,{open:!!p,onOpenChange:nt=>{nt||g(null)},children:e.jsxs(Rs,{className:"max-w-md",children:[e.jsx(Vs,{children:e.jsx($s,{children:"Edit Image"})}),p&&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:p.image_url,alt:"Preview",className:"w-full h-full object-cover"})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Caption"}),e.jsx(Ls,{value:x,onChange:nt=>y(nt.target.value),placeholder:"Enter caption...",className:"h-28"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Post Date"}),e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsxs(Xc,{children:[e.jsx(Qc,{asChild:!0,children:e.jsxs($,{variant:"outline",className:Ot("flex-1 justify-start gap-2 font-normal",!v&&"text-muted-foreground"),children:[e.jsx(ha,{className:"h-4 w-4"}),v?Ys(new Date(v+"T00:00:00"),"MMM d, yyyy"):"Pick a date"]})}),e.jsx(Bc,{className:"w-auto p-0",align:"start",children:e.jsx(vb,{mode:"single",selected:v?new Date(v+"T00:00:00"):void 0,onSelect:nt=>_(nt?Ys(nt,"yyyy-MM-dd"):null),className:"p-3 pointer-events-auto"})})]}),v&&e.jsx($,{variant:"ghost",size:"icon",onClick:()=>_(null),children:e.jsx(mr,{className:"h-4 w-4"})})]})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>g(null),children:"Cancel"}),e.jsx($,{onClick:Te,disabled:j,className:"gap-2",children:j?e.jsxs(e.Fragment,{children:[e.jsx(Jt,{className:"h-4 w-4 animate-spin"}),"Saving..."]}):"Save Changes"})]})]})})]})},FGs=()=>{const{toast:s}=Fi(),t=ls(),[n,r]=k.useState("categories"),[a,i]=k.useState(!1),[l,o]=k.useState(null),[c,d]=k.useState({name:"",description:"",icon:""}),[u,h]=k.useState(!1),[m,p]=k.useState(null),[g,x]=k.useState({name:"",description:"",icon:""}),[y,v]=k.useState(!1),[_,j]=k.useState(null),[C,A]=k.useState(""),{data:M=[],isLoading:I}=pt({queryKey:["admin-community-categories"],queryFn:async()=>{const{data:Ie,error:Ue}=await V.from("community_categories").select("*").order("sort_order");if(Ue)throw Ue;return Ie}}),{data:P=[],isLoading:R}=pt({queryKey:["admin-private-groups"],queryFn:async()=>{const{data:Ie,error:Ue}=await V.from("community_private_groups").select("*").order("sort_order");if(Ue)throw Ue;return Ie}}),{data:O=[]}=pt({queryKey:["admin-group-members",_==null?void 0:_.id],queryFn:async()=>{if(!_)return[];const{data:Ie,error:Ue}=await V.from("community_private_group_members").select("*").eq("group_id",_.id);if(Ue)throw Ue;return Ie},enabled:!!_}),{data:B=[]}=pt({queryKey:["admin-all-profiles"],queryFn:async()=>{let Ue=[],Be=0,je=!0;for(;je;){const{data:Ye,error:Ee}=await V.from("profiles").select("id, name, email, brokerage_id").order("name").range(Be,Be+1e3-1);if(Ee)throw Ee;Ye&&Ye.length>0?(Ue=[...Ue,...Ye],Be+=1e3,je=Ye.length===1e3):je=!1}return Ue}}),{data:U=[]}=pt({queryKey:["admin-all-brokerages"],queryFn:async()=>{const{data:Ie,error:Ue}=await V.from("brokerages").select("*").order("name");if(Ue)throw Ue;return Ie}}),G=Nt({mutationFn:async Ie=>{if(Ie.id){const{error:Ue}=await V.from("community_categories").update({name:Ie.name,description:Ie.description||null,icon:Ie.icon||null}).eq("id",Ie.id);if(Ue)throw Ue}else{const Ue=Math.max(...M.map(je=>je.sort_order),0),{error:Be}=await V.from("community_categories").insert({name:Ie.name,description:Ie.description||null,icon:Ie.icon||null,sort_order:Ue+1});if(Be)throw Be}},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-community-categories"]}),i(!1),o(null),d({name:"",description:"",icon:""}),s({title:l?"Category updated!":"Category created!"})},onError:Ie=>{s({title:"Error",description:Ie.message,variant:"destructive"})}}),H=Nt({mutationFn:async Ie=>{const{error:Ue}=await V.from("community_categories").delete().eq("id",Ie);if(Ue)throw Ue},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-community-categories"]}),s({title:"Category deleted"})}}),Y=Nt({mutationFn:async({id:Ie,direction:Ue})=>{const Be=M.findIndex(je=>je.id===Ie);if(Ue==="up"&&Be>0){const je=M[Be-1],Ye=M[Be];await V.from("community_categories").update({sort_order:Ye.sort_order}).eq("id",je.id),await V.from("community_categories").update({sort_order:je.sort_order}).eq("id",Ye.id)}else if(Ue==="down"&&Bet.invalidateQueries({queryKey:["admin-community-categories"]})}),se=Nt({mutationFn:async Ie=>{if(Ie.id){const{error:Ue}=await V.from("community_private_groups").update({name:Ie.name,description:Ie.description||null,icon:Ie.icon||null}).eq("id",Ie.id);if(Ue)throw Ue}else{const Ue=Math.max(...P.map(je=>je.sort_order),0),{error:Be}=await V.from("community_private_groups").insert({name:Ie.name,description:Ie.description||null,icon:Ie.icon||null,sort_order:Ue+1});if(Be)throw Be}},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-private-groups"]}),h(!1),p(null),x({name:"",description:"",icon:""}),s({title:m?"Private group updated!":"Private group created!"})},onError:Ie=>{s({title:"Error",description:Ie.message,variant:"destructive"})}}),ee=Nt({mutationFn:async Ie=>{const{error:Ue}=await V.from("community_private_groups").delete().eq("id",Ie);if(Ue)throw Ue},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-private-groups"]}),s({title:"Private group deleted"})}}),oe=Nt({mutationFn:async({id:Ie,direction:Ue})=>{const Be=P.findIndex(je=>je.id===Ie);if(Ue==="up"&&Be>0){const je=P[Be-1],Ye=P[Be];await V.from("community_private_groups").update({sort_order:Ye.sort_order}).eq("id",je.id),await V.from("community_private_groups").update({sort_order:je.sort_order}).eq("id",Ye.id)}else if(Ue==="down"&&Bet.invalidateQueries({queryKey:["admin-private-groups"]})}),me=Nt({mutationFn:async({groupId:Ie,userId:Ue,isMember:Be})=>{if(Be){const{error:je}=await V.from("community_private_group_members").delete().eq("group_id",Ie).eq("user_id",Ue);if(je)throw je}else{const{error:je}=await V.from("community_private_group_members").insert({group_id:Ie,user_id:Ue});if(je)throw je}},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-group-members",_==null?void 0:_.id]})}}),Q=Nt({mutationFn:async({groupId:Ie,brokerageId:Ue,isMember:Be})=>{if(Be){const{error:je}=await V.from("community_private_group_members").delete().eq("group_id",Ie).eq("brokerage_id",Ue);if(je)throw je}else{const{error:je}=await V.from("community_private_group_members").insert({group_id:Ie,brokerage_id:Ue});if(je)throw je}},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-group-members",_==null?void 0:_.id]})}}),te=Ie=>{o(Ie),d({name:Ie.name,description:Ie.description||"",icon:Ie.icon||""}),i(!0)},le=()=>{o(null),d({name:"",description:"",icon:""}),i(!0)},fe=Ie=>{p(Ie),x({name:Ie.name,description:Ie.description||"",icon:Ie.icon||""}),h(!0)},_e=()=>{p(null),x({name:"",description:"",icon:""}),h(!0)},ve=Ie=>{j(Ie),A(""),v(!0)},he=Ie=>O.some(Ue=>Ue.user_id===Ie),Se=Ie=>O.some(Ue=>Ue.brokerage_id===Ie),Te=B.filter(Ie=>Ie.name.toLowerCase().includes(C.toLowerCase())||Ie.email.toLowerCase().includes(C.toLowerCase()));return e.jsx(Xs,{title:"Community Management",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(nm,{title:"Community Management",description:"Manage categories and private groups for community discussions"}),e.jsxs(ya,{value:n,onValueChange:r,children:[e.jsxs(va,{children:[e.jsx(is,{value:"categories",children:"Public Categories"}),e.jsxs(is,{value:"private-groups",children:[e.jsx(fu,{className:"h-4 w-4 mr-1"}),"Private Groups"]})]}),e.jsxs(cs,{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($,{onClick:le,children:[e.jsx(nn,{className:"h-4 w-4 mr-2"}),"Add Category"]})]}),e.jsx(we,{children:e.jsx(De,{className:"pt-6",children:e.jsxs(Qa,{children:[e.jsx(Ja,{children:e.jsxs(vn,{children:[e.jsx(Dt,{className:"w-[50px]",children:"Order"}),e.jsx(Dt,{className:"w-[80px]",children:"Icon"}),e.jsx(Dt,{children:"Name"}),e.jsx(Dt,{children:"Description"}),e.jsx(Dt,{className:"w-[100px]",children:"Actions"})]})}),e.jsx(ei,{children:I?e.jsx(vn,{children:e.jsx(_t,{colSpan:5,className:"text-center py-8",children:"Loading..."})}):M.length===0?e.jsx(vn,{children:e.jsx(_t,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No categories yet. Create your first one!"})}):M.map((Ie,Ue)=>e.jsxs(vn,{children:[e.jsx(_t,{children:e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx($,{variant:"ghost",size:"icon",className:"h-6 w-6",disabled:Ue===0,onClick:()=>Y.mutate({id:Ie.id,direction:"up"}),children:"↑"}),e.jsx($,{variant:"ghost",size:"icon",className:"h-6 w-6",disabled:Ue===M.length-1,onClick:()=>Y.mutate({id:Ie.id,direction:"down"}),children:"↓"})]})}),e.jsx(_t,{className:"text-2xl",children:Ie.icon||"📁"}),e.jsx(_t,{className:"font-medium",children:Ie.name}),e.jsx(_t,{className:"text-muted-foreground",children:Ie.description||"—"}),e.jsx(_t,{children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx($,{variant:"ghost",size:"icon",onClick:()=>te(Ie),children:e.jsx(ui,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",className:"text-destructive",onClick:async()=>{await io("Delete this category? Posts will be uncategorized.")&&H.mutate(Ie.id)},children:e.jsx(Un,{className:"h-4 w-4"})})]})})]},Ie.id))})]})})})]}),e.jsxs(cs,{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(Gi,{className:"h-3 w-3"}),"Brokerage groups are created automatically and sync with brokerage names"]})]}),e.jsxs($,{onClick:_e,children:[e.jsx(nn,{className:"h-4 w-4 mr-2"}),"Add Private Group"]})]}),e.jsx(we,{children:e.jsx(De,{className:"pt-6",children:e.jsxs(Qa,{children:[e.jsx(Ja,{children:e.jsxs(vn,{children:[e.jsx(Dt,{className:"w-[50px]",children:"Order"}),e.jsx(Dt,{className:"w-[80px]",children:"Icon"}),e.jsx(Dt,{children:"Name"}),e.jsx(Dt,{children:"Description"}),e.jsx(Dt,{className:"w-[120px]",children:"Members"}),e.jsx(Dt,{className:"w-[140px]",children:"Actions"})]})}),e.jsx(ei,{children:R?e.jsx(vn,{children:e.jsx(_t,{colSpan:6,className:"text-center py-8",children:"Loading..."})}):P.length===0?e.jsx(vn,{children:e.jsx(_t,{colSpan:6,className:"text-center py-8 text-muted-foreground",children:"No private groups yet. Create your first one!"})}):P.map((Ie,Ue)=>e.jsxs(vn,{children:[e.jsx(_t,{children:e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx($,{variant:"ghost",size:"icon",className:"h-6 w-6",disabled:Ue===0,onClick:()=>oe.mutate({id:Ie.id,direction:"up"}),children:"↑"}),e.jsx($,{variant:"ghost",size:"icon",className:"h-6 w-6",disabled:Ue===P.length-1,onClick:()=>oe.mutate({id:Ie.id,direction:"down"}),children:"↓"})]})}),e.jsx(_t,{className:"text-2xl",children:Ie.icon||"🔒"}),e.jsx(_t,{className:"font-medium",children:e.jsxs("div",{className:"flex items-center gap-2",children:[Ie.name,Ie.brokerage_id?e.jsxs(qe,{variant:"outline",className:"text-xs bg-blue-50 text-blue-700 border-blue-200",children:[e.jsx(Gi,{className:"h-3 w-3 mr-1"}),"Auto-managed"]}):e.jsxs(qe,{variant:"secondary",className:"text-xs",children:[e.jsx(fu,{className:"h-3 w-3 mr-1"}),"Private"]})]})}),e.jsx(_t,{className:"text-muted-foreground",children:Ie.description||"—"}),e.jsx(_t,{children:e.jsxs($,{variant:"outline",size:"sm",onClick:()=>ve(Ie),children:[e.jsx(Xn,{className:"h-4 w-4 mr-1"}),"Manage"]})}),e.jsx(_t,{children:e.jsxs("div",{className:"flex gap-1",children:[!Ie.brokerage_id&&e.jsx($,{variant:"ghost",size:"icon",onClick:()=>fe(Ie),children:e.jsx(ui,{className:"h-4 w-4"})}),!Ie.brokerage_id&&e.jsx($,{variant:"ghost",size:"icon",className:"text-destructive",onClick:async()=>{await io("Delete this private group? All posts in this group will be deleted.")&&ee.mutate(Ie.id)},children:e.jsx(Un,{className:"h-4 w-4"})}),Ie.brokerage_id&&e.jsx("span",{className:"text-xs text-muted-foreground italic",children:"Managed via brokerage"})]})})]},Ie.id))})]})})})]})]}),e.jsx(zs,{open:a,onOpenChange:i,children:e.jsxs(Rs,{children:[e.jsx(Vs,{children:e.jsx($s,{children:l?"Edit Category":"Create Category"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Icon (emoji)"}),e.jsx(be,{value:c.icon,onChange:Ie=>d(Ue=>({...Ue,icon:Ie.target.value})),placeholder:"💬",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Name *"}),e.jsx(be,{value:c.name,onChange:Ie=>d(Ue=>({...Ue,name:Ie.target.value})),placeholder:"Category name",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Description"}),e.jsx(Ls,{value:c.description,onChange:Ie=>d(Ue=>({...Ue,description:Ie.target.value})),placeholder:"Brief description of this category",className:"mt-1"})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx($,{variant:"outline",onClick:()=>i(!1),children:"Cancel"}),e.jsx($,{onClick:()=>G.mutate({...c,id:l==null?void 0:l.id}),disabled:!c.name.trim(),children:l?"Save Changes":"Create Category"})]})]})]})}),e.jsx(zs,{open:u,onOpenChange:h,children:e.jsxs(Rs,{children:[e.jsx(Vs,{children:e.jsx($s,{children:m?"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(be,{value:g.icon,onChange:Ie=>x(Ue=>({...Ue,icon:Ie.target.value})),placeholder:"🔒",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Name *"}),e.jsx(be,{value:g.name,onChange:Ie=>x(Ue=>({...Ue,name:Ie.target.value})),placeholder:"e.g., Pioneers",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Description"}),e.jsx(Ls,{value:g.description,onChange:Ie=>x(Ue=>({...Ue,description:Ie.target.value})),placeholder:"Brief description of this private group",className:"mt-1"})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx($,{variant:"outline",onClick:()=>h(!1),children:"Cancel"}),e.jsx($,{onClick:()=>se.mutate({...g,id:m==null?void 0:m.id}),disabled:!g.name.trim(),children:m?"Save Changes":"Create Private Group"})]})]})]})}),e.jsx(zs,{open:y,onOpenChange:v,children:e.jsxs(Rs,{className:"max-w-2xl",children:[e.jsx(Vs,{children:e.jsxs($s,{children:["Manage Members: ",_==null?void 0:_.name]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs(ya,{defaultValue:"brokerages",children:[e.jsxs(va,{className:"w-full",children:[e.jsx(is,{value:"brokerages",className:"flex-1",children:"By Brokerage"}),e.jsx(is,{value:"users",className:"flex-1",children:"Individual Users"})]}),e.jsxs(cs,{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(Eo,{className:"h-[300px] border rounded-md p-4",children:e.jsxs("div",{className:"space-y-2",children:[U.map(Ie=>e.jsxs("div",{className:"flex items-center justify-between p-2 hover:bg-muted rounded-md",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Li,{checked:Se(Ie.id),onCheckedChange:()=>{_&&Q.mutate({groupId:_.id,brokerageId:Ie.id,isMember:Se(Ie.id)})}}),e.jsx("span",{className:"font-medium",children:Ie.name})]}),e.jsxs(qe,{variant:"secondary",children:[B.filter(Ue=>Ue.brokerage_id===Ie.id).length," agents"]})]},Ie.id)),U.length===0&&e.jsx("p",{className:"text-center text-muted-foreground py-4",children:"No brokerages found"})]})})]}),e.jsxs(cs,{value:"users",className:"space-y-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Yr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search users...",value:C,onChange:Ie=>A(Ie.target.value),className:"pl-9"})]}),e.jsx(Eo,{className:"h-[300px] border rounded-md p-4",children:e.jsxs("div",{className:"space-y-2",children:[Te.map(Ie=>e.jsx("div",{className:"flex items-center justify-between p-2 hover:bg-muted rounded-md",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Li,{checked:he(Ie.id),onCheckedChange:()=>{_&&me.mutate({groupId:_.id,userId:Ie.id,isMember:he(Ie.id)})}}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:Ie.name}),e.jsx("div",{className:"text-sm text-muted-foreground",children:Ie.email})]})]})},Ie.id)),Te.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($,{onClick:()=>v(!1),children:"Done"})})]})]})})]})})},fmt=s=>{switch(s){case"academy_video":return e.jsx(pu,{className:"h-3 w-3"});case"template":return e.jsx(ea,{className:"h-3 w-3"});case"toolbox":return e.jsx(bh,{className:"h-3 w-3"});case"newsletter":return e.jsx(N2,{className:"h-3 w-3"});case"social_swag":return e.jsx(kn,{className:"h-3 w-3"});default:return e.jsx(Ir,{className:"h-3 w-3"})}},zGs=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}},BGs=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}},$Gs=()=>{const{toast:s}=Fi(),[t,n]=k.useState([]),[r,a]=k.useState([]),[i,l]=k.useState([]),[o,c]=k.useState(!0),[d,u]=k.useState(""),[h,m]=k.useState(null),[p,g]=k.useState([]),[x,y]=k.useState([]);k.useEffect(()=>{v()},[]);const v=async()=>{try{c(!0);const{data:O,error:B}=await V.from("activity_logs").select(` id, user_id, app_name, launched_at, profiles ( name, email, brokerages ( name ) ) `).order("launched_at",{ascending:!1}).limit(5e3);if(B)throw B;const{data:U,error:G}=await V.from("content_engagement_logs").select(` id, user_id, resource_type, resource_id, resource_title, action_type, created_at `).order("created_at",{ascending:!1}).limit(5e3);if(G)throw G;const H=[...new Set((U==null?void 0:U.map(te=>te.user_id))||[])],{data:Y}=await V.from("profiles").select(` id, name, email, brokerages ( name ) `).in("id",H),se=new Map((Y==null?void 0:Y.map(te=>[te.id,te]))||[]),ee=(O==null?void 0:O.map(te=>{var le,fe,_e,ve;return{id:te.id,user_id:te.user_id,app_name:te.app_name,launched_at:te.launched_at,user_name:((le=te.profiles)==null?void 0:le.name)||"Unknown",user_email:((fe=te.profiles)==null?void 0:fe.email)||"Unknown",brokerage_name:((ve=(_e=te.profiles)==null?void 0:_e.brokerages)==null?void 0:ve.name)||null}}))||[],oe=(U==null?void 0:U.map(te=>{var fe;const le=se.get(te.user_id);return{id:te.id,user_id:te.user_id,resource_type:te.resource_type,resource_id:te.resource_id,resource_title:te.resource_title,action_type:te.action_type,created_at:te.created_at,user_name:(le==null?void 0:le.name)||"Unknown",user_email:(le==null?void 0:le.email)||"Unknown",brokerage_name:((fe=le==null?void 0:le.brokerages)==null?void 0:fe.name)||null}}))||[];n(ee),a(oe);const me=new Map;ee.forEach(te=>{if(!me.has(te.user_id))me.set(te.user_id,{user_id:te.user_id,user_name:te.user_name,user_email:te.user_email,brokerage_name:te.brokerage_name,last_activity_type:"app",last_activity_name:te.app_name,last_activity_at:te.launched_at,total_app_launches:1,total_content_views:0});else{const le=me.get(te.user_id);le.total_app_launches++,new Date(te.launched_at)>new Date(le.last_activity_at)&&(le.last_activity_type="app",le.last_activity_name=te.app_name,le.last_activity_at=te.launched_at)}}),oe.forEach(te=>{if(!me.has(te.user_id))me.set(te.user_id,{user_id:te.user_id,user_name:te.user_name,user_email:te.user_email,brokerage_name:te.brokerage_name,last_activity_type:te.resource_type,last_activity_name:te.resource_title,last_activity_at:te.created_at,total_app_launches:0,total_content_views:1});else{const le=me.get(te.user_id);le.total_content_views++,new Date(te.created_at)>new Date(le.last_activity_at)&&(le.last_activity_type=te.resource_type,le.last_activity_name=te.resource_title,le.last_activity_at=te.created_at)}});const Q=Array.from(me.values()).sort((te,le)=>new Date(le.last_activity_at).getTime()-new Date(te.last_activity_at).getTime());l(Q)}catch(O){console.error("Error loading activity:",O),s({title:"Error",description:"Failed to load activity logs",variant:"destructive"})}finally{c(!1)}},_=O=>{m({id:O.user_id,name:O.user_name,email:O.user_email});const B=t.filter(G=>G.user_id===O.user_id),U=r.filter(G=>G.user_id===O.user_id);g(B),y(U)},j=()=>{m(null),g([]),y([])},{sortKey:C,sortDirection:A,handleSort:M,sortData:I}=Uee("last_activity_at","desc"),P=i.filter(O=>{var U;if(!d)return!0;const B=d.toLowerCase();return O.user_name.toLowerCase().includes(B)||O.user_email.toLowerCase().includes(B)||((U=O.brokerage_name)==null?void 0:U.toLowerCase().includes(B))}),R=I(P,{user:O=>{var B;return((B=O.user_name)==null?void 0:B.toLowerCase())||""},brokerage:O=>{var B;return((B=O.brokerage_name)==null?void 0:B.toLowerCase())||""},last_activity_at:O=>new Date(O.last_activity_at).getTime(),apps:O=>O.total_app_launches,content:O=>O.total_content_views});return o?e.jsx(we,{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(we,{children:[e.jsxs(Vt,{children:[e.jsx(Yt,{children:"User Activity"}),e.jsx(vr,{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(Yr,{className:"absolute left-3 top-3 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search by name, email, or brokerage...",value:d,onChange:O=>u(O.target.value),className:"pl-9"})]})}),e.jsx("div",{className:"rounded-md border",children:e.jsxs(Qa,{children:[e.jsx(Ja,{children:e.jsxs(vn,{children:[e.jsx(Dh,{sortKey:"user",currentSortKey:C,currentDirection:A,onSort:M,children:"User"}),e.jsx(Dh,{sortKey:"brokerage",currentSortKey:C,currentDirection:A,onSort:M,children:"Brokerage"}),e.jsx(Dt,{children:"Last Activity"}),e.jsx(Dh,{sortKey:"last_activity_at",currentSortKey:C,currentDirection:A,onSort:M,children:"Last Active"}),e.jsx(Dh,{sortKey:"apps",currentSortKey:C,currentDirection:A,onSort:M,className:"text-right",children:"Apps"}),e.jsx(Dh,{sortKey:"content",currentSortKey:C,currentDirection:A,onSort:M,className:"text-right",children:"Content"})]})}),e.jsx(ei,{children:R.length===0?e.jsx(vn,{children:e.jsx(_t,{colSpan:6,className:"text-center text-muted-foreground",children:"No activity found"})}):R.map(O=>e.jsxs(vn,{className:"cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>_(O),children:[e.jsx(_t,{children:e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:O.user_name}),e.jsx("div",{className:"text-sm text-muted-foreground",children:O.user_email})]})}),e.jsx(_t,{children:O.brokerage_name?e.jsx(qe,{variant:"outline",children:O.brokerage_name}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"-"})}),e.jsx(_t,{children:e.jsx("div",{className:"flex items-center gap-2",children:O.last_activity_type==="app"?e.jsxs(qe,{variant:"secondary",children:[e.jsx(Ir,{className:"h-3 w-3 mr-1"}),O.last_activity_name]}):e.jsxs(qe,{variant:"outline",className:"flex items-center gap-1",children:[fmt(O.last_activity_type),e.jsx("span",{className:"max-w-32 truncate",children:O.last_activity_name})]})})}),e.jsx(_t,{className:"text-sm text-muted-foreground",children:Zc(new Date(O.last_activity_at),{addSuffix:!0})}),e.jsx(_t,{className:"text-right",children:e.jsx(qe,{variant:"outline",children:O.total_app_launches})}),e.jsx(_t,{className:"text-right",children:e.jsx(qe,{variant:"outline",children:O.total_content_views})})]},O.user_id))})]})})]})]}),e.jsx(zs,{open:!!h,onOpenChange:O=>!O&&j(),children:e.jsxs(Rs,{className:"max-w-3xl max-h-[80vh] overflow-hidden flex flex-col",children:[e.jsxs(Vs,{children:[e.jsxs($s,{children:[h==null?void 0:h.name,"'s Activity"]}),e.jsx(Cr,{children:h==null?void 0:h.email})]}),e.jsxs(ya,{defaultValue:"content",className:"flex-1 overflow-hidden flex flex-col",children:[e.jsxs(va,{className:"grid w-full grid-cols-2",children:[e.jsxs(is,{value:"content",children:["Content (",x.length,")"]}),e.jsxs(is,{value:"apps",children:["App Launches (",p.length,")"]})]}),e.jsx(cs,{value:"content",className:"flex-1 overflow-auto mt-4",children:e.jsx("div",{className:"rounded-md border",children:e.jsxs(Qa,{children:[e.jsx(Ja,{children:e.jsxs(vn,{children:[e.jsx(Dt,{children:"Type"}),e.jsx(Dt,{children:"Resource"}),e.jsx(Dt,{children:"Action"}),e.jsx(Dt,{children:"Time"})]})}),e.jsx(ei,{children:x.length===0?e.jsx(vn,{children:e.jsx(_t,{colSpan:4,className:"text-center text-muted-foreground",children:"No content engagement"})}):x.map(O=>e.jsxs(vn,{children:[e.jsx(_t,{children:e.jsxs(qe,{variant:"outline",className:"flex items-center gap-1 w-fit",children:[fmt(O.resource_type),zGs(O.resource_type)]})}),e.jsx(_t,{className:"max-w-48",children:e.jsx("span",{className:"truncate block",children:O.resource_title})}),e.jsx(_t,{children:e.jsx(qe,{variant:"secondary",children:BGs(O.action_type)})}),e.jsx(_t,{className:"text-sm text-muted-foreground",children:Zc(new Date(O.created_at),{addSuffix:!0})})]},O.id))})]})})}),e.jsx(cs,{value:"apps",className:"flex-1 overflow-auto mt-4",children:e.jsx("div",{className:"rounded-md border",children:e.jsxs(Qa,{children:[e.jsx(Ja,{children:e.jsxs(vn,{children:[e.jsx(Dt,{children:"App"}),e.jsx(Dt,{children:"Time"})]})}),e.jsx(ei,{children:p.length===0?e.jsx(vn,{children:e.jsx(_t,{colSpan:2,className:"text-center text-muted-foreground",children:"No app launches"})}):p.map(O=>e.jsxs(vn,{children:[e.jsx(_t,{children:e.jsx(qe,{variant:"secondary",children:O.app_name})}),e.jsx(_t,{className:"text-sm text-muted-foreground",children:Zc(new Date(O.launched_at),{addSuffix:!0})})]},O.id))})]})})})]})]})})]})},UGs=()=>{const{toast:s}=Fi(),[t,n]=k.useState({totalUsers:0,activeUsers:0,pendingUsers:0,totalBrokerages:0,totalLaunches:0,launchesThisWeek:0,launchesThisMonth:0,uniqueActiveThisWeek:0}),[r,a]=k.useState(!0);k.useEffect(()=>{i()},[]);const i=async()=>{try{a(!0);const{count:l}=await V.from("profiles").select("*",{count:"exact",head:!0}),{count:o}=await V.from("profiles").select("*",{count:"exact",head:!0}).not("last_login","is",null),c=(l||0)-(o||0),{count:d}=await V.from("brokerages").select("*",{count:"exact",head:!0}),{count:u}=await V.from("activity_logs").select("*",{count:"exact",head:!0}),h=new Date;h.setDate(h.getDate()-7);const{count:m}=await V.from("activity_logs").select("*",{count:"exact",head:!0}).gte("launched_at",h.toISOString()),p=new Date;p.setMonth(p.getMonth()-1);const{count:g}=await V.from("activity_logs").select("*",{count:"exact",head:!0}).gte("launched_at",p.toISOString()),{data:x}=await V.from("activity_logs").select("user_id").gte("launched_at",h.toISOString()),y=new Set(x==null?void 0:x.map(v=>v.user_id)).size;n({totalUsers:l||0,activeUsers:o||0,pendingUsers:c,totalBrokerages:d||0,totalLaunches:u||0,launchesThisWeek:m||0,launchesThisMonth:g||0,uniqueActiveThisWeek:y})}catch(l){console.error("Error loading analytics:",l),s({title:"Error",description:"Failed to load analytics",variant:"destructive"})}finally{a(!1)}};return r?e.jsx(we,{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(we,{children:[e.jsxs(Vt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Yt,{className:"text-sm font-medium",children:"Total Users"}),e.jsx(Xn,{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(we,{children:[e.jsxs(Vt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Yt,{className:"text-sm font-medium",children:"Active Users"}),e.jsx(nl,{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(we,{children:[e.jsxs(Vt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Yt,{className:"text-sm font-medium",children:"Pending Invites"}),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.pendingUsers}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Awaiting setup"})]})]}),e.jsxs(we,{children:[e.jsxs(Vt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Yt,{className:"text-sm font-medium",children:"Brokerages"}),e.jsx(Gi,{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(we,{children:[e.jsxs(Vt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Yt,{className:"text-sm font-medium",children:"Total App Launches"}),e.jsx(zp,{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(we,{children:[e.jsxs(Vt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Yt,{className:"text-sm font-medium",children:"Launches This Week"}),e.jsx(zp,{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(we,{children:[e.jsxs(Vt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Yt,{className:"text-sm font-medium",children:"Launches This Month"}),e.jsx(zp,{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(we,{children:[e.jsxs(Vt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Yt,{className:"text-sm font-medium",children:"Active This Week"}),e.jsx(mc,{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"})]})]})]})},pmt={event:"Event",template:"Template",academy_video:"Academy Video",resource_kit:"Resource Kit",newsletter:"Newsletter",social_swag:"Social Swag"},gmt={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 JRt({brokerageOnly:s=!1,brokerageId:t}){const[n,r]=k.useState([]),[a,i]=k.useState(!0),[l,o]=k.useState(""),[c,d]=k.useState("all");k.useEffect(()=>{u()},[t]);const u=async()=>{i(!0);try{let M=[];if(s&&t){const{data:H}=await V.from("profiles").select("id").eq("brokerage_id",t);if(M=(H==null?void 0:H.map(Y=>Y.id))||[],M.length===0){r([]),i(!1);return}}let I=V.from("resource_shares").select("*").order("created_at",{ascending:!1});s&&M.length>0&&(I=I.or(`sender_id.in.(${M.join(",")}),recipient_id.in.(${M.join(",")})`));const{data:P,error:R}=await I;if(R)throw R;const O=new Set;P==null||P.forEach(H=>{O.add(H.sender_id),O.add(H.recipient_id)});const{data:B}=await V.from("profiles").select("id, name, email").in("id",Array.from(O)),U=new Map((B==null?void 0:B.map(H=>[H.id,H]))||[]),G=(P==null?void 0:P.map(H=>({...H,sender:U.get(H.sender_id),recipient:U.get(H.recipient_id)})))||[];r(G)}catch(M){console.error("Error loading shares:",M)}finally{i(!1)}},{sortKey:h,sortDirection:m,handleSort:p,sortData:g}=Uee("created_at","desc"),x=n.filter(M=>{var R,O;const I=l===""||M.resource_title.toLowerCase().includes(l.toLowerCase())||((R=M.sender)==null?void 0:R.name.toLowerCase().includes(l.toLowerCase()))||((O=M.recipient)==null?void 0:O.name.toLowerCase().includes(l.toLowerCase())),P=c==="all"||M.resource_type===c;return I&&P}),y=g(x,{resource:M=>{var I;return((I=M.resource_title)==null?void 0:I.toLowerCase())||""},type:M=>M.resource_type,sender:M=>{var I,P;return((P=(I=M.sender)==null?void 0:I.name)==null?void 0:P.toLowerCase())||""},recipient:M=>{var I,P;return((P=(I=M.recipient)==null?void 0:I.name)==null?void 0:P.toLowerCase())||""},status:M=>M.is_read?1:0,created_at:M=>new Date(M.created_at).getTime()}),v=n.length,_=new Set(n.map(M=>M.sender_id)).size,j=new Set(n.map(M=>M.recipient_id)).size,C=n.length>0?Math.round(n.filter(M=>M.is_read).length/n.length*100):0,A=n.reduce((M,I)=>(M[I.resource_type]=(M[I.resource_type]||0)+1,M),{});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((M,I)=>e.jsxs(we,{children:[e.jsx(Vt,{className:"pb-2",children:e.jsx(fn,{className:"h-4 w-20"})}),e.jsx(De,{children:e.jsx(fn,{className:"h-8 w-16"})})]},I))}),e.jsx(we,{children:e.jsx(De,{className:"p-6",children:e.jsx(fn,{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(we,{children:[e.jsxs(Vt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Yt,{className:"text-sm font-medium",children:"Total Shares"}),e.jsx(ou,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(De,{children:e.jsx("div",{className:"text-2xl font-bold",children:v})})]}),e.jsxs(we,{children:[e.jsxs(Vt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Yt,{className:"text-sm font-medium",children:"Active Sharers"}),e.jsx(Xn,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(De,{children:e.jsx("div",{className:"text-2xl font-bold",children:_})})]}),e.jsxs(we,{children:[e.jsxs(Vt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Yt,{className:"text-sm font-medium",children:"Recipients Reached"}),e.jsx(mc,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(De,{children:e.jsx("div",{className:"text-2xl font-bold",children:j})})]}),e.jsxs(we,{children:[e.jsxs(Vt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Yt,{className:"text-sm font-medium",children:"Read Rate"}),e.jsx(ea,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(De,{children:e.jsxs("div",{className:"text-2xl font-bold",children:[C,"%"]})})]})]}),e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsx(Yt,{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(A).map(([M,I])=>e.jsxs(qe,{variant:"secondary",className:gmt[M],children:[pmt[M],": ",I]},M)),Object.keys(A).length===0&&e.jsx("span",{className:"text-muted-foreground text-sm",children:"No shares yet"})]})})]}),e.jsxs(we,{children:[e.jsxs(Vt,{children:[e.jsx(Yt,{children:"Share History"}),e.jsxs(vr,{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(Yr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search by resource, sender, or recipient...",value:l,onChange:M=>o(M.target.value),className:"pl-9"})]}),e.jsxs(bs,{value:c,onValueChange:d,children:[e.jsx(ys,{className:"w-[180px]",children:e.jsx(_s,{placeholder:"Resource type"})}),e.jsxs(vs,{children:[e.jsx(We,{value:"all",children:"All Types"}),e.jsx(We,{value:"event",children:"Events"}),e.jsx(We,{value:"template",children:"Templates"}),e.jsx(We,{value:"academy_video",children:"Academy Videos"}),e.jsx(We,{value:"resource_kit",children:"Resource Kits"}),e.jsx(We,{value:"newsletter",children:"Newsletters"}),e.jsx(We,{value:"social_swag",children:"Social Swag"})]})]})]}),e.jsx(Eo,{className:"h-[400px]",children:e.jsxs(Qa,{children:[e.jsx(Ja,{children:e.jsxs(vn,{children:[e.jsx(Dh,{sortKey:"resource",currentSortKey:h,currentDirection:m,onSort:p,children:"Resource"}),e.jsx(Dh,{sortKey:"type",currentSortKey:h,currentDirection:m,onSort:p,children:"Type"}),e.jsx(Dh,{sortKey:"sender",currentSortKey:h,currentDirection:m,onSort:p,children:"Sender"}),e.jsx(Dh,{sortKey:"recipient",currentSortKey:h,currentDirection:m,onSort:p,children:"Recipient"}),e.jsx(Dh,{sortKey:"status",currentSortKey:h,currentDirection:m,onSort:p,children:"Status"}),e.jsx(Dh,{sortKey:"created_at",currentSortKey:h,currentDirection:m,onSort:p,children:"Date"})]})}),e.jsx(ei,{children:y.length===0?e.jsx(vn,{children:e.jsx(_t,{colSpan:6,className:"text-center text-muted-foreground py-8",children:"No shares found"})}):y.map(M=>{var I,P;return e.jsxs(vn,{children:[e.jsx(_t,{className:"font-medium max-w-[200px] truncate",children:M.resource_title}),e.jsx(_t,{children:e.jsx(qe,{variant:"secondary",className:gmt[M.resource_type],children:pmt[M.resource_type]})}),e.jsx(_t,{children:((I=M.sender)==null?void 0:I.name)||"Unknown"}),e.jsx(_t,{children:((P=M.recipient)==null?void 0:P.name)||"Unknown"}),e.jsx(_t,{children:e.jsx(qe,{variant:M.is_read?"default":"outline",children:M.is_read?"Read":"Unread"})}),e.jsx(_t,{className:"text-muted-foreground",children:Ys(new Date(M.created_at),"MMM d, yyyy")})]},M.id)})})]})})]})]})]})}const iRe={academy_video:{label:"Academy Videos",icon:ia,color:"bg-purple-100 text-purple-800",actionLabel:"Watched",actionIcon:ba},template:{label:"Templates",icon:jC,color:"bg-blue-100 text-blue-800",actionLabel:"Accessed",actionIcon:sv},toolbox:{label:"Toolkit",icon:L5,color:"bg-amber-100 text-amber-800",actionLabel:"Downloaded",actionIcon:ji},newsletter:{label:"Newsletters",icon:pn,color:"bg-emerald-100 text-emerald-800",actionLabel:"Clicked",actionIcon:sv},social_swag:{label:"Social Swag",icon:gd,color:"bg-pink-100 text-pink-800",actionLabel:"Accessed",actionIcon:sv},event:{label:"Events",icon:ha,color:"bg-cyan-100 text-cyan-800",actionLabel:"Registered",actionIcon:sv}};function xmt(s){return s.resource_type==="toolbox"?s.total_downloads:s.total_clicks}function qGs(s,t){return s==="toolbox"?t.downloads:t.clicks}function VGs(){var M;const[s,t]=k.useState([]),[n,r]=k.useState(!0),[a,i]=k.useState(null),l=k.useRef(null),{sortKey:o,sortDirection:c,handleSort:d,sortData:u}=Uee("total_views","desc");k.useEffect(()=>{h()},[]);const h=async()=>{try{const{data:I,error:P}=await V.rpc("get_admin_content_engagement");if(P)throw P;t(I||[])}catch(I){console.error("Error loading content engagement:",I)}finally{r(!1)}},m=I=>{i(P=>{const R=P===I?null:I;return requestAnimationFrame(()=>{var O;(O=l.current)==null||O.scrollIntoView({behavior:"smooth",block:"start"})}),R})};if(n)return e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"grid gap-3 grid-cols-2 md:grid-cols-4",children:[...Array(4)].map((I,P)=>e.jsxs(we,{children:[e.jsx(Vt,{className:"pb-2",children:e.jsx(fn,{className:"h-4 w-20"})}),e.jsx(De,{children:e.jsx(fn,{className:"h-8 w-16"})})]},P))}),e.jsx(we,{children:e.jsx(De,{className:"py-8",children:e.jsx(fn,{className:"h-64 w-full"})})})]});const p=s.reduce((I,P)=>I+P.total_views,0),g=s.reduce((I,P)=>I+P.total_clicks,0),x=s.reduce((I,P)=>I+P.total_downloads,0),y=s.length,v=s.reduce((I,P)=>(I[P.resource_type]||(I[P.resource_type]={views:0,clicks:0,downloads:0,assets:0,uniqueUsers:0}),I[P.resource_type].views+=P.total_views,I[P.resource_type].clicks+=P.total_clicks,I[P.resource_type].downloads+=P.total_downloads,I[P.resource_type].assets+=1,I[P.resource_type].uniqueUsers+=P.unique_users,I),{}),_=a?s.filter(I=>I.resource_type===a):s,j=u(_,{asset:I=>{var P;return((P=I.resource_title)==null?void 0:P.toLowerCase())||""},type:I=>I.resource_type,views:I=>I.total_views,actions:I=>xmt(I),unique_users:I=>I.unique_users,last_activity:I=>I.last_engaged_at?new Date(I.last_engaged_at).getTime():0}),C=a?iRe[a]||{label:a,icon:ba,actionLabel:"Actions"}:null,A=C==null?void 0:C.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(we,{children:[e.jsxs(Vt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Yt,{className:"text-sm font-medium",children:"Total Views"}),e.jsx(ba,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(De,{children:[e.jsx("div",{className:"text-2xl font-bold",children:p.toLocaleString()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Across all content"})]})]}),e.jsxs(we,{children:[e.jsxs(Vt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Yt,{className:"text-sm font-medium",children:"Total Clicks"}),e.jsx(sv,{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:"Link & Canva clicks"})]})]}),e.jsxs(we,{children:[e.jsxs(Vt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Yt,{className:"text-sm font-medium",children:"Downloads"}),e.jsx(ji,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(De,{children:[e.jsx("div",{className:"text-2xl font-bold",children:x.toLocaleString()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"PDF downloads"})]})]}),e.jsxs(we,{children:[e.jsxs(Vt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Yt,{className:"text-sm font-medium",children:"Assets Tracked"}),e.jsx(mc,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(De,{children:[e.jsx("div",{className:"text-2xl font-bold",children:y}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Unique content items"})]})]}),e.jsxs(we,{children:[e.jsxs(Vt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Yt,{className:"text-sm font-medium",children:"Click Rate"}),e.jsx(sv,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(De,{children:[e.jsxs("div",{className:"text-2xl font-bold",children:[p>0?Math.round((g+x)/p*100):0,"%"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Of views → actions"})]})]})]}),e.jsxs(we,{children:[e.jsxs(Vt,{children:[e.jsx(Yt,{className:"text-sm font-medium",children:"Engagement by Content Type"}),e.jsx(vr,{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(v).map(([I,P])=>{const R=iRe[I]||{label:I,icon:ba,color:"bg-muted text-muted-foreground",actionIcon:sv},O=R.icon,B=a===I;return e.jsxs("button",{type:"button",onClick:()=>m(I),className:`flex items-center gap-3 p-3 rounded-lg border text-left transition-colors cursor-pointer ${B?"ring-2 ring-primary border-primary bg-primary/5":"hover:bg-muted/50"}`,children:[e.jsx("div",{className:`p-2 rounded-md ${R.color}`,children:e.jsx(O,{className:"h-4 w-4"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium",children:R.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(ba,{className:"h-3 w-3"})," ",P.views]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(R.actionIcon,{className:"h-3 w-3"})," ",qGs(I,P)]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Xn,{className:"h-3 w-3"})," ",P.uniqueUsers]})]})]}),e.jsxs(qe,{variant:"secondary",className:"text-[10px]",children:[P.assets," items"]})]},I)})})})]}),e.jsx("div",{ref:l,children:e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Yt,{className:"text-sm font-medium flex items-center gap-2",children:C&&A?e.jsxs(e.Fragment,{children:[e.jsx(A,{className:"h-4 w-4"}),C.label," — Top Performers"]}):"Top Content by Engagement"}),e.jsx(vr,{children:a?`${_.length} ${((M=C==null?void 0:C.label)==null?void 0:M.toLowerCase())||"items"} ranked by total interactions`:"All tracked assets ranked by total interactions"})]}),a&&e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>i(null),className:"gap-1",children:[e.jsx(Ia,{className:"h-3.5 w-3.5"}),"Show All"]})]})}),e.jsx(De,{children:_.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(Eo,{className:"h-[400px]",children:e.jsxs(Qa,{children:[e.jsx(Ja,{children:e.jsxs(vn,{children:[e.jsx(Dt,{className:"w-[40px]",children:"#"}),e.jsx(Dh,{sortKey:"asset",currentSortKey:o,currentDirection:c,onSort:d,children:"Asset"}),!a&&e.jsx(Dh,{sortKey:"type",currentSortKey:o,currentDirection:c,onSort:d,children:"Type"}),e.jsx(Dh,{sortKey:"views",currentSortKey:o,currentDirection:c,onSort:d,className:"text-right",children:"Views"}),e.jsx(Dh,{sortKey:"actions",currentSortKey:o,currentDirection:c,onSort:d,className:"text-right",children:C?C.actionLabel:"Actions"}),e.jsx(Dh,{sortKey:"unique_users",currentSortKey:o,currentDirection:c,onSort:d,className:"text-right",children:"Unique Users"}),e.jsx(Dh,{sortKey:"last_activity",currentSortKey:o,currentDirection:c,onSort:d,children:"Last Activity"})]})}),e.jsx(ei,{children:j.map((I,P)=>{const R=iRe[I.resource_type]||{label:I.resource_type,color:"bg-muted text-muted-foreground"};return e.jsxs(vn,{children:[e.jsx(_t,{className:"text-muted-foreground text-xs",children:P+1}),e.jsx(_t,{children:e.jsx("p",{className:"font-medium text-sm truncate max-w-[250px]",children:I.resource_title})}),!a&&e.jsx(_t,{children:e.jsx(qe,{className:`text-[10px] ${R.color}`,children:R.label})}),e.jsx(_t,{className:"text-right font-medium",children:I.total_views}),e.jsx(_t,{className:"text-right font-medium",children:xmt(I)}),e.jsx(_t,{className:"text-right",children:I.unique_users}),e.jsx(_t,{className:"text-xs text-muted-foreground",children:I.last_engaged_at?Zc(new Date(I.last_engaged_at),{addSuffix:!0}):"—"})]},`${I.resource_type}-${I.resource_id}`)})})]})})})]})})]})}var HGs=Array.isArray,B_=HGs,GGs=typeof jf=="object"&&jf&&jf.Object===Object&&jf,eDt=GGs,WGs=eDt,KGs=typeof self=="object"&&self&&self.Object===Object&&self,YGs=WGs||KGs||Function("return this")(),a4=YGs,ZGs=a4,XGs=ZGs.Symbol,Kee=XGs,ymt=Kee,tDt=Object.prototype,QGs=tDt.hasOwnProperty,JGs=tDt.toString,wG=ymt?ymt.toStringTag:void 0;function eWs(s){var t=QGs.call(s,wG),n=s[wG];try{s[wG]=void 0;var r=!0}catch{}var a=JGs.call(s);return r&&(t?s[wG]=n:delete s[wG]),a}var tWs=eWs,sWs=Object.prototype,nWs=sWs.toString;function rWs(s){return nWs.call(s)}var aWs=rWs,vmt=Kee,iWs=tWs,oWs=aWs,lWs="[object Null]",cWs="[object Undefined]",bmt=vmt?vmt.toStringTag:void 0;function dWs(s){return s==null?s===void 0?cWs:lWs:bmt&&bmt in Object(s)?iWs(s):oWs(s)}var uA=dWs;function uWs(s){return s!=null&&typeof s=="object"}var hA=uWs,hWs=uA,mWs=hA,fWs="[object Symbol]";function pWs(s){return typeof s=="symbol"||mWs(s)&&hWs(s)==fWs}var dV=pWs,gWs=B_,xWs=dV,yWs=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,vWs=/^\w*$/;function bWs(s,t){if(gWs(s))return!1;var n=typeof s;return n=="number"||n=="symbol"||n=="boolean"||s==null||xWs(s)?!0:vWs.test(s)||!yWs.test(s)||t!=null&&s in Object(t)}var cYe=bWs;function _Ws(s){var t=typeof s;return s!=null&&(t=="object"||t=="function")}var m6=_Ws;const uV=kd(m6);var wWs=uA,jWs=m6,NWs="[object AsyncFunction]",kWs="[object Function]",SWs="[object GeneratorFunction]",CWs="[object Proxy]";function AWs(s){if(!jWs(s))return!1;var t=wWs(s);return t==kWs||t==SWs||t==NWs||t==CWs}var dYe=AWs;const Dl=kd(dYe);var EWs=a4,TWs=EWs["__core-js_shared__"],MWs=TWs,oRe=MWs,_mt=function(){var s=/[^.]+$/.exec(oRe&&oRe.keys&&oRe.keys.IE_PROTO||"");return s?"Symbol(src)_1."+s:""}();function PWs(s){return!!_mt&&_mt in s}var IWs=PWs,LWs=Function.prototype,RWs=LWs.toString;function DWs(s){if(s!=null){try{return RWs.call(s)}catch{}try{return s+""}catch{}}return""}var sDt=DWs,OWs=dYe,FWs=IWs,zWs=m6,BWs=sDt,$Ws=/[\\^$.*+?()[\]{}|]/g,UWs=/^\[object .+?Constructor\]$/,qWs=Function.prototype,VWs=Object.prototype,HWs=qWs.toString,GWs=VWs.hasOwnProperty,WWs=RegExp("^"+HWs.call(GWs).replace($Ws,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function KWs(s){if(!zWs(s)||FWs(s))return!1;var t=OWs(s)?WWs:UWs;return t.test(BWs(s))}var YWs=KWs;function ZWs(s,t){return s==null?void 0:s[t]}var XWs=ZWs,QWs=YWs,JWs=XWs;function eKs(s,t){var n=JWs(s,t);return QWs(n)?n:void 0}var IF=eKs,tKs=IF,sKs=tKs(Object,"create"),rEe=sKs,wmt=rEe;function nKs(){this.__data__=wmt?wmt(null):{},this.size=0}var rKs=nKs;function aKs(s){var t=this.has(s)&&delete this.__data__[s];return this.size-=t?1:0,t}var iKs=aKs,oKs=rEe,lKs="__lodash_hash_undefined__",cKs=Object.prototype,dKs=cKs.hasOwnProperty;function uKs(s){var t=this.__data__;if(oKs){var n=t[s];return n===lKs?void 0:n}return dKs.call(t,s)?t[s]:void 0}var hKs=uKs,mKs=rEe,fKs=Object.prototype,pKs=fKs.hasOwnProperty;function gKs(s){var t=this.__data__;return mKs?t[s]!==void 0:pKs.call(t,s)}var xKs=gKs,yKs=rEe,vKs="__lodash_hash_undefined__";function bKs(s,t){var n=this.__data__;return this.size+=this.has(s)?0:1,n[s]=yKs&&t===void 0?vKs:t,this}var _Ks=bKs,wKs=rKs,jKs=iKs,NKs=hKs,kKs=xKs,SKs=_Ks;function hV(s){var t=-1,n=s==null?0:s.length;for(this.clear();++t-1}var qKs=UKs,VKs=aEe;function HKs(s,t){var n=this.__data__,r=VKs(n,s);return r<0?(++this.size,n.push([s,t])):n[r][1]=t,this}var GKs=HKs,WKs=EKs,KKs=OKs,YKs=BKs,ZKs=qKs,XKs=GKs;function mV(s){var t=-1,n=s==null?0:s.length;for(this.clear();++t0?1:-1},mD=function(t){return VO(t)&&t.indexOf("%")===t.length-1},Ha=function(t){return xZs(t)&&!pV(t)},_Zs=function(t){return hc(t)},by=function(t){return Ha(t)||VO(t)},wZs=0,LF=function(t){var n=++wZs;return"".concat(t||"").concat(n)},ub=function(t,n){var r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:0,a=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1;if(!Ha(t)&&!VO(t))return r;var i;if(mD(t)){var l=t.indexOf("%");i=n*parseFloat(t.slice(0,l))/100}else i=+t;return pV(i)&&(i=r),a&&i>n&&(i=n),i},PE=function(t){if(!t)return null;var n=Object.keys(t);return n&&n.length?t[n[0]]:null},jZs=function(t){if(!Array.isArray(t))return!1;for(var n=t.length,r={},a=0;a=0)&&Object.prototype.propertyIsEnumerable.call(s,r)&&(n[r]=s[r])}return n}function TZs(s,t){if(s==null)return{};var n={};for(var r in s)if(Object.prototype.hasOwnProperty.call(s,r)){if(t.indexOf(r)>=0)continue;n[r]=s[r]}return n}function cze(s){"@babel/helpers - typeof";return cze=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},cze(s)}var Emt={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"},C3=function(t){return typeof t=="string"?t:t?t.displayName||t.name||"Component":""},Tmt=null,cRe=null,bYe=function s(t){if(t===Tmt&&Array.isArray(cRe))return cRe;var n=[];return k.Children.forEach(t,function(r){hc(r)||(hZs.isFragment(r)?n=n.concat(s(r.props.children)):n.push(r))}),cRe=n,Tmt=t,n};function nj(s,t){var n=[],r=[];return Array.isArray(t)?r=t.map(function(a){return C3(a)}):r=[C3(t)],bYe(s).forEach(function(a){var i=sj(a,"type.displayName")||sj(a,"type.name");r.indexOf(i)!==-1&&n.push(a)}),n}function Lw(s,t){var n=nj(s,t);return n&&n[0]}var Mmt=function(t){if(!t||!t.props)return!1;var n=t.props,r=n.width,a=n.height;return!(!Ha(r)||r<=0||!Ha(a)||a<=0)},MZs=["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"],PZs=function(t){return t&&t.type&&VO(t.type)&&MZs.indexOf(t.type)>=0},hDt=function(t){return t&&cze(t)==="object"&&"clipDot"in t},IZs=function(t,n,r,a){var i,l=(i=lRe==null?void 0:lRe[a])!==null&&i!==void 0?i:[];return n.startsWith("data-")||!Dl(t)&&(a&&l.includes(n)||SZs.includes(n))||r&&vYe.includes(n)},Yo=function(t,n,r){if(!t||typeof t=="function"||typeof t=="boolean")return null;var a=t;if(k.isValidElement(t)&&(a=t.props),!uV(a))return null;var i={};return Object.keys(a).forEach(function(l){var o;IZs((o=a)===null||o===void 0?void 0:o[l],l,n,r)&&(i[l]=a[l])}),i},dze=function s(t,n){if(t===n)return!0;var r=k.Children.count(t);if(r!==k.Children.count(n))return!1;if(r===0)return!0;if(r===1)return Pmt(Array.isArray(t)?t[0]:t,Array.isArray(n)?n[0]:n);for(var a=0;a=0)&&Object.prototype.propertyIsEnumerable.call(s,r)&&(n[r]=s[r])}return n}function FZs(s,t){if(s==null)return{};var n={};for(var r in s)if(Object.prototype.hasOwnProperty.call(s,r)){if(t.indexOf(r)>=0)continue;n[r]=s[r]}return n}function hze(s){var t=s.children,n=s.width,r=s.height,a=s.viewBox,i=s.className,l=s.style,o=s.title,c=s.desc,d=OZs(s,DZs),u=a||{width:n,height:r,x:0,y:0},h=bc("recharts-surface",i);return zt.createElement("svg",uze({},Yo(d,!0,"svg"),{className:h,width:n,height:r,style:l,viewBox:"".concat(u.x," ").concat(u.y," ").concat(u.width," ").concat(u.height)}),zt.createElement("title",null,o),zt.createElement("desc",null,c),t)}var zZs=["children","className"];function mze(){return mze=Object.assign?Object.assign.bind():function(s){for(var t=1;t=0)&&Object.prototype.propertyIsEnumerable.call(s,r)&&(n[r]=s[r])}return n}function $Zs(s,t){if(s==null)return{};var n={};for(var r in s)if(Object.prototype.hasOwnProperty.call(s,r)){if(t.indexOf(r)>=0)continue;n[r]=s[r]}return n}var Id=zt.forwardRef(function(s,t){var n=s.children,r=s.className,a=BZs(s,zZs),i=bc("recharts-layer",r);return zt.createElement("g",mze({className:i},Yo(a,!0),{ref:t}),n)}),mk=function(t,n){for(var r=arguments.length,a=new Array(r>2?r-2:0),i=2;ia?0:a+t),n=n>a?a:n,n<0&&(n+=a),a=t>n?0:n-t>>>0,t>>>=0;for(var i=Array(a);++r=r?s:VZs(s,t,n)}var GZs=HZs,WZs="\\ud800-\\udfff",KZs="\\u0300-\\u036f",YZs="\\ufe20-\\ufe2f",ZZs="\\u20d0-\\u20ff",XZs=KZs+YZs+ZZs,QZs="\\ufe0e\\ufe0f",JZs="\\u200d",eXs=RegExp("["+JZs+WZs+XZs+QZs+"]");function tXs(s){return eXs.test(s)}var mDt=tXs;function sXs(s){return s.split("")}var nXs=sXs,fDt="\\ud800-\\udfff",rXs="\\u0300-\\u036f",aXs="\\ufe20-\\ufe2f",iXs="\\u20d0-\\u20ff",oXs=rXs+aXs+iXs,lXs="\\ufe0e\\ufe0f",cXs="["+fDt+"]",fze="["+oXs+"]",pze="\\ud83c[\\udffb-\\udfff]",dXs="(?:"+fze+"|"+pze+")",pDt="[^"+fDt+"]",gDt="(?:\\ud83c[\\udde6-\\uddff]){2}",xDt="[\\ud800-\\udbff][\\udc00-\\udfff]",uXs="\\u200d",yDt=dXs+"?",vDt="["+lXs+"]?",hXs="(?:"+uXs+"(?:"+[pDt,gDt,xDt].join("|")+")"+vDt+yDt+")*",mXs=vDt+yDt+hXs,fXs="(?:"+[pDt+fze+"?",fze,gDt,xDt,cXs].join("|")+")",pXs=RegExp(pze+"(?="+pze+")|"+fXs+mXs,"g");function gXs(s){return s.match(pXs)||[]}var xXs=gXs,yXs=nXs,vXs=mDt,bXs=xXs;function _Xs(s){return vXs(s)?bXs(s):yXs(s)}var wXs=_Xs,jXs=GZs,NXs=mDt,kXs=wXs,SXs=iDt;function CXs(s){return function(t){t=SXs(t);var n=NXs(t)?kXs(t):void 0,r=n?n[0]:t.charAt(0),a=n?jXs(n,1).join(""):t.slice(1);return r[s]()+a}}var AXs=CXs,EXs=AXs,TXs=EXs("toUpperCase"),MXs=TXs;const vEe=kd(MXs);function Rm(s){return function(){return s}}const bDt=Math.cos,k5e=Math.sin,Tk=Math.sqrt,S5e=Math.PI,bEe=2*S5e,gze=Math.PI,xze=2*gze,IR=1e-6,PXs=xze-IR;function _Dt(s){this._+=s[0];for(let t=1,n=s.length;t=0))throw new Error(`invalid digits: ${s}`);if(t>15)return _Dt;const n=10**t;return function(r){this._+=r[0];for(let a=1,i=r.length;aIR)if(!(Math.abs(h*c-d*u)>IR)||!i)this._append`L${this._x1=t},${this._y1=n}`;else{let p=r-l,g=a-o,x=c*c+d*d,y=p*p+g*g,v=Math.sqrt(x),_=Math.sqrt(m),j=i*Math.tan((gze-Math.acos((x+m-y)/(2*v*_)))/2),C=j/_,A=j/v;Math.abs(C-1)>IR&&this._append`L${t+C*u},${n+C*h}`,this._append`A${i},${i},0,0,${+(h*p>u*g)},${this._x1=t+A*c},${this._y1=n+A*d}`}}arc(t,n,r,a,i,l){if(t=+t,n=+n,r=+r,l=!!l,r<0)throw new Error(`negative radius: ${r}`);let o=r*Math.cos(a),c=r*Math.sin(a),d=t+o,u=n+c,h=1^l,m=l?a-i:i-a;this._x1===null?this._append`M${d},${u}`:(Math.abs(this._x1-d)>IR||Math.abs(this._y1-u)>IR)&&this._append`L${d},${u}`,r&&(m<0&&(m=m%xze+xze),m>PXs?this._append`A${r},${r},0,1,${h},${t-o},${n-c}A${r},${r},0,1,${h},${this._x1=d},${this._y1=u}`:m>IR&&this._append`A${r},${r},0,${+(m>=gze)},${h},${this._x1=t+r*Math.cos(i)},${this._y1=n+r*Math.sin(i)}`)}rect(t,n,r,a){this._append`M${this._x0=this._x1=+t},${this._y0=this._y1=+n}h${r=+r}v${+a}h${-r}Z`}toString(){return this._}}function _Ye(s){let t=3;return s.digits=function(n){if(!arguments.length)return t;if(n==null)t=null;else{const r=Math.floor(n);if(!(r>=0))throw new RangeError(`invalid digits: ${n}`);t=r}return s},()=>new LXs(t)}function wYe(s){return typeof s=="object"&&"length"in s?s:Array.from(s)}function wDt(s){this._context=s}wDt.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 _Ee(s){return new wDt(s)}function jDt(s){return s[0]}function NDt(s){return s[1]}function kDt(s,t){var n=Rm(!0),r=null,a=_Ee,i=null,l=_Ye(o);s=typeof s=="function"?s:s===void 0?jDt:Rm(s),t=typeof t=="function"?t:t===void 0?NDt:Rm(t);function o(c){var d,u=(c=wYe(c)).length,h,m=!1,p;for(r==null&&(i=a(p=l())),d=0;d<=u;++d)!(d=p;--g)o.point(j[g],C[g]);o.lineEnd(),o.areaEnd()}v&&(j[m]=+s(y,m,h),C[m]=+t(y,m,h),o.point(r?+r(y,m,h):j[m],n?+n(y,m,h):C[m]))}if(_)return o=null,_+""||null}function u(){return kDt().defined(a).curve(l).context(i)}return d.x=function(h){return arguments.length?(s=typeof h=="function"?h:Rm(+h),r=null,d):s},d.x0=function(h){return arguments.length?(s=typeof h=="function"?h:Rm(+h),d):s},d.x1=function(h){return arguments.length?(r=h==null?null:typeof h=="function"?h:Rm(+h),d):r},d.y=function(h){return arguments.length?(t=typeof h=="function"?h:Rm(+h),n=null,d):t},d.y0=function(h){return arguments.length?(t=typeof h=="function"?h:Rm(+h),d):t},d.y1=function(h){return arguments.length?(n=h==null?null:typeof h=="function"?h:Rm(+h),d):n},d.lineX0=d.lineY0=function(){return u().x(s).y(t)},d.lineY1=function(){return u().x(s).y(n)},d.lineX1=function(){return u().x(r).y(t)},d.defined=function(h){return arguments.length?(a=typeof h=="function"?h:Rm(!!h),d):a},d.curve=function(h){return arguments.length?(l=h,i!=null&&(o=l(i)),d):l},d.context=function(h){return arguments.length?(h==null?i=o=null:o=l(i=h),d):i},d}class SDt{constructor(t,n){this._context=t,this._x=n}areaStart(){this._line=0}areaEnd(){this._line=NaN}lineStart(){this._point=0}lineEnd(){(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line}point(t,n){switch(t=+t,n=+n,this._point){case 0:{this._point=1,this._line?this._context.lineTo(t,n):this._context.moveTo(t,n);break}case 1:this._point=2;default:{this._x?this._context.bezierCurveTo(this._x0=(this._x0+t)/2,this._y0,this._x0,n,t,n):this._context.bezierCurveTo(this._x0,this._y0=(this._y0+n)/2,t,this._y0,t,n);break}}this._x0=t,this._y0=n}}function RXs(s){return new SDt(s,!0)}function DXs(s){return new SDt(s,!1)}const jYe={draw(s,t){const n=Tk(t/S5e);s.moveTo(n,0),s.arc(0,0,n,0,bEe)}},OXs={draw(s,t){const n=Tk(t/5)/2;s.moveTo(-3*n,-n),s.lineTo(-n,-n),s.lineTo(-n,-3*n),s.lineTo(n,-3*n),s.lineTo(n,-n),s.lineTo(3*n,-n),s.lineTo(3*n,n),s.lineTo(n,n),s.lineTo(n,3*n),s.lineTo(-n,3*n),s.lineTo(-n,n),s.lineTo(-3*n,n),s.closePath()}},CDt=Tk(1/3),FXs=CDt*2,zXs={draw(s,t){const n=Tk(t/FXs),r=n*CDt;s.moveTo(0,-n),s.lineTo(r,0),s.lineTo(0,n),s.lineTo(-r,0),s.closePath()}},BXs={draw(s,t){const n=Tk(t),r=-n/2;s.rect(r,r,n,n)}},$Xs=.8908130915292852,ADt=k5e(S5e/10)/k5e(7*S5e/10),UXs=k5e(bEe/10)*ADt,qXs=-bDt(bEe/10)*ADt,VXs={draw(s,t){const n=Tk(t*$Xs),r=UXs*n,a=qXs*n;s.moveTo(0,-n),s.lineTo(r,a);for(let i=1;i<5;++i){const l=bEe*i/5,o=bDt(l),c=k5e(l);s.lineTo(c*n,-o*n),s.lineTo(o*r-c*a,c*r+o*a)}s.closePath()}},dRe=Tk(3),HXs={draw(s,t){const n=-Tk(t/(dRe*3));s.moveTo(0,n*2),s.lineTo(-dRe*n,-n),s.lineTo(dRe*n,-n),s.closePath()}},Pj=-.5,Ij=Tk(3)/2,yze=1/Tk(12),GXs=(yze/2+1)*3,WXs={draw(s,t){const n=Tk(t/GXs),r=n/2,a=n*yze,i=r,l=n*yze+n,o=-i,c=l;s.moveTo(r,a),s.lineTo(i,l),s.lineTo(o,c),s.lineTo(Pj*r-Ij*a,Ij*r+Pj*a),s.lineTo(Pj*i-Ij*l,Ij*i+Pj*l),s.lineTo(Pj*o-Ij*c,Ij*o+Pj*c),s.lineTo(Pj*r+Ij*a,Pj*a-Ij*r),s.lineTo(Pj*i+Ij*l,Pj*l-Ij*i),s.lineTo(Pj*o+Ij*c,Pj*c-Ij*o),s.closePath()}};function KXs(s,t){let n=null,r=_Ye(a);s=typeof s=="function"?s:Rm(s||jYe),t=typeof t=="function"?t:Rm(t===void 0?64:+t);function a(){let i;if(n||(n=i=r()),s.apply(this,arguments).draw(n,+t.apply(this,arguments)),i)return n=null,i+""||null}return a.type=function(i){return arguments.length?(s=typeof i=="function"?i:Rm(i),a):s},a.size=function(i){return arguments.length?(t=typeof i=="function"?i:Rm(+i),a):t},a.context=function(i){return arguments.length?(n=i??null,a):n},a}function C5e(){}function A5e(s,t,n){s._context.bezierCurveTo((2*s._x0+s._x1)/3,(2*s._y0+s._y1)/3,(s._x0+2*s._x1)/3,(s._y0+2*s._y1)/3,(s._x0+4*s._x1+t)/6,(s._y0+4*s._y1+n)/6)}function EDt(s){this._context=s}EDt.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:A5e(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:A5e(this,s,t);break}this._x0=this._x1,this._x1=s,this._y0=this._y1,this._y1=t}};function YXs(s){return new EDt(s)}function TDt(s){this._context=s}TDt.prototype={areaStart:C5e,areaEnd:C5e,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:A5e(this,s,t);break}this._x0=this._x1,this._x1=s,this._y0=this._y1,this._y1=t}};function ZXs(s){return new TDt(s)}function MDt(s){this._context=s}MDt.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=NaN,this._point=0},lineEnd:function(){(this._line||this._line!==0&&this._point===3)&&this._context.closePath(),this._line=1-this._line},point:function(s,t){switch(s=+s,t=+t,this._point){case 0:this._point=1;break;case 1:this._point=2;break;case 2:this._point=3;var n=(this._x0+4*this._x1+s)/6,r=(this._y0+4*this._y1+t)/6;this._line?this._context.lineTo(n,r):this._context.moveTo(n,r);break;case 3:this._point=4;default:A5e(this,s,t);break}this._x0=this._x1,this._x1=s,this._y0=this._y1,this._y1=t}};function XXs(s){return new MDt(s)}function PDt(s){this._context=s}PDt.prototype={areaStart:C5e,areaEnd:C5e,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 QXs(s){return new PDt(s)}function Lmt(s){return s<0?-1:1}function Rmt(s,t,n){var r=s._x1-s._x0,a=t-s._x1,i=(s._y1-s._y0)/(r||a<0&&-0),l=(n-s._y1)/(a||r<0&&-0),o=(i*a+l*r)/(r+a);return(Lmt(i)+Lmt(l))*Math.min(Math.abs(i),Math.abs(l),.5*Math.abs(o))||0}function Dmt(s,t){var n=s._x1-s._x0;return n?(3*(s._y1-s._y0)/n-t)/2:t}function uRe(s,t,n){var r=s._x0,a=s._y0,i=s._x1,l=s._y1,o=(i-r)/3;s._context.bezierCurveTo(r+o,a+o*t,i-o,l-o*n,i,l)}function E5e(s){this._context=s}E5e.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:uRe(this,this._t0,Dmt(this,this._t0));break}(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line},point:function(s,t){var n=NaN;if(s=+s,t=+t,!(s===this._x1&&t===this._y1)){switch(this._point){case 0:this._point=1,this._line?this._context.lineTo(s,t):this._context.moveTo(s,t);break;case 1:this._point=2;break;case 2:this._point=3,uRe(this,Dmt(this,n=Rmt(this,s,t)),n);break;default:uRe(this,this._t0,n=Rmt(this,s,t));break}this._x0=this._x1,this._x1=s,this._y0=this._y1,this._y1=t,this._t0=n}}};function IDt(s){this._context=new LDt(s)}(IDt.prototype=Object.create(E5e.prototype)).point=function(s,t){E5e.prototype.point.call(this,t,s)};function LDt(s){this._context=s}LDt.prototype={moveTo:function(s,t){this._context.moveTo(t,s)},closePath:function(){this._context.closePath()},lineTo:function(s,t){this._context.lineTo(t,s)},bezierCurveTo:function(s,t,n,r,a,i){this._context.bezierCurveTo(t,s,r,n,i,a)}};function JXs(s){return new E5e(s)}function eQs(s){return new IDt(s)}function RDt(s){this._context=s}RDt.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x=[],this._y=[]},lineEnd:function(){var s=this._x,t=this._y,n=s.length;if(n)if(this._line?this._context.lineTo(s[0],t[0]):this._context.moveTo(s[0],t[0]),n===2)this._context.lineTo(s[1],t[1]);else for(var r=Omt(s),a=Omt(t),i=0,l=1;l=0;--t)a[t]=(l[t]-a[t+1])/i[t];for(i[n-1]=(s[n]+a[n-1])/2,t=0;t=0&&(this._t=1-this._t,this._line=1-this._line)},point:function(s,t){switch(s=+s,t=+t,this._point){case 0:this._point=1,this._line?this._context.lineTo(s,t):this._context.moveTo(s,t);break;case 1:this._point=2;default:{if(this._t<=0)this._context.lineTo(this._x,t),this._context.lineTo(s,t);else{var n=this._x*(1-this._t)+s*this._t;this._context.lineTo(n,this._y),this._context.lineTo(n,t)}break}}this._x=s,this._y=t}};function sQs(s){return new wEe(s,.5)}function nQs(s){return new wEe(s,0)}function rQs(s){return new wEe(s,1)}function RU(s,t){if((l=s.length)>1)for(var n=1,r,a,i=s[t[0]],l,o=i.length;n=0;)n[t]=t;return n}function aQs(s,t){return s[t]}function iQs(s){const t=[];return t.key=s,t}function oQs(){var s=Rm([]),t=vze,n=RU,r=aQs;function a(i){var l=Array.from(s.apply(this,arguments),iQs),o,c=l.length,d=-1,u;for(const h of i)for(o=0,++d;o0){for(var n,r,a=0,i=s[0].length,l;a0){for(var n=0,r=s[t[0]],a,i=r.length;n0)||!((i=(a=s[t[0]]).length)>0))){for(var n=0,r=1,a,i,l;r=0)&&Object.prototype.propertyIsEnumerable.call(s,r)&&(n[r]=s[r])}return n}function gQs(s,t){if(s==null)return{};var n={};for(var r in s)if(Object.prototype.hasOwnProperty.call(s,r)){if(t.indexOf(r)>=0)continue;n[r]=s[r]}return n}var DDt={symbolCircle:jYe,symbolCross:OXs,symbolDiamond:zXs,symbolSquare:BXs,symbolStar:VXs,symbolTriangle:HXs,symbolWye:WXs},xQs=Math.PI/180,yQs=function(t){var n="symbol".concat(vEe(t));return DDt[n]||jYe},vQs=function(t,n,r){if(n==="area")return t;switch(r){case"cross":return 5*t*t/9;case"diamond":return .5*t*t/Math.sqrt(3);case"square":return t*t;case"star":{var a=18*xQs;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}},bQs=function(t,n){DDt["symbol".concat(vEe(t))]=n},NYe=function(t){var n=t.type,r=n===void 0?"circle":n,a=t.size,i=a===void 0?64:a,l=t.sizeType,o=l===void 0?"area":l,c=pQs(t,uQs),d=zmt(zmt({},c),{},{type:r,size:i,sizeType:o}),u=function(){var y=yQs(r),v=KXs().type(y).size(vQs(i,o,r));return v()},h=d.className,m=d.cx,p=d.cy,g=Yo(d,!0);return m===+m&&p===+p&&i===+i?zt.createElement("path",bze({},g,{className:bc("recharts-symbols",h),transform:"translate(".concat(m,", ").concat(p,")"),d:u()})):null};NYe.registerSymbol=bQs;function DU(s){"@babel/helpers - typeof";return DU=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},DU(s)}function _ze(){return _ze=Object.assign?Object.assign.bind():function(s){for(var t=1;t`);var _=p.inactive?d:p.color;return zt.createElement("li",_ze({className:y,style:h,key:"legend-item-".concat(g)},HO(r.props,p,g)),zt.createElement(hze,{width:l,height:l,viewBox:u,style:m},r.renderIcon(p)),zt.createElement("span",{className:"recharts-legend-item-text",style:{color:_}},x?x(v,p,g):v))})}},{key:"render",value:function(){var r=this.props,a=r.payload,i=r.layout,l=r.align;if(!a||!a.length)return null;var o={padding:0,margin:0,textAlign:i==="horizontal"?l:"left"};return zt.createElement("ul",{className:"recharts-default-legend",style:o},this.renderItems())}}])}(k.PureComponent);kX(kYe,"displayName","Legend");kX(kYe,"defaultProps",{iconSize:14,layout:"horizontal",align:"center",verticalAlign:"middle",inactiveColor:"#ccc"});var TQs=iEe;function MQs(){this.__data__=new TQs,this.size=0}var PQs=MQs;function IQs(s){var t=this.__data__,n=t.delete(s);return this.size=t.size,n}var LQs=IQs;function RQs(s){return this.__data__.get(s)}var DQs=RQs;function OQs(s){return this.__data__.has(s)}var FQs=OQs,zQs=iEe,BQs=hYe,$Qs=mYe,UQs=200;function qQs(s,t){var n=this.__data__;if(n instanceof zQs){var r=n.__data__;if(!BQs||r.lengtho))return!1;var d=i.get(s),u=i.get(t);if(d&&u)return d==t&&u==s;var h=-1,m=!0,p=n&uJs?new oJs:void 0;for(i.set(s,t),i.set(t,s);++h-1&&s%1==0&&s-1&&s%1==0&&s<=pen}var EYe=gen,xen=uA,yen=EYe,ven=hA,ben="[object Arguments]",_en="[object Array]",wen="[object Boolean]",jen="[object Date]",Nen="[object Error]",ken="[object Function]",Sen="[object Map]",Cen="[object Number]",Aen="[object Object]",Een="[object RegExp]",Ten="[object Set]",Men="[object String]",Pen="[object WeakMap]",Ien="[object ArrayBuffer]",Len="[object DataView]",Ren="[object Float32Array]",Den="[object Float64Array]",Oen="[object Int8Array]",Fen="[object Int16Array]",zen="[object Int32Array]",Ben="[object Uint8Array]",$en="[object Uint8ClampedArray]",Uen="[object Uint16Array]",qen="[object Uint32Array]",pf={};pf[Ren]=pf[Den]=pf[Oen]=pf[Fen]=pf[zen]=pf[Ben]=pf[$en]=pf[Uen]=pf[qen]=!0;pf[ben]=pf[_en]=pf[Ien]=pf[wen]=pf[Len]=pf[jen]=pf[Nen]=pf[ken]=pf[Sen]=pf[Cen]=pf[Aen]=pf[Een]=pf[Ten]=pf[Men]=pf[Pen]=!1;function Ven(s){return ven(s)&¥(s.length)&&!!pf[xen(s)]}var Hen=Ven;function Gen(s){return function(t){return s(t)}}var WDt=Gen,I5e={exports:{}};I5e.exports;(function(s,t){var n=eDt,r=t&&!t.nodeType&&t,a=r&&!0&&s&&!s.nodeType&&s,i=a&&a.exports===r,l=i&&n.process,o=function(){try{var c=a&&a.require&&a.require("util").types;return c||l&&l.binding&&l.binding("util")}catch{}}();s.exports=o})(I5e,I5e.exports);var Wen=I5e.exports,Ken=Hen,Yen=WDt,Gmt=Wen,Wmt=Gmt&&Gmt.isTypedArray,Zen=Wmt?Yen(Wmt):Ken,KDt=Zen,Xen=een,Qen=CYe,Jen=B_,etn=GDt,ttn=AYe,stn=KDt,ntn=Object.prototype,rtn=ntn.hasOwnProperty;function atn(s,t){var n=Jen(s),r=!n&&Qen(s),a=!n&&!r&&etn(s),i=!n&&!r&&!a&&stn(s),l=n||r||a||i,o=l?Xen(s.length,String):[],c=o.length;for(var d in s)(t||rtn.call(s,d))&&!(l&&(d=="length"||a&&(d=="offset"||d=="parent")||i&&(d=="buffer"||d=="byteLength"||d=="byteOffset")||ttn(d,c)))&&o.push(d);return o}var itn=atn,otn=Object.prototype;function ltn(s){var t=s&&s.constructor,n=typeof t=="function"&&t.prototype||otn;return s===n}var ctn=ltn;function dtn(s,t){return function(n){return s(t(n))}}var YDt=dtn,utn=YDt,htn=utn(Object.keys,Object),mtn=htn,ftn=ctn,ptn=mtn,gtn=Object.prototype,xtn=gtn.hasOwnProperty;function ytn(s){if(!ftn(s))return ptn(s);var t=[];for(var n in Object(s))xtn.call(s,n)&&n!="constructor"&&t.push(n);return t}var vtn=ytn,btn=dYe,_tn=EYe;function wtn(s){return s!=null&&_tn(s.length)&&!btn(s)}var Yee=wtn,jtn=itn,Ntn=vtn,ktn=Yee;function Stn(s){return ktn(s)?jtn(s):Ntn(s)}var jEe=Stn,Ctn=UJs,Atn=QJs,Etn=jEe;function Ttn(s){return Ctn(s,Etn,Atn)}var Mtn=Ttn,Kmt=Mtn,Ptn=1,Itn=Object.prototype,Ltn=Itn.hasOwnProperty;function Rtn(s,t,n,r,a,i){var l=n&Ptn,o=Kmt(s),c=o.length,d=Kmt(t),u=d.length;if(c!=u&&!l)return!1;for(var h=c;h--;){var m=o[h];if(!(l?m in t:Ltn.call(t,m)))return!1}var p=i.get(s),g=i.get(t);if(p&&g)return p==t&&g==s;var x=!0;i.set(s,t),i.set(t,s);for(var y=l;++h-1}var Inn=Pnn;function Lnn(s,t,n){for(var r=-1,a=s==null?0:s.length;++r=Ynn){var d=t?null:Wnn(s);if(d)return Knn(d);l=!1,a=Gnn,c=new qnn}else c=t?[]:o;e:for(;++r=0)&&Object.prototype.propertyIsEnumerable.call(s,r)&&(n[r]=s[r])}return n}function urn(s,t){if(s==null)return{};var n={};for(var r in s)if(Object.prototype.hasOwnProperty.call(s,r)){if(t.indexOf(r)>=0)continue;n[r]=s[r]}return n}function hrn(s){return s.value}function mrn(s,t){if(zt.isValidElement(s))return zt.cloneElement(s,t);if(typeof s=="function")return zt.createElement(s,t);t.ref;var n=drn(t,srn);return zt.createElement(kYe,n)}var dft=1,lO=function(s){function t(){var n;nrn(this,t);for(var r=arguments.length,a=new Array(r),i=0;idft||Math.abs(a.height-this.lastBoundingBox.height)>dft)&&(this.lastBoundingBox.width=a.width,this.lastBoundingBox.height=a.height,r&&r(a)):(this.lastBoundingBox.width!==-1||this.lastBoundingBox.height!==-1)&&(this.lastBoundingBox.width=-1,this.lastBoundingBox.height=-1,r&&r(null))}},{key:"getBBoxSnapshot",value:function(){return this.lastBoundingBox.width>=0&&this.lastBoundingBox.height>=0?Z4({},this.lastBoundingBox):{width:0,height:0}}},{key:"getDefaultPosition",value:function(r){var a=this.props,i=a.layout,l=a.align,o=a.verticalAlign,c=a.margin,d=a.chartWidth,u=a.chartHeight,h,m;if(!r||(r.left===void 0||r.left===null)&&(r.right===void 0||r.right===null))if(l==="center"&&i==="vertical"){var p=this.getBBoxSnapshot();h={left:((d||0)-p.width)/2}}else h=l==="right"?{right:c&&c.right||0}:{left:c&&c.left||0};if(!r||(r.top===void 0||r.top===null)&&(r.bottom===void 0||r.bottom===null))if(o==="middle"){var g=this.getBBoxSnapshot();m={top:((u||0)-g.height)/2}}else m=o==="bottom"?{bottom:c&&c.bottom||0}:{top:c&&c.top||0};return Z4(Z4({},h),m)}},{key:"render",value:function(){var r=this,a=this.props,i=a.content,l=a.width,o=a.height,c=a.wrapperStyle,d=a.payloadUniqBy,u=a.payload,h=Z4(Z4({position:"absolute",width:l||"auto",height:o||"auto"},this.getDefaultPosition(c)),c);return zt.createElement("div",{className:"recharts-legend-wrapper",style:h,ref:function(p){r.wrapperNode=p}},mrn(i,Z4(Z4({},this.props),{},{payload:s8t(u,d,hrn)})))}}],[{key:"getWithHeight",value:function(r,a){var i=Z4(Z4({},this.defaultProps),r.props),l=i.layout;return l==="vertical"&&Ha(r.props.height)?{height:r.props.height}:l==="horizontal"?{width:r.props.width||a}:null}}])}(k.PureComponent);NEe(lO,"displayName","Legend");NEe(lO,"defaultProps",{iconSize:14,layout:"horizontal",align:"center",verticalAlign:"bottom"});var uft=Kee,frn=CYe,prn=B_,hft=uft?uft.isConcatSpreadable:void 0;function grn(s){return prn(s)||frn(s)||!!(hft&&s&&s[hft])}var xrn=grn,yrn=VDt,vrn=xrn;function a8t(s,t,n,r,a){var i=-1,l=s.length;for(n||(n=vrn),a||(a=[]);++i0&&n(o)?t>1?a8t(o,t-1,n,r,a):yrn(a,o):r||(a[a.length]=o)}return a}var i8t=a8t;function brn(s){return function(t,n,r){for(var a=-1,i=Object(t),l=r(t),o=l.length;o--;){var c=l[s?o:++a];if(n(i[c],c,i)===!1)break}return t}}var _rn=brn,wrn=_rn,jrn=wrn(),Nrn=jrn,krn=Nrn,Srn=jEe;function Crn(s,t){return s&&krn(s,t,Srn)}var o8t=Crn,Arn=Yee;function Ern(s,t){return function(n,r){if(n==null)return n;if(!Arn(n))return s(n,r);for(var a=n.length,i=t?a:-1,l=Object(n);(t?i--:++it||i&&l&&c&&!o&&!d||r&&l&&c||!n&&c||!a)return 1;if(!r&&!i&&!d&&s=o)return c;var d=n[r];return c*(d=="desc"?-1:1)}}return s.index-t.index}var qrn=Urn,pRe=pYe,Vrn=gYe,Hrn=i4,Grn=l8t,Wrn=Frn,Krn=WDt,Yrn=qrn,Zrn=yV,Xrn=B_;function Qrn(s,t,n){t.length?t=pRe(t,function(i){return Xrn(i)?function(l){return Vrn(l,i.length===1?i[0]:i)}:i}):t=[Zrn];var r=-1;t=pRe(t,Krn(Hrn));var a=Grn(s,function(i,l,o){var c=pRe(t,function(d){return d(i)});return{criteria:c,index:++r,value:i}});return Wrn(a,function(i,l){return Yrn(i,l,n)})}var Jrn=Qrn;function ean(s,t,n){switch(n.length){case 0:return s.call(t);case 1:return s.call(t,n[0]);case 2:return s.call(t,n[0],n[1]);case 3:return s.call(t,n[0],n[1],n[2])}return s.apply(t,n)}var tan=ean,san=tan,fft=Math.max;function nan(s,t,n){return t=fft(t===void 0?s.length-1:t,0),function(){for(var r=arguments,a=-1,i=fft(r.length-t,0),l=Array(i);++a0){if(++t>=man)return arguments[0]}else t=0;return s.apply(void 0,arguments)}}var xan=gan,yan=han,van=xan,ban=van(yan),_an=ban,wan=yV,jan=ran,Nan=_an;function kan(s,t){return Nan(jan(s,t,wan),s+"")}var San=kan,Can=uYe,Aan=Yee,Ean=AYe,Tan=m6;function Man(s,t,n){if(!Tan(n))return!1;var r=typeof t;return(r=="number"?Aan(n)&&Ean(t,n.length):r=="string"&&t in n)?Can(n[t],s):!1}var kEe=Man,Pan=i8t,Ian=Jrn,Lan=San,gft=kEe,Ran=Lan(function(s,t){if(s==null)return[];var n=t.length;return n>1&&gft(s,t[0],t[1])?t=[]:n>2&&gft(t[0],t[1],t[2])&&(t=[t[0]]),Ian(s,Pan(t,1),[])}),Dan=Ran;const PYe=kd(Dan);function SX(s){"@babel/helpers - typeof";return SX=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},SX(s)}function Eze(){return Eze=Object.assign?Object.assign.bind():function(s){for(var t=1;ts.length)&&(t=s.length);for(var n=0,r=new Array(t);n=t.x),"".concat(jG,"-left"),Ha(n)&&t&&Ha(t.x)&&n=t.y),"".concat(jG,"-top"),Ha(r)&&t&&Ha(t.y)&&rx?Math.max(u,c[r]):Math.max(h,c[r])}function Xan(s){var t=s.translateX,n=s.translateY,r=s.useTranslate3d;return{transform:r?"translate3d(".concat(t,"px, ").concat(n,"px, 0)"):"translate(".concat(t,"px, ").concat(n,"px)")}}function Qan(s){var t=s.allowEscapeViewBox,n=s.coordinate,r=s.offsetTopLeft,a=s.position,i=s.reverseDirection,l=s.tooltipBox,o=s.useTranslate3d,c=s.viewBox,d,u,h;return l.height>0&&l.width>0&&n?(u=vft({allowEscapeViewBox:t,coordinate:n,key:"x",offsetTopLeft:r,position:a,reverseDirection:i,tooltipDimension:l.width,viewBox:c,viewBoxDimension:c.width}),h=vft({allowEscapeViewBox:t,coordinate:n,key:"y",offsetTopLeft:r,position:a,reverseDirection:i,tooltipDimension:l.height,viewBox:c,viewBoxDimension:c.height}),d=Xan({translateX:u,translateY:h,useTranslate3d:o})):d=Yan,{cssProperties:d,cssClasses:Zan({translateX:u,translateY:h,coordinate:n})}}function FU(s){"@babel/helpers - typeof";return FU=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},FU(s)}function bft(s,t){var n=Object.keys(s);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(s);t&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(s,a).enumerable})),n.push.apply(n,r)}return n}function _ft(s){for(var t=1;twft||Math.abs(r.height-this.state.lastBoundingBox.height)>wft)&&this.setState({lastBoundingBox:{width:r.width,height:r.height}})}else(this.state.lastBoundingBox.width!==-1||this.state.lastBoundingBox.height!==-1)&&this.setState({lastBoundingBox:{width:-1,height:-1}})}},{key:"componentDidMount",value:function(){document.addEventListener("keydown",this.handleKeyDown),this.updateBBox()}},{key:"componentWillUnmount",value:function(){document.removeEventListener("keydown",this.handleKeyDown)}},{key:"componentDidUpdate",value:function(){var r,a;this.props.active&&this.updateBBox(),this.state.dismissed&&(((r=this.props.coordinate)===null||r===void 0?void 0:r.x)!==this.state.dismissedAtCoordinate.x||((a=this.props.coordinate)===null||a===void 0?void 0:a.y)!==this.state.dismissedAtCoordinate.y)&&(this.state.dismissed=!1)}},{key:"render",value:function(){var r=this,a=this.props,i=a.active,l=a.allowEscapeViewBox,o=a.animationDuration,c=a.animationEasing,d=a.children,u=a.coordinate,h=a.hasPayload,m=a.isAnimationActive,p=a.offset,g=a.position,x=a.reverseDirection,y=a.useTranslate3d,v=a.viewBox,_=a.wrapperStyle,j=Qan({allowEscapeViewBox:l,coordinate:u,offsetTopLeft:p,position:g,reverseDirection:x,tooltipBox:this.state.lastBoundingBox,useTranslate3d:y,viewBox:v}),C=j.cssClasses,A=j.cssProperties,M=_ft(_ft({transition:m&&i?"transform ".concat(o,"ms ").concat(c):void 0},A),{},{pointerEvents:"none",visibility:!this.state.dismissed&&i&&h?"visible":"hidden",position:"absolute",top:0,left:0},_);return zt.createElement("div",{tabIndex:-1,className:C,style:M,ref:function(P){r.wrapperNode=P}},d)}}])}(k.PureComponent),lin=function(){return!(typeof window<"u"&&window.document&&window.document.createElement&&window.setTimeout)},f6={isSsr:lin()};function zU(s){"@babel/helpers - typeof";return zU=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},zU(s)}function jft(s,t){var n=Object.keys(s);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(s);t&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(s,a).enumerable})),n.push.apply(n,r)}return n}function Nft(s){for(var t=1;t0;return zt.createElement(oin,{allowEscapeViewBox:l,animationDuration:o,animationEasing:c,isAnimationActive:m,active:i,coordinate:u,hasPayload:M,offset:p,position:y,reverseDirection:v,useTranslate3d:_,viewBox:j,wrapperStyle:C},yin(d,Nft(Nft({},this.props),{},{payload:A})))}}])}(k.PureComponent);IYe(vg,"displayName","Tooltip");IYe(vg,"defaultProps",{accessibilityLayer:!1,allowEscapeViewBox:{x:!1,y:!1},animationDuration:400,animationEasing:"ease",contentStyle:{},coordinate:{x:0,y:0},cursor:!0,cursorStyle:{},filterNull:!0,isAnimationActive:!f6.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 vin=a4,bin=function(){return vin.Date.now()},_in=bin,win=/\s/;function jin(s){for(var t=s.length;t--&&win.test(s.charAt(t)););return t}var Nin=jin,kin=Nin,Sin=/^\s+/;function Cin(s){return s&&s.slice(0,kin(s)+1).replace(Sin,"")}var Ain=Cin,Ein=Ain,kft=m6,Tin=dV,Sft=NaN,Min=/^[-+]0x[0-9a-f]+$/i,Pin=/^0b[01]+$/i,Iin=/^0o[0-7]+$/i,Lin=parseInt;function Rin(s){if(typeof s=="number")return s;if(Tin(s))return Sft;if(kft(s)){var t=typeof s.valueOf=="function"?s.valueOf():s;s=kft(t)?t+"":t}if(typeof s!="string")return s===0?s:+s;s=Ein(s);var n=Pin.test(s);return n||Iin.test(s)?Lin(s.slice(2),n?2:8):Min.test(s)?Sft:+s}var f8t=Rin,Din=m6,xRe=_in,Cft=f8t,Oin="Expected a function",Fin=Math.max,zin=Math.min;function Bin(s,t,n){var r,a,i,l,o,c,d=0,u=!1,h=!1,m=!0;if(typeof s!="function")throw new TypeError(Oin);t=Cft(t)||0,Din(n)&&(u=!!n.leading,h="maxWait"in n,i=h?Fin(Cft(n.maxWait)||0,t):i,m="trailing"in n?!!n.trailing:m);function p(M){var I=r,P=a;return r=a=void 0,d=M,l=s.apply(P,I),l}function g(M){return d=M,o=setTimeout(v,t),u?p(M):l}function x(M){var I=M-c,P=M-d,R=t-I;return h?zin(R,i-P):R}function y(M){var I=M-c,P=M-d;return c===void 0||I>=t||I<0||h&&P>=i}function v(){var M=xRe();if(y(M))return _(M);o=setTimeout(v,x(M))}function _(M){return o=void 0,m&&r?p(M):(r=a=void 0,l)}function j(){o!==void 0&&clearTimeout(o),d=0,r=c=a=o=void 0}function C(){return o===void 0?l:_(xRe())}function A(){var M=xRe(),I=y(M);if(r=arguments,a=this,c=M,I){if(o===void 0)return g(c);if(h)return clearTimeout(o),o=setTimeout(v,t),p(c)}return o===void 0&&(o=setTimeout(v,t)),l}return A.cancel=j,A.flush=C,A}var $in=Bin,Uin=$in,qin=m6,Vin="Expected a function";function Hin(s,t,n){var r=!0,a=!0;if(typeof s!="function")throw new TypeError(Vin);return qin(n)&&(r="leading"in n?!!n.leading:r,a="trailing"in n?!!n.trailing:a),Uin(s,t,{leading:r,maxWait:t,trailing:a})}var Gin=Hin;const p8t=kd(Gin);function AX(s){"@babel/helpers - typeof";return AX=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},AX(s)}function Aft(s,t){var n=Object.keys(s);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(s);t&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(s,a).enumerable})),n.push.apply(n,r)}return n}function sae(s){for(var t=1;ts.length)&&(t=s.length);for(var n=0,r=new Array(t);n0&&(G=p8t(G,x,{trailing:!0,leading:!1}));var H=new ResizeObserver(G),Y=A.current.getBoundingClientRect(),se=Y.width,ee=Y.height;return B(se,ee),H.observe(A.current),function(){H.disconnect()}},[B,x]);var U=k.useMemo(function(){var G=R.containerWidth,H=R.containerHeight;if(G<0||H<0)return null;mk(mD(l)||mD(c),`The width(%s) and height(%s) are both fixed numbers, maybe you don't need to use a ResponsiveContainer.`,l,c),mk(!n||n>0,"The aspect(%s) must be greater than zero.",n);var Y=mD(l)?G:l,se=mD(c)?H:c;n&&n>0&&(Y?se=Y/n:se&&(Y=se*n),m&&se>m&&(se=m)),mk(Y>0||se>0,`The width(%s) and height(%s) of chart should be greater than 0, please check the style of container, or the props width(%s) and height(%s), or add a minWidth(%s) or minHeight(%s) or use aspect(%s) to control the height and width.`,Y,se,l,c,u,h,n);var ee=!Array.isArray(p)&&C3(p.type).endsWith("Chart");return zt.Children.map(p,function(oe){return zt.isValidElement(oe)?k.cloneElement(oe,sae({width:Y,height:se},ee?{style:sae({height:"100%",width:"100%",maxHeight:se,maxWidth:Y},oe.props.style)}:{})):oe})},[n,p,c,m,h,u,R,l]);return zt.createElement("div",{id:y?"".concat(y):void 0,className:bc("recharts-responsive-container",v),style:sae(sae({},C),{},{width:l,height:c,minWidth:u,minHeight:h,maxHeight:m}),ref:A},U)}),vV=function(t){return null};vV.displayName="Cell";function EX(s){"@babel/helpers - typeof";return EX=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},EX(s)}function Tft(s,t){var n=Object.keys(s);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(s);t&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(s,a).enumerable})),n.push.apply(n,r)}return n}function Ize(s){for(var t=1;t1&&arguments[1]!==void 0?arguments[1]:{};if(t==null||f6.isSsr)return{width:0,height:0};var r=ion(n),a=JSON.stringify({text:t,copyStyle:r});if(n9.widthCache[a])return n9.widthCache[a];try{var i=document.getElementById(Mft);i||(i=document.createElement("span"),i.setAttribute("id",Mft),i.setAttribute("aria-hidden","true"),document.body.appendChild(i));var l=Ize(Ize({},aon),r);Object.assign(i.style,l),i.textContent="".concat(t);var o=i.getBoundingClientRect(),c={width:o.width,height:o.height};return n9.widthCache[a]=c,++n9.cacheCount>ron&&(n9.cacheCount=0,n9.widthCache={}),c}catch{return{width:0,height:0}}},oon=function(t){return{top:t.top+window.scrollY-document.documentElement.clientTop,left:t.left+window.scrollX-document.documentElement.clientLeft}};function TX(s){"@babel/helpers - typeof";return TX=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},TX(s)}function O5e(s,t){return uon(s)||don(s,t)||con(s,t)||lon()}function lon(){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 con(s,t){if(s){if(typeof s=="string")return Pft(s,t);var n=Object.prototype.toString.call(s).slice(8,-1);if(n==="Object"&&s.constructor&&(n=s.constructor.name),n==="Map"||n==="Set")return Array.from(s);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return Pft(s,t)}}function Pft(s,t){(t==null||t>s.length)&&(t=s.length);for(var n=0,r=new Array(t);n=0)&&Object.prototype.propertyIsEnumerable.call(s,r)&&(n[r]=s[r])}return n}function kon(s,t){if(s==null)return{};var n={};for(var r in s)if(Object.prototype.hasOwnProperty.call(s,r)){if(t.indexOf(r)>=0)continue;n[r]=s[r]}return n}function Fft(s,t){return Eon(s)||Aon(s,t)||Con(s,t)||Son()}function Son(){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 Con(s,t){if(s){if(typeof s=="string")return zft(s,t);var n=Object.prototype.toString.call(s).slice(8,-1);if(n==="Object"&&s.constructor&&(n=s.constructor.name),n==="Map"||n==="Set")return Array.from(s);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return zft(s,t)}}function zft(s,t){(t==null||t>s.length)&&(t=s.length);for(var n=0,r=new Array(t);n0&&arguments[0]!==void 0?arguments[0]:[];return Y.reduce(function(se,ee){var oe=ee.word,me=ee.width,Q=se[se.length-1];if(Q&&(a==null||i||Q.width+me+ree.width?se:ee})};if(!u)return p;for(var x="…",y=function(Y){var se=h.slice(0,Y),ee=v8t({breakAll:d,style:c,children:se+x}).wordsWithComputedWidth,oe=m(ee),me=oe.length>l||g(oe).width>Number(a);return[me,oe]},v=0,_=h.length-1,j=0,C;v<=_&&j<=h.length-1;){var A=Math.floor((v+_)/2),M=A-1,I=y(M),P=Fft(I,2),R=P[0],O=P[1],B=y(A),U=Fft(B,1),G=U[0];if(!R&&!G&&(v=A+1),R&&G&&(_=A-1),!R&&G){C=O;break}j++}return C||p},Bft=function(t){var n=hc(t)?[]:t.toString().split(y8t);return[{words:n}]},Mon=function(t){var n=t.width,r=t.scaleToFit,a=t.children,i=t.style,l=t.breakAll,o=t.maxLines;if((n||r)&&!f6.isSsr){var c,d,u=v8t({breakAll:l,children:a,style:i});if(u){var h=u.wordsWithComputedWidth,m=u.spaceWidth;c=h,d=m}else return Bft(a);return Ton({breakAll:l,children:a,maxLines:o,style:i},c,d,n,r)}return Bft(a)},$ft="#808080",GO=function(t){var n=t.x,r=n===void 0?0:n,a=t.y,i=a===void 0?0:a,l=t.lineHeight,o=l===void 0?"1em":l,c=t.capHeight,d=c===void 0?"0.71em":c,u=t.scaleToFit,h=u===void 0?!1:u,m=t.textAnchor,p=m===void 0?"start":m,g=t.verticalAnchor,x=g===void 0?"end":g,y=t.fill,v=y===void 0?$ft:y,_=Oft(t,jon),j=k.useMemo(function(){return Mon({breakAll:_.breakAll,children:_.children,maxLines:_.maxLines,scaleToFit:h,style:_.style,width:_.width})},[_.breakAll,_.children,_.maxLines,h,_.style,_.width]),C=_.dx,A=_.dy,M=_.angle,I=_.className,P=_.breakAll,R=Oft(_,Non);if(!by(r)||!by(i))return null;var O=r+(Ha(C)?C:0),B=i+(Ha(A)?A:0),U;switch(x){case"start":U=yRe("calc(".concat(d,")"));break;case"middle":U=yRe("calc(".concat((j.length-1)/2," * -").concat(o," + (").concat(d," / 2))"));break;default:U=yRe("calc(".concat(j.length-1," * -").concat(o,")"));break}var G=[];if(h){var H=j[0].width,Y=_.width;G.push("scale(".concat((Ha(Y)?Y/H:1)/H,")"))}return M&&G.push("rotate(".concat(M,", ").concat(O,", ").concat(B,")")),G.length&&(R.transform=G.join(" ")),zt.createElement("text",Lze({},Yo(R,!0),{x:O,y:B,className:bc("recharts-text",I),textAnchor:p,fill:v.includes("url")?$ft:v}),j.map(function(se,ee){var oe=se.words.join(P?"":" ");return zt.createElement("tspan",{x:O,dy:ee===0?U:o,key:"".concat(oe,"-").concat(ee)},oe)}))};function pM(s,t){return s==null||t==null?NaN:st?1:s>=t?0:NaN}function Pon(s,t){return s==null||t==null?NaN:ts?1:t>=s?0:NaN}function LYe(s){let t,n,r;s.length!==2?(t=pM,n=(o,c)=>pM(s(o),c),r=(o,c)=>s(o)-c):(t=s===pM||s===Pon?s:Ion,n=s,r=s);function a(o,c,d=0,u=o.length){if(d>>1;n(o[h],c)<0?d=h+1:u=h}while(d>>1;n(o[h],c)<=0?d=h+1:u=h}while(dd&&r(o[h-1],c)>-r(o[h],c)?h-1:h}return{left:a,center:l,right:i}}function Ion(){return 0}function b8t(s){return s===null?NaN:+s}function*Lon(s,t){for(let n of s)n!=null&&(n=+n)>=n&&(yield n)}const Ron=LYe(pM),Zee=Ron.right;LYe(b8t).center;class Uft extends Map{constructor(t,n=Fon){if(super(),Object.defineProperties(this,{_intern:{value:new Map},_key:{value:n}}),t!=null)for(const[r,a]of t)this.set(r,a)}get(t){return super.get(qft(this,t))}has(t){return super.has(qft(this,t))}set(t,n){return super.set(Don(this,t),n)}delete(t){return super.delete(Oon(this,t))}}function qft({_intern:s,_key:t},n){const r=t(n);return s.has(r)?s.get(r):n}function Don({_intern:s,_key:t},n){const r=t(n);return s.has(r)?s.get(r):(s.set(r,n),n)}function Oon({_intern:s,_key:t},n){const r=t(n);return s.has(r)&&(n=s.get(r),s.delete(r)),n}function Fon(s){return s!==null&&typeof s=="object"?s.valueOf():s}function zon(s=pM){if(s===pM)return _8t;if(typeof s!="function")throw new TypeError("compare is not a function");return(t,n)=>{const r=s(t,n);return r||r===0?r:(s(n,n)===0)-(s(t,t)===0)}}function _8t(s,t){return(s==null||!(s>=s))-(t==null||!(t>=t))||(st?1:0)}const Bon=Math.sqrt(50),$on=Math.sqrt(10),Uon=Math.sqrt(2);function F5e(s,t,n){const r=(t-s)/Math.max(0,n),a=Math.floor(Math.log10(r)),i=r/Math.pow(10,a),l=i>=Bon?10:i>=$on?5:i>=Uon?2:1;let o,c,d;return a<0?(d=Math.pow(10,-a)/l,o=Math.round(s*d),c=Math.round(t*d),o/dt&&--c,d=-d):(d=Math.pow(10,a)*l,o=Math.round(s/d),c=Math.round(t/d),o*dt&&--c),c0))return[];if(s===t)return[s];const r=t=a))return[];const o=i-a+1,c=new Array(o);if(r)if(l<0)for(let d=0;d=r)&&(n=r);return n}function Hft(s,t){let n;for(const r of s)r!=null&&(n>r||n===void 0&&r>=r)&&(n=r);return n}function w8t(s,t,n=0,r=1/0,a){if(t=Math.floor(t),n=Math.floor(Math.max(0,n)),r=Math.floor(Math.min(s.length-1,r)),!(n<=t&&t<=r))return s;for(a=a===void 0?_8t:zon(a);r>n;){if(r-n>600){const c=r-n+1,d=t-n+1,u=Math.log(c),h=.5*Math.exp(2*u/3),m=.5*Math.sqrt(u*h*(c-h)/c)*(d-c/2<0?-1:1),p=Math.max(n,Math.floor(t-d*h/c+m)),g=Math.min(r,Math.floor(t+(c-d)*h/c+m));w8t(s,t,p,g,a)}const i=s[t];let l=n,o=r;for(NG(s,n,t),a(s[r],i)>0&&NG(s,n,r);l0;)--o}a(s[n],i)===0?NG(s,n,o):(++o,NG(s,o,r)),o<=t&&(n=o+1),t<=o&&(r=o-1)}return s}function NG(s,t,n){const r=s[t];s[t]=s[n],s[n]=r}function qon(s,t,n){if(s=Float64Array.from(Lon(s)),!(!(r=s.length)||isNaN(t=+t))){if(t<=0||r<2)return Hft(s);if(t>=1)return Vft(s);var r,a=(r-1)*t,i=Math.floor(a),l=Vft(w8t(s,i).subarray(0,i+1)),o=Hft(s.subarray(i+1));return l+(o-l)*(a-i)}}function Von(s,t,n=b8t){if(!(!(r=s.length)||isNaN(t=+t))){if(t<=0||r<2)return+n(s[0],0,s);if(t>=1)return+n(s[r-1],r-1,s);var r,a=(r-1)*t,i=Math.floor(a),l=+n(s[i],i,s),o=+n(s[i+1],i+1,s);return l+(o-l)*(a-i)}}function Hon(s,t,n){s=+s,t=+t,n=(a=arguments.length)<2?(t=s,s=0,1):a<3?1:+n;for(var r=-1,a=Math.max(0,Math.ceil((t-s)/n))|0,i=new Array(a);++r>8&15|t>>4&240,t>>4&15|t&240,(t&15)<<4|t&15,1):n===8?rae(t>>24&255,t>>16&255,t>>8&255,(t&255)/255):n===4?rae(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=Won.exec(s))?new f_(t[1],t[2],t[3],1):(t=Kon.exec(s))?new f_(t[1]*255/100,t[2]*255/100,t[3]*255/100,1):(t=Yon.exec(s))?rae(t[1],t[2],t[3],t[4]):(t=Zon.exec(s))?rae(t[1]*255/100,t[2]*255/100,t[3]*255/100,t[4]):(t=Xon.exec(s))?Qft(t[1],t[2]/100,t[3]/100,1):(t=Qon.exec(s))?Qft(t[1],t[2]/100,t[3]/100,t[4]):Gft.hasOwnProperty(s)?Yft(Gft[s]):s==="transparent"?new f_(NaN,NaN,NaN,0):null}function Yft(s){return new f_(s>>16&255,s>>8&255,s&255,1)}function rae(s,t,n,r){return r<=0&&(s=t=n=NaN),new f_(s,t,n,r)}function tln(s){return s instanceof Xee||(s=LX(s)),s?(s=s.rgb(),new f_(s.r,s.g,s.b,s.opacity)):new f_}function zze(s,t,n,r){return arguments.length===1?tln(s):new f_(s,t,n,r??1)}function f_(s,t,n,r){this.r=+s,this.g=+t,this.b=+n,this.opacity=+r}DYe(f_,zze,N8t(Xee,{brighter(s){return s=s==null?z5e:Math.pow(z5e,s),new f_(this.r*s,this.g*s,this.b*s,this.opacity)},darker(s){return s=s==null?PX:Math.pow(PX,s),new f_(this.r*s,this.g*s,this.b*s,this.opacity)},rgb(){return this},clamp(){return new f_(cO(this.r),cO(this.g),cO(this.b),B5e(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:Zft,formatHex:Zft,formatHex8:sln,formatRgb:Xft,toString:Xft}));function Zft(){return`#${fD(this.r)}${fD(this.g)}${fD(this.b)}`}function sln(){return`#${fD(this.r)}${fD(this.g)}${fD(this.b)}${fD((isNaN(this.opacity)?1:this.opacity)*255)}`}function Xft(){const s=B5e(this.opacity);return`${s===1?"rgb(":"rgba("}${cO(this.r)}, ${cO(this.g)}, ${cO(this.b)}${s===1?")":`, ${s})`}`}function B5e(s){return isNaN(s)?1:Math.max(0,Math.min(1,s))}function cO(s){return Math.max(0,Math.min(255,Math.round(s)||0))}function fD(s){return s=cO(s),(s<16?"0":"")+s.toString(16)}function Qft(s,t,n,r){return r<=0?s=t=n=NaN:n<=0||n>=1?s=t=NaN:t<=0&&(s=NaN),new XN(s,t,n,r)}function k8t(s){if(s instanceof XN)return new XN(s.h,s.s,s.l,s.opacity);if(s instanceof Xee||(s=LX(s)),!s)return new XN;if(s instanceof XN)return s;s=s.rgb();var t=s.r/255,n=s.g/255,r=s.b/255,a=Math.min(t,n,r),i=Math.max(t,n,r),l=NaN,o=i-a,c=(i+a)/2;return o?(t===i?l=(n-r)/o+(n0&&c<1?0:l,new XN(l,o,c,s.opacity)}function nln(s,t,n,r){return arguments.length===1?k8t(s):new XN(s,t,n,r??1)}function XN(s,t,n,r){this.h=+s,this.s=+t,this.l=+n,this.opacity=+r}DYe(XN,nln,N8t(Xee,{brighter(s){return s=s==null?z5e:Math.pow(z5e,s),new XN(this.h,this.s,this.l*s,this.opacity)},darker(s){return s=s==null?PX:Math.pow(PX,s),new XN(this.h,this.s,this.l*s,this.opacity)},rgb(){var s=this.h%360+(this.h<0)*360,t=isNaN(s)||isNaN(this.s)?0:this.s,n=this.l,r=n+(n<.5?n:1-n)*t,a=2*n-r;return new f_(vRe(s>=240?s-240:s+120,a,r),vRe(s,a,r),vRe(s<120?s+240:s-120,a,r),this.opacity)},clamp(){return new XN(Jft(this.h),aae(this.s),aae(this.l),B5e(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=B5e(this.opacity);return`${s===1?"hsl(":"hsla("}${Jft(this.h)}, ${aae(this.s)*100}%, ${aae(this.l)*100}%${s===1?")":`, ${s})`}`}}));function Jft(s){return s=(s||0)%360,s<0?s+360:s}function aae(s){return Math.max(0,Math.min(1,s||0))}function vRe(s,t,n){return(s<60?t+(n-t)*s/60:s<180?n:s<240?t+(n-t)*(240-s)/60:t)*255}const OYe=s=>()=>s;function rln(s,t){return function(n){return s+n*t}}function aln(s,t,n){return s=Math.pow(s,n),t=Math.pow(t,n)-s,n=1/n,function(r){return Math.pow(s+r*t,n)}}function iln(s){return(s=+s)==1?S8t:function(t,n){return n-t?aln(t,n,s):OYe(isNaN(t)?n:t)}}function S8t(s,t){var n=t-s;return n?rln(s,n):OYe(isNaN(s)?t:s)}const ept=function s(t){var n=iln(t);function r(a,i){var l=n((a=zze(a)).r,(i=zze(i)).r),o=n(a.g,i.g),c=n(a.b,i.b),d=S8t(a.opacity,i.opacity);return function(u){return a.r=l(u),a.g=o(u),a.b=c(u),a.opacity=d(u),a+""}}return r.gamma=s,r}(1);function oln(s,t){t||(t=[]);var n=s?Math.min(t.length,s.length):0,r=t.slice(),a;return function(i){for(a=0;an&&(i=t.slice(n,i),o[l]?o[l]+=i:o[++l]=i),(r=r[0])===(a=a[0])?o[l]?o[l]+=a:o[++l]=a:(o[++l]=null,c.push({i:l,x:$5e(r,a)})),n=bRe.lastIndex;return nt&&(n=s,s=t,t=n),function(r){return Math.max(s,Math.min(t,r))}}function yln(s,t,n){var r=s[0],a=s[1],i=t[0],l=t[1];return a2?vln:yln,c=d=null,h}function h(m){return m==null||isNaN(m=+m)?i:(c||(c=o(s.map(r),t,n)))(r(l(m)))}return h.invert=function(m){return l(a((d||(d=o(t,s.map(r),$5e)))(m)))},h.domain=function(m){return arguments.length?(s=Array.from(m,U5e),u()):s.slice()},h.range=function(m){return arguments.length?(t=Array.from(m),u()):t.slice()},h.rangeRound=function(m){return t=Array.from(m),n=FYe,u()},h.clamp=function(m){return arguments.length?(l=m?!0:hb,u()):l!==hb},h.interpolate=function(m){return arguments.length?(n=m,u()):n},h.unknown=function(m){return arguments.length?(i=m,h):i},function(m,p){return r=m,a=p,u()}}function zYe(){return SEe()(hb,hb)}function bln(s){return Math.abs(s=Math.round(s))>=1e21?s.toLocaleString("en").replace(/,/g,""):s.toString(10)}function q5e(s,t){if(!isFinite(s)||s===0)return null;var n=(s=t?s.toExponential(t-1):s.toExponential()).indexOf("e"),r=s.slice(0,n);return[r.length>1?r[0]+r.slice(2):r,+s.slice(n+1)]}function BU(s){return s=q5e(Math.abs(s)),s?s[1]:NaN}function _ln(s,t){return function(n,r){for(var a=n.length,i=[],l=0,o=s[0],c=0;a>0&&o>0&&(c+o+1>r&&(o=Math.max(1,r-c)),i.push(n.substring(a-=o,a+o)),!((c+=o+1)>r));)o=s[l=(l+1)%s.length];return i.reverse().join(t)}}function wln(s){return function(t){return t.replace(/[0-9]/g,function(n){return s[+n]})}}var jln=/^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i;function RX(s){if(!(t=jln.exec(s)))throw new Error("invalid format: "+s);var t;return new BYe({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]})}RX.prototype=BYe.prototype;function BYe(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+""}BYe.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 Nln(s){e:for(var t=s.length,n=1,r=-1,a;n0&&(r=0);break}return r>0?s.slice(0,r)+s.slice(a+1):s}var V5e;function kln(s,t){var n=q5e(s,t);if(!n)return V5e=void 0,s.toPrecision(t);var r=n[0],a=n[1],i=a-(V5e=Math.max(-8,Math.min(8,Math.floor(a/3)))*3)+1,l=r.length;return i===l?r:i>l?r+new Array(i-l+1).join("0"):i>0?r.slice(0,i)+"."+r.slice(i):"0."+new Array(1-i).join("0")+q5e(s,Math.max(0,t+i-1))[0]}function spt(s,t){var n=q5e(s,t);if(!n)return s+"";var r=n[0],a=n[1];return a<0?"0."+new Array(-a).join("0")+r:r.length>a+1?r.slice(0,a+1)+"."+r.slice(a+1):r+new Array(a-r.length+2).join("0")}const npt={"%":(s,t)=>(s*100).toFixed(t),b:s=>Math.round(s).toString(2),c:s=>s+"",d:bln,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)=>spt(s*100,t),r:spt,s:kln,X:s=>Math.round(s).toString(16).toUpperCase(),x:s=>Math.round(s).toString(16)};function rpt(s){return s}var apt=Array.prototype.map,ipt=["y","z","a","f","p","n","µ","m","","k","M","G","T","P","E","Z","Y"];function Sln(s){var t=s.grouping===void 0||s.thousands===void 0?rpt:_ln(apt.call(s.grouping,Number),s.thousands+""),n=s.currency===void 0?"":s.currency[0]+"",r=s.currency===void 0?"":s.currency[1]+"",a=s.decimal===void 0?".":s.decimal+"",i=s.numerals===void 0?rpt:wln(apt.call(s.numerals,String)),l=s.percent===void 0?"%":s.percent+"",o=s.minus===void 0?"−":s.minus+"",c=s.nan===void 0?"NaN":s.nan+"";function d(h,m){h=RX(h);var p=h.fill,g=h.align,x=h.sign,y=h.symbol,v=h.zero,_=h.width,j=h.comma,C=h.precision,A=h.trim,M=h.type;M==="n"?(j=!0,M="g"):npt[M]||(C===void 0&&(C=12),A=!0,M="g"),(v||p==="0"&&g==="=")&&(v=!0,p="0",g="=");var I=(m&&m.prefix!==void 0?m.prefix:"")+(y==="$"?n:y==="#"&&/[boxX]/.test(M)?"0"+M.toLowerCase():""),P=(y==="$"?r:/[%p]/.test(M)?l:"")+(m&&m.suffix!==void 0?m.suffix:""),R=npt[M],O=/[defgprs%]/.test(M);C=C===void 0?6:/[gprs]/.test(M)?Math.max(1,Math.min(21,C)):Math.max(0,Math.min(20,C));function B(U){var G=I,H=P,Y,se,ee;if(M==="c")H=R(U)+H,U="";else{U=+U;var oe=U<0||1/U<0;if(U=isNaN(U)?c:R(Math.abs(U),C),A&&(U=Nln(U)),oe&&+U==0&&x!=="+"&&(oe=!1),G=(oe?x==="("?x:o:x==="-"||x==="("?"":x)+G,H=(M==="s"&&!isNaN(U)&&V5e!==void 0?ipt[8+V5e/3]:"")+H+(oe&&x==="("?")":""),O){for(Y=-1,se=U.length;++Yee||ee>57){H=(ee===46?a+U.slice(Y+1):U.slice(Y))+H,U=U.slice(0,Y);break}}}j&&!v&&(U=t(U,1/0));var me=G.length+U.length+H.length,Q=me<_?new Array(_-me+1).join(p):"";switch(j&&v&&(U=t(Q+U,Q.length?_-H.length:1/0),Q=""),g){case"<":U=G+U+H+Q;break;case"=":U=G+Q+U+H;break;case"^":U=Q.slice(0,me=Q.length>>1)+G+U+H+Q.slice(me);break;default:U=Q+G+U+H;break}return i(U)}return B.toString=function(){return h+""},B}function u(h,m){var p=Math.max(-8,Math.min(8,Math.floor(BU(m)/3)))*3,g=Math.pow(10,-p),x=d((h=RX(h),h.type="f",h),{suffix:ipt[8+p/3]});return function(y){return x(g*y)}}return{format:d,formatPrefix:u}}var iae,$Ye,C8t;Cln({thousands:",",grouping:[3],currency:["$",""]});function Cln(s){return iae=Sln(s),$Ye=iae.format,C8t=iae.formatPrefix,iae}function Aln(s){return Math.max(0,-BU(Math.abs(s)))}function Eln(s,t){return Math.max(0,Math.max(-8,Math.min(8,Math.floor(BU(t)/3)))*3-BU(Math.abs(s)))}function Tln(s,t){return s=Math.abs(s),t=Math.abs(t)-s,Math.max(0,BU(t)-BU(s))+1}function A8t(s,t,n,r){var a=Oze(s,t,n),i;switch(r=RX(r??",f"),r.type){case"s":{var l=Math.max(Math.abs(s),Math.abs(t));return r.precision==null&&!isNaN(i=Eln(a,l))&&(r.precision=i),C8t(r,l)}case"":case"e":case"g":case"p":case"r":{r.precision==null&&!isNaN(i=Tln(a,Math.max(Math.abs(s),Math.abs(t))))&&(r.precision=i-(r.type==="e"));break}case"f":case"%":{r.precision==null&&!isNaN(i=Aln(a))&&(r.precision=i-(r.type==="%")*2);break}}return $Ye(r)}function p6(s){var t=s.domain;return s.ticks=function(n){var r=t();return Rze(r[0],r[r.length-1],n??10)},s.tickFormat=function(n,r){var a=t();return A8t(a[0],a[a.length-1],n??10,r)},s.nice=function(n){n==null&&(n=10);var r=t(),a=0,i=r.length-1,l=r[a],o=r[i],c,d,u=10;for(o0;){if(d=Dze(l,o,n),d===c)return r[a]=l,r[i]=o,t(r);if(d>0)l=Math.floor(l/d)*d,o=Math.ceil(o/d)*d;else if(d<0)l=Math.ceil(l*d)/d,o=Math.floor(o*d)/d;else break;c=d}return s},s}function H5e(){var s=zYe();return s.copy=function(){return Qee(s,H5e())},G2.apply(s,arguments),p6(s)}function E8t(s){var t;function n(r){return r==null||isNaN(r=+r)?t:r}return n.invert=n,n.domain=n.range=function(r){return arguments.length?(s=Array.from(r,U5e),n):s.slice()},n.unknown=function(r){return arguments.length?(t=r,n):t},n.copy=function(){return E8t(s).unknown(t)},s=arguments.length?Array.from(s,U5e):[0,1],p6(n)}function T8t(s,t){s=s.slice();var n=0,r=s.length-1,a=s[n],i=s[r],l;return iMath.pow(s,t)}function Rln(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 cpt(s){return(t,n)=>-s(-t,n)}function UYe(s){const t=s(opt,lpt),n=t.domain;let r=10,a,i;function l(){return a=Rln(r),i=Lln(r),n()[0]<0?(a=cpt(a),i=cpt(i),s(Mln,Pln)):s(opt,lpt),t}return t.base=function(o){return arguments.length?(r=+o,l()):r},t.domain=function(o){return arguments.length?(n(o),l()):n()},t.ticks=o=>{const c=n();let d=c[0],u=c[c.length-1];const h=u0){for(;m<=p;++m)for(g=1;gu)break;v.push(x)}}else for(;m<=p;++m)for(g=r-1;g>=1;--g)if(x=m>0?g/i(-m):g*i(m),!(xu)break;v.push(x)}v.length*2{if(o==null&&(o=10),c==null&&(c=r===10?"s":","),typeof c!="function"&&(!(r%1)&&(c=RX(c)).precision==null&&(c.trim=!0),c=$Ye(c)),o===1/0)return c;const d=Math.max(1,r*o/t.ticks().length);return u=>{let h=u/i(Math.round(a(u)));return h*rn(T8t(n(),{floor:o=>i(Math.floor(a(o))),ceil:o=>i(Math.ceil(a(o)))})),t}function M8t(){const s=UYe(SEe()).domain([1,10]);return s.copy=()=>Qee(s,M8t()).base(s.base()),G2.apply(s,arguments),s}function dpt(s){return function(t){return Math.sign(t)*Math.log1p(Math.abs(t/s))}}function upt(s){return function(t){return Math.sign(t)*Math.expm1(Math.abs(t))*s}}function qYe(s){var t=1,n=s(dpt(t),upt(t));return n.constant=function(r){return arguments.length?s(dpt(t=+r),upt(t)):t},p6(n)}function P8t(){var s=qYe(SEe());return s.copy=function(){return Qee(s,P8t()).constant(s.constant())},G2.apply(s,arguments)}function hpt(s){return function(t){return t<0?-Math.pow(-t,s):Math.pow(t,s)}}function Dln(s){return s<0?-Math.sqrt(-s):Math.sqrt(s)}function Oln(s){return s<0?-s*s:s*s}function VYe(s){var t=s(hb,hb),n=1;function r(){return n===1?s(hb,hb):n===.5?s(Dln,Oln):s(hpt(n),hpt(1/n))}return t.exponent=function(a){return arguments.length?(n=+a,r()):n},p6(t)}function HYe(){var s=VYe(SEe());return s.copy=function(){return Qee(s,HYe()).exponent(s.exponent())},G2.apply(s,arguments),s}function Fln(){return HYe.apply(null,arguments).exponent(.5)}function mpt(s){return Math.sign(s)*s*s}function zln(s){return Math.sign(s)*Math.sqrt(Math.abs(s))}function I8t(){var s=zYe(),t=[0,1],n=!1,r;function a(i){var l=zln(s(i));return isNaN(l)?r:n?Math.round(l):l}return a.invert=function(i){return s.invert(mpt(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,U5e)).map(mpt)),a):t.slice()},a.rangeRound=function(i){return a.range(i).round(!0)},a.round=function(i){return arguments.length?(n=!!i,a):n},a.clamp=function(i){return arguments.length?(s.clamp(i),a):s.clamp()},a.unknown=function(i){return arguments.length?(r=i,a):r},a.copy=function(){return I8t(s.domain(),t).round(n).clamp(s.clamp()).unknown(r)},G2.apply(a,arguments),p6(a)}function L8t(){var s=[],t=[],n=[],r;function a(){var l=0,o=Math.max(1,t.length);for(n=new Array(o-1);++l0?n[o-1]:s[0],o=n?[r[n-1],t]:[r[d-1],r[d]]},l.unknown=function(c){return arguments.length&&(i=c),l},l.thresholds=function(){return r.slice()},l.copy=function(){return R8t().domain([s,t]).range(a).unknown(i)},G2.apply(p6(l),arguments)}function D8t(){var s=[.5],t=[0,1],n,r=1;function a(i){return i!=null&&i<=i?t[Zee(s,i,0,r)]:n}return a.domain=function(i){return arguments.length?(s=Array.from(i),r=Math.min(s.length,t.length-1),a):s.slice()},a.range=function(i){return arguments.length?(t=Array.from(i),r=Math.min(s.length,t.length-1),a):t.slice()},a.invertExtent=function(i){var l=t.indexOf(i);return[s[l-1],s[l]]},a.unknown=function(i){return arguments.length?(n=i,a):n},a.copy=function(){return D8t().domain(s).range(t).unknown(n)},G2.apply(a,arguments)}const _Re=new Date,wRe=new Date;function Ly(s,t,n,r){function a(i){return s(i=arguments.length===0?new Date:new Date(+i)),i}return a.floor=i=>(s(i=new Date(+i)),i),a.ceil=i=>(s(i=new Date(i-1)),t(i,1),s(i),i),a.round=i=>{const l=a(i),o=a.ceil(i);return i-l(t(i=new Date(+i),l==null?1:Math.floor(l)),i),a.range=(i,l,o)=>{const c=[];if(i=a.ceil(i),o=o==null?1:Math.floor(o),!(i0))return c;let d;do c.push(d=new Date(+i)),t(i,o),s(i);while(dLy(l=>{if(l>=l)for(;s(l),!i(l);)l.setTime(l-1)},(l,o)=>{if(l>=l)if(o<0)for(;++o<=0;)for(;t(l,-1),!i(l););else for(;--o>=0;)for(;t(l,1),!i(l););}),n&&(a.count=(i,l)=>(_Re.setTime(+i),wRe.setTime(+l),s(_Re),s(wRe),Math.floor(n(_Re,wRe))),a.every=i=>(i=Math.floor(i),!isFinite(i)||!(i>0)?null:i>1?a.filter(r?l=>r(l)%i===0:l=>a.count(0,l)%i===0):a)),a}const G5e=Ly(()=>{},(s,t)=>{s.setTime(+s+t)},(s,t)=>t-s);G5e.every=s=>(s=Math.floor(s),!isFinite(s)||!(s>0)?null:s>1?Ly(t=>{t.setTime(Math.floor(t/s)*s)},(t,n)=>{t.setTime(+t+n*s)},(t,n)=>(n-t)/s):G5e);G5e.range;const c3=1e3,f2=c3*60,d3=f2*60,V3=d3*24,GYe=V3*7,fpt=V3*30,jRe=V3*365,pD=Ly(s=>{s.setTime(s-s.getMilliseconds())},(s,t)=>{s.setTime(+s+t*c3)},(s,t)=>(t-s)/c3,s=>s.getUTCSeconds());pD.range;const WYe=Ly(s=>{s.setTime(s-s.getMilliseconds()-s.getSeconds()*c3)},(s,t)=>{s.setTime(+s+t*f2)},(s,t)=>(t-s)/f2,s=>s.getMinutes());WYe.range;const KYe=Ly(s=>{s.setUTCSeconds(0,0)},(s,t)=>{s.setTime(+s+t*f2)},(s,t)=>(t-s)/f2,s=>s.getUTCMinutes());KYe.range;const YYe=Ly(s=>{s.setTime(s-s.getMilliseconds()-s.getSeconds()*c3-s.getMinutes()*f2)},(s,t)=>{s.setTime(+s+t*d3)},(s,t)=>(t-s)/d3,s=>s.getHours());YYe.range;const ZYe=Ly(s=>{s.setUTCMinutes(0,0,0)},(s,t)=>{s.setTime(+s+t*d3)},(s,t)=>(t-s)/d3,s=>s.getUTCHours());ZYe.range;const Jee=Ly(s=>s.setHours(0,0,0,0),(s,t)=>s.setDate(s.getDate()+t),(s,t)=>(t-s-(t.getTimezoneOffset()-s.getTimezoneOffset())*f2)/V3,s=>s.getDate()-1);Jee.range;const CEe=Ly(s=>{s.setUTCHours(0,0,0,0)},(s,t)=>{s.setUTCDate(s.getUTCDate()+t)},(s,t)=>(t-s)/V3,s=>s.getUTCDate()-1);CEe.range;const O8t=Ly(s=>{s.setUTCHours(0,0,0,0)},(s,t)=>{s.setUTCDate(s.getUTCDate()+t)},(s,t)=>(t-s)/V3,s=>Math.floor(s/V3));O8t.range;function RF(s){return Ly(t=>{t.setDate(t.getDate()-(t.getDay()+7-s)%7),t.setHours(0,0,0,0)},(t,n)=>{t.setDate(t.getDate()+n*7)},(t,n)=>(n-t-(n.getTimezoneOffset()-t.getTimezoneOffset())*f2)/GYe)}const AEe=RF(0),W5e=RF(1),Bln=RF(2),$ln=RF(3),$U=RF(4),Uln=RF(5),qln=RF(6);AEe.range;W5e.range;Bln.range;$ln.range;$U.range;Uln.range;qln.range;function DF(s){return Ly(t=>{t.setUTCDate(t.getUTCDate()-(t.getUTCDay()+7-s)%7),t.setUTCHours(0,0,0,0)},(t,n)=>{t.setUTCDate(t.getUTCDate()+n*7)},(t,n)=>(n-t)/GYe)}const EEe=DF(0),K5e=DF(1),Vln=DF(2),Hln=DF(3),UU=DF(4),Gln=DF(5),Wln=DF(6);EEe.range;K5e.range;Vln.range;Hln.range;UU.range;Gln.range;Wln.range;const XYe=Ly(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());XYe.range;const QYe=Ly(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());QYe.range;const H3=Ly(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());H3.every=s=>!isFinite(s=Math.floor(s))||!(s>0)?null:Ly(t=>{t.setFullYear(Math.floor(t.getFullYear()/s)*s),t.setMonth(0,1),t.setHours(0,0,0,0)},(t,n)=>{t.setFullYear(t.getFullYear()+n*s)});H3.range;const G3=Ly(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());G3.every=s=>!isFinite(s=Math.floor(s))||!(s>0)?null:Ly(t=>{t.setUTCFullYear(Math.floor(t.getUTCFullYear()/s)*s),t.setUTCMonth(0,1),t.setUTCHours(0,0,0,0)},(t,n)=>{t.setUTCFullYear(t.getUTCFullYear()+n*s)});G3.range;function F8t(s,t,n,r,a,i){const l=[[pD,1,c3],[pD,5,5*c3],[pD,15,15*c3],[pD,30,30*c3],[i,1,f2],[i,5,5*f2],[i,15,15*f2],[i,30,30*f2],[a,1,d3],[a,3,3*d3],[a,6,6*d3],[a,12,12*d3],[r,1,V3],[r,2,2*V3],[n,1,GYe],[t,1,fpt],[t,3,3*fpt],[s,1,jRe]];function o(d,u,h){const m=uy).right(l,m);if(p===l.length)return s.every(Oze(d/jRe,u/jRe,h));if(p===0)return G5e.every(Math.max(Oze(d,u,h),1));const[g,x]=l[m/l[p-1][2]53)return null;"w"in je||(je.w=1),"Z"in je?(Ee=kRe(kG(je.y,0,1)),Re=Ee.getUTCDay(),Ee=Re>4||Re===0?K5e.ceil(Ee):K5e(Ee),Ee=CEe.offset(Ee,(je.V-1)*7),je.y=Ee.getUTCFullYear(),je.m=Ee.getUTCMonth(),je.d=Ee.getUTCDate()+(je.w+6)%7):(Ee=NRe(kG(je.y,0,1)),Re=Ee.getDay(),Ee=Re>4||Re===0?W5e.ceil(Ee):W5e(Ee),Ee=Jee.offset(Ee,(je.V-1)*7),je.y=Ee.getFullYear(),je.m=Ee.getMonth(),je.d=Ee.getDate()+(je.w+6)%7)}else("W"in je||"U"in je)&&("w"in je||(je.w="u"in je?je.u%7:"W"in je?1:0),Re="Z"in je?kRe(kG(je.y,0,1)).getUTCDay():NRe(kG(je.y,0,1)).getDay(),je.m=0,je.d="W"in je?(je.w+6)%7+je.W*7-(Re+5)%7:je.w+je.U*7-(Re+6)%7);return"Z"in je?(je.H+=je.Z/100|0,je.M+=je.Z%100,kRe(je)):NRe(je)}}function P(Ie,Ue,Be,je){for(var Ye=0,Ee=Ue.length,Re=Be.length,ke,Fe;Ye=Re)return-1;if(ke=Ue.charCodeAt(Ye++),ke===37){if(ke=Ue.charAt(Ye++),Fe=A[ke in ppt?Ue.charAt(Ye++):ke],!Fe||(je=Fe(Ie,Be,je))<0)return-1}else if(ke!=Be.charCodeAt(je++))return-1}return je}function R(Ie,Ue,Be){var je=d.exec(Ue.slice(Be));return je?(Ie.p=u.get(je[0].toLowerCase()),Be+je[0].length):-1}function O(Ie,Ue,Be){var je=p.exec(Ue.slice(Be));return je?(Ie.w=g.get(je[0].toLowerCase()),Be+je[0].length):-1}function B(Ie,Ue,Be){var je=h.exec(Ue.slice(Be));return je?(Ie.w=m.get(je[0].toLowerCase()),Be+je[0].length):-1}function U(Ie,Ue,Be){var je=v.exec(Ue.slice(Be));return je?(Ie.m=_.get(je[0].toLowerCase()),Be+je[0].length):-1}function G(Ie,Ue,Be){var je=x.exec(Ue.slice(Be));return je?(Ie.m=y.get(je[0].toLowerCase()),Be+je[0].length):-1}function H(Ie,Ue,Be){return P(Ie,t,Ue,Be)}function Y(Ie,Ue,Be){return P(Ie,n,Ue,Be)}function se(Ie,Ue,Be){return P(Ie,r,Ue,Be)}function ee(Ie){return l[Ie.getDay()]}function oe(Ie){return i[Ie.getDay()]}function me(Ie){return c[Ie.getMonth()]}function Q(Ie){return o[Ie.getMonth()]}function te(Ie){return a[+(Ie.getHours()>=12)]}function le(Ie){return 1+~~(Ie.getMonth()/3)}function fe(Ie){return l[Ie.getUTCDay()]}function _e(Ie){return i[Ie.getUTCDay()]}function ve(Ie){return c[Ie.getUTCMonth()]}function he(Ie){return o[Ie.getUTCMonth()]}function Se(Ie){return a[+(Ie.getUTCHours()>=12)]}function Te(Ie){return 1+~~(Ie.getUTCMonth()/3)}return{format:function(Ie){var Ue=M(Ie+="",j);return Ue.toString=function(){return Ie},Ue},parse:function(Ie){var Ue=I(Ie+="",!1);return Ue.toString=function(){return Ie},Ue},utcFormat:function(Ie){var Ue=M(Ie+="",C);return Ue.toString=function(){return Ie},Ue},utcParse:function(Ie){var Ue=I(Ie+="",!0);return Ue.toString=function(){return Ie},Ue}}}var ppt={"-":"",_:" ",0:"0"},k0=/^\s*\d+/,Jln=/^%/,ecn=/[\\^$*+?|[\]().{}]/g;function Hu(s,t,n){var r=s<0?"-":"",a=(r?-s:s)+"",i=a.length;return r+(i[t.toLowerCase(),n]))}function scn(s,t,n){var r=k0.exec(t.slice(n,n+1));return r?(s.w=+r[0],n+r[0].length):-1}function ncn(s,t,n){var r=k0.exec(t.slice(n,n+1));return r?(s.u=+r[0],n+r[0].length):-1}function rcn(s,t,n){var r=k0.exec(t.slice(n,n+2));return r?(s.U=+r[0],n+r[0].length):-1}function acn(s,t,n){var r=k0.exec(t.slice(n,n+2));return r?(s.V=+r[0],n+r[0].length):-1}function icn(s,t,n){var r=k0.exec(t.slice(n,n+2));return r?(s.W=+r[0],n+r[0].length):-1}function gpt(s,t,n){var r=k0.exec(t.slice(n,n+4));return r?(s.y=+r[0],n+r[0].length):-1}function xpt(s,t,n){var r=k0.exec(t.slice(n,n+2));return r?(s.y=+r[0]+(+r[0]>68?1900:2e3),n+r[0].length):-1}function ocn(s,t,n){var r=/^(Z)|([+-]\d\d)(?::?(\d\d))?/.exec(t.slice(n,n+6));return r?(s.Z=r[1]?0:-(r[2]+(r[3]||"00")),n+r[0].length):-1}function lcn(s,t,n){var r=k0.exec(t.slice(n,n+1));return r?(s.q=r[0]*3-3,n+r[0].length):-1}function ccn(s,t,n){var r=k0.exec(t.slice(n,n+2));return r?(s.m=r[0]-1,n+r[0].length):-1}function ypt(s,t,n){var r=k0.exec(t.slice(n,n+2));return r?(s.d=+r[0],n+r[0].length):-1}function dcn(s,t,n){var r=k0.exec(t.slice(n,n+3));return r?(s.m=0,s.d=+r[0],n+r[0].length):-1}function vpt(s,t,n){var r=k0.exec(t.slice(n,n+2));return r?(s.H=+r[0],n+r[0].length):-1}function ucn(s,t,n){var r=k0.exec(t.slice(n,n+2));return r?(s.M=+r[0],n+r[0].length):-1}function hcn(s,t,n){var r=k0.exec(t.slice(n,n+2));return r?(s.S=+r[0],n+r[0].length):-1}function mcn(s,t,n){var r=k0.exec(t.slice(n,n+3));return r?(s.L=+r[0],n+r[0].length):-1}function fcn(s,t,n){var r=k0.exec(t.slice(n,n+6));return r?(s.L=Math.floor(r[0]/1e3),n+r[0].length):-1}function pcn(s,t,n){var r=Jln.exec(t.slice(n,n+1));return r?n+r[0].length:-1}function gcn(s,t,n){var r=k0.exec(t.slice(n));return r?(s.Q=+r[0],n+r[0].length):-1}function xcn(s,t,n){var r=k0.exec(t.slice(n));return r?(s.s=+r[0],n+r[0].length):-1}function bpt(s,t){return Hu(s.getDate(),t,2)}function ycn(s,t){return Hu(s.getHours(),t,2)}function vcn(s,t){return Hu(s.getHours()%12||12,t,2)}function bcn(s,t){return Hu(1+Jee.count(H3(s),s),t,3)}function z8t(s,t){return Hu(s.getMilliseconds(),t,3)}function _cn(s,t){return z8t(s,t)+"000"}function wcn(s,t){return Hu(s.getMonth()+1,t,2)}function jcn(s,t){return Hu(s.getMinutes(),t,2)}function Ncn(s,t){return Hu(s.getSeconds(),t,2)}function kcn(s){var t=s.getDay();return t===0?7:t}function Scn(s,t){return Hu(AEe.count(H3(s)-1,s),t,2)}function B8t(s){var t=s.getDay();return t>=4||t===0?$U(s):$U.ceil(s)}function Ccn(s,t){return s=B8t(s),Hu($U.count(H3(s),s)+(H3(s).getDay()===4),t,2)}function Acn(s){return s.getDay()}function Ecn(s,t){return Hu(W5e.count(H3(s)-1,s),t,2)}function Tcn(s,t){return Hu(s.getFullYear()%100,t,2)}function Mcn(s,t){return s=B8t(s),Hu(s.getFullYear()%100,t,2)}function Pcn(s,t){return Hu(s.getFullYear()%1e4,t,4)}function Icn(s,t){var n=s.getDay();return s=n>=4||n===0?$U(s):$U.ceil(s),Hu(s.getFullYear()%1e4,t,4)}function Lcn(s){var t=s.getTimezoneOffset();return(t>0?"-":(t*=-1,"+"))+Hu(t/60|0,"0",2)+Hu(t%60,"0",2)}function _pt(s,t){return Hu(s.getUTCDate(),t,2)}function Rcn(s,t){return Hu(s.getUTCHours(),t,2)}function Dcn(s,t){return Hu(s.getUTCHours()%12||12,t,2)}function Ocn(s,t){return Hu(1+CEe.count(G3(s),s),t,3)}function $8t(s,t){return Hu(s.getUTCMilliseconds(),t,3)}function Fcn(s,t){return $8t(s,t)+"000"}function zcn(s,t){return Hu(s.getUTCMonth()+1,t,2)}function Bcn(s,t){return Hu(s.getUTCMinutes(),t,2)}function $cn(s,t){return Hu(s.getUTCSeconds(),t,2)}function Ucn(s){var t=s.getUTCDay();return t===0?7:t}function qcn(s,t){return Hu(EEe.count(G3(s)-1,s),t,2)}function U8t(s){var t=s.getUTCDay();return t>=4||t===0?UU(s):UU.ceil(s)}function Vcn(s,t){return s=U8t(s),Hu(UU.count(G3(s),s)+(G3(s).getUTCDay()===4),t,2)}function Hcn(s){return s.getUTCDay()}function Gcn(s,t){return Hu(K5e.count(G3(s)-1,s),t,2)}function Wcn(s,t){return Hu(s.getUTCFullYear()%100,t,2)}function Kcn(s,t){return s=U8t(s),Hu(s.getUTCFullYear()%100,t,2)}function Ycn(s,t){return Hu(s.getUTCFullYear()%1e4,t,4)}function Zcn(s,t){var n=s.getUTCDay();return s=n>=4||n===0?UU(s):UU.ceil(s),Hu(s.getUTCFullYear()%1e4,t,4)}function Xcn(){return"+0000"}function wpt(){return"%"}function jpt(s){return+s}function Npt(s){return Math.floor(+s/1e3)}var r9,q8t,V8t;Qcn({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 Qcn(s){return r9=Qln(s),q8t=r9.format,r9.parse,V8t=r9.utcFormat,r9.utcParse,r9}function Jcn(s){return new Date(s)}function edn(s){return s instanceof Date?+s:+new Date(+s)}function JYe(s,t,n,r,a,i,l,o,c,d){var u=zYe(),h=u.invert,m=u.domain,p=d(".%L"),g=d(":%S"),x=d("%I:%M"),y=d("%I %p"),v=d("%a %d"),_=d("%b %d"),j=d("%B"),C=d("%Y");function A(M){return(c(M)t(a/(s.length-1)))},n.quantiles=function(r){return Array.from({length:r+1},(a,i)=>qon(s,i/r))},n.copy=function(){return K8t(t).domain(s)},mA.apply(n,arguments)}function MEe(){var s=0,t=.5,n=1,r=1,a,i,l,o,c,d=hb,u,h=!1,m;function p(x){return isNaN(x=+x)?m:(x=.5+((x=+u(x))-i)*(r*xt}var Q8t=odn,ldn=PEe,cdn=Q8t,ddn=yV;function udn(s){return s&&s.length?ldn(s,ddn,cdn):void 0}var hdn=udn;const kT=kd(hdn);function mdn(s,t){return ss.e^i.s<0?1:-1;for(r=i.d.length,a=s.d.length,t=0,n=rs.d[t]^i.s<0?1:-1;return r===a?0:r>a^i.s<0?1:-1};vo.decimalPlaces=vo.dp=function(){var s=this,t=s.d.length-1,n=(t-s.e)*yf;if(t=s.d[t],t)for(;t%10==0;t/=10)n--;return n<0?0:n};vo.dividedBy=vo.div=function(s){return A3(this,new this.constructor(s))};vo.dividedToIntegerBy=vo.idiv=function(s){var t=this,n=t.constructor;return vm(A3(t,new n(s),0,1),n.precision)};vo.equals=vo.eq=function(s){return!this.cmp(s)};vo.exponent=function(){return qx(this)};vo.greaterThan=vo.gt=function(s){return this.cmp(s)>0};vo.greaterThanOrEqualTo=vo.gte=function(s){return this.cmp(s)>=0};vo.isInteger=vo.isint=function(){return this.e>this.d.length-2};vo.isNegative=vo.isneg=function(){return this.s<0};vo.isPositive=vo.ispos=function(){return this.s>0};vo.isZero=function(){return this.s===0};vo.lessThan=vo.lt=function(s){return this.cmp(s)<0};vo.lessThanOrEqualTo=vo.lte=function(s){return this.cmp(s)<1};vo.logarithm=vo.log=function(s){var t,n=this,r=n.constructor,a=r.precision,i=a+5;if(s===void 0)s=new r(10);else if(s=new r(s),s.s<1||s.eq(qw))throw Error(L2+"NaN");if(n.s<1)throw Error(L2+(n.s?"NaN":"-Infinity"));return n.eq(qw)?new r(0):(rp=!1,t=A3(DX(n,i),DX(s,i),i),rp=!0,vm(t,a))};vo.minus=vo.sub=function(s){var t=this;return s=new t.constructor(s),t.s==s.s?nOt(t,s):tOt(t,(s.s=-s.s,s))};vo.modulo=vo.mod=function(s){var t,n=this,r=n.constructor,a=r.precision;if(s=new r(s),!s.s)throw Error(L2+"NaN");return n.s?(rp=!1,t=A3(n,s,0,1).times(s),rp=!0,n.minus(t)):vm(new r(n),a)};vo.naturalExponential=vo.exp=function(){return sOt(this)};vo.naturalLogarithm=vo.ln=function(){return DX(this)};vo.negated=vo.neg=function(){var s=new this.constructor(this);return s.s=-s.s||0,s};vo.plus=vo.add=function(s){var t=this;return s=new t.constructor(s),t.s==s.s?tOt(t,s):nOt(t,(s.s=-s.s,s))};vo.precision=vo.sd=function(s){var t,n,r,a=this;if(s!==void 0&&s!==!!s&&s!==1&&s!==0)throw Error(dO+s);if(t=qx(a)+1,r=a.d.length-1,n=r*yf+1,r=a.d[r],r){for(;r%10==0;r/=10)n--;for(r=a.d[0];r>=10;r/=10)n++}return s&&t>n?t:n};vo.squareRoot=vo.sqrt=function(){var s,t,n,r,a,i,l,o=this,c=o.constructor;if(o.s<1){if(!o.s)return new c(0);throw Error(L2+"NaN")}for(s=qx(o),rp=!1,a=Math.sqrt(+o),a==0||a==1/0?(t=p5(o.d),(t.length+s)%2==0&&(t+="0"),a=Math.sqrt(t),s=wV((s+1)/2)-(s<0||s%2),a==1/0?t="5e"+s:(t=a.toExponential(),t=t.slice(0,t.indexOf("e")+1)+s),r=new c(t)):r=new c(a.toString()),n=c.precision,a=l=n+3;;)if(i=r,r=i.plus(A3(o,i,l+2)).times(.5),p5(i.d).slice(0,l)===(t=p5(r.d)).slice(0,l)){if(t=t.slice(l-3,l+1),a==l&&t=="4999"){if(vm(i,n+1,0),i.times(i).eq(o)){r=i;break}}else if(t!="9999")break;l+=4}return rp=!0,vm(r,n)};vo.times=vo.mul=function(s){var t,n,r,a,i,l,o,c,d,u=this,h=u.constructor,m=u.d,p=(s=new h(s)).d;if(!u.s||!s.s)return new h(0);for(s.s*=u.s,n=u.e+s.e,c=m.length,d=p.length,c=0;){for(t=0,a=c+r;a>r;)o=i[a]+p[r]*m[a-r-1]+t,i[a--]=o%n0|0,t=o/n0|0;i[a]=(i[a]+t)%n0|0}for(;!i[--l];)i.pop();return t?++n:i.shift(),s.d=i,s.e=n,rp?vm(s,h.precision):s};vo.toDecimalPlaces=vo.todp=function(s,t){var n=this,r=n.constructor;return n=new r(n),s===void 0?n:(K5(s,0,_V),t===void 0?t=r.rounding:K5(t,0,8),vm(n,s+qx(n)+1,t))};vo.toExponential=function(s,t){var n,r=this,a=r.constructor;return s===void 0?n=KO(r,!0):(K5(s,0,_V),t===void 0?t=a.rounding:K5(t,0,8),r=vm(new a(r),s+1,t),n=KO(r,!0,s+1)),n};vo.toFixed=function(s,t){var n,r,a=this,i=a.constructor;return s===void 0?KO(a):(K5(s,0,_V),t===void 0?t=i.rounding:K5(t,0,8),r=vm(new i(a),s+qx(a)+1,t),n=KO(r.abs(),!1,s+qx(r)+1),a.isneg()&&!a.isZero()?"-"+n:n)};vo.toInteger=vo.toint=function(){var s=this,t=s.constructor;return vm(new t(s),qx(s)+1,t.rounding)};vo.toNumber=function(){return+this};vo.toPower=vo.pow=function(s){var t,n,r,a,i,l,o=this,c=o.constructor,d=12,u=+(s=new c(s));if(!s.s)return new c(qw);if(o=new c(o),!o.s){if(s.s<1)throw Error(L2+"Infinity");return o}if(o.eq(qw))return o;if(r=c.precision,s.eq(qw))return vm(o,r);if(t=s.e,n=s.d.length-1,l=t>=n,i=o.s,l){if((n=u<0?-u:u)<=eOt){for(a=new c(qw),t=Math.ceil(r/yf+4),rp=!1;n%2&&(a=a.times(o),Cpt(a.d,t)),n=wV(n/2),n!==0;)o=o.times(o),Cpt(o.d,t);return rp=!0,s.s<0?new c(qw).div(a):vm(a,r)}}else if(i<0)throw Error(L2+"NaN");return i=i<0&&s.d[Math.max(t,n)]&1?-1:1,o.s=1,rp=!1,a=s.times(DX(o,r+d)),rp=!0,a=sOt(a),a.s=i,a};vo.toPrecision=function(s,t){var n,r,a=this,i=a.constructor;return s===void 0?(n=qx(a),r=KO(a,n<=i.toExpNeg||n>=i.toExpPos)):(K5(s,1,_V),t===void 0?t=i.rounding:K5(t,0,8),a=vm(new i(a),s,t),n=qx(a),r=KO(a,s<=n||n<=i.toExpNeg,s)),r};vo.toSignificantDigits=vo.tosd=function(s,t){var n=this,r=n.constructor;return s===void 0?(s=r.precision,t=r.rounding):(K5(s,1,_V),t===void 0?t=r.rounding:K5(t,0,8)),vm(new r(n),s,t)};vo.toString=vo.valueOf=vo.val=vo.toJSON=vo[Symbol.for("nodejs.util.inspect.custom")]=function(){var s=this,t=qx(s),n=s.constructor;return KO(s,t<=n.toExpNeg||t>=n.toExpPos)};function tOt(s,t){var n,r,a,i,l,o,c,d,u=s.constructor,h=u.precision;if(!s.s||!t.s)return t.s||(t=new u(s)),rp?vm(t,h):t;if(c=s.d,d=t.d,l=s.e,a=t.e,c=c.slice(),i=l-a,i){for(i<0?(r=c,i=-i,o=d.length):(r=d,a=l,o=c.length),l=Math.ceil(h/yf),o=l>o?l+1:o+1,i>o&&(i=o,r.length=1),r.reverse();i--;)r.push(0);r.reverse()}for(o=c.length,i=d.length,o-i<0&&(i=o,r=d,d=c,c=r),n=0;i;)n=(c[--i]=c[i]+d[i]+n)/n0|0,c[i]%=n0;for(n&&(c.unshift(n),++a),o=c.length;c[--o]==0;)c.pop();return t.d=c,t.e=a,rp?vm(t,h):t}function K5(s,t,n){if(s!==~~s||sn)throw Error(dO+s)}function p5(s){var t,n,r,a=s.length-1,i="",l=s[0];if(a>0){for(i+=l,t=1;tl?1:-1;else for(o=c=0;oa[o]?1:-1;break}return c}function n(r,a,i){for(var l=0;i--;)r[i]-=l,l=r[i]1;)r.shift()}return function(r,a,i,l){var o,c,d,u,h,m,p,g,x,y,v,_,j,C,A,M,I,P,R=r.constructor,O=r.s==a.s?1:-1,B=r.d,U=a.d;if(!r.s)return new R(r);if(!a.s)throw Error(L2+"Division by zero");for(c=r.e-a.e,I=U.length,A=B.length,p=new R(O),g=p.d=[],d=0;U[d]==(B[d]||0);)++d;if(U[d]>(B[d]||0)&&--c,i==null?_=i=R.precision:l?_=i+(qx(r)-qx(a))+1:_=i,_<0)return new R(0);if(_=_/yf+2|0,d=0,I==1)for(u=0,U=U[0],_++;(d1&&(U=s(U,u),B=s(B,u),I=U.length,A=B.length),C=I,x=B.slice(0,I),y=x.length;y=n0/2&&++M;do u=0,o=t(U,x,I,y),o<0?(v=x[0],I!=y&&(v=v*n0+(x[1]||0)),u=v/M|0,u>1?(u>=n0&&(u=n0-1),h=s(U,u),m=h.length,y=x.length,o=t(h,x,m,y),o==1&&(u--,n(h,I16)throw Error(sZe+qx(s));if(!s.s)return new u(qw);for(rp=!1,o=h,l=new u(.03125);s.abs().gte(.1);)s=s.times(l),d+=5;for(r=Math.log(RR(2,d))/Math.LN10*2+5|0,o+=r,n=a=i=new u(qw),u.precision=o;;){if(a=vm(a.times(s),o),n=n.times(++c),l=i.plus(A3(a,n,o)),p5(l.d).slice(0,o)===p5(i.d).slice(0,o)){for(;d--;)i=vm(i.times(i),o);return u.precision=h,t==null?(rp=!0,vm(i,h)):i}i=l}}function qx(s){for(var t=s.e*yf,n=s.d[0];n>=10;n/=10)t++;return t}function SRe(s,t,n){if(t>s.LN10.sd())throw rp=!0,n&&(s.precision=n),Error(L2+"LN10 precision limit exceeded");return vm(new s(s.LN10),t)}function bE(s){for(var t="";s--;)t+="0";return t}function DX(s,t){var n,r,a,i,l,o,c,d,u,h=1,m=10,p=s,g=p.d,x=p.constructor,y=x.precision;if(p.s<1)throw Error(L2+(p.s?"NaN":"-Infinity"));if(p.eq(qw))return new x(0);if(t==null?(rp=!1,d=y):d=t,p.eq(10))return t==null&&(rp=!0),SRe(x,d);if(d+=m,x.precision=d,n=p5(g),r=n.charAt(0),i=qx(p),Math.abs(i)<15e14){for(;r<7&&r!=1||r==1&&n.charAt(1)>3;)p=p.times(s),n=p5(p.d),r=n.charAt(0),h++;i=qx(p),r>1?(p=new x("0."+n),i++):p=new x(r+"."+n.slice(1))}else return c=SRe(x,d+2,y).times(i+""),p=DX(new x(r+"."+n.slice(1)),d-m).plus(c),x.precision=y,t==null?(rp=!0,vm(p,y)):p;for(o=l=p=A3(p.minus(qw),p.plus(qw),d),u=vm(p.times(p),d),a=3;;){if(l=vm(l.times(u),d),c=o.plus(A3(l,new x(a),d)),p5(c.d).slice(0,d)===p5(o.d).slice(0,d))return o=o.times(2),i!==0&&(o=o.plus(SRe(x,d+2,y).times(i+""))),o=A3(o,new x(h),d),x.precision=y,t==null?(rp=!0,vm(o,y)):o;o=c,a+=2}}function Spt(s,t){var n,r,a;for((n=t.indexOf("."))>-1&&(t=t.replace(".","")),(r=t.search(/e/i))>0?(n<0&&(n=r),n+=+t.slice(r+1),t=t.substring(0,r)):n<0&&(n=t.length),r=0;t.charCodeAt(r)===48;)++r;for(a=t.length;t.charCodeAt(a-1)===48;)--a;if(t=t.slice(r,a),t){if(a-=r,n=n-r-1,s.e=wV(n/yf),s.d=[],r=(n+1)%yf,n<0&&(r+=yf),rY5e||s.e<-Y5e))throw Error(sZe+n)}else s.s=0,s.e=0,s.d=[0];return s}function vm(s,t,n){var r,a,i,l,o,c,d,u,h=s.d;for(l=1,i=h[0];i>=10;i/=10)l++;if(r=t-l,r<0)r+=yf,a=t,d=h[u=0];else{if(u=Math.ceil((r+1)/yf),i=h.length,u>=i)return s;for(d=i=h[u],l=1;i>=10;i/=10)l++;r%=yf,a=r-yf+l}if(n!==void 0&&(i=RR(10,l-a-1),o=d/i%10|0,c=t<0||h[u+1]!==void 0||d%i,c=n<4?(o||c)&&(n==0||n==(s.s<0?3:2)):o>5||o==5&&(n==4||c||n==6&&(r>0?a>0?d/RR(10,l-a):0:h[u-1])%10&1||n==(s.s<0?8:7))),t<1||!h[0])return c?(i=qx(s),h.length=1,t=t-i-1,h[0]=RR(10,(yf-t%yf)%yf),s.e=wV(-t/yf)||0):(h.length=1,h[0]=s.e=s.s=0),s;if(r==0?(h.length=u,i=1,u--):(h.length=u+1,i=RR(10,yf-r),h[u]=a>0?(d/RR(10,l-a)%RR(10,a)|0)*i:0),c)for(;;)if(u==0){(h[0]+=i)==n0&&(h[0]=1,++s.e);break}else{if(h[u]+=i,h[u]!=n0)break;h[u--]=0,i=1}for(r=h.length;h[--r]===0;)h.pop();if(rp&&(s.e>Y5e||s.e<-Y5e))throw Error(sZe+qx(s));return s}function nOt(s,t){var n,r,a,i,l,o,c,d,u,h,m=s.constructor,p=m.precision;if(!s.s||!t.s)return t.s?t.s=-t.s:t=new m(s),rp?vm(t,p):t;if(c=s.d,h=t.d,r=t.e,d=s.e,c=c.slice(),l=d-r,l){for(u=l<0,u?(n=c,l=-l,o=h.length):(n=h,r=d,o=c.length),a=Math.max(Math.ceil(p/yf),o)+2,l>a&&(l=a,n.length=1),n.reverse(),a=l;a--;)n.push(0);n.reverse()}else{for(a=c.length,o=h.length,u=a0;--a)c[o++]=0;for(a=h.length;a>l;){if(c[--a]0?i=i.charAt(0)+"."+i.slice(1)+bE(r):l>1&&(i=i.charAt(0)+"."+i.slice(1)),i=i+(a<0?"e":"e+")+a):a<0?(i="0."+bE(-a-1)+i,n&&(r=n-l)>0&&(i+=bE(r))):a>=l?(i+=bE(a+1-l),n&&(r=n-a-1)>0&&(i=i+"."+bE(r))):((r=a+1)0&&(a+1===l&&(i+="."),i+=bE(r))),s.s<0?"-"+i:i}function Cpt(s,t){if(s.length>t)return s.length=t,!0}function rOt(s){var t,n,r;function a(i){var l=this;if(!(l instanceof a))return new a(i);if(l.constructor=a,i instanceof a){l.s=i.s,l.e=i.e,l.d=(i=i.d)?i.slice():i;return}if(typeof i=="number"){if(i*0!==0)throw Error(dO+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 Spt(l,i.toString())}else if(typeof i!="string")throw Error(dO+i);if(i.charCodeAt(0)===45?(i=i.slice(1),l.s=-1):l.s=1,Ldn.test(i))Spt(l,i);else throw Error(dO+i)}if(a.prototype=vo,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=rOt,a.config=a.set=Rdn,s===void 0&&(s={}),s)for(r=["precision","rounding","toExpNeg","toExpPos","LN10"],t=0;t=a[t+1]&&r<=a[t+2])this[n]=r;else throw Error(dO+n+": "+r);if((r=s[n="LN10"])!==void 0)if(r==Math.LN10)this[n]=new this(r);else throw Error(dO+n+": "+r);return this}var nZe=rOt(Idn);qw=new nZe(1);const Zh=nZe;function Ddn(s){return Bdn(s)||zdn(s)||Fdn(s)||Odn()}function Odn(){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 Fdn(s,t){if(s){if(typeof s=="string")return Uze(s,t);var n=Object.prototype.toString.call(s).slice(8,-1);if(n==="Object"&&s.constructor&&(n=s.constructor.name),n==="Map"||n==="Set")return Array.from(s);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return Uze(s,t)}}function zdn(s){if(typeof Symbol<"u"&&Symbol.iterator in Object(s))return Array.from(s)}function Bdn(s){if(Array.isArray(s))return Uze(s)}function Uze(s,t){(t==null||t>s.length)&&(t=s.length);for(var n=0,r=new Array(t);n=t?n.apply(void 0,a):s(t-l,Apt(function(){for(var o=arguments.length,c=new Array(o),d=0;ds.length)&&(t=s.length);for(var n=0,r=new Array(t);n"u"||!(Symbol.iterator in Object(s)))){var n=[],r=!0,a=!1,i=void 0;try{for(var l=s[Symbol.iterator](),o;!(r=(o=l.next()).done)&&(n.push(o.value),!(t&&n.length===t));r=!0);}catch(c){a=!0,i=c}finally{try{!r&&l.return!=null&&l.return()}finally{if(a)throw i}}return n}}function tun(s){if(Array.isArray(s))return s}function cOt(s){var t=OX(s,2),n=t[0],r=t[1],a=n,i=r;return n>r&&(a=r,i=n),[a,i]}function dOt(s,t,n){if(s.lte(0))return new Zh(0);var r=REe.getDigitCount(s.toNumber()),a=new Zh(10).pow(r),i=s.div(a),l=r!==1?.05:.1,o=new Zh(Math.ceil(i.div(l).toNumber())).add(n).mul(l),c=o.mul(a);return t?c:new Zh(Math.ceil(c))}function sun(s,t,n){var r=1,a=new Zh(s);if(!a.isint()&&n){var i=Math.abs(s);i<1?(r=new Zh(10).pow(REe.getDigitCount(s)-1),a=new Zh(Math.floor(a.div(r).toNumber())).mul(r)):i>1&&(a=new Zh(Math.floor(s)))}else s===0?a=new Zh(Math.floor((t-1)/2)):n||(a=new Zh(Math.floor(s)));var l=Math.floor((t-1)/2),o=Vdn(qdn(function(c){return a.add(new Zh(c-l).mul(r)).toNumber()}),qze);return o(0,t)}function uOt(s,t,n,r){var a=arguments.length>4&&arguments[4]!==void 0?arguments[4]:0;if(!Number.isFinite((t-s)/(n-1)))return{step:new Zh(0),tickMin:new Zh(0),tickMax:new Zh(0)};var i=dOt(new Zh(t).sub(s).div(n-1),r,a),l;s<=0&&t>=0?l=new Zh(0):(l=new Zh(s).add(t).div(2),l=l.sub(new Zh(l).mod(i)));var o=Math.ceil(l.sub(s).div(i).toNumber()),c=Math.ceil(new Zh(t).sub(l).div(i).toNumber()),d=o+c+1;return d>n?uOt(s,t,n,r,a+1):(d0?c+(n-d):c,o=t>0?o:o+(n-d)),{step:i,tickMin:l.sub(new Zh(o).mul(i)),tickMax:l.add(new Zh(c).mul(i))})}function nun(s){var t=OX(s,2),n=t[0],r=t[1],a=arguments.length>1&&arguments[1]!==void 0?arguments[1]:6,i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,l=Math.max(a,2),o=cOt([n,r]),c=OX(o,2),d=c[0],u=c[1];if(d===-1/0||u===1/0){var h=u===1/0?[d].concat(Hze(qze(0,a-1).map(function(){return 1/0}))):[].concat(Hze(qze(0,a-1).map(function(){return-1/0})),[u]);return n>r?Vze(h):h}if(d===u)return sun(d,a,i);var m=uOt(d,u,l,i),p=m.step,g=m.tickMin,x=m.tickMax,y=REe.rangeStep(g,x.add(new Zh(.1).mul(p)),p);return n>r?Vze(y):y}function run(s,t){var n=OX(s,2),r=n[0],a=n[1],i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,l=cOt([r,a]),o=OX(l,2),c=o[0],d=o[1];if(c===-1/0||d===1/0)return[r,a];if(c===d)return[c];var u=Math.max(t,2),h=dOt(new Zh(d).sub(c).div(u-1),i,0),m=[].concat(Hze(REe.rangeStep(new Zh(c),new Zh(d).sub(new Zh(.99).mul(h)),h)),[d]);return r>a?Vze(m):m}var aun=oOt(nun),iun=oOt(run),oun="Invariant failed";function YO(s,t){throw new Error(oun)}var lun=["offset","layout","width","dataKey","data","dataPointFormatter","xAxis","yAxis"];function qU(s){"@babel/helpers - typeof";return qU=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},qU(s)}function Z5e(){return Z5e=Object.assign?Object.assign.bind():function(s){for(var t=1;ts.length)&&(t=s.length);for(var n=0,r=new Array(t);n=0)&&Object.prototype.propertyIsEnumerable.call(s,r)&&(n[r]=s[r])}return n}function pun(s,t){if(s==null)return{};var n={};for(var r in s)if(Object.prototype.hasOwnProperty.call(s,r)){if(t.indexOf(r)>=0)continue;n[r]=s[r]}return n}function gun(s,t){if(!(s instanceof t))throw new TypeError("Cannot call a class as a function")}function xun(s,t){for(var n=0;ns.length)&&(t=s.length);for(var n=0,r=new Array(t);n1&&arguments[1]!==void 0?arguments[1]:[],a=arguments.length>2?arguments[2]:void 0,i=arguments.length>3?arguments[3]:void 0,l=-1,o=(n=r==null?void 0:r.length)!==null&&n!==void 0?n:0;if(o<=1)return 0;if(i&&i.axisType==="angleAxis"&&Math.abs(Math.abs(i.range[1]-i.range[0])-360)<=1e-6)for(var c=i.range,d=0;d0?a[d-1].coordinate:a[o-1].coordinate,h=a[d].coordinate,m=d>=o-1?a[0].coordinate:a[d+1].coordinate,p=void 0;if(db(h-u)!==db(m-h)){var g=[];if(db(m-h)===db(c[1]-c[0])){p=m;var x=h+c[1]-c[0];g[0]=Math.min(x,(x+u)/2),g[1]=Math.max(x,(x+u)/2)}else{p=u;var y=m+c[1]-c[0];g[0]=Math.min(h,(y+h)/2),g[1]=Math.max(h,(y+h)/2)}var v=[Math.min(h,(p+h)/2),Math.max(h,(p+h)/2)];if(t>v[0]&&t<=v[1]||t>=g[0]&&t<=g[1]){l=a[d].index;break}}else{var _=Math.min(u,m),j=Math.max(u,m);if(t>(_+h)/2&&t<=(j+h)/2){l=a[d].index;break}}}else for(var C=0;C0&&C(r[C].coordinate+r[C-1].coordinate)/2&&t<=(r[C].coordinate+r[C+1].coordinate)/2||C===o-1&&t>(r[C].coordinate+r[C-1].coordinate)/2){l=r[C].index;break}return l},rZe=function(t){var n,r=t,a=r.type.displayName,i=(n=t.type)!==null&&n!==void 0&&n.defaultProps?gg(gg({},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},Lun=function(t){var n=t.barSize,r=t.totalSize,a=t.stackGroups,i=a===void 0?{}:a;if(!i)return{};for(var l={},o=Object.keys(i),c=0,d=o.length;c=0});if(v&&v.length){var _=v[0].type.defaultProps,j=_!==void 0?gg(gg({},_),v[0].props):v[0].props,C=j.barSize,A=j[y];l[A]||(l[A]=[]);var M=hc(C)?n:C;l[A].push({item:v[0],stackList:v.slice(1),barSize:hc(M)?void 0:ub(M,r,0)})}}return l},Run=function(t){var n=t.barGap,r=t.barCategoryGap,a=t.bandSize,i=t.sizeList,l=i===void 0?[]:i,o=t.maxBarSize,c=l.length;if(c<1)return null;var d=ub(n,a,0,!0),u,h=[];if(l[0].barSize===+l[0].barSize){var m=!1,p=a/c,g=l.reduce(function(C,A){return C+A.barSize||0},0);g+=(c-1)*d,g>=a&&(g-=(c-1)*d,d=0),g>=a&&p>0&&(m=!0,p*=.9,g=c*p);var x=(a-g)/2>>0,y={offset:x-d,size:0};u=l.reduce(function(C,A){var M={item:A.item,position:{offset:y.offset+y.size+d,size:m?p:A.barSize}},I=[].concat(Mpt(C),[M]);return y=I[I.length-1].position,A.stackList&&A.stackList.length&&A.stackList.forEach(function(P){I.push({item:P,position:y})}),I},h)}else{var v=ub(r,a,0,!0);a-2*v-(c-1)*d<=0&&(d=0);var _=(a-2*v-(c-1)*d)/c;_>1&&(_>>=0);var j=o===+o?Math.min(_,o):_;u=l.reduce(function(C,A,M){var I=[].concat(Mpt(C),[{item:A.item,position:{offset:v+(_+d)*M+(_-j)/2,size:j}}]);return A.stackList&&A.stackList.length&&A.stackList.forEach(function(P){I.push({item:P,position:I[I.length-1].position})}),I},h)}return u},Dun=function(t,n,r,a){var i=r.children,l=r.width,o=r.margin,c=l-(o.left||0)-(o.right||0),d=pOt({children:i,legendWidth:c});if(d){var u=a||{},h=u.width,m=u.height,p=d.align,g=d.verticalAlign,x=d.layout;if((x==="vertical"||x==="horizontal"&&g==="middle")&&p!=="center"&&Ha(t[p]))return gg(gg({},t),{},PB({},p,t[p]+(h||0)));if((x==="horizontal"||x==="vertical"&&p==="center")&&g!=="middle"&&Ha(t[g]))return gg(gg({},t),{},PB({},g,t[g]+(m||0)))}return t},Oun=function(t,n,r){return hc(n)?!0:t==="horizontal"?n==="yAxis":t==="vertical"||r==="x"?n==="xAxis":r==="y"?n==="yAxis":!0},gOt=function(t,n,r,a,i){var l=n.props.children,o=nj(l,ete).filter(function(d){return Oun(a,i,d.props.direction)});if(o&&o.length){var c=o.map(function(d){return d.props.dataKey});return t.reduce(function(d,u){var h=Qg(u,r);if(hc(h))return d;var m=Array.isArray(h)?[IEe(h),kT(h)]:[h,h],p=c.reduce(function(g,x){var y=Qg(u,x,0),v=m[0]-Math.abs(Array.isArray(y)?y[0]:y),_=m[1]+Math.abs(Array.isArray(y)?y[1]:y);return[Math.min(v,g[0]),Math.max(_,g[1])]},[1/0,-1/0]);return[Math.min(p[0],d[0]),Math.max(p[1],d[1])]},[1/0,-1/0])}return null},Fun=function(t,n,r,a,i){var l=n.map(function(o){return gOt(t,o,r,i,a)}).filter(function(o){return!hc(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},xOt=function(t,n,r,a,i){var l=n.map(function(c){var d=c.props.dataKey;return r==="number"&&d&&gOt(t,c,d,a)||GY(t,d,r,i)});if(r==="number")return l.reduce(function(c,d){return[Math.min(c[0],d[0]),Math.max(c[1],d[1])]},[1/0,-1/0]);var o={};return l.reduce(function(c,d){for(var u=0,h=d.length;u=2?db(o[0]-o[1])*2*d:d,n&&(t.ticks||t.niceTicks)){var u=(t.ticks||t.niceTicks).map(function(h){var m=i?i.indexOf(h):h;return{coordinate:a(m)+d,value:h,offset:d}});return u.filter(function(h){return!pV(h.coordinate)})}return t.isCategorical&&t.categoricalDomain?t.categoricalDomain.map(function(h,m){return{coordinate:a(h)+d,value:h,index:m,offset:d}}):a.ticks&&!r?a.ticks(t.tickCount).map(function(h){return{coordinate:a(h)+d,value:h,offset:d}}):a.domain().map(function(h,m){return{coordinate:a(h)+d,value:i?i[h]:h,index:m,offset:d}})},CRe=new WeakMap,oae=function(t,n){if(typeof n!="function")return t;CRe.has(t)||CRe.set(t,new WeakMap);var r=CRe.get(t);if(r.has(n))return r.get(n);var a=function(){t.apply(void 0,arguments),n.apply(void 0,arguments)};return r.set(n,a),a},bOt=function(t,n,r){var a=t.scale,i=t.type,l=t.layout,o=t.axisType;if(a==="auto")return l==="radial"&&o==="radiusAxis"?{scale:MX(),realScaleType:"band"}:l==="radial"&&o==="angleAxis"?{scale:H5e(),realScaleType:"linear"}:i==="category"&&n&&(n.indexOf("LineChart")>=0||n.indexOf("AreaChart")>=0||n.indexOf("ComposedChart")>=0&&!r)?{scale:HY(),realScaleType:"point"}:i==="category"?{scale:MX(),realScaleType:"band"}:{scale:H5e(),realScaleType:"linear"};if(VO(a)){var c="scale".concat(vEe(a));return{scale:(kpt[c]||HY)(),realScaleType:kpt[c]?c:"point"}}return Dl(a)?{scale:a}:{scale:HY(),realScaleType:"point"}},Ipt=1e-4,_Ot=function(t){var n=t.domain();if(!(!n||n.length<=2)){var r=n.length,a=t.range(),i=Math.min(a[0],a[1])-Ipt,l=Math.max(a[0],a[1])+Ipt,o=t(n[0]),c=t(n[r-1]);(ol||cl)&&t.domain([n[0],n[r-1]])}},zun=function(t,n){if(!t)return null;for(var r=0,a=t.length;ra)&&(i[1]=a),i[0]>a&&(i[0]=a),i[1]=0?(t[o][r][0]=i,t[o][r][1]=i+c,i=t[o][r][1]):(t[o][r][0]=l,t[o][r][1]=l+c,l=t[o][r][1])}},Uun=function(t){var n=t.length;if(!(n<=0))for(var r=0,a=t[0].length;r=0?(t[l][r][0]=i,t[l][r][1]=i+o,i=t[l][r][1]):(t[l][r][0]=0,t[l][r][1]=0)}},qun={sign:$un,expand:lQs,none:RU,silhouette:cQs,wiggle:dQs,positive:Uun},Vun=function(t,n,r){var a=n.map(function(o){return o.props.dataKey}),i=qun[r],l=oQs().keys(a).value(function(o,c){return+Qg(o,c,0)}).order(vze).offset(i);return l(t)},Hun=function(t,n,r,a,i,l){if(!t)return null;var o=l?n.reverse():n,c={},d=o.reduce(function(h,m){var p,g=(p=m.type)!==null&&p!==void 0&&p.defaultProps?gg(gg({},m.type.defaultProps),m.props):m.props,x=g.stackId,y=g.hide;if(y)return h;var v=g[r],_=h[v]||{hasStack:!1,stackGroups:{}};if(by(x)){var j=_.stackGroups[x]||{numericAxisId:r,cateAxisId:a,items:[]};j.items.push(m),_.hasStack=!0,_.stackGroups[x]=j}else _.stackGroups[LF("_stackId_")]={numericAxisId:r,cateAxisId:a,items:[m]};return gg(gg({},h),{},PB({},v,_))},c),u={};return Object.keys(d).reduce(function(h,m){var p=d[m];if(p.hasStack){var g={};p.stackGroups=Object.keys(p.stackGroups).reduce(function(x,y){var v=p.stackGroups[y];return gg(gg({},x),{},PB({},y,{numericAxisId:r,cateAxisId:a,items:v.items,stackedData:Vun(t,v.items,i)}))},g)}return gg(gg({},h),{},PB({},m,p))},u)},wOt=function(t,n){var r=n.realScaleType,a=n.type,i=n.tickCount,l=n.originalDomain,o=n.allowDecimals,c=r||n.scale;if(c!=="auto"&&c!=="linear")return null;if(i&&a==="number"&&l&&(l[0]==="auto"||l[1]==="auto")){var d=t.domain();if(!d.length)return null;var u=aun(d,i,o);return t.domain([IEe(u),kT(u)]),{niceTicks:u}}if(i&&a==="number"){var h=t.domain(),m=iun(h,i,o);return{niceTicks:m}}return null};function Q5e(s){var t=s.axis,n=s.ticks,r=s.bandSize,a=s.entry,i=s.index,l=s.dataKey;if(t.type==="category"){if(!t.allowDuplicatedCategory&&t.dataKey&&!hc(a[t.dataKey])){var o=j5e(n,"value",a[t.dataKey]);if(o)return o.coordinate+r/2}return n[i]?n[i].coordinate+r/2:null}var c=Qg(a,hc(l)?t.dataKey:l);return hc(c)?null:t.scale(c)}var Lpt=function(t){var n=t.axis,r=t.ticks,a=t.offset,i=t.bandSize,l=t.entry,o=t.index;if(n.type==="category")return r[o]?r[o].coordinate+a:null;var c=Qg(l,n.dataKey,n.domain[o]);return hc(c)?null:n.scale(c)-i/2+a},Gun=function(t){var n=t.numericAxis,r=n.scale.domain();if(n.type==="number"){var a=Math.min(r[0],r[1]),i=Math.max(r[0],r[1]);return a<=0&&i>=0?0:i<0?i:a}return r[0]},Wun=function(t,n){var r,a=(r=t.type)!==null&&r!==void 0&&r.defaultProps?gg(gg({},t.type.defaultProps),t.props):t.props,i=a.stackId;if(by(i)){var l=n[i];if(l){var o=l.items.indexOf(t);return o>=0?l.stackedData[o]:null}}return null},Kun=function(t){return t.reduce(function(n,r){return[IEe(r.concat([n[0]]).filter(Ha)),kT(r.concat([n[1]]).filter(Ha))]},[1/0,-1/0])},jOt=function(t,n,r){return Object.keys(t).reduce(function(a,i){var l=t[i],o=l.stackedData,c=o.reduce(function(d,u){var h=Kun(u.slice(n,r+1));return[Math.min(d[0],h[0]),Math.max(d[1],h[1])]},[1/0,-1/0]);return[Math.min(c[0],a[0]),Math.max(c[1],a[1])]},[1/0,-1/0]).map(function(a){return a===1/0||a===-1/0?0:a})},Rpt=/^dataMin[\s]*-[\s]*([0-9]+([.]{1}[0-9]+){0,1})$/,Dpt=/^dataMax[\s]*\+[\s]*([0-9]+([.]{1}[0-9]+){0,1})$/,Yze=function(t,n,r){if(Dl(t))return t(n,r);if(!Array.isArray(t))return n;var a=[];if(Ha(t[0]))a[0]=r?t[0]:Math.min(t[0],n[0]);else if(Rpt.test(t[0])){var i=+Rpt.exec(t[0])[1];a[0]=n[0]-i}else Dl(t[0])?a[0]=t[0](n[0]):a[0]=n[0];if(Ha(t[1]))a[1]=r?t[1]:Math.max(t[1],n[1]);else if(Dpt.test(t[1])){var l=+Dpt.exec(t[1])[1];a[1]=n[1]+l}else Dl(t[1])?a[1]=t[1](n[1]):a[1]=n[1];return a},J5e=function(t,n,r){if(t&&t.scale&&t.scale.bandwidth){var a=t.scale.bandwidth();if(!r||a>0)return a}if(t&&n&&n.length>=2){for(var i=PYe(n,function(h){return h.coordinate}),l=1/0,o=1,c=i.length;os.length)&&(t=s.length);for(var n=0,r=new Array(t);n2&&arguments[2]!==void 0?arguments[2]:{top:0,right:0,bottom:0,left:0};return Math.min(Math.abs(t-(r.left||0)-(r.right||0)),Math.abs(n-(r.top||0)-(r.bottom||0)))/2},nhn=function(t,n,r,a,i){var l=t.width,o=t.height,c=t.startAngle,d=t.endAngle,u=ub(t.cx,l,l/2),h=ub(t.cy,o,o/2),m=SOt(l,o,r),p=ub(t.innerRadius,m,0),g=ub(t.outerRadius,m,m*.8),x=Object.keys(n);return x.reduce(function(y,v){var _=n[v],j=_.domain,C=_.reversed,A;if(hc(_.range))a==="angleAxis"?A=[c,d]:a==="radiusAxis"&&(A=[p,g]),C&&(A=[A[1],A[0]]);else{A=_.range;var M=A,I=Xun(M,2);c=I[0],d=I[1]}var P=bOt(_,i),R=P.realScaleType,O=P.scale;O.domain(j).range(A),_Ot(O);var B=wOt(O,xC(xC({},_),{},{realScaleType:R})),U=xC(xC(xC({},_),B),{},{range:A,radius:g,realScaleType:R,scale:O,cx:u,cy:h,innerRadius:p,outerRadius:g,startAngle:c,endAngle:d});return xC(xC({},y),{},kOt({},v,U))},{})},rhn=function(t,n){var r=t.x,a=t.y,i=n.x,l=n.y;return Math.sqrt(Math.pow(r-i,2)+Math.pow(a-l,2))},ahn=function(t,n){var r=t.x,a=t.y,i=n.cx,l=n.cy,o=rhn({x:r,y:a},{x:i,y:l});if(o<=0)return{radius:o};var c=(r-i)/o,d=Math.acos(c);return a>l&&(d=2*Math.PI-d),{radius:o,angle:shn(d),angleInRadian:d}},ihn=function(t){var n=t.startAngle,r=t.endAngle,a=Math.floor(n/360),i=Math.floor(r/360),l=Math.min(a,i);return{startAngle:n-l*360,endAngle:r-l*360}},ohn=function(t,n){var r=n.startAngle,a=n.endAngle,i=Math.floor(r/360),l=Math.floor(a/360),o=Math.min(i,l);return t+o*360},Bpt=function(t,n){var r=t.x,a=t.y,i=ahn({x:r,y:a},n),l=i.radius,o=i.angle,c=n.innerRadius,d=n.outerRadius;if(ld)return!1;if(l===0)return!0;var u=ihn(n),h=u.startAngle,m=u.endAngle,p=o,g;if(h<=m){for(;p>m;)p-=360;for(;p=h&&p<=m}else{for(;p>h;)p-=360;for(;p=m&&p<=h}return g?xC(xC({},n),{},{radius:l,angle:ohn(p,n)}):null},COt=function(t){return!k.isValidElement(t)&&!Dl(t)&&typeof t!="boolean"?t.className:""};function $X(s){"@babel/helpers - typeof";return $X=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},$X(s)}var lhn=["offset"];function chn(s){return mhn(s)||hhn(s)||uhn(s)||dhn()}function dhn(){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 uhn(s,t){if(s){if(typeof s=="string")return Zze(s,t);var n=Object.prototype.toString.call(s).slice(8,-1);if(n==="Object"&&s.constructor&&(n=s.constructor.name),n==="Map"||n==="Set")return Array.from(s);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return Zze(s,t)}}function hhn(s){if(typeof Symbol<"u"&&s[Symbol.iterator]!=null||s["@@iterator"]!=null)return Array.from(s)}function mhn(s){if(Array.isArray(s))return Zze(s)}function Zze(s,t){(t==null||t>s.length)&&(t=s.length);for(var n=0,r=new Array(t);n=0)&&Object.prototype.propertyIsEnumerable.call(s,r)&&(n[r]=s[r])}return n}function phn(s,t){if(s==null)return{};var n={};for(var r in s)if(Object.prototype.hasOwnProperty.call(s,r)){if(t.indexOf(r)>=0)continue;n[r]=s[r]}return n}function $pt(s,t){var n=Object.keys(s);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(s);t&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(s,a).enumerable})),n.push.apply(n,r)}return n}function ay(s){for(var t=1;t=0?1:-1,j,C;a==="insideStart"?(j=p+_*l,C=x):a==="insideEnd"?(j=g-_*l,C=!x):a==="end"&&(j=g+_*l,C=x),C=v<=0?C:!C;var A=zm(d,u,y,j),M=zm(d,u,y,j+(C?1:-1)*359),I="M".concat(A.x,",").concat(A.y,` A`).concat(y,",").concat(y,",0,1,").concat(C?0:1,`, `).concat(M.x,",").concat(M.y),P=hc(t.id)?LF("recharts-radial-line-"):t.id;return zt.createElement("text",UX({},r,{dominantBaseline:"central",className:bc("recharts-radial-bar-label",o)}),zt.createElement("defs",null,zt.createElement("path",{id:P,d:I})),zt.createElement("textPath",{xlinkHref:"#".concat(P)},n))},whn=function(t){var n=t.viewBox,r=t.offset,a=t.position,i=n,l=i.cx,o=i.cy,c=i.innerRadius,d=i.outerRadius,u=i.startAngle,h=i.endAngle,m=(u+h)/2;if(a==="outside"){var p=zm(l,o,d+r,m),g=p.x,x=p.y;return{x:g,y:x,textAnchor:g>=l?"start":"end",verticalAnchor:"middle"}}if(a==="center")return{x:l,y:o,textAnchor:"middle",verticalAnchor:"middle"};if(a==="centerTop")return{x:l,y:o,textAnchor:"middle",verticalAnchor:"start"};if(a==="centerBottom")return{x:l,y:o,textAnchor:"middle",verticalAnchor:"end"};var y=(c+d)/2,v=zm(l,o,y,m),_=v.x,j=v.y;return{x:_,y:j,textAnchor:"middle",verticalAnchor:"middle"}},jhn=function(t){var n=t.viewBox,r=t.parentViewBox,a=t.offset,i=t.position,l=n,o=l.x,c=l.y,d=l.width,u=l.height,h=u>=0?1:-1,m=h*a,p=h>0?"end":"start",g=h>0?"start":"end",x=d>=0?1:-1,y=x*a,v=x>0?"end":"start",_=x>0?"start":"end";if(i==="top"){var j={x:o+d/2,y:c-h*a,textAnchor:"middle",verticalAnchor:p};return ay(ay({},j),r?{height:Math.max(c-r.y,0),width:d}:{})}if(i==="bottom"){var C={x:o+d/2,y:c+u+m,textAnchor:"middle",verticalAnchor:g};return ay(ay({},C),r?{height:Math.max(r.y+r.height-(c+u),0),width:d}:{})}if(i==="left"){var A={x:o-y,y:c+u/2,textAnchor:v,verticalAnchor:"middle"};return ay(ay({},A),r?{width:Math.max(A.x-r.x,0),height:u}:{})}if(i==="right"){var M={x:o+d+y,y:c+u/2,textAnchor:_,verticalAnchor:"middle"};return ay(ay({},M),r?{width:Math.max(r.x+r.width-M.x,0),height:u}:{})}var I=r?{width:d,height:u}:{};return i==="insideLeft"?ay({x:o+y,y:c+u/2,textAnchor:_,verticalAnchor:"middle"},I):i==="insideRight"?ay({x:o+d-y,y:c+u/2,textAnchor:v,verticalAnchor:"middle"},I):i==="insideTop"?ay({x:o+d/2,y:c+m,textAnchor:"middle",verticalAnchor:g},I):i==="insideBottom"?ay({x:o+d/2,y:c+u-m,textAnchor:"middle",verticalAnchor:p},I):i==="insideTopLeft"?ay({x:o+y,y:c+m,textAnchor:_,verticalAnchor:g},I):i==="insideTopRight"?ay({x:o+d-y,y:c+m,textAnchor:v,verticalAnchor:g},I):i==="insideBottomLeft"?ay({x:o+y,y:c+u-m,textAnchor:_,verticalAnchor:p},I):i==="insideBottomRight"?ay({x:o+d-y,y:c+u-m,textAnchor:v,verticalAnchor:p},I):uV(i)&&(Ha(i.x)||mD(i.x))&&(Ha(i.y)||mD(i.y))?ay({x:o+ub(i.x,d),y:c+ub(i.y,u),textAnchor:"end",verticalAnchor:"end"},I):ay({x:o+d/2,y:c+u/2,textAnchor:"middle",verticalAnchor:"middle"},I)},Nhn=function(t){return"cx"in t&&Ha(t.cx)};function h0(s){var t=s.offset,n=t===void 0?5:t,r=fhn(s,lhn),a=ay({offset:n},r),i=a.viewBox,l=a.position,o=a.value,c=a.children,d=a.content,u=a.className,h=u===void 0?"":u,m=a.textBreakAll;if(!i||hc(o)&&hc(c)&&!k.isValidElement(d)&&!Dl(d))return null;if(k.isValidElement(d))return k.cloneElement(d,a);var p;if(Dl(d)){if(p=k.createElement(d,a),k.isValidElement(p))return p}else p=vhn(a);var g=Nhn(i),x=Yo(a,!0);if(g&&(l==="insideStart"||l==="insideEnd"||l==="end"))return _hn(a,p,x);var y=g?whn(a):jhn(a);return zt.createElement(GO,UX({className:bc("recharts-label",h)},x,y,{breakAll:m}),p)}h0.displayName="Label";var AOt=function(t){var n=t.cx,r=t.cy,a=t.angle,i=t.startAngle,l=t.endAngle,o=t.r,c=t.radius,d=t.innerRadius,u=t.outerRadius,h=t.x,m=t.y,p=t.top,g=t.left,x=t.width,y=t.height,v=t.clockWise,_=t.labelViewBox;if(_)return _;if(Ha(x)&&Ha(y)){if(Ha(h)&&Ha(m))return{x:h,y:m,width:x,height:y};if(Ha(p)&&Ha(g))return{x:p,y:g,width:x,height:y}}return Ha(h)&&Ha(m)?{x:h,y:m,width:0,height:0}:Ha(n)&&Ha(r)?{cx:n,cy:r,startAngle:i||a||0,endAngle:l||a||0,innerRadius:d||0,outerRadius:u||c||o||0,clockWise:v}:t.viewBox?t.viewBox:{}},khn=function(t,n){return t?t===!0?zt.createElement(h0,{key:"label-implicit",viewBox:n}):by(t)?zt.createElement(h0,{key:"label-implicit",viewBox:n,value:t}):k.isValidElement(t)?t.type===h0?k.cloneElement(t,{key:"label-implicit",viewBox:n}):zt.createElement(h0,{key:"label-implicit",content:t,viewBox:n}):Dl(t)?zt.createElement(h0,{key:"label-implicit",content:t,viewBox:n}):uV(t)?zt.createElement(h0,UX({viewBox:n},t,{key:"label-implicit"})):null:null},Shn=function(t,n){var r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;if(!t||!t.children&&r&&!t.label)return null;var a=t.children,i=AOt(t),l=nj(a,h0).map(function(c,d){return k.cloneElement(c,{viewBox:n||i,key:"label-".concat(d)})});if(!r)return l;var o=khn(t.label,n||i);return[o].concat(chn(l))};h0.parseViewBox=AOt;h0.renderCallByParent=Shn;function Chn(s){var t=s==null?0:s.length;return t?s[t-1]:void 0}var Ahn=Chn;const Ehn=kd(Ahn);function qX(s){"@babel/helpers - typeof";return qX=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},qX(s)}var Thn=["valueAccessor"],Mhn=["data","dataKey","clockWise","id","textBreakAll"];function Phn(s){return Dhn(s)||Rhn(s)||Lhn(s)||Ihn()}function Ihn(){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 Lhn(s,t){if(s){if(typeof s=="string")return Xze(s,t);var n=Object.prototype.toString.call(s).slice(8,-1);if(n==="Object"&&s.constructor&&(n=s.constructor.name),n==="Map"||n==="Set")return Array.from(s);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return Xze(s,t)}}function Rhn(s){if(typeof Symbol<"u"&&s[Symbol.iterator]!=null||s["@@iterator"]!=null)return Array.from(s)}function Dhn(s){if(Array.isArray(s))return Xze(s)}function Xze(s,t){(t==null||t>s.length)&&(t=s.length);for(var n=0,r=new Array(t);n=0)&&Object.prototype.propertyIsEnumerable.call(s,r)&&(n[r]=s[r])}return n}function Bhn(s,t){if(s==null)return{};var n={};for(var r in s)if(Object.prototype.hasOwnProperty.call(s,r)){if(t.indexOf(r)>=0)continue;n[r]=s[r]}return n}var $hn=function(t){return Array.isArray(t.value)?Ehn(t.value):t.value};function F5(s){var t=s.valueAccessor,n=t===void 0?$hn:t,r=Vpt(s,Thn),a=r.data,i=r.dataKey,l=r.clockWise,o=r.id,c=r.textBreakAll,d=Vpt(r,Mhn);return!a||!a.length?null:zt.createElement(Id,{className:"recharts-label-list"},a.map(function(u,h){var m=hc(i)?n(u,h):Qg(u&&u.payload,i),p=hc(o)?{}:{id:"".concat(o,"-").concat(h)};return zt.createElement(h0,t4e({},Yo(u,!0),d,p,{parentViewBox:u.parentViewBox,value:m,textBreakAll:c,viewBox:h0.parseViewBox(hc(l)?u:qpt(qpt({},u),{},{clockWise:l})),key:"label-".concat(h),index:h}))}))}F5.displayName="LabelList";function Uhn(s,t){return s?s===!0?zt.createElement(F5,{key:"labelList-implicit",data:t}):zt.isValidElement(s)||Dl(s)?zt.createElement(F5,{key:"labelList-implicit",data:t,content:s}):uV(s)?zt.createElement(F5,t4e({data:t},s,{key:"labelList-implicit"})):null:null}function qhn(s,t){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;if(!s||!s.children&&n&&!s.label)return null;var r=s.children,a=nj(r,F5).map(function(l,o){return k.cloneElement(l,{data:t,key:"labelList-".concat(o)})});if(!n)return a;var i=Uhn(s.label,t);return[i].concat(Phn(a))}F5.renderCallByParent=qhn;function VX(s){"@babel/helpers - typeof";return VX=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},VX(s)}function Qze(){return Qze=Object.assign?Object.assign.bind():function(s){for(var t=1;t180),",").concat(+(l>d),`, `).concat(h.x,",").concat(h.y,` `);if(a>0){var p=zm(n,r,a,l),g=zm(n,r,a,d);m+="L ".concat(g.x,",").concat(g.y,` A `).concat(a,",").concat(a,`,0, `).concat(+(Math.abs(c)>180),",").concat(+(l<=d),`, `).concat(p.x,",").concat(p.y," Z")}else m+="L ".concat(n,",").concat(r," Z");return m},Khn=function(t){var n=t.cx,r=t.cy,a=t.innerRadius,i=t.outerRadius,l=t.cornerRadius,o=t.forceCornerRadius,c=t.cornerIsExternal,d=t.startAngle,u=t.endAngle,h=db(u-d),m=lae({cx:n,cy:r,radius:i,angle:d,sign:h,cornerRadius:l,cornerIsExternal:c}),p=m.circleTangency,g=m.lineTangency,x=m.theta,y=lae({cx:n,cy:r,radius:i,angle:u,sign:-h,cornerRadius:l,cornerIsExternal:c}),v=y.circleTangency,_=y.lineTangency,j=y.theta,C=c?Math.abs(d-u):Math.abs(d-u)-x-j;if(C<0)return o?"M ".concat(g.x,",").concat(g.y,` a`).concat(l,",").concat(l,",0,0,1,").concat(l*2,`,0 a`).concat(l,",").concat(l,",0,0,1,").concat(-l*2,`,0 `):EOt({cx:n,cy:r,innerRadius:a,outerRadius:i,startAngle:d,endAngle:u});var A="M ".concat(g.x,",").concat(g.y,` A`).concat(l,",").concat(l,",0,0,").concat(+(h<0),",").concat(p.x,",").concat(p.y,` A`).concat(i,",").concat(i,",0,").concat(+(C>180),",").concat(+(h<0),",").concat(v.x,",").concat(v.y,` A`).concat(l,",").concat(l,",0,0,").concat(+(h<0),",").concat(_.x,",").concat(_.y,` `);if(a>0){var M=lae({cx:n,cy:r,radius:a,angle:d,sign:h,isExternal:!0,cornerRadius:l,cornerIsExternal:c}),I=M.circleTangency,P=M.lineTangency,R=M.theta,O=lae({cx:n,cy:r,radius:a,angle:u,sign:-h,isExternal:!0,cornerRadius:l,cornerIsExternal:c}),B=O.circleTangency,U=O.lineTangency,G=O.theta,H=c?Math.abs(d-u):Math.abs(d-u)-R-G;if(H<0&&l===0)return"".concat(A,"L").concat(n,",").concat(r,"Z");A+="L".concat(U.x,",").concat(U.y,` A`).concat(l,",").concat(l,",0,0,").concat(+(h<0),",").concat(B.x,",").concat(B.y,` A`).concat(a,",").concat(a,",0,").concat(+(H>180),",").concat(+(h>0),",").concat(I.x,",").concat(I.y,` A`).concat(l,",").concat(l,",0,0,").concat(+(h<0),",").concat(P.x,",").concat(P.y,"Z")}else A+="L".concat(n,",").concat(r,"Z");return A},Yhn={cx:0,cy:0,innerRadius:0,outerRadius:0,startAngle:0,endAngle:0,cornerRadius:0,forceCornerRadius:!1,cornerIsExternal:!1},TOt=function(t){var n=Gpt(Gpt({},Yhn),t),r=n.cx,a=n.cy,i=n.innerRadius,l=n.outerRadius,o=n.cornerRadius,c=n.forceCornerRadius,d=n.cornerIsExternal,u=n.startAngle,h=n.endAngle,m=n.className;if(l0&&Math.abs(u-h)<360?y=Khn({cx:r,cy:a,innerRadius:i,outerRadius:l,cornerRadius:Math.min(x,g/2),forceCornerRadius:c,cornerIsExternal:d,startAngle:u,endAngle:h}):y=EOt({cx:r,cy:a,innerRadius:i,outerRadius:l,startAngle:u,endAngle:h}),zt.createElement("path",Qze({},Yo(n,!0),{className:p,d:y,role:"img"}))};function HX(s){"@babel/helpers - typeof";return HX=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},HX(s)}function Jze(){return Jze=Object.assign?Object.assign.bind():function(s){for(var t=1;tlmn.call(s,t));function OF(s,t){return s===t||!s&&!t&&s!==s&&t!==t}const umn="__v",hmn="__o",mmn="_owner",{getOwnPropertyDescriptor:Xpt,keys:Qpt}=Object;function fmn(s,t){return s.byteLength===t.byteLength&&s4e(new Uint8Array(s),new Uint8Array(t))}function pmn(s,t,n){let r=s.length;if(t.length!==r)return!1;for(;r-- >0;)if(!n.equals(s[r],t[r],r,r,s,t,n))return!1;return!0}function gmn(s,t){return s.byteLength===t.byteLength&&s4e(new Uint8Array(s.buffer,s.byteOffset,s.byteLength),new Uint8Array(t.buffer,t.byteOffset,t.byteLength))}function xmn(s,t){return OF(s.getTime(),t.getTime())}function ymn(s,t){return s.name===t.name&&s.message===t.message&&s.cause===t.cause&&s.stack===t.stack}function vmn(s,t){return s===t}function Jpt(s,t,n){const r=s.size;if(r!==t.size)return!1;if(!r)return!0;const a=new Array(r),i=s.entries();let l,o,c=0;for(;(l=i.next())&&!l.done;){const d=t.entries();let u=!1,h=0;for(;(o=d.next())&&!o.done;){if(a[h]){h++;continue}const m=l.value,p=o.value;if(n.equals(m[0],p[0],c,h,s,t,n)&&n.equals(m[1],p[1],m[0],p[0],s,t,n)){u=a[h]=!0;break}h++}if(!u)return!1;c++}return!0}const bmn=OF;function _mn(s,t,n){const r=Qpt(s);let a=r.length;if(Qpt(t).length!==a)return!1;for(;a-- >0;)if(!LOt(s,t,n,r[a]))return!1;return!0}function TG(s,t,n){const r=Zpt(s);let a=r.length;if(Zpt(t).length!==a)return!1;let i,l,o;for(;a-- >0;)if(i=r[a],!LOt(s,t,n,i)||(l=Xpt(s,i),o=Xpt(t,i),(l||o)&&(!l||!o||l.configurable!==o.configurable||l.enumerable!==o.enumerable||l.writable!==o.writable)))return!1;return!0}function wmn(s,t){return OF(s.valueOf(),t.valueOf())}function jmn(s,t){return s.source===t.source&&s.flags===t.flags}function egt(s,t,n){const r=s.size;if(r!==t.size)return!1;if(!r)return!0;const a=new Array(r),i=s.values();let l,o;for(;(l=i.next())&&!l.done;){const c=t.values();let d=!1,u=0;for(;(o=c.next())&&!o.done;){if(!a[u]&&n.equals(l.value,o.value,l.value,o.value,s,t,n)){d=a[u]=!0;break}u++}if(!d)return!1}return!0}function s4e(s,t){let n=s.byteLength;if(t.byteLength!==n||s.byteOffset!==t.byteOffset)return!1;for(;n-- >0;)if(s[n]!==t[n])return!1;return!0}function Nmn(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 LOt(s,t,n,r){return(r===mmn||r===hmn||r===umn)&&(s.$$typeof||t.$$typeof)?!0:dmn(t,r)&&n.equals(s[r],t[r],r,r,s,t,n)}const kmn="[object ArrayBuffer]",Smn="[object Arguments]",Cmn="[object Boolean]",Amn="[object DataView]",Emn="[object Date]",Tmn="[object Error]",Mmn="[object Map]",Pmn="[object Number]",Imn="[object Object]",Lmn="[object RegExp]",Rmn="[object Set]",Dmn="[object String]",Omn={"[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},Fmn="[object URL]",zmn=Object.prototype.toString;function Bmn({areArrayBuffersEqual:s,areArraysEqual:t,areDataViewsEqual:n,areDatesEqual:r,areErrorsEqual:a,areFunctionsEqual:i,areMapsEqual:l,areNumbersEqual:o,areObjectsEqual:c,arePrimitiveWrappersEqual:d,areRegExpsEqual:u,areSetsEqual:h,areTypedArraysEqual:m,areUrlsEqual:p,unknownTagComparators:g}){return function(y,v,_){if(y===v)return!0;if(y==null||v==null)return!1;const j=typeof y;if(j!==typeof v)return!1;if(j!=="object")return j==="number"?o(y,v,_):j==="function"?i(y,v,_):!1;const C=y.constructor;if(C!==v.constructor)return!1;if(C===Object)return c(y,v,_);if(Array.isArray(y))return t(y,v,_);if(C===Date)return r(y,v,_);if(C===RegExp)return u(y,v,_);if(C===Map)return l(y,v,_);if(C===Set)return h(y,v,_);const A=zmn.call(y);if(A===Emn)return r(y,v,_);if(A===Lmn)return u(y,v,_);if(A===Mmn)return l(y,v,_);if(A===Rmn)return h(y,v,_);if(A===Imn)return typeof y.then!="function"&&typeof v.then!="function"&&c(y,v,_);if(A===Fmn)return p(y,v,_);if(A===Tmn)return a(y,v,_);if(A===Smn)return c(y,v,_);if(Omn[A])return m(y,v,_);if(A===kmn)return s(y,v,_);if(A===Amn)return n(y,v,_);if(A===Cmn||A===Pmn||A===Dmn)return d(y,v,_);if(g){let M=g[A];if(!M){const I=cmn(y);I&&(M=g[I])}if(M)return M(y,v,_)}return!1}}function $mn({circular:s,createCustomConfig:t,strict:n}){let r={areArrayBuffersEqual:fmn,areArraysEqual:n?TG:pmn,areDataViewsEqual:gmn,areDatesEqual:xmn,areErrorsEqual:ymn,areFunctionsEqual:vmn,areMapsEqual:n?ARe(Jpt,TG):Jpt,areNumbersEqual:bmn,areObjectsEqual:n?TG:_mn,arePrimitiveWrappersEqual:wmn,areRegExpsEqual:jmn,areSetsEqual:n?ARe(egt,TG):egt,areTypedArraysEqual:n?ARe(s4e,TG):s4e,areUrlsEqual:Nmn,unknownTagComparators:void 0};if(t&&(r=Object.assign({},r,t(r))),s){const a=dae(r.areArraysEqual),i=dae(r.areMapsEqual),l=dae(r.areObjectsEqual),o=dae(r.areSetsEqual);r=Object.assign({},r,{areArraysEqual:a,areMapsEqual:i,areObjectsEqual:l,areSetsEqual:o})}return r}function Umn(s){return function(t,n,r,a,i,l,o){return s(t,n,o)}}function qmn({circular:s,comparator:t,createState:n,equals:r,strict:a}){if(n)return function(o,c){const{cache:d=s?new WeakMap:void 0,meta:u}=n();return t(o,c,{cache:d,equals:r,meta:u,strict:a})};if(s)return function(o,c){return t(o,c,{cache:new WeakMap,equals:r,meta:void 0,strict:a})};const i={cache:void 0,equals:r,meta:void 0,strict:a};return function(o,c){return t(o,c,i)}}const Vmn=x6();x6({strict:!0});x6({circular:!0});x6({circular:!0,strict:!0});x6({createInternalComparator:()=>OF});x6({strict:!0,createInternalComparator:()=>OF});x6({circular:!0,createInternalComparator:()=>OF});x6({circular:!0,createInternalComparator:()=>OF,strict:!0});function x6(s={}){const{circular:t=!1,createInternalComparator:n,createState:r,strict:a=!1}=s,i=$mn(s),l=Bmn(i),o=n?n(l):Umn(l);return qmn({circular:t,comparator:l,createState:r,equals:o,strict:a})}function Hmn(s){typeof requestAnimationFrame<"u"&&requestAnimationFrame(s)}function tgt(s){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,n=-1,r=function a(i){n<0&&(n=i),i-n>t?(s(i),n=-1):Hmn(a)};requestAnimationFrame(r)}function eBe(s){"@babel/helpers - typeof";return eBe=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},eBe(s)}function Gmn(s){return Zmn(s)||Ymn(s)||Kmn(s)||Wmn()}function Wmn(){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 Kmn(s,t){if(s){if(typeof s=="string")return sgt(s,t);var n=Object.prototype.toString.call(s).slice(8,-1);if(n==="Object"&&s.constructor&&(n=s.constructor.name),n==="Map"||n==="Set")return Array.from(s);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return sgt(s,t)}}function sgt(s,t){(t==null||t>s.length)&&(t=s.length);for(var n=0,r=new Array(t);ns.length)&&(t=s.length);for(var n=0,r=new Array(t);n1?1:v<0?0:v},x=function(v){for(var _=v>1?1:v,j=_,C=0;C<8;++C){var A=h(j)-_,M=p(j);if(Math.abs(A-_)0&&arguments[0]!==void 0?arguments[0]:{},n=t.stiff,r=n===void 0?100:n,a=t.damping,i=a===void 0?8:a,l=t.dt,o=l===void 0?17:l,c=function(u,h,m){var p=-(u-h)*r,g=m*i,x=m+(p-g)*o/1e3,y=m*o/1e3+u;return Math.abs(y-h)s.length)&&(t=s.length);for(var n=0,r=new Array(t);n=0)&&Object.prototype.propertyIsEnumerable.call(s,r)&&(n[r]=s[r])}return n}function Cfn(s,t){if(s==null)return{};var n={},r=Object.keys(s),a,i;for(i=0;i=0)&&(n[a]=s[a]);return n}function ERe(s){return Mfn(s)||Tfn(s)||Efn(s)||Afn()}function Afn(){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 Efn(s,t){if(s){if(typeof s=="string")return aBe(s,t);var n=Object.prototype.toString.call(s).slice(8,-1);if(n==="Object"&&s.constructor&&(n=s.constructor.name),n==="Map"||n==="Set")return Array.from(s);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return aBe(s,t)}}function Tfn(s){if(typeof Symbol<"u"&&s[Symbol.iterator]!=null||s["@@iterator"]!=null)return Array.from(s)}function Mfn(s){if(Array.isArray(s))return aBe(s)}function aBe(s,t){(t==null||t>s.length)&&(t=s.length);for(var n=0,r=new Array(t);n"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}function a4e(s){return a4e=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(n){return n.__proto__||Object.getPrototypeOf(n)},a4e(s)}var _k=function(s){Dfn(n,s);var t=Ofn(n);function n(r,a){var i;Pfn(this,n),i=t.call(this,r,a);var l=i.props,o=l.isActive,c=l.attributeName,d=l.from,u=l.to,h=l.steps,m=l.children,p=l.duration;if(i.handleStyleChange=i.handleStyleChange.bind(lBe(i)),i.changeStyle=i.changeStyle.bind(lBe(i)),!o||p<=0)return i.state={style:{}},typeof m=="function"&&(i.state={style:u}),oBe(i);if(h&&h.length)i.state={style:h[0].style};else if(d){if(typeof m=="function")return i.state={style:d},oBe(i);i.state={style:c?DW({},c,d):d}}else i.state={style:{}};return i}return Lfn(n,[{key:"componentDidMount",value:function(){var a=this.props,i=a.isActive,l=a.canBegin;this.mounted=!0,!(!i||!l)&&this.runAnimation(this.props)}},{key:"componentDidUpdate",value:function(a){var i=this.props,l=i.isActive,o=i.canBegin,c=i.attributeName,d=i.shouldReAnimate,u=i.to,h=i.from,m=this.state.style;if(o){if(!l){var p={style:c?DW({},c,u):u};this.state&&m&&(c&&m[c]!==u||!c&&m!==u)&&this.setState(p);return}if(!(Vmn(a.to,u)&&a.canBegin&&a.isActive)){var g=!a.canBegin||!a.isActive;this.manager&&this.manager.stop(),this.stopJSAnimation&&this.stopJSAnimation();var x=g||d?h:a.to;if(this.state&&m){var y={style:c?DW({},c,x):x};(c&&m[c]!==x||!c&&m!==x)&&this.setState(y)}this.runAnimation(hN(hN({},this.props),{},{from:x,begin:0}))}}}},{key:"componentWillUnmount",value:function(){this.mounted=!1;var a=this.props.onAnimationEnd;this.unSubscribe&&this.unSubscribe(),this.manager&&(this.manager.stop(),this.manager=null),this.stopJSAnimation&&this.stopJSAnimation(),a&&a()}},{key:"handleStyleChange",value:function(a){this.changeStyle(a)}},{key:"changeStyle",value:function(a){this.mounted&&this.setState({style:a})}},{key:"runJSAnimation",value:function(a){var i=this,l=a.from,o=a.to,c=a.duration,d=a.easing,u=a.begin,h=a.onAnimationEnd,m=a.onAnimationStart,p=Nfn(l,o,mfn(d),c,this.changeStyle),g=function(){i.stopJSAnimation=p()};this.manager.start([m,u,g,c,h])}},{key:"runStepAnimation",value:function(a){var i=this,l=a.steps,o=a.begin,c=a.onAnimationStart,d=l[0],u=d.style,h=d.duration,m=h===void 0?0:h,p=function(x,y,v){if(v===0)return x;var _=y.duration,j=y.easing,C=j===void 0?"ease":j,A=y.style,M=y.properties,I=y.onAnimationEnd,P=v>0?l[v-1]:y,R=M||Object.keys(A);if(typeof C=="function"||C==="spring")return[].concat(ERe(x),[i.runJSAnimation.bind(i,{from:P.style,to:A,duration:_,easing:C}),_]);var O=agt(R,_,C),B=hN(hN(hN({},P.style),A),{},{transition:O});return[].concat(ERe(x),[B,_,I]).filter(tfn)};return this.manager.start([c].concat(ERe(l.reduce(p,[u,Math.max(m,o)])),[a.onAnimationEnd]))}},{key:"runAnimation",value:function(a){this.manager||(this.manager=Xmn());var i=a.begin,l=a.duration,o=a.attributeName,c=a.to,d=a.easing,u=a.onAnimationStart,h=a.onAnimationEnd,m=a.steps,p=a.children,g=this.manager;if(this.unSubscribe=g.subscribe(this.handleStyleChange),typeof d=="function"||typeof p=="function"||d==="spring"){this.runJSAnimation(a);return}if(m.length>1){this.runStepAnimation(a);return}var x=o?DW({},o,c):c,y=agt(Object.keys(x),l,d);g.start([u,i,hN(hN({},x),{},{transition:y}),l,h])}},{key:"render",value:function(){var a=this.props,i=a.children;a.begin;var l=a.duration;a.attributeName,a.easing;var o=a.isActive;a.steps,a.from,a.to,a.canBegin,a.onAnimationEnd,a.shouldReAnimate,a.onAnimationReStart;var c=Sfn(a,kfn),d=k.Children.count(i),u=this.state.style;if(typeof i=="function")return i(u);if(!o||d===0||l<=0)return i;var h=function(p){var g=p.props,x=g.style,y=x===void 0?{}:x,v=g.className,_=k.cloneElement(p,hN(hN({},c),{},{style:hN(hN({},y),u),className:v}));return _};return d===1?h(k.Children.only(i)):zt.createElement("div",null,k.Children.map(i,function(m){return h(m)}))}}]),n}(k.PureComponent);_k.displayName="Animate";_k.defaultProps={begin:0,duration:1e3,from:"",to:"",attributeName:"",easing:"ease",isActive:!0,canBegin:!0,steps:[],onAnimationEnd:function(){},onAnimationStart:function(){}};_k.propTypes={from:ph.oneOfType([ph.object,ph.string]),to:ph.oneOfType([ph.object,ph.string]),attributeName:ph.string,duration:ph.number,begin:ph.number,easing:ph.oneOfType([ph.string,ph.func]),steps:ph.arrayOf(ph.shape({duration:ph.number.isRequired,style:ph.object.isRequired,easing:ph.oneOfType([ph.oneOf(["ease","ease-in","ease-out","ease-in-out","linear"]),ph.func]),properties:ph.arrayOf("string"),onAnimationEnd:ph.func})),children:ph.oneOfType([ph.node,ph.func]),isActive:ph.bool,canBegin:ph.bool,onAnimationEnd:ph.func,shouldReAnimate:ph.bool,onAnimationStart:ph.func,onAnimationReStart:ph.func};function KX(s){"@babel/helpers - typeof";return KX=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},KX(s)}function i4e(){return i4e=Object.assign?Object.assign.bind():function(s){for(var t=1;ts.length)&&(t=s.length);for(var n=0,r=new Array(t);n=0?1:-1,c=r>=0?1:-1,d=a>=0&&r>=0||a<0&&r<0?1:0,u;if(l>0&&i instanceof Array){for(var h=[0,0,0,0],m=0,p=4;ml?l:i[m];u="M".concat(t,",").concat(n+o*h[0]),h[0]>0&&(u+="A ".concat(h[0],",").concat(h[0],",0,0,").concat(d,",").concat(t+c*h[0],",").concat(n)),u+="L ".concat(t+r-c*h[1],",").concat(n),h[1]>0&&(u+="A ".concat(h[1],",").concat(h[1],",0,0,").concat(d,`, `).concat(t+r,",").concat(n+o*h[1])),u+="L ".concat(t+r,",").concat(n+a-o*h[2]),h[2]>0&&(u+="A ".concat(h[2],",").concat(h[2],",0,0,").concat(d,`, `).concat(t+r-c*h[2],",").concat(n+a)),u+="L ".concat(t+c*h[3],",").concat(n+a),h[3]>0&&(u+="A ".concat(h[3],",").concat(h[3],",0,0,").concat(d,`, `).concat(t,",").concat(n+a-o*h[3])),u+="Z"}else if(l>0&&i===+i&&i>0){var g=Math.min(l,i);u="M ".concat(t,",").concat(n+o*g,` A `).concat(g,",").concat(g,",0,0,").concat(d,",").concat(t+c*g,",").concat(n,` L `).concat(t+r-c*g,",").concat(n,` A `).concat(g,",").concat(g,",0,0,").concat(d,",").concat(t+r,",").concat(n+o*g,` L `).concat(t+r,",").concat(n+a-o*g,` A `).concat(g,",").concat(g,",0,0,").concat(d,",").concat(t+r-c*g,",").concat(n+a,` L `).concat(t+c*g,",").concat(n+a,` A `).concat(g,",").concat(g,",0,0,").concat(d,",").concat(t,",").concat(n+a-o*g," Z")}else u="M ".concat(t,",").concat(n," h ").concat(r," v ").concat(a," h ").concat(-r," Z");return u},Wfn=function(t,n){if(!t||!n)return!1;var r=t.x,a=t.y,i=n.x,l=n.y,o=n.width,c=n.height;if(Math.abs(o)>0&&Math.abs(c)>0){var d=Math.min(i,i+o),u=Math.max(i,i+o),h=Math.min(l,l+c),m=Math.max(l,l+c);return r>=d&&r<=u&&a>=h&&a<=m}return!1},Kfn={x:0,y:0,width:0,height:0,radius:0,isAnimationActive:!1,isUpdateAnimationActive:!1,animationBegin:0,animationDuration:1500,animationEasing:"ease"},aZe=function(t){var n=mgt(mgt({},Kfn),t),r=k.useRef(),a=k.useState(-1),i=zfn(a,2),l=i[0],o=i[1];k.useEffect(function(){if(r.current&&r.current.getTotalLength)try{var C=r.current.getTotalLength();C&&o(C)}catch{}},[]);var c=n.x,d=n.y,u=n.width,h=n.height,m=n.radius,p=n.className,g=n.animationEasing,x=n.animationDuration,y=n.animationBegin,v=n.isAnimationActive,_=n.isUpdateAnimationActive;if(c!==+c||d!==+d||u!==+u||h!==+h||u===0||h===0)return null;var j=bc("recharts-rectangle",p);return _?zt.createElement(_k,{canBegin:l>0,from:{width:u,height:h,x:c,y:d},to:{width:u,height:h,x:c,y:d},duration:x,animationEasing:g,isActive:_},function(C){var A=C.width,M=C.height,I=C.x,P=C.y;return zt.createElement(_k,{canBegin:l>0,from:"0px ".concat(l===-1?1:l,"px"),to:"".concat(l,"px 0px"),attributeName:"strokeDasharray",begin:y,duration:x,isActive:v,easing:g},zt.createElement("path",i4e({},Yo(n,!0),{className:j,d:fgt(I,P,A,M,m),ref:r})))}):zt.createElement("path",i4e({},Yo(n,!0),{className:j,d:fgt(c,d,u,h,m)}))},Yfn=["points","className","baseLinePoints","connectNulls"];function _z(){return _z=Object.assign?Object.assign.bind():function(s){for(var t=1;t=0)&&Object.prototype.propertyIsEnumerable.call(s,r)&&(n[r]=s[r])}return n}function Xfn(s,t){if(s==null)return{};var n={};for(var r in s)if(Object.prototype.hasOwnProperty.call(s,r)){if(t.indexOf(r)>=0)continue;n[r]=s[r]}return n}function pgt(s){return tpn(s)||epn(s)||Jfn(s)||Qfn()}function Qfn(){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 Jfn(s,t){if(s){if(typeof s=="string")return cBe(s,t);var n=Object.prototype.toString.call(s).slice(8,-1);if(n==="Object"&&s.constructor&&(n=s.constructor.name),n==="Map"||n==="Set")return Array.from(s);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return cBe(s,t)}}function epn(s){if(typeof Symbol<"u"&&s[Symbol.iterator]!=null||s["@@iterator"]!=null)return Array.from(s)}function tpn(s){if(Array.isArray(s))return cBe(s)}function cBe(s,t){(t==null||t>s.length)&&(t=s.length);for(var n=0,r=new Array(t);n0&&arguments[0]!==void 0?arguments[0]:[],n=[[]];return t.forEach(function(r){ggt(r)?n[n.length-1].push(r):n[n.length-1].length>0&&n.push([])}),ggt(t[0])&&n[n.length-1].push(t[0]),n[n.length-1].length<=0&&(n=n.slice(0,-1)),n},KY=function(t,n){var r=spn(t);n&&(r=[r.reduce(function(i,l){return[].concat(pgt(i),pgt(l))},[])]);var a=r.map(function(i){return i.reduce(function(l,o,c){return"".concat(l).concat(c===0?"M":"L").concat(o.x,",").concat(o.y)},"")}).join("");return r.length===1?"".concat(a,"Z"):a},npn=function(t,n,r){var a=KY(t,r);return"".concat(a.slice(-1)==="Z"?a.slice(0,-1):a,"L").concat(KY(n.reverse(),r).slice(1))},rpn=function(t){var n=t.points,r=t.className,a=t.baseLinePoints,i=t.connectNulls,l=Zfn(t,Yfn);if(!n||!n.length)return null;var o=bc("recharts-polygon",r);if(a&&a.length){var c=l.stroke&&l.stroke!=="none",d=npn(n,a,i);return zt.createElement("g",{className:o},zt.createElement("path",_z({},Yo(l,!0),{fill:d.slice(-1)==="Z"?l.fill:"none",stroke:"none",d})),c?zt.createElement("path",_z({},Yo(l,!0),{fill:"none",d:KY(n,i)})):null,c?zt.createElement("path",_z({},Yo(l,!0),{fill:"none",d:KY(a,i)})):null)}var u=KY(n,i);return zt.createElement("path",_z({},Yo(l,!0),{fill:u.slice(-1)==="Z"?l.fill:"none",className:o,d:u}))};function dBe(){return dBe=Object.assign?Object.assign.bind():function(s){for(var t=1;t=0)&&Object.prototype.propertyIsEnumerable.call(s,r)&&(n[r]=s[r])}return n}function upn(s,t){if(s==null)return{};var n={};for(var r in s)if(Object.prototype.hasOwnProperty.call(s,r)){if(t.indexOf(r)>=0)continue;n[r]=s[r]}return n}var hpn=function(t,n,r,a,i,l){return"M".concat(t,",").concat(i,"v").concat(a,"M").concat(l,",").concat(n,"h").concat(r)},mpn=function(t){var n=t.x,r=n===void 0?0:n,a=t.y,i=a===void 0?0:a,l=t.top,o=l===void 0?0:l,c=t.left,d=c===void 0?0:c,u=t.width,h=u===void 0?0:u,m=t.height,p=m===void 0?0:m,g=t.className,x=dpn(t,apn),y=ipn({x:r,y:i,top:o,left:d,width:h,height:p},x);return!Ha(r)||!Ha(i)||!Ha(h)||!Ha(p)||!Ha(o)||!Ha(d)?null:zt.createElement("path",uBe({},Yo(y,!0),{className:bc("recharts-cross",g),d:hpn(r,i,h,p,o,d)}))},fpn=PEe,ppn=Q8t,gpn=i4;function xpn(s,t){return s&&s.length?fpn(s,gpn(t),ppn):void 0}var ypn=xpn;const vpn=kd(ypn);var bpn=PEe,_pn=i4,wpn=J8t;function jpn(s,t){return s&&s.length?bpn(s,_pn(t),wpn):void 0}var Npn=jpn;const kpn=kd(Npn);var Spn=["cx","cy","angle","ticks","axisLine"],Cpn=["ticks","tick","angle","tickFormatter","stroke"];function HU(s){"@babel/helpers - typeof";return HU=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},HU(s)}function YY(){return YY=Object.assign?Object.assign.bind():function(s){for(var t=1;t=0)&&Object.prototype.propertyIsEnumerable.call(s,r)&&(n[r]=s[r])}return n}function Apn(s,t){if(s==null)return{};var n={};for(var r in s)if(Object.prototype.hasOwnProperty.call(s,r)){if(t.indexOf(r)>=0)continue;n[r]=s[r]}return n}function Epn(s,t){if(!(s instanceof t))throw new TypeError("Cannot call a class as a function")}function bgt(s,t){for(var n=0;njgt?l=a==="outer"?"start":"end":i<-jgt?l=a==="outer"?"end":"start":l="middle",l}},{key:"renderAxisLine",value:function(){var r=this.props,a=r.cx,i=r.cy,l=r.radius,o=r.axisLine,c=r.axisLineType,d=uP(uP({},Yo(this.props,!1)),{},{fill:"none"},Yo(o,!1));if(c==="circle")return zt.createElement(tte,KR({className:"recharts-polar-angle-axis-line"},d,{cx:a,cy:i,r:l}));var u=this.props.ticks,h=u.map(function(m){return zm(a,i,l,m.coordinate)});return zt.createElement(rpn,KR({className:"recharts-polar-angle-axis-line"},d,{points:h}))}},{key:"renderTicks",value:function(){var r=this,a=this.props,i=a.ticks,l=a.tick,o=a.tickLine,c=a.tickFormatter,d=a.stroke,u=Yo(this.props,!1),h=Yo(l,!1),m=uP(uP({},u),{},{fill:"none"},Yo(o,!1)),p=i.map(function(g,x){var y=r.getTickLineCoord(g),v=r.getTickTextAnchor(g),_=uP(uP(uP({textAnchor:v},u),{},{stroke:"none",fill:d},h),{},{index:x,payload:g,x:y.x2,y:y.y2});return zt.createElement(Id,KR({className:bc("recharts-polar-angle-axis-tick",COt(l)),key:"tick-".concat(g.coordinate)},HO(r.props,g,x)),o&&zt.createElement("line",KR({className:"recharts-polar-angle-axis-tick-line"},m,y)),l&&t.renderTickItem(l,_,c?c(g.value,x):g.value))});return zt.createElement(Id,{className:"recharts-polar-angle-axis-ticks"},p)}},{key:"render",value:function(){var r=this.props,a=r.ticks,i=r.radius,l=r.axisLine;return i<=0||!a||!a.length?null:zt.createElement(Id,{className:bc("recharts-polar-angle-axis",this.props.className)},l&&this.renderAxisLine(),this.renderTicks())}}],[{key:"renderTickItem",value:function(r,a,i){var l;return zt.isValidElement(r)?l=zt.cloneElement(r,a):Dl(r)?l=r(a):l=zt.createElement(GO,KR({},a,{className:"recharts-polar-angle-axis-tick-value"}),i),l}}])}(k.PureComponent);FEe(zEe,"displayName","PolarAngleAxis");FEe(zEe,"axisType","angleAxis");FEe(zEe,"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 Vpn=YDt,Hpn=Vpn(Object.getPrototypeOf,Object),Gpn=Hpn,Wpn=uA,Kpn=Gpn,Ypn=hA,Zpn="[object Object]",Xpn=Function.prototype,Qpn=Object.prototype,HOt=Xpn.toString,Jpn=Qpn.hasOwnProperty,egn=HOt.call(Object);function tgn(s){if(!Ypn(s)||Wpn(s)!=Zpn)return!1;var t=Kpn(s);if(t===null)return!0;var n=Jpn.call(t,"constructor")&&t.constructor;return typeof n=="function"&&n instanceof n&&HOt.call(n)==egn}var sgn=tgn;const ngn=kd(sgn);var rgn=uA,agn=hA,ign="[object Boolean]";function ogn(s){return s===!0||s===!1||agn(s)&&rgn(s)==ign}var lgn=ogn;const cgn=kd(lgn);function ZX(s){"@babel/helpers - typeof";return ZX=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},ZX(s)}function c4e(){return c4e=Object.assign?Object.assign.bind():function(s){for(var t=1;ts.length)&&(t=s.length);for(var n=0,r=new Array(t);n0,from:{upperWidth:0,lowerWidth:0,height:m,x:c,y:d},to:{upperWidth:u,lowerWidth:h,height:m,x:c,y:d},duration:x,animationEasing:g,isActive:v},function(j){var C=j.upperWidth,A=j.lowerWidth,M=j.height,I=j.x,P=j.y;return zt.createElement(_k,{canBegin:l>0,from:"0px ".concat(l===-1?1:l,"px"),to:"".concat(l,"px 0px"),attributeName:"strokeDasharray",begin:y,duration:x,easing:g},zt.createElement("path",c4e({},Yo(n,!0),{className:_,d:Cgt(I,P,C,A,M),ref:r})))}):zt.createElement("g",null,zt.createElement("path",c4e({},Yo(n,!0),{className:_,d:Cgt(c,d,u,h,m)})))},bgn=["option","shapeType","propTransformer","activeClassName","isActive"];function XX(s){"@babel/helpers - typeof";return XX=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},XX(s)}function _gn(s,t){if(s==null)return{};var n=wgn(s,t),r,a;if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(s);for(a=0;a=0)&&Object.prototype.propertyIsEnumerable.call(s,r)&&(n[r]=s[r])}return n}function wgn(s,t){if(s==null)return{};var n={};for(var r in s)if(Object.prototype.hasOwnProperty.call(s,r)){if(t.indexOf(r)>=0)continue;n[r]=s[r]}return n}function Agt(s,t){var n=Object.keys(s);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(s);t&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(s,a).enumerable})),n.push.apply(n,r)}return n}function d4e(s){for(var t=1;t0?sj(j,"paddingAngle",0):0;if(A){var I=xy(A.endAngle-A.startAngle,j.endAngle-j.startAngle),P=Lm(Lm({},j),{},{startAngle:_+M,endAngle:_+I(x)+M});y.push(P),_=P.endAngle}else{var R=j.endAngle,O=j.startAngle,B=xy(0,R-O),U=B(x),G=Lm(Lm({},j),{},{startAngle:_+M,endAngle:_+U+M});y.push(G),_=G.endAngle}}),zt.createElement(Id,null,r.renderSectorsStatically(y))})}},{key:"attachKeyboardHandlers",value:function(r){var a=this;r.onkeydown=function(i){if(!i.altKey)switch(i.key){case"ArrowLeft":{var l=++a.state.sectorToFocus%a.sectorRefs.length;a.sectorRefs[l].focus(),a.setState({sectorToFocus:l});break}case"ArrowRight":{var o=--a.state.sectorToFocus<0?a.sectorRefs.length-1:a.state.sectorToFocus%a.sectorRefs.length;a.sectorRefs[o].focus(),a.setState({sectorToFocus:o});break}case"Escape":{a.sectorRefs[a.state.sectorToFocus].blur(),a.setState({sectorToFocus:0});break}}}}},{key:"renderSectors",value:function(){var r=this.props,a=r.sectors,i=r.isAnimationActive,l=this.state.prevSectors;return i&&a&&a.length&&(!l||!WO(l,a))?this.renderSectorsWithAnimation():this.renderSectorsStatically(a)}},{key:"componentDidMount",value:function(){this.pieRef&&this.attachKeyboardHandlers(this.pieRef)}},{key:"render",value:function(){var r=this,a=this.props,i=a.hide,l=a.sectors,o=a.className,c=a.label,d=a.cx,u=a.cy,h=a.innerRadius,m=a.outerRadius,p=a.isAnimationActive,g=this.state.isAnimationFinished;if(i||!l||!l.length||!Ha(d)||!Ha(u)||!Ha(h)||!Ha(m))return null;var x=bc("recharts-pie",o);return zt.createElement(Id,{tabIndex:this.props.rootTabIndex,className:x,ref:function(v){r.pieRef=v}},this.renderSectors(),c&&this.renderLabels(l),h0.renderCallByParent(this.props,null,!1),(!p||g)&&F5.renderCallByParent(this.props,l,!1))}}],[{key:"getDerivedStateFromProps",value:function(r,a){return a.prevIsAnimationActive!==r.isAnimationActive?{prevIsAnimationActive:r.isAnimationActive,prevAnimationId:r.animationId,curSectors:r.sectors,prevSectors:[],isAnimationFinished:!0}:r.isAnimationActive&&r.animationId!==a.prevAnimationId?{prevAnimationId:r.animationId,curSectors:r.sectors,prevSectors:a.curSectors,isAnimationFinished:!0}:r.sectors!==a.curSectors?{curSectors:r.sectors,isAnimationFinished:!0}:null}},{key:"getTextAnchor",value:function(r,a){return r>a?"start":r=360?_:_-1)*c,C=y-_*p-j,A=a.reduce(function(P,R){var O=Qg(R,v,0);return P+(Ha(O)?O:0)},0),M;if(A>0){var I;M=a.map(function(P,R){var O=Qg(P,v,0),B=Qg(P,u,R),U=(Ha(O)?O:0)/A,G;R?G=I.endAngle+db(x)*c*(O!==0?1:0):G=l;var H=G+db(x)*((O!==0?p:0)+U*C),Y=(G+H)/2,se=(g.innerRadius+g.outerRadius)/2,ee=[{name:B,value:O,payload:P,dataKey:v,type:m}],oe=zm(g.cx,g.cy,se,Y);return I=Lm(Lm(Lm({percent:U,cornerRadius:i,name:B,tooltipPayload:ee,midAngle:Y,middleRadius:se,tooltipPosition:oe},P),g),{},{value:Qg(P,v),startAngle:G,endAngle:H,payload:P,paddingAngle:db(x)*c}),I})}return Lm(Lm({},g),{},{sectors:M,data:a})});var qgn=Math.ceil,Vgn=Math.max;function Hgn(s,t,n,r){for(var a=-1,i=Vgn(qgn((t-s)/(n||1)),0),l=Array(i);i--;)l[r?i:++a]=s,s+=n;return l}var Ggn=Hgn,Wgn=f8t,Pgt=1/0,Kgn=17976931348623157e292;function Ygn(s){if(!s)return s===0?s:0;if(s=Wgn(s),s===Pgt||s===-Pgt){var t=s<0?-1:1;return t*Kgn}return s===s?s:0}var YOt=Ygn,Zgn=Ggn,Xgn=kEe,TRe=YOt;function Qgn(s){return function(t,n,r){return r&&typeof r!="number"&&Xgn(t,n,r)&&(n=r=void 0),t=TRe(t),n===void 0?(n=t,t=0):n=TRe(n),r=r===void 0?t0&&r.handleDrag(a.changedTouches[0])}),_w(r,"handleDragEnd",function(){r.setState({isTravellerMoving:!1,isSlideMoving:!1},function(){var a=r.props,i=a.endIndex,l=a.onDragEnd,o=a.startIndex;l==null||l({endIndex:i,startIndex:o})}),r.detachDragEndListener()}),_w(r,"handleLeaveWrapper",function(){(r.state.isTravellerMoving||r.state.isSlideMoving)&&(r.leaveTimer=window.setTimeout(r.handleDragEnd,r.props.leaveTimeOut))}),_w(r,"handleEnterSlideOrTraveller",function(){r.setState({isTextActive:!0})}),_w(r,"handleLeaveSlideOrTraveller",function(){r.setState({isTextActive:!1})}),_w(r,"handleSlideDragStart",function(a){var i=Ogt(a)?a.changedTouches[0]:a;r.setState({isTravellerMoving:!1,isSlideMoving:!0,slideMoveStartX:i.pageX}),r.attachDragEndListener()}),r.travellerDragStartHandlers={startX:r.handleTravellerDragStart.bind(r,"startX"),endX:r.handleTravellerDragStart.bind(r,"endX")},r.state={},r}return hxn(t,s),lxn(t,[{key:"componentWillUnmount",value:function(){this.leaveTimer&&(clearTimeout(this.leaveTimer),this.leaveTimer=null),this.detachDragEndListener()}},{key:"getIndex",value:function(r){var a=r.startX,i=r.endX,l=this.state.scaleValues,o=this.props,c=o.gap,d=o.data,u=d.length-1,h=Math.min(a,i),m=Math.max(a,i),p=t.getIndexInRange(l,h),g=t.getIndexInRange(l,m);return{startIndex:p-p%c,endIndex:g===u?u:g-g%c}}},{key:"getTextOfTick",value:function(r){var a=this.props,i=a.data,l=a.tickFormatter,o=a.dataKey,c=Qg(i[r],o,r);return Dl(l)?l(c,r):c}},{key:"attachDragEndListener",value:function(){window.addEventListener("mouseup",this.handleDragEnd,!0),window.addEventListener("touchend",this.handleDragEnd,!0),window.addEventListener("mousemove",this.handleDrag,!0)}},{key:"detachDragEndListener",value:function(){window.removeEventListener("mouseup",this.handleDragEnd,!0),window.removeEventListener("touchend",this.handleDragEnd,!0),window.removeEventListener("mousemove",this.handleDrag,!0)}},{key:"handleSlideDrag",value:function(r){var a=this.state,i=a.slideMoveStartX,l=a.startX,o=a.endX,c=this.props,d=c.x,u=c.width,h=c.travellerWidth,m=c.startIndex,p=c.endIndex,g=c.onChange,x=r.pageX-i;x>0?x=Math.min(x,d+u-h-o,d+u-h-l):x<0&&(x=Math.max(x,d-l,d-o));var y=this.getIndex({startX:l+x,endX:o+x});(y.startIndex!==m||y.endIndex!==p)&&g&&g(y),this.setState({startX:l+x,endX:o+x,slideMoveStartX:r.pageX})}},{key:"handleTravellerDragStart",value:function(r,a){var i=Ogt(a)?a.changedTouches[0]:a;this.setState({isSlideMoving:!1,isTravellerMoving:!0,movingTravellerId:r,brushMoveStartX:i.pageX}),this.attachDragEndListener()}},{key:"handleTravellerMove",value:function(r){var a=this.state,i=a.brushMoveStartX,l=a.movingTravellerId,o=a.endX,c=a.startX,d=this.state[l],u=this.props,h=u.x,m=u.width,p=u.travellerWidth,g=u.onChange,x=u.gap,y=u.data,v={startX:this.state.startX,endX:this.state.endX},_=r.pageX-i;_>0?_=Math.min(_,h+m-p-d):_<0&&(_=Math.max(_,h-d)),v[l]=d+_;var j=this.getIndex(v),C=j.startIndex,A=j.endIndex,M=function(){var P=y.length-1;return l==="startX"&&(o>c?C%x===0:A%x===0)||oc?A%x===0:C%x===0)||o>c&&A===P};this.setState(_w(_w({},l,d+_),"brushMoveStartX",r.pageX),function(){g&&M()&&g(j)})}},{key:"handleTravellerMoveKeyboard",value:function(r,a){var i=this,l=this.state,o=l.scaleValues,c=l.startX,d=l.endX,u=this.state[a],h=o.indexOf(u);if(h!==-1){var m=h+r;if(!(m===-1||m>=o.length)){var p=o[m];a==="startX"&&p>=d||a==="endX"&&p<=c||this.setState(_w({},a,p),function(){i.props.onChange(i.getIndex({startX:i.state.startX,endX:i.state.endX}))})}}}},{key:"renderBackground",value:function(){var r=this.props,a=r.x,i=r.y,l=r.width,o=r.height,c=r.fill,d=r.stroke;return zt.createElement("rect",{stroke:d,fill:c,x:a,y:i,width:l,height:o})}},{key:"renderPanorama",value:function(){var r=this.props,a=r.x,i=r.y,l=r.width,o=r.height,c=r.data,d=r.children,u=r.padding,h=k.Children.only(d);return h?zt.cloneElement(h,{x:a,y:i,width:l,height:o,margin:u,compact:!0,data:c}):null}},{key:"renderTravellerLayer",value:function(r,a){var i,l,o=this,c=this.props,d=c.y,u=c.travellerWidth,h=c.height,m=c.traveller,p=c.ariaLabel,g=c.data,x=c.startIndex,y=c.endIndex,v=Math.max(r,this.props.x),_=MRe(MRe({},Yo(this.props,!1)),{},{x:v,y:d,width:u,height:h}),j=p||"Min value: ".concat((i=g[x])===null||i===void 0?void 0:i.name,", Max value: ").concat((l=g[y])===null||l===void 0?void 0:l.name);return zt.createElement(Id,{tabIndex:0,role:"slider","aria-label":j,"aria-valuenow":r,className:"recharts-brush-traveller",onMouseEnter:this.handleEnterSlideOrTraveller,onMouseLeave:this.handleLeaveSlideOrTraveller,onMouseDown:this.travellerDragStartHandlers[a],onTouchStart:this.travellerDragStartHandlers[a],onKeyDown:function(A){["ArrowLeft","ArrowRight"].includes(A.key)&&(A.preventDefault(),A.stopPropagation(),o.handleTravellerMoveKeyboard(A.key==="ArrowRight"?1:-1,a))},onFocus:function(){o.setState({isTravellerFocused:!0})},onBlur:function(){o.setState({isTravellerFocused:!1})},style:{cursor:"col-resize"}},t.renderTraveller(m,_))}},{key:"renderSlide",value:function(r,a){var i=this.props,l=i.y,o=i.height,c=i.stroke,d=i.travellerWidth,u=Math.min(r,a)+d,h=Math.max(Math.abs(a-r)-d,0);return zt.createElement("rect",{className:"recharts-brush-slide",onMouseEnter:this.handleEnterSlideOrTraveller,onMouseLeave:this.handleLeaveSlideOrTraveller,onMouseDown:this.handleSlideDragStart,onTouchStart:this.handleSlideDragStart,style:{cursor:"move"},stroke:"none",fill:c,fillOpacity:.2,x:u,y:l,width:h,height:o})}},{key:"renderText",value:function(){var r=this.props,a=r.startIndex,i=r.endIndex,l=r.y,o=r.height,c=r.travellerWidth,d=r.stroke,u=this.state,h=u.startX,m=u.endX,p=5,g={pointerEvents:"none",fill:d};return zt.createElement(Id,{className:"recharts-brush-texts"},zt.createElement(GO,m4e({textAnchor:"end",verticalAnchor:"middle",x:Math.min(h,m)-p,y:l+o/2},g),this.getTextOfTick(a)),zt.createElement(GO,m4e({textAnchor:"start",verticalAnchor:"middle",x:Math.max(h,m)+c+p,y:l+o/2},g),this.getTextOfTick(i)))}},{key:"render",value:function(){var r=this.props,a=r.data,i=r.className,l=r.children,o=r.x,c=r.y,d=r.width,u=r.height,h=r.alwaysShowText,m=this.state,p=m.startX,g=m.endX,x=m.isTextActive,y=m.isSlideMoving,v=m.isTravellerMoving,_=m.isTravellerFocused;if(!a||!a.length||!Ha(o)||!Ha(c)||!Ha(d)||!Ha(u)||d<=0||u<=0)return null;var j=bc("recharts-brush",i),C=zt.Children.count(l)===1,A=ixn("userSelect","none");return zt.createElement(Id,{className:j,onMouseLeave:this.handleLeaveWrapper,onTouchMove:this.handleTouchMove,style:A},this.renderBackground(),C&&this.renderPanorama(),this.renderSlide(p,g),this.renderTravellerLayer(p,"startX"),this.renderTravellerLayer(g,"endX"),(x||y||v||_||h)&&this.renderText())}}],[{key:"renderDefaultTraveller",value:function(r){var a=r.x,i=r.y,l=r.width,o=r.height,c=r.stroke,d=Math.floor(i+o/2)-1;return zt.createElement(zt.Fragment,null,zt.createElement("rect",{x:a,y:i,width:l,height:o,fill:c,stroke:"none"}),zt.createElement("line",{x1:a+1,y1:d,x2:a+l-1,y2:d,fill:"none",stroke:"#fff"}),zt.createElement("line",{x1:a+1,y1:d+2,x2:a+l-1,y2:d+2,fill:"none",stroke:"#fff"}))}},{key:"renderTraveller",value:function(r,a){var i;return zt.isValidElement(r)?i=zt.cloneElement(r,a):Dl(r)?i=r(a):i=t.renderDefaultTraveller(a),i}},{key:"getDerivedStateFromProps",value:function(r,a){var i=r.data,l=r.width,o=r.x,c=r.travellerWidth,d=r.updateId,u=r.startIndex,h=r.endIndex;if(i!==a.prevData||d!==a.prevUpdateId)return MRe({prevData:i,prevTravellerWidth:c,prevUpdateId:d,prevX:o,prevWidth:l},i&&i.length?fxn({data:i,width:l,x:o,travellerWidth:c,startIndex:u,endIndex:h}):{scale:null,scaleValues:null});if(a.scale&&(l!==a.prevWidth||o!==a.prevX||c!==a.prevTravellerWidth)){a.scale.range([o,o+l-c]);var m=a.scale.domain().map(function(p){return a.scale(p)});return{prevData:i,prevTravellerWidth:c,prevUpdateId:d,prevX:o,prevWidth:l,startX:a.scale(r.startIndex),endX:a.scale(r.endIndex),scaleValues:m}}return null}},{key:"getIndexInRange",value:function(r,a){for(var i=r.length,l=0,o=i-1;o-l>1;){var c=Math.floor((l+o)/2);r[c]>a?o=c:l=c}return a>=r[o]?o:l}}])}(k.PureComponent);_w(YU,"displayName","Brush");_w(YU,"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 pxn=MYe;function gxn(s,t){var n;return pxn(s,function(r,a,i){return n=t(r,a,i),!n}),!!n}var xxn=gxn,yxn=$Dt,vxn=i4,bxn=xxn,_xn=B_,wxn=kEe;function jxn(s,t,n){var r=_xn(s)?yxn:bxn;return n&&wxn(s,t,n)&&(t=void 0),r(s,vxn(t))}var Nxn=jxn;const kxn=kd(Nxn);var z5=function(t,n){var r=t.alwaysShow,a=t.ifOverflow;return r&&(a="extendDomain"),a===n},Fgt=c8t;function Sxn(s,t,n){t=="__proto__"&&Fgt?Fgt(s,t,{configurable:!0,enumerable:!0,value:n,writable:!0}):s[t]=n}var Cxn=Sxn,Axn=Cxn,Exn=o8t,Txn=i4;function Mxn(s,t){var n={};return t=Txn(t),Exn(s,function(r,a,i){Axn(n,a,t(r,a,i))}),n}var Pxn=Mxn;const Ixn=kd(Pxn);function Lxn(s,t){for(var n=-1,r=s==null?0:s.length;++n=0)&&Object.prototype.propertyIsEnumerable.call(s,r)&&(n[r]=s[r])}return n}function Xxn(s,t){if(s==null)return{};var n={};for(var r in s)if(Object.prototype.hasOwnProperty.call(s,r)){if(t.indexOf(r)>=0)continue;n[r]=s[r]}return n}function Qxn(s,t){var n=s.x,r=s.y,a=Zxn(s,Gxn),i="".concat(n),l=parseInt(i,10),o="".concat(r),c=parseInt(o,10),d="".concat(t.height||a.height),u=parseInt(d,10),h="".concat(t.width||a.width),m=parseInt(h,10);return MG(MG(MG(MG(MG({},t),a),l?{x:l}:{}),c?{y:c}:{}),{},{height:u,width:m,name:t.name,radius:t.radius})}function Bgt(s){return zt.createElement(GOt,gBe({shapeType:"rectangle",propTransformer:Qxn,activeClassName:"recharts-active-bar"},s))}var Jxn=function(t){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0;return function(r,a){if(typeof t=="number")return t;var i=Ha(r)||_Zs(r);return i?t(r,a):(i||YO(),n)}},eyn=["value","background"],eFt;function ZU(s){"@babel/helpers - typeof";return ZU=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},ZU(s)}function tyn(s,t){if(s==null)return{};var n=syn(s,t),r,a;if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(s);for(a=0;a=0)&&Object.prototype.propertyIsEnumerable.call(s,r)&&(n[r]=s[r])}return n}function syn(s,t){if(s==null)return{};var n={};for(var r in s)if(Object.prototype.hasOwnProperty.call(s,r)){if(t.indexOf(r)>=0)continue;n[r]=s[r]}return n}function p4e(){return p4e=Object.assign?Object.assign.bind():function(s){for(var t=1;t0&&Math.abs(Y)0&&Math.abs(H)0&&(G=Math.min((_e||0)-(H[ve-1]||0),G))}),Number.isFinite(G)){var Y=G/U,se=x.layout==="vertical"?r.height:r.width;if(x.padding==="gap"&&(I=Y*se/2),x.padding==="no-gap"){var ee=ub(t.barCategoryGap,Y*se),oe=Y*se/2;I=oe-ee-(oe-ee)/se*ee}}}a==="xAxis"?P=[r.left+(j.left||0)+(I||0),r.left+r.width-(j.right||0)-(I||0)]:a==="yAxis"?P=c==="horizontal"?[r.top+r.height-(j.bottom||0),r.top+(j.top||0)]:[r.top+(j.top||0)+(I||0),r.top+r.height-(j.bottom||0)-(I||0)]:P=x.range,A&&(P=[P[1],P[0]]);var me=bOt(x,i,m),Q=me.scale,te=me.realScaleType;Q.domain(v).range(P),_Ot(Q);var le=wOt(Q,UN(UN({},x),{},{realScaleType:te}));a==="xAxis"?(B=y==="top"&&!C||y==="bottom"&&C,R=r.left,O=h[M]-B*x.height):a==="yAxis"&&(B=y==="left"&&!C||y==="right"&&C,R=h[M]-B*x.width,O=r.top);var fe=UN(UN(UN({},x),le),{},{realScaleType:te,x:R,y:O,scale:Q,width:a==="xAxis"?r.width:x.width,height:a==="yAxis"?r.height:x.height});return fe.bandSize=J5e(fe,le),!x.hide&&a==="xAxis"?h[M]+=(B?-1:1)*fe.height:x.hide||(h[M]+=(B?-1:1)*fe.width),UN(UN({},p),{},UEe({},g,fe))},{})},rFt=function(t,n){var r=t.x,a=t.y,i=n.x,l=n.y;return{x:Math.min(r,i),y:Math.min(a,l),width:Math.abs(i-r),height:Math.abs(l-a)}},myn=function(t){var n=t.x1,r=t.y1,a=t.x2,i=t.y2;return rFt({x:n,y:r},{x:a,y:i})},aFt=function(){function s(t){dyn(this,s),this.scale=t}return uyn(s,[{key:"domain",get:function(){return this.scale.domain}},{key:"range",get:function(){return this.scale.range}},{key:"rangeMin",get:function(){return this.range()[0]}},{key:"rangeMax",get:function(){return this.range()[1]}},{key:"bandwidth",get:function(){return this.scale.bandwidth}},{key:"apply",value:function(n){var r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},a=r.bandAware,i=r.position;if(n!==void 0){if(i)switch(i){case"start":return this.scale(n);case"middle":{var l=this.bandwidth?this.bandwidth()/2:0;return this.scale(n)+l}case"end":{var o=this.bandwidth?this.bandwidth():0;return this.scale(n)+o}default:return this.scale(n)}if(a){var c=this.bandwidth?this.bandwidth()/2:0;return this.scale(n)+c}return this.scale(n)}}},{key:"isInRange",value:function(n){var r=this.range(),a=r[0],i=r[r.length-1];return a<=i?n>=a&&n<=i:n>=i&&n<=a}}],[{key:"create",value:function(n){return new s(n)}}])}();UEe(aFt,"EPS",1e-4);var oZe=function(t){var n=Object.keys(t).reduce(function(r,a){return UN(UN({},r),{},UEe({},a,aFt.create(t[a])))},{});return UN(UN({},n),{},{apply:function(a){var i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},l=i.bandAware,o=i.position;return Ixn(a,function(c,d){return n[d].apply(c,{bandAware:l,position:o})})},isInRange:function(a){return JOt(a,function(i,l){return n[l].isInRange(i)})}})};function fyn(s){return(s%180+180)%180}var pyn=function(t){var n=t.width,r=t.height,a=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,i=fyn(a),l=i*Math.PI/180,o=Math.atan(r/n),c=l>o&&l-1?a[i?t[l]:l]:void 0}}var byn=vyn,_yn=YOt;function wyn(s){var t=_yn(s),n=t%1;return t===t?n?t-n:t:0}var jyn=wyn,Nyn=t8t,kyn=i4,Syn=jyn,Cyn=Math.max;function Ayn(s,t,n){var r=s==null?0:s.length;if(!r)return-1;var a=n==null?0:Syn(n);return a<0&&(a=Cyn(r+a,0)),Nyn(s,kyn(t),a)}var Eyn=Ayn,Tyn=byn,Myn=Eyn,Pyn=Tyn(Myn),Iyn=Pyn;const Lyn=kd(Iyn);var Ryn=CYs(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("")}),lZe=k.createContext(void 0),cZe=k.createContext(void 0),iFt=k.createContext(void 0),oFt=k.createContext({}),lFt=k.createContext(void 0),cFt=k.createContext(0),dFt=k.createContext(0),Hgt=function(t){var n=t.state,r=n.xAxisMap,a=n.yAxisMap,i=n.offset,l=t.clipPathId,o=t.children,c=t.width,d=t.height,u=Ryn(i);return zt.createElement(lZe.Provider,{value:r},zt.createElement(cZe.Provider,{value:a},zt.createElement(oFt.Provider,{value:i},zt.createElement(iFt.Provider,{value:u},zt.createElement(lFt.Provider,{value:l},zt.createElement(cFt.Provider,{value:d},zt.createElement(dFt.Provider,{value:c},o)))))))},Dyn=function(){return k.useContext(lFt)},uFt=function(t){var n=k.useContext(lZe);n==null&&YO();var r=n[t];return r==null&&YO(),r},Oyn=function(){var t=k.useContext(lZe);return PE(t)},Fyn=function(){var t=k.useContext(cZe),n=Lyn(t,function(r){return JOt(r.domain,Number.isFinite)});return n||PE(t)},hFt=function(t){var n=k.useContext(cZe);n==null&&YO();var r=n[t];return r==null&&YO(),r},zyn=function(){var t=k.useContext(iFt);return t},Byn=function(){return k.useContext(oFt)},dZe=function(){return k.useContext(dFt)},uZe=function(){return k.useContext(cFt)};function XU(s){"@babel/helpers - typeof";return XU=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},XU(s)}function $yn(s,t){if(!(s instanceof t))throw new TypeError("Cannot call a class as a function")}function Uyn(s,t){for(var n=0;ns.length)&&(t=s.length);for(var n=0,r=new Array(t);ns*a)return!1;var i=n();return s*(t-s*i/2-r)>=0&&s*(t+s*i/2-a)<=0}function j0n(s,t){return vFt(s,t+1)}function N0n(s,t,n,r,a){for(var i=(r||[]).slice(),l=t.start,o=t.end,c=0,d=1,u=l,h=function(){var g=r==null?void 0:r[c];if(g===void 0)return{v:vFt(r,d)};var x=c,y,v=function(){return y===void 0&&(y=n(g,x)),y},_=g.coordinate,j=c===0||b4e(s,_,v,u,o);j||(c=0,u=l,d+=1),j&&(u=_+s*(v()/2+a),c+=d)},m;d<=i.length;)if(m=h(),m)return m.v;return[]}function sQ(s){"@babel/helpers - typeof";return sQ=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},sQ(s)}function Jgt(s,t){var n=Object.keys(s);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(s);t&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(s,a).enumerable})),n.push.apply(n,r)}return n}function e1(s){for(var t=1;t0?p.coordinate-y*s:p.coordinate})}else i[m]=p=e1(e1({},p),{},{tickCoord:p.coordinate});var v=b4e(s,p.tickCoord,x,o,c);v&&(c=p.tickCoord-s*(x()/2+a),i[m]=e1(e1({},p),{},{isShow:!0}))},u=l-1;u>=0;u--)d(u);return i}function E0n(s,t,n,r,a,i){var l=(r||[]).slice(),o=l.length,c=t.start,d=t.end;if(i){var u=r[o-1],h=n(u,o-1),m=s*(u.coordinate+s*h/2-d);l[o-1]=u=e1(e1({},u),{},{tickCoord:m>0?u.coordinate-m*s:u.coordinate});var p=b4e(s,u.tickCoord,function(){return h},c,d);p&&(d=u.tickCoord-s*(h/2+a),l[o-1]=e1(e1({},u),{},{isShow:!0}))}for(var g=i?o-1:o,x=function(_){var j=l[_],C,A=function(){return C===void 0&&(C=n(j,_)),C};if(_===0){var M=s*(j.coordinate-s*A()/2-c);l[_]=j=e1(e1({},j),{},{tickCoord:M<0?j.coordinate-M*s:j.coordinate})}else l[_]=j=e1(e1({},j),{},{tickCoord:j.coordinate});var I=b4e(s,j.tickCoord,A,c,d);I&&(c=j.tickCoord+s*(A()/2+a),l[_]=e1(e1({},j),{},{isShow:!0}))},y=0;y=2?db(a[1].coordinate-a[0].coordinate):1,v=w0n(i,y,p);return c==="equidistantPreserveStart"?N0n(y,v,x,a,l):(c==="preserveStart"||c==="preserveStartEnd"?m=E0n(y,v,x,a,l,c==="preserveStartEnd"):m=A0n(y,v,x,a,l),m.filter(function(_){return _.isShow}))}var T0n=["viewBox"],M0n=["viewBox"],P0n=["ticks"];function eq(s){"@babel/helpers - typeof";return eq=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},eq(s)}function jz(){return jz=Object.assign?Object.assign.bind():function(s){for(var t=1;t=0)&&Object.prototype.propertyIsEnumerable.call(s,r)&&(n[r]=s[r])}return n}function I0n(s,t){if(s==null)return{};var n={};for(var r in s)if(Object.prototype.hasOwnProperty.call(s,r)){if(t.indexOf(r)>=0)continue;n[r]=s[r]}return n}function L0n(s,t){if(!(s instanceof t))throw new TypeError("Cannot call a class as a function")}function txt(s,t){for(var n=0;n0?c(this.props):c(p)),l<=0||o<=0||!g||!g.length?null:zt.createElement(Id,{className:bc("recharts-cartesian-axis",d),ref:function(y){r.layerReference=y}},i&&this.renderAxisLine(),this.renderTicks(g,this.state.fontSize,this.state.letterSpacing),h0.renderCallByParent(this.props))}}],[{key:"renderTickItem",value:function(r,a,i){var l,o=bc(a.className,"recharts-cartesian-axis-tick-value");return zt.isValidElement(r)?l=zt.cloneElement(r,ry(ry({},a),{},{className:o})):Dl(r)?l=r(ry(ry({},a),{},{className:o})):l=zt.createElement(GO,jz({},a,{className:"recharts-cartesian-axis-tick-value"}),i),l}}])}(k.Component);pZe(jV,"displayName","CartesianAxis");pZe(jV,"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 $0n=["x1","y1","x2","y2","key"],U0n=["offset"];function ZO(s){"@babel/helpers - typeof";return ZO=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},ZO(s)}function sxt(s,t){var n=Object.keys(s);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(s);t&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(s,a).enumerable})),n.push.apply(n,r)}return n}function r1(s){for(var t=1;t=0)&&Object.prototype.propertyIsEnumerable.call(s,r)&&(n[r]=s[r])}return n}function G0n(s,t){if(s==null)return{};var n={};for(var r in s)if(Object.prototype.hasOwnProperty.call(s,r)){if(t.indexOf(r)>=0)continue;n[r]=s[r]}return n}var W0n=function(t){var n=t.fill;if(!n||n==="none")return null;var r=t.fillOpacity,a=t.x,i=t.y,l=t.width,o=t.height,c=t.ry;return zt.createElement("rect",{x:a,y:i,ry:c,width:l,height:o,stroke:"none",fill:n,fillOpacity:r,className:"recharts-cartesian-grid-bg"})};function wFt(s,t){var n;if(zt.isValidElement(s))n=zt.cloneElement(s,t);else if(Dl(s))n=s(t);else{var r=t.x1,a=t.y1,i=t.x2,l=t.y2,o=t.key,c=nxt(t,$0n),d=Yo(c,!1);d.offset;var u=nxt(d,U0n);n=zt.createElement("line",gD({},u,{x1:r,y1:a,x2:i,y2:l,fill:"none",key:o}))}return n}function K0n(s){var t=s.x,n=s.width,r=s.horizontal,a=r===void 0?!0:r,i=s.horizontalPoints;if(!a||!i||!i.length)return null;var l=i.map(function(o,c){var d=r1(r1({},s),{},{x1:t,y1:o,x2:t+n,y2:o,key:"line-".concat(c),index:c});return wFt(a,d)});return zt.createElement("g",{className:"recharts-cartesian-grid-horizontal"},l)}function Y0n(s){var t=s.y,n=s.height,r=s.vertical,a=r===void 0?!0:r,i=s.verticalPoints;if(!a||!i||!i.length)return null;var l=i.map(function(o,c){var d=r1(r1({},s),{},{x1:o,y1:t,x2:o,y2:t+n,key:"line-".concat(c),index:c});return wFt(a,d)});return zt.createElement("g",{className:"recharts-cartesian-grid-vertical"},l)}function Z0n(s){var t=s.horizontalFill,n=s.fillOpacity,r=s.x,a=s.y,i=s.width,l=s.height,o=s.horizontalPoints,c=s.horizontal,d=c===void 0?!0:c;if(!d||!t||!t.length)return null;var u=o.map(function(m){return Math.round(m+a-a)}).sort(function(m,p){return m-p});a!==u[0]&&u.unshift(0);var h=u.map(function(m,p){var g=!u[p+1],x=g?a+l-m:u[p+1]-m;if(x<=0)return null;var y=p%t.length;return zt.createElement("rect",{key:"react-".concat(p),y:m,x:r,height:x,width:i,stroke:"none",fill:t[y],fillOpacity:n,className:"recharts-cartesian-grid-bg"})});return zt.createElement("g",{className:"recharts-cartesian-gridstripes-horizontal"},h)}function X0n(s){var t=s.vertical,n=t===void 0?!0:t,r=s.verticalFill,a=s.fillOpacity,i=s.x,l=s.y,o=s.width,c=s.height,d=s.verticalPoints;if(!n||!r||!r.length)return null;var u=d.map(function(m){return Math.round(m+i-i)}).sort(function(m,p){return m-p});i!==u[0]&&u.unshift(0);var h=u.map(function(m,p){var g=!u[p+1],x=g?i+o-m:u[p+1]-m;if(x<=0)return null;var y=p%r.length;return zt.createElement("rect",{key:"react-".concat(p),x:m,y:l,width:x,height:c,stroke:"none",fill:r[y],fillOpacity:a,className:"recharts-cartesian-grid-bg"})});return zt.createElement("g",{className:"recharts-cartesian-gridstripes-vertical"},h)}var Q0n=function(t,n){var r=t.xAxis,a=t.width,i=t.height,l=t.offset;return vOt(fZe(r1(r1(r1({},jV.defaultProps),r),{},{ticks:u3(r,!0),viewBox:{x:0,y:0,width:a,height:i}})),l.left,l.left+l.width,n)},J0n=function(t,n){var r=t.yAxis,a=t.width,i=t.height,l=t.offset;return vOt(fZe(r1(r1(r1({},jV.defaultProps),r),{},{ticks:u3(r,!0),viewBox:{x:0,y:0,width:a,height:i}})),l.top,l.top+l.height,n)},a9={horizontal:!0,vertical:!0,stroke:"#ccc",fill:"none",verticalFill:[],horizontalFill:[]};function XO(s){var t,n,r,a,i,l,o=dZe(),c=uZe(),d=Byn(),u=r1(r1({},s),{},{stroke:(t=s.stroke)!==null&&t!==void 0?t:a9.stroke,fill:(n=s.fill)!==null&&n!==void 0?n:a9.fill,horizontal:(r=s.horizontal)!==null&&r!==void 0?r:a9.horizontal,horizontalFill:(a=s.horizontalFill)!==null&&a!==void 0?a:a9.horizontalFill,vertical:(i=s.vertical)!==null&&i!==void 0?i:a9.vertical,verticalFill:(l=s.verticalFill)!==null&&l!==void 0?l:a9.verticalFill,x:Ha(s.x)?s.x:d.left,y:Ha(s.y)?s.y:d.top,width:Ha(s.width)?s.width:d.width,height:Ha(s.height)?s.height:d.height}),h=u.x,m=u.y,p=u.width,g=u.height,x=u.syncWithTicks,y=u.horizontalValues,v=u.verticalValues,_=Oyn(),j=Fyn();if(!Ha(p)||p<=0||!Ha(g)||g<=0||!Ha(h)||h!==+h||!Ha(m)||m!==+m)return null;var C=u.verticalCoordinatesGenerator||Q0n,A=u.horizontalCoordinatesGenerator||J0n,M=u.horizontalPoints,I=u.verticalPoints;if((!M||!M.length)&&Dl(A)){var P=y&&y.length,R=A({yAxis:j?r1(r1({},j),{},{ticks:P?y:j.ticks}):void 0,width:o,height:c,offset:d},P?!0:x);mk(Array.isArray(R),"horizontalCoordinatesGenerator should return Array but instead it returned [".concat(ZO(R),"]")),Array.isArray(R)&&(M=R)}if((!I||!I.length)&&Dl(C)){var O=v&&v.length,B=C({xAxis:_?r1(r1({},_),{},{ticks:O?v:_.ticks}):void 0,width:o,height:c,offset:d},O?!0:x);mk(Array.isArray(B),"verticalCoordinatesGenerator should return Array but instead it returned [".concat(ZO(B),"]")),Array.isArray(B)&&(I=B)}return zt.createElement("g",{className:"recharts-cartesian-grid"},zt.createElement(W0n,{fill:u.fill,fillOpacity:u.fillOpacity,x:u.x,y:u.y,width:u.width,height:u.height,ry:u.ry}),zt.createElement(K0n,gD({},u,{offset:d,horizontalPoints:M,xAxis:_,yAxis:j})),zt.createElement(Y0n,gD({},u,{offset:d,verticalPoints:I,xAxis:_,yAxis:j})),zt.createElement(Z0n,gD({},u,{horizontalPoints:M})),zt.createElement(X0n,gD({},u,{verticalPoints:I})))}XO.displayName="CartesianGrid";var evn=["type","layout","connectNulls","ref"],tvn=["key"];function tq(s){"@babel/helpers - typeof";return tq=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},tq(s)}function rxt(s,t){if(s==null)return{};var n=svn(s,t),r,a;if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(s);for(a=0;a=0)&&Object.prototype.propertyIsEnumerable.call(s,r)&&(n[r]=s[r])}return n}function svn(s,t){if(s==null)return{};var n={};for(var r in s)if(Object.prototype.hasOwnProperty.call(s,r)){if(t.indexOf(r)>=0)continue;n[r]=s[r]}return n}function ZY(){return ZY=Object.assign?Object.assign.bind():function(s){for(var t=1;ts.length)&&(t=s.length);for(var n=0,r=new Array(t);nh){p=[].concat(i9(c.slice(0,g)),[h-x]);break}var y=p.length%2===0?[0,m]:[m];return[].concat(i9(t.repeat(c,u)),i9(p),y).map(function(v){return"".concat(v,"px")}).join(", ")}),qN(n,"id",LF("recharts-line-")),qN(n,"pathRef",function(l){n.mainCurve=l}),qN(n,"handleAnimationEnd",function(){n.setState({isAnimationFinished:!0}),n.props.onAnimationEnd&&n.props.onAnimationEnd()}),qN(n,"handleAnimationStart",function(){n.setState({isAnimationFinished:!1}),n.props.onAnimationStart&&n.props.onAnimationStart()}),n}return hvn(t,s),lvn(t,[{key:"componentDidMount",value:function(){if(this.props.isAnimationActive){var r=this.getTotalLength();this.setState({totalLength:r})}}},{key:"componentDidUpdate",value:function(){if(this.props.isAnimationActive){var r=this.getTotalLength();r!==this.state.totalLength&&this.setState({totalLength:r})}}},{key:"getTotalLength",value:function(){var r=this.mainCurve;try{return r&&r.getTotalLength&&r.getTotalLength()||0}catch{return 0}}},{key:"renderErrorBar",value:function(r,a){if(this.props.isAnimationActive&&!this.state.isAnimationFinished)return null;var i=this.props,l=i.points,o=i.xAxis,c=i.yAxis,d=i.layout,u=i.children,h=nj(u,ete);if(!h)return null;var m=function(x,y){return{x:x.x,y:x.y,value:x.value,errorVal:Qg(x.payload,y)}},p={clipPath:r?"url(#clipPath-".concat(a,")"):null};return zt.createElement(Id,p,h.map(function(g){return zt.cloneElement(g,{key:"bar-".concat(g.props.dataKey),data:l,xAxis:o,yAxis:c,layout:d,dataPointFormatter:m})}))}},{key:"renderDots",value:function(r,a,i){var l=this.props.isAnimationActive;if(l&&!this.state.isAnimationFinished)return null;var o=this.props,c=o.dot,d=o.points,u=o.dataKey,h=Yo(this.props,!1),m=Yo(c,!0),p=d.map(function(x,y){var v=yw(yw(yw({key:"dot-".concat(y),r:3},h),m),{},{index:y,cx:x.x,cy:x.y,value:x.value,dataKey:u,payload:x.payload,points:d});return t.renderDotItem(c,v)}),g={clipPath:r?"url(#clipPath-".concat(a?"":"dots-").concat(i,")"):null};return zt.createElement(Id,ZY({className:"recharts-line-dots",key:"dots"},g),p)}},{key:"renderCurveStatically",value:function(r,a,i,l){var o=this.props,c=o.type,d=o.layout,u=o.connectNulls;o.ref;var h=rxt(o,evn),m=yw(yw(yw({},Yo(h,!0)),{},{fill:"none",className:"recharts-line-curve",clipPath:a?"url(#clipPath-".concat(i,")"):null,points:r},l),{},{type:c,layout:d,connectNulls:u});return zt.createElement(uO,ZY({},m,{pathRef:this.pathRef}))}},{key:"renderCurveWithAnimation",value:function(r,a){var i=this,l=this.props,o=l.points,c=l.strokeDasharray,d=l.isAnimationActive,u=l.animationBegin,h=l.animationDuration,m=l.animationEasing,p=l.animationId,g=l.animateNewValues,x=l.width,y=l.height,v=this.state,_=v.prevPoints,j=v.totalLength;return zt.createElement(_k,{begin:u,duration:h,isActive:d,easing:m,from:{t:0},to:{t:1},key:"line-".concat(p),onAnimationEnd:this.handleAnimationEnd,onAnimationStart:this.handleAnimationStart},function(C){var A=C.t;if(_){var M=_.length/o.length,I=o.map(function(U,G){var H=Math.floor(G*M);if(_[H]){var Y=_[H],se=xy(Y.x,U.x),ee=xy(Y.y,U.y);return yw(yw({},U),{},{x:se(A),y:ee(A)})}if(g){var oe=xy(x*2,U.x),me=xy(y/2,U.y);return yw(yw({},U),{},{x:oe(A),y:me(A)})}return yw(yw({},U),{},{x:U.x,y:U.y})});return i.renderCurveStatically(I,r,a)}var P=xy(0,j),R=P(A),O;if(c){var B="".concat(c).split(/[,\s]+/gim).map(function(U){return parseFloat(U)});O=i.getStrokeDasharray(R,j,B)}else O=i.generateSimpleStrokeDasharray(j,R);return i.renderCurveStatically(o,r,a,{strokeDasharray:O})})}},{key:"renderCurve",value:function(r,a){var i=this.props,l=i.points,o=i.isAnimationActive,c=this.state,d=c.prevPoints,u=c.totalLength;return o&&l&&l.length&&(!d&&u>0||!WO(d,l))?this.renderCurveWithAnimation(r,a):this.renderCurveStatically(l,r,a)}},{key:"render",value:function(){var r,a=this.props,i=a.hide,l=a.dot,o=a.points,c=a.className,d=a.xAxis,u=a.yAxis,h=a.top,m=a.left,p=a.width,g=a.height,x=a.isAnimationActive,y=a.id;if(i||!o||!o.length)return null;var v=this.state.isAnimationFinished,_=o.length===1,j=bc("recharts-line",c),C=d&&d.allowDataOverflow,A=u&&u.allowDataOverflow,M=C||A,I=hc(y)?this.id:y,P=(r=Yo(l,!1))!==null&&r!==void 0?r:{r:3,strokeWidth:2},R=P.r,O=R===void 0?3:R,B=P.strokeWidth,U=B===void 0?2:B,G=hDt(l)?l:{},H=G.clipDot,Y=H===void 0?!0:H,se=O*2+U;return zt.createElement(Id,{className:j},C||A?zt.createElement("defs",null,zt.createElement("clipPath",{id:"clipPath-".concat(I)},zt.createElement("rect",{x:C?m:m-p/2,y:A?h:h-g/2,width:C?p:p*2,height:A?g:g*2})),!Y&&zt.createElement("clipPath",{id:"clipPath-dots-".concat(I)},zt.createElement("rect",{x:m-se/2,y:h-se/2,width:p+se,height:g+se}))):null,!_&&this.renderCurve(M,I),this.renderErrorBar(M,I),(_||l)&&this.renderDots(M,Y,I),(!x||v)&&F5.renderCallByParent(this.props,o))}}],[{key:"getDerivedStateFromProps",value:function(r,a){return r.animationId!==a.prevAnimationId?{prevAnimationId:r.animationId,curPoints:r.points,prevPoints:a.curPoints}:r.points!==a.curPoints?{curPoints:r.points}:null}},{key:"repeat",value:function(r,a){for(var i=r.length%2!==0?[].concat(i9(r),[0]):r,l=[],o=0;o=0)&&Object.prototype.propertyIsEnumerable.call(s,r)&&(n[r]=s[r])}return n}function gvn(s,t){if(s==null)return{};var n={};for(var r in s)if(Object.prototype.hasOwnProperty.call(s,r)){if(t.indexOf(r)>=0)continue;n[r]=s[r]}return n}function xD(){return xD=Object.assign?Object.assign.bind():function(s){for(var t=1;t0||!WO(u,l)||!WO(h,o))?this.renderAreaWithAnimation(r,a):this.renderAreaStatically(l,o,r,a)}},{key:"render",value:function(){var r,a=this.props,i=a.hide,l=a.dot,o=a.points,c=a.className,d=a.top,u=a.left,h=a.xAxis,m=a.yAxis,p=a.width,g=a.height,x=a.isAnimationActive,y=a.id;if(i||!o||!o.length)return null;var v=this.state.isAnimationFinished,_=o.length===1,j=bc("recharts-area",c),C=h&&h.allowDataOverflow,A=m&&m.allowDataOverflow,M=C||A,I=hc(y)?this.id:y,P=(r=Yo(l,!1))!==null&&r!==void 0?r:{r:3,strokeWidth:2},R=P.r,O=R===void 0?3:R,B=P.strokeWidth,U=B===void 0?2:B,G=hDt(l)?l:{},H=G.clipDot,Y=H===void 0?!0:H,se=O*2+U;return zt.createElement(Id,{className:j},C||A?zt.createElement("defs",null,zt.createElement("clipPath",{id:"clipPath-".concat(I)},zt.createElement("rect",{x:C?u:u-p/2,y:A?d:d-g/2,width:C?p:p*2,height:A?g:g*2})),!Y&&zt.createElement("clipPath",{id:"clipPath-dots-".concat(I)},zt.createElement("rect",{x:u-se/2,y:d-se/2,width:p+se,height:g+se}))):null,_?null:this.renderArea(M,I),(l||_)&&this.renderDots(M,Y,I),(!x||v)&&F5.renderCallByParent(this.props,o))}}],[{key:"getDerivedStateFromProps",value:function(r,a){return r.animationId!==a.prevAnimationId?{prevAnimationId:r.animationId,curPoints:r.points,curBaseLine:r.baseLine,prevPoints:a.curPoints,prevBaseLine:a.curBaseLine}:r.points!==a.curPoints||r.baseLine!==a.curBaseLine?{curPoints:r.points,curBaseLine:r.baseLine}:null}}])}(k.PureComponent);kFt=A_;g5(A_,"displayName","Area");g5(A_,"defaultProps",{stroke:"#3182bd",fill:"#3182bd",fillOpacity:.6,xAxisId:0,yAxisId:0,legendType:"line",connectNulls:!1,points:[],dot:!1,activeDot:!0,hide:!1,isAnimationActive:!f6.isSsr,animationBegin:0,animationDuration:1500,animationEasing:"ease"});g5(A_,"getBaseValue",function(s,t,n,r){var a=s.layout,i=s.baseValue,l=t.props.baseValue,o=l??i;if(Ha(o)&&typeof o=="number")return o;var c=a==="horizontal"?r:n,d=c.scale.domain();if(c.type==="number"){var u=Math.max(d[0],d[1]),h=Math.min(d[0],d[1]);return o==="dataMin"?h:o==="dataMax"||u<0?u:Math.max(Math.min(d[0],d[1]),0)}return o==="dataMin"?d[0]:o==="dataMax"?d[1]:d[0]});g5(A_,"getComposedData",function(s){var t=s.props,n=s.item,r=s.xAxis,a=s.yAxis,i=s.xAxisTicks,l=s.yAxisTicks,o=s.bandSize,c=s.dataKey,d=s.stackedData,u=s.dataStartIndex,h=s.displayedData,m=s.offset,p=t.layout,g=d&&d.length,x=kFt.getBaseValue(t,n,r,a),y=p==="horizontal",v=!1,_=h.map(function(C,A){var M;g?M=d[u+A]:(M=Qg(C,c),Array.isArray(M)?v=!0:M=[x,M]);var I=M[1]==null||g&&Qg(C,c)==null;return y?{x:Q5e({axis:r,ticks:i,bandSize:o,entry:C,index:A}),y:I?null:a.scale(M[1]),value:M,payload:C}:{x:I?null:r.scale(M[1]),y:Q5e({axis:a,ticks:l,bandSize:o,entry:C,index:A}),value:M,payload:C}}),j;return g||v?j=_.map(function(C){var A=Array.isArray(C.value)?C.value[0]:null;return y?{x:C.x,y:A!=null&&C.y!=null?a.scale(A):null}:{x:A!=null?r.scale(A):null,y:C.y}}):j=y?a.scale(x):r.scale(x),aE({points:_,baseLine:j,layout:p,isRange:v},m)});g5(A_,"renderDotItem",function(s,t){var n;if(zt.isValidElement(s))n=zt.cloneElement(s,t);else if(Dl(s))n=s(t);else{var r=bc("recharts-area-dot",typeof s!="boolean"?s.className:""),a=t.key,i=SFt(t,pvn);n=zt.createElement(tte,xD({},i,{key:a,className:r}))}return n});function nq(s){"@babel/helpers - typeof";return nq=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},nq(s)}function Nvn(s,t){if(!(s instanceof t))throw new TypeError("Cannot call a class as a function")}function kvn(s,t){for(var n=0;ns.length)&&(t=s.length);for(var n=0,r=new Array(t);n=0)&&Object.prototype.propertyIsEnumerable.call(s,r)&&(n[r]=s[r])}return n}function u1n(s,t){if(s==null)return{};var n={};for(var r in s)if(Object.prototype.hasOwnProperty.call(s,r)){if(t.indexOf(r)>=0)continue;n[r]=s[r]}return n}function h1n(s,t){if(!(s instanceof t))throw new TypeError("Cannot call a class as a function")}function m1n(s,t){for(var n=0;ns.length)&&(t=s.length);for(var n=0,r=new Array(t);n0?l:t&&t.length&&Ha(a)&&Ha(i)?t.slice(a,i+1):[]};function UFt(s){return s==="number"?[0,"auto"]:void 0}var DBe=function(t,n,r,a){var i=t.graphicalItems,l=t.tooltipAxis,o=WEe(n,t);return r<0||!i||!i.length||r>=o.length?null:i.reduce(function(c,d){var u,h=(u=d.props.data)!==null&&u!==void 0?u:n;h&&t.dataStartIndex+t.dataEndIndex!==0&&t.dataEndIndex-t.dataStartIndex>=r&&(h=h.slice(t.dataStartIndex,t.dataEndIndex+1));var m;if(l.dataKey&&!l.allowDuplicatedCategory){var p=h===void 0?o:h;m=j5e(p,l.dataKey,a)}else m=h&&h[r]||o[r];return m?[].concat(iq(c),[NOt(d,m)]):c},[])},fxt=function(t,n,r,a){var i=a||{x:t.chartX,y:t.chartY},l=k1n(i,r),o=t.orderedTooltipTicks,c=t.tooltipAxis,d=t.tooltipTicks,u=Iun(l,o,d,c);if(u>=0&&d){var h=d[u]&&d[u].value,m=DBe(t,n,u,h),p=S1n(r,o,u,i);return{activeTooltipIndex:u,activeLabel:h,activePayload:m,activeCoordinate:p}}return null},C1n=function(t,n){var r=n.axes,a=n.graphicalItems,i=n.axisType,l=n.axisIdKey,o=n.stackGroups,c=n.dataStartIndex,d=n.dataEndIndex,u=t.layout,h=t.children,m=t.stackOffset,p=yOt(u,i);return r.reduce(function(g,x){var y,v=x.type.defaultProps!==void 0?ra(ra({},x.type.defaultProps),x.props):x.props,_=v.type,j=v.dataKey,C=v.allowDataOverflow,A=v.allowDuplicatedCategory,M=v.scale,I=v.ticks,P=v.includeHidden,R=v[l];if(g[R])return g;var O=WEe(t.data,{graphicalItems:a.filter(function(le){var fe,_e=l in le.props?le.props[l]:(fe=le.type.defaultProps)===null||fe===void 0?void 0:fe[l];return _e===R}),dataStartIndex:c,dataEndIndex:d}),B=O.length,U,G,H;Jvn(v.domain,C,_)&&(U=Yze(v.domain,null,C),p&&(_==="number"||M!=="auto")&&(H=GY(O,j,"category")));var Y=UFt(_);if(!U||U.length===0){var se,ee=(se=v.domain)!==null&&se!==void 0?se:Y;if(j){if(U=GY(O,j,_),_==="category"&&p){var oe=jZs(U);A&&oe?(G=U,U=h4e(0,B)):A||(U=Opt(ee,U,x).reduce(function(le,fe){return le.indexOf(fe)>=0?le:[].concat(iq(le),[fe])},[]))}else if(_==="category")A?U=U.filter(function(le){return le!==""&&!hc(le)}):U=Opt(ee,U,x).reduce(function(le,fe){return le.indexOf(fe)>=0||fe===""||hc(fe)?le:[].concat(iq(le),[fe])},[]);else if(_==="number"){var me=Fun(O,a.filter(function(le){var fe,_e,ve=l in le.props?le.props[l]:(fe=le.type.defaultProps)===null||fe===void 0?void 0:fe[l],he="hide"in le.props?le.props.hide:(_e=le.type.defaultProps)===null||_e===void 0?void 0:_e.hide;return ve===R&&(P||!he)}),j,i,u);me&&(U=me)}p&&(_==="number"||M!=="auto")&&(H=GY(O,j,"category"))}else p?U=h4e(0,B):o&&o[R]&&o[R].hasStack&&_==="number"?U=m==="expand"?[0,1]:jOt(o[R].stackGroups,c,d):U=xOt(O,a.filter(function(le){var fe=l in le.props?le.props[l]:le.type.defaultProps[l],_e="hide"in le.props?le.props.hide:le.type.defaultProps.hide;return fe===R&&(P||!_e)}),_,u,!0);if(_==="number")U=IBe(h,U,R,i,I),ee&&(U=Yze(ee,U,C));else if(_==="category"&&ee){var Q=ee,te=U.every(function(le){return Q.indexOf(le)>=0});te&&(U=Q)}}return ra(ra({},g),{},Rl({},R,ra(ra({},v),{},{axisType:i,domain:U,categoricalDomain:H,duplicateDomain:G,originalDomain:(y=v.domain)!==null&&y!==void 0?y:Y,isCategorical:p,layout:u})))},{})},A1n=function(t,n){var r=n.graphicalItems,a=n.Axis,i=n.axisType,l=n.axisIdKey,o=n.stackGroups,c=n.dataStartIndex,d=n.dataEndIndex,u=t.layout,h=t.children,m=WEe(t.data,{graphicalItems:r,dataStartIndex:c,dataEndIndex:d}),p=m.length,g=yOt(u,i),x=-1;return r.reduce(function(y,v){var _=v.type.defaultProps!==void 0?ra(ra({},v.type.defaultProps),v.props):v.props,j=_[l],C=UFt("number");if(!y[j]){x++;var A;return g?A=h4e(0,p):o&&o[j]&&o[j].hasStack?(A=jOt(o[j].stackGroups,c,d),A=IBe(h,A,j,i)):(A=Yze(C,xOt(m,r.filter(function(M){var I,P,R=l in M.props?M.props[l]:(I=M.type.defaultProps)===null||I===void 0?void 0:I[l],O="hide"in M.props?M.props.hide:(P=M.type.defaultProps)===null||P===void 0?void 0:P.hide;return R===j&&!O}),"number",u),a.defaultProps.allowDataOverflow),A=IBe(h,A,j,i)),ra(ra({},y),{},Rl({},j,ra(ra({axisType:i},a.defaultProps),{},{hide:!0,orientation:sj(j1n,"".concat(i,".").concat(x%2),null),domain:A,originalDomain:C,isCategorical:g,layout:u})))}return y},{})},E1n=function(t,n){var r=n.axisType,a=r===void 0?"xAxis":r,i=n.AxisComp,l=n.graphicalItems,o=n.stackGroups,c=n.dataStartIndex,d=n.dataEndIndex,u=t.children,h="".concat(a,"Id"),m=nj(u,i),p={};return m&&m.length?p=C1n(t,{axes:m,graphicalItems:l,axisType:a,axisIdKey:h,stackGroups:o,dataStartIndex:c,dataEndIndex:d}):l&&l.length&&(p=A1n(t,{Axis:i,graphicalItems:l,axisType:a,axisIdKey:h,stackGroups:o,dataStartIndex:c,dataEndIndex:d})),p},T1n=function(t){var n=PE(t),r=u3(n,!1,!0);return{tooltipTicks:r,orderedTooltipTicks:PYe(r,function(a){return a.coordinate}),tooltipAxis:n,tooltipAxisBandSize:J5e(n,r)}},pxt=function(t){var n=t.children,r=t.defaultShowTooltip,a=Lw(n,YU),i=0,l=0;return t.data&&t.data.length!==0&&(l=t.data.length-1),a&&a.props&&(a.props.startIndex>=0&&(i=a.props.startIndex),a.props.endIndex>=0&&(l=a.props.endIndex)),{chartX:0,chartY:0,dataStartIndex:i,dataEndIndex:l,activeTooltipIndex:-1,isTooltipActive:!!r}},M1n=function(t){return!t||!t.length?!1:t.some(function(n){var r=C3(n&&n.type);return r&&r.indexOf("Bar")>=0})},gxt=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"}},P1n=function(t,n){var r=t.props,a=t.graphicalItems,i=t.xAxisMap,l=i===void 0?{}:i,o=t.yAxisMap,c=o===void 0?{}:o,d=r.width,u=r.height,h=r.children,m=r.margin||{},p=Lw(h,YU),g=Lw(h,lO),x=Object.keys(c).reduce(function(A,M){var I=c[M],P=I.orientation;return!I.mirror&&!I.hide?ra(ra({},A),{},Rl({},P,A[P]+I.width)):A},{left:m.left||0,right:m.right||0}),y=Object.keys(l).reduce(function(A,M){var I=l[M],P=I.orientation;return!I.mirror&&!I.hide?ra(ra({},A),{},Rl({},P,sj(A,"".concat(P))+I.height)):A},{top:m.top||0,bottom:m.bottom||0}),v=ra(ra({},y),x),_=v.bottom;p&&(v.bottom+=p.props.height||YU.defaultProps.height),g&&n&&(v=Dun(v,a,r,n));var j=d-v.left-v.right,C=u-v.top-v.bottom;return ra(ra({brushBottom:_},v),{},{width:Math.max(j,0),height:Math.max(C,0)})},I1n=function(t,n){if(n==="xAxis")return t[n].width;if(n==="yAxis")return t[n].height},KEe=function(t){var n=t.chartName,r=t.GraphicalChild,a=t.defaultTooltipEventType,i=a===void 0?"axis":a,l=t.validateTooltipEventTypes,o=l===void 0?["axis"]:l,c=t.axisComponents,d=t.legendContent,u=t.formatAxisMap,h=t.defaultProps,m=function(v,_){var j=_.graphicalItems,C=_.stackGroups,A=_.offset,M=_.updateId,I=_.dataStartIndex,P=_.dataEndIndex,R=v.barSize,O=v.layout,B=v.barGap,U=v.barCategoryGap,G=v.maxBarSize,H=gxt(O),Y=H.numericAxisName,se=H.cateAxisName,ee=M1n(j),oe=[];return j.forEach(function(me,Q){var te=WEe(v.data,{graphicalItems:[me],dataStartIndex:I,dataEndIndex:P}),le=me.type.defaultProps!==void 0?ra(ra({},me.type.defaultProps),me.props):me.props,fe=le.dataKey,_e=le.maxBarSize,ve=le["".concat(Y,"Id")],he=le["".concat(se,"Id")],Se={},Te=c.reduce(function(tt,ut){var nt=_["".concat(ut.axisType,"Map")],et=le["".concat(ut.axisType,"Id")];nt&&nt[et]||ut.axisType==="zAxis"||YO();var at=nt[et];return ra(ra({},tt),{},Rl(Rl({},ut.axisType,at),"".concat(ut.axisType,"Ticks"),u3(at)))},Se),Ie=Te[se],Ue=Te["".concat(se,"Ticks")],Be=C&&C[ve]&&C[ve].hasStack&&Wun(me,C[ve].stackGroups),je=C3(me.type).indexOf("Bar")>=0,Ye=J5e(Ie,Ue),Ee=[],Re=ee&&Lun({barSize:R,stackGroups:C,totalSize:I1n(Te,se)});if(je){var ke,Fe,Oe=hc(_e)?G:_e,Ge=(ke=(Fe=J5e(Ie,Ue,!0))!==null&&Fe!==void 0?Fe:Oe)!==null&&ke!==void 0?ke:0;Ee=Run({barGap:B,barCategoryGap:U,bandSize:Ge!==Ye?Ge:Ye,sizeList:Re[he],maxBarSize:Oe}),Ge!==Ye&&(Ee=Ee.map(function(tt){return ra(ra({},tt),{},{position:ra(ra({},tt.position),{},{offset:tt.position.offset-Ge/2})})}))}var yt=me&&me.type&&me.type.getComposedData;yt&&oe.push({props:ra(ra({},yt(ra(ra({},Te),{},{displayedData:te,props:v,dataKey:fe,item:me,bandSize:Ye,barPosition:Ee,offset:A,stackedData:Be,layout:O,dataStartIndex:I,dataEndIndex:P}))),{},Rl(Rl(Rl({key:me.key||"item-".concat(Q)},Y,Te[Y]),se,Te[se]),"animationId",M)),childIndex:RZs(me,v.children),item:me})}),oe},p=function(v,_){var j=v.props,C=v.dataStartIndex,A=v.dataEndIndex,M=v.updateId;if(!Mmt({props:j}))return null;var I=j.children,P=j.layout,R=j.stackOffset,O=j.data,B=j.reverseStackOrder,U=gxt(P),G=U.numericAxisName,H=U.cateAxisName,Y=nj(I,r),se=Hun(O,Y,"".concat(G,"Id"),"".concat(H,"Id"),R,B),ee=c.reduce(function(le,fe){var _e="".concat(fe.axisType,"Map");return ra(ra({},le),{},Rl({},_e,E1n(j,ra(ra({},fe),{},{graphicalItems:Y,stackGroups:fe.axisType===G&&se,dataStartIndex:C,dataEndIndex:A}))))},{}),oe=P1n(ra(ra({},ee),{},{props:j,graphicalItems:Y}),_==null?void 0:_.legendBBox);Object.keys(ee).forEach(function(le){ee[le]=u(j,ee[le],oe,le.replace("Map",""),n)});var me=ee["".concat(H,"Map")],Q=T1n(me),te=m(j,ra(ra({},ee),{},{dataStartIndex:C,dataEndIndex:A,updateId:M,graphicalItems:Y,stackGroups:se,offset:oe}));return ra(ra({formattedGraphicalItems:te,graphicalItems:Y,offset:oe,stackGroups:se},Q),ee)},g=function(y){function v(_){var j,C,A;return h1n(this,v),A=p1n(this,v,[_]),Rl(A,"eventEmitterSymbol",Symbol("rechartsEventEmitter")),Rl(A,"accessibilityManager",new Qvn),Rl(A,"handleLegendBBoxUpdate",function(M){if(M){var I=A.state,P=I.dataStartIndex,R=I.dataEndIndex,O=I.updateId;A.setState(ra({legendBBox:M},p({props:A.props,dataStartIndex:P,dataEndIndex:R,updateId:O},ra(ra({},A.state),{},{legendBBox:M}))))}}),Rl(A,"handleReceiveSyncEvent",function(M,I,P){if(A.props.syncId===M){if(P===A.eventEmitterSymbol&&typeof A.props.syncMethod!="function")return;A.applySyncEvent(I)}}),Rl(A,"handleBrushChange",function(M){var I=M.startIndex,P=M.endIndex;if(I!==A.state.dataStartIndex||P!==A.state.dataEndIndex){var R=A.state.updateId;A.setState(function(){return ra({dataStartIndex:I,dataEndIndex:P},p({props:A.props,dataStartIndex:I,dataEndIndex:P,updateId:R},A.state))}),A.triggerSyncEvent({dataStartIndex:I,dataEndIndex:P})}}),Rl(A,"handleMouseEnter",function(M){var I=A.getMouseInfo(M);if(I){var P=ra(ra({},I),{},{isTooltipActive:!0});A.setState(P),A.triggerSyncEvent(P);var R=A.props.onMouseEnter;Dl(R)&&R(P,M)}}),Rl(A,"triggeredAfterMouseMove",function(M){var I=A.getMouseInfo(M),P=I?ra(ra({},I),{},{isTooltipActive:!0}):{isTooltipActive:!1};A.setState(P),A.triggerSyncEvent(P);var R=A.props.onMouseMove;Dl(R)&&R(P,M)}),Rl(A,"handleItemMouseEnter",function(M){A.setState(function(){return{isTooltipActive:!0,activeItem:M,activePayload:M.tooltipPayload,activeCoordinate:M.tooltipPosition||{x:M.cx,y:M.cy}}})}),Rl(A,"handleItemMouseLeave",function(){A.setState(function(){return{isTooltipActive:!1}})}),Rl(A,"handleMouseMove",function(M){M.persist(),A.throttleTriggeredAfterMouseMove(M)}),Rl(A,"handleMouseLeave",function(M){A.throttleTriggeredAfterMouseMove.cancel();var I={isTooltipActive:!1};A.setState(I),A.triggerSyncEvent(I);var P=A.props.onMouseLeave;Dl(P)&&P(I,M)}),Rl(A,"handleOuterEvent",function(M){var I=LZs(M),P=sj(A.props,"".concat(I));if(I&&Dl(P)){var R,O;/.*touch.*/i.test(I)?O=A.getMouseInfo(M.changedTouches[0]):O=A.getMouseInfo(M),P((R=O)!==null&&R!==void 0?R:{},M)}}),Rl(A,"handleClick",function(M){var I=A.getMouseInfo(M);if(I){var P=ra(ra({},I),{},{isTooltipActive:!0});A.setState(P),A.triggerSyncEvent(P);var R=A.props.onClick;Dl(R)&&R(P,M)}}),Rl(A,"handleMouseDown",function(M){var I=A.props.onMouseDown;if(Dl(I)){var P=A.getMouseInfo(M);I(P,M)}}),Rl(A,"handleMouseUp",function(M){var I=A.props.onMouseUp;if(Dl(I)){var P=A.getMouseInfo(M);I(P,M)}}),Rl(A,"handleTouchMove",function(M){M.changedTouches!=null&&M.changedTouches.length>0&&A.throttleTriggeredAfterMouseMove(M.changedTouches[0])}),Rl(A,"handleTouchStart",function(M){M.changedTouches!=null&&M.changedTouches.length>0&&A.handleMouseDown(M.changedTouches[0])}),Rl(A,"handleTouchEnd",function(M){M.changedTouches!=null&&M.changedTouches.length>0&&A.handleMouseUp(M.changedTouches[0])}),Rl(A,"handleDoubleClick",function(M){var I=A.props.onDoubleClick;if(Dl(I)){var P=A.getMouseInfo(M);I(P,M)}}),Rl(A,"handleContextMenu",function(M){var I=A.props.onContextMenu;if(Dl(I)){var P=A.getMouseInfo(M);I(P,M)}}),Rl(A,"triggerSyncEvent",function(M){A.props.syncId!==void 0&&IRe.emit(LRe,A.props.syncId,M,A.eventEmitterSymbol)}),Rl(A,"applySyncEvent",function(M){var I=A.props,P=I.layout,R=I.syncMethod,O=A.state.updateId,B=M.dataStartIndex,U=M.dataEndIndex;if(M.dataStartIndex!==void 0||M.dataEndIndex!==void 0)A.setState(ra({dataStartIndex:B,dataEndIndex:U},p({props:A.props,dataStartIndex:B,dataEndIndex:U,updateId:O},A.state)));else if(M.activeTooltipIndex!==void 0){var G=M.chartX,H=M.chartY,Y=M.activeTooltipIndex,se=A.state,ee=se.offset,oe=se.tooltipTicks;if(!ee)return;if(typeof R=="function")Y=R(oe,M);else if(R==="value"){Y=-1;for(var me=0;me=0){var Be,je;if(G.dataKey&&!G.allowDuplicatedCategory){var Ye=typeof G.dataKey=="function"?Ue:"payload.".concat(G.dataKey.toString());Be=j5e(me,Ye,Y),je=Q&&te&&j5e(te,Ye,Y)}else Be=me==null?void 0:me[H],je=Q&&te&&te[H];if(he||ve){var Ee=M.props.activeIndex!==void 0?M.props.activeIndex:H;return[k.cloneElement(M,ra(ra(ra({},R.props),Te),{},{activeIndex:Ee})),null,null]}if(!hc(Be))return[Ie].concat(iq(A.renderActivePoints({item:R,activePoint:Be,basePoint:je,childIndex:H,isRange:Q})))}else{var Re,ke=(Re=A.getItemByXY(A.state.activeCoordinate))!==null&&Re!==void 0?Re:{graphicalItem:Ie},Fe=ke.graphicalItem,Oe=Fe.item,Ge=Oe===void 0?M:Oe,yt=Fe.childIndex,tt=ra(ra(ra({},R.props),Te),{},{activeIndex:yt});return[k.cloneElement(Ge,tt),null,null]}return Q?[Ie,null,null]:[Ie,null]}),Rl(A,"renderCustomized",function(M,I,P){return k.cloneElement(M,ra(ra({key:"recharts-customized-".concat(P)},A.props),A.state))}),Rl(A,"renderMap",{CartesianGrid:{handler:hae,once:!0},ReferenceArea:{handler:A.renderReferenceElement},ReferenceLine:{handler:hae},ReferenceDot:{handler:A.renderReferenceElement},XAxis:{handler:hae},YAxis:{handler:hae},Brush:{handler:A.renderBrush,once:!0},Bar:{handler:A.renderGraphicChild},Line:{handler:A.renderGraphicChild},Area:{handler:A.renderGraphicChild},Radar:{handler:A.renderGraphicChild},RadialBar:{handler:A.renderGraphicChild},Scatter:{handler:A.renderGraphicChild},Pie:{handler:A.renderGraphicChild},Funnel:{handler:A.renderGraphicChild},Tooltip:{handler:A.renderCursor,once:!0},PolarGrid:{handler:A.renderPolarGrid,once:!0},PolarAngleAxis:{handler:A.renderPolarAxis},PolarRadiusAxis:{handler:A.renderPolarAxis},Customized:{handler:A.renderCustomized}}),A.clipPathId="".concat((j=_.id)!==null&&j!==void 0?j:LF("recharts"),"-clip"),A.throttleTriggeredAfterMouseMove=p8t(A.triggeredAfterMouseMove,(C=_.throttleDelay)!==null&&C!==void 0?C:1e3/60),A.state={},A}return y1n(v,y),f1n(v,[{key:"componentDidMount",value:function(){var j,C;this.addListener(),this.accessibilityManager.setDetails({container:this.container,offset:{left:(j=this.props.margin.left)!==null&&j!==void 0?j:0,top:(C=this.props.margin.top)!==null&&C!==void 0?C:0},coordinateList:this.state.tooltipTicks,mouseHandlerCallback:this.triggeredAfterMouseMove,layout:this.props.layout}),this.displayDefaultTooltip()}},{key:"displayDefaultTooltip",value:function(){var j=this.props,C=j.children,A=j.data,M=j.height,I=j.layout,P=Lw(C,vg);if(P){var R=P.props.defaultIndex;if(!(typeof R!="number"||R<0||R>this.state.tooltipTicks.length-1)){var O=this.state.tooltipTicks[R]&&this.state.tooltipTicks[R].value,B=DBe(this.state,A,R,O),U=this.state.tooltipTicks[R].coordinate,G=(this.state.offset.top+M)/2,H=I==="horizontal",Y=H?{x:U,y:G}:{y:U,x:G},se=this.state.formattedGraphicalItems.find(function(oe){var me=oe.item;return me.type.name==="Scatter"});se&&(Y=ra(ra({},Y),se.props.points[R].tooltipPosition),B=se.props.points[R].tooltipPayload);var ee={activeTooltipIndex:R,isTooltipActive:!0,activeLabel:O,activePayload:B,activeCoordinate:Y};this.setState(ee),this.renderCursor(P),this.accessibilityManager.setIndex(R)}}}},{key:"getSnapshotBeforeUpdate",value:function(j,C){if(!this.props.accessibilityLayer)return null;if(this.state.tooltipTicks!==C.tooltipTicks&&this.accessibilityManager.setDetails({coordinateList:this.state.tooltipTicks}),this.props.layout!==j.layout&&this.accessibilityManager.setDetails({layout:this.props.layout}),this.props.margin!==j.margin){var A,M;this.accessibilityManager.setDetails({offset:{left:(A=this.props.margin.left)!==null&&A!==void 0?A:0,top:(M=this.props.margin.top)!==null&&M!==void 0?M:0}})}return null}},{key:"componentDidUpdate",value:function(j){dze([Lw(j.children,vg)],[Lw(this.props.children,vg)])||this.displayDefaultTooltip()}},{key:"componentWillUnmount",value:function(){this.removeListener(),this.throttleTriggeredAfterMouseMove.cancel()}},{key:"getTooltipEventType",value:function(){var j=Lw(this.props.children,vg);if(j&&typeof j.props.shared=="boolean"){var C=j.props.shared?"axis":"item";return o.indexOf(C)>=0?C:i}return i}},{key:"getMouseInfo",value:function(j){if(!this.container)return null;var C=this.container,A=C.getBoundingClientRect(),M=oon(A),I={chartX:Math.round(j.pageX-M.left),chartY:Math.round(j.pageY-M.top)},P=A.width/C.offsetWidth||1,R=this.inRange(I.chartX,I.chartY,P);if(!R)return null;var O=this.state,B=O.xAxisMap,U=O.yAxisMap,G=this.getTooltipEventType(),H=fxt(this.state,this.props.data,this.props.layout,R);if(G!=="axis"&&B&&U){var Y=PE(B).scale,se=PE(U).scale,ee=Y&&Y.invert?Y.invert(I.chartX):null,oe=se&&se.invert?se.invert(I.chartY):null;return ra(ra({},I),{},{xValue:ee,yValue:oe},H)}return H?ra(ra({},I),H):null}},{key:"inRange",value:function(j,C){var A=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1,M=this.props.layout,I=j/A,P=C/A;if(M==="horizontal"||M==="vertical"){var R=this.state.offset,O=I>=R.left&&I<=R.left+R.width&&P>=R.top&&P<=R.top+R.height;return O?{x:I,y:P}:null}var B=this.state,U=B.angleAxisMap,G=B.radiusAxisMap;if(U&&G){var H=PE(U);return Bpt({x:I,y:P},H)}return null}},{key:"parseEventsOfWrapper",value:function(){var j=this.props.children,C=this.getTooltipEventType(),A=Lw(j,vg),M={};A&&C==="axis"&&(A.props.trigger==="click"?M={onClick:this.handleClick}:M={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 I=N5e(this.props,this.handleOuterEvent);return ra(ra({},I),M)}},{key:"addListener",value:function(){IRe.on(LRe,this.handleReceiveSyncEvent)}},{key:"removeListener",value:function(){IRe.removeListener(LRe,this.handleReceiveSyncEvent)}},{key:"filterFormatItem",value:function(j,C,A){for(var M=this.state.formattedGraphicalItems,I=0,P=M.length;I{const{data:_,error:j}=await V.from("email_campaigns").select("*").eq("status","sent").order("sent_at",{ascending:!0});if(j)throw j;return _}}),{data:r}=pt({queryKey:["campaign-agent-profiles"],queryFn:async()=>{const{data:_,error:j}=await V.from("profiles").select("id, name, email");if(j)throw j;return _}});if(n)return e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"Loading analytics..."});const a=t||[],i=new Map((r||[]).map(_=>[_.id,_])),l=a.reduce((_,j)=>_+(j.sent_count||0),0),o=a.reduce((_,j)=>_+(j.open_count||0),0),c=a.reduce((_,j)=>_+(j.click_count||0),0),d=a.reduce((_,j)=>_+(j.bounce_count||0),0),u=a.reduce((_,j)=>_+(j.complaint_count||0),0),h=l>0?(o/l*100).toFixed(1):"0.0",m=l>0?(c/l*100).toFixed(1):"0.0",p=[{label:"Campaigns Sent",value:a.length,icon:Wr,color:"text-foreground"},{label:"Total Emails Sent",value:l,icon:Xn,color:"text-green-600"},{label:"Avg Open Rate",value:`${h}%`,icon:ba,color:"text-blue-600"},{label:"Avg Click Rate",value:`${m}%`,icon:sv,color:"text-purple-600"},{label:"Total Bounces",value:d,icon:Gd,color:"text-orange-600"},{label:"Complaints",value:u,icon:mc,color:"text-destructive"}],g=new Map;a.forEach(_=>{var A,M;const j=_.user_id,C=g.get(j)||{name:((A=i.get(j))==null?void 0:A.name)||((M=i.get(j))==null?void 0:M.email)||"Unknown",campaigns:0,sent:0,opens:0,clicks:0};C.campaigns++,C.sent+=_.sent_count||0,C.opens+=_.open_count||0,C.clicks+=_.click_count||0,g.set(j,C)});const x=[...g.entries()].map(([_,j])=>({id:_,...j,openRate:j.sent>0?+(j.opens/j.sent*100).toFixed(1):0})).sort((_,j)=>j.sent-_.sent),y=x.slice(0,6).map(_=>({name:_.name,value:_.sent})),v=a.map(_=>{var j;return{name:_.name.length>20?_.name.slice(0,20)+"…":_.name,agent:((j=i.get(_.user_id))==null?void 0:j.name)||"Unknown",openRate:_.sent_count>0?+(_.open_count/_.sent_count*100).toFixed(1):0,clickRate:_.sent_count>0?+(_.click_count/_.sent_count*100).toFixed(1):0,sent:_.sent_count,date:_.sent_at?Ys(new Date(_.sent_at),"MMM d"):""}});return e.jsx("div",{className:"space-y-6",children:a.length===0?e.jsx(we,{children:e.jsxs(De,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Wr,{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:p.map(_=>e.jsx(we,{children:e.jsxs(De,{className:"p-4 text-center",children:[e.jsx(_.icon,{className:`h-5 w-5 mx-auto mb-1 ${_.color}`}),e.jsx("p",{className:"text-2xl font-bold",children:_.value}),e.jsx("p",{className:"text-xs text-muted-foreground",children:_.label})]})},_.label))}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsx(Yt,{className:"text-base",children:"Open & Click Rates by Campaign"})}),e.jsx(De,{children:e.jsx("div",{className:"h-[280px]",children:e.jsx(C_,{width:"100%",height:"100%",children:e.jsxs(YEe,{data:v,children:[e.jsx(Cb,{dataKey:"date",fontSize:11}),e.jsx(Ab,{fontSize:11,unit:"%"}),e.jsx(vg,{formatter:_=>`${_}%`}),e.jsx(R2,{dataKey:"openRate",fill:"hsl(220, 70%, 50%)",name:"Open Rate",radius:[2,2,0,0]}),e.jsx(R2,{dataKey:"clickRate",fill:"hsl(270, 70%, 50%)",name:"Click Rate",radius:[2,2,0,0]})]})})})})]}),e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsx(Yt,{className:"text-base",children:"Send Volume by Agent"})}),e.jsx(De,{children:e.jsx("div",{className:"h-[280px]",children:e.jsx(C_,{width:"100%",height:"100%",children:e.jsxs(xZe,{children:[e.jsx(Mk,{data:y,dataKey:"value",nameKey:"name",cx:"50%",cy:"50%",outerRadius:100,label:({name:_,percent:j})=>`${_} (${(j*100).toFixed(0)}%)`,fontSize:11,children:y.map((_,j)=>e.jsx(vV,{fill:xxt[j%xxt.length]},j))}),e.jsx(vg,{})]})})})})]})]}),e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsx(Yt,{className:"text-base",children:"Send Volume Trend"})}),e.jsx(De,{children:e.jsx("div",{className:"h-[240px]",children:e.jsx(C_,{width:"100%",height:"100%",children:e.jsxs(gZe,{data:v,children:[e.jsx(Cb,{dataKey:"date",fontSize:11}),e.jsx(Ab,{fontSize:11}),e.jsx(vg,{}),e.jsx(FF,{type:"monotone",dataKey:"sent",stroke:"hsl(142, 71%, 45%)",strokeWidth:2,name:"Emails Sent",dot:{r:4}})]})})})})]}),e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsx(Yt,{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:x.map(_=>e.jsxs("tr",{className:"border-b last:border-0 hover:bg-muted/30",children:[e.jsx("td",{className:"py-2.5 font-medium",children:_.name}),e.jsx("td",{className:"py-2.5 text-center",children:_.campaigns}),e.jsx("td",{className:"py-2.5 text-center",children:_.sent}),e.jsx("td",{className:"py-2.5 text-center",children:_.opens}),e.jsx("td",{className:"py-2.5 text-center",children:_.clicks}),e.jsx("td",{className:"py-2.5 text-center",children:e.jsxs(qe,{variant:"outline",children:[_.openRate,"%"]})})]},_.id))})]})})})]}),e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsx(Yt,{className:"text-base",children:"Campaign Leaderboard"})}),e.jsx(De,{children:e.jsx("div",{className:"space-y-2",children:[...a].sort((_,j)=>{const C=_.sent_count>0?_.open_count/_.sent_count:0;return(j.sent_count>0?j.open_count/j.sent_count:0)-C}).slice(0,10).map((_,j)=>{const C=_.sent_count>0?(_.open_count/_.sent_count*100).toFixed(1):"0.0",A=_.sent_count>0?(_.click_count/_.sent_count*100).toFixed(1):"0.0",M=i.get(_.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/${_.id}`),children:[e.jsxs("span",{className:"text-lg font-bold text-muted-foreground w-6",children:["#",j+1]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:_.name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[(M==null?void 0:M.name)||"Unknown"," · ",_.sent_at?Ys(new Date(_.sent_at),"MMM d, yyyy"):""," · ",_.sent_count," sent"]})]}),e.jsxs("div",{className:"flex gap-3 text-xs",children:[e.jsxs(qe,{variant:"outline",className:"gap-1",children:[e.jsx(ba,{className:"h-3 w-3"})," ",C,"%"]}),e.jsxs(qe,{variant:"outline",className:"gap-1",children:[e.jsx(sv,{className:"h-3 w-3"})," ",A,"%"]})]})]},_.id)})})})]})]})})}const R1n=()=>{const{toast:s}=Fi(),[t,n]=k.useState(!0),[r,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{n(!0);const u=new Date;u.setDate(u.getDate()-30);const h=u.toISOString(),{data:m}=await V.from("website_apps").select("slug, name").order("sort_order"),p=[];let g=0;for(;;){const{data:A,error:M}=await V.from("agent_website_app_installs").select("user_id, app_slug, enabled").range(g,g+999);if(M)throw M;if(p.push(...A||[]),!A||A.length<1e3)break;g+=1e3}const x=[];for(g=0;;){const{data:A,error:M}=await V.from("widget_events").select("user_id, app_slug, event_type, created_at").gte("created_at",h).order("created_at",{ascending:!1}).range(g,g+999);if(M)throw M;if(x.push(...A||[]),!A||A.length<1e3||(g+=1e3,g>2e4))break}const y=new Map;for(const A of m||[])y.set(A.slug,{app_slug:A.slug,app_name:A.name,installs:0,enabled:0,impressions:0,expands:0,cta_clicks:0,lead_captures:0});for(const A of p){const M=y.get(A.app_slug);M&&(M.installs+=1,A.enabled&&(M.enabled+=1))}for(const A of x){const M=y.get(A.app_slug);M&&(A.event_type==="impression"?M.impressions+=1:A.event_type==="expand"?M.expands+=1:A.event_type==="cta_click"?M.cta_clicks+=1:A.event_type==="lead_capture"&&(M.lead_captures+=1))}const v=new Map;for(const A of p){if(!A.enabled)continue;const M=v.get(A.user_id)||{user_id:A.user_id,name:null,email:null,apps_enabled:[],events_30d:0,leads_30d:0};M.apps_enabled.includes(A.app_slug)||M.apps_enabled.push(A.app_slug),v.set(A.user_id,M)}for(const A of x){const M=v.get(A.user_id);M&&(M.events_30d+=1,A.event_type==="lead_capture"&&(M.leads_30d+=1))}const _=Array.from(v.keys());if(_.length>0){const{data:A}=await V.from("profiles").select("id, name, email").in("id",_);for(const M of A||[]){const I=v.get(M.id);I&&(I.name=M.name,I.email=M.email)}}const j=Array.from(y.values()),C=Array.from(v.values()).sort((A,M)=>M.events_30d-A.events_30d);a(j),l(C),c({installs:j.reduce((A,M)=>A+M.enabled,0),activeAgents:C.length,impressions30d:j.reduce((A,M)=>A+M.impressions,0),leads30d:j.reduce((A,M)=>A+M.lead_captures,0)})}catch(u){console.error(u),s({title:"Error",description:u.message||"Failed to load website app analytics",variant:"destructive"})}finally{n(!1)}};return t?e.jsx(we,{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(we,{children:[e.jsxs(Vt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Yt,{className:"text-sm font-medium",children:"Active Installs"}),e.jsx(kc,{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(we,{children:[e.jsxs(Vt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Yt,{className:"text-sm font-medium",children:"Agents Using Apps"}),e.jsx(Xn,{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(we,{children:[e.jsxs(Vt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Yt,{className:"text-sm font-medium",children:"Impressions (30d)"}),e.jsx(ba,{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(we,{children:[e.jsxs(Vt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Yt,{className:"text-sm font-medium",children:"Leads Captured (30d)"}),e.jsx(pn,{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(we,{children:[e.jsx(Vt,{children:e.jsx(Yt,{children:"App Performance (last 30 days)"})}),e.jsx(De,{children:e.jsxs(Qa,{children:[e.jsx(Ja,{children:e.jsxs(vn,{children:[e.jsx(Dt,{children:"App"}),e.jsx(Dt,{className:"text-right",children:"Installs"}),e.jsx(Dt,{className:"text-right",children:"Enabled"}),e.jsx(Dt,{className:"text-right",children:"Impressions"}),e.jsx(Dt,{className:"text-right",children:"Expands"}),e.jsx(Dt,{className:"text-right",children:"CTA Clicks"}),e.jsx(Dt,{className:"text-right",children:"Leads"}),e.jsx(Dt,{className:"text-right",children:"Conv. Rate"})]})}),e.jsxs(ei,{children:[r.map(u=>{const h=u.impressions>0?(u.lead_captures/u.impressions*100).toFixed(1):"—";return e.jsxs(vn,{children:[e.jsx(_t,{className:"font-medium",children:u.app_name}),e.jsx(_t,{className:"text-right",children:u.installs}),e.jsx(_t,{className:"text-right",children:u.enabled}),e.jsx(_t,{className:"text-right",children:u.impressions}),e.jsx(_t,{className:"text-right",children:u.expands}),e.jsx(_t,{className:"text-right",children:u.cta_clicks}),e.jsx(_t,{className:"text-right font-semibold",children:u.lead_captures}),e.jsx(_t,{className:"text-right text-muted-foreground",children:h==="—"?"—":`${h}%`})]},u.app_slug)}),r.length===0&&e.jsx(vn,{children:e.jsx(_t,{colSpan:8,className:"text-center text-muted-foreground py-6",children:"No data yet"})})]})]})})]}),e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsx(Yt,{children:"Agent Usage (last 30 days)"})}),e.jsxs(De,{children:[e.jsxs(Qa,{children:[e.jsx(Ja,{children:e.jsxs(vn,{children:[e.jsx(Dt,{children:"Agent"}),e.jsx(Dt,{children:"Email"}),e.jsx(Dt,{children:"Apps Enabled"}),e.jsx(Dt,{className:"text-right",children:"Events (30d)"}),e.jsx(Dt,{className:"text-right",children:"Leads (30d)"})]})}),e.jsxs(ei,{children:[i.slice(0,100).map(u=>e.jsxs(vn,{children:[e.jsx(_t,{className:"font-medium",children:u.name||"—"}),e.jsx(_t,{className:"text-muted-foreground",children:u.email||"—"}),e.jsx(_t,{children:e.jsx("div",{className:"flex flex-wrap gap-1",children:u.apps_enabled.map(h=>e.jsx(qe,{variant:"secondary",className:"text-xs",children:h},h))})}),e.jsx(_t,{className:"text-right",children:u.events_30d}),e.jsx(_t,{className:"text-right font-semibold",children:u.leads_30d})]},u.user_id)),i.length===0&&e.jsx(vn,{children:e.jsx(_t,{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."]})]})]})]})},D1n=()=>{const[s,t]=k.useState([]),[n,r]=k.useState([]),[a,i]=k.useState({}),[l,o]=k.useState(!0);k.useEffect(()=>{c()},[]);const c=async()=>{o(!0);try{const[{data:h},{data:m}]=await Promise.all([V.rpc("get_extension_usage_summary"),V.from("extension_usage_events").select("id, user_id, action, metadata, created_at").order("created_at",{ascending:!1}).limit(50)]),p=h||[],g=m||[];t(p),r(g);const x=Array.from(new Set(g.map(y=>y.user_id)));if(x.length){const{data:y}=await V.from("profiles").select("id, name, email").in("id",x),v={};(y||[]).forEach(_=>{v[_.id]={name:_.name,email:_.email}}),i(v)}}finally{o(!1)}},d=s.reduce((h,m)=>({users:h.users+1,contacts:h.contacts+Number(m.contacts_saved||0),listings:h.listings+Number(m.listings_imported||0),activities:h.activities+Number(m.activities_logged||0),events:h.events+Number(m.total_events||0)}),{users:0,contacts:0,listings:0,activities:0,events:0});if(l)return e.jsx(we,{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 u=h=>{switch(h){case"contact_saved":return"Contact saved";case"listing_imported":return"Listing imported";case"activity_logged":return"Activity logged";case"template_used":return"Template used";case"paired":return"Extension paired";default:return h}};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-5",children:[e.jsxs(we,{children:[e.jsxs(Vt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Yt,{className:"text-sm font-medium",children:"Active Users"}),e.jsx(Xn,{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(we,{children:[e.jsxs(Vt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Yt,{className:"text-sm font-medium",children:"Total Actions"}),e.jsx(R8,{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(we,{children:[e.jsxs(Vt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Yt,{className:"text-sm font-medium",children:"Contacts Saved"}),e.jsx(Pl,{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(we,{children:[e.jsxs(Vt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Yt,{className:"text-sm font-medium",children:"Listings Imported"}),e.jsx(ua,{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(we,{children:[e.jsxs(Vt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Yt,{className:"text-sm font-medium",children:"Activities Logged"}),e.jsx(bo,{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(we,{children:[e.jsx(Vt,{children:e.jsx(Yt,{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(Qa,{children:[e.jsx(Ja,{children:e.jsxs(vn,{children:[e.jsx(Dt,{children:"User"}),e.jsx(Dt,{className:"text-right",children:"Total"}),e.jsx(Dt,{className:"text-right",children:"Contacts"}),e.jsx(Dt,{className:"text-right",children:"Listings"}),e.jsx(Dt,{className:"text-right",children:"Activities"}),e.jsx(Dt,{children:"First Used"}),e.jsx(Dt,{children:"Last Used"})]})}),e.jsx(ei,{children:s.map(h=>e.jsxs(vn,{children:[e.jsxs(_t,{children:[e.jsx("div",{className:"font-medium",children:h.name||"—"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:h.email})]}),e.jsx(_t,{className:"text-right font-medium",children:h.total_events}),e.jsx(_t,{className:"text-right",children:h.contacts_saved}),e.jsx(_t,{className:"text-right",children:h.listings_imported}),e.jsx(_t,{className:"text-right",children:h.activities_logged}),e.jsx(_t,{className:"text-xs text-muted-foreground",children:h.first_event_at?Ys(new Date(h.first_event_at),"MMM d, yyyy"):"—"}),e.jsx(_t,{className:"text-xs text-muted-foreground",children:h.last_event_at?Ys(new Date(h.last_event_at),"MMM d, h:mm a"):"—"})]},h.user_id))})]})})})]}),e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsx(Yt,{children:"Recent Activity"})}),e.jsx(De,{children:n.length===0?e.jsx("p",{className:"text-sm text-muted-foreground py-4 text-center",children:"No recent events."}):e.jsx("div",{className:"space-y-2",children:n.map(h=>{const m=a[h.user_id];return e.jsxs("div",{className:"flex items-center justify-between border-b pb-2 last:border-0",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(qe,{variant:"secondary",children:u(h.action)}),e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium",children:(m==null?void 0:m.name)||(m==null?void 0:m.email)||h.user_id.slice(0,8)}),h.metadata&&Object.keys(h.metadata).length>0&&e.jsx("div",{className:"text-xs text-muted-foreground truncate max-w-md",children:JSON.stringify(h.metadata)})]})]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:Ys(new Date(h.created_at),"MMM d, h:mm a")})]},h.id)})})})]})]})},O1n=()=>e.jsx(Xs,{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(ya,{defaultValue:"analytics",className:"space-y-4",children:[e.jsxs(va,{children:[e.jsx(is,{value:"analytics",children:"Analytics"}),e.jsx(is,{value:"website-apps",children:"Website Apps"}),e.jsx(is,{value:"extension",children:"Chrome Extension"}),e.jsx(is,{value:"content",children:"Content"}),e.jsx(is,{value:"email-campaigns",children:"Email Campaigns"}),e.jsx(is,{value:"activity",children:"Activity"}),e.jsx(is,{value:"shares",children:"Shares"})]}),e.jsx(cs,{value:"analytics",className:"space-y-4",children:e.jsx(UGs,{})}),e.jsx(cs,{value:"website-apps",className:"space-y-4",children:e.jsx(R1n,{})}),e.jsx(cs,{value:"extension",className:"space-y-4",children:e.jsx(D1n,{})}),e.jsx(cs,{value:"content",className:"space-y-4",children:e.jsx(VGs,{})}),e.jsx(cs,{value:"email-campaigns",className:"space-y-4",children:e.jsx(L1n,{})}),e.jsx(cs,{value:"activity",className:"space-y-4",children:e.jsx($Gs,{})}),e.jsx(cs,{value:"shares",className:"space-y-4",children:e.jsx(JRt,{})})]})]})});function F1n(){const s=ls(),[t,n]=k.useState(!1),[r,a]=k.useState(null),[i,l]=k.useState({title:"",description:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1,category_id:""}),[o,c]=k.useState(null),[d,u]=k.useState(""),[h,m]=k.useState([]),[p,g]=k.useState([]),[x,y]=k.useState([]),[v,_]=k.useState(!1),[j,C]=k.useState(null),[A,M]=k.useState(""),{data:I,isLoading:P}=pt({queryKey:["brokerage-resources"],queryFn:async()=>{const{data:je,error:Ye}=await V.from("brokerage_resources").select("*").order("publish_date",{ascending:!1});if(Ye)throw Ye;return je}}),{data:R}=pt({queryKey:["brokerage-resource-pdfs"],queryFn:async()=>{const{data:je,error:Ye}=await V.from("brokerage_resource_pdfs").select("*").order("sort_order",{ascending:!0});if(Ye)throw Ye;return je}}),{data:O}=pt({queryKey:["brokerage-resource-videos"],queryFn:async()=>{const{data:je,error:Ye}=await V.from("brokerage_resource_videos").select("*").order("sort_order",{ascending:!0});if(Ye)throw Ye;return je}}),{data:B}=pt({queryKey:["brokerage-resource-links"],queryFn:async()=>{const{data:je,error:Ye}=await V.from("brokerage_resource_links").select("*").order("sort_order",{ascending:!0});if(Ye)throw Ye;return je}}),{data:U,isLoading:G}=pt({queryKey:["brokerage-resource-categories"],queryFn:async()=>{const{data:je,error:Ye}=await V.from("brokerage_resource_categories").select("*").order("sort_order",{ascending:!0});if(Ye)throw Ye;return je}}),H=()=>{l({title:"",description:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1,category_id:""}),c(null),u(""),m([]),g([]),y([]),a(null),M("")},Y=je=>{a(je),l({title:je.title,description:je.description||"",publish_date:je.publish_date.split("T")[0],is_published:je.is_published,category_id:je.category_id||""}),u(je.preview_image_url||""),M("");const Ye=(R==null?void 0:R.filter(ke=>ke.resource_id===je.id))||[];m(Ye.map(ke=>({id:ke.id,name:ke.name,file_url:ke.file_url,file_size:ke.file_size,sort_order:ke.sort_order})));const Ee=(O==null?void 0:O.filter(ke=>ke.resource_id===je.id))||[];g(Ee.map(ke=>({id:ke.id,title:ke.title,video_url:ke.video_url,sort_order:ke.sort_order})));const Re=(B==null?void 0:B.filter(ke=>ke.resource_id===je.id))||[];y(Re.map(ke=>({id:ke.id,title:ke.title,canva_share_link:ke.canva_share_link,sort_order:ke.sort_order}))),n(!0)},se=je=>{var Ee;const Ye=(Ee=je.target.files)==null?void 0:Ee[0];Ye&&(c(Ye),u(URL.createObjectURL(Ye)))},ee=()=>{m([...h,{name:"",file_url:"",sort_order:h.length}])},oe=je=>{m(h.filter((Ye,Ee)=>Ee!==je))},me=(je,Ye,Ee)=>{const Re=[...h];if(Ye==="file"&&Ee instanceof File){const ke=Ee.name.replace(/\.[^/.]+$/,"");Re[je]={...Re[je],file:Ee,file_size:Ee.size,name:Re[je].name||ke}}else Re[je]={...Re[je],[Ye]:Ee};m(Re)},Q=()=>{g([...p,{title:"",video_url:"",sort_order:p.length}])},te=je=>{g(p.filter((Ye,Ee)=>Ee!==je))},le=(je,Ye,Ee)=>{const Re=[...p];Ye==="file"&&Ee instanceof File?Re[je]={...Re[je],file:Ee}:Re[je]={...Re[je],[Ye]:Ee},g(Re)},fe=()=>{y([...x,{title:"",canva_share_link:"",sort_order:x.length}])},_e=je=>{y(x.filter((Ye,Ee)=>Ee!==je))},ve=(je,Ye,Ee)=>{const Re=[...x];Re[je]={...Re[je],[Ye]:Ee},y(Re)},he=async(je,Ye)=>{try{const Ee=await V.functions.invoke("bunny-upload",{body:{action:"create",title:je.name}});if(Ee.error)throw Ee.error;const{videoId:Re,uploadUrl:ke,libraryId:Fe}=Ee.data,Oe=await V.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:Re,libraryId:Fe}});if(Oe.error)throw Oe.error;const{uploadUrl:Ge,apiKey:yt}=Oe.data,tt=new XMLHttpRequest;return tt.open("PUT",Ge,!0),tt.setRequestHeader("AccessKey",yt),tt.upload.onprogress=ut=>{if(ut.lengthComputable){const nt=Math.round(ut.loaded/ut.total*100),et=[...p];et[Ye]={...et[Ye],uploadProgress:nt},g(et)}},await new Promise((ut,nt)=>{tt.onload=()=>tt.status>=200&&tt.status<300?ut():nt(new Error("Upload failed")),tt.onerror=()=>nt(new Error("Upload failed")),tt.send(je)}),`https://iframe.mediadelivery.net/embed/${Fe}/${Re}`}catch(Ee){throw console.error("Bunny upload error:",Ee),Ee}},Se=Nt({mutationFn:async je=>{const{data:Ye,error:Ee}=await V.from("brokerage_resource_categories").insert({name:je,sort_order:(U==null?void 0:U.length)||0}).select().single();if(Ee)throw Ee;return Ye},onSuccess:je=>{s.invalidateQueries({queryKey:["brokerage-resource-categories"]}),l({...i,category_id:je.id}),M(""),ae.success("Category created")},onError:je=>{ae.error("Failed to create category: "+je.message)}}),Te=Nt({mutationFn:async()=>{_(!0);let je=(r==null?void 0:r.preview_image_url)||null;if(o){const Re=o.name.split(".").pop(),ke=`${Date.now()}.${Re}`,{error:Fe}=await V.storage.from("brokerage-resources").upload(`previews/${ke}`,o);if(Fe)throw Fe;const{data:Oe}=V.storage.from("brokerage-resources").getPublicUrl(`previews/${ke}`);je=Oe.publicUrl}const Ye={title:i.title,description:i.description||null,preview_image_url:je,publish_date:i.publish_date,is_published:i.is_published,category_id:i.category_id||null};let Ee;if(r){const{error:Re}=await V.from("brokerage_resources").update(Ye).eq("id",r.id);if(Re)throw Re;Ee=r.id;const ke=(R==null?void 0:R.filter(at=>at.resource_id===r.id).map(at=>at.id))||[],Fe=h.filter(at=>at.id).map(at=>at.id),Oe=ke.filter(at=>!Fe.includes(at));Oe.length>0&&await V.from("brokerage_resource_pdfs").delete().in("id",Oe);const Ge=(O==null?void 0:O.filter(at=>at.resource_id===r.id).map(at=>at.id))||[],yt=p.filter(at=>at.id).map(at=>at.id),tt=Ge.filter(at=>!yt.includes(at));tt.length>0&&await V.from("brokerage_resource_videos").delete().in("id",tt);const ut=(B==null?void 0:B.filter(at=>at.resource_id===r.id).map(at=>at.id))||[],nt=x.filter(at=>at.id).map(at=>at.id),et=ut.filter(at=>!nt.includes(at));et.length>0&&await V.from("brokerage_resource_links").delete().in("id",et)}else{const{data:Re,error:ke}=await V.from("brokerage_resources").insert(Ye).select().single();if(ke)throw ke;Ee=Re.id}for(let Re=0;Re{s.invalidateQueries({queryKey:["brokerage-resources"]}),s.invalidateQueries({queryKey:["brokerage-resource-pdfs"]}),s.invalidateQueries({queryKey:["brokerage-resource-videos"]}),s.invalidateQueries({queryKey:["brokerage-resource-links"]}),ae.success(r?"Resource updated":"Resource created"),n(!1),H(),_(!1)},onError:je=>{ae.error("Failed to save resource: "+je.message),_(!1)}}),Ie=Nt({mutationFn:async je=>{const{error:Ye}=await V.from("brokerage_resources").delete().eq("id",je);if(Ye)throw Ye},onSuccess:()=>{s.invalidateQueries({queryKey:["brokerage-resources"]}),s.invalidateQueries({queryKey:["brokerage-resource-pdfs"]}),s.invalidateQueries({queryKey:["brokerage-resource-videos"]}),s.invalidateQueries({queryKey:["brokerage-resource-links"]}),ae.success("Resource deleted")},onError:je=>{ae.error("Failed to delete: "+je.message)}}),Ue=je=>{if(je.preventDefault(),!i.title){ae.error("Please enter a title");return}Te.mutate()},Be=je=>{const Ye=(R==null?void 0:R.filter(ke=>ke.resource_id===je).length)||0,Ee=(O==null?void 0:O.filter(ke=>ke.resource_id===je).length)||0,Re=(B==null?void 0:B.filter(ke=>ke.resource_id===je).length)||0;return{pdfCount:Ye,videoCount:Ee,linkCount:Re}};return e.jsx(Xs,{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(we,{children:[e.jsx(Vt,{className:"pb-2",children:e.jsx(Yt,{className:"text-sm font-medium text-muted-foreground",children:"Total Resources"})}),e.jsx(De,{children:e.jsx("div",{className:"text-2xl font-bold",children:(I==null?void 0:I.length)||0})})]}),e.jsxs(we,{children:[e.jsx(Vt,{className:"pb-2",children:e.jsx(Yt,{className:"text-sm font-medium text-muted-foreground",children:"Published"})}),e.jsx(De,{children:e.jsx("div",{className:"text-2xl font-bold",children:(I==null?void 0:I.filter(je=>je.is_published).length)||0})})]})]}),e.jsxs($,{onClick:()=>{H(),n(!0)},children:[e.jsx(nn,{className:"h-4 w-4 mr-2"}),"Add Resource"]})]}),e.jsx(we,{children:e.jsx(De,{className:"p-0",children:e.jsxs(Qa,{children:[e.jsx(Ja,{children:e.jsxs(vn,{children:[e.jsx(Dt,{children:"Title"}),e.jsx(Dt,{children:"Category"}),e.jsx(Dt,{children:"Content"}),e.jsx(Dt,{children:"Publish Date"}),e.jsx(Dt,{children:"Status"}),e.jsx(Dt,{className:"text-right",children:"Actions"})]})}),e.jsx(ei,{children:P?e.jsx(vn,{children:e.jsx(_t,{colSpan:6,className:"text-center py-8",children:"Loading..."})}):(I==null?void 0:I.length)===0?e.jsx(vn,{children:e.jsx(_t,{colSpan:6,className:"text-center py-8 text-muted-foreground",children:"No brokerage resources yet. Create your first one!"})}):I==null?void 0:I.map(je=>{const{pdfCount:Ye,videoCount:Ee,linkCount:Re}=Be(je.id),ke=U==null?void 0:U.find(Fe=>Fe.id===je.category_id);return e.jsxs(vn,{children:[e.jsx(_t,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[je.preview_image_url?e.jsx("img",{src:je.preview_image_url,alt:je.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(zx,{className:"h-5 w-5 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:je.title}),je.description&&e.jsx("div",{className:"text-sm text-muted-foreground line-clamp-1",children:je.description})]})]})}),e.jsx(_t,{children:ke?e.jsx("span",{className:"inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-muted",children:ke.name}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"—"})}),e.jsx(_t,{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(ea,{className:"h-3.5 w-3.5"}),Ye]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ia,{className:"h-3.5 w-3.5"}),Ee]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(od,{className:"h-3.5 w-3.5"}),Re]})]})}),e.jsx(_t,{children:Ys(new Date(je.publish_date),"MMM d, yyyy")}),e.jsx(_t,{children:e.jsx("span",{className:`inline-flex items-center px-2 py-1 rounded-full text-xs font-medium ${je.is_published?"bg-green-100 text-green-800":"bg-yellow-100 text-yellow-800"}`,children:je.is_published?"Published":"Draft"})}),e.jsx(_t,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx($,{variant:"ghost",size:"icon",onClick:()=>{const Fe=(R==null?void 0:R.filter(yt=>yt.resource_id===je.id))||[],Oe=(O==null?void 0:O.filter(yt=>yt.resource_id===je.id))||[],Ge=(B==null?void 0:B.filter(yt=>yt.resource_id===je.id))||[];C({...je,pdfs:Fe,videos:Oe,links:Ge})},children:e.jsx(ba,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>Y(je),children:e.jsx(ui,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:async()=>{await io("Delete this resource?")&&Ie.mutate(je.id)},children:e.jsx(Un,{className:"h-4 w-4 text-destructive"})})]})})]},je.id)})})]})})}),e.jsx(zs,{open:t,onOpenChange:n,children:e.jsxs(Rs,{className:"max-w-3xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Vs,{children:e.jsx($s,{children:r?"Edit Brokerage Resource":"Add Brokerage Resource"})}),e.jsxs("form",{onSubmit:Ue,className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{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(zx,{className:"h-8 w-8 text-muted-foreground"})}),e.jsx(be,{type:"file",accept:"image/*",onChange:se})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"title",children:"Title *"}),e.jsx(be,{id:"title",value:i.title,onChange:je=>l({...i,title:je.target.value}),placeholder:"Resource Title"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(re,{className:"flex items-center gap-2",children:[e.jsx(kg,{className:"h-4 w-4"}),"Category"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(bs,{value:i.category_id,onValueChange:je=>l({...i,category_id:je}),children:[e.jsx(ys,{className:"flex-1",children:e.jsx(_s,{placeholder:"Select a category"})}),e.jsx(vs,{children:U==null?void 0:U.map(je=>e.jsx(We,{value:je.id,children:je.name},je.id))})]}),i.category_id&&e.jsx($,{type:"button",variant:"ghost",size:"icon",onClick:()=>l({...i,category_id:""}),children:e.jsx(mr,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(be,{placeholder:"Or create new category...",value:A,onChange:je=>M(je.target.value),className:"flex-1"}),e.jsxs($,{type:"button",variant:"outline",size:"sm",disabled:!A.trim()||Se.isPending,onClick:()=>Se.mutate(A.trim()),children:[e.jsx(nn,{className:"h-4 w-4 mr-1"}),"Add"]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Description"}),e.jsx(V2,{content:i.description,onChange:je=>l({...i,description:je}),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(re,{htmlFor:"publish_date",children:"Publish Date"}),e.jsx(be,{id:"publish_date",type:"date",value:i.publish_date,onChange:je=>l({...i,publish_date:je.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Published"}),e.jsxs("div",{className:"flex items-center space-x-2 pt-2",children:[e.jsx(On,{checked:i.is_published,onCheckedChange:je=>l({...i,is_published:je})}),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(re,{className:"flex items-center gap-2",children:[e.jsx(ea,{className:"h-4 w-4"}),"PDF Documents (",h.length,")"]}),e.jsxs($,{type:"button",variant:"outline",size:"sm",onClick:ee,children:[e.jsx(nn,{className:"h-4 w-4 mr-1"}),"Add PDF"]})]}),h.map((je,Ye)=>e.jsxs("div",{className:"flex items-center gap-2 p-3 border rounded-lg bg-muted/50",children:[e.jsx(be,{placeholder:"PDF Name",value:je.name,onChange:Ee=>me(Ye,"name",Ee.target.value),className:"flex-1"}),e.jsx(be,{type:"file",accept:".pdf",onChange:Ee=>{var ke;const Re=(ke=Ee.target.files)==null?void 0:ke[0];Re&&me(Ye,"file",Re)},className:"flex-1"}),je.file_url&&!je.file&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"Uploaded"}),e.jsx($,{type:"button",variant:"ghost",size:"icon",onClick:()=>oe(Ye),children:e.jsx(mr,{className:"h-4 w-4"})})]},Ye))]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(re,{className:"flex items-center gap-2",children:[e.jsx(ia,{className:"h-4 w-4"}),"Videos (",p.length,")"]}),e.jsxs($,{type:"button",variant:"outline",size:"sm",onClick:Q,children:[e.jsx(nn,{className:"h-4 w-4 mr-1"}),"Add Video"]})]}),p.map((je,Ye)=>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(be,{placeholder:"Video Title",value:je.title,onChange:Ee=>le(Ye,"title",Ee.target.value),className:"flex-1"}),e.jsx($,{type:"button",variant:"ghost",size:"icon",onClick:()=>te(Ye),children:e.jsx(mr,{className:"h-4 w-4"})})]}),e.jsx(be,{type:"file",accept:"video/*",onChange:Ee=>{var ke;const Re=(ke=Ee.target.files)==null?void 0:ke[0];Re&&le(Ye,"file",Re)}}),je.uploadProgress!==void 0&&je.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:`${je.uploadProgress}%`}})}),je.video_url&&!je.file&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"Video uploaded"})]},Ye))]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(re,{className:"flex items-center gap-2",children:[e.jsx(od,{className:"h-4 w-4"}),"Canva Links (",x.length,")"]}),e.jsxs($,{type:"button",variant:"outline",size:"sm",onClick:fe,children:[e.jsx(nn,{className:"h-4 w-4 mr-1"}),"Add Link"]})]}),x.map((je,Ye)=>e.jsxs("div",{className:"flex items-center gap-2 p-3 border rounded-lg bg-muted/50",children:[e.jsx(be,{placeholder:"Link Title",value:je.title,onChange:Ee=>ve(Ye,"title",Ee.target.value),className:"flex-1"}),e.jsx(be,{placeholder:"Canva Share Link",value:je.canva_share_link,onChange:Ee=>ve(Ye,"canva_share_link",Ee.target.value),className:"flex-1"}),e.jsx($,{type:"button",variant:"ghost",size:"icon",onClick:()=>_e(Ye),children:e.jsx(mr,{className:"h-4 w-4"})})]},Ye))]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx($,{type:"button",variant:"outline",onClick:()=>n(!1),children:"Cancel"}),e.jsx($,{type:"submit",disabled:Te.isPending||v,children:Te.isPending||v?"Saving...":r?"Update":"Create"})]})]})]})}),e.jsx(zs,{open:!!j,onOpenChange:()=>C(null),children:e.jsxs(Rs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Vs,{children:e.jsx($s,{children:j==null?void 0:j.title})}),j&&e.jsxs("div",{className:"space-y-4",children:[j.preview_image_url&&e.jsx("img",{src:j.preview_image_url,alt:j.title,className:"w-full h-48 object-cover rounded-lg"}),j.description&&e.jsx("p",{className:"text-muted-foreground",children:j.description}),j.pdfs&&j.pdfs.length>0&&e.jsxs("div",{children:[e.jsxs("h4",{className:"font-medium mb-2 flex items-center gap-2",children:[e.jsx(ea,{className:"h-4 w-4"}),"PDF Documents (",j.pdfs.length,")"]}),e.jsx("div",{className:"space-y-1",children:j.pdfs.map(je=>e.jsx("a",{href:je.file_url,target:"_blank",rel:"noopener noreferrer",className:"block p-2 border rounded hover:bg-muted",children:je.name},je.id))})]}),j.videos&&j.videos.length>0&&e.jsxs("div",{children:[e.jsxs("h4",{className:"font-medium mb-2 flex items-center gap-2",children:[e.jsx(ia,{className:"h-4 w-4"}),"Videos (",j.videos.length,")"]}),e.jsx("div",{className:"space-y-2",children:j.videos.map(je=>e.jsx("div",{className:"p-2 border rounded",children:e.jsx("p",{className:"font-medium text-sm",children:je.title})},je.id))})]}),j.links&&j.links.length>0&&e.jsxs("div",{children:[e.jsxs("h4",{className:"font-medium mb-2 flex items-center gap-2",children:[e.jsx(od,{className:"h-4 w-4"}),"Canva Links (",j.links.length,")"]}),e.jsx("div",{className:"space-y-1",children:j.links.map(je=>e.jsx("a",{href:je.canva_share_link,target:"_blank",rel:"noopener noreferrer",className:"block p-2 border rounded hover:bg-muted",children:je.title},je.id))})]})]})]})})]})})}const qFt=[{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 z1n(){const[s,t]=k.useState([]),[n,r]=k.useState(!0),[a,i]=k.useState(!1),[l,o]=k.useState(!1),[c,d]=k.useState(null),[u,h]=k.useState(!1),[m,p]=k.useState(!1),[g,x]=k.useState(""),[y,v]=k.useState(""),[_,j]=k.useState(""),[C,A]=k.useState(""),[M,I]=k.useState("Learn More"),[P,R]=k.useState("top"),[O,B]=k.useState(""),[U,G]=k.useState(!0),[H,Y]=k.useState(""),[se,ee]=k.useState("");k.useEffect(()=>{oe()},[]);const oe=async()=>{try{const{data:Se,error:Te}=await V.from("dashboard_banners").select("*").order("placement").order("sort_order");if(Te)throw Te;t(Se||[])}catch(Se){ae.error("Failed to load banners: "+Se.message)}finally{r(!1)}},me=()=>{x(""),v(""),j(""),A(""),I("Learn More"),R("top"),B(""),G(!0),Y(""),ee(""),d(null)},Q=Se=>{d(Se),x(Se.title),v(Se.description||""),j(Se.image_url),A(Se.link_url||""),I(Se.link_text||"Learn More"),R(Se.placement),B(Se.section_after||""),G(Se.is_active),Y(Se.start_date?Ys(new Date(Se.start_date),"yyyy-MM-dd'T'HH:mm"):""),ee(Se.end_date?Ys(new Date(Se.end_date),"yyyy-MM-dd'T'HH:mm"):""),i(!0)},te=async Se=>{var Ie;const Te=(Ie=Se.target.files)==null?void 0:Ie[0];if(Te){h(!0);try{const Ue=Te.name.split(".").pop(),Be=`${Date.now()}.${Ue}`,{error:je}=await V.storage.from("banner-images").upload(Be,Te);if(je)throw je;const{data:{publicUrl:Ye}}=V.storage.from("banner-images").getPublicUrl(Be);j(Ye),ae.success("Image uploaded successfully")}catch(Ue){ae.error("Failed to upload image: "+Ue.message)}finally{h(!1)}}},le=async()=>{if(!g.trim()||!_){ae.error("Please fill in required fields (title and image)");return}p(!0);try{const Se={title:g.trim(),description:y.trim()||null,image_url:_,link_url:C.trim()||null,link_text:M.trim()||"Learn More",placement:P,section_after:P==="between"?O:null,is_active:U,start_date:H?new Date(H).toISOString():null,end_date:se?new Date(se).toISOString():null};if(c){const{error:Te}=await V.from("dashboard_banners").update(Se).eq("id",c.id);if(Te)throw Te;ae.success("Banner updated successfully")}else{const Te=s.filter(Ue=>Ue.placement===P).length,{error:Ie}=await V.from("dashboard_banners").insert({...Se,sort_order:Te});if(Ie)throw Ie;ae.success("Banner created successfully")}i(!1),me(),oe()}catch(Se){ae.error("Failed to save banner: "+Se.message)}finally{p(!1)}},fe=async()=>{if(c)try{const{error:Se}=await V.from("dashboard_banners").delete().eq("id",c.id);if(Se)throw Se;ae.success("Banner deleted successfully"),o(!1),d(null),oe()}catch(Se){ae.error("Failed to delete banner: "+Se.message)}},_e=async Se=>{try{const{error:Te}=await V.from("dashboard_banners").update({is_active:!Se.is_active}).eq("id",Se.id);if(Te)throw Te;ae.success(Se.is_active?"Banner deactivated":"Banner activated"),oe()}catch(Te){ae.error("Failed to update banner: "+Te.message)}},ve=s.filter(Se=>Se.placement==="top"),he=s.filter(Se=>Se.placement==="between");return n?e.jsx(Xs,{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(Xs,{title:"Dashboard Management",description:"Configure dashboard modules and banners",children:[e.jsxs("div",{className:"space-y-8",children:[e.jsxs(we,{children:[e.jsxs(Vt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(Yt,{className:"flex items-center gap-2",children:[e.jsx(zc,{className:"h-5 w-5"}),"Hero Banners (Top of Dashboard)"]}),e.jsx(vr,{children:"These banners appear in a rotating carousel at the top of the dashboard"})]}),e.jsxs(zs,{open:a&&P==="top",onOpenChange:Se=>{Se||me(),i(Se),Se&&R("top")},children:[e.jsx(yl,{asChild:!0,children:e.jsxs($,{onClick:()=>{me(),R("top")},children:[e.jsx(nn,{className:"mr-2 h-4 w-4"}),"Add Hero Banner"]})}),e.jsxs(Rs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(Vs,{children:[e.jsxs($s,{children:[c?"Edit":"Create"," Banner"]}),e.jsx(Cr,{children:"Configure the banner's content and display settings"})]}),e.jsx(yxt,{title:g,setTitle:x,description:y,setDescription:v,imageUrl:_,linkUrl:C,setLinkUrl:A,linkText:M,setLinkText:I,placement:P,setPlacement:R,sectionAfter:O,setSectionAfter:B,isActive:U,setIsActive:G,startDate:H,setStartDate:Y,endDate:se,setEndDate:ee,handleImageUpload:te,uploading:u,showPlacementOptions:!1}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>{i(!1),me()},children:"Cancel"}),e.jsx($,{onClick:le,disabled:m,children:m?"Saving...":c?"Update Banner":"Create Banner"})]})]})]})]}),e.jsx(De,{children:ve.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:ve.map(Se=>e.jsx(vxt,{banner:Se,onEdit:()=>Q(Se),onDelete:()=>{d(Se),o(!0)},onToggleActive:()=>_e(Se)},Se.id))})})]}),e.jsxs(we,{children:[e.jsxs(Vt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(Yt,{className:"flex items-center gap-2",children:[e.jsx(zc,{className:"h-5 w-5"}),"Section Banners"]}),e.jsx(vr,{children:"These banners appear between dashboard content sections"})]}),e.jsxs(zs,{open:a&&P==="between",onOpenChange:Se=>{Se||me(),i(Se),Se&&R("between")},children:[e.jsx(yl,{asChild:!0,children:e.jsxs($,{onClick:()=>{me(),R("between")},children:[e.jsx(nn,{className:"mr-2 h-4 w-4"}),"Add Section Banner"]})}),e.jsxs(Rs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(Vs,{children:[e.jsxs($s,{children:[c?"Edit":"Create"," Section Banner"]}),e.jsx(Cr,{children:"Configure where this banner appears between sections"})]}),e.jsx(yxt,{title:g,setTitle:x,description:y,setDescription:v,imageUrl:_,linkUrl:C,setLinkUrl:A,linkText:M,setLinkText:I,placement:P,setPlacement:R,sectionAfter:O,setSectionAfter:B,isActive:U,setIsActive:G,startDate:H,setStartDate:Y,endDate:se,setEndDate:ee,handleImageUpload:te,uploading:u,showPlacementOptions:!0}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>{i(!1),me()},children:"Cancel"}),e.jsx($,{onClick:le,disabled:m,children:m?"Saving...":c?"Update Banner":"Create Banner"})]})]})]})]}),e.jsx(De,{children:he.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:he.map(Se=>e.jsx(vxt,{banner:Se,onEdit:()=>Q(Se),onDelete:()=>{d(Se),o(!0)},onToggleActive:()=>_e(Se),showSection:!0},Se.id))})})]})]}),e.jsx(zs,{open:l,onOpenChange:o,children:e.jsxs(Rs,{children:[e.jsxs(Vs,{children:[e.jsx($s,{children:"Delete Banner"}),e.jsxs(Cr,{children:['Are you sure you want to delete "',c==null?void 0:c.title,'"? This action cannot be undone.']})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>o(!1),children:"Cancel"}),e.jsx($,{variant:"destructive",onClick:fe,children:"Delete"})]})]})})]})}function yxt({title:s,setTitle:t,description:n,setDescription:r,imageUrl:a,linkUrl:i,setLinkUrl:l,linkText:o,setLinkText:c,placement:d,setPlacement:u,sectionAfter:h,setSectionAfter:m,isActive:p,setIsActive:g,startDate:x,setStartDate:y,endDate:v,setEndDate:_,handleImageUpload:j,uploading:C,showPlacementOptions:A}){return e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"title",children:"Title *"}),e.jsx(be,{id:"title",placeholder:"Banner headline...",value:s,onChange:M=>t(M.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"description",children:"Description"}),e.jsx(Ls,{id:"description",placeholder:"Optional banner description...",value:n,onChange:M=>r(M.target.value),rows:2})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Banner Image *"}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(be,{type:"file",accept:"image/*",onChange:j,disabled:C,className:"flex-1"}),C&&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(re,{htmlFor:"linkUrl",children:"Link URL (optional)"}),e.jsx(be,{id:"linkUrl",placeholder:"https://...",value:i,onChange:M=>l(M.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"linkText",children:"Button Text"}),e.jsx(be,{id:"linkText",placeholder:"Learn More",value:o,onChange:M=>c(M.target.value)})]})]}),A&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Placement"}),e.jsxs(bs,{value:h,onValueChange:m,children:[e.jsx(ys,{children:e.jsx(_s,{placeholder:"Select section placement..."})}),e.jsx(vs,{children:qFt.map(M=>e.jsx(We,{value:M.value,children:M.label},M.value))})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(re,{htmlFor:"startDate",className:"flex items-center gap-2",children:[e.jsx(ha,{className:"h-4 w-4"}),"Start Date (optional)"]}),e.jsx(be,{id:"startDate",type:"datetime-local",value:x,onChange:M=>y(M.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(re,{htmlFor:"endDate",className:"flex items-center gap-2",children:[e.jsx(ha,{className:"h-4 w-4"}),"End Date (optional)"]}),e.jsx(be,{id:"endDate",type:"datetime-local",value:v,onChange:M=>_(M.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(On,{id:"isActive",checked:p,onCheckedChange:g}),e.jsx(re,{htmlFor:"isActive",children:"Active"})]})})]})}function vxt({banner:s,onEdit:t,onDelete:n,onToggleActive:r,showSection:a=!1}){var c;const i=(c=qFt.find(d=>d.value===s.section_after))==null?void 0:c.label,[l,o]=k.useState(null);return k.useEffect(()=>{(async()=>{const{count:u}=await V.from("content_engagement_logs").select("*",{count:"exact",head:!0}).eq("resource_id",s.id).eq("action_type","click_link");o(u??0)})()},[s.id]),e.jsxs("div",{className:"flex items-center gap-4 p-3 border rounded-lg bg-card hover:bg-accent/50 transition-colors",children:[e.jsx(Bp,{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(qe,{variant:"secondary",children:"Inactive"}),s.start_date&&new Date(s.start_date)>new Date&&e.jsx(qe,{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(rh,{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($,{variant:"ghost",size:"icon",children:e.jsx(Ir,{className:"h-4 w-4"})})}),e.jsx($,{variant:"ghost",size:"icon",onClick:r,children:s.is_active?e.jsx(ba,{className:"h-4 w-4"}):e.jsx(x0,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:t,children:e.jsx(ui,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:n,children:e.jsx(Un,{className:"h-4 w-4 text-destructive"})})]})]})}const mae={open:{label:"Open",icon:sa,color:"bg-yellow-500"},in_progress:{label:"In Progress",icon:Vu,color:"bg-blue-500"},resolved:{label:"Resolved",icon:nl,color:"bg-green-500"},closed:{label:"Closed",icon:ju,color:"bg-muted-foreground"}},bxt={general:"General Support",technology:"Technology Support",crm:"CRM Support",marketing:"Marketing Support"};function B1n(){var P,R;const{user:s}=ks(),t=ls(),[n,r]=k.useState(null),[a,i]=k.useState(""),[l,o]=k.useState([]),[c,d]=k.useState("all"),[u,h]=k.useState("all"),[m,p]=k.useState(!1),{data:g=[],isLoading:x}=pt({queryKey:["admin-support-tickets",c,u],queryFn:async()=>{let O=V.from("support_tickets").select("*, profiles!support_tickets_user_id_fkey(name, email)").order("created_at",{ascending:!1});c!=="all"&&(O=O.eq("status",c)),u!=="all"&&(O=O.eq("category",u));const{data:B,error:U}=await O;if(U)throw U;return B}}),{data:y=[]}=pt({queryKey:["admin-users-notifications"],queryFn:async()=>{const{data:O,error:B}=await V.from("user_roles").select("user_id").eq("role","admin");if(B)throw B;const U=O.map(oe=>oe.user_id),{data:G,error:H}=await V.from("profiles").select("id, name, email").in("id",U);if(H)throw H;const{data:Y,error:se}=await V.from("support_notification_settings").select("user_id, receive_notifications");if(se)throw se;const ee=new Map((Y==null?void 0:Y.map(oe=>[oe.user_id,oe.receive_notifications]))||[]);return G.map(oe=>({...oe,receives_notifications:ee.get(oe.id)||!1}))}}),{data:v=[]}=pt({queryKey:["admin-ticket-replies",n==null?void 0:n.id],queryFn:async()=>{if(!n)return[];const{data:O,error:B}=await V.from("support_ticket_replies").select("*, profiles(name)").eq("ticket_id",n.id).order("created_at",{ascending:!0});if(B)throw B;return O},enabled:!!n}),_=Nt({mutationFn:async({userId:O,enabled:B})=>{const{data:U}=await V.from("support_notification_settings").select("id").eq("user_id",O).maybeSingle();if(U){const{error:G}=await V.from("support_notification_settings").update({receive_notifications:B}).eq("user_id",O);if(G)throw G}else{const{error:G}=await V.from("support_notification_settings").insert({user_id:O,receive_notifications:B});if(G)throw G}},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-users-notifications"]}),ae.success("Notification settings updated")},onError:()=>{ae.error("Failed to update settings")}}),j=Nt({mutationFn:async({ticketId:O,status:B})=>{const{error:U}=await V.from("support_tickets").update({status:B}).eq("id",O);if(U)throw U},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-support-tickets"]}),n&&r({...n,status:n.status}),ae.success("Status updated")},onError:()=>{ae.error("Failed to update status")}}),C=Nt({mutationFn:async({ticketId:O,assignedTo:B})=>{const{error:U}=await V.from("support_tickets").update({assigned_to:B}).eq("id",O);if(U)throw U},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-support-tickets"]}),ae.success("Ticket assigned")},onError:()=>{ae.error("Failed to assign ticket")}}),A=Nt({mutationFn:async({content:O,attachments:B})=>{var G,H;if(!n||!s)throw new Error("Missing data");const{error:U}=await V.from("support_ticket_replies").insert({ticket_id:n.id,user_id:s.id,content:O,is_admin_reply:!0,attachments:B});if(U)throw U;try{await V.functions.invoke("support-reply-notify",{body:{ticketId:n.id,ticketSubject:n.subject,replyContent:O,userEmail:(G=n.profiles)==null?void 0:G.email,userName:(H=n.profiles)==null?void 0:H.name}})}catch(Y){console.error("Failed to send reply notification:",Y)}},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-ticket-replies",n==null?void 0:n.id]}),i(""),o([]),ae.success("Reply sent!")},onError:()=>{ae.error("Failed to send reply")}}),M=()=>{!a.trim()&&l.length===0||A.mutate({content:a,attachments:l})};k.useEffect(()=>{const O=V.channel("admin-tickets").on("postgres_changes",{event:"*",schema:"public",table:"support_tickets"},()=>{t.invalidateQueries({queryKey:["admin-support-tickets"]})}).subscribe();return()=>{V.removeChannel(O)}},[t]);const I=g.filter(O=>O.status==="open").length;return n?(mae[n.status].icon,e.jsx(Xs,{children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx($,{variant:"ghost",size:"icon",onClick:()=>r(null),children:e.jsx(Ia,{className:"h-5 w-5"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h1",{className:"text-2xl font-bold",children:n.subject}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(qe,{variant:"secondary",children:bxt[n.category]}),e.jsxs("span",{className:"text-sm text-muted-foreground",children:["from ",((P=n.profiles)==null?void 0:P.name)||"Unknown"," (",(R=n.profiles)==null?void 0:R.email,")"]})]})]})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs(we,{children:[e.jsx(Vt,{className:"pb-2",children:e.jsx(Yt,{className:"text-sm",children:"Status"})}),e.jsx(De,{children:e.jsxs(bs,{value:n.status,onValueChange:O=>{j.mutate({ticketId:n.id,status:O}),r({...n,status:O})},children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"open",children:"Open"}),e.jsx(We,{value:"in_progress",children:"In Progress"}),e.jsx(We,{value:"resolved",children:"Resolved"}),e.jsx(We,{value:"closed",children:"Closed"})]})]})})]}),e.jsxs(we,{children:[e.jsx(Vt,{className:"pb-2",children:e.jsx(Yt,{className:"text-sm",children:"Assigned To"})}),e.jsx(De,{children:e.jsxs(bs,{value:n.assigned_to||"unassigned",onValueChange:O=>{const B=O==="unassigned"?null:O;C.mutate({ticketId:n.id,assignedTo:B}),r({...n,assigned_to:B})},children:[e.jsx(ys,{children:e.jsx(_s,{placeholder:"Unassigned"})}),e.jsxs(vs,{children:[e.jsx(We,{value:"unassigned",children:"Unassigned"}),y.map(O=>e.jsx(We,{value:O.id,children:O.name},O.id))]})]})})]})]}),e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsxs(vr,{children:["Created on ",Ys(new Date(n.created_at),"MMM d, yyyy 'at' h:mm a")]})}),e.jsx(De,{children:e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:n.description})})]}),e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsx(Yt,{className:"text-lg",children:"Conversation"})}),e.jsxs(De,{children:[e.jsx(Eo,{className:"h-[300px] pr-4",children:v.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:v.map(O=>{var B,U;return e.jsxs("div",{className:`p-4 rounded-lg ${O.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:O.is_admin_reply?`${((B=O.profiles)==null?void 0:B.name)||"Admin"} (Support)`:((U=O.profiles)==null?void 0:U.name)||"User"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:Ys(new Date(O.created_at),"MMM d, h:mm a")})]}),e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:O.content}),O.attachments&&O.attachments.length>0&&e.jsx(bRt,{attachments:O.attachments})]},O.id)})})}),e.jsx(Pc,{className:"my-4"}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ls,{placeholder:"Type your reply...",value:a,onChange:O=>i(O.target.value),className:"min-h-[80px]"}),e.jsx($,{onClick:M,disabled:!a.trim()&&l.length===0||A.isPending,className:"self-end",children:e.jsx(Wr,{className:"h-4 w-4"})})]}),e.jsx(vRt,{value:l,onChange:o,disabled:A.isPending})]})]})]})]})})):e.jsx(Xs,{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",I>0&&e.jsxs(qe,{variant:"destructive",className:"ml-2",children:[I," open"]})]})]}),e.jsxs(zs,{open:m,onOpenChange:p,children:[e.jsx(yl,{asChild:!0,children:e.jsxs($,{variant:"outline",children:[e.jsx(Yc,{className:"h-4 w-4 mr-2"}),"Notification Settings"]})}),e.jsxs(Rs,{children:[e.jsxs(Vs,{children:[e.jsx($s,{children:"Email Notification Settings"}),e.jsx(Cr,{children:"Choose which admins receive email notifications for new support tickets."})]}),e.jsx("div",{className:"space-y-4 mt-4",children:y.map(O=>e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(el,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:O.name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:O.email})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[O.receives_notifications?e.jsx(Fx,{className:"h-4 w-4 text-primary"}):e.jsx(k5,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(On,{checked:O.receives_notifications,onCheckedChange:B=>_.mutate({userId:O.id,enabled:B})})]})]},O.id))})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap gap-4 items-center",children:[e.jsx(ya,{value:c,onValueChange:d,className:"w-auto",children:e.jsxs(va,{children:[e.jsx(is,{value:"all",children:"All"}),e.jsx(is,{value:"open",children:"Open"}),e.jsx(is,{value:"in_progress",children:"In Progress"}),e.jsx(is,{value:"resolved",children:"Resolved"}),e.jsx(is,{value:"closed",children:"Closed"})]})}),e.jsxs(bs,{value:u,onValueChange:h,children:[e.jsx(ys,{className:"w-[180px]",children:e.jsx(_s,{placeholder:"All Categories"})}),e.jsxs(vs,{children:[e.jsx(We,{value:"all",children:"All Categories"}),e.jsx(We,{value:"general",children:"General Support"}),e.jsx(We,{value:"technology",children:"Technology Support"}),e.jsx(We,{value:"crm",children:"CRM Support"}),e.jsx(We,{value:"marketing",children:"Marketing Support"})]})]})]}),e.jsx("div",{className:"mt-4",children:x?e.jsx("div",{className:"text-center py-12 text-muted-foreground",children:"Loading tickets..."}):g.length===0?e.jsx(we,{children:e.jsxs(De,{className:"text-center py-12",children:[e.jsx(Vu,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-medium mb-2",children:"No tickets found"}),e.jsx("p",{className:"text-muted-foreground",children:"No support tickets match the current filters."})]})}):e.jsx("div",{className:"space-y-3",children:g.map(O=>{var U,G;const B=mae[O.status].icon;return e.jsx(we,{className:"cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>r(O),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:O.subject}),e.jsxs("div",{className:"flex items-center gap-2 mt-1 flex-wrap",children:[e.jsx(qe,{variant:"outline",className:"text-xs",children:bxt[O.category]}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[(U=O.profiles)==null?void 0:U.name," • ",Ys(new Date(O.created_at),"MMM d, yyyy")]}),O.assigned_to&&e.jsxs(qe,{variant:"secondary",className:"text-xs gap-1",children:[e.jsx(el,{className:"h-3 w-3"}),((G=y.find(H=>H.id===O.assigned_to))==null?void 0:G.name)||"Assigned"]})]})]}),e.jsxs(qe,{className:mae[O.status].color,children:[e.jsx(B,{className:"h-3 w-3 mr-1"}),mae[O.status].label]})]})})},O.id)})})})]})]})})}const VFt=xv.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 $1n({content:s,onChange:t,variables:n}){const r=QWe({extensions:[eKe,dKe.configure({openOnClick:!1,HTMLAttributes:{class:"text-primary underline"}}),uKe.configure({types:["heading","paragraph"]}),hKe,VFt],content:s,onUpdate:({editor:l})=>{t(l.getHTML())}});k.useEffect(()=>{r&&s!==r.getHTML()&&r.commands.setContent(s)},[s,r]);const a=l=>{r&&r.chain().focus().insertContent(`{{${l.key}}}`).run()},i=()=>{if(!r)return;const l=r.getAttributes("link").href,o=window.prompt("URL",l);if(o!==null){if(o===""){r.chain().focus().extendMarkRange("link").unsetLink().run();return}r.chain().focus().extendMarkRange("link").setLink({href:o}).run()}};return r?e.jsxs("div",{className:"border rounded-lg overflow-hidden",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-1 p-2 border-b bg-muted/30",children:[e.jsx($,{type:"button",variant:"ghost",size:"sm",onClick:()=>r.chain().focus().toggleBold().run(),className:r.isActive("bold")?"bg-muted":"",children:e.jsx(zT,{className:"h-4 w-4"})}),e.jsx($,{type:"button",variant:"ghost",size:"sm",onClick:()=>r.chain().focus().toggleItalic().run(),className:r.isActive("italic")?"bg-muted":"",children:e.jsx(GT,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx($,{type:"button",variant:"ghost",size:"sm",onClick:()=>r.chain().focus().toggleBulletList().run(),className:r.isActive("bulletList")?"bg-muted":"",children:e.jsx(Sy,{className:"h-4 w-4"})}),e.jsx($,{type:"button",variant:"ghost",size:"sm",onClick:()=>r.chain().focus().toggleOrderedList().run(),className:r.isActive("orderedList")?"bg-muted":"",children:e.jsx(_2,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx($,{type:"button",variant:"ghost",size:"sm",onClick:()=>r.chain().focus().setTextAlign("left").run(),className:r.isActive({textAlign:"left"})?"bg-muted":"",children:e.jsx(M8,{className:"h-4 w-4"})}),e.jsx($,{type:"button",variant:"ghost",size:"sm",onClick:()=>r.chain().focus().setTextAlign("center").run(),className:r.isActive({textAlign:"center"})?"bg-muted":"",children:e.jsx(T8,{className:"h-4 w-4"})}),e.jsx($,{type:"button",variant:"ghost",size:"sm",onClick:()=>r.chain().focus().setTextAlign("right").run(),className:r.isActive({textAlign:"right"})?"bg-muted":"",children:e.jsx(P8,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx($,{type:"button",variant:"ghost",size:"sm",onClick:i,className:r.isActive("link")?"bg-muted":"",children:e.jsx(od,{className:"h-4 w-4"})}),e.jsx($,{type:"button",variant:"ghost",size:"sm",onClick:()=>r.chain().focus().toggleCodeBlock().run(),className:r.isActive("codeBlock")?"bg-muted":"",children:e.jsx($T,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx($,{type:"button",variant:"ghost",size:"sm",onClick:()=>r.chain().focus().undo().run(),disabled:!r.can().undo(),children:e.jsx(rM,{className:"h-4 w-4"})}),e.jsx($,{type:"button",variant:"ghost",size:"sm",onClick:()=>r.chain().focus().redo().run(),disabled:!r.can().redo(),children:e.jsx(JT,{className:"h-4 w-4"})}),e.jsx("div",{className:"flex-1"}),n.length>0&&e.jsxs(Au,{children:[e.jsx(Eu,{asChild:!0,children:e.jsxs($,{type:"button",variant:"outline",size:"sm",className:"gap-2",children:[e.jsx(xB,{className:"h-4 w-4"}),"Insert Variable"]})}),e.jsx(gu,{align:"end",className:"w-64",children:n.map(l=>e.jsxs(Pa,{onClick:()=>a(l),className:"flex flex-col items-start",children:[e.jsx("span",{className:"font-medium",children:l.label}),e.jsx("span",{className:"text-xs text-muted-foreground font-mono",children:`{{${l.key}}}`}),l.description&&e.jsx("span",{className:"text-xs text-muted-foreground mt-1",children:l.description})]},l.key))})]})]}),e.jsx(ZWe,{editor:r,className:"prose prose-sm max-w-none p-4 min-h-[300px] focus:outline-none [&_.ProseMirror]:outline-none [&_.ProseMirror]:min-h-[280px]"}),n.length>0&&e.jsxs("div",{className:"border-t p-3 bg-muted/20",children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:"Available variables (click to copy):"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:n.map(l=>e.jsx(qe,{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 U1n(){const s=ls(),[t,n]=k.useState(null),[r,a]=k.useState(null),[i,l]=k.useState(""),[o,c]=k.useState(""),[d,u]=k.useState(""),[h,m]=k.useState(!0),[p,g]=k.useState("visual"),{data:x,isLoading:y}=pt({queryKey:["email-templates"],queryFn:async()=>{const{data:A,error:M}=await V.from("email_templates").select("*").order("name");if(M)throw M;return A.map(I=>({...I,available_variables:I.available_variables||[]}))}}),v=Nt({mutationFn:async A=>{const{error:M}=await V.from("email_templates").update({subject:A.subject,body_html:A.body_html,description:A.description,is_active:A.is_active}).eq("id",A.id);if(M)throw M},onSuccess:()=>{s.invalidateQueries({queryKey:["email-templates"]}),ae.success("Email template updated successfully"),n(null)},onError:A=>{ae.error("Failed to update template: "+A.message)}}),_=A=>{n(A),l(A.subject),c(A.body_html),u(A.description||""),m(A.is_active),g("visual")},j=()=>{t&&v.mutate({id:t.id,subject:i,body_html:o,description:d,is_active:h})},C=(A,M)=>{let I=A;return M.forEach(P=>{const R=`{{${P.key}}}`,O=`[${P.label}]`;I=I.replace(new RegExp(R.replace(/[{}]/g,"\\$&"),"g"),O)}),I};return t?e.jsxs(Xs,{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($,{variant:"ghost",onClick:()=>n(null),children:[e.jsx(Ia,{className:"h-4 w-4 mr-2"}),"Back to Templates"]}),e.jsx("div",{className:"flex-1"}),e.jsxs($,{variant:"outline",onClick:()=>a(t),children:[e.jsx(ba,{className:"h-4 w-4 mr-2"}),"Preview"]}),e.jsxs($,{onClick:j,disabled:v.isPending,children:[e.jsx(Ml,{className:"h-4 w-4 mr-2"}),v.isPending?"Saving...":"Save Changes"]})]}),e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(Yt,{className:"flex items-center gap-2",children:[e.jsx(pn,{className:"h-5 w-5"}),t.name]}),e.jsxs(vr,{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(re,{htmlFor:"active-toggle",children:"Active"}),e.jsx(On,{id:"active-toggle",checked:h,onCheckedChange:m})]})]})}),e.jsxs(De,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"description",children:"Description"}),e.jsx(Ls,{id:"description",value:d,onChange:A=>u(A.target.value),placeholder:"Brief description of when this email is sent",rows:2})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"subject",children:"Email Subject"}),e.jsx(be,{id:"subject",value:i,onChange:A=>l(A.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(re,{children:"Email Body"}),e.jsx(ya,{value:p,onValueChange:A=>g(A),children:e.jsxs(va,{className:"h-8",children:[e.jsxs(is,{value:"visual",className:"text-xs px-3 h-6",children:[e.jsx(j2,{className:"h-3 w-3 mr-1"}),"Visual"]}),e.jsxs(is,{value:"html",className:"text-xs px-3 h-6",children:[e.jsx($T,{className:"h-3 w-3 mr-1"}),"HTML"]})]})})]}),p==="visual"?e.jsx($1n,{content:o,onChange:c,variables:t.available_variables}):e.jsx(Ls,{value:o,onChange:A=>c(A.target.value),className:"font-mono text-sm min-h-[400px]",placeholder:"HTML email body"})]})]})]})]}),e.jsx(zs,{open:!!r,onOpenChange:()=>a(null),children:e.jsxs(Rs,{className:"max-w-3xl max-h-[90vh] overflow-auto",children:[e.jsxs(Vs,{children:[e.jsx($s,{children:"Email Preview"}),e.jsxs(Cr,{children:["Subject: ",i.replace(/\{\{(\w+)\}\}/g,"[$1]")]})]}),e.jsx("div",{className:"border rounded-lg p-4 bg-white",children:e.jsx("div",{dangerouslySetInnerHTML:{__html:C(o,t.available_variables)}})})]})})]}):e.jsx(Xs,{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"})]}),y?e.jsx("div",{className:"grid gap-4",children:[...Array(4)].map((A,M)=>e.jsx(we,{children:e.jsxs(Vt,{children:[e.jsx(fn,{className:"h-5 w-48"}),e.jsx(fn,{className:"h-4 w-96"})]})},M))}):e.jsx("div",{className:"grid gap-4",children:x==null?void 0:x.map(A=>e.jsxs(we,{className:"hover:shadow-md transition-shadow",children:[e.jsx(Vt,{children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs(Yt,{className:"flex items-center gap-2 text-lg",children:[e.jsx(pn,{className:"h-5 w-5 text-muted-foreground"}),A.name,!A.is_active&&e.jsx(qe,{variant:"secondary",children:"Inactive"})]}),e.jsx(vr,{children:A.description})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs($,{variant:"outline",size:"sm",onClick:()=>a(A),children:[e.jsx(ba,{className:"h-4 w-4 mr-2"}),"Preview"]}),e.jsxs($,{size:"sm",onClick:()=>_(A),children:[e.jsx(Cp,{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:A.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:A.available_variables.map(M=>e.jsx(qe,{variant:"outline",className:"font-mono text-xs",children:`{{${M.key}}}`},M.key))})]})]})})]},A.id))}),e.jsx(zs,{open:!!r&&!t,onOpenChange:()=>a(null),children:e.jsxs(Rs,{className:"max-w-3xl max-h-[90vh] overflow-auto",children:[e.jsxs(Vs,{children:[e.jsxs($s,{children:["Email Preview: ",r==null?void 0:r.name]}),e.jsxs(Cr,{children:["Subject: ",r==null?void 0:r.subject.replace(/\{\{(\w+)\}\}/g,"[$1]")]})]}),r&&e.jsx("div",{className:"border rounded-lg p-4 bg-white",children:e.jsx("div",{dangerouslySetInnerHTML:{__html:C(r.body_html,r.available_variables)}})})]})})]})})}function q1n(){const s=ls(),[t,n]=k.useState("templates"),[r,a]=k.useState(null),[i,l]=k.useState(null),[o,c]=k.useState(!1),[d,u]=k.useState(!1),[h,m]=k.useState({title:"",subject:"",body:"",description:"",tone:"",category_id:"",is_active:!0}),[p,g]=k.useState({name:"",description:"",icon:"📧"}),{data:x=[]}=pt({queryKey:["agent-email-template-categories"],queryFn:async()=>{const{data:O,error:B}=await V.from("email_template_categories").select("*").order("sort_order");if(B)throw B;return O}}),{data:y=[],isLoading:v}=pt({queryKey:["agent-email-templates-admin"],queryFn:async()=>{const{data:O,error:B}=await V.from("agent_email_templates").select("*, category:email_template_categories(*)").order("sort_order");if(B)throw B;return O}}),_=Nt({mutationFn:async O=>{const B={title:O.title,subject:O.subject,body:O.body,description:O.description||null,tone:O.tone||null,category_id:O.category_id||null,is_active:O.is_active};if(O.id){const{error:U}=await V.from("agent_email_templates").update(B).eq("id",O.id);if(U)throw U}else{const{error:U}=await V.from("agent_email_templates").insert(B);if(U)throw U}},onSuccess:()=>{s.invalidateQueries({queryKey:["agent-email-templates-admin"]}),c(!1),ae.success(r?"Template updated":"Template created")},onError:()=>ae.error("Failed to save template")}),j=Nt({mutationFn:async O=>{const{error:B}=await V.from("agent_email_templates").delete().eq("id",O);if(B)throw B},onSuccess:()=>{s.invalidateQueries({queryKey:["agent-email-templates-admin"]}),ae.success("Template deleted")}}),C=Nt({mutationFn:async O=>{const B={name:O.name,description:O.description||null,icon:O.icon};if(O.id){const{error:U}=await V.from("email_template_categories").update(B).eq("id",O.id);if(U)throw U}else{const U=x.length>0?Math.max(...x.map(H=>H.sort_order))+1:0,{error:G}=await V.from("email_template_categories").insert({...B,sort_order:U});if(G)throw G}},onSuccess:()=>{s.invalidateQueries({queryKey:["agent-email-template-categories"]}),u(!1),ae.success(i?"Category updated":"Category created")},onError:()=>ae.error("Failed to save category")}),A=Nt({mutationFn:async O=>{const{error:B}=await V.from("email_template_categories").delete().eq("id",O);if(B)throw B},onSuccess:()=>{s.invalidateQueries({queryKey:["agent-email-template-categories"]}),ae.success("Category deleted")}}),M=()=>{a(null),m({title:"",subject:"",body:"",description:"",tone:"",category_id:"",is_active:!0}),c(!0)},I=O=>{a(O),m({title:O.title,subject:O.subject,body:O.body,description:O.description||"",tone:O.tone||"",category_id:O.category_id||"",is_active:O.is_active}),c(!0)},P=()=>{l(null),g({name:"",description:"",icon:"📧"}),u(!0)},R=O=>{l(O),g({name:O.name,description:O.description||"",icon:O.icon}),u(!0)};return e.jsx(Xs,{children:e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsx(nm,{title:"Agent Email Templates",description:"Manage email templates that agents use when composing emails from Mission Control."}),e.jsxs(ya,{value:t,onValueChange:n,children:[e.jsxs(va,{children:[e.jsxs(is,{value:"templates",className:"gap-2",children:[e.jsx(pn,{className:"h-4 w-4"})," Templates"]}),e.jsxs(is,{value:"categories",className:"gap-2",children:[e.jsx(d1,{className:"h-4 w-4"})," Categories"]})]}),e.jsxs(cs,{value:"templates",className:"space-y-4",children:[e.jsx("div",{className:"flex justify-end",children:e.jsxs($,{onClick:M,className:"gap-2",children:[e.jsx(nn,{className:"h-4 w-4"})," Add Template"]})}),e.jsx(we,{children:e.jsx(De,{className:"p-0",children:e.jsxs(Qa,{children:[e.jsx(Ja,{children:e.jsxs(vn,{children:[e.jsx(Dt,{children:"Template"}),e.jsx(Dt,{className:"hidden md:table-cell",children:"Category"}),e.jsx(Dt,{className:"hidden md:table-cell",children:"Tone"}),e.jsx(Dt,{children:"Status"}),e.jsx(Dt,{className:"text-right",children:"Actions"})]})}),e.jsx(ei,{children:v?e.jsx(vn,{children:e.jsx(_t,{colSpan:5,className:"text-center py-8",children:e.jsx(Jt,{className:"h-6 w-6 animate-spin mx-auto"})})}):y.length===0?e.jsx(vn,{children:e.jsx(_t,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No templates yet. Create your first one!"})}):y.map(O=>e.jsxs(vn,{children:[e.jsx(_t,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:O.title}),e.jsx("p",{className:"text-xs text-muted-foreground truncate max-w-[300px]",children:O.subject})]})}),e.jsx(_t,{className:"hidden md:table-cell",children:O.category?e.jsxs(qe,{variant:"outline",className:"gap-1",children:[O.category.icon," ",O.category.name]}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"—"})}),e.jsx(_t,{className:"hidden md:table-cell",children:O.tone?e.jsx(qe,{variant:"secondary",children:O.tone}):"—"}),e.jsx(_t,{children:e.jsx(qe,{variant:O.is_active?"default":"secondary",children:O.is_active?"Active":"Inactive"})}),e.jsx(_t,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-1",children:[e.jsx($,{variant:"ghost",size:"icon",onClick:()=>I(O),children:e.jsx(ui,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",onClick:async()=>{await io("Delete this template?")&&j.mutate(O.id)},children:e.jsx(Un,{className:"h-4 w-4"})})]})})]},O.id))})]})})})]}),e.jsxs(cs,{value:"categories",className:"space-y-4",children:[e.jsx("div",{className:"flex justify-end",children:e.jsxs($,{onClick:P,className:"gap-2",children:[e.jsx(nn,{className:"h-4 w-4"})," Add Category"]})}),e.jsx("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-3",children:x.map(O=>e.jsxs(we,{children:[e.jsx(Vt,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(Yt,{className:"text-base flex items-center gap-2",children:[e.jsx("span",{className:"text-lg",children:O.icon})," ",O.name]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>R(O),children:e.jsx(ui,{className:"h-3.5 w-3.5"})}),e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive",onClick:async()=>{await io("Delete this category?")&&A.mutate(O.id)},children:e.jsx(Un,{className:"h-3.5 w-3.5"})})]})]})}),e.jsxs(De,{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:O.description||"No description"}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-2",children:[y.filter(B=>B.category_id===O.id).length," templates"]})]})]},O.id))})]})]}),e.jsx(zs,{open:o,onOpenChange:c,children:e.jsxs(Rs,{className:"sm:max-w-[700px] max-h-[90vh] overflow-y-auto",children:[e.jsx(Vs,{children:e.jsx($s,{children:r?"Edit Template":"New Template"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Title"}),e.jsx(be,{value:h.title,onChange:O=>m(B=>({...B,title:O.target.value})),placeholder:"e.g. Quick Check-in"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Category"}),e.jsxs(bs,{value:h.category_id,onValueChange:O=>m(B=>({...B,category_id:O})),children:[e.jsx(ys,{children:e.jsx(_s,{placeholder:"Select category"})}),e.jsx(vs,{children:x.map(O=>e.jsxs(We,{value:O.id,children:[O.icon," ",O.name]},O.id))})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Subject Line"}),e.jsx(be,{value:h.subject,onChange:O=>m(B=>({...B,subject:O.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(re,{children:"Email Body"}),e.jsx(Ls,{value:h.body,onChange:O=>m(B=>({...B,body:O.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(re,{children:"Description (internal)"}),e.jsx(be,{value:h.description,onChange:O=>m(B=>({...B,description:O.target.value})),placeholder:"Short description for admin reference"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Tone"}),e.jsx(be,{value:h.tone,onChange:O=>m(B=>({...B,tone:O.target.value})),placeholder:"e.g. Warm & Casual"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(On,{checked:h.is_active,onCheckedChange:O=>m(B=>({...B,is_active:O}))}),e.jsx(re,{children:"Active"})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsxs($,{onClick:()=>_.mutate({...h,id:r==null?void 0:r.id}),disabled:_.isPending||!h.title||!h.subject||!h.body,children:[_.isPending&&e.jsx(Jt,{className:"h-4 w-4 mr-2 animate-spin"}),r?"Save Changes":"Create Template"]})]})]})}),e.jsx(zs,{open:d,onOpenChange:u,children:e.jsxs(Rs,{className:"sm:max-w-[450px]",children:[e.jsx(Vs,{children:e.jsx($s,{children:i?"Edit Category":"New Category"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-[60px_1fr] gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Icon"}),e.jsx(be,{value:p.icon,onChange:O=>g(B=>({...B,icon:O.target.value})),className:"text-center text-lg"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Name"}),e.jsx(be,{value:p.name,onChange:O=>g(B=>({...B,name:O.target.value})),placeholder:"e.g. Check-in & Stay in Touch"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Description"}),e.jsx(be,{value:p.description,onChange:O=>g(B=>({...B,description:O.target.value})),placeholder:"Brief description of this category"})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>u(!1),children:"Cancel"}),e.jsxs($,{onClick:()=>C.mutate({...p,id:i==null?void 0:i.id}),disabled:C.isPending||!p.name,children:[C.isPending&&e.jsx(Jt,{className:"h-4 w-4 mr-2 animate-spin"}),i?"Save Changes":"Create Category"]})]})]})})]})})}const V1n=({brokerageId:s})=>{var Ei,fo,co;const{toast:t}=Fi(),n=Jn(),[r,a]=k.useState([]),[i,l]=k.useState(!0),[o,c]=k.useState(""),[d,u]=k.useState("all"),[h,m]=k.useState(new Set),[p,g]=k.useState(!1),[x,y]=k.useState({}),[v,_]=k.useState(!1),[j,C]=k.useState(!1),[A,M]=k.useState({email:"",name:"",password:"",phone:""}),[I,P]=k.useState(null),[R,O]=k.useState([]),[B,U]=k.useState("none"),[G,H]=k.useState(!1),[Y,se]=k.useState(null),[ee,oe]=k.useState(!1),[me,Q]=k.useState(!1),[te,le]=k.useState(!1),[fe,_e]=k.useState(""),[ve,he]=k.useState(!1),[Se,Te]=k.useState([]),[Ie,Ue]=k.useState(!1),[Be,je]=k.useState(!1),[Ye,Ee]=k.useState(null),[Re,ke]=k.useState({name:"",phone:"",email:""}),[Fe,Oe]=k.useState(!1),[Ge,yt]=k.useState(!1),[tt,ut]=k.useState(null),[nt,et]=k.useState("asc"),[at,wt]=k.useState(!1),[rt,Ft]=k.useState(null),[Ut,Is]=k.useState(!1),[xs,st]=k.useState(null),[dt,jt]=k.useState(""),[gt,rs]=k.useState(!1),[Ns,us]=k.useState(null);k.useEffect(()=>{Fn(),Ts(),Bs()},[s]);const Bs=async()=>{try{const{data:Tn}=await V.from("partnership_programs").select("id, name, enabled").eq("brokerage_id",s).maybeSingle();if(!Tn||!Tn.enabled){P(null),O([]);return}const{data:Mr}=await V.from("partnership_packages").select("id, name, description, sort_order").eq("program_id",Tn.id).order("sort_order",{ascending:!0});P({id:Tn.id,name:Tn.name}),O(Mr||[]),Mr&&Mr.length>0&&U(Mr[0].id)}catch(Tn){console.error("Error loading partnership packages:",Tn)}},Ts=async()=>{try{const{data:Tn,error:Mr}=await V.from("brokerage_manager_assignments").select("user_id").eq("brokerage_id",s);if(Mr)throw Mr;Te((Tn==null?void 0:Tn.map(Aa=>Aa.user_id))||[])}catch(Tn){console.error("Error loading brokerage managers:",Tn)}},Fn=async()=>{try{l(!0);const{data:Tn,error:Mr}=await V.functions.invoke("get-brokerage-agents",{body:{brokerageId:s}});if(Mr)throw Mr;const Aa=Tn.agents||[];if(a(Aa),Aa.length>0){const Lo=Aa.map(vl=>vl.id),{data:Ac}=await V.from("agent_assistant_assignments").select("agent_id, assistant_id").in("agent_id",Lo);if(Ac&&Ac.length>0){const vl=Ac.map(_a=>_a.assistant_id),{data:Ol}=await V.from("profiles").select("id, name, email").in("id",vl),To={};for(const _a of Ac){const $o=Ol==null?void 0:Ol.find(jh=>jh.id===_a.assistant_id);$o&&(To[_a.agent_id]={name:$o.name||"",email:$o.email||""})}y(To)}else y({})}}catch(Tn){console.error("Error loading agents:",Tn),t({title:"Error",description:"Failed to load agents",variant:"destructive"})}finally{l(!1)}},An=async()=>{var Tn;if(!A.email||!A.name||!A.password){t({title:"Error",description:"Please fill in all fields",variant:"destructive"});return}C(!0);try{const{data:{session:Mr}}=await V.auth.getSession(),Aa=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/create-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Mr==null?void 0:Mr.access_token}`},body:JSON.stringify({...A,brokerageId:s,partnershipPackageId:I&&B!=="none"?B:void 0})}),Lo=await Aa.json();if(!Aa.ok)throw new Error(Lo.error||"Failed to create agent");t({title:"Success",description:`Agent ${A.email} created successfully`}),M({email:"",name:"",password:"",phone:""}),U(((Tn=R[0])==null?void 0:Tn.id)||"none"),_(!1),Fn()}catch(Mr){console.error("Error creating agent:",Mr),t({title:"Error",description:Mr.message||"Failed to create agent",variant:"destructive"})}finally{C(!1)}},js=async Tn=>{try{const{data:{session:Mr}}=await V.auth.getSession(),Aa=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/resend-welcome-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Mr==null?void 0:Mr.access_token}`},body:JSON.stringify({userId:Tn})}),Lo=await Aa.json();if(!Aa.ok)throw new Error(Lo.error||"Failed to resend welcome email");t({title:"Success",description:"Welcome email sent successfully"})}catch(Mr){console.error("Error resending welcome email:",Mr),t({title:"Error",description:Mr.message||"Failed to resend welcome email",variant:"destructive"})}},In=async(Tn,Mr)=>{try{const{error:Aa}=await V.functions.invoke("send-password-reset",{body:{email:Tn,redirectTo:window.location.origin}});if(Aa)throw Aa;t({title:"Password Reset Sent",description:`Password reset email sent to ${Mr}`})}catch(Aa){console.error("Error sending password reset:",Aa),t({title:"Error",description:Aa.message||"Failed to send password reset email",variant:"destructive"})}},un=Tn=>{se(Tn),H(!0)},jr=Tn=>{Ee(Tn),ke({name:Tn.name,phone:Tn.phone||"",email:Tn.email}),je(!0)},Ln=async()=>{if(!Ye)return;if(!Re.name.trim()){t({title:"Error",description:"Name is required",variant:"destructive"});return}const Tn=Re.email.trim().toLowerCase()!==Ye.email.toLowerCase();Oe(!0);try{if(Tn){if(!Re.email.trim())throw new Error("Email is required");yt(!0);const{data:{session:Aa}}=await V.auth.getSession(),Lo=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/update-agent-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Aa==null?void 0:Aa.access_token}`},body:JSON.stringify({agentId:Ye.id,newEmail:Re.email.trim(),brokerageId:s})}),Ac=await Lo.json();if(yt(!1),!Lo.ok)throw new Error(Ac.error||"Failed to update email")}const{error:Mr}=await V.from("profiles").update({name:Re.name.trim(),phone:Re.phone.trim()||null}).eq("id",Ye.id);if(Mr)throw Mr;t({title:"Success",description:"Agent profile updated successfully"}),je(!1),Ee(null),Fn()}catch(Mr){console.error("Error updating agent:",Mr),t({title:"Error",description:Mr.message||"Failed to update agent",variant:"destructive"})}finally{Oe(!1),yt(!1)}},Sr=async()=>{if(!fe){t({title:"Error",description:"Please select an agent to promote",variant:"destructive"});return}he(!0);try{const{data:{session:Tn}}=await V.auth.getSession(),Mr=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/manage-user-roles",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Tn==null?void 0:Tn.access_token}`},body:JSON.stringify({userId:fe,role:"brokerage_manager",action:"add",brokerageId:s})}),Aa=await Mr.json();if(!Mr.ok)throw new Error(Aa.error||"Failed to add brokerage manager");t({title:"Success",description:"Brokerage manager added successfully"}),le(!1),_e(""),Ts()}catch(Tn){console.error("Error adding brokerage manager:",Tn),t({title:"Error",description:Tn.message||"Failed to add brokerage manager",variant:"destructive"})}finally{he(!1)}},Qn=async Tn=>{try{const{data:{session:Mr}}=await V.auth.getSession(),Aa=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/manage-user-roles",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Mr==null?void 0:Mr.access_token}`},body:JSON.stringify({userId:Tn,role:"brokerage_manager",action:"remove",brokerageId:s})}),Lo=await Aa.json();if(!Aa.ok)throw new Error(Lo.error||"Failed to remove brokerage manager");t({title:"Success",description:"Brokerage manager role removed"}),Ts()}catch(Mr){console.error("Error removing brokerage manager:",Mr),t({title:"Error",description:Mr.message||"Failed to remove brokerage manager",variant:"destructive"})}},En=Tn=>Se.includes(Tn),pr=Tn=>{st(Tn),jt(""),Is(!0)},xn=async()=>{if(!(!xs||!dt)){if(dt.length<6){t({title:"Error",description:"Password must be at least 6 characters",variant:"destructive"});return}rs(!0);try{const{data:{session:Tn}}=await V.auth.getSession(),Mr=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/update-agent-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Tn==null?void 0:Tn.access_token}`},body:JSON.stringify({agentId:xs.id,brokerageId:s,action:"set_password",newPassword:dt})}),Aa=await Mr.json();if(!Mr.ok)throw new Error(Aa.error||"Failed to set password");t({title:"Success",description:`Password set for ${xs.name}`}),Is(!1),st(null),jt("")}catch(Tn){console.error("Error setting password:",Tn),t({title:"Error",description:Tn.message||"Failed to set password",variant:"destructive"})}finally{rs(!1)}}},Ar=async Tn=>{us(Tn.id);try{const{data:{session:Mr}}=await V.auth.getSession(),Aa=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/update-agent-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Mr==null?void 0:Mr.access_token}`},body:JSON.stringify({agentId:Tn.id,brokerageId:s,action:"claim_account"})}),Lo=await Aa.json();if(!Aa.ok)throw new Error(Lo.error||"Failed to claim account");t({title:"Success",description:`Account claimed for ${Tn.name}`}),Fn()}catch(Mr){console.error("Error claiming account:",Mr),t({title:"Error",description:Mr.message||"Failed to claim account",variant:"destructive"})}finally{us(null)}},Zr=async()=>{if(Y){oe(!0);try{const{data:{session:Tn}}=await V.auth.getSession(),Mr=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/remove-agent",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Tn==null?void 0:Tn.access_token}`},body:JSON.stringify({userId:Y.id,brokerageId:s})}),Aa=await Mr.json();if(!Mr.ok)throw new Error(Aa.error||"Failed to remove agent");t({title:"Success",description:`${Y.name} has been removed from your brokerage`}),H(!1),se(null),Fn()}catch(Tn){console.error("Error removing agent:",Tn),t({title:"Error",description:Tn.message||"Failed to remove agent",variant:"destructive"})}finally{oe(!1)}}},dn=Tn=>{const Mr=Tn.trim().split(" ");return Mr.length>1?Mr[Mr.length-1].toLowerCase():Tn.toLowerCase()},Kt=Tn=>{tt===Tn?et(nt==="asc"?"desc":"asc"):(ut(Tn),et("asc"))},Er=Tn=>tt!==Tn?e.jsx(Ix,{className:"ml-1 h-4 w-4"}):nt==="asc"?e.jsx(ap,{className:"ml-1 h-4 w-4"}):e.jsx(nx,{className:"ml-1 h-4 w-4"}),ti=r.filter(Tn=>{if(d==="active"&&!Tn.claimed||d==="pending"&&Tn.claimed)return!1;if(!o)return!0;const Mr=o.toLowerCase();return Tn.name.toLowerCase().includes(Mr)||Tn.email.toLowerCase().includes(Mr)}),Ba=[...ti].sort((Tn,Mr)=>{if(!tt)return 0;let Aa=0;return tt==="name"?Aa=dn(Tn.name).localeCompare(dn(Mr.name)):tt==="status"&&(Aa=Tn.claimed===Mr.claimed?0:Tn.claimed?-1:1),nt==="asc"?Aa:-Aa});ti.filter(Tn=>Tn.claimed&&!En(Tn.id));const lo=Tn=>{m(Mr=>{const Aa=new Set(Mr);return Aa.has(Tn)?Aa.delete(Tn):Aa.add(Tn),Aa})},Yn=()=>{h.size===Ba.length?m(new Set):m(new Set(Ba.map(Tn=>Tn.id)))},Hr=()=>{m(new Set)},Ur=async()=>{const Tn=Array.from(h);if(Tn.length===0)return;g(!0);let Mr=0,Aa=0;try{const{data:{session:Lo}}=await V.auth.getSession();for(const Ac of Tn)try{(await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/resend-welcome-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Lo==null?void 0:Lo.access_token}`},body:JSON.stringify({userId:Ac})})).ok?Mr++:Aa++}catch{Aa++}Mr>0?t({title:"Success",description:`Welcome emails sent to ${Mr} agent${Mr>1?"s":""}${Aa>0?` (${Aa} failed)`:""}`}):t({title:"Error",description:"Failed to send welcome emails",variant:"destructive"}),Hr()}catch(Lo){console.error("Error bulk sending welcome emails:",Lo),t({title:"Error",description:Lo.message||"Failed to send welcome emails",variant:"destructive"})}finally{g(!1)}};return i?e.jsx(we,{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(we,{children:[e.jsx(Vt,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Yt,{children:"Agents"}),e.jsx(vr,{children:"Manage your brokerage's agents"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs($,{variant:"outline",onClick:()=>le(!0),children:[e.jsx(Ng,{className:"mr-2 h-4 w-4"}),"Add Brokerage Manager"]}),e.jsxs($,{variant:"outline",onClick:()=>Q(!0),children:[e.jsx(rk,{className:"mr-2 h-4 w-4"}),"Import CSV"]}),e.jsxs($,{onClick:()=>_(!0),children:[e.jsx(Pl,{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(Yr,{className:"absolute left-3 top-3 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search agents...",value:o,onChange:Tn=>c(Tn.target.value),className:"pl-9"})]}),e.jsxs(bs,{value:d,onValueChange:Tn=>u(Tn),children:[e.jsx(ys,{className:"w-[160px]",children:e.jsx(_s,{placeholder:"Filter by status"})}),e.jsxs(vs,{children:[e.jsx(We,{value:"all",children:"All Agents"}),e.jsx(We,{value:"active",children:"Active"}),e.jsx(We,{value:"pending",children:"Pending"})]})]})]}),h.size>0&&e.jsxs("div",{className:"mb-4 flex items-center gap-3 rounded-lg border bg-muted/50 p-3",children:[e.jsxs("span",{className:"text-sm font-medium",children:[h.size," agent",h.size>1?"s":""," selected"]}),e.jsx("div",{className:"flex-1"}),e.jsxs($,{size:"sm",variant:"outline",onClick:()=>{const Mr=r.filter(Aa=>h.has(Aa.id)&&Aa.email).map(Aa=>({email:Aa.email,name:Aa.name}));sessionStorage.setItem("campaign_direct_recipients",JSON.stringify(Mr)),n("/admin/email-campaigns/new?directMode=1",{state:{directRecipients:Mr}})},disabled:p,children:[e.jsx(xm,{className:"mr-2 h-4 w-4"}),"Email Agents (",h.size,")"]}),e.jsxs($,{size:"sm",variant:"outline",onClick:Ur,disabled:p,children:[e.jsx(pn,{className:"mr-2 h-4 w-4"}),p?"Sending...":"Resend Welcome Email"]}),e.jsx($,{size:"sm",variant:"ghost",onClick:Hr,children:"Clear"})]}),e.jsx("div",{className:"rounded-md border",children:e.jsxs(Qa,{children:[e.jsx(Ja,{children:e.jsxs(vn,{children:[e.jsx(Dt,{className:"w-[40px]",children:e.jsx(Li,{checked:Ba.length>0&&h.size===Ba.length,onCheckedChange:Yn,"aria-label":"Select all"})}),e.jsx(Dt,{children:e.jsxs($,{variant:"ghost",size:"sm",className:"-ml-3 h-8 hover:bg-transparent",onClick:()=>Kt("name"),children:["Name (Last)",Er("name")]})}),e.jsx(Dt,{children:"Email"}),e.jsx(Dt,{children:e.jsxs($,{variant:"ghost",size:"sm",className:"-ml-3 h-8 hover:bg-transparent",onClick:()=>Kt("status"),children:["Status",Er("status")]})}),e.jsx(Dt,{children:"Actions"})]})}),e.jsx(ei,{children:Ba.length===0?e.jsx(vn,{children:e.jsx(_t,{colSpan:5,className:"text-center text-muted-foreground",children:"No agents found"})}):Ba.map(Tn=>e.jsxs(vn,{children:[e.jsx(_t,{children:e.jsx(Li,{checked:h.has(Tn.id),onCheckedChange:()=>lo(Tn.id),"aria-label":`Select ${Tn.name}`})}),e.jsx(_t,{className:"font-medium",children:Tn.name}),e.jsx(_t,{children:Tn.email}),e.jsx(_t,{children:e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[Tn.claimed?e.jsx(qe,{variant:"default",children:"Active"}):e.jsx(qe,{variant:"secondary",children:"Pending"}),En(Tn.id)&&e.jsxs(qe,{variant:"outline",className:"border-primary text-primary",children:[e.jsx(b0,{className:"mr-1 h-3 w-3"}),"Manager"]}),x[Tn.id]&&e.jsxs(qe,{variant:"outline",className:"text-xs",children:[e.jsx(Xn,{className:"mr-1 h-3 w-3"}),"Asst: ",x[Tn.id].name||x[Tn.id].email]})]})}),e.jsx(_t,{children:e.jsxs("div",{className:"flex items-center gap-1 flex-wrap",children:[e.jsx($,{size:"sm",variant:"ghost",onClick:()=>{Ft(Tn),wt(!0)},title:"Send celebration",className:"text-yellow-500 hover:text-yellow-600 hover:bg-yellow-50",children:e.jsx(jg,{className:"h-4 w-4"})}),e.jsx($,{size:"sm",variant:"ghost",onClick:()=>jr(Tn),title:"Edit agent",children:e.jsx(ui,{className:"h-4 w-4"})}),!Tn.claimed&&e.jsxs(e.Fragment,{children:[e.jsx($,{size:"sm",variant:"ghost",onClick:()=>js(Tn.id),title:"Resend welcome email",children:e.jsx(pn,{className:"h-4 w-4"})}),e.jsx($,{size:"sm",variant:"ghost",onClick:()=>Ar(Tn),title:"Claim account for agent",disabled:Ns===Tn.id,className:"text-green-600 hover:text-green-700 hover:bg-green-50",children:e.jsx(ck,{className:"h-4 w-4"})})]}),e.jsx($,{size:"sm",variant:"ghost",onClick:()=>pr(Tn),title:"Set password",className:"text-blue-600 hover:text-blue-700 hover:bg-blue-50",children:e.jsx(fu,{className:"h-4 w-4"})}),e.jsx($,{size:"sm",variant:"ghost",onClick:()=>In(Tn.email,Tn.name),title:"Send password reset email",children:e.jsx(x3,{className:"h-4 w-4"})}),En(Tn.id)&&e.jsx($,{size:"sm",variant:"ghost",onClick:()=>Qn(Tn.id),title:"Remove manager role",className:"text-orange-500 hover:text-orange-600",children:e.jsx(Ng,{className:"h-4 w-4"})}),e.jsx($,{size:"sm",variant:"ghost",onClick:()=>un(Tn),className:"text-destructive hover:text-destructive",title:"Remove agent",children:e.jsx(Un,{className:"h-4 w-4"})})]})})]},Tn.id))})]})})]})]}),e.jsx(zs,{open:v,onOpenChange:_,children:e.jsxs(Rs,{children:[e.jsxs(Vs,{children:[e.jsx($s,{children:"Add New Agent"}),e.jsx(Cr,{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(re,{htmlFor:"name",children:"Name"}),e.jsx(be,{id:"name",value:A.name,onChange:Tn=>M({...A,name:Tn.target.value}),placeholder:"John Doe"})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"email",children:"Email"}),e.jsx(be,{id:"email",type:"email",value:A.email,onChange:Tn=>M({...A,email:Tn.target.value}),placeholder:"john@example.com"})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"phone",children:"Phone (optional)"}),e.jsx(be,{id:"phone",type:"tel",value:A.phone,onChange:Tn=>M({...A,phone:Tn.target.value}),placeholder:"555-123-4567"})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"password",children:"Temporary Password"}),e.jsx(be,{id:"password",type:"password",value:A.password,onChange:Tn=>M({...A,password:Tn.target.value}),placeholder:"Temporary password"})]}),I&&R.length>0&&e.jsxs("div",{children:[e.jsxs(re,{htmlFor:"package",children:[I.name," Package"]}),e.jsxs(bs,{value:B,onValueChange:U,children:[e.jsx(ys,{id:"package",children:e.jsx(_s,{placeholder:"Choose a package"})}),e.jsxs(vs,{children:[R.map(Tn=>e.jsx(We,{value:Tn.id,children:Tn.name},Tn.id)),e.jsx(We,{value:"none",children:"No package (full access)"})]})]}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:B==="none"?"Agent gets unrestricted LevelUp access.":((Ei=R.find(Tn=>Tn.id===B))==null?void 0:Ei.description)||"Their welcome email will list what is included in this package."})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>_(!1),children:"Cancel"}),e.jsx($,{onClick:An,disabled:j,children:j?"Creating...":"Create Agent"})]})]})}),e.jsx(zs,{open:G,onOpenChange:H,children:e.jsxs(Rs,{children:[e.jsxs(Vs,{children:[e.jsx($s,{children:"Remove Agent"}),e.jsxs(Cr,{children:["Are you sure you want to remove ",e.jsx("strong",{children:Y==null?void 0:Y.name})," from your brokerage? This will revoke their access to the dashboard."]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>H(!1),children:"Cancel"}),e.jsx($,{variant:"destructive",onClick:Zr,disabled:ee,children:ee?"Removing...":"Remove Agent"})]})]})}),e.jsx(_Rt,{open:me,onOpenChange:Q,fixedBrokerageId:s,onSuccess:Fn}),e.jsx(zs,{open:te,onOpenChange:le,children:e.jsxs(Rs,{children:[e.jsxs(Vs,{children:[e.jsx($s,{children:"Add Brokerage Manager"}),e.jsx(Cr,{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(re,{children:"Select Agent"}),e.jsxs(Xc,{open:Ie,onOpenChange:Ue,children:[e.jsx(Qc,{asChild:!0,children:e.jsxs($,{variant:"outline",role:"combobox","aria-expanded":Ie,className:"w-full justify-between",children:[fe?((fo=r.find(Tn=>Tn.id===fe))==null?void 0:fo.name)+" ("+((co=r.find(Tn=>Tn.id===fe))==null?void 0:co.email)+")":"Select an agent to promote...",e.jsx(v_,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(Bc,{className:"w-full p-0",align:"start",children:e.jsxs(M_,{children:[e.jsx(P_,{placeholder:"Search by name or email..."}),e.jsxs(I_,{className:"max-h-[200px]",children:[e.jsx(L_,{children:"No eligible agents found."}),e.jsx(Nb,{children:r.filter(Tn=>!En(Tn.id)).map(Tn=>e.jsxs(rv,{value:`${Tn.name} ${Tn.email}`,onSelect:()=>{_e(Tn.id),Ue(!1)},children:[e.jsx(ma,{className:`mr-2 h-4 w-4 ${fe===Tn.id?"opacity-100":"opacity-0"}`}),Tn.name," (",Tn.email,")"]},Tn.id))})]})]})})]}),r.filter(Tn=>!En(Tn.id)).length===0&&e.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:"All agents are already brokerage managers."})]})}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>le(!1),children:"Cancel"}),e.jsx($,{onClick:Sr,disabled:ve||!fe,children:ve?"Adding...":"Add as Manager"})]})]})}),e.jsx(zs,{open:Be,onOpenChange:je,children:e.jsxs(Rs,{children:[e.jsxs(Vs,{children:[e.jsx($s,{children:"Edit Agent"}),e.jsxs(Cr,{children:["Update profile information for ",Ye==null?void 0:Ye.name]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(re,{htmlFor:"edit-name",children:"Name"}),e.jsx(be,{id:"edit-name",value:Re.name,onChange:Tn=>ke({...Re,name:Tn.target.value}),placeholder:"Agent name"})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"edit-email",children:"Email"}),e.jsx(be,{id:"edit-email",type:"email",value:Re.email,onChange:Tn=>ke({...Re,email:Tn.target.value}),placeholder:"agent@example.com"}),Re.email.trim().toLowerCase()!==(Ye==null?void 0:Ye.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(re,{htmlFor:"edit-phone",children:"Phone"}),e.jsx(be,{id:"edit-phone",type:"tel",value:Re.phone,onChange:Tn=>ke({...Re,phone:Tn.target.value}),placeholder:"555-123-4567"})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>je(!1),children:"Cancel"}),e.jsx($,{onClick:Ln,disabled:Fe||Ge,children:Ge?"Updating email...":Fe?"Saving...":"Save Changes"})]})]})}),rt&&e.jsx(wRt,{open:at,onOpenChange:Tn=>{wt(Tn),Tn||Ft(null)},userId:rt.id,userName:rt.name}),e.jsx(zs,{open:Ut,onOpenChange:Is,children:e.jsxs(Rs,{children:[e.jsxs(Vs,{children:[e.jsx($s,{children:"Set Password"}),e.jsxs(Cr,{children:["Set a new password for ",xs==null?void 0:xs.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(re,{htmlFor:"new-password",children:"New Password"}),e.jsx(be,{id:"new-password",type:"password",value:dt,onChange:Tn=>jt(Tn.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(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>Is(!1),children:"Cancel"}),e.jsx($,{onClick:xn,disabled:gt||!dt||dt.length<6,children:gt?"Setting...":"Set Password"})]})]})})]})},H1n={academy_video:"Academy Video",template:"Template",toolbox:"Toolbox Resource",newsletter:"Newsletter",social_swag:"Social Swag",event:"Event"},G1n={view:"Viewed",click_canva:"Opened Canva",click_pdf:"Downloaded PDF",click_video:"Watched Video",click_link:"Clicked Link",register:"Registered"},W1n=s=>{switch(s){case"academy_video":return e.jsx(ia,{className:"h-4 w-4"});case"template":return e.jsx(ea,{className:"h-4 w-4"});case"toolbox":return e.jsx(ea,{className:"h-4 w-4"});case"newsletter":return e.jsx(N2,{className:"h-4 w-4"});case"social_swag":return e.jsx(kn,{className:"h-4 w-4"});case"event":return e.jsx(ha,{className:"h-4 w-4"});default:return e.jsx(Ir,{className:"h-4 w-4"})}},K1n=({brokerageId:s})=>{const{toast:t}=Fi(),[n,r]=k.useState([]),[a,i]=k.useState([]),[l,o]=k.useState([]),[c,d]=k.useState(!0),[u,h]=k.useState(null);k.useEffect(()=>{m()},[s]);const m=async()=>{try{d(!0);const{data:x,error:y}=await V.from("profiles").select("id, name, email").eq("brokerage_id",s);if(y)throw y;const v=x.map(B=>B.id),_=new Map(x.map(B=>[B.id,B]));if(v.length===0){r([]),i([]),o([]);return}const{data:j,error:C}=await V.from("activity_logs").select("*").in("user_id",v).order("launched_at",{ascending:!1});if(C)throw C;const A=j.map(B=>{var U,G;return{id:B.id,user_id:B.user_id,app_name:B.app_name,launched_at:B.launched_at,user_name:((U=_.get(B.user_id))==null?void 0:U.name)||"Unknown",user_email:((G=_.get(B.user_id))==null?void 0:G.email)||"Unknown"}});r(A);const{data:M,error:I}=await V.from("content_engagement_logs").select("*").in("user_id",v).order("created_at",{ascending:!1});if(I)throw I;const P=(M||[]).map(B=>{var U,G;return{id:B.id,user_id:B.user_id,resource_type:B.resource_type,resource_id:B.resource_id,resource_title:B.resource_title,action_type:B.action_type,created_at:B.created_at,user_name:((U=_.get(B.user_id))==null?void 0:U.name)||"Unknown",user_email:((G=_.get(B.user_id))==null?void 0:G.email)||"Unknown"}});i(P);const R=new Map;x.forEach(B=>{R.set(B.id,{user_id:B.id,user_name:B.name,user_email:B.email,app_launches:0,content_views:0,last_activity:""})}),A.forEach(B=>{const U=R.get(B.user_id);U&&(U.app_launches++,(!U.last_activity||new Date(B.launched_at)>new Date(U.last_activity))&&(U.last_activity=B.launched_at))}),P.forEach(B=>{const U=R.get(B.user_id);U&&(U.content_views++,(!U.last_activity||new Date(B.created_at)>new Date(U.last_activity))&&(U.last_activity=B.created_at))});const O=Array.from(R.values()).filter(B=>B.app_launches>0||B.content_views>0).sort((B,U)=>new Date(U.last_activity).getTime()-new Date(B.last_activity).getTime());o(O)}catch(x){console.error("Error loading activity:",x),t({title:"Error",description:"Failed to load activity logs",variant:"destructive"})}finally{d(!1)}},p=x=>n.filter(y=>y.user_id===x),g=x=>a.filter(y=>y.user_id===x);return c?e.jsx(we,{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(we,{children:[e.jsxs(Vt,{children:[e.jsx(Yt,{children:"Agent Activity"}),e.jsx(vr,{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(Qa,{children:[e.jsx(Ja,{children:e.jsxs(vn,{children:[e.jsx(Dt,{children:"Agent"}),e.jsx(Dt,{className:"text-center",children:"App Launches"}),e.jsx(Dt,{className:"text-center",children:"Content Views"}),e.jsx(Dt,{children:"Last Active"})]})}),e.jsx(ei,{children:l.length===0?e.jsx(vn,{children:e.jsx(_t,{colSpan:4,className:"text-center text-muted-foreground",children:"No activity yet"})}):l.map(x=>e.jsxs(vn,{className:"cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>h({id:x.user_id,name:x.user_name,email:x.user_email}),children:[e.jsx(_t,{children:e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:x.user_name}),e.jsx("div",{className:"text-sm text-muted-foreground",children:x.user_email})]})}),e.jsx(_t,{className:"text-center",children:e.jsxs(qe,{variant:"outline",className:"gap-1",children:[e.jsx(pu,{className:"h-3 w-3"}),x.app_launches]})}),e.jsx(_t,{className:"text-center",children:e.jsxs(qe,{variant:"secondary",className:"gap-1",children:[e.jsx(ea,{className:"h-3 w-3"}),x.content_views]})}),e.jsx(_t,{className:"text-sm text-muted-foreground",children:x.last_activity&&Zc(new Date(x.last_activity),{addSuffix:!0})})]},x.user_id))})]})})})]}),e.jsx(zs,{open:!!u,onOpenChange:x=>!x&&h(null),children:e.jsxs(Rs,{className:"max-w-3xl max-h-[80vh] overflow-hidden flex flex-col",children:[e.jsxs(Vs,{children:[e.jsxs($s,{children:[u==null?void 0:u.name,"'s Activity"]}),e.jsx(Cr,{children:u==null?void 0:u.email})]}),e.jsxs(ya,{defaultValue:"content",className:"flex-1 overflow-hidden flex flex-col",children:[e.jsxs(va,{className:"grid w-full grid-cols-2",children:[e.jsx(is,{value:"content",children:"Content Engagement"}),e.jsx(is,{value:"apps",children:"App Launches"})]}),e.jsx(cs,{value:"content",className:"flex-1 overflow-auto",children:e.jsx("div",{className:"rounded-md border",children:e.jsxs(Qa,{children:[e.jsx(Ja,{children:e.jsxs(vn,{children:[e.jsx(Dt,{children:"Resource"}),e.jsx(Dt,{children:"Type"}),e.jsx(Dt,{children:"Action"}),e.jsx(Dt,{children:"Time"})]})}),e.jsx(ei,{children:u&&g(u.id).length===0?e.jsx(vn,{children:e.jsx(_t,{colSpan:4,className:"text-center text-muted-foreground",children:"No content engagement yet"})}):u&&g(u.id).map(x=>e.jsxs(vn,{children:[e.jsx(_t,{className:"max-w-[200px] truncate font-medium",children:x.resource_title}),e.jsx(_t,{children:e.jsxs(qe,{variant:"outline",className:"gap-1",children:[W1n(x.resource_type),H1n[x.resource_type]||x.resource_type]})}),e.jsx(_t,{children:e.jsx("span",{className:"text-sm text-muted-foreground",children:G1n[x.action_type]||x.action_type})}),e.jsx(_t,{className:"text-sm text-muted-foreground",children:Zc(new Date(x.created_at),{addSuffix:!0})})]},x.id))})]})})}),e.jsx(cs,{value:"apps",className:"flex-1 overflow-auto",children:e.jsx("div",{className:"rounded-md border",children:e.jsxs(Qa,{children:[e.jsx(Ja,{children:e.jsxs(vn,{children:[e.jsx(Dt,{children:"App"}),e.jsx(Dt,{children:"Time"})]})}),e.jsx(ei,{children:u&&p(u.id).length===0?e.jsx(vn,{children:e.jsx(_t,{colSpan:2,className:"text-center text-muted-foreground",children:"No app launches yet"})}):u&&p(u.id).map(x=>e.jsxs(vn,{children:[e.jsx(_t,{children:e.jsx(qe,{variant:"outline",children:x.app_name})}),e.jsx(_t,{className:"text-sm text-muted-foreground",children:Zc(new Date(x.launched_at),{addSuffix:!0})})]},x.id))})]})})})]})]})})]})},Y1n=({brokerageId:s})=>{const{toast:t}=Fi(),[n,r]=k.useState({totalAgents:0,activeAgents:0,pendingAgents:0,totalLaunches:0,launchesThisWeek:0,launchesThisMonth:0}),[a,i]=k.useState(!0);k.useEffect(()=>{l()},[s]);const l=async()=>{try{i(!0);const{data:o,error:c}=await V.from("profiles").select("id").eq("brokerage_id",s);if(c)throw c;const d=o.map(A=>A.id),u=d.length;if(d.length===0){i(!1);return}const{data:h,error:m}=await V.from("profiles").select("id, email").in("id",d);if(m)throw m;const{count:p}=await V.from("profiles").select("*",{count:"exact",head:!0}).eq("brokerage_id",s).not("last_login","is",null),g=p||0,x=u-g,{count:y}=await V.from("activity_logs").select("*",{count:"exact",head:!0}).in("user_id",d),v=new Date;v.setDate(v.getDate()-7);const{count:_}=await V.from("activity_logs").select("*",{count:"exact",head:!0}).in("user_id",d).gte("launched_at",v.toISOString()),j=new Date;j.setMonth(j.getMonth()-1);const{count:C}=await V.from("activity_logs").select("*",{count:"exact",head:!0}).in("user_id",d).gte("launched_at",j.toISOString());r({totalAgents:u,activeAgents:g,pendingAgents:x,totalLaunches:y||0,launchesThisWeek:_||0,launchesThisMonth:C||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(we,{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(we,{children:[e.jsxs(Vt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Yt,{className:"text-sm font-medium",children:"Total Agents"}),e.jsx(Xn,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(De,{children:[e.jsx("div",{className:"text-2xl font-bold",children:n.totalAgents}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[n.activeAgents," active, ",n.pendingAgents," pending"]})]})]}),e.jsxs(we,{children:[e.jsxs(Vt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Yt,{className:"text-sm font-medium",children:"Active Agents"}),e.jsx(nl,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(De,{children:[e.jsx("div",{className:"text-2xl font-bold",children:n.activeAgents}),e.jsx("p",{className:"text-xs text-muted-foreground",children:n.totalAgents>0?`${Math.round(n.activeAgents/n.totalAgents*100)}% of total`:"0% of total"})]})]}),e.jsxs(we,{children:[e.jsxs(Vt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Yt,{className:"text-sm font-medium",children:"Pending Invites"}),e.jsx(sa,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(De,{children:[e.jsx("div",{className:"text-2xl font-bold",children:n.pendingAgents}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Awaiting setup"})]})]}),e.jsxs(we,{children:[e.jsxs(Vt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Yt,{className:"text-sm font-medium",children:"Total App Launches"}),e.jsx(zp,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(De,{children:[e.jsx("div",{className:"text-2xl font-bold",children:n.totalLaunches}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"All time"})]})]}),e.jsxs(we,{children:[e.jsxs(Vt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Yt,{className:"text-sm font-medium",children:"This Week"}),e.jsx(zp,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(De,{children:[e.jsx("div",{className:"text-2xl font-bold",children:n.launchesThisWeek}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Last 7 days"})]})]}),e.jsxs(we,{children:[e.jsxs(Vt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Yt,{className:"text-sm font-medium",children:"This Month"}),e.jsx(zp,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(De,{children:[e.jsx("div",{className:"text-2xl font-bold",children:n.launchesThisMonth}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Last 30 days"})]})]})]})},Z1n=({brokerageId:s})=>{const[t,n]=k.useState([]),[r,a]=k.useState(!0),[i,l]=k.useState(!1),[o,c]=k.useState(!1),[d,u]=k.useState({description:"",maxUses:""});k.useEffect(()=>{h()},[s]);const h=async()=>{try{const{data:v,error:_}=await V.from("invite_codes").select("*").eq("brokerage_id",s).order("created_at",{ascending:!1});if(_)throw _;n(v||[])}catch(v){console.error("Error loading invite codes:",v),ae.error("Failed to load invite links")}finally{a(!1)}},m=()=>Math.random().toString(36).substring(2,8).toUpperCase(),p=async()=>{l(!0);try{const v=m(),{error:_}=await V.from("invite_codes").insert({code:v,description:d.description||null,max_uses:d.maxUses?parseInt(d.maxUses):null,brokerage_id:s,is_active:!0});if(_)throw _;ae.success("Invite link created!"),c(!1),u({description:"",maxUses:""}),h()}catch(v){console.error("Error creating invite code:",v),ae.error("Failed to create invite link")}finally{l(!1)}},g=async v=>{try{const{error:_}=await V.from("invite_codes").delete().eq("id",v);if(_)throw _;ae.success("Invite link deleted"),n(t.filter(j=>j.id!==v))}catch(_){console.error("Error deleting invite code:",_),ae.error("Failed to delete invite link")}},x=async(v,_)=>{try{const{error:j}=await V.from("invite_codes").update({is_active:!_}).eq("id",v);if(j)throw j;n(t.map(C=>C.id===v?{...C,is_active:!_}:C)),ae.success(`Invite link ${_?"deactivated":"activated"}`)}catch(j){console.error("Error toggling invite code:",j),ae.error("Failed to update invite link")}},y=v=>{const _=`${window.location.origin}/join?code=${v}`;navigator.clipboard.writeText(_),ae.success("Link copied to clipboard!")};return r?e.jsx(we,{children:e.jsx(De,{className:"flex items-center justify-center py-8",children:e.jsx(Jt,{className:"h-6 w-6 animate-spin text-muted-foreground"})})}):e.jsxs(we,{children:[e.jsxs(Vt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(Yt,{className:"flex items-center gap-2",children:[e.jsx(od,{className:"h-5 w-5"}),"Agent Invite Links"]}),e.jsx(vr,{children:"Create shareable links for agents to join your brokerage"})]}),e.jsxs(zs,{open:o,onOpenChange:c,children:[e.jsx(yl,{asChild:!0,children:e.jsxs($,{size:"sm",children:[e.jsx(nn,{className:"mr-2 h-4 w-4"}),"Create Link"]})}),e.jsxs(Rs,{children:[e.jsxs(Vs,{children:[e.jsx($s,{children:"Create Invite Link"}),e.jsx(Cr,{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(re,{htmlFor:"description",children:"Description (optional)"}),e.jsx(be,{id:"description",placeholder:"e.g., New agent recruiting campaign",value:d.description,onChange:v=>u({...d,description:v.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"maxUses",children:"Max Uses (optional)"}),e.jsx(be,{id:"maxUses",type:"number",placeholder:"Leave empty for unlimited",value:d.maxUses,onChange:v=>u({...d,maxUses:v.target.value})})]}),e.jsx($,{onClick:p,disabled:i,className:"w-full",children:i?e.jsxs(e.Fragment,{children:[e.jsx(Jt,{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(od,{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(v=>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:v.code}),e.jsx(qe,{variant:v.is_active?"default":"secondary",children:v.is_active?"Active":"Inactive"})]}),v.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1 truncate",children:v.description}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[v.uses_count," uses",v.max_uses&&` / ${v.max_uses} max`]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx($,{variant:"ghost",size:"sm",onClick:()=>y(v.code),title:"Copy link",children:e.jsx(Da,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>x(v.id,v.is_active),title:v.is_active?"Deactivate":"Activate",children:v.is_active?"Disable":"Enable"}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>g(v.id),className:"text-destructive hover:text-destructive",title:"Delete",children:e.jsx(Un,{className:"h-4 w-4"})})]})]},v.id))})})]})},X1n=({open:s,onOpenChange:t,referralCode:n,brokerageId:r,senderName:a,brokerageName:i,onInvitesSent:l})=>{const[o,c]=k.useState(""),[d,u]=k.useState([]),[h,m]=k.useState(""),[p,g]=k.useState(!1),x=C=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(C),y=()=>{const C=o.trim().toLowerCase();if(C&&x(C)&&!d.includes(C)){if(d.length>=10){ae.error("Maximum 10 emails per invite");return}u([...d,C]),c("")}else C&&!x(C)?ae.error("Please enter a valid email address"):d.includes(C)&&ae.error("Email already added")},v=C=>{u(d.filter(A=>A!==C))},_=C=>{(C.key==="Enter"||C.key===",")&&(C.preventDefault(),y())},j=async()=>{if(d.length===0){ae.error("Please add at least one email address");return}g(!0);try{const{data:C,error:A}=await V.functions.invoke("send-referral-invite",{body:{emails:d,personalMessage:h.trim()||void 0,referralCode:n,brokerageId:r,senderName:a,brokerageName:i}});if(A)throw A;C.successCount===C.totalCount?ae.success(`${C.successCount} invite${C.successCount>1?"s":""} sent successfully!`):ae.warning(`${C.successCount} of ${C.totalCount} invites sent. Some failed.`),u([]),m(""),t(!1),l==null||l()}catch(C){console.error("Error sending invites:",C),ae.error("Failed to send invites. Please try again.")}finally{g(!1)}};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"sm:max-w-[550px]",children:[e.jsxs(Vs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(pn,{className:"h-5 w-5 text-primary"}),"Invite Broker Friends"]}),e.jsx(Cr,{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(Zo,{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(re,{htmlFor:"email",children:"Email Addresses (up to 10)"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(be,{id:"email",type:"email",placeholder:"Enter email and press Enter",value:o,onChange:C=>c(C.target.value),onKeyDown:_,onBlur:y}),e.jsx($,{type:"button",variant:"secondary",onClick:y,children:"Add"})]}),d.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2 mt-2",children:d.map(C=>e.jsxs(qe,{variant:"secondary",className:"flex items-center gap-1 pr-1",children:[C,e.jsx("button",{type:"button",onClick:()=>v(C),className:"ml-1 rounded-full p-0.5 hover:bg-muted",children:e.jsx(mr,{className:"h-3 w-3"})})]},C))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"message",children:"Personal Message (optional)"}),e.jsx(Ls,{id:"message",placeholder:"Add a personal note that will appear at the top of the email...",value:h,onChange:C=>m(C.target.value),rows:3,maxLength:500}),e.jsxs("p",{className:"text-xs text-muted-foreground text-right",children:[h.length,"/500 characters"]})]}),e.jsxs("div",{className:"bg-muted/50 rounded-lg p-4 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium",children:[e.jsx(kn,{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($,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx($,{onClick:j,disabled:d.length===0||p,children:p?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(Wr,{className:"h-4 w-4 mr-2"}),"Send ",d.length>0&&`(${d.length})`," Invite",d.length!==1?"s":""]})})]})]})})},Q1n=({brokerageId:s,refreshTrigger:t})=>{const[n,r]=k.useState([]),[a,i]=k.useState(!0);k.useEffect(()=>{l()},[s,t]);const l=async()=>{try{const{data:c,error:d}=await V.from("referral_invites").select("*").eq("referrer_brokerage_id",s).order("sent_at",{ascending:!1}).limit(20);if(d)throw d;r(c||[])}catch(c){console.error("Error fetching invites:",c)}finally{i(!1)}},o=c=>{switch(c){case"signed_up":return e.jsxs(qe,{className:"bg-green-100 text-green-800 gap-1",children:[e.jsx(nl,{className:"h-3 w-3"}),"Signed Up"]});case"expired":return e.jsxs(qe,{variant:"outline",className:"text-muted-foreground gap-1",children:[e.jsx(ju,{className:"h-3 w-3"}),"Expired"]});default:return e.jsxs(qe,{variant:"secondary",className:"gap-1",children:[e.jsx(sa,{className:"h-3 w-3"}),"Pending"]})}};return a?e.jsx("div",{className:"flex justify-center py-4",children:e.jsx("div",{className:"h-5 w-5 animate-spin rounded-full border-2 border-primary border-t-transparent"})}):n.length===0?e.jsxs("div",{className:"text-center py-6 text-muted-foreground",children:[e.jsx(pn,{className:"h-8 w-8 mx-auto mb-2 opacity-50"}),e.jsx("p",{className:"text-sm",children:"No invites sent yet"}),e.jsx("p",{className:"text-xs",children:"Start inviting broker friends to earn rewards!"})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm font-medium mb-3",children:"Recent Invites"}),n.map(c=>e.jsxs("div",{className:"flex items-center justify-between p-2.5 bg-muted/30 rounded-lg",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:c.recipient_email}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Sent ",Ys(new Date(c.sent_at),"MMM d, yyyy")]})]}),o(c.status)]},c.id))]})},J1n=()=>{const{brokerageId:s,user:t}=ks(),[n,r]=k.useState(null),[a,i]=k.useState(""),[l,o]=k.useState(""),[c,d]=k.useState([]),[u,h]=k.useState(!0),[m,p]=k.useState(!1),[g,x]=k.useState(0);k.useEffect(()=>{s&&y()},[s]);const y=async()=>{try{const[M,I]=await Promise.all([V.from("brokerages").select("name").eq("id",s).single(),t?V.from("profiles").select("name").eq("id",t.id).single():Promise.resolve({data:null})]);M.data&&i(M.data.name),I.data&&o(I.data.name||"A LevelUp Member");const{data:P}=await V.from("referral_codes").select("code").eq("brokerage_id",s).single();if(P)r(P.code);else{const O=`REF${s==null?void 0:s.slice(0,8).toUpperCase()}`;await V.from("referral_codes").insert({brokerage_id:s,code:O}),r(O)}const{data:R}=await V.from("referrals").select(` *, referred_user:profiles!referred_user_id(name, email), referred_brokerage:brokerages!referred_brokerage_id(name) `).eq("referrer_brokerage_id",s).order("created_at",{ascending:!1});d(R||[])}catch(M){console.error("Error fetching referral data:",M)}finally{h(!1)}},v=()=>{const M=`https://dashboard.relevelup.com/?ref=${n}`;navigator.clipboard.writeText(M),ae.success("Referral link copied to clipboard!")},_=c.filter(M=>M.status==="qualified").length,j=c.filter(M=>M.status==="pending").length,C=_*25,A=Math.max(0,Math.ceil((299-C)/25));return u?null:e.jsxs(e.Fragment,{children:[e.jsxs(we,{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(Zo,{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:["$",C]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Monthly Savings"})]}),C>0&&e.jsxs("div",{className:"flex items-center gap-1 text-green-600",children:[e.jsx(nl,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm font-medium",children:"Active"})]})]}),A>0&&C<299&&e.jsxs("div",{className:"text-right",children:[e.jsxs("p",{className:"text-sm font-medium",children:["Refer ",A," 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"})]}),C>=299&&e.jsxs("div",{className:"flex items-center gap-2 text-primary",children:[e.jsx(kn,{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($,{onClick:()=>p(!0),className:"w-full",size:"lg",children:[e.jsx(pn,{className:"h-4 w-4 mr-2"}),"Invite Broker Friends"]}),e.jsxs($,{onClick:v,variant:"outline",className:"w-full",size:"lg",children:[e.jsx(Da,{className:"h-4 w-4 mr-2"}),"Copy Referral Link"]})]}),e.jsxs("div",{className:"p-4 bg-muted/50 rounded-lg",children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:"Your Referral Link"}),e.jsxs("code",{className:"block px-3 py-2 bg-background rounded border text-sm break-all",children:["https://dashboard.relevelup.com/?ref=",n]})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsxs("div",{className:"text-center p-4 bg-green-50 dark:bg-green-950/20 rounded-lg border border-green-200 dark:border-green-900",children:[e.jsx(Su,{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:["$",C]}),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(Xn,{className:"h-5 w-5 mx-auto text-primary mb-1"}),e.jsx("p",{className:"text-2xl font-bold",children:_}),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(sa,{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:j}),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(Q1n,{brokerageId:s,refreshTrigger:g}),c.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm font-medium",children:"Your Referrals"}),c.slice(0,5).map(M=>{var I,P;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:((I=M.referred_brokerage)==null?void 0:I.name)||((P=M.referred_user)==null?void 0:P.email)||"Pending setup"}),e.jsxs(qe,{variant:M.status==="qualified"?"default":M.status==="pending"?"secondary":"destructive",className:M.status==="qualified"?"bg-green-600":"",children:[M.status==="qualified"&&e.jsx(nl,{className:"h-3 w-3 mr-1"}),M.status]})]},M.id)})]})]})]}),e.jsx(X1n,{open:m,onOpenChange:p,referralCode:n||"",brokerageId:s||"",senderName:l||"A LevelUp Member",brokerageName:a,onInvitesSent:()=>x(M=>M+1)})]})},ebn=({brokerageId:s})=>{const t=Jn(),{teams:n,isLoading:r}=dA(s),{data:a,isLoading:i}=pt({queryKey:["team-aggregate-stats",s,n.map(u=>u.id)],queryFn:async()=>{if(n.length===0)return[];const u=n.map(M=>M.id),{data:h}=await V.from("team_members").select("team_id, user_id, role").in("team_id",u);if(!h||h.length===0)return n.map(M=>({team_id:M.id,team_name:M.name,member_count:0,leader_name:null,leader_avatar:null,total_contacts:0,total_deals:0,total_videos:0}));const m=h.map(M=>M.user_id),p=h.filter(M=>M.role==="team_leader").map(M=>M.user_id),{data:g}=await V.from("profiles").select("id, name, avatar_url").in("id",p),x=new Map((g||[]).map(M=>[M.id,M])),{data:y}=await V.from("innercircle_contacts").select("owner_user_id").in("owner_user_id",m),{data:v}=await V.from("deal_pipeline").select("owner_user_id").in("owner_user_id",m),{data:_}=await V.from("agent_videos").select("owner_user_id").in("owner_user_id",m).eq("is_deleted",!1),j=new Map;(y||[]).forEach(M=>{j.set(M.owner_user_id,(j.get(M.owner_user_id)||0)+1)});const C=new Map;(v||[]).forEach(M=>{C.set(M.owner_user_id,(C.get(M.owner_user_id)||0)+1)});const A=new Map;return(_||[]).forEach(M=>{A.set(M.owner_user_id,(A.get(M.owner_user_id)||0)+1)}),n.map(M=>{const I=h.filter(H=>H.team_id===M.id),P=I.find(H=>H.role==="team_leader"),R=P?x.get(P.user_id):null,O=I.map(H=>H.user_id),B=O.reduce((H,Y)=>H+(j.get(Y)||0),0),U=O.reduce((H,Y)=>H+(C.get(Y)||0),0),G=O.reduce((H,Y)=>H+(A.get(Y)||0),0);return{team_id:M.id,team_name:M.name,member_count:I.length,leader_name:(R==null?void 0:R.name)||null,leader_avatar:(R==null?void 0:R.avatar_url)||null,total_contacts:B,total_deals:U,total_videos:G}})},enabled:n.length>0});if(r||i)return e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:[1,2,3].map(u=>e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsx(fn,{className:"h-5 w-32"})}),e.jsx(De,{children:e.jsx(fn,{className:"h-24 w-full"})})]},u))});if(n.length===0)return e.jsx(we,{children:e.jsxs(De,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Xn,{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($,{onClick:()=>t("/brokerage/teams"),children:"Manage Teams"})]})});const o=(a||[]).reduce((u,h)=>u+h.member_count,0),c=(a||[]).reduce((u,h)=>u+h.total_contacts,0),d=(a||[]).reduce((u,h)=>u+h.total_deals,0);return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid gap-4 grid-cols-2 md:grid-cols-4",children:[e.jsx(we,{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(Xn,{className:"h-4 w-4"})," Teams"]}),e.jsx("p",{className:"text-2xl font-bold",children:n.length})]})}),e.jsx(we,{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(Xn,{className:"h-4 w-4"})," Total Members"]}),e.jsx("p",{className:"text-2xl font-bold",children:o})]})}),e.jsx(we,{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(O8,{className:"h-4 w-4"})," Total Contacts"]}),e.jsx("p",{className:"text-2xl font-bold",children:c.toLocaleString()})]})}),e.jsx(we,{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(zx,{className:"h-4 w-4"})," Total Deals"]}),e.jsx("p",{className:"text-2xl font-bold",children:d.toLocaleString()})]})})]}),e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:(a||[]).map(u=>e.jsxs(we,{className:"hover:shadow-md transition-shadow",children:[e.jsxs(Vt,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(Yt,{className:"text-lg",children:u.team_name}),e.jsxs(qe,{variant:"secondary",children:[u.member_count," members"]})]}),u.leader_name&&e.jsxs("div",{className:"flex items-center gap-2 mt-2",children:[e.jsxs(Wa,{className:"h-6 w-6",children:[e.jsx(eo,{src:u.leader_avatar||""}),e.jsx(Ka,{className:"text-xs",children:u.leader_name.charAt(0).toUpperCase()})]}),e.jsxs("span",{className:"text-sm text-muted-foreground flex items-center gap-1",children:[e.jsx(ky,{className:"h-3 w-3 text-amber-500"}),u.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:u.total_contacts.toLocaleString()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Contacts"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-lg font-semibold",children:u.total_deals.toLocaleString()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Deals"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-lg font-semibold",children:u.total_videos.toLocaleString()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Videos"})]})]})})]},u.team_id))}),e.jsx("div",{className:"flex justify-end",children:e.jsx($,{variant:"outline",onClick:()=>t("/brokerage/teams"),children:"Manage Teams →"})})]})},tbn=()=>{const{user:s,isBrokerageManager:t,brokerageId:n,isAdmin:r,managedBrokerages:a,selectedBrokerageId:i,setSelectedBrokerageId:l}=ks(),o=Jn(),{toast:c}=Fi(),[d,u]=k.useState(""),[h,m]=k.useState(!0),p=i||(a.length>0?a[0].id:n);k.useEffect(()=>{if(!s||!t&&!r){o("/dashboard");return}!i&&a.length>0&&l(a[0].id),p?g():a.length===0&&!n&&m(!1)},[s,t,r,p,o,a,i]);const g=async()=>{if(!p){m(!1);return}try{const{data:x,error:y}=await V.from("brokerages").select("name").eq("id",p).single();if(y)throw y;u(x.name)}catch(x){console.error("Error loading brokerage info:",x),c({title:"Error",description:"Failed to load brokerage information",variant:"destructive"})}finally{m(!1)}};return h?e.jsx(Xs,{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"})})}):p?e.jsx(Xs,{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(bs,{value:i||"",onValueChange:l,children:[e.jsxs(ys,{className:"w-[280px]",children:[e.jsx(Gi,{className:"mr-2 h-4 w-4"}),e.jsx(_s,{placeholder:"Select brokerage"})]}),e.jsx(vs,{children:a.map(x=>e.jsx(We,{value:x.id,children:x.name},x.id))})]})]}),e.jsxs(ya,{defaultValue:"agents",className:"space-y-4",children:[e.jsxs(va,{className:"grid w-full grid-cols-4 md:grid-cols-8",children:[e.jsx(is,{value:"agents",children:"Agents"}),e.jsx(is,{value:"teams",children:"Teams"}),e.jsx(is,{value:"invite",children:"Invite Links"}),e.jsx(is,{value:"referrals",children:"Referrals"}),e.jsx(is,{value:"leaderboard",children:"Leaderboard"}),e.jsx(is,{value:"activity",children:"Activity"}),e.jsx(is,{value:"analytics",children:"Analytics"}),e.jsx(is,{value:"shares",children:"Shares"})]}),e.jsx(cs,{value:"agents",className:"space-y-4",children:e.jsx(V1n,{brokerageId:p})}),e.jsx(cs,{value:"teams",className:"space-y-4",children:e.jsx(ebn,{brokerageId:p})}),e.jsx(cs,{value:"invite",className:"space-y-4",children:e.jsx(Z1n,{brokerageId:p})}),e.jsx(cs,{value:"referrals",className:"space-y-4",children:e.jsx(J1n,{})}),e.jsx(cs,{value:"leaderboard",className:"space-y-4",children:e.jsx(yIt,{brokerageId:p,title:`${d} Event Leaderboard`,showUserStats:!1})}),e.jsx(cs,{value:"activity",className:"space-y-4",children:e.jsx(K1n,{brokerageId:p})}),e.jsx(cs,{value:"analytics",className:"space-y-4",children:e.jsx(Y1n,{brokerageId:p})}),e.jsx(cs,{value:"shares",className:"space-y-4",children:e.jsx(JRt,{brokerageOnly:!0,brokerageId:p})})]})]})}):e.jsx(Xs,{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(Gi,{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 sbn({brokerageId:s,canManage:t}){const{user:n}=ks(),[r,a]=k.useState([]),[i,l]=k.useState(!0),[o,c]=k.useState(!1),[d,u]=k.useState(null),[h,m]=k.useState(null),[p,g]=k.useState(!1),[x,y]=k.useState(""),[v,_]=k.useState(""),[j,C]=k.useState(!1),A=async()=>{try{const{data:O,error:B}=await V.from("brokerage_announcements").select("*").eq("brokerage_id",s).order("is_pinned",{ascending:!1}).order("pinned_at",{ascending:!1,nullsFirst:!1}).order("created_at",{ascending:!1});if(B)throw B;const U=O;if(U&&U.length>0){const G=[...new Set(U.map(ee=>ee.created_by))],{data:H}=await V.from("profiles").select("id, name, avatar_url").in("id",G),Y=new Map((H==null?void 0:H.map(ee=>[ee.id,ee]))||[]),se=U.map(ee=>({...ee,author:Y.get(ee.created_by)||{name:"Unknown",avatar_url:null}}));a(se)}else a([])}catch(O){console.error("Error fetching announcements:",O)}finally{l(!1)}};k.useEffect(()=>{A()},[s]);const M=()=>{y(""),_(""),C(!1),u(null)},I=O=>{O?(u(O),y(O.title),_(O.content),C(O.is_pinned)):M(),c(!0)},P=async()=>{if(!x.trim()||!v.trim()){ae.error("Please fill in all fields");return}g(!0);try{if(d){const{error:O}=await V.from("brokerage_announcements").update({title:x.trim(),content:v.trim(),is_pinned:j,pinned_at:j?new Date().toISOString():null}).eq("id",d.id);if(O)throw O;ae.success("Announcement updated")}else{const{error:O}=await V.from("brokerage_announcements").insert({brokerage_id:s,created_by:n==null?void 0:n.id,title:x.trim(),content:v.trim(),is_pinned:j,pinned_at:j?new Date().toISOString():null});if(O)throw O;ae.success("Announcement created")}c(!1),M(),A()}catch(O){console.error("Error saving announcement:",O),ae.error("Failed to save announcement")}finally{g(!1)}},R=async()=>{if(h)try{const{error:O}=await V.from("brokerage_announcements").delete().eq("id",h);if(O)throw O;ae.success("Announcement deleted"),A()}catch(O){console.error("Error deleting announcement:",O),ae.error("Failed to delete announcement")}finally{m(null)}};return i?e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsxs(Yt,{className:"flex items-center gap-2",children:[e.jsx(xm,{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(we,{children:[e.jsxs(Vt,{className:"flex flex-row items-center justify-between space-y-0 pb-4",children:[e.jsxs(Yt,{className:"flex items-center gap-2",children:[e.jsx(xm,{className:"h-5 w-5 text-primary"}),"Announcements"]}),t&&e.jsxs($,{size:"sm",onClick:()=>I(),className:"gap-1",children:[e.jsx(nn,{className:"h-4 w-4"}),"New"]})]}),e.jsx(De,{children:r.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No announcements yet"}):e.jsx("div",{className:"space-y-4",children:r.map(O=>{var B,U,G,H;return e.jsx("div",{className:`p-4 rounded-lg border ${O.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:[O.is_pinned&&e.jsx(XT,{className:"h-3.5 w-3.5 text-primary shrink-0"}),e.jsx("h4",{className:"font-semibold truncate",children:O.title})]}),e.jsx("p",{className:"text-sm text-muted-foreground whitespace-pre-wrap",children:O.content}),e.jsxs("div",{className:"flex items-center gap-2 mt-3 text-xs text-muted-foreground",children:[e.jsxs(Wa,{className:"h-5 w-5",children:[e.jsx(eo,{src:((B=O.author)==null?void 0:B.avatar_url)||void 0}),e.jsx(Ka,{className:"text-[10px]",children:((G=(U=O.author)==null?void 0:U.name)==null?void 0:G.charAt(0))||"?"})]}),e.jsx("span",{children:(H=O.author)==null?void 0:H.name}),e.jsx("span",{children:"•"}),e.jsx("span",{children:Ys(new Date(O.created_at),"MMM d, yyyy")})]})]}),t&&e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>I(O),children:e.jsx(ui,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive hover:text-destructive",onClick:()=>m(O.id),children:e.jsx(Un,{className:"h-4 w-4"})})]})]})},O.id)})})})]}),e.jsx(zs,{open:o,onOpenChange:c,children:e.jsxs(Rs,{children:[e.jsx(Vs,{children:e.jsx($s,{children:d?"Edit Announcement":"New Announcement"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"title",children:"Title"}),e.jsx(be,{id:"title",value:x,onChange:O=>y(O.target.value),placeholder:"Announcement title..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"content",children:"Content"}),e.jsx(Ls,{id:"content",value:v,onChange:O=>_(O.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(On,{id:"pinned",checked:j,onCheckedChange:C}),e.jsxs(re,{htmlFor:"pinned",className:"flex items-center gap-1 cursor-pointer",children:[e.jsx(XT,{className:"h-4 w-4"}),"Pin to top"]})]})}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx($,{variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsx($,{onClick:P,disabled:p,children:p?"Saving...":d?"Update":"Create"})]})]})]})}),e.jsx(oc,{open:!!h,onOpenChange:()=>m(null),children:e.jsxs(Ql,{children:[e.jsxs(Jl,{children:[e.jsx(tc,{children:"Delete Announcement"}),e.jsx(sc,{children:"Are you sure you want to delete this announcement? This action cannot be undone."})]}),e.jsxs(ec,{children:[e.jsx(nc,{children:"Cancel"}),e.jsx(Vl,{onClick:R,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete"})]})]})})]})}function nbn({brokerageId:s,canManage:t=!1}){const{startImpersonation:n,isLoading:r}=C3e(),{user:a}=ks(),[i,l]=k.useState([]),[o,c]=k.useState(!0),[d,u]=k.useState(""),[h,m]=k.useState(new Set);k.useEffect(()=>{(async()=>{try{const{data:x,error:y}=await V.from("profiles").select("id, name, email, phone, avatar_url, title, bio, areas_served, years_experience, instagram_url, facebook_url, linkedin_url").eq("brokerage_id",s).order("name");if(y)throw y;if(l(x||[]),x&&x.length>0){const v=x.map(j=>j.id),{data:_}=await V.from("agent_assistant_assignments").select("agent_id").in("agent_id",v);_&&m(new Set(_.map(j=>j.agent_id)))}}catch(x){console.error("Error fetching agents:",x)}finally{c(!1)}})()},[s]);const p=i.filter(g=>{var x,y;return g.name.toLowerCase().includes(d.toLowerCase())||g.email.toLowerCase().includes(d.toLowerCase())||((x=g.title)==null?void 0:x.toLowerCase().includes(d.toLowerCase()))||((y=g.areas_served)==null?void 0:y.toLowerCase().includes(d.toLowerCase()))});return o?e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsxs(Yt,{className:"flex items-center gap-2",children:[e.jsx(Xn,{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(g=>e.jsx("div",{className:"animate-pulse",children:e.jsx("div",{className:"h-48 bg-muted rounded-lg"})},g))})})]}):e.jsxs(we,{children:[e.jsxs(Vt,{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4 space-y-0",children:[e.jsxs(Yt,{className:"flex items-center gap-2",children:[e.jsx(Xn,{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(Yr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search agents...",value:d,onChange:g=>u(g.target.value),className:"pl-9"})]})]}),e.jsx(De,{children:p.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:p.map(g=>e.jsx(rbn,{agent:g,hasAssistant:h.has(g.id),canImpersonate:t&&g.id!==(a==null?void 0:a.id),onImpersonate:()=>n(g.id,"/my-brokerage"),impersonationLoading:r},g.id))})})]})}function rbn({agent:s,hasAssistant:t,canImpersonate:n,onImpersonate:r,impersonationLoading:a}){const i=s.name.split(" ").map(l=>l[0]).join("").toUpperCase().slice(0,2);return e.jsxs("div",{className:"group relative bg-card border rounded-xl p-4 hover:shadow-md transition-shadow",children:[e.jsxs("div",{className:"flex flex-col items-center text-center mb-3",children:[e.jsxs(Wa,{className:"h-20 w-20 mb-3 ring-2 ring-background shadow-md",children:[e.jsx(eo,{src:s.avatar_url||void 0,alt:s.name}),e.jsx(Ka,{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(qe,{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(Si,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:"truncate",children:s.areas_served})]}),s.years_experience&&e.jsxs("p",{className:"text-xs text-muted-foreground text-center",children:[s.years_experience," ",s.years_experience===1?"year":"years"," experience"]})]}),e.jsxs("div",{className:"flex items-center justify-center gap-2",children:[n&&e.jsxs(Lx,{children:[e.jsx(Rx,{asChild:!0,children:e.jsx($,{variant:"outline",size:"icon",className:"h-8 w-8 text-blue-600 hover:text-blue-700 hover:bg-blue-50",onClick:r,disabled:a,children:e.jsx(U8,{className:"h-4 w-4"})})}),e.jsxs(Jg,{children:["Login as ",s.name]})]}),s.phone&&e.jsx($,{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(ka,{className:"h-4 w-4"})})}),e.jsx($,{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(pn,{className:"h-4 w-4"})})}),s.linkedin_url&&e.jsx($,{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(dv,{className:"h-4 w-4"})})}),s.instagram_url&&e.jsx($,{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(Sf,{className:"h-4 w-4"})})})]})]})}function abn({brokerageId:s}){const[t,n]=k.useState([]),[r,a]=k.useState(!0);if(k.useEffect(()=>{(async()=>{try{const{data:c,error:d}=await V.from("profiles").select("id, name, avatar_url").eq("brokerage_id",s);if(d)throw d;if(!c||c.length===0){n([]),a(!1);return}const u=c.map(x=>x.id),{data:h,error:m}=await V.from("agent_attendance_stats").select("user_id, total_points").in("user_id",u).order("total_points",{ascending:!1});if(m)throw m;const p=new Map(c.map(x=>[x.id,x])),g=(h||[]).filter(x=>x.total_points>0).map(x=>{const y=p.get(x.user_id);return{user_id:x.user_id,total_points:x.total_points,name:(y==null?void 0:y.name)||"Unknown",avatar_url:(y==null?void 0:y.avatar_url)||null}});n(g)}catch(c){console.error("Error fetching leaderboard:",c)}finally{a(!1)}})()},[s]),r)return e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsxs(Yt,{className:"flex items-center gap-2",children:[e.jsx(ql,{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(y3,{className:Ot("h-5 w-5",i(o))}):e.jsx("span",{className:"w-5 text-center text-sm text-muted-foreground",children:o});return e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsxs(Yt,{className:"flex items-center gap-2",children:[e.jsx(ql,{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(h=>h[0]).join("").toUpperCase().slice(0,2),u=c+1;return e.jsxs("div",{className:Ot("flex items-center gap-3 p-2 rounded-lg",u<=3&&"bg-muted/50"),children:[e.jsx("div",{className:"w-6 flex justify-center",children:l(u)}),e.jsxs(Wa,{className:"h-8 w-8",children:[e.jsx(eo,{src:o.avatar_url||void 0}),e.jsx(Ka,{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 ibn({brokerageId:s}){const t=Jn(),[n,r]=k.useState([]),[a,i]=k.useState(!0);k.useEffect(()=>{(async()=>{try{const{data:c,error:d}=await V.from("profiles").select("id, name, avatar_url").eq("brokerage_id",s);if(d)throw d;if(!c||c.length===0){r([]),i(!1);return}const u=c.map(x=>x.id),h=new Map(c.map(x=>[x.id,x])),{data:m,error:p}=await V.from("listings").select(` id, slug, property_address, city, price, property_type, agent_id, listing_photos(photo_url) `).in("agent_id",u).eq("status","active").order("created_at",{ascending:!1}).limit(6);if(p)throw p;const g=(m||[]).map(x=>({id:x.id,slug:x.slug,property_address:x.property_address,city:x.city,price:x.price,property_type:x.property_type,agent_id:x.agent_id,agent:h.get(x.agent_id)||null,photos:x.listing_photos||[]}));r(g)}catch(c){console.error("Error fetching listings:",c)}finally{i(!1)}})()},[s]);const l=o=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(o);return a?e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsxs(Yt,{className:"flex items-center gap-2",children:[e.jsx(ua,{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(we,{children:[e.jsxs(Vt,{className:"flex flex-row items-center justify-between space-y-0 pb-4",children:[e.jsxs(Yt,{className:"flex items-center gap-2",children:[e.jsx(ua,{className:"h-5 w-5 text-primary"}),"Brokerage Listings"]}),e.jsxs($,{size:"sm",variant:"outline",onClick:()=>t("/mission-control/listings"),className:"gap-1",children:[e.jsx(nn,{className:"h-4 w-4"}),"Add Listing"]})]}),e.jsxs(De,{children:[n.length===0?e.jsxs("div",{className:"text-center py-8",children:[e.jsx(ua,{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($,{size:"sm",onClick:()=>t("/mission-control/listings/new"),className:"gap-1",children:[e.jsx(nn,{className:"h-4 w-4"}),"Add Your First Listing"]})]}):e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:n.map(o=>e.jsxs("div",{onClick:()=>window.open(`https://listings.relevelup.com/${o.slug||o.id}`,"_blank"),className:"group cursor-pointer border rounded-lg overflow-hidden hover:shadow-md transition-shadow",children:[e.jsxs("div",{className:"relative h-24 bg-muted",children:[o.photos&&o.photos.length>0?e.jsx("img",{src:o.photos[0].photo_url,alt:o.property_address||"Listing",className:"w-full h-full object-cover"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(ua,{className:"h-8 w-8 text-muted-foreground"})}),e.jsx("div",{className:"absolute top-2 left-2",children:e.jsx("span",{className:"text-[10px] font-medium bg-primary text-primary-foreground px-1.5 py-0.5 rounded uppercase",children:o.property_type.replace("_"," ")})})]}),e.jsxs("div",{className:"p-2.5",children:[e.jsx("p",{className:"font-semibold text-sm text-primary",children:l(o.price)}),e.jsx("p",{className:"text-xs text-muted-foreground truncate mt-0.5",children:o.property_address||"Address not available"}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:o.city}),o.agent&&e.jsxs("p",{className:"text-[10px] text-muted-foreground mt-1.5 truncate",children:["Listed by ",o.agent.name]})]})]},o.id))}),n.length>0&&e.jsxs($,{variant:"ghost",size:"sm",className:"w-full mt-3",onClick:()=>t("/mission-control/listings"),children:["View All Listings",e.jsx(Ir,{className:"h-3 w-3 ml-1"})]})]})]})}const obn={primary_color:"",secondary_color:"",accent_color:"",logo_url:"",logo_dark_url:"",icon_mark_url:"",heading_font:"",body_font:"",legal_name:"",license_number:"",license_state:"",compliance_line:""};function lbn({brokerageId:s,canManage:t}){const{user:n}=ks(),{toast:r}=Fi(),{data:a,isLoading:i}=M8s(s),l=P8s(s),[o,c]=k.useState({...obn}),[d,u]=k.useState({show_equal_housing:!1,show_realtor_logo:!1,lock_colors:!1,lock_logo:!1}),[h,m]=k.useState(null),p={logo_url:k.useRef(null),logo_dark_url:k.useRef(null),icon_mark_url:k.useRef(null)};k.useEffect(()=>{a&&(c({primary_color:a.primary_color||"",secondary_color:a.secondary_color||"",accent_color:a.accent_color||"",logo_url:a.logo_url||"",logo_dark_url:a.logo_dark_url||"",icon_mark_url:a.icon_mark_url||"",heading_font:a.heading_font||"",body_font:a.body_font||"",legal_name:a.legal_name||"",license_number:a.license_number||"",license_state:a.license_state||"",compliance_line:a.compliance_line||""}),u({show_equal_housing:!!a.show_equal_housing,show_realtor_logo:!!a.show_realtor_logo,lock_colors:!!a.lock_colors,lock_logo:!!a.lock_logo}))},[a]);const g=(_,j)=>c(C=>({...C,[_]:j})),x=async(_,j)=>{if(n){m(_);try{const C=await xIt(n.id,j,`brokerage-${_}`);g(_,C),r({title:"Image uploaded"})}catch(C){r({title:"Upload failed",description:C.message,variant:"destructive"})}finally{m(null)}}},y=async()=>{try{await l.mutateAsync({...Object.fromEntries(Object.entries(o).map(([_,j])=>[_,j||null])),...d}),r({title:"Brokerage brand saved",description:"Agents in this brokerage now inherit these settings."})}catch(_){r({title:"Could not save",description:_.message,variant:"destructive"})}},v=(_,j)=>e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:j}),e.jsxs("div",{className:"flex items-center gap-3",children:[o[_]&&e.jsx("img",{src:o[_],alt:j,className:"h-12 w-auto rounded border bg-background p-1"}),e.jsx("input",{ref:p[_],type:"file",accept:"image/*",className:"hidden",onChange:C=>{var A;return((A=C.target.files)==null?void 0:A[0])&&x(_,C.target.files[0])}}),e.jsxs($,{type:"button",variant:"outline",disabled:!t||h===_,onClick:()=>{var C;return(C=p[_].current)==null?void 0:C.click()},children:[h===_?e.jsx(Jt,{className:"h-4 w-4 animate-spin"}):e.jsx(gi,{className:"h-4 w-4"}),e.jsx("span",{className:"ml-2",children:"Upload"})]}),o[_]&&t&&e.jsx($,{type:"button",variant:"ghost",onClick:()=>g(_,""),children:"Remove"})]})]});return e.jsxs(we,{children:[e.jsxs(Vt,{children:[e.jsxs(Yt,{className:"flex items-center gap-2",children:[e.jsx(Gi,{className:"h-5 w-5"}),"Brokerage Brand"]}),e.jsx(vr,{children:t?"Every agent in this brokerage inherits these colors, logos and disclaimer wherever they leave their own brand blank — including AI-generated marketing through the LevelUp connector.":"These are your brokerage brand settings. Only a brokerage manager can change them."})]}),e.jsx(De,{className:"space-y-6",children:i?e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground text-sm",children:[e.jsx(Jt,{className:"h-4 w-4 animate-spin"})," Loading…"]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"grid gap-4 sm:grid-cols-3",children:[["primary_color","Primary color","#2a4c64"],["secondary_color","Secondary color","#1c1c1c"],["accent_color","Accent color","#B8965A"]].map(([_,j,C])=>e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:j}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(be,{type:"color",className:"h-10 w-14 p-1",disabled:!t,value:o[_]||C,onChange:A=>g(_,A.target.value)}),e.jsx(be,{disabled:!t,value:o[_],placeholder:C,onChange:A=>g(_,A.target.value)})]})]},_))}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-3",children:[v("logo_url","Logo (light background)"),v("logo_dark_url","Logo (dark background)"),v("icon_mark_url","Icon mark")]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Heading font"}),e.jsx(be,{disabled:!t,value:o.heading_font,placeholder:"Playfair Display",onChange:_=>g("heading_font",_.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Body font"}),e.jsx(be,{disabled:!t,value:o.body_font,placeholder:"Inter",onChange:_=>g("body_font",_.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Legal brokerage name"}),e.jsx(be,{disabled:!t,value:o.legal_name,placeholder:"Acme Realty, Inc.",onChange:_=>g("legal_name",_.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Brokerage license #"}),e.jsx(be,{disabled:!t,value:o.license_number,placeholder:"DRE #01234567",onChange:_=>g("license_number",_.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"License state"}),e.jsx(be,{disabled:!t,value:o.license_state,placeholder:"CA",onChange:_=>g("license_state",_.target.value)})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Required disclaimer / compliance line"}),e.jsx(Ls,{disabled:!t,rows:2,value:o.compliance_line,placeholder:"Each office independently owned and operated. Information deemed reliable but not guaranteed.",onChange:_=>g("compliance_line",_.target.value)}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Included in every brand kit so AI-generated marketing carries it automatically."})]}),e.jsx("div",{className:"grid gap-3 sm:grid-cols-2",children:[["show_equal_housing","Include Equal Housing logo"],["show_realtor_logo","Include REALTOR® logo"],["lock_colors","Lock colors (agents cannot override)"],["lock_logo","Lock logo (agents cannot override)"]].map(([_,j])=>e.jsxs("div",{className:"flex items-center justify-between rounded-md border p-3",children:[e.jsx(re,{className:"text-sm font-normal",children:j}),e.jsx(On,{disabled:!t,checked:d[_],onCheckedChange:C=>u(A=>({...A,[_]:C}))})]},_))}),t&&e.jsxs($,{onClick:y,disabled:l.isPending,children:[l.isPending?e.jsx(Jt,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(Ml,{className:"mr-2 h-4 w-4"}),"Save brokerage brand"]})]})})]})}function cbn(){const{user:s,isAdmin:t,isBrokerageManager:n}=ks(),r=Jn(),[a,i]=k.useState(!0),[l,o]=k.useState(null),[c,d]=k.useState(""),[u,h]=k.useState(0),[m,p]=k.useState(!1),[g,x]=k.useState(!1);return k.useEffect(()=>{(async()=>{if(s)try{const{data:v}=await V.from("profiles").select("brokerage_id").eq("id",s.id).maybeSingle();if(!(v!=null&&v.brokerage_id)){i(!1);return}o(v.brokerage_id);const{data:_}=await V.from("brokerages").select("name").eq("id",v.brokerage_id).maybeSingle();_&&d(_.name);const{count:j}=await V.from("profiles").select("id",{count:"exact",head:!0}).eq("brokerage_id",v.brokerage_id);if(h(j||0),t)p(!0),x(!0);else if(n){const{data:C}=await V.from("brokerage_manager_assignments").select("id").eq("user_id",s.id).eq("brokerage_id",v.brokerage_id).maybeSingle();p(!!C),x(!!C)}}catch(v){console.error("Error fetching brokerage info:",v)}finally{i(!1)}})()},[s,t,n]),a?e.jsx(Xs,{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(Xs,{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(Xn,{className:"h-5 w-5 text-primary"}),e.jsxs("span",{className:"font-medium",children:[u," ",u===1?"Agent":"Agents"]})]}),g&&e.jsxs("div",{className:"flex gap-2",children:[e.jsxs($,{variant:"outline",onClick:()=>r("/brokerage-content"),children:[e.jsx(wg,{className:"h-4 w-4 mr-2"}),"Brokerage Content"]}),e.jsxs($,{onClick:()=>r(`/mission-control/listings/new?brokerage=${l}`),children:[e.jsx(ua,{className:"h-4 w-4 mr-2"}),"Add Listing"]})]})]}),e.jsx(lbn,{brokerageId:l,canManage:m}),e.jsx(sbn,{brokerageId:l,canManage:m}),e.jsx(nbn,{brokerageId:l,canManage:m}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-8",children:[e.jsx(abn,{brokerageId:l}),e.jsx(ibn,{brokerageId:l})]})]})}):e.jsx(Xs,{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(Gi,{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 dbn(s){if(!s)return null;try{const t=new URL(s),n=t.hostname.replace("www.","");let r=null;if(n==="youtube.com"||n==="m.youtube.com"?r=t.searchParams.get("v"):n==="youtu.be"&&(r=t.pathname.slice(1)),r)return`https://img.youtube.com/vi/${r}/hqdefault.jpg`}catch{}return null}function ubn(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 _xt={video:{icon:pu,label:"Video",color:"bg-red-500/10 text-red-600 dark:text-red-400"},pdf:{icon:ea,label:"Document",color:"bg-blue-500/10 text-blue-600 dark:text-blue-400"},link:{icon:pd,label:"Link",color:"bg-green-500/10 text-green-600 dark:text-green-400"},event:{icon:ha,label:"Event",color:"bg-purple-500/10 text-purple-600 dark:text-purple-400"},graphic:{icon:gd,label:"Graphic",color:"bg-amber-500/10 text-amber-600 dark:text-amber-400"}};function hbn({item:s,canManage:t}){const[n,r]=k.useState(!1),[a,i]=k.useState(null),l=XAs(),o=Jn(),c=_xt[s.content_type]||_xt.link,d=c.icon,u=k.useMemo(()=>s.thumbnail_url?s.thumbnail_url:s.content_type==="graphic"&&s.file_url?s.file_url:s.content_type==="video"?dbn(s.url):null,[s]);k.useEffect(()=>{u||!s.url||s.content_type!=="video"||!ubn(s.url)||fetch(`https://www.youtube.com/oembed?url=${encodeURIComponent(s.url)}&format=json`).then(g=>g.ok?g.json():null).then(g=>{g!=null&&g.thumbnail_url&&i(g.thumbnail_url)}).catch(()=>{})},[s.url,s.content_type,u]);const h=u||a,m=()=>{o(`/brokerage-content/${s.id}`)},p=async()=>{try{await l.mutateAsync(s.id),ae.success("Content deleted")}catch{ae.error("Failed to delete")}r(!1)};return e.jsxs(e.Fragment,{children:[e.jsxs(we,{className:"group overflow-hidden transition-all duration-200 hover:shadow-lg hover:border-primary/30 cursor-pointer",onClick:m,children:[h?e.jsx("div",{className:"aspect-video bg-muted/50 overflow-hidden",children:e.jsx("img",{src:h,alt:s.title,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-300",referrerPolicy:"no-referrer"})}):e.jsx("div",{className:"aspect-video bg-muted/30 flex items-center justify-center",children:e.jsx(d,{className:"h-12 w-12 text-muted-foreground/30"})}),e.jsx(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(qe,{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(qe,{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:["📅 ",Ys(new Date(s.event_date),"MMM d, yyyy · h:mm a")]}),e.jsxs("p",{className:"text-[10px] text-muted-foreground mt-2",children:["Added ",Ys(new Date(s.created_at),"MMM d, yyyy")]})]}),t&&e.jsxs(Au,{children:[e.jsx(Eu,{asChild:!0,onClick:g=>g.stopPropagation(),children:e.jsx($,{variant:"ghost",size:"icon",className:"h-7 w-7 shrink-0",children:e.jsx(Z0,{className:"h-4 w-4"})})}),e.jsx(gu,{align:"end",children:e.jsxs(Pa,{onClick:g=>{g.stopPropagation(),r(!0)},className:"text-destructive",children:[e.jsx(Un,{className:"h-4 w-4 mr-2"}),"Delete"]})})]})]})})]}),e.jsx(oc,{open:n,onOpenChange:r,children:e.jsxs(Ql,{children:[e.jsxs(Jl,{children:[e.jsx(tc,{children:"Delete Content"}),e.jsxs(sc,{children:['Are you sure you want to delete "',s.title,'"? This cannot be undone.']})]}),e.jsxs(ec,{children:[e.jsx(nc,{children:"Cancel"}),e.jsx(Vl,{onClick:p,className:"bg-destructive text-destructive-foreground",children:"Delete"})]})]})})]})}function mbn(s){try{const t=new URL(s),n=t.hostname.replace("www.","");let r=null;if(n==="youtube.com"||n==="m.youtube.com"?r=t.searchParams.get("v"):n==="youtu.be"&&(r=t.pathname.slice(1)),r)return`https://img.youtube.com/vi/${r}/hqdefault.jpg`}catch{}return null}const wxt=[{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 fbn({brokerageId:s,categories:t}){var le;const{user:n}=ks(),[r,a]=k.useState(!1),[i,l]=k.useState(!1),[o,c]=k.useState(""),[d,u]=k.useState("📁"),[h,m]=k.useState(!1);k.useRef(null);const[p,g]=k.useState("video"),[x,y]=k.useState(""),[v,_]=k.useState(""),[j,C]=k.useState(""),[A,M]=k.useState(""),[I,P]=k.useState(""),[R,O]=k.useState(""),[B,U]=k.useState(""),G=ZAs(),H=QAs(s),Y=JAs(),se=eEs(s),ee=()=>{g("video"),y(""),_(""),C(""),M(""),P(""),O(""),U("")},oe=async(fe,_e)=>{var he;const ve=(he=fe.target.files)==null?void 0:he[0];if(ve){m(!0);try{const Se=ve.name.split(".").pop(),Te=`${s}/${Date.now()}-${Math.random().toString(36).slice(2)}.${Se}`,{error:Ie}=await V.storage.from("brokerage-content").upload(Te,ve);if(Ie)throw Ie;const{data:{publicUrl:Ue}}=V.storage.from("brokerage-content").getPublicUrl(Te);_e==="file"?(M(Ue),p==="graphic"&&!I&&P(Ue)):P(Ue),ae.success("File uploaded")}catch(Se){ae.error(Se.message||"Upload failed")}finally{m(!1)}}},me=async()=>{if(!x.trim()){ae.error("Title is required");return}if(n)try{await G.mutateAsync({brokerage_id:s,category_id:B||null,content_type:p,title:x.trim(),description:v.trim()||null,url:j.trim()||null,file_url:A.trim()||null,thumbnail_url:I.trim()||null,event_date:R?new Date(R).toISOString():null,created_by:n.id}),ae.success("Content added!"),ee(),a(!1)}catch(fe){ae.error(fe.message||"Failed to add content")}},Q=async()=>{if(o.trim())try{await H.mutateAsync({name:o.trim(),icon:d,sort_order:t.length}),c(""),u("📁"),ae.success("Category created")}catch(fe){ae.error(fe.message||"Failed to create category")}},te=async()=>{try{await se.mutateAsync(),ae.success("Default categories created")}catch{ae.error("Failed to create defaults")}};return e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs(zs,{open:r,onOpenChange:a,children:[e.jsx(yl,{asChild:!0,children:e.jsxs($,{children:[e.jsx(nn,{className:"h-4 w-4 mr-2"}),"Add Content"]})}),e.jsxs(Rs,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(Vs,{children:e.jsx($s,{children:"Add Brokerage Content"})}),e.jsxs("div",{className:"space-y-4 mt-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Content Type"}),e.jsxs(bs,{value:p,onValueChange:g,children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsx(vs,{children:wxt.map(fe=>e.jsx(We,{value:fe.value,children:fe.label},fe.value))})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:(le=wxt.find(fe=>fe.value===p))==null?void 0:le.hint})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Category"}),e.jsxs(bs,{value:B,onValueChange:U,children:[e.jsx(ys,{children:e.jsx(_s,{placeholder:"Select category (optional)"})}),e.jsx(vs,{children:t.map(fe=>e.jsxs(We,{value:fe.id,children:[fe.icon," ",fe.name]},fe.id))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Title *"}),e.jsx(be,{value:x,onChange:fe=>y(fe.target.value),placeholder:"Content title"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Description"}),e.jsx(Ls,{value:v,onChange:fe=>_(fe.target.value),placeholder:"Brief description...",rows:2})]}),["video","link","graphic","event"].includes(p)&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:p==="video"?"Video URL":p==="graphic"?"Canva / Image URL":p==="event"?"Event Link (Zoom, etc.)":"URL"}),e.jsx(be,{value:j,onChange:fe=>{const _e=fe.target.value;if(C(_e),p==="video"&&!I){const ve=mbn(_e);ve&&P(ve)}},placeholder:"https://..."})]}),["pdf","graphic"].includes(p)&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:p==="pdf"?"Upload PDF":"Upload Image"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(be,{type:"file",accept:p==="pdf"?".pdf,.doc,.docx":"image/*",onChange:fe=>oe(fe,"file"),disabled:h}),h&&e.jsx(Jt,{className:"h-4 w-4 animate-spin"})]}),A&&e.jsx("p",{className:"text-xs text-green-600",children:"✓ File uploaded"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Thumbnail Image (optional)"}),e.jsx(be,{type:"file",accept:"image/*",onChange:fe=>oe(fe,"thumbnail"),disabled:h}),I&&e.jsxs("div",{className:"relative w-20 h-20 rounded overflow-hidden",children:[e.jsx("img",{src:I,className:"w-full h-full object-cover",alt:"thumb"}),e.jsx("button",{onClick:()=>P(""),className:"absolute top-0 right-0 bg-background/80 rounded-bl p-0.5",children:e.jsx(mr,{className:"h-3 w-3"})})]})]}),p==="event"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Event Date & Time"}),e.jsx(be,{type:"datetime-local",value:R,onChange:fe=>O(fe.target.value)})]}),e.jsxs($,{onClick:me,disabled:G.isPending||!x.trim(),className:"w-full",children:[G.isPending?e.jsx(Jt,{className:"h-4 w-4 animate-spin mr-2"}):e.jsx(nn,{className:"h-4 w-4 mr-2"}),"Add Content"]})]})]})]}),e.jsxs(zs,{open:i,onOpenChange:l,children:[e.jsx(yl,{asChild:!0,children:e.jsxs($,{variant:"outline",size:"sm",children:[e.jsx(Yc,{className:"h-4 w-4 mr-2"}),"Categories"]})}),e.jsxs(Rs,{className:"max-w-md",children:[e.jsx(Vs,{children:e.jsx($s,{children:"Manage Categories"})}),e.jsxs("div",{className:"space-y-4 mt-2",children:[t.length===0&&e.jsxs("div",{className:"text-center py-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground mb-3",children:"No categories yet"}),e.jsxs($,{variant:"outline",size:"sm",onClick:te,disabled:se.isPending,children:[se.isPending?e.jsx(Jt,{className:"h-4 w-4 animate-spin mr-2"}):null,"Create Default Categories"]})]}),t.map(fe=>e.jsxs("div",{className:"flex items-center justify-between p-2 rounded-lg border",children:[e.jsxs("span",{className:"text-sm",children:[fe.icon," ",fe.name]}),!fe.is_default&&e.jsx($,{variant:"ghost",size:"icon",className:"h-7 w-7 text-destructive",onClick:async()=>{await Y.mutateAsync(fe.id),ae.success("Category deleted")},children:e.jsx(mr,{className:"h-4 w-4"})})]},fe.id)),e.jsxs("div",{className:"flex gap-2 pt-2 border-t",children:[e.jsx(be,{value:d,onChange:fe=>u(fe.target.value),className:"w-14 text-center",maxLength:2}),e.jsx(be,{value:o,onChange:fe=>c(fe.target.value),placeholder:"New category name",className:"flex-1",onKeyDown:fe=>fe.key==="Enter"&&Q()}),e.jsx($,{size:"sm",onClick:Q,disabled:!o.trim(),children:"Add"})]})]})]})]})]})}function pbn(){const{user:s,isAdmin:t,isBrokerageManager:n}=ks(),[r,a]=k.useState(!0),[i,l]=k.useState(null),[o,c]=k.useState(""),[d,u]=k.useState(!1),[h,m]=k.useState(null),[p,g]=k.useState("");k.useEffect(()=>{(async()=>{if(s)try{const{data:C}=await V.from("profiles").select("brokerage_id").eq("id",s.id).maybeSingle();if(!(C!=null&&C.brokerage_id)){a(!1);return}l(C.brokerage_id);const{data:A}=await V.from("brokerages").select("name").eq("id",C.brokerage_id).maybeSingle();if(A&&c(A.name),t)u(!0);else if(n){const{data:M}=await V.from("brokerage_manager_assignments").select("id").eq("user_id",s.id).eq("brokerage_id",C.brokerage_id).maybeSingle();u(!!M)}}catch(C){console.error("Error fetching brokerage info:",C)}finally{a(!1)}})()},[s,t,n]);const{data:x=[]}=WAs(i),{data:y=[],isLoading:v}=KAs(i,h),_=k.useMemo(()=>{if(!p.trim())return y;const j=p.toLowerCase();return y.filter(C=>{var A;return C.title.toLowerCase().includes(j)||((A=C.description)==null?void 0:A.toLowerCase().includes(j))||C.content_type.toLowerCase().includes(j)})},[y,p]);return r?e.jsx(Xs,{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(Xs,{title:`${o} Content`,description:"Brokerage Content Hub",children:e.jsxs("div",{className:"space-y-6",children:[d&&i&&e.jsx(fbn,{brokerageId:i,categories:x}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"relative max-w-sm",children:[e.jsx(Yr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search content...",value:p,onChange:j=>g(j.target.value),className:"pl-9"})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx($,{variant:h===null?"default":"outline",size:"sm",onClick:()=>m(null),children:"All"}),x.map(j=>e.jsxs($,{variant:h===j.id?"default":"outline",size:"sm",onClick:()=>m(j.id),children:[e.jsx("span",{className:"mr-1",children:j.icon}),j.name]},j.id))]})]}),v?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):_.length===0?e.jsx(we,{className:"bg-muted/30 border-dashed",children:e.jsxs(De,{className:"flex flex-col items-center justify-center py-12",children:[e.jsx(d1,{className:"h-12 w-12 text-muted-foreground/50 mb-3"}),e.jsx("p",{className:"text-muted-foreground font-medium",children:p.trim()?"No matching content found":"No content yet"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:p.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:_.map(j=>e.jsx(hbn,{item:j,canManage:d},j.id))})]})}):e.jsx(Xs,{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(Gi,{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 jxt={video:{icon:pu,label:"Video",color:"bg-red-500/10 text-red-600 dark:text-red-400"},pdf:{icon:ea,label:"Document",color:"bg-blue-500/10 text-blue-600 dark:text-blue-400"},link:{icon:pd,label:"Link",color:"bg-green-500/10 text-green-600 dark:text-green-400"},event:{icon:ha,label:"Event",color:"bg-purple-500/10 text-purple-600 dark:text-purple-400"},graphic:{icon:gd,label:"Graphic",color:"bg-amber-500/10 text-amber-600 dark:text-amber-400"}};function gbn(s){try{const t=new URL(s),n=t.hostname.replace("www.","");if(t.pathname==="/playlist"){const r=t.searchParams.get("list");if(r)return`https://www.youtube.com/embed/videoseries?list=${r}`}if(n==="youtube.com"||n==="m.youtube.com"){const r=t.searchParams.get("v");if(r){const a=t.searchParams.get("list");let i=`https://www.youtube.com/embed/${r}`;return a&&(i+=`?list=${a}`),i}}if(n==="youtu.be"){const r=t.pathname.slice(1);if(r){const a=t.searchParams.get("list");let i=`https://www.youtube.com/embed/${r}`;return a&&(i+=`?list=${a}`),i}}if(n==="youtube.com"&&t.pathname.startsWith("/embed/"))return s}catch{}return null}function xbn(s){try{const t=new URL(s).hostname.replace("www.","");return["youtube.com","youtu.be","m.youtube.com"].includes(t)}catch{return!1}}function ybn(s){try{return new URL(s).hostname.includes("vimeo.com")}catch{return!1}}function vbn(s){try{const t=s.match(/vimeo\.com\/(\d+)/);if(t)return`https://player.vimeo.com/video/${t[1]}`}catch{}return null}function bbn(){const{contentId:s}=oo(),{data:t,isLoading:n}=pt({queryKey:["brokerage-content-detail",s],queryFn:async()=>{const{data:d,error:u}=await V.from("brokerage_content").select(` *, category:brokerage_content_categories(*) `).eq("id",s).single();if(u)throw u;return d},enabled:!!s});if(n)return e.jsx(Xs,{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(Xs,{title:"Brokerage Content",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Gi,{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($,{asChild:!0,className:"mt-4",children:e.jsx(nr,{to:"/brokerage-content",children:"Back to Content"})})]})});const r=jxt[t.content_type]||jxt.link,a=r.icon,i=t.url||t.file_url,l=i&&xbn(i)?gbn(i):null,o=i&&ybn(i)?vbn(i):null,c=l||o;return e.jsx(Xs,{title:t.title,children:e.jsxs("div",{className:"space-y-6 max-w-4xl mx-auto",children:[e.jsx($,{variant:"ghost",size:"sm",asChild:!0,className:"gap-2",children:e.jsxs(nr,{to:"/brokerage-content",children:[e.jsx(Ia,{className:"h-4 w-4"}),"Back to Content"]})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(qe,{variant:"secondary",className:`text-xs px-2 py-0.5 ${r.color}`,children:[e.jsx(a,{className:"h-3 w-3 mr-1"}),r.label]}),t.category&&e.jsxs(qe,{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 ",Ys(new Date(t.created_at),"MMMM d, yyyy")]})]}),e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:t.title}),c&&e.jsx(we,{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(we,{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(we,{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(we,{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(we,{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(ha,{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:Ys(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($,{asChild:!0,size:"lg",children:e.jsxs("a",{href:t.file_url,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(ji,{className:"h-4 w-4 mr-2"}),t.content_type==="pdf"?"Download Document":"Download File"]})}),t.url&&e.jsx($,{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(Ir,{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 C4e={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 _bn(s="open"){const{user:t}=ks();return pt({queryKey:["brokerage-help-requests",s,t==null?void 0:t.id],queryFn:async()=>{if(!t)return[];let n=V.from("brokerage_help_requests").select("*, requester:profiles!brokerage_help_requests_requester_user_id_fkey(name, email, avatar_url)").order("created_at",{ascending:!1});if(s==="open")n=n.eq("status","open");else if(s==="mine")n=n.eq("requester_user_id",t.id);else if(s==="filled")n=n.in("status",["filled","completed"]);else if(s==="my_claims"){const{data:i}=await V.from("brokerage_help_claims").select("request_id").eq("claimant_user_id",t.id),l=(i||[]).map(o=>o.request_id);if(l.length===0)return[];n=n.in("id",l)}const{data:r,error:a}=await n;if(a)throw a;return r},enabled:!!t})}function wbn(s){return pt({queryKey:["brokerage-help-request",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await V.from("brokerage_help_requests").select("*, requester:profiles!brokerage_help_requests_requester_user_id_fkey(name, email, phone, avatar_url)").eq("id",s).single();if(n)throw n;return t},enabled:!!s})}function jbn(s){return pt({queryKey:["brokerage-help-claims",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await V.from("brokerage_help_claims").select("*, claimant:profiles!brokerage_help_claims_claimant_user_id_fkey(name, email, phone, avatar_url)").eq("request_id",s).order("created_at",{ascending:!0});if(n)throw n;return t},enabled:!!s})}function Nbn(){const s=ls(),{user:t,brokerageId:n}=ks();return Nt({mutationFn:async r=>{if(!t||!n)throw new Error("You must be in a brokerage to post.");const{data:a,error:i}=await V.from("brokerage_help_requests").insert({...r,brokerage_id:n,requester_user_id:t.id}).select().single();if(i)throw i;try{await V.functions.invoke("brokerage-help-notify",{body:{request_id:a.id}})}catch(l){console.warn("notify failed (non-blocking):",l)}return a},onSuccess:()=>{s.invalidateQueries({queryKey:["brokerage-help-requests"]})}})}function kbn(){const s=ls(),{user:t}=ks();return Nt({mutationFn:async({request_id:n,note:r})=>{if(!t)throw new Error("Not signed in");const{data:a,error:i}=await V.from("brokerage_help_claims").insert({request_id:n,claimant_user_id:t.id,note:r}).select().single();if(i)throw i;return a},onSuccess:(n,r)=>{s.invalidateQueries({queryKey:["brokerage-help-claims",r.request_id]}),s.invalidateQueries({queryKey:["brokerage-help-requests"]})}})}function Sbn(){const s=ls();return Nt({mutationFn:async({claim_id:t,request_id:n,claimant_user_id:r})=>{const{error:a}=await V.from("brokerage_help_claims").update({status:"accepted",responded_at:new Date().toISOString()}).eq("id",t);if(a)throw a;const{error:i}=await V.from("brokerage_help_requests").update({status:"filled",assigned_user_id:r}).eq("id",n);if(i)throw i;try{await V.functions.invoke("brokerage-help-claim-decision",{body:{claim_id:t}})}catch(l){console.warn("claim decision notify failed:",l)}},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["brokerage-help-claims",n.request_id]}),s.invalidateQueries({queryKey:["brokerage-help-request",n.request_id]}),s.invalidateQueries({queryKey:["brokerage-help-requests"]})}})}function Cbn(){const s=ls();return Nt({mutationFn:async({claim_id:t})=>{const{error:n}=await V.from("brokerage_help_claims").update({status:"declined",responded_at:new Date().toISOString()}).eq("id",t);if(n)throw n},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["brokerage-help-claims",n.request_id]})}})}function Abn(){const s=ls();return Nt({mutationFn:async t=>{const{error:n}=await V.from("brokerage_help_requests").update({status:"cancelled"}).eq("id",t);if(n)throw n},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["brokerage-help-requests"]}),s.invalidateQueries({queryKey:["brokerage-help-request",n]})}})}function Ebn(){const s=ls();return Nt({mutationFn:async t=>{const{error:n}=await V.from("brokerage_help_requests").update({status:"completed"}).eq("id",t);if(n)throw n},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["brokerage-help-requests"]}),s.invalidateQueries({queryKey:["brokerage-help-request",n]})}})}function Tbn(){const{user:s,brokerageId:t}=ks(),n=ls(),r=pt({queryKey:["brokerage-help-prefs",s==null?void 0:s.id,t],queryFn:async()=>{if(!s||!t)return null;const{data:i,error:l}=await V.from("brokerage_help_notification_prefs").select("*").eq("user_id",s.id).eq("brokerage_id",t).maybeSingle();if(l)throw l;return i},enabled:!!s&&!!t}),a=Nt({mutationFn:async i=>{if(!s||!t)throw new Error("No user/brokerage");const{error:l}=await V.from("brokerage_help_notification_prefs").upsert({user_id:s.id,brokerage_id:t,email_enabled:i},{onConflict:"user_id,brokerage_id"});if(l)throw l},onSuccess:()=>{n.invalidateQueries({queryKey:["brokerage-help-prefs"]})}});return{...r,setEmailEnabled:a.mutate,isSaving:a.isPending}}function Mbn(s,t){if(!s)return null;const n=(a,i)=>new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",...i}).format(new Date(a)),r=n(s,{weekday:"short",month:"short",day:"numeric",hour:"numeric",minute:"2-digit"});if(t){const a=n(t,{hour:"numeric",minute:"2-digit"});return`${r} – ${a} ET`}return`${r} ET`}function Pbn(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 Ibn({req:s,onClick:t}){var i;const n=C4e[s.request_type],r=Mbn(s.event_start_at,s.event_end_at),a=[s.address,s.city,s.state].filter(Boolean).join(", ");return e.jsx(we,{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(qe,{variant:"secondary",className:"text-xs",children:[n.emoji," ",n.label]}),s.status!=="open"&&e.jsx(qe,{variant:"outline",className:"text-xs capitalize",children:s.status})]}),e.jsx(fi,{className:"h-4 w-4 text-muted-foreground group-hover:translate-x-0.5 transition"})]}),e.jsx("h3",{className:"font-semibold text-base mb-2 line-clamp-2",children:s.title}),e.jsxs("div",{className:"space-y-1.5 text-sm text-muted-foreground",children:[r&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(sa,{className:"h-3.5 w-3.5 shrink-0"}),e.jsx("span",{children:r})]}),a&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Si,{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(Su,{className:"h-3.5 w-3.5 shrink-0"}),e.jsx("span",{children:Pbn(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 Lbn(){var c;const s=Jn(),{brokerageId:t}=ks(),[n,r]=k.useState("open"),{data:a=[],isLoading:i}=_bn(n),l=Tbn(),o=((c=l.data)==null?void 0:c.email_enabled)??!0;return t?e.jsx(Xs,{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(ya,{value:n,onValueChange:d=>r(d),children:e.jsxs(va,{children:[e.jsx(is,{value:"open",children:"Open"}),e.jsx(is,{value:"mine",children:"My Posts"}),e.jsx(is,{value:"my_claims",children:"My Claims"}),e.jsx(is,{value:"filled",children:"Filled"})]})}),e.jsxs($,{onClick:()=>s("/brokerage/help-board/new"),className:"gap-2",children:[e.jsx(nn,{className:"h-4 w-4"})," Post Request"]})]}),e.jsx(we,{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(Fx,{className:"h-4 w-4 text-primary"}):e.jsx(k5,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx(re,{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(On,{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(we,{className:"bg-muted/30 border-dashed",children:e.jsxs(De,{className:"flex flex-col items-center justify-center py-12",children:[e.jsx(n5,{className:"h-12 w-12 text-muted-foreground/50 mb-3"}),e.jsx("p",{className:"font-medium",children:"Nothing here yet"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:n==="open"?"No open requests right now — be the first to post one!":"Check back later."})]})}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:a.map(d=>e.jsx(Ibn,{req:d,onClick:()=>s(`/brokerage/help-board/${d.id}`)},d.id))})]})}):e.jsx(Xs,{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(n5,{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 Rbn(){const s=Jn(),{toast:t}=Fi(),n=Nbn(),[r,a]=k.useState("open_house"),[i,l]=k.useState(""),[o,c]=k.useState(""),[d,u]=k.useState(""),[h,m]=k.useState(""),[p,g]=k.useState(""),[x,y]=k.useState(""),[v,_]=k.useState(""),[j,C]=k.useState(""),[A,M]=k.useState(""),[I,P]=k.useState(""),[R,O]=k.useState("goodwill"),[B,U]=k.useState(""),[G,H]=k.useState(""),Y=r==="open_house"||r==="showing_coverage",se=r!=="general",ee=(me,Q)=>!me||!Q?null:`${me}T${Q}:00`,oe=async me=>{if(me.preventDefault(),!i.trim()){t({title:"Add a title",description:"Tell teammates what you need help with.",variant:"destructive"});return}try{const Q=ee(d,h),te=ee(d,p);await n.mutateAsync({request_type:r,title:i.trim(),description:o.trim()||null,event_start_at:Q,event_end_at:te,address:Y&&x.trim()||null,city:Y&&v.trim()||null,state:Y&&j.trim()||null,zip:Y&&A.trim()||null,mls_number:I.trim()||null,compensation_type:R,compensation_amount:B?Number(B):null,compensation_notes:G.trim()||null}),t({title:"Posted!",description:"Your teammates have been notified."}),s("/brokerage/help-board")}catch(Q){t({title:"Could not post",description:(Q==null?void 0:Q.message)??"Something went wrong.",variant:"destructive"})}};return e.jsx(Xs,{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($,{variant:"ghost",size:"sm",onClick:()=>s("/brokerage/help-board"),className:"mb-4 gap-2",children:[e.jsx(Ia,{className:"h-4 w-4"})," Back to board"]}),e.jsx("form",{onSubmit:oe,children:e.jsx(we,{children:e.jsxs(De,{className:"p-6 space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"What do you need help with?"}),e.jsx("div",{className:"grid grid-cols-2 gap-2",children:Object.keys(C4e).map(me=>{const Q=C4e[me],te=me===r;return e.jsxs("button",{type:"button",onClick:()=>a(me),className:`text-left p-3 rounded-lg border-2 transition ${te?"border-primary bg-primary/5":"border-border hover:border-primary/40"}`,children:[e.jsx("div",{className:"text-lg",children:Q.emoji}),e.jsx("div",{className:"font-medium text-sm mt-1",children:Q.label}),e.jsx("div",{className:"text-xs text-muted-foreground line-clamp-1",children:Q.description})]},me)})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"title",children:"Title *"}),e.jsx(be,{id:"title",value:i,onChange:me=>l(me.target.value),placeholder:r==="open_house"?"Open house at 123 Oak St — Sat 1-3pm":"Quick description",maxLength:120,required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"description",children:"Details"}),e.jsx(Ls,{id:"description",value:o,onChange:me=>c(me.target.value),placeholder:"Any context — lockbox code instructions later, what to expect, etc.",rows:3,maxLength:1e3})]}),se&&e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"date",children:"Date"}),e.jsx(be,{id:"date",type:"date",value:d,onChange:me=>u(me.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"start",children:"Start"}),e.jsx(be,{id:"start",type:"time",value:h,onChange:me=>m(me.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"end",children:"End"}),e.jsx(be,{id:"end",type:"time",value:p,onChange:me=>g(me.target.value)})]})]}),Y&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"address",children:"Address"}),e.jsx(be,{id:"address",value:x,onChange:me=>y(me.target.value),placeholder:"123 Oak St"})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:"space-y-2 col-span-2",children:[e.jsx(re,{htmlFor:"city",children:"City"}),e.jsx(be,{id:"city",value:v,onChange:me=>_(me.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"state",children:"State"}),e.jsx(be,{id:"state",value:j,onChange:me=>C(me.target.value.toUpperCase()),maxLength:2})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"zip",children:"Zip"}),e.jsx(be,{id:"zip",value:A,onChange:me=>M(me.target.value),maxLength:10})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"mls",children:"MLS # (optional)"}),e.jsx(be,{id:"mls",value:I,onChange:me=>P(me.target.value)})]})]})]}),e.jsxs("div",{className:"space-y-3 pt-2 border-t",children:[e.jsx(re,{children:"Compensation"}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-2",children:[{val:"goodwill",label:"Goodwill",sub:"Pay it forward"},{val:"flat_fee",label:"Flat Fee",sub:"Dollar amount"},{val:"referral_percent",label:"Referral %",sub:"On the deal"}].map(me=>{const Q=R===me.val;return e.jsxs("button",{type:"button",onClick:()=>O(me.val),className:`text-left p-3 rounded-lg border-2 transition ${Q?"border-primary bg-primary/5":"border-border hover:border-primary/40"}`,children:[e.jsx("div",{className:"font-medium text-sm",children:me.label}),e.jsx("div",{className:"text-xs text-muted-foreground",children:me.sub})]},me.val)})}),R!=="goodwill"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"amount",children:R==="flat_fee"?"Amount ($)":"Percent (%)"}),e.jsx(be,{id:"amount",type:"number",min:"0",step:R==="referral_percent"?"1":"5",value:B,onChange:me=>U(me.target.value),placeholder:R==="flat_fee"?"100":"25"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"comp-notes",children:"Compensation notes"}),e.jsx(be,{id:"comp-notes",value:G,onChange:me=>H(me.target.value),placeholder:"e.g. Venmo same day, or split any leads",maxLength:200})]})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx($,{type:"button",variant:"ghost",onClick:()=>s("/brokerage/help-board"),children:"Cancel"}),e.jsxs($,{type:"submit",disabled:n.isPending,className:"gap-2",children:[n.isPending&&e.jsx(Jt,{className:"h-4 w-4 animate-spin"}),"Post & Notify Brokerage"]})]})]})})})]})})}function Dbn(s,t){if(!s)return null;const n=(a,i)=>new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",...i}).format(new Date(a)),r=n(s,{weekday:"long",month:"long",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit"});return t?`${r} – ${n(t,{hour:"numeric",minute:"2-digit"})} ET`:`${r} ET`}function DRe(s){return s?s.split(" ").map(t=>t[0]).slice(0,2).join("").toUpperCase():"?"}function Obn(){var I,P,R,O,B,U,G,H;const{id:s}=oo(),t=Jn(),{user:n}=ks(),{toast:r}=Fi(),{data:a,isLoading:i}=wbn(s),{data:l=[]}=jbn(s),o=kbn(),c=Sbn(),d=Cbn(),u=Abn(),h=Ebn(),[m,p]=k.useState("");if(i)return e.jsx(Xs,{title:"Loading...",description:"",children:e.jsx("div",{className:"flex items-center justify-center py-16",children:e.jsx(Jt,{className:"h-8 w-8 animate-spin text-primary"})})});if(!a)return e.jsxs(Xs,{title:"Not Found",description:"",children:[e.jsxs($,{variant:"ghost",onClick:()=>t("/brokerage/help-board"),className:"gap-2",children:[e.jsx(Ia,{className:"h-4 w-4"})," Back to board"]}),e.jsx("p",{className:"mt-4 text-muted-foreground",children:"Request not found or you don't have access."})]});const g=C4e[a.request_type],x=Dbn(a.event_start_at,a.event_end_at),y=[a.address,a.city,a.state,a.zip].filter(Boolean).join(", "),v=(n==null?void 0:n.id)===a.requester_user_id,_=l.find(Y=>Y.claimant_user_id===(n==null?void 0:n.id)),j=l.find(Y=>Y.status==="accepted"),C=a.status==="open",A=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)",M=async()=>{if(!m.trim()){r({title:"Add a quick note",description:"Let the requester know you're available."});return}try{await o.mutateAsync({request_id:a.id,note:m.trim()}),r({title:"You're in!",description:"The requester will review and pick someone."}),p("")}catch(Y){r({title:"Could not submit",description:Y==null?void 0:Y.message,variant:"destructive"})}};return e.jsx(Xs,{title:a.title,description:`${g.emoji} ${g.label}`,children:e.jsxs("div",{className:"max-w-3xl mx-auto space-y-4",children:[e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>t("/brokerage/help-board"),className:"gap-2",children:[e.jsx(Ia,{className:"h-4 w-4"})," Back to board"]}),e.jsx(we,{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(qe,{variant:"secondary",children:[g.emoji," ",g.label]}),e.jsx(qe,{variant:C?"default":"outline",className:"capitalize",children:a.status})]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsxs(Wa,{className:"h-7 w-7",children:[e.jsx(eo,{src:((I=a.requester)==null?void 0:I.avatar_url)||void 0}),e.jsx(Ka,{children:DRe((P=a.requester)==null?void 0:P.name)})]}),e.jsx("span",{children:((R=a.requester)==null?void 0:R.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:[x&&e.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[e.jsx(sa,{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:x})]})]}),y&&e.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[e.jsx(Si,{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:y})]})]}),e.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[e.jsx(Su,{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:A})]})]}),a.mls_number&&e.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[e.jsx(VT,{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]})]})}),!v&&C&&!_&&e.jsx(we,{children:e.jsxs(De,{className:"p-6 space-y-3",children:[e.jsx("h3",{className:"font-semibold",children:"Offer to cover this"}),e.jsx(Ls,{placeholder:"Quick note — e.g. 'I'm 10 min away and free that day'",value:m,onChange:Y=>p(Y.target.value),rows:3,maxLength:400}),e.jsxs($,{onClick:M,disabled:o.isPending,className:"gap-2",children:[o.isPending&&e.jsx(Jt,{className:"h-4 w-4 animate-spin"}),"I can cover this"]})]})}),!v&&_&&e.jsx(we,{className:"border-primary/30 bg-primary/5",children:e.jsxs(De,{className:"p-4 flex items-center gap-3",children:[e.jsx(ma,{className:"h-5 w-5 text-primary"}),e.jsxs("div",{className:"text-sm",children:[e.jsxs("div",{className:"font-medium capitalize",children:["Your offer: ",_.status]}),e.jsxs("div",{className:"text-muted-foreground",children:[_.status==="pending"&&"Waiting for the requester to pick.",_.status==="accepted"&&"You're confirmed — see contact info below.",_.status==="declined"&&"They went with someone else this time."]})]})]})}),j&&(v||j.claimant_user_id===(n==null?void 0:n.id))&&e.jsx(we,{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(Wa,{className:"h-10 w-10",children:[e.jsx(eo,{src:((O=j.claimant)==null?void 0:O.avatar_url)||void 0}),e.jsx(Ka,{children:DRe((B=j.claimant)==null?void 0:B.name)})]}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:(U=j.claimant)==null?void 0:U.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:[((G=j.claimant)==null?void 0:G.email)&&e.jsxs("a",{href:`mailto:${j.claimant.email}`,className:"flex items-center gap-2 text-primary hover:underline",children:[e.jsx(pn,{className:"h-4 w-4"})," ",j.claimant.email]}),((H=j.claimant)==null?void 0:H.phone)&&e.jsxs("a",{href:`tel:${j.claimant.phone}`,className:"flex items-center gap-2 text-primary hover:underline",children:[e.jsx(ka,{className:"h-4 w-4"})," ",j.claimant.phone]})]})]})}),v&&e.jsx(we,{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(Y=>{var se,ee,oe,me,Q;return e.jsxs("div",{className:"flex items-start gap-3 p-3 rounded-lg border",children:[e.jsxs(Wa,{className:"h-10 w-10",children:[e.jsx(eo,{src:((se=Y.claimant)==null?void 0:se.avatar_url)||void 0}),e.jsx(Ka,{children:DRe((ee=Y.claimant)==null?void 0:ee.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:((oe=Y.claimant)==null?void 0:oe.name)||"Teammate"}),e.jsx(qe,{variant:"outline",className:"capitalize text-xs",children:Y.status})]}),Y.note&&e.jsxs("p",{className:"text-sm text-muted-foreground mt-1",children:['"',Y.note,'"']}),Y.status==="pending"&&C&&e.jsxs("div",{className:"flex gap-2 mt-2",children:[e.jsxs($,{size:"sm",onClick:()=>c.mutate({claim_id:Y.id,request_id:a.id,claimant_user_id:Y.claimant_user_id}),disabled:c.isPending,className:"gap-1",children:[e.jsx(ma,{className:"h-3.5 w-3.5"})," Pick ",((Q=(me=Y.claimant)==null?void 0:me.name)==null?void 0:Q.split(" ")[0])||"them"]}),e.jsxs($,{size:"sm",variant:"ghost",onClick:()=>d.mutate({claim_id:Y.id,request_id:a.id}),disabled:d.isPending,className:"gap-1",children:[e.jsx(mr,{className:"h-3.5 w-3.5"})," Pass"]})]})]})]},Y.id)}),v&&C&&e.jsx("div",{className:"pt-3 border-t flex justify-end",children:e.jsx($,{variant:"ghost",size:"sm",onClick:()=>u.mutate(a.id),disabled:u.isPending,children:"Cancel request"})}),v&&a.status==="filled"&&e.jsx("div",{className:"pt-3 border-t flex justify-end",children:e.jsx($,{size:"sm",onClick:()=>h.mutate(a.id),disabled:h.isPending,children:"Mark complete"})})]})})]})})}function HFt({onSelect:s,maxHeight:t="460px"}){const[n,r]=k.useState(""),[a,i]=k.useState("all"),{data:l=[],isLoading:o}=pt({queryKey:["newsletter-graphics-picker"],queryFn:async()=>{const{data:u,error:h}=await V.from("newsletter_graphics").select("*").eq("is_active",!0).order("is_featured",{ascending:!1}).order("sort_order",{ascending:!0}).order("created_at",{ascending:!1});if(h)throw h;return u||[]}}),c=k.useMemo(()=>{const u=new Set;return l.forEach(h=>u.add(h.category||"general")),["all",...Array.from(u).sort()]},[l]),d=k.useMemo(()=>{const u=n.trim().toLowerCase();return l.filter(h=>a!=="all"&&h.category!==a?!1:u?h.title.toLowerCase().includes(u)||(h.description||"").toLowerCase().includes(u)||(h.tags||[]).some(m=>m.toLowerCase().includes(u)):!0)},[l,n,a]);return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Yr,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(be,{value:n,onChange:u=>r(u.target.value),placeholder:"Search graphics...",className:"pl-8 h-9"})]}),c.length>1&&e.jsx("div",{className:"flex flex-wrap gap-1.5",children:c.map(u=>e.jsx("button",{onClick:()=>i(u),className:`px-2.5 py-1 rounded-full text-xs font-medium transition-colors ${a===u?"bg-primary text-primary-foreground":"bg-muted hover:bg-muted/70 text-muted-foreground"}`,children:u==="all"?"All":u},u))}),e.jsx(Eo,{style:{maxHeight:t},className:"rounded-md border",children:o?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(Jt,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):d.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(zc,{className:"h-8 w-8 text-muted-foreground/50 mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:l.length===0?"No graphics available yet":"No graphics match your search"})]}):e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-2 p-2",children:d.map(u=>e.jsxs("button",{onClick:()=>s(u),className:"group relative rounded-md overflow-hidden border bg-muted/30 hover:ring-2 hover:ring-primary hover:border-primary transition-all text-left",title:u.title,children:[e.jsx("div",{className:"aspect-video bg-muted overflow-hidden",children:e.jsx("img",{src:u.thumbnail_url||u.image_url,alt:u.title,loading:"lazy",className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-200"})}),u.is_featured&&e.jsxs(qe,{className:"absolute top-1 left-1 h-5 px-1.5 gap-0.5 text-[10px] bg-amber-500 hover:bg-amber-500 text-white border-0",children:[e.jsx(ri,{className:"h-2.5 w-2.5 fill-current"}),"Featured"]}),e.jsxs("div",{className:"p-1.5 bg-background",children:[e.jsx("p",{className:"text-xs font-medium truncate",children:u.title}),e.jsx("p",{className:"text-[10px] text-muted-foreground truncate",children:u.category})]})]},u.id))})}),e.jsxs("p",{className:"text-xs text-muted-foreground text-center",children:[d.length," graphic",d.length===1?"":"s",a!=="all"?` in ${a}`:""]})]})}const Fbn=[{key:"search",label:"Search for Properties",icon:Yr,defaultText:"Search for Properties",placeholder:"https://your-website.com/search",helper:"Link to your home search page"},{key:"call",label:"Call Agent",icon:ka,defaultText:"Call Me",hrefPrefix:"tel:",placeholder:"+15555551234",helper:"Your phone number"},{key:"email",label:"Email Agent",icon:pn,defaultText:"Email Me",hrefPrefix:"mailto:",placeholder:"you@email.com",helper:"Your email address"},{key:"schedule",label:"Schedule a Call",icon:ha,defaultText:"Schedule a Call",placeholder:"https://calendly.com/you",helper:"Link to your booking page"},{key:"listings",label:"View My Listings",icon:ua,defaultText:"View My Listings",placeholder:"https://your-website.com/listings",helper:"Link to your listings page"},{key:"valuation",label:"Get Home Value",icon:Su,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:Si,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:ou,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:rh,defaultText:"Learn More",placeholder:"https://...",helper:"Any link you want"}];function Nxt(s){const t=s.match(/(?:youtube\.com\/(?:watch\?v=|embed\/|v\/)|youtu\.be\/)([A-Za-z0-9_-]{11})/);return t?t[1]:null}function zbn(s){const t=s.match(/vimeo\.com\/(?:video\/)?(\d+)/);return t?t[1]:null}function GFt({html:s,onChange:t}){const{user:n}=ks(),r=k.useRef(null),a=k.useRef(""),i=k.useRef(t);i.current=t;const[l,o]=k.useState("desktop"),c=k.useRef(null),[d,u]=k.useState(!1),[h,m]=k.useState(""),[p,g]=k.useState(""),x=k.useRef(null),y=()=>{var gt;const dt=(gt=r.current)==null?void 0:gt.contentDocument,jt=dt==null?void 0:dt.getSelection();jt&&jt.rangeCount>0&&(dt!=null&&dt.body.contains(jt.anchorNode))&&(x.current=jt.getRangeAt(0).cloneRange())},v=()=>{var us;const dt=c.current,jt=(us=r.current)==null?void 0:us.contentDocument;if(!dt||!jt)return;let gt=h.trim();gt&&!/^(https?:|mailto:|tel:|#|\/)/i.test(gt)&&(gt="https://"+gt),dt.setAttribute("href",gt),dt.setAttribute("target","_blank");const rs=p.trim();rs&&rs!==(dt.textContent||"").trim()&&(dt.textContent=rs);const Ns=` `+jt.documentElement.outerHTML;a.current=Ns,i.current(Ns),u(!1)};k.useEffect(()=>{var gt,rs;const dt=r.current;if(!dt||a.current===s)return;const jt=()=>{const Ns=dt.contentDocument;if(!Ns)return;Ns.open(),Ns.write(s||""),Ns.close(),a.current=s;const us=Ns.body;if(!us)return;us.setAttribute("contenteditable","true"),us.style.outline="none",us.style.minHeight="400px",us.style.cursor="text";const Bs=()=>{const Fn=` `+Ns.documentElement.outerHTML;a.current=Fn,i.current(Fn)};us.addEventListener("input",Bs),us.addEventListener("blur",Bs),us.addEventListener("mouseup",y),us.addEventListener("keyup",y),Ns.addEventListener("selectionchange",y);const Ts=Fn=>{var Ln;const An=Fn.target,js=An==null?void 0:An.closest("a");if(js){if(Fn.metaKey||Fn.ctrlKey||Fn.shiftKey)return;Fn.preventDefault(),Fn.stopPropagation(),c.current=js,m(js.getAttribute("href")||""),g((js.textContent||"").trim()),u(!0);return}const In=Ns.getSelection();if(!In)return;const un=(Ln=Ns.caretRangeFromPoint)==null?void 0:Ln.call(Ns,Fn.clientX,Fn.clientY),jr=un==null?void 0:un.startContainer;if(jr&&jr.nodeType===Node.TEXT_NODE){const Sr=jr.textContent||"",Qn=un.startOffset,En=Sr.lastIndexOf("[",Qn),pr=Sr.indexOf("]",Qn);if(En!==-1&&pr!==-1&&pr>En){const xn=Ns.createRange();xn.setStart(jr,En),xn.setEnd(jr,pr+1),In.removeAllRanges(),In.addRange(xn),x.current=xn.cloneRange()}}};us.addEventListener("click",Ts,!0)};((gt=dt.contentDocument)==null?void 0:gt.readyState)==="complete"||(rs=dt.contentDocument)!=null&&rs.body?jt():dt.addEventListener("load",jt,{once:!0})},[s]);const _=(dt,jt)=>{var Ns;const gt=(Ns=r.current)==null?void 0:Ns.contentDocument;if(!gt)return;gt.body.focus(),gt.execCommand(dt,!1,jt);const rs=` `+gt.documentElement.outerHTML;a.current=rs,i.current(rs)},j=()=>{const dt=window.prompt("Enter URL (https://...)");dt&&_("createLink",dt)},C=(dt,jt)=>{var Ns;const gt=(Ns=r.current)==null?void 0:Ns.contentDocument;if(!gt)return;if(gt.body.focus(),jt==="cursor"&&x.current&>.body.contains(x.current.startContainer)){const us=gt.getSelection();if(us){us.removeAllRanges(),us.addRange(x.current),gt.execCommand("insertHTML",!1,dt);const Bs=` `+gt.documentElement.outerHTML;a.current=Bs,i.current(Bs);return}}jt==="top"?gt.body.insertAdjacentHTML("afterbegin",dt):gt.body.insertAdjacentHTML("beforeend",dt);const rs=` `+gt.documentElement.outerHTML;a.current=rs,i.current(rs)},[A,M]=k.useState(!1),[I,P]=k.useState(null),[R,O]=k.useState(""),[B,U]=k.useState(""),[G,H]=k.useState("#406E71"),[Y,se]=k.useState("cursor"),ee=dt=>{P(dt),O(dt.defaultText),U(""),M(!0)},oe=()=>{if(!I)return;const dt=B.trim();if(!I.isForward&&!dt)return;let jt=dt;if(I.isForward){const us=dt||"",Bs=encodeURIComponent("You should see this newsletter"),Ts=encodeURIComponent(us?`I thought you'd like this — take a look: ${us} `:`I thought you'd like this newsletter — take a look! `);jt=`mailto:?subject=${Bs}&body=${Ts}`}else I.hrefPrefix==="tel:"?jt="tel:"+dt.replace(/[^0-9+]/g,""):I.hrefPrefix==="mailto:"?jt="mailto:"+dt:/^https?:\/\//i.test(dt)||(jt="https://"+dt);const gt=(R||I.defaultText).replace(/[<>]/g,""),rs=G||"#406E71",Ns=`
${gt}

 

`;C(Ns,Y),M(!1)},[me,Q]=k.useState(!1),[te,le]=k.useState(""),[fe,_e]=k.useState(""),[ve,he]=k.useState(""),[Se,Te]=k.useState("cursor"),Ie=(()=>{if(fe.trim())return fe.trim();const dt=Nxt(te);return dt?`https://i.ytimg.com/vi/${dt}/hqdefault.jpg`:""})(),Ue=()=>{le(""),_e(""),he(""),Q(!0)},Be=()=>{const dt=te.trim();if(!dt)return;let jt=dt;/^https?:\/\//i.test(jt)||(jt="https://"+jt);const gt=Nxt(jt),rs=gt?null:zbn(jt);let Ns=fe.trim();!Ns&>&&(Ns=`https://i.ytimg.com/vi/${gt}/hqdefault.jpg`),!Ns&&rs&&(Ns=`https://vumbnail.com/${rs}.jpg`),Ns||(Ns="https://placehold.co/600x340/406E71/ffffff?text=Watch+Video");const us=(ve||"Watch the video").replace(/[<>]/g,""),Bs=`
${us}
▶ ${us}

 

`.trim();C(Bs,Se),Q(!1)},[je,Ye]=k.useState(!1),[Ee,Re]=k.useState(""),[ke,Fe]=k.useState(""),[Oe,Ge]=k.useState("full"),[yt,tt]=k.useState("cursor"),[ut,nt]=k.useState(!1),et=k.useRef(null),at=()=>{Re(""),Fe(""),Ge("full"),Ye(!0)},wt=async dt=>{var jt;if(!n){ae.error("You must be signed in to upload images");return}if(dt.size>10*1024*1024){ae.error("Image must be under 10MB");return}nt(!0);try{const gt=((jt=dt.name.split(".").pop())==null?void 0:jt.toLowerCase())||"png",rs=`${n.id}/newsletters/${Date.now()}-${Math.random().toString(36).slice(2,8)}.${gt}`,{error:Ns}=await V.storage.from("email-assets").upload(rs,dt,{cacheControl:"3600",upsert:!1,contentType:dt.type});if(Ns)throw Ns;const{data:us}=V.storage.from("email-assets").getPublicUrl(rs);Re(us.publicUrl),ae.success("Image uploaded")}catch(gt){ae.error(gt.message||"Upload failed")}finally{nt(!1)}},rt=()=>{if(!Ee.trim())return;const dt=(ke||"").replace(/[<>"]/g,""),jt=Oe==="half"?280:560,gt=`
${dt}

 

`.trim();C(gt,yt),Ye(!1)},{data:Ft,isLoading:Ut}=pt({queryKey:["newsletter-editor-videos",n==null?void 0:n.id],enabled:!!(n!=null&&n.id)&&me,queryFn:async()=>{const{data:dt,error:jt}=await V.from("agent_videos").select("id, title, thumbnail_url, share_token, duration_seconds, created_at").eq("owner_user_id",n.id).eq("is_deleted",!1).eq("status","ready").not("share_token","is",null).order("created_at",{ascending:!1}).limit(50);if(jt)throw jt;return dt||[]}}),Is=dt=>{dt.share_token&&(le(`https://video.relevelup.com/share/video/${dt.share_token}`),_e(`https://video.relevelup.com/thumb/${dt.share_token}`),he(dt.title||"Watch the video"))},xs=l==="mobile"?390:"100%",st=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($,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>_("bold"),title:"Bold",children:e.jsx(zT,{className:"h-3.5 w-3.5"})}),e.jsx($,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>_("italic"),title:"Italic",children:e.jsx(GT,{className:"h-3.5 w-3.5"})}),e.jsx($,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>_("underline"),title:"Underline",children:e.jsx(pB,{className:"h-3.5 w-3.5"})}),e.jsx("div",{className:"w-px h-5 bg-border mx-1"}),e.jsx($,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>_("insertUnorderedList"),title:"Bullet list",children:e.jsx(Sy,{className:"h-3.5 w-3.5"})}),e.jsx($,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>_("insertOrderedList"),title:"Numbered list",children:e.jsx(_2,{className:"h-3.5 w-3.5"})}),e.jsx($,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:j,title:"Insert link",children:e.jsx(od,{className:"h-3.5 w-3.5"})}),e.jsx("div",{className:"w-px h-5 bg-border mx-1"}),e.jsx($,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>_("undo"),title:"Undo",children:e.jsx(rM,{className:"h-3.5 w-3.5"})}),e.jsx($,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>_("redo"),title:"Redo",children:e.jsx(JT,{className:"h-3.5 w-3.5"})}),e.jsx("div",{className:"w-px h-5 bg-border mx-1"}),e.jsxs(Au,{children:[e.jsx(Eu,{asChild:!0,children:e.jsxs($,{type:"button",variant:"ghost",size:"sm",className:"h-7 px-2 gap-1.5",title:"Insert CTA Button",children:[e.jsx(rh,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"text-xs font-medium",children:"CTA Button"})]})}),e.jsxs(gu,{align:"start",className:"w-56 bg-popover z-50",children:[e.jsx(TO,{children:"Insert a call-to-action"}),e.jsx(j0,{}),Fbn.map(dt=>{const jt=dt.icon;return e.jsxs(Pa,{onClick:()=>ee(dt),children:[e.jsx(jt,{className:"h-4 w-4 mr-2"}),dt.label]},dt.key)})]})]}),e.jsxs($,{type:"button",variant:"ghost",size:"sm",className:"h-7 px-2 gap-1.5",title:"Insert image",onClick:at,children:[e.jsx(zc,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"text-xs font-medium",children:"Image"})]}),e.jsxs($,{type:"button",variant:"ghost",size:"sm",className:"h-7 px-2 gap-1.5",title:"Insert video block",onClick:Ue,children:[e.jsx(ia,{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(AB,{type:"single",value:l,onValueChange:dt=>dt&&o(dt),size:"sm",className:"h-7",children:[e.jsx(oO,{value:"desktop",className:"h-7 px-2",title:"Desktop preview",children:e.jsx(j2,{className:"h-3.5 w-3.5"})}),e.jsx(oO,{value:"mobile",className:"h-7 px-2",title:"Mobile preview",children:e.jsx(yb,{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(rh,{className:"h-3 w-3"}),e.jsxs("span",{children:["Tip: click where you want to add an image, video, or button — or click a ",e.jsx("em",{children:"[ bracketed placeholder ]"})," to replace it. Click any button/link to edit where it goes."]})]}),e.jsx("div",{className:"bg-muted/20 flex justify-center overflow-auto",style:{padding:l==="mobile"?16:0},children:e.jsx("iframe",{ref:r,title:"Newsletter visual editor",className:"bg-white",style:{width:xs,maxWidth:st,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(zs,{open:d,onOpenChange:u,children:e.jsxs(Rs,{className:"sm:max-w-md",children:[e.jsx(Vs,{children:e.jsx($s,{children:"Edit link"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"link-edit-text",children:"Button / link text"}),e.jsx(be,{id:"link-edit-text",value:p,onChange:dt=>g(dt.target.value),placeholder:"Click here"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"link-edit-href",children:"Where should this link go?"}),e.jsx(be,{id:"link-edit-href",value:h,onChange:dt=>m(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(kr,{children:[e.jsx($,{type:"button",variant:"outline",onClick:()=>u(!1),children:"Cancel"}),e.jsx($,{type:"button",onClick:v,disabled:!h.trim(),children:"Save link"})]})]})}),e.jsx(zs,{open:A,onOpenChange:M,children:e.jsxs(Rs,{className:"sm:max-w-md",children:[e.jsx(Vs,{children:e.jsxs($s,{children:["Insert ",(I==null?void 0:I.label)||"CTA Button"]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"cta-text",children:"Button text"}),e.jsx(be,{id:"cta-text",value:R,onChange:dt=>O(dt.target.value),placeholder:I==null?void 0:I.defaultText})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"cta-value",children:I==null?void 0:I.helper}),e.jsx(be,{id:"cta-value",value:B,onChange:dt=>U(dt.target.value),placeholder:I==null?void 0:I.placeholder,autoFocus:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"cta-color",children:"Button color"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(be,{id:"cta-color",type:"color",value:G,onChange:dt=>H(dt.target.value),className:"h-9 w-16 p-1 cursor-pointer"}),e.jsx(be,{value:G,onChange:dt=>H(dt.target.value),className:"flex-1"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Position"}),e.jsxs(m_,{value:Y,onValueChange:dt=>se(dt),className:"flex gap-4 flex-wrap",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Yh,{value:"cursor",id:"cta-cursor"}),e.jsxs(re,{htmlFor:"cta-cursor",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(rh,{className:"h-3.5 w-3.5"}),"At cursor"]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Yh,{value:"top",id:"cta-top"}),e.jsxs(re,{htmlFor:"cta-top",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(ap,{className:"h-3.5 w-3.5"}),"Top of newsletter"]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Yh,{value:"bottom",id:"cta-bottom"}),e.jsxs(re,{htmlFor:"cta-bottom",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(nx,{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:G,color:"#ffffff",borderRadius:6,padding:"14px 28px",fontFamily:"Arial, sans-serif",fontWeight:600,fontSize:16},children:R||(I==null?void 0:I.defaultText)})})]}),e.jsxs(kr,{children:[e.jsx($,{type:"button",variant:"outline",onClick:()=>M(!1),children:"Cancel"}),e.jsx($,{type:"button",onClick:oe,disabled:!(I!=null&&I.isForward)&&!B.trim(),children:"Insert Button"})]})]})}),e.jsx(zs,{open:me,onOpenChange:Q,children:e.jsxs(Rs,{className:"sm:max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(Vs,{children:e.jsx($s,{children:"Insert Video Block"})}),e.jsxs(ya,{defaultValue:"library",className:"space-y-3",children:[e.jsxs(va,{className:"grid w-full grid-cols-3",children:[e.jsx(is,{value:"library",children:"My Library"}),e.jsx(is,{value:"url",children:"From URL"}),e.jsx(is,{value:"record",children:"Record New"})]}),e.jsxs(cs,{value:"library",className:"space-y-3 mt-2",children:[Ut?e.jsxs("div",{className:"text-center py-8 text-sm text-muted-foreground",children:[e.jsx(Jt,{className:"h-5 w-5 animate-spin mx-auto mb-2"}),"Loading your videos..."]}):!Ft||Ft.length===0?e.jsxs("div",{className:"text-center py-8 text-sm text-muted-foreground border rounded-md",children:[e.jsx(ia,{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:Ft.map(dt=>{const jt=te.includes(dt.share_token||"___"),gt=dt.share_token?`https://video.relevelup.com/thumb/${dt.share_token}`:dt.thumbnail_url||"";return e.jsxs("button",{type:"button",onClick:()=>Is(dt),className:`group text-left rounded-md border-2 overflow-hidden transition-all ${jt?"border-primary ring-2 ring-primary/30":"border-transparent hover:border-primary/40"}`,children:[e.jsxs("div",{className:"aspect-video bg-muted relative",children:[gt?e.jsx("img",{src:gt,alt: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(ia,{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(pu,{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(re,{htmlFor:"vid-title-lib",className:"text-xs",children:"Caption (optional)"}),e.jsx(be,{id:"vid-title-lib",value:ve,onChange:dt=>he(dt.target.value),placeholder:"Watch the video"})]})]}),e.jsxs(cs,{value:"url",className:"space-y-3 mt-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{htmlFor:"vid-url",children:"Video URL"}),e.jsx(be,{id:"vid-url",value:te,onChange:dt=>le(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(re,{htmlFor:"vid-title",children:"Caption (optional)"}),e.jsx(be,{id:"vid-title",value:ve,onChange:dt=>he(dt.target.value),placeholder:"Watch the video"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{htmlFor:"vid-thumb",children:"Custom thumbnail URL (optional)"}),e.jsx(be,{id:"vid-thumb",value:fe,onChange:dt=>_e(dt.target.value),placeholder:"https://... (only if not YouTube/Vimeo)"})]})]}),e.jsx(cs,{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(ia,{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($,{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(re,{children:"Position"}),e.jsxs(m_,{value:Se,onValueChange:dt=>Te(dt),className:"flex gap-4 flex-wrap",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Yh,{value:"cursor",id:"vid-cursor"}),e.jsxs(re,{htmlFor:"vid-cursor",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(rh,{className:"h-3.5 w-3.5"}),"At cursor"]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Yh,{value:"top",id:"vid-top"}),e.jsxs(re,{htmlFor:"vid-top",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(ap,{className:"h-3.5 w-3.5"}),"Top"]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Yh,{value:"bottom",id:"vid-bottom"}),e.jsxs(re,{htmlFor:"vid-bottom",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(nx,{className:"h-3.5 w-3.5"}),"Bottom"]})]})]})]}),Ie&&e.jsxs("div",{className:"rounded-md border bg-muted/30 p-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:"Preview"}),e.jsxs("div",{className:"relative",children:[e.jsx("img",{src:Ie,alt:"thumbnail",className:"w-full rounded-md",style:{maxHeight:180,objectFit:"cover"},onError: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(kr,{children:[e.jsx($,{type:"button",variant:"outline",onClick:()=>Q(!1),children:"Cancel"}),e.jsx($,{type:"button",onClick:Be,disabled:!te.trim(),children:"Insert Video"})]})]})}),e.jsx(zs,{open:je,onOpenChange:Ye,children:e.jsxs(Rs,{className:"sm:max-w-md max-h-[90vh] overflow-y-auto",children:[e.jsx(Vs,{children:e.jsx($s,{children:"Insert Image"})}),e.jsxs(ya,{defaultValue:"library",className:"space-y-3",children:[e.jsxs(va,{className:"grid w-full grid-cols-3",children:[e.jsx(is,{value:"library",children:"Library"}),e.jsx(is,{value:"upload",children:"Upload"}),e.jsx(is,{value:"url",children:"From URL"})]}),e.jsx(cs,{value:"library",className:"mt-2",children:e.jsx(HFt,{maxHeight:"380px",onSelect:dt=>{Re(dt.image_url),ke||Fe(dt.title)}})}),e.jsxs(cs,{value:"upload",className:"space-y-3 mt-2",children:[e.jsx("input",{ref:et,type:"file",accept:"image/png,image/jpeg,image/webp,image/gif",className:"hidden",onChange:dt=>{var gt;const jt=(gt=dt.target.files)==null?void 0:gt[0];jt&&wt(jt),dt.target.value=""}}),Ee?e.jsxs("div",{className:"rounded-md border overflow-hidden bg-muted/30",children:[e.jsx("img",{src:Ee,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($,{type:"button",variant:"ghost",size:"sm",onClick:()=>Re(""),children:"Replace"})]})]}):e.jsx("button",{type:"button",onClick:()=>{var dt;return(dt=et.current)==null?void 0:dt.click()},disabled:ut,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:ut?e.jsxs(e.Fragment,{children:[e.jsx(Jt,{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(gi,{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(cs,{value:"url",className:"space-y-3 mt-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{htmlFor:"img-url",children:"Image URL"}),e.jsx(be,{id:"img-url",value:Ee,onChange:dt=>Re(dt.target.value),placeholder:"https://..."})]}),Ee&&/^https?:\/\//i.test(Ee)&&e.jsx("div",{className:"rounded-md border overflow-hidden bg-muted/30",children:e.jsx("img",{src:Ee,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(re,{htmlFor:"img-alt",children:"Alt text (for accessibility)"}),e.jsx(be,{id:"img-alt",value:ke,onChange:dt=>Fe(dt.target.value),placeholder:"Describe the image"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Size"}),e.jsxs(m_,{value:Oe,onValueChange:dt=>Ge(dt),className:"flex gap-4",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Yh,{value:"full",id:"img-full"}),e.jsx(re,{htmlFor:"img-full",className:"cursor-pointer font-normal",children:"Full width"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Yh,{value:"half",id:"img-half"}),e.jsx(re,{htmlFor:"img-half",className:"cursor-pointer font-normal",children:"Half width"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Position"}),e.jsxs(m_,{value:yt,onValueChange:dt=>tt(dt),className:"flex gap-4 flex-wrap",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Yh,{value:"cursor",id:"img-cursor"}),e.jsxs(re,{htmlFor:"img-cursor",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(rh,{className:"h-3.5 w-3.5"}),"At cursor"]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Yh,{value:"top",id:"img-top"}),e.jsxs(re,{htmlFor:"img-top",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(ap,{className:"h-3.5 w-3.5"}),"Top"]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Yh,{value:"bottom",id:"img-bottom"}),e.jsxs(re,{htmlFor:"img-bottom",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(nx,{className:"h-3.5 w-3.5"}),"Bottom"]})]})]})]})]}),e.jsxs(kr,{children:[e.jsx($,{type:"button",variant:"outline",onClick:()=>Ye(!1),children:"Cancel"}),e.jsx($,{type:"button",onClick:rt,disabled:!Ee.trim()||ut,children:"Insert Image"})]})]})})]})}const kxt="newsletter-content",Bbn="inline-images";function $bn(s,t){const n=atob(s),r=new Array(n.length);for(let a=0;a{const{data:P}=await V.from("team_members").select("team_id, role").eq("user_id",a.id).maybeSingle();return P}}),A=(C==null?void 0:C.role)==="team_leader",M=(C==null?void 0:C.team_id)??null;k.useEffect(()=>{s&&(d((n==null?void 0:n.title)??""),h((n==null?void 0:n.description)??""),p((n==null?void 0:n.html_content)??Vbn()),x((n==null?void 0:n.is_template)??!1),v((n==null?void 0:n.share_scope)??"private"))},[s,n]);const I=async()=>{if(a){if(!c.trim()){ae.error("Please enter a title");return}if(!m.trim()){ae.error("Newsletter content is empty");return}j(!0);try{const P=await Ubn(m);P!==m&&p(P);const R={user_id:a.id,title:c.trim(),description:u.trim()||null,html_content:P,is_template:g,share_scope:y,shared_team_id:y==="team"?M:null,shared_brokerage_id:y==="brokerage"?o:null};if(y==="team"&&!M){ae.error("You must be a team leader to share with a team"),j(!1);return}if(y==="brokerage"&&!l){ae.error("Only brokerage managers can share to a brokerage"),j(!1);return}if(y==="global"&&!i){ae.error("Only admins can publish global starter templates"),j(!1);return}let O;if(n!=null&&n.id?{error:O}=await V.from("agent_custom_newsletters").update(R).eq("id",n.id):{error:O}=await V.from("agent_custom_newsletters").insert(R),O)throw O;ae.success(n!=null&&n.id?"Saved":"Newsletter created"),r==null||r(),t(!1)}catch(P){ae.error(P.message||"Failed to save")}finally{j(!1)}}};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"max-w-6xl h-[92vh] flex flex-col p-0",children:[e.jsx(Vs,{className:"px-6 pt-6 pb-3 border-b",children:e.jsx($s,{children:n!=null&&n.id?"Edit Newsletter":"Create Newsletter"})}),e.jsxs("div",{className:"flex-1 overflow-y-auto px-6 py-4 space-y-4",children:[e.jsxs("div",{className:"grid sm:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(re,{htmlFor:"acn-title",children:"Title *"}),e.jsx(be,{id:"acn-title",value:c,onChange:P=>d(P.target.value),placeholder:"e.g. June Market Update"})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"acn-desc",children:"Description (optional)"}),e.jsx(be,{id:"acn-desc",value:u,onChange:P=>h(P.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(On,{id:"acn-template",checked:g,onCheckedChange:x}),e.jsx(re,{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"})]}),(A||l||i)&&e.jsxs("div",{className:"rounded-lg border p-4 space-y-3",children:[e.jsx(re,{className:"text-sm font-semibold",children:"Sharing"}),e.jsxs(m_,{value:y,onValueChange:P=>v(P),className:"space-y-2",children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Yh,{value:"private",id:"s-private",className:"mt-0.5"}),e.jsxs(re,{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"})]})]}),A&&e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Yh,{value:"team",id:"s-team",className:"mt-0.5"}),e.jsxs(re,{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(Yh,{value:"brokerage",id:"s-brokerage",className:"mt-0.5"}),e.jsxs(re,{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(Yh,{value:"global",id:"s-global",className:"mt-0.5"}),e.jsxs(re,{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(re,{className:"mb-2 block",children:"Content"}),e.jsx(GFt,{html:m,onChange:p})]})]}),e.jsxs(kr,{className:"px-6 py-3 border-t",children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),disabled:_,children:"Cancel"}),e.jsxs($,{onClick:I,disabled:_,children:[_?e.jsx(Jt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Ml,{className:"h-4 w-4 mr-2"}),n!=null&&n.id?"Save Changes":"Create"]})]})]})})}function Vbn(){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}}

`}const vZe=/\[[^\]\[<>]{2,80}\]/g,Hbn=/^\[\s*(?:\/?\s*if\b[^\]]*|endif|else|x-apple-[\w-]*|data-[\w-]*|object [^\]]*|cdata[^\]]*)\s*\]$/i;function bZe(s){return!Hbn.test(s)}function Gbn(s){return(s.match(vZe)||[]).filter(bZe)}function Sxt(s){const t=s.toLowerCase();return t.charAt(0).toUpperCase()+t.slice(1)}function Wbn(s){const t=[],n=new RegExp(vZe.source,"g");let r;for(;(r=n.exec(s))!==null;)bZe(r[0])&&t.push({token:r[0],start:r.index});const a=t.reduce((l,o)=>(l[o.token]=(l[o.token]||0)+1,l),{}),i={};return t.map((l,o)=>{const c=l.token.slice(1,-1),d=/^#+$/.test(c);i[l.token]=(i[l.token]||0)+1;const u=t[o+1],h=u?u.token.slice(1,-1):"";let m;return d?m=u&&!/^#+$/.test(h)?`Date · ${Sxt(h)}`:`Date ${i[l.token]}`:(m=Sxt(c),a[l.token]>1&&(m+=` (${i[l.token]} of ${a[l.token]})`)),{index:o,token:l.token,label:m,hint:d?"Day of the month, e.g. 14":l.token}})}function Kbn({html:s,onChange:t,originalHtml:n}){const r=k.useMemo(()=>Wbn(s),[s]),[a,i]=k.useState({}),[l,o]=k.useState([]),c=k.useRef(null);c.current===null&&s&&(c.current=n??s);const d=k.useRef(!1);k.useEffect(()=>{if(d.current){d.current=!1;return}i({}),o([])},[s]);const u=()=>{const v=new RegExp(vZe.source,"g");let _=0;const j=s.replace(v,C=>{if(!bZe(C))return C;const A=(a[_]||"").trim();return _+=1,A||C});j!==s&&(o(C=>[...C,{html:s,values:a}]),d.current=!0,i({}),t(j))},h=()=>{const v=l[l.length-1];v&&(o(_=>_.slice(0,-1)),d.current=!0,i(v.values),t(v.html))},m=()=>{const v=c.current;!v||v===s||(o([]),d.current=!0,i({}),t(v))},p=l.length>0,g=!!c.current&&c.current!==s,x=e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs($,{type:"button",size:"sm",variant:"outline",onClick:h,disabled:!p,children:[e.jsx(rY,{className:"h-3.5 w-3.5 mr-1"}),"Undo last fill"]}),e.jsxs($,{type:"button",size:"sm",variant:"ghost",onClick:m,disabled:!g,children:[e.jsx(jm,{className:"h-3.5 w-3.5 mr-1"}),"Start over"]})]});if(r.length===0)return e.jsxs("div",{className:"rounded-lg border border-emerald-500/30 bg-emerald-500/5 p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(Gr,{className:"h-4 w-4 text-emerald-600 shrink-0"}),e.jsx("span",{className:"text-muted-foreground",children:"All template fields are filled in. Your name, phone, website and brokerage fill in automatically."})]}),(p||g)&&e.jsxs("div",{className:"flex flex-wrap items-center gap-2 pl-6",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Made a typo?"}),x]})]});const y=r.filter(v=>(a[v.index]||"").trim()).length;return e.jsxs("div",{className:"rounded-xl border border-amber-500/40 bg-amber-500/5 p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Gd,{className:"h-4 w-4 text-amber-600 mt-0.5 shrink-0"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-semibold",children:"Customize before you send"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["This template has ",r.length," field",r.length===1?"":"s"," that only you can fill in (local dates, events, favorite spots). Sending is locked until they're done."]})]})]}),e.jsxs(qe,{variant:"secondary",className:"shrink-0",children:[y,"/",r.length," ready"]})]}),e.jsx("div",{className:"grid grid-cols-1 gap-4",children:r.map(v=>e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{className:"text-[11px] uppercase tracking-wide text-muted-foreground",children:v.label}),e.jsx(be,{value:a[v.index]||"",placeholder:v.hint,className:"h-10 text-sm",onChange:_=>i(j=>({...j,[v.index]:_.target.value})),onKeyDown:_=>{_.key==="Enter"&&(_.preventDefault(),u())}})]},v.index))}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs($,{type:"button",size:"sm",onClick:u,children:[e.jsx(aB,{className:"h-3.5 w-3.5 mr-1"}),"Apply to email"]}),x]}),e.jsxs("p",{className:"text-[11px] text-muted-foreground",children:["Typed something wrong? Use ",e.jsx("span",{className:"font-medium",children:"Undo last fill"})," to bring the fields back with your text still in them, or ",e.jsx("span",{className:"font-medium",children:"Start over"})," to restore the original template."]})]})}function NV(){var a;const{user:s}=ks(),{data:t,isLoading:n}=pt({queryKey:["mass-email-settings",s==null?void 0:s.id],enabled:!!s,staleTime:60*1e3,queryFn:async()=>{var d,u,h,m;const[i,l]=await Promise.all([V.from("mass_email_settings").select("reply_to_email, display_name").eq("user_id",s.id).maybeSingle(),V.from("profiles").select("email, name").eq("id",s.id).maybeSingle()]),o=i.data,c=l.data;return{reply_to_email:((d=o==null?void 0:o.reply_to_email)==null?void 0:d.trim())||((u=c==null?void 0:c.email)==null?void 0:u.trim())||s.email||null,display_name:((h=o==null?void 0:o.display_name)==null?void 0:h.trim())||((m=c==null?void 0:c.name)==null?void 0:m.trim())||null}}});return{isReady:!!((a=t==null?void 0:t.reply_to_email)!=null&&a.trim()),isLoading:n,settings:t}}function ZEe(){const{user:s}=ks();return pt({queryKey:["verified-sender-check",s==null?void 0:s.id],enabled:!!s,staleTime:3e4,queryFn:async()=>{const[t,n]=await Promise.all([V.from("user_verified_senders").select("id, email, status").eq("user_id",s.id),V.from("gmail_integrations").select("gmail_email, is_active").eq("user_id",s.id).eq("is_active",!0).maybeSingle()]),r=t.data||[],a=r.filter(l=>l.status==="verified"),i=r.filter(l=>l.status==="pending");return{hasVerifiedSes:a.length>0,hasPendingSes:i.length>0,hasAnySender:r.length>0,hasGmail:!!n.data,verifiedEmails:a.map(l=>l.email),pendingEmails:i.map(l=>l.email)}}})}function XEe({open:s,onOpenChange:t,hasPending:n,pendingEmails:r}){const a=Jn();return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"sm:max-w-md",children:[e.jsxs(Vs,{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("div",{className:"h-9 w-9 rounded-full bg-amber-500/10 text-amber-600 flex items-center justify-center",children:e.jsx(Ho,{className:"h-5 w-5"})}),e.jsx($s,{children:"Verify your sending email first"})]}),e.jsx(Cr,{className:"pt-2",children:`Before you can send emails through Amazon, your "from" address needs to be verified so inboxes trust it and it doesn't land in spam.`})]}),n&&r&&r.length>0?e.jsxs("div",{className:"rounded-lg border bg-amber-500/5 p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium text-amber-700",children:[e.jsx(sa,{className:"h-4 w-4"})," Waiting for you to click Amazon's link"]}),r.map(i=>e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(pn,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"truncate",children:i})]},i)),e.jsx("p",{className:"text-xs text-muted-foreground pt-1",children:"Check that inbox (and your spam folder) for an email from Amazon Web Services and click the verification link."})]}):e.jsx("div",{className:"rounded-lg border bg-muted/40 p-3 text-sm text-muted-foreground",children:"It only takes a minute — add your email address on the Integrations page, then click the verification link Amazon sends you."}),e.jsxs(kr,{className:"gap-2 sm:gap-2",children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),children:"Not now"}),e.jsxs($,{onClick:()=>{t(!1),a("/mission-control/integrations")},children:[e.jsx(Ir,{className:"h-4 w-4 mr-1"}),n?"Manage senders":"Verify my email"]})]})]})})}function kV(){const s=ai();return pt({queryKey:["custom-tags",s],queryFn:async()=>{const{data:t,error:n}=await V.from("contact_custom_tags").select("*").eq("owner_user_id",s).order("name");if(n)throw n;return t},enabled:!!s})}function Ybn(s){return pt({queryKey:["contact-custom-tags",s],queryFn:async()=>{const{data:t,error:n}=await V.from("contact_custom_tag_assignments").select("*, tag:contact_custom_tags(*)").eq("contact_id",s);if(n)throw n;return t},enabled:!!s})}function _Ze(){const s=ls(),t=ai();return Nt({mutationFn:async({name:n,color:r})=>{const{data:a,error:i}=await V.from("contact_custom_tags").insert({owner_user_id:t,name:n.trim(),color:r||"#6366F1"}).select().single();if(i)throw i;return a},onSuccess:()=>{s.invalidateQueries({queryKey:["custom-tags"]})}})}function Zbn(){const s=ls();return Nt({mutationFn:async t=>{const{error:n}=await V.from("contact_custom_tags").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["custom-tags"]}),s.invalidateQueries({queryKey:["contact-custom-tags"]}),s.invalidateQueries({queryKey:["all-contact-custom-tags"]})}})}function Xbn(){const s=ls();return Nt({mutationFn:async({id:t,name:n,color:r})=>{const a={};n!==void 0&&(a.name=n.trim()),r!==void 0&&(a.color=r);const{error:i}=await V.from("contact_custom_tags").update(a).eq("id",t);if(i)throw i},onSuccess:()=>{s.invalidateQueries({queryKey:["custom-tags"]}),s.invalidateQueries({queryKey:["contact-custom-tags"]}),s.invalidateQueries({queryKey:["all-contact-custom-tags"]})}})}function WFt(){const s=ls();return Nt({mutationFn:async({contactId:t,tagId:n})=>{const{error:r}=await V.from("contact_custom_tag_assignments").insert({contact_id:t,tag_id:n});if(r)throw r},onSuccess:(t,{contactId:n})=>{s.invalidateQueries({queryKey:["contact-custom-tags",n]}),s.invalidateQueries({queryKey:["all-contact-custom-tags"]})}})}function Qbn(){const s=ls();return Nt({mutationFn:async({contactId:t,tagId:n})=>{const{error:r}=await V.from("contact_custom_tag_assignments").delete().eq("contact_id",t).eq("tag_id",n);if(r)throw r},onSuccess:(t,{contactId:n})=>{s.invalidateQueries({queryKey:["contact-custom-tags",n]}),s.invalidateQueries({queryKey:["all-contact-custom-tags"]})}})}function QEe(){const s=ai();return pt({queryKey:["all-contact-custom-tags",s],queryFn:async()=>{const{data:t,error:n}=await V.from("contact_custom_tag_assignments").select("contact_id, tag_id, tag:contact_custom_tags(id, name, color)");if(n)throw n;return t},enabled:!!s})}function wZe(){const{user:s}=ks();return pt({queryKey:["contact-smart-lists",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await V.from("contact_smart_lists").select("*").order("created_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function KFt(){const s=ls(),{user:t}=ks();return Nt({mutationFn:async({name:n,filters:r,sort_by:a})=>{const{data:i,error:l}=await V.from("contact_smart_lists").insert({owner_user_id:t.id,name:n,filters:r,sort_by:a}).select().single();if(l)throw l;return i},onSuccess:()=>{s.invalidateQueries({queryKey:["contact-smart-lists"]}),Ma({title:"Smart filter saved"})},onError:n=>{Ma({title:"Error saving smart filter",description:n.message,variant:"destructive"})}})}function YFt(){const s=ls();return Nt({mutationFn:async t=>{const{error:n}=await V.from("contact_smart_lists").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["contact-smart-lists"]}),Ma({title:"Smart filter deleted"})}})}const Cxt=s=>s.replace(/&/g,"&").replace(//g,">").replace(/"/g,""");function Axt(s,t,n,r){const a=t.name||`${t.first_name||""} ${t.last_name||""}`.trim()||"there",i=new Date,l=new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",month:"long",day:"numeric",year:"numeric"}).format(i),o=new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",year:"numeric"}).format(i),c=(n==null?void 0:n.name)||"",d=c.split(/\s+/).filter(Boolean).map(p=>p[0]).join("").slice(0,2).toUpperCase(),u=((n==null?void 0:n.website_url)||"").trim(),h=[n==null?void 0:n.return_address_line1,[n==null?void 0:n.return_address_city,n==null?void 0:n.return_address_state].filter(Boolean).join(", "),n==null?void 0:n.return_address_zip].filter(Boolean).join(" · "),m={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:c,agent_first_name:c.split(" ")[0]||"",agent_initials:d,agent_email:(n==null?void 0:n.email)||"",agent_phone:(n==null?void 0:n.phone)||"",agent_title:(n==null?void 0:n.title)||"",agent_website:u.replace(/^https?:\/\//i,"").replace(/\/$/,""),agent_website_url:u?/^https?:\/\//i.test(u)?u:`https://${u}`:"#",market_city:(n==null?void 0:n.market_city)||t.city||"",brokerage:r||(n==null?void 0:n.brokerage_name)||"",brokerage_address:h,current_date:l,current_year:o};return s.replace(/\{\{\s*(\w+)\s*\}\}/g,(p,g)=>m[g]??`{{${g}}}`)}function Jbn(s,t,n,r){const a=t.trim()?`
${Cxt(t).replace(/\n/g,"
")}
`:"",i=n.trim()?`
${Cxt(n).replace(/\n/g,"
")}
`:"",l=r?`
${r}
`:"";return`${a} ${s} ${i} ${l}`}function e_n(s,t,n){const r=(s==null?void 0:s.name)||"Your Agent",a=(s==null?void 0:s.email)||"",i=(t==null?void 0:t.name)||"",l=[t==null?void 0:t.city,t==null?void 0:t.state].filter(Boolean).join(", "),o=a?`mailto:${encodeURIComponent(a)}?subject=${encodeURIComponent("Unsubscribe")}&body=${encodeURIComponent(`Please remove ${n} from your newsletter list.`)}`:"#";return`
${r}${i?" • "+i:""}
${l?`
${l}
`:""}
You're receiving this because ${r} thought you'd find it useful. Unsubscribe
`}const t_n=["free","act now","click here","limited time","urgent","$$$","100% free","guarantee","no obligation","risk-free","winner","cash bonus","make money","earn extra","amazing"];function s_n(s,t){const n=[],r=s.trim();if(r.length>0){r.length<10&&n.push("Subject line is very short — most opened subjects are 30-60 characters."),r.length>90&&n.push("Subject line is very long — many inboxes truncate after 60-70 characters.");const l=r.replace(/[^A-Za-z]/g,""),o=r.replace(/[^A-Z]/g,"");l.length>6&&o.length/l.length>.6&&n.push("Subject is mostly uppercase — this often triggers spam filters."),(r.match(/!/g)||[]).length>=3&&n.push("Too many exclamation marks in the subject.");const d=r.toLowerCase(),u=t_n.filter(h=>d.includes(h));u.length>0&&n.push(`Subject contains spam-trigger words: ${u.slice(0,3).join(", ")}.`)}const a=t.replace(/<[^>]+>/g," ").replace(/\s+/g," ").trim();return a.length<40&&n.push("Email body is very short — add more text so it doesn't look like a spam blast."),(t.match(/0&&a.length<80&&n.push("Email is mostly images with little text — many spam filters block these."),n}function jZe({open:s,onOpenChange:t,newsletterId:n,newsletterTitle:r,htmlCode:a}){const{user:i}=ks();dx();const{isReady:l,settings:o}=NV(),{data:c}=ZEe(),[d,u]=k.useState(!1),h=ai(),{data:m}=pt({queryKey:["agent-profile-for-newsletter-send",i==null?void 0:i.id],enabled:!!i&&s,staleTime:5*60*1e3,queryFn:async()=>{if(!i)return null;const{data:dn}=await V.from("profiles").select("name, email, phone, avatar_url, title, email_signature, use_email_signature, website_url, market_city, brokerage_name, return_address_line1, return_address_city, return_address_state, return_address_zip").eq("id",i.id).maybeSingle();return dn}}),[p,g]=k.useState("visual"),[x,y]=k.useState("all"),[v,_]=k.useState(""),[j,C]=k.useState(""),[A,M]=k.useState(""),[I,P]=k.useState(""),[R,O]=k.useState(!0),[B,U]=k.useState([]),[G,H]=k.useState(null),[Y,se]=k.useState(new Set),[ee,oe]=k.useState(""),[me,Q]=k.useState(!1),[te,le]=k.useState(!1),[fe,_e]=k.useState(!1),[ve,he]=k.useState({sent:0,failed:0,total:0,currentName:""}),[Se,Te]=k.useState(!0),[Ie,Ue]=k.useState(!1),[Be,je]=k.useState([]),[Ye,Ee]=k.useState(!1),[Re,ke]=k.useState(new Set),[Fe,Oe]=k.useState("now"),[Ge,yt]=k.useState(""),{data:tt=[]}=kV(),{data:ut=[]}=QEe(),{data:nt=[]}=wZe(),{data:et=[],isLoading:at}=pt({queryKey:["newsletter-send-contacts",h],enabled:!!h&&s,queryFn:async()=>{const dn=[];let Kt=0;const Er=1e3;for(;;){const{data:ti,error:Ba}=await V.from("innercircle_contacts").select("id, first_name, last_name, email, phone, address, city, state, zip, zip_code").eq("owner_user_id",h).not("email","is",null).neq("email","").order("first_name").range(Kt,Kt+Er-1);if(Ba)throw Ba;if(!ti||ti.length===0||(dn.push(...ti),ti.length{const{data:dn}=await V.from("ses_suppressed_emails").select("email");return(dn||[]).map(Kt=>Kt.email.toLowerCase())}}),{data:rt}=pt({queryKey:["newsletter-brokerage-info",i==null?void 0:i.id],enabled:!!i&&s,staleTime:10*60*1e3,queryFn:async()=>{if(!i)return null;const{data:dn}=await V.from("profiles").select("brokerage_id").eq("id",i.id).maybeSingle();if(!(dn!=null&&dn.brokerage_id))return null;const{data:Kt}=await V.from("brokerages").select("name, city, state").eq("id",dn.brokerage_id).maybeSingle();return Kt}}),{data:Ft}=pt({queryKey:["newsletter-active-lead-site",h],enabled:!!h&&s,staleTime:5*60*1e3,queryFn:async()=>{if(!h)return null;const{data:dn}=await V.from("lead_sites").select("id, subdomain_slug, mls_provider_id, mls_agent_id, mls_agent_key, is_active").eq("agent_id",h).eq("is_active",!0).not("mls_provider_id","is",null).order("created_at",{ascending:!0}).limit(1).maybeSingle();return dn}}),Ut=!!(Ft!=null&&Ft.mls_provider_id),Is=(Ft==null?void 0:Ft.mls_agent_id)||(Ft==null?void 0:Ft.mls_agent_key)||null,{data:xs=[],isLoading:st}=pt({queryKey:["newsletter-agent-listings",h,Is],enabled:!!h&&!!Is&&Ye,staleTime:60*1e3,queryFn:async()=>{if(!Is)return[];const{data:dn}=await V.from("mlsgrid_listings").select("listing_key, address, city, state, list_price, bedrooms, bathrooms_total, living_area, photos, standard_status, modification_timestamp").eq("list_agent_mls_id",Is).eq("standard_status","Active").order("modification_timestamp",{ascending:!1}).limit(30);return dn||[]}}),{data:dt=[],isLoading:jt}=pt({queryKey:["newsletter-exchange-listings",h],enabled:!!h&&Ye,staleTime:60*1e3,queryFn:async()=>{const{data:dn}=await V.from("listings").select("id, slug, property_address, city, state, price, bedrooms, bathrooms, square_footage, status, created_at").eq("agent_id",h).in("status",["active","coming_soon","office_exclusive","pre_market"]).order("created_at",{ascending:!1}).limit(30),Kt=dn||[];if(Kt.length===0)return[];const Er=Kt.map(Yn=>Yn.id),{data:ti}=await V.from("listing_photos").select("listing_id, photo_url, is_primary, sort_order").in("listing_id",Er),Ba=new Map,lo=new Map;for(const Yn of ti||[])Yn.is_primary&&!Ba.has(Yn.listing_id)&&Ba.set(Yn.listing_id,Yn.photo_url),lo.has(Yn.listing_id)||lo.set(Yn.listing_id,Yn.photo_url);return Kt.map(Yn=>({...Yn,_photo:Ba.get(Yn.id)||lo.get(Yn.id)||""}))}}),{data:gt=!1}=pt({queryKey:["newsletter-exchange-listings-exists",h],enabled:!!h&&s,staleTime:5*60*1e3,queryFn:async()=>{const{count:dn}=await V.from("listings").select("id",{count:"exact",head:!0}).eq("agent_id",h).in("status",["active","coming_soon","office_exclusive","pre_market"]);return(dn||0)>0}}),rs=k.useMemo(()=>{const dn=new Set(wt);return et.filter(Kt=>Kt.email&&Kt.email.includes("@")&&!dn.has(Kt.email.toLowerCase()))},[et,wt]),Ns=k.useMemo(()=>{if(B.length===0)return null;const dn=new Set;for(const Kt of ut)B.includes(Kt.tag_id)&&dn.add(Kt.contact_id);return dn},[ut,B]),us=k.useMemo(()=>nt.find(dn=>dn.id===G)||null,[nt,G]),Bs=k.useMemo(()=>{var dn;if(x==="all")return rs;if(x==="tags")return Ns?rs.filter(Kt=>Ns.has(Kt.id)):[];if(x==="smartlists"){if(!us)return[];const Kt=(((dn=us.filters)==null?void 0:dn.search)||"").toLowerCase().trim();return Kt?rs.filter(Er=>`${Er.first_name||""} ${Er.last_name||""}`.toLowerCase().includes(Kt)||(Er.email||"").toLowerCase().includes(Kt)):rs}return rs.filter(Kt=>Y.has(Kt.id))},[x,rs,Ns,us,Y]),Ts=k.useMemo(()=>{if(!ee.trim())return rs;const dn=ee.toLowerCase();return rs.filter(Kt=>`${Kt.first_name||""} ${Kt.last_name||""}`.toLowerCase().includes(dn))},[rs,ee]);k.useEffect(()=>{s&&(_(""),C(`Hi {{first_name}}, Sharing this month's update — hope you find something useful!`),M(`As always, reach out anytime if I can help. Talk soon!`),P(a||""),g("light"),y("all"),U([]),H(null),se(new Set),oe(""),Q(!1),O(!0),Te(!0),je([]),Oe("now"),yt(""),he({sent:0,failed:0,total:0,currentName:""}))},[s,r,a]);const Fn=l,An=k.useMemo(()=>Gbn(I||a||""),[I,a]),js=!!(v.trim()&&Fn&&Bs.length>0&&!te&&An.length===0),In=dn=>{const Kt=I||a,Er=R&&(m!=null&&m.email_signature)?m.email_signature:null;let ti;return p==="light"?ti=Jbn(Kt,j,A,Er):ti=Er?`${Kt}
${Er}
`:Kt,Se&&(ti+=e_n(m??null,rt??null,dn.email)),Axt(ti,dn,m??null,(rt==null?void 0:rt.name)??null)},un=k.useMemo(()=>In({first_name:"Friend",last_name:"",email:"preview@example.com",phone:"",address:"",city:"",state:"",zip:""}),[p,j,A,I,a,R,m,Se,rt]),jr=k.useMemo(()=>s_n(v,p==="advanced"||p==="visual"?I:a),[v,p,I,a]),Ln=async()=>{Ue(!0),je([]);try{const dn=p==="advanced"||p==="visual"?I:a,{data:Kt,error:Er}=await V.functions.invoke("generate-newsletter-subjects",{body:{newsletterTitle:r,bodyHtml:dn,currentSubject:v}});if(Er)throw Er;const ti=Kt==null?void 0:Kt.subjects;if(!Array.isArray(ti)||ti.length===0)throw new Error("No subjects returned");je(ti)}catch(dn){const Kt=(dn==null?void 0:dn.message)||"Failed to generate subjects";Kt.includes("credits exhausted")||Kt.includes("402")?ae.error("AI credits exhausted. Please add credits to your workspace."):Kt.includes("Rate limit")||Kt.includes("429")?ae.error("Rate limit hit — try again in a moment."):ae.error(Kt)}finally{Ue(!1)}},Sr=dn=>dn?"$"+Number(dn).toLocaleString("en-US"):"",Qn=()=>{var lo,Yn;if(Re.size===0){ae.error("Pick at least one listing first.");return}const dn=(Ft==null?void 0:Ft.subdomain_slug)||"",Kt=dn?`https://${dn}.relevelup.com`:"https://relevelup.com",Er=[];for(const Hr of xs){const Ur=`mls:${Hr.listing_key}`;if(!Re.has(Ur))continue;const Ei=Array.isArray(Hr.photos)&&Hr.photos.length>0?typeof Hr.photos[0]=="string"?Hr.photos[0]:((lo=Hr.photos[0])==null?void 0:lo.MediaURL)||((Yn=Hr.photos[0])==null?void 0:Yn.url)||"":"",fo=Hr.bedrooms?`${Hr.bedrooms} bd`:"",co=Hr.bathrooms_total?`${Hr.bathrooms_total} ba`:"",Tn=Hr.living_area?`${Number(Hr.living_area).toLocaleString()} sqft`:"";Er.push({url:`${Kt}/listings/${Hr.listing_key}`,photo:Ei,price:Sr(Hr.list_price),addr:`${Hr.address||""}${Hr.city?", "+Hr.city:""}`,stats:[fo,co,Tn].filter(Boolean).join(" • ")})}for(const Hr of dt){const Ur=`ex:${Hr.id}`;if(!Re.has(Ur))continue;const Ei=Hr.bedrooms?`${Hr.bedrooms} bd`:"",fo=Hr.bathrooms?`${Hr.bathrooms} ba`:"",co=Hr.square_footage?`${Number(Hr.square_footage).toLocaleString()} sqft`:"";Er.push({url:`https://listings.relevelup.com/${Hr.slug||Hr.id}`,photo:Hr._photo||"",price:Sr(Hr.price),addr:`${Hr.property_address||""}${Hr.city?", "+Hr.city:""}`,stats:[Ei,fo,co].filter(Boolean).join(" • ")})}const Ba=`

Featured Listings

${Er.map(Hr=>`
${Hr.photo?`${Hr.addr}`:""}
${Hr.price}
${Hr.addr}
${Hr.stats}
`.trim()).join(` `)}
`.trim();P(Hr=>(Hr||a||"")+` `+Ba),g("visual"),ke(new Set),Ee(!1),ae.success(`Added ${Er.length} listing${Er.length===1?"":"s"} to your newsletter.`)},En=()=>In({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}}"),pr=()=>Axt(v,{first_name:"__FN__",last_name:"__LN__",email:"__EM__",name:"__NAME__",phone:"__PHONE__",address:"__ADDR__",city:"__CITY__",state:"__STATE__",zip:"__ZIP__"},m??null,(rt==null?void 0:rt.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}}"),xn=()=>{if(An.length>0){ae.error(`Fill in ${An.length} template field${An.length===1?"":"s"} before sending.`);return}if(js){if(Fe==="later"){if(!Ge){ae.error("Pick a date and time to schedule.");return}const dn=new Date(Ge).getTime();if(Number.isNaN(dn)||dn{if(!(!js||!i)){_e(!1),le(!0),he({sent:0,failed:0,total:Bs.length,currentName:"Preparing campaign…"});try{const Kt=`${((o==null?void 0:o.display_name)||"ReLevelUp").toLowerCase().replace(/[^a-z]/g,".")}@send.relevelup.com`,Er=En(),ti=pr(),Ba=Fe==="later",{data:lo,error:Yn}=await V.from("email_campaigns").insert({user_id:h||i.id,name:`Newsletter: ${r}`,subject:ti,body_html:Er,from_email:Kt,reply_to_email:(o==null?void 0:o.reply_to_email)||null,total_recipients:Bs.length,status:Ba?"scheduled":"draft",scheduled_at:Ba?new Date(Ge).toISOString():null}).select("id").single();if(Yn)throw Yn;he(Ur=>({...Ur,currentName:"Adding recipients…"}));const Hr=Bs.map(Ur=>({campaign_id:lo.id,contact_id:Ur.id,email:Ur.email,name:[Ur.first_name,Ur.last_name].filter(Boolean).join(" ")||null,status:"pending"}));for(let Ur=0;Ur({...co,sent:Math.min(Ur+Ei.length,Hr.length)}))}if(Ba){const{error:Ur}=await V.functions.invoke("ses-schedule-campaign",{body:{action:"schedule",campaign_id:lo.id}});if(Ur)throw Ur;ae.success(`Newsletter scheduled for ${new Date(Ge).toLocaleString()}.`)}else{const{error:Ur}=await V.functions.invoke("ses-send-campaign",{body:{action:"send_campaign",campaign_id:lo.id}});if(Ur)throw Ur;ae.success(`Sending to ${Bs.length} contact${Bs.length===1?"":"s"}! Open & click tracking will appear in Sent Emails.`)}t(!1)}catch(dn){console.error("Newsletter send failed:",dn),ae.error(`Failed to send: ${dn.message||"Unknown error"}`)}finally{le(!1)}}},Zr=dn=>{se(Kt=>{const Er=new Set(Kt);return Er.has(dn)?Er.delete(dn):Er.add(dn),Er})};return e.jsxs(zs,{open:s,onOpenChange:dn=>!te&&t(dn),children:[e.jsxs(Rs,{className:"max-w-5xl max-h-[92vh] overflow-y-auto",children:[e.jsx(Vs,{children:e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(Wr,{className:"h-5 w-5"})," Send Newsletter"]})}),!Fn&&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(Ho,{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($,{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(re,{children:"Subject"}),e.jsxs($,{type:"button",variant:"ghost",size:"sm",className:"h-7 gap-1 text-xs",onClick:Ln,disabled:Ie,title:"Generate subject lines with AI",children:[Ie?e.jsx(Jt,{className:"h-3 w-3 animate-spin"}):e.jsx(kn,{className:"h-3 w-3"}),"AI Suggestions"]})]}),e.jsx(be,{value:v,onChange:dn=>_(dn.target.value),placeholder:"Newsletter subject"}),Be.length>0&&e.jsxs("div",{className:"rounded-md border bg-primary/5 p-2 space-y-1",children:[e.jsx("p",{className:"text-[11px] font-medium text-muted-foreground px-1",children:"Click to use:"}),Be.map((dn,Kt)=>e.jsxs("button",{type:"button",onClick:()=>{_(dn),je([])},className:"w-full text-left text-sm px-2 py-1.5 rounded hover:bg-primary/10 transition-colors",children:[e.jsx(kn,{className:"h-3 w-3 inline-block mr-1.5 text-primary"}),dn]},Kt))]}),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}}"})]})]}),jr.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(dB,{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:jr.map((dn,Kt)=>e.jsx("li",{children:dn},Kt))})]}),(Ut||gt)&&e.jsxs("div",{className:"rounded-lg border border-primary/30 bg-primary/5 p-3 flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"text-xs",children:[e.jsxs("div",{className:"font-medium flex items-center gap-1.5",children:[e.jsx(ua,{className:"h-3.5 w-3.5 text-primary"}),"Insert your active listings"]}),e.jsx("p",{className:"text-muted-foreground mt-0.5",children:Ut&>?"Pick from your live MLS listings or your Listing Exchange listings.":Ut?"Pick from your live MLS listings and drop them into the email.":"Pick from your Listing Exchange listings and drop them into the email."})]}),e.jsx($,{type:"button",size:"sm",variant:"outline",onClick:()=>Ee(!0),children:"Choose listings"})]}),e.jsx(Kbn,{html:I||a||"",originalHtml:a||"",onChange:P}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Editing"}),e.jsxs(ya,{value:p,onValueChange:dn=>g(dn),children:[e.jsxs(va,{className:"grid grid-cols-3 w-full",children:[e.jsxs(is,{value:"visual",children:[e.jsx(vf,{className:"h-3 w-3 mr-1"}),"Visual"]}),e.jsxs(is,{value:"light",children:[e.jsx(ea,{className:"h-3 w-3 mr-1"}),"Quick edit"]}),e.jsxs(is,{value:"advanced",children:[e.jsx(wC,{className:"h-3 w-3 mr-1"}),"HTML"]})]}),e.jsx(cs,{value:"visual",className:"mt-3",children:e.jsx(GFt,{html:I,onChange:P})}),e.jsxs(cs,{value:"light",className:"space-y-3 mt-3",children:[e.jsxs("div",{children:[e.jsx(re,{className:"text-xs text-muted-foreground",children:"Personal intro (above newsletter)"}),e.jsx(Ls,{value:j,onChange:dn=>C(dn.target.value),rows:4,placeholder:"Hi {{first_name}}, ..."})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs text-muted-foreground",children:"Personal outro (below newsletter)"}),e.jsx(Ls,{value:A,onChange:dn=>M(dn.target.value),rows:3,placeholder:"Talk soon!"})]})]}),e.jsxs(cs,{value:"advanced",className:"mt-3",children:[e.jsx(re,{className:"text-xs text-muted-foreground",children:"Edit full HTML"}),e.jsx(Ls,{value:I,onChange:dn=>P(dn.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:m!=null&&m.email_signature?"Will append the signature from your profile.":"No signature set. Add one in Profile → Email Signature."})]}),e.jsx(On,{checked:R&&!!(m!=null&&m.email_signature),disabled:!(m!=null&&m.email_signature),onCheckedChange:O})]}),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(On,{checked:Se,onCheckedChange:Te})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Recipients"}),e.jsxs(ya,{value:x,onValueChange:dn=>y(dn),children:[e.jsxs(va,{className:"grid grid-cols-4 w-full",children:[e.jsxs(is,{value:"all",children:[e.jsx(Xn,{className:"h-3 w-3 mr-1"}),"All"]}),e.jsxs(is,{value:"tags",children:[e.jsx(kg,{className:"h-3 w-3 mr-1"}),"Tags"]}),e.jsxs(is,{value:"smartlists",children:[e.jsx(DK,{className:"h-3 w-3 mr-1"}),"Lists"]}),e.jsxs(is,{value:"individual",children:[e.jsx(el,{className:"h-3 w-3 mr-1"}),"Pick"]})]}),e.jsx(cs,{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:rs.length})," contact",rs.length===1?"":"s"," with a valid, non-suppressed email."]})}),e.jsxs(cs,{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(Eo,{className:"h-40 rounded-lg border p-2",children:tt.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."}):tt.map(dn=>e.jsxs("label",{className:"flex items-center gap-2 p-1.5 hover:bg-muted rounded cursor-pointer",children:[e.jsx(Li,{checked:B.includes(dn.id),onCheckedChange:Kt=>U(Er=>Kt?[...Er,dn.id]:Er.filter(ti=>ti!==dn.id))}),e.jsx("span",{className:"inline-block h-2 w-2 rounded-full",style:{background:dn.color||"#406E71"}}),e.jsx("span",{className:"text-sm",children:dn.name})]},dn.id))})]}),e.jsxs(cs,{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(Eo,{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(dn=>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:G===dn.id,onChange:()=>H(dn.id)}),e.jsx("span",{className:"text-sm",children:dn.name})]},dn.id))})]}),e.jsxs(cs,{value:"individual",className:"mt-3 space-y-2",children:[e.jsx(be,{placeholder:"Search contacts...",value:ee,onChange:dn=>oe(dn.target.value)}),e.jsxs("div",{className:"flex items-center justify-between text-xs text-muted-foreground",children:[e.jsxs("span",{children:[Y.size," selected"]}),e.jsx("button",{type:"button",className:"underline",onClick:()=>se(new Set),children:"Clear"})]}),e.jsxs(Eo,{className:"h-48 rounded-lg border p-2",children:[at&&e.jsx("p",{className:"text-xs text-muted-foreground p-2",children:"Loading contacts…"}),!at&&Ts.length===0&&e.jsx("p",{className:"text-xs text-muted-foreground p-2",children:"No matching contacts."}),Ts.slice(0,200).map(dn=>e.jsxs("label",{className:"flex items-center gap-2 p-1.5 hover:bg-muted rounded cursor-pointer",children:[e.jsx(Li,{checked:Y.has(dn.id),onCheckedChange:()=>Zr(dn.id)}),e.jsxs("div",{className:"text-sm flex-1 min-w-0",children:[e.jsxs("div",{className:"truncate",children:[dn.first_name," ",dn.last_name||""]}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:dn.email})]})]},dn.id)),Ts.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(qe,{variant:"secondary",className:"gap-1",children:[e.jsx(Gr,{className:"h-3 w-3"})," ",Bs.length," recipient",Bs.length===1?"":"s"]}),Fn&&e.jsxs(qe,{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(re,{children:"Preview"}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>Q(dn=>!dn),children:me?e.jsxs(e.Fragment,{children:[e.jsx(x0,{className:"h-3 w-3 mr-1"}),"Hide"]}):e.jsxs(e.Fragment,{children:[e.jsx(ba,{className:"h-3 w-3 mr-1"}),"Show"]})})]}),me?e.jsx("div",{className:"rounded-lg border overflow-hidden bg-white",children:e.jsx("iframe",{title:"newsletter-preview",srcDoc:un,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)."]})]})]}),te&&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(Jt,{className:"h-4 w-4 animate-spin"}),"Sending to ",ve.currentName||"..."]}),e.jsxs("span",{className:"text-muted-foreground",children:[ve.sent+ve.failed," / ",ve.total]})]}),e.jsx(ho,{value:ve.total?(ve.sent+ve.failed)/ve.total*100:0}),ve.failed>0&&e.jsxs("p",{className:"text-xs text-destructive",children:[ve.failed," failed"]})]}),e.jsxs("div",{className:"space-y-3 pt-2 border-t",children:[e.jsxs("div",{className:"rounded-lg border bg-muted/20 p-3 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium",children:[e.jsx(sa,{className:"h-4 w-4"})," When to send"]}),e.jsxs(m_,{value:Fe,onValueChange:dn=>Oe(dn),className:"flex flex-col sm:flex-row gap-3",children:[e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[e.jsx(Yh,{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(Yh,{value:"later",id:"send-later"}),e.jsxs("span",{className:"text-sm flex items-center gap-1",children:[e.jsx(wm,{className:"h-3.5 w-3.5"})," Schedule for later"]})]}),Fe==="later"&&e.jsx(be,{type:"datetime-local",value:Ge,onChange:dn=>yt(dn.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:An.length>0?`${An.length} template field${An.length===1?"":"s"} still need${An.length===1?"s":""} your input before this can go out.`:"Suppressed/unsubscribed contacts are skipped automatically. Open & click tracking is included."}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),disabled:te,children:"Cancel"}),e.jsx($,{onClick:xn,disabled:!js,children:te?e.jsxs(e.Fragment,{children:[e.jsx(Jt,{className:"h-4 w-4 mr-1 animate-spin"}),"Working…"]}):Fe==="later"?e.jsxs(e.Fragment,{children:[e.jsx(wm,{className:"h-4 w-4 mr-1"}),"Schedule for ",Bs.length]}):e.jsxs(e.Fragment,{children:[e.jsx(Wr,{className:"h-4 w-4 mr-1"}),"Send to ",Bs.length]})})]})]})]})]}),e.jsx(oc,{open:fe,onOpenChange:_e,children:e.jsxs(Ql,{children:[e.jsxs(Jl,{children:[e.jsx(tc,{children:Fe==="later"?"Schedule newsletter?":"Send newsletter?"}),e.jsxs(sc,{children:[Fe==="later"?"Schedule ":"Send ",e.jsxs("span",{className:"font-medium text-foreground",children:['"',v,'"']})," to"," ",e.jsxs("span",{className:"font-medium text-foreground",children:[Bs.length," contact",Bs.length===1?"":"s"]}),Fe==="later"&&Ge?` for ${new Date(Ge).toLocaleString()}`:"","? Suppressed and unsubscribed contacts are skipped automatically."]})]}),e.jsxs(ec,{children:[e.jsx(nc,{children:"Cancel"}),e.jsx(Vl,{onClick:Ar,children:Fe==="later"?e.jsxs(e.Fragment,{children:[e.jsx(wm,{className:"h-4 w-4 mr-1"}),"Schedule"]}):e.jsxs(e.Fragment,{children:[e.jsx(Wr,{className:"h-4 w-4 mr-1"}),"Send to ",Bs.length]})})]})]})}),e.jsx(zs,{open:Ye,onOpenChange:Ee,children:e.jsxs(Rs,{className:"max-w-2xl max-h-[85vh] overflow-y-auto",children:[e.jsx(Vs,{children:e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(ua,{className:"h-5 w-5"})," Choose listings to insert"]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Pick up to 6 listings. They'll be added as an email-safe grid."}),(st||jt)&&e.jsxs("div",{className:"text-sm text-muted-foreground p-6 text-center",children:[e.jsx(Jt,{className:"h-4 w-4 animate-spin inline-block mr-2"}),"Loading your listings…"]}),!st&&!jt&&xs.length===0&&dt.length===0&&e.jsx("div",{className:"rounded-lg border bg-muted/30 p-6 text-center text-sm text-muted-foreground",children:"No listings found. Add a listing on the Listing Exchange or connect your MLS to get started."}),xs.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-wide text-muted-foreground",children:"From your MLS"}),e.jsx("div",{className:"grid grid-cols-2 gap-3",children:xs.map(dn=>{var Ba,lo;const Kt=`mls:${dn.listing_key}`,Er=Re.has(Kt),ti=Array.isArray(dn.photos)&&dn.photos.length>0?typeof dn.photos[0]=="string"?dn.photos[0]:((Ba=dn.photos[0])==null?void 0:Ba.MediaURL)||((lo=dn.photos[0])==null?void 0:lo.url)||"":"";return e.jsxs("button",{type:"button",onClick:()=>{ke(Yn=>{const Hr=new Set(Yn);return Hr.has(Kt)?Hr.delete(Kt):Hr.size<6?Hr.add(Kt):ae.error("Max 6 listings per newsletter"),Hr})},className:`relative rounded-lg border-2 overflow-hidden text-left transition-all ${Er?"border-primary ring-2 ring-primary/30":"border-border hover:border-primary/50"}`,children:[ti&&e.jsx("img",{src:ti,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:dn.list_price?`$${Number(dn.list_price).toLocaleString()}`:""}),e.jsx("div",{className:"text-xs truncate",children:dn.address}),e.jsxs("div",{className:"text-[11px] text-muted-foreground truncate",children:[dn.city,dn.state?`, ${dn.state}`:""]})]}),Er&&e.jsx("div",{className:"absolute top-1 right-1 bg-primary text-primary-foreground rounded-full p-0.5",children:e.jsx(Gr,{className:"h-4 w-4"})})]},Kt)})})]}),dt.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-wide text-muted-foreground",children:"From your Listing Exchange"}),e.jsx("div",{className:"grid grid-cols-2 gap-3",children:dt.map(dn=>{const Kt=`ex:${dn.id}`,Er=Re.has(Kt);return e.jsxs("button",{type:"button",onClick:()=>{ke(ti=>{const Ba=new Set(ti);return Ba.has(Kt)?Ba.delete(Kt):Ba.size<6?Ba.add(Kt):ae.error("Max 6 listings per newsletter"),Ba})},className:`relative rounded-lg border-2 overflow-hidden text-left transition-all ${Er?"border-primary ring-2 ring-primary/30":"border-border hover:border-primary/50"}`,children:[dn._photo&&e.jsx("img",{src:dn._photo,alt:"",className:"w-full h-32 object-cover"}),e.jsxs("div",{className:"p-2",children:[e.jsx("div",{className:"text-sm font-semibold text-primary",children:dn.price?`$${Number(dn.price).toLocaleString()}`:""}),e.jsx("div",{className:"text-xs truncate",children:dn.property_address}),e.jsxs("div",{className:"text-[11px] text-muted-foreground truncate",children:[dn.city,dn.state?`, ${dn.state}`:""]})]}),Er&&e.jsx("div",{className:"absolute top-1 right-1 bg-primary text-primary-foreground rounded-full p-0.5",children:e.jsx(Gr,{className:"h-4 w-4"})})]},Kt)})})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>Ee(!1),children:"Cancel"}),e.jsxs($,{onClick:Qn,disabled:Re.size===0,children:["Insert ",Re.size>0?Re.size:""," listing",Re.size===1?"":"s"]})]})]})}),e.jsx(XEe,{open:d,onOpenChange:u,hasPending:!!(c!=null&&c.hasPendingSes),pendingEmails:c==null?void 0:c.pendingEmails})]})}function n_n(){const{user:s}=ks(),t=ls(),[n,r]=k.useState("starters"),[a,i]=k.useState(!1),[l,o]=k.useState(null),[c,d]=k.useState(null),[u,h]=k.useState(null),{data:m,isLoading:p}=pt({queryKey:["agent-custom-newsletters",s==null?void 0:s.id],enabled:!!(s!=null&&s.id),queryFn:async()=>{const{data:I,error:P}=await V.from("agent_custom_newsletters").select("*").order("updated_at",{ascending:!1});if(P)throw P;return I||[]}}),g=()=>t.invalidateQueries({queryKey:["agent-custom-newsletters"]}),x=(m==null?void 0:m.filter(I=>I.user_id===(s==null?void 0:s.id)&&!I.is_template))??[],y=(m==null?void 0:m.filter(I=>I.user_id===(s==null?void 0:s.id)&&I.is_template))??[],v=(m==null?void 0:m.filter(I=>I.user_id!==(s==null?void 0:s.id)&&I.is_template&&(I.share_scope==="team"||I.share_scope==="brokerage"||I.share_scope==="global")))??[],_=(m==null?void 0:m.filter(I=>I.share_scope==="global"&&I.is_template))??[],j=n==="starters"?_:n==="mine"?x:n==="templates"?y:v.filter(I=>I.share_scope!=="global"),C=async I=>{if(!s)return;const{error:P}=await V.from("agent_custom_newsletters").insert({user_id:s.id,title:`${I.title} (Copy)`,description:I.description,html_content:I.html_content,is_template:!1,share_scope:"private"});if(P){ae.error(P.message);return}ae.success('Duplicated to "My Newsletters"'),g(),r("mine")},A=async I=>{const{error:P}=await V.from("agent_custom_newsletters").delete().eq("id",I);if(P){ae.error(P.message);return}ae.success("Deleted"),h(null),g()},M=I=>I.share_scope==="global"?e.jsxs(qe,{variant:"secondary",className:"gap-1",children:[e.jsx(kn,{className:"h-3 w-3"}),"Starter"]}):I.share_scope==="brokerage"?e.jsxs(qe,{variant:"secondary",className:"gap-1",children:[e.jsx(Gi,{className:"h-3 w-3"}),"Brokerage"]}):I.share_scope==="team"?e.jsxs(qe,{variant:"secondary",className:"gap-1",children:[e.jsx(Xn,{className:"h-3 w-3"}),"Team"]}):e.jsxs(qe,{variant:"outline",className:"gap-1 text-muted-foreground",children:[e.jsx(fu,{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($,{variant:n==="starters"?"default":"outline",size:"sm",onClick:()=>r("starters"),className:"gap-1.5",children:[e.jsx(kn,{className:"h-3.5 w-3.5"}),"Starter Templates (",_.length,")"]}),e.jsxs($,{variant:n==="mine"?"default":"outline",size:"sm",onClick:()=>r("mine"),children:["My Newsletters (",x.length,")"]}),e.jsxs($,{variant:n==="templates"?"default":"outline",size:"sm",onClick:()=>r("templates"),children:["My Templates (",y.length,")"]}),e.jsxs($,{variant:n==="shared"?"default":"outline",size:"sm",onClick:()=>r("shared"),children:["Shared with Me (",v.filter(I=>I.share_scope!=="global").length,")"]})]}),e.jsxs($,{onClick:()=>{o(null),i(!0)},children:[e.jsx(nn,{className:"h-4 w-4 mr-1.5"})," Create Newsletter"]})]}),p&&e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4",children:[...Array(3)].map((I,P)=>e.jsx(fn,{className:"h-48 w-full"},P))}),n==="starters"&&!p&&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(kn,{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.']})]}),!p&&j.length===0&&e.jsx(we,{children:e.jsxs(De,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(ea,{className:"h-10 w-10 mx-auto mb-3 opacity-50"}),n==="starters"&&e.jsx("p",{children:"No starter templates available yet."}),n==="mine"&&e.jsx("p",{children:`You haven't created any newsletters yet. Try a Starter Template or click "Create Newsletter"!`}),n==="templates"&&e.jsx("p",{children:`You haven't saved any templates yet. Toggle "Save as reusable template" when creating a newsletter.`}),n==="shared"&&e.jsx("p",{children:"No team or brokerage templates have been shared with you yet."})]})}),!p&&j.length>0&&e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4",children:j.map(I=>{const P=I.user_id===(s==null?void 0:s.id);return e.jsxs(we,{className:"overflow-hidden hover:shadow-md transition-shadow",children:[e.jsxs("div",{className:"aspect-[3/2] bg-muted relative overflow-hidden",children:[I.thumbnail_url?e.jsx("img",{src:I.thumbnail_url,alt:I.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:`
${I.html_content}
`}}),e.jsxs("div",{className:"absolute top-2 right-2 flex gap-1",children:[I.is_template&&e.jsx(qe,{className:"bg-primary/90",children:"Template"}),M(I)]})]}),e.jsxs(De,{className:"p-3 space-y-2",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold line-clamp-1",children:I.title}),I.description&&e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-1",children:I.description}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5",children:["Updated ",Ys(new Date(I.updated_at||I.created_at),"MMM d, yyyy")]})]}),e.jsxs("div",{className:"flex gap-1.5 flex-wrap",children:[e.jsxs($,{size:"sm",onClick:()=>d(I),className:"flex-1 min-w-[80px]",children:[e.jsx(Wr,{className:"h-3.5 w-3.5 mr-1"})," Send"]}),P?e.jsxs(e.Fragment,{children:[e.jsx($,{size:"sm",variant:"outline",onClick:()=>{o(I),i(!0)},children:e.jsx(ui,{className:"h-3.5 w-3.5"})}),e.jsx($,{size:"sm",variant:"outline",onClick:()=>C(I),children:e.jsx(Da,{className:"h-3.5 w-3.5"})}),e.jsx($,{size:"sm",variant:"outline",onClick:()=>h(I.id),children:e.jsx(Un,{className:"h-3.5 w-3.5"})})]}):e.jsxs($,{size:"sm",variant:"outline",onClick:()=>C(I),children:[e.jsx(Da,{className:"h-3.5 w-3.5 mr-1"})," Use"]})]})]})]},I.id)})}),e.jsx(qbn,{open:a,onOpenChange:i,initial:l,onSaved:g}),c&&e.jsx(jZe,{open:!!c,onOpenChange:I=>!I&&d(null),newsletterId:c.id,newsletterTitle:c.title,htmlCode:c.html_content}),e.jsx(oc,{open:!!u,onOpenChange:I=>!I&&h(null),children:e.jsxs(Ql,{children:[e.jsxs(Jl,{children:[e.jsx(tc,{children:"Delete this newsletter?"}),e.jsx(sc,{children:"This cannot be undone."})]}),e.jsxs(ec,{children:[e.jsx(nc,{children:"Cancel"}),e.jsx(Vl,{onClick:()=>u&&A(u),children:"Delete"})]})]})})]})}function r_n(){const s=Jn(),[t,n]=k.useState(""),[r,a]=k.useState("grid"),[i,l]=k.useState(null),{data:o,isLoading:c}=pt({queryKey:["newsletters"],queryFn:async()=>{const{data:A,error:M}=await V.from("newsletter_content").select("*").eq("is_published",!0).order("publish_date",{ascending:!1});if(M)throw M;return A}}),{data:d}=pt({queryKey:["newsletter-likes-all"],queryFn:async()=>{const{data:A}=await V.from("newsletter_likes").select("newsletter_id");return A||[]}}),{data:u}=pt({queryKey:["newsletter-comments-all"],queryFn:async()=>{const{data:A}=await V.from("newsletter_comments").select("newsletter_id");return A||[]}}),{data:h}=pt({queryKey:["newsletter-resource-counts"],queryFn:async()=>{const[A,M,I,P]=await Promise.all([V.from("newsletter_canva_links").select("newsletter_id"),V.from("newsletter_pdfs").select("newsletter_id"),V.from("newsletter_videos").select("newsletter_id"),V.from("newsletter_drive_links").select("newsletter_id")]);return{canva:A.data||[],pdfs:M.data||[],videos:I.data||[],drives:P.data||[]}}}),m=A=>(d==null?void 0:d.filter(M=>M.newsletter_id===A).length)||0,p=A=>(u==null?void 0:u.filter(M=>M.newsletter_id===A).length)||0,g=A=>{var M;return((M=h==null?void 0:h.canva)==null?void 0:M.filter(I=>I.newsletter_id===A).length)||0},x=A=>{var M;return((M=h==null?void 0:h.pdfs)==null?void 0:M.filter(I=>I.newsletter_id===A).length)||0},y=A=>{var M;return((M=h==null?void 0:h.videos)==null?void 0:M.filter(I=>I.newsletter_id===A).length)||0},v=A=>{var M;return((M=h==null?void 0:h.drives)==null?void 0:M.filter(I=>I.newsletter_id===A).length)||0},_=A=>g(A)+x(A)+y(A)+v(A),j=o==null?void 0:o.filter(A=>{var M;return A.title.toLowerCase().includes(t.toLowerCase())||((M=A.description)==null?void 0:M.toLowerCase().includes(t.toLowerCase()))}),C=A=>{s(`/newsletters/${A}`)};return e.jsx(Xs,{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(ya,{defaultValue:"custom",className:"space-y-4",children:[e.jsxs(va,{children:[e.jsx(is,{value:"custom",children:"Build & Send"}),e.jsx(is,{value:"curated",children:"Curated Monthly"})]}),e.jsx(cs,{value:"custom",className:"mt-2",children:e.jsx(n_n,{})}),e.jsxs(cs,{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(Yr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search newsletters...",value:t,onChange:A=>n(A.target.value),className:"pl-9"})]}),e.jsxs("div",{className:"flex gap-2",children:[t&&e.jsx($,{variant:"outline",size:"sm",onClick:()=>n(""),children:"Clear"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx($,{variant:r==="grid"?"secondary":"outline",size:"icon",onClick:()=>a("grid"),className:"rounded-full",children:e.jsx(y0,{className:"h-4 w-4"})}),e.jsx($,{variant:r==="list"?"secondary":"outline",size:"icon",onClick:()=>a("list"),className:"rounded-full",children:e.jsx(Sy,{className:"h-4 w-4"})})]})]})]}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[(j==null?void 0:j.length)||0," item",(j==null?void 0:j.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((A,M)=>e.jsx(we,{children:e.jsxs(De,{className:"p-0",children:[e.jsx(fn,{className:"aspect-[3/2] w-full"}),e.jsxs("div",{className:"p-4 space-y-2",children:[e.jsx(fn,{className:"h-5 w-3/4"}),e.jsx(fn,{className:"h-4 w-full"})]})]})},M))}),!c&&(j==null?void 0:j.length)===0&&e.jsxs("div",{className:"text-center py-12",children:[e.jsx(ea,{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($,{variant:"outline",onClick:()=>n(""),children:"Clear Search"})]}),!c&&j&&j.length>0&&e.jsx("div",{className:r==="grid"?"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6":"space-y-3",children:j.map(A=>{const M=_(A.id),I=g(A.id),P=x(A.id),R=y(A.id);return r==="grid"?e.jsxs(we,{className:"group overflow-hidden hover:shadow-lg transition-all duration-200 cursor-pointer border-border/50",onClick:()=>C(A.id),children:[e.jsx("div",{className:"relative overflow-hidden bg-muted aspect-[3/2]",children:A.preview_image_url?e.jsx("img",{src:A.preview_image_url,alt:A.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(ea,{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:A.title}),e.jsxs("div",{className:"flex items-center gap-1.5 mt-1 text-xs text-muted-foreground",children:[e.jsx(ha,{className:"h-3 w-3"}),Ys(new Date(A.publish_date),"MMM d, yyyy")]})]}),A.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2",children:A.description.replace(/<[^>]*>/g,"")}),M>0&&e.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[I>0&&e.jsxs(qe,{variant:"secondary",className:"text-xs gap-1 font-normal",children:[e.jsx(gd,{className:"h-3 w-3"})," ",I," Template",I>1?"s":""]}),P>0&&e.jsxs(qe,{variant:"secondary",className:"text-xs gap-1 font-normal",children:[e.jsx(ji,{className:"h-3 w-3"})," ",P," PDF",P>1?"s":""]}),R>0&&e.jsxs(qe,{variant:"secondary",className:"text-xs gap-1 font-normal",children:[e.jsx(pu,{className:"h-3 w-3"})," ",R," Video",R>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(Ay,{className:"h-3 w-3"})," ",m(A.id)]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Vu,{className:"h-3 w-3"})," ",p(A.id)]})]}),A.html_code&&e.jsxs($,{size:"sm",className:"w-full bg-gradient-to-r from-[#2a4c64] to-[#406E71] text-white hover:opacity-90",onClick:O=>{O.stopPropagation(),l(A)},children:[e.jsx(Wr,{className:"h-4 w-4 mr-1.5"}),"Send Newsletter"]})]})]},A.id):e.jsx(we,{className:"group overflow-hidden hover:shadow-md transition-all duration-200 cursor-pointer border-border/50",onClick:()=>C(A.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:A.preview_image_url?e.jsx("img",{src:A.preview_image_url,alt:A.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(ea,{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:A.title}),e.jsxs("div",{className:"flex items-center gap-1.5 mt-0.5 text-xs text-muted-foreground",children:[e.jsx(ha,{className:"h-3 w-3"}),Ys(new Date(A.publish_date),"MMM d, yyyy")]})]}),A.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-1",children:A.description.replace(/<[^>]*>/g,"")}),e.jsxs("div",{className:"flex items-center gap-4 text-xs text-muted-foreground",children:[M>0&&e.jsxs("span",{children:[M," resource",M>1?"s":""]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ay,{className:"h-3 w-3"})," ",m(A.id)]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Vu,{className:"h-3 w-3"})," ",p(A.id)]})]})]}),A.html_code&&e.jsx("div",{className:"p-3 flex items-center shrink-0",children:e.jsxs($,{size:"sm",className:"bg-gradient-to-r from-[#2a4c64] to-[#406E71] text-white hover:opacity-90",onClick:O=>{O.stopPropagation(),l(A)},children:[e.jsx(Wr,{className:"h-4 w-4 mr-1.5"}),"Send"]})})]})},A.id)})})]})]}),(i==null?void 0:i.html_code)&&e.jsx(jZe,{open:!!i,onOpenChange:A=>!A&&l(null),newsletterId:i.id,newsletterTitle:i.title,htmlCode:i.html_code})]})})}function a_n({rows:s}){if(!s||s.length===0)return null;const t=s.filter(n=>n.columns.some(r=>r.title||r.description||r.image_url));return t.length===0?null:e.jsx("div",{className:"space-y-6",children:t.map((n,r)=>{const a=n.columns.filter(i=>i.title||i.description||i.image_url);return a.length===0?null:e.jsx("div",{className:"grid gap-4",style:{gridTemplateColumns:`repeat(${a.length}, minmax(0, 1fr))`},children:a.map((i,l)=>e.jsxs(we,{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))},r)})})}function i_n(){const{id:s}=oo(),t=Jn(),{user:n}=ks(),{toast:r}=Fi(),a=ls(),{trackEngagement:i}=Xq(),[l,o]=k.useState(""),[c,d]=k.useState(!1),{data:u,isLoading:h}=pt({queryKey:["newsletter",s],queryFn:async()=>{const{data:I,error:P}=await V.from("newsletter_content").select("*").eq("id",s).single();if(P)throw P;return I},enabled:!!s});k.useEffect(()=>{u&&i("newsletter",u.id,u.title,"view")},[u==null?void 0:u.id]);const{data:m}=pt({queryKey:["newsletter-drives",s],queryFn:async()=>{const{data:I}=await V.from("newsletter_drive_links").select("*").eq("newsletter_id",s).order("sort_order");return I||[]},enabled:!!s}),{data:p}=pt({queryKey:["newsletter-pdfs",s],queryFn:async()=>{const{data:I}=await V.from("newsletter_pdfs").select("*").eq("newsletter_id",s).order("sort_order");return I||[]},enabled:!!s}),{data:g}=pt({queryKey:["newsletter-videos",s],queryFn:async()=>{const{data:I}=await V.from("newsletter_videos").select("*").eq("newsletter_id",s).order("sort_order");return I||[]},enabled:!!s}),{data:x}=pt({queryKey:["newsletter-canva-links",s],queryFn:async()=>{const{data:I}=await V.from("newsletter_canva_links").select("*").eq("newsletter_id",s).order("sort_order");return I||[]},enabled:!!s}),{data:y}=pt({queryKey:["newsletter-likes",s],queryFn:async()=>{const{data:I}=await V.from("newsletter_likes").select("*").eq("newsletter_id",s);return I||[]},enabled:!!s}),{data:v}=pt({queryKey:["newsletter-comments",s],queryFn:async()=>{const{data:I}=await V.from("newsletter_comments").select("*, profiles:user_id(name)").eq("newsletter_id",s).order("created_at",{ascending:!1});return I||[]},enabled:!!s}),_=y==null?void 0:y.some(I=>I.user_id===(n==null?void 0:n.id)),j=Nt({mutationFn:async()=>{_?await V.from("newsletter_likes").delete().eq("newsletter_id",s).eq("user_id",n==null?void 0:n.id):await V.from("newsletter_likes").insert({newsletter_id:s,user_id:n==null?void 0:n.id})},onSuccess:()=>{a.invalidateQueries({queryKey:["newsletter-likes",s]})}}),C=Nt({mutationFn:async I=>{const{error:P}=await V.from("newsletter_comments").insert({newsletter_id:s,user_id:n==null?void 0:n.id,content:I});if(P)throw P},onSuccess:()=>{a.invalidateQueries({queryKey:["newsletter-comments",s]}),o(""),r({title:"Comment added"})}}),A=Nt({mutationFn:async I=>{const{error:P}=await V.from("newsletter_comments").delete().eq("id",I);if(P)throw P},onSuccess:()=>{a.invalidateQueries({queryKey:["newsletter-comments",s]}),r({title:"Comment deleted"})}}),M=I=>{if(I.includes("player.mediadelivery.net")||I.includes("iframe.mediadelivery.net")){const P=I.match(/embed\/(\d+)\/([a-f0-9-]+)/);if(P)return e.jsx("div",{className:"relative w-full pt-[56.25%]",children:e.jsx("iframe",{src:`https://iframe.mediadelivery.net/embed/${P[1]}/${P[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(I.includes("youtube.com")||I.includes("youtu.be")){const P=I.match(/(?:youtube\.com\/(?:watch\?v=|embed\/)|youtu\.be\/)([^&\s]+)/);if(P)return e.jsx("div",{className:"relative w-full pt-[56.25%]",children:e.jsx("iframe",{src:`https://www.youtube.com/embed/${P[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:I,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-2 text-primary hover:underline",children:[e.jsx(pu,{className:"h-4 w-4"})," Watch Video"]})};return h?e.jsx(Xs,{title:"",description:"",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(fn,{className:"h-8 w-32"}),e.jsx(fn,{className:"h-64 w-full"}),e.jsx(fn,{className:"h-32 w-full"})]})}):u?e.jsx(Xs,{title:"",description:"",children:e.jsxs("div",{className:"max-w-4xl mx-auto space-y-6",children:[e.jsxs($,{variant:"ghost",onClick:()=>t("/newsletters"),className:"mb-4",children:[e.jsx(Ia,{className:"mr-2 h-4 w-4"})," Back to Newsletters"]}),u.preview_image_url&&e.jsx("img",{src:u.preview_image_url,alt:u.title,className:"w-full h-64 md:h-80 object-cover rounded-lg"}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-3xl font-bold",children:u.title}),e.jsx("p",{className:"text-muted-foreground mt-1",children:Ys(new Date(u.publish_date),"MMMM d, yyyy")})]}),u.description&&e.jsx("div",{className:"text-lg text-muted-foreground prose prose-sm max-w-none dark:prose-invert [&_p]:mb-4 [&_p:last-child]:mb-0 whitespace-pre-line",dangerouslySetInnerHTML:{__html:u.description}}),e.jsx(a_n,{rows:u.content_blocks||[]}),e.jsxs("div",{className:"flex items-center gap-4 flex-wrap",children:[e.jsx(tV,{resourceType:"newsletter",resourceId:u.id,resourceTitle:u.title}),e.jsxs($,{variant:_?"default":"outline",size:"sm",onClick:()=>j.mutate(),children:[e.jsx(Bo,{className:`h-4 w-4 mr-1 ${_?"fill-current":""}`}),(y==null?void 0:y.length)||0," ",(y==null?void 0:y.length)===1?"Like":"Likes"]}),u.html_code&&e.jsxs($,{size:"sm",className:"bg-gradient-to-r from-[#2a4c64] to-[#406E71] text-white hover:opacity-90",onClick:()=>d(!0),children:[e.jsx(Wr,{className:"h-4 w-4 mr-1"}),"Send Newsletter"]})]}),u.html_code&&e.jsx(jZe,{open:c,onOpenChange:d,newsletterId:u.id,newsletterTitle:u.title,htmlCode:u.html_code}),x&&x.length>0&&e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsx(Yt,{className:"text-lg",children:"Canva Templates"})}),e.jsx(De,{className:"space-y-2",children:x.map(I=>e.jsxs("a",{href:I.canva_share_link,target:"_blank",rel:"noopener noreferrer",onClick:()=>i("newsletter",u.id,u.title,"click_canva"),className:"flex items-center gap-3 p-3 rounded-lg hover:bg-muted transition-colors",children:[e.jsx(gd,{className:"h-5 w-5 text-purple-500"}),e.jsx("span",{className:"font-medium",children:I.title}),e.jsx(Ir,{className:"h-4 w-4 text-muted-foreground ml-auto"})]},I.id))})]}),m&&m.length>0&&e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsx(Yt,{className:"text-lg",children:"Google Drive Files"})}),e.jsx(De,{className:"space-y-2",children:m.map(I=>e.jsxs("a",{href:I.drive_url,target:"_blank",rel:"noopener noreferrer",onClick:()=>i("newsletter",u.id,u.title,"click_link"),className:"flex items-center gap-3 p-3 rounded-lg hover:bg-muted transition-colors",children:[e.jsx(Ir,{className:"h-5 w-5 text-primary"}),e.jsx("span",{className:"font-medium",children:I.title})]},I.id))})]}),p&&p.length>0&&e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsx(Yt,{className:"text-lg",children:"PDF Downloads"})}),e.jsx(De,{className:"space-y-2",children:p.map(I=>e.jsxs("a",{href:I.file_url,target:"_blank",rel:"noopener noreferrer",onClick:()=>i("newsletter",u.id,u.title,"click_pdf"),className:"flex items-center gap-3 p-3 rounded-lg hover:bg-muted transition-colors",children:[e.jsx(ea,{className:"h-5 w-5 text-red-500"}),e.jsx("span",{className:"font-medium flex-1",children:I.name}),e.jsx(ji,{className:"h-4 w-4 text-muted-foreground"})]},I.id))})]}),g&&g.length>0&&e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsx(Yt,{className:"text-lg",children:"Videos"})}),e.jsx(De,{className:"space-y-6",children:g.map(I=>e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-medium",children:I.title}),M(I.video_url)]},I.id))})]}),e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsxs(Yt,{className:"text-lg",children:["Comments (",(v==null?void 0:v.length)||0,")"]})}),e.jsxs(De,{className:"space-y-4",children:[e.jsxs("div",{className:"flex gap-3",children:[e.jsx(Ls,{placeholder:"Write a comment...",value:l,onChange:I=>o(I.target.value),className:"flex-1"}),e.jsx($,{onClick:()=>l.trim()&&C.mutate(l),disabled:!l.trim()||C.isPending,children:e.jsx(Wr,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"space-y-4",children:v==null?void 0:v.map(I=>{var P,R,O;return e.jsxs("div",{className:"flex gap-3",children:[e.jsx(Wa,{className:"h-8 w-8",children:e.jsx(Ka,{children:((R=(P=I.profiles)==null?void 0:P.name)==null?void 0:R[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:((O=I.profiles)==null?void 0:O.name)||"User"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:Ys(new Date(I.created_at),"MMM d, yyyy")}),I.user_id===(n==null?void 0:n.id)&&e.jsx($,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>A.mutate(I.id),children:e.jsx(Un,{className:"h-3 w-3"})})]})]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:I.content})]})]},I.id)})})]})]})]})}):e.jsx(Xs,{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($,{variant:"link",onClick:()=>t("/newsletters"),children:"Back to Newsletters"})]})})}function o_n({rows:s,onChange:t}){const[n,r]=k.useState(null),[a,i]=k.useState(null),l=()=>{t([...s,{columns:[{title:"",description:""},{title:"",description:""},{title:"",description:""}]}])},o=h=>{t(s.filter((m,p)=>p!==h))},c=(h,m,p,g)=>{const x=[...s];x[h]={...x[h],columns:x[h].columns.map((y,v)=>v===m?{...y,[p]:g}:y)},t(x)},d=async(h,m,p)=>{var y;const g=(y=p.target.files)==null?void 0:y[0];if(!g)return;const x=`${h}-${m}`;r(x);try{const v=`content-blocks/${Date.now()}-${g.name}`,{error:_}=await V.storage.from("newsletter-content").upload(v,g);if(!_){const{data:j}=V.storage.from("newsletter-content").getPublicUrl(v);c(h,m,"image_url",j.publicUrl)}}finally{r(null)}},u=(h,m)=>{c(h,m,"image_url","")};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(re,{className:"text-base font-medium",children:"Content Blocks (3-Column Rows)"}),e.jsxs($,{type:"button",variant:"outline",size:"sm",onClick:l,children:[e.jsx(nn,{className:"mr-1 h-3 w-3"})," Add Row"]})]}),s.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"No content block rows yet. Add a row to create a 3-column layout."}),s.map((h,m)=>e.jsxs(we,{className:"relative",children:[e.jsx($,{type:"button",variant:"ghost",size:"icon",className:"absolute top-2 right-2 h-6 w-6 text-muted-foreground hover:text-destructive",onClick:()=>o(m),children:e.jsx(mr,{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(Bp,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:["Row ",m+1]})]}),e.jsx("div",{className:"grid grid-cols-3 gap-3",children:h.columns.map((p,g)=>{const x=`${m}-${g}`;return e.jsxs("div",{className:"space-y-2 border border-border/50 rounded-md p-3 bg-muted/20",children:[e.jsxs("span",{className:"text-xs text-muted-foreground font-medium",children:["Column ",g+1]}),p.image_url?e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:p.image_url,alt:"",className:"w-full h-20 object-cover rounded"}),e.jsx($,{type:"button",variant:"destructive",size:"icon",className:"absolute top-1 right-1 h-5 w-5 opacity-0 group-hover:opacity-100 transition-opacity",onClick:()=>u(m,g),children:e.jsx(mr,{className:"h-3 w-3"})})]}):e.jsxs("div",{className:"grid grid-cols-2 gap-1.5",children:[e.jsx(be,{type:"file",accept:"image/*",className:"hidden",id:`block-img-${x}`,onChange:y=>d(m,g,y)}),e.jsx($,{type:"button",variant:"outline",size:"sm",className:"text-xs h-8",disabled:n===x,asChild:!0,children:e.jsx("label",{htmlFor:`block-img-${x}`,className:"cursor-pointer",children:n===x?"...":e.jsxs(e.Fragment,{children:[e.jsx(zc,{className:"h-3 w-3 mr-1"})," Upload"]})})}),e.jsxs($,{type:"button",variant:"outline",size:"sm",className:"text-xs h-8",onClick:()=>i({row:m,col:g}),children:[e.jsx(xb,{className:"h-3 w-3 mr-1"})," Library"]})]}),e.jsx(be,{placeholder:"Title",value:p.title,onChange:y=>c(m,g,"title",y.target.value),className:"h-8 text-sm"}),e.jsx(Ls,{placeholder:"Description",value:p.description,onChange:y=>c(m,g,"description",y.target.value),className:"text-sm min-h-[60px] resize-none"})]},g)})})]})]},m)),e.jsx(zs,{open:!!a,onOpenChange:h=>!h&&i(null),children:e.jsxs(Rs,{className:"sm:max-w-2xl",children:[e.jsx(Vs,{children:e.jsx($s,{children:"Choose a Graphic"})}),e.jsx(HFt,{onSelect:h=>{a&&(c(a.row,a.col,"image_url",h.image_url),i(null))}})]})})]})}function l_n(){const{toast:s}=Fi(),t=ls(),[n,r]=k.useState(!1),[a,i]=k.useState(null),[l,o]=k.useState({title:"",description:"",publish_date:Ys(new Date,"yyyy-MM-dd'T'HH:mm"),is_published:!1}),[c,d]=k.useState(null),[u,h]=k.useState(null),[m,p]=k.useState([]),[g,x]=k.useState([]),[y,v]=k.useState([]),[_,j]=k.useState([]),[C,A]=k.useState([]),[M,I]=k.useState(""),[P,R]=k.useState([]),[O,B]=k.useState(!1),{data:U,isLoading:G}=pt({queryKey:["admin-newsletters"],queryFn:async()=>{const{data:Se,error:Te}=await V.from("newsletter_content").select("*").order("publish_date",{ascending:!1});if(Te)throw Te;return Se}}),H=Nt({mutationFn:async Se=>{const{data:Te,error:Ie}=await V.from("newsletter_content").insert({title:Se.title,description:Se.description||null,preview_image_url:Se.preview_image_url,publish_date:Se.publish_date,is_published:Se.is_published,content_blocks:Se.content_blocks,html_code:Se.html_code}).select().single();if(Ie)throw Ie;return Te},onSuccess:async Se=>{await ee(Se.id),t.invalidateQueries({queryKey:["admin-newsletters"]}),s({title:"Newsletter created successfully"}),Se.is_published&&$Vs(Se.title,Se.id),Q()},onError:Se=>{s({title:"Error creating newsletter",description:Se.message,variant:"destructive"})}}),Y=Nt({mutationFn:async Se=>{const{error:Te}=await V.from("newsletter_content").update({title:Se.title,description:Se.description||null,preview_image_url:Se.preview_image_url,publish_date:Se.publish_date,is_published:Se.is_published,content_blocks:Se.content_blocks,html_code:Se.html_code}).eq("id",Se.id);if(Te)throw Te;return Se.id},onSuccess:async Se=>{await ee(Se),t.invalidateQueries({queryKey:["admin-newsletters"]}),s({title:"Newsletter updated successfully"}),Q()},onError:Se=>{s({title:"Error updating newsletter",description:Se.message,variant:"destructive"})}}),se=Nt({mutationFn:async Se=>{const{error:Te}=await V.from("newsletter_content").delete().eq("id",Se);if(Te)throw Te},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-newsletters"]}),s({title:"Newsletter deleted successfully"})},onError:Se=>{s({title:"Error deleting newsletter",description:Se.message,variant:"destructive"})}}),ee=async Se=>{await V.from("newsletter_drive_links").delete().eq("newsletter_id",Se),await V.from("newsletter_pdfs").delete().eq("newsletter_id",Se),await V.from("newsletter_videos").delete().eq("newsletter_id",Se),await V.from("newsletter_canva_links").delete().eq("newsletter_id",Se);for(const Te of P){const Ie=`${Se}/${Date.now()}-${Te.file.name}`,{error:Ue}=await V.storage.from("newsletter-content").upload(Ie,Te.file);if(!Ue){const{data:Be}=V.storage.from("newsletter-content").getPublicUrl(Ie);g.push({name:Te.name,file_url:Be.publicUrl,file_size:Te.file.size,sort_order:g.length})}}m.length>0&&await V.from("newsletter_drive_links").insert(m.map((Te,Ie)=>({newsletter_id:Se,title:Te.title,drive_url:Te.drive_url,sort_order:Ie}))),g.length>0&&await V.from("newsletter_pdfs").insert(g.map((Te,Ie)=>({newsletter_id:Se,name:Te.name,file_url:Te.file_url,file_size:Te.file_size||null,sort_order:Ie}))),y.length>0&&await V.from("newsletter_videos").insert(y.map((Te,Ie)=>({newsletter_id:Se,title:Te.title,video_url:Te.video_url,sort_order:Ie}))),_.length>0&&await V.from("newsletter_canva_links").insert(_.map((Te,Ie)=>({newsletter_id:Se,title:Te.title,canva_share_link:Te.canva_share_link,sort_order:Ie})))},oe=async Se=>{i(Se),o({title:Se.title,description:Se.description||"",publish_date:Ys(new Date(Se.publish_date),"yyyy-MM-dd'T'HH:mm"),is_published:Se.is_published}),h(Se.preview_image_url),A(Se.content_blocks||[]),I(Se.html_code||"");const[Te,Ie,Ue,Be]=await Promise.all([V.from("newsletter_drive_links").select("*").eq("newsletter_id",Se.id).order("sort_order"),V.from("newsletter_pdfs").select("*").eq("newsletter_id",Se.id).order("sort_order"),V.from("newsletter_videos").select("*").eq("newsletter_id",Se.id).order("sort_order"),V.from("newsletter_canva_links").select("*").eq("newsletter_id",Se.id).order("sort_order")]);p(Te.data||[]),x(Ie.data||[]),v(Ue.data||[]),j(Be.data||[]),R([]),r(!0)},me=async Se=>{const[Te,Ie,Ue,Be]=await Promise.all([V.from("newsletter_drive_links").select("*").eq("newsletter_id",Se.id).order("sort_order"),V.from("newsletter_pdfs").select("*").eq("newsletter_id",Se.id).order("sort_order"),V.from("newsletter_videos").select("*").eq("newsletter_id",Se.id).order("sort_order"),V.from("newsletter_canva_links").select("*").eq("newsletter_id",Se.id).order("sort_order")]);i(null),o({title:`${Se.title} (Copy)`,description:Se.description||"",publish_date:Ys(new Date,"yyyy-MM-dd'T'HH:mm"),is_published:!1}),h(Se.preview_image_url),A(Se.content_blocks||[]),I(Se.html_code||""),p((Te.data||[]).map(({id:je,...Ye})=>Ye)),x((Ie.data||[]).map(({id:je,...Ye})=>Ye)),v((Ue.data||[]).map(({id:je,...Ye})=>Ye)),j((Be.data||[]).map(({id:je,...Ye})=>Ye)),R([]),r(!0)},Q=()=>{r(!1),i(null),o({title:"",description:"",publish_date:Ys(new Date,"yyyy-MM-dd'T'HH:mm"),is_published:!1}),d(null),h(null),p([]),x([]),v([]),j([]),A([]),I(""),R([])},te=async Se=>{var Ie;const Te=(Ie=Se.target.files)==null?void 0:Ie[0];Te&&(d(Te),h(URL.createObjectURL(Te)))},le=async()=>{if(!l.title){s({title:"Title is required",variant:"destructive"});return}B(!0);let Se=u;if(c){const Te=`previews/${Date.now()}-${c.name}`,{error:Ie}=await V.storage.from("newsletter-content").upload(Te,c);if(!Ie){const{data:Ue}=V.storage.from("newsletter-content").getPublicUrl(Te);Se=Ue.publicUrl}}a?Y.mutate({id:a.id,...l,preview_image_url:Se,content_blocks:C,html_code:M||null}):H.mutate({...l,preview_image_url:Se,content_blocks:C,html_code:M||null}),B(!1)},fe=()=>p([...m,{title:"",drive_url:"",sort_order:m.length}]),_e=()=>v([...y,{title:"",video_url:"",sort_order:y.length}]),ve=()=>j([..._,{title:"",canva_share_link:"",sort_order:_.length}]),he=Se=>{const Te=Se.target.files;if(!Te)return;const Ie=Array.from(Te).map(Ue=>({file:Ue,name:Ue.name.replace(/\.[^/.]+$/,"")}));R([...P,...Ie])};return e.jsx(Xs,{title:"Newsletter Content",description:"Manage monthly newsletter templates and resources",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(nm,{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(we,{children:[e.jsx(Vt,{className:"pb-2",children:e.jsx(Yt,{className:"text-sm font-medium text-muted-foreground",children:"Total"})}),e.jsx(De,{children:e.jsx("div",{className:"text-2xl font-bold",children:(U==null?void 0:U.length)||0})})]}),e.jsxs(we,{children:[e.jsx(Vt,{className:"pb-2",children:e.jsx(Yt,{className:"text-sm font-medium text-muted-foreground",children:"Published"})}),e.jsx(De,{children:e.jsx("div",{className:"text-2xl font-bold",children:(U==null?void 0:U.filter(Se=>Se.is_published).length)||0})})]})]}),e.jsxs(zs,{open:n,onOpenChange:Se=>!Se&&Q(),children:[e.jsx(yl,{asChild:!0,children:e.jsxs($,{onClick:()=>r(!0),children:[e.jsx(nn,{className:"mr-2 h-4 w-4"})," Add Newsletter"]})}),e.jsxs(Rs,{className:"max-w-4xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Vs,{children:e.jsx($s,{children:a?"Edit Newsletter":"Add Newsletter"})}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Title *"}),e.jsx(be,{value:l.title,onChange:Se=>o({...l,title:Se.target.value}),placeholder:"Newsletter title"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Publish Date"}),e.jsx(be,{type:"datetime-local",value:l.publish_date,onChange:Se=>o({...l,publish_date:Se.target.value})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Description"}),e.jsx(V2,{content:l.description,onChange:Se=>o({...l,description:Se}),placeholder:"Newsletter description",minHeight:"120px"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Preview Image"}),e.jsxs("div",{className:"flex items-center gap-4",children:[u&&e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:u,alt:"Preview",className:"h-20 w-32 object-cover rounded-md"}),e.jsx($,{type:"button",variant:"destructive",size:"icon",className:"absolute -top-2 -right-2 h-5 w-5 opacity-0 group-hover:opacity-100 transition-opacity",onClick:()=>{d(null),h(null)},children:e.jsx(mr,{className:"h-3 w-3"})})]}),e.jsxs("div",{children:[e.jsx(be,{type:"file",accept:"image/*",onChange:te,className:"hidden",id:"preview-upload"}),e.jsx($,{variant:"outline",asChild:!0,children:e.jsxs("label",{htmlFor:"preview-upload",className:"cursor-pointer",children:[e.jsx(gi,{className:"mr-2 h-4 w-4"})," Upload Image"]})})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(On,{checked:l.is_published,onCheckedChange:Se=>o({...l,is_published:Se})}),e.jsx(re,{children:"Published"})]}),e.jsx(o_n,{rows:C,onChange:A}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(re,{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:M,onChange:Se=>I(Se.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(re,{className:"text-base font-medium",children:"Canva Links"}),e.jsxs($,{type:"button",variant:"outline",size:"sm",onClick:ve,children:[e.jsx(nn,{className:"mr-1 h-3 w-3"})," Add Canva Link"]})]}),_.map((Se,Te)=>e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx(be,{placeholder:"Link title",value:Se.title,onChange:Ie=>{const Ue=[..._];Ue[Te].title=Ie.target.value,j(Ue)},className:"w-1/3"}),e.jsx(be,{placeholder:"Canva share link",value:Se.canva_share_link,onChange:Ie=>{const Ue=[..._];Ue[Te].canva_share_link=Ie.target.value,j(Ue)},className:"flex-1"}),e.jsx($,{type:"button",variant:"ghost",size:"icon",onClick:()=>j(_.filter((Ie,Ue)=>Ue!==Te)),children:e.jsx(mr,{className:"h-4 w-4"})})]},Te))]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(re,{className:"text-base font-medium",children:"Google Drive Links"}),e.jsxs($,{type:"button",variant:"outline",size:"sm",onClick:fe,children:[e.jsx(nn,{className:"mr-1 h-3 w-3"})," Add Link"]})]}),m.map((Se,Te)=>e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx(be,{placeholder:"Link title",value:Se.title,onChange:Ie=>{const Ue=[...m];Ue[Te].title=Ie.target.value,p(Ue)},className:"w-1/3"}),e.jsx(be,{placeholder:"Google Drive URL",value:Se.drive_url,onChange:Ie=>{const Ue=[...m];Ue[Te].drive_url=Ie.target.value,p(Ue)},className:"flex-1"}),e.jsx($,{type:"button",variant:"ghost",size:"icon",onClick:()=>p(m.filter((Ie,Ue)=>Ue!==Te)),children:e.jsx(mr,{className:"h-4 w-4"})})]},Te))]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(re,{className:"text-base font-medium",children:"PDF Files"}),e.jsxs("div",{children:[e.jsx(be,{type:"file",accept:".pdf",multiple:!0,onChange:he,className:"hidden",id:"pdf-upload"}),e.jsx($,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("label",{htmlFor:"pdf-upload",className:"cursor-pointer",children:[e.jsx(gi,{className:"mr-1 h-3 w-3"})," Upload PDF"]})})]})]}),g.map((Se,Te)=>e.jsxs("div",{className:"flex gap-2 items-center bg-muted/50 p-2 rounded",children:[e.jsx(ea,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"flex-1 text-sm",children:Se.name}),e.jsx($,{type:"button",variant:"ghost",size:"icon",onClick:()=>x(g.filter((Ie,Ue)=>Ue!==Te)),children:e.jsx(mr,{className:"h-4 w-4"})})]},`existing-${Te}`)),P.map((Se,Te)=>e.jsxs("div",{className:"flex gap-2 items-center bg-muted/50 p-2 rounded",children:[e.jsx(ea,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(be,{value:Se.name,onChange:Ie=>{const Ue=[...P];Ue[Te].name=Ie.target.value,R(Ue)},className:"flex-1 h-8",placeholder:"PDF name"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"(new)"}),e.jsx($,{type:"button",variant:"ghost",size:"icon",onClick:()=>R(P.filter((Ie,Ue)=>Ue!==Te)),children:e.jsx(mr,{className:"h-4 w-4"})})]},`pending-${Te}`))]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(re,{className:"text-base font-medium",children:"Video Links"}),e.jsxs($,{type:"button",variant:"outline",size:"sm",onClick:_e,children:[e.jsx(nn,{className:"mr-1 h-3 w-3"})," Add Video"]})]}),y.map((Se,Te)=>e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx(be,{placeholder:"Video title",value:Se.title,onChange:Ie=>{const Ue=[...y];Ue[Te].title=Ie.target.value,v(Ue)},className:"w-1/3"}),e.jsx(be,{placeholder:"Video URL",value:Se.video_url,onChange:Ie=>{const Ue=[...y];Ue[Te].video_url=Ie.target.value,v(Ue)},className:"flex-1"}),e.jsx($,{type:"button",variant:"ghost",size:"icon",onClick:()=>v(y.filter((Ie,Ue)=>Ue!==Te)),children:e.jsx(mr,{className:"h-4 w-4"})})]},Te))]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4 border-t",children:[e.jsx($,{variant:"outline",onClick:Q,children:"Cancel"}),e.jsx($,{onClick:le,disabled:O||H.isPending||Y.isPending,children:O?"Uploading...":a?"Update":"Create"})]})]})]})]})]}),e.jsx(we,{children:e.jsx(De,{className:"p-0",children:e.jsxs(Qa,{children:[e.jsx(Ja,{children:e.jsxs(vn,{children:[e.jsx(Dt,{children:"Name"}),e.jsx(Dt,{children:"Publish Date"}),e.jsx(Dt,{children:"Status"}),e.jsx(Dt,{className:"text-right",children:"Actions"})]})}),e.jsx(ei,{children:G?e.jsx(vn,{children:e.jsx(_t,{colSpan:4,className:"text-center py-8",children:"Loading..."})}):(U==null?void 0:U.length)===0?e.jsx(vn,{children:e.jsx(_t,{colSpan:4,className:"text-center py-8 text-muted-foreground",children:"No newsletters yet. Create your first one!"})}):U==null?void 0:U.map(Se=>e.jsxs(vn,{children:[e.jsx(_t,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[Se.preview_image_url?e.jsx("img",{src:Se.preview_image_url,alt:Se.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(ea,{className:"h-5 w-5 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:Se.title}),Se.description&&e.jsx("div",{className:"text-sm text-muted-foreground line-clamp-1",children:Se.description.replace(/<[^>]*>/g,"")})]})]})}),e.jsx(_t,{children:Ys(new Date(Se.publish_date),"MMM d, yyyy")}),e.jsx(_t,{children:e.jsx("span",{className:`inline-flex items-center px-2 py-1 rounded-full text-xs font-medium ${Se.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:Se.is_published?"Published":"Draft"})}),e.jsx(_t,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-1",children:[e.jsx($,{variant:"ghost",size:"icon",onClick:()=>oe(Se),title:"Edit",children:e.jsx(ui,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>me(Se),title:"Duplicate",children:e.jsx(Da,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",title:"Delete",onClick:async()=>{await io("Are you sure you want to delete this newsletter?")&&se.mutate(Se.id)},children:e.jsx(Un,{className:"h-4 w-4"})})]})})]},Se.id))})]})})})]})})}const c_n={status:"all",billing:"all",role:"all",brokerage:"all",joinedWithinDays:null};function d_n({brokerages:s}){var A;const{toast:t}=Fi(),[n,r]=k.useState(c_n),[a,i]=k.useState(""),[l,o]=k.useState(""),[c,d]=k.useState(""),[u,h]=k.useState(null),[m,p]=k.useState(!1),[g,x]=k.useState(!1),[y,v]=k.useState(null),_=(M,I)=>r(P=>({...P,[M]:I}));k.useEffect(()=>{const M=setTimeout(async()=>{p(!0);try{const{data:I,error:P}=await V.functions.invoke("admin-broadcast-sms",{body:{action:"preview",filters:n,sms_body:a||"Sample message"}});if(P)throw P;h(I)}catch{h(null)}finally{p(!1)}},450);return()=>clearTimeout(M)},[n,a]);const j=async()=>{if(!c||!a.trim()){t({title:"Add a test number and message",variant:"destructive"});return}x(!0);const{data:M,error:I}=await V.functions.invoke("admin-broadcast-sms",{body:{action:"test",to:c,sms_body:a}});if(x(!1),I||M!=null&&M.error){t({title:"Test failed",description:(M==null?void 0:M.error)||(I==null?void 0:I.message),variant:"destructive"});return}t({title:"Test text sent",description:`Sent to ${c}`})},C=async()=>{const M=(u==null?void 0:u.count)||0;if(!(!a.trim()||M===0||!await io({title:"Send text broadcast?",description:`This will text ${M} member${M===1?"":"s"} who have a recorded SMS opt-in. Texts cannot be recalled.`,confirmText:"Send broadcast"}))){x(!0),v({total:M,sent:0,failed:0});try{const{data:P,error:R}=await V.functions.invoke("admin-broadcast-sms",{body:{action:"queue",name:l||a.slice(0,60),sms_body:a,filters:n}});if(R||P!=null&&P.error)throw new Error((P==null?void 0:P.error)||(R==null?void 0:R.message));let O=0,B=0,U=P.total,G=0;for(;U>0&&G++<400;){const{data:H,error:Y}=await V.functions.invoke("admin-broadcast-sms",{body:{action:"process",broadcast_id:P.broadcast_id,limit:40}});if(Y||H!=null&&H.error)throw new Error((H==null?void 0:H.error)||(Y==null?void 0:Y.message));if(H.deferred){t({title:"Paused for quiet hours",description:H.reason});break}O+=H.sent||0,B+=H.failed||0,U=H.remaining||0,v({total:M,sent:O,failed:B})}t({title:"Broadcast complete",description:`${O} sent${B?`, ${B} failed`:""}.`})}catch(P){t({title:"Broadcast failed",description:P.message,variant:"destructive"})}finally{x(!1)}}};return e.jsxs("div",{className:"grid gap-6 lg:grid-cols-[340px_1fr]",children:[e.jsx("div",{className:"space-y-4",children:e.jsxs(we,{children:[e.jsxs(Vt,{className:"pb-3",children:[e.jsxs(Yt,{className:"flex items-center gap-2 text-base",children:[e.jsx(b0,{className:"h-4 w-4"})," SMS Audience"]}),e.jsx(vr,{children:"Only members with a recorded consent date and source are included. Opted-out and undeliverable numbers are always excluded."})]}),e.jsxs(De,{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{className:"text-xs",children:"Account status"}),e.jsxs(bs,{value:n.status,onValueChange:M=>_("status",M),children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"all",children:"All members"}),e.jsx(We,{value:"active",children:"Signed in before"}),e.jsx(We,{value:"pending",children:"Never signed in"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{className:"text-xs",children:"Billing"}),e.jsxs(bs,{value:n.billing,onValueChange:M=>_("billing",M),children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"all",children:"All"}),e.jsx(We,{value:"trial",children:"On trial"}),e.jsx(We,{value:"paid",children:"Paid"}),e.jsx(We,{value:"grandfathered",children:"Grandfathered"}),e.jsx(We,{value:"canceled",children:"Canceled / past due"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{className:"text-xs",children:"Role"}),e.jsxs(bs,{value:n.role,onValueChange:M=>_("role",M),children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"all",children:"All roles"}),e.jsx(We,{value:"user",children:"Agents"}),e.jsx(We,{value:"brokerage_manager",children:"Brokerage managers"}),e.jsx(We,{value:"coach",children:"Coaches"}),e.jsx(We,{value:"admin",children:"Admins"})]})]})]}),!!(s!=null&&s.length)&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{className:"text-xs",children:"Brokerage"}),e.jsxs(bs,{value:n.brokerage,onValueChange:M=>_("brokerage",M),children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"all",children:"All brokerages"}),e.jsx(We,{value:"none",children:"No brokerage"}),s.map(M=>e.jsx(We,{value:M.id,children:M.name},M.id))]})]})]}),e.jsxs("div",{className:"rounded-lg border bg-muted/30 p-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"SMS-eligible members"}),e.jsx("span",{className:"text-lg font-semibold",children:m?e.jsx(Jt,{className:"h-4 w-4 animate-spin"}):(u==null?void 0:u.count)??0})]}),(A=u==null?void 0:u.sample)!=null&&A.length?e.jsxs("p",{className:"mt-2 text-xs text-muted-foreground",children:["e.g. ",u.sample.slice(0,3).map(M=>M.name||M.phone).join(", ")]}):null]}),u&&!u.quiet_hours_ok&&e.jsxs("div",{className:"flex items-start gap-2 rounded-lg border border-amber-500/40 bg-amber-500/10 p-3 text-xs",children:[e.jsx(sa,{className:"mt-0.5 h-3.5 w-3.5 shrink-0"}),e.jsx("span",{children:"Outside the 9:00 AM – 8:00 PM ET sending window. Queued texts will be held and resumed instead of sent now."})]})]})]})}),e.jsx("div",{className:"space-y-4",children:e.jsxs(we,{children:[e.jsxs(Vt,{className:"pb-3",children:[e.jsxs(Yt,{className:"flex items-center gap-2 text-base",children:[e.jsx(bo,{className:"h-4 w-4"})," Text message"]}),e.jsxs(vr,{children:["Merge tags: ",e.jsx("code",{children:"{{first_name}}"})," ",e.jsx("code",{children:"{{name}}"}),'. The LevelUp prefix and "Reply STOP to opt out" are added automatically.']})]}),e.jsxs(De,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{htmlFor:"sms-broadcast-name",className:"text-xs",children:"Internal name"}),e.jsx(be,{id:"sms-broadcast-name",value:l,onChange:M=>o(M.target.value),placeholder:"August member update"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{htmlFor:"sms-broadcast-body",className:"text-xs",children:"Message"}),e.jsx(Ls,{id:"sms-broadcast-body",value:a,onChange:M=>i(M.target.value),rows:5,maxLength:480,placeholder:"Hi {{first_name}} — join us Thursday at 11am ET for the LevelUp Live session on listing videos."}),e.jsxs("div",{className:"flex items-center justify-between text-xs text-muted-foreground",children:[e.jsxs("span",{children:[(u==null?void 0:u.length)??a.length," characters"]}),e.jsxs(qe,{variant:((u==null?void 0:u.segments)??1)>2?"destructive":"secondary",children:[(u==null?void 0:u.segments)??1," segment",((u==null?void 0:u.segments)??1)===1?"":"s"]})]})]}),(u==null?void 0:u.composed)&&e.jsxs("div",{className:"rounded-lg border bg-muted/30 p-3",children:[e.jsx("p",{className:"mb-1 text-xs font-medium text-muted-foreground",children:"Preview as delivered"}),e.jsx("p",{className:"whitespace-pre-wrap text-sm",children:u.composed})]}),e.jsxs("div",{className:"flex flex-wrap items-end gap-2",children:[e.jsxs("div",{className:"flex-1 space-y-1.5",style:{minWidth:200},children:[e.jsx(re,{htmlFor:"sms-test-phone",className:"text-xs",children:"Send a test to"}),e.jsx(be,{id:"sms-test-phone",value:c,onChange:M=>d(M.target.value),placeholder:"(555) 123-4567",type:"tel"})]}),e.jsxs($,{variant:"outline",onClick:j,disabled:g,children:[g&&e.jsx(Jt,{className:"mr-2 h-4 w-4 animate-spin"})," Send test"]})]}),y&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ho,{value:y.total?(y.sent+y.failed)/y.total*100:0}),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(Gr,{className:"h-3 w-3"})," ",y.sent," sent"]}),y.failed>0&&e.jsxs("span",{className:"flex items-center gap-1 text-destructive",children:[e.jsx(Ho,{className:"h-3 w-3"})," ",y.failed," failed"]}),e.jsxs("span",{children:["of ",y.total]})]})]}),e.jsxs($,{onClick:C,disabled:g||!a.trim()||!(u!=null&&u.count),className:"w-full",children:[g?e.jsx(Jt,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(Wr,{className:"mr-2 h-4 w-4"}),"Send to ",(u==null?void 0:u.count)??0," member",((u==null?void 0:u.count)??0)===1?"":"s"]})]})]})})]})}const ORe={status:"all",billing:"all",role:"all",brokerage:"all",joinedWithinDays:null,respectOptOut:!0,program:"all",programStatus:"active"},u_n=["{{first_name}}","{{name}}","{{email}}"];function h_n(s){return`${s||'

Your email preview will appear here…

'}`}function m_n(){var et;const{toast:s}=Fi(),{user:t}=ks(),n=ls(),[r,a]=k.useState("filters"),[i,l]=k.useState([]),[o,c]=k.useState(""),[d,u]=k.useState([]),[h,m]=k.useState(!1),[p,g]=k.useState(""),[x,y]=k.useState(!1),[v,_]=k.useState(ORe),[j,C]=k.useState(null),[A,M]=k.useState(!1),[I,P]=k.useState(""),[R,O]=k.useState(""),[B,U]=k.useState(""),[G,H]=k.useState(""),[Y,se]=k.useState("rich"),[ee,oe]=k.useState(""),[me,Q]=k.useState(""),[te,le]=k.useState(""),[fe,_e]=k.useState(!1),[ve,he]=k.useState(null),Se=Y==="rich"?ee:me;k.useEffect(()=>{t!=null&&t.email&&(U(at=>at||t.email),H(at=>at||t.email),le(at=>at||t.email))},[t==null?void 0:t.email]);const{data:Te}=pt({queryKey:["broadcast-brokerages"],queryFn:async()=>{const{data:at}=await V.from("brokerages").select("id, name").order("name");return at||[]}}),{data:Ie}=pt({queryKey:["broadcast-programs"],queryFn:async()=>{const{data:at}=await V.from("programs").select("id, name").order("created_at",{ascending:!1});return at||[]}}),{data:Ue}=pt({queryKey:["admin-broadcasts"],queryFn:async()=>{const{data:at,error:wt}=await V.from("admin_broadcasts").select("*").order("created_at",{ascending:!1}).limit(30);if(wt)throw wt;return at}}),{data:Be}=pt({queryKey:["admin-broadcast-templates"],queryFn:async()=>{const{data:at,error:wt}=await V.from("admin_broadcast_templates").select("*").order("updated_at",{ascending:!1});if(wt)throw wt;return at}}),je=async at=>{M(!0);try{const{data:wt,error:rt}=await V.functions.invoke("admin-broadcast",{body:{action:"preview",filters:at}});if(rt)throw rt;if(wt!=null&&wt.error)throw new Error(wt.error);C(wt)}catch(wt){s({title:"Could not load audience",description:wt.message,variant:"destructive"})}finally{M(!1)}};k.useEffect(()=>{if(r!=="filters")return;const at=setTimeout(()=>je(v),400);return()=>clearTimeout(at)},[v,r]),k.useEffect(()=>{if(r!=="manual")return;const at=setTimeout(async()=>{m(!0);try{const{data:wt,error:rt}=await V.functions.invoke("admin-broadcast",{body:{action:"search_members",query:o}});if(rt)throw rt;u((wt==null?void 0:wt.members)||[])}catch{u([])}finally{m(!1)}},350);return()=>clearTimeout(at)},[o,r]);const Ye=(at,wt)=>_(rt=>({...rt,[at]:wt})),Ee=r==="manual"?i.length:(j==null?void 0:j.count)||0,Re=()=>r==="manual"?{recipient_mode:"manual",manual_emails:i.map(at=>at.email)}:{recipient_mode:"filters",filters:v},ke=at=>l(wt=>wt.some(rt=>rt.email.toLowerCase()===at.email.toLowerCase())?wt.filter(rt=>rt.email.toLowerCase()!==at.email.toLowerCase()):[...wt,at]),Fe=async()=>{const at=(p||I||R).trim();if(!at||!Se.trim()){s({title:"Add a template name and content first",variant:"destructive"});return}y(!0);try{const{error:wt}=await V.from("admin_broadcast_templates").insert({created_by:t.id,name:at,subject:R,body_html:Se,editor_mode:Y,from_email:B||null,reply_to_email:G||null,filters:v});if(wt)throw wt;g(""),s({title:"Template saved",description:`"${at}" is available for future sends.`}),n.invalidateQueries({queryKey:["admin-broadcast-templates"]})}catch(wt){s({title:"Could not save template",description:wt.message,variant:"destructive"})}finally{y(!1)}},Oe=at=>{P(at.name||""),O(at.subject||""),at.from_email&&U(at.from_email),at.reply_to_email&&H(at.reply_to_email);const wt=at.editor_mode==="html"?"html":"rich";se(wt),wt==="html"?Q(at.body_html||""):oe(at.body_html||""),at.filters&&Object.keys(at.filters).length&&_({...ORe,...at.filters}),s({title:"Template loaded",description:"Edit and send when ready."})},Ge=async at=>{if(!await io(`Delete template "${at.name}"?`))return;const{error:wt}=await V.from("admin_broadcast_templates").delete().eq("id",at.id);if(wt){s({title:"Delete failed",description:wt.message,variant:"destructive"});return}n.invalidateQueries({queryKey:["admin-broadcast-templates"]})},yt=k.useMemo(()=>!!R.trim()&&!!Se.trim()&&!!B.trim()&&Ee>0,[R,Se,B,Ee]),tt=async()=>{if(!te||!R.trim()||!Se.trim()){s({title:"Add a subject, content and test address first",variant:"destructive"});return}try{const{data:at,error:wt}=await V.functions.invoke("admin-broadcast",{body:{action:"test",to:te,subject:R,html:Se,from_email:B,reply_to:G||void 0}});if(wt)throw wt;if(at!=null&&at.error)throw new Error(at.error);s({title:"Test sent",description:`Check ${te}`})}catch(at){s({title:"Test failed",description:at.message,variant:"destructive"})}},ut=async()=>{const at=Ee;if(await io({title:"Send this broadcast?",description:`"${R}" will be emailed to ${at} member${at===1?"":"s"}. Sent emails can't be recalled.`,confirmText:"Send broadcast",cancelText:"Cancel",destructive:!1})){_e(!0),he({total:at,sent:0,failed:0});try{const{data:rt,error:Ft}=await V.functions.invoke("admin-broadcast",{body:{action:"queue",name:I||R,subject:R,html:Se,from_email:B,reply_to:G||void 0,...Re()}});if(Ft)throw Ft;if(rt!=null&&rt.error)throw new Error(rt.error);let Ut=0,Is=0,xs=rt.total,st=0;for(;xs>0;){const{data:dt,error:jt}=await V.functions.invoke("admin-broadcast",{body:{action:"process",broadcast_id:rt.broadcast_id,limit:40}});if(jt)throw jt;if(dt!=null&&dt.error)throw new Error(dt.error);if(Ut+=dt.sent,Is+=dt.failed,xs=dt.remaining,he({total:rt.total,sent:Ut,failed:Is}),dt.throttled){const gt=Math.min(Math.max(Number(dt.retry_after_ms)||15e3,5e3),45e3);await new Promise(rs=>setTimeout(rs,gt));continue}if(dt.sent===0&&dt.failed===0){if(++st>=3)break;await new Promise(gt=>setTimeout(gt,5e3))}else st=0}s({title:"Broadcast complete",description:`${Ut} sent${Is?`, ${Is} failed`:""}`}),n.invalidateQueries({queryKey:["admin-broadcasts"]})}catch(rt){s({title:"Send failed",description:rt.message,variant:"destructive"})}finally{_e(!1)}}},nt=async at=>{_e(!0);try{const{data:wt,error:rt}=await V.functions.invoke("admin-broadcast",{body:{action:"retry_failed",broadcast_id:at}});if(rt)throw rt;if(wt!=null&&wt.error)throw new Error(wt.error);let Ft=0,Ut=0,Is=wt.requeued,xs=0;for(he({total:Is,sent:0,failed:0});Is>0;){const{data:st,error:dt}=await V.functions.invoke("admin-broadcast",{body:{action:"process",broadcast_id:at,limit:25}});if(dt)throw dt;if(st!=null&&st.error)throw new Error(st.error);if(Ft+=st.sent,Ut+=st.failed,Is=st.remaining,he({total:wt.requeued,sent:Ft,failed:Ut}),st.throttled){await new Promise(jt=>setTimeout(jt,Math.min(Math.max(Number(st.retry_after_ms)||15e3,5e3),45e3)));continue}if(st.sent===0&&st.failed===0){if(++xs>=3)break;await new Promise(jt=>setTimeout(jt,5e3))}else xs=0}s({title:"Retry complete",description:`${Ft} sent${Ut?`, ${Ut} still failed`:""}`}),n.invalidateQueries({queryKey:["admin-broadcasts"]})}catch(wt){s({title:"Retry failed",description:wt.message,variant:"destructive"})}finally{_e(!1)}};return e.jsx(Xs,{children:e.jsxs("div",{className:"space-y-6 p-4 md:p-8",children:[e.jsx(nm,{title:"Member Broadcasts",description:"Send a one-off email to a filtered slice of LevelUp members"}),e.jsxs(ya,{defaultValue:"compose",className:"space-y-6",children:[e.jsxs(va,{children:[e.jsxs(is,{value:"compose",className:"gap-2",children:[e.jsx(pn,{className:"h-4 w-4"})," Compose"]}),e.jsxs(is,{value:"sms",className:"gap-2",children:[e.jsx(bo,{className:"h-4 w-4"})," Text (SMS)"]}),e.jsxs(is,{value:"templates",className:"gap-2",children:[e.jsx(Zw,{className:"h-4 w-4"})," Templates"]}),e.jsxs(is,{value:"history",className:"gap-2",children:[e.jsx(b2,{className:"h-4 w-4"})," History"]})]}),e.jsx(cs,{value:"sms",className:"space-y-6",children:e.jsx(d_n,{brokerages:Te})}),e.jsx(cs,{value:"compose",className:"space-y-6",children:e.jsxs("div",{className:"grid gap-6 lg:grid-cols-[340px_1fr]",children:[e.jsx("div",{className:"space-y-4",children:e.jsxs(we,{className:"overflow-hidden",children:[e.jsxs("div",{className:"bg-gradient-to-br from-primary/90 to-primary p-5 text-primary-foreground",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm opacity-90",children:[e.jsx(Xn,{className:"h-4 w-4"})," Audience"]}),e.jsxs("div",{className:"mt-2 flex items-baseline gap-2",children:[e.jsx("span",{className:"text-4xl font-bold",children:r==="manual"?i.length:A?"—":(j==null?void 0:j.count)??0}),e.jsx("span",{className:"text-sm opacity-90",children:r==="manual"?"members selected":"members match"})]})]}),e.jsxs(De,{className:"space-y-4 pt-5",children:[e.jsx(ya,{value:r,onValueChange:at=>a(at),children:e.jsxs(va,{className:"grid w-full grid-cols-2",children:[e.jsxs(is,{value:"filters",className:"gap-1.5 text-xs",children:[e.jsx(Xn,{className:"h-3.5 w-3.5"})," Filters"]}),e.jsxs(is,{value:"manual",className:"gap-1.5 text-xs",children:[e.jsx(Pl,{className:"h-3.5 w-3.5"})," Individuals"]})]})}),r==="manual"&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Find members"}),e.jsxs("div",{className:"relative",children:[e.jsx(Yr,{className:"pointer-events-none absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground"}),e.jsx(be,{value:o,onChange:at=>c(at.target.value),placeholder:"Search by name or email",className:"pl-8"})]})]}),i.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1.5",children:i.map(at=>e.jsxs(qe,{variant:"secondary",className:"gap-1",children:[e.jsx("span",{className:"max-w-[150px] truncate",children:at.name||at.email}),e.jsx("button",{type:"button",onClick:()=>ke(at),"aria-label":`Remove ${at.email}`,children:e.jsx(mr,{className:"h-3 w-3"})})]},at.email))}),e.jsx("div",{className:"max-h-72 space-y-1 overflow-y-auto rounded-lg border p-1",children:h?e.jsx("p",{className:"p-3 text-xs text-muted-foreground",children:"Searching…"}):d.length===0?e.jsx("p",{className:"p-3 text-xs text-muted-foreground",children:"No members found."}):d.map(at=>{const wt=i.some(rt=>rt.email.toLowerCase()===at.email.toLowerCase());return e.jsxs("button",{type:"button",onClick:()=>ke(at),className:`flex w-full items-center justify-between rounded-md px-2.5 py-2 text-left text-xs hover:bg-muted ${wt?"bg-muted":""}`,children:[e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:"block truncate font-medium",children:at.name||"Member"}),e.jsx("span",{className:"block truncate text-muted-foreground",children:at.email})]}),wt&&e.jsx(Gr,{className:"h-4 w-4 shrink-0 text-primary"})]},at.id)})})]}),r==="filters"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Account status"}),e.jsxs(bs,{value:v.status,onValueChange:at=>Ye("status",at),children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"all",children:"All members"}),e.jsx(We,{value:"active",children:"Active (signed in)"}),e.jsx(We,{value:"pending",children:"Pending (never signed in)"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Membership"}),e.jsxs(bs,{value:v.billing,onValueChange:at=>Ye("billing",at),children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"all",children:"Any membership"}),e.jsx(We,{value:"trial",children:"On trial"}),e.jsx(We,{value:"paid",children:"Paid subscribers"}),e.jsx(We,{value:"grandfathered",children:"Grandfathered"}),e.jsx(We,{value:"canceled",children:"Canceled / past due"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Role"}),e.jsxs(bs,{value:v.role,onValueChange:at=>Ye("role",at),children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"all",children:"Any role"}),e.jsx(We,{value:"user",children:"Members"}),e.jsx(We,{value:"brokerage_manager",children:"Brokerage managers"}),e.jsx(We,{value:"coach",children:"Coaches"}),e.jsx(We,{value:"assistant",children:"Assistants"}),e.jsx(We,{value:"admin",children:"Admins"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Brokerage"}),e.jsxs(bs,{value:v.brokerage,onValueChange:at=>Ye("brokerage",at),children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsxs(vs,{className:"max-h-72",children:[e.jsx(We,{value:"all",children:"All brokerages"}),e.jsx(We,{value:"none",children:"No brokerage"}),(Te||[]).map(at=>e.jsx(We,{value:at.id,children:at.name},at.id))]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Program enrollment"}),e.jsxs(bs,{value:v.program,onValueChange:at=>Ye("program",at),children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsxs(vs,{className:"max-h-72",children:[e.jsx(We,{value:"all",children:"Not filtered by program"}),e.jsx(We,{value:"any",children:"Enrolled in any program"}),(Ie||[]).map(at=>e.jsx(We,{value:at.id,children:at.name},at.id))]})]})]}),v.program!=="all"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Enrollment status"}),e.jsxs(bs,{value:v.programStatus,onValueChange:at=>Ye("programStatus",at),children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"active",children:"Active enrollees (paid, reserved, completed)"}),e.jsx(We,{value:"any",children:"Any enrollment status"}),e.jsx(We,{value:"paid",children:"Paid"}),e.jsx(We,{value:"reserved",children:"Reserved"}),e.jsx(We,{value:"scheduled_for_charge",children:"Scheduled for charge"}),e.jsx(We,{value:"pending_payment_method",children:"Pending payment method"}),e.jsx(We,{value:"payment_failed",children:"Payment failed"}),e.jsx(We,{value:"completed",children:"Completed"}),e.jsx(We,{value:"canceled",children:"Canceled"}),e.jsx(We,{value:"refunded",children:"Refunded"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Joined within"}),e.jsxs(bs,{value:v.joinedWithinDays?String(v.joinedWithinDays):"all",onValueChange:at=>Ye("joinedWithinDays",at==="all"?null:Number(at)),children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"all",children:"Any time"}),e.jsx(We,{value:"30",children:"Last 30 days"}),e.jsx(We,{value:"60",children:"Last 60 days"}),e.jsx(We,{value:"90",children:"Last 90 days"})]})]})]}),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:"Respect opt-outs"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Skip members who opted out of updates"})]}),e.jsx(On,{checked:v.respectOptOut,onCheckedChange:at=>Ye("respectOptOut",at)})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx($,{variant:"ghost",size:"sm",onClick:()=>_(ORe),children:"Reset"}),e.jsxs($,{variant:"outline",size:"sm",className:"gap-2",onClick:()=>je(v),disabled:A,children:[A?e.jsx(Jt,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(yo,{className:"h-3.5 w-3.5"}),"Refresh"]})]}),(et=j==null?void 0:j.sample)!=null&&et.length?e.jsxs("div",{className:"rounded-lg bg-muted/40 p-3",children:[e.jsx("p",{className:"mb-2 text-xs font-medium text-muted-foreground",children:"Sample recipients"}),e.jsx("div",{className:"space-y-1",children:j.sample.map(at=>e.jsxs("p",{className:"truncate text-xs",children:[e.jsx("span",{className:"font-medium",children:at.name||"Member"})," ",e.jsx("span",{className:"text-muted-foreground",children:at.email})]},at.email))})]}):null]})]})]})}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs(we,{children:[e.jsxs(Vt,{className:"pb-4",children:[e.jsx(Yt,{className:"text-base",children:"Message"}),e.jsxs(vr,{children:["Personalize with merge tags: ",u_n.join(" ")]})]}),e.jsxs(De,{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Internal name"}),e.jsx(be,{value:I,onChange:at=>P(at.target.value),placeholder:"August product update"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Subject line"}),e.jsx(be,{value:R,onChange:at=>O(at.target.value),placeholder:"Big news for LevelUp members"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"From (must be a verified sender)"}),e.jsx(be,{value:B,onChange:at=>U(at.target.value),placeholder:"hello@relevelup.com"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Reply-to"}),e.jsx(be,{value:G,onChange:at=>H(at.target.value),placeholder:"support@relevelup.com"})]})]}),e.jsxs(ya,{value:Y,onValueChange:at=>se(at),children:[e.jsxs(va,{children:[e.jsxs(is,{value:"rich",className:"gap-2",children:[e.jsx(kn,{className:"h-3.5 w-3.5"})," Rich text"]}),e.jsxs(is,{value:"html",className:"gap-2",children:[e.jsx($T,{className:"h-3.5 w-3.5"})," Paste HTML"]})]}),e.jsx(cs,{value:"rich",className:"mt-3",children:e.jsx(V2,{content:ee,onChange:oe,minHeight:"320px",placeholder:"Write your message…"})}),e.jsxs(cs,{value:"html",className:"mt-3 space-y-2",children:[e.jsx(Ls,{value:me,onChange:at=>Q(at.target.value),placeholder:"…paste your full email HTML here…",className:"min-h-[320px] font-mono text-xs"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Paste full HTML from Canva, Beefree, Mailchimp, etc. It is sent exactly as written (merge tags still work)."})]})]})]})]}),e.jsxs(we,{children:[e.jsxs(Vt,{className:"flex flex-row items-center justify-between space-y-0 pb-3",children:[e.jsxs(Yt,{className:"flex items-center gap-2 text-base",children:[e.jsx(ba,{className:"h-4 w-4"})," Preview"]}),e.jsx(qe,{variant:"secondary",children:Y==="html"?"Raw HTML":"Rich text"})]}),e.jsx(De,{children:e.jsx("iframe",{title:"Email preview",srcDoc:h_n(Se),className:"h-[420px] w-full rounded-lg border bg-white"})})]}),e.jsx(we,{children:e.jsxs(De,{className:"space-y-4 pt-6",children:[ve&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsxs("span",{children:[ve.sent+ve.failed," of ",ve.total," processed"]}),e.jsxs("span",{className:"text-muted-foreground",children:[ve.sent," sent",ve.failed?` • ${ve.failed} failed`:""]})]}),e.jsx(ho,{value:ve.total?(ve.sent+ve.failed)/ve.total*100:0})]}),e.jsxs("div",{className:"flex flex-wrap items-end gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Send a test to"}),e.jsx(be,{value:te,onChange:at=>le(at.target.value),className:"w-64"})]}),e.jsx($,{variant:"outline",onClick:tt,disabled:fe,children:"Send test"}),e.jsx("div",{className:"flex-1"}),e.jsxs($,{onClick:ut,disabled:!yt||fe,size:"lg",className:"gap-2",children:[fe?e.jsx(Jt,{className:"h-4 w-4 animate-spin"}):e.jsx(Wr,{className:"h-4 w-4"}),fe?"Sending…":`Send to ${Ee} member${Ee===1?"":"s"}`]})]}),e.jsxs("div",{className:"flex flex-wrap items-end gap-3 border-t pt-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Save as template"}),e.jsx(be,{value:p,onChange:at=>g(at.target.value),placeholder:I||R||"Template name",className:"w-64"})]}),e.jsxs($,{variant:"outline",className:"gap-2",onClick:Fe,disabled:x,children:[x?e.jsx(Jt,{className:"h-4 w-4 animate-spin"}):e.jsx(BT,{className:"h-4 w-4"}),"Save template"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Saves the subject, content, sender and current filters for reuse later."})]})]})})]})]})}),e.jsx(cs,{value:"templates",className:"space-y-3",children:(Be||[]).length===0?e.jsx(we,{children:e.jsxs(De,{className:"flex flex-col items-center py-14 text-center",children:[e.jsx(Zw,{className:"mb-3 h-10 w-10 text-muted-foreground"}),e.jsx("p",{className:"font-medium",children:"No saved templates yet"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:'Compose an email, then use "Save template" to reuse it for future sends.'})]})}):(Be||[]).map(at=>e.jsx(we,{children:e.jsxs(De,{className:"flex flex-wrap items-center justify-between gap-4 py-4",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"truncate text-sm font-semibold",children:at.name}),e.jsx(qe,{variant:"secondary",className:"text-xs",children:at.editor_mode==="html"?"Raw HTML":"Rich text"})]}),e.jsxs("p",{className:"truncate text-xs text-muted-foreground",children:["Subject: ",at.subject||"—"]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Updated ",Ys(new Date(at.updated_at),"MMM d, yyyy h:mm a")]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs($,{size:"sm",className:"gap-2",onClick:()=>Oe(at),children:[e.jsx(Ml,{className:"h-3.5 w-3.5"})," Use template"]}),e.jsx($,{size:"sm",variant:"ghost",onClick:()=>Ge(at),children:e.jsx(Un,{className:"h-3.5 w-3.5"})})]})]})},at.id))}),e.jsx(cs,{value:"history",className:"space-y-3",children:(Ue||[]).length===0?e.jsx(we,{children:e.jsxs(De,{className:"flex flex-col items-center py-14 text-center",children:[e.jsx(pn,{className:"mb-3 h-10 w-10 text-muted-foreground"}),e.jsx("p",{className:"font-medium",children:"No broadcasts sent yet"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Your sent member emails will show up here."})]})}):(Ue||[]).map(at=>e.jsx(we,{children:e.jsxs(De,{className:"flex flex-wrap items-center justify-between gap-4 py-4",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"truncate text-sm font-semibold",children:at.name}),e.jsxs(qe,{variant:at.status==="sent"?"default":at.status==="sending"?"secondary":"outline",className:"gap-1 text-xs",children:[at.status==="sent"?e.jsx(Gr,{className:"h-3 w-3"}):e.jsx(Ho,{className:"h-3 w-3"}),at.status]})]}),e.jsxs("p",{className:"truncate text-xs text-muted-foreground",children:["Subject: ",at.subject]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[Ys(new Date(at.created_at),"MMM d, yyyy h:mm a")," • from ",at.from_email]})]}),e.jsxs("div",{className:"flex gap-6 text-center",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-lg font-bold",children:at.total_recipients}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Recipients"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-lg font-bold",children:at.sent_count}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Sent"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-lg font-bold",children:at.failed_count}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Failed"})]}),e.jsxs("div",{children:[e.jsxs("p",{className:"text-lg font-bold",children:[at.open_count??0,at.sent_count>0&&e.jsxs("span",{className:"ml-1 text-xs font-medium text-muted-foreground",children:[Math.round((at.open_count??0)/at.sent_count*100),"%"]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Opens"})]}),e.jsxs("div",{children:[e.jsxs("p",{className:"text-lg font-bold",children:[at.click_count??0,at.sent_count>0&&e.jsxs("span",{className:"ml-1 text-xs font-medium text-muted-foreground",children:[Math.round((at.click_count??0)/at.sent_count*100),"%"]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Clicks"})]}),at.failed_count>0&&e.jsx("div",{className:"flex items-center",children:e.jsx($,{size:"sm",variant:"outline",disabled:fe,onClick:()=>nt(at.id),children:"Retry failed"})})]})]})},at.id))})]})]})})}const f_n=["Headers","Footers","Seasonal","Holidays","Market Updates","Just Sold","Just Listed","Open House","Buyer Tips","Seller Tips","Testimonials","CTAs & Buttons","Dividers","General"];function p_n(){const s=ls(),t=k.useRef(null),[n,r]=k.useState(""),[a,i]=k.useState("all"),[l,o]=k.useState(null),[c,d]=k.useState(!1),[u,h]=k.useState(!1),[m,p]=k.useState({title:"",description:"",image_url:"",category:"General",tags:"",is_active:!0,is_featured:!1}),{data:g=[],isLoading:x}=pt({queryKey:["admin-newsletter-graphics"],queryFn:async()=>{const{data:B,error:U}=await V.from("newsletter_graphics").select("*").order("is_featured",{ascending:!1}).order("created_at",{ascending:!1});if(U)throw U;return B||[]}}),y=k.useMemo(()=>{const B=new Set(f_n);return g.forEach(U=>B.add(U.category)),Array.from(B).sort()},[g]),v=k.useMemo(()=>{const B=n.trim().toLowerCase();return g.filter(U=>a!=="all"&&U.category!==a?!1:B?U.title.toLowerCase().includes(B)||(U.description||"").toLowerCase().includes(B)||U.tags.some(G=>G.toLowerCase().includes(B)):!0)},[g,n,a]),_=()=>{p({title:"",description:"",image_url:"",category:"General",tags:"",is_active:!0,is_featured:!1}),o(null)},j=()=>{_(),d(!0)},C=B=>{o(B),p({title:B.title,description:B.description||"",image_url:B.image_url,category:B.category,tags:B.tags.join(", "),is_active:B.is_active,is_featured:B.is_featured}),d(!0)},A=async B=>{var U;if(!B.type.startsWith("image/")){ae.error("Please choose an image file");return}if(B.size>15*1024*1024){ae.error("Image must be under 15MB");return}h(!0);try{const G=((U=B.name.split(".").pop())==null?void 0:U.toLowerCase())||"png",H=`graphics-library/${Date.now()}-${Math.random().toString(36).slice(2,8)}.${G}`,{error:Y}=await V.storage.from("newsletter-content").upload(H,B,{cacheControl:"31536000",upsert:!1,contentType:B.type});if(Y)throw Y;const{data:se}=V.storage.from("newsletter-content").getPublicUrl(H);p(ee=>({...ee,image_url:se.publicUrl,title:ee.title||B.name.replace(/\.[^.]+$/,"").replace(/[-_]/g," ")})),ae.success("Uploaded")}catch(G){ae.error(G.message||"Upload failed")}finally{h(!1),t.current&&(t.current.value="")}},M=Nt({mutationFn:async()=>{var G;if(!m.image_url)throw new Error("Please upload an image");if(!m.title.trim())throw new Error("Please add a title");const B=m.tags.split(",").map(H=>H.trim()).filter(Boolean),U={title:m.title.trim(),description:m.description.trim()||null,image_url:m.image_url,category:m.category||"General",tags:B,is_active:m.is_active,is_featured:m.is_featured};if(l){const{error:H}=await V.from("newsletter_graphics").update(U).eq("id",l.id);if(H)throw H}else{const{data:H}=await V.auth.getUser(),{error:Y}=await V.from("newsletter_graphics").insert({...U,created_by:(G=H.user)==null?void 0:G.id});if(Y)throw Y}},onSuccess:()=>{ae.success(l?"Updated":"Graphic added to library"),s.invalidateQueries({queryKey:["admin-newsletter-graphics"]}),s.invalidateQueries({queryKey:["newsletter-graphics-picker"]}),d(!1),_()},onError:B=>ae.error(B.message||"Save failed")}),I=Nt({mutationFn:async B=>{const{error:U}=await V.from("newsletter_graphics").delete().eq("id",B);if(U)throw U},onSuccess:()=>{ae.success("Deleted"),s.invalidateQueries({queryKey:["admin-newsletter-graphics"]}),s.invalidateQueries({queryKey:["newsletter-graphics-picker"]})},onError:B=>ae.error(B.message||"Delete failed")}),P=async B=>{const{error:U}=await V.from("newsletter_graphics").update({is_active:!B.is_active}).eq("id",B.id);U?ae.error(U.message):(s.invalidateQueries({queryKey:["admin-newsletter-graphics"]}),s.invalidateQueries({queryKey:["newsletter-graphics-picker"]}))},R=async B=>{const{error:U}=await V.from("newsletter_graphics").update({is_featured:!B.is_featured}).eq("id",B.id);U?ae.error(U.message):(s.invalidateQueries({queryKey:["admin-newsletter-graphics"]}),s.invalidateQueries({queryKey:["newsletter-graphics-picker"]}))},O=B=>{navigator.clipboard.writeText(B),ae.success("URL copied")};return e.jsxs(Xs,{children:[e.jsxs("div",{className:"p-4 md:p-6 max-w-7xl mx-auto space-y-5",children:[e.jsx(nm,{title:"Newsletter Graphics Library",description:"Upload branded graphics agents can drop into their newsletters and email campaigns."}),e.jsx(we,{children:e.jsxs(De,{className:"p-4 flex flex-col md:flex-row gap-3 md:items-center",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Yr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{value:n,onChange:B=>r(B.target.value),placeholder:"Search graphics by title, tag, description...",className:"pl-9"})]}),e.jsxs(bs,{value:a,onValueChange:i,children:[e.jsx(ys,{className:"w-full md:w-56",children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"all",children:"All categories"}),y.map(B=>e.jsx(We,{value:B,children:B},B))]})]}),e.jsxs($,{onClick:j,className:"gap-1.5 whitespace-nowrap",children:[e.jsx(gb,{className:"h-4 w-4"})," Add Graphic"]})]})}),x?e.jsx("div",{className:"flex justify-center py-16",children:e.jsx(Jt,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):v.length===0?e.jsx(we,{children:e.jsxs(De,{className:"py-16 text-center",children:[e.jsx(zc,{className:"h-10 w-10 mx-auto mb-3 text-muted-foreground/50"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:g.length===0?"No graphics uploaded yet — add your first one to get started.":"No graphics match your filters."}),g.length===0&&e.jsxs($,{onClick:j,className:"gap-1.5",children:[e.jsx(gb,{className:"h-4 w-4"})," Upload First Graphic"]})]})}):e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4",children:v.map(B=>e.jsxs(we,{className:`overflow-hidden group ${B.is_active?"":"opacity-60"}`,children:[e.jsxs("div",{className:"aspect-video bg-muted relative overflow-hidden",children:[e.jsx("img",{src:B.image_url,alt:B.title,loading:"lazy",className:"w-full h-full object-cover"}),B.is_featured&&e.jsxs(qe,{className:"absolute top-2 left-2 gap-0.5 bg-amber-500 hover:bg-amber-500 text-white border-0",children:[e.jsx(ri,{className:"h-3 w-3 fill-current"})," Featured"]}),!B.is_active&&e.jsx(qe,{variant:"secondary",className:"absolute top-2 right-2",children:"Hidden"})]}),e.jsxs(De,{className:"p-3 space-y-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm truncate",children:B.title}),e.jsx("p",{className:"text-xs text-muted-foreground",children:B.category})]}),B.tags.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1",children:B.tags.slice(0,3).map(U=>e.jsx(qe,{variant:"outline",className:"text-[10px] px-1.5 py-0",children:U},U))}),e.jsxs("div",{className:"flex items-center justify-between pt-1 border-t",children:[e.jsxs("div",{className:"flex gap-1",children:[e.jsx($,{size:"icon",variant:"ghost",className:"h-7 w-7",onClick:()=>C(B),title:"Edit",children:e.jsx(ui,{className:"h-3.5 w-3.5"})}),e.jsx($,{size:"icon",variant:"ghost",className:"h-7 w-7",onClick:()=>R(B),title:B.is_featured?"Unfeature":"Feature",children:e.jsx(ri,{className:`h-3.5 w-3.5 ${B.is_featured?"fill-amber-500 text-amber-500":""}`})}),e.jsx($,{size:"icon",variant:"ghost",className:"h-7 w-7",onClick:()=>O(B.image_url),title:"Copy URL",children:e.jsx(Da,{className:"h-3.5 w-3.5"})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(On,{checked:B.is_active,onCheckedChange:()=>P(B)}),e.jsx($,{size:"icon",variant:"ghost",className:"h-7 w-7 text-destructive hover:text-destructive",onClick:async()=>{await io(`Delete "${B.title}"?`)&&I.mutate(B.id)},children:e.jsx(Un,{className:"h-3.5 w-3.5"})})]})]})]})]},B.id))})]}),e.jsx(zs,{open:c,onOpenChange:d,children:e.jsxs(Rs,{className:"sm:max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(Vs,{children:e.jsx($s,{children:l?"Edit Graphic":"Add New Graphic"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Image"}),e.jsx("input",{ref:t,type:"file",accept:"image/*",className:"hidden",onChange:B=>{var G;const U=(G=B.target.files)==null?void 0:G[0];U&&A(U)}}),m.image_url?e.jsxs("div",{className:"relative rounded-lg overflow-hidden border bg-muted/30 mt-1.5",children:[e.jsx("img",{src:m.image_url,alt:"Preview",className:"w-full max-h-64 object-contain"}),e.jsx($,{type:"button",variant:"destructive",size:"icon",className:"absolute top-2 right-2 h-7 w-7",onClick:()=>p(B=>({...B,image_url:""})),children:e.jsx(mr,{className:"h-3.5 w-3.5"})})]}):e.jsx("button",{type:"button",onClick:()=>{var B;return(B=t.current)==null?void 0:B.click()},disabled:u,className:"w-full mt-1.5 rounded-lg border-2 border-dashed border-border hover:border-primary/50 hover:bg-muted/40 transition-colors py-10 text-center disabled:opacity-60",children:u?e.jsxs(e.Fragment,{children:[e.jsx(Jt,{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(gi,{className:"h-8 w-8 mx-auto mb-2 text-muted-foreground"}),e.jsx("p",{className:"text-sm font-medium",children:"Click to upload image"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"PNG, JPG, WEBP, GIF · up to 15MB"})]})})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"g-title",children:"Title *"}),e.jsx(be,{id:"g-title",value:m.title,onChange:B=>p(U=>({...U,title:B.target.value})),placeholder:"e.g. Fall Market Update Banner"})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"g-desc",children:"Description"}),e.jsx(Ls,{id:"g-desc",value:m.description,onChange:B=>p(U=>({...U,description:B.target.value})),placeholder:"Short note about when to use this graphic",rows:2})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Category"}),e.jsxs(bs,{value:m.category,onValueChange:B=>p(U=>({...U,category:B})),children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsx(vs,{children:y.map(B=>e.jsx(We,{value:B,children:B},B))})]})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"g-tags",children:"Tags (comma-separated)"}),e.jsx(be,{id:"g-tags",value:m.tags,onChange:B=>p(U=>({...U,tags:B.target.value})),placeholder:"fall, autumn, banner"})]})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-md border p-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Featured"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Show at top of the picker"})]}),e.jsx(On,{checked:m.is_featured,onCheckedChange:B=>p(U=>({...U,is_featured:B}))})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-md border p-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Active"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Visible to agents"})]}),e.jsx(On,{checked:m.is_active,onCheckedChange:B=>p(U=>({...U,is_active:B}))})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>d(!1),children:"Cancel"}),e.jsxs($,{onClick:()=>M.mutate(),disabled:M.isPending,children:[M.isPending&&e.jsx(Jt,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}),l?"Save Changes":"Add to Library"]})]})]})})]})}const Ext={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 g_n(){const{user:s}=ks(),{toast:t}=Fi(),n=Jn(),r=ls(),[a,i]=k.useState(""),[l,o]=k.useState("popular"),[c,d]=k.useState(!1),[u,h]=k.useState(""),[m,p]=k.useState(""),[g,x]=k.useState(!1),{data:y=[],isLoading:v}=pt({queryKey:["wishlist-items",l,g],queryFn:async()=>{let M=V.from("wishlist_items").select("*");g&&s&&(M=M.eq("user_id",s.id)),l==="latest"?M=M.order("created_at",{ascending:!1}):l==="popular"?M=M.order("vote_count",{ascending:!1}):l==="trending"&&(M=M.order("vote_count",{ascending:!1}));const{data:I,error:P}=await M;if(P)throw P;const R=[...new Set((I==null?void 0:I.map(se=>se.user_id))||[])],{data:O}=await V.from("profiles").select("id, name").in("id",R),B=new Map((O==null?void 0:O.map(se=>[se.id,se]))||[]);let U=[];if(s){const{data:se}=await V.from("wishlist_votes").select("item_id").eq("user_id",s.id);U=(se==null?void 0:se.map(ee=>ee.item_id))||[]}const G=(I==null?void 0:I.map(se=>se.id))||[],{data:H}=await V.from("wishlist_comments").select("item_id").in("item_id",G),Y=new Map;return H==null||H.forEach(se=>{Y.set(se.item_id,(Y.get(se.item_id)||0)+1)}),I==null?void 0:I.map(se=>{const ee=B.get(se.user_id),oe=(ee==null?void 0:ee.name)||"Unknown";return{...se,user_name:oe,user_initials:oe.split(" ").map(me=>me[0]).join("").toUpperCase().slice(0,2),has_voted:U.includes(se.id),comment_count:Y.get(se.id)||0}})}}),_=Nt({mutationFn:async({title:M,description:I})=>{const{error:P}=await V.from("wishlist_items").insert({user_id:s.id,title:M,description:I});if(P)throw P},onSuccess:()=>{r.invalidateQueries({queryKey:["wishlist-items"]}),d(!1),h(""),p(""),t({title:"Idea submitted!",description:"Your idea has been added to the wishlist."})},onError:M=>{t({title:"Error",description:M.message,variant:"destructive"})}}),j=Nt({mutationFn:async({itemId:M,hasVoted:I})=>{if(I){const{error:P}=await V.from("wishlist_votes").delete().eq("item_id",M).eq("user_id",s.id);if(P)throw P;return{itemId:M,wasAdded:!1}}else{const{error:P}=await V.from("wishlist_votes").insert({item_id:M,user_id:s.id});if(P)throw P;return{itemId:M,wasAdded:!0}}},onSuccess:async M=>{if(r.invalidateQueries({queryKey:["wishlist-items"]}),M!=null&&M.wasAdded){const I=y.find(R=>R.id===M.itemId),P=((I==null?void 0:I.vote_count)||0)+1;V.functions.invoke("wishlist-notify",{body:{itemId:M.itemId,voteCount:P}}).catch(console.error)}},onError:M=>{t({title:"Error",description:M.message,variant:"destructive"})}}),C=y.filter(M=>M.title.toLowerCase().includes(a.toLowerCase())||M.description.toLowerCase().includes(a.toLowerCase())),A=()=>{if(!u.trim()||!m.trim()){t({title:"Error",description:"Please fill in both title and description.",variant:"destructive"});return}_.mutate({title:u.trim(),description:m.trim()})};return e.jsx(Xs,{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(P5,{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(zs,{open:c,onOpenChange:d,children:[e.jsx(yl,{asChild:!0,children:e.jsxs($,{className:"gap-2",children:[e.jsx(nn,{className:"h-4 w-4"}),"Add Idea"]})}),e.jsxs(Rs,{children:[e.jsx(Vs,{children:e.jsx($s,{children:"Submit a New Idea"})}),e.jsxs("div",{className:"space-y-4 pt-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"title",children:"Title"}),e.jsx(be,{id:"title",placeholder:"Give your idea a clear title...",value:u,onChange:M=>h(M.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"description",children:"Description"}),e.jsx(Ls,{id:"description",placeholder:"Describe your idea in detail. What problem does it solve? How would it help agents?",value:m,onChange:M=>p(M.target.value),rows:4})]}),e.jsx($,{onClick:A,className:"w-full",disabled:_.isPending,children:_.isPending?e.jsxs(e.Fragment,{children:[e.jsx(Jt,{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(Yr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search ideas...",value:a,onChange:M=>i(M.target.value),className:"pl-10"})]}),e.jsx("div",{className:"flex gap-2",children:e.jsx(ya,{value:l,onValueChange:M=>o(M),children:e.jsxs(va,{children:[e.jsx(is,{value:"popular",children:"Most Popular"}),e.jsx(is,{value:"latest",children:"Latest"}),e.jsx(is,{value:"trending",children:"Trending"})]})})})]}),e.jsx("div",{className:"flex items-center gap-2 mb-4",children:e.jsx($,{variant:g?"default":"outline",size:"sm",onClick:()=>x(!g),children:g?"Show All Ideas":"My Ideas"})}),v?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(Jt,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):C.length===0?e.jsxs("div",{className:"text-center py-12 bg-muted/30 rounded-lg",children:[e.jsx(P5,{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($,{onClick:()=>d(!0),children:[e.jsx(nn,{className:"h-4 w-4 mr-2"}),"Add Idea"]})]}):e.jsx("div",{className:"space-y-3",children:C.map(M=>e.jsx("div",{className:"bg-card border rounded-lg p-4 hover:shadow-md transition-shadow cursor-pointer",onClick:()=>n(`/wishlist/${M.id}`),children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsxs("button",{onClick:I=>{I.stopPropagation(),j.mutate({itemId:M.id,hasVoted:M.has_voted||!1})},className:Ot("flex flex-col items-center justify-center min-w-[50px] py-2 px-3 rounded-lg border transition-colors",M.has_voted?"bg-primary/10 border-primary text-primary":"bg-muted/50 border-border hover:bg-muted"),children:[e.jsx(ap,{className:Ot("h-4 w-4",M.has_voted&&"fill-current")}),e.jsx("span",{className:"text-sm font-semibold",children:M.vote_count})]}),e.jsx(Wa,{className:"h-10 w-10 bg-primary/20",children:e.jsx(Ka,{className:"bg-primary/20 text-primary text-sm font-medium",children:M.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:M.title}),e.jsx(qe,{className:Ot("text-xs",Ext[M.status].color),children:Ext[M.status].label})]}),e.jsx("p",{className:"text-muted-foreground text-sm line-clamp-2",children:M.description}),e.jsxs("div",{className:"flex items-center gap-3 mt-2 text-xs text-muted-foreground",children:[e.jsx("span",{children:M.user_name}),e.jsx("span",{children:"•"}),e.jsx("span",{children:new Date(M.created_at).toLocaleDateString()})]})]}),e.jsxs("div",{className:"flex items-center gap-1 text-muted-foreground",children:[e.jsx(bo,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm",children:M.comment_count})]})]})},M.id))})]})})}const Txt={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 x_n(){const{itemId:s}=oo(),t=Jn(),{user:n}=ks(),{toast:r}=Fi(),a=ls(),[i,l]=k.useState(""),{data:o=!1}=pt({queryKey:["user-is-admin",n==null?void 0:n.id],queryFn:async()=>{if(!n)return!1;const{data:y,error:v}=await V.from("user_roles").select("role").eq("user_id",n.id).eq("role","admin").maybeSingle();return!v&&!!y},enabled:!!n}),{data:c,isLoading:d}=pt({queryKey:["wishlist-item",s],queryFn:async()=>{const{data:y,error:v}=await V.from("wishlist_items").select("*").eq("id",s).single();if(v)throw v;const{data:_}=await V.from("profiles").select("name").eq("id",y.user_id).single();let j=!1;if(n){const{data:C}=await V.from("wishlist_votes").select("id").eq("item_id",s).eq("user_id",n.id).maybeSingle();j=!!C}return{...y,user_name:(_==null?void 0:_.name)||"Unknown",user_initials:((_==null?void 0:_.name)||"U").split(" ").map(C=>C[0]).join("").toUpperCase().slice(0,2),has_voted:j}}}),{data:u=[],isLoading:h}=pt({queryKey:["wishlist-comments",s],queryFn:async()=>{const{data:y,error:v}=await V.from("wishlist_comments").select("*").eq("item_id",s).order("created_at",{ascending:!0});if(v)throw v;const _=[...new Set((y==null?void 0:y.map(A=>A.user_id))||[])],{data:j}=await V.from("profiles").select("id, name").in("id",_),C=new Map((j==null?void 0:j.map(A=>[A.id,A]))||[]);return y==null?void 0:y.map(A=>{const M=C.get(A.user_id),I=(M==null?void 0:M.name)||"Unknown";return{...A,user_name:I,user_initials:I.split(" ").map(P=>P[0]).join("").toUpperCase().slice(0,2)}})}}),m=Nt({mutationFn:async y=>{if(y){const{error:v}=await V.from("wishlist_votes").delete().eq("item_id",s).eq("user_id",n.id);if(v)throw v;return{wasAdded:!1}}else{const{error:v}=await V.from("wishlist_votes").insert({item_id:s,user_id:n.id});if(v)throw v;return{wasAdded:!0}}},onSuccess:async y=>{if(a.invalidateQueries({queryKey:["wishlist-item",s]}),a.invalidateQueries({queryKey:["wishlist-items"]}),y!=null&&y.wasAdded&&c){const v=(c.vote_count||0)+1;V.functions.invoke("wishlist-notify",{body:{itemId:s,voteCount:v}}).catch(console.error)}},onError:y=>{r({title:"Error",description:y.message,variant:"destructive"})}}),p=Nt({mutationFn:async y=>{const{error:v}=await V.from("wishlist_comments").insert({item_id:s,user_id:n.id,content:y});if(v)throw v},onSuccess:()=>{a.invalidateQueries({queryKey:["wishlist-comments",s]}),l(""),r({title:"Comment added!"})},onError:y=>{r({title:"Error",description:y.message,variant:"destructive"})}}),g=Nt({mutationFn:async y=>{const{error:v}=await V.from("wishlist_comments").delete().eq("id",y);if(v)throw v},onSuccess:()=>{a.invalidateQueries({queryKey:["wishlist-comments",s]}),r({title:"Comment deleted"})},onError:y=>{r({title:"Error",description:y.message,variant:"destructive"})}}),x=()=>{i.trim()&&p.mutate(i.trim())};return d?e.jsx(Xs,{title:"Wishlist",children:e.jsxs("div",{className:"max-w-3xl mx-auto",children:[e.jsx(fn,{className:"h-8 w-32 mb-6"}),e.jsx(fn,{className:"h-48 w-full mb-6"}),e.jsx(fn,{className:"h-32 w-full"})]})}):c?e.jsx(Xs,{title:"Wishlist",children:e.jsxs("div",{className:"max-w-3xl mx-auto",children:[e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>t("/wishlist"),className:"mb-4",children:[e.jsx(Ia,{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:()=>m.mutate(c.has_voted),className:Ot("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(ap,{className:Ot("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(qe,{className:Ot("text-xs",Txt[c.status].color),children:Txt[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(Wa,{className:"h-6 w-6",children:e.jsx(Ka,{className:"bg-primary/20 text-primary text-xs",children:c.user_initials})}),e.jsx("span",{children:c.user_name}),e.jsx("span",{children:"•"}),e.jsx("span",{children:new Date(c.created_at).toLocaleDateString()})]})]})]})}),e.jsxs("div",{className:"bg-card border rounded-lg p-6",children:[e.jsxs("h2",{className:"text-lg font-semibold mb-4",children:["Comments (",u.length,")"]}),e.jsxs("div",{className:"flex gap-3 mb-6",children:[e.jsx(y5e,{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($,{onClick:x,disabled:!i.trim()||p.isPending,size:"icon",className:"h-auto",children:p.isPending?e.jsx(Jt,{className:"h-4 w-4 animate-spin"}):e.jsx(Wr,{className:"h-4 w-4"})})]}),h?e.jsx("div",{className:"space-y-4",children:[1,2].map(y=>e.jsx(fn,{className:"h-20 w-full"},y))}):u.length===0?e.jsx("p",{className:"text-center text-muted-foreground py-8",children:"No comments yet. Be the first to share your thoughts!"}):e.jsx("div",{className:"space-y-4",children:u.map(y=>e.jsxs("div",{className:"flex gap-3 p-3 bg-muted/30 rounded-lg",children:[e.jsx(Wa,{className:"h-8 w-8",children:e.jsx(Ka,{className:"bg-primary/20 text-primary text-xs",children:y.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:y.user_name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:new Date(y.created_at).toLocaleDateString()})]}),e.jsx(JKe,{content:y.content,className:"text-sm text-foreground"})]}),(n==null?void 0:n.id)===y.user_id&&e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8 text-muted-foreground hover:text-destructive",onClick:()=>g.mutate(y.id),children:e.jsx(Un,{className:"h-4 w-4"})})]},y.id))})]})]})}):e.jsx(Xs,{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($,{variant:"link",onClick:()=>t("/wishlist"),children:"Go back to Wishlist"})]})})}const Mxt={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"}},Pxt=["open","under_review","planned","in_progress","launched","declined"];function y_n(){const{toast:s}=Fi(),t=Jn(),n=ls(),[r,a]=k.useState(""),[i,l]=k.useState("all"),[o,c]=k.useState(!1),[d,u]=k.useState(null),{data:h=[],isLoading:m}=pt({queryKey:["admin-wishlist-items"],queryFn:async()=>{const{data:v,error:_}=await V.from("wishlist_items").select("*").order("vote_count",{ascending:!1});if(_)throw _;const j=[...new Set((v==null?void 0:v.map(R=>R.user_id))||[])],{data:C}=await V.from("profiles").select("id, name, email").in("id",j),A=new Map((C==null?void 0:C.map(R=>[R.id,R]))||[]),M=(v==null?void 0:v.map(R=>R.id))||[],{data:I}=await V.from("wishlist_comments").select("item_id").in("item_id",M),P=new Map;return I==null||I.forEach(R=>{P.set(R.item_id,(P.get(R.item_id)||0)+1)}),v==null?void 0:v.map(R=>{const O=A.get(R.user_id);return{...R,user_name:(O==null?void 0:O.name)||"Unknown",user_email:(O==null?void 0:O.email)||"",comment_count:P.get(R.id)||0}})}}),p=Nt({mutationFn:async({itemId:v,status:_})=>{const{error:j}=await V.from("wishlist_items").update({status:_}).eq("id",v);if(j)throw j},onSuccess:()=>{n.invalidateQueries({queryKey:["admin-wishlist-items"]}),s({title:"Status updated!"})},onError:v=>{s({title:"Error",description:v.message,variant:"destructive"})}}),g=Nt({mutationFn:async v=>{const{error:_}=await V.from("wishlist_items").delete().eq("id",v);if(_)throw _},onSuccess:()=>{n.invalidateQueries({queryKey:["admin-wishlist-items"]}),c(!1),u(null),s({title:"Item deleted!"})},onError:v=>{s({title:"Error",description:v.message,variant:"destructive"})}}),x=h.filter(v=>{const _=v.title.toLowerCase().includes(r.toLowerCase())||v.description.toLowerCase().includes(r.toLowerCase())||v.user_name.toLowerCase().includes(r.toLowerCase()),j=i==="all"||v.status===i;return _&&j}),y={total:h.length,open:h.filter(v=>v.status==="open").length,inProgress:h.filter(v=>v.status==="in_progress").length,launched:h.filter(v=>v.status==="launched").length,highVotes:h.filter(v=>v.vote_count>=10).length};return e.jsx(Xs,{title:"Admin - Wishlist",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx($,{variant:"ghost",size:"icon",onClick:()=>t("/admin"),children:e.jsx(Ia,{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:y.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:y.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:y.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:y.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:y.highVotes})]})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Yr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search ideas, users...",value:r,onChange:v=>a(v.target.value),className:"pl-10"})]}),e.jsxs(bs,{value:i,onValueChange:v=>l(v),children:[e.jsx(ys,{className:"w-[180px]",children:e.jsx(_s,{placeholder:"Filter by status"})}),e.jsxs(vs,{children:[e.jsx(We,{value:"all",children:"All Statuses"}),Pxt.map(v=>e.jsx(We,{value:v,children:Mxt[v].label},v))]})]})]}),m?e.jsx("div",{className:"space-y-2",children:[1,2,3,4,5].map(v=>e.jsx(fn,{className:"h-16 w-full"},v))}):e.jsx("div",{className:"bg-card border rounded-lg overflow-hidden",children:e.jsxs(Qa,{children:[e.jsx(Ja,{children:e.jsxs(vn,{children:[e.jsx(Dt,{className:"w-[60px]",children:"Votes"}),e.jsx(Dt,{children:"Title"}),e.jsx(Dt,{className:"hidden md:table-cell",children:"Submitted By"}),e.jsx(Dt,{className:"hidden sm:table-cell",children:"Comments"}),e.jsx(Dt,{children:"Status"}),e.jsx(Dt,{className:"w-[100px]",children:"Actions"})]})}),e.jsx(ei,{children:x.length===0?e.jsx(vn,{children:e.jsx(_t,{colSpan:6,className:"text-center py-8 text-muted-foreground",children:"No items found"})}):x.map(v=>e.jsxs(vn,{className:Ot(v.vote_count>=10&&"bg-primary/5"),children:[e.jsx(_t,{children:e.jsx(qe,{variant:v.vote_count>=10?"default":"secondary",children:v.vote_count})}),e.jsx(_t,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium line-clamp-1",children:v.title}),e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-1",children:v.description})]})}),e.jsx(_t,{className:"hidden md:table-cell",children:e.jsxs("div",{children:[e.jsx("p",{className:"text-sm",children:v.user_name}),e.jsx("p",{className:"text-xs text-muted-foreground",children:v.user_email})]})}),e.jsx(_t,{className:"hidden sm:table-cell",children:v.comment_count}),e.jsx(_t,{children:e.jsxs(bs,{value:v.status,onValueChange:_=>p.mutate({itemId:v.id,status:_}),children:[e.jsx(ys,{className:"w-[140px] h-8",children:e.jsx(_s,{})}),e.jsx(vs,{children:Pxt.map(_=>e.jsx(We,{value:_,children:Mxt[_].label},_))})]})}),e.jsx(_t,{children:e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx($,{variant:"ghost",size:"icon",onClick:()=>window.open(`/wishlist/${v.id}`,"_blank"),children:e.jsx(Ir,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",className:"text-destructive",onClick:()=>{u(v.id),c(!0)},children:e.jsx(Un,{className:"h-4 w-4"})})]})})]},v.id))})]})}),e.jsx(zs,{open:o,onOpenChange:c,children:e.jsxs(Rs,{children:[e.jsx(Vs,{children:e.jsx($s,{children:"Delete Wishlist Item"})}),e.jsx("p",{className:"text-muted-foreground",children:"Are you sure you want to delete this idea? This will also delete all votes and comments."}),e.jsxs("div",{className:"flex justify-end gap-2 mt-4",children:[e.jsx($,{variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsx($,{variant:"destructive",onClick:()=>d&&g.mutate(d),disabled:g.isPending,children:g.isPending?e.jsxs(e.Fragment,{children:[e.jsx(Jt,{className:"h-4 w-4 mr-2 animate-spin"}),"Deleting..."]}):"Delete"})]})]})})]})})}function v_n(){const{user:s}=ks(),[t,n]=k.useState([]),[r,a]=k.useState(!0),[i,l]=k.useState(!1),[o,c]=k.useState(null),[d,u]=k.useState(!1),[h,m]=k.useState(null),[p,g]=k.useState(""),[x,y]=k.useState(""),[v,_]=k.useState(""),[j,C]=k.useState(""),[A,M]=k.useState(""),[I,P]=k.useState(!1),[R,O]=k.useState(""),[B,U]=k.useState("once"),[G,H]=k.useState([]),[Y,se]=k.useState([]),[ee,oe]=k.useState(!1),[me,Q]=k.useState(!1),[te,le]=k.useState([]),[fe,_e]=k.useState({total:0,dismissed:0});k.useEffect(()=>{ve()},[]);const ve=async()=>{const{data:nt,error:et}=await V.from("levelup_briefs").select("*").order("created_at",{ascending:!1});et?(ae.error("Failed to fetch briefs"),console.error(et)):n(nt||[]),a(!1)},he=()=>{g(""),y(""),_(""),C(""),M(""),P(!1),O(new Date().toISOString().slice(0,16)),U("once"),H([]),se([]),c(null)},Se=()=>{he(),l(!0)},Te=async nt=>{c(nt),g(nt.title),y(nt.description||""),_(nt.video_url||""),C(nt.graphic_url||""),M(nt.graphic_link_url||""),P(nt.is_published),O(nt.publish_date.slice(0,16)),U(nt.show_frequency);const{data:et}=await V.from("levelup_brief_links").select("*").eq("brief_id",nt.id).order("sort_order");H((et==null?void 0:et.map(wt=>({title:wt.title,url:wt.url})))||[]);const{data:at}=await V.from("levelup_brief_polls").select("*").eq("brief_id",nt.id).order("sort_order");if(at){const wt=[];for(const rt of at){const{data:Ft}=await V.from("levelup_brief_poll_options").select("*").eq("poll_id",rt.id).order("sort_order");wt.push({question:rt.question,poll_type:rt.poll_type,options:(Ft==null?void 0:Ft.map(Ut=>Ut.option_text))||[]})}se(wt)}l(!0)},Ie=async nt=>{var at;const et=(at=nt.target.files)==null?void 0:at[0];if(et){oe(!0);try{const wt=await V.functions.invoke("bunny-upload",{body:{action:"create",title:et.name.replace(/\.[^/.]+$/,"")}});if(wt.error)throw wt.error;const{videoId:rt,libraryId:Ft}=wt.data,Ut=await V.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:rt}});if(Ut.error)throw Ut.error;const{uploadUrl:Is,apiKey:xs}=Ut.data,st=new XMLHttpRequest;await new Promise((jt,gt)=>{st.upload.addEventListener("progress",rs=>{if(rs.lengthComputable){const Ns=Math.round(rs.loaded/rs.total*100);console.log("Upload progress:",Ns)}}),st.addEventListener("load",()=>{st.status>=200&&st.status<300?jt():gt(new Error(`Upload failed with status ${st.status}`))}),st.addEventListener("error",()=>gt(new Error("Upload failed"))),st.open("PUT",Is),st.setRequestHeader("AccessKey",xs),st.send(et)});const dt=`https://player.mediadelivery.net/embed/${Ft}/${rt}`;_(dt),ae.success("Video uploaded successfully! It may take a few minutes to process.")}catch(wt){console.error("Upload error:",wt),ae.error("Failed to upload video")}finally{oe(!1)}}},Ue=async()=>{if(!p.trim()){ae.error("Title is required");return}try{let nt;if(o){const{error:et}=await V.from("levelup_briefs").update({title:p,description:x||null,video_url:v||null,graphic_url:j||null,graphic_link_url:A||null,is_published:I,publish_date:R,show_frequency:B}).eq("id",o.id);if(et)throw et;nt=o.id,await V.from("levelup_brief_links").delete().eq("brief_id",nt);const{data:at}=await V.from("levelup_brief_polls").select("id").eq("brief_id",nt);if(at)for(const wt of at)await V.from("levelup_brief_poll_options").delete().eq("poll_id",wt.id);await V.from("levelup_brief_polls").delete().eq("brief_id",nt)}else{const{data:et,error:at}=await V.from("levelup_briefs").insert({title:p,description:x||null,video_url:v||null,graphic_url:j||null,graphic_link_url:A||null,is_published:I,publish_date:R,show_frequency:B,created_by:s==null?void 0:s.id}).select().single();if(at)throw at;nt=et.id}if(G.length>0){const et=G.map((at,wt)=>({brief_id:nt,title:at.title,url:at.url,sort_order:wt}));await V.from("levelup_brief_links").insert(et)}for(let et=0;et0){const Ft=at.options.map((Ut,Is)=>({poll_id:wt.id,option_text:Ut,sort_order:Is}));await V.from("levelup_brief_poll_options").insert(Ft)}}ae.success(o?"Brief updated":"Brief created"),l(!1),he(),ve()}catch(nt){console.error("Error saving brief:",nt),ae.error("Failed to save brief")}},Be=async nt=>{if(await io("Are you sure you want to delete this brief?"))try{const{error:et}=await V.from("levelup_briefs").delete().eq("id",nt);if(et)throw et;ae.success("Brief deleted"),ve()}catch(et){console.error("Error deleting brief:",et),ae.error("Failed to delete brief")}},je=async nt=>{m(nt);const{count:et}=await V.from("levelup_brief_views").select("*",{count:"exact",head:!0}).eq("brief_id",nt.id),{count:at}=await V.from("levelup_brief_views").select("*",{count:"exact",head:!0}).eq("brief_id",nt.id).not("dismissed_at","is",null);_e({total:et||0,dismissed:at||0});const{data:wt}=await V.from("levelup_brief_polls").select("*").eq("brief_id",nt.id).order("sort_order");if(wt){const rt=[];for(const Ft of wt){const{data:Ut}=await V.from("levelup_brief_poll_options").select("*").eq("poll_id",Ft.id).order("sort_order"),{data:Is}=await V.from("levelup_brief_poll_responses").select("option_id, user_id").eq("poll_id",Ft.id),xs=[...new Set((Is==null?void 0:Is.map(rs=>rs.user_id))||[])];let st={};if(xs.length>0){const{data:rs}=await V.from("profiles").select("id, name, email").in("id",xs);rs&&rs.forEach(Ns=>{st[Ns.id]=Ns.name||Ns.email||"Unknown"})}const dt=(Is||[]).map(rs=>({optionId:rs.option_id,userName:st[rs.user_id]||"Unknown",userId:rs.user_id})),jt={};let gt=0;Ut&&Ut.forEach(rs=>{const Ns=(Is==null?void 0:Is.filter(us=>us.option_id===rs.id).length)||0;jt[rs.id]=Ns,gt+=Ns}),rt.push({...Ft,options:Ut||[],results:jt,respondents:dt,totalResponses:Ft.poll_type==="single"?new Set(Is==null?void 0:Is.map(rs=>rs.user_id)).size:gt})}le(rt)}u(!0)},Ye=()=>{H([...G,{title:"",url:""}])},Ee=(nt,et,at)=>{const wt=[...G];wt[nt][et]=at,H(wt)},Re=nt=>{H(G.filter((et,at)=>at!==nt))},ke=()=>{se([...Y,{question:"",poll_type:"single",options:["",""]}])},Fe=(nt,et)=>{const at=[...Y];at[nt].question=et,se(at)},Oe=(nt,et)=>{const at=[...Y];at[nt].poll_type=et,se(at)},Ge=nt=>{const et=[...Y];et[nt].options.push(""),se(et)},yt=(nt,et,at)=>{const wt=[...Y];wt[nt].options[et]=at,se(wt)},tt=(nt,et)=>{const at=[...Y];at[nt].options=at[nt].options.filter((wt,rt)=>rt!==et),se(at)},ut=nt=>{se(Y.filter((et,at)=>at!==nt))};return e.jsxs(Xs,{title:"The LevelUp Brief",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsx(nm,{title:"The LevelUp Brief",description:"Create engaging popup briefs for your agents",children:e.jsxs($,{onClick:Se,children:[e.jsx(nn,{className:"h-4 w-4 mr-2"}),"Create Brief"]})}),e.jsx(we,{children:e.jsx(De,{className:"p-0",children:e.jsxs(Qa,{children:[e.jsx(Ja,{children:e.jsxs(vn,{children:[e.jsx(Dt,{children:"Title"}),e.jsx(Dt,{children:"Status"}),e.jsx(Dt,{children:"Frequency"}),e.jsx(Dt,{children:"Publish Date"}),e.jsx(Dt,{className:"text-right",children:"Actions"})]})}),e.jsx(ei,{children:r?e.jsx(vn,{children:e.jsx(_t,{colSpan:5,className:"text-center py-8",children:"Loading..."})}):t.length===0?e.jsx(vn,{children:e.jsx(_t,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No briefs created yet"})}):t.map(nt=>e.jsxs(vn,{children:[e.jsx(_t,{className:"font-medium",children:nt.title}),e.jsx(_t,{children:e.jsx(qe,{variant:nt.is_published?"default":"secondary",children:nt.is_published?"Published":"Draft"})}),e.jsx(_t,{className:"capitalize",children:nt.show_frequency.replace("_"," ")}),e.jsx(_t,{children:Ys(new Date(nt.publish_date),"MMM d, yyyy h:mm a")}),e.jsx(_t,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx($,{variant:"ghost",size:"icon",onClick:()=>je(nt),children:e.jsx(Ul,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>Te(nt),children:e.jsx(Cp,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>Be(nt.id),children:e.jsx(Un,{className:"h-4 w-4 text-destructive"})})]})})]},nt.id))})]})})})]}),e.jsx(zs,{open:i,onOpenChange:l,children:e.jsxs(Rs,{className:"max-w-3xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Vs,{children:e.jsx($s,{children:o?"Edit Brief":"Create New Brief"})}),e.jsxs(ya,{defaultValue:"content",className:"w-full",children:[e.jsxs(va,{className:"grid w-full grid-cols-4",children:[e.jsx(is,{value:"content",children:"Content"}),e.jsx(is,{value:"media",children:"Media"}),e.jsx(is,{value:"links",children:"Links"}),e.jsx(is,{value:"polls",children:"Polls"})]}),e.jsxs(cs,{value:"content",className:"space-y-4 mt-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Title *"}),e.jsx(be,{value:p,onChange:nt=>g(nt.target.value),placeholder:"What's happening at LevelUp..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Description"}),e.jsx(V2,{content:x,onChange:nt=>y(nt),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(re,{children:"Publish Date"}),e.jsx(be,{type:"datetime-local",value:R,onChange:nt=>O(nt.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Show Frequency"}),e.jsxs(bs,{value:B,onValueChange:U,children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"once",children:"Once (until dismissed)"}),e.jsx(We,{value:"every_login",children:"Every login"}),e.jsx(We,{value:"daily",children:"Daily"})]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(On,{checked:I,onCheckedChange:P}),e.jsx(re,{children:"Publish immediately"})]})]}),e.jsxs(cs,{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(re,{children:"Upload Video to Bunny.net"}),e.jsx("div",{className:"flex gap-2",children:e.jsx(be,{type:"file",accept:"video/*",onChange:Ie,disabled:ee})}),ee&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Uploading..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Or paste embed URL"}),e.jsx(be,{value:v,onChange:nt=>_(nt.target.value),placeholder:"https://iframe.mediadelivery.net/embed/..."})]}),v&&e.jsx("div",{className:"aspect-video rounded-lg overflow-hidden bg-muted",children:e.jsx("iframe",{src:v,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(re,{children:"Upload Image"}),e.jsx("div",{className:"flex gap-2",children:e.jsx(be,{type:"file",accept:"image/*",onChange:async nt=>{var at;const et=(at=nt.target.files)==null?void 0:at[0];if(et){Q(!0);try{const wt=et.name.split(".").pop(),rt=`brief-graphics/${Date.now()}.${wt}`,{error:Ft}=await V.storage.from("banner-images").upload(rt,et,{upsert:!0});if(Ft)throw Ft;const{data:Ut}=V.storage.from("banner-images").getPublicUrl(rt);C(Ut.publicUrl),ae.success("Image uploaded!")}catch(wt){console.error(wt),ae.error("Failed to upload image")}finally{Q(!1)}}},disabled:me})}),me&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Uploading..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Or paste Image URL"}),e.jsx(be,{value:j,onChange:nt=>C(nt.target.value),placeholder:"https://example.com/image.png"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Click-through Link (optional)"}),e.jsx(be,{value:A,onChange:nt=>M(nt.target.value),placeholder:"https://example.com/landing-page"})]}),j&&e.jsx("div",{className:"rounded-lg overflow-hidden bg-muted border",children:e.jsx("img",{src:j,alt:"Brief graphic preview",className:"w-full object-contain max-h-64"})})]})]}),e.jsxs(cs,{value:"links",className:"space-y-4 mt-4",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx(re,{children:"Quick Links"}),e.jsxs($,{variant:"outline",size:"sm",onClick:Ye,children:[e.jsx(nn,{className:"h-4 w-4 mr-1"}),"Add Link"]})]}),G.map((nt,et)=>e.jsxs("div",{className:"flex gap-2 items-start",children:[e.jsx(be,{value:nt.title,onChange:at=>Ee(et,"title",at.target.value),placeholder:"Link title",className:"flex-1"}),e.jsx(be,{value:nt.url,onChange:at=>Ee(et,"url",at.target.value),placeholder:"https://...",className:"flex-[2]"}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>Re(et),children:e.jsx(Un,{className:"h-4 w-4 text-destructive"})})]},et)),G.length===0&&e.jsx("p",{className:"text-muted-foreground text-center py-4",children:"No links added yet"})]}),e.jsxs(cs,{value:"polls",className:"space-y-4 mt-4",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx(re,{children:"Polls"}),e.jsxs($,{variant:"outline",size:"sm",onClick:ke,children:[e.jsx(nn,{className:"h-4 w-4 mr-1"}),"Add Poll"]})]}),Y.map((nt,et)=>e.jsx(we,{className:"p-4",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx(be,{value:nt.question,onChange:at=>Fe(et,at.target.value),placeholder:"Poll question...",className:"flex-1 mr-2"}),e.jsxs(bs,{value:nt.poll_type,onValueChange:at=>Oe(et,at),children:[e.jsx(ys,{className:"w-32",children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"single",children:"Single"}),e.jsx(We,{value:"multi",children:"Multi-select"})]})]}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>ut(et),children:e.jsx(Un,{className:"h-4 w-4 text-destructive"})})]}),e.jsxs("div",{className:"space-y-2 pl-4",children:[nt.options.map((at,wt)=>e.jsxs("div",{className:"flex gap-2",children:[e.jsx(be,{value:at,onChange:rt=>yt(et,wt,rt.target.value),placeholder:`Option ${wt+1}`}),nt.options.length>2&&e.jsx($,{variant:"ghost",size:"icon",onClick:()=>tt(et,wt),children:e.jsx(Un,{className:"h-4 w-4 text-muted-foreground"})})]},wt)),e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>Ge(et),children:[e.jsx(nn,{className:"h-4 w-4 mr-1"}),"Add Option"]})]})]})},et)),Y.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($,{variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsx($,{onClick:Ue,children:o?"Update Brief":"Create Brief"})]})]})}),e.jsx(zs,{open:d,onOpenChange:u,children:e.jsxs(Rs,{className:"max-w-2xl",children:[e.jsx(Vs,{children:e.jsxs($s,{children:["Results: ",h==null?void 0:h.title]})}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs(we,{children:[e.jsx(Vt,{className:"pb-2",children:e.jsx(Yt,{className:"text-sm font-medium text-muted-foreground",children:"Total Views"})}),e.jsx(De,{children:e.jsx("p",{className:"text-2xl font-bold",children:fe.total})})]}),e.jsxs(we,{children:[e.jsx(Vt,{className:"pb-2",children:e.jsx(Yt,{className:"text-sm font-medium text-muted-foreground",children:"Dismissed"})}),e.jsx(De,{children:e.jsx("p",{className:"text-2xl font-bold",children:fe.dismissed})})]})]}),te.length>0?e.jsxs("div",{className:"space-y-4",children:[e.jsx("h3",{className:"font-semibold",children:"Poll Results"}),te.map(nt=>e.jsxs(we,{className:"p-4",children:[e.jsx("h4",{className:"font-medium mb-3",children:nt.question}),e.jsx("div",{className:"space-y-2",children:nt.options.map(et=>{const at=nt.results[et.id]||0,wt=nt.totalResponses>0?Math.round(at/nt.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:et.option_text}),e.jsxs("span",{className:"text-muted-foreground",children:[at," (",wt,"%)"]})]}),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:`${wt}%`}})}),at>0&&e.jsx("div",{className:"flex flex-wrap gap-1 pt-1",children:(nt.respondents||[]).filter(rt=>rt.optionId===et.id).map((rt,Ft)=>e.jsx(qe,{variant:"secondary",className:"text-xs font-normal",children:rt.userName},Ft))})]},et.id)})})]},nt.id))]}):e.jsx("p",{className:"text-muted-foreground text-center py-4",children:"No polls in this brief"})]})]})})]})}const b_n=()=>{const{user:s}=ks(),{toast:t}=Fi(),n=ls(),[r,a]=k.useState(!1),[i,l]=k.useState(null),[o,c]=k.useState({name:"",description:"",signup_link_url:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1}),[d,u]=k.useState(null),[h,m]=k.useState(""),{data:p=[],isLoading:g}=pt({queryKey:["additional-services-admin"],queryFn:async()=>{const{data:A,error:M}=await V.from("additional_services").select("*").order("publish_date",{ascending:!1});if(M)throw M;return A}}),x=Nt({mutationFn:async A=>{let M=A.existingImageUrl;if(A.image){const P=A.image.name.split(".").pop(),R=`${Date.now()}-${Math.random().toString(36).substring(7)}.${P}`,{error:O}=await V.storage.from("service-images").upload(R,A.image);if(O)throw O;const{data:B}=V.storage.from("service-images").getPublicUrl(R);M=B.publicUrl}const I={name:A.item.name,description:A.item.description||null,preview_image_url:M,signup_link_url:A.item.signup_link_url,publish_date:A.item.publish_date?new Date(A.item.publish_date).toISOString():new Date().toISOString(),is_published:A.item.is_published,created_by:s==null?void 0:s.id};if(A.itemId){const{error:P}=await V.from("additional_services").update(I).eq("id",A.itemId);if(P)throw P}else{const{error:P}=await V.from("additional_services").insert(I);if(P)throw P}},onSuccess:()=>{n.invalidateQueries({queryKey:["additional-services-admin"]}),n.invalidateQueries({queryKey:["additional-services"]}),t({title:i?"Service updated":"Service created"}),a(!1),v()},onError:A=>{t({title:"Error saving service",description:A.message,variant:"destructive"})}}),y=Nt({mutationFn:async A=>{const{error:M}=await V.from("additional_services").delete().eq("id",A);if(M)throw M},onSuccess:()=>{n.invalidateQueries({queryKey:["additional-services-admin"]}),n.invalidateQueries({queryKey:["additional-services"]}),t({title:"Service deleted"})},onError:A=>{t({title:"Error deleting service",description:A.message,variant:"destructive"})}}),v=()=>{c({name:"",description:"",signup_link_url:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1}),u(null),m(""),l(null)},_=A=>{l(A),c({name:A.name,description:A.description||"",signup_link_url:A.signup_link_url,publish_date:A.publish_date?new Date(A.publish_date).toISOString().split("T")[0]:new Date().toISOString().split("T")[0],is_published:A.is_published}),m(A.preview_image_url||""),a(!0)},j=A=>{var I;const M=(I=A.target.files)==null?void 0:I[0];M&&(u(M),m(URL.createObjectURL(M)))},C=A=>{if(A.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}x.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(Xs,{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(we,{children:[e.jsx(Vt,{className:"pb-2",children:e.jsx(Yt,{className:"text-sm font-medium text-muted-foreground",children:"Total Services"})}),e.jsx(De,{children:e.jsx("div",{className:"text-2xl font-bold",children:p.length})})]}),e.jsxs(we,{children:[e.jsx(Vt,{className:"pb-2",children:e.jsx(Yt,{className:"text-sm font-medium text-muted-foreground",children:"Published"})}),e.jsx(De,{children:e.jsx("div",{className:"text-2xl font-bold",children:p.filter(A=>A.is_published).length})})]})]}),e.jsxs(zs,{open:r,onOpenChange:A=>{a(A),A||v()},children:[e.jsx(yl,{asChild:!0,children:e.jsxs($,{className:"gap-2",children:[e.jsx(nn,{className:"h-4 w-4"}),"Add Service"]})}),e.jsxs(Rs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Vs,{children:e.jsx($s,{children:i?"Edit Service":"Add New Service"})}),e.jsxs("form",{onSubmit:C,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"name",children:"Name *"}),e.jsx(be,{id:"name",value:o.name,onChange:A=>c({...o,name:A.target.value}),placeholder:"Enter service name"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Description"}),e.jsx(V2,{content:o.description,onChange:A=>c({...o,description:A}),placeholder:"Enter description",minHeight:"120px"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"signup_link_url",children:"Signup Link URL *"}),e.jsx(be,{id:"signup_link_url",type:"url",value:o.signup_link_url,onChange:A=>c({...o,signup_link_url:A.target.value}),placeholder:"https://example.com/signup"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"publish_date",children:"Publish Date"}),e.jsx(be,{id:"publish_date",type:"date",value:o.publish_date,onChange:A=>c({...o,publish_date:A.target.value})})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(On,{id:"is_published",checked:o.is_published,onCheckedChange:A=>c({...o,is_published:A})}),e.jsx(re,{htmlFor:"is_published",children:"Published"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Preview Image"}),h?e.jsxs("div",{className:"relative",children:[e.jsx("img",{src:h,alt:"Preview",className:"w-full max-h-48 object-contain rounded-lg border"}),e.jsx($,{type:"button",variant:"destructive",size:"icon",className:"absolute top-2 right-2 h-6 w-6",onClick:()=>{u(null),m("")},children:e.jsx(mr,{className:"h-3 w-3"})})]}):e.jsxs("div",{className:"border-2 border-dashed rounded-lg p-4 text-center",children:[e.jsx(zc,{className:"h-8 w-8 mx-auto text-muted-foreground mb-2"}),e.jsx(be,{type:"file",accept:"image/*",onChange:j,className:"cursor-pointer"})]})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx($,{type:"button",variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx($,{type:"submit",disabled:x.isPending,children:x.isPending?"Saving...":i?"Update":"Create"})]})]})]})]})]}),e.jsx(we,{children:e.jsx(De,{className:"p-0",children:g?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):p.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(Qa,{children:[e.jsx(Ja,{children:e.jsxs(vn,{children:[e.jsx(Dt,{className:"w-16",children:"Preview"}),e.jsx(Dt,{children:"Name"}),e.jsx(Dt,{children:"Signup Link"}),e.jsx(Dt,{children:"Publish Date"}),e.jsx(Dt,{children:"Status"}),e.jsx(Dt,{className:"text-right",children:"Actions"})]})}),e.jsx(ei,{children:p.map(A=>e.jsxs(vn,{children:[e.jsx(_t,{children:A.preview_image_url?e.jsx("img",{src:A.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(zc,{className:"h-5 w-5 text-muted-foreground"})})}),e.jsx(_t,{className:"font-medium",children:A.name}),e.jsx(_t,{children:e.jsxs("a",{href:A.signup_link_url,target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline flex items-center gap-1",children:[e.jsx(Ir,{className:"h-3 w-3"}),"Link"]})}),e.jsx(_t,{children:new Date(A.publish_date).toLocaleDateString()}),e.jsx(_t,{children:e.jsx(qe,{variant:A.is_published?"default":"secondary",children:A.is_published?"Published":"Draft"})}),e.jsx(_t,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx($,{variant:"ghost",size:"icon",onClick:()=>_(A),children:e.jsx(ui,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:async()=>{await io("Are you sure you want to delete this service?")&&y.mutate(A.id)},children:e.jsx(Un,{className:"h-4 w-4 text-destructive"})})]})})]},A.id))})]})})})]})})};function __n(){const{toast:s}=Fi(),[t,n]=k.useState([]),[r,a]=k.useState(!0),[i,l]=k.useState(!1),[o,c]=k.useState(!1),[d,u]=k.useState({name:"",promotionCode:"",discountType:"percent",percentOff:"",amountOff:"",duration:"once",durationInMonths:""});k.useEffect(()=>{h()},[]);const h=async()=>{try{const{data:y,error:v}=await V.functions.invoke("stripe-manage-coupons",{body:{action:"list"}});if(v)throw v;n(y.coupons||[])}catch(y){console.error("Error fetching coupons:",y),s({title:"Error",description:"Failed to load coupons",variant:"destructive"})}finally{a(!1)}},m=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 y={action:"create",name:d.name,duration:d.duration,promotion_code:d.promotionCode.trim()||void 0};d.discountType==="percent"?y.percent_off=parseFloat(d.percentOff):(y.amount_off=Math.round(parseFloat(d.amountOff)*100),y.currency="usd"),d.duration==="repeating"&&(y.duration_in_months=parseInt(d.durationInMonths));const{data:v,error:_}=await V.functions.invoke("stripe-manage-coupons",{body:y});if(_)throw _;s({title:"Success",description:"Coupon created successfully"}),c(!1),u({name:"",promotionCode:"",discountType:"percent",percentOff:"",amountOff:"",duration:"once",durationInMonths:""}),h()}catch(y){console.error("Error creating coupon:",y),s({title:"Error",description:y.message||"Failed to create coupon",variant:"destructive"})}finally{l(!1)}},p=async y=>{if(await io("Are you sure you want to delete this coupon?"))try{const{error:v}=await V.functions.invoke("stripe-manage-coupons",{body:{action:"delete",couponId:y}});if(v)throw v;s({title:"Success",description:"Coupon deleted successfully"}),h()}catch(v){console.error("Error deleting coupon:",v),s({title:"Error",description:v.message||"Failed to delete coupon",variant:"destructive"})}},g=y=>y.percent_off?`${y.percent_off}% off`:y.amount_off?`$${(y.amount_off/100).toFixed(2)} off`:"N/A",x=y=>{switch(y.duration){case"once":return"Once";case"forever":return"Forever";case"repeating":return`${y.duration_in_months} months`;default:return y.duration}};return e.jsx(Xs,{title:"Subscription Discounts",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(nm,{title:"Subscription Discounts",description:"Create and manage discount coupons for subscriptions",children:e.jsxs(zs,{open:o,onOpenChange:c,children:[e.jsx(yl,{asChild:!0,children:e.jsxs($,{children:[e.jsx(nn,{className:"mr-2 h-4 w-4"}),"Create Coupon"]})}),e.jsxs(Rs,{children:[e.jsxs(Vs,{children:[e.jsx($s,{children:"Create New Coupon"}),e.jsx(Cr,{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(re,{children:"Promotion Code (what users will type)"}),e.jsx(be,{placeholder:"e.g., BROKERAGE50",value:d.promotionCode,onChange:y=>u({...d,promotionCode:y.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(re,{children:"Coupon Name (internal label)"}),e.jsx(be,{placeholder:"e.g., 50% Off Brokerage Launch",value:d.name,onChange:y=>u({...d,name:y.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Discount Type"}),e.jsxs(bs,{value:d.discountType,onValueChange:y=>{const v=y==="amount"&&d.duration==="forever"?"once":d.duration;u({...d,discountType:y,duration:v})},children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"percent",children:e.jsxs("span",{className:"flex items-center",children:[e.jsx(ZT,{className:"mr-2 h-4 w-4"}),"Percentage Off"]})}),e.jsx(We,{value:"amount",children:e.jsxs("span",{className:"flex items-center",children:[e.jsx(Su,{className:"mr-2 h-4 w-4"}),"Fixed Amount Off"]})})]})]})]}),d.discountType==="percent"?e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Percent Off"}),e.jsxs("div",{className:"relative",children:[e.jsx(be,{type:"number",min:"1",max:"100",placeholder:"20",value:d.percentOff,onChange:y=>u({...d,percentOff:y.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(re,{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(be,{type:"number",min:"1",placeholder:"10.00",className:"pl-7",value:d.amountOff,onChange:y=>u({...d,amountOff:y.target.value})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Duration"}),e.jsxs(bs,{value:d.duration,onValueChange:y=>u({...d,duration:y}),children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"once",children:"Once (first payment only)"}),e.jsx(We,{value:"repeating",children:"Multiple months"}),e.jsxs(We,{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(re,{children:"Number of Months"}),e.jsx(be,{type:"number",min:"1",placeholder:"3",value:d.durationInMonths,onChange:y=>u({...d,durationInMonths:y.target.value})})]}),e.jsx($,{onClick:m,disabled:i,className:"w-full",children:i?e.jsxs(e.Fragment,{children:[e.jsx(Jt,{className:"mr-2 h-4 w-4 animate-spin"}),"Creating..."]}):"Create Coupon"})]})]})]})}),e.jsxs(we,{children:[e.jsxs(Vt,{children:[e.jsx(Yt,{children:"Active Coupons"}),e.jsx(vr,{children:"Share coupon codes with users to give them discounts on subscriptions"})]}),e.jsx(De,{children:r?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(Jt,{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(Qa,{children:[e.jsx(Ja,{children:e.jsxs(vn,{children:[e.jsx(Dt,{children:"Promo Code"}),e.jsx(Dt,{children:"Name"}),e.jsx(Dt,{children:"Discount"}),e.jsx(Dt,{children:"Duration"}),e.jsx(Dt,{children:"Redemptions"}),e.jsx(Dt,{children:"Status"}),e.jsx(Dt,{className:"text-right",children:"Actions"})]})}),e.jsx(ei,{children:t.map(y=>{var v;return e.jsxs(vn,{children:[e.jsx(_t,{className:"font-mono font-medium",children:((v=y.promotion_codes)==null?void 0:v.length)>0?y.promotion_codes.join(", "):e.jsx("span",{className:"text-muted-foreground text-xs",children:"No promo code"})}),e.jsx(_t,{children:y.name||"-"}),e.jsx(_t,{children:g(y)}),e.jsx(_t,{children:x(y)}),e.jsx(_t,{children:y.times_redeemed}),e.jsx(_t,{children:e.jsx(qe,{variant:y.valid?"default":"secondary",children:y.valid?"Active":"Inactive"})}),e.jsx(_t,{className:"text-right",children:e.jsx($,{variant:"ghost",size:"sm",onClick:()=>p(y.id),children:e.jsx(Un,{className:"h-4 w-4 text-destructive"})})})]},y.id)})})]})})]}),e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsx(Yt,{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 FRe={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 w_n(){const[s,t]=k.useState(""),[n,r]=k.useState("all"),[a,i]=k.useState("all"),[l,o]=k.useState(null),{data:c,isLoading:d,refetch:u}=pt({queryKey:["admin-subscriptions"],queryFn:async()=>{const{data:v,error:_}=await V.from("profiles").select(` *, brokerages:brokerage_id (id, name) `).order("created_at",{ascending:!1});if(_)throw _;return v}}),{data:h}=pt({queryKey:["admin-brokerages-subscriptions"],queryFn:async()=>{const{data:v,error:_}=await V.from("brokerages").select("*").order("name");if(_)throw _;return await Promise.all((v||[]).map(async C=>{const{data:A}=await V.from("profiles").select("id, name, email, subscription_status, subscription_product_id").eq("brokerage_id",C.id),{data:M}=await V.from("user_roles").select("user_id").eq("role","brokerage_manager"),I=(M==null?void 0:M.map(O=>O.user_id))||[],P=(A==null?void 0:A.filter(O=>I.includes(O.id)))||[],R=(A==null?void 0:A.length)||0;return{...C,managers:P,agentCount:R}}))}}),{data:m}=pt({queryKey:["admin-website-subscriptions"],queryFn:async()=>{const{data:v,error:_}=await V.from("local_move_subscriptions").select("*").order("created_at",{ascending:!1});if(_)throw _;return v}}),p=v=>{if(v.is_grandfathered)return{status:"Grandfathered",badge:"Legacy",variant:"secondary"};if(v.brokerage_id&&!v.subscription_product_id)return{status:"Brokerage",badge:"Team Member",variant:"outline"};if(v.is_trial&&v.trial_expires_at)return new Date(v.trial_expires_at)>new Date?{status:"Trial",badge:"Active Trial",variant:"default"}:{status:"Trial Expired",badge:"Expired",variant:"destructive"};if(v.subscription_status==="active"||v.subscription_status==="trialing"){const _=FRe[v.subscription_product_id];return{status:(_==null?void 0:_.name)||"Active",badge:v.subscription_status==="trialing"?"Trial":"Active",variant:"default"}}return v.subscription_status==="canceled"||v.subscription_status==="past_due"?{status:"Canceled",badge:"Inactive",variant:"destructive"}:{status:"None",badge:"No Subscription",variant:"outline"}},g=c==null?void 0:c.filter(v=>{var j,C;if(!(((j=v.name)==null?void 0:j.toLowerCase().includes(s.toLowerCase()))||((C=v.email)==null?void 0:C.toLowerCase().includes(s.toLowerCase()))))return!1;if(a!=="all"){const A=v.subscription_source||"platform";if(a==="platform"&&A==="local_move_website"||a==="local_move_website"&&A!=="local_move_website")return!1}switch(p(v),n){case"active":return v.subscription_status==="active";case"trialing":return v.subscription_status==="trialing"||v.is_trial&&new Date(v.trial_expires_at)>new Date;case"grandfathered":return v.is_grandfathered;case"brokerage":return v.brokerage_id&&!v.subscription_product_id&&!v.is_grandfathered;case"expired":return v.subscription_status==="canceled"||v.subscription_status==="past_due"||v.is_trial&&new Date(v.trial_expires_at)<=new Date;case"none":return!v.subscription_status||v.subscription_status==="none";default:return!0}}),x={totalUsers:(c==null?void 0:c.length)||0,activeSubscriptions:(c==null?void 0:c.filter(v=>v.subscription_status==="active").length)||0,trials:(c==null?void 0:c.filter(v=>v.subscription_status==="trialing"||v.is_trial&&new Date(v.trial_expires_at)>new Date).length)||0,grandfathered:(c==null?void 0:c.filter(v=>v.is_grandfathered).length)||0,brokerageMembers:(c==null?void 0:c.filter(v=>v.brokerage_id&&!v.subscription_product_id&&!v.is_grandfathered).length)||0,individualSubscribers:(c==null?void 0:c.filter(v=>v.subscription_status==="active"&&v.subscription_product_id==="prod_Tc07cYplXUGNkm").length)||0,brokerageSubscribers:(c==null?void 0:c.filter(v=>v.subscription_status==="active"&&(v.subscription_product_id==="prod_Tc08MupgoVySDG"||v.subscription_product_id==="prod_Tc09N1tJ4RrAFn")).length)||0},y=v=>{window.open(`https://dashboard.stripe.com/customers/${v}`,"_blank")};return e.jsx(Xs,{title:"Subscription Management",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(nm,{title:"Subscription Management",description:"Track and manage all subscriptions",children:e.jsxs($,{onClick:()=>u(),variant:"outline",size:"sm",children:[e.jsx(yo,{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(we,{children:e.jsxs(De,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Xn,{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:x.totalUsers})]})}),e.jsx(we,{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(cv,{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:x.activeSubscriptions})]})}),e.jsx(we,{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(sa,{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:x.trials})]})}),e.jsx(we,{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(ky,{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:x.grandfathered})]})}),e.jsx(we,{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(Gi,{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:x.brokerageMembers})]})}),e.jsx(we,{children:e.jsxs(De,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ck,{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:x.individualSubscribers})]})}),e.jsx(we,{children:e.jsxs(De,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Gi,{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:x.brokerageSubscribers})]})})]}),e.jsxs(ya,{defaultValue:"users",className:"space-y-4",children:[e.jsxs(va,{children:[e.jsx(is,{value:"users",children:"All Users"}),e.jsx(is,{value:"brokerages",children:"Brokerages"}),e.jsxs(is,{value:"websites",className:"gap-2",children:[e.jsx(kc,{className:"h-4 w-4"}),"Website Subscriptions",m&&m.length>0&&e.jsx(qe,{variant:"secondary",className:"ml-1",children:m.length})]})]}),e.jsxs(cs,{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(Yr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search by name or email...",value:s,onChange:v=>t(v.target.value),className:"pl-9"})]}),e.jsxs(bs,{value:a,onValueChange:v=>i(v),children:[e.jsx(ys,{className:"w-[200px]",children:e.jsx(_s,{placeholder:"Source"})}),e.jsxs(vs,{children:[e.jsx(We,{value:"all",children:"All Sources"}),e.jsx(We,{value:"platform",children:"Platform"}),e.jsx(We,{value:"local_move_website",children:"Local Move Website"})]})]}),e.jsxs(bs,{value:n,onValueChange:v=>r(v),children:[e.jsx(ys,{className:"w-[200px]",children:e.jsx(_s,{placeholder:"Filter by status"})}),e.jsxs(vs,{children:[e.jsx(We,{value:"all",children:"All Statuses"}),e.jsx(We,{value:"active",children:"Active Subscriptions"}),e.jsx(We,{value:"trialing",children:"Trials"}),e.jsx(We,{value:"grandfathered",children:"Grandfathered"}),e.jsx(We,{value:"brokerage",children:"Brokerage Members"}),e.jsx(We,{value:"expired",children:"Expired/Canceled"}),e.jsx(We,{value:"none",children:"No Subscription"})]})]})]}),e.jsx(we,{children:e.jsx(De,{className:"p-0",children:e.jsxs(Qa,{children:[e.jsx(Ja,{children:e.jsxs(vn,{children:[e.jsx(Dt,{children:"User"}),e.jsx(Dt,{children:"Status"}),e.jsx(Dt,{children:"Plan"}),e.jsx(Dt,{children:"Brokerage"}),e.jsx(Dt,{children:"End Date"}),e.jsx(Dt,{className:"text-right",children:"Actions"})]})}),e.jsx(ei,{children:d?e.jsx(vn,{children:e.jsx(_t,{colSpan:6,className:"text-center py-8",children:"Loading subscriptions..."})}):(g==null?void 0:g.length)===0?e.jsx(vn,{children:e.jsx(_t,{colSpan:6,className:"text-center py-8 text-muted-foreground",children:"No users found"})}):g==null?void 0:g.map(v=>{var C,A;const _=p(v),j=FRe[v.subscription_product_id];return e.jsxs(vn,{children:[e.jsx(_t,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:v.name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:v.email})]})}),e.jsx(_t,{children:e.jsx(qe,{variant:_.variant,children:_.badge})}),e.jsx(_t,{children:e.jsx("span",{className:"text-sm",children:v.is_grandfathered?"Legacy Access":v.brokerage_id&&!v.subscription_product_id?"Brokerage Subscription":(j==null?void 0:j.name)||_.status})}),e.jsx(_t,{children:(C=v.brokerages)!=null&&C.name?e.jsx("span",{className:"text-sm",children:v.brokerages.name}):e.jsx("span",{className:"text-sm text-muted-foreground",children:"—"})}),e.jsx(_t,{children:v.subscription_end_date?e.jsx("span",{className:"text-sm",children:Ys(new Date(v.subscription_end_date),"MMM d, yyyy")}):v.trial_expires_at?e.jsxs("span",{className:"text-sm text-blue-600",children:["Trial: ",Ys(new Date(v.trial_expires_at),"MMM d, yyyy")]}):e.jsx("span",{className:"text-sm text-muted-foreground",children:"—"})}),e.jsx(_t,{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[v.stripe_customer_id&&e.jsx($,{variant:"ghost",size:"sm",onClick:()=>y(v.stripe_customer_id),children:e.jsx(Ir,{className:"h-4 w-4"})}),e.jsxs(zs,{children:[e.jsx(yl,{asChild:!0,children:e.jsx($,{variant:"outline",size:"sm",onClick:()=>o(v),children:"Details"})}),e.jsxs(Rs,{children:[e.jsxs(Vs,{children:[e.jsx($s,{children:"Subscription Details"}),e.jsxs(Cr,{children:[v.name," (",v.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(qe,{variant:_.variant,className:"mt-1",children:_.badge})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Plan"}),e.jsx("p",{className:"font-medium",children:v.is_grandfathered?"Grandfathered (Legacy)":v.brokerage_id&&!v.subscription_product_id?"Brokerage Subscription":(j==null?void 0:j.name)||"None"})]}),v.brokerage_id&&e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Brokerage"}),e.jsx("p",{className:"font-medium",children:((A=v.brokerages)==null?void 0:A.name)||"Unknown"})]}),v.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:Ys(new Date(v.subscription_end_date),"MMMM d, yyyy")})]}),v.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:Ys(new Date(v.trial_expires_at),"MMMM d, yyyy")})]}),v.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:v.stripe_customer_id})]})]}),v.stripe_customer_id&&e.jsxs($,{className:"w-full",onClick:()=>y(v.stripe_customer_id),children:[e.jsx(Ir,{className:"h-4 w-4 mr-2"}),"View in Stripe Dashboard"]})]})]})]})]})})]},v.id)})})]})})})]}),e.jsx(cs,{value:"brokerages",className:"space-y-4",children:e.jsx("div",{className:"grid gap-4",children:h==null?void 0:h.map(v=>{var j,C;const _=(j=v.managers)==null?void 0:j.some(A=>A.subscription_status==="active"&&(A.subscription_product_id==="prod_Tc08MupgoVySDG"||A.subscription_product_id==="prod_Tc09N1tJ4RrAFn"));return e.jsxs(we,{children:[e.jsx(Vt,{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(Gi,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx(Yt,{className:"text-lg",children:v.name}),e.jsxs(vr,{children:[v.agentCount," agents"]})]})]}),e.jsx(qe,{variant:_?"default":"outline",children:_?"Active Subscription":"No Active Subscription"})]})}),e.jsx(De,{children:((C=v.managers)==null?void 0:C.length)>0?e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm font-medium text-muted-foreground",children:"Managers:"}),v.managers.map(A=>{const M=FRe[A.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:A.name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:A.email})]}),e.jsx("div",{className:"text-right",children:M?e.jsxs("div",{children:[e.jsx(qe,{variant:"default",children:M.name}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:M.price})]}):e.jsx(qe,{variant:"outline",children:"No Subscription"})})]},A.id)})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"No managers assigned"})})]},v.id)})})}),e.jsx(cs,{value:"websites",className:"space-y-4",children:e.jsxs(we,{children:[e.jsxs(Vt,{children:[e.jsxs(Yt,{className:"flex items-center gap-2",children:[e.jsx(kc,{className:"h-5 w-5 text-primary"}),"Local Move Website Subscriptions"]}),e.jsx(vr,{children:"$249 setup fee + $99/mo subscriptions from TheLocalMove.com agent websites"})]}),e.jsx(De,{className:"p-0",children:e.jsxs(Qa,{children:[e.jsx(Ja,{children:e.jsxs(vn,{children:[e.jsx(Dt,{children:"Agent"}),e.jsx(Dt,{children:"Status"}),e.jsx(Dt,{children:"Setup Fee"}),e.jsx(Dt,{children:"Monthly"}),e.jsx(Dt,{children:"Next Renewal"}),e.jsx(Dt,{children:"Started"}),e.jsx(Dt,{className:"text-right",children:"Actions"})]})}),e.jsx(ei,{children:m?m.length===0?e.jsx(vn,{children:e.jsx(_t,{colSpan:7,className:"text-center py-8 text-muted-foreground",children:"No website subscriptions yet"})}):m.map(v=>e.jsxs(vn,{children:[e.jsx(_t,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:v.agent_name||"—"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:v.agent_email})]})}),e.jsx(_t,{children:e.jsx(qe,{variant:v.status==="active"?"default":v.status==="canceled"?"destructive":"outline",children:v.status})}),e.jsx(_t,{children:v.setup_fee_paid?e.jsxs(qe,{variant:"secondary",children:["Paid · $",(v.setup_fee_amount_cents/100).toFixed(0)]}):e.jsx(qe,{variant:"outline",children:"Unpaid"})}),e.jsxs(_t,{className:"font-medium",children:["$",(v.monthly_amount_cents/100).toFixed(0),"/mo"]}),e.jsx(_t,{children:v.current_period_end?e.jsx("span",{className:"text-sm",children:Ys(new Date(v.current_period_end),"MMM d, yyyy")}):e.jsx("span",{className:"text-sm text-muted-foreground",children:"—"})}),e.jsx(_t,{children:e.jsx("span",{className:"text-sm",children:Ys(new Date(v.created_at),"MMM d, yyyy")})}),e.jsx(_t,{className:"text-right",children:v.stripe_customer_id&&e.jsx($,{variant:"ghost",size:"sm",onClick:()=>y(v.stripe_customer_id),children:e.jsx(Ir,{className:"h-4 w-4"})})})]},v.id)):e.jsx(vn,{children:e.jsx(_t,{colSpan:7,className:"text-center py-8",children:"Loading…"})})})]})})]})})]})]})})}function j_n(){const[s,t]=k.useState([]),[n,r]=k.useState(!0),[a,i]=k.useState(""),[l,o]=k.useState("all"),[c,d]=k.useState({total:0,qualified:0,pending:0,cancelled:0,totalDiscounts:0});k.useEffect(()=>{u()},[]);const u=async()=>{try{const{data:g,error:x}=await V.from("referrals").select(` *, referrer_brokerage:brokerages!referrer_brokerage_id(name), referred_brokerage:brokerages!referred_brokerage_id(name), referred_user:profiles!referred_user_id(name, email) `).order("created_at",{ascending:!1});if(x)throw x;t(g||[]);const y=(g==null?void 0:g.filter(j=>j.status==="qualified").length)||0,v=(g==null?void 0:g.filter(j=>j.status==="pending").length)||0,_=(g==null?void 0:g.filter(j=>j.status==="cancelled").length)||0;d({total:(g==null?void 0:g.length)||0,qualified:y,pending:v,cancelled:_,totalDiscounts:y*25})}catch(g){console.error("Error fetching referrals:",g),ae.error("Failed to load referrals")}finally{r(!1)}},h=async()=>{try{ae.loading("Processing qualifications...");const{error:g}=await V.functions.invoke("process-referral-qualifications");if(g)throw g;ae.dismiss(),ae.success("Qualifications processed successfully"),u()}catch(g){ae.dismiss(),console.error("Error processing qualifications:",g),ae.error("Failed to process qualifications")}},m=s.filter(g=>{var v,_,j,C,A,M;const x=((_=(v=g.referrer_brokerage)==null?void 0:v.name)==null?void 0:_.toLowerCase().includes(a.toLowerCase()))||((C=(j=g.referred_brokerage)==null?void 0:j.name)==null?void 0:C.toLowerCase().includes(a.toLowerCase()))||((M=(A=g.referred_user)==null?void 0:A.email)==null?void 0:M.toLowerCase().includes(a.toLowerCase())),y=l==="all"||g.status===l;return x&&y}),p=g=>{switch(g){case"qualified":return e.jsxs(qe,{className:"bg-green-100 text-green-800",children:[e.jsx(nl,{className:"h-3 w-3 mr-1"}),"Qualified"]});case"pending":return e.jsxs(qe,{variant:"secondary",children:[e.jsx(sa,{className:"h-3 w-3 mr-1"}),"Pending"]});case"cancelled":return e.jsxs(qe,{variant:"destructive",children:[e.jsx(ju,{className:"h-3 w-3 mr-1"}),"Cancelled"]});default:return e.jsx(qe,{children:g})}};return e.jsx(Xs,{title:"Referral Program",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(nm,{title:"Referral Program",description:"Track and manage brokerage referrals",children:e.jsxs($,{onClick:h,variant:"outline",children:[e.jsx(yo,{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(we,{children:e.jsx(De,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Xn,{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(we,{children:e.jsx(De,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(nl,{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(we,{children:e.jsx(De,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(sa,{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(we,{children:e.jsx(De,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ju,{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(we,{children:e.jsx(De,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Su,{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(we,{children:[e.jsxs(Vt,{children:[e.jsx(Yt,{children:"All Referrals"}),e.jsx(vr,{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(Yr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search by brokerage or email...",value:a,onChange:g=>i(g.target.value),className:"pl-10"})]}),e.jsxs(bs,{value:l,onValueChange:o,children:[e.jsx(ys,{className:"w-[180px]",children:e.jsx(_s,{placeholder:"Filter by status"})}),e.jsxs(vs,{children:[e.jsx(We,{value:"all",children:"All Statuses"}),e.jsx(We,{value:"pending",children:"Pending"}),e.jsx(We,{value:"qualified",children:"Qualified"}),e.jsx(We,{value:"cancelled",children:"Cancelled"})]})]})]}),n?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):e.jsxs(Qa,{children:[e.jsx(Ja,{children:e.jsxs(vn,{children:[e.jsx(Dt,{children:"Referrer"}),e.jsx(Dt,{children:"Referred"}),e.jsx(Dt,{children:"Signup Date"}),e.jsx(Dt,{children:"Status"}),e.jsx(Dt,{children:"Qualified Date"}),e.jsx(Dt,{children:"Discount"})]})}),e.jsx(ei,{children:m.length===0?e.jsx(vn,{children:e.jsx(_t,{colSpan:6,className:"text-center text-muted-foreground py-8",children:"No referrals found"})}):m.map(g=>{var x,y,v,_;return e.jsxs(vn,{children:[e.jsx(_t,{className:"font-medium",children:((x=g.referrer_brokerage)==null?void 0:x.name)||"Unknown"}),e.jsx(_t,{children:e.jsxs("div",{children:[e.jsx("p",{children:((y=g.referred_brokerage)==null?void 0:y.name)||((v=g.referred_user)==null?void 0:v.name)||"Pending setup"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:(_=g.referred_user)==null?void 0:_.email})]})}),e.jsx(_t,{children:Ys(new Date(g.signup_date),"MMM d, yyyy")}),e.jsx(_t,{children:p(g.status)}),e.jsx(_t,{children:g.qualified_date?Ys(new Date(g.qualified_date),"MMM d, yyyy"):"-"}),e.jsx(_t,{children:g.discount_applied?e.jsx(qe,{variant:"outline",className:"text-green-600",children:"$25/mo applied"}):e.jsx("span",{className:"text-muted-foreground",children:"-"})})]},g.id)})})]})]})]})]})})}const zRe=[{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"}],N_n=[{value:"brokerage_manager",label:"Brokerage Manager"},{value:"agent",label:"Agent"}];function k_n(){const[s,t]=k.useState([]),[n,r]=k.useState(!0),[a,i]=k.useState(!1),[l,o]=k.useState(null),[c,d]=k.useState({title:"",description:"",action_type:"view_template",target_role:"agent",is_active:!0});k.useEffect(()=>{u()},[]);const u=async()=>{try{const{data:_,error:j}=await V.from("onboarding_checklist_items").select("*").order("target_role").order("sort_order");if(j)throw j;t(_||[])}catch(_){console.error("Error fetching checklist items:",_),ae.error("Failed to load checklist items")}finally{r(!1)}},h=()=>{o(null),d({title:"",description:"",action_type:"view_template",target_role:"agent",is_active:!0}),i(!0)},m=_=>{o(_),d({title:_.title,description:_.description||"",action_type:_.action_type,target_role:_.target_role,is_active:_.is_active}),i(!0)},p=async()=>{if(!c.title.trim()){ae.error("Title is required");return}try{if(l){const{error:_}=await V.from("onboarding_checklist_items").update({title:c.title,description:c.description||null,action_type:c.action_type,target_role:c.target_role,is_active:c.is_active}).eq("id",l.id);if(_)throw _;ae.success("Checklist item updated")}else{const _=s.filter(C=>C.target_role===c.target_role).reduce((C,A)=>Math.max(C,A.sort_order),-1),{error:j}=await V.from("onboarding_checklist_items").insert({title:c.title,description:c.description||null,action_type:c.action_type,target_role:c.target_role,is_active:c.is_active,sort_order:_+1});if(j)throw j;ae.success("Checklist item created")}i(!1),u()}catch(_){console.error("Error saving checklist item:",_),ae.error("Failed to save checklist item")}},g=async _=>{if(await io("Are you sure you want to delete this checklist item?"))try{const{error:j}=await V.from("onboarding_checklist_items").delete().eq("id",_);if(j)throw j;ae.success("Checklist item deleted"),u()}catch(j){console.error("Error deleting checklist item:",j),ae.error("Failed to delete checklist item")}},x=async _=>{try{const{error:j}=await V.from("onboarding_checklist_items").update({is_active:!_.is_active}).eq("id",_.id);if(j)throw j;ae.success(_.is_active?"Item deactivated":"Item activated"),u()}catch(j){console.error("Error toggling item:",j),ae.error("Failed to update item")}},y=s.filter(_=>_.target_role==="brokerage_manager"),v=s.filter(_=>_.target_role==="agent");return e.jsxs(Xs,{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($,{onClick:h,className:"gap-2",children:[e.jsx(nn,{className:"h-4 w-4"}),"Add Item"]})]}),e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsxs(Yt,{className:"flex items-center gap-2",children:[e.jsx(qe,{variant:"secondary",children:"Brokerage Manager"}),"Checklist Items"]})}),e.jsx(De,{children:y.length===0?e.jsx("p",{className:"text-muted-foreground text-center py-4",children:"No checklist items for brokerage managers"}):e.jsxs(Qa,{children:[e.jsx(Ja,{children:e.jsxs(vn,{children:[e.jsx(Dt,{className:"w-12",children:"#"}),e.jsx(Dt,{children:"Title"}),e.jsx(Dt,{children:"Action Type"}),e.jsx(Dt,{children:"Status"}),e.jsx(Dt,{className:"text-right",children:"Actions"})]})}),e.jsx(ei,{children:y.map((_,j)=>{var C;return e.jsxs(vn,{children:[e.jsx(_t,{className:"text-muted-foreground",children:j+1}),e.jsx(_t,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:_.title}),_.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-1",children:_.description})]})}),e.jsx(_t,{children:e.jsx(qe,{variant:"outline",children:((C=zRe.find(A=>A.value===_.action_type))==null?void 0:C.label)||_.action_type})}),e.jsx(_t,{children:e.jsx(On,{checked:_.is_active,onCheckedChange:()=>x(_)})}),e.jsx(_t,{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[e.jsx($,{variant:"ghost",size:"icon",onClick:()=>m(_),children:e.jsx(ui,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>g(_.id),children:e.jsx(Un,{className:"h-4 w-4 text-destructive"})})]})})]},_.id)})})]})})]}),e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsxs(Yt,{className:"flex items-center gap-2",children:[e.jsx(qe,{variant:"secondary",children:"Agent"}),"Checklist Items"]})}),e.jsx(De,{children:v.length===0?e.jsx("p",{className:"text-muted-foreground text-center py-4",children:"No checklist items for agents"}):e.jsxs(Qa,{children:[e.jsx(Ja,{children:e.jsxs(vn,{children:[e.jsx(Dt,{className:"w-12",children:"#"}),e.jsx(Dt,{children:"Title"}),e.jsx(Dt,{children:"Action Type"}),e.jsx(Dt,{children:"Status"}),e.jsx(Dt,{className:"text-right",children:"Actions"})]})}),e.jsx(ei,{children:v.map((_,j)=>{var C;return e.jsxs(vn,{children:[e.jsx(_t,{className:"text-muted-foreground",children:j+1}),e.jsx(_t,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:_.title}),_.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-1",children:_.description})]})}),e.jsx(_t,{children:e.jsx(qe,{variant:"outline",children:((C=zRe.find(A=>A.value===_.action_type))==null?void 0:C.label)||_.action_type})}),e.jsx(_t,{children:e.jsx(On,{checked:_.is_active,onCheckedChange:()=>x(_)})}),e.jsx(_t,{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[e.jsx($,{variant:"ghost",size:"icon",onClick:()=>m(_),children:e.jsx(ui,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>g(_.id),children:e.jsx(Un,{className:"h-4 w-4 text-destructive"})})]})})]},_.id)})})]})})]})]}),e.jsx(zs,{open:a,onOpenChange:i,children:e.jsxs(Rs,{children:[e.jsx(Vs,{children:e.jsx($s,{children:l?"Edit Checklist Item":"Add Checklist Item"})}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"title",children:"Title *"}),e.jsx(be,{id:"title",value:c.title,onChange:_=>d({...c,title:_.target.value}),placeholder:"e.g., Watch your first academy video"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"description",children:"Description"}),e.jsx(Ls,{id:"description",value:c.description,onChange:_=>d({...c,description:_.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(re,{children:"Target Role"}),e.jsxs(bs,{value:c.target_role,onValueChange:_=>d({...c,target_role:_}),children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsx(vs,{children:N_n.map(_=>e.jsx(We,{value:_.value,children:_.label},_.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Action Type"}),e.jsxs(bs,{value:c.action_type,onValueChange:_=>d({...c,action_type:_}),children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsx(vs,{children:zRe.map(_=>e.jsx(We,{value:_.value,children:_.label},_.value))})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(On,{id:"is_active",checked:c.is_active,onCheckedChange:_=>d({...c,is_active:_})}),e.jsx(re,{htmlFor:"is_active",children:"Active"})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>i(!1),children:"Cancel"}),e.jsx($,{onClick:p,children:l?"Save Changes":"Create Item"})]})]})})]})}function S_n(){const[s,t]=k.useState(""),[n,r]=k.useState("all"),[a,i]=k.useState("name"),[l,o]=k.useState("asc"),[c,d]=k.useState(""),[u,h]=k.useState(""),[m,p]=k.useState(""),[g,x]=k.useState(""),{data:y}=pt({queryKey:["admin-brokerages"],queryFn:async()=>{const{data:O,error:B}=await V.from("brokerages").select("id, name").order("name");if(B)throw B;return O}}),v=async O=>{let U=[],G=0,H=!0;for(;H;){const{data:Y,error:se}=await O(G,G+1e3-1);if(se)throw se;Y&&Y.length>0?(U=[...U,...Y],G+=1e3,H=Y.length===1e3):H=!1}return U},{data:_,isLoading:j}=pt({queryKey:["admin-agent-os-user-stats"],queryFn:async()=>{const O=await v((Te,Ie)=>V.from("profiles").select("id, name, email, brokerage_id, created_at").range(Te,Ie)),{data:B}=await V.from("brokerages").select("id, name"),U=new Map((B==null?void 0:B.map(Te=>[Te.id,Te.name]))||[]),[{data:G},{data:H},{data:Y},{data:se},{data:ee},{data:oe},{data:me}]=await Promise.all([V.rpc("get_admin_contact_counts"),V.rpc("get_admin_video_counts"),V.rpc("get_admin_popby_counts"),V.rpc("get_admin_listing_counts"),V.rpc("get_admin_deal_counts"),V.rpc("get_admin_portal_counts"),V.rpc("get_admin_sendable_card_counts")]),Q=new Map;G==null||G.forEach(Te=>Q.set(Te.owner_user_id,Te.contact_count));const te=new Map;H==null||H.forEach(Te=>te.set(Te.owner_user_id,Te.video_count));const le=new Map;Y==null||Y.forEach(Te=>le.set(Te.owner_user_id,Te.popby_count));const fe=new Map;se==null||se.forEach(Te=>fe.set(Te.agent_id,Te.listing_count));const _e=new Map;ee==null||ee.forEach(Te=>_e.set(Te.owner_user_id,Te.deal_count));const ve=new Map;oe==null||oe.forEach(Te=>ve.set(Te.owner_user_id,{total:Te.portal_count,active:Te.active_portal_count}));const he=new Map;return me==null||me.forEach(Te=>he.set(Te.owner_user_id,{total:Te.card_count,sent:Te.sent_card_count,views:Te.total_card_views})),O.map(Te=>{const Ie=ve.get(Te.id),Ue=he.get(Te.id);return{id:Te.id,name:Te.name||"Unknown",email:Te.email||"",brokerage_id:Te.brokerage_id,brokerage_name:Te.brokerage_id&&U.get(Te.brokerage_id)||null,contact_count:Q.get(Te.id)||0,video_count:te.get(Te.id)||0,popby_count:le.get(Te.id)||0,listing_count:fe.get(Te.id)||0,deal_count:_e.get(Te.id)||0,portal_count:(Ie==null?void 0:Ie.total)||0,active_portal_count:(Ie==null?void 0:Ie.active)||0,card_count:(Ue==null?void 0:Ue.total)||0,sent_card_count:(Ue==null?void 0:Ue.sent)||0,total_card_views:(Ue==null?void 0:Ue.views)||0,created_at:Te.created_at}})}}),C=k.useMemo(()=>{if(!_)return[];let O=_.filter(B=>{const U=s.toLowerCase(),G=!s||B.name.toLowerCase().includes(U)||B.email.toLowerCase().includes(U),H=n==="all"||n==="none"&&!B.brokerage_id||B.brokerage_id===n,Y=parseInt(c)||0,se=parseInt(u)||0,ee=parseInt(m)||0,oe=parseInt(g)||0,me=B.contact_count>=Y&&B.video_count>=se&&B.popby_count>=ee&&B.listing_count>=oe;return G&&H&&me});return O.sort((B,U)=>{let G=0;return a==="name"?G=B.name.localeCompare(U.name):G=B[a]-U[a],l==="asc"?G:-G}),O},[_,s,n,a,l,c,u,m,g]),A=O=>{a===O?o(l==="asc"?"desc":"asc"):(i(O),o("desc"))},M=()=>{const O=["Name","Email","Brokerage","Contacts","Videos","Popbys","Listings","Deals","Portals (Active)","Cards Created","Cards Sent","Card Views"],B=C.map(se=>[se.name,se.email,se.brokerage_name||"None",se.contact_count,se.video_count,se.popby_count,se.listing_count,se.deal_count,`${se.portal_count} (${se.active_portal_count})`,se.card_count,se.sent_card_count,se.total_card_views]),U=[O.join(","),...B.map(se=>se.map(ee=>`"${ee}"`).join(","))].join(` `),G=new Blob([U],{type:"text/csv"}),H=URL.createObjectURL(G),Y=document.createElement("a");Y.href=H,Y.download=`agent-os-user-stats-${new Date().toISOString().split("T")[0]}.csv`,Y.click(),URL.revokeObjectURL(H)},I=k.useMemo(()=>C.length?C.reduce((O,B)=>({contacts:O.contacts+B.contact_count,videos:O.videos+B.video_count,popbys:O.popbys+B.popby_count,listings:O.listings+B.listing_count,deals:O.deals+B.deal_count,portals:O.portals+B.portal_count,activePortals:O.activePortals+B.active_portal_count,cards:O.cards+B.card_count,sentCards:O.sentCards+B.sent_card_count,cardViews:O.cardViews+B.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},[C]),P=k.useMemo(()=>C.length?{portals:C.filter(O=>O.portal_count>0).length,cards:C.filter(O=>O.card_count>0).length}:{portals:0,cards:0},[C]),R=({field:O,children:B})=>e.jsx(Dt,{className:"cursor-pointer hover:bg-muted/50 select-none",onClick:()=>A(O),children:e.jsxs("div",{className:"flex items-center gap-1",children:[B,e.jsx(Ix,{className:`h-3 w-3 ${a===O?"text-primary":"text-muted-foreground"}`})]})});return e.jsx(Sk,{children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs(we,{className:"border-blue-500/20 bg-gradient-to-br from-blue-500/5 to-transparent",children:[e.jsx(Vt,{className:"pb-2",children:e.jsxs(Yt,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(x2,{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:P.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:I.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:I.activePortals}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Active Portals"})]})]})})]}),e.jsxs(we,{className:"border-violet-500/20 bg-gradient-to-br from-violet-500/5 to-transparent",children:[e.jsx(Vt,{className:"pb-2",children:e.jsxs(Yt,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(pn,{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:P.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:I.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:I.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:I.cardViews}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Total Views"})]})]})})]})]}),e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(Yt,{className:"flex items-center gap-2",children:[e.jsx(Xn,{className:"h-5 w-5"}),"User Activity Analytics"]}),e.jsx(vr,{children:"View all users and their Agent OS usage metrics"})]}),e.jsxs($,{variant:"outline",size:"sm",onClick:M,children:[e.jsx(ji,{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(Yr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search by name or email...",value:s,onChange:O=>t(O.target.value),className:"pl-9"})]})}),e.jsx("div",{children:e.jsxs(bs,{value:n,onValueChange:r,children:[e.jsxs(ys,{children:[e.jsx(Gi,{className:"h-4 w-4 mr-2 text-muted-foreground"}),e.jsx(_s,{placeholder:"Brokerage"})]}),e.jsxs(vs,{children:[e.jsx(We,{value:"all",children:"All Brokerages"}),e.jsx(We,{value:"none",children:"No Brokerage"}),y==null?void 0:y.map(O=>e.jsx(We,{value:O.id,children:O.name},O.id))]})]})}),e.jsx("div",{children:e.jsx(be,{type:"number",placeholder:"Min contacts",value:c,onChange:O=>d(O.target.value),min:"0"})}),e.jsx("div",{children:e.jsx(be,{type:"number",placeholder:"Min videos",value:u,onChange:O=>h(O.target.value),min:"0"})}),e.jsx("div",{children:e.jsx(be,{type:"number",placeholder:"Min popbys",value:m,onChange:O=>p(O.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:C.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:I.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:I.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:I.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:I.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:I.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:I.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:I.cards.toLocaleString()}),e.jsx("div",{className:"text-muted-foreground",children:"Cards"})]})]}),j?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx(Jt,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsx("div",{className:"rounded-md border overflow-x-auto",children:e.jsxs(Qa,{children:[e.jsx(Ja,{children:e.jsxs(vn,{children:[e.jsx(R,{field:"name",children:"Name"}),e.jsx(Dt,{children:"Email"}),e.jsx(Dt,{children:"Brokerage"}),e.jsx(R,{field:"contact_count",children:"Contacts"}),e.jsx(R,{field:"video_count",children:"Videos"}),e.jsx(R,{field:"popby_count",children:"Popbys"}),e.jsx(R,{field:"listing_count",children:"Listings"}),e.jsx(R,{field:"deal_count",children:"Deals"}),e.jsx(R,{field:"portal_count",children:e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(x2,{className:"h-3 w-3 text-blue-500"}),"Portals"]})}),e.jsx(R,{field:"card_count",children:e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(pn,{className:"h-3 w-3 text-violet-500"}),"Cards"]})})]})}),e.jsx(ei,{children:C.length===0?e.jsx(vn,{children:e.jsx(_t,{colSpan:10,className:"text-center py-8 text-muted-foreground",children:"No users found matching your filters"})}):C.map(O=>e.jsxs(vn,{children:[e.jsx(_t,{className:"font-medium",children:O.name}),e.jsx(_t,{className:"text-muted-foreground",children:O.email}),e.jsx(_t,{children:O.brokerage_name?e.jsx(qe,{variant:"secondary",children:O.brokerage_name}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx(_t,{children:e.jsx(qe,{variant:O.contact_count>0?"default":"outline",children:O.contact_count})}),e.jsx(_t,{children:e.jsx(qe,{variant:O.video_count>0?"default":"outline",children:O.video_count})}),e.jsx(_t,{children:e.jsx(qe,{variant:O.popby_count>0?"default":"outline",children:O.popby_count})}),e.jsx(_t,{children:e.jsx(qe,{variant:O.listing_count>0?"default":"outline",children:O.listing_count})}),e.jsx(_t,{children:e.jsx(qe,{variant:O.deal_count>0?"default":"outline",children:O.deal_count})}),e.jsx(_t,{children:O.portal_count>0?e.jsxs(Lx,{children:[e.jsx(Rx,{children:e.jsxs(qe,{variant:"default",className:"bg-blue-600 hover:bg-blue-700",children:[O.portal_count,O.active_portal_count>0&&e.jsxs("span",{className:"ml-1 opacity-75",children:["(",O.active_portal_count," active)"]})]})}),e.jsxs(Jg,{children:[e.jsxs("p",{children:[O.portal_count," total portals"]}),e.jsxs("p",{children:[O.active_portal_count," currently active"]})]})]}):e.jsx(qe,{variant:"outline",children:"0"})}),e.jsx(_t,{children:O.card_count>0?e.jsxs(Lx,{children:[e.jsx(Rx,{children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(qe,{variant:"default",className:"bg-violet-600 hover:bg-violet-700",children:O.card_count}),O.sent_card_count>0&&e.jsxs("span",{className:"flex items-center gap-0.5 text-xs text-emerald-600",children:[e.jsx(Wr,{className:"h-3 w-3"}),O.sent_card_count]}),O.total_card_views>0&&e.jsxs("span",{className:"flex items-center gap-0.5 text-xs text-muted-foreground",children:[e.jsx(ba,{className:"h-3 w-3"}),O.total_card_views]})]})}),e.jsxs(Jg,{children:[e.jsxs("p",{children:[O.card_count," cards created"]}),e.jsxs("p",{children:[O.sent_card_count," sent"]}),e.jsxs("p",{children:[O.total_card_views," total views"]})]})]}):e.jsx(qe,{variant:"outline",children:"0"})})]},O.id))})]})})]})]})]})})}function C_n(){Fi(),ls();const[s,t]=k.useState("user-analytics"),{data:n}=pt({queryKey:["admin-feature-flags"],queryFn:async()=>{const{data:p,error:g}=await V.from("feature_flags").select("*").order("key");if(g)throw g;return p}}),{data:r,isLoading:a}=pt({queryKey:["admin-relationship-types"],queryFn:async()=>{const{data:p,error:g}=await V.from("relationship_types").select("*").order("sort_order");if(g)throw g;return p}}),{data:i,isLoading:l}=pt({queryKey:["admin-action-types"],queryFn:async()=>{const{data:p,error:g}=await V.from("action_types").select("*").order("sort_order");if(g)throw g;return p}}),{data:o,isLoading:c}=pt({queryKey:["admin-action-scripts"],queryFn:async()=>{const{data:p,error:g}=await V.from("action_scripts").select("*, action_type:action_types(*)");if(g)throw g;return p}}),{data:d,isLoading:u}=pt({queryKey:["admin-touchpoint-plans"],queryFn:async()=>{const{data:p,error:g}=await V.from("touchpoint_plans").select("*").order("name");if(g)throw g;return p}}),{data:h,isLoading:m}=pt({queryKey:["admin-popby-items"],queryFn:async()=>{const{data:p,error:g}=await V.from("popby_items").select("*").is("owner_user_id",null).order("name");if(g)throw g;return p}});return e.jsx(Xs,{title:"Agent OS Control Center",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(nm,{title:"Agent OS Control Center",description:"Manage InnerCircle settings, scripts, and touchpoint plans"}),e.jsxs(ya,{value:s,onValueChange:t,children:[e.jsxs(va,{className:"grid w-full grid-cols-9",children:[e.jsxs(is,{value:"user-analytics",className:"gap-2",children:[e.jsx(Ul,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Users"})]}),e.jsxs(is,{value:"relationship-types",className:"gap-2",children:[e.jsx(Xn,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Relationships"})]}),e.jsxs(is,{value:"action-types",className:"gap-2",children:[e.jsx(ka,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Actions"})]}),e.jsxs(is,{value:"scripts",className:"gap-2",children:[e.jsx(ea,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Scripts"})]}),e.jsxs(is,{value:"video-scripts",className:"gap-2",children:[e.jsx(em,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Video Scripts"})]}),e.jsxs(is,{value:"plans",className:"gap-2",children:[e.jsx(ha,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Plans"})]}),e.jsxs(is,{value:"popbys",className:"gap-2",children:[e.jsx(Zo,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Popbys"})]}),e.jsxs(is,{value:"settings",className:"gap-2",children:[e.jsx(Yc,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Settings"})]}),e.jsxs(is,{value:"feature-flags",className:"gap-2",children:[e.jsx(g3,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Flags"})]})]}),e.jsx(cs,{value:"user-analytics",className:"mt-6",children:e.jsx(S_n,{})}),e.jsx(cs,{value:"relationship-types",className:"mt-6",children:e.jsx(A_n,{types:r||[],isLoading:a})}),e.jsx(cs,{value:"action-types",className:"mt-6",children:e.jsx(E_n,{types:i||[],isLoading:l})}),e.jsx(cs,{value:"scripts",className:"mt-6",children:e.jsx(T_n,{scripts:o||[],actionTypes:i||[],isLoading:c})}),e.jsx(cs,{value:"video-scripts",className:"mt-6",children:e.jsx(L_n,{})}),e.jsx(cs,{value:"plans",className:"mt-6",children:e.jsx(M_n,{plans:d||[],actionTypes:i||[],scripts:o||[],isLoading:u})}),e.jsx(cs,{value:"popbys",className:"mt-6",children:e.jsx(I_n,{items:h||[],isLoading:m})}),e.jsx(cs,{value:"settings",className:"mt-6",children:e.jsx(R_n,{})}),e.jsx(cs,{value:"feature-flags",className:"mt-6",children:e.jsx(P_n,{flags:n||[]})})]})]})})}function A_n({types:s,isLoading:t}){const{toast:n}=Fi(),r=ls(),[a,i]=k.useState(null),[l,o]=k.useState(!1),c=Nt({mutationFn:async u=>{if(u.id){const{error:h}=await V.from("relationship_types").update({name:u.name,description:u.description,icon:u.icon}).eq("id",u.id);if(h)throw h}else{const{error:h}=await V.from("relationship_types").insert([{name:u.name,description:u.description,icon:u.icon,sort_order:s.length}]);if(h)throw h}},onSuccess:()=>{r.invalidateQueries({queryKey:["admin-relationship-types"]}),o(!1),i(null),n({title:"Saved successfully"})},onError:u=>{n({title:"Error",description:u.message,variant:"destructive"})}}),d=async u=>{await V.from("relationship_types").update({active:!u.active}).eq("id",u.id),r.invalidateQueries({queryKey:["admin-relationship-types"]})};return e.jsxs(we,{children:[e.jsxs(Vt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Yt,{children:"Relationship Types"}),e.jsx(vr,{children:"Define the relationship categories for InnerCircle contacts"})]}),e.jsxs($,{onClick:()=>{i(null),o(!0)},children:[e.jsx(nn,{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(Jt,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsxs(Qa,{children:[e.jsx(Ja,{children:e.jsxs(vn,{children:[e.jsx(Dt,{className:"w-12"}),e.jsx(Dt,{children:"Name"}),e.jsx(Dt,{children:"Description"}),e.jsx(Dt,{children:"Status"}),e.jsx(Dt,{className:"w-24",children:"Actions"})]})}),e.jsx(ei,{children:s.map(u=>e.jsxs(vn,{children:[e.jsx(_t,{children:e.jsx(Bp,{className:"h-4 w-4 text-muted-foreground cursor-grab"})}),e.jsx(_t,{className:"font-medium",children:u.name}),e.jsx(_t,{className:"text-muted-foreground",children:u.description}),e.jsx(_t,{children:e.jsx(On,{checked:u.active,onCheckedChange:()=>d(u)})}),e.jsx(_t,{children:e.jsx($,{variant:"ghost",size:"icon",onClick:()=>{i(u),o(!0)},children:e.jsx(ui,{className:"h-4 w-4"})})})]},u.id))})]})}),e.jsx(zs,{open:l,onOpenChange:o,children:e.jsxs(Rs,{children:[e.jsx(Vs,{children:e.jsxs($s,{children:[a?"Edit":"Add"," Relationship Type"]})}),e.jsxs("form",{onSubmit:u=>{u.preventDefault();const h=new FormData(u.currentTarget);c.mutate({id:a==null?void 0:a.id,name:h.get("name"),description:h.get("description"),icon:h.get("icon")})},children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(re,{htmlFor:"name",children:"Name"}),e.jsx(be,{id:"name",name:"name",defaultValue:a==null?void 0:a.name,required:!0})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"description",children:"Description"}),e.jsx(Ls,{id:"description",name:"description",defaultValue:(a==null?void 0:a.description)||""})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"icon",children:"Icon"}),e.jsx(be,{id:"icon",name:"icon",defaultValue:(a==null?void 0:a.icon)||"",placeholder:"e.g., star, heart, user"})]})]}),e.jsxs(kr,{className:"mt-4",children:[e.jsx($,{type:"button",variant:"outline",onClick:()=>o(!1),children:"Cancel"}),e.jsxs($,{type:"submit",disabled:c.isPending,children:[c.isPending&&e.jsx(Jt,{className:"h-4 w-4 mr-2 animate-spin"}),"Save"]})]})]})]})})]})}function E_n({types:s,isLoading:t}){const{toast:n}=Fi(),r=ls(),[a,i]=k.useState(null),[l,o]=k.useState(!1),c=Nt({mutationFn:async u=>{if(u.id){const{error:h}=await V.from("action_types").update({name:u.name,description:u.description,icon:u.icon,color:u.color}).eq("id",u.id);if(h)throw h}else{const{error:h}=await V.from("action_types").insert([{name:u.name,description:u.description,icon:u.icon,color:u.color,sort_order:s.length}]);if(h)throw h}},onSuccess:()=>{r.invalidateQueries({queryKey:["admin-action-types"]}),o(!1),i(null),n({title:"Saved successfully"})},onError:u=>{n({title:"Error",description:u.message,variant:"destructive"})}}),d=async u=>{await V.from("action_types").update({active:!u.active}).eq("id",u.id),r.invalidateQueries({queryKey:["admin-action-types"]})};return e.jsxs(we,{children:[e.jsxs(Vt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Yt,{children:"Action Types"}),e.jsx(vr,{children:"Define the types of touchpoint actions agents can take"})]}),e.jsxs($,{onClick:()=>{i(null),o(!0)},children:[e.jsx(nn,{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(Jt,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsxs(Qa,{children:[e.jsx(Ja,{children:e.jsxs(vn,{children:[e.jsx(Dt,{children:"Name"}),e.jsx(Dt,{children:"Description"}),e.jsx(Dt,{children:"Color"}),e.jsx(Dt,{children:"Status"}),e.jsx(Dt,{className:"w-24",children:"Actions"})]})}),e.jsx(ei,{children:s.map(u=>e.jsxs(vn,{children:[e.jsx(_t,{className:"font-medium",children:u.name}),e.jsx(_t,{className:"text-muted-foreground",children:u.description}),e.jsx(_t,{children:u.color&&e.jsx("div",{className:"w-6 h-6 rounded",style:{backgroundColor:u.color}})}),e.jsx(_t,{children:e.jsx(On,{checked:u.active,onCheckedChange:()=>d(u)})}),e.jsx(_t,{children:e.jsx($,{variant:"ghost",size:"icon",onClick:()=>{i(u),o(!0)},children:e.jsx(ui,{className:"h-4 w-4"})})})]},u.id))})]})}),e.jsx(zs,{open:l,onOpenChange:o,children:e.jsxs(Rs,{children:[e.jsx(Vs,{children:e.jsxs($s,{children:[a?"Edit":"Add"," Action Type"]})}),e.jsxs("form",{onSubmit:u=>{u.preventDefault();const h=new FormData(u.currentTarget);c.mutate({id:a==null?void 0:a.id,name:h.get("name"),description:h.get("description"),icon:h.get("icon"),color:h.get("color")})},children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(re,{htmlFor:"name",children:"Name"}),e.jsx(be,{id:"name",name:"name",defaultValue:a==null?void 0:a.name,required:!0})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"description",children:"Description"}),e.jsx(Ls,{id:"description",name:"description",defaultValue:(a==null?void 0:a.description)||""})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"icon",children:"Icon"}),e.jsx(be,{id:"icon",name:"icon",defaultValue:(a==null?void 0:a.icon)||"",placeholder:"e.g., phone, message"})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"color",children:"Color"}),e.jsx(be,{id:"color",name:"color",type:"color",defaultValue:(a==null?void 0:a.color)||"#6366f1"})]})]}),e.jsxs(kr,{className:"mt-4",children:[e.jsx($,{type:"button",variant:"outline",onClick:()=>o(!1),children:"Cancel"}),e.jsxs($,{type:"submit",disabled:c.isPending,children:[c.isPending&&e.jsx(Jt,{className:"h-4 w-4 mr-2 animate-spin"}),"Save"]})]})]})]})})]})}function T_n({scripts:s,actionTypes:t,isLoading:n}){const{toast:r}=Fi(),a=ls(),[i,l]=k.useState(null),[o,c]=k.useState(!1),d=Nt({mutationFn:async h=>{if(h.id){const{error:m}=await V.from("action_scripts").update({title:h.title,action_type_id:h.action_type_id,tone:h.tone,script_body:h.script_body,active:h.active}).eq("id",h.id);if(m)throw m}else{const{error:m}=await V.from("action_scripts").insert([{title:h.title,action_type_id:h.action_type_id,tone:h.tone,script_body:h.script_body,active:!0}]);if(m)throw m}},onSuccess:()=>{a.invalidateQueries({queryKey:["admin-action-scripts"]}),c(!1),l(null),r({title:"Saved successfully"})},onError:h=>{r({title:"Error",description:h.message,variant:"destructive"})}}),u=Nt({mutationFn:async h=>{const{error:m}=await V.from("action_scripts").delete().eq("id",h);if(m)throw m},onSuccess:()=>{a.invalidateQueries({queryKey:["admin-action-scripts"]}),r({title:"Deleted successfully"})}});return e.jsxs(we,{children:[e.jsxs(Vt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Yt,{children:"Script Library"}),e.jsx(vr,{children:"Create and manage scripts for each action type"})]}),e.jsxs($,{onClick:()=>{l(null),c(!0)},children:[e.jsx(nn,{className:"h-4 w-4 mr-2"}),"Add Script"]})]}),e.jsx(De,{children:n?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(Jt,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsxs(Qa,{children:[e.jsx(Ja,{children:e.jsxs(vn,{children:[e.jsx(Dt,{children:"Title"}),e.jsx(Dt,{children:"Action Type"}),e.jsx(Dt,{children:"Tone"}),e.jsx(Dt,{children:"Status"}),e.jsx(Dt,{className:"w-24",children:"Actions"})]})}),e.jsx(ei,{children:s.map(h=>{var m;return e.jsxs(vn,{children:[e.jsx(_t,{className:"font-medium",children:h.title}),e.jsx(_t,{children:e.jsx(qe,{variant:"outline",children:((m=h.action_type)==null?void 0:m.name)||"Unknown"})}),e.jsx(_t,{className:"text-muted-foreground",children:h.tone}),e.jsx(_t,{children:e.jsx(qe,{variant:h.active?"default":"secondary",children:h.active?"Active":"Inactive"})}),e.jsxs(_t,{className:"flex gap-1",children:[e.jsx($,{variant:"ghost",size:"icon",onClick:()=>{l(h),c(!0)},children:e.jsx(ui,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>u.mutate(h.id),children:e.jsx(Un,{className:"h-4 w-4 text-destructive"})})]})]},h.id)})})]})}),e.jsx(zs,{open:o,onOpenChange:c,children:e.jsxs(Rs,{className:"max-w-2xl",children:[e.jsx(Vs,{children:e.jsxs($s,{children:[i?"Edit":"Add"," Script"]})}),e.jsxs("form",{onSubmit:h=>{h.preventDefault();const m=new FormData(h.currentTarget);d.mutate({id:i==null?void 0:i.id,title:m.get("title"),action_type_id:m.get("action_type_id"),tone:m.get("tone"),script_body:m.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(re,{htmlFor:"title",children:"Title"}),e.jsx(be,{id:"title",name:"title",defaultValue:i==null?void 0:i.title,required:!0})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"action_type_id",children:"Action Type"}),e.jsxs(bs,{name:"action_type_id",defaultValue:i==null?void 0:i.action_type_id,children:[e.jsx(ys,{children:e.jsx(_s,{placeholder:"Select action type"})}),e.jsx(vs,{children:t.map(h=>e.jsx(We,{value:h.id,children:h.name},h.id))})]})]})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"tone",children:"Tone (optional)"}),e.jsx(be,{id:"tone",name:"tone",defaultValue:(i==null?void 0:i.tone)||"",placeholder:"e.g., Friendly, Professional, Casual"})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"script_body",children:"Script Body"}),e.jsx(Ls,{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(kr,{className:"mt-4",children:[e.jsx($,{type:"button",variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsxs($,{type:"submit",disabled:d.isPending,children:[d.isPending&&e.jsx(Jt,{className:"h-4 w-4 mr-2 animate-spin"}),"Save"]})]})]})]})})]})}function M_n({plans:s,actionTypes:t,scripts:n,isLoading:r}){const{toast:a}=Fi(),i=ls(),[l,o]=k.useState(null),[c,d]=k.useState(!1),[u,h]=k.useState(null),[m,p]=k.useState(!1),[g,x]=k.useState(null),[y,v]=k.useState(null),{data:_}=pt({queryKey:["plan-items",u],queryFn:async()=>{if(!u)return[];const{data:R,error:O}=await V.from("touchpoint_plan_items").select("*").eq("plan_id",u).order("month_number");if(O)throw O;return R},enabled:!!u}),j=Nt({mutationFn:async R=>{if(R.id){const{error:O}=await V.from("touchpoint_plans").update({name:R.name,description:R.description,active:R.active}).eq("id",R.id);if(O)throw O}else{const{error:O}=await V.from("touchpoint_plans").insert([{name:R.name,description:R.description,active:!0}]);if(O)throw O}},onSuccess:()=>{i.invalidateQueries({queryKey:["admin-touchpoint-plans"]}),d(!1),o(null),a({title:"Saved successfully"})},onError:R=>{a({title:"Error",description:R.message,variant:"destructive"})}}),C=Nt({mutationFn:async R=>{if(R.id){const{error:O}=await V.from("touchpoint_plan_items").update({action_type_id:R.action_type_id,default_script_id:R.default_script_id,notes:R.notes}).eq("id",R.id);if(O)throw O}else{const{error:O}=await V.from("touchpoint_plan_items").insert([{plan_id:R.plan_id,month_number:R.month_number,action_type_id:R.action_type_id,default_script_id:R.default_script_id,notes:R.notes}]);if(O)throw O}},onSuccess:()=>{i.invalidateQueries({queryKey:["plan-items",u]}),a({title:"Item saved"})}}),A=Nt({mutationFn:async R=>{const{error:O}=await V.from("touchpoint_plan_items").delete().eq("id",R);if(O)throw O},onSuccess:()=>{i.invalidateQueries({queryKey:["plan-items",u]})}}),M=Nt({mutationFn:async R=>{const{data:O,error:B}=await V.from("action_scripts").insert([{...R,active:!0}]).select().single();if(B)throw B;return O},onSuccess:async R=>{i.invalidateQueries({queryKey:["admin-action-scripts"]}),g&&await C.mutateAsync({id:g.itemId,plan_id:u,month_number:g.month,action_type_id:g.actionTypeId,default_script_id:R.id}),p(!1),x(null),a({title:"Script created and assigned"})},onError:R=>{a({title:"Error",description:R.message,variant:"destructive"})}}),I=(R,O,B)=>{x({month:R,actionTypeId:O,itemId:B}),p(!0)},P=R=>n.find(O=>O.id===R);return e.jsxs("div",{className:"space-y-6",children:[e.jsxs(we,{children:[e.jsxs(Vt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Yt,{children:"Touchpoint Plans"}),e.jsx(vr,{children:"Create annual touchpoint plans that agents can apply to their contacts"})]}),e.jsxs($,{onClick:()=>{o(null),d(!0)},children:[e.jsx(nn,{className:"h-4 w-4 mr-2"}),"Add Plan"]})]}),e.jsx(De,{children:r?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(Jt,{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(R=>e.jsxs(we,{className:`cursor-pointer transition-colors ${u===R.id?"border-primary":""}`,onClick:()=>h(R.id),children:[e.jsx(Vt,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(Yt,{className:"text-base",children:R.name}),e.jsx($,{variant:"ghost",size:"icon",onClick:O=>{O.stopPropagation(),o(R),d(!0)},children:e.jsx(ui,{className:"h-4 w-4"})})]})}),e.jsxs(De,{children:[e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2",children:R.description}),e.jsx(qe,{variant:R.active?"default":"secondary",className:"mt-2",children:R.active?"Active":"Inactive"})]})]},R.id))})})]}),u&&e.jsxs(we,{children:[e.jsxs(Vt,{children:[e.jsx(Yt,{children:"Plan Schedule"}),e.jsx(vr,{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},(R,O)=>O+1).map(R=>{const O=_==null?void 0:_.find(G=>G.month_number===R),B=O!=null&&O.default_script_id?P(O.default_script_id):null,U=n.filter(G=>G.action_type_id===(O==null?void 0:O.action_type_id)&&G.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 ",R]}),e.jsxs(bs,{value:(O==null?void 0:O.action_type_id)||"none",onValueChange:G=>{G==="none"&&O?A.mutate(O.id):G!=="none"&&C.mutate({id:O==null?void 0:O.id,plan_id:u,month_number:R,action_type_id:G,default_script_id:null})},children:[e.jsx(ys,{className:"w-40",children:e.jsx(_s,{placeholder:"No action"})}),e.jsxs(vs,{children:[e.jsx(We,{value:"none",children:"No action"}),t.filter(G=>G.active).map(G=>e.jsx(We,{value:G.id,children:e.jsxs("span",{className:"flex items-center gap-2",children:[G.color&&e.jsx("span",{className:"w-3 h-3 rounded-full",style:{backgroundColor:G.color}}),G.name]})},G.id))]})]}),O&&e.jsxs(e.Fragment,{children:[e.jsxs(bs,{value:O.default_script_id||"none",onValueChange:G=>{v(null),C.mutate({id:O.id,default_script_id:G==="none"?null:G})},children:[e.jsx(ys,{className:"w-56",children:e.jsx(_s,{placeholder:"Select script"})}),e.jsxs(vs,{children:[e.jsx(We,{value:"none",children:"No default script"}),U.map(G=>e.jsxs(We,{value:G.id,children:[G.title," ",G.tone&&`(${G.tone})`]},G.id))]})]}),e.jsxs($,{variant:"outline",size:"sm",onClick:()=>I(R,O.action_type_id,O.id),children:[e.jsx(nn,{className:"h-3 w-3 mr-1"}),"New Script"]}),B&&e.jsx($,{variant:"ghost",size:"sm",onClick:()=>v((y==null?void 0:y.id)===B.id?null:B),children:(y==null?void 0:y.id)===B.id?"Hide":"Preview"})]})]}),y&&(O==null?void 0:O.default_script_id)===y.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(qe,{variant:"outline",children:y.title}),y.tone&&e.jsx(qe,{variant:"secondary",children:y.tone})]}),e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:y.script_body})]})]},R)})})})]}),e.jsx(zs,{open:c,onOpenChange:d,children:e.jsxs(Rs,{children:[e.jsx(Vs,{children:e.jsxs($s,{children:[l?"Edit":"Add"," Touchpoint Plan"]})}),e.jsxs("form",{onSubmit:R=>{R.preventDefault();const O=new FormData(R.currentTarget);j.mutate({id:l==null?void 0:l.id,name:O.get("name"),description:O.get("description"),active:!0})},children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(re,{htmlFor:"name",children:"Name"}),e.jsx(be,{id:"name",name:"name",defaultValue:l==null?void 0:l.name,required:!0})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"description",children:"Description"}),e.jsx(Ls,{id:"description",name:"description",defaultValue:(l==null?void 0:l.description)||"",rows:3})]})]}),e.jsxs(kr,{className:"mt-4",children:[e.jsx($,{type:"button",variant:"outline",onClick:()=>d(!1),children:"Cancel"}),e.jsxs($,{type:"submit",disabled:j.isPending,children:[j.isPending&&e.jsx(Jt,{className:"h-4 w-4 mr-2 animate-spin"}),"Save"]})]})]})]})}),e.jsx(zs,{open:m,onOpenChange:p,children:e.jsxs(Rs,{className:"max-w-2xl",children:[e.jsxs(Vs,{children:[e.jsx($s,{children:"Create New Script"}),e.jsxs(Cr,{children:["Create a script for Month ",g==null?void 0:g.month,". Use ","{{FirstName}}",", ","{{LastName}}",", and ","{{AgentName}}"," as placeholders."]})]}),e.jsxs("form",{onSubmit:R=>{R.preventDefault();const O=new FormData(R.currentTarget);M.mutate({title:O.get("title"),action_type_id:g.actionTypeId,tone:O.get("tone"),script_body:O.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(re,{htmlFor:"script_title",children:"Title"}),e.jsx(be,{id:"script_title",name:"title",placeholder:"e.g., Warm Check-In",required:!0})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"script_tone",children:"Tone"}),e.jsx(be,{id:"script_tone",name:"tone",placeholder:"e.g., Friendly, Professional"})]})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"script_body",children:"Script Body"}),e.jsx(Ls,{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(kr,{className:"mt-4",children:[e.jsx($,{type:"button",variant:"outline",onClick:()=>p(!1),children:"Cancel"}),e.jsxs($,{type:"submit",disabled:M.isPending,children:[M.isPending&&e.jsx(Jt,{className:"h-4 w-4 mr-2 animate-spin"}),"Create & Assign"]})]})]})]})})]})}function P_n({flags:s}){const{toast:t}=Fi(),n=ls(),r=async(a,i)=>{const{error:l}=await V.from("feature_flags").update({...i,updated_at:new Date().toISOString()}).eq("id",a.id);l?t({title:"Error",description:l.message,variant:"destructive"}):(n.invalidateQueries({queryKey:["admin-feature-flags"]}),t({title:"Flag updated"}))};return e.jsxs(we,{children:[e.jsxs(Vt,{children:[e.jsx(Yt,{children:"Feature Flags"}),e.jsx(vr,{children:"Control which features are enabled for members"})]}),e.jsx(De,{children:e.jsxs(Qa,{children:[e.jsx(Ja,{children:e.jsxs(vn,{children:[e.jsx(Dt,{children:"Flag"}),e.jsx(Dt,{children:"Status"}),e.jsx(Dt,{children:"Notes"}),e.jsx(Dt,{children:"Last Updated"})]})}),e.jsx(ei,{children:s.map(a=>e.jsxs(vn,{children:[e.jsx(_t,{className:"font-mono text-sm",children:a.key}),e.jsx(_t,{children:e.jsx(On,{checked:a.enabled,onCheckedChange:i=>r(a,{enabled:i})})}),e.jsx(_t,{children:e.jsx(be,{defaultValue:a.notes||"",placeholder:"Add notes...",className:"max-w-xs",onBlur:i=>{i.target.value!==a.notes&&r(a,{notes:i.target.value})}})}),e.jsx(_t,{className:"text-muted-foreground text-sm",children:new Date(a.updated_at).toLocaleDateString()})]},a.id))})]})})]})}function I_n({items:s,isLoading:t}){const{toast:n}=Fi(),r=ls(),[a,i]=k.useState(null),[l,o]=k.useState(!1),c=Nt({mutationFn:async h=>{if(h.id){const{error:m}=await V.from("popby_items").update({name:h.name,description:h.description}).eq("id",h.id);if(m)throw m}else{const{error:m}=await V.from("popby_items").insert([{name:h.name,description:h.description,owner_user_id:null}]);if(m)throw m}},onSuccess:()=>{r.invalidateQueries({queryKey:["admin-popby-items"]}),r.invalidateQueries({queryKey:["popby-items"]}),o(!1),i(null),n({title:"Saved successfully"})},onError:h=>{n({title:"Error",description:h.message,variant:"destructive"})}}),d=async h=>{await V.from("popby_items").update({is_active:!h.is_active}).eq("id",h.id),r.invalidateQueries({queryKey:["admin-popby-items"]}),r.invalidateQueries({queryKey:["popby-items"]})},u=async h=>{await V.from("popby_items").delete().eq("id",h),r.invalidateQueries({queryKey:["admin-popby-items"]}),r.invalidateQueries({queryKey:["popby-items"]}),n({title:"Deleted successfully"})};return e.jsxs(we,{children:[e.jsxs(Vt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Yt,{children:"Popby Ideas"}),e.jsx(vr,{children:"Manage global popby ideas that all agents can see"})]}),e.jsxs($,{onClick:()=>{i(null),o(!0)},children:[e.jsx(nn,{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(Jt,{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(Zo,{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(Qa,{children:[e.jsx(Ja,{children:e.jsxs(vn,{children:[e.jsx(Dt,{children:"Name"}),e.jsx(Dt,{children:"Description"}),e.jsx(Dt,{children:"Status"}),e.jsx(Dt,{className:"w-24",children:"Actions"})]})}),e.jsx(ei,{children:s.map(h=>e.jsxs(vn,{children:[e.jsx(_t,{className:"font-medium",children:h.name}),e.jsx(_t,{className:"text-muted-foreground",children:h.description}),e.jsx(_t,{children:e.jsx(On,{checked:h.is_active,onCheckedChange:()=>d(h)})}),e.jsx(_t,{children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx($,{variant:"ghost",size:"icon",onClick:()=>{i(h),o(!0)},children:e.jsx(ui,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>u(h.id),children:e.jsx(Un,{className:"h-4 w-4 text-destructive"})})]})})]},h.id))})]})}),e.jsx(zs,{open:l,onOpenChange:o,children:e.jsxs(Rs,{children:[e.jsx(Vs,{children:e.jsxs($s,{children:[a?"Edit":"Add"," Popby Idea"]})}),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")})},children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(re,{htmlFor:"name",children:"Name"}),e.jsx(be,{id:"name",name:"name",defaultValue:a==null?void 0:a.name,required:!0,placeholder:"e.g., Homemade Cookies"})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"description",children:"Description"}),e.jsx(Ls,{id:"description",name:"description",defaultValue:(a==null?void 0:a.description)||"",placeholder:"Brief description of the popby idea..."})]})]}),e.jsxs(kr,{className:"mt-4",children:[e.jsx($,{type:"button",variant:"outline",onClick:()=>o(!1),children:"Cancel"}),e.jsxs($,{type:"submit",disabled:c.isPending,children:[c.isPending&&e.jsx(Jt,{className:"h-4 w-4 mr-2 animate-spin"}),"Save"]})]})]})]})})]})}function L_n(){var p;const{toast:s}=Fi(),t=ls(),[n,r]=k.useState(null),[a,i]=k.useState(!1),{data:l,isLoading:o}=pt({queryKey:["admin-video-script-categories"],queryFn:async()=>{const{data:g,error:x}=await V.from("video_script_categories").select("*").order("sort_order");if(x)throw x;return g}}),{data:c,isLoading:d}=pt({queryKey:["admin-video-scripts"],queryFn:async()=>{const{data:g,error:x}=await V.from("video_scripts").select("*, category:video_script_categories(*)").order("title");if(x)throw x;return g}}),u=Nt({mutationFn:async g=>{var x,y;if(g.id){const{error:v}=await V.from("video_scripts").update({title:g.title,script_text:g.script_text,category_id:g.category_id,tags:((x=g.tags)==null?void 0:x.split(",").map(_=>_.trim()).filter(Boolean))||[]}).eq("id",g.id);if(v)throw v}else{const{error:v}=await V.from("video_scripts").insert([{title:g.title,script_text:g.script_text,category_id:g.category_id||null,tags:((y=g.tags)==null?void 0:y.split(",").map(_=>_.trim()).filter(Boolean))||[]}]);if(v)throw v}},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-video-scripts"]}),i(!1),r(null),s({title:"Video script saved!"})},onError:g=>s({title:"Error",description:g.message,variant:"destructive"})}),h=async g=>{await V.from("video_scripts").update({is_active:!g.is_active}).eq("id",g.id),t.invalidateQueries({queryKey:["admin-video-scripts"]})},m=async g=>{await io("Delete this video script?")&&(await V.from("video_scripts").delete().eq("id",g),t.invalidateQueries({queryKey:["admin-video-scripts"]}),s({title:"Script deleted"}))};return e.jsxs(we,{children:[e.jsxs(Vt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Yt,{children:"Video Scripts"}),e.jsx(vr,{children:"Manage teleprompter scripts for Quick Video Touch"})]}),e.jsxs($,{onClick:()=>{r(null),i(!0)},children:[e.jsx(nn,{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(Jt,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsxs(Qa,{children:[e.jsx(Ja,{children:e.jsxs(vn,{children:[e.jsx(Dt,{children:"Title"}),e.jsx(Dt,{children:"Category"}),e.jsx(Dt,{children:"Status"}),e.jsx(Dt,{className:"w-24",children:"Actions"})]})}),e.jsx(ei,{children:c==null?void 0:c.map(g=>{var x;return e.jsxs(vn,{children:[e.jsx(_t,{className:"font-medium",children:g.title}),e.jsx(_t,{className:"text-muted-foreground",children:((x=g.category)==null?void 0:x.name)||"Uncategorized"}),e.jsx(_t,{children:e.jsx(On,{checked:g.is_active,onCheckedChange:()=>h(g)})}),e.jsxs(_t,{className:"flex gap-1",children:[e.jsx($,{variant:"ghost",size:"icon",onClick:()=>{r(g),i(!0)},children:e.jsx(ui,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>m(g.id),children:e.jsx(Un,{className:"h-4 w-4"})})]})]},g.id)})})]})}),e.jsx(zs,{open:a,onOpenChange:i,children:e.jsxs(Rs,{className:"max-w-2xl",children:[e.jsx(Vs,{children:e.jsxs($s,{children:[n?"Edit":"Add"," Video Script"]})}),e.jsxs("form",{onSubmit:g=>{g.preventDefault();const x=new FormData(g.currentTarget);u.mutate({id:n==null?void 0:n.id,title:x.get("title"),script_text:x.get("script_text"),category_id:x.get("category_id")||null,tags:x.get("tags")})},children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(re,{htmlFor:"title",children:"Title"}),e.jsx(be,{id:"title",name:"title",defaultValue:n==null?void 0:n.title,required:!0})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"category_id",children:"Category"}),e.jsxs(bs,{name:"category_id",defaultValue:(n==null?void 0:n.category_id)||"",children:[e.jsx(ys,{children:e.jsx(_s,{placeholder:"Select category"})}),e.jsx(vs,{children:l==null?void 0:l.map(g=>e.jsx(We,{value:g.id,children:g.name},g.id))})]})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"script_text",children:"Script Text"}),e.jsx(Ls,{id:"script_text",name:"script_text",defaultValue:n==null?void 0:n.script_text,rows:6,required:!0,placeholder:"Enter the teleprompter script..."})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"tags",children:"Tags (comma-separated)"}),e.jsx(be,{id:"tags",name:"tags",defaultValue:((p=n==null?void 0:n.tags)==null?void 0:p.join(", "))||"",placeholder:"birthday, follow-up, thank-you"})]})]}),e.jsxs(kr,{className:"mt-4",children:[e.jsx($,{type:"button",variant:"outline",onClick:()=>i(!1),children:"Cancel"}),e.jsxs($,{type:"submit",disabled:u.isPending,children:[u.isPending&&e.jsx(Jt,{className:"h-4 w-4 mr-2 animate-spin"}),"Save"]})]})]})]})})]})}function R_n(){const{toast:s}=Fi(),[t,n]=k.useState(""),[r,a]=k.useState(!0),[i,l]=k.useState(!1);k.useEffect(()=>{(async()=>{a(!0);try{const{data:d}=await V.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle();d!=null&&d.value&&n(d.value)}catch(d){console.error("Error fetching settings:",d)}a(!1)})()},[]);const o=async()=>{l(!0);try{await V.from("settings").upsert({key:"mapbox_public_token",value:t.trim()}),s({title:"Mapbox token saved!"})}catch{s({title:"Error saving token",variant:"destructive"})}l(!1)};return r?e.jsx(we,{children:e.jsx(De,{className:"flex justify-center py-8",children:e.jsx(Jt,{className:"h-8 w-8 animate-spin text-muted-foreground"})})}):e.jsx("div",{className:"space-y-6",children:e.jsxs(we,{children:[e.jsxs(Vt,{children:[e.jsxs(Yt,{className:"flex items-center gap-2",children:[e.jsx(Si,{className:"h-5 w-5"}),"Popby Map Settings"]}),e.jsx(vr,{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(re,{htmlFor:"mapbox-token",children:"Mapbox Public Token"}),e.jsx(be,{id:"mapbox-token",placeholder:"pk.eyJ1I...",value:t,onChange:c=>n(c.target.value)}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Get your token at"," ",e.jsx("a",{href:"https://mapbox.com/",target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline",children:"mapbox.com"}),". This token will be used by all agents for the popby map feature."]})]}),e.jsxs($,{onClick:o,disabled:i,children:[i&&e.jsx(Jt,{className:"h-4 w-4 mr-2 animate-spin"}),"Save Token"]}),t&&e.jsx(qe,{variant:"secondary",className:"ml-2",children:"Token configured"})]})]})})}const D_n=()=>{const[s,t]=k.useState(""),[n,r]=k.useState("grid"),a=Jn(),{data:i=[],isLoading:l}=pt({queryKey:["additional-services"],queryFn:async()=>{const{data:c,error:d}=await V.from("additional_services").select("*").eq("is_published",!0).order("publish_date",{ascending:!1});if(d)throw d;return c}}),o=i.filter(c=>{var u;return c.name.toLowerCase().includes(s.toLowerCase())||((u=c.description)==null?void 0:u.toLowerCase().includes(s.toLowerCase()))});return e.jsx(Xs,{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(Yr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{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($,{variant:"outline",size:"sm",onClick:()=>t(""),children:"Clear"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx($,{variant:n==="grid"?"secondary":"outline",size:"icon",onClick:()=>r("grid"),className:"rounded-full",children:e.jsx(y0,{className:"h-4 w-4"})}),e.jsx($,{variant:n==="list"?"secondary":"outline",size:"icon",onClick:()=>r("list"),className:"rounded-full",children:e.jsx(Sy,{className:"h-4 w-4"})})]})]})]}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[o.length," service",o.length!==1?"s":""," found"]}),l&&e.jsx("div",{className:n==="grid"?"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6":"space-y-4",children:[...Array(4)].map((c,d)=>e.jsx(we,{children:e.jsxs(De,{className:"p-4",children:[e.jsx(fn,{className:"aspect-[3/2] w-full rounded-lg mb-4"}),e.jsx(fn,{className:"h-5 w-3/4 mb-2"}),e.jsx(fn,{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($,{variant:"outline",onClick:()=>t(""),children:"Clear Search"})]}),!l&&o.length>0&&e.jsx("div",{className:n==="grid"?"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6":"space-y-4",children:o.map(c=>e.jsxs(we,{className:`group overflow-hidden hover:shadow-lg transition-all duration-200 cursor-pointer ${n==="list"?"flex flex-row":""}`,onClick:()=>a(`/additional-services/${c.id}`),children:[e.jsx("div",{className:`relative overflow-hidden bg-muted ${n==="list"?"w-48 shrink-0":"aspect-[3/2]"}`,children:c.preview_image_url?e.jsx("img",{src:c.preview_image_url,alt:c.name,className:"w-full h-full object-contain group-hover:scale-105 transition-transform duration-300"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center text-muted-foreground",children:e.jsx(kn,{className:"h-8 w-8"})})}),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:c.name}),c.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2 flex-1",children:IZ(c.description)})]})]},c.id))})]})})},O_n=()=>{const{serviceId:s}=oo(),t=Jn(),{data:n,isLoading:r}=pt({queryKey:["additional-service",s],queryFn:async()=>{const{data:a,error:i}=await V.from("additional_services").select("*").eq("id",s).eq("is_published",!0).single();if(i)throw i;return a},enabled:!!s});return r?e.jsx(Xs,{title:"Loading...",children:e.jsxs("div",{className:"max-w-4xl mx-auto space-y-6",children:[e.jsx(fn,{className:"h-8 w-48"}),e.jsx(fn,{className:"h-64 w-full rounded-lg"}),e.jsx(fn,{className:"h-24 w-full"})]})}):n?e.jsx(Xs,{title:n.name,children:e.jsxs("div",{className:"max-w-4xl mx-auto space-y-6",children:[e.jsxs($,{variant:"ghost",onClick:()=>t("/additional-services"),className:"gap-2",children:[e.jsx(Ia,{className:"h-4 w-4"}),"Back to Services"]}),e.jsx(we,{className:"overflow-hidden",children:e.jsx("div",{className:"relative bg-muted",children:n.preview_image_url?e.jsx("img",{src:n.preview_image_url,alt:n.name,className:"w-full h-auto max-h-[500px] object-contain mx-auto"}):e.jsx("div",{className:"w-full h-64 flex items-center justify-center text-muted-foreground",children:e.jsx(kn,{className:"h-16 w-16"})})})}),e.jsx(we,{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:n.name}),e.jsxs("div",{className:"flex items-center text-sm text-muted-foreground",children:[e.jsx(ha,{className:"h-4 w-4 mr-1"}),"Published ",Ys(new Date(n.publish_date),"MMMM d, yyyy")]})]}),n.description&&e.jsx("div",{className:"prose prose-sm max-w-none text-muted-foreground [&_a]:text-primary [&_a]:underline",dangerouslySetInnerHTML:{__html:n.description}}),e.jsx("div",{className:"pt-4 border-t",children:e.jsxs($,{size:"lg",className:"gap-2",onClick:()=>window.open(n.signup_link_url,"_blank"),children:[e.jsx(Ir,{className:"h-5 w-5"}),"Sign Up Now"]})})]})})]})}):e.jsx(Xs,{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($,{onClick:()=>t("/additional-services"),children:[e.jsx(Ia,{className:"h-4 w-4 mr-2"}),"Back to Services"]})]})})},PG=[{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 F_n(){const[s,t]=k.useState(PG[0].id),n=PG.find(r=>r.id===s)||PG[0];return e.jsx(Xs,{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(S5,{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(bs,{value:s,onValueChange:t,children:[e.jsx(ys,{className:"w-full",children:e.jsx(_s,{placeholder:"Select a tool"})}),e.jsx(vs,{children:PG.map(r=>e.jsx(We,{value:r.id,children:r.name},r.id))})]})}),e.jsx("div",{className:"hidden md:block",children:e.jsx(ya,{value:s,onValueChange:t,className:"w-full",children:e.jsx(va,{className:"w-full flex-wrap h-auto gap-1 bg-muted p-1",children:PG.map(r=>e.jsx(is,{value:r.id,className:"flex-1 min-w-[150px] text-xs lg:text-sm whitespace-normal h-auto py-2",children:r.name},r.id))})})}),e.jsx("div",{className:"flex justify-center",children:e.jsx("div",{className:"w-full max-w-[700px]",dangerouslySetInnerHTML:{__html:n.iframe}})})]})})}function z_n(s,t){const n={};return(s[s.length-1]===""?[...s,""]:s).join((n.padRight?" ":"")+","+(n.padLeft===!1?"":" ")).trim()}const B_n=/^[$_\p{ID_Start}][$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,$_n=/^[$_\p{ID_Start}][-$_\u{200C}\u{200D}\p{ID_Continue}]*$/u,U_n={};function Ixt(s,t){return(U_n.jsx?$_n:B_n).test(s)}const q_n=/[ \t\n\f\r]/g;function V_n(s){return typeof s=="object"?s.type==="text"?Lxt(s.value):!1:Lxt(s)}function Lxt(s){return s.replace(q_n,"")===""}class ste{constructor(t,n,r){this.normal=n,this.property=t,r&&(this.space=r)}}ste.prototype.normal={};ste.prototype.property={};ste.prototype.space=void 0;function ZFt(s,t){const n={},r={};for(const a of s)Object.assign(n,a.property),Object.assign(r,a.normal);return new ste(n,r,t)}function OBe(s){return s.toLowerCase()}class $_{constructor(t,n){this.attribute=n,this.property=t}}$_.prototype.attribute="";$_.prototype.booleanish=!1;$_.prototype.boolean=!1;$_.prototype.commaOrSpaceSeparated=!1;$_.prototype.commaSeparated=!1;$_.prototype.defined=!1;$_.prototype.mustUseProperty=!1;$_.prototype.number=!1;$_.prototype.overloadedBoolean=!1;$_.prototype.property="";$_.prototype.spaceSeparated=!1;$_.prototype.space=void 0;let H_n=0;const yc=zF(),Cx=zF(),FBe=zF(),Xa=zF(),um=zF(),hO=zF(),vw=zF();function zF(){return 2**++H_n}const zBe=Object.freeze(Object.defineProperty({__proto__:null,boolean:yc,booleanish:Cx,commaOrSpaceSeparated:vw,commaSeparated:hO,number:Xa,overloadedBoolean:FBe,spaceSeparated:um},Symbol.toStringTag,{value:"Module"})),BRe=Object.keys(zBe);class NZe extends $_{constructor(t,n,r,a){let i=-1;if(super(t,n),Rxt(this,"space",a),typeof r=="number")for(;++i4&&n.slice(0,4)==="data"&&Z_n.test(t)){if(t.charAt(4)==="-"){const i=t.slice(5).replace(Dxt,J_n);r="data"+i.charAt(0).toUpperCase()+i.slice(1)}else{const i=t.slice(4);if(!Dxt.test(i)){let l=i.replace(Y_n,Q_n);l.charAt(0)!=="-"&&(l="-"+l),t="data"+l}}a=NZe}return new a(r,t)}function Q_n(s){return"-"+s.toLowerCase()}function J_n(s){return s.charAt(1).toUpperCase()}const ewn=ZFt([XFt,G_n,e7t,t7t,s7t],"html"),kZe=ZFt([XFt,W_n,e7t,t7t,s7t],"svg");function twn(s){return s.join(" ").trim()}var SZe={},Oxt=/\/\*[^*]*\*+([^/*][^*]*\*+)*\//g,swn=/\n/g,nwn=/^\s*/,rwn=/^(\*?[-#/*\\\w]+(\[[0-9a-z_-]+\])?)\s*/,awn=/^:\s*/,iwn=/^((?:'(?:\\'|.)*?'|"(?:\\"|.)*?"|\([^)]*?\)|[^};])+)/,own=/^[;\s]*/,lwn=/^\s+|\s+$/g,cwn=` `,Fxt="/",zxt="*",YR="",dwn="comment",uwn="declaration";function hwn(s,t){if(typeof s!="string")throw new TypeError("First argument must be a string");if(!s)return[];t=t||{};var n=1,r=1;function a(g){var x=g.match(swn);x&&(n+=x.length);var y=g.lastIndexOf(cwn);r=~y?g.length-y:r+g.length}function i(){var g={line:n,column:r};return function(x){return x.position=new l(g),d(),x}}function l(g){this.start=g,this.end={line:n,column:r},this.source=t.source}l.prototype.content=s;function o(g){var x=new Error(t.source+":"+n+":"+r+": "+g);if(x.reason=g,x.filename=t.source,x.line=n,x.column=r,x.source=s,!t.silent)throw x}function c(g){var x=g.exec(s);if(x){var y=x[0];return a(y),s=s.slice(y.length),x}}function d(){c(nwn)}function u(g){var x;for(g=g||[];x=h();)x!==!1&&g.push(x);return g}function h(){var g=i();if(!(Fxt!=s.charAt(0)||zxt!=s.charAt(1))){for(var x=2;YR!=s.charAt(x)&&(zxt!=s.charAt(x)||Fxt!=s.charAt(x+1));)++x;if(x+=2,YR===s.charAt(x-1))return o("End of comment missing");var y=s.slice(2,x-2);return r+=2,a(y),s=s.slice(x),r+=2,g({type:dwn,comment:y})}}function m(){var g=i(),x=c(rwn);if(x){if(h(),!c(awn))return o("property missing ':'");var y=c(iwn),v=g({type:uwn,property:Bxt(x[0].replace(Oxt,YR)),value:y?Bxt(y[0].replace(Oxt,YR)):YR});return c(own),v}}function p(){var g=[];u(g);for(var x;x=m();)x!==!1&&(g.push(x),u(g));return g}return d(),p()}function Bxt(s){return s?s.replace(lwn,YR):YR}var mwn=hwn,fwn=jf&&jf.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(SZe,"__esModule",{value:!0});SZe.default=gwn;const pwn=fwn(mwn);function gwn(s,t){let n=null;if(!s||typeof s!="string")return n;const r=(0,pwn.default)(s),a=typeof t=="function";return r.forEach(i=>{if(i.type!=="declaration")return;const{property:l,value:o}=i;a?t(l,o,i):o&&(n=n||{},n[l]=o)}),n}var JEe={};Object.defineProperty(JEe,"__esModule",{value:!0});JEe.camelCase=void 0;var xwn=/^--[a-zA-Z0-9_-]+$/,ywn=/-([a-z])/g,vwn=/^[^-]+$/,bwn=/^-(webkit|moz|ms|o|khtml)-/,_wn=/^-(ms)-/,wwn=function(s){return!s||vwn.test(s)||xwn.test(s)},jwn=function(s,t){return t.toUpperCase()},$xt=function(s,t){return"".concat(t,"-")},Nwn=function(s,t){return t===void 0&&(t={}),wwn(s)?s:(s=s.toLowerCase(),t.reactCompat?s=s.replace(_wn,$xt):s=s.replace(bwn,$xt),s.replace(ywn,jwn))};JEe.camelCase=Nwn;var kwn=jf&&jf.__importDefault||function(s){return s&&s.__esModule?s:{default:s}},Swn=kwn(SZe),Cwn=JEe;function BBe(s,t){var n={};return!s||typeof s!="string"||(0,Swn.default)(s,function(r,a){r&&a&&(n[(0,Cwn.camelCase)(r,t)]=a)}),n}BBe.default=BBe;var Awn=BBe;const Ewn=kd(Awn),n7t=r7t("end"),CZe=r7t("start");function r7t(s){return t;function t(n){const r=n&&n.position&&n.position[s]||{};if(typeof r.line=="number"&&r.line>0&&typeof r.column=="number"&&r.column>0)return{line:r.line,column:r.column,offset:typeof r.offset=="number"&&r.offset>-1?r.offset:void 0}}}function Twn(s){const t=CZe(s),n=n7t(s);if(t&&n)return{start:t,end:n}}function XY(s){return!s||typeof s!="object"?"":"position"in s||"type"in s?Uxt(s.position):"start"in s||"end"in s?Uxt(s):"line"in s||"column"in s?$Be(s):""}function $Be(s){return qxt(s&&s.line)+":"+qxt(s&&s.column)}function Uxt(s){return $Be(s&&s.start)+"-"+$Be(s&&s.end)}function qxt(s){return s&&typeof s=="number"?s:1}class w1 extends Error{constructor(t,n,r){super(),typeof n=="string"&&(r=n,n=void 0);let a="",i={},l=!1;if(n&&("line"in n&&"column"in n?i={place:n}:"start"in n&&"end"in n?i={place:n}:"type"in n?i={ancestors:[n],place:n.position}:i={...n}),typeof t=="string"?a=t:!i.cause&&t&&(l=!0,a=t.message,i.cause=t),!i.ruleId&&!i.source&&typeof r=="string"){const c=r.indexOf(":");c===-1?i.ruleId=r:(i.source=r.slice(0,c),i.ruleId=r.slice(c+1))}if(!i.place&&i.ancestors&&i.ancestors){const c=i.ancestors[i.ancestors.length-1];c&&(i.place=c.position)}const o=i.place&&"start"in i.place?i.place.start:i.place;this.ancestors=i.ancestors||void 0,this.cause=i.cause||void 0,this.column=o?o.column:void 0,this.fatal=void 0,this.file="",this.message=a,this.line=o?o.line:void 0,this.name=XY(i.place)||"1:1",this.place=i.place||void 0,this.reason=this.message,this.ruleId=i.ruleId||void 0,this.source=i.source||void 0,this.stack=l&&i.cause&&typeof i.cause.stack=="string"?i.cause.stack:"",this.actual=void 0,this.expected=void 0,this.note=void 0,this.url=void 0}}w1.prototype.file="";w1.prototype.name="";w1.prototype.reason="";w1.prototype.message="";w1.prototype.stack="";w1.prototype.column=void 0;w1.prototype.line=void 0;w1.prototype.ancestors=void 0;w1.prototype.cause=void 0;w1.prototype.fatal=void 0;w1.prototype.place=void 0;w1.prototype.ruleId=void 0;w1.prototype.source=void 0;const AZe={}.hasOwnProperty,Mwn=new Map,Pwn=/[A-Z]/g,Iwn=new Set(["table","tbody","thead","tfoot","tr"]),Lwn=new Set(["td","th"]),a7t="https://github.com/syntax-tree/hast-util-to-jsx-runtime";function Rwn(s,t){if(!t||t.Fragment===void 0)throw new TypeError("Expected `Fragment` in options");const n=t.filePath||void 0;let r;if(t.development){if(typeof t.jsxDEV!="function")throw new TypeError("Expected `jsxDEV` in options when `development: true`");r=qwn(n,t.jsxDEV)}else{if(typeof t.jsx!="function")throw new TypeError("Expected `jsx` in production options");if(typeof t.jsxs!="function")throw new TypeError("Expected `jsxs` in production options");r=Uwn(n,t.jsx,t.jsxs)}const a={Fragment:t.Fragment,ancestors:[],components:t.components||{},create:r,elementAttributeNameCase:t.elementAttributeNameCase||"react",evaluater:t.createEvaluater?t.createEvaluater():void 0,filePath:n,ignoreInvalidStyle:t.ignoreInvalidStyle||!1,passKeys:t.passKeys!==!1,passNode:t.passNode||!1,schema:t.space==="svg"?kZe:ewn,stylePropertyNameCase:t.stylePropertyNameCase||"dom",tableCellAlignToStyle:t.tableCellAlignToStyle!==!1},i=i7t(a,s,void 0);return i&&typeof i!="string"?i:a.create(s,a.Fragment,{children:i||void 0},void 0)}function i7t(s,t,n){if(t.type==="element")return Dwn(s,t,n);if(t.type==="mdxFlowExpression"||t.type==="mdxTextExpression")return Own(s,t);if(t.type==="mdxJsxFlowElement"||t.type==="mdxJsxTextElement")return zwn(s,t,n);if(t.type==="mdxjsEsm")return Fwn(s,t);if(t.type==="root")return Bwn(s,t,n);if(t.type==="text")return $wn(s,t)}function Dwn(s,t,n){const r=s.schema;let a=r;t.tagName.toLowerCase()==="svg"&&r.space==="html"&&(a=kZe,s.schema=a),s.ancestors.push(t);const i=l7t(s,t.tagName,!1),l=Vwn(s,t);let o=TZe(s,t);return Iwn.has(t.tagName)&&(o=o.filter(function(c){return typeof c=="string"?!V_n(c):!0})),o7t(s,l,i,t),EZe(l,o),s.ancestors.pop(),s.schema=r,s.create(t,i,l,n)}function Own(s,t){if(t.data&&t.data.estree&&s.evaluater){const r=t.data.estree.body[0];return r.type,s.evaluater.evaluateExpression(r.expression)}aQ(s,t.position)}function Fwn(s,t){if(t.data&&t.data.estree&&s.evaluater)return s.evaluater.evaluateProgram(t.data.estree);aQ(s,t.position)}function zwn(s,t,n){const r=s.schema;let a=r;t.name==="svg"&&r.space==="html"&&(a=kZe,s.schema=a),s.ancestors.push(t);const i=t.name===null?s.Fragment:l7t(s,t.name,!0),l=Hwn(s,t),o=TZe(s,t);return o7t(s,l,i,t),EZe(l,o),s.ancestors.pop(),s.schema=r,s.create(t,i,l,n)}function Bwn(s,t,n){const r={};return EZe(r,TZe(s,t)),s.create(t,s.Fragment,r,n)}function $wn(s,t){return t.value}function o7t(s,t,n,r){typeof n!="string"&&n!==s.Fragment&&s.passNode&&(t.node=r)}function EZe(s,t){if(t.length>0){const n=t.length>1?t:t[0];n&&(s.children=n)}}function Uwn(s,t,n){return r;function r(a,i,l,o){const d=Array.isArray(l.children)?n:t;return o?d(i,l,o):d(i,l)}}function qwn(s,t){return n;function n(r,a,i,l){const o=Array.isArray(i.children),c=CZe(r);return t(a,i,l,o,{columnNumber:c?c.column-1:void 0,fileName:s,lineNumber:c?c.line:void 0},void 0)}}function Vwn(s,t){const n={};let r,a;for(a in t.properties)if(a!=="children"&&AZe.call(t.properties,a)){const i=Gwn(s,a,t.properties[a]);if(i){const[l,o]=i;s.tableCellAlignToStyle&&l==="align"&&typeof o=="string"&&Lwn.has(t.tagName)?r=o:n[l]=o}}if(r){const i=n.style||(n.style={});i[s.stylePropertyNameCase==="css"?"text-align":"textAlign"]=r}return n}function Hwn(s,t){const n={};for(const r of t.attributes)if(r.type==="mdxJsxExpressionAttribute")if(r.data&&r.data.estree&&s.evaluater){const i=r.data.estree.body[0];i.type;const l=i.expression;l.type;const o=l.properties[0];o.type,Object.assign(n,s.evaluater.evaluateExpression(o.argument))}else aQ(s,t.position);else{const a=r.name;let i;if(r.value&&typeof r.value=="object")if(r.value.data&&r.value.data.estree&&s.evaluater){const o=r.value.data.estree.body[0];o.type,i=s.evaluater.evaluateExpression(o.expression)}else aQ(s,t.position);else i=r.value===null?!0:r.value;n[a]=i}return n}function TZe(s,t){const n=[];let r=-1;const a=s.passKeys?new Map:Mwn;for(;++ra?0:a+t:t=t>a?a:t,n=n>0?n:0,r.length<1e4)l=Array.from(r),l.unshift(t,n),s.splice(...l);else for(n&&s.splice(t,n);i0?(Y5(s,s.length,0,t),s):t}const Gxt={}.hasOwnProperty;function ejn(s){const t={};let n=-1;for(;++n13&&n<32||n>126&&n<160||n>55295&&n<57344||n>64975&&n<65008||(n&65535)===65535||(n&65535)===65534||n>1114111?"�":String.fromCodePoint(n)}function IB(s){return s.replace(/[\t\n\r ]+/g," ").replace(/^ | $/g,"").toLowerCase().toUpperCase()}const u5=y6(/[A-Za-z]/),Gw=y6(/[\dA-Za-z]/),njn=y6(/[#-'*+\--9=?A-Z^-~]/);function UBe(s){return s!==null&&(s<32||s===127)}const qBe=y6(/\d/),rjn=y6(/[\dA-Fa-f]/),ajn=y6(/[!-/:-@[-`{-~]/);function ic(s){return s!==null&&s<-2}function E_(s){return s!==null&&(s<0||s===32)}function nh(s){return s===-2||s===-1||s===32}const ijn=y6(new RegExp("\\p{P}|\\p{S}","u")),ojn=y6(/\s/);function y6(s){return t;function t(n){return n!==null&&n>-1&&s.test(String.fromCharCode(n))}}function CV(s){const t=[];let n=-1,r=0,a=0;for(;++n55295&&i<57344){const o=s.charCodeAt(n+1);i<56320&&o>56319&&o<57344?(l=String.fromCharCode(i,o),a=1):l="�"}else l=String.fromCharCode(i);l&&(t.push(s.slice(r,n),encodeURIComponent(l)),r=n+a+1,l=""),a&&(n+=a,a=0)}return t.join("")+s.slice(r)}function Fm(s,t,n,r){const a=r?r-1:Number.POSITIVE_INFINITY;let i=0;return l;function l(c){return nh(c)?(s.enter(n),o(c)):t(c)}function o(c){return nh(c)&&i++l))return;const I=t.events.length;let P=I,R,O;for(;P--;)if(t.events[P][0]==="exit"&&t.events[P][1].type==="chunkFlow"){if(R){O=t.events[P][1].end;break}R=!0}for(v(r),M=I;Mj;){const A=n[C];t.containerState=A[1],A[0].exit.call(t,s)}n.length=j}function _(){a.write([null]),i=void 0,a=void 0,t.containerState._closeFlow=void 0}}function hjn(s,t,n){return Fm(s,s.attempt(this.parser.constructs.document,t,n),"linePrefix",this.parser.constructs.disable.null.includes("codeIndented")?void 0:4)}function Kxt(s){if(s===null||E_(s)||ojn(s))return 1;if(ijn(s))return 2}function PZe(s,t,n){const r=[];let a=-1;for(;++a1&&s[n][1].end.offset-s[n][1].start.offset>1?2:1;const h={...s[r][1].end},m={...s[n][1].start};Yxt(h,-c),Yxt(m,c),l={type:c>1?"strongSequence":"emphasisSequence",start:h,end:{...s[r][1].end}},o={type:c>1?"strongSequence":"emphasisSequence",start:{...s[n][1].start},end:m},i={type:c>1?"strongText":"emphasisText",start:{...s[r][1].end},end:{...s[n][1].start}},a={type:c>1?"strong":"emphasis",start:{...l.start},end:{...o.end}},s[r][1].end={...l.start},s[n][1].start={...o.end},d=[],s[r][1].end.offset-s[r][1].start.offset&&(d=n2(d,[["enter",s[r][1],t],["exit",s[r][1],t]])),d=n2(d,[["enter",a,t],["enter",l,t],["exit",l,t],["enter",i,t]]),d=n2(d,PZe(t.parser.constructs.insideSpan.null,s.slice(r+1,n),t)),d=n2(d,[["exit",i,t],["enter",o,t],["exit",o,t],["exit",a,t]]),s[n][1].end.offset-s[n][1].start.offset?(u=2,d=n2(d,[["enter",s[n][1],t],["exit",s[n][1],t]])):u=0,Y5(s,r-1,n-r+3,d),n=r+d.length-u-2;break}}for(n=-1;++n0&&nh(M)?Fm(s,_,"linePrefix",i+1)(M):_(M)}function _(M){return M===null||ic(M)?s.check(Zxt,x,C)(M):(s.enter("codeFlowValue"),j(M))}function j(M){return M===null||ic(M)?(s.exit("codeFlowValue"),_(M)):(s.consume(M),j)}function C(M){return s.exit("codeFenced"),t(M)}function A(M,I,P){let R=0;return O;function O(Y){return M.enter("lineEnding"),M.consume(Y),M.exit("lineEnding"),B}function B(Y){return M.enter("codeFencedFence"),nh(Y)?Fm(M,U,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(Y):U(Y)}function U(Y){return Y===o?(M.enter("codeFencedFenceSequence"),G(Y)):P(Y)}function G(Y){return Y===o?(R++,M.consume(Y),G):R>=l?(M.exit("codeFencedFenceSequence"),nh(Y)?Fm(M,H,"whitespace")(Y):H(Y)):P(Y)}function H(Y){return Y===null||ic(Y)?(M.exit("codeFencedFence"),I(Y)):P(Y)}}}function Njn(s,t,n){const r=this;return a;function a(l){return l===null?n(l):(s.enter("lineEnding"),s.consume(l),s.exit("lineEnding"),i)}function i(l){return r.parser.lazy[r.now().line]?n(l):t(l)}}const URe={name:"codeIndented",tokenize:Sjn},kjn={partial:!0,tokenize:Cjn};function Sjn(s,t,n){const r=this;return a;function a(d){return s.enter("codeIndented"),Fm(s,i,"linePrefix",5)(d)}function i(d){const u=r.events[r.events.length-1];return u&&u[1].type==="linePrefix"&&u[2].sliceSerialize(u[1],!0).length>=4?l(d):n(d)}function l(d){return d===null?c(d):ic(d)?s.attempt(kjn,l,c)(d):(s.enter("codeFlowValue"),o(d))}function o(d){return d===null||ic(d)?(s.exit("codeFlowValue"),l(d)):(s.consume(d),o)}function c(d){return s.exit("codeIndented"),t(d)}}function Cjn(s,t,n){const r=this;return a;function a(l){return r.parser.lazy[r.now().line]?n(l):ic(l)?(s.enter("lineEnding"),s.consume(l),s.exit("lineEnding"),a):Fm(s,i,"linePrefix",5)(l)}function i(l){const o=r.events[r.events.length-1];return o&&o[1].type==="linePrefix"&&o[2].sliceSerialize(o[1],!0).length>=4?t(l):ic(l)?a(l):n(l)}}const Ajn={name:"codeText",previous:Tjn,resolve:Ejn,tokenize:Mjn};function Ejn(s){let t=s.length-4,n=3,r,a;if((s[n][1].type==="lineEnding"||s[n][1].type==="space")&&(s[t][1].type==="lineEnding"||s[t][1].type==="space")){for(r=n;++r=this.left.length+this.right.length)throw new RangeError("Cannot access index `"+t+"` in a splice buffer of size `"+(this.left.length+this.right.length)+"`");return tthis.left.length?this.right.slice(this.right.length-r+this.left.length,this.right.length-t+this.left.length).reverse():this.left.slice(t).concat(this.right.slice(this.right.length-r+this.left.length).reverse())}splice(t,n,r){const a=n||0;this.setCursor(Math.trunc(t));const i=this.right.splice(this.right.length-a,Number.POSITIVE_INFINITY);return r&&IG(this.left,r),i.reverse()}pop(){return this.setCursor(Number.POSITIVE_INFINITY),this.left.pop()}push(t){this.setCursor(Number.POSITIVE_INFINITY),this.left.push(t)}pushMany(t){this.setCursor(Number.POSITIVE_INFINITY),IG(this.left,t)}unshift(t){this.setCursor(0),this.right.push(t)}unshiftMany(t){this.setCursor(0),IG(this.right,t.reverse())}setCursor(t){if(!(t===this.left.length||t>this.left.length&&this.right.length===0||t<0&&this.left.length===0))if(t=4?t(l):s.interrupt(r.parser.constructs.flow,n,t)(l)}}function p7t(s,t,n,r,a,i,l,o,c){const d=c||Number.POSITIVE_INFINITY;let u=0;return h;function h(v){return v===60?(s.enter(r),s.enter(a),s.enter(i),s.consume(v),s.exit(i),m):v===null||v===32||v===41||UBe(v)?n(v):(s.enter(r),s.enter(l),s.enter(o),s.enter("chunkString",{contentType:"string"}),x(v))}function m(v){return v===62?(s.enter(i),s.consume(v),s.exit(i),s.exit(a),s.exit(r),t):(s.enter(o),s.enter("chunkString",{contentType:"string"}),p(v))}function p(v){return v===62?(s.exit("chunkString"),s.exit(o),m(v)):v===null||v===60||ic(v)?n(v):(s.consume(v),v===92?g:p)}function g(v){return v===60||v===62||v===92?(s.consume(v),p):p(v)}function x(v){return!u&&(v===null||v===41||E_(v))?(s.exit("chunkString"),s.exit(o),s.exit(l),s.exit(r),t(v)):u999||p===null||p===91||p===93&&!c||p===94&&!o&&"_hiddenFootnoteSupport"in l.parser.constructs?n(p):p===93?(s.exit(i),s.enter(a),s.consume(p),s.exit(a),s.exit(r),t):ic(p)?(s.enter("lineEnding"),s.consume(p),s.exit("lineEnding"),u):(s.enter("chunkString",{contentType:"string"}),h(p))}function h(p){return p===null||p===91||p===93||ic(p)||o++>999?(s.exit("chunkString"),u(p)):(s.consume(p),c||(c=!nh(p)),p===92?m:h)}function m(p){return p===91||p===92||p===93?(s.consume(p),o++,h):h(p)}}function x7t(s,t,n,r,a,i){let l;return o;function o(m){return m===34||m===39||m===40?(s.enter(r),s.enter(a),s.consume(m),s.exit(a),l=m===40?41:m,c):n(m)}function c(m){return m===l?(s.enter(a),s.consume(m),s.exit(a),s.exit(r),t):(s.enter(i),d(m))}function d(m){return m===l?(s.exit(i),c(l)):m===null?n(m):ic(m)?(s.enter("lineEnding"),s.consume(m),s.exit("lineEnding"),Fm(s,d,"linePrefix")):(s.enter("chunkString",{contentType:"string"}),u(m))}function u(m){return m===l||m===null||ic(m)?(s.exit("chunkString"),d(m)):(s.consume(m),m===92?h:u)}function h(m){return m===l||m===92?(s.consume(m),u):u(m)}}function QY(s,t){let n;return r;function r(a){return ic(a)?(s.enter("lineEnding"),s.consume(a),s.exit("lineEnding"),n=!0,r):nh(a)?Fm(s,r,n?"linePrefix":"lineSuffix")(a):t(a)}}const zjn={name:"definition",tokenize:$jn},Bjn={partial:!0,tokenize:Ujn};function $jn(s,t,n){const r=this;let a;return i;function i(p){return s.enter("definition"),l(p)}function l(p){return g7t.call(r,s,o,n,"definitionLabel","definitionLabelMarker","definitionLabelString")(p)}function o(p){return a=IB(r.sliceSerialize(r.events[r.events.length-1][1]).slice(1,-1)),p===58?(s.enter("definitionMarker"),s.consume(p),s.exit("definitionMarker"),c):n(p)}function c(p){return E_(p)?QY(s,d)(p):d(p)}function d(p){return p7t(s,u,n,"definitionDestination","definitionDestinationLiteral","definitionDestinationLiteralMarker","definitionDestinationRaw","definitionDestinationString")(p)}function u(p){return s.attempt(Bjn,h,h)(p)}function h(p){return nh(p)?Fm(s,m,"whitespace")(p):m(p)}function m(p){return p===null||ic(p)?(s.exit("definition"),r.parser.defined.push(a),t(p)):n(p)}}function Ujn(s,t,n){return r;function r(o){return E_(o)?QY(s,a)(o):n(o)}function a(o){return x7t(s,i,n,"definitionTitle","definitionTitleMarker","definitionTitleString")(o)}function i(o){return nh(o)?Fm(s,l,"whitespace")(o):l(o)}function l(o){return o===null||ic(o)?t(o):n(o)}}const qjn={name:"hardBreakEscape",tokenize:Vjn};function Vjn(s,t,n){return r;function r(i){return s.enter("hardBreakEscape"),s.consume(i),a}function a(i){return ic(i)?(s.exit("hardBreakEscape"),t(i)):n(i)}}const Hjn={name:"headingAtx",resolve:Gjn,tokenize:Wjn};function Gjn(s,t){let n=s.length-2,r=3,a,i;return s[r][1].type==="whitespace"&&(r+=2),n-2>r&&s[n][1].type==="whitespace"&&(n-=2),s[n][1].type==="atxHeadingSequence"&&(r===n-1||n-4>r&&s[n-2][1].type==="whitespace")&&(n-=r+1===n?2:4),n>r&&(a={type:"atxHeadingText",start:s[r][1].start,end:s[n][1].end},i={type:"chunkText",start:s[r][1].start,end:s[n][1].end,contentType:"text"},Y5(s,r,n-r+1,[["enter",a,t],["enter",i,t],["exit",i,t],["exit",a,t]])),s}function Wjn(s,t,n){let r=0;return a;function a(u){return s.enter("atxHeading"),i(u)}function i(u){return s.enter("atxHeadingSequence"),l(u)}function l(u){return u===35&&r++<6?(s.consume(u),l):u===null||E_(u)?(s.exit("atxHeadingSequence"),o(u)):n(u)}function o(u){return u===35?(s.enter("atxHeadingSequence"),c(u)):u===null||ic(u)?(s.exit("atxHeading"),t(u)):nh(u)?Fm(s,o,"whitespace")(u):(s.enter("atxHeadingText"),d(u))}function c(u){return u===35?(s.consume(u),c):(s.exit("atxHeadingSequence"),o(u))}function d(u){return u===null||u===35||E_(u)?(s.exit("atxHeadingText"),o(u)):(s.consume(u),d)}}const Kjn=["address","article","aside","base","basefont","blockquote","body","caption","center","col","colgroup","dd","details","dialog","dir","div","dl","dt","fieldset","figcaption","figure","footer","form","frame","frameset","h1","h2","h3","h4","h5","h6","head","header","hr","html","iframe","legend","li","link","main","menu","menuitem","nav","noframes","ol","optgroup","option","p","param","search","section","summary","table","tbody","td","tfoot","th","thead","title","tr","track","ul"],Qxt=["pre","script","style","textarea"],Yjn={concrete:!0,name:"htmlFlow",resolveTo:Qjn,tokenize:Jjn},Zjn={partial:!0,tokenize:t2n},Xjn={partial:!0,tokenize:e2n};function Qjn(s){let t=s.length;for(;t--&&!(s[t][0]==="enter"&&s[t][1].type==="htmlFlow"););return t>1&&s[t-2][1].type==="linePrefix"&&(s[t][1].start=s[t-2][1].start,s[t+1][1].start=s[t-2][1].start,s.splice(t-2,2)),s}function Jjn(s,t,n){const r=this;let a,i,l,o,c;return d;function d(fe){return u(fe)}function u(fe){return s.enter("htmlFlow"),s.enter("htmlFlowData"),s.consume(fe),h}function h(fe){return fe===33?(s.consume(fe),m):fe===47?(s.consume(fe),i=!0,x):fe===63?(s.consume(fe),a=3,r.interrupt?t:Q):u5(fe)?(s.consume(fe),l=String.fromCharCode(fe),y):n(fe)}function m(fe){return fe===45?(s.consume(fe),a=2,p):fe===91?(s.consume(fe),a=5,o=0,g):u5(fe)?(s.consume(fe),a=4,r.interrupt?t:Q):n(fe)}function p(fe){return fe===45?(s.consume(fe),r.interrupt?t:Q):n(fe)}function g(fe){const _e="CDATA[";return fe===_e.charCodeAt(o++)?(s.consume(fe),o===_e.length?r.interrupt?t:U:g):n(fe)}function x(fe){return u5(fe)?(s.consume(fe),l=String.fromCharCode(fe),y):n(fe)}function y(fe){if(fe===null||fe===47||fe===62||E_(fe)){const _e=fe===47,ve=l.toLowerCase();return!_e&&!i&&Qxt.includes(ve)?(a=1,r.interrupt?t(fe):U(fe)):Kjn.includes(l.toLowerCase())?(a=6,_e?(s.consume(fe),v):r.interrupt?t(fe):U(fe)):(a=7,r.interrupt&&!r.parser.lazy[r.now().line]?n(fe):i?_(fe):j(fe))}return fe===45||Gw(fe)?(s.consume(fe),l+=String.fromCharCode(fe),y):n(fe)}function v(fe){return fe===62?(s.consume(fe),r.interrupt?t:U):n(fe)}function _(fe){return nh(fe)?(s.consume(fe),_):O(fe)}function j(fe){return fe===47?(s.consume(fe),O):fe===58||fe===95||u5(fe)?(s.consume(fe),C):nh(fe)?(s.consume(fe),j):O(fe)}function C(fe){return fe===45||fe===46||fe===58||fe===95||Gw(fe)?(s.consume(fe),C):A(fe)}function A(fe){return fe===61?(s.consume(fe),M):nh(fe)?(s.consume(fe),A):j(fe)}function M(fe){return fe===null||fe===60||fe===61||fe===62||fe===96?n(fe):fe===34||fe===39?(s.consume(fe),c=fe,I):nh(fe)?(s.consume(fe),M):P(fe)}function I(fe){return fe===c?(s.consume(fe),c=null,R):fe===null||ic(fe)?n(fe):(s.consume(fe),I)}function P(fe){return fe===null||fe===34||fe===39||fe===47||fe===60||fe===61||fe===62||fe===96||E_(fe)?A(fe):(s.consume(fe),P)}function R(fe){return fe===47||fe===62||nh(fe)?j(fe):n(fe)}function O(fe){return fe===62?(s.consume(fe),B):n(fe)}function B(fe){return fe===null||ic(fe)?U(fe):nh(fe)?(s.consume(fe),B):n(fe)}function U(fe){return fe===45&&a===2?(s.consume(fe),se):fe===60&&a===1?(s.consume(fe),ee):fe===62&&a===4?(s.consume(fe),te):fe===63&&a===3?(s.consume(fe),Q):fe===93&&a===5?(s.consume(fe),me):ic(fe)&&(a===6||a===7)?(s.exit("htmlFlowData"),s.check(Zjn,le,G)(fe)):fe===null||ic(fe)?(s.exit("htmlFlowData"),G(fe)):(s.consume(fe),U)}function G(fe){return s.check(Xjn,H,le)(fe)}function H(fe){return s.enter("lineEnding"),s.consume(fe),s.exit("lineEnding"),Y}function Y(fe){return fe===null||ic(fe)?G(fe):(s.enter("htmlFlowData"),U(fe))}function se(fe){return fe===45?(s.consume(fe),Q):U(fe)}function ee(fe){return fe===47?(s.consume(fe),l="",oe):U(fe)}function oe(fe){if(fe===62){const _e=l.toLowerCase();return Qxt.includes(_e)?(s.consume(fe),te):U(fe)}return u5(fe)&&l.length<8?(s.consume(fe),l+=String.fromCharCode(fe),oe):U(fe)}function me(fe){return fe===93?(s.consume(fe),Q):U(fe)}function Q(fe){return fe===62?(s.consume(fe),te):fe===45&&a===2?(s.consume(fe),Q):U(fe)}function te(fe){return fe===null||ic(fe)?(s.exit("htmlFlowData"),le(fe)):(s.consume(fe),te)}function le(fe){return s.exit("htmlFlow"),t(fe)}}function e2n(s,t,n){const r=this;return a;function a(l){return ic(l)?(s.enter("lineEnding"),s.consume(l),s.exit("lineEnding"),i):n(l)}function i(l){return r.parser.lazy[r.now().line]?n(l):t(l)}}function t2n(s,t,n){return r;function r(a){return s.enter("lineEnding"),s.consume(a),s.exit("lineEnding"),s.attempt(eTe,t,n)}}const s2n={name:"htmlText",tokenize:n2n};function n2n(s,t,n){const r=this;let a,i,l;return o;function o(Q){return s.enter("htmlText"),s.enter("htmlTextData"),s.consume(Q),c}function c(Q){return Q===33?(s.consume(Q),d):Q===47?(s.consume(Q),A):Q===63?(s.consume(Q),j):u5(Q)?(s.consume(Q),P):n(Q)}function d(Q){return Q===45?(s.consume(Q),u):Q===91?(s.consume(Q),i=0,g):u5(Q)?(s.consume(Q),_):n(Q)}function u(Q){return Q===45?(s.consume(Q),p):n(Q)}function h(Q){return Q===null?n(Q):Q===45?(s.consume(Q),m):ic(Q)?(l=h,ee(Q)):(s.consume(Q),h)}function m(Q){return Q===45?(s.consume(Q),p):h(Q)}function p(Q){return Q===62?se(Q):Q===45?m(Q):h(Q)}function g(Q){const te="CDATA[";return Q===te.charCodeAt(i++)?(s.consume(Q),i===te.length?x:g):n(Q)}function x(Q){return Q===null?n(Q):Q===93?(s.consume(Q),y):ic(Q)?(l=x,ee(Q)):(s.consume(Q),x)}function y(Q){return Q===93?(s.consume(Q),v):x(Q)}function v(Q){return Q===62?se(Q):Q===93?(s.consume(Q),v):x(Q)}function _(Q){return Q===null||Q===62?se(Q):ic(Q)?(l=_,ee(Q)):(s.consume(Q),_)}function j(Q){return Q===null?n(Q):Q===63?(s.consume(Q),C):ic(Q)?(l=j,ee(Q)):(s.consume(Q),j)}function C(Q){return Q===62?se(Q):j(Q)}function A(Q){return u5(Q)?(s.consume(Q),M):n(Q)}function M(Q){return Q===45||Gw(Q)?(s.consume(Q),M):I(Q)}function I(Q){return ic(Q)?(l=I,ee(Q)):nh(Q)?(s.consume(Q),I):se(Q)}function P(Q){return Q===45||Gw(Q)?(s.consume(Q),P):Q===47||Q===62||E_(Q)?R(Q):n(Q)}function R(Q){return Q===47?(s.consume(Q),se):Q===58||Q===95||u5(Q)?(s.consume(Q),O):ic(Q)?(l=R,ee(Q)):nh(Q)?(s.consume(Q),R):se(Q)}function O(Q){return Q===45||Q===46||Q===58||Q===95||Gw(Q)?(s.consume(Q),O):B(Q)}function B(Q){return Q===61?(s.consume(Q),U):ic(Q)?(l=B,ee(Q)):nh(Q)?(s.consume(Q),B):R(Q)}function U(Q){return Q===null||Q===60||Q===61||Q===62||Q===96?n(Q):Q===34||Q===39?(s.consume(Q),a=Q,G):ic(Q)?(l=U,ee(Q)):nh(Q)?(s.consume(Q),U):(s.consume(Q),H)}function G(Q){return Q===a?(s.consume(Q),a=void 0,Y):Q===null?n(Q):ic(Q)?(l=G,ee(Q)):(s.consume(Q),G)}function H(Q){return Q===null||Q===34||Q===39||Q===60||Q===61||Q===96?n(Q):Q===47||Q===62||E_(Q)?R(Q):(s.consume(Q),H)}function Y(Q){return Q===47||Q===62||E_(Q)?R(Q):n(Q)}function se(Q){return Q===62?(s.consume(Q),s.exit("htmlTextData"),s.exit("htmlText"),t):n(Q)}function ee(Q){return s.exit("htmlTextData"),s.enter("lineEnding"),s.consume(Q),s.exit("lineEnding"),oe}function oe(Q){return nh(Q)?Fm(s,me,"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(Q):me(Q)}function me(Q){return s.enter("htmlTextData"),l(Q)}}const IZe={name:"labelEnd",resolveAll:o2n,resolveTo:l2n,tokenize:c2n},r2n={tokenize:d2n},a2n={tokenize:u2n},i2n={tokenize:h2n};function o2n(s){let t=-1;const n=[];for(;++t=3&&(d===null||ic(d))?(s.exit("thematicBreak"),t(d)):n(d)}function c(d){return d===a?(s.consume(d),r++,c):(s.exit("thematicBreakSequence"),nh(d)?Fm(s,o,"whitespace")(d):o(d))}}const Zb={continuation:{tokenize:w2n},exit:N2n,name:"list",tokenize:_2n},v2n={partial:!0,tokenize:k2n},b2n={partial:!0,tokenize:j2n};function _2n(s,t,n){const r=this,a=r.events[r.events.length-1];let i=a&&a[1].type==="linePrefix"?a[2].sliceSerialize(a[1],!0).length:0,l=0;return o;function o(p){const g=r.containerState.type||(p===42||p===43||p===45?"listUnordered":"listOrdered");if(g==="listUnordered"?!r.containerState.marker||p===r.containerState.marker:qBe(p)){if(r.containerState.type||(r.containerState.type=g,s.enter(g,{_container:!0})),g==="listUnordered")return s.enter("listItemPrefix"),p===42||p===45?s.check(kNe,n,d)(p):d(p);if(!r.interrupt||p===49)return s.enter("listItemPrefix"),s.enter("listItemValue"),c(p)}return n(p)}function c(p){return qBe(p)&&++l<10?(s.consume(p),c):(!r.interrupt||l<2)&&(r.containerState.marker?p===r.containerState.marker:p===41||p===46)?(s.exit("listItemValue"),d(p)):n(p)}function d(p){return s.enter("listItemMarker"),s.consume(p),s.exit("listItemMarker"),r.containerState.marker=r.containerState.marker||p,s.check(eTe,r.interrupt?n:u,s.attempt(v2n,m,h))}function u(p){return r.containerState.initialBlankLine=!0,i++,m(p)}function h(p){return nh(p)?(s.enter("listItemPrefixWhitespace"),s.consume(p),s.exit("listItemPrefixWhitespace"),m):n(p)}function m(p){return r.containerState.size=i+r.sliceSerialize(s.exit("listItemPrefix"),!0).length,t(p)}}function w2n(s,t,n){const r=this;return r.containerState._closeFlow=void 0,s.check(eTe,a,i);function a(o){return r.containerState.furtherBlankLines=r.containerState.furtherBlankLines||r.containerState.initialBlankLine,Fm(s,t,"listItemIndent",r.containerState.size+1)(o)}function i(o){return r.containerState.furtherBlankLines||!nh(o)?(r.containerState.furtherBlankLines=void 0,r.containerState.initialBlankLine=void 0,l(o)):(r.containerState.furtherBlankLines=void 0,r.containerState.initialBlankLine=void 0,s.attempt(b2n,t,l)(o))}function l(o){return r.containerState._closeFlow=!0,r.interrupt=void 0,Fm(s,s.attempt(Zb,t,n),"linePrefix",r.parser.constructs.disable.null.includes("codeIndented")?void 0:4)(o)}}function j2n(s,t,n){const r=this;return Fm(s,a,"listItemIndent",r.containerState.size+1);function a(i){const l=r.events[r.events.length-1];return l&&l[1].type==="listItemIndent"&&l[2].sliceSerialize(l[1],!0).length===r.containerState.size?t(i):n(i)}}function N2n(s){s.exit(this.containerState.type)}function k2n(s,t,n){const r=this;return Fm(s,a,"listItemPrefixWhitespace",r.parser.constructs.disable.null.includes("codeIndented")?void 0:5);function a(i){const l=r.events[r.events.length-1];return!nh(i)&&l&&l[1].type==="listItemPrefixWhitespace"?t(i):n(i)}}const Jxt={name:"setextUnderline",resolveTo:S2n,tokenize:C2n};function S2n(s,t){let n=s.length,r,a,i;for(;n--;)if(s[n][0]==="enter"){if(s[n][1].type==="content"){r=n;break}s[n][1].type==="paragraph"&&(a=n)}else s[n][1].type==="content"&&s.splice(n,1),!i&&s[n][1].type==="definition"&&(i=n);const l={type:"setextHeading",start:{...s[r][1].start},end:{...s[s.length-1][1].end}};return s[a][1].type="setextHeadingText",i?(s.splice(a,0,["enter",l,t]),s.splice(i+1,0,["exit",s[r][1],t]),s[r][1].end={...s[i][1].end}):s[r][1]=l,s.push(["exit",l,t]),s}function C2n(s,t,n){const r=this;let a;return i;function i(d){let u=r.events.length,h;for(;u--;)if(r.events[u][1].type!=="lineEnding"&&r.events[u][1].type!=="linePrefix"&&r.events[u][1].type!=="content"){h=r.events[u][1].type==="paragraph";break}return!r.parser.lazy[r.now().line]&&(r.interrupt||h)?(s.enter("setextHeadingLine"),a=d,l(d)):n(d)}function l(d){return s.enter("setextHeadingLineSequence"),o(d)}function o(d){return d===a?(s.consume(d),o):(s.exit("setextHeadingLineSequence"),nh(d)?Fm(s,c,"lineSuffix")(d):c(d))}function c(d){return d===null||ic(d)?(s.exit("setextHeadingLine"),t(d)):n(d)}}const A2n={tokenize:E2n};function E2n(s){const t=this,n=s.attempt(eTe,r,s.attempt(this.parser.constructs.flowInitial,a,Fm(s,s.attempt(this.parser.constructs.flow,a,s.attempt(Ljn,a)),"linePrefix")));return n;function r(i){if(i===null){s.consume(i);return}return s.enter("lineEndingBlank"),s.consume(i),s.exit("lineEndingBlank"),t.currentConstruct=void 0,n}function a(i){if(i===null){s.consume(i);return}return s.enter("lineEnding"),s.consume(i),s.exit("lineEnding"),t.currentConstruct=void 0,n}}const T2n={resolveAll:v7t()},M2n=y7t("string"),P2n=y7t("text");function y7t(s){return{resolveAll:v7t(s==="text"?I2n:void 0),tokenize:t};function t(n){const r=this,a=this.parser.constructs[s],i=n.attempt(a,l,o);return l;function l(u){return d(u)?i(u):o(u)}function o(u){if(u===null){n.consume(u);return}return n.enter("data"),n.consume(u),c}function c(u){return d(u)?(n.exit("data"),i(u)):(n.consume(u),c)}function d(u){if(u===null)return!0;const h=a[u];let m=-1;if(h)for(;++m-1){const o=l[0];typeof o=="string"?l[0]=o.slice(r):l.shift()}i>0&&l.push(s[a].slice(0,i))}return l}function G2n(s,t){let n=-1;const r=[];let a;for(;++n0){const xs=Ft.tokenStack[Ft.tokenStack.length-1];(xs[1]||tyt).call(Ft,void 0,xs[0])}for(rt.position={start:UA(wt.length>0?wt[0][1].start:{line:1,column:1,offset:0}),end:UA(wt.length>0?wt[wt.length-2][1].end:{line:1,column:1,offset:0})},Is=-1;++Is0&&(r.className=["language-"+a[0]]);let i={type:"element",tagName:"code",properties:r,children:[{type:"text",value:n}]};return t.meta&&(i.data={meta:t.meta}),s.patch(t,i),i=s.applyData(t,i),i={type:"element",tagName:"pre",properties:{},children:[i]},s.patch(t,i),i}function iNn(s,t){const n={type:"element",tagName:"del",properties:{},children:s.all(t)};return s.patch(t,n),s.applyData(t,n)}function oNn(s,t){const n={type:"element",tagName:"em",properties:{},children:s.all(t)};return s.patch(t,n),s.applyData(t,n)}function lNn(s,t){const n=typeof s.options.clobberPrefix=="string"?s.options.clobberPrefix:"user-content-",r=String(t.identifier).toUpperCase(),a=CV(r.toLowerCase()),i=s.footnoteOrder.indexOf(r);let l,o=s.footnoteCounts.get(r);o===void 0?(o=0,s.footnoteOrder.push(r),l=s.footnoteOrder.length):l=i+1,o+=1,s.footnoteCounts.set(r,o);const c={type:"element",tagName:"a",properties:{href:"#"+n+"fn-"+a,id:n+"fnref-"+a+(o>1?"-"+o:""),dataFootnoteRef:!0,ariaDescribedBy:["footnote-label"]},children:[{type:"text",value:String(l)}]};s.patch(t,c);const d={type:"element",tagName:"sup",properties:{},children:[c]};return s.patch(t,d),s.applyData(t,d)}function cNn(s,t){const n={type:"element",tagName:"h"+t.depth,properties:{},children:s.all(t)};return s.patch(t,n),s.applyData(t,n)}function dNn(s,t){if(s.options.allowDangerousHtml){const n={type:"raw",value:t.value};return s.patch(t,n),s.applyData(t,n)}}function w7t(s,t){const n=t.referenceType;let r="]";if(n==="collapsed"?r+="[]":n==="full"&&(r+="["+(t.label||t.identifier)+"]"),t.type==="imageReference")return[{type:"text",value:"!["+t.alt+r}];const a=s.all(t),i=a[0];i&&i.type==="text"?i.value="["+i.value:a.unshift({type:"text",value:"["});const l=a[a.length-1];return l&&l.type==="text"?l.value+=r:a.push({type:"text",value:r}),a}function uNn(s,t){const n=String(t.identifier).toUpperCase(),r=s.definitionById.get(n);if(!r)return w7t(s,t);const a={src:CV(r.url||""),alt:t.alt};r.title!==null&&r.title!==void 0&&(a.title=r.title);const i={type:"element",tagName:"img",properties:a,children:[]};return s.patch(t,i),s.applyData(t,i)}function hNn(s,t){const n={src:CV(t.url)};t.alt!==null&&t.alt!==void 0&&(n.alt=t.alt),t.title!==null&&t.title!==void 0&&(n.title=t.title);const r={type:"element",tagName:"img",properties:n,children:[]};return s.patch(t,r),s.applyData(t,r)}function mNn(s,t){const n={type:"text",value:t.value.replace(/\r?\n|\r/g," ")};s.patch(t,n);const r={type:"element",tagName:"code",properties:{},children:[n]};return s.patch(t,r),s.applyData(t,r)}function fNn(s,t){const n=String(t.identifier).toUpperCase(),r=s.definitionById.get(n);if(!r)return w7t(s,t);const a={href:CV(r.url||"")};r.title!==null&&r.title!==void 0&&(a.title=r.title);const i={type:"element",tagName:"a",properties:a,children:s.all(t)};return s.patch(t,i),s.applyData(t,i)}function pNn(s,t){const n={href:CV(t.url)};t.title!==null&&t.title!==void 0&&(n.title=t.title);const r={type:"element",tagName:"a",properties:n,children:s.all(t)};return s.patch(t,r),s.applyData(t,r)}function gNn(s,t,n){const r=s.all(t),a=n?xNn(n):j7t(t),i={},l=[];if(typeof t.checked=="boolean"){const u=r[0];let h;u&&u.type==="element"&&u.tagName==="p"?h=u:(h={type:"element",tagName:"p",properties:{},children:[]},r.unshift(h)),h.children.length>0&&h.children.unshift({type:"text",value:" "}),h.children.unshift({type:"element",tagName:"input",properties:{type:"checkbox",checked:t.checked,disabled:!0},children:[]}),i.className=["task-list-item"]}let o=-1;for(;++o1}function yNn(s,t){const n={},r=s.all(t);let a=-1;for(typeof t.start=="number"&&t.start!==1&&(n.start=t.start);++a0){const l={type:"element",tagName:"tbody",properties:{},children:s.wrap(n,!0)},o=CZe(t.children[1]),c=n7t(t.children[t.children.length-1]);o&&c&&(l.position={start:o,end:c}),a.push(l)}const i={type:"element",tagName:"table",properties:{},children:s.wrap(a,!0)};return s.patch(t,i),s.applyData(t,i)}function jNn(s,t,n){const r=n?n.children:void 0,i=(r?r.indexOf(t):1)===0?"th":"td",l=n&&n.type==="table"?n.align:void 0,o=l?l.length:t.children.length;let c=-1;const d=[];for(;++c0,!0),r[0]),a=r.index+r[0].length,r=n.exec(t);return i.push(ryt(t.slice(a),a>0,!1)),i.join("")}function ryt(s,t,n){let r=0,a=s.length;if(t){let i=s.codePointAt(r);for(;i===syt||i===nyt;)r++,i=s.codePointAt(r)}if(n){let i=s.codePointAt(a-1);for(;i===syt||i===nyt;)a--,i=s.codePointAt(a-1)}return a>r?s.slice(r,a):""}function SNn(s,t){const n={type:"text",value:kNn(String(t.value))};return s.patch(t,n),s.applyData(t,n)}function CNn(s,t){const n={type:"element",tagName:"hr",properties:{},children:[]};return s.patch(t,n),s.applyData(t,n)}const ANn={blockquote:nNn,break:rNn,code:aNn,delete:iNn,emphasis:oNn,footnoteReference:lNn,heading:cNn,html:dNn,imageReference:uNn,image:hNn,inlineCode:mNn,linkReference:fNn,link:pNn,listItem:gNn,list:yNn,paragraph:vNn,root:bNn,strong:_Nn,table:wNn,tableCell:NNn,tableRow:jNn,text:SNn,thematicBreak:CNn,toml:fae,yaml:fae,definition:fae,footnoteDefinition:fae};function fae(){}const N7t=-1,tTe=0,JY=1,A4e=2,LZe=3,RZe=4,DZe=5,OZe=6,k7t=7,S7t=8,C7t=typeof self=="object"?self:globalThis,ayt=(s,t)=>{switch(s){case"Function":case"SharedWorker":case"Worker":case"eval":case"setInterval":case"setTimeout":throw new TypeError("unable to deserialize "+s)}return new C7t[s](t)},ENn=(s,t)=>{const n=(a,i)=>(s.set(i,a),a),r=a=>{if(s.has(a))return s.get(a);const[i,l]=t[a];switch(i){case tTe:case N7t:return n(l,a);case JY:{const o=n([],a);for(const c of l)o.push(r(c));return o}case A4e:{const o=n({},a);for(const[c,d]of l)o[r(c)]=r(d);return o}case LZe:return n(new Date(l),a);case RZe:{const{source:o,flags:c}=l;return n(new RegExp(o,c),a)}case DZe:{const o=n(new Map,a);for(const[c,d]of l)o.set(r(c),r(d));return o}case OZe:{const o=n(new Set,a);for(const c of l)o.add(r(c));return o}case k7t:{const{name:o,message:c}=l;return n(typeof C7t[o]=="function"?ayt(o,c):new Error(c),a)}case S7t:return n(BigInt(l),a);case"BigInt":return n(Object(BigInt(l)),a);case"ArrayBuffer":return n(new Uint8Array(l).buffer,l);case"DataView":{const{buffer:o}=new Uint8Array(l);return n(new DataView(o),l)}}return n(ayt(i,l),a)};return r},iyt=s=>ENn(new Map,s)(0),DR="",{toString:TNn}={},{keys:MNn}=Object,LG=s=>{const t=typeof s;if(t!=="object"||!s)return[tTe,t];const n=TNn.call(s).slice(8,-1);switch(n){case"Array":return[JY,DR];case"Object":return[A4e,DR];case"Date":return[LZe,DR];case"RegExp":return[RZe,DR];case"Map":return[DZe,DR];case"Set":return[OZe,DR];case"DataView":return[JY,n]}return n.includes("Array")?[JY,n]:s instanceof Error?[k7t,s.name||"Error"]:[A4e,n]},pae=([s,t])=>s===tTe&&(t==="function"||t==="symbol"),PNn=(s,t,n,r)=>{const a=(l,o)=>{const c=r.push(l)-1;return n.set(o,c),c},i=l=>{if(n.has(l))return n.get(l);let[o,c]=LG(l);switch(o){case tTe:{let u=l;switch(c){case"bigint":o=S7t,u=l.toString();break;case"function":case"symbol":if(s)throw new TypeError("unable to serialize "+c);u=null;break;case"undefined":return a([N7t],l)}return a([o,u],l)}case JY:{if(c){let m=l;return c==="DataView"?m=new Uint8Array(l.buffer):c==="ArrayBuffer"&&(m=new Uint8Array(l)),a([c,[...m]],l)}const u=[],h=a([o,u],l);for(const m of l)u.push(i(m));return h}case A4e:{if(c)switch(c){case"BigInt":return a([c,l.toString()],l);case"Boolean":case"Number":case"String":return a([c,l.valueOf()],l)}if(t&&"toJSON"in l)return i(l.toJSON());const u=[],h=a([o,u],l);for(const m of MNn(l))(s||!pae(LG(l[m])))&&u.push([i(m),i(l[m])]);return h}case LZe:return a([o,isNaN(l.getTime())?DR:l.toISOString()],l);case RZe:{const{source:u,flags:h}=l;return a([o,{source:u,flags:h}],l)}case DZe:{const u=[],h=a([o,u],l);for(const[m,p]of l)(s||!(pae(LG(m))||pae(LG(p))))&&u.push([i(m),i(p)]);return h}case OZe:{const u=[],h=a([o,u],l);for(const m of l)(s||!pae(LG(m)))&&u.push(i(m));return h}}const{message:d}=l;return a([o,{name:c,message:d}],l)};return i},oyt=(s,{json:t,lossy:n}={})=>{const r=[];return PNn(!(t||n),!!t,new Map,r)(s),r},E4e=typeof structuredClone=="function"?(s,t)=>t&&("json"in t||"lossy"in t)?iyt(oyt(s,t)):structuredClone(s):(s,t)=>iyt(oyt(s,t));function INn(s,t){const n=[{type:"text",value:"↩"}];return t>1&&n.push({type:"element",tagName:"sup",properties:{},children:[{type:"text",value:String(t)}]}),n}function LNn(s,t){return"Back to reference "+(s+1)+(t>1?"-"+t:"")}function RNn(s){const t=typeof s.options.clobberPrefix=="string"?s.options.clobberPrefix:"user-content-",n=s.options.footnoteBackContent||INn,r=s.options.footnoteBackLabel||LNn,a=s.options.footnoteLabel||"Footnotes",i=s.options.footnoteLabelTagName||"h2",l=s.options.footnoteLabelProperties||{className:["sr-only"]},o=[];let c=-1;for(;++c0&&g.push({type:"text",value:" "});let _=typeof n=="string"?n:n(c,p);typeof _=="string"&&(_={type:"text",value:_}),g.push({type:"element",tagName:"a",properties:{href:"#"+t+"fnref-"+m+(p>1?"-"+p:""),dataFootnoteBackref:"",ariaLabel:typeof r=="string"?r:r(c,p),className:["data-footnote-backref"]},children:Array.isArray(_)?_:[_]})}const y=u[u.length-1];if(y&&y.type==="element"&&y.tagName==="p"){const _=y.children[y.children.length-1];_&&_.type==="text"?_.value+=" ":y.children.push({type:"text",value:" "}),y.children.push(...g)}else u.push(...g);const v={type:"element",tagName:"li",properties:{id:t+"fn-"+m},children:s.wrap(u,!0)};s.patch(d,v),o.push(v)}if(o.length!==0)return{type:"element",tagName:"section",properties:{dataFootnotes:!0,className:["footnotes"]},children:[{type:"element",tagName:i,properties:{...E4e(l),id:"footnote-label"},children:[{type:"text",value:a}]},{type:"text",value:` `},{type:"element",tagName:"ol",properties:{},children:s.wrap(o,!0)},{type:"text",value:` `}]}}const A7t=function(s){if(s==null)return zNn;if(typeof s=="function")return sTe(s);if(typeof s=="object")return Array.isArray(s)?DNn(s):ONn(s);if(typeof s=="string")return FNn(s);throw new Error("Expected function, string, or object as test")};function DNn(s){const t=[];let n=-1;for(;++n":""))+")"})}return m;function m(){let p=E7t,g,x,y;if((!t||i(c,d,u[u.length-1]||void 0))&&(p=VNn(n(c,u)),p[0]===lyt))return p;if("children"in c&&c.children){const v=c;if(v.children&&p[0]!==UNn)for(x=(r?v.children.length:-1)+l,y=u.concat(v);x>-1&&x0&&n.push({type:"text",value:` `}),n}function cyt(s){let t=0,n=s.charCodeAt(t);for(;n===9||n===32;)t++,n=s.charCodeAt(t);return s.slice(t)}function dyt(s,t){const n=GNn(s,t),r=n.one(s,void 0),a=RNn(n),i=Array.isArray(r)?{type:"root",children:r}:r||{type:"root",children:[]};return a&&i.children.push({type:"text",value:` `},a),i}function XNn(s,t){return s&&"run"in s?async function(n,r){const a=dyt(n,{file:r,...t});await s.run(a,r)}:function(n,r){return dyt(n,{file:r,...s||t})}}function uyt(s){if(s)throw s}var SNe=Object.prototype.hasOwnProperty,M7t=Object.prototype.toString,hyt=Object.defineProperty,myt=Object.getOwnPropertyDescriptor,fyt=function(t){return typeof Array.isArray=="function"?Array.isArray(t):M7t.call(t)==="[object Array]"},pyt=function(t){if(!t||M7t.call(t)!=="[object Object]")return!1;var n=SNe.call(t,"constructor"),r=t.constructor&&t.constructor.prototype&&SNe.call(t.constructor.prototype,"isPrototypeOf");if(t.constructor&&!n&&!r)return!1;var a;for(a in t);return typeof a>"u"||SNe.call(t,a)},gyt=function(t,n){hyt&&n.name==="__proto__"?hyt(t,n.name,{enumerable:!0,configurable:!0,value:n.newValue,writable:!0}):t[n.name]=n.newValue},xyt=function(t,n){if(n==="__proto__")if(SNe.call(t,n)){if(myt)return myt(t,n).value}else return;return t[n]},QNn=function s(){var t,n,r,a,i,l,o=arguments[0],c=1,d=arguments.length,u=!1;for(typeof o=="boolean"&&(u=o,o=arguments[1]||{},c=2),(o==null||typeof o!="object"&&typeof o!="function")&&(o={});cl.length;let c;o&&l.push(a);try{c=s.apply(this,l)}catch(d){const u=d;if(o&&n)throw u;return a(u)}o||(c&&c.then&&typeof c.then=="function"?c.then(i,a):c instanceof Error?a(c):i(c))}function a(l,...o){n||(n=!0,t(l,...o))}function i(l){a(null,l)}}const ES={basename:tkn,dirname:skn,extname:nkn,join:rkn,sep:"/"};function tkn(s,t){if(t!==void 0&&typeof t!="string")throw new TypeError('"ext" argument must be a string');nte(s);let n=0,r=-1,a=s.length,i;if(t===void 0||t.length===0||t.length>s.length){for(;a--;)if(s.codePointAt(a)===47){if(i){n=a+1;break}}else r<0&&(i=!0,r=a+1);return r<0?"":s.slice(n,r)}if(t===s)return"";let l=-1,o=t.length-1;for(;a--;)if(s.codePointAt(a)===47){if(i){n=a+1;break}}else l<0&&(i=!0,l=a+1),o>-1&&(s.codePointAt(a)===t.codePointAt(o--)?o<0&&(r=a):(o=-1,r=l));return n===r?r=l:r<0&&(r=s.length),s.slice(n,r)}function skn(s){if(nte(s),s.length===0)return".";let t=-1,n=s.length,r;for(;--n;)if(s.codePointAt(n)===47){if(r){t=n;break}}else r||(r=!0);return t<0?s.codePointAt(0)===47?"/":".":t===1&&s.codePointAt(0)===47?"//":s.slice(0,t)}function nkn(s){nte(s);let t=s.length,n=-1,r=0,a=-1,i=0,l;for(;t--;){const o=s.codePointAt(t);if(o===47){if(l){r=t+1;break}continue}n<0&&(l=!0,n=t+1),o===46?a<0?a=t:i!==1&&(i=1):a>-1&&(i=-1)}return a<0||n<0||i===0||i===1&&a===n-1&&a===r+1?"":s.slice(a,n)}function rkn(...s){let t=-1,n;for(;++t0&&s.codePointAt(s.length-1)===47&&(n+="/"),t?"/"+n:n}function ikn(s,t){let n="",r=0,a=-1,i=0,l=-1,o,c;for(;++l<=s.length;){if(l2){if(c=n.lastIndexOf("/"),c!==n.length-1){c<0?(n="",r=0):(n=n.slice(0,c),r=n.length-1-n.lastIndexOf("/")),a=l,i=0;continue}}else if(n.length>0){n="",r=0,a=l,i=0;continue}}t&&(n=n.length>0?n+"/..":"..",r=2)}else n.length>0?n+="/"+s.slice(a+1,l):n=s.slice(a+1,l),r=l-a-1;a=l,i=0}else o===46&&i>-1?i++:i=-1}return n}function nte(s){if(typeof s!="string")throw new TypeError("Path must be a string. Received "+JSON.stringify(s))}const okn={cwd:lkn};function lkn(){return"/"}function WBe(s){return!!(s!==null&&typeof s=="object"&&"href"in s&&s.href&&"protocol"in s&&s.protocol&&s.auth===void 0)}function ckn(s){if(typeof s=="string")s=new URL(s);else if(!WBe(s)){const t=new TypeError('The "path" argument must be of type string or an instance of URL. Received `'+s+"`");throw t.code="ERR_INVALID_ARG_TYPE",t}if(s.protocol!=="file:"){const t=new TypeError("The URL must be of scheme file");throw t.code="ERR_INVALID_URL_SCHEME",t}return dkn(s)}function dkn(s){if(s.hostname!==""){const r=new TypeError('File URL host must be "localhost" or empty on darwin');throw r.code="ERR_INVALID_FILE_URL_HOST",r}const t=s.pathname;let n=-1;for(;++n0){let[p,...g]=u;const x=r[m][1];GBe(x)&&GBe(p)&&(p=VRe(!0,x,p)),r[m]=[d,p,...g]}}}}const fkn=new FZe().freeze();function KRe(s,t){if(typeof t!="function")throw new TypeError("Cannot `"+s+"` without `parser`")}function YRe(s,t){if(typeof t!="function")throw new TypeError("Cannot `"+s+"` without `compiler`")}function ZRe(s,t){if(t)throw new Error("Cannot call `"+s+"` on a frozen processor.\nCreate a new processor first, by calling it: use `processor()` instead of `processor`.")}function vyt(s){if(!GBe(s)||typeof s.type!="string")throw new TypeError("Expected node, got `"+s+"`")}function byt(s,t,n){if(!n)throw new Error("`"+s+"` finished async. Use `"+t+"` instead")}function gae(s){return pkn(s)?s:new P7t(s)}function pkn(s){return!!(s&&typeof s=="object"&&"message"in s&&"messages"in s)}function gkn(s){return typeof s=="string"||xkn(s)}function xkn(s){return!!(s&&typeof s=="object"&&"byteLength"in s&&"byteOffset"in s)}const ykn="https://github.com/remarkjs/react-markdown/blob/main/changelog.md",_yt=[],wyt={allowDangerousHtml:!0},vkn=/^(https?|ircs?|mailto|xmpp)$/i,bkn=[{from:"astPlugins",id:"remove-buggy-html-in-markdown-parser"},{from:"allowDangerousHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"allowNode",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowElement"},{from:"allowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"allowedElements"},{from:"className",id:"remove-classname"},{from:"disallowedTypes",id:"replace-allownode-allowedtypes-and-disallowedtypes",to:"disallowedElements"},{from:"escapeHtml",id:"remove-buggy-html-in-markdown-parser"},{from:"includeElementIndex",id:"#remove-includeelementindex"},{from:"includeNodeIndex",id:"change-includenodeindex-to-includeelementindex"},{from:"linkTarget",id:"remove-linktarget"},{from:"plugins",id:"change-plugins-to-remarkplugins",to:"remarkPlugins"},{from:"rawSourcePos",id:"#remove-rawsourcepos"},{from:"renderers",id:"change-renderers-to-components",to:"components"},{from:"source",id:"change-source-to-children",to:"children"},{from:"sourcePos",id:"#remove-sourcepos"},{from:"transformImageUri",id:"#add-urltransform",to:"urlTransform"},{from:"transformLinkUri",id:"#add-urltransform",to:"urlTransform"}];function _kn(s){const t=wkn(s),n=jkn(s);return Nkn(t.runSync(t.parse(n),n),s)}function wkn(s){const t=s.rehypePlugins||_yt,n=s.remarkPlugins||_yt,r=s.remarkRehypeOptions?{...s.remarkRehypeOptions,...wyt}:wyt;return fkn().use(sNn).use(n).use(XNn,r).use(t)}function jkn(s){const t=s.children||"",n=new P7t;return typeof t=="string"&&(n.value=t),n}function Nkn(s,t){const n=t.allowedElements,r=t.allowElement,a=t.components,i=t.disallowedElements,l=t.skipHtml,o=t.unwrapDisallowed,c=t.urlTransform||kkn;for(const u of bkn)Object.hasOwn(t,u.from)&&(""+u.from+(u.to?"use `"+u.to+"` instead":"remove it")+ykn+u.id,void 0);return T7t(s,d),Rwn(s,{Fragment:e.Fragment,components:a,ignoreInvalidStyle:!0,jsx:e.jsx,jsxs:e.jsxs,passKeys:!0,passNode:!0});function d(u,h,m){if(u.type==="raw"&&m&&typeof h=="number")return l?m.children.splice(h,1):m.children[h]={type:"text",value:u.value},h;if(u.type==="element"){let p;for(p in $Re)if(Object.hasOwn($Re,p)&&Object.hasOwn(u.properties,p)){const g=u.properties[p],x=$Re[p];(x===null||x.includes(u.tagName))&&(u.properties[p]=c(String(g||""),p,u))}}if(u.type==="element"){let p=n?!n.includes(u.tagName):i?i.includes(u.tagName):!1;if(!p&&r&&typeof h=="number"&&(p=!r(u,h,m)),p&&m&&typeof h=="number")return o&&u.children?m.children.splice(h,1,...u.children):m.children.splice(h,1),h}}}function kkn(s){const t=s.indexOf(":"),n=s.indexOf("?"),r=s.indexOf("#"),a=s.indexOf("/");return t===-1||a!==-1&&t>a||n!==-1&&t>n||r!==-1&&t>r||vkn.test(s.slice(0,t))?s:""}const Skn={a:({href:s,children:t})=>{const n=s||"",r=n.startsWith("/"),a="inline-flex items-center gap-1 rounded-md bg-primary/10 px-1.5 py-0.5 font-medium text-primary no-underline transition-colors hover:bg-primary/20";return r?e.jsxs(nr,{to:n,className:a,children:[t,e.jsx(FT,{className:"h-3 w-3"})]}):e.jsxs("a",{href:n,target:"_blank",rel:"noopener noreferrer",className:a,children:[t,e.jsx(FT,{className:"h-3 w-3"})]})}},Ckn=["What should I do first thing every morning in LevelUp?","How do I get my website showing up on Google?","Write me a follow-up text for a lead who toured a home last week","Where do I create social posts for a new listing?"];function Akn(){var h,m,p;const{user:s}=ks(),[t,n]=k.useState([]),[r,a]=k.useState(""),[i,l]=k.useState(!1),o=k.useRef(null),c=k.useRef(null),d=((h=s==null?void 0:s.user_metadata)==null?void 0:h.first_name)||((p=(m=s==null?void 0:s.user_metadata)==null?void 0:m.full_name)==null?void 0:p.split(" ")[0])||"";k.useEffect(()=>{var g;(g=c.current)==null||g.scrollTo({top:c.current.scrollHeight,behavior:"smooth"})},[t,i]);const u=async g=>{var _;const x=g.trim();if(!x||i)return;const y=[...t,{role:"user",content:x}];n([...y,{role:"assistant",content:""}]),a(""),l(!0);const v=new AbortController;o.current=v;try{const{data:j}=await V.auth.getSession(),C=(_=j.session)==null?void 0:_.access_token,A=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/levelup-assistant",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${C}`,apikey:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InJlbHplamlzd25vdGlramd2amh6Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjE5NTAzNDQsImV4cCI6MjA3NzUyNjM0NH0.dzIkIr_oFSbFE3oWS0ktIr83iKHHkZxt40Gc7SpC_mM"},body:JSON.stringify({messages:y,agentName:d}),signal:v.signal});if(!A.ok||!A.body){const O=await A.json().catch(()=>({error:"Something went wrong."}));throw new Error(O.error||"Something went wrong.")}const M=A.body.getReader(),I=new TextDecoder;let P="",R="";for(;;){const{done:O,value:B}=await M.read();if(O)break;P+=I.decode(B,{stream:!0});const U=P.split(` `);P=U.pop()||"";for(const G of U){const H=G.trim();if(!H.startsWith("data:"))continue;const Y=H.slice(5).trim();if(!(!Y||Y==="[DONE]"))try{const se=JSON.parse(Y);se.delta&&(R+=se.delta,n(ee=>{const oe=[...ee];return oe[oe.length-1]={role:"assistant",content:R},oe}))}catch{}}}R||n(O=>{const B=[...O];return B[B.length-1]={role:"assistant",content:"I didn't catch that — mind asking again?"},B})}catch(j){j.name==="AbortError"?n(C=>C.filter((A,M)=>!(M===C.length-1&&!A.content))):(ae.error(j.message||"The assistant is unavailable right now."),n(C=>C.slice(0,-1)))}finally{l(!1),o.current=null}};return e.jsx(Xs,{children:e.jsxs("div",{className:"mx-auto flex h-[calc(100vh-7rem)] w-full max-w-3xl flex-col p-4 md:p-6",children:[e.jsxs("div",{className:"mb-4 flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"flex h-10 w-10 items-center justify-center rounded-xl bg-primary/10",children:e.jsx(S5,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-xl font-bold tracking-tight",children:"Ask LevelUp AI"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Your in-app guide to the platform and your business."})]})]}),t.length>0&&e.jsxs($,{variant:"ghost",size:"sm",className:"gap-1",onClick:()=>n([]),children:[e.jsx(jm,{className:"h-4 w-4"})," New chat"]})]}),e.jsx("div",{ref:c,className:"flex-1 space-y-5 overflow-y-auto rounded-2xl border bg-card/40 p-4",children:t.length===0?e.jsxs("div",{className:"flex h-full flex-col items-center justify-center text-center",children:[e.jsx("span",{className:"mb-3 flex h-14 w-14 items-center justify-center rounded-2xl bg-primary/10",children:e.jsx(S5,{className:"h-7 w-7 text-primary"})}),e.jsx("p",{className:"text-base font-semibold",children:d?`Hey ${d} — what can I help with?`:"What can I help with?"}),e.jsx("p",{className:"mt-1 max-w-md text-sm text-muted-foreground",children:"I know every tool in LevelUp and can help you write, plan, and find things fast."}),e.jsx("div",{className:"mt-5 grid w-full max-w-lg gap-2 sm:grid-cols-2",children:Ckn.map(g=>e.jsx("button",{onClick:()=>u(g),className:"rounded-xl border bg-background px-3 py-2.5 text-left text-sm transition-colors hover:border-primary/40 hover:bg-muted/50",children:g},g))})]}):t.map((g,x)=>e.jsx("div",{className:Ot("flex",g.role==="user"?"justify-end":"justify-start"),children:g.role==="user"?e.jsx("div",{className:"max-w-[85%] rounded-2xl rounded-br-sm bg-primary px-3.5 py-2.5 text-sm text-primary-foreground",children:e.jsx("p",{className:"whitespace-pre-wrap break-words",children:g.content})}):e.jsx("div",{className:"max-w-full text-sm leading-relaxed text-foreground",children:g.content?e.jsx("div",{className:"prose prose-sm max-w-none dark:prose-invert prose-p:my-2 prose-ul:my-2 prose-headings:mt-4 prose-headings:mb-2",children:e.jsx(_kn,{components:Skn,children:g.content})}):e.jsx("span",{className:"animate-pulse text-muted-foreground",children:"Thinking…"})})},x))}),e.jsxs("div",{className:"mt-3 flex items-end gap-2 rounded-2xl border bg-background p-2",children:[e.jsx(Ls,{value:r,onChange:g=>a(g.target.value),onKeyDown:g=>{g.key==="Enter"&&!g.shiftKey&&(g.preventDefault(),u(r))},rows:1,placeholder:"Ask anything about LevelUp or your business…",className:"min-h-[44px] resize-none border-0 bg-transparent shadow-none focus-visible:ring-0"}),i?e.jsx($,{size:"icon",variant:"secondary",onClick:()=>{var g;return(g=o.current)==null?void 0:g.abort()},children:e.jsx(w_,{className:"h-4 w-4"})}):e.jsx($,{size:"icon",disabled:!r.trim(),onClick:()=>u(r),children:e.jsx(Wr,{className:"h-4 w-4"})})]}),e.jsx("p",{className:"mt-2 text-center text-[11px] text-muted-foreground",children:"LevelUp AI can make mistakes. Double-check anything important."})]})})}function Ekn({done:s,total:t,size:n=132}){const a=(n-10)/2,i=2*Math.PI*a,l=t>0?Math.min(100,s/t*100):0,o=i-l/100*i;return e.jsxs("div",{className:"relative shrink-0",style:{width:n,height:n},children:[e.jsxs("svg",{width:n,height:n,className:"-rotate-90 text-primary",children:[e.jsx("circle",{cx:n/2,cy:n/2,r:a,fill:"none",strokeWidth:10,className:"stroke-muted"}),e.jsx("circle",{cx:n/2,cy:n/2,r:a,fill:"none",strokeWidth:10,strokeLinecap:"round",stroke:"currentColor",strokeDasharray:i,strokeDashoffset:o,style:{transition:"stroke-dashoffset 700ms ease"}})]}),e.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center",children:[e.jsxs("div",{className:"flex items-baseline gap-0.5",children:[e.jsx("span",{className:"text-3xl font-semibold tabular-nums",children:s}),e.jsxs("span",{className:"text-sm text-muted-foreground",children:["/",t]})]}),e.jsx("span",{className:"text-[10px] uppercase tracking-wider text-muted-foreground",children:"today"})]})]})}function xae({icon:s,label:t,value:n,hint:r,tone:a="default",onClick:i,action:l}){const o=i?"button":"div";return e.jsxs(o,{onClick:i,className:Ot("group relative flex flex-col justify-between rounded-2xl border bg-card p-4 text-left transition-colors",i&&"hover:bg-accent/50 cursor-pointer",a==="warm"&&"border-orange-500/30 bg-orange-500/[0.04]",a==="alert"&&"border-amber-500/30 bg-amber-500/[0.04]"),children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5 text-[11px] font-medium uppercase tracking-wide text-muted-foreground",children:[s,t]}),l,i&&!l&&e.jsx(fi,{className:"h-3.5 w-3.5 text-muted-foreground opacity-0 group-hover:opacity-100 transition-opacity"})]}),e.jsxs("div",{className:"mt-2",children:[e.jsx("div",{className:"text-2xl font-semibold tabular-nums leading-none",children:n}),r&&e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:r})]})]})}function Tkn({agentName:s,todayDone:t,todayTotal:n,focusLine:r,weekDone:a,weekGoal:i,streak:l,staleCount:o,sphereCount:c,onEditGoal:d,onStaleClick:u,onSphereClick:h}){const m=new Date().getHours(),p=m<12?"Good morning":m<17?"Good afternoon":"Good evening",g=i>0?Math.min(100,Math.round(a/i*100)):0;return e.jsxs("div",{className:"grid gap-4 lg:grid-cols-[minmax(0,1.15fr)_minmax(0,1fr)]",children:[e.jsxs("div",{className:"relative overflow-hidden rounded-2xl border bg-gradient-to-br from-primary/[0.07] via-card to-card p-5 sm:p-6",children:[e.jsx("div",{className:"pointer-events-none absolute -right-16 -top-16 h-48 w-48 rounded-full bg-primary/10 blur-3xl"}),e.jsxs("div",{className:"relative flex flex-col-reverse items-start gap-5 sm:flex-row sm:items-center",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("p",{className:"text-[11px] font-semibold uppercase tracking-[0.16em] text-primary",children:[p,s?`, ${s}`:""]}),e.jsx("h2",{className:"mt-1.5 text-xl font-semibold leading-snug sm:text-2xl",children:n===0?"Your day is clear — pick a few people to reconnect with.":t>=n?"Today's list is done. That's how referrals get built.":`${n-t} ${n-t===1?"touch":"touches"} left to stay on track.`}),e.jsxs("p",{className:"mt-2 flex items-start gap-1.5 text-sm text-muted-foreground",children:[e.jsx(kn,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-primary"}),e.jsx("span",{children:r})]})]}),e.jsx(Ekn,{done:t,total:n})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(xae,{icon:e.jsx(_h,{className:"h-3.5 w-3.5"}),label:"Weekly goal",value:`${a}/${i}`,hint:`${g}% of your weekly touches`,action:e.jsx("button",{onClick:d,className:"rounded p-0.5 text-muted-foreground transition-colors hover:text-primary","aria-label":"Edit weekly goal",children:e.jsx(Yc,{className:"h-3.5 w-3.5"})})}),e.jsx(xae,{icon:e.jsx(iu,{className:"h-3.5 w-3.5 text-orange-500"}),label:"Streak",value:l>0?`${l}d`:"—",hint:l>0?"Log one touch to keep it alive":"Log a touch today to start one",tone:l>0?"warm":"default"}),e.jsx(xae,{icon:e.jsx(sa,{className:"h-3.5 w-3.5 text-amber-500"}),label:"Going cold",value:String(o),hint:"No contact in 90+ days",tone:o>0?"alert":"default",onClick:u}),e.jsx(xae,{icon:e.jsx(Xn,{className:"h-3.5 w-3.5"}),label:"Your sphere",value:String(c),hint:"People in your database",onClick:h})]})]})}const jyt="agent-os-onboarding-completed",yae=[{icon:v0,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:ix,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:Xn,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:fd,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:Zo,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:Ul,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"]}],Mkn=()=>{const[s,t]=k.useState(!1),[n,r]=k.useState(0),[a,i]=k.useState(!1);k.useEffect(()=>{if(!localStorage.getItem(jyt)){const g=setTimeout(()=>t(!0),500);return()=>clearTimeout(g)}},[]);const l=()=>{n{r(n+1),i(!1)},150)):c()},o=()=>{c()},c=()=>{localStorage.setItem(jyt,"true"),t(!1)},d=yae[n],u=d.icon,h=n===yae.length-1,m=p=>{p||c(),t(p)};return e.jsx(zs,{open:s,onOpenChange:m,children:e.jsxs(Rs,{className:"sm:max-w-lg overflow-hidden p-0 gap-0",children:[e.jsxs("div",{className:`relative bg-gradient-to-br ${d.bgGradient} p-8 pb-12 transition-all duration-500`,children:[e.jsxs("div",{className:"absolute inset-0 overflow-hidden",children:[e.jsx("div",{className:"absolute -top-4 -right-4 w-32 h-32 bg-white/10 rounded-full blur-2xl animate-pulse"}),e.jsx("div",{className:"absolute -bottom-8 -left-8 w-40 h-40 bg-white/10 rounded-full blur-3xl animate-pulse",style:{animationDelay:"1s"}}),e.jsx("div",{className:"absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-64 h-64 bg-white/5 rounded-full blur-3xl"})]}),e.jsxs("div",{className:`relative mx-auto flex h-20 w-20 items-center justify-center transition-all duration-300 ${a?"scale-75 opacity-0":"scale-100 opacity-100"}`,children:[e.jsx("div",{className:"absolute inset-0 bg-white/20 rounded-2xl blur-xl"}),e.jsx("div",{className:"relative flex h-20 w-20 items-center justify-center rounded-2xl bg-white/20 backdrop-blur-sm border border-white/30 shadow-2xl",children:e.jsx(u,{className:`h-10 w-10 ${d.iconColor} drop-shadow-lg`})})]}),n===0&&e.jsxs("div",{className:"absolute top-4 right-4 px-3 py-1 rounded-full bg-white/20 backdrop-blur-sm border border-white/30 text-white text-xs font-medium flex items-center gap-1.5",children:[e.jsx(kn,{className:"h-3 w-3"}),"Beta"]})]}),e.jsxs("div",{className:"p-6 pt-4",children:[e.jsxs(Vs,{className:"text-center sm:text-center pb-2",children:[e.jsx($s,{className:`text-2xl font-bold transition-all duration-300 ${a?"translate-y-2 opacity-0":"translate-y-0 opacity-100"}`,children:d.title}),e.jsx(Cr,{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((p,g)=>e.jsxs("div",{className:"flex items-center gap-3 group",style:{transitionDelay:`${150+g*50}ms`},children:[e.jsx("div",{className:`flex h-6 w-6 shrink-0 items-center justify-center rounded-full bg-gradient-to-br ${d.bgGradient} shadow-sm`,children:e.jsx(ma,{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:p})]},g))}),e.jsx("div",{className:"flex justify-center gap-2 py-4",children:yae.map((p,g)=>e.jsx("button",{onClick:()=>{g!==n&&(i(!0),setTimeout(()=>{r(g),i(!1)},150))},className:`h-2 rounded-full transition-all duration-300 ${g===n?"w-8 bg-gradient-to-r "+d.bgGradient:g{const{user:s}=ks();return pt({queryKey:["contact-snoozes",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await V.from("contact_snoozes").select("*").gte("snoozed_until",new Date().toISOString());if(n)throw n;return t},enabled:!!s})},Ikn=()=>{const s=ls(),{user:t}=ks();return Nt({mutationFn:async({contactId:n,days:r})=>{if(!(t!=null&&t.id))throw new Error("Not authenticated");const a=wu(new Date,r);await V.from("contact_snoozes").delete().eq("contact_id",n);const{error:i}=await V.from("contact_snoozes").insert({contact_id:n,owner_user_id:t.id,snoozed_until:a.toISOString()});if(i)throw i},onSuccess:()=>{s.invalidateQueries({queryKey:["contact-snoozes"]}),s.invalidateQueries({queryKey:["today-actions"]}),s.invalidateQueries({queryKey:["popby-logs"]}),Ma({title:"Touch snoozed!",description:"Contact has been snoozed."})},onError:n=>{Ma({title:"Error snoozing contact",description:n.message,variant:"destructive"})}})},Lkn=()=>{const s=ls();return Nt({mutationFn:async t=>{const{error:n}=await V.from("contact_snoozes").delete().eq("contact_id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["contact-snoozes"]}),Ma({title:"Snooze cancelled"})},onError:t=>{Ma({title:"Error cancelling snooze",description:t.message,variant:"destructive"})}})},Rkn=[{label:"1 week",days:7},{label:"2 weeks",days:14},{label:"1 month",days:30}];function nTe({open:s,onOpenChange:t,contactId:n,contactName:r}){const[a,i]=k.useState(null),l=Ikn(),o=async()=>{a&&(await l.mutateAsync({contactId:n,days:a}),i(null),t(!1))},c=d=>Ys(wu(new Date,d),"MMM d, yyyy");return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"sm:max-w-md",children:[e.jsxs(Vs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(sa,{className:"h-5 w-5"}),"Snooze Touch"]}),e.jsxs(Cr,{children:["Postpone the next scheduled touch for ",r,". Select how long to snooze."]})]}),e.jsx("div",{className:"space-y-3 py-4",children:Rkn.map(d=>e.jsxs("button",{type:"button",onClick:()=>i(d.days),className:Ot("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(ha,{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($,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx($,{onClick:o,disabled:!a||l.isPending,children:l.isPending?"Snoozing...":"Snooze Touch"})]})]})})}const Dkn={Crown:ky,FileText:ea,Users:Xn,Globe:kc,Star:ri,Phone:ka,MessageSquare:bo,PenTool:YT,Video:ia,Gift:Zo};function Okn({actions:s,onMarkComplete:t,onViewScript:n,isLoading:r,buildSmsLink:a,buildEmailLink:i,onGmailCompose:l}){const o=Jn(),[c,d]=k.useState("name"),[u,h]=k.useState("asc"),[m,p]=k.useState(null),[g,x]=k.useState(""),y=A=>{c===A?h(M=>M==="asc"?"desc":"asc"):(d(A),h("asc"))},v=k.useMemo(()=>[...s].sort((A,M)=>{var P,R;let I=0;switch(c){case"name":{const O=`${A.contact.first_name} ${A.contact.last_name||""}`.toLowerCase(),B=`${M.contact.first_name} ${M.contact.last_name||""}`.toLowerCase();I=O.localeCompare(B);break}case"relationship_type":I=(A.relationshipTypeName||"").localeCompare(M.relationshipTypeName||"");break;case"action_type":I=(((P=A.actionType)==null?void 0:P.name)||"").localeCompare(((R=M.actionType)==null?void 0:R.name)||"");break;case"last_touch":I=(A.monthNumber||0)-(M.monthNumber||0);break}return u==="asc"?I:-I}),[s,c,u]),_=A=>Dkn[A||"Phone"]||ka,j=({field:A,children:M})=>e.jsxs($,{variant:"ghost",size:"sm",className:"h-8 -ml-3 font-medium",onClick:()=>y(A),children:[M,c===A?u==="asc"?e.jsx(ap,{className:"ml-2 h-4 w-4"}):e.jsx(nx,{className:"ml-2 h-4 w-4"}):e.jsx(Ix,{className:"ml-2 h-4 w-4 opacity-50"})]}),C=(A,M,I)=>{p(A),x(`${M} ${I||""}`.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(Qa,{children:[e.jsx(Ja,{children:e.jsxs(vn,{className:"bg-muted/50",children:[e.jsx(Dt,{className:"w-[180px]",children:e.jsx(j,{field:"name",children:"Contact"})}),e.jsx(Dt,{className:"w-[130px]",children:e.jsx(j,{field:"relationship_type",children:"Type"})}),e.jsx(Dt,{className:"w-[120px]",children:e.jsx(j,{field:"action_type",children:"Action"})}),e.jsx(Dt,{className:"w-[130px]",children:"Phone"}),e.jsx(Dt,{className:"w-[200px]",children:"Quick Actions"})]})}),e.jsx(ei,{children:v.map((A,M)=>{var U,G,H,Y,se,ee;const I=A.isSpecialDate,P=A.specialDateType,R=I?P==="birthday"?ip:ua:_(((U=A.actionType)==null?void 0:U.icon)||null),O=A.contact.phone,B=A.contact.email;return e.jsxs(vn,{className:Ot("hover:bg-muted/50 transition-colors",I&&P==="birthday"&&"bg-pink-50/50 dark:bg-pink-950/20",I&&P==="anniversary"&&"bg-purple-50/50 dark:bg-purple-950/20"),children:[e.jsx(_t,{className:"font-medium",children:e.jsx("div",{children:e.jsxs("button",{onClick:()=>o(`/mission-control/contacts/${A.contact.id}`),className:"truncate max-w-[160px] text-left hover:text-primary hover:underline transition-colors",children:[A.contact.first_name," ",A.contact.last_name]})})}),e.jsx(_t,{children:A.relationshipTypeName?e.jsx(qe,{variant:"secondary",className:"text-xs",children:A.relationshipTypeName}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"—"})}),e.jsx(_t,{children:e.jsx("div",{className:"flex items-center gap-1.5",children:I?e.jsx(qe,{className:Ot("gap-1",P==="birthday"&&"bg-pink-500 hover:bg-pink-600",P==="anniversary"&&"bg-purple-500 hover:bg-purple-600"),children:P==="birthday"?e.jsxs(e.Fragment,{children:[e.jsx(ip,{className:"h-3 w-3"})," Birthday"]}):e.jsxs(e.Fragment,{children:[e.jsx(ua,{className:"h-3 w-3"})," Anniversary"]})}):e.jsxs(qe,{variant:"outline",className:"gap-1",children:[e.jsx(R,{className:"h-3 w-3"}),(G=A.actionType)==null?void 0:G.name]})})}),e.jsx(_t,{children:O?e.jsx("span",{className:"text-sm font-mono",children:A.contact.phone}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"—"})}),e.jsx(_t,{children:e.jsxs("div",{className:"flex items-center gap-1",children:[O&&e.jsx("a",{href:`tel:${A.contact.phone}`,className:"p-1.5 rounded bg-primary/10 hover:bg-primary/20 text-primary transition-colors",title:"Call",children:e.jsx(ka,{className:"h-3.5 w-3.5"})}),O&&e.jsx("a",{href:a(A.contact.phone,(H=A.script)==null?void 0:H.script_body,A.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(bo,{className:"h-3.5 w-3.5"})}),B&&(l?e.jsx("button",{onClick:()=>l({id:A.contact.id,first_name:A.contact.first_name,last_name:A.contact.last_name,email:A.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(pn,{className:"h-3.5 w-3.5"})}):e.jsx("a",{href:i(A.contact.email,(Y=A.script)==null?void 0:Y.script_body,(se=A.script)==null?void 0:se.email_subject,(ee=A.actionType)==null?void 0:ee.name,A.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(pn,{className:"h-3.5 w-3.5"})})),I&&e.jsxs("button",{onClick:()=>{const oe=`${A.contact.first_name}${A.contact.last_name?" "+A.contact.last_name:""}`,me=P==="birthday"?"birthday":"home_anniversary",Q=new URLSearchParams({cardType:me,contactId:A.contact.id,name:oe,...A.contact.address?{address:A.contact.address}:{},...P==="anniversary"&&A.contact.home_anniversary?{date:A.contact.home_anniversary}:{}});o(`/mission-control/card-studio?${Q.toString()}`)},className:Ot("h-7 px-2 rounded text-xs font-semibold flex items-center gap-1 transition-colors",P==="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 ${P==="birthday"?"Birthday":"Anniversary"} Card`,children:[e.jsx(pn,{className:"h-3.5 w-3.5"}),"Send Card"]}),e.jsx($,{variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground hover:text-foreground",onClick:()=>C(A.contact.id,A.contact.first_name,A.contact.last_name),title:"Snooze",children:e.jsx(uv,{className:"h-3.5 w-3.5"})}),e.jsxs($,{variant:"default",size:"sm",className:"h-7 px-2 text-xs ml-1",onClick:()=>{var oe;return t(A.contact.id,A.actionType.id,(oe=A.script)==null?void 0:oe.id)},disabled:r,children:[e.jsx(Gr,{className:"h-3.5 w-3.5 mr-1"}),"Done"]})]})})]},`${A.contact.id}-${M}`)})})]})}),e.jsx(nTe,{open:!!m,onOpenChange:A=>!A&&p(null),contactId:m||"",contactName:g})]})}function Fkn(){const{user:s}=ks(),{limitFor:t,isRestricted:n}=rA(),r=n?t("mass_email"):null,{data:a=0,refetch:i}=pt({queryKey:["mass-email-usage",s==null?void 0:s.id],enabled:!!(s!=null&&s.id)&&!!r,staleTime:60*1e3,queryFn:async()=>{const o=new Date;o.setDate(1),o.setHours(0,0,0,0);const{count:c}=await V.from("bulk_email_sends").select("id",{count:"exact",head:!0}).eq("user_id",s.id).gte("sent_at",o.toISOString());return c||0}}),l=r===null?1/0:Math.max(0,r-a);return{limit:r,used:a,remaining:l,wouldExceed:o=>r!==null&&o>l,refetch:i}}function zkn({onSelect:s}){const{user:t}=ks(),[n,r]=k.useState("root"),[a,i]=k.useState(null),{data:l=[],isLoading:o}=pt({queryKey:["agent-email-template-categories"],queryFn:async()=>{const{data:v,error:_}=await V.from("email_template_categories").select("*").order("sort_order");if(_)throw _;return v}}),{data:c=[],isLoading:d}=pt({queryKey:["agent-email-templates",a],enabled:n==="category"&&!!a,queryFn:async()=>{const{data:v,error:_}=await V.from("agent_email_templates").select("*").eq("is_active",!0).eq("category_id",a).order("sort_order");if(_)throw _;return v}}),{data:u=[],isLoading:h}=pt({queryKey:["picker-campaign-templates",t==null?void 0:t.id],enabled:!!t,queryFn:async()=>{const{data:v,error:_}=await V.from("campaign_templates").select("id,name,subject,body_html,is_shared,user_id,updated_at").or(`user_id.eq.${t.id},is_shared.eq.true`).order("updated_at",{ascending:!1});if(_)throw _;return v}}),m=u.filter(v=>v.user_id===(t==null?void 0:t.id)&&!v.is_shared),p=u.filter(v=>v.is_shared),g=l.find(v=>v.id===a);if(o)return e.jsx("div",{className:"flex items-center justify-center py-6",children:e.jsx(Jt,{className:"h-5 w-5 animate-spin text-muted-foreground"})});const x=v=>{s({title:v.name,subject:v.subject,body:v.body_html})};if(n==="root")return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground px-1 mb-1.5",children:"Your templates"}),e.jsxs("button",{onClick:()=>r("my"),className:"w-full flex items-center justify-between p-2.5 rounded-lg border hover:bg-accent transition-colors text-left",children:[e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("div",{className:"h-8 w-8 rounded-md bg-primary/10 text-primary flex items-center justify-center",children:e.jsx(el,{className:"h-4 w-4"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:"My Saved Templates"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[m.length," template",m.length===1?"":"s"," you've created"]})]})]}),e.jsx(fi,{className:"h-4 w-4 text-muted-foreground shrink-0"})]}),e.jsxs("button",{onClick:()=>r("shared"),className:"w-full flex items-center justify-between p-2.5 rounded-lg border hover:bg-accent transition-colors text-left",children:[e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("div",{className:"h-8 w-8 rounded-md bg-blue-500/10 text-blue-600 dark:text-blue-400 flex items-center justify-center",children:e.jsx(kc,{className:"h-4 w-4"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:"Shared Library"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[p.length," team template",p.length===1?"":"s"]})]})]}),e.jsx(fi,{className:"h-4 w-4 text-muted-foreground shrink-0"})]})]}),l.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground px-1 mb-1.5",children:"Quick scripts by category"}),e.jsx("div",{className:"max-h-[200px] overflow-y-auto space-y-1 pr-1",children:l.map(v=>e.jsxs("button",{onClick:()=>{i(v.id),r("category")},className:"w-full flex items-center justify-between p-2.5 rounded-lg border hover:bg-accent transition-colors text-left",children:[e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("span",{className:"text-lg",children:v.icon}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:v.name}),v.description&&e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-1",children:v.description})]})]}),e.jsx(fi,{className:"h-4 w-4 text-muted-foreground shrink-0"})]},v.id))})]})]});const y=e.jsxs("button",{onClick:()=>{r("root"),i(null)},className:"flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx(Ld,{className:"h-3.5 w-3.5"}),"Back"]});return n==="my"?e.jsxs("div",{className:"space-y-2",children:[y,e.jsxs("p",{className:"text-xs font-medium flex items-center gap-1.5",children:[e.jsx(el,{className:"h-3.5 w-3.5"})," My Saved Templates"]}),h?e.jsx("div",{className:"flex items-center justify-center py-6",children:e.jsx(Jt,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):m.length===0?e.jsxs("div",{className:"text-center py-6 space-y-2",children:[e.jsx(kn,{className:"h-6 w-6 text-muted-foreground mx-auto"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"You haven't created any templates yet."}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Create beautiful templates in ",e.jsx("span",{className:"font-medium",children:"Email Templates"})," in the sidebar — they'll appear here."]})]}):e.jsx(Eo,{className:"max-h-[280px]",children:e.jsx("div",{className:"space-y-1",children:m.map(v=>e.jsxs("button",{onClick:()=>x(v),className:"w-full p-2.5 rounded-lg border hover:bg-accent transition-colors text-left",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:v.name}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 line-clamp-1",children:v.subject||"(no subject)"})]},v.id))})})]}):n==="shared"?e.jsxs("div",{className:"space-y-2",children:[y,e.jsxs("p",{className:"text-xs font-medium flex items-center gap-1.5",children:[e.jsx(kc,{className:"h-3.5 w-3.5"})," Shared Library"]}),h?e.jsx("div",{className:"flex items-center justify-center py-6",children:e.jsx(Jt,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):p.length===0?e.jsx("p",{className:"text-sm text-muted-foreground py-4 text-center",children:"No shared templates yet."}):e.jsx(Eo,{className:"max-h-[280px]",children:e.jsx("div",{className:"space-y-1",children:p.map(v=>e.jsxs("button",{onClick:()=>x(v),className:"w-full p-2.5 rounded-lg border hover:bg-accent transition-colors text-left",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:v.name}),e.jsx(qe,{variant:"secondary",className:"text-[10px] shrink-0",children:"Shared"})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 line-clamp-1",children:v.subject||"(no subject)"})]},v.id))})})]}):e.jsxs("div",{className:"space-y-2",children:[y,e.jsxs("p",{className:"text-xs font-medium flex items-center gap-1.5",children:[e.jsx("span",{children:g==null?void 0:g.icon})," ",g==null?void 0:g.name]}),d?e.jsx("div",{className:"flex items-center justify-center py-6",children:e.jsx(Jt,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):c.length===0?e.jsx("p",{className:"text-sm text-muted-foreground py-4 text-center",children:"No templates in this category"}):e.jsx(Eo,{className:"max-h-[280px]",children:e.jsx("div",{className:"space-y-1",children:c.map(v=>e.jsxs("button",{onClick:()=>s(v),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:v.title}),v.tone&&e.jsx(qe,{variant:"secondary",className:"text-[10px] shrink-0",children:v.tone})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 line-clamp-1",children:v.subject})]},v.id))})})]})}function rTe(){const{user:s}=ks(),t=ls(),{data:n,isLoading:r}=pt({queryKey:["contact-intake-page",s==null?void 0:s.id],queryFn:async()=>{if(!(s!=null&&s.id))return null;const{data:d,error:u}=await V.from("contact_intake_pages").select("*").eq("user_id",s.id).maybeSingle();if(u)throw u;return d},enabled:!!(s!=null&&s.id)}),a=Nt({mutationFn:async d=>{if(!(s!=null&&s.id))throw new Error("Not authenticated");const{data:u,error:h}=await V.from("contact_intake_pages").insert({user_id:s.id,slug:d.toLowerCase().replace(/[^a-z0-9-]/g,"-")}).select().single();if(h)throw h;return u},onSuccess:()=>{t.invalidateQueries({queryKey:["contact-intake-page"]}),ae.success("Connect page created!")},onError:d=>{var u;(u=d.message)!=null&&u.includes("duplicate")?ae.error("That slug is already taken. Try another."):ae.error("Failed to create page")}}),i=Nt({mutationFn:async d=>{if(!(n!=null&&n.id))throw new Error("No intake page");const{error:u}=await V.from("contact_intake_pages").update({...d,updated_at:new Date().toISOString()}).eq("id",n.id);if(u)throw u},onSuccess:()=>{t.invalidateQueries({queryKey:["contact-intake-page"]}),ae.success("Page updated!")},onError:()=>ae.error("Failed to update page")}),{data:l=[],isLoading:o}=pt({queryKey:["contact-intake-submissions",s==null?void 0:s.id],queryFn:async()=>{if(!(s!=null&&s.id))return[];const{data:d,error:u}=await V.from("contact_intake_submissions").select("*").eq("agent_user_id",s.id).order("created_at",{ascending:!1}).limit(100);if(u)throw u;return d},enabled:!!(s!=null&&s.id)}),c=Nt({mutationFn:async d=>{if(!(n!=null&&n.id))throw new Error("No intake page. Create your Connect page first.");const{data:u,error:h}=await V.from("contact_intake_tokens").insert({contact_id:d,intake_page_id:n.id}).select("token").single();if(h)throw h;return`${window.location.origin}/connect/${n.slug}?t=${u.token}`}});return{intakePage:n,isLoading:r,createPage:a,updatePage:i,submissions:l,loadingSubmissions:o,generateUpdateLink:c}}function I7t({value:s,onChange:t,userId:n,placeholder:r}){const[a,i]=k.useState(!1),[l,o]=k.useState([]),[c,d]=k.useState(!1),[u,h]=k.useState(0),m=k.useRef(null),p=k.useRef(null);k.useEffect(()=>{const x=y=>{m.current&&!m.current.contains(y.target)&&i(!1)};return document.addEventListener("mousedown",x),()=>document.removeEventListener("mousedown",x)},[]),k.useEffect(()=>{p.current&&clearTimeout(p.current);const x=s.trim();if(!n||x.length<1||x.includes("@")&&x.indexOf("@")>0&&/\S+@\S+\.\S+/.test(x)){o([]);return}return p.current=setTimeout(async()=>{d(!0);const y=`%${x}%`,v=V,{data:_,error:j}=await v.from("innercircle_contacts").select("id, first_name, last_name, email").eq("owner_user_id",n).not("email","is",null).or(`first_name.ilike.${y},last_name.ilike.${y},email.ilike.${y}`).order("first_name",{ascending:!0}).limit(8);d(!1),!j&&_&&(o(_),h(0),i(_.length>0))},180),()=>{p.current&&clearTimeout(p.current)}},[s,n]);const g=x=>{x.email&&(t(x.email),i(!1))};return e.jsxs("div",{ref:m,className:"relative",children:[e.jsx(be,{id:"gmail-to",value:s,onChange:x=>t(x.target.value),onFocus:()=>l.length>0&&i(!0),onKeyDown:x=>{!a||l.length===0||(x.key==="ArrowDown"?(x.preventDefault(),h(y=>Math.min(y+1,l.length-1))):x.key==="ArrowUp"?(x.preventDefault(),h(y=>Math.max(y-1,0))):x.key==="Enter"?(x.preventDefault(),g(l[u])):x.key==="Escape"&&i(!1))},placeholder:r||"Start typing a name or email...",autoComplete:"off"}),a&&e.jsx("div",{className:"absolute z-50 mt-1 w-full rounded-md border bg-popover shadow-lg max-h-72 overflow-y-auto",children:c&&l.length===0?e.jsxs("div",{className:"px-3 py-2 text-sm text-muted-foreground flex items-center gap-2",children:[e.jsx(Jt,{className:"h-3 w-3 animate-spin"})," Searching..."]}):l.map((x,y)=>{const v=[x.first_name,x.last_name].filter(Boolean).join(" ")||"(No name)";return e.jsxs("button",{type:"button",onMouseEnter:()=>h(y),onClick:()=>g(x),className:`w-full flex items-center gap-2 px-3 py-2 text-left text-sm border-b last:border-b-0 ${y===u?"bg-accent":"bg-popover"}`,children:[e.jsx(el,{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:v}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:x.email})]})]},x.id)})})]})}function Bkn(){const{user:s}=ks(),{data:t,isLoading:n}=pt({queryKey:["email-signature",s==null?void 0:s.id],enabled:!!(s!=null&&s.id),staleTime:5*60*1e3,queryFn:async()=>{const{data:a,error:i}=await V.from("profiles").select("email_signature, use_email_signature").eq("id",s.id).maybeSingle();if(i)throw i;return a}}),r=((t==null?void 0:t.email_signature)||"").trim();return{signatureHtml:r,hasSignature:r.length>0,signatureEnabledByDefault:!!(t!=null&&t.use_email_signature)&&r.length>0,isLoading:n}}function $kn(s,t){if(!t||s.includes(t))return s;const n=`
${t}
`;return/<\/body>/i.test(s)?s.replace(/<\/body>/i,`${n}`):`${s}${n}`}function Ukn(s){if(!/<[a-z][\s\S]*>/i.test(s)||typeof window>"u")return s;const t=s.replace(/<\s*(br|\/p|\/div|\/li|\/h[1-6]|\/tr)\s*[^>]*>/gi,` `).replace(/<\s*li\b[^>]*>/gi,"• ").replace(/<\s*(p|div|h[1-6]|tr)\b[^>]*>/gi,""),n=document.createElement("div");return n.innerHTML=t,(n.textContent||n.innerText||"").replace(/\u00a0/g," ").replace(/\n{3,}/g,` `).trim()}const XRe=25*1024*1024,Nyt=Math.floor(6.5*1024*1024),qkn=750*1024,Rj=50,Vkn=["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 vae(s){return s<1024?s+" B":s<1024*1024?(s/1024).toFixed(1)+" KB":(s/(1024*1024)).toFixed(1)+" MB"}function Hkn(s){return new Promise((t,n)=>{const r=new FileReader;r.onload=()=>{const a=r.result;t(a.split(",")[1])},r.onerror=n,r.readAsDataURL(s)})}function Gkn(s){if(!s)return"";const t=s.trim();return t.split(/\s+/)[0]||t}function Dj(s,t){const n=Gkn(t.first_name),r=t.last_name||"";let a=s.replace(/\{\{first_name\}\}/gi,n).replace(/\{\{last_name\}\}/gi,r).replace(/\{\{full_name\}\}/gi,`${n} ${r}`.trim());return t.updateLink&&(a=a.replace(/\{\{update_link\}\}/gi,t.updateLink)),a}function W2({open:s,onOpenChange:t,contact:n,bulkContacts:r,defaultSubject:a="",defaultBody:i="",gmailEmail:l,onSendComplete:o,sendSource:c,logTouchpoint:d=!0}){const{user:u}=ks(),h=ls(),{isReady:m,settings:p}=NV(),{data:g}=ZEe(),[x,y]=k.useState(!1),{intakePage:v}=rTe(),_=v?`https://contacts.relevelup.com/${v.slug}`:null,j=!!r&&r.length>0,C=Fkn(),A=m,M=j?r:n?[n]:[],I=M[0],P=j?Math.ceil(M.length/Rj):1,R=j&&M.length>Rj,[O,B]=k.useState((I==null?void 0:I.email)||""),[U,G]=k.useState(a),[H,Y]=k.useState(i),[se,ee]=k.useState(!1),[oe,me]=k.useState(!1),[Q,te]=k.useState([]),le=k.useRef(new Map),[fe,_e]=k.useState(a),[ve,he]=k.useState(i),[Se,Te]=k.useState(!1),[Ie,Ue]=k.useState("composing"),[Be,je]=k.useState(0),[Ye,Ee]=k.useState(0),[Re,ke]=k.useState(0),[Fe,Oe]=k.useState(0),Ge=k.useRef(!1),yt=k.useRef(0),[tt,ut]=k.useState(!0),{signatureHtml:nt,hasSignature:et}=Bkn(),[at,wt]=k.useState(!0),[rt,Ft]=k.useState(null);k.useEffect(()=>{s&&wt(et)},[s,et]),k.useEffect(()=>{if(s){const Ln=/<[a-z][\s\S]*>/i.test(i),Sr=Ln?Ukn(i):i;dt.current=Ln?{plain:Sr,html:i}:null,B((I==null?void 0:I.email)||""),_e(a),he(Sr),G(Dj(a,I||{first_name:""})),Y(Dj(Sr,I||{first_name:""})),me(!a&&!i),Te(!1),te([]),le.current=new Map,Ue("composing"),je(0),Ee(0),ke(0),Oe(0),Ge.current=!1,yt.current=0,Ft(null)}},[s,I,a,i]);const Ut=async Ln=>{const Sr=Ln.target.files;if(!Sr)return;const Qn=Q.reduce((xn,Ar)=>xn+Ar.size,0),En=[];let pr=Qn;for(const xn of Array.from(Sr)){if(!Vkn.includes(xn.type)){ae.error(`${xn.name}: Unsupported file type`);continue}if(pr+xn.size>XRe){ae.error(`Total attachments exceed ${vae(XRe)} limit`);break}try{const Ar=await Hkn(xn);En.push({name:xn.name,type:xn.type,size:xn.size,data:Ar}),pr+=xn.size}catch{ae.error(`Failed to read ${xn.name}`)}}te(xn=>[...xn,...En]),Ln.target.value=""},Is=Ln=>{const Sr=Q[Ln];Sr&&le.current.delete(`${Sr.name}::${Sr.size}`),te(Qn=>Qn.filter((En,pr)=>pr!==Ln))},xs=async()=>{if(Q.length===0||!u)return{inline:[],paths:[]};const Ln=[],Sr=[];for(const Qn of Q){const En=`${Qn.name}::${Qn.size}`,pr=le.current.get(En);if(pr){Sr.push(pr);continue}if(Qn.size<=qkn){Ln.push(Qn);continue}const xn=Qn.name.replace(/[^a-zA-Z0-9._-]/g,"_"),Ar=`${u.id}/${Date.now()}-${xn}`,Zr=atob(Qn.data),dn=new Uint8Array(Zr.length);for(let Er=0;Er{if(!/<[a-z][\s\S]*>/i.test(Ln)||typeof window>"u")return Ln;const Sr=Ln.replace(/<\s*(br|\/p|\/div|\/li|\/h[1-6]|\/tr)\s*[^>]*>/gi,` `).replace(/<\s*li\b[^>]*>/gi,"• ").replace(/<\s*(p|div|h[1-6]|tr)\b[^>]*>/gi,""),Qn=document.createElement("div");return Qn.innerHTML=Sr,(Qn.textContent||Qn.innerText||"").replace(/\u00a0/g," ").replace(/\n{3,}/g,` `).trim()},dt=k.useRef(null),jt=dt.current&&ve===dt.current.plain?dt.current.html:null,gt=Ln=>{const Sr=/<[a-z][\s\S]*>/i.test(Ln.body),Qn=Sr?st(Ln.body):Ln.body;dt.current=Sr?{plain:Qn,html:Ln.body}:null,_e(Ln.subject),he(Qn),G(Dj(Ln.subject,I||{first_name:""})),Y(Dj(Qn,I||{first_name:""})),me(!1)},rs=Ln=>/<\s*(p|div|span|table|tr|td|img|br|h[1-6]|a|body|html|section|article|ul|ol|li)\b/i.test(Ln)?Ln:Ln.split(/\n\n+/).map(Sr=>`

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

`).join(""),Ns=(Ln,Sr)=>{const Qn="https://relzejiswnotikjgvjhz.supabase.co/functions/v1/bulk-email-track";let En=Ln.replace(/]*?)href=(["'])(.*?)\2([^>]*)>/gi,(xn,Ar,Zr,dn,Kt)=>{if(!dn||/^(mailto:|tel:|#)/i.test(dn)||dn.includes("/bulk-email-track")||dn.includes("/ses-campaign-track"))return xn;const Er=`${Qn}?s=${Sr}&t=click&u=${encodeURIComponent(dn)}`;return``});const pr=``;return/<\/body>/i.test(En)?En=En.replace(/<\/body>/i,`${pr}`):En=`${En}${pr}`,En},us=async Ln=>{if(!(Ln!=null&&Ln.email))return ae.error("Please enter a recipient email"),!1;const Sr=Ln||{first_name:""},Qn=Dj(fe,Sr),En=dt.current,pr=En&&ve===En.plain,xn=Dj(pr?En.html:ve,Sr);let Ar=pr?xn:rs(xn);at&&nt&&(Ar=$kn(Ar,Dj(nt,Sr)));const Zr=u&&Ln.id?crypto.randomUUID():null;Zr&&(Ar=Ns(Ar,Zr));try{if(u&&Ln.email){const Er=new Date(Date.now()-6e5).toISOString(),{data:ti}=await V.from("bulk_email_sends").select("id").eq("user_id",u.id).eq("contact_email",Ln.email).eq("subject",Qn).gte("sent_at",Er).limit(1);if(ti&&ti.length>0)return console.log(`Skipping duplicate send to ${Ln.email} (same subject within 10 min)`),ae.info(`Skipped ${Ln.first_name||Ln.email} — already sent this in the last 10 min`),!0}const{inline:dn,paths:Kt}=await xs();if(A){const Er=(p==null?void 0:p.display_name)||"ReLevelUp",ti=`${Er.toLowerCase().replace(/[^a-z]/g,".")}@send.relevelup.com`,Ba=`${Er} <${ti}>`;let lo=Kt[0];if(!lo&&dn.length>0&&u){const Ur=dn[0],Ei=Ur.name.replace(/[^a-zA-Z0-9._-]/g,"_"),fo=`${u.id}/${Date.now()}-${Ei}`,co=atob(Ur.data),Tn=new Uint8Array(co.length);for(let Aa=0;Aa({name:Ba,type:lo,data:Yn})),attachment_paths:Kt,skip_signature:!0}});if(ti)throw ti;if(!(Er!=null&&Er.success))throw new Error((Er==null?void 0:Er.error)||"Failed to send")}if(u&&Ln.id&&Zr&&(await V.from("bulk_email_sends").insert({id:Zr,user_id:u.id,contact_id:Ln.id,contact_email:Ln.email,subject:Qn,source:c||(A?"ses_bulk":"sphere_gaps")}),d))try{await V.from("contact_touch_logs").insert({owner_user_id:u.id,contact_id:Ln.id,action_type_id:"9a88a47c-cb2a-4401-a2b5-111a76b19f9d",notes:`Mass Email: ${Qn}`,completed_at:new Date().toISOString()})}catch(Er){console.warn("touch log insert failed",Er)}return!0}catch(dn){return console.error("Send error:",dn),ae.error("Failed to send to "+Ln.first_name+": "+(dn instanceof Error?dn.message:"Unknown error")),!1}},Bs=()=>{const Ln=Be*Rj;return M.slice(Ln,Ln+Rj)},Ts=async(Ln=0,Sr=tt)=>{if(!U||!H){ae.error("Please fill in subject and message");return}ee(!0),Ue("sending");let Qn=Math.max(0,Math.min(Ln,M.length)),En=!1;for(;QnKt+1):ke(Kt=>Kt+1),ZrsetTimeout(Kt,150))}if(h.invalidateQueries({queryKey:["bulk-email-sends"]}),h.invalidateQueries({queryKey:["contact-touch-logs"]}),h.invalidateQueries({queryKey:["contacts-last-touch"]}),En||Ge.current||Qn>=M.length)break;if(!Sr){ee(!1),Ue("batch_complete");return}if(Oe(0),await new Promise(Zr=>setTimeout(Zr,1500)),Ge.current){En=!0;break}}ee(!1),Ue(En||Ge.current?"batch_complete":"all_done")},Fn=async()=>{var Sr;if(!U||!H){ae.error("Please fill in subject and message");return}const Ln=j?(r==null?void 0:r.length)||0:1;if(C.wouldExceed(Ln)){ae.error(`Your package includes ${(Sr=C.limit)==null?void 0:Sr.toLocaleString()} emails per month. You have ${C.remaining.toLocaleString()} left — request an upgrade for unlimited sending.`);return}if(A&&g&&!g.hasVerifiedSes&&!g.hasGmail){y(!0);return}if(!j){const Qn=I||{id:"",first_name:"",last_name:"",email:O.trim()};if(!Qn.email){ae.error("Please enter a recipient email");return}ee(!0);try{await us(Qn)&&(h.invalidateQueries({queryKey:["bulk-email-sends"]}),ae.success("Email sent successfully!"),t(!1),o==null||o())}finally{ee(!1)}return}Ge.current=!1,yt.current=0,await Ts(0)},An=async()=>{Ge.current=!1,Oe(0),await Ts(yt.current,!1)},js=async()=>{Ge.current=!1,ut(!0),Oe(0),await Ts(yt.current,!0)},In=()=>{if(se){Ge.current=!0;return}t(!1),o==null||o()},un=Be*Rj;Math.min(un+Rj,M.length);const jr=j&&M.length>0?Math.round((Ye+Re)/M.length*100):0;return e.jsxs(zs,{open:s,onOpenChange:In,children:[e.jsxs(Rs,{className:"sm:max-w-[600px] max-h-[90vh] overflow-y-auto",children:[e.jsxs(Vs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(pn,{className:`h-5 w-5 ${A?"text-orange-500":"text-red-500"}`}),j?`Send to ${M.length} Contacts`:"Compose Email"]}),A?e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Sending via ",e.jsx("span",{className:"font-medium",children:"Mass Email"})," (reply-to: ",p==null?void 0:p.reply_to_email,")"]}):l?e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Sending from ",e.jsx("span",{className:"font-medium",children:l})]}):null,j&&Ie==="composing"&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["Composing email for ",e.jsxs("span",{className:"font-medium",children:[M.length," contacts"]}),". You'll review each personalized email before sending."]})]}),Ie==="sending"&&e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"text-center space-y-2",children:[e.jsx(Jt,{className:"h-8 w-8 animate-spin mx-auto text-primary"}),e.jsxs("p",{className:"font-medium",children:["Sending batch ",Be+1," of ",P,"..."]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[Fe," of ",Bs().length," in this batch"]}),tt&&P>1&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Auto-continuing through all ",P," batches — keep this window open."]})]}),e.jsx(ho,{value:Fe/Math.max(Bs().length,1)*100,className:"h-2"}),e.jsxs("div",{className:"flex justify-between text-xs text-muted-foreground",children:[e.jsxs("span",{children:["Overall: ",Ye+Re," / ",M.length]}),e.jsxs("span",{children:[Ye," sent • ",Re," failed"]})]}),e.jsx($,{variant:"outline",size:"sm",className:"w-full",onClick:()=>{Ge.current=!0},children:"Stop Sending"})]}),Ie==="batch_complete"&&e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"text-center space-y-2",children:[e.jsx(Gr,{className:"h-8 w-8 text-emerald-500 mx-auto"}),e.jsxs("p",{className:"font-medium",children:["Sending paused after batch ",Be+1]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[Ye," sent, ",Re," failed so far"]})]}),e.jsx(ho,{value:jr,className:"h-2"}),e.jsxs("p",{className:"text-xs text-center text-muted-foreground",children:[M.length-Ye-Re," contacts remaining (",Math.max(P-Be-1,0)," batches left)"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{variant:"outline",className:"flex-1",onClick:In,children:"Done for Now"}),e.jsxs($,{className:"flex-1 gap-2",onClick:js,children:[e.jsx(Wr,{className:"h-4 w-4"}),"Resume Sending"]})]}),e.jsxs($,{variant:"ghost",size:"sm",className:"w-full",onClick:An,children:["Send just the next ",Math.min(Rj,Math.max(M.length-(Ye+Re),0))," contacts"]})]}),Ie==="all_done"&&e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"text-center space-y-2",children:[e.jsx(Gr,{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:[Ye," emails sent successfully",Re>0&&e.jsxs("span",{className:"text-destructive",children:[" • ",Re," failed"]})]})]}),e.jsx($,{className:"w-full",onClick:In,children:"Close"})]}),Ie==="composing"&&e.jsxs("div",{className:"space-y-4",children:[oe?e.jsxs("div",{className:"border rounded-lg p-3 bg-muted/30 max-h-[50vh] overflow-y-auto",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("p",{className:"text-sm font-medium flex items-center gap-1.5",children:[e.jsx(ea,{className:"h-4 w-4"})," Choose a Template"]}),e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>me(!1),className:"h-7 px-2 text-xs",children:[e.jsx(mr,{className:"h-3 w-3 mr-1"})," Write from scratch"]})]}),e.jsx(zkn,{onSelect:gt})]}):e.jsxs($,{variant:"outline",size:"sm",className:"gap-2",onClick:()=>me(!0),children:[e.jsx(ea,{className:"h-4 w-4"}),"Browse Templates"]}),e.jsx(Pc,{}),!j&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{htmlFor:"gmail-to",children:"To"}),e.jsx(I7t,{value:O,onChange:B,userId:u==null?void 0:u.id})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{htmlFor:"gmail-subject",children:"Subject"}),e.jsx(be,{id:"gmail-subject",value:U,onChange:Ln=>{G(Ln.target.value),_e(Ln.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(re,{htmlFor:"gmail-body",children:"Message"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(qe,{variant:"outline",className:"text-[10px] cursor-pointer hover:bg-accent",onClick:()=>{Y(Ln=>Ln+"{{first_name}}"),he(Ln=>Ln+"{{first_name}}")},children:"{{first_name}}"}),e.jsx(qe,{variant:"outline",className:"text-[10px] cursor-pointer hover:bg-accent",onClick:()=>{Y(Ln=>Ln+"{{last_name}}"),he(Ln=>Ln+"{{last_name}}")},children:"{{last_name}}"}),_&&e.jsx(qe,{variant:"outline",className:"text-[10px] cursor-pointer hover:bg-primary/10 border-primary/40 text-primary",onClick:()=>{const Ln=` When you get a sec, can you share your latest contact info with me? It only takes about a minute: ${_} `;Y(Sr=>Sr+Ln),he(Sr=>Sr+Ln)},title:"Insert your Connect Page link",children:"+ Connect Page"})]})]}),jt&&!Se?e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"overflow-hidden rounded-xl border bg-background",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2 border-b bg-muted/40 px-3 py-2",children:[e.jsx("p",{className:"text-[11px] font-semibold uppercase tracking-wider text-muted-foreground",children:"Branded email preview"}),e.jsx($,{type:"button",variant:"ghost",size:"sm",className:"h-7 px-2 text-xs",onClick:()=>Te(!0),children:"Edit as plain text"})]}),e.jsx("div",{className:"max-h-[420px] overflow-y-auto [&_img]:max-w-full",dangerouslySetInnerHTML:{__html:Dj(jt,I||{first_name:"there"})}})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"This designed template is sent as-is, personalized for each recipient."})]}):e.jsx(Ls,{id:"gmail-body",value:H,onChange:Ln=>{Y(Ln.target.value),he(Ln.target.value)},placeholder:"Write your message...",rows:10,className:"resize-y"}),j&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Use ","{{first_name}}",", ","{{last_name}}"," to personalize. You'll preview each recipient's email in the next step."]}),e.jsxs("div",{className:"flex items-center justify-between rounded-md border bg-muted/30 px-3 py-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs font-medium",children:"Include my email signature"}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:et?"Your saved signature is added to the bottom of this email.":"Add a signature in Profile settings to use this."})]}),e.jsx(On,{checked:at&&et,onCheckedChange:wt,disabled:!et})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs($,{type:"button",variant:"outline",size:"sm",className:"gap-2",onClick:()=>{var Ln;return(Ln=document.getElementById("gmail-attachments"))==null?void 0:Ln.click()},disabled:se,children:[e.jsx(KT,{className:"h-4 w-4"}),"Attach Files"]}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["PDF, images, Word, Excel (max ",vae(XRe)," 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:Ut})]}),Q.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2",children:Q.map((Ln,Sr)=>e.jsxs(qe,{variant:"secondary",className:"gap-1.5 pl-2 pr-1 py-1",children:[e.jsx(KT,{className:"h-3 w-3"}),e.jsx("span",{className:"max-w-[140px] truncate text-xs",children:Ln.name}),e.jsxs("span",{className:"text-[10px] text-muted-foreground",children:["(",vae(Ln.size),")"]}),e.jsx("button",{type:"button",onClick:()=>Is(Sr),className:"ml-0.5 rounded-full p-0.5 hover:bg-muted",children:e.jsx(mr,{className:"h-3 w-3"})})]},Sr))}),A&&Q.some(Ln=>Ln.size>Nyt)&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Files over ",vae(Nyt)," will be sent as secure download links."]})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),j?e.jsxs($,{onClick:()=>{Ft(M[0]||null),Ue("reviewing")},disabled:!U||!H,className:"gap-2",children:["Review Emails",e.jsx(xi,{className:"h-4 w-4"})]}):e.jsxs($,{onClick:Fn,disabled:se||!U||!H||!O.trim(),className:"gap-2",children:[se?e.jsx(Jt,{className:"h-4 w-4 animate-spin"}):e.jsx(Wr,{className:"h-4 w-4"}),se?"Sending...":"Send Email"]})]})]}),Ie==="reviewing"&&j&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("p",{className:"text-xs text-primary bg-primary/10 rounded-md px-2.5 py-1.5",children:["✉️ Click any recipient below to preview the ",e.jsx("span",{className:"font-semibold",children:"exact personalized email"})," they will receive."]}),R&&e.jsxs("div",{className:"rounded-md border border-amber-500/30 bg-amber-500/5 px-2.5 py-2 space-y-2",children:[e.jsxs("p",{className:"text-xs text-amber-600",children:["📦 ",M.length," contacts will be sent in ",P," batches of up to ",Rj,"."]}),e.jsxs("label",{className:"flex items-start gap-2 text-xs cursor-pointer",children:[e.jsx("input",{type:"checkbox",className:"mt-0.5 accent-current",checked:tt,onChange:Ln=>ut(Ln.target.checked)}),e.jsxs("span",{children:[e.jsx("span",{className:"font-medium",children:"Send all batches automatically"}),e.jsx("span",{className:"block text-muted-foreground",children:"Runs straight through every batch — no need to click Continue. Keep this window open; you can stop anytime."})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(re,{children:["Recipients (",M.length,")"]}),e.jsx("div",{className:"bg-muted p-1.5 rounded-md space-y-0.5 max-h-32 overflow-y-auto",children:M.map(Ln=>e.jsxs("div",{className:`text-sm px-2 py-1 rounded cursor-pointer transition-colors ${(rt==null?void 0:rt.id)===Ln.id?"bg-primary/10 text-primary font-medium":"text-muted-foreground hover:bg-accent hover:text-foreground"}`,onClick:()=>Ft(Ln),children:[Ln.first_name," ",Ln.last_name," — ",Ln.email]},Ln.id))})]}),rt&&e.jsxs("div",{className:"border rounded-xl 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(pn,{className:"h-3.5 w-3.5"}),"Preview for ",rt.first_name," ",rt.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:"})," ",rt.email]}),e.jsxs("p",{children:[e.jsx("span",{className:"text-muted-foreground text-xs",children:"Subject:"})," ",Dj(fe,rt)]})]}),e.jsx(Pc,{}),jt?e.jsx("div",{className:"rounded-lg border bg-background max-h-72 overflow-y-auto [&_img]:max-w-full",dangerouslySetInnerHTML:{__html:Dj(jt,rt)}}):e.jsx("div",{className:"text-sm whitespace-pre-wrap bg-background rounded p-2.5 max-h-40 overflow-y-auto border",children:Dj(ve,rt)})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsxs($,{variant:"outline",onClick:()=>{Ue("composing"),Ft(null)},children:[e.jsx(Ia,{className:"h-4 w-4 mr-1"}),"Back to Edit"]}),e.jsxs($,{onClick:Fn,disabled:se,className:"gap-2",children:[se?e.jsx(Jt,{className:"h-4 w-4 animate-spin"}):e.jsx(Wr,{className:"h-4 w-4"}),R?`Send First ${Rj}`:`Send to ${M.length}`]})]})]})]}),e.jsx(XEe,{open:x,onOpenChange:y,hasPending:!!(g!=null&&g.hasPendingSes),pendingEmails:g==null?void 0:g.pendingEmails})]})}function Wkn(){const s=Jn(),{data:t}=vv(),{data:n}=Aee(),r=gAe(),{isGmailConnected:a,gmailEmail:i}=dx(),[l,o]=k.useState(null),[c,d]=k.useState(!1),[u,h]=k.useState(new Set),m=np(new Date),p=wu(m,30),g=A=>{if(!A)return null;const M=A.split(/[-/T]/);if(M.length<3)return null;const I=parseInt(M[1],10)-1,P=parseInt(M[2],10);return isNaN(I)||isNaN(P)?null:new Date(m.getFullYear(),I,P)},x=k.useMemo(()=>{if(!t)return[];const A=[];for(const M of t){if(M.birthday){const I=g(M.birthday);I&&(ah(I,m)||N_(I,m)&&Xw(I,p))&&A.push({contact:M,type:"birthday",date:I,daysUntil:o1(I,m),dateStr:M.birthday})}if(M.home_anniversary){const I=g(M.home_anniversary);I&&(ah(I,m)||N_(I,m)&&Xw(I,p))&&A.push({contact:M,type:"anniversary",date:I,daysUntil:o1(I,m),dateStr:M.home_anniversary})}if(M.wedding_anniversary){const I=g(M.wedding_anniversary);I&&(ah(I,m)||N_(I,m)&&Xw(I,p))&&A.push({contact:M,type:"wedding_anniversary",date:I,daysUntil:o1(I,m),dateStr:M.wedding_anniversary})}}return A.sort((M,I)=>M.daysUntil-I.daysUntil),A},[t]),y=A=>A==="birthday"?"Birthday":A==="wedding_anniversary"?"Wedding Anniversary":"Home Anniversary",v=async A=>{const M=(n==null?void 0:n.find(I=>I.name==="Call"))||(n==null?void 0:n[0]);if(M)try{await r.mutateAsync({contactId:A.contact.id,actionTypeId:M.id,notes:`${y(A.type)} outreach`}),h(I=>new Set(I).add(`${A.contact.id}-${A.type}`)),Ma({title:"Touch logged!",description:`Logged outreach for ${A.contact.first_name}`})}catch{Ma({title:"Error",description:"Failed to log touch",variant:"destructive"})}},_=A=>{const M=`${A.contact.first_name}${A.contact.last_name?" "+A.contact.last_name:""}`,I=A.type==="birthday"?"birthday":A.type==="wedding_anniversary"?"wedding_anniversary":"home_anniversary",P=new URLSearchParams({cardType:I,contactId:A.contact.id,name:M,...A.contact.address?{address:A.contact.address}:{},...(A.type==="anniversary"||A.type==="wedding_anniversary")&&A.dateStr?{date:A.dateStr}:{}});s(`/mission-control/card-studio?${P.toString()}`)},j=A=>A===0?"Today!":A===1?"Tomorrow":`${A} days`,C=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(we,{children:[e.jsx(Vt,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(Yt,{className:"text-lg flex items-center gap-2",children:[e.jsx(fd,{className:"h-5 w-5 text-primary"}),"Upcoming Milestones",e.jsx(qe,{variant:"secondary",className:"text-xs font-normal",children:"Next 30 days"})]}),e.jsxs("span",{className:"text-sm text-muted-foreground",children:[x.length," event",x.length!==1?"s":""]})]})}),e.jsxs(De,{className:"space-y-2",children:[x.length===0&&e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(ip,{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."})]}),x.map((A,M)=>{var O,B;const I=`${A.contact.id}-${A.type}`,P=u.has(I),R=`${((O=A.contact.first_name)==null?void 0:O[0])||""}${((B=A.contact.last_name)==null?void 0:B[0])||""}`.toUpperCase();return e.jsxs("div",{className:Ot("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"||A.type==="wedding_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(Wa,{className:Ot("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(Ka,{className:Ot("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:R})}),e.jsx("span",{className:"absolute -bottom-1.5 -right-1.5 text-base leading-none drop-shadow-sm",children:A.type==="birthday"?"🎂":A.type==="wedding_anniversary"?"💍":"🏠"})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"font-medium text-sm truncate",children:[A.contact.first_name," ",A.contact.last_name||""]}),e.jsx(qe,{variant:"outline",className:Ot("text-[10px] shrink-0 whitespace-nowrap",C(A.daysUntil)),children:j(A.daysUntil)})]}),e.jsxs("div",{className:Ot("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(ip,{className:"h-3 w-3"})," Birthday"]}):A.type==="wedding_anniversary"?e.jsxs(e.Fragment,{children:[e.jsx(Bo,{className:"h-3 w-3"})," Wedding Anniversary"]}):e.jsxs(e.Fragment,{children:[e.jsx(ua,{className:"h-3 w-3"})," Home Anniversary"]}),e.jsx("span",{children:"·"}),e.jsx("span",{children:Ys(A.date,"MMM d")})]})]})]}),e.jsxs("div",{className:"flex items-center gap-1 mt-2 pl-[52px]",children:[A.contact.phone&&e.jsx($,{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(ka,{className:"h-3.5 w-3.5"})})}),A.contact.phone&&e.jsx($,{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(bo,{className:"h-3.5 w-3.5"})})}),A.contact.email&&e.jsx($,{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(pn,{className:"h-3.5 w-3.5"})}),e.jsx($,{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(ia,{className:"h-3.5 w-3.5"})}),e.jsxs($,{variant:"ghost",size:"sm",className:Ot("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:()=>_(A),children:[e.jsx(kn,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"Card"})]}),e.jsx($,{variant:"ghost",size:"icon",className:Ot("h-7 w-7",P&&"text-green-600"),title:"Log a touch",disabled:P||r.isPending,onClick:()=>v(A),children:e.jsx(Gr,{className:"h-3.5 w-3.5"})}),e.jsx($,{variant:"ghost",size:"icon",className:"h-7 w-7",title:"View contact",onClick:()=>s(`/mission-control/contacts/${A.contact.id}`),children:e.jsx(ba,{className:"h-3.5 w-3.5"})})]})]},`${I}-${M}`)})]})]}),a&&l&&e.jsx(W2,{open:c,onOpenChange:d,contact:l,gmailEmail:i})]})}function Kkn(s){const[t,n]=k.useState([]),[r,a]=k.useState(!1),{data:i,isLoading:l}=pt({queryKey:["active-visitors",s],queryFn:async()=>{if(!s)return[];try{await V.rpc("cleanup_stale_visitors")}catch{}const{data:u}=await V.from("lead_site_active_visitors").select("*").eq("lead_site_id",s).gte("last_seen_at",new Date(Date.now()-2*60*1e3).toISOString()).order("last_seen_at",{ascending:!1});if(!u)return[];const h=u.map(g=>g.contact_id).filter(Boolean);let m={};if(h.length>0){const{data:g}=await V.from("innercircle_contacts").select("id, first_name, last_name, email, phone").in("id",h);(g||[]).forEach(x=>{m[x.id]=x})}const p=u.map(g=>g.auth_user_id).filter(Boolean);if(p.length>0){const{data:g}=await V.from("lead_site_consumer_profiles").select("user_id, name, phone, contact_id").eq("lead_site_id",s).in("user_id",p);(g||[]).forEach(x=>{const y=u.find(v=>v.auth_user_id===x.user_id);y&&!y.contact_id&&x.contact_id&&(y.contact_id=x.contact_id),y&&!m[y.contact_id||""]&&x.name&&(m[y.contact_id||y.auth_user_id||""]={first_name:x.name.split(" ")[0],last_name:x.name.split(" ").slice(1).join(" ")||null,email:null,phone:x.phone})})}return u.map(g=>{var x,y;return{...g,contact_name:m[g.contact_id||g.auth_user_id||""]?`${m[g.contact_id||g.auth_user_id||""].first_name} ${m[g.contact_id||g.auth_user_id||""].last_name||""}`.trim():null,contact_email:((x=m[g.contact_id||g.auth_user_id||""])==null?void 0:x.email)||null,contact_phone:((y=m[g.contact_id||g.auth_user_id||""])==null?void 0:y.phone)||null}})},enabled:!!s,refetchInterval:6e4});k.useEffect(()=>{if(!s)return;const u=V.channel(`active-visitors-${s}`).on("postgres_changes",{event:"*",schema:"public",table:"lead_site_active_visitors",filter:`lead_site_id=eq.${s}`},h=>{h.eventType==="INSERT"?n(m=>m.find(g=>g.id===h.new.id)?m:[h.new,...m]):h.eventType==="UPDATE"?n(m=>m.map(p=>p.id===h.new.id?{...p,...h.new}:p)):h.eventType==="DELETE"&&n(m=>m.filter(p=>p.id!==h.old.id))}).subscribe(h=>{h==="SUBSCRIBED"&&a(!0)});return()=>{V.removeChannel(u)}},[s]);const o=r&&t.length>0?Ykn([...t,...i||[]]):i||[],c=Date.now(),d=o.filter(u=>c-new Date(u.last_seen_at).getTime()<2*60*1e3);return{activeVisitors:d,isLoading:l,count:d.length}}function Ykn(s){const t=new Set;return s.filter(n=>t.has(n.id)?!1:(t.add(n.id),!0))}const Zkn={property_view:{label:"Viewed",icon:ba,color:"text-blue-500",bgColor:"bg-blue-500/10"},new_lead:{label:"New Lead",icon:Pl,color:"text-emerald-500",bgColor:"bg-emerald-500/10"},saved_listing:{label:"Saved",icon:Bo,color:"text-rose-500",bgColor:"bg-rose-500/10"}};function Xkn(){const{user:s}=ks(),t=Jn(),{isGmailConnected:n,gmailEmail:r}=dx(),{leadSite:a}=Tg(),{count:i}=Kkn(a==null?void 0:a.id),[l,o]=k.useState(!1),[c,d]=k.useState(null),{data:u,isLoading:h}=pt({queryKey:["lead-site-activity",s==null?void 0:s.id],queryFn:async()=>{const{data:v,error:_}=await V.rpc("get_lead_site_activity",{_user_id:s.id});if(_)throw _;return v},enabled:!!s,refetchInterval:6e4});if(h||!(u!=null&&u.has_site))return null;const m=(u.activities||[]).filter(v=>v.visitor_name&&v.visitor_name!=="Site Visitor"),p=m.filter(v=>v.activity_type==="new_lead"),g=(u.activities||[]).filter(v=>v.activity_type==="property_view").length,x=(u.activities||[]).filter(v=>v.activity_type==="saved_listing").length,y=v=>{if(v.visitor_email)if(n){const _=(v.visitor_name||"").split(" ");d({id:v.contact_id||"",first_name:_[0]||"",last_name:_.slice(1).join(" ")||null,email:v.visitor_email}),o(!0)}else window.location.href=`mailto:${v.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(kc,{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($,{variant:"ghost",size:"sm",className:"text-primary gap-1",onClick:()=>t("/mission-control/website-activity"),children:["View All",e.jsx(xi,{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(Pl,{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:p.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(ba,{className:"h-4 w-4 text-blue-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-lg font-bold text-blue-600 dark:text-blue-400",children:g}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Views"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 p-3 rounded-lg bg-rose-500/5 border border-rose-200 dark:border-rose-800",children:[e.jsx(Bo,{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:x}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Saved"})]})]})]}),m.length>0?e.jsxs("div",{className:"space-y-2",children:[m.slice(0,5).map((v,_)=>{const j=Zkn[v.activity_type],C=j.icon,A=Zc(new Date(v.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 ${j.bgColor}`,children:e.jsx(C,{className:`h-3.5 w-3.5 ${j.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:()=>{v.contact_id&&t(`/mission-control/contacts/${v.contact_id}`)},children:v.visitor_name}),e.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-muted-foreground",children:[e.jsx("span",{children:j.label}),v.mls_number&&e.jsxs("span",{children:["· MLS# ",v.mls_number]}),v.lead_type&&e.jsxs("span",{children:["· ",v.lead_type]}),e.jsxs("span",{children:["· ",A]})]})]}),e.jsxs("div",{className:"flex items-center gap-0.5 shrink-0",children:[v.visitor_email&&e.jsx($,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-primary",onClick:()=>y(v),children:e.jsx(pn,{className:"h-3.5 w-3.5"})}),v.visitor_phone&&e.jsxs(e.Fragment,{children:[e.jsx($,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-primary",onClick:()=>window.location.href=`tel:${v.visitor_phone}`,children:e.jsx(ka,{className:"h-3.5 w-3.5"})}),e.jsx($,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-primary",onClick:()=>window.location.href=`sms:${v.visitor_phone}`,children:e.jsx(bo,{className:"h-3.5 w-3.5"})})]}),v.contact_id&&e.jsx($,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>t(`/mission-control/contacts/${v.contact_id}`),children:e.jsx(fi,{className:"h-3.5 w-3.5"})})]})]},`${v.activity_type}-${v.occurred_at}-${_}`)}),m.length>5&&e.jsxs($,{variant:"outline",className:"w-full text-xs",onClick:()=>t("/mission-control/website-activity"),children:["View ",m.length-5," more activities",e.jsx(xi,{className:"h-3.5 w-3.5 ml-1"})]})]}):e.jsx(we,{children:e.jsxs(De,{className:"p-6 text-center",children:[e.jsx(zp,{className:"h-8 w-8 text-muted-foreground/30 mx-auto mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No actionable website activity yet."}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:g>0?`${g} anonymous listing views recorded.`:"Lead engagement will appear here as visitors interact with your site."}),e.jsxs($,{variant:"outline",size:"sm",className:"mt-3",onClick:()=>t("/mission-control/website-activity"),children:["View Full Activity",e.jsx(xi,{className:"h-3.5 w-3.5 ml-1"})]})]})}),n&&c&&e.jsx(W2,{open:l,onOpenChange:o,contact:c,gmailEmail:r})]})}const kyt={Crown:ky,FileText:ea,Users:Xn,Globe:kc,Star:ri,Phone:ka,MessageSquare:bo,PenTool:YT,Video:ia,Gift:Zo},Qkn={"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 Jkn(){var wt,rt,Ft,Ut,Is,xs;const s=Jn(),{user:t}=ks(),{data:n}=vj(),{data:r}=WMt(),{data:a}=vv(),{data:i}=Aee(),{data:l}=vWe(),o=$Es(),c=xAe(),d=FEs(90),u=gAe(),[h,m]=k.useState(null),[p,g]=k.useState(null),[x,y]=k.useState(!1),[v,_]=k.useState(""),[j,C]=k.useState(!1),[A,M]=k.useState(""),[I,P]=k.useState(XMt()),[R,O]=k.useState("cards"),[B,U]=k.useState(!1),[G,H]=k.useState(null),[Y,se]=k.useState(null),[ee,oe]=k.useState(""),{isGmailConnected:me,gmailEmail:Q}=dx(),te=()=>{const st=parseInt(A,10);if(isNaN(st)||st<1){Ma({title:"Invalid goal",description:"Please enter a number greater than 0",variant:"destructive"});return}P(st),zEs(st),C(!1),Ma({title:"Goal updated",description:`Weekly touch goal set to ${st}`})},le=()=>{M(I.toString()),C(!0)};k.useEffect(()=>{(async()=>{if(!(t!=null&&t.id))return;const{data:dt}=await V.from("profiles").select("name").eq("id",t.id).single();dt!=null&&dt.name&&_(dt.name.split(" ")[0])})()},[t==null?void 0:t.id]),k.useEffect(()=>{o.mutate()},[]);const fe=np(new Date),_e=wu(fe,7),ve=st=>{if(!st)return null;const dt=st.split(/[-/T]/);if(dt.length<3)return null;const jt=parseInt(dt[1],10)-1,gt=parseInt(dt[2],10);return isNaN(jt)||isNaN(gt)?null:new Date(fe.getFullYear(),jt,gt)},he=(a==null?void 0:a.filter(st=>{const dt=ve(st.birthday),jt=ve(st.home_anniversary);return dt&&ah(dt,fe)||jt&&ah(jt,fe)}))||[],Se=(a==null?void 0:a.filter(st=>{if(!st.birthday&&!st.home_anniversary)return!1;const dt=jt=>{if(!jt)return!1;const gt=ve(jt);return gt?N_(gt,fe)&&Xw(gt,_e):!1};return dt(st.birthday)||dt(st.home_anniversary)}).slice(0,5))||[],Te=[],Ie=(i==null?void 0:i.find(st=>st.name==="Call"))||(i==null?void 0:i[0]);for(const st of he){const dt=ve(st.birthday),jt=ve(st.home_anniversary),gt=dt&&ah(dt,fe),rs=jt&&ah(jt,fe);gt&&Te.push({contact:st,actionType:Ie||{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:((Ft=(rt=(wt=st.tags)==null?void 0:wt[0])==null?void 0:rt.relationship_type)==null?void 0:Ft.name)||"",monthNumber:0,isSpecialDate:!0,specialDateType:"birthday"}),rs&&Te.push({contact:st,actionType:Ie||{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:((xs=(Is=(Ut=st.tags)==null?void 0:Ut[0])==null?void 0:Is.relationship_type)==null?void 0:xs.name)||"",monthNumber:0,isSpecialDate:!0,specialDateType:"anniversary"})}const Be=l!==void 0?l||[]:(a==null?void 0:a.slice(0,5).map((st,dt)=>{var gt,rs,Ns;const jt=i==null?void 0:i[dt%((i==null?void 0:i.length)||1)];return jt?{contact:st,actionType:jt,planName:"Quick Touch",relationshipTypeName:((Ns=(rs=(gt=st.tags)==null?void 0:gt[0])==null?void 0:rs.relationship_type)==null?void 0:Ns.name)||"",monthNumber:0}:null}).filter(Boolean))||[],je=[...Te,...Be],{data:Ye}=Jq(7),Ee=(Ye||[]).filter(st=>ah(new Date(st.completed_at),fe)).length,Re=Ee+je.length,ke=(a==null?void 0:a.length)??0,Fe=Te.length>0?`${Te.length} celebration${Te.length===1?"":"s"} today — a card or a call goes a long way.`:d.count>0?`${d.count} people haven't heard from you in 90+ days. Start with one.`:Se.length>0?`${Se.length} milestone${Se.length===1?"":"s"} coming up this week — get ahead of them.`:"Consistency beats intensity. A few real conversations today is a win.",Oe=async(st,dt,jt)=>{await u.mutateAsync({contactId:st,actionTypeId:dt,scriptUsedId:jt}),y(!1),g(null)},Ge=st=>{st.script?(g(st),y(!0)):Oe(st.contact.id,st.actionType.id)},yt=st=>kyt[st||"Phone"]||ka,tt=st=>kyt[st||"Users"]||Xn,ut=(st,dt)=>st.replace(/\{\{FirstName\}\}/g,dt.first_name).replace(/\{\{LastName\}\}/g,dt.last_name||"").replace(/\{\{AgentName\}\}/g,v||"there"),nt=(st,dt)=>({Call:`Thinking of you, ${dt}!`,Text:`Quick hello, ${dt}`,Email:`Checking in, ${dt}`,"Handwritten Note":`A note for ${dt}`,Video:`Video message for ${dt}`,Gift:`Something special for you, ${dt}`})[st]||`Hello ${dt}!`,et=(st,dt,jt)=>{const gt=`sms:${st}`;if(dt&&jt){const rs=ut(dt,jt);return`${gt}?body=${encodeURIComponent(rs)}`}return gt},at=(st,dt,jt,gt,rs)=>{const Ns=`mailto:${st}`,us=[];if(rs){const Bs=jt||nt(gt||"Email",rs.first_name);if(us.push(`subject=${encodeURIComponent(Bs)}`),dt){const Ts=ut(dt,rs);us.push(`body=${encodeURIComponent(Ts)}`)}}return us.length>0?`${Ns}?${us.join("&")}`:Ns};return e.jsxs(e.Fragment,{children:[e.jsxs(Xs,{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 flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("h1",{className:"text-2xl font-bold tracking-tight",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.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs($,{size:"sm",onClick:()=>s("/mission-control/video/record"),className:"gap-1.5 bg-gradient-to-r from-primary to-primary/80",children:[e.jsx(em,{className:"h-4 w-4"}),"Quick Video"]}),e.jsxs($,{size:"sm",variant:"outline",onClick:()=>s("/mission-control/contacts"),className:"gap-1.5",children:[e.jsx(Xn,{className:"h-4 w-4"}),"Contacts"]}),e.jsxs($,{size:"sm",variant:"outline",onClick:()=>s("/mission-control/video-library"),className:"gap-1.5",children:[e.jsx(ia,{className:"h-4 w-4"}),"Library"]}),e.jsxs($,{size:"sm",variant:"outline",onClick:()=>s("/mission-control/plans"),className:"gap-1.5",children:[e.jsx(Yc,{className:"h-4 w-4"}),"Plans"]})]})]}),e.jsx(Tkn,{agentName:v,todayDone:Ee,todayTotal:Re,focusLine:Fe,weekDone:c.actionsThisWeek,weekGoal:I,streak:c.streak,staleCount:d.count,sphereCount:ke,onEditGoal:le,onStaleClick:()=>s("/mission-control/contacts?filter=not-touched-90"),onSphereClick:()=>s("/mission-control/contacts")}),e.jsx(Xkn,{}),e.jsxs("section",{children:[e.jsxs("div",{className:"mb-3 flex items-center justify-between gap-2",children:[e.jsx("h2",{className:"text-sm font-semibold uppercase tracking-wide text-muted-foreground",children:"Your Sphere"}),e.jsxs("button",{onClick:()=>s("/mission-control/contacts"),className:"inline-flex items-center gap-1 text-xs font-medium text-primary hover:underline",children:["View all ",e.jsx(fi,{className:"h-3 w-3"})]})]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:n==null?void 0:n.filter(st=>st.active).map(st=>{const dt=tt(st.icon),jt=(r==null?void 0:r[st.id])||0,gt=h===st.id,rs=Qkn[st.name]||"bg-secondary text-secondary-foreground";return e.jsxs("button",{onClick:()=>{gt?(m(null),s("/mission-control/contacts")):(m(st.id),s(`/mission-control/contacts?type=${st.id}`))},className:` inline-flex items-center gap-2 rounded-full border px-3 py-1.5 text-sm transition-all ${gt?rs:"bg-card hover:bg-accent"} `,children:[e.jsx(dt,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"font-medium",children:st.name}),e.jsx("span",{className:`rounded-full px-1.5 py-0.5 text-[11px] tabular-nums ${gt?"bg-black/15":"bg-muted text-muted-foreground"}`,children:jt})]},st.id)})})]}),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(qe,{variant:"outline",className:"gap-1",children:[e.jsx(kn,{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($,{variant:R==="cards"?"secondary":"ghost",size:"sm",className:"h-7 px-2",onClick:()=>O("cards"),title:"Card view",children:e.jsx(y0,{className:"h-4 w-4"})}),e.jsx($,{variant:R==="table"?"secondary":"ghost",size:"sm",className:"h-7 px-2",onClick:()=>O("table"),title:"Table view",children:e.jsx(Sy,{className:"h-4 w-4"})})]})]}),e.jsx(we,{children:e.jsx(De,{className:"p-4",children:je.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($,{variant:"outline",className:"mt-4",onClick:()=>s("/mission-control/plans"),children:"Manage Plans"})]}):R==="table"?e.jsx(Okn,{actions:je,onMarkComplete:Oe,onViewScript:Ge,isLoading:u.isPending,buildSmsLink:et,buildEmailLink:at,onGmailCompose:me?st=>{H(st),U(!0)}:void 0}):e.jsxs("div",{className:"flex gap-3 overflow-x-auto pb-2",children:[je.map((st,dt)=>{var Fn,An,js,In,un,jr,Ln;const jt=st.isSpecialDate,gt=st.specialDateType,rs=jt?gt==="birthday"?ip:ua:yt(((Fn=st.actionType)==null?void 0:Fn.icon)||null),Ns=st.contact.phone,us=st.contact.email,Bs=jt?gt==="birthday"?"#EC4899":"#8B5CF6":((An=st.actionType)==null?void 0:An.color)||"#3B82F6",Ts=jt?gt==="birthday"?"🎂 Birthday Today!":"🏠 Home Anniversary!":(js=st.actionType)==null?void 0:js.name;return e.jsxs("div",{className:`flex-shrink-0 w-[260px] border rounded-lg overflow-hidden ${jt?"ring-2 ring-offset-2":""}`,style:jt?{"--tw-ring-color":Bs}:void 0,children:[e.jsxs("div",{className:"p-3 text-white flex items-center gap-2",style:{backgroundColor:Bs},children:[e.jsx(rs,{className:"h-4 w-4"}),e.jsx("span",{className:"font-medium text-sm",children:Ts})]}),e.jsxs("div",{className:"p-3 space-y-2",children:[e.jsxs("button",{onClick:()=>s(`/mission-control/contacts/${st.contact.id}`),className:"font-medium text-sm hover:text-primary hover:underline transition-colors text-left",children:[st.contact.first_name," ",st.contact.last_name]}),e.jsxs("div",{className:"flex gap-1.5",children:[Ns&&e.jsxs(e.Fragment,{children:[e.jsxs("a",{href:`tel:${st.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(ka,{className:"h-3 w-3"}),"Call"]}),e.jsxs("a",{href:et(st.contact.phone,(In=st.script)==null?void 0:In.script_body,st.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(bo,{className:"h-3 w-3"}),"Text"]})]}),us&&(me?e.jsxs("button",{onClick:()=>{H({id:st.contact.id,first_name:st.contact.first_name,last_name:st.contact.last_name,email:st.contact.email}),U(!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(pn,{className:"h-3 w-3"}),"Email"]}):e.jsxs("a",{href:at(st.contact.email,(un=st.script)==null?void 0:un.script_body,(jr=st.script)==null?void 0:jr.email_subject,(Ln=st.actionType)==null?void 0:Ln.name,st.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(pn,{className:"h-3 w-3"}),"Email"]}))]}),jt&&e.jsxs("button",{onClick:()=>{const Sr=`${st.contact.first_name}${st.contact.last_name?" "+st.contact.last_name:""}`,Qn=gt==="birthday"?"birthday":"home_anniversary",En=new URLSearchParams({cardType:Qn,contactId:st.contact.id,name:Sr,...st.contact.address?{address:st.contact.address}:{},...gt==="anniversary"&&st.contact.home_anniversary?{date:st.contact.home_anniversary}:{}});s(`/mission-control/card-studio?${En.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(pn,{className:"h-3 w-3"}),"Send ",gt==="birthday"?"Birthday":"Anniversary"," Card"]}),!Ns&&!us&&e.jsx("p",{className:"text-xs text-muted-foreground italic",children:"No contact info"}),e.jsxs("div",{className:"flex gap-1 flex-wrap",children:[st.relationshipTypeName&&e.jsx(qe,{variant:"secondary",className:"text-xs",children:st.relationshipTypeName}),st.monthNumber>0&&e.jsxs(qe,{variant:"outline",className:"text-xs",children:["Month ",st.monthNumber]})]}),st.script&&e.jsx($,{size:"sm",variant:"outline",className:"w-full",onClick:()=>Ge(st),children:"View Script"}),e.jsxs("div",{className:"flex gap-1.5",children:[e.jsxs($,{size:"sm",variant:"outline",className:"flex-1 gap-1",onClick:()=>{se(st.contact.id),oe(`${st.contact.first_name} ${st.contact.last_name||""}`.trim())},children:[e.jsx(uv,{className:"h-3.5 w-3.5"}),"Snooze"]}),e.jsx($,{size:"sm",className:"flex-1",onClick:()=>{var Sr;return Oe(st.contact.id,st.actionType.id,(Sr=st.script)==null?void 0:Sr.id)},disabled:u.isPending,children:"Mark Complete"})]})]})]},st.contact.id+dt)}),e.jsx("div",{className:"flex-shrink-0 w-[100px] border rounded-lg flex items-center justify-center",children:e.jsxs(Au,{children:[e.jsx(Eu,{asChild:!0,children:e.jsxs($,{variant:"ghost",className:"h-full w-full",children:[e.jsx(u0,{className:"h-5 w-5 mr-2"}),"More"]})}),e.jsx(gu,{children:e.jsx(Pa,{onClick:()=>s("/mission-control/contacts"),children:"View all contacts"})})]})})]})})})]}),e.jsxs("div",{className:"rounded-2xl border bg-card p-4",children:[e.jsxs("div",{className:"mb-2 flex items-center justify-between gap-2",children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5 text-[11px] font-medium uppercase tracking-wide text-muted-foreground",children:[e.jsx(iu,{className:"h-3.5 w-3.5 text-orange-500"}),"This week's momentum"]}),e.jsxs("span",{className:"text-xs tabular-nums text-muted-foreground",children:[c.actionsThisWeek," of ",I," touches"]})]}),e.jsx(ho,{value:Math.min(c.actionsThisWeek/I*100,100),className:"h-2.5 w-full max-w-full"}),e.jsx("p",{className:"mt-2 text-xs text-muted-foreground",children:c.actionsThisWeek>=I?"Goal hit for the week — anything else is bonus.":`${I-c.actionsThisWeek} more to hit your goal.`})]}),e.jsx(zs,{open:j,onOpenChange:C,children:e.jsxs(Rs,{className:"sm:max-w-[360px]",children:[e.jsxs(Vs,{children:[e.jsx($s,{children:"Set Weekly Goal"}),e.jsx(Cr,{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(re,{htmlFor:"weekly-goal-ic",children:"Weekly touch goal"}),e.jsx(be,{id:"weekly-goal-ic",type:"number",min:"1",value:A,onChange:st=>M(st.target.value),placeholder:"20",onKeyDown:st=>{st.key==="Enter"&&te()}})]}),e.jsx($,{onClick:te,className:"w-full",children:"Save Goal"})]})]})}),e.jsxs("div",{className:"grid md:grid-cols-2 gap-6",children:[e.jsx(e6t,{}),e.jsx(Wkn,{})]})]}),e.jsx(zs,{open:x,onOpenChange:y,children:e.jsxs(Rs,{className:"max-w-md",children:[e.jsx(Vs,{children:e.jsx($s,{className:"flex items-center gap-2",children:p&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"w-3 h-3 rounded-full",style:{backgroundColor:p.actionType.color||"#3B82F6"}}),p.actionType.name," Script"]})})}),p&&p.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:[p.contact.first_name," ",p.contact.last_name]})]}),e.jsx("div",{className:"bg-muted p-4 rounded-lg",children:e.jsx("p",{className:"whitespace-pre-wrap",children:ut(p.script.script_body,p.contact)})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{variant:"outline",className:"flex-1",onClick:()=>y(!1),children:"Close"}),e.jsx($,{className:"flex-1",onClick:()=>{var st;return Oe(p.contact.id,p.actionType.id,(st=p.script)==null?void 0:st.id)},disabled:u.isPending,children:"Mark Complete"})]})]})]})}),e.jsx(Mkn,{})]}),me&&G&&e.jsx(W2,{open:B,onOpenChange:U,contact:G,gmailEmail:Q}),e.jsx(nTe,{open:!!Y,onOpenChange:st=>!st&&se(null),contactId:Y||"",contactName:ee})]})}const eSn=[{value:"bidirectional",label:"Two-Way",icon:Ix,tooltip:"Sync contacts in both directions"},{value:"push_only",label:"Push Only",icon:ap,tooltip:"Only push Agent OS → BoldTrail"},{value:"pull_only",label:"Pull Only",icon:nx,tooltip:"Only pull BoldTrail → Agent OS"}];function T4e({value:s,onChange:t,size:n="default"}){const r=n==="sm"?"text-xs":"text-sm";return e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("p",{className:`font-medium ${r} text-muted-foreground`,children:"Sync Direction"}),e.jsx(AB,{type:"single",value:s,onValueChange:a=>{a&&t(a)},className:"justify-start",children:eSn.map(a=>e.jsxs(Lx,{children:[e.jsx(Rx,{asChild:!0,children:e.jsxs(oO,{value:a.value,"aria-label":a.tooltip,className:`gap-1.5 ${r} border border-transparent data-[state=on]:!bg-primary data-[state=on]:!text-primary-foreground data-[state=on]:!border-primary data-[state=on]:shadow-sm`,children:[e.jsx(a.icon,{className:n==="sm"?"h-3 w-3":"h-4 w-4"}),a.label]})}),e.jsx(Jg,{children:a.tooltip})]},a.value))})]})}function tSn(){const s=ls(),[t,n]=k.useState(!1),[r,a]=k.useState(null),[i,l]=k.useState(!1),[o,c]=k.useState(!1),[d,u]=k.useState(null),[h,m]=k.useState(null),[p,g]=k.useState(0),x=k.useRef(!1),{data:y}=pt({queryKey:["boldtrail-status"],queryFn:async()=>{const{data:R,error:O}=await V.functions.invoke("boldtrail-sync",{body:{action:"status"}});if(O)throw O;return R}}),v=(y==null?void 0:y.sync_direction)||"bidirectional",_=d??v,j=Nt({mutationFn:async()=>{const{data:R,error:O}=await V.functions.invoke("boldtrail-sync",{body:{action:"sync_preview"}});if(O)throw O;if(R!=null&&R.error)throw new Error(R.error);return R},onSuccess:R=>{u(null),a(R),n(!0)},onError:R=>{ae.error(R.message||"Failed to generate sync preview")}}),C=Nt({mutationFn:async()=>{x.current=!1,m("Initializing sync..."),g(5);const{data:R,error:O}=await V.functions.invoke("boldtrail-sync",{body:{action:"sync",phase:"init",sync_direction:_}});if(O)throw O;if(R!=null&&R.error)throw new Error(R.error);const B=R;let U=B.sync_log_id,G=B.next_phase,H=B.next_offset,Y=B.push_total||0,se=B.pull_total||0,ee=B.update_total||0,oe=0,me=0,Q=0;for(;G!=="finalize"&&!x.current;){const fe=Y+se+ee;G==="fetch_bt"?m("Fetching BoldTrail contacts..."):G==="analyze"?(m("Analyzing contacts..."),g(15)):G==="push"?(m(`Pushing contacts to BoldTrail... (${oe}/${Y})`),g(fe>0?oe/fe*90:0)):G==="pull"?(m(`Pulling contacts from BoldTrail... (${me}/${se})`),g(fe>0?(Y+me)/fe*90:0)):G==="update"&&(m(`Updating existing contacts... (${Q}/${ee})`),g(fe>0?(Y+se+Q)/fe*90:0));const{data:_e,error:ve}=await V.functions.invoke("boldtrail-sync",{body:{action:"sync",phase:G,offset:H,sync_log_id:U,sync_direction:_}});if(ve)throw ve;if(_e!=null&&_e.error)throw new Error(_e.error);const he=_e;oe+=he.chunk_pushed||0,me+=he.chunk_pulled||0,Q+=he.chunk_updated||0,he.push_total!==void 0&&(Y=he.push_total||0),he.pull_total!==void 0&&(se=he.pull_total||0),he.update_total!==void 0&&(ee=he.update_total||0),he.progress&&m(he.progress),G=he.next_phase,H=he.next_offset}m("Finalizing sync..."),g(95);const{data:te,error:le}=await V.functions.invoke("boldtrail-sync",{body:{action:"sync",phase:"finalize",sync_log_id:U,sync_direction:_}});if(le)throw le;return g(100),te},onSuccess:R=>{m(null),g(0),n(!1),s.invalidateQueries({queryKey:["boldtrail-status"]}),s.invalidateQueries({queryKey:["innercircle-contacts"]}),s.invalidateQueries({queryKey:["innercircle-contact-counts"]}),s.invalidateQueries({queryKey:["contacts-last-touch"]});const O=[`Pushed ${R.contacts_pushed||0}`,`pulled ${R.contacts_pulled||0}`,`updated ${R.contacts_updated||0}`,`skipped ${R.contacts_skipped||0} duplicates`];ae.success(`Sync complete! ${O.join(", ")}.`)},onError:R=>{m(null),g(0),ae.error(R.message||"Sync failed")}});if(!(y!=null&&y.connected))return null;const A=_==="pull_only"?0:(r==null?void 0:r.to_push)??0,M=_==="push_only"?0:(r==null?void 0:r.to_pull)??0,I=(r==null?void 0:r.to_update)??0,P=A>0||M>0||I>0;return e.jsxs(e.Fragment,{children:[e.jsxs(Lx,{children:[e.jsx(Rx,{asChild:!0,children:e.jsx($,{variant:"outline",size:"icon",onClick:()=>j.mutate(),disabled:j.isPending,className:"shrink-0",children:j.isPending?e.jsx(yo,{className:"h-4 w-4 animate-spin"}):e.jsx(Ix,{className:"h-4 w-4 text-emerald-600"})})}),e.jsx(Jg,{children:"Sync with BoldTrail"})]}),e.jsx(zs,{open:t,onOpenChange:R=>{C.isPending||n(R)},children:e.jsxs(Rs,{className:"sm:max-w-lg",children:[e.jsxs(Vs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(Ix,{className:"h-5 w-5 text-emerald-600"}),"Sync Preview"]}),e.jsx(Cr,{children:"Review what will happen when you sync your contacts."})]}),r&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(T4e,{value:_,onChange:u,size:"sm"}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:`rounded-lg border p-3 text-center ${_==="pull_only"?"opacity-40":""}`,children:[e.jsx("p",{className:"text-2xl font-bold text-emerald-600",children:A}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center justify-center gap-1",children:[e.jsx(ap,{className:"h-3 w-3"})," Push to BoldTrail"]})]}),e.jsxs("div",{className:`rounded-lg border p-3 text-center ${_==="push_only"?"opacity-40":""}`,children:[e.jsx("p",{className:"text-2xl font-bold text-blue-600",children:M}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center justify-center gap-1",children:[e.jsx(nx,{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:I}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center justify-center gap-1",children:[e.jsx(oB,{className:"h-3 w-3"})," To update"]})]}),e.jsxs("div",{className:"rounded-lg border p-3 text-center",children:[e.jsx("p",{className:"text-2xl font-bold text-muted-foreground",children:r.already_synced}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center justify-center gap-1",children:[e.jsx(Xn,{className:"h-3 w-3"})," Already synced"]})]})]}),e.jsxs("div",{className:"text-xs text-muted-foreground text-center",children:["Agent OS: ",r.agent_os_total," contacts · BoldTrail: ",r.boldtrail_total," contacts"]}),I>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(oB,{className:"h-3 w-3 inline mr-1"}),I," contacts have missing fields that will be filled from the other system"]}),A>0&&e.jsxs(h1,{open:i,onOpenChange:l,children:[e.jsx(m1,{asChild:!0,children:e.jsxs($,{variant:"ghost",size:"sm",className:"w-full justify-between text-xs",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ap,{className:"h-3 w-3 text-emerald-600"}),A," contacts to push to BoldTrail"]}),e.jsx(Go,{className:`h-3 w-3 transition-transform ${i?"rotate-180":""}`})]})}),e.jsx(f1,{children:e.jsxs("div",{className:"rounded border divide-y max-h-40 overflow-y-auto",children:[r.push_preview.map((R,O)=>e.jsxs("div",{className:"px-3 py-1.5 text-xs flex justify-between",children:[e.jsx("span",{className:"font-medium",children:R.name||"No name"}),e.jsx("span",{className:"text-muted-foreground",children:R.email})]},O)),r.to_push>20&&e.jsxs("div",{className:"px-3 py-1.5 text-xs text-muted-foreground text-center",children:["...and ",r.to_push-20," more"]})]})})]}),M>0&&e.jsxs(h1,{open:o,onOpenChange:c,children:[e.jsx(m1,{asChild:!0,children:e.jsxs($,{variant:"ghost",size:"sm",className:"w-full justify-between text-xs",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(nx,{className:"h-3 w-3 text-blue-600"}),M," contacts to pull from BoldTrail"]}),e.jsx(Go,{className:`h-3 w-3 transition-transform ${o?"rotate-180":""}`})]})}),e.jsx(f1,{children:e.jsxs("div",{className:"rounded border divide-y max-h-40 overflow-y-auto",children:[r.pull_preview.map((R,O)=>e.jsxs("div",{className:"px-3 py-1.5 text-xs flex justify-between",children:[e.jsx("span",{className:"font-medium",children:R.name||"No name"}),e.jsx("span",{className:"text-muted-foreground",children:R.email})]},O)),r.to_pull>20&&e.jsxs("div",{className:"px-3 py-1.5 text-xs text-muted-foreground text-center",children:["...and ",r.to_pull-20," more"]})]})})]}),!P&&!C.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."}),C.isPending&&e.jsxs("div",{className:"space-y-2 py-2",children:[e.jsx(ho,{value:p||10,className:"h-2"}),e.jsx("p",{className:"text-xs text-muted-foreground text-center",children:h||"Sync in progress..."})]}),e.jsxs("div",{className:"flex gap-2 justify-end pt-2",children:[e.jsx($,{variant:"outline",onClick:()=>n(!1),disabled:C.isPending,children:"Cancel"}),e.jsxs($,{onClick:()=>C.mutate(),disabled:C.isPending||!P,className:"gap-2",children:[C.isPending?e.jsx(yo,{className:"h-4 w-4 animate-spin"}):e.jsx(Ix,{className:"h-4 w-4"}),C.isPending?"Syncing...":"Sync Now"]})]})]})]})})]})}const sSn=()=>{const{user:s}=ks();return pt({queryKey:["popby-items",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await V.from("popby_items").select("*").or(`owner_user_id.is.null,owner_user_id.eq.${s==null?void 0:s.id}`).eq("is_active",!0).order("name");if(n)throw n;return t},enabled:!!s})},aTe=s=>{const{user:t}=ks();return pt({queryKey:["popby-logs",t==null?void 0:t.id,s],queryFn:async()=>{let n=V.from("popby_logs").select("*").order("completed_at",{ascending:!1});if(s){const i=new Date;i.setDate(i.getDate()-s),n=n.gte("completed_at",i.toISOString())}const{data:r,error:a}=await n;if(a)throw a;return r},enabled:!!t})},zZe=()=>{const{user:s}=ks();return pt({queryKey:["relationship-type-popby-defaults",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await V.from("relationship_type_popby_defaults").select("*");if(n)throw n;return t},enabled:!!s})},L7t=()=>{const{user:s}=ks();return pt({queryKey:["contact-popby-settings",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await V.from("contact_popby_settings").select("*");if(n)throw n;return t},enabled:!!s})},nSn=()=>{const{data:s}=vv(),{data:t}=vj(),{data:n}=aTe(),{data:r}=L7t(),{data:a}=zZe(),i=new Map;n==null||n.forEach(u=>{const h=i.get(u.contact_id);(!h||new Date(u.completed_at)>new Date(h))&&i.set(u.contact_id,u.completed_at)});const l=new Map;a==null||a.forEach(u=>l.set(u.relationship_type_id,u.frequency_days));const o=new Map;r==null||r.filter(u=>u.is_active).forEach(u=>{o.set(u.contact_id,u.frequency_days)});const c=np(new Date);return(s||[]).map(u=>{let h=90;if(o.has(u.id))h=o.get(u.id);else if(u.tags&&u.tags.length>0){const y=u.tags.map(v=>l.get(v.relationship_type_id)).filter(v=>v!==void 0);y.length>0&&(h=Math.min(...y))}const m=i.get(u.id)||null,p=m?I2(c,np(new Date(m))):null,g=p===null||p>=h,x=g&&p!==null?p-h:0;return{...u,lastPopby:m,daysSinceLastPopby:p,frequencyDays:h,isDue:g,daysOverdue:x}}).sort((u,h)=>h.daysOverdue-u.daysOverdue)},R7t=()=>nSn().filter(t=>t.isDue),rSn=()=>{const s=ls(),{user:t}=ks();return Nt({mutationFn:async n=>{const{error:r}=await V.from("popby_items").insert({...n,owner_user_id:t==null?void 0:t.id});if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["popby-items"]}),Ma({title:"Popby item created!"})},onError:n=>{Ma({title:"Error creating popby item",description:n.message,variant:"destructive"})}})},aSn=()=>{const s=ls(),{user:t}=ks();return Nt({mutationFn:async n=>{const r=new Date().toISOString(),{error:a}=await V.from("popby_logs").insert({...n,owner_user_id:t==null?void 0:t.id,completed_at:r});if(a)throw a;try{const{data:i}=await V.from("action_types").select("id").ilike("name","Pop-By").eq("active",!0).maybeSingle();i!=null&&i.id&&await V.from("contact_touch_logs").insert({owner_user_id:t==null?void 0:t.id,contact_id:n.contact_id,action_type_id:i.id,notes:n.notes??"Pop-by logged",completed_at:r})}catch(i){console.error("Failed to log corresponding touch for popby",i)}},onSuccess:()=>{s.invalidateQueries({queryKey:["popby-logs"]}),s.invalidateQueries({queryKey:["contact-touch-logs"]}),s.invalidateQueries({queryKey:["contacts-last-touch"]}),Ma({title:"Popby logged!"})},onError:n=>{Ma({title:"Error logging popby",description:n.message,variant:"destructive"})}})},iSn=()=>{const s=ls(),{user:t}=ks();return Nt({mutationFn:async n=>{const{error:r}=await V.from("relationship_type_popby_defaults").upsert({...n,owner_user_id:t==null?void 0:t.id},{onConflict:"relationship_type_id,owner_user_id"});if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["relationship-type-popby-defaults"]}),Ma({title:"Frequency updated!"})},onError:n=>{Ma({title:"Error updating frequency",description:n.message,variant:"destructive"})}})},oSn=()=>{const{data:s}=aTe(30),t=R7t(),n=new Date;n.setDate(n.getDate()-7);const r=(s==null?void 0:s.filter(i=>new Date(i.completed_at)>=n).length)||0,a=(s==null?void 0:s.length)||0;return{thisWeekCount:r,thisMonthCount:a,dueCount:t.length}};function lSn(){const{user:s}=ks();return pt({queryKey:["contact-touch-logs",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await V.from("contact_touch_logs").select("*").order("completed_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function D7t(s){const{data:t}=lSn(),{data:n}=L7t(),{data:r}=zZe(),{data:a}=Pkn();return k.useMemo(()=>{const i=a==null?void 0:a.find(y=>y.contact_id===s.id),l=i?new Date(i.snoozed_until):null,o=np(new Date);if(l&&!Xw(l,o))return{nextTouchDate:l,daysUntil:I2(l,o),status:"snoozed",frequencyDays:90,lastTouchDate:null,snoozedUntil:l};const d=((t==null?void 0:t.filter(y=>y.contact_id===s.id))||[]).sort((y,v)=>new Date(v.completed_at).getTime()-new Date(y.completed_at).getTime())[0],u=d?new Date(d.completed_at):null;let h=90;const m=n==null?void 0:n.find(y=>y.contact_id===s.id&&y.is_active);if(m)h=m.frequency_days;else if(s.tags&&s.tags.length>0){const y=s.tags.map(v=>{const _=r==null?void 0:r.find(j=>j.relationship_type_id===v.relationship_type_id);return _==null?void 0:_.frequency_days}).filter(v=>v!==void 0);y.length>0&&(h=Math.min(...y))}if(!u)return{nextTouchDate:null,daysUntil:null,status:"never-touched",frequencyDays:h,lastTouchDate:null,snoozedUntil:null};const p=wu(np(u),h),g=I2(p,o);let x;return g<0?x="overdue":g<=7?x="due-soon":x="on-track",{nextTouchDate:p,daysUntil:g,status:x,frequencyDays:h,lastTouchDate:u,snoozedUntil:null}},[s,t,n,r,a])}function Syt({contact:s}){const t=D7t(s),r=(()=>{switch(t.status){case"overdue":return{variant:"destructive",icon:Ho,text:`${Math.abs(t.daysUntil)} days overdue`,className:""};case"due-soon":return{variant:"secondary",icon:sa,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:Gr,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:uv,text:`Snoozed until ${Ys(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:ha,text:"Never touched",className:"border-dashed"}}})(),a=r.icon;return e.jsxs(qe,{variant:r.variant,className:Ot("gap-1",r.className),children:[e.jsx(a,{className:"h-3 w-3"}),r.text]})}function cSn({contact:s,onLogTouch:t,onSnooze:n}){const r=D7t(s),a=Lkn(),[i,l]=k.useState(!1),o=()=>{switch(r.status){case"overdue":return"text-destructive";case"due-soon":return"text-amber-600 dark:text-amber-400";case"on-track":return"text-emerald-600 dark:text-emerald-400";case"snoozed":return"text-slate-600 dark:text-slate-400";case"never-touched":return"text-muted-foreground"}},c=()=>{switch(r.status){case"overdue":return e.jsx(Ho,{className:"h-5 w-5 text-destructive"});case"due-soon":return e.jsx(sa,{className:"h-5 w-5 text-amber-600 dark:text-amber-400"});case"on-track":return e.jsx(Gr,{className:"h-5 w-5 text-emerald-600 dark:text-emerald-400"});case"snoozed":return e.jsx(uv,{className:"h-5 w-5 text-slate-600 dark:text-slate-400"});case"never-touched":return e.jsx(ha,{className:"h-5 w-5 text-muted-foreground"})}},d=()=>{switch(r.status){case"overdue":return`${Math.abs(r.daysUntil)} days overdue`;case"due-soon":return r.daysUntil===0?"Due today!":`Due in ${r.daysUntil} days`;case"on-track":return`On track - ${r.daysUntil} days remaining`;case"snoozed":return`Snoozed for ${r.daysUntil} more days`;case"never-touched":return"No touches logged yet"}},u=async()=>{await a.mutateAsync(s.id)};return e.jsxs(e.Fragment,{children:[e.jsxs(we,{children:[e.jsx(Vt,{className:"pb-2",children:e.jsxs(Yt,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(ha,{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:Ot("font-medium",o()),children:d()})]}),r.status==="snoozed"&&r.snoozedUntil&&e.jsxs("div",{className:"text-sm text-muted-foreground",children:[e.jsx("span",{className:"font-medium",children:"Snoozed until:"})," ",Ys(r.snoozedUntil,"MMMM d, yyyy")]}),r.status!=="snoozed"&&r.nextTouchDate&&e.jsxs("div",{className:"text-sm text-muted-foreground",children:[e.jsx("span",{className:"font-medium",children:"Scheduled:"})," ",Ys(r.nextTouchDate,"MMMM d, yyyy")]}),r.lastTouchDate&&e.jsxs("div",{className:"text-sm text-muted-foreground",children:[e.jsx("span",{className:"font-medium",children:"Last touch:"})," ",Ys(r.lastTouchDate,"MMM d, yyyy")]}),r.status!=="snoozed"&&e.jsxs("div",{className:"text-xs text-muted-foreground border-t pt-2",children:["Touch frequency: Every ",r.frequencyDays," days"]}),r.status==="snoozed"&&e.jsxs("div",{className:"flex gap-2 pt-1",children:[e.jsxs($,{size:"sm",variant:"outline",className:"flex-1",onClick:u,disabled:a.isPending,children:[e.jsx(mr,{className:"h-4 w-4 mr-1"}),"Cancel Snooze"]}),t&&e.jsx($,{size:"sm",className:"flex-1",onClick:t,children:"Log Touch"})]}),r.status!=="snoozed"&&e.jsxs("div",{className:"flex gap-2 pt-1",children:[e.jsxs($,{size:"sm",variant:"outline",className:"flex-1",onClick:()=>l(!0),children:[e.jsx(uv,{className:"h-4 w-4 mr-1"}),"Snooze"]}),(r.status==="overdue"||r.status==="due-soon"||r.status==="never-touched")&&t&&e.jsx($,{size:"sm",className:"flex-1",variant:r.status==="overdue"?"default":"outline",onClick:t,children:"Log Touch"})]})]})]}),e.jsx(nTe,{open:i,onOpenChange:l,contactId:s.id,contactName:`${s.first_name} ${s.last_name||""}`.trim()})]})}const QRe=768;function AV(){const[s,t]=k.useState(void 0);return k.useEffect(()=>{const n=window.matchMedia(`(max-width: ${QRe-1}px)`),r=()=>{t(window.innerWidthn.removeEventListener("change",r)},[]),!!s}function dSn(){const{user:s}=ks(),{hasLeadSite:t,leadSite:n}=Tg(),{data:r,isLoading:a}=pt({queryKey:["website-active-contacts",s==null?void 0:s.id,n==null?void 0:n.id],queryFn:async()=>{if(!n)return new Set;const{data:i}=await V.from("lead_site_visitors").select("contact_id").eq("lead_site_id",n.id).not("contact_id","is",null),{data:l}=await V.from("lead_site_consumer_profiles").select("contact_id").eq("lead_site_id",n.id).not("contact_id","is",null),o=new Set;return(i||[]).forEach(c=>{c.contact_id&&o.add(c.contact_id)}),(l||[]).forEach(c=>{c.contact_id&&o.add(c.contact_id)}),o},enabled:!!s&&t,staleTime:5*60*1e3});return{activeContactIds:r??new Set,hasLeadSite:t,isLoading:a}}const uSn={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"}},hSn={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 KBe({score:s,showScore:t=!1,showTooltip:n=!0,size:r="sm",className:a}){const i=uSn[s.status],l=hSn[r],o=e.jsxs("div",{className:Ot("inline-flex items-center rounded-full font-medium",i.bgLightClass,i.textClass,l.badge,l.text,a),children:[e.jsx("span",{className:Ot("rounded-full",i.bgClass,l.dot)}),t?e.jsx("span",{children:s.score}):e.jsx("span",{children:i.label})]});return n?e.jsx(Sk,{children:e.jsxs(Lx,{children:[e.jsx(Rx,{asChild:!0,children:o}),e.jsx(Jg,{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:Ot("font-bold",i.textClass),children:[s.score,"/100"]})]}),e.jsx(ho,{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 mSn=[{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}],bae=s=>{if(!s||!s.trim())return null;const t=s.trim();if(/^\d{4}-\d{2}-\d{2}$/.test(t))return t;const n=t.match(/^(\d{1,2})[\/\-](\d{1,2})(?:[\/\-](\d{2,4}))?$/);if(n){const a=n[1].padStart(2,"0"),i=n[2].padStart(2,"0");let l="2000";n[3]&&(l=n[3].length===2?(parseInt(n[3])>50?"19":"20")+n[3]:n[3]);const o=parseInt(a),c=parseInt(i);if(o>=1&&o<=12&&c>=1&&c<=31)return`${l}-${a}-${i}`}const r=new Date(t);return isNaN(r.getTime())?null:r.toISOString().split("T")[0]},fSn=({open:s,onOpenChange:t,relationshipTypes:n,onSuccess:r})=>{const{user:a}=ks(),{toast:i}=Fi(),l=k.useRef(null),[o,c]=k.useState("upload"),[d,u]=k.useState([]),[h,m]=k.useState([]),[p,g]=k.useState({}),[x,y]=k.useState([]),[v,_]=k.useState([]),[j,C]=k.useState([]),[A,M]=k.useState(""),[I,P]=k.useState(!1),[R,O]=k.useState([]),[B,U]=k.useState(!1),[G,H]=k.useState(null);k.useEffect(()=>{!s||!(a!=null&&a.id)||(async()=>{const{data:Ue}=await V.from("contact_custom_tags").select("id, name, color").eq("owner_user_id",a.id).order("name");_(Ue||[])})()},[s,a==null?void 0:a.id]);const Y=Ue=>{C(Be=>Be.includes(Ue)?Be.filter(je=>je!==Ue):[...Be,Ue])},se=async()=>{const Ue=A.trim();if(!(!Ue||!(a!=null&&a.id))){P(!0);try{const{data:Be,error:je}=await V.from("contact_custom_tags").insert({owner_user_id:a.id,name:Ue}).select("id, name, color").single();if(je)throw je;Be&&(_(Ye=>[...Ye,Be].sort((Ee,Re)=>Ee.name.localeCompare(Re.name))),C(Ye=>[...Ye,Be.id]),M(""))}catch(Be){i({title:"Could not create tag",description:Be.message||"Try a different name.",variant:"destructive"})}finally{P(!1)}}},ee=()=>{c("upload"),u([]),m([]),g({}),y([]),C([]),M(""),O([]),H(null),l.current&&(l.current.value="")},oe=()=>{ee(),t(!1)},me=Ue=>{const Be=Ue.split(` `).map(Fe=>Fe.trim()).filter(Fe=>Fe);if(Be.length===0)return{headers:[],data:[]};const je=Fe=>{const Oe=[];let Ge="",yt=!1;for(let tt=0;tt0&&(Ye[0]=Ye[0].replace(/^\uFEFF/,""));const Ee=new Map,Re=Ye.map((Fe,Oe)=>{let Ge=(Fe||"").trim();Ge||(Ge=`Column ${Oe+1}`);const yt=Ee.get(Ge)||0;return Ee.set(Ge,yt+1),yt===0?Ge:`${Ge} (${yt+1})`}),ke=Be.slice(1).map(je);return{headers:Re,data:ke}},Q=Ue=>{var Ye;const Be=(Ye=Ue.target.files)==null?void 0:Ye[0];if(!Be)return;const je=new FileReader;je.onload=Ee=>{var Ge;const Re=(Ge=Ee.target)==null?void 0:Ge.result,{headers:ke,data:Fe}=me(Re);if(ke.length===0){i({title:"No data found",description:"The CSV file appears to be empty.",variant:"destructive"});return}u(ke),m(Fe);const Oe={};ke.forEach(yt=>{const tt=yt.toLowerCase().replace(/[_\s-]/g,"");tt.includes("firstname")||tt==="first"?Oe.first_name=yt:tt.includes("lastname")||tt==="last"?Oe.last_name=yt:tt.includes("spouse")&&tt.includes("email")?Oe.spouse_email=yt:tt.includes("spouse")||tt.includes("partner")?Oe.spouse_name=yt:tt.includes("email")?Oe.email=yt:tt.includes("phone")||tt.includes("mobile")||tt.includes("cell")?Oe.phone=yt:tt.includes("address")||tt.includes("street")?Oe.address=yt:tt==="city"?Oe.city=yt:tt==="state"||tt==="province"?Oe.state=yt:tt==="zip"||tt==="zipcode"||tt==="postalcode"?Oe.zip=yt:tt.includes("company")||tt.includes("organization")||tt.includes("business")?Oe.company_name=yt:tt.includes("jobtitle")||tt.includes("title")&&!tt.includes("spouse")?Oe.job_title=yt:tt.includes("birthday")||tt.includes("dob")||tt.includes("birthdate")?Oe.birthday=yt:tt.includes("anniversary")||tt.includes("homeanniversary")?Oe.home_anniversary=yt:(tt.includes("notes")||tt.includes("comment"))&&(Oe.notes=yt)}),g(Oe),c("mapping")},je.readAsText(Be)},te=(Ue,Be)=>{g(je=>{if(Be==="none"){const{[Ue]:Ye,...Ee}=je;return Ee}return{...je,[Ue]:Be}})},le=Ue=>{y(Be=>Be.includes(Ue)?Be.filter(je=>je!==Ue):[...Be,Ue])},fe=async()=>{if(!(a!=null&&a.id))return;const{data:Ue}=await V.from("innercircle_contacts").select("id, email, phone").eq("owner_user_id",a.id),Be=new Set((Ue||[]).filter(Ee=>Ee.email).map(Ee=>Ee.email.toLowerCase())),je=new Set((Ue||[]).filter(Ee=>Ee.phone).map(Ee=>Ee.phone.replace(/[^0-9]/g,""))),Ye=h.map(Ee=>{const Re=tt=>{const ut=p[tt];if(!ut)return"";const nt=d.indexOf(ut);return nt>=0?(Ee[nt]||"").trim():""},ke=Re("first_name"),Fe=Re("email"),Oe=Re("phone"),Ge=ke.length>0,yt=!!(Fe&&Be.has(Fe.toLowerCase())||Oe&&je.has(Oe.replace(/[^0-9]/g,"")));return{first_name:ke,last_name:Re("last_name"),email:Fe,phone:Oe,address:Re("address"),city:Re("city"),state:Re("state"),zip:Re("zip"),spouse_name:Re("spouse_name"),spouse_email:Re("spouse_email"),company_name:Re("company_name"),job_title:Re("job_title"),birthday:Re("birthday"),home_anniversary:Re("home_anniversary"),notes:Re("notes"),isValid:Ge,isDuplicate:yt,error:Ge?void 0:"First name is required"}});O(Ye),c("preview")},_e=Ue=>{const Be=Ue.trim().split(/\s+/);return{first_name:Be[0],last_name:Be.length>1?Be.slice(1).join(" "):null}},ve=async()=>{if(!(a!=null&&a.id))return;const Ue=R.filter(Ee=>Ee.isValid);if(Ue.length===0){i({title:"No valid contacts",description:"There are no valid contacts to import.",variant:"destructive"});return}U(!0);let Be=0,je=0,Ye=0;try{for(const Ee of Ue)try{let Re=null;if(Ee.email){const{data:Oe}=await V.from("innercircle_contacts").select("id").eq("owner_user_id",a.id).eq("email",Ee.email).maybeSingle();Re=Oe}if(!Re&&Ee.phone){const Oe=Ee.phone.replace(/[^0-9]/g,""),{data:Ge}=await V.from("innercircle_contacts").select("id, phone").eq("owner_user_id",a.id).not("phone","is",null);if(Ge){const yt=Ge.find(tt=>tt.phone&&tt.phone.replace(/[^0-9]/g,"")===Oe);yt&&(Re={id:yt.id})}}const ke={owner_user_id:a.id,first_name:Ee.first_name,last_name:Ee.last_name||null,email:Ee.email||null,phone:Ee.phone||null,address:Ee.address||null,city:Ee.city||null,state:Ee.state||null,zip:Ee.zip||null,spouse_name:Ee.spouse_name||null,spouse_email:Ee.spouse_email||null,company_name:Ee.company_name||null,job_title:Ee.job_title||null,birthday:bae(Ee.birthday),home_anniversary:bae(Ee.home_anniversary),notes:Ee.notes||null};let Fe=null;if(Re){const{data:Oe}=await V.from("innercircle_contacts").select("*").eq("id",Re.id).single();if(Oe){const Ge={},yt=["last_name","email","phone","address","city","state","zip","spouse_name","spouse_email","company_name","job_title","birthday","home_anniversary","notes"];for(const tt of yt){const ut=Oe[tt],nt=ke[tt];(!ut||ut==="")&&nt&&(Ge[tt]=nt)}Object.keys(Ge).length>0&&await V.from("innercircle_contacts").update(Ge).eq("id",Re.id)}Fe=Re.id,je++}else{const{data:Oe,error:Ge}=await V.from("innercircle_contacts").insert(ke).select("id").single();Ge?(console.error("Insert error for contact:",Ee.first_name,Ge),Ye++):Oe?(Fe=Oe.id,x.length>0&&await V.from("innercircle_contact_tags").insert(x.map(yt=>({contact_id:Oe.id,relationship_type_id:yt}))),Be++):Ye++}if(Fe&&j.length>0&&await V.from("contact_custom_tag_assignments").upsert(j.map(Oe=>({contact_id:Fe,tag_id:Oe})),{onConflict:"contact_id,tag_id",ignoreDuplicates:!0}),Fe&&Ee.spouse_name){const Oe=_e(Ee.spouse_name);let Ge=null;if(Ee.spouse_email){const{data:tt}=await V.from("innercircle_contacts").select("id").eq("owner_user_id",a.id).eq("email",Ee.spouse_email).maybeSingle();Ge=tt}if(!Ge){const{data:tt}=await V.from("innercircle_contacts").select("id").eq("owner_user_id",a.id).eq("first_name",Oe.first_name).eq("last_name",Oe.last_name||Ee.last_name||"").maybeSingle();Ge=tt}let yt=null;if(Ge){yt=Ge.id;const tt=bae(Ee.home_anniversary);tt&&await V.from("innercircle_contacts").update({home_anniversary:tt}).eq("id",Ge.id).is("home_anniversary",null)}else{const{data:tt}=await V.from("innercircle_contacts").insert({owner_user_id:a.id,first_name:Oe.first_name,last_name:Oe.last_name||Ee.last_name||null,email:Ee.spouse_email||null,address:Ee.address||null,city:Ee.city||null,state:Ee.state||null,zip:Ee.zip||null,home_anniversary:bae(Ee.home_anniversary),spouse_name:`${Ee.first_name}${Ee.last_name?" "+Ee.last_name:""}`,spouse_email:Ee.email||null,notes:`Spouse of ${Ee.first_name} ${Ee.last_name||""} (imported via CSV)`.trim()}).select("id").single();tt&&(yt=tt.id,Be++)}yt&&(await V.from("innercircle_contacts").update({spouse_contact_id:yt}).eq("id",Fe),await V.from("innercircle_contacts").update({spouse_contact_id:Fe}).eq("id",yt))}}catch(Re){console.error("Error importing contact:",Re),Ye++}H({created:Be,updated:je,failed:Ye}),c("result"),(Be>0||je>0)&&r(),i({title:"Import Complete",description:`${Be} created, ${je} updated${Ye>0?`, ${Ye} failed`:""}.`})}catch(Ee){console.error("Import error:",Ee),i({title:"Import Failed",description:Ee.message||"Failed to import contacts",variant:"destructive"})}finally{U(!1)}},he=R.filter(Ue=>Ue.isValid).length,Se=R.filter(Ue=>!Ue.isValid).length,Te=R.filter(Ue=>Ue.isValid&&Ue.isDuplicate).length,Ie=he-Te;return e.jsx(zs,{open:s,onOpenChange:oe,children:e.jsxs(Rs,{className:"max-w-3xl max-h-[85vh] overflow-hidden flex flex-col",children:[e.jsxs(Vs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(rk,{className:"h-5 w-5"}),"Import Contacts from CSV"]}),e.jsx(Cr,{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:Q,className:"hidden"}),e.jsx(gi,{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($,{onClick:()=>{var Ue;return(Ue=l.current)==null?void 0:Ue.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($,{variant:"outline",size:"sm",onClick:()=>{const Ue=`First Name,Last Name,Email,Phone,Street Address,City,State,Zip,Spouse Name,Spouse Email,Company,Job Title,Birthday,Home Anniversary,Notes John,Doe,john@example.com,555-123-4567,123 Main St,Austin,TX,78701,Jane Doe,jane@example.com,ABC Realty,Real Estate Agent,1985-06-15,2020-03-22,Met at open house`,Be=new Blob([Ue],{type:"text/csv"}),je=URL.createObjectURL(Be),Ye=document.createElement("a");Ye.href=je,Ye.download="contact_import_template.csv",Ye.click(),URL.revokeObjectURL(je)},children:[e.jsx(ji,{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(re,{className:"text-base font-medium",children:"Map CSV Columns to Contact Fields"}),e.jsx("div",{className:"grid gap-3",children:mSn.map(Ue=>e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs(re,{className:"w-40 text-sm",children:[Ue.label,Ue.required&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsxs(bs,{value:p[Ue.key]||"none",onValueChange:Be=>te(Ue.key,Be),children:[e.jsx(ys,{className:"w-48",children:e.jsx(_s,{placeholder:"Select column..."})}),e.jsxs(vs,{children:[e.jsx(We,{value:"none",children:"-- Not mapped --"}),d.map(Be=>e.jsx(We,{value:Be,children:Be},Be))]})]})]},Ue.key))})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(re,{className:"text-base font-medium",children:"Apply Relationship Types (optional)"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:n.map(Ue=>e.jsx(qe,{variant:x.includes(Ue.id)?"default":"outline",className:"cursor-pointer",onClick:()=>le(Ue.id),children:Ue.name},Ue.id))})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(re,{className:"text-base font-medium",children:"Apply Tags to All Imported Contacts (optional)"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Every contact in this CSV — both newly created and merged duplicates — will receive the selected tags."}),v.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2",children:v.map(Ue=>{const Be=j.includes(Ue.id);return e.jsxs(qe,{variant:Be?"default":"outline",className:"cursor-pointer gap-1",style:Be&&Ue.color?{backgroundColor:Ue.color,borderColor:Ue.color}:void 0,onClick:()=>Y(Ue.id),children:[Ue.name,Be&&e.jsx(mr,{className:"h-3 w-3"})]},Ue.id)})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(be,{placeholder:"Create a new tag (e.g. Open House Oct 2026)",value:A,onChange:Ue=>M(Ue.target.value),onKeyDown:Ue=>{Ue.key==="Enter"&&(Ue.preventDefault(),se())},className:"max-w-xs"}),e.jsxs($,{type:"button",variant:"outline",size:"sm",onClick:se,disabled:!A.trim()||I,children:[I?e.jsx(Jt,{className:"h-4 w-4 animate-spin"}):e.jsx(nn,{className:"h-4 w-4 mr-1"}),"Add Tag"]})]})]}),e.jsx("div",{className:"bg-muted/50 rounded-lg p-3 text-sm",children:e.jsxs("p",{className:"text-muted-foreground",children:["Preview: ",h.length," row(s) found in CSV"]})})]}),o==="preview"&&e.jsxs("div",{className:"flex-1 overflow-hidden flex flex-col space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-4 text-sm flex-wrap",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Gr,{className:"h-4 w-4 text-primary"}),e.jsxs("span",{children:[Ie," new"]})]}),Te>0&&e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(Ho,{className:"h-4 w-4"}),e.jsxs("span",{children:[Te," existing (will merge gaps)"]})]}),Se>0&&e.jsxs("div",{className:"flex items-center gap-2 text-destructive",children:[e.jsx(Ho,{className:"h-4 w-4"}),e.jsxs("span",{children:[Se," invalid"]})]})]}),Te>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(Qa,{children:[e.jsx(Ja,{children:e.jsxs(vn,{className:"bg-muted/30",children:[e.jsx(Dt,{children:"First Name"}),e.jsx(Dt,{children:"Last Name"}),e.jsx(Dt,{children:"Email"}),e.jsx(Dt,{children:"Phone"}),e.jsx(Dt,{children:"Status"})]})}),e.jsx(ei,{children:R.slice(0,100).map((Ue,Be)=>e.jsxs(vn,{children:[e.jsx(_t,{children:Ue.first_name}),e.jsx(_t,{children:Ue.last_name}),e.jsx(_t,{children:Ue.email}),e.jsx(_t,{children:Ue.phone}),e.jsx(_t,{children:Ue.isValid?Ue.isDuplicate?e.jsx(qe,{variant:"outline",className:"bg-accent text-accent-foreground",children:"Merge"}):e.jsx(qe,{variant:"secondary",className:"bg-primary/10 text-primary",children:"New"}):e.jsx(qe,{variant:"destructive",children:Ue.error||"Invalid"})})]},Be))})]}),R.length>100&&e.jsxs("p",{className:"text-sm text-muted-foreground text-center py-2",children:["Showing first 100 of ",R.length," contacts"]})]})]}),o==="result"&&G&&e.jsxs("div",{className:"space-y-4 py-4 text-center",children:[e.jsx(Gr,{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:[G.created," created, ",G.updated," merged"]}),G.failed>0&&e.jsxs("p",{className:"text-destructive",children:[G.failed," failed to import"]})]}),e.jsxs(kr,{children:[o==="upload"&&e.jsx($,{variant:"outline",onClick:oe,children:"Cancel"}),o==="mapping"&&e.jsxs(e.Fragment,{children:[e.jsx($,{variant:"outline",onClick:ee,children:"Back"}),e.jsx($,{onClick:fe,disabled:!p.first_name,children:"Continue"})]}),o==="preview"&&e.jsxs(e.Fragment,{children:[e.jsx($,{variant:"outline",onClick:()=>c("mapping"),children:"Back"}),e.jsx($,{onClick:ve,disabled:B||he===0,children:B?e.jsxs(e.Fragment,{children:[e.jsx(Jt,{className:"mr-2 h-4 w-4 animate-spin"}),"Importing..."]}):`Import ${he} Contact${he!==1?"s":""}`})]}),o==="result"&&e.jsx($,{onClick:oe,children:"Done"})]})]})})};function pSn(){return"contacts"in navigator&&"ContactsManager"in window}function gSn(s){const t=[],n=s.split("BEGIN:VCARD").filter(r=>r.trim());for(const r of n){const a=r.split(/\r?\n/);let i="",l="",o="",c="",d="";for(const u of a){const h=u.replace(/^\s+/,"");if(h.startsWith("N:")||h.startsWith("N;")){const p=h.substring(h.indexOf(":")+1).split(";");l=(p[0]||"").trim(),i=(p[1]||"").trim()}if((h.startsWith("FN:")||h.startsWith("FN;"))&&!i){const p=h.substring(h.indexOf(":")+1).trim().split(" ");i=p[0]||"",l=p.slice(1).join(" ")}(h.startsWith("EMAIL")||h.match(/^item\d+\.EMAIL/i))&&!o&&(o=h.substring(h.indexOf(":")+1).trim()),(h.startsWith("TEL")||h.match(/^item\d+\.TEL/i))&&!c&&(c=h.substring(h.indexOf(":")+1).trim()),(h.startsWith("ADR")||h.match(/^item\d+\.ADR/i))&&!d&&(d=h.substring(h.indexOf(":")+1).split(";").map(g=>g.trim()).filter(Boolean).join(", "))}(i||l)&&t.push({first_name:i,last_name:l,email:o,phone:c,address:d})}return t}function xSn({open:s,onOpenChange:t,onComplete:n}){const{user:r}=ks(),{data:a}=vv(),i=pAe(),l=k.useRef(null),[o,c]=k.useState("choose"),[d,u]=k.useState([]),[h,m]=k.useState(new Set),[p,g]=k.useState(0),[x,y]=k.useState(0),v=pSn(),_=k.useCallback(B=>{if(!a)return B;const U=new Set(a.filter(H=>H.email).map(H=>H.email.toLowerCase())),G=new Set(a.filter(H=>H.phone).map(H=>H.phone.replace(/\D/g,"")));return B.map(H=>{var ee,oe;const Y=(ee=H.email)==null?void 0:ee.toLowerCase(),se=(oe=H.phone)==null?void 0:oe.replace(/\D/g,"");return Y&&U.has(Y)?{...H,isDuplicate:!0,duplicateField:"email"}:se&&se.length>=7&&G.has(se)?{...H,isDuplicate:!0,duplicateField:"phone"}:H})},[a]),j=async()=>{try{const B=["name","email","tel","address"],U=await navigator.contacts.select(B,{multiple:!0});if(!U||U.length===0)return;const G=U.map(se=>{var me,Q,te,le;const oe=(((me=se.name)==null?void 0:me[0])||"").split(" ");return{first_name:oe[0]||"",last_name:oe.slice(1).join(" "),email:((Q=se.email)==null?void 0:Q[0])||"",phone:((te=se.tel)==null?void 0:te[0])||"",address:(le=se.address)!=null&&le[0]?[se.address[0].streetAddress,se.address[0].city,se.address[0].region,se.address[0].postalCode].filter(Boolean).join(", "):""}}),H=_(G);u(H);const Y=new Set;H.forEach((se,ee)=>{se.isDuplicate||Y.add(ee)}),m(Y),c("preview")}catch(B){console.error("Contact Picker error:",B),Ma({title:"Could not access contacts",description:"Please try the file upload option instead.",variant:"destructive"})}},C=B=>{var H;const U=(H=B.target.files)==null?void 0:H[0];if(!U)return;const G=new FileReader;G.onload=Y=>{var Q;const se=(Q=Y.target)==null?void 0:Q.result,ee=gSn(se);if(ee.length===0){Ma({title:"No contacts found",description:"The file didn't contain any valid contacts.",variant:"destructive"});return}const oe=_(ee);u(oe);const me=new Set;oe.forEach((te,le)=>{te.isDuplicate||me.add(le)}),m(me),c("preview")},G.readAsText(U),l.current&&(l.current.value="")},A=async()=>{const B=d.filter((G,H)=>h.has(H));if(B.length===0)return;c("importing");let U=0;for(const G of B)try{await i.mutateAsync({first_name:G.first_name,last_name:G.last_name||void 0,email:G.email||void 0,phone:G.phone||void 0,address:G.address||void 0}),U++,y(Math.round(U/B.length*100))}catch(H){console.error(`Failed to import ${G.first_name} ${G.last_name}:`,H)}g(U),c("done")},M=B=>{m(U=>{const G=new Set(U);return G.has(B)?G.delete(B):G.add(B),G})},I=()=>{h.size===d.length?m(new Set):m(new Set(d.map((B,U)=>U)))},P=B=>{B||(c("choose"),u([]),m(new Set),g(0),y(0),o==="done"&&n()),t(B)},R=d.filter(B=>B.isDuplicate).length,O=h.size;return e.jsx(zs,{open:s,onOpenChange:P,children:e.jsxs(Rs,{className:"sm:max-w-lg max-h-[90vh]",children:[e.jsxs(Vs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(yb,{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(Cr,{children:"Add contacts from your phone directly into Agent OS."})]}),o==="choose"&&e.jsxs("div",{className:"space-y-4 pt-2",children:[v&&e.jsxs($,{onClick:j,className:"w-full h-auto py-4 flex flex-col items-center gap-2",children:[e.jsx(yb,{className:"h-6 w-6"}),e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"font-semibold",children:"Select from Phone"}),e.jsx("div",{className:"text-xs opacity-80",children:"Pick contacts directly from your device"})]})]}),e.jsxs("div",{className:"relative",children:[v&&e.jsx("div",{className:"absolute inset-0 flex items-center",children:e.jsx("span",{className:"w-full border-t"})}),v&&e.jsx("div",{className:"relative flex justify-center text-xs uppercase",children:e.jsx("span",{className:"bg-background px-2 text-muted-foreground",children:"or"})})]}),e.jsxs($,{variant:v?"outline":"default",onClick:()=>{var B;return(B=l.current)==null?void 0:B.click()},className:"w-full h-auto py-4 flex flex-col items-center gap-2",children:[e.jsx(gi,{className:"h-6 w-6"}),e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"font-semibold",children:"Upload Contact File"}),e.jsx("div",{className:"text-xs opacity-80",children:v?"Import a .vcf file exported from your Contacts app":"Export contacts from your phone as a .vcf file, then upload here"})]})]}),e.jsx("input",{ref:l,type:"file",accept:".vcf,.vcard",onChange:C,className:"hidden"}),!v&&e.jsxs("div",{className:"rounded-lg bg-muted p-3 text-sm text-muted-foreground space-y-2",children:[e.jsx("p",{className:"font-medium",children:"How to export contacts:"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-xs",children:"iPhone:"}),e.jsx("p",{className:"text-xs",children:'Open Contacts → select contacts → Share → choose "Export vCard"'})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-xs",children:"Android:"}),e.jsx("p",{className:"text-xs",children:"Open Contacts → Menu → Export → save as .vcf file"})]})]})]}),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",R>0&&e.jsxs("span",{className:"text-amber-600 ml-1",children:["(",R," already exist)"]})]}),e.jsx($,{variant:"ghost",size:"sm",onClick:I,children:h.size===d.length?"Deselect All":"Select All"})]}),e.jsx(Eo,{className:"h-[350px] rounded-md border",children:e.jsx("div",{className:"divide-y",children:d.map((B,U)=>e.jsxs("div",{className:`flex items-start gap-3 p-3 cursor-pointer hover:bg-accent/50 transition-colors ${B.isDuplicate?"opacity-60":""}`,onClick:()=>M(U),children:[e.jsx(Li,{checked:h.has(U),onCheckedChange:()=>M(U),className:"mt-0.5"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"font-medium text-sm truncate",children:[B.first_name," ",B.last_name]}),B.isDuplicate&&e.jsxs(qe,{variant:"secondary",className:"text-[10px] px-1.5 py-0 bg-amber-500/10 text-amber-600 border-amber-200",children:["Exists (",B.duplicateField,")"]})]}),e.jsxs("div",{className:"text-xs text-muted-foreground space-y-0.5 mt-0.5",children:[B.phone&&e.jsx("div",{children:B.phone}),B.email&&e.jsx("div",{className:"truncate",children:B.email})]})]})]},U))})}),e.jsxs("div",{className:"flex items-center justify-between pt-2",children:[e.jsx($,{variant:"ghost",size:"sm",onClick:()=>c("choose"),children:"Back"}),e.jsxs($,{onClick:A,disabled:O===0,children:["Import ",O," Contact",O!==1?"s":""]})]})]}),o==="importing"&&e.jsxs("div",{className:"flex flex-col items-center gap-4 py-8",children:[e.jsx(Jt,{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:[x,"% 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:`${x}%`}})})]}),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(ma,{className:"h-6 w-6 text-emerald-600"})}),e.jsxs("div",{className:"text-center",children:[e.jsxs("p",{className:"font-semibold text-lg",children:[p," contact",p!==1?"s":""," imported!"]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Your contacts are now in Agent OS and ready for touchpoint plans."})]}),e.jsx($,{onClick:()=>P(!1),className:"mt-2",children:"Done"})]})]})})}function ySn(s){return pt({queryKey:["video-share-recipients",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await V.from("video_share_recipients").select("*").eq("video_id",s).order("sent_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function vSn(){const{user:s}=ks();return pt({queryKey:["video-share-stats",s==null?void 0:s.id],queryFn:async()=>{if(!(s!=null&&s.id))return null;const{data:t,error:n}=await V.from("video_share_recipients").select("*").eq("owner_user_id",s.id);if(n)throw n;const r=t;return{totalSent:r.length,totalOpened:r.filter(a=>a.opened_at).length,totalClicked:r.filter(a=>a.clicked_at).length,totalWatched:r.filter(a=>a.watched_at).length,openRate:r.length>0?Math.round(r.filter(a=>a.opened_at).length/r.length*100):0,clickRate:r.length>0?Math.round(r.filter(a=>a.clicked_at).length/r.length*100):0,watchRate:r.length>0?Math.round(r.filter(a=>a.watched_at).length/r.length*100):0}},enabled:!!(s!=null&&s.id)})}function bSn(){const{user:s}=ks();return pt({queryKey:["video-share-history",s==null?void 0:s.id],queryFn:async()=>{if(!(s!=null&&s.id))return[];const{data:t,error:n}=await V.from("video_share_recipients").select(` *, agent_videos!inner(id, title, thumbnail_url, share_token, duration_seconds) `).eq("owner_user_id",s.id).order("sent_at",{ascending:!1}).limit(200);if(n)throw n;return t},enabled:!!(s!=null&&s.id)})}function O7t(){const{user:s}=ks(),t=ls();return Nt({mutationFn:async n=>{if(!(s!=null&&s.id))throw new Error("Not authenticated");const{data:r,error:a}=await V.from("video_share_recipients").insert([{video_id:n.video_id,owner_user_id:s.id,recipient_email:n.recipient_email,recipient_name:n.recipient_name||null,contact_id:n.contact_id||null,sent_via:n.sent_via||"gmail",share_token:"placeholder"}]).select().single();if(a)throw a;return r},onSuccess:n=>{t.invalidateQueries({queryKey:["video-share-recipients",n.video_id]}),t.invalidateQueries({queryKey:["video-share-stats"]}),t.invalidateQueries({queryKey:["video-share-history"]})}})}function F7t(s){return`https://relzejiswnotikjgvjhz.supabase.co/functions/v1/track-video-share?t=${s}&e=open`}function z7t(s){return`https://relzejiswnotikjgvjhz.supabase.co/functions/v1/track-video-share?t=${s}&e=click`}const _Sn=100;function wSn({open:s,onOpenChange:t,contacts:n,isGmailConnected:r,isMassEmailReady:a,onSendComplete:i}){const l=Jn(),o=ai(),c=O7t(),[d,u]=k.useState([]),[h,m]=k.useState(!1),[p,g]=k.useState(""),[x,y]=k.useState(null),[v,_]=k.useState(""),[j,C]=k.useState(""),[A,M]=k.useState(!1),[I,P]=k.useState({done:0,total:0,failed:0}),R=n.filter(ee=>!!ee.email),O=n.length-R.length,B=R.length>_Sn;k.useEffect(()=>{s&&(y(null),g(""),P({done:0,total:0,failed:0}))},[s]),k.useEffect(()=>{!s||!o||(m(!0),V.from("agent_videos").select("id, title, share_token, thumbnail_url, playback_url, duration_seconds, created_at").eq("owner_user_id",o).eq("is_deleted",!1).eq("status","ready").order("created_at",{ascending:!1}).limit(50).then(({data:ee})=>{u(ee||[]),m(!1)}))},[s,o]),k.useEffect(()=>{if(!x)return;const ee=x.title||"a quick video";_(`I recorded a video for you — ${ee}`),C("Hey {{first_name}}! I recorded a quick video just for you. Click below to watch it:")},[x]);const U=d.filter(ee=>!p||(ee.title||"").toLowerCase().includes(p.toLowerCase())),G=(ee,oe)=>{if(!x)return"";const me=x.share_token?`https://video.relevelup.com/share/video/${x.share_token}`:"",Q=x.share_token?`https://video.relevelup.com/thumb/${x.share_token}`:x.thumbnail_url||"",te=x.title||"Video Message",fe=j.replace(/\{\{first_name\}\}/gi,ee).split(/\n\n+/).map(he=>`

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

`).join(""),_e=oe?z7t(oe):me,ve=oe?``:"";return`
`},H=async()=>{if(!x)return;M(!0),P({done:0,total:R.length,failed:0});let ee=0,oe=0;for(const me of R)try{let Q;try{Q=(await c.mutateAsync({video_id:x.id,recipient_email:me.email,recipient_name:`${me.first_name} ${me.last_name||""}`.trim(),contact_id:me.id,sent_via:"gmail"})).share_token}catch(ve){console.warn("Tracking record failed for",me.email,ve)}const te=G(me.first_name,Q),le=v.replace(/\{\{first_name\}\}/gi,me.first_name),{data:fe,error:_e}=await V.functions.invoke("gmail-send",{body:{to:me.email,subject:le,body:te,contactId:me.id}});if(_e||!(fe!=null&&fe.success))throw new Error((fe==null?void 0:fe.error)||(_e==null?void 0:_e.message)||"Send failed");ee+=1}catch(Q){console.error("Failed to send to",me.email,Q),oe+=1}finally{P({done:ee+oe,total:R.length,failed:oe}),await new Promise(Q=>setTimeout(Q,250))}M(!1),oe===0?ae.success(`Video sent to ${ee} ${ee===1?"contact":"contacts"}!`):ae.warning(`Sent to ${ee}, ${oe} failed. Check console for details.`),t(!1),i==null||i()},Y=()=>{if(!x)return;const ee=G("there",void 0);l("/admin/email-campaigns/new",{state:{directRecipients:R.map(oe=>({email:oe.email,name:`${oe.first_name} ${oe.last_name||""}`.trim()})),initialSubject:v,initialBodyHtml:ee}}),t(!1)},se=!!x&&!!v.trim()&&R.length>0&&(B?a:r);return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"sm:max-w-[640px] max-h-[90vh] overflow-y-auto",children:[e.jsxs(Vs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(ia,{className:"h-5 w-5 text-primary"}),"Send Video to ",R.length," ",R.length===1?"Contact":"Contacts"]}),e.jsxs(Cr,{children:[B?e.jsxs("span",{className:"flex items-center gap-1.5 text-amber-600",children:[e.jsx(xm,{className:"h-3.5 w-3.5"}),R.length," recipients — will be sent as a Mass Email campaign"]}):e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(pn,{className:"h-3.5 w-3.5"}),"Sent individually via your connected Gmail"]}),O>0&&e.jsxs("span",{className:"ml-2 text-xs text-muted-foreground",children:["(",O," skipped — no email)"]})]})]}),e.jsxs("div",{className:"space-y-4",children:[B&&!a&&e.jsxs("div",{className:"flex items-start gap-2 p-3 rounded-md bg-destructive/10 text-destructive text-sm",children:[e.jsx(Ho,{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 ",R.length," recipients."]})]}),!B&&!r&&e.jsxs("div",{className:"flex items-start gap-2 p-3 rounded-md bg-destructive/10 text-destructive text-sm",children:[e.jsx(Ho,{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(re,{children:"Choose a video"}),e.jsxs($,{type:"button",variant:"ghost",size:"sm",className:"gap-1",onClick:()=>l("/innercircle/videos/record"),children:[e.jsx(nn,{className:"h-3.5 w-3.5"})," Record new"]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(Yr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search your video library...",value:p,onChange:ee=>g(ee.target.value),className:"pl-10"})]}),e.jsx("div",{className:"max-h-[220px] overflow-y-auto space-y-2 border rounded-md p-2",children:h?e.jsxs(e.Fragment,{children:[e.jsx(fn,{className:"h-14 w-full"}),e.jsx(fn,{className:"h-14 w-full"})]}):U.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."}):U.map(ee=>{const oe=(x==null?void 0:x.id)===ee.id;return e.jsxs("button",{type:"button",onClick:()=>y(ee),className:`w-full flex items-center gap-3 p-2 rounded-md border text-left transition-colors ${oe?"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:[ee.thumbnail_url?e.jsx("img",{src:ee.thumbnail_url,alt:"",className:"w-full h-full object-cover",referrerPolicy:"no-referrer"}):e.jsx(em,{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(pu,{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:ee.title||"Untitled Video"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[ee.duration_seconds?`${Math.round(ee.duration_seconds)}s`:"",ee.created_at?` · ${new Date(ee.created_at).toLocaleDateString()}`:""]})]})]},ee.id)})})]}),e.jsx(Pc,{}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{htmlFor:"bulk-video-subject",children:"Subject"}),e.jsx(be,{id:"bulk-video-subject",value:v,onChange:ee=>_(ee.target.value),placeholder:"I recorded a video for you"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(re,{htmlFor:"bulk-video-message",children:["Personal message ",e.jsxs("span",{className:"text-xs text-muted-foreground",children:["(use ","{{first_name}}"," to personalize)"]})]}),e.jsx(Ls,{id:"bulk-video-message",value:j,onChange:ee=>C(ee.target.value),rows:4,className:"resize-y"})]}),A&&I.total>0&&e.jsxs("div",{className:"p-3 rounded-md bg-muted text-sm",children:["Sending… ",I.done," / ",I.total,I.failed>0&&e.jsxs("span",{className:"text-destructive ml-2",children:["(",I.failed," failed)"]})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),disabled:A,children:"Cancel"}),B?e.jsxs($,{onClick:Y,disabled:!se,className:"gap-2",children:[e.jsx(xm,{className:"h-4 w-4"}),"Continue in Mass Email"]}):e.jsxs($,{onClick:H,disabled:!se||A,className:"gap-2",children:[A?e.jsx(Jt,{className:"h-4 w-4 animate-spin"}):e.jsx(Wr,{className:"h-4 w-4"}),A?"Sending…":`Send to ${R.length}`]})]})]})]})})}function rte(){const s=ai();return pt({queryKey:["drip-campaigns",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await V.from("drip_campaigns").select("*").or(`owner_user_id.eq.${s},is_starter.eq.true`).order("is_starter",{ascending:!1}).order("sort_order",{ascending:!0});if(n)throw n;return t},enabled:!!s})}function jSn(s){return pt({queryKey:["drip-campaign",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await V.from("drip_campaigns").select("*").eq("id",s).maybeSingle();if(n)throw n;return t},enabled:!!s})}function NSn(){const s=ai(),t=ls();return Nt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r,error:a}=await V.from("drip_campaigns").insert({owner_user_id:s,name:n.name,description:n.description??null,category:n.category??"nurture",icon:n.icon??"🌱",cover_color:n.cover_color??"from-emerald-500 to-teal-600",goal:n.goal??null,is_active:!1}).select().single();if(a)throw a;return r},onSuccess:()=>t.invalidateQueries({queryKey:["drip-campaigns"]})})}function B7t(){const s=ls();return Nt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await V.from("drip_campaigns").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["drip-campaigns"]}),s.invalidateQueries({queryKey:["drip-campaign",n.id]})}})}function kSn(){const s=ls();return Nt({mutationFn:async t=>{const{error:n}=await V.from("drip_campaigns").delete().eq("id",t);if(n)throw n},onSuccess:()=>s.invalidateQueries({queryKey:["drip-campaigns"]})})}function BZe(){const s=ai(),t=ls();return Nt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const[{data:r,error:a},{data:i,error:l}]=await Promise.all([V.from("drip_campaigns").select("*").eq("id",n).single(),V.from("drip_campaign_steps").select("*").eq("campaign_id",n).order("step_order")]);if(a)throw a;if(l)throw l;const{data:o,error:c}=await V.from("drip_campaigns").insert({owner_user_id:s,name:r.name,description:r.description,category:r.category,icon:r.icon,cover_color:r.cover_color,goal:r.goal,is_active:!1,is_starter:!1}).select().single();if(c)throw c;if(i&&i.length>0){const d=i.map(h=>({campaign_id:o.id,step_order:h.step_order,channel:h.channel,subject:h.subject,body:h.body,video_url:h.video_url,delay_type:h.delay_type,delay_days:h.delay_days,delay_hours:h.delay_hours,anchor_field:h.anchor_field,anchor_offset_days:h.anchor_offset_days,send_window_start:h.send_window_start,send_window_end:h.send_window_end})),{error:u}=await V.from("drip_campaign_steps").insert(d);if(u)throw u}return o},onSuccess:()=>t.invalidateQueries({queryKey:["drip-campaigns"]})})}function $7t(s){return pt({queryKey:["drip-campaign-steps",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await V.from("drip_campaign_steps").select("*").eq("campaign_id",s).order("step_order",{ascending:!0});if(n)throw n;return t},enabled:!!s})}function SSn(){const s=ls();return Nt({mutationFn:async t=>{const{data:n,error:r}=await V.from("drip_campaign_steps").insert({campaign_id:t.campaign_id,step_order:t.step_order,channel:t.channel??"email",subject:t.subject??"",body:t.body??"",video_url:t.video_url??null,delay_type:t.delay_type??"relative",delay_days:t.delay_days??0,delay_hours:t.delay_hours??0,anchor_field:t.anchor_field??null,anchor_offset_days:t.anchor_offset_days??0}).select().single();if(r)throw r;return n},onSuccess:(t,n)=>s.invalidateQueries({queryKey:["drip-campaign-steps",n.campaign_id]})})}function CSn(){const s=ls();return Nt({mutationFn:async({id:t,campaign_id:n,...r})=>{const{data:a,error:i}=await V.from("drip_campaign_steps").update(r).eq("id",t).select().single();if(i)throw i;return{data:a,campaign_id:n}},onSuccess:t=>s.invalidateQueries({queryKey:["drip-campaign-steps",t.campaign_id]})})}function ASn(){const s=ls();return Nt({mutationFn:async({id:t,campaign_id:n})=>{const{error:r}=await V.from("drip_campaign_steps").delete().eq("id",t);if(r)throw r;return n},onSuccess:t=>s.invalidateQueries({queryKey:["drip-campaign-steps",t]})})}function ESn(s){return pt({queryKey:["campaign-enrollments",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await V.from("drip_campaign_enrollments").select("*, contact:innercircle_contacts(id, first_name, last_name, email)").eq("campaign_id",s).order("enrolled_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function TSn(s){return pt({queryKey:["campaign-enrollment-count",s],queryFn:async()=>{if(!s)return 0;const{count:t,error:n}=await V.from("drip_campaign_enrollments").select("id",{count:"exact",head:!0}).eq("campaign_id",s).eq("status","active");if(n)throw n;return t??0},enabled:!!s,staleTime:3e4})}function $Ze(){const s=ls();return Nt({mutationFn:async({campaignId:t,contactIds:n})=>{const{data:r,error:a}=await V.functions.invoke("enroll-contacts-in-campaign",{body:{campaign_id:t,contact_ids:n}});if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["campaign-enrollments"]}),s.invalidateQueries({queryKey:["contact-campaigns"]})}})}function MSn(){const s=ls();return Nt({mutationFn:async({id:t,status:n})=>{const r={status:n};n==="paused"&&(r.paused_at=new Date().toISOString()),n==="exited"&&(r.exited_at=new Date().toISOString(),r.exit_reason="manual");const{data:a,error:i}=await V.from("drip_campaign_enrollments").update(r).eq("id",t).select().single();if(i)throw i;return a},onSuccess:()=>{s.invalidateQueries({queryKey:["campaign-enrollments"]}),s.invalidateQueries({queryKey:["contact-campaigns"]})}})}const PSn=[{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"}],iTe={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"},ISn={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 LSn({open:s,onOpenChange:t,subject:n,body:r,ownerUserId:a,stepLabel:i}){const[l,o]=k.useState(!1),[c,d]=k.useState(""),[u,h]=k.useState(""),[m,p]=k.useState("desktop"),[g,x]=k.useState(""),[y,v]=k.useState(!1);k.useEffect(()=>{if(!s)return;let j=!1;return(async()=>{var C,A;o(!0);try{const{data:M}=await V.auth.getSession();g||x(((A=(C=M==null?void 0:M.session)==null?void 0:C.user)==null?void 0:A.email)||"");const{data:I,error:P}=await V.functions.invoke("process-drip-campaigns",{body:{action:"preview",subject:n,body:r,owner_user_id:a||void 0}});if(P)throw P;if(j)return;d((I==null?void 0:I.html)||""),h((I==null?void 0:I.subject)||n)}catch{j||ae.error("Could not build preview")}finally{j||o(!1)}})(),()=>{j=!0}},[s,n,r,a]);const _=async()=>{if(g.trim()){v(!0);try{const{data:j,error:C}=await V.functions.invoke("process-drip-campaigns",{body:{action:"test_send",subject:n,body:r,to:g.trim(),owner_user_id:a||void 0}});if(C)throw C;j!=null&&j.success?ae.success(`Test email sent to ${g.trim()}`):ae.error((j==null?void 0:j.error)||"Could not send test email",{duration:1e4})}catch{ae.error("Could not send test email")}finally{v(!1)}}};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"sm:max-w-3xl max-h-[92vh] flex flex-col p-0 gap-0",children:[e.jsxs(Vs,{className:"p-5 pb-3 border-b shrink-0",children:[e.jsxs($s,{children:["Email preview",i?` — ${i}`:""]}),e.jsx(Cr,{children:"Exactly how this email will look when it sends, with sample contact details filled in."})]}),e.jsxs("div",{className:"px-5 py-3 border-b shrink-0 space-y-2",children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Subject"}),e.jsx("div",{className:"text-sm font-medium",children:u||n||"(no subject)"}),e.jsxs("div",{className:"flex items-center gap-1.5 pt-1",children:[e.jsxs($,{variant:m==="desktop"?"secondary":"ghost",size:"sm",className:"h-7 text-xs",onClick:()=>p("desktop"),children:[e.jsx(j2,{className:"h-3.5 w-3.5 mr-1"})," Desktop"]}),e.jsxs($,{variant:m==="mobile"?"secondary":"ghost",size:"sm",className:"h-7 text-xs",onClick:()=>p("mobile"),children:[e.jsx(yb,{className:"h-3.5 w-3.5 mr-1"})," Mobile"]})]})]}),e.jsx("div",{className:"flex-1 overflow-y-auto overscroll-contain bg-muted/30 p-4 min-h-0",children:l?e.jsxs("div",{className:"flex items-center justify-center py-16 text-sm text-muted-foreground",children:[e.jsx(Jt,{className:"h-4 w-4 mr-2 animate-spin"})," Building preview…"]}):e.jsx("div",{className:"mx-auto bg-background rounded-lg overflow-hidden border",style:{maxWidth:m==="mobile"?390:"100%"},children:e.jsx("iframe",{title:"Email preview",srcDoc:c,sandbox:"",className:"w-full",style:{height:620,border:0,background:"#fff"}})})}),e.jsxs("div",{className:"border-t p-4 shrink-0 flex flex-col sm:flex-row sm:items-end gap-3",children:[e.jsxs("div",{className:"flex-1 space-y-1.5",children:[e.jsx(re,{className:"text-xs",children:"Send a test to"}),e.jsx(be,{type:"email",value:g,onChange:j=>x(j.target.value),placeholder:"you@email.com",className:"h-9",onKeyDown:j=>j.key==="Enter"&&_()})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),children:"Close"}),e.jsxs($,{onClick:_,disabled:y||!g.trim(),children:[y?e.jsx(Jt,{className:"h-4 w-4 mr-1.5 animate-spin"}):e.jsx(Wr,{className:"h-4 w-4 mr-1.5"}),"Send test"]})]})]})]})})}function BF({userId:s,onSelect:t,onSelectVideo:n,triggerLabel:r="Library",triggerSize:a="sm",triggerVariant:i="outline",triggerClassName:l}){const[o,c]=k.useState(!1),[d,u]=k.useState([]),[h,m]=k.useState(!1),[p,g]=k.useState("");k.useEffect(()=>{!o||!s||(m(!0),V.from("agent_videos").select("id, title, recipient_name, playback_url, thumbnail_url, created_at, duration_seconds").eq("owner_user_id",s).eq("is_deleted",!1).eq("status","ready").order("created_at",{ascending:!1}).limit(50).then(({data:y})=>{u(y||[]),m(!1)}))},[o,s]);const x=d.filter(y=>!p||(y.title||y.recipient_name||"").toLowerCase().includes(p.toLowerCase()));return e.jsxs(zs,{open:o,onOpenChange:c,children:[e.jsx(yl,{asChild:!0,children:e.jsxs($,{variant:i,size:a,className:l||"gap-1.5 shrink-0",children:[e.jsx(em,{className:"h-3.5 w-3.5"}),r]})}),e.jsxs(Rs,{className:"max-w-lg max-h-[70vh] flex flex-col",children:[e.jsxs(Vs,{children:[e.jsx($s,{children:"Select from Video Library"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Choose a video from your library"})]}),e.jsxs("div",{className:"relative mb-3",children:[e.jsx(Yr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search videos...",value:p,onChange:y=>g(y.target.value),className:"pl-10"})]}),e.jsx("div",{className:"flex-1 overflow-y-auto space-y-2 min-h-0",children:h?e.jsxs(e.Fragment,{children:[e.jsx(fn,{className:"h-16 w-full"}),e.jsx(fn,{className:"h-16 w-full"})]}):x.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"}):x.map(y=>e.jsxs("button",{onClick:()=>{t(y.playback_url||""),n==null||n(y),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:y.thumbnail_url?e.jsx("img",{src:y.thumbnail_url,alt:"",className:"w-full h-full object-cover",referrerPolicy:"no-referrer",onError:v=>{const _=v.currentTarget.parentElement;if(_){v.currentTarget.remove();const j=document.createElement("span");j.innerHTML="🎬",j.className="text-lg",_.appendChild(j)}}}):e.jsx(ia,{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:y.title||y.recipient_name||"Untitled Video"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[y.duration_seconds?`${Math.round(y.duration_seconds)}s`:"",y.created_at?` · ${new Date(y.created_at).toLocaleDateString()}`:""]})]})]},y.id))})]})]})}function RSn(){return pt({queryKey:["video-script-categories"],queryFn:async()=>{const{data:s,error:t}=await V.from("video_script_categories").select("*").order("sort_order");if(t)throw t;return s}})}function DSn(s){return pt({queryKey:["video-scripts",s],queryFn:async()=>{let t=V.from("video_scripts").select("*, category:video_script_categories(*)").eq("is_active",!0).order("title");const{data:n,error:r}=await t;if(r)throw r;return n}})}function OSn(){const{user:s}=ks();return pt({queryKey:["user-video-scripts",s==null?void 0:s.id],queryFn:async()=>{if(!(s!=null&&s.id))return[];const{data:t,error:n}=await V.from("user_video_scripts").select("*, category:video_script_categories(*)").eq("owner_user_id",s.id).order("title");if(n)throw n;return t},enabled:!!(s!=null&&s.id)})}function FSn(){const{user:s}=ks(),t=ls();return Nt({mutationFn:async n=>{if(!(s!=null&&s.id))throw new Error("Not authenticated");const{data:r,error:a}=await V.from("user_video_scripts").insert([{owner_user_id:s.id,source_script_id:n.id,category_id:n.category_id,title:n.title,script_text:n.script_text,tags:n.tags,is_custom:!1}]).select().single();if(a)throw a;return r},onSuccess:()=>{t.invalidateQueries({queryKey:["user-video-scripts"]})}})}function zSn(s){const{user:t}=ks();return pt({queryKey:["agent-videos",t==null?void 0:t.id,s],queryFn:async()=>{if(!(t!=null&&t.id))return[];let n=V.from("agent_videos").select("*, contact:innercircle_contacts(id, first_name, last_name)").eq("owner_user_id",t.id).order("created_at",{ascending:!1});n=n.eq("is_deleted",!1);const{data:r,error:a}=await n;if(a)throw a;return r},enabled:!!(t!=null&&t.id)})}function BSn(s){return pt({queryKey:["agent-video",s],queryFn:async()=>{const{data:t,error:n}=await V.from("agent_videos").select("*, contact:innercircle_contacts(id, first_name, last_name)").eq("id",s).single();if(n)throw n;return t},enabled:!!s})}function o4(){const{user:s}=ks(),t=ls();return Nt({mutationFn:async n=>{if(!(s!=null&&s.id))throw new Error("Not authenticated");const{data:r,error:a}=await V.from("agent_videos").insert([{owner_user_id:s.id,contact_id:n.contact_id,bunny_video_id:n.bunny_video_id,playback_url:n.playback_url,thumbnail_url:n.thumbnail_url,preview_url:n.preview_url,duration_seconds:n.duration_seconds,file_size_mb:n.file_size_mb||0,title:n.title,notes:n.notes,task_id:n.task_id,status:n.status||"processing",touch_type:n.touch_type||"video",page_template:"default",category:n.category||"general"}]).select("*, share_token").single();if(a)throw a;return r},onSuccess:()=>{t.invalidateQueries({queryKey:["agent-videos"]}),t.invalidateQueries({queryKey:["storage-usage"]})}})}function $Sn(){const s=ls();return Nt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await V.from("agent_videos").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:t=>{s.invalidateQueries({queryKey:["agent-videos"]}),s.invalidateQueries({queryKey:["agent-video",t.id]})}})}function USn(){const s=ls();return Nt({mutationFn:async({id:t,bunnyVideoId:n,hardDelete:r=!1})=>{if(console.log("Deleting video:",{id:t,bunnyVideoId:n,hardDelete:r}),n){console.log("Calling bunny-upload delete for videoId:",n);const{data:a,error:i}=await V.functions.invoke("bunny-upload",{body:{action:"delete",videoId:n,isAgentVideo:!0}});i?console.error("Failed to delete from Bunny:",i):console.log("Bunny delete response:",a)}else console.warn("No bunnyVideoId provided, skipping Bunny.net deletion");if(r){console.log("Hard deleting from database:",t);const{error:a}=await V.from("agent_videos").delete().eq("id",t);if(a)throw a}else{console.log("Soft deleting from database:",t);const{error:a}=await V.from("agent_videos").update({is_deleted:!0}).eq("id",t);if(a)throw a}console.log("Video deletion complete")},onSuccess:()=>{s.invalidateQueries({queryKey:["agent-videos"]}),s.invalidateQueries({queryKey:["storage-usage"]})}})}function oTe(){const{user:s}=ks();return pt({queryKey:["storage-usage",s==null?void 0:s.id],queryFn:async()=>{if(!(s!=null&&s.id))return null;const{data:t,error:n}=await V.from("agent_storage_usage").select("*").eq("user_id",s.id).maybeSingle();if(n)throw n;return t||{user_id:s.id,total_storage_mb:0,storage_tier:"basic",max_storage_mb:1024}},enabled:!!(s!=null&&s.id)})}function U7t(){const{data:s,isLoading:t}=oTe(),n=s?s.total_storage_mb0?s.total_storage_mb/s.max_storage_mb*100:0,i=a>=80;return{canRecord:n,remainingMb:r,usagePercent:a,isNearLimit:i,storage:s,isLoading:t}}async function v6(s){const{data:t,error:n}=await V.functions.invoke("bunny-upload",{body:{action:"create",title:s,isAgentVideo:!0}});if(n)throw n;return t}async function b6(s){const{data:t,error:n}=await V.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:s,isAgentVideo:!0}});if(n)throw n;return t}async function D2(s){const{data:t,error:n}=await V.functions.invoke("bunny-upload",{body:{action:"status",videoId:s,isAgentVideo:!0}});if(n)throw n;return t}function qSn(){const{user:s}=ks(),t=ls();return Nt({mutationFn:async({contactId:n,videoId:r,notes:a})=>{if(!(s!=null&&s.id))throw new Error("Not authenticated");const{data:i}=await V.from("action_types").select("id").eq("name","Video").single();if(!i)throw new Error("Video action type not found");const{data:l,error:o}=await V.from("contact_touch_logs").insert([{owner_user_id:s.id,contact_id:n,action_type_id:i.id,notes:a||`Quick Video Touch - Video ID: ${r}`}]).select().single();if(o)throw o;return l},onSuccess:()=>{t.invalidateQueries({queryKey:["contact-touch-logs"]}),t.invalidateQueries({queryKey:["contacts"]})}})}function q7t({open:s,onOpenChange:t,onUploadComplete:n}){const{data:r}=vv(),{data:a}=oTe(),i=o4(),l=k.useRef(null),[o,c]=k.useState(null),[d,u]=k.useState(""),[h,m]=k.useState(""),[p,g]=k.useState(""),[x,y]=k.useState(!1),[v,_]=k.useState(0),[j,C]=k.useState("idle"),A=(a==null?void 0:a.total_storage_mb)||0,I=((a==null?void 0:a.max_storage_mb)||1024)-A,P=U=>{var Y;const G=(Y=U.target.files)==null?void 0:Y[0];if(!G)return;if(!G.type.startsWith("video/")){ae.error("Please select a video file");return}const H=G.size/(1024*1024);if(H>500){ae.error("Video file must be less than 500MB");return}if(H>I){ae.error(`Not enough storage. You have ${I.toFixed(1)} MB remaining.`);return}c(G),d||u(G.name.replace(/\.[^/.]+$/,""))},R=async()=>{if(!o){ae.error("Please select a video file");return}y(!0),_(0),C("creating");try{const{data:U,error:G}=await V.functions.invoke("bunny-upload",{body:{action:"create",title:d||o.name,isAgentVideo:!0}});if(G)throw new Error(G.message);const{videoId:H,libraryId:Y}=U;C("uploading");const{data:se,error:ee}=await V.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:H,isAgentVideo:!0}});if(ee)throw new Error(ee.message);await new Promise((Q,te)=>{const le=new XMLHttpRequest;le.upload.addEventListener("progress",fe=>{if(fe.lengthComputable){const _e=Math.round(fe.loaded/fe.total*100);_(_e)}}),le.addEventListener("load",()=>{le.status>=200&&le.status<300?Q():te(new Error(`Upload failed with status ${le.status}`))}),le.addEventListener("error",()=>te(new Error("Upload failed"))),le.open("PUT",se.uploadUrl),le.setRequestHeader("AccessKey",se.apiKey),le.send(o)}),C("processing");const oe=o.size/(1024*1024),me=`https://iframe.mediadelivery.net/embed/${Y}/${H}`;await i.mutateAsync({bunny_video_id:H,playback_url:me,file_size_mb:oe,title:d||o.name,notes:h||void 0,contact_id:p||void 0,status:"processing",touch_type:"video_upload"}),ae.success("Video uploaded successfully! Processing may take a few minutes."),n==null||n(me),O()}catch(U){console.error("Upload error:",U),ae.error(U instanceof Error?U.message:"Failed to upload video")}finally{y(!1),C("idle")}},O=()=>{x||(c(null),u(""),m(""),g(""),_(0),C("idle"),t(!1))},B=()=>{switch(j){case"creating":return"Preparing upload...";case"uploading":return`Uploading... ${v}%`;case"processing":return"Saving video...";default:return""}};return e.jsx(zs,{open:s,onOpenChange:O,children:e.jsxs(Rs,{className:"sm:max-w-md",children:[e.jsxs(Vs,{children:[e.jsx($s,{children:"Upload Video"}),e.jsx(Cr,{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(re,{children:"Video File"}),o?e.jsxs("div",{className:"flex items-center gap-3 p-3 bg-muted rounded-lg",children:[e.jsx(ia,{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"]})]}),!x&&e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:U=>{U.stopPropagation(),c(null)},children:e.jsx(mr,{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 U;return(U=l.current)==null?void 0:U.click()},children:[e.jsx(gi,{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:P,disabled:x})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"title",children:"Title"}),e.jsx(be,{id:"title",value:d,onChange:U=>u(U.target.value),placeholder:"Enter video title",disabled:x})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Associate with Contact (optional)"}),e.jsxs(bs,{value:p||"__none__",onValueChange:U=>g(U==="__none__"?"":U),disabled:x,children:[e.jsx(ys,{children:e.jsx(_s,{placeholder:"Select a contact"})}),e.jsxs(vs,{children:[e.jsx(We,{value:"__none__",children:"No contact"}),r==null?void 0:r.map(U=>e.jsxs(We,{value:U.id,children:[U.first_name," ",U.last_name||""]},U.id))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"notes",children:"Notes (optional)"}),e.jsx(Ls,{id:"notes",value:h,onChange:U=>m(U.target.value),placeholder:"Add any notes about this video",rows:2,disabled:x})]}),x&&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(Jt,{className:"h-4 w-4 animate-spin"}),e.jsx("span",{children:B()})]}),e.jsx(ho,{value:j==="uploading"?v:j==="processing"?100:10})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:O,disabled:x,children:"Cancel"}),e.jsx($,{onClick:R,disabled:!o||x,children:x?e.jsxs(e.Fragment,{children:[e.jsx(Jt,{className:"h-4 w-4 mr-2 animate-spin"}),"Uploading..."]}):e.jsxs(e.Fragment,{children:[e.jsx(gi,{className:"h-4 w-4 mr-2"}),"Upload Video"]})})]})]})})}const VSn=["🌱","💎","🏠","🔑","📧","💌","🎂","🥂","🤝","⭐","🎉","📞"],HSn={" ":" ","&":"&","<":"<",">":">",""":'"',"'":"'"},Cyt=s=>s?/<\/?[a-z][\s\S]*>/i.test(s)?s.replace(//gi,"").replace(//gi,"").replace(//gi,` `).replace(/<\/p\s*>/gi,` `).replace(/<\/div\s*>/gi,` `).replace(/<\/h[1-6]\s*>/gi,` `).replace(/<\/li\s*>/gi,` `).replace(/]*>/gi,"• ").replace(/<[^>]+>/g,"").replace(/&(nbsp|amp|lt|gt|quot);|'/gi,t=>HSn[t.toLowerCase()]||t).replace(/\n{3,}/g,` `).replace(/[ \t]+\n/g,` `).trim():s:"";function V7t({open:s,onOpenChange:t,campaignId:n}){const[r,a]=k.useState(n??null),[i,l]=k.useState("details");k.useEffect(()=>{a(n??null),l("details")},[n,s]);const o=r,c=!!o,{data:d}=jSn(o||void 0),{data:u,isLoading:h}=$7t(o||void 0),m=NSn(),p=B7t(),g=SSn(),[x,y]=k.useState(""),[v,_]=k.useState(""),[j,C]=k.useState("nurture"),[A,M]=k.useState("🌱"),[I,P]=k.useState("");k.useEffect(()=>{d?(y(d.name),_(d.description||""),C(d.category),M(d.icon),P(d.goal||"")):c||(y(""),_(""),C("nurture"),M("🌱"),P(""))},[d,c,s]);const R=ISn[j],O=async()=>{if(!x.trim()){ae.error("Give your campaign a name");return}try{if(c&&o)await p.mutateAsync({id:o,name:x,description:v,category:j,icon:A,goal:I,cover_color:R}),ae.success("Campaign updated");else{const U=await m.mutateAsync({name:x,description:v,category:j,icon:A,goal:I,cover_color:R});return ae.success("Campaign created — now add your first step!"),a(U.id),l("steps"),U}}catch(U){ae.error(U.message||"Failed to save")}},B=async()=>{if(!o){ae.error("Save the campaign first, then add steps");return}const U=((u==null?void 0:u.length)||0)+1;try{await g.mutateAsync({campaign_id:o,step_order:U,channel:"email",subject:"",body:"",delay_type:"relative",delay_days:U===1?0:2,delay_hours:0})}catch{ae.error("Failed to add step")}};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"max-w-3xl max-h-[90vh] flex flex-col p-0 overflow-hidden",children:[e.jsx("div",{className:`bg-gradient-to-br ${R} 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:A}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx($s,{className:"text-lg font-bold text-white",children:c?"Edit Campaign":"Create New Campaign"}),e.jsx(Cr,{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(ya,{value:i,onValueChange:U=>l(U),className:"flex-1 flex flex-col overflow-hidden min-h-0",children:[e.jsxs(va,{className:"mx-5 mt-4 grid grid-cols-2 w-fit",children:[e.jsx(is,{value:"details",children:"Details"}),e.jsxs(is,{value:"steps",disabled:!c,children:["Steps ",u&&u.length>0&&e.jsx(qe,{variant:"secondary",className:"ml-1.5 text-[10px]",children:u.length})]})]}),e.jsx(cs,{value:"details",className:"flex-1 overflow-y-auto overscroll-contain mt-0 min-h-0 data-[state=inactive]:hidden",children:e.jsx("div",{children:e.jsxs("div",{className:"p-5 space-y-4",children:[e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Campaign Name *"}),e.jsx(be,{value:x,onChange:U=>y(U.target.value),placeholder:"e.g. New Buyer Lead — 7 Touch Nurture",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Description"}),e.jsx(Ls,{value:v,onChange:U=>_(U.target.value),placeholder:"What's this campaign for? When should you use it?",rows:2,className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Goal (optional)"}),e.jsx(be,{value:I,onChange:U=>P(U.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(re,{className:"text-xs",children:"Category"}),e.jsxs(bs,{value:j,onValueChange:U=>C(U),children:[e.jsx(ys,{className:"mt-1",children:e.jsx(_s,{})}),e.jsx(vs,{children:Object.entries(iTe).map(([U,G])=>e.jsx(We,{value:U,children:G},U))})]})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Icon"}),e.jsx("div",{className:"flex gap-1.5 flex-wrap mt-1",children:VSn.map(U=>e.jsx("button",{type:"button",onClick:()=>M(U),className:`h-8 w-8 rounded-md text-lg flex items-center justify-center transition-all ${A===U?"bg-primary/15 ring-2 ring-primary":"hover:bg-muted"}`,children:U},U))})]})]}),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(cs,{value:"steps",className:"flex-1 overflow-y-auto overscroll-contain mt-0 min-h-0 data-[state=inactive]:hidden",children:e.jsx("div",{children:e.jsx("div",{className:"p-5 space-y-3",children:h?e.jsx("div",{className:"text-center text-sm text-muted-foreground py-8",children:"Loading steps…"}):!u||u.length===0?e.jsxs("div",{className:"text-center py-10 border border-dashed rounded-xl",children:[e.jsx(kn,{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($,{size:"sm",onClick:B,disabled:g.isPending,children:[e.jsx(nn,{className:"h-3.5 w-3.5 mr-1.5"})," Add first step"]})]}):e.jsxs(e.Fragment,{children:[u.map((U,G)=>e.jsx(GSn,{step:U,index:G,totalSteps:u.length},U.id)),e.jsxs($,{variant:"outline",size:"sm",onClick:B,disabled:g.isPending,className:"w-full",children:[g.isPending?e.jsx(Jt,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}):e.jsx(nn,{className:"h-3.5 w-3.5 mr-1.5"}),"Add another step"]})]})})})})]}),e.jsxs(kr,{className:"border-t p-4 shrink-0",children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),children:c?"Done":"Cancel"}),e.jsxs($,{onClick:O,disabled:m.isPending||p.isPending,children:[(m.isPending||p.isPending)&&e.jsx(Jt,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}),c?"Save Changes":"Create Campaign"]})]})]})})}function GSn({step:s,index:t,totalSteps:n}){const r=CSn(),a=ASn(),i=ai(),[l,o]=k.useState(!1),[c,d]=k.useState(()=>({...s,body:Cyt(s.body)})),[u,h]=k.useState(!1),[m,p]=k.useState(!1),[g,x]=k.useState(""),[y,v]=k.useState(!1),[_,j]=k.useState(!1);k.useEffect(()=>{d({...s,body:Cyt(s.body)})},[s]);const C=JSON.stringify(c)!==JSON.stringify(s),A=async()=>{h(!0);try{await r.mutateAsync({id:s.id,campaign_id:s.campaign_id,channel:c.channel,subject:c.subject,body:c.body,video_url:c.video_url,delay_type:c.delay_type,delay_days:c.delay_days,delay_hours:c.delay_hours,anchor_field:c.anchor_field,anchor_offset_days:c.anchor_offset_days}),ae.success(`Step ${t+1} saved`)}catch{ae.error("Failed to save step")}finally{h(!1)}},M=async()=>{if(await io(`Delete step ${t+1}?`))try{await a.mutateAsync({id:s.id,campaign_id:s.campaign_id}),ae.success("Step deleted")}catch{ae.error("Failed to delete")}},I=R=>{d({...c,body:c.body+R})},P=()=>{if(c.delay_type==="calendar_anchor"){const O=c.anchor_field==="birthday"?"birthday":"home anniversary",B=c.anchor_offset_days||0;return B===0?`On their ${O}`:B<0?`${Math.abs(B)}d before ${O}`:`${B}d after ${O}`}if(t===0&&!c.delay_days&&!c.delay_hours)return"Sends immediately";const R=[];return c.delay_days&&R.push(`${c.delay_days}d`),c.delay_hours&&R.push(`${c.delay_hours}h`),t===0?`After ${R.join(" ")||"0"}`:`+${R.join(" ")||"0"}`};return e.jsxs("div",{className:"border rounded-lg bg-card overflow-hidden",children:[e.jsxs("div",{className:"flex items-center gap-2 p-3 hover:bg-muted/30 cursor-pointer",onClick:()=>o(!l),children:[e.jsx("div",{className:"h-7 w-7 shrink-0 rounded-full bg-primary/10 text-primary flex items-center justify-center text-xs font-semibold",children:t+1}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[c.delay_type==="calendar_anchor"?e.jsx(ha,{className:"h-3 w-3"}):e.jsx(sa,{className:"h-3 w-3"}),e.jsx("span",{children:P()}),e.jsx("span",{children:"·"}),c.channel==="email"?e.jsx(pn,{className:"h-3 w-3"}):e.jsx(bo,{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(Ny,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(Go,{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(re,{className:"text-xs",children:"Channel"}),e.jsxs(bs,{value:c.channel,onValueChange:R=>d({...c,channel:R}),children:[e.jsx(ys,{className:"mt-1 h-9",children:e.jsx(_s,{})}),e.jsx(vs,{children:e.jsx(We,{value:"email",children:"📧 Email"})})]})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Timing Type"}),e.jsxs(bs,{value:c.delay_type,onValueChange:R=>d({...c,delay_type:R}),children:[e.jsx(ys,{className:"mt-1 h-9",children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"relative",children:"⏱ Relative delay"}),e.jsx(We,{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(re,{className:"text-xs",children:"Days delay"}),e.jsx(be,{type:"number",min:0,value:c.delay_days,onChange:R=>d({...c,delay_days:parseInt(R.target.value)||0}),className:"mt-1 h-9"})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Hours delay"}),e.jsx(be,{type:"number",min:0,max:23,value:c.delay_hours,onChange:R=>d({...c,delay_hours:parseInt(R.target.value)||0}),className:"mt-1 h-9"})]})]}):e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Anchor"}),e.jsxs(bs,{value:c.anchor_field||"birthday",onValueChange:R=>d({...c,anchor_field:R}),children:[e.jsx(ys,{className:"mt-1 h-9",children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"birthday",children:"🎂 Birthday"}),e.jsx(We,{value:"home_anniversary",children:"🏠 Home Anniversary"})]})]})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Offset (days, negative = before)"}),e.jsx(be,{type:"number",value:c.anchor_offset_days||0,onChange:R=>d({...c,anchor_offset_days:parseInt(R.target.value)||0}),className:"mt-1 h-9",placeholder:"0 = on the day, -7 = week before"})]})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Subject Line"}),e.jsx(be,{value:c.subject,onChange:R=>d({...c,subject:R.target.value}),placeholder:"e.g. Quick question about your home search, {{client_first_name}}",className:"mt-1 h-9"})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx(re,{className:"text-xs",children:"Email Body"}),e.jsxs("span",{className:"text-[10px] text-muted-foreground",children:[c.body.length," chars"]})]}),e.jsx(Ls,{value:c.body,onChange:R=>d({...c,body:R.target.value}),placeholder:`Hi {{client_first_name}}, I wanted to reach out and...`,rows:6,className:"mt-1 font-mono text-xs"}),e.jsxs("div",{className:"flex flex-wrap gap-1 mt-2",children:[e.jsx("span",{className:"text-[10px] text-muted-foreground mr-1",children:"Insert:"}),PSn.map(R=>e.jsx("button",{type:"button",onClick:()=>I(R.key),className:"text-[10px] px-1.5 py-0.5 rounded bg-primary/10 text-primary hover:bg-primary/20",children:R.label},R.key))]})]}),e.jsxs("div",{children:[e.jsx(re,{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(ia,{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($,{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(BF,{userId:i||void 0,onSelect:R=>d({...c,video_url:R}),triggerSize:"sm",triggerClassName:"gap-1.5 flex-1 min-w-[120px]"}),e.jsxs($,{variant:"outline",size:"sm",className:"gap-1 text-xs flex-1 min-w-[120px]",onClick:()=>v(!0),children:[e.jsx(gi,{className:"h-3 w-3"})," Upload"]}),e.jsxs($,{variant:"ghost",size:"sm",className:"gap-1 text-xs text-muted-foreground flex-1 min-w-[120px]",onClick:()=>{x(""),p(!0)},children:[e.jsx(od,{className:"h-3 w-3"})," Paste URL"]}),e.jsx(q7t,{open:y,onOpenChange:v,onUploadComplete:R=>d({...c,video_url:R})}),e.jsx(zs,{open:m,onOpenChange:p,children:e.jsxs(Rs,{className:"sm:max-w-md",children:[e.jsxs(Vs,{children:[e.jsx($s,{children:"Add video URL"}),e.jsx(Cr,{children:"Paste a YouTube, Loom, or direct video URL."})]}),e.jsx(be,{value:g,onChange:R=>x(R.target.value),placeholder:"https://...",autoFocus:!0,onKeyDown:R=>{R.key==="Enter"&&g.trim()&&(d({...c,video_url:g.trim()}),p(!1))}}),e.jsxs(kr,{children:[e.jsx($,{variant:"ghost",onClick:()=>p(!1),children:"Cancel"}),e.jsx($,{disabled:!g.trim(),onClick:()=>{d({...c,video_url:g.trim()}),p(!1)},children:"Add video"})]})]})})]})]}),e.jsxs("div",{className:"flex items-center justify-between pt-2 border-t",children:[e.jsxs($,{variant:"ghost",size:"sm",onClick:M,className:"text-destructive hover:text-destructive",children:[e.jsx(Un,{className:"h-3.5 w-3.5 mr-1"})," Delete step"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[c.channel==="email"&&e.jsxs($,{variant:"outline",size:"sm",onClick:()=>j(!0),children:[e.jsx(ba,{className:"h-3.5 w-3.5 mr-1.5"})," Preview"]}),e.jsxs($,{size:"sm",onClick:A,disabled:!C||u,children:[u&&e.jsx(Jt,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}),"Save step"]})]})]}),e.jsx(LSn,{open:_,onOpenChange:j,subject:c.subject||"",body:c.body||"",ownerUserId:i,stepLabel:`Step ${t+1}`})]})]})}function WSn({open:s,onOpenChange:t,contactIds:n,onSuccess:r}){const{data:a,isLoading:i}=rte(),l=$Ze(),[o,c]=k.useState(""),[d,u]=k.useState(null),[h,m]=k.useState(!1),p=(a||[]).filter(y=>!y.is_starter),g=p.filter(y=>y.name.toLowerCase().includes(o.toLowerCase())||(y.description||"").toLowerCase().includes(o.toLowerCase())),x=async()=>{if(d)try{const y=await l.mutateAsync({campaignId:d,contactIds:n}),v=[`${y.enrolled} enrolled`];y.skipped>0&&v.push(`${y.skipped} skipped`),y.errors>0&&v.push(`${y.errors} errors`),ae.success(v.join(" · ")),t(!1),u(null),r==null||r()}catch(y){ae.error(y.message||"Failed to enroll contacts")}};return e.jsxs(zs,{open:s,onOpenChange:t,children:[e.jsxs(Rs,{className:"max-w-md",children:[e.jsxs(Vs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(kn,{className:"h-4 w-4 text-primary"}),"Enroll in Drip Campaign"]}),e.jsxs(Cr,{children:[n.length," contact",n.length!==1?"s":""," will be added to the selected campaign. Already-enrolled contacts will be skipped."]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Yr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(be,{placeholder:"Search campaigns...",value:o,onChange:y=>c(y.target.value),className:"pl-9 h-9"})]}),e.jsx(Eo,{className:"h-[320px] -mx-1 px-1",children:i?e.jsx("div",{className:"text-center py-8 text-sm text-muted-foreground",children:"Loading..."}):g.length===0?e.jsx("div",{className:"text-center py-8",children:p.length===0?e.jsxs(e.Fragment,{children:[e.jsx(kn,{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($,{size:"sm",onClick:()=>m(!0),children:[e.jsx(nn,{className:"h-3.5 w-3.5 mr-1.5"})," Create campaign"]})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"No campaigns match your search."})}):e.jsx("div",{className:"space-y-1.5",children:g.map(y=>e.jsxs("button",{onClick:()=>u(y.id),className:`w-full flex items-start gap-3 p-3 rounded-lg border text-left transition-all ${d===y.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 ${y.cover_color} flex items-center justify-center text-lg`,children:y.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:y.name}),y.is_active&&e.jsx(qe,{variant:"outline",className:"text-[9px] bg-emerald-500/10 text-emerald-600 border-emerald-200 px-1 py-0",children:"Active"})]}),y.description&&e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2 mt-0.5",children:y.description})]}),d===y.id&&e.jsx(ma,{className:"h-4 w-4 text-primary shrink-0 mt-1"})]},y.id))})})]}),e.jsxs(kr,{className:"gap-2 sm:gap-2",children:[p.length>0&&e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>m(!0),className:"mr-auto text-xs",children:[e.jsx(nn,{className:"h-3.5 w-3.5 mr-1"})," New campaign"]}),e.jsx($,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs($,{onClick:x,disabled:!d||l.isPending,children:[l.isPending&&e.jsx(Jt,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}),"Enroll ",n.length," contact",n.length!==1?"s":""]})]})]}),e.jsx(V7t,{open:h,onOpenChange:m})]})}function KSn({selectedIds:s,contacts:t,onClearSelection:n,onSendToLeadPond:r,showLeadPondAction:a,onTransfer:i,showTransferAction:l}){const o=Jn(),{data:c}=vj(),d=yWe(),u=ls(),{isGmailConnected:h}=dx(),{isReady:m}=NV(),{data:p}=kV(),g=_Ze(),x=WFt(),[y,v]=k.useState(!1),[_,j]=k.useState(!1),[C,A]=k.useState(!1),[M,I]=k.useState(!1),[P,R]=k.useState(!1),[O,B]=k.useState(""),U=s.size;if(U===0)return null;const G=async Q=>{v(!0);try{const le=Array.from(s).map(_e=>({contact_id:_e,relationship_type_id:Q})),{error:fe}=await V.from("innercircle_contact_tags").upsert(le,{onConflict:"contact_id,relationship_type_id",ignoreDuplicates:!0});if(fe)throw fe;u.invalidateQueries({queryKey:["innercircle-contacts"]}),u.invalidateQueries({queryKey:["innercircle-contact-counts"]}),Ma({title:`Assigned type to ${U} contacts`}),n()}catch(te){Ma({title:"Error assigning type",description:te.message,variant:"destructive"})}finally{v(!1)}},H=async Q=>{v(!0);try{const te=Array.from(s);for(const le of te)try{await x.mutateAsync({contactId:le,tagId:Q})}catch{}u.invalidateQueries({queryKey:["all-contact-custom-tags"]}),Ma({title:`Tagged ${U} contacts`}),R(!1),B("")}catch(te){Ma({title:"Error adding tags",description:te.message,variant:"destructive"})}finally{v(!1)}},Y=async()=>{if(O.trim()){v(!0);try{const Q=await g.mutateAsync({name:O.trim()});await H(Q.id)}catch(Q){Ma({title:"Error creating tag",description:Q.message,variant:"destructive"}),v(!1)}}},se=(p==null?void 0:p.filter(Q=>Q.name.toLowerCase().includes(O.toLowerCase())))||[],ee=p==null?void 0:p.find(Q=>Q.name.toLowerCase()===O.trim().toLowerCase()),oe=()=>{const Q=t.filter(Se=>s.has(Se.id)),te=["First Name","Last Name","Email","Phone","Address","Birthday","Home Anniversary","Notes","Relationship Types"],le=Q.map(Se=>{var Te;return[Se.first_name,Se.last_name||"",Se.email||"",Se.phone||"",Se.address||"",Se.birthday||"",Se.home_anniversary||"",Se.notes||"",((Te=Se.tags)==null?void 0:Te.map(Ie=>{var Ue;return(Ue=Ie.relationship_type)==null?void 0:Ue.name}).join("; "))||""]}),fe=[te.join(","),...le.map(Se=>Se.map(Te=>`"${(Te||"").replace(/"/g,'""')}"`).join(","))].join(` `),_e=new Blob([fe],{type:"text/csv"}),ve=URL.createObjectURL(_e),he=document.createElement("a");he.href=ve,he.download=`contacts-export-${new Date().toISOString().slice(0,10)}.csv`,he.click(),URL.revokeObjectURL(ve),Ma({title:`Exported ${U} contacts`})},me=async()=>{if(await io(`Are you sure you want to delete ${U} contacts? This cannot be undone.`)){v(!0);try{const Q=Array.from(s);for(const te of Q)await d.mutateAsync(te);n()}catch(Q){Ma({title:"Error deleting contacts",description:Q.message,variant:"destructive"})}finally{v(!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(qe,{variant:"secondary",className:"font-semibold",children:[U," selected"]}),e.jsxs(bs,{onValueChange:G,disabled:y,children:[e.jsx(ys,{className:"w-[180px] h-8",children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(kg,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"text-sm",children:"Assign Type"})]})}),e.jsx(vs,{children:c==null?void 0:c.filter(Q=>Q.active).map(Q=>e.jsx(We,{value:Q.id,children:Q.name},Q.id))})]}),e.jsxs(Xc,{open:P,onOpenChange:R,children:[e.jsx(Qc,{asChild:!0,children:e.jsxs($,{variant:"outline",size:"sm",disabled:y,children:[e.jsx(nn,{className:"h-3.5 w-3.5 mr-1"}),"Add Tag"]})}),e.jsxs(Bc,{className:"w-56 p-2",align:"start",children:[e.jsx(be,{placeholder:"Search or create tag...",value:O,onChange:Q=>B(Q.target.value),onKeyDown:Q=>{Q.key==="Enter"&&O.trim()&&!ee?(Q.preventDefault(),Y()):Q.key==="Enter"&&ee&&(Q.preventDefault(),H(ee.id))},className:"h-8 text-sm mb-2"}),e.jsxs("div",{className:"max-h-[200px] overflow-y-auto space-y-0.5",children:[se.map(Q=>e.jsxs("button",{onClick:()=>H(Q.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:Q.color}}),e.jsx("span",{className:"flex-1 text-left truncate",children:Q.name})]},Q.id)),O.trim()&&!ee&&e.jsxs("button",{onClick:Y,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(nn,{className:"h-3.5 w-3.5"}),'Create "',O.trim(),'"']}),se.length===0&&!O.trim()&&e.jsx("p",{className:"text-xs text-muted-foreground text-center py-2",children:"Type to create a tag"})]})]})]}),h&&e.jsxs($,{variant:"outline",size:"sm",onClick:()=>j(!0),disabled:y,children:[e.jsx(pn,{className:"h-3.5 w-3.5 mr-1"}),"Email"]}),m&&e.jsxs($,{variant:"outline",size:"sm",onClick:()=>{const Q=Array.from(s).join(",");o(`/admin/email-campaigns/new?contactIds=${Q}`)},disabled:y,children:[e.jsx(xm,{className:"h-3.5 w-3.5 mr-1"}),"Mass Email"]}),e.jsxs($,{variant:"outline",size:"sm",onClick:()=>A(!0),disabled:y,children:[e.jsx(ia,{className:"h-3.5 w-3.5 mr-1"}),"Send Video"]}),e.jsxs($,{variant:"outline",size:"sm",onClick:()=>I(!0),disabled:y,children:[e.jsx(kn,{className:"h-3.5 w-3.5 mr-1"}),"Enroll in Campaign"]}),a&&r&&e.jsxs($,{variant:"outline",size:"sm",onClick:()=>r(Array.from(s)),disabled:y,children:[e.jsx(pb,{className:"h-3.5 w-3.5 mr-1"}),"Send to Lead Pond"]}),l&&i&&e.jsxs($,{variant:"outline",size:"sm",onClick:()=>i(Array.from(s)),disabled:y,children:[e.jsx(N5,{className:"h-3.5 w-3.5 mr-1"}),"Transfer"]}),e.jsxs($,{variant:"outline",size:"sm",onClick:oe,disabled:y,children:[e.jsx(ji,{className:"h-3.5 w-3.5 mr-1"}),"Export"]}),e.jsxs($,{variant:"outline",size:"sm",onClick:me,disabled:y,className:"text-destructive hover:text-destructive",children:[e.jsx(Un,{className:"h-3.5 w-3.5 mr-1"}),"Delete"]}),e.jsxs($,{variant:"ghost",size:"sm",onClick:n,className:"ml-auto",children:[e.jsx(mr,{className:"h-3.5 w-3.5 mr-1"}),"Clear"]})]}),e.jsx(WSn,{open:M,onOpenChange:I,contactIds:Array.from(s),onSuccess:n}),e.jsx(W2,{open:_,onOpenChange:j,bulkContacts:Array.from(s).map(Q=>{const te=t.find(le=>le.id===Q);return te?{id:te.id,first_name:te.first_name,last_name:te.last_name,email:te.email||""}:null}).filter(Q=>Q!==null&&Q.email!==""),onSendComplete:()=>{j(!1),n()}}),e.jsx(wSn,{open:C,onOpenChange:A,contacts:Array.from(s).map(Q=>t.find(te=>te.id===Q)).filter(Q=>!!Q).map(Q=>({id:Q.id,first_name:Q.first_name,last_name:Q.last_name,email:Q.email})),isGmailConnected:!!h,isMassEmailReady:!!m,onSendComplete:()=>{A(!1),n()}})]})}function Ayt({contact:s,onEdit:t,onDelete:n,onSnooze:r,onSendToLeadPond:a,showLeadPondAction:i,onTransfer:l,showTransferAction:o}){const c=Jn(),{isReady:d}=NV(),u=`${s.first_name} ${s.last_name||""}`.trim();return e.jsxs(Au,{children:[e.jsx(Eu,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:h=>h.stopPropagation(),children:e.jsx(u0,{className:"h-4 w-4"})})}),e.jsxs(gu,{align:"end",onClick:h=>h.stopPropagation(),children:[e.jsxs(Pa,{onClick:()=>c(`/mission-control/contacts/${s.id}?tab=activity&action=log`),children:[e.jsx(ka,{className:"h-4 w-4 mr-2"}),"Log Touch"]}),e.jsxs(Pa,{onClick:()=>c(`/mission-control/video?contactId=${s.id}`),children:[e.jsx(ia,{className:"h-4 w-4 mr-2"}),"Send Video"]}),e.jsxs(Pa,{onClick:()=>c(`/mission-control/popbys?contactId=${s.id}`),children:[e.jsx(Si,{className:"h-4 w-4 mr-2"}),"Schedule Pop-by"]}),d&&s.email&&e.jsxs(Pa,{onClick:()=>c(`/admin/email-campaigns/new?contactIds=${s.id}`),children:[e.jsx(pn,{className:"h-4 w-4 mr-2"}),"Mass Email"]}),e.jsxs(Pa,{onClick:()=>r(s.id,u),children:[e.jsx(uv,{className:"h-4 w-4 mr-2"}),"Snooze"]}),i&&a&&e.jsxs(Pa,{onClick:()=>a(s.id),children:[e.jsx(pb,{className:"h-4 w-4 mr-2"}),"Send to Lead Pond"]}),o&&l&&e.jsxs(Pa,{onClick:()=>l(s.id),children:[e.jsx(N5,{className:"h-4 w-4 mr-2"}),"Transfer to Team Member"]}),e.jsxs(Pa,{onClick:()=>t(s),children:[e.jsx(ui,{className:"h-4 w-4 mr-2"}),"Edit"]}),e.jsxs(Pa,{onClick:()=>n(s.id),className:"text-destructive focus:text-destructive",children:[e.jsx(Un,{className:"h-4 w-4 mr-2"}),"Delete"]})]})]})}function Eyt({currentFilters:s,currentSortBy:t,onApplySmartList:n}){const{data:r}=wZe(),a=KFt(),i=YFt(),[l,o]=k.useState(!1),[c,d]=k.useState(""),u=s.search||s.type&&s.type!=="all"||s.status&&s.status!=="all"||s.behavior&&Object.values(s.behavior).some(m=>m!==void 0&&m!==!1),h=async()=>{c.trim()&&(await a.mutateAsync({name:c.trim(),filters:s,sort_by:t}),d(""),o(!1))};return e.jsxs(e.Fragment,{children:[e.jsxs(Au,{children:[e.jsx(Eu,{asChild:!0,children:e.jsxs($,{variant:"outline",size:"sm",className:"gap-1.5",children:[e.jsx(v2,{className:"h-3.5 w-3.5"}),"Smart Filters",r&&r.length>0&&e.jsx(qe,{variant:"secondary",className:"h-5 px-1.5 text-[10px]",children:r.length}),e.jsx(Go,{className:"h-3.5 w-3.5"})]})}),e.jsxs(gu,{align:"start",className:"w-56",children:[r&&r.length>0?e.jsxs(e.Fragment,{children:[r.map(m=>e.jsxs(Pa,{className:"flex items-center justify-between group",children:[e.jsx("span",{className:"flex-1 cursor-pointer",onClick:()=>n(m.filters,m.sort_by),children:m.name}),e.jsx($,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 group-hover:opacity-100",onClick:p=>{p.stopPropagation(),i.mutate(m.id)},children:e.jsx(Un,{className:"h-3 w-3 text-destructive"})})]},m.id)),e.jsx(j0,{})]}):e.jsx(Pa,{disabled:!0,className:"text-muted-foreground text-xs",children:"No saved filters yet"}),u&&e.jsxs(Pa,{onClick:()=>o(!0),children:[e.jsx(BT,{className:"h-4 w-4 mr-2"}),"Save Current Filter"]})]})]}),e.jsx(zs,{open:l,onOpenChange:o,children:e.jsxs(Rs,{className:"max-w-sm",children:[e.jsx(Vs,{children:e.jsx($s,{children:"Save Smart Filter"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsx(be,{placeholder:"e.g. Buyers in 40205",value:c,onChange:m=>d(m.target.value),onKeyDown:m=>m.key==="Enter"&&h(),autoFocus:!0}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx($,{variant:"outline",onClick:()=>o(!1),children:"Cancel"}),e.jsx($,{onClick:h,disabled:!c.trim()||a.isPending,children:"Save"})]})]})]})})]})}const M4e=[{value:1,label:"January"},{value:2,label:"February"},{value:3,label:"March"},{value:4,label:"April"},{value:5,label:"May"},{value:6,label:"June"},{value:7,label:"July"},{value:8,label:"August"},{value:9,label:"September"},{value:10,label:"October"},{value:11,label:"November"},{value:12,label:"December"}],H7t=[{value:"home_anniversary",label:"Home anniversary"},{value:"wedding_anniversary",label:"Wedding anniversary"}],YSn=[{value:"today",label:"Today"},{value:"7d",label:"Last 7 days"},{value:"30d",label:"Last 30 days"},{value:"90d",label:"Last 90 days"},{value:"never",label:"Never active"}];function ZSn({open:s,onOpenChange:t,hasLeadSite:n,behavior:r,onApply:a,selectedType:i,onSelectedTypeChange:l,relationshipTypes:o}){const[c,d]=k.useState(r),[u,h]=k.useState(n?"behavior":"contact"),{data:m}=NF();k.useEffect(()=>{s&&d(r)},[s,r]);const p=x=>d(y=>({...y,...x})),g=Object.entries(c).filter(([,x])=>x!==void 0&&x!==!1&&x!=="").length;return e.jsx(D_,{open:s,onOpenChange:t,children:e.jsxs(Mb,{side:"right",className:"w-full sm:max-w-lg overflow-y-auto",children:[e.jsxs(xj,{children:[e.jsxs(yj,{className:"flex items-center gap-2",children:[e.jsx(kn,{className:"h-4 w-4 text-primary"}),"Advanced Filters"]}),e.jsx(hee,{children:"Slice your database by website activity, contact details, and engagement."})]}),e.jsxs(ya,{value:u,onValueChange:x=>h(x),className:"mt-4",children:[e.jsxs(va,{className:"grid w-full grid-cols-3",children:[e.jsxs(is,{value:"contact",className:"gap-1.5",children:[e.jsx(Xn,{className:"h-3.5 w-3.5"})," Contact"]}),e.jsxs(is,{value:"behavior",disabled:!n,className:"gap-1.5",children:[e.jsx(zp,{className:"h-3.5 w-3.5"})," Behavior"]}),e.jsx(is,{value:"engagement",children:"Engagement"})]}),e.jsxs(cs,{value:"contact",className:"space-y-6 mt-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Contact Type"}),e.jsxs(bs,{value:i,onValueChange:l,children:[e.jsx(ys,{children:e.jsx(_s,{placeholder:"All types"})}),e.jsxs(vs,{children:[e.jsx(We,{value:"all",children:"All Types"}),o==null?void 0:o.map(x=>e.jsx(We,{value:x.id,children:x.name},x.id))]})]})]}),e.jsxs(X4,{title:"Contact Info Present",children:[e.jsx($v,{label:"Has email",checked:c.hasEmail===!0,onChange:x=>p({hasEmail:x||void 0})}),e.jsx($v,{label:"Has phone",checked:c.hasPhone===!0,onChange:x=>p({hasPhone:x||void 0})}),e.jsx($v,{label:"Has address",checked:c.hasAddress===!0,onChange:x=>p({hasAddress:x||void 0})}),e.jsx($v,{label:"Has birthday",checked:c.hasBirthday===!0,onChange:x=>p({hasBirthday:x||void 0})}),e.jsx($v,{label:"Has spouse",checked:c.hasSpouse===!0,onChange:x=>p({hasSpouse:x||void 0})}),e.jsx($v,{label:"Has company / job",checked:c.hasCompany===!0,onChange:x=>p({hasCompany:x||void 0})}),e.jsx($v,{label:"Has notes",checked:c.hasNotes===!0,onChange:x=>p({hasNotes:x||void 0})})]}),e.jsxs(X4,{title:"Location",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:[e.jsx(JRe,{label:"City",value:c.city||"",onChange:x=>p({city:x||void 0}),placeholder:"Any city"}),e.jsx(JRe,{label:"State",value:c.state||"",onChange:x=>p({state:x||void 0}),placeholder:"Any state"})]}),e.jsx(JRe,{label:"ZIP / Postal",value:c.zip||"",onChange:x=>p({zip:x||void 0}),placeholder:"Any ZIP"})]}),e.jsxs(X4,{title:"Important Dates",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Birthday month"}),e.jsxs(bs,{value:c.birthdayMonth?String(c.birthdayMonth):"all",onValueChange:x=>p({birthdayMonth:x==="all"?void 0:Number(x)}),children:[e.jsx(ys,{children:e.jsx(_s,{placeholder:"Any month"})}),e.jsxs(vs,{children:[e.jsx(We,{value:"all",children:"Any month"}),M4e.map(x=>e.jsx(We,{value:String(x.value),children:x.label},x.value))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Anniversary month"}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:[e.jsxs(bs,{value:c.anniversaryField||"home_anniversary",onValueChange:x=>p({anniversaryField:x}),children:[e.jsx(ys,{children:e.jsx(_s,{placeholder:"Field"})}),e.jsx(vs,{children:H7t.map(x=>e.jsx(We,{value:x.value,children:x.label},x.value))})]}),e.jsxs(bs,{value:c.anniversaryMonth?String(c.anniversaryMonth):"all",onValueChange:x=>p({anniversaryMonth:x==="all"?void 0:Number(x)}),children:[e.jsx(ys,{children:e.jsx(_s,{placeholder:"Any month"})}),e.jsxs(vs,{children:[e.jsx(We,{value:"all",children:"Any month"}),M4e.map(x=>e.jsx(We,{value:String(x.value),children:x.label},x.value))]})]})]})]})]}),e.jsx(X4,{title:"Date Added",children:e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:[e.jsx(Tyt,{label:"From",value:c.dateAddedFrom,onChange:x=>p({dateAddedFrom:x||void 0})}),e.jsx(Tyt,{label:"To",value:c.dateAddedTo,onChange:x=>p({dateAddedTo:x||void 0})})]})}),e.jsx(X4,{title:"Lead Source",children:e.jsxs(bs,{value:c.leadSourceId||"all",onValueChange:x=>p({leadSourceId:x==="all"?void 0:x}),children:[e.jsx(ys,{children:e.jsx(_s,{placeholder:"All sources"})}),e.jsxs(vs,{children:[e.jsx(We,{value:"all",children:"All sources"}),e.jsx(We,{value:"none",children:"No source"}),m==null?void 0:m.map(x=>e.jsx(We,{value:x.id,children:x.name},x.id))]})]})})]}),e.jsx(cs,{value:"behavior",className:"space-y-6 mt-4",children:n?e.jsxs(e.Fragment,{children:[e.jsxs(X4,{title:"Last Active On Site",children:[e.jsx(m_,{value:c.lastActive||"",onValueChange:x=>p({lastActive:x||void 0}),className:"grid grid-cols-2 gap-2",children:YSn.map(x=>e.jsxs("label",{className:"flex items-center gap-2 rounded-md border px-3 py-2 cursor-pointer hover:bg-accent",children:[e.jsx(Yh,{value:x.value}),e.jsx("span",{className:"text-sm",children:x.label})]},x.value))}),c.lastActive&&e.jsx($,{variant:"ghost",size:"sm",className:"mt-1 h-7 px-2 text-xs",onClick:()=>p({lastActive:void 0}),children:"Clear"})]}),e.jsxs(X4,{title:"Registration",children:[e.jsx($v,{label:"Registered on lead site",checked:c.registered==="yes",onChange:x=>p({registered:x?"yes":void 0})}),e.jsx($v,{label:"Anonymous visitors only",checked:c.registered==="no",onChange:x=>p({registered:x?"no":void 0})})]}),e.jsxs(X4,{title:"Property Activity",children:[e.jsx($v,{label:"Viewed any listing",checked:c.viewedListing==="any",onChange:x=>p({viewedListing:x?"any":void 0})}),e.jsx($v,{label:"Hot buyer — 3+ views in last 7 days",checked:c.viewedListing==="multiple7d",onChange:x=>p({viewedListing:x?"multiple7d":void 0})}),e.jsx($v,{label:"Saved a property",checked:!!c.savedProperty,onChange:x=>p({savedProperty:x||void 0})}),e.jsx($v,{label:"Has an active saved search / alert",checked:!!c.hasSavedSearch,onChange:x=>p({hasSavedSearch:x||void 0})})]}),e.jsxs(X4,{title:"Requests",children:[e.jsx($v,{label:"Requested a showing / asked a question",checked:!!c.requestedShowing,onChange:x=>p({requestedShowing:x||void 0})}),e.jsx($v,{label:"Requested a home valuation",checked:!!c.requestedValuation,onChange:x=>p({requestedValuation:x||void 0})})]})]}):e.jsx("div",{className:"rounded-md border border-dashed p-4 text-sm text-muted-foreground",children:"Connect a Lead Site with MLS to unlock website behavior filters."})}),e.jsxs(cs,{value:"engagement",className:"space-y-4 mt-4",children:[e.jsx($v,{label:"Any website activity",checked:!!c.websiteActiveOnly,onChange:x=>p({websiteActiveOnly:x||void 0})}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"More engagement filters (last emailed, awaiting response, past-due tasks) are in the pipeline."})]})]}),e.jsxs(bCt,{className:"mt-6 flex-row gap-2 sm:justify-between",children:[e.jsx($,{variant:"ghost",onClick:()=>d({}),disabled:g===0,children:"Clear behavior filters"}),e.jsx($,{onClick:()=>{a(c),t(!1)},children:"Apply"})]})]})})}function X4({title:s,children:t}){return e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:s}),e.jsx("div",{className:"space-y-2",children:t})]})}function $v({label:s,checked:t,onChange:n}){return e.jsxs("div",{className:"flex items-center justify-between rounded-md border px-3 py-2",children:[e.jsx("span",{className:"text-sm",children:s}),e.jsx(On,{checked:t,onCheckedChange:n})]})}function JRe({label:s,value:t,onChange:n,placeholder:r}){return e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:s}),e.jsxs("div",{className:"relative",children:[e.jsx(be,{value:t,onChange:a=>n(a.target.value),placeholder:r,className:"h-8"}),t&&e.jsx("button",{onClick:()=>n(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground",children:e.jsx(mr,{className:"h-3 w-3"})})]})]})}function Tyt({label:s,value:t,onChange:n}){const[r,a]=k.useState(!1),i=t?Mp(t):void 0;return e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:s}),e.jsxs(Xc,{open:r,onOpenChange:a,children:[e.jsx(Qc,{asChild:!0,children:e.jsxs($,{variant:"outline",className:Ot("w-full justify-start text-left font-normal h-8",!i&&"text-muted-foreground"),children:[e.jsx(ha,{className:"mr-2 h-3.5 w-3.5"}),i?Ys(i,"MMM d, yyyy"):e.jsx("span",{children:"Pick a date"})]})}),e.jsx(Bc,{className:"w-auto p-0",align:"start",children:e.jsx(vb,{mode:"single",selected:i,onSelect:l=>{n(l?Ys(l,"yyyy-MM-dd"):void 0),a(!1)},initialFocus:!0})})]})]})}function XSn({behavior:s,onRemove:t,onClearAll:n}){const r=QSn(s);return r.length===0?null:e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[r.map(({key:a,label:i})=>e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full bg-primary/10 text-primary text-xs px-2.5 py-1",children:[i,e.jsx("button",{onClick:()=>t(a),className:"hover:bg-primary/20 rounded-full h-4 w-4 inline-flex items-center justify-center","aria-label":`Remove ${i}`,children:"×"})]},a)),e.jsx("button",{onClick:n,className:"text-xs text-primary underline underline-offset-2 hover:no-underline",children:"Clear"})]})}function QSn(s){var n;const t=[];if(s.lastActive){const r={today:"Active today","7d":"Active last 7 days","30d":"Active last 30 days","90d":"Active last 90 days",never:"Never active"};t.push({key:"lastActive",label:r[s.lastActive]})}if(s.registered==="yes"&&t.push({key:"registered",label:"Registered"}),s.registered==="no"&&t.push({key:"registered",label:"Anonymous visitor"}),s.viewedListing==="any"&&t.push({key:"viewedListing",label:"Viewed a listing"}),s.viewedListing==="multiple7d"&&t.push({key:"viewedListing",label:"Hot buyer (3+ views/7d)"}),s.savedProperty&&t.push({key:"savedProperty",label:"Saved a property"}),s.hasSavedSearch&&t.push({key:"hasSavedSearch",label:"Active saved search"}),s.requestedShowing&&t.push({key:"requestedShowing",label:"Requested showing/question"}),s.requestedValuation&&t.push({key:"requestedValuation",label:"Requested valuation"}),s.websiteActiveOnly&&t.push({key:"websiteActiveOnly",label:"Any website activity"}),s.hasEmail&&t.push({key:"hasEmail",label:"Has email"}),s.hasPhone&&t.push({key:"hasPhone",label:"Has phone"}),s.hasAddress&&t.push({key:"hasAddress",label:"Has address"}),s.hasBirthday&&t.push({key:"hasBirthday",label:"Has birthday"}),s.hasSpouse&&t.push({key:"hasSpouse",label:"Has spouse"}),s.hasCompany&&t.push({key:"hasCompany",label:"Has company / job"}),s.hasNotes&&t.push({key:"hasNotes",label:"Has notes"}),s.city&&t.push({key:"city",label:`City: ${s.city}`}),s.state&&t.push({key:"state",label:`State: ${s.state}`}),s.zip&&t.push({key:"zip",label:`ZIP: ${s.zip}`}),s.birthdayMonth){const r=M4e.find(a=>a.value===s.birthdayMonth);t.push({key:"birthdayMonth",label:`Birthday in ${(r==null?void 0:r.label)||s.birthdayMonth}`})}if(s.anniversaryMonth){const r=M4e.find(i=>i.value===s.anniversaryMonth),a=((n=H7t.find(i=>i.value===(s.anniversaryField||"home_anniversary")))==null?void 0:n.label)||"Anniversary";t.push({key:"anniversaryMonth",label:`${a} in ${(r==null?void 0:r.label)||s.anniversaryMonth}`})}return s.dateAddedFrom&&t.push({key:"dateAddedFrom",label:`Added on/after ${Ys(Mp(s.dateAddedFrom),"MMM d, yyyy")}`}),s.dateAddedTo&&t.push({key:"dateAddedTo",label:`Added on/before ${Ys(Mp(s.dateAddedTo),"MMM d, yyyy")}`}),s.leadSourceId&&t.push({key:"leadSourceId",label:s.leadSourceId==="none"?"No lead source":"Lead source"}),t}async function o9(s){const n=[];for(let r=0;r<50;r++){const{data:a,error:i}=await s(r*1e3,r*1e3+1e3-1);if(i)throw i;const l=a||[];if(n.push(...l),l.length<1e3)break}return n}function RG(){return{lastActiveAt:null,registered:!1,propertyViewCount:0,propertyViewCount7d:0,savedListingCount:0,activeSavedSearchCount:0,showingRequests:0,valuationRequests:0,viewedCities:[],viewedZips:[]}}function JSn(){const{user:s}=ks(),{leadSite:t,hasLeadSite:n}=Tg(),{data:r,isLoading:a}=pt({queryKey:["contact-behavior-summary",s==null?void 0:s.id,t==null?void 0:t.id],queryFn:async()=>{const i=new Map;if(!t)return i;const l=(v,_)=>{const j=i.get(v)||RG();i.set(v,{...j,..._})},o=await o9((v,_)=>V.from("lead_site_visitors").select("id, contact_id, last_seen_at, email").eq("lead_site_id",t.id).not("contact_id","is",null).range(v,_)),c=new Map,d=new Map;o.forEach(v=>{if(!v.contact_id)return;c.set(v.id,v.contact_id),v.email&&d.set(v.email.toLowerCase(),v.contact_id);const _=i.get(v.contact_id);(!_||!_.lastActiveAt||v.last_seen_at>_.lastActiveAt)&&l(v.contact_id,{lastActiveAt:v.last_seen_at})});const u=await o9((v,_)=>V.from("lead_site_consumer_profiles").select("contact_id, user_id").eq("lead_site_id",t.id).not("contact_id","is",null).range(v,_)),h=new Map;u.forEach(v=>{v.contact_id&&(h.set(v.user_id,v.contact_id),l(v.contact_id,{registered:!0}))});const m=new Date(Date.now()-7*24*60*60*1e3).toISOString();return(await o9((v,_)=>V.from("lead_site_property_views").select("visitor_id, viewed_at, property_address").eq("lead_site_id",t.id).not("visitor_id","is",null).range(v,_))).forEach(v=>{const _=v.visitor_id?c.get(v.visitor_id):null;if(!_)return;const j=i.get(_)||RG();j.propertyViewCount+=1,v.viewed_at>=m&&(j.propertyViewCount7d+=1),i.set(_,j)}),(await o9((v,_)=>V.from("lead_site_saved_listings").select("user_id, mls_number").eq("lead_site_id",t.id).range(v,_))).forEach(v=>{const _=h.get(v.user_id);if(!_)return;const j=i.get(_)||RG();j.savedListingCount+=1,i.set(_,j)}),(await o9((v,_)=>V.from("lead_site_saved_searches").select("user_id").eq("lead_site_id",t.id).eq("is_active",!0).range(v,_))).forEach(v=>{const _=h.get(v.user_id);if(!_)return;const j=i.get(_)||RG();j.activeSavedSearchCount+=1,i.set(_,j)}),(await o9((v,_)=>V.from("lead_site_leads").select("email, lead_type").eq("lead_site_id",t.id).not("email","is",null).range(v,_))).forEach(v=>{if(!v.email)return;const _=d.get(v.email.toLowerCase());if(!_)return;const j=i.get(_)||RG(),C=(v.lead_type||"").toLowerCase();(C.includes("showing")||C.includes("question")||C==="contact")&&(j.showingRequests+=1),(C.includes("valuation")||C.includes("cma")||C.includes("home_value"))&&(j.valuationRequests+=1),i.set(_,j)}),i},enabled:!!s&&n,staleTime:5*60*1e3});return{behaviorMap:r??new Map,hasLeadSite:n,isLoading:a}}const G7t="innercircle_geocode_cache_v1";function e5n(){try{return JSON.parse(localStorage.getItem(G7t)||"{}")}catch{return{}}}function t5n(s){try{localStorage.setItem(G7t,JSON.stringify(s))}catch{}}function s5n(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 n5n({open:s,onOpenChange:t,contacts:n,onCitySelect:r}){const a=k.useRef(null),i=k.useRef(null),[l,o]=k.useState(""),[c,d]=k.useState(!0),[u,h]=k.useState([]),[m,p]=k.useState({done:0,total:0}),[g,x]=k.useState(!1),[y,v]=k.useState("heat");k.useEffect(()=>{if(!s)return;let j=!1;return(async()=>{d(!0);const{data:C}=await V.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle();j||(o((C==null?void 0:C.value)||""),d(!1))})(),()=>{j=!0}},[s]),k.useEffect(()=>{if(!s||!l)return;let j=!1;return(async()=>{const A=e5n(),M=n.map(H=>({c:H,addr:s5n(H)})).filter(H=>H.addr),I=[],P=[];for(const{c:H,addr:Y}of M){const se=A[Y];se!==null&&(se?I.push({id:H.id,name:`${H.first_name||""} ${H.last_name||""}`.trim(),city:H.city||null,state:H.state||null,zip:H.zip||H.zip_code||null,lat:se.lat,lng:se.lng}):P.push({c:H,addr:Y}))}if(j||h(I),p({done:I.length,total:M.length}),P.length===0)return;x(!0);const R=6;let O=0;const B={...A},U=[...I],G=async()=>{var H;for(;O{j=!0}},[s,l,n]);const _=k.useMemo(()=>{const j=new Map;for(const C of n){const A=(C.city||"").trim();if(!A)continue;const M=(C.state||"").trim()||null,I=`${A.toLowerCase()}|${M||""}`,P=j.get(I);P?P.count++:j.set(I,{city:A,state:M,count:1})}return Array.from(j.values()).sort((C,A)=>A.count-C.count)},[n]);return k.useEffect(()=>{if(!(!s||!l||!a.current||i.current))return Td.accessToken=l,i.current=new Td.Map({container:a.current,style:"mapbox://styles/mapbox/light-v11",center:[-98.5795,39.8283],zoom:3.5}),i.current.addControl(new Td.NavigationControl,"top-right"),()=>{var j;(j=i.current)==null||j.remove(),i.current=null}},[s,l]),k.useEffect(()=>{const j=i.current;if(!j||u.length===0)return;const C=()=>{const M={type:"FeatureCollection",features:u.map(P=>({type:"Feature",properties:{id:P.id,name:P.name},geometry:{type:"Point",coordinates:[P.lng,P.lat]}}))},I=j.getSource("contacts-src");if(I?I.setData(M):(j.addSource("contacts-src",{type:"geojson",data:M}),j.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]}}),j.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}}),j.on("click","contacts-points",P=>{var B;const R=(B=P.features)==null?void 0:B[0];if(!R)return;const O=R.geometry.coordinates.slice();new Td.Popup({offset:12}).setLngLat(O).setHTML(`
${R.properties.name||"Contact"}
`).addTo(j)}),j.on("mouseenter","contacts-points",()=>{j.getCanvas().style.cursor="pointer"}),j.on("mouseleave","contacts-points",()=>{j.getCanvas().style.cursor=""})),j.getLayer("contacts-heat")&&j.setLayoutProperty("contacts-heat","visibility",y==="heat"?"visible":"none"),j.getLayer("contacts-points")&&(j.setPaintProperty("contacts-points","circle-opacity",y==="points"?.9:0),j.setLayoutProperty("contacts-points","visibility","visible")),u.length>0&&!j._fitDone){const P=new Td.LngLatBounds;u.forEach(R=>P.extend([R.lng,R.lat]));try{j.fitBounds(P,{padding:60,maxZoom:11,duration:600}),j._fitDone=!0}catch{}}};j.isStyleLoaded()?C():j.once("load",C)},[u,y]),e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"max-w-6xl w-[95vw] h-[90vh] p-0 flex flex-col",children:[e.jsx(Vs,{className:"p-4 pb-2 border-b",children:e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(iu,{className:"h-5 w-5 text-orange-500"}),"Geographic Heat Map",e.jsxs(qe,{variant:"secondary",className:"ml-2",children:[u.length," mapped · ",_.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(Jt,{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($,{size:"sm",variant:y==="heat"?"default":"ghost",onClick:()=>v("heat"),className:"h-8",children:[e.jsx(iu,{className:"h-3.5 w-3.5 mr-1"})," Heat"]}),e.jsxs($,{size:"sm",variant:y==="points"?"default":"ghost",onClick:()=>v("points"),className:"h-8",children:[e.jsx(Wz,{className:"h-3.5 w-3.5 mr-1"})," Pins"]})]}),g&&e.jsxs("div",{className:"bg-background/95 backdrop-blur rounded-md shadow-md border px-2.5 py-1.5 text-xs flex items-center gap-2",children:[e.jsx(Jt,{className:"h-3 w-3 animate-spin"}),"Mapping ",m.done," / ",m.total]})]})]}):e.jsxs("div",{className:"h-full flex flex-col items-center justify-center gap-3 p-6 text-center",children:[e.jsx(Ho,{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(Si,{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(Eo,{className:"flex-1",children:e.jsxs("div",{className:"p-2 space-y-1.5",children:[_.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."}),_.slice(0,50).map((j,C)=>{var I;const A=((I=_[0])==null?void 0:I.count)||1,M=j.count/A*100;return e.jsx(we,{className:"cursor-pointer hover:border-primary transition-colors overflow-hidden",onClick:()=>{r==null||r(j.city,j.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:`${M}%`}}),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:[j.city,j.state?`, ${j.state}`:""]}),e.jsx("div",{className:"text-[10px] text-muted-foreground",children:C===0?"🔥 Hottest market":`Rank #${C+1}`})]}),e.jsx(qe,{variant:"secondary",className:"shrink-0",children:j.count})]})]})},`${j.city}-${j.state}-${C}`)})]})})]})]})]})})}function OR(s){if(!s)return null;try{const t=s.split(/[-/T]/);if(t.length<3)return null;const n=parseInt(t[1],10)-1,r=parseInt(t[2],10);if(isNaN(n)||isNaN(r))return null;const a=new Date;a.setHours(0,0,0,0);let i=new Date(a.getFullYear(),n,r);return i.setHours(0,0,0,0),in)return null;const a=t==="birthday"?"🎂":"🏡",i=r===0?t==="birthday"?"Birthday today!":"Anniversary today!":r===1?t==="birthday"?"Birthday tomorrow":"Anniversary tomorrow":`${a} in ${r}d`;return{emoji:a,label:i,daysUntil:r}}function Myt({birthday:s,homeAnniversary:t,weddingAnniversary:n,className:r,contactId:a,contactName:i,contactAddress:l}){const o=Jn(),c=eDe(s,"birthday",7),d=eDe(t,"anniversary",7),u=eDe(n||null,"anniversary",7);if(!c&&!d&&!u)return null;const h=(m,p,g)=>{g.stopPropagation();const x=new URLSearchParams;a&&x.set("contactId",a),i&&x.set("name",i),l&&x.set("address",l),(m==="home_anniversary"||m==="wedding_anniversary")&&p&&x.set("date",p),x.set("cardType",m),o(`/mission-control/card-studio?${x.toString()}`)};return e.jsxs("div",{className:Ot("flex flex-wrap gap-1",r),children:[c&&e.jsxs("div",{className:"flex items-center gap-0.5",children:[e.jsx(qe,{variant:"secondary",className:Ot("text-[10px] gap-0.5 font-medium",c.daysUntil===0?"bg-pink-100 text-pink-700 dark:bg-pink-900/30 dark:text-pink-400 animate-pulse":"bg-pink-50 text-pink-600 dark:bg-pink-900/20 dark:text-pink-400"),children:c.label}),a&&e.jsxs("button",{onClick:m=>h("birthday",s,m),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(pn,{className:"h-2.5 w-2.5"}),"Send Card"]})]}),d&&e.jsxs("div",{className:"flex items-center gap-0.5",children:[e.jsx(qe,{variant:"secondary",className:Ot("text-[10px] gap-0.5 font-medium",d.daysUntil===0?"bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400 animate-pulse":"bg-blue-50 text-blue-600 dark:bg-blue-900/20 dark:text-blue-400"),children:d.label}),a&&e.jsxs("button",{onClick:m=>h("home_anniversary",t,m),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(pn,{className:"h-2.5 w-2.5"}),"Send Card"]})]}),u&&e.jsxs("div",{className:"flex items-center gap-0.5",children:[e.jsxs(qe,{variant:"secondary",className:Ot("text-[10px] gap-0.5 font-medium",u.daysUntil===0?"bg-rose-100 text-rose-700 dark:bg-rose-900/30 dark:text-rose-400 animate-pulse":"bg-rose-50 text-rose-600 dark:bg-rose-900/20 dark:text-rose-400"),children:["💍 ",u.label.replace(/^[^\w]+/,"")]}),a&&e.jsxs("button",{onClick:m=>h("wedding_anniversary",n||null,m),className:"inline-flex items-center gap-0.5 px-1.5 py-0.5 rounded-full text-[9px] font-semibold bg-rose-500/15 text-rose-600 dark:text-rose-400 hover:bg-rose-500/25 transition-colors",title:"Send a wedding anniversary card",children:[e.jsx(pn,{className:"h-2.5 w-2.5"}),"Send Card"]})]})]})}function Pyt({deal:s}){if(!s||!s.stage)return null;const{stage:t}=s;return e.jsxs(qe,{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 Iyt({count:s,className:t}){return!s||s<=0?null:e.jsxs(qe,{variant:"outline",className:Ot("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(sM,{className:"h-2.5 w-2.5"}),s===1?"In drip":`${s} drips`]})}function r5n(){const s=ai();return pt({queryKey:["contacts-campaign-counts",s],queryFn:async()=>{if(!s)return{};const{data:t,error:n}=await V.from("drip_campaign_enrollments").select("contact_id, status").eq("owner_user_id",s).eq("status","active");if(n)throw n;const r={};return(t||[]).forEach(a=>{a.contact_id&&(r[a.contact_id]=(r[a.contact_id]||0)+1)}),r},enabled:!!s,staleTime:6e4})}function a5n(){const s=ai();return pt({queryKey:["contact-deals-map",s],queryFn:async()=>{const{data:t,error:n}=await V.from("deal_pipeline").select(` id, deal_name, contact_id, deal_type, expected_price, sale_price, stage:deal_pipeline_stages(id, name, color, icon, is_won_stage, is_lost_stage) `).not("contact_id","is",null);if(n)throw n;const r={};return(t||[]).forEach(a=>{a.contact_id&&!r[a.contact_id]&&(r[a.contact_id]=a)}),r},enabled:!!s})}const i5n="#6366F1";function Lyt(s,t){return`color-mix(in srgb, ${s} ${t}%, transparent)`}function o5n(s){return`color-mix(in oklab, ${s} 78%, hsl(var(--foreground)))`}function W7t({label:s,color:t,className:n,onClick:r,title:a}){const i=t||i5n,l=r?"button":"span";return e.jsxs(l,{type:r?"button":void 0,onClick:r,title:a??s,style:{backgroundColor:Lyt(i,14),color:o5n(i),boxShadow:`inset 0 0 0 1px ${Lyt(i,22)}`},className:Ot("inline-flex h-6 max-w-[140px] items-center gap-1.5 rounded-full px-2.5 text-[11px] font-medium leading-none",r&&"transition-transform hover:scale-[1.03]",n),children:[e.jsx("span",{className:"h-1.5 w-1.5 shrink-0 rounded-full",style:{backgroundColor:i},"aria-hidden":!0}),e.jsx("span",{className:"truncate",children:s})]})}function l5n({tags:s,max:t=2,className:n}){const[r,a]=k.useState(!1);if(!s||s.length===0)return null;const i=r?s:s.slice(0,t),l=s.length-i.length;return e.jsxs("div",{className:Ot("flex flex-wrap items-center gap-1.5",n),children:[i.map(o=>{var c,d;return e.jsx(W7t,{label:((c=o.tag)==null?void 0:c.name)||"Tag",color:(d=o.tag)==null?void 0:d.color},o.tag_id)}),l>0&&e.jsxs("button",{type:"button",onClick:o=>{o.stopPropagation(),a(!0)},className:"inline-flex h-6 items-center rounded-full bg-muted px-2 text-[11px] font-medium leading-none text-muted-foreground transition-colors hover:bg-accent hover:text-foreground",children:["+",l]})]})}function Ryt({contactId:s,compact:t=!1}){const{data:n}=kV(),{data:r}=Ybn(s),a=_Ze(),i=WFt(),l=Qbn(),[o,c]=k.useState(!1),[d,u]=k.useState(""),h=k.useRef(null),m=new Set((r==null?void 0:r.map(v=>v.tag_id))||[]),p=(n==null?void 0:n.filter(v=>v.name.toLowerCase().includes(d.toLowerCase())))||[],g=n==null?void 0:n.find(v=>v.name.toLowerCase()===d.trim().toLowerCase()),x=async v=>{m.has(v.id)?await l.mutateAsync({contactId:s,tagId:v.id}):await i.mutateAsync({contactId:s,tagId:v.id})},y=async()=>{if(!(!d.trim()||g))try{const v=await a.mutateAsync({name:d.trim()});await i.mutateAsync({contactId:s,tagId:v.id}),u("")}catch{}};return e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[r==null?void 0:r.map(v=>{var _,j,C;return e.jsxs(qe,{variant:"outline",className:"text-xs gap-1 pr-1",style:{borderColor:((_=v.tag)==null?void 0:_.color)||"#6366F1",color:((j=v.tag)==null?void 0:j.color)||"#6366F1"},children:[e.jsx(kg,{className:"h-2.5 w-2.5"}),(C=v.tag)==null?void 0:C.name,e.jsx("button",{onClick:A=>{A.stopPropagation(),l.mutate({contactId:s,tagId:v.tag_id})},className:"ml-0.5 rounded-full hover:bg-accent p-0.5",children:e.jsx(mr,{className:"h-2.5 w-2.5"})})]},v.id)}),e.jsxs(Xc,{open:o,onOpenChange:c,children:[e.jsx(Qc,{asChild:!0,children:e.jsxs($,{variant:"ghost",size:"sm",className:t?"h-6 w-6 p-0":"h-6 px-2 text-xs",onClick:v=>v.stopPropagation(),children:[e.jsx(nn,{className:"h-3 w-3"}),!t&&e.jsx("span",{className:"ml-1",children:"Tag"})]})}),e.jsxs(Bc,{className:"w-56 p-2",align:"start",onClick:v=>v.stopPropagation(),children:[e.jsx(be,{ref:h,placeholder:"Search or create tag...",value:d,onChange:v=>u(v.target.value),onKeyDown:v=>{v.key==="Enter"&&d.trim()&&!g?(v.preventDefault(),y()):v.key==="Enter"&&g&&!m.has(g.id)&&(v.preventDefault(),x(g))},className:"h-8 text-sm mb-2"}),e.jsxs("div",{className:"max-h-[200px] overflow-y-auto space-y-0.5",children:[p.map(v=>e.jsxs("button",{onClick:()=>x(v),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:v.color}}),e.jsx("span",{className:"flex-1 text-left truncate",children:v.name}),m.has(v.id)&&e.jsx(ma,{className:"h-3.5 w-3.5 text-primary shrink-0"})]},v.id)),d.trim()&&!g&&e.jsxs("button",{onClick:y,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(nn,{className:"h-3.5 w-3.5"}),'Create "',d.trim(),'"']}),p.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 Dyt({contactId:s,tags:t,max:n=2}){return!t||t.length===0?null:e.jsx(l5n,{tags:t,max:n})}const _ae=["#6366F1","#8B5CF6","#EC4899","#EF4444","#F97316","#F59E0B","#10B981","#14B8A6","#06B6D4","#3B82F6","#6B7280","#1F2937"];function c5n({open:s,onOpenChange:t}){const{data:n,isLoading:r}=kV(),a=_Ze(),i=Xbn(),l=Zbn(),[o,c]=k.useState(""),[d,u]=k.useState(_ae[0]),[h,m]=k.useState(null),[p,g]=k.useState(""),[x,y]=k.useState(""),v=async()=>{if(o.trim())try{await a.mutateAsync({name:o.trim(),color:d}),c(""),u(_ae[0]),Ma({title:"Tag created"})}catch(A){Ma({title:"Error",description:A.message,variant:"destructive"})}},_=async A=>{if(p.trim())try{await i.mutateAsync({id:A,name:p.trim(),color:x}),m(null),Ma({title:"Tag updated"})}catch(M){Ma({title:"Error",description:M.message,variant:"destructive"})}},j=async(A,M)=>{if(await io(`Delete tag "${M}"? It will be removed from all contacts.`))try{await l.mutateAsync(A),Ma({title:"Tag deleted"})}catch(I){Ma({title:"Error",description:I.message,variant:"destructive"})}},C=A=>{m(A.id),g(A.name),y(A.color)};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"max-w-md",children:[e.jsx(Vs,{children:e.jsx($s,{children:"Manage Tags"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(be,{placeholder:"New tag name...",value:o,onChange:A=>c(A.target.value),onKeyDown:A=>A.key==="Enter"&&v(),className:"flex-1 h-9"}),e.jsxs($,{size:"sm",onClick:v,disabled:!o.trim()||a.isPending,className:"h-9",children:[e.jsx(nn,{className:"h-4 w-4 mr-1"}),"Add"]})]}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:_ae.map(A=>e.jsx("button",{onClick:()=>u(A),className:`h-6 w-6 rounded-full border-2 transition-transform ${d===A?"border-foreground scale-110":"border-transparent hover:scale-105"}`,style:{backgroundColor:A}},A))})]}),e.jsxs("div",{className:"mt-2 space-y-1 max-h-[320px] overflow-y-auto",children:[r&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"Loading..."}),(n==null?void 0:n.length)===0&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No tags yet. Create one above!"}),n==null?void 0:n.map(A=>e.jsx("div",{className:"flex items-center gap-2 p-2 rounded-lg hover:bg-accent/50 group",children:h===A.id?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"flex flex-wrap gap-1",children:_ae.map(M=>e.jsx("button",{onClick:()=>y(M),className:`h-5 w-5 rounded-full border-2 ${x===M?"border-foreground":"border-transparent"}`,style:{backgroundColor:M}},M))}),e.jsx(be,{value:p,onChange:M=>g(M.target.value),onKeyDown:M=>M.key==="Enter"&&_(A.id),className:"flex-1 h-8 text-sm",autoFocus:!0}),e.jsx($,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>_(A.id),children:e.jsx(ma,{className:"h-4 w-4 text-primary"})}),e.jsx($,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>m(null),children:e.jsx(mr,{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:A.color}}),e.jsx("span",{className:"flex-1 text-sm",children:A.name}),e.jsx($,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 opacity-0 group-hover:opacity-100 transition-opacity",onClick:()=>C(A),children:e.jsx(ui,{className:"h-3.5 w-3.5"})}),e.jsx($,{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(A.id,A.name),children:e.jsx(Un,{className:"h-3.5 w-3.5"})})]})},A.id))]})]})})}function d5n({open:s,onOpenChange:t}){const{data:n,isLoading:r}=NF(),a=bWe(),i=UEs(),l=qEs(),[o,c]=k.useState(""),[d,u]=k.useState(null),[h,m]=k.useState(""),p=async()=>{if(o.trim())try{await a.mutateAsync(o.trim()),c("")}catch(v){ae.error(v.message||"Failed to add lead source")}},g=async v=>{if(h.trim())try{await i.mutateAsync({id:v,name:h.trim()}),u(null)}catch(_){ae.error(_.message||"Failed to update")}},x=async(v,_)=>{if(await io(`Remove lead source "${_}"? Contacts using it will keep the label but it won't appear in new dropdowns.`))try{await l.mutateAsync(v)}catch(j){ae.error(j.message||"Failed to remove")}},y=v=>{u(v.id),m(v.name)};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"max-w-md",children:[e.jsx(Vs,{children:e.jsx($s,{children:"Manage Lead Sources"})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(be,{placeholder:"New lead source name...",value:o,onChange:v=>c(v.target.value),onKeyDown:v=>v.key==="Enter"&&p(),className:"flex-1 h-9"}),e.jsxs($,{size:"sm",onClick:p,disabled:!o.trim()||a.isPending,className:"h-9",children:[e.jsx(nn,{className:"h-4 w-4 mr-1"}),"Add"]})]}),e.jsxs("div",{className:"mt-2 space-y-1 max-h-[360px] overflow-y-auto",children:[r&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"Loading..."}),(n==null?void 0:n.length)===0&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No lead sources yet. Create one above!"}),n==null?void 0:n.map(v=>e.jsx("div",{className:"flex items-center gap-2 p-2 rounded-lg hover:bg-accent/50 group",children:d===v.id?e.jsxs(e.Fragment,{children:[e.jsx(be,{value:h,onChange:_=>m(_.target.value),onKeyDown:_=>_.key==="Enter"&&g(v.id),className:"flex-1 h-8 text-sm",autoFocus:!0}),e.jsx($,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>g(v.id),children:e.jsx(ma,{className:"h-4 w-4 text-primary"})}),e.jsx($,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>u(null),children:e.jsx(mr,{className:"h-4 w-4"})})]}):e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"flex-1 text-sm",children:v.name}),v.owner_user_id&&e.jsxs(e.Fragment,{children:[e.jsx($,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 opacity-0 group-hover:opacity-100 transition-opacity",onClick:()=>y(v),children:e.jsx(ui,{className:"h-3.5 w-3.5"})}),e.jsx($,{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:()=>x(v.id,v.name),children:e.jsx(Un,{className:"h-3.5 w-3.5"})})]}),!v.owner_user_id&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"Default"})]})},v.id))]})]})})}function K7t({value:s,onChange:t,label:n="Lead Source"}){const{data:r}=NF(),a=bWe(),[i,l]=k.useState(!1),[o,c]=k.useState(""),d=async()=>{if(o.trim())try{const u=await a.mutateAsync(o.trim());u&&(t(u.id),c(""),l(!1))}catch{}};return e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:n}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(bs,{value:s||"_none",onValueChange:u=>t(u==="_none"?"":u),children:[e.jsx(ys,{className:"flex-1",children:e.jsx(_s,{placeholder:"Select lead source"})}),e.jsxs(vs,{children:[e.jsx(We,{value:"_none",children:"No source"}),r==null?void 0:r.map(u=>e.jsx(We,{value:u.id,children:u.name},u.id))]})]}),e.jsx($,{type:"button",variant:"outline",size:"icon",className:"shrink-0",onClick:()=>l(!i),children:i?e.jsx(mr,{className:"h-4 w-4"}):e.jsx(nn,{className:"h-4 w-4"})})]}),i&&e.jsxs("div",{className:"flex gap-2",children:[e.jsx(be,{placeholder:"New lead source name...",value:o,onChange:u=>c(u.target.value),onKeyDown:u=>{u.key==="Enter"&&(u.preventDefault(),d())},className:"flex-1"}),e.jsx($,{type:"button",size:"sm",onClick:d,disabled:!o.trim()||a.isPending,children:"Add"})]})]})}function YBe({contactId:s,currentSpouseContactId:t,currentSpouseName:n,currentSpouseEmail:r,onLink:a,onUnlink:i,isEditing:l}){const o=Jn(),c=ai(),[d,u]=k.useState(!1),[h,m]=k.useState(""),{data:p}=pt({queryKey:["innercircle-contact-spouse",t],queryFn:async()=>{const{data:x,error:y}=await V.from("innercircle_contacts").select("id, first_name, last_name, email, phone, birthday").eq("id",t).maybeSingle();if(y)throw y;return x},enabled:!!t}),{data:g}=pt({queryKey:["spouse-search",c,s,h],queryFn:async()=>{let x=V.from("innercircle_contacts").select("id, first_name, last_name, email, phone").eq("owner_user_id",c).is("synced_source",null).neq("id",s).order("first_name").limit(20);if(h.trim()){const _=h.replace(/[,()%]/g," ").trim();_&&(x=x.or(`first_name.ilike.%${_}%,last_name.ilike.%${_}%,email.ilike.%${_}%,phone.ilike.%${_}%`))}const{data:y,error:v}=await x;if(v)throw v;return y},enabled:d&&!!c});if(t&&p){const x=`${p.first_name} ${p.last_name||""}`.trim();return e.jsxs("div",{className:"space-y-1",children:[e.jsx(re,{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(el,{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/${p.id}`),className:"text-sm font-medium text-primary hover:underline truncate block",children:x}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:[p.phone,p.email].filter(Boolean).join(" · ")||"No contact info"})]}),l&&e.jsxs($,{variant:"ghost",size:"sm",onClick:i,className:"shrink-0 h-7 px-2",children:[e.jsx(Q8,{className:"h-3.5 w-3.5 mr-1"}),"Unlink"]}),!l&&e.jsx($,{variant:"ghost",size:"sm",onClick:()=>o(`/mission-control/contacts/${p.id}`),className:"shrink-0 h-7 px-2",children:e.jsx(xi,{className:"h-3.5 w-3.5"})})]})]})}return!t&&(n||r)?e.jsxs("div",{className:"space-y-1",children:[e.jsx(re,{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(el,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("span",{className:"text-sm",children:n}),r&&e.jsx("span",{className:"text-xs text-muted-foreground block truncate",children:r})]}),l&&e.jsxs(Xc,{open:d,onOpenChange:u,children:[e.jsx(Qc,{asChild:!0,children:e.jsxs($,{variant:"outline",size:"sm",className:"shrink-0 h-7 px-2",children:[e.jsx(pd,{className:"h-3.5 w-3.5 mr-1"}),"Link Contact"]})}),e.jsx(Bc,{className:"w-72 p-2",align:"end",children:e.jsx(Oyt,{search:h,setSearch:m,results:g,onSelect:x=>{a(x),u(!1),m("")}})})]})]})]}):l?e.jsxs("div",{className:"space-y-1",children:[e.jsx(re,{className:"text-sm font-medium",children:"Spouse / Partner"}),e.jsxs(Xc,{open:d,onOpenChange:u,children:[e.jsx(Qc,{asChild:!0,children:e.jsxs($,{variant:"outline",className:"w-full justify-start text-muted-foreground font-normal h-10",children:[e.jsx(pd,{className:"h-4 w-4 mr-2"}),"Link an existing contact as spouse..."]})}),e.jsx(Bc,{className:"w-72 p-2",align:"start",children:e.jsx(Oyt,{search:h,setSearch:m,results:g,onSelect:x=>{a(x),u(!1),m("")}})})]})]}):null}function Oyt({search:s,setSearch:t,results:n,onSelect:r}){return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Yr,{className:"absolute left-2 top-2.5 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(be,{value:s,onChange:a=>t(a.target.value),placeholder:"Search contacts...",className:"pl-7 h-8 text-sm",autoFocus:!0})]}),e.jsx(Eo,{className:"max-h-48",children:n&&n.length>0?e.jsx("div",{className:"space-y-0.5",children:n.map(a=>e.jsxs("button",{onClick:()=>r(a.id),className:"w-full text-left px-2 py-1.5 rounded hover:bg-accent transition-colors",children:[e.jsxs("div",{className:"text-sm font-medium truncate",children:[a.first_name," ",a.last_name]}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:[a.phone,a.email].filter(Boolean).join(" · ")||"No contact info"})]},a.id))}):e.jsx("p",{className:"text-xs text-muted-foreground text-center py-3",children:s?"No contacts found":"Type to search contacts"})})]})}const u5n={warm:"stroke-emerald-500",cooling:"stroke-amber-500","at-risk":"stroke-red-500"},h5n={warm:"text-emerald-600 dark:text-emerald-400",cooling:"text-amber-600 dark:text-amber-400","at-risk":"text-red-600 dark:text-red-400"};function m5n({score:s,status:t,size:n=36,className:r}){const a=n>=56?5:3,i=(n-a)/2,l=2*Math.PI*i,o=Math.max(0,Math.min(100,s)),c=l-o/100*l;return e.jsxs("div",{className:Ot("relative shrink-0",r),style:{width:n,height:n},children:[e.jsxs("svg",{width:n,height:n,className:"-rotate-90",children:[e.jsx("circle",{cx:n/2,cy:n/2,r:i,fill:"none",strokeWidth:a,className:"stroke-muted"}),e.jsx("circle",{cx:n/2,cy:n/2,r:i,fill:"none",strokeWidth:a,strokeLinecap:"round",strokeDasharray:l,strokeDashoffset:c,className:u5n[t]})]}),e.jsx("span",{className:Ot("absolute inset-0 flex items-center justify-center font-semibold tabular-nums",h5n[t],n>=56?"text-lg":"text-[11px]"),children:o})]})}const wae=new Map;async function f5n(s){const t=new TextEncoder().encode(s),n=await crypto.subtle.digest("SHA-256",t);return Array.from(new Uint8Array(n)).map(r=>r.toString(16).padStart(2,"0")).join("")}async function p5n(s,t=256){const n=s.trim().toLowerCase();if(!n||!n.includes("@"))return null;const r=`${n}|${t}`;if(wae.has(r))return wae.get(r)??null;try{const i=`https://gravatar.com/avatar/${await f5n(n)}?s=${t}&d=404`;return wae.set(r,i),i}catch{return wae.set(r,null),null}}function g5n(s,t=256){const[n,r]=k.useState(null);return k.useEffect(()=>{let a=!0;if(!s){r(null);return}return p5n(s,t).then(i=>{a&&r(i)}),()=>{a=!1}},[s,t]),n}function Y7t({firstName:s,lastName:t,avatarUrl:n,email:r,size:a=36,className:i,rounded:l="full"}){const o=`${(s==null?void 0:s[0])??""}${(t==null?void 0:t[0])??""}`.toUpperCase()||"?",c=l==="full"?"rounded-full":l==="xl"?"rounded-xl":"rounded-2xl",d=g5n(n?null:r,Math.max(64,a*2)),[u,h]=k.useState(!1);k.useEffect(()=>h(!1),[d]);const m=n||(u?null:d);return e.jsx("div",{className:Ot("shrink-0 overflow-hidden bg-primary/10 text-primary flex items-center justify-center font-semibold select-none",c,i),style:{width:a,height:a,fontSize:Math.max(10,Math.round(a*.36))},children:m?e.jsx("img",{src:m,alt:`${s??""} ${t??""}`.trim()||"Contact photo",className:"h-full w-full object-cover",loading:"lazy",onError:()=>h(!0)}):e.jsx("span",{children:o})})}function x5n({spouseName:s,linked:t,onClick:n}){if(!s&&!t)return null;const r=s?`${t?"Linked spouse":"Spouse"}: ${s}`:"Spouse / partner linked";return e.jsxs(Lx,{children:[e.jsx(Rx,{asChild:!0,children:e.jsx("span",{role:n?"button":void 0,onClick:n?a=>{a.stopPropagation(),n()}:void 0,className:`inline-flex h-5 w-5 shrink-0 items-center justify-center rounded-full bg-muted text-muted-foreground ${n?"cursor-pointer hover:bg-accent hover:text-accent-foreground":""}`,"aria-label":r,children:e.jsx(Xn,{className:"h-3 w-3"})})}),e.jsx(Jg,{children:r})]})}function y5n({totalLabel:s,stats:t,search:n,onSearchChange:r,onAddContact:a,onImportCsv:i,onImportPhone:l,onManageTags:o,onHeatMap:c,viewMode:d="my",onViewModeChange:u,showTeamTab:h,showLeadPondTab:m,extraActions:p}){const g=!!u&&(h||m);return e.jsx("section",{className:"hub-ink relative overflow-hidden rounded-2xl p-5 sm:p-6",children:e.jsxs("div",{className:"relative flex flex-col gap-5",children:[e.jsxs("div",{className:"flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-xs uppercase tracking-wider hub-ink-muted",children:"Agent OS"}),e.jsx("h1",{className:"mt-1 text-2xl font-bold sm:text-3xl",children:"Contacts"}),e.jsx("p",{className:"mt-1 text-sm hub-ink-muted",children:s})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs("button",{onClick:a,className:"inline-flex items-center gap-2 rounded-full bg-background px-4 py-2 text-sm font-semibold text-foreground shadow-sm transition-transform hover:scale-[1.02]",children:[e.jsx(nn,{className:"h-4 w-4"}),"Add Contact"]}),e.jsxs("button",{onClick:c,className:"hub-glass inline-flex items-center gap-2 rounded-full px-4 py-2 text-sm font-medium transition-colors",children:[e.jsx(iu,{className:"h-4 w-4",style:{color:"hsl(var(--hub-glow))"}}),"Heat Map"]}),e.jsxs(Au,{children:[e.jsx(Eu,{asChild:!0,children:e.jsxs("button",{className:"hub-glass inline-flex items-center gap-2 rounded-full px-4 py-2 text-sm font-medium transition-colors",children:[e.jsx(gi,{className:"h-4 w-4",style:{color:"hsl(var(--hub-glow))"}}),"Import",e.jsx(Go,{className:"h-3.5 w-3.5 opacity-70"})]})}),e.jsxs(gu,{align:"end",children:[e.jsxs(Pa,{onClick:i,children:[e.jsx(gi,{className:"mr-2 h-4 w-4"})," Import CSV"]}),e.jsxs(Pa,{onClick:l,children:[e.jsx(yb,{className:"mr-2 h-4 w-4"})," Import from Phone"]}),e.jsxs(Pa,{onClick:o,children:[e.jsx(kg,{className:"mr-2 h-4 w-4"})," Manage Tags"]})]})]}),p]})]}),e.jsxs("div",{className:"flex flex-col gap-3 sm:flex-row sm:items-center",children:[e.jsxs("div",{className:"relative flex-1 min-w-0",children:[e.jsx(Yr,{className:"pointer-events-none absolute left-3.5 top-1/2 h-4 w-4 -translate-y-1/2 opacity-70"}),e.jsx(be,{value:n,onChange:x=>r(x.target.value),placeholder:"Search by name, email, phone, or notes...",className:"h-11 rounded-xl border-transparent bg-white/10 pl-10 text-current placeholder:text-current/50 focus-visible:ring-2 focus-visible:ring-white/30"})]}),g&&e.jsx("div",{className:"hub-glass inline-flex shrink-0 items-center gap-1 rounded-xl p-1",children:[{key:"my",label:"Mine",icon:Xn,show:!0},{key:"team",label:"Team",icon:Xn,show:!!h},{key:"lead-pond",label:"Pond",icon:pb,show:!!m}].filter(x=>x.show).map(x=>e.jsxs("button",{onClick:()=>u==null?void 0:u(x.key),className:Ot("inline-flex items-center gap-1.5 rounded-lg px-3 py-1.5 text-xs font-semibold transition-colors",d===x.key?"bg-background text-foreground shadow-sm":"hub-ink-muted"),children:[e.jsx(x.icon,{className:"h-3.5 w-3.5"}),x.label]},x.key))})]}),e.jsx("div",{className:"grid grid-cols-2 gap-2 sm:grid-cols-4",children:t.map(x=>e.jsxs("button",{onClick:x.onClick,className:Ot("hub-glass rounded-xl px-3 py-2.5 text-left transition-colors",x.active&&"ring-2 ring-white/40"),children:[e.jsx("span",{className:"text-xl font-bold",children:x.value}),e.jsx("p",{className:"mt-0.5 text-[11px] hub-ink-muted",children:x.label})]},x.label))})]})})}function v5n({rows:s=8,columns:t=5}){return e.jsx(e.Fragment,{children:Array.from({length:s}).map((n,r)=>e.jsxs("tr",{className:"border-b border-border/60",children:[e.jsx("td",{className:"px-4 py-4",children:e.jsx(fn,{className:"h-4 w-4 rounded"})}),e.jsx("td",{className:"px-4 py-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(fn,{className:"h-9 w-9 rounded-full"}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(fn,{className:"h-3.5 w-36"}),e.jsx(fn,{className:"h-3 w-24"})]})]})}),Array.from({length:Math.max(t-2,1)}).map((a,i)=>e.jsx("td",{className:"px-4 py-4",children:e.jsx(fn,{className:"h-3.5 w-20"})},i))]},r))})}function b5n({count:s=6}){return e.jsx("div",{className:"space-y-3",children:Array.from({length:s}).map((t,n)=>e.jsxs("div",{className:"rounded-xl border border-border bg-card p-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(fn,{className:"h-10 w-10 rounded-full"}),e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsx(fn,{className:"h-4 w-2/5"}),e.jsx(fn,{className:"h-3 w-3/5"})]})]}),e.jsxs("div",{className:"mt-3 flex gap-2",children:[e.jsx(fn,{className:"h-6 w-16 rounded-full"}),e.jsx(fn,{className:"h-6 w-20 rounded-full"})]})]},n))})}function Fyt({filtered:s,onAdd:t,onImport:n,onClearFilters:r}){return e.jsxs("div",{className:"flex flex-col items-center justify-center gap-3 px-6 py-14 text-center",children:[e.jsx("div",{className:"flex h-12 w-12 items-center justify-center rounded-2xl bg-primary/10 text-primary",children:e.jsxs("svg",{viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"1.8",className:"h-6 w-6",children:[e.jsx("path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",strokeLinecap:"round"}),e.jsx("circle",{cx:"9",cy:"7",r:"4"}),e.jsx("path",{d:"M19 8v6M22 11h-6",strokeLinecap:"round"})]})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-base font-semibold text-foreground",children:s?"No contacts match these filters":"Your database is empty"}),e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:s?"Try a different search or clear the filters to see everyone.":"Add someone manually or import your existing contacts to get started."})]}),e.jsx("div",{className:"mt-1 flex flex-wrap items-center justify-center gap-2",children:s?e.jsx("button",{onClick:r,className:"rounded-full bg-primary px-4 py-2 text-sm font-semibold text-primary-foreground",children:"Clear filters"}):e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:t,className:"rounded-full bg-primary px-4 py-2 text-sm font-semibold text-primary-foreground",children:"Add contact"}),e.jsx("button",{onClick:n,className:"rounded-full border border-border px-4 py-2 text-sm font-medium text-foreground hover:bg-accent",children:"Import contacts"})]})})]})}function Z7t(s){const t=r=>!(typeof r=="string"?r.trim():r),n=!t(s==null?void 0:s.address)||!t(s==null?void 0:s.city)||!t(s==null?void 0:s.state)||!t(s==null?void 0:s.zip);return t(s==null?void 0:s.email)||t(s==null?void 0:s.phone)||t(s==null?void 0:s.birthday)||!n}function zyt(s){if(!s)return null;const t=ih(s);if(!t)return null;const n=new Date;n.setHours(0,0,0,0);const r=new Date(n.getFullYear(),t.getMonth(),t.getDate());return rs.relationshipScore.status==="at-risk"},{key:"never-contacted",title:"Never Contacted",icon:Pl,color:"text-violet-600 dark:text-violet-400",match:s=>s.relationshipScore.daysSinceTouch===null},{key:"stale-90",title:"Stale 90+ Days",icon:sa,color:"text-amber-600 dark:text-amber-400",match:s=>{const t=s.relationshipScore.daysSinceTouch;return t!==null&&t>90}},{key:"cooling",title:"Cooling Off",icon:Hw,color:"text-cyan-600 dark:text-cyan-400",match:s=>s.relationshipScore.status==="cooling"},{key:"birthdays-soon",title:"Birthdays Soon",icon:ip,color:"text-pink-600 dark:text-pink-400",match:(s,t)=>t.daysToBirthday!==null&&t.daysToBirthday<=30},{key:"anniversary-soon",title:"Home Anniversary",icon:ua,color:"text-emerald-600 dark:text-emerald-400",match:(s,t)=>t.daysToAnniv!==null&&t.daysToAnniv<=30},{key:"has-deal",title:"Active Deal",icon:zx,color:"text-teal-700 dark:text-teal-400",match:(s,t)=>t.hasDeal},{key:"website-active",title:"Active on Site",icon:kc,color:"text-indigo-600 dark:text-indigo-400",match:()=>!1},{key:"vips",title:"VIPs",icon:kn,color:"text-amber-600 dark:text-amber-300",match:s=>s.relationshipScore.score>=80},{key:"missing-info",title:"Missing Info",icon:Gd,color:"text-slate-600 dark:text-slate-400",match:s=>Z7t(s)}];function _5n({contacts:s,contactDealsMap:t,websiteActiveIds:n,totalCount:r,activeKey:a,onSelectSegment:i,currentFilters:l,currentSortBy:o,activeViewId:c,onApplyView:d,onClearAll:u}){const{data:h}=wZe(),m=KFt(),p=YFt(),[g,x]=k.useState(!1),[y,v]=k.useState(""),_=k.useMemo(()=>{const M={"needs-attention":0,cooling:0,"never-contacted":0,"stale-90":0,"birthdays-soon":0,"anniversary-soon":0,"has-deal":0,"website-active":n.size,"missing-info":0,vips:0};if(!s)return M;for(const I of s){const P={hasDeal:!!(t&&t[I.id]),daysToBirthday:zyt(I.birthday),daysToAnniv:zyt(I.home_anniversary)};for(const R of Byt)R.key!=="website-active"&&R.match(I,P)&&M[R.key]++}return M},[s,t,n]),j=!!l.search||!!l.type&&l.type!=="all"||!!l.status&&l.status!=="all"||!!l.behavior&&Object.values(l.behavior).some(M=>M!==void 0&&M!==!1),C=async()=>{y.trim()&&(await m.mutateAsync({name:y.trim(),filters:l,sort_by:o}),v(""),x(!1))},A="inline-flex items-center gap-1.5 h-8 shrink-0 rounded-full border px-3 text-xs font-medium transition-colors whitespace-nowrap";return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2 overflow-x-auto pb-1 -mx-1 px-1 [scrollbar-width:none] [&::-webkit-scrollbar]:hidden",children:[e.jsxs("button",{type:"button",onClick:u,className:Ot(A,!a&&!c?"bg-primary text-primary-foreground border-primary":"bg-card hover:bg-accent border-border"),children:[e.jsx(Xn,{className:"h-3.5 w-3.5"}),"All Contacts",e.jsx("span",{className:"tabular-nums opacity-70",children:r.toLocaleString()})]}),h==null?void 0:h.map(M=>{const I=c===M.id;return e.jsxs("div",{className:Ot(A,"group pr-1",I?"bg-primary text-primary-foreground border-primary":"bg-card hover:bg-accent border-border"),children:[e.jsx("button",{type:"button",onClick:()=>d(M.id,M.filters,M.sort_by),children:M.name}),e.jsx("button",{type:"button","aria-label":`Delete view ${M.name}`,className:"h-5 w-5 rounded-full flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity hover:bg-foreground/10",onClick:()=>{p.mutate(M.id),I&&u()},children:e.jsx(mr,{className:"h-3 w-3"})})]},M.id)}),e.jsx("div",{className:"h-5 w-px bg-border shrink-0"}),Byt.map(M=>{const I=M.icon,P=_[M.key],R=a===M.key;return e.jsxs("button",{type:"button",onClick:()=>i(R?null:M.key),"aria-pressed":R,className:Ot(A,R?"bg-primary text-primary-foreground border-primary":"bg-card hover:bg-accent border-border",!R&&P===0&&"opacity-55"),children:[e.jsx(I,{className:Ot("h-3.5 w-3.5",R?"":M.color)}),M.title,e.jsx("span",{className:"tabular-nums opacity-70",children:P.toLocaleString()})]},M.key)}),e.jsxs($,{variant:"ghost",size:"sm",className:"h-8 gap-1.5 text-xs shrink-0",disabled:!j,onClick:()=>x(!0),children:[e.jsx(BT,{className:"h-3.5 w-3.5"}),"Save view"]})]}),e.jsx(zs,{open:g,onOpenChange:x,children:e.jsxs(Rs,{className:"sm:max-w-sm",children:[e.jsxs(Vs,{children:[e.jsx($s,{children:"Save this view"}),e.jsx(Cr,{children:"Your current search, filters, and sorting are saved as a one-click chip."})]}),e.jsx(be,{autoFocus:!0,placeholder:"e.g. Past clients cooling off",value:y,onChange:M=>v(M.target.value),onKeyDown:M=>M.key==="Enter"&&C()}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>x(!1),children:"Cancel"}),e.jsx($,{onClick:C,disabled:!y.trim()||m.isPending,children:"Save view"})]})]})})]})}const $yt=[{key:"relationship",label:"Relationship"},{key:"stage",label:"Stage"},{key:"leadSource",label:"Lead Source"},{key:"tags",label:"Tags"},{key:"lastTouch",label:"Last Touch"},{key:"nextAction",label:"Next Action"},{key:"dealValue",label:"Pipeline Value"},{key:"email",label:"Email"},{key:"phone",label:"Phone"},{key:"address",label:"Address"},{key:"birthday",label:"Birthday"}],tDe={relationship:!0,stage:!0,leadSource:!0,tags:!0,lastTouch:!0,nextAction:!0,dealValue:!0,email:!1,phone:!1,address:!1,birthday:!1},Uyt="innercircle:contact-columns:v1";function w5n(){const[s,t]=k.useState(()=>{try{const a=localStorage.getItem(Uyt);if(a)return{...tDe,...JSON.parse(a)}}catch{}return tDe});k.useEffect(()=>{try{localStorage.setItem(Uyt,JSON.stringify(s))}catch{}},[s]);const n=k.useCallback(a=>{t(i=>({...i,[a]:!i[a]}))},[]),r=k.useCallback(()=>t(tDe),[]);return{columns:s,toggle:n,reset:r}}function j5n({columns:s,onToggle:t,onReset:n}){const r=$yt.filter(a=>s[a.key]).length;return e.jsxs(Xc,{children:[e.jsx(Qc,{asChild:!0,children:e.jsxs($,{variant:"outline",size:"sm",className:"h-8 gap-1.5 rounded-lg text-xs",children:[e.jsx(dE,{className:"h-3.5 w-3.5"}),"Columns",e.jsx(qe,{variant:"secondary",className:"h-5 px-1.5 text-[10px]",children:r})]})}),e.jsxs(Bc,{align:"end",className:"w-56 p-2",children:[e.jsxs("div",{className:"flex items-center justify-between px-1 pb-2",children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Show columns"}),e.jsxs("button",{type:"button",onClick:n,className:"inline-flex items-center gap-1 text-[11px] text-muted-foreground hover:text-foreground",children:[e.jsx(jm,{className:"h-3 w-3"}),"Reset"]})]}),e.jsx("div",{className:"max-h-[320px] overflow-y-auto space-y-0.5",children:$yt.map(a=>e.jsxs("button",{type:"button",onClick:()=>t(a.key),className:"flex items-center gap-2 w-full px-2 py-1.5 rounded-md text-sm hover:bg-accent transition-colors",children:[e.jsx(Li,{checked:s[a.key],className:"pointer-events-none"}),e.jsx("span",{className:"flex-1 text-left",children:a.label})]},a.key))}),e.jsx("p",{className:"px-2 pt-2 text-[11px] text-muted-foreground",children:"Name and actions are always shown."})]})]})}function N5n(){var Lc;const s=Jn(),[t,n]=Jc(),{user:r}=ks(),a=AV(),i=ls(),{columns:l,toggle:o,reset:c}=w5n(),d=t.get("type"),u=t.get("filter")??t.get("status"),h=t.get("new")==="true",{contactsWithScores:m,isLoading:p}=Eee(),{activeContactIds:g,hasLeadSite:x}=dSn(),{data:y}=r5n(),{data:v}=vj(),{data:_}=a5n(),{data:j}=kV(),{data:C}=QEe(),[A,M]=k.useState(new Set),[I,P]=k.useState("any"),R=pAe(),O=xWe(),B=yWe(),U=KMt(),[G,H]=k.useState(""),[Y,se]=k.useState(!1),[ee,oe]=k.useState(d||"all"),[me,Q]=k.useState(u||"all"),[te,le]=k.useState("date-added"),[fe,_e]=k.useState("all"),[ve,he]=k.useState({}),Se=k.useMemo(()=>Object.values(ve).filter(Ss=>Ss!==void 0&&Ss!==!1&&Ss!=="").length,[ve]),[Te,Ie]=k.useState(!1),{behaviorMap:Ue,hasLeadSite:Be}=JSn(),[je,Ye]=k.useState(h),[Ee,Re]=k.useState(null),[ke,Fe]=k.useState(!1),[Oe,Ge]=k.useState(!1),[yt,tt]=k.useState(null),[ut,nt]=k.useState(""),[et,at]=k.useState(new Set),[wt,rt]=k.useState(!1),Ft=Math.max(1,parseInt(t.get("page")||"1",10)||1),[Ut,Is]=k.useState(Ft),xs=k.useCallback(Ss=>{Is(wa=>{const Ci=typeof Ss=="function"?Ss(wa):Ss;return n(fa=>{const zn=new URLSearchParams(fa);return Ci<=1?zn.delete("page"):zn.set("page",String(Ci)),zn},{replace:!0}),Ci})},[]),[st,dt]=k.useState(50),[jt,gt]=k.useState("my"),[rs,Ns]=k.useState(!1),[us,Bs]=k.useState(!1),{data:Ts}=gj(),{addToLeadPond:Fn}=NRt(Ts==null?void 0:Ts.teamId),{ponds:An}=eYe(Ts==null?void 0:Ts.teamId),js=An.filter(Ss=>Ss.has_access),[In,un]=k.useState(null),[jr,Ln]=k.useState(""),Sr=!!((Lc=Ts==null?void 0:Ts.team)!=null&&Lc.lead_pond_enabled&&(Ts!=null&&Ts.teamId)),Qn=!!(Ts!=null&&Ts.teamId),[En,pr]=k.useState([]),[xn,Ar]=k.useState(!1),Zr=Ss=>{pr([Ss]),Ar(!0)},dn=Ss=>{pr(Ss),Ar(!0)},Kt=(Ss,wa)=>{Ts!=null&&Ts.teamId&&Ss.forEach(Ci=>{Fn.mutate({contact_id:Ci,team_id:Ts.teamId,pond_id:wa||null})})},Er=Ss=>{var wa;if(Ts!=null&&Ts.teamId){if(js.length>1){Ln(js[0].id),un(Ss);return}Kt(Ss,((wa=js[0])==null?void 0:wa.id)||null)}},ti=Ss=>Er([Ss]),Ba=Ss=>Er(Ss),lo=k.useCallback(Ss=>{rt(!1),at(wa=>{const Ci=new Set(wa);return Ci.has(Ss)?Ci.delete(Ss):Ci.add(Ss),Ci})},[]);k.useEffect(()=>{if(!(r!=null&&r.id))return;const Ss=V.channel(`innercircle_contacts_inserts_${r.id}`).on("postgres_changes",{event:"INSERT",schema:"public",table:"innercircle_contacts",filter:`owner_user_id=eq.${r.id}`},()=>{i.invalidateQueries({queryKey:["innercircle-contacts"]}),i.invalidateQueries({queryKey:["innercircle-contact-counts"]})}).subscribe();return()=>{V.removeChannel(Ss)}},[i,r==null?void 0:r.id]),k.useEffect(()=>{u&&Q(u)},[u]);const[Yn,Hr]=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(()=>{h&&Ye(!0)},[h]),k.useEffect(()=>{var Ss;Ee&&Hr({first_name:Ee.first_name||"",last_name:Ee.last_name||"",email:Ee.email||"",phone:Ee.phone||"",address:Ee.address||"",city:Ee.city||"",state:Ee.state||"",zip_code:Ee.zip_code||"",birthday:Ee.birthday||"",home_anniversary:Ee.home_anniversary||"",spouse_name:Ee.spouse_name||"",spouse_email:Ee.spouse_email||"",lead_source_id:Ee.lead_source_id||"",notes:Ee.notes||"",tagIds:((Ss=Ee.tags)==null?void 0:Ss.map(wa=>wa.relationship_type_id))||[]})},[Ee]);const Ur=k.useMemo(()=>{const Ss=new Set;return j==null||j.forEach(wa=>{(wa.name==="Recruits"||wa.name==="Brokerage Agents")&&Ss.add(wa.id)}),Ss},[j]),Ei=k.useMemo(()=>Array.from(A).some(Ss=>Ur.has(Ss)),[A,Ur]),fo=k.useMemo(()=>{const Ss={};return(m||[]).forEach(wa=>{Ss[wa.id]=`${wa.first_name||""} ${wa.last_name||""}`.trim()}),Ss},[m]),co=k.useMemo(()=>{if(!m)return[];let Ss=m.filter(fa=>{var Gm,Gu,Zd,Bh,Mg,Sd,$h,Af,Gp,Ef,Wx;const zn=fa.synced_source;if(!Ei&&(zn==="recruit"||zn==="brokerage_agent"))return!1;const ja=G===""||`${fa.first_name} ${fa.last_name}`.toLowerCase().includes(G.toLowerCase())||((Gm=fa.email)==null?void 0:Gm.toLowerCase().includes(G.toLowerCase()))||((Gu=fa.phone)==null?void 0:Gu.includes(G))||((Zd=fa.city)==null?void 0:Zd.toLowerCase().includes(G.toLowerCase()))||((Bh=fa.state)==null?void 0:Bh.toLowerCase().includes(G.toLowerCase()))||((Mg=fa.address)==null?void 0:Mg.toLowerCase().includes(G.toLowerCase()))||((Sd=fa.zip_code)==null?void 0:Sd.toLowerCase().includes(G.toLowerCase())),Il=ee==="all"||(($h=fa.tags)==null?void 0:$h.some(rl=>rl.relationship_type_id===ee)),zo=A.size===0||(()=>{const rl=(C==null?void 0:C.filter(to=>to.contact_id===fa.id).map(to=>to.tag_id))||[];return I==="any"?rl.some(to=>A.has(to)):Array.from(A).every(to=>rl.includes(to))})(),Hl=!!((Af=fa.address)!=null&&Af.trim()||(Gp=fa.city)!=null&&Gp.trim()||(Ef=fa.state)!=null&&Ef.trim()||(Wx=fa.zip_code)!=null&&Wx.trim()),Cf=fe==="all"||fe==="has-address"&&Hl||fe==="no-address"&&!Hl,oi=fa,Mo=ve,zh=(Mo.hasEmail===void 0||!!oi.email===Mo.hasEmail)&&(Mo.hasPhone===void 0||!!oi.phone===Mo.hasPhone)&&(Mo.hasAddress===void 0||Hl===Mo.hasAddress)&&(Mo.hasBirthday===void 0||!!oi.birthday===Mo.hasBirthday)&&(Mo.hasSpouse===void 0||!!(oi.spouse_name||oi.spouse_contact_id||oi.spouse_email)===Mo.hasSpouse)&&(Mo.hasCompany===void 0||!!(oi.company_name||oi.job_title)===Mo.hasCompany)&&(Mo.hasNotes===void 0||!!(oi.notes&&oi.notes.trim())===Mo.hasNotes)&&(!Mo.city||(oi.city||"").toLowerCase().includes(Mo.city.toLowerCase()))&&(!Mo.state||(oi.state||"").toLowerCase().includes(Mo.state.toLowerCase()))&&(!Mo.zip||((oi.zip||"")+(oi.zip_code||"")).toLowerCase().includes(Mo.zip.toLowerCase()))&&(!Mo.birthdayMonth||!!oi.birthday&&ih(oi.birthday).getMonth()+1===Mo.birthdayMonth)&&(!Mo.anniversaryMonth||((Mo.anniversaryField||"home_anniversary")==="home_anniversary"?!!oi.home_anniversary&&ih(oi.home_anniversary).getMonth()+1===Mo.anniversaryMonth:!!oi.wedding_anniversary&&ih(oi.wedding_anniversary).getMonth()+1===Mo.anniversaryMonth))&&(!Mo.dateAddedFrom||!!oi.created_at&&oi.created_at.slice(0,10)>=Mo.dateAddedFrom)&&(!Mo.dateAddedTo||!!oi.created_at&&oi.created_at.slice(0,10)<=Mo.dateAddedTo)&&(!Mo.leadSourceId||oi.lead_source_id===Mo.leadSourceId||!oi.lead_source_id&&Mo.leadSourceId==="none");return ja&&Il&&zo&&Cf&&zh});me==="not-touched-90"?Ss=Ss.filter(fa=>{const zn=fa.relationshipScore.daysSinceTouch;return zn===null||zn>90}):me==="at-risk"?Ss=Ss.filter(fa=>fa.relationshipScore.status==="at-risk"):me==="cooling"?Ss=Ss.filter(fa=>fa.relationshipScore.status==="cooling"):me==="warm"?Ss=Ss.filter(fa=>fa.relationshipScore.status==="warm"):me==="has-deal"?Ss=Ss.filter(fa=>_&&_[fa.id]):me==="no-deal"?Ss=Ss.filter(fa=>!_||!_[fa.id]):me==="open-house"?Ss=Ss.filter(fa=>{var Rr;return(((Rr=fa.lead_source_ref)==null?void 0:Rr.name)||fa.lead_source)==="Open House"}):me==="website-active"?Ss=Ss.filter(fa=>g.has(fa.id)):me==="never-contacted"?Ss=Ss.filter(fa=>fa.relationshipScore.daysSinceTouch===null):me==="vips"?Ss=Ss.filter(fa=>fa.relationshipScore.score>=80):me==="missing-info"?Ss=Ss.filter(fa=>Z7t(fa)):me==="birthdays-soon"?Ss=Ss.filter(fa=>{const zn=OR(fa.birthday);return zn!==null&&zn<=30}):me==="anniversary-soon"?Ss=Ss.filter(fa=>{const zn=OR(fa.home_anniversary);return zn!==null&&zn<=30}):me==="in-drip"?Ss=Ss.filter(fa=>((y==null?void 0:y[fa.id])??0)>0):me==="not-in-drip"&&(Ss=Ss.filter(fa=>((y==null?void 0:y[fa.id])??0)===0));const wa=ve;if(wa.lastActive||wa.registered||wa.viewedListing||wa.savedProperty||wa.hasSavedSearch||wa.requestedShowing||wa.requestedValuation||wa.websiteActiveOnly){const fa=Date.now(),zn={today:24*60*60*1e3,"7d":7*24*60*60*1e3,"30d":30*24*60*60*1e3,"90d":90*24*60*60*1e3};Ss=Ss.filter(Rr=>{const ja=Ue.get(Rr.id);if(wa.lastActive==="never"){if(ja!=null&&ja.lastActiveAt)return!1}else if(wa.lastActive){const Il=fa-zn[wa.lastActive];if(!(ja!=null&&ja.lastActiveAt)||new Date(ja.lastActiveAt).getTime()0)||wa.viewedListing==="multiple7d"&&!(ja&&ja.propertyViewCount7d>=3)||wa.savedProperty&&!(ja&&ja.savedListingCount>0)||wa.hasSavedSearch&&!(ja&&ja.activeSavedSearchCount>0)||wa.requestedShowing&&!(ja&&ja.showingRequests>0)||wa.requestedValuation&&!(ja&&ja.valuationRequests>0)||wa.websiteActiveOnly&&!g.has(Rr.id))})}return Ss=[...Ss].sort((fa,zn)=>{switch(te){case"important-dates":{const Rr=OR(fa.birthday),ja=OR(zn.birthday),Il=OR(fa.home_anniversary),zo=OR(zn.home_anniversary),Hl=[Rr,Il].filter(oi=>oi!==null).sort((oi,Mo)=>(oi??1/0)-(Mo??1/0))[0]??1/0,Cf=[ja,zo].filter(oi=>oi!==null).sort((oi,Mo)=>(oi??1/0)-(Mo??1/0))[0]??1/0;return Hl-Cf}case"last-touched":{const Rr=fa.relationshipScore.lastTouchDate,ja=zn.relationshipScore.lastTouchDate;return!Rr&&!ja?0:Rr?ja?new Date(Rr).getTime()-new Date(ja).getTime():1:-1}case"next-touch":{const Rr=fa.relationshipScore.daysSinceTouch,ja=zn.relationshipScore.daysSinceTouch;return Rr===null&&ja===null?0:Rr===null?-1:ja===null?1:ja-Rr}case"score":return fa.relationshipScore.score-zn.relationshipScore.score;case"date-added":{const Rr=fa.created_at,ja=zn.created_at;return!Rr&&!ja?0:Rr?ja?new Date(ja).getTime()-new Date(Rr).getTime():-1:1}case"last-name":{const Rr=(fa.last_name||"").toLowerCase(),ja=(zn.last_name||"").toLowerCase();if(Rr!==ja)return Rr.localeCompare(ja);const Il=(fa.first_name||"").toLowerCase(),zo=(zn.first_name||"").toLowerCase();return Il.localeCompare(zo)}case"name":default:{const Rr=`${fa.first_name||""} ${fa.last_name||""}`.toLowerCase(),ja=`${zn.first_name||""} ${zn.last_name||""}`.toLowerCase();return Rr.localeCompare(ja)}}}),Ss},[m,G,ee,A,I,me,te,_,C,g,y,fe,ve,Ue,Ei]),Tn=co.length,Mr=Math.max(1,Math.ceil(Tn/st)),Aa=Math.min(Ut,Mr),Lo=k.useMemo(()=>{const Ss=(Aa-1)*st;return co.slice(Ss,Ss+st)},[co,Aa,st]),Ac=k.useMemo(()=>{const Ss=(m||[]).length;return{total:Ss,label:Ss===0?"Build your database — add or import your first contacts.":`${Ss.toLocaleString()} ${Ss===1?"person":"people"} in your database`}},[m]),vl=k.useMemo(()=>{const Ss=m||[],wa=Ss.filter(Rr=>{var ja;return((ja=Rr.relationshipScore)==null?void 0:ja.status)==="at-risk"}).length,Ci=Ss.filter(Rr=>{var Il;const ja=(Il=Rr.relationshipScore)==null?void 0:Il.daysSinceTouch;return typeof ja=="number"&&ja<=7}).length,fa=new Date().getMonth()+1,zn=Ss.filter(Rr=>Rr.birthday?String(Rr.birthday).split(/[-/T]/).map(Number)[1]===fa:!1).length;return[{label:"Total contacts",value:Ac.total.toLocaleString(),onClick:()=>{Q("all"),xs(1)},active:me==="all"},{label:"Needs attention",value:wa,onClick:()=>{Q("at-risk"),xs(1)},active:me==="at-risk"},{label:"Touched this week",value:Ci,onClick:()=>{Q("warm"),xs(1)},active:me==="warm"},{label:"Birthdays this month",value:zn,onClick:()=>{Q("birthdays-soon"),xs(1)},active:me==="birthdays-soon"}]},[m,Ac.total,me,xs]),Ol=k.useCallback(Ss=>{const wa=new URLSearchParams;G&&wa.set("search",G),ee!=="all"&&wa.set("type",ee),me!=="all"&&wa.set("filter",me),A.size>0&&(wa.set("tags",Array.from(A).join(",")),wa.set("tagMode",I));const Ci=wa.toString();s(`/mission-control/contacts/${Ss}${Ci?`?${Ci}`:""}`)},[s,G,ee,me,A,I]),To=k.useRef(!1);k.useEffect(()=>{if(!To.current){To.current=!0;return}xs(1)},[G,ee,A,I,me,te,fe,ve]);const _a=k.useCallback(()=>{rt(!1),at(Ss=>Ss.size>0?new Set:new Set(Lo.map(wa=>wa.id)))},[Lo]),$o=k.useCallback(()=>{rt(!0),at(new Set(co.map(Ss=>Ss.id)))},[co]),[jh,Mu]=k.useState(null),dh=k.useCallback((Ss,wa)=>{H(Ss.search||""),oe(Ss.type||"all"),Q(Ss.status||"all"),he(Ss.behavior||{}),le(wa||"name")},[]),Jr=()=>{Hr({first_name:"",last_name:"",email:"",phone:"",address:"",city:"",state:"",zip_code:"",birthday:"",home_anniversary:"",spouse_name:"",spouse_email:"",lead_source_id:"",notes:"",tagIds:[]})},Uo=async Ss=>{Ss.preventDefault();const wa={...Yn,lead_source_id:Yn.lead_source_id||null};Ee?(await O.mutateAsync({id:Ee.id,...wa}),Re(null)):(await R.mutateAsync(wa),Ye(!1)),Jr()},fc=async Ss=>{await io("Are you sure you want to delete this contact?")&&await B.mutateAsync(Ss)};return e.jsx(Xs,{title:"Contacts",description:"Manage your InnerCircle contacts",children:e.jsxs("div",{className:"space-y-6 overflow-x-hidden",children:[e.jsx(y5n,{totalLabel:Ac.label,stats:vl,search:G,onSearchChange:H,onAddContact:()=>Ye(!0),onImportCsv:()=>Fe(!0),onImportPhone:()=>Ge(!0),onManageTags:()=>Ns(!0),onHeatMap:()=>se(!0),viewMode:jt,onViewModeChange:Ss=>gt(Ss),showTeamTab:!!Ts&&(Ts.team.contact_visibility==="full_team"||Ts.team.contact_visibility==="leader_only"&&Ts.role==="team_leader"),showLeadPondTab:!!(Ts!=null&&Ts.team.lead_pond_enabled),extraActions:e.jsx(tSn,{})}),jt==="team"?e.jsx(tYe,{}):jt==="lead-pond"&&Ts?e.jsx(sYe,{teamId:Ts.teamId}):e.jsxs(e.Fragment,{children:[e.jsx(_5n,{contacts:m,contactDealsMap:_,websiteActiveIds:g,totalCount:(m||[]).length,activeViewId:jh,currentFilters:{search:G,type:ee,status:me,behavior:ve},currentSortBy:te,onApplyView:(Ss,wa,Ci)=>{Mu(Ss),dh(wa,Ci),xs(1)},onClearAll:()=>{Mu(null),dh({search:"",type:"all",status:"all",behavior:{}},"name"),xs(1)},activeKey:{"at-risk":"needs-attention",cooling:"cooling","not-touched-90":"stale-90","never-contacted":"never-contacted","birthdays-soon":"birthdays-soon","anniversary-soon":"anniversary-soon","has-deal":"has-deal","website-active":"website-active",vips:"vips","missing-info":"missing-info"}[me]??null,onSelectSegment:Ss=>{const Ci=Ss?{"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"}[Ss]:"all";Q(Ci),xs(1)}}),e.jsxs(we,{className:"overflow-hidden",children:[e.jsxs("div",{className:"p-3 sm:p-4 bg-background",children:[e.jsx("div",{className:"sm:hidden space-y-3",children:e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs(D_,{children:[e.jsx(uee,{asChild:!0,children:e.jsxs($,{variant:"outline",className:"h-10 flex-1 rounded-xl relative gap-2","aria-label":"Filters",children:[e.jsx(tM,{className:"h-4 w-4"}),"Filters & Views",(()=>{const Ss=(ee!=="all"?1:0)+(me!=="all"?1:0)+(fe!=="all"?1:0)+A.size+Se;return Ss>0?e.jsx("span",{className:"absolute -top-1 -right-1 h-4 min-w-[16px] px-1 rounded-full bg-primary text-primary-foreground text-[10px] font-bold flex items-center justify-center",children:Ss}):null})()]})}),e.jsxs(Mb,{side:"bottom",className:"h-[85vh] rounded-t-2xl overflow-y-auto",children:[e.jsx(xj,{className:"text-left",children:e.jsx(yj,{children:"Filters & Views"})}),e.jsxs("div",{className:"space-y-5 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Type"}),e.jsxs(bs,{value:ee,onValueChange:oe,children:[e.jsx(ys,{className:"h-11 rounded-xl bg-muted/40",children:e.jsx(_s,{placeholder:"All Types"})}),e.jsxs(vs,{children:[e.jsx(We,{value:"all",children:"All Types"}),v==null?void 0:v.filter(Ss=>Ss.active).map(Ss=>e.jsx(We,{value:Ss.id,children:Ss.name},Ss.id))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Status"}),e.jsxs(bs,{value:me,onValueChange:Q,children:[e.jsx(ys,{className:"h-11 rounded-xl bg-muted/40",children:e.jsx(_s,{placeholder:"All Status"})}),e.jsxs(vs,{children:[e.jsx(We,{value:"all",children:"All Status"}),e.jsx(We,{value:"warm",children:"🟢 Warm"}),e.jsx(We,{value:"cooling",children:"🟡 Cooling Off"}),e.jsx(We,{value:"at-risk",children:"🔴 At Risk"}),e.jsx(We,{value:"has-deal",children:"📋 Has Deal"}),e.jsx(We,{value:"no-deal",children:"📭 No Deal"}),e.jsx(We,{value:"open-house",children:"🏠 Open House"}),x&&e.jsx(We,{value:"website-active",children:"🌐 Website Active"}),e.jsx(We,{value:"in-drip",children:"🌱 In Drip Campaign"}),e.jsx(We,{value:"not-in-drip",children:"🚫 Not In Drip"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Address"}),e.jsxs(bs,{value:fe,onValueChange:Ss=>_e(Ss),children:[e.jsx(ys,{className:"h-11 rounded-xl bg-muted/40",children:e.jsx(_s,{placeholder:"All Addresses"})}),e.jsxs(vs,{children:[e.jsx(We,{value:"all",children:"All Addresses"}),e.jsx(We,{value:"has-address",children:"Has Address"}),e.jsx(We,{value:"no-address",children:"No Address"})]})]})]}),j&&j.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(re,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Tags"}),e.jsxs("div",{className:"flex items-center gap-1 bg-muted rounded-md p-0.5",children:[e.jsx("button",{onClick:()=>P("any"),className:`px-2 py-0.5 rounded text-xs font-medium ${I==="any"?"bg-background shadow-sm":"text-muted-foreground"}`,children:"Any"}),e.jsx("button",{onClick:()=>P("all"),className:`px-2 py-0.5 rounded text-xs font-medium ${I==="all"?"bg-background shadow-sm":"text-muted-foreground"}`,children:"All"})]})]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:j.map(Ss=>{const wa=A.has(Ss.id);return e.jsxs("button",{onClick:()=>{M(Ci=>{const fa=new Set(Ci);return fa.has(Ss.id)?fa.delete(Ss.id):fa.add(Ss.id),fa})},className:`inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full text-xs border transition-colors ${wa?"bg-primary text-primary-foreground border-primary":"bg-background border-border"}`,children:[e.jsx("span",{className:"h-2 w-2 rounded-full",style:{backgroundColor:Ss.color}}),Ss.name]},Ss.id)})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Sort by"}),e.jsxs(bs,{value:te,onValueChange:le,children:[e.jsx(ys,{className:"h-11 rounded-xl bg-muted/40",children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"name",children:"Name (A-Z)"}),e.jsx(We,{value:"last-name",children:"Last Name (A-Z)"}),e.jsx(We,{value:"important-dates",children:"Important Dates"}),e.jsx(We,{value:"last-touched",children:"Last Touched"}),e.jsx(We,{value:"next-touch",children:"Next Touch Due"}),e.jsx(We,{value:"score",children:"Relationship Score"}),e.jsx(We,{value:"date-added",children:"Date Added"})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2 pt-2",children:[e.jsxs($,{variant:"outline",className:"h-11 rounded-xl gap-1.5",onClick:()=>Ie(!0),children:[e.jsx(kn,{className:"h-4 w-4"})," Advanced"]}),e.jsxs($,{variant:"outline",className:"h-11 rounded-xl gap-1.5",onClick:()=>Ns(!0),children:[e.jsx(kg,{className:"h-4 w-4"})," Manage Tags"]})]}),e.jsx("div",{children:e.jsx(Eyt,{currentFilters:{search:G,type:ee,status:me,behavior:ve},currentSortBy:te,onApplySmartList:dh})}),e.jsx($,{variant:"ghost",className:"w-full h-11 rounded-xl text-muted-foreground",onClick:()=>{oe("all"),Q("all"),_e("all"),M(new Set),he({})},children:"Clear all filters"})]})]})]})})}),e.jsxs("div",{className:"hidden sm:flex items-center gap-3 flex-wrap",children:[e.jsxs("div",{className:"flex-1 min-w-[120px] text-sm text-muted-foreground",children:[Tn.toLocaleString()," ",Tn===1?"contact":"contacts"," shown"]}),e.jsxs(Xc,{children:[e.jsx(Qc,{asChild:!0,children:e.jsx($,{variant:"outline",size:"icon",className:"h-10 w-10 rounded-xl",title:"Sort contacts",children:e.jsx(_2,{className:"h-4 w-4"})})}),e.jsxs(Bc,{align:"end",className:"w-56 p-2",children:[e.jsx("div",{className:"text-xs font-semibold text-muted-foreground px-2 py-1.5",children:"Sort by"}),[{v:"name",l:"Name (A-Z)"},{v:"last-name",l:"Last Name (A-Z)"},{v:"important-dates",l:"Important Dates"},{v:"last-touched",l:"Last Touched"},{v:"next-touch",l:"Next Touch Due"},{v:"score",l:"Relationship Score"},{v:"date-added",l:"Date Added"}].map(Ss=>e.jsx("button",{onClick:()=>le(Ss.v),className:`w-full text-left px-2 py-1.5 rounded-md text-sm hover:bg-accent transition-colors ${te===Ss.v?"bg-accent font-medium text-primary":""}`,children:Ss.l},Ss.v))]})]})]})]}),e.jsxs("div",{className:"hidden sm:flex px-3 sm:px-4 py-3 bg-muted/40 border-t flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs(bs,{value:ee,onValueChange:oe,children:[e.jsx(ys,{className:"h-8 text-xs rounded-lg bg-background w-auto min-w-[130px] gap-2",children:e.jsx(_s,{placeholder:"All Types"})}),e.jsxs(vs,{children:[e.jsx(We,{value:"all",children:"All Types"}),v==null?void 0:v.filter(Ss=>Ss.active).map(Ss=>e.jsx(We,{value:Ss.id,children:Ss.name},Ss.id))]})]}),e.jsxs(bs,{value:me,onValueChange:Q,children:[e.jsx(ys,{className:"h-8 text-xs rounded-lg bg-background w-auto min-w-[130px] gap-2",children:e.jsx(_s,{placeholder:"All Status"})}),e.jsxs(vs,{children:[e.jsx(We,{value:"all",children:"All Status"}),e.jsx(We,{value:"warm",children:"🟢 Warm"}),e.jsx(We,{value:"cooling",children:"🟡 Cooling Off"}),e.jsx(We,{value:"at-risk",children:"🔴 At Risk"}),e.jsx(We,{value:"has-deal",children:"📋 Has Deal"}),e.jsx(We,{value:"no-deal",children:"📭 No Deal"}),e.jsx(We,{value:"open-house",children:"🏠 Open House"}),x&&e.jsx(We,{value:"website-active",children:"🌐 Website Active"}),e.jsx(We,{value:"in-drip",children:"🌱 In Drip Campaign"}),e.jsx(We,{value:"not-in-drip",children:"🚫 Not In Drip"})]})]}),e.jsxs(bs,{value:fe,onValueChange:Ss=>_e(Ss),children:[e.jsx(ys,{className:"h-8 text-xs rounded-lg bg-background w-auto min-w-[130px] gap-2",children:e.jsx(_s,{placeholder:"All Addresses"})}),e.jsxs(vs,{children:[e.jsx(We,{value:"all",children:"All Addresses"}),e.jsx(We,{value:"has-address",children:"Has Address"}),e.jsx(We,{value:"no-address",children:"No Address"})]})]}),j&&j.length>0&&e.jsxs("div",{className:"inline-flex items-center bg-background border rounded-lg overflow-hidden h-8",children:[e.jsxs(Xc,{children:[e.jsx(Qc,{asChild:!0,children:e.jsxs("button",{className:"pl-2.5 pr-2 h-full text-xs font-medium text-muted-foreground hover:text-foreground inline-flex items-center gap-1.5",children:[e.jsx(kg,{className:"h-3.5 w-3.5"}),A.size===0?"Filter by Tags":`${A.size} tag${A.size>1?"s":""}`]})}),e.jsx(Bc,{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 ${I==="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 ${I==="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:j.map(Ss=>{const wa=A.has(Ss.id);return e.jsxs("button",{onClick:()=>{M(Ci=>{const fa=new Set(Ci);return fa.has(Ss.id)?fa.delete(Ss.id):fa.add(Ss.id),fa})},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(Li,{checked:wa,className:"pointer-events-none"}),e.jsx("div",{className:"h-2.5 w-2.5 rounded-full shrink-0",style:{backgroundColor:Ss.color}}),e.jsx("span",{className:"flex-1 text-left truncate",children:Ss.name})]},Ss.id)})}),A.size>0&&e.jsx($,{variant:"ghost",size:"sm",className:"w-full text-xs",onClick:()=>M(new Set),children:"Clear tags"})]})})]}),e.jsx("div",{className:"w-px h-4 bg-border"}),e.jsxs(Au,{children:[e.jsx(Eu,{asChild:!0,children:e.jsx("button",{className:"px-2 h-full text-muted-foreground hover:text-primary transition-colors",title:"Manage tags & lead sources",children:e.jsx(Yc,{className:"h-3.5 w-3.5"})})}),e.jsxs(gu,{align:"end",children:[e.jsxs(Pa,{onClick:()=>Ns(!0),children:[e.jsx(kg,{className:"h-4 w-4 mr-2"}),"Manage Tags"]}),e.jsxs(Pa,{onClick:()=>Bs(!0),children:[e.jsx(pb,{className:"h-4 w-4 mr-2"}),"Manage Lead Sources"]})]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Eyt,{currentFilters:{search:G,type:ee,status:me,behavior:ve},currentSortBy:te,onApplySmartList:dh}),e.jsx("div",{className:"h-5 w-px bg-border"}),e.jsxs($,{variant:"outline",size:"sm",className:"gap-1.5 h-8 rounded-lg border-[#2a4c64]/20 text-[#2a4c64] hover:bg-[#2a4c64]/5 hover:text-[#2a4c64]",onClick:()=>Ie(!0),children:[e.jsx(kn,{className:"h-3.5 w-3.5"}),"Advanced Filters",Se>0&&e.jsx(qe,{variant:"secondary",className:"h-5 px-1.5 text-[10px]",children:Se})]}),e.jsx(j5n,{columns:l,onToggle:o,onReset:c})]})]}),Se>0&&e.jsx("div",{className:"px-3 sm:px-4 py-3 border-t bg-background",children:e.jsx(XSn,{behavior:ve,onRemove:Ss=>he(wa=>{const Ci={...wa};return delete Ci[Ss],Ci}),onClearAll:()=>he({})})})]}),e.jsx(ZSn,{open:Te,onOpenChange:Ie,hasLeadSite:Be||x,behavior:ve,onApply:he,selectedType:ee,onSelectedTypeChange:oe,relationshipTypes:v}),e.jsx(KSn,{selectedIds:et,contacts:co,onClearSelection:()=>{at(new Set),rt(!1)},showLeadPondAction:Sr,onSendToLeadPond:Ba,showTransferAction:Qn,onTransfer:dn}),et.size>0&&et.size===Lo.length&&!wt&&Tn>st&&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 ",Lo.length," contacts on this page are selected."]}),e.jsxs($,{variant:"link",size:"sm",className:"h-auto p-0 font-semibold",onClick:$o,children:["Select all ",Tn.toLocaleString()," matching contacts"]})]}),wt&&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 ",Tn.toLocaleString()," matching contacts are selected.",e.jsx($,{variant:"link",size:"sm",className:"h-auto p-0",onClick:()=>{at(new Set),rt(!1)},children:"Clear selection"})]}),Tn>st&&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 ",(Aa-1)*st+1,"–",Math.min(Aa*st,Tn)," of ",Tn.toLocaleString()," contacts"]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx($,{variant:"outline",size:"sm",disabled:Aa<=1,onClick:()=>xs(1),children:"First"}),e.jsx($,{variant:"outline",size:"sm",disabled:Aa<=1,onClick:()=>xs(Ss=>Ss-1),children:e.jsx(Ld,{className:"h-4 w-4"})}),e.jsxs("span",{className:"px-3 text-sm font-medium",children:["Page ",Aa," of ",Mr]}),e.jsx($,{variant:"outline",size:"sm",disabled:Aa>=Mr,onClick:()=>xs(Ss=>Ss+1),children:e.jsx(fi,{className:"h-4 w-4"})}),e.jsx($,{variant:"outline",size:"sm",disabled:Aa>=Mr,onClick:()=>xs(Mr),children:"Last"})]})]}),a?e.jsx("div",{className:"space-y-3",children:p?e.jsx(b5n,{}):co.length===0?e.jsx(we,{children:e.jsx(Fyt,{filtered:!!G||ee!=="all"||me!=="all"||fe!=="all"||A.size>0,onAdd:()=>Ye(!0),onImport:()=>Fe(!0),onClearFilters:()=>{H(""),oe("all"),Q("all"),_e("all"),M(new Set),he({})}})}):Lo.map(Ss=>{var Ci,fa,zn;const{relationshipScore:wa}=Ss;return e.jsx(we,{className:"cursor-pointer hover:bg-accent/50 transition-colors",onClick:()=>Ol(Ss.id),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:[Ss.first_name," ",Ss.last_name]}),e.jsx(Iyt,{count:(y==null?void 0:y[Ss.id])??0}),e.jsx(fi,{className:"h-4 w-4 text-muted-foreground shrink-0 ml-auto"})]}),e.jsxs("div",{className:"space-y-1 text-sm mb-3",children:[Ss.email&&e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(pn,{className:"h-3.5 w-3.5 shrink-0"}),e.jsx("span",{className:"truncate",children:Ss.email})]}),Ss.phone&&e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(ka,{className:"h-3.5 w-3.5 shrink-0"}),e.jsx("span",{children:Ss.phone})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-1 mb-2",children:[e.jsx(KBe,{score:wa,size:"sm"}),e.jsx(Syt,{contact:Ss}),(((Ci=Ss.lead_source_ref)==null?void 0:Ci.name)||Ss.lead_source)&&e.jsx(qe,{variant:"outline",className:"text-xs gap-1 border-primary/30 text-primary",children:((fa=Ss.lead_source_ref)==null?void 0:fa.name)||Ss.lead_source}),(zn=Ss.tags)==null?void 0:zn.map(Rr=>{var ja;return e.jsx(qe,{variant:"secondary",className:"text-xs",children:(ja=Rr.relationship_type)==null?void 0:ja.name},Rr.id)}),e.jsx(Dyt,{contactId:Ss.id,tags:C==null?void 0:C.filter(Rr=>Rr.contact_id===Ss.id)}),e.jsx(Pyt,{deal:_==null?void 0:_[Ss.id]})]}),e.jsx(Myt,{birthday:Ss.birthday,homeAnniversary:Ss.home_anniversary,weddingAnniversary:Ss.wedding_anniversary,className:"mb-2",contactId:Ss.id,contactName:`${Ss.first_name}${Ss.last_name?" "+Ss.last_name:""}`,contactAddress:[Ss.address,Ss.city,Ss.state].filter(Boolean).join(", ")}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 text-xs text-muted-foreground",children:[wa.lastTouchDate?e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(sa,{className:"h-3 w-3"}),Ys(new Date(wa.lastTouchDate),"MMM d")]}):e.jsx("span",{className:"italic",children:"Never contacted"}),Ss.birthday&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(ha,{className:"h-3 w-3"}),Ys(ih(Ss.birthday),"MMM d")]}),Ss.home_anniversary&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(ua,{className:"h-3 w-3"}),Ys(ih(Ss.home_anniversary),"MMM d")]}),Ss.created_at&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(nn,{className:"h-3 w-3"}),"Added ",Ys(new Date(Ss.created_at),"MMM d, yyyy")]})]})]}),e.jsx("div",{className:"ml-2",onClick:Rr=>Rr.stopPropagation(),children:e.jsx(Ayt,{contact:Ss,onEdit:Re,onDelete:fc,onSnooze:(Rr,ja)=>{tt(Rr),nt(ja)},showLeadPondAction:Sr,onSendToLeadPond:ti,showTransferAction:Qn,onTransfer:Zr})})]})})},Ss.id)})}):e.jsx(we,{children:e.jsx(De,{className:"p-0 overflow-x-auto",children:e.jsxs(Qa,{className:"min-w-[800px]",children:[e.jsx(Ja,{className:"sticky top-0 z-10 bg-card/95 backdrop-blur supports-[backdrop-filter]:bg-card/80",children:e.jsxs(vn,{className:"hover:bg-transparent",children:[e.jsx(Dt,{className:"w-[40px]",children:e.jsx(Li,{checked:Lo.length>0&&Lo.every(Ss=>et.has(Ss.id)),onCheckedChange:()=>_a()})}),e.jsx(Dt,{children:e.jsxs("button",{onClick:()=>le(Ss=>Ss==="last-name"?"name":"last-name"),className:"group inline-flex items-center gap-1 font-medium text-muted-foreground hover:text-foreground transition-colors",children:["Contact",te==="name"&&e.jsx(fi,{className:"h-3 w-3 rotate-90 text-primary"}),te==="last-name"&&e.jsx(fi,{className:"h-3 w-3 -rotate-90 text-primary"})]})}),l.relationship&&e.jsx(Dt,{children:"Relationship"}),l.stage&&e.jsx(Dt,{children:"Stage"}),l.leadSource&&e.jsx(Dt,{children:"Lead Source"}),l.tags&&e.jsx(Dt,{children:"Tags"}),l.lastTouch&&e.jsx(Dt,{children:"Last Touch"}),l.nextAction&&e.jsx(Dt,{children:"Next Action"}),l.dealValue&&e.jsx(Dt,{title:"Total value of deals linked to this contact in your pipeline",children:"Pipeline Value"}),l.email&&e.jsx(Dt,{children:"Email"}),l.phone&&e.jsx(Dt,{children:"Phone"}),l.address&&e.jsx(Dt,{children:"Address"}),l.birthday&&e.jsx(Dt,{children:"Birthday"}),e.jsx(Dt,{className:"w-[50px]"})]})}),e.jsx(ei,{children:p?e.jsx(v5n,{columns:2+Object.values(l).filter(Boolean).length}):co.length===0?e.jsx(vn,{className:"hover:bg-transparent",children:e.jsx(_t,{colSpan:3+Object.values(l).filter(Boolean).length,className:"p-0",children:e.jsx(Fyt,{filtered:!!G||ee!=="all"||me!=="all"||fe!=="all"||A.size>0,onAdd:()=>Ye(!0),onImport:()=>Fe(!0),onClearFilters:()=>{H(""),oe("all"),Q("all"),_e("all"),M(new Set),he({})}})})}):Lo.map(Ss=>{var fa;const{relationshipScore:wa}=Ss,Ci=_==null?void 0:_[Ss.id];return e.jsxs(vn,{className:`group cursor-pointer border-border/60 transition-colors hover:bg-accent/40 [&>td]:py-3.5 ${et.has(Ss.id)?"bg-accent/30":""}`,onClick:()=>Ol(Ss.id),children:[e.jsx(_t,{onClick:zn=>zn.stopPropagation(),children:e.jsx(Li,{checked:et.has(Ss.id),onCheckedChange:()=>lo(Ss.id)})}),e.jsx(_t,{className:"min-w-[220px]",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Y7t,{firstName:Ss.first_name,lastName:Ss.last_name,avatarUrl:Ss.avatar_url,email:Ss.email,size:36}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsxs("span",{className:"font-medium truncate",children:[Ss.first_name," ",Ss.last_name]}),e.jsx(x5n,{linked:!!Ss.spouse_contact_id||!!Ss.spouse_name,spouseName:Ss.spouse_contact_id&&fo[Ss.spouse_contact_id]||Ss.spouse_name||null}),e.jsx(Iyt,{count:(y==null?void 0:y[Ss.id])??0})]}),Ss.email&&!l.email&&e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:Ss.email}),Ss.phone&&!l.phone&&e.jsx("p",{className:"text-xs text-muted-foreground",children:Ss.phone})]})]})}),l.relationship&&e.jsx(_t,{children:e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx(m5n,{score:wa.score,status:wa.status}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium leading-tight",children:wa.status==="warm"?"Strong":wa.status==="cooling"?"Cooling":"At Risk"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:wa.daysSinceTouch===null?"Never contacted":wa.daysSinceTouch===0?"Touched today":`${wa.daysSinceTouch}d since touch`})]})]})}),l.stage&&e.jsx(_t,{children:e.jsx(Pyt,{deal:Ci})}),l.leadSource&&e.jsx(_t,{className:"text-sm text-muted-foreground max-w-[160px] truncate",children:((fa=Ss.lead_source_ref)==null?void 0:fa.name)||Ss.lead_source||"—"}),l.tags&&e.jsx(_t,{children:e.jsx("div",{className:"flex flex-wrap items-center gap-1 max-w-[220px]",children:e.jsx(Dyt,{contactId:Ss.id,tags:C==null?void 0:C.filter(zn=>zn.contact_id===Ss.id)})})}),l.lastTouch&&e.jsx(_t,{children:wa.lastTouchDate?e.jsxs("div",{className:"flex items-center gap-1.5 text-sm text-muted-foreground",children:[e.jsx(sa,{className:"h-3.5 w-3.5"}),Ys(new Date(wa.lastTouchDate),"MMM d, yyyy")]}):e.jsx("span",{className:"text-xs italic text-muted-foreground",children:"No activity"})}),l.nextAction&&e.jsx(_t,{children:e.jsxs("div",{className:"flex flex-col items-start gap-1",children:[e.jsx(Syt,{contact:Ss}),e.jsx(Myt,{birthday:Ss.birthday,homeAnniversary:Ss.home_anniversary,weddingAnniversary:Ss.wedding_anniversary,contactId:Ss.id,contactName:`${Ss.first_name}${Ss.last_name?" "+Ss.last_name:""}`,contactAddress:[Ss.address,Ss.city,Ss.state].filter(Boolean).join(", ")})]})}),l.dealValue&&e.jsx(_t,{children:(()=>{const zn=(Ci==null?void 0:Ci.sale_price)??(Ci==null?void 0:Ci.expected_price);return zn?e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-semibold",children:yh(Number(zn))}),(Ci==null?void 0:Ci.deal_type)&&e.jsx("p",{className:"text-xs text-muted-foreground capitalize",children:String(Ci.deal_type).replace(/_/g," ")})]}):e.jsx("span",{className:"text-sm text-muted-foreground",children:"—"})})()}),l.email&&e.jsx(_t,{className:"text-sm text-muted-foreground max-w-[220px] truncate",children:Ss.email||"—"}),l.phone&&e.jsx(_t,{className:"text-sm text-muted-foreground whitespace-nowrap",children:Ss.phone||"—"}),l.address&&e.jsx(_t,{className:"text-sm text-muted-foreground max-w-[220px] truncate",children:[Ss.address,Ss.city,Ss.state].filter(Boolean).join(", ")||"—"}),l.birthday&&e.jsx(_t,{className:"text-sm text-muted-foreground whitespace-nowrap",children:Ss.birthday?(()=>{const[zn,Rr,ja]=String(Ss.birthday).split(/[-/T]/).map(Number);return Rr&&ja?`${Rr}/${ja}${zn&&zn>1900?`/${zn}`:""}`:"—"})():"—"}),e.jsx(_t,{onClick:zn=>zn.stopPropagation(),children:e.jsx(Ayt,{contact:Ss,onEdit:Re,onDelete:fc,onSnooze:(zn,Rr)=>{tt(zn),nt(Rr)},showLeadPondAction:Sr,onSendToLeadPond:ti,showTransferAction:Qn,onTransfer:Zr})})]},Ss.id)})})]})})}),Tn>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 ",(Aa-1)*st+1,"–",Math.min(Aa*st,Tn)," of ",Tn.toLocaleString()," contacts"]}),e.jsxs(bs,{value:String(st),onValueChange:Ss=>{dt(Number(Ss)),xs(1)},children:[e.jsx(ys,{className:"w-[80px] h-8",children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"50",children:"50"}),e.jsx(We,{value:"100",children:"100"}),e.jsx(We,{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($,{variant:"outline",size:"sm",disabled:Aa<=1,onClick:()=>xs(1),children:"First"}),e.jsx($,{variant:"outline",size:"sm",disabled:Aa<=1,onClick:()=>xs(Ss=>Ss-1),children:e.jsx(Ld,{className:"h-4 w-4"})}),e.jsxs("span",{className:"px-3 text-sm font-medium",children:["Page ",Aa," of ",Mr]}),e.jsx($,{variant:"outline",size:"sm",disabled:Aa>=Mr,onClick:()=>xs(Ss=>Ss+1),children:e.jsx(fi,{className:"h-4 w-4"})}),e.jsx($,{variant:"outline",size:"sm",disabled:Aa>=Mr,onClick:()=>xs(Mr),children:"Last"})]})]}),e.jsx(zs,{open:je||!!Ee,onOpenChange:Ss=>{Ss||(Ye(!1),Re(null),Jr())},children:e.jsxs(Rs,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(Vs,{children:e.jsx($s,{children:Ee?"Edit Contact":"Add Contact"})}),e.jsxs("form",{onSubmit:Uo,className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(re,{htmlFor:"first_name",children:"First Name *"}),e.jsx(be,{id:"first_name",value:Yn.first_name,onChange:Ss=>Hr({...Yn,first_name:Ss.target.value}),required:!0})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"last_name",children:"Last Name"}),e.jsx(be,{id:"last_name",value:Yn.last_name,onChange:Ss=>Hr({...Yn,last_name:Ss.target.value})})]})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"email",children:"Email"}),e.jsx(be,{id:"email",type:"email",value:Yn.email,onChange:Ss=>Hr({...Yn,email:Ss.target.value})})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"phone",children:"Phone"}),e.jsx(be,{id:"phone",value:Yn.phone,onChange:Ss=>Hr({...Yn,phone:Ss.target.value})})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"address",children:"Address"}),e.jsx(be,{id:"address",value:Yn.address,onChange:Ss=>Hr({...Yn,address:Ss.target.value}),placeholder:"Street address"})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsxs("div",{children:[e.jsx(re,{htmlFor:"city",children:"City"}),e.jsx(be,{id:"city",value:Yn.city,onChange:Ss=>Hr({...Yn,city:Ss.target.value})})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"state",children:"State"}),e.jsx(be,{id:"state",value:Yn.state,onChange:Ss=>Hr({...Yn,state:Ss.target.value})})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"zip_code",children:"Zip"}),e.jsx(be,{id:"zip_code",value:Yn.zip_code,onChange:Ss=>Hr({...Yn,zip_code:Ss.target.value})})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(re,{htmlFor:"birthday",children:"Birthday"}),e.jsx(be,{id:"birthday",type:"date",value:Yn.birthday,onChange:Ss=>Hr({...Yn,birthday:Ss.target.value})})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"home_anniversary",children:"Home Anniversary"}),e.jsx(be,{id:"home_anniversary",type:"date",value:Yn.home_anniversary,onChange:Ss=>Hr({...Yn,home_anniversary:Ss.target.value})})]})]}),Ee&&e.jsx(YBe,{contactId:Ee.id,currentSpouseContactId:(Ee==null?void 0:Ee.spouse_contact_id)||null,currentSpouseName:(Ee==null?void 0:Ee.spouse_name)||null,currentSpouseEmail:(Ee==null?void 0:Ee.spouse_email)||null,onLink:Ss=>U.mutate({contactId:Ee.id,spouseContactId:Ss}),onUnlink:()=>U.mutate({contactId:Ee.id,spouseContactId:null}),isEditing:!0}),e.jsx(K7t,{value:Yn.lead_source_id,onChange:Ss=>Hr({...Yn,lead_source_id:Ss})}),e.jsxs("div",{children:[e.jsx(re,{children:"Relationship Types"}),e.jsx("div",{className:"flex flex-wrap gap-2 mt-2",children:v==null?void 0:v.filter(Ss=>Ss.active).map(Ss=>e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[e.jsx(Li,{checked:Yn.tagIds.includes(Ss.id),onCheckedChange:wa=>{Hr(wa?{...Yn,tagIds:[...Yn.tagIds,Ss.id]}:{...Yn,tagIds:Yn.tagIds.filter(Ci=>Ci!==Ss.id)})}}),e.jsx("span",{className:"text-sm",children:Ss.name})]},Ss.id))})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"notes",children:"Notes"}),e.jsx(Ls,{id:"notes",value:Yn.notes,onChange:Ss=>Hr({...Yn,notes:Ss.target.value}),rows:3})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx($,{type:"button",variant:"outline",onClick:()=>{Ye(!1),Re(null),Jr()},children:"Cancel"}),e.jsxs($,{type:"submit",disabled:R.isPending||O.isPending,children:[Ee?"Update":"Create"," Contact"]})]})]})]})}),e.jsx(fSn,{open:ke,onOpenChange:Fe,relationshipTypes:(v==null?void 0:v.filter(Ss=>Ss.active))||[],onSuccess:()=>{Fe(!1)}}),e.jsx(xSn,{open:Oe,onOpenChange:Ge,onComplete:()=>Ge(!1)}),e.jsx(nTe,{open:!!yt,onOpenChange:Ss=>{Ss||tt(null)},contactId:yt||"",contactName:ut}),e.jsx(c5n,{open:rs,onOpenChange:Ns}),e.jsx(d5n,{open:us,onOpenChange:Bs}),e.jsx(n5n,{open:Y,onOpenChange:se,contacts:m||[],onCitySelect:Ss=>{H(Ss),xs(1)}}),e.jsx(kRt,{open:xn,onOpenChange:Ar,contactIds:En,contactNames:En.map(Ss=>{const wa=co.find(Ci=>Ci.id===Ss);return wa?`${wa.first_name} ${wa.last_name||""}`.trim():""}),onComplete:()=>{pr([]),at(new Set),rt(!1)}}),e.jsx(zs,{open:!!In,onOpenChange:Ss=>!Ss&&un(null),children:e.jsxs(Rs,{className:"sm:max-w-md",children:[e.jsx(Vs,{children:e.jsx($s,{children:"Choose a Lead Pond"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Sharing ",(In==null?void 0:In.length)||0," contact",((In==null?void 0:In.length)||0)===1?"":"s"," with your team."]}),e.jsxs(bs,{value:jr,onValueChange:Ln,children:[e.jsx(ys,{children:e.jsx(_s,{placeholder:"Select a pond"})}),e.jsx(vs,{children:js.map(Ss=>e.jsx(We,{value:Ss.id,children:Ss.name},Ss.id))})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx($,{variant:"outline",onClick:()=>un(null),children:"Cancel"}),e.jsx($,{onClick:()=>{In&&Kt(In,jr),un(null)},disabled:!jr,children:"Share to Pond"})]})]})]})})]})]})})}const k5n=5*1024*1024;function S5n({contactId:s,firstName:t,lastName:n,avatarUrl:r,email:a,size:i=88}){const l=k.useRef(null),o=ls(),[c,d]=k.useState(!1),u=()=>{o.invalidateQueries({queryKey:["innercircle-contacts"]}),o.invalidateQueries({queryKey:["innercircle-contact"]}),o.invalidateQueries({queryKey:["contact",s]})},h=async g=>{const{error:x}=await V.from("innercircle_contacts").update({avatar_url:g}).eq("id",s);if(x)throw x;u()},m=async g=>{var x;if(!g.type.startsWith("image/")){Ma({title:"Please choose an image file",variant:"destructive"});return}if(g.size>k5n){Ma({title:"Image too large",description:"Please use an image under 5MB.",variant:"destructive"});return}d(!0);try{const{data:y}=await V.auth.getUser(),v=(x=y.user)==null?void 0:x.id,_=(g.name.split(".").pop()||"jpg").toLowerCase(),j=`contacts/${v}/${s}-${Date.now()}.${_}`,{error:C}=await V.storage.from("avatars").upload(j,g,{upsert:!0,contentType:g.type});if(C)throw C;const{data:A}=V.storage.from("avatars").getPublicUrl(j);await h(A.publicUrl),Ma({title:"Photo updated"})}catch(y){Ma({title:"Upload failed",description:y.message,variant:"destructive"})}finally{d(!1),l.current&&(l.current.value="")}},p=async()=>{d(!0);try{await h(null),Ma({title:"Photo removed"})}catch(g){Ma({title:"Could not remove photo",description:g.message,variant:"destructive"})}finally{d(!1)}};return e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("button",{type:"button",onClick:()=>{var g;return(g=l.current)==null?void 0:g.click()},disabled:c,className:"relative group rounded-full focus:outline-none focus-visible:ring-2 focus-visible:ring-ring","aria-label":r?"Change contact photo":"Upload contact photo",children:[e.jsx(Y7t,{firstName:t,lastName:n,avatarUrl:r,email:a,size:i}),e.jsx("span",{className:"absolute inset-0 rounded-full bg-foreground/55 opacity-0 group-hover:opacity-100 transition-opacity flex items-center justify-center",children:c?e.jsx(Jt,{className:"h-5 w-5 text-background animate-spin"}):e.jsx(g0,{className:"h-5 w-5 text-background"})}),c&&e.jsx("span",{className:"absolute inset-0 rounded-full bg-foreground/55 flex items-center justify-center",children:e.jsx(Jt,{className:"h-5 w-5 text-background animate-spin"})})]}),r&&e.jsxs($,{variant:"ghost",size:"sm",className:"text-muted-foreground gap-1.5",onClick:p,disabled:c,children:[e.jsx(Un,{className:"h-3.5 w-3.5"}),"Remove"]}),e.jsx("input",{ref:l,type:"file",accept:"image/*",className:"hidden",onChange:g=>{var y;const x=(y=g.target.files)==null?void 0:y[0];x&&m(x)}})]})}const qyt="America/New_York";function C5n(s){const t=new Date(s),n=new Intl.DateTimeFormat("en-US",{timeZone:qyt,month:"short",day:"numeric",year:"numeric"}).format(t),r=new Intl.DateTimeFormat("en-US",{timeZone:qyt,hour:"numeric",minute:"2-digit"}).format(t);return`${n} · ${r}`}function A5n(s){const t=Date.now()-new Date(s).getTime(),n=Math.round(t/6e4);if(n<1)return"just now";if(n<60)return`${n}m ago`;const r=Math.round(n/60);if(r<24)return`${r}h ago`;const a=Math.round(r/24);return a<30?`${a}d ago`:`${Math.round(a/30)}mo ago`}function E5n({contactId:s,ownerUserId:t,legacyNote:n}){const r=ls(),[a,i]=k.useState(""),{data:l=[],isLoading:o}=pt({queryKey:["contact-notes",s],queryFn:async()=>{const{data:u,error:h}=await V.from("innercircle_contact_notes").select("id, body, source, author_name, created_at").eq("contact_id",s).order("created_at",{ascending:!1});if(h)throw h;return u||[]},enabled:!!s}),c=Nt({mutationFn:async u=>{var x,y,v;const{data:h}=await V.auth.getUser(),m=h.user,p=((x=m==null?void 0:m.user_metadata)==null?void 0:x.full_name)||[(y=m==null?void 0:m.user_metadata)==null?void 0:y.first_name,(v=m==null?void 0:m.user_metadata)==null?void 0:v.last_name].filter(Boolean).join(" ")||(m==null?void 0:m.email)||null,{error:g}=await V.from("innercircle_contact_notes").insert({contact_id:s,owner_user_id:t||(m==null?void 0:m.id),author_user_id:m==null?void 0:m.id,author_name:p,source:"agent",body:u});if(g)throw g},onSuccess:()=>{i(""),r.invalidateQueries({queryKey:["contact-notes",s]}),Ma({title:"Note added"})},onError:u=>Ma({title:"Could not add note",description:u.message,variant:"destructive"})}),d=Nt({mutationFn:async u=>{const{error:h}=await V.from("innercircle_contact_notes").delete().eq("id",u);if(h)throw h},onSuccess:()=>r.invalidateQueries({queryKey:["contact-notes",s]})});return e.jsxs(we,{children:[e.jsx(Vt,{className:"pb-3",children:e.jsxs(Yt,{className:"flex items-center gap-2 text-base",children:[e.jsx(bo,{className:"h-4 w-4 text-primary"}),"Notes",l.length>0&&e.jsx(qe,{variant:"secondary",className:"ml-1 rounded-full text-[11px]",children:l.length})]})}),e.jsxs(De,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(Ls,{value:a,onChange:u=>i(u.target.value),placeholder:"Add a note — it's stamped with the date and time automatically.",rows:3,className:"resize-none"}),e.jsx("div",{className:"flex justify-end",children:e.jsxs($,{size:"sm",disabled:!a.trim()||c.isPending,onClick:()=>c.mutate(a.trim()),children:[c.isPending?e.jsx(Jt,{className:"mr-1.5 h-3.5 w-3.5 animate-spin"}):null,"Add Note"]})})]}),o?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading notes…"}):l.length===0&&!n?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No notes yet — add context about this relationship."}):e.jsxs("div",{className:"space-y-3",children:[l.map(u=>e.jsxs("div",{className:"group rounded-xl border border-border/60 bg-muted/30 p-3",children:[e.jsxs("div",{className:"mb-1.5 flex flex-wrap items-center gap-2 text-[11px] text-muted-foreground",children:[e.jsxs("span",{className:"inline-flex items-center gap-1 font-medium text-foreground/80",children:[e.jsx(sa,{className:"h-3 w-3"}),C5n(u.created_at)]}),e.jsxs("span",{children:["· ",A5n(u.created_at)]}),u.source!=="agent"?e.jsxs(qe,{variant:"outline",className:"gap-1 text-[10px]",children:[e.jsx(kn,{className:"h-2.5 w-2.5"})," System"]}):u.author_name?e.jsxs("span",{children:["· ",u.author_name]}):null,e.jsx("button",{type:"button",onClick:()=>d.mutate(u.id),className:"ml-auto opacity-0 transition-opacity hover:text-destructive group-hover:opacity-100","aria-label":"Delete note",children:e.jsx(Un,{className:"h-3.5 w-3.5"})})]}),e.jsx("p",{className:"whitespace-pre-wrap text-sm",children:u.body})]},u.id)),n&&e.jsxs("div",{className:"rounded-xl border border-dashed border-border/60 p-3",children:[e.jsx("div",{className:"mb-1.5 text-[11px] font-medium uppercase tracking-wide text-muted-foreground",children:"Background (no timestamp)"}),e.jsx("p",{className:"whitespace-pre-wrap text-sm text-muted-foreground",children:n})]})]})]})]})}const T5n="9a88a47c-cb2a-4401-a2b5-111a76b19f9d";function M5n({open:s,onOpenChange:t,contact:n}){var G;const{user:r}=ks(),a=Jn(),i=ls(),{intakePage:l,isLoading:o}=rTe(),{isGmailConnected:c,gmailEmail:d}=dx(),u=gAe(),{data:h}=pt({queryKey:["profile-for-invite",r==null?void 0:r.id],enabled:!!(r!=null&&r.id)&&s,queryFn:async()=>{const{data:H}=await V.from("profiles").select("name, email, avatar_url").eq("id",r.id).maybeSingle();return H}}),m=(h==null?void 0:h.name)||((G=r==null?void 0:r.email)==null?void 0:G.split("@")[0])||"Your Agent",p=m.split(" ")[0],g=l?`https://contacts.relevelup.com/${l.slug}`:"",x=k.useMemo(()=>`Hi ${n.first_name}, I'm updating my contact list and want to make sure I have your latest info — the best phone, email, address, and a couple of dates I love to remember (like your birthday and home anniversary). It only takes about a minute, and it helps me stay in touch the right way. Thanks so much!`,[n.first_name]),[y,v]=k.useState("gmail"),[_,j]=k.useState(""),[C,A]=k.useState(""),[M,I]=k.useState(!1);k.useEffect(()=>{s&&(j(`Quick favor, ${n.first_name} — can you update your info?`),A(x),v(c?"gmail":"system"))},[s,x,n.first_name,c]);const P=k.useMemo(()=>C.split(/\n\n+/).map(H=>`

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

`).join(""),[C]),R=async()=>{var H,Y;if(!l)return g;try{const{data:se,error:ee}=await V.functions.invoke("process-intake-submissions",{body:{action:"generate_tokens",contact_ids:[n.id],intake_page_id:l.id}}),oe=ee?null:(Y=(H=se==null?void 0:se.tokens)==null?void 0:H[0])==null?void 0:Y.token;return oe?`${g}?t=${oe}`:g}catch{return g}},O=H=>`
${h!=null&&h.avatar_url?`${m}`:`
${p.charAt(0)}
`}

A note from ${m}

${P}

Update Your Info

Takes about a minute — promise

Share My Info →

${H}

Sent with care by ${m}

Powered by ReLevelUp

`,B=async()=>{if(!l){ae.error("Set up your Connect Page first",{action:{label:"Set Up",onClick:()=>a("/mission-control/connect-page")}});return}if(!_.trim()||!C.trim()){ae.error("Subject and message are required");return}I(!0);const H=await R(),Y=O(H),se=async()=>{const{data:ee,error:oe}=await V.functions.invoke("send-connect-invite",{body:{contactEmail:n.email,subject:_,htmlBody:Y,replyToEmail:(h==null?void 0:h.email)||(r==null?void 0:r.email),agentName:m}});if(oe)throw oe;if(!(ee!=null&&ee.success))throw new Error((ee==null?void 0:ee.error)||"Failed to send")};try{if(y==="gmail"&&c){const{data:ee,error:oe}=await V.functions.invoke("gmail-send",{body:{to:n.email,subject:_,body:Y,contactId:n.id}});let me=ee&&ee.error?ee:null;if(oe){me={error:"send_failed",message:oe.message};const Q=oe.context;if(Q&&typeof Q.json=="function")try{me=await Q.clone().json()}catch{}}if(me)if(me.error==="insufficient_scope")await se(),ae.warning("Sent using system email — your Gmail connection is missing send permission. Reconnect Gmail in Integrations to send from your own inbox.",{duration:8e3});else throw new Error(me.message||me.error||"Failed to send");else if(!(ee!=null&&ee.success))throw new Error("Failed to send")}else await se();try{await u.mutateAsync({contactId:n.id,actionTypeId:T5n,notes:`Sent Connect Page invite — Subject: "${_}"`})}catch(ee){console.warn("Failed to log activity:",ee)}i.invalidateQueries({queryKey:["contact-touch-logs"]}),ae.success("Connect Page invite sent!"),t(!1)}catch(ee){console.error("Send error:",ee),ae.error(ee instanceof Error?ee.message:"Failed to send invite")}finally{I(!1)}},U=C.split(/\n\n+/).filter(Boolean);return e.jsx(zs,{open:s,onOpenChange:H=>!M&&t(H),children:e.jsxs(Rs,{className:"sm:max-w-[720px] max-h-[92vh] overflow-y-auto",children:[e.jsxs(Vs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(kn,{className:"h-5 w-5 text-primary"}),"Send Connect Page Invite"]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Ask ",e.jsxs("span",{className:"font-medium",children:[n.first_name," ",n.last_name||""]})," to share their latest contact info — takes them about a minute."]})]}),o?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx(Jt,{className:"h-6 w-6 animate-spin text-primary"})}):l?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(re,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Send From"}),e.jsx(ya,{value:y,onValueChange:H=>v(H),className:"mt-1.5",children:e.jsxs(va,{className:"grid w-full grid-cols-2",children:[e.jsxs(is,{value:"gmail",disabled:!c,children:[e.jsx(pn,{className:"h-3.5 w-3.5 mr-1.5"}),c?`Gmail (${d})`:"Gmail (not connected)"]}),e.jsxs(is,{value:"system",children:[e.jsx(kn,{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:y==="gmail"?"Replies go directly to your Gmail inbox.":`Sent from notifications@dashboard.relevelup.com — replies go to ${(h==null?void 0:h.email)||(r==null?void 0:r.email)||"your account email"}.`})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"invite-subject",children:"Subject"}),e.jsx(be,{id:"invite-subject",value:_,onChange:H=>j(H.target.value),className:"mt-1.5"})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"invite-message",children:"Personal Message"}),e.jsx(Ls,{id:"invite-message",value:C,onChange:H=>A(H.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(re,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Preview"}),e.jsxs("a",{href:g,target:"_blank",rel:"noopener noreferrer",className:"text-xs text-primary hover:underline flex items-center gap-1",children:["Open Connect Page ",e.jsx(Ir,{className:"h-3 w-3"})]})]}),e.jsx("div",{className:"rounded-xl border bg-muted/40 p-4 max-h-[380px] overflow-y-auto",children:e.jsxs("div",{className:"mx-auto max-w-[480px] rounded-2xl bg-white shadow-sm overflow-hidden",children:[e.jsxs("div",{className:"bg-gradient-to-br from-[#406E71] to-[#2a4c64] px-6 py-7 text-center",children:[h!=null&&h.avatar_url?e.jsx("img",{src:h.avatar_url,alt:m,className:"mx-auto mb-3 h-14 w-14 rounded-full object-cover ring-2 ring-white/40"}):e.jsx("div",{className:"mx-auto mb-3 flex h-14 w-14 items-center justify-center rounded-full bg-white/20 text-xl font-bold text-white",children:p.charAt(0)}),e.jsxs("p",{className:"text-base font-bold text-white",children:["A note from ",m]})]}),e.jsx("div",{className:"px-6 py-5 space-y-3",children:U.map((H,Y)=>e.jsx("p",{className:"text-[13px] leading-relaxed text-slate-600 whitespace-pre-line",children:H},Y))}),e.jsx("div",{className:"px-6 pb-6",children:e.jsxs("div",{className:"rounded-xl border border-slate-200 bg-slate-50 px-5 py-6 text-center",children:[e.jsx("p",{className:"text-[10px] font-semibold uppercase tracking-wider text-slate-400",children:"Update Your Info"}),e.jsx("p",{className:"mt-1 text-sm font-semibold text-slate-800",children:"Takes about a minute — promise"}),e.jsx("span",{className:"mt-4 inline-block rounded-lg bg-gradient-to-br from-[#406E71] to-[#2a4c64] px-7 py-3 text-sm font-semibold text-white",children:"Share My Info →"}),e.jsxs("p",{className:"mt-3 break-all text-[11px] text-slate-400",children:[g,"?t=…"]})]})}),e.jsx("div",{className:"border-t border-slate-100 px-6 py-4 text-center",children:e.jsxs("p",{className:"text-[11px] text-slate-400",children:["Sent with care by ",m]})})]})}),e.jsxs("p",{className:"text-[11px] text-muted-foreground mt-1.5",children:["Each invite includes a private link that pre-fills ",n.first_name,"'s current info, so their updates come straight back to this contact record."]})]}),e.jsxs("div",{className:"flex items-center justify-end gap-2 pt-2",children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),disabled:M,children:"Cancel"}),e.jsx($,{onClick:B,disabled:M,children:M?e.jsxs(e.Fragment,{children:[e.jsx(Jt,{className:"h-4 w-4 mr-1.5 animate-spin"})," Sending…"]}):e.jsxs(e.Fragment,{children:[e.jsx(Wr,{className:"h-4 w-4 mr-1.5"})," Send Invite"]})})]})]}):e.jsxs("div",{className:"space-y-4 py-6 text-center",children:[e.jsx(Ho,{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($,{onClick:()=>a("/mission-control/connect-page"),children:[e.jsx(pd,{className:"h-4 w-4 mr-1"})," Set Up Connect Page"]})]})]})})}function P5n(){const{user:s}=ks();return pt({queryKey:["cmas",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await V.from("cmas").select("*").eq("agent_id",s.id).order("updated_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function I5n(s){return pt({queryKey:["cma",s],queryFn:async()=>{const{data:t,error:n}=await V.from("cmas").select("*").eq("id",s).single();if(n)throw n;return t},enabled:!!s})}function L5n(s){return pt({queryKey:["cma-comps",s],queryFn:async()=>{const{data:t,error:n}=await V.from("cma_comps").select("*").eq("cma_id",s).order("position",{ascending:!0});if(n)throw n;return t||[]},enabled:!!s})}function X7t(){const s=ls(),{user:t}=ks(),{leadSite:n}=Tg();return Nt({mutationFn:async r=>{const{data:a,error:i}=await V.from("cmas").insert({agent_id:t.id,lead_site_id:(n==null?void 0:n.id)??null,contact_id:r.contactId??null,deal_id:r.dealId??null,buyer_mode:!!r.buyerMode,title:r.title??r.subject.address,subject:r.subject,settings:{sqftPct:.2,monthsBack:6,statuses:["Active","Pending","Closed"]}}).select("*").single();if(i)throw i;return a},onSuccess:()=>s.invalidateQueries({queryKey:["cmas"]})})}function R5n(){const s=ls();return Nt({mutationFn:async({id:t,patch:n})=>{const{data:r,error:a}=await V.from("cmas").update(n).eq("id",t).select("*").single();if(a)throw a;return r},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["cma",n.id]}),s.invalidateQueries({queryKey:["cmas"]})}})}function D5n(){const s=ls();return Nt({mutationFn:async t=>{const{error:n}=await V.from("cmas").delete().eq("id",t);if(n)throw n},onSuccess:()=>s.invalidateQueries({queryKey:["cmas"]})})}function O5n(){const{leadSite:s}=Tg();return Nt({mutationFn:async t=>{const{data:n,error:r}=await V.functions.invoke("cma-subject-lookup",{body:{...t,leadSiteId:(s==null?void 0:s.id)??null}});if(r)throw r;return n}})}function F5n(){const{leadSite:s}=Tg();return Nt({mutationFn:async t=>{const{data:n,error:r}=await V.functions.invoke("cma-comp-search",{body:{...t,leadSiteId:t.leadSiteId??(s==null?void 0:s.id)??null}});if(r)throw r;return n}})}function z5n(){const s=ls();return Nt({mutationFn:async({cmaId:t,comps:n})=>{if(await V.from("cma_comps").delete().eq("cma_id",t),!n.length)return;const r=n.map((i,l)=>({cma_id:t,mls_number:i.mlsNumber??null,source_provider:i.source_provider??null,selected:i.selected!==!1,manual:!!i.manual,score:i.score??null,position:l,snapshot:i})),{error:a}=await V.from("cma_comps").insert(r);if(a)throw a},onSuccess:(t,n)=>s.invalidateQueries({queryKey:["cma-comps",n.cmaId]})})}function Vyt(s,t){const n=t.filter(h=>{var m,p;return h.selected!==!1&&(((m=h.snapshot)==null?void 0:m.sqft)||h.sqft)&&(((p=h.snapshot)==null?void 0:p.price)||h.price)});if(!n.length||!s.sqft)return{low:null,likely:null,high:null,ppsf:null};const r=n.map(h=>{const m=h.snapshot||h;return(m.soldPrice||m.price)/m.sqft}).filter(h=>Number.isFinite(h)&&h>0).sort((h,m)=>h-m);if(!r.length)return{low:null,likely:null,high:null,ppsf:null};const a=r[Math.floor(r.length/2)],i=r.reduce((h,m)=>h+m,0)/r.length,l=r.reduce((h,m)=>h+(m-i)**2,0)/r.length,o=Math.sqrt(l),c=Math.round(a*s.sqft),d=Math.round((a-o)*s.sqft),u=Math.round((a+o)*s.sqft);return{low:d,likely:c,high:u,ppsf:Math.round(a)}}function B5n(s){return pt({queryKey:["contact-video-replies",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await V.from("video_replies").select(` *, video:agent_videos(id, title, thumbnail_url, playback_url) `).eq("contact_id",s).order("created_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function $5n(s){return pt({queryKey:["client-portal",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await V.from("client_portals").select("*").eq("deal_id",s).maybeSingle();if(n)throw n;return t},enabled:!!s})}function UZe(){const s=ai(),t=ls();return Nt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r,error:a}=await V.from("client_portals").insert({deal_id:n.deal_id,owner_user_id:s,slug:"",is_enabled:n.is_enabled??!0,visibility:n.visibility||"private",require_onboarding:n.require_onboarding??!0,allow_spouse:n.allow_spouse??!1,client_name:n.client_name||null,client_email:n.client_email||null,client_phone:n.client_phone||null,invite_method:n.invite_method||"email"}).select().single();if(a)throw a;return r},onSuccess:(n,r)=>{t.invalidateQueries({queryKey:["client-portal",r.deal_id]})}})}function EV(){const s=ls();return Nt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await V.from("client_portals").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:t=>{s.invalidateQueries({queryKey:["client-portal",t.deal_id]}),s.invalidateQueries({queryKey:["all-client-portals"]})}})}function Q7t(){const s=ls();return Nt({mutationFn:async t=>{const{data:n,error:r}=await V.from("client_portals").update({archived_at:new Date().toISOString(),is_enabled:!1}).eq("id",t).select().single();if(r)throw r;return n},onSuccess:t=>{s.invalidateQueries({queryKey:["client-portal",t.deal_id]}),s.invalidateQueries({queryKey:["all-client-portals"]})}})}function J7t(){const s=ls();return Nt({mutationFn:async t=>{const{data:n,error:r}=await V.from("client_portals").update({archived_at:null}).eq("id",t).select().single();if(r)throw r;return n},onSuccess:t=>{s.invalidateQueries({queryKey:["client-portal",t.deal_id]}),s.invalidateQueries({queryKey:["all-client-portals"]})}})}function e9t(){const s=ls();return Nt({mutationFn:async({id:t,dealId:n})=>{await V.from("portal_updates").delete().eq("portal_id",t);const{error:r}=await V.from("client_portals").delete().eq("id",t);if(r)throw r;return n},onSuccess:t=>{s.invalidateQueries({queryKey:["client-portal",t]}),s.invalidateQueries({queryKey:["all-client-portals"]})}})}function U5n(s){return pt({queryKey:["portal-updates",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await V.from("portal_updates").select("*").eq("portal_id",s).order("created_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function t9t(){const s=ls();return Nt({mutationFn:async t=>{const{data:n,error:r}=await V.from("portal_updates").insert({portal_id:t.portal_id,title:t.title,content:t.content||null,video_url:t.video_url||null,is_stage_change:t.is_stage_change||!1}).select().single();if(r)throw r;return n},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["portal-updates",n.portal_id]})}})}function q5n(){const s=ai();return pt({queryKey:["portal-custom-questions",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await V.from("portal_custom_questions").select("*").eq("owner_user_id",s).eq("is_active",!0).order("sort_order",{ascending:!0});if(n)throw n;return t},enabled:!!s})}function V5n(){const s=ai(),t=ls();return Nt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r,error:a}=await V.from("portal_custom_questions").insert({owner_user_id:s,question_text:n.question_text,field_type:n.field_type,options:n.options||[],is_required:n.is_required||!1,sort_order:n.sort_order||0}).select().single();if(a)throw a;return r},onSuccess:()=>{t.invalidateQueries({queryKey:["portal-custom-questions"]})}})}function H5n(){const s=ls();return Nt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await V.from("portal_custom_questions").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["portal-custom-questions"]})}})}function G5n(){const s=ls();return Nt({mutationFn:async t=>{const{error:n}=await V.from("portal_custom_questions").update({is_active:!1}).eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["portal-custom-questions"]})}})}function B5(s){const t=window.location.hostname;return t==="localhost"||t.includes("lovable.app")?`${window.location.origin}/portal/${s}`:`https://clients.relevelup.com/${s}`}function W5n({contactId:s}){const t=Jn(),n=ls(),[r,a]=k.useState(null),[i,l]=k.useState(!1),[o,c]=k.useState(!1),[d,u]=k.useState(""),[h,m]=k.useState(""),[p,g]=k.useState(null),x=EV(),y=t9t(),{data:v,isLoading:_}=pt({queryKey:["contact-portals",s],queryFn:async()=>{const{data:P,error:R}=await V.from("deal_pipeline").select("id, deal_name, deal_type").eq("contact_id",s);if(R)throw R;if(!P||P.length===0)return[];const O=P.map(G=>G.id),{data:B,error:U}=await V.from("client_portals").select("*").in("deal_id",O).is("archived_at",null);if(U)throw U;return(B||[]).map(G=>({...G,deal:P.find(H=>H.id===G.deal_id)}))},enabled:!!s}),j=(v==null?void 0:v.map(P=>P.id))||[],{data:C}=pt({queryKey:["contact-portal-updates",j],queryFn:async()=>{if(j.length===0)return{};const{data:P,error:R}=await V.from("portal_updates").select("*").in("portal_id",j).order("created_at",{ascending:!1});if(R)throw R;const O={};return(P||[]).forEach(B=>{O[B.portal_id]||(O[B.portal_id]=B)}),O},enabled:j.length>0}),A=P=>{navigator.clipboard.writeText(B5(P)),a(P),ae.success("Portal link copied!"),setTimeout(()=>a(null),2e3)},M=async P=>{d.trim()&&(await y.mutateAsync({portal_id:P,title:d,content:h||void 0}),c(!1),u(""),m(""),n.invalidateQueries({queryKey:["contact-portal-updates"]}),ae.success("Portal update posted!"))},I=async()=>{p&&(await x.mutateAsync({id:p.id,welcome_message:p.welcome_message,next_step_text:p.next_step_text,is_enabled:p.is_enabled,show_post_close_tips:p.show_post_close_tips,review_url:p.review_url}),l(!1),g(null),n.invalidateQueries({queryKey:["contact-portals",s]}),ae.success("Portal settings updated!"))};return _||!v||v.length===0?null:e.jsxs(we,{children:[e.jsx(Vt,{className:"pb-2",children:e.jsxs(Yt,{className:"text-base flex items-center gap-2",children:[e.jsx(kc,{className:"h-4 w-4"}),"Client Portal"]})}),e.jsx(De,{className:"space-y-3",children:v.map(P=>{var U,G,H;const R=((U=P.stage_mapping)==null?void 0:U.length)>0?P.stage_mapping:mAe(((G=P.deal)==null?void 0:G.deal_type)||"buyer"),O=R==null?void 0:R[P.current_stage_index??0],B=C==null?void 0:C[P.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:((H=P.deal)==null?void 0:H.deal_name)||"Portal"}),O&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Stage: ",O.label||O.name]})]}),e.jsx(qe,{variant:P.is_enabled?"default":"secondary",className:"text-[10px] flex-shrink-0",children:P.is_enabled?"Active":"Disabled"})]}),B&&e.jsxs("div",{className:"bg-muted/50 rounded-md p-2",children:[e.jsx("p",{className:"text-xs font-medium truncate",children:B.title}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:Ys(new Date(B.created_at),"MMM d, yyyy")})]}),e.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[e.jsxs($,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>A(P.slug),children:[r===P.slug?e.jsx(ma,{className:"h-3 w-3 mr-1"}):e.jsx(Da,{className:"h-3 w-3 mr-1"}),"Copy Link"]}),e.jsxs($,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>window.open(B5(P.slug),"_blank"),children:[e.jsx(Ir,{className:"h-3 w-3 mr-1"}),"View"]}),e.jsxs(zs,{open:o,onOpenChange:c,children:[e.jsx(yl,{asChild:!0,children:e.jsxs($,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>c(!0),children:[e.jsx(bo,{className:"h-3 w-3 mr-1"}),"Post Update"]})}),e.jsxs(Rs,{children:[e.jsx(Vs,{children:e.jsx($s,{children:"Post Portal Update"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Title"}),e.jsx(be,{value:d,onChange:Y=>u(Y.target.value),placeholder:"e.g. Inspection completed!"})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Details (optional)"}),e.jsx(Ls,{value:h,onChange:Y=>m(Y.target.value),placeholder:"Add more details...",rows:3})]}),e.jsxs($,{onClick:()=>M(P.id),disabled:!d.trim()||y.isPending,className:"w-full",children:[e.jsx(Wr,{className:"h-4 w-4 mr-1"}),"Post Update"]})]})]})]}),e.jsxs(zs,{open:i,onOpenChange:l,children:[e.jsx(yl,{asChild:!0,children:e.jsxs($,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>{g({...P}),l(!0)},children:[e.jsx(Yc,{className:"h-3 w-3 mr-1"}),"Settings"]})}),e.jsxs(Rs,{children:[e.jsx(Vs,{children:e.jsx($s,{children:"Portal Settings"})}),p&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(re,{children:"Portal Enabled"}),e.jsx(On,{checked:p.is_enabled,onCheckedChange:Y=>g({...p,is_enabled:Y})})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Welcome Message"}),e.jsx(Ls,{value:p.welcome_message||"",onChange:Y=>g({...p,welcome_message:Y.target.value}),placeholder:"Welcome to your home journey!",rows:2})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Next Step"}),e.jsx(be,{value:p.next_step_text||"",onChange:Y=>g({...p,next_step_text:Y.target.value}),placeholder:"What your client should do next..."})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Review URL"}),e.jsx(be,{value:p.review_url||"",onChange:Y=>g({...p,review_url:Y.target.value}),placeholder:"https://..."})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(re,{children:"Show Post-Close Tips"}),e.jsx(On,{checked:p.show_post_close_tips,onCheckedChange:Y=>g({...p,show_post_close_tips:Y})})]}),e.jsx(Pc,{}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{onClick:I,disabled:x.isPending,className:"flex-1",children:"Save Settings"}),e.jsxs($,{variant:"outline",onClick:()=>t(`/mission-control/pipeline?deal=${P.deal_id}`),children:[e.jsx(xi,{className:"h-4 w-4 mr-1"}),"Full Settings"]})]})]})]})]})]}),v.length>1&&e.jsx(Pc,{})]},P.id)})})]})}function K5n({contactId:s}){const{data:t}=pt({queryKey:["agent-lead-sites-slugs"],queryFn:async()=>{const{data:l,error:o}=await V.from("lead_sites").select("id, subdomain_slug").eq("is_active",!0);if(o)throw o;return new Map((l||[]).map(c=>[c.id,c.subdomain_slug]))},staleTime:6e5}),n=t&&t.size>0,{data:r,isLoading:a}=pt({queryKey:["contact-property-views",s],queryFn:async()=>{const{data:l,error:o}=await V.rpc("get_contact_property_views",{p_contact_id:s});if(o)throw o;return l||[]},enabled:!!s&&!!n});if(!n||a||!r||r.length===0)return null;const i=l=>{const o=t==null?void 0:t.get(l.lead_site_id);return o?`https://${o}.thelocalmove.com/listing/${l.mls_number}`:null};return e.jsxs(we,{className:"overflow-hidden",children:[e.jsx(Vt,{className:"pb-2",children:e.jsxs(Yt,{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(ba,{className:"h-4 w-4 text-primary"})}),"Property Activity",e.jsxs(qe,{variant:"secondary",className:"text-xs ml-auto",children:[r.length," ",r.length===1?"property":"properties"]})]})}),e.jsx(De,{className:"pt-0",children:e.jsx("div",{className:"space-y-1",children:r.map(l=>{const o=i(l),c=l.property_address||`MLS# ${l.mls_number}`;return e.jsxs("a",{href:o||"#",target:"_blank",rel:"noopener noreferrer",onClick:d=>{o||d.preventDefault()},className:"group flex items-center gap-3 p-2.5 rounded-lg hover:bg-muted/60 transition-colors",children:[l.photo_url?e.jsx("div",{className:"h-10 w-10 rounded-lg overflow-hidden flex-shrink-0 bg-muted",children:e.jsx("img",{src:l.photo_url,alt:c,className:"w-full h-full object-cover"})}):e.jsx("div",{className:"h-9 w-9 rounded-lg bg-gradient-to-br from-primary/15 to-primary/5 flex items-center justify-center flex-shrink-0",children:e.jsx(ua,{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(sa,{className:"h-3 w-3"}),e.jsx("span",{title:Ys(new Date(l.viewed_at),"PPp"),children:Zc(new Date(l.viewed_at),{addSuffix:!0})})]})]}),o&&e.jsx(Ir,{className:"h-3.5 w-3.5 text-muted-foreground opacity-0 group-hover:opacity-100 transition-opacity"})]},l.mls_number)})})})]})}const Y5n=["Single Family","Condo","Townhouse","Multi-Family","Land","Commercial"];function Hyt({value:s,onChange:t,onAdd:n,suggestions:r,placeholder:a,icon:i}){const[l,o]=k.useState(!1),c=k.useRef(null),d=k.useRef(null);k.useEffect(()=>{const h=m=>{d.current&&!d.current.contains(m.target)&&c.current&&!c.current.contains(m.target)&&o(!1)};return document.addEventListener("mousedown",h),()=>document.removeEventListener("mousedown",h)},[]);const u=r.filter(h=>h.toLowerCase().includes(s.toLowerCase()));return e.jsxs("div",{className:"relative flex-1",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(be,{ref:c,value:s,onChange:h=>{t(h.target.value),o(!0)},onFocus:()=>o(!0),placeholder:a,onKeyDown:h=>{h.key==="Enter"&&(h.preventDefault(),u.length>0?n(u[0]):n(s))}}),r.length>0&&e.jsx(Go,{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($,{type:"button",variant:"outline",size:"sm",onClick:()=>n(s),children:e.jsx(nn,{className:"h-4 w-4"})})]}),l&&u.length>0&&e.jsx("div",{ref:d,className:"absolute z-50 mt-1 w-full max-h-60 overflow-y-auto rounded-md border bg-popover shadow-md",children:u.map(h=>e.jsxs("button",{type:"button",className:"w-full text-left px-3 py-2 text-sm hover:bg-accent hover:text-accent-foreground transition-colors flex items-center gap-2",onClick:()=>{n(h),o(!1)},children:[i||e.jsx(Si,{className:"h-3 w-3 text-muted-foreground flex-shrink-0"}),h]},h))})]})}function Z5n({contactId:s,contactName:t}){var te,le,fe;const{user:n}=ks(),r=ai(),{hasLeadSite:a}=Tg(),i=ls(),[l,o]=k.useState(!1),[c,d]=k.useState(""),[u,h]=k.useState(""),[m,p]=k.useState(!1),[g,x]=k.useState(""),[y,v]=k.useState(null),[_,j]=k.useState(!1),[C,A]=k.useState(!1),{data:M}=pt({queryKey:["agent-lead-site-config",r],queryFn:async()=>{const{data:_e,error:ve}=await V.from("lead_sites").select("theme_config, mls_market_area").eq("agent_id",r).eq("is_active",!0).order("created_at",{ascending:!0}).limit(1).maybeSingle();if(ve||!_e)return{cities:[],zipCodes:[]};const he=_e.theme_config||{},Se=Array.isArray(he.searchCities)?he.searchCities:[];_e.mls_market_area&&!Se.includes(_e.mls_market_area)&&Se.unshift(_e.mls_market_area);const Te=Array.isArray(he.searchZipCodes)?he.searchZipCodes:[];return{cities:Se,zipCodes:Te}},enabled:!!r}),{data:I,isLoading:P}=pt({queryKey:["contact-property-alert",s],queryFn:async()=>{const{data:_e,error:ve}=await V.from("contact_property_alerts").select("*").eq("contact_id",s).maybeSingle();if(ve)throw ve;return _e},enabled:!!s&&!!n}),[R,O]=k.useState({}),B=()=>{O({is_active:(I==null?void 0:I.is_active)??!0,min_price:(I==null?void 0:I.min_price)??null,max_price:(I==null?void 0:I.max_price)??null,min_beds:(I==null?void 0:I.min_beds)??null,min_baths:(I==null?void 0:I.min_baths)??null,min_sqft:(I==null?void 0:I.min_sqft)??null,max_sqft:(I==null?void 0:I.max_sqft)??null,cities:(I==null?void 0:I.cities)??[],zip_codes:(I==null?void 0:I.zip_codes)??[],property_types:(I==null?void 0:I.property_types)??[],frequency:(I==null?void 0:I.frequency)??"daily"}),o(!0)},U=Nt({mutationFn:async()=>{const _e={contact_id:s,owner_user_id:r,is_active:R.is_active??!0,min_price:R.min_price||null,max_price:R.max_price||null,min_beds:R.min_beds||null,min_baths:R.min_baths||null,min_sqft:R.min_sqft||null,max_sqft:R.max_sqft||null,cities:R.cities||[],zip_codes:R.zip_codes||[],property_types:R.property_types||[],frequency:R.frequency||"daily"};if(I!=null&&I.id){const{error:ve}=await V.from("contact_property_alerts").update(_e).eq("id",I.id);if(ve)throw ve}else{const{error:ve}=await V.from("contact_property_alerts").insert(_e);if(ve)throw ve}},onSuccess:()=>{i.invalidateQueries({queryKey:["contact-property-alert",s]}),o(!1),ae.success("Property alert saved!")},onError:_e=>{ae.error(_e.message||"Failed to save alert")}}),G=Nt({mutationFn:async()=>{if(!(I!=null&&I.id))return;const{error:_e}=await V.from("contact_property_alerts").delete().eq("id",I.id);if(_e)throw _e},onSuccess:()=>{i.invalidateQueries({queryKey:["contact-property-alert",s]}),o(!1),ae.success("Property alert removed")}}),H=_e=>{var he;const ve=_e.trim();ve&&!((he=R.cities)!=null&&he.includes(ve))&&O(Se=>({...Se,cities:[...Se.cities||[],ve]})),d("")},Y=_e=>{var he;const ve=_e.trim();ve&&!((he=R.zip_codes)!=null&&he.includes(ve))&&O(Se=>({...Se,zip_codes:[...Se.zip_codes||[],ve]})),h("")},se=_e=>{O(ve=>{const he=ve.property_types||[];return{...ve,property_types:he.includes(_e)?he.filter(Se=>Se!==_e):[...he,_e]}})},ee=async()=>{if(I!=null&&I.id){j(!0),p(!0),x(""),v(null);try{const{data:_e,error:ve}=await V.functions.invoke("process-property-alerts",{body:{alert_id:I.id,mode:"preview"}});if(ve)throw ve;_e!=null&&_e.html?(x(_e.html),v({count:_e.listings_count||0,recipient:_e.recipient,subject:_e.subject})):v({count:0,message:(_e==null?void 0:_e.message)||"No matching listings found right now."})}catch(_e){ae.error(_e.message||"Failed to generate preview"),p(!1)}finally{j(!1)}}},oe=async()=>{if(I!=null&&I.id&&await io(`Send property alert email to ${t} now?`)){A(!0);try{const{data:_e,error:ve}=await V.functions.invoke("process-property-alerts",{body:{alert_id:I.id,mode:"send"}});if(ve)throw ve;_e!=null&&_e.sent_count?(ae.success(`Sent ${_e.sent_count} ${_e.sent_count===1?"listing":"listings"} to ${_e.recipient}`),i.invalidateQueries({queryKey:["contact-property-alert",s]})):ae.info((_e==null?void 0:_e.message)||"No new matching listings to send right now.")}catch(_e){ae.error(_e.message||"Failed to send alert")}finally{A(!1)}}};if(!a||P)return null;if(I&&!l)return e.jsxs(e.Fragment,{children:[e.jsxs(we,{className:"overflow-hidden",children:[e.jsx(Vt,{className:"pb-2",children:e.jsxs(Yt,{className:"text-base flex items-center gap-2",children:[e.jsx("div",{className:`h-7 w-7 rounded-lg flex items-center justify-center ${I.is_active?"bg-green-500/10":"bg-muted"}`,children:I.is_active?e.jsx(Fx,{className:"h-4 w-4 text-green-600"}):e.jsx(k5,{className:"h-4 w-4 text-muted-foreground"})}),"Property Alerts",e.jsxs(qe,{variant:I.is_active?"default":"secondary",className:"text-xs ml-auto",children:[I.is_active?"Active":"Paused"," · ",I.frequency]})]})}),e.jsxs(De,{className:"pt-0 space-y-2",children:[e.jsxs("div",{className:"flex flex-wrap gap-1.5 text-xs",children:[I.min_price||I.max_price?e.jsxs(qe,{variant:"outline",className:"gap-1",children:[e.jsx(Su,{className:"h-3 w-3"}),I.min_price?`$${(I.min_price/1e3).toFixed(0)}k`:"$0"," - ",I.max_price?`$${(I.max_price/1e3).toFixed(0)}k`:"Any"]}):null,I.min_beds?e.jsxs(qe,{variant:"outline",className:"gap-1",children:[e.jsx(f3,{className:"h-3 w-3"}),I.min_beds,"+ beds"]}):null,I.min_baths?e.jsxs(qe,{variant:"outline",className:"gap-1",children:[e.jsx(p0,{className:"h-3 w-3"}),I.min_baths,"+ baths"]}):null,(te=I.cities)==null?void 0:te.map(_e=>e.jsxs(qe,{variant:"outline",className:"gap-1",children:[e.jsx(Si,{className:"h-3 w-3"}),_e]},_e)),(le=I.zip_codes)==null?void 0:le.map(_e=>e.jsx(qe,{variant:"outline",children:_e},_e)),(fe=I.property_types)==null?void 0:fe.map(_e=>e.jsx(qe,{variant:"outline",children:_e},_e))]}),I.last_sent_at&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Last sent: ",new Date(I.last_sent_at).toLocaleDateString()]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs($,{variant:"outline",size:"sm",onClick:ee,disabled:_,children:[_?e.jsx(Jt,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(ba,{className:"h-4 w-4 mr-1"}),"Preview Email"]}),e.jsxs($,{size:"sm",onClick:oe,disabled:C||!I.is_active,title:I.is_active?"Send this alert email now":"Activate alert to send",children:[C?e.jsx(Jt,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Wr,{className:"h-4 w-4 mr-1"}),"Send Now"]}),e.jsx($,{variant:"outline",size:"sm",onClick:B,children:"Manage Alert"}),e.jsxs($,{variant:"destructive",size:"sm",onClick:()=>G.mutate(),disabled:G.isPending,children:[G.isPending?e.jsx(Jt,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(mr,{className:"h-4 w-4 mr-1"}),"Remove"]})]})]})]}),e.jsx(zs,{open:m,onOpenChange:p,children:e.jsxs(Rs,{className:"max-w-3xl max-h-[90vh] flex flex-col",children:[e.jsxs(Vs,{children:[e.jsx($s,{children:"Property Alert Email Preview"}),(y==null?void 0:y.subject)&&e.jsxs("div",{className:"text-xs text-muted-foreground space-y-0.5 pt-1",children:[e.jsxs("div",{children:[e.jsx("span",{className:"font-medium",children:"To:"})," ",y.recipient]}),e.jsxs("div",{children:[e.jsx("span",{className:"font-medium",children:"Subject:"})," ",y.subject]}),e.jsxs("div",{children:[e.jsx("span",{className:"font-medium",children:"Listings:"})," ",y.count]})]})]}),e.jsx("div",{className:"flex-1 overflow-hidden border rounded-md bg-muted/30",children:_?e.jsxs("div",{className:"flex items-center justify-center h-96 text-muted-foreground",children:[e.jsx(Jt,{className:"h-5 w-5 mr-2 animate-spin"})," Building preview…"]}):g?e.jsx("iframe",{srcDoc:g,title:"Property alert preview",className:"w-full h-[65vh] bg-white rounded-md"}):e.jsx("div",{className:"flex items-center justify-center h-96 text-sm text-muted-foreground p-6 text-center",children:(y==null?void 0:y.message)||"No matching listings found right now."})}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>p(!1),children:"Close"}),g&&e.jsxs($,{onClick:()=>{p(!1),oe()},disabled:C||!I.is_active,children:[e.jsx(Wr,{className:"h-4 w-4 mr-1"}),"Send to ",t]})]})]})})]});const me=((M==null?void 0:M.cities)||[]).filter(_e=>{var ve;return!((ve=R.cities)!=null&&ve.includes(_e))}),Q=((M==null?void 0:M.zipCodes)||[]).filter(_e=>{var ve;return!((ve=R.zip_codes)!=null&&ve.includes(_e))});return l?e.jsxs(we,{children:[e.jsx(Vt,{className:"pb-3",children:e.jsxs(Yt,{className:"text-base flex items-center gap-2",children:[e.jsx(Fx,{className:"h-4 w-4 text-primary"}),I?"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(re,{children:"Alert Active"}),e.jsx(On,{checked:R.is_active??!0,onCheckedChange:_e=>O(ve=>({...ve,is_active:_e}))})]}),e.jsxs("div",{children:[e.jsxs(re,{className:"flex items-center gap-1 mb-1.5",children:[e.jsx(Su,{className:"h-3.5 w-3.5"})," Price Range"]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(be,{type:"number",placeholder:"Min price",value:R.min_price??"",onChange:_e=>O(ve=>({...ve,min_price:_e.target.value?Number(_e.target.value):null}))}),e.jsx(be,{type:"number",placeholder:"Max price",value:R.max_price??"",onChange:_e=>O(ve=>({...ve,max_price:_e.target.value?Number(_e.target.value):null}))})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsxs(re,{className:"flex items-center gap-1 mb-1.5",children:[e.jsx(f3,{className:"h-3.5 w-3.5"})," Min Beds"]}),e.jsxs(bs,{value:R.min_beds?String(R.min_beds):"any",onValueChange:_e=>O(ve=>({...ve,min_beds:_e==="any"?null:Number(_e)})),children:[e.jsx(ys,{children:e.jsx(_s,{placeholder:"Any"})}),e.jsxs(vs,{children:[e.jsx(We,{value:"any",children:"Any"}),[1,2,3,4,5].map(_e=>e.jsxs(We,{value:String(_e),children:[_e,"+"]},_e))]})]})]}),e.jsxs("div",{children:[e.jsxs(re,{className:"flex items-center gap-1 mb-1.5",children:[e.jsx(p0,{className:"h-3.5 w-3.5"})," Min Baths"]}),e.jsxs(bs,{value:R.min_baths?String(R.min_baths):"any",onValueChange:_e=>O(ve=>({...ve,min_baths:_e==="any"?null:Number(_e)})),children:[e.jsx(ys,{children:e.jsx(_s,{placeholder:"Any"})}),e.jsxs(vs,{children:[e.jsx(We,{value:"any",children:"Any"}),[1,1.5,2,2.5,3,4].map(_e=>e.jsxs(We,{value:String(_e),children:[_e,"+"]},_e))]})]})]})]}),e.jsxs("div",{children:[e.jsxs(re,{className:"flex items-center gap-1 mb-1.5",children:[e.jsx(b3,{className:"h-3.5 w-3.5"})," Square Feet"]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(be,{type:"number",placeholder:"Min sqft",value:R.min_sqft??"",onChange:_e=>O(ve=>({...ve,min_sqft:_e.target.value?Number(_e.target.value):null}))}),e.jsx(be,{type:"number",placeholder:"Max sqft",value:R.max_sqft??"",onChange:_e=>O(ve=>({...ve,max_sqft:_e.target.value?Number(_e.target.value):null}))})]})]}),e.jsxs("div",{children:[e.jsxs(re,{className:"flex items-center gap-1 mb-1.5",children:[e.jsx(Si,{className:"h-3.5 w-3.5"})," Cities"]}),e.jsx(Hyt,{value:c,onChange:d,onAdd:H,suggestions:me,placeholder:"Type to search cities..."}),R.cities&&R.cities.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1 mt-2",children:R.cities.map(_e=>e.jsxs(qe,{variant:"secondary",className:"gap-1",children:[_e,e.jsx("button",{onClick:()=>O(ve=>{var he;return{...ve,cities:(he=ve.cities)==null?void 0:he.filter(Se=>Se!==_e)}}),children:e.jsx(mr,{className:"h-3 w-3"})})]},_e))})]}),e.jsxs("div",{children:[e.jsx(re,{className:"mb-1.5",children:"Zip Codes"}),e.jsx(Hyt,{value:u,onChange:h,onAdd:Y,suggestions:Q,placeholder:"Type to search zip codes...",icon:e.jsx("span",{className:"text-xs text-muted-foreground font-mono",children:"#"})}),R.zip_codes&&R.zip_codes.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1 mt-2",children:R.zip_codes.map(_e=>e.jsxs(qe,{variant:"secondary",className:"gap-1",children:[_e,e.jsx("button",{onClick:()=>O(ve=>{var he;return{...ve,zip_codes:(he=ve.zip_codes)==null?void 0:he.filter(Se=>Se!==_e)}}),children:e.jsx(mr,{className:"h-3 w-3"})})]},_e))})]}),e.jsxs("div",{children:[e.jsxs(re,{className:"flex items-center gap-1 mb-1.5",children:[e.jsx(ua,{className:"h-3.5 w-3.5"})," Property Types"]}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:Y5n.map(_e=>{var ve;return e.jsx(qe,{variant:(ve=R.property_types)!=null&&ve.includes(_e)?"default":"outline",className:"cursor-pointer",onClick:()=>se(_e),children:_e},_e)})})]}),e.jsxs("div",{children:[e.jsx(re,{className:"mb-1.5",children:"Frequency"}),e.jsxs(bs,{value:R.frequency||"daily",onValueChange:_e=>O(ve=>({...ve,frequency:_e})),children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"daily",children:"Daily"}),e.jsx(We,{value:"weekly",children:"Weekly"})]})]})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsxs($,{onClick:()=>U.mutate(),disabled:U.isPending,className:"flex-1",children:[U.isPending?e.jsx(Jt,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Ml,{className:"h-4 w-4 mr-1"}),"Save Alert"]}),e.jsx($,{variant:"outline",onClick:()=>o(!1),children:"Cancel"}),I&&e.jsx($,{variant:"destructive",size:"icon",onClick:()=>G.mutate(),disabled:G.isPending,children:e.jsx(mr,{className:"h-4 w-4"})})]})]})]}):e.jsx(we,{className:"overflow-hidden",children:e.jsx(De,{className:"p-4",children:e.jsxs("button",{onClick:B,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(Fx,{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 X5n({contactId:s,contactName:t}){var se;const{user:n}=ks(),r=ai(),{hasLeadSite:a}=Tg(),i=ls(),[l,o]=k.useState(!1),[c,d]=k.useState(""),[u,h]=k.useState([]),[m,p]=k.useState(!1),[g,x]=k.useState(!1),[y,v]=k.useState(!1),[_,j]=k.useState(""),C=k.useRef(null),A=k.useRef(null),{data:M}=pt({queryKey:["agent-lead-site-cities",r],queryFn:async()=>{const{data:ee,error:oe}=await V.from("lead_sites").select("theme_config, mls_market_area").eq("agent_id",r).eq("is_active",!0).order("created_at",{ascending:!0}).limit(1).maybeSingle();if(oe||!ee)return[];const me=ee.theme_config||{},Q=Array.isArray(me.searchCities)?me.searchCities:[];return ee.mls_market_area&&!Q.includes(ee.mls_market_area)&&Q.unshift(ee.mls_market_area),Q},enabled:!!r}),{data:I,isLoading:P}=pt({queryKey:["contact-market-report",s],queryFn:async()=>{const{data:ee,error:oe}=await V.from("innercircle_contacts").select("market_report_enabled, market_report_cities").eq("id",s).single();if(oe)throw oe;return ee},enabled:!!s&&!!n});k.useEffect(()=>{const ee=oe=>{A.current&&!A.current.contains(oe.target)&&C.current&&!C.current.contains(oe.target)&&x(!1)};return document.addEventListener("mousedown",ee),()=>document.removeEventListener("mousedown",ee)},[]);const R=()=>{p((I==null?void 0:I.market_report_enabled)??!1),h((I==null?void 0:I.market_report_cities)??[]),o(!0)},O=ee=>{const oe=(ee||c).trim();oe&&!u.includes(oe)&&h([...u,oe]),d(""),x(!1)},B=(M||[]).filter(ee=>!u.includes(ee)&&ee.toLowerCase().includes(c.toLowerCase())),U=Nt({mutationFn:async()=>{const{data:ee,error:oe}=await V.functions.invoke("send-market-report",{body:{action:"preview",agentId:r,cities:(I==null?void 0:I.market_report_cities)??[]}});if(oe)throw new Error(oe.message||"Failed to generate preview");if(ee&&!ee.ok&&ee.error)throw new Error(ee.error);return ee},onSuccess:ee=>{j(ee.html),v(!0)},onError:ee=>{ae.error(ee.message||"Failed to generate preview")}}),G=Nt({mutationFn:async()=>{const{data:ee,error:oe}=await V.functions.invoke("send-market-report",{body:{action:"send",agentId:r,cities:(I==null?void 0:I.market_report_cities)??[],contactIds:[s]}});if(oe)throw new Error(oe.message||"Failed to send report");if(ee&&!ee.ok&&ee.error)throw new Error(ee.error);return ee},onSuccess:()=>{ae.success(`Market report sent to ${t}!`)},onError:ee=>{ae.error(ee.message||"Failed to send report")}}),H=Nt({mutationFn:async()=>{const{error:ee}=await V.from("innercircle_contacts").update({market_report_enabled:m,market_report_cities:u}).eq("id",s);if(ee)throw ee},onSuccess:()=>{i.invalidateQueries({queryKey:["contact-market-report",s]}),o(!1),ae.success(m?"Monthly market report enabled!":"Market report disabled")},onError:ee=>{ae.error(ee.message||"Failed to save")}}),Y=Nt({mutationFn:async()=>{const{error:ee}=await V.from("innercircle_contacts").update({market_report_enabled:!1,market_report_cities:[]}).eq("id",s);if(ee)throw ee},onSuccess:()=>{i.invalidateQueries({queryKey:["contact-market-report",s]}),o(!1),p(!1),h([]),ae.success("Market report removed")},onError:ee=>{ae.error(ee.message||"Failed to remove market report")}});return!a||P?null:I!=null&&I.market_report_enabled&&!l?e.jsxs(we,{className:"overflow-hidden",children:[e.jsx(Vt,{className:"pb-2",children:e.jsxs(Yt,{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(Ul,{className:"h-4 w-4 text-primary"})}),"Monthly Market Report",e.jsx(qe,{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:((se=I.market_report_cities)==null?void 0:se.length)>0?I.market_report_cities.map(ee=>e.jsxs(qe,{variant:"outline",className:"gap-1",children:[e.jsx(Si,{className:"h-3 w-3"}),ee]},ee)):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($,{variant:"outline",size:"sm",onClick:()=>U.mutate(),disabled:U.isPending,className:"flex-1",children:[U.isPending?e.jsx(Jt,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(ba,{className:"h-4 w-4 mr-1"}),"Preview"]}),e.jsxs($,{variant:"default",size:"sm",onClick:()=>G.mutate(),disabled:G.isPending,className:"flex-1",children:[G.isPending?e.jsx(Jt,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Wr,{className:"h-4 w-4 mr-1"}),"Send Now"]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{variant:"outline",size:"sm",onClick:R,className:"flex-1",children:"Manage"}),e.jsxs($,{variant:"destructive",size:"sm",onClick:()=>Y.mutate(),disabled:Y.isPending,className:"flex-1",children:[Y.isPending?e.jsx(Jt,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(mr,{className:"h-4 w-4 mr-1"}),"Remove"]})]}),e.jsx(zs,{open:y,onOpenChange:v,children:e.jsxs(Rs,{className:"max-w-3xl max-h-[85vh] overflow-hidden flex flex-col",children:[e.jsx(Vs,{children:e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(Ul,{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:_}})}),e.jsxs("div",{className:"flex gap-2 pt-4 border-t",children:[e.jsxs($,{onClick:()=>{v(!1),G.mutate()},disabled:G.isPending,className:"flex-1",children:[G.isPending?e.jsx(Jt,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Wr,{className:"h-4 w-4 mr-1"}),"Send to ",t]}),e.jsx($,{variant:"outline",onClick:()=>v(!1),children:"Close"})]})]})})]})]}):l?e.jsxs(we,{children:[e.jsx(Vt,{className:"pb-3",children:e.jsxs(Yt,{className:"text-base flex items-center gap-2",children:[e.jsx(Ul,{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(re,{children:"Send Monthly Report"}),e.jsx(On,{checked:m,onCheckedChange:p})]}),m&&e.jsxs("div",{children:[e.jsxs(re,{className:"flex items-center gap-1 mb-1.5",children:[e.jsx(Si,{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(be,{ref:C,value:c,onChange:ee=>{d(ee.target.value),x(!0)},onFocus:()=>x(!0),placeholder:"Type to search cities...",onKeyDown:ee=>{ee.key==="Enter"&&(ee.preventDefault(),B.length>0?O(B[0]):O())}}),e.jsx(Go,{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($,{type:"button",variant:"outline",size:"sm",onClick:()=>O(),children:e.jsx(nn,{className:"h-4 w-4"})})]}),g&&B.length>0&&e.jsx("div",{ref:A,className:"absolute z-50 mt-1 w-full max-h-60 overflow-y-auto rounded-md border bg-popover shadow-md",children:B.map(ee=>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:()=>O(ee),children:[e.jsx(Si,{className:"h-3 w-3 text-muted-foreground flex-shrink-0"}),ee]},ee))})]}),u.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1 mt-2",children:u.map(ee=>e.jsxs(qe,{variant:"secondary",className:"gap-1",children:[ee,e.jsx("button",{onClick:()=>h(u.filter(oe=>oe!==ee)),children:e.jsx(mr,{className:"h-3 w-3"})})]},ee))})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsxs($,{onClick:()=>H.mutate(),disabled:H.isPending,className:"flex-1",children:[H.isPending?e.jsx(Jt,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Ml,{className:"h-4 w-4 mr-1"}),"Save"]}),e.jsx($,{variant:"outline",onClick:()=>o(!1),children:"Cancel"})]})]})]}):e.jsx(we,{className:"overflow-hidden",children:e.jsx(De,{className:"p-4",children:e.jsxs("button",{onClick:R,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(Ul,{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 Q5n(s){return pt({queryKey:["contact-drip-activity",s],queryFn:async()=>{if(!s)return{enrollments:[],stepLogs:[]};const{data:t,error:n}=await V.from("drip_campaign_enrollments").select("id, campaign_id, current_step, status, next_send_at, enrolled_at, completed_at, exited_at, exit_reason").eq("contact_id",s).order("enrolled_at",{ascending:!1});if(n)throw console.error("[ContactDripActivity] enrollments error",n),n;const r=(t||[]).map(c=>c.id),a=Array.from(new Set((t||[]).map(c=>c.campaign_id)));let i=new Map;if(a.length>0){const{data:c}=await V.from("drip_campaigns").select("id, name, description, is_active").in("id",a);(c||[]).forEach(d=>i.set(d.id,d))}const l=(t||[]).map(c=>({...c,campaign:i.get(c.campaign_id)||null}));let o=[];if(r.length>0){const{data:c,error:d}=await V.from("drip_campaign_step_log").select("id, enrollment_id, campaign_id, step_order, channel, recipient_email, subject, status, error_message, sent_at").in("enrollment_id",r).order("sent_at",{ascending:!1});d?console.error("[ContactDripActivity] step log error",d):o=(c||[]).map(u=>{var h;return{...u,campaign:{name:((h=i.get(u.campaign_id))==null?void 0:h.name)??""}}})}return{enrollments:l,stepLogs:o}},enabled:!!s})}function J5n(s){switch(s){case"active":return e.jsx(qe,{variant:"secondary",className:"bg-emerald-500/10 text-emerald-600 border-emerald-500/20",children:"Active"});case"paused":return e.jsx(qe,{variant:"secondary",className:"bg-amber-500/10 text-amber-600 border-amber-500/20",children:"Paused"});case"completed":return e.jsx(qe,{variant:"secondary",className:"bg-sky-500/10 text-sky-600 border-sky-500/20",children:"Completed"});case"exited":return e.jsx(qe,{variant:"outline",children:"Exited"});default:return e.jsx(qe,{variant:"outline",children:s})}}function Gyt(s){return s==="sent"?e.jsx(Gr,{className:"h-4 w-4 text-emerald-500"}):s==="failed"?e.jsx(Gd,{className:"h-4 w-4 text-destructive"}):s==="skipped"?e.jsx(uv,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(sa,{className:"h-4 w-4 text-muted-foreground"})}function e4n({contactId:s}){const t=Jn(),{data:n,isLoading:r}=Q5n(s),[a,i]=k.useState(null);if(r)return null;const l=(n==null?void 0:n.enrollments)||[],o=(n==null?void 0:n.stepLogs)||[];return l.length===0&&o.length===0?null:e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsxs(Yt,{className:"flex items-center gap-2 text-base",children:[e.jsx(sM,{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(sM,{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"}),J5n(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: ",Zc(new Date(c.next_send_at),{addSuffix:!0})]}),c.completed_at&&e.jsxs(e.Fragment,{children:[" · Completed ",Zc(new Date(c.completed_at),{addSuffix:!0})]}),c.exited_at&&!c.completed_at&&e.jsxs(e.Fragment,{children:[" · ",c.exit_reason||"Exited"," ",Zc(new Date(c.exited_at),{addSuffix:!0})]})]})]}),e.jsx(fi,{className:"h-4 w-4 text-muted-foreground mt-1 flex-shrink-0"})]},c.id)})]}),o.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("p",{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:["Send History (",o.length,")"]}),e.jsxs("div",{className:"space-y-1",children:[o.slice(0,8).map(c=>{var d,u;return e.jsxs(zs,{open:(a==null?void 0:a.id)===c.id,onOpenChange:h=>!h&&i(null),children:[e.jsx(yl,{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:Gyt(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(bo,{className:"h-3 w-3 text-muted-foreground flex-shrink-0"}):e.jsx(pn,{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"," · ",Ys(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(Rs,{className:"max-w-lg",children:[e.jsx(Vs,{children:e.jsxs($s,{className:"flex items-center gap-2",children:[Gyt(c.status),c.subject||"Drip step"]})}),e.jsxs("div",{className:"space-y-2 text-sm",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Campaign"}),e.jsx("span",{className:"font-medium",children:((u=c.campaign)==null?void 0:u.name)||"—"})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Channel"}),e.jsx("span",{className:"font-medium uppercase",children:c.channel})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Step"}),e.jsxs("span",{className:"font-medium",children:["#",c.step_order+1]})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Recipient"}),e.jsx("span",{className:"font-medium",children:c.recipient_email||"—"})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Status"}),e.jsx("span",{className:"font-medium capitalize",children:c.status})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Sent"}),e.jsx("span",{className:"font-medium",children:Ys(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($,{variant:"ghost",size:"sm",className:"w-full text-xs",onClick:()=>t("/mission-control/smart-drips"),children:"View all in Smart Drips"})]})]})]})]})}function s9t({contactId:s}={}){const{user:t}=ks();return pt({queryKey:["sent-emails",t==null?void 0:t.id,s??"all"],enabled:!!t,queryFn:async()=>{const n=t.id;let r=V.from("gmail_sent_emails").select("id, contact_id, to_email, subject, sent_at, source").eq("user_id",n).or("source.is.null,source.neq.drip_campaign").order("sent_at",{ascending:!1}).limit(1e3);s&&(r=r.eq("contact_id",s));let a=V.from("bulk_email_sends").select("id, contact_id, contact_email, subject, sent_at, source, opened_at, clicked_at").eq("user_id",n).order("sent_at",{ascending:!1}).limit(1e3);s&&(a=a.eq("contact_id",s));const i=await V.from("email_campaigns").select("id, subject").eq("user_id",n),l=(i.data||[]).map(x=>x.id),o=new Map((i.data||[]).map(x=>[x.id,x.subject]));let c=[];if(l.length>0){let x=V.from("email_campaign_recipients").select("id, contact_id, email, sent_at, campaign_id, opened_at, clicked_at").in("campaign_id",l).eq("status","sent").not("sent_at","is",null).order("sent_at",{ascending:!1}).limit(1e3);s&&(x=x.eq("contact_id",s)),c=(await x).data||[]}const[d,u]=await Promise.all([r,a]),h=(d.data||[]).map(x=>({id:`g-${x.id}`,channel:x.source==="portal_invite"?"Client Portal Invite":"Gmail",subject:x.subject,to_email:x.to_email,contact_id:x.contact_id,sent_at:x.sent_at,source:x.source})),m=(u.data||[]).map(x=>({id:`b-${x.id}`,channel:"Mass Email",subject:x.subject,to_email:x.contact_email,contact_id:x.contact_id,sent_at:x.sent_at,source:x.source,opened_at:x.opened_at,clicked_at:x.clicked_at})),p=c.map(x=>({id:`c-${x.id}`,channel:"Campaign",subject:o.get(x.campaign_id)||"(campaign)",to_email:x.email,contact_id:x.contact_id,sent_at:x.sent_at,source:null,campaign_id:x.campaign_id,opened_at:x.opened_at,clicked_at:x.clicked_at})),g=[...h,...m,...p];return g.sort((x,y)=>x.sent_at0&&e.jsx(qe,{variant:"secondary",className:"ml-1",children:t.length})]})}),e.jsx(De,{children:n?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading..."}):t.length===0?e.jsxs("div",{className:"text-center py-6 text-sm text-muted-foreground",children:[e.jsx(pn,{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(qe,{variant:"outline",className:`text-xs ${t4n[l.channel]}`,children:l.channel}),e.jsx("span",{className:"text-xs text-muted-foreground",children:Ys(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($,{variant:"ghost",size:"sm",className:"w-full mt-3",onClick:()=>a(!r),children:r?"Show less":`Show all ${t.length}`}),e.jsx("div",{className:"mt-3 pt-3 border-t",children:e.jsx(nr,{to:"/mission-control/sent-emails",className:"text-xs text-primary hover:underline",children:"View all sent emails →"})})]})})]})}function n4n({videoId:s}){var l;const{data:t,isLoading:n,error:r}=BSn(s);if(n)return e.jsxs("div",{className:"space-y-4",children:[e.jsx(fn,{className:"w-full aspect-video rounded-lg"}),e.jsx(fn,{className:"h-4 w-1/3"})]});if(r||!t||t.is_deleted)return e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx(Gd,{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 r4n({contactId:s}){const t=Jn(),[n,r]=k.useState(!1),{data:a,isLoading:i}=pt({queryKey:["deal-tasks","contact",s],queryFn:async()=>{const{data:h,error:m}=await V.from("deal_tasks").select(` id, title, priority, status, due_date, completed_at, deal:deal_pipeline(id, deal_name) `).eq("contact_id",s).order("status").order("due_date",{ascending:!0,nullsFirst:!1});if(m)throw m;return h},enabled:!!s}),l=async(h,m)=>{const p=m==="done"?"todo":"done";await V.from("deal_tasks").update({status:p,completed_at:p==="done"?new Date().toISOString():null}).eq("id",h),window.dispatchEvent(new CustomEvent("refetch-contact-tasks"))},{refetch:o}=pt({queryKey:["deal-tasks","contact",s],queryFn:async()=>{const{data:h,error:m}=await V.from("deal_tasks").select(` id, title, priority, status, due_date, completed_at, deal:deal_pipeline(id, deal_name) `).eq("contact_id",s).order("status").order("due_date",{ascending:!0,nullsFirst:!1});if(m)throw m;return h},enabled:!!s}),c={urgent:"🔴",high:"🟠",medium:"🟡",low:"🟢"},d=(a==null?void 0:a.filter(h=>h.status!=="done"))||[],u=(a==null?void 0:a.filter(h=>h.status==="done"))||[];return e.jsxs(we,{children:[e.jsx(Vt,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(Yt,{className:"text-base flex items-center gap-2",children:[e.jsx(ma,{className:"h-4 w-4"}),"Tasks",d.length>0&&e.jsx(qe,{variant:"secondary",className:"text-xs",children:d.length})]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx($,{variant:"ghost",size:"sm",onClick:()=>t("/mission-control/tasks"),children:"View All"}),e.jsx($,{variant:"outline",size:"sm",onClick:()=>r(!0),children:e.jsx(nn,{className:"h-3.5 w-3.5"})})]})]})}),e.jsx(De,{className:"space-y-1",children:i?e.jsx(fn,{className:"h-8 w-full"}):d.length===0&&u.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No tasks yet"}):e.jsxs(e.Fragment,{children:[d.map(h=>e.jsxs("button",{onClick:async()=>{await l(h.id,h.status),o()},className:"w-full text-left flex items-center gap-2 px-2 py-1.5 rounded hover:bg-muted/50 transition-colors group",children:[e.jsx("div",{className:"h-4 w-4 rounded-full border-2 border-muted-foreground/30 shrink-0 group-hover:border-primary"}),e.jsxs("span",{className:"text-sm flex-1 truncate",children:[c[h.priority]," ",h.title]}),h.due_date&&e.jsx("span",{className:"text-[10px] text-muted-foreground",children:Ys(new Date(h.due_date),"MMM d")})]},h.id)),u.length>0&&e.jsx("div",{className:"pt-1 border-t mt-1",children:e.jsxs("p",{className:"text-[10px] text-muted-foreground px-2 py-1",children:[u.length," completed"]})})]})}),n&&e.jsx(a4n,{contactId:s,open:n,onOpenChange:h=>{r(h),h||o()}})]})}function a4n({contactId:s,open:t,onOpenChange:n}){const[r,a]=k.useState(""),[i,l]=k.useState("medium"),[o,c]=k.useState(),{data:d}=pt({queryKey:["session"],queryFn:async()=>{const{data:h}=await V.auth.getSession();return h.session}}),u=async()=>{var m;if(!r.trim()||!((m=d==null?void 0:d.user)!=null&&m.id))return;const{error:h}=await V.from("deal_tasks").insert([{owner_user_id:d.user.id,contact_id:s,title:r.trim(),priority:i,status:"todo",due_date:o?Ys(o,"yyyy-MM-dd"):null}]);if(h){console.error("Task create error:",h);return}n(!1)};return e.jsx(zs,{open:t,onOpenChange:n,children:e.jsxs(Rs,{className:"sm:max-w-[400px]",children:[e.jsx(Vs,{children:e.jsx($s,{children:"Add Task"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Title"}),e.jsx(be,{value:r,onChange:h=>a(h.target.value),placeholder:"Task title...",onKeyDown:h=>h.key==="Enter"&&u()})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Priority"}),e.jsxs("select",{value:i,onChange:h=>l(h.target.value),className:"w-full h-10 rounded-md border border-input bg-background px-3 text-sm",children:[e.jsx("option",{value:"low",children:"🟢 Low"}),e.jsx("option",{value:"medium",children:"🟡 Medium"}),e.jsx("option",{value:"high",children:"🟠 High"}),e.jsx("option",{value:"urgent",children:"🔴 Urgent"})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Due Date"}),e.jsx(be,{type:"date",value:o?Ys(o,"yyyy-MM-dd"):"",onChange:h=>c(h.target.value?new Date(h.target.value+"T00:00:00"):void 0)})]})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx($,{variant:"outline",onClick:()=>n(!1),children:"Cancel"}),e.jsx($,{onClick:u,disabled:!r.trim(),children:"Create Task"})]})]})]})})}function i4n({contactId:s}){const t=Jn(),{data:n,isLoading:r}=pt({queryKey:["contact-linked-deals",s],queryFn:async()=>{const{data:a,error:i}=await V.from("deal_pipeline").select(` id, deal_name, deal_type, expected_price, property_address, stage:deal_pipeline_stages(id, name, color, icon, is_won_stage, is_lost_stage) `).eq("contact_id",s).order("updated_at",{ascending:!1});if(i)throw i;return a},enabled:!!s});return r||!n||n.length===0?null:e.jsxs(we,{children:[e.jsx(Vt,{className:"pb-2",children:e.jsxs(Yt,{className:"text-base flex items-center gap-2",children:[e.jsx(zx,{className:"h-4 w-4"}),"Linked Deals"]})}),e.jsx(De,{className:"space-y-2",children:n.map(a=>{const i=a.stage;return e.jsx("button",{onClick:()=>t(`/mission-control/pipeline?deal=${a.id}`),className:"w-full text-left p-3 rounded-lg border hover:bg-accent transition-colors group",children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:a.deal_name}),a.property_address&&e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:a.property_address}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(qe,{variant:"outline",className:"text-[10px] capitalize",children:a.deal_type}),i&&e.jsxs(qe,{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(xi,{className:"h-4 w-4 text-muted-foreground group-hover:text-primary transition-colors flex-shrink-0"})]})},a.id)})})]})}function o4n(){var Bs,Ts,Fn,An;const{contactId:s}=oo(),{hasIdx:t}=Tg(),n=Jn(),[r]=Jc(),a=r.get("search")||"",i=r.get("type")||"all",l=r.get("status")||r.get("filter")||"all",o=r.get("tags")||"",c=r.get("tagMode")==="all"?"all":"any",d=k.useMemo(()=>new Set(o.split(",").map(js=>js.trim()).filter(Boolean)),[o]),{data:u,isLoading:h}=CEs(s||""),{data:m}=vj(),{data:p}=Aee(),{data:g}=Jq(3650),{data:x}=aTe(365),{data:y}=B5n(s),{contactsWithScores:v}=Eee(),{data:_}=QEe(),{score:j}=eTs(s||""),C=xWe(),A=yWe(),M=gAe(),I=KMt(),[P,R]=k.useState(!1),[O,B]=k.useState("overview"),[U,G]=k.useState({}),[H,Y]=k.useState(!1),[se,ee]=k.useState(null),[oe,me]=k.useState(""),[Q,te]=k.useState(void 0),[le,fe]=k.useState(""),[_e,ve]=k.useState(null),[he,Se]=k.useState(!1),[Te,Ie]=k.useState(null),[Ue,Be]=k.useState(!1),{isGmailConnected:je,gmailEmail:Ye}=dx(),{isReady:Ee}=NV(),Re=Ee||je,ke=X7t(),[Fe,Oe]=k.useState(!1),{data:Ge}=pt({queryKey:["cma-eligible"],queryFn:async()=>{const{data:{user:js}}=await V.auth.getUser();if(!js)return!1;const{data:In}=await V.from("lead_sites").select("id, mls_provider_id, no_mls_mode, is_active").eq("agent_id",js.id);return(In||[]).some(un=>un.is_active&&un.mls_provider_id&&!un.no_mls_mode)}}),yt=async()=>{var Ln,Sr,Qn,En;if(!u)return;const js=(Ln=u.address)==null?void 0:Ln.trim(),In=(Sr=u.city)==null?void 0:Sr.trim(),un=(Qn=u.state)==null?void 0:Qn.trim().toUpperCase(),jr=((En=u.zip_code)==null?void 0:En.trim())||"";if(!js||!In||!un){ae.error("Add a full address (street, city, state) before creating a CMA.");return}try{Oe(!0);const pr=await ke.mutateAsync({subject:{address:js,city:In,state:un,zip:jr},contactId:u.id,title:`${u.first_name||""} ${u.last_name||""}`.trim()+" — "+js});n(`/mission-control/cma/${pr.id}`)}catch(pr){ae.error("Could not create CMA: "+((pr==null?void 0:pr.message)||"unknown error"))}finally{Oe(!1)}},{data:tt}=pt({queryKey:["gmail-sent-emails",s],queryFn:async()=>{const{data:js,error:In}=await V.from("gmail_sent_emails").select("*").eq("contact_id",s).order("sent_at",{ascending:!1});if(In)throw In;return js},enabled:!!s}),ut=js=>{if(!js)return null;const In=js.match(/Video ID:\s*([a-f0-9-]+)/i);return In?In[1]:null},nt=k.useMemo(()=>{if(!v)return[];const js=new Map;if(d.size>0&&_)for(const un of _)js.has(un.contact_id)||js.set(un.contact_id,new Set),js.get(un.contact_id).add(un.tag_id);let In=v.filter(un=>{var Qn,En,pr;const jr=a===""||`${un.first_name} ${un.last_name}`.toLowerCase().includes(a.toLowerCase())||((Qn=un.email)==null?void 0:Qn.toLowerCase().includes(a.toLowerCase()))||((En=un.phone)==null?void 0:En.includes(a)),Ln=i==="all"||((pr=un.tags)==null?void 0:pr.some(xn=>xn.relationship_type_id===i));let Sr=!0;if(d.size>0){const xn=js.get(un.id)||new Set;c==="all"?Sr=Array.from(d).every(Ar=>xn.has(Ar)):Sr=Array.from(d).some(Ar=>xn.has(Ar))}return jr&&Ln&&Sr});return l==="not-touched-90"?In=In.filter(un=>{const jr=un.relationshipScore.daysSinceTouch;return jr===null||jr>90}):l==="at-risk"?In=In.filter(un=>un.relationshipScore.status==="at-risk"):l==="cooling"?In=In.filter(un=>un.relationshipScore.status==="cooling"):l==="warm"&&(In=In.filter(un=>un.relationshipScore.status==="warm")),In.map(un=>un.id)},[v,a,i,l,d,c,_]),et=nt.indexOf(s||""),at=et>0?nt[et-1]:null,wt=et1&&et!==-1,Ft=js=>{const In=new URLSearchParams;a&&In.set("search",a),i!=="all"&&In.set("type",i),l!=="all"&&In.set("status",l),d.size>0&&(In.set("tags",Array.from(d).join(",")),In.set("tagMode",c));const un=In.toString();return`/mission-control/contacts/${js}${un?`?${un}`:""}`},Ut=k.useMemo(()=>{const js=((g==null?void 0:g.filter(un=>un.contact_id===s))||[]).map(un=>{var Qn,En,pr;const jr=ut(un.notes);let Ln=((Qn=un.action_type)==null?void 0:Qn.name)||"Touch",Sr=un.notes;if(Ln==="Other"&&((En=un.notes)!=null&&En.startsWith("["))){const xn=un.notes.indexOf("]");xn>0&&(Ln=un.notes.substring(1,xn),Sr=un.notes.substring(xn+1).replace(/^\s*—\s*/,"").trim()||null)}return{id:un.id,type:"touch",completed_at:un.completed_at,name:Ln,color:((pr=un.action_type)==null?void 0:pr.color)||"#3B82F6",notes:Sr,videoId:jr}}),In=((x==null?void 0:x.filter(un=>un.contact_id===s))||[]).map(un=>({id:un.id,type:"popby",completed_at:un.completed_at,name:"Pop-by",color:"#F97316",notes:un.notes,videoId:null}));return[...js,...In].sort((un,jr)=>new Date(jr.completed_at).getTime()-new Date(un.completed_at).getTime())},[g,x,s]),Is=js=>{var In;return{first_name:js.first_name||"",last_name:js.last_name||"",email:js.email||"",phone:js.phone||"",address:js.address||"",city:js.city||"",state:js.state||"",zip_code:js.zip_code||"",birthday:js.birthday||"",home_anniversary:js.home_anniversary||"",wedding_anniversary:js.wedding_anniversary||"",spouse_birthday:js.spouse_birthday||"",spouse_name:js.spouse_name||"",spouse_email:js.spouse_email||"",company_name:js.company_name||"",job_title:js.job_title||"",lead_source_id:js.lead_source_id||"",notes:js.notes||"",tagIds:((In=js.tags)==null?void 0:In.map(un=>un.relationship_type_id))||[]}};k.useEffect(()=>{R(!1),G({})},[s]);const xs=k.useRef(null);k.useEffect(()=>{u!=null&&u.id&&xs.current!==u.id&&(xs.current=u.id,G(Is(u)))},[u==null?void 0:u.id,u]);const st=()=>{u&&(G(Is(u)),R(!0))},dt=async()=>{await C.mutateAsync({id:s,...U,lead_source_id:U.lead_source_id||null}),R(!1)},jt=async()=>{await io("Are you sure you want to delete this contact?")&&(await A.mutateAsync(s),n("/mission-control/contacts"))},rs=((Bs=p==null?void 0:p.find(js=>js.id===se))==null?void 0:Bs.name)==="Other",Ns=async()=>{if(!se||rs&&!le.trim())return;const js=Q?new Date(Q.getFullYear(),Q.getMonth(),Q.getDate(),12,0,0).toISOString():void 0,In=rs?`[${le.trim()}]${oe?" — "+oe:""}`:oe;await M.mutateAsync({contactId:s,actionTypeId:se,notes:In,completedAt:js}),Y(!1),ee(null),me(""),te(void 0),fe("")},us=(js,In)=>{Re&&u?(Ie({email:js,name:In||`${u.first_name} ${u.last_name||""}`.trim()}),Se(!0)):window.location.href=`mailto:${js}`};return h?e.jsx(Xs,{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"})})}):u?e.jsxs(e.Fragment,{children:[e.jsx(Xs,{title:`${u.first_name} ${u.last_name||""}`,description:"Contact details and activity",children:e.jsxs("div",{className:"space-y-5 overflow-x-hidden pb-24 lg:pb-6",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs($,{variant:"ghost",size:"sm",className:"-ml-2",onClick:()=>{window.history.length>1?n(-1):n("/mission-control/contacts")},children:[e.jsx(Ld,{className:"h-4 w-4 mr-1"}),"Back to Contacts"]}),rt&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx($,{variant:"outline",size:"sm",className:"h-8 px-2",onClick:()=>at&&n(Ft(at)),disabled:!at,children:e.jsx(Ld,{className:"h-4 w-4"})}),e.jsxs("span",{className:"px-1 text-xs text-muted-foreground whitespace-nowrap",children:[et+1," of ",nt.length]}),e.jsx($,{variant:"outline",size:"sm",className:"h-8 px-2",onClick:()=>wt&&n(Ft(wt)),disabled:!wt,children:e.jsx(fi,{className:"h-4 w-4"})})]})]}),e.jsx("section",{className:"hub-ink relative overflow-hidden rounded-2xl p-4 sm:p-6",children:e.jsxs("div",{className:"relative flex flex-col gap-5",children:[e.jsxs("div",{className:"flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between",children:[e.jsxs("div",{className:"flex min-w-0 items-start gap-4",children:[e.jsx("div",{className:"shrink-0 rounded-full bg-background p-1 shadow-lg ring-2 ring-white/20",children:e.jsx(S5n,{contactId:u.id,firstName:u.first_name,lastName:u.last_name,avatarUrl:u.avatar_url,email:u.email,size:72})}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("h1",{className:"truncate text-2xl font-bold sm:text-3xl",children:[u.first_name," ",u.last_name||""]}),e.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-1.5",children:[j&&e.jsxs("span",{className:"hub-glass inline-flex items-center gap-1.5 rounded-full px-2.5 py-1 text-[11px] font-semibold capitalize",children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full",style:{backgroundColor:j.status==="warm"?"#22c55e":j.status==="cooling"?"#f59e0b":"#ef4444"}}),j.status==="at-risk"?"At risk":j.status," · ",j.score]}),(((Ts=u.lead_source_ref)==null?void 0:Ts.name)||u.lead_source)&&e.jsx("span",{className:"hub-glass rounded-full px-2.5 py-1 text-[11px] font-medium",children:((Fn=u.lead_source_ref)==null?void 0:Fn.name)||u.lead_source}),(An=u.tags)==null?void 0:An.map(js=>{const In=m==null?void 0:m.find(un=>un.id===js.relationship_type_id);return In?e.jsx("span",{className:"hub-glass rounded-full px-2.5 py-1 text-[11px] font-medium",children:In.name},js.id):null})]}),e.jsxs("div",{className:"mt-3 flex flex-col gap-1.5 text-sm sm:flex-row sm:flex-wrap sm:items-center sm:gap-4",children:[u.email&&e.jsxs("button",{onClick:()=>us(u.email),className:"inline-flex min-w-0 items-center gap-1.5 hub-ink-muted transition-opacity hover:opacity-100",children:[e.jsx(pn,{className:"h-3.5 w-3.5 shrink-0"}),e.jsx("span",{className:"truncate",children:u.email})]}),u.phone&&e.jsxs("a",{href:`tel:${u.phone}`,className:"inline-flex items-center gap-1.5 hub-ink-muted",children:[e.jsx(ka,{className:"h-3.5 w-3.5"}),u.phone]}),(u.address||u.city)&&e.jsxs("span",{className:"inline-flex min-w-0 items-center gap-1.5 hub-ink-muted",children:[e.jsx(Si,{className:"h-3.5 w-3.5 shrink-0"}),e.jsx("span",{className:"truncate",children:[u.address,u.city,u.state].filter(Boolean).join(", ")})]})]})]})]}),e.jsxs("div",{className:"flex shrink-0 items-center gap-2",children:[e.jsxs("button",{onClick:()=>{st(),B("details")},className:"inline-flex items-center gap-2 rounded-full bg-background px-4 py-2 text-sm font-semibold text-foreground shadow-sm transition-transform hover:scale-[1.02]",children:[e.jsx(Cp,{className:"h-4 w-4"}),"Edit"]}),e.jsx("button",{onClick:jt,className:"hub-glass inline-flex h-9 w-9 items-center justify-center rounded-full",title:"Delete contact",children:e.jsx(Un,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2 sm:flex sm:flex-wrap",children:[u.phone&&e.jsxs("a",{href:`tel:${u.phone}`,className:"hub-glass inline-flex items-center justify-center gap-2 rounded-xl px-4 py-2.5 text-sm font-medium",children:[e.jsx(ka,{className:"h-4 w-4",style:{color:"hsl(var(--hub-glow))"}}),"Call"]}),u.phone&&e.jsxs("button",{onClick:()=>window.location.href=`sms:${u.phone}`,className:"hub-glass inline-flex items-center justify-center gap-2 rounded-xl px-4 py-2.5 text-sm font-medium",children:[e.jsx(bo,{className:"h-4 w-4",style:{color:"hsl(var(--hub-glow))"}}),"Text"]}),u.email&&e.jsxs("button",{onClick:()=>us(u.email,`${u.first_name} ${u.last_name||""}`.trim()),className:"hub-glass inline-flex items-center justify-center gap-2 rounded-xl px-4 py-2.5 text-sm font-medium",children:[e.jsx(pn,{className:"h-4 w-4",style:{color:"hsl(var(--hub-glow))"}}),"Email"]}),e.jsxs("button",{onClick:()=>n(`/mission-control/video/record?contact_id=${s}`),className:"hub-glass inline-flex items-center justify-center gap-2 rounded-xl px-4 py-2.5 text-sm font-medium",children:[e.jsx(ia,{className:"h-4 w-4",style:{color:"hsl(var(--hub-glow))"}}),"Video"]}),e.jsxs("button",{onClick:()=>Y(!0),className:"hub-glass inline-flex items-center justify-center gap-2 rounded-xl px-4 py-2.5 text-sm font-medium",children:[e.jsx(nn,{className:"h-4 w-4",style:{color:"hsl(var(--hub-glow))"}}),"Log Action"]}),u.email&&e.jsxs("button",{onClick:()=>Be(!0),className:"hub-glass inline-flex items-center justify-center gap-2 rounded-xl px-4 py-2.5 text-sm font-medium",children:[e.jsx(kn,{className:"h-4 w-4",style:{color:"hsl(var(--hub-glow))"}}),"Connect Page"]})]})]})}),e.jsxs(ya,{value:O,onValueChange:js=>{js==="details"&&!P&&st(),B(js)},children:[e.jsx("div",{className:"-mx-1 overflow-x-auto px-1",children:e.jsxs(va,{className:"inline-flex h-10 w-auto",children:[e.jsx(is,{value:"overview",children:"Overview"}),e.jsx(is,{value:"details",children:"Details"}),e.jsx(is,{value:"activity",children:"Activity"}),e.jsx(is,{value:"marketing",children:"Marketing"})]})}),e.jsx(cs,{value:"overview",className:"mt-4 space-y-5",children:e.jsxs("div",{className:"grid gap-5 lg:grid-cols-3",children:[e.jsxs("div",{className:"space-y-5 lg:col-span-2",children:[e.jsx(cSn,{contact:u,onLogTouch:()=>Y(!0)}),e.jsxs(we,{children:[e.jsx(Vt,{className:"pb-3",children:e.jsxs(Yt,{className:"flex items-center gap-2 text-base",children:[e.jsx(ha,{className:"h-4 w-4 text-primary"}),"Key Dates"]})}),e.jsxs(De,{children:[e.jsx("div",{className:"grid gap-3 sm:grid-cols-2",children:[{icon:Zo,label:"Birthday",value:u.birthday},{icon:ua,label:"Home Anniversary",value:u.home_anniversary},{icon:Bo,label:"Wedding Anniversary",value:u.wedding_anniversary},{icon:Bo,label:"Spouse Birthday",value:u.spouse_birthday}].map(({icon:js,label:In,value:un})=>e.jsxs("div",{className:"flex items-center gap-3 rounded-xl border border-border/70 bg-muted/30 px-3 py-2.5",children:[e.jsx(js,{className:"h-4 w-4 shrink-0 text-primary"}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-[11px] uppercase tracking-wide text-muted-foreground",children:In}),e.jsx("p",{className:"truncate text-sm font-medium",children:un?Ys(ih(un),ih(un).getFullYear()===1900?"MMMM d":"MMMM d, yyyy"):"—"})]})]},In))}),Ut.length>0&&e.jsxs("p",{className:"mt-3 text-xs text-muted-foreground",children:["Last contacted ",Ys(new Date(Ut[0].completed_at),"MMM d, yyyy")," (",Ut[0].name,")",u.created_at&&` · Added ${Ys(new Date(u.created_at),"MMM d, yyyy")}`]})]})]}),(u.address||u.city)&&e.jsxs(we,{children:[e.jsx(Vt,{className:"pb-3",children:e.jsxs(Yt,{className:"flex items-center gap-2 text-base",children:[e.jsx(ua,{className:"h-4 w-4 text-primary"}),"Home"]})}),e.jsxs(De,{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Si,{className:"mt-0.5 h-4 w-4 text-muted-foreground"}),e.jsxs("div",{className:"text-sm",children:[u.address&&e.jsx("div",{children:u.address}),e.jsxs("div",{className:"text-muted-foreground",children:[[u.city,u.state].filter(Boolean).join(", "),u.zip_code?` ${u.zip_code}`:""]})]})]}),Ge&&u.address&&u.city&&u.state&&e.jsxs($,{size:"sm",variant:"outline",onClick:yt,disabled:Fe,children:[Fe?e.jsx(Jt,{className:"mr-1 h-4 w-4 animate-spin"}):e.jsx(C5,{className:"mr-1 h-4 w-4"}),"Create CMA"]})]})]}),e.jsx(E5n,{contactId:u.id,ownerUserId:u.owner_user_id,legacyNote:u.notes}),e.jsx(r4n,{contactId:s})]}),e.jsxs("div",{className:"space-y-5",children:[e.jsxs(we,{children:[e.jsx(Vt,{className:"pb-3",children:e.jsx(Yt,{className:"text-base",children:"Tags"})}),e.jsx(De,{children:e.jsx(Ryt,{contactId:s})})]}),e.jsxs(we,{children:[e.jsx(Vt,{className:"pb-3",children:e.jsxs(Yt,{className:"flex items-center gap-2 text-base",children:[e.jsx(el,{className:"h-4 w-4 text-primary"}),"People & Work"]})}),e.jsxs(De,{className:"space-y-3",children:[e.jsx(YBe,{contactId:s,currentSpouseContactId:(u==null?void 0:u.spouse_contact_id)||null,currentSpouseName:u.spouse_name||null,currentSpouseEmail:u.spouse_email||null,onLink:js=>I.mutate({contactId:s,spouseContactId:js}),onUnlink:()=>I.mutate({contactId:s,spouseContactId:null}),isEditing:!1}),e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(Gi,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:Ot(!u.company_name&&!u.job_title&&"text-muted-foreground"),children:u.job_title&&u.company_name?`${u.job_title} at ${u.company_name}`:u.job_title||u.company_name||"No company on file"})]})]})]}),e.jsx(i4n,{contactId:s}),e.jsx(W5n,{contactId:s})]})]})}),e.jsx(cs,{value:"details",className:"mt-4",children:e.jsxs(we,{children:[e.jsx(Vt,{className:"pb-3",children:e.jsx(Yt,{className:"text-base",children:"Edit Contact"})}),e.jsxs(De,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Basics"}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{children:[e.jsx(re,{htmlFor:"first_name",children:"First Name"}),e.jsx(be,{id:"first_name",value:U.first_name||"",onChange:js=>G({...U,first_name:js.target.value})})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"last_name",children:"Last Name"}),e.jsx(be,{id:"last_name",value:U.last_name||"",onChange:js=>G({...U,last_name:js.target.value})})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"email",children:"Email"}),e.jsx(be,{id:"email",type:"email",value:U.email||"",onChange:js=>G({...U,email:js.target.value})})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"phone",children:"Phone"}),e.jsx(be,{id:"phone",value:U.phone||"",onChange:js=>G({...U,phone:js.target.value})})]})]})]}),e.jsx(Pc,{}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Address"}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"address",children:"Street Address"}),e.jsx(be,{id:"address",value:U.address||"",onChange:js=>G({...U,address:js.target.value}),placeholder:"123 Main St"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4 sm:grid-cols-4",children:[e.jsxs("div",{className:"col-span-2",children:[e.jsx(re,{htmlFor:"city",children:"City"}),e.jsx(be,{id:"city",value:U.city||"",onChange:js=>G({...U,city:js.target.value}),placeholder:"City"})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"state",children:"State"}),e.jsx(be,{id:"state",value:U.state||"",onChange:js=>G({...U,state:js.target.value}),placeholder:"TX",maxLength:2})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"zip_code",children:"Zip Code"}),e.jsx(be,{id:"zip_code",value:U.zip_code||"",onChange:js=>G({...U,zip_code:js.target.value}),placeholder:"12345"})]})]})]}),e.jsx(Pc,{}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Important Dates"}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{children:[e.jsx(re,{htmlFor:"birthday",children:"Birthday"}),e.jsx(be,{id:"birthday",type:"date",value:U.birthday||"",onChange:js=>G({...U,birthday:js.target.value})})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"home_anniversary",children:"Home Anniversary"}),e.jsx(be,{id:"home_anniversary",type:"date",value:U.home_anniversary||"",onChange:js=>G({...U,home_anniversary:js.target.value})})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"wedding_anniversary",children:"Wedding Anniversary"}),e.jsx(be,{id:"wedding_anniversary",type:"date",value:U.wedding_anniversary||"",onChange:js=>G({...U,wedding_anniversary:js.target.value})})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"spouse_birthday",children:"Spouse Birthday"}),e.jsx(be,{id:"spouse_birthday",type:"date",value:U.spouse_birthday||"",onChange:js=>G({...U,spouse_birthday:js.target.value})})]})]})]}),e.jsx(Pc,{}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Household & Work"}),e.jsx(YBe,{contactId:s,currentSpouseContactId:(u==null?void 0:u.spouse_contact_id)||null,currentSpouseName:(u==null?void 0:u.spouse_name)||null,currentSpouseEmail:(u==null?void 0:u.spouse_email)||null,onLink:js=>I.mutate({contactId:s,spouseContactId:js}),onUnlink:()=>I.mutate({contactId:s,spouseContactId:null}),isEditing:!0}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{children:[e.jsx(re,{htmlFor:"company_name",children:"Company"}),e.jsx(be,{id:"company_name",value:U.company_name||"",onChange:js=>G({...U,company_name:js.target.value}),placeholder:"Enter company name"})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"job_title",children:"Job Title"}),e.jsx(be,{id:"job_title",value:U.job_title||"",onChange:js=>G({...U,job_title:js.target.value}),placeholder:"Enter job title"})]})]}),e.jsx(K7t,{value:U.lead_source_id||"",onChange:js=>G({...U,lead_source_id:js})})]}),e.jsx(Pc,{}),e.jsxs("div",{className:"space-y-3",children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Relationship Types"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:m==null?void 0:m.filter(js=>js.active).map(js=>{var un;const In=!!((un=U.tagIds)!=null&&un.includes(js.id));return e.jsxs("label",{className:Ot("inline-flex cursor-pointer items-center gap-2 rounded-full border px-3 py-1.5 text-sm transition-colors",In?"border-primary bg-primary/10 text-primary":"border-border hover:bg-accent"),children:[e.jsx(Li,{checked:In,onCheckedChange:jr=>{var Ln;G(jr?{...U,tagIds:[...U.tagIds||[],js.id]}:{...U,tagIds:(Ln=U.tagIds)==null?void 0:Ln.filter(Sr=>Sr!==js.id)})}}),js.name]},js.id)})}),e.jsxs("div",{children:[e.jsx(re,{children:"Tags"}),e.jsx("div",{className:"mt-2",children:e.jsx(Ryt,{contactId:s})})]})]}),e.jsx(Pc,{}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"notes",children:"Notes"}),e.jsx(Ls,{id:"notes",value:U.notes||"",onChange:js=>G({...U,notes:js.target.value}),rows:5})]}),e.jsxs("div",{className:"sticky bottom-0 -mx-6 flex flex-wrap items-center justify-end gap-2 border-t bg-card/95 px-6 py-3 backdrop-blur",children:[e.jsx($,{variant:"outline",onClick:()=>{R(!1),B("overview")},children:"Cancel"}),e.jsxs($,{onClick:dt,disabled:C.isPending,children:[C.isPending?e.jsx(Jt,{className:"mr-1 h-4 w-4 animate-spin"}):e.jsx(ma,{className:"mr-1 h-4 w-4"}),"Save Changes"]})]})]})]})}),e.jsx(cs,{value:"activity",className:"mt-4",children:e.jsxs("div",{className:"grid gap-5 lg:grid-cols-3",children:[e.jsx("div",{className:"lg:col-span-2",children:e.jsxs(we,{children:[e.jsxs(Vt,{className:"flex flex-row items-center justify-between gap-2 pb-3",children:[e.jsx(Yt,{className:"text-base",children:"Activity Log"}),e.jsxs($,{size:"sm",variant:"outline",onClick:()=>Y(!0),children:[e.jsx(nn,{className:"mr-1 h-3.5 w-3.5"})," Log Action"]})]}),e.jsx(De,{children:Ut.length>0?e.jsx("div",{className:"space-y-4",children:Ut.map(js=>{var In;return e.jsxs("div",{className:"flex items-start gap-3 border-b pb-3 last:border-0",children:[e.jsx("div",{className:"flex h-8 w-8 items-center justify-center rounded-full text-xs text-white",style:{backgroundColor:js.color},children:js.type==="popby"?e.jsx(Zo,{className:"h-4 w-4"}):(In=js.name)==null?void 0:In.charAt(0)}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-medium",children:js.name}),js.videoId&&e.jsxs($,{variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",onClick:()=>ve(js.videoId),children:[e.jsx(pu,{className:"mr-1 h-3 w-3"}),"Preview"]})]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:Ys(new Date(js.completed_at),"MMM d, yyyy h:mm a")}),js.notes&&!js.videoId&&e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:js.notes})]})]},js.id)})}):e.jsx("p",{className:"py-6 text-center text-sm text-muted-foreground",children:"No activity logged yet"})})]})}),e.jsxs("div",{className:"space-y-5",children:[y&&y.length>0&&e.jsxs(we,{children:[e.jsx(Vt,{className:"pb-3",children:e.jsxs(Yt,{className:"flex items-center gap-2 text-base",children:[e.jsx(bo,{className:"h-4 w-4 text-primary"}),"Video Replies"]})}),e.jsx(De,{children:e.jsx("div",{className:"space-y-4",children:y.map(js=>{var In,un;return e.jsxs("div",{className:"flex items-start gap-3 border-b pb-3 last:border-0",children:[(In=js.video)!=null&&In.thumbnail_url?e.jsx("img",{src:js.video.thumbnail_url,alt:js.video.title||"Video",className:"h-12 w-16 cursor-pointer rounded object-cover transition-opacity hover:opacity-80",onClick:()=>ve(js.video_id)}):e.jsx("div",{className:"flex h-12 w-16 cursor-pointer items-center justify-center rounded bg-muted transition-colors hover:bg-muted/80",onClick:()=>ve(js.video_id),children:e.jsx(ia,{className:"h-5 w-5 text-muted-foreground"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("span",{className:"block truncate text-sm font-medium",children:["Replied to: ",((un=js.video)==null?void 0:un.title)||"Untitled Video"]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:Ys(new Date(js.created_at),"MMM d, yyyy h:mm a")}),js.message&&e.jsxs("p",{className:"mt-1 line-clamp-2 text-sm text-muted-foreground",children:['"',js.message,'"']})]})]},js.id)})})})]}),tt&&tt.length>0&&e.jsxs(we,{children:[e.jsx(Vt,{className:"pb-3",children:e.jsxs(Yt,{className:"flex items-center gap-2 text-base",children:[e.jsx(Wr,{className:"h-4 w-4 text-sky-500"}),"Sent Emails"]})}),e.jsx(De,{children:e.jsx("div",{className:"space-y-3",children:tt.map(js=>e.jsxs(zs,{children:[e.jsx(yl,{asChild:!0,children:e.jsxs("button",{className:"flex w-full cursor-pointer items-start gap-3 rounded-lg border p-3 text-left transition-colors hover:bg-muted/50",children:[e.jsx("div",{className:"flex h-8 w-8 flex-shrink-0 items-center justify-center rounded-full bg-sky-500/10 text-sky-600",children:e.jsx(pn,{className:"h-4 w-4"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"truncate text-sm font-medium",children:js.subject}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["To: ",js.to_email," · ",Ys(new Date(js.sent_at),"MMM d, yyyy h:mm a")]})]}),e.jsx(fi,{className:"mt-1 h-4 w-4 flex-shrink-0 text-muted-foreground"})]})}),e.jsxs(Rs,{className:"flex max-h-[85vh] max-w-2xl flex-col",children:[e.jsxs(Vs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(pn,{className:"h-5 w-5 text-sky-500"}),js.subject]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["To: ",js.to_email," · ",Ys(new Date(js.sent_at),"MMM d, yyyy h:mm a")]})]}),e.jsx("div",{className:"min-h-0 flex-1 overflow-hidden rounded-lg border bg-white",children:e.jsx("iframe",{srcDoc:js.body,className:"h-[400px] w-full border-0",sandbox:"",title:`Email: ${js.subject}`})})]})]},js.id))})})]}),e.jsx(s4n,{contactId:s})]})]})}),e.jsx(cs,{value:"marketing",className:"mt-4",children:e.jsxs("div",{className:"grid gap-5 lg:grid-cols-2",children:[e.jsx(K5n,{contactId:s}),t&&e.jsxs(e.Fragment,{children:[e.jsx(Z5n,{contactId:s,contactName:u.first_name}),e.jsx(X5n,{contactId:s,contactName:u.first_name})]}),e.jsx(e4n,{contactId:s})]})})]}),e.jsxs("div",{className:"fixed inset-x-0 bottom-0 z-40 flex items-center gap-2 border-t bg-background/95 px-3 py-2 pb-[calc(env(safe-area-inset-bottom)+0.5rem)] backdrop-blur lg:hidden",children:[u.phone&&e.jsx("a",{href:`tel:${u.phone}`,className:"flex-1",children:e.jsxs($,{variant:"outline",className:"w-full",children:[e.jsx(ka,{className:"mr-1 h-4 w-4"})," Call"]})}),u.phone&&e.jsxs($,{variant:"outline",className:"flex-1",onClick:()=>window.location.href=`sms:${u.phone}`,children:[e.jsx(bo,{className:"mr-1 h-4 w-4"})," Text"]}),e.jsxs($,{className:"flex-1",onClick:()=>Y(!0),children:[e.jsx(nn,{className:"mr-1 h-4 w-4"})," Log"]})]}),e.jsx(zs,{open:H,onOpenChange:Y,children:e.jsxs(Rs,{className:"max-h-[85vh] overflow-y-auto",children:[e.jsx(Vs,{children:e.jsx($s,{children:"Log an Action"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Action Type"}),e.jsx("div",{className:"mt-2 grid grid-cols-2 gap-2",children:p==null?void 0:p.filter(js=>js.active).map(js=>e.jsxs("button",{onClick:()=>ee(js.id),className:Ot("rounded-lg border p-3 text-left transition-all",se===js.id?"border-primary bg-primary/10":"hover:bg-accent"),children:[e.jsx("div",{className:"font-medium",children:js.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:js.description})]},js.id))}),rs&&e.jsxs("div",{className:"mt-3",children:[e.jsx(re,{htmlFor:"custom-action-name",children:"What did you do?"}),e.jsx(be,{id:"custom-action-name",value:le,onChange:js=>fe(js.target.value),placeholder:"e.g. Met a client for lunch, Dropped off a gift...",className:"mt-1"})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Date (optional — backdate if needed)"}),e.jsxs(Xc,{children:[e.jsx(Qc,{asChild:!0,children:e.jsxs($,{variant:"outline",className:Ot("mt-2 w-full justify-start text-left font-normal",!Q&&"text-muted-foreground"),children:[e.jsx(ha,{className:"mr-2 h-4 w-4"}),Q?Ys(Q,"PPP"):"Today (default)"]})}),e.jsx(Bc,{className:"w-auto p-0",align:"start",children:e.jsx(vb,{mode:"single",selected:Q,onSelect:te,disabled:js=>js>new Date,initialFocus:!0,className:Ot("p-3 pointer-events-auto")})})]})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"action-notes",children:"Notes (optional)"}),e.jsx(Ls,{id:"action-notes",value:oe,onChange:js=>me(js.target.value),placeholder:"Add any notes about this interaction...",rows:3})]}),e.jsxs($,{onClick:Ns,disabled:!se||rs&&!le.trim()||M.isPending,className:"w-full",children:[e.jsx(ma,{className:"mr-1 h-4 w-4"}),"Complete Action"]})]})]})}),e.jsx(zs,{open:!!_e,onOpenChange:js=>!js&&ve(null),children:e.jsxs(Rs,{className:"max-w-2xl",children:[e.jsx(Vs,{children:e.jsx($s,{children:"Video Preview"})}),_e&&e.jsx(n4n,{videoId:_e})]})})]})}),Re&&u&&Te&&e.jsx(W2,{open:he,onOpenChange:Se,contact:{id:u.id,first_name:u.first_name,last_name:u.last_name,email:Te.email},gmailEmail:Ye}),u&&u.email&&e.jsx(M5n,{open:Ue,onOpenChange:Be,contact:{id:u.id,first_name:u.first_name,last_name:u.last_name,email:u.email}})]}):e.jsx(Xs,{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($,{onClick:()=>n("/mission-control/contacts"),children:"Back to Contacts"})]})})}function l4n({rangeDays:s}){const{user:t}=ks(),n=ls(),[r,a]=k.useState(null),[i,l]=k.useState(null),[o,c]=k.useState(!1),{data:d=[],isLoading:u}=pt({queryKey:["newsletter-campaigns",t==null?void 0:t.id,s],enabled:!!t,queryFn:async()=>{let p=V.from("email_campaigns").select("id, name, subject, status, sent_at, scheduled_at, created_at, total_recipients, sent_count, open_count, click_count, bounce_count").eq("user_id",t.id).like("name","Newsletter:%").order("created_at",{ascending:!1}).limit(50);if(s){const y=new Date(Date.now()-s*864e5).toISOString();p=p.gte("created_at",y)}const{data:g,error:x}=await p;if(x)throw x;return g||[]}}),{data:h}=pt({queryKey:["newsletter-campaign-recipients",r],enabled:!!r,queryFn:async()=>{const{data:p,error:g}=await V.from("email_campaign_recipients").select("id, email, name, status, sent_at, opened_at, clicked_at, error_message").eq("campaign_id",r).order("sent_at",{ascending:!1}).limit(2e3);if(g)throw g;return p||[]}}),m=async()=>{if(!(!i||!t)){c(!0);try{const{data:p,error:g}=await V.from("email_campaign_recipients").select("email, name, contact_id").eq("campaign_id",i.id).eq("status","sent").is("opened_at",null).limit(5e3);if(g)throw g;if(!p||p.length===0){ae.info("All recipients opened — nothing to resend!"),l(null),c(!1);return}const{data:x}=await V.from("email_campaigns").select("subject, body_html, from_email, reply_to_email").eq("id",i.id).single();if(!x)throw new Error("Original campaign not found");const{data:y,error:v}=await V.from("email_campaigns").insert({user_id:t.id,name:`${i.name} (Resend to non-openers)`,subject:x.subject,body_html:x.body_html,from_email:x.from_email,reply_to_email:x.reply_to_email,total_recipients:p.length,status:"draft"}).select("id").single();if(v)throw v;const _=p.map(C=>({campaign_id:y.id,contact_id:C.contact_id,email:C.email,name:C.name,status:"pending"}));for(let C=0;C<_.length;C+=500){const A=_.slice(C,C+500),{error:M}=await V.from("email_campaign_recipients").insert(A);if(M)throw M}const{error:j}=await V.functions.invoke("ses-send-campaign",{body:{action:"send_campaign",campaign_id:y.id}});if(j)throw j;ae.success(`Resending to ${p.length} non-opener${p.length===1?"":"s"}!`),l(null),n.invalidateQueries({queryKey:["newsletter-campaigns"]})}catch(p){console.error("Resend failed:",p),ae.error(`Resend failed: ${p.message}`)}finally{c(!1)}}};return u?e.jsx("div",{className:"text-sm text-muted-foreground",children:"Loading campaigns…"}):d.length===0?null:e.jsxs(e.Fragment,{children:[e.jsx(we,{children:e.jsxs(De,{className:"p-0",children:[e.jsxs("div",{className:"px-4 py-3 border-b flex items-center gap-2",children:[e.jsx(Ul,{className:"h-4 w-4 text-primary"}),e.jsx("h2",{className:"font-semibold text-sm",children:"Newsletter Campaigns"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"— open & click tracking"})]}),e.jsx("div",{className:"divide-y",children:d.map(p=>{const g=p.sent_count||0,x=g>0?p.open_count/g*100:0,y=g>0?p.click_count/g*100:0,v=p.sent_at?I2(new Date,new Date(p.sent_at)):0,_=p.status==="sent"&&v>=3&&g>0&&p.open_counta(p.id),children:[e.jsx(ba,{className:"h-3.5 w-3.5 mr-1"})," Details"]}),_&&e.jsxs($,{variant:"outline",size:"sm",onClick:()=>l(p),children:[e.jsx(W8,{className:"h-3.5 w-3.5 mr-1"})," Resend"]})]})]}),p.status==="sent"&&g>0&&e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3 mt-3",children:[e.jsx(jae,{icon:e.jsx(Wr,{className:"h-3.5 w-3.5"}),label:"Sent",value:g,sub:`of ${p.total_recipients}`}),e.jsx(jae,{icon:e.jsx(ba,{className:"h-3.5 w-3.5 text-blue-600"}),label:"Opens",value:p.open_count,sub:`${x.toFixed(1)}%`,children:e.jsx(ho,{value:x,className:"h-1 mt-1"})}),e.jsx(jae,{icon:e.jsx(rh,{className:"h-3.5 w-3.5 text-purple-600"}),label:"Clicks",value:p.click_count,sub:`${y.toFixed(1)}%`,children:e.jsx(ho,{value:y,className:"h-1 mt-1"})}),e.jsx(jae,{icon:e.jsx(Qz,{className:"h-3.5 w-3.5 text-orange-600"}),label:"Bounces",value:p.bounce_count,sub:p.bounce_count>0?"review":"none"})]})]},p.id)})})]})}),e.jsx(D_,{open:!!r,onOpenChange:p=>!p&&a(null),children:e.jsxs(Mb,{className:"w-full sm:max-w-2xl overflow-y-auto",children:[e.jsx(xj,{children:e.jsx(yj,{children:"Recipient Activity"})}),e.jsx("div",{className:"mt-4 space-y-1",children:h?h.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No recipients yet."}):e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"text-xs uppercase text-muted-foreground border-b",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left py-2",children:"Recipient"}),e.jsx("th",{className:"text-left py-2",children:"Opened"}),e.jsx("th",{className:"text-left py-2",children:"Clicked"}),e.jsx("th",{className:"text-left py-2",children:"Status"})]})}),e.jsx("tbody",{children:h.map(p=>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:p.name||"—"}),e.jsx("div",{className:"text-xs text-muted-foreground truncate max-w-[180px]",children:p.email})]}),e.jsx("td",{className:"py-2 text-xs",children:p.opened_at?e.jsx(qe,{variant:"default",className:"text-xs",children:Ys(new Date(p.opened_at),"MMM d")}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx("td",{className:"py-2 text-xs",children:p.clicked_at?e.jsx(qe,{variant:"default",className:"text-xs bg-purple-600",children:Ys(new Date(p.clicked_at),"MMM d")}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsxs("td",{className:"py-2 text-xs",children:[p.status==="sent"&&e.jsx(qe,{variant:"outline",className:"text-xs",children:"sent"}),p.status==="pending"&&e.jsx(qe,{variant:"secondary",className:"text-xs",children:"queued"}),p.status==="failed"&&e.jsx(qe,{variant:"destructive",className:"text-xs",title:p.error_message||"",children:"failed"}),p.status==="suppressed"&&e.jsx(qe,{variant:"outline",className:"text-xs",children:"suppressed"})]})]},p.id))})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading…"})})]})}),e.jsx(oc,{open:!!i,onOpenChange:p=>!p&&l(null),children:e.jsxs(Ql,{children:[e.jsxs(Jl,{children:[e.jsx(tc,{children:"Resend to non-openers?"}),e.jsxs(sc,{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(ec,{children:[e.jsx(nc,{disabled:o,children:"Cancel"}),e.jsx(Vl,{onClick:m,disabled:o,children:o?e.jsxs(e.Fragment,{children:[e.jsx(Jt,{className:"h-4 w-4 mr-1 animate-spin"}),"Resending…"]}):e.jsxs(e.Fragment,{children:[e.jsx(W8,{className:"h-4 w-4 mr-1"}),"Resend"]})})]})]})})]})}function jae({icon:s,label:t,value:n,sub:r,children:a}){return e.jsxs("div",{className:"rounded-lg border bg-muted/20 p-2.5",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-muted-foreground",children:[s,t]}),e.jsxs("div",{className:"flex items-baseline gap-1.5 mt-0.5",children:[e.jsx("span",{className:"text-lg font-bold",children:n.toLocaleString()}),r&&e.jsx("span",{className:"text-xs text-muted-foreground",children:r})]}),a]})}async function iQ(){var r;const{data:{session:s}}=await V.auth.getSession(),t=s!=null&&s.expires_at?s.expires_at*1e3:0;if(!(s!=null&&s.access_token)||t-Date.now()<12e4){const{data:a,error:i}=await V.auth.refreshSession();if(i||!((r=a.session)!=null&&r.access_token))throw new Error("Your session expired. Please refresh the page (or sign in again) and try sending once more.");return a.session.access_token}return s.access_token}function c4n(){const{user:s}=ks(),t=Jn(),n=ls(),{data:r=[],isLoading:a}=pt({queryKey:["scheduled-email-campaigns",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:d,error:u}=await V.from("email_campaigns").select("id, name, subject, scheduled_at, total_recipients, status, created_at").eq("user_id",s.id).eq("status","scheduled").order("scheduled_at",{ascending:!0});if(u)throw u;return d||[]},refetchInterval:3e4}),i=async(d,u)=>{const h=await iQ(),p=await(await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/ses-schedule-campaign",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${h}`},body:JSON.stringify({action:d,campaign_id:u})})).json();if(!p.success)throw new Error(p.error||`Failed to ${d}`);return p},l=Nt({mutationFn:d=>i("cancel",d),onSuccess:()=>{ae.success("Schedule cancelled — saved as draft"),n.invalidateQueries({queryKey:["scheduled-email-campaigns"]})},onError:d=>ae.error(d.message)}),o=Nt({mutationFn:d=>i("delete",d),onSuccess:()=>{ae.success("Scheduled email deleted"),n.invalidateQueries({queryKey:["scheduled-email-campaigns"]})},onError:d=>ae.error(d.message)}),c=Nt({mutationFn:async({id:d,iso:u})=>{const{error:h}=await V.from("email_campaigns").update({scheduled_at:u,status:"scheduled"}).eq("id",d);if(h)throw h;await i("schedule",d)},onSuccess:()=>{ae.success("Send time updated"),n.invalidateQueries({queryKey:["scheduled-email-campaigns"]})},onError:d=>ae.error(d.message)});return a?e.jsx("div",{className:"text-center py-12 text-muted-foreground",children:"Loading scheduled emails..."}):r.length===0?e.jsx(we,{children:e.jsxs(De,{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-3"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No scheduled emails."}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Emails you schedule for the future will appear here."})]})}):e.jsx("div",{className:"space-y-3",children:r.map(d=>e.jsx(d4n,{campaign:d,onEdit:()=>t(`/admin/email-campaigns/new?edit=${d.id}`),onCancel:()=>l.mutate(d.id),onDelete:()=>o.mutate(d.id),onReschedule:u=>c.mutate({id:d.id,iso:u}),isBusy:l.isPending||o.isPending||c.isPending},d.id))})}function d4n({campaign:s,onEdit:t,onCancel:n,onDelete:r,onReschedule:a,isBusy:i}){const l=s.scheduled_at?new Date(s.scheduled_at):null,[o,c]=k.useState(!1),[d,u]=k.useState(l||void 0),[h,m]=k.useState(l?`${String(l.getHours()).padStart(2,"0")}:${String(l.getMinutes()).padStart(2,"0")}`:"09:00"),p=()=>{if(!d)return ae.error("Pick a date");const g=new Date(`${Ys(d,"yyyy-MM-dd")}T${h}:00`).toISOString();if(new Date(g).getTime()gm(g.target.value)})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"ghost",onClick:()=>c(!1),children:"Cancel"}),e.jsxs($,{onClick:p,disabled:i,children:[i&&e.jsx(Jt,{className:"h-4 w-4 mr-1.5 animate-spin"}),"Save new time"]})]})]})]}),e.jsxs(oc,{children:[e.jsx(_g,{asChild:!0,children:e.jsxs($,{size:"sm",variant:"outline",disabled:i,children:[e.jsx(ju,{className:"h-3.5 w-3.5 mr-1.5"})," Cancel Send"]})}),e.jsxs(Ql,{children:[e.jsxs(Jl,{children:[e.jsx(tc,{children:"Cancel this scheduled send?"}),e.jsxs(sc,{children:["The email will move back to ",e.jsx("strong",{children:"Draft"})," and won't send at the scheduled time. You can re-schedule or delete it later."]})]}),e.jsxs(ec,{children:[e.jsx(nc,{children:"Keep scheduled"}),e.jsx(Vl,{onClick:n,children:"Cancel send"})]})]})]}),e.jsxs(oc,{children:[e.jsx(_g,{asChild:!0,children:e.jsxs($,{size:"sm",variant:"ghost",className:"text-destructive hover:text-destructive",disabled:i,children:[e.jsx(Un,{className:"h-3.5 w-3.5 mr-1.5"})," Delete"]})}),e.jsxs(Ql,{children:[e.jsxs(Jl,{children:[e.jsx(tc,{children:"Delete this scheduled email?"}),e.jsx(sc,{children:"This permanently removes the scheduled email and all its recipient records. This can't be undone."})]}),e.jsxs(ec,{children:[e.jsx(nc,{children:"Keep"}),e.jsx(Vl,{onClick:r,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete permanently"})]})]})]})]})]})})})}function u4n({pct:s,size:t=132,label:n}){const a=(t-10)/2,i=2*Math.PI*a,l=Math.max(0,Math.min(100,s)),o=i-l/100*i;return e.jsxs("div",{className:"relative shrink-0",style:{width:t,height:t},children:[e.jsxs("svg",{width:t,height:t,className:"-rotate-90 text-primary",children:[e.jsx("circle",{cx:t/2,cy:t/2,r:a,fill:"none",strokeWidth:10,className:"stroke-muted"}),e.jsx("circle",{cx:t/2,cy:t/2,r:a,fill:"none",strokeWidth:10,strokeLinecap:"round",stroke:"currentColor",strokeDasharray:i,strokeDashoffset:o,style:{transition:"stroke-dashoffset 700ms ease"}})]}),e.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center",children:[e.jsxs("span",{className:"text-3xl font-semibold tabular-nums",children:[Math.round(l),"%"]}),e.jsx("span",{className:"text-[10px] uppercase tracking-wider text-muted-foreground",children:n})]})]})}function Nae({icon:s,label:t,value:n,hint:r,tone:a="default",onClick:i}){const l=i?"button":"div";return e.jsxs(l,{onClick:i,className:Ot("group relative flex flex-col justify-between rounded-2xl border bg-card p-4 text-left transition-colors",i&&"hover:bg-accent/50 cursor-pointer",a==="warm"&&"border-orange-500/30 bg-orange-500/[0.04]",a==="alert"&&"border-amber-500/30 bg-amber-500/[0.04]"),children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5 text-[11px] font-medium uppercase tracking-wide text-muted-foreground",children:[s,t]}),i&&e.jsx(fi,{className:"h-3.5 w-3.5 text-muted-foreground opacity-0 group-hover:opacity-100 transition-opacity"})]}),e.jsxs("div",{className:"mt-2",children:[e.jsx("div",{className:"text-2xl font-semibold tabular-nums leading-none",children:n}),r&&e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:r})]})]})}function h4n({total:s,opened:t,clicked:n,trackable:r,scheduled:a,rangeLabel:i,channelSummary:l,onScheduledClick:o}){const c=r>0?t/r*100:0,d=r>0?n/r*100:0;return e.jsx("div",{className:"rounded-3xl border bg-gradient-to-br from-primary/[0.06] via-card to-card p-5 md:p-6",children:e.jsxs("div",{className:"grid gap-5 lg:grid-cols-[auto_1fr] lg:items-center",children:[e.jsxs("div",{className:"flex items-center gap-5",children:[e.jsx(u4n,{pct:c,label:"open rate"}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-[11px] uppercase tracking-wider text-muted-foreground",children:i}),e.jsxs("h2",{className:"mt-1 text-xl font-semibold leading-tight",children:[s.toLocaleString()," email",s===1?"":"s"," sent"]}),e.jsx("p",{className:"mt-1 text-sm text-muted-foreground line-clamp-2",children:l||"No sends in this window yet."}),r>0&&e.jsxs("p",{className:"mt-2 text-xs text-muted-foreground",children:[t.toLocaleString()," opens · ",n.toLocaleString()," clicks across ",r.toLocaleString()," tracked"]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3 xl:grid-cols-4",children:[e.jsx(Nae,{icon:e.jsx(Gr,{className:"h-3.5 w-3.5"}),label:"Delivered",value:s.toLocaleString(),hint:"All sends completed"}),e.jsx(Nae,{icon:e.jsx(ba,{className:"h-3.5 w-3.5"}),label:"Opened",value:t.toLocaleString(),hint:r>0?`${Math.round(c)}% of tracked`:"No tracked emails"}),e.jsx(Nae,{icon:e.jsx(rh,{className:"h-3.5 w-3.5"}),label:"Clicked",value:n.toLocaleString(),hint:r>0?`${Math.round(d)}% of tracked`:"No tracked emails",tone:n>0?"warm":"default"}),e.jsx(Nae,{icon:e.jsx(sa,{className:"h-3.5 w-3.5"}),label:"Scheduled",value:a.toLocaleString(),hint:a>0?"Editable before send":"Nothing queued",tone:a>0?"alert":"default",onClick:o})]})]})})}const Wyt=["Gmail","Mass Email","Campaign","Client Portal Invite"],m4n={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 f4n(){const{user:s}=ks(),[t,n]=Jc(),{data:r=[],isLoading:a}=s9t(),[i,l]=k.useState(""),[o,c]=k.useState("all"),[d,u]=k.useState("30"),[h,m]=k.useState(!1),[p,g]=k.useState(t.get("tab")==="scheduled"?"scheduled":"sent"),{gmailEmail:x}=dx(),{data:y=0}=pt({queryKey:["scheduled-email-count",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{count:I}=await V.from("email_campaigns").select("id",{count:"exact",head:!0}).eq("user_id",s.id).eq("status","scheduled");return I||0},refetchInterval:3e4});k.useEffect(()=>{const I=new URLSearchParams(t);p==="scheduled"?I.set("tab","scheduled"):I.delete("tab"),n(I,{replace:!0})},[p]);const v=k.useMemo(()=>Array.from(new Set(r.map(I=>I.contact_id).filter(Boolean))),[r]),{data:_}=pt({queryKey:["sent-emails-contact-names",s==null?void 0:s.id,v.length],enabled:v.length>0,queryFn:async()=>{const{data:I}=await V.from("innercircle_contacts").select("id, first_name, last_name").in("id",v),P=new Map;return(I||[]).forEach(R=>{P.set(R.id,[R.first_name,R.last_name].filter(Boolean).join(" ")||"Contact")}),P}}),j=k.useMemo(()=>{const I=d==="all"?null:Date.now()-parseInt(d)*864e5,P=i.trim().toLowerCase();return r.filter(R=>{if(o!=="all"&&R.channel!==o||I&&new Date(R.sent_at).getTime(){const I={};let P=0,R=0,O=0;return j.forEach(B=>{I[B.channel]=(I[B.channel]||0)+1,(B.channel==="Campaign"||B.channel==="Mass Email")&&(O++,B.opened_at&&P++,B.clicked_at&&R++)}),{byChannel:I,opened:P,clicked:R,trackable:O}},[j]),A=d==="all"?"All time":`Last ${d} days`,M=Wyt.map(I=>C.byChannel[I]?`${C.byChannel[I]} ${I}`:null).filter(Boolean).join(" · ");return e.jsx(Xs,{children:e.jsxs("div",{className:"space-y-5 p-4 md:p-8",children:[e.jsxs("div",{className:"flex flex-col gap-3 md:flex-row md:items-center md:justify-between",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("h1",{className:"text-2xl font-bold flex items-center gap-2",children:[e.jsx(Wr,{className:"h-6 w-6"})," Sent Emails"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Every send in one place — Gmail, mass emails, campaigns, and portal invites."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"inline-flex rounded-full border bg-muted/40 p-1",children:[e.jsxs("button",{onClick:()=>g("sent"),className:`inline-flex items-center gap-1.5 rounded-full px-3 py-1.5 text-sm transition-colors ${p==="sent"?"bg-background shadow-sm font-medium":"text-muted-foreground hover:text-foreground"}`,children:[e.jsx(Wr,{className:"h-3.5 w-3.5"})," Sent"]}),e.jsxs("button",{onClick:()=>g("scheduled"),className:`inline-flex items-center gap-1.5 rounded-full px-3 py-1.5 text-sm transition-colors ${p==="scheduled"?"bg-background shadow-sm font-medium":"text-muted-foreground hover:text-foreground"}`,children:[e.jsx(sa,{className:"h-3.5 w-3.5"})," Scheduled",y>0&&e.jsx(qe,{variant:"secondary",className:"ml-0.5 h-5 min-w-5 px-1.5 text-xs",children:y})]})]}),e.jsxs($,{onClick:()=>m(!0),className:"rounded-full",children:[e.jsx(pn,{className:"h-4 w-4 mr-2"})," Send Email"]})]})]}),e.jsxs(ya,{value:p,onValueChange:I=>g(I),className:"space-y-5",children:[e.jsxs(cs,{value:"sent",className:"space-y-5 mt-0",children:[e.jsx(h4n,{total:j.length,opened:C.opened,clicked:C.clicked,trackable:C.trackable,scheduled:y,rangeLabel:A,channelSummary:M,onScheduledClick:()=>g("scheduled")}),e.jsxs("div",{className:"flex flex-col gap-2 rounded-2xl border bg-card p-2 md:flex-row md:items-center",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Yr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search subject, recipient, contact...",value:i,onChange:I=>l(I.target.value),className:"pl-9 border-0 bg-transparent shadow-none focus-visible:ring-0"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(bs,{value:o,onValueChange:c,children:[e.jsx(ys,{className:"w-[170px] rounded-full h-9",children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"all",children:"All Channels"}),Wyt.map(I=>e.jsx(We,{value:I,children:I},I))]})]}),e.jsxs(bs,{value:d,onValueChange:u,children:[e.jsx(ys,{className:"w-[150px] rounded-full h-9",children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"7",children:"Last 7 days"}),e.jsx(We,{value:"30",children:"Last 30 days"}),e.jsx(We,{value:"90",children:"Last 90 days"}),e.jsx(We,{value:"365",children:"Last year"}),e.jsx(We,{value:"all",children:"All time"})]})]})]})]}),e.jsxs("p",{className:"text-xs text-muted-foreground -mt-3 px-1",children:[e.jsx(T5,{className:"h-3 w-3 inline mr-1"}),"Open & click tracking is available for Mass Emails and Campaigns. Emails sent through your connected Gmail inbox aren't tracked."]}),e.jsx(l4n,{rangeDays:d==="all"?null:parseInt(d)}),a?e.jsx("div",{className:"text-center py-12 text-muted-foreground",children:"Loading..."}):j.length===0?e.jsx(we,{className:"rounded-2xl",children:e.jsxs(De,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(pn,{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(we,{className:"rounded-2xl overflow-hidden",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("th",{className:"text-left py-3 px-4 font-medium",children:e.jsx(Sk,{children:e.jsxs(Lx,{children:[e.jsxs(Rx,{className:"inline-flex items-center gap-1",children:["Engagement ",e.jsx(T5,{className:"h-3 w-3"})]}),e.jsx(Jg,{className:"max-w-xs",children:"Open & click tracking works for Mass Emails and Campaigns. Emails sent through your connected Gmail inbox aren't tracked."})]})})})]})}),e.jsx("tbody",{children:j.slice(0,500).map(I=>{const P=I.contact_id?_==null?void 0:_.get(I.contact_id):null,R=I.channel==="Campaign"||I.channel==="Mass Email";return e.jsxs("tr",{className:"border-t hover:bg-muted/30",children:[e.jsx("td",{className:"py-3 px-4 whitespace-nowrap text-muted-foreground",children:Ys(new Date(I.sent_at),"MMM d, yyyy h:mm a")}),e.jsx("td",{className:"py-3 px-4",children:e.jsx(qe,{variant:"outline",className:m4n[I.channel],children:I.channel})}),e.jsx("td",{className:"py-3 px-4 max-w-xs truncate font-medium",children:I.subject}),e.jsx("td",{className:"py-3 px-4 text-muted-foreground",children:I.to_email}),e.jsx("td",{className:"py-3 px-4",children:I.contact_id&&P?e.jsx(nr,{to:`/mission-control/contacts/${I.contact_id}`,className:"text-primary hover:underline",children:P}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx("td",{className:"py-3 px-4",children:R?e.jsxs("div",{className:"flex flex-wrap gap-1",children:[e.jsxs(qe,{variant:"outline",className:"bg-slate-50 text-slate-700 border-slate-200 gap-1",children:[e.jsx(Gr,{className:"h-3 w-3"})," Delivered"]}),I.opened_at&&e.jsxs(qe,{variant:"outline",className:"bg-blue-50 text-blue-700 border-blue-200 gap-1",children:[e.jsx(ba,{className:"h-3 w-3"})," Opened"]}),I.clicked_at&&e.jsxs(qe,{variant:"outline",className:"bg-emerald-50 text-emerald-700 border-emerald-200 gap-1",children:[e.jsx(rh,{className:"h-3 w-3"})," Clicked"]})]}):e.jsx("span",{className:"text-xs text-muted-foreground",children:"Not tracked"})})]},I.id)})})]}),j.length>500&&e.jsxs("p",{className:"text-xs text-muted-foreground text-center py-3 border-t",children:["Showing first 500 of ",j.length," — narrow your filters to see more."]})]})})})]}),e.jsx(cs,{value:"scheduled",className:"mt-0",children:e.jsx(c4n,{})})]}),e.jsx(W2,{open:h,onOpenChange:m,gmailEmail:x})]})})}const Kyt={Crown:ky,FileText:ea,Users:Xn,Globe:kc,Star:ri,Phone:ka,MessageSquare:bo,PenTool:YT,Video:ia,Gift:Zo},kae=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function p4n(){var rt,Ft;const s=Jn(),{user:t}=ks(),{data:n}=vj(),{data:r}=EEs(),{data:a}=DEs(),{data:i}=WMt(),{data:l}=Aee(),{data:o}=AEs(),c=OEs(),d=TEs(),u=PEs(),h=IEs(),m=LEs(),p=REs(),g=MEs(),[x,y]=k.useState(null),[v,_]=k.useState(!1),[j,C]=k.useState(null),[A,M]=k.useState(""),[I,P]=k.useState(""),[R,O]=k.useState([]),[B,U]=k.useState(null),[G,H]=k.useState(null),[Y,se]=k.useState(null),[ee,oe]=k.useState(!1),[me,Q]=k.useState(""),[te,le]=k.useState(""),[fe,_e]=k.useState(""),[ve,he]=k.useState(""),Se=(Ut,Is)=>a==null?void 0:a.some(xs=>xs.plan_id===Ut&&xs.relationship_type_id===Is&&xs.active),Te=Ut=>a==null?void 0:a.find(Is=>Is.relationship_type_id===Ut&&Is.active),Ie=async(Ut,Is)=>{const xs=Se(Ut,Is);await c.mutateAsync({planId:Ut,relationshipTypeId:Is,active:!xs})},Ue=(r==null?void 0:r.filter(Ut=>Ut.active&&!Ut.owner_user_id))||[],Be=(r==null?void 0:r.filter(Ut=>Ut.owner_user_id===(t==null?void 0:t.id)))||[],je=n==null?void 0:n.find(Ut=>Ut.id===x),Ye=x?Te(x):null,Ee=r==null?void 0:r.find(Ut=>Ut.id===(Ye==null?void 0:Ye.plan_id)),Re=async()=>{if(!A.trim())return;const Ut=await d.mutateAsync({name:A,description:I});Ut&&R.length>0&&await m.mutateAsync({planId:Ut.id,items:R}),Ge()},ke=async()=>{!A.trim()||!j||(await u.mutateAsync({id:j,name:A,description:I}),await m.mutateAsync({planId:j,items:R}),Ge())},Fe=Ut=>{var Is;C(Ut.id),M(Ut.name),P(Ut.description||""),O(((Is=Ut.items)==null?void 0:Is.map(xs=>({month_number:xs.month_number,action_type_id:xs.action_type_id,default_script_id:xs.default_script_id||void 0,notes:xs.notes||void 0})))||[]),_(!0)},Oe=async(Ut,Is)=>{if(Ut.owner_user_id===(t==null?void 0:t.id)){Fe(Ut);return}try{const xs=await g.mutateAsync({sourcePlanId:Ut.id,newName:`${Ut.name} (My Copy)`});if(!xs)return;await c.mutateAsync({planId:Ut.id,relationshipTypeId:Is,active:!1}),await c.mutateAsync({planId:xs.id,relationshipTypeId:Is,active:!0}),C(xs.id),M(xs.name),P(xs.description||""),O((Ut.items||[]).map(st=>({month_number:st.month_number,action_type_id:st.action_type_id,default_script_id:st.default_script_id||void 0,notes:st.notes||void 0}))),_(!0)}catch{}},Ge=()=>{_(!1),C(null),M(""),P(""),O([])},yt=(Ut,Is)=>{H(Is)},tt=(Ut,Is,xs)=>{O(st=>[...st.filter(jt=>jt.month_number!==Ut),{month_number:Ut,action_type_id:Is,default_script_id:xs}]),U(null),H(null)},ut=Ut=>{O(Is=>Is.filter(xs=>xs.month_number!==Ut))},nt=async()=>{if(!me.trim()||!te.trim()||!G)return;const Ut=await p.mutateAsync({actionTypeId:G,title:me,scriptBody:te,emailSubject:fe||void 0,tone:ve||void 0});Ut&&B!==null&&tt(B,G,Ut.id),oe(!1),Q(""),le(""),_e(""),he("")},et=G?o==null?void 0:o.filter(Ut=>Ut.action_type_id===G&&Ut.active):[],at=Ut=>Kyt[Ut||"Phone"]||ka,wt=Ut=>Kyt[Ut||"Users"]||Xn;return e.jsxs(Xs,{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($,{variant:"ghost",size:"sm",onClick:()=>s("/mission-control"),children:[e.jsx(Ld,{className:"h-4 w-4 mr-1"}),"Back"]}),e.jsxs($,{onClick:()=>_(!0),className:"w-full sm:w-auto",children:[e.jsx(nn,{className:"h-4 w-4 mr-2"}),"Create Custom Plan"]})]}),e.jsxs("div",{className:"grid lg:grid-cols-3 gap-6",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx("h3",{className:"font-semibold text-lg",children:"Your Contact Groups"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Select a group to assign a touchpoint plan"}),n==null?void 0:n.filter(Ut=>Ut.active).map(Ut=>{const Is=wt(Ut.icon),xs=(i==null?void 0:i[Ut.id])||0,st=Te(Ut.id),dt=r==null?void 0:r.find(gt=>gt.id===(st==null?void 0:st.plan_id)),jt=x===Ut.id;return e.jsxs("button",{onClick:()=>y(Ut.id),className:` w-full flex items-center gap-3 p-4 rounded-lg border text-left transition-all ${jt?"border-primary bg-primary/5 ring-2 ring-primary":"hover:bg-accent"} `,children:[e.jsx(Is,{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:Ut.name}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[xs," contacts"]})]}),dt?e.jsxs(qe,{variant:"secondary",className:"text-xs",children:[e.jsx(nl,{className:"h-3 w-3 mr-1"}),dt.name.split(" ")[0]]}):e.jsx(qe,{variant:"outline",className:"text-xs text-muted-foreground",children:"No plan"})]},Ut.id)})]}),e.jsx("div",{className:"lg:col-span-2",children:x&&je?e.jsxs(we,{children:[e.jsxs(Vt,{children:[e.jsxs(Yt,{className:"flex items-center gap-2",children:[(()=>{const Ut=wt(je.icon);return e.jsx(Ut,{className:"h-5 w-5"})})(),je.name," Touchpoint Plan"]}),e.jsxs(vr,{children:["Choose a plan for your ",je.name," contacts"]})]}),e.jsxs(De,{className:"space-y-6",children:[Ee&&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(nl,{className:"h-4 w-4 text-green-500"}),"Currently using: ",Ee.name]}),Ee.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:Ee.description})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs($,{variant:"outline",size:"sm",disabled:g.isPending||c.isPending,onClick:()=>Oe(Ee,x),children:[e.jsx(s2,{className:"h-4 w-4 mr-1"}),"Edit Steps"]}),e.jsx($,{variant:"outline",size:"sm",onClick:()=>Ie(Ee.id,x),children:"Disable"})]})]}),Ee.items&&Ee.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(ha,{className:"h-4 w-4"}),"12-Month Schedule"]}),e.jsx("div",{className:"grid grid-cols-4 sm:grid-cols-6 gap-2",children:kae.map((Ut,Is)=>{var jt,gt;const xs=((jt=Ee.items)==null?void 0:jt.filter(rs=>rs.month_number===Is+1))||[],st=(gt=xs[0])==null?void 0:gt.action_type,dt=st?at(st.icon):null;return e.jsxs("div",{className:` p-2 rounded border text-center ${xs.length>0?"bg-primary/10 border-primary":"bg-muted"} `,children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:Ut}),dt&&e.jsx(dt,{className:"h-4 w-4 mx-auto mt-1",style:{color:(st==null?void 0:st.color)||"#3B82F6"}})]},Is)})})]})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium mb-3",children:Ee?"Switch to a Different Plan":"Choose a Plan"}),Ue.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"}),Ue.map(Ut=>{var xs;const Is=(Ee==null?void 0:Ee.id)===Ut.id;return e.jsxs("div",{className:` flex items-center justify-between p-3 rounded-lg border ${Is?"opacity-50":"hover:bg-accent"} `,children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:Ut.name}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[((xs=Ut.items)==null?void 0:xs.length)||0," touchpoints/year"]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{size:"sm",variant:"ghost",title:"View plan details",onClick:()=>se(Ut.id),children:e.jsx(ba,{className:"h-4 w-4"})}),e.jsx($,{size:"sm",variant:"ghost",title:"Duplicate as my own plan",disabled:g.isPending,onClick:()=>{const st=`${Ut.name} (Copy)`;g.mutate({sourcePlanId:Ut.id,newName:st})},children:e.jsx(Da,{className:"h-4 w-4"})}),e.jsx($,{size:"sm",variant:Is?"outline":"default",disabled:Is||c.isPending,onClick:()=>Ie(Ut.id,x),children:Is?"Active":"Use This"})]})]},Ut.id)})]}),Be.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-sm text-muted-foreground",children:"My Custom Plans"}),Be.map(Ut=>{var xs;const Is=(Ee==null?void 0:Ee.id)===Ut.id;return e.jsxs("div",{className:` flex items-center justify-between p-3 rounded-lg border ${Is?"opacity-50":"hover:bg-accent"} `,children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:Ut.name}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[((xs=Ut.items)==null?void 0:xs.length)||0," touchpoints/year"]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{size:"sm",variant:"ghost",title:"View plan details",onClick:()=>se(Ut.id),children:e.jsx(ba,{className:"h-4 w-4"})}),e.jsx($,{size:"sm",variant:"ghost",title:"Edit plan",onClick:()=>Fe(Ut),children:e.jsx(s2,{className:"h-4 w-4"})}),e.jsx($,{size:"sm",variant:"ghost",title:"Delete plan",onClick:()=>h.mutate(Ut.id),children:e.jsx(Un,{className:"h-4 w-4 text-destructive"})}),e.jsx($,{size:"sm",variant:Is?"outline":"default",disabled:Is||c.isPending,onClick:()=>Ie(Ut.id,x),children:Is?"Active":"Use This"})]})]},Ut.id)})]}),Ue.length===0&&Be.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No plans available. Create a custom plan to get started."})]})]})]}):e.jsx(we,{children:e.jsxs(De,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(ha,{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(we,{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(zs,{open:v,onOpenChange:Ut=>{Ut?_(!0):Ge()},children:e.jsxs(Rs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Vs,{children:e.jsx($s,{children:j?"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(re,{htmlFor:"plan-name",children:"Plan Name"}),e.jsx(be,{id:"plan-name",value:A,onChange:Ut=>M(Ut.target.value),placeholder:"e.g., My VIP Plan"})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"plan-description",children:"Description (optional)"}),e.jsx(Ls,{id:"plan-description",value:I,onChange:Ut=>P(Ut.target.value),placeholder:"Describe your plan...",rows:2})]})]}),e.jsxs("div",{children:[e.jsx(re,{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:kae.map((Ut,Is)=>{const xs=Is+1,st=R.find(gt=>gt.month_number===xs),dt=st?l==null?void 0:l.find(gt=>gt.id===st.action_type_id):null,jt=dt?at(dt.icon):null;return e.jsxs("div",{className:"relative",children:[e.jsxs("button",{type:"button",onClick:()=>U(B===xs?null:xs),className:` w-full p-3 rounded-lg border text-center transition-all ${st?"bg-primary/10 border-primary":"bg-muted hover:bg-accent"} ${B===xs?"ring-2 ring-primary":""} `,children:[e.jsx("div",{className:"text-xs text-muted-foreground font-medium",children:Ut}),jt?e.jsx(jt,{className:"h-5 w-5 mx-auto mt-1",style:{color:(dt==null?void 0:dt.color)||"#3B82F6"}}):e.jsx(nn,{className:"h-5 w-5 mx-auto mt-1 text-muted-foreground/50"})]}),st&&e.jsx("button",{type:"button",onClick:gt=>{gt.stopPropagation(),ut(xs)},className:"absolute -top-1 -right-1 p-1 bg-destructive text-destructive-foreground rounded-full",children:e.jsx(mr,{className:"h-3 w-3"})})]},Is)})}),B!==null&&!G&&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 ",kae[B-1],":"]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:l==null?void 0:l.filter(Ut=>Ut.active).map(Ut=>{const Is=at(Ut.icon);return e.jsxs("button",{type:"button",onClick:()=>yt(B,Ut.id),className:"flex items-center gap-2 px-3 py-2 rounded-lg border bg-background hover:bg-accent transition-colors",children:[e.jsx(Is,{className:"h-4 w-4",style:{color:Ut.color||"#3B82F6"}}),e.jsx("span",{className:"text-sm",children:Ut.name})]},Ut.id)})})]}),B!==null&&G&&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($,{variant:"ghost",size:"sm",onClick:()=>H(null),children:[e.jsx(Ld,{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:()=>tt(B,G),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"})]})}),et==null?void 0:et.map(Ut=>e.jsx("button",{type:"button",onClick:()=>tt(B,G,Ut.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:Ut.title}),Ut.tone&&e.jsx(qe,{variant:"secondary",className:"text-xs mt-1",children:Ut.tone}),e.jsxs("div",{className:"text-xs text-muted-foreground mt-1 line-clamp-2",children:[Ut.script_body.substring(0,100),"..."]})]})},Ut.id)),e.jsxs("button",{type:"button",onClick:()=>oe(!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(nn,{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"})]})]})]})]})]}),R.length>0&&e.jsxs("div",{className:"text-sm text-muted-foreground",children:[R.length," touchpoint",R.length!==1?"s":""," per year"]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:Ge,children:"Cancel"}),e.jsxs($,{onClick:j?ke:Re,disabled:!A.trim()||d.isPending||u.isPending,children:[e.jsx(Ml,{className:"h-4 w-4 mr-2"}),j?"Save Changes":"Create Plan"]})]})]})}),e.jsx(zs,{open:ee,onOpenChange:oe,children:e.jsxs(Rs,{className:"max-w-lg",children:[e.jsx(Vs,{children:e.jsx($s,{children:"Create Custom Script"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(re,{htmlFor:"script-title",children:"Script Title"}),e.jsx(be,{id:"script-title",value:me,onChange:Ut=>Q(Ut.target.value),placeholder:"e.g., Friendly Check-in Call"})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"script-tone",children:"Tone (optional)"}),e.jsxs(bs,{value:ve,onValueChange:he,children:[e.jsx(ys,{children:e.jsx(_s,{placeholder:"Select tone..."})}),e.jsxs(vs,{children:[e.jsx(We,{value:"friendly",children:"Friendly"}),e.jsx(We,{value:"professional",children:"Professional"}),e.jsx(We,{value:"casual",children:"Casual"}),e.jsx(We,{value:"formal",children:"Formal"})]})]})]}),((Ft=(rt=l==null?void 0:l.find(Ut=>Ut.id===G))==null?void 0:rt.name)==null?void 0:Ft.toLowerCase().includes("email"))&&e.jsxs("div",{children:[e.jsx(re,{htmlFor:"script-email-subject",children:"Email Subject"}),e.jsx(be,{id:"script-email-subject",value:fe,onChange:Ut=>_e(Ut.target.value),placeholder:"e.g., Quick Hello!"})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"script-body",children:"Script Content"}),e.jsx(Ls,{id:"script-body",value:te,onChange:Ut=>le(Ut.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(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>oe(!1),children:"Cancel"}),e.jsxs($,{onClick:nt,disabled:!me.trim()||!te.trim()||p.isPending,children:[e.jsx(Ml,{className:"h-4 w-4 mr-2"}),"Create & Use Script"]})]})]})}),e.jsx(zs,{open:!!Y,onOpenChange:Ut=>{Ut||se(null)},children:e.jsx(Rs,{className:"max-w-3xl max-h-[90vh] overflow-y-auto",children:(()=>{const Ut=r==null?void 0:r.find(st=>st.id===Y);if(!Ut)return null;const Is=Ut.owner_user_id===(t==null?void 0:t.id),xs=[...Ut.items||[]].sort((st,dt)=>st.month_number-dt.month_number);return e.jsxs(e.Fragment,{children:[e.jsxs(Vs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[Ut.name,!Is&&e.jsx(qe,{variant:"secondary",children:"Template"})]}),Ut.description&&e.jsx("p",{className:"text-sm text-muted-foreground",children:Ut.description})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"text-sm text-muted-foreground",children:[xs.length," touchpoint",xs.length!==1?"s":""," per year"]}),e.jsx("div",{className:"space-y-2",children:Array.from({length:12},(st,dt)=>dt+1).map(st=>{const dt=xs.find(Ns=>Ns.month_number===st),jt=dt?l==null?void 0:l.find(Ns=>Ns.id===dt.action_type_id):null,gt=dt!=null&&dt.default_script_id?o==null?void 0:o.find(Ns=>Ns.id===dt.default_script_id):null,rs=jt?at(jt.icon):null;return e.jsxs("div",{className:`p-3 rounded-lg border flex items-start gap-3 ${dt?"bg-muted/30":"opacity-60"}`,children:[e.jsx("div",{className:"w-16 shrink-0 font-medium text-sm",children:kae[st-1]}),dt&&jt?e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[rs&&e.jsx(rs,{className:"h-4 w-4",style:{color:jt.color||"#3B82F6"}}),e.jsx("span",{className:"font-medium text-sm",children:jt.name}),gt&&e.jsx(qe,{variant:"outline",className:"text-xs",children:gt.title})]}),gt&&e.jsx("div",{className:"mt-2 text-sm text-muted-foreground whitespace-pre-wrap bg-background p-2 rounded border",children:gt.script_body}),dt.notes&&e.jsx("div",{className:"mt-1 text-xs text-muted-foreground italic",children:dt.notes})]}):e.jsx("div",{className:"flex-1 text-sm text-muted-foreground",children:"No touchpoint scheduled"})]},st)})})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>se(null),children:"Close"}),Is?e.jsxs($,{onClick:()=>{const st=r==null?void 0:r.find(dt=>dt.id===Y);st&&(se(null),Fe(st))},children:[e.jsx(s2,{className:"h-4 w-4 mr-2"}),"Edit Plan"]}):e.jsxs($,{disabled:g.isPending,onClick:()=>{g.mutate({sourcePlanId:Ut.id,newName:`${Ut.name} (Copy)`}),se(null)},children:[e.jsx(Da,{className:"h-4 w-4 mr-2"}),"Duplicate to Edit"]})]})]})})()})})]})}const sDe="https://cma.relevelup.com";function n9t({open:s,onOpenChange:t,cma:n}){var se;const{user:r}=ks(),{toast:a}=Fi(),[i,l]=k.useState([]),[o,c]=k.useState(null),[d,u]=k.useState(!1),[h,m]=k.useState(""),[p,g]=k.useState(""),[x,y]=k.useState(""),[v,_]=k.useState(!1),[j,C]=k.useState(null),[A,M]=k.useState(!1),[I,P]=k.useState(!1),[R,O]=k.useState(null);k.useEffect(()=>{!s||!r||(async()=>{var _e;const[ee,oe,me,Q,te]=await Promise.all([V.from("innercircle_contacts").select("id, first_name, last_name, email").eq("owner_user_id",r.id).not("email","is",null).order("first_name"),V.from("profiles").select("name, email, phone, brokerage_name, avatar_url, email_signature").eq("id",r.id).maybeSingle(),V.from("gmail_integrations").select("id, is_active").eq("user_id",r.id).maybeSingle(),V.from("ses_verified_emails").select("email, status").eq("user_id",r.id).eq("status","Success").limit(1),V.from("mass_email_settings").select("*").eq("user_id",r.id).maybeSingle()]),le=(ee.data||[]).filter(ve=>ve.email&&ve.email.includes("@"));l(le),C(oe.data||null),M(!!((_e=me.data)!=null&&_e.is_active)),P(!!(Q.data&&Q.data.length>0)),O(te.data||null);const fe=n.contact_id?le.find(ve=>ve.id===n.contact_id):null;fe&&(c(fe),m(fe.email))})()},[s,r,n.contact_id]),k.useEffect(()=>{var Q;if(!s)return;const ee=((Q=n.subject)==null?void 0:Q.address)||"your home",oe=((j==null?void 0:j.name)||"").split(" ")[0]||"your agent",me=(o==null?void 0:o.first_name)||"there";g(`Your home value report for ${ee}`),y(`Hi ${me}, I put together a fresh market analysis for ${ee}. It pulls live comparable sales, active listings, and pending homes near you so you can see exactly where your value sits today. Take a look here — it only takes a minute: {{cma_link}} When you've had a chance to review, I'd love to hear your thoughts. Reply to this email or give me a call any time. Talk soon, ${(j==null?void 0:j.name)||oe}`)},[s,o==null?void 0:o.id,j==null?void 0:j.name,(se=n.subject)==null?void 0:se.address]);const B=k.useMemo(()=>A?"Gmail (your inbox)":I?"Amazon SES":null,[A,I]),U=!!(h.trim()&&p.trim()&&x.trim()&&B&&!v),G=ee=>{c(ee),m(ee.email||""),u(!1)},H=ee=>{const oe=`${sDe}/${n.share_token}?e=${ee}`,te=x.replace(/&/g,"&").replace(//g,">").replace(/\{\{cma_link\}\}/g,`View Your Home Value Report`).split(/\n{2,}/).map(_e=>`

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

`).join(""),le=j!=null&&j.use_email_signature&&(j!=null&&j.email_signature)?`
${j.email_signature}
`:`
${j!=null&&j.name?`
${j.name}
`:""} ${j!=null&&j.brokerage_name?`
${j.brokerage_name}
`:""} ${j!=null&&j.phone?`
${j.phone}
`:""} ${j!=null&&j.email?``:""}
`,fe=``;return`
${te} ${le}
Prepared with LevelUp · ReLevelUp Real Estate
${fe}
`},Y=async()=>{if(!(!r||!U)){_(!0);try{const{data:ee,error:oe}=await V.from("cma_email_sends").insert({cma_id:n.id,agent_id:r.id,contact_id:(o==null?void 0:o.id)??null,recipient_email:h.trim(),subject:p.trim(),sent_via:A?"gmail":"ses"}).select("id").single();if(oe)throw oe;const me=H(ee.id);if(A){const{data:Q,error:te}=await V.functions.invoke("gmail-send",{body:{to:h.trim(),subject:p.trim(),body:me}});if(te)throw te;if(!(Q!=null&&Q.success))throw new Error((Q==null?void 0:Q.error)||"Gmail send failed")}else if(I){const Q=(R==null?void 0:R.display_name)||(j==null?void 0:j.name)||"ReLevelUp",te=`${Q.toLowerCase().replace(/[^a-z]/g,".").replace(/^\.+|\.+$/g,"")||"noreply"}@send.relevelup.com`,{data:le,error:fe}=await V.functions.invoke("ses-send-campaign",{body:{action:"test_send",to:h.trim(),from_email:`${Q} <${te}>`,subject:p.trim(),body_html:me,reply_to:(R==null?void 0:R.reply_to_email)||(j==null?void 0:j.email)||void 0}});if(fe)throw fe;if(!(le!=null&&le.success))throw new Error((le==null?void 0:le.error)||"SES send failed")}o&&!n.contact_id&&await V.from("cmas").update({contact_id:o.id}).eq("id",n.id),a({title:"CMA sent",description:`Delivered to ${h.trim()}`}),t(!1)}catch(ee){console.error("Send CMA error:",ee),a({title:"Send failed",description:ee.message||"Could not send email",variant:"destructive"})}finally{_(!1)}}};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Vs,{children:e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(pn,{className:"w-5 h-5"}),"Send CMA to contact"]})}),B?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Sending via ",e.jsx("span",{className:"font-semibold text-foreground",children:B})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Contact"}),e.jsxs(Xc,{open:d,onOpenChange:u,children:[e.jsx(Qc,{asChild:!0,children:e.jsxs($,{variant:"outline",role:"combobox",className:"w-full justify-between font-normal",children:[o?`${o.first_name} ${o.last_name||""}`.trim():"Pick a contact (optional)",e.jsx(v_,{className:"w-4 h-4 opacity-50"})]})}),e.jsx(Bc,{className:"w-[--radix-popover-trigger-width] p-0",align:"start",children:e.jsxs(M_,{children:[e.jsx(P_,{placeholder:"Search contacts…"}),e.jsxs(I_,{children:[e.jsx(L_,{children:"No contacts with email found."}),e.jsx(Nb,{children:i.map(ee=>e.jsxs(rv,{value:`${ee.first_name} ${ee.last_name||""} ${ee.email}`,onSelect:()=>G(ee),children:[e.jsx(ma,{className:Ot("w-4 h-4 mr-2",(o==null?void 0:o.id)===ee.id?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"font-medium",children:[ee.first_name," ",ee.last_name||""]}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:ee.email})]})]},ee.id))})]})]})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"To email"}),e.jsx(be,{type:"email",value:h,onChange:ee=>m(ee.target.value),placeholder:"client@example.com"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Subject"}),e.jsx(be,{value:p,onChange:ee=>g(ee.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Message"}),e.jsx(Ls,{rows:10,value:x,onChange:ee=>y(ee.target.value)}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[e.jsx("code",{children:"{{cma_link}}"})," will be replaced with a styled button linking to ",e.jsxs("code",{children:["cma.relevelup.com/",n.share_token]}),". Email opens are tracked and shown on the contact's Signals."]})]}),e.jsxs("div",{className:"rounded border bg-muted/40 p-3 text-sm flex items-center gap-2",children:[e.jsx(Ir,{className:"w-4 h-4 text-muted-foreground"}),e.jsx("span",{className:"text-muted-foreground",children:"Public link:"}),e.jsx("a",{className:"text-primary underline truncate",href:`${sDe}/${n.share_token}`,target:"_blank",rel:"noreferrer",children:`${sDe}/${n.share_token}`})]})]}):e.jsx("div",{className:"p-4 rounded border bg-amber-50 text-amber-900 text-sm",children:"Connect Gmail or set up Amazon SES under Integrations to send CMAs by email."}),e.jsxs(kr,{children:[e.jsx($,{variant:"ghost",onClick:()=>t(!1),children:"Cancel"}),e.jsxs($,{onClick:Y,disabled:!U,children:[v?e.jsx(Jt,{className:"w-4 h-4 mr-2 animate-spin"}):e.jsx(Wr,{className:"w-4 h-4 mr-2"}),"Send CMA"]})]})]})})}function g4n(s){const{user:t}=ks(),n=ls(),{data:r}=pt({queryKey:["lead-site-upgrade-requests",t==null?void 0:t.id],enabled:!!t,queryFn:async()=>{const{data:l,error:o}=await V.from("lead_site_upgrade_requests").select("id, feature_key, status, created_at").eq("user_id",t.id);if(o)throw o;return l}}),a=Nt({mutationFn:async({featureKey:l,notes:o})=>{const{error:c}=await V.from("lead_site_upgrade_requests").insert({user_id:t.id,site_id:s??null,feature_key:l,notes:o??null});if(c)throw c},onSuccess:()=>{n.invalidateQueries({queryKey:["lead-site-upgrade-requests",t==null?void 0:t.id]}),ae.success("Request sent — we'll reach out about upgrading your site.")},onError:l=>ae.error((l==null?void 0:l.message)||"Could not send your request")});return{requestUpgrade:a,hasRequested:l=>!!(r!=null&&r.some(o=>o.feature_key===l&&o.status!=="declined")),isSending:a.isPending}}const x4n="free_luxury",y4n="free_beta";function r9t(s){const t=s==null?void 0:s.planTier;return t===x4n||t===y4n}const v4n={idx_search:{title:"MLS / IDX Home Search",description:"Let visitors search every active MLS listing in your market, with saved searches and instant alerts."},mls_listings:{title:"MLS Listing Feeds",description:"Automatically feature live MLS listings, new listings and sold comps on your homepage and city pages."},cma_reports:{title:"CMA Reports",description:"Build branded comparative market analyses with live MLS comps and share them with sellers."},custom_domain:{title:"Custom Branded Domain",description:"Point your own web address at your site instead of the free subdomain."},ai_content:{title:"AI Content Creation",description:"Auto-written blog posts, city guides and monthly market updates published to your site."}};function b4n({featureKey:s,siteId:t,bullets:n}){const r=v4n[s],{requestUpgrade:a,hasRequested:i,isSending:l}=g4n(t),o=i(s);return e.jsx("section",{className:"rounded-xl border border-amber-500/30 bg-gradient-to-br from-amber-500/10 via-card to-card p-6",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"h-10 w-10 shrink-0 rounded-full bg-amber-500/15 flex items-center justify-center",children:e.jsx(fu,{className:"h-5 w-5 text-amber-500"})}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h2",{className:"text-lg font-semibold text-foreground",children:r.title}),e.jsx("span",{className:"text-[10px] font-bold uppercase tracking-wide px-2 py-0.5 rounded-full bg-amber-100 text-amber-700",children:"Upgrade"})]}),e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:r.description}),n!=null&&n.length?e.jsx("ul",{className:"mt-4 space-y-2",children:n.map(c=>e.jsxs("li",{className:"flex items-start gap-2 text-sm text-muted-foreground",children:[e.jsx(kn,{className:"h-4 w-4 mt-0.5 text-amber-500 shrink-0"}),c]},c))}):null,e.jsx($,{className:"mt-5",disabled:o||l,onClick:()=>a.mutate({featureKey:s}),children:o?e.jsxs(e.Fragment,{children:[e.jsx(ma,{className:"h-4 w-4 mr-2"})," Upgrade requested"]}):"Request this upgrade"})]})]})})}function _4n({onCreated:s}){const[t,n]=k.useState(!1),[r,a]=k.useState(""),[i,l]=k.useState(""),[o,c]=k.useState(""),[d,u]=k.useState(""),h=O5n(),m=X7t(),{toast:p}=Fi(),[g,x]=k.useState([]),y=async()=>{var j;x([]);try{const C=await h.mutateAsync({address:r,city:i,state:o,zip:d});x(C.matches||[]),(j=C.matches)!=null&&j.length||p({title:"No MLS match",description:'Use "Create from manual entry" below.'})}catch(C){p({title:"Search failed",description:C.message,variant:"destructive"})}},v=async j=>{const C=await m.mutateAsync({subject:j});n(!1),s(C.id)},_=async()=>{if(!r||!i||!o){p({title:"Address, city, state required"});return}const j=await m.mutateAsync({subject:{address:r,city:i,state:o,zip:d}});n(!1),s(j.id)};return e.jsxs(zs,{open:t,onOpenChange:n,children:[e.jsx(yl,{asChild:!0,children:e.jsxs($,{children:[e.jsx(nn,{className:"w-4 h-4 mr-2"}),"New CMA"]})}),e.jsxs(Rs,{className:"max-w-2xl",children:[e.jsx(Vs,{children:e.jsx($s,{children:"Start a CMA"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-2",children:[e.jsx(be,{className:"md:col-span-2",placeholder:"Street address",value:r,onChange:j=>a(j.target.value)}),e.jsx(be,{placeholder:"City",value:i,onChange:j=>l(j.target.value)}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(be,{placeholder:"ST",maxLength:2,value:o,onChange:j=>c(j.target.value.toUpperCase())}),e.jsx(be,{placeholder:"ZIP",value:d,onChange:j=>u(j.target.value)})]})]}),e.jsxs($,{onClick:y,disabled:!r||h.isPending,className:"w-full",children:[h.isPending?e.jsx(Jt,{className:"w-4 h-4 mr-2 animate-spin"}):e.jsx(Yr,{className:"w-4 h-4 mr-2"}),"Find in MLS"]}),g.length>0&&e.jsxs("div",{className:"space-y-2 max-h-80 overflow-y-auto",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:[g.length," match(es) — pick the subject property:"]}),g.map((j,C)=>{var A;return e.jsxs("button",{onClick:()=>v(j),className:"w-full text-left p-3 border rounded hover:bg-accent transition",children:[e.jsx("div",{className:"font-medium",children:j.address}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[j.city,", ",j.state," ",j.zip," · ",j.bedrooms??"?"," bd / ",j.bathrooms??"?"," ba · ",((A=j.sqft)==null?void 0:A.toLocaleString())??"?"," sqft",j.mlsNumber?` · MLS# ${j.mlsNumber}`:""," · ",j.source_provider]})]},C)})]}),e.jsx("div",{className:"border-t pt-3",children:e.jsxs($,{variant:"outline",onClick:_,disabled:m.isPending,className:"w-full",children:[e.jsx(ua,{className:"w-4 h-4 mr-2"}),"Create from manual entry"]})})]})]})]})}function w4n(){const{data:s,isLoading:t}=P5n(),n=D5n(),r=Jn(),{toast:a}=Fi(),[i,l]=k.useState(null),{isFreePlan:o,leadSite:c}=Tg();return o?e.jsx(Xs,{children:e.jsxs("div",{className:"container mx-auto p-4 md:p-6 max-w-3xl space-y-6",children:[e.jsxs("h1",{className:"text-2xl md:text-3xl font-bold flex items-center gap-2",children:[e.jsx(ea,{className:"w-7 h-7"})," CMAs"]}),e.jsx(b4n,{featureKey:"cma_reports",siteId:c==null?void 0:c.id,bullets:["Pull live MLS comparables for any subject property","Interactive, shareable CMA presentations for sellers","Track when your seller opens and interacts with the report"]})]})}):e.jsx(Xs,{children:e.jsxs("div",{className:"container mx-auto p-4 md:p-6 max-w-6xl",children:[e.jsxs("div",{className:"flex items-center justify-between mb-6",children:[e.jsxs("div",{children:[e.jsxs("h1",{className:"text-2xl md:text-3xl font-bold flex items-center gap-2",children:[e.jsx(ea,{className:"w-7 h-7"})," CMAs"]}),e.jsx("p",{className:"text-muted-foreground text-sm",children:"Comparative Market Analyses — interactive, shareable, no static PDFs."})]}),e.jsx(_4n,{onCreated:d=>r(`/mission-control/cma/${d}`)})]}),t?e.jsx("p",{className:"text-muted-foreground",children:"Loading…"}):s!=null&&s.length?e.jsx("div",{className:"grid gap-3",children:s.map(d=>{var u,h,m;return e.jsx(we,{className:"hover:shadow-md transition",children:e.jsxs(De,{className:"p-4 flex flex-wrap items-center gap-3 justify-between",children:[e.jsxs("div",{className:"flex-1 min-w-[200px]",children:[e.jsx("div",{className:"font-semibold",children:d.title||((u=d.subject)==null?void 0:u.address)||"Untitled CMA"}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[(h=d.subject)==null?void 0:h.city,", ",(m=d.subject)==null?void 0:m.state," · ",d.buyer_mode?"Buyer":"Seller"," ·"," ",e.jsx(qe,{variant:d.status==="shared"?"default":"secondary",className:"ml-1",children:d.status})]}),d.price_likely?e.jsxs("div",{className:"text-sm mt-1",children:["Suggested: ",e.jsxs("span",{className:"font-medium",children:["$",d.price_likely.toLocaleString()]}),d.price_low&&d.price_high?e.jsxs("span",{className:"text-muted-foreground",children:[" · $",d.price_low.toLocaleString(),"–$",d.price_high.toLocaleString()]}):null]}):null]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{variant:"outline",size:"sm",onClick:()=>r(`/mission-control/cma/${d.id}`),children:"Open"}),d.status==="shared"&&e.jsxs(e.Fragment,{children:[e.jsx($,{variant:"ghost",size:"sm",onClick:()=>{const p=`https://cma.relevelup.com/${d.share_token}`;navigator.clipboard.writeText(p),a({title:"Share link copied"})},children:e.jsx(Ir,{className:"w-4 h-4"})}),e.jsxs($,{variant:"secondary",size:"sm",onClick:()=>l(d),children:[e.jsx(pn,{className:"w-4 h-4 mr-1"}),"Send"]})]}),e.jsx($,{variant:"ghost",size:"sm",onClick:async()=>{await io("Delete this CMA?")&&n.mutate(d.id)},children:e.jsx(Un,{className:"w-4 h-4"})})]})]})},d.id)})}):e.jsx(we,{children:e.jsx(De,{className:"py-12 text-center text-muted-foreground",children:"No CMAs yet. Start one above."})}),i&&e.jsx(n9t,{open:!!i,onOpenChange:d=>!d&&l(null),cma:i})]})})}function j4n(s){return s?/Closed|Sold/i.test(s)?"#16a34a":/Pending|Contingent|Under Contract/i.test(s)?"#f59e0b":/Active/i.test(s)?"#2563eb":"#64748b":"#64748b"}function Yyt(s,t,n){const a=n*1.60934,i=[],l=a/(111.32*Math.cos(s*Math.PI/180)),o=a/110.574;for(let c=0;c<64;c++){const d=c/64*(2*Math.PI);i.push([t+l*Math.cos(d),s+o*Math.sin(d)])}return i.push(i[0]),{type:"Feature",geometry:{type:"Polygon",coordinates:[i]},properties:{}}}function N4n({subject:s,comps:t,radiusMiles:n,onMarkerClick:r}){const a=k.useRef(null),i=k.useRef(null),l=k.useRef([]),[o,c]=k.useState(null);k.useEffect(()=>{let u=!1;return(async()=>{const{data:h}=await V.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle();!u&&(h!=null&&h.value)&&c(h.value)})(),()=>{u=!0}},[]);const d=k.useMemo(()=>{const u=Number(s==null?void 0:s.latitude),h=Number(s==null?void 0:s.longitude);return!Number.isFinite(u)||!Number.isFinite(h)?null:{lat:u,lng:h}},[s==null?void 0:s.latitude,s==null?void 0:s.longitude]);return k.useEffect(()=>{if(!o||!a.current||i.current||!d)return;Td.accessToken=o;const u=new Td.Map({container:a.current,style:"mapbox://styles/mapbox/light-v11",center:[d.lng,d.lat],zoom:12});return u.addControl(new Td.NavigationControl({showCompass:!1}),"top-right"),u.on("load",()=>{u.addSource("radius",{type:"geojson",data:Yyt(d.lat,d.lng,n)}),u.addLayer({id:"radius-fill",type:"fill",source:"radius",paint:{"fill-color":"#2563eb","fill-opacity":.08}}),u.addLayer({id:"radius-line",type:"line",source:"radius",paint:{"line-color":"#2563eb","line-width":2,"line-dasharray":[2,2],"line-opacity":.5}})}),i.current=u,()=>{u.remove(),i.current=null}},[o,d]),k.useEffect(()=>{const u=i.current;if(!u||!d)return;const h=()=>{const m=u.getSource("radius");m&&m.setData(Yyt(d.lat,d.lng,n))};u.isStyleLoaded()?h():u.once("load",h)},[n,d]),k.useEffect(()=>{const u=i.current;if(!u||!d)return;l.current.forEach(y=>y.remove()),l.current=[];const h=document.createElement("div");h.style.cssText=` width: 28px; height: 28px; border-radius: 50%; background: hsl(222 47% 11%); border: 3px solid white; box-shadow: 0 4px 12px rgba(0,0,0,0.3); display: flex; align-items: center; justify-content: center; color: white; font-size: 12px; font-weight: 700; `,h.textContent="★";const m=new Td.Marker({element:h}).setLngLat([d.lng,d.lat]).setPopup(new Td.Popup({offset:18}).setHTML(`Subject
${s.address??""}`)).addTo(u);l.current.push(m);const p=new Td.LngLatBounds;p.extend([d.lng,d.lat]),t.forEach((y,v)=>{const _=Number(y.latitude),j=Number(y.longitude);if(!Number.isFinite(_)||!Number.isFinite(j))return;const C=j4n(y.status),A=document.createElement("div");A.style.cssText="width:22px;height:22px;";const M=document.createElement("div");M.style.cssText=` width: 22px; height: 22px; border-radius: 50%; background: ${C}; border: 2px solid white; box-shadow: 0 2px 6px rgba(0,0,0,0.25); cursor: pointer; opacity: ${y.selected===!1?.4:1}; transition: transform 0.15s; transform-origin: center; `,M.onmouseenter=()=>{M.style.transform="scale(1.25)"},M.onmouseleave=()=>{M.style.transform="scale(1)"},r&&(M.onclick=()=>r(v)),A.appendChild(M);const I=y.soldPrice||y.price,P=new Td.Popup({offset:14}).setHTML(`
${y.address??""}
${y.status??""}`+(I?` · $${I.toLocaleString()}`:"")+"
"),R=new Td.Marker({element:A}).setLngLat([j,_]).setPopup(P).addTo(u);l.current.push(R),p.extend([j,_])});const x=n*1.60934/110.574;p.extend([d.lng,d.lat+x]),p.extend([d.lng,d.lat-x]);try{u.fitBounds(p,{padding:60,maxZoom:14,duration:600})}catch{}},[t,d,n,s.address,r]),d?e.jsxs("div",{className:"relative w-full h-[420px] rounded-xl overflow-hidden border shadow-sm",children:[e.jsx("div",{ref:a,className:"absolute inset-0"}),!o&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-muted/40 text-sm text-muted-foreground",children:"Loading map…"}),e.jsxs("div",{className:"absolute bottom-3 left-3 bg-background/95 backdrop-blur rounded-lg shadow-md border px-3 py-2 text-xs space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"inline-block w-3 h-3 rounded-full",style:{background:"hsl(222 47% 11%)"}}),"Subject"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"inline-block w-3 h-3 rounded-full",style:{background:"#2563eb"}}),"Active"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"inline-block w-3 h-3 rounded-full",style:{background:"#f59e0b"}}),"Pending"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"inline-block w-3 h-3 rounded-full",style:{background:"#16a34a"}}),"Closed"]})]})]}):e.jsx("div",{className:"w-full h-[420px] rounded-xl border bg-muted/30 flex items-center justify-center text-sm text-muted-foreground",children:"Subject property has no coordinates — map unavailable."})}let Wb=null;function k4n(){if(Wb)return Wb;try{const s=document.createElement("canvas"),t=s.getContext("webgl2")||s.getContext("webgl");if(!t)return Wb={canRunVirtualBg:!1,reason:"WebGL is not supported on this device"},Wb;const n=t.getExtension("WEBGL_debug_renderer_info"),r=n?t.getParameter(n.UNMASKED_RENDERER_WEBGL):"Unknown",a=["swiftshader","llvmpipe","software","microsoft basic render"],i=(r||"").toLowerCase();if(a.some(c=>i.includes(c)))return Wb={canRunVirtualBg:!1,reason:"Your device uses a software renderer which may cause lag",renderer:r},Wb;const o=performance;return o.memory&&o.memory.jsHeapSizeLimit<256*1024*1024?(Wb={canRunVirtualBg:!1,reason:"Limited device memory detected",renderer:r},Wb):navigator.hardwareConcurrency&&navigator.hardwareConcurrency<2?(Wb={canRunVirtualBg:!1,reason:"Single-core device detected — virtual backgrounds may cause lag",renderer:r},Wb):(Wb={canRunVirtualBg:!0,renderer:r},Wb)}catch{return Wb={canRunVirtualBg:!0},Wb}}const S4n=[{type:"none",label:"Off"},{type:"blur",label:"Blur"}];function C4n({value:s,onChange:t,isLoading:n=!1,disabled:r=!1,className:a}){const i=k.useRef(null),[l,o]=k.useState(!1),[c]=k.useState(()=>k4n()),d=!c.canRunVirtualBg,{data:u=[],refetch:h}=pt({queryKey:["video-backgrounds"],queryFn:async()=>{const{data:{user:y}}=await V.auth.getUser();if(!y)return[];const{data:v,error:_}=await V.from("video_backgrounds").select("*").eq("is_active",!0).order("sort_order",{ascending:!0});return _?(console.error("Failed to load backgrounds:",_),[]):v||[]}}),m=u.map(y=>({type:"image",label:y.name,imageUrl:y.image_url,thumbnail:y.thumbnail_url||y.image_url})),p=[...S4n,...m],g=y=>y.type!==s.type?!1:y.type==="image"?y.imageUrl===s.imageUrl:!0,x=async y=>{var _;const v=(_=y.target.files)==null?void 0:_[0];if(v){if(!v.type.startsWith("image/")){ae.error("Please select an image file");return}if(v.size>5*1024*1024){ae.error("Image must be under 5MB");return}o(!0);try{const{data:{user:j}}=await V.auth.getUser();if(!j)throw new Error("Not authenticated");const C=v.name.split(".").pop()||"jpg",A=`${j.id}/${crypto.randomUUID()}.${C}`,{error:M}=await V.storage.from("video-backgrounds").upload(A,v,{contentType:v.type});if(M)throw M;const{data:I}=V.storage.from("video-backgrounds").getPublicUrl(A),P=I.publicUrl,{error:R}=await V.from("video_backgrounds").insert({name:v.name.replace(/\.[^.]+$/,""),image_url:P,thumbnail_url:P,category:"custom",is_stock:!1,user_id:j.id});if(R)throw R;await h(),t({type:"image",imageUrl:P,blurRadius:15}),ae.success("Background uploaded!")}catch(j){console.error("Upload error:",j),ae.error("Failed to upload background")}finally{o(!1),i.current&&(i.current.value="")}}};return e.jsxs("div",{className:Ot("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(Gd,{className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{children:c.reason||"Virtual backgrounds may cause lag on this device"})]}),e.jsxs("div",{className:"flex items-center gap-2 overflow-x-auto py-2 px-1 scrollbar-none",children:[e.jsx("span",{className:"text-xs text-muted-foreground whitespace-nowrap mr-1 font-medium",children:"Background:"}),n&&e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(Jt,{className:"h-3 w-3 animate-spin"}),e.jsx("span",{children:"Loading…"})]}),p.map((y,v)=>{const _=g(y);return e.jsxs("button",{type:"button",disabled:r,onClick:()=>t({type:y.type,imageUrl:y.imageUrl,blurRadius:15}),className:Ot("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",_?"border-primary bg-primary/10":"border-transparent bg-muted/50",r&&"opacity-50 cursor-not-allowed"),children:[e.jsxs("div",{className:"w-12 h-8 rounded flex items-center justify-center overflow-hidden bg-muted",children:[y.type==="none"&&e.jsx(Fz,{className:"h-4 w-4 text-muted-foreground"}),y.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"})}),y.type==="image"&&y.thumbnail&&e.jsx("img",{src:y.thumbnail,alt:y.label,className:"w-full h-full object-cover"})]}),e.jsx("span",{className:"text-[10px] text-muted-foreground truncate max-w-14",children:y.label})]},`${y.type}-${y.imageUrl||v}`)}),e.jsxs("button",{type:"button",disabled:r||l,onClick:()=>{var y;return(y=i.current)==null?void 0:y.click()},className:Ot("flex-shrink-0 flex flex-col items-center gap-0.5 rounded-lg border-2 border-dashed p-1 transition-all","hover:border-primary/50 focus:outline-none focus:ring-2 focus:ring-primary/30","border-muted-foreground/30 bg-muted/30",(r||l)&&"opacity-50 cursor-not-allowed"),children:[e.jsx("div",{className:"w-12 h-8 rounded flex items-center justify-center",children:l?e.jsx(Jt,{className:"h-4 w-4 animate-spin text-muted-foreground"}):e.jsx(nn,{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:x}),e.jsxs("button",{type:"button",disabled:r,onClick:()=>t({...s,mirror:!s.mirror}),className:Ot("flex-shrink-0 flex flex-col items-center gap-0.5 rounded-lg border-2 p-1 transition-all ml-1","hover:border-primary/50 focus:outline-none focus:ring-2 focus:ring-primary/30",s.mirror?"border-primary bg-primary/10":"border-transparent bg-muted/50",r&&"opacity-50 cursor-not-allowed"),children:[e.jsx("div",{className:"w-12 h-8 rounded flex items-center justify-center",children:e.jsx(MK,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx("span",{className:"text-[10px] text-muted-foreground",children:"Mirror"})]})]})]})}var oq=typeof self<"u"?self:{};function a9t(s,t){e:{for(var n=["CLOSURE_FLAGS"],r=oq,a=0;a>6|192;else{if(t>=55296&&t<=57343){if(t<=56319&&a=56320&&i<=57343){t=1024*(t-55296)+i-56320+65536,r[n++]=t>>18|240,r[n++]=t>>12&63|128,r[n++]=t>>6&63|128,r[n++]=63&t|128;continue}a--}t=65533}r[n++]=t>>12|224,r[n++]=t>>6&63|128}r[n++]=63&t|128}}s=n===r.length?r:r.subarray(0,n)}return s}function o9t(s){oq.setTimeout(()=>{throw s},0)}var ZBe,M4n=a9t(610401301,!1),Xyt=a9t(748402147,!0);function Qyt(){var s=oq.navigator;return s&&(s=s.userAgent)?s:""}const Jyt=oq.navigator;function lTe(s){return lTe[" "](s),s}ZBe=Jyt&&Jyt.userAgentData||null,lTe[" "]=function(){};const l9t={};let OW=null;function P4n(s){const t=s.length;let n=3*t/4;n%3?n=Math.floor(n):"=.".indexOf(s[t-1])!=-1&&(n="=.".indexOf(s[t-2])!=-1?n-2:n-1);const r=new Uint8Array(n);let a=0;return function(i,l){function o(d){for(;c>4),h!=64&&(l(u<<4&240|h>>2),m!=64&&l(h<<6&192|m))}}(s,function(i){r[a++]=i}),a!==n?r.subarray(0,a):r}function c9t(){if(!OW){OW={};var s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".split(""),t=["+/=","+/","-_=","-_.","-_"];for(let n=0;n<5;n++){const r=s.concat(t[n].split(""));l9t[n]=r;for(let a=0;a0)&&(Qyt().indexOf("Trident")!=-1||Qyt().indexOf("MSIE")!=-1))&&typeof btoa=="function";const e0t=/[-_.]/g,L4n={"-":"+",_:"/",".":"="};function R4n(s){return L4n[s]||""}function u9t(s){if(!d9t)return P4n(s);s=e0t.test(s)?s.replace(e0t,R4n):s,s=atob(s);const t=new Uint8Array(s.length);for(let n=0;n=t||(n[s]=r+1,m9t(s=Error(),"incident"),o9t(s))}}function TV(){return typeof BigInt=="function"}var MV=typeof Symbol=="function"&&typeof Symbol()=="symbol";function l4(s,t,n=!1){return typeof Symbol=="function"&&typeof Symbol()=="symbol"?n&&Symbol.for&&s?Symbol.for(s):s!=null?Symbol(s):Symbol():t}var F4n=l4("jas",void 0,!0),t0t=l4(void 0,"0di"),DG=l4(void 0,"1oa"),rj=l4(void 0,Symbol()),z4n=l4(void 0,"0ub"),B4n=l4(void 0,"0ubs"),QBe=l4(void 0,"0ubsb"),$4n=l4(void 0,"0actk"),dq=l4("m_m","Pa",!0),s0t=l4();const f9t={Ga:{value:0,configurable:!0,writable:!0,enumerable:!1}},p9t=Object.defineProperties,Xo=MV?F4n:"Ga";var $F;const n0t=[];function ate(s,t){MV||Xo in s||p9t(s,f9t),s[Xo]|=t}function Py(s,t){MV||Xo in s||p9t(s,f9t),s[Xo]=t}function ite(s){return ate(s,34),s}function oQ(s){return ate(s,8192),s}Py(n0t,7),$F=Object.freeze(n0t);var uq={};function cj(s,t){return t===void 0?s.h!==JO&&!!(2&(0|s.v[Xo])):!!(2&t)&&s.h!==JO}const JO={};function HZe(s,t){if(s!=null){if(typeof s=="string")s=s?new $5(s,lq):QO();else if(s.constructor!==$5)if(qZe(s))s=s.length?new $5(new Uint8Array(s),lq):QO();else{if(!t)throw Error();s=void 0}}return s}let r0t=class{constructor(t,n,r){this.g=t,this.h=n,this.l=r}next(){const t=this.g.next();return t.done||(t.value=this.h.call(this.l,t.value)),t}[Symbol.iterator](){return this}};var U4n=Object.freeze({});function g9t(s,t,n){const r=128&t?0:-1,a=s.length;var i;(i=!!a)&&(i=(i=s[a-1])!=null&&typeof i=="object"&&i.constructor===Object);const l=a+(i?-1:0);for(t=128&t?1:0;ttypeof s=="number"),a0t=cTe(s=>typeof s=="string"),V4n=cTe(s=>typeof s=="boolean"),dTe=typeof oq.BigInt=="function"&&typeof oq.BigInt(0)=="bigint";function aj(s){var t=s;if(a0t(t)){if(!/^\s*(?:-?[1-9]\d*|0)?\s*$/.test(t))throw Error(String(t))}else if(q4n(t)&&!Number.isSafeInteger(t))throw Error(String(t));return dTe?BigInt(s):s=V4n(s)?s?"1":"0":a0t(s)?s.trim()||"0":String(s)}var JBe=cTe(s=>dTe?s>=G4n&&s<=K4n:s[0]==="-"?i0t(s,H4n):i0t(s,W4n));const H4n=Number.MIN_SAFE_INTEGER.toString(),G4n=dTe?BigInt(Number.MIN_SAFE_INTEGER):void 0,W4n=Number.MAX_SAFE_INTEGER.toString(),K4n=dTe?BigInt(Number.MAX_SAFE_INTEGER):void 0;function i0t(s,t){if(s.length>t.length)return!1;if(s.lengtha)return!1;if(r>>0;Ap=t,Mx=(s-t)/4294967296>>>0}function hq(s){if(s<0){o0t(-s);const[t,n]=KZe(Ap,Mx);Ap=t>>>0,Mx=n>>>0}else o0t(s)}function GZe(s){const t=Z4n||(Z4n=new DataView(new ArrayBuffer(8)));t.setFloat32(0,+s,!0),Mx=0,Ap=t.getUint32(0,!0)}function y9t(s,t){const n=4294967296*t+(s>>>0);return Number.isSafeInteger(n)?n:lQ(s,t)}function X4n(s,t){return aj(TV()?BigInt.asUintN(64,(BigInt(t>>>0)<>>0)):lQ(s,t))}function v9t(s,t){return TV()?aj(BigInt.asIntN(64,(BigInt.asUintN(32,BigInt(t))<>>=0,(t>>>=0)<=2097151)var n=""+(4294967296*t+s);else TV()?n=""+(BigInt(t)<>>24|t<<8))+6710656*(t=t>>16&65535),n+=8147497*t,t*=2,s>=1e7&&(n+=s/1e7>>>0,s%=1e7),n>=1e7&&(t+=n/1e7>>>0,n%=1e7),n=t+l0t(n)+l0t(s));return n}function l0t(s){return s=String(s),"0000000".slice(s.length)+s}function WZe(s,t){if(2147483648&t)if(TV())s=""+(BigInt(0|t)<>>0));else{const[n,r]=KZe(s,t);s="-"+lQ(n,r)}else s=lQ(s,t);return s}function uTe(s){if(s.length<16)hq(Number(s));else if(TV())s=BigInt(s),Ap=Number(s&BigInt(4294967295))>>>0,Mx=Number(s>>BigInt(32)&BigInt(4294967295));else{const t=+(s[0]==="-");Mx=Ap=0;const n=s.length;for(let r=t,a=(n-t)%6+t;a<=n;r=a,a+=6){const i=Number(s.slice(r,a));Mx*=1e6,Ap=1e6*Ap+i,Ap>=4294967296&&(Mx+=Math.trunc(Ap/4294967296),Mx>>>=0,Ap>>>=0)}if(t){const[r,a]=KZe(Ap,Mx);Ap=r,Mx=a}}}function KZe(s,t){return t=~t,s?s=1+~s:t+=1,[s,t]}function fk(s){return Array.prototype.slice.call(s)}const ote=typeof BigInt=="function"?BigInt.asIntN:void 0,Q4n=typeof BigInt=="function"?BigInt.asUintN:void 0,eF=Number.isSafeInteger,hTe=Number.isFinite,mq=Math.trunc,J4n=aj(0);function FW(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 x5(s){return s==null||typeof s=="number"?s:s==="NaN"||s==="Infinity"||s==="-Infinity"?Number(s):void 0}function cQ(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 b9t(s){return s==null||typeof s=="boolean"?s:typeof s=="number"?!!s:void 0}const eCn=/^-?([1-9][0-9]*|0)(\.[0-9]+)?$/;function lte(s){switch(typeof s){case"bigint":return!0;case"number":return hTe(s);case"string":return eCn.test(s);default:return!1}}function IV(s){if(s==null)return s;if(typeof s=="string"&&s)s=+s;else if(typeof s!="number")return;return hTe(s)?0|s:void 0}function _9t(s){if(s==null)return s;if(typeof s=="string"&&s)s=+s;else if(typeof s!="number")return;return hTe(s)?s>>>0:void 0}function w9t(s){const t=s.length;return(s[0]==="-"?t<20||t===20&&s<="-9223372036854775808":t<19||t===19&&s<="9223372036854775807")?s:(uTe(s),WZe(Ap,Mx))}function YZe(s){if(s=mq(s),!eF(s)){hq(s);var t=Ap,n=Mx;(s=2147483648&n)&&(n=~n>>>0,(t=1+~t>>>0)==0&&(n=n+1>>>0)),s=typeof(t=y9t(t,n))=="number"?s?-t:t:s?"-"+t:t}return s}function j9t(s){var t=mq(Number(s));return eF(t)?String(t):((t=s.indexOf("."))!==-1&&(s=s.substring(0,t)),w9t(s))}function N9t(s){var t=mq(Number(s));return eF(t)?aj(t):((t=s.indexOf("."))!==-1&&(s=s.substring(0,t)),TV()?aj(ote(64,BigInt(s))):aj(w9t(s)))}function k9t(s){return eF(s)?s=aj(YZe(s)):(s=mq(s),eF(s)?s=String(s):(hq(s),s=WZe(Ap,Mx)),s=aj(s)),s}function P4e(s){const t=typeof s;return s==null?s:t==="bigint"?aj(ote(64,s)):lte(s)?t==="string"?N9t(s):k9t(s):void 0}function S9t(s){if(typeof s!="string")throw Error();return s}function cte(s){if(s!=null&&typeof s!="string")throw Error();return s}function mv(s){return s==null||typeof s=="string"?s:void 0}function ZZe(s,t,n,r){return s!=null&&s[dq]===uq?s:Array.isArray(s)?((r=(n=0|s[Xo])|32&r|2&r)!==n&&Py(s,r),new t(s)):(n?2&r?((s=t[t0t])||(ite((s=new t).v),s=t[t0t]=s),t=s):t=new t:t=void 0,t)}function tCn(s,t,n){if(t)e:{if(!lte(t=s))throw XBe("int64");switch(typeof t){case"string":t=N9t(t);break e;case"bigint":t=aj(ote(64,t));break e;default:t=k9t(t)}}else t=P4e(s);return(s=t)==null?n?J4n:void 0:s}const sCn={};let nCn=function(){try{return lTe(new class extends Map{constructor(){super()}}),!1}catch{return!0}}(),rDe=class{constructor(){this.g=new Map}get(t){return this.g.get(t)}set(t,n){return this.g.set(t,n),this.size=this.g.size,this}delete(t){return t=this.g.delete(t),this.size=this.g.size,t}clear(){this.g.clear(),this.size=this.g.size}has(t){return this.g.has(t)}entries(){return this.g.entries()}keys(){return this.g.keys()}values(){return this.g.values()}forEach(t,n){return this.g.forEach(t,n)}[Symbol.iterator](){return this.entries()}};const rCn=nCn?(Object.setPrototypeOf(rDe.prototype,Map.prototype),Object.defineProperties(rDe.prototype,{size:{value:0,configurable:!0,enumerable:!0,writable:!0}}),rDe):class extends Map{constructor(){super()}};function c0t(s){return s}function aDe(s){if(2&s.J)throw Error("Cannot mutate an immutable Map")}var W3=class extends rCn{constructor(s,t,n=c0t,r=c0t){super(),this.J=0|s[Xo],this.K=t,this.S=n,this.fa=this.K?aCn:r;for(let a=0;a{s.call(t,a.get(r),r,a)}):super.forEach(s,t)}set(s,t){return aDe(this),(s=this.S(s,!0,!1))==null?this:t==null?(super.delete(s),this):super.set(s,this.fa(t,!0,!0,this.K,!1,this.J))}Ma(s){const t=this.S(s[0],!1,!0);s=s[1],s=this.K?s===void 0?null:s:this.fa(s,!1,!0,void 0,!1,this.J),super.set(t,s)}has(s){return super.has(this.S(s,!1,!1))}get(s){s=this.S(s,!1,!1);const t=super.get(s);if(t!==void 0){var n=this.K;return n?((n=this.fa(t,!1,!0,n,this.ra,this.J))!==t&&super.set(s,n),n):t}}[Symbol.iterator](){return this.entries()}};function aCn(s,t,n,r,a,i){return s=ZZe(s,r,n,i),a&&(s=QZe(s)),s}function iCn(s){return[s,this.get(s)]}let oCn;function d0t(){return oCn||(oCn=new W3(ite([]),void 0,void 0,void 0,sCn))}function mTe(s){return rj?s[rj]:void 0}function I4e(s,t){for(const n in s)!isNaN(n)&&t(s,+n,s[n])}W3.prototype.toJSON=void 0;var e$e=class{};const lCn={Ka:!0};function cCn(s,t){t<100||cq(B4n,1)}function fTe(s,t,n,r){const a=r!==void 0;r=!!r;var i,l=rj;!a&&MV&&l&&(i=s[l])&&I4e(i,cCn),l=[];var o=s.length;let c;i=4294967295;let d=!1;const u=!!(64&t),h=u?128&t?0:-1:void 0;1&t||(c=o&&s[o-1],c!=null&&typeof c=="object"&&c.constructor===Object?i=--o:c=void 0,!u||128&t||a||(d=!0,i=i-h+h)),t=void 0;for(var m=0;m=i){const g=m-h;(t??(t={}))[g]=p}else l[m]=p}if(c)for(let p in c){if((o=c[p])==null||(o=n(o,r))==null)continue;let g;m=+p,u&&!Number.isNaN(m)&&(g=m+h){g[y]=fk(v)}),g.da=p.da,g}(s)),l}function dCn(s){return s[0]=dQ(s[0]),s[1]=dQ(s[1]),s}function dQ(s){switch(typeof s){case"number":return Number.isFinite(s)?s:""+s;case"bigint":return JBe(s)?Number(s):""+s;case"boolean":return s?1:0;case"object":if(Array.isArray(s)){var t=0|s[Xo];return s.length===0&&1&t?void 0:fTe(s,t,dQ)}if(s!=null&&s[dq]===uq)return C9t(s);if(s instanceof $5){if((t=s.g)==null)s="";else if(typeof t=="string")s=t;else{if(d9t){for(var n="",r=0,a=t.length-10240;r>2];i=n[(3&i)<<4|l>>4],l=n[(15&l)<<2|o>>6],o=n[63&o],r[u++]=c+i+l+o}switch(c=0,o=a,t.length-d){case 2:o=n[(15&(c=t[d+1]))<<2]||a;case 1:t=t[d],r[u]=n[t>>2]+n[(3&t)<<4|c>>4]+o+a}t=r.join("")}s=s.g=t}return s}return s instanceof W3?s=s.size!==0?s.V(dCn):void 0:void 0}return s}let uCn,hCn;function C9t(s){return fTe(s=s.v,0|s[Xo],dQ)}function mO(s,t){return A9t(s,t[0],t[1])}function A9t(s,t,n,r=0){if(s==null){var a=32;n?(s=[n],a|=128):s=[],t&&(a=-16760833&a|(1023&t)<<14)}else{if(!Array.isArray(s))throw Error("narr");if(a=0|s[Xo],Xyt&&1&a)throw Error("rfarr");if(2048&a&&!(2&a)&&function(){if(Xyt)throw Error("carr");cq($4n,5)}(),256&a)throw Error("farr");if(64&a)return(a|r)!==a&&Py(s,a|r),s;if(n&&(a|=128,n!==s[0]))throw Error("mid");e:{a|=64;var i=(n=s).length;if(i){var l=i-1;const c=n[l];if(c!=null&&typeof c=="object"&&c.constructor===Object){if((l-=t=128&a?0:-1)>=1024)throw Error("pvtlmt");for(var o in c)(i=+o)1024)throw Error("spvt");a=-16760833&a|(1023&o)<<14}}}return Py(s,64|a|r),s}function mCn(s,t){if(typeof s!="object")return s;if(Array.isArray(s)){var n=0|s[Xo];return s.length===0&&1&n?void 0:u0t(s,n,t)}if(s!=null&&s[dq]===uq)return h0t(s);if(s instanceof W3){if(2&(t=s.J))return s;if(!s.size)return;if(n=ite(s.V()),s.K)for(s=0;s=i)if(l=s[i],l!=null&&typeof l=="object"&&l.constructor===Object)n=l[t],o=!0;else{if(a!==i)return;n=l}else n=s[a];if(r&&n!=null){if((r=r(n))==null)return r;if(!Object.is(r,n))return o?l[t]=r:s[a]=r,r}return n}}function Jh(s,t,n,r){DV(s),Ey(s=s.v,0|s[Xo],t,n,r)}function Ey(s,t,n,r,a){const i=n+(a?0:-1);var l=s.length-1;if(l>=1+(a?0:-1)&&i>=l){const o=s[l];if(o!=null&&typeof o=="object"&&o.constructor===Object)return o[n]=r,t}return i<=l?(s[i]=r,t):(r!==void 0&&(n>=(l=(t??(t=0|s[Xo]))>>14&1023||536870912)?r!=null&&(s[l+(a?0:-1)]={[n]:r}):s[i]=r),t)}function yD(){return U4n===void 0?2:4}function vD(s,t,n,r,a){let i=s.v,l=0|i[Xo];r=cj(s,l)?1:r,a=!!a||r===3,r===2&&RV(s)&&(i=s.v,l=0|i[Xo]);let o=(s=eXe(i,t))===$F?7:0|s[Xo],c=tXe(o,l);var d=!(4&c);if(d){4&c&&(s=fk(s),o=0,c=pO(c,l),l=Ey(i,l,t,s));let u=0,h=0;for(;u{const o=ZZe(l,n,!1,t);return i=o!==l&&o!=null,o}))!=null)return i&&!cj(r)&&UF(s,t),r}function Uu(s,t,n,r){let a=s.v,i=0|a[Xo];if((t=L9t(a,i,t,n,r))==null)return t;if(i=0|a[Xo],!cj(s,i)){const l=QZe(t);l!==t&&(RV(s)&&(a=s.v,i=0|a[Xo]),i=Ey(a,i,n,t=l,r),UF(a,i))}return t}function R9t(s,t,n,r,a,i,l,o){var c=cj(s,n);i=c?1:i,l=!!l||i===3,c=o&&!c,(i===2||c)&&RV(s)&&(n=0|(t=s.v)[Xo]);var d=(s=eXe(t,a))===$F?7:0|s[Xo],u=tXe(d,n);if(o=!(4&u)){var h=s,m=n;const p=!!(2&u);p&&(m|=2);let g=!p,x=!0,y=0,v=0;for(;y32)for(a|=(127&n)>>4,i=3;i<32&&128&n;i+=7)n=l[o++],a|=(127&n)<>>0,a>>>0);throw Error()}function lXe(s){let t=0,n=s.g;const r=n+10,a=s.h;for(;n>>0}function R4e(s){var t=s.h;const n=s.g;var r=t[n],a=t[n+1];const i=t[n+2];return t=t[n+3],gO(s,s.g+4),s=2*((a=(r<<0|a<<8|i<<16|t<<24)>>>0)>>31)+1,r=a>>>23&255,a&=8388607,r==255?a?NaN:s*(1/0):r==0?1401298464324817e-60*s*a:s*Math.pow(2,r-150)*(a+8388608)}function fCn(s){return IM(s)}function gO(s,t){if(s.g=t,t>s.l)throw Error()}function O9t(s,t){if(t<0)throw Error();const n=s.g;if((t=n+t)>s.l)throw Error();return s.g=t,n}function F9t(s,t){if(t==0)return QO();var n=O9t(s,t);return s.Y&&s.j?n=s.h.subarray(n,n+t):(s=s.h,n=n===(t=n+t)?new Uint8Array(0):Y4n?s.slice(n,t):new Uint8Array(s.subarray(n,t))),n.length==0?QO():new $5(n,lq)}var m0t=[];function z9t(s,t,n,r){if(D4e.length){const a=D4e.pop();return a.o(r),a.g.init(s,t,n,r),a}return new pCn(s,t,n,r)}function B9t(s){s.g.clear(),s.l=-1,s.h=-1,D4e.length<100&&D4e.push(s)}function $9t(s){var t=s.g;if(t.g==t.l)return!1;s.m=s.g.g;var n=Z5(s.g);if(t=n>>>3,!((n&=7)>=0&&n<=5)||t<1)throw Error();return s.l=t,s.h=n,!0}function CNe(s){switch(s.h){case 0:s.h!=0?CNe(s):lXe(s.g);break;case 1:gO(s=s.g,s.g+8);break;case 2:if(s.h!=2)CNe(s);else{var t=Z5(s.g);gO(s=s.g,s.g+t)}break;case 5:gO(s=s.g,s.g+4);break;case 3:for(t=s.l;;){if(!$9t(s))throw Error();if(s.h==4){if(s.l!=t)throw Error();break}CNe(s)}break;default:throw Error()}}function dte(s,t,n){const r=s.g.l;var a=Z5(s.g);let i=(a=s.g.g+a)-r;if(i<=0&&(s.g.l=a,n(t,s,void 0,void 0,void 0),i=a-s.g.g),i)throw Error();return s.g.g=a,s.g.l=r,t}function cXe(s){var t=Z5(s.g),n=O9t(s=s.g,t);if(s=s.h,A4n){var r,a=s;(r=nDe)||(r=nDe=new TextDecoder("utf-8",{fatal:!0})),t=n+t,a=n===0&&t===a.length?a:a.subarray(n,t);try{var i=r.decode(a)}catch(o){if(Sae===void 0){try{r.decode(new Uint8Array([128]))}catch{}try{r.decode(new Uint8Array([97])),Sae=!0}catch{Sae=!1}}throw!Sae&&(nDe=void 0),o}}else{t=(i=n)+t,n=[];let o,c=null;for(;i=t?hP():(o=s[i++],l<194||(192&o)!=128?(i--,hP()):n.push((31&l)<<6|63&o)):l<240?i>=t-1?hP():(o=s[i++],(192&o)!=128||l===224&&o<160||l===237&&o>=160||(192&(r=s[i++]))!=128?(i--,hP()):n.push((15&l)<<12|(63&o)<<6|63&r)):l<=244?i>=t-2?hP():(o=s[i++],(192&o)!=128||o-144+(l<<28)>>30||(192&(r=s[i++]))!=128||(192&(a=s[i++]))!=128?(i--,hP()):(l=(7&l)<<18|(63&o)<<12|(63&r)<<6|63&a,l-=65536,n.push(55296+(l>>10&1023),56320+(1023&l)))):hP(),n.length>=8192&&(c=Zyt(c,n),n.length=0)}i=Zyt(c,n)}return i}function U9t(s){const t=Z5(s.g);return F9t(s.g,t)}function gTe(s,t,n){var r=Z5(s.g);for(r=s.g.g+r;s.g.g>>0,this.g=t>>>0}};let gCn;function p0t(s){return s?/^-?\d+$/.test(s)?(uTe(s),new s$e(Ap,Mx)):null:xCn||(xCn=new s$e(0,0))}var s$e=class{constructor(s,t){this.h=s>>>0,this.g=t>>>0}};let xCn;function LB(s,t,n){for(;n>0||t>127;)s.g.push(127&t|128),t=(t>>>7|n<<25)>>>0,n>>>=7;s.g.push(t)}function FV(s,t){for(;t>127;)s.g.push(127&t|128),t>>>=7;s.g.push(t)}function xTe(s,t){if(t>=0)FV(s,t);else{for(let n=0;n<9;n++)s.g.push(127&t|128),t>>=7;s.g.push(1)}}function dXe(s){var t=Ap;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 fq(s,t){t.length!==0&&(s.l.push(t),s.h+=t.length)}function K2(s,t,n){FV(s.g,8*t+n)}function uXe(s,t){return K2(s,t,2),t=s.g.end(),fq(s,t),t.push(s.h),t}function hXe(s,t){var n=t.pop();for(n=s.h+s.g.length()-n;n>127;)t.push(127&n|128),n>>>=7,s.h++;t.push(n),s.h++}function yTe(s,t,n){K2(s,t,2),FV(s.g,n.length),fq(s,s.g.end()),fq(s,n)}function O4e(s,t,n,r){n!=null&&(t=uXe(s,t),r(n,s),hXe(s,t))}function c4(){const s=class{constructor(){throw Error()}};return Object.setPrototypeOf(s,s.prototype),s}var mXe=c4(),q9t=c4(),fXe=c4(),pXe=c4(),gXe=c4(),V9t=c4(),yCn=c4(),vTe=c4(),H9t=c4(),G9t=c4();function d4(s,t,n){var r=s.v;rj&&rj in r&&(r=r[rj])&&delete r[t.g],t.h?t.j(s,t.h,t.g,n,t.l):t.j(s,t.g,n,t.l)}var Qo=class{constructor(s,t){this.v=A9t(s,t,void 0,2048)}toJSON(){return C9t(this)}j(){var a;var s=JCn,t=this.v,n=s.g,r=rj;if(MV&&r&&((a=t[r])==null?void 0:a[n])!=null&&cq(z4n,3),t=s.g,s0t&&rj&&s0t===void 0&&(r=(n=this.v)[rj])&&(r=r.da))try{r(n,t,lCn)}catch(i){o9t(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[Xo];return JZe(this,s,t)?XZe(this,s,!0):new this.constructor(LV(s,t,!1))}};Qo.prototype[dq]=uq,Qo.prototype.toString=function(){return this.v.toString()};var zV=class{constructor(s,t,n){this.g=s,this.h=t,s=mXe,this.l=!!s&&n===s||!1}};function bTe(s,t){return new zV(s,t,mXe)}function W9t(s,t,n,r,a){O4e(s,n,X9t(t,r),a)}const vCn=bTe(function(s,t,n,r,a){return s.h===2&&(dte(s,rXe(t,r,n),a),!0)},W9t),bCn=bTe(function(s,t,n,r,a){return s.h===2&&(dte(s,rXe(t,r,n),a),!0)},W9t);var _Te=Symbol(),wTe=Symbol(),n$e=Symbol(),g0t=Symbol(),x0t=Symbol();let K9t,Y9t;function qF(s,t,n,r){var a=r[s];if(a)return a;(a={}).qa=r,a.T=function(h){switch(typeof h){case"boolean":return uCn||(uCn=[0,void 0,!0]);case"number":return h>0?void 0:h===0?hCn||(hCn=[0,void 0]):[-h,void 0];case"string":return[0,h];case"object":return h}}(r[0]);var i=r[1];let l=1;i&&i.constructor===Object&&(a.ba=i,typeof(i=r[++l])=="function"&&(a.ma=!0,K9t??(K9t=i),Y9t??(Y9t=r[l+1]),i=r[l+=2]));const o={};for(;i&&Array.isArray(i)&&i.length&&typeof i[0]=="number"&&i[0]>0;){for(var c=0;ca(i,l,o,r):a}function yXe(s,t,n,r,a){const i=n.g;let l,o;s[t]=(c,d,u)=>i(c,d,u,o||(o=qF(wTe,xXe,yXe,r).T),l||(l=vXe(r)),a)}function vXe(s){let t=s[n$e];if(t!=null)return t;const n=qF(wTe,xXe,yXe,s);return t=n.ma?(r,a)=>K9t(r,a,n):(r,a)=>{for(;$9t(a)&&a.h!=4;){var i=a.l,l=n[i];if(l==null){var o=n.ba;o&&(o=o[i])&&(o=wCn(o))!=null&&(l=n[i]=o)}if(l==null||!l(a,r,i)){if(l=(o=a).m,CNe(o),o.ha)var c=void 0;else c=o.g.g-l,o.g.g=l,c=F9t(o.g,c);l=void 0,o=r,c&&((l=o[rj]??(o[rj]=new e$e))[i]??(l[i]=[])).push(c)}}return(r=mTe(r))&&(r.da=n.qa[x0t]),!0},s[n$e]=t,s[x0t]=_Cn.bind(s),t}function _Cn(s,t,n,r){var a=this[wTe];const i=this[n$e],l=mO(void 0,a.T),o=mTe(s);if(o){var c=!1,d=a.ba;if(d){if(a=(u,h,m)=>{if(m.length!==0)if(d[h])for(const p of m){u=z9t(p);try{c=!0,i(l,u)}finally{B9t(u)}}else r==null||r(s,h,m)},t==null)I4e(o,a);else if(o!=null){const u=o[t];u&&a(o,t,u)}if(c){let u=0|s[Xo];if(2&u&&2048&u&&!(n!=null&&n.Ka))throw Error();const h=PV(u),m=(p,g)=>{if(K3(s,p,h)!=null){if((n==null?void 0:n.Qa)===1)return;throw Error()}g!=null&&(u=Ey(s,u,p,g,h)),delete o[p]};t==null?g9t(l,0|l[Xo],(p,g)=>{m(p,g)}):m(t,K3(l,t,h))}}}}function wCn(s){const t=(s=Z9t(s))[0].g;if(s=s[1]){const n=vXe(s),r=qF(wTe,xXe,yXe,s).T;return(a,i,l)=>t(a,i,l,r,n)}return t}function jTe(s,t,n){s[t]=n.h}function NTe(s,t,n,r){let a,i;const l=n.h;s[t]=(o,c,d)=>l(o,c,d,i||(i=qF(_Te,jTe,NTe,r).T),a||(a=Q9t(r)))}function Q9t(s){let t=s[g0t];if(!t){const n=qF(_Te,jTe,NTe,s);t=(r,a)=>J9t(r,a,n),s[g0t]=t}return t}function J9t(s,t,n){g9t(s,0|s[Xo],(r,a)=>{if(a!=null){var i=function(l,o){var c=l[o];if(c)return c;if((c=l.ba)&&(c=c[o])){var d=(c=Z9t(c))[0].h;if(c=c[1]){const u=Q9t(c),h=qF(_Te,jTe,NTe,c).T;c=l.ma?Y9t(h,u):(m,p,g)=>d(m,p,g,h,u)}else c=d;return l[o]=c}}(n,r);i?i(t,a,r):r<500||cq(QBe,3)}}),(s=mTe(s))&&I4e(s,(r,a,i)=>{for(fq(t,t.g.end()),r=0;r{O4e(s,n,mO([l,i],r),a)});else if(Array.isArray(t)){for(let i=0;i>BigInt(32))),LB(s.g,n.h,n.g);break;default:n=p0t(t),LB(s.g,n.h,n.g)}}function szt(s,t,n){(t=IV(t))!=null&&t!=null&&(K2(s,n,0),xTe(s.g,t))}function nzt(s,t,n){(t=b9t(t))!=null&&(K2(s,n,0),s.g.g.push(t?1:0))}function rzt(s,t,n){(t=mv(t))!=null&&yTe(s,n,i9t(t))}function azt(s,t,n,r,a){O4e(s,n,X9t(t,r),a)}function izt(s,t,n){(t=t==null||typeof t=="string"||t instanceof $5?t:void 0)!=null&&yTe(s,n,iXe(t,!0).buffer)}function ozt(s,t,n){(t=_9t(t))!=null&&t!=null&&(K2(s,n,0),FV(s.g,t))}function lzt(s,t,n){return(s.h===5||s.h===2)&&(t=OV(t,0|t[Xo],n),s.h==2?gTe(s,R4e,t):t.push(R4e(s.g)),!0)}var Ox=j1(function(s,t,n){return s.h===5&&(N1(t,n,R4e(s.g)),!0)},ezt,vTe),kCn=$V(lzt,function(s,t,n){if((t=BV(x5,t))!=null)for(let l=0;l=0?r=String(a):((a=r.indexOf("."))!==-1&&(r=r.substring(0,a)),(a=r[0]!=="-"&&((a=r.length)<20||a===20&&r<="18446744073709551615"))||(uTe(r),r=lQ(Ap,Mx))),r;if(a==="number")return(r=mq(r))>=0&&eF(r)||(hq(r),r=y9t(Ap,Mx)),r}}(t),t!=null&&(typeof t=="string"&&f0t(t),t!=null))switch(K2(s,n,0),typeof t){case"number":s=s.g,hq(t),LB(s,Ap,Mx);break;case"bigint":n=BigInt.asUintN(64,t),n=new t$e(Number(n&BigInt(4294967295)),Number(n>>BigInt(32))),LB(s.g,n.h,n.g);break;default:n=f0t(t),LB(s.g,n.h,n.g)}},yCn),_y=j1(function(s,t,n){return s.h===0&&(N1(t,n,IM(s.g)),!0)},szt,pXe),ute=$V(function(s,t,n){return(s.h===0||s.h===2)&&(t=OV(t,0|t[Xo],n),s.h==2?gTe(s,IM,t):t.push(IM(s.g)),!0)},function(s,t,n){if((t=BV(IV,t))!=null&&t.length){n=uXe(s,n);for(let r=0;r{{const i={ea:!0};r&&Object.assign(i,r),n=z9t(n,void 0,void 0,i);try{const l=new s,o=l.v;vXe(t)(o,n);var a=l}finally{B9t(n)}}return a}}function kTe(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}}}};J9t(this.v,t,qF(_Te,jTe,NTe,s)),fq(t,t.g.end());const n=new Uint8Array(t.h),r=t.l,a=r.length;let i=0;for(let l=0;la;n=b0t.createPolicy("goog#html",{createHTML:r,createScript:r,createScriptURL:r})}catch{}return n}()),s=(t=lDe)?t.createScriptURL(s):s,new class{constructor(n){this.g=n}toString(){return this.g+""}}(s)}function Cae(s,...t){if(t.length===0)return _0t(s[0]);let n=s[0];for(let r=0;r({index:p2(r,1)??0??-1,score:Gg(r,2)??0,categoryName:mv(Rp(r,3))??""??"",displayName:mv(Rp(r,4))??""??""})),headIndex:t,headName:n}}function n3n(s){const t={classifications:Y3(s,FCn,1).map(n=>{var r;return AXe(((r=Uu(n,xzt,4))==null?void 0:r.g())??[],p2(n,2)??0,mv(Rp(n,3))??"")})};return function(n){return n==null?n:typeof n=="bigint"?(JBe(n)?n=Number(n):(n=ote(64,n),n=JBe(n)?Number(n):String(n)),n):lte(n)?typeof n=="number"?YZe(n):j9t(n):void 0}(Rp(s,2,void 0,void 0,P4e))!=null&&(t.timestampMs=Vzt(Rp(s,2,void 0,void 0,P4e)??E9t)),t}function Hzt(s){var l,o;var t=vD(s,3,x5,yD()),n=vD(s,2,IV,yD()),r=vD(s,1,mv,yD()),a=vD(s,9,mv,yD());const i={categories:[],keypoints:[]};for(let c=0;ct>127?t-256:t)}function I0t(s,t){if(s.length!==t.length)throw Error(`Cannot compute cosine similarity between embeddings of different sizes (${s.length} vs. ${t.length}).`);let n=0,r=0,a=0;for(let i=0;i=1&&Number(s[1])>=17))}async function L0t(s){if(typeof importScripts!="function"){const t=document.createElement("script");return t.src=s.toString(),t.crossOrigin="anonymous",new Promise((n,r)=>{t.addEventListener("load",()=>{n()},!1),t.addEventListener("error",a=>{r(a)},!1),document.body.appendChild(t)})}try{importScripts(s.toString())}catch(t){if(!(t instanceof TypeError))throw t;{const n=self.import;n?await n(s.toString()):await import(s.toString())}}}function Kzt(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 Jo(s,t,n){s.m||console.error("No wasm multistream support detected: ensure dependency inclusion of :gl_graph_runner_internal_multi_input target"),n(t=s.i.stringToNewUTF8(t)),s.i._free(t)}function R0t(s,t,n){if(!s.i.canvas)throw Error("No OpenGL canvas configured.");if(n?s.i._bindTextureToStream(n):s.i._bindTextureToCanvas(),!(n=s.i.canvas.getContext("webgl2")||s.i.canvas.getContext("webgl")))throw Error("Failed to obtain WebGL context from the provided canvas. `getContext()` should only be invoked with `webgl` or `webgl2`.");s.i.gpuOriginForWebTexturesIsBottomLeft&&n.pixelStorei(n.UNPACK_FLIP_Y_WEBGL,!0),n.texImage2D(n.TEXTURE_2D,0,n.RGBA,n.RGBA,n.UNSIGNED_BYTE,t),s.i.gpuOriginForWebTexturesIsBottomLeft&&n.pixelStorei(n.UNPACK_FLIP_Y_WEBGL,!1);const[r,a]=Kzt(t);return!s.l||r===s.i.canvas.width&&a===s.i.canvas.height||(s.i.canvas.width=r,s.i.canvas.height=a),[r,a]}function D0t(s,t,n){s.m||console.error("No wasm multistream support detected: ensure dependency inclusion of :gl_graph_runner_internal_multi_input target");const r=new Uint32Array(t.length);for(let a=0;a>2),n(t);for(const a of r)s.i._free(a);s.i._free(t)}function uS(s,t,n){s.i.simpleListeners=s.i.simpleListeners||{},s.i.simpleListeners[t]=n}function VA(s,t,n){let r=[];s.i.simpleListeners=s.i.simpleListeners||{},s.i.simpleListeners[t]=(a,i,l)=>{i?(n(r,l),r=[]):r.push(a)}}z9.forVisionTasks=function(s,t=!1){return Eae("vision",s??Cae``,t)},z9.forTextTasks=function(s,t=!1){return Eae("text",s??Cae``,t)},z9.forGenAiTasks=function(s,t=!1){return Eae("genai",s??Cae``,t)},z9.forAudioTasks=function(s,t=!1){return Eae("audio",s??Cae``,t)},z9.isSimdSupported=function(s=!1){return Gzt(s)};async function a3n(s,t,n,r){return s=await(async(a,i,l,o,c)=>{if(i&&await L0t(i),!self.ModuleFactory||l&&(await L0t(l),!self.ModuleFactory))throw Error("ModuleFactory not set.");return self.Module&&c&&((i=self.Module).locateFile=c.locateFile,c.mainScriptUrlOrBlob&&(i.mainScriptUrlOrBlob=c.mainScriptUrlOrBlob)),c=await self.ModuleFactory(self.Module||c),self.ModuleFactory=self.Module=void 0,new a(c,o)})(s,n.wasmLoaderPath,n.assetLoaderPath,t,{locateFile:a=>a.endsWith(".wasm")?n.wasmBinaryPath.toString():n.assetBinaryPath&&a.endsWith(".data")?n.assetBinaryPath.toString():a}),await s.o(r),s}function uDe(s,t){const n=Uu(s.baseOptions,F4e,1)||new F4e;typeof t=="string"?(Jh(n,2,cte(t)),Jh(n,1)):t instanceof Uint8Array&&(Jh(n,1,HZe(t,!1)),Jh(n,2)),El(s.baseOptions,0,1,n)}function O0t(s){try{const t=s.H.length;if(t===1)throw Error(s.H[0].message);if(t>1)throw Error("Encountered multiple errors: "+s.H.map(n=>n.message).join(", "))}finally{s.H=[]}}function Co(s,t){s.C=Math.max(s.C,t)}function ETe(s,t){s.B=new U_,dj(s.B,2,"PassThroughCalculator"),lp(s.B,"free_memory"),mu(s.B,"free_memory_unused_out"),Up(t,"free_memory"),Y2(t,s.B)}function pq(s,t){lp(s.B,t),mu(s.B,t+"_unused_out")}function TTe(s){s.g.addBoolToStream(!0,"free_memory",s.C)}var l$e=class{constructor(s){this.g=s,this.H=[],this.C=0,this.g.setAutoRenderToScreen(!1)}l(s,t=!0){var n,r,a,i,l,o;if(t){const c=s.baseOptions||{};if((n=s.baseOptions)!=null&&n.modelAssetBuffer&&((r=s.baseOptions)!=null&&r.modelAssetPath))throw Error("Cannot set both baseOptions.modelAssetPath and baseOptions.modelAssetBuffer");if(!((a=Uu(this.baseOptions,F4e,1))!=null&&a.g()||(i=Uu(this.baseOptions,F4e,1))!=null&&i.l()||(l=s.baseOptions)!=null&&l.modelAssetBuffer||(o=s.baseOptions)!=null&&o.modelAssetPath))throw Error("Either baseOptions.modelAssetPath or baseOptions.modelAssetBuffer must be set");if(function(d,u){let h=Uu(d.baseOptions,A0t,3);if(!h){var m=h=new A0t,p=new w0t;eZ(m,4,ANe,p)}"delegate"in u&&(u.delegate==="GPU"?(u=h,m=new MCn,eZ(u,2,ANe,m)):(u=h,m=new w0t,eZ(u,4,ANe,m))),El(d.baseOptions,0,3,h)}(this,c),c.modelAssetPath)return fetch(c.modelAssetPath.toString()).then(d=>{if(d.ok)return d.arrayBuffer();throw Error(`Failed to fetch model: ${c.modelAssetPath} (${d.status})`)}).then(d=>{try{this.g.i.FS_unlink("/model.dat")}catch{}this.g.i.FS_createDataFile("/","model.dat",new Uint8Array(d),!0,!1,!1),uDe(this,"/model.dat"),this.m(),this.L()});if(c.modelAssetBuffer instanceof Uint8Array)uDe(this,c.modelAssetBuffer);else if(c.modelAssetBuffer)return async function(d){const u=[];for(var h=0;;){const{done:m,value:p}=await d.read();if(m)break;u.push(p),h+=p.length}if(u.length===0)return new Uint8Array(0);if(u.length===1)return u[0];d=new Uint8Array(h),h=0;for(const m of u)d.set(m,h),h+=m.length;return d}(c.modelAssetBuffer).then(d=>{uDe(this,d),this.m(),this.L()})}return this.m(),this.L(),Promise.resolve()}L(){}ca(){let s;if(this.g.ca(t=>{s=PCn(t)}),!s)throw Error("Failed to retrieve CalculatorGraphConfig");return s}setGraph(s,t){this.g.attachErrorListener((n,r)=>{this.H.push(Error(r))}),this.g.Ja(),this.g.setGraph(s,t),this.B=void 0,O0t(this)}finishProcessing(){this.g.finishProcessing(),O0t(this)}close(){this.B=void 0,this.g.closeGraph()}};function gM(s,t){if(!s)throw Error(`Unable to obtain required WebGL resource: ${t}`);return s}l$e.prototype.close=l$e.prototype.close;class i3n{constructor(t,n,r,a){this.g=t,this.h=n,this.m=r,this.l=a}bind(){this.g.bindVertexArray(this.h)}close(){this.g.deleteVertexArray(this.h),this.g.deleteBuffer(this.m),this.g.deleteBuffer(this.l)}}function F0t(s,t,n){const r=s.g;if(n=gM(r.createShader(n),"Failed to create WebGL shader"),r.shaderSource(n,t),r.compileShader(n),!r.getShaderParameter(n,r.COMPILE_STATUS))throw Error(`Could not compile WebGL shader: ${r.getShaderInfoLog(n)}`);return r.attachShader(s.h,n),n}function z0t(s,t){const n=s.g,r=gM(n.createVertexArray(),"Failed to create vertex array");n.bindVertexArray(r);const a=gM(n.createBuffer(),"Failed to create buffer");n.bindBuffer(n.ARRAY_BUFFER,a),n.enableVertexAttribArray(s.O),n.vertexAttribPointer(s.O,2,n.FLOAT,!1,0,0),n.bufferData(n.ARRAY_BUFFER,new Float32Array([-1,-1,-1,1,1,1,1,-1]),n.STATIC_DRAW);const i=gM(n.createBuffer(),"Failed to create buffer");return n.bindBuffer(n.ARRAY_BUFFER,i),n.enableVertexAttribArray(s.L),n.vertexAttribPointer(s.L,2,n.FLOAT,!1,0,0),n.bufferData(n.ARRAY_BUFFER,new Float32Array(t?[0,1,0,0,1,0,1,1]:[0,0,0,1,1,1,1,0]),n.STATIC_DRAW),n.bindBuffer(n.ARRAY_BUFFER,null),n.bindVertexArray(null),new i3n(n,r,a,i)}function EXe(s,t){if(s.g){if(t!==s.g)throw Error("Cannot change GL context once initialized")}else s.g=t}function o3n(s,t,n,r){return EXe(s,t),s.h||(s.m(),s.D()),n?(s.u||(s.u=z0t(s,!0)),n=s.u):(s.A||(s.A=z0t(s,!1)),n=s.A),t.useProgram(s.h),n.bind(),s.l(),s=r(),n.g.bindVertexArray(null),s}function Yzt(s,t,n){return EXe(s,t),s=gM(t.createTexture(),"Failed to create texture"),t.bindTexture(t.TEXTURE_2D,s),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,n??t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,n??t.LINEAR),t.bindTexture(t.TEXTURE_2D,null),s}function Zzt(s,t,n){EXe(s,t),s.B||(s.B=gM(t.createFramebuffer(),"Failed to create framebuffe.")),t.bindFramebuffer(t.FRAMEBUFFER,s.B),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,n,0)}function l3n(s){var t;(t=s.g)==null||t.bindFramebuffer(s.g.FRAMEBUFFER,null)}var Xzt=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=gM(s.createProgram(),"Failed to create WebGL program"),this.X=F0t(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=F0t(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 JC(s,t){switch(t){case 0:return s.g.find(n=>n instanceof Uint8Array);case 1:return s.g.find(n=>n instanceof Float32Array);case 2:return s.g.find(n=>typeof WebGLTexture<"u"&&n instanceof WebGLTexture);default:throw Error(`Type is not supported: ${t}`)}}function c$e(s){var t=JC(s,1);if(!t){if(t=JC(s,0))t=new Float32Array(t).map(r=>r/255);else{t=new Float32Array(s.width*s.height);const r=gq(s);var n=TXe(s);if(Zzt(n,r,Qzt(s)),"iPad Simulator;iPhone Simulator;iPod Simulator;iPad;iPhone;iPod".split(";").includes(navigator.platform)||navigator.userAgent.includes("Mac")&&"document"in self&&"ontouchend"in self.document){n=new Float32Array(s.width*s.height*4),r.readPixels(0,0,s.width,s.height,r.RGBA,r.FLOAT,n);for(let a=0,i=0;aMath.round(255*n))),s.g.push(t)),t;var s,t}ia(){return c$e(this)}N(){return Qzt(this)}clone(){const s=[];for(const t of this.g){let n;if(t instanceof Uint8Array)n=new Uint8Array(t);else if(t instanceof Float32Array)n=new Float32Array(t);else{if(!(t instanceof WebGLTexture))throw Error(`Type is not supported: ${t}`);{const r=gq(this),a=TXe(this);r.activeTexture(r.TEXTURE1),n=Yzt(a,r,this.m?r.LINEAR:r.NEAREST),r.bindTexture(r.TEXTURE_2D,n);const i=Jzt(this);r.texImage2D(r.TEXTURE_2D,0,i,this.width,this.height,0,r.RED,r.FLOAT,null),r.bindTexture(r.TEXTURE_2D,null),Zzt(a,r,n),o3n(a,r,!1,()=>{eBt(this),r.clearColor(0,0,0,0),r.clear(r.COLOR_BUFFER_BIT),r.drawArrays(r.TRIANGLE_FAN,0,4),d$e(this)}),l3n(a),d$e(this)}}s.push(n)}return new Ky(s,this.m,this.R(),this.canvas,this.l,this.width,this.height)}close(){this.j&&gq(this).deleteTexture(JC(this,2)),B0t=-1}};Ky.prototype.close=Ky.prototype.close,Ky.prototype.clone=Ky.prototype.clone,Ky.prototype.getAsWebGLTexture=Ky.prototype.N,Ky.prototype.getAsFloat32Array=Ky.prototype.ia,Ky.prototype.getAsUint8Array=Ky.prototype.ja,Ky.prototype.hasWebGLTexture=Ky.prototype.R,Ky.prototype.hasFloat32Array=Ky.prototype.ka,Ky.prototype.hasUint8Array=Ky.prototype.Fa;var B0t=250;function Pk(...s){return s.map(([t,n])=>({start:t,end:n}))}const c3n=function(s){return class extends s{Ja(){this.i._registerModelResourcesGraphService()}}}(($0t=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:Wzt()?this.i.canvas=new OffscreenCanvas(1,1):(console.warn("OffscreenCanvas not supported and GraphRunner constructor glCanvas parameter is undefined. Creating backup canvas."),this.i.canvas=document.createElement("canvas"))}async initializeGraph(s){const t=await(await fetch(s)).arrayBuffer();s=!(s.endsWith(".pbtxt")||s.endsWith(".textproto")),this.setGraph(new Uint8Array(t),s)}setGraphFromString(s){this.setGraph(new TextEncoder().encode(s),!1)}setGraph(s,t){const n=s.length,r=this.i._malloc(n);this.i.HEAPU8.set(s,r),t?this.i._changeBinaryGraph(n,r):this.i._changeTextGraph(n,r),this.i._free(r)}configureAudio(s,t,n,r,a){this.i._configureAudio||console.warn('Attempting to use configureAudio without support for input audio. Is build dep ":gl_graph_runner_audio" missing?'),Jo(this,r||"input_audio",i=>{Jo(this,a=a||"audio_header",l=>{this.i._configureAudio(i,l,s,t??0,n)})})}setAutoResizeCanvas(s){this.l=s}setAutoRenderToScreen(s){this.i._setAutoRenderToScreen(s)}setGpuBufferVerticalFlip(s){this.i.gpuOriginForWebTexturesIsBottomLeft=s}ca(s){uS(this,"__graph_config__",t=>{s(t)}),Jo(this,"__graph_config__",t=>{this.i._getGraphConfig(t,void 0)}),delete this.i.simpleListeners.__graph_config__}attachErrorListener(s){this.i.errorListener=s}attachEmptyPacketListener(s,t){this.i.emptyPacketListeners=this.i.emptyPacketListeners||{},this.i.emptyPacketListeners[s]=t}addAudioToStream(s,t,n){this.addAudioToStreamWithShape(s,0,0,t,n)}addAudioToStreamWithShape(s,t,n,r,a){const i=4*s.length;this.h!==i&&(this.g&&this.i._free(this.g),this.g=this.i._malloc(i),this.h=i),this.i.HEAPF32.set(s,this.g/4),Jo(this,r,l=>{this.i._addAudioToInputStream(this.g,t,n,l,a)})}addGpuBufferToStream(s,t,n){Jo(this,t,r=>{const[a,i]=R0t(this,s,r);this.i._addBoundTextureToStream(r,a,i,n)})}addBoolToStream(s,t,n){Jo(this,t,r=>{this.i._addBoolToInputStream(s,r,n)})}addDoubleToStream(s,t,n){Jo(this,t,r=>{this.i._addDoubleToInputStream(s,r,n)})}addFloatToStream(s,t,n){Jo(this,t,r=>{this.i._addFloatToInputStream(s,r,n)})}addIntToStream(s,t,n){Jo(this,t,r=>{this.i._addIntToInputStream(s,r,n)})}addUintToStream(s,t,n){Jo(this,t,r=>{this.i._addUintToInputStream(s,r,n)})}addStringToStream(s,t,n){Jo(this,t,r=>{Jo(this,s,a=>{this.i._addStringToInputStream(a,r,n)})})}addStringRecordToStream(s,t,n){Jo(this,t,r=>{D0t(this,Object.keys(s),a=>{D0t(this,Object.values(s),i=>{this.i._addFlatHashMapToInputStream(a,i,Object.keys(s).length,r,n)})})})}addProtoToStream(s,t,n,r){Jo(this,n,a=>{Jo(this,t,i=>{const l=this.i._malloc(s.length);this.i.HEAPU8.set(s,l),this.i._addProtoToInputStream(l,s.length,i,a,r),this.i._free(l)})})}addEmptyPacketToStream(s,t){Jo(this,s,n=>{this.i._addEmptyPacketToInputStream(n,t)})}addBoolVectorToStream(s,t,n){Jo(this,t,r=>{const a=this.i._allocateBoolVector(s.length);if(!a)throw Error("Unable to allocate new bool vector on heap.");for(const i of s)this.i._addBoolVectorEntry(a,i);this.i._addBoolVectorToInputStream(a,r,n)})}addDoubleVectorToStream(s,t,n){Jo(this,t,r=>{const a=this.i._allocateDoubleVector(s.length);if(!a)throw Error("Unable to allocate new double vector on heap.");for(const i of s)this.i._addDoubleVectorEntry(a,i);this.i._addDoubleVectorToInputStream(a,r,n)})}addFloatVectorToStream(s,t,n){Jo(this,t,r=>{const a=this.i._allocateFloatVector(s.length);if(!a)throw Error("Unable to allocate new float vector on heap.");for(const i of s)this.i._addFloatVectorEntry(a,i);this.i._addFloatVectorToInputStream(a,r,n)})}addIntVectorToStream(s,t,n){Jo(this,t,r=>{const a=this.i._allocateIntVector(s.length);if(!a)throw Error("Unable to allocate new int vector on heap.");for(const i of s)this.i._addIntVectorEntry(a,i);this.i._addIntVectorToInputStream(a,r,n)})}addUintVectorToStream(s,t,n){Jo(this,t,r=>{const a=this.i._allocateUintVector(s.length);if(!a)throw Error("Unable to allocate new unsigned int vector on heap.");for(const i of s)this.i._addUintVectorEntry(a,i);this.i._addUintVectorToInputStream(a,r,n)})}addStringVectorToStream(s,t,n){Jo(this,t,r=>{const a=this.i._allocateStringVector(s.length);if(!a)throw Error("Unable to allocate new string vector on heap.");for(const i of s)Jo(this,i,l=>{this.i._addStringVectorEntry(a,l)});this.i._addStringVectorToInputStream(a,r,n)})}addBoolToInputSidePacket(s,t){Jo(this,t,n=>{this.i._addBoolToInputSidePacket(s,n)})}addDoubleToInputSidePacket(s,t){Jo(this,t,n=>{this.i._addDoubleToInputSidePacket(s,n)})}addFloatToInputSidePacket(s,t){Jo(this,t,n=>{this.i._addFloatToInputSidePacket(s,n)})}addIntToInputSidePacket(s,t){Jo(this,t,n=>{this.i._addIntToInputSidePacket(s,n)})}addUintToInputSidePacket(s,t){Jo(this,t,n=>{this.i._addUintToInputSidePacket(s,n)})}addStringToInputSidePacket(s,t){Jo(this,t,n=>{Jo(this,s,r=>{this.i._addStringToInputSidePacket(r,n)})})}addProtoToInputSidePacket(s,t,n){Jo(this,n,r=>{Jo(this,t,a=>{const i=this.i._malloc(s.length);this.i.HEAPU8.set(s,i),this.i._addProtoToInputSidePacket(i,s.length,a,r),this.i._free(i)})})}addBoolVectorToInputSidePacket(s,t){Jo(this,t,n=>{const r=this.i._allocateBoolVector(s.length);if(!r)throw Error("Unable to allocate new bool vector on heap.");for(const a of s)this.i._addBoolVectorEntry(r,a);this.i._addBoolVectorToInputSidePacket(r,n)})}addDoubleVectorToInputSidePacket(s,t){Jo(this,t,n=>{const r=this.i._allocateDoubleVector(s.length);if(!r)throw Error("Unable to allocate new double vector on heap.");for(const a of s)this.i._addDoubleVectorEntry(r,a);this.i._addDoubleVectorToInputSidePacket(r,n)})}addFloatVectorToInputSidePacket(s,t){Jo(this,t,n=>{const r=this.i._allocateFloatVector(s.length);if(!r)throw Error("Unable to allocate new float vector on heap.");for(const a of s)this.i._addFloatVectorEntry(r,a);this.i._addFloatVectorToInputSidePacket(r,n)})}addIntVectorToInputSidePacket(s,t){Jo(this,t,n=>{const r=this.i._allocateIntVector(s.length);if(!r)throw Error("Unable to allocate new int vector on heap.");for(const a of s)this.i._addIntVectorEntry(r,a);this.i._addIntVectorToInputSidePacket(r,n)})}addUintVectorToInputSidePacket(s,t){Jo(this,t,n=>{const r=this.i._allocateUintVector(s.length);if(!r)throw Error("Unable to allocate new unsigned int vector on heap.");for(const a of s)this.i._addUintVectorEntry(r,a);this.i._addUintVectorToInputSidePacket(r,n)})}addStringVectorToInputSidePacket(s,t){Jo(this,t,n=>{const r=this.i._allocateStringVector(s.length);if(!r)throw Error("Unable to allocate new string vector on heap.");for(const a of s)Jo(this,a,i=>{this.i._addStringVectorEntry(r,i)});this.i._addStringVectorToInputSidePacket(r,n)})}attachBoolListener(s,t){uS(this,s,t),Jo(this,s,n=>{this.i._attachBoolListener(n)})}attachBoolVectorListener(s,t){VA(this,s,t),Jo(this,s,n=>{this.i._attachBoolVectorListener(n)})}attachIntListener(s,t){uS(this,s,t),Jo(this,s,n=>{this.i._attachIntListener(n)})}attachIntVectorListener(s,t){VA(this,s,t),Jo(this,s,n=>{this.i._attachIntVectorListener(n)})}attachUintListener(s,t){uS(this,s,t),Jo(this,s,n=>{this.i._attachUintListener(n)})}attachUintVectorListener(s,t){VA(this,s,t),Jo(this,s,n=>{this.i._attachUintVectorListener(n)})}attachDoubleListener(s,t){uS(this,s,t),Jo(this,s,n=>{this.i._attachDoubleListener(n)})}attachDoubleVectorListener(s,t){VA(this,s,t),Jo(this,s,n=>{this.i._attachDoubleVectorListener(n)})}attachFloatListener(s,t){uS(this,s,t),Jo(this,s,n=>{this.i._attachFloatListener(n)})}attachFloatVectorListener(s,t){VA(this,s,t),Jo(this,s,n=>{this.i._attachFloatVectorListener(n)})}attachStringListener(s,t){uS(this,s,t),Jo(this,s,n=>{this.i._attachStringListener(n)})}attachStringVectorListener(s,t){VA(this,s,t),Jo(this,s,n=>{this.i._attachStringVectorListener(n)})}attachProtoListener(s,t,n){uS(this,s,t),Jo(this,s,r=>{this.i._attachProtoListener(r,n||!1)})}attachProtoVectorListener(s,t,n){VA(this,s,t),Jo(this,s,r=>{this.i._attachProtoVectorListener(r,n||!1)})}attachAudioListener(s,t,n){this.i._attachAudioListener||console.warn('Attempting to use attachAudioListener without support for output audio. Is build dep ":gl_graph_runner_audio_out" missing?'),uS(this,s,(r,a)=>{r=new Float32Array(r.buffer,r.byteOffset,r.length/4),t(r,a)}),Jo(this,s,r=>{this.i._attachAudioListener(r,n||!1)})}finishProcessing(){this.i._waitUntilIdle()}closeGraph(){this.i._closeGraph(),this.i.simpleListeners=void 0,this.i.emptyPacketListeners=void 0}},class extends $0t{get ga(){return this.i}pa(s,t,n){Jo(this,t,r=>{const[a,i]=R0t(this,s,r);this.ga._addBoundTextureAsImageToStream(r,a,i,n)})}Z(s,t){uS(this,s,t),Jo(this,s,n=>{this.ga._attachImageListener(n)})}aa(s,t){VA(this,s,t),Jo(this,s,n=>{this.ga._attachImageVectorListener(n)})}}));var $0t,Ik=class extends c3n{};async function Cu(s,t,n){return async function(r,a,i,l){return a3n(r,a,i,l)}(s,n.canvas??(Wzt()?void 0:document.createElement("canvas")),t,n)}function tBt(s,t,n,r){if(s.U){const i=new wzt;if(n!=null&&n.regionOfInterest){if(!s.oa)throw Error("This task doesn't support region-of-interest.");var a=n.regionOfInterest;if(a.left>=a.right||a.top>=a.bottom)throw Error("Expected RectF with left < right and top < bottom.");if(a.left<0||a.top<0||a.right>1||a.bottom>1)throw Error("Expected RectF values to be in [0,1].");dl(i,1,(a.left+a.right)/2),dl(i,2,(a.top+a.bottom)/2),dl(i,4,a.right-a.left),dl(i,3,a.bottom-a.top)}else dl(i,1,.5),dl(i,2,.5),dl(i,4,1),dl(i,3,1);if(n!=null&&n.rotationDegrees){if((n==null?void 0:n.rotationDegrees)%90!=0)throw Error("Expected rotation to be a multiple of 90°.");if(dl(i,5,-Math.PI*n.rotationDegrees/180),(n==null?void 0:n.rotationDegrees)%180!=0){const[l,o]=Kzt(t);n=Gg(i,3)*o/l,a=Gg(i,4)*l/o,dl(i,4,n),dl(i,3,a)}}s.g.addProtoToStream(i.g(),"mediapipe.NormalizedRect",s.U,r)}s.g.pa(t,s.X,r??performance.now()),s.finishProcessing()}function Lk(s,t,n){var r;if((r=s.baseOptions)!=null&&r.g())throw Error("Task is not initialized with image mode. 'runningMode' must be set to 'IMAGE'.");tBt(s,t,n,s.C+1)}function h4(s,t,n,r){var a;if(!((a=s.baseOptions)!=null&&a.g()))throw Error("Task is not initialized with video mode. 'runningMode' must be set to 'VIDEO'.");tBt(s,t,n,r)}function xq(s,t,n,r){var a=t.data;const i=t.width,l=i*(t=t.height);if((a instanceof Uint8Array||a instanceof Float32Array)&&a.length!==l)throw Error("Unsupported channel count: "+a.length/l);return s=new Ky([a],n,!1,s.g.i.canvas,s.P,i,t),r?s.clone():s}var uj=class extends l$e{constructor(s,t,n,r){super(s),this.g=s,this.X=t,this.U=n,this.oa=r,this.P=new Xzt}l(s,t=!0){if("runningMode"in s&&Jh(this.baseOptions,2,cQ(!!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()}};uj.prototype.close=uj.prototype.close;var Oj=class extends uj{constructor(s,t){super(new Ik(s,t),"image_in","norm_rect_in",!1),this.j={detections:[]},El(s=this.h=new CTe,0,1,t=new Cg),dl(this.h,2,.5),dl(this.h,3,.3)}get baseOptions(){return Uu(this.h,Cg,1)}set baseOptions(s){El(this.h,0,1,s)}o(s){return"minDetectionConfidence"in s&&dl(this.h,2,s.minDetectionConfidence??.5),"minSuppressionThreshold"in s&&dl(this.h,3,s.minSuppressionThreshold??.3),this.l(s)}F(s,t){return this.j={detections:[]},Lk(this,s,t),this.j}G(s,t,n){return this.j={detections:[]},h4(this,s,n,t),this.j}m(){var s=new _j;Up(s,"image_in"),Up(s,"norm_rect_in"),sh(s,"detections");const t=new bj;d4(t,VCn,this.h);const n=new U_;dj(n,2,"mediapipe.tasks.vision.face_detector.FaceDetectorGraph"),lp(n,"IMAGE:image_in"),lp(n,"NORM_RECT:norm_rect_in"),mu(n,"DETECTIONS:detections"),n.o(t),Y2(s,n),this.g.attachProtoVectorListener("detections",(r,a)=>{for(const i of r)r=vzt(i),this.j.detections.push(Hzt(r));Co(this,a)}),this.g.attachEmptyPacketListener("detections",r=>{Co(this,r)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};Oj.prototype.detectForVideo=Oj.prototype.G,Oj.prototype.detect=Oj.prototype.F,Oj.prototype.setOptions=Oj.prototype.o,Oj.createFromModelPath=async function(s,t){return Cu(Oj,s,{baseOptions:{modelAssetPath:t}})},Oj.createFromModelBuffer=function(s,t){return Cu(Oj,s,{baseOptions:{modelAssetBuffer:t}})},Oj.createFromOptions=function(s,t){return Cu(Oj,s,t)};var MXe=Pk([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]),PXe=Pk([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]),IXe=Pk([276,283],[283,282],[282,295],[295,285],[300,293],[293,334],[334,296],[296,336]),sBt=Pk([474,475],[475,476],[476,477],[477,474]),LXe=Pk([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]),RXe=Pk([46,53],[53,52],[52,65],[65,55],[70,63],[63,105],[105,66],[66,107]),nBt=Pk([469,470],[470,471],[471,472],[472,469]),DXe=Pk([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]),rBt=[...MXe,...PXe,...IXe,...LXe,...RXe,...DXe],aBt=Pk([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 U0t(s){s.j={faceLandmarks:[],faceBlendshapes:[],facialTransformationMatrixes:[]}}var og=class extends uj{constructor(s,t){super(new Ik(s,t),"image_in","norm_rect",!1),this.j={faceLandmarks:[],faceBlendshapes:[],facialTransformationMatrixes:[]},this.outputFacialTransformationMatrixes=this.outputFaceBlendshapes=!1,El(s=this.h=new Czt,0,1,t=new Cg),this.A=new Szt,El(this.h,0,3,this.A),this.u=new CTe,El(this.h,0,2,this.u),Z3(this.u,4,1),dl(this.u,2,.5),dl(this.A,2,.5),dl(this.h,4,.5)}get baseOptions(){return Uu(this.h,Cg,1)}set baseOptions(s){El(this.h,0,1,s)}o(s){return"numFaces"in s&&Z3(this.u,4,s.numFaces??1),"minFaceDetectionConfidence"in s&&dl(this.u,2,s.minFaceDetectionConfidence??.5),"minTrackingConfidence"in s&&dl(this.h,4,s.minTrackingConfidence??.5),"minFacePresenceConfidence"in s&&dl(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 U0t(this),Lk(this,s,t),this.j}G(s,t,n){return U0t(this),h4(this,s,n,t),this.j}m(){var s=new _j;Up(s,"image_in"),Up(s,"norm_rect"),sh(s,"face_landmarks");const t=new bj;d4(t,GCn,this.h);const n=new U_;dj(n,2,"mediapipe.tasks.vision.face_landmarker.FaceLandmarkerGraph"),lp(n,"IMAGE:image_in"),lp(n,"NORM_RECT:norm_rect"),mu(n,"NORM_LANDMARKS:face_landmarks"),n.o(t),Y2(s,n),this.g.attachProtoVectorListener("face_landmarks",(r,a)=>{for(const i of r)r=hte(i),this.j.faceLandmarks.push(ATe(r));Co(this,a)}),this.g.attachEmptyPacketListener("face_landmarks",r=>{Co(this,r)}),this.outputFaceBlendshapes&&(sh(s,"blendshapes"),mu(n,"BLENDSHAPES:blendshapes"),this.g.attachProtoVectorListener("blendshapes",(r,a)=>{if(this.outputFaceBlendshapes)for(const i of r)r=STe(i),this.j.faceBlendshapes.push(AXe(r.g()??[]));Co(this,a)}),this.g.attachEmptyPacketListener("blendshapes",r=>{Co(this,r)})),this.outputFacialTransformationMatrixes&&(sh(s,"face_geometry"),mu(n,"FACE_GEOMETRY:face_geometry"),this.g.attachProtoVectorListener("face_geometry",(r,a)=>{if(this.outputFacialTransformationMatrixes)for(const i of r)(r=Uu(r=HCn(i),DCn,2))&&this.j.facialTransformationMatrixes.push({rows:p2(r,1)??0??0,columns:p2(r,2)??0??0,data:vD(r,3,x5,yD()).slice()??[]});Co(this,a)}),this.g.attachEmptyPacketListener("face_geometry",r=>{Co(this,r)})),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};og.prototype.detectForVideo=og.prototype.G,og.prototype.detect=og.prototype.F,og.prototype.setOptions=og.prototype.o,og.createFromModelPath=function(s,t){return Cu(og,s,{baseOptions:{modelAssetPath:t}})},og.createFromModelBuffer=function(s,t){return Cu(og,s,{baseOptions:{modelAssetBuffer:t}})},og.createFromOptions=function(s,t){return Cu(og,s,t)},og.FACE_LANDMARKS_LIPS=MXe,og.FACE_LANDMARKS_LEFT_EYE=PXe,og.FACE_LANDMARKS_LEFT_EYEBROW=IXe,og.FACE_LANDMARKS_LEFT_IRIS=sBt,og.FACE_LANDMARKS_RIGHT_EYE=LXe,og.FACE_LANDMARKS_RIGHT_EYEBROW=RXe,og.FACE_LANDMARKS_RIGHT_IRIS=nBt,og.FACE_LANDMARKS_FACE_OVAL=DXe,og.FACE_LANDMARKS_CONTOURS=rBt,og.FACE_LANDMARKS_TESSELATION=aBt;var OXe=Pk([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 q0t(s){s.gestures=[],s.landmarks=[],s.worldLandmarks=[],s.handedness=[]}function V0t(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 H0t(s,t=!0){const n=[];for(const a of s){var r=STe(a);s=[];for(const i of r.g())r=t&&p2(i,1)!=null?p2(i,1)??0:-1,s.push({score:Gg(i,2)??0,index:r,categoryName:mv(Rp(i,3))??""??"",displayName:mv(Rp(i,4))??""??""});n.push(s)}return n}var cw=class extends uj{constructor(s,t){super(new Ik(s,t),"image_in","norm_rect",!1),this.gestures=[],this.landmarks=[],this.worldLandmarks=[],this.handedness=[],El(s=this.j=new Tzt,0,1,t=new Cg),this.u=new NXe,El(this.j,0,2,this.u),this.D=new jXe,El(this.u,0,3,this.D),this.A=new Ezt,El(this.u,0,2,this.A),this.h=new WCn,El(this.j,0,3,this.h),dl(this.A,2,.5),dl(this.u,4,.5),dl(this.D,2,.5)}get baseOptions(){return Uu(this.j,Cg,1)}set baseOptions(s){El(this.j,0,1,s)}o(s){var a,i,l,o;if(Z3(this.A,3,s.numHands??1),"minHandDetectionConfidence"in s&&dl(this.A,2,s.minHandDetectionConfidence??.5),"minTrackingConfidence"in s&&dl(this.u,4,s.minTrackingConfidence??.5),"minHandPresenceConfidence"in s&&dl(this.D,2,s.minHandPresenceConfidence??.5),s.cannedGesturesClassifierOptions){var t=new c9,n=t,r=o$e(s.cannedGesturesClassifierOptions,(a=Uu(this.h,c9,3))==null?void 0:a.l());El(n,0,2,r),El(this.h,0,3,t)}else s.cannedGesturesClassifierOptions===void 0&&((i=Uu(this.h,c9,3))==null||i.g());return s.customGesturesClassifierOptions?(El(n=t=new c9,0,2,r=o$e(s.customGesturesClassifierOptions,(l=Uu(this.h,c9,4))==null?void 0:l.l())),El(this.h,0,4,t)):s.customGesturesClassifierOptions===void 0&&((o=Uu(this.h,c9,4))==null||o.g()),this.l(s)}Ha(s,t){return q0t(this),Lk(this,s,t),V0t(this)}Ia(s,t,n){return q0t(this),h4(this,s,n,t),V0t(this)}m(){var s=new _j;Up(s,"image_in"),Up(s,"norm_rect"),sh(s,"hand_gestures"),sh(s,"hand_landmarks"),sh(s,"world_hand_landmarks"),sh(s,"handedness");const t=new bj;d4(t,KCn,this.j);const n=new U_;dj(n,2,"mediapipe.tasks.vision.gesture_recognizer.GestureRecognizerGraph"),lp(n,"IMAGE:image_in"),lp(n,"NORM_RECT:norm_rect"),mu(n,"HAND_GESTURES:hand_gestures"),mu(n,"LANDMARKS:hand_landmarks"),mu(n,"WORLD_LANDMARKS:world_hand_landmarks"),mu(n,"HANDEDNESS:handedness"),n.o(t),Y2(s,n),this.g.attachProtoVectorListener("hand_landmarks",(r,a)=>{for(const i of r){r=hte(i);const l=[];for(const o of Y3(r,_zt,1))l.push({x:Gg(o,1)??0,y:Gg(o,2)??0,z:Gg(o,3)??0,visibility:Gg(o,4)??0});this.landmarks.push(l)}Co(this,a)}),this.g.attachEmptyPacketListener("hand_landmarks",r=>{Co(this,r)}),this.g.attachProtoVectorListener("world_hand_landmarks",(r,a)=>{for(const i of r){r=RB(i);const l=[];for(const o of Y3(r,bzt,1))l.push({x:Gg(o,1)??0,y:Gg(o,2)??0,z:Gg(o,3)??0,visibility:Gg(o,4)??0});this.worldLandmarks.push(l)}Co(this,a)}),this.g.attachEmptyPacketListener("world_hand_landmarks",r=>{Co(this,r)}),this.g.attachProtoVectorListener("hand_gestures",(r,a)=>{this.gestures.push(...H0t(r,!1)),Co(this,a)}),this.g.attachEmptyPacketListener("hand_gestures",r=>{Co(this,r)}),this.g.attachProtoVectorListener("handedness",(r,a)=>{this.handedness.push(...H0t(r)),Co(this,a)}),this.g.attachEmptyPacketListener("handedness",r=>{Co(this,r)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};function G0t(s){return{landmarks:s.landmarks,worldLandmarks:s.worldLandmarks,handednesses:s.handedness,handedness:s.handedness}}cw.prototype.recognizeForVideo=cw.prototype.Ia,cw.prototype.recognize=cw.prototype.Ha,cw.prototype.setOptions=cw.prototype.o,cw.createFromModelPath=function(s,t){return Cu(cw,s,{baseOptions:{modelAssetPath:t}})},cw.createFromModelBuffer=function(s,t){return Cu(cw,s,{baseOptions:{modelAssetBuffer:t}})},cw.createFromOptions=function(s,t){return Cu(cw,s,t)},cw.HAND_CONNECTIONS=OXe;var dw=class extends uj{constructor(s,t){super(new Ik(s,t),"image_in","norm_rect",!1),this.landmarks=[],this.worldLandmarks=[],this.handedness=[],El(s=this.h=new NXe,0,1,t=new Cg),this.u=new jXe,El(this.h,0,3,this.u),this.j=new Ezt,El(this.h,0,2,this.j),Z3(this.j,3,1),dl(this.j,2,.5),dl(this.u,2,.5),dl(this.h,4,.5)}get baseOptions(){return Uu(this.h,Cg,1)}set baseOptions(s){El(this.h,0,1,s)}o(s){return"numHands"in s&&Z3(this.j,3,s.numHands??1),"minHandDetectionConfidence"in s&&dl(this.j,2,s.minHandDetectionConfidence??.5),"minTrackingConfidence"in s&&dl(this.h,4,s.minTrackingConfidence??.5),"minHandPresenceConfidence"in s&&dl(this.u,2,s.minHandPresenceConfidence??.5),this.l(s)}F(s,t){return this.landmarks=[],this.worldLandmarks=[],this.handedness=[],Lk(this,s,t),G0t(this)}G(s,t,n){return this.landmarks=[],this.worldLandmarks=[],this.handedness=[],h4(this,s,n,t),G0t(this)}m(){var s=new _j;Up(s,"image_in"),Up(s,"norm_rect"),sh(s,"hand_landmarks"),sh(s,"world_hand_landmarks"),sh(s,"handedness");const t=new bj;d4(t,YCn,this.h);const n=new U_;dj(n,2,"mediapipe.tasks.vision.hand_landmarker.HandLandmarkerGraph"),lp(n,"IMAGE:image_in"),lp(n,"NORM_RECT:norm_rect"),mu(n,"LANDMARKS:hand_landmarks"),mu(n,"WORLD_LANDMARKS:world_hand_landmarks"),mu(n,"HANDEDNESS:handedness"),n.o(t),Y2(s,n),this.g.attachProtoVectorListener("hand_landmarks",(r,a)=>{for(const i of r)r=hte(i),this.landmarks.push(ATe(r));Co(this,a)}),this.g.attachEmptyPacketListener("hand_landmarks",r=>{Co(this,r)}),this.g.attachProtoVectorListener("world_hand_landmarks",(r,a)=>{for(const i of r)r=RB(i),this.worldLandmarks.push(sZ(r));Co(this,a)}),this.g.attachEmptyPacketListener("world_hand_landmarks",r=>{Co(this,r)}),this.g.attachProtoVectorListener("handedness",(r,a)=>{var i=this.handedness,l=i.push;const o=[];for(const c of r){r=STe(c);const d=[];for(const u of r.g())d.push({score:Gg(u,2)??0,index:p2(u,1)??0??-1,categoryName:mv(Rp(u,3))??""??"",displayName:mv(Rp(u,4))??""??""});o.push(d)}l.call(i,...o),Co(this,a)}),this.g.attachEmptyPacketListener("handedness",r=>{Co(this,r)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};dw.prototype.detectForVideo=dw.prototype.G,dw.prototype.detect=dw.prototype.F,dw.prototype.setOptions=dw.prototype.o,dw.createFromModelPath=function(s,t){return Cu(dw,s,{baseOptions:{modelAssetPath:t}})},dw.createFromModelBuffer=function(s,t){return Cu(dw,s,{baseOptions:{modelAssetBuffer:t}})},dw.createFromOptions=function(s,t){return Cu(dw,s,t)},dw.HAND_CONNECTIONS=OXe;var iBt=Pk([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 W0t(s){s.h={faceLandmarks:[],faceBlendshapes:[],poseLandmarks:[],poseWorldLandmarks:[],poseSegmentationMasks:[],leftHandLandmarks:[],leftHandWorldLandmarks:[],rightHandLandmarks:[],rightHandWorldLandmarks:[]}}function K0t(s){try{if(!s.D)return s.h;s.D(s.h)}finally{TTe(s)}}function Mae(s,t){s=hte(s),t.push(ATe(s))}var qf=class extends uj{constructor(s,t){super(new Ik(s,t),"input_frames_image",null,!1),this.h={faceLandmarks:[],faceBlendshapes:[],poseLandmarks:[],poseWorldLandmarks:[],poseSegmentationMasks:[],leftHandLandmarks:[],leftHandWorldLandmarks:[],rightHandLandmarks:[],rightHandWorldLandmarks:[]},this.outputPoseSegmentationMasks=this.outputFaceBlendshapes=!1,El(s=this.j=new Rzt,0,1,t=new Cg),this.I=new jXe,El(this.j,0,2,this.I),this.W=new ZCn,El(this.j,0,3,this.W),this.u=new CTe,El(this.j,0,4,this.u),this.O=new Szt,El(this.j,0,5,this.O),this.A=new Izt,El(this.j,0,6,this.A),this.M=new Lzt,El(this.j,0,7,this.M),dl(this.u,2,.5),dl(this.u,3,.3),dl(this.O,2,.5),dl(this.A,2,.5),dl(this.A,3,.3),dl(this.M,2,.5),dl(this.I,2,.5)}get baseOptions(){return Uu(this.j,Cg,1)}set baseOptions(s){El(this.j,0,1,s)}o(s){return"minFaceDetectionConfidence"in s&&dl(this.u,2,s.minFaceDetectionConfidence??.5),"minFaceSuppressionThreshold"in s&&dl(this.u,3,s.minFaceSuppressionThreshold??.3),"minFacePresenceConfidence"in s&&dl(this.O,2,s.minFacePresenceConfidence??.5),"outputFaceBlendshapes"in s&&(this.outputFaceBlendshapes=!!s.outputFaceBlendshapes),"minPoseDetectionConfidence"in s&&dl(this.A,2,s.minPoseDetectionConfidence??.5),"minPoseSuppressionThreshold"in s&&dl(this.A,3,s.minPoseSuppressionThreshold??.3),"minPosePresenceConfidence"in s&&dl(this.M,2,s.minPosePresenceConfidence??.5),"outputPoseSegmentationMasks"in s&&(this.outputPoseSegmentationMasks=!!s.outputPoseSegmentationMasks),"minHandLandmarksConfidence"in s&&dl(this.I,2,s.minHandLandmarksConfidence??.5),this.l(s)}F(s,t,n){const r=typeof t!="function"?t:{};return this.D=typeof t=="function"?t:n,W0t(this),Lk(this,s,r),K0t(this)}G(s,t,n,r){const a=typeof n!="function"?n:{};return this.D=typeof n=="function"?n:r,W0t(this),h4(this,s,a,t),K0t(this)}m(){var s=new _j;Up(s,"input_frames_image"),sh(s,"pose_landmarks"),sh(s,"pose_world_landmarks"),sh(s,"face_landmarks"),sh(s,"left_hand_landmarks"),sh(s,"left_hand_world_landmarks"),sh(s,"right_hand_landmarks"),sh(s,"right_hand_world_landmarks");const t=new bj,n=new y0t;dj(n,1,"type.googleapis.com/mediapipe.tasks.vision.holistic_landmarker.proto.HolisticLandmarkerGraphOptions"),function(a,i){if(i!=null)if(Array.isArray(i))Jh(a,2,fTe(i,0,dQ));else{if(!(typeof i=="string"||i instanceof $5||qZe(i)))throw Error("invalid value in Any.value field: "+i+" expected a ByteString, a base64 encoded string, a Uint8Array or a jspb array");_E(a,2,HZe(i,!1),QO())}}(n,this.j.g());const r=new U_;dj(r,2,"mediapipe.tasks.vision.holistic_landmarker.HolisticLandmarkerGraph"),aXe(r,8,y0t,n),lp(r,"IMAGE:input_frames_image"),mu(r,"POSE_LANDMARKS:pose_landmarks"),mu(r,"POSE_WORLD_LANDMARKS:pose_world_landmarks"),mu(r,"FACE_LANDMARKS:face_landmarks"),mu(r,"LEFT_HAND_LANDMARKS:left_hand_landmarks"),mu(r,"LEFT_HAND_WORLD_LANDMARKS:left_hand_world_landmarks"),mu(r,"RIGHT_HAND_LANDMARKS:right_hand_landmarks"),mu(r,"RIGHT_HAND_WORLD_LANDMARKS:right_hand_world_landmarks"),r.o(t),Y2(s,r),ETe(this,s),this.g.attachProtoListener("pose_landmarks",(a,i)=>{Mae(a,this.h.poseLandmarks),Co(this,i)}),this.g.attachEmptyPacketListener("pose_landmarks",a=>{Co(this,a)}),this.g.attachProtoListener("pose_world_landmarks",(a,i)=>{var l=this.h.poseWorldLandmarks;a=RB(a),l.push(sZ(a)),Co(this,i)}),this.g.attachEmptyPacketListener("pose_world_landmarks",a=>{Co(this,a)}),this.outputPoseSegmentationMasks&&(mu(r,"POSE_SEGMENTATION_MASK:pose_segmentation_mask"),pq(this,"pose_segmentation_mask"),this.g.Z("pose_segmentation_mask",(a,i)=>{this.h.poseSegmentationMasks=[xq(this,a,!0,!this.D)],Co(this,i)}),this.g.attachEmptyPacketListener("pose_segmentation_mask",a=>{this.h.poseSegmentationMasks=[],Co(this,a)})),this.g.attachProtoListener("face_landmarks",(a,i)=>{Mae(a,this.h.faceLandmarks),Co(this,i)}),this.g.attachEmptyPacketListener("face_landmarks",a=>{Co(this,a)}),this.outputFaceBlendshapes&&(sh(s,"extra_blendshapes"),mu(r,"FACE_BLENDSHAPES:extra_blendshapes"),this.g.attachProtoListener("extra_blendshapes",(a,i)=>{var l=this.h.faceBlendshapes;this.outputFaceBlendshapes&&(a=STe(a),l.push(AXe(a.g()??[]))),Co(this,i)}),this.g.attachEmptyPacketListener("extra_blendshapes",a=>{Co(this,a)})),this.g.attachProtoListener("left_hand_landmarks",(a,i)=>{Mae(a,this.h.leftHandLandmarks),Co(this,i)}),this.g.attachEmptyPacketListener("left_hand_landmarks",a=>{Co(this,a)}),this.g.attachProtoListener("left_hand_world_landmarks",(a,i)=>{var l=this.h.leftHandWorldLandmarks;a=RB(a),l.push(sZ(a)),Co(this,i)}),this.g.attachEmptyPacketListener("left_hand_world_landmarks",a=>{Co(this,a)}),this.g.attachProtoListener("right_hand_landmarks",(a,i)=>{Mae(a,this.h.rightHandLandmarks),Co(this,i)}),this.g.attachEmptyPacketListener("right_hand_landmarks",a=>{Co(this,a)}),this.g.attachProtoListener("right_hand_world_landmarks",(a,i)=>{var l=this.h.rightHandWorldLandmarks;a=RB(a),l.push(sZ(a)),Co(this,i)}),this.g.attachEmptyPacketListener("right_hand_world_landmarks",a=>{Co(this,a)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};qf.prototype.detectForVideo=qf.prototype.G,qf.prototype.detect=qf.prototype.F,qf.prototype.setOptions=qf.prototype.o,qf.createFromModelPath=function(s,t){return Cu(qf,s,{baseOptions:{modelAssetPath:t}})},qf.createFromModelBuffer=function(s,t){return Cu(qf,s,{baseOptions:{modelAssetBuffer:t}})},qf.createFromOptions=function(s,t){return Cu(qf,s,t)},qf.HAND_CONNECTIONS=OXe,qf.POSE_CONNECTIONS=iBt,qf.FACE_LANDMARKS_LIPS=MXe,qf.FACE_LANDMARKS_LEFT_EYE=PXe,qf.FACE_LANDMARKS_LEFT_EYEBROW=IXe,qf.FACE_LANDMARKS_LEFT_IRIS=sBt,qf.FACE_LANDMARKS_RIGHT_EYE=LXe,qf.FACE_LANDMARKS_RIGHT_EYEBROW=RXe,qf.FACE_LANDMARKS_RIGHT_IRIS=nBt,qf.FACE_LANDMARKS_FACE_OVAL=DXe,qf.FACE_LANDMARKS_CONTOURS=rBt,qf.FACE_LANDMARKS_TESSELATION=aBt;var Fj=class extends uj{constructor(s,t){super(new Ik(s,t),"input_image","norm_rect",!0),this.j={classifications:[]},El(s=this.h=new Dzt,0,1,t=new Cg)}get baseOptions(){return Uu(this.h,Cg,1)}set baseOptions(s){El(this.h,0,1,s)}o(s){return El(this.h,0,2,o$e(s,Uu(this.h,_Xe,2))),this.l(s)}sa(s,t){return this.j={classifications:[]},Lk(this,s,t),this.j}ta(s,t,n){return this.j={classifications:[]},h4(this,s,n,t),this.j}m(){var s=new _j;Up(s,"input_image"),Up(s,"norm_rect"),sh(s,"classifications");const t=new bj;d4(t,XCn,this.h);const n=new U_;dj(n,2,"mediapipe.tasks.vision.image_classifier.ImageClassifierGraph"),lp(n,"IMAGE:input_image"),lp(n,"NORM_RECT:norm_rect"),mu(n,"CLASSIFICATIONS:classifications"),n.o(t),Y2(s,n),this.g.attachProtoListener("classifications",(r,a)=>{this.j=n3n(zCn(r)),Co(this,a)}),this.g.attachEmptyPacketListener("classifications",r=>{Co(this,r)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};Fj.prototype.classifyForVideo=Fj.prototype.ta,Fj.prototype.classify=Fj.prototype.sa,Fj.prototype.setOptions=Fj.prototype.o,Fj.createFromModelPath=function(s,t){return Cu(Fj,s,{baseOptions:{modelAssetPath:t}})},Fj.createFromModelBuffer=function(s,t){return Cu(Fj,s,{baseOptions:{modelAssetBuffer:t}})},Fj.createFromOptions=function(s,t){return Cu(Fj,s,t)};var uw=class extends uj{constructor(s,t){super(new Ik(s,t),"image_in","norm_rect",!0),this.h=new Ozt,this.embeddings={embeddings:[]},El(s=this.h,0,1,t=new Cg)}get baseOptions(){return Uu(this.h,Cg,1)}set baseOptions(s){El(this.h,0,1,s)}o(s){var t=this.h,n=Uu(this.h,C0t,2);return n=n?n.clone():new C0t,s.l2Normalize!==void 0?Jh(n,1,cQ(s.l2Normalize)):"l2Normalize"in s&&Jh(n,1),s.quantize!==void 0?Jh(n,2,cQ(s.quantize)):"quantize"in s&&Jh(n,2),El(t,0,2,n),this.l(s)}za(s,t){return Lk(this,s,t),this.embeddings}Aa(s,t,n){return h4(this,s,n,t),this.embeddings}m(){var s=new _j;Up(s,"image_in"),Up(s,"norm_rect"),sh(s,"embeddings_out");const t=new bj;d4(t,QCn,this.h);const n=new U_;dj(n,2,"mediapipe.tasks.vision.image_embedder.ImageEmbedderGraph"),lp(n,"IMAGE:image_in"),lp(n,"NORM_RECT:norm_rect"),mu(n,"EMBEDDINGS:embeddings_out"),n.o(t),Y2(s,n),this.g.attachProtoListener("embeddings_out",(r,a)=>{r=UCn(r),this.embeddings=function(i){return{embeddings:Y3(i,$Cn,1).map(l=>{var d,u;const o={headIndex:p2(l,3)??0??-1,headName:mv(Rp(l,4))??""??""};var c=l.v;return L9t(c,0|c[Xo],S0t,iDe(l,1))!==void 0?(l=vD(l=Uu(l,S0t,iDe(l,1),void 0),1,x5,yD()),o.floatEmbedding=l.slice()):(c=new Uint8Array(0),o.quantizedEmbedding=((u=(d=Uu(l,BCn,iDe(l,2),void 0))==null?void 0:d.na())==null?void 0:u.h())??c),o}),timestampMs:Vzt(Rp(i,2,void 0,void 0,P4e)??E9t)}}(r),Co(this,a)}),this.g.attachEmptyPacketListener("embeddings_out",r=>{Co(this,r)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};uw.cosineSimilarity=function(s,t){if(s.floatEmbedding&&t.floatEmbedding)s=I0t(s.floatEmbedding,t.floatEmbedding);else{if(!s.quantizedEmbedding||!t.quantizedEmbedding)throw Error("Cannot compute cosine similarity between quantized and float embeddings.");s=I0t(P0t(s.quantizedEmbedding),P0t(t.quantizedEmbedding))}return s},uw.prototype.embedForVideo=uw.prototype.Aa,uw.prototype.embed=uw.prototype.za,uw.prototype.setOptions=uw.prototype.o,uw.createFromModelPath=function(s,t){return Cu(uw,s,{baseOptions:{modelAssetPath:t}})},uw.createFromModelBuffer=function(s,t){return Cu(uw,s,{baseOptions:{modelAssetBuffer:t}})},uw.createFromOptions=function(s,t){return Cu(uw,s,t)};var u$e=class{constructor(s,t,n){this.confidenceMasks=s,this.categoryMask=t,this.qualityScores=n}close(){var s,t;(s=this.confidenceMasks)==null||s.forEach(n=>{n.close()}),(t=this.categoryMask)==null||t.close()}};function d3n(s){var n,r;const t=function(a){return Y3(a,U_,1)}(s.ca()).filter(a=>(mv(Rp(a,1))??"").includes("mediapipe.tasks.TensorsToSegmentationCalculator"));if(s.u=[],t.length>1)throw Error("The graph has more than one mediapipe.tasks.TensorsToSegmentationCalculator.");t.length===1&&(((r=(n=Uu(t[0],bj,7))==null?void 0:n.j())==null?void 0:r.g())??new Map).forEach((a,i)=>{s.u[Number(i)]=mv(Rp(a,1))??""})}function Y0t(s){s.categoryMask=void 0,s.confidenceMasks=void 0,s.qualityScores=void 0}function Z0t(s){try{const t=new u$e(s.confidenceMasks,s.categoryMask,s.qualityScores);if(!s.j)return t;s.j(t)}finally{TTe(s)}}u$e.prototype.close=u$e.prototype.close;var W1=class extends uj{constructor(s,t){super(new Ik(s,t),"image_in","norm_rect",!1),this.u=[],this.outputCategoryMask=!1,this.outputConfidenceMasks=!0,this.h=new CXe,this.A=new Fzt,El(this.h,0,3,this.A),El(s=this.h,0,1,t=new Cg)}get baseOptions(){return Uu(this.h,Cg,1)}set baseOptions(s){El(this.h,0,1,s)}o(s){return s.displayNamesLocale!==void 0?Jh(this.h,2,cte(s.displayNamesLocale)):"displayNamesLocale"in s&&Jh(this.h,2),"outputCategoryMask"in s&&(this.outputCategoryMask=s.outputCategoryMask??!1),"outputConfidenceMasks"in s&&(this.outputConfidenceMasks=s.outputConfidenceMasks??!0),super.l(s)}L(){d3n(this)}segment(s,t,n){const r=typeof t!="function"?t:{};return this.j=typeof t=="function"?t:n,Y0t(this),Lk(this,s,r),Z0t(this)}La(s,t,n,r){const a=typeof n!="function"?n:{};return this.j=typeof n=="function"?n:r,Y0t(this),h4(this,s,a,t),Z0t(this)}Da(){return this.u}m(){var s=new _j;Up(s,"image_in"),Up(s,"norm_rect");const t=new bj;d4(t,Bzt,this.h);const n=new U_;dj(n,2,"mediapipe.tasks.vision.image_segmenter.ImageSegmenterGraph"),lp(n,"IMAGE:image_in"),lp(n,"NORM_RECT:norm_rect"),n.o(t),Y2(s,n),ETe(this,s),this.outputConfidenceMasks&&(sh(s,"confidence_masks"),mu(n,"CONFIDENCE_MASKS:confidence_masks"),pq(this,"confidence_masks"),this.g.aa("confidence_masks",(r,a)=>{this.confidenceMasks=r.map(i=>xq(this,i,!0,!this.j)),Co(this,a)}),this.g.attachEmptyPacketListener("confidence_masks",r=>{this.confidenceMasks=[],Co(this,r)})),this.outputCategoryMask&&(sh(s,"category_mask"),mu(n,"CATEGORY_MASK:category_mask"),pq(this,"category_mask"),this.g.Z("category_mask",(r,a)=>{this.categoryMask=xq(this,r,!1,!this.j),Co(this,a)}),this.g.attachEmptyPacketListener("category_mask",r=>{this.categoryMask=void 0,Co(this,r)})),sh(s,"quality_scores"),mu(n,"QUALITY_SCORES:quality_scores"),this.g.attachFloatVectorListener("quality_scores",(r,a)=>{this.qualityScores=r,Co(this,a)}),this.g.attachEmptyPacketListener("quality_scores",r=>{this.categoryMask=void 0,Co(this,r)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};W1.prototype.getLabels=W1.prototype.Da,W1.prototype.segmentForVideo=W1.prototype.La,W1.prototype.segment=W1.prototype.segment,W1.prototype.setOptions=W1.prototype.o,W1.createFromModelPath=function(s,t){return Cu(W1,s,{baseOptions:{modelAssetPath:t}})},W1.createFromModelBuffer=function(s,t){return Cu(W1,s,{baseOptions:{modelAssetBuffer:t}})},W1.createFromOptions=function(s,t){return Cu(W1,s,t)};var h$e=class{constructor(s,t,n){this.confidenceMasks=s,this.categoryMask=t,this.qualityScores=n}close(){var s,t;(s=this.confidenceMasks)==null||s.forEach(n=>{n.close()}),(t=this.categoryMask)==null||t.close()}};h$e.prototype.close=h$e.prototype.close;var hS=class extends uj{constructor(s,t){super(new Ik(s,t),"image_in","norm_rect_in",!1),this.outputCategoryMask=!1,this.outputConfidenceMasks=!0,this.h=new CXe,this.u=new Fzt,El(this.h,0,3,this.u),El(s=this.h,0,1,t=new Cg)}get baseOptions(){return Uu(this.h,Cg,1)}set baseOptions(s){El(this.h,0,1,s)}o(s){return"outputCategoryMask"in s&&(this.outputCategoryMask=s.outputCategoryMask??!1),"outputConfidenceMasks"in s&&(this.outputConfidenceMasks=s.outputConfidenceMasks??!0),super.l(s)}segment(s,t,n,r){const a=typeof n!="function"?n:{};if(this.j=typeof n=="function"?n:r,this.qualityScores=this.categoryMask=this.confidenceMasks=void 0,n=this.C+1,r=new $zt,t.keypoint&&t.scribble)throw Error("Cannot provide both keypoint and scribble.");if(t.keypoint){var i=new dDe;_E(i,3,cQ(!0),!1),_E(i,1,FW(t.keypoint.x),0),_E(i,2,FW(t.keypoint.y),0),eZ(r,1,i$e,i)}else{if(!t.scribble)throw Error("Must provide either a keypoint or a scribble.");{const o=new e3n;for(i of t.scribble)_E(t=new dDe,3,cQ(!0),!1),_E(t,1,FW(i.x),0),_E(t,2,FW(i.y),0),aXe(o,1,dDe,t);eZ(r,2,i$e,o)}}this.g.addProtoToStream(r.g(),"mediapipe.tasks.vision.interactive_segmenter.proto.RegionOfInterest","roi_in",n),Lk(this,s,a);e:{try{const o=new h$e(this.confidenceMasks,this.categoryMask,this.qualityScores);if(!this.j){var l=o;break e}this.j(o)}finally{TTe(this)}l=void 0}return l}m(){var s=new _j;Up(s,"image_in"),Up(s,"roi_in"),Up(s,"norm_rect_in");const t=new bj;d4(t,Bzt,this.h);const n=new U_;dj(n,2,"mediapipe.tasks.vision.interactive_segmenter.InteractiveSegmenterGraphV2"),lp(n,"IMAGE:image_in"),lp(n,"ROI:roi_in"),lp(n,"NORM_RECT:norm_rect_in"),n.o(t),Y2(s,n),ETe(this,s),this.outputConfidenceMasks&&(sh(s,"confidence_masks"),mu(n,"CONFIDENCE_MASKS:confidence_masks"),pq(this,"confidence_masks"),this.g.aa("confidence_masks",(r,a)=>{this.confidenceMasks=r.map(i=>xq(this,i,!0,!this.j)),Co(this,a)}),this.g.attachEmptyPacketListener("confidence_masks",r=>{this.confidenceMasks=[],Co(this,r)})),this.outputCategoryMask&&(sh(s,"category_mask"),mu(n,"CATEGORY_MASK:category_mask"),pq(this,"category_mask"),this.g.Z("category_mask",(r,a)=>{this.categoryMask=xq(this,r,!1,!this.j),Co(this,a)}),this.g.attachEmptyPacketListener("category_mask",r=>{this.categoryMask=void 0,Co(this,r)})),sh(s,"quality_scores"),mu(n,"QUALITY_SCORES:quality_scores"),this.g.attachFloatVectorListener("quality_scores",(r,a)=>{this.qualityScores=r,Co(this,a)}),this.g.attachEmptyPacketListener("quality_scores",r=>{this.categoryMask=void 0,Co(this,r)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};hS.prototype.segment=hS.prototype.segment,hS.prototype.setOptions=hS.prototype.o,hS.createFromModelPath=function(s,t){return Cu(hS,s,{baseOptions:{modelAssetPath:t}})},hS.createFromModelBuffer=function(s,t){return Cu(hS,s,{baseOptions:{modelAssetBuffer:t}})},hS.createFromOptions=function(s,t){return Cu(hS,s,t)};var zj=class extends uj{constructor(s,t){super(new Ik(s,t),"input_frame_gpu","norm_rect",!1),this.j={detections:[]},El(s=this.h=new Uzt,0,1,t=new Cg)}get baseOptions(){return Uu(this.h,Cg,1)}set baseOptions(s){El(this.h,0,1,s)}o(s){return s.displayNamesLocale!==void 0?Jh(this.h,2,cte(s.displayNamesLocale)):"displayNamesLocale"in s&&Jh(this.h,2),s.maxResults!==void 0?Z3(this.h,3,s.maxResults):"maxResults"in s&&Jh(this.h,3),s.scoreThreshold!==void 0?dl(this.h,4,s.scoreThreshold):"scoreThreshold"in s&&Jh(this.h,4),s.categoryAllowlist!==void 0?L4e(this.h,5,s.categoryAllowlist):"categoryAllowlist"in s&&Jh(this.h,5),s.categoryDenylist!==void 0?L4e(this.h,6,s.categoryDenylist):"categoryDenylist"in s&&Jh(this.h,6),this.l(s)}F(s,t){return this.j={detections:[]},Lk(this,s,t),this.j}G(s,t,n){return this.j={detections:[]},h4(this,s,n,t),this.j}m(){var s=new _j;Up(s,"input_frame_gpu"),Up(s,"norm_rect"),sh(s,"detections");const t=new bj;d4(t,t3n,this.h);const n=new U_;dj(n,2,"mediapipe.tasks.vision.ObjectDetectorGraph"),lp(n,"IMAGE:input_frame_gpu"),lp(n,"NORM_RECT:norm_rect"),mu(n,"DETECTIONS:detections"),n.o(t),Y2(s,n),this.g.attachProtoVectorListener("detections",(r,a)=>{for(const i of r)r=vzt(i),this.j.detections.push(Hzt(r));Co(this,a)}),this.g.attachEmptyPacketListener("detections",r=>{Co(this,r)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};zj.prototype.detectForVideo=zj.prototype.G,zj.prototype.detect=zj.prototype.F,zj.prototype.setOptions=zj.prototype.o,zj.createFromModelPath=async function(s,t){return Cu(zj,s,{baseOptions:{modelAssetPath:t}})},zj.createFromModelBuffer=function(s,t){return Cu(zj,s,{baseOptions:{modelAssetBuffer:t}})},zj.createFromOptions=function(s,t){return Cu(zj,s,t)};var m$e=class{constructor(s,t,n){this.landmarks=s,this.worldLandmarks=t,this.segmentationMasks=n}close(){var s;(s=this.segmentationMasks)==null||s.forEach(t=>{t.close()})}};function X0t(s){s.landmarks=[],s.worldLandmarks=[],s.segmentationMasks=void 0}function Q0t(s){try{const t=new m$e(s.landmarks,s.worldLandmarks,s.segmentationMasks);if(!s.u)return t;s.u(t)}finally{TTe(s)}}m$e.prototype.close=m$e.prototype.close;var hw=class extends uj{constructor(s,t){super(new Ik(s,t),"image_in","norm_rect",!1),this.landmarks=[],this.worldLandmarks=[],this.outputSegmentationMasks=!1,El(s=this.h=new qzt,0,1,t=new Cg),this.A=new Lzt,El(this.h,0,3,this.A),this.j=new Izt,El(this.h,0,2,this.j),Z3(this.j,4,1),dl(this.j,2,.5),dl(this.A,2,.5),dl(this.h,4,.5)}get baseOptions(){return Uu(this.h,Cg,1)}set baseOptions(s){El(this.h,0,1,s)}o(s){return"numPoses"in s&&Z3(this.j,4,s.numPoses??1),"minPoseDetectionConfidence"in s&&dl(this.j,2,s.minPoseDetectionConfidence??.5),"minTrackingConfidence"in s&&dl(this.h,4,s.minTrackingConfidence??.5),"minPosePresenceConfidence"in s&&dl(this.A,2,s.minPosePresenceConfidence??.5),"outputSegmentationMasks"in s&&(this.outputSegmentationMasks=s.outputSegmentationMasks??!1),this.l(s)}F(s,t,n){const r=typeof t!="function"?t:{};return this.u=typeof t=="function"?t:n,X0t(this),Lk(this,s,r),Q0t(this)}G(s,t,n,r){const a=typeof n!="function"?n:{};return this.u=typeof n=="function"?n:r,X0t(this),h4(this,s,a,t),Q0t(this)}m(){var s=new _j;Up(s,"image_in"),Up(s,"norm_rect"),sh(s,"normalized_landmarks"),sh(s,"world_landmarks"),sh(s,"segmentation_masks");const t=new bj;d4(t,s3n,this.h);const n=new U_;dj(n,2,"mediapipe.tasks.vision.pose_landmarker.PoseLandmarkerGraph"),lp(n,"IMAGE:image_in"),lp(n,"NORM_RECT:norm_rect"),mu(n,"NORM_LANDMARKS:normalized_landmarks"),mu(n,"WORLD_LANDMARKS:world_landmarks"),n.o(t),Y2(s,n),ETe(this,s),this.g.attachProtoVectorListener("normalized_landmarks",(r,a)=>{this.landmarks=[];for(const i of r)r=hte(i),this.landmarks.push(ATe(r));Co(this,a)}),this.g.attachEmptyPacketListener("normalized_landmarks",r=>{this.landmarks=[],Co(this,r)}),this.g.attachProtoVectorListener("world_landmarks",(r,a)=>{this.worldLandmarks=[];for(const i of r)r=RB(i),this.worldLandmarks.push(sZ(r));Co(this,a)}),this.g.attachEmptyPacketListener("world_landmarks",r=>{this.worldLandmarks=[],Co(this,r)}),this.outputSegmentationMasks&&(mu(n,"SEGMENTATION_MASK:segmentation_masks"),pq(this,"segmentation_masks"),this.g.aa("segmentation_masks",(r,a)=>{this.segmentationMasks=r.map(i=>xq(this,i,!0,!this.u)),Co(this,a)}),this.g.attachEmptyPacketListener("segmentation_masks",r=>{this.segmentationMasks=[],Co(this,r)})),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};hw.prototype.detectForVideo=hw.prototype.G,hw.prototype.detect=hw.prototype.F,hw.prototype.setOptions=hw.prototype.o,hw.createFromModelPath=function(s,t){return Cu(hw,s,{baseOptions:{modelAssetPath:t}})},hw.createFromModelBuffer=function(s,t){return Cu(hw,s,{baseOptions:{modelAssetBuffer:t}})},hw.createFromOptions=function(s,t){return Cu(hw,s,t)},hw.POSE_CONNECTIONS=iBt;let bD=null,zW=null;async function u3n(){return bD||zW||(zW=(async()=>{const s=await z9.forVisionTasks("https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@latest/wasm");return bD=await W1.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}),bD})(),zW)}function h3n(s,t,n,r,a){const i=new Float32Array(s.length);for(let l=0;l=0&&(o-=s[c+u]);const m=Math.min(h,n-1)-Math.max(u+1,0)+1;i[c+d]=o/m}}for(let l=0;l=0&&(o-=i[d*n+l]);const h=Math.min(u,r-1)-Math.max(d+1,0)+1;t[c*n+l]=o/h}}}function m3n(){bD&&(bD.close(),bD=null,zW=null)}function f3n(s,t){const n=k.useRef(null),r=k.useRef(null),a=k.useRef(null),i=k.useRef(null),l=k.useRef(0);k.useRef(0);const[o,c]=k.useState(null),[d,u]=k.useState(!1),[h,m]=k.useState(null),p=t.type!=="none"&&s!==null;return k.useEffect(()=>{if(t.type==="image"&&t.imageUrl){const g=new Image;g.crossOrigin="anonymous",g.src=t.imageUrl,g.onload=()=>{i.current=g}}else i.current=null},[t.type,t.imageUrl]),k.useEffect(()=>{if(!p||!s){a.current&&(a.current.srcObject=null,a.current=null);return}const g=document.createElement("video");return g.srcObject=s,g.muted=!0,g.playsInline=!0,g.autoplay=!0,g.play().catch(()=>{}),a.current=g,()=>{g.srcObject=null,a.current=null}},[p,s]),k.useEffect(()=>{if(!p){c(null),m(null);return}let g=!1;return(async()=>{u(!0),m(null);try{const y=await u3n();if(g)return;u(!1);const v=a.current;if(!v||(await new Promise(Se=>{if(v.videoWidth>0)return Se();v.onloadedmetadata=()=>Se(),setTimeout(Se,2e3)}),g))return;const _=v.videoWidth||640,j=v.videoHeight||480,C=n.current;if(!C)return;C.width=_,C.height=j;const A=C.getContext("2d",{willReadFrequently:!1,alpha:!1});r.current||(r.current=document.createElement("canvas"));const M=r.current;M.width=_,M.height=j;const I=M.getContext("2d",{willReadFrequently:!1}),P=document.createElement("canvas");P.width=_,P.height=j;const R=P.getContext("2d",{alpha:!1}),O=document.createElement("canvas");O.width=_,O.height=j;const B=O.getContext("2d",{willReadFrequently:!1}),U=B.createImageData(_,j),G=U.data;for(let Se=0;SeH.addTrack(Se)),g||c(H);const se=t.blurRadius??15,ee=t.mirror??!1,oe=new Float32Array(_*j),me=new Float32Array(_*j),Q=new Float32Array(_*j);let te=!1;const le=4,fe=.35,_e=typeof v.requestVideoFrameCallback=="function",ve=()=>{if(g||!a.current)return;const Se=a.current;if(Se.readyState<2){he(Se);return}try{const Te=performance.now(),Ue=y.segmentForVideo(Se,Te).confidenceMasks;if(Ue&&Ue.length>0){me.fill(0);for(let Be=1;Be1?1:Re}}if(h3n(me,oe,_,j,le),te)for(let Be=0;Be=1?255:Ye*255|0}if(B.putImageData(U,0,0),t.type==="blur")R.filter=`blur(${se}px)`,R.drawImage(Se,0,0,_,j),R.filter="none",A.drawImage(P,0,0);else if(t.type==="image"&&i.current){const Be=i.current,je=Be.width/Be.height,Ye=_/j;let Ee=0,Re=0,ke=Be.width,Fe=Be.height;je>Ye?(ke=Be.height*Ye,Ee=(Be.width-ke)/2):(Fe=Be.width/Ye,Re=(Be.height-Fe)/2),A.drawImage(Be,Ee,Re,ke,Fe,0,0,_,j)}else A.fillStyle="#000",A.fillRect(0,0,_,j);I.globalCompositeOperation="source-over",I.clearRect(0,0,_,j),I.drawImage(Se,0,0,_,j),I.globalCompositeOperation="destination-in",I.drawImage(O,0,0),I.globalCompositeOperation="source-over",ee?(A.save(),A.translate(_,0),A.scale(-1,1),A.drawImage(M,0,0),A.restore()):A.drawImage(M,0,0);for(const Be of Ue)Be.close()}else A.drawImage(Se,0,0,_,j)}catch{A.drawImage(Se,0,0,_,j)}he(Se)},he=Se=>{g||(_e?Se.requestVideoFrameCallback(()=>ve()):l.current=requestAnimationFrame(ve))};he(v)}catch(y){console.error("[useVirtualBackground] init error:",y),g||(u(!1),m(y.message||"Failed to initialize virtual background"))}})(),()=>{g=!0,l.current&&cancelAnimationFrame(l.current),c(null)}},[p,t.type,t.blurRadius,t.imageUrl,s]),k.useEffect(()=>()=>{m3n()},[]),{canvasRef:n,compositedStream:o,isLoading:d,isActive:p,error:h}}function w6({maxDurationSeconds:s=600,onRecordingComplete:t,onError:n,onRecordingStateChange:r,className:a,teleprompterContent:i}){const l=k.useRef(null),o=k.useRef(null),c=k.useRef(null),[d,u]=k.useState(null),h=k.useRef([]),m=k.useRef(null),p=k.useRef(null),g=k.useRef(null),x=k.useRef(null),y=AV(),[v,_]=k.useState("camera"),j=k.useRef(null),C=k.useRef(null),A=k.useRef(null),M=k.useRef(null),I=k.useRef(null),P=k.useRef(null),[R,O]=k.useState(!0),[B,U]=k.useState(!0),[G,H]=k.useState(null),[Y,se]=k.useState(!1),[ee,oe]=k.useState(!1),[me,Q]=k.useState(null),[te,le]=k.useState(null),[fe,_e]=k.useState(0),[ve,he]=k.useState("user"),[Se,Te]=k.useState(0),[Ie,Ue]=k.useState(!1),[Be,je]=k.useState(!0),[Ye,Ee]=k.useState(null),[Re,ke]=k.useState(!1),[Fe,Oe]=k.useState(null),Ge=k.useRef(null),[yt,tt]=k.useState(()=>{try{const xn=localStorage.getItem("video-bg-config");if(xn)return JSON.parse(xn)}catch{}return{type:"none"}});k.useEffect(()=>{try{localStorage.setItem("video-bg-config",JSON.stringify(yt))}catch{}},[yt]);const[ut,nt]=k.useState([]),[et,at]=k.useState([]),[wt,rt]=k.useState(()=>{try{return localStorage.getItem("video-mic-id")||""}catch{return""}}),[Ft,Ut]=k.useState(()=>{try{return localStorage.getItem("video-cam-id")||""}catch{return""}});k.useEffect(()=>{try{localStorage.setItem("video-mic-id",wt)}catch{}},[wt]),k.useEffect(()=>{try{localStorage.setItem("video-cam-id",Ft)}catch{}},[Ft]),k.useEffect(()=>{var Ar,Zr,dn;if(!((Ar=navigator.mediaDevices)!=null&&Ar.enumerateDevices))return;const xn=async()=>{try{const Kt=await navigator.mediaDevices.enumerateDevices();nt(Kt.filter(Er=>Er.kind==="audioinput")),at(Kt.filter(Er=>Er.kind==="videoinput"))}catch(Kt){console.warn("[VideoRecorder] enumerateDevices failed",Kt)}};return xn(),(dn=(Zr=navigator.mediaDevices).addEventListener)==null||dn.call(Zr,"devicechange",xn),()=>{var Kt,Er;return(Er=(Kt=navigator.mediaDevices).removeEventListener)==null?void 0:Er.call(Kt,"devicechange",xn)}},[G]);const{canvasRef:Is,compositedStream:xs,isLoading:st,isActive:dt}=f3n(d,yt),jt=k.useRef(n);jt.current=n;const gt=k.useCallback(xn=>{O(xn)},[]),rs=k.useRef(R),Ns=k.useCallback(()=>{A.current&&(cancelAnimationFrame(A.current),A.current=null),M.current&&(M.current.terminate(),M.current=null),j.current&&(j.current.getTracks().forEach(xn=>xn.stop()),j.current=null),I.current&&(I.current.getTracks().forEach(xn=>xn.stop()),I.current=null),P.current&&(P.current.srcObject=null,P.current=null)},[]),us=k.useCallback(async()=>{var xn;try{const Ar=await navigator.mediaDevices.getDisplayMedia({video:{width:{ideal:1920},height:{ideal:1080}},audio:!0});j.current=Ar;let Zr=null;try{Zr=await navigator.mediaDevices.getUserMedia({video:Ft?{deviceId:{exact:Ft},width:{ideal:320},height:{ideal:240}}:{width:{ideal:320},height:{ideal:240}},audio:!1})}catch{console.warn("[VideoRecorder] No webcam for PiP overlay")}let dn=null;try{dn=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0,...wt?{deviceId:{exact:wt}}:{}}}),console.log("[VideoRecorder] mic acquired for screen recording",dn.getAudioTracks().map(vl=>vl.label))}catch(vl){console.warn("[VideoRecorder] No mic audio for screen recording",vl);try{dn=await navigator.mediaDevices.getUserMedia({audio:!0})}catch{}}const Kt=Ar.getVideoTracks()[0],Er=Kt.getSettings(),ti=Er.width||1920,Ba=Er.height||1080,lo=document.createElement("canvas");lo.width=ti,lo.height=Ba,C.current=lo;const Yn=lo.getContext("2d");let Hr=null;Zr&&(Hr=document.createElement("video"),Hr.srcObject=Zr,Hr.muted=!0,Hr.playsInline=!0,Hr.autoplay=!0,await Hr.play(),P.current=Hr);const Ur=document.createElement("video");Ur.srcObject=Ar,Ur.muted=!0,Ur.playsInline=!0,Ur.autoplay=!0,await Ur.play();const Ei=()=>{if(Yn.drawImage(Ur,0,0,ti,Ba),Hr&&Hr.readyState>=2){const vl=Math.round(ti*.2),Ol=Math.round(vl*(Hr.videoHeight/Hr.videoWidth||.75)),To=ti-vl-20,_a=Ba-Ol-20,$o=12;Yn.save(),Yn.beginPath(),Yn.moveTo(To+$o,_a),Yn.lineTo(To+vl-$o,_a),Yn.quadraticCurveTo(To+vl,_a,To+vl,_a+$o),Yn.lineTo(To+vl,_a+Ol-$o),Yn.quadraticCurveTo(To+vl,_a+Ol,To+vl-$o,_a+Ol),Yn.lineTo(To+$o,_a+Ol),Yn.quadraticCurveTo(To,_a+Ol,To,_a+Ol-$o),Yn.lineTo(To,_a+$o),Yn.quadraticCurveTo(To,_a,To+$o,_a),Yn.closePath(),Yn.clip(),Yn.translate(To+vl,_a),Yn.scale(-1,1),Yn.drawImage(Hr,0,0,vl,Ol),Yn.restore(),Yn.strokeStyle="rgba(255,255,255,0.6)",Yn.lineWidth=2,Yn.beginPath(),Yn.moveTo(To+$o,_a),Yn.lineTo(To+vl-$o,_a),Yn.quadraticCurveTo(To+vl,_a,To+vl,_a+$o),Yn.lineTo(To+vl,_a+Ol-$o),Yn.quadraticCurveTo(To+vl,_a+Ol,To+vl-$o,_a+Ol),Yn.lineTo(To+$o,_a+Ol),Yn.quadraticCurveTo(To,_a+Ol,To,_a+Ol-$o),Yn.lineTo(To,_a+$o),Yn.quadraticCurveTo(To,_a,To+$o,_a),Yn.closePath(),Yn.stroke()}},fo="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}}",co=new Blob([fo],{type:"application/javascript"}),Tn=new Worker(URL.createObjectURL(co));M.current=Tn,Tn.onmessage=()=>Ei(),Tn.postMessage({type:"start",fps:30}),Ei();const Mr=lo.captureStream(30),Aa=[],Lo=Ar.getAudioTracks();Lo.length&&Aa.push(...Lo),dn&&Aa.push(...dn.getAudioTracks());const Ac=new MediaStream([...Mr.getVideoTracks(),...Aa]);return I.current=Ac,Kt.onended=()=>{o.current&&o.current.state!=="inactive"&&o.current.stop(),Ns()},Ac}catch(Ar){return console.error("[VideoRecorder] Screen capture error:",Ar),Ar.name!=="NotAllowedError"&&((xn=jt.current)==null||xn.call(jt,"Failed to start screen capture: "+(Ar.message||"Unknown error"))),null}},[Ns]),Bs=k.useCallback(async()=>{var Ar,Zr;U(!0),Ee(null);const xn=y&&R;console.log("[VideoRecorder] initCamera start",{isMobile:y,usePortraitMode:R,shouldBePortrait:xn,facingMode:ve});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(Yn=>Yn.stop()));const dn=y&&xn?{width:{ideal:720},height:{ideal:1280}}:{width:{ideal:1280},height:{ideal:720}},Kt=Ft?{...dn,deviceId:{exact:Ft}}:{...dn,facingMode:{ideal:ve}},Er={echoCancellation:!0,noiseSuppression:!0,...wt?{deviceId:{exact:wt}}:{}};console.log("[VideoRecorder] requesting getUserMedia",Kt);const ti=await navigator.mediaDevices.getUserMedia({video:Kt,audio:Er});if(console.log("[VideoRecorder] getUserMedia success"),ti.getVideoTracks().length===0)throw new Error("Camera stream started but no video track was provided.");c.current=ti,u(ti),H(!0);const lo=ti.getVideoTracks()[0].getSettings();if(console.log("[VideoRecorder] Camera initialized with dimensions:",lo.width,"x",lo.height),l.current){const Yn=l.current;Yn.srcObject=ti,Yn.muted=!0,Yn.playsInline=!0,Yn.autoplay=!0,Yn.setAttribute("muted",""),Yn.setAttribute("playsinline",""),Yn.setAttribute("autoplay","");try{(Ar=Yn.load)==null||Ar.call(Yn)}catch(Ur){console.warn("[VideoRecorder] videoEl.load failed",Ur)}const Hr=async()=>{try{return await Yn.play(),console.log("[VideoRecorder] preview play ok"),ke(!1),setTimeout(()=>{console.debug("[VideoRecorder] preview metrics",{readyState:Yn.readyState,videoWidth:Yn.videoWidth,videoHeight:Yn.videoHeight})},300),!0}catch(Ur){return console.warn("[VideoRecorder] preview play blocked",Ur),ke(!0),!1}};await new Promise(Ur=>{let Ei=!1;const fo=()=>{Ei||(Ei=!0,Ur())},co=()=>{Hr().finally(fo)};Yn.onloadedmetadata=co,Yn.onloadeddata=co,setTimeout(fo,1500)})}try{p.current=new AudioContext;const Yn=p.current.createMediaStreamSource(ti);g.current=p.current.createAnalyser(),g.current.fftSize=256,Yn.connect(g.current);const Hr=()=>{if(g.current){const Ur=new Uint8Array(g.current.frequencyBinCount);g.current.getByteFrequencyData(Ur);const Ei=Ur.reduce((fo,co)=>fo+co)/Ur.length;Te(Math.min(100,Ei/128*100))}x.current=requestAnimationFrame(Hr)};Hr()}catch(Yn){console.warn("Audio context not available:",Yn)}}catch(dn){console.error("Camera initialization error:",dn),H(!1);let Kt="Failed to access camera or microphone.";dn.name==="NotAllowedError"?Kt="Camera permission denied. Please allow camera access in your browser settings.":dn.name==="NotFoundError"?Kt="No camera found. Please connect a camera and try again.":dn.name==="NotReadableError"?Kt="Camera is in use by another application. Please close other apps using the camera.":dn.message&&(Kt=dn.message),Ee(Kt),(Zr=jt.current)==null||Zr.call(jt,Kt)}finally{U(!1)}},[ve,y,R,wt,Ft]);k.useEffect(()=>{rs.current!==R&&G&&!Y&&!te&&(rs.current=R,Bs())},[R,G,Y,te,Bs]),k.useEffect(()=>(Bs(),()=>{c.current&&c.current.getTracks().forEach(xn=>xn.stop()),m.current&&clearInterval(m.current),x.current&&cancelAnimationFrame(x.current),p.current&&p.current.close(),Ge.current&&clearInterval(Ge.current),te&&URL.revokeObjectURL(te),Ns()}),[Bs,te]),k.useEffect(()=>{if(B||G!==!0||te)return;const xn=c.current,Ar=l.current;!xn||!Ar||dt||(Ar.srcObject!==xn&&(Ar.srcObject=xn,Ar.muted=!0,Ar.playsInline=!0,Ar.autoplay=!0,Ar.setAttribute("muted",""),Ar.setAttribute("playsinline",""),Ar.setAttribute("autoplay","")),Ar.play().then(()=>ke(!1)).catch(Zr=>{ke(!0),console.warn("Live preview play blocked on mount:",Zr)}))},[G,B,te,dt]),k.useEffect(()=>{r==null||r(Y)},[Y,r]);const Ts=k.useCallback(async()=>{if(te)return;const xn=l.current;if(xn)try{await xn.play(),ke(!1)}catch(Ar){ke(!0),console.warn("Live preview still blocked (needs user gesture):",Ar)}},[te]),Fn=k.useCallback(()=>{o.current&&o.current.state!=="inactive"&&o.current.stop(),m.current&&(clearInterval(m.current),m.current=null),Ns(),se(!1),oe(!1)},[Ns]),An=k.useCallback(async()=>{let xn=null;if(v==="screen"){if(xn=await us(),!xn)return}else xn=dt&&xs?xs:c.current;if(!xn)return;Ts(),h.current=[],_e(0);const Zr=["video/webm;codecs=vp9,opus","video/webm;codecs=vp8,opus","video/webm;codecs=vp9","video/webm;codecs=vp8","video/webm","video/mp4"].find(Kt=>MediaRecorder.isTypeSupported(Kt)),dn=new MediaRecorder(xn,Zr?{mimeType:Zr,videoBitsPerSecond:v==="screen"?4e6:25e5}:{videoBitsPerSecond:v==="screen"?4e6:25e5});dn.ondataavailable=Kt=>{Kt.data.size>0&&h.current.push(Kt.data)},dn.onstop=()=>{var Ba;const Kt=dn.mimeType||Zr||((Ba=h.current[0])==null?void 0:Ba.type)||"video/webm",Er=new Blob(h.current,{type:Kt});Q(Er);const ti=URL.createObjectURL(Er);le(ti)},o.current=dn,dn.start(100),se(!0),m.current=setInterval(()=>{_e(Kt=>Kt>=s-1?(Fn(),s):Kt+1)},1e3)},[Ts,s,Fn,dt,xs,v,us]),js=k.useCallback(()=>{Ge.current&&(clearInterval(Ge.current),Ge.current=null),Oe(3);let xn=3;Ge.current=setInterval(()=>{xn-=1,xn<=0?(Ge.current&&clearInterval(Ge.current),Ge.current=null,Oe(null),An()):Oe(xn)},1e3)},[An]),In=k.useCallback(()=>{o.current&&o.current.state==="recording"&&(o.current.pause(),oe(!0),m.current&&clearInterval(m.current))},[]),un=k.useCallback(()=>{o.current&&o.current.state==="paused"&&(o.current.resume(),oe(!1),m.current=setInterval(()=>{_e(xn=>xn>=s-1?(Fn(),s):xn+1)},1e3))},[s,Fn]),jr=k.useCallback(()=>{te&&URL.revokeObjectURL(te),Q(null),le(null),_e(0),Ue(!1),je(!0),l.current&&c.current&&!dt&&(l.current.srcObject=c.current,l.current.muted=!0,Ts())},[Ts,te,dt]),Ln=k.useCallback(()=>{he(xn=>xn==="user"?"environment":"user")},[]),Sr=k.useCallback(()=>{me&&t(me,fe)},[me,fe,t]),Qn=k.useCallback(()=>{l.current&&te&&(Ie?l.current.pause():(je(!1),l.current.muted=!1,l.current.play()),Ue(!Ie))},[te,Ie]);k.useEffect(()=>{if(!te)return;const xn=l.current;if(!xn)return;je(!1),xn.pause(),xn.removeAttribute("src"),xn.srcObject=null,xn.load(),xn.src=te,xn.currentTime=0,xn.playsInline=!0,xn.muted=!1,xn.onended=()=>Ue(!1);const Ar=()=>{var Kt;const Zr=xn.error,dn=Zr?`Recorded video failed to play (code ${Zr.code}). Likely unsupported format/codec in this browser.`:"Recorded video failed to play.";console.warn("[VideoRecorder] recorded playback error",Zr),(Kt=jt.current)==null||Kt.call(jt,dn)};return xn.addEventListener("error",Ar),xn.load(),()=>{xn.removeEventListener("error",Ar)}},[te]);const En=xn=>{const Ar=Math.floor(xn/60),Zr=xn%60;return`${Ar}:${Zr.toString().padStart(2,"0")}`},pr=v==="screen"?"aspect-video":y&&R?"aspect-[9/16]":"aspect-video";return B?e.jsx("div",{className:Ot("flex items-center justify-center bg-black rounded-lg",pr,a),children:e.jsxs("div",{className:"text-center text-white",children:[e.jsx(Jt,{className:"h-12 w-12 animate-spin mx-auto mb-4"}),e.jsx("p",{children:"Initializing camera..."})]})}):G===!1?e.jsx("div",{className:Ot("flex items-center justify-center bg-black rounded-lg",pr,a),children:e.jsxs("div",{className:"text-center text-white p-8 max-w-md",children:[e.jsx(Ho,{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:Ye||"Please allow camera and microphone access to record videos."}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs($,{onClick:()=>Bs(),variant:"secondary",className:"w-full",children:[e.jsx(yo,{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:Ot("flex flex-col gap-2",a),children:[!Y&&!te&&e.jsxs("div",{className:"flex items-center justify-center gap-1 p-1 bg-muted rounded-lg",children:[e.jsxs($,{variant:v==="camera"?"default":"ghost",size:"sm",className:"gap-1.5 flex-1",onClick:()=>_("camera"),children:[e.jsx(g0,{className:"h-4 w-4"}),"Camera"]}),e.jsxs($,{variant:v==="screen"?"default":"ghost",size:"sm",className:"gap-1.5 flex-1",onClick:()=>_("screen"),children:[e.jsx(G8,{className:"h-4 w-4"}),"Screen"]})]}),v==="camera"&&!Y&&!te&&e.jsx(C4n,{value:yt,onChange:tt,isLoading:st,disabled:Y}),!Y&&!te&&(ut.length>0||et.length>0)&&e.jsxs("div",{className:"flex flex-wrap items-center gap-3 px-3 py-2 bg-muted/40 rounded-lg",children:[ut.length>0&&e.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-[200px]",children:[e.jsx(w2,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsxs(bs,{value:wt||"default",onValueChange:xn=>rt(xn==="default"?"":xn),children:[e.jsx(ys,{className:"h-8 text-xs",children:e.jsx(_s,{placeholder:"Default microphone"})}),e.jsxs(vs,{children:[e.jsx(We,{value:"default",children:"Default microphone"}),ut.map(xn=>e.jsx(We,{value:xn.deviceId,children:xn.label||`Microphone ${xn.deviceId.slice(0,6)}`},xn.deviceId))]})]})]}),et.length>1&&v==="camera"&&e.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-[200px]",children:[e.jsx(g0,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsxs(bs,{value:Ft||"default",onValueChange:xn=>Ut(xn==="default"?"":xn),children:[e.jsx(ys,{className:"h-8 text-xs",children:e.jsx(_s,{placeholder:"Default camera"})}),e.jsxs(vs,{children:[e.jsx(We,{value:"default",children:"Default camera"}),et.map(xn=>e.jsx(We,{value:xn.deviceId,children:xn.label||`Camera ${xn.deviceId.slice(0,6)}`},xn.deviceId))]})]})]})]}),v==="camera"&&y&&!Y&&!te&&e.jsxs("div",{className:"flex items-center justify-center gap-3 py-2 bg-muted/50 rounded-lg",children:[e.jsx(j2,{className:Ot("h-4 w-4",R?"text-muted-foreground":"text-primary")}),e.jsx(re,{htmlFor:"orientation-toggle",className:"text-sm text-muted-foreground",children:"Landscape"}),e.jsx(On,{id:"orientation-toggle",checked:R,onCheckedChange:gt}),e.jsx(re,{htmlFor:"orientation-toggle",className:"text-sm text-muted-foreground",children:"Portrait"}),e.jsx(yb,{className:Ot("h-4 w-4",R?"text-primary":"text-muted-foreground")})]}),v==="screen"&&!Y&&!te&&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(G8,{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:Ot("relative bg-black rounded-lg overflow-hidden"),onPointerDown:()=>{Ts()},children:[e.jsx("video",{ref:l,src:te??void 0,className:Ot("w-full bg-black",R&&!te?"object-contain":"object-cover",pr,!te&&ve==="user"!==(yt.mirror??!1)&&"scale-x-[-1]",dt&&!te&&"hidden"),playsInline:!0,controls:!!te,muted:te?Be:!0,autoPlay:!te},te??"live"),dt&&!te&&e.jsx("canvas",{ref:Is,className:Ot("w-full bg-black",R?"object-contain":"object-cover",pr,ve==="user"!==(yt.mirror??!1)&&"scale-x-[-1]")}),dt&&st&&!te&&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(Jt,{className:"h-8 w-8 animate-spin mx-auto mb-2"}),e.jsx("p",{className:"text-sm",children:"Loading virtual background…"})]})}),!te&&Re&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/40",children:e.jsx($,{type:"button",variant:"secondary",onClick:()=>void Ts(),className:"bg-white/20 hover:bg-white/30 text-white",children:"Tap to enable preview"})}),i&&!te&&e.jsx("div",{className:"absolute inset-0 pointer-events-none",children:i}),Fe!==null&&!te&&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:Fe},Fe),e.jsx("p",{className:"text-white/80 text-lg font-medium drop-shadow-md",children:"Get ready…"})]})}),Y&&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:Ot("w-3 h-3 rounded-full",ee?"bg-yellow-500":"bg-red-500 animate-pulse")}),e.jsxs("span",{className:"text-white text-sm font-medium",children:[En(fe)," / ",En(s)]})]}),Y&&e.jsx("div",{className:"absolute top-0 left-0 right-0",children:e.jsx(ho,{value:fe/s*100,className:"h-1 rounded-none"})}),!te&&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(w2,{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:`${Se}%`}})})]}),e.jsx("div",{className:"absolute bottom-4 left-0 right-0 flex justify-center gap-3 px-4",children:te?e.jsxs(e.Fragment,{children:[e.jsxs($,{variant:"secondary",size:"lg",className:"bg-white/20 hover:bg-white/30 text-white",onClick:jr,children:[e.jsx(yo,{className:"h-5 w-5 mr-2"}),"Re-record"]}),e.jsx($,{variant:"secondary",size:"icon",className:"h-12 w-12 rounded-full bg-white/20 hover:bg-white/30 text-white",onClick:Qn,children:Ie?e.jsx(uv,{className:"h-5 w-5"}):e.jsx(pu,{className:"h-5 w-5"})}),e.jsxs($,{size:"lg",className:"bg-green-500 hover:bg-green-600 text-white",onClick:Sr,children:[e.jsx(ma,{className:"h-5 w-5 mr-2"}),"Use This Video"]})]}):e.jsxs(e.Fragment,{children:[v==="camera"?e.jsx($,{variant:"secondary",size:"icon",className:"h-12 w-12 rounded-full bg-white/20 hover:bg-white/30 text-white",onClick:Ln,disabled:Y||Fe!==null,children:e.jsx(jm,{className:"h-5 w-5"})}):e.jsx("div",{className:"h-12 w-12"}),!Y&&Fe===null?e.jsx($,{size:"icon",className:"h-16 w-16 rounded-full bg-red-500 hover:bg-red-600 text-white",onClick:v==="screen"?An:js,children:v==="screen"?e.jsx(G8,{className:"h-6 w-6"}):e.jsx(ia,{className:"h-6 w-6"})}):e.jsxs(e.Fragment,{children:[e.jsx($,{size:"icon",className:"h-12 w-12 rounded-full bg-white/20 hover:bg-white/30 text-white",onClick:ee?un:In,children:ee?e.jsx(pu,{className:"h-5 w-5"}):e.jsx(uv,{className:"h-5 w-5"})}),e.jsx($,{size:"icon",className:"h-16 w-16 rounded-full bg-red-500 hover:bg-red-600 text-white",onClick:Fn,children:e.jsx(w_,{className:"h-6 w-6 fill-current"})})]}),e.jsx("div",{className:"h-12 w-12"})]})})]})]})}function p3n({open:s,onOpenChange:t,onUploaded:n}){const{user:r}=ks(),{toast:a}=Fi(),[i,l]=k.useState(!1),o=async(c,d)=>{if(r){l(!0);try{const u=c.type.includes("mp4")?"mp4":"webm",h=`${r.id}/${crypto.randomUUID()}.${u}`,{error:m}=await V.storage.from("cma-videos").upload(h,c,{contentType:c.type||"video/webm",upsert:!1});if(m)throw m;const{data:p,error:g}=await V.storage.from("cma-videos").createSignedUrl(h,60*60*24*365*5);if(g||!(p!=null&&p.signedUrl))throw g||new Error("Could not sign video URL");n(p.signedUrl,Math.round(d)),a({title:"Video added to your CMA"}),t(!1)}catch(u){a({title:"Upload failed",description:u==null?void 0:u.message,variant:"destructive"})}finally{l(!1)}}};return e.jsx(zs,{open:s,onOpenChange:c=>!i&&t(c),children:e.jsxs(Rs,{className:"max-w-2xl",children:[e.jsxs(Vs,{children:[e.jsx($s,{children:"Record a personal message"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"A 30-second hello goes a long way. Welcome your client, explain the price, and invite their reply."})]}),i?e.jsxs("div",{className:"py-12 flex flex-col items-center gap-3",children:[e.jsx(Jt,{className:"w-8 h-8 animate-spin text-primary"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Uploading your video…"})]}):e.jsx(w6,{maxDurationSeconds:180,onRecordingComplete:o})]})})}function g3n({value:s,onChange:t}){const{user:n}=ks(),[r,a]=k.useState(!1);return e.jsxs(we,{children:[e.jsxs(Vt,{children:[e.jsxs(Yt,{className:"text-base flex items-center gap-2",children:[e.jsx(ia,{className:"w-4 h-4"}),"Personal Video Message"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Adds the human touch your client will remember. Plays right at the top of the CMA."})]}),e.jsxs(De,{className:"space-y-3",children:[s!=null&&s.url?e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"relative rounded-lg overflow-hidden bg-black aspect-video group",children:[e.jsx("video",{src:s.url,poster:s.thumb,controls:!0,className:"w-full h-full object-cover"}),e.jsx("button",{className:"absolute top-2 right-2 bg-black/60 text-white rounded-full p-1.5 opacity-0 group-hover:opacity-100 transition-opacity",onClick:()=>t(null),"aria-label":"Remove video",type:"button",children:e.jsx(mr,{className:"w-3.5 h-3.5"})})]}),e.jsxs("p",{className:"text-xs text-emerald-700 flex items-center gap-1",children:[e.jsx(pu,{className:"w-3 h-3"})," Video attached"]})]}):e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(BF,{userId:n==null?void 0:n.id,triggerLabel:"Pick from Library",triggerVariant:"outline",triggerSize:"default",triggerClassName:"w-full justify-center gap-2",onSelect:()=>{},onSelectVideo:i=>t({url:i.playback_url,thumb:i.thumbnail_url,label:i.title||i.recipient_name})}),e.jsxs($,{variant:"outline",onClick:()=>a(!0),className:"gap-2",children:[e.jsx(ia,{className:"w-4 h-4"}),"Record New"]})]}),e.jsx(p3n,{open:r,onOpenChange:a,onUploaded:i=>t({url:i,label:"Personal message"})})]})]})}function VN(s){const t=Number(String(s).replace(/[^0-9.]/g,""));return Number.isFinite(t)&&t>0?t:null}function x3n({open:s,onOpenChange:t,subject:n,onSave:r,isSaving:a}){const[i,l]=k.useState({bedrooms:"",bathrooms:"",sqft:"",yearBuilt:"",propertyType:"",propertySubType:""});k.useEffect(()=>{s&&l({bedrooms:(n==null?void 0:n.bedrooms)!=null?String(n.bedrooms):"",bathrooms:(n==null?void 0:n.bathrooms)!=null?String(n.bathrooms):"",sqft:(n==null?void 0:n.sqft)!=null?String(n.sqft):"",yearBuilt:(n==null?void 0:n.yearBuilt)!=null?String(n.yearBuilt):"",propertyType:(n==null?void 0:n.propertyType)||"Residential",propertySubType:(n==null?void 0:n.propertySubType)||"Single Family"})},[s,n]);const o=async()=>{await r({bedrooms:VN(i.bedrooms),bathrooms:VN(i.bathrooms),sqft:VN(i.sqft),yearBuilt:VN(i.yearBuilt),propertyType:i.propertyType||null,propertySubType:i.propertySubType||null}),t(!1)};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"max-w-lg",children:[e.jsx(Vs,{children:e.jsx($s,{children:"Fill in the subject property basics"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"When the MLS feed does not return the home details, add the basics here and LevelUp will keep the CMA moving."}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Beds"}),e.jsx(be,{inputMode:"decimal",value:i.bedrooms,onChange:c=>l(d=>({...d,bedrooms:c.target.value})),placeholder:"3"})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Baths"}),e.jsx(be,{inputMode:"decimal",value:i.bathrooms,onChange:c=>l(d=>({...d,bathrooms:c.target.value})),placeholder:"2"})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Sq Ft"}),e.jsx(be,{inputMode:"numeric",value:i.sqft,onChange:c=>l(d=>({...d,sqft:c.target.value})),placeholder:"1850"})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Year Built"}),e.jsx(be,{inputMode:"numeric",value:i.yearBuilt,onChange:c=>l(d=>({...d,yearBuilt:c.target.value})),placeholder:"2006"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Property Type"}),e.jsx(be,{value:i.propertyType,onChange:c=>l(d=>({...d,propertyType:c.target.value})),placeholder:"Residential"})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Subtype"}),e.jsx(be,{value:i.propertySubType,onChange:c=>l(d=>({...d,propertySubType:c.target.value})),placeholder:"Single Family"})]})]}),e.jsxs($,{className:"w-full",onClick:o,disabled:a,children:[a?e.jsx(Jt,{className:"w-4 h-4 mr-2 animate-spin"}):e.jsx(Ml,{className:"w-4 h-4 mr-2"}),"Save subject details"]})]})]})})}function y3n({open:s,onOpenChange:t,subject:n,onAdd:r}){const[a,i]=k.useState({address:"",city:"",state:"",status:"Closed",price:"",bedrooms:"",bathrooms:"",sqft:"",yearBuilt:""});k.useEffect(()=>{s&&i({address:"",city:(n==null?void 0:n.city)||"",state:(n==null?void 0:n.state)||"",status:"Closed",price:"",bedrooms:"",bathrooms:"",sqft:"",yearBuilt:""})},[s,n]);const l=()=>{const o=VN(a.price),c=VN(a.sqft);!a.address.trim()||!o||!c||(r({mlsNumber:`manual-${Date.now()}`,source_provider:"manual",manual:!0,selected:!0,score:100,address:a.address.trim(),city:a.city||(n==null?void 0:n.city)||"",state:(a.state||(n==null?void 0:n.state)||"").toUpperCase(),status:a.status||"Closed",price:o,soldPrice:/closed|sold/i.test(a.status)?o:null,bedrooms:VN(a.bedrooms),bathrooms:VN(a.bathrooms),sqft:c,yearBuilt:VN(a.yearBuilt),photos:[]}),t(!1))};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"max-w-2xl",children:[e.jsx(Vs,{children:e.jsx($s,{children:"Add a comparable manually"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Use this when the MLS feed misses a property or you already know the best comp. Add at least the address, price, and square footage."}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-3",children:[e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(re,{className:"text-xs",children:"Address"}),e.jsx(be,{value:a.address,onChange:o=>i(c=>({...c,address:o.target.value})),placeholder:"123 Comparable St"})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"City"}),e.jsx(be,{value:a.city,onChange:o=>i(c=>({...c,city:o.target.value}))})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"State"}),e.jsx(be,{maxLength:2,value:a.state,onChange:o=>i(c=>({...c,state:o.target.value.toUpperCase()}))})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-3",children:[e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Status"}),e.jsx(be,{value:a.status,onChange:o=>i(c=>({...c,status:o.target.value})),placeholder:"Closed"})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Price"}),e.jsx(be,{inputMode:"numeric",value:a.price,onChange:o=>i(c=>({...c,price:o.target.value})),placeholder:"525000"})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Sq Ft"}),e.jsx(be,{inputMode:"numeric",value:a.sqft,onChange:o=>i(c=>({...c,sqft:o.target.value})),placeholder:"1800"})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Beds"}),e.jsx(be,{inputMode:"decimal",value:a.bedrooms,onChange:o=>i(c=>({...c,bedrooms:o.target.value})),placeholder:"3"})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Baths"}),e.jsx(be,{inputMode:"decimal",value:a.bathrooms,onChange:o=>i(c=>({...c,bathrooms:o.target.value})),placeholder:"2"})]})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Year Built"}),e.jsx(be,{className:"max-w-[180px]",inputMode:"numeric",value:a.yearBuilt,onChange:o=>i(c=>({...c,yearBuilt:o.target.value})),placeholder:"2005"})]}),e.jsxs($,{className:"w-full",onClick:l,disabled:!a.address.trim()||!VN(a.price)||!VN(a.sqft),children:[e.jsx(nn,{className:"w-4 h-4 mr-2"}),"Add comp to CMA"]})]})]})})}function v3n(){var he,Se,Te,Ie,Ue,Be,je;const{id:s}=oo(),t=Jn(),{toast:n}=Fi(),{data:r,isLoading:a}=I5n(s),{data:i}=L5n(s),l=R5n(),o=F5n(),c=z5n(),{leadSite:d,isLoading:u}=Tg(),[h,m]=k.useState([]),[p,g]=k.useState({sqftPct:.2,monthsBack:6,maxMiles:5,statuses:["Active","Pending","Closed"]}),[x,y]=k.useState(null),[v,_]=k.useState(!1),[j,C]=k.useState({low:"",likely:"",high:"",note:""}),[A,M]=k.useState(!1),[I,P]=k.useState(!1),[R,O]=k.useState(!1),[B,U]=k.useState(null),G=async Ye=>{var Ge,yt;if(!r||!(Ye!=null&&Ye.address)||!(Ye!=null&&Ye.city)||!(Ye!=null&&Ye.state))return Ye;let Ee={...Ye};const Re=async tt=>{const{data:ut,error:nt}=await V.functions.invoke("cma-subject-lookup",{body:{address:tt.address,city:tt.city,state:tt.state,zip:tt.zip,latitude:tt.latitude,longitude:tt.longitude,leadSiteId:(d==null?void 0:d.id)??r.lead_site_id}});if(nt)throw nt;return(ut==null?void 0:ut.matches)||[]},ke=tt=>{const nt=tt.find(rt=>Number.isFinite(Number(rt.latitude))&&Number.isFinite(Number(rt.longitude)))||tt[0];if(!nt)return;const et=typeof nt.match_type=="string"&&nt.match_type.startsWith("nearby-"),at=et&&Number.isFinite(Number(Ee.latitude))&&Number.isFinite(Number(Ee.longitude)),wt=rt=>nt[rt]!==void 0&&nt[rt]!==null&&nt[rt]!==""&&nt[rt]!==0?nt[rt]:Ee[rt];Ee={...Ee,bedrooms:wt("bedrooms"),bathrooms:wt("bathrooms"),sqft:wt("sqft"),yearBuilt:wt("yearBuilt"),lotSize:wt("lotSize"),propertyType:wt("propertyType"),propertySubType:wt("propertySubType"),source_provider:nt.source_provider??Ee.source_provider,match_type:nt.match_type??Ee.match_type,matched_mls_address:et?nt.address:Ee.matched_mls_address,latitude:at?Ee.latitude:nt.latitude??Ee.latitude,longitude:at?Ee.longitude:nt.longitude??Ee.longitude,mlsNumber:et?Ee.mlsNumber:nt.mlsNumber??Ee.mlsNumber,photos:!et&&Array.isArray(nt.photos)&&nt.photos.length?nt.photos:Ee.photos}};ke(await Re(Ee));const Fe=()=>Number.isFinite(Number(Ee.latitude))&&Number.isFinite(Number(Ee.longitude));if(!Fe()){const{data:tt}=await V.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle(),ut=tt==null?void 0:tt.value;if(ut){const nt=encodeURIComponent(`${Ee.address}, ${Ee.city}, ${Ee.state} ${Ee.zip||""}`.trim()),at=await(await fetch(`https://api.mapbox.com/geocoding/v5/mapbox.places/${nt}.json?access_token=${ut}&limit=1&country=us`)).json(),wt=(yt=(Ge=at==null?void 0:at.features)==null?void 0:Ge[0])==null?void 0:yt.center;Array.isArray(wt)&&wt.length===2&&(Ee.longitude=wt[0],Ee.latitude=wt[1])}}if((!Ee.bedrooms||!Ee.bathrooms||!Ee.sqft||!Ee.yearBuilt)&&Fe())try{ke(await Re(Ee))}catch(tt){console.warn("second-pass subject lookup failed",tt)}return JSON.stringify(Ee)!==JSON.stringify(Ye)&&await l.mutateAsync({id:r.id,patch:{subject:Ee}}),Ee};k.useEffect(()=>{var Re,ke;r!=null&&r.settings&&g({sqftPct:r.settings.sqftPct??.2,monthsBack:r.settings.monthsBack??6,maxMiles:r.settings.maxMiles??5,statuses:r.settings.statuses??["Active","Pending","Closed"]});const Ye=(Re=r==null?void 0:r.settings)==null?void 0:Re.priceOverride;Ye!=null&&Ye.enabled&&(_(!0),C({low:Ye.low!=null?String(Ye.low):"",likely:Ye.likely!=null?String(Ye.likely):"",high:Ye.high!=null?String(Ye.high):"",note:Ye.note??""}));const Ee=(ke=r==null?void 0:r.settings)==null?void 0:ke.personalVideo;Ee!=null&&Ee.url&&U({url:Ee.url,thumb:Ee.thumb,label:Ee.label})},[r==null?void 0:r.id]);const H=k.useRef(!1);k.useEffect(()=>{H.current||i!=null&&i.length&&(m(i.map(Ye=>({...Ye.snapshot,selected:Ye.selected,manual:Ye.manual,score:Ye.score}))),H.current=!0)},[i]);const Y=k.useRef(null);k.useEffect(()=>{if(!r||u)return;const Ye=r.subject||{},Ee=Number.isFinite(Number(Ye.latitude))&&Number.isFinite(Number(Ye.longitude)),Re=!!(Number(Ye.bedrooms)||Number(Ye.bathrooms)||Number(Ye.sqft)||Number(Ye.yearBuilt));if(Ee&&Re)return;const ke=`${r.id}:${(d==null?void 0:d.id)??r.lead_site_id??"no-site"}`;Y.current!==ke&&(!Ye.address||!Ye.city||!Ye.state||(Y.current=ke,(async()=>{try{await G(Ye)}catch(Fe){console.warn("subject enrich failed",Fe)}})()))},[r==null?void 0:r.id,r==null?void 0:r.lead_site_id,d==null?void 0:d.id,u]);const se=k.useMemo(()=>r?Vyt(r.subject,h):null,[r,h]),ee=async()=>{if(r)try{const Ye=await G(r.subject),Ee=await o.mutateAsync({subject:Ye,filters:p,leadSiteId:(d==null?void 0:d.id)??r.lead_site_id});m(Ee.comps.map(Re=>({...Re,selected:!0})).slice(0,12)),n({title:`Found ${Ee.comps.length} comps`,description:`Top ${Math.min(12,Ee.comps.length)} auto-selected.`})}catch(Ye){n({title:"Search failed",description:Ye.message,variant:"destructive"})}},oe=Ye=>{m(Ee=>Ee.map((Re,ke)=>ke===Ye?{...Re,selected:!Re.selected}:Re))},me=Ye=>{m(Ee=>Ee.filter((Re,ke)=>ke!==Ye))},Q=async Ye=>{if(!r)return;const Ee=Object.fromEntries(Object.entries(Ye).filter(([,ke])=>ke!=null&&ke!=="")),Re={...r.subject,...Ee,manually_enriched:!0};await l.mutateAsync({id:r.id,patch:{subject:Re}}),n({title:"Subject details saved",description:Re.sqft?"You can now find comps or add your own.":"Add square footage to unlock suggested pricing."})},te=Ye=>{m(Ee=>[{...Ye,selected:!0,manual:!0},...Ee]),n({title:"Manual comp added"})},le=async(Ye=!1)=>{if(!r)return;const Ee=Vyt(r.subject,h),Re=yt=>{const tt=Number(String(yt).replace(/[^0-9.]/g,""));return Number.isFinite(tt)&&tt>0?Math.round(tt):null},ke=v?Re(j.likely):null,Fe=v?Re(j.low):null,Oe=v?Re(j.high):null,Ge=v&&ke;await l.mutateAsync({id:r.id,patch:{settings:{...p,priceOverride:{enabled:v,low:Fe,likely:ke,high:Oe,note:j.note||null},personalVideo:B},price_low:Ge?Fe??ke:Ee.low??null,price_likely:Ge?ke:Ee.likely??null,price_high:Ge?Oe??ke:Ee.high??null,status:Ye?"shared":r.status}}),await c.mutateAsync({cmaId:r.id,comps:h}),n({title:Ye?"CMA published":"CMA saved"})},fe=r?`https://cma.relevelup.com/${r.share_token}`:"";if(a||!r)return e.jsx(Xs,{children:e.jsx("div",{className:"p-6",children:e.jsx(Jt,{className:"w-6 h-6 animate-spin"})})});const _e=h.filter(Ye=>Ye.selected).length,ve=!((he=r.subject)!=null&&he.bedrooms)||!((Se=r.subject)!=null&&Se.bathrooms)||!((Te=r.subject)!=null&&Te.sqft)||!((Ie=r.subject)!=null&&Ie.yearBuilt);return e.jsx(Xs,{children:e.jsxs("div",{className:"container mx-auto p-4 md:p-6 max-w-7xl",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4 gap-2 flex-wrap",children:[e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>t("/mission-control/cma"),children:[e.jsx(Ia,{className:"w-4 h-4 mr-1"})," All CMAs"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs($,{variant:"outline",onClick:()=>le(!1),disabled:l.isPending,children:[e.jsx(Ml,{className:"w-4 h-4 mr-1"}),"Save"]}),e.jsxs($,{onClick:()=>le(!0),disabled:l.isPending,children:[e.jsx(ou,{className:"w-4 h-4 mr-1"}),"Publish & Share"]}),r.status==="shared"&&e.jsxs(e.Fragment,{children:[e.jsxs($,{variant:"secondary",onClick:()=>{navigator.clipboard.writeText(fe),n({title:"Link copied"})},children:[e.jsx(Ir,{className:"w-4 h-4 mr-1"}),"Copy Link"]}),e.jsxs($,{onClick:()=>M(!0),children:[e.jsx(pn,{className:"w-4 h-4 mr-1"}),"Send to Contact"]})]})]})]}),e.jsxs("div",{className:"grid lg:grid-cols-3 gap-4",children:[e.jsxs("div",{className:"lg:col-span-1 space-y-4",children:[e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsx(Yt,{className:"text-base",children:"Subject Property"})}),e.jsxs(De,{className:"space-y-2 text-sm",children:[e.jsx("div",{className:"font-semibold",children:r.subject.address}),e.jsxs("div",{className:"text-muted-foreground",children:[r.subject.city,", ",r.subject.state," ",r.subject.zip]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2 pt-2",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Beds:"})," ",r.subject.bedrooms??"—"]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Baths:"})," ",r.subject.bathrooms??"—"]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"SqFt:"})," ",((Ue=r.subject.sqft)==null?void 0:Ue.toLocaleString())??"—"]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Year:"})," ",r.subject.yearBuilt??"—"]})]}),ve&&e.jsxs("div",{className:"rounded-lg border border-amber-200 bg-amber-50 p-3 text-amber-950 space-y-2",children:[e.jsx("p",{className:"font-medium",children:"No panic — we can still build this."}),e.jsx("p",{className:"text-xs leading-relaxed",children:"If the MLS/feed does not return beds, baths, sqft, or year, add them manually and LevelUp will use them for comps and pricing."}),e.jsxs($,{size:"sm",variant:"outline",className:"bg-white",onClick:()=>P(!0),children:[e.jsx(ui,{className:"w-3.5 h-3.5 mr-1"}),"Fill in property details"]})]}),!ve&&e.jsxs($,{size:"sm",variant:"ghost",className:"px-0",onClick:()=>P(!0),children:[e.jsx(ui,{className:"w-3.5 h-3.5 mr-1"}),"Edit details"]}),!r.subject.sqft&&e.jsxs("div",{className:"pt-2 border-t",children:[e.jsx(re,{className:"text-xs",children:"Subject SqFt (needed for price band)"}),e.jsx(be,{type:"number",defaultValue:"",onBlur:async Ye=>{const Ee=Number(Ye.target.value);Ee>0&&await l.mutateAsync({id:r.id,patch:{subject:{...r.subject,sqft:Ee}}})}})]})]})]}),e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsxs(Yt,{className:"text-base flex items-center gap-2",children:[e.jsx(C5,{className:"w-4 h-4"}),"Suggested Price"]})}),e.jsxs(De,{className:"space-y-3",children:[se!=null&&se.likely?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"text-3xl font-bold",children:["$",(v&&Number(j.likely)>0?Number(j.likely):se.likely).toLocaleString()]}),e.jsxs("div",{className:"text-xs text-muted-foreground mt-1",children:["Comps suggest: $",(Be=se.low)==null?void 0:Be.toLocaleString()," – $",(je=se.high)==null?void 0:je.toLocaleString()]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:["$",se.ppsf,"/sqft median · ",_e," comps"]})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"Add comps with sqft + price to see suggested pricing."}),e.jsxs("div",{className:"pt-3 border-t space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(re,{htmlFor:"override-toggle",className:"text-sm font-medium",children:"Override with my price"}),e.jsx(On,{id:"override-toggle",checked:v,onCheckedChange:_})]}),v&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"My suggested price"}),e.jsx(be,{type:"number",placeholder:"e.g. 750000",value:j.likely,onChange:Ye=>C(Ee=>({...Ee,likely:Ye.target.value}))})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Range low"}),e.jsx(be,{type:"number",placeholder:"optional",value:j.low,onChange:Ye=>C(Ee=>({...Ee,low:Ye.target.value}))})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Range high"}),e.jsx(be,{type:"number",placeholder:"optional",value:j.high,onChange:Ye=>C(Ee=>({...Ee,high:Ye.target.value}))})]})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Why this price (optional)"}),e.jsx(Ls,{rows:2,maxLength:500,placeholder:"Notes shown to your client",value:j.note,onChange:Ye=>C(Ee=>({...Ee,note:Ye.target.value}))})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Save to apply. Your price will replace the comp-based number on the shared report."})]})]})]})]}),e.jsx(g3n,{value:B,onChange:U}),e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsx(Yt,{className:"text-base",children:"Filters"})}),e.jsxs(De,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsxs(re,{className:"text-xs",children:["SqFt tolerance: ±",Math.round(p.sqftPct*100),"%"]}),e.jsx(sx,{value:[p.sqftPct*100],min:5,max:50,step:5,onValueChange:([Ye])=>g(Ee=>({...Ee,sqftPct:Ye/100}))})]}),e.jsxs("div",{children:[e.jsxs(re,{className:"text-xs",children:["Search radius: ",p.maxMiles," mi"]}),e.jsx(sx,{value:[p.maxMiles],min:1,max:25,step:1,onValueChange:([Ye])=>g(Ee=>({...Ee,maxMiles:Ye}))})]}),e.jsxs("div",{children:[e.jsxs(re,{className:"text-xs",children:["Sold within: ",p.monthsBack," months"]}),e.jsx(sx,{value:[p.monthsBack],min:1,max:24,step:1,onValueChange:([Ye])=>g(Ee=>({...Ee,monthsBack:Ye}))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-xs",children:"Status"}),["Active","Pending","Closed"].map(Ye=>e.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[e.jsx(Li,{checked:p.statuses.includes(Ye),onCheckedChange:Ee=>g(Re=>({...Re,statuses:Ee?[...Re.statuses,Ye]:Re.statuses.filter(ke=>ke!==Ye)}))})," ",Ye]},Ye))]}),e.jsxs($,{className:"w-full",onClick:ee,disabled:o.isPending,children:[o.isPending?e.jsx(Jt,{className:"w-4 h-4 animate-spin mr-2"}):e.jsx(kn,{className:"w-4 h-4 mr-2"}),"Find Comps"]}),e.jsxs($,{variant:"outline",className:"w-full",onClick:()=>O(!0),children:[e.jsx(nn,{className:"w-4 h-4 mr-2"}),"Add a comp manually"]})]})]})]}),e.jsxs("div",{className:"lg:col-span-2 space-y-3",children:[e.jsx(N4n,{subject:r.subject,comps:h,radiusMiles:p.maxMiles,onMarkerClick:Ye=>y(Ye)}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("h2",{className:"text-lg font-semibold",children:["Comparables (",h.length,")"]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[_e," selected"]})]}),h.length?e.jsx("div",{className:"space-y-2",children:h.map((Ye,Ee)=>{var Re;return e.jsx(we,{className:Ye.selected?"":"opacity-50",children:e.jsxs(De,{className:"p-3 flex gap-3 items-center",children:[e.jsx(Li,{checked:Ye.selected,onCheckedChange:()=>oe(Ee)}),e.jsxs("button",{type:"button",onClick:()=>y(Ee),className:"flex gap-3 items-center flex-1 min-w-0 text-left hover:bg-muted/40 -mx-1 px-1 py-1 rounded transition",children:[e.jsx(kSe,{photos:Ye.photos,className:"w-20 h-16 rounded flex-none"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"font-medium truncate hover:underline",children:Ye.address}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[Ye.city,", ",Ye.state," · ",Ye.bedrooms??"?","bd/",Ye.bathrooms??"?","ba · ",((Re=Ye.sqft)==null?void 0:Re.toLocaleString())??"?"," sqft",Ye.yearBuilt?` · ${Ye.yearBuilt}`:""]}),e.jsxs("div",{className:"text-xs mt-0.5",children:[e.jsx(qe,{variant:"outline",className:"mr-1",children:Ye.status}),Ye.score!=null&&e.jsxs("span",{className:"text-muted-foreground",children:["Score ",Ye.score]})]})]}),e.jsxs("div",{className:"text-right",children:[e.jsxs("div",{className:"font-semibold",children:["$",(Ye.soldPrice||Ye.price||0).toLocaleString()]}),Ye.sqft&&(Ye.soldPrice||Ye.price)?e.jsxs("div",{className:"text-xs text-muted-foreground",children:["$",Math.round((Ye.soldPrice||Ye.price)/Ye.sqft),"/sqft"]}):null]})]}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>y(Ee),title:"View details",children:e.jsx(ba,{className:"w-4 h-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>me(Ee),title:"Remove",children:e.jsx(Un,{className:"w-4 h-4"})})]})},Ee)})}):e.jsx(we,{children:e.jsx(De,{className:"py-12 text-center text-muted-foreground",children:e.jsxs("div",{className:"max-w-md mx-auto space-y-3",children:[e.jsxs("p",{children:["Click ",e.jsx("strong",{children:"Find Comps"})," to auto-pull from your MLS."]}),e.jsx("p",{className:"text-sm",children:"If nothing comes back, you are not stuck — use LevelUp's fallback template: enter the subject details, add 2–3 known comps, then set your suggested price."}),e.jsxs("div",{className:"flex flex-wrap justify-center gap-2",children:[ve&&e.jsx($,{variant:"outline",size:"sm",onClick:()=>P(!0),children:"Fill subject details"}),e.jsx($,{variant:"outline",size:"sm",onClick:()=>O(!0),children:"Add manual comp"})]})]})})})]})]}),e.jsx(cMt,{comp:x!=null?h[x]:null,open:x!=null,onClose:()=>y(null)}),e.jsx(x3n,{open:I,onOpenChange:P,subject:r.subject,onSave:Q,isSaving:l.isPending}),e.jsx(y3n,{open:R,onOpenChange:O,subject:r.subject,onAdd:te}),e.jsx(n9t,{open:A,onOpenChange:M,cma:r})]})})}const RM="listing-presentations";function oBt(){const{user:s}=ks(),t=ls(),n=pt({queryKey:["listing-presentation-saved-templates",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:o,error:c}=await V.from("listing_presentation_saved_templates").select("*").eq("owner_user_id",s.id).order("updated_at",{ascending:!1});if(c)throw c;return o}}),r=()=>t.invalidateQueries({queryKey:["listing-presentation-saved-templates",s==null?void 0:s.id]}),a=Nt({mutationFn:async o=>{const{data:c,error:d}=await V.from("listing_presentation_saved_templates").insert({...o,owner_user_id:s.id}).select().single();if(d)throw d;return c},onSuccess:()=>{r(),ae.success("Template saved")},onError:o=>ae.error(o.message||"Could not save the template")}),i=Nt({mutationFn:async({id:o,...c})=>{const{error:d}=await V.from("listing_presentation_saved_templates").update(c).eq("id",o);if(d)throw d},onSuccess:()=>{r(),ae.success("Template updated")},onError:o=>ae.error(o.message||"Could not update the template")}),l=Nt({mutationFn:async o=>{const{error:c}=await V.from("listing_presentation_saved_templates").delete().eq("id",o);if(c)throw c},onSuccess:()=>{r(),ae.success("Template deleted")},onError:o=>ae.error(o.message||"Could not delete the template")});return{savedTemplates:n.data??[],isLoading:n.isLoading,save:a,update:i,remove:l}}function b3n(){return pt({queryKey:["listing-presentation-templates"],staleTime:10*60*1e3,queryFn:async()=>{const{data:s,error:t}=await V.from("listing_presentation_templates").select("*").eq("is_active",!0).order("sort_order",{ascending:!0});if(t)throw t;return s}})}function lBt(){const{user:s}=ks(),t=ls(),n=pt({queryKey:["listing-presentations",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:c,error:d}=await V.from("listing_presentations").select("*").eq("owner_user_id",s.id).order("updated_at",{ascending:!1});if(d)throw d;return c}}),r=()=>t.invalidateQueries({queryKey:["listing-presentations",s==null?void 0:s.id]}),a=Nt({mutationFn:async c=>{const{data:d,error:u}=await V.from("listing_presentations").insert({...c,owner_user_id:s.id}).select().single();if(u)throw u;return d},onSuccess:r,onError:c=>ae.error(c.message||"Could not create presentation")}),i=Nt({mutationFn:async({id:c,...d})=>{const{data:u,error:h}=await V.from("listing_presentations").update(d).eq("id",c).select().single();if(h)throw h;return u},onSuccess:c=>{r(),t.invalidateQueries({queryKey:["listing-presentation",c.id]})},onError:c=>ae.error(c.message||"Could not save presentation")}),l=Nt({mutationFn:async c=>{let d=null;const{data:u,error:h}=await V.from("listing_presentations").insert({owner_user_id:s.id,title:`${c.title} (Copy)`,template_id:c.template_id,status:"draft",property_address_line1:c.property_address_line1,city:c.city,state:c.state,postal_code:c.postal_code,list_price:c.list_price,beds:c.beds,baths:c.baths,sqft:c.sqft,agent_snapshot:c.agent_snapshot,co_agent:c.co_agent,custom_pages:c.custom_pages,services:c.services,page_settings:c.page_settings,photo_focal:c.photo_focal}).select().single();if(h)throw h;if(c.property_photo_path){d=`${s.id}/${u.id}/photo.jpg`;const{error:m}=await V.storage.from(RM).copy(c.property_photo_path,d);m||await V.from("listing_presentations").update({property_photo_path:d}).eq("id",u.id)}return u},onSuccess:()=>{r(),ae.success("Presentation duplicated")},onError:c=>ae.error(c.message||"Could not duplicate")}),o=Nt({mutationFn:async c=>{const d=[c.property_photo_path,c.pdf_path,c.thumbnail_path].filter(Boolean);d.length&&await V.storage.from(RM).remove(d);const{error:u}=await V.from("listing_presentations").delete().eq("id",c.id);if(u)throw u},onSuccess:()=>{r(),ae.success("Presentation deleted")},onError:c=>ae.error(c.message||"Could not delete")});return{presentations:n.data??[],isLoading:n.isLoading,create:a,update:i,duplicate:l,remove:o}}function _3n(s){return pt({queryKey:["listing-presentation",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await V.from("listing_presentations").select("*").eq("id",s).maybeSingle();if(n)throw n;return t}})}async function w3n(s,t=3600){if(!s)return null;const{data:n,error:r}=await V.storage.from(RM).createSignedUrl(s,t);return r?null:(n==null?void 0:n.signedUrl)??null}const j3n="#2a4c64",N3n="#B8965A";function cBt(){const{user:s}=ks();return pt({queryKey:["agent-brand",s==null?void 0:s.id],enabled:!!s,staleTime:5*60*1e3,queryFn:async()=>{const t=s.id,[n,r,a]=await Promise.all([V.from("profiles").select("name, email, phone, avatar_url, website_url, title, brokerage_name, brokerage_id").eq("id",t).maybeSingle(),V.from("lead_sites").select("brand_color, accent_color, agent_license_number, brokerage_license_number, license_state, brokerage_legal_name, team_logo_url, is_active, created_at").eq("agent_id",t).order("created_at",{ascending:!0}).limit(5),V.from("agent_cards").select("brokerage_display_name, brokerage_logo_url, team_logo_url, title, positioning_statement, display_email").eq("user_id",t).maybeSingle()]),i=n.data||{},l=r.data||[],o=l.find(u=>u.is_active)||l[0]||{},c=a.data||{};let d=i.brokerage_name||c.brokerage_display_name||o.brokerage_legal_name||null;if(!d&&i.brokerage_id){const{data:u}=await V.from("brokerages").select("name").eq("id",i.brokerage_id).maybeSingle();d=(u==null?void 0:u.name)||null}return{name:i.name||s.email||"Your Name",headshotUrl:i.avatar_url||null,brokerageName:d,brokerageLogoUrl:c.brokerage_logo_url||c.team_logo_url||o.team_logo_url||null,licenseNumber:o.agent_license_number||null,licenseState:o.license_state||null,phone:i.phone||null,email:c.display_email||i.email||s.email||null,website:i.website_url||null,brandColor:o.brand_color||j3n,accentColor:o.accent_color||N3n,tagline:c.positioning_statement||i.title||c.title||null}}})}const f$e={cover:{kicker:"A smarter launch for",headline:"",subhead:"",body:"A complete marketing plan designed to make your home stand out, reach more buyers, and create stronger interest."},welcome:{kicker:"The strategy",headline:"Your listing deserves more than a sign and an MLS entry.",subhead:"It deserves a coordinated launch that builds attention from day one.",body:""},agent:{kicker:"Your agent",headline:"Who you are working with.",subhead:"",body:""},overview:{kicker:"The plan",headline:"Every home gets listed. Very few get marketed.",subhead:"These are the steps we run on your home, in order, starting the day we sign.",body:""},closing:{kicker:"The commitment",headline:'Your home will never feel like "just another listing."',subhead:"",body:"It will be prepared carefully, presented professionally, launched strategically, and promoted with purpose — from the first photo to the final signature."}},k3n={cover:"Cover",welcome:"Marketing commitment",agent:"About your agent",overview:"Marketing plan overview",closing:"Closing commitment"};function dBt(s,t){var i;const n=((i=s==null?void 0:s.copy)==null?void 0:i[t])||{},r=f$e[t],a=l=>{const o=n[l];return o??r[l]};return{kicker:a("kicker"),headline:a("headline"),subhead:a("subhead"),body:a("body")}}const uBt={enabled:!1,name:"",title:null,headshotUrl:null,phone:null,email:null,brokerageName:null,licenseNumber:null,bio:null};function hBt(s){return{...uBt,...s||{}}}const hDe=[{layout:"story",name:"Story + photo",description:'Editorial two-column story next to a full-height photo. Great for "About Us".'},{layout:"testimonials",name:"Testimonial cards",description:'Up to four pull-quote cards. Great for "What Others Are Saying".'},{layout:"stats",name:"Numbers band",description:"Big stat tiles with a short lead paragraph. Great for a track record page."},{layout:"checklist",name:"Checklist",description:"Headline, intro copy, and an accent-marked list of promises or steps."},{layout:"statement",name:"Full-bleed statement",description:"A dark, photo-backed page with one powerful line. Great for a section break."}],mBt=()=>typeof crypto<"u"&&"randomUUID"in crypto?crypto.randomUUID():`cp_${Math.random().toString(36).slice(2)}`;function FXe(s,t=0){const n={id:mBt(),layout:s,enabled:!0,order:t,placement:"after-agent",kicker:"",headline:"",subhead:"",body:"",bullets:[],testimonials:[],stats:[],imageUrl:null,imageSide:"right",dark:!1};switch(s){case"story":return{...n,kicker:"About us",headline:"A team built around one thing: your move.",subhead:"Who we are, how we work, and why sellers keep referring us.",body:"Share your background, your team, and what a seller can expect when they work with you. Two or three short paragraphs is the sweet spot — enough to build trust without turning the page into a resume."};case"testimonials":return{...n,kicker:"What others are saying",headline:"The people we have already moved.",subhead:"Real words from recent sellers and buyers.",testimonials:[{quote:"Add a real client quote here.",name:"Client name",detail:"Neighborhood or year"},{quote:"Add a second client quote here.",name:"Client name",detail:"Neighborhood or year"}]};case"stats":return{...n,kicker:"Track record",headline:"The numbers behind the plan.",body:"Add only numbers you can stand behind — sellers notice when the math is real.",stats:[{value:"",label:"Homes sold"},{value:"",label:"Avg. days on market"},{value:"",label:"List-to-sale price"}]};case"checklist":return{...n,kicker:"Our promise",headline:"What you can count on from us.",body:"A short intro to the list below.",bullets:["Add a promise, step, or service here","Add another line","Add another line"]};case"statement":return{...n,dark:!0,kicker:"Our approach",headline:"Every home has a story. We make sure buyers hear it.",body:""};default:return n}}function fBt(s){return Array.isArray(s)?s.filter(t=>t&&typeof t=="object").map((t,n)=>({...FXe(t.layout||"story",n),...t,id:t.id||mBt(),order:typeof t.order=="number"?t.order:n,bullets:Array.isArray(t.bullets)?t.bullets:[],testimonials:Array.isArray(t.testimonials)?t.testimonials:[],stats:Array.isArray(t.stats)?t.stats:[]})).sort((t,n)=>t.order-n.order):[]}const p$e={hidden:["overview"]},g$e={x:.5,y:.5},hd=(s,t,n=!0)=>({key:s,label:t,enabled:n}),z4e=[{key:"photography",title:"Professional Photography",body:"Your home is photographed by a professional real estate photographer — HDR interiors, crisp exteriors, and the detail shots that make buyers stop scrolling. Every image is color-corrected and delivered ready for print and every portal.",enabled:!0,order:0,options:[hd("hdr","Full HDR interior and exterior photo set"),hd("drone","Aerial drone photography of the home and lot"),hd("twilight","Twilight exterior session for the hero image"),hd("staging","Virtual staging for vacant or transitional rooms",!1),hd("floorplan","Measured floor plan buyers can explore")]},{key:"video",title:"Video That Sells the Feeling",body:"Photos show the rooms. Video shows the life. We produce a cinematic walkthrough plus short-form vertical cuts built specifically for how buyers actually watch — on their phone, in the first ten seconds.",enabled:!0,order:1,options:[hd("walkthrough","Cinematic full-property walkthrough video"),hd("reels","Vertical short-form cuts for Reels, Shorts, and TikTok"),hd("oncamera","On-camera agent introduction to the home"),hd("neighborhood","Neighborhood and lifestyle b-roll")]},{key:"mls",title:"MLS Launch & Pricing Strategy",body:"We launch on the MLS with a carefully written description, complete data fields, and a pricing strategy built around live comparable activity — positioning your home to attract the strongest possible offers in the first two weeks.",enabled:!0,order:2,options:[hd("data","Complete, accurate MLS data so your home shows in every filter"),hd("copy","Copywriting that leads with the features buyers pay for"),hd("pricing","Pricing built on live comparable and absorption data"),hd("comingsoon","Coming-soon window to build demand before day one")]},{key:"syndication",title:"Maximum Exposure & Portal Distribution",body:"Your listing is pushed to the sites buyers already live on, with the data monitored so your photos, price, and details stay accurate everywhere they appear.",enabled:!0,order:3,options:[hd("zillow","Zillow — the highest-traffic buyer search portal"),hd("realtor","Realtor.com — direct MLS-sourced listing feed"),hd("homes","Homes.com — agent-attributed listing exposure"),hd("others","Redfin, Trulia, Movoto, and hundreds of partner sites"),hd("routing","Buyer inquiries routed straight to me and answered fast")]},{key:"website",title:"Dedicated Property Website",body:"Your home gets its own single-property website with the full photo gallery, video, floor plan, neighborhood details, and a direct inquiry form — a link we can share in every ad, email, and social post.",enabled:!0,order:4,options:[hd("gallery","Full-screen gallery, video, and floor plan in one place"),hd("mobile","Mobile-first design with a one-tap inquiry form"),hd("link","Shareable link used across ads, email, and QR signage"),hd("traffic","Traffic tracked and reported back to you")]},{key:"social",title:"Social Media Campaign",body:"A launch that looks like a campaign, not a post. Organic content across my channels plus targeted paid placement aimed at qualified buyers and the agents who represent them.",enabled:!0,order:5,options:[hd("organic","Just-listed launch across feed, stories, and reels"),hd("ads","Geo-targeted paid campaigns aimed at active buyers"),hd("retarget","Retargeting so interested viewers keep seeing your home"),hd("agentsocial","Agent-to-agent promotion inside local networks")]},{key:"email",title:"Email, Database & Agent Outreach",body:"The fastest buyer is often already in someone’s database. Your listing goes directly to my buyers, past clients, and referral partners — and to the agents actively working your price range.",enabled:!0,order:6,options:[hd("database","Direct email to my buyer and past-client database"),hd("agents","Broadcast to area agents with matching buyers"),hd("referral","Referral partner network notified at launch"),hd("followup","Follow-up sequence to everyone who engages")]},{key:"openhouse",title:"Open Houses & Neighborhood Marketing",body:"Neighbors sell neighborhoods. We combine well-timed open houses with the local marketing that reaches the people most likely to know your next buyer.",enabled:!0,order:7,options:[hd("public","Strategically timed public open houses"),hd("broker","Broker open house for agents with active buyers"),hd("signin","Digital sign-in that captures every visitor"),hd("neighbors","Neighbor invitations and just-listed mailers"),hd("signage","Premium signage, riders, and directional placement")]},{key:"communication",title:"Communication & Weekly Reporting",body:"You will never wonder what is happening. You get a regular seller report with showing feedback, online traffic numbers, and market shifts, plus direct access to me by call, text, or email.",enabled:!0,order:8,options:[hd("weekly","Weekly seller report on the schedule you prefer"),hd("feedback","Showing feedback delivered as it comes in"),hd("analytics","Online traffic and engagement analytics"),hd("access","Direct access to me by call, text, or email")]}],S3n=Object.fromEntries(z4e.map(s=>[s.key,(s.options||[]).map(t=>t.label)]));function x$e(s){return s!=null&&s.length?z4e.map(t=>{var a;const n=s.find(i=>i.key===t.key);if(!n)return{...t,options:(a=t.options)==null?void 0:a.map(i=>({...i}))};const r=(t.options||[]).map(i=>{var o;const l=(o=n.options)==null?void 0:o.find(c=>c.key===i.key);return l?{...i,enabled:l.enabled}:{...i}});return{...t,title:n.title||t.title,body:n.body||t.body,enabled:n.enabled,order:t.order,options:r}}):z4e.map(t=>{var n;return{...t,options:(n=t.options)==null?void 0:n.map(r=>({...r}))}})}const C3n={welcome:"Marketing commitment",agent:"About your agent",overview:"Marketing plan overview",closing:"Closing commitment"};function Rh(s){"@babel/helpers - typeof";return Rh=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},Rh(s)}var wk=Uint8Array,Ww=Uint16Array,zXe=Int32Array,BXe=new wk([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]),$Xe=new wk([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]),J0t=new wk([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),pBt=function(s,t){for(var n=new Ww(31),r=0;r<31;++r)n[r]=t+=1<>1|(_f&21845)<<1;HA=(HA&52428)>>2|(HA&13107)<<2,HA=(HA&61680)>>4|(HA&3855)<<4,v$e[_f]=((HA&65280)>>8|(HA&255)<<8)>>1}var nZ=function(s,t,n){for(var r=s.length,a=0,i=new Ww(t);a>c]=d}else for(o=new Ww(r),a=0;a>15-s[a]);return o},tF=new wk(288);for(var _f=0;_f<144;++_f)tF[_f]=8;for(var _f=144;_f<256;++_f)tF[_f]=9;for(var _f=256;_f<280;++_f)tF[_f]=7;for(var _f=280;_f<288;++_f)tF[_f]=8;var B4e=new wk(32);for(var _f=0;_f<32;++_f)B4e[_f]=5;var T3n=nZ(tF,9,0),M3n=nZ(B4e,5,0),xBt=function(s){return(s+7)/8|0},P3n=function(s,t,n){return(n==null||n>s.length)&&(n=s.length),new wk(s.subarray(t,n))},Q4=function(s,t,n){n<<=t&7;var r=t/8|0;s[r]|=n,s[r+1]|=n>>8},OG=function(s,t,n){n<<=t&7;var r=t/8|0;s[r]|=n,s[r+1]|=n>>8,s[r+2]|=n>>16},mDe=function(s,t){for(var n=[],r=0;rm&&(m=i[r].s);var p=new Ww(m+1),g=b$e(n[u-1],p,0);if(g>t){var r=0,x=0,y=g-t,v=1<t)x+=v-(1<>=y;x>0;){var j=i[r].s;p[j]=0&&x;--r){var C=i[r].s;p[C]==t&&(--p[C],++x)}g=t}return{t:new wk(p),l:g}},b$e=function(s,t,n){return s.s==-1?Math.max(b$e(s.l,t,n+1),b$e(s.r,t,n+1)):t[s.s]=n},tvt=function(s){for(var t=s.length;t&&!s[--t];);for(var n=new Ww(++t),r=0,a=s[0],i=1,l=function(c){n[r++]=c},o=1;o<=t;++o)if(s[o]==a&&o!=t)++i;else{if(!a&&i>2){for(;i>138;i-=138)l(32754);i>2&&(l(i>10?i-11<<5|28690:i-3<<5|12305),i=0)}else if(i>3){for(l(a),--i;i>6;i-=6)l(8304);i>2&&(l(i-3<<5|8208),i=0)}for(;i--;)l(a);i=1,a=s[o]}return{c:n.subarray(0,r),n:t}},FG=function(s,t){for(var n=0,r=0;r>8,s[a+2]=s[a]^255,s[a+3]=s[a+1]^255;for(var i=0;i4&&!O[J0t[U-1]];--U);var G=d+5<<3,H=FG(a,tF)+FG(i,B4e)+l,Y=FG(a,m)+FG(i,x)+l+14+3*U+FG(I,O)+2*I[16]+3*I[17]+7*I[18];if(c>=0&&G<=H&&G<=Y)return yBt(t,u,s.subarray(c,c+d));var se,ee,oe,me;if(Q4(t,u,1+(Y15&&(Q4(t,u,fe[P]>>5&127),u+=fe[P]>>12)}}else se=T3n,ee=tF,oe=M3n,me=B4e;for(var P=0;P255){var _e=ve>>18&31;OG(t,u,se[_e+257]),u+=ee[_e+257],_e>7&&(Q4(t,u,ve>>23&31),u+=BXe[_e]);var he=ve&31;OG(t,u,oe[he]),u+=me[he],he>3&&(OG(t,u,ve>>5&8191),u+=$Xe[he])}else OG(t,u,se[ve]),u+=ee[ve]}return OG(t,u,se[256]),u+ee[256]},I3n=new zXe([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),vBt=new wk(0),L3n=function(s,t,n,r,a,i){var l=i.z||s.length,o=new wk(r+l+5*(1+Math.ceil(l/7e3))+a),c=o.subarray(r,o.length-a),d=i.l,u=(i.r||0)&7;if(t){u&&(c[0]=i.r>>3);for(var h=I3n[t-1],m=h>>13,p=h&8191,g=(1<7e3||O>24576)&&(se>423||!d)){u=svt(s,c,0,C,A,M,P,O,U,R-U,u),O=I=P=0,U=R;for(var ee=0;ee<286;++ee)A[ee]=0;for(var ee=0;ee<30;++ee)M[ee]=0}var oe=2,me=0,Q=p,te=H-Y&32767;if(se>2&&G==j(R-te))for(var le=Math.min(m,se)-1,fe=Math.min(32767,R),_e=Math.min(258,se);te<=fe&&--Q&&H!=Y;){if(s[R+oe]==s[R+oe-te]){for(var ve=0;ve<_e&&s[R+ve]==s[R+ve-te];++ve);if(ve>oe){if(oe=ve,me=te,ve>le)break;for(var he=Math.min(te,ve-2),Se=0,ee=0;eeSe&&(Se=Ue,Y=Te)}}}H=Y,Y=x[H],te+=H-Y&32767}if(me){C[O++]=268435456|y$e[oe]<<18|evt[me];var Be=y$e[oe]&31,je=evt[me]&31;P+=BXe[Be]+$Xe[je],++A[257+Be],++M[je],B=R+oe,++I}else C[O++]=s[R],++A[s[R]]}}for(R=Math.max(R,B);R=l&&(c[u/8|0]=d,Ye=l),u=yBt(c,u+1,s.subarray(R,Ye))}i.i=l}return P3n(o,0,r+xBt(u)+a)},bBt=function(){var s=1,t=0;return{p:function(n){for(var r=s,a=t,i=n.length|0,l=0;l!=i;){for(var o=Math.min(l+2655,i);l>16),a=(a&65535)+15*(a>>16)}s=r,t=a},d:function(){return s%=65521,t%=65521,(s&255)<<24|(s&65280)<<8|(t&255)<<8|t>>8}}},R3n=function(s,t,n,r,a){if(!a&&(a={l:1},t.dictionary)){var i=t.dictionary.subarray(-32768),l=new wk(i.length+s.length);l.set(i),l.set(s,i.length),s=l,a.w=i.length}return L3n(s,t.level==null?6:t.level,t.mem==null?a.l?Math.ceil(Math.max(8,Math.min(13,Math.log(s.length)))*1.5):20:12+t.mem,n,r,a)},_Bt=function(s,t,n){for(;n;++t)s[t]=n,n>>>=8},D3n=function(s,t){var n=t.level,r=n==0?0:n<6?1:n==9?3:2;if(s[0]=120,s[1]=r<<6|(t.dictionary&&32),s[1]|=31-(s[0]<<8|s[1])%31,t.dictionary){var a=bBt();a.p(t.dictionary),_Bt(s,2,a.d())}};function _$e(s,t){t||(t={});var n=bBt();n.p(s);var r=R3n(s,t,t.dictionary?6:2,4);return D3n(r,t),_Bt(r,r.length-4,n.d()),r}var O3n=typeof TextDecoder<"u"&&new TextDecoder,F3n=0;try{O3n.decode(vBt,{stream:!0}),F3n=1}catch{}function z3n(s){if(Array.isArray(s))return s}function B3n(s,t){var n=s==null?null:typeof Symbol<"u"&&s[Symbol.iterator]||s["@@iterator"];if(n!=null){var r,a,i,l,o=[],c=!0,d=!1;try{if(i=(n=n.call(s)).next,t!==0)for(;!(c=(r=i.call(n)).done)&&(o.push(r.value),o.length!==t);c=!0);}catch(u){d=!0,a=u}finally{try{if(!c&&n.return!=null&&(l=n.return(),Object(l)!==l))return}finally{if(d)throw a}}return o}}function nvt(s,t){(t==null||t>s.length)&&(t=s.length);for(var n=0,r=Array(t);n{const s=new Uint8Array(4),t=new Uint32Array(s.buffer);return!((t[0]=1)&s[0])})(),fDe={int8:globalThis.Int8Array,uint8:globalThis.Uint8Array,int16:globalThis.Int16Array,uint16:globalThis.Uint16Array,int32:globalThis.Int32Array,uint32:globalThis.Uint32Array,uint64:globalThis.BigUint64Array,int64:globalThis.BigInt64Array,float32:globalThis.Float32Array,float64:globalThis.Float64Array};class UXe{constructor(t=H3n,n={}){ur(this,"buffer");ur(this,"byteLength");ur(this,"byteOffset");ur(this,"length");ur(this,"offset");ur(this,"lastWrittenByte");ur(this,"littleEndian");ur(this,"_data");ur(this,"_mark");ur(this,"_marks");let r=!1;typeof t=="number"?t=new ArrayBuffer(t):(r=!0,this.lastWrittenByte=t.byteLength);const a=n.offset?n.offset>>>0:0,i=t.byteLength-a;let l=a;(ArrayBuffer.isView(t)||t instanceof UXe)&&(t.byteLength!==t.buffer.byteLength&&(l=t.byteOffset+a),t=t.buffer),r?this.lastWrittenByte=i:this.lastWrittenByte=0,this.buffer=t,this.length=i,this.byteLength=i,this.byteOffset=l,this.offset=0,this.littleEndian=!0,this._data=new DataView(this.buffer,l,i),this._mark=0,this._marks=[]}available(t=1){return this.offset+t<=this.length}isLittleEndian(){return this.littleEndian}setLittleEndian(){return this.littleEndian=!0,this}isBigEndian(){return!this.littleEndian}setBigEndian(){return this.littleEndian=!1,this}skip(t=1){return this.offset+=t,this}back(t=1){return this.offset-=t,this}seek(t){return this.offset=t,this}mark(){return this._mark=this.offset,this}reset(){return this.offset=this._mark,this}pushMark(){return this._marks.push(this.offset),this}popMark(){const t=this._marks.pop();if(t===void 0)throw new Error("Mark stack empty");return this.seek(t),this}rewind(){return this.offset=0,this}ensureAvailable(t=1){if(!this.available(t)){const r=(this.offset+t)*2,a=new Uint8Array(r);a.set(new Uint8Array(this.buffer)),this.buffer=a.buffer,this.length=r,this.byteLength=r,this._data=new DataView(this.buffer)}return this}readBoolean(){return this.readUint8()!==0}readInt8(){return this._data.getInt8(this.offset++)}readUint8(){return this._data.getUint8(this.offset++)}readByte(){return this.readUint8()}readBytes(t=1){return this.readArray(t,"uint8")}readArray(t,n){const r=fDe[n].BYTES_PER_ELEMENT*t,a=this.byteOffset+this.offset,i=this.buffer.slice(a,a+r);if(this.littleEndian===G3n&&n!=="uint8"&&n!=="int8"){const o=new Uint8Array(this.buffer.slice(a,a+r));o.reverse();const c=new fDe[n](o.buffer);return this.offset+=r,c.reverse(),c}const l=new fDe[n](i);return this.offset+=r,l}readInt16(){const t=this._data.getInt16(this.offset,this.littleEndian);return this.offset+=2,t}readUint16(){const t=this._data.getUint16(this.offset,this.littleEndian);return this.offset+=2,t}readInt32(){const t=this._data.getInt32(this.offset,this.littleEndian);return this.offset+=4,t}readUint32(){const t=this._data.getUint32(this.offset,this.littleEndian);return this.offset+=4,t}readFloat32(){const t=this._data.getFloat32(this.offset,this.littleEndian);return this.offset+=4,t}readFloat64(){const t=this._data.getFloat64(this.offset,this.littleEndian);return this.offset+=8,t}readBigInt64(){const t=this._data.getBigInt64(this.offset,this.littleEndian);return this.offset+=8,t}readBigUint64(){const t=this._data.getBigUint64(this.offset,this.littleEndian);return this.offset+=8,t}readChar(){return String.fromCharCode(this.readInt8())}readChars(t=1){let n="";for(let r=0;rthis.lastWrittenByte&&(this.lastWrittenByte=this.offset)}}function UV(s){let t=s.length;for(;--t>=0;)s[t]=0}const W3n=3,K3n=258,wBt=29,Y3n=256,Z3n=Y3n+1+wBt,jBt=30,X3n=512,Q3n=new Array((Z3n+2)*2);UV(Q3n);const J3n=new Array(jBt*2);UV(J3n);const eAn=new Array(X3n);UV(eAn);const tAn=new Array(K3n-W3n+1);UV(tAn);const sAn=new Array(wBt);UV(sAn);const nAn=new Array(jBt);UV(nAn);const rAn=(s,t,n,r)=>{let a=s&65535|0,i=s>>>16&65535|0,l=0;for(;n!==0;){l=n>2e3?2e3:n,n-=l;do a=a+t[r++]|0,i=i+a|0;while(--l);a%=65521,i%=65521}return a|i<<16|0};var w$e=rAn;const aAn=()=>{let s,t=[];for(var n=0;n<256;n++){s=n;for(var r=0;r<8;r++)s=s&1?3988292384^s>>>1:s>>>1;t[n]=s}return t},iAn=new Uint32Array(aAn()),oAn=(s,t,n,r)=>{const a=iAn,i=r+n;s^=-1;for(let l=r;l>>8^a[(s^t[l])&255];return s^-1};var mS=oAn,j$e={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"},NBt={Z_NO_FLUSH:0,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_DEFLATED:8};const lAn=(s,t)=>Object.prototype.hasOwnProperty.call(s,t);var cAn=function(s){const t=Array.prototype.slice.call(arguments,1);for(;t.length;){const n=t.shift();if(n){if(typeof n!="object")throw new TypeError(n+"must be non-object");for(const r in n)lAn(n,r)&&(s[r]=n[r])}}return s},dAn=s=>{let t=0;for(let r=0,a=s.length;r=252?6:s>=248?5:s>=240?4:s>=224?3:s>=192?2:1;uQ[254]=uQ[255]=1;var uAn=s=>{if(typeof TextEncoder=="function"&&TextEncoder.prototype.encode)return new TextEncoder().encode(s);let t,n,r,a,i,l=s.length,o=0;for(a=0;a>>6,t[i++]=128|n&63):n<65536?(t[i++]=224|n>>>12,t[i++]=128|n>>>6&63,t[i++]=128|n&63):(t[i++]=240|n>>>18,t[i++]=128|n>>>12&63,t[i++]=128|n>>>6&63,t[i++]=128|n&63);return t};const hAn=(s,t)=>{if(t<65534&&s.subarray&&SBt)return String.fromCharCode.apply(null,s.length===t?s:s.subarray(0,t));let n="";for(let r=0;r{const n=t||s.length;if(typeof TextDecoder=="function"&&TextDecoder.prototype.decode)return new TextDecoder().decode(s.subarray(0,t));let r,a;const i=new Array(n*2);for(a=0,r=0;r4){i[a++]=65533,r+=o-1;continue}for(l&=o===2?31:o===3?15:7;o>1&&r1){i[a++]=65533;continue}l<65536?i[a++]=l:(l-=65536,i[a++]=55296|l>>10&1023,i[a++]=56320|l&1023)}return hAn(i,a)},fAn=(s,t)=>{t=t||s.length,t>s.length&&(t=s.length);let n=t-1;for(;n>=0&&(s[n]&192)===128;)n--;return n<0||n===0?t:n+uQ[s[n]]>t?n:t},N$e={string2buf:uAn,buf2string:mAn,utf8border:fAn};function pAn(){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}var gAn=pAn;const Pae=16209,xAn=16191;var yAn=function(t,n){let r,a,i,l,o,c,d,u,h,m,p,g,x,y,v,_,j,C,A,M,I,P,R,O;const B=t.state;r=t.next_in,R=t.input,a=r+(t.avail_in-5),i=t.next_out,O=t.output,l=i-(n-t.avail_out),o=i+(t.avail_out-257),c=B.dmax,d=B.wsize,u=B.whave,h=B.wnext,m=B.window,p=B.hold,g=B.bits,x=B.lencode,y=B.distcode,v=(1<>>24,p>>>=C,g-=C,C=j>>>16&255,C===0)O[i++]=j&65535;else if(C&16){A=j&65535,C&=15,C&&(g>>=C,g-=C),g<15&&(p+=R[r++]<>>24,p>>>=C,g-=C,C=j>>>16&255,C&16){if(M=j&65535,C&=15,gc){t.msg="invalid distance too far back",B.mode=Pae;break e}if(p>>>=C,g-=C,C=i-l,M>C){if(C=M-C,C>u&&B.sane){t.msg="invalid distance too far back",B.mode=Pae;break e}if(I=0,P=m,h===0){if(I+=d-C,C2;)O[i++]=P[I++],O[i++]=P[I++],O[i++]=P[I++],A-=3;A&&(O[i++]=P[I++],A>1&&(O[i++]=P[I++]))}else{I=i-M;do O[i++]=O[I++],O[i++]=O[I++],O[i++]=O[I++],A-=3;while(A>2);A&&(O[i++]=O[I++],A>1&&(O[i++]=O[I++]))}}else if(C&64){t.msg="invalid distance code",B.mode=Pae;break e}else{j=y[(j&65535)+(p&(1<>3,r-=A,g-=A<<3,p&=(1<{const c=o.bits;let d=0,u=0,h=0,m=0,p=0,g=0,x=0,y=0,v=0,_=0,j,C,A,M,I,P=null,R;const O=new Uint16Array(d9+1),B=new Uint16Array(d9+1);let U=null,G,H,Y;for(d=0;d<=d9;d++)O[d]=0;for(u=0;u=1&&O[m]===0;m--);if(p>m&&(p=m),m===0)return a[i++]=1<<24|64<<16|0,a[i++]=1<<24|64<<16|0,o.bits=1,0;for(h=1;h0&&(s===lvt||m!==1))return-1;for(B[1]=0,d=1;divt||s===cvt&&v>ovt)return 1;for(;;){G=d-x,l[u]+1=R?(H=U[l[u]-R],Y=P[l[u]-R]):(H=96,Y=0),j=1<>x)+C]=G<<24|H<<16|Y|0;while(C!==0);for(j=1<>=1;if(j!==0?(_&=j-1,_+=j):_=0,u++,--O[d]===0){if(d===m)break;d=t[n+l[u]]}if(d>p&&(_&M)!==A){for(x===0&&(x=p),I+=h,g=d-x,y=1<ivt||s===cvt&&v>ovt)return 1;A=_&M,a[A]=p<<24|g<<16|I-i|0}}return _!==0&&(a[I+_]=d-x<<24|64<<16|0),o.bits=p,0};var rZ=jAn;const NAn=0,CBt=1,ABt=2,{Z_FINISH:dvt,Z_BLOCK:kAn,Z_TREES:Iae,Z_OK:sF,Z_STREAM_END:SAn,Z_NEED_DICT:CAn,Z_STREAM_ERROR:O2,Z_DATA_ERROR:EBt,Z_MEM_ERROR:TBt,Z_BUF_ERROR:AAn,Z_DEFLATED:uvt}=NBt,MTe=16180,hvt=16181,mvt=16182,fvt=16183,pvt=16184,gvt=16185,xvt=16186,yvt=16187,vvt=16188,bvt=16189,$4e=16190,J4=16191,gDe=16192,_vt=16193,xDe=16194,wvt=16195,jvt=16196,Nvt=16197,kvt=16198,Lae=16199,Rae=16200,Svt=16201,Cvt=16202,Avt=16203,Evt=16204,Tvt=16205,yDe=16206,Mvt=16207,Pvt=16208,Vf=16209,MBt=16210,PBt=16211,EAn=852,TAn=592,MAn=15,PAn=MAn,Ivt=s=>(s>>>24&255)+(s>>>8&65280)+((s&65280)<<8)+((s&255)<<24);function IAn(){this.strm=null,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 Uint16Array(320),this.work=new Uint16Array(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}const VF=s=>{if(!s)return 1;const t=s.state;return!t||t.strm!==s||t.modePBt?1:0},IBt=s=>{if(VF(s))return O2;const t=s.state;return s.total_in=s.total_out=t.total=0,s.msg="",t.wrap&&(s.adler=t.wrap&1),t.mode=MTe,t.last=0,t.havedict=0,t.flags=-1,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new Int32Array(EAn),t.distcode=t.distdyn=new Int32Array(TAn),t.sane=1,t.back=-1,sF},LBt=s=>{if(VF(s))return O2;const t=s.state;return t.wsize=0,t.whave=0,t.wnext=0,IBt(s)},RBt=(s,t)=>{let n;if(VF(s))return O2;const r=s.state;return t<0?(n=0,t=-t):(n=(t>>4)+5,t<48&&(t&=15)),t&&(t<8||t>15)?O2:(r.window!==null&&r.wbits!==t&&(r.window=null),r.wrap=n,r.wbits=t,LBt(s))},DBt=(s,t)=>{if(!s)return O2;const n=new IAn;s.state=n,n.strm=s,n.window=null,n.mode=MTe;const r=RBt(s,t);return r!==sF&&(s.state=null),r},LAn=s=>DBt(s,PAn);let Lvt=!0,vDe,bDe;const RAn=s=>{if(Lvt){vDe=new Int32Array(512),bDe=new Int32Array(32);let t=0;for(;t<144;)s.lens[t++]=8;for(;t<256;)s.lens[t++]=9;for(;t<280;)s.lens[t++]=7;for(;t<288;)s.lens[t++]=8;for(rZ(CBt,s.lens,0,288,vDe,0,s.work,{bits:9}),t=0;t<32;)s.lens[t++]=5;rZ(ABt,s.lens,0,32,bDe,0,s.work,{bits:5}),Lvt=!1}s.lencode=vDe,s.lenbits=9,s.distcode=bDe,s.distbits=5},OBt=(s,t,n,r)=>{let a;const i=s.state;return i.window===null&&(i.window=new Uint8Array(1<=i.wsize?(i.window.set(t.subarray(n-i.wsize,n),0),i.wnext=0,i.whave=i.wsize):(a=i.wsize-i.wnext,a>r&&(a=r),i.window.set(t.subarray(n-r,n-r+a),i.wnext),r-=a,r?(i.window.set(t.subarray(n-r,n),0),i.wnext=r,i.whave=i.wsize):(i.wnext+=a,i.wnext===i.wsize&&(i.wnext=0),i.whave{let n,r,a,i,l,o,c,d,u,h,m,p,g,x,y=0,v,_,j,C,A,M,I,P;const R=new Uint8Array(4);let O,B;const U=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);if(VF(s)||!s.output||!s.input&&s.avail_in!==0)return O2;n=s.state,n.mode===J4&&(n.mode=gDe),l=s.next_out,a=s.output,c=s.avail_out,i=s.next_in,r=s.input,o=s.avail_in,d=n.hold,u=n.bits,h=o,m=c,P=sF;e:for(;;)switch(n.mode){case MTe:if(n.wrap===0){n.mode=gDe;break}for(;u<16;){if(o===0)break e;o--,d+=r[i++]<>>8&255,n.check=mS(n.check,R,2,0),d=0,u=0,n.mode=hvt;break}if(n.head&&(n.head.done=!1),!(n.wrap&1)||(((d&255)<<8)+(d>>8))%31){s.msg="incorrect header check",n.mode=Vf;break}if((d&15)!==uvt){s.msg="unknown compression method",n.mode=Vf;break}if(d>>>=4,u-=4,I=(d&15)+8,n.wbits===0&&(n.wbits=I),I>15||I>n.wbits){s.msg="invalid window size",n.mode=Vf;break}n.dmax=1<>8&1),n.flags&512&&n.wrap&4&&(R[0]=d&255,R[1]=d>>>8&255,n.check=mS(n.check,R,2,0)),d=0,u=0,n.mode=mvt;case mvt:for(;u<32;){if(o===0)break e;o--,d+=r[i++]<>>8&255,R[2]=d>>>16&255,R[3]=d>>>24&255,n.check=mS(n.check,R,4,0)),d=0,u=0,n.mode=fvt;case fvt:for(;u<16;){if(o===0)break e;o--,d+=r[i++]<>8),n.flags&512&&n.wrap&4&&(R[0]=d&255,R[1]=d>>>8&255,n.check=mS(n.check,R,2,0)),d=0,u=0,n.mode=pvt;case pvt:if(n.flags&1024){for(;u<16;){if(o===0)break e;o--,d+=r[i++]<>>8&255,n.check=mS(n.check,R,2,0)),d=0,u=0}else n.head&&(n.head.extra=null);n.mode=gvt;case gvt:if(n.flags&1024&&(p=n.length,p>o&&(p=o),p&&(n.head&&(I=n.head.extra_len-n.length,n.head.extra||(n.head.extra=new Uint8Array(n.head.extra_len)),n.head.extra.set(r.subarray(i,i+p),I)),n.flags&512&&n.wrap&4&&(n.check=mS(n.check,r,p,i)),o-=p,i+=p,n.length-=p),n.length))break e;n.length=0,n.mode=xvt;case xvt:if(n.flags&2048){if(o===0)break e;p=0;do I=r[i+p++],n.head&&I&&n.length<65536&&(n.head.name+=String.fromCharCode(I));while(I&&p>9&1,n.head.done=!0),s.adler=n.check=0,n.mode=J4;break;case bvt:for(;u<32;){if(o===0)break e;o--,d+=r[i++]<>>=u&7,u-=u&7,n.mode=yDe;break}for(;u<3;){if(o===0)break e;o--,d+=r[i++]<>>=1,u-=1,d&3){case 0:n.mode=_vt;break;case 1:if(RAn(n),n.mode=Lae,t===Iae){d>>>=2,u-=2;break e}break;case 2:n.mode=jvt;break;case 3:s.msg="invalid block type",n.mode=Vf}d>>>=2,u-=2;break;case _vt:for(d>>>=u&7,u-=u&7;u<32;){if(o===0)break e;o--,d+=r[i++]<>>16^65535)){s.msg="invalid stored block lengths",n.mode=Vf;break}if(n.length=d&65535,d=0,u=0,n.mode=xDe,t===Iae)break e;case xDe:n.mode=wvt;case wvt:if(p=n.length,p){if(p>o&&(p=o),p>c&&(p=c),p===0)break e;a.set(r.subarray(i,i+p),l),o-=p,i+=p,c-=p,l+=p,n.length-=p;break}n.mode=J4;break;case jvt:for(;u<14;){if(o===0)break e;o--,d+=r[i++]<>>=5,u-=5,n.ndist=(d&31)+1,d>>>=5,u-=5,n.ncode=(d&15)+4,d>>>=4,u-=4,n.nlen>286||n.ndist>30){s.msg="too many length or distance symbols",n.mode=Vf;break}n.have=0,n.mode=Nvt;case Nvt:for(;n.have>>=3,u-=3}for(;n.have<19;)n.lens[U[n.have++]]=0;if(n.lencode=n.lendyn,n.lenbits=7,O={bits:n.lenbits},P=rZ(NAn,n.lens,0,19,n.lencode,0,n.work,O),n.lenbits=O.bits,P){s.msg="invalid code lengths set",n.mode=Vf;break}n.have=0,n.mode=kvt;case kvt:for(;n.have>>24,_=y>>>16&255,j=y&65535,!(v<=u);){if(o===0)break e;o--,d+=r[i++]<>>=v,u-=v,n.lens[n.have++]=j;else{if(j===16){for(B=v+2;u>>=v,u-=v,n.have===0){s.msg="invalid bit length repeat",n.mode=Vf;break}I=n.lens[n.have-1],p=3+(d&3),d>>>=2,u-=2}else if(j===17){for(B=v+3;u>>=v,u-=v,I=0,p=3+(d&7),d>>>=3,u-=3}else{for(B=v+7;u>>=v,u-=v,I=0,p=11+(d&127),d>>>=7,u-=7}if(n.have+p>n.nlen+n.ndist){s.msg="invalid bit length repeat",n.mode=Vf;break}for(;p--;)n.lens[n.have++]=I}}if(n.mode===Vf)break;if(n.lens[256]===0){s.msg="invalid code -- missing end-of-block",n.mode=Vf;break}if(n.lenbits=9,O={bits:n.lenbits},P=rZ(CBt,n.lens,0,n.nlen,n.lencode,0,n.work,O),n.lenbits=O.bits,P){s.msg="invalid literal/lengths set",n.mode=Vf;break}if(n.distbits=6,n.distcode=n.distdyn,O={bits:n.distbits},P=rZ(ABt,n.lens,n.nlen,n.ndist,n.distcode,0,n.work,O),n.distbits=O.bits,P){s.msg="invalid distances set",n.mode=Vf;break}if(n.mode=Lae,t===Iae)break e;case Lae:n.mode=Rae;case Rae:if(o>=6&&c>=258){s.next_out=l,s.avail_out=c,s.next_in=i,s.avail_in=o,n.hold=d,n.bits=u,yAn(s,m),l=s.next_out,a=s.output,c=s.avail_out,i=s.next_in,r=s.input,o=s.avail_in,d=n.hold,u=n.bits,n.mode===J4&&(n.back=-1);break}for(n.back=0;y=n.lencode[d&(1<>>24,_=y>>>16&255,j=y&65535,!(v<=u);){if(o===0)break e;o--,d+=r[i++]<>C)],v=y>>>24,_=y>>>16&255,j=y&65535,!(C+v<=u);){if(o===0)break e;o--,d+=r[i++]<>>=C,u-=C,n.back+=C}if(d>>>=v,u-=v,n.back+=v,n.length=j,_===0){n.mode=Tvt;break}if(_&32){n.back=-1,n.mode=J4;break}if(_&64){s.msg="invalid literal/length code",n.mode=Vf;break}n.extra=_&15,n.mode=Svt;case Svt:if(n.extra){for(B=n.extra;u>>=n.extra,u-=n.extra,n.back+=n.extra}n.was=n.length,n.mode=Cvt;case Cvt:for(;y=n.distcode[d&(1<>>24,_=y>>>16&255,j=y&65535,!(v<=u);){if(o===0)break e;o--,d+=r[i++]<>C)],v=y>>>24,_=y>>>16&255,j=y&65535,!(C+v<=u);){if(o===0)break e;o--,d+=r[i++]<>>=C,u-=C,n.back+=C}if(d>>>=v,u-=v,n.back+=v,_&64){s.msg="invalid distance code",n.mode=Vf;break}n.offset=j,n.extra=_&15,n.mode=Avt;case Avt:if(n.extra){for(B=n.extra;u>>=n.extra,u-=n.extra,n.back+=n.extra}if(n.offset>n.dmax){s.msg="invalid distance too far back",n.mode=Vf;break}n.mode=Evt;case Evt:if(c===0)break e;if(p=m-c,n.offset>p){if(p=n.offset-p,p>n.whave&&n.sane){s.msg="invalid distance too far back",n.mode=Vf;break}p>n.wnext?(p-=n.wnext,g=n.wsize-p):g=n.wnext-p,p>n.length&&(p=n.length),x=n.window}else x=a,g=l-n.offset,p=n.length;p>c&&(p=c),c-=p,n.length-=p;do a[l++]=x[g++];while(--p);n.length===0&&(n.mode=Rae);break;case Tvt:if(c===0)break e;a[l++]=n.length,c--,n.mode=Rae;break;case yDe:if(n.wrap){for(;u<32;){if(o===0)break e;o--,d|=r[i++]<{if(VF(s))return O2;let t=s.state;return t.window&&(t.window=null),s.state=null,sF},FAn=(s,t)=>{if(VF(s))return O2;const n=s.state;return n.wrap&2?(n.head=t,t.done=!1,sF):O2},zAn=(s,t)=>{const n=t.length;let r,a,i;return VF(s)||(r=s.state,r.wrap!==0&&r.mode!==$4e)?O2:r.mode===$4e&&(a=1,a=w$e(a,t,n,0),a!==r.check)?EBt:(i=OBt(s,t,n,n),i?(r.mode=MBt,TBt):(r.havedict=1,sF))};var BAn=LBt,$An=RBt,UAn=IBt,qAn=LAn,VAn=DBt,HAn=DAn,GAn=OAn,WAn=FAn,KAn=zAn,YAn="pako inflate (from Nodeca project)",IS={inflateReset:BAn,inflateReset2:$An,inflateResetKeep:UAn,inflateInit:qAn,inflateInit2:VAn,inflate:HAn,inflateEnd:GAn,inflateGetHeader:WAn,inflateSetDictionary:KAn,inflateInfo:YAn};function ZAn(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}var XAn=ZAn;const FBt=Object.prototype.toString,{Z_NO_FLUSH:QAn,Z_FINISH:Rvt,Z_OK:DB,Z_STREAM_END:_De,Z_NEED_DICT:wDe,Z_STREAM_ERROR:JAn,Z_DATA_ERROR:Dvt,Z_MEM_ERROR:eEn,Z_BUF_ERROR:Ovt}=NBt,tEn={chunkSize:1024*64,windowBits:15,to:""};function mte(s){this.options=kBt.assign({},tEn,s||{});const t=this.options;t.raw&&t.windowBits>=0&&t.windowBits<16&&(t.windowBits=-t.windowBits,t.windowBits===0&&(t.windowBits=-15)),t.windowBits>=0&&t.windowBits<16&&!(s&&s.windowBits)&&(t.windowBits+=32),t.windowBits>15&&t.windowBits<48&&(t.windowBits&15||(t.windowBits|=15)),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new gAn,this.strm.avail_out=0;let n=IS.inflateInit2(this.strm,t.windowBits);if(n!==DB)throw new Error(j$e[n]);if(this.header=new XAn,IS.inflateGetHeader(this.strm,this.header),t.dictionary&&(typeof t.dictionary=="string"?t.dictionary=N$e.string2buf(t.dictionary):FBt.call(t.dictionary)==="[object ArrayBuffer]"&&(t.dictionary=new Uint8Array(t.dictionary)),t.raw&&(n=IS.inflateSetDictionary(this.strm,t.dictionary),n!==DB)))throw new Error(j$e[n])}mte.prototype.push=function(s,t){const n=this.strm,r=this.options.chunkSize,a=this.options.dictionary;let i,l,o;if(this.ended)return!1;for(t===~~t?l=t:l=t===!0?Rvt:QAn,FBt.call(s)==="[object ArrayBuffer]"?n.input=new Uint8Array(s):n.input=s,n.next_in=0,n.avail_in=n.input.length;;){for(n.avail_out===0&&(n.output=new Uint8Array(r),n.next_out=0,n.avail_out=r),i=IS.inflate(n,l),i===wDe&&a&&(i=IS.inflateSetDictionary(n,a),i===DB?i=IS.inflate(n,l):i===Dvt&&(i=wDe));n.avail_in>0&&i===_De&&n.state.wrap&2&&n.state.flags!==0&&n.input[n.next_in]!==0;)IS.inflateReset(n),i=IS.inflate(n,l);switch(i){case JAn:case Dvt:case wDe:case eEn:return this.onEnd(i),this.ended=!0,!1}if(o=n.avail_out,n.next_out&&(n.avail_out===0||i===_De||l>0))if(this.options.to==="string"){let c=N$e.utf8border(n.output,n.next_out),d=n.next_out-c,u=N$e.buf2string(n.output,c);n.next_out=d,n.avail_out=r-d,d&&n.output.set(n.output.subarray(c,c+d),0),this.onData(u)}else this.onData(n.output.length===n.next_out?n.output:n.output.subarray(0,n.next_out)),n.avail_out=0,n.next_out=0;if(!((i===DB||i===Ovt)&&o===0)){if(i===_De)return i=IS.inflateEnd(this.strm),this.onEnd(i),this.ended=!0,!0;if(n.avail_in===0){if(l===Rvt)return i=IS.inflateEnd(this.strm),this.onEnd(i===DB?Ovt:i),this.ended=!0,!1;break}}}return!0};mte.prototype.onData=function(s){this.chunks.push(s)};mte.prototype.onEnd=function(s){s===DB&&(this.options.to==="string"?this.result=this.chunks.join(""):this.result=kBt.flattenChunks(this.chunks)),this.chunks=[],this.err=s,this.msg=this.strm.msg};function sEn(s,t){const n=new mte(t);if(n.push(s,!0),n.err)throw n.msg||j$e[n.err];return n.result}var nEn=mte,rEn=sEn,aEn={Inflate:nEn,inflate:rEn};const{Inflate:iEn,inflate:oEn}=aEn;var Fvt=iEn,lEn=oEn;const zBt=[];for(let s=0;s<256;s++){let t=s;for(let n=0;n<8;n++)t&1?t=3988292384^t>>>1:t=t>>>1;zBt[s]=t}const zvt=4294967295;function cEn(s,t,n){let r=s;for(let a=0;a>>8;return r}function dEn(s,t){return(cEn(zvt,s,t)^zvt)>>>0}function Bvt(s,t,n){const r=s.readUint32(),a=dEn(new Uint8Array(s.buffer,s.byteOffset+s.offset-t-4,t),t);if(a!==r)throw new Error(`CRC mismatch for chunk ${n}. Expected ${r}, found ${a}`)}function BBt(s,t,n){for(let r=0;r>1)&255}else{for(;i>1)&255;for(;i>1)&255}}function VBt(s,t,n,r,a){let i=0;if(n.length===0){for(;i=n||M>=r))for(let I=0;I>8&255}const yEn=new Uint16Array([255]),vEn=new Uint8Array(yEn.buffer),bEn=vEn[0]===255,_En=new Uint8Array(0);function $vt(s){const{data:t,width:n,height:r,channels:a,depth:i}=s,l=Math.ceil(i/8)*a,o=Math.ceil(i/8*a*n),c=new Uint8Array(r*o);let d=_En,u=0,h,m;for(let p=0;p>8&255}const ENe=Uint8Array.of(137,80,78,71,13,10,26,10);function Uvt(s){if(!jEn(s.readBytes(ENe.length)))throw new Error("wrong PNG signature")}function jEn(s){if(s.length79)throw new Error("keyword length must be between 1 and 79")}const CEn=/^[\u0000-\u00FF]*$/;function AEn(s){if(!CEn.test(s))throw new Error("invalid latin1 text")}function EEn(s,t,n){const r=GBt(t);s[r]=TEn(t,n-r.length-1)}function GBt(s){for(s.mark();s.readByte()!==kEn;);const t=s.offset;s.reset();const n=HBt.decode(s.readBytes(t-s.offset-1));return s.skip(1),SEn(n),n}function TEn(s,t){return HBt.decode(s.readBytes(t))}const mw={UNKNOWN:-1,GREYSCALE:0,TRUECOLOUR:2,INDEXED_COLOUR:3,GREYSCALE_ALPHA:4,TRUECOLOUR_ALPHA:6},jDe={UNKNOWN:-1,DEFLATE:0},qvt={UNKNOWN:-1,ADAPTIVE:0},NDe={UNKNOWN:-1,NO_INTERLACE:0,ADAM7:1},Dae={NONE:0,BACKGROUND:1,PREVIOUS:2},kDe={SOURCE:0,OVER:1};class MEn extends UXe{constructor(n,r={}){super(n);ur(this,"_checkCrc");ur(this,"_inflator");ur(this,"_png");ur(this,"_apng");ur(this,"_end");ur(this,"_hasPalette");ur(this,"_palette");ur(this,"_hasTransparency");ur(this,"_transparency");ur(this,"_compressionMethod");ur(this,"_filterMethod");ur(this,"_interlaceMethod");ur(this,"_colorType");ur(this,"_isAnimated");ur(this,"_numberOfFrames");ur(this,"_numberOfPlays");ur(this,"_frames");ur(this,"_writingDataChunks");const{checkCrc:a=!1}=r;this._checkCrc=a,this._inflator=new Fvt,this._png={width:-1,height:-1,channels:-1,data:new Uint8Array(0),depth:1,text:{}},this._apng={width:-1,height:-1,channels:-1,depth:1,numberOfFrames:1,numberOfPlays:0,text:{},frames:[]},this._end=!1,this._hasPalette=!1,this._palette=[],this._hasTransparency=!1,this._transparency=new Uint16Array(0),this._compressionMethod=jDe.UNKNOWN,this._filterMethod=qvt.UNKNOWN,this._interlaceMethod=NDe.UNKNOWN,this._colorType=mw.UNKNOWN,this._isAnimated=!1,this._numberOfFrames=1,this._numberOfPlays=0,this._frames=[],this._writingDataChunks=!1,this.setBigEndian()}decode(){for(Uvt(this);!this._end;){const n=this.readUint32(),r=this.readChars(4);this.decodeChunk(n,r)}return this.decodeImage(),this._png}decodeApng(){for(Uvt(this);!this._end;){const n=this.readUint32(),r=this.readChars(4);this.decodeApngChunk(n,r)}return this.decodeApngImage(),this._apng}decodeChunk(n,r){const a=this.offset;switch(r){case"IHDR":this.decodeIHDR();break;case"PLTE":this.decodePLTE(n);break;case"IDAT":this.decodeIDAT(n);break;case"IEND":this._end=!0;break;case"tRNS":this.decodetRNS(n);break;case"iCCP":this.decodeiCCP(n);break;case NEn:EEn(this._png.text,this,n);break;case"pHYs":this.decodepHYs();break;default:this.skip(n);break}if(this.offset-a!==n)throw new Error(`Length mismatch while decoding chunk ${r}`);this._checkCrc?Bvt(this,n+4,r):this.skip(4)}decodeApngChunk(n,r){const a=this.offset;switch(r!=="fdAT"&&r!=="IDAT"&&this._writingDataChunks&&this.pushDataToFrame(),r){case"acTL":this.decodeACTL();break;case"fcTL":this.decodeFCTL();break;case"fdAT":this.decodeFDAT(n);break;default:this.decodeChunk(n,r),this.offset=a+n;break}if(this.offset-a!==n)throw new Error(`Length mismatch while decoding chunk ${r}`);this._checkCrc?Bvt(this,n+4,r):this.skip(4)}decodeIHDR(){const n=this._png;n.width=this.readUint32(),n.height=this.readUint32(),n.depth=PEn(this.readUint8());const r=this.readUint8();this._colorType=r;let a;switch(r){case mw.GREYSCALE:a=1;break;case mw.TRUECOLOUR:a=3;break;case mw.INDEXED_COLOUR:a=1;break;case mw.GREYSCALE_ALPHA:a=2;break;case mw.TRUECOLOUR_ALPHA:a=4;break;case mw.UNKNOWN:default:throw new Error(`Unknown color type: ${r}`)}if(this._png.channels=a,this._compressionMethod=this.readUint8(),this._compressionMethod!==jDe.DEFLATE)throw new Error(`Unsupported compression method: ${this._compressionMethod}`);this._filterMethod=this.readUint8(),this._interlaceMethod=this.readUint8()}decodeACTL(){this._numberOfFrames=this.readUint32(),this._numberOfPlays=this.readUint32(),this._isAnimated=!0}decodeFCTL(){const n={sequenceNumber:this.readUint32(),width:this.readUint32(),height:this.readUint32(),xOffset:this.readUint32(),yOffset:this.readUint32(),delayNumber:this.readUint16(),delayDenominator:this.readUint16(),disposeOp:this.readUint8(),blendOp:this.readUint8(),data:new Uint8Array(0)};this._frames.push(n)}decodePLTE(n){if(n%3!==0)throw new RangeError(`PLTE field length must be a multiple of 3. Got ${n}`);const r=n/3;this._hasPalette=!0;const a=[];this._palette=a;for(let i=0;ithis._png.width*this._png.height)throw new Error(`tRNS chunk contains more alpha values than there are pixels (${n/2} vs ${this._png.width*this._png.height})`);this._hasTransparency=!0,this._transparency=new Uint16Array(n/2);for(let r=0;rthis._palette.length)throw new Error(`tRNS chunk contains more alpha values than there are palette colors (${n} vs ${this._palette.length})`);let r=0;for(;r{const c=((l+r.yOffset)*this._png.width+r.xOffset+o)*this._png.channels,d=(l*r.width+o)*this._png.channels;return{index:c,frameIndex:d}};switch(r.blendOp){case kDe.SOURCE:for(let l=0;l=200&&t.status<=299}function Oae(s){try{s.dispatchEvent(new MouseEvent("click"))}catch{var t=document.createEvent("MouseEvents");t.initMouseEvent("click",!0,!0,window,0,0,0,80,20,!1,!1,!1,!1,0,null),s.dispatchEvent(t)}}var FR=ac.saveAs||((typeof window>"u"?"undefined":Rh(window))!=="object"||window!==ac?function(){}:typeof HTMLAnchorElement<"u"&&"download"in HTMLAnchorElement.prototype?function(s,t,n){var r=ac.URL||ac.webkitURL,a=document.createElement("a");t=t||s.name||"download",a.download=t,a.rel="noopener",typeof s=="string"?(a.href=s,a.origin!==location.origin?Hvt(a.href)?CDe(s,t,n):Oae(a,a.target="_blank"):Oae(a)):(a.href=r.createObjectURL(s),setTimeout(function(){r.revokeObjectURL(a.href)},4e4),setTimeout(function(){Oae(a)},0))}:"msSaveOrOpenBlob"in navigator?function(s,t,n){if(t=t||s.name||"download",typeof s=="string")if(Hvt(s))CDe(s,t,n);else{var r=document.createElement("a");r.href=s,r.target="_blank",setTimeout(function(){Oae(r)})}else navigator.msSaveOrOpenBlob(function(a,i){return i===void 0?i={autoBom:!1}:Rh(i)!=="object"&&(dm.warn("Deprecated: Expected third argument to be a object"),i={autoBom:!i}),i.autoBom&&/^\s*(?:text\/\S*|application\/xml|\S*\/\S*\+xml)\s*;.*charset\s*=\s*utf-8/i.test(a.type)?new Blob(["\uFEFF",a],{type:a.type}):a}(s,n),t)}:function(s,t,n,r){if((r=r||open("","_blank"))&&(r.document.title=r.document.body.innerText="downloading..."),typeof s=="string")return CDe(s,t,n);var a=s.type==="application/octet-stream",i=/constructor/i.test(ac.HTMLElement)||ac.safari,l=/CriOS\/[\d]+/.test(navigator.userAgent);if((l||a&&i)&&(typeof FileReader>"u"?"undefined":Rh(FileReader))==="object"){var o=new FileReader;o.onloadend=function(){var u=o.result;u=l?u:u.replace(/^data:[^;]*;/,"data:attachment/file;"),r?r.location.href=u:location=u,r=null},o.readAsDataURL(s)}else{var c=ac.URL||ac.webkitURL,d=c.createObjectURL(s);r?r.location=d:location.href=d,r=null,setTimeout(function(){c.revokeObjectURL(d)},4e4)}});/** * A class to parse color values * @author Stoyan Stefanov * {@link http://www.phpied.com/rgb-color-parser-in-javascript/} * @license Use it if you like it */function WBt(s){var t;s=s||"",this.ok=!1,s.charAt(0)=="#"&&(s=s.substr(1,6)),s={aliceblue:"f0f8ff",antiquewhite:"faebd7",aqua:"00ffff",aquamarine:"7fffd4",azure:"f0ffff",beige:"f5f5dc",bisque:"ffe4c4",black:"000000",blanchedalmond:"ffebcd",blue:"0000ff",blueviolet:"8a2be2",brown:"a52a2a",burlywood:"deb887",cadetblue:"5f9ea0",chartreuse:"7fff00",chocolate:"d2691e",coral:"ff7f50",cornflowerblue:"6495ed",cornsilk:"fff8dc",crimson:"dc143c",cyan:"00ffff",darkblue:"00008b",darkcyan:"008b8b",darkgoldenrod:"b8860b",darkgray:"a9a9a9",darkgreen:"006400",darkkhaki:"bdb76b",darkmagenta:"8b008b",darkolivegreen:"556b2f",darkorange:"ff8c00",darkorchid:"9932cc",darkred:"8b0000",darksalmon:"e9967a",darkseagreen:"8fbc8f",darkslateblue:"483d8b",darkslategray:"2f4f4f",darkturquoise:"00ced1",darkviolet:"9400d3",deeppink:"ff1493",deepskyblue:"00bfff",dimgray:"696969",dodgerblue:"1e90ff",feldspar:"d19275",firebrick:"b22222",floralwhite:"fffaf0",forestgreen:"228b22",fuchsia:"ff00ff",gainsboro:"dcdcdc",ghostwhite:"f8f8ff",gold:"ffd700",goldenrod:"daa520",gray:"808080",green:"008000",greenyellow:"adff2f",honeydew:"f0fff0",hotpink:"ff69b4",indianred:"cd5c5c",indigo:"4b0082",ivory:"fffff0",khaki:"f0e68c",lavender:"e6e6fa",lavenderblush:"fff0f5",lawngreen:"7cfc00",lemonchiffon:"fffacd",lightblue:"add8e6",lightcoral:"f08080",lightcyan:"e0ffff",lightgoldenrodyellow:"fafad2",lightgrey:"d3d3d3",lightgreen:"90ee90",lightpink:"ffb6c1",lightsalmon:"ffa07a",lightseagreen:"20b2aa",lightskyblue:"87cefa",lightslateblue:"8470ff",lightslategray:"778899",lightsteelblue:"b0c4de",lightyellow:"ffffe0",lime:"00ff00",limegreen:"32cd32",linen:"faf0e6",magenta:"ff00ff",maroon:"800000",mediumaquamarine:"66cdaa",mediumblue:"0000cd",mediumorchid:"ba55d3",mediumpurple:"9370d8",mediumseagreen:"3cb371",mediumslateblue:"7b68ee",mediumspringgreen:"00fa9a",mediumturquoise:"48d1cc",mediumvioletred:"c71585",midnightblue:"191970",mintcream:"f5fffa",mistyrose:"ffe4e1",moccasin:"ffe4b5",navajowhite:"ffdead",navy:"000080",oldlace:"fdf5e6",olive:"808000",olivedrab:"6b8e23",orange:"ffa500",orangered:"ff4500",orchid:"da70d6",palegoldenrod:"eee8aa",palegreen:"98fb98",paleturquoise:"afeeee",palevioletred:"d87093",papayawhip:"ffefd5",peachpuff:"ffdab9",peru:"cd853f",pink:"ffc0cb",plum:"dda0dd",powderblue:"b0e0e6",purple:"800080",red:"ff0000",rosybrown:"bc8f8f",royalblue:"4169e1",saddlebrown:"8b4513",salmon:"fa8072",sandybrown:"f4a460",seagreen:"2e8b57",seashell:"fff5ee",sienna:"a0522d",silver:"c0c0c0",skyblue:"87ceeb",slateblue:"6a5acd",slategray:"708090",snow:"fffafa",springgreen:"00ff7f",steelblue:"4682b4",tan:"d2b48c",teal:"008080",thistle:"d8bfd8",tomato:"ff6347",turquoise:"40e0d0",violet:"ee82ee",violetred:"d02090",wheat:"f5deb3",white:"ffffff",whitesmoke:"f5f5f5",yellow:"ffff00",yellowgreen:"9acd32"}[s=(s=s.replace(/ /g,"")).toLowerCase()]||s;for(var n=[{re:/^rgb\((\d{1,3}),\s*(\d{1,3}),\s*(\d{1,3})\)$/,example:["rgb(123, 234, 45)","rgb(255,234,245)"],process:function(o){return[parseInt(o[1]),parseInt(o[2]),parseInt(o[3])]}},{re:/^(\w{2})(\w{2})(\w{2})$/,example:["#00ff00","336699"],process:function(o){return[parseInt(o[1],16),parseInt(o[2],16),parseInt(o[3],16)]}},{re:/^(\w{1})(\w{1})(\w{1})$/,example:["#fb0","f0f"],process:function(o){return[parseInt(o[1]+o[1],16),parseInt(o[2]+o[2],16),parseInt(o[3]+o[3],16)]}}],r=0;r255?255:this.r,this.g=this.g<0||isNaN(this.g)?0:this.g>255?255:this.g,this.b=this.b<0||isNaN(this.b)?0:this.b>255?255:this.b,this.toRGB=function(){return"rgb("+this.r+", "+this.g+", "+this.b+")"},this.toHex=function(){var o=this.r.toString(16),c=this.g.toString(16),d=this.b.toString(16);return o.length==1&&(o="0"+o),c.length==1&&(c="0"+c),d.length==1&&(d="0"+d),"#"+o+c+d}}var TNe=ac.atob.bind(ac),Gvt=ac.btoa.bind(ac);/** * @license * Joseph Myers does not specify a particular license for his work. * * Author: Joseph Myers * Accessed from: http://www.myersdaily.org/joseph/javascript/md5.js * * Modified by: Owen Leong */function ADe(s,t){var n=s[0],r=s[1],a=s[2],i=s[3];n=Uv(n,r,a,i,t[0],7,-680876936),i=Uv(i,n,r,a,t[1],12,-389564586),a=Uv(a,i,n,r,t[2],17,606105819),r=Uv(r,a,i,n,t[3],22,-1044525330),n=Uv(n,r,a,i,t[4],7,-176418897),i=Uv(i,n,r,a,t[5],12,1200080426),a=Uv(a,i,n,r,t[6],17,-1473231341),r=Uv(r,a,i,n,t[7],22,-45705983),n=Uv(n,r,a,i,t[8],7,1770035416),i=Uv(i,n,r,a,t[9],12,-1958414417),a=Uv(a,i,n,r,t[10],17,-42063),r=Uv(r,a,i,n,t[11],22,-1990404162),n=Uv(n,r,a,i,t[12],7,1804603682),i=Uv(i,n,r,a,t[13],12,-40341101),a=Uv(a,i,n,r,t[14],17,-1502002290),n=qv(n,r=Uv(r,a,i,n,t[15],22,1236535329),a,i,t[1],5,-165796510),i=qv(i,n,r,a,t[6],9,-1069501632),a=qv(a,i,n,r,t[11],14,643717713),r=qv(r,a,i,n,t[0],20,-373897302),n=qv(n,r,a,i,t[5],5,-701558691),i=qv(i,n,r,a,t[10],9,38016083),a=qv(a,i,n,r,t[15],14,-660478335),r=qv(r,a,i,n,t[4],20,-405537848),n=qv(n,r,a,i,t[9],5,568446438),i=qv(i,n,r,a,t[14],9,-1019803690),a=qv(a,i,n,r,t[3],14,-187363961),r=qv(r,a,i,n,t[8],20,1163531501),n=qv(n,r,a,i,t[13],5,-1444681467),i=qv(i,n,r,a,t[2],9,-51403784),a=qv(a,i,n,r,t[7],14,1735328473),n=Vv(n,r=qv(r,a,i,n,t[12],20,-1926607734),a,i,t[5],4,-378558),i=Vv(i,n,r,a,t[8],11,-2022574463),a=Vv(a,i,n,r,t[11],16,1839030562),r=Vv(r,a,i,n,t[14],23,-35309556),n=Vv(n,r,a,i,t[1],4,-1530992060),i=Vv(i,n,r,a,t[4],11,1272893353),a=Vv(a,i,n,r,t[7],16,-155497632),r=Vv(r,a,i,n,t[10],23,-1094730640),n=Vv(n,r,a,i,t[13],4,681279174),i=Vv(i,n,r,a,t[0],11,-358537222),a=Vv(a,i,n,r,t[3],16,-722521979),r=Vv(r,a,i,n,t[6],23,76029189),n=Vv(n,r,a,i,t[9],4,-640364487),i=Vv(i,n,r,a,t[12],11,-421815835),a=Vv(a,i,n,r,t[15],16,530742520),n=Hv(n,r=Vv(r,a,i,n,t[2],23,-995338651),a,i,t[0],6,-198630844),i=Hv(i,n,r,a,t[7],10,1126891415),a=Hv(a,i,n,r,t[14],15,-1416354905),r=Hv(r,a,i,n,t[5],21,-57434055),n=Hv(n,r,a,i,t[12],6,1700485571),i=Hv(i,n,r,a,t[3],10,-1894986606),a=Hv(a,i,n,r,t[10],15,-1051523),r=Hv(r,a,i,n,t[1],21,-2054922799),n=Hv(n,r,a,i,t[8],6,1873313359),i=Hv(i,n,r,a,t[15],10,-30611744),a=Hv(a,i,n,r,t[6],15,-1560198380),r=Hv(r,a,i,n,t[13],21,1309151649),n=Hv(n,r,a,i,t[4],6,-145523070),i=Hv(i,n,r,a,t[11],10,-1120210379),a=Hv(a,i,n,r,t[2],15,718787259),r=Hv(r,a,i,n,t[9],21,-343485551),s[0]=CT(n,s[0]),s[1]=CT(r,s[1]),s[2]=CT(a,s[2]),s[3]=CT(i,s[3])}function PTe(s,t,n,r,a,i){return t=CT(CT(t,s),CT(r,i)),CT(t<>>32-a,n)}function Uv(s,t,n,r,a,i,l){return PTe(t&n|~t&r,s,t,a,i,l)}function qv(s,t,n,r,a,i,l){return PTe(t&r|n&~r,s,t,a,i,l)}function Vv(s,t,n,r,a,i,l){return PTe(t^n^r,s,t,a,i,l)}function Hv(s,t,n,r,a,i,l){return PTe(n^(t|~r),s,t,a,i,l)}function KBt(s){var t,n=s.length,r=[1732584193,-271733879,-1732584194,271733878];for(t=64;t<=s.length;t+=64)ADe(r,LEn(s.substring(t-64,t)));s=s.substring(t-64);var a=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];for(t=0;t>2]|=s.charCodeAt(t)<<(t%4<<3);if(a[t>>2]|=128<<(t%4<<3),t>55)for(ADe(r,a),t=0;t<16;t++)a[t]=0;return a[14]=8*n,ADe(r,a),r}function LEn(s){var t,n=[];for(t=0;t<64;t+=4)n[t>>2]=s.charCodeAt(t)+(s.charCodeAt(t+1)<<8)+(s.charCodeAt(t+2)<<16)+(s.charCodeAt(t+3)<<24);return n}var Wvt="0123456789abcdef".split("");function REn(s){for(var t="",n=0;n<4;n++)t+=Wvt[s>>8*n+4&15]+Wvt[s>>8*n&15];return t}function DEn(s){return String.fromCharCode(255&s,(65280&s)>>8,(16711680&s)>>16,(4278190080&s)>>24)}function k$e(s){return KBt(s).map(DEn).join("")}var OEn=function(s){for(var t=0;t>16)+(t>>16)+(n>>16)<<16|65535&n}return s+t&4294967295}/** * @license * FPDF is released under a permissive license: there is no usage restriction. * You may embed it freely in your application (commercial or not), with or * without modifications. * * Reference: http://www.fpdf.org/en/script/script37.php */function S$e(s,t){var n,r,a,i;if(s!==n){for(var l=(a=s,i=1+(256/s.length|0),new Array(i+1).join(a)),o=[],c=0;c<256;c++)o[c]=c;var d=0;for(c=0;c<256;c++){var u=o[c];d=(d+u+l.charCodeAt(c))%256,o[c]=o[d],o[d]=u}n=s,r=o}else o=r;var h=t.length,m=0,p=0,g="";for(c=0;c€/\f©þdSiz";var i=(t+this.padding).substr(0,32),l=(n+this.padding).substr(0,32);this.O=this.processOwnerPassword(i,l),this.P=-(1+(255^a)),this.encryptionKey=k$e(i+this.O+this.lsbFirstWord(this.P)+this.hexToBytes(r)).substr(0,5),this.U=S$e(this.encryptionKey,this.padding)}function $9(s){if(/[^\u0000-\u00ff]/.test(s))throw new Error("Invalid PDF Name Object: "+s+", Only accept ASCII characters.");for(var t="",n=s.length,r=0;r126?"#"+("0"+a.toString(16)).slice(-2):s[r]}return t}function Yvt(s){if(Rh(s)!=="object")throw new Error("Invalid Context passed to initialize PubSub (jsPDF-module)");var t={};this.subscribe=function(n,r,a){if(a=a||!1,typeof n!="string"||typeof r!="function"||typeof a!="boolean")throw new Error("Invalid arguments passed to PubSub.subscribe (jsPDF-module)");t.hasOwnProperty(n)||(t[n]={});var i=Math.random().toString(35);return t[n][i]=[r,!!a],i},this.unsubscribe=function(n){for(var r in t)if(t[r][n])return delete t[r][n],Object.keys(t[r]).length===0&&delete t[r],!0;return!1},this.publish=function(n){if(t.hasOwnProperty(n)){var r=Array.prototype.slice.call(arguments,1),a=[];for(var i in t[n]){var l=t[n][i];try{l[0].apply(s,r)}catch(o){ac.console&&dm.error("jsPDF PubSub Error",o.message,o)}l[1]&&a.push(i)}a.length&&a.forEach(this.unsubscribe)}},this.getTopics=function(){return t}}function U4e(s){if(!(this instanceof U4e))return new U4e(s);var t="opacity,stroke-opacity".split(",");for(var n in s)s.hasOwnProperty(n)&&t.indexOf(n)>=0&&(this[n]=s[n]);this.id="",this.objectNumber=-1}function YBt(s,t){this.gState=s,this.matrix=t,this.id="",this.objectNumber=-1}function ZR(s,t,n,r,a){if(!(this instanceof ZR))return new ZR(s,t,n,r,a);this.type=s==="axial"?2:3,this.coords=t,this.colors=n,YBt.call(this,r,a)}function Sz(s,t,n,r,a){if(!(this instanceof Sz))return new Sz(s,t,n,r,a);this.boundingBox=s,this.xStep=t,this.yStep=n,this.stream="",this.cloneIndex=0,YBt.call(this,r,a)}function Oo(s){var t,n=typeof arguments[0]=="string"?arguments[0]:"p",r=arguments[1],a=arguments[2],i=arguments[3],l=[],o=1,c=16,d="S",u=null;Rh(s=s||{})==="object"&&(n=s.orientation,r=s.unit||r,a=s.format||a,i=s.compress||s.compressPdf||i,(u=s.encryption||null)!==null&&(u.userPassword=u.userPassword||"",u.ownerPassword=u.ownerPassword||"",u.userPermissions=u.userPermissions||[]),o=typeof s.userUnit=="number"?Math.abs(s.userUnit):1,s.precision!==void 0&&(t=s.precision),s.floatPrecision!==void 0&&(c=s.floatPrecision),d=s.defaultPathOperation||"S"),l=s.filters||(i===!0?["FlateEncode"]:l),r=r||"mm",n=(""+(n||"P")).toLowerCase();var h=s.putOnlyUsedFonts||!1,m={},p={internal:{},__private__:{}};p.__private__.PubSub=Yvt;var g="1.3",x=p.__private__.getPdfVersion=function(){return g};p.__private__.setPdfVersion=function(Xe){g=Xe};var y={a0:[2383.94,3370.39],a1:[1683.78,2383.94],a2:[1190.55,1683.78],a3:[841.89,1190.55],a4:[595.28,841.89],a5:[419.53,595.28],a6:[297.64,419.53],a7:[209.76,297.64],a8:[147.4,209.76],a9:[104.88,147.4],a10:[73.7,104.88],b0:[2834.65,4008.19],b1:[2004.09,2834.65],b2:[1417.32,2004.09],b3:[1000.63,1417.32],b4:[708.66,1000.63],b5:[498.9,708.66],b6:[354.33,498.9],b7:[249.45,354.33],b8:[175.75,249.45],b9:[124.72,175.75],b10:[87.87,124.72],c0:[2599.37,3676.54],c1:[1836.85,2599.37],c2:[1298.27,1836.85],c3:[918.43,1298.27],c4:[649.13,918.43],c5:[459.21,649.13],c6:[323.15,459.21],c7:[229.61,323.15],c8:[161.57,229.61],c9:[113.39,161.57],c10:[79.37,113.39],dl:[311.81,623.62],letter:[612,792],"government-letter":[576,756],legal:[612,1008],"junior-legal":[576,360],ledger:[1224,792],tabloid:[792,1224],"credit-card":[153,243]};p.__private__.getPageFormats=function(){return y};var v=p.__private__.getPageFormat=function(Xe){return y[Xe]};a=a||"a4";var _="compat",j="advanced",C=_;function A(){this.saveGraphicsState(),Re(new Qn(Is,0,0,-Is,0,Ti()*Is).toString()+" cm"),this.setFontSize(this.getFontSize()/Is),d="n",C=j}function M(){this.restoreGraphicsState(),d="S",C=_}var I=p.__private__.combineFontStyleAndFontWeight=function(Xe,Bt){if(Xe=="bold"&&Bt=="normal"||Xe=="bold"&&Bt==400||Xe=="normal"&&Bt=="italic"||Xe=="bold"&&Bt=="italic")throw new Error("Invalid Combination of fontweight and fontstyle");return Bt&&(Xe=Bt==400||Bt==="normal"?Xe==="italic"?"italic":"normal":Bt!=700&&Bt!=="bold"||Xe!=="normal"?(Bt==700?"bold":Bt)+""+Xe:"bold"),Xe};p.advancedAPI=function(Xe){var Bt=C===_;return Bt&&A.call(this),typeof Xe!="function"||(Xe(this),Bt&&M.call(this)),this},p.compatAPI=function(Xe){var Bt=C===j;return Bt&&M.call(this),typeof Xe!="function"||(Xe(this),Bt&&A.call(this)),this},p.isAdvancedAPI=function(){return C===j};var P,R=function(Xe){if(C!==j)throw new Error(Xe+" is only available in 'advanced' API mode. You need to call advancedAPI() first.")},O=p.roundToPrecision=p.__private__.roundToPrecision=function(Xe,Bt){var As=t||Bt;if(isNaN(Xe)||isNaN(As))throw new Error("Invalid argument passed to jsPDF.roundToPrecision");return Xe.toFixed(As).replace(/0+$/,"")};P=p.hpf=p.__private__.hpf=typeof c=="number"?function(Xe){if(isNaN(Xe))throw new Error("Invalid argument passed to jsPDF.hpf");return O(Xe,c)}:c==="smart"?function(Xe){if(isNaN(Xe))throw new Error("Invalid argument passed to jsPDF.hpf");return O(Xe,Xe>-1&&Xe<1?16:5)}:function(Xe){if(isNaN(Xe))throw new Error("Invalid argument passed to jsPDF.hpf");return O(Xe,16)};var B=p.f2=p.__private__.f2=function(Xe){if(isNaN(Xe))throw new Error("Invalid argument passed to jsPDF.f2");return O(Xe,2)},U=p.__private__.f3=function(Xe){if(isNaN(Xe))throw new Error("Invalid argument passed to jsPDF.f3");return O(Xe,3)},G=p.scale=p.__private__.scale=function(Xe){if(isNaN(Xe))throw new Error("Invalid argument passed to jsPDF.scale");return C===_?Xe*Is:C===j?Xe:void 0},H=function(Xe){return G(function(Bt){return C===_?Ti()-Bt:C===j?Bt:void 0}(Xe))};p.__private__.setPrecision=p.setPrecision=function(Xe){typeof parseInt(Xe,10)=="number"&&(t=parseInt(Xe,10))};var Y,se="00000000000000000000000000000000",ee=p.__private__.getFileId=function(){return se},oe=p.__private__.setFileId=function(Xe){return se=Xe!==void 0&&/^[a-fA-F0-9]{32}$/.test(Xe)?Xe.toUpperCase():se.split("").map(function(){return"ABCDEF0123456789".charAt(Math.floor(16*Math.random()))}).join(""),u!==null&&(zo=new B9(u.userPermissions,u.userPassword,u.ownerPassword,se)),se};p.setFileId=function(Xe){return oe(Xe),this},p.getFileId=function(){return ee()};var me=p.__private__.convertDateToPDFDate=function(Xe){var Bt=Xe.getTimezoneOffset(),As=Bt<0?"+":"-",Hs=Math.floor(Math.abs(Bt/60)),cn=Math.abs(Bt%60),gr=[As,_e(Hs),"'",_e(cn),"'"].join("");return["D:",Xe.getFullYear(),_e(Xe.getMonth()+1),_e(Xe.getDate()),_e(Xe.getHours()),_e(Xe.getMinutes()),_e(Xe.getSeconds()),gr].join("")},Q=p.__private__.convertPDFDateToDate=function(Xe){var Bt=parseInt(Xe.substr(2,4),10),As=parseInt(Xe.substr(6,2),10)-1,Hs=parseInt(Xe.substr(8,2),10),cn=parseInt(Xe.substr(10,2),10),gr=parseInt(Xe.substr(12,2),10),fr=parseInt(Xe.substr(14,2),10);return new Date(Bt,As,Hs,cn,gr,fr,0)},te=p.__private__.setCreationDate=function(Xe){var Bt;if(Xe===void 0&&(Xe=new Date),Xe instanceof Date)Bt=me(Xe);else{if(!/^D:(20[0-2][0-9]|203[0-7]|19[7-9][0-9])(0[0-9]|1[0-2])([0-2][0-9]|3[0-1])(0[0-9]|1[0-9]|2[0-3])(0[0-9]|[1-5][0-9])(0[0-9]|[1-5][0-9])(\+0[0-9]|\+1[0-4]|-0[0-9]|-1[0-1])'(0[0-9]|[1-5][0-9])'?$/.test(Xe))throw new Error("Invalid argument passed to jsPDF.setCreationDate");Bt=Xe}return Y=Bt},le=p.__private__.getCreationDate=function(Xe){var Bt=Y;return Xe==="jsDate"&&(Bt=Q(Y)),Bt};p.setCreationDate=function(Xe){return te(Xe),this},p.getCreationDate=function(Xe){return le(Xe)};var fe,_e=p.__private__.padd2=function(Xe){return("0"+parseInt(Xe)).slice(-2)},ve=p.__private__.padd2Hex=function(Xe){return("00"+(Xe=Xe.toString())).substr(Xe.length)},he=0,Se=[],Te=[],Ie=0,Ue=[],Be=[],je=!1,Ye=Te;p.__private__.setCustomOutputDestination=function(Xe){je=!0,Ye=Xe};var Ee=function(Xe){je||(Ye=Xe)};p.__private__.resetCustomOutputDestination=function(){je=!1,Ye=Te};var Re=p.__private__.out=function(Xe){return Xe=Xe.toString(),Ie+=Xe.length+1,Ye.push(Xe),Ye},ke=p.__private__.write=function(Xe){return Re(arguments.length===1?Xe.toString():Array.prototype.join.call(arguments," "))},Fe=p.__private__.getArrayBuffer=function(Xe){for(var Bt=Xe.length,As=new ArrayBuffer(Bt),Hs=new Uint8Array(As);Bt--;)Hs[Bt]=Xe.charCodeAt(Bt);return As},Oe=[["Helvetica","helvetica","normal","WinAnsiEncoding"],["Helvetica-Bold","helvetica","bold","WinAnsiEncoding"],["Helvetica-Oblique","helvetica","italic","WinAnsiEncoding"],["Helvetica-BoldOblique","helvetica","bolditalic","WinAnsiEncoding"],["Courier","courier","normal","WinAnsiEncoding"],["Courier-Bold","courier","bold","WinAnsiEncoding"],["Courier-Oblique","courier","italic","WinAnsiEncoding"],["Courier-BoldOblique","courier","bolditalic","WinAnsiEncoding"],["Times-Roman","times","normal","WinAnsiEncoding"],["Times-Bold","times","bold","WinAnsiEncoding"],["Times-Italic","times","italic","WinAnsiEncoding"],["Times-BoldItalic","times","bolditalic","WinAnsiEncoding"],["ZapfDingbats","zapfdingbats","normal",null],["Symbol","symbol","normal",null]];p.__private__.getStandardFonts=function(){return Oe};var Ge=s.fontSize||16;p.__private__.setFontSize=p.setFontSize=function(Xe){return Ge=C===j?Xe/Is:Xe,this};var yt,tt=p.__private__.getFontSize=p.getFontSize=function(){return C===_?Ge:Ge*Is},ut=s.R2L||!1;p.__private__.setR2L=p.setR2L=function(Xe){return ut=Xe,this},p.__private__.getR2L=p.getR2L=function(){return ut};var nt,et=p.__private__.setZoomMode=function(Xe){if(/^(?:\d+\.\d*|\d*\.\d+|\d+)%$/.test(Xe))yt=Xe;else if(isNaN(Xe)){if([void 0,null,"fullwidth","fullheight","fullpage","original"].indexOf(Xe)===-1)throw new Error('zoom must be Integer (e.g. 2), a percentage Value (e.g. 300%) or fullwidth, fullheight, fullpage, original. "'+Xe+'" is not recognized.');yt=Xe}else yt=parseInt(Xe,10)};p.__private__.getZoomMode=function(){return yt};var at,wt=p.__private__.setPageMode=function(Xe){if([void 0,null,"UseNone","UseOutlines","UseThumbs","FullScreen"].indexOf(Xe)==-1)throw new Error('Page mode must be one of UseNone, UseOutlines, UseThumbs, or FullScreen. "'+Xe+'" is not recognized.');nt=Xe};p.__private__.getPageMode=function(){return nt};var rt=p.__private__.setLayoutMode=function(Xe){if([void 0,null,"continuous","single","twoleft","tworight","two"].indexOf(Xe)==-1)throw new Error('Layout mode must be one of continuous, single, twoleft, tworight. "'+Xe+'" is not recognized.');at=Xe};p.__private__.getLayoutMode=function(){return at},p.__private__.setDisplayMode=p.setDisplayMode=function(Xe,Bt,As){return et(Xe),rt(Bt),wt(As),this};var Ft={title:"",subject:"",author:"",keywords:"",creator:""};p.__private__.getDocumentProperty=function(Xe){if(Object.keys(Ft).indexOf(Xe)===-1)throw new Error("Invalid argument passed to jsPDF.getDocumentProperty");return Ft[Xe]},p.__private__.getDocumentProperties=function(){return Ft},p.__private__.setDocumentProperties=p.setProperties=p.setDocumentProperties=function(Xe){for(var Bt in Ft)Ft.hasOwnProperty(Bt)&&Xe[Bt]&&(Ft[Bt]=Xe[Bt]);return this},p.__private__.setDocumentProperty=function(Xe,Bt){if(Object.keys(Ft).indexOf(Xe)===-1)throw new Error("Invalid arguments passed to jsPDF.setDocumentProperty");return Ft[Xe]=Bt};var Ut,Is,xs,st,dt,jt={},gt={},rs=[],Ns={},us={},Bs={},Ts={},Fn=null,An=0,js=[],In=new Yvt(p),un=s.hotfixes||[],jr={},Ln={},Sr=[],Qn=function Xe(Bt,As,Hs,cn,gr,fr){if(!(this instanceof Xe))return new Xe(Bt,As,Hs,cn,gr,fr);isNaN(Bt)&&(Bt=1),isNaN(As)&&(As=0),isNaN(Hs)&&(Hs=0),isNaN(cn)&&(cn=1),isNaN(gr)&&(gr=0),isNaN(fr)&&(fr=0),this._matrix=[Bt,As,Hs,cn,gr,fr]};Object.defineProperty(Qn.prototype,"sx",{get:function(){return this._matrix[0]},set:function(Xe){this._matrix[0]=Xe}}),Object.defineProperty(Qn.prototype,"shy",{get:function(){return this._matrix[1]},set:function(Xe){this._matrix[1]=Xe}}),Object.defineProperty(Qn.prototype,"shx",{get:function(){return this._matrix[2]},set:function(Xe){this._matrix[2]=Xe}}),Object.defineProperty(Qn.prototype,"sy",{get:function(){return this._matrix[3]},set:function(Xe){this._matrix[3]=Xe}}),Object.defineProperty(Qn.prototype,"tx",{get:function(){return this._matrix[4]},set:function(Xe){this._matrix[4]=Xe}}),Object.defineProperty(Qn.prototype,"ty",{get:function(){return this._matrix[5]},set:function(Xe){this._matrix[5]=Xe}}),Object.defineProperty(Qn.prototype,"a",{get:function(){return this._matrix[0]},set:function(Xe){this._matrix[0]=Xe}}),Object.defineProperty(Qn.prototype,"b",{get:function(){return this._matrix[1]},set:function(Xe){this._matrix[1]=Xe}}),Object.defineProperty(Qn.prototype,"c",{get:function(){return this._matrix[2]},set:function(Xe){this._matrix[2]=Xe}}),Object.defineProperty(Qn.prototype,"d",{get:function(){return this._matrix[3]},set:function(Xe){this._matrix[3]=Xe}}),Object.defineProperty(Qn.prototype,"e",{get:function(){return this._matrix[4]},set:function(Xe){this._matrix[4]=Xe}}),Object.defineProperty(Qn.prototype,"f",{get:function(){return this._matrix[5]},set:function(Xe){this._matrix[5]=Xe}}),Object.defineProperty(Qn.prototype,"rotation",{get:function(){return Math.atan2(this.shx,this.sx)}}),Object.defineProperty(Qn.prototype,"scaleX",{get:function(){return this.decompose().scale.sx}}),Object.defineProperty(Qn.prototype,"scaleY",{get:function(){return this.decompose().scale.sy}}),Object.defineProperty(Qn.prototype,"isIdentity",{get:function(){return this.sx===1&&this.shy===0&&this.shx===0&&this.sy===1&&this.tx===0&&this.ty===0}}),Qn.prototype.join=function(Xe){return[this.sx,this.shy,this.shx,this.sy,this.tx,this.ty].map(P).join(Xe)},Qn.prototype.multiply=function(Xe){var Bt=Xe.sx*this.sx+Xe.shy*this.shx,As=Xe.sx*this.shy+Xe.shy*this.sy,Hs=Xe.shx*this.sx+Xe.sy*this.shx,cn=Xe.shx*this.shy+Xe.sy*this.sy,gr=Xe.tx*this.sx+Xe.ty*this.shx+this.tx,fr=Xe.tx*this.shy+Xe.ty*this.sy+this.ty;return new Qn(Bt,As,Hs,cn,gr,fr)},Qn.prototype.decompose=function(){var Xe=this.sx,Bt=this.shy,As=this.shx,Hs=this.sy,cn=this.tx,gr=this.ty,fr=Math.sqrt(Xe*Xe+Bt*Bt),za=(Xe/=fr)*As+(Bt/=fr)*Hs;As-=Xe*za,Hs-=Bt*za;var Rt=Math.sqrt(As*As+Hs*Hs);return za/=Rt,Xe*(Hs/=Rt)>16&255,Hs=Rt>>8&255,cn=255&Rt}if(Hs===void 0||gr===void 0&&As===Hs&&Hs===cn)Bt=typeof As=="string"?As+" "+fr[0]:Xe.precision===2?B(As/255)+" "+fr[0]:U(As/255)+" "+fr[0];else if(gr===void 0||Rh(gr)==="object"){if(gr&&!isNaN(gr.a)&&gr.a===0)return["1.","1.","1.",fr[1]].join(" ");Bt=typeof As=="string"?[As,Hs,cn,fr[1]].join(" "):Xe.precision===2?[B(As/255),B(Hs/255),B(cn/255),fr[1]].join(" "):[U(As/255),U(Hs/255),U(cn/255),fr[1]].join(" ")}else Bt=typeof As=="string"?[As,Hs,cn,gr,fr[2]].join(" "):Xe.precision===2?[B(As),B(Hs),B(cn),B(gr),fr[2]].join(" "):[U(As),U(Hs),U(cn),U(gr),fr[2]].join(" ");return Bt},Hr=p.__private__.getFilters=function(){return l},Ur=p.__private__.putStream=function(Xe){var Bt=(Xe=Xe||{}).data||"",As=Xe.filters||Hr(),Hs=Xe.alreadyAppliedFilters||[],cn=Xe.addLength1||!1,gr=Bt.length,fr=Xe.objectId,za=function(Oa){return Oa};if(u!==null&&fr===void 0)throw new Error("ObjectId must be passed to putStream for file encryption");u!==null&&(za=zo.encryptor(fr,0));var Rt={};As===!0&&(As=["FlateEncode"]);var tn=Xe.additionalKeyValues||[],yn=(Rt=Oo.API.processDataByFilters!==void 0?Oo.API.processDataByFilters(Bt,As):{data:Bt,reverseChain:[]}).reverseChain+(Array.isArray(Hs)?Hs.join(" "):Hs.toString());if(Rt.data.length!==0&&(tn.push({key:"Length",value:Rt.data.length}),cn===!0&&tn.push({key:"Length1",value:gr})),yn.length!=0)if(yn.split("/").length-1==1)tn.push({key:"Filter",value:yn});else{tn.push({key:"Filter",value:"["+yn+"]"});for(var xr=0;xr>"),Rt.data.length!==0&&(Re("stream"),Re(za(Rt.data)),Re("endstream"))},Ei=p.__private__.putPage=function(Xe){var Bt=Xe.number,As=Xe.data,Hs=Xe.objId,cn=Xe.contentsObjId;Kt(Hs,!0),Re("<>"),Re("endobj");var gr=As.join(` `);return C===j&&(gr+=` Q`),Kt(cn,!0),Ur({data:gr,filters:Hr(),objectId:cn}),Re("endobj"),Hs},fo=p.__private__.putPages=function(){var Xe,Bt,As=[];for(Xe=1;Xe<=An;Xe++)js[Xe].objId=dn(),js[Xe].contentsObjId=dn();for(Xe=1;Xe<=An;Xe++)As.push(Ei({number:Xe,data:Be[Xe],objId:js[Xe].objId,contentsObjId:js[Xe].contentsObjId,mediaBox:js[Xe].mediaBox,cropBox:js[Xe].cropBox,bleedBox:js[Xe].bleedBox,trimBox:js[Xe].trimBox,artBox:js[Xe].artBox,userUnit:js[Xe].userUnit,rootDictionaryObjId:ti,resourceDictionaryObjId:Ba}));Kt(ti,!0),Re("<>"),Re("endobj"),In.publish("postPutPages")},co=function(Xe){In.publish("putFont",{font:Xe,out:Re,newObject:Zr,putStream:Ur}),Xe.isAlreadyPutted!==!0&&(Xe.objectNumber=Zr(),Re("<<"),Re("/Type /Font"),Re("/BaseFont /"+$9(Xe.postScriptName)),Re("/Subtype /Type1"),typeof Xe.encoding=="string"&&Re("/Encoding /"+Xe.encoding),Re("/FirstChar 32"),Re("/LastChar 255"),Re(">>"),Re("endobj"))},Tn=function(Xe){Xe.objectNumber=Zr();var Bt=[];Bt.push({key:"Type",value:"/XObject"}),Bt.push({key:"Subtype",value:"/Form"}),Bt.push({key:"BBox",value:"["+[P(Xe.x),P(Xe.y),P(Xe.x+Xe.width),P(Xe.y+Xe.height)].join(" ")+"]"}),Bt.push({key:"Matrix",value:"["+Xe.matrix.toString()+"]"});var As=Xe.pages[1].join(` `);Ur({data:As,additionalKeyValues:Bt,objectId:Xe.objectNumber}),Re("endobj")},Mr=function(Xe,Bt){Bt||(Bt=21);var As=Zr(),Hs=function(fr,za){var Rt,tn=[],yn=1/(za-1);for(Rt=0;Rt<1;Rt+=yn)tn.push(Rt);if(tn.push(1),fr[0].offset!=0){var xr={offset:0,color:fr[0].color};fr.unshift(xr)}if(fr[fr.length-1].offset!=1){var $r={offset:1,color:fr[fr.length-1].color};fr.push($r)}for(var Ca="",xa=0,Oa=0;Oafr[xa+1].offset;)xa++;var jl=fr[xa].offset,Ri=(Rt-jl)/(fr[xa+1].offset-jl),Ki=fr[xa].color,Rc=fr[xa+1].color;Ca+=ve(Math.round((1-Ri)*Ki[0]+Ri*Rc[0]).toString(16))+ve(Math.round((1-Ri)*Ki[1]+Ri*Rc[1]).toString(16))+ve(Math.round((1-Ri)*Ki[2]+Ri*Rc[2]).toString(16))}return Ca.trim()}(Xe.colors,Bt),cn=[];cn.push({key:"FunctionType",value:"0"}),cn.push({key:"Domain",value:"[0.0 1.0]"}),cn.push({key:"Size",value:"["+Bt+"]"}),cn.push({key:"BitsPerSample",value:"8"}),cn.push({key:"Range",value:"[0.0 1.0 0.0 1.0 0.0 1.0]"}),cn.push({key:"Decode",value:"[0.0 1.0 0.0 1.0 0.0 1.0]"}),Ur({data:Hs,additionalKeyValues:cn,alreadyAppliedFilters:["/ASCIIHexDecode"],objectId:As}),Re("endobj"),Xe.objectNumber=Zr(),Re("<< /ShadingType "+Xe.type),Re("/ColorSpace /DeviceRGB");var gr="/Coords ["+P(parseFloat(Xe.coords[0]))+" "+P(parseFloat(Xe.coords[1]))+" ";Xe.type===2?gr+=P(parseFloat(Xe.coords[2]))+" "+P(parseFloat(Xe.coords[3])):gr+=P(parseFloat(Xe.coords[2]))+" "+P(parseFloat(Xe.coords[3]))+" "+P(parseFloat(Xe.coords[4]))+" "+P(parseFloat(Xe.coords[5])),Re(gr+="]"),Xe.matrix&&Re("/Matrix ["+Xe.matrix.toString()+"]"),Re("/Function "+As+" 0 R"),Re("/Extend [true true]"),Re(">>"),Re("endobj")},Aa=function(Xe,Bt){var As=dn(),Hs=Zr();Bt.push({resourcesOid:As,objectOid:Hs}),Xe.objectNumber=Hs;var cn=[];cn.push({key:"Type",value:"/Pattern"}),cn.push({key:"PatternType",value:"1"}),cn.push({key:"PaintType",value:"1"}),cn.push({key:"TilingType",value:"1"}),cn.push({key:"BBox",value:"["+Xe.boundingBox.map(P).join(" ")+"]"}),cn.push({key:"XStep",value:P(Xe.xStep)}),cn.push({key:"YStep",value:P(Xe.yStep)}),cn.push({key:"Resources",value:As+" 0 R"}),Xe.matrix&&cn.push({key:"Matrix",value:"["+Xe.matrix.toString()+"]"}),Ur({data:Xe.stream,additionalKeyValues:cn,objectId:Xe.objectNumber}),Re("endobj")},Lo=function(Xe){for(var Bt in Xe.objectNumber=Zr(),Re("<<"),Xe)switch(Bt){case"opacity":Re("/ca "+B(Xe[Bt]));break;case"stroke-opacity":Re("/CA "+B(Xe[Bt]))}Re(">>"),Re("endobj")},Ac=function(Xe){Kt(Xe.resourcesOid,!0),Re("<<"),Re("/ProcSet [/PDF /Text /ImageB /ImageC /ImageI]"),function(){for(var Bt in Re("/Font <<"),jt)jt.hasOwnProperty(Bt)&&(h===!1||h===!0&&m.hasOwnProperty(Bt))&&Re("/"+Bt+" "+jt[Bt].objectNumber+" 0 R");Re(">>")}(),function(){if(Object.keys(Ns).length>0){for(var Bt in Re("/Shading <<"),Ns)Ns.hasOwnProperty(Bt)&&Ns[Bt]instanceof ZR&&Ns[Bt].objectNumber>=0&&Re("/"+Bt+" "+Ns[Bt].objectNumber+" 0 R");In.publish("putShadingPatternDict"),Re(">>")}}(),function(Bt){if(Object.keys(Ns).length>0){for(var As in Re("/Pattern <<"),Ns)Ns.hasOwnProperty(As)&&Ns[As]instanceof p.TilingPattern&&Ns[As].objectNumber>=0&&Ns[As].objectNumber>")}}(Xe.objectOid),function(){if(Object.keys(Bs).length>0){var Bt;for(Bt in Re("/ExtGState <<"),Bs)Bs.hasOwnProperty(Bt)&&Bs[Bt].objectNumber>=0&&Re("/"+Bt+" "+Bs[Bt].objectNumber+" 0 R");In.publish("putGStateDict"),Re(">>")}}(),function(){for(var Bt in Re("/XObject <<"),jr)jr.hasOwnProperty(Bt)&&jr[Bt].objectNumber>=0&&Re("/"+Bt+" "+jr[Bt].objectNumber+" 0 R");In.publish("putXobjectDict"),Re(">>")}(),Re(">>"),Re("endobj")},vl=function(Xe){gt[Xe.fontName]=gt[Xe.fontName]||{},gt[Xe.fontName][Xe.fontStyle]=Xe.id},Ol=function(Xe,Bt,As,Hs,cn){var gr={id:"F"+(Object.keys(jt).length+1).toString(10),postScriptName:Xe,fontName:Bt,fontStyle:As,encoding:Hs,isStandardFont:cn||!1,metadata:{}};return In.publish("addFont",{font:gr,instance:this}),jt[gr.id]=gr,vl(gr),gr.id},To=p.__private__.pdfEscape=p.pdfEscape=function(Xe,Bt){return function(As,Hs){var cn,gr,fr,za,Rt,tn,yn,xr,$r;if(fr=(Hs=Hs||{}).sourceEncoding||"Unicode",Rt=Hs.outputEncoding,(Hs.autoencode||Rt)&&jt[Ut].metadata&&jt[Ut].metadata[fr]&&jt[Ut].metadata[fr].encoding&&(za=jt[Ut].metadata[fr].encoding,!Rt&&jt[Ut].encoding&&(Rt=jt[Ut].encoding),!Rt&&za.codePages&&(Rt=za.codePages[0]),typeof Rt=="string"&&(Rt=za[Rt]),Rt)){for(yn=!1,tn=[],cn=0,gr=As.length;cn>8&&(yn=!0);As=tn.join("")}for(cn=As.length;yn===void 0&&cn!==0;)As.charCodeAt(cn-1)>>8&&(yn=!0),cn--;if(!yn)return As;for(tn=Hs.noBOM?[]:[254,255],cn=0,gr=As.length;cn>8)>>8)throw new Error("Character at position "+cn+" of string '"+As+"' exceeds 16bits. Cannot be encoded into UCS-2 BE");tn.push($r),tn.push(xr-($r<<8))}return String.fromCharCode.apply(void 0,tn)}(Xe,Bt).replace(/\\/g,"\\\\").replace(/\(/g,"\\(").replace(/\)/g,"\\)")},_a=p.__private__.beginPage=function(Xe){Be[++An]=[],js[An]={objId:0,contentsObjId:0,userUnit:Number(o),artBox:null,bleedBox:null,cropBox:null,trimBox:null,mediaBox:{bottomLeftX:0,bottomLeftY:0,topRightX:Number(Xe[0]),topRightY:Number(Xe[1])}},Mu(An),Ee(Be[fe])},$o=function(Xe,Bt){var As,Hs,cn;switch(n=Bt||n,typeof Xe=="string"&&(As=v(Xe.toLowerCase()),Array.isArray(As)&&(Hs=As[0],cn=As[1])),Array.isArray(Xe)&&(Hs=Xe[0]*Is,cn=Xe[1]*Is),isNaN(Hs)&&(Hs=a[0],cn=a[1]),(Hs>14400||cn>14400)&&(dm.warn("A page in a PDF can not be wider or taller than 14400 userUnit. jsPDF limits the width/height to 14400"),Hs=Math.min(14400,Hs),cn=Math.min(14400,cn)),a=[Hs,cn],n.substr(0,1)){case"l":cn>Hs&&(a=[cn,Hs]);break;case"p":Hs>cn&&(a=[cn,Hs])}_a(a),Kx(to),Re(Xt),qn!==0&&Re(qn+" J"),Zn!==0&&Re(Zn+" j"),In.publish("addPage",{pageNumber:An})},jh=function(Xe){Xe>0&&Xe<=An&&(Be.splice(Xe,1),js.splice(Xe,1),An--,fe>An&&(fe=An),this.setPage(fe))},Mu=function(Xe){Xe>0&&Xe<=An&&(fe=Xe)},dh=p.__private__.getNumberOfPages=p.getNumberOfPages=function(){return Be.length-1},Jr=function(Xe,Bt,As){var Hs,cn=void 0;return As=As||{},Xe=Xe!==void 0?Xe:jt[Ut].fontName,Bt=Bt!==void 0?Bt:jt[Ut].fontStyle,Hs=Xe.toLowerCase(),gt[Hs]!==void 0&>[Hs][Bt]!==void 0?cn=gt[Hs][Bt]:gt[Xe]!==void 0&>[Xe][Bt]!==void 0?cn=gt[Xe][Bt]:As.disableWarning===!1&&dm.warn("Unable to look up font label for font '"+Xe+"', '"+Bt+"'. Refer to getFontList() for available fonts."),cn||As.noFallback||(cn=gt.times[Bt])==null&&(cn=gt.times.normal),cn},Uo=p.__private__.putInfo=function(){var Xe=Zr(),Bt=function(Hs){return Hs};for(var As in u!==null&&(Bt=zo.encryptor(Xe,0)),Re("<<"),Re("/Producer ("+To(Bt("jsPDF "+Oo.version))+")"),Ft)Ft.hasOwnProperty(As)&&Ft[As]&&Re("/"+As.substr(0,1).toUpperCase()+As.substr(1)+" ("+To(Bt(Ft[As]))+")");Re("/CreationDate ("+To(Bt(Y))+")"),Re(">>"),Re("endobj")},fc=p.__private__.putCatalog=function(Xe){var Bt=(Xe=Xe||{}).rootDictionaryObjId||ti;switch(Zr(),Re("<<"),Re("/Type /Catalog"),Re("/Pages "+Bt+" 0 R"),yt||(yt="fullwidth"),yt){case"fullwidth":Re("/OpenAction [3 0 R /FitH null]");break;case"fullheight":Re("/OpenAction [3 0 R /FitV null]");break;case"fullpage":Re("/OpenAction [3 0 R /Fit]");break;case"original":Re("/OpenAction [3 0 R /XYZ null null 1]");break;default:var As=""+yt;As.substr(As.length-1)==="%"&&(yt=parseInt(yt)/100),typeof yt=="number"&&Re("/OpenAction [3 0 R /XYZ null null "+B(yt)+"]")}switch(at||(at="continuous"),at){case"continuous":Re("/PageLayout /OneColumn");break;case"single":Re("/PageLayout /SinglePage");break;case"two":case"twoleft":Re("/PageLayout /TwoColumnLeft");break;case"tworight":Re("/PageLayout /TwoColumnRight")}nt&&Re("/PageMode /"+nt),In.publish("putCatalog"),Re(">>"),Re("endobj")},Lc=p.__private__.putTrailer=function(){Re("trailer"),Re("<<"),Re("/Size "+(he+1)),Re("/Root "+he+" 0 R"),Re("/Info "+(he-1)+" 0 R"),u!==null&&Re("/Encrypt "+zo.oid+" 0 R"),Re("/ID [ <"+se+"> <"+se+"> ]"),Re(">>")},Ss=p.__private__.putHeader=function(){Re("%PDF-"+g),Re("%ºß¬à")},wa=p.__private__.putXRef=function(){var Xe="0000000000";Re("xref"),Re("0 "+(he+1)),Re("0000000000 65535 f ");for(var Bt=1;Bt<=he;Bt++)typeof Se[Bt]=="function"?Re((Xe+Se[Bt]()).slice(-10)+" 00000 n "):Se[Bt]!==void 0?Re((Xe+Se[Bt]).slice(-10)+" 00000 n "):Re("0000000000 00000 n ")},Ci=p.__private__.buildDocument=function(){var Xe;he=0,Ie=0,Te=[],Se=[],Ue=[],ti=dn(),Ba=dn(),Ee(Te),In.publish("buildDocument"),Ss(),fo(),function(){In.publish("putAdditionalObjects");for(var As=0;As"),Re("/O <"+zo.toHexString(zo.O)+">"),Re("/P "+zo.P),Re(">>"),Re("endobj")),Uo(),fc();var Bt=Ie;return wa(),Lc(),Re("startxref"),Re(""+Bt),Re("%%EOF"),Ee(Be[fe]),Te.join(` `)},fa=p.__private__.getBlob=function(Xe){return new Blob([Fe(Xe)],{type:"application/pdf"})},zn=function(Xe){for(;Xe.firstChild;)Xe.removeChild(Xe.firstChild)},Rr=function(Xe){var Bt,As=Xe.document,Hs=As.documentElement,cn=As.head,gr=As.body;return cn||(cn=As.createElement("head"),Hs.appendChild(cn)),gr||(gr=As.createElement("body"),Hs.appendChild(gr)),zn(cn),zn(gr),(Bt=As.createElement("style")).appendChild(As.createTextNode("html, body { padding: 0; margin: 0; } iframe { width: 100%; height: 100%; border: 0;}")),cn.appendChild(Bt),{document:As,body:gr}},ja=p.output=p.__private__.output=(Ar=function(Xe,Bt){switch(typeof(Bt=Bt||{})=="string"?Bt={filename:Bt}:Bt.filename=Bt.filename||"generated.pdf",Xe){case void 0:return Ci();case"save":p.save(Bt.filename);break;case"arraybuffer":return Fe(Ci());case"blob":return fa(Ci());case"bloburi":case"bloburl":if(ac.URL!==void 0&&typeof ac.URL.createObjectURL=="function")return ac.URL&&ac.URL.createObjectURL(fa(Ci()))||void 0;dm.warn("bloburl is not supported by your system, because URL.createObjectURL is not supported by your browser.");break;case"datauristring":case"dataurlstring":var As="",Hs=Ci();try{As=Gvt(Hs)}catch{As=Gvt(unescape(encodeURIComponent(Hs)))}return"data:application/pdf;filename="+encodeURIComponent(Bt.filename)+";base64,"+As;case"pdfobjectnewwindow":if(Object.prototype.toString.call(ac)==="[object Window]"){var cn="https://cdnjs.cloudflare.com/ajax/libs/pdfobject/2.1.1/pdfobject.min.js",gr=!Bt.pdfObjectUrl;gr||(cn=Bt.pdfObjectUrl);var fr=ac.open();if(fr!==null){var za=Rr(fr),Rt=za.document.createElement("script"),tn=this;Rt.src=cn,gr&&(Rt.integrity="sha512-4ze/a9/4jqu+tX9dfOqJYSvyYd5M6qum/3HpCLr+/Jqf0whc37VUbkpNGHR7/8pSnCFw47T1fmIpwBV7UySh3g==",Rt.crossOrigin="anonymous"),Rt.onload=function(){fr.PDFObject.embed(tn.output("dataurlstring"),Bt)},za.body.appendChild(Rt)}return fr}throw new Error("The option pdfobjectnewwindow just works in a browser-environment.");case"pdfjsnewwindow":if(Object.prototype.toString.call(ac)==="[object Window]"){var yn=Bt.pdfJsUrl||"examples/PDF.js/web/viewer.html",xr=ac.open();if(xr!==null){var $r=Rr(xr),Ca=$r.document.createElement("iframe"),xa=yn.indexOf("?")===-1?"?":"&";tn=this,Ca.id="pdfViewer",Ca.width="500px",Ca.height="400px",Ca.src=yn+xa+"file=&downloadName="+encodeURIComponent(Bt.filename),Ca.onload=function(){xr.document.title=Bt.filename,Ca.contentWindow.PDFViewerApplication.open(tn.output("bloburl"))},$r.body.appendChild(Ca)}return xr}throw new Error("The option pdfjsnewwindow just works in a browser-environment.");case"dataurlnewwindow":if(Object.prototype.toString.call(ac)!=="[object Window]")throw new Error("The option dataurlnewwindow just works in a browser-environment.");var Oa=ac.open();if(Oa!==null){var jl=Rr(Oa),Ri=jl.document.createElement("iframe");Ri.src=this.output("datauristring",Bt),jl.body.appendChild(Ri),Oa.document.title=Bt.filename}if(Oa||typeof safari>"u")return Oa;break;case"datauri":case"dataurl":return ac.document.location.href=this.output("datauristring",Bt);default:return null}},Ar.foo=function(){try{return Ar.apply(this,arguments)}catch(As){var Xe=As.stack||"";~Xe.indexOf(" at ")&&(Xe=Xe.split(" at ")[1]);var Bt="Error in function "+Xe.split(` `)[0].split("<")[0]+": "+As.message;if(!ac.console)throw new Error(Bt);ac.console.error(Bt,As),ac.alert&&alert(Bt)}},Ar.foo.bar=Ar,Ar.foo),Il=function(Xe){return Array.isArray(un)===!0&&un.indexOf(Xe)>-1};switch(r){case"pt":Is=1;break;case"mm":Is=72/25.4;break;case"cm":Is=72/2.54;break;case"in":Is=72;break;case"px":Is=Il("px_scaling")==1?.75:96/72;break;case"pc":case"em":Is=12;break;case"ex":Is=6;break;default:if(typeof r!="number")throw new Error("Invalid unit: "+r);Is=r}var zo=null;te(),oe();var Hl=p.__private__.getPageInfo=p.getPageInfo=function(Xe){if(isNaN(Xe)||Xe%1!=0)throw new Error("Invalid argument passed to jsPDF.getPageInfo");return{objId:js[Xe].objId,pageNumber:Xe,pageContext:js[Xe]}},Cf=p.__private__.getPageInfoByObjId=function(Xe){if(isNaN(Xe)||Xe%1!=0)throw new Error("Invalid argument passed to jsPDF.getPageInfoByObjId");for(var Bt in js)if(js[Bt].objId===Xe)break;return Hl(Bt)},oi=p.__private__.getCurrentPageInfo=p.getCurrentPageInfo=function(){return{objId:js[fe].objId,pageNumber:fe,pageContext:js[fe]}};p.addPage=function(){return $o.apply(this,arguments),this},p.setPage=function(){return Mu.apply(this,arguments),Ee.call(this,Be[fe]),this},p.insertPage=function(Xe){return this.addPage(),this.movePage(fe,Xe),this},p.movePage=function(Xe,Bt){var As,Hs;if(Xe>Bt){As=Be[Xe],Hs=js[Xe];for(var cn=Xe;cn>Bt;cn--)Be[cn]=Be[cn-1],js[cn]=js[cn-1];Be[Bt]=As,js[Bt]=Hs,this.setPage(Bt)}else if(Xe0&&(typeof Xe=="string"?Xe=xa.splitTextToSize(Xe,yn):Object.prototype.toString.call(Xe)==="[object Array]"&&(Xe=Xe.reduce(function(tl,sl){return tl.concat(xa.splitTextToSize(sl,yn))},[]))),gr={text:Xe,x:Bt,y:As,options:Hs,mutex:{pdfEscape:To,activeFontKey:Ut,fonts:jt,activeFontSize:Ge}},In.publish("preProcessText",gr),Xe=gr.text,za=(Hs=gr.options).angle,Ca instanceof Qn==0&&za&&typeof za=="number"){za*=Math.PI/180,Hs.rotationDirection===0&&(za=-za),C===j&&(za=-za);var ld=Math.cos(za),cd=Math.sin(za);Ca=new Qn(ld,cd,-cd,ld,0,0)}else za&&za instanceof Qn&&(Ca=za);C!==j||Ca||(Ca=pr),(tn=Hs.charSpace||rn)!==void 0&&(Ri+=P(G(tn))+` Tc `,this.setCharSpace(this.getCharSpace()||0)),($r=Hs.horizontalScale)!==void 0&&(Ri+=P(100*$r)+` Tz `),Hs.lang;var yd=-1,Wu=Hs.renderingMode!==void 0?Hs.renderingMode:Hs.stroke,$c=xa.internal.getCurrentPageInfo().pageContext;switch(Wu){case 0:case!1:case"fill":yd=0;break;case 1:case!0:case"stroke":yd=1;break;case 2:case"fillThenStroke":yd=2;break;case 3:case"invisible":yd=3;break;case 4:case"fillAndAddForClipping":yd=4;break;case 5:case"strokeAndAddPathForClipping":yd=5;break;case 6:case"fillThenStrokeAndAddToPathForClipping":yd=6;break;case 7:case"addToPathForClipping":yd=7}var Od=$c.usedRenderingMode!==void 0?$c.usedRenderingMode:-1;yd!==-1?Ri+=yd+` Tr `:Od!==-1&&(Ri+=`0 Tr `),yd!==-1&&($c.usedRenderingMode=yd),Rt=Hs.align||"left";var yu,Wm=Ge*Ki,lu=xa.internal.pageSize.getWidth(),rc=jt[Ut];tn=Hs.charSpace||rn,yn=Hs.maxWidth||0,xr=Object.assign({autoencode:!0,noBOM:!0},Hs.flags);var Ku=[],gc=function(tl){return xa.getStringUnitWidth(tl,{font:rc,charSpace:tn,fontSize:Ge,doKerning:!1})*Ge/Rc};if(Object.prototype.toString.call(Xe)==="[object Array]"){var kl;fr=ro(Xe),Rt!=="left"&&(yu=fr.map(gc));var sd,Tf=0;if(Rt==="right"){Bt-=yu[0],Xe=[],td=fr.length;for(var Pu=0;Pu0?(yn-yu[Fl])/Sm:0;Fl":")"),Ec=parseFloat(fr[Xd][1]),Mi=parseFloat(fr[Xd][2]);break;case 0:Ym=(jl?"<":"(")+fr[Xd]+(jl?">":")"),Ec=At(Bt),Mi=Ht(As)}Ku!==void 0&&Ku[Xd]!==void 0&&(hx=Ku[Xd]+` Tw `),Xd===0?Xe.push(hx+uh(Ec,Mi,Ca)+Ym):ux===0?Xe.push(hx+Ym):ux===1&&Xe.push(hx+uh(Ec,Mi,Ca)+Ym)}Xe=ux===0?Xe.join(` Tj T* `):Xe.join(` Tj `),Xe+=` Tj `;var al=`BT /`;return al+=Ut+" "+Ge+` Tf `,al+=P(Ge*Ki)+` TL `,al+=ps+` `,al+=Ri,al+=Xe,Re(al+="ET"),m[Ut]=!0,xa};var Mo=p.__private__.clip=p.clip=function(Xe){return Re(Xe==="evenodd"?"W*":"W"),this};p.clipEvenOdd=function(){return Mo("evenodd")},p.__private__.discardPath=p.discardPath=function(){return Re("n"),this};var zh=p.__private__.isValidStyle=function(Xe){var Bt=!1;return[void 0,null,"S","D","F","DF","FD","f","f*","B","B*","n"].indexOf(Xe)!==-1&&(Bt=!0),Bt};p.__private__.setDefaultPathOperation=p.setDefaultPathOperation=function(Xe){return zh(Xe)&&(d=Xe),this};var Gm=p.__private__.getStyle=p.getStyle=function(Xe){var Bt=d;switch(Xe){case"D":case"S":Bt="S";break;case"F":Bt="f";break;case"FD":case"DF":Bt="B";break;case"f":case"f*":case"B":case"B*":Bt=Xe}return Bt},Gu=p.close=function(){return Re("h"),this};p.stroke=function(){return Re("S"),this},p.fill=function(Xe){return Zd("f",Xe),this},p.fillEvenOdd=function(Xe){return Zd("f*",Xe),this},p.fillStroke=function(Xe){return Zd("B",Xe),this},p.fillStrokeEvenOdd=function(Xe){return Zd("B*",Xe),this};var Zd=function(Xe,Bt){Rh(Bt)==="object"?Sd(Bt,Xe):Re(Xe)},Bh=function(Xe){Xe===null||C===j&&Xe===void 0||(Xe=Gm(Xe),Re(Xe))};function Mg(Xe,Bt,As,Hs,cn){var gr=new Sz(Bt||this.boundingBox,As||this.xStep,Hs||this.yStep,this.gState,cn||this.matrix);gr.stream=this.stream;var fr=Xe+"$$"+this.cloneIndex+++"$$";return xn(fr,gr),gr}var Sd=function(Xe,Bt){var As=us[Xe.key],Hs=Ns[As];if(Hs instanceof ZR)Re("q"),Re($h(Bt)),Hs.gState&&p.setGState(Hs.gState),Re(Xe.matrix.toString()+" cm"),Re("/"+As+" sh"),Re("Q");else if(Hs instanceof Sz){var cn=new Qn(1,0,0,-1,0,Ti());Xe.matrix&&(cn=cn.multiply(Xe.matrix||pr),As=Mg.call(Hs,Xe.key,Xe.boundingBox,Xe.xStep,Xe.yStep,cn).id),Re("q"),Re("/Pattern cs"),Re("/"+As+" scn"),Hs.gState&&p.setGState(Hs.gState),Re(Bt),Re("Q")}},$h=function(Xe){switch(Xe){case"f":case"F":case"n":return"W n";case"f*":return"W* n";case"B":case"S":return"W S";case"B*":return"W* S"}},Af=p.moveTo=function(Xe,Bt){return Re(P(G(Xe))+" "+P(H(Bt))+" m"),this},Gp=p.lineTo=function(Xe,Bt){return Re(P(G(Xe))+" "+P(H(Bt))+" l"),this},Ef=p.curveTo=function(Xe,Bt,As,Hs,cn,gr){return Re([P(G(Xe)),P(H(Bt)),P(G(As)),P(H(Hs)),P(G(cn)),P(H(gr)),"c"].join(" ")),this};p.__private__.line=p.line=function(Xe,Bt,As,Hs,cn){if(isNaN(Xe)||isNaN(Bt)||isNaN(As)||isNaN(Hs)||!zh(cn))throw new Error("Invalid arguments passed to jsPDF.line");return C===_?this.lines([[As-Xe,Hs-Bt]],Xe,Bt,[1,1],cn||"S"):this.lines([[As-Xe,Hs-Bt]],Xe,Bt,[1,1]).stroke()},p.__private__.lines=p.lines=function(Xe,Bt,As,Hs,cn,gr){var fr,za,Rt,tn,yn,xr,$r,Ca,xa,Oa,jl,Ri;if(typeof Xe=="number"&&(Ri=As,As=Bt,Bt=Xe,Xe=Ri),Hs=Hs||[1,1],gr=gr||!1,isNaN(Bt)||isNaN(As)||!Array.isArray(Xe)||!Array.isArray(Hs)||!zh(cn)||typeof gr!="boolean")throw new Error("Invalid arguments passed to jsPDF.lines");for(Af(Bt,As),fr=Hs[0],za=Hs[1],tn=Xe.length,Oa=Bt,jl=As,Rt=0;Rt>8&255,s>>16&255,s>>24&255)},B9.prototype.toHexString=function(s){return s.split("").map(function(t){return("0"+(255&t.charCodeAt(0)).toString(16)).slice(-2)}).join("")},B9.prototype.hexToBytes=function(s){for(var t=[],n=0;n>8&255,s>>16&255,255&t,t>>8&255)).substr(0,10);return function(r){return S$e(n,r)}},U4e.prototype.equals=function(s){var t,n="id,objectNumber,equals";if(!s||Rh(s)!==Rh(this))return!1;var r=0;for(t in this)if(!(n.indexOf(t)>=0)){if(this.hasOwnProperty(t)&&!s.hasOwnProperty(t)||this[t]!==s[t])return!1;r++}for(t in s)s.hasOwnProperty(t)&&n.indexOf(t)<0&&r--;return r===0},Oo.API={events:[]},Oo.version="4.2.1";var hg=Oo.API,qXe=1,HF=function(s){return s.replace(/\\/g,"\\\\").replace(/\(/g,"\\(").replace(/\)/g,"\\)")},u9=function(s){return s.replace(/\\\\/g,"\\").replace(/\\\(/g,"(").replace(/\\\)/g,")")},nF=function(s){return s.toString().replace(/#/g,"#23").replace(/[\s\n\r()<>[\]{}\/%]/g,function(t){var n=t.charCodeAt(0).toString(16).toUpperCase();return"#"+(n.length===1?"0"+n:n)})},Nc=function(s){return s.toFixed(2)},GA=function(s){return s.toFixed(5)};hg.__acroform__={};var q_=function(s,t){s.prototype=Object.create(t.prototype),s.prototype.constructor=s},Zvt=function(s){return s*qXe},wS=function(s){var t=new XBt,n=ko.internal.getHeight(s)||0,r=ko.internal.getWidth(s)||0;return t.BBox=[0,0,Number(Nc(r)),Number(Nc(n))],t},FEn=hg.__acroform__.setBit=function(s,t){if(s=s||0,t=t||0,isNaN(s)||isNaN(t))throw new Error("Invalid arguments passed to jsPDF.API.__acroform__.setBit");return s|1<0;){t="",i--;var d,u,h=Fae("3",s,i).height,m=s.multiline?l-i:(l-h)/2,p=m+=2,g=0,x=0,y=0;if(i<=0){t=`(...) Tj `,t+="% Width of Text: "+Fae(t,s,i=12).width+", FieldWidth:"+o+` `;break}for(var v="",_=0,j=0;jl)continue e;v+=a[j][y],C=!0,x=j,j--}else{v=(v+=a[j][y]+" ").substr(v.length-1)==" "?v.substr(0,v.length-1):v;var A=parseInt(j),M=c(A,v,i),I=j>=a.length-1;if(M&&!I){v+=" ",y=0;continue}if(M||I){if(I)x=A;else if(s.multiline&&(h+2)*(_+2)+2>l)continue e}else{if(!s.multiline||(h+2)*(_+2)+2>l)continue e;x=A}}for(var P="",R=g;R<=x;R++){var O=a[R];if(s.multiline){if(R===x){P+=O[y]+" ",y=(y+1)%O.length;continue}if(R===g){P+=O[O.length-1]+" ";continue}}P+=O[0]+" "}switch(P=P.substr(P.length-1)==" "?P.substr(0,P.length-1):P,u=Fae(P,s,i).width,s.textAlign){case"right":d=o-u-2;break;case"center":d=(o-u)/2;break;default:d=2}t+=Nc(d)+" "+Nc(p)+` Td `,t+="("+HF(P)+`) Tj `,t+=-Nc(d)+` 0 Td `,p=-(i+2),u=0,g=C?x:x+1,_++,v=""}break}return r.text=t,r.fontSize=i,r},Fae=function(s,t,n){var r=t.scope.internal.getFont(t.fontName,t.fontStyle),a=t.scope.getStringUnitWidth(s,{font:r,fontSize:parseFloat(n),charSpace:0})*parseFloat(n);return{height:t.scope.getStringUnitWidth("3",{font:r,fontSize:parseFloat(n),charSpace:0})*parseFloat(n)*1.5,width:a}},qEn={fields:[],xForms:[],acroFormDictionaryRoot:null,printedOut:!1,internal:null,isInitialized:!1},VEn=function(s,t){var n={type:"reference",object:s};t.internal.getPageInfo(s.page).pageContext.annotations.find(function(r){return r.type===n.type&&r.object===n.object})===void 0&&t.internal.getPageInfo(s.page).pageContext.annotations.push(n)},HEn=function(s,t){if(t.scope=s,s.internal!==void 0&&(s.internal.acroformPlugin===void 0||s.internal.acroformPlugin.isInitialized===!1)){if(Rk.FieldNum=0,s.internal.acroformPlugin=JSON.parse(JSON.stringify(qEn)),s.internal.acroformPlugin.acroFormDictionaryRoot)throw new Error("Exception while creating AcroformDictionary");qXe=s.internal.scaleFactor,s.internal.acroformPlugin.acroFormDictionaryRoot=new QBt,s.internal.acroformPlugin.acroFormDictionaryRoot.scope=s,s.internal.acroformPlugin.acroFormDictionaryRoot._eventID=s.internal.events.subscribe("postPutResources",function(){(function(n){n.internal.events.unsubscribe(n.internal.acroformPlugin.acroFormDictionaryRoot._eventID),delete n.internal.acroformPlugin.acroFormDictionaryRoot._eventID,n.internal.acroformPlugin.printedOut=!0})(s)}),s.internal.events.subscribe("buildDocument",function(){(function(n){n.internal.acroformPlugin.acroFormDictionaryRoot.objId=void 0;var r=n.internal.acroformPlugin.acroFormDictionaryRoot.Fields;for(var a in r)if(r.hasOwnProperty(a)){var i=r[a];i.objId=void 0,i.hasAnnotation&&VEn(i,n)}})(s)}),s.internal.events.subscribe("putCatalog",function(){(function(n){if(n.internal.acroformPlugin.acroFormDictionaryRoot===void 0)throw new Error("putCatalogCallback: Root missing.");n.internal.write("/AcroForm "+n.internal.acroformPlugin.acroFormDictionaryRoot.objId+" 0 R")})(s)}),s.internal.events.subscribe("postPutPages",function(n){(function(r,a){var i=!r;for(var l in r||(a.internal.newObjectDeferredBegin(a.internal.acroformPlugin.acroFormDictionaryRoot.objId,!0),a.internal.acroformPlugin.acroFormDictionaryRoot.putStream()),r=r||a.internal.acroformPlugin.acroFormDictionaryRoot.Kids)if(r.hasOwnProperty(l)){var o=r[l],c=[],d=o.Rect;if(o.Rect&&(o.Rect=$En(o.Rect,a)),a.internal.newObjectDeferredBegin(o.objId,!0),o.DA=ko.createDefaultAppearanceStream(o),Rh(o)==="object"&&typeof o.getKeyValueListForStream=="function"&&(c=o.getKeyValueListForStream()),o.Rect=d,o.hasAppearanceStream&&!o.appearanceStreamContent){var u=UEn(o);c.push({key:"AP",value:"<>"}),a.internal.acroformPlugin.xForms.push(u)}if(o.appearanceStreamContent){var h="";for(var m in o.appearanceStreamContent)if(o.appearanceStreamContent.hasOwnProperty(m)){var p=o.appearanceStreamContent[m];if(h+="/"+m+" ",h+="<<",Object.keys(p).length>=1||Array.isArray(p)){for(var l in p)if(p.hasOwnProperty(l)){var g=p[l];typeof g=="function"&&(g=g.call(a,o)),h+="/"+l+" "+g+" ",a.internal.acroformPlugin.xForms.indexOf(g)>=0||a.internal.acroformPlugin.xForms.push(g)}}else typeof(g=p)=="function"&&(g=g.call(a,o)),h+="/"+l+" "+g,a.internal.acroformPlugin.xForms.indexOf(g)>=0||a.internal.acroformPlugin.xForms.push(g);h+=">>"}c.push({key:"AP",value:`<< `+h+">>"})}a.internal.putStream({additionalKeyValues:c,objectId:o.objId}),a.internal.out("endobj")}i&&function(x,y){for(var v in x)if(x.hasOwnProperty(v)){var _=v,j=x[v];y.internal.newObjectDeferredBegin(j.objId,!0),Rh(j)==="object"&&typeof j.putStream=="function"&&j.putStream(),delete x[_]}}(a.internal.acroformPlugin.xForms,a)})(n,s)}),s.internal.acroformPlugin.isInitialized=!0}},ZBt=hg.__acroform__.arrayToPdfArray=function(s,t,n){var r=function(l){return l};if(Array.isArray(s)){for(var a="[",i=0;i0?t:void 0}}),Object.defineProperty(this,"Fields",{enumerable:!1,configurable:!1,get:function(){return t}}),Object.defineProperty(this,"DA",{enumerable:!1,configurable:!1,get:function(){if(s){var n=function(r){return r};return this.scope&&(n=this.scope.internal.getEncryptor(this.objId)),"("+HF(n(s))+")"}},set:function(n){s=n}})};q_(QBt,y5);var Rk=function s(){y5.call(this);var t=4;Object.defineProperty(this,"F",{enumerable:!1,configurable:!1,get:function(){return t},set:function(v){if(isNaN(v))throw new Error('Invalid value "'+v+'" for attribute F supplied.');t=v}}),Object.defineProperty(this,"showWhenPrinted",{enumerable:!0,configurable:!0,get:function(){return!!Kg(t,3)},set:function(v){v?this.F=Yg(t,3):this.F=Zg(t,3)}});var n=0;Object.defineProperty(this,"Ff",{enumerable:!1,configurable:!1,get:function(){return n},set:function(v){if(isNaN(v))throw new Error('Invalid value "'+v+'" for attribute Ff supplied.');n=v}});var r=[];Object.defineProperty(this,"Rect",{enumerable:!1,configurable:!1,get:function(){if(r.length!==0)return r},set:function(v){r=v!==void 0?v:[]}}),Object.defineProperty(this,"x",{enumerable:!0,configurable:!0,get:function(){return!r||isNaN(r[0])?0:r[0]},set:function(v){r[0]=v}}),Object.defineProperty(this,"y",{enumerable:!0,configurable:!0,get:function(){return!r||isNaN(r[1])?0:r[1]},set:function(v){r[1]=v}}),Object.defineProperty(this,"width",{enumerable:!0,configurable:!0,get:function(){return!r||isNaN(r[2])?0:r[2]},set:function(v){r[2]=v}}),Object.defineProperty(this,"height",{enumerable:!0,configurable:!0,get:function(){return!r||isNaN(r[3])?0:r[3]},set:function(v){r[3]=v}});var a="";Object.defineProperty(this,"FT",{enumerable:!0,configurable:!1,get:function(){return a},set:function(v){switch(v){case"/Btn":case"/Tx":case"/Ch":case"/Sig":a=v;break;default:throw new Error('Invalid value "'+v+'" for attribute FT supplied.')}}});var i=null;Object.defineProperty(this,"T",{enumerable:!0,configurable:!1,get:function(){if(!i||i.length<1){if(this instanceof q4e)return;i="FieldObject"+s.FieldNum++}var v=function(_){return _};return this.scope&&(v=this.scope.internal.getEncryptor(this.objId)),"("+HF(v(i))+")"},set:function(v){i=v.toString()}}),Object.defineProperty(this,"fieldName",{configurable:!0,enumerable:!0,get:function(){return i},set:function(v){i=v}});var l="helvetica";Object.defineProperty(this,"fontName",{enumerable:!0,configurable:!0,get:function(){return l},set:function(v){l=v}});var o="normal";Object.defineProperty(this,"fontStyle",{enumerable:!0,configurable:!0,get:function(){return o},set:function(v){o=v}});var c=0;Object.defineProperty(this,"fontSize",{enumerable:!0,configurable:!0,get:function(){return c},set:function(v){c=v}});var d=void 0;Object.defineProperty(this,"maxFontSize",{enumerable:!0,configurable:!0,get:function(){return d===void 0?50/qXe:d},set:function(v){d=v}});var u="black";Object.defineProperty(this,"color",{enumerable:!0,configurable:!0,get:function(){return u},set:function(v){u=v}});var h="/F1 0 Tf 0 g";Object.defineProperty(this,"DA",{enumerable:!0,configurable:!1,get:function(){if(!(!h||this instanceof q4e||this instanceof yO))return EDe(h,this.objId,this.scope)},set:function(v){v=v.toString(),h=v}});var m=null;Object.defineProperty(this,"DV",{enumerable:!1,configurable:!1,get:function(){if(m)return this instanceof l0==0?EDe(m,this.objId,this.scope):m},set:function(v){v=v.toString(),m=this instanceof l0==0?v.substr(0,1)==="("?u9(v.substr(1,v.length-2)):u9(v):v}}),Object.defineProperty(this,"defaultValue",{enumerable:!0,configurable:!0,get:function(){return this instanceof l0==1?u9(m.substr(1,m.length-1)):m},set:function(v){v=v.toString(),m=this instanceof l0==1?"/"+nF(v):v}});var p=null;Object.defineProperty(this,"_V",{enumerable:!1,configurable:!1,get:function(){if(p)return p},set:function(v){this.V=v}}),Object.defineProperty(this,"V",{enumerable:!1,configurable:!1,get:function(){if(p)return this instanceof l0==0?EDe(p,this.objId,this.scope):p},set:function(v){v=v.toString(),p=this instanceof l0==0?v.substr(0,1)==="("?u9(v.substr(1,v.length-2)):u9(v):v}}),Object.defineProperty(this,"value",{enumerable:!0,configurable:!0,get:function(){return this instanceof l0==1?u9(p.substr(1,p.length-1)):p},set:function(v){v=v.toString(),p=this instanceof l0==1?"/"+nF(v):v}}),Object.defineProperty(this,"hasAnnotation",{enumerable:!0,configurable:!0,get:function(){return this.Rect}}),Object.defineProperty(this,"Type",{enumerable:!0,configurable:!1,get:function(){return this.hasAnnotation?"/Annot":null}}),Object.defineProperty(this,"Subtype",{enumerable:!0,configurable:!1,get:function(){return this.hasAnnotation?"/Widget":null}});var g,x=!1;Object.defineProperty(this,"hasAppearanceStream",{enumerable:!0,configurable:!0,get:function(){return x},set:function(v){v=!!v,x=v}}),Object.defineProperty(this,"page",{enumerable:!0,configurable:!0,get:function(){if(g)return g},set:function(v){g=v}}),Object.defineProperty(this,"readOnly",{enumerable:!0,configurable:!0,get:function(){return!!Kg(this.Ff,1)},set:function(v){v?this.Ff=Yg(this.Ff,1):this.Ff=Zg(this.Ff,1)}}),Object.defineProperty(this,"required",{enumerable:!0,configurable:!0,get:function(){return!!Kg(this.Ff,2)},set:function(v){v?this.Ff=Yg(this.Ff,2):this.Ff=Zg(this.Ff,2)}}),Object.defineProperty(this,"noExport",{enumerable:!0,configurable:!0,get:function(){return!!Kg(this.Ff,3)},set:function(v){v?this.Ff=Yg(this.Ff,3):this.Ff=Zg(this.Ff,3)}});var y=null;Object.defineProperty(this,"Q",{enumerable:!0,configurable:!1,get:function(){if(y!==null)return y},set:function(v){if([0,1,2].indexOf(v)===-1)throw new Error('Invalid value "'+v+'" for attribute Q supplied.');y=v}}),Object.defineProperty(this,"textAlign",{get:function(){var v;switch(y){case 0:default:v="left";break;case 1:v="center";break;case 2:v="right"}return v},configurable:!0,enumerable:!0,set:function(v){switch(v){case"right":case 2:y=2;break;case"center":case 1:y=1;break;default:y=0}}})};q_(Rk,y5);var OB=function(){Rk.call(this),this.FT="/Ch",this.V="()",this.fontName="zapfdingbats";var s=0;Object.defineProperty(this,"TI",{enumerable:!0,configurable:!1,get:function(){return s},set:function(n){s=n}}),Object.defineProperty(this,"topIndex",{enumerable:!0,configurable:!0,get:function(){return s},set:function(n){s=n}});var t=[];Object.defineProperty(this,"Opt",{enumerable:!0,configurable:!1,get:function(){return ZBt(t,this.objId,this.scope)},set:function(n){var r,a;a=[],typeof(r=n)=="string"&&(a=function(i,l,o){o||(o=1);for(var c,d=[];c=l.exec(i);)d.push(c[o]);return d}(r,/\((.*?)\)/g)),t=a}}),this.getOptions=function(){return t},this.setOptions=function(n){t=n,this.sort&&t.sort()},this.addOption=function(n){n=(n=n||"").toString(),t.push(n),this.sort&&t.sort()},this.removeOption=function(n,r){for(r=r||!1,n=(n=n||"").toString();t.indexOf(n)!==-1&&(t.splice(t.indexOf(n),1),r!==!1););},Object.defineProperty(this,"combo",{enumerable:!0,configurable:!0,get:function(){return!!Kg(this.Ff,18)},set:function(n){n?this.Ff=Yg(this.Ff,18):this.Ff=Zg(this.Ff,18)}}),Object.defineProperty(this,"edit",{enumerable:!0,configurable:!0,get:function(){return!!Kg(this.Ff,19)},set:function(n){this.combo===!0&&(n?this.Ff=Yg(this.Ff,19):this.Ff=Zg(this.Ff,19))}}),Object.defineProperty(this,"sort",{enumerable:!0,configurable:!0,get:function(){return!!Kg(this.Ff,20)},set:function(n){n?(this.Ff=Yg(this.Ff,20),t.sort()):this.Ff=Zg(this.Ff,20)}}),Object.defineProperty(this,"multiSelect",{enumerable:!0,configurable:!0,get:function(){return!!Kg(this.Ff,22)},set:function(n){n?this.Ff=Yg(this.Ff,22):this.Ff=Zg(this.Ff,22)}}),Object.defineProperty(this,"doNotSpellCheck",{enumerable:!0,configurable:!0,get:function(){return!!Kg(this.Ff,23)},set:function(n){n?this.Ff=Yg(this.Ff,23):this.Ff=Zg(this.Ff,23)}}),Object.defineProperty(this,"commitOnSelChange",{enumerable:!0,configurable:!0,get:function(){return!!Kg(this.Ff,27)},set:function(n){n?this.Ff=Yg(this.Ff,27):this.Ff=Zg(this.Ff,27)}}),this.hasAppearanceStream=!1};q_(OB,Rk);var FB=function(){OB.call(this),this.fontName="helvetica",this.combo=!1};q_(FB,OB);var zB=function(){FB.call(this),this.combo=!0};q_(zB,FB);var MNe=function(){zB.call(this),this.edit=!0};q_(MNe,zB);var l0=function(){Rk.call(this),this.FT="/Btn",Object.defineProperty(this,"noToggleToOff",{enumerable:!0,configurable:!0,get:function(){return!!Kg(this.Ff,15)},set:function(n){n?this.Ff=Yg(this.Ff,15):this.Ff=Zg(this.Ff,15)}}),Object.defineProperty(this,"radio",{enumerable:!0,configurable:!0,get:function(){return!!Kg(this.Ff,16)},set:function(n){n?this.Ff=Yg(this.Ff,16):this.Ff=Zg(this.Ff,16)}}),Object.defineProperty(this,"pushButton",{enumerable:!0,configurable:!0,get:function(){return!!Kg(this.Ff,17)},set:function(n){n?this.Ff=Yg(this.Ff,17):this.Ff=Zg(this.Ff,17)}}),Object.defineProperty(this,"radioIsUnison",{enumerable:!0,configurable:!0,get:function(){return!!Kg(this.Ff,26)},set:function(n){n?this.Ff=Yg(this.Ff,26):this.Ff=Zg(this.Ff,26)}});var s,t={};Object.defineProperty(this,"MK",{enumerable:!1,configurable:!1,get:function(){var n=function(i){return i};if(this.scope&&(n=this.scope.internal.getEncryptor(this.objId)),Object.keys(t).length!==0){var r,a=[];for(r in a.push("<<"),t)a.push("/"+r+" ("+HF(n(t[r]))+")");return a.push(">>"),a.join(` `)}},set:function(n){Rh(n)==="object"&&(t=n)}}),Object.defineProperty(this,"caption",{enumerable:!0,configurable:!0,get:function(){return t.CA||""},set:function(n){typeof n=="string"&&(t.CA=n)}}),Object.defineProperty(this,"AS",{enumerable:!1,configurable:!1,get:function(){return s},set:function(n){var r=n==null?"":n.toString();r.substr(0,1)==="/"&&(r=r.substr(1)),s="/"+nF(r)}}),Object.defineProperty(this,"appearanceState",{enumerable:!0,configurable:!0,get:function(){return s.substr(1,s.length-1)},set:function(n){s="/"+nF(n)}})};q_(l0,Rk);var PNe=function(){l0.call(this),this.pushButton=!0};q_(PNe,l0);var BB=function(){l0.call(this),this.radio=!0,this.pushButton=!1;var s=[];Object.defineProperty(this,"Kids",{enumerable:!0,configurable:!1,get:function(){return s},set:function(t){s=t!==void 0?t:[]}})};q_(BB,l0);var q4e=function(){var s,t;Rk.call(this),Object.defineProperty(this,"Parent",{enumerable:!1,configurable:!1,get:function(){return s},set:function(a){s=a}}),Object.defineProperty(this,"optionName",{enumerable:!1,configurable:!0,get:function(){return t},set:function(a){t=a}});var n,r={};Object.defineProperty(this,"MK",{enumerable:!1,configurable:!1,get:function(){var a=function(o){return o};this.scope&&(a=this.scope.internal.getEncryptor(this.objId));var i,l=[];for(i in l.push("<<"),r)l.push("/"+i+" ("+HF(a(r[i]))+")");return l.push(">>"),l.join(` `)},set:function(a){Rh(a)==="object"&&(r=a)}}),Object.defineProperty(this,"caption",{enumerable:!0,configurable:!0,get:function(){return r.CA||""},set:function(a){typeof a=="string"&&(r.CA=a)}}),Object.defineProperty(this,"AS",{enumerable:!1,configurable:!1,get:function(){return n},set:function(a){var i=a==null?"":a.toString();i.substr(0,1)==="/"&&(i=i.substr(1)),n="/"+nF(i)}}),Object.defineProperty(this,"appearanceState",{enumerable:!0,configurable:!0,get:function(){return n.substr(1,n.length-1)},set:function(a){var i=a==null?"":a.toString();i.substr(0,1)==="/"&&(i=i.substr(1)),n="/"+nF(i)}}),this.caption="l",this.appearanceState="Off",this._AppearanceType=ko.RadioButton.Circle,this.appearanceStreamContent=this._AppearanceType.createAppearanceStream(this.optionName)};q_(q4e,Rk),BB.prototype.setAppearance=function(s){if(!("createAppearanceStream"in s)||!("getCA"in s))throw new Error("Couldn't assign Appearance to RadioButton. Appearance was Invalid!");for(var t in this.Kids)if(this.Kids.hasOwnProperty(t)){var n=this.Kids[t];n.appearanceStreamContent=s.createAppearanceStream(n.optionName),n.caption=s.getCA()}},BB.prototype.createOption=function(s){var t=new q4e;return t.Parent=this,t.optionName=s,this.Kids.push(t),GEn.call(this.scope,t),t};var INe=function(){l0.call(this),this.fontName="zapfdingbats",this.caption="3",this.appearanceState="On",this.value="On",this.textAlign="center",this.appearanceStreamContent=ko.CheckBox.createAppearanceStream()};q_(INe,l0);var yO=function(){Rk.call(this),this.FT="/Tx",Object.defineProperty(this,"multiline",{enumerable:!0,configurable:!0,get:function(){return!!Kg(this.Ff,13)},set:function(t){t?this.Ff=Yg(this.Ff,13):this.Ff=Zg(this.Ff,13)}}),Object.defineProperty(this,"fileSelect",{enumerable:!0,configurable:!0,get:function(){return!!Kg(this.Ff,21)},set:function(t){t?this.Ff=Yg(this.Ff,21):this.Ff=Zg(this.Ff,21)}}),Object.defineProperty(this,"doNotSpellCheck",{enumerable:!0,configurable:!0,get:function(){return!!Kg(this.Ff,23)},set:function(t){t?this.Ff=Yg(this.Ff,23):this.Ff=Zg(this.Ff,23)}}),Object.defineProperty(this,"doNotScroll",{enumerable:!0,configurable:!0,get:function(){return!!Kg(this.Ff,24)},set:function(t){t?this.Ff=Yg(this.Ff,24):this.Ff=Zg(this.Ff,24)}}),Object.defineProperty(this,"comb",{enumerable:!0,configurable:!0,get:function(){return!!Kg(this.Ff,25)},set:function(t){t?this.Ff=Yg(this.Ff,25):this.Ff=Zg(this.Ff,25)}}),Object.defineProperty(this,"richText",{enumerable:!0,configurable:!0,get:function(){return!!Kg(this.Ff,26)},set:function(t){t?this.Ff=Yg(this.Ff,26):this.Ff=Zg(this.Ff,26)}});var s=null;Object.defineProperty(this,"MaxLen",{enumerable:!0,configurable:!1,get:function(){return s},set:function(t){s=t}}),Object.defineProperty(this,"maxLength",{enumerable:!0,configurable:!0,get:function(){return s},set:function(t){Number.isInteger(t)&&(s=t)}}),Object.defineProperty(this,"hasAppearanceStream",{enumerable:!0,configurable:!0,get:function(){return this.V||this.DV}})};q_(yO,Rk);var LNe=function(){yO.call(this),Object.defineProperty(this,"password",{enumerable:!0,configurable:!0,get:function(){return!!Kg(this.Ff,14)},set:function(s){s?this.Ff=Yg(this.Ff,14):this.Ff=Zg(this.Ff,14)}}),this.password=!0};q_(LNe,yO);var ko={CheckBox:{createAppearanceStream:function(){return{N:{On:ko.CheckBox.YesNormal},D:{On:ko.CheckBox.YesPushDown,Off:ko.CheckBox.OffPushDown}}},YesPushDown:function(s){var t=wS(s);t.scope=s.scope;var n=[],r=s.scope.internal.getFont(s.fontName,s.fontStyle).id,a=s.scope.__private__.encodeColorString(s.color),i=C$e(s,s.caption);return n.push("0.749023 g"),n.push("0 0 "+Nc(ko.internal.getWidth(s))+" "+Nc(ko.internal.getHeight(s))+" re"),n.push("f"),n.push("BMC"),n.push("q"),n.push("0 0 1 rg"),n.push("/"+r+" "+Nc(i.fontSize)+" Tf "+a),n.push("BT"),n.push(i.text),n.push("ET"),n.push("Q"),n.push("EMC"),t.stream=n.join(` `),t},YesNormal:function(s){var t=wS(s);t.scope=s.scope;var n=s.scope.internal.getFont(s.fontName,s.fontStyle).id,r=s.scope.__private__.encodeColorString(s.color),a=[],i=ko.internal.getHeight(s),l=ko.internal.getWidth(s),o=C$e(s,s.caption);return a.push("1 g"),a.push("0 0 "+Nc(l)+" "+Nc(i)+" re"),a.push("f"),a.push("q"),a.push("0 0 1 rg"),a.push("0 0 "+Nc(l-1)+" "+Nc(i-1)+" re"),a.push("W"),a.push("n"),a.push("0 g"),a.push("BT"),a.push("/"+n+" "+Nc(o.fontSize)+" Tf "+r),a.push(o.text),a.push("ET"),a.push("Q"),t.stream=a.join(` `),t},OffPushDown:function(s){var t=wS(s);t.scope=s.scope;var n=[];return n.push("0.749023 g"),n.push("0 0 "+Nc(ko.internal.getWidth(s))+" "+Nc(ko.internal.getHeight(s))+" re"),n.push("f"),t.stream=n.join(` `),t}},RadioButton:{Circle:{createAppearanceStream:function(s){var t={D:{Off:ko.RadioButton.Circle.OffPushDown},N:{}};return t.N[s]=ko.RadioButton.Circle.YesNormal,t.D[s]=ko.RadioButton.Circle.YesPushDown,t},getCA:function(){return"l"},YesNormal:function(s){var t=wS(s);t.scope=s.scope;var n=[],r=ko.internal.getWidth(s)<=ko.internal.getHeight(s)?ko.internal.getWidth(s)/4:ko.internal.getHeight(s)/4;r=Number((.9*r).toFixed(5));var a=ko.internal.Bezier_C,i=Number((r*a).toFixed(5));return n.push("q"),n.push("1 0 0 1 "+GA(ko.internal.getWidth(s)/2)+" "+GA(ko.internal.getHeight(s)/2)+" cm"),n.push(r+" 0 m"),n.push(r+" "+i+" "+i+" "+r+" 0 "+r+" c"),n.push("-"+i+" "+r+" -"+r+" "+i+" -"+r+" 0 c"),n.push("-"+r+" -"+i+" -"+i+" -"+r+" 0 -"+r+" c"),n.push(i+" -"+r+" "+r+" -"+i+" "+r+" 0 c"),n.push("f"),n.push("Q"),t.stream=n.join(` `),t},YesPushDown:function(s){var t=wS(s);t.scope=s.scope;var n=[],r=ko.internal.getWidth(s)<=ko.internal.getHeight(s)?ko.internal.getWidth(s)/4:ko.internal.getHeight(s)/4;r=Number((.9*r).toFixed(5));var a=Number((2*r).toFixed(5)),i=Number((a*ko.internal.Bezier_C).toFixed(5)),l=Number((r*ko.internal.Bezier_C).toFixed(5));return n.push("0.749023 g"),n.push("q"),n.push("1 0 0 1 "+GA(ko.internal.getWidth(s)/2)+" "+GA(ko.internal.getHeight(s)/2)+" cm"),n.push(a+" 0 m"),n.push(a+" "+i+" "+i+" "+a+" 0 "+a+" c"),n.push("-"+i+" "+a+" -"+a+" "+i+" -"+a+" 0 c"),n.push("-"+a+" -"+i+" -"+i+" -"+a+" 0 -"+a+" c"),n.push(i+" -"+a+" "+a+" -"+i+" "+a+" 0 c"),n.push("f"),n.push("Q"),n.push("0 g"),n.push("q"),n.push("1 0 0 1 "+GA(ko.internal.getWidth(s)/2)+" "+GA(ko.internal.getHeight(s)/2)+" cm"),n.push(r+" 0 m"),n.push(r+" "+l+" "+l+" "+r+" 0 "+r+" c"),n.push("-"+l+" "+r+" -"+r+" "+l+" -"+r+" 0 c"),n.push("-"+r+" -"+l+" -"+l+" -"+r+" 0 -"+r+" c"),n.push(l+" -"+r+" "+r+" -"+l+" "+r+" 0 c"),n.push("f"),n.push("Q"),t.stream=n.join(` `),t},OffPushDown:function(s){var t=wS(s);t.scope=s.scope;var n=[],r=ko.internal.getWidth(s)<=ko.internal.getHeight(s)?ko.internal.getWidth(s)/4:ko.internal.getHeight(s)/4;r=Number((.9*r).toFixed(5));var a=Number((2*r).toFixed(5)),i=Number((a*ko.internal.Bezier_C).toFixed(5));return n.push("0.749023 g"),n.push("q"),n.push("1 0 0 1 "+GA(ko.internal.getWidth(s)/2)+" "+GA(ko.internal.getHeight(s)/2)+" cm"),n.push(a+" 0 m"),n.push(a+" "+i+" "+i+" "+a+" 0 "+a+" c"),n.push("-"+i+" "+a+" -"+a+" "+i+" -"+a+" 0 c"),n.push("-"+a+" -"+i+" -"+i+" -"+a+" 0 -"+a+" c"),n.push(i+" -"+a+" "+a+" -"+i+" "+a+" 0 c"),n.push("f"),n.push("Q"),t.stream=n.join(` `),t}},Cross:{createAppearanceStream:function(s){var t={D:{Off:ko.RadioButton.Cross.OffPushDown},N:{}};return t.N[s]=ko.RadioButton.Cross.YesNormal,t.D[s]=ko.RadioButton.Cross.YesPushDown,t},getCA:function(){return"8"},YesNormal:function(s){var t=wS(s);t.scope=s.scope;var n=[],r=ko.internal.calculateCross(s);return n.push("q"),n.push("1 1 "+Nc(ko.internal.getWidth(s)-2)+" "+Nc(ko.internal.getHeight(s)-2)+" re"),n.push("W"),n.push("n"),n.push(Nc(r.x1.x)+" "+Nc(r.x1.y)+" m"),n.push(Nc(r.x2.x)+" "+Nc(r.x2.y)+" l"),n.push(Nc(r.x4.x)+" "+Nc(r.x4.y)+" m"),n.push(Nc(r.x3.x)+" "+Nc(r.x3.y)+" l"),n.push("s"),n.push("Q"),t.stream=n.join(` `),t},YesPushDown:function(s){var t=wS(s);t.scope=s.scope;var n=ko.internal.calculateCross(s),r=[];return r.push("0.749023 g"),r.push("0 0 "+Nc(ko.internal.getWidth(s))+" "+Nc(ko.internal.getHeight(s))+" re"),r.push("f"),r.push("q"),r.push("1 1 "+Nc(ko.internal.getWidth(s)-2)+" "+Nc(ko.internal.getHeight(s)-2)+" re"),r.push("W"),r.push("n"),r.push(Nc(n.x1.x)+" "+Nc(n.x1.y)+" m"),r.push(Nc(n.x2.x)+" "+Nc(n.x2.y)+" l"),r.push(Nc(n.x4.x)+" "+Nc(n.x4.y)+" m"),r.push(Nc(n.x3.x)+" "+Nc(n.x3.y)+" l"),r.push("s"),r.push("Q"),t.stream=r.join(` `),t},OffPushDown:function(s){var t=wS(s);t.scope=s.scope;var n=[];return n.push("0.749023 g"),n.push("0 0 "+Nc(ko.internal.getWidth(s))+" "+Nc(ko.internal.getHeight(s))+" re"),n.push("f"),t.stream=n.join(` `),t}}},createDefaultAppearanceStream:function(s){var t=s.scope.internal.getFont(s.fontName,s.fontStyle).id,n=s.scope.__private__.encodeColorString(s.color);return"/"+t+" "+s.fontSize+" Tf "+n}};ko.internal={Bezier_C:.551915024494,calculateCross:function(s){var t=ko.internal.getWidth(s),n=ko.internal.getHeight(s),r=Math.min(t,n);return{x1:{x:(t-r)/2,y:(n-r)/2+r},x2:{x:(t-r)/2+r,y:(n-r)/2},x3:{x:(t-r)/2,y:(n-r)/2},x4:{x:(t-r)/2+r,y:(n-r)/2+r}}}},ko.internal.getWidth=function(s){var t=0;return Rh(s)==="object"&&(t=Zvt(s.Rect[2])),t},ko.internal.getHeight=function(s){var t=0;return Rh(s)==="object"&&(t=Zvt(s.Rect[3])),t};var GEn=hg.addField=function(s){if(HEn(this,s),!(s instanceof Rk))throw new Error("Invalid argument passed to jsPDF.addField.");var t;return(t=s).scope.internal.acroformPlugin.printedOut&&(t.scope.internal.acroformPlugin.printedOut=!1,t.scope.internal.acroformPlugin.acroFormDictionaryRoot=null),t.scope.internal.acroformPlugin.acroFormDictionaryRoot.Fields.push(t),s.page=s.scope.internal.getCurrentPageInfo().pageNumber,this};hg.AcroFormChoiceField=OB,hg.AcroFormListBox=FB,hg.AcroFormComboBox=zB,hg.AcroFormEditBox=MNe,hg.AcroFormButton=l0,hg.AcroFormPushButton=PNe,hg.AcroFormRadioButton=BB,hg.AcroFormCheckBox=INe,hg.AcroFormTextField=yO,hg.AcroFormPasswordField=LNe,hg.AcroFormAppearance=ko,hg.AcroForm={ChoiceField:OB,ListBox:FB,ComboBox:zB,EditBox:MNe,Button:l0,PushButton:PNe,RadioButton:BB,CheckBox:INe,TextField:yO,PasswordField:LNe,Appearance:ko},Oo.AcroForm={ChoiceField:OB,ListBox:FB,ComboBox:zB,EditBox:MNe,Button:l0,PushButton:PNe,RadioButton:BB,CheckBox:INe,TextField:yO,PasswordField:LNe,Appearance:ko};Oo.AcroForm;function JBt(s){return s.reduce(function(t,n,r){return t[n]=r,t},{})}(function(s){var t="addImage_";s.__addimage__={};var n="UNKNOWN",r={PNG:[[137,80,78,71]],TIFF:[[77,77,0,42],[73,73,42,0]],JPEG:[[255,216,255,224,void 0,void 0,74,70,73,70,0],[255,216,255,225,void 0,void 0,69,120,105,102,0,0],[255,216,255,219],[255,216,255,238]],JPEG2000:[[0,0,0,12,106,80,32,32]],GIF87a:[[71,73,70,56,55,97]],GIF89a:[[71,73,70,56,57,97]],WEBP:[[82,73,70,70,void 0,void 0,void 0,void 0,87,69,66,80]],BMP:[[66,77],[66,65],[67,73],[67,80],[73,67],[80,84]]},a=s.__addimage__.getImageFileTypeByImageData=function(B,U){var G,H,Y,se,ee,oe=n;if((U=U||n)==="RGBA"||B.data!==void 0&&B.data instanceof Uint8ClampedArray&&"height"in B&&"width"in B)return"RGBA";if(M(B))for(ee in r)for(Y=r[ee],G=0;G>"}),"transparency"in U&&Array.isArray(U.transparency)&&U.transparency.length>0){for(var ee="",oe=0,me=U.transparency.length;oe>",x.content=i;var j=x.objId+" 0 R";i="<>";else if(r.options.pageNumber)switch(i="<=0};s.__arabicParser__.arabicLetterHasIsolatedForm=function(x){return l(x)&&i(x)&&t[x.charCodeAt(0)].length>=1};var d=s.__arabicParser__.arabicLetterHasFinalForm=function(x){return l(x)&&i(x)&&t[x.charCodeAt(0)].length>=2};s.__arabicParser__.arabicLetterHasInitialForm=function(x){return l(x)&&i(x)&&t[x.charCodeAt(0)].length>=3};var u=s.__arabicParser__.arabicLetterHasMedialForm=function(x){return l(x)&&i(x)&&t[x.charCodeAt(0)].length==4},h=s.__arabicParser__.resolveLigatures=function(x){var y=0,v=n,_="",j=0;for(y=0;y>"),this.internal.out("endobj")}),this.internal.events.subscribe("putCatalog",function(){this.internal.out("/OpenAction "+t+" 0 R")})),this},function(s){var t=function(){var n=void 0;Object.defineProperty(this,"pdf",{get:function(){return n},set:function(o){n=o}});var r=150;Object.defineProperty(this,"width",{get:function(){return r},set:function(o){r=isNaN(o)||Number.isInteger(o)===!1||o<0?150:o,this.getContext("2d").pageWrapXEnabled&&(this.getContext("2d").pageWrapX=r+1)}});var a=300;Object.defineProperty(this,"height",{get:function(){return a},set:function(o){a=isNaN(o)||Number.isInteger(o)===!1||o<0?300:o,this.getContext("2d").pageWrapYEnabled&&(this.getContext("2d").pageWrapY=a+1)}});var i=[];Object.defineProperty(this,"childNodes",{get:function(){return i},set:function(o){i=o}});var l={};Object.defineProperty(this,"style",{get:function(){return l},set:function(o){l=o}}),Object.defineProperty(this,"parentNode",{})};t.prototype.getContext=function(n,r){var a;if((n=n||"2d")!=="2d")return null;for(a in r)this.pdf.context2d.hasOwnProperty(a)&&(this.pdf.context2d[a]=r[a]);return this.pdf.context2d._canvas=this,this.pdf.context2d},t.prototype.toDataURL=function(){throw new Error("toDataURL is not implemented.")},s.events.push(["initialized",function(){this.canvas=new t,this.canvas.pdf=this}])}(Oo.API),function(s){var t={left:0,top:0,bottom:0,right:0},n=!1,r=function(){this.internal.__cell__===void 0&&(this.internal.__cell__={},this.internal.__cell__.padding=3,this.internal.__cell__.headerFunction=void 0,this.internal.__cell__.margins=Object.assign({},t),this.internal.__cell__.margins.width=this.getPageWidth(),a.call(this))},a=function(){this.internal.__cell__.lastCell=new i,this.internal.__cell__.pages=1},i=function(){var c=arguments[0];Object.defineProperty(this,"x",{enumerable:!0,get:function(){return c},set:function(x){c=x}});var d=arguments[1];Object.defineProperty(this,"y",{enumerable:!0,get:function(){return d},set:function(x){d=x}});var u=arguments[2];Object.defineProperty(this,"width",{enumerable:!0,get:function(){return u},set:function(x){u=x}});var h=arguments[3];Object.defineProperty(this,"height",{enumerable:!0,get:function(){return h},set:function(x){h=x}});var m=arguments[4];Object.defineProperty(this,"text",{enumerable:!0,get:function(){return m},set:function(x){m=x}});var p=arguments[5];Object.defineProperty(this,"lineNumber",{enumerable:!0,get:function(){return p},set:function(x){p=x}});var g=arguments[6];return Object.defineProperty(this,"align",{enumerable:!0,get:function(){return g},set:function(x){g=x}}),this};i.prototype.clone=function(){return new i(this.x,this.y,this.width,this.height,this.text,this.lineNumber,this.align)},i.prototype.toArray=function(){return[this.x,this.y,this.width,this.height,this.text,this.lineNumber,this.align]},s.setHeaderFunction=function(c){return r.call(this),this.internal.__cell__.headerFunction=typeof c=="function"?c:void 0,this},s.getTextDimensions=function(c,d){r.call(this);var u=(d=d||{}).fontSize||this.getFontSize(),h=d.font||this.getFont(),m=d.scaleFactor||this.internal.scaleFactor,p=0,g=0,x=0,y=this;if(!Array.isArray(c)&&typeof c!="string"){if(typeof c!="number")throw new Error("getTextDimensions expects text-parameter to be of type String or type Number or an Array of Strings.");c=String(c)}var v=d.maxWidth;v>0?typeof c=="string"?c=this.splitTextToSize(c,v):Object.prototype.toString.call(c)==="[object Array]"&&(c=c.reduce(function(j,C){return j.concat(y.splitTextToSize(C,v))},[])):c=Array.isArray(c)?c:[c];for(var _=0;_this.getPageHeight()?(this.cellAddPage(),c.y=h.top,p&&m&&(this.printHeaderRow(c.lineNumber,!0),c.y+=m[0].height)):c.y=d.y+d.height||c.y),c.text[0]!==void 0&&(this.rect(c.x,c.y,c.width,c.height,n===!0?"FD":void 0),c.align==="right"?this.text(c.text,c.x+c.width-u,c.y+u,{align:"right",baseline:"top"}):c.align==="center"?this.text(c.text,c.x+c.width/2,c.y+u,{align:"center",baseline:"top",maxWidth:c.width-u-u}):this.text(c.text,c.x+u,c.y+u,{align:"left",baseline:"top",maxWidth:c.width-u-u})),this.internal.__cell__.lastCell=c,this};s.table=function(c,d,u,h,m){if(r.call(this),!u)throw new Error("No data for PDF table.");var p,g,x,y,v=[],_=[],j=[],C={},A={},M=[],I=[],P=(m=m||{}).autoSize||!1,R=m.printHeaders!==!1,O=m.css&&m.css["font-size"]!==void 0?16*m.css["font-size"]:m.fontSize||12,B=m.margins||Object.assign({width:this.getPageWidth()},t),U=typeof m.padding=="number"?m.padding:3,G=m.headerBackgroundColor||"#c8c8c8",H=m.headerTextColor||"#000";if(a.call(this),this.internal.__cell__.printHeaders=R,this.internal.__cell__.margins=B,this.internal.__cell__.table_font_size=O,this.internal.__cell__.padding=U,this.internal.__cell__.headerBackgroundColor=G,this.internal.__cell__.headerTextColor=H,this.setFontSize(O),h==null)_=v=Object.keys(u[0]),j=v.map(function(){return"left"});else if(Array.isArray(h)&&Rh(h[0])==="object")for(v=h.map(function(Q){return Q.name}),_=h.map(function(Q){return Q.prompt||Q.name||""}),j=h.map(function(Q){return Q.align||"left"}),p=0;p0&&this.setTableHeaderRow(m),this.setFont(void 0,"normal"),n=!1}}(Oo.API);var e$t={italic:["italic","oblique","normal"],oblique:["oblique","italic","normal"],normal:["normal","oblique","italic"]},t$t=["ultra-condensed","extra-condensed","condensed","semi-condensed","normal","semi-expanded","expanded","extra-expanded","ultra-expanded"],A$e=JBt(t$t),s$t=[100,200,300,400,500,600,700,800,900],WEn=JBt(s$t);function TDe(s){var t=s.family.replace(/"|'/g,"").toLowerCase(),n=function(i){return e$t[i=i||"normal"]?i:"normal"}(s.style),r=function(i){return i?typeof i=="number"?i>=100&&i<=900&&i%100==0?i:400:/^\d00$/.test(i)?parseInt(i):i==="bold"?700:400:400}(s.weight),a=function(i){return typeof A$e[i=i||"normal"]=="number"?i:"normal"}(s.stretch);return{family:t,style:n,weight:r,stretch:a,src:s.src||[],ref:s.ref||{name:t,style:[a,n,r].join(" ")}}}function Xvt(s,t,n,r){var a;for(a=n;a>=0&&a=0&&a>>1)&255}return a}function l1t(s,t,n){var r=s.length,a=[];a[0]=4;for(var i=0;i>i&l}function c1t(s,t,n,r){var a=n*r,i=Math.floor(a/8),l=16-(a-8*i+r),o=(1<>8&255;d.setUint8(u,m)}})(s,i,n$t(s,i)&~(o<>7,l=1<<1+(7&a);s[t++],s[t++];var o=null,c=null;i&&(o=t,c=l,t+=3*l);var d=!0,u=[],h=0,m=null,p=0,g=null;for(this.width=n,this.height=r;d&&t=0))throw Error("Invalid block size");if(B===0)break;t+=B}break;case 249:if(s[t++]!==4||s[t+4]!==0)throw new Error("Invalid graphics extension block.");var x=s[t++];h=s[t++]|s[t++]<<8,m=s[t++],1&x||(m=null),p=x>>2&7,t++;break;case 254:for(;;){if(!((B=s[t++])>=0))throw Error("Invalid block size");if(B===0)break;t+=B}break;default:throw new Error("Unknown graphic control label: 0x"+s[t-1].toString(16))}break;case 44:var y=s[t++]|s[t++]<<8,v=s[t++]|s[t++]<<8,_=s[t++]|s[t++]<<8,j=s[t++]|s[t++]<<8,C=s[t++],A=C>>6&1,M=1<<1+(7&C),I=o,P=c,R=!1;C>>7&&(R=!0,I=t,P=M,t+=3*M);var O=t;for(t++;;){var B;if(!((B=s[t++])>=0))throw Error("Invalid block size");if(B===0)break;t+=B}u.push({x:y,y:v,width:_,height:j,has_local_palette:R,palette_offset:I,palette_size:P,data_offset:O,data_length:t-O,transparent_index:m,interlaced:!!A,delay:h,disposal:p});break;case 59:d=!1;break;default:throw new Error("Unknown gif block: 0x"+s[t-1].toString(16))}this.numFrames=function(){return u.length},this.loopCount=function(){return g},this.frameInfo=function(U){if(U<0||U>=u.length)throw new Error("Frame index out of range.");return u[U]},this.decodeAndBlitFrameBGRA=function(U,G){var H=this.frameInfo(U),Y=H.width*H.height;if(Y>536870912)throw new Error("Image dimensions exceed 512MB, which is too large.");var se=new Uint8Array(Y);d1t(s,H.data_offset,se,Y);var ee=H.palette_offset,oe=H.transparent_index;oe===null&&(oe=256);var me=H.width,Q=n-me,te=me,le=4*(H.y*n+H.x),fe=4*((H.y+H.height)*n+H.x),_e=le,ve=4*Q;H.interlaced===!0&&(ve+=4*n*7);for(var he=8,Se=0,Te=se.length;Se=fe&&(ve=4*Q+4*n*(he-1),_e=le+(me+Q)*(he<<1),he>>=1)),Ie===oe)_e+=4;else{var Ue=s[ee+3*Ie],Be=s[ee+3*Ie+1],je=s[ee+3*Ie+2];G[_e++]=je,G[_e++]=Be,G[_e++]=Ue,G[_e++]=255}--te}},this.decodeAndBlitFrameRGBA=function(U,G){var H=this.frameInfo(U),Y=H.width*H.height;if(Y>536870912)throw new Error("Image dimensions exceed 512MB, which is too large.");var se=new Uint8Array(Y);d1t(s,H.data_offset,se,Y);var ee=H.palette_offset,oe=H.transparent_index;oe===null&&(oe=256);var me=H.width,Q=n-me,te=me,le=4*(H.y*n+H.x),fe=4*((H.y+H.height)*n+H.x),_e=le,ve=4*Q;H.interlaced===!0&&(ve+=4*n*7);for(var he=8,Se=0,Te=se.length;Se=fe&&(ve=4*Q+4*n*(he-1),_e=le+(me+Q)*(he<<1),he>>=1)),Ie===oe)_e+=4;else{var Ue=s[ee+3*Ie],Be=s[ee+3*Ie+1],je=s[ee+3*Ie+2];G[_e++]=Ue,G[_e++]=Be,G[_e++]=je,G[_e++]=255}--te}}}function d1t(s,t,n,r){for(var a=s[t++],i=1<>=c,u-=c,y!==i){if(y===l)break;for(var v=yi;)j=g[j]>>8,++_;var C=j;if(m+_+(v!==y?1:0)>r)return void dm.log("Warning, gif stream longer than expected.");n[m++]=C;var A=m+=_;for(v!==y&&(n[m++]=C),j=v;_--;)j=g[j],n[--A]=255&j,j>>=8;x!==null&&o<4096&&(g[o++]=x<<8|C,o>=d+1&&c<12&&(++c,d=d<<1|1)),x=y}else o=l+1,d=(1<<(c=a+1))-1,x=null}return m!==r&&dm.log("Warning, gif stream shorter than expected."),n}/** * @license Copyright (c) 2008, Adobe Systems Incorporated All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Adobe Systems Incorporated nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */function IDe(s){var t,n,r,a,i,l=Math.floor,o=new Array(64),c=new Array(64),d=new Array(64),u=new Array(64),h=new Array(65535),m=new Array(65535),p=new Array(64),g=new Array(64),x=[],y=0,v=7,_=new Array(64),j=new Array(64),C=new Array(64),A=new Array(256),M=new Array(2048),I=[0,1,5,6,14,15,27,28,2,4,7,13,16,26,29,42,3,8,12,17,25,30,41,43,9,11,18,24,31,40,44,53,10,19,23,32,39,45,52,54,20,22,33,38,46,51,55,60,21,34,37,47,50,56,59,61,35,36,48,49,57,58,62,63],P=[0,0,1,5,1,1,1,1,1,1,0,0,0,0,0,0,0],R=[0,1,2,3,4,5,6,7,8,9,10,11],O=[0,0,2,1,3,3,2,4,3,5,5,4,4,0,0,1,125],B=[1,2,3,0,4,17,5,18,33,49,65,6,19,81,97,7,34,113,20,50,129,145,161,8,35,66,177,193,21,82,209,240,36,51,98,114,130,9,10,22,23,24,25,26,37,38,39,40,41,42,52,53,54,55,56,57,58,67,68,69,70,71,72,73,74,83,84,85,86,87,88,89,90,99,100,101,102,103,104,105,106,115,116,117,118,119,120,121,122,131,132,133,134,135,136,137,138,146,147,148,149,150,151,152,153,154,162,163,164,165,166,167,168,169,170,178,179,180,181,182,183,184,185,186,194,195,196,197,198,199,200,201,202,210,211,212,213,214,215,216,217,218,225,226,227,228,229,230,231,232,233,234,241,242,243,244,245,246,247,248,249,250],U=[0,0,3,1,1,1,1,1,1,1,1,1,0,0,0,0,0],G=[0,1,2,3,4,5,6,7,8,9,10,11],H=[0,0,2,1,2,4,4,3,4,7,5,4,4,0,1,2,119],Y=[0,1,2,3,17,4,5,33,49,6,18,65,81,7,97,113,19,34,50,129,8,20,66,145,161,177,193,9,35,51,82,240,21,98,114,209,10,22,36,52,225,37,241,23,24,25,26,38,39,40,41,42,53,54,55,56,57,58,67,68,69,70,71,72,73,74,83,84,85,86,87,88,89,90,99,100,101,102,103,104,105,106,115,116,117,118,119,120,121,122,130,131,132,133,134,135,136,137,138,146,147,148,149,150,151,152,153,154,162,163,164,165,166,167,168,169,170,178,179,180,181,182,183,184,185,186,194,195,196,197,198,199,200,201,202,210,211,212,213,214,215,216,217,218,226,227,228,229,230,231,232,233,234,242,243,244,245,246,247,248,249,250];function se(le,fe){for(var _e=0,ve=0,he=new Array,Se=1;Se<=16;Se++){for(var Te=1;Te<=le[Se];Te++)he[fe[ve]]=[],he[fe[ve]][0]=_e,he[fe[ve]][1]=Se,ve++,_e++;_e*=2}return he}function ee(le){for(var fe=le[0],_e=le[1]-1;_e>=0;)fe&1<<_e&&(y|=1<>8&255),oe(255&le)}function Q(le,fe,_e,ve,he){for(var Se,Te=he[0],Ie=he[240],Ue=function(Ge,yt){var tt,ut,nt,et,at,wt,rt,Ft,Ut,Is,xs=0;for(Ut=0;Ut<8;++Ut){tt=Ge[xs],ut=Ge[xs+1],nt=Ge[xs+2],et=Ge[xs+3],at=Ge[xs+4],wt=Ge[xs+5],rt=Ge[xs+6];var st=tt+(Ft=Ge[xs+7]),dt=tt-Ft,jt=ut+rt,gt=ut-rt,rs=nt+wt,Ns=nt-wt,us=et+at,Bs=et-at,Ts=st+us,Fn=st-us,An=jt+rs,js=jt-rs;Ge[xs]=Ts+An,Ge[xs+4]=Ts-An;var In=.707106781*(js+Fn);Ge[xs+2]=Fn+In,Ge[xs+6]=Fn-In;var un=.382683433*((Ts=Bs+Ns)-(js=gt+dt)),jr=.5411961*Ts+un,Ln=1.306562965*js+un,Sr=.707106781*(An=Ns+gt),Qn=dt+Sr,En=dt-Sr;Ge[xs+5]=En+jr,Ge[xs+3]=En-jr,Ge[xs+1]=Qn+Ln,Ge[xs+7]=Qn-Ln,xs+=8}for(xs=0,Ut=0;Ut<8;++Ut){tt=Ge[xs],ut=Ge[xs+8],nt=Ge[xs+16],et=Ge[xs+24],at=Ge[xs+32],wt=Ge[xs+40],rt=Ge[xs+48];var pr=tt+(Ft=Ge[xs+56]),xn=tt-Ft,Ar=ut+rt,Zr=ut-rt,dn=nt+wt,Kt=nt-wt,Er=et+at,ti=et-at,Ba=pr+Er,lo=pr-Er,Yn=Ar+dn,Hr=Ar-dn;Ge[xs]=Ba+Yn,Ge[xs+32]=Ba-Yn;var Ur=.707106781*(Hr+lo);Ge[xs+16]=lo+Ur,Ge[xs+48]=lo-Ur;var Ei=.382683433*((Ba=ti+Kt)-(Hr=Zr+xn)),fo=.5411961*Ba+Ei,co=1.306562965*Hr+Ei,Tn=.707106781*(Yn=Kt+Zr),Mr=xn+Tn,Aa=xn-Tn;Ge[xs+40]=Aa+fo,Ge[xs+24]=Aa-fo,Ge[xs+8]=Mr+co,Ge[xs+56]=Mr-co,xs++}for(Ut=0;Ut<64;++Ut)Is=Ge[Ut]*yt[Ut],p[Ut]=Is>0?Is+.5|0:Is-.5|0;return p}(le,fe),Be=0;Be<64;++Be)g[I[Be]]=Ue[Be];var je=g[0]-_e;_e=g[0],je==0?ee(ve[0]):(ee(ve[m[Se=32767+je]]),ee(h[Se]));for(var Ye=63;Ye>0&&g[Ye]==0;)Ye--;if(Ye==0)return ee(Te),_e;for(var Ee,Re=1;Re<=Ye;){for(var ke=Re;g[Re]==0&&Re<=Ye;)++Re;var Fe=Re-ke;if(Fe>=16){Ee=Fe>>4;for(var Oe=1;Oe<=Ee;++Oe)ee(Ie);Fe&=15}Se=32767+g[Re],ee(he[(Fe<<4)+m[Se]]),ee(h[Se]),Re++}return Ye!=63&&ee(Te),_e}function te(le){le=Math.min(Math.max(le,1),100),i!=le&&(function(fe){for(var _e=[16,11,10,16,24,40,51,61,12,12,14,19,26,58,60,55,14,13,16,24,40,57,69,56,14,17,22,29,51,87,80,62,18,22,37,56,68,109,103,77,24,35,55,64,81,104,113,92,49,64,78,87,103,121,120,101,72,92,95,98,112,100,103,99],ve=0;ve<64;ve++){var he=l((_e[ve]*fe+50)/100);he=Math.min(Math.max(he,1),255),o[I[ve]]=he}for(var Se=[17,18,24,47,99,99,99,99,18,21,26,66,99,99,99,99,24,26,56,99,99,99,99,99,47,66,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99,99],Te=0;Te<64;Te++){var Ie=l((Se[Te]*fe+50)/100);Ie=Math.min(Math.max(Ie,1),255),c[I[Te]]=Ie}for(var Ue=[1,1.387039845,1.306562965,1.175875602,1,.785694958,.5411961,.275899379],Be=0,je=0;je<8;je++)for(var Ye=0;Ye<8;Ye++)d[Be]=1/(o[I[Be]]*Ue[je]*Ue[Ye]*8),u[Be]=1/(c[I[Be]]*Ue[je]*Ue[Ye]*8),Be++}(le<50?Math.floor(5e3/le):Math.floor(200-2*le)),i=le)}this.encode=function(le,fe){fe&&te(fe),x=new Array,y=0,v=7,me(65496),me(65504),me(16),oe(74),oe(70),oe(73),oe(70),oe(0),oe(1),oe(1),oe(0),me(1),me(1),oe(0),oe(0),function(){me(65499),me(132),oe(0);for(var ut=0;ut<64;ut++)oe(o[ut]);oe(1);for(var nt=0;nt<64;nt++)oe(c[nt])}(),function(ut,nt){me(65472),me(17),oe(8),me(nt),me(ut),oe(3),oe(1),oe(17),oe(0),oe(2),oe(17),oe(1),oe(3),oe(17),oe(1)}(le.width,le.height),function(){me(65476),me(418),oe(0);for(var ut=0;ut<16;ut++)oe(P[ut+1]);for(var nt=0;nt<=11;nt++)oe(R[nt]);oe(16);for(var et=0;et<16;et++)oe(O[et+1]);for(var at=0;at<=161;at++)oe(B[at]);oe(1);for(var wt=0;wt<16;wt++)oe(U[wt+1]);for(var rt=0;rt<=11;rt++)oe(G[rt]);oe(17);for(var Ft=0;Ft<16;Ft++)oe(H[Ft+1]);for(var Ut=0;Ut<=161;Ut++)oe(Y[Ut])}(),me(65498),me(12),oe(3),oe(1),oe(0),oe(2),oe(17),oe(3),oe(17),oe(0),oe(63),oe(0);var _e=0,ve=0,he=0;y=0,v=7,this.encode.displayName="_encode_";for(var Se,Te,Ie,Ue,Be,je,Ye,Ee,Re,ke=le.data,Fe=le.width,Oe=le.height,Ge=4*Fe,yt=0;yt>3)*Ge+(Ye=4*(7&Re)),yt+Ee>=Oe&&(je-=Ge*(yt+1+Ee-Oe)),Se+Ye>=Ge&&(je-=Se+Ye-Ge+4),Te=ke[je++],Ie=ke[je++],Ue=ke[je++],_[Re]=(M[Te]+M[Ie+256|0]+M[Ue+512|0]>>16)-128,j[Re]=(M[Te+768|0]+M[Ie+1024|0]+M[Ue+1280|0]>>16)-128,C[Re]=(M[Te+1280|0]+M[Ie+1536|0]+M[Ue+1792|0]>>16)-128;_e=Q(_,d,_e,t,r),ve=Q(j,u,ve,n,a),he=Q(C,u,he,n,a),Se+=32}yt+=8}if(v>=0){var tt=[];tt[1]=v+1,tt[0]=(1<U;U++)if(R[O+U]!=B.charCodeAt(U))return!0;return!1}function r(R,O,B,U,G){for(var H=0;HH+1?[]:new O),!(Y.length>>0;Ae&ft;)ft>>>=1;return ft?(Ae&ft-1)+ft:Ae}function B(Ae,$e,ft,Et,ts){t(!(Et%ft));do Ae[$e+(Et-=ft)]=ts;while(0=ts),512>=ts)var hs=i(512);else if((hs=i(ts))==null)return 0;return function(gs,Es,Ps,Qs,Dn,dr){var Ws,Vn,or=Es,zr=1<Ws;++Ws){if(rr[Ws]>1<(il-=rr[Ws]))return 0;for(;0=Ws;++Ws,Dn<<=1){if(Ui+=il<<=1,0>(il-=rr[Ws]))return 0;for(;0Na&&!(0>=(Gn-=rr[Na]));)++Na,Gn<<=1;zr+=zi=1<<(Gn=Na-Ps),gs[Es+(Na=Yi&pa)].g=Gn+Ps,gs[Es+Na].value=or-Es-Na}Qs.g=Ws-Ps,Qs.value=dr[Vn++],B(gs,or+(Yi>>Ps),Dn,zi,Qs),Yi=O(Yi,Ws)}}return Ui!=2*Xr[15]-1?0:zr}(Ae,$e,ft,Et,ts,hs)}function G(){this.value=this.g=0}function H(){this.value=this.g=0}function Y(){this.G=l(5,G),this.H=i(5),this.jc=this.Qb=this.qb=this.nd=0,this.pd=l(rc,H)}function se(Ae,$e,ft,Et){t(Ae!=null),t($e!=null),t(2147483648>Et),Ae.Ca=254,Ae.I=0,Ae.b=-8,Ae.Ka=0,Ae.oa=$e,Ae.pa=ft,Ae.Jd=$e,Ae.Yc=ft+Et,Ae.Zc=4<=Et?ft+Et-4+1:ft,Te(Ae)}function ee(Ae,$e){for(var ft=0;0<$e--;)ft|=Ue(Ae,128)<<$e;return ft}function oe(Ae,$e){var ft=ee(Ae,$e);return Ie(Ae)?-ft:ft}function me(Ae,$e,ft,Et){var ts,hs=0;for(t(Ae!=null),t($e!=null),t(4294967288>Et),Ae.Sb=Et,Ae.Ra=0,Ae.u=0,Ae.h=0,4>>=8,Ae.Ra+=Ae.oa[Ae.pa+Ae.bb]<>>0,++Ae.bb,Ae.u-=8;ve(Ae)&&(Ae.h=1,Ae.u=0)}function te(Ae,$e){if(t(0<=$e),!Ae.h&&$e<=gc){var ft=_e(Ae)&Ku[$e];return Ae.u+=$e,Q(Ae),ft}return Ae.h=1,Ae.u=0}function le(){this.b=this.Ca=this.I=0,this.oa=[],this.pa=0,this.Jd=[],this.Yc=0,this.Zc=[],this.Ka=0}function fe(){this.Ra=0,this.oa=[],this.h=this.u=this.bb=this.Sb=this.pa=0}function _e(Ae){return Ae.Ra>>>(Ae.u&kl-1)>>>0}function ve(Ae){return t(Ae.bb<=Ae.Sb),Ae.h||Ae.bb==Ae.Sb&&Ae.u>kl}function he(Ae,$e){Ae.u=$e,Ae.h=ve(Ae)}function Se(Ae){Ae.u>=sd&&(t(Ae.u>=sd),Q(Ae))}function Te(Ae){t(Ae!=null&&Ae.oa!=null),Ae.pa>>0,Ae.b+=8):(t(Ae!=null&&Ae.oa!=null),Ae.paAe.b&&Te(Ae);var Et=Ae.b,ts=ft*$e>>>8,hs=(Ae.I>>>Et>ts)+0;for(hs?(ft-=ts,Ae.I-=ts+1<>>0):ft=ts+1,Et=ft,ts=0;256<=Et;)ts+=8,Et>>=8;return Et=7^ts+Tf[Et],Ae.b-=Et,Ae.Ca=(ft<>24&255,Ae[$e+1]=ft>>16&255,Ae[$e+2]=ft>>8&255,Ae[$e+3]=255&ft}function je(Ae,$e){return Ae[$e+0]|Ae[$e+1]<<8}function Ye(Ae,$e){return je(Ae,$e)|Ae[$e+2]<<16}function Ee(Ae,$e){return je(Ae,$e)|je(Ae,$e+2)<<16}function Re(Ae,$e){var ft=1<<$e;return t(Ae!=null),t(0<$e),Ae.X=i(ft),Ae.X==null?0:(Ae.Mb=32-$e,Ae.Xa=$e,1)}function ke(Ae,$e){t(Ae!=null),t($e!=null),t(Ae.Xa==$e.Xa),r($e.X,0,Ae.X,0,1<<$e.Xa)}function Fe(){this.X=[],this.Xa=this.Mb=0}function Oe(Ae,$e,ft,Et){t(ft!=null),t(Et!=null);var ts=ft[0],hs=Et[0];return ts==0&&(ts=(Ae*hs+$e/2)/$e),hs==0&&(hs=($e*ts+Ae/2)/Ae),0>=ts||0>=hs?0:(ft[0]=ts,Et[0]=hs,1)}function Ge(Ae,$e){return Ae+(1<<$e)-1>>>$e}function yt(Ae,$e){return((4278255360&Ae)+(4278255360&$e)>>>0&4278255360)+((16711935&Ae)+(16711935&$e)>>>0&16711935)>>>0}function tt(Ae,$e){R[$e]=function(ft,Et,ts,hs,gs,Es,Ps){var Qs;for(Qs=0;Qs>>1)+(Ae&$e)>>>0}function et(Ae){return 0<=Ae&&256>Ae?Ae:0>Ae?0:255>1))}function wt(Ae,$e,ft){return Math.abs($e-ft)-Math.abs(Ae-ft)}function rt(Ae,$e,ft,Et,ts,hs,gs){for(Et=hs[gs-1],ft=0;ft>8&255,Ps=16711935&(Ps=(Ps=16711935&gs)+((Es<<16)+Es));Et[ts+hs]=(4278255360&gs)+Ps>>>0}}function Ut(Ae,$e){$e.jd=255&Ae,$e.hd=Ae>>8&255,$e.ud=Ae>>16&255}function Is(Ae,$e,ft,Et,ts,hs){var gs;for(gs=0;gs>>8,Qs=Es,Dn=255&(Dn=(Dn=Es>>>16)+((Ae.jd<<24>>24)*(Ps<<24>>24)>>>5));Qs=255&(Qs=(Qs+=(Ae.hd<<24>>24)*(Ps<<24>>24)>>>5)+((Ae.ud<<24>>24)*(Dn<<24>>24)>>>5)),ts[hs+gs]=(4278255360&Es)+(Dn<<16)+Qs}}function xs(Ae,$e,ft,Et,ts){R[$e]=function(hs,gs,Es,Ps,Qs,Dn,dr,Ws,Vn){for(Ps=dr;Ps>hs.b,Vn=hs.Ea,or=hs.K[0],zr=hs.w;if(8>Ws)for(hs=(1<>=Ws}else R["VP8LMapColor"+ft](Ps,Qs,or,zr,Dn,dr,gs,Es,Vn)}}function st(Ae,$e,ft,Et,ts){for(ft=$e+ft;$e>16&255,Et[ts++]=hs>>8&255,Et[ts++]=255&hs}}function dt(Ae,$e,ft,Et,ts){for(ft=$e+ft;$e>16&255,Et[ts++]=hs>>8&255,Et[ts++]=255&hs,Et[ts++]=hs>>24&255}}function jt(Ae,$e,ft,Et,ts){for(ft=$e+ft;$e>16&240|gs>>12&15,gs=240&gs|gs>>28&15;Et[ts++]=hs,Et[ts++]=gs}}function gt(Ae,$e,ft,Et,ts){for(ft=$e+ft;$e>16&248|gs>>13&7,gs=gs>>5&224|gs>>3&31;Et[ts++]=hs,Et[ts++]=gs}}function rs(Ae,$e,ft,Et,ts){for(ft=$e+ft;$e>8&255,Et[ts++]=hs>>16&255}}function Ns(Ae,$e,ft,Et,ts,hs){if(hs==0)for(ft=$e+ft;$e>24|hs[1]>>8&65280|hs[2]<<8&16711680|hs[3]<<24)>>>0),ts+=32;else r(Et,ts,Ae,$e,ft)}function us(Ae,$e){R[$e][0]=R[Ae+"0"],R[$e][1]=R[Ae+"1"],R[$e][2]=R[Ae+"2"],R[$e][3]=R[Ae+"3"],R[$e][4]=R[Ae+"4"],R[$e][5]=R[Ae+"5"],R[$e][6]=R[Ae+"6"],R[$e][7]=R[Ae+"7"],R[$e][8]=R[Ae+"8"],R[$e][9]=R[Ae+"9"],R[$e][10]=R[Ae+"10"],R[$e][11]=R[Ae+"11"],R[$e][12]=R[Ae+"12"],R[$e][13]=R[Ae+"13"],R[$e][14]=R[Ae+"0"],R[$e][15]=R[Ae+"0"]}function Bs(Ae){return Ae==jv||Ae==Ry||Ae==Nv||Ae==T0}function Ts(){this.eb=[],this.size=this.A=this.fb=0}function Fn(){this.y=[],this.f=[],this.ea=[],this.F=[],this.Tc=this.Ed=this.Cd=this.Fd=this.lb=this.Db=this.Ab=this.fa=this.J=this.W=this.N=this.O=0}function An(){this.Rd=this.height=this.width=this.S=0,this.f={},this.f.RGBA=new Ts,this.f.kb=new Fn,this.sd=null}function js(){this.width=[0],this.height=[0],this.Pd=[0],this.Qd=[0],this.format=[0]}function In(){this.Id=this.fd=this.Md=this.hb=this.ib=this.da=this.bd=this.cd=this.j=this.v=this.Da=this.Sd=this.ob=0}function un(Ae){return alert("todo:WebPSamplerProcessPlane"),Ae.T}function jr(Ae,$e){var ft=Ae.T,Et=$e.ba.f.RGBA,ts=Et.eb,hs=Et.fb+Ae.ka*Et.A,gs=fp[$e.ba.S],Es=Ae.y,Ps=Ae.O,Qs=Ae.f,Dn=Ae.N,dr=Ae.ea,Ws=Ae.W,Vn=$e.cc,or=$e.dc,zr=$e.Mc,rr=$e.Nc,Xr=Ae.ka,Gn=Ae.ka+Ae.T,Na=Ae.U,pa=Na+1>>1;for(Xr==0?gs(Es,Ps,null,null,Qs,Dn,dr,Ws,Qs,Dn,dr,Ws,ts,hs,null,null,Na):(gs($e.ec,$e.fc,Es,Ps,Vn,or,zr,rr,Qs,Dn,dr,Ws,ts,hs-Et.A,ts,hs,Na),++ft);Xr+2ft,ts=ft==If||ft==E0||ft==wi||ft==Lf||ft==12||Bs(ft);if($e.memory=null,$e.Ib=null,$e.Jb=null,$e.Nd=null,!yu($e.Oa,Ae,ts?11:12))return 0;if(ts&&Bs(ft)&&Rc(),Ae.da)alert("todo:use_scaling");else{if(Et){if($e.Ib=un,Ae.Kb){if(ft=Ae.U+1>>1,$e.memory=i(Ae.U+2*ft),$e.memory==null)return 0;$e.ec=$e.memory,$e.fc=0,$e.cc=$e.ec,$e.dc=$e.fc+Ae.U,$e.Mc=$e.cc,$e.Nc=$e.dc+ft,$e.Ib=jr,Rc()}}else alert("todo:EmitYUV");ts&&($e.Jb=Ln,Et&&Ri())}if(Et&&!J2){for(Ae=0;256>Ae;++Ae)T1[Ae]=89858*(Ae-128)+Yp>>E1,$k[Ae]=-22014*(Ae-128)+Yp,Sj[Ae]=-45773*(Ae-128),kj[Ae]=113618*(Ae-128)+Yp>>E1;for(Ae=kv;Ae>E1,Uk[Ae-kv]=Uo($e,255),eN[Ae-kv]=Uo($e+8>>4,15);J2=1}return 1}function Qn(Ae){var $e=Ae.ma,ft=Ae.U,Et=Ae.T;return t(!(1&Ae.ka)),0>=ft||0>=Et?0:(ft=$e.Ib(Ae,$e),$e.Jb!=null&&$e.Jb(Ae,$e,ft),$e.Dc+=ft,1)}function En(Ae){Ae.ma.memory=null}function pr(Ae,$e,ft,Et){return te(Ae,8)!=47?0:($e[0]=te(Ae,14)+1,ft[0]=te(Ae,14)+1,Et[0]=te(Ae,1),te(Ae,3)!=0?0:!Ae.h)}function xn(Ae,$e){if(4>Ae)return Ae+1;var ft=Ae-2>>1;return(2+(1&Ae)<>4)*Ae+(8-(15&ft)))?ft:1;var ft}function Zr(Ae,$e,ft){var Et=_e(ft),ts=Ae[$e+=255&Et].g-8;return 0>>0,t(8>=ft.g),Ae.g}function Kt(Ae,$e,ft){var Et=Ae.xc;return t(($e=Et==0?0:Ae.vc[Ae.md*(ft>>Et)+($e>>Et)])>zi.b)*Ui;zrNa&&(Hi=Na),(0,Gl[_c[Vh++]>>8&15])(Ws,Vn+ +Cl,Xr,Gn+Cl-Na,Hi-Cl,Xr,Gn+Cl),Cl=Hi}Vn+=Na,Gn+=Na,++zr&Yi||(zi+=Ui)}dr!=Qs.nc&&r(Ps,Es-or,Ps,Es+(dr-Dn-1)*or,or);break;case 1:for(or=Ws,rr=Vn,Na=(Ws=Qs.Ea)-(Gn=Ws&~(Xr=(Vn=1<>Qs.b)*zr;Dn=ts),0hs.o&&(Et=hs.o),ft=Et?ft=0:(ts[0]+=4*hs.v,hs.ka=ft-hs.j,hs.U=hs.va-hs.v,hs.T=Et-ft,ft=1),ft){if(Es=Es[0],11>(ft=Ae.ca).S){var Dn=ft.f.RGBA,dr=(Et=ft.S,ts=hs.U,hs=hs.T,Qs=Dn.eb,Dn.A),Ws=hs;for(Dn=Dn.fb+Ae.Ma*Dn.A;0Et){var ts=Ae.l.width,hs=ft.ca,gs=ft.tb+ts*Et,Es=Ae.V,Ps=Ae.Ba+Ae.c*Et,Qs=Ae.gc;t(Ae.ab==1),t(Qs[0].hc==3),Mf(Qs[0],Et,$e,Es,Ps,hs,gs),lo(ft,Et,$e,hs,gs,ts)}Ae.C=Ae.Ma=$e}function Hr(Ae,$e,ft,Et,ts,hs,gs){var Es=Ae.$/Et,Ps=Ae.$%Et,Qs=Ae.m,Dn=Ae.s,dr=ft+Ae.$,Ws=dr;ts=ft+Et*ts;var Vn=ft+Et*hs,or=280+Dn.ua,zr=Ae.Pb?Es:16777216,rr=0=zr){var Yi=dr-ft;t((zr=Ae).Pb),zr.wd=zr.m,zr.xd=Yi,0il.g?(he(pa,pa.u+il.g),Yi[Ui]=il.value,pa=0):(he(pa,pa.u+il.g-256),t(256<=il.value),pa=il.value),pa==0&&(Na=!0)}else pa=Zr(Gn.G[0],Gn.H[0],Qs);if(Qs.h)break;if(Na||256>pa){if(!Na)if(Gn.nd)$e[dr]=(Gn.qb|pa<<8)>>>0;else{if(Se(Qs),Na=Zr(Gn.G[1],Gn.H[1],Qs),Se(Qs),Yi=Zr(Gn.G[2],Gn.H[2],Qs),Ui=Zr(Gn.G[3],Gn.H[3],Qs),Qs.h)break;$e[dr]=(Ui<<24|Na<<16|pa<<8|Yi)>>>0}if(Na=!1,++dr,++Ps>=Et&&(Ps=0,++Es,gs!=null&&Es<=hs&&!(Es%16)&&gs(Ae,Es),rr!=null))for(;Ws>>rr.Mb]=pa}else if(280>pa){if(pa=xn(pa-256,Qs),Yi=Zr(Gn.G[4],Gn.H[4],Qs),Se(Qs),Yi=Ar(Et,Yi=xn(Yi,Qs)),Qs.h)break;if(dr-ft=Et;)Ps-=Et,++Es,gs!=null&&Es<=hs&&!(Es%16)&&gs(Ae,Es);if(t(dr<=ts),Ps&Xr&&(Gn=Kt(Dn,Ps,Es)),rr!=null)for(;Ws>>rr.Mb]=pa}else{if(!(pa>>rr.Mb]=pa;pa=dr,t(!(Na>>>(Yi=rr).Xa)),$e[pa]=Yi.X[Na],Na=!0}Na||t(Qs.h==ve(Qs))}if(Ae.Pb&&Qs.h&&drhs?hs:Es),Ae.a=0,Ae.$=dr-ft}return 1}return Ae.a=3,0}function Ur(Ae){t(Ae!=null),Ae.vc=null,Ae.yc=null,Ae.Ya=null;var $e=Ae.Wa;$e!=null&&($e.X=null),Ae.vb=null,t(Ae!=null)}function Ei(){var Ae=new za;return Ae==null?null:(Ae.a=0,Ae.xb=Bk,us("Predictor","VP8LPredictors"),us("Predictor","VP8LPredictors_C"),us("PredictorAdd","VP8LPredictorsAdd"),us("PredictorAdd","VP8LPredictorsAdd_C"),Km=Ft,km=Is,Sm=st,Ig=dt,da=jt,Ec=gt,Mi=rs,R.VP8LMapColor32b=Fl,R.VP8LMapColor8b=Fd,Ae)}function fo(Ae,$e,ft,Et,ts){var hs=1,gs=[Ae],Es=[$e],Ps=Et.m,Qs=Et.s,Dn=null,dr=0;e:for(;;){if(ft)for(;hs&&te(Ps,1);){var Ws=gs,Vn=Es,or=Et,zr=1,rr=or.m,Xr=or.gc[or.ab],Gn=te(rr,2);if(or.Oc&1<=or.ab),Gn){case 0:case 1:Xr.b=te(rr,3)+2,zr=fo(Ge(Xr.Ea,Xr.b),Ge(Xr.nc,Xr.b),0,or,Xr.K),Xr.K=Xr.K[0];break;case 3:var Na,pa=te(rr,8)+1,Yi=16>zi.b),Vh=i(_c);if(Vh==null)Na=0;else{var Cl=zi.K[0],Hi=zi.w;for(Vh[0]=zi.K[0][0],Ui=1;Ui<1*il;++Ui)Vh[Ui]=yt(Cl[Hi+Ui],Vh[Ui-1]);for(;Ui<4*_c;++Ui)Vh[Ui]=0;zi.K[0]=null,zi.K[0]=Vh,Na=1}}zr=Na;break;case 2:break;default:t(0)}hs=zr}}if(gs=gs[0],Es=Es[0],hs&&te(Ps,1)&&!(hs=1<=(dr=te(Ps,4))&&11>=dr)){Et.a=3;break e}var li;if(li=hs)t:{var Do,po,ol,Uc=Et,tf=gs,Zp=Es,vd=dr,sf=ft,Lu=Uc.m,am=Uc.s,Dc=[null],Cd=1,mh=0,zd=Z2[vd];s:for(;;){if(sf&&te(Lu,1)){var fh=te(Lu,3)+2,Of=Ge(tf,fh),Xu=Ge(Zp,fh),Qd=Of*Xu;if(!fo(Of,Xu,0,Uc,Dc))break s;for(Dc=Dc[0],am.xc=fh,Do=0;Do>8&65535;Dc[Do]=bd,bd>=Cd&&(Cd=bd+1)}}if(Lu.h)break s;for(po=0;5>po;++po){var Ru=Dy[po];!po&&0=Am),Xp=pp;var Ff=i(mh);if(Xp==null||Ff==null||Rg==null){Uc.a=1;break s}var Dg=Rg;for(Do=ol=0;Dopo;++po){Ru=Dy[po],Qp[po]=Dg,wd[po]=ol,!po&&0Ev)break n}else P0=Ev;for(Og=0;Ogzb)Cj[Og++]=zb,zb!=0&&(gp=zb);else{var Vk=zb==16,tN=zb-16,Hk=Ok[tN],Xx=te(Zx,Nj[tN])+Hk;if(Og+Xx>Ev)break n;for(var R1=Vk?gp:0;0=po){var D1,xp=Ff[0];for(D1=1;D1xp&&(xp=Ff[D1]);Oc+=xp}}if(_d.nd=Du,_d.Qb=0,Du&&(_d.qb=(Qp[3][wd[3]+0].value<<24|Qp[1][wd[1]+0].value<<16|Qp[2][wd[2]+0].value)>>>0,ll==0&&256>Qp[0][wd[0]+0].value&&(_d.Qb=1,_d.qb+=Qp[0][wd[0]+0].value<<8)),_d.jc=!_d.Qb&&6>Oc,_d.jc){var L0,Qx=_d;for(L0=0;L0>=dn(Jx,8,xx),yp>>=dn(Qx.G[1][Qx.H[1]+yp],16,xx),yp>>=dn(Qx.G[2][Qx.H[2]+yp],0,xx),dn(Qx.G[3][Qx.H[3]+yp],24,xx))}}}am.vc=Dc,am.Wb=Cd,am.Ya=Xp,am.yc=Rg,li=1;break t}li=0}if(!(hs=li)){Et.a=3;break e}if(0Et+1?[]:0),!(ts.lengthAe?0:Ae>$e?$e:Ae}function fc(){this.T=this.U=this.ka=this.height=this.width=0,this.y=[],this.f=[],this.ea=[],this.Rc=this.fa=this.W=this.N=this.O=0,this.ma="void",this.put="VP8IoPutHook",this.ac="VP8IoSetupHook",this.bc="VP8IoTeardownHook",this.ha=this.Kb=0,this.data=[],this.hb=this.ib=this.da=this.o=this.j=this.va=this.v=this.Da=this.ob=this.w=0,this.F=[],this.J=0}function Lc(){var Ae=new Jr;return Ae!=null&&(Ae.a=0,Ae.sc="OK",Ae.cb=0,Ae.Xb=0,Jm||(Jm=fa)),Ae}function Ss(Ae,$e,ft){return Ae.a==0&&(Ae.a=$e,Ae.sc=ft,Ae.cb=0),0}function wa(Ae,$e,ft){return 3<=ft&&Ae[$e+0]==157&&Ae[$e+1]==1&&Ae[$e+2]==42}function Ci(Ae,$e){if(Ae==null)return 0;if(Ae.a=0,Ae.sc="OK",$e==null)return Ss(Ae,2,"null VP8Io passed to VP8GetHeaders()");var ft=$e.data,Et=$e.w,ts=$e.ha;if(4>ts)return Ss(Ae,7,"Truncated header.");var hs=ft[Et+0]|ft[Et+1]<<8|ft[Et+2]<<16,gs=Ae.Od;if(gs.Rb=!(1&hs),gs.td=hs>>1&7,gs.yd=hs>>4&1,gs.ub=hs>>5,3ts)return Ss(Ae,7,"cannot parse picture header");if(!wa(ft,Et,ts))return Ss(Ae,3,"Bad code word");Es.c=16383&(ft[Et+4]<<8|ft[Et+3]),Es.Td=ft[Et+4]>>6,Es.i=16383&(ft[Et+6]<<8|ft[Et+5]),Es.Ud=ft[Et+6]>>6,Et+=7,ts-=7,Ae.za=Es.c+15>>4,Ae.Ub=Es.i+15>>4,$e.width=Es.c,$e.height=Es.i,$e.Da=0,$e.j=0,$e.v=0,$e.va=$e.width,$e.o=$e.height,$e.da=0,$e.ib=$e.width,$e.hb=$e.height,$e.U=$e.width,$e.T=$e.height,a((hs=Ae.Pa).jb,0,255,hs.jb.length),t((hs=Ae.Qa)!=null),hs.Cb=0,hs.Bb=0,hs.Fb=1,a(hs.Zb,0,0,hs.Zb.length),a(hs.Lb,0,0,hs.Lb)}if(gs.ub>ts)return Ss(Ae,7,"bad partition length");se(hs=Ae.m,ft,Et,gs.ub),Et+=gs.ub,ts-=gs.ub,gs.Rb&&(Es.Ld=Ie(hs),Es.Kd=Ie(hs)),Es=Ae.Qa;var Ps,Qs=Ae.Pa;if(t(hs!=null),t(Es!=null),Es.Cb=Ie(hs),Es.Cb){if(Es.Bb=Ie(hs),Ie(hs)){for(Es.Fb=Ie(hs),Ps=0;4>Ps;++Ps)Es.Zb[Ps]=Ie(hs)?oe(hs,7):0;for(Ps=0;4>Ps;++Ps)Es.Lb[Ps]=Ie(hs)?oe(hs,6):0}if(Es.Bb)for(Ps=0;3>Ps;++Ps)Qs.jb[Ps]=Ie(hs)?ee(hs,8):255}else Es.Bb=0;if(hs.Ka)return Ss(Ae,3,"cannot parse segment header");if((Es=Ae.ed).zd=Ie(hs),Es.Tb=ee(hs,6),Es.wb=ee(hs,3),Es.Pc=Ie(hs),Es.Pc&&Ie(hs)){for(Qs=0;4>Qs;++Qs)Ie(hs)&&(Es.vd[Qs]=oe(hs,6));for(Qs=0;4>Qs;++Qs)Ie(hs)&&(Es.od[Qs]=oe(hs,6))}if(Ae.L=Es.Tb==0?0:Es.zd?1:2,hs.Ka)return Ss(Ae,3,"cannot parse filter header");var Dn=ts;if(ts=Ps=Et,Et=Ps+Dn,Es=Dn,Ae.Xb=(1<Es&&(dr=Es),se(Ae.Jc[+Dn],ft,Ps,dr),Ps+=dr,Es-=dr,ts+=3}se(Ae.Jc[+Qs],ft,Ps,Es),ft=Psdr;++dr){if(Dn.Cb){var Ws=Dn.Zb[dr];Dn.Fb||(Ws+=ft)}else{if(0>16,8>Vn.Eb[1]&&(Vn.Eb[1]=8),Vn.Qc[0]=Qm[Uo(Ws+Qs,117)],Vn.Qc[1]=mp[Uo(Ws+Ps,127)],Vn.lc=Ws+Ps}if(!gs.Rb)return Ss(Ae,4,"Not a key frame.");for(Ie(hs),gs=Ae.Pa,ft=0;4>ft;++ft){for(ts=0;8>ts;++ts)for(Et=0;3>Et;++Et)for(Es=0;11>Es;++Es)Qs=Ue(hs,x4[ft][ts][Et][Es])?ee(hs,8):X2[ft][ts][Et][Es],gs.Wc[ft][ts].Yb[Et][Es]=Qs;for(ts=0;17>ts;++ts)gs.Xc[ft][ts]=gs.Wc[ft][fA[ts]]}return Ae.kc=Ie(hs),Ae.kc&&(Ae.Bd=ee(hs,8)),Ae.cb=1}function fa(Ae,$e,ft,Et,ts,hs,gs){var Es=$e[ts].Yb[ft];for(ft=0;16>ts;++ts){if(!Ue(Ae,Es[ft+0]))return ts;for(;!Ue(Ae,Es[ft+1]);)if(Es=$e[++ts].Yb[0],ft=0,ts==16)return 16;var Ps=$e[ts+1].Yb;if(Ue(Ae,Es[ft+2])){var Qs=Ae,Dn=0;if(Ue(Qs,(Ws=Es)[(dr=ft)+3]))if(Ue(Qs,Ws[dr+6])){for(Es=0,dr=2*(Dn=Ue(Qs,Ws[dr+8]))+(Ws=Ue(Qs,Ws[dr+9+Dn])),Dn=0,Ws=hh[dr];Ws[Es];++Es)Dn+=Dn+Ue(Qs,Ws[Es]);Dn+=3+(8<(Qs=Ae).b&&Te(Qs);var dr,Ws=Qs.b,Vn=(dr=Qs.Ca>>1)-(Qs.I>>Ws)>>31;--Qs.b,Qs.Ca+=Vn,Qs.Ca|=1,Qs.I-=(dr+1&Vn)<>3),Ae[$e+ft+32*Et]=-256&ts?0>ts?0:255:ts}function ja(Ae,$e,ft,Et,ts,hs){Rr(Ae,$e,0,ft,Et+ts),Rr(Ae,$e,1,ft,Et+hs),Rr(Ae,$e,2,ft,Et-hs),Rr(Ae,$e,3,ft,Et-ts)}function Il(Ae){return(20091*Ae>>16)+Ae}function zo(Ae,$e,ft,Et){var ts,hs=0,gs=i(16);for(ts=0;4>ts;++ts){var Es=Ae[$e+0]+Ae[$e+8],Ps=Ae[$e+0]-Ae[$e+8],Qs=(35468*Ae[$e+4]>>16)-Il(Ae[$e+12]),Dn=Il(Ae[$e+4])+(35468*Ae[$e+12]>>16);gs[hs+0]=Es+Dn,gs[hs+1]=Ps+Qs,gs[hs+2]=Ps-Qs,gs[hs+3]=Es-Dn,hs+=4,$e++}for(ts=hs=0;4>ts;++ts)Es=(Ae=gs[hs+0]+4)+gs[hs+8],Ps=Ae-gs[hs+8],Qs=(35468*gs[hs+4]>>16)-Il(gs[hs+12]),Rr(ft,Et,0,0,Es+(Dn=Il(gs[hs+4])+(35468*gs[hs+12]>>16))),Rr(ft,Et,1,0,Ps+Qs),Rr(ft,Et,2,0,Ps-Qs),Rr(ft,Et,3,0,Es-Dn),hs++,Et+=32}function Hl(Ae,$e,ft,Et){var ts=Ae[$e+0]+4,hs=35468*Ae[$e+4]>>16,gs=Il(Ae[$e+4]),Es=35468*Ae[$e+1]>>16;ja(ft,Et,0,ts+gs,Ae=Il(Ae[$e+1]),Es),ja(ft,Et,1,ts+hs,Ae,Es),ja(ft,Et,2,ts-hs,Ae,Es),ja(ft,Et,3,ts-gs,Ae,Es)}function Cf(Ae,$e,ft,Et,ts){zo(Ae,$e,ft,Et),ts&&zo(Ae,$e+16,ft,Et+4)}function oi(Ae,$e,ft,Et){ux(Ae,$e+0,ft,Et,1),ux(Ae,$e+32,ft,Et+128,1)}function Mo(Ae,$e,ft,Et){var ts;for(Ae=Ae[$e+0]+4,ts=0;4>ts;++ts)for($e=0;4>$e;++$e)Rr(ft,Et,$e,ts,Ae)}function zh(Ae,$e,ft,Et){Ae[$e+0]&&Xd(Ae,$e+0,ft,Et),Ae[$e+16]&&Xd(Ae,$e+16,ft,Et+4),Ae[$e+32]&&Xd(Ae,$e+32,ft,Et+128),Ae[$e+48]&&Xd(Ae,$e+48,ft,Et+128+4)}function Gm(Ae,$e,ft,Et){var ts,hs=i(16);for(ts=0;4>ts;++ts){var gs=Ae[$e+0+ts]+Ae[$e+12+ts],Es=Ae[$e+4+ts]+Ae[$e+8+ts],Ps=Ae[$e+4+ts]-Ae[$e+8+ts],Qs=Ae[$e+0+ts]-Ae[$e+12+ts];hs[0+ts]=gs+Es,hs[8+ts]=gs-Es,hs[4+ts]=Qs+Ps,hs[12+ts]=Qs-Ps}for(ts=0;4>ts;++ts)gs=(Ae=hs[0+4*ts]+3)+hs[3+4*ts],Es=hs[1+4*ts]+hs[2+4*ts],Ps=hs[1+4*ts]-hs[2+4*ts],Qs=Ae-hs[3+4*ts],ft[Et+0]=gs+Es>>3,ft[Et+16]=Qs+Ps>>3,ft[Et+32]=gs-Es>>3,ft[Et+48]=Qs-Ps>>3,Et+=64}function Gu(Ae,$e,ft){var Et,ts=$e-32,hs=Zu,gs=255-Ae[ts-1];for(Et=0;Etft;++ft)r(Ae,$e+32*ft,Ae,$e-32,16)}function $h(Ae,$e){var ft;for(ft=16;0Et;++Et)a($e,ft+32*Et,Ae,16)}function Gp(Ae,$e){var ft,Et=16;for(ft=0;16>ft;++ft)Et+=Ae[$e-1+32*ft]+Ae[$e+ft-32];Af(Et>>5,Ae,$e)}function Ef(Ae,$e){var ft,Et=8;for(ft=0;16>ft;++ft)Et+=Ae[$e-1+32*ft];Af(Et>>4,Ae,$e)}function Wx(Ae,$e){var ft,Et=8;for(ft=0;16>ft;++ft)Et+=Ae[$e+ft-32];Af(Et>>4,Ae,$e)}function rl(Ae,$e){Af(128,Ae,$e)}function to(Ae,$e,ft){return Ae+2*$e+ft+2>>2}function Pg(Ae,$e){var ft,Et=$e-32;for(Et=new Uint8Array([to(Ae[Et-1],Ae[Et+0],Ae[Et+1]),to(Ae[Et+0],Ae[Et+1],Ae[Et+2]),to(Ae[Et+1],Ae[Et+2],Ae[Et+3]),to(Ae[Et+2],Ae[Et+3],Ae[Et+4])]),ft=0;4>ft;++ft)r(Ae,$e+32*ft,Et,0,Et.length)}function Kx(Ae,$e){var ft=Ae[$e-1],Et=Ae[$e-1+32],ts=Ae[$e-1+64],hs=Ae[$e-1+96];Be(Ae,$e+0,16843009*to(Ae[$e-1-32],ft,Et)),Be(Ae,$e+32,16843009*to(ft,Et,ts)),Be(Ae,$e+64,16843009*to(Et,ts,hs)),Be(Ae,$e+96,16843009*to(ts,hs,hs))}function Tt(Ae,$e){var ft,Et=4;for(ft=0;4>ft;++ft)Et+=Ae[$e+ft-32]+Ae[$e-1+32*ft];for(Et>>=3,ft=0;4>ft;++ft)a(Ae,$e+32*ft,Et,4)}function He(Ae,$e){var ft=Ae[$e-1+0],Et=Ae[$e-1+32],ts=Ae[$e-1+64],hs=Ae[$e-1-32],gs=Ae[$e+0-32],Es=Ae[$e+1-32],Ps=Ae[$e+2-32],Qs=Ae[$e+3-32];Ae[$e+0+96]=to(Et,ts,Ae[$e-1+96]),Ae[$e+1+96]=Ae[$e+0+64]=to(ft,Et,ts),Ae[$e+2+96]=Ae[$e+1+64]=Ae[$e+0+32]=to(hs,ft,Et),Ae[$e+3+96]=Ae[$e+2+64]=Ae[$e+1+32]=Ae[$e+0+0]=to(gs,hs,ft),Ae[$e+3+64]=Ae[$e+2+32]=Ae[$e+1+0]=to(Es,gs,hs),Ae[$e+3+32]=Ae[$e+2+0]=to(Ps,Es,gs),Ae[$e+3+0]=to(Qs,Ps,Es)}function ot(Ae,$e){var ft=Ae[$e+1-32],Et=Ae[$e+2-32],ts=Ae[$e+3-32],hs=Ae[$e+4-32],gs=Ae[$e+5-32],Es=Ae[$e+6-32],Ps=Ae[$e+7-32];Ae[$e+0+0]=to(Ae[$e+0-32],ft,Et),Ae[$e+1+0]=Ae[$e+0+32]=to(ft,Et,ts),Ae[$e+2+0]=Ae[$e+1+32]=Ae[$e+0+64]=to(Et,ts,hs),Ae[$e+3+0]=Ae[$e+2+32]=Ae[$e+1+64]=Ae[$e+0+96]=to(ts,hs,gs),Ae[$e+3+32]=Ae[$e+2+64]=Ae[$e+1+96]=to(hs,gs,Es),Ae[$e+3+64]=Ae[$e+2+96]=to(gs,Es,Ps),Ae[$e+3+96]=to(Es,Ps,Ps)}function At(Ae,$e){var ft=Ae[$e-1+0],Et=Ae[$e-1+32],ts=Ae[$e-1+64],hs=Ae[$e-1-32],gs=Ae[$e+0-32],Es=Ae[$e+1-32],Ps=Ae[$e+2-32],Qs=Ae[$e+3-32];Ae[$e+0+0]=Ae[$e+1+64]=hs+gs+1>>1,Ae[$e+1+0]=Ae[$e+2+64]=gs+Es+1>>1,Ae[$e+2+0]=Ae[$e+3+64]=Es+Ps+1>>1,Ae[$e+3+0]=Ps+Qs+1>>1,Ae[$e+0+96]=to(ts,Et,ft),Ae[$e+0+64]=to(Et,ft,hs),Ae[$e+0+32]=Ae[$e+1+96]=to(ft,hs,gs),Ae[$e+1+32]=Ae[$e+2+96]=to(hs,gs,Es),Ae[$e+2+32]=Ae[$e+3+96]=to(gs,Es,Ps),Ae[$e+3+32]=to(Es,Ps,Qs)}function Ht(Ae,$e){var ft=Ae[$e+0-32],Et=Ae[$e+1-32],ts=Ae[$e+2-32],hs=Ae[$e+3-32],gs=Ae[$e+4-32],Es=Ae[$e+5-32],Ps=Ae[$e+6-32],Qs=Ae[$e+7-32];Ae[$e+0+0]=ft+Et+1>>1,Ae[$e+1+0]=Ae[$e+0+64]=Et+ts+1>>1,Ae[$e+2+0]=Ae[$e+1+64]=ts+hs+1>>1,Ae[$e+3+0]=Ae[$e+2+64]=hs+gs+1>>1,Ae[$e+0+32]=to(ft,Et,ts),Ae[$e+1+32]=Ae[$e+0+96]=to(Et,ts,hs),Ae[$e+2+32]=Ae[$e+1+96]=to(ts,hs,gs),Ae[$e+3+32]=Ae[$e+2+96]=to(hs,gs,Es),Ae[$e+3+64]=to(gs,Es,Ps),Ae[$e+3+96]=to(Es,Ps,Qs)}function qt(Ae,$e){var ft=Ae[$e-1+0],Et=Ae[$e-1+32],ts=Ae[$e-1+64],hs=Ae[$e-1+96];Ae[$e+0+0]=ft+Et+1>>1,Ae[$e+2+0]=Ae[$e+0+32]=Et+ts+1>>1,Ae[$e+2+32]=Ae[$e+0+64]=ts+hs+1>>1,Ae[$e+1+0]=to(ft,Et,ts),Ae[$e+3+0]=Ae[$e+1+32]=to(Et,ts,hs),Ae[$e+3+32]=Ae[$e+1+64]=to(ts,hs,hs),Ae[$e+3+64]=Ae[$e+2+64]=Ae[$e+0+96]=Ae[$e+1+96]=Ae[$e+2+96]=Ae[$e+3+96]=hs}function Wt(Ae,$e){var ft=Ae[$e-1+0],Et=Ae[$e-1+32],ts=Ae[$e-1+64],hs=Ae[$e-1+96],gs=Ae[$e-1-32],Es=Ae[$e+0-32],Ps=Ae[$e+1-32],Qs=Ae[$e+2-32];Ae[$e+0+0]=Ae[$e+2+32]=ft+gs+1>>1,Ae[$e+0+32]=Ae[$e+2+64]=Et+ft+1>>1,Ae[$e+0+64]=Ae[$e+2+96]=ts+Et+1>>1,Ae[$e+0+96]=hs+ts+1>>1,Ae[$e+3+0]=to(Es,Ps,Qs),Ae[$e+2+0]=to(gs,Es,Ps),Ae[$e+1+0]=Ae[$e+3+32]=to(ft,gs,Es),Ae[$e+1+32]=Ae[$e+3+64]=to(Et,ft,gs),Ae[$e+1+64]=Ae[$e+3+96]=to(ts,Et,ft),Ae[$e+1+96]=to(hs,ts,Et)}function Xt(Ae,$e){var ft;for(ft=0;8>ft;++ft)r(Ae,$e+32*ft,Ae,$e-32,8)}function ns(Ae,$e){var ft;for(ft=0;8>ft;++ft)a(Ae,$e,Ae[$e-1],8),$e+=32}function ps(Ae,$e,ft){var Et;for(Et=0;8>Et;++Et)a($e,ft+32*Et,Ae,8)}function Zs(Ae,$e){var ft,Et=8;for(ft=0;8>ft;++ft)Et+=Ae[$e+ft-32]+Ae[$e-1+32*ft];ps(Et>>4,Ae,$e)}function rn(Ae,$e){var ft,Et=4;for(ft=0;8>ft;++ft)Et+=Ae[$e+ft-32];ps(Et>>3,Ae,$e)}function mn(Ae,$e){var ft,Et=4;for(ft=0;8>ft;++ft)Et+=Ae[$e-1+32*ft];ps(Et>>3,Ae,$e)}function qn(Ae,$e){ps(128,Ae,$e)}function Zn(Ae,$e,ft){var Et=Ae[$e-ft],ts=Ae[$e+0],hs=3*(ts-Et)+rm[1020+Ae[$e-2*ft]-Ae[$e+ft]],gs=S1[112+(hs+4>>3)];Ae[$e-ft]=Zu[255+Et+S1[112+(hs+3>>3)]],Ae[$e+0]=Zu[255+ts-gs]}function la(Ae,$e,ft,Et){var ts=Ae[$e+0],hs=Ae[$e+ft];return rd[255+Ae[$e-2*ft]-Ae[$e-ft]]>Et||rd[255+hs-ts]>Et}function Br(Ae,$e,ft,Et){return 4*rd[255+Ae[$e-ft]-Ae[$e+0]]+rd[255+Ae[$e-2*ft]-Ae[$e+ft]]<=Et}function wr(Ae,$e,ft,Et,ts){var hs=Ae[$e-3*ft],gs=Ae[$e-2*ft],Es=Ae[$e-ft],Ps=Ae[$e+0],Qs=Ae[$e+ft],Dn=Ae[$e+2*ft],dr=Ae[$e+3*ft];return 4*rd[255+Es-Ps]+rd[255+gs-Qs]>Et?0:rd[255+Ae[$e-4*ft]-hs]<=ts&&rd[255+hs-gs]<=ts&&rd[255+gs-Es]<=ts&&rd[255+dr-Dn]<=ts&&rd[255+Dn-Qs]<=ts&&rd[255+Qs-Ps]<=ts}function Ea(Ae,$e,ft,Et){var ts=2*Et+1;for(Et=0;16>Et;++Et)Br(Ae,$e+Et,ft,ts)&&Zn(Ae,$e+Et,ft)}function na(Ae,$e,ft,Et){var ts=2*Et+1;for(Et=0;16>Et;++Et)Br(Ae,$e+Et*ft,1,ts)&&Zn(Ae,$e+Et*ft,1)}function yi(Ae,$e,ft,Et){var ts;for(ts=3;0>7,Xr=18*Gn+63>>7,Gn=9*Gn+63>>7;Ps[Qs-3*Dn]=Zu[255+Ps[Qs-3*Dn]+Gn],Ps[Qs-2*Dn]=Zu[255+dr+Xr],Ps[Qs-Dn]=Zu[255+Ws+rr],Ps[Qs+0]=Zu[255+Vn-rr],Ps[Qs+Dn]=Zu[255+or-Xr],Ps[Qs+2*Dn]=Zu[255+zr-Gn]}$e+=Et}}function Ni(Ae,$e,ft,Et,ts,hs,gs,Es){for(hs=2*hs+1;0>3)],zr=S1[112+(zr+3>>3)],rr=or+1>>1;Ps[Qs-2*Dn]=Zu[255+Ps[Qs-2*Dn]+rr],Ps[Qs-Dn]=Zu[255+dr+zr],Ps[Qs+0]=Zu[255+Ws-or],Ps[Qs+Dn]=Zu[255+Vn-rr]}$e+=Et}}function vi(Ae,$e,ft,Et,ts,hs){_i(Ae,$e,ft,1,16,Et,ts,hs)}function qo(Ae,$e,ft,Et,ts,hs){_i(Ae,$e,1,ft,16,Et,ts,hs)}function Ro(Ae,$e,ft,Et,ts,hs){var gs;for(gs=3;0Qs?0:255:Qs)&255,Qs=Ps,ts[hs+Es]=Dn}}function $r(Ae,$e,ft,Et){var ts=$e.width,hs=$e.o;if(t(Ae!=null&&$e!=null),0>ft||0>=Et||ft+Et>hs)return null;if(!Ae.Cc){if(Ae.ga==null){var gs;if(Ae.ga=new Rt,(gs=Ae.ga==null)||(gs=$e.width*$e.o,t(Ae.Gb.length==0),Ae.Gb=i(gs),Ae.Uc=0,Ae.Gb==null?gs=0:(Ae.mb=Ae.Gb,Ae.nb=Ae.Uc,Ae.rc=null,gs=1),gs=!gs),!gs){gs=Ae.ga;var Es=Ae.Fa,Ps=Ae.P,Qs=Ae.qc,Dn=Ae.mb,dr=Ae.nb,Ws=Ps+1,Vn=Qs-1,or=gs.l;if(t(Es!=null&&Dn!=null&&$e!=null),Lg[0]=null,Lg[1]=tn,Lg[2]=yn,Lg[3]=xr,gs.ca=Dn,gs.tb=dr,gs.c=$e.width,gs.i=$e.height,t(0=Qs)$e=0;else if(gs.$a=3&Es[Ps+0],gs.Z=Es[Ps+0]>>2&3,gs.Lc=Es[Ps+0]>>4&3,Ps=Es[Ps+0]>>6&3,0>gs.$a||1=gs.c*gs.i;gs=!$e}if(gs)return null;Ae.ga.Lc!=1?Ae.Ga=0:Et=hs-ft}t(Ae.ga!=null),t(ft+Et<=hs);e:{if($e=(Es=Ae.ga).c,hs=Es.l.o,Es.$a==0){if(Ws=Ae.rc,Vn=Ae.Vc,or=Ae.Fa,Ps=Ae.P+1+ft*$e,Qs=Ae.mb,Dn=Ae.nb+ft*$e,t(Ps<=Ae.P+Ae.qc),Es.Z!=0)for(t(Lg[Es.Z]!=null),gs=0;gs=$e)$e=1;else if(Es.ic||Ri(),Es.ic){Es=gs.V,Ws=gs.Ba,Vn=gs.c;var zr=gs.i,rr=(or=1,Ps=gs.$/Vn,Qs=gs.$%Vn,Dn=gs.m,dr=gs.s,gs.$),Xr=Vn*zr,Gn=Vn*$e,Na=dr.wc,pa=rr(zr=Zr(pa.G[0],pa.H[0],Dn)))Es[Ws+rr]=zr,++rr,++Qs>=Vn&&(Qs=0,++Ps<=$e&&!(Ps%16)&&Yn(gs,Ps));else{if(!(280>zr)){or=0;break t}zr=xn(zr-256,Dn);var Yi,Ui=Zr(pa.G[4],pa.H[4],Dn);if(Se(Dn),!(rr>=(Ui=Ar(Vn,Ui=xn(Ui,Dn)))&&Xr-rr>=zr)){or=0;break t}for(Yi=0;Yi=Vn;)Qs-=Vn,++Ps<=$e&&!(Ps%16)&&Yn(gs,Ps);rr$e?$e:Ps);break t}!or||Dn.h&&rr=hs&&(Ae.Cc=1),Et=1}if(!Et)return null;if(Ae.Cc&&((Et=Ae.ga)!=null&&(Et.mc=null),Ae.ga=null,0>23,Es[Ps+4*gs+1]=Es[Ps+4*gs+1]*dr>>23,Es[Ps+4*gs+2]=Es[Ps+4*gs+2]*dr>>23)}$e+=hs}}function xa(Ae,$e,ft,Et,ts){for(;0>4)*Ps>>16;Ae[$e+2*hs+0]=(240&gs|gs>>4)*Ps>>16&240|(15&gs|gs<<4)*Ps>>16>>4&15,Ae[$e+2*hs+1]=240&Qs|Es}$e+=ts}}function Oa(Ae,$e,ft,Et,ts,hs,gs,Es){var Ps,Qs,Dn=255;for(Qs=0;Qs>8}function Ri(){Wl=Ca,Wp=xa,Zm=Oa,Pb=jl}function Ki(Ae,$e,ft){R[Ae]=function(Et,ts,hs,gs,Es,Ps,Qs,Dn,dr,Ws,Vn,or,zr,rr,Xr,Gn,Na){var pa,Yi=Na-1>>1,Ui=Es[Ps+0]|Qs[Dn+0]<<16,il=dr[Ws+0]|Vn[or+0]<<16;t(Et!=null);var zi=3*Ui+il+131074>>2;for($e(Et[ts+0],255&zi,zi>>16,zr,rr),hs!=null&&(zi=3*il+Ui+131074>>2,$e(hs[gs+0],255&zi,zi>>16,Xr,Gn)),pa=1;pa<=Yi;++pa){var _c=Es[Ps+pa]|Qs[Dn+pa]<<16,Vh=dr[Ws+pa]|Vn[or+pa]<<16,Cl=Ui+_c+il+Vh+524296,Hi=Cl+2*(_c+il)>>3;zi=Hi+Ui>>1,Ui=(Cl=Cl+2*(Ui+Vh)>>3)+_c>>1,$e(Et[ts+2*pa-1],255&zi,zi>>16,zr,rr+(2*pa-1)*ft),$e(Et[ts+2*pa-0],255&Ui,Ui>>16,zr,rr+(2*pa-0)*ft),hs!=null&&(zi=Cl+il>>1,Ui=Hi+Vh>>1,$e(hs[gs+2*pa-1],255&zi,zi>>16,Xr,Gn+(2*pa-1)*ft),$e(hs[gs+2*pa+0],255&Ui,Ui>>16,Xr,Gn+(2*pa+0)*ft)),Ui=_c,il=Vh}1&Na||(zi=3*Ui+il+131074>>2,$e(Et[ts+Na-1],255&zi,zi>>16,zr,rr+(Na-1)*ft),hs!=null&&(zi=3*il+Ui+131074>>2,$e(hs[gs+Na-1],255&zi,zi>>16,Xr,Gn+(Na-1)*ft)))}}function Rc(){fp[Xm]=br,fp[If]=Rb,fp[Iu]=V_,fp[E0]=y4,fp[wi]=Cm,fp[Lf]=qh,fp[wv]=A1,fp[jv]=Rb,fp[Ry]=y4,fp[Nv]=Cm,fp[T0]=qh}function xd(Ae){return Ae&-16384?0>Ae?0:255:Ae>>H_}function ro(Ae,$e){return xd((19077*Ae>>8)+(26149*$e>>8)-14234)}function pc(Ae,$e,ft){return xd((19077*Ae>>8)-(6419*$e>>8)-(13320*ft>>8)+8708)}function ed(Ae,$e){return xd((19077*Ae>>8)+(33050*$e>>8)-17685)}function Nh(Ae,$e,ft,Et,ts){Et[ts+0]=ro(Ae,ft),Et[ts+1]=pc(Ae,$e,ft),Et[ts+2]=ed(Ae,$e)}function xu(Ae,$e,ft,Et,ts){Et[ts+0]=ed(Ae,$e),Et[ts+1]=pc(Ae,$e,ft),Et[ts+2]=ro(Ae,ft)}function Dd(Ae,$e,ft,Et,ts){var hs=pc(Ae,$e,ft);$e=hs<<3&224|ed(Ae,$e)>>3,Et[ts+0]=248&ro(Ae,ft)|hs>>5,Et[ts+1]=$e}function td(Ae,$e,ft,Et,ts){var hs=240&ed(Ae,$e)|15;Et[ts+0]=240&ro(Ae,ft)|pc(Ae,$e,ft)>>4,Et[ts+1]=hs}function Uh(Ae,$e,ft,Et,ts){Et[ts+0]=255,Nh(Ae,$e,ft,Et,ts+1)}function Nl(Ae,$e,ft,Et,ts){xu(Ae,$e,ft,Et,ts),Et[ts+3]=255}function ld(Ae,$e,ft,Et,ts){Nh(Ae,$e,ft,Et,ts),Et[ts+3]=255}function cd(Ae,$e,ft){R[Ae]=function(Et,ts,hs,gs,Es,Ps,Qs,Dn,dr){for(var Ws=Dn+(-2&dr)*ft;Dn!=Ws;)$e(Et[ts+0],hs[gs+0],Es[Ps+0],Qs,Dn),$e(Et[ts+1],hs[gs+0],Es[Ps+0],Qs,Dn+ft),ts+=2,++gs,++Ps,Dn+=2*ft;1&dr&&$e(Et[ts+0],hs[gs+0],Es[Ps+0],Qs,Dn)}}function yd(Ae,$e,ft){return ft==0?Ae==0?$e==0?6:5:$e==0?4:0:ft}function Wu(Ae,$e,ft,Et,ts){switch(Ae>>>30){case 3:ux($e,ft,Et,ts,0);break;case 2:hx($e,ft,Et,ts);break;case 1:Xd($e,ft,Et,ts)}}function $c(Ae,$e){var ft,Et,ts=$e.M,hs=$e.Nb,gs=Ae.oc,Es=Ae.pc+40,Ps=Ae.oc,Qs=Ae.pc+584,Dn=Ae.oc,dr=Ae.pc+600;for(ft=0;16>ft;++ft)gs[Es+32*ft-1]=129;for(ft=0;8>ft;++ft)Ps[Qs+32*ft-1]=129,Dn[dr+32*ft-1]=129;for(0ft;++ft)r(gs,Es+32*ft-4,gs,Es+32*ft+12,4);for(ft=-1;8>ft;++ft)r(Ps,Qs+32*ft-4,Ps,Qs+32*ft+4,4),r(Dn,dr+32*ft-4,Dn,dr+32*ft+4,4)}var Vn=Ae.Gd,or=Ae.Hd+Et,zr=Ws.ad,rr=Ws.Hc;if(0=Ae.za-1?a(Xr,Gn,Vn[or].y[15],4):r(Xr,Gn,Vn[or+1].y,0,4)),ft=0;4>ft;ft++)Xr[Gn+128+ft]=Xr[Gn+256+ft]=Xr[Gn+384+ft]=Xr[Gn+0+ft];for(ft=0;16>ft;++ft,rr<<=2)Xr=gs,Gn=Es+Yx[ft],Df[Ws.Ob[ft]](Xr,Gn),Wu(rr,zr,16*+ft,Xr,Gn)}else if(Xr=yd(Et,ts,Ws.Ob[0]),Oy[Xr](gs,Es),rr!=0)for(ft=0;16>ft;++ft,rr<<=2)Wu(rr,zr,16*+ft,gs,Es+Yx[ft]);for(ft=Ws.Gc,Xr=yd(Et,ts,Ws.Dd),Fy[Xr](Ps,Qs),Fy[Xr](Dn,dr),rr=zr,Xr=Ps,Gn=Qs,255&(Ws=0|ft)&&(170&Ws?uh(rr,256,Xr,Gn):al(rr,256,Xr,Gn)),Ws=Dn,rr=dr,255&(ft>>=8)&&(170&ft?uh(zr,320,Ws,rr):al(zr,320,Ws,rr)),tsft;++ft)r(Vn,or+ft*Ae.R,gs,Es+32*ft,16);for(ft=0;8>ft;++ft)r(zr,Ws+ft*Ae.B,Ps,Qs+32*ft,8),r(rr,Xr+ft*Ae.B,Dn,dr+32*ft,8)}}function Od(Ae,$e,ft,Et,ts,hs,gs,Es,Ps){var Qs=[0],Dn=[0],dr=0,Ws=Ps!=null?Ps.kd:0,Vn=Ps??new cn;if(Ae==null||12>ft)return 7;Vn.data=Ae,Vn.w=$e,Vn.ha=ft,$e=[$e],ft=[ft],Vn.gb=[Vn.gb];e:{var or=$e,zr=ft,rr=Vn.gb;if(t(Ae!=null),t(zr!=null),t(rr!=null),rr[0]=0,12<=zr[0]&&!n(Ae,or[0],"RIFF")){if(n(Ae,or[0]+8,"WEBP")){rr=3;break e}var Xr=Ee(Ae,or[0]+4);if(12>Xr||4294967286zr[0]-8){rr=7;break e}rr[0]=Xr,or[0]+=12,zr[0]-=12}rr=0}if(rr!=0)return rr;for(Xr=0rr[0])rr=7;else{if(!n(Gn,zr[0],"VP8X")){if(Ee(Gn,zr[0]+4)!=10){rr=3;break e}if(18>rr[0]){rr=7;break e}var Ui=Ee(Gn,zr[0]+8),il=1+Ye(Gn,zr[0]+12);if(2147483648<=il*(Gn=1+Ye(Gn,zr[0]+15))){rr=3;break e}Yi!=null&&(Yi[0]=Ui),Na!=null&&(Na[0]=il),pa!=null&&(pa[0]=Gn),zr[0]+=18,rr[0]-=18,zi[0]=1}rr=0}}if(dr=dr[0],or=or[0],rr!=0)return rr;if(zr=!!(2&or),!Xr&&dr)return 3;if(hs!=null&&(hs[0]=!!(16&or)),gs!=null&&(gs[0]=zr),Es!=null&&(Es[0]=0),gs=Qs[0],or=Dn[0],dr&&zr&&Ps==null){rr=0;break}if(4>ft){rr=7;break}if(Xr&&dr||!Xr&&!dr&&!n(Ae,$e[0],"ALPH")){ft=[ft],Vn.na=[Vn.na],Vn.P=[Vn.P],Vn.Sa=[Vn.Sa];e:{Ui=Ae,rr=$e,Xr=ft;var zi=Vn.gb;Na=Vn.na,pa=Vn.P,Yi=Vn.Sa,il=22,t(Ui!=null),t(Xr!=null),Gn=rr[0];var _c=Xr[0];for(t(Na!=null),t(Yi!=null),Na[0]=null,pa[0]=null,Yi[0]=0;;){if(rr[0]=Gn,Xr[0]=_c,8>_c){rr=7;break e}var Vh=Ee(Ui,Gn+4);if(4294967286zi){rr=3;break e}if(!n(Ui,Gn,"VP8 ")||!n(Ui,Gn,"VP8L")){rr=0;break e}if(_c[0]Xr[0])rr=7;else{if(Gn||il){if(zi=Ee(zi,Ui+4),12<=Na&&zi>Na-12){rr=3;break e}if(Ws&&zi>Xr[0]-8){rr=7;break e}pa[0]=zi,rr[0]+=8,Xr[0]-=8,Yi[0]=il}else Yi[0]=5<=Xr[0]&&zi[Ui+0]==47&&!(zi[Ui+4]>>5),pa[0]=Xr[0];rr=0}if(ft=ft[0],Vn.Ja=Vn.Ja[0],Vn.xa=Vn.xa[0],$e=$e[0],rr!=0)break;if(4294967286ft){rr=7;break}Es=gs,Ws=or,zr=hs,Ae==null||5>ft?Ae=0:5<=ft&&Ae[$e+0]==47&&!(Ae[$e+4]>>5)?(Xr=[0],zi=[0],Na=[0],me(pa=new fe,Ae,$e,ft),pr(pa,Xr,zi,Na)?(Es!=null&&(Es[0]=Xr[0]),Ws!=null&&(Ws[0]=zi[0]),zr!=null&&(zr[0]=Na[0]),Ae=1):Ae=0):Ae=0}else{if(10>ft){rr=7;break}Es=or,Ae==null||10>ft||!wa(Ae,$e+3,ft-3)?Ae=0:(Ws=Ae[$e+0]|Ae[$e+1]<<8|Ae[$e+2]<<16,zr=16383&(Ae[$e+7]<<8|Ae[$e+6]),Ae=16383&(Ae[$e+9]<<8|Ae[$e+8]),1&Ws||3<(Ws>>1&7)||!(Ws>>4&1)||Ws>>5>=Vn.Ja||!zr||!Ae?Ae=0:(gs&&(gs[0]=zr),Es&&(Es[0]=Ae),Ae=1))}if(!Ae||(gs=gs[0],or=or[0],dr&&(Qs[0]!=gs||Dn[0]!=or)))return 3;Ps!=null&&(Ps[0]=Vn,Ps.offset=$e-Ps.w,t(4294967286>$e-Ps.w),t(Ps.offset==Ps.ha-ft));break}return rr==0||rr==7&&dr&&Ps==null?(hs!=null&&(hs[0]|=Vn.na!=null&&0ft||(hs&=-2,gs&=-2),0>hs||0>gs||0>=Es||0>=Ps||hs+Es>Et||gs+Ps>ts))return 0;if($e.v=hs,$e.j=gs,$e.va=hs+Es,$e.o=gs+Ps,$e.U=Es,$e.T=Ps,$e.da=Ae!=null&&0Ae.S){var $e=Ae.f.RGBA;$e.fb+=(Ae.height-1)*$e.A,$e.A=-$e.A}else $e=Ae.f.kb,Ae=Ae.height,$e.O+=(Ae-1)*$e.fa,$e.fa=-$e.fa,$e.N+=(Ae-1>>1)*$e.Ab,$e.Ab=-$e.Ab,$e.W+=(Ae-1>>1)*$e.Db,$e.Db=-$e.Db,$e.F!=null&&($e.J+=(Ae-1)*$e.lb,$e.lb=-$e.lb);return 0}function lu(Ae,$e,ft,Et){if(Et==null||0>=Ae||0>=$e)return 2;if(ft!=null){if(ft.Da){var ts=ft.cd,hs=ft.bd,gs=-2&ft.v,Es=-2&ft.j;if(0>gs||0>Es||0>=ts||0>=hs||gs+ts>Ae||Es+hs>$e)return 2;Ae=ts,$e=hs}if(ft.da){if(!Oe(Ae,$e,ts=[ft.ib],hs=[ft.hb]))return 2;Ae=ts[0],$e=hs[0]}}Et.width=Ae,Et.height=$e;e:{var Ps=Et.width,Qs=Et.height;if(Ae=Et.S,0>=Ps||0>=Qs||!(Ae>=Xm&&13>Ae))Ae=2;else{if(0>=Et.Rd&&Et.sd==null){gs=hs=ts=$e=0;var Dn=(Es=Ps*Sv[Ae])*Qs;if(11>Ae||(hs=(Qs+1)/2*($e=(Ps+1)/2),Ae==12&&(gs=(ts=Ps)*Qs)),(Qs=i(Dn+2*hs+gs))==null){Ae=1;break e}Et.sd=Qs,11>Ae?((Ps=Et.f.RGBA).eb=Qs,Ps.fb=0,Ps.A=Es,Ps.size=Dn):((Ps=Et.f.kb).y=Qs,Ps.O=0,Ps.fa=Es,Ps.Fd=Dn,Ps.f=Qs,Ps.N=0+Dn,Ps.Ab=$e,Ps.Cd=hs,Ps.ea=Qs,Ps.W=0+Dn+hs,Ps.Db=$e,Ps.Ed=hs,Ae==12&&(Ps.F=Qs,Ps.J=0+Dn+2*hs),Ps.Tc=gs,Ps.lb=ts)}if($e=1,ts=Et.S,hs=Et.width,gs=Et.height,ts>=Xm&&13>ts)if(11>ts)Ae=Et.f.RGBA,$e&=(Es=Math.abs(Ae.A))*(gs-1)+hs<=Ae.size,$e&=Es>=hs*Sv[ts],$e&=Ae.eb!=null;else{Ae=Et.f.kb,Es=(hs+1)/2,Dn=(gs+1)/2,Ps=Math.abs(Ae.fa),Qs=Math.abs(Ae.Ab);var dr=Math.abs(Ae.Db),Ws=Math.abs(Ae.lb),Vn=Ws*(gs-1)+hs;$e&=Ps*(gs-1)+hs<=Ae.Fd,$e&=Qs*(Dn-1)+Es<=Ae.Cd,$e=($e&=dr*(Dn-1)+Es<=Ae.Ed)&Ps>=hs&Qs>=Es&dr>=Es,$e&=Ae.y!=null,$e&=Ae.f!=null,$e&=Ae.ea!=null,ts==12&&($e&=Ws>=hs,$e&=Vn<=Ae.Tc,$e&=Ae.F!=null)}else $e=0;Ae=$e?0:2}}return Ae!=0||ft!=null&&ft.fd&&(Ae=Wm(Et)),Ae}var rc=64,Ku=[0,1,3,7,15,31,63,127,255,511,1023,2047,4095,8191,16383,32767,65535,131071,262143,524287,1048575,2097151,4194303,8388607,16777215],gc=24,kl=32,sd=8,Tf=[0,0,1,1,2,2,2,2,3,3,3,3,3,3,3,3,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,4,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,5,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,6,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7,7];tt("Predictor0","PredictorAdd0"),R.Predictor0=function(){return 4278190080},R.Predictor1=function(Ae){return Ae},R.Predictor2=function(Ae,$e,ft){return $e[ft+0]},R.Predictor3=function(Ae,$e,ft){return $e[ft+1]},R.Predictor4=function(Ae,$e,ft){return $e[ft-1]},R.Predictor5=function(Ae,$e,ft){return nt(nt(Ae,$e[ft+1]),$e[ft+0])},R.Predictor6=function(Ae,$e,ft){return nt(Ae,$e[ft-1])},R.Predictor7=function(Ae,$e,ft){return nt(Ae,$e[ft+0])},R.Predictor8=function(Ae,$e,ft){return nt($e[ft-1],$e[ft+0])},R.Predictor9=function(Ae,$e,ft){return nt($e[ft+0],$e[ft+1])},R.Predictor10=function(Ae,$e,ft){return nt(nt(Ae,$e[ft-1]),nt($e[ft+0],$e[ft+1]))},R.Predictor11=function(Ae,$e,ft){var Et=$e[ft+0];return 0>=wt(Et>>24&255,Ae>>24&255,($e=$e[ft-1])>>24&255)+wt(Et>>16&255,Ae>>16&255,$e>>16&255)+wt(Et>>8&255,Ae>>8&255,$e>>8&255)+wt(255&Et,255&Ae,255&$e)?Et:Ae},R.Predictor12=function(Ae,$e,ft){var Et=$e[ft+0];return(et((Ae>>24&255)+(Et>>24&255)-(($e=$e[ft-1])>>24&255))<<24|et((Ae>>16&255)+(Et>>16&255)-($e>>16&255))<<16|et((Ae>>8&255)+(Et>>8&255)-($e>>8&255))<<8|et((255&Ae)+(255&Et)-(255&$e)))>>>0},R.Predictor13=function(Ae,$e,ft){var Et=$e[ft-1];return(at((Ae=nt(Ae,$e[ft+0]))>>24&255,Et>>24&255)<<24|at(Ae>>16&255,Et>>16&255)<<16|at(Ae>>8&255,Et>>8&255)<<8|at(255&Ae,255&Et))>>>0};var Pu=R.PredictorAdd0;R.PredictorAdd1=rt,tt("Predictor2","PredictorAdd2"),tt("Predictor3","PredictorAdd3"),tt("Predictor4","PredictorAdd4"),tt("Predictor5","PredictorAdd5"),tt("Predictor6","PredictorAdd6"),tt("Predictor7","PredictorAdd7"),tt("Predictor8","PredictorAdd8"),tt("Predictor9","PredictorAdd9"),tt("Predictor10","PredictorAdd10"),tt("Predictor11","PredictorAdd11"),tt("Predictor12","PredictorAdd12"),tt("Predictor13","PredictorAdd13");var up=R.PredictorAdd2;xs("ColorIndexInverseTransform","MapARGB","32b",function(Ae){return Ae>>8&255},function(Ae){return Ae}),xs("VP8LColorIndexInverseTransformAlpha","MapAlpha","8b",function(Ae){return Ae},function(Ae){return Ae>>8&255});var Km,vu=R.ColorIndexInverseTransform,Fl=R.MapARGB,Mf=R.VP8LColorIndexInverseTransformAlpha,Fd=R.MapAlpha,Gl=R.VP8LPredictorsAdd=[];Gl.length=16,(R.VP8LPredictors=[]).length=16,(R.VP8LPredictorsAdd_C=[]).length=16,(R.VP8LPredictors_C=[]).length=16;var km,Sm,Ig,da,Ec,Mi,Ym,ux,hx,uh,Xd,al,tl,sl,Or,$i,Qi,kh,nd,Po,hp,mx,Pf,Sl,Wl,Wp,Zm,Pb,k1=i(511),Ib=i(2041),_v=i(225),Yu=i(767),Kp=0,rm=Ib,S1=_v,Zu=Yu,rd=k1,Xm=0,If=1,Iu=2,E0=3,wi=4,Lf=5,wv=6,jv=7,Ry=8,Nv=9,T0=10,Nj=[2,3,7],Ok=[3,3,11],Dy=[280,256,256,256,40],Fk=[0,1,1,1,0],fx=[17,18,0,1,2,3,4,5,16,6,7,8,9,10,11,12,13,14,15],Rf=[24,7,23,25,40,6,39,41,22,26,38,42,56,5,55,57,21,27,54,58,37,43,72,4,71,73,20,28,53,59,70,74,36,44,88,69,75,52,60,3,87,89,19,29,86,90,35,45,68,76,85,91,51,61,104,2,103,105,18,30,102,106,34,46,84,92,67,77,101,107,50,62,120,1,119,121,83,93,17,31,100,108,66,78,118,122,33,47,117,123,49,63,99,109,82,94,0,116,124,65,79,16,32,98,110,48,115,125,81,95,64,114,126,97,111,80,113,127,96,112],Z2=[2954,2956,2958,2962,2970,2986,3018,3082,3212,3468,3980,5004],C1=8,Qm=[4,5,6,7,8,9,10,10,11,12,13,14,15,16,17,17,18,19,20,20,21,21,22,22,23,23,24,25,25,26,27,28,29,30,31,32,33,34,35,36,37,37,38,39,40,41,42,43,44,45,46,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,76,77,78,79,80,81,82,83,84,85,86,87,88,89,91,93,95,96,98,100,101,102,104,106,108,110,112,114,116,118,122,124,126,128,130,132,134,136,138,140,143,145,148,151,154,157],mp=[4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,60,62,64,66,68,70,72,74,76,78,80,82,84,86,88,90,92,94,96,98,100,102,104,106,108,110,112,114,116,119,122,125,128,131,134,137,140,143,146,149,152,155,158,161,164,167,170,173,177,181,185,189,193,197,201,205,209,213,217,221,225,229,234,239,245,249,254,259,264,269,274,279,284],Jm=null,hh=[[173,148,140,0],[176,155,140,135,0],[180,157,141,134,130,0],[254,254,243,230,196,177,153,140,133,130,129,0]],ef=[0,1,4,8,5,2,3,6,9,12,13,10,7,11,14,15],zk=[-0,1,-1,2,-2,3,4,6,-3,5,-4,-5,-6,7,-7,8,-8,-9],X2=[[[[128,128,128,128,128,128,128,128,128,128,128],[128,128,128,128,128,128,128,128,128,128,128],[128,128,128,128,128,128,128,128,128,128,128]],[[253,136,254,255,228,219,128,128,128,128,128],[189,129,242,255,227,213,255,219,128,128,128],[106,126,227,252,214,209,255,255,128,128,128]],[[1,98,248,255,236,226,255,255,128,128,128],[181,133,238,254,221,234,255,154,128,128,128],[78,134,202,247,198,180,255,219,128,128,128]],[[1,185,249,255,243,255,128,128,128,128,128],[184,150,247,255,236,224,128,128,128,128,128],[77,110,216,255,236,230,128,128,128,128,128]],[[1,101,251,255,241,255,128,128,128,128,128],[170,139,241,252,236,209,255,255,128,128,128],[37,116,196,243,228,255,255,255,128,128,128]],[[1,204,254,255,245,255,128,128,128,128,128],[207,160,250,255,238,128,128,128,128,128,128],[102,103,231,255,211,171,128,128,128,128,128]],[[1,152,252,255,240,255,128,128,128,128,128],[177,135,243,255,234,225,128,128,128,128,128],[80,129,211,255,194,224,128,128,128,128,128]],[[1,1,255,128,128,128,128,128,128,128,128],[246,1,255,128,128,128,128,128,128,128,128],[255,128,128,128,128,128,128,128,128,128,128]]],[[[198,35,237,223,193,187,162,160,145,155,62],[131,45,198,221,172,176,220,157,252,221,1],[68,47,146,208,149,167,221,162,255,223,128]],[[1,149,241,255,221,224,255,255,128,128,128],[184,141,234,253,222,220,255,199,128,128,128],[81,99,181,242,176,190,249,202,255,255,128]],[[1,129,232,253,214,197,242,196,255,255,128],[99,121,210,250,201,198,255,202,128,128,128],[23,91,163,242,170,187,247,210,255,255,128]],[[1,200,246,255,234,255,128,128,128,128,128],[109,178,241,255,231,245,255,255,128,128,128],[44,130,201,253,205,192,255,255,128,128,128]],[[1,132,239,251,219,209,255,165,128,128,128],[94,136,225,251,218,190,255,255,128,128,128],[22,100,174,245,186,161,255,199,128,128,128]],[[1,182,249,255,232,235,128,128,128,128,128],[124,143,241,255,227,234,128,128,128,128,128],[35,77,181,251,193,211,255,205,128,128,128]],[[1,157,247,255,236,231,255,255,128,128,128],[121,141,235,255,225,227,255,255,128,128,128],[45,99,188,251,195,217,255,224,128,128,128]],[[1,1,251,255,213,255,128,128,128,128,128],[203,1,248,255,255,128,128,128,128,128,128],[137,1,177,255,224,255,128,128,128,128,128]]],[[[253,9,248,251,207,208,255,192,128,128,128],[175,13,224,243,193,185,249,198,255,255,128],[73,17,171,221,161,179,236,167,255,234,128]],[[1,95,247,253,212,183,255,255,128,128,128],[239,90,244,250,211,209,255,255,128,128,128],[155,77,195,248,188,195,255,255,128,128,128]],[[1,24,239,251,218,219,255,205,128,128,128],[201,51,219,255,196,186,128,128,128,128,128],[69,46,190,239,201,218,255,228,128,128,128]],[[1,191,251,255,255,128,128,128,128,128,128],[223,165,249,255,213,255,128,128,128,128,128],[141,124,248,255,255,128,128,128,128,128,128]],[[1,16,248,255,255,128,128,128,128,128,128],[190,36,230,255,236,255,128,128,128,128,128],[149,1,255,128,128,128,128,128,128,128,128]],[[1,226,255,128,128,128,128,128,128,128,128],[247,192,255,128,128,128,128,128,128,128,128],[240,128,255,128,128,128,128,128,128,128,128]],[[1,134,252,255,255,128,128,128,128,128,128],[213,62,250,255,255,128,128,128,128,128,128],[55,93,255,128,128,128,128,128,128,128,128]],[[128,128,128,128,128,128,128,128,128,128,128],[128,128,128,128,128,128,128,128,128,128,128],[128,128,128,128,128,128,128,128,128,128,128]]],[[[202,24,213,235,186,191,220,160,240,175,255],[126,38,182,232,169,184,228,174,255,187,128],[61,46,138,219,151,178,240,170,255,216,128]],[[1,112,230,250,199,191,247,159,255,255,128],[166,109,228,252,211,215,255,174,128,128,128],[39,77,162,232,172,180,245,178,255,255,128]],[[1,52,220,246,198,199,249,220,255,255,128],[124,74,191,243,183,193,250,221,255,255,128],[24,71,130,219,154,170,243,182,255,255,128]],[[1,182,225,249,219,240,255,224,128,128,128],[149,150,226,252,216,205,255,171,128,128,128],[28,108,170,242,183,194,254,223,255,255,128]],[[1,81,230,252,204,203,255,192,128,128,128],[123,102,209,247,188,196,255,233,128,128,128],[20,95,153,243,164,173,255,203,128,128,128]],[[1,222,248,255,216,213,128,128,128,128,128],[168,175,246,252,235,205,255,255,128,128,128],[47,116,215,255,211,212,255,255,128,128,128]],[[1,121,236,253,212,214,255,255,128,128,128],[141,84,213,252,201,202,255,219,128,128,128],[42,80,160,240,162,185,255,205,128,128,128]],[[1,1,255,128,128,128,128,128,128,128,128],[244,1,255,128,128,128,128,128,128,128,128],[238,1,255,128,128,128,128,128,128,128,128]]]],g4=[[[231,120,48,89,115,113,120,152,112],[152,179,64,126,170,118,46,70,95],[175,69,143,80,85,82,72,155,103],[56,58,10,171,218,189,17,13,152],[114,26,17,163,44,195,21,10,173],[121,24,80,195,26,62,44,64,85],[144,71,10,38,171,213,144,34,26],[170,46,55,19,136,160,33,206,71],[63,20,8,114,114,208,12,9,226],[81,40,11,96,182,84,29,16,36]],[[134,183,89,137,98,101,106,165,148],[72,187,100,130,157,111,32,75,80],[66,102,167,99,74,62,40,234,128],[41,53,9,178,241,141,26,8,107],[74,43,26,146,73,166,49,23,157],[65,38,105,160,51,52,31,115,128],[104,79,12,27,217,255,87,17,7],[87,68,71,44,114,51,15,186,23],[47,41,14,110,182,183,21,17,194],[66,45,25,102,197,189,23,18,22]],[[88,88,147,150,42,46,45,196,205],[43,97,183,117,85,38,35,179,61],[39,53,200,87,26,21,43,232,171],[56,34,51,104,114,102,29,93,77],[39,28,85,171,58,165,90,98,64],[34,22,116,206,23,34,43,166,73],[107,54,32,26,51,1,81,43,31],[68,25,106,22,64,171,36,225,114],[34,19,21,102,132,188,16,76,124],[62,18,78,95,85,57,50,48,51]],[[193,101,35,159,215,111,89,46,111],[60,148,31,172,219,228,21,18,111],[112,113,77,85,179,255,38,120,114],[40,42,1,196,245,209,10,25,109],[88,43,29,140,166,213,37,43,154],[61,63,30,155,67,45,68,1,209],[100,80,8,43,154,1,51,26,71],[142,78,78,16,255,128,34,197,171],[41,40,5,102,211,183,4,1,221],[51,50,17,168,209,192,23,25,82]],[[138,31,36,171,27,166,38,44,229],[67,87,58,169,82,115,26,59,179],[63,59,90,180,59,166,93,73,154],[40,40,21,116,143,209,34,39,175],[47,15,16,183,34,223,49,45,183],[46,17,33,183,6,98,15,32,183],[57,46,22,24,128,1,54,17,37],[65,32,73,115,28,128,23,128,205],[40,3,9,115,51,192,18,6,223],[87,37,9,115,59,77,64,21,47]],[[104,55,44,218,9,54,53,130,226],[64,90,70,205,40,41,23,26,57],[54,57,112,184,5,41,38,166,213],[30,34,26,133,152,116,10,32,134],[39,19,53,221,26,114,32,73,255],[31,9,65,234,2,15,1,118,73],[75,32,12,51,192,255,160,43,51],[88,31,35,67,102,85,55,186,85],[56,21,23,111,59,205,45,37,192],[55,38,70,124,73,102,1,34,98]],[[125,98,42,88,104,85,117,175,82],[95,84,53,89,128,100,113,101,45],[75,79,123,47,51,128,81,171,1],[57,17,5,71,102,57,53,41,49],[38,33,13,121,57,73,26,1,85],[41,10,67,138,77,110,90,47,114],[115,21,2,10,102,255,166,23,6],[101,29,16,10,85,128,101,196,26],[57,18,10,102,102,213,34,20,43],[117,20,15,36,163,128,68,1,26]],[[102,61,71,37,34,53,31,243,192],[69,60,71,38,73,119,28,222,37],[68,45,128,34,1,47,11,245,171],[62,17,19,70,146,85,55,62,70],[37,43,37,154,100,163,85,160,1],[63,9,92,136,28,64,32,201,85],[75,15,9,9,64,255,184,119,16],[86,6,28,5,64,255,25,248,1],[56,8,17,132,137,255,55,116,128],[58,15,20,82,135,57,26,121,40]],[[164,50,31,137,154,133,25,35,218],[51,103,44,131,131,123,31,6,158],[86,40,64,135,148,224,45,183,128],[22,26,17,131,240,154,14,1,209],[45,16,21,91,64,222,7,1,197],[56,21,39,155,60,138,23,102,213],[83,12,13,54,192,255,68,47,28],[85,26,85,85,128,128,32,146,171],[18,11,7,63,144,171,4,4,246],[35,27,10,146,174,171,12,26,128]],[[190,80,35,99,180,80,126,54,45],[85,126,47,87,176,51,41,20,32],[101,75,128,139,118,146,116,128,85],[56,41,15,176,236,85,37,9,62],[71,30,17,119,118,255,17,18,138],[101,38,60,138,55,70,43,26,142],[146,36,19,30,171,255,97,27,20],[138,45,61,62,219,1,81,188,64],[32,41,20,117,151,142,20,21,163],[112,19,12,61,195,128,48,4,24]]],x4=[[[[255,255,255,255,255,255,255,255,255,255,255],[255,255,255,255,255,255,255,255,255,255,255],[255,255,255,255,255,255,255,255,255,255,255]],[[176,246,255,255,255,255,255,255,255,255,255],[223,241,252,255,255,255,255,255,255,255,255],[249,253,253,255,255,255,255,255,255,255,255]],[[255,244,252,255,255,255,255,255,255,255,255],[234,254,254,255,255,255,255,255,255,255,255],[253,255,255,255,255,255,255,255,255,255,255]],[[255,246,254,255,255,255,255,255,255,255,255],[239,253,254,255,255,255,255,255,255,255,255],[254,255,254,255,255,255,255,255,255,255,255]],[[255,248,254,255,255,255,255,255,255,255,255],[251,255,254,255,255,255,255,255,255,255,255],[255,255,255,255,255,255,255,255,255,255,255]],[[255,253,254,255,255,255,255,255,255,255,255],[251,254,254,255,255,255,255,255,255,255,255],[254,255,254,255,255,255,255,255,255,255,255]],[[255,254,253,255,254,255,255,255,255,255,255],[250,255,254,255,254,255,255,255,255,255,255],[254,255,255,255,255,255,255,255,255,255,255]],[[255,255,255,255,255,255,255,255,255,255,255],[255,255,255,255,255,255,255,255,255,255,255],[255,255,255,255,255,255,255,255,255,255,255]]],[[[217,255,255,255,255,255,255,255,255,255,255],[225,252,241,253,255,255,254,255,255,255,255],[234,250,241,250,253,255,253,254,255,255,255]],[[255,254,255,255,255,255,255,255,255,255,255],[223,254,254,255,255,255,255,255,255,255,255],[238,253,254,254,255,255,255,255,255,255,255]],[[255,248,254,255,255,255,255,255,255,255,255],[249,254,255,255,255,255,255,255,255,255,255],[255,255,255,255,255,255,255,255,255,255,255]],[[255,253,255,255,255,255,255,255,255,255,255],[247,254,255,255,255,255,255,255,255,255,255],[255,255,255,255,255,255,255,255,255,255,255]],[[255,253,254,255,255,255,255,255,255,255,255],[252,255,255,255,255,255,255,255,255,255,255],[255,255,255,255,255,255,255,255,255,255,255]],[[255,254,254,255,255,255,255,255,255,255,255],[253,255,255,255,255,255,255,255,255,255,255],[255,255,255,255,255,255,255,255,255,255,255]],[[255,254,253,255,255,255,255,255,255,255,255],[250,255,255,255,255,255,255,255,255,255,255],[254,255,255,255,255,255,255,255,255,255,255]],[[255,255,255,255,255,255,255,255,255,255,255],[255,255,255,255,255,255,255,255,255,255,255],[255,255,255,255,255,255,255,255,255,255,255]]],[[[186,251,250,255,255,255,255,255,255,255,255],[234,251,244,254,255,255,255,255,255,255,255],[251,251,243,253,254,255,254,255,255,255,255]],[[255,253,254,255,255,255,255,255,255,255,255],[236,253,254,255,255,255,255,255,255,255,255],[251,253,253,254,254,255,255,255,255,255,255]],[[255,254,254,255,255,255,255,255,255,255,255],[254,254,254,255,255,255,255,255,255,255,255],[255,255,255,255,255,255,255,255,255,255,255]],[[255,254,255,255,255,255,255,255,255,255,255],[254,254,255,255,255,255,255,255,255,255,255],[254,255,255,255,255,255,255,255,255,255,255]],[[255,255,255,255,255,255,255,255,255,255,255],[254,255,255,255,255,255,255,255,255,255,255],[255,255,255,255,255,255,255,255,255,255,255]],[[255,255,255,255,255,255,255,255,255,255,255],[255,255,255,255,255,255,255,255,255,255,255],[255,255,255,255,255,255,255,255,255,255,255]],[[255,255,255,255,255,255,255,255,255,255,255],[255,255,255,255,255,255,255,255,255,255,255],[255,255,255,255,255,255,255,255,255,255,255]],[[255,255,255,255,255,255,255,255,255,255,255],[255,255,255,255,255,255,255,255,255,255,255],[255,255,255,255,255,255,255,255,255,255,255]]],[[[248,255,255,255,255,255,255,255,255,255,255],[250,254,252,254,255,255,255,255,255,255,255],[248,254,249,253,255,255,255,255,255,255,255]],[[255,253,253,255,255,255,255,255,255,255,255],[246,253,253,255,255,255,255,255,255,255,255],[252,254,251,254,254,255,255,255,255,255,255]],[[255,254,252,255,255,255,255,255,255,255,255],[248,254,253,255,255,255,255,255,255,255,255],[253,255,254,254,255,255,255,255,255,255,255]],[[255,251,254,255,255,255,255,255,255,255,255],[245,251,254,255,255,255,255,255,255,255,255],[253,253,254,255,255,255,255,255,255,255,255]],[[255,251,253,255,255,255,255,255,255,255,255],[252,253,254,255,255,255,255,255,255,255,255],[255,254,255,255,255,255,255,255,255,255,255]],[[255,252,255,255,255,255,255,255,255,255,255],[249,255,254,255,255,255,255,255,255,255,255],[255,255,254,255,255,255,255,255,255,255,255]],[[255,255,253,255,255,255,255,255,255,255,255],[250,255,255,255,255,255,255,255,255,255,255],[255,255,255,255,255,255,255,255,255,255,255]],[[255,255,255,255,255,255,255,255,255,255,255],[254,255,255,255,255,255,255,255,255,255,255],[255,255,255,255,255,255,255,255,255,255,255]]]],fA=[0,1,2,3,6,4,5,6,6,6,6,6,6,6,6,7,0],Oy=[],Df=[],Fy=[],Lb=1,Bk=2,Lg=[],fp=[];Ki("UpsampleRgbLinePair",Nh,3),Ki("UpsampleBgrLinePair",xu,3),Ki("UpsampleRgbaLinePair",ld,4),Ki("UpsampleBgraLinePair",Nl,4),Ki("UpsampleArgbLinePair",Uh,4),Ki("UpsampleRgba4444LinePair",td,2),Ki("UpsampleRgb565LinePair",Dd,2);var br=R.UpsampleRgbLinePair,V_=R.UpsampleBgrLinePair,Rb=R.UpsampleRgbaLinePair,y4=R.UpsampleBgraLinePair,Cm=R.UpsampleArgbLinePair,qh=R.UpsampleRgba4444LinePair,A1=R.UpsampleRgb565LinePair,E1=16,Yp=1<Et.ca.S||(alert("todo:WebPInitConvertARGBToYUV"),Et.ca.f.kb.F!=null&&Ri()),Et.Pb&&0(Ps=ft.Md)?0:100Qs;++Qs)12>(dr=ts.pb[Qs]).lc&&(dr.ia=Ps*G_[0>dr.lc?0:dr.lc]>>3),Dn|=dr.ia;Dn&&(alert("todo:VP8InitRandom"),ts.ia=1)}ts.Ga=ft.Id,100ts.Ga&&(ts.Ga=0)}(function(Ws,Vn){if(Ws==null)return 0;if(Vn==null)return Ss(Ws,2,"NULL VP8Io parameter in VP8Decode().");if(!Ws.cb&&!Ci(Ws,Vn))return 0;if(t(Ws.cb),Vn.ac==null||Vn.ac(Vn)){Vn.ob&&(Ws.L=0);var or=px[Ws.L];if(Ws.L==2?(Ws.yb=0,Ws.zb=0):(Ws.yb=Vn.v-or>>4,Ws.zb=Vn.j-or>>4,0>Ws.yb&&(Ws.yb=0),0>Ws.zb&&(Ws.zb=0)),Ws.Va=Vn.o+15+or>>4,Ws.Hb=Vn.va+15+or>>4,Ws.Hb>Ws.za&&(Ws.Hb=Ws.za),Ws.Va>Ws.Ub&&(Ws.Va=Ws.Ub),0or;++or){var rr;if(Ws.Qa.Cb){var Xr=Ws.Qa.Lb[or];Ws.Qa.Fb||(Xr+=zr.Tb)}else Xr=zr.Tb;for(rr=0;1>=rr;++rr){var Gn=Ws.gd[or][rr],Na=Xr;if(zr.Pc&&(Na+=zr.vd[0],rr&&(Na+=zr.od[0])),0<(Na=0>Na?0:63>2:pa>>1)>9-zr.wb&&(pa=9-zr.wb),1>pa&&(pa=1),Gn.dd=pa,Gn.tc=2*Na+pa,Gn.ld=40<=Na?2:15<=Na?1:0}else Gn.tc=0;Gn.La=rr}}}or=0}else Ss(Ws,6,"Frame setup failed"),or=Ws.a;if(or=or==0){if(or){Ws.$c=0,0Ws.Vb){if(Ws.Vb=0,Ws.Ec=i(Gn),Ws.Fc=0,Ws.Ec==null){or=Ss(Ws,1,"no memory during frame initialization.");break t}Ws.Vb=Gn}Gn=Ws.Ec,Na=Ws.Fc,Ws.Ac=Gn,Ws.Bc=Na,Na+=zr,Ws.Gd=l(Yi,dh),Ws.Hd=0,Ws.rb=l(Ui+1,_a),Ws.sb=1,Ws.wa=il?l(il,To):null,Ws.Y=0,Ws.D.Nb=0,Ws.D.wa=Ws.wa,Ws.D.Y=Ws.Y,0=or;++or)k1[255+or]=0>or?-or:or;for(or=-1020;1020>=or;++or)Ib[1020+or]=-128>or?-128:127=or;++or)_v[112+or]=-16>or?-16:15=or;++or)Yu[255+or]=0>or?0:255ol;++ol){var am,Dc=Zp[0+ol];for(am=0;4>am;++am){Dc=g4[Uc[tf+am]][Dc];for(var Cd=zk[Ue(po,Dc[0])];0>3;for(Cd=0;256>Cd;Cd+=16)ol[sf+Cd]=Qd}fh=1,Of=tf[0]}var bd=15&po.la,Ru=15&Lu.la;for(Cd=0;4>Cd;++Cd){var Rg=1&Ru;for(Qd=zd=0;4>Qd;++Qd)bd=bd>>1|(Rg=(Xu=Jm(Uc,Of,Xu=Rg+(1&bd),vd.Sc,fh,ol,sf))>fh)<<7,zd=zd<<2|(3>=4,Ru=Ru>>1|Rg<<7,am=(am<<8|zd)>>>0}for(Of=bd,fh=Ru>>4,mh=0;4>mh;mh+=2){for(zd=0,bd=po.la>>4+mh,Ru=Lu.la>>4+mh,Cd=0;2>Cd;++Cd){for(Rg=1&Ru,Qd=0;2>Qd;++Qd)Xu=Rg+(1&bd),bd=bd>>1|(Rg=0<(Xu=Jm(Uc,tf[2],Xu,vd.Qc,0,ol,sf)))<<3,zd=zd<<2|(3>=2,Ru=Ru>>1|Rg<<5}Dc|=zd<<4*mh,Of|=bd<<4<=Hi.zb&&Hi.M<=Hi.Va,Hi.Aa==0)t:{if(Cl.M=Hi.M,Cl.uc=po,$c(Hi,Cl),Do=1,Cl=(zd=Hi.D).Nb,po=(Dc=px[Hi.L])*Hi.R,Uc=Dc/2*Hi.B,Cd=16*Cl*Hi.R,Qd=8*Cl*Hi.B,tf=Hi.sa,Zp=Hi.ta-po+Cd,vd=Hi.qa,ol=Hi.ra-Uc+Qd,sf=Hi.Ha,Lu=Hi.Ia-Uc+Qd,Ru=(bd=zd.M)==0,am=bd>=Hi.Va-1,Hi.Aa==2&&$c(Hi,zd),zd.uc)for(Rg=(Xu=Hi).D.M,t(Xu.D.uc),zd=Xu.yb;zdli.o&&(bd=li.o),li.F=null,li.J=null,Hi.Fa!=null&&0>1),li.W+=Hi.B*(Dc>>1),li.F!=null&&(li.J+=li.width*Dc)),zd>1,li.W+=li.v>>1,li.F!=null&&(li.J+=li.v),li.ka=zd-li.j,li.U=li.va-li.v,li.T=bd-zd,Do=li.put(li))}Cl+1!=Hi.Ic||am||(r(Hi.sa,Hi.ta-po,tf,Zp+16*Hi.R,po),r(Hi.qa,Hi.ra-Uc,vd,ol+8*Hi.B,Uc),r(Hi.Ha,Hi.Ia-Uc,sf,Lu+8*Hi.B,Uc))}if(!Do)return Ss(_c,6,"Output aborted.")}return 1}(Ws,Vn)),Vn.bc!=null&&Vn.bc(Vn),or&=1}return or?(Ws.cb=0,or):0})(Ae,Et)||($e=Ae.a)}}else $e=Ae.a}$e==0&&gs.Oa!=null&&gs.Oa.fd&&($e=Wm(gs.ba))}gs=$e}hs=gs!=0?null:11>hs?Es.f.RGBA.eb:Es.f.kb.y}else hs=null;return hs};var Sv=[3,4,3,4,4,2,2,4,4,4,2,1,1]};function d(R,O){for(var B="",U=0;U<4;U++)B+=String.fromCharCode(R[O++]);return B}function u(R,O){return R[O+0]|R[O+1]<<8}function h(R,O){return(R[O+0]|R[O+1]<<8|R[O+2]<<16)>>>0}function m(R,O){return(R[O+0]|R[O+1]<<8|R[O+2]<<16|R[O+3]<<24)>>>0}new c;var p=[0],g=[0],x=[],y=new c,v=s,_=function(R,O){var B={},U=0,G=!1,H=0,Y=0;if(B.frames=[],!function(le,fe){for(var _e=0;_e<4;_e++)if(le[fe+_e]!="RIFF".charCodeAt(_e))return!0;return!1}(R,O)){for(m(R,O+=4),O+=8;O>1&1}se!="ANMF"&&(O+=oe)}return B}}(v,0);_.response=v,_.rgbaoutput=!0,_.dataurl=!1;var j=_.header?_.header:null,C=_.frames?_.frames:null;if(j){j.loop_counter=j.loop_count,p=[j.canvas_height],g=[j.canvas_width];for(var A=0;A'+n.replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'")+"",this.internal.__metadata__.metadataObjectNumber=this.internal.newObject(),this.internal.write("<< /Type /Metadata /Subtype /XML /Length "+s.length+" >>"),this.internal.write("stream"),this.internal.write(s),this.internal.write("endstream"),this.internal.write("endobj")}function sTn(){this.internal.__metadata__.metadataObjectNumber&&this.internal.write("/Metadata "+this.internal.__metadata__.metadataObjectNumber+" 0 R")}(function(s){var t,n,r,a,i,l,o,c,d,u=function(le){return le=le||{},this.isStrokeTransparent=le.isStrokeTransparent||!1,this.strokeOpacity=le.strokeOpacity||1,this.strokeStyle=le.strokeStyle||"#000000",this.fillStyle=le.fillStyle||"#000000",this.isFillTransparent=le.isFillTransparent||!1,this.fillOpacity=le.fillOpacity||1,this.font=le.font||"10px sans-serif",this.textBaseline=le.textBaseline||"alphabetic",this.textAlign=le.textAlign||"left",this.lineWidth=le.lineWidth||1,this.lineJoin=le.lineJoin||"miter",this.lineCap=le.lineCap||"butt",this.path=le.path||[],this.transform=le.transform!==void 0?le.transform.clone():new c,this.globalCompositeOperation=le.globalCompositeOperation||"normal",this.globalAlpha=le.globalAlpha||1,this.clip_path=le.clip_path||[],this.currentPoint=le.currentPoint||new l,this.miterLimit=le.miterLimit||10,this.lastPoint=le.lastPoint||new l,this.lineDashOffset=le.lineDashOffset||0,this.lineDash=le.lineDash||[],this.margin=le.margin||[0,0,0,0],this.prevPageLastElemOffset=le.prevPageLastElemOffset||0,this.ignoreClearRect=typeof le.ignoreClearRect!="boolean"||le.ignoreClearRect,this};s.events.push(["initialized",function(){this.context2d=new h(this),t=this.internal.f2,n=this.internal.getCoordinateString,r=this.internal.getVerticalCoordinateString,a=this.internal.getHorizontalCoordinate,i=this.internal.getVerticalCoordinate,l=this.internal.Point,o=this.internal.Rectangle,c=this.internal.Matrix,d=new u}]);var h=function(le){Object.defineProperty(this,"canvas",{get:function(){return{parentNode:!1,style:!1}}});var fe=le;Object.defineProperty(this,"pdf",{get:function(){return fe}});var _e=!1;Object.defineProperty(this,"pageWrapXEnabled",{get:function(){return _e},set:function(Re){_e=!!Re}});var ve=!1;Object.defineProperty(this,"pageWrapYEnabled",{get:function(){return ve},set:function(Re){ve=!!Re}});var he=0;Object.defineProperty(this,"posX",{get:function(){return he},set:function(Re){isNaN(Re)||(he=Re)}});var Se=0;Object.defineProperty(this,"posY",{get:function(){return Se},set:function(Re){isNaN(Re)||(Se=Re)}}),Object.defineProperty(this,"margin",{get:function(){return d.margin},set:function(Re){var ke;typeof Re=="number"?ke=[Re,Re,Re,Re]:((ke=new Array(4))[0]=Re[0],ke[1]=Re.length>=2?Re[1]:ke[0],ke[2]=Re.length>=3?Re[2]:ke[0],ke[3]=Re.length>=4?Re[3]:ke[1]),d.margin=ke}});var Te=!1;Object.defineProperty(this,"autoPaging",{get:function(){return Te},set:function(Re){Te=Re}});var Ie=0;Object.defineProperty(this,"lastBreak",{get:function(){return Ie},set:function(Re){Ie=Re}});var Ue=[];Object.defineProperty(this,"pageBreaks",{get:function(){return Ue},set:function(Re){Ue=Re}}),Object.defineProperty(this,"ctx",{get:function(){return d},set:function(Re){Re instanceof u&&(d=Re)}}),Object.defineProperty(this,"path",{get:function(){return d.path},set:function(Re){d.path=Re}});var Be=[];Object.defineProperty(this,"ctxStack",{get:function(){return Be},set:function(Re){Be=Re}}),Object.defineProperty(this,"fillStyle",{get:function(){return this.ctx.fillStyle},set:function(Re){var ke;ke=m(Re),this.ctx.fillStyle=ke.style,this.ctx.isFillTransparent=ke.a===0,this.ctx.fillOpacity=ke.a,this.pdf.setFillColor(ke.r,ke.g,ke.b,{a:ke.a}),this.pdf.setTextColor(ke.r,ke.g,ke.b,{a:ke.a})}}),Object.defineProperty(this,"strokeStyle",{get:function(){return this.ctx.strokeStyle},set:function(Re){var ke=m(Re);this.ctx.strokeStyle=ke.style,this.ctx.isStrokeTransparent=ke.a===0,this.ctx.strokeOpacity=ke.a,ke.a===0?this.pdf.setDrawColor(255,255,255):(ke.a,this.pdf.setDrawColor(ke.r,ke.g,ke.b))}}),Object.defineProperty(this,"lineCap",{get:function(){return this.ctx.lineCap},set:function(Re){["butt","round","square"].indexOf(Re)!==-1&&(this.ctx.lineCap=Re,this.pdf.setLineCap(Re))}}),Object.defineProperty(this,"lineWidth",{get:function(){return this.ctx.lineWidth},set:function(Re){isNaN(Re)||(this.ctx.lineWidth=Re,this.pdf.setLineWidth(Re))}}),Object.defineProperty(this,"lineJoin",{get:function(){return this.ctx.lineJoin},set:function(Re){["bevel","round","miter"].indexOf(Re)!==-1&&(this.ctx.lineJoin=Re,this.pdf.setLineJoin(Re))}}),Object.defineProperty(this,"miterLimit",{get:function(){return this.ctx.miterLimit},set:function(Re){isNaN(Re)||(this.ctx.miterLimit=Re,this.pdf.setMiterLimit(Re))}}),Object.defineProperty(this,"textBaseline",{get:function(){return this.ctx.textBaseline},set:function(Re){this.ctx.textBaseline=Re}}),Object.defineProperty(this,"textAlign",{get:function(){return this.ctx.textAlign},set:function(Re){["right","end","center","left","start"].indexOf(Re)!==-1&&(this.ctx.textAlign=Re)}});var je=null,Ye=null,Ee=null;Object.defineProperty(this,"fontFaces",{get:function(){return Ee},set:function(Re){je=null,Ye=null,Ee=Re}}),Object.defineProperty(this,"font",{get:function(){return this.ctx.font},set:function(Re){var ke;if(this.ctx.font=Re,(ke=/^\s*(?=(?:(?:[-a-z]+\s*){0,2}(italic|oblique))?)(?=(?:(?:[-a-z]+\s*){0,2}(small-caps))?)(?=(?:(?:[-a-z]+\s*){0,2}(bold(?:er)?|lighter|[1-9]00))?)(?:(?:normal|\1|\2|\3)\s*){0,3}((?:xx?-)?(?:small|large)|medium|smaller|larger|[.\d]+(?:\%|in|[cem]m|ex|p[ctx]))(?:\s*\/\s*(normal|[.\d]+(?:\%|in|[cem]m|ex|p[ctx])))?\s*([-_,\"\'\sa-z0-9]+?)\s*$/i.exec(Re))!==null){var Fe=ke[1];ke[2];var Oe=ke[3],Ge=ke[4];ke[5];var yt=ke[6],tt=/^([.\d]+)((?:%|in|[cem]m|ex|p[ctx]))$/i.exec(Ge)[2];Ge=Math.floor(tt==="px"?parseFloat(Ge)*this.pdf.internal.scaleFactor:tt==="em"?parseFloat(Ge)*this.pdf.getFontSize():parseFloat(Ge)*this.pdf.internal.scaleFactor),this.pdf.setFontSize(Ge);var ut=function(xs){var st,dt,jt=[],gt=xs.trim();if(gt==="")return MDe;if(gt in Qvt)return[Qvt[gt]];for(;gt!=="";){switch(dt=null,st=(gt=e1t(gt)).charAt(0)){case'"':case"'":dt=YEn(gt.substring(1),st);break;default:dt=ZEn(gt)}if(dt===null||(jt.push(dt[0]),(gt=e1t(dt[1]))!==""&>.charAt(0)!==","))return MDe;gt=gt.replace(/^,/,"")}return jt}(yt);if(this.fontFaces){var nt=function(xs,st){var dt=xs.getFontList(),jt=JSON.stringify(dt);if(je===null||Ye!==jt){var gt=function(rs){var Ns=[];return Object.keys(rs).forEach(function(us){rs[us].forEach(function(Bs){var Ts=null;switch(Bs){case"bold":Ts={family:us,weight:"bold"};break;case"italic":Ts={family:us,style:"italic"};break;case"bolditalic":Ts={family:us,weight:"bold",style:"italic"};break;case"":case"normal":Ts={family:us}}Ts!==null&&(Ts.ref={name:us,style:Bs},Ns.push(Ts))})}),Ns}(dt);je=function(rs){for(var Ns={},us=0;us=700||Fe==="bold")&&(wt="bold"),Fe==="italic"&&(wt+="italic"),wt.length===0&&(wt="normal");for(var rt="",Ft={arial:"Helvetica",Arial:"Helvetica",verdana:"Helvetica",Verdana:"Helvetica",helvetica:"Helvetica",Helvetica:"Helvetica","sans-serif":"Helvetica",fixed:"Courier",monospace:"Courier",terminal:"Courier",cursive:"Times",fantasy:"Times",serif:"Times"},Ut=0;Ut=2*Math.PI&&(ve=0,he=2*Math.PI),this.path.push({type:"arc",x:le,y:fe,radius:_e,startAngle:ve,endAngle:he,counterclockwise:Se})},h.prototype.arcTo=function(le,fe,_e,ve,he){throw new Error("arcTo not implemented.")},h.prototype.rect=function(le,fe,_e,ve){if(isNaN(le)||isNaN(fe)||isNaN(_e)||isNaN(ve))throw dm.error("jsPDF.context2d.rect: Invalid arguments",arguments),new Error("Invalid arguments passed to jsPDF.context2d.rect");this.moveTo(le,fe),this.lineTo(le+_e,fe),this.lineTo(le+_e,fe+ve),this.lineTo(le,fe+ve),this.lineTo(le,fe),this.lineTo(le+_e,fe),this.lineTo(le,fe)},h.prototype.fillRect=function(le,fe,_e,ve){if(isNaN(le)||isNaN(fe)||isNaN(_e)||isNaN(ve))throw dm.error("jsPDF.context2d.fillRect: Invalid arguments",arguments),new Error("Invalid arguments passed to jsPDF.context2d.fillRect");if(!p.call(this)){var he={};this.lineCap!=="butt"&&(he.lineCap=this.lineCap,this.lineCap="butt"),this.lineJoin!=="miter"&&(he.lineJoin=this.lineJoin,this.lineJoin="miter"),this.beginPath(),this.rect(le,fe,_e,ve),this.fill(),he.hasOwnProperty("lineCap")&&(this.lineCap=he.lineCap),he.hasOwnProperty("lineJoin")&&(this.lineJoin=he.lineJoin)}},h.prototype.strokeRect=function(le,fe,_e,ve){if(isNaN(le)||isNaN(fe)||isNaN(_e)||isNaN(ve))throw dm.error("jsPDF.context2d.strokeRect: Invalid arguments",arguments),new Error("Invalid arguments passed to jsPDF.context2d.strokeRect");g.call(this)||(this.beginPath(),this.rect(le,fe,_e,ve),this.stroke())},h.prototype.clearRect=function(le,fe,_e,ve){if(isNaN(le)||isNaN(fe)||isNaN(_e)||isNaN(ve))throw dm.error("jsPDF.context2d.clearRect: Invalid arguments",arguments),new Error("Invalid arguments passed to jsPDF.context2d.clearRect");this.ignoreClearRect||(this.fillStyle="#ffffff",this.fillRect(le,fe,_e,ve))},h.prototype.save=function(le){le=typeof le!="boolean"||le;for(var fe=this.pdf.internal.getCurrentPageInfo().pageNumber,_e=0;_e0||this.margin[1]>0||this.margin[2]>0||this.margin[3]>0};h.prototype.drawImage=function(le,fe,_e,ve,he,Se,Te,Ie,Ue){var Be=this.pdf.getImageProperties(le),je=1,Ye=1,Ee=1,Re=1;ve!==void 0&&Ie!==void 0&&(Ee=Ie/ve,Re=Ue/he,je=Be.width/ve*Ie/ve,Ye=Be.height/he*Ue/he),Se===void 0&&(Se=fe,Te=_e,fe=0,_e=0),ve!==void 0&&Ie===void 0&&(Ie=ve,Ue=he),ve===void 0&&Ie===void 0&&(Ie=Be.width,Ue=Be.height);var ke=this.ctx.transform.decompose(),Fe=oe(ke.rotate.shx),Oe=new c,Ge=(Oe=(Oe=(Oe=Oe.multiply(ke.translate)).multiply(ke.skew)).multiply(ke.scale)).applyToRectangle(new o(Se-fe*Ee,Te-_e*Re,ve*je,he*Ye));if(this.autoPaging){for(var yt,tt=y.call(this,Ge),ut=[],nt=0;ntet||wtGe||tt0)){for(;Ue>=0;Ue--)if(he[Ue-1].close!==!0&&he[Ue-1].begin!==!0){he[Ue-1].deltas.push(_e),he[Ue-1].abs.push(Ie);break}}break;case"bct":_e=[Ie.x1-Se[Te-1].x,Ie.y1-Se[Te-1].y,Ie.x2-Se[Te-1].x,Ie.y2-Se[Te-1].y,Ie.x-Se[Te-1].x,Ie.y-Se[Te-1].y],he[he.length-1].deltas.push(_e);break;case"qct":var Be=Se[Te-1].x+2/3*(Ie.x1-Se[Te-1].x),je=Se[Te-1].y+2/3*(Ie.y1-Se[Te-1].y),Ye=Ie.x+2/3*(Ie.x1-Ie.x),Ee=Ie.y+2/3*(Ie.y1-Ie.y),Re=Ie.x,ke=Ie.y;_e=[Be-Se[Te-1].x,je-Se[Te-1].y,Ye-Se[Te-1].x,Ee-Se[Te-1].y,Re-Se[Te-1].x,ke-Se[Te-1].y],he[he.length-1].deltas.push(_e);break;case"arc":he.push({deltas:[],abs:[],arc:!0}),Array.isArray(he[he.length-1].abs)&&he[he.length-1].abs.push(Ie)}}ve=fe?null:le==="stroke"?"stroke":"fill";for(var Fe=!1,Oe=0;Oe=.01&&(ve=this.pdf.internal.getFontSize(),this.pdf.setFontSize(ve*le.scale),he=this.lineWidth,this.lineWidth=he*le.scale);var Is=this.autoPaging!=="text";if(Is||Ut.y+Ut.h<=nt){if(Is||Ut.y>=tt&&Ut.x<=at){var xs=Is?le.text:this.pdf.splitTextToSize(le.text,le.maxWidth||at-Ut.x)[0],st=_([JSON.parse(JSON.stringify(Ye))],this.posX+this.margin[3],-rt+tt+this.ctx.prevPageLastElemOffset)[0],dt=Is&&(yt>Oe||yt=.01&&(this.pdf.setFontSize(ve),this.lineWidth=he)}}else le.scale>=.01&&(ve=this.pdf.internal.getFontSize(),this.pdf.setFontSize(ve*le.scale),he=this.lineWidth,this.lineWidth=he*le.scale),this.pdf.text(le.text,Ue.x+this.posX,Ue.y+this.posY,{angle:le.angle,align:fe,renderingMode:le.renderingMode,maxWidth:le.maxWidth}),le.scale>=.01&&(this.pdf.setFontSize(ve),this.lineWidth=he)},G=function(le,fe,_e,ve){_e=_e||0,ve=ve||0,this.pdf.internal.out(n(le+_e)+" "+r(fe+ve)+" l")},H=function(le,fe,_e){return this.pdf.lines(le,fe,_e,null,null)},Y=function(le,fe,_e,ve,he,Se,Te,Ie){this.pdf.internal.out([t(a(_e+le)),t(i(ve+fe)),t(a(he+le)),t(i(Se+fe)),t(a(Te+le)),t(i(Ie+fe)),"c"].join(" "))},se=function(le,fe,_e,ve){for(var he=2*Math.PI,Se=Math.PI/2;fe>_e;)fe-=he;var Te=Math.abs(_e-fe);Te1e-5;){var je=Be+Ue*Math.min(Te,Se);Ie.push(ee.call(this,le,Be,je)),Te-=Math.abs(je-Be),Be=je}return Ie},ee=function(le,fe,_e){var ve=(_e-fe)/2,he=le*Math.cos(ve),Se=le*Math.sin(ve),Te=he,Ie=-Se,Ue=Te*Te+Ie*Ie,Be=Ue+Te*he+Ie*Se,je=4/3*(Math.sqrt(2*Ue*Be)-Be)/(Te*Se-Ie*he),Ye=Te-je*Ie,Ee=Ie+je*Te,Re=Ye,ke=-Ee,Fe=ve+fe,Oe=Math.cos(Fe),Ge=Math.sin(Fe);return{x1:le*Math.cos(fe),y1:le*Math.sin(fe),x2:Ye*Oe-Ee*Ge,y2:Ye*Ge+Ee*Oe,x3:Re*Oe-ke*Ge,y3:Re*Ge+ke*Oe,x4:le*Math.cos(_e),y4:le*Math.sin(_e)}},oe=function(le){return 180*le/Math.PI},me=function(le,fe,_e,ve,he,Se){var Te=le+.5*(_e-le),Ie=fe+.5*(ve-fe),Ue=he+.5*(_e-he),Be=Se+.5*(ve-Se),je=Math.min(le,he,Te,Ue),Ye=Math.max(le,he,Te,Ue),Ee=Math.min(fe,Se,Ie,Be),Re=Math.max(fe,Se,Ie,Be);return new o(je,Ee,Ye-je,Re-Ee)},Q=function(le,fe,_e,ve,he,Se,Te,Ie){var Ue,Be,je,Ye,Ee,Re,ke,Fe,Oe,Ge,yt,tt,ut,nt,et=_e-le,at=ve-fe,wt=he-_e,rt=Se-ve,Ft=Te-he,Ut=Ie-Se;for(Be=0;Be<41;Be++)Oe=(ke=(je=le+(Ue=Be/40)*et)+Ue*((Ee=_e+Ue*wt)-je))+Ue*(Ee+Ue*(he+Ue*Ft-Ee)-ke),Ge=(Fe=(Ye=fe+Ue*at)+Ue*((Re=ve+Ue*rt)-Ye))+Ue*(Re+Ue*(Se+Ue*Ut-Re)-Fe),Be==0?(yt=Oe,tt=Ge,ut=Oe,nt=Ge):(yt=Math.min(yt,Oe),tt=Math.min(tt,Ge),ut=Math.max(ut,Oe),nt=Math.max(nt,Ge));return new o(Math.round(yt),Math.round(tt),Math.round(ut-yt),Math.round(nt-tt))},te=function(){if(this.prevLineDash||this.ctx.lineDash.length||this.ctx.lineDashOffset){var le,fe,_e=(le=this.ctx.lineDash,fe=this.ctx.lineDashOffset,JSON.stringify({lineDash:le,lineDashOffset:fe}));this.prevLineDash!==_e&&(this.pdf.setLineDash(this.ctx.lineDash,this.ctx.lineDashOffset),this.prevLineDash=_e)}}})(Oo.API),function(s){var t=function(l){var o,c,d,u,h,m,p,g,x,y;for(c=[],d=0,u=(l+=o="\0\0\0\0".slice(l.length%4||4)).length;u>d;d+=4)(h=(l.charCodeAt(d)<<24)+(l.charCodeAt(d+1)<<16)+(l.charCodeAt(d+2)<<8)+l.charCodeAt(d+3))!==0?(m=(h=((h=((h=((h=(h-(y=h%85))/85)-(x=h%85))/85)-(g=h%85))/85)-(p=h%85))/85)%85,c.push(m+33,p+33,g+33,x+33,y+33)):c.push(122);return function(v,_){for(var j=_;j>0;j--)v.pop()}(c,o.length),String.fromCharCode.apply(String,c)+"~>"},n=function(l){var o,c,d,u,h,m=String,p="length",g=255,x="charCodeAt",y="slice",v="replace";for(l[y](-2),l=l[y](0,-2)[v](/\s/g,"")[v]("z","!!!!!"),d=[],u=0,h=(l+=o="uuuuu"[y](l[p]%5||5))[p];h>u;u+=5)c=52200625*(l[x](u)-33)+614125*(l[x](u+1)-33)+7225*(l[x](u+2)-33)+85*(l[x](u+3)-33)+(l[x](u+4)-33),d.push(g&c>>24,g&c>>16,g&c>>8,g&c);return function(_,j){for(var C=j;C>0;C--)_.pop()}(d,o[p]),m.fromCharCode.apply(m,d)},r=function(l){return l.split("").map(function(o){return("0"+o.charCodeAt().toString(16)).slice(-2)}).join("")+">"},a=function(l){var o=new RegExp(/^([0-9A-Fa-f]{2})+$/);if((l=l.replace(/\s/g,"")).indexOf(">")!==-1&&(l=l.substr(0,l.indexOf(">"))),l.length%2&&(l+="0"),o.test(l)===!1)return"";for(var c="",d=0;dimport("./html2canvas.esm-CBrSDip1.js"),[])).catch(function(o){return Promise.reject(new Error("Could not load html2canvas: "+o))}).then(function(o){return o.default?o.default:o})}function n(){return(ac.DOMPurify?Promise.resolve(ac.DOMPurify):Ai(()=>import("./purify.es-BnINGy_Y.js"),[])).catch(function(o){return Promise.reject(new Error("Could not load dompurify: "+o))}).then(function(o){return o.default?o.default:o})}var r=function(o){var c=Rh(o);return c==="undefined"?"undefined":c==="string"||o instanceof String?"string":c==="number"||o instanceof Number?"number":c==="function"||o instanceof Function?"function":o&&o.constructor===Array?"array":o&&o.nodeType===1?"element":c==="object"?"object":"unknown"},a=function(o,c){var d=document.createElement(o);for(var u in c.className&&(d.className=c.className),c.innerHTML&&c.dompurify&&(d.innerHTML=c.dompurify.sanitize(c.innerHTML)),c.style)d.style[u]=c.style[u];return d},i=function o(c,d){for(var u=c.nodeType===3?document.createTextNode(c.nodeValue):c.cloneNode(!1),h=c.firstChild;h;h=h.nextSibling)d!==!0&&h.nodeType===1&&h.nodeName==="SCRIPT"||u.appendChild(o(h,d));return c.nodeType===1&&(c.nodeName==="CANVAS"?(u.width=c.width,u.height=c.height,u.getContext("2d").drawImage(c,0,0)):c.nodeName!=="TEXTAREA"&&c.nodeName!=="SELECT"||(u.value=c.value),u.addEventListener("load",function(){u.scrollTop=c.scrollTop,u.scrollLeft=c.scrollLeft},!0)),u},l=function o(c){var d=Object.assign(o.convert(Promise.resolve()),JSON.parse(JSON.stringify(o.template))),u=o.convert(Promise.resolve(),d);return(u=u.setProgress(1,o,1,[o])).set(c)};(l.prototype=Object.create(Promise.prototype)).constructor=l,l.convert=function(o,c){return o.__proto__=c||l.prototype,o},l.template={prop:{src:null,container:null,overlay:null,canvas:null,img:null,pdf:null,pageSize:null,callback:function(){}},progress:{val:0,state:null,n:0,stack:[]},opt:{filename:"file.pdf",margin:[0,0,0,0],enableLinks:!0,x:0,y:0,html2canvas:{},jsPDF:{},backgroundColor:"transparent"}},l.prototype.from=function(o,c){return this.then(function(){switch(c=c||function(d){switch(r(d)){case"string":return"string";case"element":return d.nodeName.toLowerCase()==="canvas"?"canvas":"element";default:return"unknown"}}(o),c){case"string":return this.then(n).then(function(d){return this.set({src:a("div",{innerHTML:o,dompurify:d})})});case"element":return this.set({src:o});case"canvas":return this.set({canvas:o});case"img":return this.set({img:o});default:return this.error("Unknown source type.")}})},l.prototype.to=function(o){switch(o){case"container":return this.toContainer();case"canvas":return this.toCanvas();case"img":return this.toImg();case"pdf":return this.toPdf();default:return this.error("Invalid target.")}},l.prototype.toContainer=function(){return this.thenList([function(){return this.prop.src||this.error("Cannot duplicate - no source HTML.")},function(){return this.prop.pageSize||this.setPageSize()}]).then(function(){var o={position:"relative",display:"inline-block",width:(typeof this.opt.width!="number"||isNaN(this.opt.width)||typeof this.opt.windowWidth!="number"||isNaN(this.opt.windowWidth)?Math.max(this.prop.src.clientWidth,this.prop.src.scrollWidth,this.prop.src.offsetWidth):this.opt.windowWidth)+"px",left:0,right:0,top:0,margin:"auto",backgroundColor:this.opt.backgroundColor},c=i(this.prop.src,this.opt.html2canvas.javascriptEnabled);c.tagName==="BODY"&&(o.height=Math.max(document.body.scrollHeight,document.body.offsetHeight,document.documentElement.clientHeight,document.documentElement.scrollHeight,document.documentElement.offsetHeight)+"px"),this.prop.overlay=a("div",{className:"html2pdf__overlay",style:{position:"fixed",overflow:"hidden",zIndex:1e3,left:"-100000px",right:0,bottom:0,top:0}}),this.prop.container=a("div",{className:"html2pdf__container",style:o}),this.prop.container.appendChild(c),this.prop.container.firstChild.appendChild(a("div",{style:{clear:"both",border:"0 none transparent",margin:0,padding:0,height:0}})),this.prop.container.style.float="none",this.prop.overlay.appendChild(this.prop.container),document.body.appendChild(this.prop.overlay),this.prop.container.firstChild.style.position="relative",this.prop.container.height=Math.max(this.prop.container.firstChild.clientHeight,this.prop.container.firstChild.scrollHeight,this.prop.container.firstChild.offsetHeight)+"px"})},l.prototype.toCanvas=function(){var o=[function(){return document.body.contains(this.prop.container)||this.toContainer()}];return this.thenList(o).then(t).then(function(c){var d=Object.assign({},this.opt.html2canvas);return delete d.onrendered,c(this.prop.container,d)}).then(function(c){(this.opt.html2canvas.onrendered||function(){})(c),this.prop.canvas=c,document.body.removeChild(this.prop.overlay)})},l.prototype.toContext2d=function(){var o=[function(){return document.body.contains(this.prop.container)||this.toContainer()}];return this.thenList(o).then(t).then(function(c){var d=this.opt.jsPDF,u=this.opt.fontFaces,h=typeof this.opt.width!="number"||isNaN(this.opt.width)||typeof this.opt.windowWidth!="number"||isNaN(this.opt.windowWidth)?1:this.opt.width/this.opt.windowWidth,m=Object.assign({async:!0,allowTaint:!0,scale:h,scrollX:this.opt.scrollX||0,scrollY:this.opt.scrollY||0,backgroundColor:"#ffffff",imageTimeout:15e3,logging:!0,proxy:null,removeContainer:!0,foreignObjectRendering:!1,useCORS:!1},this.opt.html2canvas);if(delete m.onrendered,d.context2d.autoPaging=this.opt.autoPaging===void 0||this.opt.autoPaging,d.context2d.posX=this.opt.x,d.context2d.posY=this.opt.y,d.context2d.margin=this.opt.margin,d.context2d.fontFaces=u,u)for(var p=0;px&&(g=y,y=x,x=g);else{if(o!=="l"&&o!=="landscape")throw"Invalid orientation: "+o;o="l",x>y&&(g=y,y=x,x=g)}return{width:y,height:x,unit:c,k:h,orientation:o}},s.html=function(o,c){(c=c||{}).callback=c.callback||function(){},c.html2canvas=c.html2canvas||{},c.html2canvas.canvas=c.html2canvas.canvas||this.canvas,c.jsPDF=c.jsPDF||this,c.fontFaces=c.fontFaces?c.fontFaces.map(TDe):null;var d=new l(c);return c.worker?d:d.from(o).doCallback()}}(Oo.API),Oo.API.addJS=function(s){var t,n,r=function(a){for(var i="",l=0;l=0&&a[d]==="\\";d--)c++;i+=c%2==0?"\\"+o:o}else i+=o}return i}(s);return this.internal.events.subscribe("postPutResources",function(){t=this.internal.newObject(),this.internal.out("<<"),this.internal.out("/Names [(EmbeddedJS) "+(t+1)+" 0 R]"),this.internal.out(">>"),this.internal.out("endobj"),n=this.internal.newObject(),this.internal.out("<<"),this.internal.out("/S /JavaScript"),this.internal.out("/JS ("+r+")"),this.internal.out(">>"),this.internal.out("endobj")}),this.internal.events.subscribe("putCatalog",function(){t!==void 0&&n!==void 0&&this.internal.out("/Names <>")}),this},function(s){var t;s.events.push(["postPutResources",function(){var n=this,r=/^(\d+) 0 obj$/;if(this.outline.root.children.length>0)for(var a=n.outline.render().split(/\r\n/),i=0;i> endobj")}var p=n.internal.newObject();for(n.internal.write("<< /Names [ "),i=0;i>","endobj"),t=n.internal.newObject(),n.internal.write("<< /Dests "+p+" 0 R"),n.internal.write(">>","endobj")}}]),s.events.push(["putCatalog",function(){var n=this;n.outline.root.children.length>0&&(n.internal.write("/Outlines",this.outline.makeRef(this.outline.root)),this.outline.createNamedDestinations&&n.internal.write("/Names "+t+" 0 R"))}]),s.events.push(["initialized",function(){var n=this;n.outline={createNamedDestinations:!1,root:{children:[]}},n.outline.add=function(r,a,i){var l={title:a,options:i,children:[]};return r==null&&(r=this.root),r.children.push(l),l},n.outline.render=function(){return this.ctx={},this.ctx.val="",this.ctx.pdf=n,this.genIds_r(this.root),this.renderRoot(this.root),this.renderItems(this.root),this.ctx.val},n.outline.genIds_r=function(r){r.id=n.internal.newObjectDeferred();for(var a=0;a0&&(this.line("/First "+this.makeRef(r.children[0])),this.line("/Last "+this.makeRef(r.children[r.children.length-1]))),this.line("/Count "+this.count_r({count:0},r)),this.objEnd()},n.outline.renderItems=function(r){for(var a=this.ctx.pdf.internal.getVerticalCoordinateString,i=0;i0&&this.line("/Prev "+this.makeRef(r.children[i-1])),i0&&(this.line("/First "+this.makeRef(l.children[0])),this.line("/Last "+this.makeRef(l.children[l.children.length-1])));var o=this.count=this.count_r({count:0},l);if(o>0&&this.line("/Count "+o),l.options&&l.options.pageNumber){var c=n.internal.getPageInfo(l.options.pageNumber);this.line("/Dest ["+c.objId+" 0 R /XYZ 0 "+a(0)+" 0]")}this.objEnd()}for(var d=0;d> \r endobj\r `},n.outline.count_r=function(r,a){for(var i=0;i1){H=!0,se=void 0;var he=R*O;ee=new Uint8Array(he);for(var Se=new DataView(B.buffer),Te=0;Te536870912)throw new Error("Image dimensions exceed 512MB, which is too large.");this.data=new Uint8Array(t);try{this[s]()}catch(n){dm.log("bit decode error:"+n)}},mN.prototype.bit1=function(){var s,t=Math.ceil(this.width/8),n=t%4;for(s=this.height-1;s>=0;s--){for(var r=this.bottom_up?s:this.height-1-s,a=0;a>7-o&1];this.data[l+4*o]=c.blue,this.data[l+4*o+1]=c.green,this.data[l+4*o+2]=c.red,this.data[l+4*o+3]=255}n!==0&&(this.pos+=4-n)}},mN.prototype.bit4=function(){for(var s=Math.ceil(this.width/2),t=s%4,n=this.height-1;n>=0;n--){for(var r=this.bottom_up?n:this.height-1-n,a=0;a>4,c=15&i,d=this.palette[o];if(this.data[l]=d.blue,this.data[l+1]=d.green,this.data[l+2]=d.red,this.data[l+3]=255,2*a+1>=this.width)break;d=this.palette[c],this.data[l+4]=d.blue,this.data[l+4+1]=d.green,this.data[l+4+2]=d.red,this.data[l+4+3]=255}t!==0&&(this.pos+=4-t)}},mN.prototype.bit8=function(){for(var s=this.width%4,t=this.height-1;t>=0;t--){for(var n=this.bottom_up?t:this.height-1-t,r=0;r=0;n--){for(var r=this.bottom_up?n:this.height-1-n,a=0;a>5&t)/t*255|0,c=(i>>10&t)/t*255|0,d=i>>15?255:0,u=r*this.width*4+4*a;this.data[u]=c,this.data[u+1]=o,this.data[u+2]=l,this.data[u+3]=d}this.pos+=s}},mN.prototype.bit16=function(){for(var s=this.width%3,t=parseInt("11111",2),n=parseInt("111111",2),r=this.height-1;r>=0;r--){for(var a=this.bottom_up?r:this.height-1-r,i=0;i>5&n)/n*255|0,d=(l>>11)/t*255|0,u=a*this.width*4+4*i;this.data[u]=d,this.data[u+1]=c,this.data[u+2]=o,this.data[u+3]=255}this.pos+=s}},mN.prototype.bit24=function(){for(var s=this.height-1;s>=0;s--){for(var t=this.bottom_up?s:this.height-1-s,n=0;n=0;s--)for(var t=this.bottom_up?s:this.height-1-s,n=0;nr&&(a.push(s.slice(c,i)),o=0,c=i),o+=t[i],i++;return c!==i&&a.push(s.slice(c,i)),a},n1t=function(s,t,n){n||(n={});var r,a,i,l,o,c,d,u=[],h=[u],m=n.textIndent||0,p=0,g=0,x=s.split(" "),y=zae.apply(this,[" ",n])[0];if(c=n.lineIndent===-1?x[0].length+2:n.lineIndent||0){var v=Array(c).join(" "),_=[];x.map(function(C){(C=C.split(/\s*\n/)).length>1?_=_.concat(C.map(function(A,M){return(M&&A.length?` `:"")+A})):_.push(C[0])}),x=_,c=t1t.apply(this,[v,n])}for(i=0,l=x.length;it||j){if(g>t){for(o=s1t.apply(this,[r,a,t-(m+p),t]),u.push(o.shift()),u=[o.pop()];o.length;)h.push([o.shift()]);g=a.slice(r.length-(u[0]?u[0].length:0)).reduce(function(C,A){return C+A},0)}else u=[r];h.push(u),m=g+c,p=y}else u.push(r),m+=p+g,p=y}return d=c?function(C,A){return(A?v:"")+C.join(" ")}:function(C){return C.join(" ")},h.map(d)},h9.splitTextToSize=function(s,t,n){var r,a=(n=n||{}).fontSize||this.internal.getFontSize(),i=(function(u){if(u.widths&&u.kerning)return{widths:u.widths,kerning:u.kerning};var h=this.internal.getFont(u.fontName,u.fontStyle),m="Unicode";return h.metadata[m]?{widths:h.metadata[m].widths||{0:1},kerning:h.metadata[m].kerning||{}}:{font:h.metadata,fontSize:this.internal.getFontSize(),charSpace:this.internal.getCharSpace()}}).call(this,n);r=Array.isArray(s)?s:String(s).split(/\r?\n/);var l=1*this.internal.scaleFactor*t/a;i.textIndent=n.textIndent?1*n.textIndent*this.internal.scaleFactor/a:0,i.lineIndent=n.lineIndent;var o,c,d=[];for(o=0,c=r.length;oimport("./index.es-D3jD2DzK.js"),[])).catch(function(m){return Promise.reject(new Error("Could not load canvg: "+m))}).then(function(m){return m.default?m.default:m}).then(function(m){return m.fromString(d,s,u)},function(){return Promise.reject(new Error("Could not load canvg."))}).then(function(m){return m.render(u)}).then(function(){h.addImage(c.toDataURL("image/jpeg",1),t,n,r,a,l,o)})},Oo.API.putTotalPages=function(s){var t,n=0;parseInt(this.internal.getFont().id.substr(1),10)<15?(t=new RegExp(s,"g"),n=this.internal.getNumberOfPages()):(t=new RegExp(this.pdfEscape16(s,this.internal.getFont()),"g"),n=this.pdfEscape16(this.internal.getNumberOfPages()+"",this.internal.getFont()));for(var r=1;r<=this.internal.getNumberOfPages();r++)for(var a=0;a1){for(u=0;u>`)}),this.internal.viewerpreferences.isSubscribed=!0),this.internal.viewerpreferences.configuration=n,this},Oo.API.addMetadata=function(s,t){return this.internal.__metadata__===void 0&&(this.internal.__metadata__={metadata:s,namespaceUri:t??"http://jspdf.default.namespaceuri/",rawXml:typeof t=="boolean"&&t},this.internal.events.subscribe("putCatalog",sTn),this.internal.events.subscribe("postPutResources",tTn)),this},function(s){var t=s.API,n=t.pdfEscape16=function(i,l){for(var o,c=l.metadata.Unicode.widths,d=["","0","00","000","0000"],u=[""],h=0,m=i.length;h> def /CMapName /Adobe-Identity-UCS def /CMapType 2 def 1 begincodespacerange <0000> endcodespacerange`,c=[],h=0,m=(o=Object.keys(i).sort(function(p,g){return p-g})).length;h=100&&(u+=` `+c.length+` beginbfchar `+c.join(` `)+` endbfchar`,c=[]),i[l]!==void 0&&i[l]!==null&&typeof i[l].toString=="function"&&(d=("0000"+i[l].toString(16)).slice(-4),l=("0000"+(+l).toString(16)).slice(-4),c.push("<"+l+"><"+d+">"));return c.length&&(u+=` `+c.length+` beginbfchar `+c.join(` `)+` endbfchar `),u+`endcmap CMapName currentdict /CMap defineresource pop end end`};t.events.push(["putFont",function(i){(function(l){var o=l.font,c=l.out,d=l.newObject,u=l.putStream;if(o.metadata instanceof s.API.TTFFont&&o.encoding==="Identity-H"){for(var h=o.metadata.Unicode.widths,m=o.metadata.subset.encode(o.metadata.glyIdsUsed,1),p="",g=0;g>"),c("endobj");var _=d();c("<<"),c("/Type /Font"),c("/BaseFont /"+$9(o.fontName)),c("/FontDescriptor "+v+" 0 R"),c("/W "+s.API.PDFObject.convert(h)),c("/CIDToGIDMap /Identity"),c("/DW 1000"),c("/Subtype /CIDFontType2"),c("/CIDSystemInfo"),c("<<"),c("/Supplement 0"),c("/Registry (Adobe)"),c("/Ordering ("+o.encoding+")"),c(">>"),c(">>"),c("endobj"),o.objectNumber=d(),c("<<"),c("/Type /Font"),c("/Subtype /Type0"),c("/ToUnicode "+y+" 0 R"),c("/BaseFont /"+$9(o.fontName)),c("/Encoding /"+o.encoding),c("/DescendantFonts ["+_+" 0 R]"),c(">>"),c("endobj"),o.isAlreadyPutted=!0}})(i)}]),t.events.push(["putFont",function(i){(function(l){var o=l.font,c=l.out,d=l.newObject,u=l.putStream;if(o.metadata instanceof s.API.TTFFont&&o.encoding==="WinAnsiEncoding"){for(var h=o.metadata.rawData,m="",p=0;p>"),c("endobj"),o.objectNumber=d();for(var v=0;v>"),c("endobj"),o.isAlreadyPutted=!0}})(i)}]);var a=function(i){var l,o=i.text||"",c=i.x,d=i.y,u=i.options||{},h=i.mutex||{},m=h.pdfEscape,p=h.activeFontKey,g=h.fonts,x=p,y="",v=0,_="",j=g[x].encoding;if(g[x].encoding!=="Identity-H")return{text:o,x:c,y:d,options:u,mutex:h};for(_=o,x=p,Array.isArray(o)&&(_=o[0]),v=0;v<_.length;v+=1)g[x].metadata.hasOwnProperty("cmap")&&(l=g[x].metadata.cmap.unicode.codeMap[_[v].charCodeAt(0)]),l||_[v].charCodeAt(0)<256&&g[x].metadata.hasOwnProperty("Unicode")?y+=_[v]:y+="";var C="";return parseInt(x.slice(1))<14||j==="WinAnsiEncoding"?C=m(y,x).split("").map(function(A){return A.charCodeAt(0).toString(16)}).join(""):j==="Identity-H"&&(C=n(y,g[x])),h.isHex=!0,{text:C,x:c,y:d,options:u,mutex:h}};t.events.push(["postProcessText",function(i){var l=i.text||"",o=[],c={text:l,x:i.x,y:i.y,options:i.options,mutex:i.mutex};if(Array.isArray(l)){var d=0;for(d=0;d","<","[","]","[","{","}","{","«","»","«","‹","›","‹","⁅","⁆","⁅","⁽","⁾","⁽","₍","₎","₍","≤","≥","≤","〈","〉","〈","﹙","﹚","﹙","﹛","﹜","﹛","﹝","﹞","﹝","﹤","﹥","﹤"],v=new RegExp(/^([1-4|9]|1[0-9]|2[0-9]|3[0168]|4[04589]|5[012]|7[78]|159|16[0-9]|17[0-2]|21[569]|22[03489]|250)$/),_=!1,j=0;this.__bidiEngine__={};var C=function(B){var U=B.charCodeAt(),G=U>>8,H=x[G];return H!==void 0?h[256*H+(255&U)]:G===252||G===253?"AL":v.test(G)?"L":G===8?"R":"N"},A=function(B){for(var U,G=0;G=U.length||(Y=G[H-1])!=="EN"&&Y!=="AN"||(se=U[H+1])!=="EN"&&se!=="AN"?me="N":_&&(se="AN"),me=se===Y?se:"N";break;case"ES":me=(Y=H>0?G[H-1]:"B")==="EN"&&H+10&&G[H-1]==="EN"){me="EN";break}if(_){me="N";break}for(ee=H+1,oe=U.length;ee=1425&&Q<=2303||Q===64286;if(Y=U[ee],te&&(Y==="R"||Y==="AL")){me="R";break}}}me=H<1||(Y=U[H-1])==="B"?"N":G[H-1];break;case"B":_=!1,a=!0,me=j;break;case"S":i=!0,me="N"}return me},I=function(B,U,G){var H=B.split("");return G&&P(H,G,{hiLevel:j}),H.reverse(),U&&U.reverse(),H.join("")},P=function(B,U,G){var H,Y,se,ee,oe,me=-1,Q=B.length,te=0,le=[],fe=j?p:m,_e=[];for(_=!1,a=!1,i=!1,Y=0;Y0)if(H===16){for(Y=me;Y-1){for(Y=me;Y=0&&ve[Ie]==="WS";Ie--)he[Ie]=j}}(_e,U,Q)},R=function(B,U,G,H,Y){if(!(Y.hiLevel=B){for(oe=te+1;oe=B;)oe++;for(me=te,ee=oe-1;me=0&&(se[Q]=y[me+1])}(H,G,Y),R(2,H,U,G,Y),R(1,H,U,G,Y),H.join("")};return this.__bidiEngine__.doBidiReorder=function(B,U,G){if(function(Y,se){if(se)for(var ee=0;ee>16)&&(n=-(1+(65535^n))),this.italicAngle=+(n+"."+r)):this.italicAngle=0,this.ascender=Math.round(this.ascender*this.scaleFactor),this.decender=Math.round(this.decender*this.scaleFactor),this.lineGap=Math.round(this.lineGap*this.scaleFactor),this.capHeight=this.os2.exists&&this.os2.capHeight||this.ascender,this.xHeight=this.os2.exists&&this.os2.xHeight||0,this.familyClass=(this.os2.exists&&this.os2.familyClass||0)>>8,this.isSerif=(i=this.familyClass)===1||i===2||i===3||i===4||i===5||i===7,this.isScript=this.familyClass===10,this.flags=0,this.post.isFixedPitch&&(this.flags|=1),this.isSerif&&(this.flags|=2),this.isScript&&(this.flags|=8),this.italicAngle!==0&&(this.flags|=64),this.flags|=32,!this.cmap.unicode)throw new Error("No unicode cmap for font")},s.prototype.characterToGlyph=function(t){var n;return((n=this.cmap.unicode)!=null?n.codeMap[t]:void 0)||0},s.prototype.widthOfGlyph=function(t){var n;return n=1e3/this.head.unitsPerEm,this.hmtx.forGlyph(t).advance*n},s.prototype.widthOfString=function(t,n,r){var a,i,l,o;for(l=0,i=0,o=(t=""+t).length;0<=o?io;i=0<=o?++i:--i)a=t.charCodeAt(i),l+=this.widthOfGlyph(this.characterToGlyph(a))+r*(1e3/n)||0;return l*(n/1e3)},s.prototype.lineHeight=function(t,n){var r;return n==null&&(n=!1),r=n?this.lineGap:0,(this.ascender+r-this.decender)/1e3*t},s}();var Dk,DM=function(){function s(t){this.data=t??[],this.pos=0,this.length=this.data.length}return s.prototype.readByte=function(){return this.data[this.pos++]},s.prototype.writeByte=function(t){return this.data[this.pos++]=t},s.prototype.readUInt32=function(){return 16777216*this.readByte()+(this.readByte()<<16)+(this.readByte()<<8)+this.readByte()},s.prototype.writeUInt32=function(t){return this.writeByte(t>>>24&255),this.writeByte(t>>16&255),this.writeByte(t>>8&255),this.writeByte(255&t)},s.prototype.readInt32=function(){var t;return(t=this.readUInt32())>=2147483648?t-4294967296:t},s.prototype.writeInt32=function(t){return t<0&&(t+=4294967296),this.writeUInt32(t)},s.prototype.readUInt16=function(){return this.readByte()<<8|this.readByte()},s.prototype.writeUInt16=function(t){return this.writeByte(t>>8&255),this.writeByte(255&t)},s.prototype.readInt16=function(){var t;return(t=this.readUInt16())>=32768?t-65536:t},s.prototype.writeInt16=function(t){return t<0&&(t+=65536),this.writeUInt16(t)},s.prototype.readString=function(t){var n,r;for(r=[],n=0;0<=t?nt;n=0<=t?++n:--n)r[n]=String.fromCharCode(this.readByte());return r.join("")},s.prototype.writeString=function(t){var n,r,a;for(a=[],n=0,r=t.length;0<=r?nr;n=0<=r?++n:--n)a.push(this.writeByte(t.charCodeAt(n)));return a},s.prototype.readShort=function(){return this.readInt16()},s.prototype.writeShort=function(t){return this.writeInt16(t)},s.prototype.readLongLong=function(){var t,n,r,a,i,l,o,c;return t=this.readByte(),n=this.readByte(),r=this.readByte(),a=this.readByte(),i=this.readByte(),l=this.readByte(),o=this.readByte(),c=this.readByte(),128&t?-1*(72057594037927940*(255^t)+281474976710656*(255^n)+1099511627776*(255^r)+4294967296*(255^a)+16777216*(255^i)+65536*(255^l)+256*(255^o)+(255^c)+1):72057594037927940*t+281474976710656*n+1099511627776*r+4294967296*a+16777216*i+65536*l+256*o+c},s.prototype.writeLongLong=function(t){var n,r;return n=Math.floor(t/4294967296),r=4294967295&t,this.writeByte(n>>24&255),this.writeByte(n>>16&255),this.writeByte(n>>8&255),this.writeByte(255&n),this.writeByte(r>>24&255),this.writeByte(r>>16&255),this.writeByte(r>>8&255),this.writeByte(255&r)},s.prototype.readInt=function(){return this.readInt32()},s.prototype.writeInt=function(t){return this.writeInt32(t)},s.prototype.read=function(t){var n,r;for(n=[],r=0;0<=t?rt;r=0<=t?++r:--r)n.push(this.readByte());return n},s.prototype.write=function(t){var n,r,a,i;for(i=[],r=0,a=t.length;ri;a=0<=i?++a:--a)r={tag:n.readString(4),checksum:n.readInt(),offset:n.readInt(),length:n.readInt()},this.tables[r.tag]=r}return t.prototype.encode=function(n){var r,a,i,l,o,c,d,u,h,m,p,g,x;for(x in p=Object.keys(n).length,c=Math.log(2),h=16*Math.floor(Math.log(p)/c),l=Math.floor(h/c),u=16*p-h,(a=new DM).writeInt(this.scalarType),a.writeShort(p),a.writeShort(h),a.writeShort(l),a.writeShort(u),i=16*p,d=a.pos+i,o=null,g=[],n)for(m=n[x],a.writeString(x),a.writeInt(s(m)),a.writeInt(d),a.writeInt(m.length),g=g.concat(m),x==="head"&&(o=d),d+=m.length;d%4;)g.push(0),d++;return a.write(g),r=2981146554-s(a.data),a.pos=o+8,a.writeUInt32(r),a.data},s=function(n){var r,a,i,l;for(n=a$t.call(n);n.length%4;)n.push(0);for(i=new DM(n),a=0,r=0,l=n.length;rm;c=0<=m?++C:--C)A.push(t.readUInt16());return A}(),t.pos+=2,x=function(){var C,A;for(A=[],c=C=0;0<=m?Cm;c=0<=m?++C:--C)A.push(t.readUInt16());return A}(),d=function(){var C,A;for(A=[],c=C=0;0<=m?Cm;c=0<=m?++C:--C)A.push(t.readUInt16());return A}(),u=function(){var C,A;for(A=[],c=C=0;0<=m?Cm;c=0<=m?++C:--C)A.push(t.readUInt16());return A}(),a=(this.length-t.pos+this.offset)/2,o=function(){var C,A;for(A=[],c=C=0;0<=a?Ca;c=0<=a?++C:--C)A.push(t.readUInt16());return A}(),c=v=0,j=i.length;v=y;r=g<=y?++_:--_)u[c]===0?l=r+d[c]:(l=o[u[c]/2+(r-g)-(m-c)]||0)!==0&&(l+=d[c]),this.codeMap[r]=65535&l}t.pos=h}return s.encode=function(t,n){var r,a,i,l,o,c,d,u,h,m,p,g,x,y,v,_,j,C,A,M,I,P,R,O,B,U,G,H,Y,se,ee,oe,me,Q,te,le,fe,_e,ve,he,Se,Te,Ie,Ue,Be,je;switch(H=new DM,l=Object.keys(t).sort(function(Ye,Ee){return Ye-Ee}),n){case"macroman":for(x=0,y=function(){var Ye=[];for(g=0;g<256;++g)Ye.push(0);return Ye}(),_={0:0},i={},Y=0,me=l.length;Y=32768)for(c.push(0),M.push(2*(p.length+R-g)),a=oe=B;B<=u?oe<=u:oe>=u;a=B<=u?++oe:--oe)p.push(r[a].new);else c.push(G-B),M.push(0)}for(H.writeUInt16(3),H.writeUInt16(1),H.writeUInt32(12),H.writeUInt16(4),H.writeUInt16(16+8*R+2*p.length),H.writeUInt16(0),H.writeUInt16(O),H.writeUInt16(P),H.writeUInt16(m),H.writeUInt16(I),Se=0,le=h.length;Sea;r=0<=a?++r:--r)n=new h1t(t,this.offset),this.tables.push(n),n.isUnicode&&this.unicode==null&&(this.unicode=n);return!0},s.encode=function(t,n){var r,a;return n==null&&(n="macroman"),r=h1t.encode(t,n),(a=new DM).writeUInt16(0),a.writeUInt16(1),r.table=a.data.concat(r.subtable),r},s}(),iTn=function(){function s(){return s.__super__.constructor.apply(this,arguments)}return m4(s,Dk),s.prototype.tag="hhea",s.prototype.parse=function(t){return t.pos=this.offset,this.version=t.readInt(),this.ascender=t.readShort(),this.decender=t.readShort(),this.lineGap=t.readShort(),this.advanceWidthMax=t.readShort(),this.minLeftSideBearing=t.readShort(),this.minRightSideBearing=t.readShort(),this.xMaxExtent=t.readShort(),this.caretSlopeRise=t.readShort(),this.caretSlopeRun=t.readShort(),this.caretOffset=t.readShort(),t.pos+=8,this.metricDataFormat=t.readShort(),this.numberOfMetrics=t.readUInt16()},s}(),oTn=function(){function s(){return s.__super__.constructor.apply(this,arguments)}return m4(s,Dk),s.prototype.tag="OS/2",s.prototype.parse=function(t){if(t.pos=this.offset,this.version=t.readUInt16(),this.averageCharWidth=t.readShort(),this.weightClass=t.readUInt16(),this.widthClass=t.readUInt16(),this.type=t.readShort(),this.ySubscriptXSize=t.readShort(),this.ySubscriptYSize=t.readShort(),this.ySubscriptXOffset=t.readShort(),this.ySubscriptYOffset=t.readShort(),this.ySuperscriptXSize=t.readShort(),this.ySuperscriptYSize=t.readShort(),this.ySuperscriptXOffset=t.readShort(),this.ySuperscriptYOffset=t.readShort(),this.yStrikeoutSize=t.readShort(),this.yStrikeoutPosition=t.readShort(),this.familyClass=t.readShort(),this.panose=function(){var n,r;for(r=[],n=0;n<10;++n)r.push(t.readByte());return r}(),this.charRange=function(){var n,r;for(r=[],n=0;n<4;++n)r.push(t.readInt());return r}(),this.vendorID=t.readString(4),this.selection=t.readShort(),this.firstCharIndex=t.readShort(),this.lastCharIndex=t.readShort(),this.version>0&&(this.ascent=t.readShort(),this.descent=t.readShort(),this.lineGap=t.readShort(),this.winAscent=t.readShort(),this.winDescent=t.readShort(),this.codePageRange=function(){var n,r;for(r=[],n=0;n<2;n=++n)r.push(t.readInt());return r}(),this.version>1))return this.xHeight=t.readShort(),this.capHeight=t.readShort(),this.defaultChar=t.readShort(),this.breakChar=t.readShort(),this.maxContext=t.readShort()},s}(),lTn=function(){function s(){return s.__super__.constructor.apply(this,arguments)}return m4(s,Dk),s.prototype.tag="post",s.prototype.parse=function(t){var n,r,a;switch(t.pos=this.offset,this.format=t.readInt(),this.italicAngle=t.readInt(),this.underlinePosition=t.readShort(),this.underlineThickness=t.readShort(),this.isFixedPitch=t.readInt(),this.minMemType42=t.readInt(),this.maxMemType42=t.readInt(),this.minMemType1=t.readInt(),this.maxMemType1=t.readInt(),this.format){case 65536:case 196608:break;case 131072:var i;for(r=t.readUInt16(),this.glyphNameIndex=[],i=0;0<=r?ir;i=0<=r?++i:--i)this.glyphNameIndex.push(t.readUInt16());for(this.names=[],a=[];t.poso;i=0<=o?++l:--l)c.push(t.readUInt32());return c}).call(this)}},s}(),cTn=function(s,t){this.raw=s,this.length=s.length,this.platformID=t.platformID,this.encodingID=t.encodingID,this.languageID=t.languageID},dTn=function(){function s(){return s.__super__.constructor.apply(this,arguments)}return m4(s,Dk),s.prototype.tag="name",s.prototype.parse=function(t){var n,r,a,i,l,o,c,d,u,h,m;for(t.pos=this.offset,t.readShort(),n=t.readShort(),o=t.readShort(),r=[],i=0;0<=n?in;i=0<=n?++i:--i)r.push({platformID:t.readShort(),encodingID:t.readShort(),languageID:t.readShort(),nameID:t.readShort(),length:t.readShort(),offset:this.offset+o+t.readShort()});for(c={},i=u=0,h=r.length;uo;n=0<=o?++n:--n)this.metrics.push({advance:t.readUInt16(),lsb:t.readInt16()});for(a=this.file.maxp.numGlyphs-this.file.hhea.numberOfMetrics,this.leftSideBearings=function(){var d,u;for(u=[],n=d=0;0<=a?da;n=0<=a?++d:--d)u.push(t.readInt16());return u}(),this.widths=(function(){var d,u,h,m;for(m=[],d=0,u=(h=this.metrics).length;da;n=0<=a?++l:--l)c.push(this.widths.push(r));return c},s.prototype.forGlyph=function(t){return t in this.metrics?this.metrics[t]:{advance:this.metrics[this.metrics.length-1].advance,lsb:this.leftSideBearings[t-this.metrics.length]}},s}(),a$t=[].slice,mTn=function(){function s(){return s.__super__.constructor.apply(this,arguments)}return m4(s,Dk),s.prototype.tag="glyf",s.prototype.parse=function(){return this.cache={}},s.prototype.glyphFor=function(t){var n,r,a,i,l,o,c,d,u,h;return t in this.cache?this.cache[t]:(i=this.file.loca,n=this.file.contents,r=i.indexOf(t),(a=i.lengthOf(t))===0?this.cache[t]=null:(n.pos=this.offset+r,l=(o=new DM(n.read(a))).readShort(),d=o.readShort(),h=o.readShort(),c=o.readShort(),u=o.readShort(),this.cache[t]=l===-1?new pTn(o,d,h,c,u):new fTn(o,l,d,h,c,u),this.cache[t]))},s.prototype.encode=function(t,n,r){var a,i,l,o,c;for(l=[],i=[],o=0,c=n.length;o0&&(a+=c)}for(var d=new Array(4*r.length),u=0;u>8,d[4*u+1]=(16711680&r[u])>>16,d[4*u]=(4278190080&r[u])>>24;return d},s}(),xTn=function(){function s(t){this.font=t,this.subset={},this.unicodes={},this.next=33}return s.prototype.generateCmap=function(){var t,n,r,a,i;for(n in a=this.font.cmap.tables[0].codeMap,t={},i=this.subset)r=i[n],t[n]=a[r];return t},s.prototype.glyphsFor=function(t){var n,r,a,i,l,o,c;for(a={},l=0,o=t.length;l0)for(i in c=this.glyphsFor(n))r=c[i],a[i]=r;return a},s.prototype.encode=function(t,n){var r,a,i,l,o,c,d,u,h,m,p,g,x,y,v;for(a in r=r$t.encode(this.generateCmap(),"unicode"),l=this.glyphsFor(t),p={0:0},v=r.charMap)p[(c=v[a]).old]=c.new;for(g in m=r.maxGlyphID,l)g in p||(p[g]=m++);return u=function(_){var j,C;for(j in C={},_)C[_[j]]=j;return C}(p),h=Object.keys(u).sort(function(_,j){return _-j}),x=function(){var _,j,C;for(C=[],_=0,j=h.length;_>"),i.join(` `)}return""+n},t}();const E$e=[{id:"signature",name:"Signature",description:"The default editorial look, tinted with your own brand and accent colors.",swatch:["#0E1B2C","#2A4C64","#B8965A","#FCFBF8"],brand:"#2A4C64",accent:"#B8965A",paper:"#FCFBF8",paperCool:"#F4F7FA",softLine:"#DFE4EA",bodyInk:"#484E58",headFont:"helvetica",useAgentColors:!0},{id:"land-ranch",name:"Land, Farm & Ranch",description:"Warm olive and saddle leather on a natural paper stock. Built for acreage and estates.",swatch:["#2C3A24","#3E5232","#B07C3A","#F7F4EC"],brand:"#3E5232",accent:"#B07C3A",paper:"#F7F4EC",paperCool:"#F0EDE1",softLine:"#DCD4C2",bodyInk:"#4C4A40",headFont:"times",useAgentColors:!1},{id:"luxury",name:"Luxury",description:"Near-black ink with brushed gold and serif headlines. Quiet, expensive, restrained.",swatch:["#0B0C0F","#16181E","#C9A84C","#FAF8F4"],brand:"#16181E",accent:"#C9A84C",paper:"#FAF8F4",paperCool:"#F2EFE8",softLine:"#E0DACB",bodyInk:"#4A4A50",headFont:"times",useAgentColors:!1},{id:"coastal",name:"Beaches",description:"Deep ocean navy, surf teal, and sea-glass paper. Bright, breezy, coastal.",swatch:["#08293A","#0F3B52","#2FA0A8","#F8FBFC"],brand:"#0F3B52",accent:"#2FA0A8",paper:"#F8FBFC",paperCool:"#EDF6F8",softLine:"#D2E3E9",bodyInk:"#44565E",headFont:"helvetica",useAgentColors:!1}],yTn="signature";function vTn(s){return E$e.find(t=>t.id===s)||E$e[0]}const Ic=792,Dm=612,aa=52;function m9(s){const t=(s||"").replace("#","").padEnd(6,"0");return[parseInt(t.slice(0,2),16)||0,parseInt(t.slice(2,4),16)||0,parseInt(t.slice(4,6),16)||0]}function Op(s,t,n){return[Math.round(s[0]+(t[0]-s[0])*n),Math.round(s[1]+(t[1]-s[1])*n),Math.round(s[2]+(t[2]-s[2])*n)]}const f4=[22,24,28],bb=[124,128,136],Fo=[255,255,255];function bTn(s){return s==null||!Number.isFinite(Number(s))?null:new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(Number(s))}const LDe="https://relzejiswnotikjgvjhz.supabase.co";function _Tn(s){if(!s||s.startsWith("data:")||s.startsWith("blob:"))return s;try{const t=new URL(s,window.location.origin);return t.origin===window.location.origin||t.origin===new URL(LDe).origin?s:`${LDe}/functions/v1/image-proxy?url=${encodeURIComponent(t.toString())}`}catch{return s}}async function zG(s,t=2e3){if(!s)return null;try{const n=await fetch(_Tn(s),{mode:"cors"});if(!n.ok)return null;const r=await n.blob(),a=URL.createObjectURL(r),i=await new Promise((x,y)=>{const v=new Image;v.crossOrigin="anonymous",v.onload=()=>x(v),v.onerror=y,v.src=a}),l=Math.min(1,t/i.naturalWidth),o=Math.max(1,Math.round(i.naturalWidth*l)),c=Math.max(1,Math.round(i.naturalHeight*l)),d=document.createElement("canvas");d.width=o,d.height=c,d.getContext("2d").drawImage(i,0,0,o,c),URL.revokeObjectURL(a);const h=r.type.includes("png"),m=h?"PNG":"JPEG",p=d.toDataURL(h?"image/png":"image/jpeg",.92);return{el:await new Promise(x=>{const y=new Image;y.onload=()=>x(y),y.onerror=()=>x(y),y.src=p}),dataUrl:p,w:o,h:c,format:m}}catch{return null}}let i$t={x:.5,y:.5};function wTn(s){i$t={x:Math.min(1,Math.max(0,(s==null?void 0:s.x)??.5)),y:Math.min(1,Math.max(0,(s==null?void 0:s.y)??.5))}}function fte(s,t,n,r,a,i,l={}){const o=l.dpi??2,c=Math.max(1,Math.round(a*o)),d=Math.max(1,Math.round(i*o)),u=document.createElement("canvas");u.width=c,u.height=d;const h=u.getContext("2d"),m=t.w/t.h,p=a/i;let g=0,x=0,y=t.w,v=t.h;const _=l.focal??i$t;if(m>p?(y=t.h*p,g=Math.min(Math.max(0,t.w*_.x-y/2),t.w-y)):(v=t.w/p,x=Math.min(Math.max(0,t.h*_.y-v/2),t.h-v)),l.radius&&l.radius>0){const A=Math.min(l.radius*o,c/2,d/2);h.beginPath(),h.moveTo(A,0),h.arcTo(c,0,c,d,A),h.arcTo(c,d,0,d,A),h.arcTo(0,d,0,0,A),h.arcTo(0,0,c,0,A),h.closePath(),h.clip()}const j=[];l.grayscale&&j.push("grayscale(1)"),l.blur&&j.push(`blur(${l.blur*o}px)`),j.length&&(h.filter=j.join(" "));try{h.drawImage(t.el,g,x,y,v,0,0,c,d)}catch{h.fillStyle="#e9e6e0",h.fillRect(0,0,c,d)}if(h.filter="none",l.tint&&l.tint.amount>0){const[A,M,I]=l.tint.color;h.globalCompositeOperation="multiply",h.fillStyle=`rgba(${A},${M},${I},${Math.min(1,l.tint.amount)})`,h.fillRect(0,0,c,d),h.globalCompositeOperation="source-over"}if(l.darken&&l.darken>0&&(h.fillStyle=`rgba(0,0,0,${Math.min(.9,l.darken)})`,h.fillRect(0,0,c,d)),l.gradient==="bottom"){const A=h.createLinearGradient(0,0,0,d);A.addColorStop(0,"rgba(0,0,0,0)"),A.addColorStop(.45,"rgba(0,0,0,0.05)"),A.addColorStop(1,"rgba(0,0,0,0.8)"),h.fillStyle=A,h.fillRect(0,0,c,d)}else if(l.gradient==="full"){const A=h.createLinearGradient(0,0,0,d);A.addColorStop(0,"rgba(0,0,0,0.4)"),A.addColorStop(.5,"rgba(0,0,0,0.18)"),A.addColorStop(1,"rgba(0,0,0,0.85)"),h.fillStyle=A,h.fillRect(0,0,c,d)}else if(l.gradient==="left"){const A=h.createLinearGradient(0,0,c,0);A.addColorStop(0,"rgba(0,0,0,0.75)"),A.addColorStop(.6,"rgba(0,0,0,0.15)"),A.addColorStop(1,"rgba(0,0,0,0)"),h.fillStyle=A,h.fillRect(0,0,c,d)}const C=u.toDataURL("image/jpeg",.92);s.addImage(C,"JPEG",n,r,a,i,void 0,"FAST")}function vO(s,t,n,r,a,i=3){const l=a*2,o=Math.max(1,Math.round(l*i)),c=document.createElement("canvas");c.width=o,c.height=o;const d=c.getContext("2d");d.fillStyle="#ffffff",d.fillRect(0,0,o,o),d.save(),d.beginPath(),d.arc(o/2,o/2,o/2,0,Math.PI*2),d.closePath(),d.clip();const u=t.w/t.h;let h=0,m=0,p=t.w,g=t.h;u>1?(p=t.h,h=(t.w-p)/2):(g=t.w,m=(t.h-g)/2);try{d.drawImage(t.el,h,m,p,g,0,0,o,o)}catch{}d.restore(),s.addImage(c.toDataURL("image/jpeg",.92),"JPEG",n-a,r-a,l,l,void 0,"FAST")}function VXe(s,t,n,r,a,i,l="left"){const o=t.w/t.h;let c=i,d=c*o;d>a&&(d=a,c=d/o);const u=l==="right"?n-d:n;return s.addImage(t.dataUrl,t.format,u,r,d,c,void 0,"FAST"),{w:d,h:c}}function o_(s,t){const n=s.GState;n&&s.setGState(new n({opacity:t}))}function jTn(s,t,n,r,a,i={font:"helvetica",size:10,color:f4}){s.setFont(i.font,i.style||"normal"),s.setFontSize(i.size),s.setTextColor(...i.color);const l=i.leading??i.size*1.5,o=s.splitTextToSize(t,a);return o.forEach((c,d)=>{s.text(c,n,r+d*l,i.align==="center"?{align:"center"}:void 0)}),r+o.length*l}function qV(s,t,n,r,a,i){let l=r;const o=i.size*1.45;return t.forEach(c=>{s.setFillColor(...i.accent),s.circle(n+2.4,l-i.size*.32,2,"F"),l=jTn(s,c,n+13,l,a-13,{font:i.font,size:i.size,color:i.color,leading:o})+(i.gap??7)}),l}function y1(s,t,n,r,a,i,l,o="F",c,d=.6){s.setFillColor(...l),c&&(s.setDrawColor(...c),s.setLineWidth(d)),s.roundedRect(t,n,r,a,i,i,o)}const GF='',WF='',NTn={title:"Facebook",slug:"facebook",get svg(){return GF+"Facebook"+WF+this.path+KF},path:"M9.101 23.691v-7.98H6.627v-3.667h2.474v-1.58c0-4.085 1.848-5.978 5.858-5.978.401 0 .955.042 1.468.103a8.68 8.68 0 0 1 1.141.195v3.325a8.623 8.623 0 0 0-.653-.036 26.805 26.805 0 0 0-.733-.009c-.707 0-1.259.096-1.675.309a1.686 1.686 0 0 0-.679.622c-.258.42-.374.995-.374 1.752v1.297h3.919l-.386 2.103-.287 1.564h-3.246v8.245C19.396 23.238 24 18.179 24 12.044c0-6.627-5.373-12-12-12s-12 5.373-12 12c0 5.628 3.874 10.35 9.101 11.647Z",source:"https://about.meta.com/brand/resources/facebook/logo",hex:"0866FF",guidelines:"https://about.meta.com/brand/resources/facebook/logo"},kTn={title:"Instagram",slug:"instagram",get svg(){return GF+"Instagram"+WF+this.path+KF},path:"M7.0301.084c-1.2768.0602-2.1487.264-2.911.5634-.7888.3075-1.4575.72-2.1228 1.3877-.6652.6677-1.075 1.3368-1.3802 2.127-.2954.7638-.4956 1.6365-.552 2.914-.0564 1.2775-.0689 1.6882-.0626 4.947.0062 3.2586.0206 3.6671.0825 4.9473.061 1.2765.264 2.1482.5635 2.9107.308.7889.72 1.4573 1.388 2.1228.6679.6655 1.3365 1.0743 2.1285 1.38.7632.295 1.6361.4961 2.9134.552 1.2773.056 1.6884.069 4.9462.0627 3.2578-.0062 3.668-.0207 4.9478-.0814 1.28-.0607 2.147-.2652 2.9098-.5633.7889-.3086 1.4578-.72 2.1228-1.3881.665-.6682 1.0745-1.3378 1.3795-2.1284.2957-.7632.4966-1.636.552-2.9124.056-1.2809.0692-1.6898.063-4.948-.0063-3.2583-.021-3.6668-.0817-4.9465-.0607-1.2797-.264-2.1487-.5633-2.9117-.3084-.7889-.72-1.4568-1.3876-2.1228C21.2982 1.33 20.628.9208 19.8378.6165 19.074.321 18.2017.1197 16.9244.0645 15.6471.0093 15.236-.005 11.977.0014 8.718.0076 8.31.0215 7.0301.0839m.1402 21.6932c-1.17-.0509-1.8053-.2453-2.2287-.408-.5606-.216-.96-.4771-1.3819-.895-.422-.4178-.6811-.8186-.9-1.378-.1644-.4234-.3624-1.058-.4171-2.228-.0595-1.2645-.072-1.6442-.079-4.848-.007-3.2037.0053-3.583.0607-4.848.05-1.169.2456-1.805.408-2.2282.216-.5613.4762-.96.895-1.3816.4188-.4217.8184-.6814 1.3783-.9003.423-.1651 1.0575-.3614 2.227-.4171 1.2655-.06 1.6447-.072 4.848-.079 3.2033-.007 3.5835.005 4.8495.0608 1.169.0508 1.8053.2445 2.228.408.5608.216.96.4754 1.3816.895.4217.4194.6816.8176.9005 1.3787.1653.4217.3617 1.056.4169 2.2263.0602 1.2655.0739 1.645.0796 4.848.0058 3.203-.0055 3.5834-.061 4.848-.051 1.17-.245 1.8055-.408 2.2294-.216.5604-.4763.96-.8954 1.3814-.419.4215-.8181.6811-1.3783.9-.4224.1649-1.0577.3617-2.2262.4174-1.2656.0595-1.6448.072-4.8493.079-3.2045.007-3.5825-.006-4.848-.0608M16.953 5.5864A1.44 1.44 0 1 0 18.39 4.144a1.44 1.44 0 0 0-1.437 1.4424M5.8385 12.012c.0067 3.4032 2.7706 6.1557 6.173 6.1493 3.4026-.0065 6.157-2.7701 6.1506-6.1733-.0065-3.4032-2.771-6.1565-6.174-6.1498-3.403.0067-6.156 2.771-6.1496 6.1738M8 12.0077a4 4 0 1 1 4.008 3.9921A3.9996 3.9996 0 0 1 8 12.0077",source:"https://about.meta.com/brand/resources/instagram",hex:"FF0069",guidelines:"https://about.meta.com/brand/resources/instagram"},STn={title:"Pinterest",slug:"pinterest",get svg(){return GF+"Pinterest"+WF+this.path+KF},path:"M12.017 0C5.396 0 .029 5.367.029 11.987c0 5.079 3.158 9.417 7.618 11.162-.105-.949-.199-2.403.041-3.439.219-.937 1.406-5.957 1.406-5.957s-.359-.72-.359-1.781c0-1.663.967-2.911 2.168-2.911 1.024 0 1.518.769 1.518 1.688 0 1.029-.653 2.567-.992 3.992-.285 1.193.6 2.165 1.775 2.165 2.128 0 3.768-2.245 3.768-5.487 0-2.861-2.063-4.869-5.008-4.869-3.41 0-5.409 2.562-5.409 5.199 0 1.033.394 2.143.889 2.741.099.12.112.225.085.345-.09.375-.293 1.199-.334 1.363-.053.225-.172.271-.401.165-1.495-.69-2.433-2.878-2.433-4.646 0-3.776 2.748-7.252 7.92-7.252 4.158 0 7.392 2.967 7.392 6.923 0 4.135-2.607 7.462-6.233 7.462-1.214 0-2.354-.629-2.758-1.379l-.749 2.848c-.269 1.045-1.004 2.352-1.498 3.146 1.123.345 2.306.535 3.55.535 6.607 0 11.985-5.365 11.985-11.987C23.97 5.39 18.592.026 11.985.026L12.017 0z",source:"https://business.pinterest.com/en/brand-guidelines",hex:"BD081C",guidelines:"https://business.pinterest.com/en/brand-guidelines"},CTn={title:"TikTok",slug:"tiktok",get svg(){return GF+"TikTok"+WF+this.path+KF},path:"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",source:"https://tiktok.com",hex:"000000"},ATn={title:"trulia",slug:"trulia",get svg(){return GF+"trulia"+WF+this.path+KF},path:"M17.6958 8.9368a.6678.6678 0 0 0 .095 1.329.6678.6678 0 0 0 .6678-.668.6678.6678 0 0 0-.7628-.661zm-4.3956.2812v1.121h.7513v3.4726h-.7513v1.121h2.6262v-1.121h-.7513V9.218Zm-12.549.121v1.3814H.0001v1.1281h.7513v1.0852c0 1.1799.9502 2.1362 2.1226 2.1362a2.1126 2.1126 0 0 0 .4608-.0507v-1.115a1.1025 1.1025 0 0 1-.3837.0685c-.5958 0-1.0789-.4689-1.0789-1.047v-1.0772H3.335v-1.1281H1.872V9.339Zm20.92 1.2609c-1.1147-.005-2.0196.9806-2.019 2.1905.0005 1.21.9043 2.1952 2.019 2.1905.0292 0 .0598-.0009.0877-.002.4221-.0111.8757-.2098 1.113-.488v.4218H24v-4.2458h-1.1275l-.0005.4236c-.2385-.2791-.692-.477-1.113-.4879-.0292-.002-.0585-.002-.0878-.002zm-14.8245.0473c-.5173.003-.9275.153-1.2964.654l-.2277-.64h-1.098v1.1271h.5195v3.1444h1.118v-2.1983a.9887.9887 0 0 1 .9851-.9906h.339v-1.0966Zm9.6549.047v1.1172h.7513v3.121h1.8736v-1.117h-.7514l.001-3.1212zm-8.2605.0298v2.2125c0 1.1773.9494 2.1315 2.1195 2.1315s2.1193-.9525 2.1193-2.1298v-2.214h-1.1186v2.2539a1.0018 1.0018 0 1 1-2.001 0v-2.254zm13.5857.9717c.5932 0 1.074.5008 1.0746 1.1191.0005.6184-.4814 1.1192-1.0746 1.1192-.5933 0-1.0742-.5008-1.075-1.1192-.0008-.6183.4817-1.1191 1.075-1.1191z",source:"https://www.trulia.com/newsroom/media/brand-logos",hex:"0A0B09",guidelines:"https://www.trulia.com/newsroom/media/brand-logos"},ETn={title:"YouTube",slug:"youtube",get svg(){return GF+"YouTube"+WF+this.path+KF},path:"M23.498 6.186a3.016 3.016 0 0 0-2.122-2.136C19.505 3.545 12 3.545 12 3.545s-7.505 0-9.377.505A3.017 3.017 0 0 0 .502 6.186C0 8.07 0 12 0 12s0 3.93.502 5.814a3.016 3.016 0 0 0 2.122 2.136c1.871.505 9.376.505 9.376.505s7.505 0 9.377-.505a3.015 3.015 0 0 0 2.122-2.136C24 15.93 24 12 24 12s0-3.93-.502-5.814zM9.545 15.568V8.432L15.818 12l-6.273 3.568z",source:"https://www.youtube.com/howyoutubeworks/resources/brand-resources/#logos-icons-and-colors",hex:"FF0000",guidelines:"https://www.youtube.com/howyoutubeworks/resources/brand-resources/#logos-icons-and-colors"},TTn={title:"Zillow",slug:"zillow",get svg(){return GF+"Zillow"+WF+this.path+KF},path:"M12.006 0L1.086 8.627v3.868c3.386-2.013 11.219-5.13 14.763-6.015.11-.024.16.005.227.078.372.427 1.586 1.899 1.916 2.301a.128.128 0 0 1-.03.195 43.607 43.607 0 0 0-6.67 6.527c-.03.037-.006.043.012.03 2.642-1.134 8.828-2.94 11.622-3.452V8.627zm-.48 11.177c-2.136.708-8.195 3.307-10.452 4.576V24h21.852v-7.936c-2.99.506-11.902 3.16-15.959 5.246a.183.183 0 0 1-.23-.036l-2.044-2.429c-.055-.061-.062-.098.011-.208 1.574-2.3 4.789-5.899 6.833-7.418.042-.03.031-.06-.012-.042Z",source:"https://www.zillow.com",hex:"006AFF"},MTn={facebook:NTn,instagram:kTn,youtube:ETn,tiktok:CTn,pinterest:STn,zillow:TTn,trulia:ATn},m1t=new Map;function PTn(s,t,n){return`${s}|${t}|${n}`}function ITn(s,t,n=128){const r=s.toLowerCase().replace(/[^a-z]/g,""),a=MTn[r];if(!a)return null;const i=PTn(r,t,n),l=m1t.get(i);if(l)return l;try{const o=document.createElement("canvas");o.width=n,o.height=n;const c=o.getContext("2d");if(!c)return null;c.clearRect(0,0,n,n),c.scale(n/24,n/24),c.fillStyle=t,c.fill(new Path2D(a.path));const d=o.toDataURL("image/png");return m1t.set(i,d),d}catch{return null}}const Kd="helvetica";let yq="helvetica";function o$t(s,t,n,r,a,i){const l=`#${n.map(d=>Math.round(d).toString(16).padStart(2,"0")).join("")}`,o=ITn(t,l,160);if(o){s.addImage(o,"PNG",r-i/2,a-i/2,i,i,void 0,"FAST");return}const c=i/2;s.setFillColor(...n),s.circle(r,a,c,"F"),s.setFont(Kd,"bold"),s.setFontSize(c*1.15),s.setTextColor(...Fo),s.text(t.charAt(0).toUpperCase(),r,a+c*.42,{align:"center"})}let pte=[252,251,248],rF=[244,247,250],T_=[223,228,234],yv=[72,78,88];function gte(s,t){return dBt(s.data.pages,t)}function HXe(s){var n;const t=s.coAgent;return t!=null&&t.enabled&&((n=t.name)!=null&&n.trim())?t:null}function l$t(s){const t=s.property,n=[t.city,[t.state,t.postalCode].filter(Boolean).join(" ")].filter(Boolean).join(", ");return{line1:t.addressLine1||"Your Home",line2:n}}function LTn(s){return[s.agent.brokerageName,s.agent.phone,s.agent.email].filter(Boolean).join(" | ")}function Xg(s,t,n,r,a,i,l){const o=l.font||Kd,c=l.style||"normal";let d=i;s.setFont(o,c),s.setFontSize(d);const u=l.charSpace??0,h=()=>s.getTextWidth(t)+u*Math.max(0,t.length-1);for(;h()>a&&d>(l.min??6);)d-=.5,s.setFontSize(d);return s.setTextColor(...l.color),s.text(t,n,r,{align:l.align,charSpace:u}),d}function lh(s,t,n,r,a,i){s.setFont(Kd,i.style||"normal"),s.setFontSize(i.size),s.setTextColor(...i.color);const l=i.leading??i.size*1.45;let o=s.splitTextToSize(t,a);if(i.maxLines&&o.length>i.maxLines){o=o.slice(0,i.maxLines);const c=o[o.length-1];o[o.length-1]=c.replace(/[\s,;.:]+$/,"")+"…"}return o.forEach((c,d)=>s.text(c,n,r+d*l,i.align==="center"?{align:"center"}:void 0)),r+(o.length-1)*l}function VV(s,t,n,r,a,i){const{doc:l}=s;l.setFont(Kd,"bold"),l.setFontSize(7.5),l.setTextColor(...a||s.accent),l.text(t.toUpperCase(),n,r,{charSpace:1.8,align:i})}function S0(s,t=pte){s.doc.addPage("letter","landscape"),s.pageNo+=1,s.doc.setFillColor(...t),s.doc.rect(0,0,Ic,Dm,"F")}function bv(s,t,n,r,a={}){const{doc:i}=s,l=!!a.dark,o=a.width??Ic-aa*2-60;VV(s,t,aa,62,s.accent),i.setFont(yq,"bold"),i.setFontSize(yq==="times"?25:23);const c=i.splitTextToSize(n,o).slice(0,3);i.setTextColor(...l?Fo:s.brand),c.forEach((u,h)=>i.text(u,aa,96+h*29));let d=96+(c.length-1)*29;return r&&(d=lh(i,r,aa,d+26,Math.min(o+40,Ic-aa*2),{size:10,color:l?Op(Fo,s.deep,.28):bb,leading:15,maxLines:2})),d+34}function C0(s,t=!1){const{doc:n,data:r}=s,a=t?Op(Fo,s.deep,.7):T_;n.setDrawColor(...a),n.setLineWidth(.6),n.line(aa,Dm-46,Ic-aa,Dm-46);const i=Dm-30;n.setFont(Kd,"bold"),n.setFontSize(7),n.setTextColor(...t?Fo:s.brand),t&&o_(n,.9),n.text((r.agent.name||"").toUpperCase(),aa,i,{charSpace:1.4});const l=LTn(r);l&&(n.setFont(Kd,"normal"),n.setFontSize(7),n.setTextColor(...t?Fo:bb),Xg(n,l,Ic/2,i,Ic/2-aa-40,7,{color:t?Fo:bb,align:"center"})),n.setFont(Kd,"normal"),n.setFontSize(7),n.setTextColor(...t?Fo:bb),n.text(String(s.pageNo).padStart(2,"0"),Ic-aa,i,{align:"right"}),t&&o_(n,1)}function c$t(s,t,n,r,a){const{doc:i}=s;i.setFont(Kd,"bold"),i.setFontSize(8);const l=i.splitTextToSize(t,a-28),o=16+l.length*12;return y1(i,n,r,a,o,6,Op(s.accent,Fo,.86)),i.setTextColor(...Op(s.brand,f4,.2)),l.forEach((c,d)=>i.text(c,n+14,r+20+d*12)),r+o}function GXe(s,t,n,r,a,i={}){const{doc:l}=s;s.hero?fte(l,s.hero,t,n,r,a,{radius:10,dpi:s.dpi,tint:i.tint?{color:s.deep,amount:i.tint}:void 0}):y1(l,t,n,r,a,10,Op(s.deep,Fo,.12))}function RTn(s){const{doc:t,data:n}=s,{line1:r,line2:a}=l$t(n),i=336;s.hero?fte(t,s.hero,0,0,Ic,Dm,{dpi:s.dpi,darken:.12}):(t.setFillColor(...s.deep),t.rect(0,0,Ic,Dm,"F")),t.setFillColor(...s.deep),t.rect(0,0,i,Dm,"F"),t.setFillColor(...s.accent),t.rect(i-3,0,3,Dm,"F");const l=gte(s,"cover");VV(s,l.kicker,aa,66),t.setFont(yq,"bold"),t.setFontSize(yq==="times"?29:26),t.setTextColor(...Fo);const o=t.splitTextToSize(r,i-aa*2).slice(0,3);o.forEach((y,v)=>t.text(y,aa,102+v*30));let c=102+(o.length-1)*30;a&&(t.setFont(Kd,"normal"),t.setFontSize(9),o_(t,.9),Xg(t,a.toUpperCase(),aa,c+22,i-aa*2,9,{color:Fo,charSpace:1.4}),o_(t,1),c+=22),c=lh(t,l.body,aa,c+34,i-aa*2,{size:10,color:Op(Fo,s.deep,.22),leading:16});const d=[bTn(n.property.listPrice),n.property.beds?`${n.property.beds} BD`:null,n.property.baths?`${n.property.baths} BA`:null,n.property.sqft?`${Number(n.property.sqft).toLocaleString()} SF`:null].filter(Boolean);d.length&&(t.setDrawColor(...s.accent),t.setLineWidth(1.5),t.line(aa,c+30,aa+40,c+30),Xg(t,d.join(" · "),aa,c+54,i-aa*2,10,{style:"bold",color:Fo,charSpace:1}));const u=HXe(n),h=Dm-(u?152:128);let m=aa;s.headshot&&(vO(t,s.headshot,aa+22,h+18,22),u&&s.coHeadshot?(vO(t,s.coHeadshot,aa+56,h+18,22),m=aa+90):m=aa+56),Xg(t,u?`${n.agent.name} + ${u.name}`:n.agent.name,m,h+12,i-m-24,14,{style:"bold",color:Fo}),t.setFont(Kd,"normal"),t.setFontSize(8),o_(t,.85);const p=[n.agent.brokerageName].filter(Boolean).join("");p&&Xg(t,p,m,h+26,i-m-24,8,{color:Fo});const g=[n.agent.phone,n.agent.email].filter(Boolean).join(" · ");if(g&&Xg(t,g,m,h+38,i-m-24,8,{color:Fo}),u){const y=[u.title||"Co-listing agent",u.phone].filter(Boolean).join(" · ");y&&Xg(t,y,aa,h+56,i-aa-24,8,{color:Fo})}o_(t,1),s.logo&&(o_(t,.95),VXe(t,s.logo,aa,Dm-74,132,30,"left"),o_(t,1));const x=n.sellerName?`PREPARED FOR ${n.sellerName.toUpperCase()}`:"PREPARED FOR YOUR HOME";t.setFont(Kd,"bold"),t.setFontSize(7.5),t.setTextColor(...Fo),o_(t,.9),t.text(x,Ic-aa,Dm-34,{align:"right",charSpace:1.6}),o_(t,1)}function DTn(s){S0(s);const{doc:t}=s,n=gte(s,"welcome"),r=bv(s,n.kicker,n.headline,n.subhead||null),a=[["Make it look irresistible","Professional visuals help buyers stop, click, and imagine themselves at home."],["Put it everywhere buyers search","MLS distribution, property portals, mobile search, and a dedicated online showcase."],["Create demand beyond the portals","Social campaigns, email, database outreach, and local promotion keep momentum moving."]];let i=r+10;a.forEach(([l,o],c)=>{t.setFillColor(...Op(s.accent,Fo,.85)),t.circle(aa+13,i-3,13,"F"),t.setFont(Kd,"bold"),t.setFontSize(9),t.setTextColor(...s.brand),t.text(String(c+1).padStart(2,"0"),aa+13,i,{align:"center"});const d=aa+44,u=Ic-d-aa-40;t.setFont(Kd,"bold"),t.setFontSize(11.5),t.setTextColor(...f4),t.text(l,d,i),lh(t,o,d,i+18,u,{size:9.5,color:yv,leading:14,maxLines:2}),i+=88}),C0(s)}function OTn(s){S0(s,Fo);const{doc:t,data:n}=s,r=gte(s,"agent"),a=bv(s,r.kicker,r.headline,r.subhead||n.agent.tagline||"You are not hiring a website or a billboard — you are hiring a person."),i=HXe(n),l=Ic-aa-260,o=a-6,c=262;if(i){const g=(x,y,v,_)=>{y1(t,l,x,260,124,10,rF,"FD",T_),t.setFillColor(...s.accent),t.rect(l,x,260,3,"F");let j=l+18;v&&(vO(t,v,l+48,x+62+2,30),j=l+90);const C=260-(j-l)-18;Xg(t,y,j,x+40,C,13,{style:"bold",color:s.brand});let A=x+56;_.filter(Boolean).slice(0,4).forEach(M=>{Xg(t,String(M),j,A,C,8,{color:bb}),A+=13})};g(o,n.agent.name,s.headshot,[n.agent.brokerageName,n.agent.phone,n.agent.email]),g(o+124+14,i.name,s.coHeadshot,[i.title||"Co-listing agent",i.brokerageName||n.agent.brokerageName,i.phone,i.email])}else{y1(t,l,o,260,c,10,rF,"FD",T_),t.setFillColor(...s.accent),t.rect(l,o,260,3,"F"),s.headshot&&vO(t,s.headshot,l+130,o+72,42),Xg(t,n.agent.name,l+130,o+(s.headshot?138:70),216,16,{style:"bold",color:s.brand,align:"center"});let m=o+(s.headshot?158:92);[n.agent.brokerageName,n.agent.phone,n.agent.email,n.agent.website].filter(Boolean).slice(0,4).forEach(p=>{Xg(t,String(p),l+130,m,220,8.5,{color:bb,align:"center"}),m+=14}),s.logo&&VXe(t,s.logo,l+80,o+c-44,100,28,"left")}const d=l-aa-44;let u=lh(t,i?i.bio||"You are working with both of us. Here is how to reach us, and the professional details behind the marketing plan in this presentation — every step that follows is something we run personally on your home.":"Here is how to reach me, and the professional details behind the marketing plan in this presentation. Every step that follows is something I run personally on your home.",aa,a+4,d,{size:10,color:yv,leading:16,maxLines:5});u+=34,[["Phone",n.agent.phone],["Email",n.agent.email],["Website",n.agent.website],["Brokerage",n.agent.brokerageName],["License",n.agent.licenseNumber?`${n.agent.licenseNumber}${n.agent.licenseState?` · ${n.agent.licenseState}`:""}`:null],i?["Co-listing",[i.name,i.licenseNumber].filter(Boolean).join(" · ")]:["",null]].filter(([m,p])=>!!m&&!!p).forEach(([m,p])=>{t.setFont(Kd,"bold"),t.setFontSize(7),t.setTextColor(...bb),t.text(m.toUpperCase(),aa,u,{charSpace:1.4}),Xg(t,p,aa+86,u,d-86,10.5,{color:f4}),t.setDrawColor(...T_),t.setLineWidth(.5),t.line(aa,u+11,aa+d,u+11),u+=36}),C0(s)}function FTn(s,t){S0(s);const{doc:n}=s,r=gte(s,"overview"),a=bv(s,r.kicker,r.headline,r.subhead||null),i=4,l=14,o=(Ic-aa*2-l*(i-1))/i,c=96;t.slice(0,8).forEach((d,u)=>{const h=aa+u%i*(o+l),m=a+Math.floor(u/i)*(c+l);y1(n,h,m,o,c,8,Fo,"FD",T_),n.setFillColor(...s.accent),n.rect(h,m,3,c,"F"),n.setFont(Kd,"bold"),n.setFontSize(15),n.setTextColor(...Op(s.brand,Fo,.55)),n.text(String(u+1).padStart(2,"0"),h+16,m+30),lh(n,d.title,h+16,m+52,o-30,{size:9.5,style:"bold",color:f4,leading:13,maxLines:3})}),C0(s)}function j6(s,t=5){var n;return(((n=s.options)==null?void 0:n.filter(r=>r.enabled).map(r=>r.label))??S3n[s.key]??[]).slice(0,t)}function f1t(s,t,n){S0(s,n.dark?s.deep:pte);const{doc:r}=s,a=bv(s,n.kicker,n.headline,n.sub,{dark:n.dark}),i=404,l=272,o=!!n.flip,c=o?Ic-aa-i:aa,d=o?aa:aa+i+40,u=Ic-aa*2-i-40;GXe(s,c,a,i,l,{tint:n.dark?.1:0}),VV(s,t.title,d,a+12);let h=lh(r,t.body,d,a+32,u,{size:9.5,color:n.dark?Op(Fo,s.deep,.2):yv,leading:15,maxLines:4});const m=j6(t,5);if(m.length&&(h=qV(r,m,d,h+28,u,{font:Kd,size:9.5,color:n.dark?Fo:f4,accent:s.accent,gap:7})),n.note&&!n.dark){const p=Math.min(h+14,Dm-120);c$t(s,n.note,d,p,u)}else n.note&&(r.setFont(Kd,"bold"),r.setFontSize(9.5),r.setTextColor(...Fo),o_(r,.9),lh(r,n.note,aa,Dm-78,Ic-aa*2,{size:9.5,style:"bold",color:Fo,leading:13,maxLines:1}),o_(r,1));C0(s,n.dark)}function zTn(s,t){S0(s);const{doc:n}=s,r=bv(s,"Launch day","The MLS is the starting point — not the entire plan.","We prepare the details, media, and messaging before the listing goes live."),a=j6(t,4),i=["Price + position","MLS story","Media ready","Go live"],l=Math.max(1,a.length||4),o=16,c=(Ic-aa*2-o*(l-1))/l,d=176;(a.length?a:i).forEach((u,h)=>{const m=aa+h*(c+o);y1(n,m,r,c,d,8,Fo,"FD",T_),n.setFont(Kd,"bold"),n.setFontSize(16),n.setTextColor(...s.accent),n.text(String(h+1),m+16,r+34),n.setFont(Kd,"bold"),n.setFontSize(7.5),n.setTextColor(...bb),n.text((i[h]||`STEP ${h+1}`).toUpperCase(),m+16,r+56,{charSpace:1.2}),lh(n,u,m+16,r+76,c-32,{size:9,color:yv,leading:13,maxLines:5})}),lh(n,t.body,aa,r+d+34,Ic-aa*2-120,{size:10,style:"bold",color:s.brand,leading:15,maxLines:2}),C0(s)}function BTn(s,t){S0(s);const{doc:n}=s,r=bv(s,"Maximum visibility","Your listing goes where buyers already search.","MLS syndication helps distribute your property across major real estate destinations."),a=[["Zillow",[0,106,255]],["Realtor.com",[214,40,40]],["Homes.com",[58,61,178]],["Redfin",[200,32,46]],["Trulia",[0,128,116]],["Movoto",[40,44,60]]],i=3,l=16,o=(Ic-aa*2-l*(i-1))/i,c=68;a.forEach(([u,h],m)=>{const p=aa+m%i*(o+l),g=r+Math.floor(m/i)*(c+l);y1(n,p,g,o,c,8,Fo,"FD",T_),o$t(n,u,h,p+28,g+c/2,20),Xg(n,u,p+48,g+c/2+4,o-64,13,{style:"bold",color:h})});const d=r+2*(c+l)+22;lh(n,t.body,aa,d,Ic-aa*2-140,{size:9.5,color:yv,leading:14,maxLines:3}),n.setFont(Kd,"normal"),n.setFontSize(7.5),n.setTextColor(...bb),n.text("Distribution varies by MLS, market, and portal policies.",aa,Dm-62),C0(s)}function $Tn(s,t){S0(s,rF);const{doc:n,data:r}=s,{line1:a}=l$t(r),i=bv(s,"A home of its own","Your property gets a dedicated online showcase.","One clean destination makes the listing easy to explore, save, and share."),l=404,o=274;y1(n,aa,i,l,o,10,Fo,"FD",T_),y1(n,aa,i,l,22,10,s.deep),n.setFillColor(...s.deep),n.rect(aa,i+12,l,10,"F"),n.setFont(Kd,"bold"),n.setFontSize(7),n.setTextColor(...Fo);const c=(r.agent.website||`${a}`).replace(/^https?:\/\//,"").toUpperCase();Xg(n,c,aa+14,i+15,l-28,7,{style:"bold",color:Fo,charSpace:1}),GXe(s,aa+14,i+36,186,142);const d=aa+214,u=l-228;Xg(n,a,d,i+54,u,12,{style:"bold",color:s.brand}),lh(n,"Welcome home.",d,i+72,u,{size:9,color:s.accent,leading:12,maxLines:1}),lh(n,"Photo gallery, property highlights, video tour, showing inquiry, and easy social sharing — all in one place.",d,i+92,u,{size:8.5,color:yv,leading:12,maxLines:5}),c$t(s,"Shareable. Trackable. Memorable.",aa+14,i+o-46,l-28);const h=aa+l+40,m=Ic-h-aa;VV(s,t.title,h,i+12);let p=lh(n,t.body,h,i+32,m,{size:9.5,color:yv,leading:15,maxLines:5});const g=j6(t,5);g.length&&qV(n,g,h,p+26,m,{font:Kd,size:9,color:f4,accent:s.accent,gap:7}),C0(s)}function UTn(s,t){S0(s,s.deep);const{doc:n}=s,r=bv(s,"Beyond the search portals","We turn your listing into social content people want to stop and watch.","Creative is tailored for the platforms — not copied and pasted everywhere.",{dark:!0}),a=[["Facebook",[24,119,242]],["Instagram",[214,41,118]],["YouTube",[255,0,0]],["TikTok",[16,16,16]],["Pinterest",[230,0,35]]],i=72,l=16;a.forEach(([d,u],h)=>{const m=aa+h*(i+l);y1(n,m,r,i,i,12,Fo),o$t(n,d,u,m+i/2,r+i/2-4,30),n.setFont(Kd,"bold"),n.setFontSize(6.5),n.setTextColor(...bb),n.text(d.toUpperCase(),m+i/2,r+i-8,{align:"center",charSpace:.6})});const o=aa+5*(i+l)+14,c=Ic-o-aa;VV(s,"The campaign can include",o,r+12),qV(n,j6(t,5),o,r+32,c,{font:Kd,size:9,color:Fo,accent:s.accent,gap:7}),lh(n,t.body,aa,r+i+44,420,{size:9.5,color:Op(Fo,s.deep,.2),leading:15,maxLines:4}),lh(n,"Every post sends attention back to the property.",aa,Dm-84,460,{size:11,style:"bold",color:Fo,leading:14,maxLines:1}),C0(s,!0)}function qTn(s,t){S0(s);const{doc:n}=s,r=bv(s,"Reach buyers directly","Great marketing does not wait for someone to stumble across the listing.","We activate local relationships and existing audiences to create more opportunities."),a=j6(t,4),i=["Email announcement","Agent-to-agent outreach","Database follow-up","Local community visibility"];let l=r+6;a.forEach((o,c)=>{y1(n,aa,l-14,34,34,8,Op(s.accent,Fo,.85)),n.setFont(Kd,"bold"),n.setFontSize(11),n.setTextColor(...s.brand),n.text(String(c+1),aa+17,l+7,{align:"center"});const d=aa+52,u=Ic-d-aa-20;n.setFont(Kd,"bold"),n.setFontSize(8),n.setTextColor(...s.brand),n.text((i[c]||t.title).toUpperCase(),d,l-2,{charSpace:1.2}),lh(n,o,d,l+14,u,{size:9.5,color:yv,leading:14,maxLines:2}),l+=76}),lh(n,t.body,aa,Math.min(l+8,Dm-92),Ic-aa*2-120,{size:9.5,color:bb,leading:14,maxLines:2}),C0(s)}function VTn(s,t){S0(s);const{doc:n}=s,r=bv(s,"Real-world marketing still matters","Digital reach gets attention. Local presence turns attention into action.","Each tactic is selected for the property, timing, neighborhood, and likely buyer."),a=j6(t,4),i=["Open house","Signage","Neighborhood","Follow-up"],l=2,o=20,c=(Ic-aa*2-o)/l,d=112;a.forEach((u,h)=>{const m=aa+h%l*(c+o),p=r+Math.floor(h/l)*(d+o);y1(n,m,p,c,d,8,rF,"FD",T_),n.setFont(Kd,"bold"),n.setFontSize(7.5),n.setTextColor(...s.brand),n.text((i[h]||t.title).toUpperCase(),m+16,p+24,{charSpace:1.2}),lh(n,u,m+16,p+46,c-32,{size:9.5,color:yv,leading:14,maxLines:3})}),C0(s)}function HTn(s,t){S0(s,rF);const{doc:n}=s,r=bv(s,"You will always know what is happening","A strong launch needs clear communication and thoughtful adjustments.","You receive useful feedback — not a pile of disconnected activity."),a=j6(t,4),i=["Weekly update","Market check","Smart adjustments","Direct access"];let l=r+10;a.forEach((o,c)=>{n.setFont(Kd,"bold"),n.setFontSize(11),n.setTextColor(...s.accent),n.text(String(c+1).padStart(2,"0"),aa,l),n.setFont(Kd,"bold"),n.setFontSize(9),n.setTextColor(...s.brand),n.text((i[c]||"").toUpperCase(),aa+48,l,{charSpace:1.2}),lh(n,o,aa+250,l-1,Ic-aa-250-aa,{size:9.5,color:yv,leading:13,maxLines:2}),n.setDrawColor(...T_),n.setLineWidth(.5),n.line(aa,l+22,Ic-aa,l+22),l+=62}),lh(n,"Marketing creates opportunity. Communication helps us act on it.",aa,Math.min(l+18,Dm-84),520,{size:11,style:"bold",color:s.brand,leading:14,maxLines:1}),C0(s)}function GTn(s){S0(s,s.deep);const{doc:t,data:n}=s;s.hero&&fte(t,s.hero,0,0,Ic,Dm,{tint:{color:s.deep,amount:.92},darken:.25,dpi:s.dpi});const r=gte(s,"closing"),a=bv(s,r.kicker,r.headline,r.subhead||null,{dark:!0,width:520}),i=420;let l=lh(t,r.body,aa,a,i,{size:10.5,color:Op(Fo,s.deep,.18),leading:17});l+=30,qV(t,["Regular written updates for as long as your home is on the market","Showing and online traffic feedback shared as it arrives","Honest pricing conversations backed by current data","Every offer reviewed with you line by line"],aa,l,i,{font:Kd,size:9.5,color:Fo,accent:s.accent,gap:8});const o=HXe(n),c=250,d=Ic-aa-c,u=a-20,h=o?300:258;y1(t,d,u,c,h,10,Fo),t.setFillColor(...s.accent),t.rect(d,u,c,3,"F"),s.headshot&&(o&&s.coHeadshot?(vO(t,s.headshot,d+c/2-34,u+70,32),vO(t,s.coHeadshot,d+c/2+34,u+70,32)):vO(t,s.headshot,d+c/2,u+70,38)),Xg(t,o?`${n.agent.name} + ${o.name}`:n.agent.name,d+c/2,u+(s.headshot?132:68),c-30,16,{style:"bold",color:s.brand,align:"center"});let m=u+(s.headshot?152:90);[n.agent.brokerageName,n.agent.phone,n.agent.email,n.agent.website,n.agent.licenseNumber?`License ${n.agent.licenseNumber}${n.agent.licenseState?` · ${n.agent.licenseState}`:""}`:null].filter(Boolean).slice(0,5).forEach(p=>{Xg(t,String(p),d+c/2,m,c-30,8.5,{color:bb,align:"center"}),m+=14}),o?(m+=6,t.setDrawColor(...T_),t.setLineWidth(.5),t.line(d+24,m-8,d+c-24,m-8),Xg(t,o.name,d+c/2,m+8,c-30,10,{style:"bold",color:s.brand,align:"center"}),m+=22,[o.title||"Co-listing agent",o.phone,o.email].filter(Boolean).slice(0,3).forEach(p=>{Xg(t,String(p),d+c/2,m,c-30,8.5,{color:bb,align:"center"}),m+=13})):s.logo&&VXe(t,s.logo,d+c/2-50,u+h-44,100,28,"left"),t.setFont(Kd,"bold"),t.setFontSize(9),t.setTextColor(...Fo),o_(t,.9),t.text("LET'S MAKE YOUR HOME THE ONE BUYERS REMEMBER.",aa,Dm-72,{charSpace:1.4}),o_(t,1),C0(s,!0)}function WXe(s,t){return s.customImages[t.id]||null}function d$t(s,t,n,r,a,i){const l=WXe(s,t);l?fte(s.doc,l,n,r,a,i,{radius:10,dpi:s.dpi}):GXe(s,n,r,a,i)}function WTn(s,t){S0(s,t.dark?s.deep:pte);const{doc:n}=s,r=bv(s,t.kicker||"About",t.headline,t.subhead||null,{dark:t.dark}),a=300,i=t.imageSide!=="left",l=i?Ic-aa-a:aa,o=i?aa:aa+a+40,c=Ic-aa*2-a-40;d$t(s,t,l,r,a,268);const d=(t.body||"").split(/\n{2,}/).filter(Boolean);let u=r+6;d.slice(0,3).forEach(h=>{u=lh(n,h,o,u,c,{size:10,color:t.dark?Op(Fo,s.deep,.2):yv,leading:16,maxLines:7}),u+=26}),t.bullets.length&&qV(n,t.bullets.slice(0,5),o,Math.min(u,Dm-150),c,{font:Kd,size:9.5,color:t.dark?Fo:f4,accent:s.accent,gap:7}),C0(s,t.dark)}function KTn(s,t){S0(s,t.dark?s.deep:rF);const{doc:n}=s,r=bv(s,t.kicker||"What others are saying",t.headline,t.subhead||null,{dark:t.dark}),a=t.testimonials.filter(m=>{var p;return(p=m.quote)==null?void 0:p.trim()}).slice(0,6),i=a.length<=2?a.length||1:a.length>4?3:2,l=18,o=(Ic-aa*2-l*(i-1))/i,c=Math.ceil(a.length/i)||1,d=Dm-72-r,u=c>1?Math.min(150,(d-l*(c-1))/c):Math.min(200,d),h=c>1?i===3?4:3:7;a.forEach((m,p)=>{const g=aa+p%i*(o+l),x=r+Math.floor(p/i)*(u+l);y1(n,g,x,o,u,10,t.dark?Op(s.deep,Fo,.08):Fo,"FD",T_),n.setFillColor(...s.accent),n.rect(g,x,3,u,"F"),n.setFont(yq,"bold"),n.setFontSize(30),n.setTextColor(...Op(s.accent,t.dark?s.deep:Fo,.4)),n.text("“",g+18,x+40),lh(n,m.quote,g+18,x+56,o-40,{size:9.5,color:t.dark?Op(Fo,s.deep,.2):yv,leading:14,maxLines:h}),n.setDrawColor(...s.accent),n.setLineWidth(1.2),n.line(g+18,x+u-32,g+42,x+u-32),n.setFont(Kd,"bold"),n.setFontSize(8),n.setTextColor(...s.brand);const y=[m.name,m.detail].filter(Boolean).join(" · ");y&&Xg(n,y.toUpperCase(),g+18,x+u-16,o-36,8,{style:"bold",color:t.dark?Fo:s.brand,charSpace:1.1})}),t.body&&lh(n,t.body,aa,Math.min(r+c*(u+l)+14,Dm-88),Ic-aa*2-120,{size:9.5,color:t.dark?Op(Fo,s.deep,.2):bb,leading:14,maxLines:2}),C0(s,t.dark)}function YTn(s,t){S0(s,t.dark?s.deep:pte);const{doc:n}=s,r=bv(s,t.kicker||"Track record",t.headline,t.subhead||null,{dark:t.dark}),a=t.stats.filter(i=>{var l,o;return((l=i.value)==null?void 0:l.trim())||((o=i.label)==null?void 0:o.trim())}).slice(0,4);if(a.length){const l=(Ic-aa*2-18*(a.length-1))/a.length,o=150;a.forEach((c,d)=>{const u=aa+d*(l+18);y1(n,u,r,l,o,10,t.dark?Op(s.deep,Fo,.1):Fo,"FD",T_),n.setFillColor(...s.accent),n.rect(u,r,l,3,"F"),Xg(n,c.value||"—",u+l/2,r+76,l-28,34,{style:"bold",color:t.dark?Fo:s.brand,align:"center"}),lh(n,c.label||"",u+20,r+100,l-40,{size:9,color:t.dark?Op(Fo,s.deep,.3):bb,leading:12,maxLines:2,align:"center"})}),t.body&&lh(n,t.body,aa,r+o+40,Ic-aa*2-140,{size:10,color:t.dark?Op(Fo,s.deep,.2):yv,leading:15,maxLines:3})}else t.body&&lh(n,t.body,aa,r,Ic-aa*2-140,{size:10.5,color:t.dark?Fo:yv,leading:16});C0(s,t.dark)}function ZTn(s,t){S0(s,t.dark?s.deep:Fo);const{doc:n}=s,r=bv(s,t.kicker||"Our promise",t.headline,t.subhead||null,{dark:t.dark}),i=!!WXe(s,t)||!!s.hero,l=i?Ic-aa*2-280:Ic-aa*2-140;let o=r;t.body&&(o=lh(n,t.body,aa,o,l,{size:10,color:t.dark?Op(Fo,s.deep,.2):yv,leading:15,maxLines:3})+28),t.bullets.filter(d=>d==null?void 0:d.trim()).slice(0,7).forEach(d=>{y1(n,aa,o-9,14,14,4,s.accent),n.setFont(Kd,"bold"),n.setFontSize(8),n.setTextColor(...Fo),n.text("✓",aa+7,o+1,{align:"center"}),o=lh(n,d,aa+26,o,l-26,{size:10,color:t.dark?Fo:f4,leading:14,maxLines:2})+22}),i&&d$t(s,t,Ic-aa-240,r,240,250),C0(s,t.dark)}function XTn(s,t){S0(s,s.deep);const{doc:n}=s,r=WXe(s,t)||s.hero;r&&fte(n,r,0,0,Ic,Dm,{tint:{color:s.deep,amount:.82},darken:.28,dpi:s.dpi}),VV(s,t.kicker||"Our approach",aa,Dm/2-84),n.setFont(Kd,"bold"),n.setFontSize(30),n.setTextColor(...Fo);const a=n.splitTextToSize(t.headline||"",Ic-aa*2-140).slice(0,4);a.forEach((i,l)=>n.text(i,aa,Dm/2-44+l*38)),t.body&&lh(n,t.body,aa,Dm/2+a.length*38-24,480,{size:10.5,color:Op(Fo,s.deep,.2),leading:16,maxLines:4}),C0(s,!0)}function p1t(s,t){switch(t.layout){case"testimonials":return KTn(s,t);case"stats":return YTn(s,t);case"checklist":return ZTn(s,t);case"statement":return XTn(s,t);case"story":default:return WTn(s,t)}}async function QTn(s,t,n){var I,P,R,O;const r=n==="print"?4:2,a=n==="print"?2600:1600,i=vTn((I=t.pages)==null?void 0:I.theme);pte=m9(i.paper),rF=m9(i.paperCool),T_=m9(i.softLine),yv=m9(i.bodyInk),yq=i.headFont;const l=m9((i.useAgentColors?t.agent.brandColor:i.brand)||i.brand||"#0E1B2C"),o=m9((i.useAgentColors?t.agent.accentColor:i.accent)||i.accent||"#B8965A"),c=Op(l,[0,0,0],i.id==="luxury"?.35:.2),d=(P=t.coAgent)!=null&&P.enabled&&((R=t.coAgent.name)!=null&&R.trim())?t.coAgent:null,u=(t.customPages||[]).filter(B=>B.enabled).sort((B,U)=>B.order-U.order),[h,m,p,g,...x]=await Promise.all([zG(t.property.photoUrl,a),zG(t.agent.headshotUrl,700),zG(t.agent.brokerageLogoUrl,800),zG((d==null?void 0:d.headshotUrl)||null,700),...u.map(B=>zG(B.imageUrl||null,a))]),y={};u.forEach((B,U)=>{y[B.id]=x[U]??null}),wTn(t.focal);const v={doc:s,data:t,brand:l,accent:o,deep:c,hero:h,headshot:m,coHeadshot:g,logo:p,customImages:y,dpi:r,pageNo:1},_=new Set(((O=t.pages)==null?void 0:O.hidden)||[]),j=[...t.services].filter(B=>B.enabled).sort((B,U)=>B.order-U.order),C=B=>j.find(U=>U.key===B);RTn(v),_.has("welcome")||DTn(v),_.has("agent")||OTn(v),u.filter(B=>B.placement!=="end").forEach(B=>p1t(v,B)),_.has("overview")||FTn(v,j);const A=new Set,M=(B,U)=>{const G=C(B);G&&(A.add(B),U(G))};M("photography",B=>f1t(v,B,{kicker:"First impressions",headline:"Buyers will see your home at its absolute best.",sub:"Strong presentation earns the click before a showing is ever scheduled.",note:"Every image has one job: earn the next click."})),M("video",B=>f1t(v,B,{kicker:"More ways to experience it",headline:"Photos introduce the home. Video helps buyers feel it.",sub:"A cinematic walk-through gives the listing movement, emotion, and shareability.",note:"The right format for every screen.",dark:!0,flip:!0})),M("mls",B=>zTn(v,B)),M("syndication",B=>BTn(v,B)),M("website",B=>$Tn(v,B)),M("social",B=>UTn(v,B)),M("email",B=>qTn(v,B)),M("openhouse",B=>VTn(v,B)),M("communication",B=>HTn(v,B)),j.filter(B=>!A.has(B.key)).forEach(B=>{S0(v);const U=bv(v,"Marketing",B.title,null),G=j6(B,6),H=lh(s,B.body,aa,U,Ic-aa*2-160,{size:10.5,color:yv,leading:16});G.length&&qV(s,G,aa,H+30,Ic-aa*2-160,{font:Kd,size:9.5,color:f4,accent:v.accent,gap:8}),C0(v)}),u.filter(B=>B.placement==="end").forEach(B=>p1t(v,B)),_.has("closing")||GTn(v)}const g1t=[{id:"signature",name:"Signature",description:"Editorial full-bleed cover with a brand-tinted photo motif throughout.",render:QTn}];function JTn(s){return g1t.find(t=>t.id===s)||g1t[0]}async function u$t(s,t,n="screen"){const r=new Oo({unit:"pt",format:"letter",orientation:"landscape",compress:!0});return await JTn(t).render(r,s,n),r.setProperties({title:s.title||`${s.property.addressLine1} — Listing Presentation`,subject:`Listing presentation for ${s.property.addressLine1}`,author:s.agent.name,creator:"LevelUp Hub — Listing Presentation Studio"}),r}function eMn(s){return`${(s.property.addressLine1||s.title||"listing-presentation").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")||"listing-presentation"}-presentation.pdf`}const tMn={name:"Your Name",headshotUrl:null,brokerageName:null,brokerageLogoUrl:null,licenseNumber:null,licenseState:null,phone:null,email:null,website:null,brandColor:"#2a4c64",accentColor:"#B8965A",tagline:null};async function V4e(s){if(!s)return null;const{data:t}=await V.storage.from(RM).createSignedUrl(s,3600);return(t==null?void 0:t.signedUrl)??null}function H4e(s,t,n){const r=s.agent_snapshot||{},a={...tMn,...t||{},...Object.fromEntries(Object.entries(r).filter(([,i])=>i!=null&&i!==""))};return{title:s.title,property:{addressLine1:s.property_address_line1||"",city:s.city||"",state:s.state||"",postalCode:s.postal_code||"",listPrice:s.list_price!=null?Number(s.list_price):null,beds:s.beds!=null?Number(s.beds):null,baths:s.baths!=null?Number(s.baths):null,sqft:s.sqft!=null?Number(s.sqft):null,photoUrl:n??null},agent:a,coAgent:hBt(s.co_agent),customPages:fBt(s.custom_pages),services:x$e(s.services),pages:s.page_settings&&Object.keys(s.page_settings).length?s.page_settings:p$e,focal:s.photo_focal||g$e}}async function h$t(s,t){if(s.property.photoUrl||!t)return s;const n=await V4e(t);return{...s,property:{...s.property,photoUrl:n}}}async function m$t(s,t,n){const r=await h$t(s,n);return(await u$t(r,t,"screen")).output("blob")}async function f$t(s,t,n="print",r){const a=await h$t(s,r),l=(await u$t(a,t,n)).output("blob"),o=URL.createObjectURL(l),c=document.createElement("a");return c.href=o,c.download=eMn(a),document.body.appendChild(c),c.click(),c.remove(),setTimeout(()=>URL.revokeObjectURL(o),4e3),l}async function p$t(s,t,n){const r=`${s}/${t}/presentation.pdf`,{error:a}=await V.storage.from(RM).upload(r,n,{upsert:!0,contentType:"application/pdf"});return a?null:(await V.from("listing_presentations").update({pdf_path:r,last_generated_at:new Date().toISOString(),status:"final"}).eq("id",t),r)}async function g$t(s,t=2400){const n=URL.createObjectURL(s);try{const r=await new Promise((c,d)=>{const u=new Image;u.onload=()=>c(u),u.onerror=d,u.src=n});if(r.naturalWidth<=t&&s.size<3e6)return s;const a=Math.min(1,t/r.naturalWidth),i=document.createElement("canvas");return i.width=Math.round(r.naturalWidth*a),i.height=Math.round(r.naturalHeight*a),i.getContext("2d").drawImage(r,0,0,i.width,i.height),await new Promise(c=>i.toBlob(c,"image/jpeg",.9))||s}catch{return s}finally{URL.revokeObjectURL(n)}}async function sMn(s,t,n){const r=await g$t(n),a=`${s}/${t}/photo.jpg`,{error:i}=await V.storage.from(RM).upload(a,r,{upsert:!0,contentType:"image/jpeg"});if(i)throw i;return a}async function nMn(s,t,n="presentation",r=1800){const a=await g$t(t,r),i=`${s}/${n}-${Date.now()}.jpg`,{error:l}=await V.storage.from("avatars").upload(i,a,{upsert:!0,contentType:"image/jpeg"});if(l)throw l;const{data:o}=V.storage.from("avatars").getPublicUrl(i);return o.publicUrl}function rMn({path:s,alt:t}){const[n,r]=k.useState(null),[a,i]=k.useState(!1);return k.useEffect(()=>{let l=!0;if(r(null),i(!1),!!s)return w3n(s,3600).then(o=>{l&&r(o)}),()=>{l=!1}},[s]),n&&!a?e.jsx("div",{className:"h-32 w-full overflow-hidden bg-muted",children:e.jsx("img",{src:n,alt:t,loading:"lazy",onError:()=>i(!0),className:"h-32 w-full object-cover transition-transform duration-300 group-hover:scale-[1.03]"})}):e.jsx("div",{className:"flex h-32 items-center justify-center bg-gradient-to-br from-primary/15 to-accent/10",children:e.jsx(ua,{className:"h-8 w-8 text-primary/50"})})}const x1t=60*60*24*30;function x$t({open:s,onOpenChange:t,row:n,brand:r,photoUrl:a}){const{user:i}=ks(),[l,o]=k.useState([]),[c,d]=k.useState(""),[u,h]=k.useState([]),[m,p]=k.useState(!1),[g,x]=k.useState(""),[y,v]=k.useState(""),[_,j]=k.useState(!1),C=k.useRef(null),A=(n==null?void 0:n.property_address_line1)||(n==null?void 0:n.title)||"your home";k.useEffect(()=>{!s||!n||(o([]),d(""),h([]),x(`Your listing presentation for ${A}`),v(`Hi {{first_name}}, Thank you for the opportunity to talk about selling ${A}. I put together a presentation that walks through my pricing strategy, marketing plan, and what to expect at every step. Take a look and let me know what questions come up — I'm happy to walk through it together.`))},[s,n==null?void 0:n.id]),k.useEffect(()=>{C.current&&clearTimeout(C.current);const O=c.trim();if(!i||O.length<2||/\S+@\S+\.\S+/.test(O)){h([]);return}return C.current=setTimeout(async()=>{p(!0);const B=`%${O}%`,U=V,{data:G}=await U.from("innercircle_contacts").select("id, first_name, last_name, email").eq("owner_user_id",i.id).not("email","is",null).or(`first_name.ilike.${B},last_name.ilike.${B},email.ilike.${B}`).order("first_name",{ascending:!0}).limit(6);p(!1),h(G||[])},200),()=>{C.current&&clearTimeout(C.current)}},[c,i==null?void 0:i.id]);const M=O=>{O.email&&(o(B=>B.some(U=>U.email.toLowerCase()===O.email.toLowerCase())?B:[...B,O]),d(""),h([]))},I=()=>{const O=c.trim();if(!/\S+@\S+\.\S+/.test(O)){ae.error("Enter a valid email address");return}M({email:O})},P=k.useMemo(()=>!!n&&l.length>0&&g.trim().length>0&&!_,[n,l,g,_]),R=async()=>{if(!(!n||!i)){if(!n.property_photo_path){ae.error("Add the primary exterior photo before emailing the presentation");return}j(!0);try{const O=await m$t(H4e(n,r,a??null),n.template_id,n.property_photo_path),B=await p$t(i.id,n.id,O)||n.pdf_path;if(!B)throw new Error("Could not save the presentation PDF");const{data:U,error:G}=await V.storage.from(RM).createSignedUrl(B,x1t);if(G||!(U!=null&&U.signedUrl))throw new Error("Could not create a share link");const H=await V4e(n.property_photo_path).then(oe=>oe).catch(()=>null),{data:Y}=await V.storage.from(RM).createSignedUrl(n.property_photo_path,x1t),{data:se,error:ee}=await V.functions.invoke("listing-presentation-email",{body:{presentation_id:n.id,subject:g,message:y,pdf_url:U.signedUrl,photo_url:(Y==null?void 0:Y.signedUrl)||H,recipients:l}});if(ee)throw ee;if(!(se!=null&&se.success))throw new Error((se==null?void 0:se.error)||"Could not send the email");ae.success(se.failed?`Sent to ${se.sent} · ${se.failed} failed`:`Presentation emailed to ${se.sent} ${se.sent===1?"contact":"contacts"}`),t(!1)}catch(O){ae.error((O==null?void 0:O.message)||"Could not send the presentation")}finally{j(!1)}}};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"max-w-lg",children:[e.jsxs(Vs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(pn,{className:"h-4 w-4"})," Email this presentation"]}),e.jsxs(Cr,{children:["Sends a branded email with a secure link to the PDF. Use ",e.jsx("code",{children:"{{first_name}}"})," to personalize."]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"To"}),l.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1.5",children:l.map(O=>e.jsxs(qe,{variant:"secondary",className:"gap-1 py-1",children:[[O.first_name,O.last_name].filter(Boolean).join(" ")||O.email,e.jsx("button",{type:"button",onClick:()=>o(B=>B.filter(U=>U.email!==O.email)),"aria-label":`Remove ${O.email}`,children:e.jsx(mr,{className:"h-3 w-3"})})]},O.email))}),e.jsxs("div",{className:"relative",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(be,{value:c,onChange:O=>d(O.target.value),onKeyDown:O=>{O.key==="Enter"&&(O.preventDefault(),I())},placeholder:"Search contacts or type an email"}),e.jsx($,{type:"button",variant:"outline",size:"icon",onClick:I,children:e.jsx(nn,{className:"h-4 w-4"})})]}),(u.length>0||m)&&e.jsxs("div",{className:"absolute z-50 mt-1 w-full overflow-hidden rounded-md border bg-popover shadow-lg",children:[m&&e.jsxs("div",{className:"flex items-center gap-2 p-3 text-sm text-muted-foreground",children:[e.jsx(Jt,{className:"h-3 w-3 animate-spin"})," Searching…"]}),u.map(O=>e.jsxs("button",{type:"button",className:"flex w-full items-center gap-2 px-3 py-2 text-left text-sm hover:bg-accent",onClick:()=>M({email:O.email,first_name:O.first_name,last_name:O.last_name,contact_id:O.id}),children:[e.jsx(el,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"truncate",children:[O.first_name,O.last_name].filter(Boolean).join(" ")||O.email}),e.jsx("span",{className:"ml-auto truncate text-xs text-muted-foreground",children:O.email})]},O.id))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"pres-subject",children:"Subject"}),e.jsx(be,{id:"pres-subject",value:g,onChange:O=>x(O.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"pres-message",children:"Message"}),e.jsx(Ls,{id:"pres-message",rows:7,value:y,onChange:O=>v(O.target.value)})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),disabled:_,children:"Cancel"}),e.jsxs($,{onClick:R,disabled:!P,className:"gap-2",children:[_?e.jsx(Jt,{className:"h-4 w-4 animate-spin"}):e.jsx(Wr,{className:"h-4 w-4"}),_?"Sending…":`Send${l.length?` (${l.length})`:""}`]})]})]})})}const aMn=()=>{const s=Jn(),{presentations:t,isLoading:n,create:r,duplicate:a,remove:i,update:l}=lBt(),{data:o}=b3n(),{data:c}=cBt(),{savedTemplates:d,remove:u}=oBt(),[h,m]=k.useState(null),[p,g]=k.useState(""),[x,y]=k.useState(null),[v,_]=k.useState(null),[j,C]=k.useState(null),A=k.useMemo(()=>{var R,O;return(O=(R=o==null?void 0:o[0])==null?void 0:R.default_services)!=null&&O.length?o[0].default_services:z4e},[o]),M=async()=>{var O;if(!c)return;const R=await r.mutateAsync({title:"Untitled Presentation",template_id:((O=o==null?void 0:o[0])==null?void 0:O.slug)||"signature",agent_snapshot:c,services:A});s(`/apps/listing-presentation-studio/${R.id}`)},I=async R=>{var B;const O=await r.mutateAsync({title:`${R.name} — new listing`,template_id:R.template_id||"signature",agent_snapshot:R.agent_snapshot,co_agent:R.co_agent,custom_pages:R.custom_pages,services:(B=R.services)!=null&&B.length?R.services:A,page_settings:R.page_settings});s(`/apps/listing-presentation-studio/${O.id}`)},P=async R=>{try{_(R.id),await f$t(H4e(R,c),R.template_id,"print",R.property_photo_path)}catch(O){ae.error((O==null?void 0:O.message)||"Could not build the PDF")}finally{_(null)}};return e.jsxs(Xs,{children:[e.jsxs("div",{className:"space-y-8",children:[e.jsx("div",{className:"relative overflow-hidden rounded-2xl border bg-gradient-to-br from-primary/10 via-background to-accent/10 p-8",children:e.jsxs("div",{className:"flex flex-col gap-6 md:flex-row md:items-center md:justify-between",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs(qe,{variant:"secondary",className:"gap-1",children:[e.jsx(kn,{className:"h-3 w-3"})," Listing Presentation Studio"]}),e.jsx("h1",{className:"text-3xl font-semibold tracking-tight",children:"Win the listing before you walk in"}),e.jsx("p",{className:"max-w-2xl text-sm text-muted-foreground",children:"Enter an address, drop in one exterior photo, and get a beautiful 12-page seller presentation branded with your profile — ready to present or print in under two minutes."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs($,{size:"lg",onClick:M,disabled:r.isPending||!c,className:"gap-2",children:[r.isPending?e.jsx(Jt,{className:"h-4 w-4 animate-spin"}):e.jsx(nn,{className:"h-4 w-4"}),"New presentation"]}),d.length>0&&e.jsxs(Au,{children:[e.jsx(Eu,{asChild:!0,children:e.jsxs($,{size:"lg",variant:"outline",className:"gap-2",children:[e.jsx(jy,{className:"h-4 w-4"})," From template",e.jsx(Go,{className:"h-4 w-4"})]})}),e.jsx(gu,{align:"end",className:"w-64",children:d.map(R=>e.jsxs(Pa,{onClick:()=>I(R),children:[e.jsx(jy,{className:"mr-2 h-4 w-4 shrink-0"}),e.jsx("span",{className:"truncate",children:R.name})]},R.id))})]})]})]})}),d.length>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-semibold tracking-tight",children:"Your saved templates"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Start a new presentation from a saved setup — just add the address and photo."})]}),e.jsx("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-3",children:d.map(R=>e.jsx(we,{className:"transition-shadow hover:shadow-md",children:e.jsxs(De,{className:"flex items-start justify-between gap-3 p-4",children:[e.jsxs("button",{className:"min-w-0 flex-1 text-left",onClick:()=>I(R),disabled:r.isPending,children:[e.jsxs("p",{className:"flex items-center gap-2 truncate font-medium",children:[e.jsx(jy,{className:"h-4 w-4 shrink-0 text-muted-foreground"}),R.name]}),e.jsx("p",{className:"mt-1 line-clamp-2 text-xs text-muted-foreground",children:R.description||"Branding, theme, page wording, and marketing plan saved."})]}),e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8 shrink-0 text-muted-foreground hover:text-destructive",onClick:()=>u.mutate(R.id),children:e.jsx(Un,{className:"h-4 w-4"})})]})},R.id))})]}),n?e.jsx("div",{className:"grid gap-5 sm:grid-cols-2 lg:grid-cols-3",children:[0,1,2].map(R=>e.jsx(fn,{className:"h-56 rounded-xl"},R))}):t.length===0?e.jsx(we,{className:"border-dashed",children:e.jsxs(De,{className:"flex flex-col items-center gap-4 py-16 text-center",children:[e.jsx("div",{className:"flex h-14 w-14 items-center justify-center rounded-full bg-muted",children:e.jsx(ea,{className:"h-7 w-7 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"No presentations yet"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Create your first seller presentation — it takes about two minutes."})]}),e.jsxs($,{onClick:M,disabled:r.isPending||!c,className:"gap-2",children:[e.jsx(nn,{className:"h-4 w-4"})," New presentation"]})]})}):e.jsx("div",{className:"grid gap-5 sm:grid-cols-2 lg:grid-cols-3",children:t.map(R=>{const O=R.property_address_line1||"No address yet",B=[R.city,R.state].filter(Boolean).join(", ");return e.jsxs(we,{className:"group overflow-hidden transition-shadow hover:shadow-lg",children:[e.jsx("button",{className:"block w-full text-left",onClick:()=>s(`/apps/listing-presentation-studio/${R.id}`),children:e.jsx(rMn,{path:R.property_photo_path,alt:`${O} property photo`})}),e.jsxs(De,{className:"space-y-3 p-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"truncate font-medium",children:R.title}),e.jsxs("p",{className:"truncate text-xs text-muted-foreground",children:[O,B?` · ${B}`:""]})]}),e.jsxs(Au,{children:[e.jsx(Eu,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8 shrink-0",children:e.jsx(Z0,{className:"h-4 w-4"})})}),e.jsxs(gu,{align:"end",children:[e.jsxs(Pa,{onClick:()=>s(`/apps/listing-presentation-studio/${R.id}`),children:[e.jsx(ui,{className:"mr-2 h-4 w-4"})," Open"]}),e.jsxs(Pa,{onClick:()=>{m(R),g(R.title)},children:[e.jsx(ea,{className:"mr-2 h-4 w-4"})," Rename"]}),e.jsxs(Pa,{onClick:()=>a.mutate(R),children:[e.jsx(Da,{className:"mr-2 h-4 w-4"})," Duplicate"]}),e.jsxs(Pa,{onClick:()=>P(R),children:[e.jsx(ji,{className:"mr-2 h-4 w-4"})," Download PDF"]}),e.jsxs(Pa,{onClick:()=>C(R),children:[e.jsx(pn,{className:"mr-2 h-4 w-4"})," Email to a contact"]}),e.jsx(j0,{}),e.jsxs(Pa,{className:"text-destructive",onClick:()=>y(R),children:[e.jsx(Un,{className:"mr-2 h-4 w-4"})," Delete"]})]})]})]}),e.jsxs("div",{className:"flex items-center justify-between text-xs text-muted-foreground",children:[e.jsxs("span",{children:["Updated ",Ys(new Date(R.updated_at),"MMM d, yyyy")]}),R.last_generated_at?e.jsx(qe,{variant:"secondary",className:"text-[10px]",children:"PDF ready"}):e.jsx(qe,{variant:"outline",className:"text-[10px]",children:"Draft"})]}),e.jsxs($,{variant:"outline",size:"sm",className:"w-full gap-2",disabled:v===R.id,onClick:()=>P(R),children:[v===R.id?e.jsx(Jt,{className:"h-4 w-4 animate-spin"}):e.jsx(ji,{className:"h-4 w-4"}),"Download PDF"]})]})]},R.id)})})]}),e.jsx(zs,{open:!!h,onOpenChange:R=>!R&&m(null),children:e.jsxs(Rs,{className:"sm:max-w-md",children:[e.jsx(Vs,{children:e.jsx($s,{children:"Rename presentation"})}),e.jsx(be,{value:p,onChange:R=>g(R.target.value),autoFocus:!0}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>m(null),children:"Cancel"}),e.jsx($,{onClick:async()=>{h&&(await l.mutateAsync({id:h.id,title:p.trim()||"Untitled Presentation"}),m(null),ae.success("Renamed"))},children:"Save"})]})]})}),e.jsx(oc,{open:!!x,onOpenChange:R=>!R&&y(null),children:e.jsxs(Ql,{children:[e.jsxs(Jl,{children:[e.jsx(tc,{children:"Delete this presentation?"}),e.jsx(sc,{children:"This permanently removes the presentation, its property photo, and the generated PDF."})]}),e.jsxs(ec,{children:[e.jsx(nc,{children:"Cancel"}),e.jsx(Vl,{className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",onClick:()=>{x&&i.mutate(x),y(null)},children:"Delete"})]})]})}),e.jsx(x$t,{open:!!j,onOpenChange:R=>!R&&C(null),row:j,brand:c})]})};var aZ={};aZ.d=(s,t)=>{for(var n in t)aZ.o(t,n)&&!aZ.o(s,n)&&Object.defineProperty(s,n,{enumerable:!0,get:t[n]})};aZ.o=(s,t)=>Object.prototype.hasOwnProperty.call(s,t);var Cc=globalThis.pdfjsLib={};aZ.d(Cc,{AbortException:()=>ZF,AnnotationEditorLayer:()=>BUe,AnnotationEditorParamsType:()=>vc,AnnotationEditorType:()=>Kc,AnnotationEditorUIManager:()=>iF,AnnotationLayer:()=>nPn,AnnotationMode:()=>LE,ColorPicker:()=>Y4e,DOMSVGFactory:()=>aQe,DrawLayer:()=>VUe,FeatureTest:()=>_b,GlobalWorkerOptions:()=>e3,ImageKind:()=>RNe,InvalidPDFException:()=>v$t,MissingPDFException:()=>YF,OPS:()=>NN,OutputScale:()=>L$e,PDFDataRangeTransport:()=>pUt,PDFDateString:()=>QXe,PDFWorker:()=>UB,PasswordResponses:()=>cMn,PermissionFlag:()=>lMn,PixelsPerInch:()=>OM,RenderingCancelledException:()=>ZXe,TextLayer:()=>hQ,UnexpectedResponseException:()=>DTe,Util:()=>Ko,VerbosityLevel:()=>ITe,XfaLayer:()=>xUt,build:()=>O6n,createValidAbsoluteUrl:()=>mMn,fetchData:()=>FTe,getDocument:()=>A6n,getFilenameFromUrl:()=>wMn,getPdfFilenameFromUrl:()=>jMn,getXfaPageViewport:()=>NMn,isDataScheme:()=>zTe,isPdfFile:()=>XXe,noContextMenu:()=>F2,normalizeUnicode:()=>vMn,setLayerDimensions:()=>aF,shadow:()=>nu,version:()=>D6n});const c1=typeof process=="object"&&process+""=="[object process]"&&!process.versions.nw&&!(process.versions.electron&&process.type&&process.type!=="browser"),y$t=[1,0,0,1,0,0],T$e=[.001,0,0,.001,0,0],iMn=1e7,RDe=1.35,Mw={ANY:1,DISPLAY:2,PRINT:4,ANNOTATIONS_FORMS:16,ANNOTATIONS_STORAGE:32,ANNOTATIONS_DISABLE:64,IS_EDITING:128,OPLIST:256},LE={DISABLE:0,ENABLE:1,ENABLE_FORMS:2,ENABLE_STORAGE:3},oMn="pdfjs_internal_editor_",Kc={DISABLE:-1,NONE:0,FREETEXT:3,HIGHLIGHT:9,STAMP:13,INK:15},vc={RESIZE:1,CREATE:2,FREETEXT_SIZE:11,FREETEXT_COLOR:12,FREETEXT_OPACITY:13,INK_COLOR:21,INK_THICKNESS:22,INK_OPACITY:23,HIGHLIGHT_COLOR:31,HIGHLIGHT_DEFAULT_COLOR:32,HIGHLIGHT_THICKNESS:33,HIGHLIGHT_FREE:34,HIGHLIGHT_SHOW_ALL:35},lMn={PRINT:4,MODIFY_CONTENTS:8,COPY:16,MODIFY_ANNOTATIONS:32,FILL_INTERACTIVE_FORMS:256,COPY_FOR_ACCESSIBILITY:512,ASSEMBLE:1024,PRINT_HIGH_QUALITY:2048},Gv={FILL:0,STROKE:1,FILL_STROKE:2,INVISIBLE:3,FILL_STROKE_MASK:3,ADD_TO_PATH_FLAG:4},RNe={GRAYSCALE_1BPP:1,RGB_24BPP:2,RGBA_32BPP:3},iy={TEXT:1,LINK:2,FREETEXT:3,LINE:4,SQUARE:5,CIRCLE:6,POLYGON:7,POLYLINE:8,HIGHLIGHT:9,UNDERLINE:10,SQUIGGLY:11,STRIKEOUT:12,STAMP:13,CARET:14,INK:15,POPUP:16,FILEATTACHMENT:17,WIDGET:20},BG={SOLID:1,DASHED:2,BEVELED:3,INSET:4,UNDERLINE:5},ITe={ERRORS:0,WARNINGS:1,INFOS:5},NN={dependency:1,setLineWidth:2,setLineCap:3,setLineJoin:4,setMiterLimit:5,setDash:6,setRenderingIntent:7,setFlatness:8,setGState:9,save:10,restore:11,transform:12,moveTo:13,lineTo:14,curveTo:15,curveTo2:16,curveTo3:17,closePath:18,rectangle:19,stroke:20,closeStroke:21,fill:22,eoFill:23,fillStroke:24,eoFillStroke:25,closeFillStroke:26,closeEOFillStroke:27,endPath:28,clip:29,eoClip:30,beginText:31,endText:32,setCharSpacing:33,setWordSpacing:34,setHScale:35,setLeading:36,setFont:37,setTextRenderingMode:38,setTextRise:39,moveText:40,setLeadingMoveText:41,setTextMatrix:42,nextLine:43,showText:44,showSpacedText:45,nextLineShowText:46,nextLineSetSpacingShowText:47,setCharWidth:48,setCharWidthAndBounds:49,setStrokeColorSpace:50,setFillColorSpace:51,setStrokeColor:52,setStrokeColorN:53,setFillColor:54,setFillColorN:55,setStrokeGray:56,setFillGray:57,setStrokeRGBColor:58,setFillRGBColor:59,setStrokeCMYKColor:60,setFillCMYKColor:61,shadingFill:62,beginInlineImage:63,beginImageData:64,endInlineImage:65,paintXObject:66,markPoint:67,markPointProps:68,beginMarkedContent:69,beginMarkedContentProps:70,endMarkedContent:71,beginCompat:72,endCompat:73,paintFormXObjectBegin:74,paintFormXObjectEnd:75,beginGroup:76,endGroup:77,beginAnnotation:80,endAnnotation:81,paintImageMaskXObject:83,paintImageMaskXObjectGroup:84,paintImageXObject:85,paintInlineImageXObject:86,paintInlineImageXObjectGroup:87,paintImageXObjectRepeat:88,paintImageMaskXObjectRepeat:89,paintSolidColorImageMask:90,constructPath:91,setStrokeTransparent:92,setFillTransparent:93},cMn={NEED_PASSWORD:1,INCORRECT_PASSWORD:2};let LTe=ITe.WARNINGS;function dMn(s){Number.isInteger(s)&&(LTe=s)}function uMn(){return LTe}function RTe(s){LTe>=ITe.INFOS&&console.log(`Info: ${s}`)}function md(s){LTe>=ITe.WARNINGS&&console.log(`Warning: ${s}`)}function wf(s){throw new Error(s)}function yy(s,t){s||wf(t)}function hMn(s){switch(s==null?void 0:s.protocol){case"http:":case"https:":case"ftp:":case"mailto:":case"tel:":return!0;default:return!1}}function mMn(s,t=null,n=null){if(!s)return null;try{if(n&&typeof s=="string"){if(n.addDefaultProtocol&&s.startsWith("www.")){const a=s.match(/\./g);(a==null?void 0:a.length)>=2&&(s=`http://${s}`)}if(n.tryConvertEncoding)try{s=yMn(s)}catch{}}const r=t?new URL(s,t):new URL(s);if(hMn(r))return r}catch{}return null}function nu(s,t,n,r=!1){return Object.defineProperty(s,t,{value:n,enumerable:!r,configurable:!0,writable:!1}),n}const N6=function(){function t(n,r){this.message=n,this.name=r}return t.prototype=new Error,t.constructor=t,t}();class M$e extends N6{constructor(t,n){super(t,"PasswordException"),this.code=n}}class P$e extends N6{constructor(t,n){super(t,"UnknownErrorException"),this.details=n}}class v$t extends N6{constructor(t){super(t,"InvalidPDFException")}}class YF extends N6{constructor(t){super(t,"MissingPDFException")}}class DTe extends N6{constructor(t,n){super(t,"UnexpectedResponseException"),this.status=n}}class fMn extends N6{constructor(t){super(t,"FormatError")}}class ZF extends N6{constructor(t){super(t,"AbortException")}}function b$t(s){(typeof s!="object"||(s==null?void 0:s.length)===void 0)&&wf("Invalid argument for bytesToString");const t=s.length,n=8192;if(t>24&255,s>>16&255,s>>8&255,s&255)}function KXe(s){const t=Object.create(null);for(const[n,r]of s)t[n]=r;return t}function gMn(){const s=new Uint8Array(4);return s[0]=1,new Uint32Array(s.buffer,0,1)[0]===1}function xMn(){try{return new Function(""),!0}catch{return!1}}class _b{static get isLittleEndian(){return nu(this,"isLittleEndian",gMn())}static get isEvalSupported(){return nu(this,"isEvalSupported",xMn())}static get isOffscreenCanvasSupported(){return nu(this,"isOffscreenCanvasSupported",typeof OffscreenCanvas<"u")}static get platform(){return typeof navigator<"u"&&typeof(navigator==null?void 0:navigator.platform)=="string"?nu(this,"platform",{isMac:navigator.platform.includes("Mac"),isWindows:navigator.platform.includes("Win"),isFirefox:typeof(navigator==null?void 0:navigator.userAgent)=="string"&&navigator.userAgent.includes("Firefox")}):nu(this,"platform",{isMac:!1,isWindows:!1,isFirefox:!1})}static get isCSSRoundSupported(){var t,n;return nu(this,"isCSSRoundSupported",(n=(t=globalThis.CSS)==null?void 0:t.supports)==null?void 0:n.call(t,"width: round(1.5px, 1px)"))}}const DDe=Array.from(Array(256).keys(),s=>s.toString(16).padStart(2,"0"));var I3,DNe,I$e;class Ko{static makeHexColor(t,n,r){return`#${DDe[t]}${DDe[n]}${DDe[r]}`}static scaleMinMax(t,n){let r;t[0]?(t[0]<0&&(r=n[0],n[0]=n[2],n[2]=r),n[0]*=t[0],n[2]*=t[0],t[3]<0&&(r=n[1],n[1]=n[3],n[3]=r),n[1]*=t[3],n[3]*=t[3]):(r=n[0],n[0]=n[1],n[1]=r,r=n[2],n[2]=n[3],n[3]=r,t[1]<0&&(r=n[1],n[1]=n[3],n[3]=r),n[1]*=t[1],n[3]*=t[1],t[2]<0&&(r=n[0],n[0]=n[2],n[2]=r),n[0]*=t[2],n[2]*=t[2]),n[0]+=t[4],n[1]+=t[5],n[2]+=t[4],n[3]+=t[5]}static transform(t,n){return[t[0]*n[0]+t[2]*n[1],t[1]*n[0]+t[3]*n[1],t[0]*n[2]+t[2]*n[3],t[1]*n[2]+t[3]*n[3],t[0]*n[4]+t[2]*n[5]+t[4],t[1]*n[4]+t[3]*n[5]+t[5]]}static applyTransform(t,n){const r=t[0]*n[0]+t[1]*n[2]+n[4],a=t[0]*n[1]+t[1]*n[3]+n[5];return[r,a]}static applyInverseTransform(t,n){const r=n[0]*n[3]-n[1]*n[2],a=(t[0]*n[3]-t[1]*n[2]+n[2]*n[5]-n[4]*n[3])/r,i=(-t[0]*n[1]+t[1]*n[0]+n[4]*n[1]-n[5]*n[0])/r;return[a,i]}static getAxialAlignedBoundingBox(t,n){const r=this.applyTransform(t,n),a=this.applyTransform(t.slice(2,4),n),i=this.applyTransform([t[0],t[3]],n),l=this.applyTransform([t[2],t[1]],n);return[Math.min(r[0],a[0],i[0],l[0]),Math.min(r[1],a[1],i[1],l[1]),Math.max(r[0],a[0],i[0],l[0]),Math.max(r[1],a[1],i[1],l[1])]}static inverseTransform(t){const n=t[0]*t[3]-t[1]*t[2];return[t[3]/n,-t[1]/n,-t[2]/n,t[0]/n,(t[2]*t[5]-t[4]*t[3])/n,(t[4]*t[1]-t[5]*t[0])/n]}static singularValueDecompose2dScale(t){const n=[t[0],t[2],t[1],t[3]],r=t[0]*n[0]+t[1]*n[2],a=t[0]*n[1]+t[1]*n[3],i=t[2]*n[0]+t[3]*n[2],l=t[2]*n[1]+t[3]*n[3],o=(r+l)/2,c=Math.sqrt((r+l)**2-4*(r*l-i*a))/2,d=o+c||1,u=o-c||1;return[Math.sqrt(d),Math.sqrt(u)]}static normalizeRect(t){const n=t.slice(0);return t[0]>t[2]&&(n[0]=t[2],n[2]=t[0]),t[1]>t[3]&&(n[1]=t[3],n[3]=t[1]),n}static intersect(t,n){const r=Math.max(Math.min(t[0],t[2]),Math.min(n[0],n[2])),a=Math.min(Math.max(t[0],t[2]),Math.max(n[0],n[2]));if(r>a)return null;const i=Math.max(Math.min(t[1],t[3]),Math.min(n[1],n[3])),l=Math.min(Math.max(t[1],t[3]),Math.max(n[1],n[3]));return i>l?null:[r,i,a,l]}static bezierBoundingBox(t,n,r,a,i,l,o,c,d){return d?(d[0]=Math.min(d[0],t,o),d[1]=Math.min(d[1],n,c),d[2]=Math.max(d[2],t,o),d[3]=Math.max(d[3],n,c)):d=[Math.min(t,o),Math.min(n,c),Math.max(t,o),Math.max(n,c)],ss(this,I3,I$e).call(this,t,r,i,o,n,a,l,c,3*(-t+3*(r-i)+o),6*(t-2*r+i),3*(r-t),d),ss(this,I3,I$e).call(this,t,r,i,o,n,a,l,c,3*(-n+3*(a-l)+c),6*(n-2*a+l),3*(a-n),d),d}}I3=new WeakSet,DNe=function(t,n,r,a,i,l,o,c,d,u){if(d<=0||d>=1)return;const h=1-d,m=d*d,p=m*d,g=h*(h*(h*t+3*d*n)+3*m*r)+p*a,x=h*(h*(h*i+3*d*l)+3*m*o)+p*c;u[0]=Math.min(u[0],g),u[1]=Math.min(u[1],x),u[2]=Math.max(u[2],g),u[3]=Math.max(u[3],x)},I$e=function(t,n,r,a,i,l,o,c,d,u,h,m){if(Math.abs(d)<1e-12){Math.abs(u)>=1e-12&&ss(this,I3,DNe).call(this,t,n,r,a,i,l,o,c,-h/u,m);return}const p=u**2-4*h*d;if(p<0)return;const g=Math.sqrt(p),x=2*d;ss(this,I3,DNe).call(this,t,n,r,a,i,l,o,c,(-u+g)/x,m),ss(this,I3,DNe).call(this,t,n,r,a,i,l,o,c,(-u-g)/x,m)},ds(Ko,I3);function yMn(s){return decodeURIComponent(escape(s))}let ODe=null,y1t=null;function vMn(s){return ODe||(ODe=/([\u00a0\u00b5\u037e\u0eb3\u2000-\u200a\u202f\u2126\ufb00-\ufb04\ufb06\ufb20-\ufb36\ufb38-\ufb3c\ufb3e\ufb40-\ufb41\ufb43-\ufb44\ufb46-\ufba1\ufba4-\ufba9\ufbae-\ufbb1\ufbd3-\ufbdc\ufbde-\ufbe7\ufbea-\ufbf8\ufbfc-\ufbfd\ufc00-\ufc5d\ufc64-\ufcf1\ufcf5-\ufd3d\ufd88\ufdf4\ufdfa-\ufdfb\ufe71\ufe77\ufe79\ufe7b\ufe7d]+)|(\ufb05+)/gu,y1t=new Map([["ſt","ſt"]])),s.replaceAll(ODe,(t,n,r)=>n?n.normalize("NFKC"):y1t.get(r))}function bMn(){if(typeof crypto<"u"&&typeof(crypto==null?void 0:crypto.randomUUID)=="function")return crypto.randomUUID();const s=new Uint8Array(32);if(typeof crypto<"u"&&typeof(crypto==null?void 0:crypto.getRandomValues)=="function")crypto.getRandomValues(s);else for(let t=0;t<32;t++)s[t]=Math.floor(Math.random()*255);return b$t(s)}const YXe="pdfjs_internal_id_",eC={BEZIER_CURVE_TO:0,MOVE_TO:1,LINE_TO:2,QUADRATIC_CURVE_TO:3,RESTORE:4,SAVE:5,SCALE:6,TRANSFORM:7,TRANSLATE:8};function _Mn(s){return Uint8Array.prototype.toBase64?s.toBase64():btoa(b$t(s))}const uC="http://www.w3.org/2000/svg",XR=class XR{};ur(XR,"CSS",96),ur(XR,"PDF",72),ur(XR,"PDF_TO_CSS_UNITS",XR.CSS/XR.PDF);let OM=XR;async function FTe(s,t="text"){if(BW(s,document.baseURI)){const n=await fetch(s);if(!n.ok)throw new Error(n.statusText);switch(t){case"arraybuffer":return n.arrayBuffer();case"blob":return n.blob();case"json":return n.json()}return n.text()}return new Promise((n,r)=>{const a=new XMLHttpRequest;a.open("GET",s,!0),a.responseType=t,a.onreadystatechange=()=>{if(a.readyState===XMLHttpRequest.DONE){if(a.status===200||a.status===0){switch(t){case"arraybuffer":case"blob":case"json":n(a.response);return}n(a.responseText);return}r(new Error(a.statusText))}},a.send(null)})}class xte{constructor({viewBox:t,scale:n,rotation:r,offsetX:a=0,offsetY:i=0,dontFlip:l=!1}){this.viewBox=t,this.scale=n,this.rotation=r,this.offsetX=a,this.offsetY=i;const o=(t[2]+t[0])/2,c=(t[3]+t[1])/2;let d,u,h,m;switch(r%=360,r<0&&(r+=360),r){case 180:d=-1,u=0,h=0,m=1;break;case 90:d=0,u=1,h=1,m=0;break;case 270:d=0,u=-1,h=-1,m=0;break;case 0:d=1,u=0,h=0,m=-1;break;default:throw new Error("PageViewport: Invalid rotation, must be a multiple of 90 degrees.")}l&&(h=-h,m=-m);let p,g,x,y;d===0?(p=Math.abs(c-t[1])*n+a,g=Math.abs(o-t[0])*n+i,x=(t[3]-t[1])*n,y=(t[2]-t[0])*n):(p=Math.abs(o-t[0])*n+a,g=Math.abs(c-t[1])*n+i,x=(t[2]-t[0])*n,y=(t[3]-t[1])*n),this.transform=[d*n,u*n,h*n,m*n,p-d*n*o-h*n*c,g-u*n*o-m*n*c],this.width=x,this.height=y}get rawDims(){const{viewBox:t}=this;return nu(this,"rawDims",{pageWidth:t[2]-t[0],pageHeight:t[3]-t[1],pageX:t[0],pageY:t[1]})}clone({scale:t=this.scale,rotation:n=this.rotation,offsetX:r=this.offsetX,offsetY:a=this.offsetY,dontFlip:i=!1}={}){return new xte({viewBox:this.viewBox.slice(),scale:t,rotation:n,offsetX:r,offsetY:a,dontFlip:i})}convertToViewportPoint(t,n){return Ko.applyTransform([t,n],this.transform)}convertToViewportRectangle(t){const n=Ko.applyTransform([t[0],t[1]],this.transform),r=Ko.applyTransform([t[2],t[3]],this.transform);return[n[0],n[1],r[0],r[1]]}convertToPdfPoint(t,n){return Ko.applyInverseTransform([t,n],this.transform)}}class ZXe extends N6{constructor(t,n=0){super(t,"RenderingCancelledException"),this.extraDelay=n}}function zTe(s){const t=s.length;let n=0;for(;n=1&&a<=12?a-1:0;let i=parseInt(n[3],10);i=i>=1&&i<=31?i:1;let l=parseInt(n[4],10);l=l>=0&&l<=23?l:0;let o=parseInt(n[5],10);o=o>=0&&o<=59?o:0;let c=parseInt(n[6],10);c=c>=0&&c<=59?c:0;const d=n[7]||"Z";let u=parseInt(n[8],10);u=u>=0&&u<=23?u:0;let h=parseInt(n[9],10)||0;return h=h>=0&&h<=59?h:0,d==="-"?(l+=u,o+=h):d==="+"&&(l-=u,o-=h),new Date(Date.UTC(r,a,i,l,o,c))}}PQ=new WeakMap,ds(QXe,PQ);function NMn(s,{scale:t=1,rotation:n=0}){const{width:r,height:a}=s.attributes.style,i=[0,0,parseInt(r),parseInt(a)];return new xte({viewBox:i,scale:t,rotation:n})}function JXe(s){if(s.startsWith("#")){const t=parseInt(s.slice(1),16);return[(t&16711680)>>16,(t&65280)>>8,t&255]}return s.startsWith("rgb(")?s.slice(4,-1).split(",").map(t=>parseInt(t)):s.startsWith("rgba(")?s.slice(5,-1).split(",").map(t=>parseInt(t)).slice(0,3):(md(`Not a valid color format: "${s}"`),[0,0,0])}function kMn(s){const t=document.createElement("span");t.style.visibility="hidden",document.body.append(t);for(const n of s.keys()){t.style.color=n;const r=window.getComputedStyle(t).color;s.set(n,JXe(r))}t.remove()}function kp(s){const{a:t,b:n,c:r,d:a,e:i,f:l}=s.getTransform();return[t,n,r,a,i,l]}function tC(s){const{a:t,b:n,c:r,d:a,e:i,f:l}=s.getTransform().invertSelf();return[t,n,r,a,i,l]}function aF(s,t,n=!1,r=!0){if(t instanceof xte){const{pageWidth:a,pageHeight:i}=t.rawDims,{style:l}=s,o=_b.isCSSRoundSupported,c=`var(--scale-factor) * ${a}px`,d=`var(--scale-factor) * ${i}px`,u=o?`round(down, ${c}, var(--scale-round-x, 1px))`:`calc(${c})`,h=o?`round(down, ${d}, var(--scale-round-y, 1px))`:`calc(${d})`;!n||t.rotation%180===0?(l.width=u,l.height=h):(l.width=h,l.height=u)}r&&s.setAttribute("data-main-rotation",t.rotation)}class L$e{constructor(){const t=window.devicePixelRatio||1;this.sx=t,this.sy=t}get scaled(){return this.sx!==1||this.sy!==1}get symmetric(){return this.sx===this.sy}}var VE,PD,SN,ID,IQ,LQ,_Ce,_$t,wb,w$t,j$t,ONe,N$t,D$e;const yC=class yC{constructor(t){ds(this,wb);ds(this,VE,null);ds(this,PD,null);ds(this,SN);ds(this,ID,null);ds(this,IQ,null);$t(this,SN,t),ge(yC,LQ)||$t(yC,LQ,Object.freeze({freetext:"pdfjs-editor-remove-freetext-button",highlight:"pdfjs-editor-remove-highlight-button",ink:"pdfjs-editor-remove-ink-button",stamp:"pdfjs-editor-remove-stamp-button"}))}render(){const t=$t(this,VE,document.createElement("div"));t.classList.add("editToolbar","hidden"),t.setAttribute("role","toolbar");const n=ge(this,SN)._uiManager._signal;t.addEventListener("contextmenu",F2,{signal:n}),t.addEventListener("pointerdown",ss(yC,_Ce,_$t),{signal:n});const r=$t(this,ID,document.createElement("div"));r.className="buttons",t.append(r);const a=ge(this,SN).toolbarPosition;if(a){const{style:i}=t,l=ge(this,SN)._uiManager.direction==="ltr"?1-a[0]:a[0];i.insetInlineEnd=`${100*l}%`,i.top=`calc(${100*a[1]}% + var(--editor-toolbar-vert-offset))`}return ss(this,wb,N$t).call(this),t}get div(){return ge(this,VE)}hide(){var t;ge(this,VE).classList.add("hidden"),(t=ge(this,PD))==null||t.hideDropdown()}show(){var t;ge(this,VE).classList.remove("hidden"),(t=ge(this,IQ))==null||t.shown()}async addAltText(t){const n=await t.render();ss(this,wb,ONe).call(this,n),ge(this,ID).prepend(n,ge(this,wb,D$e)),$t(this,IQ,t)}addColorPicker(t){$t(this,PD,t);const n=t.renderButton();ss(this,wb,ONe).call(this,n),ge(this,ID).prepend(n,ge(this,wb,D$e))}remove(){var t;ge(this,VE).remove(),(t=ge(this,PD))==null||t.destroy(),$t(this,PD,null)}};VE=new WeakMap,PD=new WeakMap,SN=new WeakMap,ID=new WeakMap,IQ=new WeakMap,LQ=new WeakMap,_Ce=new WeakSet,_$t=function(t){t.stopPropagation()},wb=new WeakSet,w$t=function(t){ge(this,SN)._focusEventsAllowed=!1,t.preventDefault(),t.stopPropagation()},j$t=function(t){ge(this,SN)._focusEventsAllowed=!0,t.preventDefault(),t.stopPropagation()},ONe=function(t){const n=ge(this,SN)._uiManager._signal;t.addEventListener("focusin",ss(this,wb,w$t).bind(this),{capture:!0,signal:n}),t.addEventListener("focusout",ss(this,wb,j$t).bind(this),{capture:!0,signal:n}),t.addEventListener("contextmenu",F2,{signal:n})},N$t=function(){const{editorType:t,_uiManager:n}=ge(this,SN),r=document.createElement("button");r.className="delete",r.tabIndex=0,r.setAttribute("data-l10n-id",ge(yC,LQ)[t]),ss(this,wb,ONe).call(this,r),r.addEventListener("click",a=>{n.delete()},{signal:n._signal}),ge(this,ID).append(r)},D$e=function(){const t=document.createElement("div");return t.className="divider",t},ds(yC,_Ce),ds(yC,LQ,null);let R$e=yC;var RQ,LD,RD,UM,k$t,S$t,C$t;class SMn{constructor(t){ds(this,UM);ds(this,RQ,null);ds(this,LD,null);ds(this,RD);$t(this,RD,t)}show(t,n,r){const[a,i]=ss(this,UM,S$t).call(this,n,r),{style:l}=ge(this,LD)||$t(this,LD,ss(this,UM,k$t).call(this));t.append(ge(this,LD)),l.insetInlineEnd=`${100*a}%`,l.top=`calc(${100*i}% + var(--editor-toolbar-vert-offset))`}hide(){ge(this,LD).remove()}}RQ=new WeakMap,LD=new WeakMap,RD=new WeakMap,UM=new WeakSet,k$t=function(){const t=$t(this,LD,document.createElement("div"));t.className="editToolbar",t.setAttribute("role","toolbar"),t.addEventListener("contextmenu",F2,{signal:ge(this,RD)._signal});const n=$t(this,RQ,document.createElement("div"));return n.className="buttons",t.append(n),ss(this,UM,C$t).call(this),t},S$t=function(t,n){let r=0,a=0;for(const i of t){const l=i.y+i.height;if(lr){a=o,r=l;continue}n?o>a&&(a=o):o{ge(this,RD).highlightSelection("floating_button")},{signal:r}),ge(this,RQ).append(t)};function G4e(s,t,n){for(const r of n)t.addEventListener(r,s[r].bind(s))}function CMn(s){return Math.round(Math.min(255,Math.max(1,255*s))).toString(16).padStart(2,"0")}var wCe;class AMn{constructor(){ds(this,wCe,0)}get id(){return`${oMn}${Hy(this,wCe)._++}`}}wCe=new WeakMap;var o$,DQ,Yv,l$,FNe;const kJe=class kJe{constructor(){ds(this,l$);ds(this,o$,bMn());ds(this,DQ,0);ds(this,Yv,null)}static get _isSVGFittingCanvas(){const t='data:image/svg+xml;charset=UTF-8,',r=new OffscreenCanvas(1,3).getContext("2d",{willReadFrequently:!0}),a=new Image;a.src=t;const i=a.decode().then(()=>(r.drawImage(a,0,0,1,1,0,0,1,3),new Uint32Array(r.getImageData(0,0,1,1).data.buffer)[0]===0));return nu(this,"_isSVGFittingCanvas",i)}async getFromFile(t){const{lastModified:n,name:r,size:a,type:i}=t;return ss(this,l$,FNe).call(this,`${n}_${r}_${a}_${i}`,t)}async getFromUrl(t){return ss(this,l$,FNe).call(this,t,t)}async getFromBlob(t,n){const r=await n;return ss(this,l$,FNe).call(this,t,r)}async getFromId(t){ge(this,Yv)||$t(this,Yv,new Map);const n=ge(this,Yv).get(t);if(!n)return null;if(n.bitmap)return n.refCounter+=1,n;if(n.file)return this.getFromFile(n.file);if(n.blobPromise){const{blobPromise:r}=n;return delete n.blobPromise,this.getFromBlob(n.id,r)}return this.getFromUrl(n.url)}getFromCanvas(t,n){ge(this,Yv)||$t(this,Yv,new Map);let r=ge(this,Yv).get(t);if(r!=null&&r.bitmap)return r.refCounter+=1,r;const a=new OffscreenCanvas(n.width,n.height);return a.getContext("2d").drawImage(n,0,0),r={bitmap:a.transferToImageBitmap(),id:`image_${ge(this,o$)}_${Hy(this,DQ)._++}`,refCounter:1,isSvg:!1},ge(this,Yv).set(t,r),ge(this,Yv).set(r.id,r),r}getSvgUrl(t){const n=ge(this,Yv).get(t);return n!=null&&n.isSvg?n.svgUrl:null}deleteId(t){var a;ge(this,Yv)||$t(this,Yv,new Map);const n=ge(this,Yv).get(t);if(!n||(n.refCounter-=1,n.refCounter!==0))return;const{bitmap:r}=n;if(!n.url&&!n.file){const i=new OffscreenCanvas(r.width,r.height);i.getContext("bitmaprenderer").transferFromImageBitmap(r),n.blobPromise=i.convertToBlob()}(a=r.close)==null||a.call(r),n.bitmap=null}isValidId(t){return t.startsWith(`image_${ge(this,o$)}_`)}};o$=new WeakMap,DQ=new WeakMap,Yv=new WeakMap,l$=new WeakSet,FNe=async function(t,n){ge(this,Yv)||$t(this,Yv,new Map);let r=ge(this,Yv).get(t);if(r===null)return null;if(r!=null&&r.bitmap)return r.refCounter+=1,r;try{r||(r={bitmap:null,id:`image_${ge(this,o$)}_${Hy(this,DQ)._++}`,refCounter:0,isSvg:!1});let a;if(typeof n=="string"?(r.url=n,a=await FTe(n,"blob")):n instanceof File?a=r.file=n:n instanceof Blob&&(a=n),a.type==="image/svg+xml"){const i=kJe._isSVGFittingCanvas,l=new FileReader,o=new Image,c=new Promise((d,u)=>{o.onload=()=>{r.bitmap=o,r.isSvg=!0,d()},l.onload=async()=>{const h=r.svgUrl=l.result;o.src=await i?`${h}#svgView(preserveAspectRatio(none))`:h},o.onerror=l.onerror=u});l.readAsDataURL(a),await c}else r.bitmap=await createImageBitmap(a);r.refCounter=1}catch(a){console.error(a),r=null}return ge(this,Yv).set(t,r),r&&ge(this,Yv).set(r.id,r),r};let O$e=kJe;var Xy,HE,OQ,Qy;class EMn{constructor(t=128){ds(this,Xy,[]);ds(this,HE,!1);ds(this,OQ);ds(this,Qy,-1);$t(this,OQ,t)}add({cmd:t,undo:n,post:r,mustExec:a,type:i=NaN,overwriteIfSameType:l=!1,keepUndo:o=!1}){if(a&&t(),ge(this,HE))return;const c={cmd:t,undo:n,post:r,type:i};if(ge(this,Qy)===-1){ge(this,Xy).length>0&&(ge(this,Xy).length=0),$t(this,Qy,0),ge(this,Xy).push(c);return}if(l&&ge(this,Xy)[ge(this,Qy)].type===i){o&&(c.undo=ge(this,Xy)[ge(this,Qy)].undo),ge(this,Xy)[ge(this,Qy)]=c;return}const d=ge(this,Qy)+1;d===ge(this,OQ)?ge(this,Xy).splice(0,1):($t(this,Qy,d),di===n[l]))return NCe._colorsMapping.get(r);return n}getHexCode(t){const n=this._colors.get(t);return n?Ko.makeHexColor(...n):t}};ur(NCe,"_colorsMapping",new Map([["CanvasText",[0,0,0]],["Canvas",[255,255,255]]]));let F$e=NCe;var c$,ww,ly,U0,d$,EC,u$,CN,GE,h$,DD,zS,AN,OD,FQ,zQ,m$,BQ,BS,WE,f$,KE,$S,kCe,YE,$Q,ZE,FD,UQ,qQ,Jy,Eh,TC,zD,VQ,HQ,XE,US,MC,GQ,Wj,Bi,zNe,z$e,E$t,T$t,BNe,M$t,P$t,I$t,B$e,L$t,$$e,U$e,R$t,K1,iE,D$t,O$t,q$e,F$t,$W,V$e;const Mz=class Mz{constructor(t,n,r,a,i,l,o,c,d,u,h){ds(this,Bi);ds(this,c$,new AbortController);ds(this,ww,null);ds(this,ly,new Map);ds(this,U0,new Map);ds(this,d$,null);ds(this,EC,null);ds(this,u$,null);ds(this,CN,new EMn);ds(this,GE,null);ds(this,h$,0);ds(this,DD,new Set);ds(this,zS,null);ds(this,AN,null);ds(this,OD,new Set);ds(this,FQ,!1);ds(this,zQ,!1);ds(this,m$,!1);ds(this,BQ,null);ds(this,BS,null);ds(this,WE,null);ds(this,f$,null);ds(this,KE,!1);ds(this,$S,null);ds(this,kCe,new AMn);ds(this,YE,!1);ds(this,$Q,!1);ds(this,ZE,null);ds(this,FD,null);ds(this,UQ,null);ds(this,qQ,null);ds(this,Jy,Kc.NONE);ds(this,Eh,new Set);ds(this,TC,null);ds(this,zD,null);ds(this,VQ,null);ds(this,HQ,{isEditing:!1,isEmpty:!0,hasSomethingToUndo:!1,hasSomethingToRedo:!1,hasSelectedEditor:!1,hasSelectedText:!1});ds(this,XE,[0,0]);ds(this,US,null);ds(this,MC,null);ds(this,GQ,null);ds(this,Wj,null);const m=this._signal=ge(this,c$).signal;$t(this,MC,t),$t(this,GQ,n),$t(this,d$,r),this._eventBus=a,a._on("editingaction",this.onEditingAction.bind(this),{signal:m}),a._on("pagechanging",this.onPageChanging.bind(this),{signal:m}),a._on("scalechanging",this.onScaleChanging.bind(this),{signal:m}),a._on("rotationchanging",this.onRotationChanging.bind(this),{signal:m}),a._on("setpreference",this.onSetPreference.bind(this),{signal:m}),a._on("switchannotationeditorparams",p=>this.updateParams(p.type,p.value),{signal:m}),ss(this,Bi,M$t).call(this),ss(this,Bi,R$t).call(this),ss(this,Bi,B$e).call(this),$t(this,EC,i.annotationStorage),$t(this,BQ,i.filterFactory),$t(this,zD,l),$t(this,f$,o||null),$t(this,FQ,c),$t(this,zQ,d),$t(this,m$,u),$t(this,qQ,h||null),this.viewParameters={realScale:OM.PDF_TO_CSS_UNITS,rotation:0},this.isShiftKeyDown=!1}static get _keyboardManager(){const t=Mz.prototype,n=l=>ge(l,MC).contains(document.activeElement)&&document.activeElement.tagName!=="BUTTON"&&l.hasSomethingToControl(),r=(l,{target:o})=>{if(o instanceof HTMLInputElement){const{type:c}=o;return c!=="text"&&c!=="number"}return!0},a=this.TRANSLATE_SMALL,i=this.TRANSLATE_BIG;return nu(this,"_keyboardManager",new yte([[["ctrl+a","mac+meta+a"],t.selectAll,{checker:r}],[["ctrl+z","mac+meta+z"],t.undo,{checker:r}],[["ctrl+y","ctrl+shift+z","mac+meta+shift+z","ctrl+shift+Z","mac+meta+shift+Z"],t.redo,{checker:r}],[["Backspace","alt+Backspace","ctrl+Backspace","shift+Backspace","mac+Backspace","mac+alt+Backspace","mac+ctrl+Backspace","Delete","ctrl+Delete","shift+Delete","mac+Delete"],t.delete,{checker:r}],[["Enter","mac+Enter"],t.addNewEditorFromKeyboard,{checker:(l,{target:o})=>!(o instanceof HTMLButtonElement)&&ge(l,MC).contains(o)&&!l.isEnterHandled}],[[" ","mac+ "],t.addNewEditorFromKeyboard,{checker:(l,{target:o})=>!(o instanceof HTMLButtonElement)&&ge(l,MC).contains(document.activeElement)}],[["Escape","mac+Escape"],t.unselectAll],[["ArrowLeft","mac+ArrowLeft"],t.translateSelectedEditors,{args:[-a,0],checker:n}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t.translateSelectedEditors,{args:[-i,0],checker:n}],[["ArrowRight","mac+ArrowRight"],t.translateSelectedEditors,{args:[a,0],checker:n}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t.translateSelectedEditors,{args:[i,0],checker:n}],[["ArrowUp","mac+ArrowUp"],t.translateSelectedEditors,{args:[0,-a],checker:n}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t.translateSelectedEditors,{args:[0,-i],checker:n}],[["ArrowDown","mac+ArrowDown"],t.translateSelectedEditors,{args:[0,a],checker:n}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t.translateSelectedEditors,{args:[0,i],checker:n}]]))}destroy(){var t,n,r,a;(t=ge(this,Wj))==null||t.resolve(),$t(this,Wj,null),(n=ge(this,c$))==null||n.abort(),$t(this,c$,null),this._signal=null;for(const i of ge(this,U0).values())i.destroy();ge(this,U0).clear(),ge(this,ly).clear(),ge(this,OD).clear(),$t(this,ww,null),ge(this,Eh).clear(),ge(this,CN).destroy(),(r=ge(this,d$))==null||r.destroy(),(a=ge(this,$S))==null||a.hide(),$t(this,$S,null),ge(this,BS)&&(clearTimeout(ge(this,BS)),$t(this,BS,null)),ge(this,US)&&(clearTimeout(ge(this,US)),$t(this,US,null))}combinedSignal(t){return AbortSignal.any([this._signal,t.signal])}get mlManager(){return ge(this,qQ)}get useNewAltTextFlow(){return ge(this,zQ)}get useNewAltTextWhenAddingImage(){return ge(this,m$)}get hcmFilter(){return nu(this,"hcmFilter",ge(this,zD)?ge(this,BQ).addHCMFilter(ge(this,zD).foreground,ge(this,zD).background):"none")}get direction(){return nu(this,"direction",getComputedStyle(ge(this,MC)).direction)}get highlightColors(){return nu(this,"highlightColors",ge(this,f$)?new Map(ge(this,f$).split(",").map(t=>t.split("=").map(n=>n.trim()))):null)}get highlightColorNames(){return nu(this,"highlightColorNames",this.highlightColors?new Map(Array.from(this.highlightColors,t=>t.reverse())):null)}setMainHighlightColorPicker(t){$t(this,UQ,t)}editAltText(t,n=!1){var r;(r=ge(this,d$))==null||r.editAltText(this,t,n)}switchToMode(t,n){this._eventBus.on("annotationeditormodechanged",n,{once:!0,signal:this._signal}),this._eventBus.dispatch("showannotationeditorui",{source:this,mode:t})}setPreference(t,n){this._eventBus.dispatch("setpreference",{source:this,name:t,value:n})}onSetPreference({name:t,value:n}){switch(t){case"enableNewAltTextWhenAddingImage":$t(this,m$,n);break}}onPageChanging({pageNumber:t}){$t(this,h$,t-1)}focusMainContainer(){ge(this,MC).focus()}findParent(t,n){for(const r of ge(this,U0).values()){const{x:a,y:i,width:l,height:o}=r.div.getBoundingClientRect();if(t>=a&&t<=a+l&&n>=i&&n<=i+o)return r}return null}disableUserSelect(t=!1){ge(this,GQ).classList.toggle("noUserSelect",t)}addShouldRescale(t){ge(this,OD).add(t)}removeShouldRescale(t){ge(this,OD).delete(t)}onScaleChanging({scale:t}){this.commitOrRemove(),this.viewParameters.realScale=t*OM.PDF_TO_CSS_UNITS;for(const n of ge(this,OD))n.onScaleChanging()}onRotationChanging({pagesRotation:t}){this.commitOrRemove(),this.viewParameters.rotation=t}highlightSelection(t=""){const n=document.getSelection();if(!n||n.isCollapsed)return;const{anchorNode:r,anchorOffset:a,focusNode:i,focusOffset:l}=n,o=n.toString(),d=ss(this,Bi,zNe).call(this,n).closest(".textLayer"),u=this.getSelectionBoxes(d);if(!u)return;n.empty();const h=ss(this,Bi,z$e).call(this,d),m=ge(this,Jy)===Kc.NONE,p=()=>{h==null||h.createAndAddNewEditor({x:0,y:0},!1,{methodOfCreation:t,boxes:u,anchorNode:r,anchorOffset:a,focusNode:i,focusOffset:l,text:o}),m&&this.showAllEditors("highlight",!0,!0)};if(m){this.switchToMode(Kc.HIGHLIGHT,p);return}p()}addToAnnotationStorage(t){!t.isEmpty()&&ge(this,EC)&&!ge(this,EC).has(t.id)&&ge(this,EC).setValue(t.id,t)}blur(){if(this.isShiftKeyDown=!1,ge(this,KE)&&($t(this,KE,!1),ss(this,Bi,BNe).call(this,"main_toolbar")),!this.hasSelection)return;const{activeElement:t}=document;for(const n of ge(this,Eh))if(n.div.contains(t)){$t(this,FD,[n,t]),n._focusEventsAllowed=!1;break}}focus(){if(!ge(this,FD))return;const[t,n]=ge(this,FD);$t(this,FD,null),n.addEventListener("focusin",()=>{t._focusEventsAllowed=!0},{once:!0,signal:this._signal}),n.focus()}addEditListeners(){ss(this,Bi,B$e).call(this),ss(this,Bi,$$e).call(this)}removeEditListeners(){ss(this,Bi,L$t).call(this),ss(this,Bi,U$e).call(this)}dragOver(t){for(const{type:n}of t.dataTransfer.items)for(const r of ge(this,AN))if(r.isHandlingMimeForPasting(n)){t.dataTransfer.dropEffect="copy",t.preventDefault();return}}drop(t){for(const n of t.dataTransfer.items)for(const r of ge(this,AN))if(r.isHandlingMimeForPasting(n.type)){r.paste(n,this.currentLayer),t.preventDefault();return}}copy(t){var r;if(t.preventDefault(),(r=ge(this,ww))==null||r.commitOrRemove(),!this.hasSelection)return;const n=[];for(const a of ge(this,Eh)){const i=a.serialize(!0);i&&n.push(i)}n.length!==0&&t.clipboardData.setData("application/pdfjs",JSON.stringify(n))}cut(t){this.copy(t),this.delete()}async paste(t){t.preventDefault();const{clipboardData:n}=t;for(const i of n.items)for(const l of ge(this,AN))if(l.isHandlingMimeForPasting(i.type)){l.paste(i,this.currentLayer);return}let r=n.getData("application/pdfjs");if(!r)return;try{r=JSON.parse(r)}catch(i){md(`paste: "${i.message}".`);return}if(!Array.isArray(r))return;this.unselectAll();const a=this.currentLayer;try{const i=[];for(const c of r){const d=await a.deserialize(c);if(!d)return;i.push(d)}const l=()=>{for(const c of i)ss(this,Bi,q$e).call(this,c);ss(this,Bi,V$e).call(this,i)},o=()=>{for(const c of i)c.remove()};this.addCommands({cmd:l,undo:o,mustExec:!0})}catch(i){md(`paste: "${i.message}".`)}}keydown(t){!this.isShiftKeyDown&&t.key==="Shift"&&(this.isShiftKeyDown=!0),ge(this,Jy)!==Kc.NONE&&!this.isEditorHandlingKeyboard&&Mz._keyboardManager.exec(this,t)}keyup(t){this.isShiftKeyDown&&t.key==="Shift"&&(this.isShiftKeyDown=!1,ge(this,KE)&&($t(this,KE,!1),ss(this,Bi,BNe).call(this,"main_toolbar")))}onEditingAction({name:t}){switch(t){case"undo":case"redo":case"delete":case"selectAll":this[t]();break;case"highlightSelection":this.highlightSelection("context_menu");break}}setEditingState(t){t?(ss(this,Bi,P$t).call(this),ss(this,Bi,$$e).call(this),ss(this,Bi,K1).call(this,{isEditing:ge(this,Jy)!==Kc.NONE,isEmpty:ss(this,Bi,$W).call(this),hasSomethingToUndo:ge(this,CN).hasSomethingToUndo(),hasSomethingToRedo:ge(this,CN).hasSomethingToRedo(),hasSelectedEditor:!1})):(ss(this,Bi,I$t).call(this),ss(this,Bi,U$e).call(this),ss(this,Bi,K1).call(this,{isEditing:!1}),this.disableUserSelect(!1))}registerEditorTypes(t){if(!ge(this,AN)){$t(this,AN,t);for(const n of ge(this,AN))ss(this,Bi,iE).call(this,n.defaultPropertiesToUpdate)}}getId(){return ge(this,kCe).id}get currentLayer(){return ge(this,U0).get(ge(this,h$))}getLayer(t){return ge(this,U0).get(t)}get currentPageIndex(){return ge(this,h$)}addLayer(t){ge(this,U0).set(t.pageIndex,t),ge(this,YE)?t.enable():t.disable()}removeLayer(t){ge(this,U0).delete(t.pageIndex)}async updateMode(t,n=null,r=!1){if(ge(this,Jy)!==t&&!(ge(this,Wj)&&(await ge(this,Wj).promise,!ge(this,Wj)))){if($t(this,Wj,Promise.withResolvers()),$t(this,Jy,t),t===Kc.NONE){this.setEditingState(!1),ss(this,Bi,O$t).call(this),ge(this,Wj).resolve();return}this.setEditingState(!0),await ss(this,Bi,D$t).call(this),this.unselectAll();for(const a of ge(this,U0).values())a.updateMode(t);if(!n){r&&this.addNewEditorFromKeyboard(),ge(this,Wj).resolve();return}for(const a of ge(this,ly).values())a.annotationElementId===n?(this.setSelected(a),a.enterInEditMode()):a.unselect();ge(this,Wj).resolve()}}addNewEditorFromKeyboard(){this.currentLayer.canCreateNewEmptyEditor()&&this.currentLayer.addNewEditor()}updateToolbar(t){t!==ge(this,Jy)&&this._eventBus.dispatch("switchannotationeditormode",{source:this,mode:t})}updateParams(t,n){var r;if(ge(this,AN)){switch(t){case vc.CREATE:this.currentLayer.addNewEditor();return;case vc.HIGHLIGHT_DEFAULT_COLOR:(r=ge(this,UQ))==null||r.updateColor(n);break;case vc.HIGHLIGHT_SHOW_ALL:this._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:{type:"highlight",action:"toggle_visibility"}}}),(ge(this,VQ)||$t(this,VQ,new Map)).set(t,n),this.showAllEditors("highlight",n);break}for(const a of ge(this,Eh))a.updateParams(t,n);for(const a of ge(this,AN))a.updateDefaultParams(t,n)}}showAllEditors(t,n,r=!1){var i;for(const l of ge(this,ly).values())l.editorType===t&&l.show(n);(((i=ge(this,VQ))==null?void 0:i.get(vc.HIGHLIGHT_SHOW_ALL))??!0)!==n&&ss(this,Bi,iE).call(this,[[vc.HIGHLIGHT_SHOW_ALL,n]])}enableWaiting(t=!1){if(ge(this,$Q)!==t){$t(this,$Q,t);for(const n of ge(this,U0).values())t?n.disableClick():n.enableClick(),n.div.classList.toggle("waiting",t)}}getEditors(t){const n=[];for(const r of ge(this,ly).values())r.pageIndex===t&&n.push(r);return n}getEditor(t){return ge(this,ly).get(t)}addEditor(t){ge(this,ly).set(t.id,t)}removeEditor(t){var n;t.div.contains(document.activeElement)&&(ge(this,BS)&&clearTimeout(ge(this,BS)),$t(this,BS,setTimeout(()=>{this.focusMainContainer(),$t(this,BS,null)},0))),ge(this,ly).delete(t.id),this.unselect(t),(!t.annotationElementId||!ge(this,DD).has(t.annotationElementId))&&((n=ge(this,EC))==null||n.remove(t.id))}addDeletedAnnotationElement(t){ge(this,DD).add(t.annotationElementId),this.addChangedExistingAnnotation(t),t.deleted=!0}isDeletedAnnotationElement(t){return ge(this,DD).has(t)}removeDeletedAnnotationElement(t){ge(this,DD).delete(t.annotationElementId),this.removeChangedExistingAnnotation(t),t.deleted=!1}setActiveEditor(t){ge(this,ww)!==t&&($t(this,ww,t),t&&ss(this,Bi,iE).call(this,t.propertiesToUpdate))}updateUI(t){ge(this,Bi,F$t)===t&&ss(this,Bi,iE).call(this,t.propertiesToUpdate)}toggleSelected(t){if(ge(this,Eh).has(t)){ge(this,Eh).delete(t),t.unselect(),ss(this,Bi,K1).call(this,{hasSelectedEditor:this.hasSelection});return}ge(this,Eh).add(t),t.select(),ss(this,Bi,iE).call(this,t.propertiesToUpdate),ss(this,Bi,K1).call(this,{hasSelectedEditor:!0})}setSelected(t){for(const n of ge(this,Eh))n!==t&&n.unselect();ge(this,Eh).clear(),ge(this,Eh).add(t),t.select(),ss(this,Bi,iE).call(this,t.propertiesToUpdate),ss(this,Bi,K1).call(this,{hasSelectedEditor:!0})}isSelected(t){return ge(this,Eh).has(t)}get firstSelectedEditor(){return ge(this,Eh).values().next().value}unselect(t){t.unselect(),ge(this,Eh).delete(t),ss(this,Bi,K1).call(this,{hasSelectedEditor:this.hasSelection})}get hasSelection(){return ge(this,Eh).size!==0}get isEnterHandled(){return ge(this,Eh).size===1&&this.firstSelectedEditor.isEnterHandled}undo(){ge(this,CN).undo(),ss(this,Bi,K1).call(this,{hasSomethingToUndo:ge(this,CN).hasSomethingToUndo(),hasSomethingToRedo:!0,isEmpty:ss(this,Bi,$W).call(this)})}redo(){ge(this,CN).redo(),ss(this,Bi,K1).call(this,{hasSomethingToUndo:!0,hasSomethingToRedo:ge(this,CN).hasSomethingToRedo(),isEmpty:ss(this,Bi,$W).call(this)})}addCommands(t){ge(this,CN).add(t),ss(this,Bi,K1).call(this,{hasSomethingToUndo:!0,hasSomethingToRedo:!1,isEmpty:ss(this,Bi,$W).call(this)})}delete(){if(this.commitOrRemove(),!this.hasSelection)return;const t=[...ge(this,Eh)],n=()=>{for(const a of t)a.remove()},r=()=>{for(const a of t)ss(this,Bi,q$e).call(this,a)};this.addCommands({cmd:n,undo:r,mustExec:!0})}commitOrRemove(){var t;(t=ge(this,ww))==null||t.commitOrRemove()}hasSomethingToControl(){return ge(this,ww)||this.hasSelection}selectAll(){for(const t of ge(this,Eh))t.commit();ss(this,Bi,V$e).call(this,ge(this,ly).values())}unselectAll(){if(!(ge(this,ww)&&(ge(this,ww).commitOrRemove(),ge(this,Jy)!==Kc.NONE))&&this.hasSelection){for(const t of ge(this,Eh))t.unselect();ge(this,Eh).clear(),ss(this,Bi,K1).call(this,{hasSelectedEditor:!1})}}translateSelectedEditors(t,n,r=!1){if(r||this.commitOrRemove(),!this.hasSelection)return;ge(this,XE)[0]+=t,ge(this,XE)[1]+=n;const[a,i]=ge(this,XE),l=[...ge(this,Eh)],o=1e3;ge(this,US)&&clearTimeout(ge(this,US)),$t(this,US,setTimeout(()=>{$t(this,US,null),ge(this,XE)[0]=ge(this,XE)[1]=0,this.addCommands({cmd:()=>{for(const c of l)ge(this,ly).has(c.id)&&c.translateInPage(a,i)},undo:()=>{for(const c of l)ge(this,ly).has(c.id)&&c.translateInPage(-a,-i)},mustExec:!1})},o));for(const c of l)c.translateInPage(t,n)}setUpDragSession(){if(this.hasSelection){this.disableUserSelect(!0),$t(this,zS,new Map);for(const t of ge(this,Eh))ge(this,zS).set(t,{savedX:t.x,savedY:t.y,savedPageIndex:t.pageIndex,newX:0,newY:0,newPageIndex:-1})}}endDragSession(){if(!ge(this,zS))return!1;this.disableUserSelect(!1);const t=ge(this,zS);$t(this,zS,null);let n=!1;for(const[{x:a,y:i,pageIndex:l},o]of t)o.newX=a,o.newY=i,o.newPageIndex=l,n||(n=a!==o.savedX||i!==o.savedY||l!==o.savedPageIndex);if(!n)return!1;const r=(a,i,l,o)=>{if(ge(this,ly).has(a.id)){const c=ge(this,U0).get(o);c?a._setParentAndPosition(c,i,l):(a.pageIndex=o,a.x=i,a.y=l)}};return this.addCommands({cmd:()=>{for(const[a,{newX:i,newY:l,newPageIndex:o}]of t)r(a,i,l,o)},undo:()=>{for(const[a,{savedX:i,savedY:l,savedPageIndex:o}]of t)r(a,i,l,o)},mustExec:!0}),!0}dragSelectedEditors(t,n){if(ge(this,zS))for(const r of ge(this,zS).keys())r.drag(t,n)}rebuild(t){if(t.parent===null){const n=this.getLayer(t.pageIndex);n?(n.changeParent(t),n.addOrRebuild(t)):(this.addEditor(t),this.addToAnnotationStorage(t),t.rebuild())}else t.parent.addOrRebuild(t)}get isEditorHandlingKeyboard(){var t;return((t=this.getActive())==null?void 0:t.shouldGetKeyboardEvents())||ge(this,Eh).size===1&&this.firstSelectedEditor.shouldGetKeyboardEvents()}isActive(t){return ge(this,ww)===t}getActive(){return ge(this,ww)}getMode(){return ge(this,Jy)}get imageManager(){return nu(this,"imageManager",new O$e)}getSelectionBoxes(t){if(!t)return null;const n=document.getSelection();for(let d=0,u=n.rangeCount;d({x:(u-a)/l,y:1-(d+h-r)/i,width:m/l,height:h/i});break;case"180":o=(d,u,h,m)=>({x:1-(d+h-r)/i,y:1-(u+m-a)/l,width:h/i,height:m/l});break;case"270":o=(d,u,h,m)=>({x:1-(u+m-a)/l,y:(d-r)/i,width:m/l,height:h/i});break;default:o=(d,u,h,m)=>({x:(d-r)/i,y:(u-a)/l,width:h/i,height:m/l});break}const c=[];for(let d=0,u=n.rangeCount;d{m.type==="pointerup"&&m.button!==0||(d.abort(),c==null||c.toggleDrawing(!0),m.type==="pointerup"&&ss(this,Bi,BNe).call(this,"main_toolbar"))};window.addEventListener("pointerup",h,{signal:u}),window.addEventListener("blur",h,{signal:u})}},BNe=function(t=""){ge(this,Jy)===Kc.HIGHLIGHT?this.highlightSelection(t):ge(this,FQ)&&ss(this,Bi,E$t).call(this)},M$t=function(){document.addEventListener("selectionchange",ss(this,Bi,T$t).bind(this),{signal:this._signal})},P$t=function(){if(ge(this,WE))return;$t(this,WE,new AbortController);const t=this.combinedSignal(ge(this,WE));window.addEventListener("focus",this.focus.bind(this),{signal:t}),window.addEventListener("blur",this.blur.bind(this),{signal:t})},I$t=function(){var t;(t=ge(this,WE))==null||t.abort(),$t(this,WE,null)},B$e=function(){if(ge(this,ZE))return;$t(this,ZE,new AbortController);const t=this.combinedSignal(ge(this,ZE));window.addEventListener("keydown",this.keydown.bind(this),{signal:t}),window.addEventListener("keyup",this.keyup.bind(this),{signal:t})},L$t=function(){var t;(t=ge(this,ZE))==null||t.abort(),$t(this,ZE,null)},$$e=function(){if(ge(this,GE))return;$t(this,GE,new AbortController);const t=this.combinedSignal(ge(this,GE));document.addEventListener("copy",this.copy.bind(this),{signal:t}),document.addEventListener("cut",this.cut.bind(this),{signal:t}),document.addEventListener("paste",this.paste.bind(this),{signal:t})},U$e=function(){var t;(t=ge(this,GE))==null||t.abort(),$t(this,GE,null)},R$t=function(){const t=this._signal;document.addEventListener("dragover",this.dragOver.bind(this),{signal:t}),document.addEventListener("drop",this.drop.bind(this),{signal:t})},K1=function(t){Object.entries(t).some(([r,a])=>ge(this,HQ)[r]!==a)&&(this._eventBus.dispatch("annotationeditorstateschanged",{source:this,details:Object.assign(ge(this,HQ),t)}),ge(this,Jy)===Kc.HIGHLIGHT&&t.hasSelectedEditor===!1&&ss(this,Bi,iE).call(this,[[vc.HIGHLIGHT_FREE,!0]]))},iE=function(t){this._eventBus.dispatch("annotationeditorparamschanged",{source:this,details:t})},D$t=async function(){if(!ge(this,YE)){$t(this,YE,!0);const t=[];for(const n of ge(this,U0).values())t.push(n.enable());await Promise.all(t);for(const n of ge(this,ly).values())n.enable()}},O$t=function(){if(this.unselectAll(),ge(this,YE)){$t(this,YE,!1);for(const t of ge(this,U0).values())t.disable();for(const t of ge(this,ly).values())t.disable()}},q$e=function(t){const n=ge(this,U0).get(t.pageIndex);n?n.addOrRebuild(t):(this.addEditor(t),this.addToAnnotationStorage(t))},F$t=function(){let t=null;for(t of ge(this,Eh));return t},$W=function(){if(ge(this,ly).size===0)return!0;if(ge(this,ly).size===1)for(const t of ge(this,ly).values())return t.isEmpty();return!1},V$e=function(t){for(const n of ge(this,Eh))n.unselect();ge(this,Eh).clear();for(const n of t)n.isEmpty()||(ge(this,Eh).add(n),n.select());ss(this,Bi,K1).call(this,{hasSelectedEditor:this.hasSelection})},ur(Mz,"TRANSLATE_SMALL",1),ur(Mz,"TRANSLATE_BIG",10);let iF=Mz;var e0,qS,EN,p$,VS,jw,g$,HS,s_,PC,BD,GS,QE,ek,UW,$Ne;const Z1=class Z1{constructor(t){ds(this,ek);ds(this,e0,null);ds(this,qS,!1);ds(this,EN,null);ds(this,p$,null);ds(this,VS,null);ds(this,jw,null);ds(this,g$,!1);ds(this,HS,null);ds(this,s_,null);ds(this,PC,null);ds(this,BD,null);ds(this,GS,!1);$t(this,s_,t),$t(this,GS,t._uiManager.useNewAltTextFlow),ge(Z1,QE)||$t(Z1,QE,Object.freeze({added:"pdfjs-editor-new-alt-text-added-button","added-label":"pdfjs-editor-new-alt-text-added-button-label",missing:"pdfjs-editor-new-alt-text-missing-button","missing-label":"pdfjs-editor-new-alt-text-missing-button-label",review:"pdfjs-editor-new-alt-text-to-review-button","review-label":"pdfjs-editor-new-alt-text-to-review-button-label"}))}static initialize(t){Z1._l10n??(Z1._l10n=t)}async render(){const t=$t(this,EN,document.createElement("button"));t.className="altText",t.tabIndex="0";const n=$t(this,p$,document.createElement("span"));t.append(n),ge(this,GS)?(t.classList.add("new"),t.setAttribute("data-l10n-id",ge(Z1,QE).missing),n.setAttribute("data-l10n-id",ge(Z1,QE)["missing-label"])):(t.setAttribute("data-l10n-id","pdfjs-editor-alt-text-button"),n.setAttribute("data-l10n-id","pdfjs-editor-alt-text-button-label"));const r=ge(this,s_)._uiManager._signal;t.addEventListener("contextmenu",F2,{signal:r}),t.addEventListener("pointerdown",i=>i.stopPropagation(),{signal:r});const a=i=>{i.preventDefault(),ge(this,s_)._uiManager.editAltText(ge(this,s_)),ge(this,GS)&&ge(this,s_)._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_clicked",data:{label:ge(this,ek,UW)}})};return t.addEventListener("click",a,{capture:!0,signal:r}),t.addEventListener("keydown",i=>{i.target===t&&i.key==="Enter"&&($t(this,g$,!0),a(i))},{signal:r}),await ss(this,ek,$Ne).call(this),t}finish(){ge(this,EN)&&(ge(this,EN).focus({focusVisible:ge(this,g$)}),$t(this,g$,!1))}isEmpty(){return ge(this,GS)?ge(this,e0)===null:!ge(this,e0)&&!ge(this,qS)}hasData(){return ge(this,GS)?ge(this,e0)!==null||!!ge(this,PC):this.isEmpty()}get guessedText(){return ge(this,PC)}async setGuessedText(t){ge(this,e0)===null&&($t(this,PC,t),$t(this,BD,await Z1._l10n.get("pdfjs-editor-new-alt-text-generated-alt-text-with-disclaimer",{generatedAltText:t})),ss(this,ek,$Ne).call(this))}toggleAltTextBadge(t=!1){var n;if(!ge(this,GS)||ge(this,e0)){(n=ge(this,HS))==null||n.remove(),$t(this,HS,null);return}if(!ge(this,HS)){const r=$t(this,HS,document.createElement("div"));r.className="noAltTextBadge",ge(this,s_).div.append(r)}ge(this,HS).classList.toggle("hidden",!t)}serialize(t){let n=ge(this,e0);return!t&&ge(this,PC)===n&&(n=ge(this,BD)),{altText:n,decorative:ge(this,qS),guessedText:ge(this,PC),textWithDisclaimer:ge(this,BD)}}get data(){return{altText:ge(this,e0),decorative:ge(this,qS)}}set data({altText:t,decorative:n,guessedText:r,textWithDisclaimer:a,cancel:i=!1}){r&&($t(this,PC,r),$t(this,BD,a)),!(ge(this,e0)===t&&ge(this,qS)===n)&&(i||($t(this,e0,t),$t(this,qS,n)),ss(this,ek,$Ne).call(this))}toggle(t=!1){ge(this,EN)&&(!t&&ge(this,jw)&&(clearTimeout(ge(this,jw)),$t(this,jw,null)),ge(this,EN).disabled=!t)}shown(){ge(this,s_)._reportTelemetry({action:"pdfjs.image.alt_text.image_status_label_displayed",data:{label:ge(this,ek,UW)}})}destroy(){var t,n;(t=ge(this,EN))==null||t.remove(),$t(this,EN,null),$t(this,p$,null),$t(this,VS,null),(n=ge(this,HS))==null||n.remove(),$t(this,HS,null)}};e0=new WeakMap,qS=new WeakMap,EN=new WeakMap,p$=new WeakMap,VS=new WeakMap,jw=new WeakMap,g$=new WeakMap,HS=new WeakMap,s_=new WeakMap,PC=new WeakMap,BD=new WeakMap,GS=new WeakMap,QE=new WeakMap,ek=new WeakSet,UW=function(){return ge(this,e0)&&"added"||ge(this,e0)===null&&this.guessedText&&"review"||"missing"},$Ne=async function(){var a,i,l;const t=ge(this,EN);if(!t)return;if(ge(this,GS)){if(t.classList.toggle("done",!!ge(this,e0)),t.setAttribute("data-l10n-id",ge(Z1,QE)[ge(this,ek,UW)]),(a=ge(this,p$))==null||a.setAttribute("data-l10n-id",ge(Z1,QE)[`${ge(this,ek,UW)}-label`]),!ge(this,e0)){(i=ge(this,VS))==null||i.remove();return}}else{if(!ge(this,e0)&&!ge(this,qS)){t.classList.remove("done"),(l=ge(this,VS))==null||l.remove();return}t.classList.add("done"),t.setAttribute("data-l10n-id","pdfjs-editor-alt-text-edit-button")}let n=ge(this,VS);if(!n){$t(this,VS,n=document.createElement("span")),n.className="tooltip",n.setAttribute("role","tooltip"),n.id=`alt-text-tooltip-${ge(this,s_).id}`;const o=100,c=ge(this,s_)._uiManager._signal;c.addEventListener("abort",()=>{clearTimeout(ge(this,jw)),$t(this,jw,null)},{once:!0}),t.addEventListener("mouseenter",()=>{$t(this,jw,setTimeout(()=>{$t(this,jw,null),ge(this,VS).classList.add("show"),ge(this,s_)._reportTelemetry({action:"alt_text_tooltip"})},o))},{signal:c}),t.addEventListener("mouseleave",()=>{var d;ge(this,jw)&&(clearTimeout(ge(this,jw)),$t(this,jw,null)),(d=ge(this,VS))==null||d.classList.remove("show")},{signal:c})}ge(this,qS)?n.setAttribute("data-l10n-id","pdfjs-editor-alt-text-decorative-tooltip"):(n.removeAttribute("data-l10n-id"),n.textContent=ge(this,e0)),n.parentNode||t.append(n);const r=ge(this,s_).getImageForAltText();r==null||r.setAttribute("aria-describedby",n.id)},ds(Z1,QE,null),ur(Z1,"_l10n",null);let W4e=Z1;var $D,TN,jp,x$,UD,q0,qD,JE,WQ,VD,eT,KQ,HD,IC,WS,y$,v$,Kj,YQ,SCe,id,H$e,ZQ,G$e,W$e,z$t,B$t,K$e,Y$e,Z$e,$$t,X$e,U$t,q$t,V$t,Q$e,qW;const gh=class gh{constructor(t){ds(this,id);ds(this,$D,null);ds(this,TN,null);ds(this,jp,null);ds(this,x$,!1);ds(this,UD,!1);ds(this,q0,null);ds(this,qD,null);ds(this,JE,null);ds(this,WQ,"");ds(this,VD,!1);ds(this,eT,null);ds(this,KQ,!1);ds(this,HD,!1);ds(this,IC,!1);ds(this,WS,null);ds(this,y$,0);ds(this,v$,0);ds(this,Kj,null);ur(this,"_editToolbar",null);ur(this,"_initialOptions",Object.create(null));ur(this,"_initialData",null);ur(this,"_isVisible",!0);ur(this,"_uiManager",null);ur(this,"_focusEventsAllowed",!0);ds(this,YQ,!1);ds(this,SCe,gh._zIndex++);this.parent=t.parent,this.id=t.id,this.width=this.height=null,this.pageIndex=t.parent.pageIndex,this.name=t.name,this.div=null,this._uiManager=t.uiManager,this.annotationElementId=null,this._willKeepAspectRatio=!1,this._initialOptions.isCentered=t.isCentered,this._structTreeParentId=null;const{rotation:n,rawDims:{pageWidth:r,pageHeight:a,pageX:i,pageY:l}}=this.parent.viewport;this.rotation=n,this.pageRotation=(360+n-this._uiManager.viewParameters.rotation)%360,this.pageDimensions=[r,a],this.pageTranslation=[i,l];const[o,c]=this.parentDimensions;this.x=t.x/o,this.y=t.y/c,this.isAttachedToDOM=!1,this.deleted=!1}static get _resizerKeyboardManager(){const t=gh.prototype._resizeWithKeyboard,n=iF.TRANSLATE_SMALL,r=iF.TRANSLATE_BIG;return nu(this,"_resizerKeyboardManager",new yte([[["ArrowLeft","mac+ArrowLeft"],t,{args:[-n,0]}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],t,{args:[-r,0]}],[["ArrowRight","mac+ArrowRight"],t,{args:[n,0]}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],t,{args:[r,0]}],[["ArrowUp","mac+ArrowUp"],t,{args:[0,-n]}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],t,{args:[0,-r]}],[["ArrowDown","mac+ArrowDown"],t,{args:[0,n]}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],t,{args:[0,r]}],[["Escape","mac+Escape"],gh.prototype._stopResizingWithKeyboard]]))}get editorType(){return Object.getPrototypeOf(this).constructor._type}static get _defaultLineColor(){return nu(this,"_defaultLineColor",this._colorManager.getHexCode("CanvasText"))}static deleteAnnotationElement(t){const n=new TMn({id:t.parent.getNextId(),parent:t.parent,uiManager:t._uiManager});n.annotationElementId=t.annotationElementId,n.deleted=!0,n._uiManager.addToAnnotationStorage(n)}static initialize(t,n){if(gh._l10n??(gh._l10n=t),gh._l10nResizer||(gh._l10nResizer=Object.freeze({topLeft:"pdfjs-editor-resizer-top-left",topMiddle:"pdfjs-editor-resizer-top-middle",topRight:"pdfjs-editor-resizer-top-right",middleRight:"pdfjs-editor-resizer-middle-right",bottomRight:"pdfjs-editor-resizer-bottom-right",bottomMiddle:"pdfjs-editor-resizer-bottom-middle",bottomLeft:"pdfjs-editor-resizer-bottom-left",middleLeft:"pdfjs-editor-resizer-middle-left"})),gh._borderLineWidth!==-1)return;const r=getComputedStyle(document.documentElement);gh._borderLineWidth=parseFloat(r.getPropertyValue("--outline-width"))||0}static updateDefaultParams(t,n){}static get defaultPropertiesToUpdate(){return[]}static isHandlingMimeForPasting(t){return!1}static paste(t,n){wf("Not implemented")}get propertiesToUpdate(){return[]}get _isDraggable(){return ge(this,YQ)}set _isDraggable(t){var n;$t(this,YQ,t),(n=this.div)==null||n.classList.toggle("draggable",t)}get isEnterHandled(){return!0}center(){const[t,n]=this.pageDimensions;switch(this.parentRotation){case 90:this.x-=this.height*n/(t*2),this.y+=this.width*t/(n*2);break;case 180:this.x+=this.width/2,this.y+=this.height/2;break;case 270:this.x+=this.height*n/(t*2),this.y-=this.width*t/(n*2);break;default:this.x-=this.width/2,this.y-=this.height/2;break}this.fixAndSetPosition()}addCommands(t){this._uiManager.addCommands(t)}get currentLayer(){return this._uiManager.currentLayer}setInBackground(){this.div.style.zIndex=0}setInForeground(){this.div.style.zIndex=ge(this,SCe)}setParent(t){t!==null?(this.pageIndex=t.pageIndex,this.pageDimensions=t.pageDimensions):ss(this,id,qW).call(this),this.parent=t}focusin(t){this._focusEventsAllowed&&(ge(this,VD)?$t(this,VD,!1):this.parent.setSelected(this))}focusout(t){var r;if(!this._focusEventsAllowed||!this.isAttachedToDOM)return;const n=t.relatedTarget;n!=null&&n.closest(`#${this.id}`)||(t.preventDefault(),(r=this.parent)!=null&&r.isMultipleSelection||this.commitOrRemove())}commitOrRemove(){this.isEmpty()?this.remove():this.commit()}commit(){this.addToAnnotationStorage()}addToAnnotationStorage(){this._uiManager.addToAnnotationStorage(this)}setAt(t,n,r,a){const[i,l]=this.parentDimensions;[r,a]=this.screenToPageTranslation(r,a),this.x=(t+r)/i,this.y=(n+a)/l,this.fixAndSetPosition()}translate(t,n){ss(this,id,H$e).call(this,this.parentDimensions,t,n)}translateInPage(t,n){ge(this,eT)||$t(this,eT,[this.x,this.y]),ss(this,id,H$e).call(this,this.pageDimensions,t,n),this.div.scrollIntoView({block:"nearest"})}drag(t,n){ge(this,eT)||$t(this,eT,[this.x,this.y]);const[r,a]=this.parentDimensions;if(this.x+=t/r,this.y+=n/a,this.parent&&(this.x<0||this.x>1||this.y<0||this.y>1)){const{x:d,y:u}=this.div.getBoundingClientRect();this.parent.findNewParent(this,d,u)&&(this.x-=Math.floor(this.x),this.y-=Math.floor(this.y))}let{x:i,y:l}=this;const[o,c]=this.getBaseTranslation();i+=o,l+=c,this.div.style.left=`${(100*i).toFixed(2)}%`,this.div.style.top=`${(100*l).toFixed(2)}%`,this.div.scrollIntoView({block:"nearest"})}get _hasBeenMoved(){return!!ge(this,eT)&&(ge(this,eT)[0]!==this.x||ge(this,eT)[1]!==this.y)}getBaseTranslation(){const[t,n]=this.parentDimensions,{_borderLineWidth:r}=gh,a=r/t,i=r/n;switch(this.rotation){case 90:return[-a,i];case 180:return[a,i];case 270:return[a,-i];default:return[-a,-i]}}get _mustFixPosition(){return!0}fixAndSetPosition(t=this.rotation){const[n,r]=this.pageDimensions;let{x:a,y:i,width:l,height:o}=this;if(l*=n,o*=r,a*=n,i*=r,this._mustFixPosition)switch(t){case 0:a=Math.max(0,Math.min(n-l,a)),i=Math.max(0,Math.min(r-o,i));break;case 90:a=Math.max(0,Math.min(n-o,a)),i=Math.min(r,Math.max(l,i));break;case 180:a=Math.min(n,Math.max(l,a)),i=Math.min(r,Math.max(o,i));break;case 270:a=Math.min(n,Math.max(o,a)),i=Math.max(0,Math.min(r-l,i));break}this.x=a/=n,this.y=i/=r;const[c,d]=this.getBaseTranslation();a+=c,i+=d;const{style:u}=this.div;u.left=`${(100*a).toFixed(2)}%`,u.top=`${(100*i).toFixed(2)}%`,this.moveInDOM()}screenToPageTranslation(t,n){var r;return ss(r=gh,ZQ,G$e).call(r,t,n,this.parentRotation)}pageTranslationToScreen(t,n){var r;return ss(r=gh,ZQ,G$e).call(r,t,n,360-this.parentRotation)}get parentScale(){return this._uiManager.viewParameters.realScale}get parentRotation(){return(this._uiManager.viewParameters.rotation+this.pageRotation)%360}get parentDimensions(){const{parentScale:t,pageDimensions:[n,r]}=this;return[n*t,r*t]}setDims(t,n){const[r,a]=this.parentDimensions;this.div.style.width=`${(100*t/r).toFixed(2)}%`,ge(this,UD)||(this.div.style.height=`${(100*n/a).toFixed(2)}%`)}fixDims(){const{style:t}=this.div,{height:n,width:r}=t,a=r.endsWith("%"),i=!ge(this,UD)&&n.endsWith("%");if(a&&i)return;const[l,o]=this.parentDimensions;a||(t.width=`${(100*parseFloat(r)/l).toFixed(2)}%`),!ge(this,UD)&&!i&&(t.height=`${(100*parseFloat(n)/o).toFixed(2)}%`)}getInitialTranslation(){return[0,0]}altTextFinish(){var t;(t=ge(this,jp))==null||t.finish()}async addEditToolbar(){return this._editToolbar||ge(this,HD)?this._editToolbar:(this._editToolbar=new R$e(this),this.div.append(this._editToolbar.render()),ge(this,jp)&&await this._editToolbar.addAltText(ge(this,jp)),this._editToolbar)}removeEditToolbar(){var t;this._editToolbar&&(this._editToolbar.remove(),this._editToolbar=null,(t=ge(this,jp))==null||t.destroy())}addContainer(t){var r;const n=(r=this._editToolbar)==null?void 0:r.div;n?n.before(t):this.div.append(t)}getClientDimensions(){return this.div.getBoundingClientRect()}async addAltTextButton(){ge(this,jp)||(W4e.initialize(gh._l10n),$t(this,jp,new W4e(this)),ge(this,$D)&&(ge(this,jp).data=ge(this,$D),$t(this,$D,null)),await this.addEditToolbar())}get altTextData(){var t;return(t=ge(this,jp))==null?void 0:t.data}set altTextData(t){ge(this,jp)&&(ge(this,jp).data=t)}get guessedAltText(){var t;return(t=ge(this,jp))==null?void 0:t.guessedText}async setGuessedAltText(t){var n;await((n=ge(this,jp))==null?void 0:n.setGuessedText(t))}serializeAltText(t){var n;return(n=ge(this,jp))==null?void 0:n.serialize(t)}hasAltText(){return!!ge(this,jp)&&!ge(this,jp).isEmpty()}hasAltTextData(){var t;return((t=ge(this,jp))==null?void 0:t.hasData())??!1}render(){this.div=document.createElement("div"),this.div.setAttribute("data-editor-rotation",(360-this.rotation)%360),this.div.className=this.name,this.div.setAttribute("id",this.id),this.div.tabIndex=ge(this,x$)?-1:0,this._isVisible||this.div.classList.add("hidden"),this.setInForeground(),ss(this,id,X$e).call(this);const[t,n]=this.parentDimensions;this.parentRotation%180!==0&&(this.div.style.maxWidth=`${(100*n/t).toFixed(2)}%`,this.div.style.maxHeight=`${(100*t/n).toFixed(2)}%`);const[r,a]=this.getInitialTranslation();return this.translate(r,a),G4e(this,this.div,["pointerdown"]),this.div}pointerdown(t){const{isMac:n}=_b.platform;if(t.button!==0||t.ctrlKey&&n){t.preventDefault();return}if($t(this,VD,!0),this._isDraggable){ss(this,id,$$t).call(this,t);return}ss(this,id,Z$e).call(this,t)}get isSelected(){return this._uiManager.isSelected(this)}moveInDOM(){ge(this,WS)&&clearTimeout(ge(this,WS)),$t(this,WS,setTimeout(()=>{var t;$t(this,WS,null),(t=this.parent)==null||t.moveEditorInDOM(this)},0))}_setParentAndPosition(t,n,r){t.changeParent(this),this.x=n,this.y=r,this.fixAndSetPosition()}getRect(t,n,r=this.rotation){const a=this.parentScale,[i,l]=this.pageDimensions,[o,c]=this.pageTranslation,d=t/a,u=n/a,h=this.x*i,m=this.y*l,p=this.width*i,g=this.height*l;switch(r){case 0:return[h+d+o,l-m-u-g+c,h+d+p+o,l-m-u+c];case 90:return[h+u+o,l-m+d+c,h+u+g+o,l-m+d+p+c];case 180:return[h-d-p+o,l-m+u+c,h-d+o,l-m+u+g+c];case 270:return[h-u-g+o,l-m-d-p+c,h-u+o,l-m-d+c];default:throw new Error("Invalid rotation")}}getRectInCurrentCoords(t,n){const[r,a,i,l]=t,o=i-r,c=l-a;switch(this.rotation){case 0:return[r,n-l,o,c];case 90:return[r,n-a,c,o];case 180:return[i,n-a,o,c];case 270:return[i,n-l,c,o];default:throw new Error("Invalid rotation")}}onceAdded(){}isEmpty(){return!1}enableEditMode(){$t(this,HD,!0)}disableEditMode(){$t(this,HD,!1)}isInEditMode(){return ge(this,HD)}shouldGetKeyboardEvents(){return ge(this,IC)}needsToBeRebuilt(){return this.div&&!this.isAttachedToDOM}rebuild(){ss(this,id,X$e).call(this)}rotate(t){}serializeDeleted(){var t;return{id:this.annotationElementId,deleted:!0,pageIndex:this.pageIndex,popupRef:((t=this._initialData)==null?void 0:t.popupRef)||""}}serialize(t=!1,n=null){wf("An editor must be serializable")}static async deserialize(t,n,r){const a=new this.prototype.constructor({parent:n,id:n.getNextId(),uiManager:r});a.rotation=t.rotation,$t(a,$D,t.accessibilityData);const[i,l]=a.pageDimensions,[o,c,d,u]=a.getRectInCurrentCoords(t.rect,l);return a.x=o/i,a.y=c/l,a.width=d/i,a.height=u/l,a}get hasBeenModified(){return!!this.annotationElementId&&(this.deleted||this.serialize()!==null)}remove(){var t;if((t=ge(this,JE))==null||t.abort(),$t(this,JE,null),this.isEmpty()||this.commit(),this.parent?this.parent.remove(this):this._uiManager.removeEditor(this),ge(this,WS)&&(clearTimeout(ge(this,WS)),$t(this,WS,null)),ss(this,id,qW).call(this),this.removeEditToolbar(),ge(this,Kj)){for(const n of ge(this,Kj).values())clearTimeout(n);$t(this,Kj,null)}this.parent=null}get isResizable(){return!1}makeResizable(){this.isResizable&&(ss(this,id,z$t).call(this),ge(this,q0).classList.remove("hidden"),G4e(this,this.div,["keydown"]))}get toolbarPosition(){return null}keydown(t){if(!this.isResizable||t.target!==this.div||t.key!=="Enter")return;this._uiManager.setSelected(this),$t(this,qD,{savedX:this.x,savedY:this.y,savedWidth:this.width,savedHeight:this.height});const n=ge(this,q0).children;if(!ge(this,TN)){$t(this,TN,Array.from(n));const l=ss(this,id,U$t).bind(this),o=ss(this,id,q$t).bind(this),c=this._uiManager._signal;for(const d of ge(this,TN)){const u=d.getAttribute("data-resizer-name");d.setAttribute("role","spinbutton"),d.addEventListener("keydown",l,{signal:c}),d.addEventListener("blur",o,{signal:c}),d.addEventListener("focus",ss(this,id,V$t).bind(this,u),{signal:c}),d.setAttribute("data-l10n-id",gh._l10nResizer[u])}}const r=ge(this,TN)[0];let a=0;for(const l of n){if(l===r)break;a++}const i=(360-this.rotation+this.parentRotation)%360/90*(ge(this,TN).length/4);if(i!==a){if(ia)for(let o=0;o{var a,i;(a=this.div)!=null&&a.classList.contains("selectedEditor")&&((i=this._editToolbar)==null||i.show())});return}(n=this._editToolbar)==null||n.show(),(r=ge(this,jp))==null||r.toggleAltTextBadge(!1)}unselect(){var t,n,r,a,i;(t=ge(this,q0))==null||t.classList.add("hidden"),(n=this.div)==null||n.classList.remove("selectedEditor"),(r=this.div)!=null&&r.contains(document.activeElement)&&this._uiManager.currentLayer.div.focus({preventScroll:!0}),(a=this._editToolbar)==null||a.hide(),(i=ge(this,jp))==null||i.toggleAltTextBadge(!0)}updateParams(t,n){}disableEditing(){}enableEditing(){}enterInEditMode(){}getImageForAltText(){return null}get contentDiv(){return this.div}get isEditing(){return ge(this,KQ)}set isEditing(t){$t(this,KQ,t),this.parent&&(t?(this.parent.setSelected(this),this.parent.setActiveEditor(this)):this.parent.setActiveEditor(null))}setAspectRatio(t,n){$t(this,UD,!0);const r=t/n,{style:a}=this.div;a.aspectRatio=r,a.height="auto"}static get MIN_SIZE(){return 16}static canCreateNewEmptyEditor(){return!0}get telemetryInitialData(){return{action:"added"}}get telemetryFinalData(){return null}_reportTelemetry(t,n=!1){if(n){ge(this,Kj)||$t(this,Kj,new Map);const{action:r}=t;let a=ge(this,Kj).get(r);a&&clearTimeout(a),a=setTimeout(()=>{this._reportTelemetry(t),ge(this,Kj).delete(r),ge(this,Kj).size===0&&$t(this,Kj,null)},gh._telemetryTimeout),ge(this,Kj).set(r,a);return}t.type||(t.type=this.editorType),this._uiManager._eventBus.dispatch("reporttelemetry",{source:this,details:{type:"editing",data:t}})}show(t=this._isVisible){this.div.classList.toggle("hidden",!t),this._isVisible=t}enable(){this.div&&(this.div.tabIndex=0),$t(this,x$,!1)}disable(){this.div&&(this.div.tabIndex=-1),$t(this,x$,!0)}renderAnnotationElement(t){let n=t.container.querySelector(".annotationContent");if(!n)n=document.createElement("div"),n.classList.add("annotationContent",this.editorType),t.container.prepend(n);else if(n.nodeName==="CANVAS"){const r=n;n=document.createElement("div"),n.classList.add("annotationContent",this.editorType),r.before(n)}return n}resetAnnotationElement(t){const{firstChild:n}=t.container;(n==null?void 0:n.nodeName)==="DIV"&&n.classList.contains("annotationContent")&&n.remove()}};$D=new WeakMap,TN=new WeakMap,jp=new WeakMap,x$=new WeakMap,UD=new WeakMap,q0=new WeakMap,qD=new WeakMap,JE=new WeakMap,WQ=new WeakMap,VD=new WeakMap,eT=new WeakMap,KQ=new WeakMap,HD=new WeakMap,IC=new WeakMap,WS=new WeakMap,y$=new WeakMap,v$=new WeakMap,Kj=new WeakMap,YQ=new WeakMap,SCe=new WeakMap,id=new WeakSet,H$e=function([t,n],r,a){[r,a]=this.screenToPageTranslation(r,a),this.x+=r/t,this.y+=a/n,this.fixAndSetPosition()},ZQ=new WeakSet,G$e=function(t,n,r){switch(r){case 90:return[n,-t];case 180:return[-t,-n];case 270:return[-n,t];default:return[t,n]}},W$e=function(t){switch(t){case 90:{const[n,r]=this.pageDimensions;return[0,-n/r,r/n,0]}case 180:return[-1,0,0,-1];case 270:{const[n,r]=this.pageDimensions;return[0,n/r,-r/n,0]}default:return[1,0,0,1]}},z$t=function(){if(ge(this,q0))return;$t(this,q0,document.createElement("div")),ge(this,q0).classList.add("resizers");const t=this._willKeepAspectRatio?["topLeft","topRight","bottomRight","bottomLeft"]:["topLeft","topMiddle","topRight","middleRight","bottomRight","bottomMiddle","bottomLeft","middleLeft"],n=this._uiManager._signal;for(const r of t){const a=document.createElement("div");ge(this,q0).append(a),a.classList.add("resizer",r),a.setAttribute("data-resizer-name",r),a.addEventListener("pointerdown",ss(this,id,B$t).bind(this,r),{signal:n}),a.addEventListener("contextmenu",F2,{signal:n}),a.tabIndex=-1}this.div.prepend(ge(this,q0))},B$t=function(t,n){var g;n.preventDefault();const{isMac:r}=_b.platform;if(n.button!==0||n.ctrlKey&&r)return;(g=ge(this,jp))==null||g.toggle(!1);const a=this._isDraggable;this._isDraggable=!1;const i=new AbortController,l=this._uiManager.combinedSignal(i);this.parent.togglePointerEvents(!1),window.addEventListener("pointermove",ss(this,id,Y$e).bind(this,t),{passive:!0,capture:!0,signal:l}),window.addEventListener("contextmenu",F2,{signal:l});const o=this.x,c=this.y,d=this.width,u=this.height,h=this.parent.div.style.cursor,m=this.div.style.cursor;this.div.style.cursor=this.parent.div.style.cursor=window.getComputedStyle(n.target).cursor;const p=()=>{var x;i.abort(),this.parent.togglePointerEvents(!0),(x=ge(this,jp))==null||x.toggle(!0),this._isDraggable=a,this.parent.div.style.cursor=h,this.div.style.cursor=m,ss(this,id,K$e).call(this,o,c,d,u)};window.addEventListener("pointerup",p,{signal:l}),window.addEventListener("blur",p,{signal:l})},K$e=function(t,n,r,a){const i=this.x,l=this.y,o=this.width,c=this.height;i===t&&l===n&&o===r&&c===a||this.addCommands({cmd:()=>{this.width=o,this.height=c,this.x=i,this.y=l;const[d,u]=this.parentDimensions;this.setDims(d*o,u*c),this.fixAndSetPosition()},undo:()=>{this.width=r,this.height=a,this.x=t,this.y=n;const[d,u]=this.parentDimensions;this.setDims(d*r,u*a),this.fixAndSetPosition()},mustExec:!0})},Y$e=function(t,n){const[r,a]=this.parentDimensions,i=this.x,l=this.y,o=this.width,c=this.height,d=gh.MIN_SIZE/r,u=gh.MIN_SIZE/a,h=ee=>Math.round(ee*1e4)/1e4,m=ss(this,id,W$e).call(this,this.rotation),p=(ee,oe)=>[m[0]*ee+m[2]*oe,m[1]*ee+m[3]*oe],g=ss(this,id,W$e).call(this,360-this.rotation),x=(ee,oe)=>[g[0]*ee+g[2]*oe,g[1]*ee+g[3]*oe];let y,v,_=!1,j=!1;switch(t){case"topLeft":_=!0,y=(ee,oe)=>[0,0],v=(ee,oe)=>[ee,oe];break;case"topMiddle":y=(ee,oe)=>[ee/2,0],v=(ee,oe)=>[ee/2,oe];break;case"topRight":_=!0,y=(ee,oe)=>[ee,0],v=(ee,oe)=>[0,oe];break;case"middleRight":j=!0,y=(ee,oe)=>[ee,oe/2],v=(ee,oe)=>[0,oe/2];break;case"bottomRight":_=!0,y=(ee,oe)=>[ee,oe],v=(ee,oe)=>[0,0];break;case"bottomMiddle":y=(ee,oe)=>[ee/2,oe],v=(ee,oe)=>[ee/2,0];break;case"bottomLeft":_=!0,y=(ee,oe)=>[0,oe],v=(ee,oe)=>[ee,0];break;case"middleLeft":j=!0,y=(ee,oe)=>[0,oe/2],v=(ee,oe)=>[ee,oe/2];break}const C=y(o,c),A=v(o,c);let M=p(...A);const I=h(i+M[0]),P=h(l+M[1]);let R=1,O=1,[B,U]=this.screenToPageTranslation(n.movementX,n.movementY);if([B,U]=x(B/r,U/a),_){const ee=Math.hypot(o,c);R=O=Math.max(Math.min(Math.hypot(A[0]-C[0]-B,A[1]-C[1]-U)/ee,1/o,1/c),d/o,u/c)}else j?R=Math.max(d,Math.min(1,Math.abs(A[0]-C[0]-B)))/o:O=Math.max(u,Math.min(1,Math.abs(A[1]-C[1]-U)))/c;const G=h(o*R),H=h(c*O);M=p(...v(G,H));const Y=I-M[0],se=P-M[1];this.width=G,this.height=H,this.x=Y,this.y=se,this.setDims(r*G,a*H),this.fixAndSetPosition()},Z$e=function(t){const{isMac:n}=_b.platform;t.ctrlKey&&!n||t.shiftKey||t.metaKey&&n?this.parent.toggleSelected(this):this.parent.setSelected(this)},$$t=function(t){const{isSelected:n}=this;this._uiManager.setUpDragSession();const r=new AbortController,a=this._uiManager.combinedSignal(r);if(n){this.div.classList.add("moving"),$t(this,y$,t.clientX),$t(this,v$,t.clientY);const l=o=>{const{clientX:c,clientY:d}=o,[u,h]=this.screenToPageTranslation(c-ge(this,y$),d-ge(this,v$));$t(this,y$,c),$t(this,v$,d),this._uiManager.dragSelectedEditors(u,h)};window.addEventListener("pointermove",l,{passive:!0,capture:!0,signal:a})}const i=()=>{r.abort(),n&&this.div.classList.remove("moving"),$t(this,VD,!1),this._uiManager.endDragSession()||ss(this,id,Z$e).call(this,t)};window.addEventListener("pointerup",i,{signal:a}),window.addEventListener("blur",i,{signal:a})},X$e=function(){if(ge(this,JE)||!this.div)return;$t(this,JE,new AbortController);const t=this._uiManager.combinedSignal(ge(this,JE));this.div.addEventListener("focusin",this.focusin.bind(this),{signal:t}),this.div.addEventListener("focusout",this.focusout.bind(this),{signal:t})},U$t=function(t){gh._resizerKeyboardManager.exec(this,t)},q$t=function(t){var n;ge(this,IC)&&((n=t.relatedTarget)==null?void 0:n.parentNode)!==ge(this,q0)&&ss(this,id,qW).call(this)},V$t=function(t){$t(this,WQ,ge(this,IC)?t:"")},Q$e=function(t){if(ge(this,TN))for(const n of ge(this,TN))n.tabIndex=t},qW=function(){if($t(this,IC,!1),ss(this,id,Q$e).call(this,-1),ge(this,qD)){const{savedX:t,savedY:n,savedWidth:r,savedHeight:a}=ge(this,qD);ss(this,id,K$e).call(this,t,n,r,a),$t(this,qD,null)}},ds(gh,ZQ),ur(gh,"_l10n",null),ur(gh,"_l10nResizer",null),ur(gh,"_borderLineWidth",-1),ur(gh,"_colorManager",new F$e),ur(gh,"_zIndex",1),ur(gh,"_telemetryTimeout",1e3);let Ph=gh;class TMn extends Ph{constructor(t){super(t),this.annotationElementId=t.annotationElementId,this.deleted=!0}serialize(){return this.serializeDeleted()}}const _1t=3285377520,Bj=4294901760,fS=65535;class H$t{constructor(t){this.h1=t?t&4294967295:_1t,this.h2=t?t&4294967295:_1t}update(t){let n,r;if(typeof t=="string"){n=new Uint8Array(t.length*2),r=0;for(let x=0,y=t.length;x>>8,n[r++]=v&255)}}else if(ArrayBuffer.isView(t))n=t.slice(),r=n.byteLength;else throw new Error("Invalid data format, must be a string or TypedArray.");const a=r>>2,i=r-a*4,l=new Uint32Array(n.buffer,0,a);let o=0,c=0,d=this.h1,u=this.h2;const h=3432918353,m=461845907,p=h&fS,g=m&fS;for(let x=0;x>>17,o=o*m&Bj|o*g&fS,d^=o,d=d<<13|d>>>19,d=d*5+3864292196):(c=l[x],c=c*h&Bj|c*p&fS,c=c<<15|c>>>17,c=c*m&Bj|c*g&fS,u^=c,u=u<<13|u>>>19,u=u*5+3864292196);switch(o=0,i){case 3:o^=n[a*4+2]<<16;case 2:o^=n[a*4+1]<<8;case 1:o^=n[a*4],o=o*h&Bj|o*p&fS,o=o<<15|o>>>17,o=o*m&Bj|o*g&fS,a&1?d^=o:u^=o}this.h1=d,this.h2=u}hexdigest(){let t=this.h1,n=this.h2;return t^=n>>>1,t=t*3981806797&Bj|t*36045&fS,n=n*4283543511&Bj|((n<<16|t>>>16)*2950163797&Bj)>>>16,t^=n>>>1,t=t*444984403&Bj|t*60499&fS,n=n*3301882366&Bj|((n<<16|t>>>16)*3120437893&Bj)>>>16,t^=n>>>1,(t>>>0).toString(16).padStart(8,"0")+(n>>>0).toString(16).padStart(8,"0")}}const J$e=Object.freeze({map:null,hash:"",transfer:void 0});var GD,WD,t0,CCe,G$t;class eQe{constructor(){ds(this,CCe);ds(this,GD,!1);ds(this,WD,null);ds(this,t0,new Map);this.onSetModified=null,this.onResetModified=null,this.onAnnotationEditor=null}getValue(t,n){const r=ge(this,t0).get(t);return r===void 0?n:Object.assign(n,r)}getRawValue(t){return ge(this,t0).get(t)}remove(t){if(ge(this,t0).delete(t),ge(this,t0).size===0&&this.resetModified(),typeof this.onAnnotationEditor=="function"){for(const n of ge(this,t0).values())if(n instanceof Ph)return;this.onAnnotationEditor(null)}}setValue(t,n){const r=ge(this,t0).get(t);let a=!1;if(r!==void 0)for(const[i,l]of Object.entries(n))r[i]!==l&&(a=!0,r[i]=l);else a=!0,ge(this,t0).set(t,n);a&&ss(this,CCe,G$t).call(this),n instanceof Ph&&typeof this.onAnnotationEditor=="function"&&this.onAnnotationEditor(n.constructor._type)}has(t){return ge(this,t0).has(t)}getAll(){return ge(this,t0).size>0?KXe(ge(this,t0)):null}setAll(t){for(const[n,r]of Object.entries(t))this.setValue(n,r)}get size(){return ge(this,t0).size}resetModified(){ge(this,GD)&&($t(this,GD,!1),typeof this.onResetModified=="function"&&this.onResetModified())}get print(){return new W$t(this)}get serializable(){if(ge(this,t0).size===0)return J$e;const t=new Map,n=new H$t,r=[],a=Object.create(null);let i=!1;for(const[l,o]of ge(this,t0)){const c=o instanceof Ph?o.serialize(!1,a):o;c&&(t.set(l,c),n.update(`${l}:${JSON.stringify(c)}`),i||(i=!!c.bitmap))}if(i)for(const l of t.values())l.bitmap&&r.push(l.bitmap);return t.size>0?{map:t,hash:n.hexdigest(),transfer:r}:J$e}get editorStats(){let t=null;const n=new Map;for(const r of ge(this,t0).values()){if(!(r instanceof Ph))continue;const a=r.telemetryFinalData;if(!a)continue;const{type:i}=a;n.has(i)||n.set(i,Object.getPrototypeOf(r).constructor),t||(t=Object.create(null));const l=t[i]||(t[i]=new Map);for(const[o,c]of Object.entries(a)){if(o==="type")continue;let d=l.get(o);d||(d=new Map,l.set(o,d));const u=d.get(c)??0;d.set(c,u+1)}}for(const[r,a]of n)t[r]=a.computeTelemetryFinalData(t[r]);return t}resetModifiedIds(){$t(this,WD,null)}get modifiedIds(){if(ge(this,WD))return ge(this,WD);const t=[];for(const n of ge(this,t0).values())!(n instanceof Ph)||!n.annotationElementId||!n.serialize()||t.push(n.annotationElementId);return $t(this,WD,{ids:new Set(t),hash:t.join(",")})}}GD=new WeakMap,WD=new WeakMap,t0=new WeakMap,CCe=new WeakSet,G$t=function(){ge(this,GD)||($t(this,GD,!0),typeof this.onSetModified=="function"&&this.onSetModified())};var XQ;class W$t extends eQe{constructor(n){super();ds(this,XQ);const{map:r,hash:a,transfer:i}=n.serializable,l=structuredClone(r,i?{transfer:i}:null);$t(this,XQ,{map:l,hash:a,transfer:i})}get print(){wf("Should not call PrintAnnotationStorage.print")}get serializable(){return ge(this,XQ)}get modifiedIds(){return nu(this,"modifiedIds",{ids:new Set,hash:""})}}XQ=new WeakMap;var b$;class MMn{constructor({ownerDocument:t=globalThis.document,styleElement:n=null}){ds(this,b$,new Set);this._document=t,this.nativeFontFaces=new Set,this.styleElement=null,this.loadingRequests=[],this.loadTestFontId=0}addNativeFontFace(t){this.nativeFontFaces.add(t),this._document.fonts.add(t)}removeNativeFontFace(t){this.nativeFontFaces.delete(t),this._document.fonts.delete(t)}insertRule(t){this.styleElement||(this.styleElement=this._document.createElement("style"),this._document.documentElement.getElementsByTagName("head")[0].append(this.styleElement));const n=this.styleElement.sheet;n.insertRule(t,n.cssRules.length)}clear(){for(const t of this.nativeFontFaces)this._document.fonts.delete(t);this.nativeFontFaces.clear(),ge(this,b$).clear(),this.styleElement&&(this.styleElement.remove(),this.styleElement=null)}async loadSystemFont({systemFontInfo:t,_inspectFont:n}){if(!(!t||ge(this,b$).has(t.loadedName))){if(yy(!this.disableFontFace,"loadSystemFont shouldn't be called when `disableFontFace` is set."),this.isFontLoadingAPISupported){const{loadedName:r,src:a,style:i}=t,l=new FontFace(r,a,i);this.addNativeFontFace(l);try{await l.load(),ge(this,b$).add(r),n==null||n(t)}catch{md(`Cannot load system font: ${t.baseFontName}, installing it could help to improve PDF rendering.`),this.removeNativeFontFace(l)}return}wf("Not implemented: loadSystemFont without the Font Loading API.")}}async bind(t){if(t.attached||t.missingFile&&!t.systemFontInfo)return;if(t.attached=!0,t.systemFontInfo){await this.loadSystemFont(t);return}if(this.isFontLoadingAPISupported){const r=t.createNativeFontFace();if(r){this.addNativeFontFace(r);try{await r.loaded}catch(a){throw md(`Failed to load font '${r.family}': '${a}'.`),t.disableFontFace=!0,a}}return}const n=t.createFontFaceRule();if(n){if(this.insertRule(n),this.isSyncFontLoadingSupported)return;await new Promise(r=>{const a=this._queueLoadingCallback(r);this._prepareFontLoadEvent(t,a)})}}get isFontLoadingAPISupported(){var n;const t=!!((n=this._document)!=null&&n.fonts);return nu(this,"isFontLoadingAPISupported",t)}get isSyncFontLoadingSupported(){let t=!1;return(c1||typeof navigator<"u"&&typeof(navigator==null?void 0:navigator.userAgent)=="string"&&/Mozilla\/5.0.*?rv:\d+.*? Gecko/.test(navigator.userAgent))&&(t=!0),nu(this,"isSyncFontLoadingSupported",t)}_queueLoadingCallback(t){function n(){for(yy(!a.done,"completeRequest() cannot be called twice."),a.done=!0;r.length>0&&r[0].done;){const i=r.shift();setTimeout(i.callback,0)}}const{loadingRequests:r}=this,a={done:!1,complete:n,callback:t};return r.push(a),a}get _loadTestFont(){const t=atob("T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQAABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwAAAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbmFtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAAAADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6AABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAAMQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAAAAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAAAAEAAQAAAAEAAAAAAAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUAAQAAAAEAAAAAAAYAAQAAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgABAAMAAQQJAAMAAgABAAMAAQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABYAAAAAAAAAwAAAAMAAAAcAAEAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAAAC7////TAAEAAAAAAAABBgAAAQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAAAAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgcA/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQAAAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAgABAAAAAAAAAAAD6AAAAAAAAA==");return nu(this,"_loadTestFont",t)}_prepareFontLoadEvent(t,n){function r(C,A){return C.charCodeAt(A)<<24|C.charCodeAt(A+1)<<16|C.charCodeAt(A+2)<<8|C.charCodeAt(A+3)&255}function a(C,A,M,I){const P=C.substring(0,A),R=C.substring(A+M);return P+I+R}let i,l;const o=this._document.createElement("canvas");o.width=1,o.height=1;const c=o.getContext("2d");let d=0;function u(C,A){if(++d>30){md("Load test font never loaded."),A();return}if(c.font="30px "+C,c.fillText(".",0,20),c.getImageData(0,0,1,1).data[3]>0){A();return}setTimeout(u.bind(null,C,A))}const h=`lt${Date.now()}${this.loadTestFontId++}`;let m=this._loadTestFont;m=a(m,976,h.length,h);const g=16,x=1482184792;let y=r(m,g);for(i=0,l=h.length-3;i{j.remove(),n.complete()})}}b$=new WeakMap;class PMn{constructor(t,{disableFontFace:n=!1,inspectFont:r=null}){this.compiledGlyphs=Object.create(null);for(const a in t)this[a]=t[a];this.disableFontFace=n===!0,this._inspectFont=r}createNativeFontFace(){var n;if(!this.data||this.disableFontFace)return null;let t;if(!this.cssFontInfo)t=new FontFace(this.loadedName,this.data,{});else{const r={weight:this.cssFontInfo.fontWeight};this.cssFontInfo.italicAngle&&(r.style=`oblique ${this.cssFontInfo.italicAngle}deg`),t=new FontFace(this.cssFontInfo.fontFamily,this.data,r)}return(n=this._inspectFont)==null||n.call(this,this),t}createFontFaceRule(){var r;if(!this.data||this.disableFontFace)return null;const t=`url(data:${this.mimetype};base64,${_Mn(this.data)});`;let n;if(!this.cssFontInfo)n=`@font-face {font-family:"${this.loadedName}";src:${t}}`;else{let a=`font-weight: ${this.cssFontInfo.fontWeight};`;this.cssFontInfo.italicAngle&&(a+=`font-style: oblique ${this.cssFontInfo.italicAngle}deg;`),n=`@font-face {font-family:"${this.cssFontInfo.fontFamily}";${a}src:${t}}`}return(r=this._inspectFont)==null||r.call(this,this,t),n}getPathGenerator(t,n){if(this.compiledGlyphs[n]!==void 0)return this.compiledGlyphs[n];let r;try{r=t.get(this.loadedName+"_path_"+n)}catch(i){md(`getPathGenerator - ignoring character: "${i}".`)}if(!Array.isArray(r)||r.length===0)return this.compiledGlyphs[n]=function(i,l){};const a=[];for(let i=0,l=r.length;ip.bezierCurveTo(o,c,d,u,h,m)),i+=6}break;case eC.MOVE_TO:{const[o,c]=r.slice(i,i+2);a.push(d=>d.moveTo(o,c)),i+=2}break;case eC.LINE_TO:{const[o,c]=r.slice(i,i+2);a.push(d=>d.lineTo(o,c)),i+=2}break;case eC.QUADRATIC_CURVE_TO:{const[o,c,d,u]=r.slice(i,i+4);a.push(h=>h.quadraticCurveTo(o,c,d,u)),i+=4}break;case eC.RESTORE:a.push(o=>o.restore());break;case eC.SAVE:a.push(o=>o.save());break;case eC.SCALE:yy(a.length===2,"Scale command is only valid at the third position.");break;case eC.TRANSFORM:{const[o,c,d,u,h,m]=r.slice(i,i+6);a.push(p=>p.transform(o,c,d,u,h,m)),i+=6}break;case eC.TRANSLATE:{const[o,c]=r.slice(i,i+2);a.push(d=>d.translate(o,c)),i+=2}break}return this.compiledGlyphs[n]=function(l,o){a[0](l),a[1](l),l.scale(o,-o);for(let c=2,d=a.length;c({cMapData:r,isCompressed:this.isCompressed})).catch(r=>{throw new Error(`Unable to load ${this.isCompressed?"binary ":""}CMap at: ${n}`)})}async _fetch(t){wf("Abstract method `_fetch` called.")}}class Z$t extends Y$t{async _fetch(t){const n=await FTe(t,this.isCompressed?"arraybuffer":"text");return n instanceof ArrayBuffer?new Uint8Array(n):OTe(n)}}class X$t{addFilter(t){return"none"}addHCMFilter(t,n){return"none"}addAlphaFilter(t){return"none"}addLuminosityFilter(t){return"none"}addHighlightHCMFilter(t,n,r,a,i){return"none"}destroy(t=!1){}}var KD,YD,KS,LC,Zv,ACe,ZD,no,Wv,U9,q9,UNe,V9,Q$t,eUe,H9,VW,HW,tUe,GW;class LMn extends X$t{constructor({docId:n,ownerDocument:r=globalThis.document}){super();ds(this,no);ds(this,KD);ds(this,YD);ds(this,KS);ds(this,LC);ds(this,Zv);ds(this,ACe);ds(this,ZD,0);$t(this,LC,n),$t(this,Zv,r)}addFilter(n){if(!n)return"none";let r=ge(this,no,Wv).get(n);if(r)return r;const[a,i,l]=ss(this,no,UNe).call(this,n),o=n.length===1?a:`${a}${i}${l}`;if(r=ge(this,no,Wv).get(o),r)return ge(this,no,Wv).set(n,r),r;const c=`g_${ge(this,LC)}_transfer_map_${Hy(this,ZD)._++}`,d=ss(this,no,V9).call(this,c);ge(this,no,Wv).set(n,d),ge(this,no,Wv).set(o,d);const u=ss(this,no,H9).call(this,c);return ss(this,no,HW).call(this,a,i,l,u),d}addHCMFilter(n,r){var g;const a=`${n}-${r}`,i="base";let l=ge(this,no,U9).get(i);if((l==null?void 0:l.key)===a||(l?((g=l.filter)==null||g.remove(),l.key=a,l.url="none",l.filter=null):(l={key:a,url:"none",filter:null},ge(this,no,U9).set(i,l)),!n||!r))return l.url;const o=ss(this,no,GW).call(this,n);n=Ko.makeHexColor(...o);const c=ss(this,no,GW).call(this,r);if(r=Ko.makeHexColor(...c),ge(this,no,q9).style.color="",n==="#000000"&&r==="#ffffff"||n===r)return l.url;const d=new Array(256);for(let x=0;x<=255;x++){const y=x/255;d[x]=y<=.03928?y/12.92:((y+.055)/1.055)**2.4}const u=d.join(","),h=`g_${ge(this,LC)}_hcm_filter`,m=l.filter=ss(this,no,H9).call(this,h);ss(this,no,HW).call(this,u,u,u,m),ss(this,no,eUe).call(this,m);const p=(x,y)=>{const v=o[x]/255,_=c[x]/255,j=new Array(y+1);for(let C=0;C<=y;C++)j[C]=v+C/y*(_-v);return j.join(",")};return ss(this,no,HW).call(this,p(0,5),p(1,5),p(2,5),m),l.url=ss(this,no,V9).call(this,h),l.url}addAlphaFilter(n){let r=ge(this,no,Wv).get(n);if(r)return r;const[a]=ss(this,no,UNe).call(this,[n]),i=`alpha_${a}`;if(r=ge(this,no,Wv).get(i),r)return ge(this,no,Wv).set(n,r),r;const l=`g_${ge(this,LC)}_alpha_map_${Hy(this,ZD)._++}`,o=ss(this,no,V9).call(this,l);ge(this,no,Wv).set(n,o),ge(this,no,Wv).set(i,o);const c=ss(this,no,H9).call(this,l);return ss(this,no,tUe).call(this,a,c),o}addLuminosityFilter(n){let r=ge(this,no,Wv).get(n||"luminosity");if(r)return r;let a,i;if(n?([a]=ss(this,no,UNe).call(this,[n]),i=`luminosity_${a}`):i="luminosity",r=ge(this,no,Wv).get(i),r)return ge(this,no,Wv).set(n,r),r;const l=`g_${ge(this,LC)}_luminosity_map_${Hy(this,ZD)._++}`,o=ss(this,no,V9).call(this,l);ge(this,no,Wv).set(n,o),ge(this,no,Wv).set(i,o);const c=ss(this,no,H9).call(this,l);return ss(this,no,Q$t).call(this,c),n&&ss(this,no,tUe).call(this,a,c),o}addHighlightHCMFilter(n,r,a,i,l){var _;const o=`${r}-${a}-${i}-${l}`;let c=ge(this,no,U9).get(n);if((c==null?void 0:c.key)===o||(c?((_=c.filter)==null||_.remove(),c.key=o,c.url="none",c.filter=null):(c={key:o,url:"none",filter:null},ge(this,no,U9).set(n,c)),!r||!a))return c.url;const[d,u]=[r,a].map(ss(this,no,GW).bind(this));let h=Math.round(.2126*d[0]+.7152*d[1]+.0722*d[2]),m=Math.round(.2126*u[0]+.7152*u[1]+.0722*u[2]),[p,g]=[i,l].map(ss(this,no,GW).bind(this));m{const M=new Array(256),I=(m-h)/A,P=j/255,R=(C-j)/(255*A);let O=0;for(let B=0;B<=A;B++){const U=Math.round(h+B*I),G=P+B*R;for(let H=O;H<=U;H++)M[H]=G;O=U+1}for(let B=O;B<256;B++)M[B]=M[O-1];return M.join(",")},y=`g_${ge(this,LC)}_hcm_${n}_filter`,v=c.filter=ss(this,no,H9).call(this,y);return ss(this,no,eUe).call(this,v),ss(this,no,HW).call(this,x(p[0],g[0],5),x(p[1],g[1],5),x(p[2],g[2],5),v),c.url=ss(this,no,V9).call(this,y),c.url}destroy(n=!1){n&&ge(this,no,U9).size!==0||(ge(this,KS)&&(ge(this,KS).parentNode.parentNode.remove(),$t(this,KS,null)),ge(this,YD)&&(ge(this,YD).clear(),$t(this,YD,null)),$t(this,ZD,0))}}KD=new WeakMap,YD=new WeakMap,KS=new WeakMap,LC=new WeakMap,Zv=new WeakMap,ACe=new WeakMap,ZD=new WeakMap,no=new WeakSet,Wv=function(){return ge(this,YD)||$t(this,YD,new Map)},U9=function(){return ge(this,ACe)||$t(this,ACe,new Map)},q9=function(){if(!ge(this,KS)){const n=ge(this,Zv).createElement("div"),{style:r}=n;r.visibility="hidden",r.contain="strict",r.width=r.height=0,r.position="absolute",r.top=r.left=0,r.zIndex=-1;const a=ge(this,Zv).createElementNS(uC,"svg");a.setAttribute("width",0),a.setAttribute("height",0),$t(this,KS,ge(this,Zv).createElementNS(uC,"defs")),n.append(a),a.append(ge(this,KS)),ge(this,Zv).body.append(n)}return ge(this,KS)},UNe=function(n){if(n.length===1){const d=n[0],u=new Array(256);for(let m=0;m<256;m++)u[m]=d[m]/255;const h=u.join(",");return[h,h,h]}const[r,a,i]=n,l=new Array(256),o=new Array(256),c=new Array(256);for(let d=0;d<256;d++)l[d]=r[d]/255,o[d]=a[d]/255,c[d]=i[d]/255;return[l.join(","),o.join(","),c.join(",")]},V9=function(n){if(ge(this,KD)===void 0){$t(this,KD,"");const r=ge(this,Zv).URL;r!==ge(this,Zv).baseURI&&(zTe(r)?md('#createUrl: ignore "data:"-URL for performance reasons.'):$t(this,KD,r.split("#",1)[0]))}return`url(${ge(this,KD)}#${n})`},Q$t=function(n){const r=ge(this,Zv).createElementNS(uC,"feColorMatrix");r.setAttribute("type","matrix"),r.setAttribute("values","0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0.3 0.59 0.11 0 0"),n.append(r)},eUe=function(n){const r=ge(this,Zv).createElementNS(uC,"feColorMatrix");r.setAttribute("type","matrix"),r.setAttribute("values","0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0.2126 0.7152 0.0722 0 0 0 0 0 1 0"),n.append(r)},H9=function(n){const r=ge(this,Zv).createElementNS(uC,"filter");return r.setAttribute("color-interpolation-filters","sRGB"),r.setAttribute("id",n),ge(this,no,q9).append(r),r},VW=function(n,r,a){const i=ge(this,Zv).createElementNS(uC,r);i.setAttribute("type","discrete"),i.setAttribute("tableValues",a),n.append(i)},HW=function(n,r,a,i){const l=ge(this,Zv).createElementNS(uC,"feComponentTransfer");i.append(l),ss(this,no,VW).call(this,l,"feFuncR",n),ss(this,no,VW).call(this,l,"feFuncG",r),ss(this,no,VW).call(this,l,"feFuncB",a)},tUe=function(n,r){const a=ge(this,Zv).createElementNS(uC,"feComponentTransfer");r.append(a),ss(this,no,VW).call(this,a,"feFuncA",n)},GW=function(n){return ge(this,no,q9).style.color=n,JXe(getComputedStyle(ge(this,no,q9)).getPropertyValue("color"))};class J$t{constructor({baseUrl:t=null}){this.baseUrl=t}async fetch({filename:t}){if(!this.baseUrl)throw new Error("Ensure that the `standardFontDataUrl` API parameter is provided.");if(!t)throw new Error("Font filename must be specified.");const n=`${this.baseUrl}${t}`;return this._fetch(n).catch(r=>{throw new Error(`Unable to load font data at: ${n}`)})}async _fetch(t){wf("Abstract method `_fetch` called.")}}class eUt extends J$t{async _fetch(t){const n=await FTe(t,"arraybuffer");return new Uint8Array(n)}}if(c1){var sUe=Promise.withResolvers(),iZ=null;(async()=>{const t=await Ai(()=>import("./__vite-browser-external-BIHI7g3E.js"),[]),n=await Ai(()=>import("./__vite-browser-external-BIHI7g3E.js"),[]),r=await Ai(()=>import("./__vite-browser-external-BIHI7g3E.js"),[]),a=await Ai(()=>import("./__vite-browser-external-BIHI7g3E.js"),[]);let i,l;return new Map(Object.entries({fs:t,http:n,https:r,url:a,canvas:i,path2d:l}))})().then(t=>{iZ=t,sUe.resolve()},t=>{md(`loadPackages: ${t}`),iZ=new Map,sUe.resolve()})}class FM{static get promise(){return sUe.promise}static get(t){return iZ==null?void 0:iZ.get(t)}}async function tUt(s){const n=await FM.get("fs").promises.readFile(s);return new Uint8Array(n)}class RMn extends X$t{}class DMn extends K$t{_createCanvas(t,n){return FM.get("canvas").createCanvas(t,n)}}class OMn extends Y$t{async _fetch(t){return tUt(t)}}class FMn extends J$t{async _fetch(t){return tUt(t)}}const sb={FILL:"Fill",STROKE:"Stroke",SHADING:"Shading"};function nUe(s,t){if(!t)return;const n=t[2]-t[0],r=t[3]-t[1],a=new Path2D;a.rect(t[0],t[1],n,r),s.clip(a)}class tQe{getPattern(){wf("Abstract method `getPattern` called.")}}class zMn extends tQe{constructor(t){super(),this._type=t[1],this._bbox=t[2],this._colorStops=t[3],this._p0=t[4],this._p1=t[5],this._r0=t[6],this._r1=t[7],this.matrix=null}_createGradient(t){let n;this._type==="axial"?n=t.createLinearGradient(this._p0[0],this._p0[1],this._p1[0],this._p1[1]):this._type==="radial"&&(n=t.createRadialGradient(this._p0[0],this._p0[1],this._r0,this._p1[0],this._p1[1],this._r1));for(const r of this._colorStops)n.addColorStop(r[0],r[1]);return n}getPattern(t,n,r,a){let i;if(a===sb.STROKE||a===sb.FILL){const l=n.current.getClippedPathBoundingBox(a,kp(t))||[0,0,0,0],o=Math.ceil(l[2]-l[0])||1,c=Math.ceil(l[3]-l[1])||1,d=n.cachedCanvases.getCanvas("pattern",o,c),u=d.context;u.clearRect(0,0,u.canvas.width,u.canvas.height),u.beginPath(),u.rect(0,0,u.canvas.width,u.canvas.height),u.translate(-l[0],-l[1]),r=Ko.transform(r,[1,0,0,1,l[0],l[1]]),u.transform(...n.baseTransform),this.matrix&&u.transform(...this.matrix),nUe(u,this._bbox),u.fillStyle=this._createGradient(u),u.fill(),i=t.createPattern(d.canvas,"no-repeat");const h=new DOMMatrix(r);i.setTransform(h)}else nUe(t,this._bbox),i=this._createGradient(t);return i}}function FDe(s,t,n,r,a,i,l,o){const c=t.coords,d=t.colors,u=s.data,h=s.width*4;let m;c[n+1]>c[r+1]&&(m=n,n=r,r=m,m=i,i=l,l=m),c[r+1]>c[a+1]&&(m=r,r=a,a=m,m=l,l=o,o=m),c[n+1]>c[r+1]&&(m=n,n=r,r=m,m=i,i=l,l=m);const p=(c[n]+t.offsetX)*t.scaleX,g=(c[n+1]+t.offsetY)*t.scaleY,x=(c[r]+t.offsetX)*t.scaleX,y=(c[r+1]+t.offsetY)*t.scaleY,v=(c[a]+t.offsetX)*t.scaleX,_=(c[a+1]+t.offsetY)*t.scaleY;if(g>=_)return;const j=d[i],C=d[i+1],A=d[i+2],M=d[l],I=d[l+1],P=d[l+2],R=d[o],O=d[o+1],B=d[o+2],U=Math.round(g),G=Math.round(_);let H,Y,se,ee,oe,me,Q,te;for(let le=U;le<=G;le++){if(le_?Se=1:y===_?Se=0:Se=(y-le)/(y-_),H=x-(x-v)*Se,Y=M-(M-R)*Se,se=I-(I-O)*Se,ee=P-(P-B)*Se}let fe;le_?fe=1:fe=(g-le)/(g-_),oe=p-(p-v)*fe,me=j-(j-R)*fe,Q=C-(C-O)*fe,te=A-(A-B)*fe;const _e=Math.round(Math.min(H,oe)),ve=Math.round(Math.max(H,oe));let he=h*le+_e*4;for(let Se=_e;Se<=ve;Se++)fe=(H-Se)/(H-oe),fe<0?fe=0:fe>1&&(fe=1),u[he++]=Y-(Y-me)*fe|0,u[he++]=se-(se-Q)*fe|0,u[he++]=ee-(ee-te)*fe|0,u[he++]=255}}function BMn(s,t,n){const r=t.coords,a=t.colors;let i,l;switch(t.type){case"lattice":const o=t.verticesPerRow,c=Math.floor(r.length/o)-1,d=o-1;for(i=0;i=O?C=c:M=!0,R>=B?A=d:I=!0;const U=this.getSizeAndScale(C,this.ctx.canvas.width,_),G=this.getSizeAndScale(A,this.ctx.canvas.height,j),H=t.cachedCanvases.getCanvas("pattern",U.size,G.size),Y=H.context,se=o.createCanvasGraphics(Y);if(se.groupLevel=t.groupLevel,this.setFillAndStrokeStyleToContext(se,a,l),Y.translate(-U.scale*u,-G.scale*h),se.transform(U.scale,0,0,G.scale,0,0),Y.save(),this.clipBbox(se,u,h,m,p),se.baseTransform=kp(se.ctx),se.executeOperatorList(r),se.endDrawing(),Y.restore(),M||I){const ee=H.canvas;M&&(C=c),I&&(A=d);const oe=this.getSizeAndScale(C,this.ctx.canvas.width,_),me=this.getSizeAndScale(A,this.ctx.canvas.height,j),Q=oe.size,te=me.size,le=t.cachedCanvases.getCanvas("pattern-workaround",Q,te),fe=le.context,_e=M?Math.floor(g/c):0,ve=I?Math.floor(x/d):0;for(let he=0;he<=_e;he++)for(let Se=0;Se<=ve;Se++)fe.drawImage(ee,Q*he,te*Se,Q,te,0,0,Q,te);return{canvas:le.canvas,scaleX:oe.scale,scaleY:me.scale,offsetX:u,offsetY:h}}return{canvas:H.canvas,scaleX:U.scale,scaleY:G.scale,offsetX:u,offsetY:h}}getSizeAndScale(t,n,r){const a=Math.max(ECe.MAX_PATTERN_SIZE,n);let i=Math.ceil(t*r);return i>=a?i=a:r=i/t,{scale:r,size:i}}clipBbox(t,n,r,a,i){const l=a-n,o=i-r;t.ctx.rect(n,r,l,o),t.current.updateRectMinMax(kp(t.ctx),[n,r,a,i]),t.clip(),t.endPath()}setFillAndStrokeStyleToContext(t,n,r){const a=t.ctx,i=t.current;switch(n){case w1t.COLORED:const l=this.ctx;a.fillStyle=l.fillStyle,a.strokeStyle=l.strokeStyle,i.fillColor=l.fillStyle,i.strokeColor=l.strokeStyle;break;case w1t.UNCOLORED:const o=Ko.makeHexColor(r[0],r[1],r[2]);a.fillStyle=o,a.strokeStyle=o,i.fillColor=o,i.strokeColor=o;break;default:throw new fMn(`Unsupported paint type: ${n}`)}}getPattern(t,n,r,a){let i=r;a!==sb.SHADING&&(i=Ko.transform(i,n.baseTransform),this.matrix&&(i=Ko.transform(i,this.matrix)));const l=this.createPatternCanvas(n);let o=new DOMMatrix(i);o=o.translate(l.offsetX,l.offsetY),o=o.scale(1/l.scaleX,1/l.scaleY);const c=t.createPattern(l.canvas,"repeat");return c.setTransform(o),c}};ur(ECe,"MAX_PATTERN_SIZE",3e3);let rUe=ECe;function VMn({src:s,srcPos:t=0,dest:n,width:r,height:a,nonBlackColor:i=4294967295,inverseDecode:l=!1}){const o=_b.isLittleEndian?4278190080:255,[c,d]=l?[i,o]:[o,i],u=r>>3,h=r&7,m=s.length;n=new Uint32Array(n.buffer);let p=0;for(let g=0;g{s.save=s.__originalSave,s.restore=s.__originalRestore,s.rotate=s.__originalRotate,s.scale=s.__originalScale,s.translate=s.__originalTranslate,s.transform=s.__originalTransform,s.setTransform=s.__originalSetTransform,s.resetTransform=s.__originalResetTransform,s.clip=s.__originalClip,s.moveTo=s.__originalMoveTo,s.lineTo=s.__originalLineTo,s.bezierCurveTo=s.__originalBezierCurveTo,s.rect=s.__originalRect,s.closePath=s.__originalClosePath,s.beginPath=s.__originalBeginPath,delete s._removeMirroring},s.save=function(){t.save(),this.__originalSave()},s.restore=function(){t.restore(),this.__originalRestore()},s.translate=function(r,a){t.translate(r,a),this.__originalTranslate(r,a)},s.scale=function(r,a){t.scale(r,a),this.__originalScale(r,a)},s.transform=function(r,a,i,l,o,c){t.transform(r,a,i,l,o,c),this.__originalTransform(r,a,i,l,o,c)},s.setTransform=function(r,a,i,l,o,c){t.setTransform(r,a,i,l,o,c),this.__originalSetTransform(r,a,i,l,o,c)},s.resetTransform=function(){t.resetTransform(),this.__originalResetTransform()},s.rotate=function(r){t.rotate(r),this.__originalRotate(r)},s.clip=function(r){t.clip(r),this.__originalClip(r)},s.moveTo=function(n,r){t.moveTo(n,r),this.__originalMoveTo(n,r)},s.lineTo=function(n,r){t.lineTo(n,r),this.__originalLineTo(n,r)},s.bezierCurveTo=function(n,r,a,i,l,o){t.bezierCurveTo(n,r,a,i,l,o),this.__originalBezierCurveTo(n,r,a,i,l,o)},s.rect=function(n,r,a,i){t.rect(n,r,a,i),this.__originalRect(n,r,a,i)},s.closePath=function(){t.closePath(),this.__originalClosePath()},s.beginPath=function(){t.beginPath(),this.__originalBeginPath()}}class WMn{constructor(t){this.canvasFactory=t,this.cache=Object.create(null)}getCanvas(t,n,r){let a;return this.cache[t]!==void 0?(a=this.cache[t],this.canvasFactory.reset(a,n,r)):(a=this.canvasFactory.create(n,r),this.cache[t]=a),a}delete(t){delete this.cache[t]}clear(){for(const t in this.cache){const n=this.cache[t];this.canvasFactory.destroy(n),delete this.cache[t]}}}function Bae(s,t,n,r,a,i,l,o,c,d){const[u,h,m,p,g,x]=kp(s);if(h===0&&m===0){const _=l*u+g,j=Math.round(_),C=o*p+x,A=Math.round(C),M=(l+c)*u+g,I=Math.abs(Math.round(M)-j)||1,P=(o+d)*p+x,R=Math.abs(Math.round(P)-A)||1;return s.setTransform(Math.sign(u),0,0,Math.sign(p),j,A),s.drawImage(t,n,r,a,i,0,0,I,R),s.setTransform(u,h,m,p,g,x),[I,R]}if(u===0&&p===0){const _=o*m+g,j=Math.round(_),C=l*h+x,A=Math.round(C),M=(o+d)*m+g,I=Math.abs(Math.round(M)-j)||1,P=(l+c)*h+x,R=Math.abs(Math.round(P)-A)||1;return s.setTransform(0,Math.sign(h),Math.sign(m),0,j,A),s.drawImage(t,n,r,a,i,0,0,R,I),s.setTransform(u,h,m,p,g,x),[R,I]}s.drawImage(t,n,r,a,i,l,o,c,d);const y=Math.hypot(u,h),v=Math.hypot(m,p);return[y*c,v*d]}function KMn(s){const{width:t,height:n}=s;if(t>S1t||n>S1t)return null;const r=1e3,a=new Uint8Array([0,2,4,0,1,0,5,4,8,10,0,8,0,2,1,0]),i=t+1;let l=new Uint8Array(i*(n+1)),o,c,d;const u=t+7&-8;let h=new Uint8Array(u*n),m=0;for(const v of s.data){let _=128;for(;_>0;)h[m++]=v&_?0:255,_>>=1}let p=0;for(m=0,h[m]!==0&&(l[0]=1,++p),c=1;c>2)+(h[m+1]?4:0)+(h[m-u+1]?8:0),a[v]&&(l[d+c]=a[v],++p),m++;if(h[m-u]!==h[m]&&(l[d+c]=h[m]?2:4,++p),p>r)return null}for(m=u*(n-1),d=o*i,h[m]!==0&&(l[d]=8,++p),c=1;cr)return null;const g=new Int32Array([0,i,-1,0,-i,0,0,0,1]),x=new Path2D;for(o=0;p&&o<=n;o++){let v=o*i;const _=v+t;for(;v<_&&!l[v];)v++;if(v===_)continue;x.moveTo(v%i,o);const j=v;let C=l[v];do{const A=g[C];do v+=A;while(!l[v]);const M=l[v];M!==5&&M!==10?(C=M,l[v]=0):(C=M&51*C>>4,l[v]&=C>>2|C<<2),x.lineTo(v%i,v/i|0),l[v]||--p}while(j!==v);--o}return h=null,l=null,function(v){v.save(),v.scale(1/t,-1/n),v.translate(0,-n),v.fill(x),v.beginPath(),v.restore()}}class C1t{constructor(t,n){this.alphaIsShape=!1,this.fontSize=0,this.fontSizeScale=1,this.textMatrix=y$t,this.textMatrixScale=1,this.fontMatrix=T$e,this.leading=0,this.x=0,this.y=0,this.lineX=0,this.lineY=0,this.charSpacing=0,this.wordSpacing=0,this.textHScale=1,this.textRenderingMode=Gv.FILL,this.textRise=0,this.fillColor="#000000",this.strokeColor="#000000",this.patternFill=!1,this.fillAlpha=1,this.strokeAlpha=1,this.lineWidth=1,this.activeSMask=null,this.transferMaps="none",this.startNewPathAndClipBox([0,0,t,n])}clone(){const t=Object.create(this);return t.clipBox=this.clipBox.slice(),t}setCurrentPoint(t,n){this.x=t,this.y=n}updatePathMinMax(t,n,r){[n,r]=Ko.applyTransform([n,r],t),this.minX=Math.min(this.minX,n),this.minY=Math.min(this.minY,r),this.maxX=Math.max(this.maxX,n),this.maxY=Math.max(this.maxY,r)}updateRectMinMax(t,n){const r=Ko.applyTransform(n,t),a=Ko.applyTransform(n.slice(2),t),i=Ko.applyTransform([n[0],n[3]],t),l=Ko.applyTransform([n[2],n[1]],t);this.minX=Math.min(this.minX,r[0],a[0],i[0],l[0]),this.minY=Math.min(this.minY,r[1],a[1],i[1],l[1]),this.maxX=Math.max(this.maxX,r[0],a[0],i[0],l[0]),this.maxY=Math.max(this.maxY,r[1],a[1],i[1],l[1])}updateScalingPathMinMax(t,n){Ko.scaleMinMax(t,n),this.minX=Math.min(this.minX,n[0]),this.minY=Math.min(this.minY,n[1]),this.maxX=Math.max(this.maxX,n[2]),this.maxY=Math.max(this.maxY,n[3])}updateCurvePathMinMax(t,n,r,a,i,l,o,c,d,u){const h=Ko.bezierBoundingBox(n,r,a,i,l,o,c,d,u);u||this.updateRectMinMax(t,h)}getPathBoundingBox(t=sb.FILL,n=null){const r=[this.minX,this.minY,this.maxX,this.maxY];if(t===sb.STROKE){n||wf("Stroke bounding box must include transform.");const a=Ko.singularValueDecompose2dScale(n),i=a[0]*this.lineWidth/2,l=a[1]*this.lineWidth/2;r[0]-=i,r[1]-=l,r[2]+=i,r[3]+=l}return r}updateClipFromPath(){const t=Ko.intersect(this.clipBox,this.getPathBoundingBox());this.startNewPathAndClipBox(t||[0,0,0,0])}isEmptyClip(){return this.minX===1/0}startNewPathAndClipBox(t){this.clipBox=t,this.minX=1/0,this.minY=1/0,this.maxX=0,this.maxY=0}getClippedPathBoundingBox(t=sb.FILL,n=null){return Ko.intersect(this.clipBox,this.getPathBoundingBox(t,n))}}function A1t(s,t){if(typeof ImageData<"u"&&t instanceof ImageData){s.putImageData(t,0,0);return}const n=t.height,r=t.width,a=n%i_,i=(n-a)/i_,l=a===0?i:i+1,o=s.createImageData(r,i_);let c=0,d;const u=t.data,h=o.data;let m,p,g,x;if(t.kind===RNe.GRAYSCALE_1BPP){const y=u.byteLength,v=new Uint32Array(h.buffer,0,h.byteLength>>2),_=v.length,j=r+7>>3,C=4294967295,A=_b.isLittleEndian?4278190080:255;for(m=0;mj?r:M*8-7,R=P&-8;let O=0,B=0;for(;I>=1}for(;d<_;)v[d++]=0;s.putImageData(o,0,m*i_)}}else if(t.kind===RNe.RGBA_32BPP){for(p=0,x=r*i_*4,m=0;m=i&&(g=a,x=r*g),d=0,p=x;p--;)h[d++]=u[c++],h[d++]=u[c++],h[d++]=u[c++],h[d++]=255;s.putImageData(o,0,m*i_)}else throw new Error(`bad image kind: ${t.kind}`)}function E1t(s,t){if(t.bitmap){s.drawImage(t.bitmap,0,0);return}const n=t.height,r=t.width,a=n%i_,i=(n-a)/i_,l=a===0?i:i+1,o=s.createImageData(r,i_);let c=0;const d=t.data,u=o.data;for(let h=0;hk1t&&typeof r=="function",u=d?Date.now()+HMn:0;let h=0;const m=this.commonObjs,p=this.objs;let g;for(;;){if(a!==void 0&&o===a.nextBreakPoint)return a.breakIt(o,r),o;if(g=l[o],g!==NN.dependency)this[g].apply(this,i[o]);else for(const x of i[o]){const y=x.startsWith("g_")?m:p;if(!y.has(x))return y.get(x,r),o}if(o++,o===c)return o;if(d&&++h>k1t){if(Date.now()>u)return r(),o;h=0}}}endDrawing(){ss(this,qM,aUe).call(this),this.cachedCanvases.clear(),this.cachedPatterns.clear();for(const t of this._cachedBitmapsMap.values()){for(const n of t.values())typeof HTMLCanvasElement<"u"&&n instanceof HTMLCanvasElement&&(n.width=n.height=0);t.clear()}this._cachedBitmapsMap.clear(),ss(this,qM,iUe).call(this)}_scaleImage(t,n){const r=t.width??t.displayWidth,a=t.height??t.displayHeight;let i=Math.max(Math.hypot(n[0],n[1]),1),l=Math.max(Math.hypot(n[2],n[3]),1),o=r,c=a,d="prescale1",u,h;for(;i>2&&o>1||l>2&&c>1;){let m=o,p=c;i>2&&o>1&&(m=o>=16384?Math.floor(o/2)-1||1:Math.ceil(o/2),i/=o/m),l>2&&c>1&&(p=c>=16384?Math.floor(c/2)-1||1:Math.ceil(c)/2,l/=c/p),u=this.cachedCanvases.getCanvas(d,m,p),h=u.context,h.clearRect(0,0,m,p),h.drawImage(t,0,0,o,c,0,0,m,p),t=u.canvas,o=m,c=p,d=d==="prescale1"?"prescale2":"prescale1"}return{img:t,paintWidth:o,paintHeight:c}}_createMaskCanvas(t){const n=this.ctx,{width:r,height:a}=t,i=this.current.fillColor,l=this.current.patternFill,o=kp(n);let c,d,u,h;if((t.bitmap||t.data)&&t.count>1){const P=t.bitmap||t.data.buffer;d=JSON.stringify(l?o:[o.slice(0,4),i]),c=this._cachedBitmapsMap.get(P),c||(c=new Map,this._cachedBitmapsMap.set(P,c));const R=c.get(d);if(R&&!l){const O=Math.round(Math.min(o[0],o[2])+o[4]),B=Math.round(Math.min(o[1],o[3])+o[5]);return{canvas:R,offsetX:O,offsetY:B}}u=R}u||(h=this.cachedCanvases.getCanvas("maskCanvas",r,a),E1t(h.context,t));let m=Ko.transform(o,[1/r,0,0,-1/a,0,0]);m=Ko.transform(m,[1,0,0,1,0,-a]);const[p,g,x,y]=Ko.getAxialAlignedBoundingBox([0,0,r,a],m),v=Math.round(x-p)||1,_=Math.round(y-g)||1,j=this.cachedCanvases.getCanvas("fillCanvas",v,_),C=j.context,A=p,M=g;C.translate(-A,-M),C.transform(...m),u||(u=this._scaleImage(h.canvas,tC(C)),u=u.img,c&&l&&c.set(d,u)),C.imageSmoothingEnabled=T1t(kp(C),t.interpolate),Bae(C,u,0,0,u.width,u.height,0,0,r,a),C.globalCompositeOperation="source-in";const I=Ko.transform(tC(C),[1,0,0,1,-A,-M]);return C.fillStyle=l?i.getPattern(n,this,I,sb.FILL):i,C.fillRect(0,0,r,a),c&&!l&&(this.cachedCanvases.delete("fillCanvas"),c.set(d,j.canvas)),{canvas:j.canvas,offsetX:Math.round(A),offsetY:Math.round(M)}}setLineWidth(t){t!==this.current.lineWidth&&(this._cachedScaleForStroking[0]=-1),this.current.lineWidth=t,this.ctx.lineWidth=t}setLineCap(t){this.ctx.lineCap=YMn[t]}setLineJoin(t){this.ctx.lineJoin=ZMn[t]}setMiterLimit(t){this.ctx.miterLimit=t}setDash(t,n){const r=this.ctx;r.setLineDash!==void 0&&(r.setLineDash(t),r.lineDashOffset=n)}setRenderingIntent(t){}setFlatness(t){}setGState(t){for(const[n,r]of t)switch(n){case"LW":this.setLineWidth(r);break;case"LC":this.setLineCap(r);break;case"LJ":this.setLineJoin(r);break;case"ML":this.setMiterLimit(r);break;case"D":this.setDash(r[0],r[1]);break;case"RI":this.setRenderingIntent(r);break;case"FL":this.setFlatness(r);break;case"Font":this.setFont(r[0],r[1]);break;case"CA":this.current.strokeAlpha=r;break;case"ca":this.current.fillAlpha=r,this.ctx.globalAlpha=r;break;case"BM":this.ctx.globalCompositeOperation=r;break;case"SMask":this.current.activeSMask=r?this.tempSMask:null,this.tempSMask=null,this.checkSMaskState();break;case"TR":this.ctx.filter=this.current.transferMaps=this.filterFactory.addFilter(r);break}}get inSMaskMode(){return!!this.suspendedCtx}checkSMaskState(){const t=this.inSMaskMode;this.current.activeSMask&&!t?this.beginSMaskMode():!this.current.activeSMask&&t&&this.endSMaskMode()}beginSMaskMode(){if(this.inSMaskMode)throw new Error("beginSMaskMode called while already in smask mode");const t=this.ctx.canvas.width,n=this.ctx.canvas.height,r="smaskGroupAt"+this.groupLevel,a=this.cachedCanvases.getCanvas(r,t,n);this.suspendedCtx=this.ctx,this.ctx=a.context;const i=this.ctx;i.setTransform(...kp(this.suspendedCtx)),$G(this.suspendedCtx,i),GMn(i,this.suspendedCtx),this.setGState([["BM","source-over"],["ca",1],["CA",1]])}endSMaskMode(){if(!this.inSMaskMode)throw new Error("endSMaskMode called while not in smask mode");this.ctx._removeMirroring(),$G(this.ctx,this.suspendedCtx),this.ctx=this.suspendedCtx,this.suspendedCtx=null}compose(t){if(!this.current.activeSMask)return;t?(t[0]=Math.floor(t[0]),t[1]=Math.floor(t[1]),t[2]=Math.ceil(t[2]),t[3]=Math.ceil(t[3])):t=[0,0,this.ctx.canvas.width,this.ctx.canvas.height];const n=this.current.activeSMask,r=this.suspendedCtx;this.composeSMask(r,n,this.ctx,t),this.ctx.save(),this.ctx.setTransform(1,0,0,1,0,0),this.ctx.clearRect(0,0,this.ctx.canvas.width,this.ctx.canvas.height),this.ctx.restore()}composeSMask(t,n,r,a){const i=a[0],l=a[1],o=a[2]-i,c=a[3]-l;o===0||c===0||(this.genericComposeSMask(n.context,r,o,c,n.subtype,n.backdrop,n.transferMap,i,l,n.offsetX,n.offsetY),t.save(),t.globalAlpha=1,t.globalCompositeOperation="source-over",t.setTransform(1,0,0,1,0,0),t.drawImage(r.canvas,0,0),t.restore())}genericComposeSMask(t,n,r,a,i,l,o,c,d,u,h){let m=t.canvas,p=c-u,g=d-h;if(l){const y=Ko.makeHexColor(...l);if(p<0||g<0||p+r>m.width||g+a>m.height){const v=this.cachedCanvases.getCanvas("maskExtension",r,a),_=v.context;_.drawImage(m,-p,-g),_.globalCompositeOperation="destination-atop",_.fillStyle=y,_.fillRect(0,0,r,a),_.globalCompositeOperation="source-over",m=v.canvas,p=g=0}else{t.save(),t.globalAlpha=1,t.setTransform(1,0,0,1,0,0);const v=new Path2D;v.rect(p,g,r,a),t.clip(v),t.globalCompositeOperation="destination-atop",t.fillStyle=y,t.fillRect(p,g,r,a),t.restore()}}n.save(),n.globalAlpha=1,n.setTransform(1,0,0,1,0,0),i==="Alpha"&&o?n.filter=this.filterFactory.addAlphaFilter(o):i==="Luminosity"&&(n.filter=this.filterFactory.addLuminosityFilter(o));const x=new Path2D;x.rect(c,d,r,a),n.clip(x),n.globalCompositeOperation="destination-in",n.drawImage(m,p,g,r,a,c,d,r,a),n.restore()}save(){this.inSMaskMode?($G(this.ctx,this.suspendedCtx),this.suspendedCtx.save()):this.ctx.save();const t=this.current;this.stateStack.push(t),this.current=t.clone()}restore(){this.stateStack.length===0&&this.inSMaskMode&&this.endSMaskMode(),this.stateStack.length!==0&&(this.current=this.stateStack.pop(),this.inSMaskMode?(this.suspendedCtx.restore(),$G(this.suspendedCtx,this.ctx)):this.ctx.restore(),this.checkSMaskState(),this.pendingClip=null,this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null)}transform(t,n,r,a,i,l){this.ctx.transform(t,n,r,a,i,l),this._cachedScaleForStroking[0]=-1,this._cachedGetSinglePixelWidth=null}constructPath(t,n,r){const a=this.ctx,i=this.current;let l=i.x,o=i.y,c,d;const u=kp(a),h=u[0]===0&&u[3]===0||u[1]===0&&u[2]===0,m=h?r.slice(0):null;for(let p=0,g=0,x=t.length;pN1t&&(d=N1t),this.current.fontSizeScale=n/d,this.ctx.font=`${c} ${o} ${d}px ${l}`}setTextRenderingMode(t){this.current.textRenderingMode=t}setTextRise(t){this.current.textRise=t}moveText(t,n){this.current.x=this.current.lineX+=t,this.current.y=this.current.lineY+=n}setLeadingMoveText(t,n){this.setLeading(-n),this.moveText(t,n)}setTextMatrix(t,n,r,a,i,l){this.current.textMatrix=[t,n,r,a,i,l],this.current.textMatrixScale=Math.hypot(t,n),this.current.x=this.current.lineX=0,this.current.y=this.current.lineY=0}nextLine(){this.moveText(0,this.current.leading)}paintChar(t,n,r,a){const i=this.ctx,l=this.current,o=l.font,c=l.textRenderingMode,d=l.fontSize/l.fontSizeScale,u=c&Gv.FILL_STROKE_MASK,h=!!(c&Gv.ADD_TO_PATH_FLAG),m=l.patternFill&&!o.missingFile;let p;(o.disableFontFace||h||m)&&(p=o.getPathGenerator(this.commonObjs,t)),o.disableFontFace||m?(i.save(),i.translate(n,r),i.beginPath(),p(i,d),a&&i.setTransform(...a),(u===Gv.FILL||u===Gv.FILL_STROKE)&&i.fill(),(u===Gv.STROKE||u===Gv.FILL_STROKE)&&i.stroke(),i.restore()):((u===Gv.FILL||u===Gv.FILL_STROKE)&&i.fillText(t,n,r),(u===Gv.STROKE||u===Gv.FILL_STROKE)&&i.strokeText(t,n,r)),h&&(this.pendingTextPaths||(this.pendingTextPaths=[])).push({transform:kp(i),x:n,y:r,fontSize:d,addToPath:p})}get isFontSubpixelAAEnabled(){const{context:t}=this.cachedCanvases.getCanvas("isFontSubpixelAAEnabled",10,10);t.scale(1.5,1),t.fillText("I",0,10);const n=t.getImageData(0,0,10,10).data;let r=!1;for(let a=3;a0&&n[a]<255){r=!0;break}return nu(this,"isFontSubpixelAAEnabled",r)}showText(t){const n=this.current,r=n.font;if(r.isType3Font)return this.showType3Text(t);const a=n.fontSize;if(a===0)return;const i=this.ctx,l=n.fontSizeScale,o=n.charSpacing,c=n.wordSpacing,d=n.fontDirection,u=n.textHScale*d,h=t.length,m=r.vertical,p=m?1:-1,g=r.defaultVMetrics,x=a*n.fontMatrix[0],y=n.textRenderingMode===Gv.FILL&&!r.disableFontFace&&!n.patternFill;i.save(),i.transform(...n.textMatrix),i.translate(n.x,n.y+n.textRise),d>0?i.scale(u,-1):i.scale(u,1);let v;if(n.patternFill){i.save();const M=n.fillColor.getPattern(i,this,tC(i),sb.FILL);v=kp(i),i.restore(),i.fillStyle=M}let _=n.lineWidth;const j=n.textMatrixScale;if(j===0||_===0){const M=n.textRenderingMode&Gv.FILL_STROKE_MASK;(M===Gv.STROKE||M===Gv.FILL_STROKE)&&(_=this.getSinglePixelWidth())}else _/=j;if(l!==1&&(i.scale(l,l),_/=l),i.lineWidth=_,r.isInvalidPDFjsFont){const M=[];let I=0;for(const P of t)M.push(P.unicode),I+=P.width;i.fillText(M.join(""),0,0),n.x+=I*x*u,i.restore(),this.compose();return}let C=0,A;for(A=0;A0){const Y=i.measureText(R).width*1e3/a*l;if(Gnew SJe(l,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:this.optionalContentConfig,markedContentStack:this.markedContentStack})};n=new rUe(t,r,this.ctx,i,a)}else n=this._getPattern(t[1],t[2]);return n}setStrokeColorN(){this.current.strokeColor=this.getColorN_Pattern(arguments)}setFillColorN(){this.current.fillColor=this.getColorN_Pattern(arguments),this.current.patternFill=!0}setStrokeRGBColor(t,n,r){this.ctx.strokeStyle=this.current.strokeColor=Ko.makeHexColor(t,n,r)}setStrokeTransparent(){this.ctx.strokeStyle=this.current.strokeColor="transparent"}setFillRGBColor(t,n,r){this.ctx.fillStyle=this.current.fillColor=Ko.makeHexColor(t,n,r),this.current.patternFill=!1}setFillTransparent(){this.ctx.fillStyle=this.current.fillColor="transparent",this.current.patternFill=!1}_getPattern(t,n=null){let r;return this.cachedPatterns.has(t)?r=this.cachedPatterns.get(t):(r=qMn(this.getObject(t)),this.cachedPatterns.set(t,r)),n&&(r.matrix=n),r}shadingFill(t){if(!this.contentVisible)return;const n=this.ctx;this.save();const r=this._getPattern(t);n.fillStyle=r.getPattern(n,this,tC(n),sb.SHADING);const a=tC(n);if(a){const{width:i,height:l}=n.canvas,[o,c,d,u]=Ko.getAxialAlignedBoundingBox([0,0,i,l],a);this.ctx.fillRect(o,c,d-o,u-c)}else this.ctx.fillRect(-1e10,-1e10,2e10,2e10);this.compose(this.current.getClippedPathBoundingBox()),this.restore()}beginInlineImage(){wf("Should not call beginInlineImage")}beginImageData(){wf("Should not call beginImageData")}paintFormXObjectBegin(t,n){if(this.contentVisible&&(this.save(),this.baseTransformStack.push(this.baseTransform),t&&this.transform(...t),this.baseTransform=kp(this.ctx),n)){const r=n[2]-n[0],a=n[3]-n[1];this.ctx.rect(n[0],n[1],r,a),this.current.updateRectMinMax(kp(this.ctx),n),this.clip(),this.endPath()}}paintFormXObjectEnd(){this.contentVisible&&(this.restore(),this.baseTransform=this.baseTransformStack.pop())}beginGroup(t){if(!this.contentVisible)return;this.save(),this.inSMaskMode&&(this.endSMaskMode(),this.current.activeSMask=null);const n=this.ctx;t.isolated||RTe("TODO: Support non-isolated groups."),t.knockout&&md("Knockout groups not supported.");const r=kp(n);if(t.matrix&&n.transform(...t.matrix),!t.bbox)throw new Error("Bounding box is required.");let a=Ko.getAxialAlignedBoundingBox(t.bbox,kp(n));const i=[0,0,n.canvas.width,n.canvas.height];a=Ko.intersect(a,i)||[0,0,0,0];const l=Math.floor(a[0]),o=Math.floor(a[1]),c=Math.max(Math.ceil(a[2])-l,1),d=Math.max(Math.ceil(a[3])-o,1);this.current.startNewPathAndClipBox([0,0,c,d]);let u="groupAt"+this.groupLevel;t.smask&&(u+="_smask_"+this.smaskCounter++%2);const h=this.cachedCanvases.getCanvas(u,c,d),m=h.context;m.translate(-l,-o),m.transform(...r),t.smask?this.smaskStack.push({canvas:h.canvas,context:m,offsetX:l,offsetY:o,subtype:t.smask.subtype,backdrop:t.smask.backdrop,transferMap:t.smask.transferMap||null,startTransformInverse:null}):(n.setTransform(1,0,0,1,0,0),n.translate(l,o),n.save()),$G(n,m),this.ctx=m,this.setGState([["BM","source-over"],["ca",1],["CA",1]]),this.groupStack.push(n),this.groupLevel++}endGroup(t){if(!this.contentVisible)return;this.groupLevel--;const n=this.ctx,r=this.groupStack.pop();if(this.ctx=r,this.ctx.imageSmoothingEnabled=!1,t.smask)this.tempSMask=this.smaskStack.pop(),this.restore();else{this.ctx.restore();const a=kp(this.ctx);this.restore(),this.ctx.save(),this.ctx.setTransform(...a);const i=Ko.getAxialAlignedBoundingBox([0,0,n.canvas.width,n.canvas.height],a);this.ctx.drawImage(n.canvas,0,0),this.ctx.restore(),this.compose(i)}}beginAnnotation(t,n,r,a,i){if(ss(this,qM,aUe).call(this),$ae(this.ctx),this.ctx.save(),this.save(),this.baseTransform&&this.ctx.setTransform(...this.baseTransform),n){const l=n[2]-n[0],o=n[3]-n[1];if(i&&this.annotationCanvasMap){r=r.slice(),r[4]-=n[0],r[5]-=n[1],n=n.slice(),n[0]=n[1]=0,n[2]=l,n[3]=o;const[c,d]=Ko.singularValueDecompose2dScale(kp(this.ctx)),{viewportScale:u}=this,h=Math.ceil(l*this.outputScaleX*u),m=Math.ceil(o*this.outputScaleY*u);this.annotationCanvas=this.canvasFactory.create(h,m);const{canvas:p,context:g}=this.annotationCanvas;this.annotationCanvasMap.set(t,p),this.annotationCanvas.savedCtx=this.ctx,this.ctx=g,this.ctx.save(),this.ctx.setTransform(c,0,0,-d,0,o*d),$ae(this.ctx)}else $ae(this.ctx),this.endPath(),this.ctx.rect(n[0],n[1],l,o),this.ctx.clip(),this.ctx.beginPath()}this.current=new C1t(this.ctx.canvas.width,this.ctx.canvas.height),this.transform(...r),this.transform(...a)}endAnnotation(){this.annotationCanvas&&(this.ctx.restore(),ss(this,qM,iUe).call(this),this.ctx=this.annotationCanvas.savedCtx,delete this.annotationCanvas.savedCtx,delete this.annotationCanvas)}paintImageMaskXObject(t){if(!this.contentVisible)return;const n=t.count;t=this.getObject(t.data,t),t.count=n;const r=this.ctx,a=this.processingType3;if(a&&(a.compiled===void 0&&(a.compiled=KMn(t)),a.compiled)){a.compiled(r);return}const i=this._createMaskCanvas(t),l=i.canvas;r.save(),r.setTransform(1,0,0,1,0,0),r.drawImage(l,i.offsetX,i.offsetY),r.restore(),this.compose()}paintImageMaskXObjectRepeat(t,n,r=0,a=0,i,l){if(!this.contentVisible)return;t=this.getObject(t.data,t);const o=this.ctx;o.save();const c=kp(o);o.transform(n,r,a,i,0,0);const d=this._createMaskCanvas(t);o.setTransform(1,0,0,1,d.offsetX-c[4],d.offsetY-c[5]);for(let u=0,h=l.length;uh?u/h:1,o=d>h?d/h:1}}this._cachedScaleForStroking[0]=l,this._cachedScaleForStroking[1]=o}return this._cachedScaleForStroking}rescaleAndStroke(t){const{ctx:n}=this,{lineWidth:r}=this.current,[a,i]=this.getScaleForStroking();if(n.lineWidth=r||1,a===1&&i===1){n.stroke();return}const l=n.getLineDash();if(t&&n.save(),n.scale(a,i),l.length>0){const o=Math.max(a,i);n.setLineDash(l.map(c=>c/o)),n.lineDashOffset/=o}n.stroke(),t&&n.restore()}isContentVisible(){for(let t=this.markedContentStack.length-1;t>=0;t--)if(!this.markedContentStack[t].visible)return!1;return!0}};qM=new WeakSet,aUe=function(){for(;this.stateStack.length||this.inSMaskMode;)this.restore();this.current.activeSMask=null,this.ctx.restore(),this.transparentCanvas&&(this.ctx=this.compositeCtx,this.ctx.save(),this.ctx.setTransform(1,0,0,1,0,0),this.ctx.drawImage(this.transparentCanvas,0,0),this.ctx.restore(),this.transparentCanvas=null)},iUe=function(){if(this.pageColors){const t=this.filterFactory.addHCMFilter(this.pageColors.foreground,this.pageColors.background);if(t!=="none"){const n=this.ctx.filter;this.ctx.filter=t,this.ctx.drawImage(this.ctx.canvas,0,0),this.ctx.filter=n}}};let $B=SJe;for(const s in NN)$B.prototype[s]!==void 0&&($B.prototype[NN[s]]=$B.prototype[s]);var JQ,eJ;class e3{static get workerPort(){return ge(this,JQ)}static set workerPort(t){if(!(typeof Worker<"u"&&t instanceof Worker)&&t!==null)throw new Error("Invalid `workerPort` type.");$t(this,JQ,t)}static get workerSrc(){return ge(this,eJ)}static set workerSrc(t){if(typeof t!="string")throw new Error("Invalid `workerSrc` type.");$t(this,eJ,t)}}JQ=new WeakMap,eJ=new WeakMap,ds(e3,JQ,null),ds(e3,eJ,"");const Uae={DATA:1,ERROR:2},wx={CANCEL:1,CANCEL_COMPLETE:2,CLOSE:3,ENQUEUE:4,ERROR:5,PULL:6,PULL_COMPLETE:7,START_COMPLETE:8};function fw(s){switch(s instanceof Error||typeof s=="object"&&s!==null||wf('wrapReason: Expected "reason" to be a (possibly cloned) Error.'),s.name){case"AbortException":return new ZF(s.message);case"MissingPDFException":return new YF(s.message);case"PasswordException":return new M$e(s.message,s.code);case"UnexpectedResponseException":return new DTe(s.message,s.status);case"UnknownErrorException":return new P$e(s.message,s.details);default:return new P$e(s.message,s.toString())}}var _$,T2,sUt,nUt,rUt,qNe;class WW{constructor(t,n,r){ds(this,T2);ds(this,_$,new AbortController);this.sourceName=t,this.targetName=n,this.comObj=r,this.callbackId=1,this.streamId=1,this.streamSinks=Object.create(null),this.streamControllers=Object.create(null),this.callbackCapabilities=Object.create(null),this.actionHandler=Object.create(null),r.addEventListener("message",ss(this,T2,sUt).bind(this),{signal:ge(this,_$).signal})}on(t,n){const r=this.actionHandler;if(r[t])throw new Error(`There is already an actionName called "${t}"`);r[t]=n}send(t,n,r){this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:t,data:n},r)}sendWithPromise(t,n,r){const a=this.callbackId++,i=Promise.withResolvers();this.callbackCapabilities[a]=i;try{this.comObj.postMessage({sourceName:this.sourceName,targetName:this.targetName,action:t,callbackId:a,data:n},r)}catch(l){i.reject(l)}return i.promise}sendWithStream(t,n,r,a){const i=this.streamId++,l=this.sourceName,o=this.targetName,c=this.comObj;return new ReadableStream({start:d=>{const u=Promise.withResolvers();return this.streamControllers[i]={controller:d,startCall:u,pullCall:null,cancelCall:null,isClosed:!1},c.postMessage({sourceName:l,targetName:o,action:t,streamId:i,data:n,desiredSize:d.desiredSize},a),u.promise},pull:d=>{const u=Promise.withResolvers();return this.streamControllers[i].pullCall=u,c.postMessage({sourceName:l,targetName:o,stream:wx.PULL,streamId:i,desiredSize:d.desiredSize}),u.promise},cancel:d=>{yy(d instanceof Error,"cancel must have a valid reason");const u=Promise.withResolvers();return this.streamControllers[i].cancelCall=u,this.streamControllers[i].isClosed=!0,c.postMessage({sourceName:l,targetName:o,stream:wx.CANCEL,streamId:i,reason:fw(d)}),u.promise}},r)}destroy(){var t;(t=ge(this,_$))==null||t.abort(),$t(this,_$,null)}}_$=new WeakMap,T2=new WeakSet,sUt=function({data:t}){if(t.targetName!==this.sourceName)return;if(t.stream){ss(this,T2,rUt).call(this,t);return}if(t.callback){const r=t.callbackId,a=this.callbackCapabilities[r];if(!a)throw new Error(`Cannot resolve callback ${r}`);if(delete this.callbackCapabilities[r],t.callback===Uae.DATA)a.resolve(t.data);else if(t.callback===Uae.ERROR)a.reject(fw(t.reason));else throw new Error("Unexpected callback case");return}const n=this.actionHandler[t.action];if(!n)throw new Error(`Unknown action from worker: ${t.action}`);if(t.callbackId){const r=this.sourceName,a=t.sourceName,i=this.comObj;new Promise(function(l){l(n(t.data))}).then(function(l){i.postMessage({sourceName:r,targetName:a,callback:Uae.DATA,callbackId:t.callbackId,data:l})},function(l){i.postMessage({sourceName:r,targetName:a,callback:Uae.ERROR,callbackId:t.callbackId,reason:fw(l)})});return}if(t.streamId){ss(this,T2,nUt).call(this,t);return}n(t.data)},nUt=function(t){const n=t.streamId,r=this.sourceName,a=t.sourceName,i=this.comObj,l=this,o=this.actionHandler[t.action],c={enqueue(d,u=1,h){if(this.isCancelled)return;const m=this.desiredSize;this.desiredSize-=u,m>0&&this.desiredSize<=0&&(this.sinkCapability=Promise.withResolvers(),this.ready=this.sinkCapability.promise),i.postMessage({sourceName:r,targetName:a,stream:wx.ENQUEUE,streamId:n,chunk:d},h)},close(){this.isCancelled||(this.isCancelled=!0,i.postMessage({sourceName:r,targetName:a,stream:wx.CLOSE,streamId:n}),delete l.streamSinks[n])},error(d){yy(d instanceof Error,"error must have a valid reason"),!this.isCancelled&&(this.isCancelled=!0,i.postMessage({sourceName:r,targetName:a,stream:wx.ERROR,streamId:n,reason:fw(d)}))},sinkCapability:Promise.withResolvers(),onPull:null,onCancel:null,isCancelled:!1,desiredSize:t.desiredSize,ready:null};c.sinkCapability.resolve(),c.ready=c.sinkCapability.promise,this.streamSinks[n]=c,new Promise(function(d){d(o(t.data,c))}).then(function(){i.postMessage({sourceName:r,targetName:a,stream:wx.START_COMPLETE,streamId:n,success:!0})},function(d){i.postMessage({sourceName:r,targetName:a,stream:wx.START_COMPLETE,streamId:n,reason:fw(d)})})},rUt=function(t){const n=t.streamId,r=this.sourceName,a=t.sourceName,i=this.comObj,l=this.streamControllers[n],o=this.streamSinks[n];switch(t.stream){case wx.START_COMPLETE:t.success?l.startCall.resolve():l.startCall.reject(fw(t.reason));break;case wx.PULL_COMPLETE:t.success?l.pullCall.resolve():l.pullCall.reject(fw(t.reason));break;case wx.PULL:if(!o){i.postMessage({sourceName:r,targetName:a,stream:wx.PULL_COMPLETE,streamId:n,success:!0});break}o.desiredSize<=0&&t.desiredSize>0&&o.sinkCapability.resolve(),o.desiredSize=t.desiredSize,new Promise(function(c){var d;c((d=o.onPull)==null?void 0:d.call(o))}).then(function(){i.postMessage({sourceName:r,targetName:a,stream:wx.PULL_COMPLETE,streamId:n,success:!0})},function(c){i.postMessage({sourceName:r,targetName:a,stream:wx.PULL_COMPLETE,streamId:n,reason:fw(c)})});break;case wx.ENQUEUE:if(yy(l,"enqueue should have stream controller"),l.isClosed)break;l.controller.enqueue(t.chunk);break;case wx.CLOSE:if(yy(l,"close should have stream controller"),l.isClosed)break;l.isClosed=!0,l.controller.close(),ss(this,T2,qNe).call(this,l,n);break;case wx.ERROR:yy(l,"error should have stream controller"),l.controller.error(fw(t.reason)),ss(this,T2,qNe).call(this,l,n);break;case wx.CANCEL_COMPLETE:t.success?l.cancelCall.resolve():l.cancelCall.reject(fw(t.reason)),ss(this,T2,qNe).call(this,l,n);break;case wx.CANCEL:if(!o)break;new Promise(function(c){var d;c((d=o.onCancel)==null?void 0:d.call(o,fw(t.reason)))}).then(function(){i.postMessage({sourceName:r,targetName:a,stream:wx.CANCEL_COMPLETE,streamId:n,success:!0})},function(c){i.postMessage({sourceName:r,targetName:a,stream:wx.CANCEL_COMPLETE,streamId:n,reason:fw(c)})}),o.sinkCapability.reject(fw(t.reason)),o.isCancelled=!0,delete this.streamSinks[n];break;default:throw new Error("Unexpected stream case")}},qNe=async function(t,n){var r,a,i;await Promise.allSettled([(r=t.startCall)==null?void 0:r.promise,(a=t.pullCall)==null?void 0:a.promise,(i=t.cancelCall)==null?void 0:i.promise]),delete this.streamControllers[n]};var XD,tJ;class QMn{constructor({parsedData:t,rawData:n}){ds(this,XD);ds(this,tJ);$t(this,XD,t),$t(this,tJ,n)}getRaw(){return ge(this,tJ)}get(t){return ge(this,XD).get(t)??null}getAll(){return KXe(ge(this,XD))}has(t){return ge(this,XD).has(t)}}XD=new WeakMap,tJ=new WeakMap;const G9=Symbol("INTERNAL");var sJ,nJ,rJ,w$;class JMn{constructor(t,{name:n,intent:r,usage:a,rbGroups:i}){ds(this,sJ,!1);ds(this,nJ,!1);ds(this,rJ,!1);ds(this,w$,!0);$t(this,sJ,!!(t&Mw.DISPLAY)),$t(this,nJ,!!(t&Mw.PRINT)),this.name=n,this.intent=r,this.usage=a,this.rbGroups=i}get visible(){if(ge(this,rJ))return ge(this,w$);if(!ge(this,w$))return!1;const{print:t,view:n}=this.usage;return ge(this,sJ)?(n==null?void 0:n.viewState)!=="OFF":ge(this,nJ)?(t==null?void 0:t.printState)!=="OFF":!0}_setVisible(t,n,r=!1){t!==G9&&wf("Internal method `_setVisible` called."),$t(this,rJ,r),$t(this,w$,n)}}sJ=new WeakMap,nJ=new WeakMap,rJ=new WeakMap,w$=new WeakMap;var tT,Th,j$,N$,aJ,oUe;class e6n{constructor(t,n=Mw.DISPLAY){ds(this,aJ);ds(this,tT,null);ds(this,Th,new Map);ds(this,j$,null);ds(this,N$,null);if(this.renderingIntent=n,this.name=null,this.creator=null,t!==null){this.name=t.name,this.creator=t.creator,$t(this,N$,t.order);for(const r of t.groups)ge(this,Th).set(r.id,new JMn(n,r));if(t.baseState==="OFF")for(const r of ge(this,Th).values())r._setVisible(G9,!1);for(const r of t.on)ge(this,Th).get(r)._setVisible(G9,!0);for(const r of t.off)ge(this,Th).get(r)._setVisible(G9,!1);$t(this,j$,this.getHash())}}isVisible(t){if(ge(this,Th).size===0)return!0;if(!t)return RTe("Optional content group not defined."),!0;if(t.type==="OCG")return ge(this,Th).has(t.id)?ge(this,Th).get(t.id).visible:(md(`Optional content group not found: ${t.id}`),!0);if(t.type==="OCMD"){if(t.expression)return ss(this,aJ,oUe).call(this,t.expression);if(!t.policy||t.policy==="AnyOn"){for(const n of t.ids){if(!ge(this,Th).has(n))return md(`Optional content group not found: ${n}`),!0;if(ge(this,Th).get(n).visible)return!0}return!1}else if(t.policy==="AllOn"){for(const n of t.ids){if(!ge(this,Th).has(n))return md(`Optional content group not found: ${n}`),!0;if(!ge(this,Th).get(n).visible)return!1}return!0}else if(t.policy==="AnyOff"){for(const n of t.ids){if(!ge(this,Th).has(n))return md(`Optional content group not found: ${n}`),!0;if(!ge(this,Th).get(n).visible)return!0}return!1}else if(t.policy==="AllOff"){for(const n of t.ids){if(!ge(this,Th).has(n))return md(`Optional content group not found: ${n}`),!0;if(ge(this,Th).get(n).visible)return!1}return!0}return md(`Unknown optional content policy ${t.policy}.`),!0}return md(`Unknown group type ${t.type}.`),!0}setVisibility(t,n=!0,r=!0){var i;const a=ge(this,Th).get(t);if(!a){md(`Optional content group not found: ${t}`);return}if(r&&n&&a.rbGroups.length)for(const l of a.rbGroups)for(const o of l)o!==t&&((i=ge(this,Th).get(o))==null||i._setVisible(G9,!1,!0));a._setVisible(G9,!!n,!0),$t(this,tT,null)}setOCGState({state:t,preserveRB:n}){let r;for(const a of t){switch(a){case"ON":case"OFF":case"Toggle":r=a;continue}const i=ge(this,Th).get(a);if(i)switch(r){case"ON":this.setVisibility(a,!0,n);break;case"OFF":this.setVisibility(a,!1,n);break;case"Toggle":this.setVisibility(a,!i.visible,n);break}}$t(this,tT,null)}get hasInitialVisibility(){return ge(this,j$)===null||this.getHash()===ge(this,j$)}getOrder(){return ge(this,Th).size?ge(this,N$)?ge(this,N$).slice():[...ge(this,Th).keys()]:null}getGroups(){return ge(this,Th).size>0?KXe(ge(this,Th)):null}getGroup(t){return ge(this,Th).get(t)||null}getHash(){if(ge(this,tT)!==null)return ge(this,tT);const t=new H$t;for(const[n,r]of ge(this,Th))t.update(`${n}:${r.visible}`);return $t(this,tT,t.hexdigest())}}tT=new WeakMap,Th=new WeakMap,j$=new WeakMap,N$=new WeakMap,aJ=new WeakSet,oUe=function(t){const n=t.length;if(n<2)return!0;const r=t[0];for(let a=1;a0){const c=i instanceof Uint8Array&&i.byteLength===i.buffer.byteLength?i.buffer:new Uint8Array(i).buffer;this._queuedChunks.push(c)}this._pdfDataRangeTransport=t,this._isStreamingSupported=!r,this._isRangeSupported=!n,this._contentLength=a,this._fullRequestReader=null,this._rangeReaders=[],t.addRangeListener((c,d)=>{this._onReceiveData({begin:c,chunk:d})}),t.addProgressListener((c,d)=>{this._onProgress({loaded:c,total:d})}),t.addProgressiveReadListener(c=>{this._onReceiveData({chunk:c})}),t.addProgressiveDoneListener(()=>{this._onProgressiveDone()}),t.transportReady()}_onReceiveData({begin:t,chunk:n}){const r=n instanceof Uint8Array&&n.byteLength===n.buffer.byteLength?n.buffer:new Uint8Array(n).buffer;if(t===void 0)this._fullRequestReader?this._fullRequestReader._enqueue(r):this._queuedChunks.push(r);else{const a=this._rangeReaders.some(function(i){return i._begin!==t?!1:(i._enqueue(r),!0)});yy(a,"_onReceiveData - no `PDFDataTransportStreamRangeReader` instance found.")}}get _progressiveDataLength(){var t;return((t=this._fullRequestReader)==null?void 0:t._loaded)??0}_onProgress(t){var n,r,a,i;t.total===void 0?(r=(n=this._rangeReaders[0])==null?void 0:n.onProgress)==null||r.call(n,{loaded:t.loaded}):(i=(a=this._fullRequestReader)==null?void 0:a.onProgress)==null||i.call(a,{loaded:t.loaded,total:t.total})}_onProgressiveDone(){var t;(t=this._fullRequestReader)==null||t.progressiveDone(),this._progressiveDone=!0}_removeRangeReader(t){const n=this._rangeReaders.indexOf(t);n>=0&&this._rangeReaders.splice(n,1)}getFullReader(){yy(!this._fullRequestReader,"PDFDataTransportStream.getFullReader can only be called once.");const t=this._queuedChunks;return this._queuedChunks=null,new s6n(this,t,this._progressiveDone,this._contentDispositionFilename)}getRangeReader(t,n){if(n<=this._progressiveDataLength)return null;const r=new n6n(this,t,n);return this._pdfDataRangeTransport.requestDataRange(t,n),this._rangeReaders.push(r),r}cancelAllRequests(t){var n;(n=this._fullRequestReader)==null||n.cancel(t);for(const r of this._rangeReaders.slice(0))r.cancel(t);this._pdfDataRangeTransport.abort()}}class s6n{constructor(t,n,r=!1,a=null){this._stream=t,this._done=r||!1,this._filename=XXe(a)?a:null,this._queuedChunks=n||[],this._loaded=0;for(const i of this._queuedChunks)this._loaded+=i.byteLength;this._requests=[],this._headersReady=Promise.resolve(),t._fullRequestReader=this,this.onProgress=null}_enqueue(t){this._done||(this._requests.length>0?this._requests.shift().resolve({value:t,done:!1}):this._queuedChunks.push(t),this._loaded+=t.byteLength)}get headersReady(){return this._headersReady}get filename(){return this._filename}get isRangeSupported(){return this._stream._isRangeSupported}get isStreamingSupported(){return this._stream._isStreamingSupported}get contentLength(){return this._stream._contentLength}async read(){if(this._queuedChunks.length>0)return{value:this._queuedChunks.shift(),done:!1};if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){this._done=!0;for(const n of this._requests)n.resolve({value:void 0,done:!0});this._requests.length=0}progressiveDone(){this._done||(this._done=!0)}}class n6n{constructor(t,n,r){this._stream=t,this._begin=n,this._end=r,this._queuedChunk=null,this._requests=[],this._done=!1,this.onProgress=null}_enqueue(t){if(!this._done){if(this._requests.length===0)this._queuedChunk=t;else{this._requests.shift().resolve({value:t,done:!1});for(const r of this._requests)r.resolve({value:void 0,done:!0});this._requests.length=0}this._done=!0,this._stream._removeRangeReader(this)}}get isStreamingSupported(){return!1}async read(){if(this._queuedChunk){const n=this._queuedChunk;return this._queuedChunk=null,{value:n,done:!1}}if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){this._done=!0;for(const n of this._requests)n.resolve({value:void 0,done:!0});this._requests.length=0,this._stream._removeRangeReader(this)}}function r6n(s){let t=!0,n=r("filename\\*","i").exec(s);if(n){n=n[1];let u=o(n);return u=unescape(u),u=c(u),u=d(u),i(u)}if(n=l(s),n){const u=d(n);return i(u)}if(n=r("filename","i").exec(s),n){n=n[1];let u=o(n);return u=d(u),i(u)}function r(u,h){return new RegExp("(?:^|;)\\s*"+u+'\\s*=\\s*([^";\\s][^;\\s]*|"(?:[^"\\\\]|\\\\"?)+"?)',h)}function a(u,h){if(u){if(!/^[\x00-\xFF]+$/.test(h))return h;try{const m=new TextDecoder(u,{fatal:!0}),p=OTe(h);h=m.decode(p),t=!1}catch{}}return h}function i(u){return t&&/[\x80-\xff]/.test(u)&&(u=a("utf-8",u),t&&(u=a("iso-8859-1",u))),u}function l(u){const h=[];let m;const p=r("filename\\*((?!0\\d)\\d+)(\\*?)","ig");for(;(m=p.exec(u))!==null;){let[,x,y,v]=m;if(x=parseInt(x,10),x in h){if(x===0)break;continue}h[x]=[y,v]}const g=[];for(let x=0;x{if(!aUt(i.status))throw BTe(i.status,a);this._reader=i.body.getReader(),this._headersCapability.resolve();const l=i.headers,{allowRangeRequests:o,suggestedLength:c}=nQe({responseHeaders:l,isHttp:t.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});this._isRangeSupported=o,this._contentLength=c||this._contentLength,this._filename=rQe(l),!this._isStreamingSupported&&this._isRangeSupported&&this.cancel(new ZF("Streaming is disabled."))}).catch(this._headersCapability.reject),this.onProgress=null}get headersReady(){return this._headersCapability.promise}get filename(){return this._filename}get contentLength(){return this._contentLength}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}async read(){var r;await this._headersCapability.promise;const{value:t,done:n}=await this._reader.read();return n?{value:t,done:n}:(this._loaded+=t.byteLength,(r=this.onProgress)==null||r.call(this,{loaded:this._loaded,total:this._contentLength}),{value:oUt(t),done:!1})}cancel(t){var n;(n=this._reader)==null||n.cancel(t),this._abortController.abort()}}class i6n{constructor(t,n,r){this._stream=t,this._reader=null,this._loaded=0;const a=t.source;this._withCredentials=a.withCredentials||!1,this._readCapability=Promise.withResolvers(),this._isStreamingSupported=!a.disableStream,this._abortController=new AbortController;const i=new Headers(t.headers);i.append("Range",`bytes=${n}-${r-1}`);const l=a.url;fetch(l,iUt(i,this._withCredentials,this._abortController)).then(o=>{if(!aUt(o.status))throw BTe(o.status,l);this._readCapability.resolve(),this._reader=o.body.getReader()}).catch(this._readCapability.reject),this.onProgress=null}get isStreamingSupported(){return this._isStreamingSupported}async read(){var r;await this._readCapability.promise;const{value:t,done:n}=await this._reader.read();return n?{value:t,done:n}:(this._loaded+=t.byteLength,(r=this.onProgress)==null||r.call(this,{loaded:this._loaded}),{value:oUt(t),done:!1})}cancel(t){var n;(n=this._reader)==null||n.cancel(t),this._abortController.abort()}}const zDe=200,BDe=206;function o6n(s){const t=s.response;return typeof t!="string"?t:OTe(t).buffer}class l6n{constructor({url:t,httpHeaders:n,withCredentials:r}){this.url=t,this.isHttp=/^https?:/i.test(t),this.headers=sQe(this.isHttp,n),this.withCredentials=r||!1,this.currXhrId=0,this.pendingRequests=Object.create(null)}requestRange(t,n,r){const a={begin:t,end:n};for(const i in r)a[i]=r[i];return this.request(a)}requestFull(t){return this.request(t)}request(t){const n=new XMLHttpRequest,r=this.currXhrId++,a=this.pendingRequests[r]={xhr:n};n.open("GET",this.url),n.withCredentials=this.withCredentials;for(const[i,l]of this.headers)n.setRequestHeader(i,l);return this.isHttp&&"begin"in t&&"end"in t?(n.setRequestHeader("Range",`bytes=${t.begin}-${t.end-1}`),a.expectedStatus=BDe):a.expectedStatus=zDe,n.responseType="arraybuffer",t.onError&&(n.onerror=function(i){t.onError(n.status)}),n.onreadystatechange=this.onStateChange.bind(this,r),n.onprogress=this.onProgress.bind(this,r),a.onHeadersReceived=t.onHeadersReceived,a.onDone=t.onDone,a.onError=t.onError,a.onProgress=t.onProgress,n.send(null),r}onProgress(t,n){var a;const r=this.pendingRequests[t];r&&((a=r.onProgress)==null||a.call(r,n))}onStateChange(t,n){var c,d,u;const r=this.pendingRequests[t];if(!r)return;const a=r.xhr;if(a.readyState>=2&&r.onHeadersReceived&&(r.onHeadersReceived(),delete r.onHeadersReceived),a.readyState!==4||!(t in this.pendingRequests))return;if(delete this.pendingRequests[t],a.status===0&&this.isHttp){(c=r.onError)==null||c.call(r,a.status);return}const i=a.status||zDe;if(!(i===zDe&&r.expectedStatus===BDe)&&i!==r.expectedStatus){(d=r.onError)==null||d.call(r,a.status);return}const o=o6n(a);if(i===BDe){const h=a.getResponseHeader("Content-Range"),m=/bytes (\d+)-(\d+)\/(\d+)/.exec(h);r.onDone({begin:parseInt(m[1],10),chunk:o})}else o?r.onDone({begin:0,chunk:o}):(u=r.onError)==null||u.call(r,a.status)}getRequestXhr(t){return this.pendingRequests[t].xhr}isPendingRequest(t){return t in this.pendingRequests}abortRequest(t){const n=this.pendingRequests[t].xhr;delete this.pendingRequests[t],n.abort()}}class c6n{constructor(t){this._source=t,this._manager=new l6n(t),this._rangeChunkSize=t.rangeChunkSize,this._fullRequestReader=null,this._rangeRequestReaders=[]}_onRangeRequestReaderClosed(t){const n=this._rangeRequestReaders.indexOf(t);n>=0&&this._rangeRequestReaders.splice(n,1)}getFullReader(){return yy(!this._fullRequestReader,"PDFNetworkStream.getFullReader can only be called once."),this._fullRequestReader=new d6n(this._manager,this._source),this._fullRequestReader}getRangeReader(t,n){const r=new u6n(this._manager,t,n);return r.onClosed=this._onRangeRequestReaderClosed.bind(this),this._rangeRequestReaders.push(r),r}cancelAllRequests(t){var n;(n=this._fullRequestReader)==null||n.cancel(t);for(const r of this._rangeRequestReaders.slice(0))r.cancel(t)}}class d6n{constructor(t,n){this._manager=t;const r={onHeadersReceived:this._onHeadersReceived.bind(this),onDone:this._onDone.bind(this),onError:this._onError.bind(this),onProgress:this._onProgress.bind(this)};this._url=n.url,this._fullRequestId=t.requestFull(r),this._headersCapability=Promise.withResolvers(),this._disableRange=n.disableRange||!1,this._contentLength=n.length,this._rangeChunkSize=n.rangeChunkSize,!this._rangeChunkSize&&!this._disableRange&&(this._disableRange=!0),this._isStreamingSupported=!1,this._isRangeSupported=!1,this._cachedChunks=[],this._requests=[],this._done=!1,this._storedError=void 0,this._filename=null,this.onProgress=null}_onHeadersReceived(){const t=this._fullRequestId,n=this._manager.getRequestXhr(t),r=new Headers(n.getAllResponseHeaders().trim().split(/[\r\n]+/).map(l=>{const[o,...c]=l.split(": ");return[o,c.join(": ")]})),{allowRangeRequests:a,suggestedLength:i}=nQe({responseHeaders:r,isHttp:this._manager.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});a&&(this._isRangeSupported=!0),this._contentLength=i||this._contentLength,this._filename=rQe(r),this._isRangeSupported&&this._manager.abortRequest(t),this._headersCapability.resolve()}_onDone(t){if(t&&(this._requests.length>0?this._requests.shift().resolve({value:t.chunk,done:!1}):this._cachedChunks.push(t.chunk)),this._done=!0,!(this._cachedChunks.length>0)){for(const n of this._requests)n.resolve({value:void 0,done:!0});this._requests.length=0}}_onError(t){this._storedError=BTe(t,this._url),this._headersCapability.reject(this._storedError);for(const n of this._requests)n.reject(this._storedError);this._requests.length=0,this._cachedChunks.length=0}_onProgress(t){var n;(n=this.onProgress)==null||n.call(this,{loaded:t.loaded,total:t.lengthComputable?t.total:this._contentLength})}get filename(){return this._filename}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}get contentLength(){return this._contentLength}get headersReady(){return this._headersCapability.promise}async read(){if(this._storedError)throw this._storedError;if(this._cachedChunks.length>0)return{value:this._cachedChunks.shift(),done:!1};if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){this._done=!0,this._headersCapability.reject(t);for(const n of this._requests)n.resolve({value:void 0,done:!0});this._requests.length=0,this._manager.isPendingRequest(this._fullRequestId)&&this._manager.abortRequest(this._fullRequestId),this._fullRequestReader=null}}class u6n{constructor(t,n,r){this._manager=t;const a={onDone:this._onDone.bind(this),onError:this._onError.bind(this),onProgress:this._onProgress.bind(this)};this._url=t.url,this._requestId=t.requestRange(n,r,a),this._requests=[],this._queuedChunk=null,this._done=!1,this._storedError=void 0,this.onProgress=null,this.onClosed=null}_close(){var t;(t=this.onClosed)==null||t.call(this,this)}_onDone(t){const n=t.chunk;this._requests.length>0?this._requests.shift().resolve({value:n,done:!1}):this._queuedChunk=n,this._done=!0;for(const r of this._requests)r.resolve({value:void 0,done:!0});this._requests.length=0,this._close()}_onError(t){this._storedError=BTe(t,this._url);for(const n of this._requests)n.reject(this._storedError);this._requests.length=0,this._queuedChunk=null}_onProgress(t){var n;this.isStreamingSupported||(n=this.onProgress)==null||n.call(this,{loaded:t.loaded})}get isStreamingSupported(){return!1}async read(){if(this._storedError)throw this._storedError;if(this._queuedChunk!==null){const n=this._queuedChunk;return this._queuedChunk=null,{value:n,done:!1}}if(this._done)return{value:void 0,done:!0};const t=Promise.withResolvers();return this._requests.push(t),t.promise}cancel(t){this._done=!0;for(const n of this._requests)n.resolve({value:void 0,done:!0});this._requests.length=0,this._manager.isPendingRequest(this._requestId)&&this._manager.abortRequest(this._requestId),this._close()}}const h6n=/^[a-z][a-z0-9\-+.]+:/i;function m6n(s){if(h6n.test(s))return new URL(s);const t=FM.get("url");return new URL(t.pathToFileURL(s))}function lUt(s,t,n){return s.protocol==="http:"?FM.get("http").request(s,{headers:t},n):FM.get("https").request(s,{headers:t},n)}class f6n{constructor(t){this.source=t,this.url=m6n(t.url),this.isHttp=this.url.protocol==="http:"||this.url.protocol==="https:",this.isFsUrl=this.url.protocol==="file:",this.headers=sQe(this.isHttp,t.httpHeaders),this._fullRequestReader=null,this._rangeRequestReaders=[]}get _progressiveDataLength(){var t;return((t=this._fullRequestReader)==null?void 0:t._loaded)??0}getFullReader(){return yy(!this._fullRequestReader,"PDFNodeStream.getFullReader can only be called once."),this._fullRequestReader=this.isFsUrl?new x6n(this):new p6n(this),this._fullRequestReader}getRangeReader(t,n){if(n<=this._progressiveDataLength)return null;const r=this.isFsUrl?new y6n(this,t,n):new g6n(this,t,n);return this._rangeRequestReaders.push(r),r}cancelAllRequests(t){var n;(n=this._fullRequestReader)==null||n.cancel(t);for(const r of this._rangeRequestReaders.slice(0))r.cancel(t)}}class cUt{constructor(t){this._url=t.url,this._done=!1,this._storedError=null,this.onProgress=null;const n=t.source;this._contentLength=n.length,this._loaded=0,this._filename=null,this._disableRange=n.disableRange||!1,this._rangeChunkSize=n.rangeChunkSize,!this._rangeChunkSize&&!this._disableRange&&(this._disableRange=!0),this._isStreamingSupported=!n.disableStream,this._isRangeSupported=!n.disableRange,this._readableStream=null,this._readCapability=Promise.withResolvers(),this._headersCapability=Promise.withResolvers()}get headersReady(){return this._headersCapability.promise}get filename(){return this._filename}get contentLength(){return this._contentLength}get isRangeSupported(){return this._isRangeSupported}get isStreamingSupported(){return this._isStreamingSupported}async read(){var r;if(await this._readCapability.promise,this._done)return{value:void 0,done:!0};if(this._storedError)throw this._storedError;const t=this._readableStream.read();return t===null?(this._readCapability=Promise.withResolvers(),this.read()):(this._loaded+=t.length,(r=this.onProgress)==null||r.call(this,{loaded:this._loaded,total:this._contentLength}),{value:new Uint8Array(t).buffer,done:!1})}cancel(t){if(!this._readableStream){this._error(t);return}this._readableStream.destroy(t)}_error(t){this._storedError=t,this._readCapability.resolve()}_setReadableStream(t){this._readableStream=t,t.on("readable",()=>{this._readCapability.resolve()}),t.on("end",()=>{t.destroy(),this._done=!0,this._readCapability.resolve()}),t.on("error",n=>{this._error(n)}),!this._isStreamingSupported&&this._isRangeSupported&&this._error(new ZF("streaming is disabled")),this._storedError&&this._readableStream.destroy(this._storedError)}}class dUt{constructor(t){this._url=t.url,this._done=!1,this._storedError=null,this.onProgress=null,this._loaded=0,this._readableStream=null,this._readCapability=Promise.withResolvers();const n=t.source;this._isStreamingSupported=!n.disableStream}get isStreamingSupported(){return this._isStreamingSupported}async read(){var r;if(await this._readCapability.promise,this._done)return{value:void 0,done:!0};if(this._storedError)throw this._storedError;const t=this._readableStream.read();return t===null?(this._readCapability=Promise.withResolvers(),this.read()):(this._loaded+=t.length,(r=this.onProgress)==null||r.call(this,{loaded:this._loaded}),{value:new Uint8Array(t).buffer,done:!1})}cancel(t){if(!this._readableStream){this._error(t);return}this._readableStream.destroy(t)}_error(t){this._storedError=t,this._readCapability.resolve()}_setReadableStream(t){this._readableStream=t,t.on("readable",()=>{this._readCapability.resolve()}),t.on("end",()=>{t.destroy(),this._done=!0,this._readCapability.resolve()}),t.on("error",n=>{this._error(n)}),this._storedError&&this._readableStream.destroy(this._storedError)}}class p6n extends cUt{constructor(t){super(t);const n=Object.fromEntries(t.headers),r=a=>{if(a.statusCode===404){const c=new YF(`Missing PDF "${this._url}".`);this._storedError=c,this._headersCapability.reject(c);return}this._headersCapability.resolve(),this._setReadableStream(a);const i=new Headers(this._readableStream.headers),{allowRangeRequests:l,suggestedLength:o}=nQe({responseHeaders:i,isHttp:t.isHttp,rangeChunkSize:this._rangeChunkSize,disableRange:this._disableRange});this._isRangeSupported=l,this._contentLength=o||this._contentLength,this._filename=rQe(i)};this._request=lUt(this._url,n,r),this._request.on("error",a=>{this._storedError=a,this._headersCapability.reject(a)}),this._request.end()}}class g6n extends dUt{constructor(t,n,r){super(t);const a=Object.fromEntries(t.headers);a.Range=`bytes=${n}-${r-1}`;const i=l=>{if(l.statusCode===404){const o=new YF(`Missing PDF "${this._url}".`);this._storedError=o;return}this._setReadableStream(l)};this._request=lUt(this._url,a,i),this._request.on("error",l=>{this._storedError=l}),this._request.end()}}class x6n extends cUt{constructor(t){super(t);const n=FM.get("fs");n.promises.lstat(this._url).then(r=>{this._contentLength=r.size,this._setReadableStream(n.createReadStream(this._url)),this._headersCapability.resolve()},r=>{r.code==="ENOENT"&&(r=new YF(`Missing PDF "${this._url}".`)),this._storedError=r,this._headersCapability.reject(r)})}}class y6n extends dUt{constructor(t,n,r){super(t);const a=FM.get("fs");this._setReadableStream(a.createReadStream(this._url,{start:n,end:r-1}))}}const v6n=1e5,Kb=30,b6n=.8;var i2t,sT,n_,iJ,oJ,QD,RC,lJ,cJ,JD,k$,S$,nT,C$,dJ,A$,e8,uJ,hJ,t8,s8,mJ,rT,E$,X3,uUt,hUt,lUe,oj,VNe,cUe,mUt,fUt;const oy=class oy{constructor({textContentSource:t,container:n,viewport:r}){ds(this,X3);ds(this,sT,Promise.withResolvers());ds(this,n_,null);ds(this,iJ,!1);ds(this,oJ,!!((i2t=globalThis.FontInspector)!=null&&i2t.enabled));ds(this,QD,null);ds(this,RC,null);ds(this,lJ,0);ds(this,cJ,0);ds(this,JD,null);ds(this,k$,null);ds(this,S$,0);ds(this,nT,0);ds(this,C$,Object.create(null));ds(this,dJ,[]);ds(this,A$,null);ds(this,e8,[]);ds(this,uJ,new WeakMap);ds(this,hJ,null);var c;if(t instanceof ReadableStream)$t(this,A$,t);else if(typeof t=="object")$t(this,A$,new ReadableStream({start(d){d.enqueue(t),d.close()}}));else throw new Error('No "textContentSource" parameter specified.');$t(this,n_,$t(this,k$,n)),$t(this,nT,r.scale*(globalThis.devicePixelRatio||1)),$t(this,S$,r.rotation),$t(this,RC,{div:null,properties:null,ctx:null});const{pageWidth:a,pageHeight:i,pageX:l,pageY:o}=r.rawDims;$t(this,hJ,[1,0,0,-1,-l,o+i]),$t(this,cJ,a),$t(this,lJ,i),ss(c=oy,oj,mUt).call(c),aF(n,r),ge(this,sT).promise.finally(()=>{ge(oy,E$).delete(this),$t(this,RC,null),$t(this,C$,null)}).catch(()=>{})}static get fontFamilyMap(){const{isWindows:t,isFirefox:n}=_b.platform;return nu(this,"fontFamilyMap",new Map([["sans-serif",`${t&&n?"Calibri, ":""}sans-serif`],["monospace",`${t&&n?"Lucida Console, ":""}monospace`]]))}render(){const t=()=>{ge(this,JD).read().then(({value:n,done:r})=>{if(r){ge(this,sT).resolve();return}ge(this,QD)??$t(this,QD,n.lang),Object.assign(ge(this,C$),n.styles),ss(this,X3,uUt).call(this,n.items),t()},ge(this,sT).reject)};return $t(this,JD,ge(this,A$).getReader()),ge(oy,E$).add(this),t(),ge(this,sT).promise}update({viewport:t,onBefore:n=null}){var i;const r=t.scale*(globalThis.devicePixelRatio||1),a=t.rotation;if(a!==ge(this,S$)&&(n==null||n(),$t(this,S$,a),aF(ge(this,k$),{rotation:a})),r!==ge(this,nT)){n==null||n(),$t(this,nT,r);const l={div:null,properties:null,ctx:ss(i=oy,oj,VNe).call(i,ge(this,QD))};for(const o of ge(this,e8))l.properties=ge(this,uJ).get(o),l.div=o,ss(this,X3,lUe).call(this,l)}}cancel(){var n;const t=new ZF("TextLayer task cancelled.");(n=ge(this,JD))==null||n.cancel(t).catch(()=>{}),$t(this,JD,null),ge(this,sT).reject(t)}get textDivs(){return ge(this,e8)}get textContentItemsStr(){return ge(this,dJ)}static cleanup(){if(!(ge(this,E$).size>0)){ge(this,t8).clear();for(const{canvas:t}of ge(this,s8).values())t.remove();ge(this,s8).clear()}}};sT=new WeakMap,n_=new WeakMap,iJ=new WeakMap,oJ=new WeakMap,QD=new WeakMap,RC=new WeakMap,lJ=new WeakMap,cJ=new WeakMap,JD=new WeakMap,k$=new WeakMap,S$=new WeakMap,nT=new WeakMap,C$=new WeakMap,dJ=new WeakMap,A$=new WeakMap,e8=new WeakMap,uJ=new WeakMap,hJ=new WeakMap,t8=new WeakMap,s8=new WeakMap,mJ=new WeakMap,rT=new WeakMap,E$=new WeakMap,X3=new WeakSet,uUt=function(t){var a,i;if(ge(this,iJ))return;(i=ge(this,RC)).ctx??(i.ctx=ss(a=oy,oj,VNe).call(a,ge(this,QD)));const n=ge(this,e8),r=ge(this,dJ);for(const l of t){if(n.length>v6n){md("Ignoring additional textDivs for performance reasons."),$t(this,iJ,!0);return}if(l.str===void 0){if(l.type==="beginMarkedContentProps"||l.type==="beginMarkedContent"){const o=ge(this,n_);$t(this,n_,document.createElement("span")),ge(this,n_).classList.add("markedContent"),l.id!==null&&ge(this,n_).setAttribute("id",`${l.id}`),o.append(ge(this,n_))}else l.type==="endMarkedContent"&&$t(this,n_,ge(this,n_).parentNode);continue}r.push(l.str),ss(this,X3,hUt).call(this,l)}},hUt=function(t){var x;const n=document.createElement("span"),r={angle:0,canvasWidth:0,hasText:t.str!=="",hasEOL:t.hasEOL,fontSize:0};ge(this,e8).push(n);const a=Ko.transform(ge(this,hJ),t.transform);let i=Math.atan2(a[1],a[0]);const l=ge(this,C$)[t.fontName];l.vertical&&(i+=Math.PI/2);let o=ge(this,oJ)&&l.fontSubstitution||l.fontFamily;o=oy.fontFamilyMap.get(o)||o;const c=Math.hypot(a[2],a[3]),d=c*ss(x=oy,oj,fUt).call(x,o,ge(this,QD));let u,h;i===0?(u=a[4],h=a[5]-d):(u=a[4]+d*Math.sin(i),h=a[5]-d*Math.cos(i));const m="calc(var(--scale-factor)*",p=n.style;ge(this,n_)===ge(this,k$)?(p.left=`${(100*u/ge(this,cJ)).toFixed(2)}%`,p.top=`${(100*h/ge(this,lJ)).toFixed(2)}%`):(p.left=`${m}${u.toFixed(2)}px)`,p.top=`${m}${h.toFixed(2)}px)`),p.fontSize=`${m}${(ge(oy,rT)*c).toFixed(2)}px)`,p.fontFamily=o,r.fontSize=c,n.setAttribute("role","presentation"),n.textContent=t.str,n.dir=t.dir,ge(this,oJ)&&(n.dataset.fontName=l.fontSubstitutionLoadedName||t.fontName),i!==0&&(r.angle=i*(180/Math.PI));let g=!1;if(t.str.length>1)g=!0;else if(t.str!==" "&&t.transform[0]!==t.transform[3]){const y=Math.abs(t.transform[0]),v=Math.abs(t.transform[3]);y!==v&&Math.max(y,v)/Math.min(y,v)>1.5&&(g=!0)}if(g&&(r.canvasWidth=l.vertical?t.height:t.width),ge(this,uJ).set(n,r),ge(this,RC).div=n,ge(this,RC).properties=r,ss(this,X3,lUe).call(this,ge(this,RC)),r.hasText&&ge(this,n_).append(n),r.hasEOL){const y=document.createElement("br");y.setAttribute("role","presentation"),ge(this,n_).append(y)}},lUe=function(t){var o;const{div:n,properties:r,ctx:a}=t,{style:i}=n;let l="";if(ge(oy,rT)>1&&(l=`scale(${1/ge(oy,rT)})`),r.canvasWidth!==0&&r.hasText){const{fontFamily:c}=i,{canvasWidth:d,fontSize:u}=r;ss(o=oy,oj,cUe).call(o,a,u*ge(this,nT),c);const{width:h}=a.measureText(n.textContent);h>0&&(l=`scaleX(${d*ge(this,nT)/h}) ${l}`)}r.angle!==0&&(l=`rotate(${r.angle}deg) ${l}`),l.length>0&&(i.transform=l)},oj=new WeakSet,VNe=function(t=null){let n=ge(this,s8).get(t||(t=""));if(!n){const r=document.createElement("canvas");r.className="hiddenCanvasElement",r.lang=t,document.body.append(r),n=r.getContext("2d",{alpha:!1,willReadFrequently:!0}),ge(this,s8).set(t,n),ge(this,mJ).set(n,{size:0,family:""})}return n},cUe=function(t,n,r){const a=ge(this,mJ).get(t);n===a.size&&r===a.family||(t.font=`${n}px ${r}`,a.size=n,a.family=r)},mUt=function(){if(ge(this,rT)!==null)return;const t=document.createElement("div");t.style.opacity=0,t.style.lineHeight=1,t.style.fontSize="1px",t.style.position="absolute",t.textContent="X",document.body.append(t),$t(this,rT,t.getBoundingClientRect().height),t.remove()},fUt=function(t,n){const r=ge(this,t8).get(t);if(r)return r;const a=ss(this,oj,VNe).call(this,n);a.canvas.width=a.canvas.height=Kb,ss(this,oj,cUe).call(this,a,Kb,t);const i=a.measureText("");let l=i.fontBoundingBoxAscent,o=Math.abs(i.fontBoundingBoxDescent);if(l){const u=l/(l+o);return ge(this,t8).set(t,u),a.canvas.width=a.canvas.height=0,u}a.strokeStyle="red",a.clearRect(0,0,Kb,Kb),a.strokeText("g",0,0);let c=a.getImageData(0,0,Kb,Kb).data;o=0;for(let u=c.length-1-3;u>=0;u-=4)if(c[u]>0){o=Math.ceil(u/4/Kb);break}a.clearRect(0,0,Kb,Kb),a.strokeText("A",0,Kb),c=a.getImageData(0,0,Kb,Kb).data,l=0;for(let u=0,h=c.length;u0){l=Kb-Math.floor(u/4/Kb);break}a.canvas.width=a.canvas.height=0;const d=l?l/(l+o):b6n;return ge(this,t8).set(t,d),d},ds(oy,oj),ds(oy,t8,new Map),ds(oy,s8,new Map),ds(oy,mJ,new WeakMap),ds(oy,rT,null),ds(oy,E$,new Set);let hQ=oy;class mQ{static textContent(t){const n=[],r={items:n,styles:Object.create(null)};function a(i){var c;if(!i)return;let l=null;const o=i.name;if(o==="#text")l=i.value;else if(mQ.shouldBuildText(o))(c=i==null?void 0:i.attributes)!=null&&c.textContent?l=i.attributes.textContent:i.value&&(l=i.value);else return;if(l!==null&&n.push({str:l}),!!i.children)for(const d of i.children)a(d)}return a(t),r}static shouldBuildText(t){return!(t==="textarea"||t==="input"||t==="option"||t==="select")}}const _6n=65536,w6n=100,j6n=5e3,N6n=c1?DMn:IMn,k6n=c1?OMn:Z$t,S6n=c1?RMn:LMn,C6n=c1?FMn:eUt;function A6n(s={}){typeof s=="string"||s instanceof URL?s={url:s}:(s instanceof ArrayBuffer||ArrayBuffer.isView(s))&&(s={data:s});const t=new dUe,{docId:n}=t,r=s.url?E6n(s.url):null,a=s.data?T6n(s.data):null,i=s.httpHeaders||null,l=s.withCredentials===!0,o=s.password??null,c=s.range instanceof pUt?s.range:null,d=Number.isInteger(s.rangeChunkSize)&&s.rangeChunkSize>0?s.rangeChunkSize:_6n;let u=s.worker instanceof UB?s.worker:null;const h=s.verbosity,m=typeof s.docBaseUrl=="string"&&!zTe(s.docBaseUrl)?s.docBaseUrl:null,p=typeof s.cMapUrl=="string"?s.cMapUrl:null,g=s.cMapPacked!==!1,x=s.CMapReaderFactory||k6n,y=typeof s.standardFontDataUrl=="string"?s.standardFontDataUrl:null,v=s.StandardFontDataFactory||C6n,_=s.stopAtErrors!==!0,j=Number.isInteger(s.maxImageSize)&&s.maxImageSize>-1?s.maxImageSize:-1,C=s.isEvalSupported!==!1,A=typeof s.isOffscreenCanvasSupported=="boolean"?s.isOffscreenCanvasSupported:!c1,M=typeof s.isChrome=="boolean"?s.isChrome:!_b.platform.isFirefox&&typeof window<"u"&&!!(window!=null&&window.chrome),I=Number.isInteger(s.canvasMaxAreaInBytes)?s.canvasMaxAreaInBytes:-1,P=typeof s.disableFontFace=="boolean"?s.disableFontFace:c1,R=s.fontExtraProperties===!0,O=s.enableXfa===!0,B=s.ownerDocument||globalThis.document,U=s.disableRange===!0,G=s.disableStream===!0,H=s.disableAutoFetch===!0,Y=s.pdfBug===!0,se=s.CanvasFactory||N6n,ee=s.FilterFactory||S6n,oe=s.enableHWA===!0,me=c?c.length:s.length??NaN,Q=typeof s.useSystemFonts=="boolean"?s.useSystemFonts:!c1&&!P,te=typeof s.useWorkerFetch=="boolean"?s.useWorkerFetch:x===Z$t&&v===eUt&&p&&y&&BW(p,document.baseURI)&&BW(y,document.baseURI);s.canvasFactory&&b1t("`canvasFactory`-instance option, please use `CanvasFactory` instead."),s.filterFactory&&b1t("`filterFactory`-instance option, please use `FilterFactory` instead.");const le=null;dMn(h);const fe={canvasFactory:new se({ownerDocument:B,enableHWA:oe}),filterFactory:new ee({docId:n,ownerDocument:B}),cMapReaderFactory:te?null:new x({baseUrl:p,isCompressed:g}),standardFontDataFactory:te?null:new v({baseUrl:y})};if(!u){const he={verbosity:h,port:e3.workerPort};u=he.port?UB.fromPort(he):new UB(he),t._worker=u}const _e={docId:n,apiVersion:"4.8.69",data:a,password:o,disableAutoFetch:H,rangeChunkSize:d,length:me,docBaseUrl:m,enableXfa:O,evaluatorOptions:{maxImageSize:j,disableFontFace:P,ignoreErrors:_,isEvalSupported:C,isOffscreenCanvasSupported:A,isChrome:M,canvasMaxAreaInBytes:I,fontExtraProperties:R,useSystemFonts:Q,cMapUrl:te?p:null,standardFontDataUrl:te?y:null}},ve={disableFontFace:P,fontExtraProperties:R,ownerDocument:B,pdfBug:Y,styleElement:le,loadingParams:{disableAutoFetch:H,enableXfa:O}};return u.promise.then(function(){if(t.destroyed)throw new Error("Loading aborted");if(u.destroyed)throw new Error("Worker was destroyed");const he=u.messageHandler.sendWithPromise("GetDocRequest",_e,a?[a.buffer]:null);let Se;if(c)Se=new t6n(c,{disableRange:U,disableStream:G});else if(!a){if(!r)throw new Error("getDocument - no `url` parameter provided.");let Te;c1?Te=typeof fetch<"u"&&typeof Response<"u"&&"body"in Response.prototype&&BW(r)?P1t:f6n:Te=BW(r)?P1t:c6n,Se=new Te({url:r,length:me,httpHeaders:i,withCredentials:l,rangeChunkSize:d,disableRange:U,disableStream:G})}return he.then(Te=>{if(t.destroyed)throw new Error("Loading aborted");if(u.destroyed)throw new Error("Worker was destroyed");const Ie=new WW(n,Te,u.port),Ue=new L6n(Ie,t,Se,ve,fe);t._transport=Ue,Ie.send("Ready",null)})}).catch(t._capability.reject),t}function E6n(s){if(s instanceof URL)return s.href;try{return new URL(s,window.location).href}catch{if(c1&&typeof s=="string")return s}throw new Error("Invalid PDF url data: either string or URL-object is expected in the url property.")}function T6n(s){if(c1&&typeof Buffer<"u"&&s instanceof Buffer)throw new Error("Please provide binary data as `Uint8Array`, rather than `Buffer`.");if(s instanceof Uint8Array&&s.byteLength===s.buffer.byteLength)return s;if(typeof s=="string")return OTe(s);if(s instanceof ArrayBuffer||ArrayBuffer.isView(s)||typeof s=="object"&&!isNaN(s==null?void 0:s.length))return new Uint8Array(s);throw new Error("Invalid PDF binary data: either TypedArray, string, or array-like object is expected in the data property.")}function I1t(s){return typeof s=="object"&&Number.isInteger(s==null?void 0:s.num)&&s.num>=0&&Number.isInteger(s==null?void 0:s.gen)&&s.gen>=0}var TCe;const MCe=class MCe{constructor(){this._capability=Promise.withResolvers(),this._transport=null,this._worker=null,this.docId=`d${Hy(MCe,TCe)._++}`,this.destroyed=!1,this.onPassword=null,this.onProgress=null}get promise(){return this._capability.promise}async destroy(){var t,n,r;this.destroyed=!0;try{(t=this._worker)!=null&&t.port&&(this._worker._pendingDestroy=!0),await((n=this._transport)==null?void 0:n.destroy())}catch(a){throw(r=this._worker)!=null&&r.port&&delete this._worker._pendingDestroy,a}this._transport=null,this._worker&&(this._worker.destroy(),this._worker=null)}};TCe=new WeakMap,ds(MCe,TCe,0);let dUe=MCe;class pUt{constructor(t,n,r=!1,a=null){this.length=t,this.initialData=n,this.progressiveDone=r,this.contentDispositionFilename=a,this._rangeListeners=[],this._progressListeners=[],this._progressiveReadListeners=[],this._progressiveDoneListeners=[],this._readyCapability=Promise.withResolvers()}addRangeListener(t){this._rangeListeners.push(t)}addProgressListener(t){this._progressListeners.push(t)}addProgressiveReadListener(t){this._progressiveReadListeners.push(t)}addProgressiveDoneListener(t){this._progressiveDoneListeners.push(t)}onDataRange(t,n){for(const r of this._rangeListeners)r(t,n)}onDataProgress(t,n){this._readyCapability.promise.then(()=>{for(const r of this._progressListeners)r(t,n)})}onDataProgressiveRead(t){this._readyCapability.promise.then(()=>{for(const n of this._progressiveReadListeners)n(t)})}onDataProgressiveDone(){this._readyCapability.promise.then(()=>{for(const t of this._progressiveDoneListeners)t()})}transportReady(){this._readyCapability.resolve()}requestDataRange(t,n){wf("Abstract method PDFDataRangeTransport.requestDataRange")}abort(){}}class M6n{constructor(t,n){this._pdfInfo=t,this._transport=n}get annotationStorage(){return this._transport.annotationStorage}get canvasFactory(){return this._transport.canvasFactory}get filterFactory(){return this._transport.filterFactory}get numPages(){return this._pdfInfo.numPages}get fingerprints(){return this._pdfInfo.fingerprints}get isPureXfa(){return nu(this,"isPureXfa",!!this._transport._htmlForXfa)}get allXfaHtml(){return this._transport._htmlForXfa}getPage(t){return this._transport.getPage(t)}getPageIndex(t){return this._transport.getPageIndex(t)}getDestinations(){return this._transport.getDestinations()}getDestination(t){return this._transport.getDestination(t)}getPageLabels(){return this._transport.getPageLabels()}getPageLayout(){return this._transport.getPageLayout()}getPageMode(){return this._transport.getPageMode()}getViewerPreferences(){return this._transport.getViewerPreferences()}getOpenAction(){return this._transport.getOpenAction()}getAttachments(){return this._transport.getAttachments()}getJSActions(){return this._transport.getDocJSActions()}getOutline(){return this._transport.getOutline()}getOptionalContentConfig({intent:t="display"}={}){const{renderingIntent:n}=this._transport.getRenderingIntent(t);return this._transport.getOptionalContentConfig(n)}getPermissions(){return this._transport.getPermissions()}getMetadata(){return this._transport.getMetadata()}getMarkInfo(){return this._transport.getMarkInfo()}getData(){return this._transport.getData()}saveDocument(){return this._transport.saveDocument()}getDownloadInfo(){return this._transport.downloadInfoCapability.promise}cleanup(t=!1){return this._transport.startCleanup(t||this.isPureXfa)}destroy(){return this.loadingTask.destroy()}cachedPageNumber(t){return this._transport.cachedPageNumber(t)}get loadingParams(){return this._transport.loadingParams}get loadingTask(){return this._transport.loadingTask}getFieldObjects(){return this._transport.getFieldObjects()}hasJSActions(){return this._transport.hasJSActions()}getCalculationOrderIds(){return this._transport.getCalculationOrderIds()}}var aT,DC,d2,W9,HNe;class P6n{constructor(t,n,r,a=!1){ds(this,d2);ds(this,aT,null);ds(this,DC,!1);this._pageIndex=t,this._pageInfo=n,this._transport=r,this._stats=a?new v1t:null,this._pdfBug=a,this.commonObjs=r.commonObjs,this.objs=new gUt,this._maybeCleanupAfterRender=!1,this._intentStates=new Map,this.destroyed=!1}get pageNumber(){return this._pageIndex+1}get rotate(){return this._pageInfo.rotate}get ref(){return this._pageInfo.ref}get userUnit(){return this._pageInfo.userUnit}get view(){return this._pageInfo.view}getViewport({scale:t,rotation:n=this.rotate,offsetX:r=0,offsetY:a=0,dontFlip:i=!1}={}){return new xte({viewBox:this.view,scale:t,rotation:n,offsetX:r,offsetY:a,dontFlip:i})}getAnnotations({intent:t="display"}={}){const{renderingIntent:n}=this._transport.getRenderingIntent(t);return this._transport.getAnnotations(this._pageIndex,n)}getJSActions(){return this._transport.getPageJSActions(this._pageIndex)}get filterFactory(){return this._transport.filterFactory}get isPureXfa(){return nu(this,"isPureXfa",!!this._transport._htmlForXfa)}async getXfa(){var t;return((t=this._transport._htmlForXfa)==null?void 0:t.children[this._pageIndex])||null}render({canvasContext:t,viewport:n,intent:r="display",annotationMode:a=LE.ENABLE,transform:i=null,background:l=null,optionalContentConfigPromise:o=null,annotationCanvasMap:c=null,pageColors:d=null,printAnnotationStorage:u=null,isEditing:h=!1}){var C,A;(C=this._stats)==null||C.time("Overall");const m=this._transport.getRenderingIntent(r,a,u,h),{renderingIntent:p,cacheKey:g}=m;$t(this,DC,!1),ss(this,d2,HNe).call(this),o||(o=this._transport.getOptionalContentConfig(p));let x=this._intentStates.get(g);x||(x=Object.create(null),this._intentStates.set(g,x)),x.streamReaderCancelTimeout&&(clearTimeout(x.streamReaderCancelTimeout),x.streamReaderCancelTimeout=null);const y=!!(p&Mw.PRINT);x.displayReadyCapability||(x.displayReadyCapability=Promise.withResolvers(),x.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null},(A=this._stats)==null||A.time("Page Request"),this._pumpOperatorList(m));const v=M=>{var I;x.renderTasks.delete(_),(this._maybeCleanupAfterRender||y)&&$t(this,DC,!0),ss(this,d2,W9).call(this,!y),M?(_.capability.reject(M),this._abortOperatorList({intentState:x,reason:M instanceof Error?M:new Error(M)})):_.capability.resolve(),this._stats&&(this._stats.timeEnd("Rendering"),this._stats.timeEnd("Overall"),(I=globalThis.Stats)!=null&&I.enabled&&globalThis.Stats.add(this.pageNumber,this._stats))},_=new hUe({callback:v,params:{canvasContext:t,viewport:n,transform:i,background:l},objs:this.objs,commonObjs:this.commonObjs,annotationCanvasMap:c,operatorList:x.operatorList,pageIndex:this._pageIndex,canvasFactory:this._transport.canvasFactory,filterFactory:this._transport.filterFactory,useRequestAnimationFrame:!y,pdfBug:this._pdfBug,pageColors:d});(x.renderTasks||(x.renderTasks=new Set)).add(_);const j=_.task;return Promise.all([x.displayReadyCapability.promise,o]).then(([M,I])=>{var P;if(this.destroyed){v();return}if((P=this._stats)==null||P.time("Rendering"),!(I.renderingIntent&p))throw new Error("Must use the same `intent`-argument when calling the `PDFPageProxy.render` and `PDFDocumentProxy.getOptionalContentConfig` methods.");_.initializeGraphics({transparency:M,optionalContentConfig:I}),_.operatorListChanged()}).catch(v),j}getOperatorList({intent:t="display",annotationMode:n=LE.ENABLE,printAnnotationStorage:r=null,isEditing:a=!1}={}){var d;function i(){o.operatorList.lastChunk&&(o.opListReadCapability.resolve(o.operatorList),o.renderTasks.delete(c))}const l=this._transport.getRenderingIntent(t,n,r,a,!0);let o=this._intentStates.get(l.cacheKey);o||(o=Object.create(null),this._intentStates.set(l.cacheKey,o));let c;return o.opListReadCapability||(c=Object.create(null),c.operatorListChanged=i,o.opListReadCapability=Promise.withResolvers(),(o.renderTasks||(o.renderTasks=new Set)).add(c),o.operatorList={fnArray:[],argsArray:[],lastChunk:!1,separateAnnots:null},(d=this._stats)==null||d.time("Page Request"),this._pumpOperatorList(l)),o.opListReadCapability.promise}streamTextContent({includeMarkedContent:t=!1,disableNormalization:n=!1}={}){return this._transport.messageHandler.sendWithStream("GetTextContent",{pageIndex:this._pageIndex,includeMarkedContent:t===!0,disableNormalization:n===!0},{highWaterMark:100,size(a){return a.items.length}})}getTextContent(t={}){if(this._transport._htmlForXfa)return this.getXfa().then(r=>mQ.textContent(r));const n=this.streamTextContent(t);return new Promise(function(r,a){function i(){l.read().then(function({value:c,done:d}){if(d){r(o);return}o.lang??(o.lang=c.lang),Object.assign(o.styles,c.styles),o.items.push(...c.items),i()},a)}const l=n.getReader(),o={items:[],styles:Object.create(null),lang:null};i()})}getStructTree(){return this._transport.getStructTree(this._pageIndex)}_destroy(){this.destroyed=!0;const t=[];for(const n of this._intentStates.values())if(this._abortOperatorList({intentState:n,reason:new Error("Page was destroyed."),force:!0}),!n.opListReadCapability)for(const r of n.renderTasks)t.push(r.completed),r.cancel();return this.objs.clear(),$t(this,DC,!1),ss(this,d2,HNe).call(this),Promise.all(t)}cleanup(t=!1){$t(this,DC,!0);const n=ss(this,d2,W9).call(this,!1);return t&&n&&this._stats&&(this._stats=new v1t),n}_startRenderPage(t,n){var a,i;const r=this._intentStates.get(n);r&&((a=this._stats)==null||a.timeEnd("Page Request"),(i=r.displayReadyCapability)==null||i.resolve(t))}_renderPageChunk(t,n){for(let r=0,a=t.length;r{c.read().then(({value:h,done:m})=>{if(m){d.streamReader=null;return}this._transport.destroyed||(this._renderPageChunk(h,d),u())},h=>{if(d.streamReader=null,!this._transport.destroyed){if(d.operatorList){d.operatorList.lastChunk=!0;for(const m of d.renderTasks)m.operatorListChanged();ss(this,d2,W9).call(this,!0)}if(d.displayReadyCapability)d.displayReadyCapability.reject(h);else if(d.opListReadCapability)d.opListReadCapability.reject(h);else throw h}})};u()}_abortOperatorList({intentState:t,reason:n,force:r=!1}){if(t.streamReader){if(t.streamReaderCancelTimeout&&(clearTimeout(t.streamReaderCancelTimeout),t.streamReaderCancelTimeout=null),!r){if(t.renderTasks.size>0)return;if(n instanceof ZXe){let a=w6n;n.extraDelay>0&&n.extraDelay<1e3&&(a+=n.extraDelay),t.streamReaderCancelTimeout=setTimeout(()=>{t.streamReaderCancelTimeout=null,this._abortOperatorList({intentState:t,reason:n,force:!0})},a);return}}if(t.streamReader.cancel(new ZF(n.message)).catch(()=>{}),t.streamReader=null,!this._transport.destroyed){for(const[a,i]of this._intentStates)if(i===t){this._intentStates.delete(a);break}this.cleanup()}}}get stats(){return this._stats}}aT=new WeakMap,DC=new WeakMap,d2=new WeakSet,W9=function(t=!1){if(ss(this,d2,HNe).call(this),!ge(this,DC)||this.destroyed)return!1;if(t)return $t(this,aT,setTimeout(()=>{$t(this,aT,null),ss(this,d2,W9).call(this,!1)},j6n)),!1;for(const{renderTasks:n,operatorList:r}of this._intentStates.values())if(n.size>0||!r.lastChunk)return!1;return this._intentStates.clear(),this.objs.clear(),$t(this,DC,!1),!0},HNe=function(){ge(this,aT)&&(clearTimeout(ge(this,aT)),$t(this,aT,null))};var OC,PCe;class I6n{constructor(){ds(this,OC,new Map);ds(this,PCe,Promise.resolve())}postMessage(t,n){const r={data:structuredClone(t,n?{transfer:n}:null)};ge(this,PCe).then(()=>{for(const[a]of ge(this,OC))a.call(this,r)})}addEventListener(t,n,r=null){let a=null;if((r==null?void 0:r.signal)instanceof AbortSignal){const{signal:i}=r;if(i.aborted){md("LoopbackPort - cannot use an `aborted` signal.");return}const l=()=>this.removeEventListener(t,n);a=()=>i.removeEventListener("abort",l),i.addEventListener("abort",l)}ge(this,OC).set(n,a)}removeEventListener(t,n){const r=ge(this,OC).get(n);r==null||r(),ge(this,OC).delete(n)}terminate(){for(const[,t]of ge(this,OC))t==null||t();ge(this,OC).clear()}}OC=new WeakMap,PCe=new WeakMap;var ICe,n8,r8,T$,GNe,M$,WNe;const Wf=class Wf{constructor({name:t=null,port:n=null,verbosity:r=uMn()}={}){ds(this,T$);var a;if(this.name=t,this.destroyed=!1,this.verbosity=r,this._readyCapability=Promise.withResolvers(),this._port=null,this._webWorker=null,this._messageHandler=null,n){if((a=ge(Wf,r8))!=null&&a.has(n))throw new Error("Cannot use more than one PDFWorker per port.");(ge(Wf,r8)||$t(Wf,r8,new WeakMap)).set(n,this),this._initializeFromPort(n);return}this._initialize()}get promise(){return c1?Promise.all([FM.promise,this._readyCapability.promise]):this._readyCapability.promise}get port(){return this._port}get messageHandler(){return this._messageHandler}_initializeFromPort(t){this._port=t,this._messageHandler=new WW("main","worker",t),this._messageHandler.on("ready",function(){}),ss(this,T$,GNe).call(this)}_initialize(){if(ge(Wf,n8)||ge(Wf,M$,WNe)){this._setupFakeWorker();return}let{workerSrc:t}=Wf;try{Wf._isSameOrigin(window.location.href,t)||(t=Wf._createCDNWrapper(new URL(t,window.location).href));const n=new Worker(t,{type:"module"}),r=new WW("main","worker",n),a=()=>{i.abort(),r.destroy(),n.terminate(),this.destroyed?this._readyCapability.reject(new Error("Worker was destroyed")):this._setupFakeWorker()},i=new AbortController;n.addEventListener("error",()=>{this._webWorker||a()},{signal:i.signal}),r.on("test",o=>{if(i.abort(),this.destroyed||!o){a();return}this._messageHandler=r,this._port=n,this._webWorker=n,ss(this,T$,GNe).call(this)}),r.on("ready",o=>{if(i.abort(),this.destroyed){a();return}try{l()}catch{this._setupFakeWorker()}});const l=()=>{const o=new Uint8Array;r.send("test",o,[o.buffer])};l();return}catch{RTe("The worker has been disabled.")}this._setupFakeWorker()}_setupFakeWorker(){ge(Wf,n8)||(md("Setting up fake worker."),$t(Wf,n8,!0)),Wf._setupFakeWorkerGlobal.then(t=>{if(this.destroyed){this._readyCapability.reject(new Error("Worker was destroyed"));return}const n=new I6n;this._port=n;const r=`fake${Hy(Wf,ICe)._++}`,a=new WW(r+"_worker",r,n);t.setup(a,n),this._messageHandler=new WW(r,r+"_worker",n),ss(this,T$,GNe).call(this)}).catch(t=>{this._readyCapability.reject(new Error(`Setting up fake worker failed: "${t.message}".`))})}destroy(){var t;this.destroyed=!0,this._webWorker&&(this._webWorker.terminate(),this._webWorker=null),(t=ge(Wf,r8))==null||t.delete(this._port),this._port=null,this._messageHandler&&(this._messageHandler.destroy(),this._messageHandler=null)}static fromPort(t){var r;if(!(t!=null&&t.port))throw new Error("PDFWorker.fromPort - invalid method signature.");const n=(r=ge(this,r8))==null?void 0:r.get(t.port);if(n){if(n._pendingDestroy)throw new Error("PDFWorker.fromPort - the worker is being destroyed.\nPlease remember to await `PDFDocumentLoadingTask.destroy()`-calls.");return n}return new Wf(t)}static get workerSrc(){if(e3.workerSrc)return e3.workerSrc;throw new Error('No "GlobalWorkerOptions.workerSrc" specified.')}static get _setupFakeWorkerGlobal(){return nu(this,"_setupFakeWorkerGlobal",(async()=>ge(this,M$,WNe)?ge(this,M$,WNe):(await import(this.workerSrc)).WorkerMessageHandler)())}};ICe=new WeakMap,n8=new WeakMap,r8=new WeakMap,T$=new WeakSet,GNe=function(){this._readyCapability.resolve(),this._messageHandler.send("configure",{verbosity:this.verbosity})},M$=new WeakSet,WNe=function(){var t;try{return((t=globalThis.pdfjsWorker)==null?void 0:t.WorkerMessageHandler)||null}catch{return null}},ds(Wf,M$),ds(Wf,ICe,0),ds(Wf,n8,!1),ds(Wf,r8),c1&&($t(Wf,n8,!0),e3.workerSrc||(e3.workerSrc="./pdf.worker.mjs")),Wf._isSameOrigin=(t,n)=>{let r;try{if(r=new URL(t),!r.origin||r.origin==="null")return!1}catch{return!1}const a=new URL(n,r);return r.origin===a.origin},Wf._createCDNWrapper=t=>{const n=`await import("${t}");`;return URL.createObjectURL(new Blob([n],{type:"text/javascript"}))};let UB=Wf;var FC,YS,P$,I$,ZS,a8,KW;class L6n{constructor(t,n,r,a,i){ds(this,a8);ds(this,FC,new Map);ds(this,YS,new Map);ds(this,P$,new Map);ds(this,I$,new Map);ds(this,ZS,null);this.messageHandler=t,this.loadingTask=n,this.commonObjs=new gUt,this.fontLoader=new MMn({ownerDocument:a.ownerDocument,styleElement:a.styleElement}),this.loadingParams=a.loadingParams,this._params=a,this.canvasFactory=i.canvasFactory,this.filterFactory=i.filterFactory,this.cMapReaderFactory=i.cMapReaderFactory,this.standardFontDataFactory=i.standardFontDataFactory,this.destroyed=!1,this.destroyCapability=null,this._networkStream=r,this._fullReader=null,this._lastProgress=null,this.downloadInfoCapability=Promise.withResolvers(),this.setupMessageHandler()}get annotationStorage(){return nu(this,"annotationStorage",new eQe)}getRenderingIntent(t,n=LE.ENABLE,r=null,a=!1,i=!1){let l=Mw.DISPLAY,o=J$e;switch(t){case"any":l=Mw.ANY;break;case"display":break;case"print":l=Mw.PRINT;break;default:md(`getRenderingIntent - invalid intent: ${t}`)}const c=l&Mw.PRINT&&r instanceof W$t?r:this.annotationStorage;switch(n){case LE.DISABLE:l+=Mw.ANNOTATIONS_DISABLE;break;case LE.ENABLE:break;case LE.ENABLE_FORMS:l+=Mw.ANNOTATIONS_FORMS;break;case LE.ENABLE_STORAGE:l+=Mw.ANNOTATIONS_STORAGE,o=c.serializable;break;default:md(`getRenderingIntent - invalid annotationMode: ${n}`)}a&&(l+=Mw.IS_EDITING),i&&(l+=Mw.OPLIST);const{ids:d,hash:u}=c.modifiedIds,h=[l,o.hash,u];return{renderingIntent:l,cacheKey:h.join("_"),annotationStorageSerializable:o,modifiedIds:d}}destroy(){var r;if(this.destroyCapability)return this.destroyCapability.promise;this.destroyed=!0,this.destroyCapability=Promise.withResolvers(),(r=ge(this,ZS))==null||r.reject(new Error("Worker was destroyed during onPassword callback"));const t=[];for(const a of ge(this,YS).values())t.push(a._destroy());ge(this,YS).clear(),ge(this,P$).clear(),ge(this,I$).clear(),this.hasOwnProperty("annotationStorage")&&this.annotationStorage.resetModified();const n=this.messageHandler.sendWithPromise("Terminate",null);return t.push(n),Promise.all(t).then(()=>{var a;this.commonObjs.clear(),this.fontLoader.clear(),ge(this,FC).clear(),this.filterFactory.destroy(),hQ.cleanup(),(a=this._networkStream)==null||a.cancelAllRequests(new ZF("Worker was terminated.")),this.messageHandler&&(this.messageHandler.destroy(),this.messageHandler=null),this.destroyCapability.resolve()},this.destroyCapability.reject),this.destroyCapability.promise}setupMessageHandler(){const{messageHandler:t,loadingTask:n}=this;t.on("GetReader",(r,a)=>{yy(this._networkStream,"GetReader - no `IPDFStream` instance available."),this._fullReader=this._networkStream.getFullReader(),this._fullReader.onProgress=i=>{this._lastProgress={loaded:i.loaded,total:i.total}},a.onPull=()=>{this._fullReader.read().then(function({value:i,done:l}){if(l){a.close();return}yy(i instanceof ArrayBuffer,"GetReader - expected an ArrayBuffer."),a.enqueue(new Uint8Array(i),1,[i])}).catch(i=>{a.error(i)})},a.onCancel=i=>{this._fullReader.cancel(i),a.ready.catch(l=>{if(!this.destroyed)throw l})}}),t.on("ReaderHeadersReady",async r=>{var o;await this._fullReader.headersReady;const{isStreamingSupported:a,isRangeSupported:i,contentLength:l}=this._fullReader;return(!a||!i)&&(this._lastProgress&&((o=n.onProgress)==null||o.call(n,this._lastProgress)),this._fullReader.onProgress=c=>{var d;(d=n.onProgress)==null||d.call(n,{loaded:c.loaded,total:c.total})}),{isStreamingSupported:a,isRangeSupported:i,contentLength:l}}),t.on("GetRangeReader",(r,a)=>{yy(this._networkStream,"GetRangeReader - no `IPDFStream` instance available.");const i=this._networkStream.getRangeReader(r.begin,r.end);if(!i){a.close();return}a.onPull=()=>{i.read().then(function({value:l,done:o}){if(o){a.close();return}yy(l instanceof ArrayBuffer,"GetRangeReader - expected an ArrayBuffer."),a.enqueue(new Uint8Array(l),1,[l])}).catch(l=>{a.error(l)})},a.onCancel=l=>{i.cancel(l),a.ready.catch(o=>{if(!this.destroyed)throw o})}}),t.on("GetDoc",({pdfInfo:r})=>{this._numPages=r.numPages,this._htmlForXfa=r.htmlForXfa,delete r.htmlForXfa,n._capability.resolve(new M6n(r,this))}),t.on("DocException",function(r){let a;switch(r.name){case"PasswordException":a=new M$e(r.message,r.code);break;case"InvalidPDFException":a=new v$t(r.message);break;case"MissingPDFException":a=new YF(r.message);break;case"UnexpectedResponseException":a=new DTe(r.message,r.status);break;case"UnknownErrorException":a=new P$e(r.message,r.details);break;default:wf("DocException - expected a valid Error.")}n._capability.reject(a)}),t.on("PasswordRequest",r=>{if($t(this,ZS,Promise.withResolvers()),n.onPassword){const a=i=>{i instanceof Error?ge(this,ZS).reject(i):ge(this,ZS).resolve({password:i})};try{n.onPassword(a,r.code)}catch(i){ge(this,ZS).reject(i)}}else ge(this,ZS).reject(new M$e(r.message,r.code));return ge(this,ZS).promise}),t.on("DataLoaded",r=>{var a;(a=n.onProgress)==null||a.call(n,{loaded:r.length,total:r.length}),this.downloadInfoCapability.resolve(r)}),t.on("StartRenderPage",r=>{if(this.destroyed)return;ge(this,YS).get(r.pageIndex)._startRenderPage(r.transparency,r.cacheKey)}),t.on("commonobj",([r,a,i])=>{var l;if(this.destroyed||this.commonObjs.has(r))return null;switch(a){case"Font":const{disableFontFace:o,fontExtraProperties:c,pdfBug:d}=this._params;if("error"in i){const p=i.error;md(`Error during font loading: ${p}`),this.commonObjs.resolve(r,p);break}const u=d&&((l=globalThis.FontInspector)!=null&&l.enabled)?(p,g)=>globalThis.FontInspector.fontAdded(p,g):null,h=new PMn(i,{disableFontFace:o,inspectFont:u});this.fontLoader.bind(h).catch(()=>t.sendWithPromise("FontFallback",{id:r})).finally(()=>{!c&&h.data&&(h.data=null),this.commonObjs.resolve(r,h)});break;case"CopyLocalImage":const{imageRef:m}=i;yy(m,"The imageRef must be defined.");for(const p of ge(this,YS).values())for(const[,g]of p.objs)if((g==null?void 0:g.ref)===m)return g.dataLen?(this.commonObjs.resolve(r,structuredClone(g)),g.dataLen):null;break;case"FontPath":case"Image":case"Pattern":this.commonObjs.resolve(r,i);break;default:throw new Error(`Got unknown common object type ${a}`)}return null}),t.on("obj",([r,a,i,l])=>{var c;if(this.destroyed)return;const o=ge(this,YS).get(a);if(!o.objs.has(r)){if(o._intentStates.size===0){(c=l==null?void 0:l.bitmap)==null||c.close();return}switch(i){case"Image":o.objs.resolve(r,l),(l==null?void 0:l.dataLen)>iMn&&(o._maybeCleanupAfterRender=!0);break;case"Pattern":o.objs.resolve(r,l);break;default:throw new Error(`Got unknown object type ${i}`)}}}),t.on("DocProgress",r=>{var a;this.destroyed||(a=n.onProgress)==null||a.call(n,{loaded:r.loaded,total:r.total})}),t.on("FetchBuiltInCMap",async r=>{if(this.destroyed)throw new Error("Worker was destroyed.");if(!this.cMapReaderFactory)throw new Error("CMapReaderFactory not initialized, see the `useWorkerFetch` parameter.");return this.cMapReaderFactory.fetch(r)}),t.on("FetchStandardFontData",async r=>{if(this.destroyed)throw new Error("Worker was destroyed.");if(!this.standardFontDataFactory)throw new Error("StandardFontDataFactory not initialized, see the `useWorkerFetch` parameter.");return this.standardFontDataFactory.fetch(r)})}getData(){return this.messageHandler.sendWithPromise("GetData",null)}saveDocument(){var r;this.annotationStorage.size<=0&&md("saveDocument called while `annotationStorage` is empty, please use the getData-method instead.");const{map:t,transfer:n}=this.annotationStorage.serializable;return this.messageHandler.sendWithPromise("SaveDocument",{isPureXfa:!!this._htmlForXfa,numPages:this._numPages,annotationStorage:t,filename:((r=this._fullReader)==null?void 0:r.filename)??null},n).finally(()=>{this.annotationStorage.resetModified()})}getPage(t){if(!Number.isInteger(t)||t<=0||t>this._numPages)return Promise.reject(new Error("Invalid page request."));const n=t-1,r=ge(this,P$).get(n);if(r)return r;const a=this.messageHandler.sendWithPromise("GetPage",{pageIndex:n}).then(i=>{if(this.destroyed)throw new Error("Transport destroyed");i.refStr&&ge(this,I$).set(i.refStr,t);const l=new P6n(n,i,this,this._params.pdfBug);return ge(this,YS).set(n,l),l});return ge(this,P$).set(n,a),a}getPageIndex(t){return I1t(t)?this.messageHandler.sendWithPromise("GetPageIndex",{num:t.num,gen:t.gen}):Promise.reject(new Error("Invalid pageIndex request."))}getAnnotations(t,n){return this.messageHandler.sendWithPromise("GetAnnotations",{pageIndex:t,intent:n})}getFieldObjects(){return ss(this,a8,KW).call(this,"GetFieldObjects")}hasJSActions(){return ss(this,a8,KW).call(this,"HasJSActions")}getCalculationOrderIds(){return this.messageHandler.sendWithPromise("GetCalculationOrderIds",null)}getDestinations(){return this.messageHandler.sendWithPromise("GetDestinations",null)}getDestination(t){return typeof t!="string"?Promise.reject(new Error("Invalid destination request.")):this.messageHandler.sendWithPromise("GetDestination",{id:t})}getPageLabels(){return this.messageHandler.sendWithPromise("GetPageLabels",null)}getPageLayout(){return this.messageHandler.sendWithPromise("GetPageLayout",null)}getPageMode(){return this.messageHandler.sendWithPromise("GetPageMode",null)}getViewerPreferences(){return this.messageHandler.sendWithPromise("GetViewerPreferences",null)}getOpenAction(){return this.messageHandler.sendWithPromise("GetOpenAction",null)}getAttachments(){return this.messageHandler.sendWithPromise("GetAttachments",null)}getDocJSActions(){return ss(this,a8,KW).call(this,"GetDocJSActions")}getPageJSActions(t){return this.messageHandler.sendWithPromise("GetPageJSActions",{pageIndex:t})}getStructTree(t){return this.messageHandler.sendWithPromise("GetStructTree",{pageIndex:t})}getOutline(){return this.messageHandler.sendWithPromise("GetOutline",null)}getOptionalContentConfig(t){return ss(this,a8,KW).call(this,"GetOptionalContentConfig").then(n=>new e6n(n,t))}getPermissions(){return this.messageHandler.sendWithPromise("GetPermissions",null)}getMetadata(){const t="GetMetadata",n=ge(this,FC).get(t);if(n)return n;const r=this.messageHandler.sendWithPromise(t,null).then(a=>{var i,l;return{info:a[0],metadata:a[1]?new QMn(a[1]):null,contentDispositionFilename:((i=this._fullReader)==null?void 0:i.filename)??null,contentLength:((l=this._fullReader)==null?void 0:l.contentLength)??null}});return ge(this,FC).set(t,r),r}getMarkInfo(){return this.messageHandler.sendWithPromise("GetMarkInfo",null)}async startCleanup(t=!1){if(!this.destroyed){await this.messageHandler.sendWithPromise("Cleanup",null);for(const n of ge(this,YS).values())if(!n.cleanup())throw new Error(`startCleanup: Page ${n.pageNumber} is currently rendering.`);this.commonObjs.clear(),t||this.fontLoader.clear(),ge(this,FC).clear(),this.filterFactory.destroy(!0),hQ.cleanup()}}cachedPageNumber(t){if(!I1t(t))return null;const n=t.gen===0?`${t.num}R`:`${t.num}R${t.gen}`;return ge(this,I$).get(n)??null}}FC=new WeakMap,YS=new WeakMap,P$=new WeakMap,I$=new WeakMap,ZS=new WeakMap,a8=new WeakSet,KW=function(t,n=null){const r=ge(this,FC).get(t);if(r)return r;const a=this.messageHandler.sendWithPromise(t,n);return ge(this,FC).set(t,a),a};const qae=Symbol("INITIAL_DATA");var MN,fJ,uUe;class gUt{constructor(){ds(this,fJ);ds(this,MN,Object.create(null))}get(t,n=null){if(n){const a=ss(this,fJ,uUe).call(this,t);return a.promise.then(()=>n(a.data)),null}const r=ge(this,MN)[t];if(!r||r.data===qae)throw new Error(`Requesting object that isn't resolved yet ${t}.`);return r.data}has(t){const n=ge(this,MN)[t];return!!n&&n.data!==qae}resolve(t,n=null){const r=ss(this,fJ,uUe).call(this,t);r.data=n,r.resolve()}clear(){var t;for(const n in ge(this,MN)){const{data:r}=ge(this,MN)[n];(t=r==null?void 0:r.bitmap)==null||t.close()}$t(this,MN,Object.create(null))}*[Symbol.iterator](){for(const t in ge(this,MN)){const{data:n}=ge(this,MN)[t];n!==qae&&(yield[t,n])}}}MN=new WeakMap,fJ=new WeakSet,uUe=function(t){var n;return(n=ge(this,MN))[t]||(n[t]={...Promise.withResolvers(),data:qae})};var iT;class R6n{constructor(t){ds(this,iT,null);$t(this,iT,t),this.onContinue=null}get promise(){return ge(this,iT).capability.promise}cancel(t=0){ge(this,iT).cancel(null,t)}get separateAnnots(){const{separateAnnots:t}=ge(this,iT).operatorList;if(!t)return!1;const{annotationCanvasMap:n}=ge(this,iT);return t.form||t.canvas&&(n==null?void 0:n.size)>0}}iT=new WeakMap;var oT,i8;const QR=class QR{constructor({callback:t,params:n,objs:r,commonObjs:a,annotationCanvasMap:i,operatorList:l,pageIndex:o,canvasFactory:c,filterFactory:d,useRequestAnimationFrame:u=!1,pdfBug:h=!1,pageColors:m=null}){ds(this,oT,null);this.callback=t,this.params=n,this.objs=r,this.commonObjs=a,this.annotationCanvasMap=i,this.operatorListIdx=null,this.operatorList=l,this._pageIndex=o,this.canvasFactory=c,this.filterFactory=d,this._pdfBug=h,this.pageColors=m,this.running=!1,this.graphicsReadyCallback=null,this.graphicsReady=!1,this._useRequestAnimationFrame=u===!0&&typeof window<"u",this.cancelled=!1,this.capability=Promise.withResolvers(),this.task=new R6n(this),this._cancelBound=this.cancel.bind(this),this._continueBound=this._continue.bind(this),this._scheduleNextBound=this._scheduleNext.bind(this),this._nextBound=this._next.bind(this),this._canvas=n.canvasContext.canvas}get completed(){return this.capability.promise.catch(function(){})}initializeGraphics({transparency:t=!1,optionalContentConfig:n}){var o,c;if(this.cancelled)return;if(this._canvas){if(ge(QR,i8).has(this._canvas))throw new Error("Cannot use the same canvas during multiple render() operations. Use different canvas or ensure previous operations were cancelled or completed.");ge(QR,i8).add(this._canvas)}this._pdfBug&&((o=globalThis.StepperManager)!=null&&o.enabled)&&(this.stepper=globalThis.StepperManager.create(this._pageIndex),this.stepper.init(this.operatorList),this.stepper.nextBreakPoint=this.stepper.getNextBreakPoint());const{canvasContext:r,viewport:a,transform:i,background:l}=this.params;this.gfx=new $B(r,this.commonObjs,this.objs,this.canvasFactory,this.filterFactory,{optionalContentConfig:n},this.annotationCanvasMap,this.pageColors),this.gfx.beginDrawing({transform:i,viewport:a,transparency:t,background:l}),this.operatorListIdx=0,this.graphicsReady=!0,(c=this.graphicsReadyCallback)==null||c.call(this)}cancel(t=null,n=0){var r;this.running=!1,this.cancelled=!0,(r=this.gfx)==null||r.endDrawing(),ge(this,oT)&&(window.cancelAnimationFrame(ge(this,oT)),$t(this,oT,null)),ge(QR,i8).delete(this._canvas),this.callback(t||new ZXe(`Rendering cancelled, page ${this._pageIndex+1}`,n))}operatorListChanged(){var t;if(!this.graphicsReady){this.graphicsReadyCallback||(this.graphicsReadyCallback=this._continueBound);return}(t=this.stepper)==null||t.updateOperatorList(this.operatorList),!this.running&&this._continue()}_continue(){this.running=!0,!this.cancelled&&(this.task.onContinue?this.task.onContinue(this._scheduleNextBound):this._scheduleNext())}_scheduleNext(){this._useRequestAnimationFrame?$t(this,oT,window.requestAnimationFrame(()=>{$t(this,oT,null),this._nextBound().catch(this._cancelBound)})):Promise.resolve().then(this._nextBound).catch(this._cancelBound)}async _next(){this.cancelled||(this.operatorListIdx=this.gfx.executeOperatorList(this.operatorList,this.operatorListIdx,this._continueBound,this.stepper),this.operatorListIdx===this.operatorList.argsArray.length&&(this.running=!1,this.operatorList.lastChunk&&(this.gfx.endDrawing(),ge(QR,i8).delete(this._canvas),this.callback())))}};oT=new WeakMap,i8=new WeakMap,ds(QR,i8,new WeakSet);let hUe=QR;const D6n="4.8.69",O6n="3634dab10";function L1t(s){return Math.floor(Math.max(0,Math.min(1,s))*255).toString(16).padStart(2,"0")}function UG(s){return Math.max(0,Math.min(255,255*s))}class R1t{static CMYK_G([t,n,r,a]){return["G",1-Math.min(1,.3*t+.59*r+.11*n+a)]}static G_CMYK([t]){return["CMYK",0,0,0,1-t]}static G_RGB([t]){return["RGB",t,t,t]}static G_rgb([t]){return t=UG(t),[t,t,t]}static G_HTML([t]){const n=L1t(t);return`#${n}${n}${n}`}static RGB_G([t,n,r]){return["G",.3*t+.59*n+.11*r]}static RGB_rgb(t){return t.map(UG)}static RGB_HTML(t){return`#${t.map(L1t).join("")}`}static T_HTML(){return"#00000000"}static T_rgb(){return[null]}static CMYK_RGB([t,n,r,a]){return["RGB",1-Math.min(1,t+a),1-Math.min(1,r+a),1-Math.min(1,n+a)]}static CMYK_rgb([t,n,r,a]){return[UG(1-Math.min(1,t+a)),UG(1-Math.min(1,r+a)),UG(1-Math.min(1,n+a))]}static CMYK_HTML(t){const n=this.CMYK_RGB(t).slice(1);return this.RGB_HTML(n)}static RGB_CMYK([t,n,r]){const a=1-t,i=1-n,l=1-r,o=Math.min(a,i,l);return["CMYK",a,i,l,o]}}class F6n{create(t,n,r=!1){if(t<=0||n<=0)throw new Error("Invalid SVG dimensions");const a=this._createSVG("svg:svg");return a.setAttribute("version","1.1"),r||(a.setAttribute("width",`${t}px`),a.setAttribute("height",`${n}px`)),a.setAttribute("preserveAspectRatio","none"),a.setAttribute("viewBox",`0 0 ${t} ${n}`),a}createElement(t){if(typeof t!="string")throw new Error("Invalid SVG element type");return this._createSVG(t)}_createSVG(t){wf("Abstract method `_createSVG` called.")}}class aQe extends F6n{_createSVG(t){return document.createElementNS(uC,t)}}class xUt{static setupStorage(t,n,r,a,i){const l=a.getValue(n,{value:null});switch(r.name){case"textarea":if(l.value!==null&&(t.textContent=l.value),i==="print")break;t.addEventListener("input",o=>{a.setValue(n,{value:o.target.value})});break;case"input":if(r.attributes.type==="radio"||r.attributes.type==="checkbox"){if(l.value===r.attributes.xfaOn?t.setAttribute("checked",!0):l.value===r.attributes.xfaOff&&t.removeAttribute("checked"),i==="print")break;t.addEventListener("change",o=>{a.setValue(n,{value:o.target.checked?o.target.getAttribute("xfaOn"):o.target.getAttribute("xfaOff")})})}else{if(l.value!==null&&t.setAttribute("value",l.value),i==="print")break;t.addEventListener("input",o=>{a.setValue(n,{value:o.target.value})})}break;case"select":if(l.value!==null){t.setAttribute("value",l.value);for(const o of r.children)o.attributes.value===l.value?o.attributes.selected=!0:o.attributes.hasOwnProperty("selected")&&delete o.attributes.selected}t.addEventListener("input",o=>{const c=o.target.options,d=c.selectedIndex===-1?"":c[c.selectedIndex].value;a.setValue(n,{value:d})});break}}static setAttributes({html:t,element:n,storage:r=null,intent:a,linkService:i}){const{attributes:l}=n,o=t instanceof HTMLAnchorElement;l.type==="radio"&&(l.name=`${l.name}-${a}`);for(const[c,d]of Object.entries(l))if(d!=null)switch(c){case"class":d.length&&t.setAttribute(c,d.join(" "));break;case"dataId":break;case"id":t.setAttribute("data-element-id",d);break;case"style":Object.assign(t.style,d);break;case"textContent":t.textContent=d;break;default:(!o||c!=="href"&&c!=="newWindow")&&t.setAttribute(c,d)}o&&i.addLinkAttributes(t,l.href,l.newWindow),r&&l.dataId&&this.setupStorage(t,l.dataId,n,r)}static render(t){var h,m;const n=t.annotationStorage,r=t.linkService,a=t.xfaHtml,i=t.intent||"display",l=document.createElement(a.name);a.attributes&&this.setAttributes({html:l,element:a,intent:i,linkService:r});const o=i!=="richText",c=t.div;if(c.append(l),t.viewport){const p=`matrix(${t.viewport.transform.join(",")})`;c.style.transform=p}o&&c.setAttribute("class","xfaLayer xfaFont");const d=[];if(a.children.length===0){if(a.value){const p=document.createTextNode(a.value);l.append(p),o&&mQ.shouldBuildText(a.name)&&d.push(p)}return{textDivs:d}}const u=[[a,-1,l]];for(;u.length>0;){const[p,g,x]=u.at(-1);if(g+1===p.children.length){u.pop();continue}const y=p.children[++u.at(-1)[1]];if(y===null)continue;const{name:v}=y;if(v==="#text"){const j=document.createTextNode(y.value);d.push(j),x.append(j);continue}const _=(h=y==null?void 0:y.attributes)!=null&&h.xmlns?document.createElementNS(y.attributes.xmlns,v):document.createElement(v);if(x.append(_),y.attributes&&this.setAttributes({html:_,element:y,storage:n,intent:i,linkService:r}),((m=y.children)==null?void 0:m.length)>0)u.push([y,-1,_]);else if(y.value){const j=document.createTextNode(y.value);o&&mQ.shouldBuildText(v)&&d.push(j),_.append(j)}}for(const p of c.querySelectorAll(".xfaNonInteractive input, .xfaNonInteractive textarea"))p.setAttribute("readOnly",!0);return{textDivs:d}}static update(t){const n=`matrix(${t.viewport.transform.join(",")})`;t.div.style.transform=n,t.div.hidden=!1}}const vte=1e3,z6n=9,oF=new WeakSet;function E3(s){return{width:s[2]-s[0],height:s[3]-s[1]}}class B6n{static create(t){switch(t.data.annotationType){case iy.LINK:return new yUt(t);case iy.TEXT:return new $6n(t);case iy.WIDGET:switch(t.data.fieldType){case"Tx":return new U6n(t);case"Btn":return t.data.radioButton?new _Ut(t):t.data.checkBox?new V6n(t):new H6n(t);case"Ch":return new G6n(t);case"Sig":return new q6n(t)}return new XF(t);case iy.POPUP:return new fUe(t);case iy.FREETEXT:return new SUt(t);case iy.LINE:return new K6n(t);case iy.SQUARE:return new Y6n(t);case iy.CIRCLE:return new Z6n(t);case iy.POLYLINE:return new CUt(t);case iy.CARET:return new Q6n(t);case iy.INK:return new iQe(t);case iy.POLYGON:return new X6n(t);case iy.HIGHLIGHT:return new AUt(t);case iy.UNDERLINE:return new J6n(t);case iy.SQUIGGLY:return new ePn(t);case iy.STRIKEOUT:return new tPn(t);case iy.STAMP:return new EUt(t);case iy.FILEATTACHMENT:return new sPn(t);default:return new lx(t)}}}var o8,L$,R$,pJ,mUe;const CJe=class CJe{constructor(t,{isRenderable:n=!1,ignoreBorder:r=!1,createQuadrilaterals:a=!1}={}){ds(this,pJ);ds(this,o8,null);ds(this,L$,!1);ds(this,R$,null);this.isRenderable=n,this.data=t.data,this.layer=t.layer,this.linkService=t.linkService,this.downloadManager=t.downloadManager,this.imageResourcesPath=t.imageResourcesPath,this.renderForms=t.renderForms,this.svgFactory=t.svgFactory,this.annotationStorage=t.annotationStorage,this.enableScripting=t.enableScripting,this.hasJSActions=t.hasJSActions,this._fieldObjects=t.fieldObjects,this.parent=t.parent,n&&(this.container=this._createContainer(r)),a&&this._createQuadrilaterals()}static _hasPopupData({titleObj:t,contentsObj:n,richText:r}){return!!(t!=null&&t.str||n!=null&&n.str||r!=null&&r.str)}get _isEditable(){return this.data.isEditable}get hasPopupData(){return CJe._hasPopupData(this.data)}updateEdited(t){var r;if(!this.container)return;ge(this,o8)||$t(this,o8,{rect:this.data.rect.slice(0)});const{rect:n}=t;n&&ss(this,pJ,mUe).call(this,n),(r=ge(this,R$))==null||r.popup.updateEdited(t)}resetEdited(){var t;ge(this,o8)&&(ss(this,pJ,mUe).call(this,ge(this,o8).rect),(t=ge(this,R$))==null||t.popup.resetEdited(),$t(this,o8,null))}_createContainer(t){const{data:n,parent:{page:r,viewport:a}}=this,i=document.createElement("section");i.setAttribute("data-annotation-id",n.id),this instanceof XF||(i.tabIndex=vte);const{style:l}=i;if(l.zIndex=this.parent.zIndex++,n.alternativeText&&(i.title=n.alternativeText),n.noRotate&&i.classList.add("norotate"),!n.rect||this instanceof fUe){const{rotation:x}=n;return!n.hasOwnCanvas&&x!==0&&this.setRotation(x,i),i}const{width:o,height:c}=E3(n.rect);if(!t&&n.borderStyle.width>0){l.borderWidth=`${n.borderStyle.width}px`;const x=n.borderStyle.horizontalCornerRadius,y=n.borderStyle.verticalCornerRadius;if(x>0||y>0){const _=`calc(${x}px * var(--scale-factor)) / calc(${y}px * var(--scale-factor))`;l.borderRadius=_}else if(this instanceof _Ut){const _=`calc(${o}px * var(--scale-factor)) / calc(${c}px * var(--scale-factor))`;l.borderRadius=_}switch(n.borderStyle.style){case BG.SOLID:l.borderStyle="solid";break;case BG.DASHED:l.borderStyle="dashed";break;case BG.BEVELED:md("Unimplemented border style: beveled");break;case BG.INSET:md("Unimplemented border style: inset");break;case BG.UNDERLINE:l.borderBottomStyle="solid";break}const v=n.borderColor||null;v?($t(this,L$,!0),l.borderColor=Ko.makeHexColor(v[0]|0,v[1]|0,v[2]|0)):l.borderWidth=0}const d=Ko.normalizeRect([n.rect[0],r.view[3]-n.rect[1]+r.view[1],n.rect[2],r.view[3]-n.rect[3]+r.view[1]]),{pageWidth:u,pageHeight:h,pageX:m,pageY:p}=a.rawDims;l.left=`${100*(d[0]-m)/u}%`,l.top=`${100*(d[1]-p)/h}%`;const{rotation:g}=n;return n.hasOwnCanvas||g===0?(l.width=`${100*o/u}%`,l.height=`${100*c/h}%`):this.setRotation(g,i),i}setRotation(t,n=this.container){if(!this.data.rect)return;const{pageWidth:r,pageHeight:a}=this.parent.viewport.rawDims,{width:i,height:l}=E3(this.data.rect);let o,c;t%180===0?(o=100*i/r,c=100*l/a):(o=100*l/r,c=100*i/a),n.style.width=`${o}%`,n.style.height=`${c}%`,n.setAttribute("data-main-rotation",(360-t)%360)}get _commonActions(){const t=(n,r,a)=>{const i=a.detail[n],l=i[0],o=i.slice(1);a.target.style[r]=R1t[`${l}_HTML`](o),this.annotationStorage.setValue(this.data.id,{[r]:R1t[`${l}_rgb`](o)})};return nu(this,"_commonActions",{display:n=>{const{display:r}=n.detail,a=r%2===1;this.container.style.visibility=a?"hidden":"visible",this.annotationStorage.setValue(this.data.id,{noView:a,noPrint:r===1||r===2})},print:n=>{this.annotationStorage.setValue(this.data.id,{noPrint:!n.detail.print})},hidden:n=>{const{hidden:r}=n.detail;this.container.style.visibility=r?"hidden":"visible",this.annotationStorage.setValue(this.data.id,{noPrint:r,noView:r})},focus:n=>{setTimeout(()=>n.target.focus({preventScroll:!1}),0)},userName:n=>{n.target.title=n.detail.userName},readonly:n=>{n.target.disabled=n.detail.readonly},required:n=>{this._setRequired(n.target,n.detail.required)},bgColor:n=>{t("bgColor","backgroundColor",n)},fillColor:n=>{t("fillColor","backgroundColor",n)},fgColor:n=>{t("fgColor","color",n)},textColor:n=>{t("textColor","color",n)},borderColor:n=>{t("borderColor","borderColor",n)},strokeColor:n=>{t("strokeColor","borderColor",n)},rotation:n=>{const r=n.detail.rotation;this.setRotation(r),this.annotationStorage.setValue(this.data.id,{rotation:r})}})}_dispatchEventFromSandbox(t,n){const r=this._commonActions;for(const a of Object.keys(n.detail)){const i=t[a]||r[a];i==null||i(n)}}_setDefaultPropertiesFromJS(t){if(!this.enableScripting)return;const n=this.annotationStorage.getRawValue(this.data.id);if(!n)return;const r=this._commonActions;for(const[a,i]of Object.entries(n)){const l=r[a];if(l){const o={detail:{[a]:i},target:t};l(o),delete n[a]}}}_createQuadrilaterals(){if(!this.container)return;const{quadPoints:t}=this.data;if(!t)return;const[n,r,a,i]=this.data.rect.map(x=>Math.fround(x));if(t.length===8){const[x,y,v,_]=t.subarray(2,6);if(a===x&&i===y&&n===v&&r===_)return}const{style:l}=this.container;let o;if(ge(this,L$)){const{borderColor:x,borderWidth:y}=l;l.borderWidth=0,o=["url('data:image/svg+xml;utf8,",'',``],this.container.classList.add("hasBorder")}const c=a-n,d=i-r,{svgFactory:u}=this,h=u.createElement("svg");h.classList.add("quadrilateralsContainer"),h.setAttribute("width",0),h.setAttribute("height",0);const m=u.createElement("defs");h.append(m);const p=u.createElement("clipPath"),g=`clippath_${this.data.id}`;p.setAttribute("id",g),p.setAttribute("clipPathUnits","objectBoundingBox"),m.append(p);for(let x=2,y=t.length;x`)}ge(this,L$)&&(o.push("')"),l.backgroundImage=o.join("")),this.container.append(h),this.container.style.clipPath=`url(#${g})`}_createPopup(){const{data:t}=this,n=$t(this,R$,new fUe({data:{color:t.color,titleObj:t.titleObj,modificationDate:t.modificationDate,contentsObj:t.contentsObj,richText:t.richText,parentRect:t.rect,borderStyle:0,id:`popup_${t.id}`,rotation:t.rotation},parent:this.parent,elements:[this]}));this.parent.div.append(n.render())}render(){wf("Abstract method `AnnotationElement.render` called")}_getElementsByName(t,n=null){const r=[];if(this._fieldObjects){const a=this._fieldObjects[t];if(a)for(const{page:i,id:l,exportValues:o}of a){if(i===-1||l===n)continue;const c=typeof o=="string"?o:null,d=document.querySelector(`[data-element-id="${l}"]`);if(d&&!oF.has(d)){md(`_getElementsByName - element not allowed: ${l}`);continue}r.push({id:l,exportValue:c,domElement:d})}return r}for(const a of document.getElementsByName(t)){const{exportValue:i}=a,l=a.getAttribute("data-element-id");l!==n&&oF.has(a)&&r.push({id:l,exportValue:i,domElement:a})}return r}show(){var t;this.container&&(this.container.hidden=!1),(t=this.popup)==null||t.maybeShow()}hide(){var t;this.container&&(this.container.hidden=!0),(t=this.popup)==null||t.forceHide()}getElementsToTriggerPopup(){return this.container}addHighlightArea(){const t=this.getElementsToTriggerPopup();if(Array.isArray(t))for(const n of t)n.classList.add("highlightArea");else t.classList.add("highlightArea")}_editOnDoubleClick(){if(!this._isEditable)return;const{annotationEditorType:t,data:{id:n}}=this;this.container.addEventListener("dblclick",()=>{var r;(r=this.linkService.eventBus)==null||r.dispatch("switchannotationeditormode",{source:this,mode:t,editId:n})})}};o8=new WeakMap,L$=new WeakMap,R$=new WeakMap,pJ=new WeakSet,mUe=function(t){const{container:{style:n},data:{rect:r,rotation:a},parent:{viewport:{rawDims:{pageWidth:i,pageHeight:l,pageX:o,pageY:c}}}}=this;r==null||r.splice(0,4,...t);const{width:d,height:u}=E3(t);n.left=`${100*(t[0]-o)/i}%`,n.top=`${100*(l-t[3]+c)/l}%`,a===0?(n.width=`${100*d/i}%`,n.height=`${100*u/l}%`):this.setRotation(a)};let lx=CJe;var zw,zR,vUt,bUt;class yUt extends lx{constructor(n,r=null){super(n,{isRenderable:!0,ignoreBorder:!!(r!=null&&r.ignoreBorder),createQuadrilaterals:!0});ds(this,zw);this.isTooltipOnly=n.data.isTooltipOnly}render(){const{data:n,linkService:r}=this,a=document.createElement("a");a.setAttribute("data-element-id",n.id);let i=!1;return n.url?(r.addLinkAttributes(a,n.url,n.newWindow),i=!0):n.action?(this._bindNamedAction(a,n.action),i=!0):n.attachment?(ss(this,zw,vUt).call(this,a,n.attachment,n.attachmentDest),i=!0):n.setOCGState?(ss(this,zw,bUt).call(this,a,n.setOCGState),i=!0):n.dest?(this._bindLink(a,n.dest),i=!0):(n.actions&&(n.actions.Action||n.actions["Mouse Up"]||n.actions["Mouse Down"])&&this.enableScripting&&this.hasJSActions&&(this._bindJSAction(a,n),i=!0),n.resetForm?(this._bindResetFormAction(a,n.resetForm),i=!0):this.isTooltipOnly&&!i&&(this._bindLink(a,""),i=!0)),this.container.classList.add("linkAnnotation"),i&&this.container.append(a),this.container}_bindLink(n,r){n.href=this.linkService.getDestinationHash(r),n.onclick=()=>(r&&this.linkService.goToDestination(r),!1),(r||r==="")&&ss(this,zw,zR).call(this)}_bindNamedAction(n,r){n.href=this.linkService.getAnchorUrl(""),n.onclick=()=>(this.linkService.executeNamedAction(r),!1),ss(this,zw,zR).call(this)}_bindJSAction(n,r){n.href=this.linkService.getAnchorUrl("");const a=new Map([["Action","onclick"],["Mouse Up","onmouseup"],["Mouse Down","onmousedown"]]);for(const i of Object.keys(r.actions)){const l=a.get(i);l&&(n[l]=()=>{var o;return(o=this.linkService.eventBus)==null||o.dispatch("dispatcheventinsandbox",{source:this,detail:{id:r.id,name:i}}),!1})}n.onclick||(n.onclick=()=>!1),ss(this,zw,zR).call(this)}_bindResetFormAction(n,r){const a=n.onclick;if(a||(n.href=this.linkService.getAnchorUrl("")),ss(this,zw,zR).call(this),!this._fieldObjects){md('_bindResetFormAction - "resetForm" action not supported, ensure that the `fieldObjects` parameter is provided.'),a||(n.onclick=()=>!1);return}n.onclick=()=>{var h;a==null||a();const{fields:i,refs:l,include:o}=r,c=[];if(i.length!==0||l.length!==0){const m=new Set(l);for(const p of i){const g=this._fieldObjects[p]||[];for(const{id:x}of g)m.add(x)}for(const p of Object.values(this._fieldObjects))for(const g of p)m.has(g.id)===o&&c.push(g)}else for(const m of Object.values(this._fieldObjects))c.push(...m);const d=this.annotationStorage,u=[];for(const m of c){const{id:p}=m;switch(u.push(p),m.type){case"text":{const x=m.defaultValue||"";d.setValue(p,{value:x});break}case"checkbox":case"radiobutton":{const x=m.defaultValue===m.exportValues;d.setValue(p,{value:x});break}case"combobox":case"listbox":{const x=m.defaultValue||"";d.setValue(p,{value:x});break}default:continue}const g=document.querySelector(`[data-element-id="${p}"]`);if(g){if(!oF.has(g)){md(`_bindResetFormAction - element not allowed: ${p}`);continue}}else continue;g.dispatchEvent(new Event("resetform"))}return this.enableScripting&&((h=this.linkService.eventBus)==null||h.dispatch("dispatcheventinsandbox",{source:this,detail:{id:"app",ids:u,name:"ResetForm"}})),!1}}}zw=new WeakSet,zR=function(){this.container.setAttribute("data-internal-link","")},vUt=function(n,r,a=null){n.href=this.linkService.getAnchorUrl(""),r.description&&(n.title=r.description),n.onclick=()=>{var i;return(i=this.downloadManager)==null||i.openOrDownloadData(r.content,r.filename,a),!1},ss(this,zw,zR).call(this)},bUt=function(n,r){n.href=this.linkService.getAnchorUrl(""),n.onclick=()=>(this.linkService.executeSetOCGState(r),!1),ss(this,zw,zR).call(this)};class $6n extends lx{constructor(t){super(t,{isRenderable:!0})}render(){this.container.classList.add("textAnnotation");const t=document.createElement("img");return t.src=this.imageResourcesPath+"annotation-"+this.data.name.toLowerCase()+".svg",t.setAttribute("data-l10n-id","pdfjs-text-annotation-type"),t.setAttribute("data-l10n-args",JSON.stringify({type:this.data.name})),!this.data.popupRef&&this.hasPopupData&&this._createPopup(),this.container.append(t),this.container}}class XF extends lx{render(){return this.container}showElementAndHideCanvas(t){var n;this.data.hasOwnCanvas&&(((n=t.previousSibling)==null?void 0:n.nodeName)==="CANVAS"&&(t.previousSibling.hidden=!0),t.hidden=!1)}_getKeyModifier(t){return _b.platform.isMac?t.metaKey:t.ctrlKey}_setEventListener(t,n,r,a,i){r.includes("mouse")?t.addEventListener(r,l=>{var o;(o=this.linkService.eventBus)==null||o.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:a,value:i(l),shift:l.shiftKey,modifier:this._getKeyModifier(l)}})}):t.addEventListener(r,l=>{var o;if(r==="blur"){if(!n.focused||!l.relatedTarget)return;n.focused=!1}else if(r==="focus"){if(n.focused)return;n.focused=!0}i&&((o=this.linkService.eventBus)==null||o.dispatch("dispatcheventinsandbox",{source:this,detail:{id:this.data.id,name:a,value:i(l)}}))})}_setEventListeners(t,n,r,a){var i,l,o;for(const[c,d]of r)(d==="Action"||(i=this.data.actions)!=null&&i[d])&&((d==="Focus"||d==="Blur")&&(n||(n={focused:!1})),this._setEventListener(t,n,c,d,a),d==="Focus"&&!((l=this.data.actions)!=null&&l.Blur)?this._setEventListener(t,n,"blur","Blur",null):d==="Blur"&&!((o=this.data.actions)!=null&&o.Focus)&&this._setEventListener(t,n,"focus","Focus",null))}_setBackgroundColor(t){const n=this.data.backgroundColor||null;t.style.backgroundColor=n===null?"transparent":Ko.makeHexColor(n[0],n[1],n[2])}_setTextStyle(t){const n=["left","center","right"],{fontColor:r}=this.data.defaultAppearanceData,a=this.data.defaultAppearanceData.fontSize||z6n,i=t.style;let l;const o=2,c=d=>Math.round(10*d)/10;if(this.data.multiLine){const d=Math.abs(this.data.rect[3]-this.data.rect[1]-o),u=Math.round(d/(RDe*a))||1,h=d/u;l=Math.min(a,c(h/RDe))}else{const d=Math.abs(this.data.rect[3]-this.data.rect[1]-o);l=Math.min(a,c(d/RDe))}i.fontSize=`calc(${l}px * var(--scale-factor))`,i.color=Ko.makeHexColor(r[0],r[1],r[2]),this.data.textAlignment!==null&&(i.textAlign=n[this.data.textAlignment])}_setRequired(t,n){n?t.setAttribute("required",!0):t.removeAttribute("required"),t.setAttribute("aria-required",n)}}class U6n extends XF{constructor(t){const n=t.renderForms||t.data.hasOwnCanvas||!t.data.hasAppearance&&!!t.data.fieldValue;super(t,{isRenderable:n})}setPropertyOnSiblings(t,n,r,a){const i=this.annotationStorage;for(const l of this._getElementsByName(t.name,t.id))l.domElement&&(l.domElement[n]=r),i.setValue(l.id,{[a]:r})}render(){var a,i;const t=this.annotationStorage,n=this.data.id;this.container.classList.add("textWidgetAnnotation");let r=null;if(this.renderForms){const l=t.getValue(n,{value:this.data.fieldValue});let o=l.value||"";const c=t.getValue(n,{charLimit:this.data.maxLen}).charLimit;c&&o.length>c&&(o=o.slice(0,c));let d=l.formattedValue||((a=this.data.textContent)==null?void 0:a.join(` `))||null;d&&this.data.comb&&(d=d.replaceAll(/\s+/g,""));const u={userValue:o,formattedValue:d,lastCommittedValue:null,commitKey:1,focused:!1};this.data.multiLine?(r=document.createElement("textarea"),r.textContent=d??o,this.data.doNotScroll&&(r.style.overflowY="hidden")):(r=document.createElement("input"),r.type="text",r.setAttribute("value",d??o),this.data.doNotScroll&&(r.style.overflowX="hidden")),this.data.hasOwnCanvas&&(r.hidden=!0),oF.add(r),r.setAttribute("data-element-id",n),r.disabled=this.data.readOnly,r.name=this.data.fieldName,r.tabIndex=vte,this._setRequired(r,this.data.required),c&&(r.maxLength=c),r.addEventListener("input",m=>{t.setValue(n,{value:m.target.value}),this.setPropertyOnSiblings(r,"value",m.target.value,"value"),u.formattedValue=null}),r.addEventListener("resetform",m=>{const p=this.data.defaultFieldValue??"";r.value=u.userValue=p,u.formattedValue=null});let h=m=>{const{formattedValue:p}=u;p!=null&&(m.target.value=p),m.target.scrollLeft=0};if(this.enableScripting&&this.hasJSActions){r.addEventListener("focus",p=>{var x;if(u.focused)return;const{target:g}=p;u.userValue&&(g.value=u.userValue),u.lastCommittedValue=g.value,u.commitKey=1,(x=this.data.actions)!=null&&x.Focus||(u.focused=!0)}),r.addEventListener("updatefromsandbox",p=>{this.showElementAndHideCanvas(p.target);const g={value(x){u.userValue=x.detail.value??"",t.setValue(n,{value:u.userValue.toString()}),x.target.value=u.userValue},formattedValue(x){const{formattedValue:y}=x.detail;u.formattedValue=y,y!=null&&x.target!==document.activeElement&&(x.target.value=y),t.setValue(n,{formattedValue:y})},selRange(x){x.target.setSelectionRange(...x.detail.selRange)},charLimit:x=>{var j;const{charLimit:y}=x.detail,{target:v}=x;if(y===0){v.removeAttribute("maxLength");return}v.setAttribute("maxLength",y);let _=u.userValue;!_||_.length<=y||(_=_.slice(0,y),v.value=u.userValue=_,t.setValue(n,{value:_}),(j=this.linkService.eventBus)==null||j.dispatch("dispatcheventinsandbox",{source:this,detail:{id:n,name:"Keystroke",value:_,willCommit:!0,commitKey:1,selStart:v.selectionStart,selEnd:v.selectionEnd}}))}};this._dispatchEventFromSandbox(g,p)}),r.addEventListener("keydown",p=>{var y;u.commitKey=1;let g=-1;if(p.key==="Escape"?g=0:p.key==="Enter"&&!this.data.multiLine?g=2:p.key==="Tab"&&(u.commitKey=3),g===-1)return;const{value:x}=p.target;u.lastCommittedValue!==x&&(u.lastCommittedValue=x,u.userValue=x,(y=this.linkService.eventBus)==null||y.dispatch("dispatcheventinsandbox",{source:this,detail:{id:n,name:"Keystroke",value:x,willCommit:!0,commitKey:g,selStart:p.target.selectionStart,selEnd:p.target.selectionEnd}}))});const m=h;h=null,r.addEventListener("blur",p=>{var x,y;if(!u.focused||!p.relatedTarget)return;(x=this.data.actions)!=null&&x.Blur||(u.focused=!1);const{value:g}=p.target;u.userValue=g,u.lastCommittedValue!==g&&((y=this.linkService.eventBus)==null||y.dispatch("dispatcheventinsandbox",{source:this,detail:{id:n,name:"Keystroke",value:g,willCommit:!0,commitKey:u.commitKey,selStart:p.target.selectionStart,selEnd:p.target.selectionEnd}})),m(p)}),(i=this.data.actions)!=null&&i.Keystroke&&r.addEventListener("beforeinput",p=>{var A;u.lastCommittedValue=null;const{data:g,target:x}=p,{value:y,selectionStart:v,selectionEnd:_}=x;let j=v,C=_;switch(p.inputType){case"deleteWordBackward":{const M=y.substring(0,v).match(/\w*[^\w]*$/);M&&(j-=M[0].length);break}case"deleteWordForward":{const M=y.substring(v).match(/^[^\w]*\w*/);M&&(C+=M[0].length);break}case"deleteContentBackward":v===_&&(j-=1);break;case"deleteContentForward":v===_&&(C+=1);break}p.preventDefault(),(A=this.linkService.eventBus)==null||A.dispatch("dispatcheventinsandbox",{source:this,detail:{id:n,name:"Keystroke",value:y,change:g||"",willCommit:!1,selStart:j,selEnd:C}})}),this._setEventListeners(r,u,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],p=>p.target.value)}if(h&&r.addEventListener("blur",h),this.data.comb){const p=(this.data.rect[2]-this.data.rect[0])/c;r.classList.add("comb"),r.style.letterSpacing=`calc(${p}px * var(--scale-factor) - 1ch)`}}else r=document.createElement("div"),r.textContent=this.data.fieldValue,r.style.verticalAlign="middle",r.style.display="table-cell",this.data.hasOwnCanvas&&(r.hidden=!0);return this._setTextStyle(r),this._setBackgroundColor(r),this._setDefaultPropertiesFromJS(r),this.container.append(r),this.container}}class q6n extends XF{constructor(t){super(t,{isRenderable:!!t.data.hasOwnCanvas})}}class V6n extends XF{constructor(t){super(t,{isRenderable:t.renderForms})}render(){const t=this.annotationStorage,n=this.data,r=n.id;let a=t.getValue(r,{value:n.exportValue===n.fieldValue}).value;typeof a=="string"&&(a=a!=="Off",t.setValue(r,{value:a})),this.container.classList.add("buttonWidgetAnnotation","checkBox");const i=document.createElement("input");return oF.add(i),i.setAttribute("data-element-id",r),i.disabled=n.readOnly,this._setRequired(i,this.data.required),i.type="checkbox",i.name=n.fieldName,a&&i.setAttribute("checked",!0),i.setAttribute("exportValue",n.exportValue),i.tabIndex=vte,i.addEventListener("change",l=>{const{name:o,checked:c}=l.target;for(const d of this._getElementsByName(o,r)){const u=c&&d.exportValue===n.exportValue;d.domElement&&(d.domElement.checked=u),t.setValue(d.id,{value:u})}t.setValue(r,{value:c})}),i.addEventListener("resetform",l=>{const o=n.defaultFieldValue||"Off";l.target.checked=o===n.exportValue}),this.enableScripting&&this.hasJSActions&&(i.addEventListener("updatefromsandbox",l=>{const o={value(c){c.target.checked=c.detail.value!=="Off",t.setValue(r,{value:c.target.checked})}};this._dispatchEventFromSandbox(o,l)}),this._setEventListeners(i,null,[["change","Validate"],["change","Action"],["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],l=>l.target.checked)),this._setBackgroundColor(i),this._setDefaultPropertiesFromJS(i),this.container.append(i),this.container}}class _Ut extends XF{constructor(t){super(t,{isRenderable:t.renderForms})}render(){this.container.classList.add("buttonWidgetAnnotation","radioButton");const t=this.annotationStorage,n=this.data,r=n.id;let a=t.getValue(r,{value:n.fieldValue===n.buttonValue}).value;if(typeof a=="string"&&(a=a!==n.buttonValue,t.setValue(r,{value:a})),a)for(const l of this._getElementsByName(n.fieldName,r))t.setValue(l.id,{value:!1});const i=document.createElement("input");if(oF.add(i),i.setAttribute("data-element-id",r),i.disabled=n.readOnly,this._setRequired(i,this.data.required),i.type="radio",i.name=n.fieldName,a&&i.setAttribute("checked",!0),i.tabIndex=vte,i.addEventListener("change",l=>{const{name:o,checked:c}=l.target;for(const d of this._getElementsByName(o,r))t.setValue(d.id,{value:!1});t.setValue(r,{value:c})}),i.addEventListener("resetform",l=>{const o=n.defaultFieldValue;l.target.checked=o!=null&&o===n.buttonValue}),this.enableScripting&&this.hasJSActions){const l=n.buttonValue;i.addEventListener("updatefromsandbox",o=>{const c={value:d=>{const u=l===d.detail.value;for(const h of this._getElementsByName(d.target.name)){const m=u&&h.id===r;h.domElement&&(h.domElement.checked=m),t.setValue(h.id,{value:m})}}};this._dispatchEventFromSandbox(c,o)}),this._setEventListeners(i,null,[["change","Validate"],["change","Action"],["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"]],o=>o.target.checked)}return this._setBackgroundColor(i),this._setDefaultPropertiesFromJS(i),this.container.append(i),this.container}}class H6n extends yUt{constructor(t){super(t,{ignoreBorder:t.data.hasAppearance})}render(){const t=super.render();t.classList.add("buttonWidgetAnnotation","pushButton");const n=t.lastChild;return this.enableScripting&&this.hasJSActions&&n&&(this._setDefaultPropertiesFromJS(n),n.addEventListener("updatefromsandbox",r=>{this._dispatchEventFromSandbox({},r)})),t}}class G6n extends XF{constructor(t){super(t,{isRenderable:t.renderForms})}render(){this.container.classList.add("choiceWidgetAnnotation");const t=this.annotationStorage,n=this.data.id,r=t.getValue(n,{value:this.data.fieldValue}),a=document.createElement("select");oF.add(a),a.setAttribute("data-element-id",n),a.disabled=this.data.readOnly,this._setRequired(a,this.data.required),a.name=this.data.fieldName,a.tabIndex=vte;let i=this.data.combo&&this.data.options.length>0;this.data.combo||(a.size=this.data.options.length,this.data.multiSelect&&(a.multiple=!0)),a.addEventListener("resetform",u=>{const h=this.data.defaultFieldValue;for(const m of a.options)m.selected=m.value===h});for(const u of this.data.options){const h=document.createElement("option");h.textContent=u.displayValue,h.value=u.exportValue,r.value.includes(u.exportValue)&&(h.setAttribute("selected",!0),i=!1),a.append(h)}let l=null;if(i){const u=document.createElement("option");u.value=" ",u.setAttribute("hidden",!0),u.setAttribute("selected",!0),a.prepend(u),l=()=>{u.remove(),a.removeEventListener("input",l),l=null},a.addEventListener("input",l)}const o=u=>{const h=u?"value":"textContent",{options:m,multiple:p}=a;return p?Array.prototype.filter.call(m,g=>g.selected).map(g=>g[h]):m.selectedIndex===-1?null:m[m.selectedIndex][h]};let c=o(!1);const d=u=>{const h=u.target.options;return Array.prototype.map.call(h,m=>({displayValue:m.textContent,exportValue:m.value}))};return this.enableScripting&&this.hasJSActions?(a.addEventListener("updatefromsandbox",u=>{const h={value(m){l==null||l();const p=m.detail.value,g=new Set(Array.isArray(p)?p:[p]);for(const x of a.options)x.selected=g.has(x.value);t.setValue(n,{value:o(!0)}),c=o(!1)},multipleSelection(m){a.multiple=!0},remove(m){const p=a.options,g=m.detail.remove;p[g].selected=!1,a.remove(g),p.length>0&&Array.prototype.findIndex.call(p,y=>y.selected)===-1&&(p[0].selected=!0),t.setValue(n,{value:o(!0),items:d(m)}),c=o(!1)},clear(m){for(;a.length!==0;)a.remove(0);t.setValue(n,{value:null,items:[]}),c=o(!1)},insert(m){const{index:p,displayValue:g,exportValue:x}=m.detail.insert,y=a.children[p],v=document.createElement("option");v.textContent=g,v.value=x,y?y.before(v):a.append(v),t.setValue(n,{value:o(!0),items:d(m)}),c=o(!1)},items(m){const{items:p}=m.detail;for(;a.length!==0;)a.remove(0);for(const g of p){const{displayValue:x,exportValue:y}=g,v=document.createElement("option");v.textContent=x,v.value=y,a.append(v)}a.options.length>0&&(a.options[0].selected=!0),t.setValue(n,{value:o(!0),items:d(m)}),c=o(!1)},indices(m){const p=new Set(m.detail.indices);for(const g of m.target.options)g.selected=p.has(g.index);t.setValue(n,{value:o(!0)}),c=o(!1)},editable(m){m.target.disabled=!m.detail.editable}};this._dispatchEventFromSandbox(h,u)}),a.addEventListener("input",u=>{var p;const h=o(!0),m=o(!1);t.setValue(n,{value:h}),u.preventDefault(),(p=this.linkService.eventBus)==null||p.dispatch("dispatcheventinsandbox",{source:this,detail:{id:n,name:"Keystroke",value:c,change:m,changeEx:h,willCommit:!1,commitKey:1,keyDown:!1}})}),this._setEventListeners(a,null,[["focus","Focus"],["blur","Blur"],["mousedown","Mouse Down"],["mouseenter","Mouse Enter"],["mouseleave","Mouse Exit"],["mouseup","Mouse Up"],["input","Action"],["input","Validate"]],u=>u.target.value)):a.addEventListener("input",function(u){t.setValue(n,{value:o(!0)})}),this.data.combo&&this._setTextStyle(a),this._setBackgroundColor(a),this._setDefaultPropertiesFromJS(a),this.container.append(a),this.container}}class fUe extends lx{constructor(t){const{data:n,elements:r}=t;super(t,{isRenderable:lx._hasPopupData(n)}),this.elements=r,this.popup=null}render(){this.container.classList.add("popupAnnotation");const t=this.popup=new W6n({container:this.container,color:this.data.color,titleObj:this.data.titleObj,modificationDate:this.data.modificationDate,contentsObj:this.data.contentsObj,richText:this.data.richText,rect:this.data.rect,parentRect:this.data.parentRect||null,parent:this.parent,elements:this.elements,open:this.data.open}),n=[];for(const r of this.elements)r.popup=t,r.container.ariaHasPopup="dialog",n.push(r.data.id),r.addHighlightArea();return this.container.setAttribute("aria-controls",n.map(r=>`${YXe}${r}`).join(",")),this.container}}var D$,LCe,RCe,O$,l8,ug,zC,F$,gJ,xJ,z$,BC,PN,$C,yJ,UC,vJ,c8,d8,sm,KNe,pUe,wUt,jUt,NUt,kUt,YNe,ZNe,gUe;class W6n{constructor({container:t,color:n,elements:r,titleObj:a,modificationDate:i,contentsObj:l,richText:o,parent:c,rect:d,parentRect:u,open:h}){ds(this,sm);ds(this,D$,ss(this,sm,NUt).bind(this));ds(this,LCe,ss(this,sm,gUe).bind(this));ds(this,RCe,ss(this,sm,ZNe).bind(this));ds(this,O$,ss(this,sm,YNe).bind(this));ds(this,l8,null);ds(this,ug,null);ds(this,zC,null);ds(this,F$,null);ds(this,gJ,null);ds(this,xJ,null);ds(this,z$,null);ds(this,BC,!1);ds(this,PN,null);ds(this,$C,null);ds(this,yJ,null);ds(this,UC,null);ds(this,vJ,null);ds(this,c8,null);ds(this,d8,!1);var m;$t(this,ug,t),$t(this,vJ,a),$t(this,zC,l),$t(this,UC,o),$t(this,xJ,c),$t(this,l8,n),$t(this,yJ,d),$t(this,z$,u),$t(this,gJ,r),$t(this,F$,QXe.toDateObject(i)),this.trigger=r.flatMap(p=>p.getElementsToTriggerPopup());for(const p of this.trigger)p.addEventListener("click",ge(this,O$)),p.addEventListener("mouseenter",ge(this,RCe)),p.addEventListener("mouseleave",ge(this,LCe)),p.classList.add("popupTriggerArea");for(const p of r)(m=p.container)==null||m.addEventListener("keydown",ge(this,D$));ge(this,ug).hidden=!0,h&&ss(this,sm,YNe).call(this)}render(){if(ge(this,PN))return;const t=$t(this,PN,document.createElement("div"));if(t.className="popup",ge(this,l8)){const i=t.style.outlineColor=Ko.makeHexColor(...ge(this,l8));CSS.supports("background-color","color-mix(in srgb, red 30%, white)")?t.style.backgroundColor=`color-mix(in srgb, ${i} 30%, white)`:t.style.backgroundColor=Ko.makeHexColor(...ge(this,l8).map(o=>Math.floor(.7*(255-o)+o)))}const n=document.createElement("span");n.className="header";const r=document.createElement("h1");if(n.append(r),{dir:r.dir,str:r.textContent}=ge(this,vJ),t.append(n),ge(this,F$)){const i=document.createElement("span");i.classList.add("popupDate"),i.setAttribute("data-l10n-id","pdfjs-annotation-date-time-string"),i.setAttribute("data-l10n-args",JSON.stringify({dateObj:ge(this,F$).valueOf()})),n.append(i)}const a=ge(this,sm,KNe);if(a)xUt.render({xfaHtml:a,intent:"richText",div:t}),t.lastChild.classList.add("richText","popupContent");else{const i=this._formatContents(ge(this,zC));t.append(i)}ge(this,ug).append(t)}_formatContents({str:t,dir:n}){const r=document.createElement("p");r.classList.add("popupContent"),r.dir=n;const a=t.split(/(?:\r\n?|\n)/);for(let i=0,l=a.length;i{l.key==="Enter"&&(i?l.metaKey:l.ctrlKey)&&ss(this,SJ,xUe).call(this)}),!r.popupRef&&this.hasPopupData?this._createPopup():a.classList.add("popupTriggerArea"),n.append(a),n}getElementsToTriggerPopup(){return ge(this,kJ)}addHighlightArea(){this.container.classList.add("highlightArea")}}kJ=new WeakMap,SJ=new WeakSet,xUe=function(){var n;(n=this.downloadManager)==null||n.openOrDownloadData(this.content,this.filename)};var CJ,u8,h8,AJ,cF,TUt,yUe;class nPn{constructor({div:t,accessibilityManager:n,annotationCanvasMap:r,annotationEditorUIManager:a,page:i,viewport:l,structTreeLayer:o}){ds(this,cF);ds(this,CJ,null);ds(this,u8,null);ds(this,h8,new Map);ds(this,AJ,null);this.div=t,$t(this,CJ,n),$t(this,u8,r),$t(this,AJ,o||null),this.page=i,this.viewport=l,this.zIndex=0,this._annotationEditorUIManager=a}hasEditableAnnotations(){return ge(this,h8).size>0}async render(t){var l;const{annotations:n}=t,r=this.div;aF(r,this.viewport);const a=new Map,i={data:null,layer:r,linkService:t.linkService,downloadManager:t.downloadManager,imageResourcesPath:t.imageResourcesPath||"",renderForms:t.renderForms!==!1,svgFactory:new aQe,annotationStorage:t.annotationStorage||new eQe,enableScripting:t.enableScripting===!0,hasJSActions:t.hasJSActions,fieldObjects:t.fieldObjects,parent:this,elements:null};for(const o of n){if(o.noHTML)continue;const c=o.annotationType===iy.POPUP;if(c){const h=a.get(o.id);if(!h)continue;i.elements=h}else{const{width:h,height:m}=E3(o.rect);if(h<=0||m<=0)continue}i.data=o;const d=B6n.create(i);if(!d.isRenderable)continue;if(!c&&o.popupRef){const h=a.get(o.popupRef);h?h.push(d):a.set(o.popupRef,[d])}const u=d.render();o.hidden&&(u.style.visibility="hidden"),await ss(this,cF,TUt).call(this,u,o.id),d._isEditable&&(ge(this,h8).set(d.data.id,d),(l=this._annotationEditorUIManager)==null||l.renderAnnotationElement(d))}ss(this,cF,yUe).call(this)}update({viewport:t}){const n=this.div;this.viewport=t,aF(n,{rotation:t.rotation}),ss(this,cF,yUe).call(this),n.hidden=!1}getEditableAnnotations(){return Array.from(ge(this,h8).values())}getEditableAnnotation(t){return ge(this,h8).get(t)}}CJ=new WeakMap,u8=new WeakMap,h8=new WeakMap,AJ=new WeakMap,cF=new WeakSet,TUt=async function(t,n){var l,o;const r=t.firstChild||t,a=r.id=`${YXe}${n}`,i=await((l=ge(this,AJ))==null?void 0:l.getAriaAttributes(a));if(i)for(const[c,d]of i)r.setAttribute(c,d);this.div.append(t),(o=ge(this,CJ))==null||o.moveElementInDOM(this.div,t,r,!1)},yUe=function(){if(!ge(this,u8))return;const t=this.div;for(const[n,r]of ge(this,u8)){const a=t.querySelector(`[data-annotation-id="${n}"]`);if(!a)continue;r.className="annotationContent";const{firstChild:i}=a;i?i.nodeName==="CANVAS"?i.replaceWith(r):i.classList.contains("annotationContent")?i.after(r):i.before(r):a.append(r)}ge(this,u8).clear()};const Vae=/\r\n?|\n/g;var IN,Nw,EJ,m8,kw,Vx,MUt,PUt,IUt,XNe,L3,QNe,JNe,LUt,bUe,RUt;const Mm=class Mm extends Ph{constructor(n){super({...n,name:"freeTextEditor"});ds(this,Vx);ds(this,IN);ds(this,Nw,"");ds(this,EJ,`${this.id}-editor`);ds(this,m8,null);ds(this,kw);$t(this,IN,n.color||Mm._defaultColor||Ph._defaultLineColor),$t(this,kw,n.fontSize||Mm._defaultFontSize)}static get _keyboardManager(){const n=Mm.prototype,r=l=>l.isEmpty(),a=iF.TRANSLATE_SMALL,i=iF.TRANSLATE_BIG;return nu(this,"_keyboardManager",new yte([[["ctrl+s","mac+meta+s","ctrl+p","mac+meta+p"],n.commitOrRemove,{bubbles:!0}],[["ctrl+Enter","mac+meta+Enter","Escape","mac+Escape"],n.commitOrRemove],[["ArrowLeft","mac+ArrowLeft"],n._translateEmpty,{args:[-a,0],checker:r}],[["ctrl+ArrowLeft","mac+shift+ArrowLeft"],n._translateEmpty,{args:[-i,0],checker:r}],[["ArrowRight","mac+ArrowRight"],n._translateEmpty,{args:[a,0],checker:r}],[["ctrl+ArrowRight","mac+shift+ArrowRight"],n._translateEmpty,{args:[i,0],checker:r}],[["ArrowUp","mac+ArrowUp"],n._translateEmpty,{args:[0,-a],checker:r}],[["ctrl+ArrowUp","mac+shift+ArrowUp"],n._translateEmpty,{args:[0,-i],checker:r}],[["ArrowDown","mac+ArrowDown"],n._translateEmpty,{args:[0,a],checker:r}],[["ctrl+ArrowDown","mac+shift+ArrowDown"],n._translateEmpty,{args:[0,i],checker:r}]]))}static initialize(n,r){Ph.initialize(n,r);const a=getComputedStyle(document.documentElement);this._internalPadding=parseFloat(a.getPropertyValue("--freetext-padding"))}static updateDefaultParams(n,r){switch(n){case vc.FREETEXT_SIZE:Mm._defaultFontSize=r;break;case vc.FREETEXT_COLOR:Mm._defaultColor=r;break}}updateParams(n,r){switch(n){case vc.FREETEXT_SIZE:ss(this,Vx,MUt).call(this,r);break;case vc.FREETEXT_COLOR:ss(this,Vx,PUt).call(this,r);break}}static get defaultPropertiesToUpdate(){return[[vc.FREETEXT_SIZE,Mm._defaultFontSize],[vc.FREETEXT_COLOR,Mm._defaultColor||Ph._defaultLineColor]]}get propertiesToUpdate(){return[[vc.FREETEXT_SIZE,ge(this,kw)],[vc.FREETEXT_COLOR,ge(this,IN)]]}_translateEmpty(n,r){this._uiManager.translateSelectedEditors(n,r,!0)}getInitialTranslation(){const n=this.parentScale;return[-Mm._internalPadding*n,-(Mm._internalPadding+ge(this,kw))*n]}rebuild(){this.parent&&(super.rebuild(),this.div!==null&&(this.isAttachedToDOM||this.parent.add(this)))}enableEditMode(){if(this.isInEditMode())return;this.parent.setEditingState(!1),this.parent.updateToolbar(Kc.FREETEXT),super.enableEditMode(),this.overlayDiv.classList.remove("enabled"),this.editorDiv.contentEditable=!0,this._isDraggable=!1,this.div.removeAttribute("aria-activedescendant"),$t(this,m8,new AbortController);const n=this._uiManager.combinedSignal(ge(this,m8));this.editorDiv.addEventListener("keydown",this.editorDivKeydown.bind(this),{signal:n}),this.editorDiv.addEventListener("focus",this.editorDivFocus.bind(this),{signal:n}),this.editorDiv.addEventListener("blur",this.editorDivBlur.bind(this),{signal:n}),this.editorDiv.addEventListener("input",this.editorDivInput.bind(this),{signal:n}),this.editorDiv.addEventListener("paste",this.editorDivPaste.bind(this),{signal:n})}disableEditMode(){var n;this.isInEditMode()&&(this.parent.setEditingState(!0),super.disableEditMode(),this.overlayDiv.classList.add("enabled"),this.editorDiv.contentEditable=!1,this.div.setAttribute("aria-activedescendant",ge(this,EJ)),this._isDraggable=!0,(n=ge(this,m8))==null||n.abort(),$t(this,m8,null),this.div.focus({preventScroll:!0}),this.isEditing=!1,this.parent.div.classList.add("freetextEditing"))}focusin(n){this._focusEventsAllowed&&(super.focusin(n),n.target!==this.editorDiv&&this.editorDiv.focus())}onceAdded(){var n;this.width||(this.enableEditMode(),this.editorDiv.focus(),(n=this._initialOptions)!=null&&n.isCentered&&this.center(),this._initialOptions=null)}isEmpty(){return!this.editorDiv||this.editorDiv.innerText.trim()===""}remove(){this.isEditing=!1,this.parent&&(this.parent.setEditingState(!0),this.parent.div.classList.add("freetextEditing")),super.remove()}commit(){if(!this.isInEditMode())return;super.commit(),this.disableEditMode();const n=ge(this,Nw),r=$t(this,Nw,ss(this,Vx,IUt).call(this).trimEnd());if(n===r)return;const a=i=>{if($t(this,Nw,i),!i){this.remove();return}ss(this,Vx,JNe).call(this),this._uiManager.rebuild(this),ss(this,Vx,XNe).call(this)};this.addCommands({cmd:()=>{a(r)},undo:()=>{a(n)},mustExec:!1}),ss(this,Vx,XNe).call(this)}shouldGetKeyboardEvents(){return this.isInEditMode()}enterInEditMode(){this.enableEditMode(),this.editorDiv.focus()}dblclick(n){this.enterInEditMode()}keydown(n){n.target===this.div&&n.key==="Enter"&&(this.enterInEditMode(),n.preventDefault())}editorDivKeydown(n){Mm._keyboardManager.exec(this,n)}editorDivFocus(n){this.isEditing=!0}editorDivBlur(n){this.isEditing=!1}editorDivInput(n){this.parent.div.classList.toggle("freetextEditing",this.isEmpty())}disableEditing(){this.editorDiv.setAttribute("role","comment"),this.editorDiv.removeAttribute("aria-multiline")}enableEditing(){this.editorDiv.setAttribute("role","textbox"),this.editorDiv.setAttribute("aria-multiline",!0)}render(){if(this.div)return this.div;let n,r;this.width&&(n=this.x,r=this.y),super.render(),this.editorDiv=document.createElement("div"),this.editorDiv.className="internal",this.editorDiv.setAttribute("id",ge(this,EJ)),this.editorDiv.setAttribute("data-l10n-id","pdfjs-free-text2"),this.editorDiv.setAttribute("data-l10n-attrs","default-content"),this.enableEditing(),this.editorDiv.contentEditable=!0;const{style:a}=this.editorDiv;if(a.fontSize=`calc(${ge(this,kw)}px * var(--scale-factor))`,a.color=ge(this,IN),this.div.append(this.editorDiv),this.overlayDiv=document.createElement("div"),this.overlayDiv.classList.add("overlay","enabled"),this.div.append(this.overlayDiv),G4e(this,this.div,["dblclick","keydown"]),this.width){const[i,l]=this.parentDimensions;if(this.annotationElementId){const{position:o}=this._initialData;let[c,d]=this.getInitialTranslation();[c,d]=this.pageTranslationToScreen(c,d);const[u,h]=this.pageDimensions,[m,p]=this.pageTranslation;let g,x;switch(this.rotation){case 0:g=n+(o[0]-m)/u,x=r+this.height-(o[1]-p)/h;break;case 90:g=n+(o[0]-m)/u,x=r-(o[1]-p)/h,[c,d]=[d,-c];break;case 180:g=n-this.width+(o[0]-m)/u,x=r-(o[1]-p)/h,[c,d]=[-c,-d];break;case 270:g=n+(o[0]-m-this.height*h)/u,x=r+(o[1]-p-this.width*u)/h,[c,d]=[-d,c];break}this.setAt(g*i,x*l,c,d)}else this.setAt(n*i,r*l,this.width*i,this.height*l);ss(this,Vx,JNe).call(this),this._isDraggable=!0,this.editorDiv.contentEditable=!1}else this._isDraggable=!1,this.editorDiv.contentEditable=!0;return this.div}editorDivPaste(n){var g,x,y;const r=n.clipboardData||window.clipboardData,{types:a}=r;if(a.length===1&&a[0]==="text/plain")return;n.preventDefault();const i=ss(g=Mm,L3,bUe).call(g,r.getData("text")||"").replaceAll(Vae,` `);if(!i)return;const l=window.getSelection();if(!l.rangeCount)return;this.editorDiv.normalize(),l.deleteFromDocument();const o=l.getRangeAt(0);if(!i.includes(` `)){o.insertNode(document.createTextNode(i)),this.editorDiv.normalize(),l.collapseToStart();return}const{startContainer:c,startOffset:d}=o,u=[],h=[];if(c.nodeType===Node.TEXT_NODE){const v=c.parentElement;if(h.push(c.nodeValue.slice(d).replaceAll(Vae,"")),v!==this.editorDiv){let _=u;for(const j of this.editorDiv.childNodes){if(j===v){_=h;continue}_.push(ss(x=Mm,L3,QNe).call(x,j))}}u.push(c.nodeValue.slice(0,d).replaceAll(Vae,""))}else if(c===this.editorDiv){let v=u,_=0;for(const j of this.editorDiv.childNodes)_++===d&&(v=h),v.push(ss(y=Mm,L3,QNe).call(y,j))}$t(this,Nw,`${u.join(` `)}${i}${h.join(` `)}`),ss(this,Vx,JNe).call(this);const m=new Range;let p=u.reduce((v,_)=>v+_.length,0);for(const{firstChild:v}of this.editorDiv.childNodes)if(v.nodeType===Node.TEXT_NODE){const _=v.nodeValue.length;if(p<=_){m.setStart(v,p),m.setEnd(v,p);break}p-=_}l.removeAllRanges(),l.addRange(m)}get contentDiv(){return this.editorDiv}static async deserialize(n,r,a){var o;let i=null;if(n instanceof SUt){const{data:{defaultAppearanceData:{fontSize:c,fontColor:d},rect:u,rotation:h,id:m,popupRef:p},textContent:g,textPosition:x,parent:{page:{pageNumber:y}}}=n;if(!g||g.length===0)return null;i=n={annotationType:Kc.FREETEXT,color:Array.from(d),fontSize:c,value:g.join(` `),position:x,pageIndex:y-1,rect:u.slice(0),rotation:h,id:m,deleted:!1,popupRef:p}}const l=await super.deserialize(n,r,a);return $t(l,kw,n.fontSize),$t(l,IN,Ko.makeHexColor(...n.color)),$t(l,Nw,ss(o=Mm,L3,bUe).call(o,n.value)),l.annotationElementId=n.id||null,l._initialData=i,l}serialize(n=!1){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const r=Mm._internalPadding*this.parentScale,a=this.getRect(r,r),i=Ph._colorManager.convert(this.isAttachedToDOM?getComputedStyle(this.editorDiv).color:ge(this,IN)),l={annotationType:Kc.FREETEXT,color:i,fontSize:ge(this,kw),value:ss(this,Vx,LUt).call(this),pageIndex:this.pageIndex,rect:a,rotation:this.rotation,structTreeParentId:this._structTreeParentId};return n?l:this.annotationElementId&&!ss(this,Vx,RUt).call(this,l)?null:(l.id=this.annotationElementId,l)}renderAnnotationElement(n){const r=super.renderAnnotationElement(n);if(this.deleted)return r;const{style:a}=r;a.fontSize=`calc(${ge(this,kw)}px * var(--scale-factor))`,a.color=ge(this,IN),r.replaceChildren();for(const l of ge(this,Nw).split(` `)){const o=document.createElement("div");o.append(l?document.createTextNode(l):document.createElement("br")),r.append(o)}const i=Mm._internalPadding*this.parentScale;return n.updateEdited({rect:this.getRect(i,i),popupContent:ge(this,Nw)}),r}resetAnnotationElement(n){super.resetAnnotationElement(n),n.resetEdited()}};IN=new WeakMap,Nw=new WeakMap,EJ=new WeakMap,m8=new WeakMap,kw=new WeakMap,Vx=new WeakSet,MUt=function(n){const r=i=>{this.editorDiv.style.fontSize=`calc(${i}px * var(--scale-factor))`,this.translate(0,-(i-ge(this,kw))*this.parentScale),$t(this,kw,i),ss(this,Vx,XNe).call(this)},a=ge(this,kw);this.addCommands({cmd:r.bind(this,n),undo:r.bind(this,a),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:vc.FREETEXT_SIZE,overwriteIfSameType:!0,keepUndo:!0})},PUt=function(n){const r=i=>{$t(this,IN,this.editorDiv.style.color=i)},a=ge(this,IN);this.addCommands({cmd:r.bind(this,n),undo:r.bind(this,a),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:vc.FREETEXT_COLOR,overwriteIfSameType:!0,keepUndo:!0})},IUt=function(){var a;const n=[];this.editorDiv.normalize();let r=null;for(const i of this.editorDiv.childNodes)(r==null?void 0:r.nodeType)===Node.TEXT_NODE&&i.nodeName==="BR"||(n.push(ss(a=Mm,L3,QNe).call(a,i)),r=i);return n.join(` `)},XNe=function(){const[n,r]=this.parentDimensions;let a;if(this.isAttachedToDOM)a=this.div.getBoundingClientRect();else{const{currentLayer:i,div:l}=this,o=l.style.display,c=l.classList.contains("hidden");l.classList.remove("hidden"),l.style.display="hidden",i.div.append(this.div),a=l.getBoundingClientRect(),l.remove(),l.style.display=o,l.classList.toggle("hidden",c)}this.rotation%180===this.parentRotation%180?(this.width=a.width/n,this.height=a.height/r):(this.width=a.height/n,this.height=a.width/r),this.fixAndSetPosition()},L3=new WeakSet,QNe=function(n){return(n.nodeType===Node.TEXT_NODE?n.nodeValue:n.innerText).replaceAll(Vae,"")},JNe=function(){if(this.editorDiv.replaceChildren(),!!ge(this,Nw))for(const n of ge(this,Nw).split(` `)){const r=document.createElement("div");r.append(n?document.createTextNode(n):document.createElement("br")),this.editorDiv.append(r)}},LUt=function(){return ge(this,Nw).replaceAll(" "," ")},bUe=function(n){return n.replaceAll(" "," ")},RUt=function(n){const{value:r,fontSize:a,color:i,pageIndex:l}=this._initialData;return this._hasBeenMoved||n.value!==r||n.fontSize!==a||n.color.some((o,c)=>o!==i[c])||n.pageIndex!==l},ds(Mm,L3),ur(Mm,"_freeTextDefaultContent",""),ur(Mm,"_internalPadding",0),ur(Mm,"_defaultColor",null),ur(Mm,"_defaultFontSize",10),ur(Mm,"_type","freetext"),ur(Mm,"_editorType",Kc.FREETEXT);let vUe=Mm;class DUt{toSVGPath(){wf("Abstract method `toSVGPath` must be implemented.")}get box(){wf("Abstract getter `box` must be implemented.")}serialize(t,n){wf("Abstract method `serialize` must be implemented.")}get classNamesForDrawing(){wf("Abstract getter `classNamesForDrawing` must be implemented.")}get classNamesForOutlining(){wf("Abstract getter `classNamesForOutlining` must be implemented.")}get mustRemoveSelfIntersections(){return!1}}var Sw,LN,B$,$$,XS,Nd,f8,p8,TJ,MJ,U$,q$,lT,PJ,DCe,OCe,wy,YW,OUt,FUt,zUt,BUt,$Ut,UUt;const vC=class vC{constructor({x:t,y:n},r,a,i,l,o=0){ds(this,wy);ds(this,Sw);ds(this,LN,[]);ds(this,B$);ds(this,$$);ds(this,XS,[]);ds(this,Nd,new Float64Array(18));ds(this,f8);ds(this,p8);ds(this,TJ);ds(this,MJ);ds(this,U$);ds(this,q$);ds(this,lT,[]);$t(this,Sw,r),$t(this,q$,i*a),$t(this,$$,l),ge(this,Nd).set([NaN,NaN,NaN,NaN,t,n],6),$t(this,B$,o),$t(this,MJ,ge(vC,PJ)*a),$t(this,TJ,ge(vC,OCe)*a),$t(this,U$,a),ge(this,lT).push(t,n)}isEmpty(){return isNaN(ge(this,Nd)[8])}add({x:t,y:n}){var R;$t(this,f8,t),$t(this,p8,n);const[r,a,i,l]=ge(this,Sw);let[o,c,d,u]=ge(this,Nd).subarray(8,12);const h=t-d,m=n-u,p=Math.hypot(h,m);if(p=6;a-=6)isNaN(n[a])?r.push(`L${n[a+4]} ${n[a+5]}`):r.push(`C${n[a]} ${n[a+1]} ${n[a+2]} ${n[a+3]} ${n[a+4]} ${n[a+5]}`);return ss(this,wy,FUt).call(this,r),r.join(" ")}newFreeDrawOutline(t,n,r,a,i,l){return new qUt(t,n,r,a,i,l)}getOutlines(){var h;const t=ge(this,XS),n=ge(this,LN),r=ge(this,Nd),[a,i,l,o]=ge(this,Sw),c=new Float64Array((((h=ge(this,lT))==null?void 0:h.length)??0)+2);for(let m=0,p=c.length-2;m=6;m-=6)for(let p=0;p<6;p+=2){if(isNaN(n[m+p])){d[u]=d[u+1]=NaN,u+=2;continue}d[u]=n[m+p],d[u+1]=n[m+p+1],u+=2}return ss(this,wy,$Ut).call(this,d,u),this.newFreeDrawOutline(d,c,ge(this,Sw),ge(this,U$),ge(this,B$),ge(this,$$))}};Sw=new WeakMap,LN=new WeakMap,B$=new WeakMap,$$=new WeakMap,XS=new WeakMap,Nd=new WeakMap,f8=new WeakMap,p8=new WeakMap,TJ=new WeakMap,MJ=new WeakMap,U$=new WeakMap,q$=new WeakMap,lT=new WeakMap,PJ=new WeakMap,DCe=new WeakMap,OCe=new WeakMap,wy=new WeakSet,YW=function(){const t=ge(this,Nd).subarray(4,6),n=ge(this,Nd).subarray(16,18),[r,a,i,l]=ge(this,Sw);return[(ge(this,f8)+(t[0]-n[0])/2-r)/i,(ge(this,p8)+(t[1]-n[1])/2-a)/l,(ge(this,f8)+(n[0]-t[0])/2-r)/i,(ge(this,p8)+(n[1]-t[1])/2-a)/l]},OUt=function(){const[t,n,r,a]=ge(this,Sw),[i,l,o,c]=ss(this,wy,YW).call(this);return`M${(ge(this,Nd)[2]-t)/r} ${(ge(this,Nd)[3]-n)/a} L${(ge(this,Nd)[4]-t)/r} ${(ge(this,Nd)[5]-n)/a} L${i} ${l} L${o} ${c} L${(ge(this,Nd)[16]-t)/r} ${(ge(this,Nd)[17]-n)/a} L${(ge(this,Nd)[14]-t)/r} ${(ge(this,Nd)[15]-n)/a} Z`},FUt=function(t){const n=ge(this,LN);t.push(`L${n[4]} ${n[5]} Z`)},zUt=function(t){const[n,r,a,i]=ge(this,Sw),l=ge(this,Nd).subarray(4,6),o=ge(this,Nd).subarray(16,18),[c,d,u,h]=ss(this,wy,YW).call(this);t.push(`L${(l[0]-n)/a} ${(l[1]-r)/i} L${c} ${d} L${u} ${h} L${(o[0]-n)/a} ${(o[1]-r)/i}`)},BUt=function(t){const n=ge(this,Nd),[r,a,i,l]=ge(this,Sw),[o,c,d,u]=ss(this,wy,YW).call(this),h=new Float64Array(36);return h.set([NaN,NaN,NaN,NaN,(n[2]-r)/i,(n[3]-a)/l,NaN,NaN,NaN,NaN,(n[4]-r)/i,(n[5]-a)/l,NaN,NaN,NaN,NaN,o,c,NaN,NaN,NaN,NaN,d,u,NaN,NaN,NaN,NaN,(n[16]-r)/i,(n[17]-a)/l,NaN,NaN,NaN,NaN,(n[14]-r)/i,(n[15]-a)/l],0),this.newFreeDrawOutline(h,t,ge(this,Sw),ge(this,U$),ge(this,B$),ge(this,$$))},$Ut=function(t,n){const r=ge(this,LN);return t.set([NaN,NaN,NaN,NaN,r[4],r[5]],n),n+=6},UUt=function(t,n){const r=ge(this,Nd).subarray(4,6),a=ge(this,Nd).subarray(16,18),[i,l,o,c]=ge(this,Sw),[d,u,h,m]=ss(this,wy,YW).call(this);return t.set([NaN,NaN,NaN,NaN,(r[0]-i)/o,(r[1]-l)/c,NaN,NaN,NaN,NaN,d,u,NaN,NaN,NaN,NaN,h,m,NaN,NaN,NaN,NaN,(a[0]-i)/o,(a[1]-l)/c],n),n+=24},ds(vC,PJ,8),ds(vC,DCe,2),ds(vC,OCe,ge(vC,PJ)+ge(vC,DCe));let K4e=vC;var V$,g8,qC,IJ,Cw,LJ,Vg,p_,ZW,XW,VUt;class qUt extends DUt{constructor(n,r,a,i,l,o){super();ds(this,p_);ds(this,V$);ds(this,g8,null);ds(this,qC);ds(this,IJ);ds(this,Cw);ds(this,LJ);ds(this,Vg);$t(this,Vg,n),$t(this,Cw,r),$t(this,V$,a),$t(this,LJ,i),$t(this,qC,l),$t(this,IJ,o),ss(this,p_,VUt).call(this,o);const{x:c,y:d,width:u,height:h}=ge(this,g8);for(let m=0,p=n.length;mn[0]-r[0]||n[1]-r[1]||n[2]-r[2]);const t=[];for(const n of ge(this,cT))n[3]?(t.push(...ss(this,jb,_Ue).call(this,n)),ss(this,jb,GUt).call(this,n)):(ss(this,jb,WUt).call(this,n),t.push(...ss(this,jb,_Ue).call(this,n)));return ss(this,jb,HUt).call(this,t)}}RJ=new WeakMap,cT=new WeakMap,RN=new WeakMap,jb=new WeakSet,HUt=function(t){const n=[],r=new Set;for(const l of t){const[o,c,d]=l;n.push([o,c,l],[o,d,l])}n.sort((l,o)=>l[1]-o[1]||l[0]-o[0]);for(let l=0,o=n.length;l0;){const l=r.values().next().value;let[o,c,d,u,h]=l;r.delete(l);let m=o,p=c;for(i=[o,d],a.push(i);;){let g;if(r.has(u))g=u;else if(r.has(h))g=h;else break;r.delete(g),[o,c,d,u,h]=g,m!==o&&(i.push(m,p,o,p===c?c:d),m=o),p=p===c?d:c}i.push(m,p)}return new rPn(a,ge(this,RJ))},eke=function(t){const n=ge(this,RN);let r=0,a=n.length-1;for(;r<=a;){const i=r+a>>1,l=n[i][0];if(l===t)return i;l=0;a--){const[i,l]=ge(this,RN)[a];if(i!==t)break;if(i===t&&l===n){ge(this,RN).splice(a,1);return}}},_Ue=function(t){const[n,r,a]=t,i=[[n,r,a]],l=ss(this,jb,eke).call(this,a);for(let o=0;o=c){if(p>d)i[u][1]=d;else{if(h===1)return[];i.splice(u,1),u--,h--}continue}i[u][2]=c,p>d&&i.push([n,d,p])}}}return i};var DJ,H$;class rPn extends DUt{constructor(n,r){super();ds(this,DJ);ds(this,H$);$t(this,H$,n),$t(this,DJ,r)}toSVGPath(){const n=[];for(const r of ge(this,H$)){let[a,i]=r;n.push(`M${a} ${i}`);for(let l=2;l-1?($t(this,r_,!0),ss(this,Fc,tke).call(this,n),ss(this,Fc,$R).call(this)):ge(this,VC)&&($t(this,Y$,n.anchorNode),$t(this,$J,n.anchorOffset),$t(this,UJ,n.focusNode),$t(this,qJ,n.focusOffset),ss(this,Fc,SUe).call(this),ss(this,Fc,$R).call(this),this.rotate(this.rotation))}static get _keyboardManager(){const n=eh.prototype;return nu(this,"_keyboardManager",new yte([[["ArrowLeft","mac+ArrowLeft"],n._moveCaret,{args:[0]}],[["ArrowRight","mac+ArrowRight"],n._moveCaret,{args:[1]}],[["ArrowUp","mac+ArrowUp"],n._moveCaret,{args:[2]}],[["ArrowDown","mac+ArrowDown"],n._moveCaret,{args:[3]}]]))}get telemetryInitialData(){return{action:"added",type:ge(this,r_)?"free_highlight":"highlight",color:this._uiManager.highlightColorNames.get(this.color),thickness:ge(this,Zj),methodOfCreation:ge(this,VJ)}}get telemetryFinalData(){return{type:"highlight",color:this._uiManager.highlightColorNames.get(this.color)}}static computeTelemetryFinalData(n){return{numberOfColors:n.get("color").size}}static initialize(n,r){var a;Ph.initialize(n,r),eh._defaultColor||(eh._defaultColor=((a=r.highlightColors)==null?void 0:a.values().next().value)||"#fff066")}static updateDefaultParams(n,r){switch(n){case vc.HIGHLIGHT_DEFAULT_COLOR:eh._defaultColor=r;break;case vc.HIGHLIGHT_THICKNESS:eh._defaultThickness=r;break}}translateInPage(n,r){}get toolbarPosition(){return ge(this,X$)}updateParams(n,r){switch(n){case vc.HIGHLIGHT_COLOR:ss(this,Fc,YUt).call(this,r);break;case vc.HIGHLIGHT_THICKNESS:ss(this,Fc,ZUt).call(this,r);break}}static get defaultPropertiesToUpdate(){return[[vc.HIGHLIGHT_DEFAULT_COLOR,eh._defaultColor],[vc.HIGHLIGHT_THICKNESS,eh._defaultThickness]]}get propertiesToUpdate(){return[[vc.HIGHLIGHT_COLOR,this.color||eh._defaultColor],[vc.HIGHLIGHT_THICKNESS,ge(this,Zj)||eh._defaultThickness],[vc.HIGHLIGHT_FREE,ge(this,r_)]]}async addEditToolbar(){const n=await super.addEditToolbar();return n?(this._uiManager.highlightColors&&($t(this,Z$,new Y4e({editor:this})),n.addColorPicker(ge(this,Z$))),n):null}disableEditing(){super.disableEditing(),this.div.classList.toggle("disabled",!0)}enableEditing(){super.enableEditing(),this.div.classList.toggle("disabled",!1)}fixAndSetPosition(){return super.fixAndSetPosition(ss(this,Fc,QW).call(this))}getBaseTranslation(){return[0,0]}getRect(n,r){return super.getRect(n,r,ss(this,Fc,QW).call(this))}onceAdded(){this.annotationElementId||this.parent.addUndoableEditor(this),this.div.focus()}remove(){ss(this,Fc,CUe).call(this),this._reportTelemetry({action:"deleted"}),super.remove()}rebuild(){this.parent&&(super.rebuild(),this.div!==null&&(ss(this,Fc,$R).call(this),this.isAttachedToDOM||this.parent.add(this)))}setParent(n){var a;let r=!1;this.parent&&!n?ss(this,Fc,CUe).call(this):n&&(ss(this,Fc,$R).call(this,n),r=!this.parent&&((a=this.div)==null?void 0:a.classList.contains("selectedEditor"))),super.setParent(n),this.show(this._isVisible),r&&this.select()}rotate(n){var i,l,o;const{drawLayer:r}=this.parent;let a;ge(this,r_)?(n=(n-this.rotation+360)%360,a=ss(i=eh,u2,K9).call(i,ge(this,FN).box,n)):a=ss(l=eh,u2,K9).call(l,this,n),r.rotate(ge(this,Xv),n),r.rotate(ge(this,dy),n),r.updateBox(ge(this,Xv),a),r.updateBox(ge(this,dy),ss(o=eh,u2,K9).call(o,ge(this,Yj).box,n))}render(){if(this.div)return this.div;const n=super.render();ge(this,Q$)&&(n.setAttribute("aria-label",ge(this,Q$)),n.setAttribute("role","mark")),ge(this,r_)?n.classList.add("free"):this.div.addEventListener("keydown",ss(this,Fc,QUt).bind(this),{signal:this._uiManager._signal});const r=$t(this,v8,document.createElement("div"));n.append(r),r.setAttribute("aria-hidden","true"),r.className="internal",r.style.clipPath=ge(this,y8);const[a,i]=this.parentDimensions;return this.setDims(this.width*a,this.height*i),G4e(this,ge(this,v8),["pointerover","pointerleave"]),this.enableEditing(),n}pointerover(){this.isSelected||this.parent.drawLayer.addClass(ge(this,dy),"hovered")}pointerleave(){this.isSelected||this.parent.drawLayer.removeClass(ge(this,dy),"hovered")}_moveCaret(n){switch(this.parent.unselect(this),n){case 0:case 2:ss(this,Fc,ske).call(this,!0);break;case 1:case 3:ss(this,Fc,ske).call(this,!1);break}}select(){var n,r;super.select(),ge(this,dy)&&((n=this.parent)==null||n.drawLayer.removeClass(ge(this,dy),"hovered"),(r=this.parent)==null||r.drawLayer.addClass(ge(this,dy),"selected"))}unselect(){var n;super.unselect(),ge(this,dy)&&((n=this.parent)==null||n.drawLayer.removeClass(ge(this,dy),"selected"),ge(this,r_)||ss(this,Fc,ske).call(this,!1))}get _mustFixPosition(){return!ge(this,r_)}show(n=this._isVisible){super.show(n),this.parent&&(this.parent.drawLayer.show(ge(this,Xv),n),this.parent.drawLayer.show(ge(this,dy),n))}static startHighlighting(n,r,{target:a,x:i,y:l}){const{x:o,y:c,width:d,height:u}=a.getBoundingClientRect(),h=new AbortController,m=n.combinedSignal(h),p=x=>{x.preventDefault(),x.stopPropagation()},g=x=>{h.abort(),ss(this,u2,sqt).call(this,n,x)};window.addEventListener("blur",g,{signal:m}),window.addEventListener("pointerup",g,{signal:m}),window.addEventListener("pointerdown",p,{capture:!0,passive:!1,signal:m}),window.addEventListener("contextmenu",F2,{signal:m}),a.addEventListener("pointermove",ss(this,u2,tqt).bind(this,n),{signal:m}),this._freeHighlight=new wUe({x:i,y:l},[o,c,d,u],n.scale,this._defaultThickness/2,r,.001),{id:this._freeHighlightId,clipPathId:this._freeHighlightClipId}=n.drawLayer.draw(this._freeHighlight,this._defaultColor,this._defaultOpacity,!0)}static async deserialize(n,r,a){var x,y,v,_;let i=null;if(n instanceof AUt){const{data:{quadPoints:j,rect:C,rotation:A,id:M,color:I,opacity:P,popupRef:R},parent:{page:{pageNumber:O}}}=n;i=n={annotationType:Kc.HIGHLIGHT,color:Array.from(I),opacity:P,quadPoints:j,boxes:null,pageIndex:O-1,rect:C.slice(0),rotation:A,id:M,deleted:!1,popupRef:R}}else if(n instanceof iQe){const{data:{inkLists:j,rect:C,rotation:A,id:M,color:I,borderStyle:{rawWidth:P},popupRef:R},parent:{page:{pageNumber:O}}}=n;i=n={annotationType:Kc.HIGHLIGHT,color:Array.from(I),thickness:P,inkLists:j,boxes:null,pageIndex:O-1,rect:C.slice(0),rotation:A,id:M,deleted:!1,popupRef:R}}const{color:l,quadPoints:o,inkLists:c,opacity:d}=n,u=await super.deserialize(n,r,a);u.color=Ko.makeHexColor(...l),$t(u,HC,d||1),c&&$t(u,Zj,n.thickness),u.annotationElementId=n.id||null,u._initialData=i;const[h,m]=u.pageDimensions,[p,g]=u.pageTranslation;if(o){const j=$t(u,VC,[]);for(let C=0;C=0)$t(this,Xv,r),$t(this,y8,a),this.parent.drawLayer.finalizeLine(r,n),$t(this,dy,this.parent.drawLayer.drawOutline(ge(this,Yj)));else if(this.parent){const p=this.parent.viewport.rotation;this.parent.drawLayer.updateLine(ge(this,Xv),n),this.parent.drawLayer.updateBox(ge(this,Xv),ss(h=eh,u2,K9).call(h,ge(this,FN).box,(p-this.rotation+360)%360)),this.parent.drawLayer.updateLine(ge(this,dy),ge(this,Yj)),this.parent.drawLayer.updateBox(ge(this,dy),ss(m=eh,u2,K9).call(m,ge(this,Yj).box,p))}const{x:l,y:o,width:c,height:d}=n.box;switch(this.rotation){case 0:this.x=l,this.y=o,this.width=c,this.height=d;break;case 90:{const[p,g]=this.parentDimensions;this.x=o,this.y=1-l,this.width=c*g/p,this.height=d*p/g;break}case 180:this.x=1-l,this.y=1-o,this.width=c,this.height=d;break;case 270:{const[p,g]=this.parentDimensions;this.x=1-o,this.y=l,this.width=c*g/p,this.height=d*p/g;break}}const{lastPoint:u}=ge(this,Yj).box;$t(this,X$,[(u[0]-l)/c,(u[1]-o)/d])},YUt=function(n){const r=(l,o)=>{var c,d,u;this.color=l,(c=this.parent)==null||c.drawLayer.changeColor(ge(this,Xv),l),(d=ge(this,Z$))==null||d.updateColor(l),$t(this,HC,o),(u=this.parent)==null||u.drawLayer.changeOpacity(ge(this,Xv),o)},a=this.color,i=ge(this,HC);this.addCommands({cmd:r.bind(this,n,eh._defaultOpacity),undo:r.bind(this,a,i),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:vc.HIGHLIGHT_COLOR,overwriteIfSameType:!0,keepUndo:!0}),this._reportTelemetry({action:"color_changed",color:this._uiManager.highlightColorNames.get(n)},!0)},ZUt=function(n){const r=ge(this,Zj),a=i=>{$t(this,Zj,i),ss(this,Fc,XUt).call(this,i)};this.addCommands({cmd:a.bind(this,n),undo:a.bind(this,r),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:vc.INK_THICKNESS,overwriteIfSameType:!0,keepUndo:!0}),this._reportTelemetry({action:"thickness_changed",thickness:n},!0)},XUt=function(n){if(!ge(this,r_))return;ss(this,Fc,tke).call(this,{highlightOutlines:ge(this,FN).getNewOutline(n/2)}),this.fixAndSetPosition();const[r,a]=this.parentDimensions;this.setDims(this.width*r,this.height*a)},CUe=function(){ge(this,Xv)===null||!this.parent||(this.parent.drawLayer.remove(ge(this,Xv)),$t(this,Xv,null),this.parent.drawLayer.remove(ge(this,dy)),$t(this,dy,null))},$R=function(n=this.parent){ge(this,Xv)===null&&({id:Hy(this,Xv)._,clipPathId:Hy(this,y8)._}=n.drawLayer.draw(ge(this,FN),this.color,ge(this,HC)),$t(this,dy,n.drawLayer.drawOutline(ge(this,Yj))),ge(this,v8)&&(ge(this,v8).style.clipPath=ge(this,y8)))},u2=new WeakSet,K9=function({x:n,y:r,width:a,height:i},l){switch(l){case 90:return{x:1-r-i,y:n,width:i,height:a};case 180:return{x:1-n-a,y:1-r-i,width:a,height:i};case 270:return{x:r,y:1-n-a,width:i,height:a}}return{x:n,y:r,width:a,height:i}},QUt=function(n){eh._keyboardManager.exec(this,n)},ske=function(n){if(!ge(this,Y$))return;const r=window.getSelection();n?r.setPosition(ge(this,Y$),ge(this,$J)):r.setPosition(ge(this,UJ),ge(this,qJ))},QW=function(){return ge(this,r_)?this.rotation:0},JUt=function(){if(ge(this,r_))return null;const[n,r]=this.pageDimensions,[a,i]=this.pageTranslation,l=ge(this,VC),o=new Float32Array(l.length*8);let c=0;for(const{x:d,y:u,width:h,height:m}of l){const p=d*n+a,g=(1-u-m)*r+i;o[c]=o[c+4]=p,o[c+1]=o[c+3]=g,o[c+2]=o[c+6]=p+h*n,o[c+5]=o[c+7]=g+m*r,c+=8}return o},eqt=function(n){return ge(this,FN).serialize(n,ss(this,Fc,QW).call(this))},tqt=function(n,r){this._freeHighlight.add(r)&&n.drawLayer.updatePath(this._freeHighlightId,this._freeHighlight)},sqt=function(n,r){this._freeHighlight.isEmpty()?n.drawLayer.remove(this._freeHighlightId):n.createAndAddNewEditor(r,!1,{highlightId:this._freeHighlightId,highlightOutlines:this._freeHighlight.getOutlines(),clipPathId:this._freeHighlightClipId,methodOfCreation:"main_toolbar"}),this._freeHighlightId=-1,this._freeHighlight=null,this._freeHighlightClipId=""},nqt=function(n){const{color:r}=this._initialData;return n.color.some((a,i)=>a!==r[i])},ds(eh,u2),ur(eh,"_defaultColor",null),ur(eh,"_defaultOpacity",1),ur(eh,"_defaultThickness",12),ur(eh,"_type","highlight"),ur(eh,"_editorType",Kc.HIGHLIGHT),ur(eh,"_freeHighlightId",-1),ur(eh,"_freeHighlight",null),ur(eh,"_freeHighlightClipId","");let Z4e=eh;var b8,_8,QS,GC,Xj,w8,j8,N8,WC,J$,k8,S8,uT,Pi,rqt,aqt,iqt,oqt,EUe,lqt,TUe,cqt,dqt,uqt,hqt,mqt,UR,MUe,PUe,IUe,nke,rke,Y9,LUe,ake,Q3,fqt,RUe,pqt,gqt,DUe,ike,JW;const wp=class wp extends Ph{constructor(n){super({...n,name:"inkEditor"});ds(this,Pi);ds(this,b8,0);ds(this,_8,0);ds(this,QS,null);ds(this,GC,new Path2D);ds(this,Xj,!1);ds(this,w8,null);ds(this,j8,!1);ds(this,N8,!1);ds(this,WC,null);ds(this,J$,null);ds(this,k8,0);ds(this,S8,0);ds(this,uT,null);this.color=n.color||null,this.thickness=n.thickness||null,this.opacity=n.opacity||null,this.paths=[],this.bezierPath2D=[],this.allRawPaths=[],this.currentPath=[],this.scaleFactor=1,this.translationX=this.translationY=0,this.x=0,this.y=0,this._willKeepAspectRatio=!0}static initialize(n,r){Ph.initialize(n,r)}static updateDefaultParams(n,r){switch(n){case vc.INK_THICKNESS:wp._defaultThickness=r;break;case vc.INK_COLOR:wp._defaultColor=r;break;case vc.INK_OPACITY:wp._defaultOpacity=r/100;break}}updateParams(n,r){switch(n){case vc.INK_THICKNESS:ss(this,Pi,rqt).call(this,r);break;case vc.INK_COLOR:ss(this,Pi,aqt).call(this,r);break;case vc.INK_OPACITY:ss(this,Pi,iqt).call(this,r);break}}static get defaultPropertiesToUpdate(){return[[vc.INK_THICKNESS,wp._defaultThickness],[vc.INK_COLOR,wp._defaultColor||Ph._defaultLineColor],[vc.INK_OPACITY,Math.round(wp._defaultOpacity*100)]]}get propertiesToUpdate(){return[[vc.INK_THICKNESS,this.thickness||wp._defaultThickness],[vc.INK_COLOR,this.color||wp._defaultColor||Ph._defaultLineColor],[vc.INK_OPACITY,Math.round(100*(this.opacity??wp._defaultOpacity))]]}rebuild(){this.parent&&(super.rebuild(),this.div!==null&&(this.canvas||(ss(this,Pi,nke).call(this),ss(this,Pi,rke).call(this)),this.isAttachedToDOM||(this.parent.add(this),ss(this,Pi,Y9).call(this)),ss(this,Pi,JW).call(this)))}remove(){var n;this.canvas!==null&&(this.isEmpty()||this.commit(),this.canvas.width=this.canvas.height=0,this.canvas.remove(),this.canvas=null,ge(this,QS)&&(clearTimeout(ge(this,QS)),$t(this,QS,null)),(n=ge(this,WC))==null||n.disconnect(),$t(this,WC,null),super.remove())}setParent(n){!this.parent&&n?this._uiManager.removeShouldRescale(this):this.parent&&n===null&&this._uiManager.addShouldRescale(this),super.setParent(n)}onScaleChanging(){const[n,r]=this.parentDimensions,a=this.width*n,i=this.height*r;this.setDimensions(a,i)}enableEditMode(){ge(this,Xj)||this.canvas===null||(super.enableEditMode(),this._isDraggable=!1,ss(this,Pi,MUe).call(this))}disableEditMode(){!this.isInEditMode()||this.canvas===null||(super.disableEditMode(),this._isDraggable=!this.isEmpty(),this.div.classList.remove("editing"),ss(this,Pi,PUe).call(this))}onceAdded(){this._isDraggable=!this.isEmpty()}isEmpty(){return this.paths.length===0||this.paths.length===1&&this.paths[0].length===0}commit(){ge(this,Xj)||(super.commit(),this.isEditing=!1,this.disableEditMode(),this.setInForeground(),$t(this,Xj,!0),this.div.classList.add("disabled"),ss(this,Pi,JW).call(this,!0),this.select(),this.parent.addInkEditorIfNeeded(!0),this.moveInDOM(),this.div.focus({preventScroll:!0}))}focusin(n){this._focusEventsAllowed&&(super.focusin(n),this.enableEditMode())}canvasPointerdown(n){n.button!==0||!this.isInEditMode()||ge(this,Xj)||(this.setInForeground(),n.preventDefault(),this.div.contains(document.activeElement)||this.div.focus({preventScroll:!0}),ss(this,Pi,lqt).call(this,n.offsetX,n.offsetY))}canvasPointermove(n){n.preventDefault(),ss(this,Pi,TUe).call(this,n.offsetX,n.offsetY)}canvasPointerup(n){n.preventDefault(),ss(this,Pi,IUe).call(this,n)}canvasPointerleave(n){ss(this,Pi,IUe).call(this,n)}get isResizable(){return!this.isEmpty()&&ge(this,Xj)}render(){if(this.div)return this.div;let n,r;this.width&&(n=this.x,r=this.y),super.render(),this.div.setAttribute("data-l10n-id","pdfjs-ink");const[a,i,l,o]=ss(this,Pi,oqt).call(this);if(this.setAt(a,i,0,0),this.setDims(l,o),ss(this,Pi,nke).call(this),this.width){const[c,d]=this.parentDimensions;this.setAspectRatio(this.width*c,this.height*d),this.setAt(n*c,r*d,this.width*c,this.height*d),$t(this,N8,!0),ss(this,Pi,Y9).call(this),this.setDims(this.width*c,this.height*d),ss(this,Pi,UR).call(this),this.div.classList.add("disabled")}else this.div.classList.add("editing"),this.enableEditMode();return ss(this,Pi,rke).call(this),this.div}setDimensions(n,r){const a=Math.round(n),i=Math.round(r);if(ge(this,k8)===a&&ge(this,S8)===i)return;$t(this,k8,a),$t(this,S8,i),this.canvas.style.visibility="hidden";const[l,o]=this.parentDimensions;this.width=n/l,this.height=r/o,this.fixAndSetPosition(),ge(this,Xj)&&ss(this,Pi,LUe).call(this,n,r),ss(this,Pi,Y9).call(this),ss(this,Pi,UR).call(this),this.canvas.style.visibility="visible",this.fixDims()}static async deserialize(n,r,a){var y,v,_;if(n instanceof iQe)return null;const i=await super.deserialize(n,r,a);i.thickness=n.thickness,i.color=Ko.makeHexColor(...n.color),i.opacity=n.opacity;const[l,o]=i.pageDimensions,c=i.width*l,d=i.height*o,u=i.parentScale,h=n.thickness/2;$t(i,Xj,!0),$t(i,k8,Math.round(c)),$t(i,S8,Math.round(d));const{paths:m,rect:p,rotation:g}=n;for(let{bezier:j}of m){j=ss(y=wp,Q3,pqt).call(y,j,p,g);const C=[];i.paths.push(C);let A=u*(j[0]-h),M=u*(j[1]-h);for(let P=2,R=j.length;P{this.thickness=i,ss(this,Pi,JW).call(this)},a=this.thickness;this.addCommands({cmd:r.bind(this,n),undo:r.bind(this,a),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:vc.INK_THICKNESS,overwriteIfSameType:!0,keepUndo:!0})},aqt=function(n){const r=i=>{this.color=i,ss(this,Pi,UR).call(this)},a=this.color;this.addCommands({cmd:r.bind(this,n),undo:r.bind(this,a),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:vc.INK_COLOR,overwriteIfSameType:!0,keepUndo:!0})},iqt=function(n){const r=i=>{this.opacity=i,ss(this,Pi,UR).call(this)};n/=100;const a=this.opacity;this.addCommands({cmd:r.bind(this,n),undo:r.bind(this,a),post:this._uiManager.updateUI.bind(this._uiManager,this),mustExec:!0,type:vc.INK_OPACITY,overwriteIfSameType:!0,keepUndo:!0})},oqt=function(){const{parentRotation:n,parentDimensions:[r,a]}=this;switch(n){case 90:return[0,a,a,r];case 180:return[r,a,r,a];case 270:return[r,0,a,r];default:return[0,0,r,a]}},EUe=function(){const{ctx:n,color:r,opacity:a,thickness:i,parentScale:l,scaleFactor:o}=this;n.lineWidth=i*l/o,n.lineCap="round",n.lineJoin="round",n.miterLimit=10,n.strokeStyle=`${r}${CMn(a)}`},lqt=function(n,r){this.canvas.addEventListener("contextmenu",F2,{signal:this._uiManager._signal}),ss(this,Pi,PUe).call(this),$t(this,w8,new AbortController);const a=this._uiManager.combinedSignal(ge(this,w8));this.canvas.addEventListener("pointerleave",this.canvasPointerleave.bind(this),{signal:a}),this.canvas.addEventListener("pointermove",this.canvasPointermove.bind(this),{signal:a}),this.canvas.addEventListener("pointerup",this.canvasPointerup.bind(this),{signal:a}),this.isEditing=!0,ge(this,N8)||($t(this,N8,!0),ss(this,Pi,Y9).call(this),this.thickness||(this.thickness=wp._defaultThickness),this.color||(this.color=wp._defaultColor||Ph._defaultLineColor),this.opacity??(this.opacity=wp._defaultOpacity)),this.currentPath.push([n,r]),$t(this,j8,!1),ss(this,Pi,EUe).call(this),$t(this,uT,()=>{ss(this,Pi,uqt).call(this),ge(this,uT)&&window.requestAnimationFrame(ge(this,uT))}),window.requestAnimationFrame(ge(this,uT))},TUe=function(n,r){const[a,i]=this.currentPath.at(-1);if(this.currentPath.length>1&&n===a&&r===i)return;const l=this.currentPath;let o=ge(this,GC);if(l.push([n,r]),$t(this,j8,!0),l.length<=2){o.moveTo(...l[0]),o.lineTo(n,r);return}l.length===3&&($t(this,GC,o=new Path2D),o.moveTo(...l[0])),ss(this,Pi,hqt).call(this,o,...l.at(-3),...l.at(-2),n,r)},cqt=function(){if(this.currentPath.length===0)return;const n=this.currentPath.at(-1);ge(this,GC).lineTo(...n)},dqt=function(n,r){$t(this,uT,null),n=Math.min(Math.max(n,0),this.canvas.width),r=Math.min(Math.max(r,0),this.canvas.height),ss(this,Pi,TUe).call(this,n,r),ss(this,Pi,cqt).call(this);let a;if(this.currentPath.length!==1)a=ss(this,Pi,mqt).call(this);else{const d=[n,r];a=[[d,d.slice(),d.slice(),d]]}const i=ge(this,GC),l=this.currentPath;this.currentPath=[],$t(this,GC,new Path2D);const o=()=>{this.allRawPaths.push(l),this.paths.push(a),this.bezierPath2D.push(i),this._uiManager.rebuild(this)},c=()=>{this.allRawPaths.pop(),this.paths.pop(),this.bezierPath2D.pop(),this.paths.length===0?this.remove():(this.canvas||(ss(this,Pi,nke).call(this),ss(this,Pi,rke).call(this)),ss(this,Pi,JW).call(this))};this.addCommands({cmd:o,undo:c,mustExec:!0})},uqt=function(){if(!ge(this,j8))return;$t(this,j8,!1);const n=Math.ceil(this.thickness*this.parentScale),r=this.currentPath.slice(-3),a=r.map(o=>o[0]),i=r.map(o=>o[1]);Math.min(...a)-n,Math.max(...a)+n,Math.min(...i)-n,Math.max(...i)+n;const{ctx:l}=this;l.save(),l.clearRect(0,0,this.canvas.width,this.canvas.height);for(const o of this.bezierPath2D)l.stroke(o);l.stroke(ge(this,GC)),l.restore()},hqt=function(n,r,a,i,l,o,c){const d=(r+i)/2,u=(a+l)/2,h=(i+o)/2,m=(l+c)/2;n.bezierCurveTo(d+2*(i-d)/3,u+2*(l-u)/3,h+2*(i-h)/3,m+2*(l-m)/3,h,m)},mqt=function(){const n=this.currentPath;if(n.length<=2)return[[n[0],n[0],n.at(-1),n.at(-1)]];const r=[];let a,[i,l]=n[0];for(a=1;a{$t(this,QS,null),this.canvas.removeEventListener("contextmenu",F2)},10)),ss(this,Pi,dqt).call(this,n.offsetX,n.offsetY),this.addToAnnotationStorage(),this.setInBackground()},nke=function(){this.canvas=document.createElement("canvas"),this.canvas.width=this.canvas.height=0,this.canvas.className="inkEditorCanvas",this.canvas.setAttribute("data-l10n-id","pdfjs-ink-canvas"),this.div.append(this.canvas),this.ctx=this.canvas.getContext("2d")},rke=function(){$t(this,WC,new ResizeObserver(n=>{const r=n[0].contentRect;r.width&&r.height&&this.setDimensions(r.width,r.height)})),ge(this,WC).observe(this.div),this._uiManager._signal.addEventListener("abort",()=>{var n;(n=ge(this,WC))==null||n.disconnect(),$t(this,WC,null)},{once:!0})},Y9=function(){if(!ge(this,N8))return;const[n,r]=this.parentDimensions;this.canvas.width=Math.ceil(this.width*n),this.canvas.height=Math.ceil(this.height*r),ss(this,Pi,ake).call(this)},LUe=function(n,r){const a=ss(this,Pi,ike).call(this),i=(n-a)/ge(this,_8),l=(r-a)/ge(this,b8);this.scaleFactor=Math.min(i,l)},ake=function(){const n=ss(this,Pi,ike).call(this)/2;this.ctx.setTransform(this.scaleFactor,0,0,this.scaleFactor,this.translationX*this.scaleFactor+n,this.translationY*this.scaleFactor+n)},Q3=new WeakSet,fqt=function(n){const r=new Path2D;for(let a=0,i=n.length;a`image/${r}`))}static get supportedTypesStr(){return nu(this,"supportedTypesStr",this.supportedTypes.join(","))}static isHandlingMimeForPasting(n){return this.supportedTypes.includes(n)}static paste(n,r){r.pasteEditor(Kc.STAMP,{bitmapFile:n.getAsFile()})}altTextFinish(){this._uiManager.useNewAltTextFlow&&(this.div.hidden=!1),super.altTextFinish()}get telemetryFinalData(){var n;return{type:"stamp",hasAltText:!!((n=this.altTextData)!=null&&n.altText)}}static computeTelemetryFinalData(n){const r=n.get("hasAltText");return{hasAltText:r.get(!0)??0,hasNoAltText:r.get(!1)??0}}async mlGuessAltText(n=null,r=!0){if(this.hasAltTextData())return null;const{mlManager:a}=this._uiManager;if(!a)throw new Error("No ML.");if(!await a.isEnabledFor("altText"))throw new Error("ML isn't enabled for alt text.");const{data:i,width:l,height:o}=n||this.copyCanvas(null,null,!0).imageData,c=await a.guess({name:"altText",request:{data:i,width:l,height:o,channels:i.length/(l*o)}});if(!c)throw new Error("No response from the AI service.");if(c.error)throw new Error("Error from the AI service.");if(c.cancel)return null;if(!c.output)throw new Error("No valid response from the AI service.");const d=c.output;return await this.setGuessedAltText(d),r&&!this.hasAltTextData()&&(this.altTextData={alt:d,decorative:!1}),d}remove(){var n,r;ge(this,V0)&&($t(this,Np,null),this._uiManager.imageManager.deleteId(ge(this,V0)),(n=ge(this,JS))==null||n.remove(),$t(this,JS,null),(r=ge(this,YC))==null||r.disconnect(),$t(this,YC,null),ge(this,e5)&&(clearTimeout(ge(this,e5)),$t(this,e5,null))),super.remove()}rebuild(){if(!this.parent){ge(this,V0)&&ss(this,Wd,oke).call(this);return}super.rebuild(),this.div!==null&&(ge(this,V0)&&ge(this,JS)===null&&ss(this,Wd,oke).call(this),this.isAttachedToDOM||this.parent.add(this))}onceAdded(){this._isDraggable=!0,this.div.focus()}isEmpty(){return!(ge(this,hT)||ge(this,Np)||ge(this,KC)||ge(this,mT)||ge(this,V0))}get isResizable(){return!0}render(){if(this.div)return this.div;let n,r;if(this.width&&(n=this.x,r=this.y),super.render(),this.div.hidden=!0,this.div.setAttribute("role","figure"),this.addAltTextButton(),ge(this,Np)?ss(this,Wd,FUe).call(this):ss(this,Wd,oke).call(this),this.width&&!this.annotationElementId){const[a,i]=this.parentDimensions;this.setAt(n*a,r*i,this.width*a,this.height*i)}return this.div}copyCanvas(n,r,a=!1){var p;n||(n=224);const{width:i,height:l}=ge(this,Np),o=new L$e;let c=ge(this,Np),d=i,u=l,h=null;if(r){if(i>r||l>r){const P=Math.min(r/i,r/l);d=Math.floor(i*P),u=Math.floor(l*P)}h=document.createElement("canvas");const g=h.width=Math.ceil(d*o.sx),x=h.height=Math.ceil(u*o.sy);ge(this,Aw)||(c=ss(this,Wd,lke).call(this,g,x));const y=h.getContext("2d");y.filter=this._uiManager.hcmFilter;let v="white",_="#cfcfd8";this._uiManager.hcmFilter!=="none"?_="black":(p=window.matchMedia)!=null&&p.call(window,"(prefers-color-scheme: dark)").matches&&(v="#8f8f9d",_="#42414d");const j=15,C=j*o.sx,A=j*o.sy,M=new OffscreenCanvas(C*2,A*2),I=M.getContext("2d");I.fillStyle=v,I.fillRect(0,0,C*2,A*2),I.fillStyle=_,I.fillRect(0,0,C,A),I.fillRect(C,A,C,A),y.fillStyle=y.createPattern(M,"repeat"),y.fillRect(0,0,g,x),y.drawImage(c,0,0,c.width,c.height,0,0,g,x)}let m=null;if(a){let g,x;if(o.symmetric&&c.widthn||l>n){const _=Math.min(n/i,n/l);g=Math.floor(i*_),x=Math.floor(l*_),ge(this,Aw)||(c=ss(this,Wd,lke).call(this,g,x))}const v=new OffscreenCanvas(g,x).getContext("2d",{willReadFrequently:!0});v.drawImage(c,0,0,c.width,c.height,0,0,g,x),m={width:g,height:x,data:v.getImageData(0,0,g,x).data}}return{canvas:h,width:d,height:u,imageData:m}}getImageForAltText(){return ge(this,JS)}static async deserialize(n,r,a){var x;let i=null;if(n instanceof EUt){const{data:{rect:y,rotation:v,id:_,structParent:j,popupRef:C},container:A,parent:{page:{pageNumber:M}}}=n,I=A.querySelector("canvas"),P=a.imageManager.getFromCanvas(A.id,I);I.remove();const R=((x=await r._structTree.getAriaAttributes(`${YXe}${_}`))==null?void 0:x.get("aria-label"))||"";i=n={annotationType:Kc.STAMP,bitmapId:P.id,bitmap:P.bitmap,pageIndex:M-1,rect:y.slice(0),rotation:v,id:_,deleted:!1,accessibilityData:{decorative:!1,altText:R},isSvg:!1,structParent:j,popupRef:C}}const l=await super.deserialize(n,r,a),{rect:o,bitmap:c,bitmapUrl:d,bitmapId:u,isSvg:h,accessibilityData:m}=n;u&&a.imageManager.isValidId(u)?($t(l,V0,u),c&&$t(l,Np,c)):$t(l,KC,d),$t(l,Aw,h);const[p,g]=l.pageDimensions;return l.width=(o[2]-o[0])/p,l.height=(o[3]-o[1])/g,l.annotationElementId=n.id||null,m&&(l.altTextData=m),l._initialData=i,$t(l,tU,!!i),l}serialize(n=!1,r=null){if(this.isEmpty())return null;if(this.deleted)return this.serializeDeleted();const a={annotationType:Kc.STAMP,bitmapId:ge(this,V0),pageIndex:this.pageIndex,rect:this.getRect(0,0),rotation:this.rotation,isSvg:ge(this,Aw),structTreeParentId:this._structTreeParentId};if(n)return a.bitmapUrl=ss(this,Wd,cke).call(this,!0),a.accessibilityData=this.serializeAltText(!0),a;const{decorative:i,altText:l}=this.serializeAltText(!1);if(!i&&l&&(a.accessibilityData={type:"Figure",alt:l}),this.annotationElementId){const c=ss(this,Wd,vqt).call(this,a);if(c.isSame)return null;c.isSameAltText?delete a.accessibilityData:a.accessibilityData.structParent=this._initialData.structParent??-1}if(a.id=this.annotationElementId,r===null)return a;r.stamps||(r.stamps=new Map);const o=ge(this,Aw)?(a.rect[2]-a.rect[0])*(a.rect[3]-a.rect[1]):null;if(!r.stamps.has(ge(this,V0)))r.stamps.set(ge(this,V0),{area:o,serialized:a}),a.bitmap=ss(this,Wd,cke).call(this,!1);else if(ge(this,Aw)){const c=r.stamps.get(ge(this,V0));o>c.area&&(c.area=o,c.serialized.bitmap.close(),c.serialized.bitmap=ss(this,Wd,cke).call(this,!1))}return a}renderAnnotationElement(n){return n.updateEdited({rect:this.getRect(0,0)}),null}};Np=new WeakMap,V0=new WeakMap,hT=new WeakMap,KC=new WeakMap,mT=new WeakMap,eU=new WeakMap,JS=new WeakMap,YC=new WeakMap,e5=new WeakMap,Aw=new WeakMap,tU=new WeakMap,Wd=new WeakSet,eK=function(n,r=!1){if(!n){this.remove();return}$t(this,Np,n.bitmap),r||($t(this,V0,n.id),$t(this,Aw,n.isSvg)),n.file&&$t(this,eU,n.file.name),ss(this,Wd,FUe).call(this)},tK=function(){if($t(this,hT,null),this._uiManager.enableWaiting(!1),!!ge(this,JS)){if(this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&ge(this,Np)){this._editToolbar.hide(),this._uiManager.editAltText(this,!0);return}if(!this._uiManager.useNewAltTextWhenAddingImage&&this._uiManager.useNewAltTextFlow&&ge(this,Np)){this._reportTelemetry({action:"pdfjs.image.image_added",data:{alt_text_modal:!1,alt_text_type:"empty"}});try{this.mlGuessAltText()}catch{}}this.div.focus()}},oke=function(){if(ge(this,V0)){this._uiManager.enableWaiting(!0),this._uiManager.imageManager.getFromId(ge(this,V0)).then(a=>ss(this,Wd,eK).call(this,a,!0)).finally(()=>ss(this,Wd,tK).call(this));return}if(ge(this,KC)){const a=ge(this,KC);$t(this,KC,null),this._uiManager.enableWaiting(!0),$t(this,hT,this._uiManager.imageManager.getFromUrl(a).then(i=>ss(this,Wd,eK).call(this,i)).finally(()=>ss(this,Wd,tK).call(this)));return}if(ge(this,mT)){const a=ge(this,mT);$t(this,mT,null),this._uiManager.enableWaiting(!0),$t(this,hT,this._uiManager.imageManager.getFromFile(a).then(i=>ss(this,Wd,eK).call(this,i)).finally(()=>ss(this,Wd,tK).call(this)));return}const n=document.createElement("input");n.type="file",n.accept=pZ.supportedTypesStr;const r=this._uiManager._signal;$t(this,hT,new Promise(a=>{n.addEventListener("change",async()=>{if(!n.files||n.files.length===0)this.remove();else{this._uiManager.enableWaiting(!0);const i=await this._uiManager.imageManager.getFromFile(n.files[0]);this._reportTelemetry({action:"pdfjs.image.image_selected",data:{alt_text_modal:this._uiManager.useNewAltTextFlow}}),ss(this,Wd,eK).call(this,i)}a()},{signal:r}),n.addEventListener("cancel",()=>{this.remove(),a()},{signal:r})}).finally(()=>ss(this,Wd,tK).call(this))),n.click()},FUe=function(){const{div:n}=this;let{width:r,height:a}=ge(this,Np);const[i,l]=this.pageDimensions,o=.75;if(this.width)r=this.width*i,a=this.height*l;else if(r>o*i||a>o*l){const h=Math.min(o*i/r,o*l/a);r*=h,a*=h}const[c,d]=this.parentDimensions;this.setDims(r*c/i,a*d/l),this._uiManager.enableWaiting(!1);const u=$t(this,JS,document.createElement("canvas"));u.setAttribute("role","img"),this.addContainer(u),(!this._uiManager.useNewAltTextWhenAddingImage||!this._uiManager.useNewAltTextFlow||this.annotationElementId)&&(n.hidden=!1),ss(this,Wd,zUe).call(this,r,a),ss(this,Wd,yqt).call(this),ge(this,tU)||(this.parent.addUndoableEditor(this),$t(this,tU,!0)),this._reportTelemetry({action:"inserted_image"}),ge(this,eU)&&u.setAttribute("aria-label",ge(this,eU))},xqt=function(n,r){var o;const[a,i]=this.parentDimensions;this.width=n/a,this.height=r/i,(o=this._initialOptions)!=null&&o.isCentered?this.center():this.fixAndSetPosition(),this._initialOptions=null,ge(this,e5)!==null&&clearTimeout(ge(this,e5)),$t(this,e5,setTimeout(()=>{$t(this,e5,null),ss(this,Wd,zUe).call(this,n,r)},200))},lke=function(n,r){const{width:a,height:i}=ge(this,Np);let l=a,o=i,c=ge(this,Np);for(;l>2*n||o>2*r;){const d=l,u=o;l>2*n&&(l=l>=16384?Math.floor(l/2)-1:Math.ceil(l/2)),o>2*r&&(o=o>=16384?Math.floor(o/2)-1:Math.ceil(o/2));const h=new OffscreenCanvas(l,o);h.getContext("2d").drawImage(c,0,0,d,u,0,0,l,o),c=h.transferToImageBitmap()}return c},zUe=function(n,r){const a=new L$e,i=Math.ceil(n*a.sx),l=Math.ceil(r*a.sy),o=ge(this,JS);if(!o||o.width===i&&o.height===l)return;o.width=i,o.height=l;const c=ge(this,Aw)?ge(this,Np):ss(this,Wd,lke).call(this,i,l),d=o.getContext("2d");d.filter=this._uiManager.hcmFilter,d.drawImage(c,0,0,c.width,c.height,0,0,i,l)},cke=function(n){if(n){if(ge(this,Aw)){const i=this._uiManager.imageManager.getSvgUrl(ge(this,V0));if(i)return i}const r=document.createElement("canvas");return{width:r.width,height:r.height}=ge(this,Np),r.getContext("2d").drawImage(ge(this,Np),0,0),r.toDataURL()}if(ge(this,Aw)){const[r,a]=this.pageDimensions,i=Math.round(this.width*r*OM.PDF_TO_CSS_UNITS),l=Math.round(this.height*a*OM.PDF_TO_CSS_UNITS),o=new OffscreenCanvas(i,l);return o.getContext("2d").drawImage(ge(this,Np),0,0,ge(this,Np).width,ge(this,Np).height,0,0,i,l),o.transferToImageBitmap()}return structuredClone(ge(this,Np))},yqt=function(){this._uiManager._signal&&($t(this,YC,new ResizeObserver(n=>{const r=n[0].contentRect;r.width&&r.height&&ss(this,Wd,xqt).call(this,r.width,r.height)})),ge(this,YC).observe(this.div),this._uiManager._signal.addEventListener("abort",()=>{var n;(n=ge(this,YC))==null||n.disconnect(),$t(this,YC,null)},{once:!0}))},vqt=function(n){var d;const{rect:r,pageIndex:a,accessibilityData:{altText:i}}=this._initialData,l=n.rect.every((u,h)=>Math.abs(u-r[h])<1),o=n.pageIndex===a,c=(((d=n.accessibilityData)==null?void 0:d.alt)||"")===i;return{isSame:l&&o&&c,isSameAltText:c}},ur(pZ,"_type","stamp"),ur(pZ,"_editorType",Kc.STAMP);let OUe=pZ;var C8,sU,t5,fT,ZC,Ew,pT,nU,rU,Qv,XC,fl,gT,fv,bqt,$Ue,UUe,qUe,dke;const wN=class wN{constructor({uiManager:t,pageIndex:n,div:r,structTreeLayer:a,accessibilityManager:i,annotationLayer:l,drawLayer:o,textLayer:c,viewport:d,l10n:u}){ds(this,fv);ds(this,C8);ds(this,sU,!1);ds(this,t5,null);ds(this,fT,null);ds(this,ZC,null);ds(this,Ew,new Map);ds(this,pT,!1);ds(this,nU,!1);ds(this,rU,!1);ds(this,Qv,null);ds(this,XC,null);ds(this,fl);const h=[...ge(wN,gT).values()];if(!wN._initialized){wN._initialized=!0;for(const m of h)m.initialize(u,t)}t.registerEditorTypes(h),$t(this,fl,t),this.pageIndex=n,this.div=r,$t(this,C8,i),$t(this,t5,l),this.viewport=d,$t(this,Qv,c),this.drawLayer=o,this._structTree=a,ge(this,fl).addLayer(this)}get isEmpty(){return ge(this,Ew).size===0}get isInvisible(){return this.isEmpty&&ge(this,fl).getMode()===Kc.NONE}updateToolbar(t){ge(this,fl).updateToolbar(t)}updateMode(t=ge(this,fl).getMode()){switch(ss(this,fv,dke).call(this),t){case Kc.NONE:this.disableTextSelection(),this.togglePointerEvents(!1),this.toggleAnnotationLayerPointerEvents(!0),this.disableClick();return;case Kc.INK:this.addInkEditorIfNeeded(!1),this.disableTextSelection(),this.togglePointerEvents(!0),this.disableClick();break;case Kc.HIGHLIGHT:this.enableTextSelection(),this.togglePointerEvents(!1),this.disableClick();break;default:this.disableTextSelection(),this.togglePointerEvents(!0),this.enableClick()}this.toggleAnnotationLayerPointerEvents(!1);const{classList:n}=this.div;for(const r of ge(wN,gT).values())n.toggle(`${r._type}Editing`,t===r._editorType);this.div.hidden=!1}hasTextLayer(t){var n;return t===((n=ge(this,Qv))==null?void 0:n.div)}addInkEditorIfNeeded(t){if(ge(this,fl).getMode()!==Kc.INK)return;if(!t){for(const r of ge(this,Ew).values())if(r.isEmpty()){r.setInBackground();return}}this.createAndAddNewEditor({offsetX:0,offsetY:0},!1).setInBackground()}setEditingState(t){ge(this,fl).setEditingState(t)}addCommands(t){ge(this,fl).addCommands(t)}toggleDrawing(t=!1){this.div.classList.toggle("drawing",!t)}togglePointerEvents(t=!1){this.div.classList.toggle("disabled",!t)}toggleAnnotationLayerPointerEvents(t=!1){var n;(n=ge(this,t5))==null||n.div.classList.toggle("disabled",!t)}async enable(){this.div.tabIndex=0,this.togglePointerEvents(!0);const t=new Set;for(const r of ge(this,Ew).values())r.enableEditing(),r.show(!0),r.annotationElementId&&(ge(this,fl).removeChangedExistingAnnotation(r),t.add(r.annotationElementId));if(!ge(this,t5))return;const n=ge(this,t5).getEditableAnnotations();for(const r of n){if(r.hide(),ge(this,fl).isDeletedAnnotationElement(r.data.id)||t.has(r.data.id))continue;const a=await this.deserialize(r);a&&(this.addOrRebuild(a),a.enableEditing())}}disable(){var a;$t(this,rU,!0),this.div.tabIndex=-1,this.togglePointerEvents(!1);const t=new Map,n=new Map;for(const i of ge(this,Ew).values())if(i.disableEditing(),!!i.annotationElementId){if(i.serialize()!==null){t.set(i.annotationElementId,i);continue}else n.set(i.annotationElementId,i);(a=this.getEditableAnnotation(i.annotationElementId))==null||a.show(),i.remove()}if(ge(this,t5)){const i=ge(this,t5).getEditableAnnotations();for(const l of i){const{id:o}=l.data;if(ge(this,fl).isDeletedAnnotationElement(o))continue;let c=n.get(o);if(c){c.resetAnnotationElement(l),c.show(!1),l.show();continue}c=t.get(o),c&&(ge(this,fl).addChangedExistingAnnotation(c),c.renderAnnotationElement(l)&&c.show(!1)),l.show()}}ss(this,fv,dke).call(this),this.isEmpty&&(this.div.hidden=!0);const{classList:r}=this.div;for(const i of ge(wN,gT).values())r.remove(`${i._type}Editing`);this.disableTextSelection(),this.toggleAnnotationLayerPointerEvents(!0),$t(this,rU,!1)}getEditableAnnotation(t){var n;return((n=ge(this,t5))==null?void 0:n.getEditableAnnotation(t))||null}setActiveEditor(t){ge(this,fl).getActive()!==t&&ge(this,fl).setActiveEditor(t)}enableTextSelection(){var t;if(this.div.tabIndex=-1,(t=ge(this,Qv))!=null&&t.div&&!ge(this,XC)){$t(this,XC,new AbortController);const n=ge(this,fl).combinedSignal(ge(this,XC));ge(this,Qv).div.addEventListener("pointerdown",ss(this,fv,bqt).bind(this),{signal:n}),ge(this,Qv).div.classList.add("highlighting")}}disableTextSelection(){var t;this.div.tabIndex=0,(t=ge(this,Qv))!=null&&t.div&&ge(this,XC)&&(ge(this,XC).abort(),$t(this,XC,null),ge(this,Qv).div.classList.remove("highlighting"))}enableClick(){if(ge(this,fT))return;$t(this,fT,new AbortController);const t=ge(this,fl).combinedSignal(ge(this,fT));this.div.addEventListener("pointerdown",this.pointerdown.bind(this),{signal:t}),this.div.addEventListener("pointerup",this.pointerup.bind(this),{signal:t})}disableClick(){var t;(t=ge(this,fT))==null||t.abort(),$t(this,fT,null)}attach(t){ge(this,Ew).set(t.id,t);const{annotationElementId:n}=t;n&&ge(this,fl).isDeletedAnnotationElement(n)&&ge(this,fl).removeDeletedAnnotationElement(t)}detach(t){var n;ge(this,Ew).delete(t.id),(n=ge(this,C8))==null||n.removePointerInTextLayer(t.contentDiv),!ge(this,rU)&&t.annotationElementId&&ge(this,fl).addDeletedAnnotationElement(t)}remove(t){this.detach(t),ge(this,fl).removeEditor(t),t.div.remove(),t.isAttachedToDOM=!1,ge(this,nU)||this.addInkEditorIfNeeded(!1)}changeParent(t){var n;t.parent!==this&&(t.parent&&t.annotationElementId&&(ge(this,fl).addDeletedAnnotationElement(t.annotationElementId),Ph.deleteAnnotationElement(t),t.annotationElementId=null),this.attach(t),(n=t.parent)==null||n.detach(t),t.setParent(this),t.div&&t.isAttachedToDOM&&(t.div.remove(),this.div.append(t.div)))}add(t){if(!(t.parent===this&&t.isAttachedToDOM)){if(this.changeParent(t),ge(this,fl).addEditor(t),this.attach(t),!t.isAttachedToDOM){const n=t.render();this.div.append(n),t.isAttachedToDOM=!0}t.fixAndSetPosition(),t.onceAdded(),ge(this,fl).addToAnnotationStorage(t),t._reportTelemetry(t.telemetryInitialData)}}moveEditorInDOM(t){var r;if(!t.isAttachedToDOM)return;const{activeElement:n}=document;t.div.contains(n)&&!ge(this,ZC)&&(t._focusEventsAllowed=!1,$t(this,ZC,setTimeout(()=>{$t(this,ZC,null),t.div.contains(document.activeElement)?t._focusEventsAllowed=!0:(t.div.addEventListener("focusin",()=>{t._focusEventsAllowed=!0},{once:!0,signal:ge(this,fl)._signal}),n.focus())},0))),t._structTreeParentId=(r=ge(this,C8))==null?void 0:r.moveElementInDOM(this.div,t.div,t.contentDiv,!0)}addOrRebuild(t){t.needsToBeRebuilt()?(t.parent||(t.parent=this),t.rebuild(),t.show()):this.add(t)}addUndoableEditor(t){const n=()=>t._uiManager.rebuild(t),r=()=>{t.remove()};this.addCommands({cmd:n,undo:r,mustExec:!1})}getNextId(){return ge(this,fl).getId()}combinedSignal(t){return ge(this,fl).combinedSignal(t)}canCreateNewEmptyEditor(){var t;return(t=ge(this,fv,$Ue))==null?void 0:t.canCreateNewEmptyEditor()}pasteEditor(t,n){ge(this,fl).updateToolbar(t),ge(this,fl).updateMode(t);const{offsetX:r,offsetY:a}=ss(this,fv,qUe).call(this),i=this.getNextId(),l=ss(this,fv,UUe).call(this,{parent:this,id:i,x:r,y:a,uiManager:ge(this,fl),isCentered:!0,...n});l&&this.add(l)}async deserialize(t){var n;return await((n=ge(wN,gT).get(t.annotationType??t.annotationEditorType))==null?void 0:n.deserialize(t,this,ge(this,fl)))||null}createAndAddNewEditor(t,n,r={}){const a=this.getNextId(),i=ss(this,fv,UUe).call(this,{parent:this,id:a,x:t.offsetX,y:t.offsetY,uiManager:ge(this,fl),isCentered:n,...r});return i&&this.add(i),i}addNewEditor(){this.createAndAddNewEditor(ss(this,fv,qUe).call(this),!0)}setSelected(t){ge(this,fl).setSelected(t)}toggleSelected(t){ge(this,fl).toggleSelected(t)}unselect(t){ge(this,fl).unselect(t)}pointerup(t){const{isMac:n}=_b.platform;if(!(t.button!==0||t.ctrlKey&&n)&&t.target===this.div&&ge(this,pT)){if($t(this,pT,!1),!ge(this,sU)){$t(this,sU,!0);return}if(ge(this,fl).getMode()===Kc.STAMP){ge(this,fl).unselectAll();return}this.createAndAddNewEditor(t,!1)}}pointerdown(t){if(ge(this,fl).getMode()===Kc.HIGHLIGHT&&this.enableTextSelection(),ge(this,pT)){$t(this,pT,!1);return}const{isMac:n}=_b.platform;if(t.button!==0||t.ctrlKey&&n||t.target!==this.div)return;$t(this,pT,!0);const r=ge(this,fl).getActive();$t(this,sU,!r||r.isEmpty())}findNewParent(t,n,r){const a=ge(this,fl).findParent(n,r);return a===null||a===this?!1:(a.changeParent(t),!0)}destroy(){var t,n;((t=ge(this,fl).getActive())==null?void 0:t.parent)===this&&(ge(this,fl).commitOrRemove(),ge(this,fl).setActiveEditor(null)),ge(this,ZC)&&(clearTimeout(ge(this,ZC)),$t(this,ZC,null));for(const r of ge(this,Ew).values())(n=ge(this,C8))==null||n.removePointerInTextLayer(r.contentDiv),r.setParent(null),r.isAttachedToDOM=!1,r.div.remove();this.div=null,ge(this,Ew).clear(),ge(this,fl).removeLayer(this)}render({viewport:t}){this.viewport=t,aF(this.div,t);for(const n of ge(this,fl).getEditors(this.pageIndex))this.add(n),n.rebuild();this.updateMode()}update({viewport:t}){ge(this,fl).commitOrRemove(),ss(this,fv,dke).call(this);const n=this.viewport.rotation,r=t.rotation;if(this.viewport=t,aF(this.div,{rotation:r}),n!==r)for(const a of ge(this,Ew).values())a.rotate(r);this.addInkEditorIfNeeded(!1)}get pageDimensions(){const{pageWidth:t,pageHeight:n}=this.viewport.rawDims;return[t,n]}get scale(){return ge(this,fl).viewParameters.realScale}};C8=new WeakMap,sU=new WeakMap,t5=new WeakMap,fT=new WeakMap,ZC=new WeakMap,Ew=new WeakMap,pT=new WeakMap,nU=new WeakMap,rU=new WeakMap,Qv=new WeakMap,XC=new WeakMap,fl=new WeakMap,gT=new WeakMap,fv=new WeakSet,bqt=function(t){ge(this,fl).unselectAll();const{target:n}=t;if(n===ge(this,Qv).div||(n.getAttribute("role")==="img"||n.classList.contains("endOfContent"))&&ge(this,Qv).div.contains(n)){const{isMac:r}=_b.platform;if(t.button!==0||t.ctrlKey&&r)return;ge(this,fl).showAllEditors("highlight",!0,!0),ge(this,Qv).div.classList.add("free"),this.toggleDrawing(),Z4e.startHighlighting(this,ge(this,fl).direction==="ltr",{target:ge(this,Qv).div,x:t.x,y:t.y}),ge(this,Qv).div.addEventListener("pointerup",()=>{ge(this,Qv).div.classList.remove("free"),this.toggleDrawing(!0)},{once:!0,signal:ge(this,fl)._signal}),t.preventDefault()}},$Ue=function(){return ge(wN,gT).get(ge(this,fl).getMode())},UUe=function(t){const n=ge(this,fv,$Ue);return n?new n.prototype.constructor(t):null},qUe=function(){const{x:t,y:n,width:r,height:a}=this.div.getBoundingClientRect(),i=Math.max(0,t),l=Math.max(0,n),o=Math.min(window.innerWidth,t+r),c=Math.min(window.innerHeight,n+a),d=(i+o)/2-t,u=(l+c)/2-n,[h,m]=this.viewport.rotation%180===0?[d,u]:[u,d];return{offsetX:h,offsetY:m}},dke=function(){$t(this,nU,!0);for(const t of ge(this,Ew).values())t.isEmpty()&&t.remove();$t(this,nU,!1)},ur(wN,"_initialized",!1),ds(wN,gT,new Map([vUe,AUe,OUe,Z4e].map(t=>[t._editorType,t])));let BUe=wN;var s5,HJ,kx,QC,GJ,HUe,dF,GUe,_qt;const B0=class B0{constructor({pageIndex:t}){ds(this,dF);ds(this,s5,null);ds(this,HJ,0);ds(this,kx,new Map);ds(this,QC,new Map);this.pageIndex=t}setParent(t){if(!ge(this,s5)){$t(this,s5,t);return}if(ge(this,s5)!==t){if(ge(this,kx).size>0)for(const n of ge(this,kx).values())n.remove(),t.append(n);$t(this,s5,t)}}static get _svgFactory(){return nu(this,"_svgFactory",new aQe)}draw(t,n,r,a=!1){const i=Hy(this,HJ)._++,l=ss(this,dF,GUe).call(this,t.box);l.classList.add(...t.classNamesForDrawing);const o=B0._svgFactory.createElement("defs");l.append(o);const c=B0._svgFactory.createElement("path");o.append(c);const d=`path_p${this.pageIndex}_${i}`;c.setAttribute("id",d),c.setAttribute("d",t.toSVGPath()),a&&ge(this,QC).set(i,c);const u=ss(this,dF,_qt).call(this,o,d),h=B0._svgFactory.createElement("use");return l.append(h),l.setAttribute("fill",n),l.setAttribute("fill-opacity",r),h.setAttribute("href",`#${d}`),ge(this,kx).set(i,l),{id:i,clipPathId:`url(#${u})`}}drawOutline(t){const n=Hy(this,HJ)._++,r=ss(this,dF,GUe).call(this,t.box);r.classList.add(...t.classNamesForOutlining);const a=B0._svgFactory.createElement("defs");r.append(a);const i=B0._svgFactory.createElement("path");a.append(i);const l=`path_p${this.pageIndex}_${n}`;i.setAttribute("id",l),i.setAttribute("d",t.toSVGPath()),i.setAttribute("vector-effect","non-scaling-stroke");let o;if(t.mustRemoveSelfIntersections){const u=B0._svgFactory.createElement("mask");a.append(u),o=`mask_p${this.pageIndex}_${n}`,u.setAttribute("id",o),u.setAttribute("maskUnits","objectBoundingBox");const h=B0._svgFactory.createElement("rect");u.append(h),h.setAttribute("width","1"),h.setAttribute("height","1"),h.setAttribute("fill","white");const m=B0._svgFactory.createElement("use");u.append(m),m.setAttribute("href",`#${l}`),m.setAttribute("stroke","none"),m.setAttribute("fill","black"),m.setAttribute("fill-rule","nonzero"),m.classList.add("mask")}const c=B0._svgFactory.createElement("use");r.append(c),c.setAttribute("href",`#${l}`),o&&c.setAttribute("mask",`url(#${o})`);const d=c.cloneNode();return r.append(d),c.classList.add("mainOutline"),d.classList.add("secondaryOutline"),ge(this,kx).set(n,r),n}finalizeLine(t,n){const r=ge(this,QC).get(t);ge(this,QC).delete(t),this.updateBox(t,n.box),r.setAttribute("d",n.toSVGPath())}updateLine(t,n){ge(this,kx).get(t).firstChild.firstChild.setAttribute("d",n.toSVGPath())}updatePath(t,n){ge(this,QC).get(t).setAttribute("d",n.toSVGPath())}updateBox(t,n){var r;ss(r=B0,GJ,HUe).call(r,ge(this,kx).get(t),n)}show(t,n){ge(this,kx).get(t).classList.toggle("hidden",!n)}rotate(t,n){ge(this,kx).get(t).setAttribute("data-main-rotation",n)}changeColor(t,n){ge(this,kx).get(t).setAttribute("fill",n)}changeOpacity(t,n){ge(this,kx).get(t).setAttribute("fill-opacity",n)}addClass(t,n){ge(this,kx).get(t).classList.add(n)}removeClass(t,n){ge(this,kx).get(t).classList.remove(n)}getSVGRoot(t){return ge(this,kx).get(t)}remove(t){ge(this,QC).delete(t),ge(this,s5)!==null&&(ge(this,kx).get(t).remove(),ge(this,kx).delete(t))}destroy(){$t(this,s5,null);for(const t of ge(this,kx).values())t.remove();ge(this,kx).clear(),ge(this,QC).clear()}};s5=new WeakMap,HJ=new WeakMap,kx=new WeakMap,QC=new WeakMap,GJ=new WeakSet,HUe=function(t,{x:n=0,y:r=0,width:a=1,height:i=1}={}){const{style:l}=t;l.top=`${100*r}%`,l.left=`${100*n}%`,l.width=`${100*a}%`,l.height=`${100*i}%`},dF=new WeakSet,GUe=function(t){var r;const n=B0._svgFactory.create(1,1,!0);return ge(this,s5).append(n),n.setAttribute("aria-hidden",!0),ss(r=B0,GJ,HUe).call(r,n,t),n},_qt=function(t,n){const r=B0._svgFactory.createElement("clipPath");t.append(r);const a=`clip_${n}`;r.setAttribute("id",a),r.setAttribute("clipPathUnits","objectBoundingBox");const i=B0._svgFactory.createElement("use");return r.append(i),i.setAttribute("href",`#${n}`),i.classList.add("clip"),a},ds(B0,GJ);let VUe=B0;Cc.AbortException;Cc.AnnotationEditorLayer;Cc.AnnotationEditorParamsType;Cc.AnnotationEditorType;Cc.AnnotationEditorUIManager;Cc.AnnotationLayer;Cc.AnnotationMode;Cc.ColorPicker;Cc.DOMSVGFactory;Cc.DrawLayer;Cc.FeatureTest;var iPn=Cc.GlobalWorkerOptions;Cc.ImageKind;Cc.InvalidPDFException;Cc.MissingPDFException;Cc.OPS;Cc.OutputScale;Cc.PDFDataRangeTransport;Cc.PDFDateString;Cc.PDFWorker;Cc.PasswordResponses;Cc.PermissionFlag;Cc.PixelsPerInch;Cc.RenderingCancelledException;Cc.TextLayer;Cc.UnexpectedResponseException;Cc.Util;Cc.VerbosityLevel;Cc.XfaLayer;Cc.build;Cc.createValidAbsoluteUrl;Cc.fetchData;var oPn=Cc.getDocument;Cc.getFilenameFromUrl;Cc.getPdfFilenameFromUrl;Cc.getXfaPageViewport;Cc.isDataScheme;Cc.isPdfFile;Cc.noContextMenu;Cc.normalizeUnicode;Cc.setLayerDimensions;Cc.shadow;Cc.version;const lPn="/assets/pdf.worker.min-GB3t0DcA.mjs";iPn.workerSrc=lPn;const cPn=({blob:s,scale:t=1.5})=>{const n=k.useRef(null),[r,a]=k.useState(!1),[i,l]=k.useState(null);return k.useEffect(()=>{let o=!1;const c=n.current;return!s||!c?void 0:((async()=>{a(!0),l(null);try{const u=await s.arrayBuffer(),h=await oPn({data:u}).promise;if(o)return;c.innerHTML="";for(let m=1;m<=h.numPages;m+=1){const p=await h.getPage(m);if(o)return;const g=p.getViewport({scale:t}),x=document.createElement("canvas");x.width=Math.floor(g.width),x.height=Math.floor(g.height),x.className="mx-auto w-full max-w-[900px] rounded-md border border-border bg-white shadow-sm";const y=x.getContext("2d");y&&(c.appendChild(x),await p.render({canvasContext:y,viewport:g}).promise)}}catch(u){o||l((u==null?void 0:u.message)||"Could not render the preview")}finally{o||a(!1)}})(),()=>{o=!0})},[s,t]),e.jsxs("div",{className:"relative h-full overflow-y-auto bg-muted/40 p-4",children:[r&&e.jsx("div",{className:"absolute inset-0 z-10 flex items-center justify-center bg-background/70",children:e.jsx(Jt,{className:"h-6 w-6 animate-spin text-muted-foreground"})}),i&&e.jsx("p",{className:"p-4 text-sm text-destructive",children:i}),e.jsx("div",{ref:n,className:"space-y-4"})]})};function bte({label:s,value:t,onChange:n,prefix:r="presentation",hint:a,urlPlaceholder:i="…or paste an image URL",round:l=!1,className:o}){const{user:c}=ks(),d=k.useRef(null),[u,h]=k.useState(!1),m=async p=>{if(!(!p||!c)){if(!p.type.startsWith("image/")){ae.error("Please choose an image file");return}if(p.size>20*1024*1024){ae.error("That photo is larger than 20 MB");return}h(!0);try{const g=await nMn(c.id,p,r);n(g),ae.success("Photo uploaded")}catch(g){ae.error((g==null?void 0:g.message)||"Upload failed")}finally{h(!1),d.current&&(d.current.value="")}}};return e.jsxs("div",{className:Ot("space-y-2",o),children:[e.jsx(re,{className:"text-xs",children:s}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:Ot("relative shrink-0 overflow-hidden border bg-muted",l?"h-16 w-16 rounded-full":"h-16 w-24 rounded-md"),children:t?e.jsx("img",{src:t,alt:s,className:"h-full w-full object-cover"}):e.jsx("div",{className:"flex h-full w-full items-center justify-center text-muted-foreground",children:e.jsx(zc,{className:"h-5 w-5"})})}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("input",{ref:d,type:"file",accept:"image/*",className:"hidden",onChange:p=>{var g;return m((g=p.target.files)==null?void 0:g[0])}}),e.jsxs($,{type:"button",variant:"outline",size:"sm",className:"gap-2",disabled:u,onClick:()=>{var p;return(p=d.current)==null?void 0:p.click()},children:[u?e.jsx(Jt,{className:"h-4 w-4 animate-spin"}):e.jsx(gb,{className:"h-4 w-4"}),t?"Replace photo":"Upload photo"]}),t&&e.jsxs($,{type:"button",variant:"ghost",size:"sm",className:"gap-1 text-muted-foreground",onClick:()=>n(null),children:[e.jsx(mr,{className:"h-4 w-4"})," Remove"]})]})]}),e.jsx(be,{value:t||"",onChange:p=>n(p.target.value||null),placeholder:i}),a&&e.jsx("p",{className:"text-xs text-muted-foreground",children:a})]})}function dPn({value:s,onChange:t}){return e.jsxs(we,{children:[e.jsxs(Vt,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Xn,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(Yt,{className:"text-base",children:"Co-listing agent"})]}),e.jsx(On,{checked:s.enabled,onCheckedChange:n=>t({enabled:n})})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Adds a second agent to the cover, the About page, and the closing contact card."})]}),s.enabled&&e.jsxs(De,{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Name"}),e.jsx(be,{value:s.name,onChange:n=>t({name:n.target.value}),placeholder:"Jordan Ellis"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Title"}),e.jsx(be,{value:s.title||"",onChange:n=>t({title:n.target.value}),placeholder:"Co-listing agent"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Phone"}),e.jsx(be,{value:s.phone||"",onChange:n=>t({phone:n.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Email"}),e.jsx(be,{value:s.email||"",onChange:n=>t({email:n.target.value})})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Brokerage"}),e.jsx(be,{value:s.brokerageName||"",onChange:n=>t({brokerageName:n.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"License #"}),e.jsx(be,{value:s.licenseNumber||"",onChange:n=>t({licenseNumber:n.target.value})})]})]}),e.jsx(bte,{label:"Headshot",value:s.headshotUrl,onChange:n=>t({headshotUrl:n||""}),prefix:"co-agent",round:!0}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Shared bio (optional)"}),e.jsx(Ls,{rows:4,value:s.bio||"",onChange:n=>t({bio:n.target.value}),placeholder:"Replaces the intro paragraph on the About page when both agents are shown."})]})]})]})}function uPn({value:s,onChange:t}){return e.jsxs(we,{children:[e.jsxs(Vt,{className:"pb-3",children:[e.jsx(Yt,{className:"text-base",children:"Presentation theme"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Themes restyle every page — paper, headline type, and palette. Signature follows your own brand colors."})]}),e.jsx(De,{className:"grid gap-2 sm:grid-cols-2",children:E$e.map(n=>{const r=n.id===s;return e.jsxs("button",{type:"button",onClick:()=>t(n.id),className:Ot("group relative overflow-hidden rounded-xl border p-3 text-left transition-all hover:shadow-sm",r?"border-primary ring-1 ring-primary":"border-border"),children:[e.jsx("div",{className:"flex h-10 w-full overflow-hidden rounded-md",children:n.swatch.map(a=>e.jsx("div",{className:"flex-1",style:{backgroundColor:a}},a))}),e.jsxs("div",{className:"mt-2 flex items-center justify-between gap-2",children:[e.jsx("span",{className:"text-sm font-medium",children:n.name}),r&&e.jsx(ma,{className:"h-4 w-4 text-primary"})]}),e.jsx("p",{className:"mt-1 text-xs leading-snug text-muted-foreground",children:n.description})]},n.id)})})]})}const hPn={cover:[{key:"kicker",label:"Cover eyebrow"},{key:"body",label:"Cover paragraph",long:!0}],welcome:[{key:"kicker",label:"Eyebrow"},{key:"headline",label:"Headline",long:!0},{key:"subhead",label:"Subhead",long:!0}],agent:[{key:"kicker",label:"Eyebrow"},{key:"headline",label:"Headline",long:!0},{key:"subhead",label:"Subhead (defaults to your tagline)",long:!0}],overview:[{key:"kicker",label:"Eyebrow"},{key:"headline",label:"Headline",long:!0},{key:"subhead",label:"Subhead",long:!0}],closing:[{key:"kicker",label:"Eyebrow"},{key:"headline",label:"Headline",long:!0},{key:"body",label:"Closing paragraph",long:!0}]},mPn=["cover","welcome","agent","overview","closing"];function fPn({pages:s,onChange:t}){const n=new Set(s.hidden||[]),r=(i,l,o)=>{t({...s,copy:{...s.copy||{},[i]:{...(s.copy||{})[i]||{},[l]:o}}})},a=i=>{const l={...s.copy||{}};delete l[i],t({...s,copy:l})};return e.jsxs(we,{children:[e.jsxs(Vt,{className:"pb-3",children:[e.jsx(Yt,{className:"text-base",children:"Edit page wording"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Rewrite the headlines on the built-in pages. The preview updates as you type."})]}),e.jsx(De,{children:e.jsx(SF,{type:"multiple",className:"w-full",children:mPn.filter(i=>i==="cover"||!n.has(i)).map(i=>{const l=dBt(s,i);return e.jsxs(r6,{value:i,children:[e.jsx(a6,{className:"text-sm",children:k3n[i]}),e.jsxs(i6,{className:"space-y-3 pt-1",children:[hPn[i].map(o=>e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{className:"text-xs",children:o.label}),o.long?e.jsx(Ls,{rows:2,value:l[o.key]||"",placeholder:f$e[i][o.key],onChange:c=>r(i,o.key,c.target.value)}):e.jsx(be,{value:l[o.key]||"",placeholder:f$e[i][o.key],onChange:c=>r(i,o.key,c.target.value)})]},o.key)),e.jsxs($,{variant:"ghost",size:"sm",className:"gap-2",onClick:()=>a(i),children:[e.jsx(jm,{className:"h-3.5 w-3.5"})," Reset to default wording"]})]})]},i)})})})]})}function pPn({pages:s,onChange:t}){const n=[...s].sort((o,c)=>o.order-c.order),r=(o,c)=>t(n.map(d=>d.id===o?{...d,...c}:d)),a=o=>t([...n,FXe(o,n.length)]),i=o=>t(n.filter(c=>c.id!==o).map((c,d)=>({...c,order:d}))),l=(o,c)=>{const d=n.findIndex(m=>m.id===o),u=d+c;if(d<0||u<0||u>=n.length)return;const h=[...n];[h[d],h[u]]=[h[u],h[d]],t(h.map((m,p)=>({...m,order:p})))};return e.jsxs(we,{children:[e.jsxs(Vt,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Zw,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(Yt,{className:"text-base",children:"Your own pages"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Add About Us, testimonials, track record, or a statement page. Each one is styled to match the rest of the presentation and can be toggled on or off."})]}),e.jsxs(De,{className:"space-y-4",children:[e.jsx("div",{className:"grid gap-2 sm:grid-cols-2",children:hDe.map(o=>e.jsxs("button",{type:"button",onClick:()=>a(o.layout),className:"rounded-lg border p-3 text-left transition-colors hover:border-primary hover:bg-muted/50",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"text-sm font-medium",children:o.name}),e.jsx(nn,{className:"h-3.5 w-3.5 text-muted-foreground"})]}),e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:o.description})]},o.layout))}),n.length>0&&e.jsxs(e.Fragment,{children:[e.jsx(Pc,{}),e.jsx(SF,{type:"multiple",className:"w-full",children:n.map((o,c)=>{var d,u,h;return e.jsxs(r6,{value:o.id,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(On,{checked:o.enabled,onCheckedChange:m=>r(o.id,{enabled:m})}),e.jsx(a6,{className:"flex-1 text-left text-sm",children:e.jsxs("span",{className:"flex items-center gap-2",children:[((d=o.headline)==null?void 0:d.trim())||((u=hDe.find(m=>m.layout===o.layout))==null?void 0:u.name),e.jsx(qe,{variant:"secondary",className:"text-[10px]",children:(h=hDe.find(m=>m.layout===o.layout))==null?void 0:h.name})]})}),e.jsx($,{variant:"ghost",size:"icon",className:"h-7 w-7",disabled:c===0,onClick:()=>l(o.id,-1),children:e.jsx(ap,{className:"h-3.5 w-3.5"})}),e.jsx($,{variant:"ghost",size:"icon",className:"h-7 w-7",disabled:c===n.length-1,onClick:()=>l(o.id,1),children:e.jsx(nx,{className:"h-3.5 w-3.5"})}),e.jsx($,{variant:"ghost",size:"icon",className:"h-7 w-7 text-destructive",onClick:()=>i(o.id),children:e.jsx(Un,{className:"h-3.5 w-3.5"})})]}),e.jsxs(i6,{className:"space-y-3 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(re,{className:"text-xs",children:"Placement"}),e.jsxs(bs,{value:o.placement,onValueChange:m=>r(o.id,{placement:m}),children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"after-agent",children:'After "About your agent"'}),e.jsx(We,{value:"end",children:"Before the closing page"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{className:"text-xs",children:"Style"}),e.jsxs("div",{className:"flex h-10 items-center gap-2 rounded-md border px-3",children:[e.jsx(On,{checked:o.dark,onCheckedChange:m=>r(o.id,{dark:m})}),e.jsx("span",{className:"text-sm",children:"Dark background"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{className:"text-xs",children:"Eyebrow"}),e.jsx(be,{value:o.kicker,onChange:m=>r(o.id,{kicker:m.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{className:"text-xs",children:"Headline"}),e.jsx(be,{value:o.headline,onChange:m=>r(o.id,{headline:m.target.value})})]}),o.layout!=="statement"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{className:"text-xs",children:"Subhead"}),e.jsx(be,{value:o.subhead,onChange:m=>r(o.id,{subhead:m.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{className:"text-xs",children:"Body copy"}),e.jsx(Ls,{rows:5,value:o.body,onChange:m=>r(o.id,{body:m.target.value}),placeholder:"Leave a blank line between paragraphs."})]}),(o.layout==="story"||o.layout==="checklist"||o.layout==="statement")&&e.jsx(bte,{label:"Photo (optional)",value:o.imageUrl,onChange:m=>r(o.id,{imageUrl:m}),prefix:"custom-page",urlPlaceholder:"…or paste an image URL",hint:"Defaults to the property photo when left empty."}),o.layout==="story"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{className:"text-xs",children:"Photo side"}),e.jsxs(bs,{value:o.imageSide,onValueChange:m=>r(o.id,{imageSide:m}),children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"right",children:"Right"}),e.jsx(We,{value:"left",children:"Left"})]})]})]}),(o.layout==="story"||o.layout==="checklist")&&e.jsxs("div",{className:"space-y-2 rounded-lg border bg-muted/30 p-3",children:[e.jsx(re,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"List items"}),o.bullets.map((m,p)=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(be,{value:m,onChange:g=>{const x=[...o.bullets];x[p]=g.target.value,r(o.id,{bullets:x})}}),e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive",onClick:()=>r(o.id,{bullets:o.bullets.filter((g,x)=>x!==p)}),children:e.jsx(Un,{className:"h-3.5 w-3.5"})})]},p)),e.jsxs($,{variant:"outline",size:"sm",className:"gap-2",disabled:o.bullets.length>=7,onClick:()=>r(o.id,{bullets:[...o.bullets,""]}),children:[e.jsx(nn,{className:"h-3.5 w-3.5"})," Add item"]})]}),o.layout==="testimonials"&&e.jsxs("div",{className:"space-y-3 rounded-lg border bg-muted/30 p-3",children:[e.jsx(re,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Testimonials (up to 4)"}),o.testimonials.map((m,p)=>e.jsxs("div",{className:"space-y-2 rounded-md border bg-background p-3",children:[e.jsx(Ls,{rows:3,value:m.quote,placeholder:"Client quote",onChange:g=>{const x=[...o.testimonials];x[p]={...m,quote:g.target.value},r(o.id,{testimonials:x})}}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(be,{value:m.name,placeholder:"Name",onChange:g=>{const x=[...o.testimonials];x[p]={...m,name:g.target.value},r(o.id,{testimonials:x})}}),e.jsx(be,{value:m.detail,placeholder:"Neighborhood or year",onChange:g=>{const x=[...o.testimonials];x[p]={...m,detail:g.target.value},r(o.id,{testimonials:x})}})]}),e.jsxs($,{variant:"ghost",size:"sm",className:"gap-2 text-destructive",onClick:()=>r(o.id,{testimonials:o.testimonials.filter((g,x)=>x!==p)}),children:[e.jsx(Un,{className:"h-3.5 w-3.5"})," Remove"]})]},p)),e.jsxs($,{variant:"outline",size:"sm",className:"gap-2",disabled:o.testimonials.length>=4,onClick:()=>r(o.id,{testimonials:[...o.testimonials,{quote:"",name:"",detail:""}]}),children:[e.jsx(nn,{className:"h-3.5 w-3.5"})," Add testimonial"]})]}),o.layout==="stats"&&e.jsxs("div",{className:"space-y-2 rounded-lg border bg-muted/30 p-3",children:[e.jsx(re,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Stats (up to 4)"}),o.stats.map((m,p)=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(be,{className:"w-28",value:m.value,placeholder:"27",onChange:g=>{const x=[...o.stats];x[p]={...m,value:g.target.value},r(o.id,{stats:x})}}),e.jsx(be,{value:m.label,placeholder:"Homes sold",onChange:g=>{const x=[...o.stats];x[p]={...m,label:g.target.value},r(o.id,{stats:x})}}),e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive",onClick:()=>r(o.id,{stats:o.stats.filter((g,x)=>x!==p)}),children:e.jsx(Un,{className:"h-3.5 w-3.5"})})]},p)),e.jsxs($,{variant:"outline",size:"sm",className:"gap-2",disabled:o.stats.length>=4,onClick:()=>r(o.id,{stats:[...o.stats,{value:"",label:""}]}),children:[e.jsx(nn,{className:"h-3.5 w-3.5"})," Add stat"]}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Only use numbers you can back up — leave a stat blank to hide it."})]})]})]},o.id)})})]})]})]})}function gPn({open:s,onOpenChange:t,defaultName:n,saving:r,onSave:a}){const[i,l]=k.useState(""),[o,c]=k.useState("");return k.useEffect(()=>{s&&(l((n==null?void 0:n.trim())||"My listing presentation"),c(""))},[s,n]),e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"sm:max-w-md",children:[e.jsxs(Vs,{children:[e.jsx($s,{children:"Save as a reusable template"}),e.jsx(Cr,{children:"Saves your branding, co-listing agent, theme, page wording, custom pages, and marketing plan. The property address and photo are not saved — you add those each time."})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Template name"}),e.jsx(be,{value:i,onChange:d=>l(d.target.value),autoFocus:!0})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Notes (optional)"}),e.jsx(Ls,{rows:2,value:o,onChange:d=>c(d.target.value),placeholder:"Luxury version with co-listing agent and testimonials"})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs($,{disabled:!i.trim()||r,onClick:async()=>{await a(i.trim(),o.trim()),t(!1)},className:"gap-2",children:[r&&e.jsx(Jt,{className:"h-4 w-4 animate-spin"})," Save template"]})]})]})})}const O1t=["welcome","agent","overview","closing"],xPn=()=>{const{id:s}=oo(),t=Jn(),{user:n}=ks(),{data:r}=cBt(),{data:a,isLoading:i,refetch:l}=_3n(s),{update:o}=lBt(),{save:c}=oBt(),[d,u]=k.useState(null),[h,m]=k.useState(null),[p,g]=k.useState(x$e(null)),[x,y]=k.useState(uBt),[v,_]=k.useState([]),[j,C]=k.useState(p$e),[A,M]=k.useState(g$e),[I,P]=k.useState(null),[R,O]=k.useState(null),[B,U]=k.useState(!1),[G,H]=k.useState(!1),[Y,se]=k.useState(null),[ee,oe]=k.useState(!1),[me,Q]=k.useState(!1),[te,le]=k.useState(!1),[fe,_e]=k.useState(!1),[ve,he]=k.useState(!0),[Se,Te]=k.useState(!1),Ie=k.useRef(null);k.useEffect(()=>{if(!a||d)return;u({title:a.title||"",addressLine1:a.property_address_line1||"",city:a.city||"",state:a.state||"",postalCode:a.postal_code||"",listPrice:a.list_price!=null?String(a.list_price):"",beds:a.beds!=null?String(a.beds):"",baths:a.baths!=null?String(a.baths):"",sqft:a.sqft!=null?String(a.sqft):""});const tt=a.agent_snapshot;m({...r,...tt||{}}),g(x$e(a.services)),y(hBt(a.co_agent)),_(fBt(a.custom_pages)),C(a.page_settings&&Object.keys(a.page_settings).length?a.page_settings:p$e),M(a.photo_focal||g$e),P(a.property_photo_path)},[a,r,d]),k.useEffect(()=>{let tt=!1;return I?V4e(I).then(ut=>{tt||O(ut)}):O(null),()=>{tt=!0}},[I]);const Ue=k.useMemo(()=>!a||!d?null:{...a,title:d.title,property_address_line1:d.addressLine1,city:d.city,state:d.state,postal_code:d.postalCode,list_price:d.listPrice?Number(d.listPrice):null,beds:d.beds?Number(d.beds):null,baths:d.baths?Number(d.baths):null,sqft:d.sqft?Number(d.sqft):null,agent_snapshot:h||{},co_agent:x,custom_pages:v,services:p,page_settings:j,photo_focal:A,property_photo_path:I},[a,d,h,x,v,p,j,A,I]),Be=tt=>u(ut=>ut&&{...ut,...tt}),je=tt=>m(ut=>ut&&{...ut,...tt}),Ye=tt=>(j.hidden||[]).includes(tt),Ee=(tt,ut)=>C(nt=>{const et=new Set(nt.hidden||[]);return ut?et.delete(tt):et.add(tt),{...nt,hidden:Array.from(et)}}),Re=p.filter(tt=>tt.enabled),ke=1+O1t.filter(tt=>!Ye(tt)&&tt!=="overview").length+(Ye("overview")?0:1)+Re.filter(tt=>tt.key!=="communication").length+v.filter(tt=>tt.enabled).length,Fe=async(tt=!1)=>{if(Ue){_e(!0);try{await o.mutateAsync({id:Ue.id,title:Ue.title||"Untitled Presentation",property_address_line1:Ue.property_address_line1,city:Ue.city,state:Ue.state,postal_code:Ue.postal_code,list_price:Ue.list_price,beds:Ue.beds,baths:Ue.baths,sqft:Ue.sqft,agent_snapshot:Ue.agent_snapshot,co_agent:Ue.co_agent,custom_pages:Ue.custom_pages,services:Ue.services,page_settings:Ue.page_settings,photo_focal:Ue.photo_focal,property_photo_path:Ue.property_photo_path}),tt||ae.success("Presentation saved")}finally{_e(!1)}}},Oe=async tt=>{if(!(!n||!s)){if(!tt.type.startsWith("image/")){ae.error("Please choose a JPG or PNG photo");return}if(tt.size>25*1024*1024){ae.error("That photo is larger than 25 MB");return}U(!0);try{const ut=await sMn(n.id,s,tt);P(ut);const nt=await V4e(ut);O(nt?`${nt}${nt.includes("?")?"&":"?"}v=${Date.now()}`:null),await o.mutateAsync({id:s,property_photo_path:ut}),ae.success("Photo uploaded")}catch(ut){ae.error((ut==null?void 0:ut.message)||"Upload failed")}finally{U(!1)}}},Ge=async()=>{if(Ue){oe(!0);try{const tt=await m$t(H4e(Ue,r,R),Ue.template_id,I);se(tt)}catch(tt){ae.error((tt==null?void 0:tt.message)||"Could not build the preview")}finally{oe(!1)}}};k.useEffect(()=>{if(!ve||!Ue)return;const tt=setTimeout(()=>{Ge()},900);return()=>clearTimeout(tt)},[ve,Ue]);const yt=async()=>{if(!(!Ue||!n)){if(!Ue.property_photo_path){ae.error("Add the primary exterior photo before generating the PDF");return}Q(!0);try{await Fe(!0);const tt=await f$t(H4e(Ue,r,R),Ue.template_id,"print",I);await p$t(n.id,Ue.id,tt),await l(),ae.success("Presentation downloaded")}catch(tt){ae.error((tt==null?void 0:tt.message)||"Could not build the PDF")}finally{Q(!1)}}};return i||!d||!a?e.jsx(Xs,{children:e.jsxs("div",{className:"space-y-4",children:[e.jsx(fn,{className:"h-10 w-64"}),e.jsx(fn,{className:"h-[60vh] w-full rounded-xl"})]})}):e.jsxs(Xs,{children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx($,{variant:"ghost",size:"icon",onClick:()=>t("/apps/listing-presentation-studio"),children:e.jsx(Ia,{className:"h-4 w-4"})}),e.jsxs("div",{children:[e.jsx(be,{value:d.title,onChange:tt=>Be({title:tt.target.value}),className:"h-9 border-none bg-transparent px-0 text-xl font-semibold shadow-none focus-visible:ring-0",placeholder:"Untitled Presentation"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[Re.length," services selected · ",ke," pages"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs($,{variant:"outline",onClick:()=>Fe(),disabled:fe,className:"gap-2",children:[fe?e.jsx(Jt,{className:"h-4 w-4 animate-spin"}):e.jsx(Ml,{className:"h-4 w-4"})," Save"]}),e.jsxs($,{variant:"outline",onClick:()=>Te(!0),className:"gap-2",children:[e.jsx(BT,{className:"h-4 w-4"})," Save as template"]}),e.jsxs($,{variant:"outline",onClick:Ge,disabled:ee,className:"gap-2",children:[ee?e.jsx(Jt,{className:"h-4 w-4 animate-spin"}):e.jsx(ba,{className:"h-4 w-4"})," Preview"]}),e.jsxs($,{variant:"outline",onClick:async()=>{await Fe(!0),le(!0)},className:"gap-2",children:[e.jsx(pn,{className:"h-4 w-4"})," Email"]}),e.jsxs($,{onClick:yt,disabled:me,className:"gap-2",children:[me?e.jsx(Jt,{className:"h-4 w-4 animate-spin"}):e.jsx(ji,{className:"h-4 w-4"}),"Generate PDF"]})]})]}),e.jsxs("div",{className:"grid gap-6 lg:grid-cols-[minmax(0,440px)_minmax(0,1fr)]",children:[e.jsxs(ya,{defaultValue:"property",className:"space-y-4",children:[e.jsxs(va,{className:"grid w-full grid-cols-4",children:[e.jsx(is,{value:"property",children:"Property"}),e.jsx(is,{value:"branding",children:"Branding"}),e.jsx(is,{value:"plan",children:"Plan"}),e.jsx(is,{value:"pages",children:"Pages"})]}),e.jsxs(cs,{value:"property",className:"space-y-4",children:[e.jsxs(we,{children:[e.jsx(Vt,{className:"pb-3",children:e.jsx(Yt,{className:"text-base",children:"Property address"})}),e.jsxs(De,{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Street address"}),e.jsx(be,{value:d.addressLine1,onChange:tt=>Be({addressLine1:tt.target.value}),placeholder:"1408 Elmwood Drive"})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:"col-span-2 space-y-1.5",children:[e.jsx(re,{children:"City"}),e.jsx(be,{value:d.city,onChange:tt=>Be({city:tt.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"State"}),e.jsx(be,{value:d.state,onChange:tt=>Be({state:tt.target.value})})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"ZIP"}),e.jsx(be,{value:d.postalCode,onChange:tt=>Be({postalCode:tt.target.value})})]}),e.jsx(Pc,{}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"List price (optional)"}),e.jsx(be,{inputMode:"numeric",value:d.listPrice,onChange:tt=>Be({listPrice:tt.target.value.replace(/[^0-9.]/g,"")}),placeholder:"649000"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Square feet"}),e.jsx(be,{inputMode:"numeric",value:d.sqft,onChange:tt=>Be({sqft:tt.target.value.replace(/[^0-9]/g,"")})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Beds"}),e.jsx(be,{inputMode:"numeric",value:d.beds,onChange:tt=>Be({beds:tt.target.value.replace(/[^0-9.]/g,"")})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Baths"}),e.jsx(be,{inputMode:"numeric",value:d.baths,onChange:tt=>Be({baths:tt.target.value.replace(/[^0-9.]/g,"")})})]})]})]})]}),e.jsxs(we,{children:[e.jsx(Vt,{className:"pb-3",children:e.jsxs(Yt,{className:"text-base",children:["Primary exterior photo ",e.jsx("span",{className:"text-destructive",children:"*"})]})}),e.jsxs(De,{className:"space-y-3",children:[e.jsx("div",{role:"button",tabIndex:0,onClick:()=>{var tt;return(tt=Ie.current)==null?void 0:tt.click()},onKeyDown:tt=>{var ut;return tt.key==="Enter"&&((ut=Ie.current)==null?void 0:ut.click())},onDragOver:tt=>{tt.preventDefault(),H(!0)},onDragLeave:()=>H(!1),onDrop:tt=>{var nt;tt.preventDefault(),H(!1);const ut=(nt=tt.dataTransfer.files)==null?void 0:nt[0];ut&&Oe(ut)},className:Ot("relative flex h-48 w-full cursor-pointer items-center justify-center overflow-hidden rounded-lg border border-dashed bg-muted/40 transition-colors hover:bg-muted",G&&"border-primary bg-primary/10"),children:R?e.jsx("img",{src:R,alt:"Property exterior",className:"h-full w-full object-cover",style:{objectPosition:`${A.x*100}% ${A.y*100}%`}}):e.jsxs("div",{className:"flex flex-col items-center gap-2 text-muted-foreground",children:[B?e.jsx(Jt,{className:"h-6 w-6 animate-spin"}):e.jsx(gb,{className:"h-6 w-6"}),e.jsx("span",{className:"text-sm",children:"Drag & drop the front exterior photo"}),e.jsx("span",{className:"text-xs",children:"or click to browse · JPG or PNG · landscape works best"})]})}),e.jsx("input",{ref:Ie,type:"file",accept:"image/*",className:"hidden",onChange:tt=>{var nt;const ut=(nt=tt.target.files)==null?void 0:nt[0];ut&&Oe(ut),tt.target.value=""}}),R&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-3 rounded-lg border bg-muted/30 p-3",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs font-medium text-muted-foreground",children:[e.jsx(BK,{className:"h-3.5 w-3.5"})," Reposition crop"]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{className:"text-xs",children:"Horizontal"}),e.jsx(sx,{value:[A.x*100],min:0,max:100,step:1,onValueChange:([tt])=>M(ut=>({...ut,x:tt/100}))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{className:"text-xs",children:"Vertical"}),e.jsx(sx,{value:[A.y*100],min:0,max:100,step:1,onValueChange:([tt])=>M(ut=>({...ut,y:tt/100}))})]})]}),e.jsxs($,{variant:"outline",size:"sm",className:"w-full gap-2",onClick:()=>{var tt;return(tt=Ie.current)==null?void 0:tt.click()},disabled:B,children:[e.jsx(yo,{className:"h-4 w-4"})," Replace photo"]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"This photo anchors the cover and appears on a few key pages — photography, video, the property website, and the closing page."})]})]})]}),e.jsxs(cs,{value:"branding",className:"space-y-4",children:[e.jsx(uPn,{value:j.theme||yTn,onChange:tt=>C(ut=>({...ut,theme:tt}))}),e.jsxs(we,{children:[e.jsx(Vt,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(Yt,{className:"text-base",children:"Your details"}),e.jsx(qe,{variant:"secondary",className:"text-[10px]",children:"Loaded from your LevelUp profile"})]})}),e.jsx(De,{className:"space-y-3",children:h&&e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Edits here apply to this presentation only — your LevelUp profile stays unchanged."}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Name"}),e.jsx(be,{value:h.name,onChange:tt=>je({name:tt.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Tagline"}),e.jsx(be,{value:h.tagline||"",onChange:tt=>je({tagline:tt.target.value}),placeholder:"Helping families move with confidence"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Phone"}),e.jsx(be,{value:h.phone||"",onChange:tt=>je({phone:tt.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Email"}),e.jsx(be,{value:h.email||"",onChange:tt=>je({email:tt.target.value})})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Website"}),e.jsx(be,{value:h.website||"",onChange:tt=>je({website:tt.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Brokerage"}),e.jsx(be,{value:h.brokerageName||"",onChange:tt=>je({brokerageName:tt.target.value})})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"License #"}),e.jsx(be,{value:h.licenseNumber||"",onChange:tt=>je({licenseNumber:tt.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"License state"}),e.jsx(be,{value:h.licenseState||"",onChange:tt=>je({licenseState:tt.target.value})})]})]}),e.jsx(Pc,{}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Primary color"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"color",value:h.brandColor,onChange:tt=>je({brandColor:tt.target.value}),className:"h-9 w-12 cursor-pointer rounded border bg-transparent"}),e.jsx(be,{value:h.brandColor,onChange:tt=>je({brandColor:tt.target.value})})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Accent color"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"color",value:h.accentColor,onChange:tt=>je({accentColor:tt.target.value}),className:"h-9 w-12 cursor-pointer rounded border bg-transparent"}),e.jsx(be,{value:h.accentColor,onChange:tt=>je({accentColor:tt.target.value})})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Headshot URL"}),e.jsx(be,{value:h.headshotUrl||"",onChange:tt=>je({headshotUrl:tt.target.value}),placeholder:"Pulled from your profile photo"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Brokerage logo URL"}),e.jsx(be,{value:h.brokerageLogoUrl||"",onChange:tt=>je({brokerageLogoUrl:tt.target.value})})]}),r&&e.jsxs($,{variant:"outline",size:"sm",className:"w-full gap-2",onClick:()=>m({...r}),children:[e.jsx(yo,{className:"h-4 w-4"})," Reset to my LevelUp profile"]})]})})]}),e.jsx(dPn,{value:x,onChange:tt=>y(ut=>({...ut,...tt}))})]}),e.jsx(cs,{value:"plan",className:"space-y-4",children:e.jsxs(we,{children:[e.jsxs(Vt,{className:"pb-3",children:[e.jsx(Yt,{className:"text-base",children:"Marketing plan"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Only the services you turn on appear in the PDF. Uncheck any line item you do not offer."})]}),e.jsx(De,{children:e.jsx(SF,{type:"multiple",className:"w-full",children:p.slice().sort((tt,ut)=>tt.order-ut.order).map(tt=>{var ut;return e.jsxs(r6,{value:tt.key,children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(On,{checked:tt.enabled,onCheckedChange:nt=>g(et=>et.map(at=>at.key===tt.key?{...at,enabled:nt}:at))}),e.jsx(a6,{className:"flex-1 text-left text-sm",children:tt.title})]}),e.jsxs(i6,{className:"space-y-3 pt-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Headline"}),e.jsx(be,{value:tt.title,onChange:nt=>g(et=>et.map(at=>at.key===tt.key?{...at,title:nt.target.value}:at))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Description"}),e.jsx(Ls,{rows:4,value:tt.body,onChange:nt=>g(et=>et.map(at=>at.key===tt.key?{...at,body:nt.target.value}:at))})]}),!!((ut=tt.options)!=null&&ut.length)&&e.jsxs("div",{className:"space-y-2 rounded-lg border bg-muted/30 p-3",children:[e.jsx(re,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Included in this page"}),tt.options.map(nt=>e.jsxs("label",{className:"flex items-start gap-2 text-sm",children:[e.jsx(Li,{className:"mt-0.5",checked:nt.enabled,onCheckedChange:et=>g(at=>at.map(wt=>{var rt;return wt.key===tt.key?{...wt,options:(rt=wt.options)==null?void 0:rt.map(Ft=>Ft.key===nt.key?{...Ft,enabled:!!et}:Ft)}:wt}))}),e.jsx("span",{className:"leading-snug",children:nt.label})]},nt.key))]})]})]},tt.key)})})})]})}),e.jsxs(cs,{value:"pages",className:"space-y-4",children:[e.jsxs(we,{children:[e.jsxs(Vt,{className:"pb-3",children:[e.jsx(Yt,{className:"text-base",children:"Page visibility"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"The cover and every enabled service page always print. These supporting pages are optional."})]}),e.jsxs(De,{className:"space-y-3",children:[O1t.map(tt=>e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsx("span",{className:"text-sm",children:C3n[tt]}),e.jsx(On,{checked:!Ye(tt),onCheckedChange:ut=>Ee(tt,ut)})]},tt)),e.jsxs("div",{className:"rounded-lg border bg-muted/30 p-3 text-sm",children:[e.jsx("div",{className:"font-medium",children:"Page order"}),e.jsxs("ol",{className:"mt-2 space-y-1 text-xs text-muted-foreground",children:[e.jsx("li",{children:"01 · Cover"}),!Ye("welcome")&&e.jsx("li",{children:"Marketing commitment"}),!Ye("agent")&&e.jsx("li",{children:"About your agent"}),v.filter(tt=>tt.enabled&&tt.placement!=="end").sort((tt,ut)=>tt.order-ut.order).map(tt=>e.jsx("li",{children:tt.headline||"Custom page"},tt.id)),!Ye("overview")&&e.jsx("li",{children:"Marketing plan overview"}),Re.filter(tt=>tt.key!=="communication").map(tt=>e.jsx("li",{children:tt.title},tt.key)),v.filter(tt=>tt.enabled&&tt.placement==="end").sort((tt,ut)=>tt.order-ut.order).map(tt=>e.jsx("li",{children:tt.headline||"Custom page"},tt.id)),!Ye("closing")&&e.jsx("li",{children:"Communication & closing commitment"})]})]})]})]}),e.jsx(fPn,{pages:j,onChange:C}),e.jsxs(we,{children:[e.jsxs(Vt,{className:"pb-3",children:[e.jsx(Yt,{className:"text-base",children:"What they're saying"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Add a testimonial page and drop in up to six client quotes. It styles itself to your theme."})]}),e.jsx(De,{children:e.jsx($,{variant:"outline",size:"sm",className:"w-full",onClick:()=>_(tt=>[...tt,{...FXe("testimonials",tt.length),placement:"end"}]),children:`Add a "What they're saying" page`})})]}),e.jsx(pPn,{pages:v,onChange:_})]})]}),e.jsxs(we,{className:"min-h-[70vh] overflow-hidden",children:[e.jsxs(Vt,{className:"flex flex-row items-center justify-between space-y-0 pb-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Yt,{className:"text-base",children:"Live preview"}),e.jsxs("label",{className:"flex items-center gap-1.5 text-xs text-muted-foreground",children:[e.jsx(On,{checked:ve,onCheckedChange:he}),"Auto-update"]})]}),e.jsxs($,{variant:"ghost",size:"sm",onClick:Ge,disabled:ee,className:"gap-2",children:[ee?e.jsx(Jt,{className:"h-4 w-4 animate-spin"}):e.jsx(yo,{className:"h-4 w-4"}),"Refresh"]})]}),e.jsx(De,{className:"h-[calc(70vh-60px)] p-0",children:Y?e.jsx(cPn,{blob:Y}):e.jsxs("div",{className:"flex h-full flex-col items-center justify-center gap-3 bg-muted/30 text-center",children:[e.jsx(ba,{className:"h-8 w-8 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Fill in the address, upload the photo, then generate the preview."}),e.jsxs($,{onClick:Ge,disabled:ee,className:"gap-2",children:[ee?e.jsx(Jt,{className:"h-4 w-4 animate-spin"}):e.jsx(ba,{className:"h-4 w-4"}),"Generate preview"]})]})})]})]})]}),e.jsx(gPn,{open:Se,onOpenChange:Te,defaultName:d.title,saving:c.isPending,onSave:async(tt,ut)=>{await c.mutateAsync({name:tt,description:ut||null,template_id:a.template_id,agent_snapshot:h||{},co_agent:x,custom_pages:v,services:p,page_settings:j})}}),e.jsx(x$t,{open:te,onOpenChange:le,row:Ue,brand:r,photoUrl:R})]})};function yPn(s,t,n,r){const a=d=>d*Math.PI/180,l=a(n-s),o=a(r-t),c=Math.sin(l/2)**2+Math.cos(a(s))*Math.cos(a(n))*Math.sin(o/2)**2;return 2*3958.8*Math.asin(Math.sqrt(c))}const wqt="popby_geocode_cache_v1";function vPn(){try{return JSON.parse(localStorage.getItem(wqt)||"{}")}catch{return{}}}function bPn(s){try{localStorage.setItem(wqt,JSON.stringify(s))}catch{}}function _Pn({contacts:s,onLogPopby:t}){const[n,r]=k.useState(null),[a,i]=k.useState("idle"),[l,o]=k.useState(5),[c,d]=k.useState(""),[u,h]=k.useState(new Map),[m,p]=k.useState(!1);k.useEffect(()=>{(async()=>{const{data:_}=await V.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle();_!=null&&_.value&&d(_.value)})()},[]);const g=k.useMemo(()=>s.filter(_=>_.isDue&&(_.address||_.city&&_.state||_.zip)),[s]),x=()=>{if(!("geolocation"in navigator)){i("unavailable");return}i("loading"),navigator.geolocation.getCurrentPosition(_=>{r({lat:_.coords.latitude,lng:_.coords.longitude}),i("ok")},()=>{i("denied")},{enableHighAccuracy:!0,timeout:1e4,maximumAge:6e4})};k.useEffect(()=>{if(!c||!n||g.length===0)return;let _=!1;const j=vPn(),C=new Map;g.forEach(M=>{const I=[M.address,M.city,M.state,M.zip].filter(Boolean).join("|").toLowerCase();j[I]&&C.set(M.id,j[I])}),h(new Map(C));const A=g.filter(M=>!([M.address,M.city,M.state,M.zip].filter(Boolean).join("|").toLowerCase()in j));if(A.length!==0)return p(!0),(async()=>{const M=[...A],I=async()=>{var P,R;for(;M.length&&!_;){const O=M.shift(),B=[O.address,O.city,O.state,O.zip].filter(Boolean),U=B.join("|").toLowerCase(),G=B.join(", ");try{const Y=await(await fetch(`https://api.mapbox.com/geocoding/v5/mapbox.places/${encodeURIComponent(G)}.json?limit=1&access_token=${c}`)).json();if((R=(P=Y==null?void 0:Y.features)==null?void 0:P[0])!=null&&R.center){const[se,ee]=Y.features[0].center;j[U]={lat:ee,lng:se},C.set(O.id,{lat:ee,lng:se})}else j[U]=null}catch{}}};await Promise.all([I(),I(),I(),I()]),_||(bPn(j),h(new Map(C)),p(!1))})(),()=>{_=!0}},[c,n,g]);const y=k.useMemo(()=>{if(!n)return[];const _=[];return g.forEach(j=>{const C=u.get(j.id);if(!C)return;const A=yPn(n.lat,n.lng,C.lat,C.lng);A<=l&&_.push({...j,distanceMiles:A,lat:C.lat,lng:C.lng})}),_.sort((j,C)=>j.distanceMiles-C.distanceMiles)},[n,g,u,l]),v=_=>{const C=/iPad|iPhone|iPod/.test(navigator.userAgent)?`https://maps.apple.com/?daddr=${_.lat},${_.lng}`:`https://www.google.com/maps/dir/?api=1&destination=${_.lat},${_.lng}`;window.open(C,"_blank","noopener")};return e.jsxs(we,{className:"border-primary/30 bg-gradient-to-br from-primary/5 to-transparent",children:[e.jsx(Vt,{className:"pb-3",children:e.jsxs("div",{className:"flex items-start justify-between gap-3 flex-wrap",children:[e.jsxs("div",{children:[e.jsxs(Yt,{className:"flex items-center gap-2 text-lg",children:[e.jsx(Yz,{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(bs,{value:String(l),onValueChange:_=>o(Number(_)),children:[e.jsx(ys,{className:"w-[110px] h-9",children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"2",children:"2 miles"}),e.jsx(We,{value:"5",children:"5 miles"}),e.jsx(We,{value:"10",children:"10 miles"}),e.jsx(We,{value:"25",children:"25 miles"})]})]}),e.jsxs($,{size:"sm",variant:a==="ok"?"outline":"default",onClick:x,disabled:a==="loading",children:[a==="loading"?e.jsx(yo,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Yz,{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(Si,{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(Ho,{className:"h-6 w-6"}),"Location access was blocked. Enable it in your browser to use Nearby Now."]}),a==="unavailable"&&e.jsx("div",{className:"text-center py-6 text-sm text-muted-foreground",children:"Geolocation isn't available on this device."}),a==="ok"&&!c&&e.jsx("div",{className:"text-center py-6 text-sm text-muted-foreground",children:"Mapping isn't configured yet — ask an admin to add the Mapbox token."}),a==="ok"&&c&&g.length===0&&e.jsx("div",{className:"text-center py-6 text-sm text-muted-foreground",children:"No due contacts have addresses yet. Add street addresses to your sphere to power this."}),a==="ok"&&c&&g.length>0&&m&&y.length===0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(fn,{className:"h-14 w-full"}),e.jsx(fn,{className:"h-14 w-full"}),e.jsx("p",{className:"text-xs text-muted-foreground text-center",children:"Locating contacts…"})]}),a==="ok"&&c&&!m&&y.length===0&&g.length>0&&e.jsxs("div",{className:"text-center py-6 text-sm text-muted-foreground",children:["No due contacts within ",l," miles. Try widening the radius."]}),y.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(qe,{variant:"secondary",className:"font-medium",children:[y.length," nearby"]}),m&&e.jsxs("span",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(yo,{className:"h-3 w-3 animate-spin"})," still locating…"]})]}),e.jsx("div",{className:"space-y-2",children:y.map(_=>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:[_.first_name," ",_.last_name]}),e.jsx(qe,{variant:"outline",className:"text-xs",children:_.distanceMiles<1?`${(_.distanceMiles*5280).toFixed(0)} ft`:`${_.distanceMiles.toFixed(1)} mi`}),_.daysOverdue>0&&e.jsxs(qe,{variant:"destructive",className:"text-xs",children:[_.daysOverdue,"d overdue"]})]}),e.jsx("p",{className:"text-xs text-muted-foreground truncate mt-0.5",children:[_.address,_.city,_.state].filter(Boolean).join(", ")})]}),e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[_.phone&&e.jsx($,{size:"icon",variant:"ghost",asChild:!0,className:"h-9 w-9",title:"Call",children:e.jsx("a",{href:`tel:${_.phone}`,children:e.jsx(ka,{className:"h-4 w-4"})})}),e.jsx($,{size:"icon",variant:"ghost",onClick:()=>v(_),className:"h-9 w-9",title:"Directions",children:e.jsx($K,{className:"h-4 w-4"})}),e.jsxs($,{size:"sm",onClick:()=>t(_),children:[e.jsx(Zo,{className:"h-4 w-4 mr-1"}),"Log"]})]})]},_.id))})]})]})]})}const wPn="0dde5abb-0005-4c8c-a471-30d0cbc9e280",jPn=[{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 NPn(){const s=Jn(),t=R7t(),{data:n}=sSn(),{data:r}=vj(),{data:a}=zZe(),{data:i}=aTe(90),{data:l}=vv(),o=oSn(),c=aSn(),d=rSn(),u=iSn(),{data:h=[],isLoading:m}=pt({queryKey:["popby-templates"],queryFn:async()=>{const{data:Y,error:se}=await V.from("canva_templates").select(` *, category:template_categories(id, name), type:template_types(id, name) `).eq("category_id",wPn).order("publish_date",{ascending:!1});if(se)throw se;const{data:ee}=await V.from("template_likes").select("template_id"),{data:oe}=await V.from("template_comments").select("template_id"),me=new Map;ee==null||ee.forEach(te=>{me.set(te.template_id,(me.get(te.template_id)||0)+1)});const Q=new Map;return oe==null||oe.forEach(te=>{Q.set(te.template_id,(Q.get(te.template_id)||0)+1)}),(Y||[]).map(te=>({...te,likesCount:me.get(te.id)||0,commentsCount:Q.get(te.id)||0}))}}),p=Y=>{const se=l==null?void 0:l.find(ee=>ee.id===Y);return se?`${se.first_name} ${se.last_name||""}`.trim():"Unknown"},g=Y=>{if(!Y)return null;const se=n==null?void 0:n.find(ee=>ee.id===Y);return(se==null?void 0:se.name)||null},[x,y]=k.useState(null),[v,_]=k.useState(!1),[j,C]=k.useState(!1),[A,M]=k.useState(!1),[I,P]=k.useState({popby_item_id:"",notes:""}),[R,O]=k.useState({name:"",description:""}),B=async()=>{x&&(await c.mutateAsync({contact_id:x.id,popby_item_id:I.popby_item_id||void 0,notes:I.notes||void 0}),_(!1),y(null),P({popby_item_id:"",notes:""}))},U=async()=>{R.name.trim()&&(await d.mutateAsync({name:R.name.trim(),description:R.description.trim()||void 0}),M(!1),O({name:"",description:""}))},G=async(Y,se)=>{await u.mutateAsync({relationship_type_id:Y,frequency_days:parseInt(se)})},H=Y=>{var ee;const se=a==null?void 0:a.find(oe=>oe.relationship_type_id===Y);return((ee=se==null?void 0:se.frequency_days)==null?void 0:ee.toString())||"90"};return e.jsx(Xs,{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(we,{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(we,{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(we,{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($,{onClick:()=>s("/mission-control/popbys/map"),children:[e.jsx(Si,{className:"h-4 w-4 mr-2"}),"View Map"]}),e.jsxs($,{variant:"outline",onClick:()=>C(!0),children:[e.jsx(Yc,{className:"h-4 w-4 mr-2"}),"Frequency Settings"]}),e.jsxs($,{variant:"outline",onClick:()=>M(!0),children:[e.jsx(nn,{className:"h-4 w-4 mr-2"}),"Add Popby Idea"]})]}),e.jsxs(ya,{defaultValue:"due",children:[e.jsxs(va,{children:[e.jsx(is,{value:"due",children:"Due for Popby"}),e.jsx(is,{value:"activity",children:"Recent Activity"}),e.jsx(is,{value:"library",children:"Popby Library"}),e.jsx(is,{value:"templates",children:"Popby Templates"})]}),e.jsxs(cs,{value:"due",className:"space-y-4 mt-4",children:[e.jsx(_Pn,{contacts:t||[],onLogPopby:Y=>{y(Y),_(!0)}}),!t||t.length===0?e.jsx(we,{children:e.jsxs(De,{className:"p-8 text-center text-muted-foreground",children:[e.jsx(Zo,{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(Y=>e.jsx(we,{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:[Y.first_name," ",Y.last_name]}),Y.daysOverdue>0&&e.jsxs(qe,{variant:"destructive",className:"text-xs",children:[Y.daysOverdue,"+ days overdue"]}),Y.daysSinceLastPopby===null&&e.jsx(qe,{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:[Y.address&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Si,{className:"h-3 w-3"}),Y.city||Y.address]}),Y.tags&&Y.tags.length>0&&e.jsx("span",{children:Y.tags.map(se=>{var ee;return(ee=se.relationship_type)==null?void 0:ee.name}).join(", ")})]}),Y.lastPopby&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["Last popby: ",Ys(new Date(Y.lastPopby),"MMM d, yyyy")]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[Y.phone&&e.jsx($,{size:"sm",variant:"ghost",asChild:!0,children:e.jsx("a",{href:`tel:${Y.phone}`,children:e.jsx(ka,{className:"h-4 w-4"})})}),e.jsxs($,{size:"sm",onClick:()=>{y(Y),_(!0)},children:[e.jsx(nl,{className:"h-4 w-4 mr-1"}),"Log Popby"]})]})]})})},Y.id))})]}),e.jsx(cs,{value:"activity",className:"space-y-4 mt-4",children:!i||i.length===0?e.jsx(we,{children:e.jsxs(De,{className:"p-8 text-center text-muted-foreground",children:[e.jsx(sa,{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(we,{children:[e.jsx(Vt,{children:e.jsx(Yt,{className:"text-lg",children:"Recent Popby Log"})}),e.jsx(De,{className:"space-y-3",children:i.map(Y=>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(Zo,{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:p(Y.contact_id)}),g(Y.popby_item_id)&&e.jsx(qe,{variant:"secondary",className:"text-xs",children:g(Y.popby_item_id)})]}),e.jsx("div",{className:"text-sm text-muted-foreground",children:Ys(new Date(Y.completed_at),"MMM d, yyyy h:mm a")}),Y.notes&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1 line-clamp-2",children:Y.notes})]})]},Y.id))})]})}),e.jsx(cs,{value:"library",className:"space-y-4 mt-4",children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:[n==null?void 0:n.map(Y=>e.jsx(we,{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(Zo,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h3",{className:"font-medium",children:Y.name}),Y.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:Y.description}),!Y.owner_user_id&&e.jsx(qe,{variant:"secondary",className:"mt-2 text-xs",children:"Shared"})]})]})})},Y.id)),e.jsx(we,{className:"border-dashed cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>M(!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(nn,{className:"h-8 w-8 mx-auto mb-2"}),e.jsx("p",{children:"Add New Popby Idea"})]})})})]})}),e.jsxs(cs,{value:"templates",className:"space-y-4 mt-4",children:[e.jsxs("div",{className:"text-sm text-muted-foreground",children:[h.length," template",h.length!==1?"s":""," found"]}),m&&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((Y,se)=>e.jsx(we,{children:e.jsxs(De,{className:"p-4",children:[e.jsx(fn,{className:"aspect-[3/2] w-full rounded-lg mb-4"}),e.jsx(fn,{className:"h-5 w-3/4 mb-2"}),e.jsx(fn,{className:"h-4 w-full mb-4"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(fn,{className:"h-5 w-16"}),e.jsx(fn,{className:"h-5 w-20"})]})]})},se))}),!m&&h.length===0&&e.jsx(we,{children:e.jsxs(De,{className:"p-8 text-center text-muted-foreground",children:[e.jsx(bh,{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."})]})}),!m&&h.length>0&&e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6",children:h.map(Y=>e.jsxs(we,{className:"group overflow-hidden hover:shadow-lg transition-all duration-200 cursor-pointer",onClick:()=>s(`/templates/${Y.id}`),children:[e.jsx("div",{className:"relative overflow-hidden bg-muted aspect-[3/2]",children:Y.preview_image_url?e.jsx("img",{src:Y.preview_image_url,alt:Y.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:Y.name}),Y.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2 mb-3 flex-1",children:IZ(Y.description)}),e.jsx("div",{className:"flex flex-wrap gap-2 mb-3",children:e.jsx(qe,{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(Ay,{className:"h-3.5 w-3.5"}),Y.likesCount]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Vu,{className:"h-3.5 w-3.5"}),Y.commentsCount]})]}),e.jsxs($,{size:"sm",className:"w-full gap-2",onClick:se=>{se.stopPropagation(),s(`/templates/${Y.id}`)},children:[e.jsx(Ir,{className:"h-4 w-4"}),"View Template"]})]})]},Y.id))})]})]}),e.jsx(zs,{open:v,onOpenChange:_,children:e.jsxs(Rs,{children:[e.jsx(Vs,{children:e.jsxs($s,{children:["Log Popby for ",x==null?void 0:x.first_name," ",x==null?void 0:x.last_name]})}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Popby Item (optional)"}),e.jsxs(bs,{value:I.popby_item_id,onValueChange:Y=>P(se=>({...se,popby_item_id:Y})),children:[e.jsx(ys,{children:e.jsx(_s,{placeholder:"Select a popby item..."})}),e.jsx(vs,{children:n==null?void 0:n.map(Y=>e.jsx(We,{value:Y.id,children:Y.name},Y.id))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Notes (optional)"}),e.jsx(Ls,{placeholder:"Any notes about this popby...",value:I.notes,onChange:Y=>P(se=>({...se,notes:Y.target.value}))})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>_(!1),children:"Cancel"}),e.jsx($,{onClick:B,disabled:c.isPending,children:"Log Popby"})]})]})}),e.jsx(zs,{open:j,onOpenChange:C,children:e.jsxs(Rs,{className:"max-w-md",children:[e.jsx(Vs,{children:e.jsx($s,{children:"Popby Frequency Settings"})}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Set default popby frequency for each relationship type. You can override these per-contact."}),r==null?void 0:r.map(Y=>e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsx(re,{className:"font-medium",children:Y.name}),e.jsxs(bs,{value:H(Y.id),onValueChange:se=>G(Y.id,se),children:[e.jsx(ys,{className:"w-[180px]",children:e.jsx(_s,{})}),e.jsx(vs,{children:jPn.map(se=>e.jsx(We,{value:se.value,children:se.label},se.value))})]})]},Y.id))]}),e.jsx(kr,{children:e.jsx($,{onClick:()=>C(!1),children:"Done"})})]})}),e.jsx(zs,{open:A,onOpenChange:M,children:e.jsxs(Rs,{children:[e.jsx(Vs,{children:e.jsx($s,{children:"Add Popby Idea"})}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Name *"}),e.jsx(be,{placeholder:"e.g., Homemade cookies",value:R.name,onChange:Y=>O(se=>({...se,name:Y.target.value}))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Description"}),e.jsx(Ls,{placeholder:"Optional description...",value:R.description,onChange:Y=>O(se=>({...se,description:Y.target.value}))})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>M(!1),children:"Cancel"}),e.jsx($,{onClick:U,disabled:!R.name.trim()||d.isPending,children:"Add Item"})]})]})})]})})}const kPn=t4({property_address:uc().min(1,"Property address is required"),city:uc().optional(),state:uc().optional(),zip:uc().optional(),transaction_type:ZHe(["buyer","seller"]),close_date:uc().min(1,"Close date is required"),sale_price:xY().min(0,"Sale price must be positive"),commission_amount:xY().optional(),lead_source_id:uc().optional(),client_type_id:uc().optional(),contact_id:uc().optional(),notes:uc().optional(),is_win:Mys()});function jqt({open:s,onOpenChange:t,transaction:n}){const[r,a]=k.useState(!1),[i,l]=k.useState(""),[o,c]=k.useState(!1),[d,u]=k.useState(""),h=yAe(),m=VEs(),{data:p}=NF(),{data:g}=vj(),{data:x}=vv(),y=pAe(),v=bWe(),{data:_}=vAe(),j=(_==null?void 0:_.show_commission)??!0,C=D3e({resolver:O3e(kPn),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(()=>{n?C.reset({property_address:n.property_address,city:n.city||"",state:n.state||"",zip:n.zip||"",transaction_type:n.transaction_type,close_date:n.close_date,sale_price:Number(n.sale_price),commission_amount:n.commission_amount?Number(n.commission_amount):void 0,lead_source_id:n.lead_source_id||void 0,client_type_id:n.client_type_id||void 0,contact_id:n.contact_id||void 0,notes:n.notes||"",is_win:n.is_win}):C.reset({property_address:"",city:"",state:"",zip:"",transaction_type:"buyer",close_date:new Date().toISOString().split("T")[0],sale_price:0,commission_amount:void 0,lead_source_id:void 0,client_type_id:void 0,contact_id:void 0,notes:"",is_win:!1})},[n,C]);const A=async R=>{const O={property_address:R.property_address,transaction_type:R.transaction_type,close_date:R.close_date,sale_price:R.sale_price,is_win:R.is_win,commission_amount:R.commission_amount||null,lead_source_id:R.lead_source_id||null,client_type_id:R.client_type_id||null,contact_id:R.contact_id||null,city:R.city||null,state:R.state||null,zip:R.zip||null,notes:R.notes||null};n?await m.mutateAsync({id:n.id,...O}):await h.mutateAsync(O),t(!1)},M=async()=>{if(!i.trim())return;const[R,...O]=i.trim().split(" "),B=O.join(" ")||null,U=await y.mutateAsync({first_name:R,last_name:B,tagIds:[]});U&&(C.setValue("contact_id",U.id),l(""),c(!1),a(!1))},I=async()=>{if(!d.trim())return;const R=await v.mutateAsync(d.trim());R&&(C.setValue("lead_source_id",R.id),u(""))},P=x==null?void 0:x.find(R=>R.id===C.watch("contact_id"));return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"max-w-lg max-h-[90vh]",children:[e.jsx(Vs,{children:e.jsx($s,{children:n?"Edit Transaction":"Add Transaction"})}),e.jsx(Eo,{className:"max-h-[70vh] pr-4",children:e.jsx($3e,{...C,children:e.jsxs("form",{onSubmit:C.handleSubmit(A),className:"space-y-4",children:[e.jsx(Sp,{control:C.control,name:"property_address",render:({field:R})=>e.jsxs(Zf,{children:[e.jsx(Xf,{children:"Property Address *"}),e.jsx(Qf,{children:e.jsx(be,{placeholder:"123 Main St",...R})}),e.jsx(ib,{})]})}),e.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[e.jsx(Sp,{control:C.control,name:"city",render:({field:R})=>e.jsxs(Zf,{children:[e.jsx(Xf,{children:"City"}),e.jsx(Qf,{children:e.jsx(be,{placeholder:"City",...R})})]})}),e.jsx(Sp,{control:C.control,name:"state",render:({field:R})=>e.jsxs(Zf,{children:[e.jsx(Xf,{children:"State"}),e.jsx(Qf,{children:e.jsx(be,{placeholder:"TX",...R})})]})}),e.jsx(Sp,{control:C.control,name:"zip",render:({field:R})=>e.jsxs(Zf,{children:[e.jsx(Xf,{children:"Zip"}),e.jsx(Qf,{children:e.jsx(be,{placeholder:"75001",...R})})]})})]}),e.jsx(Sp,{control:C.control,name:"transaction_type",render:({field:R})=>e.jsxs(Zf,{children:[e.jsx(Xf,{children:"Transaction Type *"}),e.jsxs(bs,{onValueChange:R.onChange,value:R.value,children:[e.jsx(Qf,{children:e.jsx(ys,{children:e.jsx(_s,{placeholder:"Select type"})})}),e.jsxs(vs,{children:[e.jsx(We,{value:"buyer",children:"Buyer"}),e.jsx(We,{value:"seller",children:"Seller"})]})]}),e.jsx(ib,{})]})}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsx(Sp,{control:C.control,name:"close_date",render:({field:R})=>e.jsxs(Zf,{children:[e.jsx(Xf,{children:"Close Date *"}),e.jsx(Qf,{children:e.jsx(be,{type:"date",...R})}),e.jsx(ib,{})]})}),e.jsx(Sp,{control:C.control,name:"sale_price",render:({field:R})=>e.jsxs(Zf,{children:[e.jsx(Xf,{children:"Sale Price *"}),e.jsx(Qf,{children:e.jsx(be,{type:"number",placeholder:"0",...R,onChange:O=>R.onChange(Number(O.target.value))})}),e.jsx(ib,{})]})})]}),j&&e.jsx(Sp,{control:C.control,name:"commission_amount",render:({field:R})=>e.jsxs(Zf,{children:[e.jsx(Xf,{children:"Commission"}),e.jsx(Qf,{children:e.jsx(be,{type:"number",placeholder:"0",...R,value:R.value??"",onChange:O=>R.onChange(O.target.value?Number(O.target.value):void 0)})})]})}),e.jsx(Sp,{control:C.control,name:"lead_source_id",render:({field:R})=>e.jsxs(Zf,{children:[e.jsx(Xf,{children:"Lead Source"}),e.jsxs(bs,{onValueChange:R.onChange,value:R.value||"",children:[e.jsx(Qf,{children:e.jsx(ys,{children:e.jsx(_s,{placeholder:"Select source"})})}),e.jsx(vs,{children:p==null?void 0:p.map(O=>e.jsx(We,{value:O.id,children:O.name},O.id))})]})]})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(be,{placeholder:"Add custom source...",value:d,onChange:R=>u(R.target.value),className:"flex-1"}),e.jsx($,{type:"button",variant:"outline",size:"icon",onClick:I,disabled:!d.trim(),children:e.jsx(nn,{className:"h-4 w-4"})})]}),e.jsx(Sp,{control:C.control,name:"client_type_id",render:({field:R})=>e.jsxs(Zf,{children:[e.jsx(Xf,{children:"Client Type"}),e.jsxs(bs,{onValueChange:R.onChange,value:R.value||"",children:[e.jsx(Qf,{children:e.jsx(ys,{children:e.jsx(_s,{placeholder:"Select client type"})})}),e.jsx(vs,{children:g==null?void 0:g.map(O=>e.jsx(We,{value:O.id,children:O.name},O.id))})]})]})}),e.jsx(Sp,{control:C.control,name:"contact_id",render:({field:R})=>e.jsxs(Zf,{children:[e.jsx(Xf,{children:"Client Contact"}),e.jsxs(Xc,{open:r,onOpenChange:a,children:[e.jsx(Qc,{asChild:!0,children:e.jsx(Qf,{children:e.jsxs($,{variant:"outline",role:"combobox",className:Ot("w-full justify-between",!R.value&&"text-muted-foreground"),children:[P?`${P.first_name} ${P.last_name||""}`.trim():"Select contact",e.jsx(v_,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})})}),e.jsxs(Bc,{className:"w-full p-0",align:"start",children:[e.jsxs(M_,{children:[e.jsx(P_,{placeholder:"Search contacts..."}),e.jsxs(I_,{children:[e.jsx(L_,{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($,{variant:"outline",size:"sm",className:"w-full",onClick:()=>c(!0),children:[e.jsx(nn,{className:"h-4 w-4 mr-2"}),"Add New Contact"]})]})}),e.jsx(Nb,{children:x==null?void 0:x.map(O=>e.jsxs(rv,{value:`${O.first_name} ${O.last_name||""}`,onSelect:()=>{R.onChange(O.id),a(!1)},children:[e.jsx(ma,{className:Ot("mr-2 h-4 w-4",O.id===R.value?"opacity-100":"opacity-0")}),O.first_name," ",O.last_name||""]},O.id))})]})]}),o&&e.jsxs("div",{className:"p-2 border-t space-y-2",children:[e.jsx(be,{placeholder:"Enter contact name...",value:i,onChange:O=>l(O.target.value)}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{size:"sm",onClick:M,disabled:!i.trim()||y.isPending,children:"Add Contact"}),e.jsx($,{size:"sm",variant:"outline",onClick:()=>{c(!1),l("")},children:"Cancel"})]})]})]})]})]})}),e.jsx(Sp,{control:C.control,name:"notes",render:({field:R})=>e.jsxs(Zf,{children:[e.jsx(Xf,{children:"Notes"}),e.jsx(Qf,{children:e.jsx(Ls,{placeholder:"Any notes about this transaction...",...R})})]})}),e.jsx(Sp,{control:C.control,name:"is_win",render:({field:R})=>e.jsxs(Zf,{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(Xf,{children:"Mark as Win 🏆"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Highlight this as a notable success"})]}),e.jsx(Qf,{children:e.jsx(On,{checked:R.value,onCheckedChange:R.onChange})})]})}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx($,{type:"button",variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs($,{type:"submit",disabled:h.isPending||m.isPending,children:[n?"Update":"Add"," Transaction"]})]})]})})})]})})}function oQe({transactions:s,showCommission:t,isLoading:n,agentNameMap:r,readOnly:a}){const[i,l]=k.useState(null),[o,c]=k.useState(null),[d,u]=k.useState(""),[h,m]=k.useState("all"),[p,g]=k.useState("all"),[x,y]=k.useState("all"),[v,_]=k.useState(!1),j=HEs(),C=yAe(),{data:A}=NF(),{data:M}=vj(),I=AV(),P=B=>{const{id:U,created_at:G,updated_at:H,lead_source:Y,client_type:se,contact:ee,...oe}=B;C.mutate(oe)},R=()=>{o&&(j.mutate(o),c(null))},O=s.filter(B=>{var ee,oe,me,Q;const U=d===""||B.property_address.toLowerCase().includes(d.toLowerCase())||((oe=(ee=B.contact)==null?void 0:ee.first_name)==null?void 0:oe.toLowerCase().includes(d.toLowerCase()))||((Q=(me=B.contact)==null?void 0:me.last_name)==null?void 0:Q.toLowerCase().includes(d.toLowerCase())),G=h==="all"||B.transaction_type===h,H=p==="all"||B.lead_source_id===p,Y=x==="all"||B.client_type_id===x,se=!v||B.is_win;return U&&G&&H&&Y&&se});return n?e.jsx(we,{children:e.jsx(De,{className:"p-6 space-y-4",children:[1,2,3].map(B=>e.jsx(fn,{className:"h-16 w-full"},B))})}):e.jsxs(e.Fragment,{children:[e.jsxs(we,{children:[e.jsx(Vt,{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(Yt,{children:["Transactions (",O.length,")"]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Yr,{className:"absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search...",value:d,onChange:B=>u(B.target.value),className:"pl-8 w-[150px]"})]}),e.jsxs(bs,{value:h,onValueChange:m,children:[e.jsx(ys,{className:"w-[100px]",children:e.jsx(_s,{placeholder:"Type"})}),e.jsxs(vs,{children:[e.jsx(We,{value:"all",children:"All Types"}),e.jsx(We,{value:"buyer",children:"Buyer"}),e.jsx(We,{value:"seller",children:"Seller"})]})]}),e.jsxs(bs,{value:p,onValueChange:g,children:[e.jsx(ys,{className:"w-[130px]",children:e.jsx(_s,{placeholder:"Lead Source"})}),e.jsxs(vs,{children:[e.jsx(We,{value:"all",children:"All Sources"}),A==null?void 0:A.map(B=>e.jsx(We,{value:B.id,children:B.name},B.id))]})]}),e.jsxs($,{variant:v?"default":"outline",size:"sm",onClick:()=>_(!v),children:[e.jsx(oh,{className:"h-4 w-4 mr-1"}),"Wins"]})]})]})}),e.jsx(De,{children:O.length===0?e.jsx("p",{className:"text-center text-muted-foreground py-8",children:"No transactions found"}):I?e.jsx("div",{className:"space-y-3",children:O.map(B=>e.jsxs(we,{className:"p-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"font-medium truncate",children:B.property_address}),B.is_win&&e.jsx(oh,{className:"h-4 w-4 text-yellow-500 flex-shrink-0"})]}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[B.city,B.state?`, ${B.state}`:""]})]}),e.jsx(qe,{variant:B.transaction_type==="buyer"?"default":"secondary",children:B.transaction_type})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2 mt-3 text-sm",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Close Date: "}),Uat(B.close_date)]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Price: "}),yh(B.sale_price)]}),t&&B.commission_amount&&e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Commission: "}),yh(B.commission_amount)]}),B.lead_source&&e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Source: "}),B.lead_source.name]}),B.contact&&e.jsxs("div",{className:"col-span-2",children:[e.jsx("span",{className:"text-muted-foreground",children:"Client: "}),B.contact.first_name," ",B.contact.last_name]}),r&&e.jsxs("div",{className:"col-span-2",children:[e.jsx("span",{className:"text-muted-foreground",children:"Agent: "}),r[B.owner_user_id]||"Unknown"]})]}),!a&&e.jsxs("div",{className:"flex justify-end gap-2 mt-3 pt-3 border-t",children:[e.jsx($,{variant:"ghost",size:"sm",onClick:()=>l(B),children:e.jsx(Cp,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>P(B),children:e.jsx(Da,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>c(B.id),children:e.jsx(Un,{className:"h-4 w-4 text-destructive"})})]})]},B.id))}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(Qa,{children:[e.jsx(Ja,{children:e.jsxs(vn,{children:[r&&e.jsx(Dt,{children:"Agent"}),e.jsx(Dt,{children:"Property"}),e.jsx(Dt,{children:"Type"}),e.jsx(Dt,{children:"Close Date"}),e.jsx(Dt,{children:"Sale Price"}),t&&e.jsx(Dt,{children:"Commission"}),e.jsx(Dt,{children:"Lead Source"}),e.jsx(Dt,{children:"Client"}),!a&&e.jsx(Dt,{className:"w-[50px]"})]})}),e.jsx(ei,{children:O.map(B=>{var U;return e.jsxs(vn,{children:[r&&e.jsx(_t,{className:"font-medium text-sm",children:r[B.owner_user_id]||"Unknown"}),e.jsx(_t,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[B.is_win&&e.jsx(oh,{className:"h-4 w-4 text-yellow-500"}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:B.property_address}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[B.city,B.state?`, ${B.state}`:""]})]})]})}),e.jsx(_t,{children:e.jsx(qe,{variant:B.transaction_type==="buyer"?"default":"secondary",children:B.transaction_type})}),e.jsx(_t,{children:Uat(B.close_date)}),e.jsx(_t,{children:yh(B.sale_price)}),t&&e.jsx(_t,{children:B.commission_amount?yh(B.commission_amount):"-"}),e.jsx(_t,{children:((U=B.lead_source)==null?void 0:U.name)||"-"}),e.jsx(_t,{children:B.contact?`${B.contact.first_name} ${B.contact.last_name||""}`.trim():"-"}),!a&&e.jsx(_t,{children:e.jsxs(Au,{children:[e.jsx(Eu,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",children:e.jsx(Z0,{className:"h-4 w-4"})})}),e.jsxs(gu,{align:"end",children:[e.jsxs(Pa,{onClick:()=>l(B),children:[e.jsx(Cp,{className:"h-4 w-4 mr-2"}),"Edit"]}),e.jsxs(Pa,{onClick:()=>P(B),children:[e.jsx(Da,{className:"h-4 w-4 mr-2"}),"Duplicate"]}),e.jsxs(Pa,{onClick:()=>c(B.id),className:"text-destructive",children:[e.jsx(Un,{className:"h-4 w-4 mr-2"}),"Delete"]})]})]})})]},B.id)})})]})})})]}),e.jsx(jqt,{open:!!i,onOpenChange:B=>!B&&l(null),transaction:i||void 0}),e.jsx(oc,{open:!!o,onOpenChange:B=>!B&&c(null),children:e.jsxs(Ql,{children:[e.jsxs(Jl,{children:[e.jsx(tc,{children:"Delete Transaction?"}),e.jsx(sc,{children:"This action cannot be undone. This will permanently delete this transaction."})]}),e.jsxs(ec,{children:[e.jsx(nc,{children:"Cancel"}),e.jsx(Vl,{onClick:R,className:"bg-destructive text-destructive-foreground",children:"Delete"})]})]})})]})}function Nqt({goals:s,stats:t,year:n,showCommission:r}){const a=new Date().getMonth()+1,i=new Date().getFullYear()===n?a:12,l=12-i,o=(m,p)=>{if(!p||p===0)return null;const g=Math.min(m/p*100,100),x=Math.max(p-m,0),y=l>0?x/l:0,v=i/12*100,_=g>=v?"ahead":g>=v*.8?"on-track":"behind";return{percent:g,remaining:x,pace:y,status:_}},c=o(t.totalTransactions,s.transactions_goal),d=o(t.totalVolume,s.volume_goal),u=r?o(t.totalCommission,s.gci_goal):null,h=m=>{switch(m){case"ahead":return e.jsxs(qe,{className:"bg-green-500 text-white",children:[e.jsx(mc,{className:"h-3 w-3 mr-1"}),"Ahead"]});case"on-track":return e.jsxs(qe,{variant:"secondary",children:[e.jsx(ak,{className:"h-3 w-3 mr-1"}),"On Track"]});case"behind":return e.jsxs(qe,{variant:"destructive",children:[e.jsx(lk,{className:"h-3 w-3 mr-1"}),"Behind"]});default:return null}};return!s.transactions_goal&&!s.volume_goal&&!s.gci_goal?null:e.jsxs(we,{children:[e.jsx(Vt,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(_h,{className:"h-5 w-5 text-primary"}),e.jsxs(Yt,{children:[n," 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"}),h(c.status)]}),e.jsx(ho,{value:c.percent,className:"h-2"}),e.jsxs("div",{className:"flex justify-between text-sm text-muted-foreground",children:[e.jsxs("span",{children:[t.totalTransactions," of ",s.transactions_goal]}),e.jsxs("span",{children:[Math.round(c.percent),"%"]})]}),c.remaining>0&&l>0&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Need ",Math.ceil(c.pace),"/month to hit goal"]})]}),s.volume_goal&&d&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm font-medium",children:"Volume"}),h(d.status)]}),e.jsx(ho,{value:d.percent,className:"h-2"}),e.jsxs("div",{className:"flex justify-between text-sm text-muted-foreground",children:[e.jsxs("span",{children:[yh(t.totalVolume,!0)," of ",yh(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 ",yh(d.pace,!0),"/month"]})]}),r&&s.gci_goal&&u&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm font-medium",children:"GCI"}),h(u.status)]}),e.jsx(ho,{value:u.percent,className:"h-2"}),e.jsxs("div",{className:"flex justify-between text-sm text-muted-foreground",children:[e.jsxs("span",{children:[yh(t.totalCommission,!0)," of ",yh(s.gci_goal,!0)]}),e.jsxs("span",{children:[Math.round(u.percent),"%"]})]}),u.remaining>0&&l>0&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Need ",yh(u.pace,!0),"/month"]})]})]})})]})}const SPn={light:"",dark:".dark"},kqt=k.createContext(null);function Sqt(){const s=k.useContext(kqt);if(!s)throw new Error("useChart must be used within a ");return s}const Cqt=k.forwardRef(({id:s,className:t,children:n,config:r,...a},i)=>{const l=k.useId(),o=`chart-${s||l.replace(/:/g,"")}`;return e.jsx(kqt.Provider,{value:{config:r},children:e.jsxs("div",{"data-chart":o,ref:i,className:Ot("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(CPn,{id:o,config:r}),e.jsx(C_,{children:n})]})})});Cqt.displayName="Chart";const CPn=({id:s,config:t})=>{const n=Object.entries(t).filter(([r,a])=>a.theme||a.color);return n.length?e.jsx("style",{dangerouslySetInnerHTML:{__html:Object.entries(SPn).map(([r,a])=>` ${a} [data-chart=${s}] { ${n.map(([i,l])=>{var c;const o=((c=l.theme)==null?void 0:c[r])||l.color;return o?` --color-${i}: ${o};`:null}).join(` `)} } `).join(` `)}}):null},Aqt=k.forwardRef(({active:s,payload:t,className:n,indicator:r="dot",hideLabel:a=!1,hideIndicator:i=!1,label:l,labelFormatter:o,labelClassName:c,formatter:d,color:u,nameKey:h,labelKey:m},p)=>{const{config:g}=Sqt(),x=k.useMemo(()=>{var A;if(a||!(t!=null&&t.length))return null;const[v]=t,_=`${m||v.dataKey||v.name||"value"}`,j=WUe(g,v,_),C=!m&&typeof l=="string"?((A=g[l])==null?void 0:A.label)||l:j==null?void 0:j.label;return o?e.jsx("div",{className:Ot("font-medium",c),children:o(C,t)}):C?e.jsx("div",{className:Ot("font-medium",c),children:C}):null},[l,o,t,a,c,g,m]);if(!s||!(t!=null&&t.length))return null;const y=t.length===1&&r!=="dot";return e.jsxs("div",{ref:p,className:Ot("grid min-w-[8rem] items-start gap-1.5 rounded-lg border border-border/50 bg-background px-2.5 py-1.5 text-xs shadow-xl",n),children:[y?null:x,e.jsx("div",{className:"grid gap-1.5",children:t.map((v,_)=>{const j=`${h||v.name||v.dataKey||"value"}`,C=WUe(g,v,j),A=u||v.payload.fill||v.color;return e.jsx("div",{className:Ot("flex w-full flex-wrap items-stretch gap-2 [&>svg]:h-2.5 [&>svg]:w-2.5 [&>svg]:text-muted-foreground",r==="dot"&&"items-center"),children:d&&(v==null?void 0:v.value)!==void 0&&v.name?d(v.value,v.name,v,_,v.payload):e.jsxs(e.Fragment,{children:[C!=null&&C.icon?e.jsx(C.icon,{}):!i&&e.jsx("div",{className:Ot("shrink-0 rounded-[2px] border-[--color-border] bg-[--color-bg]",{"h-2.5 w-2.5":r==="dot","w-1":r==="line","w-0 border-[1.5px] border-dashed bg-transparent":r==="dashed","my-0.5":y&&r==="dashed"}),style:{"--color-bg":A,"--color-border":A}}),e.jsxs("div",{className:Ot("flex flex-1 justify-between leading-none",y?"items-end":"items-center"),children:[e.jsxs("div",{className:"grid gap-1.5",children:[y?x:null,e.jsx("span",{className:"text-muted-foreground",children:(C==null?void 0:C.label)||v.name})]}),v.value&&e.jsx("span",{className:"font-mono font-medium tabular-nums text-foreground",children:v.value.toLocaleString()})]})]})},v.dataKey)})})]})});Aqt.displayName="ChartTooltip";const APn=k.forwardRef(({className:s,hideIcon:t=!1,payload:n,verticalAlign:r="bottom",nameKey:a},i)=>{const{config:l}=Sqt();return n!=null&&n.length?e.jsx("div",{ref:i,className:Ot("flex items-center justify-center gap-4",r==="top"?"pb-3":"pt-3",s),children:n.map(o=>{const c=`${a||o.dataKey||"value"}`,d=WUe(l,o,c);return e.jsxs("div",{className:Ot("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});APn.displayName="ChartLegend";function WUe(s,t,n){if(typeof t!="object"||t===null)return;const r="payload"in t&&typeof t.payload=="object"&&t.payload!==null?t.payload:void 0;let a=n;return n in t&&typeof t[n]=="string"?a=t[n]:r&&n in r&&typeof r[n]=="string"&&(a=r[n]),a in s?s[a]:s[n]}const Hae=["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 lQe({stats:s,year:t}){const n=s.transactionsByMonth.some(a=>a.count>0),r=s.leadSourceBreakdown.length>0;return!n&&!r?e.jsx(we,{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:[n&&e.jsxs(we,{className:"overflow-hidden",children:[e.jsx(Vt,{children:e.jsx(Yt,{className:"text-base",children:"Transactions by Month"})}),e.jsx(De,{className:"overflow-hidden",children:e.jsx(Cqt,{config:{count:{label:"Transactions",color:"hsl(var(--primary))"}},className:"h-[250px]",children:e.jsx(C_,{width:"100%",height:"100%",children:e.jsxs(YEe,{data:s.transactionsByMonth,margin:{top:5,right:10,left:0,bottom:5},children:[e.jsx(XO,{strokeDasharray:"3 3",className:"stroke-muted"}),e.jsx(Cb,{dataKey:"month",tick:{fontSize:11},className:"fill-muted-foreground",interval:0}),e.jsx(Ab,{allowDecimals:!1,tick:{fontSize:12},className:"fill-muted-foreground",width:30}),e.jsx(vg,{content:e.jsx(Aqt,{})}),e.jsx(R2,{dataKey:"count",fill:"hsl(var(--primary))",radius:[4,4,0,0],name:"Transactions"})]})})})})]}),r&&e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsx(Yt,{className:"text-base",children:"Lead Sources"})}),e.jsxs(De,{children:[e.jsx("div",{className:"h-[250px]",children:e.jsx(C_,{width:"100%",height:"100%",children:e.jsxs(xZe,{children:[e.jsx(Mk,{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(vV,{fill:Hae[i%Hae.length]},`cell-${i}`))}),e.jsx(vg,{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:Hae[i%Hae.length]}}),e.jsx("span",{className:"text-muted-foreground",children:a.name})]},a.name))})]})]})]})}function EPn(s){if(!s||!s.trim())return null;const t=s.trim(),n=["yyyy-MM-dd","M/d/yyyy","MM/dd/yyyy","M-d-yyyy","MM-dd-yyyy","MM/dd/yy","M/d/yy"];for(const r of n)try{const a=cGe(t,r,new Date);if(f7e(a))return Ys(a,"yyyy-MM-dd")}catch{}try{const r=new Date(t);if(f7e(r))return Ys(r,"yyyy-MM-dd")}catch{}return null}const TPn=["property_address","city","state","zip","transaction_type","close_date","sale_price","commission_amount","lead_source","client_type","is_win","notes"];function MPn({open:s,onOpenChange:t}){const[n,r]=k.useState([]),[a,i]=k.useState(!1),[l,o]=k.useState(0),{data:c}=NF(),{data:d}=vj(),u=yAe(),h=()=>{const v=TPn.join(","),_=["123 Main St","Dallas","TX","75001","buyer","2024-06-15","450000","13500","Referral","Past Client","yes","Great transaction!"].join(","),j=`${v} ${_}`,C=new Blob([j],{type:"text/csv"}),A=URL.createObjectURL(C),M=document.createElement("a");M.href=A,M.download="transaction-import-template.csv",M.click(),URL.revokeObjectURL(A)},m=v=>{const _=v.split(` `).filter(C=>C.trim());if(_.length<2)return[];const j=_[0].split(",").map(C=>C.trim().toLowerCase().replace(/['"]/g,""));return _.slice(1).map((C,A)=>{var ee,oe,me,Q;const M=[];let I="",P=!1;for(const te of C)te==='"'?P=!P:te===","&&!P?(M.push(I.trim()),I=""):I+=te;M.push(I.trim());const R=te=>{var fe;const le=j.indexOf(te);return le>=0?(fe=M[le])==null?void 0:fe.replace(/^["']|["']$/g,"").trim():""},O=(ee=R("transaction_type"))==null?void 0:ee.toLowerCase(),B=(oe=R("sale_price"))==null?void 0:oe.replace(/[$,]/g,""),U=(me=R("commission_amount"))==null?void 0:me.replace(/[$,]/g,""),G=(Q=R("is_win"))==null?void 0:Q.toLowerCase(),H=R("close_date"),Y=EPn(H);let se;return R("property_address")?["buyer","seller"].includes(O)?Y?(!B||isNaN(Number(B)))&&(se="Invalid sale price"):se=`Invalid date format: "${H}" - use MM/DD/YYYY or YYYY-MM-DD`:se='Transaction type must be "buyer" or "seller"':se="Missing property address",{property_address:R("property_address"),city:R("city"),state:R("state"),zip:R("zip"),transaction_type:O==="seller"?"seller":"buyer",close_date:Y||"",sale_price:Number(B)||0,commission_amount:U?Number(U):null,lead_source_name:R("lead_source"),client_type_name:R("client_type"),is_win:["yes","true","1"].includes(G),notes:R("notes"),error:se}})},p=v=>{var C;const _=(C=v.target.files)==null?void 0:C[0];if(!_)return;const j=new FileReader;j.onload=A=>{var P;const M=(P=A.target)==null?void 0:P.result,I=m(M);r(I)},j.readAsText(_)},g=async()=>{const v=n.filter(C=>!C.error);if(v.length===0){ae.error("No valid transactions to import");return}i(!0),o(0);let _=0,j=0;for(let C=0;CP.name.toLowerCase()===A.lead_source_name.toLowerCase()),I=d==null?void 0:d.find(P=>P.name.toLowerCase()===A.client_type_name.toLowerCase());await u.mutateAsync({property_address:A.property_address,city:A.city||null,state:A.state||null,zip:A.zip||null,transaction_type:A.transaction_type,close_date:A.close_date,sale_price:A.sale_price,commission_amount:A.commission_amount,lead_source_id:(M==null?void 0:M.id)||null,client_type_id:(I==null?void 0:I.id)||null,contact_id:null,notes:A.notes||null,is_win:A.is_win}),_++}catch(M){j++,console.error("Failed to import transaction:",M)}o(Math.round((C+1)/v.length*100))}i(!1),_>0&&ae.success(`Imported ${_} transaction${_>1?"s":""}`),j>0&&ae.error(`Failed to import ${j} transaction${j>1?"s":""}`),r([]),t(!1)},x=n.filter(v=>!v.error).length,y=n.filter(v=>v.error).length;return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"max-w-2xl max-h-[90vh]",children:[e.jsxs(Vs,{children:[e.jsx($s,{children:"Import Transactions"}),e.jsx(Cr,{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($,{variant:"outline",onClick:h,children:[e.jsx(ji,{className:"h-4 w-4 mr-2"}),"Template"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"csv-file",children:"Upload CSV File"}),e.jsx(be,{id:"csv-file",type:"file",accept:".csv",onChange:p})]}),n.length>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(qe,{variant:"outline",children:[n.length," rows found"]}),x>0&&e.jsxs(qe,{className:"bg-green-500 text-white",children:[e.jsx(ma,{className:"h-3 w-3 mr-1"}),x," valid"]}),y>0&&e.jsxs(qe,{variant:"destructive",children:[e.jsx(Ho,{className:"h-3 w-3 mr-1"}),y," errors"]})]}),e.jsx(Eo,{className:"h-[200px] border rounded-lg",children:e.jsxs("div",{className:"p-2 space-y-2",children:[n.slice(0,10).map((v,_)=>e.jsxs("div",{className:`p-2 rounded text-sm ${v.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:v.property_address||"(no address)"}),e.jsx(qe,{variant:v.transaction_type==="buyer"?"default":"secondary",children:v.transaction_type})]}),e.jsxs("div",{className:"text-muted-foreground",children:[v.close_date," • $",v.sale_price.toLocaleString()]}),v.error&&e.jsx(IKe,{variant:"destructive",className:"mt-1 py-1",children:e.jsx(LKe,{className:"text-xs",children:v.error})})]},_)),n.length>10&&e.jsxs("p",{className:"text-center text-sm text-muted-foreground",children:["...and ",n.length-10," more"]})]})}),a&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"w-full bg-muted rounded-full h-2",children:e.jsx("div",{className:"bg-primary h-2 rounded-full transition-all",style:{width:`${l}%`}})}),e.jsxs("p",{className:"text-sm text-center text-muted-foreground",children:["Importing... ",l,"%"]})]})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs($,{onClick:g,disabled:x===0||a,children:[e.jsx(gi,{className:"h-4 w-4 mr-2"}),"Import ",x," Transaction",x!==1?"s":""]})]})]})]})})}const PPn=t4({transactions_goal:xY().min(0).optional(),volume_goal:xY().min(0).optional(),gci_goal:xY().min(0).optional()});function IPn({open:s,onOpenChange:t,year:n,existingGoals:r}){const a=GEs(),{data:i}=vAe(),l=(i==null?void 0:i.show_commission)??!0,o=D3e({resolver:O3e(PPn),defaultValues:{transactions_goal:void 0,volume_goal:void 0,gci_goal:void 0}});k.useEffect(()=>{r?o.reset({transactions_goal:r.transactions_goal??void 0,volume_goal:r.volume_goal?Number(r.volume_goal):void 0,gci_goal:r.gci_goal?Number(r.gci_goal):void 0}):o.reset({transactions_goal:void 0,volume_goal:void 0,gci_goal:void 0})},[r,o,s]);const c=async d=>{await a.mutateAsync({year:n,transactions_goal:d.transactions_goal??null,volume_goal:d.volume_goal??null,gci_goal:l?d.gci_goal??null:null}),t(!1)};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"max-w-md",children:[e.jsxs(Vs,{children:[e.jsxs($s,{children:[n," Goals"]}),e.jsx(Cr,{children:"Set your annual targets to track your progress throughout the year."})]}),e.jsx($3e,{...o,children:e.jsxs("form",{onSubmit:o.handleSubmit(c),className:"space-y-4",children:[e.jsx(Sp,{control:o.control,name:"transactions_goal",render:({field:d})=>e.jsxs(Zf,{children:[e.jsx(Xf,{children:"Transactions Goal"}),e.jsx(Qf,{children:e.jsx(be,{type:"number",placeholder:"e.g., 24",...d,value:d.value??"",onChange:u=>d.onChange(u.target.value?Number(u.target.value):void 0)})}),e.jsx(eNe,{children:"Total number of deals you want to close"}),e.jsx(ib,{})]})}),e.jsx(Sp,{control:o.control,name:"volume_goal",render:({field:d})=>e.jsxs(Zf,{children:[e.jsx(Xf,{children:"Volume Goal ($)"}),e.jsx(Qf,{children:e.jsx(be,{type:"number",placeholder:"e.g., 5000000",...d,value:d.value??"",onChange:u=>d.onChange(u.target.value?Number(u.target.value):void 0)})}),e.jsx(eNe,{children:"Total sales volume you want to achieve"}),e.jsx(ib,{})]})}),l&&e.jsx(Sp,{control:o.control,name:"gci_goal",render:({field:d})=>e.jsxs(Zf,{children:[e.jsx(Xf,{children:"GCI Goal ($)"}),e.jsx(Qf,{children:e.jsx(be,{type:"number",placeholder:"e.g., 150000",...d,value:d.value??"",onChange:u=>d.onChange(u.target.value?Number(u.target.value):void 0)})}),e.jsx(eNe,{children:"Gross commission income target"}),e.jsx(ib,{})]})}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx($,{type:"button",variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx($,{type:"submit",disabled:a.isPending,children:"Save Goals"})]})]})})]})})}function cQe({transactions:s,isLoading:t}){const n=k.useRef(null),r=k.useRef(null),a=k.useRef([]),i=k.useRef(null),{isAdmin:l}=ks(),[o,c]=k.useState(""),[d,u]=k.useState(!0),[h,m]=k.useState(0),[p,g]=k.useState(!1),x=s.filter(v=>v.latitude!=null&&v.longitude!=null),y=s.filter(v=>v.latitude==null||v.longitude==null);return k.useEffect(()=>{(async()=>{u(!0);try{const{data:_}=await V.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle();_!=null&&_.value&&c(_.value)}catch(_){console.error("Error fetching mapbox token:",_)}u(!1)})()},[]),k.useEffect(()=>{if(!o||y.length===0||p)return;(async()=>{var j;g(!0);let _=0;for(const C of y){const A=[C.property_address,C.city,C.state,C.zip].filter(Boolean).join(", ");if(A)try{const I=await(await fetch(`https://api.mapbox.com/geocoding/v5/mapbox.places/${encodeURIComponent(A)}.json?access_token=${o}&limit=1`)).json();if((j=I.features)!=null&&j[0]){const[P,R]=I.features[0].center;await V.from("scorecard_transactions").update({latitude:R,longitude:P}).eq("id",C.id),C.latitude=R,C.longitude=P,_++}}catch(M){console.error("Geocode error:",M)}}m(_),g(!1)})()},[o,s]),k.useEffect(()=>{if(!n.current||!o||r.current)return;Td.accessToken=o;const v=s.filter(C=>C.latitude!=null&&C.longitude!=null);let _=[-98.5795,39.8283],j=4;if(v.length>0){const C=v.reduce((M,I)=>M+I.longitude,0)/v.length,A=v.reduce((M,I)=>M+I.latitude,0)/v.length;_=[C,A],j=v.length===1?12:10}return r.current=new Td.Map({container:n.current,style:"mapbox://styles/mapbox/light-v11",zoom:j,center:_}),r.current.addControl(new Td.NavigationControl,"top-right"),()=>{var C;(C=r.current)==null||C.remove(),r.current=null}},[o]),k.useEffect(()=>{var _;if(!r.current||!o)return;a.current.forEach(j=>j.remove()),a.current=[],(_=i.current)==null||_.remove();const v=s.filter(j=>j.latitude!=null&&j.longitude!=null);if(v.forEach(j=>{var R;const C=j.transaction_type==="buyer",A=C?"#3B82F6":"#10B981",M=document.createElement("div");M.className="cursor-pointer",M.innerHTML=`
${C?'':''}
`;const I=new Td.Popup({offset:25,closeButton:!0}).setHTML(`
${j.property_address}
${j.city?`
${j.city}${j.state?", "+j.state:""} ${j.zip||""}
`:""}
${C?"Buyer":"Seller"} $${Number(j.sale_price).toLocaleString()}
Closed: ${ih(j.close_date).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"})} ${(R=j.lead_source)!=null&&R.name?" · "+j.lead_source.name:""}
${j.contact?`
Client: ${j.contact.first_name} ${j.contact.last_name||""}
`:""}
`),P=new Td.Marker(M).setLngLat([j.longitude,j.latitude]).setPopup(I).addTo(r.current);a.current.push(P)}),v.length>1){const j=new Td.LngLatBounds;v.forEach(C=>j.extend([C.longitude,C.latitude])),r.current.fitBounds(j,{padding:60,maxZoom:13})}else v.length===1&&r.current.flyTo({center:[v[0].longitude,v[0].latitude],zoom:12})},[s,o,p]),d||t?e.jsx(we,{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(we,{children:e.jsxs(De,{className:"flex flex-col items-center justify-center h-[50vh] text-center gap-3",children:[e.jsx(Si,{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:[x.length," of ",s.length," mapped",p&&" · Geocoding..."]})]}),e.jsx("div",{ref:n,className:"w-full h-[55vh] rounded-lg shadow-lg border"})]}):e.jsx(we,{children:e.jsxs(De,{className:"flex flex-col items-center justify-center h-[50vh] text-center gap-3",children:[e.jsx(Ho,{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 Eqt=()=>{const{data:s}=gj();return pt({queryKey:["team-scorecard-members",s==null?void 0:s.teamId],queryFn:async()=>{const{data:t,error:n}=await V.from("team_members").select("user_id").eq("team_id",s.teamId);if(n)throw n;const r=t.map(l=>l.user_id),{data:a,error:i}=await V.from("profiles").select("id, name, email, avatar_url").in("id",r);if(i)throw i;return a||[]},enabled:!!(s!=null&&s.teamId)&&(s==null?void 0:s.role)==="team_leader"})},LPn=s=>{const{data:t}=gj(),{data:n}=Eqt();return pt({queryKey:["team-scorecard-transactions",t==null?void 0:t.teamId,s],queryFn:async()=>{const r=n.map(o=>o.id);let a=V.from("scorecard_transactions").select(` *, lead_source:lead_sources(id, name), client_type:relationship_types(id, name), contact:innercircle_contacts(id, first_name, last_name) `).in("owner_user_id",r).order("close_date",{ascending:!1});s&&(a=a.gte("close_date",`${s}-01-01`).lte("close_date",`${s}-12-31`));const{data:i,error:l}=await a;if(l)throw l;return i},enabled:!!n&&n.length>0})};function RPn(s,t){const n=t.filter(i=>i.owner_user_id===s.id),r=n.reduce((i,l)=>i+Number(l.sale_price),0),a=n.reduce((i,l)=>i+(Number(l.commission_amount)||0),0);return{member:s,totalTransactions:n.length,buyerCount:n.filter(i=>i.transaction_type==="buyer").length,sellerCount:n.filter(i=>i.transaction_type==="seller").length,totalVolume:r,averagePrice:n.length>0?r/n.length:0,totalGCI:a}}function DPn(s,t){return s?s.split(" ").map(n=>n[0]).join("").toUpperCase().slice(0,2):t[0].toUpperCase()}function OPn({year:s}){var m;const{data:t,isLoading:n}=Eqt(),{data:r,isLoading:a}=LPn(s),i=Jn(),l=n||a,{aggregate:o,memberStats:c,topPerformer:d,agentNameMap:u,teamChartStats:h}=k.useMemo(()=>{if(!t||!r)return{aggregate:null,memberStats:[],topPerformer:null,agentNameMap:{},teamChartStats:null};const p=t.map(O=>RPn(O,r));p.sort((O,B)=>B.totalVolume-O.totalVolume);const g={};t.forEach(O=>{g[O.id]=O.name||O.email});const x=r.length,y=r.reduce((O,B)=>O+Number(B.sale_price),0),v=r.reduce((O,B)=>O+(Number(B.commission_amount)||0),0),_=r.filter(O=>O.transaction_type==="buyer").length,j=r.filter(O=>O.transaction_type==="seller").length,C={};r.forEach(O=>{var U;const B=((U=O.lead_source)==null?void 0:U.name)||"Unknown";C[B]=(C[B]||0)+1});const A=Object.entries(C).sort((O,B)=>B[1]-O[1])[0],M={};r.forEach(O=>{const B=ih(O.close_date).toLocaleString("default",{month:"short"});M[B]=(M[B]||0)+1});const P=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"].map(O=>({month:O,count:M[O]||0})),R=Object.entries(C).map(([O,B])=>({name:O,count:B})).sort((O,B)=>B.count-O.count);return{aggregate:{totalTxns:x,buyerCount:_,sellerCount:j,totalVolume:y,avgPrice:x>0?y/x:0,totalGCI:v,topSource:A?{name:A[0],count:A[1]}:null,memberCount:t.length},memberStats:p,topPerformer:p[0]||null,agentNameMap:g,teamChartStats:{transactionsByMonth:P,leadSourceBreakdown:R}}},[t,r]);return l?e.jsxs("div",{className:"space-y-6",children:[e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[1,2,3,4].map(p=>e.jsx(fn,{className:"h-24"},p))}),e.jsx(fn,{className:"h-64"})]}):!o||c.length===0?e.jsx(we,{className:"py-12",children:e.jsxs(De,{className:"text-center space-y-2",children:[e.jsx(Xn,{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(we,{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(Xn,{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(we,{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(ua,{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(we,{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(Su,{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:yh(o.totalVolume,!0)})]})}),e.jsx(we,{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(mc,{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:yh(o.avgPrice,!0)})]})}),e.jsx(we,{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(Su,{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:yh(o.totalGCI,!0)})]})}),e.jsx(we,{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(oh,{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:((m=o.topSource)==null?void 0:m.name)||"-"}),o.topSource&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:[o.topSource.count," deals"]})]})})]}),d&&d.totalTransactions>0&&e.jsx(we,{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(ql,{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:yh(d.totalVolume,!0)})]})]})}),e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsx(Yt,{className:"text-lg",children:"Member Performance"})}),e.jsx(De,{children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(Qa,{children:[e.jsx(Ja,{children:e.jsxs(vn,{children:[e.jsx(Dt,{children:"Agent"}),e.jsx(Dt,{className:"text-center",children:"Transactions"}),e.jsx(Dt,{className:"text-center",children:"B / S"}),e.jsx(Dt,{className:"text-right",children:"Volume"}),e.jsx(Dt,{className:"text-right",children:"Avg Price"}),e.jsx(Dt,{className:"text-right",children:"GCI"}),e.jsx(Dt,{className:"text-right"})]})}),e.jsx(ei,{children:c.map((p,g)=>e.jsxs(vn,{children:[e.jsx(_t,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"relative",children:[g===0&&p.totalTransactions>0&&e.jsx(ql,{className:"absolute -top-2 -right-2 h-3.5 w-3.5 text-amber-500"}),e.jsxs(Wa,{className:"h-8 w-8",children:[e.jsx(eo,{src:p.member.avatar_url||void 0}),e.jsx(Ka,{className:"text-xs",children:DPn(p.member.name,p.member.email)})]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:p.member.name||p.member.email}),p.member.name&&e.jsx("p",{className:"text-xs text-muted-foreground",children:p.member.email})]})]})}),e.jsx(_t,{className:"text-center font-semibold",children:p.totalTransactions}),e.jsxs(_t,{className:"text-center text-sm",children:[p.buyerCount," / ",p.sellerCount]}),e.jsx(_t,{className:"text-right font-medium",children:yh(p.totalVolume,!0)}),e.jsx(_t,{className:"text-right text-sm",children:yh(p.averagePrice,!0)}),e.jsx(_t,{className:"text-right font-medium",children:yh(p.totalGCI,!0)}),e.jsx(_t,{className:"text-right",children:e.jsx($,{variant:"ghost",size:"sm",onClick:()=>i(`/mission-control/scorecard/${p.member.id}`),children:e.jsx(ba,{className:"h-4 w-4"})})})]},p.member.id))})]})})})]}),e.jsxs(ya,{defaultValue:"transactions",className:"space-y-4",children:[e.jsxs(va,{children:[e.jsxs(is,{value:"transactions",children:[e.jsx(Sy,{className:"h-4 w-4 mr-1"}),"All Transactions"]}),e.jsxs(is,{value:"charts",children:[e.jsx(Ul,{className:"h-4 w-4 mr-1"}),"Charts"]}),e.jsxs(is,{value:"map",children:[e.jsx(Si,{className:"h-4 w-4 mr-1"}),"Map"]})]}),e.jsx(cs,{value:"transactions",children:e.jsx(oQe,{transactions:r||[],showCommission:!0,isLoading:a,agentNameMap:u,readOnly:!0})}),e.jsx(cs,{value:"charts",children:h&&e.jsx(lQe,{stats:h,year:s})}),e.jsx(cs,{value:"map",children:e.jsx(cQe,{transactions:r||[],isLoading:a})})]})]})}const uke=new Date().getFullYear(),F1t=Array.from({length:10},(s,t)=>uke-t),Gae="all";function FPn(){var B;const[s,t]=k.useState(uke),n=s===null?Gae:String(s),r=U=>t(U===Gae?null:Number(U)),[a,i]=k.useState(!1),[l,o]=k.useState(!1),[c,d]=k.useState(!1),[u,h]=k.useState(!1),[m,p]=k.useState("my"),{data:g}=gj(),x=(g==null?void 0:g.role)==="team_leader",{data:y,isLoading:v}=_We(s??void 0),{yearStats:_,lifetimeStats:j,showCommission:C}=JMt(s??void 0),{data:A,isLoading:M}=QMt(s??uke),{data:I}=vAe(),P=WEs(),R=()=>{if(!y||y.length===0)return;const U=["Property Address","City","State","Zip","Transaction Type","Close Date","Sale Price",...C?["Commission"]:[],"Lead Source","Client Type","Contact Name","Is Win","Notes"],G=y.map(oe=>{var me,Q;return[oe.property_address,oe.city||"",oe.state||"",oe.zip||"",oe.transaction_type,oe.close_date,oe.sale_price,...C?[oe.commission_amount||""]:[],((me=oe.lead_source)==null?void 0:me.name)||"",((Q=oe.client_type)==null?void 0:Q.name)||"",oe.contact?`${oe.contact.first_name} ${oe.contact.last_name||""}`.trim():"",oe.is_win?"Yes":"No",oe.notes||""]}),H=[U,...G].map(oe=>oe.map(me=>`"${String(me).replace(/"/g,'""')}"`).join(",")).join(` `),Y=new Blob([H],{type:"text/csv"}),se=URL.createObjectURL(Y),ee=document.createElement("a");ee.href=se,ee.download=s===null?"transactions-all.csv":`transactions-${s}.csv`,ee.click(),URL.revokeObjectURL(se)},O=!y||y.length===0;return e.jsxs(Xs,{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"})]}),x&&e.jsxs("div",{className:"flex items-center gap-1 bg-muted rounded-lg p-1 w-fit",children:[e.jsx($,{variant:m==="my"?"default":"ghost",size:"sm",onClick:()=>p("my"),className:"h-8",children:"My Scorecard"}),e.jsxs($,{variant:m==="team"?"default":"ghost",size:"sm",onClick:()=>p("team"),className:"h-8",children:[e.jsx(Xn,{className:"h-4 w-4 mr-1.5"}),"Team"]})]}),m==="team"&&x?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(bs,{value:n,onValueChange:r,children:[e.jsx(ys,{className:"w-[140px]",children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:Gae,children:"All Years"}),F1t.map(U=>e.jsx(We,{value:String(U),children:U},U))]})]})]}),e.jsx(OPn,{year:s??void 0})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Business Scorecard"}),e.jsx("p",{className:"text-muted-foreground",children:"Track your transactions, goals, and performance"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(bs,{value:n,onValueChange:r,children:[e.jsx(ys,{className:"w-[140px]",children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:Gae,children:"All Years"}),F1t.map(U=>e.jsx(We,{value:String(U),children:U},U))]})]}),e.jsx($,{variant:"outline",size:"icon",onClick:()=>h(!u),children:e.jsx(Yc,{className:"h-4 w-4"})})]})]}),u&&e.jsxs(we,{children:[e.jsx(Vt,{className:"pb-3",children:e.jsx(Yt,{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(re,{children:"Show Commission"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Display commission fields and include in stats"})]}),e.jsx(On,{checked:(I==null?void 0:I.show_commission)??!0,onCheckedChange:U=>P.mutate({show_commission:U})})]})})]}),O&&!v?e.jsx(we,{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(Ul,{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($,{onClick:()=>i(!0),children:[e.jsx(nn,{className:"h-4 w-4 mr-2"}),"Add Your First Transaction"]}),e.jsxs($,{variant:"outline",onClick:()=>o(!0),children:[e.jsx(gi,{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($,{variant:"link",className:"h-auto p-0",asChild:!0,children:e.jsxs("a",{href:"/templates/transaction-import-template.csv",download:!0,children:[e.jsx(ji,{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($,{onClick:()=>i(!0),children:[e.jsx(nn,{className:"h-4 w-4 mr-2"}),"Add Transaction"]}),e.jsxs($,{variant:"outline",onClick:()=>d(!0),children:[e.jsx(_h,{className:"h-4 w-4 mr-2"}),"Set Goals"]}),e.jsxs($,{variant:"outline",onClick:()=>o(!0),children:[e.jsx(gi,{className:"h-4 w-4 mr-2"}),"Import"]}),e.jsxs($,{variant:"outline",onClick:R,disabled:O,children:[e.jsx(ji,{className:"h-4 w-4 mr-2"}),"Export"]}),e.jsx($,{variant:"ghost",size:"sm",asChild:!0,children:e.jsxs("a",{href:"/templates/transaction-import-template.csv",download:!0,children:[e.jsx(ji,{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(we,{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(ua,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Transactions"})]}),e.jsx("p",{className:"text-2xl font-bold",children:_.totalTransactions}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[j.totalTransactions," lifetime"]})]})}),e.jsx(we,{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(Xn,{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:[_.buyerCount,"/",_.sellerCount]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"B/S split"})]})}),e.jsx(we,{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(Su,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Volume"})]}),e.jsx("p",{className:"text-2xl font-bold",children:yh(_.totalVolume,!0)}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[yh(j.totalVolume,!0)," lifetime"]})]})}),e.jsx(we,{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(mc,{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:yh(_.averagePrice,!0)})]})}),e.jsx(we,{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(oh,{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:((B=_.topLeadSource)==null?void 0:B.name)||"-"}),_.topLeadSource&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:[_.topLeadSource.count," deals"]})]})}),C&&e.jsx(we,{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(Su,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"GCI"})]}),e.jsx("p",{className:"text-2xl font-bold",children:yh(_.totalCommission,!0)}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[yh(j.totalCommission,!0)," lifetime"]})]})}),C&&_.totalNetToAgent>0&&_.totalNetToAgent!==_.totalCommission&&e.jsx(we,{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(Su,{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:yh(_.totalNetToAgent,!0)}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[yh(j.totalNetToAgent,!0)," lifetime"]})]})})]}),s!==null&&A&&e.jsx(Nqt,{goals:A,stats:_,year:s,showCommission:C}),e.jsxs(ya,{defaultValue:"transactions",className:"space-y-4",children:[e.jsxs(va,{children:[e.jsx(is,{value:"transactions",children:"Transactions"}),e.jsx(is,{value:"charts",children:"Charts"}),e.jsxs(is,{value:"map",children:[e.jsx(Si,{className:"h-4 w-4 mr-1"}),"Map"]})]}),e.jsx(cs,{value:"transactions",children:e.jsx(oQe,{transactions:y||[],showCommission:C,isLoading:v})}),e.jsx(cs,{value:"charts",children:e.jsx(lQe,{stats:_,year:s??void 0})}),e.jsx(cs,{value:"map",children:e.jsx(cQe,{transactions:y||[],isLoading:v})})]})]})]})]}),e.jsx(jqt,{open:a,onOpenChange:i}),e.jsx(MPn,{open:l,onOpenChange:o}),e.jsx(IPn,{open:c,onOpenChange:d,year:s??uke,existingGoals:A})]})}function Tqt({open:s,onOpenChange:t,listingId:n,listingSlug:r,listingTitle:a}){const{user:i}=ks(),[l,o]=k.useState(null),[c,d]=k.useState(!1),[u,h]=k.useState(!1);k.useEffect(()=>{(async()=>{if(!(!s||!i)){d(!0);try{const{data:y,error:v}=await V.from("listing_shares").select("id, share_token, click_count, lead_count").eq("listing_id",n).eq("sharing_agent_id",i.id).order("created_at",{ascending:!1}).limit(1).maybeSingle();if(v)throw v;if(y&&y.share_token)o(y);else if(y&&!y.share_token){const{data:_,error:j}=await V.from("listing_shares").update({share_type:"referral_link"}).eq("id",y.id).select("id, share_token, click_count, lead_count").single();if(j)throw j;o(_)}else{const{data:_,error:j}=await V.from("listing_shares").insert({listing_id:n,sharing_agent_id:i.id,share_type:"referral_link"}).select("id, share_token, click_count, lead_count").single();if(j)throw j;o(_)}}catch(y){console.error("Error creating share link:",y),ae.error("Failed to generate share link")}finally{d(!1)}}})()},[s,i,n]);const m=l!=null&&l.share_token?`https://listings.relevelup.com/${r||n}?ref=${l.share_token}`:"",p=async()=>{try{await navigator.clipboard.writeText(m),h(!0),ae.success("Link copied to clipboard!"),setTimeout(()=>h(!1),2e3)}catch{ae.error("Failed to copy link")}},g=x=>{const y=encodeURIComponent(m),v=encodeURIComponent(`Check out this listing: ${a}`);switch(x){case"email":window.open(`mailto:?subject=${v}&body=${y}`);break;case"text":window.open(`sms:?body=${v}%20${y}`);break;case"facebook":window.open(`https://www.facebook.com/sharer/sharer.php?u=${y}`,"_blank");break}};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"sm:max-w-md",children:[e.jsxs(Vs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(kn,{className:"h-5 w-5 text-amber-500"}),"Share & Earn Leads"]}),e.jsx(Cr,{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(re,{children:"Your Referral Link"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(be,{value:c?"Generating...":m,readOnly:!0,className:"font-mono text-sm"}),e.jsx($,{onClick:p,disabled:c||!m,variant:u?"default":"outline",children:u?e.jsx(ma,{className:"h-4 w-4"}):e.jsx(Da,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Share via"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs($,{variant:"outline",className:"flex-1",onClick:()=>g("email"),disabled:c,children:[e.jsx(pn,{className:"h-4 w-4 mr-2"}),"Email"]}),e.jsxs($,{variant:"outline",className:"flex-1",onClick:()=>g("text"),disabled:c,children:[e.jsx(bo,{className:"h-4 w-4 mr-2"}),"Text"]}),e.jsxs($,{variant:"outline",className:"flex-1",onClick:()=>g("facebook"),disabled:c,children:[e.jsx(ax,{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(re,{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(ba,{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(Xn,{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 zPn={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"},BPn={active:"Active",coming_soon:"Coming Soon",office_exclusive:"Office Exclusive",pre_market:"Pre-Market",price_improvement:"Price Improvement",under_contract:"Under Contract",sold:"Sold"},$Pn={single_family:"Single Family",condo:"Condo",townhouse:"Townhouse",land:"Land",multi_family:"Multi-Family",luxury:"Luxury",commercial:"Commercial",other:"Other"};function UPn({listing:s,onClick:t,onEdit:n,onDelete:r,onCreateMusicVideo:a,showActions:i}){var y,v;const{user:l}=ks(),{data:o}=$Mt(s.id),c=BMt(),[d,u]=k.useState(!1),h=_=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(_),m=((y=s.photos)==null?void 0:y.find(_=>_.is_primary))||((v=s.photos)==null?void 0:v[0]),p=(l==null?void 0:l.id)===s.agent_id,g=async _=>{_.stopPropagation();try{const j=await c.mutateAsync(s.id);ae.success(j.saved?"Listing saved!":"Listing removed from saved")}catch{ae.error("Failed to save listing")}},x=_=>{if(_.stopPropagation(),l)u(!0);else{const j=`https://listings.relevelup.com/${s.slug||s.id}`;navigator.clipboard.writeText(j),ae.success("Link copied to clipboard!")}};return e.jsxs(we,{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(w_,{className:"h-12 w-12"})}),e.jsx(qe,{className:`absolute top-2 left-2 ${zPn[s.status]} text-white border-0`,children:BPn[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(ri,{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($,{size:"icon",variant:"secondary",className:"h-8 w-8",onClick:g,children:e.jsx(Bo,{className:`h-4 w-4 ${o?"fill-pink-500 text-pink-500":""}`})}),e.jsx($,{size:"icon",variant:"secondary",className:"h-8 w-8",onClick:x,title:p?"Copy link":"Share & earn leads",children:p?e.jsx(ou,{className:"h-4 w-4"}):e.jsx(kn,{className:"h-4 w-4 text-amber-500"})})]})]}),e.jsx(Tqt,{open:d,onOpenChange:u,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(qe,{variant:"outline",className:"text-xs",children:[e.jsx(Xn,{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(Si,{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(Yw,{className:"h-4 w-4"}),s.bedrooms," bd"]}),s.bathrooms&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(p0,{className:"h-4 w-4"}),s.bathrooms," ba"]}),s.square_footage&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(w_,{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(qe,{variant:"secondary",className:"text-xs",children:$Pn[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(ba,{className:"h-3 w-3"}),s.view_count]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ou,{className:"h-3 w-3"}),s.share_count]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Bo,{className:"h-3 w-3"}),s.save_count]})]}),i&&(n||r||a)&&e.jsxs("div",{className:"flex flex-wrap gap-2",children:[a&&e.jsxs($,{variant:"outline",size:"sm",className:"flex-1 min-w-[140px] gap-1.5 border-violet-500/60 text-violet-600 hover:bg-violet-50",onClick:_=>{_.stopPropagation(),a()},children:[e.jsx(rB,{className:"h-4 w-4"}),"Music Video"]}),n&&e.jsxs($,{variant:"outline",size:"sm",className:"flex-1",onClick:_=>{_.stopPropagation(),n()},children:[e.jsx(Cp,{className:"h-4 w-4 mr-2"}),"Edit"]}),r&&e.jsx($,{variant:"destructive",size:"sm",onClick:_=>{_.stopPropagation(),r()},children:e.jsx(Un,{className:"h-4 w-4"})})]})]})]})}const dQe="lu_listing_selection_v1",X4e=24,Q4e=new Set;function Mqt(){try{return JSON.parse(sessionStorage.getItem(dQe)||"{}")}catch{return{}}}function $De(s){try{sessionStorage.setItem(dQe,JSON.stringify(s))}catch{}Q4e.forEach(t=>t())}let hC=Mqt();function qPn(){hC=Mqt(),Q4e.forEach(s=>s())}typeof window<"u"&&window.addEventListener("storage",s=>{s.key===dQe&&qPn()});const wE={getSnapshot:()=>hC,subscribe(s){return Q4e.add(s),()=>Q4e.delete(s)},toggle(s){const t={...hC};if(t[s.mlsNumber])delete t[s.mlsNumber];else{if(Object.keys(t).length>=X4e)return!1;t[s.mlsNumber]=s}return hC=t,$De(t),!0},remove(s){const t={...hC};delete t[s],hC=t,$De(t)},clear(){hC={},$De({})},has(s){return!!hC[s]},all(){return Object.values(hC)}};function Pqt(){const s=k.useSyncExternalStore(wE.subscribe,wE.getSnapshot,wE.getSnapshot);return{selected:Object.values(s),selectedIds:new Set(Object.keys(s)),count:Object.keys(s).length,has:t=>!!s[t],toggle:wE.toggle,remove:wE.remove,clear:wE.clear}}const VPn=new Set(["office_exclusive","coming_soon","pre_market"]);function HPn(s){const t=(s.photos??[]).slice().sort((i,l)=>(l.is_primary?1:0)-(i.is_primary?1:0)||(i.sort_order??0)-(l.sort_order??0)).map(i=>i.photo_url).filter(Boolean),n=s.status||"active",r=VPn.has(n);return{mlsNumber:`lx-${s.id}`,address:s.property_address||`${s.city??""}, ${s.state??""}`.trim(),city:s.city||"",state:s.state||"",zip:s.zip_code||s.zip||"",price:Number(s.price)||0,bedrooms:Number(s.bedrooms)||0,bathrooms:Number(s.bathrooms)||0,sqft:Number(s.square_footage)||0,lotSize:s.lot_size?String(s.lot_size):"",yearBuilt:s.year_built??null,propertyType:s.property_type||"",propertySubType:null,description:s.description||"",photos:t,status:n,listDate:s.created_at||new Date().toISOString(),soldDate:null,soldPrice:null,latitude:s.latitude??null,longitude:s.longitude??null,garageSpaces:null,stories:null,hoaFee:null,hoaFrequency:null,taxAmount:null,taxYear:null,heating:null,cooling:null,basement:null,pool:null,fireplace:null,virtualTourUrl:s.virtual_tour_url??null,features:[],appliances:[],flooring:[],parking:null,waterSource:null,sewer:null,externalUrl:r?null:`https://listings.relevelup.com/${s.slug||s.id}`,is_private:r}}function Wae(s){const{has:t}=Pqt(),n=`lx-${s.listing.id}`,r=t(n);return e.jsxs("div",{className:"relative",children:[e.jsx(UPn,{...s}),e.jsx("button",{type:"button",onClick:a=>{a.stopPropagation(),wE.toggle(HPn(s.listing))||ae.error(`You can select up to ${X4e} listings`)},title:r?"Remove from email":"Add to email",className:`absolute top-3 right-3 z-10 h-8 w-8 rounded-full flex items-center justify-center shadow-md border transition ${r?"bg-primary text-primary-foreground border-primary":"bg-white/95 text-foreground border-white hover:bg-white"}`,children:r?e.jsx(ma,{className:"h-4 w-4"}):e.jsx(pn,{className:"h-4 w-4"})})]})}function GPn({open:s,onOpenChange:t,listings:n}){const{user:r}=ks(),{leadSite:a}=Tg(),[i,l]=k.useState("grid"),[o,c]=k.useState(""),[d,u]=k.useState(""),[h,m]=k.useState(""),[p,g]=k.useState(new Set),[x,y]=k.useState(!1),[v,_]=k.useState(!1),{data:j}=ZEe(),[C,A]=k.useState(!1);k.useEffect(()=>{!s||!(r!=null&&r.id)||V.from("gmail_integrations").select("gmail_email").eq("user_id",r.id).maybeSingle().then(({data:Y})=>_(!!(Y!=null&&Y.gmail_email)))},[s,r==null?void 0:r.id]),k.useEffect(()=>{if(s){if(!o){const Y=Array.from(new Set(n.map(ee=>ee.city).filter(Boolean))),se=Y.length===1?` in ${Y[0]}`:"";c(n.length===1?`New listing for you${se}`:`${n.length} hand-picked listings${se}`)}d||u(`Hi {{first_name}}, Thought of you — I just picked a few properties I think you'll love. Take a look and let me know if anything catches your eye. Happy to set up a private showing whenever works.`)}},[s]);const{data:M=[],isLoading:I}=pt({queryKey:["send-listings-contacts",r==null?void 0:r.id],queryFn:async()=>{const{data:Y}=await V.from("innercircle_contacts").select("id, first_name, last_name, email, city").eq("owner_user_id",r.id).not("email","is",null).neq("email","").order("first_name");return Y||[]},enabled:!!(r!=null&&r.id)&&s}),{data:P}=pt({queryKey:["send-listings-suggestions",n.map(Y=>Y.mlsNumber).join(",")],queryFn:async()=>{const{data:Y,error:se}=await V.functions.invoke("listing-email-suggestions",{body:{listings:n.map(ee=>({mlsNumber:ee.mlsNumber,city:ee.city,state:ee.state,price:ee.price,bedrooms:ee.bedrooms,bathrooms:ee.bathrooms}))}});if(se)throw se;return Y},enabled:s&&n.length>0}),R=(P==null?void 0:P.suggestions)||[],O=k.useMemo(()=>{const Y=h.trim().toLowerCase();return Y?M.filter(se=>`${se.first_name??""} ${se.last_name??""} ${se.email} ${se.city??""}`.toLowerCase().includes(Y)):M},[M,h]),B=Y=>{g(se=>{const ee=new Set(se);return ee.has(Y)?ee.delete(Y):ee.add(Y),ee})},U=()=>{g(Y=>{const se=new Set(Y);return R.forEach(ee=>se.add(ee.contact_id)),se})},G=n.length>0&&n.every(Y=>Y.mlsNumber.startsWith("lx-")),H=async()=>{if(!G&&!(a!=null&&a.id)){ae.error("You need an active lead site to send listings.");return}if(!o.trim())return ae.error("Subject is required");if(p.size===0)return ae.error("Pick at least one recipient");if(!v&&j&&!j.hasVerifiedSes){A(!0);return}const Y=M.filter(se=>p.has(se.id)).map(se=>({contact_id:se.id,email:se.email,first_name:se.first_name,last_name:se.last_name}));y(!0);try{const{data:se,error:ee}=await V.functions.invoke("listing-email-send",{body:{lead_site_id:(a==null?void 0:a.id)||null,layout:i,subject:o.trim(),intro_message:d.trim()||null,listings:n.map(oe=>({mlsNumber:oe.mlsNumber,address:oe.address,city:oe.city,state:oe.state,zip:oe.zip,price:oe.price,bedrooms:oe.bedrooms,bathrooms:oe.bathrooms,sqft:oe.sqft,status:oe.status,photos:(oe.photos||[]).slice(0,1),description:oe.description||"",external_url:oe.externalUrl||null,is_private:oe.is_private===!0})),recipients:Y}});if(ee)throw ee;if(!(se!=null&&se.success))throw new Error((se==null?void 0:se.error)||"Send failed");ae.success(`Sent ${se.sent}/${Y.length} via ${v?"Gmail":"Amazon SES"}${se.failed?` · ${se.failed} failed`:""}`),wE.clear(),g(new Set),t(!1)}catch(se){ae.error((se==null?void 0:se.message)||"Failed to send")}finally{y(!1)}};return e.jsxs(zs,{open:s,onOpenChange:t,children:[e.jsxs(Rs,{className:"max-w-5xl max-h-[92vh] overflow-hidden p-0 flex flex-col",children:[e.jsxs(Vs,{className:"px-6 pt-6 pb-2",children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(pn,{className:"h-5 w-5 text-primary"}),"Email ",n.length," ",n.length===1?"Listing":"Listings"]}),e.jsx(Cr,{children:G?"Send your Listing Exchange properties. Recipients land on listings.relevelup.com and clicks track back to the contact.":"Drive traffic to your site. Recipients land on your lead site and clicks show up on Mission Control."})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-0 flex-1 overflow-hidden",children:[e.jsxs("div",{className:"overflow-y-auto px-6 pb-4 space-y-4 border-r",children:[e.jsxs("div",{children:[e.jsx(re,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Selected listings"}),e.jsx("div",{className:"mt-2 flex gap-2 overflow-x-auto pb-1",children:n.map(Y=>{var se;return e.jsxs("div",{className:"shrink-0 w-32 rounded-lg overflow-hidden border bg-muted",children:[e.jsx("div",{className:"h-20 w-full bg-muted",children:((se=Y.photos)==null?void 0:se[0])&&e.jsx("img",{src:Y.photos[0],alt:"",className:"h-full w-full object-cover"})}),e.jsxs("div",{className:"p-1.5",children:[e.jsxs("div",{className:"text-[11px] font-semibold truncate",children:["$",(Y.price/1e3).toFixed(0),"k"]}),e.jsxs("div",{className:"text-[10px] text-muted-foreground truncate",children:[Y.city,", ",Y.state]})]})]},Y.mlsNumber)})})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Layout"}),e.jsxs("div",{className:"grid grid-cols-2 gap-2 mt-2",children:[e.jsxs("button",{type:"button",onClick:()=>l("grid"),className:`rounded-lg border p-3 text-left transition ${i==="grid"?"border-primary bg-primary/5":"hover:bg-muted/50"}`,children:[e.jsx(y0,{className:"h-4 w-4 mb-1.5"}),e.jsx("div",{className:"text-sm font-medium",children:"Magazine grid"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Clean card stack"})]}),e.jsxs("button",{type:"button",onClick:()=>l("hero"),className:`rounded-lg border p-3 text-left transition ${i==="hero"?"border-primary bg-primary/5":"hover:bg-muted/50"}`,children:[e.jsx(zc,{className:"h-4 w-4 mb-1.5"}),e.jsx("div",{className:"text-sm font-medium",children:"Hero + list"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"First listing gets spotlight"})]})]})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"subject",children:"Subject"}),e.jsx(be,{id:"subject",value:o,onChange:Y=>c(Y.target.value),placeholder:"Subject line",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"intro",children:"Personal message"}),e.jsx(Ls,{id:"intro",value:d,onChange:Y=>u(Y.target.value),placeholder:"Optional intro shown above the listings…",className:"mt-1 min-h-[120px]"}),e.jsxs("p",{className:"text-[11px] text-muted-foreground mt-1",children:["Use ",e.jsx("code",{className:"px-1 rounded bg-muted",children:"{{first_name}}"})," to personalize."]})]}),e.jsxs("div",{className:"rounded-lg border bg-muted/40 p-3 text-xs text-muted-foreground",children:["Sending via"," ",e.jsx("span",{className:"font-medium text-foreground",children:v?"your connected Gmail":"Amazon SES"}),". Every click tracks back to the contact and triggers a buyer signal."]})]}),e.jsxs("div",{className:"flex flex-col overflow-hidden",children:[e.jsxs("div",{className:"px-6 pt-4 pb-2 space-y-3",children:[R.length>0&&e.jsxs(we,{className:"p-3 bg-amber-50/50 border-amber-200",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(kn,{className:"h-4 w-4 text-amber-600"}),e.jsxs("div",{className:"text-sm font-medium",children:[R.length," smart ",R.length===1?"match":"matches"]})]}),e.jsx($,{size:"sm",variant:"outline",onClick:U,children:"Add all"})]}),e.jsx(Eo,{className:"max-h-32 mt-2",children:e.jsx("div",{className:"space-y-1",children:R.slice(0,12).map(Y=>{const se=p.has(Y.contact_id);return e.jsxs("label",{className:"flex items-start gap-2 text-xs py-1 cursor-pointer",children:[e.jsx(Li,{checked:se,onCheckedChange:()=>B(Y.contact_id),className:"mt-0.5"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"font-medium truncate",children:[Y.first_name," ",Y.last_name??""," ",e.jsxs("span",{className:"text-muted-foreground font-normal",children:["· ",Y.email]})]}),e.jsx("div",{className:"text-muted-foreground truncate",children:Y.reason})]})]},Y.contact_id)})})})]}),e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs(re,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:["All contacts (",O.length,")"]}),p.size>0&&e.jsxs(qe,{variant:"secondary",children:[p.size," selected"]})]}),e.jsx(be,{placeholder:"Search contacts…",value:h,onChange:Y=>m(Y.target.value)})]}),e.jsx("div",{className:"flex-1 overflow-hidden px-6 pb-2",children:e.jsx("div",{className:"border rounded-md h-full",children:e.jsx(Eo,{className:"h-full",children:I?e.jsx("div",{className:"p-4 text-sm text-muted-foreground",children:"Loading…"}):O.length===0?e.jsx("div",{className:"p-4 text-sm text-muted-foreground text-center",children:"No contacts found"}):e.jsx("div",{className:"divide-y",children:O.map(Y=>{const se=p.has(Y.id);return e.jsxs("label",{className:"flex items-center gap-2 px-3 py-2 cursor-pointer hover:bg-muted/40",children:[e.jsx(Li,{checked:se,onCheckedChange:()=>B(Y.id)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"text-sm font-medium truncate",children:[Y.first_name," ",Y.last_name??""]}),e.jsxs("div",{className:"text-xs text-muted-foreground truncate",children:[Y.email,Y.city&&e.jsxs(e.Fragment,{children:[" · ",Y.city]})]})]})]},Y.id)})})})})}),e.jsxs("div",{className:"px-6 py-2 text-xs text-muted-foreground border-t flex items-center justify-between",children:[e.jsxs("span",{children:[e.jsx("strong",{className:"text-foreground",children:p.size})," recipients"]}),p.size>0&&e.jsxs($,{variant:"ghost",size:"sm",className:"h-7 text-xs",onClick:()=>g(new Set),children:[e.jsx(mr,{className:"h-3 w-3 mr-1"}),"Clear"]})]})]})]}),e.jsxs(kr,{className:"px-6 py-4 border-t bg-muted/30",children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),disabled:x,children:"Cancel"}),e.jsx($,{onClick:H,disabled:x||p.size===0,children:x?e.jsxs(e.Fragment,{children:[e.jsx(Jt,{className:"h-4 w-4 mr-2 animate-spin"}),"Sending…"]}):e.jsxs(e.Fragment,{children:[e.jsx(Wr,{className:"h-4 w-4 mr-2"}),"Send to ",p.size," ",p.size===1?"contact":"contacts"]})})]})]}),e.jsx(XEe,{open:C,onOpenChange:A,hasPending:!!(j!=null&&j.hasPendingSes),pendingEmails:j==null?void 0:j.pendingEmails})]})}function WPn(){const{selected:s,count:t,remove:n,clear:r}=Pqt(),[a,i]=k.useState(!1);return t===0?null:e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed bottom-4 left-1/2 -translate-x-1/2 z-50 w-[min(96vw,820px)]",children:e.jsxs("div",{className:"rounded-2xl border bg-background/95 backdrop-blur shadow-2xl p-3 flex items-center gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2 px-2",children:[e.jsx("div",{className:"h-9 w-9 rounded-full bg-primary/10 text-primary flex items-center justify-center font-semibold",children:t}),e.jsxs("div",{className:"text-sm",children:[e.jsxs("div",{className:"font-medium leading-tight",children:[t," listing",t===1?"":"s"," selected"]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:t>=X4e?"Max reached":`Pick up to ${X4e}`})]})]}),e.jsx("div",{className:"flex-1 overflow-x-auto hidden sm:block",children:e.jsxs("div",{className:"flex items-center gap-2",children:[s.slice(0,6).map(l=>{var o;return e.jsxs("div",{className:"group relative shrink-0 h-12 w-16 rounded-md overflow-hidden border bg-muted",title:l.address,children:[(o=l.photos)!=null&&o[0]?e.jsx("img",{src:l.photos[0],alt:"",className:"h-full w-full object-cover"}):e.jsx("div",{className:"h-full w-full"}),e.jsx("button",{"aria-label":"Remove",onClick:()=>n(l.mlsNumber),className:"absolute inset-0 bg-black/50 opacity-0 group-hover:opacity-100 flex items-center justify-center transition",children:e.jsx(mr,{className:"h-4 w-4 text-white"})})]},l.mlsNumber)}),t>6&&e.jsxs("div",{className:"shrink-0 h-12 w-12 rounded-md border bg-muted flex items-center justify-center text-xs font-medium text-muted-foreground",children:["+",t-6]})]})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs($,{variant:"ghost",size:"sm",onClick:r,className:"gap-1.5",children:[e.jsx(Un,{className:"h-4 w-4"})," Clear"]}),e.jsxs($,{size:"sm",className:"gap-1.5",onClick:()=>i(!0),children:[e.jsx(Wr,{className:"h-4 w-4"}),"Email these ",t===1?"listing":"listings"]})]})]})}),e.jsx(GPn,{open:a,onOpenChange:i,listings:s})]})}const KPn=[{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"}],YPn=[{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 ZPn({filters:s,onFiltersChange:t,onClose:n}){const r=()=>{t({sortBy:"newest"})};return e.jsxs(we,{children:[e.jsxs(Vt,{className:"flex flex-row items-center justify-between pb-3",children:[e.jsx(Yt,{className:"text-lg",children:"Filters"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx($,{variant:"ghost",size:"sm",onClick:r,children:"Clear All"}),e.jsx($,{variant:"ghost",size:"icon",onClick:n,children:e.jsx(mr,{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(re,{children:"Status"}),e.jsxs(bs,{value:s.status||"all",onValueChange:a=>t({...s,status:a==="all"?void 0:a}),children:[e.jsx(ys,{children:e.jsx(_s,{placeholder:"All statuses"})}),e.jsxs(vs,{children:[e.jsx(We,{value:"all",children:"All Statuses"}),KPn.map(a=>e.jsx(We,{value:a.value,children:a.label},a.value))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Property Type"}),e.jsxs(bs,{value:s.propertyType||"all",onValueChange:a=>t({...s,propertyType:a==="all"?void 0:a}),children:[e.jsx(ys,{children:e.jsx(_s,{placeholder:"All types"})}),e.jsxs(vs,{children:[e.jsx(We,{value:"all",children:"All Types"}),YPn.map(a=>e.jsx(We,{value:a.value,children:a.label},a.value))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Min Price"}),e.jsx(be,{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(re,{children:"Max Price"}),e.jsx(be,{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(re,{children:"Open to Referrals Only"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Show only listings accepting buyer referrals"})]}),e.jsx(On,{checked:s.openToReferrals||!1,onCheckedChange:a=>t({...s,openToReferrals:a||void 0})})]})]})]})}function XPn({leaderboard:s}){const t=r=>{switch(r){case 0:return e.jsx(ql,{className:"h-5 w-5 text-amber-500"});case 1:return e.jsx(y3,{className:"h-5 w-5 text-gray-400"});case 2:return e.jsx(oh,{className:"h-5 w-5 text-amber-700"});default:return e.jsx("span",{className:"text-sm font-medium text-muted-foreground w-5 text-center",children:r+1})}},n=(r,a)=>!r||r.length===0?e.jsx("div",{className:"py-8 text-center text-muted-foreground",children:"No data yet. Start sharing to climb the leaderboard!"}):e.jsx("div",{className:"space-y-2",children:r.map((i,l)=>e.jsxs("div",{className:`flex items-center gap-4 p-3 rounded-lg ${l===0?"bg-gradient-to-r from-amber-500/10 to-amber-500/5 border border-amber-500/20":"bg-muted/50"}`,children:[e.jsx("div",{className:"flex items-center justify-center w-8",children:t(l)}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsx("p",{className:"font-medium truncate",children:i.name})}),e.jsxs(qe,{variant:l===0?"default":"secondary",children:[i.count," ",a]})]},i.agentId))});return e.jsxs("div",{className:"space-y-6",children:[e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsxs(Yt,{className:"flex items-center gap-2",children:[e.jsx(ql,{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(ou,{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(ua,{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(y3,{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(ql,{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(we,{children:[e.jsx(Vt,{children:e.jsx(Yt,{children:"Community Leaderboard"})}),e.jsx(De,{children:e.jsxs(ya,{defaultValue:"sharers",children:[e.jsxs(va,{className:"w-full",children:[e.jsxs(is,{value:"sharers",className:"flex-1",children:[e.jsx(ou,{className:"h-4 w-4 mr-2"}),"Top Sharers"]}),e.jsxs(is,{value:"listers",className:"flex-1",children:[e.jsx(ua,{className:"h-4 w-4 mr-2"}),"Top Contributors"]})]}),e.jsx(cs,{value:"sharers",className:"mt-4",children:n(s==null?void 0:s.topSharers,"shares")}),e.jsx(cs,{value:"listers",className:"mt-4",children:n(s==null?void 0:s.topListers,"listings")})]})})]})]})}const z1t={coming_soon:"#F59E0B",office_exclusive:"#6366F1",pre_market:"#06B6D4",active:"#10B981",price_improvement:"#8B5CF6",under_contract:"#3B82F6",sold:"#A855F7"},B1t={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 QPn(s){return s>=1e6?`$${(s/1e6).toFixed(1)}M`:`$${(s/1e3).toFixed(0)}K`}function JPn({listings:s,isLoading:t}){const n=Jn(),r=k.useRef(null),a=k.useRef(null),i=k.useRef([]),{isAdmin:l}=ks(),[o,c]=k.useState(""),[d,u]=k.useState(!0),[h,m]=k.useState(!1),p=s.filter(x=>x.latitude!=null&&x.longitude!=null),g=s.filter(x=>(x.latitude==null||x.longitude==null)&&(x.property_address||x.city));return k.useEffect(()=>{(async()=>{u(!0);try{const{data:y}=await V.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle();y!=null&&y.value&&c(y.value)}catch(y){console.error("Error fetching mapbox token:",y)}u(!1)})()},[]),k.useEffect(()=>{if(!o||g.length===0||h)return;(async()=>{var y;m(!0);for(const v of g){const _=[v.property_address,v.city,v.state].filter(Boolean).join(", ");if(_)try{const C=await(await fetch(`https://api.mapbox.com/geocoding/v5/mapbox.places/${encodeURIComponent(_)}.json?access_token=${o}&limit=1`)).json();if((y=C.features)!=null&&y[0]){const[A,M]=C.features[0].center;await V.from("listings").update({latitude:M,longitude:A}).eq("id",v.id),v.latitude=M,v.longitude=A}}catch(j){console.error("Geocode error:",j)}}m(!1)})()},[o,s]),k.useEffect(()=>{if(!r.current||!o||a.current)return;Td.accessToken=o;const x=s.filter(_=>_.latitude!=null&&_.longitude!=null);let y=[-98.5795,39.8283],v=4;if(x.length>0){const _=x.reduce((C,A)=>C+A.longitude,0)/x.length,j=x.reduce((C,A)=>C+A.latitude,0)/x.length;y=[_,j],v=x.length===1?12:10}return a.current=new Td.Map({container:r.current,style:"mapbox://styles/mapbox/light-v11",zoom:v,center:y}),a.current.addControl(new Td.NavigationControl,"top-right"),()=>{var _;(_=a.current)==null||_.remove(),a.current=null}},[o]),k.useEffect(()=>{if(!a.current||!o)return;i.current.forEach(y=>y.remove()),i.current=[];const x=s.filter(y=>y.latitude!=null&&y.longitude!=null);if(x.forEach(y=>{var M,I,P;const v=z1t[y.status]||"#10B981",_=((M=y.photos)==null?void 0:M.find(R=>R.is_primary))||((I=y.photos)==null?void 0:I[0]),j=document.createElement("div");j.className="cursor-pointer",j.innerHTML=`
`;const C=new Td.Popup({offset:25,closeButton:!0,maxWidth:"280px"}).setHTML(`
${_!=null&&_.photo_url?``:""}
${QPn(y.price)}
${y.property_address||""}
${y.city}, ${y.state}
${B1t[y.status]||y.status} ${y.bedrooms?`${y.bedrooms} bed`:""} ${y.bathrooms?`${y.bathrooms} bath`:""}
${(P=y.agent)!=null&&P.name?`
Listed by ${y.agent.name}
`:""}
Click to view details →
`),A=new Td.Marker(j).setLngLat([y.longitude,y.latitude]).setPopup(C).addTo(a.current);i.current.push(A)}),x.length>1){const y=new Td.LngLatBounds;x.forEach(v=>y.extend([v.longitude,v.latitude])),a.current.fitBounds(y,{padding:60,maxZoom:13})}else x.length===1&&a.current.flyTo({center:[x[0].longitude,x[0].latitude],zoom:12})},[s,o,h]),k.useEffect(()=>(window.__navigateToListing__=x=>{n(`/mission-control/listings/${x}`)},()=>{delete window.__navigateToListing__}),[n]),d||t?e.jsx(we,{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(we,{children:e.jsxs(De,{className:"flex flex-col items-center justify-center h-[60vh] text-center gap-3",children:[e.jsx(Si,{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(z1t).map(([x,y])=>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:y}}),e.jsx("span",{className:"text-xs",children:B1t[x]})]},x)),e.jsxs("span",{className:"text-muted-foreground ml-auto text-xs",children:[p.length," of ",s.length," mapped",h&&" · Geocoding..."]})]}),e.jsx("div",{ref:r,className:"w-full h-[60vh] rounded-lg shadow-lg border"})]}):e.jsx(we,{children:e.jsxs(De,{className:"flex flex-col items-center justify-center h-[60vh] text-center gap-3",children:[e.jsx(Ho,{className:"h-12 w-12 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold",children:"Map Not Configured"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:l?"Set up your Mapbox token in Settings to enable maps.":"The map feature has not been configured yet. Please contact your administrator."})]})]})})}const KUe="homereel_mv_prefill",YUe="homereel_mv_badge_default";function Iqt(s){try{sessionStorage.setItem(KUe,JSON.stringify(s)),s.badge&&s.badge.type!=="none"&&sessionStorage.setItem(YUe,JSON.stringify(s.badge))}catch{}}function kJn(){try{const s=sessionStorage.getItem(KUe);return s?(sessionStorage.removeItem(KUe),JSON.parse(s)):null}catch{return null}}function SJn(){try{const s=sessionStorage.getItem(YUe);return s?(sessionStorage.removeItem(YUe),JSON.parse(s)):null}catch{return null}}function Lqt(s,t){switch(s){case"coming_soon":case"pre_market":return{type:"coming_soon"};case"price_improvement":return{type:"price_improvement",newPrice:t?String(t):""};case"active":return{type:"just_listed"};default:return{type:"none"}}}function eIn(){var R,O,B,U,G,H,Y,se;const s=Jn(),{brokerageId:t}=ks(),{data:n,isLoading:r}=DMt(),[a,i]=k.useState("feed"),[l,o]=k.useState(!1),[c,d]=k.useState(""),[u,h]=k.useState({sortBy:"newest"}),{data:m,isLoading:p}=OMt({...u,city:c||u.city}),{data:g,isLoading:x}=fEs(),{data:y,isLoading:v}=FMt(),{data:_,isLoading:j}=yEs(),{data:C,isLoading:A}=_Es(),{data:M}=bEs(),I=zMt(),P=async ee=>{if(await io("Are you sure you want to delete this listing? This action cannot be undone."))try{await I.mutateAsync(ee),ae.success("Listing deleted successfully")}catch{ae.error("Failed to delete listing")}};return r?e.jsx(Xs,{title:"Listing Exchange",description:"Community-powered listing collaboration",children:e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"animate-spin h-8 w-8 border-4 border-primary border-t-transparent rounded-full"})})}):n?e.jsxs(Xs,{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($,{onClick:()=>s("/mission-control/listings/new"),children:[e.jsx(nn,{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(we,{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(ua,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:(m==null?void 0:m.length)||0}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Active Listings"})]})]})}),e.jsx(we,{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(Bo,{className:"h-5 w-5 text-pink-500"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:(g==null?void 0:g.length)||0}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Saved"})]})]})}),e.jsx(we,{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(I8,{className:"h-5 w-5 text-emerald-500"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:(y==null?void 0:y.length)||0}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"My Listings"})]})]})}),e.jsx(we,{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(Xn,{className:"h-5 w-5 text-sky-500"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:(((R=_==null?void 0:_.sent)==null?void 0:R.length)||0)+(((O=_==null?void 0:_.received)==null?void 0:O.length)||0)}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Referrals"})]})]})})]}),e.jsxs(ya,{value:a,onValueChange:i,children:[e.jsxs(va,{className:"w-full justify-start overflow-x-auto",children:[e.jsx(is,{value:"feed",children:"Community Feed"}),t&&e.jsx(is,{value:"brokerage",children:"Brokerage"}),e.jsx(is,{value:"my-listings",children:"My Listings"}),e.jsx(is,{value:"saved",children:"Saved"}),e.jsx(is,{value:"referrals",children:"Referrals"}),e.jsx(is,{value:"map",children:"Map"}),e.jsx(is,{value:"leaderboard",children:"Leaderboard"})]}),e.jsxs(cs,{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(Yr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search by city or neighborhood...",value:c,onChange:ee=>d(ee.target.value),className:"pl-9"})]}),e.jsxs(bs,{value:u.sortBy,onValueChange:ee=>h({...u,sortBy:ee}),children:[e.jsx(ys,{className:"w-[180px]",children:e.jsx(_s,{placeholder:"Sort by"})}),e.jsxs(vs,{children:[e.jsx(We,{value:"newest",children:"Newest First"}),e.jsx(We,{value:"updated",children:"Recently Updated"}),e.jsx(We,{value:"price_asc",children:"Price: Low to High"}),e.jsx(We,{value:"price_desc",children:"Price: High to Low"})]})]}),e.jsxs($,{variant:"outline",onClick:()=>o(!l),children:[e.jsx(v2,{className:"h-4 w-4 mr-2"}),"Filters"]})]}),l&&e.jsx(ZPn,{filters:u,onFiltersChange:h,onClose:()=>o(!1)}),p?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:[...Array(6)].map((ee,oe)=>e.jsxs(we,{children:[e.jsx(fn,{className:"h-48 w-full"}),e.jsxs(De,{className:"p-4 space-y-2",children:[e.jsx(fn,{className:"h-5 w-3/4"}),e.jsx(fn,{className:"h-4 w-1/2"}),e.jsx(fn,{className:"h-4 w-1/4"})]})]},oe))}):(m==null?void 0:m.length)===0?e.jsx(we,{children:e.jsxs(De,{className:"py-12 text-center",children:[e.jsx(ua,{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($,{onClick:()=>s("/mission-control/listings/new"),children:[e.jsx(nn,{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:m==null?void 0:m.map(ee=>e.jsx(Wae,{listing:ee,onClick:()=>s(`/mission-control/listings/${ee.id}`)},ee.id))})]}),e.jsx(cs,{value:"my-listings",className:"space-y-4",children:v?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:[...Array(3)].map((ee,oe)=>e.jsxs(we,{children:[e.jsx(fn,{className:"h-48 w-full"}),e.jsxs(De,{className:"p-4 space-y-2",children:[e.jsx(fn,{className:"h-5 w-3/4"}),e.jsx(fn,{className:"h-4 w-1/2"})]})]},oe))}):(y==null?void 0:y.length)===0?e.jsx(we,{children:e.jsxs(De,{className:"py-12 text-center",children:[e.jsx(I8,{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($,{onClick:()=>s("/mission-control/listings/new"),children:[e.jsx(nn,{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:y==null?void 0:y.map(ee=>e.jsx(Wae,{listing:ee,showActions:!0,onClick:()=>s(`/mission-control/listings/${ee.id}`),onEdit:()=>s(`/mission-control/listings/${ee.id}/edit`),onDelete:()=>P(ee.id),onCreateMusicVideo:()=>{const oe=(ee.photos??[]).slice().sort((me,Q)=>(Q.is_primary?1:0)-(me.is_primary?1:0)||(me.sort_order??0)-(Q.sort_order??0)).map(me=>me.photo_url).filter(Boolean);if(oe.length===0){ae.error("Add photos to this listing first.");return}Iqt({photos:oe,details:{address:ee.property_address||`${ee.city??""} ${ee.state??""}`.trim(),beds:ee.bedrooms?String(ee.bedrooms):"",baths:ee.bathrooms?String(ee.bathrooms):"",sqft:ee.square_footage?String(ee.square_footage):"",price:ee.price?String(ee.price):"",highlights:ee.description||""},sourceLabel:"My Listings",badge:Lqt(ee.status,ee.price)}),s("/admin/beta/homereel?tab=music-video")}},ee.id))})}),e.jsx(cs,{value:"saved",className:"space-y-4",children:x?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:[...Array(3)].map((ee,oe)=>e.jsxs(we,{children:[e.jsx(fn,{className:"h-48 w-full"}),e.jsxs(De,{className:"p-4 space-y-2",children:[e.jsx(fn,{className:"h-5 w-3/4"}),e.jsx(fn,{className:"h-4 w-1/2"})]})]},oe))}):(g==null?void 0:g.length)===0?e.jsx(we,{children:e.jsxs(De,{className:"py-12 text-center",children:[e.jsx(Bo,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-medium mb-2",children:"No saved listings"}),e.jsx("p",{className:"text-muted-foreground",children:"Save listings to quickly access them later"})]})}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:g==null?void 0:g.map(ee=>e.jsx(Wae,{listing:ee.listing,onClick:()=>s(`/mission-control/listings/${ee.listing.id}`)},ee.id))})}),e.jsx(cs,{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(ou,{className:"h-4 w-4"}),"Referrals Sent (",((B=_==null?void 0:_.sent)==null?void 0:B.length)||0,")"]}),((U=_==null?void 0:_.sent)==null?void 0:U.length)===0?e.jsx(we,{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:(G=_==null?void 0:_.sent)==null?void 0:G.map(ee=>{var oe,me;return e.jsx(we,{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:ee.buyer_name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:((oe=ee.listing)==null?void 0:oe.property_address)||((me=ee.listing)==null?void 0:me.city)})]}),e.jsx(qe,{variant:ee.status==="closed"?"default":"secondary",children:ee.status.replace("_"," ")})]})})},ee.id)})})]}),e.jsxs("div",{children:[e.jsxs("h3",{className:"font-semibold mb-3 flex items-center gap-2",children:[e.jsx(Xn,{className:"h-4 w-4"}),"Referrals Received (",((H=_==null?void 0:_.received)==null?void 0:H.length)||0,")"]}),((Y=_==null?void 0:_.received)==null?void 0:Y.length)===0?e.jsx(we,{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:(se=_==null?void 0:_.received)==null?void 0:se.map(ee=>{var oe;return e.jsx(we,{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:ee.buyer_name}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["From: ",(oe=ee.sender)==null?void 0:oe.name]})]}),e.jsx(qe,{variant:ee.status==="closed"?"default":"secondary",children:ee.status.replace("_"," ")})]}),e.jsx($,{size:"sm",variant:"outline",className:"w-full mt-2",onClick:()=>s(`/mission-control/listings/${ee.listing_id}`),children:"View Listing"})]})},ee.id)})})]})]})}),t&&e.jsx(cs,{value:"brokerage",className:"space-y-4",children:A?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:[...Array(3)].map((ee,oe)=>e.jsxs(we,{children:[e.jsx(fn,{className:"h-48 w-full"}),e.jsxs(De,{className:"p-4 space-y-2",children:[e.jsx(fn,{className:"h-5 w-3/4"}),e.jsx(fn,{className:"h-4 w-1/2"})]})]},oe))}):(C==null?void 0:C.length)===0?e.jsx(we,{children:e.jsxs(De,{className:"py-12 text-center",children:[e.jsx(I8,{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($,{onClick:()=>s("/mission-control/listings/new"),children:[e.jsx(nn,{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:C==null?void 0:C.map(ee=>e.jsx(Wae,{listing:ee,onClick:()=>s(`/mission-control/listings/${ee.id}`)},ee.id))})}),e.jsx(cs,{value:"map",children:e.jsx(JPn,{listings:m||[],isLoading:p})}),e.jsx(cs,{value:"leaderboard",children:e.jsx(XPn,{leaderboard:M})})]})]}),e.jsx(WPn,{})]}):e.jsx(Xs,{title:"Listing Exchange",description:"Community-powered listing collaboration",children:e.jsx(we,{children:e.jsxs(De,{className:"py-12 text-center",children:[e.jsx(ua,{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 Rqt(s){return pt({queryKey:["listing-documents",s],queryFn:async()=>{const{data:t,error:n}=await V.from("listing_documents").select("*").eq("listing_id",s).order("sort_order",{ascending:!0}).order("created_at",{ascending:!0});if(n)throw n;return t},enabled:!!s})}function tIn(){const{user:s}=ks(),t=ls();return Nt({mutationFn:async({listingId:n,file:r})=>{if(!(s!=null&&s.id))throw new Error("Not authenticated");const a=r.name.split(".").pop(),i=`${s.id}/${n}/${crypto.randomUUID()}.${a}`,{error:l}=await V.storage.from("listing-documents").upload(i,r,{contentType:r.type||void 0});if(l)throw l;const{data:o,error:c}=await V.from("listing_documents").insert({listing_id:n,owner_user_id:s.id,file_name:r.name,file_size:r.size,file_type:r.type||null,storage_path:i}).select().single();if(c)throw c;return o},onSuccess:(n,r)=>{t.invalidateQueries({queryKey:["listing-documents",r.listingId]})}})}function sIn(){const s=ls();return Nt({mutationFn:async({id:t,storage_path:n,listingId:r})=>{await V.storage.from("listing-documents").remove([n]);const{error:a}=await V.from("listing_documents").delete().eq("id",t);if(a)throw a;return r},onSuccess:t=>{s.invalidateQueries({queryKey:["listing-documents",t]})}})}function nIn(){const s=ls();return Nt({mutationFn:async({id:t,visible:n,listingId:r})=>{const{error:a}=await V.from("listing_documents").update({visible_on_exchange:n}).eq("id",t);if(a)throw a;return r},onSuccess:t=>{s.invalidateQueries({queryKey:["listing-documents",t]})}})}async function Dqt(s){const{data:t,error:n}=await V.storage.from("listing-documents").createSignedUrl(s,3600);if(n)throw n;return t.signedUrl}const rIn=s=>s<1024?`${s} B`:s<1024*1024?`${(s/1024).toFixed(0)} KB`:`${(s/(1024*1024)).toFixed(1)} MB`;function aIn({listingId:s,ownerOnly:t=!1}){const{data:n=[]}=Rqt(s),r=t?n:n.filter(i=>i.visible_on_exchange);if(r.length===0)return null;const a=async i=>{try{const l=await Dqt(i);window.open(l,"_blank")}catch{ae.error("Failed to open document")}};return e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsxs(Yt,{className:"text-lg flex items-center gap-2",children:[e.jsx(ea,{className:"h-5 w-5"}),"Documents & Disclosures (",r.length,")"]})}),e.jsx(De,{children:e.jsx("div",{className:"space-y-2",children:r.map(i=>e.jsxs("button",{onClick:()=>a(i.storage_path),className:"w-full flex items-center gap-3 p-3 rounded-lg border hover:bg-muted transition-colors text-left group",children:[e.jsx("div",{className:"p-2 rounded-md bg-primary/10 flex-shrink-0",children:e.jsx(ea,{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:rIn(i.file_size)})]}),e.jsx(ji,{className:"h-4 w-4 text-muted-foreground group-hover:text-primary"})]},i.id))})})]})}var iIn=Object.defineProperty,J4e=Object.getOwnPropertySymbols,Oqt=Object.prototype.hasOwnProperty,Fqt=Object.prototype.propertyIsEnumerable,$1t=(s,t,n)=>t in s?iIn(s,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):s[t]=n,ZUe=(s,t)=>{for(var n in t||(t={}))Oqt.call(t,n)&&$1t(s,n,t[n]);if(J4e)for(var n of J4e(t))Fqt.call(t,n)&&$1t(s,n,t[n]);return s},XUe=(s,t)=>{var n={};for(var r in s)Oqt.call(s,r)&&t.indexOf(r)<0&&(n[r]=s[r]);if(s!=null&&J4e)for(var r of J4e(s))t.indexOf(r)<0&&Fqt.call(s,r)&&(n[r]=s[r]);return n};/** * @license QR Code generator library (TypeScript) * Copyright (c) Project Nayuki. * SPDX-License-Identifier: MIT */var lF;(s=>{const t=class Ed{constructor(c,d,u,h){if(this.version=c,this.errorCorrectionLevel=d,this.modules=[],this.isFunction=[],cEd.MAX_VERSION)throw new RangeError("Version value out of range");if(h<-1||h>7)throw new RangeError("Mask value out of range");this.size=c*4+17;let m=[];for(let g=0;g7)throw new RangeError("Invalid value");let g,x;for(g=u;;g++){const j=Ed.getNumDataCodewords(g,d)*8,C=l.getTotalBits(c,g);if(C<=j){x=C;break}if(g>=h)throw new RangeError("Data too long")}for(const j of[Ed.Ecc.MEDIUM,Ed.Ecc.QUARTILE,Ed.Ecc.HIGH])p&&x<=Ed.getNumDataCodewords(g,j)*8&&(d=j);let y=[];for(const j of c){n(j.mode.modeBits,4,y),n(j.numChars,j.mode.numCharCountBits(g),y);for(const C of j.getData())y.push(C)}a(y.length==x);const v=Ed.getNumDataCodewords(g,d)*8;a(y.length<=v),n(0,Math.min(4,v-y.length),y),n(0,(8-y.length%8)%8,y),a(y.length%8==0);for(let j=236;y.length_[C>>>3]|=j<<7-(C&7)),new Ed(g,d,_,m)}getModule(c,d){return 0<=c&&c>>9)*1335;const h=(d<<10|u)^21522;a(h>>>15==0);for(let m=0;m<=5;m++)this.setFunctionModule(8,m,r(h,m));this.setFunctionModule(8,7,r(h,6)),this.setFunctionModule(8,8,r(h,7)),this.setFunctionModule(7,8,r(h,8));for(let m=9;m<15;m++)this.setFunctionModule(14-m,8,r(h,m));for(let m=0;m<8;m++)this.setFunctionModule(this.size-1-m,8,r(h,m));for(let m=8;m<15;m++)this.setFunctionModule(8,this.size-15+m,r(h,m));this.setFunctionModule(8,this.size-8,!0)}drawVersion(){if(this.version<7)return;let c=this.version;for(let u=0;u<12;u++)c=c<<1^(c>>>11)*7973;const d=this.version<<12|c;a(d>>>18==0);for(let u=0;u<18;u++){const h=r(d,u),m=this.size-11+u%3,p=Math.floor(u/3);this.setFunctionModule(m,p,h),this.setFunctionModule(p,m,h)}}drawFinderPattern(c,d){for(let u=-4;u<=4;u++)for(let h=-4;h<=4;h++){const m=Math.max(Math.abs(h),Math.abs(u)),p=c+h,g=d+u;0<=p&&p{(j!=x-m||A>=g)&&_.push(C[j])});return a(_.length==p),_}drawCodewords(c){if(c.length!=Math.floor(Ed.getNumRawDataModules(this.version)/8))throw new RangeError("Invalid argument");let d=0;for(let u=this.size-1;u>=1;u-=2){u==6&&(u=5);for(let h=0;h>>3],7-(d&7)),d++)}}a(d==c.length*8)}applyMask(c){if(c<0||c>7)throw new RangeError("Mask value out of range");for(let d=0;d5&&c++):(this.finderPenaltyAddHistory(g,x),p||(c+=this.finderPenaltyCountPatterns(x)*Ed.PENALTY_N3),p=this.modules[m][y],g=1);c+=this.finderPenaltyTerminateAndCount(p,g,x)*Ed.PENALTY_N3}for(let m=0;m5&&c++):(this.finderPenaltyAddHistory(g,x),p||(c+=this.finderPenaltyCountPatterns(x)*Ed.PENALTY_N3),p=this.modules[y][m],g=1);c+=this.finderPenaltyTerminateAndCount(p,g,x)*Ed.PENALTY_N3}for(let m=0;mp+(g?1:0),d);const u=this.size*this.size,h=Math.ceil(Math.abs(d*20-u*10)/u)-1;return a(0<=h&&h<=9),c+=h*Ed.PENALTY_N4,a(0<=c&&c<=2568888),c}getAlignmentPatternPositions(){if(this.version==1)return[];{const c=Math.floor(this.version/7)+2,d=this.version==32?26:Math.ceil((this.version*4+4)/(c*2-2))*2;let u=[6];for(let h=this.size-7;u.lengthEd.MAX_VERSION)throw new RangeError("Version number out of range");let d=(16*c+128)*c+64;if(c>=2){const u=Math.floor(c/7)+2;d-=(25*u-10)*u-55,c>=7&&(d-=36)}return a(208<=d&&d<=29648),d}static getNumDataCodewords(c,d){return Math.floor(Ed.getNumRawDataModules(c)/8)-Ed.ECC_CODEWORDS_PER_BLOCK[d.ordinal][c]*Ed.NUM_ERROR_CORRECTION_BLOCKS[d.ordinal][c]}static reedSolomonComputeDivisor(c){if(c<1||c>255)throw new RangeError("Degree out of range");let d=[];for(let h=0;h0);for(const h of c){const m=h^u.shift();u.push(0),d.forEach((p,g)=>u[g]^=Ed.reedSolomonMultiply(p,m))}return u}static reedSolomonMultiply(c,d){if(c>>>8||d>>>8)throw new RangeError("Byte out of range");let u=0;for(let h=7;h>=0;h--)u=u<<1^(u>>>7)*285,u^=(d>>>h&1)*c;return a(u>>>8==0),u}finderPenaltyCountPatterns(c){const d=c[1];a(d<=this.size*3);const u=d>0&&c[2]==d&&c[3]==d*3&&c[4]==d&&c[5]==d;return(u&&c[0]>=d*4&&c[6]>=d?1:0)+(u&&c[6]>=d*4&&c[0]>=d?1:0)}finderPenaltyTerminateAndCount(c,d,u){return c&&(this.finderPenaltyAddHistory(d,u),d=0),d+=this.size,this.finderPenaltyAddHistory(d,u),this.finderPenaltyCountPatterns(u)}finderPenaltyAddHistory(c,d){d[0]==0&&(c+=this.size),d.pop(),d.unshift(c)}};t.MIN_VERSION=1,t.MAX_VERSION=40,t.PENALTY_N1=3,t.PENALTY_N2=3,t.PENALTY_N3=40,t.PENALTY_N4=10,t.ECC_CODEWORDS_PER_BLOCK=[[-1,7,10,15,20,26,18,20,24,30,18,20,24,26,30,22,24,28,30,28,28,28,28,30,30,26,28,30,30,30,30,30,30,30,30,30,30,30,30,30,30],[-1,10,16,26,18,24,16,18,22,22,26,30,22,22,24,24,28,28,26,26,26,26,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28],[-1,13,22,18,26,18,24,18,22,20,24,28,26,24,20,30,24,28,28,26,30,28,30,30,30,30,28,30,30,30,30,30,30,30,30,30,30,30,30,30,30],[-1,17,28,22,16,22,28,26,26,24,28,24,28,22,24,24,30,28,28,26,28,30,24,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30]],t.NUM_ERROR_CORRECTION_BLOCKS=[[-1,1,1,1,1,1,2,2,2,2,4,4,4,4,4,6,6,6,6,7,8,8,9,9,10,12,12,12,13,14,15,16,17,18,19,19,20,21,22,24,25],[-1,1,1,1,2,2,4,4,4,5,5,5,8,9,9,10,10,11,13,14,16,17,17,18,20,21,23,25,26,28,29,31,33,35,37,38,40,43,45,47,49],[-1,1,1,2,2,4,4,6,6,8,8,8,10,12,16,12,17,16,18,21,20,23,23,25,27,29,34,34,35,38,40,43,45,48,51,53,56,59,62,65,68],[-1,1,1,2,4,4,4,5,6,8,8,11,11,16,16,18,16,19,21,25,25,25,34,30,32,35,37,40,42,45,48,51,54,57,60,63,66,70,74,77,81]],s.QrCode=t;function n(o,c,d){if(c<0||c>31||o>>>c)throw new RangeError("Value out of range");for(let u=c-1;u>=0;u--)d.push(o>>>u&1)}function r(o,c){return(o>>>c&1)!=0}function a(o){if(!o)throw new Error("Assertion error")}const i=class cg{constructor(c,d,u){if(this.mode=c,this.numChars=d,this.bitData=u,d<0)throw new RangeError("Invalid argument");this.bitData=u.slice()}static makeBytes(c){let d=[];for(const u of c)n(u,8,d);return new cg(cg.Mode.BYTE,c.length,d)}static makeNumeric(c){if(!cg.isNumeric(c))throw new RangeError("String contains non-numeric characters");let d=[];for(let u=0;u=1<{(t=>{const n=class{constructor(a,i){this.ordinal=a,this.formatBits=i}};n.LOW=new n(0,1),n.MEDIUM=new n(1,0),n.QUARTILE=new n(2,3),n.HIGH=new n(3,2),t.Ecc=n})(s.QrCode||(s.QrCode={}))})(lF||(lF={}));(s=>{(t=>{const n=class{constructor(a,i){this.modeBits=a,this.numBitsCharCount=i}numCharCountBits(a){return this.numBitsCharCount[Math.floor((a+7)/17)]}};n.NUMERIC=new n(1,[10,12,14]),n.ALPHANUMERIC=new n(2,[9,11,13]),n.BYTE=new n(4,[8,16,16]),n.KANJI=new n(8,[8,10,12]),n.ECI=new n(7,[0,0,0]),t.Mode=n})(s.QrSegment||(s.QrSegment={}))})(lF||(lF={}));var Cz=lF;/** * @license qrcode.react * Copyright (c) Paul O'Shannessy * SPDX-License-Identifier: ISC */var oIn={L:Cz.QrCode.Ecc.LOW,M:Cz.QrCode.Ecc.MEDIUM,Q:Cz.QrCode.Ecc.QUARTILE,H:Cz.QrCode.Ecc.HIGH},zqt=128,Bqt="L",$qt="#FFFFFF",Uqt="#000000",qqt=!1,Vqt=1,lIn=4,cIn=0,dIn=.1;function Hqt(s,t=0){const n=[];return s.forEach(function(r,a){let i=null;r.forEach(function(l,o){if(!l&&i!==null){n.push(`M${i+t} ${a+t}h${o-i}v1H${i+t}z`),i=null;return}if(o===r.length-1){if(!l)return;i===null?n.push(`M${o+t},${a+t} h1v1H${o+t}z`):n.push(`M${i+t},${a+t} h${o+1-i}v1H${i+t}z`);return}l&&i===null&&(i=o)})}),n.join("")}function Gqt(s,t){return s.slice().map((n,r)=>r=t.y+t.h?n:n.map((a,i)=>i=t.x+t.w?a:!1))}function uIn(s,t,n,r){if(r==null)return null;const a=s.length+n*2,i=Math.floor(t*dIn),l=a/t,o=(r.width||i)*l,c=(r.height||i)*l,d=r.x==null?s.length/2-o/2:r.x*l,u=r.y==null?s.length/2-c/2:r.y*l,h=r.opacity==null?1:r.opacity;let m=null;if(r.excavate){let g=Math.floor(d),x=Math.floor(u),y=Math.ceil(o+d-g),v=Math.ceil(c+u-x);m={x:g,y:x,w:y,h:v}}const p=r.crossOrigin;return{x:d,y:u,h:c,w:o,excavation:m,opacity:h,crossOrigin:p}}function hIn(s,t){return t!=null?Math.max(Math.floor(t),0):s?lIn:cIn}function Wqt({value:s,level:t,minVersion:n,includeMargin:r,marginSize:a,imageSettings:i,size:l,boostLevel:o}){let c=zt.useMemo(()=>{const g=(Array.isArray(s)?s:[s]).reduce((x,y)=>(x.push(...Cz.QrSegment.makeSegments(y)),x),[]);return Cz.QrCode.encodeSegments(g,oIn[t],n,void 0,void 0,o)},[s,t,n,o]);const{cells:d,margin:u,numCells:h,calculatedImageSettings:m}=zt.useMemo(()=>{let p=c.getModules();const g=hIn(r,a),x=p.length+g*2,y=uIn(p,l,g,i);return{cells:p,margin:g,numCells:x,calculatedImageSettings:y}},[c,l,i,r,a]);return{qrcode:c,margin:u,cells:d,numCells:h,calculatedImageSettings:m}}var mIn=function(){try{new Path2D().addPath(new Path2D)}catch{return!1}return!0}(),fIn=zt.forwardRef(function(t,n){const r=t,{value:a,size:i=zqt,level:l=Bqt,bgColor:o=$qt,fgColor:c=Uqt,includeMargin:d=qqt,minVersion:u=Vqt,boostLevel:h,marginSize:m,imageSettings:p}=r,x=XUe(r,["value","size","level","bgColor","fgColor","includeMargin","minVersion","boostLevel","marginSize","imageSettings"]),{style:y}=x,v=XUe(x,["style"]),_=p==null?void 0:p.src,j=zt.useRef(null),C=zt.useRef(null),A=zt.useCallback(H=>{j.current=H,typeof n=="function"?n(H):n&&(n.current=H)},[n]),[M,I]=zt.useState(!1),{margin:P,cells:R,numCells:O,calculatedImageSettings:B}=Wqt({value:a,level:l,minVersion:u,boostLevel:h,includeMargin:d,marginSize:m,imageSettings:p,size:i});zt.useEffect(()=>{if(j.current!=null){const H=j.current,Y=H.getContext("2d");if(!Y)return;let se=R;const ee=C.current,oe=B!=null&&ee!==null&&ee.complete&&ee.naturalHeight!==0&&ee.naturalWidth!==0;oe&&B.excavation!=null&&(se=Gqt(R,B.excavation));const me=window.devicePixelRatio||1;H.height=H.width=i*me;const Q=i/O*me;Y.scale(Q,Q),Y.fillStyle=o,Y.fillRect(0,0,O,O),Y.fillStyle=c,mIn?Y.fill(new Path2D(Hqt(se,P))):R.forEach(function(te,le){te.forEach(function(fe,_e){fe&&Y.fillRect(_e+P,le+P,1,1)})}),B&&(Y.globalAlpha=B.opacity),oe&&Y.drawImage(ee,B.x+P,B.y+P,B.w,B.h)}}),zt.useEffect(()=>{I(!1)},[_]);const U=ZUe({height:i,width:i},y);let G=null;return _!=null&&(G=zt.createElement("img",{src:_,key:_,style:{display:"none"},onLoad:()=>{I(!0)},ref:C,crossOrigin:B==null?void 0:B.crossOrigin})),zt.createElement(zt.Fragment,null,zt.createElement("canvas",ZUe({style:U,height:i,width:i,ref:A,role:"img"},v)),G)});fIn.displayName="QRCodeCanvas";var jk=zt.forwardRef(function(t,n){const r=t,{value:a,size:i=zqt,level:l=Bqt,bgColor:o=$qt,fgColor:c=Uqt,includeMargin:d=qqt,minVersion:u=Vqt,boostLevel:h,title:m,marginSize:p,imageSettings:g}=r,x=XUe(r,["value","size","level","bgColor","fgColor","includeMargin","minVersion","boostLevel","title","marginSize","imageSettings"]),{margin:y,cells:v,numCells:_,calculatedImageSettings:j}=Wqt({value:a,level:l,minVersion:u,boostLevel:h,includeMargin:d,marginSize:p,imageSettings:g,size:i});let C=v,A=null;g!=null&&j!=null&&(j.excavation!=null&&(C=Gqt(v,j.excavation)),A=zt.createElement("image",{href:g.src,height:j.h,width:j.w,x:j.x+y,y:j.y+y,preserveAspectRatio:"none",opacity:j.opacity,crossOrigin:j.crossOrigin}));const M=Hqt(C,y);return zt.createElement("svg",ZUe({height:i,width:i,viewBox:`0 0 ${_} ${_}`,ref:n,role:"img"},x),!!m&&zt.createElement("title",null,m),zt.createElement("path",{fill:o,d:`M0,0 h${_}v${_}H0z`,shapeRendering:"crispEdges"}),zt.createElement("path",{fill:c,d:M,shapeRendering:"crispEdges"}),A)});jk.displayName="QRCodeSVG";function pIn({open:s,onOpenChange:t,url:n,title:r,fileBase:a}){const i=k.useRef(null),o=`${(h=>h.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")||"listing")(a||r||"listing")}-qr`,c=()=>{var m;const h=(m=i.current)==null?void 0:m.querySelector("svg");return h?new XMLSerializer().serializeToString(h):null},d=()=>{const h=c();if(!h)return;const m=new Blob([h],{type:"image/svg+xml;charset=utf-8"}),p=document.createElement("a");p.href=URL.createObjectURL(m),p.download=`${o}.svg`,p.click(),URL.revokeObjectURL(p.href)},u=(h=1024)=>{const m=c();if(!m)return;const p=new Image,g=new Blob([m],{type:"image/svg+xml;charset=utf-8"}),x=URL.createObjectURL(g);p.onload=()=>{const y=document.createElement("canvas");y.width=h,y.height=h;const v=y.getContext("2d");v&&(v.fillStyle="#ffffff",v.fillRect(0,0,h,h),v.drawImage(p,0,0,h,h),URL.revokeObjectURL(x),y.toBlob(_=>{if(!_)return;const j=document.createElement("a");j.href=URL.createObjectURL(_),j.download=`${o}.png`,j.click(),URL.revokeObjectURL(j.href)},"image/png"))},p.src=x};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"sm:max-w-md",children:[e.jsxs(Vs,{children:[e.jsx($s,{children:"Listing QR Code"}),e.jsx(Cr,{children:"Scans straight to the public listing page — great for flyers, signs, and open houses."})]}),e.jsxs("div",{className:"flex flex-col items-center gap-4",children:[e.jsx("div",{ref:i,className:"rounded-xl bg-white p-4 shadow-sm border",children:e.jsx(jk,{value:n,size:220,level:"H",includeMargin:!0})}),e.jsx("p",{className:"text-xs text-muted-foreground break-all text-center",children:n})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-2 pt-2",children:[e.jsxs($,{onClick:()=>u(),className:"gap-2",children:[e.jsx(ji,{className:"h-4 w-4"}),"PNG"]}),e.jsxs($,{variant:"outline",onClick:d,className:"gap-2",children:[e.jsx(ji,{className:"h-4 w-4"}),"SVG"]}),e.jsxs($,{variant:"outline",onClick:async()=>{await navigator.clipboard.writeText(n),ae.success("Link copied")},className:"gap-2",children:[e.jsx(Da,{className:"h-4 w-4"}),"Copy link"]})]})]})})}const gIn=s=>{if(!s)return"";const t=s.replace(/\D/g,""),n=t.length===11&&t.startsWith("1")?t.slice(1):t;return n.length!==10?s:`${n.slice(0,3)}-${n.slice(3,6)}-${n.slice(6)}`},U1t=s=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s),mP="#D4AF37",q1t="#0F172A",V1t=async s=>new Promise((t,n)=>{const r=new Image;r.crossOrigin="anonymous",r.referrerPolicy="no-referrer",r.onload=()=>t(r),r.onerror=n,r.src=s}),H1t=(s,t,n,r,a,i)=>{const l=Math.max(a/t.naturalWidth,i/t.naturalHeight),o=a/l,c=i/l,d=(t.naturalWidth-o)/2,u=(t.naturalHeight-c)/2;s.drawImage(t,d,u,o,c,n,r,a,i)},sK=(s,t,n)=>{if(s.measureText(t).width<=n)return t;let r=t;for(;r.length>3&&s.measureText(`${r}…`).width>n;)r=r.slice(0,-1);return`${r.trim()}…`},xIn=(s,t,n,r)=>{const a=t.split(/\s+/).filter(Boolean),i=[];let l="";for(const o of a){const c=l?`${l} ${o}`:o;if(s.measureText(c).width<=n||!l)l=c;else if(i.push(l),l=o,i.length===r)break}return l&&i.length{let i=n;for(const l of t)s.fillText(l,i,r),i+=s.measureText(l).width+a},vIn=s=>s instanceof DOMException||s instanceof Error?s.name:null;function Kqt({listingId:s,open:t,onOpenChange:n}){var A,M;const{data:r}=gWe(s||""),[a,i]=k.useState(null),[l,o]=k.useState(!1),[c,d]=k.useState(null),[u,h]=k.useState(null),m=((r==null?void 0:r.photos)||[]).slice().sort((I,P)=>I.is_primary&&!P.is_primary?-1:!I.is_primary&&P.is_primary?1:(I.sort_order??0)-(P.sort_order??0));k.useEffect(()=>{var P;if(!t)return;const I=((P=m[0])==null?void 0:P.photo_url)||null;h(R=>R||I)},[t,r==null?void 0:r.id,m.length]),k.useEffect(()=>{let I=!1;if(!(!t||!(r!=null&&r.agent_id)))return(async()=>{var B,U,G,H;const{data:P}=await V.from("profiles").select("name, phone, phone_e164, avatar_url, brokerage:brokerages!profiles_brokerage_id_fkey(name)").eq("id",r.agent_id).maybeSingle();if(I)return;const R=P,O=((B=R==null?void 0:R.brokerage)==null?void 0:B.name)||((G=(U=r.agent)==null?void 0:U.brokerage)==null?void 0:G.name)||null;i({name:(R==null?void 0:R.name)||((H=r.agent)==null?void 0:H.name)||"Agent",phone:(R==null?void 0:R.phone)||(R==null?void 0:R.phone_e164)||null,avatar_url:(R==null?void 0:R.avatar_url)||null,brokerage:O})})(),()=>{I=!0}},[t,r==null?void 0:r.agent_id]),k.useEffect(()=>{if(!t){d(null),h(null);return}if(!r||!a)return;const I=setTimeout(()=>{p()},350);return()=>clearTimeout(I)},[t,r==null?void 0:r.id,a==null?void 0:a.name,u]);const p=async()=>{if(!(!r||!a)){o(!0);try{const I=document.createElement("canvas");I.width=1080,I.height=1080;const P=I.getContext("2d");if(!P)throw new Error("Canvas unavailable");if(P.fillStyle=q1t,P.fillRect(0,0,1080,1080),_){const H=await V1t(_);H1t(P,H,0,0,1080,1080)}const R=P.createLinearGradient(0,0,0,1080);R.addColorStop(0,"rgba(15,23,42,0.58)"),R.addColorStop(.34,"rgba(15,23,42,0.16)"),R.addColorStop(.62,"rgba(15,23,42,0.48)"),R.addColorStop(1,"rgba(15,23,42,0.98)"),P.fillStyle=R,P.fillRect(0,0,1080,1080),P.fillStyle=mP,P.fillRect(56,62,72,2),P.font="600 22px Arial, sans-serif",yIn(P,"JUST LISTED",146,72,8),P.save(),P.shadowColor="rgba(0,0,0,0.55)",P.shadowBlur=24,P.shadowOffsetY=4,P.fillStyle="#F8FAFC",P.font="600 64px Georgia, serif",P.textBaseline="top";const O=xIn(P,r.property_address||`${r.city||""}, ${r.state||""}`.trim(),952,2);let B=O.length>1?590:654;O.forEach(H=>{P.fillText(H,64,B),B+=70}),P.restore();const U=[r.city,r.state].filter(Boolean).join(", ")+(r.neighborhood?` · ${r.neighborhood}`:"");P.fillStyle="rgba(248,250,252,0.9)",P.font="600 26px Arial, sans-serif",P.fillText(sK(P,U.toUpperCase(),952),64,B+8),P.fillStyle=mP,P.font="700 56px Arial, sans-serif",P.fillText(U1t(r.price),64,B+58),C.length>0&&(P.fillStyle="rgba(248,250,252,0.86)",P.font="600 22px Arial, sans-serif",P.fillText(sK(P,C.join(" · "),430),360,B+78));const G=P.createLinearGradient(0,880,0,1080);if(G.addColorStop(0,"rgba(15,23,42,0.96)"),G.addColorStop(1,"#0B1322"),P.fillStyle=G,P.fillRect(0,880,1080,200),P.fillStyle=mP,P.fillRect(0,880,1080,2),P.save(),P.beginPath(),P.arc(124,980,60,0,Math.PI*2),P.closePath(),P.fillStyle="#1E293B",P.fill(),P.lineWidth=6,P.strokeStyle=mP,P.stroke(),P.clip(),a.avatar_url)try{const H=await V1t(a.avatar_url);H1t(P,H,64,920,120,120)}catch{P.fillStyle=mP,P.font="700 48px Arial, sans-serif",P.textAlign="center",P.textBaseline="middle",P.fillText(a.name.charAt(0).toUpperCase(),124,982)}else P.fillStyle=mP,P.font="700 48px Arial, sans-serif",P.textAlign="center",P.textBaseline="middle",P.fillText(a.name.charAt(0).toUpperCase(),124,982);P.restore(),P.textAlign="left",P.textBaseline="alphabetic",P.fillStyle="#F8FAFC",P.font="600 38px Georgia, serif",P.fillText(sK(P,a.name,j?430:820),212,970),a.brokerage&&(P.fillStyle=mP,P.font="600 20px Arial, sans-serif",P.fillText(sK(P,a.brokerage.toUpperCase(),j?430:820),212,1008)),j&&(P.textAlign="right",P.fillStyle="rgba(212,175,55,0.86)",P.font="600 16px Arial, sans-serif",P.fillText("CALL · TEXT",1016,958),P.fillStyle="#F8FAFC",P.font="600 38px Arial, sans-serif",P.fillText(j,1016,1008)),d(I.toDataURL("image/png"))}catch(I){console.error("Generate graphic error",I),ae.error("Could not generate graphic")}finally{o(!1)}}},g=async I=>(await fetch(I)).blob(),x=async()=>{if(!c)return;const I=document.createElement("a");I.href=c,I.download=`just-listed-${(r==null?void 0:r.slug)||(r==null?void 0:r.id)||"graphic"}.png`,I.click(),ae.success("Downloaded!")},y=async()=>{if(c)try{const I=await g(c);await navigator.clipboard.write([new ClipboardItem({"image/png":I})]),ae.success("Copied to clipboard")}catch{ae.error("Copy not supported in this browser")}},v=async()=>{if(c)try{const I=await g(c),P=new File([I],"just-listed.png",{type:"image/png"});navigator.canShare&&navigator.canShare({files:[P]})?await navigator.share({files:[P],title:"Just Listed"}):x()}catch(I){vIn(I)!=="AbortError"&&ae.error("Share failed")}},_=u||((A=m[0])==null?void 0:A.photo_url)||null,j=gIn(a==null?void 0:a.phone),C=[r!=null&&r.bedrooms?`${r.bedrooms} BD`:null,r!=null&&r.bathrooms?`${r.bathrooms} BA`:null,r!=null&&r.square_footage?`${r.square_footage.toLocaleString()} SF`:null].filter(Boolean);return e.jsx(zs,{open:t,onOpenChange:n,children:e.jsx(Rs,{className:"!max-w-[480px] !w-[calc(100vw-2rem)] !p-0 !gap-0 !block overflow-hidden",style:{maxHeight:"calc(100vh - 2rem)"},children:e.jsxs("div",{className:"flex flex-col",style:{maxHeight:"calc(100vh - 2rem)"},children:[e.jsxs(Vs,{className:"px-5 pt-5 pb-3 shrink-0",children:[e.jsxs($s,{className:"flex items-center gap-2 pr-8",children:[e.jsx(kn,{className:"h-5 w-5 text-amber-500 shrink-0"}),e.jsx("span",{className:"truncate",children:"Your Just Listed Graphic"})]}),e.jsx(Cr,{className:"text-xs",children:"Square 1080×1080 — perfect for Instagram, Facebook, LinkedIn."})]}),e.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-5 pb-3",children:[e.jsxs("div",{className:"relative mx-auto flex items-center justify-center rounded-lg overflow-hidden",style:{width:"280px",maxWidth:"100%",height:"280px",background:q1t},children:[_&&e.jsx("img",{src:_,alt:"Selected property",className:"absolute inset-0 h-full w-full object-cover"}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-b from-slate-950/65 via-slate-950/25 to-slate-950"}),e.jsxs("div",{className:"absolute left-4 right-4 top-4 flex items-center gap-2",children:[e.jsx("span",{className:"h-px w-6 bg-amber-400"}),e.jsx("span",{className:"text-[9px] font-semibold uppercase tracking-[0.28em] text-amber-300",children:"Just Listed"})]}),e.jsxs("div",{className:"absolute left-4 right-4 bottom-[64px] text-white",children:[e.jsx("div",{className:"line-clamp-2 font-serif text-[18px] font-semibold leading-[1.05] drop-shadow-lg",children:(r==null?void 0:r.property_address)||`${(r==null?void 0:r.city)||""}, ${(r==null?void 0:r.state)||""}`}),e.jsxs("div",{className:"mt-1 truncate text-[9px] font-semibold uppercase tracking-[0.18em] text-white/85",children:[[r==null?void 0:r.city,r==null?void 0:r.state].filter(Boolean).join(", "),r!=null&&r.neighborhood?` · ${r.neighborhood}`:""]}),e.jsxs("div",{className:"mt-1.5 flex items-center gap-2",children:[e.jsx("span",{className:"text-[16px] font-bold text-amber-300",children:r?U1t(r.price):""}),C.length>0&&e.jsx("span",{className:"truncate text-[8px] font-semibold uppercase tracking-[0.14em] text-white/80",children:C.join(" · ")})]})]}),e.jsxs("div",{className:"absolute inset-x-0 bottom-0 flex h-[52px] items-center border-t border-amber-400 bg-slate-950/95 px-4",children:[e.jsx("div",{className:"flex h-9 w-9 shrink-0 items-center justify-center overflow-hidden rounded-full border-2 border-amber-400 bg-slate-800 text-xs font-bold text-amber-300",children:a!=null&&a.avatar_url?e.jsx("img",{src:a.avatar_url,alt:"",className:"h-full w-full object-cover"}):(M=a==null?void 0:a.name)==null?void 0:M.charAt(0).toUpperCase()}),e.jsxs("div",{className:"ml-2 min-w-0 flex-1",children:[e.jsx("div",{className:"truncate font-serif text-xs font-semibold text-white",children:a==null?void 0:a.name}),(a==null?void 0:a.brokerage)&&e.jsx("div",{className:"truncate text-[7px] font-semibold uppercase tracking-[0.18em] text-amber-300",children:a.brokerage})]}),j&&e.jsx("div",{className:"ml-2 shrink-0 text-[9px] font-semibold text-white",children:j})]}),l&&e.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center gap-2 bg-slate-950/80 text-white/85",children:[e.jsx(Jt,{className:"h-7 w-7 animate-spin"}),e.jsx("p",{className:"text-xs",children:"Crafting your graphic…"})]})]}),m.length>1&&e.jsxs("div",{className:"mt-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:"Choose photo"}),e.jsx("div",{className:"flex gap-2 pb-2",style:{overflowX:"auto",overflowY:"hidden",WebkitOverflowScrolling:"touch"},children:m.map(I=>{const P=u===I.photo_url;return e.jsx("button",{type:"button",onClick:()=>h(I.photo_url),className:`relative shrink-0 h-14 w-14 rounded-md overflow-hidden border-2 transition ${P?"border-amber-500 ring-2 ring-amber-500/30":"border-transparent hover:border-muted-foreground/40"}`,children:e.jsx("img",{src:I.photo_url,alt:"",className:"w-full h-full object-cover"})},I.id)})})]})]}),e.jsxs("div",{className:"px-5 pb-5 pt-2 shrink-0 border-t bg-background flex flex-wrap justify-end gap-2",children:[e.jsx($,{variant:"outline",size:"sm",onClick:()=>void p(),disabled:l||!r||!a,children:"Regenerate"}),e.jsxs($,{variant:"outline",size:"sm",onClick:y,disabled:!c,className:"gap-1.5",children:[e.jsx(Da,{className:"h-3.5 w-3.5"})," Copy"]}),e.jsxs($,{variant:"outline",size:"sm",onClick:v,disabled:!c,className:"gap-1.5",children:[e.jsx(ou,{className:"h-3.5 w-3.5"})," Share"]}),e.jsxs($,{size:"sm",onClick:x,disabled:!c,className:"gap-1.5",children:[e.jsx(ji,{className:"h-3.5 w-3.5"})," Download"]})]})]})})})}function bIn(s){return new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s)}const _In={single_family:"Single Family Home",condo:"Condo",townhouse:"Townhouse",land:"Land",multi_family:"Multi-Family",luxury:"Luxury Home",commercial:"Commercial",other:"Property"};function wIn({open:s,onOpenChange:t,listing:n}){const{user:r}=ks(),{data:a=[],isLoading:i}=vv(),{data:l=[]}=vj(),[o,c]=k.useState(""),[d,u]=k.useState("all"),[h,m]=k.useState(new Set),[p,g]=k.useState(!1),[x,y]=k.useState(null);k.useEffect(()=>{s||(c(""),u("all"),m(new Set),g(!1))},[s]),k.useEffect(()=>{!s||!r||(async()=>{const{data:P}=await V.from("gmail_integrations").select("gmail_email").eq("user_id",r.id).maybeSingle();y((P==null?void 0:P.gmail_email)||null)})()},[s,r]);const v=k.useMemo(()=>a.filter(P=>P.email),[a]),_=k.useMemo(()=>{let P=v;if(d!=="all"&&(P=P.filter(R=>{var O;return(O=R.tags)==null?void 0:O.some(B=>B.relationship_type_id===d)})),o.trim()){const R=o.toLowerCase();P=P.filter(O=>`${O.first_name||""} ${O.last_name||""}`.toLowerCase().includes(R)||(O.email||"").toLowerCase().includes(R))}return P},[v,o,d]),j=()=>{h.size===_.length?m(new Set):m(new Set(_.map(P=>P.id)))},C=P=>{const R=new Set(h);R.has(P)?R.delete(P):R.add(P),m(R)},A=k.useMemo(()=>v.filter(P=>h.has(P.id)).map(P=>({id:P.id,first_name:P.first_name||"there",last_name:P.last_name,email:P.email})),[v,h]),{defaultSubject:M,defaultBody:I}=k.useMemo(()=>{var te,le,fe,_e;const P=n.property_address||`${n.city}, ${n.state}`,R=bIn(n.price),O=_In[n.property_type]||"home",B=n.bedrooms?`${n.bedrooms} bed`:"",U=n.bathrooms?`${n.bathrooms} bath`:"",G=n.square_footage?`${n.square_footage.toLocaleString()} sqft`:"",H=[B,U,G].filter(Boolean).join(" • "),Y=`https://listings.relevelup.com/${n.slug||n.id}`,se=((le=(te=n.photos)==null?void 0:te.find(ve=>ve.is_primary))==null?void 0:le.photo_url)||((_e=(fe=n.photos)==null?void 0:fe[0])==null?void 0:_e.photo_url)||"",oe={active:"Just Listed",coming_soon:"Coming Soon",office_exclusive:"Office Exclusive",pre_market:"Pre-Market",price_improvement:"Price Improvement",under_contract:"Under Contract",sold:"Sold"}[n.status]||"New Listing",me=`${oe}: ${P} — ${R}`,Q=`

Hi {{first_name}},

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

${se?` ${P} `:""}
${oe}

${R}

${P}

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

${H?`

${H} • ${O}

`:""} View Photos & Details →

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

Talk soon,

`;return{defaultSubject:me,defaultBody:Q}},[n]);return p?e.jsx(W2,{open:p,onOpenChange:P=>{g(P),P||t(!1)},bulkContacts:A,defaultSubject:M,defaultBody:I,gmailEmail:x}):e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"sm:max-w-[640px] max-h-[90vh] flex flex-col",children:[e.jsxs(Vs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(kn,{className:"h-5 w-5 text-amber-500"}),"Email this listing to your sphere"]}),e.jsx(Cr,{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(Yr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search contacts...",value:o,onChange:P=>c(P.target.value),className:"pl-9"})]}),e.jsxs(bs,{value:d,onValueChange:u,children:[e.jsx(ys,{className:"sm:w-[180px]",children:e.jsx(_s,{placeholder:"Filter by tag"})}),e.jsxs(vs,{children:[e.jsx(We,{value:"all",children:"All contacts"}),l.map(P=>e.jsx(We,{value:P.id,children:P.name},P.id))]})]})]}),e.jsxs("div",{className:"flex items-center justify-between text-sm border-y py-2",children:[e.jsxs("button",{type:"button",onClick:j,className:"flex items-center gap-2 text-primary hover:underline",children:[e.jsx(Li,{checked:_.length>0&&h.size===_.length,className:"pointer-events-none"}),e.jsx("span",{children:h.size===_.length&&_.length>0?"Deselect all":`Select all (${_.length})`})]}),e.jsxs(qe,{variant:"secondary",className:"gap-1",children:[e.jsx(Xn,{className:"h-3 w-3"}),h.size," selected"]})]}),e.jsx(Eo,{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(Jt,{className:"h-5 w-5 animate-spin mr-2"}),"Loading your contacts..."]}):_.length===0?e.jsx("div",{className:"text-center py-12 text-muted-foreground text-sm",children:v.length===0?"No contacts with email addresses yet.":"No contacts match your search."}):e.jsx("div",{className:"space-y-1 py-2",children:_.map(P=>e.jsxs("label",{className:"flex items-center gap-3 p-2 rounded-md hover:bg-muted/50 cursor-pointer",children:[e.jsx(Li,{checked:h.has(P.id),onCheckedChange:()=>C(P.id)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("p",{className:"text-sm font-medium truncate",children:[P.first_name," ",P.last_name]}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:P.email})]}),P.tags&&P.tags.length>0&&e.jsx("div",{className:"flex gap-1 flex-wrap justify-end max-w-[40%]",children:P.tags.slice(0,2).map(R=>{var O;return e.jsx(qe,{variant:"outline",className:"text-[10px] px-1.5 py-0",children:(O=R.relationship_type)==null?void 0:O.name},R.id)})})]},P.id))})}),e.jsx(Pc,{}),e.jsxs("div",{className:"flex justify-between items-center gap-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:x?`Sending from ${x}`:"Connect Gmail in Settings to send"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs($,{onClick:()=>g(!0),disabled:h.size===0,className:"gap-2",children:[e.jsx(pn,{className:"h-4 w-4"}),"Compose Email (",h.size,")"]})]})]})]})})}function c2(s){const t=s.expected_commission;if(!t)return null;if((s.commission_calc_method||"standard")==="referral_first"){let a=t;s.referral_fee_pct&&(a-=t*(s.referral_fee_pct/100));let i=a;return s.brokerage_split_pct&&(i-=a*(s.brokerage_split_pct/100)),s.team_split_pct&&(i-=t*(s.team_split_pct/100)),s.franchise_fee_pct&&(i-=t*(s.franchise_fee_pct/100)),s.transaction_fee&&(i-=s.transaction_fee),Math.max(0,i)}let r=t;return s.brokerage_split_pct&&(r-=t*(s.brokerage_split_pct/100)),s.team_split_pct&&(r-=t*(s.team_split_pct/100)),s.franchise_fee_pct&&(r-=t*(s.franchise_fee_pct/100)),s.referral_fee_pct&&(r-=t*(s.referral_fee_pct/100)),s.transaction_fee&&(r-=s.transaction_fee),Math.max(0,r)}function _te(){const s=ai();return pt({queryKey:["deal-pipeline-stages",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await V.from("deal_pipeline_stages").select("*").eq("owner_user_id",s).order("sort_order",{ascending:!0});if(n)throw n;return t},enabled:!!s})}function Yqt(){const s=ai(),t=ls();return Nt({mutationFn:async()=>{if(!s)throw new Error("Not authenticated");const{error:n}=await V.rpc("initialize_deal_pipeline_stages",{p_user_id:s});if(n)throw n},onSuccess:()=>{t.invalidateQueries({queryKey:["deal-pipeline-stages"]})}})}function $Te(){const s=ai();return pt({queryKey:["deal-pipeline-deals",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await V.from("deal_pipeline").select(` *, contact:innercircle_contacts(id, first_name, last_name, email, phone), listing:listings(id, property_address, city, state, price, status, created_at) `).eq("owner_user_id",s).order("updated_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function Zqt(){const s=ai(),t=ls();return Nt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r,error:a}=await V.from("deal_pipeline").insert({deal_name:n.deal_name,deal_type:n.deal_type,stage_id:n.stage_id||null,contact_id:n.contact_id||null,listing_id:n.listing_id||null,property_address:n.property_address||null,city:n.city||null,state:n.state||null,zip_code:n.zip_code||null,expected_price:n.expected_price||null,expected_commission:n.expected_commission||null,commission_percentage:n.commission_percentage||3,target_close_date:n.target_close_date||null,contract_date:n.contract_date||null,listing_date:n.listing_date||null,priority:n.priority||"medium",probability:n.probability||50,notes:n.notes||null,owner_user_id:s}).select().single();if(a)throw a;return await V.from("deal_activities").insert([{deal_id:r.id,activity_type:"system",title:"Deal created",description:`Deal "${n.deal_name}" was created`}]),r},onSuccess:()=>{t.invalidateQueries({queryKey:["deal-pipeline-deals"]}),t.invalidateQueries({queryKey:["deal-pipeline-stats"]})}})}function Xqt(){const s=ls();return Nt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await V.from("deal_pipeline").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["deal-pipeline-deals"]}),s.invalidateQueries({queryKey:["deal-pipeline-stats"]})}})}function jIn(){const s=ls();return Nt({mutationFn:async({dealId:t,stageId:n,stageName:r})=>{const{data:a}=await V.from("deal_pipeline_stages").select("default_probability").eq("id",n).maybeSingle(),i={stage_id:n};typeof(a==null?void 0:a.default_probability)=="number"&&(i.probability=a.default_probability);const{data:l,error:o}=await V.from("deal_pipeline").update(i).eq("id",t).select().single();if(o)throw o;return await V.from("deal_activities").insert({deal_id:t,activity_type:"stage_change",title:`Moved to ${r}`,metadata:{new_stage_id:n,new_stage_name:r}}),l},onSuccess:()=>{s.invalidateQueries({queryKey:["deal-pipeline-deals"]}),s.invalidateQueries({queryKey:["deal-activities"]})}})}function NIn(){const s=ls();return Nt({mutationFn:async t=>{const{error:n}=await V.from("deal_pipeline").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["deal-pipeline-deals"]}),s.invalidateQueries({queryKey:["deal-pipeline-stats"]})}})}function kIn(s){return pt({queryKey:["deal-activities",s],queryFn:async()=>{const{data:t,error:n}=await V.from("deal_activities").select("*").eq("deal_id",s).order("created_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function SIn(){const s=ls();return Nt({mutationFn:async t=>{const{data:n,error:r}=await V.from("deal_activities").insert([{deal_id:t.deal_id,activity_type:t.activity_type,title:t.title,description:t.description||null}]).select().single();if(r)throw r;return n},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["deal-activities",n.deal_id]})}})}function CIn(s){return pt({queryKey:["deal-checklist",s],queryFn:async()=>{const{data:t,error:n}=await V.from("deal_checklist_items").select("*").eq("deal_id",s).order("sort_order",{ascending:!0});if(n)throw n;return t},enabled:!!s})}function AIn(){const s=ls();return Nt({mutationFn:async({id:t,is_completed:n,deal_id:r})=>{const{data:a,error:i}=await V.from("deal_checklist_items").update({is_completed:n,completed_at:n?new Date().toISOString():null}).eq("id",t).select().single();if(i)throw i;return a},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["deal-checklist",n.deal_id]})}})}function EIn(){const s=ls();return Nt({mutationFn:async t=>{const{data:n,error:r}=await V.from("deal_checklist_items").insert([{deal_id:t.deal_id,title:t.title,description:t.description||null,due_date:t.due_date||null,sort_order:t.sort_order||0}]).select().single();if(r)throw r;return n},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["deal-checklist",n.deal_id]})}})}function TIn(){const s=ai();return pt({queryKey:["deal-pipeline-stats",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await V.from("deal_pipeline").select("*, deal_pipeline_stages(name, is_won_stage, is_lost_stage)").eq("owner_user_id",s);if(n)throw n;const r=(t==null?void 0:t.filter(o=>{var c,d,u;return!((c=o.deal_pipeline_stages)!=null&&c.is_won_stage)&&!((d=o.deal_pipeline_stages)!=null&&d.is_lost_stage)&&((u=o.deal_pipeline_stages)==null?void 0:u.name)!=="Cancelled"}))||[],a=(t==null?void 0:t.filter(o=>{var c;return(c=o.deal_pipeline_stages)==null?void 0:c.is_won_stage}))||[],i=new Date().getFullYear(),l=a.filter(o=>{const c=o.actual_close_date;return c?new Date(c).getFullYear()===i:!0});return{totalDeals:(t==null?void 0:t.length)||0,activeDeals:r.length,wonDeals:a.length,pipelineValue:r.reduce((o,c)=>o+(c.expected_price||0),0),expectedCommission:r.reduce((o,c)=>o+(c.expected_commission||0),0),expectedNetToAgent:r.reduce((o,c)=>o+(c2(c)||0),0),wonValue:a.reduce((o,c)=>o+(c.expected_price||0),0),weightedGCI:r.reduce((o,c)=>{const d=(c.probability??50)/100;return o+(c.expected_commission||0)*d},0),weightedNet:r.reduce((o,c)=>{const d=(c.probability??50)/100;return o+(c2(c)||0)*d},0),ytdWonDeals:l.length,ytdWonGCI:l.reduce((o,c)=>o+(c.expected_commission||0),0),ytdWonNet:l.reduce((o,c)=>o+(c2(c)||0),0),projectedAnnualNet:l.reduce((o,c)=>o+(c2(c)||0),0)+r.reduce((o,c)=>{const d=(c.probability??50)/100;return o+(c2(c)||0)*d},0)}},enabled:!!s})}function MIn(s){const t=ai();return pt({queryKey:["deal-by-listing",s,t],queryFn:async()=>{if(!t||!s)return null;const{data:n,error:r}=await V.from("deal_pipeline").select(` *, deal_pipeline_stages(id, name, color) `).eq("owner_user_id",t).eq("listing_id",s).maybeSingle();if(r)throw r;return n},enabled:!!t&&!!s})}function PIn(){const s=ls();return Nt({mutationFn:async({dealId:t,listingId:n})=>{const{data:r,error:a}=await V.from("deal_pipeline").update({listing_id:n}).eq("id",t).select().single();if(a)throw a;return await V.from("deal_activities").insert({deal_id:t,activity_type:"system",title:"Linked to Listing Exchange",description:"This deal is now synced with Listing Exchange",metadata:{listing_id:n}}),r},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["deal-pipeline-deals"]}),s.invalidateQueries({queryKey:["deal-by-listing",n.listingId]})}})}function IIn(){const s=ls();return Nt({mutationFn:async({dealId:t,listingId:n})=>{const{data:r,error:a}=await V.from("deal_pipeline").update({listing_id:null}).eq("id",t).select().single();if(a)throw a;return{data:r,listingId:n}},onSuccess:t=>{s.invalidateQueries({queryKey:["deal-pipeline-deals"]}),s.invalidateQueries({queryKey:["deal-by-listing",t.listingId]})}})}function LIn({listing:s}){const t=Jn(),[n,r]=k.useState(""),[a,i]=k.useState(!1),{data:l,isLoading:o}=MIn(s.id),{data:c,isLoading:d}=_te(),{data:u,isLoading:h}=$Te(),m=Yqt(),p=PIn(),g=IIn(),x=Zqt(),y=(u==null?void 0:u.filter(A=>!A.listing_id))||[],v=A=>{if(!(c!=null&&c.length))return null;switch(A){case"coming_soon":case"active":case"price_improvement":return c.find(M=>M.name==="Active");case"under_contract":return c.find(M=>M.name==="Under Contract");case"sold":return c.find(M=>M.is_won_stage);default:return c.find(M=>M.name==="Active")}},_=async()=>{i(!0);try{c!=null&&c.length||await m.mutateAsync();const A=v(s.status);await x.mutateAsync({deal_name:s.property_address?`${s.property_address}, ${s.city}`:`${s.city}, ${s.state}`,deal_type:"seller",stage_id:(A==null?void 0:A.id)||null,listing_id:s.id,property_address:s.property_address,city:s.city,state:s.state,expected_price:s.price,expected_commission:s.price*.03,commission_percentage:3,priority:"medium",probability:50}),ae.success("Deal created and linked to listing!")}catch(A){console.error("Failed to create deal:",A),ae.error("Failed to create deal")}finally{i(!1)}},j=async()=>{if(!n){ae.error("Please select a deal");return}try{await p.mutateAsync({dealId:n,listingId:s.id}),ae.success("Listing linked to deal!"),r("")}catch{ae.error("Failed to link listing")}},C=async()=>{if(l)try{await g.mutateAsync({dealId:l.id,listingId:s.id}),ae.success("Listing unlinked from deal")}catch{ae.error("Failed to unlink listing")}};return o||d?e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsxs(Yt,{className:"flex items-center gap-2 text-base",children:[e.jsx(M5,{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(Jt,{className:"h-5 w-5 animate-spin text-muted-foreground"})})})]}):l?e.jsxs(we,{className:"border-primary/20 bg-primary/5",children:[e.jsx(Vt,{className:"pb-2",children:e.jsxs(Yt,{className:"flex items-center gap-2 text-base",children:[e.jsx(pd,{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(qe,{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($,{variant:"outline",size:"sm",className:"flex-1",onClick:()=>t("/mission-control/pipeline"),children:["View Pipeline",e.jsx(xi,{className:"h-3 w-3 ml-1"})]}),e.jsx($,{variant:"ghost",size:"sm",onClick:C,disabled:g.isPending,children:g.isPending?e.jsx(Jt,{className:"h-4 w-4 animate-spin"}):e.jsx(Q8,{className:"h-4 w-4"})})]})]})]}):e.jsxs(we,{children:[e.jsx(Vt,{className:"pb-2",children:e.jsxs(Yt,{className:"flex items-center gap-2 text-base",children:[e.jsx(M5,{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($,{onClick:_,disabled:a||x.isPending,className:"w-full",size:"sm",children:[a||x.isPending?e.jsx(Jt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(nn,{className:"h-4 w-4 mr-2"}),"Create New Deal"]}),y.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(bs,{value:n,onValueChange:r,children:[e.jsx(ys,{className:"flex-1 text-sm",children:e.jsx(_s,{placeholder:"Link to existing deal..."})}),e.jsx(vs,{children:y.map(A=>e.jsx(We,{value:A.id,children:A.deal_name},A.id))})]}),e.jsx($,{variant:"secondary",size:"icon",onClick:j,disabled:!n||p.isPending,children:p.isPending?e.jsx(Jt,{className:"h-4 w-4 animate-spin"}):e.jsx(pd,{className:"h-4 w-4"})})]})]})]})]})}const RIn={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"},DIn={active:"Active",coming_soon:"Coming Soon",office_exclusive:"Office Exclusive",pre_market:"Pre-Market",price_improvement:"Price Improvement",under_contract:"Under Contract",sold:"Sold"},G1t={single_family:"Single Family",condo:"Condo",townhouse:"Townhouse",land:"Land",multi_family:"Multi-Family",luxury:"Luxury",commercial:"Commercial",other:"Other"};function OIn(){var me,Q,te,le,fe,_e,ve,he,Se;const{listingId:s}=oo(),t=Jn(),{user:n}=ks(),{data:r,isLoading:a}=gWe(s||""),{data:i}=$Mt(s||""),{data:l}=gEs(s||""),o=BMt(),c=pEs(),d=xEs(),u=zMt(),h=vEs(),[m,p]=k.useState(!1),[g,x]=k.useState(!1),[y,v]=k.useState(!1),[_,j]=k.useState(!1),[C,A]=k.useState(!1),[M,I]=k.useState(!1),[P,R]=k.useState(null),[O,B]=k.useState({buyerName:"",buyerType:"",notes:""}),U=(n==null?void 0:n.id)===(r==null?void 0:r.agent_id),G=Te=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(Te),H=async Te=>{const Ie=`https://listings.relevelup.com/${(r==null?void 0:r.slug)||(r==null?void 0:r.id)}`,Ue=`Check out this listing: ${(r==null?void 0:r.property_address)||(r==null?void 0:r.city)}`;d.mutate({listingId:r.id,shareType:Te});try{switch(Te){case"facebook":window.open(`https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(Ie)}`,"_blank");break;case"copy":await navigator.clipboard.writeText(Ie),ae.success("Link copied to clipboard!");break;case"text":window.open(`sms:?body=${encodeURIComponent(`${Ue} ${Ie}`)}`);break;case"email":window.open(`mailto:?subject=${encodeURIComponent(Ue)}&body=${encodeURIComponent(`Check out this listing: ${Ie}`)}`);break}}catch(Be){console.error("Share error:",Be),ae.error("Failed to share")}},Y=async()=>{try{await u.mutateAsync(r.id),ae.success("Listing deleted"),t("/mission-control/listings")}catch{ae.error("Failed to delete listing")}},se=async()=>{if(!O.buyerName.trim()){ae.error("Please enter buyer name");return}try{await h.mutateAsync({listingId:r.id,listingAgentId:r.agent_id,buyerName:O.buyerName,buyerType:O.buyerType||void 0,notes:O.notes||void 0}),ae.success("Referral sent successfully!"),x(!1),B({buyerName:"",buyerType:"",notes:""})}catch{ae.error("Failed to send referral")}},ee=Te=>{var Re,ke;const Ie=(r==null?void 0:r.property_address)||`${r==null?void 0:r.city}, ${r==null?void 0:r.state}`,Ue=G((r==null?void 0:r.price)||0),Be=r!=null&&r.bedrooms?`${r.bedrooms}BD`:"",je=r!=null&&r.bathrooms?`${r.bathrooms}BA`:"",Ye=r!=null&&r.square_footage?`${r.square_footage.toLocaleString()}SF`:"",Ee=[Be,je,Ye].filter(Boolean).join(" | ");switch(Te){case"just_listed":return`🏡 JUST LISTED! ${Ie} ${Ue} ${Ee} ${(r==null?void 0:r.description)||"Schedule your showing today!"} #JustListed #RealEstate #HomeForSale #${(Re=r==null?void 0:r.city)==null?void 0:Re.replace(/\s/g,"")}`;case"price_improvement":return`📣 PRICE IMPROVEMENT! ${Ie} Now ${Ue}! ${Ee} Don't miss this opportunity! #PriceReduced #RealEstate #HomeForSale`;case"teaser":return`Looking for a ${G1t[(r==null?void 0:r.property_type)||"single_family"].toLowerCase()} in ${r==null?void 0:r.city}? 👀 I've got just the one for you! ${Ee} DM me for details! 📩 #ComingSoon #RealEstate #${(ke=r==null?void 0:r.city)==null?void 0:ke.replace(/\s/g,"")}`;default:return""}};if(a)return e.jsx(Xs,{title:"Listing",description:"",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(fn,{className:"h-10 w-32"}),e.jsx(fn,{className:"h-[400px] w-full"}),e.jsxs("div",{className:"grid md:grid-cols-3 gap-6",children:[e.jsx(fn,{className:"h-48"}),e.jsx(fn,{className:"h-48"}),e.jsx(fn,{className:"h-48"})]})]})});if(!r)return e.jsx(Xs,{title:"Listing Not Found",description:"",children:e.jsx(we,{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($,{onClick:()=>t("/mission-control/listings"),children:"Back to Listings"})]})})});const oe=((me=r.photos)==null?void 0:me.find(Te=>Te.is_primary))||((Q=r.photos)==null?void 0:Q[0]);return e.jsxs(Xs,{title:"",description:"",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs($,{variant:"ghost",onClick:()=>t("/mission-control/listings"),children:[e.jsx(Ia,{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:()=>oe&&R(oe.photo_url),children:oe?e.jsx("img",{src:oe.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:(te=r.photos)==null?void 0:te.slice(1,5).map((Te,Ie)=>e.jsx("div",{className:"aspect-square rounded-lg overflow-hidden bg-muted cursor-pointer",onClick:()=>R(Te.photo_url),children:e.jsx("img",{src:Te.photo_url,alt:`Photo ${Ie+2}`,className:"w-full h-full object-cover"})},Te.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(we,{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(qe,{className:`${RIn[r.status]} text-white border-0`,children:DIn[r.status]}),r.is_featured&&e.jsxs(qe,{variant:"outline",className:"border-amber-500 text-amber-500",children:[e.jsx(ri,{className:"h-3 w-3 mr-1 fill-amber-500"}),"Featured"]}),r.open_to_referrals&&e.jsxs(qe,{variant:"outline",children:[e.jsx(Xn,{className:"h-3 w-3 mr-1"}),"Open to Referrals"]})]}),e.jsx("h1",{className:"text-3xl font-bold text-primary mb-2",children:G(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(Si,{className:"h-4 w-4"}),r.city,", ",r.state,r.neighborhood&&` • ${r.neighborhood}`]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx($,{variant:"outline",size:"icon",onClick:()=>o.mutate(r.id),children:e.jsx(Bo,{className:`h-4 w-4 ${i?"fill-pink-500 text-pink-500":""}`})}),e.jsx($,{variant:"outline",size:"icon",onClick:()=>c.mutate(r.id),children:l?e.jsx(k5,{className:"h-4 w-4"}):e.jsx(Fx,{className:"h-4 w-4"})}),!U&&e.jsxs($,{variant:"outline",className:"border-amber-500 text-amber-600 hover:bg-amber-50",onClick:()=>v(!0),children:[e.jsx(kn,{className:"h-4 w-4 mr-2"}),"Share & Earn Leads"]}),e.jsxs(Au,{children:[e.jsx(Eu,{asChild:!0,children:e.jsxs($,{variant:"outline",children:[e.jsx(ou,{className:"h-4 w-4 mr-2"}),"Share"]})}),e.jsxs(gu,{children:[e.jsxs(Pa,{onClick:()=>H("copy"),children:[e.jsx(Da,{className:"h-4 w-4 mr-2"}),"Copy Link"]}),e.jsxs(Pa,{onClick:()=>H("facebook"),children:[e.jsx(ax,{className:"h-4 w-4 mr-2"}),"Facebook"]}),e.jsxs(Pa,{onClick:()=>H("text"),children:[e.jsx(bo,{className:"h-4 w-4 mr-2"}),"Text"]}),e.jsxs(Pa,{onClick:()=>H("email"),children:[e.jsx(pn,{className:"h-4 w-4 mr-2"}),"Email"]})]})]}),U&&e.jsxs(e.Fragment,{children:[e.jsxs($,{variant:"outline",onClick:()=>{const Te=(r.photos??[]).slice().sort((Ie,Ue)=>(Ue.is_primary?1:0)-(Ie.is_primary?1:0)||(Ie.sort_order??0)-(Ue.sort_order??0)).map(Ie=>Ie.photo_url).filter(Boolean);if(Te.length===0){ae.error("Add photos to this listing first.");return}Iqt({photos:Te,details:{address:r.property_address||`${r.city??""} ${r.state??""}`.trim(),beds:r.bedrooms?String(r.bedrooms):"",baths:r.bathrooms?String(r.bathrooms):"",sqft:r.square_footage?String(r.square_footage):"",price:r.price?String(r.price):"",highlights:r.description||""},sourceLabel:"Listing Exchange",badge:Lqt(r.status,r.price)}),t("/admin/beta/homereel?tab=music-video")},className:"gap-2 border-violet-500/60 text-violet-600 hover:bg-violet-50",children:[e.jsx(rB,{className:"h-4 w-4"}),"Create Music Video"]}),e.jsxs($,{variant:"outline",onClick:()=>A(!0),className:"gap-2 border-amber-500/60 text-amber-600 hover:bg-amber-50",children:[e.jsx(kn,{className:"h-4 w-4"}),"Just Listed Graphic"]}),e.jsxs($,{variant:"outline",onClick:()=>I(!0),className:"gap-2",children:[e.jsx(Bx,{className:"h-4 w-4"}),"QR Code"]}),e.jsxs($,{variant:"outline",onClick:()=>j(!0),className:"gap-2",children:[e.jsx(pn,{className:"h-4 w-4"}),"Email My Sphere"]}),e.jsxs($,{onClick:()=>t(`/mission-control/listings/${r.id}/customize`),className:"gap-2 bg-gradient-to-r from-primary to-primary/80 hover:opacity-95 text-primary-foreground shadow-md",children:[e.jsx(kn,{className:"h-4 w-4"}),"Customize Public Page"]}),e.jsxs($,{variant:"outline",onClick:()=>t(`/mission-control/listings/${r.id}/edit`),children:[e.jsx(Cp,{className:"h-4 w-4 mr-2"}),"Edit"]}),e.jsx($,{variant:"destructive",size:"icon",onClick:()=>p(!0),children:e.jsx(Un,{className:"h-4 w-4"})})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-4 py-4 border-y",children:[r.bedrooms&&e.jsxs("div",{className:"text-center",children:[e.jsx(Yw,{className:"h-5 w-5 mx-auto mb-1 text-muted-foreground"}),e.jsx("p",{className:"font-semibold",children:r.bedrooms}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Beds"})]}),r.bathrooms&&e.jsxs("div",{className:"text-center",children:[e.jsx(p0,{className:"h-5 w-5 mx-auto mb-1 text-muted-foreground"}),e.jsx("p",{className:"font-semibold",children:r.bathrooms}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Baths"})]}),r.square_footage&&e.jsxs("div",{className:"text-center",children:[e.jsx(w_,{className:"h-5 w-5 mx-auto mb-1 text-muted-foreground"}),e.jsx("p",{className:"font-semibold",children:r.square_footage.toLocaleString()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Sq Ft"})]}),r.year_built&&e.jsxs("div",{className:"text-center",children:[e.jsx(ha,{className:"h-5 w-5 mx-auto mb-1 text-muted-foreground"}),e.jsx("p",{className:"font-semibold",children:r.year_built}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Built"})]})]}),e.jsxs("div",{className:"pt-4 space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(qe,{variant:"secondary",children:[e.jsx(Gi,{className:"h-3 w-3 mr-1"}),G1t[r.property_type]]}),r.lot_size&&e.jsxs(qe,{variant:"secondary",children:["Lot: ",r.lot_size]}),r.has_hoa&&e.jsx(qe,{variant:"secondary",children:"HOA"})]}),r.description&&e.jsxs("div",{children:[e.jsx("h3",{className:"font-medium mb-2",children:"Description"}),e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:r.description})]}),r.agent_notes&&r.agent_notes_public&&e.jsxs("div",{children:[e.jsx("h3",{className:"font-medium mb-2",children:"Agent Notes"}),e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:r.agent_notes})]}),r.co_agent_name&&e.jsxs("div",{children:[e.jsx("h3",{className:"font-medium mb-2",children:"Co-Listing Agent"}),e.jsxs("div",{className:"flex items-center gap-3 rounded-lg border p-3",children:[r.co_agent_photo_url?e.jsx("img",{src:r.co_agent_photo_url,alt:r.co_agent_name,className:"h-12 w-12 rounded-full object-cover"}):e.jsx("div",{className:"h-12 w-12 rounded-full bg-muted flex items-center justify-center text-sm font-medium",children:r.co_agent_name.charAt(0)}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:r.co_agent_name}),r.co_agent_brokerage&&e.jsx("p",{className:"text-sm text-muted-foreground truncate",children:r.co_agent_brokerage}),e.jsx("p",{className:"text-sm text-muted-foreground truncate",children:[r.co_agent_email,r.co_agent_phone].filter(Boolean).join(" · ")})]})]})]}),r.mls_link&&e.jsx($,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:r.mls_link,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(Ir,{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(ba,{className:"h-4 w-4"}),r.view_count," views"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ou,{className:"h-4 w-4"}),r.share_count," shares"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Bo,{className:"h-4 w-4"}),r.save_count," saves"]})]})]})}),r.allow_sharing&&e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsx(Yt,{className:"text-lg",children:"Share Content"})}),e.jsx(De,{className:"space-y-4",children:["just_listed","price_improvement","teaser"].map(Te=>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:[Te.replace("_"," ")," Caption"]}),e.jsx($,{size:"sm",variant:"ghost",onClick:()=>{navigator.clipboard.writeText(ee(Te)),ae.success("Caption copied!")},children:e.jsx(Da,{className:"h-3 w-3"})})]}),e.jsx("p",{className:"text-xs text-muted-foreground whitespace-pre-wrap",children:ee(Te)})]},Te))})]}),e.jsx(aIn,{listingId:r.id,ownerOnly:U})]}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsx(Yt,{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:((fe=(le=r.agent)==null?void 0:le.name)==null?void 0:fe.charAt(0))||"?"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:((_e=r.agent)==null?void 0:_e.name)||"Unknown"}),((he=(ve=r.agent)==null?void 0:ve.brokerage)==null?void 0:he.name)&&e.jsx("p",{className:"text-sm text-muted-foreground",children:r.agent.brokerage.name})]})]}),!U&&e.jsx("div",{className:"space-y-2",children:((Se=r.agent)==null?void 0:Se.email)&&e.jsx($,{variant:"outline",className:"w-full",asChild:!0,children:e.jsxs("a",{href:`mailto:${r.agent.email}`,children:[e.jsx(pn,{className:"h-4 w-4 mr-2"}),"Email Agent"]})})})]})]}),U&&e.jsx(LIn,{listing:r}),!U&&r.open_to_referrals&&e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsxs(Yt,{className:"text-lg flex items-center gap-2",children:[e.jsx(Xn,{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($,{className:"w-full",onClick:()=>x(!0),children:"Send Referral"})]})]})]})]})]}),e.jsx(zs,{open:!!P,onOpenChange:()=>R(null),children:e.jsx(Rs,{className:"max-w-4xl",children:e.jsx("img",{src:P||"",alt:"Full size",className:"w-full h-auto"})})}),e.jsx(zs,{open:m,onOpenChange:p,children:e.jsxs(Rs,{children:[e.jsxs(Vs,{children:[e.jsx($s,{children:"Delete Listing"}),e.jsx(Cr,{children:"Are you sure you want to delete this listing? This action cannot be undone."})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>p(!1),children:"Cancel"}),e.jsx($,{variant:"destructive",onClick:Y,disabled:u.isPending,children:u.isPending?"Deleting...":"Delete"})]})]})}),e.jsx(zs,{open:g,onOpenChange:x,children:e.jsxs(Rs,{children:[e.jsxs(Vs,{children:[e.jsx($s,{children:"Send Buyer Referral"}),e.jsx(Cr,{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(re,{children:"Buyer Name *"}),e.jsx(be,{value:O.buyerName,onChange:Te=>B({...O,buyerName:Te.target.value}),placeholder:"Enter buyer's name"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Buyer Type"}),e.jsxs(bs,{value:O.buyerType,onValueChange:Te=>B({...O,buyerType:Te}),children:[e.jsx(ys,{children:e.jsx(_s,{placeholder:"Select type"})}),e.jsxs(vs,{children:[e.jsx(We,{value:"first_time",children:"First-Time Buyer"}),e.jsx(We,{value:"investor",children:"Investor"}),e.jsx(We,{value:"relocating",children:"Relocating"}),e.jsx(We,{value:"upgrade",children:"Upgrading"}),e.jsx(We,{value:"downsize",children:"Downsizing"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Notes"}),e.jsx(Ls,{value:O.notes,onChange:Te=>B({...O,notes:Te.target.value}),placeholder:"Any additional information..."})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>x(!1),children:"Cancel"}),e.jsx($,{onClick:se,disabled:h.isPending,children:h.isPending?"Sending...":"Send Referral"})]})]})}),e.jsx(pIn,{open:M,onOpenChange:I,url:`https://listings.relevelup.com/${r.slug||r.id}`,title:r.property_address||`${r.city}, ${r.state}`,fileBase:r.slug||r.property_address||r.city}),e.jsx(Tqt,{open:y,onOpenChange:v,listingId:(r==null?void 0:r.id)||"",listingSlug:(r==null?void 0:r.slug)||null,listingTitle:(r==null?void 0:r.property_address)||`${r==null?void 0:r.city}, ${r==null?void 0:r.state}`}),r&&e.jsx(wIn,{open:_,onOpenChange:j,listing:r}),e.jsx(Kqt,{listingId:(r==null?void 0:r.id)||null,open:C,onOpenChange:A})]})}function FIn({onImport:s}){const[t,n]=k.useState(""),[r,a]=k.useState([]),[i,l]=k.useState(!1),[o,c]=k.useState(!1),[d,u]=k.useState(null),h=k.useRef(),m=k.useRef(null);k.useEffect(()=>{const _=j=>{m.current&&!m.current.contains(j.target)&&c(!1)};return document.addEventListener("mousedown",_),()=>document.removeEventListener("mousedown",_)},[]);const p=async _=>{if(_.trim().length<3){a([]),c(!1);return}l(!0);try{const{data:j,error:C}=await V.functions.invoke("mls-listing-search",{body:{query:_}});if(C)throw C;a((j==null?void 0:j.listings)||[]),c(!0)}catch(j){console.error("MLS search error:",j),a([])}finally{l(!1)}},g=_=>{n(_),h.current&&clearTimeout(h.current),h.current=setTimeout(()=>p(_),400)},x=_=>{u(_.mlsNumber),s(_),c(!1),n(`${_.address}, ${_.city}`),ae.success(`Imported: ${_.address}`,{description:"Property details and photos have been auto-filled."}),u(null)},y=_=>_?`$${_.toLocaleString()}`:"",v=_=>{const j=(_||"").toLowerCase();return j.includes("single")||j.includes("detached")?"Single Family":j.includes("condo")?"Condo":j.includes("town")?"Townhouse":j.includes("land")||j.includes("lot")?"Land":j.includes("multi")?"Multi-Family":j.includes("commercial")?"Commercial":_||"Other"};return e.jsxs(we,{className:"border-primary/30 bg-primary/5",children:[e.jsxs(Vt,{className:"pb-3",children:[e.jsxs(Yt,{className:"text-base flex items-center gap-2",children:[e.jsx(ji,{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:m,className:"relative",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Yr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{value:t,onChange:_=>g(_.target.value),onFocus:()=>r.length>0&&c(!0),placeholder:"Start typing a property address...",className:"pl-9 pr-9"}),i&&e.jsx(Jt,{className:"absolute right-3 top-1/2 -translate-y-1/2 h-4 w-4 animate-spin text-muted-foreground"}),t&&!i&&e.jsx("button",{type:"button",onClick:()=>{n(""),a([]),c(!1)},className:"absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground",children:e.jsx(mr,{className:"h-4 w-4"})})]}),o&&e.jsx("div",{className:"absolute z-50 w-full mt-1 bg-popover border rounded-lg shadow-lg max-h-[400px] overflow-y-auto",children:r.length===0&&!i?e.jsx("div",{className:"p-4 text-center text-sm text-muted-foreground",children:"No properties found. Try a different address."}):r.map(_=>e.jsxs("button",{type:"button",onClick:()=>x(_),disabled:d===_.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:[_.photos[0]?e.jsx("img",{src:_.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(Si,{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:_.address}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[_.city,", ",_.state," ",_.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:y(_.price)}),_.bedrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(Yw,{className:"h-3 w-3"})," ",_.bedrooms]}),_.bathrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(p0,{className:"h-3 w-3"})," ",_.bathrooms]}),_.sqft>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(b3,{className:"h-3 w-3"})," ",_.sqft.toLocaleString()]})]})]}),e.jsxs("div",{className:"flex-shrink-0 flex flex-col items-end gap-1",children:[e.jsx(qe,{variant:"outline",className:"text-[10px]",children:v(_.propertyType)}),_.photos.length>0&&e.jsxs("span",{className:"text-[10px] text-muted-foreground",children:[_.photos.length," photos"]})]})]},_.mlsNumber))})]})})]})}function zIn({photo:s,onRemove:t,onSetPrimary:n}){const{attributes:r,listeners:a,setNodeRef:i,transform:l,transition:o,isDragging:c}=nEe({id:s.id}),d={transform:PM.Transform.toString(l),transition:o};return e.jsxs("div",{ref:i,style:d,className:Ot("relative aspect-square rounded-lg overflow-hidden bg-muted group",c&&"opacity-50 ring-2 ring-primary z-50"),children:[e.jsx("img",{src:s.photo_url,alt:"",className:"w-full h-full object-cover"}),e.jsx("button",{type:"button",...r,...a,className:"absolute top-1 left-1 p-1 bg-black/60 text-white rounded cursor-grab active:cursor-grabbing opacity-0 group-hover:opacity-100 transition-opacity",children:e.jsx(Bp,{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(mr,{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(ri,{className:"h-2.5 w-2.5 fill-current"})," Primary"]}):e.jsx("button",{type:"button",onClick:()=>n(s.id),className:"absolute bottom-1 left-1 text-[10px] bg-black/60 text-white px-1.5 py-0.5 rounded opacity-0 group-hover:opacity-100 transition-opacity hover:bg-black/80",children:"Set as Primary"})]})}function BIn({photos:s,uploading:t,onUpload:n,onRemove:r,onReorder:a,onSetPrimary:i}){const l=KAe(LU(cV,{activationConstraint:{distance:5}})),o=[...s].sort((d,u)=>(d.sort_order??0)-(u.sort_order??0)),c=d=>{const{active:u,over:h}=d;if(!h||u.id===h.id)return;const m=o.findIndex(v=>v.id===u.id),p=o.findIndex(v=>v.id===h.id),g=[...o],[x]=g.splice(m,1);g.splice(p,0,x);const y=g.map((v,_)=>({...v,sort_order:_}));a(y)};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(eEe,{sensors:l,collisionDetection:YAe,onDragEnd:c,children:e.jsx(sEe,{items:o.map(d=>d.id),strategy:Wee,children:e.jsxs("div",{className:"grid grid-cols-3 sm:grid-cols-4 gap-4",children:[o.map(d=>e.jsx(zIn,{photo:d,onRemove:r,onSetPrimary:i},d.id)),e.jsxs("label",{className:"aspect-square rounded-lg border-2 border-dashed border-muted-foreground/25 hover:border-muted-foreground/50 cursor-pointer flex flex-col items-center justify-center gap-2 text-muted-foreground",children:[t?e.jsx(Jt,{className:"h-8 w-8 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(gi,{className:"h-8 w-8"}),e.jsx("span",{className:"text-xs",children:"Upload"})]}),e.jsx("input",{type:"file",accept:"image/*",multiple:!0,className:"hidden",onChange:d=>n(d.target.files),disabled:t})]})]})})})]})}function $In({selectedVideoId:s,onVideoSelect:t,listingId:n}){const r=Jn(),{user:a}=ks(),[i,l]=k.useState(!1),[o,c]=k.useState([]),[d,u]=k.useState(!1),[h,m]=k.useState(null),[p,g]=k.useState({});k.useEffect(()=>{s&&a?x():m(null)},[s,a]);const x=async()=>{if(!s)return;const{data:R,error:O}=await V.from("agent_videos").select("id, bunny_video_id, title, thumbnail_url, preview_url, playback_url, duration_seconds, status, created_at").eq("id",s).eq("is_deleted",!1).single();!O&&R&&(m(R),y(R))},y=async R=>{try{const{data:O,error:B}=await V.functions.invoke("bunny-upload",{body:{action:"asset-urls",videoId:R.bunny_video_id,isAgentVideo:!0}});!B&&(O!=null&&O.thumbnailUrl)&&g(U=>({...U,[R.id]:{thumbnailUrl:O.thumbnailUrl}}))}catch(O){console.warn("Failed to get signed URL",O)}},v=async()=>{if(a){u(!0);try{const{data:R,error:O}=await V.from("agent_videos").select("id, bunny_video_id, title, thumbnail_url, preview_url, playback_url, duration_seconds, status, created_at").eq("owner_user_id",a.id).eq("is_deleted",!1).eq("status","ready").order("created_at",{ascending:!1});if(O)throw O;c(R||[]),R!=null&&R.length&&_(R)}catch(R){console.error("Error fetching videos:",R),ae.error("Failed to load videos")}finally{u(!1)}}},_=async R=>{var O;try{const B=R.map(se=>se.bunny_video_id),{data:U,error:G}=await V.functions.invoke("bunny-upload",{body:{action:"bulk-asset-urls",videoIds:B,isAgentVideo:!0}});if(G)throw G;const H=(U==null?void 0:U.assets)||{},Y={};for(const se of R)(O=H[se.bunny_video_id])!=null&&O.thumbnailUrl&&(Y[se.id]={thumbnailUrl:H[se.bunny_video_id].thumbnailUrl});g(se=>({...se,...Y}))}catch(B){console.warn("Failed to bulk-fetch signed URLs",B)}},j=()=>{l(!0),v()},C=R=>{t(R.id),m(R),l(!1),ae.success("Video selected")},A=()=>{t(null),m(null)},M=()=>{const R=n?`/mission-control/listings/${n}/edit`:"/mission-control/listings/new";r(`/mission-control/video?returnUrl=${encodeURIComponent(R)}`)},I=R=>{if(!R)return"0:00";const O=Math.floor(R/60),B=R%60;return`${O}:${B.toString().padStart(2,"0")}`},P=R=>{var O;return((O=p[R.id])==null?void 0:O.thumbnailUrl)||R.thumbnail_url};return e.jsxs("div",{className:"space-y-3",children:[h?e.jsx(we,{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:[P(h)?e.jsx("img",{src:P(h),alt:h.title||"Video thumbnail",className:"w-full h-full object-cover"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(ia,{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(pu,{className:"h-6 w-6 text-white fill-white"})}),h.duration_seconds&&e.jsx("div",{className:"absolute bottom-1 right-1 bg-black/70 text-white text-[10px] px-1.5 py-0.5 rounded",children:I(h.duration_seconds)})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:h.title||"Untitled Video"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Property Video Tour"})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{type:"button",variant:"outline",size:"sm",onClick:j,children:"Change"}),e.jsx($,{type:"button",variant:"ghost",size:"sm",onClick:A,className:"text-destructive hover:text-destructive",children:e.jsx(mr,{className:"h-4 w-4"})})]})]})})}):e.jsx(we,{className:"border-dashed",children:e.jsx(De,{className:"p-6",children:e.jsxs("div",{className:"text-center",children:[e.jsx(ia,{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($,{type:"button",variant:"outline",onClick:j,className:"gap-2",children:[e.jsx(xb,{className:"h-4 w-4"}),"Select from Library"]}),e.jsxs($,{type:"button",variant:"outline",onClick:M,className:"gap-2",children:[e.jsx(g0,{className:"h-4 w-4"}),"Record New Video"]})]})]})})}),e.jsx(zs,{open:i,onOpenChange:l,children:e.jsxs(Rs,{className:"max-w-2xl max-h-[80vh] overflow-hidden flex flex-col",children:[e.jsx(Vs,{children:e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(xb,{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(Jt,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):o.length===0?e.jsxs("div",{className:"text-center py-12",children:[e.jsx(ia,{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($,{onClick:M,className:"gap-2",children:[e.jsx(g0,{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(R=>e.jsxs("button",{type:"button",onClick:()=>C(R),className:`group relative rounded-lg overflow-hidden border-2 transition-all text-left ${s===R.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:[P(R)?e.jsx("img",{src:P(R),alt:R.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(ia,{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(pu,{className:"h-8 w-8 text-white opacity-0 group-hover:opacity-100 transition-opacity"})}),R.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:I(R.duration_seconds)})]}),e.jsx("div",{className:"p-2 bg-card",children:e.jsx("p",{className:"text-xs font-medium truncate",children:R.title||"Untitled Video"})})]},R.id))})}),e.jsxs("div",{className:"flex justify-between items-center pt-4 border-t",children:[e.jsxs($,{type:"button",variant:"ghost",onClick:M,className:"gap-2",children:[e.jsx(g0,{className:"h-4 w-4"}),"Record New Video"]}),e.jsx($,{type:"button",variant:"outline",onClick:()=>l(!1),children:"Cancel"})]})]})})]})}const UIn=s=>s<1024?`${s} B`:s<1024*1024?`${(s/1024).toFixed(0)} KB`:`${(s/(1024*1024)).toFixed(1)} MB`;function qIn({listingId:s}){const t=k.useRef(null),{data:n=[],isLoading:r}=Rqt(s),a=tIn(),i=sIn(),l=nIn(),o=async d=>{if(!(!d||d.length===0)){for(const u of Array.from(d)){if(u.size>25*1024*1024){ae.error(`${u.name} exceeds 25MB limit`);continue}try{await a.mutateAsync({listingId:s,file:u})}catch(h){ae.error(`Failed to upload ${u.name}: ${h.message}`)}}t.current&&(t.current.value=""),ae.success("Documents uploaded")}},c=async d=>{try{const u=await Dqt(d);window.open(u,"_blank")}catch{ae.error("Failed to open document")}};return e.jsxs("div",{className:"space-y-3",children:[e.jsx("input",{ref:t,type:"file",multiple:!0,accept:".pdf,application/pdf",className:"hidden",onChange:d=>o(d.target.files)}),e.jsxs($,{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(Jt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(gi,{className:"h-4 w-4 mr-2"}),"Upload PDFs (disclosures, etc.)"]}),r?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading..."}):n.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No documents yet. Upload PDFs that other agents can download from your listing."}):e.jsx("div",{className:"space-y-2",children:n.map(d=>e.jsxs(we,{className:"p-3 flex items-center gap-3",children:[e.jsx("div",{className:"p-2 rounded-md bg-primary/10",children:e.jsx(ea,{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:UIn(d.file_size)})]}),e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[d.visible_on_exchange?e.jsx(ba,{className:"h-3 w-3"}):e.jsx(x0,{className:"h-3 w-3"}),e.jsx("span",{className:"hidden sm:inline",children:d.visible_on_exchange?"Visible":"Hidden"}),e.jsx(On,{checked:d.visible_on_exchange,onCheckedChange:u=>l.mutate({id:d.id,visible:u,listingId:s}),className:"ml-1"})]}),e.jsx($,{type:"button",variant:"ghost",size:"icon",onClick:()=>c(d.storage_path),children:e.jsx(ji,{className:"h-4 w-4"})}),e.jsx($,{type:"button",variant:"ghost",size:"icon",onClick:async()=>{await io(`Delete ${d.file_name}?`)&&i.mutate({id:d.id,storage_path:d.storage_path,listingId:s})},children:e.jsx(mr,{className:"h-4 w-4 text-destructive"})})]},d.id))})]})}const VIn=[{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"}],HIn=[{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 GIn({id:s,url:t,index:n,onRemove:r}){const{attributes:a,listeners:i,setNodeRef:l,transform:o,transition:c,isDragging:d}=nEe({id:s}),u={transform:PM.Transform.toString(o),transition:c};return e.jsxs("div",{ref:l,style:u,className:`relative aspect-square rounded-lg overflow-hidden bg-muted group ${d?"opacity-50 ring-2 ring-primary z-50":""}`,children:[e.jsx("img",{src:t,alt:"",className:"w-full h-full object-cover"}),e.jsx("button",{type:"button",...a,...i,className:"absolute top-1 left-1 p-1 bg-black/60 text-white rounded cursor-grab active:cursor-grabbing opacity-0 group-hover:opacity-100 transition-opacity",children:e.jsx(Bp,{className:"h-3.5 w-3.5"})}),e.jsx("button",{type:"button",onClick:()=>r(n),className:"absolute top-1 right-1 p-1 bg-destructive text-destructive-foreground rounded-full hover:bg-destructive/90 opacity-0 group-hover:opacity-100 transition-opacity",children:e.jsx(mr,{className:"h-3 w-3"})}),n===0&&e.jsxs("span",{className:"absolute bottom-1 left-1 text-[10px] bg-primary text-primary-foreground px-1.5 py-0.5 rounded flex items-center gap-0.5",children:[e.jsx(ri,{className:"h-2.5 w-2.5 fill-current"})," Primary"]})]})}function WIn({photoUrls:s,pendingPhotos:t,onRemove:n,onReorder:r,uploading:a,onUpload:i}){const l=KAe(LU(cV,{activationConstraint:{distance:5}})),o=s.map((d,u)=>`pending-${u}`),c=d=>{const{active:u,over:h}=d;if(!h||u.id===h.id)return;const m=o.indexOf(u.id),p=o.indexOf(h.id),g=[...s],x=[...t],[y]=g.splice(m,1),[v]=x.splice(m,1);g.splice(p,0,y),x.splice(p,0,v),r(g,x)};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(eEe,{sensors:l,collisionDetection:YAe,onDragEnd:c,children:e.jsx(sEe,{items:o,strategy:Wee,children:e.jsxs("div",{className:"grid grid-cols-3 sm:grid-cols-4 gap-4",children:[s.map((d,u)=>e.jsx(GIn,{id:o[u],url:d,index:u,onRemove:n},o[u])),e.jsxs("label",{className:"aspect-square rounded-lg border-2 border-dashed border-muted-foreground/25 hover:border-muted-foreground/50 cursor-pointer flex flex-col items-center justify-center gap-2 text-muted-foreground",children:[a?e.jsx(Jt,{className:"h-8 w-8 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(gi,{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 W1t(){const{listingId:s}=oo(),[t]=Jc(),n=t.get("brokerage"),r=Jn(),{user:a}=ks(),{hasLeadSite:i}=Tg(),l=!!s&&s!=="new",o=!!n&&!l,[c,d]=k.useState([]),[u,h]=k.useState({open:!1,listingId:null,nextPath:"/mission-control/listings"}),{data:m,isLoading:p}=gWe(l?s:""),g=oEs(),x=lEs(),y=cEs(),v=dEs(),_=uEs(),j=hEs(),C=mEs(),{data:A=[]}=pt({queryKey:["brokerage-agents",n],queryFn:async()=>{if(!n)return[];const{data:he,error:Se}=await V.from("profiles").select("id, name, email").eq("brokerage_id",n).order("name");if(Se)throw Se;return he||[]},enabled:o}),[M,I]=k.useState(""),[P,R]=k.useState(!1),[O,B]=k.useState([]),[U,G]=k.useState([]),[H,Y]=k.useState(!1),se=async he=>{if(he.size>5*1024*1024){ae.error("Image must be under 5MB");return}Y(!0);try{const Se=he.name.split(".").pop()||"jpg",Te=`${(a==null?void 0:a.id)||"anon"}/co-agents/${Date.now()}.${Se}`,{error:Ie}=await V.storage.from("listing-photos").upload(Te,he,{upsert:!0});if(Ie)throw Ie;const{data:Ue}=V.storage.from("listing-photos").getPublicUrl(Te);oe(Be=>({...Be,co_agent_photo_url:Ue.publicUrl})),ae.success("Headshot uploaded")}catch(Se){ae.error((Se==null?void 0:Se.message)||"Failed to upload headshot")}finally{Y(!1)}},[ee,oe]=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,co_agent_name:"",co_agent_email:"",co_agent_phone:"",co_agent_brokerage:"",co_agent_photo_url:"",allow_sharing:!0,open_to_referrals:!0,open_to_social_promotion:!0,share_with_brokerage:!1,is_public:!0,site_only:!1,show_on_lead_site:!0});k.useEffect(()=>{var he,Se,Te,Ie,Ue;m&&l&&oe({property_address:m.property_address||"",city:m.city||"",state:m.state||"",neighborhood:m.neighborhood||"",price:((he=m.price)==null?void 0:he.toString())||"",property_type:m.property_type,status:m.status,bedrooms:((Se=m.bedrooms)==null?void 0:Se.toString())||"",bathrooms:((Te=m.bathrooms)==null?void 0:Te.toString())||"",square_footage:((Ie=m.square_footage)==null?void 0:Ie.toString())||"",lot_size:m.lot_size||"",year_built:((Ue=m.year_built)==null?void 0:Ue.toString())||"",has_hoa:m.has_hoa,description:m.description||"",agent_notes:m.agent_notes||"",agent_notes_public:m.agent_notes_public,mls_link:m.mls_link||"",video_link:m.video_link||"",video_id:m.video_id||null,co_agent_name:m.co_agent_name||"",co_agent_email:m.co_agent_email||"",co_agent_phone:m.co_agent_phone||"",co_agent_brokerage:m.co_agent_brokerage||"",co_agent_photo_url:m.co_agent_photo_url||"",allow_sharing:m.allow_sharing,open_to_referrals:m.open_to_referrals,open_to_social_promotion:m.open_to_social_promotion,share_with_brokerage:m.share_with_brokerage??!1,is_public:m.is_public,site_only:m.site_only??!1,show_on_lead_site:m.show_on_lead_site??!0})},[m,l]);const me=he=>{var Ue,Be;const Se={"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"},Te=(he.propertyType||"").toLowerCase(),Ie=((Ue=Object.entries(Se).find(([je])=>Te.includes(je)))==null?void 0:Ue[1])||"other";oe(je=>({...je,property_address:he.address||je.property_address,city:he.city||je.city,state:he.state||je.state,price:he.price?String(he.price):je.price,property_type:Ie,bedrooms:he.bedrooms?String(he.bedrooms):je.bedrooms,bathrooms:he.bathrooms?String(he.bathrooms):je.bathrooms,square_footage:he.sqft?String(he.sqft):je.square_footage,lot_size:he.lotSize?String(he.lotSize):je.lot_size,year_built:he.yearBuilt?String(he.yearBuilt):je.year_built,description:he.description||je.description})),((Be=he.photos)==null?void 0:Be.length)>0&&(d(he.photos),U.forEach(je=>URL.revokeObjectURL(je)),B([]),G([]))},Q=he=>{if(!he)return;const Se=Array.from(he);B(Ie=>[...Ie,...Se]);const Te=Se.map(Ie=>URL.createObjectURL(Ie));G(Ie=>[...Ie,...Te])},te=he=>{URL.revokeObjectURL(U[he]),B(Se=>Se.filter((Te,Ie)=>Ie!==he)),G(Se=>Se.filter((Te,Ie)=>Ie!==he))},le=async he=>{var Se;if(!(!he||!m)){R(!0);try{for(const Te of Array.from(he)){const Ie=Te.name.split(".").pop(),Ue=`${a==null?void 0:a.id}/${m.id}/${Date.now()}.${Ie}`,{error:Be}=await V.storage.from("listing-photos").upload(Ue,Te);if(Be)throw Be;const{data:{publicUrl:je}}=V.storage.from("listing-photos").getPublicUrl(Ue);await v.mutateAsync({listingId:m.id,photoUrl:je,isPrimary:!((Se=m.photos)!=null&&Se.length)})}ae.success("Photos uploaded!")}catch(Te){console.error("Upload error:",Te),ae.error("Failed to upload photos")}finally{R(!1)}}},fe=async he=>{for(let Se=0;Se{if(m)try{await _.mutateAsync({photoId:he,listingId:m.id}),ae.success("Photo removed")}catch{ae.error("Failed to remove photo")}},ve=async he=>{if(he.preventDefault(),!ee.city.trim()||!ee.state.trim()||!ee.price){ae.error("Please fill in required fields (City, State, Price)");return}if(o&&!M){ae.error("Please select an agent to assign this listing to");return}try{const Se={property_address:ee.property_address||null,city:ee.city,state:ee.state,neighborhood:ee.neighborhood||null,price:Number(ee.price),property_type:ee.property_type,status:ee.status,bedrooms:ee.bedrooms?Number(ee.bedrooms):null,bathrooms:ee.bathrooms?Number(ee.bathrooms):null,square_footage:ee.square_footage?Number(ee.square_footage):null,lot_size:ee.lot_size||null,year_built:ee.year_built?Number(ee.year_built):null,has_hoa:ee.has_hoa,description:ee.description||null,agent_notes:ee.agent_notes||null,agent_notes_public:ee.agent_notes_public,mls_link:ee.mls_link||null,video_link:ee.video_link||null,video_id:ee.video_id||null,co_agent_name:ee.co_agent_name||null,co_agent_email:ee.co_agent_email||null,co_agent_phone:ee.co_agent_phone||null,co_agent_brokerage:ee.co_agent_brokerage||null,co_agent_photo_url:ee.co_agent_photo_url||null,allow_sharing:ee.allow_sharing,open_to_referrals:ee.open_to_referrals,open_to_social_promotion:ee.open_to_social_promotion,share_with_brokerage:ee.share_with_brokerage,is_public:ee.site_only?!1:ee.is_public,site_only:ee.site_only,show_on_lead_site:ee.site_only?!0:ee.show_on_lead_site};if(l)await y.mutateAsync({id:s,...Se}),ae.success("Listing updated!"),r(`/mission-control/listings/${s}`);else{R(!0);let Te;if(o&&M?Te=await x.mutateAsync({agentId:M,...Se}):Te=await g.mutateAsync(Se),O.length>0)try{await fe(Te.id),U.forEach(Ue=>URL.revokeObjectURL(Ue)),B([]),G([])}catch(Ue){console.error("Photo upload error:",Ue),ae.error("Listing created but some photos failed to upload")}if(c.length>0)try{for(let Ue=0;Uer(o?"/my-brokerage":"/mission-control/listings"),children:[e.jsx(Ia,{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(we,{children:[e.jsx(Vt,{children:e.jsx(Yt,{children:"Assign to Agent *"})}),e.jsxs(De,{children:[e.jsxs(bs,{value:M,onValueChange:I,children:[e.jsx(ys,{children:e.jsx(_s,{placeholder:"Select an agent..."})}),e.jsx(vs,{children:A.map(he=>e.jsx(We,{value:he.id,children:he.name||he.email},he.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(FIn,{onImport:me}),c.length>0&&e.jsxs(we,{className:"border-primary/30 bg-primary/5",children:[e.jsxs(Vt,{className:"pb-3",children:[e.jsxs(Yt,{className:"text-base flex items-center gap-2",children:[e.jsx(ji,{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((he,Se)=>e.jsx("div",{className:"aspect-square rounded overflow-hidden bg-muted",children:e.jsx("img",{src:he,alt:"",className:"w-full h-full object-cover"})},Se)),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($,{type:"button",variant:"ghost",size:"sm",className:"mt-2 text-destructive",onClick:()=>d([]),children:[e.jsx(mr,{className:"h-3 w-3 mr-1"})," Clear MLS photos"]})]})]}),e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsx(Yt,{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(re,{children:"Property Address"}),e.jsx(be,{value:ee.property_address,onChange:he=>oe({...ee,property_address:he.target.value}),placeholder:"123 Main St"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"City *"}),e.jsx(be,{value:ee.city,onChange:he=>oe({...ee,city:he.target.value}),placeholder:"City",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"State *"}),e.jsx(be,{value:ee.state,onChange:he=>oe({...ee,state:he.target.value}),placeholder:"State",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Neighborhood"}),e.jsx(be,{value:ee.neighborhood,onChange:he=>oe({...ee,neighborhood:he.target.value}),placeholder:"Neighborhood"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Price *"}),e.jsx(be,{type:"number",value:ee.price,onChange:he=>oe({...ee,price:he.target.value}),placeholder:"500000",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Property Type"}),e.jsxs(bs,{value:ee.property_type,onValueChange:he=>oe({...ee,property_type:he}),children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsx(vs,{children:HIn.map(he=>e.jsx(We,{value:he.value,children:he.label},he.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Status"}),e.jsxs(bs,{value:ee.status,onValueChange:he=>oe({...ee,status:he}),children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsx(vs,{children:VIn.map(he=>e.jsx(We,{value:he.value,children:he.label},he.value))})]})]})]})})]}),e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsx(Yt,{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(re,{children:"Bedrooms"}),e.jsx(be,{type:"number",value:ee.bedrooms,onChange:he=>oe({...ee,bedrooms:he.target.value}),placeholder:"3"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Bathrooms"}),e.jsx(be,{type:"number",step:"0.5",value:ee.bathrooms,onChange:he=>oe({...ee,bathrooms:he.target.value}),placeholder:"2"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Sq Ft"}),e.jsx(be,{type:"number",value:ee.square_footage,onChange:he=>oe({...ee,square_footage:he.target.value}),placeholder:"2000"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Lot Size"}),e.jsx(be,{value:ee.lot_size,onChange:he=>oe({...ee,lot_size:he.target.value}),placeholder:"0.25 acres"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Year Built"}),e.jsx(be,{type:"number",value:ee.year_built,onChange:he=>oe({...ee,year_built:he.target.value}),placeholder:"2005"})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-6",children:[e.jsx(On,{checked:ee.has_hoa,onCheckedChange:he=>oe({...ee,has_hoa:he})}),e.jsx(re,{children:"Has HOA"})]})]})})]}),e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsx(Yt,{children:"Description & Links"})}),e.jsxs(De,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Description"}),e.jsx(Ls,{value:ee.description,onChange:he=>oe({...ee,description:he.target.value}),placeholder:"Tell the story of this property...",rows:4})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Agent Notes"}),e.jsx(Ls,{value:ee.agent_notes,onChange:he=>oe({...ee,agent_notes:he.target.value}),placeholder:"Notes for other agents...",rows:2}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(On,{checked:ee.agent_notes_public,onCheckedChange:he=>oe({...ee,agent_notes_public:he})}),e.jsx(re,{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(re,{children:"MLS Link"}),e.jsx(be,{value:ee.mls_link,onChange:he=>oe({...ee,mls_link:he.target.value}),placeholder:"https://..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Video Link"}),e.jsx(be,{value:ee.video_link,onChange:he=>oe({...ee,video_link:he.target.value}),placeholder:"YouTube or Vimeo URL"})]})]})]})]}),e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsx(Yt,{children:"Co-Listing Agent (optional)"})}),e.jsxs(De,{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Credit a second agent on this listing. Their info appears on the listing page alongside yours."}),e.jsxs("div",{className:"grid sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Name"}),e.jsx(be,{value:ee.co_agent_name,onChange:he=>oe({...ee,co_agent_name:he.target.value}),placeholder:"Jordan Ellis"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Brokerage"}),e.jsx(be,{value:ee.co_agent_brokerage,onChange:he=>oe({...ee,co_agent_brokerage:he.target.value}),placeholder:"Brokerage name"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Email"}),e.jsx(be,{type:"email",value:ee.co_agent_email,onChange:he=>oe({...ee,co_agent_email:he.target.value}),placeholder:"agent@email.com"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Phone"}),e.jsx(be,{value:ee.co_agent_phone,onChange:he=>oe({...ee,co_agent_phone:he.target.value}),placeholder:"(555) 123-4567"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Headshot"}),e.jsxs("div",{className:"flex items-center gap-4",children:[ee.co_agent_photo_url?e.jsx("img",{src:ee.co_agent_photo_url,alt:"Co-listing agent headshot",className:"h-20 w-20 rounded-full object-cover border"}):e.jsx("div",{className:"h-20 w-20 rounded-full border border-dashed flex items-center justify-center text-muted-foreground",children:e.jsx(gi,{className:"h-5 w-5"})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{id:"co-agent-headshot",type:"file",accept:"image/*",className:"hidden",onChange:he=>{var Te;const Se=(Te=he.target.files)==null?void 0:Te[0];he.target.value="",Se&&se(Se)}}),e.jsx($,{type:"button",variant:"outline",disabled:H,onClick:()=>{var he;return(he=document.getElementById("co-agent-headshot"))==null?void 0:he.click()},children:H?e.jsxs(e.Fragment,{children:[e.jsx(Jt,{className:"h-4 w-4 mr-2 animate-spin"})," Uploading…"]}):e.jsxs(e.Fragment,{children:[e.jsx(gi,{className:"h-4 w-4 mr-2"})," ",ee.co_agent_photo_url?"Replace photo":"Upload photo"]})}),ee.co_agent_photo_url&&e.jsxs($,{type:"button",variant:"ghost",onClick:()=>oe(he=>({...he,co_agent_photo_url:""})),children:[e.jsx(mr,{className:"h-4 w-4 mr-1"})," Remove"]})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"JPG or PNG, up to 5MB."})]})]})]}),e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsxs(Yt,{className:"flex items-center gap-2",children:[e.jsx(ia,{className:"h-5 w-5"}),"Property Video"]})}),e.jsx(De,{children:e.jsx($In,{selectedVideoId:ee.video_id,onVideoSelect:he=>oe({...ee,video_id:he}),listingId:l?s:void 0})})]}),e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsx(Yt,{children:"Photos"})}),e.jsx(De,{children:l&&(m!=null&&m.photos)?e.jsx(BIn,{photos:m.photos,uploading:P,onUpload:he=>le(he),onRemove:he=>_e(he),onReorder:he=>{j.mutate({photos:he.map(Se=>({id:Se.id,sort_order:Se.sort_order,is_primary:Se.is_primary}))})},onSetPrimary:he=>{m&&C.mutate({photoId:he,listingId:m.id})}}):e.jsx(WIn,{photoUrls:U,onRemove:te,onReorder:(he,Se)=>{G(he),B(Se)},pendingPhotos:O,uploading:P,onUpload:Q})})]}),e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsxs(Yt,{className:"flex items-center gap-2",children:[e.jsx(ji,{className:"h-5 w-5"}),"Documents & Disclosures"]})}),e.jsx(De,{children:l&&s?e.jsx(qIn,{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(we,{children:[e.jsx(Vt,{children:e.jsx(Yt,{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(re,{children:"Allow Sharing"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Other agents can share this listing"})]}),e.jsx(On,{checked:ee.allow_sharing,onCheckedChange:he=>oe({...ee,allow_sharing:he})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Open to Referrals"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Accept buyer referrals"})]}),e.jsx(On,{checked:ee.open_to_referrals,onCheckedChange:he=>oe({...ee,open_to_referrals:he})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Social Promotion"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Can be promoted on social media"})]}),e.jsx(On,{checked:ee.open_to_social_promotion,onCheckedChange:he=>oe({...ee,open_to_social_promotion:he})})]}),e.jsxs("div",{className:"flex items-center justify-between pt-2 border-t",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Share with Brokerage"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Visible to agents in your brokerage"})]}),e.jsx(On,{checked:ee.share_with_brokerage,onCheckedChange:he=>oe({...ee,share_with_brokerage:he})})]}),i&&e.jsxs("div",{className:"flex items-center justify-between pt-2 border-t",children:[e.jsxs("div",{children:[e.jsx(re,{children:"My Website Only"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Hide from the Listing Exchange and other agents — only show it on your own website"})]}),e.jsx(On,{checked:ee.site_only,onCheckedChange:he=>oe({...ee,site_only:he,is_public:he?!1:ee.is_public,show_on_lead_site:he?!0:ee.show_on_lead_site,share_with_brokerage:he?!1:ee.share_with_brokerage})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Make Public"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Publish on listings.relevelup.com to get leads"})]}),e.jsx(On,{checked:ee.is_public,disabled:ee.site_only,onCheckedChange:he=>oe({...ee,is_public:he})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Show on My Website"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Feature this listing on your lead site homepage"})]}),e.jsx(On,{checked:ee.show_on_lead_site,onCheckedChange:he=>oe({...ee,show_on_lead_site:he})})]})]})]}),e.jsx($,{type:"submit",className:"w-full",size:"lg",disabled:g.isPending||y.isPending,children:g.isPending||y.isPending?e.jsxs(e.Fragment,{children:[e.jsx(Jt,{className:"h-4 w-4 mr-2 animate-spin"}),"Saving..."]}):l?"Update Listing":"Create Listing"})]})]})]}),e.jsx(Kqt,{listingId:u.listingId,open:u.open,onOpenChange:he=>{if(!he){const{nextPath:Se}=u;h({open:!1,listingId:null,nextPath:Se}),r(Se)}}})]})}const QUe=[{key:"stats",label:"Stats strip",hint:"Beds, baths, sqft, lot, year"},{key:"story",label:"The Story",hint:"Property description"},{key:"agent_note",label:"Agent note",hint:"Personal note callout"},{key:"gallery",label:"Photo gallery",hint:"Bento gallery + lightbox"},{key:"video",label:"Video tour",hint:"Uses the linked video"},{key:"map",label:"Location map",hint:"Neighborhood map"},{key:"payment",label:"Payment calc",hint:"Interactive mortgage estimator"},{key:"agent_card",label:"Agent card",hint:"Your info + contact form"}],Qqt=[{type:"extra_video",label:"Extra Video / Reel",icon:ia,desc:"Add a YouTube, Vimeo, or MP4 embed",accent:"from-rose-500/20 to-rose-500/5"},{type:"tour_3d",label:"3D Tour",icon:wK,desc:"Matterport, iGuide, or Kuula embed",accent:"from-indigo-500/20 to-indigo-500/5"},{type:"floor_plans",label:"Floor Plans",icon:zc,desc:"Upload floor plan images",accent:"from-sky-500/20 to-sky-500/5"},{type:"testimonial",label:"Testimonial",icon:ik,desc:"A quote from a past client",accent:"from-amber-500/20 to-amber-500/5"},{type:"countdown",label:"Offer Countdown",icon:sa,desc:'"Offers due Friday 5pm"',accent:"from-emerald-500/20 to-emerald-500/5"},{type:"custom_cta",label:"Custom CTA Button",icon:od,desc:"Link to a brochure or booking page",accent:"from-violet-500/20 to-violet-500/5"}],KIn=["#0f172a","#406E71","#c9a84c","#b91c1c","#0d7a5f","#4f46e5","#e85d3a","#111827"],UDe={sections:Object.fromEntries(QUe.map(s=>[s.key,!0])),hero_style:"photo",accent_color:null,custom_note:"",addons:[]},YIn=()=>Math.random().toString(36).slice(2,10);function ZIn(){const{listingId:s}=oo(),t=Jn(),{user:n}=ks(),r=ls(),[a,i]=k.useState("desktop"),[l,o]=k.useState(UDe),[c,d]=k.useState(!1),[u,h]=k.useState(0),{data:m,isLoading:p}=pt({queryKey:["listing-customize",s],queryFn:async()=>{const{data:O,error:B}=await V.from("listings").select("id, agent_id, slug, property_address, city, state, price, page_config, page_theme").eq("id",s).single();if(B)throw B;return O},enabled:!!s});k.useEffect(()=>{var O,B;m!=null&&m.page_config&&o({...UDe,...m.page_config||{},sections:{...UDe.sections,...((O=m.page_config)==null?void 0:O.sections)||{}},addons:((B=m.page_config)==null?void 0:B.addons)||[]})},[m==null?void 0:m.id]);const g=!!n&&!!m&&n.id===m.agent_id,x=k.useMemo(()=>m?`/public/listing/${m.slug||m.id}?preview=1&t=${u}`:"",[m,u]),y=k.useMemo(()=>m?`https://listings.relevelup.com/${m.slug||m.id}`:"",[m]),v=Nt({mutationFn:async()=>{const{error:O}=await V.from("listings").update({page_config:l}).eq("id",s);if(O)throw O},onSuccess:()=>{ae.success("Saved. Your public page is live."),d(!1),r.invalidateQueries({queryKey:["listing-customize",s]}),r.invalidateQueries({queryKey:["public-listing"]}),h(O=>O+1)},onError:O=>ae.error(`Save failed: ${O.message||"Try again"}`)}),_=O=>{o(B=>({...B,...O})),d(!0)},j=(O,B)=>_({sections:{...l.sections||{},[O]:B}}),C=O=>_({addons:[...l.addons||[],{id:YIn(),type:O,data:{}}]}),A=(O,B)=>_({addons:(l.addons||[]).map(U=>U.id===O?{...U,data:{...U.data,...B}}:U)}),M=O=>_({addons:(l.addons||[]).filter(B=>B.id!==O)}),I=(O,B)=>{const U=[...l.addons||[]],G=U.findIndex(Y=>Y.id===O);if(G<0)return;const H=G+B;H<0||H>=U.length||([U[G],U[H]]=[U[H],U[G]],_({addons:U}))};if(p)return e.jsx(Xs,{title:"",description:"",children:e.jsx("div",{className:"p-8 text-sm text-muted-foreground",children:"Loading…"})});if(!m)return e.jsx(Xs,{title:"",description:"",children:e.jsx("div",{className:"p-8",children:"Listing not found."})});if(!g)return e.jsx(Xs,{title:"",description:"",children:e.jsxs("div",{className:"p-8",children:[e.jsx("p",{children:"You can only customize your own listing pages."}),e.jsx($,{className:"mt-3",onClick:()=>t(`/mission-control/listings/${m.id}`),children:"Back"})]})});const P=(l.addons||[]).length,R=Object.values(l.sections||{}).filter(Boolean).length;return e.jsxs(Xs,{title:"",description:"",children:[e.jsxs("div",{className:"sticky top-0 z-30 -mx-4 sm:-mx-6 px-4 sm:px-6 py-3 bg-background/85 backdrop-blur border-b flex items-center gap-3",children:[e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>t(`/mission-control/listings/${m.id}`),children:[e.jsx(Ia,{className:"h-4 w-4 mr-1.5"})," Back"]}),e.jsxs("div",{className:"hidden md:flex flex-col leading-tight",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-widest text-muted-foreground",children:"Customize Public Page"}),e.jsx("p",{className:"text-sm font-medium truncate max-w-[420px]",children:m.property_address||`${m.city}, ${m.state}`})]}),e.jsxs("div",{className:"ml-auto flex items-center gap-2",children:[c&&e.jsx("span",{className:"text-xs text-amber-600 hidden sm:inline",children:"Unsaved changes"}),e.jsxs("div",{className:"hidden md:inline-flex rounded-lg border bg-muted p-0.5",children:[e.jsxs("button",{onClick:()=>i("desktop"),className:`h-8 px-2.5 rounded-md text-xs flex items-center gap-1.5 ${a==="desktop"?"bg-background shadow-sm":"text-muted-foreground"}`,children:[e.jsx(j2,{className:"h-3.5 w-3.5"})," Desktop"]}),e.jsxs("button",{onClick:()=>i("mobile"),className:`h-8 px-2.5 rounded-md text-xs flex items-center gap-1.5 ${a==="mobile"?"bg-background shadow-sm":"text-muted-foreground"}`,children:[e.jsx(yb,{className:"h-3.5 w-3.5"})," Mobile"]})]}),e.jsxs($,{variant:"outline",size:"sm",onClick:()=>h(O=>O+1),children:[e.jsx(yo,{className:"h-3.5 w-3.5 mr-1.5"})," Refresh"]}),e.jsx($,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("a",{href:y,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(Ir,{className:"h-3.5 w-3.5 mr-1.5"})," Open live"]})}),e.jsx($,{size:"sm",onClick:()=>v.mutate(),disabled:!c||v.isPending,children:v.isPending?"Saving…":e.jsxs(e.Fragment,{children:[e.jsx(Ml,{className:"h-3.5 w-3.5 mr-1.5"})," Save & Publish"]})})]})]}),e.jsxs("div",{className:"grid lg:grid-cols-[minmax(360px,440px)_1fr] gap-6 mt-4",children:[e.jsx(Eo,{className:"lg:h-[calc(100vh-140px)] pr-2",children:e.jsxs("div",{className:"space-y-6 pb-16",children:[e.jsx(qG,{icon:e.jsx(kn,{className:"h-4 w-4"}),title:"Hero",desc:"What visitors see first",children:e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Hero style"}),e.jsx("div",{className:"mt-2 grid grid-cols-3 gap-2",children:["photo","video","slideshow"].map(O=>e.jsx("button",{onClick:()=>_({hero_style:O}),className:`text-xs rounded-lg border py-3 capitalize transition ${l.hero_style===O?"border-primary bg-primary/5 text-primary font-medium":"border-border hover:bg-muted"}`,children:O},O))})]})}),e.jsx(qG,{icon:e.jsx(gd,{className:"h-4 w-4"}),title:"Accent color",desc:"Highlights on the public page",children:e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("button",{onClick:()=>_({accent_color:null}),className:`h-9 px-3 rounded-full text-xs border ${l.accent_color?"border-border hover:bg-muted":"border-primary bg-primary/5 text-primary"}`,children:"Default"}),KIn.map(O=>e.jsx("button",{onClick:()=>_({accent_color:O}),className:`h-9 w-9 rounded-full border-2 transition ${l.accent_color===O?"ring-2 ring-offset-2 ring-primary border-white":"border-white/20"}`,style:{background:O},"aria-label":O},O))]})}),e.jsx(qG,{icon:e.jsx(vf,{className:"h-4 w-4"}),title:"Personal note",desc:"Shows in a beautiful callout on the public page",children:e.jsx(Ls,{value:l.custom_note||"",onChange:O=>_({custom_note:O.target.value}),placeholder:"Why we love this home… (optional)",rows:3})}),e.jsx(qG,{icon:e.jsx(jC,{className:"h-4 w-4"}),title:"Page sections",desc:"Toggle any default section on or off",rightLabel:`${R} of ${QUe.length} on`,children:e.jsx("div",{className:"divide-y rounded-xl border",children:QUe.map(O=>{var U;const B=((U=l.sections)==null?void 0:U[O.key])!==!1;return e.jsxs("div",{className:"flex items-center justify-between p-3.5",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium",children:O.label}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:O.hint})]}),e.jsx(On,{checked:B,onCheckedChange:G=>j(O.key,G)})]},O.key)})})}),e.jsxs(qG,{icon:e.jsx(nn,{className:"h-4 w-4"}),title:"Add-on modules",desc:"Drop in extras to make this page unique",rightLabel:P?`${P} added`:void 0,children:[e.jsx("div",{className:"grid grid-cols-2 gap-2",children:Qqt.map(O=>e.jsxs("button",{onClick:()=>C(O.type),className:`group text-left rounded-xl border p-3 hover:shadow-md transition bg-gradient-to-br ${O.accent}`,children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("div",{className:"h-7 w-7 rounded-md bg-background border flex items-center justify-center",children:e.jsx(O.icon,{className:"h-3.5 w-3.5"})}),e.jsx("span",{className:"text-sm font-medium",children:O.label})]}),e.jsx("p",{className:"text-[11px] text-muted-foreground leading-snug",children:O.desc})]},O.type))}),(l.addons||[]).length>0&&e.jsxs("div",{className:"mt-4 space-y-3",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-widest text-muted-foreground",children:"On this page · drag to reorder"}),(l.addons||[]).map((O,B)=>e.jsx(XIn,{addon:O,onChange:U=>A(O.id,U),onRemove:()=>M(O.id),onMoveUp:B>0?()=>I(O.id,-1):void 0,onMoveDown:BI(O.id,1):void 0},O.id))]})]}),e.jsx("div",{className:"lg:hidden",children:e.jsx($,{className:"w-full",onClick:()=>v.mutate(),disabled:!c||v.isPending,children:v.isPending?"Saving…":e.jsxs(e.Fragment,{children:[e.jsx(Ml,{className:"h-4 w-4 mr-1.5"})," Save & Publish"]})})})]})}),e.jsx("div",{className:"lg:h-[calc(100vh-140px)]",children:e.jsxs(we,{className:"h-full overflow-hidden bg-neutral-100 p-4 lg:p-6 border rounded-2xl",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx(ba,{className:"h-3.5 w-3.5"}),"Live preview",c&&e.jsx(qe,{variant:"outline",className:"text-[10px] border-amber-400 text-amber-700 bg-amber-50 ml-1",children:"Save to update"}),!c&&e.jsxs("span",{className:"inline-flex items-center gap-1 text-emerald-600 ml-1",children:[e.jsx(ma,{className:"h-3 w-3"})," In sync"]})]}),e.jsxs("div",{className:"lg:hidden inline-flex rounded-lg border bg-background p-0.5",children:[e.jsx("button",{onClick:()=>i("desktop"),className:`h-7 px-2 rounded ${a==="desktop"?"bg-muted":""}`,children:e.jsx(j2,{className:"h-3.5 w-3.5"})}),e.jsx("button",{onClick:()=>i("mobile"),className:`h-7 px-2 rounded ${a==="mobile"?"bg-muted":""}`,children:e.jsx(yb,{className:"h-3.5 w-3.5"})})]})]}),e.jsx("div",{className:"h-[calc(100%-32px)] w-full flex items-start justify-center overflow-auto",children:e.jsx("div",{className:`bg-neutral-950 rounded-xl shadow-2xl overflow-hidden transition-all mx-auto ${a==="mobile"?"w-[390px] h-[800px]":"w-full h-full min-h-[720px]"}`,children:e.jsx("iframe",{src:x,title:"Preview",className:"w-full h-full border-0"},u)})})]})})]})]})}function qG({icon:s,title:t,desc:n,rightLabel:r,children:a}){return e.jsxs("div",{className:"rounded-2xl border bg-card p-5",children:[e.jsxs("div",{className:"flex items-start justify-between mb-4",children:[e.jsxs("div",{className:"flex items-start gap-2.5",children:[e.jsx("div",{className:"h-8 w-8 rounded-lg bg-primary/10 text-primary flex items-center justify-center shrink-0",children:s}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-semibold leading-tight",children:t}),n&&e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:n})]})]}),r&&e.jsx("span",{className:"text-[10px] uppercase tracking-widest text-muted-foreground",children:r})]}),e.jsx("div",{className:"space-y-3",children:a})]})}function XIn({addon:s,onChange:t,onRemove:n,onMoveUp:r,onMoveDown:a}){const i=Qqt.find(o=>o.type===s.type),l=i.icon;return e.jsxs("div",{className:"rounded-xl border bg-background p-3.5",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx("div",{className:"flex flex-col -my-1",children:e.jsx("button",{onClick:r,disabled:!r,className:"text-muted-foreground/50 hover:text-foreground disabled:opacity-30 leading-none",children:e.jsx(Bp,{className:"h-3.5 w-3.5"})})}),e.jsx("div",{className:"h-7 w-7 rounded-md bg-primary/10 text-primary flex items-center justify-center",children:e.jsx(l,{className:"h-3.5 w-3.5"})}),e.jsx("p",{className:"text-sm font-medium flex-1",children:i.label}),e.jsxs("div",{className:"flex items-center gap-1",children:[a&&e.jsx($,{size:"icon",variant:"ghost",className:"h-7 w-7",onClick:a,"aria-label":"Move down",children:e.jsx(Bp,{className:"h-3.5 w-3.5 rotate-180"})}),e.jsx($,{size:"icon",variant:"ghost",className:"h-7 w-7 text-destructive hover:text-destructive",onClick:n,"aria-label":"Remove",children:e.jsx(Un,{className:"h-3.5 w-3.5"})})]})]}),s.type==="extra_video"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-xs",children:"Video URL"}),e.jsx(be,{placeholder:"https://youtu.be/…",value:s.data.url||"",onChange:o=>t({url:o.target.value})}),e.jsx(re,{className:"text-xs",children:"Title (optional)"}),e.jsx(be,{placeholder:"e.g. Sunset drone flyover",value:s.data.title||"",onChange:o=>t({title:o.target.value})})]}),s.type==="tour_3d"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-xs",children:"3D tour embed URL"}),e.jsx(be,{placeholder:"https://my.matterport.com/show/?m=…",value:s.data.url||"",onChange:o=>t({url:o.target.value})})]}),s.type==="floor_plans"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-xs",children:"Floor plan image URLs (one per line)"}),e.jsx(Ls,{rows:3,placeholder:`https://…/floor1.jpg https://…/floor2.jpg`,value:(s.data.urls||[]).join(` `),onChange:o=>t({urls:o.target.value.split(` `).map(c=>c.trim()).filter(Boolean)})})]}),s.type==="testimonial"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-xs",children:"Quote"}),e.jsx(Ls,{rows:3,placeholder:`"Best home-buying experience we've ever had."`,value:s.data.quote||"",onChange:o=>t({quote:o.target.value})}),e.jsx(re,{className:"text-xs",children:"Attribution"}),e.jsx(be,{placeholder:"Sarah & Mike, past clients",value:s.data.author||"",onChange:o=>t({author:o.target.value})})]}),s.type==="countdown"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-xs",children:"Headline"}),e.jsx(be,{placeholder:"Offers due",value:s.data.headline||"",onChange:o=>t({headline:o.target.value})}),e.jsx(re,{className:"text-xs",children:"Deadline (date & time)"}),e.jsx(be,{type:"datetime-local",value:s.data.deadline||"",onChange:o=>t({deadline:o.target.value})})]}),s.type==="custom_cta"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-xs",children:"Button label"}),e.jsx(be,{placeholder:"Download brochure",value:s.data.label||"",onChange:o=>t({label:o.target.value})}),e.jsx(re,{className:"text-xs",children:"Link URL"}),e.jsx(be,{placeholder:"https://…",value:s.data.url||"",onChange:o=>t({url:o.target.value})})]})]})}const Jqt="teleprompter_settings",qDe={scrollSpeed:30,fontSize:24,lineHeight:1.6,opacity:.85,position:"top",isMirrored:!1};function QIn(){try{const s=localStorage.getItem(Jqt);return s?{...qDe,...JSON.parse(s)}:qDe}catch{return qDe}}function JIn(s){try{localStorage.setItem(Jqt,JSON.stringify(s))}catch{}}function uQe({text:s,isVisible:t,onToggleVisibility:n,isRecording:r=!1,startCountdown:a=!1,onCountdownComplete:i,className:l}){const o=k.useRef(null),c=k.useRef(null),d=k.useRef(0),u=k.useRef(0),[h,m]=k.useState(QIn),{scrollSpeed:p,fontSize:g,lineHeight:x,opacity:y,position:v,isMirrored:_}=h,j=k.useCallback((U,G)=>{m(H=>{const Y={...H,[U]:G};return JIn(Y),Y})},[]),[C,A]=k.useState(!1),[M,I]=k.useState(null),P=k.useCallback(U=>{if(!o.current)return;d.current===0&&(d.current=U);const G=U-d.current;d.current=U,u.current+=p*G/1e3;const H=Math.floor(u.current);H>0&&(o.current.scrollTop+=H,u.current-=H);const{scrollTop:Y,scrollHeight:se,clientHeight:ee}=o.current;if(Y+ee>=se){A(!1);return}c.current=requestAnimationFrame(P)},[p]);k.useEffect(()=>(C?(d.current=0,u.current=0,c.current=requestAnimationFrame(P)):c.current&&cancelAnimationFrame(c.current),()=>{c.current&&cancelAnimationFrame(c.current)}),[C,P]),k.useEffect(()=>{if(r&&t)if(o.current&&(o.current.scrollTop=0),a){I(3);let U=3;const G=setInterval(()=>{U-=1,U<=0?(clearInterval(G),I(null),i==null||i(),A(!0)):I(U)},1e3);return()=>clearInterval(G)}else setTimeout(()=>A(!0),100);else r||(A(!1),I(null))},[r,t,a,i]);const R=k.useCallback(()=>{o.current&&(o.current.scrollTop=0),A(!1)},[]),O=k.useCallback(()=>{A(U=>!U)},[]);if(!t)return e.jsx("div",{className:Ot("absolute top-4 right-4 pointer-events-auto z-10",l),children:e.jsxs($,{variant:"secondary",size:"sm",onClick:n,className:"bg-black/50 hover:bg-black/70 text-white border-0",children:[e.jsx(ba,{className:"h-4 w-4 mr-2"}),"Show Script"]})});const B={top:"top-0 pt-16",center:"top-1/2 -translate-y-1/2",bottom:"bottom-0 pb-24"};return e.jsxs("div",{className:Ot("absolute inset-0 pointer-events-none",l),children:[M!==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:M},M),e.jsx("p",{className:"text-white/80 text-lg font-medium drop-shadow-md",children:"Get ready…"})]})}),e.jsx("div",{className:Ot("absolute left-0 right-0 h-[60%] overflow-hidden pointer-events-auto",B[v],M!==null&&"opacity-30"),style:{opacity:M!==null?.3:y},children:e.jsxs("div",{ref:o,className:Ot("mx-auto max-w-2xl px-6 overflow-y-auto scrollbar-hide h-full",_&&"scale-x-[-1]"),style:{maskImage:"linear-gradient(to bottom, transparent, black 10%, black 90%, transparent)",WebkitMaskImage:"linear-gradient(to bottom, transparent, black 10%, black 90%, transparent)"},children:[e.jsx("div",{className:"h-full",style:{minHeight:"100%"}}),e.jsx("p",{className:"text-white text-center font-medium drop-shadow-lg",style:{fontSize:`${g}px`,lineHeight:x,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(Xc,{children:[e.jsx(Qc,{asChild:!0,children:e.jsx($,{variant:"secondary",size:"icon",className:"h-9 w-9 bg-black/50 hover:bg-black/70 text-white border-0",children:e.jsx(Yc,{className:"h-4 w-4"})})}),e.jsx(Bc,{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(re,{className:"text-xs",children:"Scroll Speed"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:p})]}),e.jsx(sx,{value:[p],onValueChange:([U])=>j("scrollSpeed",U),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(re,{className:"text-xs",children:"Font Size"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[g,"px"]})]}),e.jsx(sx,{value:[g],onValueChange:([U])=>j("fontSize",U),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(re,{className:"text-xs",children:"Line Spacing"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:x.toFixed(1)})]}),e.jsx(sx,{value:[x*10],onValueChange:([U])=>j("lineHeight",U/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(re,{className:"text-xs",children:"Opacity"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[Math.round(y*100),"%"]})]}),e.jsx(sx,{value:[y*100],onValueChange:([U])=>j("opacity",U/100),min:30,max:100,step:5})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-xs",children:"Position"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx($,{variant:v==="top"?"default":"outline",size:"sm",onClick:()=>j("position","top"),children:e.jsx(Ny,{className:"h-4 w-4"})}),e.jsx($,{variant:v==="center"?"default":"outline",size:"sm",onClick:()=>j("position","center"),children:e.jsx(ak,{className:"h-4 w-4"})}),e.jsx($,{variant:v==="bottom"?"default":"outline",size:"sm",onClick:()=>j("position","bottom"),children:e.jsx(Go,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(re,{className:"text-xs",children:"Mirror Mode"}),e.jsx(On,{checked:_,onCheckedChange:U=>j("isMirrored",U)})]})]})})]}),e.jsx($,{variant:"secondary",size:"icon",onClick:O,className:"h-9 w-9 bg-black/50 hover:bg-black/70 text-white border-0",children:C?e.jsx(uv,{className:"h-4 w-4"}):e.jsx(pu,{className:"h-4 w-4"})}),e.jsx($,{variant:"secondary",size:"icon",onClick:R,className:"h-9 w-9 bg-black/50 hover:bg-black/70 text-white border-0",children:e.jsx(jm,{className:"h-4 w-4"})}),e.jsxs($,{variant:"secondary",size:"sm",onClick:n,className:"bg-black/50 hover:bg-black/70 text-white border-0",children:[e.jsx(x0,{className:"h-4 w-4 mr-2"}),"Hide"]})]})]})}function eLn({onSelectScript:s,onCreateNew:t,selectedScriptId:n,className:r}){const{toast:a}=Fi(),[i,l]=k.useState(""),[o,c]=k.useState(null),[d,u]=k.useState("levelup"),{data:h,isLoading:m}=RSn(),{data:p,isLoading:g}=DSn(),{data:x,isLoading:y}=OSn(),v=FSn(),_=k.useMemo(()=>p?p.filter(I=>{const P=!i||I.title.toLowerCase().includes(i.toLowerCase())||I.script_text.toLowerCase().includes(i.toLowerCase())||I.tags.some(O=>O.toLowerCase().includes(i.toLowerCase())),R=!o||I.category_id===o;return P&&R}):[],[p,i,o]),j=k.useMemo(()=>x?x.filter(I=>!i||I.title.toLowerCase().includes(i.toLowerCase())||I.script_text.toLowerCase().includes(i.toLowerCase())):[],[x,i]),C=I=>{s({title:I.title,text:I.script_text})},A=async I=>{try{await v.mutateAsync(I),a({title:"Script saved to My Scripts"})}catch{a({title:"Failed to save script",variant:"destructive"})}},M=m||g||y;return e.jsxs("div",{className:Ot("flex flex-col h-full",r),children:[e.jsx("div",{className:"p-4 border-b",children:e.jsxs("div",{className:"relative",children:[e.jsx(Yr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search scripts...",value:i,onChange:I=>l(I.target.value),className:"pl-9"})]})}),e.jsxs(ya,{value:d,onValueChange:I=>u(I),className:"flex-1 flex flex-col",children:[e.jsxs(va,{className:"mx-4 mt-4 grid grid-cols-2",children:[e.jsxs(is,{value:"levelup",children:[e.jsx(ea,{className:"h-4 w-4 mr-2"}),"LevelUp Scripts"]}),e.jsxs(is,{value:"my-scripts",children:[e.jsx(jy,{className:"h-4 w-4 mr-2"}),"My Scripts"]})]}),e.jsxs(cs,{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(qe,{variant:o?"outline":"default",className:"cursor-pointer",onClick:()=>c(null),children:"All"}),h==null?void 0:h.map(I=>e.jsx(qe,{variant:o===I.id?"default":"outline",className:"cursor-pointer",onClick:()=>c(I.id),children:I.name},I.id))]}),e.jsx(Eo,{className:"flex-1 max-h-[50vh]",children:M?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(Jt,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):_.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(ea,{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:_.map(I=>e.jsxs(we,{className:Ot("cursor-pointer hover:bg-accent/50 transition-colors",n===I.id&&"ring-2 ring-primary"),onClick:()=>C(I),children:[e.jsx(Vt,{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(Yt,{className:"text-sm font-medium truncate",children:I.title}),I.category&&e.jsx(qe,{variant:"secondary",className:"mt-1 text-xs",children:I.category.name})]}),e.jsxs("div",{className:"flex items-center gap-1 ml-2",children:[e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:P=>{P.stopPropagation(),A(I)},children:e.jsx(jy,{className:"h-4 w-4"})}),e.jsx(fi,{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:I.script_text})})]},I.id))})})]}),e.jsxs(cs,{value:"my-scripts",className:"flex-1 flex flex-col mt-0 p-4",children:[t&&e.jsxs($,{variant:"outline",className:"mb-4",onClick:t,children:[e.jsx(nn,{className:"h-4 w-4 mr-2"}),"Create New Script"]}),e.jsx(Eo,{className:"flex-1 max-h-[50vh]",children:y?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(Jt,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):j.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(jy,{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:j.map(I=>e.jsxs(we,{className:Ot("cursor-pointer hover:bg-accent/50 transition-colors",n===I.id&&"ring-2 ring-primary"),onClick:()=>C(I),children:[e.jsx(Vt,{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(Yt,{className:"text-sm font-medium truncate",children:I.title}),e.jsx("div",{className:"flex items-center gap-2 mt-1",children:I.is_custom?e.jsx(qe,{variant:"outline",className:"text-xs",children:"Custom"}):e.jsx(qe,{variant:"secondary",className:"text-xs",children:"Saved"})})]}),e.jsx(fi,{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:I.script_text})})]},I.id))})})]})]})]})}function tLn({selectedTemplate:s,onSelect:t,contactName:n,saving:r=!1}){const[a,i]=k.useState(()=>{const o=SB(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(re,{className:"text-sm font-medium",children:"Share Page Template"}),r&&e.jsx(Jt,{className:"h-3 w-3 animate-spin text-muted-foreground"})]}),e.jsx("div",{className:"space-y-3",children:Y3s.map(o=>{const c=Z3s(o.id),d=a.has(o.id),u=c.some(h=>h.id===s);return e.jsxs(h1,{open:d,onOpenChange:()=>l(o.id),children:[e.jsxs(m1,{className:"flex items-center justify-between w-full p-2.5 rounded-lg bg-muted/50 hover:bg-muted transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-medium text-sm",children:o.name}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["(",c.length,")"]}),u&&!d&&e.jsx("span",{className:"text-xs bg-primary/10 text-primary px-1.5 py-0.5 rounded-full",children:"✓"})]}),e.jsx(Go,{className:Ot("h-4 w-4 text-muted-foreground transition-transform",d&&"rotate-180")})]}),e.jsx(f1,{className:"pt-2",children:e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-2",children:c.map(h=>{const m=s===h.id;return e.jsxs("button",{type:"button",onClick:()=>t(h.id),disabled:r,className:Ot("relative rounded-lg border-2 p-2.5 text-left transition-all hover:shadow-sm disabled:opacity-50 disabled:cursor-not-allowed",m?"border-primary ring-1 ring-primary/20 bg-primary/5":"border-muted hover:border-muted-foreground/30"),children:[m&&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(ma,{className:"h-2.5 w-2.5 text-primary-foreground"})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"opacity-70 shrink-0",children:h.icon}),e.jsx("span",{className:"text-sm font-medium truncate",children:h.name})]})]},h.id)})})})]},o.id)})}),n&&s!=="default"&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:['Will show: "',SB(s).headerText(n),'"']})]})}function eVt({open:s,onOpenChange:t,video:n,contactName:r,onTemplateUpdated:a}){const[i,l]=k.useState(n.page_template||"default"),[o,c]=k.useState(!1),[d,u]=k.useState(!1),[h,m]=k.useState(n.page_template||"default"),[p,g]=k.useState([]),[x,y]=k.useState(n.contact_id&&r?{id:n.contact_id,name:r,email:null}:null),[v,_]=k.useState(!1),[j,C]=k.useState(!1),A=n.share_token?`https://video.relevelup.com/${n.share_token}`:"";k.useEffect(()=>{s&&p.length===0&&M()},[s]);const M=async()=>{C(!0);try{const{data:Y,error:se}=await V.from("innercircle_contacts").select("id, first_name, last_name, email").order("first_name",{ascending:!0}).limit(500);if(se)throw se;const ee=(Y||[]).map(oe=>({id:oe.id,name:[oe.first_name,oe.last_name].filter(Boolean).join(" ")||"Unnamed",email:oe.email||null}));g(ee)}catch(Y){console.error("Failed to fetch contacts:",Y)}finally{C(!1)}},I=async Y=>{y(Y),_(!1),c(!0);try{const{error:se}=await V.from("agent_videos").update({contact_id:(Y==null?void 0:Y.id)||null,recipient_name:(Y==null?void 0:Y.name)||null}).eq("id",n.id);if(se)throw se;ae.success(Y?`Assigned to ${Y.name}`:"Contact removed"),a==null||a()}catch(se){console.error("Failed to update contact:",se),ae.error("Failed to update contact")}finally{c(!1)}},P=async Y=>{l(Y),c(!0);try{const{error:se}=await V.from("agent_videos").update({page_template:Y}).eq("id",n.id);if(se)throw se;m(Y),ae.success("Template saved!"),a==null||a()}catch(se){console.error("Failed to save template:",se),ae.error("Failed to save template"),l(h)}finally{c(!1)}},R=(x==null?void 0:x.name)||null,O=()=>{const Y=n.title||"Video Message",se=n.share_token?`https://video.relevelup.com/thumb/${n.share_token}`:n.thumbnail_url||"";return``},B=async()=>{if(!n.thumbnail_url){ae.error("Video thumbnail not available yet");return}const Y=O(),se=`Watch: ${n.title||"Video Message"} ${A}`;try{const ee=new Blob([Y],{type:"text/html"}),oe=new Blob([se],{type:"text/plain"}),me=new ClipboardItem({"text/html":ee,"text/plain":oe});await navigator.clipboard.write([me]),ae.success("Copied! Paste into Gmail - the thumbnail will appear after sending.")}catch{await navigator.clipboard.writeText(se+` `+Y),ae.success("Copied! Paste into your email.")}},U=async()=>{await navigator.clipboard.writeText(A),u(!0),ae.success("Share link copied!"),setTimeout(()=>u(!1),2e3)},G=()=>{const se=SB(i).headerText(R),ee=i==="default"?`Check out this video: ${A}`:`${se} Check out this special video: ${A}`;window.open(`sms:?body=${encodeURIComponent(ee)}`,"_self")},H=()=>{const Y=SB(i),se=Y.headerText(R),ee=i==="default"?n.title||"Video Message":se,oe=`${Y.subText} Watch the video: ${A}`,me=x!=null&&x.email?encodeURIComponent(x.email):"";window.open(`mailto:${me}?subject=${encodeURIComponent(ee)}&body=${encodeURIComponent(oe)}`,"_self")};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsxs(Vs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(od,{className:"h-5 w-5"}),"Share Video"]}),e.jsx(Cr,{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(re,{className:"text-sm font-medium",children:"Personalize for Contact (Optional)"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(Xc,{open:v,onOpenChange:_,children:[e.jsx(Qc,{asChild:!0,children:e.jsxs($,{variant:"outline",role:"combobox","aria-expanded":v,className:"flex-1 justify-between",disabled:o,children:[x?e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(el,{className:"h-4 w-4 text-muted-foreground"}),x.name]}):e.jsx("span",{className:"text-muted-foreground",children:"Select a contact..."}),e.jsx(v_,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(Bc,{className:"w-[300px] p-0",align:"start",children:e.jsxs(M_,{children:[e.jsx(P_,{placeholder:"Search contacts..."}),e.jsxs(I_,{children:[e.jsx(L_,{children:j?"Loading...":"No contacts found."}),e.jsx(Nb,{children:p.map(Y=>e.jsxs(rv,{value:Y.name,onSelect:()=>I(Y),children:[e.jsx(ma,{className:Ot("mr-2 h-4 w-4",(x==null?void 0:x.id)===Y.id?"opacity-100":"opacity-0")}),Y.name]},Y.id))})]})]})})]}),x&&e.jsx($,{variant:"ghost",size:"icon",onClick:()=>I(null),disabled:o,className:"shrink-0",children:e.jsx(mr,{className:"h-4 w-4"})})]}),x&&i!=="default"&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:['Page will show: "',SB(i).headerText(x.name),'"']})]}),e.jsx(tLn,{selectedTemplate:i,onSelect:P,contactName:R,saving:o}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Share Link"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(be,{value:A,readOnly:!0,className:"font-mono text-sm"}),e.jsx($,{onClick:U,variant:d?"default":"outline",className:"shrink-0 gap-2",children:d?e.jsxs(e.Fragment,{children:[e.jsx(ma,{className:"h-4 w-4"}),"Copied"]}):e.jsxs(e.Fragment,{children:[e.jsx(Da,{className:"h-4 w-4"}),"Copy"]})})]})]}),n.thumbnail_url&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Share for Email"}),e.jsxs($,{variant:"outline",className:"w-full gap-2",onClick:B,children:[e.jsx(zc,{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(re,{children:"Quick Share"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs($,{variant:"outline",className:"flex-1 gap-2",onClick:G,children:[e.jsx(bo,{className:"h-4 w-4"}),"Text"]}),e.jsxs($,{variant:"outline",className:"flex-1 gap-2",onClick:H,children:[e.jsx(pn,{className:"h-4 w-4"}),"Email"]})]})]})]}),e.jsx(kr,{children:e.jsx($,{variant:"outline",onClick:()=>t(!1),children:"Done"})})]})})}function sLn(){var Fe;const s=Jn(),[t]=Jc(),{toast:n}=Fi(),r=t.get("contact_id"),a=t.get("task_id"),{canRecord:i,remainingMb:l,usagePercent:o,isNearLimit:c}=U7t(),{data:d}=vv(),u=o4(),h=qSn(),[m,p]=k.useState("record"),[g,x]=k.useState(""),[y,v]=k.useState(!1),[_,j]=k.useState(!1),[C,A]=k.useState(!1),[M,I]=k.useState(null),[P,R]=k.useState(0),[O,B]=k.useState(0),[U,G]=k.useState(null),[H,Y]=k.useState(null),[se,ee]=k.useState(r||""),[oe,me]=k.useState(""),[Q,te]=k.useState(""),[le,fe]=k.useState(null),[_e,ve]=k.useState(null),[he,Se]=k.useState(null),[Te,Ie]=k.useState(!1),Ue=k.useCallback(async(Oe,Ge)=>{I(Oe),p("uploading");try{const{videoId:yt,uploadUrl:tt}=await v6(oe||"Quick Video Touch");G(yt);const{apiKey:ut}=await b6(yt),nt=new XMLHttpRequest;nt.upload.onprogress=rt=>{rt.lengthComputable&&R(rt.loaded/rt.total*100)},await new Promise((rt,Ft)=>{nt.onload=()=>{nt.status>=200&&nt.status<300?rt():Ft(new Error(`Upload failed: ${nt.status}`))},nt.onerror=()=>Ft(new Error("Upload failed")),nt.open("PUT",tt),nt.setRequestHeader("AccessKey",ut),nt.send(Oe)}),p("processing");let et=0;const at=Date.now(),wt=90*1e3;for(;et<4;){if(await new Promise(Ft=>setTimeout(Ft,3e3)),Date.now()-at>wt){const Ft=Oe.size/1048576,Ut=`https://iframe.mediadelivery.net/play/${yt}/${yt}`;await u.mutateAsync({bunny_video_id:yt,playback_url:Ut,file_size_mb:Ft,title:oe||"Quick Video Touch",notes:Q||void 0,contact_id:se&&se!=="none"?se:void 0,status:"processing",touch_type:"video_touch"}),n({title:"Video saved — still processing",description:'Your video has been saved and will appear in your library with a "processing" badge. It will be ready to share once encoding completes (usually within a few minutes).',duration:8e3}),s("/mission-control/video-library");return}const rt=await D2(yt);if(et=rt.status,B(rt.encodeProgress||0),et===4)Y({playbackUrl:rt.directPlayUrl,thumbnailUrl:rt.thumbnailUrl,previewUrl:rt.previewUrl||null,duration:rt.length||Ge,fileSizeMb:(rt.storageSize||Oe.size)/(1024*1024)});else if(et===5||et===6)throw new Error("Video processing failed")}p("details")}catch(yt){console.error("Upload error:",yt),n({title:"Upload failed",description:"Please try recording again.",variant:"destructive"}),p("record")}},[oe,n]),Be=async()=>{if(!(!U||!H))try{const Oe=se&&se!=="none"?se:null,Ge=await u.mutateAsync({bunny_video_id:U,contact_id:Oe,playback_url:H.playbackUrl,thumbnail_url:H.thumbnailUrl,preview_url:H.previewUrl,duration_seconds:H.duration,file_size_mb:H.fileSizeMb,title:oe||"Quick Video Touch",notes:Q,task_id:a||null,status:"ready"});fe(Ge.id),ve(Ge.share_token||null),Oe&&await h.mutateAsync({contactId:Oe,videoId:Ge.id,notes:Q}),n({title:"Video saved successfully!"}),p("share")}catch(Oe){console.error("Save video error:",Oe),n({title:"Failed to save video",description:(Oe==null?void 0:Oe.message)||"Please try again.",variant:"destructive"})}},je=(Oe,Ge)=>{navigator.clipboard.writeText(Ge),Se(Oe),setTimeout(()=>Se(null),2e3),n({title:"Copied to clipboard!"})},Ye=()=>_e?`https://video.relevelup.com/${_e}`:(H==null?void 0:H.playbackUrl)||"",Ee=()=>{const Oe=d==null?void 0:d.find(nt=>nt.id===se),Ge=Oe?`${Oe.first_name}`:"",yt=(Oe==null?void 0:Oe.phone)||"",tt=(Oe==null?void 0:Oe.email)||"",ut=Ye();return{text:`Hey${Ge?` ${Ge}`:""}! I recorded a quick video for you: ${ut}`,link:ut,contactPhone:yt,contactEmail:tt}},Re=()=>{const{text:Oe,contactPhone:Ge}=Ee(),yt=Ge?`sms:${Ge}?body=${encodeURIComponent(Oe)}`:`sms:?body=${encodeURIComponent(Oe)}`;window.open(yt,"_self")},ke=()=>{const{link:Oe,contactEmail:Ge}=Ee(),yt="Check out this video",tt=`I recorded a quick video for you: ${Oe}`,ut=Ge?`mailto:${Ge}?subject=${encodeURIComponent(yt)}&body=${encodeURIComponent(tt)}`:`mailto:?subject=${encodeURIComponent(yt)}&body=${encodeURIComponent(tt)}`;window.open(ut,"_self")};return i?e.jsx(Xs,{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($,{variant:"ghost",size:"icon",onClick:()=>s(-1),children:e.jsx(Ia,{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($,{variant:"outline",size:"sm",onClick:()=>s("/mission-control/video-library"),className:"gap-1.5",children:[e.jsx(ea,{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"]})]})]})]}),m==="record"&&e.jsxs("div",{className:"grid gap-6 lg:grid-cols-3",children:[e.jsxs("div",{className:"lg:col-span-2",children:[e.jsx(w6,{maxDurationSeconds:600,onRecordingComplete:Ue,onRecordingStateChange:A,className:"w-full",teleprompterContent:y&&g&&e.jsx(uQe,{text:g,isVisible:y,onToggleVisibility:()=>v(!1),isRecording:C,startCountdown:!1})}),!y&&g&&e.jsxs($,{variant:"outline",className:"mt-4",onClick:()=>v(!0),children:[e.jsx(ea,{className:"h-4 w-4 mr-2"}),"Show Teleprompter"]})]}),e.jsxs(we,{className:"lg:col-span-1",children:[e.jsx(Vt,{className:"pb-2",children:e.jsx(Yt,{className:"text-lg",children:"Teleprompter Script"})}),e.jsxs(De,{className:"space-y-4",children:[e.jsx(Ls,{placeholder:"Type or paste your script here...",value:g,onChange:Oe=>x(Oe.target.value),rows:6}),e.jsxs(D_,{open:_,onOpenChange:j,children:[e.jsx(uee,{asChild:!0,children:e.jsxs($,{variant:"outline",className:"w-full",children:[e.jsx(ea,{className:"h-4 w-4 mr-2"}),"Browse Scripts"]})}),e.jsxs(Mb,{side:"right",className:"w-[400px] sm:w-[540px] p-0",children:[e.jsx(xj,{className:"p-4 border-b",children:e.jsx(yj,{children:"Select a Script"})}),e.jsx(eLn,{onSelectScript:Oe=>{x(Oe.text),j(!1),v(!0)},className:"h-[calc(100vh-80px)]"})]})]}),g&&e.jsx($,{className:"w-full",onClick:()=>v(!0),children:"Use Script"})]})]})]}),m==="uploading"&&e.jsx(we,{className:"max-w-md mx-auto",children:e.jsxs(De,{className:"pt-6 text-center",children:[e.jsx(gi,{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(ho,{value:P,className:"mb-2"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[P.toFixed(0),"%"]})]})}),m==="processing"&&e.jsx(we,{className:"max-w-md mx-auto",children:e.jsxs(De,{className:"pt-6 text-center space-y-4",children:[e.jsx(Jt,{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(ho,{value:O,className:"mb-2"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[O.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.`})]})}),m==="details"&&e.jsxs(we,{className:"max-w-lg mx-auto",children:[e.jsx(Vt,{children:e.jsx(Yt,{children:"Video Details"})}),e.jsxs(De,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Title"}),e.jsx(be,{value:oe,onChange:Oe=>me(Oe.target.value),placeholder:"Quick Video Touch"})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Attach to Contact (Optional)"}),e.jsxs(bs,{value:se,onValueChange:ee,children:[e.jsx(ys,{children:e.jsx(_s,{placeholder:"No contact - use anywhere"})}),e.jsxs(vs,{children:[e.jsx(We,{value:"none",children:e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(od,{className:"h-4 w-4"}),"No contact - use anywhere"]})}),d==null?void 0:d.map(Oe=>e.jsx(We,{value:Oe.id,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(el,{className:"h-4 w-4"}),Oe.first_name," ",Oe.last_name]})},Oe.id))]})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Notes"}),e.jsx(Ls,{value:Q,onChange:Oe=>te(Oe.target.value),placeholder:"Add notes about this video...",rows:3})]}),e.jsxs($,{className:"w-full",onClick:Be,disabled:u.isPending,children:[u.isPending&&e.jsx(Jt,{className:"h-4 w-4 mr-2 animate-spin"}),"Save Video"]})]})]}),m==="share"&&e.jsxs(we,{className:"max-w-lg mx-auto",children:[e.jsx(Vt,{children:e.jsxs(Yt,{className:"flex items-center gap-2",children:[e.jsx(ma,{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($,{variant:"outline",className:"justify-start",onClick:Re,children:[e.jsx(bo,{className:"h-4 w-4 mr-2"}),"Text Contact Video"]}),e.jsxs($,{variant:"outline",className:"justify-start",onClick:ke,children:[e.jsx(pn,{className:"h-4 w-4 mr-2"}),"Email Contact Video"]}),e.jsxs($,{variant:"outline",className:"justify-start",onClick:()=>je("link",Ee().link),children:[e.jsx(od,{className:"h-4 w-4 mr-2"}),"Copy Video Link",he==="link"&&e.jsx(ma,{className:"h-4 w-4 ml-auto text-green-500"})]}),e.jsxs($,{variant:"outline",className:"justify-start",onClick:()=>Ie(!0),children:[e.jsx(gd,{className:"h-4 w-4 mr-2"}),"Send with Page Template"]})]}),e.jsxs("div",{className:"flex gap-3 pt-4",children:[e.jsx($,{variant:"outline",onClick:()=>s("/mission-control/video-library"),children:"View Library"}),e.jsx($,{onClick:()=>{p("record"),I(null),G(null),Y(null)},children:"Record Another"})]})]})]}),le&&_e&&e.jsx(eVt,{open:Te,onOpenChange:Ie,video:{id:le,share_token:_e,title:oe||null,contact_id:se||null,thumbnail_url:(H==null?void 0:H.thumbnailUrl)||null},contactName:((Fe=d==null?void 0:d.find(Oe=>Oe.id===se))==null?void 0:Fe.first_name)||null})]})}):e.jsx(Xs,{title:"QuickVid",children:e.jsxs("div",{className:"max-w-2xl mx-auto text-center py-12",children:[e.jsx(Gd,{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($,{onClick:()=>s("/mission-control/video-library"),children:"Open Video Library"})]})})}function nLn({open:s,onOpenChange:t,video:n,gmailEmail:r,signedThumbnailUrl:a,onSendComplete:i}){const[l,o]=k.useState([]),[c,d]=k.useState(null),[u,h]=k.useState(!1),[m,p]=k.useState(!1),[g,x]=k.useState(""),[y,v]=k.useState(""),[_,j]=k.useState(""),[C,A]=k.useState(!1),M=O7t(),I=n.share_token?`https://video.relevelup.com/share/video/${n.share_token}`:"",P=n.share_token?`https://video.relevelup.com/thumb/${n.share_token}`:a||n.thumbnail_url||"",R=n.title||"Video Message";k.useEffect(()=>{s&&l.length===0&&O()},[s]),k.useEffect(()=>{if(s&&(v(`I recorded a video for you — ${R}`),j("Hey! I recorded a quick video just for you. Click below to watch it:"),d(null),x(""),n.contact_id)){const se=l.find(ee=>ee.id===n.contact_id);se&&(d(se),x(se.email||""))}},[s,n.contact_id,l]);const O=async()=>{p(!0);try{const{data:se,error:ee}=await V.from("innercircle_contacts").select("id, first_name, last_name, email").order("first_name",{ascending:!0}).limit(500);if(ee)throw ee;o(se||[])}catch{console.error("Failed to fetch contacts")}finally{p(!1)}},B=se=>{d(se),h(!1),x(se.email||""),j(`Hey ${se.first_name}! I recorded a quick video just for you. Click below to watch it:`),v(`I recorded a video for you — ${R}`)},U=()=>{d(null),x(""),j("Hey! I recorded a quick video just for you. Click below to watch it:")},G=se=>{const ee=`${se.first_name||""} ${se.last_name||""}`.replace(/<[^>]*>/g," ").replace(/\s+/g," ").trim();return ee?ee.length>60?`${ee.slice(0,60)}…`:ee:se.email||"Unnamed contact"},H=se=>{const ee=_.split(/\n\n+/).map(Q=>`

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

`).join(""),oe=se?z7t(se):I,me=se?``:"";return`
${ee}

▶ Watch Video

${me}
`},Y=async()=>{var se;if(!g){ae.error("Please enter a recipient email");return}if(!I){ae.error("Video does not have a share link");return}A(!0);try{let ee;try{const le=c?G(c):g.split("@")[0];ee=(await M.mutateAsync({video_id:n.id,recipient_email:g,recipient_name:le,contact_id:(c==null?void 0:c.id)||null,sent_via:"gmail"})).share_token}catch(le){console.warn("Failed to create tracking record, sending without tracking:",le)}const oe=H(ee),{data:me,error:Q}=await V.functions.invoke("gmail-send",{body:{to:g,subject:y,body:oe,contactId:(c==null?void 0:c.id)||null}});let te=null;if(Q&&((se=Q.context)!=null&&se.json))try{te=await Q.context.json()}catch{}if((te==null?void 0:te.error)==="insufficient_scope"||(me==null?void 0:me.error)==="insufficient_scope"){ae.error((te==null?void 0:te.message)||"Gmail is missing send permission. Please disconnect and reconnect Gmail, allowing 'Send email on your behalf'.",{duration:1e4});return}if(Q)throw new Error((te==null?void 0:te.message)||Q.message);if(!(me!=null&&me.success))throw new Error((me==null?void 0:me.error)||"Failed to send");ae.success("Video email sent!"),t(!1),i==null||i()}catch(ee){console.error("Gmail send error:",ee),ae.error("Failed to send: "+(ee instanceof Error?ee.message:"Unknown error"))}finally{A(!1)}};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"sm:max-w-[560px] max-h-[90vh] overflow-y-auto",children:[e.jsxs(Vs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(pn,{className:"h-5 w-5 text-red-500"}),"Send Video via Gmail"]}),r&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Sending from ",e.jsx("span",{className:"font-medium",children:r})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Send to Contact"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(Xc,{open:u,onOpenChange:h,children:[e.jsx(Qc,{asChild:!0,children:e.jsxs($,{variant:"outline",role:"combobox",className:"flex-1 justify-between",children:[c?e.jsxs("span",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(el,{className:"h-4 w-4 shrink-0 text-muted-foreground"}),e.jsx("span",{className:"truncate",children:G(c)}),c.email&&e.jsxs("span",{className:"text-muted-foreground text-xs truncate",children:["(",c.email,")"]})]}):e.jsx("span",{className:"text-muted-foreground",children:"Select a contact..."}),e.jsx(v_,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(Bc,{className:"w-[350px] p-0",align:"start",children:e.jsxs(M_,{children:[e.jsx(P_,{placeholder:"Search contacts..."}),e.jsxs(I_,{children:[e.jsx(L_,{children:m?"Loading...":"No contacts found."}),e.jsx(Nb,{children:l.filter(se=>se.email).map(se=>e.jsxs(rv,{value:`${G(se)} ${se.email||""}`,onSelect:()=>B(se),children:[e.jsx(ma,{className:Ot("mr-2 h-4 w-4",(c==null?void 0:c.id)===se.id?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"font-medium truncate",children:G(se)}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:se.email})]})]},se.id))})]})]})})]}),c&&e.jsx($,{variant:"ghost",size:"icon",onClick:U,className:"shrink-0",children:e.jsx(mr,{className:"h-4 w-4"})})]})]}),!c&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{htmlFor:"video-to",children:"Or type email address"}),e.jsx(be,{id:"video-to",value:g,onChange:se=>x(se.target.value),placeholder:"recipient@example.com",type:"email"})]}),e.jsx(Pc,{}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{htmlFor:"video-subject",children:"Subject"}),e.jsx(be,{id:"video-subject",value:y,onChange:se=>v(se.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{htmlFor:"video-message",children:"Personal Message"}),e.jsx(Ls,{id:"video-message",value:_,onChange:se=>j(se.target.value),rows:4,className:"resize-y"})]}),e.jsxs("div",{className:"rounded-lg border bg-muted/30 p-3 space-y-2",children:[e.jsx(re,{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:[P?e.jsx("img",{src:P,alt:R,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(pu,{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(pu,{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($,{variant:"outline",onClick:()=>t(!1),disabled:C,children:"Cancel"}),e.jsxs($,{onClick:Y,disabled:C||!g||!y,className:"gap-2",children:[C?e.jsx(Jt,{className:"h-4 w-4 animate-spin"}):e.jsx(Wr,{className:"h-4 w-4"}),C?"Sending...":"Send Video Email"]})]})]})]})})}const rLn=()=>{const{user:s}=ks();return pt({queryKey:["team-videos",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await V.rpc("get_team_videos",{_user_id:s.id});if(n)throw n;return t||[]},enabled:!!s})};function aLn({recipient:s}){return s.watched_at?e.jsxs(qe,{className:"bg-emerald-100 text-emerald-800 text-[10px]",children:[e.jsx(pu,{className:"h-2.5 w-2.5 mr-0.5"}),"Watched"]}):s.clicked_at?e.jsxs(qe,{className:"bg-blue-100 text-blue-800 text-[10px]",children:[e.jsx(sv,{className:"h-2.5 w-2.5 mr-0.5"}),"Clicked"]}):s.opened_at?e.jsxs(qe,{className:"bg-amber-100 text-amber-800 text-[10px]",children:[e.jsx(ba,{className:"h-2.5 w-2.5 mr-0.5"}),"Opened"]}):e.jsxs(qe,{variant:"outline",className:"text-[10px]",children:[e.jsx(Wr,{className:"h-2.5 w-2.5 mr-0.5"}),"Sent"]})}function iLn({open:s,onOpenChange:t,videoId:n,videoTitle:r}){const{data:a=[],isLoading:i}=ySn(n);return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"max-w-2xl max-h-[80vh]",children:[e.jsx(Vs,{children:e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(Ul,{className:"h-5 w-5"}),"Send Analytics: ",r]})}),i?e.jsx("div",{className:"space-y-2",children:[...Array(3)].map((l,o)=>e.jsx(fn,{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(Eo,{className:"h-[400px]",children:e.jsxs(Qa,{children:[e.jsx(Ja,{children:e.jsxs(vn,{children:[e.jsx(Dt,{children:"Recipient"}),e.jsx(Dt,{children:"Status"}),e.jsx(Dt,{children:"Sent"}),e.jsx(Dt,{children:"Last Activity"})]})}),e.jsx(ei,{children:a.map(l=>e.jsxs(vn,{children:[e.jsx(_t,{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(_t,{children:e.jsx(aLn,{recipient:l})}),e.jsx(_t,{className:"text-xs text-muted-foreground",children:Ys(new Date(l.sent_at),"MMM d, h:mm a")}),e.jsx(_t,{className:"text-xs text-muted-foreground",children:l.last_activity_at?Zc(new Date(l.last_activity_at),{addSuffix:!0}):"—"})]},l.id))})]})})]})]})})}function oLn(){const{data:s,isLoading:t}=vSn(),{data:n=[],isLoading:r}=bSn(),[a,i]=k.useState(null),l=t||r,o=n.reduce((c,d)=>{const u=d.agent_videos,h=(u==null?void 0:u.id)||d.video_id;return c[h]||(c[h]={videoId:h,title:(u==null?void 0:u.title)||"Untitled",thumbnailUrl:u==null?void 0:u.thumbnail_url,recipients:[]}),c[h].recipients.push(d),c},{});return l?e.jsx("div",{className:"space-y-4",children:e.jsx("div",{className:"grid gap-4 md:grid-cols-4",children:[...Array(4)].map((c,d)=>e.jsxs(we,{children:[e.jsx(Vt,{className:"pb-2",children:e.jsx(fn,{className:"h-4 w-20"})}),e.jsx(De,{children:e.jsx(fn,{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(we,{children:[e.jsxs(Vt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Yt,{className:"text-sm font-medium",children:"Total Sent"}),e.jsx(Wr,{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(we,{children:[e.jsxs(Vt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Yt,{className:"text-sm font-medium",children:"Open Rate"}),e.jsx(ba,{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(we,{children:[e.jsxs(Vt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Yt,{className:"text-sm font-medium",children:"Click Rate"}),e.jsx(sv,{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(we,{children:[e.jsxs(Vt,{children:[e.jsx(Yt,{className:"text-sm font-medium",children:"Send History by Video"}),e.jsx(vr,{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(h=>h.opened_at).length,u=c.recipients.filter(h=>h.clicked_at).length;return e.jsxs("button",{onClick:()=>i({id:c.videoId,title:c.title}),className:"w-full flex items-center gap-3 p-3 rounded-lg border hover:bg-muted/50 transition-colors text-left",children:[e.jsx("div",{className:"h-10 w-16 rounded bg-muted overflow-hidden flex-shrink-0",children:c.thumbnailUrl?e.jsx("img",{src:c.thumbnailUrl,alt:"",className:"h-full w-full object-cover",referrerPolicy:"no-referrer",onError:h=>{const m=h.currentTarget;m.style.display="none",m.parentElement.innerHTML='
'}}):e.jsx("div",{className:"h-full w-full flex items-center justify-center",children:e.jsx(ia,{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(Wr,{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(ba,{className:"h-3 w-3"})," ",d]}),e.jsxs("span",{className:"text-xs text-blue-600 flex items-center gap-1",children:[e.jsx(sv,{className:"h-3 w-3"})," ",u]})]})]}),e.jsx(mc,{className:"h-4 w-4 text-muted-foreground"})]},c.videoId)})})})]}),e.jsx(iLn,{open:!!a,onOpenChange:c=>!c&&i(null),videoId:(a==null?void 0:a.id)||null,videoTitle:(a==null?void 0:a.title)||""})]})}function lLn({previewSrc:s,thumbnailSrc:t,alt:n,isHovered:r}){const[a,i]=k.useState(!1),[l,o]=k.useState(!1),c=r&&s&&!a,d=t&&!l;return!d&&!c?e.jsx("div",{className:"w-full h-full flex items-center justify-center absolute inset-0 bg-muted",children:e.jsx(ia,{className:"h-12 w-12 text-muted-foreground"})}):e.jsxs(e.Fragment,{children:[d&&e.jsx("img",{src:t,alt:n,loading:"lazy",className:`w-full h-full object-cover absolute inset-0 transition-opacity duration-200 ${c?"opacity-0":"opacity-100"}`,onError:()=>o(!0)}),c&&e.jsx("img",{src:s,alt:n,className:"w-full h-full object-cover absolute inset-0",onError:()=>i(!0)})]})}function cLn({video:s,previewSrc:t,thumbnailSrc:n,onOpen:r,onDelete:a,onRename:i,onNavigateToContact:l,onGetEmbedCode:o,onCopyEmailHtml:c,onEmbedToCrm:d,onShareWithTemplate:u,onSendViaGmail:h,isGmailConnected:m,getContactName:p,getShareUrl:g,copyToClipboard:x,formatDuration:y}){const[v,_]=k.useState(!1);return e.jsxs(we,{className:"overflow-hidden group cursor-pointer",onClick:r,onMouseEnter:()=>_(!0),onMouseLeave:()=>_(!1),children:[e.jsxs("div",{className:"relative aspect-video bg-muted overflow-hidden",children:[e.jsx(lLn,{previewSrc:t,thumbnailSrc:n,alt:s.title||"Video preview",isHovered:v}),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(pu,{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:y(s.duration_seconds)}),s.status!=="ready"&&e.jsx(qe,{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(el,{className:"h-3 w-3"}),e.jsx("span",{className:"truncate",children:p(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(sa,{className:"h-3 w-3"}),e.jsx("span",{children:Ys(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(ba,{className:"h-3 w-3"}),e.jsxs("span",{children:[s.view_count," ",s.view_count===1?"view":"views"]})]})]}),m&&s.share_token&&e.jsxs($,{variant:"outline",size:"sm",className:"mt-2 gap-1.5 text-xs h-7",onClick:j=>{j.stopPropagation(),h==null||h()},children:[e.jsx(pn,{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(el,{className:"h-3 w-3"}),e.jsx("span",{className:"truncate",children:p(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(sa,{className:"h-3 w-3"}),e.jsx("span",{children:Ys(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(ba,{className:"h-3 w-3"}),e.jsxs("span",{children:[s.view_count," ",s.view_count===1?"view":"views"]})]})]})]}),e.jsxs(Au,{children:[e.jsx(Eu,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:j=>j.stopPropagation(),children:e.jsx(Z0,{className:"h-4 w-4"})})}),e.jsxs(gu,{align:"end",className:"bg-popover",children:[e.jsxs(Pa,{onClick:j=>{j.stopPropagation(),r()},children:[e.jsx(ba,{className:"h-4 w-4 mr-2"}),"Watch"]}),e.jsx(j0,{}),e.jsxs(Pa,{onClick:j=>{j.stopPropagation(),u()},children:[e.jsx(gd,{className:"h-4 w-4 mr-2"}),"Share with Template"]}),e.jsxs(Pa,{onClick:j=>{j.stopPropagation(),x(g(s),"Share link")},children:[e.jsx(od,{className:"h-4 w-4 mr-2"}),"Copy Share Link"]}),e.jsxs(Pa,{onClick:j=>{j.stopPropagation(),o()},children:[e.jsx($T,{className:"h-4 w-4 mr-2"}),"Get Embed Code"]}),e.jsxs(Pa,{onClick:j=>{j.stopPropagation(),c()},children:[e.jsx(pn,{className:"h-4 w-4 mr-2"}),"Copy HTML for Email"]}),e.jsxs(Pa,{onClick:j=>{j.stopPropagation(),d()},children:[e.jsx(Ir,{className:"h-4 w-4 mr-2"}),"Embed to CRM"]}),m&&s.share_token&&e.jsxs(Pa,{onClick:j=>{j.stopPropagation(),h==null||h()},children:[e.jsx(Wr,{className:"h-4 w-4 mr-2"}),"Send via Gmail"]}),e.jsxs(Pa,{onClick:j=>{j.stopPropagation(),i()},children:[e.jsx(ui,{className:"h-4 w-4 mr-2"}),"Rename"]}),e.jsx(j0,{}),s.contact_id&&e.jsxs(Pa,{onClick:j=>{j.stopPropagation(),l()},children:[e.jsx(el,{className:"h-4 w-4 mr-2"}),"View Contact"]}),e.jsxs(Pa,{onClick:j=>{j.stopPropagation(),a()},className:"text-destructive",children:[e.jsx(Un,{className:"h-4 w-4 mr-2"}),"Delete"]})]})]})]})})]})}function dLn(){var Is,xs;const s=Jn(),{data:t,isLoading:n,refetch:r}=zSn(),{data:a}=oTe(),{data:i}=vv(),l=USn(),o=$Sn(),{isGmailConnected:c,gmailEmail:d}=dx(),{data:u}=gj(),{data:h=[],isLoading:m}=rLn(),[p,g]=k.useState("my"),[x,y]=k.useState(""),[v,_]=k.useState(null),[j,C]=k.useState(!1),[A,M]=k.useState(!1),[I,P]=k.useState(!1),[R,O]=k.useState(!1),[B,U]=k.useState(!1),[G,H]=k.useState(""),[Y,se]=k.useState(!1),[ee,oe]=k.useState(!1),[me,Q]=k.useState(!1),[te,le]=k.useState(!1),[fe,_e]=k.useState(""),[ve,he]=k.useState({}),Se=st=>{if(!st)return"Unassigned";const dt=i==null?void 0:i.find(jt=>jt.id===st);return dt?`${dt.first_name} ${dt.last_name||""}`.trim():"Unknown"},Te=st=>{if(!st)return"0:00";const dt=Math.floor(st/60),jt=st%60;return`${dt}:${jt.toString().padStart(2,"0")}`},[Ie,Ue]=k.useState("all"),Be=t==null?void 0:t.filter(st=>{const dt=st.category||"general";if(Ie==="general"&&dt!=="general"||Ie==="open_house"&&dt!=="open_house")return!1;if(!x)return!0;const jt=Se(st.contact_id).toLowerCase(),gt=(st.title||"").toLowerCase(),rs=(st.notes||"").toLowerCase();return jt.includes(x.toLowerCase())||gt.includes(x.toLowerCase())||rs.includes(x.toLowerCase())}),je=(t==null?void 0:t.filter(st=>(st.category||"general")==="open_house").length)||0,Ye=(t==null?void 0:t.filter(st=>(st.category||"general")==="general").length)||0,Ee=(t||[]).filter(st=>st.status==="processing"&&st.bunny_video_id).map(st=>st.id).join(",");k.useEffect(()=>{(async()=>{if(!(t!=null&&t.length))return;const dt=t.filter(gt=>gt.status==="processing"&>.bunny_video_id);if(!dt.length)return;let jt=!1;for(const gt of dt)try{const{data:rs,error:Ns}=await V.functions.invoke("bunny-upload",{body:{action:"status",videoId:gt.bunny_video_id,isAgentVideo:!0}});if(Ns||!rs)continue;rs.status===4&&(await V.from("agent_videos").update({status:"ready",playback_url:rs.directPlayUrl,thumbnail_url:rs.thumbnailUrl,preview_url:rs.previewUrl,duration_seconds:rs.length||gt.duration_seconds,updated_at:new Date().toISOString()}).eq("id",gt.id),jt=!0)}catch(rs){console.warn("Reconcile check failed for video",gt.id,rs)}jt&&r()})()},[Ee,r]),k.useEffect(()=>{(async()=>{if(!(t!=null&&t.length))return;const dt=t.filter(us=>(us==null?void 0:us.bunny_video_id)&&!ve[us.id]);if(!dt.length)return;const jt=dt.map(us=>us.bunny_video_id),{data:gt,error:rs}=await V.functions.invoke("bunny-upload",{body:{action:"bulk-asset-urls",videoIds:jt,isAgentVideo:!0}});if(rs)throw rs;const Ns=(gt==null?void 0:gt.assets)||{};he(us=>{const Bs={...us};for(const Ts of dt)Ns[Ts.bunny_video_id]&&(Bs[Ts.id]={previewUrl:Ns[Ts.bunny_video_id].previewUrl,thumbnailUrl:Ns[Ts.bunny_video_id].thumbnailUrl});return Bs})})().catch(dt=>console.warn("Failed to load signed Bunny asset URLs",dt))},[t,ve]);const Re=(a==null?void 0:a.total_storage_mb)||0,ke=(a==null?void 0:a.max_storage_mb)||1024,Fe=Re/ke*100,Oe=Fe>=80,Ge=Fe>=100,yt=async(st,dt)=>{await navigator.clipboard.writeText(st),ae.success(`${dt} copied to clipboard`)},tt=st=>st.share_token?`https://video.relevelup.com/${st.share_token}`:st.playback_url||"",ut=st=>{const dt=tt(st),jt=i==null?void 0:i.find(Ts=>Ts.id===st.contact_id),gt=Se(st.contact_id),rs=gt!=="Unassigned"?gt.split(" ")[0]:"",Ns=(jt==null?void 0:jt.phone)||"",us=`Hey${rs?` ${rs}`:""}! I recorded a quick video message for you. Check it out: ${dt}`,Bs=Ns?`sms:${Ns}?body=${encodeURIComponent(us)}`:`sms:?body=${encodeURIComponent(us)}`;window.open(Bs,"_self")},nt=st=>{const dt=i==null?void 0:i.find(Bs=>Bs.id===st.contact_id),jt=(dt==null?void 0:dt.email)||"",gt=tt(st),rs="Check out this video",Ns=`I recorded a quick video for you: ${gt}`,us=jt?`mailto:${jt}?subject=${encodeURIComponent(rs)}&body=${encodeURIComponent(Ns)}`:`mailto:?subject=${encodeURIComponent(rs)}&body=${encodeURIComponent(Ns)}`;window.open(us,"_self")},et=st=>{var rs;const dt=tt(st),jt=st.title||"Video Message",gt=st.share_token?`https://video.relevelup.com/thumb/${st.share_token}`:((rs=ve[st.id])==null?void 0:rs.thumbnailUrl)||st.thumbnail_url||"";return``},at=async st=>{if(!st.thumbnail_url&&!st.share_token){ae.error("Video thumbnail not available yet");return}const dt=et(st),jt=tt(st),gt=`Watch: ${st.title||"Video Message"} ${jt}`;try{const rs=new Blob([dt],{type:"text/html"}),Ns=new Blob([gt],{type:"text/plain"}),us=new ClipboardItem({"text/html":rs,"text/plain":Ns});await navigator.clipboard.write([us]),ae.success("Copied! Paste into Gmail - the thumbnail will appear after sending.")}catch{await navigator.clipboard.writeText(gt+` `+dt),ae.success("Copied! Paste into your email.")}},wt=async st=>{try{ae.loading("Preparing download...",{id:"download"});const{data:dt,error:jt}=await V.functions.invoke("bunny-upload",{body:{action:"download-url",videoId:st.bunny_video_id,isAgentVideo:!0}});if(jt||!(dt!=null&&dt.downloadUrl))throw new Error((jt==null?void 0:jt.message)||"Failed to get download URL");const rs=`${((st.title||"video").toString().trim()||"video").replace(/[\\/:*?"<>|]+/g,"-")}.mp4`,Ns=await fetch(dt.downloadUrl);if(!Ns.ok)throw new Error("Failed to fetch video file");const us=await Ns.blob(),Bs=URL.createObjectURL(us),Ts=document.createElement("a");Ts.href=Bs,Ts.download=rs,Ts.rel="noreferrer",document.body.appendChild(Ts),Ts.click(),Ts.remove(),URL.revokeObjectURL(Bs),ae.success("Download started",{id:"download"})}catch(dt){console.error("Download error:",dt),ae.error("Could not force download (your browser may block it).",{id:"download"})}},rt=async st=>{_(st),se(!0),H(""),U(!0);try{const{data:dt,error:jt}=await V.functions.invoke("bunny-upload",{body:{action:"crm-embed",videoId:st.bunny_video_id,title:st.title,isAgentVideo:!0,shareToken:st.share_token}});if(jt||!(dt!=null&&dt.html))throw new Error("Failed to generate CRM embed code");H(dt.html)}catch(dt){console.error("CRM embed error:",dt),ae.error("Failed to generate CRM embed code"),U(!1)}finally{se(!1)}},Ft=st=>{_(st),C(!0)},Ut=async()=>{if(v)try{await l.mutateAsync({id:v.id,bunnyVideoId:v.bunny_video_id,hardDelete:!0}),M(!1),_(null),ae.success("Video deleted successfully")}catch{ae.error("Failed to delete video")}};return e.jsx(Xs,{title:"Video Library",description:"Manage your video touches",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row items-start sm:items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Video Library"}),e.jsx("p",{className:"text-muted-foreground",children:"Manage and share your video touches"})]}),e.jsxs("div",{className:"flex bg-muted rounded-lg p-1 gap-0.5 ml-2",children:[e.jsx("button",{onClick:()=>g("my"),className:`px-3 py-1.5 rounded-md text-sm font-medium transition-colors ${p==="my"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:"My Videos"}),u&&((Is=u.team)==null?void 0:Is.shared_videos_enabled)&&e.jsxs("button",{onClick:()=>g("team"),className:`px-3 py-1.5 rounded-md text-sm font-medium transition-colors flex items-center gap-1.5 ${p==="team"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:[e.jsx(Xn,{className:"h-3.5 w-3.5"}),"Team"]}),e.jsxs("button",{onClick:()=>g("analytics"),className:`px-3 py-1.5 rounded-md text-sm font-medium transition-colors flex items-center gap-1.5 ${p==="analytics"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:[e.jsx(Ul,{className:"h-3.5 w-3.5"}),"Analytics"]})]})]}),p==="my"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs($,{variant:"outline",onClick:()=>P(!0),children:[e.jsx(gi,{className:"h-4 w-4 mr-2"}),"Upload Video"]}),e.jsxs($,{onClick:()=>s("/mission-control/video/record"),children:[e.jsx(nn,{className:"h-4 w-4 mr-2"}),"Record New Video"]})]})]}),p==="team"?e.jsx(uLn,{videos:h,isLoading:m,searchTerm:x,setSearchTerm:y}):p==="analytics"?e.jsx(oLn,{}):e.jsxs(e.Fragment,{children:[e.jsx(we,{className:Oe?"border-amber-500":Ge?"border-destructive":"",children:e.jsxs(De,{className:"py-4",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(IK,{className:`h-5 w-5 ${Ge?"text-destructive":Oe?"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:[Re.toFixed(1)," MB / ",ke>=1024?`${(ke/1024).toFixed(0)} GB`:`${ke} MB`]})]}),e.jsx(ho,{value:Math.min(Fe,100),className:`h-2 ${Ge?"[&>div]:bg-destructive":Oe?"[&>div]:bg-amber-500":""}`})]}),Oe&&!Ge&&e.jsxs(qe,{variant:"outline",className:"border-amber-500 text-amber-600",children:[e.jsx(Ho,{className:"h-3 w-3 mr-1"}),"Near Limit"]}),Ge&&e.jsxs(qe,{variant:"destructive",children:[e.jsx(Ho,{className:"h-3 w-3 mr-1"}),"At Limit"]})]}),Ge&&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:Ye},{id:"open_house",label:"Open House Tours",count:je}].map(st=>e.jsxs("button",{onClick:()=>Ue(st.id),className:`px-3 py-1.5 rounded-md text-sm font-medium transition-colors ${Ie===st.id?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:[st.label," ",e.jsx("span",{className:"ml-1 text-xs text-muted-foreground",children:st.count})]},st.id))}),e.jsxs("div",{className:"relative",children:[e.jsx(Yr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search videos by contact, title, or notes...",value:x,onChange:st=>y(st.target.value),className:"pl-10"})]}),n?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"animate-spin h-8 w-8 border-4 border-primary border-t-transparent rounded-full"})}):(Be==null?void 0:Be.length)===0?e.jsx(we,{children:e.jsxs(De,{className:"py-12 text-center",children:[e.jsx(ia,{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($,{onClick:()=>s("/mission-control/video/record"),children:[e.jsx(nn,{className:"h-4 w-4 mr-2"}),"Record Video"]})]})}):e.jsx("div",{className:"grid sm:grid-cols-2 lg:grid-cols-3 gap-4",children:Be==null?void 0:Be.map(st=>{var dt,jt;return e.jsx(cLn,{video:st,previewSrc:(dt=ve[st.id])==null?void 0:dt.previewUrl,thumbnailSrc:(jt=ve[st.id])==null?void 0:jt.thumbnailUrl,onOpen:()=>Ft(st),onDelete:()=>{_(st),M(!0)},onRename:()=>{_(st),_e(st.title||""),le(!0)},onNavigateToContact:()=>s(`/mission-control/contacts/${st.contact_id}`),onGetEmbedCode:()=>{_(st),O(!0)},onCopyEmailHtml:()=>at(st),onEmbedToCrm:()=>rt(st),onShareWithTemplate:()=>{_(st),oe(!0)},onSendViaGmail:()=>{_(st),Q(!0)},isGmailConnected:c,getContactName:Se,getShareUrl:tt,copyToClipboard:yt,formatDuration:Te},st.id)})}),e.jsx(zs,{open:j,onOpenChange:C,children:e.jsxs(Rs,{className:"max-w-2xl",children:[e.jsxs(Vs,{children:[e.jsx($s,{children:(v==null?void 0:v.title)||"Video Preview"}),e.jsx(Cr,{children:(v==null?void 0:v.contact_id)&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(el,{className:"h-3 w-3"}),Se(v.contact_id)]})})]}),v&&e.jsxs("div",{className:"space-y-4",children:[v.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(Jt,{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($,{variant:"outline",size:"sm",onClick:()=>{C(!1),r()},children:[e.jsx(yo,{className:"h-4 w-4 mr-2"}),"Refresh Library"]})]}):e.jsx("div",{className:"relative w-full",style:{paddingBottom:"56.25%"},children:v.playback_url?(()=>{let st=v.playback_url;return st.includes("iframe.mediadelivery.net/play/")&&(st=st.replace("/play/","/embed/"),st+=(st.includes("?")?"&":"?")+"autoplay=false&responsive=true"),st.includes("iframe.mediadelivery.net")?e.jsx("iframe",{src:st,title:v.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:v.playback_url,controls:!0,playsInline:!0,preload:"metadata",poster:v.thumbnail_url||void 0,className:"absolute top-0 left-0 w-full h-full rounded-lg object-cover",onError:()=>ae.error("Video preview failed to load")},v.playback_url)})():e.jsxs("div",{className:"absolute inset-0 flex items-center justify-center bg-muted rounded-lg",children:[e.jsx(ia,{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($,{variant:"outline",onClick:()=>ut(v),children:[e.jsx(bo,{className:"h-4 w-4 mr-2"}),"Text Contact Video"]}),!c&&e.jsxs($,{variant:"outline",onClick:()=>nt(v),children:[e.jsx(pn,{className:"h-4 w-4 mr-2"}),"Email Contact Video"]}),e.jsxs($,{variant:"outline",onClick:()=>yt(tt(v),"Share link"),children:[e.jsx(Da,{className:"h-4 w-4 mr-2"}),"Copy Share Link"]}),e.jsxs($,{variant:"outline",onClick:()=>at(v),children:[e.jsx(pn,{className:"h-4 w-4 mr-2"}),"Copy HTML for Email"]}),e.jsxs($,{variant:"outline",onClick:()=>wt(v),children:[e.jsx(ji,{className:"h-4 w-4 mr-2"}),"Download Video"]}),e.jsxs($,{variant:"outline",onClick:()=>{C(!1),rt(v)},children:[e.jsx(Ir,{className:"h-4 w-4 mr-2"}),"Embed to CRM"]}),e.jsxs($,{variant:"outline",onClick:()=>{C(!1),oe(!0)},children:[e.jsx(gd,{className:"h-4 w-4 mr-2"}),"Send with Page Template"]}),c&&(v==null?void 0:v.share_token)&&e.jsxs($,{variant:"outline",onClick:()=>{C(!1),Q(!0)},children:[e.jsx(Wr,{className:"h-4 w-4 mr-2"}),"Send via Gmail"]})]}),e.jsx("div",{className:"flex justify-end pt-2 border-t",children:e.jsxs($,{variant:"destructive",onClick:()=>{C(!1),M(!0)},children:[e.jsx(Un,{className:"h-4 w-4 mr-2"}),"Delete Video"]})})]})]})}),e.jsx(zs,{open:A,onOpenChange:M,children:e.jsxs(Rs,{children:[e.jsxs(Vs,{children:[e.jsx($s,{children:"Delete Video"}),e.jsx(Cr,{children:"Are you sure you want to delete this video? This action cannot be undone."})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>M(!1),children:"Cancel"}),e.jsx($,{variant:"destructive",onClick:Ut,disabled:l.isPending,children:l.isPending?"Deleting...":"Delete"})]})]})}),e.jsx(q7t,{open:I,onOpenChange:P}),e.jsx(zs,{open:R,onOpenChange:O,children:e.jsxs(Rs,{className:"sm:max-w-lg",children:[e.jsxs(Vs,{children:[e.jsx($s,{children:"Embed Video"}),e.jsx(Cr,{children:"Copy this code to embed the video on your website."})]}),v&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Embed Code"}),e.jsx(Ls,{readOnly:!0,rows:5,value:``,className:"font-mono text-xs"})]}),e.jsx("div",{className:"flex gap-2",children:e.jsxs($,{className:"flex-1",onClick:()=>{const st=``;yt(st,"Embed code")},children:[e.jsx(Da,{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."})]})]})}),v&&e.jsx(eVt,{open:ee,onOpenChange:oe,video:v,contactName:Se(v.contact_id)}),v&&e.jsx(nLn,{open:me,onOpenChange:Q,video:v,gmailEmail:d,signedThumbnailUrl:(xs=ve[v.id])==null?void 0:xs.thumbnailUrl}),e.jsx(zs,{open:te,onOpenChange:le,children:e.jsxs(Rs,{className:"max-w-sm",children:[e.jsxs(Vs,{children:[e.jsx($s,{children:"Rename Video"}),e.jsx(Cr,{children:"Enter a new title for this video."})]}),e.jsx(be,{value:fe,onChange:st=>_e(st.target.value),placeholder:"Video title",autoFocus:!0,onKeyDown:st=>{st.key==="Enter"&&fe.trim()&&o.mutate({id:v.id,title:fe.trim()},{onSuccess:()=>{ae.success("Video renamed"),le(!1)}})}}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>le(!1),children:"Cancel"}),e.jsx($,{disabled:!fe.trim()||o.isPending,onClick:()=>{o.mutate({id:v.id,title:fe.trim()},{onSuccess:()=>{ae.success("Video renamed"),le(!1)}})},children:o.isPending?"Saving...":"Save"})]})]})}),e.jsx(zs,{open:B,onOpenChange:U,children:e.jsxs(Rs,{className:"sm:max-w-lg",children:[e.jsxs(Vs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(Ir,{className:"h-5 w-5"}),"Embed to CRM"]}),e.jsx(Cr,{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."})]}),Y?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(Jt,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):G?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"CRM Email HTML"}),e.jsx(Ls,{readOnly:!0,rows:12,value:G,className:"font-mono text-xs"})]}),e.jsxs($,{className:"w-full",onClick:()=>{yt(G,"CRM embed code")},children:[e.jsx(Da,{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 uLn({videos:s,isLoading:t,searchTerm:n,setSearchTerm:r}){const a=k.useMemo(()=>{if(!n)return s;const o=n.toLowerCase();return s.filter(c=>(c.title||"").toLowerCase().includes(o)||(c.owner_name||"").toLowerCase().includes(o)||(c.recipient_name||"").toLowerCase().includes(o))},[s,n]),i=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(Yr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search team videos by title, owner, or recipient...",value:n,onChange:o=>r(o.target.value),className:"pl-10"})]}),t?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"animate-spin h-8 w-8 border-4 border-primary border-t-transparent rounded-full"})}):a.length===0?e.jsx(we,{children:e.jsxs(De,{className:"py-12 text-center",children:[e.jsx(Xn,{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(Wa,{className:"h-7 w-7",children:[e.jsx(eo,{src:c.avatar||""}),e.jsx(Ka,{children:(c.name||"?").charAt(0).toUpperCase()})]}),e.jsx("h3",{className:"font-semibold text-sm",children:c.name}),e.jsx(qe,{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(we,{className:"overflow-hidden",children:[e.jsxs("div",{className:"relative aspect-video bg-muted flex items-center justify-center",children:[d.thumbnail_url?e.jsx("img",{src:d.thumbnail_url,alt:d.title||"Video",className:"w-full h-full object-cover",referrerPolicy:"no-referrer",onError:u=>{u.target.style.display="none"}}):e.jsx(ia,{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(el,{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(ba,{className:"h-3 w-3"}),d.view_count]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(sa,{className:"h-3 w-3"}),Ys(new Date(d.created_at),"MMM d")]})]})]})]},d.id))})]},o))})]})}const hLn=()=>{const{user:s}=ks();return pt({queryKey:["team-deals",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await V.rpc("get_team_deals",{_user_id:s.id});if(n)throw n;return t||[]},enabled:!!s})},K1t=["#8B5CF6","#EC4899","#F59E0B","#10B981","#3B82F6","#EF4444","#06B6D4","#F97316"];function mLn({open:s,onOpenChange:t}){const{data:n,isLoading:r}=hLn(),[a,i]=k.useState(""),[l,o]=k.useState("all"),c=k.useMemo(()=>{if(!n)return new Map;const g=new Map;let x=0;return n.forEach(y=>{g.has(y.owner_user_id)||(g.set(y.owner_user_id,{name:y.owner_name||"Unknown",avatar:y.owner_avatar_url,color:K1t[x%K1t.length]}),x++)}),g},[n]),d=k.useMemo(()=>Array.from(c.entries()).map(([g,x])=>({id:g,...x})),[c]),u=k.useMemo(()=>{if(!n)return[];let g=n;if(l!=="all"&&(g=g.filter(x=>x.owner_user_id===l)),a.trim()){const x=a.toLowerCase();g=g.filter(y=>{var v,_,j,C;return y.deal_name.toLowerCase().includes(x)||((v=y.contact_name)==null?void 0:v.toLowerCase().includes(x))||((_=y.property_address)==null?void 0:_.toLowerCase().includes(x))||((j=y.city)==null?void 0:j.toLowerCase().includes(x))||((C=y.owner_name)==null?void 0:C.toLowerCase().includes(x))})}return g},[n,a,l]),h=k.useMemo(()=>{const g=new Map;return u.forEach(x=>{const y=x.stage_name||"Unknown";g.has(y)||g.set(y,{name:y,color:x.stage_color,icon:x.stage_icon,deals:[],totalValue:0});const v=g.get(y);v.deals.push(x),v.totalValue+=x.sale_price||0}),Array.from(g.values())},[u]),m=g=>g>=1e6?`$${(g/1e6).toFixed(1)}M`:g>=1e3?`$${(g/1e3).toFixed(0)}K`:`$${g.toFixed(0)}`,p=g=>g?new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(g):null;return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"max-w-[95vw] w-full max-h-[90vh] flex flex-col",children:[e.jsx(Vs,{children:e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(Xn,{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(Yr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search deals...",value:a,onChange:g=>i(g.target.value),className:"pl-9"})]}),e.jsxs(bs,{value:l,onValueChange:o,children:[e.jsx(ys,{className:"w-[180px]",children:e.jsx(_s,{placeholder:"All Members"})}),e.jsxs(vs,{children:[e.jsx(We,{value:"all",children:"All Members"}),d.map(g=>e.jsx(We,{value:g.id,children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"h-2 w-2 rounded-full inline-block",style:{backgroundColor:g.color}}),g.name]})},g.id))]})]}),e.jsxs("div",{className:"hidden md:flex items-center gap-3 ml-auto text-xs text-muted-foreground",children:[d.slice(0,6).map(g=>e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"h-2 w-2 rounded-full",style:{backgroundColor:g.color}}),g.name.split(" ")[0]]},g.id)),d.length>6&&e.jsxs("span",{children:["+",d.length-6," more"]})]})]}),e.jsx("div",{className:"flex-1 overflow-hidden mt-2",children:r?e.jsx("div",{className:"flex gap-4 h-full",children:[1,2,3,4].map(g=>e.jsxs("div",{className:"min-w-[260px] flex-1",children:[e.jsx(fn,{className:"h-12 w-full mb-2 rounded-lg"}),e.jsx(fn,{className:"h-24 w-full mb-2 rounded-lg"}),e.jsx(fn,{className:"h-24 w-full rounded-lg"})]},g))}):h.length===0?e.jsx("div",{className:"flex items-center justify-center h-full text-muted-foreground",children:e.jsxs("div",{className:"text-center",children:[e.jsx(Xn,{className:"h-10 w-10 mx-auto mb-3 opacity-50"}),e.jsx("p",{className:"font-medium",children:"No team deals found"}),e.jsx("p",{className:"text-sm",children:"Team members' deals will appear here."})]})}):e.jsx("div",{className:"flex gap-3 h-full overflow-x-auto pb-2",children:h.map(g=>{const x=g.icon&&n3e[g.icon]||rx;return e.jsxs("div",{className:"flex flex-col h-full min-w-[260px] max-w-[300px] flex-1 bg-muted/30 rounded-xl border border-border/50",children:[e.jsxs("div",{className:"p-3 border-b border-border/50 shrink-0",style:{borderTopColor:g.color||"hsl(var(--border))",borderTopWidth:3},children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-6 h-6 rounded-md flex items-center justify-center",style:{backgroundColor:g.color?`${g.color}20`:void 0},children:e.jsx(x,{className:"h-3.5 w-3.5",style:{color:g.color||void 0}})}),e.jsx("h3",{className:"font-semibold text-sm",children:g.name})]}),e.jsx(qe,{variant:"secondary",className:"text-xs px-2",children:g.deals.length})]}),g.totalValue>0&&e.jsx("p",{className:"text-xs text-muted-foreground ml-8",children:m(g.totalValue)})]}),e.jsx(Eo,{className:"flex-1 p-2",children:e.jsx("div",{className:"space-y-2",children:g.deals.map(y=>{const v=c.get(y.owner_user_id);return e.jsx(fLn,{deal:y,ownerColor:(v==null?void 0:v.color)||"#888",ownerName:(v==null?void 0:v.name)||"Unknown",ownerAvatar:(v==null?void 0:v.avatar)||null,formatPrice:p},y.id)})})})]},g.name)})})}),e.jsxs("p",{className:"text-xs text-muted-foreground text-center pt-2 border-t shrink-0",children:[u.length," deal",u.length!==1?"s":""," across ",h.length," stage",h.length!==1?"s":""," from ",d.length," member",d.length!==1?"s":""]})]})})}function fLn({deal:s,ownerColor:t,ownerName:n,ownerAvatar:r,formatPrice:a}){const i={buyer:{label:"Buyer",className:"bg-blue-500/10 text-blue-600 border-blue-200"},seller:{label:"Seller",className:"bg-emerald-500/10 text-emerald-600 border-emerald-200"},dual:{label:"Dual",className:"bg-purple-500/10 text-purple-600 border-purple-200"},referral:{label:"Referral",className:"bg-orange-500/10 text-orange-600 border-orange-200"},lease:{label:"Lease",className:"bg-cyan-500/10 text-cyan-600 border-cyan-200"}},l=s.deal_type?i[s.deal_type]:null;return e.jsxs("div",{className:"rounded-lg border bg-card p-3 space-y-2 transition-all hover:shadow-sm",style:{borderLeftWidth:4,borderLeftColor:t},children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsxs(Wa,{className:"h-4 w-4",children:[e.jsx(eo,{src:r||""}),e.jsx(Ka,{className:"text-[8px] font-semibold text-white",style:{backgroundColor:t},children:n.charAt(0).toUpperCase()})]}),e.jsx("span",{className:"text-[10px] font-medium truncate",style:{color:t},children:n})]}),e.jsxs("div",{className:"flex items-start justify-between gap-1",children:[e.jsx("h4",{className:"font-medium text-sm leading-tight line-clamp-2",children:s.deal_name}),l&&e.jsx(qe,{variant:"outline",className:Ot("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(ua,{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(Su,{className:"h-3 w-3 text-emerald-500 shrink-0"}),e.jsx("span",{className:"font-semibold text-foreground",children:a(s.sale_price)})]})]})}function pLn({members:s,enabledMembers:t,onToggleMember:n,isOpen:r,onToggleOpen:a}){const i=t.size;return e.jsxs("div",{className:Ot("shrink-0 border-r border-border/50 bg-muted/20 transition-all duration-300 flex flex-col",r?"w-[220px]":"w-[48px]"),children:[e.jsx("div",{className:"p-2 border-b border-border/50 shrink-0",children:e.jsxs($,{variant:"ghost",size:"sm",className:"w-full justify-start gap-2 px-2",onClick:a,children:[e.jsx(Xn,{className:"h-4 w-4 shrink-0 text-primary"}),r&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-xs font-semibold flex-1 text-left",children:"Team"}),i>0&&e.jsx("span",{className:"text-[10px] bg-primary text-primary-foreground rounded-full px-1.5 py-0.5",children:i}),e.jsx(Ld,{className:"h-3 w-3 text-muted-foreground"})]}),!r&&i>0&&e.jsx("span",{className:"absolute -top-1 -right-1 text-[9px] bg-primary text-primary-foreground rounded-full w-4 h-4 flex items-center justify-center",children:i})]})}),r?e.jsxs(Eo,{className:"flex-1 p-2",children:[e.jsx("div",{className:"space-y-1",children:s.map(l=>{const o=t.has(l.id);return e.jsxs("button",{onClick:()=>n(l.id),className:Ot("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(Wa,{className:"h-7 w-7",children:[e.jsx(eo,{src:l.avatar_url||""}),e.jsx(Ka,{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:Ot("text-xs truncate flex-1",o?"font-medium text-foreground":"text-muted-foreground"),children:l.name}),e.jsx(On,{checked:o,onCheckedChange:()=>n(l.id),className:"scale-75",onClick:c=>c.stopPropagation()})]},l.id)})}),s.length===0&&e.jsx("p",{className:"text-xs text-muted-foreground text-center py-4",children:"No team members"})]}):e.jsxs("div",{className:"flex-1 flex flex-col items-center pt-2 gap-2",children:[s.slice(0,5).map(l=>{const o=t.has(l.id);return e.jsx("button",{onClick:()=>n(l.id),className:"relative",title:l.name,children:e.jsxs(Wa,{className:Ot("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(eo,{src:l.avatar_url||""}),e.jsx(Ka,{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 Y1t=["#8B5CF6","#EC4899","#F59E0B","#10B981","#3B82F6","#EF4444","#06B6D4","#F97316"];function gLn(){const s=ai(),{data:t}=gj(),n=(t==null?void 0:t.role)==="team_leader",r=t==null?void 0:t.teamId,a=pt({queryKey:["team-pipeline-members",r,s],queryFn:async()=>{const{data:i,error:l}=await V.from("team_members").select("user_id, role").eq("team_id",r).neq("user_id",s);if(l)throw l;if(!i||i.length===0)return[];const o=i.map(u=>u.user_id),{data:c,error:d}=await V.from("profiles").select("id, name, avatar_url").in("id",o);if(d)throw d;return(c||[]).map((u,h)=>({id:u.id,name:u.name||"Unknown",avatar_url:u.avatar_url,color:Y1t[h%Y1t.length]}))},enabled:!!r&&!!s&&n,staleTime:5*60*1e3});return{isTeamLeader:n,teamMembers:a.data||[],isLoadingMembers:a.isLoading}}function xLn(s){return pt({queryKey:["team-member-deals",s],queryFn:async()=>{if(s.length===0)return[];const{data:t,error:n}=await V.from("deal_pipeline").select(` *, contact:innercircle_contacts(id, first_name, last_name, email, phone), listing:listings(id, property_address, city, state, price, status, created_at), deal_pipeline_stages(name) `).in("owner_user_id",s).order("updated_at",{ascending:!1});if(n)throw n;return(t||[]).map(r=>{var a;return{...r,_stage_name:((a=r.deal_pipeline_stages)==null?void 0:a.name)||null}})},enabled:s.length>0})}function yLn(){const s=ai();return pt({queryKey:["all-deal-tags-map",s],queryFn:async()=>{if(!s)return{tags:[],byDeal:{},unique:[]};const{data:t,error:n}=await V.from("deal_tags").select("id, deal_id, tag").eq("owner_user_id",s);if(n)throw n;const r=t||[],a={},i=new Set;r.forEach(o=>{a[o.deal_id]||(a[o.deal_id]=[]),a[o.deal_id].push(o.tag),i.add(o.tag)});const l=Array.from(i).sort((o,c)=>o.localeCompare(c));return{tags:r,byDeal:a,unique:l}},enabled:!!s})}function tVt({stages:s,currentStageId:t,onStageSelect:n,disabled:r}){const[a,i]=k.useState(!1),l=s.find(c=>c.id===t),o=c=>{c.id!==t&&n(c.id,c.name),i(!1)};return e.jsxs(Au,{open:a,onOpenChange:i,children:[e.jsx(Eu,{asChild:!0,children:e.jsxs($,{variant:"outline",size:"sm",className:"h-7 text-xs gap-1.5",disabled:r,onClick:c=>c.stopPropagation(),children:[l&&e.jsx("div",{className:"w-2 h-2 rounded-full shrink-0",style:{backgroundColor:l.color}}),e.jsx("span",{className:"max-w-[80px] truncate",children:(l==null?void 0:l.name)||"Move"}),e.jsx(fi,{className:"h-3 w-3 shrink-0"})]})}),e.jsx(gu,{align:"end",className:"w-48 z-50 bg-popover",onClick:c=>c.stopPropagation(),children:s.map(c=>{const d=c.icon&&n3e[c.icon]||rx,u=c.id===t;return e.jsxs(Pa,{onClick:()=>o(c),className:Ot("flex items-center gap-2 cursor-pointer",u&&"bg-accent"),children:[e.jsx("div",{className:"w-5 h-5 rounded flex items-center justify-center shrink-0",style:{backgroundColor:`${c.color}20`},children:e.jsx(d,{className:"h-3 w-3",style:{color:c.color}})}),e.jsx("span",{className:"flex-1",children:c.name}),u&&e.jsx(ma,{className:"h-4 w-4 text-primary"})]},c.id)})})]})}const vLn={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"}},bLn={low:{color:"bg-slate-100 text-slate-600",dot:"bg-slate-400",stripe:"bg-slate-300"},medium:{color:"bg-amber-100 text-amber-700",dot:"bg-amber-500",stripe:"bg-amber-400"},high:{color:"bg-orange-100 text-orange-700",dot:"bg-orange-500",stripe:"bg-orange-500"},urgent:{color:"bg-red-100 text-red-700",dot:"bg-red-500",stripe:"bg-red-500"}};function sVt({deal:s,onClick:t,isDragging:n,stages:r,onStageChange:a,showStagePicker:i=!1,isWonStage:l=!1,ownerInfo:o=null,tags:c=[],overdueTaskCount:d=0}){var C,A;const u=AV(),h=vLn[s.deal_type],m=bLn[s.priority],p=k.useMemo(()=>s.target_close_date?I2(ih(s.target_close_date),new Date):null,[s.target_close_date]),g=p!==null&&p<0,x=p!==null&&p<=7&&p>=0,y=k.useMemo(()=>{var P;if(s.deal_type!=="seller"&&s.deal_type!=="dual")return null;const M=((P=s.listing)==null?void 0:P.created_at)||s.listing_date;if(!M)return null;const I=s.contract_date?ih(s.contract_date):new Date;return I2(I,ih(M))},[s]),v=l&&!s.scorecard_transaction_id,_=!!s.scorecard_transaction_id,j=M=>M?new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(M):null;return e.jsxs(we,{className:Ot("cursor-pointer transition-all duration-200 hover:shadow-md hover:border-primary/30 group overflow-hidden",n&&"opacity-50 rotate-2 shadow-xl",g&&"border-red-200 bg-red-50/30",v&&"border-amber-300 bg-amber-50/30 dark:bg-amber-950/20"),onClick:t,style:o?{borderLeftWidth:4,borderLeftColor:o.color}:void 0,children:[!o&&e.jsx("div",{className:Ot("h-1 w-full",m.stripe),"aria-hidden":!0}),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(Wa,{className:"h-4 w-4",children:[e.jsx(eo,{src:o.avatar_url||""}),e.jsx(Ka,{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(qe,{variant:"outline",className:Ot("text-[10px] px-1.5 py-0 shrink-0",h.color),children:h.label})]}),s.contact&&e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx(Wa,{className:"h-5 w-5",children:e.jsxs(Ka,{className:"text-[10px] bg-primary/10 text-primary",children:[(C=s.contact.first_name)==null?void 0:C[0],(A=s.contact.last_name)==null?void 0:A[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(pd,{className:"h-3 w-3 text-primary shrink-0"}),e.jsx("span",{className:"text-primary truncate",children:"Linked to Listing Exchange"})]}),v&&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(ql,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:"truncate font-medium",children:"Add to Scorecard"})]}),_&&l&&e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-green-600 dark:text-green-400",children:[e.jsx(Gr,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:"truncate",children:"Synced to Scorecard"})]}),y!==null&&e.jsxs("div",{className:"flex items-center gap-1.5 text-xs",children:[e.jsx(wm,{className:"h-3 w-3 text-muted-foreground shrink-0"}),e.jsxs("span",{className:Ot("font-medium",y>90?"text-red-600":y>60?"text-amber-600":"text-muted-foreground"),children:[y," DOM"]}),s.contract_date&&e.jsx("span",{className:"text-muted-foreground",children:"(final)"})]}),!s.listing&&(s.property_address||s.city)&&e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-muted-foreground",children:[e.jsx(ua,{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(Su,{className:"h-3 w-3 text-emerald-500 shrink-0"}),e.jsx("span",{className:"font-semibold text-foreground",children:j(s.expected_price)}),s.expected_commission&&e.jsxs("span",{className:"text-muted-foreground",children:["• ",j(s.expected_commission)," GCI"]}),(()=>{const M=c2(s);return M!==null&&M!==s.expected_commission?e.jsxs("span",{className:"text-teal-600 dark:text-teal-400",children:["• ",j(M)," Net"]}):null})()]}),d>0&&e.jsxs("div",{className:"flex items-center gap-1.5 rounded bg-destructive/10 px-2 py-1 text-xs font-medium text-destructive",children:[e.jsx(op,{className:"h-3 w-3 shrink-0"}),e.jsxs("span",{children:[d," overdue task",d>1?"s":""]})]}),c.length>0&&e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[c.slice(0,3).map(M=>e.jsx(W7t,{label:M},M)),c.length>3&&e.jsxs("span",{className:"inline-flex h-6 items-center rounded-full bg-muted px-2 text-[11px] font-medium text-muted-foreground",children:["+",c.length-3]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center justify-between text-[10px] text-muted-foreground",children:[e.jsx("span",{children:"Win probability"}),e.jsxs("span",{className:"font-semibold text-foreground",children:[s.probability,"%"]})]}),e.jsx("div",{className:"h-1.5 w-full overflow-hidden rounded-full bg-muted",children:e.jsx("div",{className:"h-full rounded-full bg-primary transition-all",style:{width:`${Math.min(100,Math.max(0,s.probability??0))}%`}})})]}),e.jsxs("div",{className:"flex items-center justify-between pt-1 border-t border-border/50",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs("div",{className:Ot("flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px]",m.color),children:[e.jsx("div",{className:Ot("w-1.5 h-1.5 rounded-full",m.dot)}),e.jsx("span",{className:"capitalize",children:s.priority})]})}),i&&u&&r&&a?e.jsx(tVt,{stages:r,currentStageId:s.stage_id||"",onStageSelect:(M,I)=>a(s.id,M,I)}):s.target_close_date?e.jsxs("div",{className:Ot("flex items-center gap-1 text-[10px]",g&&"text-red-600",x&&!g&&"text-amber-600",!g&&!x&&"text-muted-foreground"),children:[g?e.jsx(Ho,{className:"h-3 w-3"}):e.jsx(ha,{className:"h-3 w-3"}),e.jsx("span",{children:g?`${Math.abs(p)}d overdue`:x?`${p}d left`:Ys(ih(s.target_close_date),"MMM d")})]}):null]})]})]})}function _Ln({stage:s,deals:t,onDealClick:n,onAddDeal:r,onDragStart:a,onDragOver:i,onDrop:l,isDragOver:o,isWonStage:c=!1,getOwnerInfo:d,tagsByDeal:u={},overdueTasksByDeal:h={}}){const m=k.useRef(null),[p,g]=k.useState(!1),x=t.reduce((C,A)=>C+(A.expected_price||0),0),y=t.reduce((C,A)=>C+(A.expected_commission||0),0),v=t.reduce((C,A)=>C+(c2(A)||0),0),_=C=>C>=1e6?`$${(C/1e6).toFixed(1)}M`:C>=1e3?`$${(C/1e3).toFixed(0)}K`:`$${C.toFixed(0)}`,j=s.icon&&n3e[s.icon]||rx;return p?e.jsxs("div",{className:"flex h-full w-12 shrink-0 flex-col items-center gap-3 rounded-xl border border-border/50 bg-muted/30 py-3",style:{borderTopColor:s.color,borderTopWidth:3},children:[e.jsx("button",{onClick:()=>g(!1),"aria-label":`Expand ${s.name}`,className:"text-muted-foreground transition-colors hover:text-foreground",children:e.jsx(fi,{className:"h-4 w-4"})}),e.jsx(qe,{variant:"secondary",className:"px-1.5 text-[10px]",children:t.length}),e.jsx("span",{className:"mt-1 whitespace-nowrap text-xs font-semibold",style:{writingMode:"vertical-rl",color:s.color},children:s.name})]}):e.jsxs("div",{ref:m,className:Ot("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:C=>i(C,s.id),onDrop:C=>l(C,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.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(qe,{variant:"secondary",className:"text-xs font-medium px-2",children:t.length}),e.jsx("button",{onClick:()=>g(!0),"aria-label":`Collapse ${s.name}`,className:"rounded p-0.5 text-muted-foreground transition-colors hover:bg-accent hover:text-foreground",children:e.jsx(Ld,{className:"h-3.5 w-3.5"})})]})]}),x>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:_(x)}),e.jsx("span",{children:"•"}),e.jsxs("span",{children:[_(y)," GCI"]}),v>0&&v!==y&&e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"•"}),e.jsxs("span",{className:"text-teal-600 dark:text-teal-400",children:[_(v)," Net"]})]})]})]}),e.jsx(Eo,{className:"flex-1 p-2",children:e.jsxs("div",{className:"space-y-2",children:[t.map(C=>e.jsx("div",{draggable:!0,onDragStart:A=>{A.dataTransfer.effectAllowed="move",a(C.id,s.id)},children:e.jsx(sVt,{deal:C,onClick:()=>n(C),isWonStage:c,ownerInfo:(d==null?void 0:d(C))||null,tags:u[C.id]||[],overdueTaskCount:h[C.id]||0})},C.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($,{variant:"ghost",size:"sm",className:"w-full justify-start text-muted-foreground hover:text-foreground",onClick:()=>r(s.id),children:[e.jsx(nn,{className:"h-4 w-4 mr-2"}),"Add Deal"]})})]})}function wLn({formData:s,onChange:t,isEditing:n}){const{isAdmin:r}=ks(),[a,i]=k.useState(s.portal_enabled);if(!r)return e.jsxs("div",{className:"border rounded-lg p-4 opacity-60",children:[e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(kn,{className:"h-4 w-4 text-primary"}),e.jsx("h4",{className:"font-medium text-sm",children:"Client Portal"}),e.jsx(qe,{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(h1,{open:a,onOpenChange:i,children:e.jsxs("div",{className:"border rounded-lg",children:[e.jsxs(m1,{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(kn,{className:"h-4 w-4 text-primary"}),e.jsx("h4",{className:"font-medium text-sm",children:"Client Portal"}),s.portal_enabled&&e.jsx(qe,{className:"text-xs bg-emerald-500/10 text-emerald-600 border-emerald-200",variant:"outline",children:"Enabled"})]}),e.jsx(Go,{className:Ot("h-4 w-4 text-muted-foreground transition-transform",a&&"rotate-180")})]}),e.jsx(f1,{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(re,{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(On,{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(re,{className:"text-sm font-medium",children:"Portal Visibility"}),e.jsxs(m_,{value:s.visibility,onValueChange:o=>l({visibility:o}),className:"grid grid-cols-2 gap-3",children:[e.jsxs("label",{className:Ot("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(Yh,{value:"private"}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(fu,{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:Ot("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(Yh,{value:"public"}),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:"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(Li,{id:"require_onboarding",checked:s.require_onboarding,onCheckedChange:o=>l({require_onboarding:!!o}),className:"mt-0.5"}),e.jsxs("div",{children:[e.jsx(re,{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(Li,{id:"allow_spouse",checked:s.allow_spouse,onCheckedChange:o=>l({allow_spouse:!!o})}),e.jsx(re,{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(re,{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(re,{className:"text-xs text-muted-foreground",children:"Client Full Name"}),e.jsx(be,{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(re,{className:"text-xs text-muted-foreground",children:"Email"}),e.jsx(be,{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(re,{className:"text-xs text-muted-foreground",children:"Phone"}),e.jsx(be,{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(re,{className:"text-xs text-muted-foreground",children:"Preferred Invite Method"}),e.jsxs(bs,{value:s.invite_method,onValueChange:o=>l({invite_method:o}),children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"email",children:"Email"}),e.jsxs(We,{value:"sms",disabled:!s.client_phone,children:["SMS ",!s.client_phone&&"(add phone first)"]})]})]})]})]})]})]})]})})]})})}const jLn=[{value:"buyer",label:"Buyer"},{value:"seller",label:"Seller"},{value:"dual",label:"Dual Agency"},{value:"referral",label:"Referral"},{value:"lease",label:"Lease"}],NLn=[{value:"low",label:"Low"},{value:"medium",label:"Medium"},{value:"high",label:"High"},{value:"urgent",label:"Urgent"}];function kLn({open:s,onOpenChange:t,deal:n,defaultStageId:r}){const{data:a}=_te(),{data:i}=vv(),{data:l}=FMt(),o=pAe(),c=Zqt(),d=Xqt(),u=UZe(),[h,m]=k.useState({portal_enabled:!1,visibility:"private",require_onboarding:!0,allow_spouse:!1,client_name:"",client_email:"",client_phone:"",invite_method:"email"}),[p,g]=k.useState(""),[x,y]=k.useState(!1),[v,_]=k.useState(!1),[j,C]=k.useState({first_name:"",last_name:"",email:"",phone:""}),A=(l==null?void 0:l.filter(G=>((n==null?void 0:n.listing_id)===G.id,!0)))||[],[M,I]=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 G,H,Y,se,ee,oe,me,Q,te;s&&(n?(I({deal_name:n.deal_name,deal_type:n.deal_type,stage_id:n.stage_id||"",contact_id:n.contact_id||"",listing_id:n.listing_id||"",property_address:n.property_address||"",city:n.city||"",state:n.state||"",zip_code:n.zip_code||"",expected_price:((G=n.expected_price)==null?void 0:G.toString())||"",commission_percentage:((H=n.commission_percentage)==null?void 0:H.toString())||"3",brokerage_split_pct:((Y=n.brokerage_split_pct)==null?void 0:Y.toString())||"",team_split_pct:((se=n.team_split_pct)==null?void 0:se.toString())||"",referral_fee_pct:((ee=n.referral_fee_pct)==null?void 0:ee.toString())||"",franchise_fee_pct:((oe=n.franchise_fee_pct)==null?void 0:oe.toString())||"",transaction_fee:((me=n.transaction_fee)==null?void 0:me.toString())||"",commission_calc_method:n.commission_calc_method||"standard",target_close_date:n.target_close_date?ih(n.target_close_date):void 0,contract_date:n.contract_date?ih(n.contract_date):void 0,listing_date:n.listing_date?ih(n.listing_date):void 0,priority:n.priority,probability:n.probability.toString(),notes:n.notes||""}),n.contact&&g(`${n.contact.first_name} ${n.contact.last_name}`)):(I({deal_name:"",deal_type:"buyer",stage_id:r||((Q=a==null?void 0:a[0])==null?void 0:Q.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:String(((te=a==null?void 0:a.find(le=>{var fe;return le.id===(r||((fe=a==null?void 0:a[0])==null?void 0:fe.id))}))==null?void 0:te.default_probability)??50),notes:""}),g(""),m({portal_enabled:!1,visibility:"private",require_onboarding:!0,allow_spouse:!1,client_name:"",client_email:"",client_phone:"",invite_method:"email"})))},[s,n,r,a]);const P=i==null?void 0:i.filter(G=>{var le,fe,_e,ve,he;const H=p.toLowerCase().trim();if(!H)return!0;const Y=((le=G.first_name)==null?void 0:le.toLowerCase())||"",se=((fe=G.last_name)==null?void 0:fe.toLowerCase())||"",ee=((_e=G.email)==null?void 0:_e.toLowerCase())||"",oe=((he=(ve=G.phone)==null?void 0:ve.toLowerCase)==null?void 0:he.call(ve))||"",me=`${Y} ${se}`.trim(),Q=`${se} ${Y}`.trim();if(me.includes(H)||Q.includes(H)||Y.includes(H)||se.includes(H)||ee.includes(H)||oe.includes(H))return!0;const te=H.split(/\s+/).filter(Boolean);return te.length>1?te.every(Se=>Y.includes(Se)||se.includes(Se)||ee.includes(Se)||oe.includes(Se)):!1}).slice(0,8),R=()=>{const G=parseFloat(M.expected_price)||0,H=parseFloat(M.commission_percentage)||0;return G*(H/100)},O=()=>{const G=R();if(!G)return null;const H=parseFloat(M.brokerage_split_pct)||0,Y=parseFloat(M.team_split_pct)||0,se=parseFloat(M.referral_fee_pct)||0,ee=parseFloat(M.franchise_fee_pct)||0,oe=parseFloat(M.transaction_fee)||0;if(M.commission_calc_method==="referral_first"){let Q=G;se&&(Q-=G*se/100);let te=Q;return H&&(te-=Q*H/100),Y&&(te-=G*Y/100),ee&&(te-=G*ee/100),oe&&(te-=oe),Math.max(0,te)}let me=G;return H&&(me=me*((100-H)/100)),Y&&(me=me*((100-Y)/100)),se&&(me=me-G*se/100),ee&&(me=me-G*ee/100),oe&&(me=me-oe),Math.max(0,me)},B=async G=>{var H,Y,se;if(G.preventDefault(),!M.deal_name.trim()){ae.error("Please enter a deal name");return}try{const ee={deal_name:M.deal_name,deal_type:M.deal_type,stage_id:M.stage_id||null,contact_id:M.contact_id||null,listing_id:M.listing_id||null,property_address:M.property_address||null,city:M.city||null,state:M.state||null,zip_code:M.zip_code||null,expected_price:M.expected_price?parseFloat(M.expected_price):null,expected_commission:R()||null,commission_percentage:M.commission_percentage?parseFloat(M.commission_percentage):3,brokerage_split_pct:M.brokerage_split_pct?parseFloat(M.brokerage_split_pct):null,team_split_pct:M.team_split_pct?parseFloat(M.team_split_pct):null,referral_fee_pct:M.referral_fee_pct?parseFloat(M.referral_fee_pct):null,franchise_fee_pct:M.franchise_fee_pct?parseFloat(M.franchise_fee_pct):null,transaction_fee:M.transaction_fee?parseFloat(M.transaction_fee):null,commission_calc_method:M.commission_calc_method,target_close_date:((H=M.target_close_date)==null?void 0:H.toISOString().split("T")[0])||null,contract_date:((Y=M.contract_date)==null?void 0:Y.toISOString().split("T")[0])||null,listing_date:((se=M.listing_date)==null?void 0:se.toISOString().split("T")[0])||null,priority:M.priority,probability:parseInt(M.probability)||50,notes:M.notes||null};if(n)await d.mutateAsync({id:n.id,...ee}),ae.success("Deal updated successfully");else{const oe=await c.mutateAsync(ee);if(ae.success("Deal created successfully"),h.portal_enabled&&(oe!=null&&oe.id))try{await u.mutateAsync({deal_id:oe.id,visibility:h.visibility,require_onboarding:h.require_onboarding,allow_spouse:h.allow_spouse,client_name:h.client_name||null,client_email:h.client_email||null,client_phone:h.client_phone||null,invite_method:h.invite_method}),ae.success("Client portal created!")}catch{ae.error("Deal created, but portal setup failed")}}t(!1)}catch{ae.error("Failed to save deal")}},U=c.isPending||d.isPending;return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(Vs,{children:[e.jsx($s,{children:n?"Edit Deal":"Add New Deal"}),e.jsx(Cr,{children:n?"Update the deal details below.":"Enter the details for your new deal."})]}),e.jsxs("form",{onSubmit:B,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(re,{htmlFor:"deal_name",children:"Deal Name *"}),e.jsx(be,{id:"deal_name",value:M.deal_name,onChange:G=>I(H=>({...H,deal_name:G.target.value})),placeholder:"e.g., Smith Family - 123 Main St"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Deal Type"}),e.jsxs(bs,{value:M.deal_type,onValueChange:G=>I(H=>({...H,deal_type:G})),children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsx(vs,{children:jLn.map(G=>e.jsx(We,{value:G.value,children:G.label},G.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Stage"}),e.jsxs(bs,{value:M.stage_id||"none",onValueChange:G=>{const H=G==="none"?"":G,Y=a==null?void 0:a.find(se=>se.id===H);I(se=>({...se,stage_id:H,probability:typeof(Y==null?void 0:Y.default_probability)=="number"?String(Y.default_probability):se.probability}))},children:[e.jsx(ys,{children:e.jsx(_s,{placeholder:"Select stage"})}),e.jsxs(vs,{children:[e.jsx(We,{value:"none",children:"No Stage"}),a==null?void 0:a.map(G=>e.jsx(We,{value:G.id,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-2 h-2 rounded-full",style:{backgroundColor:G.color}}),G.name]})},G.id))]})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Link to Contact"}),e.jsxs("div",{className:"relative",children:[e.jsx(Yr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{value:p,onChange:G=>{g(G.target.value),y(!0),_(!1),G.target.value||I(H=>({...H,contact_id:""}))},onFocus:()=>y(!0),placeholder:"Search contacts...",className:"pl-9"}),x&&p&&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:[P&&P.length>0?P.map(G=>e.jsxs("button",{type:"button",className:"w-full px-3 py-2 text-left hover:bg-muted flex items-center gap-2",onClick:()=>{I(H=>({...H,contact_id:G.id})),g(`${G.first_name} ${G.last_name}`),y(!1)},children:[e.jsx(el,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{children:[G.first_name," ",G.last_name]}),G.email&&e.jsx("span",{className:"text-xs text-muted-foreground ml-auto",children:G.email})]},G.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 G=p.trim().split(/\s+/);C({first_name:G[0]||"",last_name:G.slice(1).join(" ")||"",email:"",phone:""}),_(!0),y(!1)},children:[e.jsx(Pl,{className:"h-4 w-4"}),e.jsxs("span",{children:['Create new contact "',p.trim(),'"']})]})]})]}),v&&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(Pl,{className:"h-3.5 w-3.5"}),"Quick Add Contact"]}),e.jsx($,{type:"button",variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",onClick:()=>_(!1),children:"Cancel"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(be,{placeholder:"First name *",value:j.first_name,onChange:G=>C(H=>({...H,first_name:G.target.value})),className:"h-8 text-sm"}),e.jsx(be,{placeholder:"Last name",value:j.last_name,onChange:G=>C(H=>({...H,last_name:G.target.value})),className:"h-8 text-sm"}),e.jsx(be,{placeholder:"Email",type:"email",value:j.email,onChange:G=>C(H=>({...H,email:G.target.value})),className:"h-8 text-sm"}),e.jsx(be,{placeholder:"Phone",type:"tel",value:j.phone,onChange:G=>C(H=>({...H,phone:G.target.value})),className:"h-8 text-sm"})]}),e.jsx($,{type:"button",size:"sm",className:"w-full h-8",disabled:!j.first_name.trim()||o.isPending,onClick:async()=>{try{const G=await o.mutateAsync({first_name:j.first_name.trim(),last_name:j.last_name.trim()||null,email:j.email.trim()||null,phone:j.phone.trim()||null});G&&(I(H=>({...H,contact_id:G.id})),g(`${G.first_name} ${G.last_name||""}`.trim()),_(!1))}catch{}},children:o.isPending?e.jsxs(e.Fragment,{children:[e.jsx(Jt,{className:"h-3.5 w-3.5 mr-1 animate-spin"})," Creating..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Pl,{className:"h-3.5 w-3.5 mr-1"})," Add & Link Contact"]})})]})]}),A.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(re,{className:"flex items-center gap-2",children:[e.jsx(pd,{className:"h-4 w-4"}),"Link to Listing Exchange"]}),e.jsxs(bs,{value:M.listing_id||"none",onValueChange:G=>{const H=G==="none"?"":G,Y=A.find(se=>se.id===H);I(Y?se=>{var ee;return{...se,listing_id:H,deal_type:"seller",property_address:Y.property_address||se.property_address,city:Y.city||se.city,state:Y.state||se.state,expected_price:((ee=Y.price)==null?void 0:ee.toString())||se.expected_price}}:se=>({...se,listing_id:H}))},children:[e.jsx(ys,{children:e.jsx(_s,{placeholder:"Select a listing to sync status..."})}),e.jsxs(vs,{children:[e.jsx(We,{value:"none",children:"None"}),A.map(G=>e.jsx(We,{value:G.id,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{children:G.property_address||`${G.city}, ${G.state}`}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["$",(G.price/1e3).toFixed(0),"K"]})]})},G.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(re,{htmlFor:"property_address",children:"Address"}),e.jsx(be,{id:"property_address",value:M.property_address,onChange:G=>I(H=>({...H,property_address:G.target.value})),placeholder:"123 Main Street"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"city",children:"City"}),e.jsx(be,{id:"city",value:M.city,onChange:G=>I(H=>({...H,city:G.target.value}))})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"state",children:"State"}),e.jsx(be,{id:"state",value:M.state,onChange:G=>I(H=>({...H,state:G.target.value})),maxLength:2,placeholder:"TX"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"zip_code",children:"ZIP"}),e.jsx(be,{id:"zip_code",value:M.zip_code,onChange:G=>I(H=>({...H,zip_code:G.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(re,{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(be,{id:"expected_price",type:"number",value:M.expected_price,onChange:G=>I(H=>({...H,expected_price:G.target.value})),className:"pl-7",placeholder:"500000"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"commission_percentage",children:"Commission %"}),e.jsxs("div",{className:"relative",children:[e.jsx(be,{id:"commission_percentage",type:"number",step:"0.1",value:M.commission_percentage,onChange:G=>I(H=>({...H,commission_percentage:G.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(re,{children:"Expected GCI"}),e.jsx(be,{value:R()?`$${R().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(re,{className:"text-xs whitespace-nowrap",children:"Calculation Method:"}),e.jsxs(bs,{value:M.commission_calc_method,onValueChange:G=>I(H=>({...H,commission_calc_method:G})),children:[e.jsx(ys,{className:"h-7 text-xs",children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"standard",children:"Standard (all splits on GCI)"}),e.jsx(We,{value:"referral_first",children:"Referral First (brokerage split after referral)"})]})]})]}),M.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(re,{className:"text-xs",children:"Brokerage Split"}),e.jsxs("div",{className:"relative",children:[e.jsx(be,{type:"number",step:"1",min:"0",max:"100",value:M.brokerage_split_pct,onChange:G=>I(H=>({...H,brokerage_split_pct:G.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(re,{className:"text-xs",children:"Team Split"}),e.jsxs("div",{className:"relative",children:[e.jsx(be,{type:"number",step:"1",min:"0",max:"100",value:M.team_split_pct,onChange:G=>I(H=>({...H,team_split_pct:G.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(re,{className:"text-xs",children:"Referral Fee"}),e.jsxs("div",{className:"relative",children:[e.jsx(be,{type:"number",step:"1",min:"0",max:"100",value:M.referral_fee_pct,onChange:G=>I(H=>({...H,referral_fee_pct:G.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(re,{className:"text-xs",children:"Franchise Fee"}),e.jsxs("div",{className:"relative",children:[e.jsx(be,{type:"number",step:"1",min:"0",max:"100",value:M.franchise_fee_pct,onChange:G=>I(H=>({...H,franchise_fee_pct:G.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(re,{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(be,{type:"number",step:"1",min:"0",value:M.transaction_fee,onChange:G=>I(H=>({...H,transaction_fee:G.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(re,{className:"text-xs",children:"Net to Agent"}),e.jsx(be,{value:O()?`$${Math.round(O()).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(re,{children:"Target Close Date"}),e.jsxs(Xc,{children:[e.jsx(Qc,{asChild:!0,children:e.jsxs($,{variant:"outline",className:Ot("w-full justify-start text-left font-normal",!M.target_close_date&&"text-muted-foreground"),children:[e.jsx(ha,{className:"mr-2 h-4 w-4"}),M.target_close_date?Ys(M.target_close_date,"PPP"):"Pick a date"]})}),e.jsx(Bc,{className:"w-auto p-0",align:"start",children:e.jsx(vb,{mode:"single",selected:M.target_close_date,onSelect:G=>I(H=>({...H,target_close_date:G})),initialFocus:!0,className:"pointer-events-auto"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Contract Date"}),e.jsxs(Xc,{children:[e.jsx(Qc,{asChild:!0,children:e.jsxs($,{variant:"outline",className:Ot("w-full justify-start text-left font-normal",!M.contract_date&&"text-muted-foreground"),children:[e.jsx(ha,{className:"mr-2 h-4 w-4"}),M.contract_date?Ys(M.contract_date,"PPP"):"Pick a date"]})}),e.jsx(Bc,{className:"w-auto p-0",align:"start",children:e.jsx(vb,{mode:"single",selected:M.contract_date,onSelect:G=>I(H=>({...H,contract_date:G})),initialFocus:!0,className:"pointer-events-auto"})})]})]}),(M.deal_type==="seller"||M.deal_type==="dual")&&!M.listing_id&&e.jsxs("div",{className:"space-y-2 col-span-2",children:[e.jsx(re,{children:"Listing Date (for Days on Market)"}),e.jsxs(Xc,{children:[e.jsx(Qc,{asChild:!0,children:e.jsxs($,{variant:"outline",className:Ot("w-full justify-start text-left font-normal",!M.listing_date&&"text-muted-foreground"),children:[e.jsx(ha,{className:"mr-2 h-4 w-4"}),M.listing_date?Ys(M.listing_date,"PPP"):"Pick a date"]})}),e.jsx(Bc,{className:"w-auto p-0",align:"start",children:e.jsx(vb,{mode:"single",selected:M.listing_date,onSelect:G=>I(H=>({...H,listing_date:G})),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(re,{children:"Priority"}),e.jsxs(bs,{value:M.priority,onValueChange:G=>I(H=>({...H,priority:G})),children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsx(vs,{children:NLn.map(G=>e.jsx(We,{value:G.value,children:G.label},G.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Win Probability"}),e.jsxs("div",{className:"relative",children:[e.jsx(be,{type:"number",min:"0",max:"100",value:M.probability,onChange:G=>I(H=>({...H,probability:G.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(re,{htmlFor:"notes",children:"Notes"}),e.jsx(Ls,{id:"notes",value:M.notes,onChange:G=>I(H=>({...H,notes:G.target.value})),placeholder:"Add any additional notes about this deal...",rows:3})]}),!n&&e.jsx(wLn,{formData:h,onChange:m}),e.jsxs("div",{className:"flex justify-end gap-3 pt-4 border-t",children:[e.jsx($,{type:"button",variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs($,{type:"submit",disabled:U,children:[U&&e.jsx(Jt,{className:"h-4 w-4 mr-2 animate-spin"}),n?"Update Deal":"Create Deal"]})]})]})]})})}function SLn({dealId:s}){const t=ai(),n=ls(),[r,a]=k.useState(""),[i,l]=k.useState(!1),{data:o=[]}=pt({queryKey:["deal-tags",s],queryFn:async()=>{const{data:g,error:x}=await V.from("deal_tags").select("*").eq("deal_id",s).order("created_at");if(x)throw x;return g},enabled:!!s}),{data:c=[]}=pt({queryKey:["all-deal-tags",t],queryFn:async()=>{if(!t)return[];const{data:g,error:x}=await V.from("deal_tags").select("tag").eq("owner_user_id",t);if(x)throw x;return[...new Set(g.map(v=>v.tag))].sort()},enabled:!!t}),d=Nt({mutationFn:async g=>{if(!t)throw new Error("Not authenticated");const{error:x}=await V.from("deal_tags").insert({deal_id:s,owner_user_id:t,tag:g.trim()});if(x)throw x},onSuccess:()=>{n.invalidateQueries({queryKey:["deal-tags",s]}),n.invalidateQueries({queryKey:["all-deal-tags"]}),a("")}}),u=Nt({mutationFn:async g=>{const{error:x}=await V.from("deal_tags").delete().eq("id",g);if(x)throw x},onSuccess:()=>{n.invalidateQueries({queryKey:["deal-tags",s]})}}),h=()=>{const g=r.trim();g&&(o.some(x=>x.tag.toLowerCase()===g.toLowerCase())||d.mutate(g))},m=o.map(g=>g.tag.toLowerCase()),p=c.filter(g=>g.toLowerCase().includes(r.toLowerCase())&&!m.includes(g.toLowerCase())).slice(0,5);return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[o.map(g=>e.jsxs(qe,{variant:"secondary",className:"gap-1 text-xs",children:[g.tag,e.jsx("button",{type:"button",onClick:()=>u.mutate(g.id),className:"ml-0.5 hover:text-destructive",children:e.jsx(mr,{className:"h-3 w-3"})})]},g.id)),!i&&e.jsxs("button",{type:"button",onClick:()=>l(!0),className:"flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground px-2 py-0.5 rounded border border-dashed border-border hover:border-primary transition-colors",children:[e.jsx(nn,{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(be,{value:r,onChange:g=>a(g.target.value),onKeyDown:g=>{g.key==="Enter"&&(g.preventDefault(),h()),g.key==="Escape"&&(l(!1),a(""))},placeholder:"Type tag name...",className:"h-8 text-xs flex-1",autoFocus:!0}),e.jsx("button",{type:"button",onClick:h,disabled:!r.trim()||d.isPending,className:"h-8 px-3 rounded-md bg-primary text-primary-foreground text-xs font-medium disabled:opacity-50 shrink-0",children:"Add"}),e.jsx("button",{type:"button",onClick:()=>{l(!1),a("")},className:"h-8 px-2 rounded-md bg-muted text-muted-foreground text-xs shrink-0",children:"Cancel"})]}),r&&p.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:p.map(g=>e.jsx("button",{type:"button",className:"w-full px-3 py-2 text-left text-xs hover:bg-muted active:bg-muted",onClick:x=>{x.preventDefault(),d.mutate(g)},children:g},g))})]})]})}function CLn(s){return pt({queryKey:["deal-files",s],queryFn:async()=>{const{data:t,error:n}=await V.from("deal_files").select("*").eq("deal_id",s).order("created_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function ALn(){const s=ai(),t=ls();return Nt({mutationFn:async({dealId:n,file:r})=>{if(!s)throw new Error("Not authenticated");const a=r.name.split(".").pop(),i=`${s}/${n}/${crypto.randomUUID()}.${a}`,{error:l}=await V.storage.from("deal-files").upload(i,r);if(l)throw l;const{data:o,error:c}=await V.from("deal_files").insert({deal_id:n,owner_user_id:s,file_name:r.name,file_size:r.size,file_type:r.type||null,storage_path:i}).select().single();if(c)throw c;return o},onSuccess:(n,r)=>{t.invalidateQueries({queryKey:["deal-files",r.dealId]})}})}function ELn(){const s=ls();return Nt({mutationFn:async({fileId:t,storagePath:n,dealId:r})=>{await V.storage.from("deal-files").remove([n]);const{error:a}=await V.from("deal_files").delete().eq("id",t);if(a)throw a;return r},onSuccess:t=>{s.invalidateQueries({queryKey:["deal-files",t]})}})}function TLn(){const s=ls();return Nt({mutationFn:async({fileId:t,visible:n,dealId:r})=>{const{error:a}=await V.from("deal_files").update({visible_on_portal:n}).eq("id",t);if(a)throw a;return r},onSuccess:t=>{s.invalidateQueries({queryKey:["deal-files",t]})}})}async function MLn(s){const{data:t,error:n}=await V.storage.from("deal-files").createSignedUrl(s,3600);if(n)throw n;return t.signedUrl}const Z1t={text:"Short Text",textarea:"Long Text",dropdown:"Dropdown",toggle:"Yes / No"};function nVt({open:s,onOpenChange:t}){const{data:n,isLoading:r}=q5n(),a=V5n(),i=H5n(),l=G5n(),[o,c]=k.useState(!1),[d,u]=k.useState({question_text:"",field_type:"text",options:[],is_required:!1}),[h,m]=k.useState(""),p=async()=>{if(d.question_text.trim())try{await a.mutateAsync({question_text:d.question_text.trim(),field_type:d.field_type,options:d.field_type==="dropdown"?d.options:[],is_required:d.is_required,sort_order:((n==null?void 0:n.length)||0)+1}),u({question_text:"",field_type:"text",options:[],is_required:!1}),m(""),c(!1),ae.success("Question added")}catch{ae.error("Failed to add question")}},g=async _=>{try{await l.mutateAsync(_),ae.success("Question removed")}catch{ae.error("Failed to remove question")}},x=async(_,j)=>{try{await i.mutateAsync({id:_,is_required:j})}catch{ae.error("Failed to update question")}},y=()=>{h.trim()&&(u(_=>({..._,options:[..._.options,h.trim()]})),m(""))},v=_=>{u(j=>({...j,options:j.options.filter((C,A)=>A!==_)}))};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"max-w-md max-h-[85vh] flex flex-col",children:[e.jsxs(Vs,{children:[e.jsx($s,{children:"Custom Intake Questions"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"These questions appear on all your portal onboarding forms."})]}),e.jsx(Eo,{className:"flex-1",children:e.jsxs("div",{className:"space-y-3 pr-2",children:[r&&e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(Jt,{className:"h-5 w-5 animate-spin text-muted-foreground"})}),n==null?void 0:n.map(_=>{var j;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(Bp,{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:_.question_text}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(qe,{variant:"secondary",className:"text-xs",children:Z1t[_.field_type]||_.field_type}),_.is_required&&e.jsx(qe,{variant:"outline",className:"text-xs",children:"Required"})]}),_.field_type==="dropdown"&&((j=_.options)==null?void 0:j.length)>0&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["Options: ",_.options.join(", ")]})]}),e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[e.jsx(On,{checked:_.is_required,onCheckedChange:C=>x(_.id,C),className:"scale-75"}),e.jsx($,{variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground hover:text-destructive",onClick:()=>g(_.id),children:e.jsx(Un,{className:"h-3.5 w-3.5"})})]})]})},_.id)}),!r&&(n==null?void 0:n.length)===0&&!o&&e.jsxs("div",{className:"text-center py-8 border border-dashed rounded-lg",children:[e.jsx("p",{className:"text-sm text-muted-foreground mb-2",children:"No custom questions yet"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Add questions that clients will answer during onboarding."})]}),o&&e.jsxs("div",{className:"border-2 border-primary/20 rounded-lg p-4 space-y-3 bg-primary/5",children:[e.jsxs("div",{children:[e.jsx(re,{className:"text-sm font-medium",children:"Question"}),e.jsx(be,{value:d.question_text,onChange:_=>u(j=>({...j,question_text:_.target.value})),className:"mt-1",placeholder:"e.g., Do you have a home to sell first?",autoFocus:!0})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-sm font-medium",children:"Answer Type"}),e.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:Object.entries(Z1t).map(([_,j])=>e.jsx("button",{type:"button",onClick:()=>u(C=>({...C,field_type:_,options:[]})),className:`px-3 py-1.5 rounded-full text-xs font-medium border transition-colors ${d.field_type===_?"bg-primary text-primary-foreground border-primary":"bg-background text-muted-foreground border-input hover:border-primary/50"}`,children:j},_))})]}),d.field_type==="dropdown"&&e.jsxs("div",{children:[e.jsx(re,{className:"text-sm font-medium",children:"Options"}),e.jsxs("div",{className:"space-y-1.5 mt-1.5",children:[d.options.map((_,j)=>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:_}),e.jsx("button",{onClick:()=>v(j),className:"text-muted-foreground hover:text-destructive",children:e.jsx(mr,{className:"h-3.5 w-3.5"})})]},j)),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(be,{value:h,onChange:_=>m(_.target.value),onKeyDown:_=>_.key==="Enter"&&(_.preventDefault(),y()),placeholder:"Add option...",className:"h-8 text-sm"}),e.jsx($,{variant:"outline",size:"sm",onClick:y,disabled:!h.trim(),className:"h-8",children:e.jsx(nn,{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(On,{checked:d.is_required,onCheckedChange:_=>u(j=>({...j,is_required:_}))}),e.jsx(re,{className:"text-xs text-muted-foreground",children:"Required"})]})}),e.jsxs("div",{className:"flex gap-2 pt-1",children:[e.jsx($,{variant:"outline",size:"sm",onClick:()=>c(!1),className:"flex-1",children:"Cancel"}),e.jsxs($,{size:"sm",onClick:p,disabled:!d.question_text.trim()||a.isPending,className:"flex-1",children:[a.isPending?e.jsx(Jt,{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($,{variant:"outline",size:"sm",onClick:()=>c(!0),children:[e.jsx(nn,{className:"h-4 w-4 mr-1"})," Add Question"]}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>t(!1),children:"Done"})]})]})})}function PLn({override:s,onChange:t}){const n=ai(),{data:r}=aMt(),[a,i]=k.useState(null),l=d=>t({...s,...d}),o=async(d,u)=>{if(n){if(d.size>5*1024*1024){ae.error("Image must be under 5MB");return}i(u);try{const h=await iMt(n,d,`${u}`);l(u==="logo"?{logo_url:h}:{cover_photo_url:h})}catch(h){ae.error(`Upload failed: ${h.message||h}`)}finally{i(null)}}},c=Object.values(s||{}).some(d=>d!=null&&d!=="");return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-start gap-2 p-3 rounded-md bg-primary/5 border border-primary/10",children:[e.jsx(kn,{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(X1t,{label:"Logo",value:s.logo_url??null,globalValue:(r==null?void 0:r.logo_url)??null,uploading:a==="logo",onUpload:d=>o(d,"logo"),onClear:()=>l({logo_url:null}),aspect:"square"}),e.jsx(X1t,{label:"Cover Photo",value:s.cover_photo_url??null,globalValue:(r==null?void 0:r.cover_photo_url)??null,uploading:a==="cover",onUpload:d=>o(d,"cover"),onClear:()=>l({cover_photo_url:null}),aspect:"cover"}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(Q1t,{label:"Brand Color",value:s.brand_color??null,globalValue:(r==null?void 0:r.brand_color)??null,onChange:d=>l({brand_color:d})}),e.jsx(Q1t,{label:"Accent Color",value:s.accent_color??null,globalValue:(r==null?void 0:r.accent_color)??null,onChange:d=>l({accent_color:d})})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-sm font-medium",children:"Tagline"}),e.jsx(be,{value:s.tagline||"",onChange:d=>l({tagline:d.target.value||null}),placeholder:(r==null?void 0:r.tagline)||"Your trusted real estate advisor",maxLength:80,className:"mt-1"})]}),c&&e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>t({}),className:"text-xs text-muted-foreground hover:text-destructive",children:[e.jsx(Un,{className:"h-3 w-3 mr-1"}),"Clear all overrides"]})]})}function X1t({label:s,value:t,globalValue:n,uploading:r,onUpload:a,onClear:i,aspect:l}){const o=t||n,c=!!t;return e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(re,{className:"text-sm font-medium",children:s}),c?e.jsx("span",{className:"text-[10px] font-medium text-primary",children:"Overridden"}):n?e.jsx("span",{className:"text-[10px] text-muted-foreground",children:"Using global"}):null]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:Ot("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(zc,{className:"h-5 w-5 text-muted-foreground/40"})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("label",{className:"cursor-pointer",children:[e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:d=>{var h;const u=(h=d.target.files)==null?void 0:h[0];u&&a(u),d.target.value=""}}),e.jsxs("span",{className:"inline-flex items-center gap-1.5 h-9 px-3 rounded-md border border-input bg-background hover:bg-accent text-sm font-medium",children:[r?e.jsx(Jt,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(gi,{className:"h-3.5 w-3.5"}),t?"Replace":"Override"]})]}),t&&e.jsx($,{variant:"ghost",size:"sm",onClick:i,className:"text-muted-foreground hover:text-destructive",children:e.jsx(Un,{className:"h-3.5 w-3.5"})})]})]})]})}function Q1t({label:s,value:t,globalValue:n,onChange:r}){const a=t||n||"#000000",i=!!t;return e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(re,{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:Ot("mt-1 flex items-center gap-2 h-9 rounded-md border bg-background px-2",i?"border-primary":"border-input"),children:[e.jsx("input",{type:"color",value:a,onChange:l=>r(l.target.value),className:"h-6 w-8 rounded cursor-pointer border-0 bg-transparent"}),e.jsx(be,{value:t||"",onChange:l=>r(l.target.value||null),placeholder:n||"#406E71",className:"border-0 h-7 px-1 focus-visible:ring-0 text-xs font-mono"}),t&&e.jsx($,{variant:"ghost",size:"sm",onClick:()=>r(null),className:"h-6 w-6 p-0 text-muted-foreground hover:text-destructive",children:e.jsx(Un,{className:"h-3 w-3"})})]})]})}function ILn({portalId:s,agentUserId:t}){const n=ls(),{data:r,isLoading:a}=pt({queryKey:["portal-vendor-manage",s,t],queryFn:async()=>{const{data:h}=await V.from("profiles").select("brokerage_id").eq("id",t).maybeSingle(),m=h==null?void 0:h.brokerage_id,p=V.from("vendors").select("*").eq("is_active",!0),g=m?p.or(`and(owner_type.eq.agent,owner_user_id.eq.${t}),and(owner_type.eq.brokerage,owner_brokerage_id.eq.${m})`):p.eq("owner_type","agent").eq("owner_user_id",t),[{data:x,error:y},{data:v},{data:_}]=await Promise.all([g.order("sort_order",{ascending:!0}).order("name",{ascending:!0}),V.from("agent_vendor_selections").select("vendor_id, is_visible").eq("agent_user_id",t),V.from("portal_vendor_overrides").select("vendor_id, is_visible").eq("portal_id",s)]);if(y)throw y;const j=new Map;(v||[]).forEach(A=>j.set(A.vendor_id,A.is_visible));const C=new Map;return(_||[]).forEach(A=>C.set(A.vendor_id,A.is_visible)),{vendors:x||[],selMap:j,overrideMap:C}}}),i=Nt({mutationFn:async({vendorId:h,isVisible:m})=>{const{data:p}=await V.from("portal_vendor_overrides").select("id").eq("portal_id",s).eq("vendor_id",h).maybeSingle();if(p){const{error:g}=await V.from("portal_vendor_overrides").update({is_visible:m}).eq("id",p.id);if(g)throw g}else{const{error:g}=await V.from("portal_vendor_overrides").insert({portal_id:s,vendor_id:h,is_visible:m});if(g)throw g}},onSuccess:()=>{n.invalidateQueries({queryKey:["portal-vendor-manage",s,t]}),n.invalidateQueries({queryKey:["portal-vendors",s]})},onError:h=>ae.error(h.message)});if(a)return e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(Jt,{className:"w-5 h-5 animate-spin text-muted-foreground"})});const l=(r==null?void 0:r.vendors)||[],o=(r==null?void 0:r.selMap)||new Map,c=(r==null?void 0:r.overrideMap)||new Map;if(l.length===0)return e.jsxs("div",{className:"text-center py-12 border-2 border-dashed rounded-xl",children:[e.jsx(E5,{className:"w-10 h-10 text-muted-foreground mx-auto mb-3"}),e.jsx("h3",{className:"font-semibold",children:"No vendors in your library yet"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Add vendors in the Vendors tab of Client Portals, then toggle them here per portal."})]});const d=h=>{const m=c.get(h.id);if(m!==void 0)return m;if(h.is_required)return!0;const p=o.get(h.id);return p===void 0?!0:p!==!1},u=h=>{var m;return((m=Zq.find(p=>p.value===h))==null?void 0:m.label)||h};return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Choose which vendors from your library appear in ",e.jsx("em",{children:"this specific portal"}),". Changes here only affect this deal — your global vendor library and other portals are unaffected."]}),e.jsx(Eo,{className:"h-[400px] rounded-lg border",children:e.jsx("div",{className:"divide-y",children:l.map(h=>{const m=d(h);return e.jsxs("div",{className:"flex items-center gap-3 p-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-lg bg-muted border flex items-center justify-center overflow-hidden shrink-0",children:h.logo_url?e.jsx("img",{src:h.logo_url,alt:h.name,className:"w-full h-full object-cover"}):e.jsx("span",{className:"text-sm font-semibold text-muted-foreground",children:h.name.charAt(0)})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:h.company||h.name}),e.jsx(qe,{variant:"outline",className:"text-[10px] shrink-0",children:u(h.category)}),h.owner_type==="brokerage"&&e.jsx(qe,{variant:"secondary",className:"text-[10px] shrink-0",children:"Brokerage"}),h.is_required&&e.jsx(qe,{className:"text-[10px] shrink-0",children:"Required"})]}),h.company&&h.name&&e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:h.name})]}),e.jsx(On,{checked:m,disabled:h.is_required||i.isPending,onCheckedChange:p=>i.mutate({vendorId:h.id,isVisible:p})})]},h.id)})})})]})}function LLn({portalId:s,ownerId:t,clientEmail:n,linkedPortalId:r,onLink:a}){const[i,l]=k.useState(""),[o,c]=k.useState(!1),{data:d,isLoading:u}=pt({queryKey:["all-owner-portals",t],queryFn:async()=>{const{data:g,error:x}=await V.from("client_portals").select(` id, slug, client_name, client_email, deal_id, archived_at, deal_pipeline (id, deal_name, deal_type, property_address) `).eq("owner_user_id",t).neq("id",s).is("archived_at",null).eq("is_enabled",!0);if(x)throw x;return g},enabled:o||!!r}),h=k.useMemo(()=>!r||!d?null:d.find(g=>g.id===r),[r,d]),m=k.useMemo(()=>!d||!n?[]:d.filter(g=>{var x;return((x=g.client_email)==null?void 0:x.toLowerCase())===n.toLowerCase()&&g.id!==s}),[d,n,s]),p=k.useMemo(()=>{if(!d||!i.trim())return[];const g=i.toLowerCase();return d.filter(x=>{var v,_,j,C;const y=x.deal_pipeline;return((v=x.client_name)==null?void 0:v.toLowerCase().includes(g))||((_=x.client_email)==null?void 0:_.toLowerCase().includes(g))||((j=y==null?void 0:y.deal_name)==null?void 0:j.toLowerCase().includes(g))||((C=y==null?void 0:y.property_address)==null?void 0:C.toLowerCase().includes(g))})},[d,i]);if(r){const g=h==null?void 0:h.deal_pipeline;return e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{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(pd,{className:"h-4 w-4 text-primary shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:(h==null?void 0:h.client_name)||(g==null?void 0:g.deal_name)||"Linked Portal"}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[(g==null?void 0:g.deal_type)==="listing"?"🏠 Listing":"🔑 Purchase"," · ",(g==null?void 0:g.property_address)||"No address"]})]}),e.jsxs($,{variant:"ghost",size:"sm",className:"text-xs text-destructive hover:text-destructive shrink-0",onClick:()=>a(null),children:[e.jsx(Q8,{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(re,{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($,{variant:"outline",size:"sm",className:"text-xs",onClick:()=>c(!o),children:[e.jsx(pd,{className:"h-3 w-3 mr-1"}),o?"Cancel":"Link"]})]}),!o&&m.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)"}),m.map(g=>{const x=g.deal_pipeline;return e.jsxs("button",{onClick:()=>a(g.id),className:"w-full flex items-center gap-2 bg-amber-50 border border-amber-200 rounded-lg p-2.5 hover:bg-amber-100 transition-colors text-left",children:[e.jsx(qe,{variant:"outline",className:"text-[10px] shrink-0 bg-amber-100 border-amber-300 text-amber-700",children:(x==null?void 0:x.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:(x==null?void 0:x.deal_name)||g.client_name}),e.jsx("p",{className:"text-[11px] text-muted-foreground truncate",children:x==null?void 0:x.property_address})]}),e.jsx(pd,{className:"h-3.5 w-3.5 text-amber-600 shrink-0"})]},g.id)})]}),o&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Yr,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(be,{value:i,onChange:g=>l(g.target.value),placeholder:"Search by name, email, or address...",className:"pl-8 h-8 text-xs",autoFocus:!0})]}),u&&e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(Jt,{className:"h-4 w-4 animate-spin text-muted-foreground"})}),p.length>0&&e.jsx("div",{className:"space-y-1 max-h-[200px] overflow-y-auto",children:p.map(g=>{const x=g.deal_pipeline;return e.jsxs("button",{onClick:()=>{a(g.id),c(!1),l("")},className:"w-full flex items-center gap-2 border rounded-lg p-2 hover:bg-muted/50 transition-colors text-left",children:[e.jsx(qe,{variant:"outline",className:"text-[10px] shrink-0",children:(x==null?void 0:x.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:(x==null?void 0:x.deal_name)||g.client_name}),e.jsx("p",{className:"text-[11px] text-muted-foreground truncate",children:g.client_email})]})]},g.id)})}),i&&p.length===0&&!u&&e.jsx("p",{className:"text-xs text-muted-foreground text-center py-3",children:"No portals found"})]})]})}function hQe({contactId:s,onVideoReady:t}){const[n,r]=k.useState(!1),[a,i]=k.useState("record"),[l,o]=k.useState(0),[c,d]=k.useState(0),u=o4(),h=()=>{i("record"),o(0),d(0)},m=g=>{!g&&(a==="uploading"||a==="processing")||(r(g),g||h())},p=k.useCallback(async(g,x)=>{i("uploading");try{const y="Card Video",{videoId:v,libraryId:_}=await v6(y),{uploadUrl:j,apiKey:C}=await b6(v),A=new XMLHttpRequest;A.upload.onprogress=U=>{U.lengthComputable&&o(U.loaded/U.total*100)},await new Promise((U,G)=>{A.onload=()=>A.status>=200&&A.status<300?U():G(new Error("Upload failed")),A.onerror=()=>G(new Error("Upload failed")),A.open("PUT",j),A.setRequestHeader("AccessKey",C),A.send(g)}),i("processing");let M=0;const I=Date.now(),P=9e4,R=`https://iframe.mediadelivery.net/embed/${_}/${v}`;for(;M<4;){if(await new Promise(G=>setTimeout(G,3e3)),Date.now()-I>P){const G=g.size/1048576;await u.mutateAsync({bunny_video_id:v,playback_url:`https://iframe.mediadelivery.net/play/${_}/${v}`,file_size_mb:G,title:y,contact_id:s||void 0,status:"processing",touch_type:"video"}),t(R),ae.success("Video saved — still encoding. It will be ready shortly."),i("done"),setTimeout(()=>{r(!1),h()},1500);return}const U=await D2(v);if(M=U.status,d(U.encodeProgress||0),M===5||M===6)throw new Error("Video processing failed")}const O=await D2(v),B=(O.storageSize||g.size)/(1024*1024);await u.mutateAsync({bunny_video_id:v,contact_id:s||void 0,playback_url:O.directPlayUrl||R,thumbnail_url:O.thumbnailUrl,preview_url:O.previewUrl||null,duration_seconds:O.length||x,file_size_mb:B,title:y,status:"ready",touch_type:"video"}),t(R),ae.success("Video recorded & added to your library!"),i("done"),setTimeout(()=>{r(!1),h()},1500)}catch(y){console.error("Recording upload error:",y),ae.error("Failed to process video. Please try again."),i("record")}},[s,t,u]);return e.jsxs(zs,{open:n,onOpenChange:m,children:[e.jsx(yl,{asChild:!0,children:e.jsxs($,{variant:"outline",size:"sm",className:"gap-1.5 w-full",children:[e.jsx(ia,{className:"h-3.5 w-3.5"}),"Record Video"]})}),e.jsxs(Rs,{className:"sm:max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Vs,{children:e.jsx($s,{children:"Record a Video for Your Card"})}),a==="record"&&e.jsx(w6,{maxDurationSeconds:600,onRecordingComplete:p,onError:g=>ae.error(g)}),a==="uploading"&&e.jsxs("div",{className:"flex flex-col items-center gap-4 py-12",children:[e.jsx(Jt,{className:"h-10 w-10 animate-spin text-primary"}),e.jsx("p",{className:"text-sm font-medium",children:"Uploading video..."}),e.jsx(ho,{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(Jt,{className:"h-10 w-10 animate-spin text-primary"}),e.jsx("p",{className:"text-sm font-medium",children:"Processing video..."}),e.jsx(ho,{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(nl,{className:"h-12 w-12 text-emerald-500"}),e.jsx("p",{className:"text-sm font-medium",children:"Video attached to your card!"})]})]})]})}const RLn=s=>`portal-settings-draft:${s}`;function mQe({open:s,onOpenChange:t,portal:n,dealOwnerId:r}){const a=EV(),[i,l]=k.useState(!1),o=k.useMemo(()=>RLn(n.id),[n.id]),[c,d]=k.useState(!1),[u,h]=k.useState(n.next_step_text||""),[m,p]=k.useState(n.next_step_video_url||""),[g,x]=k.useState(n.inspection_date||""),[y,v]=k.useState(n.appraisal_date||""),[_,j]=k.useState(n.welcome_message||""),[C,A]=k.useState(n.review_url||""),[M,I]=k.useState(n.show_post_close_tips),[P,R]=k.useState(n.notify_client),[O,B]=k.useState(n.require_onboarding),[U,G]=k.useState(n.allow_spouse),[H,Y]=k.useState(n.visibility),[se,ee]=k.useState(n.stage_mapping||[]),[oe,me]=k.useState(null),[Q,te]=k.useState(n.linked_portal_id||null),[le,fe]=k.useState(n.referral_enabled??!0),[_e,ve]=k.useState(n.referral_reward_text||""),[he,Se]=k.useState(n.referral_cta_headline||""),[Te,Ie]=k.useState(n.homeowner_hub_video_url||""),[Ue,Be]=k.useState(n.branding_override||{}),je=()=>{h(n.next_step_text||""),p(n.next_step_video_url||""),x(n.inspection_date||""),v(n.appraisal_date||""),j(n.welcome_message||""),A(n.review_url||""),I(n.show_post_close_tips),R(n.notify_client),B(n.require_onboarding),G(n.allow_spouse),Y(n.visibility),ee(n.stage_mapping||[]),te(n.linked_portal_id||null),fe(n.referral_enabled??!0),ve(n.referral_reward_text||""),Se(n.referral_cta_headline||""),Ie(n.homeowner_hub_video_url||""),Be(n.branding_override||{})};k.useEffect(()=>{d(!1);const Ge=localStorage.getItem(o);if(Ge)try{const yt=JSON.parse(Ge);h(yt.nextStepText||""),p(yt.nextStepVideo||""),x(yt.inspectionDate||""),v(yt.appraisalDate||""),j(yt.welcomeMessage||""),A(yt.reviewUrl||""),I(!!yt.showPostClose),R(!!yt.notifyClient),B(!!yt.requireOnboarding),G(!!yt.allowSpouse),Y(yt.visibility||n.visibility),ee(yt.stageMapping||[]),te(yt.linkedPortalId??null),fe(yt.referralEnabled??!0),ve(yt.referralRewardText||""),Se(yt.referralCtaHeadline||""),Ie(yt.homeownerHubVideoUrl||""),Be(yt.brandingOverride||{}),d(!0);return}catch{localStorage.removeItem(o)}je(),d(!0)},[o,n]),k.useEffect(()=>{if(!c)return;const Ge={nextStepText:u,nextStepVideo:m,inspectionDate:g,appraisalDate:y,welcomeMessage:_,reviewUrl:C,showPostClose:M,notifyClient:P,requireOnboarding:O,allowSpouse:U,visibility:H,stageMapping:se,linkedPortalId:Q,referralEnabled:le,referralRewardText:_e,referralCtaHeadline:he,homeownerHubVideoUrl:Te,brandingOverride:Ue};u!==(n.next_step_text||"")||m!==(n.next_step_video_url||"")||g!==(n.inspection_date||"")||y!==(n.appraisal_date||"")||_!==(n.welcome_message||"")||C!==(n.review_url||"")||M!==n.show_post_close_tips||P!==n.notify_client||O!==n.require_onboarding||U!==n.allow_spouse||H!==n.visibility||JSON.stringify(se)!==JSON.stringify(n.stage_mapping||[])||Q!==(n.linked_portal_id||null)||le!==(n.referral_enabled??!0)||_e!==(n.referral_reward_text||"")||he!==(n.referral_cta_headline||"")||Te!==(n.homeowner_hub_video_url||"")||JSON.stringify(Ue)!==JSON.stringify(n.branding_override||{})?localStorage.setItem(o,JSON.stringify(Ge)):localStorage.removeItem(o)},[u,m,g,y,_,C,M,P,O,U,H,se,Q,le,_e,he,Te,Ue,o,c,n]);const Ye=()=>{localStorage.removeItem(o),je()},Ee=async()=>{try{await a.mutateAsync({id:n.id,next_step_text:u||null,next_step_video_url:m||null,inspection_date:g||null,appraisal_date:y||null,welcome_message:_||null,review_url:C||null,show_post_close_tips:M,notify_client:P,require_onboarding:O,allow_spouse:U,visibility:H,stage_mapping:se.length>0?se:null,linked_portal_id:Q,referral_enabled:le,referral_reward_text:_e||null,referral_cta_headline:he||null,homeowner_hub_video_url:Te||null,branding_override:Object.values(Ue).some(yt=>yt!=null&&yt!=="")?Ue:null});const Ge=n.linked_portal_id;Q&&Q!==Ge&&await V.from("client_portals").update({linked_portal_id:n.id}).eq("id",Q),!Q&&Ge&&await V.from("client_portals").update({linked_portal_id:null}).eq("id",Ge),localStorage.removeItem(o),ae.success("Portal settings saved"),t(!1)}catch{ae.error("Failed to save settings")}},Re=()=>{ee([...se,{label:""}])},ke=Ge=>{ee(se.filter((yt,tt)=>tt!==Ge)),oe===Ge&&me(null)},Fe=(Ge,yt,tt)=>{const ut=[...se];ut[Ge]={...ut[Ge],[yt]:tt},ee(ut)},Oe=()=>{const yt=mAe(null).map(tt=>({label:tt.label,description:tt.description,stageId:void 0}));ee(yt)};return e.jsxs(e.Fragment,{children:[e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"max-w-lg max-h-[85vh] flex flex-col",children:[e.jsx(Vs,{children:e.jsx($s,{children:"Portal Settings"})}),e.jsxs(ya,{defaultValue:"general",className:"flex-1 overflow-hidden flex flex-col",children:[e.jsxs(va,{className:"grid grid-cols-5 shrink-0",children:[e.jsx(is,{value:"general",children:"General"}),e.jsx(is,{value:"timeline",children:"Timeline"}),e.jsx(is,{value:"content",children:"Content"}),e.jsx(is,{value:"vendors",children:"Vendors"}),e.jsx(is,{value:"branding",children:"Branding"})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto mt-4 min-h-0",children:[e.jsxs(cs,{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(re,{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(Ge=>e.jsx("button",{onClick:()=>Y(Ge),className:`px-3 py-1.5 rounded-full text-xs font-medium border transition-colors ${H===Ge?"bg-primary text-primary-foreground border-primary":"bg-background text-muted-foreground border-input hover:border-primary/50"}`,children:Ge.charAt(0).toUpperCase()+Ge.slice(1)},Ge))})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(re,{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(On,{checked:O,onCheckedChange:B})]}),O&&e.jsxs("div",{className:"flex items-center justify-between pl-4 border-l-2 border-primary/20",children:[e.jsxs("div",{children:[e.jsx(re,{className:"text-sm font-medium",children:"Custom Questions"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Manage intake form questions"})]}),e.jsx($,{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(re,{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(On,{checked:U,onCheckedChange:G})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(re,{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(On,{checked:M,onCheckedChange:I})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(re,{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(On,{checked:P,onCheckedChange:R})]}),e.jsx("div",{className:"border-t pt-4",children:e.jsx(LLn,{portalId:n.id,ownerId:r,clientEmail:n.client_email,linkedPortalId:Q,onLink:te})}),e.jsx("div",{children:e.jsx(be,{type:"date",value:g,onChange:Ge=>x(Ge.target.value),className:"mt-1"})}),e.jsxs("div",{children:[e.jsx(re,{className:"text-sm font-medium",children:"Appraisal Date"}),e.jsx(be,{type:"date",value:y,onChange:Ge=>v(Ge.target.value),className:"mt-1"})]})]}),e.jsx(cs,{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(re,{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($,{variant:"outline",size:"sm",onClick:Oe,className:"text-xs",children:"Auto-map"})]}),e.jsx("p",{className:"text-[11px] text-muted-foreground bg-muted/50 rounded-md p-2",children:'💡 These labels are what clients see. Click "More" on any stage to customize its description and add a video link. Internal pipeline stages are automatically translated to friendly names.'}),se.length===0&&e.jsxs("div",{className:"border border-dashed rounded-lg p-4 text-center",children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:"No custom mapping — using default client-friendly journey stages"}),e.jsx($,{variant:"outline",size:"sm",onClick:Oe,children:"Customize journey labels"})]}),e.jsx("div",{className:"space-y-2 mt-2",children:se.map((Ge,yt)=>e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Bp,{className:"h-4 w-4 text-muted-foreground/50 flex-shrink-0"}),e.jsx(be,{value:Ge.label,onChange:tt=>Fe(yt,"label",tt.target.value),placeholder:`Stage ${yt+1} label`,className:"flex-1 h-9 text-sm"}),e.jsx($,{variant:"ghost",size:"sm",className:"h-9 px-2 text-xs text-muted-foreground hover:text-primary",onClick:()=>me(oe===yt?null:yt),children:oe===yt?"Less":"More"}),e.jsx($,{variant:"ghost",size:"icon",className:"h-9 w-9 text-muted-foreground hover:text-destructive",onClick:()=>ke(yt),children:e.jsx(Un,{className:"h-3.5 w-3.5"})})]}),oe===yt&&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(re,{className:"text-xs text-muted-foreground",children:"Description"}),e.jsx("textarea",{value:Ge.description||"",onChange:tt=>Fe(yt,"description",tt.target.value),placeholder:"e.g. Now it's time to start actively looking at homes",className:"mt-0.5 w-full rounded-md border border-input bg-background px-3 py-2 text-xs min-h-[50px] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs text-muted-foreground",children:"Video"}),Ge.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:Ge.video_url.length>40?Ge.video_url.slice(0,40)+"...":Ge.video_url}),e.jsx($,{variant:"ghost",size:"sm",className:"h-7 text-xs text-destructive hover:text-destructive",onClick:()=>Fe(yt,"video_url",""),children:"Remove"})]}):e.jsxs("div",{className:"mt-1 flex items-center gap-1.5",children:[e.jsx(hQe,{onVideoReady:tt=>Fe(yt,"video_url",tt)}),e.jsx(BF,{userId:r,onSelect:tt=>Fe(yt,"video_url",tt),triggerSize:"sm",triggerClassName:"gap-1.5 shrink-0 flex-1"}),e.jsxs($,{variant:"ghost",size:"sm",className:"gap-1 text-xs text-muted-foreground flex-1",onClick:()=>{const tt=prompt("Paste a YouTube or Loom URL:");tt&&Fe(yt,"video_url",tt)},children:[e.jsx(od,{className:"h-3 w-3"}),"Paste URL"]})]})]})]})]},yt))}),se.length>0&&e.jsxs($,{variant:"outline",size:"sm",onClick:Re,className:"mt-2 text-xs w-full",children:[e.jsx(nn,{className:"h-3 w-3 mr-1"})," Add Stage"]})]})}),e.jsxs(cs,{value:"content",className:"space-y-4 mt-0 px-1",children:[e.jsxs("div",{children:[e.jsx(re,{className:"text-sm font-medium",children:"Welcome Message"}),e.jsx("textarea",{value:_,onChange:Ge=>j(Ge.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(re,{className:"text-sm font-medium",children:"What's Next"}),e.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"Tell your client what to expect next"}),e.jsx("textarea",{value:u,onChange:Ge=>h(Ge.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(re,{className:"text-sm font-medium",children:"Next Step Video (optional)"}),e.jsx(be,{value:m,onChange:Ge=>p(Ge.target.value),className:"mt-1",placeholder:"YouTube or Loom URL"})]}),e.jsxs("div",{children:[e.jsx(re,{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(be,{value:C,onChange:Ge=>A(Ge.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(re,{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(re,{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(On,{checked:le,onCheckedChange:fe})]}),le&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsx(re,{className:"text-sm font-medium",children:"Headline"}),e.jsx(be,{value:he,onChange:Ge=>Se(Ge.target.value),className:"mt-1",placeholder:"Know someone buying or selling?"})]}),e.jsxs("div",{children:[e.jsx(re,{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(be,{value:_e,onChange:Ge=>ve(Ge.target.value),className:"mt-1",placeholder:"$250 gift card • Donation to your charity • Closing gift"})]}),e.jsxs("div",{children:[e.jsx(re,{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(be,{value:Te,onChange:Ge=>Ie(Ge.target.value),className:"mt-1",placeholder:"YouTube, Loom, or direct video URL"})]})]})]})]}),e.jsx(cs,{value:"vendors",className:"space-y-4 mt-0 px-1",children:e.jsx(ILn,{portalId:n.id,agentUserId:r})}),e.jsx(cs,{value:"branding",className:"space-y-4 mt-0 px-1",children:e.jsx(PLn,{override:Ue,onChange:Be})})]})]}),e.jsxs("div",{className:"flex justify-between gap-2 pt-4 border-t shrink-0",children:[e.jsx($,{variant:"ghost",onClick:Ye,children:"Reset Draft"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),children:"Close"}),e.jsxs($,{onClick:Ee,disabled:a.isPending,children:[a.isPending?e.jsx(Jt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Ml,{className:"h-4 w-4 mr-2"}),"Save Settings"]})]})]})]})}),e.jsx(nVt,{open:i,onOpenChange:l})]})}const DLn=s=>`portal-update-draft:${s}`;function fQe({open:s,onOpenChange:t,portalId:n,portalSlug:r,notifyClient:a}){const i=k.useMemo(()=>DLn(n),[n]),[l,o]=k.useState(""),[c,d]=k.useState(""),[u,h]=k.useState(""),[m,p]=k.useState(!1),[g,x]=k.useState(a??!1),[y,v]=k.useState(!1),_=t9t();k.useEffect(()=>{v(!1);const A=localStorage.getItem(i);if(A)try{const M=JSON.parse(A);o(M.title||""),d(M.content||""),h(M.videoUrl||""),p(!!M.isStageChange),x(typeof M.sendNotification=="boolean"?M.sendNotification:a??!1),v(!0);return}catch{localStorage.removeItem(i)}o(""),d(""),h(""),p(!1),x(a??!1),v(!0)},[i,a]),k.useEffect(()=>{if(!y)return;const A={title:l,content:c,videoUrl:u,isStageChange:m,sendNotification:g};l.trim()||c.trim()||u.trim()||m||g!==(a??!1)?localStorage.setItem(i,JSON.stringify(A)):localStorage.removeItem(i)},[l,c,u,m,g,y,i,a]);const j=()=>{localStorage.removeItem(i),o(""),d(""),h(""),p(!1),x(a??!1)},C=async()=>{if(l.trim())try{if(await _.mutateAsync({portal_id:n,title:l.trim(),content:c.trim()||void 0,video_url:u.trim()||void 0,is_stage_change:m}),g&&r)try{const A=B5(r);await V.functions.invoke("send-portal-notification",{body:{portal_id:n,update_title:l.trim(),update_content:c.trim()||null,portal_url:A}}),ae.success("Update posted & client notified")}catch(A){console.error("Notification failed:",A),ae.success("Update posted (notification failed to send)")}else ae.success("Update posted to portal");j(),t(!1)}catch{ae.error("Failed to post update")}};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"max-w-md",children:[e.jsx(Vs,{children:e.jsx($s,{children:"Post Portal Update"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(re,{className:"text-sm font-medium",children:"Title *"}),e.jsx(be,{value:l,onChange:A=>o(A.target.value),className:"mt-1",placeholder:"Inspection cleared!"})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-sm font-medium",children:"Message"}),e.jsx("textarea",{value:c,onChange:A=>d(A.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(re,{className:"text-sm font-medium",children:"Video URL (optional)"}),e.jsxs("div",{className:"relative mt-1",children:[e.jsx(be,{value:u,onChange:A=>h(A.target.value),className:"pl-9",placeholder:"YouTube or Loom link"}),e.jsx(ia,{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:()=>p(!m),className:`px-3 py-1.5 rounded-full text-xs font-medium border transition-colors ${m?"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:()=>x(!g),className:`px-3 py-1.5 rounded-full text-xs font-medium border transition-colors flex items-center gap-1.5 ${g?"bg-blue-500/10 text-blue-700 border-blue-200":"bg-background text-muted-foreground border-input"}`,children:[g?e.jsx(Fx,{className:"h-3 w-3"}):e.jsx(k5,{className:"h-3 w-3"}),g?"Notify Client":"No Notification"]})]})]}),e.jsxs("div",{className:"flex justify-between gap-2 pt-2",children:[e.jsx($,{variant:"ghost",onClick:j,children:"Clear Draft"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),children:"Close"}),e.jsxs($,{onClick:C,disabled:!l.trim()||_.isPending,children:[_.isPending?e.jsx(Jt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Wr,{className:"h-4 w-4 mr-2"}),"Post Update"]})]})]})]})})}function pQe({open:s,onOpenChange:t,portal:n,dealName:r}){const a=EV(),{isGmailConnected:i,gmailEmail:l}=dx(),[o,c]=k.useState(n.client_name||""),[d,u]=k.useState(n.client_email||""),[h,m]=k.useState(!1),[p,g]=k.useState(!1),x=B5(n.slug),y=o.split(" ")[0]||"there",v=`Your Transaction Portal – ${r}`,_=`Hi ${y}, I've set up a dedicated portal where you can track the progress of your transaction in real-time. Here's your link: ${x} You can view your timeline, key dates, documents, and any updates I post along the way. Let me know if you have any questions!`,j=()=>{navigator.clipboard.writeText(x),g(!0),setTimeout(()=>g(!1),2e3),ae.success("Portal link copied!")},C=async()=>{if(!d.trim()){ae.error("Please enter the client email");return}m(!0);try{await a.mutateAsync({id:n.id,client_name:o||null,client_email:d||null,invite_sent_at:new Date().toISOString(),invite_method:"email"});const{error:M}=await V.functions.invoke("gmail-send",{body:{to:d,subject:v,body:_.replace(/\n/g,"
")}});if(M){let I="";try{const P=M==null?void 0:M.context;if(P&&typeof P.json=="function"){const R=await P.json();I=(R==null?void 0:R.message)||(R==null?void 0:R.error)||""}}catch{}throw new Error(I||M.message||"Failed to send invite")}ae.success(`Invite sent to ${d}`),t(!1)}catch(M){ae.error(M.message||"Failed to send invite")}finally{m(!1)}},A=()=>{const M=encodeURIComponent(v),I=encodeURIComponent(_);window.open(`mailto:${d}?subject=${M}&body=${I}`,"_blank"),a.mutateAsync({id:n.id,client_name:o||null,client_email:d||null,invite_sent_at:new Date().toISOString(),invite_method:"email"}).catch(()=>{})};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"max-w-md",children:[e.jsx(Vs,{children:e.jsx($s,{children:"Invite Client to Portal"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(re,{className:"text-sm font-medium",children:"Client Name"}),e.jsx(be,{value:o,onChange:M=>c(M.target.value),className:"mt-1",placeholder:"John Doe"})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-sm font-medium",children:"Client Email"}),e.jsx(be,{type:"email",value:d,onChange:M=>u(M.target.value),className:"mt-1",placeholder:"john@example.com"})]}),e.jsxs("div",{children:[e.jsx(re,{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:x})}),e.jsx($,{variant:"outline",size:"icon",onClick:j,className:"shrink-0",children:p?e.jsx(ma,{className:"h-4 w-4 text-emerald-600"}):e.jsx(Da,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2 pt-2 border-t",children:[i?e.jsxs($,{onClick:C,disabled:h||!d.trim(),className:"w-full",children:[h?e.jsx(Jt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(pn,{className:"h-4 w-4 mr-2"}),"Send via Gmail (",l,")"]}):e.jsxs($,{onClick:A,disabled:!d.trim(),className:"w-full",variant:"outline",children:[e.jsx(Ir,{className:"h-4 w-4 mr-2"}),"Open in Email App"]}),e.jsxs($,{variant:"ghost",onClick:j,className:"w-full text-muted-foreground",children:[e.jsx(Da,{className:"h-4 w-4 mr-2"}),"Just Copy Link"]})]})]})]})})}function OLn({deal:s}){const{isAdmin:t,user:n}=ks(),{data:r,isLoading:a}=$5n(s.id),i=UZe(),l=EV(),[o,c]=k.useState(!1),[d,u]=k.useState(!1),[h,m]=k.useState(!1),[p,g]=k.useState(!1),x=`portal-management-ui:${s.id}`;if(k.useEffect(()=>{const M=sessionStorage.getItem(x);if(M)try{const I=JSON.parse(M);u(!!I.settingsOpen),m(!!I.composerOpen),g(!!I.inviteOpen)}catch{sessionStorage.removeItem(x)}},[x]),k.useEffect(()=>{d||h||p?sessionStorage.setItem(x,JSON.stringify({settingsOpen:d,composerOpen:h,inviteOpen:p})):sessionStorage.removeItem(x)},[d,h,p,x]),a)return e.jsx("div",{className:"border rounded-lg p-4",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(kn,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"font-medium text-sm",children:"Client Portal"}),e.jsx(Jt,{className:"h-3 w-3 animate-spin ml-auto"})]})});const y=async()=>{var M,I;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:((M=s.contact)==null?void 0:M.email)||void 0,client_phone:((I=s.contact)==null?void 0:I.phone)||void 0}),ae.success("Client portal enabled!")}catch{ae.error("Failed to create portal")}finally{c(!1)}},v=async M=>{if(r)try{await l.mutateAsync({id:r.id,is_enabled:M}),ae.success(M?"Portal enabled":"Portal disabled")}catch{ae.error("Failed to update portal")}},_=()=>{if(!r)return;const M=B5(r.slug);navigator.clipboard.writeText(M),ae.success("Portal link copied!")},j=()=>{if(!r)return;const M=B5(r.slug);window.open(M,"_blank")};if(!r)return e.jsxs("div",{className:"border rounded-lg p-4 border-dashed",children:[e.jsx("div",{className:"flex items-center justify-between mb-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(kn,{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($,{onClick:y,disabled:o,size:"sm",className:"w-full",children:[o?e.jsx(Jt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(kn,{className:"h-4 w-4 mr-2"}),"Enable Client Portal"]})]});const C=B5(r.slug),A=(n==null?void 0:n.id)||"";return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"border rounded-lg p-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(kn,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"font-medium text-sm",children:"Client Portal"}),e.jsx(qe,{variant:"outline",className:r.is_enabled?"text-xs bg-emerald-500/10 text-emerald-600 border-emerald-200":"text-xs bg-muted text-muted-foreground",children:r.is_enabled?"Active":"Disabled"})]}),e.jsx(On,{checked:r.is_enabled,onCheckedChange:v})]}),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(qe,{variant:"outline",className:"text-[10px] px-1.5 py-0",children:r.visibility==="private"?"Private":"Public"})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx("span",{children:"Onboarding:"}),e.jsx("span",{className:"text-foreground",children:r.require_onboarding?"Required":"Disabled"})]}),r.client_name&&e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx("span",{children:"Client:"}),e.jsx("span",{className:"text-foreground",children:r.client_name})]})]}),e.jsx("div",{className:"bg-muted/50 rounded-md p-2 mb-3",children:e.jsx("p",{className:"text-xs font-mono text-muted-foreground truncate",children:C})}),e.jsxs("div",{className:"grid grid-cols-3 gap-2 mb-2 w-full",children:[e.jsxs($,{variant:"outline",size:"sm",onClick:_,className:"text-xs w-full min-w-0 px-2",children:[e.jsx(Da,{className:"h-3 w-3 mr-1 shrink-0"}),e.jsx("span",{className:"truncate",children:"Copy"})]}),e.jsxs($,{variant:"outline",size:"sm",onClick:j,className:"text-xs w-full min-w-0 px-2",children:[e.jsx(Ir,{className:"h-3 w-3 mr-1 shrink-0"}),e.jsx("span",{className:"truncate",children:"Preview"})]}),e.jsxs($,{variant:"outline",size:"sm",onClick:()=>g(!0),className:"text-xs w-full min-w-0 px-2",children:[e.jsx(Wr,{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($,{variant:"ghost",size:"sm",onClick:()=>m(!0),className:"text-xs text-muted-foreground w-full min-w-0 px-2",children:[e.jsx(h5,{className:"h-3 w-3 mr-1 shrink-0"}),e.jsx("span",{className:"truncate",children:"Post Update"})]}),e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>u(!0),className:"text-xs text-muted-foreground w-full min-w-0 px-2",children:[e.jsx(Yc,{className:"h-3 w-3 mr-1 shrink-0"}),e.jsx("span",{className:"truncate",children:"Settings"})]})]}),e.jsxs(nr,{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(Zo,{className:"h-3 w-3"}),"View incoming referrals"]})]}),e.jsx(mQe,{open:d,onOpenChange:u,portal:r,dealOwnerId:A}),e.jsx(fQe,{open:h,onOpenChange:m,portalId:r.id,portalSlug:r.slug,notifyClient:r.notify_client}),e.jsx(pQe,{open:p,onOpenChange:g,portal:r,dealName:s.deal_name})]})}const FLn=["Client","Co-Buyer","Co-Seller","Spouse","Lender","Title Company","Inspector","Appraiser","Attorney","Contractor","Other"];function zLn(s){return pt({queryKey:["deal-contacts",s],queryFn:async()=>{const{data:t,error:n}=await V.from("deal_contacts").select(` id, deal_id, contact_id, role, created_at, contact:innercircle_contacts(id, first_name, last_name, email, phone) `).eq("deal_id",s).order("created_at");if(n)throw n;return t||[]},enabled:!!s})}function BLn(){const s=ls();return Nt({mutationFn:async({dealId:t,contactId:n,role:r})=>{const{data:a,error:i}=await V.from("deal_contacts").insert({deal_id:t,contact_id:n,role:r}).select().single();if(i)throw i;return a},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["deal-contacts",n.dealId]}),ae.success("Contact linked to deal")},onError:t=>{var n;(n=t.message)!=null&&n.includes("duplicate")?ae.error("This contact is already linked to this deal"):ae.error("Failed to link contact")}})}function $Ln(){const s=ls();return Nt({mutationFn:async({id:t,dealId:n})=>{const{error:r}=await V.from("deal_contacts").delete().eq("id",t);if(r)throw r},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["deal-contacts",n.dealId]}),ae.success("Contact removed from deal")},onError:()=>{ae.error("Failed to remove contact")}})}function ULn({dealId:s,primaryContactId:t}){const n=Jn(),{data:r,isLoading:a}=zLn(s),{data:i}=vv(),l=BLn(),o=$Ln(),[c,d]=k.useState(!1),[u,h]=k.useState(""),[m,p]=k.useState("Client"),g=new Set((r==null?void 0:r.map(j=>j.contact_id))||[]);t&&g.add(t);const x=i==null?void 0:i.filter(j=>{var A,M,I;if(g.has(j.id))return!1;if(!u.trim())return!0;const C=u.toLowerCase();return((A=j.first_name)==null?void 0:A.toLowerCase().includes(C))||((M=j.last_name)==null?void 0:M.toLowerCase().includes(C))||((I=j.email)==null?void 0:I.toLowerCase().includes(C))}).slice(0,8),y=j=>{l.mutate({dealId:s,contactId:j,role:m}),d(!1),h("")},v=j=>{o.mutate({id:j,dealId: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!(r!=null&&r.length)&&!c?e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("h4",{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(Xn,{className:"h-4 w-4"}),"Additional Contacts"]})}),e.jsxs(Xc,{open:c,onOpenChange:d,children:[e.jsx(Qc,{asChild:!0,children:e.jsxs($,{variant:"outline",size:"sm",className:"w-full text-muted-foreground",children:[e.jsx(nn,{className:"h-3.5 w-3.5 mr-1"}),"Link a contact (lender, spouse, vendor...)"]})}),e.jsx(Bc,{className:"w-80 p-3",align:"start",children:e.jsx(J1t,{search:u,setSearch:h,selectedRole:m,setSelectedRole:p,filteredContacts:x,onAdd:y})})]})]}):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(Xn,{className:"h-4 w-4"}),"Linked Contacts",r&&r.length>0&&e.jsx(qe,{variant:"secondary",className:"text-[10px] px-1.5",children:r.length})]}),e.jsxs(Xc,{open:c,onOpenChange:d,children:[e.jsx(Qc,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"sm",className:"h-7 px-2",children:e.jsx(nn,{className:"h-3.5 w-3.5"})})}),e.jsx(Bc,{className:"w-80 p-3",align:"end",children:e.jsx(J1t,{search:u,setSearch:h,selectedRole:m,setSelectedRole:p,filteredContacts:x,onAdd:y})})]})]}),e.jsx("div",{className:"space-y-1.5",children:r==null?void 0:r.map(j=>{var C,A,M,I,P,R,O,B;return e.jsxs("div",{className:"flex items-center gap-2 p-2 rounded-md bg-muted/40 group",children:[e.jsx(Wa,{className:"h-7 w-7",children:e.jsxs(Ka,{className:"text-[10px] bg-primary/10 text-primary",children:[(A=(C=j.contact)==null?void 0:C.first_name)==null?void 0:A[0],(I=(M=j.contact)==null?void 0:M.last_name)==null?void 0:I[0]]})}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsxs("button",{onClick:()=>n(`/mission-control/contacts/${j.contact_id}`),className:"text-sm font-medium hover:underline text-primary truncate block",children:[(P=j.contact)==null?void 0:P.first_name," ",(R=j.contact)==null?void 0:R.last_name]})}),e.jsx(qe,{variant:"outline",className:`text-[10px] px-1.5 py-0 shrink-0 ${_[j.role]||_.Other}`,children:j.role}),e.jsxs("div",{className:"flex gap-0.5 opacity-0 group-hover:opacity-100 transition-opacity",children:[((O=j.contact)==null?void 0:O.phone)&&e.jsx($,{variant:"ghost",size:"icon",className:"h-6 w-6",asChild:!0,children:e.jsx("a",{href:`tel:${j.contact.phone}`,children:e.jsx(ka,{className:"h-3 w-3"})})}),((B=j.contact)==null?void 0:B.email)&&e.jsx($,{variant:"ghost",size:"icon",className:"h-6 w-6",asChild:!0,children:e.jsx("a",{href:`mailto:${j.contact.email}`,children:e.jsx(pn,{className:"h-3 w-3"})})}),e.jsx($,{variant:"ghost",size:"icon",className:"h-6 w-6 text-destructive",onClick:()=>v(j.id),children:e.jsx(Un,{className:"h-3 w-3"})})]})]},j.id)})})]})}function J1t({search:s,setSearch:t,selectedRole:n,setSelectedRole:r,filteredContacts:a,onAdd:i}){return e.jsxs("div",{className:"space-y-3",children:[e.jsxs(bs,{value:n,onValueChange:r,children:[e.jsx(ys,{className:"h-8 text-sm",children:e.jsx(_s,{placeholder:"Role"})}),e.jsx(vs,{children:FLn.map(l=>e.jsx(We,{value:l,children:l},l))})]}),e.jsxs("div",{className:"relative",children:[e.jsx(Yr,{className:"absolute left-2 top-2.5 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(be,{value:s,onChange:l=>t(l.target.value),placeholder:"Search contacts...",className:"pl-7 h-8 text-sm",autoFocus:!0})]}),e.jsx(Eo,{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 nK=[{key:"contract_date",label:"Contract Accepted",short:"Contract"},{key:"earnest_money_due_date",label:"Earnest Money Due",short:"Earnest $"},{key:"inspection_date",label:"Inspection",short:"Inspection"},{key:"inspection_contingency_date",label:"Inspection Deadline",short:"Insp. Deadline"},{key:"appraisal_date",label:"Appraisal",short:"Appraisal"},{key:"loan_approval_date",label:"Loan Approval",short:"Loan"},{key:"title_docs_due_date",label:"Title / Disclosures",short:"Title"},{key:"final_walkthrough_date",label:"Final Walkthrough",short:"Walkthrough"},{key:"target_close_date",label:"Target Closing",short:"Closing"}],qLn=[{value:"stage_entry",label:"When the deal enters this stage"},{value:"contract_date",label:"Contract accepted date"},{value:"earnest_money_due_date",label:"Earnest money due date"},{value:"inspection_date",label:"Inspection date"},{value:"inspection_contingency_date",label:"Inspection deadline"},{value:"appraisal_date",label:"Appraisal date"},{value:"loan_approval_date",label:"Loan approval date"},{value:"title_docs_due_date",label:"Title / disclosures date"},{value:"final_walkthrough_date",label:"Final walkthrough date"},{value:"target_close_date",label:"Target closing date"},{value:"listing_date",label:"Listing date"},{value:"actual_close_date",label:"Actual close date"}];function VLn(){const s=ls();return Nt({mutationFn:async({dealId:t,dates:n})=>{const r={};Object.entries(n).forEach(([i,l])=>{r[i]=l&&l.trim()!==""?l:null});const{error:a}=await V.from("deal_pipeline").update(r).eq("id",t);if(a)throw a},onSuccess:()=>{s.invalidateQueries({queryKey:["deals"]}),s.invalidateQueries({queryKey:["deal-pipeline"]}),s.invalidateQueries({queryKey:["tc-dashboard"]})}})}function HLn(){const s=ls();return Nt({mutationFn:async({dealId:t,completed:n})=>{const{error:r}=await V.from("deal_pipeline").update({completed_key_dates:n}).eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["deals"]}),s.invalidateQueries({queryKey:["deal-pipeline"]}),s.invalidateQueries({queryKey:["tc-dashboard"]})}})}function GLn(){return pt({queryKey:["tc-playbooks"],queryFn:async()=>{const{data:s,error:t}=await V.from("tc_playbooks").select("*").eq("is_active",!0).order("sort_order");if(t)throw t;const{data:n,error:r}=await V.from("tc_playbook_tasks").select("*").order("sort_order");if(r)throw r;return(s||[]).map(a=>({...a,tasks:(n||[]).filter(i=>i.playbook_id===a.id)}))},staleTime:10*6e4})}function WLn(){const s=ai(),t=ls();return Nt({mutationFn:async({playbookId:n,dealId:r})=>{if(!s)throw new Error("Not authenticated");const[{data:a,error:i},{data:l,error:o}]=await Promise.all([V.from("deal_pipeline").select("*").eq("id",r).single(),V.from("tc_playbook_tasks").select("*").eq("playbook_id",n).order("sort_order")]);if(i)throw i;if(o)throw o;if(!l||l.length===0)return 0;const{data:c}=await V.from("deal_tasks").select("title").eq("deal_id",r),d=new Set((c||[]).map(g=>String(g.title).toLowerCase())),u=a,h=(g,x)=>{const y=g==="stage_entry"?null:u[g],v=y?new Date(`${y}T12:00:00`):new Date;return v.setDate(v.getDate()+(x||0)),v.toISOString().split("T")[0]},m=l.filter(g=>!d.has(String(g.title).toLowerCase())).map((g,x)=>({owner_user_id:s,deal_id:r,contact_id:u.contact_id,stage_id:u.stage_id,title:g.title,description:g.description,priority:g.priority,status:"todo",due_date:h(g.due_anchor,g.due_offset_days),sort_order:x}));if(m.length===0)return 0;const{error:p}=await V.from("deal_tasks").insert(m);if(p)throw p;return m.length},onSuccess:()=>{t.invalidateQueries({queryKey:["deal-tasks"]}),t.invalidateQueries({queryKey:["tc-dashboard"]})}})}function KLn(){const s=ai(),t=ls();return Nt({mutationFn:async({playbookId:n,stageId:r})=>{if(!s)throw new Error("Not authenticated");const[{data:a},{data:i,error:l}]=await Promise.all([V.from("tc_playbooks").select("deal_type").eq("id",n).single(),V.from("tc_playbook_tasks").select("*").eq("playbook_id",n).order("sort_order")]);if(l)throw l;if(!i||i.length===0)return 0;const{data:o}=await V.from("deal_task_templates").select("title").eq("owner_user_id",s).eq("stage_id",r),c=new Set((o||[]).map(h=>String(h.title).toLowerCase())),d=i.filter(h=>!c.has(String(h.title).toLowerCase())).map((h,m)=>({owner_user_id:s,stage_id:r,title:h.title,description:h.description,priority:h.priority,due_anchor:h.due_anchor,default_due_offset_days:h.due_offset_days,deal_type:(a==null?void 0:a.deal_type)??null,playbook_id:n,sort_order:m}));if(d.length===0)return 0;const{error:u}=await V.from("deal_task_templates").insert(d);if(u)throw u;return d.length},onSuccess:()=>{t.invalidateQueries({queryKey:["deal-task-templates"]})}})}function YLn(){const s=ai();return pt({queryKey:["tc-dashboard",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await V.from("deal_pipeline").select(` id, deal_name, deal_type, property_address, city, state, expected_price, expected_commission, stage_id, contact_id, contract_date, target_close_date, actual_close_date, inspection_date, inspection_contingency_date, appraisal_date, loan_approval_date, earnest_money_due_date, title_docs_due_date, final_walkthrough_date, stage:deal_pipeline_stages(id, name, color, is_won_stage, is_lost_stage), contact:innercircle_contacts(id, first_name, last_name, email, phone) `).eq("owner_user_id",s);if(n)throw n;const r=(t||[]).filter(l=>{var o,c;return!((o=l.stage)!=null&&o.is_lost_stage)&&!((c=l.stage)!=null&&c.is_won_stage)}),a=r.map(l=>l.id);let i={};if(a.length>0){const{data:l}=await V.from("deal_tasks").select("id, deal_id, title, status, priority, due_date").in("deal_id",a).order("due_date",{ascending:!0,nullsFirst:!1});(l||[]).forEach(o=>{var c;o.deal_id&&(i[c=o.deal_id]||(i[c]=[])).push(o)})}return r.map(l=>({...l,tasks:i[l.id]||[]}))},enabled:!!s})}function gQe(s){if(!s)return null;const[t,n,r]=String(s).split(/[-/T]/).map(Number);return!t||!n||!r?null:new Date(t,n-1,r)}function TS(s){const t=gQe(s);if(!t)return null;const n=new Date;return n.setHours(0,0,0,0),t.setHours(0,0,0,0),Math.round((t.getTime()-n.getTime())/864e5)}function ZLn(s){return s===null?"none":s<0?"overdue":s===0?"today":s<=3?"soon":"upcoming"}const XLn={done:"border-emerald-500/40 bg-emerald-500/10 text-emerald-700 dark:text-emerald-400",overdue:"border-destructive/40 bg-destructive/10 text-destructive",today:"border-amber-500/40 bg-amber-500/10 text-amber-700 dark:text-amber-400",soon:"border-amber-500/30 bg-amber-500/5 text-amber-700 dark:text-amber-400",upcoming:"border-border bg-muted/40 text-foreground",none:"border-dashed border-border bg-transparent text-muted-foreground"};function QLn(s){const t=gQe(s);return t?t.toLocaleDateString("en-US",{month:"short",day:"numeric"}):null}function ebt(s,t){return s==="done"?"Completed":t===null?"Not set":t===0?"Today":t<0?`${Math.abs(t)}d past due`:`in ${t}d`}function JLn({deal:s,compact:t=!1}){const n=VLn(),r=HLn(),[a,i]=k.useState(!1),[l,o]=k.useState({}),c=Array.isArray(s==null?void 0:s.completed_key_dates)?s.completed_key_dates:[],[d,u]=k.useState(c),h=c.join(","),m=k.useRef(h);k.useEffect(()=>{m.current!==h&&(m.current=h,u(c))},[h]);const p=d,g=()=>{const R={};nK.forEach(O=>{R[O.key]=(s==null?void 0:s[O.key])??""}),o(R),i(!0)},x=async()=>{try{await n.mutateAsync({dealId:s.id,dates:l}),ae.success("Transaction dates updated"),i(!1)}catch(R){ae.error((R==null?void 0:R.message)||"Could not save dates")}},y=async(R,O)=>{const B=p;u(R);try{await r.mutateAsync({dealId:s.id,completed:R}),ae.success(O)}catch(U){u(B),ae.error((U==null?void 0:U.message)||"Could not update milestone")}},v=k.useMemo(()=>nK.map(R=>{const O=(s==null?void 0:s[R.key])??null,B=TS(O),U=p.includes(R.key),G=O?U?"done":ZLn(B):"none";return{...R,value:O,days:B,isDone:U,state:G}}),[s,p.join(",")]),_=v.filter(R=>R.value).length,j=v.filter(R=>R.state==="done").length,C=TS(s==null?void 0:s.target_close_date),A=v.filter(R=>R.value&&!R.isDone&&R.days!==null&&R.days>=0).sort((R,O)=>(R.days??0)-(O.days??0))[0],M=v.filter(R=>R.state==="overdue"),I=()=>{const R=Array.from(new Set([...p,...M.map(O=>O.key)]));y(R,"Past milestones marked complete")},P=(R,O)=>{const B=O?p.filter(U=>U!==R):[...p,R];y(B,O?"Marked as not complete":"Milestone completed")};return e.jsx(Sk,{delayDuration:200,children:e.jsxs("div",{className:"rounded-xl border bg-card overflow-hidden",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 px-4 py-3 border-b bg-muted/30",children:[e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx("div",{className:"h-8 w-8 rounded-lg bg-primary/10 flex items-center justify-center shrink-0",children:e.jsx(wm,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-semibold leading-tight",children:"Transaction Timeline"}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:C!==null?C>=0?`${C} day${C===1?"":"s"} to closing · ${j}/${_} milestones done`:`Closing was ${Math.abs(C)} day${Math.abs(C)===1?"":"s"} ago`:`${_} of ${nK.length} key dates set`})]})]}),e.jsxs(Xc,{open:a,onOpenChange:R=>R?g():i(!1),children:[e.jsx(Qc,{asChild:!0,children:e.jsxs($,{variant:"outline",size:"sm",className:"shrink-0 gap-1.5",children:[e.jsx(ui,{className:"h-3.5 w-3.5"}),t?"":"Edit dates"]})}),e.jsxs(Bc,{className:"w-80 p-4 max-h-[70vh] overflow-y-auto",align:"end",children:[e.jsx("p",{className:"text-sm font-semibold mb-3",children:"Key transaction dates"}),e.jsx("div",{className:"space-y-3",children:nK.map(R=>e.jsxs("div",{className:"space-y-1",children:[e.jsx(re,{htmlFor:`kd-${R.key}`,className:"text-xs text-muted-foreground",children:R.label}),e.jsx(be,{id:`kd-${R.key}`,type:"date",value:l[R.key]??"",onChange:O=>o(B=>({...B,[R.key]:O.target.value})),className:"h-9"})]},R.key))}),e.jsxs("div",{className:"flex justify-end gap-2 mt-4",children:[e.jsx($,{variant:"ghost",size:"sm",onClick:()=>i(!1),children:"Cancel"}),e.jsxs($,{size:"sm",onClick:x,disabled:n.isPending,children:[n.isPending?e.jsx(Jt,{className:"h-3.5 w-3.5 mr-1 animate-spin"}):e.jsx(ma,{className:"h-3.5 w-3.5 mr-1"}),"Save"]})]})]})]})]}),e.jsxs("div",{className:"p-3",children:[e.jsx("div",{className:"grid grid-cols-3 sm:grid-cols-3 gap-2",children:v.map(R=>{const O=!!R.value;return e.jsxs(Lx,{children:[e.jsx(Rx,{asChild:!0,children:e.jsxs("button",{type:"button",disabled:!O||r.isPending,onClick:()=>O&&P(R.key,R.isDone),className:Ot("relative text-left rounded-lg border px-2.5 py-2 transition-colors w-full",XLn[R.state],O&&"hover:brightness-105 cursor-pointer"),children:[e.jsx("p",{className:"text-[10px] uppercase tracking-wide opacity-70 truncate pr-4",children:R.short}),e.jsx("p",{className:"text-sm font-semibold leading-tight truncate",children:QLn(R.value)??"—"}),R.value&&e.jsx("p",{className:"text-[10px] opacity-80 truncate",children:ebt(R.state,R.days)}),O&&e.jsx("span",{className:Ot("absolute top-1.5 right-1.5 h-4 w-4 rounded-full border flex items-center justify-center",R.isDone?"bg-emerald-500 border-emerald-500 text-white":"border-current opacity-40"),children:R.isDone&&e.jsx(ma,{className:"h-2.5 w-2.5"})})]})}),e.jsx(Jg,{side:"top",children:R.value?R.isDone?`${R.label} completed — click to reopen`:`Click to mark ${R.label} complete`:`${R.label} — not set`})]},R.key)})}),(M.length>0||A||j>0)&&e.jsxs("div",{className:"mt-3 flex flex-wrap items-center gap-2 text-xs",children:[j>0&&e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full bg-emerald-500/10 text-emerald-700 dark:text-emerald-400 px-2.5 py-1 font-medium",children:[e.jsx(L8,{className:"h-3 w-3"}),j," completed"]}),M.length>0&&e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full bg-destructive/10 text-destructive px-2.5 py-1 font-medium",children:[e.jsx(Gd,{className:"h-3 w-3"}),M.length," awaiting confirmation"]}),A&&e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full bg-primary/10 text-primary px-2.5 py-1 font-medium",children:["Next: ",A.label," · ",ebt(A.state,A.days)]}),M.length>0&&e.jsxs("button",{type:"button",onClick:I,disabled:r.isPending,className:"ml-auto inline-flex items-center gap-1 rounded-full border px-2.5 py-1 font-medium hover:bg-muted transition-colors",children:[e.jsx(L8,{className:"h-3 w-3"}),"Mark past dates complete"]})]}),M.length>0&&e.jsx("p",{className:"mt-2 text-[11px] text-muted-foreground",children:"Dates in the past show as awaiting confirmation until you check them off — tap a tile to mark it complete."}),_===0&&e.jsx("p",{className:"mt-3 text-xs text-muted-foreground text-center",children:"No key dates yet. Add them to unlock automatic deadline reminders."})]})]})})}const eRn={Home:ua,FileSignature:uE,Handshake:E5,CalendarClock:wm,Sparkles:kn,ClipboardCheck:A5},tRn={urgent:"bg-destructive/10 text-destructive",high:"bg-amber-500/10 text-amber-700 dark:text-amber-400",medium:"bg-primary/10 text-primary",low:"bg-muted text-muted-foreground"};function sRn(s,t){var a;const n=((a=qLn.find(i=>i.value===s))==null?void 0:a.label)??s;if(s==="stage_entry")return t===0?"Due immediately":`${t} days after stage entry`;const r=n.replace(/ date$/i,"");return t===0?`On ${r.toLowerCase()}`:t<0?`${Math.abs(t)} days before ${r.toLowerCase()}`:`${t} days after ${r.toLowerCase()}`}function rVt({open:s,onOpenChange:t,dealId:n,dealName:r}){const{data:a,isLoading:i}=GLn(),{data:l}=_te(),o=WLn(),c=KLn(),[d,u]=k.useState(null),[h,m]=k.useState({}),p=y=>{if(h[y.id])return h[y.id];const v=l==null?void 0:l.find(_=>{var j,C;return((j=_.name)==null?void 0:j.toLowerCase())===((C=y.target_stage_name)==null?void 0:C.toLowerCase())});return(v==null?void 0:v.id)??""},g=async y=>{if(n){u(y.id);try{const v=await o.mutateAsync({playbookId:y.id,dealId:n});ae.success(v>0?`Added ${v} task${v===1?"":"s"} to this deal`:"All tasks already exist on this deal"),v>0&&t(!1)}catch(v){ae.error((v==null?void 0:v.message)||"Could not apply playbook")}finally{u(null)}}},x=async y=>{const v=p(y);if(!v){ae.error("Pick which stage this playbook should trigger on");return}u(`install-${y.id}`);try{const _=await c.mutateAsync({playbookId:y.id,stageId:v});ae.success(_>0?`Automated — ${_} task${_===1?"":"s"} will now be created every time a deal reaches this stage`:"This playbook is already automated for that stage")}catch(_){ae.error((_==null?void 0:_.message)||"Could not automate playbook")}finally{u(null)}};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"sm:max-w-2xl max-h-[85vh] flex flex-col p-0",children:[e.jsx(Vs,{className:"p-6 pb-4 border-b",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-9 w-9 rounded-lg bg-primary/10 flex items-center justify-center",children:e.jsx(wg,{className:"h-4.5 w-4.5 text-primary"})}),e.jsxs("div",{children:[e.jsx($s,{children:"Transaction Playbooks"}),e.jsx(Cr,{children:r?`Drop a proven checklist onto ${r} — deadlines calculate from its real dates.`:"Proven checklists that run themselves. Automate one and every future deal gets it."})]})]})}),e.jsx(Eo,{className:"flex-1 min-h-0 overflow-y-auto",children:e.jsx("div",{className:"p-6 pt-4",children:i?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx(Jt,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):e.jsx(SF,{type:"single",collapsible:!0,className:"space-y-3",children:(a||[]).map(y=>{const v=eRn[y.icon||"ClipboardCheck"]||A5,_=y.accent_color||"hsl(var(--primary))";return e.jsxs(r6,{value:y.id,className:"border rounded-xl px-0 overflow-hidden bg-card",children:[e.jsx(a6,{className:"px-4 py-3 hover:no-underline",children:e.jsxs("div",{className:"flex items-center gap-3 text-left flex-1 min-w-0",children:[e.jsx("div",{className:"h-10 w-10 rounded-lg flex items-center justify-center shrink-0",style:{backgroundColor:`${_}1a`},children:e.jsx(v,{className:"h-5 w-5",style:{color:_}})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"font-semibold text-sm",children:y.name}),e.jsxs(qe,{variant:"secondary",className:"text-[10px]",children:[y.tasks.length," steps"]}),y.deal_type&&e.jsx(qe,{variant:"outline",className:"text-[10px] capitalize",children:y.deal_type})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 line-clamp-1",children:y.description})]})]})}),e.jsxs(i6,{className:"px-4 pb-4",children:[e.jsx("div",{className:"space-y-1.5 mb-4",children:y.tasks.map((j,C)=>e.jsxs("div",{className:"flex items-start gap-2.5 rounded-lg border bg-background px-3 py-2",children:[e.jsx("span",{className:"text-[10px] font-mono text-muted-foreground mt-0.5 w-4 shrink-0",children:C+1}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"text-sm font-medium leading-tight",children:j.title}),j.description&&e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:j.description}),e.jsx("p",{className:"text-[11px] text-muted-foreground mt-1",children:sRn(j.due_anchor,j.due_offset_days)})]}),e.jsx("span",{className:Ot("text-[10px] px-1.5 py-0.5 rounded-full shrink-0 capitalize",tRn[j.priority]),children:j.priority})]},j.id))}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-2 pt-2 border-t",children:[n&&e.jsxs($,{size:"sm",className:"gap-1.5",onClick:()=>g(y),disabled:d===y.id,children:[d===y.id?e.jsx(Jt,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(ix,{className:"h-3.5 w-3.5"}),"Add to this deal"]}),e.jsxs("div",{className:"flex gap-2 flex-1",children:[e.jsxs(bs,{value:p(y),onValueChange:j=>m(C=>({...C,[y.id]:j})),children:[e.jsx(ys,{className:"h-9 text-xs flex-1",children:e.jsx(_s,{placeholder:"Trigger stage"})}),e.jsx(vs,{children:(l||[]).map(j=>e.jsx(We,{value:j.id,children:j.name},j.id))})]}),e.jsxs($,{size:"sm",variant:"outline",className:"gap-1.5 shrink-0",onClick:()=>x(y),disabled:d===`install-${y.id}`,children:[d===`install-${y.id}`?e.jsx(Jt,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(lB,{className:"h-3.5 w-3.5"}),"Automate"]})]})]}),e.jsxs("p",{className:"text-[11px] text-muted-foreground mt-2 flex items-center gap-1",children:[e.jsx(Gr,{className:"h-3 w-3"}),"Automating adds these steps to every future deal that reaches that stage."]})]})]},y.id)})})})})]})})}const nRn={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"}},rRn={note:bo,call:ka,email:pn,meeting:ha,stage_change:Ir,task_completed:Gr,document:ua,system:sa};function aRn({deal:s,open:t,onOpenChange:n,onEdit:r,onAddToScorecard:a,isWonStage:i}){var Ue,Be;const l=Jn(),{data:o,isLoading:c}=kIn((s==null?void 0:s.id)||""),{data:d,isLoading:u}=CIn((s==null?void 0:s.id)||""),h=SIn(),m=EIn(),p=AIn(),g=NIn(),{data:x,isLoading:y}=CLn((s==null?void 0:s.id)||""),v=ALn(),_=ELn(),j=TLn(),C=k.useRef(null),[A,M]=k.useState(""),[I,P]=k.useState(""),[R,O]=k.useState(!1),[B,U]=k.useState(!1),[G,H]=k.useState(!1);if(!s)return null;const Y=nRn[s.deal_type],se=(()=>{var Ee;if(s.deal_type!=="seller"&&s.deal_type!=="dual")return null;const je=((Ee=s.listing)==null?void 0:Ee.created_at)||s.listing_date;if(!je)return null;const Ye=s.contract_date?ih(s.contract_date):new Date;return I2(Ye,ih(je))})(),ee=je=>je?new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(je):"-",oe=async()=>{if(A.trim())try{await h.mutateAsync({deal_id:s.id,activity_type:"note",title:"Note added",description:A}),M(""),ae.success("Note added")}catch{ae.error("Failed to add note")}},me=async()=>{if(I.trim())try{await m.mutateAsync({deal_id:s.id,title:I,sort_order:((d==null?void 0:d.length)||0)+1}),P(""),ae.success("Task added")}catch{ae.error("Failed to add task")}},Q=async(je,Ye)=>{try{await p.mutateAsync({id:je,is_completed:Ye,deal_id:s.id})}catch{ae.error("Failed to update task")}},te=async()=>{try{await g.mutateAsync(s.id),ae.success("Deal deleted"),n(!1)}catch{ae.error("Failed to delete deal")}},le=(d==null?void 0:d.filter(je=>je.is_completed).length)||0,fe=(d==null?void 0:d.length)||0,_e=(x==null?void 0:x.length)||0,ve=je=>je<1024?`${je} B`:je<1024*1024?`${(je/1024).toFixed(1)} KB`:`${(je/(1024*1024)).toFixed(1)} MB`,he=je=>je?je.startsWith("image/")?zc:je.includes("pdf")?ea:Uz:Uz,Se=async je=>{const Ye=je.target.files;if(!(!Ye||!s)){H(!0);try{for(const Ee of Array.from(Ye)){if(Ee.size>20*1024*1024){ae.error(`${Ee.name} exceeds 20MB limit`);continue}await v.mutateAsync({dealId:s.id,file:Ee})}ae.success("File(s) uploaded")}catch{ae.error("Failed to upload file")}finally{H(!1),C.current&&(C.current.value="")}}},Te=async(je,Ye)=>{if(s)try{await _.mutateAsync({fileId:je,storagePath:Ye,dealId:s.id}),ae.success("File deleted")}catch{ae.error("Failed to delete file")}},Ie=async(je,Ye)=>{try{const Ee=await MLn(je),Re=document.createElement("a");Re.href=Ee,Re.download=Ye,Re.target="_blank",document.body.appendChild(Re),Re.click(),document.body.removeChild(Re)}catch{ae.error("Failed to download file")}};return e.jsxs(e.Fragment,{children:[e.jsx(D_,{open:t,onOpenChange:n,children:e.jsxs(Mb,{className:"w-full sm:max-w-xl p-0 flex flex-col",children:[e.jsx(xj,{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(qe,{variant:"outline",className:Ot("text-xs",Y.color),children:Y.label}),e.jsxs(qe,{variant:"secondary",className:"text-xs capitalize",children:[s.priority," priority"]})]}),e.jsx(yj,{className:"text-xl",children:s.deal_name}),e.jsx("div",{className:"mt-2",children:e.jsx(SLn,{dealId:s.id})})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{variant:"outline",size:"icon",onClick:()=>r(s),children:e.jsx(Cp,{className:"h-4 w-4"})}),e.jsx($,{variant:"outline",size:"icon",className:"text-destructive hover:bg-destructive/10",onClick:()=>U(!0),children:e.jsx(Un,{className:"h-4 w-4"})})]})]})}),e.jsx(Eo,{className:"flex-1 [&>[data-radix-scroll-area-viewport]>div]:!block [&>[data-radix-scroll-area-viewport]>div]:!w-full",children:e.jsxs("div",{className:"p-6 space-y-6 min-w-0",children:[s.contact&&e.jsxs("div",{className:"flex items-center gap-3 p-3 bg-muted/50 rounded-lg",children:[e.jsxs("button",{type:"button",onClick:()=>{n(!1),l(`/mission-control/contacts/${s.contact_id}`)},className:"flex items-center gap-3 flex-1 min-w-0 text-left hover:opacity-80 transition-opacity group",children:[e.jsx(Wa,{className:"h-10 w-10",children:e.jsxs(Ka,{className:"bg-primary/10 text-primary",children:[(Ue=s.contact.first_name)==null?void 0:Ue[0],(Be=s.contact.last_name)==null?void 0:Be[0]]})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("p",{className:"font-medium group-hover:text-primary group-hover:underline truncate",children:[s.contact.first_name," ",s.contact.last_name]}),s.contact.email&&e.jsx("p",{className:"text-sm text-muted-foreground truncate",children:s.contact.email})]})]}),e.jsxs("div",{className:"flex gap-2 shrink-0",children:[s.contact.phone&&e.jsx($,{variant:"outline",size:"icon",asChild:!0,children:e.jsx("a",{href:`tel:${s.contact.phone}`,children:e.jsx(ka,{className:"h-4 w-4"})})}),s.contact.email&&e.jsx($,{variant:"outline",size:"icon",asChild:!0,children:e.jsx("a",{href:`mailto:${s.contact.email}`,children:e.jsx(pn,{className:"h-4 w-4"})})}),e.jsx($,{variant:"outline",size:"icon",title:"Open contact record",onClick:()=>{n(!1),l(`/mission-control/contacts/${s.contact_id}`)},children:e.jsx(Ir,{className:"h-4 w-4"})})]})]}),e.jsx(ULn,{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(ua,{className:"h-4 w-4 text-muted-foreground mt-0.5"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:s.property_address||"Address TBD"}),e.jsx("p",{className:"text-muted-foreground",children:[s.city,s.state,s.zip_code].filter(Boolean).join(", ")})]})]}),e.jsxs("div",{className:"bg-muted/50 rounded-lg p-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"Expected Price"}),e.jsx("p",{className:"text-lg font-bold",children:ee(s.expected_price)})]}),e.jsxs("div",{className:"bg-emerald-500/10 rounded-lg p-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"Expected GCI"}),e.jsx("p",{className:"text-lg font-bold text-emerald-600",children:ee(s.expected_commission)})]}),(s.brokerage_split_pct||s.team_split_pct||s.referral_fee_pct||s.franchise_fee_pct||s.transaction_fee)&&e.jsxs("div",{className:"col-span-2 bg-muted/30 rounded-lg p-3 space-y-1.5",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground mb-2",children:"Commission Splits"}),s.brokerage_split_pct!=null&&e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Brokerage Split"}),e.jsxs("span",{children:[s.brokerage_split_pct,"%",s.expected_commission?` (${ee(s.expected_commission*s.brokerage_split_pct/100)})`:""]})]}),s.team_split_pct!=null&&e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Team Split"}),e.jsxs("span",{children:[s.team_split_pct,"%"]})]}),s.referral_fee_pct!=null&&e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Referral Fee"}),e.jsxs("span",{children:[s.referral_fee_pct,"%"]})]}),s.franchise_fee_pct!=null&&e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Franchise Fee"}),e.jsxs("span",{children:[s.franchise_fee_pct,"%"]})]}),s.transaction_fee!=null&&e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Transaction Fee"}),e.jsx("span",{children:ee(s.transaction_fee)})]}),s.net_commission!=null&&e.jsx(e.Fragment,{children:e.jsx("div",{className:"border-t pt-1.5 mt-1.5",children:e.jsxs("div",{className:"flex justify-between text-sm font-semibold",children:[e.jsx("span",{children:"Net to Agent"}),e.jsx("span",{className:"text-emerald-600",children:ee(s.net_commission)})]})})})]}),i&&!s.scorecard_transaction_id&&a&&e.jsxs($,{onClick:()=>a(s),className:"w-full bg-green-600 hover:bg-green-700",children:[e.jsx(ql,{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(Gr,{className:"h-4 w-4 text-green-600"}),e.jsx("span",{children:"Synced to Scorecard"})]}),se!==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:Ot("text-lg font-bold",se>90?"text-red-600":se>60?"text-amber-600":"text-foreground"),children:[se," ",s.contract_date?"(final)":"days"]})]}),s.target_close_date&&e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(ha,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{children:["Close: ",Ys(ih(s.target_close_date),"MMM d, yyyy")]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(Su,{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(JLn,{deal:s}),e.jsx(OLn,{deal:s}),e.jsxs(ya,{defaultValue:"tasks",className:"w-full",children:[e.jsxs(va,{className:"w-full grid grid-cols-3",children:[e.jsxs(is,{value:"tasks",className:"gap-1",children:[e.jsx(Gr,{className:"h-4 w-4"}),"Tasks ",fe>0&&`(${le}/${fe})`]}),e.jsxs(is,{value:"files",className:"gap-1",children:[e.jsx(KT,{className:"h-4 w-4"}),"Files ",_e>0&&`(${_e})`]}),e.jsxs(is,{value:"activity",className:"gap-1",children:[e.jsx(sa,{className:"h-4 w-4"}),"Activity"]})]}),e.jsxs(cs,{value:"tasks",className:"mt-4 space-y-3",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(be,{placeholder:"Add a new task...",value:I,onChange:je=>P(je.target.value),onKeyDown:je=>je.key==="Enter"&&me()}),e.jsx($,{onClick:me,disabled:!I.trim(),children:e.jsx(nn,{className:"h-4 w-4"})}),e.jsxs($,{variant:"outline",className:"gap-1.5 shrink-0",onClick:()=>O(!0),children:[e.jsx(wg,{className:"h-4 w-4"}),"Playbooks"]})]}),e.jsxs("div",{className:"space-y-2",children:[d==null?void 0:d.map(je=>e.jsxs("div",{className:Ot("flex items-center gap-3 p-3 rounded-lg border transition-colors",je.is_completed?"bg-muted/50 border-border":"bg-background"),children:[e.jsx(Li,{checked:je.is_completed,onCheckedChange:Ye=>Q(je.id,!!Ye)}),e.jsx("span",{className:Ot("flex-1 text-sm",je.is_completed&&"line-through text-muted-foreground"),children:je.title}),je.due_date&&e.jsx("span",{className:"text-xs text-muted-foreground",children:Ys(new Date(je.due_date),"MMM d")})]},je.id)),(d==null?void 0:d.length)===0&&e.jsx("p",{className:"text-center text-muted-foreground text-sm py-4",children:"No tasks yet. Add one above!"})]})]}),e.jsxs(cs,{value:"files",className:"mt-4 space-y-3",children:[e.jsx("input",{type:"file",ref:C,className:"hidden",multiple:!0,onChange:Se,accept:".pdf,.doc,.docx,.xls,.xlsx,.jpg,.jpeg,.png,.webp,.gif,.txt,.csv"}),e.jsxs($,{variant:"outline",className:"w-full border-dashed",onClick:()=>{var je;return(je=C.current)==null?void 0:je.click()},disabled:G,children:[G?e.jsx(Jt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(gi,{className:"h-4 w-4 mr-2"}),G?"Uploading...":"Upload Files"]}),e.jsxs("div",{className:"space-y-2",children:[x==null?void 0:x.map(je=>{const Ye=he(je.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(Ye,{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:je.file_name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[ve(je.file_size)," · ",Ys(new Date(je.created_at),"MMM d, yyyy")]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Sk,{children:e.jsxs(Lx,{children:[e.jsx(Rx,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:`h-8 w-8 transition-colors ${je.visible_on_portal?"text-primary bg-primary/10 hover:bg-primary/20":"text-muted-foreground/40 hover:text-muted-foreground"}`,onClick:()=>j.mutate({fileId:je.id,visible:!je.visible_on_portal,dealId:s.id}),children:je.visible_on_portal?e.jsx(ba,{className:"h-4 w-4"}):e.jsx(x0,{className:"h-4 w-4"})})}),e.jsx(Jg,{side:"top",children:je.visible_on_portal?"Visible on client portal":"Hidden from client portal"})]})}),e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>Ie(je.storage_path,je.file_name),children:e.jsx(ji,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive hover:text-destructive",onClick:()=>Te(je.id,je.storage_path),children:e.jsx(mr,{className:"h-4 w-4"})})]})]},je.id)}),(x==null?void 0:x.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(cs,{value:"activity",className:"mt-4 space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(Ls,{placeholder:"Add a note...",value:A,onChange:je=>M(je.target.value),rows:2}),e.jsxs($,{onClick:oe,disabled:!A.trim(),size:"sm",className:"w-full",children:[e.jsx(Wr,{className:"h-4 w-4 mr-2"}),"Add Note"]})]}),e.jsxs("div",{className:"space-y-3",children:[o==null?void 0:o.map(je=>{const Ye=rRn[je.activity_type]||sa;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(Ye,{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:je.title}),je.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-0.5",children:je.description}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:Zc(new Date(je.created_at),{addSuffix:!0})})]})]},je.id)}),(o==null?void 0:o.length)===0&&e.jsx("p",{className:"text-center text-muted-foreground text-sm py-4",children:"No activity yet"})]})]})]})]})})]})}),e.jsx(rVt,{open:R,onOpenChange:O,dealId:s==null?void 0:s.id,dealName:s==null?void 0:s.deal_name}),e.jsx(oc,{open:B,onOpenChange:U,children:e.jsxs(Ql,{children:[e.jsxs(Jl,{children:[e.jsx(tc,{children:"Delete Deal?"}),e.jsxs(sc,{children:['This will permanently delete "',s.deal_name,'" and all associated data. This action cannot be undone.']})]}),e.jsxs(ec,{children:[e.jsx(nc,{children:"Cancel"}),e.jsx(Vl,{onClick:te,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete"})]})]})})]})}function iRn({open:s,onOpenChange:t,deal:n,onComplete:r}){const a=yAe(),i=Xqt(),{data:l}=NF(),{data:o}=vj(),[c,d]=k.useState({property_address:"",city:"",state:"",zip:"",transaction_type:"buyer",close_date:Ys(new Date,"yyyy-MM-dd"),sale_price:0,commission_amount:0,lead_source_id:"",client_type_id:"",notes:""});k.useEffect(()=>{if(n&&s){const m=n.deal_type==="seller"?"seller":"buyer",p=n.expected_price||0,g=n.commission_percentage||3,x=n.expected_commission||p*g/100;d({property_address:n.property_address||n.deal_name||"",city:n.city||"",state:n.state||"",zip:n.zip_code||"",transaction_type:m,close_date:n.actual_close_date||n.target_close_date||Ys(new Date,"yyyy-MM-dd"),sale_price:p,commission_amount:x,lead_source_id:"",client_type_id:"",notes:n.notes||""})}},[n,s]);const u=async m=>{if(m.preventDefault(),!!n)try{const p=await a.mutateAsync({property_address:c.property_address,city:c.city||null,state:c.state||null,zip:c.zip||null,transaction_type:c.transaction_type,close_date:c.close_date,sale_price:c.sale_price,commission_amount:c.commission_amount||null,brokerage_split_pct:n.brokerage_split_pct||null,team_split_pct:n.team_split_pct||null,franchise_fee_pct:n.franchise_fee_pct||null,referral_fee_pct:n.referral_fee_pct||null,transaction_fee:n.transaction_fee||null,lead_source_id:c.lead_source_id||null,client_type_id:c.client_type_id||null,contact_id:n.contact_id||null,notes:c.notes||null,is_win:!0});await i.mutateAsync({id:n.id,scorecard_transaction_id:p.id,actual_close_date:c.close_date}),ae.success("Deal added to Scorecard! 🎉"),t(!1),r==null||r()}catch(p){console.error("Error syncing to scorecard:",p),ae.error("Failed to add to scorecard")}},h=m=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:0,maximumFractionDigits:0}).format(m);return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"sm:max-w-[550px] max-h-[90vh] overflow-y-auto",children:[e.jsxs(Vs,{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(ql,{className:"h-6 w-6 text-green-600 dark:text-green-400"})}),e.jsx($s,{className:"text-center text-xl",children:"Congratulations on Closing! 🎉"}),e.jsx(Cr,{className:"text-center",children:"Review and confirm the details before adding this deal to your Scorecard."})]}),e.jsxs("form",{onSubmit:u,className:"space-y-4 mt-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(re,{htmlFor:"property_address",className:"flex items-center gap-2",children:[e.jsx(ua,{className:"h-4 w-4 text-muted-foreground"}),"Property Address *"]}),e.jsx(be,{id:"property_address",value:c.property_address,onChange:m=>d(p=>({...p,property_address:m.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(re,{htmlFor:"city",children:"City"}),e.jsx(be,{id:"city",value:c.city,onChange:m=>d(p=>({...p,city:m.target.value})),placeholder:"City"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"state",children:"State"}),e.jsx(be,{id:"state",value:c.state,onChange:m=>d(p=>({...p,state:m.target.value})),placeholder:"TX",maxLength:2})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"zip",children:"Zip"}),e.jsx(be,{id:"zip",value:c.zip,onChange:m=>d(p=>({...p,zip:m.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(re,{children:"Transaction Type *"}),e.jsxs(bs,{value:c.transaction_type,onValueChange:m=>d(p=>({...p,transaction_type:m})),children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"buyer",children:"Buyer"}),e.jsx(We,{value:"seller",children:"Seller"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(re,{htmlFor:"close_date",className:"flex items-center gap-2",children:[e.jsx(ha,{className:"h-4 w-4 text-muted-foreground"}),"Close Date *"]}),e.jsx(be,{id:"close_date",type:"date",value:c.close_date,onChange:m=>d(p=>({...p,close_date:m.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(re,{htmlFor:"sale_price",className:"flex items-center gap-2",children:[e.jsx(Su,{className:"h-4 w-4 text-muted-foreground"}),"Sale Price *"]}),e.jsx(be,{id:"sale_price",type:"number",value:c.sale_price||"",onChange:m=>d(p=>({...p,sale_price:Number(m.target.value)})),placeholder:"450000",required:!0,min:0}),c.sale_price>0&&e.jsx("p",{className:"text-xs text-muted-foreground",children:h(c.sale_price)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(re,{htmlFor:"commission_amount",className:"flex items-center gap-2",children:[e.jsx(ZT,{className:"h-4 w-4 text-muted-foreground"}),"GCI (Commission)"]}),e.jsx(be,{id:"commission_amount",type:"number",value:c.commission_amount||"",onChange:m=>d(p=>({...p,commission_amount:Number(m.target.value)})),placeholder:"13500",min:0}),c.commission_amount>0&&e.jsx("p",{className:"text-xs text-muted-foreground",children:h(c.commission_amount)})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Lead Source"}),e.jsxs(bs,{value:c.lead_source_id,onValueChange:m=>d(p=>({...p,lead_source_id:m})),children:[e.jsx(ys,{children:e.jsx(_s,{placeholder:"Select source"})}),e.jsx(vs,{children:l==null?void 0:l.map(m=>e.jsx(We,{value:m.id,children:m.name},m.id))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Client Type"}),e.jsxs(bs,{value:c.client_type_id,onValueChange:m=>d(p=>({...p,client_type_id:m})),children:[e.jsx(ys,{children:e.jsx(_s,{placeholder:"Select type"})}),e.jsx(vs,{children:o==null?void 0:o.map(m=>e.jsx(We,{value:m.id,children:m.name},m.id))})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"notes",children:"Notes"}),e.jsx(Ls,{id:"notes",value:c.notes,onChange:m=>d(p=>({...p,notes:m.target.value})),placeholder:"Any additional notes about this transaction...",rows:2})]}),e.jsxs(kr,{className:"gap-2 sm:gap-0 pt-4",children:[e.jsx($,{type:"button",variant:"outline",onClick:()=>t(!1),children:"Skip for now"}),e.jsx($,{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(xi,{className:"ml-2 h-4 w-4"})]})})]})]})]})})}const oRn={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"}},tbt={urgent:0,high:1,medium:2,low:3};function lRn({deals:s,stages:t,onDealClick:n,onStageChange:r}){const[a,i]=k.useState("target_close_date"),[l,o]=k.useState("asc"),c=p=>{a===p?o(g=>g==="asc"?"desc":"asc"):(i(p),o("asc"))},d=k.useMemo(()=>[...s].sort((p,g)=>{var y,v;let x=0;switch(a){case"deal_name":x=p.deal_name.localeCompare(g.deal_name);break;case"stage":{const _=((y=t.find(C=>C.id===p.stage_id))==null?void 0:y.sort_order)||0,j=((v=t.find(C=>C.id===g.stage_id))==null?void 0:v.sort_order)||0;x=_-j;break}case"expected_price":x=(p.expected_price||0)-(g.expected_price||0);break;case"expected_commission":x=(p.expected_commission||0)-(g.expected_commission||0);break;case"target_close_date":{const _=p.target_close_date?ih(p.target_close_date).getTime():1/0,j=g.target_close_date?ih(g.target_close_date).getTime():1/0;x=_-j;break}case"priority":x=tbt[p.priority]-tbt[g.priority];break}return l==="asc"?x:-x}),[s,t,a,l]),u=p=>p?new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(p):"—",h=p=>p?t.find(g=>g.id===p):null,m=({field:p,children:g})=>e.jsxs($,{variant:"ghost",size:"sm",className:"h-8 -ml-3 font-medium",onClick:()=>c(p),children:[g,a===p?l==="asc"?e.jsx(ap,{className:"ml-2 h-4 w-4"}):e.jsx(nx,{className:"ml-2 h-4 w-4"}):e.jsx(Ix,{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(Qa,{children:[e.jsx(Ja,{children:e.jsxs(vn,{className:"bg-muted/50",children:[e.jsx(Dt,{className:"w-[250px]",children:e.jsx(m,{field:"deal_name",children:"Deal Name"})}),e.jsx(Dt,{className:"w-[150px]",children:e.jsx(m,{field:"stage",children:"Stage"})}),e.jsx(Dt,{className:"w-[100px]",children:"Type"}),e.jsx(Dt,{className:"w-[120px]",children:e.jsx(m,{field:"expected_price",children:"Price"})}),e.jsx(Dt,{className:"w-[120px]",children:e.jsx(m,{field:"expected_commission",children:"GCI"})}),e.jsx(Dt,{className:"w-[130px]",children:e.jsx(m,{field:"target_close_date",children:"Close Date"})}),e.jsx(Dt,{className:"w-[100px]",children:e.jsx(m,{field:"priority",children:"Priority"})})]})}),e.jsx(ei,{children:d.map(p=>{h(p.stage_id);const g=oRn[p.deal_type],x=p.target_close_date?I2(ih(p.target_close_date),new Date):null,y=x!==null&&x<0,v=x!==null&&x<=7&&x>=0;return e.jsxs(vn,{className:Ot("cursor-pointer hover:bg-muted/50 transition-colors",y&&"bg-red-50/50"),onClick:()=>n(p),children:[e.jsx(_t,{className:"font-medium",children:e.jsxs("div",{children:[e.jsx("p",{className:"truncate max-w-[230px]",children:p.deal_name}),p.contact&&e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[p.contact.first_name," ",p.contact.last_name]})]})}),e.jsx(_t,{onClick:_=>_.stopPropagation(),children:e.jsx(tVt,{stages:t,currentStageId:p.stage_id||"",onStageSelect:(_,j)=>r(p.id,_,j)})}),e.jsx(_t,{children:e.jsx(qe,{variant:"outline",className:Ot("text-xs",g.color),children:g.label})}),e.jsx(_t,{children:e.jsx("span",{className:"font-medium",children:u(p.expected_price)})}),e.jsx(_t,{children:e.jsx("span",{className:"text-emerald-600",children:u(p.expected_commission)})}),e.jsx(_t,{children:p.target_close_date?e.jsxs("div",{className:Ot("flex items-center gap-1 text-sm",y&&"text-red-600",v&&!y&&"text-amber-600"),children:[y&&e.jsx(Ho,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:Ys(ih(p.target_close_date),"MMM d, yyyy")})]}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx(_t,{children:e.jsx(qe,{variant:"outline",className:Ot("text-xs capitalize",p.priority==="urgent"&&"border-red-200 bg-red-50 text-red-700",p.priority==="high"&&"border-orange-200 bg-orange-50 text-orange-700",p.priority==="medium"&&"border-amber-200 bg-amber-50 text-amber-700",p.priority==="low"&&"border-slate-200 bg-slate-50 text-slate-600"),children:p.priority})})]},p.id)})})]})})}function aVt(){const s=ai();return pt({queryKey:["deal-tasks",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await V.from("deal_tasks").select(` *, deal:deal_pipeline(id, deal_name, stage_id), contact:innercircle_contacts(id, first_name, last_name), stage:deal_pipeline_stages(id, name, color) `).eq("owner_user_id",s).order("sort_order",{ascending:!0});if(n)throw n;return t},enabled:!!s})}function cRn(s){const t=ai();return pt({queryKey:["deal-tasks","deal",s,t],queryFn:async()=>{if(!t||!s)return[];const{data:n,error:r}=await V.from("deal_tasks").select(` *, stage:deal_pipeline_stages(id, name, color) `).eq("owner_user_id",t).eq("deal_id",s).order("sort_order",{ascending:!0});if(r)throw r;return n},enabled:!!t&&!!s})}function dRn(){const s=ai(),t=ls();return Nt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r,error:a}=await V.from("deal_tasks").insert({owner_user_id:s,title:n.title,description:n.description||null,deal_id:n.deal_id||null,contact_id:n.contact_id||null,stage_id:n.stage_id||null,priority:n.priority||"medium",status:n.status||"todo",due_date:n.due_date||null,sort_order:n.sort_order||0}).select().single();if(a)throw a;return r},onSuccess:()=>{t.invalidateQueries({queryKey:["deal-tasks"]})}})}function uRn(){const s=ls();return Nt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await V.from("deal_tasks").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["deal-tasks"]})}})}function hRn(){const s=ls();return Nt({mutationFn:async t=>{const{error:n}=await V.from("deal_tasks").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["deal-tasks"]})}})}function UTe(){const s=ls();return Nt({mutationFn:async({id:t,status:n})=>{const{data:r,error:a}=await V.from("deal_tasks").update({status:n,completed_at:n==="done"?new Date().toISOString():null}).eq("id",t).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["deal-tasks"]})}})}function mRn(){const s=ls();return Nt({mutationFn:async t=>{if(t.length===0)return;const{error:n}=await V.from("deal_tasks").update({status:"done",completed_at:new Date().toISOString()}).in("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["deal-tasks"]})}})}function fRn(s){const t=ai();return pt({queryKey:["deal-task-templates",t,s],queryFn:async()=>{if(!t)return[];let n=V.from("deal_task_templates").select("*").eq("owner_user_id",t).order("sort_order",{ascending:!0});s&&(n=n.eq("stage_id",s));const{data:r,error:a}=await n;if(a)throw a;return r},enabled:!!t})}function pRn(){const s=ai(),t=ls();return Nt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r,error:a}=await V.from("deal_task_templates").insert({owner_user_id:s,stage_id:n.stage_id,title:n.title,description:n.description||null,priority:n.priority||"medium",default_due_offset_days:n.default_due_offset_days||null,sort_order:n.sort_order||0}).select().single();if(a)throw a;return r},onSuccess:()=>{t.invalidateQueries({queryKey:["deal-task-templates"]})}})}function gRn(){const s=ls();return Nt({mutationFn:async t=>{const{error:n}=await V.from("deal_task_templates").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["deal-task-templates"]})}})}function xRn(){const s=ai(),t=ls();return Nt({mutationFn:async({dealId:n,stageId:r})=>{if(!s)throw new Error("Not authenticated");const{data:a,error:i}=await V.from("deal_task_templates").select("*").eq("owner_user_id",s).eq("stage_id",r).order("sort_order");if(i)throw i;if(!a||a.length===0)return[];const{data:l}=await V.from("deal_tasks").select("title, stage_id").eq("deal_id",n).eq("stage_id",r),o=new Set((l||[]).map(h=>h.title)),c=a.filter(h=>!o.has(h.title)).map((h,m)=>({owner_user_id:s,deal_id:n,stage_id:r,title:h.title,description:h.description,priority:h.priority,due_date:h.default_due_offset_days?new Date(Date.now()+h.default_due_offset_days*864e5).toISOString().split("T")[0]:null,sort_order:m,status:"todo"}));if(c.length===0)return[];const{data:d,error:u}=await V.from("deal_tasks").insert(c).select();if(u)throw u;return d},onSuccess:()=>{t.invalidateQueries({queryKey:["deal-tasks"]})}})}const yRn={urgent:"🔴",high:"🟠",medium:"🟡",low:"🟢"};function vRn({open:s,onOpenChange:t,dealId:n,dealName:r,fromStageName:a,toStageName:i,toStageId:l,onConfirm:o}){const{data:c,isLoading:d}=cRn(s?n:void 0),u=mRn(),h=xRn(),[m,p]=k.useState(new Set),[g,x]=k.useState(!1),y=(c||[]).filter(C=>C.status!=="done");k.useEffect(()=>{y.length>0&&p(new Set(y.map(C=>C.id)))},[c]);const v=C=>{p(A=>{const M=new Set(A);return M.has(C)?M.delete(C):M.add(C),M})},_=async()=>{x(!0);try{const C=Array.from(m);C.length>0&&await u.mutateAsync(C),await o(),await h.mutateAsync({dealId:n,stageId:l}),t(!1)}catch(C){console.error("Stage move failed:",C),ae.error((C==null?void 0:C.message)||"Failed to move deal. Please try again.")}finally{x(!1)}},j=async()=>{x(!0);try{await o(),await h.mutateAsync({dealId:n,stageId:l}),t(!1)}catch(C){console.error("Stage move (skip) failed:",C),ae.error((C==null?void 0:C.message)||"Failed to move deal. Please try again.")}finally{x(!1)}};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"sm:max-w-[480px]",children:[e.jsxs(Vs,{children:[e.jsx($s,{children:"Move Deal"}),e.jsxs(Cr,{children:["Moving ",e.jsx("span",{className:"font-medium text-foreground",children:r})]})]}),e.jsxs("div",{className:"flex items-center justify-center gap-3 py-2",children:[e.jsx(qe,{variant:"outline",className:"text-sm",children:a}),e.jsx(xi,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(qe,{className:"text-sm bg-primary",children:i})]}),d?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(Jt,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):y.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:y.length})," incomplete task",y.length!==1?"s":"",". Select which to mark as done:"]}),e.jsx(Eo,{className:"max-h-[250px]",children:e.jsx("div",{className:"space-y-1",children:y.map(C=>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(Li,{checked:m.has(C.id),onCheckedChange:()=>v(C.id)}),e.jsxs("span",{className:"text-sm flex-1",children:[yRn[C.priority]," ",C.title]}),C.stage&&e.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded-full",style:{backgroundColor:C.stage.color+"20",color:C.stage.color},children:C.stage.name})]},C.id))})}),e.jsxs("div",{className:"flex items-center justify-between gap-2 pt-2",children:[e.jsx($,{variant:"ghost",size:"sm",onClick:()=>{m.size===y.length?p(new Set):p(new Set(y.map(C=>C.id)))},children:m.size===y.length?"Deselect All":"Select All"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{variant:"outline",size:"sm",onClick:j,disabled:g,children:"Skip"}),e.jsxs($,{size:"sm",onClick:_,disabled:g,children:[g&&e.jsx(Jt,{className:"h-4 w-4 mr-1 animate-spin"}),m.size>0?`Complete ${m.size} & Move`:"Move Deal"]})]})]})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"text-center py-4",children:[e.jsx(Gr,{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($,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs($,{onClick:_,disabled:g,children:[g&&e.jsx(Jt,{className:"h-4 w-4 mr-1 animate-spin"}),"Move to ",i]})]})]})]})})}const bRn=[{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"}],_Rn=[{id:"noir",name:"Luxury — Noir & Gold",description:"Dark, editorial, high-end concierge feel.",bg:"#0d0d0d",surface:"#171717",accent:"#c9a84c",ink:"#f5f2ea"},{id:"azure",name:"Professional Blue",description:"Light, clean and corporate — easy to read.",bg:"#f5f8fc",surface:"#ffffff",accent:"#1259ce",ink:"#1a2433"}];function iVt({open:s,onOpenChange:t}){const n=ai(),{data:r,isLoading:a}=aMt(),i=D4s(),[l,o]=k.useState({logo_url:null,cover_photo_url:null,brand_color:null,accent_color:null,tagline:null,welcome_message:null,portal_theme:"noir"}),[c,d]=k.useState(null);k.useEffect(()=>{s&&o({logo_url:(r==null?void 0:r.logo_url)??null,cover_photo_url:(r==null?void 0:r.cover_photo_url)??null,brand_color:(r==null?void 0:r.brand_color)??null,accent_color:(r==null?void 0:r.accent_color)??null,tagline:(r==null?void 0:r.tagline)??null,welcome_message:(r==null?void 0:r.welcome_message)??null,portal_theme:(r==null?void 0:r.portal_theme)??"noir"})},[s,r]);const u=p=>o(g=>({...g,...p})),h=async(p,g)=>{if(n){if(p.size>5*1024*1024){ae.error("Image must be under 5MB");return}d(g);try{const x=await iMt(n,p,g);u(g==="logo"?{logo_url:x}:{cover_photo_url:x})}catch(x){ae.error(`Upload failed: ${x.message||x}`)}finally{d(null)}}},m=async()=>{try{await i.mutateAsync(l),ae.success("Portal branding saved"),t(!1)}catch{ae.error("Failed to save branding")}};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"max-w-lg max-h-[90vh] flex flex-col",children:[e.jsxs(Vs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(gd,{className:"h-5 w-5 text-primary"}),"Portal Branding"]}),e.jsx(Cr,{children:"Customize how your client portals look. These defaults apply to every portal — you can override them per deal."})]}),e.jsx(Eo,{className:"flex-1 pr-3 -mr-3",children:a?e.jsx("div",{className:"py-12 flex justify-center",children:e.jsx(Jt,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):e.jsxs("div",{className:"space-y-6 py-2",children:[e.jsx(wRn,{draft:l}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(re,{className:"text-sm font-medium",children:"Portal Theme"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"The overall look and feel your clients see when they open their portal."})]}),e.jsx("div",{className:"grid grid-cols-2 gap-3",children:_Rn.map(p=>{const g=(l.portal_theme??"noir")===p.id;return e.jsxs("button",{type:"button",onClick:()=>u({portal_theme:p.id}),className:Ot("rounded-xl border-2 p-3 text-left transition-all",g?"border-primary ring-2 ring-primary/20":"border-input hover:border-primary/40"),children:[e.jsx("div",{className:"rounded-lg overflow-hidden mb-2",style:{background:p.bg},children:e.jsxs("div",{className:"p-3 space-y-1.5",children:[e.jsx("div",{className:"h-1.5 w-10 rounded-full",style:{background:p.accent}}),e.jsx("div",{className:"h-2.5 w-20 rounded",style:{background:p.ink,opacity:.85}}),e.jsx("div",{className:"h-6 rounded-md",style:{background:p.surface,border:`1px solid ${p.accent}44`}})]})}),e.jsx("div",{className:"text-sm font-medium text-foreground",children:p.name}),e.jsx("div",{className:"text-[11px] text-muted-foreground leading-snug",children:p.description})]},p.id)})})]}),e.jsx(sbt,{label:"Logo",hint:"Shown above your name on the portal. PNG with transparent background works best.",value:l.logo_url,uploading:c==="logo",onUpload:p=>h(p,"logo"),onClear:()=>u({logo_url:null}),aspect:"square"}),e.jsx(sbt,{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:p=>h(p,"cover"),onClear:()=>u({cover_photo_url:null}),aspect:"cover"}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(re,{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:bRn.map(p=>{const g=l.brand_color===p.brand&&l.accent_color===p.accent;return e.jsxs("button",{type:"button",onClick:()=>u({brand_color:p.brand,accent_color:p.accent}),className:Ot("group relative rounded-lg border-2 p-2 text-left transition-all",g?"border-primary ring-2 ring-primary/20":"border-input hover:border-primary/40"),children:[e.jsxs("div",{className:"flex h-6 rounded-md overflow-hidden",children:[e.jsx("div",{className:"flex-1",style:{background:p.brand}}),e.jsx("div",{className:"flex-1",style:{background:p.accent}})]}),e.jsx("div",{className:"text-[11px] mt-1.5 font-medium text-foreground",children:p.name})]},p.name)})}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(nbt,{label:"Brand",value:l.brand_color,onChange:p=>u({brand_color:p})}),e.jsx(nbt,{label:"Accent",value:l.accent_color,onChange:p=>u({accent_color:p})})]})]}),e.jsxs("div",{children:[e.jsx(re,{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(be,{value:l.tagline||"",onChange:p=>u({tagline:p.target.value}),placeholder:"Your trusted real estate advisor",maxLength:80})]}),e.jsxs("div",{children:[e.jsx(re,{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:p=>u({welcome_message:p.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($,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs($,{onClick:m,disabled:i.isPending,children:[i.isPending?e.jsx(Jt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Ml,{className:"h-4 w-4 mr-2"}),"Save Branding"]})]})]})})}function wRn({draft:s}){const t=s.brand_color||"#2a4c64",n=s.accent_color||"#406E71";return e.jsxs("div",{className:"rounded-xl overflow-hidden border border-input shadow-sm",children:[e.jsx("div",{className:"relative h-24 flex items-center justify-center text-white",style:{background:s.cover_photo_url?`linear-gradient(135deg, ${t}cc, ${n}cc), url(${s.cover_photo_url}) center/cover`:`linear-gradient(135deg, ${t}, ${n})`},children:s.logo_url?e.jsx("img",{src:s.logo_url,alt:"logo",className:"h-12 w-12 rounded-full object-cover border-2 border-white/40 shadow"}):e.jsx("div",{className:"h-12 w-12 rounded-full bg-white/20 border-2 border-white/40"})}),e.jsxs("div",{className:"bg-white p-3 text-center",children:[e.jsx("div",{className:"text-sm font-semibold text-slate-800",children:"Your Name"}),e.jsx("div",{className:"text-[11px] text-slate-500",children:s.tagline||"Your tagline appears here"})]})]})}function sbt({label:s,hint:t,value:n,uploading:r,onUpload:a,onClear:i,aspect:l}){return e.jsxs("div",{children:[e.jsx(re,{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:Ot("rounded-lg border-2 border-dashed border-input flex items-center justify-center overflow-hidden bg-muted/30 shrink-0",l==="square"?"h-16 w-16":"h-16 w-32"),children:n?e.jsx("img",{src:n,alt:s,className:"h-full w-full object-cover"}):e.jsx(zc,{className:"h-5 w-5 text-muted-foreground/40"})}),e.jsxs("div",{className:"flex-1 flex gap-2",children:[e.jsxs("label",{className:"cursor-pointer",children:[e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:o=>{var d;const c=(d=o.target.files)==null?void 0:d[0];c&&a(c),o.target.value=""}}),e.jsxs("span",{className:"inline-flex items-center gap-1.5 h-9 px-3 rounded-md border border-input bg-background hover:bg-accent text-sm font-medium",children:[r?e.jsx(Jt,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(gi,{className:"h-3.5 w-3.5"}),n?"Replace":"Upload"]})]}),n&&e.jsx($,{variant:"ghost",size:"sm",onClick:i,className:"text-muted-foreground hover:text-destructive",children:e.jsx(Un,{className:"h-3.5 w-3.5"})})]})]})]})}function nbt({label:s,value:t,onChange:n}){const r=t||"#000000";return e.jsxs("div",{children:[e.jsx(re,{className:"text-xs text-muted-foreground",children:s}),e.jsxs("div",{className:"mt-1 flex items-center gap-2 h-9 rounded-md border border-input bg-background px-2",children:[e.jsx("input",{type:"color",value:r,onChange:a=>n(a.target.value),className:"h-6 w-8 rounded cursor-pointer border-0 bg-transparent"}),e.jsx(be,{value:t||"",onChange:a=>n(a.target.value||null),placeholder:"#406E71",className:"border-0 h-7 px-1 focus-visible:ring-0 text-xs font-mono"})]})]})}function jRn(){const s=ai();return pt({queryKey:["all-client-portals",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await V.from("client_portals").select("*").eq("owner_user_id",s);if(n)throw n;return t||[]},enabled:!!s})}function NRn({dealId:s,dealName:t,contactName:n,portal:r,onSettingsOpen:a,onComposerOpen:i,onInviteOpen:l,onDeleteConfirm:o}){const c=UZe(),d=EV(),u=Q7t(),h=J7t(),[m,p]=k.useState(!1),g=!!(r!=null&&r.archived_at),x=async()=>{p(!0);try{await c.mutateAsync({deal_id:s,visibility:"private",require_onboarding:!0}),ae.success("Portal enabled!")}catch{ae.error("Failed to create portal")}finally{p(!1)}},y=async A=>{if(r)try{await d.mutateAsync({id:r.id,is_enabled:A}),ae.success(A?"Portal enabled":"Portal disabled")}catch{ae.error("Failed to update portal")}},v=()=>{r&&(navigator.clipboard.writeText(B5(r.slug)),ae.success("Link copied!"))},_=()=>{r&&window.open(B5(r.slug),"_blank")},j=async()=>{if(r)try{await u.mutateAsync(r.id),ae.success("Portal archived")}catch{ae.error("Failed to archive portal")}},C=async()=>{if(r)try{await h.mutateAsync(r.id),ae.success("Portal restored")}catch{ae.error("Failed to restore portal")}};return r?g?e.jsxs("div",{className:"flex items-center gap-4 p-4 border rounded-lg opacity-60 bg-muted/30",children:[e.jsxs(nr,{to:`/mission-control/client-portals/${r.id}`,className:"flex-1 min-w-0 hover:opacity-80",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:t}),e.jsx(qe,{variant:"outline",className:"text-[10px] bg-muted text-muted-foreground",children:"Archived"})]}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:r.client_name||n||"No client name"})]}),e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[e.jsxs($,{variant:"ghost",size:"sm",onClick:C,className:"text-xs gap-1",children:[e.jsx(OT,{className:"h-3.5 w-3.5"}),"Restore"]}),e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>o(r),className:"text-xs gap-1 text-destructive hover:text-destructive",children:[e.jsx(Un,{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(nr,{to:`/mission-control/client-portals/${r.id}`,className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"font-medium text-sm truncate group-hover:text-primary transition-colors",children:t}),e.jsx(qe,{variant:"outline",className:r.is_enabled?"text-[10px] bg-emerald-500/10 text-emerald-600 border-emerald-200":"text-[10px] bg-muted text-muted-foreground",children:r.is_enabled?"Active":"Disabled"}),e.jsx(fi,{className:"h-3.5 w-3.5 text-muted-foreground opacity-0 group-hover:opacity-100 transition-opacity"})]}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:r.client_name||n||"No client name"})]}),e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:v,title:"Copy link",children:e.jsx(Da,{className:"h-3.5 w-3.5"})}),e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:_,title:"Preview",children:e.jsx(Ir,{className:"h-3.5 w-3.5"})}),e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>l(r,t),title:"Invite client",children:e.jsx(Wr,{className:"h-3.5 w-3.5"})}),e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>i(r),title:"Post update",children:e.jsx(h5,{className:"h-3.5 w-3.5"})}),e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>a(r),title:"Settings",children:e.jsx(Yc,{className:"h-3.5 w-3.5"})}),e.jsxs(Au,{children:[e.jsx(Eu,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8",children:e.jsx(u0,{className:"h-3.5 w-3.5"})})}),e.jsx(gu,{align:"end",children:e.jsxs(Pa,{onClick:j,children:[e.jsx(kf,{className:"h-4 w-4 mr-2"}),"Archive Portal"]})})]}),e.jsx(On,{checked:r.is_enabled,onCheckedChange:y,className:"ml-1"})]})]}):e.jsxs("div",{className:"flex items-center justify-between p-4 border rounded-lg border-dashed bg-muted/20",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:t}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:n||"No contact"})]}),e.jsxs($,{size:"sm",onClick:x,disabled:m,className:"shrink-0 ml-4",children:[m?e.jsx(Jt,{className:"h-3 w-3 animate-spin mr-1"}):e.jsx(kn,{className:"h-3 w-3 mr-1"}),"Enable Portal"]})]})}function oVt(){const{data:s,isLoading:t}=$Te(),{data:n,isLoading:r}=jRn(),[a,i]=k.useState(""),[l,o]=k.useState("all"),c=e9t(),[d,u]=k.useState(null),[h,m]=k.useState(null),[p,g]=k.useState(null),[x,y]=k.useState(null),[v,_]=k.useState(!1),j=ai(),C=t||r,A=new Map;n==null||n.forEach(U=>A.set(U.deal_id,U));const I=[...(s||[]).filter(U=>{var ee,oe,me,Q,te;const G=A.get(U.id),H=a.toLowerCase(),Y=!H||U.deal_name.toLowerCase().includes(H)||((oe=(ee=U.contact)==null?void 0:ee.first_name)==null?void 0:oe.toLowerCase().includes(H))||((Q=(me=U.contact)==null?void 0:me.last_name)==null?void 0:Q.toLowerCase().includes(H))||((te=G==null?void 0:G.client_name)==null?void 0:te.toLowerCase().includes(H));let se=!0;return l==="active"?se=!!(G!=null&&G.is_enabled)&&!(G!=null&&G.archived_at):l==="disabled"?se=!!G&&!G.is_enabled&&!G.archived_at:l==="archived"?se=!!(G!=null&&G.archived_at):l==="none"?se=!G:l==="all"&&(se=!(G!=null&&G.archived_at)||!G),Y&&se})].sort((U,G)=>{const H=A.get(U.id),Y=A.get(G.id);if(H!=null&&H.archived_at&&!(Y!=null&&Y.archived_at))return 1;if(!(H!=null&&H.archived_at)&&(Y!=null&&Y.archived_at)||H&&!Y)return-1;if(!H&&Y)return 1;if(H&&Y){if(H.is_enabled&&!Y.is_enabled)return-1;if(!H.is_enabled&&Y.is_enabled)return 1}return 0}),P=(n==null?void 0:n.filter(U=>!U.archived_at).length)||0,R=(n==null?void 0:n.filter(U=>U.is_enabled&&!U.archived_at).length)||0,O=(n==null?void 0:n.filter(U=>U.archived_at).length)||0,B=async()=>{if(x)try{await c.mutateAsync({id:x.id,dealId:x.deal_id}),ae.success("Portal permanently deleted"),y(null)}catch{ae.error("Failed to delete portal")}};return C?e.jsx("div",{className:"flex items-center justify-center py-16",children:e.jsx(Jt,{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(kn,{className:"h-4 w-4 text-primary"}),e.jsxs("span",{className:"font-medium",children:[P," Portals"]})]}),e.jsxs("span",{className:"text-muted-foreground",children:[R," active · ",P-R," disabled",O>0&&` · ${O} archived`]})]}),e.jsxs($,{variant:"outline",size:"sm",onClick:()=>_(!0),className:"gap-1.5",children:[e.jsx(gd,{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(Yr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search deals or clients...",value:a,onChange:U=>i(U.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(mr,{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(U=>e.jsx($,{variant:l===U?"secondary":"ghost",size:"sm",onClick:()=>o(U),className:"text-xs px-3 capitalize",children:U==="none"?"No Portal":U},U))})]}),e.jsx(Eo,{className:"h-[calc(100vh-22rem)]",children:e.jsxs("div",{className:"space-y-2 pb-4",children:[I.map(U=>{const G=A.get(U.id)||null,H=U.contact?`${U.contact.first_name||""} ${U.contact.last_name||""}`.trim():"";return e.jsx(NRn,{dealId:U.id,dealName:U.deal_name,contactName:H,portal:G,onSettingsOpen:u,onComposerOpen:Y=>m(Y),onInviteOpen:(Y,se)=>g({portal:Y,dealName:se}),onDeleteConfirm:y},U.id)}),I.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(kn,{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(mQe,{open:!!d,onOpenChange:U=>!U&&u(null),portal:d,dealOwnerId:j||""}),h&&e.jsx(fQe,{open:!!h,onOpenChange:U=>!U&&m(null),portalId:h.id,portalSlug:h.slug,notifyClient:h.notify_client}),p&&e.jsx(pQe,{open:!!p,onOpenChange:U=>!U&&g(null),portal:p.portal,dealName:p.dealName}),e.jsx(iVt,{open:v,onOpenChange:_}),e.jsx(oc,{open:!!x,onOpenChange:U=>!U&&y(null),children:e.jsxs(Ql,{children:[e.jsxs(Jl,{children:[e.jsx(tc,{children:"Permanently delete this portal?"}),e.jsx(sc,{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(ec,{children:[e.jsx(nc,{children:"Cancel"}),e.jsx(Vl,{onClick:B,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete Permanently"})]})]})})]})}function kRn({summary:s,stats:t,search:n,onSearchChange:r,onAddDeal:a,onRefresh:i,onTeam:l,viewControls:o,filters:c,activeFilters:d=[],onClearAll:u,resultLabel:h,showSearch:m=!0}){return e.jsx("section",{className:"hub-ink relative overflow-hidden rounded-2xl p-4 sm:p-6",children:e.jsxs("div",{className:"relative flex flex-col gap-4",children:[e.jsxs("div",{className:"flex flex-col gap-3 lg:flex-row lg:items-start lg:justify-between",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-xs uppercase tracking-wider hub-ink-muted",children:"Agent OS"}),e.jsx("h1",{className:"mt-1 text-2xl font-bold sm:text-3xl",children:"Deal Pipeline"}),e.jsx("p",{className:"mt-1 text-sm hub-ink-muted",children:s})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs("button",{onClick:a,className:"inline-flex items-center gap-2 rounded-full bg-background px-4 py-2 text-sm font-semibold text-foreground shadow-sm transition-transform hover:scale-[1.02]",children:[e.jsx(nn,{className:"h-4 w-4"}),"Add Deal"]}),l&&e.jsxs("button",{onClick:l,className:"hub-glass inline-flex items-center gap-2 rounded-full px-4 py-2 text-sm font-medium transition-colors",children:[e.jsx(Xn,{className:"h-4 w-4",style:{color:"hsl(var(--hub-glow))"}}),"Team"]}),e.jsx("button",{onClick:i,"aria-label":"Refresh pipeline",className:"hub-glass inline-flex h-9 w-9 items-center justify-center rounded-full transition-colors",children:e.jsx(yo,{className:"h-4 w-4"})}),o]})]}),t.length>0&&e.jsx("div",{className:"-mx-1 flex gap-2 overflow-x-auto px-1 pb-1 sm:grid sm:grid-cols-3 sm:overflow-visible lg:grid-cols-5",children:t.map(p=>{const g=p.onClick?"button":"div";return e.jsxs(g,{type:p.onClick?"button":void 0,onClick:p.onClick,title:p.hint,className:Ot("hub-glass min-w-[130px] shrink-0 rounded-xl px-3 py-2.5 text-left transition-all sm:min-w-0",p.onClick&&"hover:scale-[1.02]",p.active&&"ring-2"),style:p.active?{boxShadow:"0 0 0 2px hsl(var(--hub-glow))"}:void 0,children:[e.jsx("p",{className:"text-[11px] uppercase tracking-wide hub-ink-muted",children:p.label}),e.jsx("p",{className:"mt-0.5 text-lg font-bold leading-tight",children:p.value}),p.subtitle&&e.jsx("p",{className:"text-[11px] hub-ink-muted",children:p.subtitle})]},p.label)})}),m&&e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs("div",{className:"relative min-w-[200px] flex-1 sm:max-w-sm",children:[e.jsx(Yr,{className:"pointer-events-none absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 opacity-70"}),e.jsx("input",{value:n,onChange:p=>r(p.target.value),placeholder:"Search deals, contacts, addresses, tags...",className:"hub-glass h-10 w-full rounded-full border-0 pl-9 pr-8 text-sm outline-none placeholder:opacity-60 focus:ring-2 focus:ring-white/30"}),n&&e.jsx("button",{onClick:()=>r(""),"aria-label":"Clear search",className:"absolute right-3 top-1/2 -translate-y-1/2 opacity-70 hover:opacity-100",children:e.jsx(mr,{className:"h-4 w-4"})})]}),c]}),(d.length>0||h)&&e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[d.map(p=>e.jsxs("button",{onClick:p.onClear,className:"hub-glass inline-flex items-center gap-1.5 rounded-full px-3 py-1 text-xs font-medium",children:[p.label,e.jsx(mr,{className:"h-3 w-3 opacity-70"})]},p.key)),d.length>0&&u&&e.jsx("button",{onClick:u,className:"text-xs font-medium underline underline-offset-2 hub-ink-muted hover:opacity-90",children:"Clear all"}),h&&e.jsx("span",{className:"text-xs hub-ink-muted",children:h})]})]})]})})}const SRn={closing_soon:{label:"Closing in 7 days",icon:wm,tone:"text-primary"},past_due:{label:"Past close date",icon:Gd,tone:"text-destructive"},overdue_tasks:{label:"Overdue tasks",icon:r5,tone:"text-amber-600 dark:text-amber-400"},stalled:{label:"Stalled 14+ days",icon:RK,tone:"text-muted-foreground"}};function CRn({items:s,active:t,onToggle:n}){const r=s.filter(a=>a.count>0);return r.length===0?null:e.jsxs("div",{className:"-mx-1 flex items-center gap-2 overflow-x-auto px-1 pb-1",children:[e.jsx("span",{className:"shrink-0 text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"Needs attention"}),r.map(({key:a,count:i})=>{const l=SRn[a],o=l.icon,c=t===a;return e.jsxs("button",{onClick:()=>n(a),className:Ot("inline-flex shrink-0 items-center gap-1.5 rounded-full border px-3 py-1.5 text-xs font-medium transition-colors",c?"border-primary bg-primary/10 text-primary":"border-border bg-card text-foreground hover:bg-accent"),children:[e.jsx(o,{className:Ot("h-3.5 w-3.5",!c&&l.tone)}),l.label,e.jsx("span",{className:Ot("ml-0.5 rounded-full px-1.5 text-[10px] font-bold",c?"bg-primary text-primary-foreground":"bg-muted text-muted-foreground"),children:i})]},a)})]})}class ARn extends k.Component{constructor(t){super(t),this.state={hasError:!1,error:null}}static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,n){console.error("DealPipeline error:",t,n)}render(){return this.state.hasError?e.jsx(Xs,{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 VG="deal-pipeline-detail-sheet";function HG(s){return s>=1e6?`$${(s/1e6).toFixed(1)}M`:s>=1e3?`$${(s/1e3).toFixed(0)}K`:`$${Math.round(s).toLocaleString()}`}function ERn(){var Qn;const s=AV(),{data:t,isLoading:n}=_te(),{data:r,isLoading:a,refetch:i}=$Te(),{data:l,isLoading:o}=TIn(),c=Yqt(),d=jIn(),[u,h]=k.useState("board"),[m,p]=k.useState(!1),[g,x]=k.useState(!1),[y,v]=k.useState(null),[_,j]=k.useState(null),[C,A]=k.useState(null),[M,I]=k.useState(null),[P,R]=k.useState(!1),[O,B]=k.useState(null),[U,G]=k.useState(""),[H,Y]=k.useState("all"),[se,ee]=k.useState("all"),[oe,me]=k.useState("all"),[Q,te]=k.useState(null),{data:le}=aVt(),{data:fe}=yLn(),[_e,ve]=k.useState(!1),[he,Se]=k.useState(!1),[Te,Ie]=k.useState(new Set),Ue=k.useRef(!1),[Be,je]=k.useState(null),{data:Ye}=gj(),{isTeamLeader:Ee,teamMembers:Re}=gLn(),ke=k.useMemo(()=>Array.from(Te),[Te]),{data:Fe}=xLn(ke),Oe=k.useMemo(()=>{const En=new Map;return Re.forEach(pr=>En.set(pr.id,{name:pr.name,avatar_url:pr.avatar_url,color:pr.color})),En},[Re]),Ge=k.useCallback(En=>En.owner_user_id&&Oe.get(En.owner_user_id)||null,[Oe]),yt=k.useCallback(En=>{Ie(pr=>{const xn=new Set(pr);return xn.has(En)?xn.delete(En):xn.add(En),xn})},[]);k.useEffect(()=>{!n&&t&&t.length===0&&c.mutate()},[n,t]);const[tt,ut]=Jc(),nt=k.useRef(!1);k.useEffect(()=>{const En=tt.get("deal");if(En&&r&&r.length>0&&!nt.current){const pr=r.find(xn=>xn.id===En);pr&&(nt.current=!0,v(pr),x(!0),tt.delete("deal"),ut(tt,{replace:!0}))}},[r,tt]);const et=k.useMemo(()=>{if(!Fe||!t)return[];const En=new Map(t.map(pr=>[pr.name,pr.id]));return Fe.map(pr=>{const xn=pr._stage_name&&En.get(pr._stage_name)||null;return{...pr,stage_id:xn||pr.stage_id}})},[Fe,t]),at=k.useMemo(()=>[...r||[],...et],[r,et]);k.useEffect(()=>{if(Ue.current||at.length===0)return;Ue.current=!0;const En=sessionStorage.getItem(VG);if(En)try{const pr=JSON.parse(En);if(!pr.open||!pr.dealId)return;const xn=at.find(Ar=>Ar.id===pr.dealId);xn&&(v(xn),x(!0))}catch{sessionStorage.removeItem(VG)}},[at]),k.useEffect(()=>{g&&(y!=null&&y.id)?sessionStorage.setItem(VG,JSON.stringify({dealId:y.id,open:!0})):sessionStorage.removeItem(VG)},[g,y==null?void 0:y.id]);const wt=k.useMemo(()=>{const En={},pr=new Date;return pr.setHours(0,0,0,0),(le||[]).forEach(xn=>{!xn.deal_id||xn.status==="done"||!xn.due_date||ih(xn.due_date){const En=new Set((t||[]).filter(Kt=>Kt.is_won_stage).map(Kt=>Kt.id)),pr=new Set((t||[]).filter(Kt=>Kt.is_lost_stage).map(Kt=>Kt.id)),xn=new Date;xn.setHours(0,0,0,0);const Ar=new Date(xn);Ar.setDate(Ar.getDate()+7);const Zr=new Date(xn);Zr.setDate(Zr.getDate()-14);const dn={closing_soon:new Set,past_due:new Set,overdue_tasks:new Set,stalled:new Set};return at.forEach(Kt=>{if(!(Kt.stage_id&&(En.has(Kt.stage_id)||pr.has(Kt.stage_id)))){if(Kt.target_close_date){const ti=ih(Kt.target_close_date);ti[{key:"closing_soon",count:Ut.closing_soon.size},{key:"past_due",count:Ut.past_due.size},{key:"overdue_tasks",count:Ut.overdue_tasks.size},{key:"stalled",count:Ut.stalled.size}],[Ut]),xs=at.filter(En=>{var lo,Yn,Hr,Ur,Ei,fo;const pr=U.toLowerCase(),xn=rt[En.id]||[],Ar=!pr||En.deal_name.toLowerCase().includes(pr)||((Yn=(lo=En.contact)==null?void 0:lo.first_name)==null?void 0:Yn.toLowerCase().includes(pr))||((Ur=(Hr=En.contact)==null?void 0:Hr.last_name)==null?void 0:Ur.toLowerCase().includes(pr))||((Ei=En.property_address)==null?void 0:Ei.toLowerCase().includes(pr))||((fo=En.city)==null?void 0:fo.toLowerCase().includes(pr))||xn.some(co=>co.toLowerCase().includes(pr)),Zr=H==="all"||En.deal_type===H,dn=se==="all"||xn.includes(se),Kt=En.actual_close_date||En.target_close_date||En.contract_date||En.created_at,Er=Kt?String(Kt).slice(0,4):null,ti=oe==="all"||Er===oe,Ba=!Q||Ut[Q].has(En.id);return Ar&&Zr&&dn&&ti&&Ba}),st=k.useMemo(()=>{const En=new Set;return En.add(String(new Date().getFullYear())),at.forEach(pr=>{const xn=pr.actual_close_date||pr.target_close_date||pr.contract_date||pr.created_at;xn&&En.add(String(xn).slice(0,4))}),Array.from(En).sort((pr,xn)=>Number(xn)-Number(pr))},[at]),dt=k.useMemo(()=>{if(!t)return l||null;const En=new Set(t.filter(Kt=>Kt.is_won_stage).map(Kt=>Kt.id)),pr=new Set(t.filter(Kt=>Kt.is_lost_stage).map(Kt=>Kt.id)),xn=at.filter(Kt=>Kt.stage_id&&!En.has(Kt.stage_id)&&!pr.has(Kt.stage_id)),Ar=at.filter(Kt=>Kt.stage_id&&En.has(Kt.stage_id)),Zr=new Date().getFullYear(),dn=Ar.filter(Kt=>Kt.actual_close_date?new Date(Kt.actual_close_date).getFullYear()===Zr:!0);return{totalDeals:at.length,activeDeals:xn.length,wonDeals:Ar.length,pipelineValue:xn.reduce((Kt,Er)=>Kt+(Er.expected_price||0),0),expectedCommission:xn.reduce((Kt,Er)=>Kt+(Er.expected_commission||0),0),expectedNetToAgent:xn.reduce((Kt,Er)=>Kt+(c2(Er)||0),0),wonValue:Ar.reduce((Kt,Er)=>Kt+(Er.expected_price||0),0),weightedGCI:xn.reduce((Kt,Er)=>Kt+(Er.expected_commission||0)*((Er.probability??50)/100),0),weightedNet:xn.reduce((Kt,Er)=>Kt+(c2(Er)||0)*((Er.probability??50)/100),0),ytdWonDeals:dn.length,ytdWonGCI:dn.reduce((Kt,Er)=>Kt+(Er.expected_commission||0),0),ytdWonNet:dn.reduce((Kt,Er)=>Kt+(c2(Er)||0),0),projectedAnnualNet:dn.reduce((Kt,Er)=>Kt+(c2(Er)||0),0)+xn.reduce((Kt,Er)=>Kt+(c2(Er)||0)*((Er.probability??50)/100),0)}},[at,t,l]),jt=En=>{v(En),x(!0)},gt=En=>{j(En||null),v(null),p(!0)},rs=En=>{v(En),x(!1),p(!0)},Ns=En=>{x(En),En||sessionStorage.removeItem(VG)},us=(En,pr)=>{A(En)},Bs=(En,pr)=>{En.preventDefault(),En.dataTransfer.dropEffect="move",I(pr)},Ts=async(En,pr)=>{if(En.preventDefault(),I(null),!C)return;const xn=r==null?void 0:r.find(dn=>dn.id===C),Ar=t==null?void 0:t.find(dn=>dn.id===pr),Zr=t==null?void 0:t.find(dn=>dn.id===(xn==null?void 0:xn.stage_id));if(!xn||!Ar||xn.stage_id===pr){A(null);return}je({dealId:C,dealName:xn.deal_name,fromStageName:(Zr==null?void 0:Zr.name)||"Unknown",toStageName:Ar.name,toStageId:pr,isWonStage:Ar.is_won_stage,deal:xn}),A(null)},Fn=async()=>{if(!Be)return;const{dealId:En,toStageId:pr,toStageName:xn,isWonStage:Ar,deal:Zr}=Be;if(await d.mutateAsync({dealId:En,stageId:pr,stageName:xn}),ae.success(`Moved to ${xn}`),Ar&&!Zr.scorecard_transaction_id){const dn={...Zr,stage_id:pr};B(dn),R(!0)}},An=k.useCallback(async(En,pr,xn)=>{const Ar=r==null?void 0:r.find(Kt=>Kt.id===En),Zr=t==null?void 0:t.find(Kt=>Kt.id===pr),dn=t==null?void 0:t.find(Kt=>Kt.id===(Ar==null?void 0:Ar.stage_id));!Ar||!Zr||Ar.stage_id===pr||je({dealId:En,dealName:Ar.deal_name,fromStageName:(dn==null?void 0:dn.name)||"Unknown",toStageName:xn,toStageId:pr,isWonStage:Zr.is_won_stage,deal:Ar})},[r,t]),js=En=>xs.filter(pr=>pr.stage_id===En),In=n||a,un=s?"list":u,jr=[{label:"Active Deals",value:(dt==null?void 0:dt.activeDeals)||0,hint:"Deals still in play"},{label:"Weighted GCI",value:HG((dt==null?void 0:dt.weightedGCI)||0),hint:"GCI adjusted by each deal's win probability"},{label:"Weighted Net",value:HG((dt==null?void 0:dt.weightedNet)||0),hint:"Net to agent adjusted by each deal's win probability"},{label:"YTD Closed Net",value:HG((dt==null?void 0:dt.ytdWonNet)||0),subtitle:`${(dt==null?void 0:dt.ytdWonDeals)||0} deals`,hint:"Net commission from deals closed this year"},{label:"Projected Annual",value:HG((dt==null?void 0:dt.projectedAnnualNet)||0),hint:"YTD closed net + weighted active net"}],Ln=[...H!=="all"?[{key:"type",label:`Type: ${H}`,onClear:()=>Y("all")}]:[],...oe!=="all"?[{key:"year",label:`Year: ${oe}`,onClear:()=>me("all")}]:[],...se!=="all"?[{key:"tag",label:`Tag: ${se}`,onClear:()=>ee("all")}]:[],...U?[{key:"search",label:`"${U}"`,onClear:()=>G("")}]:[],...Q?[{key:"attention",label:"Needs attention",onClear:()=>te(null)}]:[]],Sr=()=>{G(""),Y("all"),ee("all"),me("all"),te(null)};return e.jsxs(Xs,{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.jsx(kRn,{summary:`${(dt==null?void 0:dt.activeDeals)||0} active deals • ${HG((dt==null?void 0:dt.weightedNet)||0)} weighted net`,stats:un==="portals"?[]:jr,search:U,onSearchChange:G,onAddDeal:()=>gt(),onRefresh:()=>i(),onTeam:Ye&&!Ee?()=>ve(!0):void 0,showSearch:un!=="portals",activeFilters:Ln,onClearAll:Sr,resultLabel:Ln.length>0?`${xs.length} of ${at.length} deals`:null,viewControls:s?null:e.jsx(Sk,{children:e.jsx("div",{className:"hub-glass flex items-center gap-0.5 rounded-full p-1",children:[{mode:"board",icon:y0,label:"Board",hint:"Kanban board view"},{mode:"list",icon:Sy,label:"List",hint:"Grouped list view"},{mode:"table",icon:hB,label:"Table",hint:"Sortable table view"},{mode:"portals",icon:kn,label:"Portals",hint:"Client portal management"}].map(({mode:En,icon:pr,label:xn,hint:Ar})=>e.jsxs(Lx,{children:[e.jsx(Rx,{asChild:!0,children:e.jsxs("button",{onClick:()=>h(En),className:Ot("inline-flex items-center gap-1.5 rounded-full px-3 py-1.5 text-xs font-medium transition-colors",u===En?"bg-background text-foreground shadow-sm":"opacity-80 hover:opacity-100"),children:[e.jsx(pr,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:xn})]})}),e.jsx(Jg,{children:Ar})]},En))})}),filters:un!=="portals"?e.jsxs(e.Fragment,{children:[e.jsxs(bs,{value:H,onValueChange:Y,children:[e.jsx(ys,{className:"hub-glass h-10 w-[130px] rounded-full border-0 text-sm",children:e.jsx(_s,{placeholder:"All Types"})}),e.jsxs(vs,{children:[e.jsx(We,{value:"all",children:"All Types"}),e.jsx(We,{value:"buyer",children:"Buyer"}),e.jsx(We,{value:"seller",children:"Seller"}),e.jsx(We,{value:"dual",children:"Dual"}),e.jsx(We,{value:"referral",children:"Referral"}),e.jsx(We,{value:"lease",children:"Lease"})]})]}),e.jsxs(bs,{value:oe,onValueChange:me,children:[e.jsx(ys,{className:"hub-glass h-10 w-[110px] rounded-full border-0 text-sm",children:e.jsx(_s,{placeholder:"Year"})}),e.jsxs(vs,{children:[e.jsx(We,{value:"all",children:"All Years"}),st.map(En=>e.jsx(We,{value:En,children:En},En))]})]}),e.jsxs(bs,{value:se,onValueChange:ee,children:[e.jsxs(ys,{className:"hub-glass h-10 w-[150px] rounded-full border-0 text-sm",children:[e.jsx(kg,{className:"mr-1.5 h-3.5 w-3.5 opacity-70"}),e.jsx(_s,{placeholder:"All Tags"})]}),e.jsxs(vs,{className:"max-h-[300px]",children:[e.jsx(We,{value:"all",children:"All Tags"}),Ft.length===0&&e.jsx("div",{className:"px-2 py-1.5 text-xs text-muted-foreground",children:"No tags yet"}),Ft.map(En=>e.jsx(We,{value:En,children:En},En))]})]})]}):null}),un!=="portals"&&e.jsx(CRn,{items:Is,active:Q,onToggle:En=>te(pr=>pr===En?null:En)})]}),e.jsxs("div",{className:"flex-1 min-h-0 flex",children:[Ee&&!s&&Re.length>0&&e.jsx(pLn,{members:Re,enabledMembers:Te,onToggleMember:yt,isOpen:he,onToggleOpen:()=>Se(En=>!En)}),e.jsx("div",{className:"flex-1 min-w-0 min-h-0 p-4 md:p-6 pt-4",children:In?e.jsx("div",{className:"flex gap-4 h-full",children:[1,2,3,4].map(En=>e.jsx("div",{className:"min-w-[280px] max-w-[320px] flex-shrink-0",children:e.jsx(fn,{className:"h-full rounded-xl"})},En))}):un==="board"?e.jsxs(Eo,{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(En=>e.jsx(_Ln,{stage:En,deals:js(En.id),onDealClick:jt,onAddDeal:gt,onDragStart:us,onDragOver:Bs,onDrop:Ts,isDragOver:M===En.id,isWonStage:En.is_won_stage,getOwnerInfo:Ge,tagsByDeal:rt,overdueTasksByDeal:wt},En.id))}),e.jsx(Uq,{orientation:"horizontal"})]}):un==="table"?e.jsx(Eo,{className:"h-full",children:e.jsx(lRn,{deals:xs,stages:t||[],onDealClick:jt,onStageChange:An})}):un==="portals"?e.jsx(oVt,{}):e.jsx(Eo,{className:"h-full",children:e.jsxs("div",{className:"space-y-6",children:[t==null?void 0:t.map(En=>{const pr=js(En.id);return pr.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:En.color}}),e.jsx("h3",{className:"font-semibold",children:En.name}),e.jsxs("span",{className:"text-muted-foreground text-sm",children:["(",pr.length,")"]})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-3",children:pr.map(xn=>e.jsx(sVt,{deal:xn,onClick:()=>jt(xn),stages:t,onStageChange:An,showStagePicker:!0,isWonStage:En.is_won_stage,ownerInfo:Ge(xn),tags:rt[xn.id]||[],overdueTaskCount:wt[xn.id]||0},xn.id))})]},En.id)}),(r==null?void 0:r.length)===0&&e.jsxs("div",{className:"text-center py-16",children:[e.jsx("div",{className:"w-16 h-16 mx-auto mb-4 bg-muted rounded-full flex items-center justify-center",children:e.jsx(y0,{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($,{onClick:()=>gt(),children:[e.jsx(nn,{className:"h-4 w-4 mr-2"}),"Add Your First Deal"]})]}),((r==null?void 0:r.length)||0)>0&&xs.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(Yr,{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($,{variant:"outline",onClick:Sr,children:"Clear Filters"})]})]})})})]})]}),e.jsx(kLn,{open:m,onOpenChange:p,deal:y,defaultStageId:_}),e.jsx(aRn,{deal:y,open:g,onOpenChange:Ns,onEdit:rs,isWonStage:y?(Qn=t==null?void 0:t.find(En=>En.id===y.stage_id))==null?void 0:Qn.is_won_stage:!1,onAddToScorecard:En=>{B(En),R(!0),x(!1)}}),e.jsx(iRn,{open:P,onOpenChange:R,deal:O,onComplete:()=>{i(),B(null)}}),Be&&e.jsx(vRn,{open:!!Be,onOpenChange:En=>{En||je(null)},dealId:Be.dealId,dealName:Be.dealName,fromStageName:Be.fromStageName,toStageName:Be.toStageName,toStageId:Be.toStageId,onConfirm:Fn}),e.jsx(mLn,{open:_e,onOpenChange:ve})]})}function TRn(){return e.jsx(ARn,{children:e.jsx(ERn,{})})}function lVt({open:s,onOpenChange:t,editTask:n,defaultDealId:r,defaultStageId:a}){var G;const i=dRn(),l=uRn(),{data:o}=$Te(),c=ai(),{data:d}=pt({queryKey:["contacts-for-tasks",c],queryFn:async()=>{if(!c)return[];const{data:H,error:Y}=await V.from("innercircle_contacts").select("id, first_name, last_name").eq("owner_user_id",c).order("first_name").limit(500);if(Y)throw Y;return H},enabled:!!c&&s}),[u,h]=k.useState(""),[m,p]=k.useState(""),[g,x]=k.useState("none"),[y,v]=k.useState("none"),[_,j]=k.useState("medium"),[C,A]=k.useState("todo"),[M,I]=k.useState(),[P,R]=k.useState(!1),[O,B]=k.useState(!1);k.useEffect(()=>{n?(h(n.title),p(n.description||""),x(n.deal_id||"none"),v(n.contact_id||"none"),j(n.priority),A(n.status),I(n.due_date?Mp(n.due_date):void 0)):(h(""),p(""),x(r||"none"),v("none"),j("medium"),A("todo"),I(void 0))},[n,s,r]);const U=async()=>{if(!u.trim()){ae.error("Task title is required");return}try{const H={title:u.trim(),description:m.trim()||null,deal_id:g==="none"?null:g,contact_id:y==="none"?null:y,stage_id:a||null,priority:_,status:C,due_date:M?Ys(M,"yyyy-MM-dd"):null};n?(await l.mutateAsync({id:n.id,...H}),ae.success("Task updated")):(await i.mutateAsync(H),ae.success("Task created")),t(!1)}catch{ae.error("Failed to save task")}};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"sm:max-w-[480px]",children:[e.jsx(Vs,{children:e.jsx($s,{children:n?"Edit Task":"New Task"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Title *"}),e.jsx(be,{value:u,onChange:H=>h(H.target.value),placeholder:"e.g., Send inspection report"})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Description"}),e.jsx(Ls,{value:m,onChange:H=>p(H.target.value),placeholder:"Optional details...",rows:2})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Priority"}),e.jsxs(bs,{value:_,onValueChange:H=>j(H),children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"low",children:"🟢 Low"}),e.jsx(We,{value:"medium",children:"🟡 Medium"}),e.jsx(We,{value:"high",children:"🟠 High"}),e.jsx(We,{value:"urgent",children:"🔴 Urgent"})]})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Status"}),e.jsxs(bs,{value:C,onValueChange:H=>A(H),children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"todo",children:"To Do"}),e.jsx(We,{value:"in_progress",children:"In Progress"}),e.jsx(We,{value:"done",children:"Done"})]})]})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Due Date"}),e.jsxs(Xc,{children:[e.jsx(Qc,{asChild:!0,children:e.jsxs($,{variant:"outline",className:Ot("w-full justify-start text-left font-normal",!M&&"text-muted-foreground"),children:[e.jsx(ha,{className:"mr-2 h-4 w-4"}),M?Ys(M,"PPP"):"Pick a date"]})}),e.jsx(Bc,{className:"w-auto p-0",align:"start",children:e.jsx(vb,{mode:"single",selected:M,onSelect:I,initialFocus:!0,className:"p-3 pointer-events-auto"})})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Link to Deal"}),e.jsxs(Xc,{open:P,onOpenChange:R,children:[e.jsx(Qc,{asChild:!0,children:e.jsxs($,{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(Gi,{className:"h-3.5 w-3.5 text-muted-foreground shrink-0"}),g!=="none"?((G=o==null?void 0:o.find(H=>H.id===g))==null?void 0:G.deal_name)||"Select deal":"No Deal"]}),e.jsx(v_,{className:"h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(Bc,{className:"w-[--radix-popover-trigger-width] p-0",align:"start",children:e.jsxs(M_,{children:[e.jsx(P_,{placeholder:"Search deals..."}),e.jsxs(I_,{children:[e.jsx(L_,{children:"No deals found."}),e.jsxs(Nb,{children:[e.jsxs(rv,{value:"no-deal",onSelect:()=>{x("none"),R(!1)},children:[e.jsx(ma,{className:Ot("mr-2 h-4 w-4",g==="none"?"opacity-100":"opacity-0")}),"No Deal"]}),o==null?void 0:o.map(H=>e.jsxs(rv,{value:H.deal_name,onSelect:()=>{x(H.id),R(!1)},children:[e.jsx(ma,{className:Ot("mr-2 h-4 w-4",g===H.id?"opacity-100":"opacity-0")}),H.deal_name]},H.id))]})]})]})})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Link to Contact"}),e.jsxs(Xc,{open:O,onOpenChange:B,children:[e.jsx(Qc,{asChild:!0,children:e.jsxs($,{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(el,{className:"h-3.5 w-3.5 text-muted-foreground shrink-0"}),y!=="none"?(()=>{const H=d==null?void 0:d.find(Y=>Y.id===y);return H?`${H.first_name} ${H.last_name}`:"Select contact"})():"No Contact"]}),e.jsx(v_,{className:"h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(Bc,{className:"w-[--radix-popover-trigger-width] p-0",align:"start",children:e.jsxs(M_,{children:[e.jsx(P_,{placeholder:"Search contacts..."}),e.jsxs(I_,{children:[e.jsx(L_,{children:"No contacts found."}),e.jsxs(Nb,{children:[e.jsxs(rv,{value:"no-contact",onSelect:()=>{v("none"),B(!1)},children:[e.jsx(ma,{className:Ot("mr-2 h-4 w-4",y==="none"?"opacity-100":"opacity-0")}),"No Contact"]}),d==null?void 0:d.map(H=>e.jsxs(rv,{value:`${H.first_name} ${H.last_name}`,onSelect:()=>{v(H.id),B(!1)},children:[e.jsx(ma,{className:Ot("mr-2 h-4 w-4",y===H.id?"opacity-100":"opacity-0")}),H.first_name," ",H.last_name]},H.id))]})]})]})})]})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx($,{onClick:U,disabled:i.isPending||l.isPending,children:n?"Save Changes":"Create Task"})]})]})]})})}const MRn={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 PRn({tasks:s}){const t=UTe(),n=hRn(),r=Jn(),[a,i]=k.useState(null),l=async u=>{const h=u.status==="done"?"todo":"done";try{await t.mutateAsync({id:u.id,status:h})}catch{ae.error("Failed to update task")}},o=async u=>{try{await n.mutateAsync(u),ae.success("Task deleted")}catch{ae.error("Failed to delete task")}};if(s.length===0)return e.jsxs("div",{className:"flex flex-col items-center justify-center py-20 text-center",children:[e.jsx(Gr,{className:"h-12 w-12 text-muted-foreground/30 mb-3"}),e.jsx("p",{className:"text-muted-foreground font-medium",children:"No tasks found"}),e.jsx("p",{className:"text-muted-foreground/60 text-sm",children:"Create a new task to get started"})]});const c=new Map,d=[];return s.forEach(u=>{if(u.deal){const h=c.get(u.deal.id)||{dealName:u.deal.deal_name,tasks:[]};h.tasks.push(u),c.set(u.deal.id,h)}else d.push(u)}),e.jsxs("div",{className:"space-y-4",children:[d.length>0&&e.jsxs("div",{className:"border rounded-lg overflow-hidden",children:[e.jsx("div",{className:"bg-muted/30 px-4 py-2 border-b",children:e.jsx("h3",{className:"font-medium text-sm text-muted-foreground",children:"General Tasks"})}),d.map(u=>e.jsx(rbt,{task:u,onToggle:l,onDelete:o,onEdit:i,onNavigateDeal:h=>r(`/mission-control/pipeline?deal=${h}`)},u.id))]}),Array.from(c.entries()).map(([u,h])=>e.jsxs("div",{className:"border rounded-lg overflow-hidden",children:[e.jsxs("button",{onClick:()=>r(`/mission-control/pipeline?deal=${u}`),className:"w-full bg-muted/30 px-4 py-2 border-b flex items-center gap-2 hover:bg-muted/50 transition-colors text-left",children:[e.jsx(Gi,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("h3",{className:"font-medium text-sm",children:h.dealName}),e.jsxs(qe,{variant:"secondary",className:"ml-auto text-xs",children:[h.tasks.filter(m=>m.status==="done").length,"/",h.tasks.length]}),e.jsx(fi,{className:"h-3.5 w-3.5 text-muted-foreground"})]}),h.tasks.map(m=>e.jsx(rbt,{task:m,onToggle:l,onDelete:o,onEdit:i,onNavigateDeal:p=>r(`/mission-control/pipeline?deal=${p}`)},m.id))]},u)),a&&e.jsx(lVt,{open:!!a,onOpenChange:()=>i(null),editTask:a})]})}function rbt({task:s,onToggle:t,onDelete:n,onEdit:r,onNavigateDeal:a}){const i=s.status==="done",l=!i&&s.due_date&&R5(Mp(s.due_date))&&!m0(Mp(s.due_date)),o=!i&&s.due_date&&m0(Mp(s.due_date)),c=MRn[s.priority];return e.jsxs("div",{className:Ot("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(Gr,{className:"h-5 w-5 text-emerald-500"}):e.jsx(rx,{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:Ot("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(el,{className:"h-2.5 w-2.5"}),s.contact.first_name," ",s.contact.last_name]})]})]}),e.jsxs(qe,{variant:"outline",className:Ot("text-[10px] shrink-0",c.color),children:[c.dot," ",c.label]}),s.due_date&&e.jsxs("span",{className:Ot("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(sa,{className:"h-3 w-3"}),Ys(Mp(s.due_date),"MMM d")]}),e.jsxs("div",{className:"flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity",children:[e.jsx("button",{onClick:()=>r(s),className:"p-1 hover:bg-muted rounded",children:e.jsx(Cp,{className:"h-3.5 w-3.5 text-muted-foreground"})}),e.jsx("button",{onClick:()=>n(s.id),className:"p-1 hover:bg-destructive/10 rounded",children:e.jsx(Un,{className:"h-3.5 w-3.5 text-destructive"})})]})]})}const IRn=[{status:"todo",label:"To Do",icon:rx,color:"border-t-slate-400"},{status:"in_progress",label:"In Progress",icon:mm,color:"border-t-blue-500"},{status:"done",label:"Done",icon:Gr,color:"border-t-emerald-500"}],LRn={urgent:"🔴",high:"🟠",medium:"🟡",low:"🟢"};function RRn({tasks:s}){const t=UTe(),n=k.useMemo(()=>{const i={todo:[],in_progress:[],done:[]};return s.forEach(l=>i[l.status].push(l)),i},[s]),r=(i,l)=>{i.dataTransfer.setData("taskId",l)},a=async(i,l)=>{i.preventDefault();const o=i.dataTransfer.getData("taskId");if(!o)return;const c=s.find(d=>d.id===o);if(!(!c||c.status===l))try{await t.mutateAsync({id:o,status:l})}catch{ae.error("Failed to move task")}};return e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:IRn.map(i=>e.jsxs("div",{className:Ot("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(qe,{variant:"secondary",className:"ml-auto text-xs",children:n[i.status].length})]}),e.jsxs("div",{className:"p-2 space-y-2 min-h-[200px]",children:[n[i.status].map(l=>e.jsx(DRn,{task:l,onDragStart:r},l.id)),n[i.status].length===0&&e.jsx("p",{className:"text-xs text-muted-foreground text-center py-8",children:"Drag tasks here"})]})]},i.status))})}function DRn({task:s,onDragStart:t}){const n=s.status==="done",r=!n&&s.due_date&&R5(Mp(s.due_date))&&!m0(Mp(s.due_date)),a=!n&&s.due_date&&m0(Mp(s.due_date));return e.jsx("div",{draggable:!0,onDragStart:i=>t(i,s.id),className:Ot("bg-background border rounded-lg p-3 cursor-grab active:cursor-grabbing shadow-sm hover:shadow-md transition-shadow",r&&"border-destructive/50"),children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"text-xs mt-0.5",children:LRn[s.priority]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:Ot("text-sm font-medium",n&&"line-through text-muted-foreground"),children:s.title}),e.jsxs("div",{className:"flex items-center gap-2 mt-1.5 flex-wrap",children:[s.deal&&e.jsxs("span",{className:"text-[10px] text-muted-foreground flex items-center gap-0.5",children:[e.jsx(Gi,{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(el,{className:"h-2.5 w-2.5"}),s.contact.first_name," ",s.contact.last_name]})]}),s.due_date&&e.jsxs("div",{className:Ot("text-[10px] mt-1.5 flex items-center gap-1",r&&"text-destructive font-medium",a&&"text-amber-600 font-medium",!r&&!a&&"text-muted-foreground"),children:[e.jsx(sa,{className:"h-2.5 w-2.5"}),r?"Overdue — ":a?"Due today — ":"",Ys(Mp(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 abt={urgent:"🔴",high:"🟠",medium:"🟡",low:"🟢"};function ORn({tasks:s}){const[t,n]=k.useState(new Date),r=UTe(),a=Ih(t),i=eb(t),l=My(a),o=wU(i),c=p7e({start:l,end:o}),d=k.useMemo(()=>{const m=new Map;return s.forEach(p=>{if(!p.due_date)return;const g=p.due_date,x=m.get(g)||[];x.push(p),m.set(g,x)}),m},[s]),u=k.useMemo(()=>s.filter(m=>!m.due_date),[s]),h=async m=>{const p=m.status==="done"?"todo":"done";try{await r.mutateAsync({id:m.id,status:p})}catch{ae.error("Failed to update task")}};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx($,{variant:"ghost",size:"icon",onClick:()=>n(nD(t,1)),children:e.jsx(Ld,{className:"h-4 w-4"})}),e.jsx("h3",{className:"font-semibold",children:Ys(t,"MMMM yyyy")}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>n(Ux(t,1)),children:e.jsx(fi,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"grid grid-cols-7 text-center",children:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"].map(m=>e.jsx("div",{className:"text-xs font-medium text-muted-foreground py-2",children:m},m))}),e.jsx("div",{className:"grid grid-cols-7 border-l border-t",children:c.map(m=>{const p=Ys(m,"yyyy-MM-dd"),g=d.get(p)||[],x=Vq(m,t),y=m0(m);return e.jsxs("div",{className:Ot("border-r border-b min-h-[100px] p-1",!x&&"bg-muted/30",y&&"bg-primary/5"),children:[e.jsx("div",{className:Ot("text-xs font-medium mb-1 text-right px-1",!x&&"text-muted-foreground/40",y&&"text-primary font-bold"),children:Ys(m,"d")}),e.jsxs("div",{className:"space-y-0.5",children:[g.slice(0,3).map(v=>e.jsxs("button",{onClick:()=>h(v),className:Ot("w-full text-left text-[10px] px-1 py-0.5 rounded truncate flex items-center gap-0.5 hover:bg-muted transition-colors",v.status==="done"?"text-muted-foreground line-through":"text-foreground"),children:[v.status==="done"?e.jsx(Gr,{className:"h-2.5 w-2.5 text-emerald-500 shrink-0"}):e.jsx(rx,{className:"h-2.5 w-2.5 shrink-0"}),e.jsxs("span",{className:"truncate",children:[abt[v.priority]," ",v.title]})]},v.id)),g.length>3&&e.jsxs("p",{className:"text-[9px] text-muted-foreground text-center",children:["+",g.length-3," more"]})]})]},p)})}),u.length>0&&e.jsxs("div",{className:"border rounded-lg p-3",children:[e.jsxs("h4",{className:"text-sm font-medium text-muted-foreground mb-2",children:["No Due Date (",u.length,")"]}),e.jsx("div",{className:"space-y-1",children:u.map(m=>e.jsxs("button",{onClick:()=>h(m),className:Ot("w-full text-left text-xs px-2 py-1.5 rounded flex items-center gap-2 hover:bg-muted transition-colors",m.status==="done"&&"opacity-50 line-through"),children:[m.status==="done"?e.jsx(Gr,{className:"h-3.5 w-3.5 text-emerald-500 shrink-0"}):e.jsx(rx,{className:"h-3.5 w-3.5 shrink-0"}),e.jsxs("span",{className:"truncate",children:[abt[m.priority]," ",m.title]}),m.deal&&e.jsxs("span",{className:"text-muted-foreground ml-auto shrink-0",children:["• ",m.deal.deal_name]})]},m.id))})]})]})}const FRn={urgent:"🔴",high:"🟠",medium:"🟡",low:"🟢"};function zRn({open:s,onOpenChange:t,stages:n}){var v;const[r,a]=k.useState(((v=n[0])==null?void 0:v.id)||""),{data:i,isLoading:l}=fRn(r||void 0),o=pRn(),c=gRn(),[d,u]=k.useState(""),[h,m]=k.useState("medium"),[p,g]=k.useState(""),x=async()=>{if(!(!d.trim()||!r))try{await o.mutateAsync({stage_id:r,title:d.trim(),priority:h,default_due_offset_days:p?parseInt(p):null,sort_order:((i==null?void 0:i.length)||0)+1}),u(""),g(""),ae.success("Template added")}catch{ae.error("Failed to add template")}},y=async _=>{try{await c.mutateAsync(_),ae.success("Template deleted")}catch{ae.error("Failed to delete template")}};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"sm:max-w-[560px]",children:[e.jsx(Vs,{children:e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(EK,{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(re,{children:"Pipeline Stage"}),e.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:n.filter(_=>!_.is_won_stage&&!_.is_lost_stage).map(_=>e.jsx("button",{onClick:()=>a(_.id),className:Ot("px-3 py-1.5 rounded-full text-xs font-medium border transition-colors",r===_.id?"border-primary bg-primary/10 text-primary":"border-border hover:bg-muted"),children:_.name},_.id))})]}),e.jsx(Eo,{className:"max-h-[250px]",children:e.jsxs("div",{className:"space-y-1.5",children:[i==null?void 0:i.map((_,j)=>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:FRn[_.priority]}),e.jsx("span",{className:"text-sm flex-1 truncate",children:_.title}),_.default_due_offset_days&&e.jsxs(qe,{variant:"outline",className:"text-[10px]",children:["+",_.default_due_offset_days,"d"]}),e.jsx("button",{onClick:()=>y(_.id),className:"opacity-0 group-hover:opacity-100 p-1 hover:bg-destructive/10 rounded transition-opacity",children:e.jsx(Un,{className:"h-3.5 w-3.5 text-destructive"})})]},_.id)),(i==null?void 0:i.length)===0&&r&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-6",children:"No templates for this stage yet"})]})}),r&&e.jsxs("div",{className:"space-y-3 border-t pt-3",children:[e.jsx(re,{className:"text-xs text-muted-foreground",children:"Add Template Task"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(be,{placeholder:"Task title...",value:d,onChange:_=>u(_.target.value),className:"flex-1",onKeyDown:_=>_.key==="Enter"&&x()}),e.jsxs(bs,{value:h,onValueChange:_=>m(_),children:[e.jsx(ys,{className:"w-[100px]",children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"low",children:"🟢 Low"}),e.jsx(We,{value:"medium",children:"🟡 Med"}),e.jsx(We,{value:"high",children:"🟠 High"}),e.jsx(We,{value:"urgent",children:"🔴 Urgent"})]})]})]}),e.jsxs("div",{className:"flex gap-2 items-end",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx(re,{className:"text-xs",children:"Due offset (days from entering stage)"}),e.jsx(be,{type:"number",placeholder:"e.g., 7",value:p,onChange:_=>g(_.target.value)})]}),e.jsxs($,{onClick:x,disabled:!d.trim()||o.isPending,children:[e.jsx(nn,{className:"h-4 w-4 mr-1"}),"Add"]})]})]})]})})}function BRn(){const{data:s,isLoading:t}=aVt(),{data:n}=_te(),[r,a]=k.useState("list"),[i,l]=k.useState(""),[o,c]=k.useState("active"),[d,u]=k.useState("all"),[h,m]=k.useState("all"),[p,g]=k.useState(!1),[x,y]=k.useState(!1),v=k.useMemo(()=>{if(!s)return[];const C=new Map;return s.forEach(A=>{A.deal&&C.set(A.deal.id,A.deal.deal_name)}),Array.from(C,([A,M])=>({id:A,name:M}))},[s]),_=k.useMemo(()=>s?s.filter(C=>{var O,B,U,G;const A=i.toLowerCase(),M=!A||C.title.toLowerCase().includes(A)||((B=(O=C.deal)==null?void 0:O.deal_name)==null?void 0:B.toLowerCase().includes(A))||`${((U=C.contact)==null?void 0:U.first_name)||""} ${((G=C.contact)==null?void 0:G.last_name)||""}`.toLowerCase().includes(A),I=o==="all"||o==="active"&&C.status!=="done"||o==="todo"&&C.status==="todo"||o==="in_progress"&&C.status==="in_progress"||o==="done"&&C.status==="done"||o==="overdue"&&C.status!=="done"&&C.due_date&&R5(Mp(C.due_date))&&!m0(Mp(C.due_date)),P=d==="all"||C.priority===d,R=h==="all"||h==="no_deal"&&!C.deal_id||C.deal_id===h;return M&&I&&P&&R}):[],[s,i,o,d,h]),j=k.useMemo(()=>{if(!s)return{total:0,overdue:0,dueToday:0,dueThisWeek:0,completed:0};const C=s.filter(A=>A.status!=="done");return{total:C.length,overdue:C.filter(A=>A.due_date&&R5(Mp(A.due_date))&&!m0(Mp(A.due_date))).length,dueToday:C.filter(A=>A.due_date&&m0(Mp(A.due_date))).length,dueThisWeek:C.filter(A=>A.due_date&&nbs(Mp(A.due_date))).length,completed:s.filter(A=>A.status==="done").length}},[s]);return e.jsx(Xs,{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($,{variant:"outline",size:"sm",onClick:()=>y(!0),children:[e.jsx(v2,{className:"h-4 w-4 mr-1"}),"Templates"]}),e.jsxs($,{size:"sm",onClick:()=>g(!0),children:[e.jsx(nn,{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(Sy,{className:"h-3.5 w-3.5"}),"Active"]}),e.jsx("p",{className:"text-xl font-bold mt-1",children:j.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(Gd,{className:"h-3.5 w-3.5"}),"Overdue"]}),e.jsx("p",{className:"text-xl font-bold mt-1 text-destructive",children:j.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(sa,{className:"h-3.5 w-3.5"}),"Due Today"]}),e.jsx("p",{className:"text-xl font-bold mt-1",children:j.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(fd,{className:"h-3.5 w-3.5"}),"This Week"]}),e.jsx("p",{className:"text-xl font-bold mt-1",children:j.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(Gr,{className:"h-3.5 w-3.5"}),"Completed"]}),e.jsx("p",{className:"text-xl font-bold mt-1",children:j.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(Yr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search tasks...",value:i,onChange:C=>l(C.target.value),className:"pl-9"})]}),e.jsxs(bs,{value:d,onValueChange:u,children:[e.jsx(ys,{className:"w-[130px]",children:e.jsx(_s,{placeholder:"Priority"})}),e.jsxs(vs,{children:[e.jsx(We,{value:"all",children:"All Priorities"}),e.jsx(We,{value:"urgent",children:"🔴 Urgent"}),e.jsx(We,{value:"high",children:"🟠 High"}),e.jsx(We,{value:"medium",children:"🟡 Medium"}),e.jsx(We,{value:"low",children:"🟢 Low"})]})]}),e.jsxs(bs,{value:h,onValueChange:m,children:[e.jsx(ys,{className:"w-[160px]",children:e.jsx(_s,{placeholder:"Deal"})}),e.jsxs(vs,{children:[e.jsx(We,{value:"all",children:"All Deals"}),e.jsx(We,{value:"no_deal",children:"No Deal"}),v.map(C=>e.jsx(We,{value:C.id,children:C.name},C.id))]})]}),e.jsxs("div",{className:"flex items-center border rounded-lg p-0.5 ml-auto",children:[e.jsx("button",{onClick:()=>a("list"),className:`p-1.5 rounded-md transition-colors ${r==="list"?"bg-primary text-primary-foreground":"text-muted-foreground hover:text-foreground"}`,children:e.jsx(Sy,{className:"h-4 w-4"})}),e.jsx("button",{onClick:()=>a("kanban"),className:`p-1.5 rounded-md transition-colors ${r==="kanban"?"bg-primary text-primary-foreground":"text-muted-foreground hover:text-foreground"}`,children:e.jsx(M5,{className:"h-4 w-4"})}),e.jsx("button",{onClick:()=>a("calendar"),className:`p-1.5 rounded-md transition-colors ${r==="calendar"?"bg-primary text-primary-foreground":"text-muted-foreground hover:text-foreground"}`,children:e.jsx(fd,{className:"h-4 w-4"})})]})]}),t?e.jsx("div",{className:"flex items-center justify-center py-20",children:e.jsx("div",{className:"animate-spin h-8 w-8 border-2 border-primary border-t-transparent rounded-full"})}):e.jsxs(e.Fragment,{children:[r==="list"&&e.jsx(PRn,{tasks:_}),r==="kanban"&&e.jsx(RRn,{tasks:_}),r==="calendar"&&e.jsx(ORn,{tasks:_})]}),e.jsx(lVt,{open:p,onOpenChange:g}),e.jsx(zRn,{open:x,onOpenChange:y,stages:n||[]})]})})}function $Rn(s){const t=gQe(s);return t?t.toLocaleDateString("en-US",{weekday:"short",month:"short",day:"numeric"}):""}function URn({value:s,size:t=52}){const r=(t-5)/2,a=2*Math.PI*r,i=a-Math.min(100,Math.max(0,s))/100*a;return e.jsxs("div",{className:"relative shrink-0",style:{width:t,height:t},children:[e.jsxs("svg",{width:t,height:t,className:"-rotate-90",children:[e.jsx("circle",{cx:t/2,cy:t/2,r,fill:"none",strokeWidth:5,className:"stroke-muted"}),e.jsx("circle",{cx:t/2,cy:t/2,r,fill:"none",strokeWidth:5,strokeLinecap:"round",strokeDasharray:a,strokeDashoffset:i,className:"stroke-primary transition-all duration-500"})]}),e.jsxs("span",{className:"absolute inset-0 flex items-center justify-center text-[11px] font-bold",children:[Math.round(s),"%"]})]})}function Kae({icon:s,label:t,value:n,tone:r="default",hint:a}){const i={default:"bg-primary/10 text-primary",danger:"bg-destructive/10 text-destructive",warn:"bg-amber-500/10 text-amber-600 dark:text-amber-400",good:"bg-emerald-500/10 text-emerald-600 dark:text-emerald-400"};return e.jsxs("div",{className:"rounded-xl border bg-card p-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:Ot("h-9 w-9 rounded-lg flex items-center justify-center shrink-0",i[r]),children:e.jsx(s,{className:"h-4 w-4"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-2xl font-bold leading-none",children:n}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1 truncate",children:t})]})]}),a&&e.jsx("p",{className:"text-[11px] text-muted-foreground mt-2",children:a})]})}function qRn(){const s=Jn(),{data:t,isLoading:n}=YLn(),r=UTe(),[a,i]=k.useState(""),[l,o]=k.useState(!1),[c,d]=k.useState("all"),u=k.useMemo(()=>{let _=t||[];c==="contract"&&(_=_.filter(C=>!!C.contract_date));const j=a.trim().toLowerCase();return j&&(_=_.filter(C=>{var A,M,I,P;return((A=C.deal_name)==null?void 0:A.toLowerCase().includes(j))||((M=C.property_address)==null?void 0:M.toLowerCase().includes(j))||`${((I=C.contact)==null?void 0:I.first_name)??""} ${((P=C.contact)==null?void 0:P.last_name)??""}`.toLowerCase().includes(j)})),_},[t,a,c]),h=k.useMemo(()=>{const _=[];return(u||[]).forEach(j=>{nK.forEach(C=>{const A=j[C.key],M=TS(A);A&&M!==null&&M<=30&&_.push({id:`${j.id}-${C.key}`,kind:"date",label:C.label,dealId:j.id,dealName:j.deal_name,date:A,days:M})}),j.tasks.filter(C=>C.status!=="done"&&C.due_date).forEach(C=>{const A=TS(C.due_date);A!==null&&A<=30&&_.push({id:C.id,kind:"task",label:C.title,dealId:j.id,dealName:j.deal_name,date:C.due_date,days:A,priority:C.priority})})}),_.sort((j,C)=>j.days-C.days)},[u]),m=k.useMemo(()=>({overdue:h.filter(_=>_.days<0),today:h.filter(_=>_.days===0),week:h.filter(_=>_.days>0&&_.days<=7),later:h.filter(_=>_.days>7)}),[h]),p=k.useMemo(()=>{const _=t||[],j=_.filter(M=>{const I=TS(M.target_close_date);return I!==null&&I>=0&&I<=7}).length,C=_.reduce((M,I)=>M+I.tasks.filter(P=>{const R=TS(P.due_date);return P.status!=="done"&&R!==null&&R<0}).length,0),A=_.reduce((M,I)=>M+(Number(I.expected_price)||0),0);return{active:_.length,closingSoon:j,overdueTasks:C,volume:A}},[t]),g=_=>_.tasks.length===0?0:_.tasks.filter(j=>j.status==="done").length/_.tasks.length*100,x=_=>s(`/mission-control/pipeline?deal=${_}`),y=async _=>{try{await r.mutateAsync({id:_,status:"done"}),ae.success("Task completed")}catch{ae.error("Could not update task")}},v=({title:_,items:j,tone:C})=>{if(j.length===0)return null;const A=C==="danger"?"bg-destructive":C==="warn"?"bg-amber-500":"bg-primary";return e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center gap-2 px-1",children:[e.jsx("span",{className:Ot("h-1.5 w-1.5 rounded-full",A)}),e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:_}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["(",j.length,")"]})]}),j.slice(0,12).map(M=>e.jsxs("div",{className:Ot("group flex items-center gap-3 rounded-lg border px-3 py-2 transition-colors hover:bg-muted/50",C==="danger"&&"border-destructive/30 bg-destructive/5"),children:[M.kind==="task"?e.jsx(Li,{className:"shrink-0",onCheckedChange:()=>y(M.id),"aria-label":`Complete ${M.label}`}):e.jsx(wm,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsxs("button",{type:"button",onClick:()=>x(M.dealId),className:"flex-1 min-w-0 text-left",children:[e.jsx("p",{className:"text-sm font-medium leading-tight truncate",children:M.label}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[M.dealName," · ",$Rn(M.date)]})]}),e.jsx("span",{className:Ot("text-[11px] font-semibold shrink-0 tabular-nums",M.days<0?"text-destructive":M.days<=3?"text-amber-600":"text-muted-foreground"),children:M.days<0?`${Math.abs(M.days)}d late`:M.days===0?"Today":`${M.days}d`})]},M.id))]})};return e.jsxs(Xs,{children:[e.jsxs("div",{className:"p-4 sm:p-6 space-y-6 max-w-[1400px] mx-auto",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold tracking-tight",children:"Transaction Coordinator"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Every deadline, every checklist, one screen. Nothing slips."})]}),e.jsxs($,{onClick:()=>o(!0),className:"gap-2 shrink-0",children:[e.jsx(wg,{className:"h-4 w-4"}),"Playbooks"]})]}),e.jsxs("div",{className:"grid grid-cols-2 lg:grid-cols-4 gap-3",children:[e.jsx(Kae,{icon:lv,label:"Active transactions",value:p.active}),e.jsx(Kae,{icon:iu,label:"Closing within 7 days",value:p.closingSoon,tone:"warn"}),e.jsx(Kae,{icon:Gd,label:"Overdue tasks",value:p.overdueTasks,tone:p.overdueTasks>0?"danger":"good"}),e.jsx(Kae,{icon:mc,label:"Pipeline volume",value:p.volume>=1e6?`$${(p.volume/1e6).toFixed(1)}M`:`$${Math.round(p.volume/1e3)}K`,tone:"good"})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-2",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Yr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search transactions, addresses, or clients...",value:a,onChange:_=>i(_.target.value),className:"pl-9"})]}),e.jsxs("div",{className:"flex gap-1 rounded-lg border p-1 bg-card",children:[e.jsx($,{size:"sm",variant:c==="all"?"default":"ghost",onClick:()=>d("all"),className:"h-8",children:"All active"}),e.jsx($,{size:"sm",variant:c==="contract"?"default":"ghost",onClick:()=>d("contract"),className:"h-8",children:"Under contract"})]})]}),n?e.jsx("div",{className:"flex justify-center py-20",children:e.jsx(Jt,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):e.jsxs("div",{className:"grid lg:grid-cols-5 gap-6",children:[e.jsx("div",{className:"lg:col-span-2 space-y-4",children:e.jsxs("div",{className:"rounded-xl border bg-card p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[e.jsx(wm,{className:"h-4 w-4 text-primary"}),e.jsx("h2",{className:"text-sm font-semibold",children:"Deadline Radar"}),e.jsx(qe,{variant:"secondary",className:"text-[10px] ml-auto",children:"next 30 days"})]}),h.length===0?e.jsxs("div",{className:"text-center py-10",children:[e.jsx(Gr,{className:"h-8 w-8 text-emerald-500 mx-auto mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Nothing due in the next 30 days."})]}):e.jsxs("div",{className:"space-y-4",children:[e.jsx(v,{title:"Overdue",items:m.overdue,tone:"danger"}),e.jsx(v,{title:"Today",items:m.today,tone:"warn"}),e.jsx(v,{title:"This week",items:m.week,tone:"warn"}),e.jsx(v,{title:"Coming up",items:m.later,tone:"default"})]})]})}),e.jsx("div",{className:"lg:col-span-3 space-y-3",children:u.length===0?e.jsxs("div",{className:"rounded-xl border border-dashed p-12 text-center",children:[e.jsx(ua,{className:"h-8 w-8 text-muted-foreground mx-auto mb-3"}),e.jsx("p",{className:"font-medium",children:"No active transactions"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Deals in progress will appear here with their full deadline chain."}),e.jsx($,{variant:"outline",className:"mt-4",onClick:()=>s("/mission-control/pipeline"),children:"Go to Deal Pipeline"})]}):u.map(_=>{const j=g(_),C=TS(_.target_close_date),A=_.tasks.filter(P=>P.status!=="done"),M=A.filter(P=>{const R=TS(P.due_date);return R!==null&&R<0}),I=A.filter(P=>P.due_date).sort((P,R)=>(TS(P.due_date)??0)-(TS(R.due_date)??0))[0];return e.jsx("button",{type:"button",onClick:()=>x(_.id),className:"w-full text-left rounded-xl border bg-card p-4 hover:border-primary/40 hover:shadow-sm transition-all group",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx(URn,{value:j}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-semibold truncate group-hover:text-primary transition-colors",children:_.deal_name}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[_.property_address||"Address TBD",_.contact&&` · ${_.contact.first_name} ${_.contact.last_name}`]})]}),e.jsx(fi,{className:"h-4 w-4 text-muted-foreground shrink-0 mt-0.5"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 mt-2",children:[_.stage&&e.jsx("span",{className:"text-[10px] px-2 py-0.5 rounded-full font-medium",style:{backgroundColor:`${_.stage.color}1f`,color:_.stage.color},children:_.stage.name}),e.jsx(qe,{variant:"outline",className:"text-[10px] capitalize",children:_.deal_type}),C!==null&&e.jsx(qe,{variant:"secondary",className:Ot("text-[10px]",C<0&&"bg-destructive/10 text-destructive",C>=0&&C<=7&&"bg-amber-500/10 text-amber-700 dark:text-amber-400"),children:C<0?`Closing ${Math.abs(C)}d overdue`:`Closes in ${C}d`}),M.length>0&&e.jsxs(qe,{className:"text-[10px] bg-destructive/10 text-destructive hover:bg-destructive/10",children:[M.length," overdue"]})]}),e.jsxs("div",{className:"mt-3",children:[e.jsx(ho,{value:j,className:"h-1.5"}),e.jsxs("div",{className:"flex items-center justify-between mt-1.5 gap-2",children:[e.jsxs("p",{className:"text-[11px] text-muted-foreground",children:[_.tasks.filter(P=>P.status==="done").length," of"," ",_.tasks.length," steps complete"]}),I&&e.jsxs("p",{className:"text-[11px] text-muted-foreground truncate max-w-[55%]",children:["Next: ",I.title]})]})]}),_.tasks.length===0&&e.jsx("p",{className:"text-[11px] text-muted-foreground mt-2 italic",children:"No checklist yet — open the deal and apply a playbook."})]})]})},_.id)})})]})]}),e.jsx(rVt,{open:l,onOpenChange:o})]})}function cVt(){const s=ai();return pt({queryKey:["portal-referrals",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await V.from("portal_referrals").select("*, client_portals!inner(slug, client_name, deal_id)").eq("owner_user_id",s).order("created_at",{ascending:!1});if(n)throw n;return t||[]},enabled:!!s})}function VRn(){const s=ls();return Nt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await V.from("portal_referrals").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["portal-referrals"]})}})}function HRn(){const s=ls();return Nt({mutationFn:async t=>{const{error:n}=await V.from("portal_referrals").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["portal-referrals"]})}})}const GRn=s=>new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",month:"short",day:"numeric",year:"numeric"}).format(new Date(s)),VDe=[{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"}],WRn={buying:"Buying",selling:"Selling",both:"Buying & Selling",unsure:"Not sure yet"};function dVt(){const{data:s=[],isLoading:t}=cVt(),n=VRn(),r=HRn(),[a,i]=k.useState("all"),[l,o]=k.useState({}),c=k.useMemo(()=>a==="all"?s:s.filter(p=>p.status===a),[s,a]),d=k.useMemo(()=>({total:s.length,new:s.filter(p=>p.status==="new").length,converted:s.filter(p=>p.status==="converted").length}),[s]),u=(p,g)=>{n.mutate({id:p.id,status:g}),ae.success("Status updated")},h=p=>{const g=l[p.id];n.mutate({id:p.id,agent_notes:g}),o(x=>{const{[p.id]:y,...v}=x;return v}),ae.success("Notes saved")},m=async p=>{await io(`Delete referral for ${p.friend_name}?`)&&r.mutate(p.id)};return e.jsxs("div",{className:"container max-w-5xl py-6 px-4",children:[e.jsx(Sc,{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(Zo,{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"},...VDe.map(p=>({v:p.value,l:p.label}))].map(p=>e.jsx("button",{onClick:()=>i(p.v),className:`px-3 py-1.5 rounded-full text-xs font-medium border transition-colors ${a===p.v?"bg-primary text-primary-foreground border-primary":"bg-background text-muted-foreground border-input hover:border-primary/50"}`,children:p.l},p.v))}),t?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(Jt,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):c.length===0?e.jsx(we,{children:e.jsxs(De,{className:"py-12 text-center",children:[e.jsx(Zo,{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(p=>{var v,_;const g=VDe.find(j=>j.value===p.status),x=(v=p.client_portals)==null?void 0:v.slug,y=p.referrer_name||((_=p.client_portals)==null?void 0:_.client_name)||"Anonymous client";return e.jsxs(we,{children:[e.jsx(Vt,{className:"pb-3",children:e.jsxs("div",{className:"flex items-start justify-between flex-wrap gap-2",children:[e.jsxs("div",{children:[e.jsx(Yt,{className:"text-lg",children:p.friend_name}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1 flex items-center gap-1.5",children:[e.jsx(ha,{className:"h-3 w-3"}),"Referred by ",e.jsx("span",{className:"font-medium text-foreground",children:y})," ·"," ",GRn(p.created_at)]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(qe,{variant:"outline",className:g==null?void 0:g.className,children:(g==null?void 0:g.label)||p.status}),e.jsxs(bs,{value:p.status,onValueChange:j=>u(p,j),children:[e.jsx(ys,{className:"h-8 w-[130px] text-xs",children:e.jsx(_s,{})}),e.jsx(vs,{children:VDe.map(j=>e.jsx(We,{value:j.value,className:"text-xs",children:j.label},j.value))})]})]})]})}),e.jsxs(De,{className:"space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[p.friend_interest&&e.jsx(qe,{variant:"secondary",className:"text-xs",children:WRn[p.friend_interest]||p.friend_interest}),p.friend_email&&e.jsxs("a",{href:`mailto:${p.friend_email}`,className:"inline-flex items-center gap-1 text-xs text-primary hover:underline",children:[e.jsx(pn,{className:"h-3 w-3"}),p.friend_email]}),p.friend_phone&&e.jsxs(e.Fragment,{children:[e.jsxs("a",{href:`tel:${p.friend_phone}`,className:"inline-flex items-center gap-1 text-xs text-primary hover:underline",children:[e.jsx(ka,{className:"h-3 w-3"}),p.friend_phone]}),e.jsxs("a",{href:`sms:${p.friend_phone}`,className:"inline-flex items-center gap-1 text-xs text-primary hover:underline",children:[e.jsx(Vu,{className:"h-3 w-3"}),"Text"]})]})]}),p.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:['"',p.friend_message,'"']})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] uppercase tracking-wide text-muted-foreground mb-1",children:"Your notes"}),l[p.id]!==void 0?e.jsxs("div",{className:"space-y-2",children:[e.jsx(Ls,{value:l[p.id],onChange:j=>o(C=>({...C,[p.id]:j.target.value})),rows:3,className:"text-sm"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{size:"sm",onClick:()=>h(p),children:"Save"}),e.jsx($,{size:"sm",variant:"ghost",onClick:()=>o(j=>{const{[p.id]:C,...A}=j;return A}),children:"Cancel"})]})]}):e.jsx("button",{onClick:()=>o(j=>({...j,[p.id]:p.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:p.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:[x&&e.jsxs("a",{href:`/portal/${x}`,target:"_blank",rel:"noopener noreferrer",className:"text-xs text-muted-foreground hover:text-primary inline-flex items-center gap-1",children:[e.jsx(Ir,{className:"h-3 w-3"}),"View source portal"]}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>m(p),className:"text-destructive hover:text-destructive ml-auto h-8",children:e.jsx(Un,{className:"h-3.5 w-3.5"})})]})]})]},p.id)})})]})}function uVt({vendor:s,onEdit:t,onDelete:n,onToggleVisible:r,isVisible:a,showOwnerBadge:i,clickCount:l}){var c;const o=((c=Zq.find(d=>d.value===s.category))==null?void 0:c.label)||s.category;return e.jsxs(we,{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(fu,{className:"w-3.5 h-3.5 text-amber-600","aria-label":"Required"}),s.is_featured&&e.jsx(ri,{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(qe,{variant:"secondary",className:"text-[10px]",children:o}),i==="brokerage"&&e.jsx(qe,{variant:"outline",className:"text-[10px]",children:"Brokerage"}),i==="agent"&&e.jsx(qe,{variant:"outline",className:"text-[10px]",children:"Personal"}),!s.is_active&&e.jsx(qe,{variant:"destructive",className:"text-[10px]",children:"Inactive"}),typeof l=="number"&&l>0&&e.jsxs(qe,{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(ka,{className:"w-3 h-3"}),s.phone]}),s.email&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(pn,{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(kc,{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(ha,{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(Si,{className:"w-3 h-3"}),e.jsx("span",{className:"truncate",children:s.address})]})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-2 border-t",children:[r&&e.jsxs($,{size:"sm",variant:a?"default":"outline",onClick:()=>r(!a),disabled:s.is_required&&!a,className:"flex-1",children:[a?e.jsx(ba,{className:"w-3.5 h-3.5 mr-1.5"}):e.jsx(x0,{className:"w-3.5 h-3.5 mr-1.5"}),a?"Showing in portals":"Hidden"]}),t&&e.jsx($,{size:"sm",variant:"ghost",onClick:t,children:e.jsx(Cp,{className:"w-3.5 h-3.5"})}),n&&e.jsx($,{size:"sm",variant:"ghost",onClick:n,className:"text-destructive",children:e.jsx(Un,{className:"w-3.5 h-3.5"})})]})]})}function hVt({open:s,onOpenChange:t,vendor:n,ownerType:r,brokerageId:a,agentUserId:i,showBrokerageOnlyFields:l}){const o=N4s(),[c,d]=k.useState({}),[u,h]=k.useState(!1),m=k.useRef(null),p=async y=>{if(!y.type.startsWith("image/")){ae.error("Please select an image");return}if(y.size>5*1024*1024){ae.error("Image must be under 5MB");return}h(!0);try{const v=y.name.split(".").pop()||"png",_=`${r}/${a||i||"misc"}/${Date.now()}.${v}`,{error:j}=await V.storage.from("vendor-logos").upload(_,y,{upsert:!0,contentType:y.type});if(j)throw j;const{data:C}=V.storage.from("vendor-logos").getPublicUrl(_);d(A=>({...A,logo_url:C.publicUrl})),ae.success("Logo uploaded")}catch(v){ae.error(v.message||"Upload failed")}finally{h(!1)}};k.useEffect(()=>{s&&d(n||{owner_type:r,owner_brokerage_id:r==="brokerage"&&a||null,owner_user_id:r==="agent"&&i||null,category:"other",action_type:"call",is_active:!0,is_featured:!1,is_required:!1})},[s,n,r,a,i]);const g=(y,v)=>d(_=>({..._,[y]:v})),x=async()=>{var y;if(!((y=c.name)!=null&&y.trim())){ae.error("Name is required");return}try{await o.mutateAsync(c),ae.success(n?"Vendor updated":"Vendor added"),t(!1)}catch(v){ae.error(v.message||"Failed to save vendor")}};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Vs,{children:e.jsx($s,{children:n?"Edit Vendor":"Add Vendor"})}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(re,{children:"Contact Name *"}),e.jsx(be,{value:c.name||"",onChange:y=>g("name",y.target.value),placeholder:"Bob Smith"})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Company"}),e.jsx(be,{value:c.company||"",onChange:y=>g("company",y.target.value),placeholder:"Smith Inspections"})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Category"}),e.jsxs(bs,{value:c.category,onValueChange:y=>g("category",y),children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsx(vs,{children:Zq.map(y=>e.jsx(We,{value:y.value,children:y.label},y.value))})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Phone"}),e.jsx(be,{value:c.phone||"",onChange:y=>g("phone",y.target.value),placeholder:"(555) 123-4567"})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Email"}),e.jsx(be,{type:"email",value:c.email||"",onChange:y=>g("email",y.target.value),placeholder:"bob@smithinsp.com"})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Website"}),e.jsx(be,{value:c.website||"",onChange:y=>g("website",y.target.value),placeholder:"https://..."})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Logo"}),e.jsx("input",{ref:m,type:"file",accept:"image/*",className:"hidden",onChange:y=>{var _;const v=(_=y.target.files)==null?void 0:_[0];v&&p(v),y.target.value=""}}),e.jsxs("div",{className:"flex items-center gap-3 mt-1",children:[c.logo_url?e.jsxs("div",{className:"relative",children:[e.jsx("img",{src:c.logo_url,alt:"Vendor logo",className:"h-14 w-14 rounded-md object-cover border"}),e.jsx("button",{type:"button",onClick:()=>g("logo_url",""),className:"absolute -top-2 -right-2 bg-background border rounded-full p-0.5 shadow","aria-label":"Remove logo",children:e.jsx(mr,{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(gi,{className:"h-5 w-5"})}),e.jsxs($,{type:"button",variant:"outline",size:"sm",onClick:()=>{var y;return(y=m.current)==null?void 0:y.click()},disabled:u,children:[u?e.jsx(Jt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(gi,{className:"h-4 w-4 mr-2"}),c.logo_url?"Replace":"Upload Logo"]})]})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(re,{children:"Address"}),e.jsx(be,{value:c.address||"",onChange:y=>g("address",y.target.value)})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(re,{children:"Description"}),e.jsx(Ls,{rows:3,value:c.description||"",onChange:y=>g("description",y.target.value),placeholder:"Why your clients should use this vendor..."})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Primary Action"}),e.jsxs(bs,{value:c.action_type,onValueChange:y=>g("action_type",y),children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsx(vs,{children:_4s.map(y=>e.jsx(We,{value:y.value,children:y.label},y.value))})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Booking URL (Calendly etc.)"}),e.jsx(be,{value:c.booking_url||"",onChange:y=>g("booking_url",y.target.value),placeholder:"https://calendly.com/..."})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(re,{children:"Compliance Disclosure (optional)"}),e.jsx(Ls,{rows:2,value:c.disclosure_text||"",onChange:y=>g("disclosure_text",y.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(re,{className:"font-medium",children:"Active"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Show this vendor in client portals"})]}),e.jsx(On,{checked:!!c.is_active,onCheckedChange:y=>g("is_active",y)})]}),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(re,{className:"font-medium",children:"Featured"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Highlight in agent library"})]}),e.jsx(On,{checked:!!c.is_featured,onCheckedChange:y=>g("is_featured",y)})]}),e.jsxs("div",{className:"flex items-center justify-between border rounded-lg p-3",children:[e.jsxs("div",{children:[e.jsx(re,{className:"font-medium",children:"Required"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Agents cannot hide"})]}),e.jsx(On,{checked:!!c.is_required,onCheckedChange:y=>g("is_required",y)})]})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx($,{onClick:x,disabled:o.isPending,children:o.isPending?"Saving...":"Save Vendor"})]})]})})}function mVt({embedded:s=!1}={}){const t=ai(),{brokerageId:n}=ks(),{data:r,isLoading:a}=j4s(),{data:i={}}=tMt("agent",t),l=JTt(),o=k4s(),[c,d]=k.useState(null),[u,h]=k.useState(!1),[m,p]=k.useState(""),[g,x]=k.useState("all"),y=(r==null?void 0:r.vendors)||[],v=(r==null?void 0:r.selections)||[],_=k.useMemo(()=>{const O=new Map;return v.forEach(B=>O.set(B.vendor_id,B.is_visible)),O},[v]),j=k.useMemo(()=>y.filter(O=>!(g!=="all"&&O.category!==g||m&&!`${O.name} ${O.company||""}`.toLowerCase().includes(m.toLowerCase()))),[y,m,g]),C=j.filter(O=>O.owner_type==="agent"),A=j.filter(O=>O.owner_type==="brokerage"),M=async O=>{if(await io("Delete this vendor?"))try{await l.mutateAsync(O),ae.success("Vendor deleted")}catch(B){ae.error(B.message)}},I=async(O,B)=>{try{await o.mutateAsync({vendorId:O,isVisible:B})}catch(U){ae.error(U.message)}},P=O=>O.is_required?!0:_.get(O.id)??O.owner_type==="agent",R=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(zx,{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($,{onClick:()=>{d(null),h(!0)},children:[e.jsx(nn,{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(Yr,{className:"w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground"}),e.jsx(be,{className:"pl-9",placeholder:"Search vendors...",value:m,onChange:O=>p(O.target.value)})]}),e.jsxs("select",{value:g,onChange:O=>x(O.target.value),className:"border rounded-md px-3 py-2 text-sm bg-background",children:[e.jsx("option",{value:"all",children:"All categories"}),Zq.map(O=>e.jsx("option",{value:O.value,children:O.label},O.value))]})]}),a?e.jsx("div",{className:"text-center text-muted-foreground py-12",children:"Loading vendors..."}):e.jsxs(ya,{defaultValue:n?"all":"personal",children:[e.jsxs(va,{children:[e.jsxs(is,{value:"all",children:["All (",j.length,")"]}),n&&e.jsxs(is,{value:"brokerage",children:["From Brokerage (",A.length,")"]}),e.jsxs(is,{value:"personal",children:["My Personal (",C.length,")"]})]}),e.jsx(cs,{value:"all",className:"mt-4",children:e.jsx(HDe,{vendors:j,isVisibleInPortals:P,onToggle:I,onEdit:O=>{d(O),h(!0)},onDelete:M,userId:t,clicks:i})}),n&&e.jsx(cs,{value:"brokerage",className:"mt-4",children:A.length===0?e.jsx(ibt,{icon:e.jsx(kn,{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(HDe,{vendors:A,isVisibleInPortals:P,onToggle:I,userId:t,clicks:i})}),e.jsx(cs,{value:"personal",className:"mt-4",children:C.length===0?e.jsx(ibt,{icon:e.jsx(zx,{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($,{onClick:()=>{d(null),h(!0)},children:[e.jsx(nn,{className:"w-4 h-4 mr-2"})," Add Your First Vendor"]})}):e.jsx(HDe,{vendors:C,isVisibleInPortals:P,onToggle:I,onEdit:O=>{d(O),h(!0)},onDelete:M,userId:t,clicks:i})})]}),e.jsx(hVt,{open:u,onOpenChange:h,vendor:c,ownerType:"agent",agentUserId:t})]});return s?R:e.jsx(Xs,{children:R})}function HDe({vendors:s,isVisibleInPortals:t,onToggle:n,onEdit:r,onDelete:a,userId:i,clicks:l}){return e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:s.map(o=>e.jsx(uVt,{vendor:o,isVisible:t(o),onToggleVisible:c=>n(o.id,c),onEdit:o.owner_type==="agent"&&o.owner_user_id===i?()=>r==null?void 0:r(o):void 0,onDelete:o.owner_type==="agent"&&o.owner_user_id===i?()=>a==null?void 0:a(o.id):void 0,showOwnerBadge:o.owner_type,clickCount:l[o.id]},o.id))})}function ibt({icon:s,title:t,desc:n,action:r}){return e.jsxs("div",{className:"text-center py-16 border-2 border-dashed rounded-xl",children:[e.jsx("div",{className:"text-muted-foreground inline-block mb-3",children:s}),e.jsx("h3",{className:"font-semibold",children:t}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1 mb-4 max-w-md mx-auto",children:n}),r]})}function KRn(){const{brokerageId:s,isBrokerageManager:t,isAdmin:n,loading:r}=ks(),{data:a=[],isLoading:i}=w4s(s),{data:l={}}=tMt("brokerage",s),o=JTt(),[c,d]=k.useState(null),[u,h]=k.useState(!1),[m,p]=k.useState(""),[g,x]=k.useState("all");if(r)return e.jsx(Xs,{children:e.jsx("div",{className:"p-8",children:"Loading..."})});if(!t&&!n)return e.jsx(Xs,{children:e.jsx("div",{className:"p-8 text-center",children:e.jsx("h2",{className:"text-xl font-semibold",children:"Brokerage managers only"})})});const y=a.filter(_=>!(g!=="all"&&_.category!==g||m&&!`${_.name} ${_.company||""}`.toLowerCase().includes(m.toLowerCase()))),v=async _=>{if(await io("Delete this vendor? This will remove it from all agent libraries."))try{await o.mutateAsync(_),ae.success("Vendor deleted")}catch(j){ae.error(j.message)}};return e.jsx(Xs,{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(Gi,{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($,{onClick:()=>{d(null),h(!0)},children:[e.jsx(nn,{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(Yr,{className:"w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground"}),e.jsx(be,{className:"pl-9",placeholder:"Search vendors...",value:m,onChange:_=>p(_.target.value)})]}),e.jsxs("select",{value:g,onChange:_=>x(_.target.value),className:"border rounded-md px-3 py-2 text-sm bg-background",children:[e.jsx("option",{value:"all",children:"All categories"}),Zq.map(_=>e.jsx("option",{value:_.value,children:_.label},_.value))]})]}),i?e.jsx("div",{className:"text-center text-muted-foreground py-12",children:"Loading vendors..."}):y.length===0?e.jsxs("div",{className:"text-center py-16 border-2 border-dashed rounded-xl",children:[e.jsx(Gi,{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($,{onClick:()=>{d(null),h(!0)},children:[e.jsx(nn,{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:y.map(_=>e.jsx(uVt,{vendor:_,onEdit:()=>{d(_),h(!0)},onDelete:()=>v(_.id),clickCount:l[_.id]},_.id))}),e.jsx(hVt,{open:u,onOpenChange:h,vendor:c,ownerType:"brokerage",brokerageId:s,showBrokerageOnlyFields:!0})]})})}const YRn=[{value:"overview",label:"Portals",icon:y0},{value:"vendors",label:"Vendors",icon:E5},{value:"referrals",label:"Referrals",icon:Zo},{value:"branding",label:"Branding",icon:gd},{value:"questions",label:"Onboarding",icon:op}];function ZRn(){const[s,t]=Jc(),n=s.get("tab")||"overview",[r,a]=k.useState(n),[i,l]=k.useState(!1),[o,c]=k.useState(!1);return k.useEffect(()=>{t(d=>{const u=new URLSearchParams(d);return u.set("tab",r),u},{replace:!0})},[r,t]),e.jsxs(Xs,{children:[e.jsx(Sc,{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(kn,{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(uY,{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($,{asChild:!0,variant:"outline",size:"sm",className:"shrink-0",children:e.jsx(nr,{to:"/mission-control/pipeline",children:"Open Deal Pipeline"})})]})}),e.jsxs(ya,{value:r,onValueChange:a,className:"w-full",children:[e.jsx(va,{className:"w-full justify-start overflow-x-auto h-auto flex-wrap",children:YRn.map(d=>e.jsxs(is,{value:d.value,className:"gap-2",children:[e.jsx(d.icon,{className:"w-4 h-4"}),d.label]},d.value))}),e.jsx(cs,{value:"overview",className:"mt-6",children:e.jsx(oVt,{})}),e.jsx(cs,{value:"vendors",className:"mt-6",children:e.jsx(XRn,{})}),e.jsx(cs,{value:"referrals",className:"mt-6",children:e.jsx(QRn,{})}),e.jsx(cs,{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(gd,{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($,{onClick:()=>l(!0),children:[e.jsx(Yc,{className:"w-4 h-4 mr-2"}),"Edit Branding Defaults"]})]})]})})}),e.jsx(cs,{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(op,{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($,{onClick:()=>c(!0),children:[e.jsx(Yc,{className:"w-4 h-4 mr-2"}),"Manage Questions"]})]})]})})})]})]}),e.jsx(iVt,{open:i,onOpenChange:l}),e.jsx(nVt,{open:o,onOpenChange:c})]})}function XRn(){return e.jsx(mVt,{embedded:!0})}function QRn(){return e.jsx(dVt,{})}const f9=s=>new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",month:"short",day:"numeric",year:"numeric"}).format(new Date(s));function JRn(s){return pt({queryKey:["client-portal-by-id",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await V.from("client_portals").select("*").eq("id",s).maybeSingle();if(n)throw n;if(!t)return{portal:null,deal:null};const{data:r,error:a}=await V.from("deal_pipeline").select("deal_name, contact_id").eq("id",t.deal_id).maybeSingle();if(a)throw a;let i=null;if(r!=null&&r.contact_id){const{data:l,error:o}=await V.from("innercircle_contacts").select("first_name, last_name, email, phone").eq("id",r.contact_id).maybeSingle();if(o)throw o;i=l}return{portal:t,deal:r?{deal_name:r.deal_name,contact_id:r.contact_id,contact:i}:null}},enabled:!!s})}function eDn(){const{portalId:s}=oo(),t=Jn(),n=ai(),{data:r,isLoading:a}=JRn(s),{data:i=[]}=U5n(s),{data:l=[]}=cVt(),o=EV(),c=Q7t(),d=J7t(),u=e9t(),[h,m]=k.useState(!1),[p,g]=k.useState(!1),[x,y]=k.useState(!1),[v,_]=k.useState(!1),j=(r==null?void 0:r.portal)??null,C=(r==null?void 0:r.deal)??null,A=k.useMemo(()=>j?l.filter(se=>se.portal_id===j.id):[],[l,j==null?void 0:j.id]);if(a)return e.jsx(Xs,{children:e.jsx("div",{className:"flex items-center justify-center py-24",children:e.jsx(Jt,{className:"h-6 w-6 animate-spin text-muted-foreground"})})});if(!j)return e.jsx(Xs,{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($,{asChild:!0,variant:"outline",children:e.jsxs(nr,{to:"/mission-control/client-portals",children:[e.jsx(Ia,{className:"w-4 h-4 mr-2"}),"Back to Portals"]})})]})});const M=B5(j.slug),I=(C==null?void 0:C.deal_name)||"Untitled deal",P=C==null?void 0:C.contact,R=P?`${P.first_name||""} ${P.last_name||""}`.trim():"",O=!!j.archived_at,B=()=>{navigator.clipboard.writeText(M),ae.success("Portal link copied!")},U=async se=>{try{await o.mutateAsync({id:j.id,is_enabled:se}),ae.success(se?"Portal enabled":"Portal disabled")}catch{ae.error("Failed to update")}},G=async()=>{try{await c.mutateAsync(j.id),ae.success("Portal archived")}catch{ae.error("Failed to archive")}},H=async()=>{try{await d.mutateAsync(j.id),ae.success("Portal restored")}catch{ae.error("Failed to restore")}},Y=async()=>{try{await u.mutateAsync({id:j.id,dealId:j.deal_id}),ae.success("Portal deleted"),t("/mission-control/client-portals")}catch{ae.error("Failed to delete")}};return e.jsxs(Xs,{children:[e.jsx(Sc,{children:e.jsxs("title",{children:[I," — 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($,{asChild:!0,variant:"ghost",size:"sm",className:"-ml-2 text-muted-foreground",children:e.jsxs(nr,{to:"/mission-control/client-portals?tab=overview",children:[e.jsx(Ia,{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(kn,{className:"w-5 h-5 text-primary"}),e.jsx("h1",{className:"text-2xl font-bold truncate",children:I}),e.jsx(qe,{variant:"outline",className:O?"bg-muted text-muted-foreground":j.is_enabled?"bg-emerald-500/10 text-emerald-700 border-emerald-200":"bg-muted text-muted-foreground",children:O?"Archived":j.is_enabled?"Active":"Disabled"}),e.jsx(qe,{variant:"outline",className:"capitalize text-xs",children:j.visibility})]}),e.jsxs("p",{className:"text-sm text-muted-foreground flex items-center gap-2 flex-wrap",children:[e.jsx(el,{className:"w-3.5 h-3.5"}),j.client_name||R||"No client name set",(P==null?void 0:P.email)&&e.jsxs(e.Fragment,{children:["· ",e.jsx(pn,{className:"w-3.5 h-3.5"}),e.jsx("span",{className:"truncate",children:P.email})]}),(P==null?void 0:P.phone)&&e.jsxs(e.Fragment,{children:["· ",e.jsx(ka,{className:"w-3.5 h-3.5"}),P.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:M})})]}),!O&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Live"}),e.jsx(On,{checked:j.is_enabled,onCheckedChange:U})]})]}),e.jsxs("div",{className:"mt-5 flex items-center gap-2 flex-wrap",children:[e.jsxs($,{onClick:B,variant:"outline",size:"sm",children:[e.jsx(Da,{className:"w-4 h-4 mr-1.5"})," Copy Link"]}),e.jsxs($,{onClick:()=>window.open(M,"_blank"),variant:"outline",size:"sm",children:[e.jsx(Ir,{className:"w-4 h-4 mr-1.5"})," Preview"]}),e.jsxs($,{onClick:()=>y(!0),size:"sm",children:[e.jsx(Wr,{className:"w-4 h-4 mr-1.5"})," Invite Client"]}),e.jsxs($,{onClick:()=>g(!0),variant:"outline",size:"sm",children:[e.jsx(h5,{className:"w-4 h-4 mr-1.5"})," Post Update"]}),e.jsxs($,{onClick:()=>m(!0),variant:"outline",size:"sm",children:[e.jsx(Yc,{className:"w-4 h-4 mr-1.5"})," Settings"]}),e.jsxs("div",{className:"ml-auto flex items-center gap-2",children:[O?e.jsxs($,{onClick:H,variant:"outline",size:"sm",children:[e.jsx(OT,{className:"w-4 h-4 mr-1.5"})," Restore"]}):e.jsxs($,{onClick:G,variant:"ghost",size:"sm",children:[e.jsx(kf,{className:"w-4 h-4 mr-1.5"})," Archive"]}),e.jsx($,{onClick:()=>_(!0),variant:"ghost",size:"sm",className:"text-destructive hover:text-destructive",children:e.jsx(Un,{className:"w-4 h-4"})})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:[e.jsx(Yae,{icon:h5,label:"Updates Posted",value:i.length}),e.jsx(Yae,{icon:Zo,label:"Referrals",value:A.length}),e.jsx(Yae,{icon:ha,label:"Inspection",value:j.inspection_date?f9(j.inspection_date):"—"}),e.jsx(Yae,{icon:ha,label:"Appraisal",value:j.appraisal_date?f9(j.appraisal_date):"—"})]}),e.jsxs(ya,{defaultValue:"updates",className:"w-full",children:[e.jsxs(va,{children:[e.jsxs(is,{value:"updates",children:["Updates (",i.length,")"]}),e.jsxs(is,{value:"referrals",children:["Referrals (",A.length,")"]}),e.jsx(is,{value:"branding",children:"Branding"}),e.jsx(is,{value:"details",children:"Details"})]}),e.jsx(cs,{value:"updates",className:"mt-4",children:e.jsx(we,{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($,{size:"sm",onClick:()=>g(!0),children:[e.jsx(h5,{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(h5,{className:"w-10 h-10 text-muted-foreground/40 mx-auto mb-3"}),e.jsx("p",{className:"text-sm font-medium",children:"No updates posted yet"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Keep your client in the loop — post your first update."})]}):e.jsx("div",{className:"space-y-3",children:i.map(se=>e.jsx("div",{className:"border rounded-lg p-4",children:e.jsx("div",{className:"flex items-start justify-between gap-2",children:e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("h4",{className:"font-medium text-sm",children:se.title}),se.is_stage_change&&e.jsx(qe,{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:f9(se.created_at)}),se.content&&e.jsx("p",{className:"text-sm text-muted-foreground mt-2 whitespace-pre-wrap",children:se.content}),se.video_url&&e.jsxs("a",{href:se.video_url,target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-1 text-xs text-primary hover:underline mt-2",children:[e.jsx(ia,{className:"w-3 h-3"})," View video"]})]})})},se.id))})]})})}),e.jsx(cs,{value:"referrals",className:"mt-4",children:e.jsx(we,{children:e.jsxs(De,{className:"p-4",children:[e.jsx("h3",{className:"font-semibold mb-4",children:"Referrals from this Portal"}),A.length===0?e.jsxs("div",{className:"text-center py-12 border-2 border-dashed rounded-lg",children:[e.jsx(Zo,{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:A.map(se=>e.jsx(nr,{to:"/mission-control/client-portals?tab=referrals",className:"block border rounded-lg p-3 hover:bg-muted/50 transition-colors",children:e.jsxs("div",{className:"flex items-center justify-between gap-2 flex-wrap",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:se.friend_name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[se.friend_email||se.friend_phone||"No contact info"," · ",f9(se.created_at)]})]}),e.jsx(qe,{variant:"outline",className:"text-xs capitalize",children:se.status})]})},se.id))})]})})}),e.jsx(cs,{value:"branding",className:"mt-4",children:e.jsx(we,{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(gd,{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($,{onClick:()=>m(!0),children:[e.jsx(Yc,{className:"w-4 h-4 mr-2"}),"Edit Branding (in Settings)"]})]})]})})})}),e.jsx(cs,{value:"details",className:"mt-4",children:e.jsx(we,{children:e.jsxs(De,{className:"p-6 space-y-4",children:[e.jsx(WA,{label:"Visibility",value:j.visibility}),e.jsx(WA,{label:"Onboarding Required",value:j.require_onboarding?"Yes":"No"}),e.jsx(WA,{label:"Allow Spouse",value:j.allow_spouse?"Yes":"No"}),e.jsx(WA,{label:"Notify Client on Updates",value:j.notify_client?"Yes":"No"}),e.jsx(WA,{label:"Show Post-Close Tips",value:j.show_post_close_tips?"Yes":"No"}),e.jsx(WA,{label:"Slug",value:j.slug,mono:!0}),e.jsx(WA,{label:"Created",value:f9(j.created_at)}),e.jsx(WA,{label:"Last Updated",value:f9(j.updated_at)}),e.jsx("div",{className:"pt-2",children:e.jsxs($,{variant:"outline",onClick:()=>m(!0),children:[e.jsx(Yc,{className:"w-4 h-4 mr-2"})," Edit All Settings"]})})]})})})]})]}),e.jsx(mQe,{open:h,onOpenChange:m,portal:j,dealOwnerId:n||""}),e.jsx(fQe,{open:p,onOpenChange:g,portalId:j.id,portalSlug:j.slug,notifyClient:j.notify_client}),e.jsx(pQe,{open:x,onOpenChange:y,portal:j,dealName:I}),e.jsx(oc,{open:v,onOpenChange:_,children:e.jsxs(Ql,{children:[e.jsxs(Jl,{children:[e.jsx(tc,{children:"Permanently delete this portal?"}),e.jsx(sc,{children:"This removes the portal and all its updates. The client will lose access. This action cannot be undone."})]}),e.jsxs(ec,{children:[e.jsx(nc,{children:"Cancel"}),e.jsx(Vl,{onClick:Y,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete Permanently"})]})]})})]})}function Yae({icon:s,label:t,value:n}){return e.jsxs("div",{className:"border rounded-lg p-4 bg-card",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(s,{className:"w-3.5 h-3.5"}),e.jsx("span",{className:"text-[11px] uppercase tracking-wide",children:t})]}),e.jsx("p",{className:"text-xl font-semibold truncate",children:n})]})}function WA({label:s,value:t,mono:n}){return e.jsxs("div",{className:"flex items-center justify-between gap-4 border-b pb-2 last:border-b-0 last:pb-0",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:s}),e.jsx("span",{className:`text-sm ${n?"font-mono text-xs":""} text-right truncate`,children:t})]})}const JUe=[{value:"video_intro",label:"Video Intro",icon:ia,description:"Add an intro video"},{value:"testimonials",label:"Testimonials",icon:v3,description:"Client testimonials carousel"},{value:"specialties",label:"Specialties",icon:kg,description:"Tags for your specialties"},{value:"custom_links",label:"Custom Links",icon:pd,description:"Custom CTA buttons"},{value:"social_media",label:"Social Media",icon:ou,description:"Links to your social profiles"}],tDn=["First-Time Buyers","Luxury Homes","Investment Properties","Relocation","New Construction","Condos & Townhomes","Waterfront","Commercial","Land & Lots","Senior Living","Military/VA","Short Sales & Foreclosures"],sDn={video_intro:{video_url:""},testimonials:{testimonials:[{name:"",quote:"",role:""}]},specialties:{tags:[]},custom_links:{links:[{label:"",url:""}]},social_media:{platforms:[]}};function fVt({cardId:s}){const{data:t,isLoading:n}=Zws(s),r=Xws(),a=Qws(),i=Jws(),[l,o]=k.useState(!1),[c,d]=k.useState(""),[u,h]=k.useState(null);if(n)return e.jsxs("div",{className:"space-y-3",children:[e.jsx(fn,{className:"h-16 w-full"}),e.jsx(fn,{className:"h-16 w-full"})]});const m=()=>{c&&r.mutate({card_id:s,block_type:c,sort_order:(t==null?void 0:t.length)||0,config:sDn[c]||{}},{onSuccess:()=>{o(!1),d("")}})},p=_=>{a.mutate({id:_.id,is_visible:!_.is_visible})},g=(_,j)=>{if(!t)return;const C=t.findIndex(I=>I.id===_.id),A=j==="up"?C-1:C+1;if(A<0||A>=t.length)return;const M=t[A];a.mutate({id:_.id,sort_order:M.sort_order}),a.mutate({id:M.id,sort_order:_.sort_order})},x=async _=>{await io("Remove this block from this card?")&&i.mutate(_.id)},y=(_,j)=>{a.mutate({id:_.id,config:j},{onSuccess:()=>h(null)})},v=_=>JUe.find(j=>j.value===_);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($,{size:"sm",onClick:()=>o(!0),children:[e.jsx(nn,{className:"h-4 w-4 mr-1"})," Add Block"]})]}):e.jsxs(e.Fragment,{children:[t.map((_,j)=>{const C=v(_.block_type),A=(C==null?void 0:C.icon)||kg;return e.jsx(we,{className:_.is_visible?"":"opacity-50",children:e.jsx(De,{className:"p-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Bp,{className:"h-4 w-4 text-muted-foreground flex-shrink-0"}),e.jsx(A,{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:(C==null?void 0:C.label)||_.block_type}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:nDn(_)})]}),e.jsxs("div",{className:"flex items-center gap-0.5",children:[e.jsx($,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>g(_,"up"),disabled:j===0,children:e.jsx(ap,{className:"h-3 w-3"})}),e.jsx($,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>g(_,"down"),disabled:j===t.length-1,children:e.jsx(nx,{className:"h-3 w-3"})}),e.jsx($,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>p(_),children:_.is_visible?e.jsx(ba,{className:"h-3 w-3"}):e.jsx(x0,{className:"h-3 w-3"})}),e.jsx($,{variant:"ghost",size:"sm",className:"h-7 text-xs",onClick:()=>h(_),children:"Edit"}),e.jsx($,{variant:"ghost",size:"icon",className:"h-7 w-7 text-destructive",onClick:()=>x(_),children:e.jsx(Un,{className:"h-3 w-3"})})]})]})})},_.id)}),e.jsxs($,{variant:"outline",size:"sm",className:"w-full",onClick:()=>o(!0),children:[e.jsx(nn,{className:"h-4 w-4 mr-1"})," Add Block"]})]}),e.jsx(zs,{open:l,onOpenChange:o,children:e.jsxs(Rs,{children:[e.jsx(Vs,{children:e.jsx($s,{children:"Add Block"})}),e.jsx("div",{className:"grid gap-3",children:JUe.map(_=>{const j=_.icon;return e.jsxs("button",{onClick:()=>d(_.value),className:`flex items-center gap-3 p-3 rounded-lg border text-left transition-colors ${c===_.value?"border-primary bg-primary/5":"border-border hover:bg-muted"}`,children:[e.jsx(j,{className:"h-5 w-5 text-primary flex-shrink-0"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:_.label}),e.jsx("p",{className:"text-xs text-muted-foreground",children:_.description})]})]},_.value)})}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>o(!1),children:"Cancel"}),e.jsx($,{onClick:m,disabled:!c||r.isPending,children:"Add Block"})]})]})}),u&&e.jsx(rDn,{block:u,onSave:_=>y(u,_),onClose:()=>h(null)})]})}function nDn(s){var n;const t=s.config;switch(s.block_type){case"video_intro":return t.video_url?"Video configured":"No video set";case"testimonials":{const r=((n=t.testimonials)==null?void 0:n.length)||0;return`${r} testimonial${r!==1?"s":""}`}case"specialties":{const r=t.tags||[];return r.length?r.slice(0,3).join(", ")+(r.length>3?"...":""):"No tags"}case"custom_links":{const r=t.links||[];return`${r.length} link${r.length!==1?"s":""}`}case"social_media":{const r=t.platforms||[];return r.length?r.map(a=>a.platform).join(", "):"No platforms"}default:return""}}function rDn({block:s,onSave:t,onClose:n}){const[r,a]=k.useState(s.config),i=JUe.find(l=>l.value===s.block_type);return e.jsx(zs,{open:!0,onOpenChange:n,children:e.jsxs(Rs,{className:"max-w-lg max-h-[80vh] overflow-y-auto",children:[e.jsx(Vs,{children:e.jsxs($s,{children:["Edit ",i==null?void 0:i.label]})}),s.block_type==="video_intro"&&e.jsx(aDn,{config:r,onChange:a,cardId:s.card_id}),s.block_type==="testimonials"&&e.jsx(iDn,{config:r,onChange:a}),s.block_type==="specialties"&&e.jsx(oDn,{config:r,onChange:a}),s.block_type==="custom_links"&&e.jsx(lDn,{config:r,onChange:a}),s.block_type==="social_media"&&e.jsx(cDn,{config:r,onChange:a}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:n,children:"Cancel"}),e.jsx($,{onClick:()=>t(r),children:"Save"})]})]})})}function aDn({config:s,onChange:t,cardId:n}){var p,g;const[r,a]=k.useState(""),[i,l]=k.useState((p=s.video_url)!=null&&p.includes("youtube")||(g=s.video_url)!=null&&g.includes("youtu.be")?"youtube":"library"),{data:o}=pt({queryKey:["card-owner",n],queryFn:async()=>{const{data:x}=await V.from("agent_cards").select("user_id").eq("id",n).single();return x==null?void 0:x.user_id},enabled:!!n}),{data:c,isLoading:d}=pt({queryKey:["agent-videos-library",o],queryFn:async()=>{const{data:x,error:y}=await V.from("agent_videos").select("id, title, bunny_video_id, thumbnail_url, playback_url, created_at").eq("owner_user_id",o).eq("is_deleted",!1).eq("status","ready").order("created_at",{ascending:!1});if(y)throw y;return x||[]},enabled:!!o}),u=(c==null?void 0:c.filter(x=>!r||(x.title||"").toLowerCase().includes(r.toLowerCase())))||[],h=s.bunny_video_id,m=x=>{var j;const y=(j=x.playback_url)==null?void 0:j.match(/\/(?:play|embed)\/(\d+)\//),_=`https://iframe.mediadelivery.net/embed/${y?y[1]:"570924"}/${x.bunny_video_id}?autoplay=false&responsive=true`;t({...s,video_url:_,bunny_video_id:x.bunny_video_id,video_source:"library"})};return e.jsx("div",{className:"space-y-4",children:e.jsxs(ya,{value:i,onValueChange:l,children:[e.jsxs(va,{className:"w-full",children:[e.jsx(is,{value:"library",className:"flex-1",children:"Video Library"}),e.jsx(is,{value:"youtube",className:"flex-1",children:"YouTube URL"})]}),e.jsxs(cs,{value:"library",className:"space-y-3 mt-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Yr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search videos...",value:r,onChange:x=>a(x.target.value),className:"pl-9"})]}),e.jsx(Eo,{className:"h-[240px]",children:d?e.jsxs("div",{className:"space-y-2",children:[e.jsx(fn,{className:"h-14 w-full"}),e.jsx(fn,{className:"h-14 w-full"})]}):u.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-8",children:(c==null?void 0:c.length)===0?"No videos in library yet":"No matching videos"}):e.jsx("div",{className:"space-y-1.5 pr-3",children:u.map(x=>e.jsxs("button",{onClick:()=>m(x),className:`w-full flex items-center gap-3 p-2 rounded-lg border text-left transition-colors ${h===x.bunny_video_id?"border-primary bg-primary/5":"border-border hover:bg-muted"}`,children:[x.thumbnail_url?e.jsx("img",{src:x.thumbnail_url,alt:"",className:"h-10 w-16 rounded object-cover flex-shrink-0 bg-muted",onError:y=>{var v;y.currentTarget.style.display="none",(v=y.currentTarget.nextElementSibling)==null||v.classList.remove("hidden")}}):null,e.jsx("div",{className:`h-10 w-16 rounded bg-muted flex items-center justify-center flex-shrink-0 ${x.thumbnail_url?"hidden":""}`,children:e.jsx(ia,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx("span",{className:"text-sm font-medium truncate flex-1",children:x.title||"Untitled Video"}),h===x.bunny_video_id&&e.jsx(ma,{className:"h-4 w-4 text-primary flex-shrink-0"})]},x.id))})})]}),e.jsx(cs,{value:"youtube",className:"space-y-3 mt-3",children:e.jsxs("div",{children:[e.jsx(re,{children:"YouTube URL"}),e.jsx(be,{placeholder:"https://www.youtube.com/watch?v=...",value:s.video_source==="youtube"&&s.video_url||"",onChange:x=>t({...s,video_url:x.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 iDn({config:s,onChange:t}){const n=s.testimonials||[],r=(l,o,c)=>{const d=[...n];d[l]={...d[l],[o]:c},t({...s,testimonials:d})},a=()=>t({...s,testimonials:[...n,{name:"",quote:"",role:""}]}),i=l=>t({...s,testimonials:n.filter((o,c)=>c!==l)});return e.jsxs("div",{className:"space-y-4",children:[n.map((l,o)=>e.jsx(we,{children:e.jsxs(De,{className:"p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(re,{className:"text-xs font-medium",children:["Testimonial ",o+1]}),n.length>1&&e.jsx($,{variant:"ghost",size:"icon",className:"h-6 w-6 text-destructive",onClick:()=>i(o),children:e.jsx(Un,{className:"h-3 w-3"})})]}),e.jsx(be,{placeholder:"Client name",value:l.name,onChange:c=>r(o,"name",c.target.value)}),e.jsx(be,{placeholder:"Role/title (optional)",value:l.role||"",onChange:c=>r(o,"role",c.target.value)}),e.jsx("textarea",{className:"w-full min-h-[60px] rounded-md border border-input bg-background px-3 py-2 text-sm",placeholder:"Their testimonial quote...",value:l.quote,onChange:c=>r(o,"quote",c.target.value)})]})},o)),e.jsxs($,{variant:"outline",size:"sm",onClick:a,className:"w-full",children:[e.jsx(nn,{className:"h-4 w-4 mr-1"})," Add Testimonial"]})]})}function oDn({config:s,onChange:t}){const n=s.tags||[],[r,a]=k.useState(""),i=o=>{t({...s,tags:n.includes(o)?n.filter(c=>c!==o):[...n,o]})},l=()=>{r.trim()&&!n.includes(r.trim())&&(t({...s,tags:[...n,r.trim()]}),a(""))};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(re,{className:"text-sm mb-2 block",children:"Preset Specialties"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:tDn.map(o=>e.jsx("button",{onClick:()=>i(o),className:`px-3 py-1.5 text-xs rounded-full border transition-colors ${n.includes(o)?"bg-primary text-primary-foreground border-primary":"bg-muted border-border hover:bg-muted/80"}`,children:o},o))})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-sm mb-2 block",children:"Custom Tag"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(be,{placeholder:"Add your own...",value:r,onChange:o=>a(o.target.value),onKeyDown:o=>o.key==="Enter"&&(o.preventDefault(),l())}),e.jsx($,{variant:"outline",size:"sm",onClick:l,children:"Add"})]})]}),n.length>0&&e.jsxs("div",{children:[e.jsxs(re,{className:"text-xs text-muted-foreground mb-1 block",children:["Selected (",n.length,")"]}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:n.map(o=>e.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-1 text-xs bg-primary/10 text-primary rounded-full",children:[o,e.jsx("button",{onClick:()=>i(o),className:"hover:text-destructive",children:"×"})]},o))})]})]})}function lDn({config:s,onChange:t}){const n=s.links||[],r=(l,o,c)=>{const d=[...n];d[l]={...d[l],[o]:c},t({...s,links:d})},a=()=>t({...s,links:[...n,{label:"",url:""}]}),i=l=>t({...s,links:n.filter((o,c)=>c!==l)});return e.jsxs("div",{className:"space-y-3",children:[n.map((l,o)=>e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsx(be,{placeholder:"Button label",value:l.label,onChange:c=>r(o,"label",c.target.value)}),e.jsx(be,{placeholder:"https://...",value:l.url,onChange:c=>r(o,"url",c.target.value)})]}),n.length>1&&e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8 mt-1 text-destructive",onClick:()=>i(o),children:e.jsx(Un,{className:"h-3 w-3"})})]},o)),e.jsxs($,{variant:"outline",size:"sm",onClick:a,className:"w-full",children:[e.jsx(nn,{className:"h-4 w-4 mr-1"})," Add Link"]})]})}const obt=[{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 cDn({config:s,onChange:t}){const n=s.platforms||[],r=c=>{n.find(d=>d.platform===c)||t({...s,platforms:[...n,{platform:c,url:""}]})},a=(c,d)=>{const u=[...n];u[c]={...u[c],url:d},t({...s,platforms:u})},i=c=>{t({...s,platforms:n.filter((d,u)=>u!==c)})},l=obt.filter(c=>!n.find(d=>d.platform===c.value)),o=c=>{const d=j7e[c],u=obt.find(h=>h.value===c);return{label:(u==null?void 0:u.label)||c,color:(d==null?void 0:d.color)||"#666",iconPath:d==null?void 0:d.icon}};return e.jsxs("div",{className:"space-y-4",children:[n.length>0&&e.jsx("div",{className:"space-y-3",children:n.map((c,d)=>{const u=o(c.platform);return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-9 w-9 rounded-lg flex items-center justify-center flex-shrink-0 border",style:{borderColor:u.color+"30",backgroundColor:u.color+"10"},children:u.iconPath&&e.jsx("svg",{viewBox:"0 0 24 24",width:16,height:16,fill:u.color,children:e.jsx("path",{d:u.iconPath})})}),e.jsx("div",{className:"flex-1",children:e.jsx(be,{placeholder:`Your ${u.label} profile URL`,value:c.url,onChange:h=>a(d,h.target.value)})}),e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive flex-shrink-0",onClick:()=>i(d),children:e.jsx(Un,{className:"h-3.5 w-3.5"})})]},d)})}),l.length>0&&e.jsxs("div",{children:[e.jsx(re,{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=j7e[c.value];return e.jsxs("button",{onClick:()=>r(c.value),className:"inline-flex items-center gap-1.5 px-3 py-1.5 text-xs rounded-full border border-border bg-muted hover:bg-muted/80 transition-colors",children:[(d==null?void 0:d.icon)&&e.jsx("svg",{viewBox:"0 0 24 24",width:12,height:12,fill:d.color,children:e.jsx("path",{d:d.icon})}),c.label]},c.value)})})]}),n.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"Tap a platform above to add your social media profile."})]})}function dDn({slug:s,agentName:t}){const n=k.useRef(null),r=`https://cards.relevelup.com/${s}`,a=k.useCallback(()=>{var h;const i=(h=n.current)==null?void 0:h.querySelector("svg");if(!i)return;const l=document.createElement("canvas"),o=1024;l.width=o,l.height=o;const c=l.getContext("2d");if(!c)return;const d=new XMLSerializer().serializeToString(i),u=new Image;u.onload=()=>{c.fillStyle="#ffffff",c.fillRect(0,0,o,o),c.drawImage(u,0,0,o,o);const m=document.createElement("a");m.download=`${s}-qr-code.png`,m.href=l.toDataURL("image/png"),m.click(),ae.success("QR code downloaded!")},u.src="data:image/svg+xml;base64,"+btoa(unescape(encodeURIComponent(d)))},[s]);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(re,{className:"text-sm font-medium",children:"QR Code"}),e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{ref:n,className:"bg-white p-3 rounded-lg border shadow-sm shrink-0",children:e.jsx(jk,{value:r,size:120,level:"H",bgColor:"#ffffff",fgColor:"#000000"})}),e.jsxs("div",{className:"space-y-2 min-w-0",children:[e.jsx("p",{className:"text-xs text-muted-foreground leading-relaxed",children:"Download this QR code to use on business cards, flyers, signs, or any print materials. Scanning it opens your digital card instantly."}),e.jsxs($,{variant:"outline",size:"sm",onClick:a,className:"gap-1.5",children:[e.jsx(ji,{className:"h-3.5 w-3.5"}),"Download PNG"]})]})]})]})}function GDe(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 uDn(){const{user:s}=ks(),{data:t,isLoading:n}=Wws(s==null?void 0:s.id),r=AV(),[a,i]=k.useState(null),l=k.useMemo(()=>a||(t?GDe(t):null),[a,t]);if(n)return e.jsx(Xs,{children:e.jsxs("div",{className:"max-w-2xl mx-auto p-4 space-y-4",children:[e.jsx(fn,{className:"h-8 w-48"}),e.jsx(fn,{className:"h-32 w-full"}),e.jsx(fn,{className:"h-32 w-full"})]})});if(!t)return e.jsx(Xs,{children:e.jsx(mDn,{userId:s==null?void 0:s.id})});const o=l||GDe(t),c=d=>{i(u=>{const h=u||GDe(t);return typeof d=="function"?d(h):d})};return e.jsx(Xs,{children:e.jsxs("div",{className:"flex gap-6 items-start",children:[e.jsxs("div",{className:`${r?"w-full":"flex-1 min-w-0"} max-w-2xl p-4 space-y-6 animate-fade-in`,children:[e.jsx(fDn,{card:t}),e.jsx(yDn,{card:t,form:o,setForm:c})]}),!r&&e.jsx("div",{className:"w-[400px] shrink-0","aria-hidden":"true"}),!r&&e.jsx("div",{className:"fixed right-8 top-[5.5rem] w-[400px] z-30",style:{height:"calc(100vh - 6.5rem)"},children:e.jsxs("div",{className:"rounded-xl border bg-muted/30 overflow-hidden h-full flex flex-col",children:[e.jsxs("div",{className:"flex items-center gap-2 px-4 py-2.5 border-b bg-card shrink-0",children:[e.jsx(j2,{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(hDn,{card:t,form:o})})]})})]})})}function hDn({card:s,form:t}){const{data:n}=pt({queryKey:["card-preview-profile",s.user_id],queryFn:async()=>{const{data:a}=await V.from("profiles").select("name, email, phone, avatar_url, brokerage_id").eq("id",s.user_id).single();let i=(a==null?void 0:a.avatar_url)||null;if(!i){const{data:l}=await V.storage.from("avatars").list(`${s.user_id}`);if(l&&l.length>0){const{data:o}=V.storage.from("avatars").getPublicUrl(`${s.user_id}/${l[0].name}`);i=`${o.publicUrl}?t=${Date.now()}`}}return{...a,avatar_url:i}}}),r=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:(n==null?void 0:n.name)||null,email:t.display_email||(n==null?void 0:n.email)||null,phone:(n==null?void 0:n.phone)||null,brokerage_id:(n==null?void 0:n.brokerage_id)||null},brokerage_name:t.brokerage_display_name||null,avatar_url:(n==null?void 0:n.avatar_url)||null}),[s,t,n]);return e.jsx("div",{className:"transform scale-[0.85] origin-top",children:e.jsx(EGe,{card:r})})}function mDn({userId:s}){var c;const[t,n]=k.useState(""),r=eEt(),{data:a}=pt({queryKey:["my-profile-for-card",s],queryFn:async()=>{if(!s)return null;const{data:d}=await V.from("profiles").select("name").eq("id",s).single();return d},enabled:!!s}),i=((c=a==null?void 0:a.name)==null?void 0:c.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/(^-|-$)/g,""))||"",l=()=>{if(!s)return;const d=(t.trim()||i).toLowerCase().replace(/[^a-z0-9-]/g,"-");if(!d){ae.error("Please enter a URL slug for your card");return}r.mutate({user_id:s,slug:d,is_published:!0},{onSuccess:()=>ae.success("Your digital card has been created!")})},o=[{icon:kc,title:"Shareable Link",desc:"One link that works everywhere"},{icon:ix,title:"Lead Capture",desc:"Collect leads automatically"},{icon:Ng,title:"Always Up-to-Date",desc:"Edit anytime, changes are instant"},{icon:gd,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(kn,{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(we,{className:"shadow-lg border-2",children:[e.jsxs(Vt,{className:"text-center pb-2",children:[e.jsx(Yt,{className:"text-xl",children:"Set Up Your Card"}),e.jsx(vr,{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(re,{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(be,{value:t||i,onChange:d=>n(d.target.value),placeholder:"your-name",className:"rounded-l-none"})]})]}),e.jsxs($,{onClick:l,disabled:r.isPending,className:"w-full h-11 text-base font-semibold",size:"lg",children:[e.jsx(kn,{className:"h-4 w-4 mr-2"}),r.isPending?"Creating...":"Create My Card"]})]})]})]})}function fDn({card:s}){const n=`https://cards.relevelup.com/${s.slug}`,r=()=>{navigator.clipboard.writeText(n),ae.success("Card link copied!")};return e.jsx("div",{className:"rounded-xl border bg-card p-5",children:e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h1",{className:"text-xl font-bold",children:"My Digital Card"}),e.jsx(qe,{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(kc,{className:"h-3.5 w-3.5"}),"cards.relevelup.com/",s.slug]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs($,{variant:"outline",size:"sm",onClick:r,className:"gap-1.5",children:[e.jsx(Da,{className:"h-3.5 w-3.5"})," Copy Link"]}),e.jsx($,{size:"sm",asChild:!0,className:"gap-1.5",children:e.jsxs("a",{href:n,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(Ir,{className:"h-3.5 w-3.5"})," Preview"]})})]})]})})}function pDn({userId:s}){const t=ls(),n=k.useRef(null),[r,a]=k.useState(!1),[i,l]=k.useState(""),{data:o,isLoading:c}=pt({queryKey:["card-editor-profile",s],queryFn:async()=>{const{data:B}=await V.from("profiles").select("name, email, phone, avatar_url").eq("id",s).single();let U=(B==null?void 0:B.avatar_url)||null;if(!U){const{data:G}=await V.storage.from("avatars").list(`${s}`);if(G&&G.length>0){const{data:H}=V.storage.from("avatars").getPublicUrl(`${s}/${G[0].name}`);U=`${H.publicUrl}?t=${Date.now()}`,await V.from("profiles").update({avatar_url:U}).eq("id",s)}}return{...B,avatar_url:U}}}),[d,u]=k.useState(null),[h,m]=k.useState(null),[p,g]=k.useState(null),[x,y]=k.useState(!1),v=d??(o==null?void 0:o.name)??"",_=h??(o==null?void 0:o.phone)??"",j=p??(o==null?void 0:o.email)??"",C=o==null?void 0:o.avatar_url,A=((o==null?void 0:o.name)||"A").split(" ").map(B=>B[0]).join("").toUpperCase().slice(0,2),M=!(o!=null&&o.avatar_url)||!(o!=null&&o.phone),I=Nt({mutationFn:async B=>{const{error:U}=await V.from("profiles").update(B).eq("id",s);if(U)throw U},onSuccess:()=>{t.invalidateQueries({queryKey:["card-editor-profile",s]}),t.invalidateQueries({queryKey:["card-preview-profile",s]}),t.invalidateQueries({queryKey:["agent-card-user"]}),ae.success("Profile updated!")},onError:()=>ae.error("Failed to update profile")}),P=()=>{const B={};if(d!==null&&d!==(o==null?void 0:o.name)&&(B.name=d),h!==null&&h!==(o==null?void 0:o.phone)&&(B.phone=h||null),p!==null&&p!==(o==null?void 0:o.email)&&(B.email=p),Object.keys(B).length===0){ae.info("No changes to save");return}I.mutate(B)},R=B=>{var H;const U=(H=B.target.files)==null?void 0:H[0];if(!U)return;if(!U.type.startsWith("image/")){ae.error("Please select an image file");return}const G=new FileReader;G.onloadend=()=>{l(G.result),a(!0)},G.readAsDataURL(U),B.target.value=""},O=async B=>{y(!0);try{const{data:U}=await V.storage.from("avatars").list(`${s}`);U&&U.length>0&&await V.storage.from("avatars").remove(U.map(ee=>`${s}/${ee.name}`));const G=`${s}/avatar.jpg`,{error:H}=await V.storage.from("avatars").upload(G,B,{upsert:!0,contentType:"image/jpeg"});if(H)throw H;const{data:Y}=V.storage.from("avatars").getPublicUrl(G),se=Y.publicUrl+"?t="+Date.now();await V.from("profiles").update({avatar_url:se}).eq("id",s),t.invalidateQueries({queryKey:["card-editor-profile",s]}),t.invalidateQueries({queryKey:["card-preview-profile",s]}),t.invalidateQueries({queryKey:["agent-card-user"]}),ae.success("Photo updated!")}catch{ae.error("Failed to upload photo")}finally{y(!1)}};return c?e.jsx(fn,{className:"h-32 w-full rounded-xl"}):e.jsxs(e.Fragment,{children:[e.jsx(we,{className:M?"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(re,{className:"text-sm font-semibold",children:"Profile Info"}),M&&e.jsxs("span",{className:"inline-flex items-center gap-1 text-xs text-amber-600 dark:text-amber-400 font-medium",children:[e.jsx(Ho,{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 B;return(B=n.current)==null?void 0:B.click()},children:[e.jsxs(Wa,{className:"h-16 w-16 ring-2 ring-muted",children:[e.jsx(eo,{src:C||void 0,alt:v}),e.jsx(Ka,{className:"text-lg font-semibold bg-primary/10 text-primary",children:A})]}),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(g0,{className:"h-5 w-5 text-white"})}),e.jsx("input",{ref:n,type:"file",accept:"image/*",className:"hidden",onChange:R})]}),e.jsxs("div",{className:"flex-1 space-y-0.5",children:[e.jsx("p",{className:"text-sm font-medium",children:x?"Uploading...":C?"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(re,{className:"text-xs font-medium text-muted-foreground",children:"Full Name"}),e.jsx(be,{value:v,onChange:B=>u(B.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(re,{className:"text-xs font-medium text-muted-foreground",children:"Phone Number"}),e.jsx(be,{value:_,onChange:B=>m(B.target.value),placeholder:"(555) 123-4567",className:"h-10",type:"tel"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{className:"text-xs font-medium text-muted-foreground",children:"Email"}),e.jsx(be,{value:j,onChange:B=>g(B.target.value),placeholder:"you@example.com",className:"h-10",type:"email"})]})]})]}),e.jsx($,{variant:"outline",size:"sm",onClick:P,disabled:I.isPending,className:"w-full",children:I.isPending?"Saving...":"Update Profile Info"})]})}),e.jsx(pKe,{open:r,onClose:()=>a(!1),imageSrc:i,onCropComplete:O,aspectRatio:1})]})}function gDn({form:s,setForm:t,userId:n}){const[r,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=p=>{l(p),t(p==="name"?g=>({...g,brokerage_logo_url:""}):g=>({...g,brokerage_display_name:""}))},u=p=>{c(p),t(p==="name"?g=>({...g,team_logo_url:""}):g=>({...g,team_name:""}))},h=async(p,g)=>{var y;const x=(y=p.target.files)==null?void 0:y[0];if(x){if(!x.type.startsWith("image/")){ae.error("Please select an image file");return}a(g);try{const v=x.name.split(".").pop()||"png",j=`${n}/${g==="brokerage_logo_url"?"brokerage-logo":"team-logo"}.${v}`,{error:C}=await V.storage.from("card-logos").upload(j,x,{upsert:!0});if(C)throw C;const{data:A}=V.storage.from("card-logos").getPublicUrl(j),M=A.publicUrl+"?t="+Date.now();t(g==="brokerage_logo_url"?I=>({...I,[g]:M,brokerage_display_name:""}):I=>({...I,[g]:M,team_name:""})),ae.success("Logo uploaded!")}catch{ae.error("Failed to upload logo")}finally{a(null),p.target.value=""}}},m=p=>{t(g=>({...g,[p]:""}))};return e.jsx(we,{children:e.jsxs(De,{className:"p-5 space-y-5",children:[e.jsxs("div",{children:[e.jsx(re,{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(re,{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:"Brokerage"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{type:"button",variant:i==="name"?"default":"outline",size:"sm",className:"text-xs",onClick:()=>d("name"),children:"Use Name"}),e.jsx($,{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(re,{className:"text-xs font-medium text-muted-foreground",children:"Brokerage Name"}),e.jsx(be,{value:s.brokerage_display_name,onChange:p=>t(g=>({...g,brokerage_display_name:p.target.value})),placeholder:"e.g. Keller Williams Realty",className:"h-10"})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsx(re,{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:()=>m("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(g0,{className:"h-3.5 w-3.5"}),r==="brokerage_logo_url"?"Uploading...":s.brokerage_logo_url?"Change":"Upload Logo"]}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:p=>h(p,"brokerage_logo_url"),disabled:r!==null})]})]}),s.brokerage_logo_url&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(re,{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(sx,{value:[s.brokerage_logo_size||56],onValueChange:([p])=>t(g=>({...g,brokerage_logo_size:p})),min:24,max:120,step:4})]})]})]}),e.jsxs("div",{className:"space-y-3 p-3 rounded-lg bg-muted/30 border",children:[e.jsx(re,{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:"Team"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{type:"button",variant:o==="name"?"default":"outline",size:"sm",className:"text-xs",onClick:()=>u("name"),children:"Use Name"}),e.jsx($,{type:"button",variant:o==="logo"?"default":"outline",size:"sm",className:"text-xs",onClick:()=>u("logo"),children:"Use Logo"})]}),o==="name"?e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{className:"text-xs font-medium text-muted-foreground",children:"Team Name"}),e.jsx(be,{value:s.team_name,onChange:p=>t(g=>({...g,team_name:p.target.value})),placeholder:"e.g. The Smith Group",className:"h-10"})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsx(re,{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:()=>m("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(g0,{className:"h-3.5 w-3.5"}),r==="team_logo_url"?"Uploading...":s.team_logo_url?"Change":"Upload Logo"]}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:p=>h(p,"team_logo_url"),disabled:r!==null})]})]}),s.team_logo_url&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(re,{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(sx,{value:[s.team_logo_size||56],onValueChange:([p])=>t(g=>({...g,team_logo_size:p})),min:24,max:120,step:4})]})]})]})]})})}function xDn({form:s,setForm:t}){const n={accent:"#ff5722",dark:"#1a1a2e",button:"#ff5722"},r=s.bold_theme_colors||n,a=(o,c)=>{t(d=>({...d,bold_theme_colors:{...n,...d.bold_theme_colors,[o]:c}}))},i=()=>{t(o=>({...o,bold_theme_colors:null}))},l=[{key:"accent",label:"Accent Color",desc:"Page background, icons, highlights"},{key:"dark",label:"Dark Color",desc:"Header background, action buttons, social icons"},{key:"button",label:"CTA Button Color",desc:"Main call-to-action button"}];return e.jsxs("div",{className:"space-y-3 p-4 rounded-xl border bg-muted/30",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(re,{className:"text-sm font-semibold flex items-center gap-1.5",children:[e.jsx(gd,{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($,{variant:"ghost",size:"sm",className:"text-xs h-7",onClick:i,children:"Reset to Default"})]}),e.jsx("div",{className:"grid gap-3",children:l.map(({key:o,label:c,desc:d})=>e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("label",{className:"relative shrink-0",children:[e.jsx("input",{type:"color",value:r[o],onChange:u=>a(o,u.target.value),className:"sr-only"}),e.jsx("div",{className:"h-10 w-10 rounded-lg border-2 border-border cursor-pointer shadow-sm hover:scale-105 transition-transform",style:{backgroundColor:r[o]}})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium",children:c}),e.jsx("p",{className:"text-xs text-muted-foreground",children:d})]}),e.jsx(be,{value:r[o],onChange:u=>{const h=u.target.value;/^#[0-9a-fA-F]{0,6}$/.test(h)&&a(o,h)},className:"w-24 h-8 text-xs font-mono",placeholder:"#ff5722"})]},o))}),e.jsxs("div",{className:"flex items-center gap-2 pt-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Preview:"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx("div",{className:"h-6 w-12 rounded",style:{backgroundColor:r.accent}}),e.jsx("div",{className:"h-6 w-12 rounded",style:{backgroundColor:r.dark}}),e.jsx("div",{className:"h-6 w-12 rounded",style:{backgroundColor:r.button}})]})]})]})}function yDn({card:s,form:t,setForm:n}){var x;const r=tEt(),a=ls(),{data:i}=sEt(s.id),[l,o]=k.useState(s.slug),[c,d]=k.useState(!1),[u,h]=k.useState("idle"),m=k.useRef(JSON.stringify(t)),p=k.useRef(null);k.useEffect(()=>{const y=JSON.stringify(t);if(y!==m.current)return p.current&&clearTimeout(p.current),p.current=setTimeout(()=>{h("saving"),r.mutate({id:s.id,...t,is_published:!0,title:t.title||null,positioning_statement:t.positioning_statement||null,bio:t.bio||null,review_snippet:t.review_snippet||null,review_source_url:t.review_source_url||null,booking_url:t.booking_url||null,custom_cta_label:t.custom_cta_label||null,brokerage_display_name:t.brokerage_display_name||null,brokerage_logo_url:t.brokerage_logo_url||null,brokerage_logo_size:t.brokerage_logo_size,team_name:t.team_name||null,team_logo_url:t.team_logo_url||null,team_logo_size:t.team_logo_size,bold_theme_colors:t.bold_theme_colors||null,display_email:t.display_email||null},{onSuccess:()=>{m.current=y,h("saved"),setTimeout(()=>h("idle"),2e3)},onError:()=>h("idle")})},1500),()=>{p.current&&clearTimeout(p.current)}},[t]);const g=async()=>{const y=l.trim().toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/(^-|-$)/g,"");if(!y){ae.error("Please enter a valid URL");return}if(y===s.slug){ae.info("No changes to save");return}d(!0);try{const{data:v}=await V.from("agent_cards").select("id").eq("slug",y).neq("id",s.id).maybeSingle();if(v){ae.error("This URL is already taken. Try another one.");return}const{error:_}=await V.from("agent_cards").update({slug:y}).eq("id",s.id);if(_)throw _;o(y),a.invalidateQueries({queryKey:["agent-card"]}),ae.success("Card address updated!")}catch{ae.error("Failed to update card address")}finally{d(!1)}};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs(ya,{defaultValue:"content",children:[e.jsxs(va,{className:"w-full h-11 p-1",children:[e.jsxs(is,{value:"content",className:"flex-1 gap-1.5 data-[state=active]:shadow-sm",children:[e.jsx(cv,{className:"h-3.5 w-3.5 hidden sm:inline"}),"Content"]}),e.jsxs(is,{value:"sections",className:"flex-1 gap-1.5 data-[state=active]:shadow-sm",children:[e.jsx(ba,{className:"h-3.5 w-3.5 hidden sm:inline"}),"Sections"]}),e.jsxs(is,{value:"blocks",className:"flex-1 gap-1.5 data-[state=active]:shadow-sm",children:[e.jsx(ix,{className:"h-3.5 w-3.5 hidden sm:inline"}),"Blocks"]}),e.jsxs(is,{value:"qrcode",className:"flex-1 gap-1.5 data-[state=active]:shadow-sm",children:[e.jsx(Bx,{className:"h-3.5 w-3.5 hidden sm:inline"}),"QR Code"]}),e.jsxs(is,{value:"analytics",className:"flex-1 gap-1.5 data-[state=active]:shadow-sm",children:[e.jsx(rh,{className:"h-3.5 w-3.5 hidden sm:inline"}),"Analytics"]})]}),e.jsxs(cs,{value:"content",className:"mt-4 space-y-4",children:[e.jsx(pDn,{userId:s.user_id}),e.jsx(gDn,{form:t,setForm:n,userId:s.user_id}),e.jsx(we,{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(re,{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(On,{checked:t.is_published,onCheckedChange:y=>n(v=>({...v,is_published:y}))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{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(be,{value:l,onChange:y=>o(y.target.value.toLowerCase().replace(/[^a-z0-9-]/g,"-")),placeholder:"your-name",className:"rounded-l-none h-10"})]}),e.jsx($,{variant:"outline",size:"sm",onClick:g,disabled:c||l===s.slug,className:"shrink-0",children:c?"Saving...":"Update"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"This is your unique card URL. Only letters, numbers, and dashes allowed."})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{className:"text-sm font-medium",children:"Card Email (Override)"}),e.jsx(be,{value:t.display_email,onChange:y=>n(v=>({...v,display_email:y.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(re,{className:"text-sm font-medium",children:"Theme"}),e.jsxs(bs,{value:t.theme,onValueChange:y=>n(v=>({...v,theme:y})),children:[e.jsx(ys,{className:"h-11",children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"standard",children:"✨ Standard — Modern & Clean"}),e.jsx(We,{value:"luxury",children:"🌙 Luxury — Dark & Gold"}),e.jsx(We,{value:"bold",children:"🔥 Bold — Vibrant & Punchy"}),e.jsx(We,{value:"classic",children:"📋 Classic — Professional"})]})]})]}),t.theme==="bold"&&e.jsx(xDn,{form:t,setForm:n}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{className:"text-sm font-medium",children:"Title / Tagline"}),e.jsx(be,{value:t.title,onChange:y=>n(v=>({...v,title:y.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(re,{className:"text-sm font-medium",children:"Positioning Statement"}),e.jsx(be,{value:t.positioning_statement,onChange:y=>n(v=>({...v,positioning_statement:y.target.value})),placeholder:"Your home journey, handled with care.",className:"h-11"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{className:"text-sm font-medium",children:"Bio"}),e.jsx(Ls,{value:t.bio,onChange:y=>n(v=>({...v,bio:y.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(re,{className:"text-sm font-medium",children:"Review Snippet"}),e.jsx(be,{value:t.review_snippet,onChange:y=>n(v=>({...v,review_snippet:y.target.value})),placeholder:"Best agent we've ever worked with...",className:"h-11"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{className:"text-sm font-medium",children:"Review Source URL"}),e.jsx(be,{value:t.review_source_url,onChange:y=>n(v=>({...v,review_source_url:y.target.value})),placeholder:"https://g.page/your-business/review",className:"h-11"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{className:"text-sm font-medium",children:"Booking URL"}),e.jsx(be,{value:t.booking_url,onChange:y=>n(v=>({...v,booking_url:y.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(re,{className:"text-sm font-medium",children:"Custom CTA Label"}),e.jsx(be,{value:t.custom_cta_label,onChange:y=>n(v=>({...v,custom_cta_label:y.target.value})),placeholder:"Book a Call",className:"h-11"})]})]})})]}),e.jsx(cs,{value:"sections",className:"mt-4",children:e.jsx(we,{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:y,label:v,desc:_})=>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(re,{className:"text-sm font-medium",children:v}),e.jsx("p",{className:"text-xs text-muted-foreground",children:_})]}),e.jsx(On,{checked:t[y],onCheckedChange:j=>n(C=>({...C,[y]:j}))})]},y))})})}),e.jsx(cs,{value:"blocks",className:"mt-4",children:e.jsx(fVt,{cardId:s.id})}),e.jsx(cs,{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:ba,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:rh,color:"text-amber-600 bg-amber-100 dark:text-amber-400 dark:bg-amber-900/30"},{label:"Leads",value:((x=i==null?void 0:i.leads)==null?void 0:x.length)??0,icon:Pl,color:"text-emerald-600 bg-emerald-100 dark:text-emerald-400 dark:bg-emerald-900/30"}].map(y=>e.jsx(we,{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 ${y.color}`,children:e.jsx(y.icon,{className:"h-3.5 w-3.5"})}),e.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:y.label})]}),e.jsx("div",{className:"text-2xl font-bold",children:y.value})]})},y.label))}),i&&i.leads.length>0&&e.jsxs(we,{children:[e.jsx(Vt,{className:"pb-3",children:e.jsx(Yt,{className:"text-base",children:"Recent Leads"})}),e.jsx(De,{className:"pt-0 space-y-2",children:i.leads.slice(0,5).map(y=>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:y.name}),y.phone&&e.jsx("span",{className:"text-muted-foreground ml-2",children:y.phone})]}),y.intent&&e.jsx(qe,{variant:"secondary",className:"text-xs",children:y.intent})]},y.id))})]}),(!i||i.leads.length===0)&&e.jsx(we,{children:e.jsxs(De,{className:"p-8 text-center",children:[e.jsx(rh,{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(cs,{value:"qrcode",className:"mt-4 space-y-4",children:e.jsx(we,{children:e.jsx(De,{className:"p-6",children:e.jsx(dDn,{slug:s.slug})})})})]}),e.jsxs("div",{className:"flex items-center justify-center gap-2 py-2 text-sm text-muted-foreground",children:[u==="saving"&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"h-2 w-2 rounded-full bg-amber-400 animate-pulse"})," Saving..."]}),u==="saved"&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"h-2 w-2 rounded-full bg-green-500"})," All changes saved"]}),u==="idle"&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"h-2 w-2 rounded-full bg-muted-foreground/30"})," Changes auto-save"]})]})]})}function vDn(){const s=ls(),[t,n]=k.useState(""),[r,a]=k.useState(!1),[i,l]=k.useState(!1),[o,c]=k.useState(null),[d,u]=k.useState(!1),[h,m]=k.useState(!1),[p,g]=k.useState(null),[x,y]=k.useState(null),[v,_]=k.useState(0),[j,C]=k.useState(""),[A,M]=k.useState(!1),{data:I,isLoading:P}=pt({queryKey:["boldtrail-status"],queryFn:async()=>{const{data:me,error:Q}=await V.functions.invoke("boldtrail-sync",{body:{action:"status"}});if(Q)throw Q;return me}}),R=Nt({mutationFn:async me=>{const{data:Q,error:te}=await V.functions.invoke("boldtrail-sync",{body:{action:"save_token",api_token:me}});if(te)throw te;if(Q!=null&&Q.error)throw new Error(Q.error);return Q},onSuccess:()=>{s.invalidateQueries({queryKey:["boldtrail-status"]}),n(""),ae.success("BoldTrail connected successfully!")},onError:me=>{ae.error(me.message||"Failed to connect BoldTrail")}}),O=Nt({mutationFn:async()=>{const{data:me,error:Q}=await V.functions.invoke("boldtrail-sync",{body:{action:"disconnect"}});if(Q)throw Q;return me},onSuccess:()=>{s.invalidateQueries({queryKey:["boldtrail-status"]}),ae.success("BoldTrail disconnected")},onError:()=>ae.error("Failed to disconnect")}),B=Nt({mutationFn:async me=>{const{data:Q,error:te}=await V.functions.invoke("boldtrail-sync",{body:{action:"save_direction",sync_direction:me}});if(te)throw te;if(Q!=null&&Q.error)throw new Error(Q.error);return Q},onSuccess:()=>{s.invalidateQueries({queryKey:["boldtrail-status"]}),ae.success("Sync direction saved")},onError:me=>{ae.error(me.message||"Failed to save sync direction")}}),U=Nt({mutationFn:async()=>{const{data:me,error:Q}=await V.functions.invoke("boldtrail-sync",{body:{action:"detect_owner"}});if(Q)throw Q;if(me!=null&&me.error)throw new Error(me.error);return me},onSuccess:me=>{if(s.invalidateQueries({queryKey:["boldtrail-status"]}),me.kvcore_user_id){const Q=me.detected_name||me.detected_email||`ID ${me.kvcore_user_id}`;ae.success(`Detected your BoldTrail account: ${Q}`)}else if(me.candidates&&me.candidates.length>0){const Q=me.candidates.slice(0,5).map(te=>`${te.id} (${te.count} contacts)`).join(", ");ae.warning(`Couldn't auto-detect your ID. Owner IDs found in your contacts: ${Q}. Pick yours and enter it below.`,{duration:12e3}),M(!0)}else ae.warning("Couldn't auto-detect your BoldTrail user ID. Please find it in BoldTrail (My Profile URL) and enter it manually."),M(!0)},onError:me=>ae.error(me.message||"Detection failed")}),G=Nt({mutationFn:async me=>{const{data:Q,error:te}=await V.functions.invoke("boldtrail-sync",{body:{action:"save_owner_settings",...me}});if(te)throw te;if(Q!=null&&Q.error)throw new Error(Q.error);return Q},onSuccess:()=>{s.invalidateQueries({queryKey:["boldtrail-status"]}),ae.success("Settings saved"),M(!1)},onError:me=>ae.error(me.message||"Failed to save settings")}),H=Nt({mutationFn:async()=>{const{data:me,error:Q}=await V.functions.invoke("boldtrail-sync",{body:{action:"sync_preview"}});if(Q)throw Q;if(me!=null&&me.error)throw new Error(me.error);return me},onSuccess:me=>{g(null),c(me),a(!0)},onError:me=>{ae.error(me.message||"Failed to generate sync preview")}}),Y=Nt({mutationFn:async()=>{y("Initializing sync..."),_(5);const{data:me,error:Q}=await V.functions.invoke("boldtrail-sync",{body:{action:"sync",phase:"init",sync_direction:oe}});if(Q)throw Q;if(me!=null&&me.error)throw new Error(me.error);const te=me;let le=te.sync_log_id,fe=te.next_phase,_e=te.next_offset,ve=te.push_total||0,he=te.pull_total||0,Se=0,Te=0;for(;fe!=="finalize";){const Be=ve+he;fe==="fetch_bt"?y("Fetching BoldTrail contacts..."):fe==="analyze"?(y("Analyzing contacts..."),_(15)):fe==="push"?(y(`Pushing contacts to BoldTrail... (${Se}/${ve})`),_(Be>0?Se/Be*100:0)):fe==="pull"&&(y(`Pulling contacts from BoldTrail... (${Te}/${he})`),_(Be>0?(ve+Te)/Be*100:0));const{data:je,error:Ye}=await V.functions.invoke("boldtrail-sync",{body:{action:"sync",phase:fe,offset:_e,sync_log_id:le,sync_direction:oe}});if(Ye)throw Ye;if(je!=null&&je.error)throw new Error(je.error);const Ee=je;Se+=Ee.chunk_pushed||0,Te+=Ee.chunk_pulled||0,Ee.push_total!==void 0&&(ve=Ee.push_total||0),Ee.pull_total!==void 0&&(he=Ee.pull_total||0),Ee.progress&&y(Ee.progress),fe==="pull"&&he>0?_(Math.min(95,Te/he*100)):fe==="push"&&ve>0&&_(Math.min(95,Se/ve*100)),fe=Ee.next_phase,_e=Ee.next_offset}y("Finalizing sync..."),_(95);const{data:Ie,error:Ue}=await V.functions.invoke("boldtrail-sync",{body:{action:"sync",phase:"finalize",sync_log_id:le,sync_direction:oe}});if(Ue)throw Ue;return _(100),Ie},onSuccess:me=>{y(null),_(0),a(!1),s.invalidateQueries({queryKey:["boldtrail-status"]}),s.invalidateQueries({queryKey:["contacts"]}),s.invalidateQueries({queryKey:["innercircle-contacts"]}),s.invalidateQueries({queryKey:["innercircle-contact-counts"]}),s.invalidateQueries({queryKey:["contacts-last-touch"]}),ae.success(`Sync complete! Pushed ${me.contacts_pushed||0}, pulled ${me.contacts_pulled||0}, skipped ${me.contacts_skipped||0} duplicates.`)},onError:me=>{y(null),_(0),ae.error(me.message||"Sync failed")}}),se=I==null?void 0:I.connected,ee=(I==null?void 0:I.sync_direction)||"bidirectional",oe=p??ee;return e.jsxs(e.Fragment,{children:[e.jsxs(we,{children:[e.jsx(Vt,{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(Ix,{className:"h-5 w-5 text-emerald-600"})}),e.jsxs("div",{children:[e.jsxs(Yt,{className:"text-lg flex items-center gap-2",children:["BoldTrail",se&&e.jsx(qe,{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(mm,{className:"h-3.5 w-3.5"}),"Learn More"]})]}),e.jsx(vr,{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(nl,{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(nl,{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(nl,{className:"h-4 w-4 mt-0.5 text-green-500 shrink-0"}),e.jsx("span",{children:"Syncs name, email, phone, address, notes, and lead source"})]}),se?e.jsxs("div",{className:"space-y-3 mt-4",children:[e.jsx("div",{className:"rounded-lg border p-3 space-y-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:"BoldTrail Connected"}),(I==null?void 0:I.last_sync_at)&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Last sync: ",new Date(I.last_sync_at).toLocaleString(),I.last_sync_status&&e.jsx(qe,{variant:I.last_sync_status==="success"?"default":"secondary",className:"ml-2 text-[10px]",children:I.last_sync_status})]}),(I==null?void 0:I.boldtrail_contact_count)!=null&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:[I.boldtrail_contact_count," contacts in BoldTrail"]}),(I==null?void 0:I.last_sync_message)&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:I.last_sync_message})]}),e.jsxs(oc,{children:[e.jsx(_g,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(Un,{className:"h-4 w-4"})})}),e.jsxs(Ql,{children:[e.jsxs(Jl,{children:[e.jsx(tc,{children:"Disconnect BoldTrail?"}),e.jsx(sc,{children:"This will remove your API token. Previously synced contacts will remain in both systems."})]}),e.jsxs(ec,{children:[e.jsx(nc,{children:"Cancel"}),e.jsx(Vl,{onClick:()=>O.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(ck,{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(On,{checked:!!(I!=null&&I.sync_only_owned),onCheckedChange:me=>G.mutate({sync_only_owned:me}),disabled:G.isPending})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(re,{className:"text-xs",children:"Your BoldTrail Agent ID"}),A?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(be,{type:"number",placeholder:"e.g. 12345",value:j,onChange:me=>C(me.target.value),className:"h-8 text-sm"}),e.jsx($,{size:"sm",onClick:()=>{const me=j.trim()===""?null:Number(j);G.mutate({kvcore_user_id:me})},disabled:G.isPending,children:"Save"}),e.jsx($,{size:"sm",variant:"ghost",onClick:()=>M(!1),children:"Cancel"})]}):e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"text-sm font-mono",children:(I==null?void 0:I.kvcore_user_id)??e.jsx("span",{className:"text-muted-foreground",children:"Not set"})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs($,{size:"sm",variant:"outline",onClick:()=>U.mutate(),disabled:U.isPending,children:[U.isPending?e.jsx(yo,{className:"h-3 w-3 mr-1 animate-spin"}):null,"Auto-detect"]}),e.jsx($,{size:"sm",variant:"ghost",onClick:()=>{var me;C(((me=I==null?void 0:I.kvcore_user_id)==null?void 0:me.toString())??""),M(!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(T4e,{value:ee,onChange:me=>B.mutate(me)})}),e.jsx("div",{className:"flex gap-2",children:e.jsxs($,{onClick:()=>H.mutate(),disabled:H.isPending||Y.isPending,variant:"outline",className:"gap-2",children:[H.isPending?e.jsx(yo,{className:"h-4 w-4 animate-spin"}):e.jsx(ba,{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(be,{type:"password",placeholder:"Paste your BoldTrail API token",value:t,onChange:me=>n(me.target.value),className:"flex-1"}),e.jsxs($,{onClick:()=>R.mutate(t),disabled:!t||t.length<10||R.isPending,children:[R.isPending?e.jsx(yo,{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(zs,{open:r,onOpenChange:me=>{Y.isPending||a(me)},children:e.jsxs(Rs,{className:"sm:max-w-lg",children:[e.jsxs(Vs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(Ix,{className:"h-5 w-5 text-emerald-600"}),"Sync Preview"]}),e.jsx(Cr,{children:"Review what will happen when you sync your contacts."})]}),o&&(()=>{const me=oe==="pull_only"?0:o.to_push,Q=oe==="push_only"?0:o.to_pull;return e.jsxs("div",{className:"space-y-4",children:[e.jsx(T4e,{value:oe,onChange:g,size:"sm"}),o.owner_filter_active&&e.jsxs("div",{className:"rounded-md border border-emerald-200 bg-emerald-50 p-2 text-xs text-emerald-900 flex items-start gap-2",children:[e.jsx(ck,{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 ${oe==="pull_only"?"opacity-40":""}`,children:[e.jsx("p",{className:"text-2xl font-bold text-emerald-600",children:me}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center justify-center gap-1",children:[e.jsx(ap,{className:"h-3 w-3"})," Push to BoldTrail"]})]}),e.jsxs("div",{className:`rounded-lg border p-3 text-center ${oe==="push_only"?"opacity-40":""}`,children:[e.jsx("p",{className:"text-2xl font-bold text-blue-600",children:Q}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center justify-center gap-1",children:[e.jsx(nx,{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(Xn,{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"]}),Y.isPending&&e.jsxs("div",{className:"space-y-2 py-2",children:[e.jsx(ho,{value:v||10,className:"h-2"}),e.jsx("p",{className:"text-xs text-muted-foreground text-center",children:x||"Sync in progress..."})]}),me>0&&e.jsxs(h1,{open:d,onOpenChange:u,children:[e.jsx(m1,{asChild:!0,children:e.jsxs($,{variant:"ghost",size:"sm",className:"w-full justify-between text-xs",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ap,{className:"h-3 w-3 text-emerald-600"}),me," contacts to push to BoldTrail"]}),e.jsx(Go,{className:`h-3 w-3 transition-transform ${d?"rotate-180":""}`})]})}),e.jsx(f1,{children:e.jsxs("div",{className:"rounded border divide-y max-h-40 overflow-y-auto",children:[o.push_preview.map((te,le)=>e.jsxs("div",{className:"px-3 py-1.5 text-xs flex justify-between",children:[e.jsx("span",{className:"font-medium",children:te.name||"No name"}),e.jsx("span",{className:"text-muted-foreground",children:te.email})]},le)),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"]})]})})]}),Q>0&&e.jsxs(h1,{open:h,onOpenChange:m,children:[e.jsx(m1,{asChild:!0,children:e.jsxs($,{variant:"ghost",size:"sm",className:"w-full justify-between text-xs",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(nx,{className:"h-3 w-3 text-blue-600"}),Q," contacts to pull from BoldTrail"]}),e.jsx(Go,{className:`h-3 w-3 transition-transform ${h?"rotate-180":""}`})]})}),e.jsx(f1,{children:e.jsxs("div",{className:"rounded border divide-y max-h-40 overflow-y-auto",children:[o.pull_preview.map((te,le)=>e.jsxs("div",{className:"px-3 py-1.5 text-xs flex justify-between",children:[e.jsx("span",{className:"font-medium",children:te.name||"No name"}),e.jsx("span",{className:"text-muted-foreground",children:te.email})]},le)),o.to_pull>20&&e.jsxs("div",{className:"px-3 py-1.5 text-xs text-muted-foreground text-center",children:["...and ",o.to_pull-20," more"]})]})})]}),me===0&&Q===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($,{variant:"outline",onClick:()=>a(!1),disabled:Y.isPending,children:"Cancel"}),e.jsxs($,{onClick:()=>Y.mutate(),disabled:Y.isPending||me===0&&Q===0,className:"gap-2",children:[Y.isPending?e.jsx(yo,{className:"h-4 w-4 animate-spin"}):e.jsx(Ix,{className:"h-4 w-4"}),Y.isPending?"Syncing...":"Sync Now"]})]})]})})()]})}),e.jsx(zs,{open:i,onOpenChange:l,children:e.jsxs(Rs,{className:"sm:max-w-2xl p-0 overflow-hidden",children:[e.jsx(Vs,{className:"p-6 pb-0",children:e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(Ix,{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"})})]})})]})}const p9=async s=>{const{data:t,error:n}=await V.functions.invoke("lofty-sync",{body:s});if(n)throw new Error(n.message);if(t!=null&&t.error)throw new Error(typeof t.error=="string"?t.error:JSON.stringify(t.error));return t};function bDn(){const s=ls(),[t,n]=k.useState(""),[r,a]=k.useState(""),[i,l]=k.useState(!1),[o,c]=k.useState(0),[d,u]=k.useState(null),[h,m]=k.useState(null),{data:p,isLoading:g}=pt({queryKey:["lofty-status"],queryFn:async()=>await p9({action:"status"})}),x=()=>s.invalidateQueries({queryKey:["lofty-status"]}),y=Nt({mutationFn:async()=>p9({action:"save_token",api_token:t.trim()}),onSuccess:M=>{ae.success(M!=null&&M.contact_count?`Connected to Lofty — ${M.contact_count} contacts found`:"Connected to Lofty"),n(""),x()},onError:M=>ae.error(M.message)}),v=Nt({mutationFn:async()=>p9({action:"disconnect"}),onSuccess:()=>{ae.success("Lofty disconnected"),x()},onError:M=>ae.error(M.message)}),_=Nt({mutationFn:async M=>p9({action:"save_settings",...M}),onSuccess:()=>x(),onError:M=>ae.error(M.message)}),j=Nt({mutationFn:async()=>p9({action:"detect_owner"}),onSuccess:M=>{const I=(M==null?void 0:M.candidates)||[];m(I),I.length===0?ae.info("No assigned-agent IDs found on your Lofty contacts."):I.length===1?(_.mutate({lofty_user_id:I[0].id}),ae.success(`Using Lofty agent ID ${I[0].id}`)):ae.success("Pick which Lofty agent ID is yours below.")},onError:M=>ae.error(M.message)}),C=async()=>{l(!0),c(2),u("Starting Lofty sync…");try{let M="start",I=0,P=null,R=0;for(;M&&R<400;){R++;const O=await p9({action:"sync",phase:M,offset:I,sync_log_id:P});P=O.sync_log_id||P,O.progress&&u(O.progress),c(B=>Math.min(95,B+4)),M=O.next_phase,I=O.next_offset||0,M||(c(100),u(O.message||"Sync complete"),ae.success(O.message||"Lofty sync complete"))}}catch(M){ae.error(M.message||"Lofty sync failed"),u(null)}finally{l(!1),setTimeout(()=>c(0),2500),x()}},A=!!(p!=null&&p.connected);return e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs(Yt,{className:"flex items-center gap-2",children:["Lofty",A?e.jsxs(qe,{variant:"secondary",className:"gap-1",children:[e.jsx(nl,{className:"h-3 w-3"})," Connected"]}):e.jsx(qe,{variant:"outline",children:"Not connected"})]}),e.jsx(vr,{children:"Sync your Lofty (formerly Chime) contacts — names, emails, phones, address, source, stage, tags and notes — into Agent OS."})]}),A&&e.jsxs(oc,{children:[e.jsx(_g,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon","aria-label":"Disconnect Lofty",children:e.jsx(Un,{className:"h-4 w-4"})})}),e.jsxs(Ql,{children:[e.jsxs(Jl,{children:[e.jsx(tc,{children:"Disconnect Lofty?"}),e.jsx(sc,{children:"Your API key and sync settings will be removed. Contacts already imported into Agent OS stay put."})]}),e.jsxs(ec,{children:[e.jsx(nc,{children:"Cancel"}),e.jsx(Vl,{onClick:()=>v.mutate(),children:"Disconnect"})]})]})]})]})}),e.jsx(De,{className:"space-y-5",children:g?e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(Jt,{className:"h-4 w-4 animate-spin"})," Loading…"]}):A?e.jsxs("div",{className:"space-y-5",children:[e.jsx(T4e,{value:(p==null?void 0:p.sync_direction)||"pull_only",onChange:M=>_.mutate({sync_direction:M}),size:"sm"}),e.jsxs("div",{className:"space-y-3 rounded-lg border p-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Only my contacts"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Skip team/brokerage contacts assigned to other Lofty agents."})]}),e.jsx(On,{checked:!!(p!=null&&p.sync_only_owned),onCheckedChange:M=>_.mutate({sync_only_owned:M})})]}),(p==null?void 0:p.sync_only_owned)&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs($,{size:"sm",variant:"outline",onClick:()=>j.mutate(),disabled:j.isPending,children:[j.isPending?e.jsx(Jt,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(Xn,{className:"h-3.5 w-3.5"}),"Detect my Lofty agent ID"]}),(p==null?void 0:p.lofty_user_id)&&e.jsxs(qe,{variant:"secondary",children:["Agent ID ",p.lofty_user_id]})]}),h&&h.length>1&&e.jsx("div",{className:"flex flex-wrap gap-2",children:h.map(M=>e.jsxs($,{size:"sm",variant:(p==null?void 0:p.lofty_user_id)===M.id?"default":"outline",onClick:()=>_.mutate({lofty_user_id:M.id}),children:[M.id," · ",M.count," contacts"]},M.id))})]}),e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Import notes"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Pull each contact's Lofty notes into their Agent OS notes (deduped)."})]}),e.jsx(On,{checked:!!(p!=null&&p.import_notes),onCheckedChange:M=>_.mutate({import_notes:M})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{htmlFor:"lofty-tags",className:"text-sm",children:"Tag filter (optional)"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(be,{id:"lofty-tags",placeholder:((p==null?void 0:p.pull_tag_filter)||[]).join(", ")||"e.g. Sphere, Buyer",value:r,onChange:M=>a(M.target.value)}),e.jsx($,{variant:"outline",onClick:()=>_.mutate({pull_tag_filter:r.split(",").map(M=>M.trim()).filter(Boolean)}),children:"Save"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Leave empty to import every contact. Comma-separated Lofty tags."})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs($,{onClick:C,disabled:i,children:[i?e.jsx(Jt,{className:"h-4 w-4 animate-spin"}):e.jsx(yo,{className:"h-4 w-4"}),i?"Syncing…":"Sync Now"]}),(p==null?void 0:p.last_sync_at)&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["Last sync ",new Date(p.last_sync_at).toLocaleString("en-US",{timeZone:"America/New_York"})]})]}),(i||o>0)&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(ho,{value:o}),d&&e.jsx("p",{className:"text-xs text-muted-foreground",children:d})]}),(p==null?void 0:p.last_sync_message)&&!i&&e.jsx("p",{className:"text-xs text-muted-foreground",children:p.last_sync_message})]}),((p==null?void 0:p.logs)||[]).length>0&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("p",{className:"text-sm font-medium",children:"Recent syncs"}),e.jsx("div",{className:"space-y-1",children:p.logs.map(M=>e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 rounded-md border px-3 py-2 text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:new Date(M.created_at).toLocaleString("en-US",{timeZone:"America/New_York"})}),e.jsxs("span",{children:[M.contacts_pulled," imported · ",M.contacts_pushed," pushed ·"," ",M.contacts_skipped," skipped"]}),e.jsx(qe,{variant:M.status==="completed"?"secondary":"destructive",children:M.status})]},M.id))})]})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{htmlFor:"lofty-key",children:"Lofty API Key"}),e.jsx(be,{id:"lofty-key",type:"password",placeholder:"Paste your Lofty API key",value:t,onChange:M=>n(M.target.value),autoComplete:"off"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["In Lofty go to ",e.jsx("strong",{children:"Settings → Integrations → API Key Management"})," and create a key with contact access."]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs($,{onClick:()=>y.mutate(),disabled:t.trim().length<10||y.isPending,children:[y.isPending?e.jsx(Jt,{className:"h-4 w-4 animate-spin"}):e.jsx(k2,{className:"h-4 w-4"}),"Connect Lofty"]}),e.jsx($,{variant:"ghost",size:"sm",asChild:!0,children:e.jsxs("a",{href:"https://developer.lofty.com/",target:"_blank",rel:"noreferrer",children:["Lofty API docs ",e.jsx(Ir,{className:"ml-1 h-3 w-3"})]})})]})]})})]})}function _Dn(){const s=ls(),[t,n]=k.useState(""),[r,a]=k.useState(!1),[i,l]=k.useState(0),[o,c]=k.useState(null),{data:d,isLoading:u}=pt({queryKey:["fub-status"],queryFn:async()=>{const{data:x,error:y}=await V.functions.invoke("followupboss-sync",{body:{action:"status"}});if(y)throw y;return x}}),h=Nt({mutationFn:async x=>{const{data:y,error:v}=await V.functions.invoke("followupboss-sync",{body:{action:"save_token",api_key:x}});if(v)throw v;if(y!=null&&y.error)throw new Error(y.error);return y},onSuccess:()=>{ae.success("Connected to Follow Up Boss"),n(""),s.invalidateQueries({queryKey:["fub-status"]})},onError:x=>ae.error(x.message)}),m=Nt({mutationFn:async()=>{const{error:x}=await V.functions.invoke("followupboss-sync",{body:{action:"disconnect"}});if(x)throw x},onSuccess:()=>{ae.success("Disconnected"),s.invalidateQueries({queryKey:["fub-status"]})}}),p=Nt({mutationFn:async x=>{const{error:y}=await V.functions.invoke("followupboss-sync",{body:{action:"set_direction",sync_direction:x}});if(y)throw y},onSuccess:()=>s.invalidateQueries({queryKey:["fub-status"]})}),g=async()=>{a(!0),l(0),c("Pulling from FUB…");let x=0,y=0,v=0,_=0;try{for(;;){const{data:M,error:I}=await V.functions.invoke("followupboss-sync",{body:{action:"sync",offset:x}});if(I)throw I;if(M!=null&&M.error)throw new Error(M.error);y+=M.chunk_created||0,v+=M.chunk_updated||0,_+=M.chunk_skipped||0,x=M.next_offset;const P=M.total?Math.min(100,Math.round(x/M.total*100)):100;if(l(P),c(`Pulling · ${x} / ${M.total||"?"}`),M.done)break;await new Promise(R=>setTimeout(R,400))}let j=0,C=0;if((d==null?void 0:d.sync_direction)==="bidirectional"){let M=0;for(l(0),c("Pushing to FUB…");;){const{data:I,error:P}=await V.functions.invoke("followupboss-sync",{body:{action:"push",offset:M}});if(P)throw P;if(I!=null&&I.error)throw new Error(I.error);j+=I.chunk_pushed||0,C+=I.chunk_failed||0,M=I.next_offset;const R=I.total?Math.min(100,Math.round(M/I.total*100)):100;if(l(R),c(`Pushing · ${M} / ${I.total||"?"}`),I.done)break;await new Promise(O=>setTimeout(O,400))}}const A=j||C?` · pushed ${j}${C?`, ${C} failed`:""}`:"";ae.success(`Sync complete · ${y} new, ${v} updated${_?`, ${_} skipped`:""}${A}`),s.invalidateQueries({queryKey:["fub-status"]})}catch(j){ae.error(j.message||"Sync failed")}finally{a(!1),setTimeout(()=>{l(0),c(null)},2500)}};return e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsx("div",{className:"flex items-start justify-between gap-3",children:e.jsxs("div",{children:[e.jsxs(Yt,{className:"flex items-center gap-2",children:[e.jsx(k2,{className:"h-5 w-5 text-primary"}),"Follow Up Boss",(d==null?void 0:d.connected)&&e.jsxs(qe,{variant:"default",className:"ml-1",children:[e.jsx(nl,{className:"h-3 w-3 mr-1"})," Connected"]})]}),e.jsx(vr,{children:"Sync your Follow Up Boss contacts into Agent OS."})]})})}),e.jsx(De,{className:"space-y-4",children:u?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading…"}):d!=null&&d.connected?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid sm:grid-cols-2 gap-3 text-sm",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground",children:"Last sync"}),e.jsx("p",{className:"font-medium",children:d.last_sync_at?new Date(d.last_sync_at).toLocaleString():"Never"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground",children:"FUB contacts"}),e.jsx("p",{className:"font-medium",children:d.fub_contact_count??"—"})]})]}),d.last_sync_status==="error"&&e.jsx("p",{className:"text-sm text-destructive",children:d.last_sync_message}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border px-3 py-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Two-way sync"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Off = pull from FUB only. On = also push new Agent OS contacts to FUB."})]}),e.jsx(On,{checked:d.sync_direction==="bidirectional",onCheckedChange:x=>p.mutate(x?"bidirectional":"pull_only"),disabled:r||p.isPending})]}),o&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(ho,{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($,{onClick:g,disabled:r,children:[e.jsx(yo,{className:`h-4 w-4 mr-2 ${r?"animate-spin":""}`}),r?"Syncing…":"Sync Now"]}),e.jsxs(oc,{children:[e.jsx(_g,{asChild:!0,children:e.jsxs($,{variant:"outline",disabled:r,children:[e.jsx(Un,{className:"h-4 w-4 mr-2"})," Disconnect"]})}),e.jsxs(Ql,{children:[e.jsxs(Jl,{children:[e.jsx(tc,{children:"Disconnect Follow Up Boss?"}),e.jsx(sc,{children:"Your API key will be removed. Synced contacts stay in Agent OS."})]}),e.jsxs(ec,{children:[e.jsx(nc,{children:"Cancel"}),e.jsx(Vl,{onClick:()=>m.mutate(),children:"Disconnect"})]})]})]})]})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(re,{htmlFor:"fub-key",children:"Follow Up Boss API Key"}),e.jsx(be,{id:"fub-key",type:"password",placeholder:"fka_live_...",value:t,onChange:x=>n(x.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(Ir,{className:"h-3 w-3"})]})]})]}),e.jsx($,{onClick:()=>h.mutate(t),disabled:!t.trim()||h.isPending,children:h.isPending?"Connecting…":"Connect"})]})})]})}function wDn(){var H;const s=ls(),[t,n]=k.useState(""),[r,a]=k.useState(""),[i,l]=k.useState(!1),[o,c]=k.useState(0),[d,u]=k.useState(null),[h,m]=k.useState(!1),[p,g]=k.useState(null),[x,y]=k.useState(!1),[v,_]=k.useState(new Set),{data:j,isLoading:C}=pt({queryKey:["cloze-status"],queryFn:async()=>{const{data:Y,error:se}=await V.functions.invoke("cloze-sync",{body:{action:"status"}});if(se)throw se;return Y}}),A=Nt({mutationFn:async()=>{const{data:Y,error:se}=await V.functions.invoke("cloze-sync",{body:{action:"save_token",api_key:t.trim(),account_email:r.trim()}});if(se)throw se;if(Y!=null&&Y.error)throw new Error(Y.error);return Y},onSuccess:()=>{ae.success("Connected to Cloze"),n(""),a(""),s.invalidateQueries({queryKey:["cloze-status"]})},onError:Y=>ae.error(Y.message)}),M=Nt({mutationFn:async()=>{const{error:Y}=await V.functions.invoke("cloze-sync",{body:{action:"disconnect"}});if(Y)throw Y},onSuccess:()=>{ae.success("Cloze disconnected"),s.invalidateQueries({queryKey:["cloze-status"]})}}),I=Nt({mutationFn:async Y=>{const{error:se}=await V.functions.invoke("cloze-sync",{body:{action:"set_direction",sync_direction:Y}});if(se)throw se},onSuccess:()=>s.invalidateQueries({queryKey:["cloze-status"]})}),P=Nt({mutationFn:async Y=>{const{error:se}=await V.functions.invoke("cloze-sync",{body:{action:"set_scope",...Y}});if(se)throw se},onSuccess:()=>s.invalidateQueries({queryKey:["cloze-status"]})}),R=async()=>{y(!0);try{const{data:Y,error:se}=await V.functions.invoke("cloze-sync",{body:{action:"list_segments"}});if(se)throw se;if(Y!=null&&Y.error)throw new Error(Y.error);g(Y.segments||[]),_(new Set((j==null?void 0:j.selected_segments)||[])),m(!0)}catch(Y){ae.error(Y.message||"Failed to load segments")}finally{y(!1)}},O=async()=>{const Y=Array.from(v);await P.mutateAsync({sync_scope:"segments",selected_segments:Y}),ae.success(`Saved · ${Y.length} segment(s) selected`),m(!1)},B=async()=>{const Y=(j==null?void 0:j.sync_direction)||"pull_only";l(!0),c(0);try{if(Y==="pull_only"||Y==="bidirectional"){u("Pulling from Cloze…");let se=0,ee=0,oe=0;for(;;){const{data:me,error:Q}=await V.functions.invoke("cloze-sync",{body:{action:"sync",offset:se}});if(Q)throw Q;if(me!=null&&me.error)throw new Error(me.error);if(ee+=me.chunk_created||0,oe+=me.chunk_updated||0,se=me.next_offset,u(`Pulling · ${ee+oe} contacts processed`),c(me.done?100:Math.min(95,(ee+oe)%200/2)),me.done)break;await new Promise(te=>setTimeout(te,300))}ae.success(`Pulled · ${ee} new, ${oe} updated`)}if(Y==="push_only"||Y==="bidirectional"){c(0),u("Pushing to Cloze…");let se=0,ee=0,oe=0;for(;;){const{data:me,error:Q}=await V.functions.invoke("cloze-sync",{body:{action:"push",offset:se}});if(Q)throw Q;if(me!=null&&me.error)throw new Error(me.error);ee+=me.chunk_pushed||0,oe+=me.chunk_failed||0,se=me.next_offset;const te=me.total?Math.min(100,Math.round(se/me.total*100)):100;if(c(te),u(`Pushing · ${se} / ${me.total||"?"}`),me.done)break;await new Promise(le=>setTimeout(le,300))}ae.success(`Pushed · ${ee}${oe?`, ${oe} failed`:""}`)}s.invalidateQueries({queryKey:["cloze-status"]})}catch(se){ae.error(se.message||"Sync failed")}finally{l(!1),setTimeout(()=>{c(0),u(null)},2e3)}},U=(j==null?void 0:j.sync_scope)||"all",G=((H=j==null?void 0:j.selected_segments)==null?void 0:H.length)||0;return e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsx("div",{className:"flex items-start justify-between gap-3",children:e.jsxs("div",{children:[e.jsxs(Yt,{className:"flex items-center gap-2",children:[e.jsx(k2,{className:"h-5 w-5 text-primary"}),"Cloze",(j==null?void 0:j.connected)&&e.jsxs(qe,{variant:"default",className:"ml-1",children:[e.jsx(nl,{className:"h-3 w-3 mr-1"})," Connected"]})]}),e.jsx(vr,{children:"Sync contacts between Cloze and Agent OS using your personal Cloze API key."})]})})}),e.jsx(De,{className:"space-y-4",children:C?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading…"}):j!=null&&j.connected?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid sm:grid-cols-2 gap-3 text-sm",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground",children:"Account"}),e.jsx("p",{className:"font-medium break-all",children:j.account_email})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground",children:"Last sync"}),e.jsx("p",{className:"font-medium",children:j.last_sync_at?new Date(j.last_sync_at).toLocaleString():"Never"})]})]}),j.last_sync_status==="error"&&e.jsx("p",{className:"text-sm text-destructive",children:j.last_sync_message}),e.jsx("div",{className:"rounded-lg border px-3 py-2 space-y-2",children:e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Sync direction"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Choose which way contacts should flow."})]}),e.jsxs(bs,{value:j.sync_direction||"pull_only",onValueChange:Y=>I.mutate(Y),disabled:i||I.isPending,children:[e.jsx(ys,{className:"w-[180px]",children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"pull_only",children:"Pull from Cloze"}),e.jsx(We,{value:"push_only",children:"Push to Cloze"}),e.jsx(We,{value:"bidirectional",children:"Two-way sync"})]})]})]})}),e.jsxs("div",{className:"rounded-lg border px-3 py-2 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"What to sync"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:U==="all"?"All Cloze contacts.":`${G} segment${G===1?"":"s"} selected.`})]}),e.jsxs(bs,{value:U,onValueChange:Y=>{Y==="all"?P.mutate({sync_scope:"all",selected_segments:[]}):(P.mutate({sync_scope:"segments",selected_segments:j.selected_segments||[]}),R())},disabled:i||P.isPending,children:[e.jsx(ys,{className:"w-[180px]",children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"all",children:"All contacts"}),e.jsx(We,{value:"segments",children:"Selected segments"})]})]})]}),U==="segments"&&e.jsxs("div",{children:[e.jsxs($,{variant:"outline",size:"sm",onClick:R,disabled:x,children:[e.jsx(eY,{className:"h-4 w-4 mr-2"}),x?"Loading segments…":"Choose segments"]}),h&&p&&e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsxs("div",{className:"max-h-96 overflow-y-auto rounded-md border divide-y",children:[p.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground p-3",children:"No segments found in your Cloze account."}),p.map(Y=>{const se=v.has(Y.id);return e.jsxs("label",{className:"flex items-center gap-3 p-2 cursor-pointer hover:bg-muted/50",children:[e.jsx(Li,{checked:se,onCheckedChange:ee=>{const oe=new Set(v);ee?oe.add(Y.id):oe.delete(Y.id),_(oe)}}),e.jsx("span",{className:"flex-1 text-sm",children:Y.name}),Y.count!=null&&e.jsx(qe,{variant:"secondary",className:"text-xs",children:Y.count})]},Y.id)})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs($,{size:"sm",onClick:O,disabled:P.isPending,children:["Save selection (",v.size,")"]}),e.jsx($,{size:"sm",variant:"ghost",onClick:()=>m(!1),children:"Cancel"})]})]})]})]}),d&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(ho,{value:o}),e.jsx("p",{className:"text-xs text-muted-foreground",children:d})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(oc,{children:[e.jsx(_g,{asChild:!0,children:e.jsxs($,{disabled:i,children:[e.jsx(yo,{className:`h-4 w-4 mr-2 ${i?"animate-spin":""}`}),i?"Syncing…":"Sync Now"]})}),e.jsxs(Ql,{children:[e.jsxs(Jl,{children:[e.jsx(tc,{children:"Preview sync"}),e.jsx(sc,{asChild:!0,children:e.jsx(jDn,{segments:p})})]}),e.jsxs(ec,{children:[e.jsx(nc,{children:"Cancel"}),e.jsx(Vl,{onClick:B,children:"Start Sync"})]})]})]}),e.jsxs(oc,{children:[e.jsx(_g,{asChild:!0,children:e.jsxs($,{variant:"outline",disabled:i,children:[e.jsx(Un,{className:"h-4 w-4 mr-2"})," Disconnect"]})}),e.jsxs(Ql,{children:[e.jsxs(Jl,{children:[e.jsx(tc,{children:"Disconnect Cloze?"}),e.jsx(sc,{children:"Your API key will be removed. Contacts already synced will remain."})]}),e.jsxs(ec,{children:[e.jsx(nc,{children:"Cancel"}),e.jsx(Vl,{onClick:()=>M.mutate(),children:"Disconnect"})]})]})]})]})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(re,{htmlFor:"cloze-email",children:"Cloze Account Email"}),e.jsx(be,{id:"cloze-email",type:"email",placeholder:"you@example.com",value:r,onChange:Y=>a(Y.target.value)})]}),e.jsxs("div",{children:[e.jsx(re,{htmlFor:"cloze-key",children:"Cloze API Key"}),e.jsx(be,{id:"cloze-key",type:"password",placeholder:"Your personal Cloze API key",value:t,onChange:Y=>n(Y.target.value)}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1 flex items-center gap-1",children:["Generate one in Cloze → Settings → API Keys.",e.jsxs("a",{href:"https://app.cloze.com/app/#/settings/apikeys",target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-0.5 text-primary hover:underline",children:["Open ",e.jsx(Ir,{className:"h-3 w-3"})]})]})]}),e.jsx($,{onClick:()=>A.mutate(),disabled:!t.trim()||!r.trim()||A.isPending,children:A.isPending?"Connecting…":"Connect Cloze"})]})})]})}function jDn({segments:s}){var h;const[t,n]=k.useState(!0),[r,a]=k.useState(null),[i,l]=k.useState(null);if(k.useEffect(()=>{(async()=>{try{const{data:m,error:p}=await V.functions.invoke("cloze-sync",{body:{action:"preview"}});if(p)throw p;if(m!=null&&m.error)throw new Error(m.error);a(m)}catch(m){l(m.message||"Could not load preview")}finally{n(!1)}})()},[]),t)return e.jsx("span",{className:"text-sm",children:"Calculating…"});if(i)return e.jsx("span",{className:"text-sm text-destructive",children:i});const o=new Map((s||[]).map(m=>[m.id,m.name])),c=r.total_incoming??0,d=r.already_synced??0,u=Math.max(0,c-d);return e.jsxs("div",{className:"space-y-3 text-sm text-foreground",children:[e.jsxs("div",{className:"rounded-md border p-3 space-y-1",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsxs("span",{children:["Contacts in Cloze (",r.scope==="segments"?"selected segments":"all",")"]}),e.jsx("strong",{children:c.toLocaleString()})]}),e.jsxs("div",{className:"flex justify-between text-muted-foreground",children:[e.jsx("span",{children:"Already linked to Cloze in your CRM"}),e.jsx("span",{children:d.toLocaleString()})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{children:"Estimated new contacts"}),e.jsxs("strong",{children:["~",u.toLocaleString()]})]})]}),r.scope==="segments"&&((h=r.segment_counts)==null?void 0:h.length)>0&&e.jsx("div",{className:"rounded-md border p-3 space-y-1 max-h-40 overflow-auto",children:r.segment_counts.map(m=>e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsx("span",{children:o.get(m.id)||m.id}),e.jsx("span",{className:"text-muted-foreground",children:m.total})]},m.id))}),e.jsx("p",{className:"text-xs text-muted-foreground",children:r.note})]})}function NDn(){const s=ls(),[t,n]=k.useState(""),[r,a]=k.useState(!1),[i,l]=k.useState(0),[o,c]=k.useState(null),{data:d,isLoading:u}=pt({queryKey:["boomtown-status"],queryFn:async()=>{const{data:x,error:y}=await V.functions.invoke("boomtown-sync",{body:{action:"status"}});if(y)throw y;return x}}),h=Nt({mutationFn:async x=>{const{data:y,error:v}=await V.functions.invoke("boomtown-sync",{body:{action:"save_token",api_key:x}});if(v)throw v;if(y!=null&&y.error)throw new Error(y.error);return y},onSuccess:()=>{ae.success("Connected to Boomtown"),n(""),s.invalidateQueries({queryKey:["boomtown-status"]})},onError:x=>ae.error(x.message)}),m=Nt({mutationFn:async()=>{const{error:x}=await V.functions.invoke("boomtown-sync",{body:{action:"disconnect"}});if(x)throw x},onSuccess:()=>{ae.success("Disconnected"),s.invalidateQueries({queryKey:["boomtown-status"]})}}),p=Nt({mutationFn:async x=>{const{error:y}=await V.functions.invoke("boomtown-sync",{body:{action:"set_direction",sync_direction:x}});if(y)throw y},onSuccess:()=>s.invalidateQueries({queryKey:["boomtown-status"]})}),g=async()=>{a(!0),l(0),c("Pulling from Boomtown…");let x=0,y=0,v=0,_=0;try{for(;;){const{data:M,error:I}=await V.functions.invoke("boomtown-sync",{body:{action:"sync",offset:x}});if(I)throw I;if(M!=null&&M.error)throw new Error(M.error);y+=M.chunk_created||0,v+=M.chunk_updated||0,_+=M.chunk_skipped||0,x=M.next_offset;const P=M.total?Math.min(100,Math.round(x/M.total*100)):100;if(l(P),c(`Pulling · ${x} / ${M.total||"?"}`),M.done)break;await new Promise(R=>setTimeout(R,400))}let j=0,C=0;if((d==null?void 0:d.sync_direction)==="bidirectional"){let M=0;for(l(0),c("Pushing to Boomtown…");;){const{data:I,error:P}=await V.functions.invoke("boomtown-sync",{body:{action:"push",offset:M}});if(P)throw P;if(I!=null&&I.error)throw new Error(I.error);j+=I.chunk_pushed||0,C+=I.chunk_failed||0,M=I.next_offset;const R=I.total?Math.min(100,Math.round(M/I.total*100)):100;if(l(R),c(`Pushing · ${M} / ${I.total||"?"}`),I.done)break;await new Promise(O=>setTimeout(O,400))}}const A=j||C?` · pushed ${j}${C?`, ${C} failed`:""}`:"";ae.success(`Sync complete · ${y} new, ${v} updated${_?`, ${_} skipped`:""}${A}`),s.invalidateQueries({queryKey:["boomtown-status"]})}catch(j){ae.error(j.message||"Sync failed")}finally{a(!1),setTimeout(()=>{l(0),c(null)},2500)}};return e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsx("div",{className:"flex items-start justify-between gap-3",children:e.jsxs("div",{children:[e.jsxs(Yt,{className:"flex items-center gap-2",children:[e.jsx(k2,{className:"h-5 w-5 text-primary"}),"Boomtown",(d==null?void 0:d.connected)&&e.jsxs(qe,{variant:"default",className:"ml-1",children:[e.jsx(nl,{className:"h-3 w-3 mr-1"})," Connected"]})]}),e.jsx(vr,{children:"Sync your Boomtown contacts into Agent OS."})]})})}),e.jsx(De,{className:"space-y-4",children:u?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading…"}):d!=null&&d.connected?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid sm:grid-cols-2 gap-3 text-sm",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground",children:"Last sync"}),e.jsx("p",{className:"font-medium",children:d.last_sync_at?new Date(d.last_sync_at).toLocaleString():"Never"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground",children:"Boomtown contacts"}),e.jsx("p",{className:"font-medium",children:d.boomtown_contact_count??"—"})]})]}),d.last_sync_status==="error"&&e.jsx("p",{className:"text-sm text-destructive",children:d.last_sync_message}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border px-3 py-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Two-way sync"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Off = pull from Boomtown only. On = also push new Agent OS contacts to Boomtown."})]}),e.jsx(On,{checked:d.sync_direction==="bidirectional",onCheckedChange:x=>p.mutate(x?"bidirectional":"pull_only"),disabled:r||p.isPending})]}),o&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(ho,{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($,{onClick:g,disabled:r,children:[e.jsx(yo,{className:`h-4 w-4 mr-2 ${r?"animate-spin":""}`}),r?"Syncing…":"Sync Now"]}),e.jsxs(oc,{children:[e.jsx(_g,{asChild:!0,children:e.jsxs($,{variant:"outline",disabled:r,children:[e.jsx(Un,{className:"h-4 w-4 mr-2"})," Disconnect"]})}),e.jsxs(Ql,{children:[e.jsxs(Jl,{children:[e.jsx(tc,{children:"Disconnect Boomtown?"}),e.jsx(sc,{children:"Your API key will be removed. Synced contacts stay in Agent OS."})]}),e.jsxs(ec,{children:[e.jsx(nc,{children:"Cancel"}),e.jsx(Vl,{onClick:()=>m.mutate(),children:"Disconnect"})]})]})]})]})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(re,{htmlFor:"boomtown-key",children:"Boomtown API Key"}),e.jsx(be,{id:"boomtown-key",type:"password",placeholder:"Paste your Boomtown Ambassador API key",value:t,onChange:x=>n(x.target.value)}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Requires a Boomtown Ambassador/Partner API key with contact access."})]}),e.jsxs("div",{className:"rounded-lg border bg-muted/40 p-3 space-y-2",children:[e.jsx("p",{className:"text-sm font-medium",children:"How to get your API key"}),e.jsxs("ol",{className:"text-xs text-muted-foreground space-y-1 list-decimal list-inside",children:[e.jsx("li",{children:"Log in to Boomtown as an admin or manager."}),e.jsxs("li",{children:["Go to ",e.jsx("strong",{children:"Settings → Integrations → API Keys"}),"."]}),e.jsxs("li",{children:["Generate a key with ",e.jsx("strong",{children:"Contact read/write"})," scope."]}),e.jsx("li",{children:"Copy the key and paste it above, then click Connect."})]}),e.jsxs("a",{href:"https://backoffice.boomtownroi.com/#/settings/integrations",target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-1 text-xs text-primary hover:underline",children:["Open Boomtown settings ",e.jsx(Ir,{className:"h-3 w-3"})]})]}),e.jsx($,{onClick:()=>h.mutate(t),disabled:!t.trim()||h.isPending,children:h.isPending?"Connecting…":"Connect"})]})})]})}function pVt(){const s=Jn(),[t,n]=k.useState(""),[r,a]=k.useState(""),[i,l]=k.useState("Test from ReLevelUp"),[o,c]=k.useState(!1),{data:d,isLoading:u}=pt({queryKey:["ses-config"],queryFn:async()=>{const p=await iQ();return(await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/ses-send-campaign",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${p}`},body:JSON.stringify({action:"check_config"})})).json()}}),h=async()=>{if(!t||!r){ae.error("Please fill in From and To email addresses");return}c(!0);try{const p=await iQ(),x=await(await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/ses-send-campaign",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${p}`},body:JSON.stringify({action:"test_send",to:t,from_email:r,subject:i,body_html:"

Test Email

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

If you received this, SES is configured correctly! 🎉

"})})).json();x.success?ae.success(`Test email sent! Message ID: ${x.messageId}`):ae.error(x.error||"Failed to send test email")}catch(p){ae.error(p.message||"Failed to send test email")}finally{c(!1)}},m=(d==null?void 0:d.configured)===!0;return e.jsxs(we,{children:[e.jsx(Vt,{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(pn,{className:"h-5 w-5 text-orange-600"})}),e.jsxs("div",{children:[e.jsx(Yt,{className:"text-lg",children:"Amazon SES — Mass Email"}),e.jsx(vr,{children:"Send bulk email campaigns via Amazon SES"})]})]}),e.jsx(qe,{variant:m?"default":"secondary",children:u?"Checking...":m?e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(nl,{className:"h-3 w-3"})," Connected"]}):e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Ho,{className:"h-3 w-3"})," Not Configured"]})})]})}),m&&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(re,{className:"text-xs",children:"From Email"}),e.jsx(be,{placeholder:"notifications@mail.relevelup.com",value:r,onChange:p=>a(p.target.value),className:"text-sm"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(re,{className:"text-xs",children:"To Email"}),e.jsx(be,{placeholder:"your@email.com",value:t,onChange:p=>n(p.target.value),className:"text-sm"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(re,{className:"text-xs",children:"Subject"}),e.jsx(be,{value:i,onChange:p=>l(p.target.value),className:"text-sm"})]})]}),e.jsxs($,{onClick:h,disabled:o,size:"sm",children:[o?e.jsx(Jt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Wr,{className:"h-4 w-4 mr-2"}),"Send Test"]})]}),e.jsxs($,{onClick:()=>s("/admin/email-campaigns"),className:"w-full",children:[e.jsx(xm,{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)"]})]})]}),!m&&!u&&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 WDe(s){const t=await iQ(),n=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/ses-verify-sender",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(s)}),r=await n.json();if(!n.ok)throw new Error(r.error||"Request failed");return r}function kDn({status:s}){return s==="verified"?e.jsxs(qe,{className:"bg-green-500/10 text-green-700 hover:bg-green-500/20 border-green-500/20",children:[e.jsx(Gr,{className:"h-3 w-3 mr-1"})," Verified"]}):s==="pending"?e.jsxs(qe,{variant:"secondary",children:[e.jsx(sa,{className:"h-3 w-3 mr-1"})," Pending — check inbox"]}):s==="failed"||s==="temporary_failure"?e.jsxs(qe,{variant:"destructive",children:[e.jsx(Ho,{className:"h-3 w-3 mr-1"})," Failed"]}):e.jsxs(qe,{variant:"outline",children:[e.jsx(Ho,{className:"h-3 w-3 mr-1"})," Not started"]})}function gVt({brokerageId:s,onVerifiedSelect:t}){const n=ls(),[r,a]=k.useState(""),[i,l]=k.useState(""),[o,c]=k.useState(!1),[d,u]=k.useState(null),[h,m]=k.useState(null),{data:p,isLoading:g}=pt({queryKey:["brokerage-verified-senders",s],queryFn:async()=>{const{data:_,error:j}=await V.from("brokerage_verified_senders").select("*").eq("brokerage_id",s).order("created_at",{ascending:!1});if(j)throw j;return _||[]}}),x=Nt({mutationFn:async()=>WDe({action:"request_verification",brokerage_id:s,email:r,display_name:i||void 0}),onSuccess:()=>{n.invalidateQueries({queryKey:["brokerage-verified-senders",s]}),ae.success("Verification email sent",{description:`Check ${r} and click the AWS verification link.`}),a(""),l(""),c(!1)},onError:_=>ae.error(_.message)}),y=async _=>{var j,C;u(_.id);try{const A=await WDe({action:"check_status",sender_id:_.id});n.invalidateQueries({queryKey:["brokerage-verified-senders",s]}),((j=A.sender)==null?void 0:j.status)==="verified"?ae.success(`${_.email} is verified! 🎉`):ae.info(`Status: ${((C=A.sender)==null?void 0:C.status)||"unknown"}`)}catch(A){ae.error(A.message)}finally{u(null)}},v=Nt({mutationFn:async _=>WDe({action:"delete",sender_id:_}),onSuccess:()=>{n.invalidateQueries({queryKey:["brokerage-verified-senders",s]}),ae.success("Sender removed"),m(null)},onError:_=>ae.error(_.message)});return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium mb-1",children:"Verified Sender Addresses"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Verify any email address (yours or your brokerage's) so recruiting emails can be sent from that address. Anyone managing this brokerage can use these senders."})]}),g?e.jsx("div",{className:"text-xs text-muted-foreground py-3",children:"Loading…"}):p&&p.length>0?e.jsx("div",{className:"space-y-2",children:p.map(_=>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(pn,{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:_.email}),e.jsx(kDn,{status:_.status})]}),_.display_name&&e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:['"',_.display_name,'"']})]})]}),e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[_.status==="verified"&&t&&e.jsx($,{size:"sm",variant:"outline",onClick:()=>t(_.email),children:"Use"}),_.status!=="verified"&&e.jsx($,{size:"sm",variant:"ghost",onClick:()=>y(_),disabled:d===_.id,title:"Refresh status from AWS",children:d===_.id?e.jsx(Jt,{className:"h-4 w-4 animate-spin"}):e.jsx(yo,{className:"h-4 w-4"})}),e.jsx($,{size:"sm",variant:"ghost",onClick:()=>m(_),className:"text-destructive hover:text-destructive",children:e.jsx(Un,{className:"h-4 w-4"})})]})]},_.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(re,{className:"text-xs",children:"Email Address *"}),e.jsx(be,{type:"email",value:r,onChange:_=>a(_.target.value),placeholder:"broker@yourbrokerage.com",className:"text-sm"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(re,{className:"text-xs",children:"Display Name (optional)"}),e.jsx(be,{value:i,onChange:_=>l(_.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($,{size:"sm",onClick:()=>x.mutate(),disabled:!r.trim()||x.isPending,children:[x.isPending?e.jsx(Jt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(pn,{className:"h-4 w-4 mr-2"}),"Send Verification Email"]}),e.jsx($,{size:"sm",variant:"ghost",onClick:()=>{c(!1),a(""),l("")},children:"Cancel"})]})]}):e.jsxs($,{size:"sm",variant:"outline",onClick:()=>c(!0),children:[e.jsx(nn,{className:"h-4 w-4 mr-1"})," Add Sender Address"]}),e.jsx(oc,{open:!!h,onOpenChange:_=>!_&&m(null),children:e.jsxs(Ql,{children:[e.jsxs(Jl,{children:[e.jsx(tc,{children:"Remove this sender?"}),e.jsxs(sc,{children:['"',h==null?void 0:h.email,`" will be removed from your verified senders and from Amazon SES. You'd need to verify it again to use it.`]})]}),e.jsxs(ec,{children:[e.jsx(nc,{children:"Cancel"}),e.jsx(Vl,{onClick:()=>h&&v.mutate(h.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Remove"})]})]})})]})}async function KDe(s){const t=await iQ(),n=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/ses-verify-sender",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t}`},body:JSON.stringify(s)}),r=await n.json();if(!n.ok)throw new Error(r.error||"Request failed");return r}function SDn({status:s}){return s==="verified"?e.jsxs(qe,{className:"bg-green-500/10 text-green-700 hover:bg-green-500/20 border-green-500/20",children:[e.jsx(Gr,{className:"h-3 w-3 mr-1"})," Verified"]}):s==="pending"?e.jsxs(qe,{variant:"secondary",children:[e.jsx(sa,{className:"h-3 w-3 mr-1"})," Pending — check inbox"]}):s==="failed"||s==="temporary_failure"?e.jsxs(qe,{variant:"destructive",children:[e.jsx(Ho,{className:"h-3 w-3 mr-1"})," Failed"]}):e.jsxs(qe,{variant:"outline",children:[e.jsx(Ho,{className:"h-3 w-3 mr-1"})," Not started"]})}function CDn({userId:s,onVerifiedSelect:t}){const n=ls(),[r,a]=k.useState(""),[i,l]=k.useState(""),[o,c]=k.useState(!1),[d,u]=k.useState(null),[h,m]=k.useState(null),{data:p,isLoading:g}=pt({queryKey:["user-verified-senders",s],queryFn:async()=>{const{data:_,error:j}=await V.from("user_verified_senders").select("*").eq("user_id",s).order("created_at",{ascending:!1});if(j)throw j;return _||[]}}),x=Nt({mutationFn:async()=>KDe({action:"request_verification",scope:"user",email:r,display_name:i||void 0}),onSuccess:()=>{n.invalidateQueries({queryKey:["user-verified-senders",s]}),ae.success("Verification email sent",{description:`Check ${r} and click the AWS verification link.`}),a(""),l(""),c(!1)},onError:_=>ae.error(_.message)}),y=async _=>{var j,C;u(_.id);try{const A=await KDe({action:"check_status",sender_id:_.id});n.invalidateQueries({queryKey:["user-verified-senders",s]}),((j=A.sender)==null?void 0:j.status)==="verified"?ae.success(`${_.email} is verified! 🎉`):ae.info(`Status: ${((C=A.sender)==null?void 0:C.status)||"unknown"}`)}catch(A){ae.error(A.message)}finally{u(null)}},v=Nt({mutationFn:async _=>KDe({action:"delete",sender_id:_}),onSuccess:()=>{n.invalidateQueries({queryKey:["user-verified-senders",s]}),ae.success("Sender removed"),m(null)},onError:_=>ae.error(_.message)});return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium mb-1",children:"Your Verified Sender Addresses"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Verify your email address with Amazon so mass emails can be sent ",e.jsx("em",{children:"from"})," you. Add an address, then click the verification link Amazon sends to that inbox."]})]}),g?e.jsx("div",{className:"text-xs text-muted-foreground py-3",children:"Loading…"}):p&&p.length>0?e.jsx("div",{className:"space-y-2",children:p.map(_=>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(pn,{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:_.email}),e.jsx(SDn,{status:_.status})]}),_.display_name&&e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:['"',_.display_name,'"']})]})]}),e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[_.status==="verified"&&t&&e.jsx($,{size:"sm",variant:"outline",onClick:()=>t(_.email),children:"Use"}),_.status!=="verified"&&e.jsx($,{size:"sm",variant:"ghost",onClick:()=>y(_),disabled:d===_.id,title:"Refresh status from AWS",children:d===_.id?e.jsx(Jt,{className:"h-4 w-4 animate-spin"}):e.jsx(yo,{className:"h-4 w-4"})}),e.jsx($,{size:"sm",variant:"ghost",onClick:()=>m(_),className:"text-destructive hover:text-destructive",children:e.jsx(Un,{className:"h-4 w-4"})})]})]},_.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(re,{className:"text-xs",children:"Email Address *"}),e.jsx(be,{type:"email",value:r,onChange:_=>a(_.target.value),placeholder:"you@yourdomain.com",className:"text-sm"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(re,{className:"text-xs",children:"Display Name (optional)"}),e.jsx(be,{value:i,onChange:_=>l(_.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($,{size:"sm",onClick:()=>x.mutate(),disabled:!r.trim()||x.isPending,children:[x.isPending?e.jsx(Jt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(pn,{className:"h-4 w-4 mr-2"}),"Send Verification Email"]}),e.jsx($,{size:"sm",variant:"ghost",onClick:()=>{c(!1),a(""),l("")},children:"Cancel"})]})]}):e.jsxs($,{size:"sm",variant:"outline",onClick:()=>c(!0),children:[e.jsx(nn,{className:"h-4 w-4 mr-1"})," Add Sender Address"]}),e.jsx(oc,{open:!!h,onOpenChange:_=>!_&&m(null),children:e.jsxs(Ql,{children:[e.jsxs(Jl,{children:[e.jsx(tc,{children:"Remove this sender?"}),e.jsxs(sc,{children:['"',h==null?void 0:h.email,`" will be removed from your verified senders and from Amazon. You'd need to verify it again to use it.`]})]}),e.jsxs(ec,{children:[e.jsx(nc,{children:"Cancel"}),e.jsx(Vl,{onClick:()=>h&&v.mutate(h.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Remove"})]})]})})]})}function ADn(){var C,A,M,I,P;const{user:s,isBrokerageManager:t,isAdmin:n,managedBrokerages:r,selectedBrokerageId:a}=ks(),i=a||((C=r==null?void 0:r[0])==null?void 0:C.id)||null,l=(t||n)&&!!i,o=ls(),[c,d]=k.useState(!1),[u,h]=k.useState(""),[m,p]=k.useState(""),{data:g}=pt({queryKey:["mass-email-settings",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:R,error:O}=await V.from("mass_email_settings").select("*").eq("user_id",s.id).maybeSingle();if(O)throw O;return R}}),{data:x}=pt({queryKey:["agent-profile-email",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:R,error:O}=await V.from("profiles").select("email, name").eq("id",s.id).single();if(O)throw O;return R}}),y=((A=g==null?void 0:g.reply_to_email)==null?void 0:A.trim())||((M=x==null?void 0:x.email)==null?void 0:M.trim())||"",v=((I=g==null?void 0:g.display_name)==null?void 0:I.trim())||((P=x==null?void 0:x.name)==null?void 0:P.trim())||"";k.useEffect(()=>{c||(h(y),p(v))},[c,y,v]);const _=Nt({mutationFn:async()=>{if(!s||!u.trim())throw new Error("Please enter a reply-to email");const R={reply_to_email:u.trim(),display_name:m.trim()||null,updated_at:new Date().toISOString()};if(g){const{error:O}=await V.from("mass_email_settings").update(R).eq("user_id",s.id);if(O)throw O}else{const{error:O}=await V.from("mass_email_settings").insert({user_id:s.id,...R});if(O)throw O}},onSuccess:()=>{o.invalidateQueries({queryKey:["mass-email-settings",s==null?void 0:s.id]}),o.invalidateQueries({queryKey:["mass-email-ready",s==null?void 0:s.id]}),o.invalidateQueries({queryKey:["mass-email-settings-check",s==null?void 0:s.id]}),ae.success("Reply-to email saved!"),d(!1)},onError:R=>ae.error(R.message)}),j=!!y;return e.jsxs(we,{children:[e.jsx(Vt,{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(Wr,{className:"h-5 w-5 text-orange-600"})}),e.jsxs("div",{children:[e.jsxs(Yt,{className:"text-lg flex items-center gap-2",children:["Mass Email",j?e.jsxs(qe,{variant:"default",className:"text-xs bg-green-600",children:[e.jsx(nl,{className:"h-3 w-3 mr-1"})," Set Up"]}):e.jsx(qe,{variant:"secondary",className:"text-xs",children:"Setup Required"})]}),e.jsx(vr,{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:[j&&!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:v||"No display name"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:y})]}),e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>d(!0),children:[e.jsx(ui,{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(re,{className:"text-xs",children:"Display Name"}),e.jsx(be,{placeholder:"e.g. 🏡 Karen Hall",value:m,onChange:R=>p(R.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(re,{className:"text-xs",children:"Reply-To Email *"}),e.jsx(be,{type:"email",placeholder:"your@email.com",value:u,onChange:R=>h(R.target.value)})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs($,{size:"sm",onClick:()=>_.mutate(),disabled:_.isPending||!u.trim(),children:[e.jsx(Ml,{className:"h-4 w-4 mr-1"})," Save"]}),c&&e.jsxs($,{size:"sm",variant:"outline",onClick:()=>{d(!1),h(y),p(v)},children:[e.jsx(mr,{className:"h-4 w-4 mr-1"})," Cancel"]})]})]}),s&&e.jsxs(e.Fragment,{children:[e.jsx(Pc,{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(b0,{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(CDn,{userId:s.id,onVerifiedSelect:R=>{h(R),d(!0)}})]})]}),l&&e.jsxs(e.Fragment,{children:[e.jsx(Pc,{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(b0,{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(gVt,{brokerageId:i})]})]})]})]})}function EDn({authUserId:s,actingAsUserId:t}){const n=s??null,r=t??null,a=!!r&&!!n&&r!==n,i=a?r:n;return{scopeUserId:i,isDelegated:a,canViewConnections:!!i&&!a,canManageConnections:!!i&&!a}}function TDn(){const s=Jn(),{isAdmin:t,user:n}=ks(),{actingAsAgent:r,effectiveUserId:a}=cee(),i=ls(),[l,o]=k.useState(!1),[c,d]=k.useState(!1),[u,h]=k.useState(!1),{scopeUserId:m,isDelegated:p}=EDn({authUserId:n==null?void 0:n.id,actingAsUserId:(r==null?void 0:r.id)??a}),{data:g,isLoading:x}=pt({queryKey:["gmail-integration",m],enabled:!!m&&!p,queryFn:async()=>{const{data:O,error:B}=await V.from("gmail_integrations").select("*").eq("user_id",m).maybeSingle();if(B)throw B;return O}}),{data:y}=pt({queryKey:["social-accounts",m],enabled:!!m&&!p,queryFn:async()=>{const{data:O,error:B}=await V.from("social_accounts").select("*").eq("user_id",m).order("created_at",{ascending:!1});if(B)throw B;return O}}),v=async()=>{if(p){ae.error("Account connections must be made by the agent from their own login.");return}o(!0);try{const{data:O,error:B}=await V.functions.invoke("gmail-oauth",{body:{action:"get_auth_url"}});if(B)throw B;if(O!=null&&O.authUrl)window.location.href=O.authUrl;else throw new Error("Failed to get authorization URL")}catch(O){console.error("Gmail OAuth error:",O),ae.error("Failed to start Gmail connection"),o(!1)}},_=async O=>{if(p){ae.error("Account connections must be made by the agent from their own login.");return}d(!0);try{sessionStorage.setItem("social-connect-return-to",window.location.pathname);const{data:B,error:U}=await V.functions.invoke("meta-oauth",{body:{action:"get_auth_url",callbackPath:"/social-connections/callback",authMode:O}});if(U)throw U;if(B!=null&&B.authUrl)window.location.href=B.authUrl;else throw new Error("Failed to get authorization URL")}catch(B){console.error("Meta OAuth error:",B),ae.error("Failed to start connection. Make sure Meta App credentials are configured."),d(!1)}},j=async()=>{if(p){ae.error("Account connections must be made by the agent from their own login.");return}h(!0);try{const{data:O,error:B}=await V.functions.invoke("linkedin-oauth",{body:{action:"get_auth_url",callbackPath:"/social-connections/linkedin-callback"}});if(B)throw B;if(O!=null&&O.authUrl)window.location.href=O.authUrl;else throw new Error("Failed to get LinkedIn authorization URL")}catch(O){console.error("LinkedIn OAuth error:",O),ae.error("Failed to start LinkedIn connection. Please try again."),h(!1)}},C=Nt({mutationFn:async O=>{const{error:B}=await V.from("gmail_integrations").delete().eq("id",O).eq("user_id",m);if(B)throw B},onSuccess:()=>{i.invalidateQueries({queryKey:["gmail-integration",m]}),ae.success("Gmail disconnected")},onError:()=>{ae.error("Failed to disconnect Gmail")}}),A=Nt({mutationFn:async O=>{const{error:B}=await V.from("social_accounts").delete().eq("id",O).eq("user_id",m);if(B)throw B},onSuccess:()=>{i.invalidateQueries({queryKey:["social-accounts",m]}),ae.success("Account disconnected")},onError:()=>{ae.error("Failed to disconnect account")}}),M=!p&&!!(g!=null&&g.is_active),I=(y==null?void 0:y.filter(O=>O.platform==="facebook"))||[],P=(y==null?void 0:y.filter(O=>O.platform==="instagram"))||[],R=(y==null?void 0:y.filter(O=>O.platform==="linkedin"))||[];return e.jsx(Xs,{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."})]}),p&&e.jsx(we,{className:"border-amber-500/40 bg-amber-500/5",children:e.jsxs(Vt,{className:"flex flex-row items-start gap-3 space-y-0",children:[e.jsx(fu,{className:"h-5 w-5 text-amber-600 mt-0.5"}),e.jsxs("div",{children:[e.jsx(Yt,{className:"text-base",children:"Connected accounts are hidden"}),e.jsxs(vr,{children:["You're working on behalf of ",r==null?void 0:r.name,". Email and social account connections are private to each agent and can only be viewed or changed from their own login."]})]})]})}),e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-lg bg-primary/10 flex items-center justify-center",children:e.jsx(S5,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx(Yt,{className:"text-lg",children:"ChatGPT"}),e.jsx(vr,{children:"Connect ChatGPT to LevelUp so it can use LevelUp tools on your behalf."})]})]})}),e.jsx(De,{children:e.jsxs($,{variant:"outline",onClick:()=>s("/connect-chatgpt"),children:["View connection instructions ",e.jsx(xi,{className:"h-4 w-4 ml-1"})]})})]}),e.jsxs(we,{children:[e.jsx(Vt,{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(pn,{className:"h-5 w-5 text-destructive"})}),e.jsxs("div",{children:[e.jsxs(Yt,{className:"text-lg flex items-center gap-2",children:["Gmail",M&&e.jsx(qe,{variant:"default",className:"text-xs bg-green-600",children:"Connected"})]}),e.jsx(vr,{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(nl,{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(nl,{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(nl,{className:"h-4 w-4 mt-0.5 text-green-500 shrink-0"}),e.jsx("span",{children:"Quick compose from any contact detail page"})]}),M?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:g.gmail_email}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Connected Gmail account"})]}),e.jsxs(oc,{children:[e.jsx(_g,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(Un,{className:"h-4 w-4"})})}),e.jsxs(Ql,{children:[e.jsxs(Jl,{children:[e.jsx(tc,{children:"Disconnect Gmail?"}),e.jsx(sc,{children:"This will remove your Gmail connection. You'll need to reconnect to send emails."})]}),e.jsxs(ec,{children:[e.jsx(nc,{children:"Cancel"}),e.jsx(Vl,{onClick:()=>C.mutate(g.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]}):e.jsxs($,{className:"mt-4",onClick:v,disabled:l||x,children:[l?e.jsx(yo,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(pn,{className:"h-4 w-4 mr-2"}),"Connect Gmail",e.jsx(xi,{className:"h-4 w-4 ml-2"})]})]})})]}),e.jsxs(we,{children:[e.jsx(Vt,{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(ax,{className:"h-5 w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsxs(Yt,{className:"text-lg flex items-center gap-2",children:["Facebook",I.length>0&&e.jsx(qe,{variant:"default",className:"text-xs bg-green-600",children:"Connected"})]}),e.jsx(vr,{children:"Connect Facebook Pages to post content and reach your audience."})]})]})}),e.jsxs(De,{className:"space-y-3",children:[I.length>0&&e.jsx("div",{className:"space-y-2",children:I.map(O=>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(Wa,{className:"h-8 w-8",children:[e.jsx(eo,{src:O.profile_picture_url||""}),e.jsx(Ka,{children:e.jsx(ax,{className:"h-4 w-4"})})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:O.page_name||O.platform_username||"Facebook Page"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Connected Facebook Page"})]})]}),e.jsxs(oc,{children:[e.jsx(_g,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(Un,{className:"h-4 w-4"})})}),e.jsxs(Ql,{children:[e.jsxs(Jl,{children:[e.jsx(tc,{children:"Disconnect Facebook?"}),e.jsx(sc,{children:"This will remove the connection. You'll need to reconnect to post content."})]}),e.jsxs(ec,{children:[e.jsx(nc,{children:"Cancel"}),e.jsx(Vl,{onClick:()=>A.mutate(O.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]},O.id))}),e.jsxs($,{onClick:()=>_("facebook"),disabled:c,variant:"outline",className:"gap-2",children:[c?e.jsx(yo,{className:"h-4 w-4 animate-spin"}):e.jsx(nn,{className:"h-4 w-4"}),"Connect Facebook Page"]})]})]}),e.jsxs(we,{children:[e.jsx(Vt,{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(Sf,{className:"h-5 w-5 text-pink-600"})}),e.jsxs("div",{children:[e.jsxs(Yt,{className:"text-lg flex items-center gap-2",children:["Instagram",P.length>0&&e.jsx(qe,{variant:"default",className:"text-xs bg-green-600",children:"Connected"})]}),e.jsx(vr,{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:[P.length>0&&e.jsx("div",{className:"space-y-2",children:P.map(O=>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(Wa,{className:"h-8 w-8",children:[e.jsx(eo,{src:O.profile_picture_url||""}),e.jsx(Ka,{children:e.jsx(Sf,{className:"h-4 w-4"})})]}),e.jsxs("div",{children:[e.jsxs("p",{className:"font-medium text-sm",children:["@",O.platform_username||"Instagram Account"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Connected Instagram account"})]})]}),e.jsxs(oc,{children:[e.jsx(_g,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(Un,{className:"h-4 w-4"})})}),e.jsxs(Ql,{children:[e.jsxs(Jl,{children:[e.jsx(tc,{children:"Disconnect Instagram?"}),e.jsx(sc,{children:"This will remove the connection. You'll need to reconnect to post content."})]}),e.jsxs(ec,{children:[e.jsx(nc,{children:"Cancel"}),e.jsx(Vl,{onClick:()=>A.mutate(O.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]},O.id))}),e.jsxs($,{onClick:()=>_("instagram"),disabled:c,variant:"outline",className:"gap-2",children:[c?e.jsx(yo,{className:"h-4 w-4 animate-spin"}):e.jsx(nn,{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(we,{children:[e.jsx(Vt,{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(dv,{className:"h-5 w-5 text-blue-700"})}),e.jsxs("div",{children:[e.jsxs(Yt,{className:"text-lg flex items-center gap-2",children:["LinkedIn",R.length>0&&e.jsx(qe,{variant:"default",className:"text-xs bg-green-600",children:"Connected"})]}),e.jsx(vr,{children:"Connect your LinkedIn profile to share content and grow your professional network."})]})]})}),e.jsxs(De,{className:"space-y-3",children:[R.length>0&&e.jsx("div",{className:"space-y-2",children:R.map(O=>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(Wa,{className:"h-8 w-8",children:[e.jsx(eo,{src:O.profile_picture_url||""}),e.jsx(Ka,{children:e.jsx(dv,{className:"h-4 w-4"})})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:O.platform_username||"LinkedIn Account"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Connected LinkedIn profile"})]})]}),e.jsxs(oc,{children:[e.jsx(_g,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(Un,{className:"h-4 w-4"})})}),e.jsxs(Ql,{children:[e.jsxs(Jl,{children:[e.jsx(tc,{children:"Disconnect LinkedIn?"}),e.jsx(sc,{children:"This will remove your LinkedIn connection. You'll need to reconnect to post content."})]}),e.jsxs(ec,{children:[e.jsx(nc,{children:"Cancel"}),e.jsx(Vl,{onClick:()=>A.mutate(O.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]},O.id))}),e.jsxs($,{onClick:j,disabled:u,variant:"outline",className:"gap-2",children:[u?e.jsx(yo,{className:"h-4 w-4 animate-spin"}):e.jsx(nn,{className:"h-4 w-4"}),"Connect LinkedIn"]})]})]}),e.jsx(vDn,{}),e.jsx(bDn,{}),e.jsx(_Dn,{}),e.jsx(wDn,{}),e.jsx(NDn,{}),e.jsx(ADn,{}),t&&e.jsx(pVt,{})]})})}const MDn="https://chromewebstore.google.com/detail/levelup-companion/lppakdeaencigddecnkcifdcemlfpkkk";function PDn(){const[s,t]=k.useState(null),[n,r]=k.useState(!1),[a,i]=k.useState(0),[l,o]=k.useState(!1),c="/levelup-extension.zip",d="https://tile-portal.lovable.app/levelup-extension.zip",u=window.location.hostname.startsWith("id-preview--"),h=async y=>{const v=new Uint8Array(await y.slice(0,4).arrayBuffer());return v[0]===80&&v[1]===75&&v[2]===3&&v[3]===4||v[0]===80&&v[1]===75&&v[2]===5&&v[3]===6||v[0]===80&&v[1]===75&&v[2]===7&&v[3]===8},m=y=>{const v=document.createElement("a");v.href=y,v.download="levelup-extension.zip",v.rel="noopener noreferrer",v.target="_blank",document.body.appendChild(v),v.click(),v.remove()},p=async()=>{o(!0);try{if(u){m(`${d}?v=${Date.now()}`);return}const y=await fetch(`${c}?v=${Date.now()}`,{cache:"no-store"});if(!y.ok)throw new Error(`Download failed (${y.status})`);const v=await y.blob();if(!await h(v)){m(`${d}?v=${Date.now()}`);return}const _=new Blob([v],{type:"application/zip"}),j=URL.createObjectURL(_),C=document.createElement("a");C.href=j,C.download="levelup-extension.zip",document.body.appendChild(C),C.click(),C.remove(),setTimeout(()=>URL.revokeObjectURL(j),1e3)}catch(y){ae.error(y.message||"Download failed")}finally{o(!1)}},g=async()=>{r(!0);try{await V.auth.refreshSession();const{data:y}=await V.auth.getSession();if(!y.session){ae.error("Your session has expired. Please sign in again.");return}const{data:v,error:_}=await V.functions.invoke("extension-pair-start",{headers:{Authorization:`Bearer ${y.session.access_token}`}});if(_)throw _;t(v.code),i(v.expires_in||300);const j=setInterval(()=>{i(C=>C<=1?(clearInterval(j),t(null),0):C-1)},1e3)}catch(y){console.error("generateCode error",y),ae.error("We couldn't generate a pairing code",{description:"Please refresh the page and try again. If it still fails, sign out and sign back in, then click Generate pairing code.",duration:8e3})}finally{r(!1)}},x=()=>{s&&(navigator.clipboard.writeText(s),ae.success("Copied"))};return e.jsx(Xs,{title:"Browser Extension",children:e.jsxs("div",{className:"container max-w-3xl mx-auto py-8 px-4 space-y-6",children:[e.jsxs(Sc,{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(R8,{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(we,{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($,{size:"lg",className:"w-full",onClick:()=>window.open(MDn,"_blank","noopener,noreferrer"),children:[e.jsx(R8,{className:"w-4 h-4 mr-2"}),"Add to Chrome",e.jsx(Ir,{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(we,{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($,{onClick:x,variant:"outline",className:"flex-1",children:[e.jsx(Da,{className:"w-4 h-4 mr-2"})," Copy"]}),e.jsxs($,{onClick:g,variant:"outline",className:"flex-1",children:[e.jsx(yo,{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(ma,{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($,{onClick:g,disabled:n,size:"lg",className:"w-full",children:n?e.jsxs(e.Fragment,{children:[e.jsx(yo,{className:"w-4 h-4 mr-2 animate-spin"}),"Generating…"]}):"Generate pairing code"})]}),e.jsxs(we,{className:"p-6 space-y-4 bg-muted/30 border-dashed",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(bh,{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($,{variant:"link",className:"h-auto p-0 text-sm",onClick:p,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 IDn(){const[s]=Jc(),t=Jn(),[n,r]=k.useState("loading"),[a,i]=k.useState("Connecting your Gmail account...");return k.useEffect(()=>{(async()=>{const o=s.get("code"),c=s.get("error"),d=s.get("error_description"),u=s.get("state");if(c){r("error"),i(d||"Authorization was denied"),ae.error("Connection failed: "+(d||c));return}if(!o){r("error"),i("No authorization code received"),ae.error("No authorization code received");return}try{const{data:h,error:m}=await V.functions.invoke("gmail-oauth",{body:{action:"exchange_code",code:o,state:u}});if(m)throw m;if(h!=null&&h.success)r("success"),i(h.message||"Gmail connected successfully!"),ae.success("Gmail connected!");else throw new Error((h==null?void 0:h.error)||"Unknown error")}catch(h){console.error("Gmail OAuth callback error:",h),r("error"),i(h instanceof Error?h.message:"Failed to connect Gmail"),ae.error("Failed to connect: "+(h instanceof Error?h.message:"Unknown error"))}})()},[s]),e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background p-4",children:e.jsxs(we,{className:"w-full max-w-md",children:[e.jsxs(Vt,{className:"text-center",children:[n==="loading"&&e.jsx(Jt,{className:"h-12 w-12 animate-spin mx-auto text-primary"}),n==="success"&&e.jsx(nl,{className:"h-12 w-12 mx-auto text-green-500"}),n==="error"&&e.jsx(ju,{className:"h-12 w-12 mx-auto text-destructive"}),e.jsxs(Yt,{className:"mt-4",children:[n==="loading"&&"Connecting...",n==="success"&&"Connected!",n==="error"&&"Connection Failed"]}),e.jsx(vr,{children:a})]}),e.jsx(De,{className:"flex justify-center",children:n!=="loading"&&e.jsx($,{onClick:()=>t("/mission-control/integrations"),children:n==="success"?"Back to Integrations":"Try Again"})})]})})}function LDn(){const s=Jn();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 RDn(){const[s]=Jc(),t=Jn(),[n,r]=k.useState("loading"),a=k.useRef(!1),[i,l]=k.useState("Processing your connection...");return k.useEffect(()=>{if(a.current)return;a.current=!0,(async()=>{var m;const c=s.get("code"),d=s.get("error"),u=s.get("error_description"),h=s.get("state");if(d){r("error"),l(u||"Authorization was denied"),ae.error("Connection failed: "+(u||d));return}if(!c){r("error"),l("No authorization code received"),ae.error("No authorization code received");return}try{const{data:p,error:g}=await V.functions.invoke("meta-oauth",{body:{action:"exchange_code",code:c,state:h,callbackPath:"/mission-control/integrations/meta/callback"}});if(p&&p.success===!1)throw new Error(p.error||"Failed to connect accounts");if(g){let x=g.message||"Failed to connect accounts";try{const y=g.context;if(y&&typeof y.json=="function"){const v=await y.json();v!=null&&v.error&&(x=v.error)}}catch{}throw new Error(x)}if(p!=null&&p.success)r("success"),l(`Successfully connected ${((m=p.accounts)==null?void 0:m.length)||0} account(s)!`),ae.success("Social accounts connected successfully!");else throw new Error((p==null?void 0:p.error)||"Unknown error")}catch(p){console.error("OAuth callback error:",p),r("error"),l(p instanceof Error?p.message:"Failed to connect accounts"),ae.error("Failed to connect: "+(p instanceof Error?p.message:"Unknown error"))}})()},[s]),e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background p-4",children:e.jsxs(we,{className:"w-full max-w-md",children:[e.jsxs(Vt,{className:"text-center",children:[n==="loading"&&e.jsx(Jt,{className:"h-12 w-12 animate-spin mx-auto text-primary"}),n==="success"&&e.jsx(nl,{className:"h-12 w-12 mx-auto text-green-500"}),n==="error"&&e.jsx(ju,{className:"h-12 w-12 mx-auto text-destructive"}),e.jsxs(Yt,{className:"mt-4",children:[n==="loading"&&"Connecting...",n==="success"&&"Connected!",n==="error"&&"Connection Failed"]}),e.jsx(vr,{children:i})]}),e.jsx(De,{className:"flex justify-center",children:n!=="loading"&&e.jsx($,{onClick:()=>t("/mission-control/integrations"),children:n==="success"?"View Integrations":"Try Again"})})]})})}const xVt=new Date().getFullYear(),DDn=Array.from({length:5},(s,t)=>xVt-t);function ODn(){const[s,t]=k.useState(xVt),n=Jn(),{data:r,isLoading:a}=KEs();return a?e.jsx(Xs,{title:"Scorecard Admin",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(fn,{className:"h-8 w-64"}),e.jsx("div",{className:"grid grid-cols-4 gap-4",children:[1,2,3,4].map(i=>e.jsx(fn,{className:"h-24"},i))}),e.jsx(fn,{className:"h-96"})]})}):e.jsx(Xs,{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(bs,{value:String(s),onValueChange:i=>t(Number(i)),children:[e.jsx(ys,{className:"w-[120px]",children:e.jsx(_s,{})}),e.jsx(vs,{children:DDn.map(i=>e.jsx(We,{value:String(i),children:i},i))})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsx(we,{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(Xn,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Agents Tracking"})]}),e.jsx("p",{className:"text-2xl font-bold",children:(r==null?void 0:r.length)||0})]})}),e.jsx(we,{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(Ul,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Total Agents"})]}),e.jsx("p",{className:"text-2xl font-bold",children:(r==null?void 0:r.length)||0}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"with transactions"})]})})]}),e.jsxs(we,{children:[e.jsxs(Vt,{children:[e.jsx(Yt,{children:"Agents with Scorecards"}),e.jsx(vr,{children:"Click to view individual agent scorecards"})]}),e.jsx(De,{children:!r||r.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Ul,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No agents have added transactions yet"})]}):e.jsxs(Qa,{children:[e.jsx(Ja,{children:e.jsxs(vn,{children:[e.jsx(Dt,{children:"Agent"}),e.jsx(Dt,{children:"Email"}),e.jsx(Dt,{className:"text-right",children:"Actions"})]})}),e.jsx(ei,{children:r.map(i=>e.jsxs(vn,{children:[e.jsx(_t,{className:"font-medium",children:i.name}),e.jsx(_t,{className:"text-muted-foreground",children:i.email}),e.jsx(_t,{className:"text-right",children:e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>n(`/admin/scorecard/${i.id}`),children:[e.jsx(ba,{className:"h-4 w-4 mr-2"}),"View Scorecard"]})})]},i.id))})]})})]})]})})}const yVt=new Date().getFullYear(),FDn=Array.from({length:10},(s,t)=>yVt-t);function lbt(){var g;const{userId:s}=oo(),t=Jn(),r=Tu().pathname.startsWith("/mission-control"),[a,i]=k.useState(yVt),{data:l,isLoading:o}=pt({queryKey:["agent-profile",s],queryFn:async()=>{const{data:x,error:y}=await V.from("profiles").select("id, name, email").eq("id",s).single();if(y)throw y;return x},enabled:!!s}),{data:c,isLoading:d}=_We(a,s),{yearStats:u,lifetimeStats:h,showCommission:m}=JMt(a,s),{data:p}=QMt(a,s);return o?e.jsx(Xs,{title:"Agent Scorecard",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(fn,{className:"h-8 w-64"}),e.jsx("div",{className:"grid grid-cols-4 gap-4",children:[1,2,3,4].map(x=>e.jsx(fn,{className:"h-24"},x))})]})}):e.jsx(Xs,{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($,{variant:"ghost",size:"icon",onClick:()=>t(r?"/mission-control/scorecard":"/admin/scorecard"),children:e.jsx(Ia,{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(bs,{value:String(a),onValueChange:x=>i(Number(x)),children:[e.jsx(ys,{className:"w-[120px]",children:e.jsx(_s,{})}),e.jsx(vs,{children:FDn.map(x=>e.jsx(We,{value:String(x),children:x},x))})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 lg:grid-cols-5 gap-4",children:[e.jsx(we,{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(ua,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Transactions"})]}),e.jsx("p",{className:"text-2xl font-bold",children:u.totalTransactions}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[h.totalTransactions," lifetime"]})]})}),e.jsx(we,{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(Xn,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Buyer/Seller"})]}),e.jsxs("p",{className:"text-2xl font-bold",children:[u.buyerCount,"/",u.sellerCount]})]})}),e.jsx(we,{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(Su,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Volume"})]}),e.jsx("p",{className:"text-2xl font-bold",children:yh(u.totalVolume,!0)})]})}),e.jsx(we,{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(mc,{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:yh(u.averagePrice,!0)})]})}),e.jsx(we,{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(oh,{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:((g=u.topLeadSource)==null?void 0:g.name)||"-"})]})})]}),p&&e.jsx(Nqt,{goals:p,stats:u,year:a,showCommission:m}),e.jsxs(ya,{defaultValue:"transactions",className:"space-y-4",children:[e.jsxs(va,{children:[e.jsx(is,{value:"transactions",children:"Transactions"}),e.jsx(is,{value:"charts",children:"Charts"}),e.jsxs(is,{value:"map",children:[e.jsx(Si,{className:"h-4 w-4 mr-1"}),"Map"]})]}),e.jsx(cs,{value:"transactions",children:e.jsx(oQe,{transactions:c||[],showCommission:m,isLoading:d})}),e.jsx(cs,{value:"charts",children:e.jsx(lQe,{stats:u,year:a})}),e.jsx(cs,{value:"map",children:e.jsx(cQe,{transactions:c||[],isLoading:d})})]})]})})}function zDn(){const s=ls(),[t,n]=k.useState(""),[r,a]=k.useState("all"),[i,l]=k.useState(null);EHe();const{data:o,refetch:c}=pt({queryKey:["listing-exchange-flag"],queryFn:async()=>{const{data:R}=await V.from("feature_flags").select("enabled").eq("key","listing_exchange_enabled").single();return(R==null?void 0:R.enabled)??!1}}),{data:d,isLoading:u}=pt({queryKey:["admin-listings"],queryFn:async()=>{const{data:R,error:O}=await V.from("listings").select(` *, agent:profiles!listings_agent_id_fkey(id, name, email), photos:listing_photos(id, photo_url, is_primary) `).order("created_at",{ascending:!1});if(O)throw O;return R}}),{data:h}=pt({queryKey:["admin-listing-stats"],queryFn:async()=>{const{data:R}=await V.from("listings").select("id, is_approved, status"),{data:O}=await V.from("listing_shares").select("id"),{data:B}=await V.from("listing_views").select("id"),{count:U}=await V.from("listing_leads").select("id",{count:"exact",head:!0}),G=new Date(Date.now()-7*24*60*60*1e3).toISOString(),{count:H}=await V.from("listing_leads").select("id",{count:"exact",head:!0}).gte("created_at",G);return{total:(R==null?void 0:R.length)||0,pending:(R==null?void 0:R.filter(Y=>!Y.is_approved).length)||0,active:(R==null?void 0:R.filter(Y=>Y.status==="active").length)||0,totalShares:(O==null?void 0:O.length)||0,totalViews:(B==null?void 0:B.length)||0,totalLeads:U||0,leadsLast7:H||0}}}),{data:m}=pt({queryKey:["admin-listing-lead-counts"],queryFn:async()=>{const R={};let O=0;const B=1e3;for(;;){const{data:U,error:G}=await V.from("listing_leads").select("listing_id").range(O,O+B-1);if(G)throw G;if(!U||U.length===0)break;for(const H of U)H.listing_id&&(R[H.listing_id]=(R[H.listing_id]||0)+1);if(U.length{const{data:R,error:O}=await V.from("listing_leads").select("*").eq("listing_id",i.listingId).order("created_at",{ascending:!1});if(O)throw O;return R}}),x=async(R,O,B="submit_url")=>{try{const{data:{session:U}}=await V.auth.getSession();if(!U)return;const{data:G,error:H}=await V.functions.invoke("google-indexing",{body:{action:B,listing_id:R,listing_slug:O}});if(H)throw H;if((G==null?void 0:G.configured)===!1)return;G!=null&&G.success&&ae.success("Submitted to Google for indexing")}catch(U){console.error("Google indexing submission failed:",U)}},y=Nt({mutationFn:async()=>{const{data:{session:R}}=await V.auth.getSession();if(!R)throw new Error("Not authenticated");const{data:O,error:B}=await V.functions.invoke("google-indexing",{body:{action:"submit_all"}});if(B)throw B;return O},onSuccess:R=>{if((R==null?void 0:R.configured)===!1){ae.error("Google Indexing API not configured. Add the GOOGLE_INDEXING_SERVICE_ACCOUNT secret.");return}ae.success(`Submitted ${(R==null?void 0:R.succeeded)||0} URLs to Google (${(R==null?void 0:R.failed)||0} failed)`)},onError:R=>{ae.error("Failed to submit to Google"),console.error(R)}}),v=Nt({mutationFn:async({id:R,approved:O,slug:B})=>{const{error:U}=await V.from("listings").update({is_approved:O}).eq("id",R);if(U)throw U;return{id:R,approved:O,slug:B}},onSuccess:R=>{s.invalidateQueries({queryKey:["admin-listings"]}),s.invalidateQueries({queryKey:["admin-listing-stats"]}),ae.success(R.approved?"Listing approved":"Listing unapproved"),R.approved?x(R.id,R.slug||null,"submit_url"):x(R.id,R.slug||null,"remove_url")}}),_=Nt({mutationFn:async({id:R,featured:O})=>{const{error:B}=await V.from("listings").update({is_featured:O}).eq("id",R);if(B)throw B},onSuccess:(R,{featured:O})=>{s.invalidateQueries({queryKey:["admin-listings"]}),ae.success(O?"Listing featured":"Listing unfeatured")}}),j=Nt({mutationFn:async R=>{const{error:O}=await V.from("listings").delete().eq("id",R);if(O)throw O},onSuccess:()=>{s.invalidateQueries({queryKey:["admin-listings"]}),s.invalidateQueries({queryKey:["admin-listing-stats"]}),ae.success("Listing deleted")}}),C=Nt({mutationFn:async R=>{const{error:O}=await V.from("feature_flags").update({enabled:R}).eq("key","listing_exchange_enabled");if(O)throw O},onSuccess:()=>{c(),ae.success("Feature flag updated")}}),A=o??!1,M=d==null?void 0:d.filter(R=>{var U,G,H,Y;const O=((U=R.city)==null?void 0:U.toLowerCase().includes(t.toLowerCase()))||((H=(G=R.agent)==null?void 0:G.name)==null?void 0:H.toLowerCase().includes(t.toLowerCase()))||((Y=R.property_address)==null?void 0:Y.toLowerCase().includes(t.toLowerCase())),B=r==="all"||r==="pending"&&!R.is_approved||r==="approved"&&R.is_approved;return O&&B}),I=R=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(R),P=R=>{const O={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 O[R]||O.active};return e.jsxs(Xs,{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($,{variant:"outline",size:"sm",onClick:()=>y.mutate(),disabled:y.isPending,className:"gap-2",children:[y.isPending?e.jsx(Jt,{className:"h-4 w-4 animate-spin"}):e.jsx(kc,{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(On,{checked:A,onCheckedChange:R=>C.mutate(R)})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-6 gap-4",children:[e.jsx(we,{children:e.jsxs(De,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Gi,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Total Listings"})]}),e.jsx("p",{className:"text-2xl font-bold mt-1",children:(h==null?void 0:h.total)||0})]})}),e.jsx(we,{children:e.jsxs(De,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(mc,{className:"h-4 w-4 text-green-500"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Active"})]}),e.jsx("p",{className:"text-2xl font-bold mt-1",children:(h==null?void 0:h.active)||0})]})}),e.jsx(we,{children:e.jsxs(De,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Xn,{className:"h-4 w-4 text-amber-500"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Pending Review"})]}),e.jsx("p",{className:"text-2xl font-bold mt-1",children:(h==null?void 0:h.pending)||0})]})}),e.jsx(we,{children:e.jsxs(De,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ba,{className:"h-4 w-4 text-blue-500"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Total Views"})]}),e.jsx("p",{className:"text-2xl font-bold mt-1",children:(h==null?void 0:h.totalViews)||0})]})}),e.jsx(we,{children:e.jsxs(De,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ou,{className:"h-4 w-4 text-purple-500"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Total Shares"})]}),e.jsx("p",{className:"text-2xl font-bold mt-1",children:(h==null?void 0:h.totalShares)||0})]})}),e.jsx(we,{children:e.jsxs(De,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Pl,{className:"h-4 w-4 text-teal-600"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Leads"})]}),e.jsx("p",{className:"text-2xl font-bold mt-1",children:(h==null?void 0:h.totalLeads)||0}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5",children:[(h==null?void 0:h.leadsLast7)||0," in last 7 days"]})]})})]}),e.jsx(we,{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(Yr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search by city, address, or agent...",value:t,onChange:R=>n(R.target.value),className:"pl-9"})]}),e.jsx(ya,{value:r,onValueChange:R=>a(R),children:e.jsxs(va,{children:[e.jsx(is,{value:"all",children:"All"}),e.jsx(is,{value:"pending",children:"Pending"}),e.jsx(is,{value:"approved",children:"Approved"})]})})]})})}),e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsxs(Yt,{children:["Listings (",(M==null?void 0:M.length)||0,")"]})}),e.jsx(De,{children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(Qa,{children:[e.jsx(Ja,{children:e.jsxs(vn,{children:[e.jsx(Dt,{children:"Property"}),e.jsx(Dt,{children:"Agent"}),e.jsx(Dt,{children:"Price"}),e.jsx(Dt,{children:"Status"}),e.jsx(Dt,{className:"text-center",children:"Approved"}),e.jsx(Dt,{className:"text-center",children:"Featured"}),e.jsx(Dt,{children:"Views"}),e.jsx(Dt,{children:"Shares"}),e.jsx(Dt,{children:"Leads"}),e.jsx(Dt,{children:"Date"}),e.jsx(Dt,{})]})}),e.jsx(ei,{children:u?e.jsx(vn,{children:e.jsx(_t,{colSpan:11,className:"text-center py-8 text-muted-foreground",children:"Loading..."})}):(M==null?void 0:M.length)===0?e.jsx(vn,{children:e.jsx(_t,{colSpan:11,className:"text-center py-8 text-muted-foreground",children:"No listings found"})}):M==null?void 0:M.map(R=>{var O,B,U,G,H;return e.jsxs(vn,{children:[e.jsx(_t,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[(B=(O=R.photos)==null?void 0:O[0])!=null&&B.photo_url?e.jsx("img",{src:R.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(Gi,{className:"h-5 w-5 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:R.property_address||`${R.city}, ${R.state}`}),e.jsx("p",{className:"text-xs text-muted-foreground",children:(U=R.property_type)==null?void 0:U.replace("_"," ")})]})]})}),e.jsx(_t,{children:e.jsx("p",{className:"text-sm",children:((G=R.agent)==null?void 0:G.name)||"Unknown"})}),e.jsx(_t,{className:"font-medium",children:I(R.price)}),e.jsx(_t,{children:e.jsx(qe,{variant:"outline",className:P(R.status),children:(H=R.status)==null?void 0:H.replace("_"," ")})}),e.jsx(_t,{className:"text-center",children:e.jsx(On,{checked:R.is_approved??!1,onCheckedChange:Y=>v.mutate({id:R.id,approved:Y,slug:R.slug})})}),e.jsx(_t,{className:"text-center",children:e.jsx(On,{checked:R.is_featured??!1,onCheckedChange:Y=>_.mutate({id:R.id,featured:Y})})}),e.jsx(_t,{children:R.view_count||0}),e.jsx(_t,{children:R.share_count||0}),e.jsx(_t,{children:((m==null?void 0:m[R.id])??0)>0?e.jsx($,{variant:"link",size:"sm",className:"px-0 h-auto font-semibold text-teal-600",onClick:()=>l({listingId:R.id,label:R.property_address||`${R.city}, ${R.state}`}),children:m==null?void 0:m[R.id]}):e.jsx("span",{className:"text-muted-foreground",children:"0"})}),e.jsx(_t,{className:"text-sm text-muted-foreground",children:Ys(new Date(R.created_at),"MMM d, yyyy")}),e.jsx(_t,{children:e.jsxs(Au,{children:[e.jsx(Eu,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",children:e.jsx(u0,{className:"h-4 w-4"})})}),e.jsxs(gu,{align:"end",children:[e.jsxs(Pa,{onClick:()=>window.open(`/mission-control/listings/${R.id}`,"_blank"),children:[e.jsx(ba,{className:"h-4 w-4 mr-2"}),"View Listing"]}),e.jsxs(Pa,{onClick:()=>_.mutate({id:R.id,featured:!R.is_featured}),children:[e.jsx(ri,{className:"h-4 w-4 mr-2"}),R.is_featured?"Unfeature":"Feature"]}),e.jsxs(Pa,{className:"text-destructive",onClick:async()=>{await io("Are you sure you want to delete this listing?")&&j.mutate(R.id)},children:[e.jsx(mr,{className:"h-4 w-4 mr-2"}),"Delete"]})]})]})})]},R.id)})})]})})})]})]}),e.jsx(zs,{open:!!i,onOpenChange:R=>!R&&l(null),children:e.jsxs(Rs,{className:"max-w-3xl max-h-[80vh] overflow-y-auto",children:[e.jsxs(Vs,{children:[e.jsx($s,{children:"Leads from listing"}),e.jsx(Cr,{children:i==null?void 0:i.label})]}),g?e.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[e.jsx(Jt,{className:"h-5 w-5 animate-spin inline mr-2"}),"Loading leads..."]}):!p||p.length===0?e.jsx("div",{className:"py-8 text-center text-muted-foreground",children:"No leads yet."}):e.jsxs(Qa,{children:[e.jsx(Ja,{children:e.jsxs(vn,{children:[e.jsx(Dt,{children:"Name"}),e.jsx(Dt,{children:"Email"}),e.jsx(Dt,{children:"Phone"}),e.jsx(Dt,{children:"Type"}),e.jsx(Dt,{children:"Captured"})]})}),e.jsx(ei,{children:p.map(R=>{var O;return e.jsxs(vn,{children:[e.jsx(_t,{className:"font-medium",children:[R.first_name,R.last_name].filter(Boolean).join(" ")||"—"}),e.jsx(_t,{children:R.email}),e.jsx(_t,{children:R.phone||"—"}),e.jsx(_t,{children:e.jsx(qe,{variant:"outline",children:(O=R.lead_type)==null?void 0:O.replace("_"," ")})}),e.jsx(_t,{className:"text-sm text-muted-foreground",children:Ys(new Date(R.created_at),"MMM d, yyyy h:mm a")})]},R.id)})})]})]})})]})}function BDn(s){return s?new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s):"—"}function $Dn(){const[s,t]=k.useState(""),[n,r]=k.useState("all"),[a,i]=k.useState("all"),{data:l,isLoading:o}=pt({queryKey:["admin-all-listing-leads"],queryFn:async()=>{const h=[];let m=0;const p=1e3;for(;;){const{data:g,error:x}=await V.from("listing_leads").select(` id, listing_id, agent_id, referred_by_agent_id, first_name, last_name, email, phone, lead_type, showing_mode, preferred_date, preferred_time, message, created_at, listing:listings!listing_leads_listing_id_fkey(id, slug, property_address, city, state, price), agent:profiles!listing_leads_agent_id_fkey(id, name, email), referrer:profiles!listing_leads_referred_by_agent_id_fkey(id, name, email) `).order("created_at",{ascending:!1}).range(m,m+p-1);if(x)throw x;if(!g||g.length===0||(h.push(...g),g.length{if(!l)return[];const h=n==="all"?0:Date.now()-parseInt(n)*24*60*60*1e3,m=s.trim().toLowerCase();return l.filter(p=>{var x,y,v,_,j,C;return h&&new Date(p.created_at).getTime(){const h=c.length,m=c.filter(x=>x.lead_type==="showing_request").length,p=new Set(c.map(x=>x.agent_id)).size,g=new Set(c.map(x=>x.listing_id)).size;return{total:h,showings:m,uniqueAgents:p,uniqueListings:g}},[c]),u=()=>{const m=[["Date","Name","Email","Phone","Type","Showing Date","Property","City","Price","Assigned Agent","Agent Email","Referred By","Message"],...c.map(y=>{var v,_,j,C,A,M;return[Ys(new Date(y.created_at),"yyyy-MM-dd HH:mm"),`${y.first_name||""} ${y.last_name||""}`.trim(),y.email,y.phone||"",y.lead_type,y.preferred_date?`${y.preferred_date} ${y.preferred_time||""}`:"",((v=y.listing)==null?void 0:v.property_address)||"",((_=y.listing)==null?void 0:_.city)||"",(j=y.listing)!=null&&j.price?String(y.listing.price):"",((C=y.agent)==null?void 0:C.name)||"",((A=y.agent)==null?void 0:A.email)||"",((M=y.referrer)==null?void 0:M.name)||"",(y.message||"").replace(/[\r\n]+/g," ")]})].map(y=>y.map(v=>`"${String(v).replace(/"/g,'""')}"`).join(",")).join(` `),p=new Blob([m],{type:"text/csv"}),g=URL.createObjectURL(p),x=document.createElement("a");x.href=g,x.download=`listing-leads-${Ys(new Date,"yyyy-MM-dd")}.csv`,x.click(),URL.revokeObjectURL(g)};return e.jsx(Xs,{title:"Listing Leads",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Listing Leads"}),e.jsx("p",{className:"text-muted-foreground",children:"All leads submitted through the public listings site"})]}),e.jsxs($,{variant:"outline",onClick:u,disabled:!c.length,className:"gap-2",children:[e.jsx(ji,{className:"h-4 w-4"}),"Export CSV"]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsx(we,{children:e.jsxs(De,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Pl,{className:"h-4 w-4 text-teal-600"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Total Leads"})]}),e.jsx("p",{className:"text-2xl font-bold mt-1",children:d.total})]})}),e.jsx(we,{children:e.jsxs(De,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ha,{className:"h-4 w-4 text-purple-600"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Showing Requests"})]}),e.jsx("p",{className:"text-2xl font-bold mt-1",children:d.showings})]})}),e.jsx(we,{children:e.jsxs(De,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ua,{className:"h-4 w-4 text-blue-600"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Properties"})]}),e.jsx("p",{className:"text-2xl font-bold mt-1",children:d.uniqueListings})]})}),e.jsx(we,{children:e.jsxs(De,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Pl,{className:"h-4 w-4 text-amber-600"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Agents w/ Leads"})]}),e.jsx("p",{className:"text-2xl font-bold mt-1",children:d.uniqueAgents})]})})]}),e.jsx(we,{children:e.jsx(De,{className:"p-4",children:e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Yr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search name, email, property, agent...",value:s,onChange:h=>t(h.target.value),className:"pl-9"})]}),e.jsxs(bs,{value:a,onValueChange:h=>i(h),children:[e.jsx(ys,{className:"w-full sm:w-48",children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"all",children:"All Types"}),e.jsx(We,{value:"info_request",children:"Info Request"}),e.jsx(We,{value:"showing_request",children:"Showing Request"})]})]}),e.jsxs(bs,{value:n,onValueChange:h=>r(h),children:[e.jsx(ys,{className:"w-full sm:w-40",children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"all",children:"All Time"}),e.jsx(We,{value:"7",children:"Last 7 days"}),e.jsx(We,{value:"30",children:"Last 30 days"}),e.jsx(We,{value:"90",children:"Last 90 days"})]})]})]})})}),e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsxs(Yt,{children:["Leads (",c.length,")"]})}),e.jsx(De,{children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(Qa,{children:[e.jsx(Ja,{children:e.jsxs(vn,{children:[e.jsx(Dt,{children:"Date"}),e.jsx(Dt,{children:"Lead"}),e.jsx(Dt,{children:"Contact"}),e.jsx(Dt,{children:"Property"}),e.jsx(Dt,{children:"Type"}),e.jsx(Dt,{children:"Assigned To"}),e.jsx(Dt,{children:"Referred By"}),e.jsx(Dt,{children:"Message"})]})}),e.jsx(ei,{children:o?e.jsx(vn,{children:e.jsx(_t,{colSpan:8,className:"text-center py-8 text-muted-foreground",children:"Loading..."})}):c.length===0?e.jsx(vn,{children:e.jsx(_t,{colSpan:8,className:"text-center py-8 text-muted-foreground",children:"No leads found"})}):c.map(h=>{var m,p;return e.jsxs(vn,{children:[e.jsxs(_t,{className:"whitespace-nowrap text-sm",children:[Ys(new Date(h.created_at),"MMM d, yyyy"),e.jsx("div",{className:"text-xs text-muted-foreground",children:Ys(new Date(h.created_at),"h:mm a")})]}),e.jsx(_t,{children:e.jsx("div",{className:"font-medium",children:`${h.first_name||""} ${h.last_name||""}`.trim()||"—"})}),e.jsx(_t,{children:e.jsxs("div",{className:"flex flex-col gap-1 text-sm",children:[e.jsxs("a",{href:`mailto:${h.email}`,className:"flex items-center gap-1 hover:underline",children:[e.jsx(pn,{className:"h-3 w-3"}),h.email]}),h.phone&&e.jsxs("a",{href:`tel:${h.phone}`,className:"flex items-center gap-1 text-muted-foreground hover:underline",children:[e.jsx(ka,{className:"h-3 w-3"}),h.phone]})]})}),e.jsx(_t,{children:h.listing?e.jsxs(nr,{to:`/public/listing/${h.listing.slug||h.listing.id}`,target:"_blank",className:"group",children:[e.jsxs("div",{className:"font-medium text-sm group-hover:underline flex items-center gap-1",children:[h.listing.property_address||"Untitled",e.jsx(Ir,{className:"h-3 w-3 opacity-60"})]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[[h.listing.city,h.listing.state].filter(Boolean).join(", ")," · ",BDn(h.listing.price)]})]}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"—"})}),e.jsxs(_t,{children:[e.jsx(qe,{variant:h.lead_type==="showing_request"?"default":"secondary",className:"text-xs",children:h.lead_type==="showing_request"?"Showing":"Info"}),h.preferred_date&&e.jsxs("div",{className:"text-xs text-muted-foreground mt-1",children:[h.preferred_date," ",h.preferred_time||""]}),h.showing_mode&&e.jsx("div",{className:"text-xs text-muted-foreground capitalize",children:h.showing_mode.replace("_"," ")})]}),e.jsxs(_t,{children:[e.jsx("div",{className:"text-sm font-medium",children:((m=h.agent)==null?void 0:m.name)||"—"}),((p=h.agent)==null?void 0:p.email)&&e.jsx("div",{className:"text-xs text-muted-foreground",children:h.agent.email})]}),e.jsx(_t,{children:h.referrer?e.jsxs("div",{children:[e.jsx("div",{className:"text-sm",children:h.referrer.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:h.referrer.email})]}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"Direct"})}),e.jsx(_t,{className:"max-w-xs",children:h.message?e.jsxs("div",{className:"text-xs text-muted-foreground line-clamp-3 flex items-start gap-1",children:[e.jsx(bo,{className:"h-3 w-3 mt-0.5 shrink-0"}),h.message]}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"—"})})]},h.id)})})]})})})]})]})})}const g9={new_listing_alerts:{label:"New Listing Alerts",icon:Fx,color:"bg-amber-100 text-amber-800"},exit_intent:{label:"Exit Intent",icon:q8,color:"bg-rose-100 text-rose-800"},saved_listing:{label:"Saved Home",icon:Bo,color:"bg-pink-100 text-pink-800"},saved_search:{label:"Saved Search",icon:Yr,color:"bg-blue-100 text-blue-800"},buyer_guide:{label:"Buyer's Guide",icon:wg,color:"bg-emerald-100 text-emerald-800"}},cbt=[{key:"24h",label:"Last 24h",days:1},{key:"7d",label:"Last 7 days",days:7},{key:"30d",label:"Last 30 days",days:30},{key:"all",label:"All time",days:0}];function dbt(s){return new Date(s).toLocaleString("en-US",{timeZone:"America/New_York",month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit"})}function UDn(){const[s,t]=k.useState([]),[n,r]=k.useState(!0),[a,i]=k.useState("30d"),[l,o]=k.useState("all"),[c,d]=k.useState("");k.useEffect(()=>{let p=!1;return(async()=>{r(!0);let g=V.from("public_site_leads").select("*").order("created_at",{ascending:!1}).limit(2e3);const x=cbt.find(_=>_.key===a);if(x&&x.days>0){const _=new Date(Date.now()-x.days*864e5).toISOString();g=g.gte("created_at",_)}const{data:y,error:v}=await g;p||(v?(console.error(v),t([])):t(y||[]),r(!1))})(),()=>{p=!0}},[a]);const u=k.useMemo(()=>s.filter(p=>{if(l!=="all"&&p.lead_type!==l)return!1;if(c){const g=c.toLowerCase();if(![p.email,p.first_name,p.last_name,p.phone,p.source_page,p.referrer].filter(Boolean).join(" ").toLowerCase().includes(g))return!1}return!0}),[s,l,c]),h=k.useMemo(()=>{const p=u.length,g=new Set(u.map(y=>y.email.toLowerCase())).size,x={};return u.forEach(y=>{x[y.lead_type]=(x[y.lead_type]||0)+1}),{total:p,uniqueEmails:g,byType:x}},[u]),m=()=>{const g=[["Date (ET)","Type","Email","First","Last","Phone","Listing ID","Source Page","Referrer","Criteria"].join(",")];u.forEach(_=>{var C;const j=[dbt(_.created_at),((C=g9[_.lead_type])==null?void 0:C.label)||_.lead_type,_.email,_.first_name||"",_.last_name||"",_.phone||"",_.listing_id||"",_.source_page||"",_.referrer||"",_.criteria?JSON.stringify(_.criteria):""].map(A=>`"${String(A).replace(/"/g,'""')}"`);g.push(j.join(","))});const x=new Blob([g.join(` `)],{type:"text/csv"}),y=URL.createObjectURL(x),v=document.createElement("a");v.href=y,v.download=`public-site-leads-${new Date().toISOString().slice(0,10)}.csv`,v.click(),URL.revokeObjectURL(y)};return e.jsxs("div",{className:"min-h-screen bg-slate-50",children:[e.jsx(Sc,{children:e.jsx("title",{children:"Public Site Leads — Admin"})}),e.jsx("div",{className:"border-b bg-white",children:e.jsxs("div",{className:"max-w-7xl mx-auto px-6 py-4 flex items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(nr,{to:"/admin",children:e.jsxs($,{variant:"ghost",size:"sm",children:[e.jsx(Ia,{className:"h-4 w-4 mr-1"}),"Admin"]})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-lg font-semibold",children:"Public Site Leads"}),e.jsx("p",{className:"text-xs text-slate-500",children:"listings.relevelup.com — alerts, exit intent & saved homes"})]})]}),e.jsxs($,{onClick:m,variant:"outline",size:"sm",children:[e.jsx(ji,{className:"h-4 w-4 mr-1"})," Export CSV"]})]})}),e.jsxs("div",{className:"max-w-7xl mx-auto px-6 py-6 space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-3",children:[e.jsx(we,{children:e.jsxs(De,{className:"p-4",children:[e.jsx("div",{className:"text-xs text-slate-500 uppercase tracking-wide",children:"Total Leads"}),e.jsx("div",{className:"text-2xl font-bold mt-1",children:h.total}),e.jsxs("div",{className:"text-xs text-slate-500 mt-1",children:[h.uniqueEmails," unique"]})]})}),Object.keys(g9).map(p=>{const g=g9[p],x=g.icon;return e.jsx(we,{children:e.jsxs(De,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-slate-500 uppercase tracking-wide",children:[e.jsx(x,{className:"h-3.5 w-3.5"}),g.label]}),e.jsx("div",{className:"text-2xl font-bold mt-1",children:h.byType[p]||0})]})},p)})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(bs,{value:a,onValueChange:p=>i(p),children:[e.jsx(ys,{className:"w-[160px] bg-white",children:e.jsx(_s,{})}),e.jsx(vs,{children:cbt.map(p=>e.jsx(We,{value:p.key,children:p.label},p.key))})]}),e.jsxs(bs,{value:l,onValueChange:o,children:[e.jsx(ys,{className:"w-[200px] bg-white",children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"all",children:"All lead types"}),Object.keys(g9).map(p=>e.jsx(We,{value:p,children:g9[p].label},p))]})]}),e.jsxs("div",{className:"relative flex-1 min-w-[200px] max-w-md",children:[e.jsx(Yr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400"}),e.jsx(be,{placeholder:"Search name, email, phone…",value:c,onChange:p=>d(p.target.value),className:"pl-9 bg-white"})]}),e.jsxs("div",{className:"ml-auto text-sm text-slate-500",children:[u.length," ",u.length===1?"lead":"leads"]})]}),e.jsx(we,{children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b bg-slate-50 text-left text-xs uppercase tracking-wide text-slate-500",children:[e.jsx("th",{className:"px-4 py-3",children:"Date"}),e.jsx("th",{className:"px-4 py-3",children:"Type"}),e.jsx("th",{className:"px-4 py-3",children:"Contact"}),e.jsx("th",{className:"px-4 py-3",children:"Phone"}),e.jsx("th",{className:"px-4 py-3",children:"Details"}),e.jsx("th",{className:"px-4 py-3",children:"Source"})]})}),e.jsx("tbody",{children:n?e.jsx("tr",{children:e.jsx("td",{colSpan:6,className:"px-4 py-12 text-center text-slate-500",children:"Loading…"})}):u.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:6,className:"px-4 py-12 text-center text-slate-500",children:"No leads yet in this range."})}):u.map(p=>{const g=g9[p.lead_type],x=g==null?void 0:g.icon,y=[p.first_name,p.last_name].filter(Boolean).join(" ")||"—";return e.jsxs("tr",{className:"border-b hover:bg-slate-50/60",children:[e.jsx("td",{className:"px-4 py-3 whitespace-nowrap text-slate-600 text-xs",children:dbt(p.created_at)}),e.jsx("td",{className:"px-4 py-3 whitespace-nowrap",children:e.jsxs(qe,{className:`${(g==null?void 0:g.color)||""} font-normal`,variant:"secondary",children:[x?e.jsx(x,{className:"h-3 w-3 mr-1"}):null,(g==null?void 0:g.label)||p.lead_type]})}),e.jsxs("td",{className:"px-4 py-3",children:[e.jsx("div",{className:"font-medium text-slate-900",children:y}),e.jsxs("a",{href:`mailto:${p.email}`,className:"text-xs text-blue-600 hover:underline inline-flex items-center gap-1",children:[e.jsx(pn,{className:"h-3 w-3"}),p.email]})]}),e.jsx("td",{className:"px-4 py-3 whitespace-nowrap",children:p.phone?e.jsxs("a",{href:`tel:${p.phone}`,className:"text-xs text-blue-600 hover:underline inline-flex items-center gap-1",children:[e.jsx(ka,{className:"h-3 w-3"}),p.phone]}):e.jsx("span",{className:"text-slate-400 text-xs",children:"—"})}),e.jsxs("td",{className:"px-4 py-3 text-xs text-slate-600 max-w-xs",children:[p.listing_id&&e.jsxs("div",{className:"mb-0.5",children:["Listing: ",e.jsxs("span",{className:"font-mono text-[10px]",children:[p.listing_id.slice(0,8),"…"]})]}),p.criteria&&Object.keys(p.criteria).length>0&&e.jsx("div",{className:"text-slate-500 line-clamp-2",children:Object.entries(p.criteria).map(([v,_])=>`${v}: ${_}`).join(" · ")})]}),e.jsxs("td",{className:"px-4 py-3 text-xs text-slate-500 max-w-xs truncate",children:[p.source_page&&e.jsxs("div",{className:"inline-flex items-center gap-1",children:[e.jsx(Ir,{className:"h-3 w-3"}),e.jsx("span",{className:"truncate",children:p.source_page})]}),p.referrer&&e.jsxs("div",{className:"text-slate-400 truncate",children:["from ",p.referrer]})]})]},p.id)})})]})})})]})]})}const qDn=()=>{var h,m;const[s,t]=k.useState(""),[n,r]=k.useState(null),{data:a,isLoading:i}=pt({queryKey:["membership-reviews"],queryFn:async()=>{const{data:p,error:g}=await V.from("membership_reviews").select("*").order("created_at",{ascending:!1});if(g)throw g;const x=(p==null?void 0:p.map(_=>_.user_id))||[],{data:y}=await V.from("profiles").select("id, name, email").in("id",x);return p==null?void 0:p.map(_=>({..._,profiles:(y==null?void 0:y.find(j=>j.id===_.user_id))||null}))}}),l=a==null?void 0:a.filter(p=>{var x,y,v,_,j;const g=s.toLowerCase();return((y=(x=p.profiles)==null?void 0:x.name)==null?void 0:y.toLowerCase().includes(g))||((_=(v=p.profiles)==null?void 0:v.email)==null?void 0:_.toLowerCase().includes(g))||((j=p.review_text)==null?void 0:j.toLowerCase().includes(g))}),o=a!=null&&a.length?(a.reduce((p,g)=>p+g.rating,0)/a.length).toFixed(1):"0.0",c=a==null?void 0:a.reduce((p,g)=>(p[g.rating]=(p[g.rating]||0)+1,p),{}),d=(a==null?void 0:a.filter(p=>p.posted_to_google).length)||0,u=p=>e.jsx("div",{className:"flex gap-0.5",children:[1,2,3,4,5].map(g=>e.jsx(ri,{className:Ot("h-4 w-4",p>=g?"fill-yellow-400 text-yellow-400":"text-muted-foreground")},g))});return e.jsx(Xs,{children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(nm,{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(we,{children:e.jsxs(Vt,{className:"pb-2",children:[e.jsx(vr,{children:"Total Reviews"}),e.jsx(Yt,{className:"text-3xl",children:(a==null?void 0:a.length)||0})]})}),e.jsx(we,{children:e.jsxs(Vt,{className:"pb-2",children:[e.jsx(vr,{children:"Average Rating"}),e.jsxs(Yt,{className:"flex items-center gap-2 text-3xl",children:[o,e.jsx(ri,{className:"h-6 w-6 fill-yellow-400 text-yellow-400"})]})]})}),e.jsx(we,{children:e.jsxs(Vt,{className:"pb-2",children:[e.jsx(vr,{children:"5-Star Reviews"}),e.jsx(Yt,{className:"text-3xl",children:(c==null?void 0:c[5])||0})]})}),e.jsx(we,{children:e.jsxs(Vt,{className:"pb-2",children:[e.jsx(vr,{children:"Posted to Google"}),e.jsxs(Yt,{className:"flex items-center gap-2 text-3xl",children:[d,e.jsx(Ir,{className:"h-5 w-5 text-muted-foreground"})]})]})})]}),e.jsxs("div",{className:"relative max-w-sm",children:[e.jsx(Yr,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(be,{placeholder:"Search by name, email, or review...",value:s,onChange:p=>t(p.target.value),className:"pl-9"})]}),e.jsx(we,{children:e.jsx(De,{className:"p-0",children:e.jsxs(Qa,{children:[e.jsx(Ja,{children:e.jsxs(vn,{children:[e.jsx(Dt,{children:"Member"}),e.jsx(Dt,{children:"Rating"}),e.jsx(Dt,{className:"hidden md:table-cell",children:"Review"}),e.jsx(Dt,{children:"Google"}),e.jsx(Dt,{children:"Date"})]})}),e.jsx(ei,{children:i?e.jsx(vn,{children:e.jsx(_t,{colSpan:5,className:"text-center py-8",children:"Loading reviews..."})}):(l==null?void 0:l.length)===0?e.jsx(vn,{children:e.jsx(_t,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No reviews found"})}):l==null?void 0:l.map(p=>{var g,x;return e.jsxs(vn,{className:"cursor-pointer hover:bg-muted/50",onClick:()=>r(p),children:[e.jsx(_t,{children:e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:((g=p.profiles)==null?void 0:g.name)||"Unknown"}),e.jsx("div",{className:"text-sm text-muted-foreground",children:(x=p.profiles)==null?void 0:x.email})]})}),e.jsx(_t,{children:u(p.rating)}),e.jsx(_t,{className:"hidden md:table-cell max-w-xs",children:e.jsx("p",{className:"truncate text-sm text-muted-foreground",children:p.review_text||"-"})}),e.jsx(_t,{children:p.posted_to_google?e.jsx(qe,{variant:"secondary",className:"bg-green-100 text-green-800",children:"Posted"}):e.jsx(qe,{variant:"outline",children:"No"})}),e.jsx(_t,{className:"text-sm text-muted-foreground",children:Ys(new Date(p.created_at),"MMM d, yyyy")})]},p.id)})})]})})}),e.jsx(zs,{open:!!n,onOpenChange:()=>r(null),children:e.jsxs(Rs,{className:"max-w-lg",children:[e.jsx(Vs,{children:e.jsx($s,{children:"Review Details"})}),n&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-start gap-4 p-4 bg-muted/50 rounded-lg",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx("h3",{className:"font-semibold text-lg",children:((h=n.profiles)==null?void 0:h.name)||"Unknown Member"}),((m=n.profiles)==null?void 0:m.email)&&e.jsxs("a",{href:`mailto:${n.profiles.email}`,className:"flex items-center gap-1 text-sm text-muted-foreground hover:text-primary",children:[e.jsx(pn,{className:"h-3 w-3"}),n.profiles.email]})]}),e.jsxs("div",{className:"text-right",children:[u(n.rating),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[n.rating," out of 5 stars"]})]})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-medium mb-2",children:"Review"}),e.jsx("p",{className:"text-sm text-muted-foreground whitespace-pre-wrap",children:n.review_text||"No written review provided."})]}),e.jsxs("div",{className:"flex items-center justify-between pt-4 border-t",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(ha,{className:"h-4 w-4"}),Ys(new Date(n.created_at),"MMMM d, yyyy 'at' h:mm a")]}),n.posted_to_google?e.jsxs(qe,{variant:"secondary",className:"bg-green-100 text-green-800",children:[e.jsx(Ir,{className:"h-3 w-3 mr-1"}),"Posted to Google"]}):e.jsx(qe,{variant:"outline",children:"Not posted to Google"})]})]})]})})]})})},ubt={agent_card:"Agent Card",listing:"Listing",lead_site:"Lead Site",guest_book:"Guest Book",landing_page:"Landing Page",connect_page:"Connect Page",booking:"Booking"},VDn={sent:"bg-green-100 text-green-800",backfilled:"bg-blue-100 text-blue-800",failed:"bg-red-100 text-red-800",pending:"bg-yellow-100 text-yellow-800"};function HDn(){const[s,t]=k.useState(""),[n,r]=k.useState("all"),[a,i]=k.useState("all"),[l,o]=k.useState("7"),{data:c,isLoading:d}=pt({queryKey:["lead-notification-log",l],queryFn:async()=>{const m=new Date(Date.now()-Number(l)*864e5).toISOString(),{data:p,error:g}=await V.from("lead_notification_log").select("*").gte("created_at",m).order("created_at",{ascending:!1}).limit(2e3);if(g)throw g;return p||[]}}),u=k.useMemo(()=>{const m=s.trim().toLowerCase();return(c||[]).filter(p=>n!=="all"&&p.source!==n||a!=="all"&&p.status!==a?!1:m?[p.agent_name,p.agent_email,p.lead_name,p.lead_email,p.lead_phone,p.subject].some(g=>(g||"").toLowerCase().includes(m)):!0)},[c,s,n,a]),h=k.useMemo(()=>{const m=u.length,p=u.filter(y=>y.status==="sent"||y.status==="backfilled").length,g=u.filter(y=>y.status==="failed").length,x=new Set(u.map(y=>y.agent_user_id).filter(Boolean)).size;return{total:m,sent:p,failed:g,agents:x}},[u]);return e.jsx(Xs,{children:e.jsxs("div",{className:"container mx-auto py-6 space-y-6",children:[e.jsx(nm,{title:"Lead Notifications",description:"Every new-lead notification sent to agents — agent cards, listings, lead sites, guest book sign-ins, landing pages, connect pages, and bookings."}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsx(we,{children:e.jsxs(De,{className:"p-4",children:[e.jsx("div",{className:"text-sm text-muted-foreground",children:"Total"}),e.jsx("div",{className:"text-2xl font-bold",children:h.total})]})}),e.jsx(we,{children:e.jsxs(De,{className:"p-4",children:[e.jsx("div",{className:"text-sm text-muted-foreground",children:"Sent"}),e.jsx("div",{className:"text-2xl font-bold text-green-600",children:h.sent})]})}),e.jsx(we,{children:e.jsxs(De,{className:"p-4",children:[e.jsx("div",{className:"text-sm text-muted-foreground",children:"Failed"}),e.jsx("div",{className:"text-2xl font-bold text-red-600",children:h.failed})]})}),e.jsx(we,{children:e.jsxs(De,{className:"p-4",children:[e.jsx("div",{className:"text-sm text-muted-foreground",children:"Unique Agents"}),e.jsx("div",{className:"text-2xl font-bold",children:h.agents})]})})]}),e.jsxs("div",{className:"flex flex-col md:flex-row gap-3",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Yr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search agent or lead name, email, phone…",value:s,onChange:m=>t(m.target.value),className:"pl-9"})]}),e.jsxs(bs,{value:n,onValueChange:r,children:[e.jsx(ys,{className:"w-full md:w-48",children:e.jsx(_s,{placeholder:"Source"})}),e.jsxs(vs,{children:[e.jsx(We,{value:"all",children:"All Sources"}),Object.entries(ubt).map(([m,p])=>e.jsx(We,{value:m,children:p},m))]})]}),e.jsxs(bs,{value:a,onValueChange:i,children:[e.jsx(ys,{className:"w-full md:w-40",children:e.jsx(_s,{placeholder:"Status"})}),e.jsxs(vs,{children:[e.jsx(We,{value:"all",children:"All Statuses"}),e.jsx(We,{value:"sent",children:"Sent"}),e.jsx(We,{value:"backfilled",children:"Backfilled"}),e.jsx(We,{value:"failed",children:"Failed"})]})]}),e.jsxs(bs,{value:l,onValueChange:o,children:[e.jsx(ys,{className:"w-full md:w-36",children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"1",children:"Last 24h"}),e.jsx(We,{value:"7",children:"Last 7 days"}),e.jsx(We,{value:"14",children:"Last 14 days"}),e.jsx(We,{value:"30",children:"Last 30 days"})]})]})]}),e.jsx(we,{children:e.jsx(De,{className:"p-0",children:e.jsxs(Qa,{children:[e.jsx(Ja,{children:e.jsxs(vn,{children:[e.jsx(Dt,{children:"When"}),e.jsx(Dt,{children:"Source"}),e.jsx(Dt,{children:"Agent"}),e.jsx(Dt,{children:"Lead"}),e.jsx(Dt,{children:"Status"})]})}),e.jsx(ei,{children:d?e.jsx(vn,{children:e.jsx(_t,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"Loading…"})}):u.length===0?e.jsx(vn,{children:e.jsx(_t,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No notifications match the current filters."})}):u.map(m=>e.jsxs(vn,{children:[e.jsx(_t,{className:"whitespace-nowrap text-sm",children:Ys(new Date(m.created_at),"MMM d, yyyy h:mm a")}),e.jsx(_t,{children:e.jsx(qe,{variant:"secondary",children:ubt[m.source]||m.source})}),e.jsxs(_t,{children:[e.jsx("div",{className:"font-medium",children:m.agent_name||"—"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:m.agent_email||"—"})]}),e.jsxs(_t,{children:[e.jsx("div",{className:"font-medium",children:m.lead_name||"—"}),e.jsxs("div",{className:"text-xs text-muted-foreground flex flex-wrap gap-x-3 gap-y-1",children:[m.lead_email&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(pn,{className:"h-3 w-3"}),m.lead_email]}),m.lead_phone&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ka,{className:"h-3 w-3"}),m.lead_phone]})]})]}),e.jsxs(_t,{children:[e.jsx(qe,{className:VDn[m.status]||"",children:m.status}),m.error_message&&e.jsx("div",{className:"text-xs text-red-600 mt-1 max-w-[220px] truncate",title:m.error_message,children:m.error_message})]})]},m.id))})]})})}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Historical entries (before this feature was enabled) are marked as ",e.jsx("em",{children:"backfilled"})," and reconstructed from the underlying lead records. New leads are logged automatically going forward."]})]})})}const GDn=[{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"}],WDn=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 KDn(){const s=ls(),{user:t}=ks(),[n,r]=k.useState(!1),[a,i]=k.useState(!1),[l,o]=k.useState(!1),{data:c,isLoading:d}=pt({queryKey:["weekly-digest-settings"],queryFn:async()=>{const{data:P,error:R}=await V.from("weekly_digest_settings").select("*").single();if(R)throw R;return P}}),{data:u,isLoading:h}=pt({queryKey:["weekly-digest-logs"],queryFn:async()=>{const{data:P,error:R}=await V.from("weekly_digest_logs").select("*").order("sent_at",{ascending:!1}).limit(100);if(R)throw R;return P}}),{data:m}=pt({queryKey:["digest-subscriber-count"],queryFn:async()=>{const{count:P,error:R}=await V.from("profiles").select("id",{count:"exact",head:!0}).eq("digest_opt_out",!1).not("email","is",null);if(R)throw R;return P||0}}),{data:p,refetch:g}=pt({queryKey:["digest-queue-status"],queryFn:async()=>{const P=new Date;P.setUTCHours(0,0,0,0);const[R,O,B,U]=await Promise.all([V.from("weekly_digest_send_queue").select("id",{count:"exact",head:!0}).eq("status","pending").gte("created_at",P.toISOString()),V.from("weekly_digest_send_queue").select("id",{count:"exact",head:!0}).eq("status","processing").gte("created_at",P.toISOString()),V.from("weekly_digest_send_queue").select("id",{count:"exact",head:!0}).eq("status","sent").gte("created_at",P.toISOString()),V.from("weekly_digest_send_queue").select("id",{count:"exact",head:!0}).eq("status","failed").gte("created_at",P.toISOString())]);return{pending:R.count||0,processing:O.count||0,sent:B.count||0,failed:U.count||0,total:(R.count||0)+(O.count||0)+(B.count||0)+(U.count||0)}},refetchInterval:5e3});k.useEffect(()=>{if(p&&(p.pending>0||p.processing>0)){const P=setInterval(()=>{g(),s.invalidateQueries({queryKey:["weekly-digest-logs"]}),s.invalidateQueries({queryKey:["digest-today-failed-count"]}),s.invalidateQueries({queryKey:["digest-today-missing-count"]})},5e3);return()=>clearInterval(P)}},[p,g,s]);const{data:x=0}=pt({queryKey:["digest-today-failed-count"],queryFn:async()=>{const P=new Date;P.setUTCHours(0,0,0,0);const{count:R,error:O}=await V.from("weekly_digest_logs").select("id",{count:"exact",head:!0}).eq("delivery_status","failed").gte("sent_at",P.toISOString());if(O)throw O;return R||0}}),y=Nt({mutationFn:async P=>{const{error:R}=await V.from("weekly_digest_settings").update(P).eq("id",c==null?void 0:c.id);if(R)throw R},onSuccess:()=>{s.invalidateQueries({queryKey:["weekly-digest-settings"]}),ae.success("Settings updated")},onError:P=>{ae.error("Failed to update settings: "+P.message)}}),v=async()=>{r(!0);try{const{data:P,error:R}=await V.functions.invoke("send-weekly-digest",{body:{manual:!0}});if(R)throw R;P.queued?ae.success(`${P.queued.toLocaleString()} emails queued! They'll be sent automatically (~80/minute).`):P.sent!==void 0&&ae.success(`Digest sent! ${P.sent} emails delivered, ${P.failed} failed`),g(),s.invalidateQueries({queryKey:["weekly-digest-logs"]})}catch(P){ae.error("Failed to send digest: "+P.message)}finally{r(!1)}},_=async()=>{var P,R,O,B,U,G;if(!(t!=null&&t.email)){ae.error("No email found for your account");return}i(!0);try{const{data:H,error:Y}=await V.functions.invoke("send-weekly-digest",{body:{preview:!0,previewEmail:t.email}});if(Y)throw Y;const se=H==null?void 0:H.resendId,ee=H==null?void 0:H.resendDetails,oe=ee==null?void 0:ee.status,me=((P=ee==null?void 0:ee.body)==null?void 0:P.status)||((O=(R=ee==null?void 0:ee.body)==null?void 0:R.data)==null?void 0:O.status),Q=((U=(B=ee==null?void 0:ee.body)==null?void 0:B.error)==null?void 0:U.message)||((G=ee==null?void 0:ee.body)==null?void 0:G.message);ae.success(se?`Preview accepted by email provider (id: ${se})${oe?`, status check: ${oe}`:""}${me?`, provider: ${me}`:""}${Q?` (${Q})`:""}. Check spam/promotions—delivery can take a few minutes.`:"Preview accepted by email provider. Check spam/promotions—delivery can take a few minutes.")}catch(H){ae.error("Failed to send preview: "+H.message)}finally{i(!1)}},j=async()=>{o(!0);try{const{data:P,error:R}=await V.functions.invoke("send-weekly-digest",{body:{retryFailed:!0}});if(R)throw R;P.queued===0||P.sent===0&&P.failed===0&&!P.queued?ae.info("No failed emails to retry"):P.queued?ae.success(`${P.queued} emails queued for retry!`):ae.success(`Retry complete! ${P.sent} emails delivered, ${P.failed} failed`),g(),s.invalidateQueries({queryKey:["weekly-digest-logs"]}),s.invalidateQueries({queryKey:["digest-today-failed-count"]}),s.invalidateQueries({queryKey:["digest-today-missing-count"]})}catch(P){ae.error("Failed to retry: "+P.message)}finally{o(!1)}},C=p!=null&&p.total?Math.round((p.sent+p.failed)/p.total*100):0,A=((p==null?void 0:p.pending)||0)>0||((p==null?void 0:p.processing)||0)>0,{data:M}=pt({queryKey:["digest-delivery-stats"],queryFn:async()=>{var G,H;const P=new Date;P.setUTCHours(0,0,0,0);const[R,O,B,U]=await Promise.all([V.from("weekly_digest_logs").select("id",{count:"exact",head:!0}).eq("delivery_status","sent").gte("sent_at",P.toISOString()),V.from("weekly_digest_logs").select("id",{count:"exact",head:!0}).eq("delivery_status","failed").gte("sent_at",P.toISOString()),V.from("weekly_digest_logs").select("id",{count:"exact",head:!0}).eq("has_agent_os_activity",!0).gte("sent_at",P.toISOString()),V.from("weekly_digest_logs").select("sent_at").order("sent_at",{ascending:!1}).limit(1)]);return{totalSent:R.count||0,totalFailed:O.count||0,agentOsEngaged:B.count||0,lastSent:((H=(G=U.data)==null?void 0:G[0])==null?void 0:H.sent_at)||null}},refetchInterval:A?5e3:!1}),I={totalSent:(M==null?void 0:M.totalSent)||0,totalFailed:(M==null?void 0:M.totalFailed)||0,lastSent:M==null?void 0:M.lastSent,agentOsEngaged:(M==null?void 0:M.agentOsEngaged)||0};return d?e.jsx(Xs,{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(Xs,{title:"Weekly Digest",description:"Configure and manage automated weekly email digests for members",children:e.jsxs(ya,{defaultValue:"settings",className:"space-y-6",children:[e.jsxs(va,{children:[e.jsxs(is,{value:"settings",className:"flex items-center gap-2",children:[e.jsx(Yc,{className:"h-4 w-4"}),"Settings"]}),e.jsxs(is,{value:"stats",className:"flex items-center gap-2",children:[e.jsx(Ul,{className:"h-4 w-4"}),"Delivery Stats"]})]}),e.jsxs(cs,{value:"settings",className:"space-y-6",children:[A&&p&&e.jsx(we,{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(Jt,{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:[p.sent.toLocaleString()," sent, ",p.pending.toLocaleString()," pending",p.failed>0&&`, ${p.failed} failed`]})]}),e.jsxs("span",{className:"text-sm font-medium",children:[C,"%"]})]}),e.jsx(ho,{value:C,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(p.pending/80)," min"]})]})}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-4",children:[e.jsx(we,{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(Xn,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:m}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Subscribers"})]})]})})}),e.jsx(we,{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(Gr,{className:"h-5 w-5 text-emerald-500"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:I.totalSent}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Delivered"})]})]})})}),e.jsx(we,{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(ju,{className:"h-5 w-5 text-destructive"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:I.totalFailed}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Failed"})]})]})})}),e.jsx(we,{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(sa,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:I.lastSent?Ys(new Date(I.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(we,{children:[e.jsxs(Vt,{children:[e.jsxs(Yt,{className:"flex items-center gap-2",children:[e.jsx(sa,{className:"h-5 w-5"}),"Schedule"]}),e.jsx(vr,{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(re,{children:"Enable Weekly Digest"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Send automated weekly emails to members"})]}),e.jsx(On,{checked:c==null?void 0:c.is_enabled,onCheckedChange:P=>y.mutate({is_enabled:P})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Cron Frequency"}),e.jsxs(bs,{value:(c==null?void 0:c.cron_frequency)||"daily",onValueChange:P=>y.mutate({cron_frequency:P}),children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"daily",children:"Daily (runs once at selected time)"}),e.jsx(We,{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(re,{children:"Day of Week"}),e.jsxs(bs,{value:String(c==null?void 0:c.send_day),onValueChange:P=>y.mutate({send_day:parseInt(P)}),children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsx(vs,{children:GDn.map(P=>e.jsx(We,{value:P.value,children:P.label},P.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Time (UTC)"}),e.jsxs(bs,{value:String(c==null?void 0:c.send_hour),onValueChange:P=>y.mutate({send_hour:parseInt(P)}),disabled:(c==null?void 0:c.cron_frequency)==="daily",children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsx(vs,{children:WDn.map(P=>e.jsx(We,{value:P.value,children:P.label},P.value))})]})]})]}),e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsxs($,{onClick:_,disabled:a,variant:"outline",className:"flex-1",children:[e.jsx(ba,{className:"h-4 w-4 mr-2"}),a?"Sending...":"Send Preview to Me"]}),e.jsxs($,{onClick:v,disabled:n,className:"flex-1",children:[e.jsx(Wr,{className:"h-4 w-4 mr-2"}),n?"Sending...":"Send to All"]})]}),x>0&&e.jsxs($,{onClick:j,disabled:l,variant:"outline",className:"w-full",children:[e.jsx(yo,{className:`h-4 w-4 mr-2 ${l?"animate-spin":""}`}),l?"Retrying...":`Retry ${x} Failed`]})]})]})]}),e.jsxs(we,{children:[e.jsxs(Vt,{children:[e.jsxs(Yt,{className:"flex items-center gap-2",children:[e.jsx(ea,{className:"h-5 w-5"}),"Content Sections"]}),e.jsx(vr,{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(ea,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(re,{children:"New Resources"})]}),e.jsx(On,{checked:c==null?void 0:c.include_new_resources,onCheckedChange:P=>y.mutate({include_new_resources:P})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Xn,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(re,{children:"Community Highlights"})]}),e.jsx(On,{checked:c==null?void 0:c.include_community_posts,onCheckedChange:P=>y.mutate({include_community_posts:P})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ul,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(re,{children:"Agent OS Stats"})]}),e.jsx(On,{checked:c==null?void 0:c.include_agent_os_stats,onCheckedChange:P=>y.mutate({include_agent_os_stats:P})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ha,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(re,{children:"Upcoming Events"})]}),e.jsx(On,{checked:c==null?void 0:c.include_upcoming_events,onCheckedChange:P=>y.mutate({include_upcoming_events:P})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(_h,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(re,{children:"Goals Progress"})]}),e.jsx(On,{checked:c==null?void 0:c.include_goals_progress,onCheckedChange:P=>y.mutate({include_goals_progress:P})})]})]})]})]}),e.jsxs(we,{children:[e.jsxs(Vt,{children:[e.jsx(Yt,{children:"Custom Introduction"}),e.jsx(vr,{children:"Personalize the intro message (optional)"})]}),e.jsx(De,{children:e.jsx(Ls,{placeholder:"Here's what's new this week to help you grow your business...",value:(c==null?void 0:c.custom_intro_text)||"",onChange:P=>y.mutate({custom_intro_text:P.target.value||null}),rows:3})})]})]}),e.jsx(cs,{value:"stats",children:e.jsxs(we,{children:[e.jsxs(Vt,{children:[e.jsxs(Yt,{className:"flex items-center gap-2",children:[e.jsx(pn,{className:"h-5 w-5"}),"Delivery History"]}),e.jsx(vr,{children:"Recent digest emails sent to members"})]}),e.jsx(De,{children:h?e.jsx("div",{className:"animate-pulse space-y-2",children:[1,2,3,4,5].map(P=>e.jsx("div",{className:"h-12 bg-muted rounded"},P))}):u&&u.length>0?e.jsxs(Qa,{children:[e.jsx(Ja,{children:e.jsxs(vn,{children:[e.jsx(Dt,{children:"Email"}),e.jsx(Dt,{children:"Sent At"}),e.jsx(Dt,{children:"Status"}),e.jsx(Dt,{children:"Resources"}),e.jsx(Dt,{children:"Agent OS"})]})}),e.jsx(ei,{children:u.map(P=>e.jsxs(vn,{children:[e.jsx(_t,{className:"font-medium",children:P.email_sent_to}),e.jsx(_t,{children:Ys(new Date(P.sent_at),"MMM d, yyyy h:mm a")}),e.jsx(_t,{children:e.jsx(qe,{variant:P.delivery_status==="sent"?"default":"destructive",children:P.delivery_status})}),e.jsx(_t,{children:P.resources_count}),e.jsx(_t,{children:P.has_agent_os_activity?e.jsx(qe,{variant:"secondary",children:"Active"}):e.jsx(qe,{variant:"outline",children:"Not Started"})})]},P.id))})]}):e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(pn,{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 YDn={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 ZDn(){var le,fe,_e;const s=ls(),[t,n]=k.useState(""),[r,a]=k.useState(null),[i,l]=k.useState(!1),[o,c]=k.useState(!1),[d,u]=k.useState(""),[h,m]=k.useState(""),[p,g]=k.useState(!0),[x,y]=k.useState(!1),[v,_]=k.useState(""),[j,C]=k.useState(null),{data:A,isLoading:M}=pt({queryKey:["admin-agent-points"],queryFn:async()=>{const{data:ve,error:he}=await V.from("agent_attendance_stats").select("*").order("total_points",{ascending:!1});if(he)throw he;const Se=(ve==null?void 0:ve.map(Ue=>Ue.user_id))||[],{data:Te}=await V.from("profiles").select("id, name, email").in("id",Se),Ie=new Map((Te==null?void 0:Te.map(Ue=>[Ue.id,{name:Ue.name,email:Ue.email}]))||[]);return ve==null?void 0:ve.map(Ue=>({...Ue,profile:Ie.get(Ue.user_id)||null}))}}),{data:I}=pt({queryKey:["all-profiles-for-points",A],queryFn:async()=>{const he=[];let Se=0;for(;;){const{data:Te,error:Ie}=await V.from("profiles").select("id, name, email").order("name").range(Se,Se+1e3-1);if(Ie)throw Ie;if(he.push(...Te),!Te||Te.length<1e3)break;Se+=1e3}return he}}),R=((I==null?void 0:I.filter(ve=>!(A!=null&&A.some(he=>he.user_id===ve.id))))||[]).filter(ve=>{var Se,Te;if(!v)return!0;const he=v.toLowerCase();return((Se=ve.name)==null?void 0:Se.toLowerCase().includes(he))||((Te=ve.email)==null?void 0:Te.toLowerCase().includes(he))}),{data:O,isLoading:B}=pt({queryKey:["agent-point-history",r==null?void 0:r.user_id],queryFn:async()=>{if(!(r!=null&&r.user_id))return[];const{data:ve,error:he}=await V.from("agent_points").select("*").eq("user_id",r.user_id).order("created_at",{ascending:!1});if(he)throw he;return ve},enabled:!!(r!=null&&r.user_id)&&o}),{data:U}=pt({queryKey:["agent-badges",r==null?void 0:r.user_id],queryFn:async()=>{if(!(r!=null&&r.user_id))return[];const{data:ve,error:he}=await V.from("agent_badges").select("*").eq("user_id",r.user_id).order("earned_at",{ascending:!1});if(he)throw he;return ve},enabled:!!(r!=null&&r.user_id)}),G=Nt({mutationFn:async({userId:ve,points:he,reason:Se})=>{const{error:Te}=await V.from("agent_points").insert({user_id:ve,points:he,reason:Se});if(Te)throw Te;const{data:Ie}=await V.from("agent_attendance_stats").select("total_points, spendable_points").eq("user_id",ve).maybeSingle(),Ue=((Ie==null?void 0:Ie.total_points)||0)+he,Be=((Ie==null?void 0:Ie.spendable_points)||0)+he,{error:je}=await V.from("agent_attendance_stats").upsert({user_id:ve,total_points:Math.max(0,Ue),spendable_points:Math.max(0,Be),updated_at:new Date().toISOString()},{onConflict:"user_id"});if(je)throw je},onSuccess:()=>{s.invalidateQueries({queryKey:["admin-agent-points"]}),s.invalidateQueries({queryKey:["agent-point-history"]}),l(!1),u(""),m(""),ae.success(p?"Points awarded successfully!":"Points deducted successfully!")},onError:ve=>{console.error("Error modifying points:",ve),ae.error("Failed to modify points")}}),H=()=>{if(!r||!d||!h){ae.error("Please fill in all fields");return}const ve=parseInt(d);if(isNaN(ve)||ve<=0){ae.error("Please enter a valid positive number");return}G.mutate({userId:r.user_id,points:p?ve:-ve,reason:h})},Y=()=>{if(!j||!d||!h){ae.error("Please fill in all fields");return}const ve=parseInt(d);if(isNaN(ve)||ve<=0){ae.error("Please enter a valid positive number");return}G.mutate({userId:j.id,points:ve,reason:h},{onSuccess:()=>{y(!1),C(null),_("")}})},se=(ve,he)=>{a(ve),g(he),l(!0)},ee=ve=>{a(ve),c(!0)},oe=A==null?void 0:A.filter(ve=>{var Ie,Ue,Be,je;const he=((Ue=(Ie=ve.profile)==null?void 0:Ie.name)==null?void 0:Ue.toLowerCase())||"",Se=((je=(Be=ve.profile)==null?void 0:Be.email)==null?void 0:je.toLowerCase())||"",Te=t.toLowerCase();return he.includes(Te)||Se.includes(Te)}),me=(A==null?void 0:A.reduce((ve,he)=>ve+he.total_points,0))||0,Q=(A==null?void 0:A.length)||0,te=Q>0?Math.round(me/Q):0;return M?e.jsx(Xs,{title:"Agent Points",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(fn,{className:"h-8 w-64"}),e.jsx("div",{className:"grid grid-cols-3 gap-4",children:[1,2,3].map(ve=>e.jsx(fn,{className:"h-24"},ve))}),e.jsx(fn,{className:"h-96"})]})}):e.jsx(Xs,{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(we,{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(Xn,{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:Q}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"with points tracked"})]})}),e.jsx(we,{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(ql,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Total Points"})]}),e.jsx("p",{className:"text-2xl font-bold",children:me.toLocaleString()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"awarded across all agents"})]})}),e.jsx(we,{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(mc,{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:te}),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(Yr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search agents...",value:t,onChange:ve=>n(ve.target.value),className:"pl-10"})]}),e.jsxs($,{onClick:()=>y(!0),children:[e.jsx(nn,{className:"h-4 w-4 mr-2"}),"Award Points to New Agent"]})]}),e.jsxs(we,{children:[e.jsxs(Vt,{children:[e.jsx(Yt,{children:"Agent Leaderboard"}),e.jsx(vr,{children:"All agents with their points, events, and streaks"})]}),e.jsx(De,{children:!oe||oe.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(ql,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No agents with points yet"})]}):e.jsxs(Qa,{children:[e.jsx(Ja,{children:e.jsxs(vn,{children:[e.jsx(Dt,{className:"w-12",children:"#"}),e.jsx(Dt,{children:"Agent"}),e.jsx(Dt,{className:"text-center",children:"Total Points"}),e.jsx(Dt,{className:"text-center",children:"Spendable"}),e.jsx(Dt,{className:"text-center",children:"Events"}),e.jsx(Dt,{className:"text-center",children:"Streak"}),e.jsx(Dt,{className:"text-right",children:"Actions"})]})}),e.jsx(ei,{children:oe.map((ve,he)=>{var Se,Te,Ie,Ue;return e.jsxs(vn,{children:[e.jsx(_t,{className:"font-medium",children:he<3?e.jsx("div",{className:`w-6 h-6 rounded-full flex items-center justify-center ${he===0?"bg-yellow-100 text-yellow-700":he===1?"bg-gray-100 text-gray-600":"bg-amber-100 text-amber-700"}`,children:he+1}):e.jsx("span",{className:"text-muted-foreground",children:he+1})}),e.jsx(_t,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Wa,{className:"h-8 w-8",children:e.jsx(Ka,{children:((Te=(Se=ve.profile)==null?void 0:Se.name)==null?void 0:Te.charAt(0))||"?"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:((Ie=ve.profile)==null?void 0:Ie.name)||"Unknown"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:(Ue=ve.profile)==null?void 0:Ue.email})]})]})}),e.jsx(_t,{className:"text-center",children:e.jsxs(qe,{variant:"secondary",className:"font-bold",children:[e.jsx(ri,{className:"h-3 w-3 mr-1"}),ve.total_points]})}),e.jsx(_t,{className:"text-center",children:e.jsxs(qe,{variant:"outline",className:"font-bold text-primary",children:[e.jsx(Zo,{className:"h-3 w-3 mr-1"}),ve.spendable_points||0]})}),e.jsx(_t,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(ha,{className:"h-3 w-3 text-muted-foreground"}),ve.total_events_attended]})}),e.jsx(_t,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(iu,{className:"h-3 w-3 text-orange-500"}),ve.current_streak]})}),e.jsx(_t,{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-1",children:[e.jsx($,{variant:"ghost",size:"sm",onClick:()=>se(ve,!0),title:"Award points",children:e.jsx(nn,{className:"h-4 w-4 text-green-600"})}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>se(ve,!1),title:"Deduct points",children:e.jsx(ak,{className:"h-4 w-4 text-red-600"})}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>ee(ve),title:"View history",children:e.jsx(b2,{className:"h-4 w-4"})})]})})]},ve.user_id)})})]})})]}),e.jsx(zs,{open:i,onOpenChange:l,children:e.jsxs(Rs,{children:[e.jsxs(Vs,{children:[e.jsx($s,{children:p?"Award Points":"Deduct Points"}),e.jsxs(Cr,{children:[p?"Award":"Deduct"," points ",p?"to":"from"," ",((le=r==null?void 0:r.profile)==null?void 0:le.name)||"this agent"]})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"points",children:"Points Amount"}),e.jsx(be,{id:"points",type:"number",min:"1",placeholder:"Enter points...",value:d,onChange:ve=>u(ve.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"reason",children:"Reason"}),e.jsx(Ls,{id:"reason",placeholder:"Enter reason for this adjustment...",value:h,onChange:ve=>m(ve.target.value)})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsx($,{onClick:H,disabled:G.isPending,className:p?"bg-green-600 hover:bg-green-700":"bg-red-600 hover:bg-red-700",children:G.isPending?"Saving...":p?"Award Points":"Deduct Points"})]})]})}),e.jsx(zs,{open:o,onOpenChange:c,children:e.jsxs(Rs,{className:"max-w-2xl",children:[e.jsxs(Vs,{children:[e.jsxs($s,{children:["Point History: ",(fe=r==null?void 0:r.profile)==null?void 0:fe.name]}),e.jsx(Cr,{children:"View all point transactions and badges for this agent"})]}),e.jsxs(ya,{defaultValue:"history",className:"w-full",children:[e.jsxs(va,{className:"grid w-full grid-cols-2",children:[e.jsx(is,{value:"history",children:"Point History"}),e.jsx(is,{value:"badges",children:"Badges"})]}),e.jsx(cs,{value:"history",className:"mt-4",children:B?e.jsx("div",{className:"space-y-2",children:[1,2,3].map(ve=>e.jsx(fn,{className:"h-12"},ve))}):!O||O.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(b2,{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:O.map(ve=>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:ve.reason}),e.jsx("p",{className:"text-xs text-muted-foreground",children:Ys(new Date(ve.created_at),"MMM d, yyyy h:mm a")})]}),e.jsxs(qe,{variant:ve.points>=0?"default":"destructive",className:ve.points>=0?"bg-green-100 text-green-800":"",children:[ve.points>=0?"+":"",ve.points]})]},ve.id))})}),e.jsx(cs,{value:"badges",className:"mt-4",children:!U||U.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(oh,{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:U.map(ve=>e.jsxs("div",{className:`p-3 rounded-lg ${YDn[ve.badge_type]||"bg-gray-100"}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(oh,{className:"h-5 w-5"}),e.jsx("span",{className:"font-medium",children:ve.badge_name})]}),ve.badge_description&&e.jsx("p",{className:"text-xs mt-1 opacity-80",children:ve.badge_description}),e.jsxs("p",{className:"text-xs mt-1 opacity-60",children:["Earned ",Ys(new Date(ve.earned_at),"MMM d, yyyy")]})]},ve.id))})})]})]})}),e.jsx(zs,{open:x,onOpenChange:ve=>{y(ve),ve||(C(null),_(""),u(""),m(""))},children:e.jsxs(Rs,{className:"max-w-md",children:[e.jsxs(Vs,{children:[e.jsx($s,{children:"Award Points to New Agent"}),e.jsx(Cr,{children:"Select an agent who doesn't have points yet and award them points"})]}),e.jsx("div",{className:"space-y-4 py-4",children:j?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-3 p-3 bg-muted/50 rounded-lg",children:[e.jsx(Wa,{className:"h-10 w-10",children:e.jsx(Ka,{children:((_e=j.name)==null?void 0:_e.charAt(0))||"?"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"font-medium",children:j.name||"Unknown"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:j.email})]}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>C(null),children:"Change"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"new-points",children:"Points Amount"}),e.jsx(be,{id:"new-points",type:"number",min:"1",placeholder:"Enter points...",value:d,onChange:ve=>u(ve.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"new-reason",children:"Reason"}),e.jsx(Ls,{id:"new-reason",placeholder:"Enter reason for awarding points...",value:h,onChange:ve=>m(ve.target.value)})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Search Agent"}),e.jsxs("div",{className:"relative",children:[e.jsx(Yr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search by name or email...",value:v,onChange:ve=>_(ve.target.value),className:"pl-10"})]})]}),e.jsx("div",{className:"max-h-60 overflow-y-auto border rounded-lg",children:R.length===0?e.jsxs("div",{className:"text-center py-4 text-muted-foreground",children:[e.jsx(Xn,{className:"h-6 w-6 mx-auto mb-2 opacity-50"}),e.jsx("p",{className:"text-sm",children:v?"No matching agents found":"All agents already have points"})]}):R.slice(0,20).map(ve=>{var he;return e.jsxs("button",{onClick:()=>C(ve),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(Wa,{className:"h-8 w-8",children:e.jsx(Ka,{children:((he=ve.name)==null?void 0:he.charAt(0))||"?"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:ve.name||"Unknown"}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:ve.email})]})]},ve.id)})})]})}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>y(!1),children:"Cancel"}),j&&e.jsxs($,{onClick:Y,disabled:G.isPending,className:"bg-green-600 hover:bg-green-700",children:[e.jsx(nn,{className:"h-4 w-4 mr-2"}),"Award Points"]})]})]})})]})})}function XDn(){const{data:s,isLoading:t}=Gws(),[n,r]=k.useState(null),[a,i]=k.useState(!1),[l,o]=k.useState(""),[c,d]=k.useState("all"),[u,h]=k.useState("newest"),[m,p]=k.useState("table"),g=k.useMemo(()=>(s==null?void 0:s.map(j=>j.user_id))||[],[s]),x=k.useMemo(()=>(s==null?void 0:s.map(j=>j.id))||[],[s]),{data:y}=pt({queryKey:["card-profiles-lookup",g],queryFn:async()=>{if(g.length===0)return{};const{data:j}=await V.from("profiles").select("id, name, email").in("id",g),C={};return j==null||j.forEach(A=>{C[A.id]={name:A.name||"",email:A.email||""}}),C},enabled:g.length>0}),{data:v}=pt({queryKey:["card-stats-all",x],queryFn:async()=>{if(x.length===0)return{};const j={};x.forEach(M=>{j[M]={views:0,leads:0}});const{data:C}=await V.from("agent_card_interactions").select("card_id").in("card_id",x).eq("interaction_type","card_view");C==null||C.forEach(M=>{j[M.card_id]&&j[M.card_id].views++});const{data:A}=await V.from("agent_card_leads").select("card_id").in("card_id",x);return A==null||A.forEach(M=>{j[M.card_id]&&j[M.card_id].leads++}),j},enabled:x.length>0}),_=k.useMemo(()=>{if(!s)return[];let j=[...s];if(c==="live"?j=j.filter(C=>C.is_published):c==="draft"&&(j=j.filter(C=>!C.is_published)),l.trim()){const C=l.toLowerCase();j=j.filter(A=>{var I,P;const M=y==null?void 0:y[A.user_id];return A.slug.toLowerCase().includes(C)||((I=M==null?void 0:M.name)==null?void 0:I.toLowerCase().includes(C))||((P=M==null?void 0:M.email)==null?void 0:P.toLowerCase().includes(C))})}return u==="newest"?j.sort((C,A)=>new Date(A.created_at).getTime()-new Date(C.created_at).getTime()):u==="oldest"?j.sort((C,A)=>new Date(C.created_at).getTime()-new Date(A.created_at).getTime()):u==="name"?j.sort((C,A)=>{var M,I;return(((M=y==null?void 0:y[C.user_id])==null?void 0:M.name)||"").localeCompare(((I=y==null?void 0:y[A.user_id])==null?void 0:I.name)||"")}):u==="slug"?j.sort((C,A)=>C.slug.localeCompare(A.slug)):u==="views_desc"?j.sort((C,A)=>{var M,I;return(((M=v==null?void 0:v[A.id])==null?void 0:M.views)||0)-(((I=v==null?void 0:v[C.id])==null?void 0:I.views)||0)}):u==="views_asc"?j.sort((C,A)=>{var M,I;return(((M=v==null?void 0:v[C.id])==null?void 0:M.views)||0)-(((I=v==null?void 0:v[A.id])==null?void 0:I.views)||0)}):u==="leads_desc"?j.sort((C,A)=>{var M,I;return(((M=v==null?void 0:v[A.id])==null?void 0:M.leads)||0)-(((I=v==null?void 0:v[C.id])==null?void 0:I.leads)||0)}):u==="leads_asc"&&j.sort((C,A)=>{var M,I;return(((M=v==null?void 0:v[C.id])==null?void 0:M.leads)||0)-(((I=v==null?void 0:v[A.id])==null?void 0:I.leads)||0)}),j},[s,c,l,u,y]);return e.jsxs(Xs,{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($,{onClick:()=>i(!0),children:[e.jsx(nn,{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(Yr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search by name, email, or slug...",value:l,onChange:j=>o(j.target.value),className:"pl-9"})]}),e.jsxs(bs,{value:c,onValueChange:d,children:[e.jsx(ys,{className:"w-full sm:w-36",children:e.jsx(_s,{placeholder:"Status"})}),e.jsxs(vs,{children:[e.jsx(We,{value:"all",children:"All Status"}),e.jsx(We,{value:"live",children:"Live"}),e.jsx(We,{value:"draft",children:"Draft"})]})]}),e.jsxs(bs,{value:u,onValueChange:h,children:[e.jsx(ys,{className:"w-full sm:w-44",children:e.jsx(_s,{placeholder:"Sort by"})}),e.jsxs(vs,{children:[e.jsx(We,{value:"newest",children:"Newest First"}),e.jsx(We,{value:"oldest",children:"Oldest First"}),e.jsx(We,{value:"name",children:"Name A–Z"}),e.jsx(We,{value:"slug",children:"Slug A–Z"}),e.jsx(We,{value:"views_desc",children:"Most Views"}),e.jsx(We,{value:"views_asc",children:"Fewest Views"}),e.jsx(We,{value:"leads_desc",children:"Most Leads"}),e.jsx(We,{value:"leads_asc",children:"Fewest Leads"})]})]}),e.jsxs("div",{className:"flex border rounded-md",children:[e.jsx($,{variant:m==="table"?"default":"ghost",size:"sm",onClick:()=>p("table"),className:"rounded-r-none",children:e.jsx(hB,{className:"h-4 w-4"})}),e.jsx($,{variant:m==="grid"?"default":"ghost",size:"sm",onClick:()=>p("grid"),className:"rounded-l-none",children:e.jsx(y0,{className:"h-4 w-4"})})]})]}),!t&&s&&s.length>0&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Showing ",_.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(j=>e.jsx(fn,{className:"h-48"},j))}):_.length>0?m==="table"?e.jsx(QDn,{cards:_,cardProfiles:y,cardStats:v,onEdit:r,sortBy:u,setSortBy:h}):e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:_.map(j=>e.jsx(JDn,{card:j,onEdit:()=>r(j),stats:v==null?void 0:v[j.id]},j.id))}):s&&s.length>0?e.jsx(we,{children:e.jsxs(De,{className:"flex flex-col items-center justify-center py-12",children:[e.jsx(Yr,{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(we,{children:e.jsxs(De,{className:"flex flex-col items-center justify-center py-12",children:[e.jsx(Xn,{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($,{onClick:()=>i(!0),children:[e.jsx(nn,{className:"h-4 w-4 mr-2"}),"Create Card"]})]})})]}),e.jsx(e8n,{open:a,onOpenChange:i}),n&&e.jsx(t8n,{card:n,open:!!n,onOpenChange:j=>!j&&r(null)})]})}function QDn({cards:s,cardProfiles:t,cardStats:n,onEdit:r,sortBy:a,setSortBy:i}){const l=c=>{a===`${c}_desc`?i(`${c}_asc`):i(`${c}_desc`)},o=({field:c})=>a===`${c}_desc`?e.jsx(nx,{className:"h-3 w-3"}):a===`${c}_asc`?e.jsx(ap,{className:"h-3 w-3"}):e.jsx(Ix,{className:"h-3 w-3 opacity-40"});return e.jsx(we,{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(ap,{className:"h-3 w-3"})]})}),e.jsx("th",{className:"text-left p-3 font-medium text-muted-foreground hidden md:table-cell",children:"Slug"}),e.jsx("th",{className:"text-center p-3 font-medium text-muted-foreground",children:"Status"}),e.jsx("th",{className:"text-right p-3 font-medium",children:e.jsxs("button",{onClick:()=>l("views"),className:"flex items-center gap-1 ml-auto hover:text-foreground text-muted-foreground",children:["Views ",e.jsx(o,{field:"views"})]})}),e.jsx("th",{className:"text-right p-3 font-medium",children:e.jsxs("button",{onClick:()=>l("leads"),className:"flex items-center gap-1 ml-auto hover:text-foreground text-muted-foreground",children:["Leads ",e.jsx(o,{field:"leads"})]})}),e.jsx("th",{className:"text-right p-3 font-medium text-muted-foreground",children:"Actions"})]})}),e.jsx("tbody",{children:s.map(c=>{const d=t==null?void 0:t[c.user_id],u=n==null?void 0:n[c.id],h=`https://cards.relevelup.com/${c.slug}`;return e.jsxs("tr",{className:"border-b last:border-0 hover:bg-muted/30 transition-colors",children:[e.jsx("td",{className:"p-3",children:e.jsxs("div",{children:[e.jsx("span",{className:"font-medium",children:(d==null?void 0:d.name)||"Unknown"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:(d==null?void 0:d.email)||""})]})}),e.jsx("td",{className:"p-3 hidden md:table-cell",children:e.jsxs("span",{className:"text-xs text-muted-foreground font-mono",children:["/",c.slug]})}),e.jsx("td",{className:"p-3 text-center",children:e.jsx(qe,{variant:c.is_published?"default":"secondary",className:"text-xs",children:c.is_published?"Live":"Draft"})}),e.jsx("td",{className:"p-3 text-right tabular-nums font-medium",children:(u==null?void 0:u.views)??0}),e.jsx("td",{className:"p-3 text-right tabular-nums font-medium",children:(u==null?void 0:u.leads)??0}),e.jsx("td",{className:"p-3",children:e.jsxs("div",{className:"flex items-center justify-end gap-1",children:[e.jsx($,{variant:"ghost",size:"sm",onClick:()=>r(c),className:"h-8 w-8 p-0",children:e.jsx(ui,{className:"h-3.5 w-3.5"})}),e.jsx($,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>{navigator.clipboard.writeText(h),ae.success("Link copied!")},children:e.jsx(Da,{className:"h-3.5 w-3.5"})}),e.jsx($,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",asChild:!0,children:e.jsx("a",{href:h,target:"_blank",rel:"noopener noreferrer",children:e.jsx(Ir,{className:"h-3.5 w-3.5"})})})]})})]},c.id)})})]})})})}function JDn({card:s,onEdit:t,stats:n}){const[r,a]=k.useState(null);k.useEffect(()=>{(async()=>{const{data:c}=await V.from("profiles").select("name").eq("id",s.user_id).single();let d=null;try{const{data:u}=await V.storage.from("avatars").list(`${s.user_id}`);if(u&&u.length>0){const{data:h}=V.storage.from("avatars").getPublicUrl(`${s.user_id}/${u[0].name}`);d=h.publicUrl}}catch{}a({name:(c==null?void 0:c.name)||"Unknown",avatar_url:d})})()},[s.user_id]);const i=`https://cards.relevelup.com/${s.slug}`,l=()=>{navigator.clipboard.writeText(i),ae.success("Link copied!")};return e.jsx(we,{children:e.jsxs(De,{className:"p-4",children:[e.jsxs("div",{className:"flex items-start gap-3 mb-3",children:[e.jsxs(Wa,{className:"h-10 w-10",children:[e.jsx(eo,{src:(r==null?void 0:r.avatar_url)||void 0}),e.jsx(Ka,{children:((r==null?void 0:r.name)||"U")[0]})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h3",{className:"font-semibold truncate",children:(r==null?void 0:r.name)||"Loading..."}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:["/card/",s.slug]})]}),e.jsx(qe,{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(ba,{className:"h-3.5 w-3.5"}),(n==null?void 0:n.views)??0," views"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Xn,{className:"h-3.5 w-3.5"}),(n==null?void 0:n.leads)??0," leads"]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs($,{variant:"outline",size:"sm",onClick:t,className:"flex-1",children:[e.jsx(ui,{className:"h-3 w-3 mr-1"}),"Edit"]}),e.jsx($,{variant:"outline",size:"sm",onClick:l,children:e.jsx(Da,{className:"h-3 w-3"})}),e.jsx($,{variant:"outline",size:"sm",asChild:!0,children:e.jsx("a",{href:i,target:"_blank",rel:"noopener noreferrer",children:e.jsx(Ir,{className:"h-3 w-3"})})})]})]})})}function e8n({open:s,onOpenChange:t}){const[n,r]=k.useState(""),[a,i]=k.useState(""),[l,o]=k.useState(""),[c,d]=k.useState(!1),u=eEt(),h=l.trim(),{data:m}=pt({queryKey:["profiles-search-for-cards",h],queryFn:async()=>{let _=V.from("profiles").select("id, name, email").order("name").limit(50);h.length>=2&&(_=_.or(`name.ilike.%${h}%,email.ilike.%${h}%`));const{data:j}=await _;return j||[]},enabled:s}),[p,g]=k.useState(null),x=(m==null?void 0:m.find(_=>_.id===n))||p,y=()=>{if(!n||!a.trim()){ae.error("Select an agent and enter a slug");return}u.mutate({user_id:n,slug:a.trim().toLowerCase().replace(/[^a-z0-9-]/g,"-"),is_published:!0},{onSuccess:()=>{t(!1),r(""),i(""),o("")}})},v=_=>{var C;r(_),d(!1);const j=m==null?void 0:m.find(A=>A.id===_);j&&(g(j),i(((C=j.name)==null?void 0:C.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/(^-|-$)/g,""))||""))};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Rs,{children:[e.jsxs(Vs,{children:[e.jsx($s,{children:"Create Agent Card"}),e.jsx(Cr,{children:"Select an agent and set their card URL slug."})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Agent"}),e.jsxs(Xc,{open:c,onOpenChange:d,children:[e.jsx(Qc,{asChild:!0,children:e.jsxs($,{variant:"outline",role:"combobox","aria-expanded":c,className:"w-full justify-between font-normal",children:[x?`${x.name} (${x.email})`:"Search for an agent...",e.jsx(v_,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(Bc,{className:"w-[--radix-popover-trigger-width] p-0",align:"start",children:e.jsxs(M_,{shouldFilter:!1,children:[e.jsx(P_,{placeholder:"Search by name or email...",value:l,onValueChange:o}),e.jsxs(I_,{children:[e.jsx(L_,{children:"No agents found."}),e.jsx(Nb,{children:(m||[]).map(_=>e.jsxs(rv,{value:_.id,onSelect:v,children:[e.jsx(ma,{className:Ot("mr-2 h-4 w-4",n===_.id?"opacity-100":"opacity-0")}),_.name," (",_.email,")"]},_.id))})]})]})})]})]}),e.jsxs("div",{children:[e.jsx(re,{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(be,{value:a,onChange:_=>i(_.target.value),placeholder:"john-doe"})]})]}),e.jsx($,{onClick:y,disabled:u.isPending,className:"w-full",children:u.isPending?"Creating...":"Create Card"})]})]})})}function t8n({card:s,open:t,onOpenChange:n}){const r=tEt(),{data:a}=sEt(s.id),i=ls(),[l,o]=k.useState(null),[c,d]=k.useState(!1),[u,h]=k.useState(!1),[m,p]=k.useState(""),[g,x]=k.useState(s.slug),[y,v]=k.useState(!1),[_,j]=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:O}=await V.storage.from("avatars").list(`${s.user_id}`);if(O&&O.length>0){const{data:B}=V.storage.from("avatars").getPublicUrl(`${s.user_id}/${O[0].name}`);o(`${B.publicUrl}?t=${Date.now()}`)}}catch{}})()},[s.user_id,t]);const C=R=>{var U;const O=(U=R.target.files)==null?void 0:U[0];if(!O)return;if(!O.type.startsWith("image/")){ae.error("Please select an image file");return}if(O.size>5*1024*1024){ae.error("Image must be under 5MB");return}const B=new FileReader;B.onloadend=()=>{p(B.result),h(!0)},B.readAsDataURL(O),R.target.value=""},A=async R=>{d(!0);try{const{data:O}=await V.storage.from("avatars").list(`${s.user_id}`);O&&O.length>0&&await V.storage.from("avatars").remove(O.map(Y=>`${s.user_id}/${Y.name}`));const B=`${s.user_id}/avatar.jpg`,{error:U}=await V.storage.from("avatars").upload(B,R,{upsert:!0,contentType:"image/jpeg"});if(U)throw U;const{data:G}=V.storage.from("avatars").getPublicUrl(B),H=`${G.publicUrl}?t=${Date.now()}`;o(H),await V.from("profiles").update({avatar_url:H}).eq("id",s.user_id),i.invalidateQueries({queryKey:["agent-card-public"]}),ae.success("Photo updated!")}catch(O){ae.error(O.message||"Upload failed")}finally{d(!1)}},M=async()=>{const R=g.trim().toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/(^-|-$)/g,"");if(!R){ae.error("Please enter a valid URL");return}if(R===s.slug){ae.info("No changes to save");return}v(!0);try{const{data:O}=await V.from("agent_cards").select("id").eq("slug",R).neq("id",s.id).maybeSingle();if(O){ae.error("This URL is already taken. Try another one.");return}const{error:B}=await V.from("agent_cards").update({slug:R}).eq("id",s.id);if(B)throw B;x(R),i.invalidateQueries({queryKey:["agent-cards-admin"]}),ae.success("Card address updated!")}catch{ae.error("Failed to update card address")}finally{v(!1)}},I=async(R,O)=>{var U;const B=(U=R.target.files)==null?void 0:U[0];if(B){if(!B.type.startsWith("image/")){ae.error("Please select an image file");return}try{const G=B.name.split(".").pop()||"png",H=O==="brokerage_logo_url"?"brokerage-logo":"team-logo",Y=`${s.user_id}/${H}.${G}`,{error:se}=await V.storage.from("card-logos").upload(Y,B,{upsert:!0});if(se)throw se;const{data:ee}=V.storage.from("card-logos").getPublicUrl(Y),oe=ee.publicUrl+"?t="+Date.now();j(O==="brokerage_logo_url"?me=>({...me,[O]:oe,brokerage_display_name:""}):me=>({...me,[O]:oe,team_name:""})),ae.success("Logo uploaded!")}catch{ae.error("Failed to upload logo")}finally{R.target.value=""}}},P=()=>{r.mutate({id:s.id,..._,title:_.title||null,positioning_statement:_.positioning_statement||null,bio:_.bio||null,review_snippet:_.review_snippet||null,review_source_url:_.review_source_url||null,booking_url:_.booking_url||null,custom_cta_label:_.custom_cta_label||null,custom_cta_url:_.custom_cta_url||null,brokerage_display_name:_.brokerage_display_name||null,brokerage_logo_url:_.brokerage_logo_url||null,brokerage_logo_size:_.brokerage_logo_size,team_name:_.team_name||null,team_logo_url:_.team_logo_url||null,team_logo_size:_.team_logo_size},{onSuccess:()=>n(!1)})};return e.jsxs(e.Fragment,{children:[e.jsx(zs,{open:t,onOpenChange:n,children:e.jsxs(Rs,{className:"max-w-2xl max-h-[85vh] overflow-y-auto",children:[e.jsxs(Vs,{children:[e.jsx($s,{children:"Edit Agent Card"}),e.jsxs(Cr,{children:["/card/",s.slug]})]}),e.jsxs(ya,{defaultValue:"content",children:[e.jsxs(va,{className:"w-full",children:[e.jsx(is,{value:"content",className:"flex-1",children:"Content"}),e.jsx(is,{value:"sections",className:"flex-1",children:"Sections"}),e.jsx(is,{value:"blocks",className:"flex-1",children:"Blocks"}),e.jsx(is,{value:"analytics",className:"flex-1",children:"Analytics"})]}),e.jsxs(cs,{value:"content",className:"space-y-4 mt-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(re,{children:"Published"}),e.jsx(On,{checked:_.is_published,onCheckedChange:R=>j(O=>({...O,is_published:R}))})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Agent Photo"}),e.jsxs("div",{className:"flex items-center gap-4 mt-1",children:[e.jsxs(Wa,{className:"h-16 w-16",children:[e.jsx(eo,{src:l||void 0}),e.jsx(Ka,{children:"?"})]}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:C,disabled:c}),e.jsx($,{variant:"outline",size:"sm",asChild:!0,disabled:c,children:e.jsx("span",{children:c?e.jsxs(e.Fragment,{children:[e.jsx(Jt,{className:"h-3 w-3 mr-1 animate-spin"}),"Uploading..."]}):e.jsxs(e.Fragment,{children:[e.jsx(gi,{className:"h-3 w-3 mr-1"}),"Change Photo"]})})})]})]})]}),e.jsxs("div",{children:[e.jsx(re,{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(be,{value:g,onChange:R=>x(R.target.value.toLowerCase().replace(/[^a-z0-9-]/g,"-")),placeholder:"agent-name",className:"rounded-l-none"})]}),e.jsx($,{variant:"outline",size:"sm",onClick:M,disabled:y||g===s.slug,className:"shrink-0",children:y?"Saving...":"Update"})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Theme"}),e.jsxs(bs,{value:_.theme,onValueChange:R=>j(O=>({...O,theme:R})),children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"standard",children:"✨ Standard (Modern Clean)"}),e.jsx(We,{value:"luxury",children:"🌙 Luxury (Dark & Gold)"}),e.jsx(We,{value:"bold",children:"🔥 Bold (Vibrant & Punchy)"}),e.jsx(We,{value:"classic",children:"📋 Classic (Professional)"})]})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Title / Tagline"}),e.jsx(be,{value:_.title,onChange:R=>j(O=>({...O,title:R.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(re,{children:"Positioning Statement"}),e.jsx(be,{value:_.positioning_statement,onChange:R=>j(O=>({...O,positioning_statement:R.target.value})),placeholder:"Your home journey, handled with care."})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Bio"}),e.jsx(Ls,{value:_.bio,onChange:R=>j(O=>({...O,bio:R.target.value})),placeholder:"Short about me...",rows:3})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Review Snippet"}),e.jsx(be,{value:_.review_snippet,onChange:R=>j(O=>({...O,review_snippet:R.target.value})),placeholder:"Best agent we've ever worked with..."})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Review Source URL"}),e.jsx(be,{value:_.review_source_url,onChange:R=>j(O=>({...O,review_source_url:R.target.value})),placeholder:"https://g.page/your-business/review"})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Booking URL (optional — if empty, shows lead form)"}),e.jsx(be,{value:_.booking_url,onChange:R=>j(O=>({...O,booking_url:R.target.value})),placeholder:"https://calendly.com/your-link"})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Custom CTA Label (optional)"}),e.jsx(be,{value:_.custom_cta_label,onChange:R=>j(O=>({...O,custom_cta_label:R.target.value})),placeholder:"Book a Call"})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Custom CTA URL (optional)"}),e.jsx(be,{value:_.custom_cta_url,onChange:R=>j(O=>({...O,custom_cta_url:R.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(re,{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:"Brokerage Branding"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(be,{value:_.brokerage_display_name,onChange:R=>j(O=>({...O,brokerage_display_name:R.target.value,brokerage_logo_url:""})),placeholder:"Brokerage name (or upload logo below)",disabled:!!_.brokerage_logo_url}),e.jsxs("div",{className:"flex items-center gap-3",children:[_.brokerage_logo_url&&e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:_.brokerage_logo_url,alt:"Brokerage logo",style:{height:`${_.brokerage_logo_size||56}px`},className:"max-w-[200px] object-contain rounded border bg-white p-1"}),e.jsx("button",{onClick:()=>j(R=>({...R,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(gi,{className:"h-3.5 w-3.5"}),_.brokerage_logo_url?"Change Logo":"Upload Logo"]}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:R=>I(R,"brokerage_logo_url")})]})]}),_.brokerage_logo_url&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(re,{className:"text-xs font-medium text-muted-foreground",children:"Logo Size"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[_.brokerage_logo_size||56,"px"]})]}),e.jsx(sx,{value:[_.brokerage_logo_size||56],onValueChange:([R])=>j(O=>({...O,brokerage_logo_size:R})),min:24,max:120,step:4})]})]})]}),e.jsxs("div",{className:"space-y-3 p-3 rounded-lg bg-muted/30 border",children:[e.jsx(re,{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:"Team Branding"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(be,{value:_.team_name,onChange:R=>j(O=>({...O,team_name:R.target.value,team_logo_url:""})),placeholder:"Team name (or upload logo below)",disabled:!!_.team_logo_url}),e.jsxs("div",{className:"flex items-center gap-3",children:[_.team_logo_url&&e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:_.team_logo_url,alt:"Team logo",style:{height:`${_.team_logo_size||56}px`},className:"max-w-[200px] object-contain rounded border bg-white p-1"}),e.jsx("button",{onClick:()=>j(R=>({...R,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(gi,{className:"h-3.5 w-3.5"}),_.team_logo_url?"Change Logo":"Upload Logo"]}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:R=>I(R,"team_logo_url")})]})]}),_.team_logo_url&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(re,{className:"text-xs font-medium text-muted-foreground",children:"Logo Size"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[_.team_logo_size||56,"px"]})]}),e.jsx(sx,{value:[_.team_logo_size||56],onValueChange:([R])=>j(O=>({...O,team_logo_size:R})),min:24,max:120,step:4})]})]})]})]}),e.jsx(cs,{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:R,label:O,hint:B})=>e.jsxs("div",{className:"flex items-center justify-between py-2",children:[e.jsxs("div",{children:[e.jsx(re,{children:O}),B&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5",children:[B," ",R==="show_photo"&&e.jsx("a",{href:"/profile",target:"_blank",rel:"noopener noreferrer",className:"text-primary underline hover:no-underline",children:"Update Profile"})]})]}),e.jsx(On,{checked:_[R],onCheckedChange:U=>j(G=>({...G,[R]:U}))})]},R))}),e.jsx(cs,{value:"blocks",className:"mt-4",children:e.jsx(fVt,{cardId:s.id})}),e.jsx(cs,{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(we,{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(we,{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(we,{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(R=>e.jsxs("div",{className:"text-sm p-2 bg-muted/50 rounded-lg",children:[e.jsx("span",{className:"font-medium",children:R.name}),R.phone&&e.jsxs("span",{className:"text-muted-foreground",children:[" · ",R.phone]}),R.intent&&e.jsx(qe,{variant:"secondary",className:"ml-2 text-xs",children:R.intent})]},R.id))})]})]}):e.jsx("p",{className:"text-center text-muted-foreground py-8",children:"No analytics data yet"})})]}),e.jsx($,{onClick:P,disabled:r.isPending,className:"w-full mt-4",children:r.isPending?"Saving...":"Save Changes"})]})}),e.jsx(pKe,{open:u,onClose:()=>h(!1),imageSrc:m,onCropComplete:A,aspectRatio:1})]})}const qB={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"},xQe={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 yQe(s=!0){return pt({queryKey:["marketplace-categories",s],queryFn:async()=>{let t=V.from("marketplace_categories").select("*").order("sort_order",{ascending:!0});s&&(t=t.eq("is_active",!0));const{data:n,error:r}=await t;if(r)throw r;return n}})}function s8n(){const s=ls();return Nt({mutationFn:async t=>{const{data:n,error:r}=await V.from("marketplace_categories").insert([t]).select().single();if(r)throw r;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["marketplace-categories"]}),ae.success("Category created successfully")},onError:t=>{ae.error("Failed to create category: "+t.message)}})}function n8n(){const s=ls();return Nt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await V.from("marketplace_categories").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["marketplace-categories"]}),ae.success("Category updated successfully")},onError:t=>{ae.error("Failed to update category: "+t.message)}})}function r8n(){const s=ls();return Nt({mutationFn:async t=>{const{error:n}=await V.from("marketplace_categories").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["marketplace-categories"]}),ae.success("Category deleted successfully")},onError:t=>{ae.error("Failed to delete category: "+t.message)}})}function vVt(s,t=!0){return pt({queryKey:["marketplace-products",s,t],queryFn:async()=>{let n=V.from("marketplace_products").select(` *, category:marketplace_categories(*), images:marketplace_product_images(*), video:marketplace_product_videos(*), variants:marketplace_product_variants(*) `).order("sort_order",{ascending:!0});s&&(n=n.eq("category_id",s)),t&&(n=n.eq("is_active",!0));const{data:r,error:a}=await n;if(a)throw a;return r}})}function a8n(s){return pt({queryKey:["marketplace-product",s],queryFn:async()=>{const{data:t,error:n}=await V.from("marketplace_products").select(` *, category:marketplace_categories(*), images:marketplace_product_images(*), video:marketplace_product_videos(*), variants:marketplace_product_variants(*) `).eq("id",s).single();if(n)throw n;return t},enabled:!!s})}function i8n(){const s=ls();return Nt({mutationFn:async t=>{const{data:n,error:r}=await V.from("marketplace_products").insert([t]).select().single();if(r)throw r;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["marketplace-products"]}),ae.success("Product created successfully")},onError:t=>{ae.error("Failed to create product: "+t.message)}})}function o8n(){const s=ls();return Nt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await V.from("marketplace_products").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["marketplace-products"]}),s.invalidateQueries({queryKey:["marketplace-product",n.id]}),ae.success("Product updated successfully")},onError:t=>{ae.error("Failed to update product: "+t.message)}})}function l8n(){const s=ls();return Nt({mutationFn:async t=>{const{error:n}=await V.from("marketplace_products").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["marketplace-products"]}),ae.success("Product deleted successfully")},onError:t=>{ae.error("Failed to delete product: "+t.message)}})}function c8n(){const s=ls();return Nt({mutationFn:async t=>{const{data:n,error:r}=await V.from("marketplace_product_images").insert([t]).select().single();if(r)throw r;return n},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["marketplace-products"]}),s.invalidateQueries({queryKey:["marketplace-product",n.product_id]})}})}function d8n(){const s=ls();return Nt({mutationFn:async({id:t,productId:n})=>{const{error:r}=await V.from("marketplace_product_images").delete().eq("id",t);if(r)throw r;return n},onSuccess:t=>{s.invalidateQueries({queryKey:["marketplace-products"]}),s.invalidateQueries({queryKey:["marketplace-product",t]}),ae.success("Image deleted successfully")},onError:t=>{ae.error("Failed to delete image: "+t.message)}})}function u8n(){const s=ls();return Nt({mutationFn:async({imageId:t,productId:n})=>{const{error:r}=await V.from("marketplace_product_images").update({is_primary:!1}).eq("product_id",n);if(r)throw r;const{error:a}=await V.from("marketplace_product_images").update({is_primary:!0}).eq("id",t);if(a)throw a;return n},onSuccess:t=>{s.invalidateQueries({queryKey:["marketplace-products"]}),s.invalidateQueries({queryKey:["marketplace-product",t]}),ae.success("Primary image updated")},onError:t=>{ae.error("Failed to set primary image: "+t.message)}})}function h8n(){const s=ls();return Nt({mutationFn:async t=>{const{data:n,error:r}=await V.from("marketplace_product_variants").insert([t]).select().single();if(r)throw r;return n},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["marketplace-products"]}),s.invalidateQueries({queryKey:["marketplace-product",n.product_id]}),ae.success("Variant added successfully")}})}function m8n(){const s=ls();return Nt({mutationFn:async({id:t,productId:n})=>{const{error:r}=await V.from("marketplace_product_variants").delete().eq("id",t);if(r)throw r;return n},onSuccess:t=>{s.invalidateQueries({queryKey:["marketplace-products"]}),s.invalidateQueries({queryKey:["marketplace-product",t]}),ae.success("Variant deleted successfully")}})}function f8n(){const s=ls();return Nt({mutationFn:async({productId:t,videoUrl:n})=>{await V.from("marketplace_product_videos").delete().eq("product_id",t);const{data:r,error:a}=await V.from("marketplace_product_videos").insert({product_id:t,video_url:n}).select().single();if(a)throw a;return r},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["marketplace-products"]}),s.invalidateQueries({queryKey:["marketplace-product",n.productId]}),ae.success("Video updated successfully")}})}function p8n(s){const{isAdmin:t}=ks();return pt({queryKey:["marketplace-orders",s,t],queryFn:async()=>{let n=V.from("marketplace_orders").select(` *, items:marketplace_order_items(*), status_history:marketplace_order_status_history(*) `).order("created_at",{ascending:!1});const{data:r,error:a}=await n;if(a)throw a;if(t&&r){const i=[...new Set(r.map(c=>c.user_id))],{data:l}=await V.from("profiles").select("id, name, email").in("id",i),o=new Map((l==null?void 0:l.map(c=>[c.id,c]))||[]);return r.map(c=>({...c,user:o.get(c.user_id)}))}return r}})}function g8n(){const{user:s}=ks();return pt({queryKey:["my-marketplace-orders",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await V.from("marketplace_orders").select(` *, items:marketplace_order_items(*), status_history:marketplace_order_status_history(*) `).eq("user_id",s.id).order("created_at",{ascending:!1});if(n)throw n;return t},enabled:!!(s!=null&&s.id)})}function x8n(s){return pt({queryKey:["marketplace-order",s],queryFn:async()=>{const{data:t,error:n}=await V.from("marketplace_orders").select(` *, items:marketplace_order_items(*), status_history:marketplace_order_status_history(*) `).eq("id",s).single();if(n)throw n;return t},enabled:!!s})}function y8n(){const s=ls(),{user:t}=ks();return Nt({mutationFn:async({orderId:n,status:r,notes:a,trackingNumber:i,trackingUrl:l,previousStatus:o})=>{const c={status:r};i!==void 0&&(c.tracking_number=i),l!==void 0&&(c.tracking_url=l);const{error:d}=await V.from("marketplace_orders").update(c).eq("id",n);if(d)throw d;const{error:u}=await V.from("marketplace_order_status_history").insert({order_id:n,status:r,notes:a,created_by:t==null?void 0:t.id});if(u)throw u;if(["shipped","in_production","processing","completed"].includes(r)&&r!==o)try{await V.functions.invoke("marketplace-order-notify",{body:{orderId:n,notificationType:r==="shipped"?"shipped":"status_update",newStatus:r,trackingNumber:i,trackingUrl:l}})}catch(m){console.error("Failed to send notification email:",m)}},onSuccess:(n,r)=>{s.invalidateQueries({queryKey:["marketplace-orders"]}),s.invalidateQueries({queryKey:["marketplace-order",r.orderId]}),s.invalidateQueries({queryKey:["my-marketplace-orders"]}),ae.success("Order status updated")},onError:n=>{ae.error("Failed to update order: "+n.message)}})}function v8n(){const s=ls();return Nt({mutationFn:async({itemId:t,proofUrl:n,proofNotes:r,orderId:a})=>{const{error:i}=await V.from("marketplace_order_items").update({proof_url:n,proof_notes:r,proof_status:"pending"}).eq("id",t);if(i)throw i;await V.from("marketplace_orders").update({status:"awaiting_proof_approval"}).eq("id",a);try{await V.functions.invoke("marketplace-order-notify",{body:{orderId:a,notificationType:"proof_ready"}})}catch(l){console.error("Failed to send proof notification:",l)}return a},onSuccess:t=>{s.invalidateQueries({queryKey:["marketplace-orders"]}),s.invalidateQueries({queryKey:["marketplace-order",t]}),s.invalidateQueries({queryKey:["my-marketplace-orders"]}),ae.success("Proof uploaded & customer notified")}})}function b8n(){const s=ls();return Nt({mutationFn:async({itemId:t,orderId:n})=>{const{error:r}=await V.from("marketplace_order_items").update({proof_status:"approved"}).eq("id",t);if(r)throw r;return n},onSuccess:t=>{s.invalidateQueries({queryKey:["marketplace-orders"]}),s.invalidateQueries({queryKey:["marketplace-order",t]}),s.invalidateQueries({queryKey:["my-marketplace-orders"]}),ae.success("Proof approved")}})}function _8n(){const s=ls();return Nt({mutationFn:async({itemId:t,orderId:n,reason:r})=>{const{error:a}=await V.from("marketplace_order_items").update({proof_status:"rejected",proof_notes:r}).eq("id",t);if(a)throw a;return n},onSuccess:t=>{s.invalidateQueries({queryKey:["marketplace-orders"]}),s.invalidateQueries({queryKey:["marketplace-order",t]}),s.invalidateQueries({queryKey:["my-marketplace-orders"]}),ae.success("Proof rejected - please upload a new proof")}})}function w8n(){const{data:s,isLoading:t}=yQe(!1),n=s8n(),r=n8n(),a=r8n(),[i,l]=k.useState(!1),[o,c]=k.useState(null),[d,u]=k.useState({name:"",description:"",image_url:"",sort_order:0,is_active:!0}),h=()=>{u({name:"",description:"",image_url:"",sort_order:0,is_active:!0}),c(null)},m=x=>{c(x),u({name:x.name,description:x.description||"",image_url:x.image_url||"",sort_order:x.sort_order,is_active:x.is_active}),l(!0)},p=async x=>{x.preventDefault(),o?await r.mutateAsync({id:o.id,...d}):await n.mutateAsync(d),l(!1),h()},g=async x=>{await io("Are you sure you want to delete this category?")&&await a.mutateAsync(x)};return t?e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsx(fn,{className:"h-8 w-48"})}),e.jsx(De,{children:e.jsx("div",{className:"space-y-4",children:[1,2,3].map(x=>e.jsx(fn,{className:"h-12 w-full"},x))})})]}):e.jsxs(we,{children:[e.jsxs(Vt,{className:"flex flex-row items-center justify-between",children:[e.jsx(Yt,{children:"Categories"}),e.jsxs(zs,{open:i,onOpenChange:x=>{l(x),x||h()},children:[e.jsx(yl,{asChild:!0,children:e.jsxs($,{children:[e.jsx(nn,{className:"h-4 w-4 mr-2"}),"Add Category"]})}),e.jsxs(Rs,{children:[e.jsx(Vs,{children:e.jsx($s,{children:o?"Edit Category":"Add Category"})}),e.jsxs("form",{onSubmit:p,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"name",children:"Name"}),e.jsx(be,{id:"name",value:d.name,onChange:x=>u({...d,name:x.target.value}),required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"description",children:"Description"}),e.jsx(Ls,{id:"description",value:d.description,onChange:x=>u({...d,description:x.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"image_url",children:"Image URL"}),e.jsx(be,{id:"image_url",value:d.image_url,onChange:x=>u({...d,image_url:x.target.value}),placeholder:"https://..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"sort_order",children:"Sort Order"}),e.jsx(be,{id:"sort_order",type:"number",value:d.sort_order,onChange:x=>u({...d,sort_order:parseInt(x.target.value)||0})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(On,{id:"is_active",checked:d.is_active,onCheckedChange:x=>u({...d,is_active:x})}),e.jsx(re,{htmlFor:"is_active",children:"Active"})]}),e.jsx($,{type:"submit",className:"w-full",disabled:n.isPending||r.isPending,children:o?"Update Category":"Create Category"})]})]})]})]}),e.jsx(De,{children:s&&s.length>0?e.jsxs(Qa,{children:[e.jsx(Ja,{children:e.jsxs(vn,{children:[e.jsx(Dt,{children:"Name"}),e.jsx(Dt,{children:"Description"}),e.jsx(Dt,{children:"Sort Order"}),e.jsx(Dt,{children:"Status"}),e.jsx(Dt,{className:"text-right",children:"Actions"})]})}),e.jsx(ei,{children:s.map(x=>e.jsxs(vn,{children:[e.jsx(_t,{className:"font-medium",children:x.name}),e.jsx(_t,{className:"max-w-xs truncate",children:x.description}),e.jsx(_t,{children:x.sort_order}),e.jsx(_t,{children:e.jsx("span",{className:`px-2 py-1 rounded-full text-xs ${x.is_active?"bg-green-100 text-green-800":"bg-gray-100 text-gray-800"}`,children:x.is_active?"Active":"Inactive"})}),e.jsx(_t,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx($,{variant:"ghost",size:"icon",onClick:()=>m(x),children:e.jsx(ui,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>g(x.id),disabled:a.isPending,children:e.jsx(Un,{className:"h-4 w-4 text-destructive"})})]})})]},x.id))})]}):e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"No categories yet. Create your first category to get started."})})]})}function j8n(){var te,le;const{data:s,isLoading:t}=vVt(void 0,!1),{data:n}=yQe(!1),r=i8n(),a=o8n(),i=l8n(),l=c8n(),o=d8n(),c=u8n(),d=h8n(),u=m8n(),h=f8n(),[m,p]=k.useState(!1),[g,x]=k.useState(!1),[y,v]=k.useState(!1),[_,j]=k.useState(null),[C,A]=k.useState(null),[M,I]=k.useState(!1),[P,R]=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}),[O,B]=k.useState({name:"",price_adjustment:0}),[U,G]=k.useState(""),H=()=>{R({name:"",description:"",base_price:0,shipping_fee:0,category_id:"",allow_artwork_upload:!1,requires_proof_approval:!1,is_active:!0,sort_order:0}),j(null)},Y=fe=>{j(fe),R({name:fe.name,description:fe.description||"",base_price:Number(fe.base_price),shipping_fee:Number(fe.shipping_fee),category_id:fe.category_id||"",allow_artwork_upload:fe.allow_artwork_upload,requires_proof_approval:fe.requires_proof_approval,is_active:fe.is_active,sort_order:fe.sort_order}),p(!0)},se=async fe=>{fe.preventDefault();const _e={...P,category_id:P.category_id||null};_?await a.mutateAsync({id:_.id,..._e}):await r.mutateAsync(_e),p(!1),H()},ee=async fe=>{await io("Are you sure you want to delete this product?")&&await i.mutateAsync(fe)},oe=async fe=>{if(!C||!fe.target.files||fe.target.files.length===0)return;I(!0);const _e=fe.target.files[0],ve=_e.name.split(".").pop(),he=`products/${C.id}/${Date.now()}.${ve}`;try{const{error:Se}=await V.storage.from("marketplace").upload(he,_e);if(Se)throw Se;const{data:{publicUrl:Te}}=V.storage.from("marketplace").getPublicUrl(he);await l.mutateAsync({product_id:C.id,image_url:Te,is_primary:!C.images||C.images.length===0}),ae.success("Image uploaded successfully")}catch(Se){ae.error("Failed to upload image: "+Se.message)}finally{I(!1)}},me=async fe=>{fe.preventDefault(),C&&(await d.mutateAsync({product_id:C.id,name:O.name,price_adjustment:O.price_adjustment}),B({name:"",price_adjustment:0}))},Q=async()=>{!C||!U||(await h.mutateAsync({productId:C.id,videoUrl:U}),G(""))};return t?e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsx(fn,{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(fe=>e.jsx(fn,{className:"h-64 w-full"},fe))})})]}):e.jsxs(e.Fragment,{children:[e.jsxs(we,{children:[e.jsxs(Vt,{className:"flex flex-row items-center justify-between",children:[e.jsx(Yt,{children:"Products"}),e.jsxs(zs,{open:m,onOpenChange:fe=>{p(fe),fe||H()},children:[e.jsx(yl,{asChild:!0,children:e.jsxs($,{children:[e.jsx(nn,{className:"h-4 w-4 mr-2"}),"Add Product"]})}),e.jsxs(Rs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Vs,{children:e.jsx($s,{children:_?"Edit Product":"Add Product"})}),e.jsxs("form",{onSubmit:se,className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"name",children:"Product Name"}),e.jsx(be,{id:"name",value:P.name,onChange:fe=>R({...P,name:fe.target.value}),required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"category",children:"Category"}),e.jsxs(bs,{value:P.category_id,onValueChange:fe=>R({...P,category_id:fe}),children:[e.jsx(ys,{children:e.jsx(_s,{placeholder:"Select category"})}),e.jsx(vs,{children:n==null?void 0:n.map(fe=>e.jsx(We,{value:fe.id,children:fe.name},fe.id))})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"description",children:"Description"}),e.jsx(Ls,{id:"description",value:P.description,onChange:fe=>R({...P,description:fe.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(re,{htmlFor:"base_price",children:"Base Price ($)"}),e.jsx(be,{id:"base_price",type:"number",step:"0.01",min:"0",value:P.base_price,onChange:fe=>R({...P,base_price:parseFloat(fe.target.value)||0}),required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"shipping_fee",children:"Shipping Fee ($)"}),e.jsx(be,{id:"shipping_fee",type:"number",step:"0.01",min:"0",value:P.shipping_fee,onChange:fe=>R({...P,shipping_fee:parseFloat(fe.target.value)||0})})]})]}),e.jsx("div",{className:"grid grid-cols-2 gap-4",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"sort_order",children:"Sort Order"}),e.jsx(be,{id:"sort_order",type:"number",value:P.sort_order,onChange:fe=>R({...P,sort_order:parseInt(fe.target.value)||0})})]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(On,{id:"allow_artwork_upload",checked:P.allow_artwork_upload,onCheckedChange:fe=>R({...P,allow_artwork_upload:fe})}),e.jsx(re,{htmlFor:"allow_artwork_upload",children:"Allow customer to upload artwork"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(On,{id:"requires_proof_approval",checked:P.requires_proof_approval,onCheckedChange:fe=>R({...P,requires_proof_approval:fe})}),e.jsx(re,{htmlFor:"requires_proof_approval",children:"Requires proof approval"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(On,{id:"is_active",checked:P.is_active,onCheckedChange:fe=>R({...P,is_active:fe})}),e.jsx(re,{htmlFor:"is_active",children:"Active"})]})]}),e.jsx($,{type:"submit",className:"w-full",disabled:r.isPending||a.isPending,children:_?"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(fe=>{var _e,ve;return e.jsxs(we,{className:"overflow-hidden",children:[e.jsxs("div",{className:"aspect-video bg-muted relative",children:[fe.images&&fe.images.length>0?e.jsx("img",{src:((_e=fe.images.find(he=>he.is_primary))==null?void 0:_e.image_url)||fe.images[0].image_url,alt:fe.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"}),!fe.is_active&&e.jsx(qe,{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:fe.name}),e.jsx("p",{className:"text-sm text-muted-foreground mb-2",children:((ve=fe.category)==null?void 0:ve.name)||"No category"}),e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("span",{className:"font-bold",children:["$",Number(fe.base_price).toFixed(2)]}),Number(fe.shipping_fee)>0&&e.jsxs("span",{className:"text-sm text-muted-foreground",children:["+$",Number(fe.shipping_fee).toFixed(2)," shipping"]})]}),e.jsxs("div",{className:"flex flex-wrap gap-1 mb-3",children:[fe.allow_artwork_upload&&e.jsx(qe,{variant:"outline",className:"text-xs",children:"Artwork Upload"}),fe.requires_proof_approval&&e.jsx(qe,{variant:"outline",className:"text-xs",children:"Proof Required"}),fe.variants&&fe.variants.length>0&&e.jsxs(qe,{variant:"outline",className:"text-xs",children:[fe.variants.length," Variants"]})]}),e.jsxs("div",{className:"flex gap-2 flex-wrap",children:[e.jsxs($,{variant:"outline",size:"sm",onClick:()=>Y(fe),children:[e.jsx(ui,{className:"h-3 w-3 mr-1"}),"Edit"]}),e.jsxs($,{variant:"outline",size:"sm",onClick:()=>{A(fe),x(!0)},children:[e.jsx(gb,{className:"h-3 w-3 mr-1"}),"Images"]}),e.jsxs($,{variant:"outline",size:"sm",onClick:()=>{A(fe),v(!0)},children:[e.jsx(kg,{className:"h-3 w-3 mr-1"}),"Variants"]}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>ee(fe.id),children:e.jsx(Un,{className:"h-3 w-3 text-destructive"})})]})]})]},fe.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(zs,{open:g,onOpenChange:x,children:e.jsxs(Rs,{className:"max-w-2xl",children:[e.jsx(Vs,{children:e.jsxs($s,{children:["Manage Images - ",C==null?void 0:C.name]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"grid grid-cols-3 gap-4",children:(te=C==null?void 0:C.images)==null?void 0:te.map(fe=>e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:fe.image_url,alt:"",className:"w-full aspect-square object-cover rounded-lg"}),fe.is_primary&&e.jsx(qe,{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:[!fe.is_primary&&e.jsx($,{variant:"secondary",size:"icon",onClick:async()=>{var _e;await c.mutateAsync({imageId:fe.id,productId:C.id}),A({...C,images:(_e=C.images)==null?void 0:_e.map(ve=>({...ve,is_primary:ve.id===fe.id}))})},disabled:c.isPending,title:"Set as primary",children:e.jsx(ri,{className:"h-4 w-4"})}),e.jsx($,{variant:"destructive",size:"icon",onClick:async()=>{var ve;await o.mutateAsync({id:fe.id,productId:C.id});const _e=s==null?void 0:s.find(he=>he.id===C.id);_e&&A({..._e,images:(ve=_e.images)==null?void 0:ve.filter(he=>he.id!==fe.id)})},disabled:o.isPending,children:e.jsx(Un,{className:"h-4 w-4"})})]})]},fe.id))}),e.jsxs("div",{className:"border-2 border-dashed rounded-lg p-6 text-center",children:[e.jsx("input",{type:"file",accept:"image/*",onChange:oe,className:"hidden",id:"image-upload",disabled:M}),e.jsxs("label",{htmlFor:"image-upload",className:"cursor-pointer",children:[e.jsx(gb,{className:"h-8 w-8 mx-auto mb-2 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:M?"Uploading...":"Click to upload an image"})]})]}),e.jsxs("div",{className:"border-t pt-4 mt-4",children:[e.jsx(re,{children:"Product Video (optional)"}),e.jsxs("div",{className:"flex gap-2 mt-2",children:[e.jsx(be,{placeholder:"Enter video URL (YouTube, Vimeo, etc.)",value:U,onChange:fe=>G(fe.target.value)}),e.jsxs($,{onClick:Q,disabled:!U,children:[e.jsx(ia,{className:"h-4 w-4 mr-2"}),"Set Video"]})]}),(C==null?void 0:C.video)&&e.jsxs("p",{className:"text-sm text-muted-foreground mt-2",children:["Current video: ",C.video.video_url]})]})]})]})}),e.jsx(zs,{open:y,onOpenChange:v,children:e.jsxs(Rs,{children:[e.jsx(Vs,{children:e.jsxs($s,{children:["Manage Variants - ",C==null?void 0:C.name]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("form",{onSubmit:me,className:"flex gap-2",children:[e.jsx(be,{placeholder:"Variant name (e.g., 500 count)",value:O.name,onChange:fe=>B({...O,name:fe.target.value}),required:!0}),e.jsx(be,{type:"number",step:"0.01",placeholder:"Price adj.",value:O.price_adjustment,onChange:fe=>B({...O,price_adjustment:parseFloat(fe.target.value)||0}),className:"w-32"}),e.jsx($,{type:"submit",children:"Add"})]}),e.jsxs("div",{className:"space-y-2",children:[(le=C==null?void 0:C.variants)==null?void 0:le.map(fe=>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:fe.name}),e.jsxs("span",{className:"text-sm text-muted-foreground ml-2",children:[Number(fe.price_adjustment)>=0?"+":"","$",Number(fe.price_adjustment).toFixed(2)]})]}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>u.mutateAsync({id:fe.id,productId:C.id}),children:e.jsx(Un,{className:"h-4 w-4 text-destructive"})})]},fe.id)),(!(C!=null&&C.variants)||C.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 N8n=["pending_payment","order_submitted","awaiting_proof_approval","proof_approved","processing","in_production","shipped","completed","cancelled","refunded"];function k8n(){var x,y,v;const{data:s,isLoading:t}=p8n(),n=y8n(),r=v8n(),[a,i]=k.useState(null),[l,o]=k.useState(!1),[c,d]=k.useState({status:"",notes:"",trackingNumber:"",trackingUrl:""}),[u,h]=k.useState(!1),m=_=>{i(_),d({status:_.status,notes:"",trackingNumber:_.tracking_number||"",trackingUrl:_.tracking_url||""}),o(!0)},p=async()=>{a&&(await n.mutateAsync({orderId:a.id,status:c.status,notes:c.notes,trackingNumber:c.trackingNumber,trackingUrl:c.trackingUrl,previousStatus:a.status}),o(!1))},g=async(_,j)=>{if(!a||!_.target.files||_.target.files.length===0)return;h(!0);const C=_.target.files[0],A=C.name.split(".").pop(),M=`proofs/${a.id}/${j}/${Date.now()}.${A}`;try{const{error:I}=await V.storage.from("marketplace").upload(M,C);if(I)throw I;const{data:{publicUrl:P}}=V.storage.from("marketplace").getPublicUrl(M);await r.mutateAsync({itemId:j,proofUrl:P,orderId:a.id}),ae.success("Proof uploaded successfully")}catch(I){ae.error("Failed to upload proof: "+I.message)}finally{h(!1)}};return t?e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsx(fn,{className:"h-8 w-48"})}),e.jsx(De,{children:e.jsx("div",{className:"space-y-4",children:[1,2,3].map(_=>e.jsx(fn,{className:"h-16 w-full"},_))})})]}):e.jsxs(e.Fragment,{children:[e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsx(Yt,{children:"Orders"})}),e.jsx(De,{children:s&&s.length>0?e.jsxs(Qa,{children:[e.jsx(Ja,{children:e.jsxs(vn,{children:[e.jsx(Dt,{children:"Order #"}),e.jsx(Dt,{children:"Customer"}),e.jsx(Dt,{children:"Date"}),e.jsx(Dt,{children:"Total"}),e.jsx(Dt,{children:"Status"}),e.jsx(Dt,{className:"text-right",children:"Actions"})]})}),e.jsx(ei,{children:s.map(_=>{var j,C;return e.jsxs(vn,{children:[e.jsx(_t,{className:"font-mono",children:_.order_number}),e.jsx(_t,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:((j=_.user)==null?void 0:j.name)||"Unknown"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:(C=_.user)==null?void 0:C.email})]})}),e.jsx(_t,{children:Ys(new Date(_.created_at),"MMM d, yyyy")}),e.jsxs(_t,{className:"font-bold",children:["$",Number(_.total).toFixed(2)]}),e.jsx(_t,{children:e.jsx(qe,{className:xQe[_.status],children:qB[_.status]})}),e.jsx(_t,{className:"text-right",children:e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>m(_),children:[e.jsx(ba,{className:"h-4 w-4 mr-1"}),"View"]})})]},_.id)})})]}):e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"No orders yet."})})]}),e.jsx(zs,{open:l,onOpenChange:o,children:e.jsxs(Rs,{className:"max-w-3xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Vs,{children:e.jsxs($s,{children:["Order ",a==null?void 0:a.order_number]})}),a&&e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium mb-2",children:"Customer"}),e.jsx("p",{children:(x=a.user)==null?void 0:x.name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:(y=a.user)==null?void 0:y.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:(v=a.items)==null?void 0:v.map(_=>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:_.product_name}),_.variant_name&&e.jsx("p",{className:"text-sm text-muted-foreground",children:_.variant_name})]}),e.jsxs("p",{className:"font-bold",children:["$",Number(_.unit_price).toFixed(2)," x ",_.quantity]})]}),_.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:_.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(qe,{variant:_.proof_status==="approved"?"default":"secondary",children:_.proof_status||"No proof yet"})]}),_.proof_url?e.jsx("a",{href:_.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:j=>g(j,_.id),className:"hidden",id:`proof-${_.id}`,disabled:u}),e.jsx("label",{htmlFor:`proof-${_.id}`,children:e.jsx($,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("span",{children:[e.jsx(gi,{className:"h-4 w-4 mr-1"}),u?"Uploading...":"Upload Proof"]})})})]})]})})]},_.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(re,{children:"Status"}),e.jsxs(bs,{value:c.status,onValueChange:_=>d({...c,status:_}),children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsx(vs,{children:N8n.map(_=>e.jsx(We,{value:_,children:qB[_]},_))})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Tracking Number"}),e.jsx(be,{value:c.trackingNumber,onChange:_=>d({...c,trackingNumber:_.target.value}),placeholder:"Enter tracking number"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Tracking URL"}),e.jsx(be,{value:c.trackingUrl,onChange:_=>d({...c,trackingUrl:_.target.value}),placeholder:"https://..."})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Notes (optional)"}),e.jsx(Ls,{value:c.notes,onChange:_=>d({...c,notes:_.target.value}),placeholder:"Add a note about this status change..."})]}),e.jsxs($,{onClick:p,disabled:n.isPending,className:"w-full",children:[e.jsx(bh,{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(_=>e.jsxs("div",{className:"flex justify-between text-sm p-2 bg-muted rounded",children:[e.jsxs("div",{children:[e.jsx(qe,{variant:"outline",children:qB[_.status]}),_.notes&&e.jsx("p",{className:"text-muted-foreground mt-1",children:_.notes})]}),e.jsx("span",{className:"text-muted-foreground",children:Ys(new Date(_.created_at),"MMM d, h:mm a")})]},_.id))})]})]})]})})]})}function S8n(){const[s,t]=k.useState("products"),n=Jn();return e.jsx(Xs,{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($,{variant:"outline",onClick:()=>n("/marketplace"),children:[e.jsx(Ir,{className:"h-4 w-4 mr-2"}),"View Store"]})]}),e.jsxs(ya,{value:s,onValueChange:t,children:[e.jsxs(va,{className:"grid w-full grid-cols-3",children:[e.jsxs(is,{value:"products",className:"flex items-center gap-2",children:[e.jsx(bh,{className:"h-4 w-4"}),"Products"]}),e.jsxs(is,{value:"categories",className:"flex items-center gap-2",children:[e.jsx(d1,{className:"h-4 w-4"}),"Categories"]}),e.jsxs(is,{value:"orders",className:"flex items-center gap-2",children:[e.jsx(ok,{className:"h-4 w-4"}),"Orders"]})]}),e.jsx(cs,{value:"products",children:e.jsx(j8n,{})}),e.jsx(cs,{value:"categories",children:e.jsx(w8n,{})}),e.jsx(cs,{value:"orders",children:e.jsx(k8n,{})})]})]})})}function bVt(){return pt({queryKey:["reward-categories"],queryFn:async()=>{const{data:s,error:t}=await V.from("reward_store_categories").select("*").order("sort_order",{ascending:!0});if(t)throw t;return s}})}function C8n(s){return pt({queryKey:["reward-items",s],queryFn:async()=>{let t=V.from("reward_store_items").select(` *, category:reward_store_categories(*) `).order("created_at",{ascending:!1});const{data:n,error:r}=await t;if(r)throw r;return n}})}function A8n(s){return pt({queryKey:["active-reward-items",s],queryFn:async()=>{let t=V.from("reward_store_items").select(` *, category:reward_store_categories(*) `).eq("is_active",!0).order("created_at",{ascending:!1});s&&(t=t.eq("category_id",s));const{data:n,error:r}=await t;if(r)throw r;return n}})}function E8n(s){return pt({queryKey:["user-purchases",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await V.from("reward_store_purchases").select(` *, item:reward_store_items(*) `).eq("user_id",s).order("purchased_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function T8n(){return pt({queryKey:["all-reward-purchases"],queryFn:async()=>{const{data:s,error:t}=await V.from("reward_store_purchases").select(` *, item:reward_store_items(*) `).order("purchased_at",{ascending:!1});if(t)throw t;if(!s||s.length===0)return[];const n=[...new Set(s.map(l=>l.user_id))],{data:r,error:a}=await V.from("profiles").select("id, name, email").in("id",n);if(a)throw a;const i=new Map((r==null?void 0:r.map(l=>[l.id,l]))||[]);return s.map(l=>({...l,user:i.get(l.user_id)||null}))}})}function M8n(s){return pt({queryKey:["spendable-points",s],queryFn:async()=>{if(!s)return 0;const{data:t,error:n}=await V.from("agent_attendance_stats").select("spendable_points").eq("user_id",s).single();if(n&&n.code!=="PGRST116")throw n;return(t==null?void 0:t.spendable_points)||0},enabled:!!s})}function P8n(){const s=ls();return Nt({mutationFn:async t=>{const{data:n,error:r}=await V.rpc("purchase_reward_item",{p_item_id:t});if(r)throw r;const a=n;if(!a.success)throw new Error(a.error||"Purchase failed");return a},onSuccess:()=>{s.invalidateQueries({queryKey:["user-purchases"]}),s.invalidateQueries({queryKey:["spendable-points"]}),s.invalidateQueries({queryKey:["active-reward-items"]}),s.invalidateQueries({queryKey:["reward-items"]}),s.invalidateQueries({queryKey:["homereel-credits"]})}})}function I8n(){const s=ls();return Nt({mutationFn:async t=>{const{data:n,error:r}=await V.from("reward_store_categories").insert([t]).select().single();if(r)throw r;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["reward-categories"]})}})}function L8n(){const s=ls();return Nt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await V.from("reward_store_categories").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["reward-categories"]})}})}function R8n(){const s=ls();return Nt({mutationFn:async t=>{const{error:n}=await V.from("reward_store_categories").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["reward-categories"]})}})}function D8n(){const s=ls();return Nt({mutationFn:async t=>{const{data:n,error:r}=await V.from("reward_store_items").insert([t]).select().single();if(r)throw r;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["reward-items"]}),s.invalidateQueries({queryKey:["active-reward-items"]})}})}function O8n(){const s=ls();return Nt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await V.from("reward_store_items").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["reward-items"]}),s.invalidateQueries({queryKey:["active-reward-items"]})}})}function F8n(){const s=ls();return Nt({mutationFn:async t=>{const{error:n}=await V.from("reward_store_items").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["reward-items"]}),s.invalidateQueries({queryKey:["active-reward-items"]})}})}function z8n(s){const t=s.match(/\/storage\/v1\/object\/public\/([^/]+)\/(.+)$/);return t?{bucket:t[1],path:t[2]}:null}async function YDe(s,t){const n=z8n(s);if(n)try{const{data:r,error:a}=await V.storage.from(n.bucket).download(n.path);if(a){console.error("Error downloading file:",a),ae.error("Failed to download file");return}const i=URL.createObjectURL(r),l=document.createElement("a");l.href=i,l.download=t||n.path.split("/").pop()||"download",document.body.appendChild(l),l.click(),document.body.removeChild(l),setTimeout(()=>URL.revokeObjectURL(i),100)}catch(r){console.error("Download error:",r),ae.error("Failed to download file")}else try{const a=await(await fetch(s)).blob(),i=URL.createObjectURL(a),l=document.createElement("a");l.href=i,l.download=t||s.split("/").pop()||"download",document.body.appendChild(l),l.click(),document.body.removeChild(l),setTimeout(()=>URL.revokeObjectURL(i),100)}catch(r){console.error("External download error:",r),ae.error("Failed to download file")}}function _Vt(){return pt({queryKey:["point-reward-settings"],queryFn:async()=>{const{data:s,error:t}=await V.from("point_reward_settings").select("*").order("action_name");if(t)throw t;return s}})}function B8n(){const s=ls();return Nt({mutationFn:async({id:t,points:n,is_active:r})=>{const a={points:n};r!==void 0&&(a.is_active=r);const{data:i,error:l}=await V.from("point_reward_settings").update(a).eq("id",t).select().single();if(l)throw l;return i},onSuccess:()=>{s.invalidateQueries({queryKey:["point-reward-settings"]})}})}function $8n(){const{user:s}=ks(),[t,n]=k.useState("items"),[r,a]=k.useState(!1),[i,l]=k.useState(null),[o,c]=k.useState(""),[d,u]=k.useState(""),[h,m]=k.useState(""),[p,g]=k.useState(null),[x,y]=k.useState(!1),[v,_]=k.useState(null),[j,C]=k.useState(""),[A,M]=k.useState(""),[I,P]=k.useState(null),[R,O]=k.useState(""),[B,U]=k.useState("file"),[G,H]=k.useState(""),[Y,se]=k.useState(""),[ee,oe]=k.useState(""),[me,Q]=k.useState(!0),[te,le]=k.useState(null),[fe,_e]=k.useState(!1),[ve,he]=k.useState(!1),Se=k.useRef(null),Te=k.useRef(null),{data:Ie,isLoading:Ue}=bVt(),{data:Be,isLoading:je}=C8n(),{data:Ye,isLoading:Ee}=T8n(),{data:Re,isLoading:ke}=_Vt(),Fe=I8n(),Oe=L8n(),Ge=R8n(),yt=D8n(),tt=O8n(),ut=F8n(),nt=B8n(),[et,at]=k.useState({}),wt=gt=>{gt?(l(gt),c(gt.name),u(gt.description||""),m(gt.icon||"")):(l(null),c(""),u(""),m("")),a(!0)},rt=async()=>{if(!o.trim()){ae.error("Please enter a category name");return}try{i?(await Oe.mutateAsync({id:i.id,name:o,description:d||null,icon:h||null}),ae.success("Category updated successfully")):(await Fe.mutateAsync({name:o,description:d||null,icon:h||null,sort_order:((Ie==null?void 0:Ie.length)||0)+1}),ae.success("Category created successfully")),a(!1)}catch(gt){console.error("Error saving category:",gt),ae.error("Failed to save category")}},Ft=async()=>{if(p)try{await Ge.mutateAsync(p),ae.success("Category deleted successfully"),g(null)}catch(gt){console.error("Error deleting category:",gt),ae.error("Failed to delete category")}},Ut=gt=>{var rs;gt?(_(gt),C(gt.name),M(gt.description||""),P(gt.category_id),O(gt.points_cost.toString()),U(gt.item_type),H(gt.file_url||""),se(gt.preview_image_url||""),oe(((rs=gt.max_quantity)==null?void 0:rs.toString())||""),Q(gt.is_active)):(_(null),C(""),M(""),P(null),O(""),U("file"),H(""),se(""),oe(""),Q(!0)),y(!0)},Is=async(gt,rs)=>{rs==="file"?_e(!0):he(!0);try{const Ns=gt.name.split(".").pop(),us=`${Date.now()}-${Math.random().toString(36).substring(7)}.${Ns}`,Bs=`${rs==="file"?"items":"previews"}/${us}`,{error:Ts}=await V.storage.from("reward-store").upload(Bs,gt);if(Ts)throw Ts;const{data:{publicUrl:Fn}}=V.storage.from("reward-store").getPublicUrl(Bs);rs==="file"?H(Fn):se(Fn),ae.success("File uploaded successfully")}catch(Ns){console.error("Error uploading file:",Ns),ae.error("Failed to upload file")}finally{rs==="file"?_e(!1):he(!1)}},xs=async()=>{if(!j.trim()){ae.error("Please enter an item name");return}if(!R||parseInt(R)<0){ae.error("Please enter a valid points cost");return}try{const gt={name:j,description:A||null,category_id:I,points_cost:parseInt(R),item_type:B,file_url:G||null,preview_image_url:Y||null,max_quantity:ee?parseInt(ee):null,current_quantity:ee?parseInt(ee):null,is_active:me,created_by:s==null?void 0:s.id};v?(await tt.mutateAsync({id:v.id,...gt,current_quantity:v.max_quantity!==(ee?parseInt(ee):null)?ee?parseInt(ee):null:v.current_quantity}),ae.success("Item updated successfully")):(await yt.mutateAsync(gt),ae.success("Item created successfully")),y(!1)}catch(gt){console.error("Error saving item:",gt),ae.error("Failed to save item")}},st=async()=>{if(te)try{await ut.mutateAsync(te),ae.success("Item deleted successfully"),le(null)}catch(gt){console.error("Error deleting item:",gt),ae.error("Failed to delete item")}},dt=async(gt,rs)=>{const Ns=et[gt];if(Ns===void 0||Ns===rs.toString())return;const us=parseInt(Ns);if(isNaN(us)||us<0){ae.error("Please enter a valid positive number");return}try{await nt.mutateAsync({id:gt,points:us}),ae.success("Points updated successfully"),at(Bs=>{const Ts={...Bs};return delete Ts[gt],Ts})}catch(Bs){console.error("Error updating points:",Bs),ae.error("Failed to update points")}};return Ue||je||Ee||ke?e.jsx(Xs,{title:"Reward Store",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(fn,{className:"h-8 w-64"}),e.jsx(fn,{className:"h-96"})]})}):e.jsxs(Xs,{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(we,{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(bh,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Total Items"})]}),e.jsx("p",{className:"text-2xl font-bold",children:(Be==null?void 0:Be.length)||0}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[(Be==null?void 0:Be.filter(gt=>gt.is_active).length)||0," active"]})]})}),e.jsx(we,{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(d1,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Categories"})]}),e.jsx("p",{className:"text-2xl font-bold",children:(Ie==null?void 0:Ie.length)||0})]})}),e.jsx(we,{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(ri,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Avg. Cost"})]}),e.jsxs("p",{className:"text-2xl font-bold",children:[Be&&Be.length>0?Math.round(Be.reduce((gt,rs)=>gt+rs.points_cost,0)/Be.length):0," pts"]})]})})]}),e.jsxs(ya,{value:t,onValueChange:n,children:[e.jsxs(va,{children:[e.jsx(is,{value:"items",children:"Items"}),e.jsx(is,{value:"categories",children:"Categories"}),e.jsx(is,{value:"purchases",children:"Purchases"}),e.jsx(is,{value:"point-settings",children:"Point Settings"})]}),e.jsx(cs,{value:"items",className:"mt-4",children:e.jsxs(we,{children:[e.jsxs(Vt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Yt,{children:"Store Items"}),e.jsx(vr,{children:"Manage rewards that agents can purchase"})]}),e.jsxs($,{onClick:()=>Ut(),children:[e.jsx(nn,{className:"h-4 w-4 mr-2"}),"Add Item"]})]}),e.jsx(De,{children:!Be||Be.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Zo,{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(Qa,{children:[e.jsx(Ja,{children:e.jsxs(vn,{children:[e.jsx(Dt,{children:"Item"}),e.jsx(Dt,{children:"Category"}),e.jsx(Dt,{className:"text-center",children:"Cost"}),e.jsx(Dt,{className:"text-center",children:"Type"}),e.jsx(Dt,{className:"text-center",children:"Quantity"}),e.jsx(Dt,{className:"text-center",children:"Status"}),e.jsx(Dt,{className:"text-right",children:"Actions"})]})}),e.jsx(ei,{children:Be.map(gt=>e.jsxs(vn,{children:[e.jsx(_t,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[gt.preview_image_url?e.jsx("img",{src:gt.preview_image_url,alt:gt.name,className:"h-10 w-10 rounded object-cover"}):e.jsx("div",{className:"h-10 w-10 rounded bg-muted flex items-center justify-center",children:e.jsx(Zo,{className:"h-5 w-5 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:gt.name}),e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-1",children:gt.description||"No description"})]})]})}),e.jsx(_t,{children:gt.category?e.jsx(qe,{variant:"outline",children:gt.category.name}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx(_t,{className:"text-center",children:e.jsxs(qe,{variant:"secondary",className:"font-bold",children:[e.jsx(ri,{className:"h-3 w-3 mr-1"}),gt.points_cost]})}),e.jsx(_t,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[gt.item_type==="file"?e.jsx(ea,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(od,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"text-xs capitalize",children:gt.item_type})]})}),e.jsx(_t,{className:"text-center",children:gt.max_quantity!==null?e.jsxs("span",{className:gt.current_quantity===0?"text-red-500":"",children:[gt.current_quantity,"/",gt.max_quantity]}):e.jsx("span",{className:"text-muted-foreground",children:"Unlimited"})}),e.jsx(_t,{className:"text-center",children:e.jsx(qe,{variant:gt.is_active?"default":"secondary",children:gt.is_active?"Active":"Inactive"})}),e.jsx(_t,{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-1",children:[e.jsx($,{variant:"ghost",size:"sm",onClick:()=>Ut(gt),children:e.jsx(ui,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>le(gt.id),children:e.jsx(Un,{className:"h-4 w-4 text-destructive"})})]})})]},gt.id))})]})})]})}),e.jsx(cs,{value:"categories",className:"mt-4",children:e.jsxs(we,{children:[e.jsxs(Vt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Yt,{children:"Categories"}),e.jsx(vr,{children:"Organize your store items into categories"})]}),e.jsxs($,{onClick:()=>wt(),children:[e.jsx(nn,{className:"h-4 w-4 mr-2"}),"Add Category"]})]}),e.jsx(De,{children:!Ie||Ie.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(d1,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No categories yet. Add your first category!"})]}):e.jsxs(Qa,{children:[e.jsx(Ja,{children:e.jsxs(vn,{children:[e.jsx(Dt,{children:"Name"}),e.jsx(Dt,{children:"Description"}),e.jsx(Dt,{className:"text-center",children:"Items"}),e.jsx(Dt,{className:"text-right",children:"Actions"})]})}),e.jsx(ei,{children:Ie.map(gt=>e.jsxs(vn,{children:[e.jsxs(_t,{className:"font-medium",children:[gt.icon&&e.jsx("span",{className:"mr-2",children:gt.icon}),gt.name]}),e.jsx(_t,{className:"text-muted-foreground",children:gt.description||"—"}),e.jsx(_t,{className:"text-center",children:(Be==null?void 0:Be.filter(rs=>rs.category_id===gt.id).length)||0}),e.jsx(_t,{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-1",children:[e.jsx($,{variant:"ghost",size:"sm",onClick:()=>wt(gt),children:e.jsx(ui,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>g(gt.id),children:e.jsx(Un,{className:"h-4 w-4 text-destructive"})})]})})]},gt.id))})]})})]})}),e.jsx(cs,{value:"purchases",className:"mt-4",children:e.jsxs(we,{children:[e.jsxs(Vt,{children:[e.jsxs(Yt,{className:"flex items-center gap-2",children:[e.jsx(ok,{className:"h-5 w-5"}),"Purchase History"]}),e.jsx(vr,{children:"View all reward redemptions by agents"})]}),e.jsx(De,{children:!Ye||Ye.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(ok,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No purchases yet."})]}):e.jsxs(Qa,{children:[e.jsx(Ja,{children:e.jsxs(vn,{children:[e.jsx(Dt,{children:"Date"}),e.jsx(Dt,{children:"Agent"}),e.jsx(Dt,{children:"Item"}),e.jsx(Dt,{className:"text-center",children:"Points Spent"})]})}),e.jsx(ei,{children:Ye.map(gt=>{var rs,Ns,us,Bs;return e.jsxs(vn,{children:[e.jsx(_t,{className:"text-muted-foreground",children:Ys(new Date(gt.purchased_at),"MMM d, yyyy 'at' h:mm a")}),e.jsx(_t,{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(el,{className:"h-4 w-4 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:((rs=gt.user)==null?void 0:rs.name)||"Unknown"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:((Ns=gt.user)==null?void 0:Ns.email)||"—"})]})]})}),e.jsx(_t,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[(us=gt.item)!=null&&us.preview_image_url?e.jsx("img",{src:gt.item.preview_image_url,alt:gt.item.name,className:"h-8 w-8 rounded object-cover"}):e.jsx("div",{className:"h-8 w-8 rounded bg-muted flex items-center justify-center",children:e.jsx(Zo,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx("span",{children:((Bs=gt.item)==null?void 0:Bs.name)||"Deleted item"})]})}),e.jsx(_t,{className:"text-center",children:e.jsxs(qe,{variant:"secondary",className:"font-bold",children:[e.jsx(ri,{className:"h-3 w-3 mr-1"}),gt.points_spent]})})]},gt.id)})})]})})]})})]})]}),e.jsx(zs,{open:r,onOpenChange:a,children:e.jsxs(Rs,{children:[e.jsxs(Vs,{children:[e.jsx($s,{children:i?"Edit Category":"Add Category"}),e.jsx(Cr,{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(re,{htmlFor:"categoryName",children:"Name"}),e.jsx(be,{id:"categoryName",value:o,onChange:gt=>c(gt.target.value),placeholder:"e.g., Templates, Resources"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"categoryDescription",children:"Description"}),e.jsx(Ls,{id:"categoryDescription",value:d,onChange:gt=>u(gt.target.value),placeholder:"Optional description..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"categoryIcon",children:"Icon (emoji)"}),e.jsx(be,{id:"categoryIcon",value:h,onChange:gt=>m(gt.target.value),placeholder:"e.g., 📄, 🎁"})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx($,{onClick:rt,disabled:Fe.isPending||Oe.isPending,children:Fe.isPending||Oe.isPending?"Saving...":"Save"})]})]})}),e.jsx(zs,{open:x,onOpenChange:y,children:e.jsxs(Rs,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsxs(Vs,{children:[e.jsx($s,{children:v?"Edit Item":"Add Item"}),e.jsx(Cr,{children:v?"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(re,{htmlFor:"itemName",children:"Name *"}),e.jsx(be,{id:"itemName",value:j,onChange:gt=>C(gt.target.value),placeholder:"e.g., Premium Template Pack"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"itemDescription",children:"Description"}),e.jsx(Ls,{id:"itemDescription",value:A,onChange:gt=>M(gt.target.value),placeholder:"Describe the item..."})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"itemCategory",children:"Category"}),e.jsxs(bs,{value:I||"none",onValueChange:gt=>P(gt==="none"?null:gt),children:[e.jsx(ys,{children:e.jsx(_s,{placeholder:"Select category"})}),e.jsxs(vs,{children:[e.jsx(We,{value:"none",children:"No category"}),Ie==null?void 0:Ie.map(gt=>e.jsxs(We,{value:gt.id,children:[gt.icon&&`${gt.icon} `,gt.name]},gt.id))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"itemPointsCost",children:"Points Cost *"}),e.jsx(be,{id:"itemPointsCost",type:"number",min:"0",value:R,onChange:gt=>O(gt.target.value),placeholder:"e.g., 100"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"itemType",children:"Type"}),e.jsxs(bs,{value:B,onValueChange:U,children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"file",children:"File Download"}),e.jsx(We,{value:"link",children:"External Link"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"itemMaxQuantity",children:"Max Quantity"}),e.jsx(be,{id:"itemMaxQuantity",type:"number",min:"1",value:ee,onChange:gt=>oe(gt.target.value),placeholder:"Leave empty for unlimited"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"File / Link URL"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(be,{value:G,onChange:gt=>H(gt.target.value),placeholder:B==="file"?"Upload a file or paste URL":"Paste external link"}),B==="file"&&e.jsxs(e.Fragment,{children:[e.jsx($,{type:"button",variant:"outline",size:"icon",onClick:()=>{var gt;return(gt=Se.current)==null?void 0:gt.click()},disabled:fe,children:e.jsx(gi,{className:"h-4 w-4"})}),e.jsx("input",{ref:Se,type:"file",className:"hidden",onChange:gt=>{var Ns;const rs=(Ns=gt.target.files)==null?void 0:Ns[0];rs&&Is(rs,"file")}})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Preview Image"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(be,{value:Y,onChange:gt=>se(gt.target.value),placeholder:"Upload an image or paste URL"}),e.jsx($,{type:"button",variant:"outline",size:"icon",onClick:()=>{var gt;return(gt=Te.current)==null?void 0:gt.click()},disabled:ve,children:e.jsx(zc,{className:"h-4 w-4"})}),e.jsx("input",{ref:Te,type:"file",accept:"image/*",className:"hidden",onChange:gt=>{var Ns;const rs=(Ns=gt.target.files)==null?void 0:Ns[0];rs&&Is(rs,"preview")}})]}),Y&&e.jsx("img",{src:Y,alt:"Preview",className:"mt-2 h-24 rounded object-cover"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(On,{id:"itemIsActive",checked:me,onCheckedChange:Q}),e.jsx(re,{htmlFor:"itemIsActive",children:"Active (visible to agents)"})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>y(!1),children:"Cancel"}),e.jsx($,{onClick:xs,disabled:yt.isPending||tt.isPending,children:yt.isPending||tt.isPending?"Saving...":"Save"})]})]})}),e.jsx(oc,{open:!!p,onOpenChange:()=>g(null),children:e.jsxs(Ql,{children:[e.jsxs(Jl,{children:[e.jsx(tc,{children:"Delete Category"}),e.jsx(sc,{children:"Are you sure you want to delete this category? Items in this category will become uncategorized."})]}),e.jsxs(ec,{children:[e.jsx(nc,{children:"Cancel"}),e.jsx(Vl,{onClick:Ft,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete"})]})]})}),e.jsx(oc,{open:!!te,onOpenChange:()=>le(null),children:e.jsxs(Ql,{children:[e.jsxs(Jl,{children:[e.jsx(tc,{children:"Delete Item"}),e.jsx(sc,{children:"Are you sure you want to delete this item? This action cannot be undone."})]}),e.jsxs(ec,{children:[e.jsx(nc,{children:"Cancel"}),e.jsx(Vl,{onClick:st,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete"})]})]})}),t==="point-settings"&&e.jsxs(we,{className:"mt-4",children:[e.jsx(Vt,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Yc,{className:"h-5 w-5"}),e.jsxs("div",{children:[e.jsx(Yt,{children:"Point Reward Settings"}),e.jsx(vr,{children:"Configure how many points agents earn for various actions. Adjust these values to run double-points promotions."})]})]})}),e.jsx(De,{children:!Re||Re.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Yc,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No point settings configured."})]}):e.jsxs(Qa,{children:[e.jsx(Ja,{children:e.jsxs(vn,{children:[e.jsx(Dt,{children:"Action"}),e.jsx(Dt,{children:"Description"}),e.jsx(Dt,{className:"text-center w-32",children:"Points"}),e.jsx(Dt,{className:"text-right w-24",children:"Save"})]})}),e.jsx(ei,{children:Re.map(gt=>e.jsxs(vn,{children:[e.jsx(_t,{children:e.jsx("p",{className:"font-medium",children:gt.action_name})}),e.jsx(_t,{children:e.jsx("p",{className:"text-sm text-muted-foreground",children:gt.description})}),e.jsx(_t,{className:"text-center",children:e.jsx(be,{type:"number",min:"0",className:"w-20 mx-auto text-center",value:et[gt.id]??gt.points.toString(),onChange:rs=>at(Ns=>({...Ns,[gt.id]:rs.target.value}))})}),e.jsx(_t,{className:"text-right",children:e.jsx($,{size:"sm",variant:"outline",disabled:et[gt.id]===void 0||et[gt.id]===gt.points.toString()||nt.isPending,onClick:()=>dt(gt.id,gt.points),children:e.jsx(Ml,{className:"h-4 w-4"})})})]},gt.id))})]})})]})]})}const hbt=()=>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"})]}),mbt=[{value:"template",label:"Templates"},{value:"brand",label:"Brand Assets"},{value:"listing",label:"Listing Assets"},{value:"social",label:"Social Media"},{value:"general",label:"General"}];function U8n(){const s=ls(),[t,n]=k.useState(!1),[r,a]=k.useState(!1),[i,l]=k.useState(!1),[o,c]=k.useState({brokerage_id:"",folder_id:"",folder_name:"",folder_type:"template",description:""}),{data:d,isLoading:u}=pt({queryKey:["canva-integration"],queryFn:async()=>{const{data:_,error:j}=await V.from("canva_integration").select("*").eq("is_active",!0).maybeSingle();if(j)throw j;return _}}),{data:h}=pt({queryKey:["brokerages-list"],queryFn:async()=>{const{data:_,error:j}=await V.from("brokerages").select("id, name").order("name");if(j)throw j;return _}}),{data:m}=pt({queryKey:["canva-brokerage-folders"],queryFn:async()=>{const{data:_,error:j}=await V.from("canva_brokerage_folders").select("*, brokerages(name)").order("sort_order");if(j)throw j;return _}}),p=async()=>{var _;n(!0);try{const{data:j}=await V.auth.getSession(),C=(_=j==null?void 0:j.session)==null?void 0:_.access_token;if(!C)throw new Error("Not authenticated");const I=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/canva-oauth",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${C}`,apikey:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InJlbHplamlzd25vdGlramd2amh6Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjE5NTAzNDQsImV4cCI6MjA3NzUyNjM0NH0.dzIkIr_oFSbFE3oWS0ktIr83iKHHkZxt40Gc7SpC_mM"},body:JSON.stringify({action:"get_auth_url"})}),P=await I.json();if(!I.ok||P!=null&&P.error)throw new Error((P==null?void 0:P.error)||"Failed to get authorization URL");if(P!=null&&P.authUrl){localStorage.setItem("canva_code_verifier",P.codeVerifier),localStorage.setItem("canva_oauth_state",P.state);const R=window.open(P.authUrl,"canva-oauth","width=600,height=700,scrollbars=yes,resizable=yes");if(!R){ae.error("Popup was blocked. Please allow popups for this site and try again."),n(!1);return}const O=U=>{var G,H;U.origin===window.location.origin&&(((G=U.data)==null?void 0:G.type)==="canva-oauth-success"?(window.removeEventListener("message",O),ae.success("Canva connected successfully!"),s.invalidateQueries({queryKey:["canva-integration"]}),n(!1)):((H=U.data)==null?void 0:H.type)==="canva-oauth-error"&&(window.removeEventListener("message",O),ae.error("Canva connection failed: "+(U.data.error||"Unknown error")),n(!1)))};window.addEventListener("message",O);const B=setInterval(()=>{R.closed&&(clearInterval(B),window.removeEventListener("message",O),s.invalidateQueries({queryKey:["canva-integration"]}),n(!1))},500)}else throw new Error("Failed to get authorization URL")}catch(j){console.error("Canva connect error:",j);const C=(j==null?void 0:j.message)||"";C.includes("CANVA_CLIENT_ID")?ae.error("Canva app credentials not configured yet."):ae.error(C||"Failed to start Canva connection"),n(!1)}},g=Nt({mutationFn:async _=>{var R;const{data:j}=await V.auth.getSession(),C=(R=j==null?void 0:j.session)==null?void 0:R.access_token;if(!C)throw new Error("Not authenticated");const I=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/canva-oauth",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${C}`,apikey:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InJlbHplamlzd25vdGlramd2amh6Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjE5NTAzNDQsImV4cCI6MjA3NzUyNjM0NH0.dzIkIr_oFSbFE3oWS0ktIr83iKHHkZxt40Gc7SpC_mM"},body:JSON.stringify({action:"disconnect",integrationId:_})}),P=await I.json();if(!I.ok||P!=null&&P.error)throw new Error((P==null?void 0:P.error)||"Failed to disconnect")},onSuccess:()=>{s.invalidateQueries({queryKey:["canva-integration"]}),ae.success("Canva disconnected")},onError:_=>{ae.error(_.message||"Failed to disconnect Canva")}}),x=Nt({mutationFn:async _=>{const{error:j}=await V.from("canva_brokerage_folders").insert({brokerage_id:_.brokerage_id,folder_id:_.folder_id.trim(),folder_name:_.folder_name.trim(),folder_type:_.folder_type,description:_.description.trim()||null,sort_order:(m==null?void 0:m.length)||0});if(j)throw j},onSuccess:()=>{s.invalidateQueries({queryKey:["canva-brokerage-folders"]}),ae.success("Folder added"),l(!1),c({brokerage_id:"",folder_id:"",folder_name:"",folder_type:"template",description:""})},onError:()=>ae.error("Failed to add folder")}),y=Nt({mutationFn:async _=>{const{error:j}=await V.from("canva_brokerage_folders").delete().eq("id",_);if(j)throw j},onSuccess:()=>{s.invalidateQueries({queryKey:["canva-brokerage-folders"]}),ae.success("Folder removed")},onError:()=>ae.error("Failed to remove folder")}),v=!!d;return e.jsxs(e.Fragment,{children:[e.jsxs(we,{children:[e.jsx(Vt,{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(hbt,{})}),e.jsxs("div",{children:[e.jsxs(Yt,{className:"text-lg flex items-center gap-2",children:["Canva Connect",v&&e.jsx(qe,{variant:"default",className:"text-xs",children:"Connected"}),e.jsx(qe,{variant:"outline",className:"text-xs",children:"Admin Only"})]}),e.jsx(vr,{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(nl,{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(nl,{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(nl,{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"})]}),v?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(oc,{children:[e.jsx(_g,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(Un,{className:"h-4 w-4"})})}),e.jsxs(Ql,{children:[e.jsxs(Jl,{children:[e.jsx(tc,{children:"Disconnect Canva?"}),e.jsx(sc,{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(ec,{children:[e.jsx(nc,{children:"Cancel"}),e.jsx(Vl,{onClick:()=>g.mutate(d.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]}),e.jsxs("div",{className:"border rounded-lg overflow-hidden",children:[e.jsxs("button",{onClick:()=>a(!r),className:"w-full flex items-center justify-between p-3 text-sm font-medium hover:bg-muted transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(d1,{className:"h-4 w-4 text-primary"}),"Brokerage Folder Mappings",m&&m.length>0&&e.jsx(qe,{variant:"secondary",className:"text-xs",children:m.length})]}),r?e.jsx(Ny,{className:"h-4 w-4"}):e.jsx(Go,{className:"h-4 w-4"})]}),r&&e.jsxs("div",{className:"border-t p-3 space-y-2",children:[m&&m.length>0?m.map(_=>{var j,C;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:_.folder_name}),e.jsx(qe,{variant:"outline",className:"text-xs shrink-0",children:((j=mbt.find(A=>A.value===_.folder_type))==null?void 0:j.label)||_.folder_type})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[(C=_.brokerages)==null?void 0:C.name," · ID: ",e.jsx("span",{className:"font-mono",children:_.folder_id})]})]}),e.jsx($,{variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground hover:text-destructive shrink-0 ml-2",onClick:()=>y.mutate(_.id),children:e.jsx(mr,{className:"h-3.5 w-3.5"})})]},_.id)}):e.jsx("p",{className:"text-sm text-muted-foreground text-center py-2",children:"No folders mapped yet"}),e.jsxs($,{variant:"outline",size:"sm",className:"w-full gap-1.5 mt-1",onClick:()=>l(!0),children:[e.jsx(nn,{className:"h-3.5 w-3.5"}),"Add Folder Mapping"]})]})]})]}):e.jsxs($,{className:"mt-4",onClick:p,disabled:t||u,children:[t?e.jsx(yo,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx("div",{className:"mr-2",children:e.jsx(hbt,{})}),"Connect Canva",e.jsx(xi,{className:"h-4 w-4 ml-2"})]})]})})]}),e.jsx(zs,{open:i,onOpenChange:l,children:e.jsxs(Rs,{children:[e.jsx(Vs,{children:e.jsx($s,{children:"Add Brokerage Folder Mapping"})}),e.jsxs("div",{className:"space-y-4 py-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Brokerage"}),e.jsxs(bs,{value:o.brokerage_id,onValueChange:_=>c(j=>({...j,brokerage_id:_})),children:[e.jsx(ys,{children:e.jsx(_s,{placeholder:"Select a brokerage…"})}),e.jsx(vs,{children:h==null?void 0:h.map(_=>e.jsx(We,{value:_.id,children:_.name},_.id))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Canva Folder ID"}),e.jsx(be,{placeholder:"e.g. FABCdef123456",value:o.folder_id,onChange:_=>c(j=>({...j,folder_id:_.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(re,{children:"Folder Display Name"}),e.jsx(be,{placeholder:"e.g. Brand Templates 2024",value:o.folder_name,onChange:_=>c(j=>({...j,folder_name:_.target.value}))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Folder Type"}),e.jsxs(bs,{value:o.folder_type,onValueChange:_=>c(j=>({...j,folder_type:_})),children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsx(vs,{children:mbt.map(_=>e.jsx(We,{value:_.value,children:_.label},_.value))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(re,{children:["Description ",e.jsx("span",{className:"text-muted-foreground",children:"(optional)"})]}),e.jsx(be,{placeholder:"What's in this folder?",value:o.description,onChange:_=>c(j=>({...j,description:_.target.value}))})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsxs($,{onClick:()=>x.mutate(o),disabled:!o.brokerage_id||!o.folder_id||!o.folder_name||x.isPending,children:[x.isPending?e.jsx(yo,{className:"h-4 w-4 mr-2 animate-spin"}):null,"Add Folder"]})]})]})})]})}function q8n(){const s=Jn();return e.jsx(Xs,{children:e.jsxs("div",{className:"space-y-6 p-4 md:p-8",children:[e.jsx(nm,{title:"Integrations",description:"Manage platform-level service connections"}),e.jsxs(we,{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(ou,{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($,{onClick:()=>s("/admin/social-connections"),children:["View ",e.jsx(xi,{className:"h-4 w-4 ml-1"})]})]}),e.jsx(U8n,{}),e.jsx(pVt,{})]})})}const fbt=s=>{const t="h-4 w-4";return s==="facebook"?e.jsx(ax,{className:t}):s==="instagram"?e.jsx(Sf,{className:t}):s==="linkedin"?e.jsx(dv,{className:t}):s==="google"?e.jsx(pn,{className:t}):null},V8n=s=>s?new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",year:"numeric",month:"short",day:"numeric"}).format(new Date(s)):"—";function H8n(){const[s,t]=k.useState([]),[n,r]=k.useState(!0),[a,i]=k.useState(""),[l,o]=k.useState("all");k.useEffect(()=>{(async()=>{r(!0);const{data:m,error:p}=await V.rpc("admin_get_social_connections");if(p){ae.error(p.message),r(!1);return}t(m||[]),r(!1)})()},[]);const c=k.useMemo(()=>{const m=a.trim().toLowerCase();return s.filter(p=>l!=="all"&&p.platform!==l?!1:m?(p.user_name||"").toLowerCase().includes(m)||(p.user_email||"").toLowerCase().includes(m)||(p.page_name||"").toLowerCase().includes(m)||(p.platform_username||"").toLowerCase().includes(m):!0)},[s,a,l]),d=k.useMemo(()=>{const m=new Map;return s.forEach(p=>{const g=m.get(p.user_id)||{name:p.user_name,email:p.user_email,platforms:new Set,count:0};g.platforms.add(p.platform),g.count+=1,m.set(p.user_id,g)}),Array.from(m.entries()).map(([p,g])=>({user_id:p,...g}))},[s]),u=k.useMemo(()=>{const m=new Map;return s.forEach(p=>m.set(p.platform,(m.get(p.platform)||0)+1)),{uniqueUsers:d.length,totalConnections:s.length,byPlatform:Array.from(m.entries())}},[s,d]),h=m=>m&&new Date(m).getTime()e.jsxs(we,{className:"p-4",children:[e.jsxs("div",{className:"text-sm text-muted-foreground capitalize flex items-center gap-2",children:[fbt(m)," ",m]}),e.jsx("div",{className:"text-2xl font-bold",children:p})]},m))]}),e.jsxs("div",{className:"flex flex-col md:flex-row gap-3",children:[e.jsx(be,{placeholder:"Search by user, email, page, or handle…",value:a,onChange:m=>i(m.target.value),className:"md:max-w-md"}),e.jsxs(bs,{value:l,onValueChange:o,children:[e.jsx(ys,{className:"md:w-48",children:e.jsx(_s,{placeholder:"All platforms"})}),e.jsxs(vs,{children:[e.jsx(We,{value:"all",children:"All platforms"}),e.jsx(We,{value:"facebook",children:"Facebook"}),e.jsx(We,{value:"instagram",children:"Instagram"}),e.jsx(We,{value:"linkedin",children:"LinkedIn"}),e.jsx(We,{value:"google",children:"Google"})]})]})]}),e.jsx(we,{children:n?e.jsx("div",{className:"flex items-center justify-center p-12",children:e.jsx(Jt,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):e.jsxs(Qa,{children:[e.jsx(Ja,{children:e.jsxs(vn,{children:[e.jsx(Dt,{children:"User"}),e.jsx(Dt,{children:"Platform"}),e.jsx(Dt,{children:"Page / Account"}),e.jsx(Dt,{children:"Status"}),e.jsx(Dt,{children:"Connected"})]})}),e.jsx(ei,{children:c.length===0?e.jsx(vn,{children:e.jsx(_t,{colSpan:5,className:"text-center text-muted-foreground py-8",children:"No connections found."})}):c.map(m=>{const p=h(m.token_expires_at);return e.jsxs(vn,{children:[e.jsxs(_t,{children:[e.jsx("div",{className:"font-medium",children:m.user_name||"—"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:m.user_email})]}),e.jsx(_t,{children:e.jsxs("div",{className:"flex items-center gap-2 capitalize",children:[fbt(m.platform)," ",m.platform]})}),e.jsxs(_t,{children:[e.jsx("div",{className:"font-medium",children:m.page_name||m.platform_username||"—"}),m.instagram_business_id&&e.jsxs("div",{className:"text-xs text-muted-foreground",children:["IG Business: ",m.instagram_business_id]})]}),e.jsx(_t,{children:m.is_active?p?e.jsxs(qe,{variant:"destructive",className:"gap-1",children:[e.jsx(Ho,{className:"h-3 w-3"})," Expired"]}):e.jsx(qe,{children:"Active"}):e.jsx(qe,{variant:"secondary",children:"Inactive"})}),e.jsx(_t,{className:"text-sm text-muted-foreground",children:V8n(m.created_at)})]},m.id)})})]})})]})})}const G8n={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 GG(s,t=18,n=10){return s.length<=t+n+3?s:`${s.slice(0,t)}…${s.slice(-n)}`}function W8n(){var B,U,G,H,Y;const s=ls(),[t,n]=k.useState("Test Push"),[r,a]=k.useState("Testing web push notification"),[i,l]=k.useState("/community"),[o,c]=k.useState(!1),[d,u]=k.useState(!1),[h,m]=k.useState({isSupported:typeof window<"u"&&"serviceWorker"in navigator&&"PushManager"in window}),[p,g]=k.useState(null),[x,y]=k.useState(null),{data:v,isLoading:_}=pt({queryKey:["push-notification-settings"],queryFn:async()=>{const{data:se,error:ee}=await V.from("push_notification_settings").select("*").order("setting_key");if(ee)throw ee;return se}}),{data:j,isLoading:C}=pt({queryKey:["push-subscription-stats"],queryFn:async()=>{const{count:se,error:ee}=await V.from("push_subscriptions").select("*",{count:"exact",head:!0});if(ee)throw ee;return{totalSubscriptions:se||0}}}),A=Nt({mutationFn:async({settingKey:se,isEnabled:ee})=>{const{error:oe}=await V.from("push_notification_settings").update({is_enabled:ee}).eq("setting_key",se);if(oe)throw oe},onSuccess:()=>{s.invalidateQueries({queryKey:["push-notification-settings"]}),ae.success("Notification setting updated")},onError:se=>{ae.error("Failed to update setting: "+se.message)}}),M=k.useMemo(()=>{var se,ee;return h.isSupported?`perm=${h.permission??"unknown"} · controller=${h.controllerPresent?"yes":"no"} · sw=${((se=h.serviceWorker)==null?void 0:se.activeState)??"unknown"} · sub=${(ee=h.subscription)!=null&&ee.endpoint?"yes":"no"}`:"Push not supported in this browser."},[h]);k.useEffect(()=>{let se=!0;const ee=async()=>{var te,le,fe,_e,ve,he,Se;const me="serviceWorker"in navigator&&"PushManager"in window,Q={isSupported:me,permission:typeof Notification<"u"?Notification.permission:void 0,controllerPresent:!!((te=navigator.serviceWorker)!=null&&te.controller)};if(!me){se&&m(Q);return}try{const{data:Te,error:Ie}=await V.functions.invoke("get-vapid-public-key",{body:{}});if(Ie)throw Ie;Q.vapidPublicKey=Te==null?void 0:Te.vapidPublicKey;const Be=(await navigator.serviceWorker.getRegistrations()).find(je=>{var Ee,Re,ke;return(((Ee=je.active)==null?void 0:Ee.scriptURL)||((Re=je.waiting)==null?void 0:Re.scriptURL)||((ke=je.installing)==null?void 0:ke.scriptURL)||"").includes("/sw.js")});if(Be){Q.pushWorkerScriptUrl=((le=Be.active)==null?void 0:le.scriptURL)||((fe=Be.waiting)==null?void 0:fe.scriptURL)||((_e=Be.installing)==null?void 0:_e.scriptURL),Q.serviceWorker={scope:Be.scope,activeState:(ve=Be.active)==null?void 0:ve.state};const je=await Be.pushManager.getSubscription();if(je){const Ye=je.toJSON();Q.subscription={endpoint:Ye.endpoint,p256dh:(he=Ye.keys)==null?void 0:he.p256dh,auth:(Se=Ye.keys)==null?void 0:Se.auth}}}}catch(Te){Q.error=(Te==null?void 0:Te.message)||String(Te)}se&&m(Q)};ee();const oe=window.setInterval(ee,4e3);return()=>{se=!1,window.clearInterval(oe)}},[]);const I=async()=>{if(typeof Notification>"u"){ae.error("Notifications API not available in this browser.");return}try{if(Notification.permission!=="granted"&&await Notification.requestPermission()!=="granted"){ae.error("Notification permission not granted.");return}new Notification("Local notification test",{body:"If you see this, OS/browser notifications can display."}),ae.success("Triggered a local notification (not push).")}catch(se){ae.error(`Local notification failed: ${(se==null?void 0:se.message)||String(se)}`)}},P=async()=>{c(!0),g(null);try{const{data:se,error:ee}=await V.functions.invoke("send-push-notification",{body:{title:t,body:r,url:i}});if(ee)throw ee;g({sent:se==null?void 0:se.sent,failed:se==null?void 0:se.failed,expiredCleaned:se==null?void 0:se.expiredCleaned,vapidPublicKey:se==null?void 0:se.vapidPublicKey}),(se==null?void 0:se.sent)>0?ae.success(`Test notification sent to ${se.sent} subscriber(s)`):(se==null?void 0:se.failed)>0?ae.warning(`Notification failed for ${se.failed} subscriber(s). ${se.expired||0} expired subscriptions cleaned up.`):ae.info("No active subscriptions to send to")}catch(se){console.error("Error sending test notification:",se),g({error:(se==null?void 0:se.message)||String(se)}),ae.error("Failed to send test notification: "+(se.message||"Unknown error"))}finally{c(!1)}},R=async()=>{u(!0),y(null);try{const{data:se,error:ee}=await V.functions.invoke("generate-vapid-keys",{body:{}});if(ee)throw ee;const oe=se==null?void 0:se.publicKey,me=se==null?void 0:se.privateKey;if(!oe||!me)throw new Error("generate-vapid-keys did not return keys");y({publicKey:oe,privateKey:me}),ae.success("Generated new VAPID keys. Update backend secrets, then clear + re-subscribe.")}catch(se){console.error("Error generating VAPID keys:",se),ae.error("Failed to generate VAPID keys: "+((se==null?void 0:se.message)||"Unknown error"))}finally{u(!1)}},O=Nt({mutationFn:async()=>{const{error:se}=await V.from("push_subscriptions").delete().neq("id","00000000-0000-0000-0000-000000000000");if(se)throw se},onSuccess:()=>{ae.success("All subscriptions cleared. Users will need to re-enable notifications."),s.invalidateQueries({queryKey:["push-subscription-stats"]})},onError:se=>{ae.error("Failed to clear subscriptions: "+se.message)}});return e.jsx(Xs,{title:"Notification Settings",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(nm,{title:"Notification Settings",description:"Manage push notifications and test the notification system"}),e.jsxs(we,{children:[e.jsxs(Vt,{children:[e.jsxs(Yt,{className:"flex items-center gap-2",children:[e.jsx(Xn,{className:"h-5 w-5"}),"Push Notification Subscribers"]}),e.jsx(vr,{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:C?"...":(j==null?void 0:j.totalSubscriptions)||0}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"active subscriptions"})]})})]}),e.jsxs(we,{children:[e.jsxs(Vt,{children:[e.jsxs(Yt,{className:"flex items-center gap-2",children:[e.jsx(Yc,{className:"h-5 w-5"}),"Notification Types"]}),e.jsx(vr,{children:"Control which types of push notifications are sent to users"})]}),e.jsx(De,{children:_?e.jsx("div",{className:"text-sm text-muted-foreground",children:"Loading settings..."}):e.jsx("div",{className:"space-y-4",children:v==null?void 0:v.map(se=>{const ee=G8n[se.setting_key]||{label:se.setting_key,icon:"🔔"};return e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("span",{className:"text-2xl",children:ee.icon}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:ee.label}),e.jsx("div",{className:"text-sm text-muted-foreground",children:se.description})]})]}),e.jsx(On,{checked:se.is_enabled,onCheckedChange:oe=>A.mutate({settingKey:se.setting_key,isEnabled:oe}),disabled:A.isPending})]},se.id)})})})]}),e.jsxs(we,{children:[e.jsxs(Vt,{children:[e.jsxs(Yt,{className:"flex items-center gap-2",children:[e.jsx(Fx,{className:"h-5 w-5"}),"Send Test Notification"]}),e.jsx(vr,{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:M}),h.error&&e.jsx("div",{className:"mt-2 text-destructive",children:h.error}),e.jsxs("div",{className:"mt-2 grid gap-2 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground",children:"Backend VAPID public key"}),e.jsx("div",{className:"break-all rounded-md border bg-background p-2 font-mono text-xs",children:h.vapidPublicKey?GG(h.vapidPublicKey):"(not loaded)"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground",children:"Service worker"}),e.jsxs("div",{className:"rounded-md border bg-background p-2 font-mono text-xs",children:[e.jsxs("div",{children:["scope: ",(B=h.serviceWorker)!=null&&B.scope?GG(h.serviceWorker.scope,24,8):"none"]}),e.jsxs("div",{children:["active: ",((U=h.serviceWorker)==null?void 0:U.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: ",(G=h.subscription)!=null&&G.endpoint?GG(h.subscription.endpoint,40,12):"none"]}),e.jsxs("div",{children:["p256dh: ",(H=h.subscription)!=null&&H.p256dh?GG(h.subscription.p256dh,22,10):"none"]}),e.jsxs("div",{children:["auth: ",(Y=h.subscription)!=null&&Y.auth?GG(h.subscription.auth,22,10):"none"]})]})]})]}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[e.jsx($,{variant:"outline",onClick:I,children:"Local notification test"}),e.jsx($,{variant:"outline",onClick:()=>window.location.reload(),children:"Reload page"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"test-title",children:"Notification Title"}),e.jsx(be,{id:"test-title",value:t,onChange:se=>n(se.target.value),placeholder:"Enter notification title"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"test-body",children:"Notification Body"}),e.jsx(Ls,{id:"test-body",value:r,onChange:se=>a(se.target.value),placeholder:"Enter notification message",rows:3})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"test-url",children:"Click URL (optional)"}),e.jsx(be,{id:"test-url",value:i,onChange:se=>l(se.target.value),placeholder:"/community or full URL"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Where users will be taken when they click the notification"})]}),e.jsxs($,{onClick:P,disabled:o||!t||!r,className:"w-full sm:w-auto",children:[e.jsx(Wr,{className:"h-4 w-4 mr-2"}),o?"Sending...":"Send Test Notification"]}),p&&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"}),p.error?e.jsxs("div",{className:"mt-1 text-destructive",children:["Error: ",p.error]}):e.jsxs("div",{className:"mt-1 space-y-1 text-muted-foreground",children:[e.jsxs("div",{children:["Result: ",p.sent??0," sent, ",p.failed??0," failed, ",p.expiredCleaned??0," expired cleaned"]}),p.vapidPublicKey?e.jsxs("div",{className:"break-all",children:["Backend VAPID public key: ",e.jsx("span",{className:"font-mono",children:p.vapidPublicKey})]}):e.jsx("div",{children:"Backend VAPID public key: (not returned)"})]})]})]})]}),e.jsxs(we,{children:[e.jsxs(Vt,{children:[e.jsxs(Yt,{className:"flex items-center gap-2 text-destructive",children:[e.jsx(Un,{className:"h-5 w-5"}),"Subscription Maintenance"]}),e.jsx(vr,{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($,{variant:"destructive",onClick:()=>O.mutate(),disabled:O.isPending,children:[e.jsx(Un,{className:"h-4 w-4 mr-2"}),O.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($,{variant:"outline",onClick:R,disabled:d,children:d?"Generating…":"Generate VAPID keys"})}),x&&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:x.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:x.privateKey})]})]})]})]})]})]})})}function K8n(){const{toast:s}=Fi(),[t,n]=k.useState([]),[r,a]=k.useState({totalPresentations:0,totalViews:0,totalLeads:0,totalCtaClicks:0,agentsUsing:0}),[i,l]=k.useState(!0),{sortKey:o,sortDirection:c,handleSort:d,sortData:u}=Uee("presentation_count","desc"),h=u(t,{name:g=>{var x;return((x=g.name)==null?void 0:x.toLowerCase())||""},presentations:g=>g.presentation_count,views:g=>g.total_views,leads:g=>g.total_leads,cta_clicks:g=>g.total_cta_clicks,conversion:g=>g.total_views>0?g.total_leads/g.total_views*100:0});k.useEffect(()=>{m()},[]);const m=async()=>{try{l(!0);const{data:g,error:x}=await V.rpc("get_admin_presentation_stats");if(x)throw x;if(!g||g.length===0){l(!1);return}const y=g.map(A=>A.owner_user_id),{data:v,error:_}=await V.from("profiles").select("id, name, email, avatar_url").in("id",y);if(_)throw _;const j=new Map((v==null?void 0:v.map(A=>[A.id,A]))||[]),C=g.map(A=>{const M=j.get(A.owner_user_id);return{owner_user_id:A.owner_user_id,name:(M==null?void 0:M.name)||"Unknown",email:(M==null?void 0:M.email)||"",avatar_url:(M==null?void 0:M.avatar_url)||null,presentation_count:Number(A.presentation_count),total_views:Number(A.total_views),total_leads:Number(A.total_leads),total_cta_clicks:Number(A.total_cta_clicks)}});n(C),n(C),a({totalPresentations:C.reduce((A,M)=>A+M.presentation_count,0),totalViews:C.reduce((A,M)=>A+M.total_views,0),totalLeads:C.reduce((A,M)=>A+M.total_leads,0),totalCtaClicks:C.reduce((A,M)=>A+M.total_cta_clicks,0),agentsUsing:C.length})}catch(g){console.error("Error loading presentation stats:",g),s({title:"Error",description:"Failed to load presentation analytics",variant:"destructive"})}finally{l(!1)}},p=[{label:"Agents Using",value:r.agentsUsing,icon:Xn,color:"text-blue-600"},{label:"Total Presentations",value:r.totalPresentations,icon:hv,color:"text-violet-600"},{label:"Total Views",value:r.totalViews,icon:ba,color:"text-emerald-600"},{label:"Total Leads",value:r.totalLeads,icon:Pl,color:"text-amber-600"},{label:"CTA Clicks",value:r.totalCtaClicks,icon:rh,color:"text-rose-600"}];return e.jsx(Xs,{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:p.map(g=>e.jsxs(we,{children:[e.jsxs(Vt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Yt,{className:"text-sm font-medium",children:g.label}),e.jsx(g.icon,{className:`h-4 w-4 ${g.color}`})]}),e.jsx(De,{children:i?e.jsx(fn,{className:"h-8 w-16"}):e.jsx("div",{className:"text-2xl font-bold",children:g.value.toLocaleString()})})]},g.label))}),e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsxs(Yt,{className:"flex items-center gap-2",children:[e.jsx(mc,{className:"h-5 w-5"}),"Agent Breakdown"]})}),e.jsx(De,{children:i?e.jsx("div",{className:"space-y-3",children:[...Array(5)].map((g,x)=>e.jsx(fn,{className:"h-12 w-full"},x))}):t.length===0?e.jsx("p",{className:"text-muted-foreground text-center py-8",children:"No presentations created yet."}):e.jsxs(Qa,{children:[e.jsx(Ja,{children:e.jsxs(vn,{children:[e.jsx(Dh,{sortKey:"name",currentSortKey:o,currentDirection:c,onSort:d,children:"Agent"}),e.jsx(Dh,{sortKey:"presentations",currentSortKey:o,currentDirection:c,onSort:d,className:"text-center",children:"Presentations"}),e.jsx(Dh,{sortKey:"views",currentSortKey:o,currentDirection:c,onSort:d,className:"text-center",children:"Views"}),e.jsx(Dh,{sortKey:"leads",currentSortKey:o,currentDirection:c,onSort:d,className:"text-center",children:"Leads"}),e.jsx(Dh,{sortKey:"cta_clicks",currentSortKey:o,currentDirection:c,onSort:d,className:"text-center",children:"CTA Clicks"}),e.jsx(Dh,{sortKey:"conversion",currentSortKey:o,currentDirection:c,onSort:d,className:"text-center",children:"Conversion"})]})}),e.jsx(ei,{children:h.map(g=>{var y,v;const x=g.total_views>0?(g.total_leads/g.total_views*100).toFixed(1):"0.0";return e.jsxs(vn,{children:[e.jsx(_t,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-8 w-8 rounded-full bg-muted flex items-center justify-center overflow-hidden",children:g.avatar_url?e.jsx("img",{src:g.avatar_url,alt:"",className:"h-full w-full object-cover"}):e.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:((v=(y=g.name)==null?void 0:y.charAt(0))==null?void 0:v.toUpperCase())||"?"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-sm",children:g.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:g.email})]})]})}),e.jsx(_t,{className:"text-center font-medium",children:g.presentation_count}),e.jsx(_t,{className:"text-center",children:g.total_views.toLocaleString()}),e.jsx(_t,{className:"text-center",children:g.total_leads>0?e.jsx(qe,{variant:"secondary",children:g.total_leads}):e.jsx("span",{className:"text-muted-foreground",children:"0"})}),e.jsx(_t,{className:"text-center",children:g.total_cta_clicks}),e.jsx(_t,{className:"text-center",children:e.jsxs("span",{className:Number(x)>0?"text-emerald-600 font-medium":"text-muted-foreground",children:[x,"%"]})})]},g.owner_user_id)})})]})})]})]})})}const ZDe=s=>s?new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",month:"short",day:"numeric",year:"numeric"}).format(new Date(s)):"—",Y8n=s=>s==null?"—":`$${Number(s).toLocaleString("en-US",{maximumFractionDigits:0})}`;function Z8n(){const{toast:s}=Fi(),[t,n]=k.useState(!0),[r,a]=k.useState([]),[i,l]=k.useState({}),[o,c]=k.useState("");k.useEffect(()=>{(async()=>{try{n(!0);const y=[],v=1e3;for(let C=0;;C+=v){const{data:A,error:M}=await V.from("listing_presentations").select("id, owner_user_id, title, status, property_address_line1, city, state, list_price, template_id, last_generated_at, created_at, updated_at").order("created_at",{ascending:!1}).range(C,C+v-1);if(M)throw M;if(y.push(...A??[]),!A||A.lengthC.owner_user_id))),j={};for(let C=0;C<_.length;C+=200){const{data:A}=await V.from("profiles").select("id, name, email").in("id",_.slice(C,C+200));(A??[]).forEach(M=>{j[M.id]={name:M.name??"Unknown",email:M.email??""}})}l(j)}catch(y){console.error(y),s({title:"Error",description:"Failed to load presentation data",variant:"destructive"})}finally{n(!1)}})()},[s]);const d=k.useMemo(()=>{const x=Date.now(),y=x-7*24*60*60*1e3,v=x-30*24*60*60*1e3;return{total:r.length,generated:r.filter(_=>!!_.last_generated_at).length,agents:new Set(r.map(_=>_.owner_user_id)).size,thisWeek:r.filter(_=>new Date(_.created_at).getTime()>=y).length,thisMonth:r.filter(_=>new Date(_.created_at).getTime()>=v).length}},[r]),u=k.useMemo(()=>{const x=new Map;return r.forEach(y=>{const v=i[y.owner_user_id],_=x.get(y.owner_user_id)??{user_id:y.owner_user_id,name:(v==null?void 0:v.name)??"Unknown",email:(v==null?void 0:v.email)??"",total:0,generated:0,last_activity:y.updated_at};_.total+=1,y.last_generated_at&&(_.generated+=1),new Date(y.updated_at)>new Date(_.last_activity)&&(_.last_activity=y.updated_at),x.set(y.owner_user_id,_)}),Array.from(x.values()).sort((y,v)=>v.total-y.total)},[r,i]),h=o.trim().toLowerCase(),m=h?u.filter(x=>x.name.toLowerCase().includes(h)||x.email.toLowerCase().includes(h)):u,p=h?r.filter(x=>{const y=i[x.owner_user_id];return(x.title??"").toLowerCase().includes(h)||(x.property_address_line1??"").toLowerCase().includes(h)||(x.city??"").toLowerCase().includes(h)||((y==null?void 0:y.name)??"").toLowerCase().includes(h)||((y==null?void 0:y.email)??"").toLowerCase().includes(h)}):r,g=[{label:"Total presentations",value:d.total,icon:ea,sub:"All time"},{label:"Agents using it",value:d.agents,icon:Xn,sub:"Created at least one"},{label:"PDFs generated",value:d.generated,icon:kn,sub:"Rendered at least once"},{label:"Created last 30 days",value:d.thisMonth,icon:wm,sub:`${d.thisWeek} in last 7 days`}];return e.jsx(Xs,{title:"Listing Presentation Studio",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(nm,{title:"Listing Presentation Studio",description:"Adoption and usage of the Listing Presentation Studio across all agents"}),t?e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-4",children:[0,1,2,3].map(x=>e.jsx(fn,{className:"h-28 w-full"},x))}):e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-4",children:g.map(x=>e.jsxs(we,{children:[e.jsxs(Vt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Yt,{className:"text-sm font-medium",children:x.label}),e.jsx(x.icon,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(De,{children:[e.jsx("div",{className:"text-2xl font-bold",children:x.value}),e.jsx("p",{className:"text-xs text-muted-foreground",children:x.sub})]})]},x.label))}),e.jsxs("div",{className:"relative max-w-md",children:[e.jsx(Yr,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(be,{className:"pl-9",placeholder:"Search agents, addresses, titles...",value:o,onChange:x=>c(x.target.value)})]}),e.jsxs(ya,{defaultValue:"agents",className:"space-y-4",children:[e.jsxs(va,{children:[e.jsxs(is,{value:"agents",children:["By agent (",m.length,")"]}),e.jsxs(is,{value:"all",children:["All presentations (",p.length,")"]})]}),e.jsx(cs,{value:"agents",children:e.jsx(we,{children:e.jsx(De,{className:"p-0",children:e.jsxs(Qa,{children:[e.jsx(Ja,{children:e.jsxs(vn,{children:[e.jsx(Dt,{children:"Agent"}),e.jsx(Dt,{className:"text-right",children:"Presentations"}),e.jsx(Dt,{className:"text-right",children:"Generated"}),e.jsx(Dt,{children:"Last activity"})]})}),e.jsxs(ei,{children:[m.map(x=>e.jsxs(vn,{children:[e.jsxs(_t,{children:[e.jsx("div",{className:"font-medium",children:x.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:x.email})]}),e.jsx(_t,{className:"text-right font-semibold",children:x.total}),e.jsx(_t,{className:"text-right",children:x.generated}),e.jsx(_t,{children:ZDe(x.last_activity)})]},x.user_id)),!t&&m.length===0&&e.jsx(vn,{children:e.jsx(_t,{colSpan:4,className:"py-10 text-center text-muted-foreground",children:"No agents have created a listing presentation yet."})})]})]})})})}),e.jsx(cs,{value:"all",children:e.jsx(we,{children:e.jsx(De,{className:"p-0",children:e.jsxs(Qa,{children:[e.jsx(Ja,{children:e.jsxs(vn,{children:[e.jsx(Dt,{children:"Presentation"}),e.jsx(Dt,{children:"Agent"}),e.jsx(Dt,{children:"Property"}),e.jsx(Dt,{children:"Price"}),e.jsx(Dt,{children:"Status"}),e.jsx(Dt,{children:"Created"}),e.jsx(Dt,{children:"Last generated"})]})}),e.jsxs(ei,{children:[p.slice(0,300).map(x=>{var y,v;return e.jsxs(vn,{children:[e.jsx(_t,{className:"font-medium",children:x.title||"Untitled"}),e.jsxs(_t,{children:[e.jsx("div",{children:((y=i[x.owner_user_id])==null?void 0:y.name)??"Unknown"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:((v=i[x.owner_user_id])==null?void 0:v.email)??""})]}),e.jsx(_t,{className:"text-sm",children:[x.property_address_line1,x.city,x.state].filter(Boolean).join(", ")||"—"}),e.jsx(_t,{children:Y8n(x.list_price)}),e.jsx(_t,{children:e.jsx(qe,{variant:x.last_generated_at?"default":"secondary",children:x.last_generated_at?"Generated":x.status||"Draft"})}),e.jsx(_t,{children:ZDe(x.created_at)}),e.jsx(_t,{children:ZDe(x.last_generated_at)})]},x.id)}),!t&&p.length===0&&e.jsx(vn,{children:e.jsx(_t,{colSpan:7,className:"py-10 text-center text-muted-foreground",children:"No presentations found."})})]})]})})})})]})]})})}const oZ="listing_revival";function X8n(){const{user:s,loading:t,isAdmin:n}=ks(),{data:r}=pt({queryKey:["feature-entitlement",oZ,s==null?void 0:s.id],enabled:!!s&&!n,staleTime:5*60*1e3,queryFn:async()=>{const{data:a,error:i}=await V.from("feature_entitlements").select("enabled, expires_at, tier").eq("user_id",s.id).eq("feature_key",oZ).maybeSingle();if(i)throw i;return{tier:(a==null?void 0:a.tier)??null}}});return{hasAccess:!0,tier:n?"admin":(r==null?void 0:r.tier)??null,isLoading:t}}const Q8n=s=>s?new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",month:"short",day:"numeric",year:"numeric"}).format(new Date(s)):"—";function J8n(){var u,h;const{user:s}=ks(),t=ls(),[n,r]=k.useState(""),a=pt({queryKey:["lr-admin-stats"],queryFn:async()=>{const{data:m,error:p}=await V.rpc("get_admin_listing_revival_stats");if(p)throw p;return m??[]}}),i=pt({queryKey:["lr-admin-members",n],queryFn:async()=>{let m=V.from("profiles").select("id, name, email").order("name").limit(200);if(n.trim()){const _=`%${n.trim()}%`;m=m.or(`email.ilike.${_},name.ilike.${_}`)}const{data:p,error:g}=await m;if(g)throw g;const x=(p??[]).map(_=>_.id),{data:y}=await V.from("feature_entitlements").select("user_id, enabled, tier").eq("feature_key",oZ).in("user_id",x.length?x:["00000000-0000-0000-0000-000000000000"]),v=new Map((y??[]).map(_=>[_.user_id,_]));return(p??[]).map(_=>{var j;return{user_id:_.id,name:_.name,email:_.email,enabled:!!((j=v.get(_.id))!=null&&j.enabled)}})}}),l=Nt({mutationFn:async({userId:m,enabled:p})=>{const{error:g}=await V.from("feature_entitlements").upsert({user_id:m,feature_key:oZ,enabled:p,tier:"member",enabled_by:s.id,enabled_at:new Date().toISOString()},{onConflict:"user_id,feature_key"});if(g)throw g;await V.from("feature_entitlement_audit").insert({feature_key:oZ,target_user_id:m,action:p?"grant":"revoke",performed_by:s.id})},onSuccess:(m,p)=>{t.invalidateQueries({queryKey:["lr-admin-members"]}),ae.success(p.enabled?"Access granted":"Access revoked")},onError:m=>ae.error(m.message)}),o=pt({queryKey:["lr-admin-stat-profiles",(a.data??[]).length],enabled:!!((u=a.data)!=null&&u.length),queryFn:async()=>{const m=(a.data??[]).map(g=>g.owner_user_id),{data:p}=await V.from("profiles").select("id, name, email").in("id",m);return new Map((p??[]).map(g=>[g.id,g]))}}),c=k.useMemo(()=>{const m=a.data??[];return{agents:m.length,campaigns:m.reduce((p,g)=>p+Number(g.campaign_count),0),leads:m.reduce((p,g)=>p+Number(g.lead_count),0),hot:m.reduce((p,g)=>p+Number(g.hot_lead_count),0)}},[a.data]),d=[{label:"Agents using it",value:c.agents,icon:Xn},{label:"Campaigns built",value:c.campaigns,icon:kn},{label:"Seller leads",value:c.leads,icon:v0},{label:"Hot leads",value:c.hot,icon:iu}];return e.jsxs(Xs,{title:"Listing Revival Admin",children:[e.jsx(nm,{title:"Listing Revival",description:"Track adoption, campaign output and seller leads — and control who gets access."}),e.jsx("div",{className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-4 mt-6",children:d.map(m=>e.jsx(we,{children:e.jsxs(De,{className:"p-5 flex items-center gap-4",children:[e.jsx("div",{className:"rounded-xl bg-amber-500/15 text-amber-600 p-3",children:e.jsx(m.icon,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold tabular-nums",children:a.isLoading?"—":m.value}),e.jsx("div",{className:"text-xs text-muted-foreground uppercase tracking-wider",children:m.label})]})]})},m.label))}),e.jsxs(ya,{defaultValue:"usage",className:"mt-6",children:[e.jsxs(va,{children:[e.jsx(is,{value:"usage",children:"Agent usage"}),e.jsx(is,{value:"access",children:"Access"})]}),e.jsx(cs,{value:"usage",className:"mt-4",children:e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsx(Yt,{className:"text-base",children:"Usage by agent"})}),e.jsx(De,{children:a.isLoading?e.jsx("div",{className:"space-y-2",children:[0,1,2].map(m=>e.jsx(fn,{className:"h-10 w-full"},m))}):(h=a.data)!=null&&h.length?e.jsxs(Qa,{children:[e.jsx(Ja,{children:e.jsxs(vn,{children:[e.jsx(Dt,{children:"Agent"}),e.jsx(Dt,{className:"text-right",children:"Campaigns"}),e.jsx(Dt,{className:"text-right",children:"Live pages"}),e.jsx(Dt,{className:"text-right",children:"Leads"}),e.jsx(Dt,{className:"text-right",children:"Hot"}),e.jsx(Dt,{className:"text-right",children:"Engagement"}),e.jsx(Dt,{className:"text-right",children:"Last activity"})]})}),e.jsx(ei,{children:[...a.data].sort((m,p)=>Number(p.campaign_count)-Number(m.campaign_count)).map(m=>{var g;const p=(g=o.data)==null?void 0:g.get(m.owner_user_id);return e.jsxs(vn,{children:[e.jsxs(_t,{children:[e.jsx("div",{className:"font-medium",children:(p==null?void 0:p.name)??"Agent"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:(p==null?void 0:p.email)??m.owner_user_id.slice(0,8)})]}),e.jsx(_t,{className:"text-right tabular-nums",children:m.campaign_count}),e.jsx(_t,{className:"text-right tabular-nums",children:m.published_count}),e.jsx(_t,{className:"text-right tabular-nums",children:m.lead_count}),e.jsx(_t,{className:"text-right",children:Number(m.hot_lead_count)>0?e.jsx(qe,{className:"bg-red-500/15 text-red-600 hover:bg-red-500/15",children:m.hot_lead_count}):e.jsx("span",{className:"text-muted-foreground",children:"0"})}),e.jsx(_t,{className:"text-right tabular-nums",children:m.event_count}),e.jsx(_t,{className:"text-right text-sm text-muted-foreground",children:Q8n(m.last_activity)})]},m.owner_user_id)})})]}):e.jsx("p",{className:"text-sm text-muted-foreground py-6",children:"No campaigns have been created yet."})})]})}),e.jsx(cs,{value:"access",className:"mt-4",children:e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsx(Yt,{className:"text-base",children:"Who can use Listing Revival"})}),e.jsxs(De,{className:"space-y-4",children:[e.jsxs("div",{className:"relative max-w-sm",children:[e.jsx(Yr,{className:"h-4 w-4 absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground"}),e.jsx(be,{className:"pl-9",placeholder:"Search agents by name or email",value:n,onChange:m=>r(m.target.value)})]}),i.isLoading?e.jsx("div",{className:"space-y-2",children:[0,1,2].map(m=>e.jsx(fn,{className:"h-10 w-full"},m))}):e.jsxs(Qa,{children:[e.jsx(Ja,{children:e.jsxs(vn,{children:[e.jsx(Dt,{children:"Agent"}),e.jsx(Dt,{children:"Email"}),e.jsx(Dt,{className:"text-right",children:"Access"})]})}),e.jsx(ei,{children:(i.data??[]).map(m=>e.jsxs(vn,{children:[e.jsx(_t,{className:"font-medium",children:m.name??"—"}),e.jsx(_t,{className:"text-muted-foreground",children:m.email??"—"}),e.jsx(_t,{className:"text-right",children:e.jsx(On,{checked:m.enabled,onCheckedChange:p=>l.mutate({userId:m.user_id,enabled:p})})})]},m.user_id))})]})]})]})})]})]})}function eOn(){const{toast:s}=Fi(),[t,n]=k.useState([]),[r,a]=k.useState({totalOpenHouses:0,totalVisitors:0,totalLeads:0,activeOpenHouses:0,agentsUsing:0}),[i,l]=k.useState(!0);k.useEffect(()=>{o()},[]);const o=async()=>{try{l(!0);const{data:d,error:u}=await V.rpc("get_admin_guest_book_stats");if(u)throw u;if(!d||d.length===0){l(!1);return}const h=d.map(y=>y.agent_id),{data:m,error:p}=await V.from("profiles").select("id, name, email, avatar_url").in("id",h);if(p)throw p;const g=new Map((m==null?void 0:m.map(y=>[y.id,y]))||[]),x=d.map(y=>{const v=g.get(y.agent_id);return{agent_id:y.agent_id,name:(v==null?void 0:v.name)||"Unknown",email:(v==null?void 0:v.email)||"",avatar_url:(v==null?void 0:v.avatar_url)||null,open_house_count:Number(y.open_house_count),total_visitors:Number(y.total_visitors),total_leads:Number(y.total_leads),active_count:Number(y.active_count)}});x.sort((y,v)=>v.total_visitors-y.total_visitors),n(x),a({totalOpenHouses:x.reduce((y,v)=>y+v.open_house_count,0),totalVisitors:x.reduce((y,v)=>y+v.total_visitors,0),totalLeads:x.reduce((y,v)=>y+v.total_leads,0),activeOpenHouses:x.reduce((y,v)=>y+v.active_count,0),agentsUsing:x.length})}catch(d){console.error("Error loading guest book stats:",d),s({title:"Error",description:"Failed to load guest book analytics",variant:"destructive"})}finally{l(!1)}},c=[{label:"Agents Using",value:r.agentsUsing,icon:Xn,color:"text-blue-600"},{label:"Total Open Houses",value:r.totalOpenHouses,icon:ua,color:"text-violet-600"},{label:"Active Now",value:r.activeOpenHouses,icon:nl,color:"text-emerald-600"},{label:"Total Visitors",value:r.totalVisitors,icon:ba,color:"text-amber-600"},{label:"Leads Created",value:r.totalLeads,icon:Pl,color:"text-rose-600"}];return e.jsx(Xs,{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(we,{children:[e.jsxs(Vt,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Yt,{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(fn,{className:"h-8 w-16"}):e.jsx("div",{className:"text-2xl font-bold",children:d.value.toLocaleString()})})]},d.label))}),e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsxs(Yt,{className:"flex items-center gap-2",children:[e.jsx(mc,{className:"h-5 w-5"}),"Agent Breakdown"]})}),e.jsx(De,{children:i?e.jsx("div",{className:"space-y-3",children:[...Array(5)].map((d,u)=>e.jsx(fn,{className:"h-12 w-full"},u))}):t.length===0?e.jsx("p",{className:"text-muted-foreground text-center py-8",children:"No open houses created yet."}):e.jsxs(Qa,{children:[e.jsx(Ja,{children:e.jsxs(vn,{children:[e.jsx(Dt,{children:"Agent"}),e.jsx(Dt,{className:"text-center",children:"Open Houses"}),e.jsx(Dt,{className:"text-center",children:"Active"}),e.jsx(Dt,{className:"text-center",children:"Visitors"}),e.jsx(Dt,{className:"text-center",children:"Leads"}),e.jsx(Dt,{className:"text-center",children:"Conversion"})]})}),e.jsx(ei,{children:t.map(d=>{var h,m;const u=d.total_visitors>0?(d.total_leads/d.total_visitors*100).toFixed(1):"0.0";return e.jsxs(vn,{children:[e.jsx(_t,{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:((m=(h=d.name)==null?void 0:h.charAt(0))==null?void 0:m.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(_t,{className:"text-center font-medium",children:d.open_house_count}),e.jsx(_t,{className:"text-center",children:d.active_count>0?e.jsx(qe,{variant:"secondary",className:"bg-emerald-100 text-emerald-700",children:d.active_count}):e.jsx("span",{className:"text-muted-foreground",children:"0"})}),e.jsx(_t,{className:"text-center",children:d.total_visitors.toLocaleString()}),e.jsx(_t,{className:"text-center",children:d.total_leads>0?e.jsx(qe,{variant:"secondary",children:d.total_leads}):e.jsx("span",{className:"text-muted-foreground",children:"0"})}),e.jsx(_t,{className:"text-center",children:e.jsxs("span",{className:Number(u)>0?"text-emerald-600 font-medium":"text-muted-foreground",children:[u,"%"]})})]},d.agent_id)})})]})})]})]})})}function tOn(){const[s]=Jc(),t=Jn(),[n,r]=k.useState("loading"),a=k.useRef(!1),[i,l]=k.useState("Processing connection...");return k.useEffect(()=>{if(a.current)return;a.current=!0,(async()=>{const c=s.get("code"),d=s.get("error"),u=s.get("error_description"),h=s.get("state");if(d){r("error"),l(u||"Authorization was denied"),ae.error("Failed to connect: "+(u||d));return}if(!c){r("error"),l("No authorization code received"),ae.error("Failed to connect: No authorization code");return}try{const{data:m,error:p}=await V.functions.invoke("meta-oauth",{body:{action:"exchange_code",code:c,state:h}});if(m&&m.success===!1)throw new Error(m.error||"Failed to connect accounts");if(p){let g=p.message||"Failed to connect accounts";try{const x=p.context;if(x&&typeof x.json=="function"){const y=await x.json();y!=null&&y.error&&(g=y.error)}}catch{}throw new Error(g)}if(m!=null&&m.success)r("success"),l(m.message||"Accounts connected successfully!"),ae.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),r("error"),l(m.message||"Failed to complete connection"),ae.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(we,{className:"w-full max-w-md",children:[e.jsxs(Vt,{className:"text-center",children:[e.jsxs("div",{className:"mx-auto mb-4",children:[n==="loading"&&e.jsx(Jt,{className:"h-12 w-12 animate-spin text-primary"}),n==="success"&&e.jsx(nl,{className:"h-12 w-12 text-green-500"}),n==="error"&&e.jsx(ju,{className:"h-12 w-12 text-destructive"})]}),e.jsxs(Yt,{children:[n==="loading"&&"Connecting...",n==="success"&&"Connected!",n==="error"&&"Connection Failed"]}),e.jsx(vr,{children:i})]}),e.jsx(De,{className:"flex justify-center",children:e.jsx($,{onClick:()=>t("/admin/integrations"),children:n==="success"?"View Integrations":"Back to Integrations"})})]})})}function sOn(){const s=ls(),[t,n]=k.useState(""),[r,a]=k.useState(""),[i,l]=k.useState([]),o=k.useRef(null),{data:c,isLoading:d}=pt({queryKey:["prospect-emails"],queryFn:async()=>{const{data:_,error:j}=await V.from("prospect_emails").select("*").order("sent_at",{ascending:!1});if(j)throw j;return _}}),u=(c==null?void 0:c.filter(_=>_.status==="live_lead"))||[],h={total:(c==null?void 0:c.length)||0,sent:(c==null?void 0:c.filter(_=>_.status==="sent").length)||0,converted:(c==null?void 0:c.filter(_=>_.status==="converted").length)||0,liveLeads:u.length,conversionRate:c!=null&&c.length?Math.round(c.filter(_=>_.status==="converted").length/c.length*100):0},m=Nt({mutationFn:async _=>{const{data:j,error:C}=await V.functions.invoke("send-prospect-email",{body:{emails:_}});if(C)throw C;return j},onSuccess:_=>{s.invalidateQueries({queryKey:["prospect-emails"]}),ae.success(`${_.sent} email${_.sent>1?"s":""} sent successfully!`),n(""),a(""),l([])},onError:_=>{ae.error("Failed to send: "+_.message)}}),p=Nt({mutationFn:async()=>{var A,M;const{data:{user:_}}=await V.auth.getUser();if(!(_!=null&&_.email))throw new Error("Could not get your email");const{data:j,error:C}=await V.functions.invoke("send-prospect-email",{body:{emails:[{email:_.email,first_name:(M=(A=_.user_metadata)==null?void 0:A.name)==null?void 0:M.split(" ")[0]}],test_mode:!0}});if(C)throw C;return j},onSuccess:()=>{ae.success("Test email sent to your inbox!")},onError:_=>{ae.error("Failed to send test: "+_.message)}}),g=Nt({mutationFn:async()=>{const{data:_,error:j}=await V.functions.invoke("send-prospect-email",{body:{mode:"live_leads"}});if(j)throw j;return _},onSuccess:_=>{s.invalidateQueries({queryKey:["prospect-emails"]}),ae.success(`${_.sent} live lead invite${_.sent===1?"":"s"} sent!`)},onError:_=>{ae.error("Failed to send live lead invites: "+_.message)}}),x=()=>{if(!t.trim()){ae.error("Please enter an email address");return}if(c==null?void 0:c.find(j=>j.email.toLowerCase()===t.trim().toLowerCase())){ae.error("This email has already been prospected");return}m.mutate([{email:t.trim(),first_name:r.trim()||void 0}])},y=_=>{var A;const j=(A=_.target.files)==null?void 0:A[0];if(!j)return;const C=new FileReader;C.onload=M=>{var B,U;const P=((B=M.target)==null?void 0:B.result).split(` `).filter(G=>G.trim()),R=[],O=(U=P[0])!=null&&U.toLowerCase().includes("email")?1:0;for(let G=O;Gee.trim().replace(/"/g,"")),Y=H[0],se=H[1];Y&&Y.includes("@")&&R.push({email:Y,first_name:se||void 0})}l(R),ae.success(`${R.length} entries loaded from CSV`)},C.readAsText(j),o.current&&(o.current.value="")},v=()=>{if(i.length===0){ae.error("No entries to send");return}const _=new Set((c==null?void 0:c.map(C=>C.email.toLowerCase()))||[]),j=i.filter(C=>!_.has(C.email.toLowerCase()));if(j.length===0){ae.error("All emails have already been prospected");return}j.length0&&e.jsxs(we,{className:"border-red-200/50 bg-red-500/[0.02]",children:[e.jsxs(Vt,{children:[e.jsxs(Yt,{className:"flex items-center gap-2",children:[e.jsx(Cy,{className:"h-5 w-5 text-red-600"}),"Live Event Leads",e.jsx(qe,{variant:"secondary",className:"ml-2",children:h.liveLeads})]}),e.jsx(vr,{children:"These agents registered on a LevelUp Live page but haven't received a free trial invite yet."})]}),e.jsx(De,{children:e.jsxs($,{onClick:()=>g.mutate(),disabled:g.isPending,className:"gap-2",children:[g.isPending?e.jsx(Jt,{className:"h-4 w-4 animate-spin"}):e.jsx(Wr,{className:"h-4 w-4"}),"Send free trial invite to all live leads"]})})]}),e.jsxs(we,{children:[e.jsxs(Vt,{children:[e.jsxs(Yt,{className:"flex items-center gap-2",children:[e.jsx(_h,{className:"h-5 w-5"}),"Send Prospect Email"]}),e.jsxs(vr,{className:"flex items-center justify-between",children:[e.jsx("span",{children:"Send a beautiful free trial invitation email to potential members"}),e.jsxs($,{variant:"outline",size:"sm",onClick:()=>p.mutate(),disabled:p.isPending,className:"gap-2 ml-4 shrink-0",children:[p.isPending?e.jsx(Jt,{className:"h-3 w-3 animate-spin"}):e.jsx(pn,{className:"h-3 w-3"}),"Send Test to Me"]})]})]}),e.jsx(De,{children:e.jsxs(ya,{defaultValue:"single",children:[e.jsxs(va,{className:"mb-4",children:[e.jsxs(is,{value:"single",children:[e.jsx(Wr,{className:"h-4 w-4 mr-2"}),"Single Send"]}),e.jsxs(is,{value:"bulk",children:[e.jsx(gi,{className:"h-4 w-4 mr-2"}),"Bulk CSV"]})]}),e.jsx(cs,{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(re,{htmlFor:"prospect-email",className:"sr-only",children:"Email"}),e.jsx(be,{id:"prospect-email",type:"email",placeholder:"agent@example.com",value:t,onChange:_=>n(_.target.value),onKeyDown:_=>_.key==="Enter"&&x()})]}),e.jsxs("div",{className:"w-full sm:w-48",children:[e.jsx(re,{htmlFor:"prospect-name",className:"sr-only",children:"First Name"}),e.jsx(be,{id:"prospect-name",placeholder:"First name (optional)",value:r,onChange:_=>a(_.target.value),onKeyDown:_=>_.key==="Enter"&&x()})]}),e.jsxs($,{onClick:x,disabled:m.isPending,className:"gap-2",children:[m.isPending?e.jsx(Jt,{className:"h-4 w-4 animate-spin"}):e.jsx(Wr,{className:"h-4 w-4"}),"Send Invite"]})]})}),e.jsx(cs,{value:"bulk",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("input",{ref:o,type:"file",accept:".csv",onChange:y,className:"hidden"}),e.jsxs($,{variant:"outline",onClick:()=>{var _;return(_=o.current)==null?void 0:_.click()},className:"gap-2",children:[e.jsx(ea,{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(qe,{variant:"secondary",className:"gap-1",children:[e.jsx(Xn,{className:"h-3 w-3"}),i.length," entries ready"]}),e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>l([]),children:[e.jsx(mr,{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((_,j)=>e.jsxs("div",{className:"text-muted-foreground",children:[_.email,_.first_name?` — ${_.first_name}`:""]},j)),i.length>20&&e.jsxs("div",{className:"text-muted-foreground/60",children:["...and ",i.length-20," more"]})]}),e.jsxs($,{onClick:v,disabled:m.isPending,className:"gap-2",children:[m.isPending?e.jsx(Jt,{className:"h-4 w-4 animate-spin"}):e.jsx(Wr,{className:"h-4 w-4"}),"Send ",i.length," Invites"]})]})]})})]})})]}),e.jsxs(we,{children:[e.jsxs(Vt,{children:[e.jsxs(Yt,{className:"flex items-center gap-2",children:[e.jsx(pn,{className:"h-5 w-5"}),"Prospect Log"]}),e.jsx(vr,{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((_,j)=>e.jsx(fn,{className:"h-12 w-full"},j))}):c&&c.length>0?e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b",children:[e.jsx("th",{className:"text-left py-3 px-4 text-sm font-medium text-muted-foreground",children:"Email"}),e.jsx("th",{className:"text-left py-3 px-4 text-sm font-medium text-muted-foreground",children:"Name"}),e.jsx("th",{className:"text-left py-3 px-4 text-sm font-medium text-muted-foreground",children:"Sent"}),e.jsx("th",{className:"text-left py-3 px-4 text-sm font-medium text-muted-foreground",children:"Status"}),e.jsx("th",{className:"text-left py-3 px-4 text-sm font-medium text-muted-foreground",children:"Converted"})]})}),e.jsx("tbody",{children:c.map(_=>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:_.email}),e.jsx("td",{className:"py-3 px-4 text-sm text-muted-foreground",children:_.first_name||"—"}),e.jsx("td",{className:"py-3 px-4 text-sm text-muted-foreground",children:Ys(new Date(_.sent_at),"MMM d, yyyy")}),e.jsx("td",{className:"py-3 px-4",children:_.status==="converted"?e.jsxs(qe,{className:"bg-green-500/10 text-green-700 hover:bg-green-500/20 border-0",children:[e.jsx(Gr,{className:"h-3 w-3 mr-1"}),"Converted"]}):_.status==="live_lead"?e.jsxs(qe,{className:"bg-red-500/10 text-red-700 hover:bg-red-500/20 border-0 gap-1",children:[e.jsx(Cy,{className:"h-3 w-3"}),"Live lead"]}):e.jsxs(qe,{variant:"secondary",className:"gap-1",children:[e.jsx(sa,{className:"h-3 w-3"}),"Sent"]})}),e.jsx("td",{className:"py-3 px-4 text-sm text-muted-foreground",children:_.converted_at?Ys(new Date(_.converted_at),"MMM d, yyyy"):"—"})]},_.id))})]})}):e.jsxs("div",{className:"text-center py-12",children:[e.jsx(_h,{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 wte(s){const t=ls(),{toast:n}=Fi(),r=pt({queryKey:["recruit-stages",s],queryFn:async()=>{if(!s)return[];const{data:c,error:d}=await V.from("recruit_pipeline_stages").select("*").eq("brokerage_id",s).order("sort_order");if(d)throw d;return c},enabled:!!s}),a=pt({queryKey:["recruit-prospects",s],queryFn:async()=>{if(!s)return[];const c=1e3;let d=[],u=0,h=!0;for(;h;){const{data:m,error:p}=await V.from("recruit_prospects").select("*").eq("brokerage_id",s).order("created_at",{ascending:!1}).range(u,u+c-1);if(p)throw p;d=d.concat(m),h=m.length===c,u+=c}return d},enabled:!!s}),i=Nt({mutationFn:async c=>{const{data:{user:d}}=await V.auth.getUser();if(!d)throw new Error("Not authenticated");const u={first_name:c.first_name||"",last_name:c.last_name||null,email:c.email||null,phone:c.phone||null,current_brokerage:c.current_brokerage||null,license_number:c.license_number||null,experience_years:c.experience_years??null,annual_production:c.annual_production||null,source:c.source||"manual",notes:c.notes||null,stage_id:c.stage_id||null,brokerage_id:s,created_by:d.id,address:c.address||null,city:c.city||null,state:c.state||null,zip_code:c.zip_code||null,last_year_volume:c.last_year_volume||null,last_year_transactions:c.last_year_transactions??null,avg_sale_price:c.avg_sale_price||null,specialties:c.specialties||null,linkedin_url:c.linkedin_url||null,website_url:c.website_url||null,instagram_handle:c.instagram_handle||null,facebook_url:c.facebook_url||null,birthday:c.birthday||null,spouse_name:c.spouse_name||null,interests:c.interests||null,referred_by:c.referred_by||null},{data:h,error:m}=await V.from("recruit_prospects").insert(u).select().single();if(m)throw m;return h},onSuccess:()=>{t.invalidateQueries({queryKey:["recruit-prospects",s]}),n({title:"Prospect added"})},onError:c=>n({title:"Error",description:c.message,variant:"destructive"})}),l=Nt({mutationFn:async({id:c,...d})=>{const{data:u,error:h}=await V.from("recruit_prospects").update({...d,updated_at:new Date().toISOString()}).eq("id",c).select().single();if(h)throw h;return u},onSuccess:()=>{t.invalidateQueries({queryKey:["recruit-prospects",s]})},onError:c=>n({title:"Error",description:c.message,variant:"destructive"})}),o=Nt({mutationFn:async c=>{const{error:d}=await V.from("recruit_prospects").delete().eq("id",c);if(d)throw d},onSuccess:()=>{t.invalidateQueries({queryKey:["recruit-prospects",s]}),n({title:"Prospect removed"})}});return{stages:r.data||[],prospects:a.data||[],isLoading:r.isLoading||a.isLoading,addProspect:i,updateProspect:l,deleteProspect:o}}function nOn(s){const t=ls(),{toast:n}=Fi(),r=pt({queryKey:["recruit-activities",s],queryFn:async()=>{if(!s)return[];const{data:i,error:l}=await V.from("recruit_activities").select("*").eq("prospect_id",s).order("created_at",{ascending:!1});if(l)throw l;return i},enabled:!!s}),a=Nt({mutationFn:async i=>{const{data:{user:l}}=await V.auth.getUser();if(!l)throw new Error("Not authenticated");const{data:o,error:c}=await V.from("recruit_activities").insert({...i,created_by:l.id}).select().single();if(c)throw c;return o},onSuccess:()=>{t.invalidateQueries({queryKey:["recruit-activities",s]}),n({title:"Activity logged"})},onError:i=>n({title:"Error",description:i.message,variant:"destructive"})});return{activities:r.data||[],isLoading:r.isLoading,addActivity:a}}const pbt=(s,t)=>{var n;return{first_name:"",last_name:"",email:"",phone:"",current_brokerage:"",license_number:"",experience_years:"",annual_production:"",source:"manual",notes:"",stage_id:s||((n=t==null?void 0:t[0])==null?void 0:n.id)||"",address:"",city:"",state:"",zip_code:"",last_year_volume:"",last_year_transactions:"",avg_sale_price:"",specialties:"",linkedin_url:"",website_url:"",instagram_handle:"",facebook_url:"",birthday:"",spouse_name:"",interests:"",referred_by:""}};function wVt({open:s,onOpenChange:t,stages:n,defaultStageId:r,onSubmit:a,isSubmitting:i}){const[l,o]=k.useState(pbt(r,n)),c=u=>h=>o(m=>({...m,[u]:h.target.value})),d=u=>{u.preventDefault(),a({...l,experience_years:l.experience_years?parseInt(l.experience_years):null,last_year_transactions:l.last_year_transactions?parseInt(l.last_year_transactions):null,stage_id:l.stage_id||null}),o(pbt(r,n)),t(!1)};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Vs,{children:e.jsx($s,{children:"Add Recruit Prospect"})}),e.jsxs("form",{onSubmit:d,className:"space-y-4",children:[e.jsxs(ya,{defaultValue:"basic",className:"w-full",children:[e.jsxs(va,{className:"grid w-full grid-cols-4",children:[e.jsx(is,{value:"basic",children:"Basic Info"}),e.jsx(is,{value:"production",children:"Production"}),e.jsx(is,{value:"social",children:"Social & Web"}),e.jsx(is,{value:"personal",children:"Personal"})]}),e.jsxs(cs,{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(re,{children:"First Name *"}),e.jsx(be,{required:!0,value:l.first_name,onChange:c("first_name")})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Last Name"}),e.jsx(be,{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(re,{children:"Email"}),e.jsx(be,{type:"email",value:l.email,onChange:c("email")})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Phone"}),e.jsx(be,{value:l.phone,onChange:c("phone")})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Current Brokerage"}),e.jsx(be,{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(re,{children:"License #"}),e.jsx(be,{value:l.license_number,onChange:c("license_number")})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Experience (years)"}),e.jsx(be,{type:"number",min:"0",value:l.experience_years,onChange:c("experience_years")})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Address"}),e.jsx(be,{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(re,{children:"City"}),e.jsx(be,{value:l.city,onChange:c("city")})]}),e.jsxs("div",{children:[e.jsx(re,{children:"State"}),e.jsx(be,{value:l.state,onChange:c("state")})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Zip"}),e.jsx(be,{value:l.zip_code,onChange:c("zip_code")})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Pipeline Stage"}),e.jsxs(bs,{value:l.stage_id,onValueChange:u=>o(h=>({...h,stage_id:u})),children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsx(vs,{children:n.map(u=>e.jsx(We,{value:u.id,children:u.name},u.id))})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Referred By"}),e.jsx(be,{placeholder:"Who referred this prospect?",value:l.referred_by,onChange:c("referred_by")})]})]}),e.jsxs(cs,{value:"production",className:"space-y-4 mt-4",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Annual Production Volume"}),e.jsx(be,{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(re,{children:"Last Year Volume"}),e.jsx(be,{placeholder:"e.g. $8.2M",value:l.last_year_volume,onChange:c("last_year_volume")})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Last Year Transactions"}),e.jsx(be,{type:"number",min:"0",placeholder:"e.g. 24",value:l.last_year_transactions,onChange:c("last_year_transactions")})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Avg Sale Price"}),e.jsx(be,{placeholder:"e.g. $350K",value:l.avg_sale_price,onChange:c("avg_sale_price")})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Specialties / Niche"}),e.jsx(be,{placeholder:"e.g. Luxury, First-time buyers, Investment",value:l.specialties,onChange:c("specialties")})]})]}),e.jsxs(cs,{value:"social",className:"space-y-4 mt-4",children:[e.jsxs("div",{children:[e.jsx(re,{children:"LinkedIn URL"}),e.jsx(be,{type:"url",placeholder:"https://linkedin.com/in/...",value:l.linkedin_url,onChange:c("linkedin_url")})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Website URL"}),e.jsx(be,{type:"url",placeholder:"https://...",value:l.website_url,onChange:c("website_url")})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Instagram Handle"}),e.jsx(be,{placeholder:"@handle",value:l.instagram_handle,onChange:c("instagram_handle")})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Facebook URL"}),e.jsx(be,{type:"url",placeholder:"https://facebook.com/...",value:l.facebook_url,onChange:c("facebook_url")})]})]}),e.jsxs(cs,{value:"personal",className:"space-y-4 mt-4",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Birthday"}),e.jsx(be,{type:"date",value:l.birthday,onChange:c("birthday")})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Spouse / Partner Name"}),e.jsx(be,{value:l.spouse_name,onChange:c("spouse_name")})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Interests / Hobbies"}),e.jsx(be,{placeholder:"Golf, travel, community events...",value:l.interests,onChange:c("interests")})]})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Notes"}),e.jsx(Ls,{value:l.notes,onChange:c("notes"),rows:3})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx($,{type:"button",variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx($,{type:"submit",disabled:i,children:"Add Prospect"})]})]})]})})}function qTe(){const{user:s}=ks();return pt({queryKey:["recruit-email-senders",s==null?void 0:s.id],enabled:!!s,staleTime:6e4,queryFn:async()=>{const[t,n]=await Promise.all([V.from("user_verified_senders").select("email, display_name, status").eq("user_id",s.id).eq("status","verified").limit(1).maybeSingle(),V.from("gmail_integrations").select("gmail_email, is_active").eq("user_id",s.id).eq("is_active",!0).maybeSingle()]);return{massEmail:t.data?{email:t.data.email,displayName:t.data.display_name}:null,gmail:n.data?{email:n.data.gmail_email}:null}}})}function vQe({value:s,onChange:t}){const{data:n,isLoading:r}=qTe();return e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Send from"}),e.jsxs(bs,{value:s,onValueChange:a=>t(a),disabled:r,children:[e.jsx(ys,{className:"mt-1",children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"default",children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(Gi,{className:"h-3.5 w-3.5"})," Brokerage default sender"]})}),e.jsx(We,{value:"mass_email",disabled:!(n!=null&&n.massEmail),children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(HT,{className:"h-3.5 w-3.5"}),"Mass Email",n!=null&&n.massEmail?` (${n.massEmail.email})`:" — not configured"]})}),e.jsx(We,{value:"gmail",disabled:!(n!=null&&n.gmail),children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(pn,{className:"h-3.5 w-3.5"}),"Gmail",n!=null&&n.gmail?` (${n.gmail.email})`:" — not connected"]})})]})]}),e.jsx("p",{className:"text-[11px] text-muted-foreground mt-1",children:"Mass Email and Gmail use your own verified sender. Configure them under Integrations."})]})}function jVt({open:s,onOpenChange:t,recruitVideoId:n,brokerageId:r,prospectName:a,prospectEmail:i,videoTitle:l,defaultMessage:o}){const c=(a||"").split(" ")[0]||"there",[d,u]=k.useState(""),[h,m]=k.useState(""),[p,g]=k.useState("default"),[x,y]=k.useState(!1),v=ls(),{data:_}=qTe();k.useEffect(()=>{s&&(u(`${c}, I made you a quick video 🎥`),m(o||""),g(_!=null&&_.massEmail?"mass_email":_!=null&&_.gmail?"gmail":"default"))},[s,c,o,_==null?void 0:_.massEmail,_==null?void 0:_.gmail]);const j=async()=>{var C,A;if(!i){ae.error("This prospect has no email address on file.");return}y(!0);try{const{data:M,error:I}=await V.functions.invoke("send-recruit-video-email",{body:{recruit_video_ids:[n],brokerage_id:r,subject_override:d.trim()||void 0,message_override:h.trim()||void 0,send_via:p}});if(I)throw I;if(((M==null?void 0:M.sent)??0)>0)ae.success(`Email sent to ${i}`),v.invalidateQueries({queryKey:["recruit-videos"]}),v.invalidateQueries({queryKey:["recruit-videos-prospect"]}),t(!1);else{const R=((A=(C=M==null?void 0:M.results)==null?void 0:C[0])==null?void 0:A.error)||"Failed to send";ae.error(R)}}catch(M){ae.error((M==null?void 0:M.message)||"Failed to send email")}finally{y(!1)}};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"max-w-lg",children:[e.jsx(Vs,{children:e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(pn,{className:"h-5 w-5"})," Email video to ",a]})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"To"}),e.jsx(be,{value:i||"— no email on file —",disabled:!0,className:"mt-1"})]}),e.jsx(vQe,{value:p,onChange:g}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Subject"}),e.jsx(be,{value:d,onChange:C=>u(C.target.value),className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Personal message (optional)"}),e.jsx(Ls,{value:h,onChange:C=>m(C.target.value),rows:5,placeholder:`Hi ${c}, wanted to share a quick video...`,className:"mt-1"})]}),l&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Video: ",e.jsx("span",{className:"font-medium",children:l})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"ghost",onClick:()=>t(!1),disabled:x,children:"Cancel"}),e.jsxs($,{onClick:j,disabled:x||!i,children:[x?e.jsx(Jt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Wr,{className:"h-4 w-4 mr-2"}),"Send Email"]})]})]})})}function v5(s){return s?s.share_token?`https://video.relevelup.com/thumb/${s.share_token}`:s.thumbnail_url||s.preview_url||null:null}const eqe=[{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 rOn(s){return pt({queryKey:["recruit-videos",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await V.from("recruit_videos").select(` *, prospect:recruit_prospects(id, first_name, last_name, email, phone, current_brokerage), video:agent_videos(id, title, thumbnail_url, playback_url, preview_url, duration_seconds, status, share_token) `).eq("brokerage_id",s).order("created_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function aOn(s){return pt({queryKey:["recruit-videos-prospect",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await V.from("recruit_videos").select(` *, video:agent_videos(id, title, thumbnail_url, playback_url, preview_url, duration_seconds, status, share_token) `).eq("prospect_id",s).order("created_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function NVt(){const s=ls(),{toast:t}=Fi();return Nt({mutationFn:async n=>{const{data:{user:r}}=await V.auth.getUser();if(!r)throw new Error("Not authenticated");const{data:a,error:i}=await V.from("recruit_videos").insert({prospect_id:n.prospect_id,video_id:n.video_id,brokerage_id:n.brokerage_id,message:n.message||null,created_by:r.id}).select("*, prospect:recruit_prospects(id, first_name, last_name, email, phone, current_brokerage), video:agent_videos(id, title, thumbnail_url, playback_url, preview_url, duration_seconds, status, share_token)").single();if(i)throw i;return a},onSuccess:n=>{s.invalidateQueries({queryKey:["recruit-videos"]}),s.invalidateQueries({queryKey:["recruit-videos-prospect",n.prospect_id]}),t({title:"Video linked to prospect"})},onError:n=>t({title:"Error",description:n.message,variant:"destructive"})})}function kVt(){const s=ls();return Nt({mutationFn:async({id:t,sent_via:n})=>{const{error:r}=await V.from("recruit_videos").update({sent_at:new Date().toISOString(),sent_via:n,updated_at:new Date().toISOString()}).eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["recruit-videos"]})}})}function SVt(s){return pt({queryKey:["recruit-video-scripts",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await V.from("recruit_video_scripts").select("*").or(`brokerage_id.eq.${s},is_global.eq.true`).order("created_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function iOn(){const s=ls(),{toast:t}=Fi();return Nt({mutationFn:async n=>{const{data:{user:r}}=await V.auth.getUser();if(!r)throw new Error("Not authenticated");const{data:a,error:i}=await V.from("recruit_video_scripts").insert({...n,created_by:r.id}).select().single();if(i)throw i;return a},onSuccess:()=>{s.invalidateQueries({queryKey:["recruit-video-scripts"]}),t({title:"Script saved"})},onError:n=>t({title:"Error",description:n.message,variant:"destructive"})})}function oOn(){const s=ls();return Nt({mutationFn:async t=>{const{error:n}=await V.from("recruit_video_scripts").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["recruit-video-scripts"]})}})}function lOn({prospectId:s,prospectName:t,prospectEmail:n,brokerageId:r}){var Y;const{data:a=[],isLoading:i}=aOn(s),{data:l=[]}=SVt(r),o=NVt(),c=o4();kVt();const[d,u]=k.useState("idle"),[h,m]=k.useState(0),[p,g]=k.useState(0),[x,y]=k.useState(""),[v,_]=k.useState(""),[j,C]=k.useState(!1),[A,M]=k.useState(null),[I,P]=k.useState(null),[R,O]=k.useState(null),B=((Y=l.find(se=>se.id===x))==null?void 0:Y.script_text)||"",U=()=>{u("idle"),m(0),g(0),y(""),_("")},G=k.useCallback(async(se,ee)=>{u("uploading");try{const oe=`Recruiting: ${t}`,{videoId:me,libraryId:Q}=await v6(oe),{uploadUrl:te,apiKey:le}=await b6(me),fe=new XMLHttpRequest;fe.upload.onprogress=Be=>{Be.lengthComputable&&m(Be.loaded/Be.total*100)},await new Promise((Be,je)=>{fe.onload=()=>fe.status>=200&&fe.status<300?Be():je(new Error("Upload failed")),fe.onerror=()=>je(new Error("Upload failed")),fe.open("PUT",te),fe.setRequestHeader("AccessKey",le),fe.send(se)}),u("processing");let _e=0;const ve=Date.now(),he=9e4,Se=`https://iframe.mediadelivery.net/embed/${Q}/${me}`;for(;_e<4&&(await new Promise(je=>setTimeout(je,3e3)),!(Date.now()-ve>he));){const Be=await D2(me);if(_e=Be.status,g(Be.encodeProgress||0),_e===5||_e===6)throw new Error("Video processing failed")}const Te=await D2(me),Ie=(Te.storageSize||se.size)/(1024*1024),Ue=await c.mutateAsync({bunny_video_id:me,playback_url:Te.directPlayUrl||Se,thumbnail_url:Te.thumbnailUrl,preview_url:Te.previewUrl||null,duration_seconds:Te.length||ee,file_size_mb:Ie,title:oe,status:_e>=4?"ready":"processing",touch_type:"recruiting"});await o.mutateAsync({prospect_id:s,video_id:Ue.id,brokerage_id:r,message:v||void 0}),u("done"),ae.success("Video recorded and linked to prospect!"),setTimeout(()=>{C(!1),U()},1500)}catch(oe){ae.error(oe.message||"Failed to upload video"),u("record")}},[s,t,r,v,c,o]),H=se=>{se&&(navigator.clipboard.writeText(`${window.location.origin}/recruit-video/${se}`),ae.success("Share link copied"))};return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("h3",{className:"font-semibold text-sm flex items-center gap-1.5",children:[e.jsx(ia,{className:"h-4 w-4"})," Video Outreach"]}),e.jsxs(zs,{open:j,onOpenChange:se=>{!se&&(d==="uploading"||d==="processing")||(C(se),se||U())},children:[e.jsx(yl,{asChild:!0,children:e.jsxs($,{size:"sm",variant:"outline",onClick:()=>u("script"),children:[e.jsx(nn,{className:"h-3.5 w-3.5 mr-1"})," Record Video"]})}),e.jsxs(Rs,{className:"max-w-2xl",children:[e.jsx(Vs,{children:e.jsxs($s,{children:["Record Video for ",t]})}),d==="script"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Choose a Script (optional)"}),e.jsxs(bs,{value:x,onValueChange:y,children:[e.jsx(ys,{className:"mt-1",children:e.jsx(_s,{placeholder:"No script — speak freely"})}),e.jsxs(vs,{children:[e.jsx(We,{value:"none",children:"No script"}),l.map(se=>{var ee;return e.jsx(We,{value:se.id,children:e.jsxs("span",{className:"flex items-center gap-2",children:[se.title,e.jsx(qe,{variant:"outline",className:"text-[9px] ml-1",children:(ee=eqe.find(oe=>oe.value===se.category))==null?void 0:ee.label})]})},se.id)})]})]}),B&&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:B})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Personal Message (shown on landing page)"}),e.jsx(Ls,{value:v,onChange:se=>_(se.target.value),placeholder:`Hi ${t.split(" ")[0]}, I'd love to chat about what we're building here...`,rows:3,className:"mt-1"})]}),e.jsxs($,{onClick:()=>u("record"),className:"w-full",children:[e.jsx(ia,{className:"h-4 w-4 mr-2"})," Start Recording"]})]}),d==="record"&&e.jsx(w6,{maxDurationSeconds:600,onRecordingComplete:G,teleprompterContent:B||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(ho,{value:h,className:"mx-auto max-w-sm"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[Math.round(h),"%"]})]}),d==="processing"&&e.jsxs("div",{className:"py-8 space-y-4 text-center",children:[e.jsx("p",{className:"font-medium",children:"Processing video…"}),e.jsx(ho,{value:p,className:"mx-auto max-w-sm"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[Math.round(p),"%"]})]}),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(pu,{className:"h-6 w-6 text-emerald-600"})}),e.jsx("p",{className:"font-medium text-emerald-600",children:"Video ready!"})]})]})]})]}),i?e.jsx("div",{className:"text-center py-4",children:e.jsx("div",{className:"h-5 w-5 animate-spin rounded-full border-2 border-primary border-t-transparent mx-auto"})}):a.length===0?e.jsx("p",{className:"text-xs text-muted-foreground text-center py-3",children:"No videos sent yet"}):e.jsx("div",{className:"space-y-2",children:a.map(se=>{var ee;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:v5(se.video)?e.jsx("img",{src:v5(se.video),alt:"",className:"h-full w-full object-cover",referrerPolicy:"no-referrer"}):e.jsx("div",{className:"h-full w-full flex items-center justify-center",children:e.jsx(ia,{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:((ee=se.video)==null?void 0:ee.title)||"Untitled"}),e.jsxs("div",{className:"flex items-center gap-2 mt-0.5",children:[se.view_count>0?e.jsxs(qe,{variant:"secondary",className:"text-[9px] h-4",children:[e.jsx(ba,{className:"h-2.5 w-2.5 mr-0.5"}),se.view_count]}):se.sent_at?e.jsxs(qe,{variant:"outline",className:"text-[9px] h-4",children:[e.jsx(Wr,{className:"h-2.5 w-2.5 mr-0.5"}),"Sent"]}):e.jsxs(qe,{variant:"outline",className:"text-[9px] h-4",children:[e.jsx(sa,{className:"h-2.5 w-2.5 mr-0.5"}),"Draft"]}),e.jsx("span",{className:"text-[10px] text-muted-foreground",children:Ys(new Date(se.created_at),"MMM d")})]})]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx($,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>H(se.share_token),title:"Copy link",children:e.jsx(Da,{className:"h-3 w-3"})}),e.jsxs($,{variant:se.sent_at?"ghost":"default",size:"sm",className:"h-7 gap-1",disabled:!n,onClick:()=>{var oe;M(se.id),P(((oe=se.video)==null?void 0:oe.title)||null),O(se.message||null)},title:n?"Email video to prospect":"No email on file",children:[e.jsx(pn,{className:"h-3 w-3"}),e.jsx("span",{className:"text-[10px]",children:se.sent_at?"Resend":"Email"})]})]})]},se.id)})}),A&&e.jsx(jVt,{open:!!A,onOpenChange:se=>{se||M(null)},recruitVideoId:A,brokerageId:r,prospectName:t,prospectEmail:n,videoTitle:I,defaultMessage:R})]})}function cOn({brokerageId:s,onSelect:t}){const{data:n=[],isLoading:r}=pt({queryKey:["recruit-email-templates",s??"global-only"],queryFn:async()=>{let i=V.from("recruit_email_templates").select("id,brokerage_id,category,title,subject,body,sort_order").eq("is_active",!0).order("sort_order");s?i=i.or(`brokerage_id.is.null,brokerage_id.eq.${s}`):i=i.is("brokerage_id",null);const{data:l,error:o}=await i;if(o)throw o;return l}}),a=n.reduce((i,l)=>{var o;return(i[o=l.category]||(i[o]=[])).push(l),i},{});return e.jsxs(Au,{children:[e.jsx(Eu,{asChild:!0,children:e.jsxs($,{variant:"outline",size:"sm",className:"gap-2",type:"button",children:[e.jsx(ea,{className:"h-4 w-4"}),"Use Template",e.jsx(Go,{className:"h-3.5 w-3.5 opacity-60"})]})}),e.jsx(gu,{align:"end",className:"w-80 max-h-[420px] overflow-y-auto",children:r?e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(Jt,{className:"h-4 w-4 animate-spin text-muted-foreground"})}):n.length===0?e.jsx("div",{className:"px-3 py-4 text-xs text-muted-foreground text-center",children:"No templates available."}):Object.entries(a).map(([i,l],o)=>e.jsxs("div",{children:[o>0&&e.jsx(j0,{}),e.jsx(TO,{className:"text-[11px] uppercase tracking-wide text-muted-foreground",children:i}),l.map(c=>e.jsxs(Pa,{onClick:()=>t(c),className:"flex flex-col items-start gap-0.5 py-2",children:[e.jsxs("div",{className:"flex w-full items-center justify-between gap-2",children:[e.jsx("span",{className:"text-sm font-medium truncate",children:c.title}),c.brokerage_id===null&&e.jsx(qe,{variant:"secondary",className:"text-[9px] shrink-0",children:"Built-in"})]}),e.jsx("span",{className:"text-xs text-muted-foreground line-clamp-1",children:c.subject})]},c.id))]},i))})]})}function dOn({open:s,onOpenChange:t,prospectId:n,brokerageId:r,prospectName:a,prospectEmail:i}){const{user:l}=ks(),o=(a||"").split(" ")[0]||"there",[c,d]=k.useState(""),[u,h]=k.useState(""),[m,p]=k.useState("default"),[g,x]=k.useState(!1),[y,v]=k.useState(null),[_,j]=k.useState(!1),C=ls(),{data:A}=qTe();k.useEffect(()=>{if(s){d(`Hi ${o}`),h("");const B=A!=null&&A.massEmail?"mass_email":A!=null&&A.gmail?"gmail":"default";p(B),v(null),j(!1)}},[s,o,A==null?void 0:A.massEmail,A==null?void 0:A.gmail]);const{data:M=[],isLoading:I}=pt({queryKey:["prospect-email-video-library",l==null?void 0:l.id],queryFn:async()=>{const{data:B,error:U}=await V.from("agent_videos").select("id, title, thumbnail_url, duration_seconds, touch_type, created_at, share_token").eq("owner_user_id",l.id).eq("status","ready").eq("is_deleted",!1).order("created_at",{ascending:!1}).limit(50);if(U)throw U;return B??[]},enabled:s&&!!(l!=null&&l.id)}),P=M.find(B=>B.id===y)||null,R=async()=>{var B,U;if(!i){ae.error("This prospect has no email address on file.");return}if(!c.trim()||!u.trim()){ae.error("Subject and message are required.");return}x(!0);try{if(y){const{data:G}=await V.from("recruit_videos").select("id").eq("prospect_id",n).eq("video_id",y).maybeSingle();let H=G==null?void 0:G.id;if(!H){const{data:oe,error:me}=await V.from("recruit_videos").insert({prospect_id:n,video_id:y,brokerage_id:r,message:u.trim(),created_by:l.id}).select("id").single();if(me)throw me;H=oe.id}const{data:Y,error:se}=await V.functions.invoke("send-recruit-video-email",{body:{recruit_video_ids:[H],brokerage_id:r,subject_override:c.trim(),message_override:u.trim(),send_via:m}});if(se)throw se;if(((Y==null?void 0:Y.sent)??0)>0)ae.success(`Email sent to ${i}`),C.invalidateQueries({queryKey:["recruit-videos"]}),C.invalidateQueries({queryKey:["recruit-videos-prospect",n]}),C.invalidateQueries({queryKey:["recruit-activities",n]}),C.invalidateQueries({queryKey:["recruit-sent-emails"]}),t(!1);else{const oe=((U=(B=Y==null?void 0:Y.results)==null?void 0:B[0])==null?void 0:U.error)||"Failed to send";ae.error(oe)}}else{const{data:G,error:H}=await V.functions.invoke("send-recruit-prospect-email",{body:{prospect_id:n,brokerage_id:r,subject:c.trim(),message:u.trim(),send_via:m}});if(H)throw H;G!=null&&G.success?(ae.success(`Email sent to ${i}`),C.invalidateQueries({queryKey:["recruit-activities",n]}),C.invalidateQueries({queryKey:["recruit-sent-emails"]}),t(!1)):ae.error((G==null?void 0:G.error)||"Failed to send")}}catch(G){ae.error((G==null?void 0:G.message)||"Failed to send email")}finally{x(!1)}},O=B=>{const U=G=>G.replace(/\[First Name\]/gi,o);d(U(B.subject)),h(U(B.body)),ae.success(`Loaded "${B.title}"`)};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(Vs,{children:e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(pn,{className:"h-5 w-5"})," Email ",a]})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"To"}),e.jsx(be,{value:i||"— no email on file —",disabled:!0,className:"mt-1"})]}),e.jsx(vQe,{value:m,onChange:p}),e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx(re,{className:"text-xs",children:"Subject"}),e.jsx(cOn,{brokerageId:r,onSelect:O})]}),e.jsx(be,{value:c,onChange:B=>d(B.target.value)}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Message"}),e.jsx(Ls,{value:u,onChange:B=>h(B.target.value),rows:8,placeholder:`Hi ${o}, wanted to reach out…`,className:"mt-1"})]}),e.jsxs("div",{className:"rounded-md border p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(re,{className:"text-xs flex items-center gap-1.5",children:[e.jsx(ia,{className:"h-3.5 w-3.5"})," Include a video"]}),P?e.jsxs($,{type:"button",variant:"ghost",size:"sm",className:"h-7 text-xs",onClick:()=>{v(null),j(!1)},children:[e.jsx(mr,{className:"h-3 w-3 mr-1"})," Remove"]}):e.jsx($,{type:"button",variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>j(B=>!B),children:_?"Hide library":"Pick from library"})]}),P&&e.jsxs("div",{className:"flex items-center gap-3 p-2 rounded bg-muted/40",children:[e.jsx("div",{className:"h-10 w-16 rounded bg-muted overflow-hidden flex-shrink-0",children:v5(P)?e.jsx("img",{src:v5(P),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(ia,{className:"h-4 w-4 text-muted-foreground"})})}),e.jsx("p",{className:"text-xs font-medium truncate flex-1",children:P.title||"Untitled video"})]}),!P&&_&&e.jsx("div",{className:"max-h-56 overflow-y-auto space-y-1 -mx-1 px-1",children:I?e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(Jt,{className:"h-4 w-4 animate-spin text-muted-foreground"})}):M.length===0?e.jsx("p",{className:"text-xs text-muted-foreground text-center py-3",children:"No videos in your library yet. Record one from a prospect to get started."}):M.map(B=>e.jsxs("button",{type:"button",onClick:()=>{v(B.id),j(!1)},className:"w-full flex items-center gap-3 p-2 rounded hover:bg-accent text-left transition-colors",children:[e.jsx("div",{className:"h-10 w-16 rounded bg-muted overflow-hidden flex-shrink-0",children:v5(B)?e.jsx("img",{src:v5(B),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(ia,{className:"h-4 w-4 text-muted-foreground"})})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-xs font-medium truncate",children:B.title||"Untitled video"}),B.duration_seconds&&e.jsxs("p",{className:"text-[10px] text-muted-foreground",children:[Math.floor(B.duration_seconds/60),":",String(Math.floor(B.duration_seconds%60)).padStart(2,"0")]})]})]},B.id))}),P&&e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"A tracked share link with thumbnail will be added to the email automatically."})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"ghost",onClick:()=>t(!1),disabled:g,children:"Cancel"}),e.jsxs($,{onClick:R,disabled:g||!i,children:[g?e.jsx(Jt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Wr,{className:"h-4 w-4 mr-2"}),"Send Email"]})]})]})})}function uOn(s){return pt({queryKey:["recruit-campaign-sends",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await V.from("recruit_campaign_sends").select("id, prospect_id, subject, email_number, status, sent_at, opened_at, clicked_at, error_message, created_at").eq("prospect_id",s).neq("status","failed").order("created_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}const gbt=[{value:"call",label:"Phone Call",icon:ka},{value:"email",label:"Email",icon:pn},{value:"text",label:"Text Message",icon:bo},{value:"meeting",label:"Meeting",icon:ha},{value:"note",label:"Note",icon:ea},{value:"campaign_email",label:"Campaign Email",icon:Wr}];function pw({label:s,value:t,icon:n}){return t?e.jsxs("div",{children:[e.jsxs("span",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[n&&e.jsx(n,{className:"h-3 w-3"})," ",s]}),e.jsx("p",{className:"font-medium text-sm",children:t})]}):null}function Zae({label:s,url:t,icon:n}){return t?e.jsxs("a",{href:t.startsWith("http")?t:`https://${t}`,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-2 text-sm text-primary hover:underline",children:[e.jsx(n,{className:"h-3.5 w-3.5"})," ",s," ",e.jsx(Ir,{className:"h-3 w-3 opacity-50"})]}):null}function mf({label:s,value:t,onChange:n,type:r="text",placeholder:a}){return e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:s}),e.jsx(be,{type:r,value:t,onChange:i=>n(i.target.value),placeholder:a,className:"mt-1 h-8 text-sm"})]})}function CVt({prospect:s,stages:t,brokerageId:n,open:r,onOpenChange:a,onUpdate:i,onDelete:l}){const{activities:o,addActivity:c}=nOn((s==null?void 0:s.id)||null),{data:d=[]}=uOn((s==null?void 0:s.id)||null),[u,h]=k.useState({type:"note",title:"",description:""}),[m,p]=k.useState(!1),[g,x]=k.useState(!1),[y,v]=k.useState({}),[_,j]=k.useState(!1);if(!s)return null;const C=()=>{var H,Y;v({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:((H=s.experience_years)==null?void 0:H.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:((Y=s.last_year_transactions)==null?void 0:Y.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||""}),x(!0)},A=()=>{const H={id:s.id};for(const[Y,se]of Object.entries(y))Y==="experience_years"||Y==="last_year_transactions"?H[Y]=se?parseInt(se):null:H[Y]=se||null;i(H),x(!1)},M=()=>x(!1),I=H=>Y=>v(se=>({...se,[H]:Y})),P=()=>{u.title.trim()&&(c.mutate({prospect_id:s.id,activity_type:u.type,title:u.title,description:u.description||null}),h({type:"note",title:"",description:""}),p(!1))},R=t.find(H=>H.id===s.stage_id),O=s.address||s.city||s.state,B=s.last_year_volume||s.last_year_transactions||s.avg_sale_price||s.specialties||s.annual_production,U=s.linkedin_url||s.website_url||s.instagram_handle||s.facebook_url,G=s.birthday||s.spouse_name||s.interests||s.referred_by;return e.jsxs(D_,{open:r,onOpenChange:H=>{H||x(!1),a(H)},children:[e.jsx(Mb,{className:"w-full sm:max-w-lg p-0",children:e.jsx(Eo,{className:"h-full",children:e.jsxs("div",{className:"p-6 space-y-5",children:[e.jsx(xj,{children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{children:[e.jsxs(yj,{className:"text-xl",children:[s.first_name," ",s.last_name]}),R&&e.jsx(qe,{variant:"outline",style:{borderColor:R.color,color:R.color},className:"mt-1",children:R.name})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[g?e.jsxs(e.Fragment,{children:[e.jsx($,{variant:"ghost",size:"icon",onClick:M,children:e.jsx(mr,{className:"h-4 w-4"})}),e.jsx($,{variant:"default",size:"icon",onClick:A,children:e.jsx(Ml,{className:"h-4 w-4"})})]}):e.jsx($,{variant:"ghost",size:"icon",onClick:C,title:"Edit prospect",children:e.jsx(ui,{className:"h-4 w-4"})}),e.jsxs(oc,{children:[e.jsx(_g,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(Un,{className:"h-4 w-4"})})}),e.jsxs(Ql,{children:[e.jsxs(Jl,{children:[e.jsx(tc,{children:"Delete prospect?"}),e.jsx(sc,{children:"This will permanently remove this prospect and all their activity history."})]}),e.jsxs(ec,{children:[e.jsx(nc,{children:"Cancel"}),e.jsx(Vl,{onClick:()=>{l(s.id),a(!1)},children:"Delete"})]})]})]})]})]})}),!g&&e.jsxs("div",{className:"space-y-2 text-sm",children:[s.email&&e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground min-w-0",children:[e.jsx(pn,{className:"h-3.5 w-3.5 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:s.email})]}),e.jsxs($,{size:"sm",variant:"outline",className:"h-7 gap-1.5 flex-shrink-0",onClick:()=>j(!0),children:[e.jsx(pn,{className:"h-3 w-3"})," Email"]})]}),s.phone&&e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(ka,{className:"h-3.5 w-3.5"})," ",s.phone]}),O&&e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(Si,{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(re,{className:"text-xs text-muted-foreground",children:"Move to Stage"}),e.jsxs(bs,{value:s.stage_id||"",onValueChange:H=>i({id:s.id,stage_id:H}),children:[e.jsx(ys,{className:"mt-1",children:e.jsx(_s,{})}),e.jsx(vs,{children:t.map(H=>e.jsx(We,{value:H.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:H.color}}),H.name]})},H.id))})]})]}),e.jsxs(ya,{defaultValue:"details",className:"w-full",children:[e.jsxs(va,{className:"grid w-full grid-cols-4 h-8 text-xs",children:[e.jsx(is,{value:"details",className:"text-xs",children:"Details"}),e.jsx(is,{value:"production",className:"text-xs",children:"Production"}),e.jsx(is,{value:"social",className:"text-xs",children:"Social"}),e.jsx(is,{value:"personal",className:"text-xs",children:"Personal"})]}),g?e.jsxs(e.Fragment,{children:[e.jsxs(cs,{value:"details",className:"mt-3 space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(mf,{label:"First Name",value:y.first_name,onChange:I("first_name")}),e.jsx(mf,{label:"Last Name",value:y.last_name,onChange:I("last_name")})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(mf,{label:"Email",value:y.email,onChange:I("email"),type:"email"}),e.jsx(mf,{label:"Phone",value:y.phone,onChange:I("phone")})]}),e.jsx(mf,{label:"Current Brokerage",value:y.current_brokerage,onChange:I("current_brokerage")}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(mf,{label:"License #",value:y.license_number,onChange:I("license_number")}),e.jsx(mf,{label:"Experience (years)",value:y.experience_years,onChange:I("experience_years"),type:"number"})]}),e.jsx(mf,{label:"Address",value:y.address,onChange:I("address"),placeholder:"Street address"}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsx(mf,{label:"City",value:y.city,onChange:I("city")}),e.jsx(mf,{label:"State",value:y.state,onChange:I("state")}),e.jsx(mf,{label:"Zip",value:y.zip_code,onChange:I("zip_code")})]}),e.jsx(mf,{label:"Source",value:y.source,onChange:I("source")}),e.jsx(mf,{label:"Referred By",value:y.referred_by,onChange:I("referred_by")}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Notes"}),e.jsx(Ls,{value:y.notes,onChange:H=>v(Y=>({...Y,notes:H.target.value})),rows:3,className:"mt-1 text-sm"})]})]}),e.jsxs(cs,{value:"production",className:"mt-3 space-y-3",children:[e.jsx(mf,{label:"Annual Production",value:y.annual_production,onChange:I("annual_production"),placeholder:"e.g. $5M"}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(mf,{label:"Last Year Volume",value:y.last_year_volume,onChange:I("last_year_volume"),placeholder:"e.g. $8.2M"}),e.jsx(mf,{label:"Last Year Transactions",value:y.last_year_transactions,onChange:I("last_year_transactions"),type:"number",placeholder:"e.g. 24"})]}),e.jsx(mf,{label:"Avg Sale Price",value:y.avg_sale_price,onChange:I("avg_sale_price"),placeholder:"e.g. $350K"}),e.jsx(mf,{label:"Specialties / Niche",value:y.specialties,onChange:I("specialties"),placeholder:"e.g. Luxury, Investment"})]}),e.jsxs(cs,{value:"social",className:"mt-3 space-y-3",children:[e.jsx(mf,{label:"LinkedIn URL",value:y.linkedin_url,onChange:I("linkedin_url"),type:"url",placeholder:"https://linkedin.com/in/..."}),e.jsx(mf,{label:"Website URL",value:y.website_url,onChange:I("website_url"),type:"url",placeholder:"https://..."}),e.jsx(mf,{label:"Instagram Handle",value:y.instagram_handle,onChange:I("instagram_handle"),placeholder:"@handle"}),e.jsx(mf,{label:"Facebook URL",value:y.facebook_url,onChange:I("facebook_url"),type:"url",placeholder:"https://facebook.com/..."})]}),e.jsxs(cs,{value:"personal",className:"mt-3 space-y-3",children:[e.jsx(mf,{label:"Birthday",value:y.birthday,onChange:I("birthday"),type:"date"}),e.jsx(mf,{label:"Spouse / Partner",value:y.spouse_name,onChange:I("spouse_name")}),e.jsx(mf,{label:"Interests / Hobbies",value:y.interests,onChange:I("interests"),placeholder:"Golf, travel, community events..."})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs(cs,{value:"details",className:"mt-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(pw,{label:"Current Brokerage",value:s.current_brokerage}),e.jsx(pw,{label:"License #",value:s.license_number}),e.jsx(pw,{label:"Experience",value:s.experience_years!=null?`${s.experience_years} years`:null}),e.jsx(pw,{label:"Referred By",value:s.referred_by}),e.jsx(pw,{label:"Source",value:s.source})]}),s.notes&&e.jsxs("div",{className:"mt-3",children:[e.jsx(re,{className:"text-xs text-muted-foreground",children:"Notes"}),e.jsx("p",{className:"text-sm mt-1 whitespace-pre-wrap",children:s.notes})]})]}),e.jsx(cs,{value:"production",className:"mt-3",children:B?e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(pw,{label:"Annual Production",value:s.annual_production}),e.jsx(pw,{label:"Last Year Volume",value:s.last_year_volume}),e.jsx(pw,{label:"Last Year Transactions",value:s.last_year_transactions}),e.jsx(pw,{label:"Avg Sale Price",value:s.avg_sale_price}),e.jsx(pw,{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(cs,{value:"social",className:"mt-3",children:U?e.jsxs("div",{className:"space-y-2",children:[e.jsx(Zae,{label:"LinkedIn",url:s.linkedin_url,icon:dv}),e.jsx(Zae,{label:"Website",url:s.website_url,icon:kc}),s.instagram_handle&&e.jsx(Zae,{label:s.instagram_handle,url:`https://instagram.com/${s.instagram_handle.replace("@","")}`,icon:Sf}),e.jsx(Zae,{label:"Facebook",url:s.facebook_url,icon:ax})]}):e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No social profiles added yet"})}),e.jsx(cs,{value:"personal",className:"mt-3",children:G?e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(pw,{label:"Birthday",value:s.birthday?Ys(new Date(s.birthday+"T00:00:00"),"MMMM d, yyyy"):null,icon:Zo}),e.jsx(pw,{label:"Spouse / Partner",value:s.spouse_name,icon:Bo}),e.jsx("div",{className:"col-span-2",children:e.jsx(pw,{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(lOn,{prospectId:s.id,prospectName:`${s.first_name} ${s.last_name||""}`,prospectEmail:s.email,brokerageId:n}),e.jsx(Pc,{}),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($,{size:"sm",variant:"outline",onClick:()=>p(!m),children:[e.jsx(nn,{className:"h-3.5 w-3.5 mr-1"})," Log Activity"]})]}),m&&e.jsxs("div",{className:"border rounded-lg p-3 mb-4 space-y-3 bg-muted/30",children:[e.jsxs(bs,{value:u.type,onValueChange:H=>h(Y=>({...Y,type:H})),children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsx(vs,{children:gbt.map(H=>e.jsx(We,{value:H.value,children:H.label},H.value))})]}),e.jsx(be,{placeholder:"Subject / Title",value:u.title,onChange:H=>h(Y=>({...Y,title:H.target.value}))}),e.jsx(Ls,{placeholder:"Details (optional)",value:u.description,onChange:H=>h(Y=>({...Y,description:H.target.value})),rows:2}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx($,{size:"sm",variant:"ghost",onClick:()=>p(!1),children:"Cancel"}),e.jsx($,{size:"sm",onClick:P,disabled:!u.title.trim(),children:"Save"})]})]}),e.jsx("div",{className:"space-y-3",children:(()=>{const H=[...o.map(Y=>({type:"manual",data:Y,date:Y.created_at})),...d.map(Y=>({type:"campaign_email",data:Y,date:Y.sent_at||Y.created_at}))].sort((Y,se)=>new Date(se.date).getTime()-new Date(Y.date).getTime());return H.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No activity logged yet"}):H.map(Y=>{if(Y.type==="manual"){const ee=Y.data,oe=gbt.find(Q=>Q.value===ee.activity_type),me=(oe==null?void 0:oe.icon)||ea;return e.jsxs("div",{className:"flex gap-3 text-sm",children:[e.jsx("div",{className:"mt-0.5",children:e.jsx("div",{className:"h-7 w-7 rounded-full bg-muted flex items-center justify-center",children:e.jsx(me,{className:"h-3.5 w-3.5 text-muted-foreground"})})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium",children:ee.title}),ee.description&&e.jsx("p",{className:"text-muted-foreground text-xs mt-0.5",children:ee.description}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:Ys(new Date(ee.created_at),"MMM d, yyyy h:mm a")})]})]},`activity-${ee.id}`)}const se=Y.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(Wr,{className:"h-3.5 w-3.5 text-primary"})})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("p",{className:"font-medium",children:["Campaign Email #",se.email_number]}),e.jsx("p",{className:"text-muted-foreground text-xs mt-0.5",children:se.subject}),e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 mt-1.5",children:[se.status==="failed"?e.jsx(qe,{variant:"destructive",className:"text-[10px] px-1.5 py-0 h-4",children:"Failed"}):e.jsxs(qe,{variant:"outline",className:"text-[10px] px-1.5 py-0 h-4 border-green-500 text-green-600",children:[e.jsx(Wr,{className:"h-2.5 w-2.5 mr-0.5"})," Sent"]}),se.opened_at?e.jsxs(qe,{variant:"outline",className:"text-[10px] px-1.5 py-0 h-4 border-blue-500 text-blue-600",children:[e.jsx(ba,{className:"h-2.5 w-2.5 mr-0.5"})," Opened ",Ys(new Date(se.opened_at),"MMM d, h:mm a")]}):se.status!=="failed"?e.jsx(qe,{variant:"outline",className:"text-[10px] px-1.5 py-0 h-4 text-muted-foreground",children:"Not opened"}):null,se.clicked_at&&e.jsxs(qe,{variant:"outline",className:"text-[10px] px-1.5 py-0 h-4 border-purple-500 text-purple-600",children:[e.jsx(sv,{className:"h-2.5 w-2.5 mr-0.5"})," Clicked ",Ys(new Date(se.clicked_at),"MMM d, h:mm a")]})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:Ys(new Date(se.sent_at||se.created_at),"MMM d, yyyy h:mm a")})]})]},`send-${se.id}`)})})()})]})]})})}),e.jsx(dOn,{open:_,onOpenChange:j,prospectId:s.id,brokerageId:s.brokerage_id,prospectName:`${s.first_name} ${s.last_name??""}`.trim(),prospectEmail:s.email})]})}const hOn=["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 AVt({open:s,onOpenChange:t,brokerageId:n,stages:r}){var O;const{toast:a}=Fi(),i=ls(),l=k.useRef(null),[o,c]=k.useState([]),[d,u]=k.useState([]),[h,m]=k.useState({}),[p,g]=k.useState(((O=r[0])==null?void 0:O.id)||""),[x,y]=k.useState(!1),[v,_]=k.useState("upload"),[j,C]=k.useState(0),A=()=>{c([]),u([]),m({}),_("upload"),C(0)},M=B=>{var H;const U=(H=B.target.files)==null?void 0:H[0];if(!U)return;const G=new FileReader;G.onload=Y=>{var le;const ee=((le=Y.target)==null?void 0:le.result).split(/\r?\n/).filter(fe=>fe.trim());if(ee.length<2){a({title:"Invalid CSV",description:"File must have a header row and at least one data row",variant:"destructive"});return}const oe=I(ee[0]);u(oe);const me={},Q=new Set;oe.forEach((fe,_e)=>{const ve=fe.toLowerCase().replace(/[^a-z0-9]/g,"");let he=null;/^firstname$/.test(ve)||ve==="first"?he="first_name":/^lastname$/.test(ve)||ve==="last"?he="last_name":/^email$/.test(ve)||ve==="emailaddress"?he="email":/^mobile$|^phone$|^cellphone$|^mobilephone$/.test(ve)?he="phone":/officename|currentbrokerage|brokerage|company/.test(ve)?he="current_brokerage":/membernumber|licensenumber|license/.test(ve)?he="license_number":/experienceyears|yearsexperience/.test(ve)?he="experience_years":/^totalvolume$|annualproduction/.test(ve)?he="annual_production":/^address$/.test(ve)?he="address":/^city$/.test(ve)?he="city":/^state$/.test(ve)?he="state":/^postalcode$|^zip$|^zipcode$/.test(ve)?he="zip_code":/listsidevolume|lastyearvolume/.test(ve)?he="last_year_volume":/^totalcount$|lastyeartransactions/.test(ve)?he="last_year_transactions":/avgsaleprice|averageprice/.test(ve)?he="avg_sale_price":/linkedin/.test(ve)?he="linkedin_url":/website/.test(ve)?he="website_url":/specialt/.test(ve)?he="specialties":/referr/.test(ve)?he="referred_by":/^notes$|^note$/.test(ve)&&(he="notes"),he&&!Q.has(he)&&(me[String(_e)]=he,Q.add(he))}),m(me);const te=ee.slice(1).map(fe=>{const _e=I(fe),ve={};return oe.forEach((he,Se)=>{ve[String(Se)]=_e[Se]||""}),ve});c(te),_("map")},G.readAsText(U)},I=B=>{const U=[];let G="",H=!1;for(const Y of B)Y==='"'?H=!H:Y===","&&!H?(U.push(G.trim()),G=""):G+=Y;return U.push(G.trim()),U},P=async()=>{y(!0);try{const{data:{user:B}}=await V.auth.getUser();if(!B)throw new Error("Not authenticated");const U=o.map(H=>{const Y={brokerage_id:n,created_by:B.id,stage_id:p,source:"csv_import",first_name:"Unknown"},se=Y;return Object.entries(h).forEach(([ee,oe])=>{var Q;const me=(Q=H[ee])==null?void 0:Q.trim();me&&(oe==="experience_years"||oe==="last_year_transactions"?se[oe]=parseInt(me.replace(/[^0-9.-]/g,""))||null:oe==="annual_production"||oe==="last_year_volume"||oe==="avg_sale_price"?se[oe]=me.replace(/[^0-9.$,.-]/g,""):se[oe]=me)}),Y});let G=0;for(let H=0;H{const B=`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`,U=new Blob([B],{type:"text/csv"}),G=URL.createObjectURL(U),H=document.createElement("a");H.href=G,H.download="recruit-prospects-template.csv",H.click(),URL.revokeObjectURL(G)};return e.jsx(zs,{open:s,onOpenChange:B=>{B||A(),t(B)},children:e.jsxs(Rs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Vs,{children:e.jsx($s,{children:"Import Prospects from CSV"})}),v==="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(rk,{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:M}),e.jsxs($,{onClick:()=>{var B;return(B=l.current)==null?void 0:B.click()},children:[e.jsx(gi,{className:"h-4 w-4 mr-2"})," Choose File"]})]}),e.jsx($,{variant:"link",className:"text-xs",onClick:R,children:"Download CSV template"})]}),v==="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(bs,{value:p,onValueChange:g,children:[e.jsx(ys,{className:"w-[180px]",children:e.jsx(_s,{})}),e.jsx(vs,{children:r.map(B=>e.jsx(We,{value:B.id,children:B.name},B.id))})]})]})]}),e.jsx("div",{className:"border rounded-lg overflow-hidden",children:e.jsxs(Qa,{children:[e.jsx(Ja,{children:e.jsxs(vn,{children:[e.jsx(Dt,{className:"w-[140px]",children:"CSV Column"}),e.jsx(Dt,{className:"w-[160px]",children:"Map To"}),e.jsx(Dt,{children:"Preview"})]})}),e.jsx(ei,{children:d.map((B,U)=>{var G;return e.jsxs(vn,{children:[e.jsx(_t,{className:"font-medium text-xs",children:B}),e.jsx(_t,{children:e.jsxs(bs,{value:h[String(U)]||"skip",onValueChange:H=>m(Y=>({...Y,[String(U)]:H==="skip"?"":H})),children:[e.jsx(ys,{className:"h-8 text-xs",children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"skip",children:"— Skip —"}),hOn.map(H=>e.jsx(We,{value:H,children:H.replace(/_/g," ")},H))]})]})}),e.jsx(_t,{className:"text-xs text-muted-foreground truncate max-w-[200px]",children:((G=o[0])==null?void 0:G[String(U)])||"—"})]},U)})})]})}),!Object.values(h).includes("first_name")&&e.jsxs("div",{className:"flex items-center gap-2 text-amber-600 text-sm",children:[e.jsx(Ho,{className:"h-4 w-4"}),' Map at least "first name" to proceed']}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx($,{variant:"outline",onClick:()=>{A()},children:"Back"}),e.jsx($,{onClick:P,disabled:x||!Object.values(h).includes("first_name"),children:x?"Importing...":`Import ${o.length} Prospects`})]})]}),v==="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(ma,{className:"h-6 w-6 text-green-600"})}),e.jsxs("p",{className:"font-semibold",children:[j," prospects imported successfully!"]}),e.jsx($,{onClick:()=>{A(),t(!1)},children:"Close"})]})]})})}function EVt({brokerageId:s}){const{stages:t,prospects:n,isLoading:r,addProspect:a,updateProspect:i,deleteProspect:l}=wte(s),[o,c]=k.useState(!1),[d,u]=k.useState(),[h,m]=k.useState(null),[p,g]=k.useState(!1),[x,y]=k.useState(!1),[v,_]=k.useState(null);if(r)return e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})});const j=R=>n.filter(O=>O.stage_id===R),C=(R,O)=>{_(O),R.dataTransfer.effectAllowed="move"},A=R=>{R.preventDefault(),R.dataTransfer.dropEffect="move"},M=(R,O)=>{R.preventDefault(),v&&(i.mutate({id:v,stage_id:O}),_(null))},I=R=>{u(R),c(!0)},P=R=>{m(R),g(!0)};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{children:e.jsxs("p",{className:"text-sm text-muted-foreground",children:[n.length," prospect",n.length!==1?"s":""]})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs($,{variant:"outline",onClick:()=>y(!0),children:[e.jsx(gi,{className:"h-4 w-4 mr-2"})," Import CSV"]}),e.jsxs($,{onClick:()=>{u(void 0),c(!0)},children:[e.jsx(nn,{className:"h-4 w-4 mr-2"})," Add Prospect"]})]})]}),e.jsxs(Eo,{className:"w-full",children:[e.jsx("div",{className:"flex gap-4 pb-4",style:{minWidth:t.length*300},children:t.map(R=>{const O=j(R.id);return e.jsxs("div",{className:"w-[280px] flex-shrink-0 flex flex-col",onDragOver:A,onDrop:B=>M(B,R.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:R.color}}),e.jsx("h3",{className:"font-semibold text-sm",children:R.name}),e.jsx(qe,{variant:"secondary",className:"text-xs h-5 px-1.5",children:O.length})]}),e.jsx($,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>I(R.id),children:e.jsx(nn,{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:O.map(B=>e.jsx(we,{className:"p-3 cursor-pointer hover:shadow-md transition-shadow border-l-4 group",style:{borderLeftColor:R.color},draggable:!0,onDragStart:U=>C(U,B.id),onClick:()=>P(B),children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Bp,{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(el,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsxs("span",{className:"font-medium text-sm truncate",children:[B.first_name," ",B.last_name]})]}),B.current_brokerage&&e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-muted-foreground",children:[e.jsx(Gi,{className:"h-3 w-3"}),e.jsx("span",{className:"truncate",children:B.current_brokerage})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[B.email&&e.jsx(pn,{className:"h-3 w-3 text-muted-foreground"}),B.phone&&e.jsx(ka,{className:"h-3 w-3 text-muted-foreground"}),B.experience_years!=null&&e.jsxs(qe,{variant:"secondary",className:"text-[10px] h-4 px-1",children:[B.experience_years,"yr"]})]})]})]})},B.id))})]},R.id)})}),e.jsx(Uq,{orientation:"horizontal"})]}),e.jsx(wVt,{open:o,onOpenChange:c,stages:t,defaultStageId:d,onSubmit:R=>a.mutate(R),isSubmitting:a.isPending}),e.jsx(CVt,{prospect:h,stages:t,brokerageId:s,open:p,onOpenChange:g,onUpdate:R=>{i.mutate(R),m(O=>O?{...O,...R}:null)},onDelete:R=>l.mutate(R)}),e.jsx(AVt,{open:x,onOpenChange:y,brokerageId:s,stages:t})]})}function eCe({brokerageId:s}){const{stages:t,prospects:n,isLoading:r,addProspect:a,updateProspect:i,deleteProspect:l}=wte(s),{user:o}=ks(),c=ls(),[d,u]=k.useState(!1),[h,m]=k.useState(null),[p,g]=k.useState(!1),[x,y]=k.useState(!1),[v,_]=k.useState(""),[j,C]=k.useState("all"),[A,M]=k.useState("all"),[I,P]=k.useState("all"),[R,O]=k.useState(null),[B,U]=k.useState("asc"),[G,H]=k.useState(new Set),[Y,se]=k.useState(!1),[ee,oe]=k.useState(""),me=k.useMemo(()=>{const je=new Set;return n.forEach(Ye=>{Ye.current_brokerage&&je.add(Ye.current_brokerage)}),Array.from(je).sort()},[n]),{data:Q=[]}=pt({queryKey:["recruit-campaigns-list",s],queryFn:async()=>{const{data:je,error:Ye}=await V.from("recruit_campaigns").select("id, name, warmth_level").or(`brokerage_id.is.null,brokerage_id.eq.${s}`).order("name");if(Ye)throw Ye;return je}}),{data:te=[]}=pt({queryKey:["recruit-campaign-assignments-lookup",s],queryFn:async()=>{let Ye=[],Ee=0;for(;;){const{data:Re,error:ke}=await V.from("recruit_campaign_assignments").select("prospect_id, campaign_id, status").eq("brokerage_id",s).range(Ee,Ee+1e3-1);if(ke)throw ke;if(Ye=Ye.concat(Re??[]),!Re||Re.length<1e3)break;Ee+=1e3}return Ye}}),le=k.useMemo(()=>{const je=new Map;return te.forEach(Ye=>{je.has(Ye.prospect_id)||je.set(Ye.prospect_id,new Set),je.get(Ye.prospect_id).add(Ye.campaign_id)}),je},[te]),fe=je=>{R===je?U(Ye=>Ye==="asc"?"desc":"asc"):(O(je),U("asc"))},_e=({column:je})=>R!==je?e.jsx(Ix,{className:"h-3.5 w-3.5 ml-1 text-muted-foreground/50"}):B==="asc"?e.jsx(ap,{className:"h-3.5 w-3.5 ml-1 text-primary"}):e.jsx(nx,{className:"h-3.5 w-3.5 ml-1 text-primary"}),ve=je=>t.find(Ye=>Ye.id===je),he=k.useMemo(()=>{let je=n.filter(Ye=>{var Oe,Ge,yt;const Ee=!v||`${Ye.first_name} ${Ye.last_name}`.toLowerCase().includes(v.toLowerCase())||((Oe=Ye.email)==null?void 0:Oe.toLowerCase().includes(v.toLowerCase()))||((Ge=Ye.current_brokerage)==null?void 0:Ge.toLowerCase().includes(v.toLowerCase())),Re=j==="all"||Ye.stage_id===j,ke=A==="all"||Ye.current_brokerage===A;let Fe=!0;return I==="in_campaign"?Fe=le.has(Ye.id):I==="not_in_campaign"?Fe=!le.has(Ye.id):I!=="all"&&(Fe=((yt=le.get(Ye.id))==null?void 0:yt.has(I))??!1),Ee&&Re&&ke&&Fe});return R&&(je=[...je].sort((Ye,Ee)=>{var Oe,Ge;let Re=null,ke=null;switch(R){case"name":Re=`${Ye.first_name} ${Ye.last_name||""}`.toLowerCase(),ke=`${Ee.first_name} ${Ee.last_name||""}`.toLowerCase();break;case"stage":Re=((Oe=ve(Ye.stage_id))==null?void 0:Oe.sort_order)??999,ke=((Ge=ve(Ee.stage_id))==null?void 0:Ge.sort_order)??999;break;case"brokerage":Re=(Ye.current_brokerage||"").toLowerCase(),ke=(Ee.current_brokerage||"").toLowerCase();break;case"experience":Re=Ye.experience_years??-1,ke=Ee.experience_years??-1;break;case"production":Re=(Ye.annual_production||"").toLowerCase(),ke=(Ee.annual_production||"").toLowerCase();break;case"source":Re=(Ye.source||"").toLowerCase(),ke=(Ee.source||"").toLowerCase();break;default:return 0}if(Re===ke)return 0;if(Re==null)return 1;if(ke==null)return-1;const Fe=Re0&&he.every(je=>G.has(je.id)),Te=he.some(je=>G.has(je.id)),Ie=()=>{H(Se?new Set:new Set(he.map(je=>je.id)))},Ue=je=>{H(Ye=>{const Ee=new Set(Ye);return Ee.has(je)?Ee.delete(je):Ee.add(je),Ee})},Be=Nt({mutationFn:async()=>{if(!ee||!(o!=null&&o.id))throw new Error("Select a campaign");const je=new Set(te.filter(Re=>Re.campaign_id===ee).map(Re=>Re.prospect_id)),Ye=Array.from(G).filter(Re=>!je.has(Re)).map(Re=>({prospect_id:Re,campaign_id:ee,brokerage_id:s,assigned_by:o.id,status:"active",current_email_number:0}));if(Ye.length===0)throw new Error("All selected prospects are already in this campaign");const{error:Ee}=await V.from("recruit_campaign_assignments").insert(Ye);if(Ee)throw Ee;return Ye.length},onSuccess:je=>{ae.success(`${je} prospect(s) added to campaign`),se(!1),H(new Set),oe(""),c.invalidateQueries({queryKey:["recruit-campaign-assignments-lookup"]})},onError:je=>ae.error(je.message)});return r?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4 flex-wrap",children:[e.jsxs("div",{className:"relative flex-1 max-w-sm min-w-[200px]",children:[e.jsx(Yr,{className:"absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search prospects...",value:v,onChange:je=>_(je.target.value),className:"pl-8"})]}),e.jsxs("div",{className:"flex gap-2",children:[G.size>0&&e.jsxs($,{variant:"secondary",onClick:()=>se(!0),className:"gap-1.5",children:[e.jsx(Wr,{className:"h-4 w-4"})," Add ",G.size," to Campaign"]}),e.jsxs($,{variant:"outline",onClick:()=>y(!0),children:[e.jsx(gi,{className:"h-4 w-4 mr-2"})," Import CSV"]}),e.jsxs($,{onClick:()=>u(!0),children:[e.jsx(nn,{className:"h-4 w-4 mr-2"})," Add Prospect"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx(v2,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs(bs,{value:j,onValueChange:C,children:[e.jsx(ys,{className:"w-[160px] h-8 text-xs",children:e.jsx(_s,{placeholder:"All stages"})}),e.jsxs(vs,{children:[e.jsx(We,{value:"all",children:"All stages"}),t.map(je=>e.jsx(We,{value:je.id,children:je.name},je.id))]})]}),e.jsxs(bs,{value:A,onValueChange:M,children:[e.jsxs(ys,{className:"w-[200px] h-8 text-xs",children:[e.jsx(Gi,{className:"h-3.5 w-3.5 mr-1.5"}),e.jsx(_s,{placeholder:"All brokerages"})]}),e.jsxs(vs,{children:[e.jsx(We,{value:"all",children:"All brokerages"}),me.map(je=>e.jsx(We,{value:je,children:je},je))]})]}),e.jsxs(bs,{value:I,onValueChange:P,children:[e.jsxs(ys,{className:"w-[200px] h-8 text-xs",children:[e.jsx(pn,{className:"h-3.5 w-3.5 mr-1.5"}),e.jsx(_s,{placeholder:"Campaign status"})]}),e.jsxs(vs,{children:[e.jsx(We,{value:"all",children:"All contacts"}),e.jsx(We,{value:"in_campaign",children:"In any campaign"}),e.jsx(We,{value:"not_in_campaign",children:"Not in any campaign"}),Q.map(je=>e.jsxs(We,{value:je.id,children:["In: ",je.name]},je.id))]})]}),(j!=="all"||A!=="all"||I!=="all")&&e.jsx($,{variant:"ghost",size:"sm",className:"h-8 text-xs text-muted-foreground",onClick:()=>{C("all"),M("all"),P("all")},children:"Clear filters"})]}),e.jsx("div",{className:"rounded-md border",children:e.jsxs(Qa,{children:[e.jsx(Ja,{children:e.jsxs(vn,{children:[e.jsx(Dt,{className:"w-[40px]",children:e.jsx(Li,{checked:Se,onCheckedChange:Ie,"aria-label":"Select all",...Te&&!Se?{"data-state":"indeterminate"}:{}})}),e.jsx(Dt,{className:"cursor-pointer select-none",onClick:()=>fe("name"),children:e.jsxs("span",{className:"inline-flex items-center",children:["Name ",e.jsx(_e,{column:"name"})]})}),e.jsx(Dt,{className:"cursor-pointer select-none",onClick:()=>fe("stage"),children:e.jsxs("span",{className:"inline-flex items-center",children:["Stage ",e.jsx(_e,{column:"stage"})]})}),e.jsx(Dt,{className:"hidden md:table-cell cursor-pointer select-none",onClick:()=>fe("brokerage"),children:e.jsxs("span",{className:"inline-flex items-center",children:["Brokerage ",e.jsx(_e,{column:"brokerage"})]})}),e.jsx(Dt,{className:"hidden md:table-cell",children:"Contact"}),e.jsx(Dt,{className:"hidden lg:table-cell cursor-pointer select-none",onClick:()=>fe("experience"),children:e.jsxs("span",{className:"inline-flex items-center",children:["Experience ",e.jsx(_e,{column:"experience"})]})}),e.jsx(Dt,{className:"hidden lg:table-cell cursor-pointer select-none",onClick:()=>fe("production"),children:e.jsxs("span",{className:"inline-flex items-center",children:["Production ",e.jsx(_e,{column:"production"})]})}),e.jsx(Dt,{className:"hidden lg:table-cell",children:"Campaigns"}),e.jsx(Dt,{className:"w-[50px]"})]})}),e.jsx(ei,{children:he.length===0?e.jsx(vn,{children:e.jsx(_t,{colSpan:9,className:"text-center text-muted-foreground py-8",children:"No prospects found"})}):he.map(je=>{const Ye=ve(je.stage_id),Ee=le.get(je.id),Re=(Ee==null?void 0:Ee.size)??0;return e.jsxs(vn,{className:"cursor-pointer",onClick:()=>{m(je),g(!0)},children:[e.jsx(_t,{onClick:ke=>ke.stopPropagation(),children:e.jsx(Li,{checked:G.has(je.id),onCheckedChange:()=>Ue(je.id),"aria-label":`Select ${je.first_name}`})}),e.jsxs(_t,{className:"font-medium",children:[je.first_name," ",je.last_name]}),e.jsx(_t,{children:Ye?e.jsxs(qe,{variant:"outline",className:"text-xs gap-1 whitespace-nowrap",style:{borderColor:Ye.color,color:Ye.color,backgroundColor:`${Ye.color}10`},children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full inline-block",style:{backgroundColor:Ye.color}}),Ye.name]}):e.jsx("span",{className:"text-muted-foreground text-xs",children:"—"})}),e.jsx(_t,{className:"hidden md:table-cell",children:je.current_brokerage?e.jsxs("div",{className:"flex items-center gap-1.5 text-sm",children:[e.jsx(Gi,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"truncate max-w-[150px]",children:je.current_brokerage})]}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx(_t,{className:"hidden md:table-cell",children:e.jsxs("div",{className:"flex items-center gap-2",children:[je.email&&e.jsx(pn,{className:"h-3.5 w-3.5 text-muted-foreground"}),je.phone&&e.jsx(ka,{className:"h-3.5 w-3.5 text-muted-foreground"}),!je.email&&!je.phone&&e.jsx("span",{className:"text-muted-foreground",children:"—"})]})}),e.jsx(_t,{className:"hidden lg:table-cell",children:je.experience_years!=null?`${je.experience_years} yr`:"—"}),e.jsx(_t,{className:"hidden lg:table-cell",children:je.annual_production||"—"}),e.jsx(_t,{className:"hidden lg:table-cell",children:Re>0?e.jsxs(qe,{variant:"secondary",className:"text-xs",children:[Re," campaign",Re>1?"s":""]}):e.jsx("span",{className:"text-muted-foreground text-xs",children:"None"})}),e.jsx(_t,{children:e.jsx($,{variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground hover:text-destructive",onClick:ke=>{ke.stopPropagation(),l.mutate(je.id)},children:e.jsx(Un,{className:"h-3.5 w-3.5"})})})]},je.id)})})]})}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[G.size>0&&e.jsxs("span",{className:"font-medium text-foreground",children:[G.size," selected · "]}),he.length," of ",n.length," prospects"]}),e.jsx(zs,{open:Y,onOpenChange:se,children:e.jsxs(Rs,{className:"sm:max-w-md",children:[e.jsx(Vs,{children:e.jsx($s,{children:"Add to Campaign"})}),e.jsxs("div",{className:"space-y-4 py-2",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Add ",e.jsx("span",{className:"font-medium text-foreground",children:G.size})," selected prospect(s) to a recruiting campaign drip."]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Campaign"}),e.jsxs(bs,{value:ee,onValueChange:oe,children:[e.jsx(ys,{children:e.jsx(_s,{placeholder:"Select a campaign..."})}),e.jsx(vs,{children:Q.map(je=>e.jsxs(We,{value:je.id,children:[je.name," ",e.jsxs("span",{className:"text-muted-foreground ml-1",children:["(",je.warmth_level,")"]})]},je.id))})]})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>se(!1),children:"Cancel"}),e.jsx($,{onClick:()=>Be.mutate(),disabled:!ee||Be.isPending,children:Be.isPending?"Adding...":"Add to Campaign"})]})]})}),e.jsx(wVt,{open:d,onOpenChange:u,stages:t,onSubmit:je=>a.mutate(je),isSubmitting:a.isPending}),e.jsx(CVt,{prospect:h,stages:t,brokerageId:s,open:p,onOpenChange:g,onUpdate:je=>{i.mutate(je),m(Ye=>Ye?{...Ye,...je}:null)},onDelete:je=>l.mutate(je)}),e.jsx(AVt,{open:x,onOpenChange:y,brokerageId:s,stages:t})]})}function TVt({brokerageId:s}){const{stages:t,prospects:n,isLoading:r}=wte(s),a=k.useMemo(()=>{if(!t.length||!n.length)return null;const i=n.length,l=t.find(v=>v.name==="Signed"),o=t.find(v=>v.name==="Onboarded"),c=n.filter(v=>v.stage_id===(l==null?void 0:l.id)||v.stage_id===(o==null?void 0:o.id)).length,d=i>0?(c/i*100).toFixed(1):"0",u=new Date,h=i>0?Math.round(n.reduce((v,_)=>v+I2(u,new Date(_.created_at)),0)/i):0,m=t.map(v=>({...v,count:n.filter(_=>_.stage_id===v.id).length})),p={};n.forEach(v=>{const _=v.source||"unknown";p[_]=(p[_]||0)+1});const g=Object.entries(p).sort((v,_)=>_[1]-v[1]),x=new Date;x.setDate(x.getDate()-30);const y=n.filter(v=>new Date(v.created_at)>=x).length;return{total:i,signed:c,conversionRate:d,avgDays:h,byStage:m,bySrc:g,recentCount:y}},[t,n]);return r?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx("div",{className:"h-6 w-6 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):a?e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsx(we,{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(Xn,{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(we,{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(mc,{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(we,{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(sa,{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(we,{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(_h,{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(we,{children:[e.jsx(Vt,{children:e.jsx(Yt,{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(we,{children:[e.jsx(Vt,{children:e.jsx(Yt,{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(qe,{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 mOn=["Outreach","Follow-up","Interview","Offer","Referral","Other"];function MVt({brokerageId:s}){const{toast:t}=Fi(),{user:n}=ks(),r=ls(),[a,i]=k.useState(null),[l,o]=k.useState(null),[c,d]=k.useState(!1),[u,h]=k.useState(null),{data:m=[],isLoading:p}=pt({queryKey:["recruit-email-templates-manage",s],queryFn:async()=>{const{data:C,error:A}=await V.from("recruit_email_templates").select("*").or(`brokerage_id.is.null,brokerage_id.eq.${s}`).order("sort_order");if(A)throw A;return C}}),g=Nt({mutationFn:async C=>{if(C.id){const{error:A}=await V.from("recruit_email_templates").update({category:C.category,title:C.title,subject:C.subject,body:C.body}).eq("id",C.id);if(A)throw A}else{const{error:A}=await V.from("recruit_email_templates").insert({brokerage_id:s,category:C.category||"Outreach",title:C.title,subject:C.subject,body:C.body,created_by:n==null?void 0:n.id,sort_order:100});if(A)throw A}},onSuccess:()=>{r.invalidateQueries({queryKey:["recruit-email-templates-manage",s]}),r.invalidateQueries({queryKey:["recruit-email-templates"]}),t({title:"Template saved"}),d(!1),h(null)},onError:C=>t({title:"Save failed",description:C.message,variant:"destructive"})}),x=Nt({mutationFn:async C=>{const{error:A}=await V.from("recruit_email_templates").delete().eq("id",C);if(A)throw A},onSuccess:()=>{r.invalidateQueries({queryKey:["recruit-email-templates-manage",s]}),r.invalidateQueries({queryKey:["recruit-email-templates"]}),t({title:"Template deleted"})},onError:C=>t({title:"Delete failed",description:C.message,variant:"destructive"})}),y=(C,A)=>{navigator.clipboard.writeText(C),i(A),t({title:"Copied to clipboard!"}),setTimeout(()=>i(null),2e3)},v=()=>{h({category:"Outreach",title:"",subject:"",body:""}),d(!0)},_=C=>{h(C),d(!0)},j=Array.from(new Set(m.map(C=>C.category)));return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 flex-wrap",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Pre-built and custom recruiting templates. Built-in templates are global; your custom ones are private to this brokerage."}),e.jsxs($,{onClick:v,size:"sm",className:"gap-1.5",children:[e.jsx(nn,{className:"h-4 w-4"})," New Template"]})]}),p?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(Jt,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):j.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(pn,{className:"h-4 w-4"})," ",C]}),m.filter(A=>A.category===C).map(A=>{const M=A.brokerage_id!==null;return e.jsxs(we,{className:`transition-all ${l===A.id?"ring-2 ring-primary/20":"hover:shadow-sm"}`,children:[e.jsx(Vt,{className:"pb-2 cursor-pointer",onClick:()=>o(l===A.id?null:A.id),children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs(Yt,{className:"text-sm flex items-center gap-2",children:[e.jsx("span",{className:"truncate",children:A.title}),!M&&e.jsx(qe,{variant:"secondary",className:"text-[10px] shrink-0",children:"Built-in"}),M&&e.jsx(qe,{className:"text-[10px] shrink-0",children:"Custom"})]}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5 truncate",children:["Subject: ",A.subject]})]}),e.jsx(qe,{variant:"outline",className:"text-[10px] shrink-0",children:A.category})]})}),l===A.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:A.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:A.body})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs($,{size:"sm",variant:"outline",onClick:()=>y(A.subject,A.id+"-s"),children:[a===A.id+"-s"?e.jsx(ma,{className:"h-3.5 w-3.5 mr-1"}):e.jsx(Da,{className:"h-3.5 w-3.5 mr-1"}),"Copy Subject"]}),e.jsxs($,{size:"sm",variant:"outline",onClick:()=>y(A.body,A.id+"-b"),children:[a===A.id+"-b"?e.jsx(ma,{className:"h-3.5 w-3.5 mr-1"}):e.jsx(Da,{className:"h-3.5 w-3.5 mr-1"}),"Copy Body"]}),M&&e.jsxs(e.Fragment,{children:[e.jsxs($,{size:"sm",variant:"outline",onClick:()=>_(A),children:[e.jsx(ui,{className:"h-3.5 w-3.5 mr-1"})," Edit"]}),e.jsxs($,{size:"sm",variant:"outline",className:"text-destructive hover:text-destructive",onClick:async()=>{await io("Delete this template?")&&x.mutate(A.id)},children:[e.jsx(Un,{className:"h-3.5 w-3.5 mr-1"})," Delete"]})]})]})]})]},A.id)})]},C)),e.jsx(zs,{open:c,onOpenChange:d,children:e.jsxs(Rs,{className:"max-w-2xl",children:[e.jsx(Vs,{children:e.jsx($s,{children:u!=null&&u.id?"Edit Template":"New Template"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Title"}),e.jsx(be,{value:(u==null?void 0:u.title)||"",onChange:C=>h(A=>({...A,title:C.target.value})),className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Category"}),e.jsx("select",{value:(u==null?void 0:u.category)||"Outreach",onChange:C=>h(A=>({...A,category:C.target.value})),className:"mt-1 flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm",children:mOn.map(C=>e.jsx("option",{value:C,children:C},C))})]})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Subject"}),e.jsx(be,{value:(u==null?void 0:u.subject)||"",onChange:C=>h(A=>({...A,subject:C.target.value})),className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Body"}),e.jsx(Ls,{value:(u==null?void 0:u.body)||"",onChange:C=>h(A=>({...A,body:C.target.value})),rows:12,className:"mt-1 font-sans",placeholder:`Hi [First Name], ... Best, [Your Name]`}),e.jsx("p",{className:"text-[11px] text-muted-foreground mt-1",children:"Available placeholders: [First Name], [Your Name], [Brokerage Name]"})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"ghost",onClick:()=>d(!1),children:"Cancel"}),e.jsxs($,{onClick:()=>g.mutate(u||{}),disabled:g.isPending||!(u!=null&&u.title)||!(u!=null&&u.subject)||!(u!=null&&u.body),children:[g.isPending&&e.jsx(Jt,{className:"h-4 w-4 mr-2 animate-spin"}),"Save Template"]})]})]})})]})}const xbt={call:ka,email:pn,text:bo,meeting:ha,note:ea};function PVt({brokerageId:s}){const{data:t,isLoading:n}=pt({queryKey:["recruit-activity-report",s],queryFn:async()=>{const{data:r,error:a}=await V.from("recruit_prospects").select("id, created_by").eq("brokerage_id",s);if(a)throw a;const i=(r==null?void 0:r.map(p=>p.id))||[];if(i.length===0)return{recruiters:[],recentActivities:[]};const{data:l,error:o}=await V.from("recruit_activities").select("*").in("prospect_id",i).order("created_at",{ascending:!1});if(o)throw o;const c=[...new Set([...r.map(p=>p.created_by),...(l||[]).map(p=>p.created_by)])],{data:d}=await V.from("profiles").select("id, name, email").in("id",c),u=Object.fromEntries((d||[]).map(p=>[p.id,p])),h=yY(new Date,30);return{recruiters:c.map(p=>{var _,j;const g=(l||[]).filter(C=>C.created_by===p),x=g.filter(C=>new Date(C.created_at)>=h),y={};x.forEach(C=>{y[C.activity_type]=(y[C.activity_type]||0)+1});const v=r.filter(C=>C.created_by===p).length;return{id:p,name:((_=u[p])==null?void 0:_.name)||"Unknown",email:((j=u[p])==null?void 0:j.email)||"",totalActivities:g.length,recentActivities:x.length,byType:y,prospectsCreated:v}}).sort((p,g)=>g.recentActivities-p.recentActivities),recentActivities:(l||[]).slice(0,20)}},enabled:!!s});return n?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx("div",{className:"h-6 w-6 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):t!=null&&t.recruiters.length?e.jsxs("div",{className:"space-y-6",children:[e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsx(Yt,{className:"text-base",children:"Recruiter Leaderboard (Last 30 Days)"})}),e.jsx(De,{className:"space-y-4",children:t.recruiters.map((r,a)=>e.jsxs("div",{className:"flex items-center gap-4 p-3 rounded-lg bg-muted/30",children:[e.jsx("div",{className:"flex items-center justify-center h-8 w-8 rounded-full bg-primary/10 text-primary font-bold text-sm",children:a+1}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(el,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"font-medium text-sm",children:r.name})]}),e.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:Object.entries(r.byType).map(([i,l])=>{const o=xbt[i]||ea;return e.jsxs(qe,{variant:"outline",className:"text-[10px] gap-1",children:[e.jsx(o,{className:"h-2.5 w-2.5"})," ",l," ",i,l!==1?"s":""]},i)})})]}),e.jsxs("div",{className:"text-right",children:[e.jsx("p",{className:"text-lg font-bold",children:r.recentActivities}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"activities"})]}),e.jsxs("div",{className:"text-right",children:[e.jsx("p",{className:"text-lg font-bold",children:r.prospectsCreated}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"prospects"})]})]},r.id))})]}),e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsx(Yt,{className:"text-base",children:"Recent Activity"})}),e.jsx(De,{className:"space-y-3",children:t.recentActivities.map(r=>{const a=xbt[r.activity_type]||ea;return e.jsxs("div",{className:"flex items-start gap-3 text-sm",children:[e.jsx("div",{className:"h-7 w-7 rounded-full bg-muted flex items-center justify-center flex-shrink-0 mt-0.5",children:e.jsx(a,{className:"h-3.5 w-3.5 text-muted-foreground"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium",children:r.title}),r.description&&e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:r.description}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:Ys(new Date(r.created_at),"MMM d, h:mm a")})]})]},r.id)})})]})]}):e.jsx("p",{className:"text-sm text-muted-foreground text-center py-8",children:"No recruiter activity yet."})}function IVt({brokerageId:s}){const{toast:t}=Fi(),n=ls(),[r,a]=k.useState(!1),[i,l]=k.useState({first_name:"",last_name:"",email:"",phone:"",current_brokerage:"",notes:""}),{data:o=[],isLoading:c}=pt({queryKey:["recruit-referrals",s],queryFn:async()=>{const{data:y,error:v}=await V.from("recruit_referrals").select("*").eq("brokerage_id",s).order("created_at",{ascending:!1});if(v)throw v;return y}}),d=[...new Set(o.map(y=>y.referred_by))],{data:u=[]}=pt({queryKey:["referral-profiles",d],queryFn:async()=>{if(!d.length)return[];const{data:y}=await V.from("profiles").select("id, name, email").in("id",d);return y||[]},enabled:d.length>0}),h=Object.fromEntries(u.map(y=>[y.id,y])),m=Nt({mutationFn:async y=>{const{data:{user:v}}=await V.auth.getUser();if(!v)throw new Error("Not authenticated");const{error:_}=await V.from("recruit_referrals").insert({brokerage_id:s,referred_by:v.id,referee_first_name:y.first_name,referee_last_name:y.last_name||null,referee_email:y.email||null,referee_phone:y.phone||null,referee_current_brokerage:y.current_brokerage||null,notes:y.notes||null});if(_)throw _},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-referrals",s]}),t({title:"Referral submitted!"}),l({first_name:"",last_name:"",email:"",phone:"",current_brokerage:"",notes:""}),a(!1)},onError:y=>t({title:"Error",description:y.message,variant:"destructive"})}),p=Nt({mutationFn:async({id:y,status:v,incentive_status:_})=>{const j={updated_at:new Date().toISOString()};v&&(j.status=v),_&&(j.incentive_status=_);const{error:C}=await V.from("recruit_referrals").update(j).eq("id",y);if(C)throw C},onSuccess:()=>n.invalidateQueries({queryKey:["recruit-referrals",s]})}),g=y=>y==="approved"||y==="signed"?e.jsx(ma,{className:"h-3 w-3"}):y==="rejected"?e.jsx(ju,{className:"h-3 w-3"}):e.jsx(sa,{className:"h-3 w-3"}),x=y=>y==="approved"||y==="signed"||y==="paid"?"bg-green-500/10 text-green-600 border-green-200":y==="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($,{onClick:()=>a(!0),children:[e.jsx(nn,{className:"h-4 w-4 mr-2"})," Submit Referral"]})]}),o.length===0?e.jsxs(we,{className:"py-12 text-center",children:[e.jsx(Pl,{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(y=>{var v;return e.jsx(we,{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:[y.referee_first_name," ",y.referee_last_name]}),e.jsxs(qe,{variant:"outline",className:x(y.status),children:[g(y.status)," ",y.status]}),y.incentive_status&&e.jsxs(qe,{variant:"outline",className:x(y.incentive_status),children:[e.jsx(Zo,{className:"h-3 w-3 mr-1"})," ",y.incentive_status]})]}),e.jsxs("div",{className:"text-xs text-muted-foreground space-y-0.5",children:[y.referee_email&&e.jsx("p",{children:y.referee_email}),y.referee_phone&&e.jsx("p",{children:y.referee_phone}),y.referee_current_brokerage&&e.jsxs("p",{children:["Currently at: ",y.referee_current_brokerage]}),e.jsxs("p",{children:["Referred by: ",((v=h[y.referred_by])==null?void 0:v.name)||"Unknown"," • ",Ys(new Date(y.created_at),"MMM d, yyyy")]})]}),y.notes&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1 italic",children:y.notes})]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsxs(bs,{value:y.status,onValueChange:_=>p.mutate({id:y.id,status:_}),children:[e.jsx(ys,{className:"h-7 text-xs w-[110px]",children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"pending",children:"Pending"}),e.jsx(We,{value:"contacted",children:"Contacted"}),e.jsx(We,{value:"approved",children:"Approved"}),e.jsx(We,{value:"signed",children:"Signed"}),e.jsx(We,{value:"rejected",children:"Rejected"})]})]}),e.jsxs(bs,{value:y.incentive_status||"pending",onValueChange:_=>p.mutate({id:y.id,incentive_status:_}),children:[e.jsx(ys,{className:"h-7 text-xs w-[100px]",children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"pending",children:"Unpaid"}),e.jsx(We,{value:"paid",children:"Paid"}),e.jsx(We,{value:"n/a",children:"N/A"})]})]})]})]})},y.id)})}),e.jsx(zs,{open:r,onOpenChange:a,children:e.jsxs(Rs,{children:[e.jsx(Vs,{children:e.jsx($s,{children:"Submit a Recruit Referral"})}),e.jsxs("form",{onSubmit:y=>{y.preventDefault(),m.mutate(i)},className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(re,{children:"First Name *"}),e.jsx(be,{required:!0,value:i.first_name,onChange:y=>l(v=>({...v,first_name:y.target.value}))})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Last Name"}),e.jsx(be,{value:i.last_name,onChange:y=>l(v=>({...v,last_name:y.target.value}))})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Email"}),e.jsx(be,{type:"email",value:i.email,onChange:y=>l(v=>({...v,email:y.target.value}))})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Phone"}),e.jsx(be,{value:i.phone,onChange:y=>l(v=>({...v,phone:y.target.value}))})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Current Brokerage"}),e.jsx(be,{value:i.current_brokerage,onChange:y=>l(v=>({...v,current_brokerage:y.target.value}))})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Notes"}),e.jsx(Ls,{value:i.notes,onChange:y=>l(v=>({...v,notes:y.target.value})),rows:2})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx($,{type:"button",variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx($,{type:"submit",disabled:m.isPending,children:"Submit"})]})]})]})})]})}function LVt({brokerageId:s}){const{toast:t}=Fi(),n=ls(),[r,a]=k.useState(!1),{data:i}=pt({queryKey:["brokerage-recruit-form",s],queryFn:async()=>{const{data:m,error:p}=await V.from("brokerages").select("id, name, recruit_form_slug, recruit_form_enabled").eq("id",s).single();if(p)throw p;return m}}),{data:l=[]}=pt({queryKey:["recruit-interest-submissions",s],queryFn:async()=>{const{data:m,error:p}=await V.from("recruit_interest_submissions").select("*").eq("brokerage_id",s).order("created_at",{ascending:!1});if(p)throw p;return m}}),o=Nt({mutationFn:async m=>{const{error:p}=await V.from("brokerages").update({recruit_form_enabled:m}).eq("id",s);if(p)throw p},onSuccess:()=>{n.invalidateQueries({queryKey:["brokerage-recruit-form",s]}),t({title:i!=null&&i.recruit_form_enabled?"Form disabled":"Form enabled"})}}),c=Nt({mutationFn:async({id:m,status:p})=>{const{error:g}=await V.from("recruit_interest_submissions").update({status:p}).eq("id",m);if(g)throw g},onSuccess:()=>n.invalidateQueries({queryKey:["recruit-interest-submissions",s]})}),d=`https://bestbrokerage.relevelup.com/join-brokerage/${(i==null?void 0:i.recruit_form_slug)||""}`,u=()=>{navigator.clipboard.writeText(d),a(!0),t({title:"Link copied!"}),setTimeout(()=>a(!1),2e3)},h=m=>m==="contacted"||m==="converted"?"bg-green-500/10 text-green-600":m==="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(we,{children:[e.jsx(Vt,{children:e.jsx(Yt,{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(re,{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(On,{checked:(i==null?void 0:i.recruit_form_enabled)||!1,onCheckedChange:m=>o.mutate(m)})]}),(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($,{size:"sm",variant:"outline",onClick:u,children:r?e.jsx(ma,{className:"h-3.5 w-3.5"}):e.jsx(Da,{className:"h-3.5 w-3.5"})}),e.jsx($,{size:"sm",variant:"outline",asChild:!0,children:e.jsx("a",{href:d,target:"_blank",rel:"noopener noreferrer",children:e.jsx(Ir,{className:"h-3.5 w-3.5"})})})]})]})]}),e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsxs(Yt,{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(Pl,{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(m=>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:[m.first_name," ",m.last_name]}),e.jsx(qe,{variant:"outline",className:h(m.status),children:m.status})]}),e.jsxs("div",{className:"flex flex-wrap gap-3 text-xs text-muted-foreground",children:[m.email&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(pn,{className:"h-3 w-3"}),m.email]}),m.phone&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ka,{className:"h-3 w-3"}),m.phone]}),m.current_brokerage&&e.jsxs("span",{children:["From: ",m.current_brokerage]}),m.experience_years&&e.jsxs("span",{children:[m.experience_years,"yr exp"]})]}),m.why_interested&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1 italic",children:['"',m.why_interested,'"']}),e.jsx("p",{className:"text-[10px] text-muted-foreground mt-1",children:Ys(new Date(m.created_at),"MMM d, yyyy h:mm a")})]}),e.jsxs(bs,{value:m.status,onValueChange:p=>c.mutate({id:m.id,status:p}),children:[e.jsx(ys,{className:"h-7 text-xs w-[110px]",children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"new",children:"New"}),e.jsx(We,{value:"contacted",children:"Contacted"}),e.jsx(We,{value:"converted",children:"Converted"}),e.jsx(We,{value:"dismissed",children:"Dismissed"})]})]})]},m.id))})})]})]})}function RVt({brokerageId:s}){const{toast:t}=Fi(),n=ls(),[r,a]=k.useState(!1),[i,l]=k.useState({prospect_id:"",title:"",description:"",due_date:Ys(wu(new Date,1),"yyyy-MM-dd'T'HH:mm")}),[o,c]=k.useState("pending"),{data:d=[]}=pt({queryKey:["recruit-prospects-list",s],queryFn:async()=>{const{data:A,error:M}=await V.from("recruit_prospects").select("id, first_name, last_name").eq("brokerage_id",s).order("first_name");if(M)throw M;return A}}),{data:u=[],isLoading:h}=pt({queryKey:["recruit-follow-ups",s],queryFn:async()=>{const A=d.map(P=>P.id);if(!A.length)return[];const{data:M,error:I}=await V.from("recruit_follow_ups").select("*").in("prospect_id",A).order("due_date");if(I)throw I;return M},enabled:d.length>0}),m=Object.fromEntries(d.map(A=>[A.id,A])),p=Nt({mutationFn:async A=>{const{data:{user:M}}=await V.auth.getUser();if(!M)throw new Error("Not authenticated");const{error:I}=await V.from("recruit_follow_ups").insert({prospect_id:A.prospect_id,assigned_to:M.id,title:A.title,description:A.description||null,due_date:new Date(A.due_date).toISOString()});if(I)throw I},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-follow-ups",s]}),t({title:"Follow-up scheduled"}),l({prospect_id:"",title:"",description:"",due_date:Ys(wu(new Date,1),"yyyy-MM-dd'T'HH:mm")}),a(!1)},onError:A=>t({title:"Error",description:A.message,variant:"destructive"})}),g=Nt({mutationFn:async({id:A,completed:M})=>{const{error:I}=await V.from("recruit_follow_ups").update({completed_at:M?new Date().toISOString():null}).eq("id",A);if(I)throw I},onSuccess:()=>n.invalidateQueries({queryKey:["recruit-follow-ups",s]})}),x=u.filter(A=>o==="pending"?!A.completed_at:o==="completed"?!!A.completed_at:!0),y=x.filter(A=>!A.completed_at&&R5(new Date(A.due_date))&&!m0(new Date(A.due_date))),v=x.filter(A=>!A.completed_at&&m0(new Date(A.due_date))),_=x.filter(A=>!A.completed_at&&!R5(new Date(A.due_date))&&!m0(new Date(A.due_date))),j=x.filter(A=>!!A.completed_at),C=A=>{const M=m[A.prospect_id],I=!A.completed_at&&R5(new Date(A.due_date))&&!m0(new Date(A.due_date));return e.jsxs("div",{className:"flex items-start gap-3 p-3 border rounded-lg",children:[e.jsx(Li,{checked:!!A.completed_at,onCheckedChange:P=>g.mutate({id:A.id,completed:P}),className:"mt-0.5"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:`text-sm font-medium ${A.completed_at?"line-through text-muted-foreground":""}`,children:A.title}),A.description&&e.jsx("p",{className:"text-xs text-muted-foreground",children:A.description}),e.jsxs("div",{className:"flex items-center gap-2 mt-1 text-xs text-muted-foreground",children:[M&&e.jsxs(qe,{variant:"secondary",className:"text-[10px]",children:[M.first_name," ",M.last_name]}),e.jsxs("span",{className:`flex items-center gap-1 ${I?"text-destructive font-medium":""}`,children:[I?e.jsx(Ho,{className:"h-3 w-3"}):e.jsx(ha,{className:"h-3 w-3"}),Ys(new Date(A.due_date),"MMM d, h:mm a")]}),A.is_automated&&e.jsx(qe,{variant:"outline",className:"text-[10px]",children:"Auto"})]})]})]},A.id)};return h?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx("div",{className:"h-6 w-6 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{className:"flex gap-2",children:["pending","completed","all"].map(A=>e.jsxs($,{size:"sm",variant:o===A?"default":"outline",onClick:()=>c(A),className:"capitalize text-xs",children:[A," ",A==="pending"&&y.length+v.length+_.length>0&&`(${y.length+v.length+_.length})`]},A))}),e.jsxs($,{size:"sm",onClick:()=>a(!0),children:[e.jsx(nn,{className:"h-4 w-4 mr-1"})," Add Follow-up"]})]}),o!=="completed"&&y.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(Ho,{className:"h-3.5 w-3.5"})," Overdue (",y.length,")"]}),y.map(C)]}),o!=="completed"&&v.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(sa,{className:"h-3.5 w-3.5"})," Today (",v.length,")"]}),v.map(C)]}),o!=="completed"&&_.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(ha,{className:"h-3.5 w-3.5"})," Upcoming (",_.length,")"]}),_.map(C)]}),o!=="pending"&&j.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(ma,{className:"h-3.5 w-3.5"})," Completed (",j.length,")"]}),j.map(C)]}),x.length===0&&e.jsxs("p",{className:"text-sm text-muted-foreground text-center py-8",children:["No follow-ups ",o!=="all"?`(${o})`:""]}),e.jsx(zs,{open:r,onOpenChange:a,children:e.jsxs(Rs,{children:[e.jsx(Vs,{children:e.jsx($s,{children:"Schedule Follow-up"})}),e.jsxs("form",{onSubmit:A=>{A.preventDefault(),p.mutate(i)},className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(re,{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:A=>l(M=>({...M,prospect_id:A.target.value})),children:[e.jsx("option",{value:"",children:"Select prospect..."}),d.map(A=>e.jsxs("option",{value:A.id,children:[A.first_name," ",A.last_name]},A.id))]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Task *"}),e.jsx(be,{required:!0,value:i.title,onChange:A=>l(M=>({...M,title:A.target.value})),placeholder:"e.g. Follow-up call"})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Details"}),e.jsx(Ls,{value:i.description,onChange:A=>l(M=>({...M,description:A.target.value})),rows:2})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Due Date *"}),e.jsx(be,{type:"datetime-local",required:!0,value:i.due_date,onChange:A=>l(M=>({...M,due_date:A.target.value}))})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx($,{type:"button",variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx($,{type:"submit",disabled:p.isPending,children:"Schedule"})]})]})]})})]})}const fOn=[{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 DVt({brokerageId:s}){const{toast:t}=Fi(),n=ls(),[r,a]=k.useState(null),{data:i,isLoading:l}=pt({queryKey:["recruit-landing-settings",s],queryFn:async()=>{const{data:y,error:v}=await V.from("recruit_landing_page_settings").select("*").eq("brokerage_id",s).maybeSingle();if(v)throw v;return y}}),[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:fOn,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=Nt({mutationFn:async()=>{const y={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:v}=await V.from("recruit_landing_page_settings").update(y).eq("id",o.id);if(v)throw v}else{const{error:v}=await V.from("recruit_landing_page_settings").insert(y);if(v)throw v}},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-landing-settings",s]}),t({title:"Landing page saved!"})},onError:y=>t({title:"Error",description:y.message,variant:"destructive"})}),u=async(y,v)=>{const _=y.name.split(".").pop(),j=`${s}/${v}-${Date.now()}.${_}`,{error:C}=await V.storage.from("recruit-landing").upload(j,y);if(C)throw C;const{data:{publicUrl:A}}=V.storage.from("recruit-landing").getPublicUrl(j);return A},h=async(y,v)=>{var j;const _=(j=y.target.files)==null?void 0:j[0];if(_){a(v);try{const C=await u(_,v);c(A=>({...A,[v]:C})),t({title:"Image uploaded!"})}catch(C){t({title:"Upload failed",description:C.message,variant:"destructive"})}finally{a(null)}}},m=async y=>{var _;const v=(_=y.target.files)==null?void 0:_[0];if(v){a("gallery");try{const j=await u(v,"gallery");c(C=>({...C,gallery_images:[...C.gallery_images,j]})),t({title:"Gallery image added!"})}catch(j){t({title:"Upload failed",description:j.message,variant:"destructive"})}finally{a(null)}}},p=async(y,v)=>{var j;const _=(j=y.target.files)==null?void 0:j[0];if(_){a(`testimonial-${v}`);try{const C=await u(_,`testimonial-${v}`);c(A=>{const M=[...A.testimonials];return M[v]={...M[v],photo_url:C},{...A,testimonials:M}})}catch(C){t({title:"Upload failed",description:C.message,variant:"destructive"})}finally{a(null)}}},{data:g}=pt({queryKey:["brokerage-slug-for-landing",s],queryFn:async()=>{const{data:y,error:v}=await V.from("brokerages").select("recruit_form_slug, recruit_form_enabled").eq("id",s).single();if(v)throw v;return y}}),x=`https://bestbrokerage.relevelup.com/join-brokerage/${(g==null?void 0:g.recruit_form_slug)||""}`;return l?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):e.jsxs("div",{className:"space-y-6",children:[(g==null?void 0:g.recruit_form_enabled)&&e.jsxs("div",{className:"flex items-center gap-2 p-3 bg-muted/50 rounded-lg border",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Live page:"}),e.jsx("code",{className:"text-xs flex-1 truncate",children:x}),e.jsx($,{size:"sm",variant:"outline",asChild:!0,children:e.jsxs("a",{href:x,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(Ir,{className:"h-3.5 w-3.5 mr-1"})," Preview"]})})]}),e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsx(Yt,{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(re,{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($,{variant:"outline",size:"sm",asChild:!0,disabled:r==="logo_url",children:e.jsxs("span",{children:[e.jsx(gi,{className:"h-3.5 w-3.5 mr-1"}),r==="logo_url"?"Uploading...":"Upload Logo"]})}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:y=>h(y,"logo_url")})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(re,{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:y=>c(v=>({...v,primary_color:y.target.value})),className:"h-9 w-12 rounded border cursor-pointer"}),e.jsx(be,{value:o.primary_color,onChange:y=>c(v=>({...v,primary_color:y.target.value})),className:"font-mono text-xs"})]})]}),e.jsxs("div",{children:[e.jsx(re,{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:y=>c(v=>({...v,accent_color:y.target.value})),className:"h-9 w-12 rounded border cursor-pointer"}),e.jsx(be,{value:o.accent_color,onChange:y=>c(v=>({...v,accent_color:y.target.value})),className:"font-mono text-xs"})]})]})]})]})})]}),e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsx(Yt,{className:"text-base",children:"Hero Section"})}),e.jsxs(De,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Headline"}),e.jsx(be,{value:o.hero_headline,onChange:y=>c(v=>({...v,hero_headline:y.target.value})),placeholder:"Join Our Team"})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Subtext"}),e.jsx(Ls,{value:o.hero_subtext,onChange:y=>c(v=>({...v,hero_subtext:y.target.value})),rows:2,placeholder:"Take your career to the next level..."})]}),e.jsxs("div",{children:[e.jsx(re,{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($,{variant:"outline",size:"sm",asChild:!0,disabled:r==="hero_image_url",children:e.jsxs("span",{children:[e.jsx(gi,{className:"h-3.5 w-3.5 mr-1"}),r==="hero_image_url"?"Uploading...":"Upload Image"]})}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:y=>h(y,"hero_image_url")})]}),o.hero_image_url&&e.jsx($,{variant:"ghost",size:"sm",onClick:()=>c(y=>({...y,hero_image_url:null})),children:e.jsx(Un,{className:"h-3.5 w-3.5"})})]})]})]})]}),e.jsxs(we,{children:[e.jsxs(Vt,{className:"flex flex-row items-center justify-between",children:[e.jsx(Yt,{className:"text-base",children:"Benefits / Why Join Us"}),e.jsxs($,{size:"sm",variant:"outline",onClick:()=>c(y=>({...y,benefits:[...y.benefits,{title:"",description:"",icon:"✨"}]})),children:[e.jsx(nn,{className:"h-3.5 w-3.5 mr-1"})," Add"]})]}),e.jsxs(De,{className:"space-y-3",children:[o.benefits.map((y,v)=>e.jsxs("div",{className:"flex items-start gap-3 p-3 border rounded-lg",children:[e.jsx(Bp,{className:"h-4 w-4 mt-2 text-muted-foreground"}),e.jsx(be,{value:y.icon,onChange:_=>{const j=[...o.benefits];j[v]={...y,icon:_.target.value},c(C=>({...C,benefits:j}))},className:"w-14 text-center"}),e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsx(be,{value:y.title,onChange:_=>{const j=[...o.benefits];j[v]={...y,title:_.target.value},c(C=>({...C,benefits:j}))},placeholder:"Benefit title"}),e.jsx(be,{value:y.description,onChange:_=>{const j=[...o.benefits];j[v]={...y,description:_.target.value},c(C=>({...C,benefits:j}))},placeholder:"Short description"})]}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>c(_=>({..._,benefits:_.benefits.filter((j,C)=>C!==v)})),children:e.jsx(Un,{className:"h-3.5 w-3.5 text-destructive"})})]},v)),o.benefits.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No benefits added yet"})]})]}),e.jsxs(we,{children:[e.jsxs(Vt,{className:"flex flex-row items-center justify-between",children:[e.jsx(Yt,{className:"text-base",children:"Testimonials"}),e.jsxs($,{size:"sm",variant:"outline",onClick:()=>c(y=>({...y,testimonials:[...y.testimonials,{name:"",role:"",quote:""}]})),children:[e.jsx(nn,{className:"h-3.5 w-3.5 mr-1"})," Add"]})]}),e.jsxs(De,{className:"space-y-3",children:[o.testimonials.map((y,v)=>{var _;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:[y.photo_url?e.jsx("img",{src:y.photo_url,alt:y.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:((_=y.name)==null?void 0:_[0])||"?"}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx("span",{className:"text-[10px] text-primary hover:underline",children:r===`testimonial-${v}`?"...":"Photo"}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:j=>p(j,v)})]})]}),e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(be,{value:y.name,onChange:j=>{const C=[...o.testimonials];C[v]={...y,name:j.target.value},c(A=>({...A,testimonials:C}))},placeholder:"Name"}),e.jsx(be,{value:y.role,onChange:j=>{const C=[...o.testimonials];C[v]={...y,role:j.target.value},c(A=>({...A,testimonials:C}))},placeholder:"Role / Title"})]}),e.jsx(Ls,{value:y.quote,onChange:j=>{const C=[...o.testimonials];C[v]={...y,quote:j.target.value},c(A=>({...A,testimonials:C}))},placeholder:"What they say about working here...",rows:2})]}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>c(j=>({...j,testimonials:j.testimonials.filter((C,A)=>A!==v)})),children:e.jsx(Un,{className:"h-3.5 w-3.5 text-destructive"})})]},v)}),o.testimonials.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No testimonials added yet"})]})]}),e.jsxs(we,{children:[e.jsxs(Vt,{className:"flex flex-row items-center justify-between",children:[e.jsx(Yt,{className:"text-base",children:"Team & Culture Gallery"}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx($,{size:"sm",variant:"outline",asChild:!0,disabled:r==="gallery",children:e.jsxs("span",{children:[e.jsx(zc,{className:"h-3.5 w-3.5 mr-1"}),r==="gallery"?"Uploading...":"Add Photo"]})}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:m})]})]}),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((y,v)=>e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:y,alt:`Gallery ${v+1}`,className:"h-24 w-full object-cover rounded-lg"}),e.jsx($,{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(_=>({..._,gallery_images:_.gallery_images.filter((j,C)=>C!==v)})),children:e.jsx(Un,{className:"h-3 w-3"})})]},v))}):e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No gallery images added yet"})})]}),e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsxs(Yt,{className:"text-base flex items-center gap-2",children:[e.jsx(kn,{className:"h-4 w-4 text-primary"})," Form Style & Trust"]})}),e.jsxs(De,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Application Form Style"}),e.jsxs(bs,{value:o.form_style,onValueChange:y=>c(v=>({...v,form_style:y})),children:[e.jsx(ys,{className:"mt-1.5",children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"classic",children:"Classic — single-page form (all fields visible)"}),e.jsx(We,{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(fu,{className:"h-4 w-4 mt-0.5 text-primary"}),e.jsxs("div",{children:[e.jsx(re,{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(On,{checked:o.confidential_messaging,onCheckedChange:y=>c(v=>({...v,confidential_messaging:y}))})]})]})]}),e.jsxs(we,{children:[e.jsxs(Vt,{className:"flex flex-row items-center justify-between",children:[e.jsxs(Yt,{className:"text-base flex items-center gap-2",children:[e.jsx(C5,{className:"h-4 w-4 text-primary"})," Split & Income Calculator"]}),e.jsx(On,{checked:o.calculator_enabled,onCheckedChange:y=>c(v=>({...v,calculator_enabled:y}))})]}),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(re,{className:"text-xs",children:"Calculator Headline"}),e.jsx(be,{value:o.calculator_config.headline||"",onChange:y=>c(v=>({...v,calculator_config:{...v.calculator_config,headline:y.target.value}})),placeholder:"See What You Could Earn With Us"})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Subtext"}),e.jsx(be,{value:o.calculator_config.subtext||"",onChange:y=>c(v=>({...v,calculator_config:{...v.calculator_config,subtext:y.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(re,{className:"text-xs",children:"Pre-Cap Split % (agent keeps)"}),e.jsx(be,{type:"number",value:o.calculator_config.commission_split_pct??80,onChange:y=>c(v=>({...v,calculator_config:{...v.calculator_config,commission_split_pct:parseFloat(y.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(re,{className:"text-xs",children:"Cap Amount ($)"}),e.jsx(be,{type:"number",value:o.calculator_config.cap_amount??16e3,onChange:y=>c(v=>({...v,calculator_config:{...v.calculator_config,cap_amount:parseFloat(y.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(re,{className:"text-xs",children:"Post-Cap Split % (agent keeps)"}),e.jsx(be,{type:"number",value:o.calculator_config.post_cap_split_pct??100,onChange:y=>c(v=>({...v,calculator_config:{...v.calculator_config,post_cap_split_pct:parseFloat(y.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(re,{className:"text-xs",children:"Monthly Fee ($)"}),e.jsx(be,{type:"number",value:o.calculator_config.monthly_fee??99,onChange:y=>c(v=>({...v,calculator_config:{...v.calculator_config,monthly_fee:parseFloat(y.target.value)||0}}))})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Per-Transaction Fee ($)"}),e.jsx(be,{type:"number",value:o.calculator_config.transaction_fee??0,onChange:y=>c(v=>({...v,calculator_config:{...v.calculator_config,transaction_fee:parseFloat(y.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(re,{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(On,{checked:o.calculator_config.show_email_capture!==!1,onCheckedChange:y=>c(v=>({...v,calculator_config:{...v.calculator_config,show_email_capture:y}}))})]})]})]}),e.jsxs(we,{children:[e.jsxs(Vt,{className:"flex flex-row items-center justify-between",children:[e.jsxs(Yt,{className:"text-base flex items-center gap-2",children:[e.jsx(y2,{className:"h-4 w-4 text-primary"})," Lead Magnet (Gated PDF)"]}),e.jsx(On,{checked:o.lead_magnet_enabled,onCheckedChange:y=>c(v=>({...v,lead_magnet_enabled:y}))})]}),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(re,{className:"text-xs",children:"Title"}),e.jsx(be,{value:o.lead_magnet_config.title||"",onChange:y=>c(v=>({...v,lead_magnet_config:{...v.lead_magnet_config,title:y.target.value}})),placeholder:"Get the Full Comp Plan PDF"})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Description"}),e.jsx(Ls,{rows:2,value:o.lead_magnet_config.description||"",onChange:y=>c(v=>({...v,lead_magnet_config:{...v.lead_magnet_config,description:y.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(re,{className:"text-xs",children:"Button Text"}),e.jsx(be,{value:o.lead_magnet_config.button_text||"",onChange:y=>c(v=>({...v,lead_magnet_config:{...v.lead_magnet_config,button_text:y.target.value}})),placeholder:"Email Me the PDF"})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"PDF / File URL"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(be,{value:o.lead_magnet_config.pdf_url||"",onChange:y=>c(v=>({...v,lead_magnet_config:{...v.lead_magnet_config,pdf_url:y.target.value||null}})),placeholder:"https://...",className:"flex-1"}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx($,{variant:"outline",size:"sm",asChild:!0,disabled:r==="lead_magnet_pdf",children:e.jsxs("span",{children:[e.jsx(gi,{className:"h-3.5 w-3.5 mr-1"}),r==="lead_magnet_pdf"?"...":"Upload"]})}),e.jsx("input",{type:"file",accept:"application/pdf,.pdf,.doc,.docx",className:"hidden",onChange:async y=>{var _;const v=(_=y.target.files)==null?void 0:_[0];if(v){a("lead_magnet_pdf");try{const j=await u(v,"lead-magnet");c(C=>({...C,lead_magnet_config:{...C.lead_magnet_config,pdf_url:j}})),t({title:"PDF uploaded!"})}catch(j){t({title:"Upload failed",description:j.message,variant:"destructive"})}finally{a(null)}}}})]})]})]})]})]})]}),e.jsx(pOn,{brokerageId:s}),e.jsx("div",{className:"flex justify-end",children:e.jsxs($,{onClick:()=>d.mutate(),disabled:d.isPending,size:"lg",children:[e.jsx(Ml,{className:"h-4 w-4 mr-2"}),d.isPending?"Saving...":"Save Landing Page"]})})]})}function pOn({brokerageId:s}){const{data:t=[]}=pt({queryKey:["lead-magnet-downloads",s],queryFn:async()=>{const{data:n,error:r}=await V.from("recruit_lead_magnet_downloads").select("*").eq("brokerage_id",s).order("created_at",{ascending:!1}).limit(100);if(r)throw r;return n}});return t.length===0?null:e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsxs(Yt,{className:"text-base flex items-center gap-2",children:[e.jsx(ji,{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(n=>e.jsx("div",{className:"flex items-center justify-between gap-3 p-2.5 border rounded-lg text-sm",children:e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"font-medium truncate",children:[n.first_name||"—"," · ",n.email]}),e.jsxs("div",{className:"text-[11px] text-muted-foreground",children:[Ys(new Date(n.created_at),"MMM d, yyyy h:mm a")," · via ",n.source]})]})},n.id))})})]})}function OVt({brokerageId:s,trigger:t,initialProspectId:n,open:r,onOpenChange:a}){const[i,l]=k.useState(!1),o=r??i,c=a??l,[d,u]=k.useState("pick-recipients"),[h,m]=k.useState(new Set(n?[n]:[])),[p,g]=k.useState("all"),[x,y]=k.useState(""),[v,_]=k.useState(null),[j,C]=k.useState(""),[A,M]=k.useState(0),[I,P]=k.useState(0),[R,O]=k.useState(""),[B,U]=k.useState(""),{data:G}=qTe(),[H,Y]=k.useState("default");k.useEffect(()=>{Y(G!=null&&G.massEmail?"mass_email":G!=null&&G.gmail?"gmail":"default")},[G==null?void 0:G.massEmail,G==null?void 0:G.gmail]);const[se,ee]=k.useState(null),{prospects:oe,stages:me}=wte(s),Q=NVt(),te=o4(),{data:le=[]}=pt({queryKey:["brokerage-recruit-video-pool",s],queryFn:async()=>{const{data:je,error:Ye}=await V.from("agent_videos").select("id, title, thumbnail_url, duration_seconds, created_at, owner_user_id, share_token").eq("touch_type","recruiting").eq("status","ready").eq("is_deleted",!1).order("created_at",{ascending:!1}).limit(50);if(Ye)throw Ye;return je??[]},enabled:o&&d==="pick-video"}),fe=k.useCallback(()=>{u("pick-recipients"),m(new Set(n?[n]:[])),g("all"),y(""),_(null),C(""),M(0),P(0),O(""),U(""),Y("default"),ee(null)},[n]),_e=je=>{!je&&(d==="uploading"||d==="processing"||d==="sending")||(c(je),je||setTimeout(fe,200))},ve=k.useMemo(()=>oe.filter(je=>{if(!je.email||p!=="all"&&je.stage_id!==p)return!1;if(x){const Ye=x.toLowerCase();if(!`${je.first_name} ${je.last_name??""}`.toLowerCase().includes(Ye)&&!je.email.toLowerCase().includes(Ye))return!1}return!0}),[oe,p,x]),he=je=>{m(Ye=>{const Ee=new Set(Ye);return Ee.has(je)?Ee.delete(je):Ee.add(je),Ee})},Se=()=>{h.size===ve.length?m(new Set):m(new Set(ve.map(je=>je.id)))},Te=k.useCallback(async(je,Ye)=>{u("uploading");try{const Ee=`Recruiting blast (${h.size} recipients)`,{videoId:Re,libraryId:ke}=await v6(Ee),{uploadUrl:Fe,apiKey:Oe}=await b6(Re),Ge=new XMLHttpRequest;Ge.upload.onprogress=rt=>{rt.lengthComputable&&M(rt.loaded/rt.total*100)},await new Promise((rt,Ft)=>{Ge.onload=()=>Ge.status>=200&&Ge.status<300?rt():Ft(new Error("Upload failed")),Ge.onerror=()=>Ft(new Error("Upload failed")),Ge.open("PUT",Fe),Ge.setRequestHeader("AccessKey",Oe),Ge.send(je)}),u("processing");const yt=`https://iframe.mediadelivery.net/embed/${ke}/${Re}`;let tt=0;const ut=Date.now(),nt=9e4;for(;tt<4&&(await new Promise(Ft=>setTimeout(Ft,3e3)),!(Date.now()-ut>nt));){const rt=await D2(Re);if(tt=rt.status,P(rt.encodeProgress||0),tt===5||tt===6)throw new Error("Video processing failed")}const et=await D2(Re),at=(et.storageSize||je.size)/(1024*1024),wt=await te.mutateAsync({bunny_video_id:Re,playback_url:et.directPlayUrl||yt,thumbnail_url:et.thumbnailUrl,preview_url:et.previewUrl||null,duration_seconds:et.length||Ye,file_size_mb:at,title:Ee,status:tt>=4?"ready":"processing",touch_type:"recruiting"});_(wt.id),C(Ee),u("compose")}catch(Ee){ae.error((Ee==null?void 0:Ee.message)||"Failed to upload video"),u("pick-video")}},[h.size,te]),Ie=k.useCallback(async()=>{if(!(!v||h.size===0)){u("sending");try{const je=[];for(const Re of h){const ke=await Q.mutateAsync({prospect_id:Re,video_id:v,brokerage_id:s,message:B||void 0});je.push(ke.id)}const{data:Ye,error:Ee}=await V.functions.invoke("send-recruit-video-email",{body:{recruit_video_ids:je,brokerage_id:s,subject_override:R||void 0,message_override:B||void 0,send_via:H}});if(Ee)throw new Error(Ee.message);ee({sent:(Ye==null?void 0:Ye.sent)??0,total:(Ye==null?void 0:Ye.total)??je.length}),u("done"),ae.success(`Sent ${(Ye==null?void 0:Ye.sent)??0} of ${(Ye==null?void 0:Ye.total)??je.length} videos`)}catch(je){ae.error((je==null?void 0:je.message)||"Failed to send"),u("compose")}}},[v,h,s,B,R,H,Q]),Ue=h.size,Be=oe.filter(je=>!je.email).length;return e.jsxs(zs,{open:o,onOpenChange:_e,children:[t&&e.jsx(yl,{asChild:!0,children:t}),e.jsxs(Rs,{className:"max-w-3xl max-h-[90vh] overflow-hidden flex flex-col",children:[e.jsx(Vs,{children:e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(ia,{className:"h-5 w-5 text-primary"}),"Send Recruiting Video",Ue>0&&e.jsxs(qe,{variant:"secondary",className:"ml-2",children:[e.jsx(Xn,{className:"h-3 w-3 mr-1"}),Ue," ",Ue===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(Yr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search prospects...",value:x,onChange:je=>y(je.target.value),className:"pl-9"})]}),e.jsxs(bs,{value:p,onValueChange:g,children:[e.jsx(ys,{className:"w-48",children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"all",children:"All stages"}),me.map(je=>e.jsx(We,{value:je.id,children:je.name},je.id))]})]})]}),e.jsxs("div",{className:"flex items-center justify-between text-xs text-muted-foreground",children:[e.jsxs("button",{onClick:Se,className:"hover:underline",children:[h.size===ve.length&&ve.length>0?"Deselect all":"Select all"," ","(",ve.length,")"]}),Be>0&&e.jsxs("span",{children:[Be," prospect(s) hidden — no email on file"]})]}),e.jsx(Eo,{className:"flex-1 border rounded-md",children:ve.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:ve.map(je=>{const Ye=h.has(je.id),Ee=me.find(Re=>Re.id===je.stage_id);return e.jsxs("label",{className:"flex items-center gap-3 p-3 hover:bg-muted/30 cursor-pointer",children:[e.jsx(Li,{checked:Ye,onCheckedChange:()=>he(je.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:[je.first_name," ",je.last_name]}),Ee&&e.jsx(qe,{variant:"outline",className:"text-[10px]",style:{borderColor:Ee.color,color:Ee.color},children:Ee.name})]}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[je.email," ",je.current_brokerage&&`· ${je.current_brokerage}`]})]})]},je.id)})})}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>_e(!1),children:"Cancel"}),e.jsx($,{disabled:Ue===0,onClick:()=>u("pick-video"),children:"Next: Choose Video"})]})]}),d==="pick-video"&&e.jsxs("div",{className:"flex-1 overflow-hidden flex flex-col",children:[e.jsxs(ya,{defaultValue:"record",className:"flex-1 flex flex-col overflow-hidden",children:[e.jsxs(va,{className:"self-start",children:[e.jsxs(is,{value:"record",children:[e.jsx(nn,{className:"h-3.5 w-3.5 mr-1"}),"Record New"]}),e.jsxs(is,{value:"library",children:[e.jsx(xb,{className:"h-3.5 w-3.5 mr-1"}),"Use Existing"]})]}),e.jsx(cs,{value:"record",className:"flex-1 overflow-auto",children:e.jsxs("div",{className:"text-center py-8 space-y-4",children:[e.jsx(em,{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 ",Ue," ",Ue===1?"recipient":"recipients"," — each gets their own tracked link."]})]}),e.jsxs($,{onClick:()=>u("record"),children:[e.jsx(ia,{className:"h-4 w-4 mr-2"}),"Start Recording"]})]})}),e.jsx(cs,{value:"library",className:"flex-1 overflow-auto",children:le.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:le.map(je=>e.jsxs("button",{onClick:()=>{_(je.id),C(je.title||"Untitled"),u("compose")},className:"text-left group rounded-md border overflow-hidden hover:border-primary transition-colors",children:[e.jsx("div",{className:"aspect-video bg-muted relative",children:v5(je)?e.jsx("img",{src:v5(je),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(ia,{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:je.title||"Untitled"})})]},je.id))})})]}),e.jsx(kr,{children:e.jsx($,{variant:"outline",onClick:()=>u("pick-recipients"),children:"Back"})})]}),d==="record"&&e.jsxs("div",{className:"flex-1 overflow-auto",children:[e.jsx(w6,{maxDurationSeconds:600,onRecordingComplete:Te}),e.jsx("div",{className:"mt-2 flex justify-start",children:e.jsx($,{variant:"ghost",size:"sm",onClick:()=>u("pick-video"),children:"← Back"})})]}),(d==="uploading"||d==="processing")&&e.jsxs("div",{className:"py-12 space-y-4 text-center",children:[e.jsx(Jt,{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(ho,{value:d==="uploading"?A:I,className:"mx-auto max-w-sm"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[Math.round(d==="uploading"?A:I),"%"]})]}),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(Gr,{className:"h-4 w-4 text-primary"}),e.jsxs("div",{className:"flex-1 text-sm",children:[e.jsx("span",{className:"font-medium",children:j})," selected · sending to ",e.jsx("strong",{children:Ue})," recipient",Ue===1?"":"s"]})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Subject (optional override)"}),e.jsx(be,{value:R,onChange:je=>O(je.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(re,{className:"text-xs",children:"Personal message shown in the email & on the landing page"}),e.jsx(Ls,{value:B,onChange:je=>U(je.target.value),placeholder:"Hey there — wanted to share a quick thought on what we're building here...",rows:5,className:"mt-1"})]}),e.jsx(vQe,{value:H,onChange:Y}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>u("pick-video"),children:"Back"}),e.jsxs($,{onClick:Ie,disabled:!v||Ue===0,children:[e.jsx(Wr,{className:"h-4 w-4 mr-2"})," Send to ",Ue," ",Ue===1?"prospect":"prospects"]})]})]}),d==="sending"&&e.jsxs("div",{className:"py-12 text-center space-y-3",children:[e.jsx(Jt,{className:"h-8 w-8 animate-spin mx-auto text-primary"}),e.jsxs("p",{className:"font-medium",children:["Sending to ",Ue," recipient",Ue===1?"":"s","…"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Each prospect gets their own tracked share link."})]}),d==="done"&&se&&e.jsxs("div",{className:"py-12 text-center space-y-4",children:[e.jsx("div",{className:`h-16 w-16 rounded-full mx-auto flex items-center justify-center ${se.sent===se.total?"bg-primary/10":"bg-muted"}`,children:se.sent===se.total?e.jsx(Gr,{className:"h-8 w-8 text-primary"}):e.jsx(Ho,{className:"h-8 w-8 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsxs("p",{className:"font-semibold text-lg",children:[se.sent," of ",se.total," sent"]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"View engagement under the Video Outreach tab."})]}),e.jsx($,{onClick:()=>_e(!1),children:"Done"})]})]})]})}function gOn(s){if(!s)return"—";const t=Math.floor(s/60),n=s%60;return t>0?`${t}m ${n}s`:`${n}s`}function xOn({video:s}){return s.cta_clicked_at?e.jsx(qe,{className:"bg-emerald-500/10 text-emerald-600 border-emerald-200",children:"CTA Clicked"}):s.view_count>0?e.jsxs(qe,{className:"bg-blue-500/10 text-blue-600 border-blue-200",children:[e.jsx(ba,{className:"h-3 w-3 mr-1"}),s.view_count," views"]}):s.sent_at?e.jsxs(qe,{variant:"secondary",children:[e.jsx(Wr,{className:"h-3 w-3 mr-1"}),"Sent"]}):e.jsxs(qe,{variant:"outline",children:[e.jsx(sa,{className:"h-3 w-3 mr-1"}),"Draft"]})}function FVt({brokerageId:s}){var j,C,A,M;const{data:t=[],isLoading:n}=rOn(s),{data:r=[]}=SVt(s),a=iOn(),i=oOn(),l=kVt(),[o,c]=k.useState(""),[d,u]=k.useState(!1),[h,m]=k.useState({title:"",script_text:"",category:"general"}),[p,g]=k.useState(null),x=t.filter(I=>{var R,O,B,U;return o?`${((R=I.prospect)==null?void 0:R.first_name)||""} ${((O=I.prospect)==null?void 0:O.last_name)||""}`.toLowerCase().includes(o.toLowerCase())||((U=(B=I.video)==null?void 0:B.title)==null?void 0:U.toLowerCase().includes(o.toLowerCase())):!0}),y={total:t.length,sent:t.filter(I=>I.sent_at).length,viewed:t.filter(I=>I.view_count>0).length,ctaClicked:t.filter(I=>I.cta_clicked_at).length},v=k.useCallback(I=>{if(!I)return;const P=`${window.location.origin}/recruit-video/${I}`;navigator.clipboard.writeText(P),ae.success("Share link copied")},[]);k.useCallback((I,P)=>{l.mutate({id:I,sent_via:P})},[l]);const _=()=>{!h.title.trim()||!h.script_text.trim()||a.mutate({brokerage_id:s,...h},{onSuccess:()=>{m({title:"",script_text:"",category:"general"}),u(!1)}})};return e.jsxs("div",{className:"space-y-6",children:[e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[{label:"Total Videos",value:y.total,icon:ia,color:"text-primary"},{label:"Sent",value:y.sent,icon:Wr,color:"text-blue-500"},{label:"Viewed",value:y.viewed,icon:ba,color:"text-amber-500"},{label:"CTA Clicked",value:y.ctaClicked,icon:Gr,color:"text-emerald-500"}].map(I=>e.jsx(we,{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 ${I.color}`,children:e.jsx(I.icon,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:I.value}),e.jsx("p",{className:"text-xs text-muted-foreground",children:I.label})]})]})},I.label))}),e.jsxs(ya,{defaultValue:"videos",className:"space-y-4",children:[e.jsxs(va,{children:[e.jsxs(is,{value:"videos",children:[e.jsx(ia,{className:"h-4 w-4 mr-1.5"}),"All Videos"]}),e.jsxs(is,{value:"scripts",children:[e.jsx(ea,{className:"h-4 w-4 mr-1.5"}),"Script Library"]}),e.jsxs(is,{value:"analytics",children:[e.jsx(Ul,{className:"h-4 w-4 mr-1.5"}),"Engagement"]})]}),e.jsx(cs,{value:"videos",children:e.jsxs(we,{children:[e.jsx(Vt,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between gap-2 flex-wrap",children:[e.jsx(Yt,{className:"text-lg",children:"Video Outreach"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"relative w-64",children:[e.jsx(Yr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search by name or title...",value:o,onChange:I=>c(I.target.value),className:"pl-9"})]}),e.jsx(OVt,{brokerageId:s,trigger:e.jsxs($,{size:"sm",className:"gap-1.5",children:[e.jsx(pn,{className:"h-4 w-4"})," Send Video Email"]})})]})]})}),e.jsx(De,{children:n?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):x.length===0?e.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[e.jsx(ia,{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:x.map(I=>{var P,R,O,B,U,G,H;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:[v5(I.video)?e.jsx("img",{src:v5(I.video),alt:"",className:"h-full w-full object-cover",referrerPolicy:"no-referrer"}):e.jsx("div",{className:"h-full w-full flex items-center justify-center",children:e.jsx(ia,{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:gOn(((P=I.video)==null?void 0:P.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:[(R=I.prospect)==null?void 0:R.first_name," ",(O=I.prospect)==null?void 0:O.last_name]}),e.jsx(xOn,{video:I})]}),e.jsx("p",{className:"text-sm text-muted-foreground truncate",children:((B=I.video)==null?void 0:B.title)||"Untitled video"}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5",children:[Ys(new Date(I.created_at),"MMM d, yyyy"),((U=I.prospect)==null?void 0:U.current_brokerage)&&` · ${I.prospect.current_brokerage}`]})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>v(I.share_token),title:"Copy share link",children:e.jsx(Da,{className:"h-4 w-4"})}),e.jsxs($,{variant:I.sent_at?"ghost":"default",size:"sm",className:"h-8 gap-1.5",onClick:()=>g(I),disabled:!((G=I.prospect)!=null&&G.email),title:(H=I.prospect)!=null&&H.email?"Email this video to the prospect":"Prospect has no email",children:[e.jsx(pn,{className:"h-4 w-4"}),I.sent_at?"Resend":"Email"]}),I.share_token&&e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>window.open(`/recruit-video/${I.share_token}`,"_blank"),title:"Preview landing page",children:e.jsx(Ir,{className:"h-4 w-4"})})]})]},I.id)})})})]})}),e.jsx(cs,{value:"scripts",children:e.jsxs(we,{children:[e.jsx(Vt,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(Yt,{className:"text-lg",children:"Recruiting Scripts"}),e.jsxs(zs,{open:d,onOpenChange:u,children:[e.jsx(yl,{asChild:!0,children:e.jsxs($,{size:"sm",children:[e.jsx(nn,{className:"h-4 w-4 mr-1.5"}),"New Script"]})}),e.jsxs(Rs,{children:[e.jsx(Vs,{children:e.jsx($s,{children:"Create Recruiting Script"})}),e.jsxs("div",{className:"space-y-4 mt-2",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Title"}),e.jsx(be,{value:h.title,onChange:I=>m(P=>({...P,title:I.target.value})),placeholder:"e.g., Why Switch to Our Brokerage"})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Category"}),e.jsxs(bs,{value:h.category,onValueChange:I=>m(P=>({...P,category:I})),children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsx(vs,{children:eqe.map(I=>e.jsx(We,{value:I.value,children:I.label},I.value))})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Script"}),e.jsx(Ls,{value:h.script_text,onChange:I=>m(P=>({...P,script_text:I.target.value})),placeholder:"Hi [Name], I noticed you've been doing great work at [Brokerage]...",rows:8})]}),e.jsx($,{onClick:_,disabled:!h.title.trim()||!h.script_text.trim(),className:"w-full",children:"Save Script"})]})]})]})]})}),e.jsx(De,{children:r.length===0?e.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[e.jsx(ea,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{className:"font-medium",children:"No scripts yet"}),e.jsx("p",{className:"text-sm mt-1",children:"Create teleprompter scripts for common recruiting conversations"})]}):e.jsx("div",{className:"grid gap-3 md:grid-cols-2",children:r.map(I=>{var R;const P=((R=eqe.find(O=>O.value===I.category))==null?void 0:R.label)||I.category;return e.jsx(we,{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(qe,{variant:"outline",className:"text-[10px] mb-2",children:P}),e.jsx("h4",{className:"font-medium text-sm",children:I.title})]}),e.jsx($,{variant:"ghost",size:"icon",className:"h-7 w-7 opacity-0 group-hover:opacity-100 transition-opacity text-destructive",onClick:()=>i.mutate(I.id),children:e.jsx(Un,{className:"h-3.5 w-3.5"})})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-2 line-clamp-3",children:I.script_text}),I.is_global&&e.jsx(qe,{variant:"secondary",className:"mt-2 text-[10px]",children:"Template"})]})},I.id)})})})]})}),e.jsx(cs,{value:"analytics",children:e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsx(Yt,{className:"text-lg",children:"Engagement Funnel"})}),e.jsxs(De,{children:[e.jsx("div",{className:"space-y-4",children:[{label:"Videos Created",count:y.total,pct:100,color:"bg-primary"},{label:"Sent to Prospects",count:y.sent,pct:y.total?Math.round(y.sent/y.total*100):0,color:"bg-blue-500"},{label:"Viewed by Prospect",count:y.viewed,pct:y.sent?Math.round(y.viewed/y.sent*100):0,color:"bg-amber-500"},{label:"CTA Clicked",count:y.ctaClicked,pct:y.viewed?Math.round(y.ctaClicked/y.viewed*100):0,color:"bg-emerald-500"}].map(I=>e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{children:I.label}),e.jsxs("span",{className:"font-medium",children:[I.count," (",I.pct,"%)"]})]}),e.jsx("div",{className:"h-3 bg-muted rounded-full overflow-hidden",children:e.jsx("div",{className:`h-full ${I.color} rounded-full transition-all`,style:{width:`${I.pct}%`}})})]},I.label))}),t.filter(I=>I.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(I=>I.view_count>0).sort((I,P)=>P.view_count-I.view_count).slice(0,5).map(I=>{var P,R;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:[(P=I.prospect)==null?void 0:P.first_name," ",(R=I.prospect)==null?void 0:R.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(ba,{className:"h-3.5 w-3.5"})," ",I.view_count]}),I.cta_clicked_at&&e.jsx(Gr,{className:"h-4 w-4 text-emerald-500"})]})]},I.id)})})]})]})]})})]}),p&&e.jsx(jVt,{open:!!p,onOpenChange:I=>{I||g(null)},recruitVideoId:p.id,brokerageId:s,prospectName:`${((j=p.prospect)==null?void 0:j.first_name)||""} ${((C=p.prospect)==null?void 0:C.last_name)||""}`.trim(),prospectEmail:(A=p.prospect)==null?void 0:A.email,videoTitle:(M=p.video)==null?void 0:M.title,defaultMessage:p.message})]})}function zVt({brokerageId:s}){const{toast:t}=Fi(),n=ls(),{stages:r,prospects:a}=wte(s),[i,l]=k.useState(!1),[o,c]=k.useState({title:"",target_count:"10",target_stage_id:"",period_start:Ys(new Date,"yyyy-MM-dd"),period_end:Ys(new Date(new Date().getFullYear(),new Date().getMonth()+3,0),"yyyy-MM-dd")}),{data:d=[],isLoading:u}=pt({queryKey:["recruit-goals",s],queryFn:async()=>{const{data:g,error:x}=await V.from("recruit_goals").select("*").eq("brokerage_id",s).order("period_end",{ascending:!1});if(x)throw x;return g}}),h=Nt({mutationFn:async g=>{const{data:{user:x}}=await V.auth.getUser();if(!x)throw new Error("Not authenticated");const{error:y}=await V.from("recruit_goals").insert({brokerage_id:s,title:g.title,target_count:parseInt(g.target_count),target_stage_id:g.target_stage_id||null,period_start:g.period_start,period_end:g.period_end,created_by:x.id});if(y)throw y},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-goals",s]}),t({title:"Goal created"}),l(!1)},onError:g=>t({title:"Error",description:g.message,variant:"destructive"})}),m=Nt({mutationFn:async g=>{const{error:x}=await V.from("recruit_goals").delete().eq("id",g);if(x)throw x},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-goals",s]}),t({title:"Goal removed"})}}),p=g=>{const x=r.find(v=>v.id===g.target_stage_id);return{count:a.filter(v=>$N(new Date(v.created_at),{start:new Date(g.period_start),end:new Date(g.period_end)})?g.target_stage_id?v.stage_id===g.target_stage_id:!0:!1).length,stage:x}};return u?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx("div",{className:"h-6 w-6 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:[d.length," goal",d.length!==1?"s":""]}),e.jsxs($,{size:"sm",onClick:()=>l(!0),children:[e.jsx(nn,{className:"h-4 w-4 mr-1"})," New Goal"]})]}),d.length===0?e.jsxs(we,{className:"py-12 text-center",children:[e.jsx(_h,{className:"h-10 w-10 mx-auto text-muted-foreground mb-3"}),e.jsx("p",{className:"text-muted-foreground",children:"No goals set. Create a recruiting target to track progress."})]}):e.jsx("div",{className:"grid md:grid-cols-2 gap-4",children:d.map(g=>{const{count:x,stage:y}=p(g),v=Math.min(100,x/g.target_count*100),_=$N(new Date,{start:new Date(g.period_start),end:new Date(g.period_end)});return e.jsxs(we,{className:_?"":"opacity-60",children:[e.jsx(Vt,{className:"pb-2",children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{children:[e.jsx(Yt,{className:"text-sm",children:g.title}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5",children:[Ys(new Date(g.period_start),"MMM d")," – ",Ys(new Date(g.period_end),"MMM d, yyyy")]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[_?e.jsx(qe,{className:"text-[10px]",children:"Active"}):e.jsx(qe,{variant:"secondary",className:"text-[10px]",children:"Ended"}),e.jsx($,{variant:"ghost",size:"icon",className:"h-6 w-6 text-muted-foreground",onClick:()=>m.mutate(g.id),children:e.jsx(Un,{className:"h-3.5 w-3.5"})})]})]})}),e.jsxs(De,{className:"space-y-2",children:[y&&e.jsxs(qe,{variant:"outline",className:"text-[10px]",style:{borderColor:y.color,color:y.color},children:["Stage: ",y.name]}),e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsx("span",{className:"font-bold text-lg",children:x}),e.jsxs("span",{className:"text-muted-foreground",children:["/ ",g.target_count]})]}),e.jsx(ho,{value:v,className:"h-2"}),e.jsxs("p",{className:"text-xs text-muted-foreground text-right",children:[v.toFixed(0),"% complete"]})]})]},g.id)})}),e.jsx(zs,{open:i,onOpenChange:l,children:e.jsxs(Rs,{children:[e.jsx(Vs,{children:e.jsx($s,{children:"Create Recruiting Goal"})}),e.jsxs("form",{onSubmit:g=>{g.preventDefault(),h.mutate(o)},className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Goal Title *"}),e.jsx(be,{required:!0,value:o.title,onChange:g=>c(x=>({...x,title:g.target.value})),placeholder:"e.g. Q2 Recruiting Target"})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Target Count *"}),e.jsx(be,{type:"number",min:"1",required:!0,value:o.target_count,onChange:g=>c(x=>({...x,target_count:g.target.value}))})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Target Stage (optional)"}),e.jsxs("select",{className:"w-full rounded-md border border-input bg-background px-3 py-2 text-sm",value:o.target_stage_id,onChange:g=>c(x=>({...x,target_stage_id:g.target.value})),children:[e.jsx("option",{value:"",children:"All stages (total prospects)"}),r.map(g=>e.jsx("option",{value:g.id,children:g.name},g.id))]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Count prospects that reach this stage"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Start Date"}),e.jsx(be,{type:"date",required:!0,value:o.period_start,onChange:g=>c(x=>({...x,period_start:g.target.value}))})]}),e.jsxs("div",{children:[e.jsx(re,{children:"End Date"}),e.jsx(be,{type:"date",required:!0,value:o.period_end,onChange:g=>c(x=>({...x,period_end:g.target.value}))})]})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx($,{type:"button",variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsx($,{type:"submit",disabled:h.isPending,children:"Create Goal"})]})]})]})})]})}const yOn={first_name:"Sarah",brokerage_name:"ABC Realty",city:"Austin",sender_name:"Jeremy"};function BVt({email:s,mergeValues:t=yOn,selectedSubjectIndex:n,onClose:r}){var c;const a=d=>d.replace(/\{\{first_name\}\}/g,t.first_name).replace(/\{\{brokerage_name\}\}/g,t.brokerage_name).replace(/\{\{city\}\}/g,t.city).replace(/\{\{sender_name\}\}/g,t.sender_name).replace(/\{\{landing_page_link\}\}/g,"https://bestbrokerage.relevelup.com/join-brokerage/your-slug"),i=((c=s.subject_line_options)==null?void 0:c.length)>0?s.subject_line_options:[s.subject_line],l=n??0,o=i[l]||s.subject_line;return e.jsx(zs,{open:!0,onOpenChange:()=>r(),children:e.jsxs(Rs,{className:"max-w-2xl max-h-[85vh] overflow-y-auto p-0",children:[e.jsxs(Vs,{className:"px-6 pt-6 pb-4 border-b",children:[e.jsxs($s,{className:"text-base",children:["Email #",s.email_number," — ",s.title]}),e.jsxs("div",{className:"flex items-center gap-3 mt-2",children:[e.jsxs(qe,{variant:"outline",className:"text-xs gap-1",children:[e.jsx(sa,{className:"h-3 w-3"}),s.email_number===1?"Sent immediately":`Day ${s.delay_days}`]}),i.length>1&&e.jsxs(qe,{variant:"secondary",className:"text-xs",children:[i.length," subject variants"]})]})]}),e.jsxs("div",{className:"space-y-0",children:[i.length>1&&e.jsxs("div",{className:"px-6 py-3 border-b bg-muted/20",children:[e.jsx("p",{className:"text-[10px] font-medium text-muted-foreground uppercase tracking-wider mb-2",children:"Subject Line Options"}),e.jsx("div",{className:"flex flex-col gap-1.5",children:i.map((d,u)=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:`text-[10px] font-bold uppercase px-1.5 py-0.5 rounded ${u===l?"bg-primary/10 text-primary":"bg-muted text-muted-foreground"}`,children:u===l?"Selected":u===0?"Primary":`Alt ${u}`}),e.jsx("span",{className:"text-sm",children:a(d)})]},u))})]}),e.jsxs("div",{className:"border-b",children:[e.jsxs("div",{className:"px-6 py-2 flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx("span",{className:"font-medium w-14",children:"From:"}),e.jsxs("span",{children:[t.sender_name," "]})]}),e.jsxs("div",{className:"px-6 py-2 flex items-center gap-2 text-xs text-muted-foreground border-t",children:[e.jsx("span",{className:"font-medium w-14",children:"To:"}),e.jsxs("span",{children:[t.first_name," "]})]}),e.jsxs("div",{className:"px-6 py-2 flex items-center gap-2 text-xs border-t",children:[e.jsx("span",{className:"font-medium w-14 text-muted-foreground",children:"Subject:"}),e.jsx("span",{className:"font-medium",children:a(o)})]})]}),e.jsx("div",{className:"bg-white px-8 py-6",children:e.jsx("div",{className:"prose prose-sm max-w-none [&_p]:my-3 [&_p+p]:mt-4 [&_br]:block [&_br]:mt-2",style:{fontSize:"15px",lineHeight:"1.75",color:"#1a1a1a"},dangerouslySetInnerHTML:{__html:a(s.body_html)}})})]})]})})}function bQe({brokerageId:s}){const t=ls(),{user:n}=ks(),[r,a]=k.useState(""),[i,l]=k.useState(!1),[o,c]=k.useState({brokerage_id:s,sender_name:"LevelUp",sender_email:"recruiting@relevelup.com",reply_to_email:"",merge_fields:{city:"",broker_name:""}}),{data:d}=pt({queryKey:["brokerage-recruit-settings",s],queryFn:async()=>{const{data:g,error:x}=await V.from("brokerage_recruit_settings").select("*").eq("brokerage_id",s).maybeSingle();if(x)throw x;return g}}),{data:u}=pt({queryKey:["brokerage-detail",s],queryFn:async()=>{const{data:g,error:x}=await V.from("brokerages").select("name, city, state").eq("id",s).single();if(x)throw x;return g}});k.useEffect(()=>{d?c({...d,merge_fields:d.merge_fields||{city:"",broker_name:""}}):u&&c(g=>({...g,merge_fields:{...g.merge_fields,brokerage_name:u.name,city:u.city||""}}))},[d,u]),k.useEffect(()=>{n!=null&&n.id&&V.from("profiles").select("recruit_cta_url").eq("id",n.id).single().then(({data:g})=>a((g==null?void 0:g.recruit_cta_url)||""))},[n==null?void 0:n.id]);const h=async()=>{if(!(n!=null&&n.id))return;l(!0);const{error:g}=await V.from("profiles").update({recruit_cta_url:r.trim()||null}).eq("id",n.id);l(!1),g?ae.error(g.message):ae.success("Scheduling link saved!")},m=Nt({mutationFn:async()=>{const g={brokerage_id:s,sender_name:o.sender_name,sender_email:o.sender_email,reply_to_email:o.reply_to_email||null,merge_fields:o.merge_fields,updated_at:new Date().toISOString()};if(d!=null&&d.id){const{error:x}=await V.from("brokerage_recruit_settings").update(g).eq("id",d.id);if(x)throw x}else{const{error:x}=await V.from("brokerage_recruit_settings").insert(g);if(x)throw x}},onSuccess:()=>{t.invalidateQueries({queryKey:["brokerage-recruit-settings",s]}),ae.success("Recruiting email settings saved!")},onError:g=>ae.error(g.message)}),p=(g,x)=>{c(y=>({...y,merge_fields:{...y.merge_fields,[g]:x}}))};return e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Configure the sender identity and merge fields for recruiting emails sent to this brokerage's prospects."}),e.jsxs("div",{className:"rounded-lg border bg-muted/30 p-4 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ha,{className:"h-4 w-4 text-primary"}),e.jsx("p",{className:"text-sm font-medium",children:"Your Scheduling Link"})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["This URL powers the ",e.jsx("strong",{children:'"Schedule a Conversation"'})," button on every recruiting video page you send. Paste your Calendly, HubSpot Meetings, Google Calendar booking link, etc."]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(be,{value:r,onChange:g=>a(g.target.value),placeholder:"https://calendly.com/your-name/intro"}),e.jsxs($,{onClick:h,disabled:i,size:"sm",children:[e.jsx(Ml,{className:"h-4 w-4 mr-1"})," Save"]})]}),!r&&e.jsx("p",{className:"text-xs text-amber-600",children:"⚠️ No link set — the CTA button will be hidden on your video pages until you add one."})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(re,{className:"text-xs",children:"Sender Display Name"}),e.jsx(be,{value:o.sender_name,onChange:g=>c({...o,sender_name:g.target.value}),placeholder:"e.g. Jeremy at LevelUp"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(re,{className:"text-xs",children:"Sender Email Address"}),e.jsx(be,{value:o.sender_email,onChange:g=>c({...o,sender_email:g.target.value}),placeholder:"recruiting@relevelup.com"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Must be a verified SES identity. Verify your own address below to send from it."})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(re,{className:"text-xs",children:"Reply-To Email (optional)"}),e.jsx(be,{value:o.reply_to_email,onChange:g=>c({...o,reply_to_email:g.target.value}),placeholder:"jeremy@relevelup.com"})]})]}),e.jsxs("div",{className:"border-t pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(b0,{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(gVt,{brokerageId:s,onVerifiedSelect:g=>{c(x=>({...x,sender_email:g})),ae.success(`Sender set to ${g}`)}})]}),e.jsxs("div",{className:"border-t pt-4",children:[e.jsx("p",{className:"text-sm font-medium mb-3",children:"Default Merge Fields"}),e.jsx("p",{className:"text-xs text-muted-foreground mb-3",children:"These values will auto-fill in campaign emails for this brokerage."}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(re,{className:"text-xs",children:"{{brokerage_name}}"}),e.jsx(be,{value:o.merge_fields.brokerage_name||"",onChange:g=>p("brokerage_name",g.target.value),placeholder:(u==null?void 0:u.name)||"Brokerage Name"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(re,{className:"text-xs",children:"{{city}}"}),e.jsx(be,{value:o.merge_fields.city||"",onChange:g=>p("city",g.target.value),placeholder:"e.g. Austin"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(re,{className:"text-xs",children:"{{sender_name}}"}),e.jsx(be,{value:o.merge_fields.sender_name||"",onChange:g=>p("sender_name",g.target.value),placeholder:"e.g. Jeremy"})]})]})]}),e.jsxs($,{onClick:()=>m.mutate(),disabled:m.isPending,className:"w-full",children:[e.jsx(Ml,{className:"h-4 w-4 mr-1"})," Save Settings"]})]})}const vOn=yk.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",cp(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()}}}),ybt=[{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 F0({onClick:s,active:t,disabled:n,icon:r,tooltip:a}){return e.jsxs(Lx,{children:[e.jsx(Rx,{asChild:!0,children:e.jsx($,{type:"button",variant:"ghost",size:"sm",onClick:s,disabled:n,className:`h-8 w-8 p-0 ${t?"bg-accent text-accent-foreground":"text-muted-foreground hover:text-foreground"}`,children:e.jsx(r,{className:"h-4 w-4"})})}),e.jsx(Jg,{side:"bottom",className:"text-xs",children:a})]})}function bOn({content:s,onChange:t}){const n=QWe({extensions:[eKe.configure({heading:{levels:[1,2,3]}}),vOn,dKe.configure({openOnClick:!1,HTMLAttributes:{class:"text-primary underline cursor-pointer"}}),uKe.configure({types:["heading","paragraph"]}),hKe,VFt],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(()=>{n&&s!==n.getHTML()&&n.commands.setContent(s)},[s,n]);const r=k.useCallback(()=>{if(!n)return;const i=n.getAttributes("link").href,l=window.prompt("Enter URL",i);if(l!==null){if(l===""){n.chain().focus().extendMarkRange("link").unsetLink().run();return}n.chain().focus().extendMarkRange("link").setLink({href:l}).run()}},[n]),a=k.useCallback(i=>{n&&n.chain().focus().insertContent(`{{${i}}}`).run()},[n]);return n?e.jsx(Sk,{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(F0,{onClick:()=>n.chain().focus().toggleBold().run(),active:n.isActive("bold"),icon:zT,tooltip:"Bold"}),e.jsx(F0,{onClick:()=>n.chain().focus().toggleItalic().run(),active:n.isActive("italic"),icon:GT,tooltip:"Italic"}),e.jsx(F0,{onClick:()=>n.chain().focus().toggleUnderline().run(),active:n.isActive("underline"),icon:pB,tooltip:"Underline"}),e.jsx(F0,{onClick:()=>n.chain().focus().toggleStrike().run(),active:n.isActive("strike"),icon:JK,tooltip:"Strikethrough"}),e.jsx(Pc,{orientation:"vertical",className:"mx-1 h-6"}),e.jsx(F0,{onClick:()=>n.chain().focus().toggleHeading({level:1}).run(),active:n.isActive("heading",{level:1}),icon:Vz,tooltip:"Heading 1"}),e.jsx(F0,{onClick:()=>n.chain().focus().toggleHeading({level:2}).run(),active:n.isActive("heading",{level:2}),icon:Hz,tooltip:"Heading 2"}),e.jsx(F0,{onClick:()=>n.chain().focus().toggleHeading({level:3}).run(),active:n.isActive("heading",{level:3}),icon:LK,tooltip:"Heading 3"}),e.jsx(Pc,{orientation:"vertical",className:"mx-1 h-6"}),e.jsx(F0,{onClick:()=>n.chain().focus().toggleBulletList().run(),active:n.isActive("bulletList"),icon:Sy,tooltip:"Bullet List"}),e.jsx(F0,{onClick:()=>n.chain().focus().toggleOrderedList().run(),active:n.isActive("orderedList"),icon:_2,tooltip:"Numbered List"}),e.jsx(F0,{onClick:()=>n.chain().focus().toggleBlockquote().run(),active:n.isActive("blockquote"),icon:ik,tooltip:"Blockquote"}),e.jsx(F0,{onClick:()=>n.chain().focus().setHorizontalRule().run(),icon:ak,tooltip:"Divider"}),e.jsx(Pc,{orientation:"vertical",className:"mx-1 h-6"}),e.jsx(F0,{onClick:()=>n.chain().focus().setTextAlign("left").run(),active:n.isActive({textAlign:"left"}),icon:M8,tooltip:"Align Left"}),e.jsx(F0,{onClick:()=>n.chain().focus().setTextAlign("center").run(),active:n.isActive({textAlign:"center"}),icon:T8,tooltip:"Align Center"}),e.jsx(F0,{onClick:()=>n.chain().focus().setTextAlign("right").run(),active:n.isActive({textAlign:"right"}),icon:P8,tooltip:"Align Right"}),e.jsx(Pc,{orientation:"vertical",className:"mx-1 h-6"}),e.jsx(F0,{onClick:r,active:n.isActive("link"),icon:od,tooltip:"Insert Link"}),e.jsx(Pc,{orientation:"vertical",className:"mx-1 h-6"}),e.jsx(F0,{onClick:()=>n.chain().focus().undo().run(),disabled:!n.can().undo(),icon:rM,tooltip:"Undo"}),e.jsx(F0,{onClick:()=>n.chain().focus().redo().run(),disabled:!n.can().redo(),icon:JT,tooltip:"Redo"}),e.jsx("div",{className:"flex-1"}),e.jsx($,{type:"button",variant:"outline",size:"sm",className:"h-8 gap-1.5 text-xs font-medium",onClick:()=>{n&&n.chain().focus().insertContent('

Learn More About Us

').run()},children:"🔘 CTA Button"}),e.jsxs(Au,{children:[e.jsx(Eu,{asChild:!0,children:e.jsxs($,{type:"button",variant:"outline",size:"sm",className:"h-8 gap-1.5 text-xs font-medium",children:[e.jsx(xB,{className:"h-3.5 w-3.5"}),"Merge Tags"]})}),e.jsx(gu,{align:"end",className:"w-56",children:ybt.map(i=>e.jsxs(Pa,{onClick:()=>a(i.key),className:"flex flex-col items-start gap-0.5",children:[e.jsx("span",{className:"font-medium text-sm",children:i.label}),e.jsx("span",{className:"text-xs text-muted-foreground font-mono",children:`{{${i.key}}}`})]},i.key))})]})]}),e.jsx("div",{className:"bg-white",children:e.jsx(ZWe,{editor:n,className:"[&_.ProseMirror]:outline-none [&_.ProseMirror]:min-h-[350px] [&_.ProseMirror_p]:my-3 [&_.ProseMirror_ul]:my-3 [&_.ProseMirror_ol]:my-3 [&_.ProseMirror_blockquote]:my-3 [&_.ProseMirror_h1]:my-4 [&_.ProseMirror_h2]:my-3 [&_.ProseMirror_h3]:my-2"})}),e.jsx("div",{className:"border-t px-4 py-2.5 bg-muted/20",children:e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground font-medium",children:"Tags:"}),ybt.map(i=>e.jsx(qe,{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 _On({open:s,onClose:t,campaignName:n,stat:r}){return e.jsx(zs,{open:s,onOpenChange:a=>!a&&t(),children:e.jsxs(Rs,{className:"max-w-3xl max-h-[85vh] overflow-y-auto",children:[e.jsxs(Vs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(mc,{className:"h-5 w-5 text-primary"}),n," — Engagement Stats"]}),e.jsx(Cr,{children:"Per-email breakdown of sends, opens, and clicks for this campaign at your brokerage."})]}),!r||r.sent===0?e.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[e.jsx(Wr,{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(Xae,{icon:pn,color:"text-blue-500",label:"Total Sent",value:r.sent.toLocaleString()}),e.jsx(Xae,{icon:ba,color:"text-amber-500",label:"Opens",value:`${r.opened.toLocaleString()}`,sub:`${r.openRate.toFixed(1)}% open rate`}),e.jsx(Xae,{icon:rh,color:"text-green-500",label:"Clicks",value:`${r.clicked.toLocaleString()}`,sub:`${r.clickRate.toFixed(1)}% click rate`}),e.jsx(Xae,{icon:Gd,color:"text-destructive",label:"Failed",value:r.failed.toLocaleString()})]}),r.lastSentAt&&e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center gap-1.5",children:[e.jsx(sa,{className:"h-3 w-3"})," Last sent: ",Ys(new Date(r.lastSentAt),"MMM d, yyyy h:mm a")]}),e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-semibold mb-2 mt-4",children:"Per-Email Performance"}),e.jsx("div",{className:"space-y-2",children:r.byEmail.map(a=>{const i=a.sent_count>0?a.opened_count/a.sent_count*100:0,l=a.sent_count>0?a.clicked_count/a.sent_count*100:0;return e.jsx(we,{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(qe,{variant:"outline",className:"text-[10px] gap-1",children:[e.jsx(pn,{className:"h-2.5 w-2.5"})," ",a.sent_count.toLocaleString()," sent"]}),e.jsxs(qe,{variant:"outline",className:"text-[10px] gap-1 border-amber-500/30 text-amber-600",children:[e.jsx(ba,{className:"h-2.5 w-2.5"})," ",a.opened_count.toLocaleString()," (",i.toFixed(1),"%)"]}),e.jsxs(qe,{variant:"outline",className:"text-[10px] gap-1 border-green-500/30 text-green-600",children:[e.jsx(rh,{className:"h-2.5 w-2.5"})," ",a.clicked_count.toLocaleString()," (",l.toFixed(1),"%)"]}),a.failed_count>0&&e.jsxs(qe,{variant:"outline",className:"text-[10px] gap-1 border-destructive/30 text-destructive",children:[e.jsx(Gd,{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 Xae({icon:s,color:t,label:n,value:r,sub:a}){return e.jsx(we,{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:r}),e.jsx("p",{className:"text-[10px] text-muted-foreground mt-1",children:n}),a&&e.jsx("p",{className:"text-[10px] text-muted-foreground",children:a})]})]})})})}function $Vt(s){return pt({queryKey:["recruit-campaign-stats",s],enabled:!!s,staleTime:6e4,queryFn:async()=>{const{data:t,error:n}=await V.from("recruit_campaign_email_stats").select("*").eq("brokerage_id",s);if(n)throw n;const r=t??[],a={};for(const i of r){a[i.campaign_id]||(a[i.campaign_id]={campaign_id:i.campaign_id,sent:0,opened:0,clicked:0,failed:0,openRate:0,clickRate:0,byEmail:[],lastSentAt:null});const l=a[i.campaign_id];l.sent+=i.sent_count,l.opened+=i.opened_count,l.clicked+=i.clicked_count,l.failed+=i.failed_count,l.byEmail.push(i),i.last_sent_at&&(!l.lastSentAt||i.last_sent_at>l.lastSentAt)&&(l.lastSentAt=i.last_sent_at)}return Object.values(a).forEach(i=>{i.openRate=i.sent>0?i.opened/i.sent*100:0,i.clickRate=i.sent>0?i.clicked/i.sent*100:0,i.byEmail.sort((l,o)=>l.email_number-o.email_number)}),a}})}const vbt={cold:{icon:Hw,color:"text-blue-500",bg:"bg-blue-50 dark:bg-blue-950/30",label:"Cold — Curiosity"},warm:{icon:S2,color:"text-amber-500",bg:"bg-amber-50 dark:bg-amber-950/30",label:"Warm — Growth"},hot:{icon:iu,color:"text-red-500",bg:"bg-red-50 dark:bg-red-950/30",label:"Hot — Private Invite"}};function UVt({brokerageId:s}){var Se,Te,Ie,Ue;const{user:t}=ks(),n=ls(),[r,a]=k.useState(null),[i,l]=k.useState(null),[o,c]=k.useState(null),[d,u]=k.useState(!1),[h,m]=k.useState(!1),[p,g]=k.useState("editor"),[x,y]=k.useState(null),[v,_]=k.useState(null),{data:j={}}=$Vt(s),[C,A]=k.useState({name:"",description:"",theme:"",goal:"",primary_cta:"Learn more",warmth_level:"warm",sender_name:"",sender_email:"",reply_to_email:""}),{data:M}=pt({queryKey:["brokerage-detail",s],queryFn:async()=>{const{data:Be,error:je}=await V.from("brokerages").select("name, city, state").eq("id",s).single();if(je)throw je;return Be}}),{data:I}=pt({queryKey:["brokerage-recruit-settings",s],queryFn:async()=>{const{data:Be,error:je}=await V.from("brokerage_recruit_settings").select("*").eq("brokerage_id",s).maybeSingle();if(je)throw je;return Be}}),P={first_name:"Sarah",brokerage_name:((Se=I==null?void 0:I.merge_fields)==null?void 0:Se.brokerage_name)||(M==null?void 0:M.name)||"Your Brokerage",city:((Te=I==null?void 0:I.merge_fields)==null?void 0:Te.city)||(M==null?void 0:M.city)||"Your City",sender_name:((Ie=I==null?void 0:I.merge_fields)==null?void 0:Ie.sender_name)||(I==null?void 0:I.sender_name)||"Your Name"},R=Be=>Be.replace(/\{\{first_name\}\}/g,P.first_name).replace(/\{\{brokerage_name\}\}/g,P.brokerage_name).replace(/\{\{city\}\}/g,P.city).replace(/\{\{sender_name\}\}/g,P.sender_name),{data:O=[],isLoading:B}=pt({queryKey:["recruit-campaigns",s],queryFn:async()=>{const{data:Be,error:je}=await V.from("recruit_campaigns").select("*").or(`brokerage_id.is.null,brokerage_id.eq.${s}`).order("sort_order");if(je)throw je;return Be}}),{data:U={}}=pt({queryKey:["recruit-campaign-emails",s],enabled:O.length>0,queryFn:async()=>{const Be=O.map(Re=>Re.id),{data:je,error:Ye}=await V.from("recruit_campaign_emails").select("*").in("campaign_id",Be).order("email_number");if(Ye)throw Ye;const Ee={};return je.forEach(Re=>{Ee[Re.campaign_id]||(Ee[Re.campaign_id]=[]),Ee[Re.campaign_id].push(Re)}),Ee}}),G=Object.values(U).flat().map(Be=>Be.id),{data:H=[]}=pt({queryKey:["recruit-subject-overrides",s],enabled:G.length>0,queryFn:async()=>{const{data:Be,error:je}=await V.from("recruit_brokerage_subject_overrides").select("*").eq("brokerage_id",s);if(je)throw je;return Be}}),Y={};H.forEach(Be=>{Y[Be.campaign_email_id]=Be.selected_subject_index});const se=Nt({mutationFn:async({campaignEmailId:Be,selectedIndex:je})=>{const{error:Ye}=await V.from("recruit_brokerage_subject_overrides").upsert({brokerage_id:s,campaign_email_id:Be,selected_subject_index:je,updated_at:new Date().toISOString()},{onConflict:"brokerage_id,campaign_email_id"});if(Ye)throw Ye},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-subject-overrides",s]}),ae.success("Subject line updated for your brokerage")},onError:Be=>ae.error(Be.message)}),ee=Nt({mutationFn:async Be=>{const{error:je}=await V.from("recruit_campaign_emails").update({title:Be.title,subject_line:Be.subject_line,subject_line_options:Be.subject_line_options,body_html:Be.body_html,body_text:Be.body_text,delay_days:Be.delay_days,updated_at:new Date().toISOString()}).eq("id",Be.id);if(je)throw je},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-campaign-emails"]}),ae.success("Email template saved!"),l(null)},onError:Be=>ae.error(Be.message)}),oe=Nt({mutationFn:async()=>{const Be=C.name.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/(^-|-$)/g,""),{data:je,error:Ye}=await V.from("recruit_campaigns").insert({name:C.name,slug:Be,description:C.description||null,theme:C.theme||null,goal:C.goal||null,primary_cta:C.primary_cta||"Learn more",warmth_level:C.warmth_level,brokerage_id:s,created_by:t==null?void 0:t.id,sender_name:C.sender_name||null,sender_email:C.sender_email||null,reply_to_email:C.reply_to_email||null,is_active:!0,sort_order:O.length+1}).select().single();if(Ye)throw Ye;const Ee=[{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:Re}=await V.from("recruit_campaign_emails").insert(Ee.map(ke=>({campaign_id:je.id,...ke,body_html:"

Hi {{first_name}},

Write your message here...

Best,
{{sender_name}}

",body_text:"",subject_line_options:[],is_active:!0})));if(Re)throw Re;return je},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-campaigns"]}),n.invalidateQueries({queryKey:["recruit-campaign-emails"]}),ae.success("Campaign created with 4 starter emails!"),m(!1),A({name:"",description:"",theme:"",goal:"",primary_cta:"Learn more",warmth_level:"warm",sender_name:"",sender_email:"",reply_to_email:""})},onError:Be=>ae.error(Be.message)}),me=Nt({mutationFn:async Be=>{const{error:je}=await V.from("recruit_campaigns").update({name:Be.name,description:Be.description,theme:Be.theme,goal:Be.goal,primary_cta:Be.primary_cta,warmth_level:Be.warmth_level,sender_name:Be.sender_name,sender_email:Be.sender_email,reply_to_email:Be.reply_to_email,updated_at:new Date().toISOString()}).eq("id",Be.id);if(je)throw je},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-campaigns"]}),ae.success("Campaign settings saved!"),y(null)},onError:Be=>ae.error(Be.message)}),Q=Nt({mutationFn:async Be=>{var Fe,Oe;const{data:je}=await V.from("recruit_campaign_emails").select("email_number, delay_days").eq("campaign_id",Be).order("email_number",{ascending:!1}).limit(1),Ye=((Fe=je==null?void 0:je[0])==null?void 0:Fe.email_number)??0,Ee=((Oe=je==null?void 0:je[0])==null?void 0:Oe.delay_days)??0,Re=Ye+1,{error:ke}=await V.from("recruit_campaign_emails").insert({campaign_id:Be,email_number:Re,title:`Email ${Re}`,subject_line:"Hey {{first_name}}",subject_line_options:[],body_html:"

Hi {{first_name}},

Write your message here...

Best,
{{sender_name}}

",body_text:"",delay_days:Ee+7,is_active:!0});if(ke)throw ke},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-campaign-emails"]}),ae.success("Email added to campaign!")},onError:Be=>ae.error(Be.message)}),te=Nt({mutationFn:async Be=>{const{error:je}=await V.from("recruit_campaigns").delete().eq("id",Be);if(je)throw je},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-campaigns"]}),n.invalidateQueries({queryKey:["recruit-campaign-emails"]}),ae.success("Campaign deleted")},onError:Be=>ae.error(Be.message)}),le=Nt({mutationFn:async Be=>{const{error:je}=await V.from("recruit_campaign_emails").delete().eq("id",Be);if(je)throw je},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-campaign-emails"]}),ae.success("Email removed from campaign")},onError:Be=>ae.error(Be.message)}),fe=Nt({mutationFn:async({emailId:Be,delay_days:je})=>{const{error:Ye}=await V.from("recruit_campaign_emails").update({delay_days:je,updated_at:new Date().toISOString()}).eq("id",Be);if(Ye)throw Ye},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-campaign-emails"]}),ae.success("Send delay updated")},onError:Be=>ae.error(Be.message)});if(B)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 _e=O.filter(Be=>!Be.brokerage_id),ve=O.filter(Be=>Be.brokerage_id===s);return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-xl font-bold",children:"Recruiting Campaigns"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"System campaigns + custom campaigns · Each can have its own email settings"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs($,{variant:"outline",size:"sm",onClick:()=>u(!0),className:"gap-1.5",children:[e.jsx(Yc,{className:"h-4 w-4"})," Default Settings"]}),e.jsxs($,{size:"sm",onClick:()=>m(!0),className:"gap-1.5",children:[e.jsx(nn,{className:"h-4 w-4"})," New Campaign"]})]})]}),e.jsx(we,{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(kn,{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(Yc,{className:"inline h-3.5 w-3.5"})," icon on any campaign to customize."]})]})]})})}),ve.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(OK,{className:"h-4 w-4"})," Your Custom Campaigns"]}),e.jsx("div",{className:"space-y-3",children:ve.map(Be=>he(Be,!0))})]}),_e.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(kn,{className:"h-4 w-4"})," System Campaigns"]}),e.jsx("div",{className:"space-y-3",children:_e.map(Be=>he(Be,!1))})]}),O.length===0&&e.jsx(we,{children:e.jsxs(De,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(pn,{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($,{className:"mt-4",onClick:()=>m(!0),children:[e.jsx(nn,{className:"h-4 w-4 mr-1"})," Create Campaign"]})]})}),e.jsx(_On,{open:!!v,onClose:()=>_(null),campaignName:(v==null?void 0:v.name)||"",stat:v&&j[v.id]||null}),o&&e.jsx(BVt,{email:o,mergeValues:P,selectedSubjectIndex:Y[o.id],onClose:()=>c(null)}),e.jsx(zs,{open:!!i,onOpenChange:Be=>!Be&&l(null),children:e.jsxs(Rs,{className:"max-w-4xl max-h-[90vh] overflow-y-auto p-0",children:[e.jsxs(Vs,{className:"px-6 pt-6 pb-4 border-b",children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(VT,{className:"h-5 w-5 text-primary"}),"Edit Email #",i==null?void 0:i.email_number]}),e.jsx(Cr,{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(re,{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:"Email Title"}),e.jsx(be,{value:i.title,onChange:Be=>l({...i,title:Be.target.value}),className:"h-9"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:"Delay (days after previous)"}),e.jsx(be,{type:"number",min:0,max:90,value:i.delay_days,onChange:Be=>l({...i,delay_days:parseInt(Be.target.value)||7}),className:"h-9"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:"Subject Line"}),e.jsx(be,{value:i.subject_line,onChange:Be=>l({...i,subject_line:Be.target.value}),placeholder:"e.g. Hey {{first_name}}, quick question...",className:"h-9"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(re,{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(Ls,{value:((Ue=i.subject_line_options)==null?void 0:Ue.join(` `))||"",onChange:Be=>l({...i,subject_line_options:Be.target.value.split(` `).filter(Boolean)}),rows:2,className:"text-sm resize-none"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(re,{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:"Email Body"}),e.jsx(ya,{value:p,onValueChange:Be=>g(Be),children:e.jsxs(va,{className:"h-7",children:[e.jsx(is,{value:"editor",className:"text-xs px-3 h-6",children:"Editor"}),e.jsx(is,{value:"preview",className:"text-xs px-3 h-6",children:"Preview"})]})})]}),p==="editor"?e.jsx(bOn,{content:i.body_html,onChange:Be=>l({...i,body_html:Be})}):e.jsxs("div",{className:"border rounded-xl overflow-hidden",children:[e.jsxs("div",{className:"bg-muted/50 px-4 py-2 border-b space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx("span",{className:"font-medium w-12",children:"From:"}),e.jsxs("span",{children:[P.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:[P.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:R(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:R(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($,{variant:"outline",size:"sm",onClick:()=>l(null),children:"Cancel"}),e.jsxs($,{size:"sm",onClick:()=>ee.mutate(i),disabled:ee.isPending,className:"gap-1.5",children:[e.jsx(Ml,{className:"h-3.5 w-3.5"})," Save Changes"]})]})]})]})]})}),e.jsx(zs,{open:h,onOpenChange:m,children:e.jsxs(Rs,{className:"max-w-lg",children:[e.jsxs(Vs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(nn,{className:"h-5 w-5 text-primary"})," Create Custom Campaign"]}),e.jsx(Cr,{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(re,{className:"text-xs font-medium",children:"Campaign Name *"}),e.jsx(be,{value:C.name,onChange:Be=>A({...C,name:Be.target.value}),placeholder:"e.g. Q2 Agent Outreach"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{className:"text-xs font-medium",children:"Warmth Level"}),e.jsxs(bs,{value:C.warmth_level,onValueChange:Be=>A({...C,warmth_level:Be}),children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"cold",children:"❄️ Cold — Curiosity"}),e.jsx(We,{value:"warm",children:"☀️ Warm — Growth"}),e.jsx(We,{value:"hot",children:"🔥 Hot — Private Invite"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{className:"text-xs font-medium",children:"Primary CTA"}),e.jsx(be,{value:C.primary_cta,onChange:Be=>A({...C,primary_cta:Be.target.value}),placeholder:"Learn more"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{className:"text-xs font-medium",children:"Description"}),e.jsx(Ls,{value:C.description,onChange:Be=>A({...C,description:Be.target.value}),placeholder:"What is this campaign about?",rows:2})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{className:"text-xs font-medium",children:"Goal"}),e.jsx(be,{value:C.goal,onChange:Be=>A({...C,goal:Be.target.value}),placeholder:"e.g. Convert warm leads to meetings"})]}),e.jsxs(h1,{children:[e.jsx(m1,{asChild:!0,children:e.jsxs($,{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(pn,{className:"h-3.5 w-3.5"})," Email Settings Override"]}),e.jsx(Go,{className:"h-3.5 w-3.5"})]})}),e.jsxs(f1,{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(re,{className:"text-xs",children:"Sender Name"}),e.jsx(be,{value:C.sender_name,onChange:Be=>A({...C,sender_name:Be.target.value}),placeholder:"e.g. Jeremy at LevelUp"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{className:"text-xs",children:"Sender Email"}),e.jsx(be,{value:C.sender_email,onChange:Be=>A({...C,sender_email:Be.target.value}),placeholder:"e.g. recruiting@send.relevelup.com"}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Must be a verified sending domain"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{className:"text-xs",children:"Reply-To Email"}),e.jsx(be,{value:C.reply_to_email,onChange:Be=>A({...C,reply_to_email:Be.target.value}),placeholder:"e.g. jeremy@mybrokerage.com"})]})]})]}),e.jsxs($,{className:"w-full",disabled:!C.name.trim()||oe.isPending,onClick:()=>oe.mutate(),children:[e.jsx(nn,{className:"h-4 w-4 mr-1"})," Create Campaign"]})]})]})}),e.jsx(zs,{open:!!x,onOpenChange:Be=>!Be&&y(null),children:e.jsxs(Rs,{className:"max-w-lg",children:[e.jsxs(Vs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(Yc,{className:"h-5 w-5 text-primary"})," Campaign Email Settings"]}),e.jsx(Cr,{children:"Override the default sender for this campaign. Leave blank to use brokerage defaults."})]}),x&&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(re,{className:"text-xs font-medium",children:"Campaign Name"}),e.jsx(be,{value:x.name,onChange:Be=>y({...x,name:Be.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{className:"text-xs font-medium",children:"Warmth Level"}),e.jsxs(bs,{value:x.warmth_level,onValueChange:Be=>y({...x,warmth_level:Be}),children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"cold",children:"❄️ Cold"}),e.jsx(We,{value:"warm",children:"☀️ Warm"}),e.jsx(We,{value:"hot",children:"🔥 Hot"})]})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{className:"text-xs font-medium",children:"Goal"}),e.jsx(be,{value:x.goal||"",onChange:Be=>y({...x,goal:Be.target.value})})]}),e.jsxs("div",{className:"border-t pt-4 space-y-3",children:[e.jsxs("p",{className:"text-sm font-semibold flex items-center gap-1.5",children:[e.jsx(pn,{className:"h-4 w-4 text-primary"})," Email Sender Override"]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{className:"text-xs",children:"Sender Name"}),e.jsx(be,{value:x.sender_name||"",onChange:Be=>y({...x,sender_name:Be.target.value}),placeholder:"Uses brokerage default"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{className:"text-xs",children:"Sender Email"}),e.jsx(be,{value:x.sender_email||"",onChange:Be=>y({...x,sender_email:Be.target.value}),placeholder:"Uses brokerage default"}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Must be a verified sending domain"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{className:"text-xs",children:"Reply-To Email"}),e.jsx(be,{value:x.reply_to_email||"",onChange:Be=>y({...x,reply_to_email:Be.target.value}),placeholder:"Uses brokerage default"})]})]}),e.jsxs($,{className:"w-full",onClick:()=>me.mutate(x),disabled:me.isPending,children:[e.jsx(Ml,{className:"h-4 w-4 mr-1"})," Save Campaign Settings"]})]})]})}),e.jsx(zs,{open:d,onOpenChange:u,children:e.jsxs(Rs,{className:"max-w-lg",children:[e.jsxs(Vs,{children:[e.jsx($s,{children:"Default Recruiting Email Settings"}),e.jsx(Cr,{children:"These defaults apply to campaigns without their own overrides."})]}),e.jsx(bQe,{brokerageId:s})]})})]});function he(Be,je){const Ye=vbt[Be.warmth_level]||vbt.cold,Ee=Ye.icon,Re=U[Be.id]||[],ke=r===Be.id,Fe=!!(Be.sender_name||Be.sender_email||Be.reply_to_email),Oe=j[Be.id];return e.jsxs(we,{className:"overflow-hidden transition-shadow hover:shadow-md",children:[e.jsx(Vt,{className:"cursor-pointer hover:bg-muted/40 transition-colors py-4",onClick:()=>a(ke?null:Be.id),children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:`h-11 w-11 rounded-xl ${Ye.bg} flex items-center justify-center`,children:e.jsx(Ee,{className:`h-5 w-5 ${Ye.color}`})}),e.jsxs("div",{children:[e.jsxs(Yt,{className:"text-base flex items-center gap-2",children:[Be.name,e.jsx(qe,{variant:Be.is_active?"default":"secondary",className:"text-[10px] px-1.5",children:Be.is_active?"Active":"Draft"}),je&&e.jsx(qe,{variant:"outline",className:"text-[10px] px-1.5",children:"Custom"}),Fe&&e.jsxs(qe,{variant:"outline",className:"text-[10px] px-1.5 border-primary/30 text-primary",children:[e.jsx(pn,{className:"h-2.5 w-2.5 mr-0.5"})," Custom Sender"]})]}),e.jsx(vr,{className:"text-xs mt-0.5",children:Be.theme||Be.description})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx($,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:Ge=>{Ge.stopPropagation(),y({...Be})},children:e.jsx(Yc,{className:"h-4 w-4 text-muted-foreground"})}),je&&e.jsx($,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0 text-destructive hover:text-destructive hover:bg-destructive/10",onClick:async Ge=>{Ge.stopPropagation(),await io("Delete this campaign and all its emails? This cannot be undone.")&&te.mutate(Be.id)},children:e.jsx(Un,{className:"h-4 w-4"})}),Oe&&Oe.sent>0&&e.jsxs("div",{className:"hidden md:flex items-center gap-1.5",children:[e.jsxs(qe,{variant:"outline",className:"text-[10px] gap-1 font-medium",title:"Total emails sent",children:[e.jsx(pn,{className:"h-2.5 w-2.5"})," ",Oe.sent.toLocaleString()]}),e.jsxs(qe,{variant:"outline",className:"text-[10px] gap-1 border-amber-500/30 text-amber-600 font-medium",title:`${Oe.openRate.toFixed(1)}% open rate`,children:[e.jsx(ba,{className:"h-2.5 w-2.5"})," ",Oe.opened.toLocaleString()," (",Oe.openRate.toFixed(0),"%)"]}),e.jsxs(qe,{variant:"outline",className:"text-[10px] gap-1 border-green-500/30 text-green-600 font-medium",title:`${Oe.clickRate.toFixed(1)}% click rate`,children:[e.jsx(rh,{className:"h-2.5 w-2.5"})," ",Oe.clicked.toLocaleString()," (",Oe.clickRate.toFixed(1),"%)"]})]}),e.jsxs($,{variant:"outline",size:"sm",className:"h-7 px-2 gap-1 text-xs",onClick:Ge=>{Ge.stopPropagation(),_(Be)},title:"View detailed engagement stats",children:[e.jsx(Ul,{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(pn,{className:"h-3.5 w-3.5"}),e.jsxs("span",{children:[Re.length," emails"]})]}),e.jsx("div",{className:"h-7 w-7 rounded-md flex items-center justify-center",children:ke?e.jsx(Ny,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(Go,{className:"h-4 w-4 text-muted-foreground"})})]})]})}),ke&&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:Be.goal||"—"})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:"Primary CTA"}),e.jsx("p",{className:"mt-0.5",children:Be.primary_cta||"—"})]})]}),Fe&&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(pn,{className:"h-3 w-3"})," Campaign Sender Override"]}),e.jsxs("div",{className:"grid grid-cols-3 gap-2 text-xs text-muted-foreground",children:[Be.sender_name&&e.jsxs("p",{children:[e.jsx("span",{className:"font-medium",children:"Name:"})," ",Be.sender_name]}),Be.sender_email&&e.jsxs("p",{children:[e.jsx("span",{className:"font-medium",children:"Email:"})," ",Be.sender_email]}),Be.reply_to_email&&e.jsxs("p",{children:[e.jsx("span",{className:"font-medium",children:"Reply-To:"})," ",Be.reply_to_email]})]})]}),e.jsx("div",{className:"relative",children:Re.map((Ge,yt)=>{var tt,ut;return e.jsxs("div",{className:"relative flex gap-4 pb-4 last:pb-0",children:[ytnt.stopPropagation(),onBlur:nt=>{const et=parseInt(nt.target.value)||0;et!==Ge.delay_days&&fe.mutate({emailId:Ge.id,delay_days:et})},onKeyDown:nt=>{nt.key==="Enter"&&nt.target.blur()}}),"days"]})]}):e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(sa,{className:"h-3 w-3"}),Ge.email_number===1?"Sent immediately":`Day ${Ge.delay_days}`]}),e.jsx("span",{className:"text-border",children:"•"}),e.jsxs("span",{className:"truncate",children:["Subject: ",R(((tt=Ge.subject_line_options)==null?void 0:tt.length)>0&&Ge.subject_line_options[Y[Ge.id]??0]||Ge.subject_line)]})]}),((ut=Ge.subject_line_options)==null?void 0:ut.length)>1&&e.jsx("div",{className:"mt-2",children:e.jsxs(bs,{value:String(Y[Ge.id]??0),onValueChange:nt=>se.mutate({campaignEmailId:Ge.id,selectedIndex:parseInt(nt)}),children:[e.jsx(ys,{className:"h-7 text-xs w-full max-w-sm",children:e.jsx(_s,{placeholder:"Choose subject line"})}),e.jsx(vs,{children:Ge.subject_line_options.map((nt,et)=>e.jsxs(We,{value:String(et),className:"text-xs",children:[e.jsxs("span",{className:"font-medium mr-1.5",children:[et===0?"Primary":`Alt ${et}`,":"]}),R(nt)]},et))})]})})]}),e.jsxs("div",{className:"flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity shrink-0",children:[e.jsx($,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>c(Ge),children:e.jsx(ba,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>{l({...Ge}),g("editor")},children:e.jsx(ui,{className:"h-4 w-4"})}),je&&Re.length>1&&e.jsx($,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0 text-destructive hover:text-destructive hover:bg-destructive/10",onClick:async()=>{await io("Delete this email from the sequence?")&&le.mutate(Ge.id)},children:e.jsx(Un,{className:"h-4 w-4"})})]})]})})]},Ge.id)})}),je&&e.jsxs($,{variant:"outline",size:"sm",className:"w-full gap-1.5",onClick:()=>Q.mutate(Be.id),disabled:Q.isPending,children:[e.jsx(nn,{className:"h-3.5 w-3.5"})," Add Email to Sequence"]})]})]},Be.id)}}const bbt={active:{icon:pu,color:"bg-green-500/10 text-green-600",label:"Active"},paused:{icon:uv,color:"bg-amber-500/10 text-amber-600",label:"Paused"},completed:{icon:nl,color:"bg-blue-500/10 text-blue-600",label:"Completed"},cancelled:{icon:ju,color:"bg-red-500/10 text-red-600",label:"Cancelled"}},_bt={sent:{icon:pn,color:"text-blue-500"},opened:{icon:ba,color:"text-amber-500"},clicked:{icon:rh,color:"text-green-500"},failed:{icon:Gd,color:"text-destructive"}};function qVt({brokerageId:s}){var Ue,Be,je,Ye,Ee;const{user:t}=ks(),n=ls(),[r,a]=k.useState(!1),[i,l]=k.useState(""),[o,c]=k.useState(new Set),[d,u]=k.useState("assignments"),[h,m]=k.useState(null),[p,g]=k.useState(""),[x,y]=k.useState("all"),[v,_]=k.useState("all"),[j,C]=k.useState(!1),{data:A}=ZEe(),{data:M={}}=pt({queryKey:["recruit-campaign-emails-for-preview",s],queryFn:async()=>{const{data:Re,error:ke}=await V.from("recruit_campaign_emails").select("*").order("email_number");if(ke)throw ke;const Fe={};return(Re??[]).forEach(Oe=>{Fe[Oe.campaign_id]||(Fe[Oe.campaign_id]=[]),Fe[Oe.campaign_id].push(Oe)}),Fe}}),{data:I}=pt({queryKey:["brokerage-detail",s],queryFn:async()=>{const{data:Re,error:ke}=await V.from("brokerages").select("name, city, state").eq("id",s).single();if(ke)throw ke;return Re}}),{data:P}=pt({queryKey:["brokerage-recruit-settings",s],queryFn:async()=>{const{data:Re,error:ke}=await V.from("brokerage_recruit_settings").select("*").eq("brokerage_id",s).maybeSingle();if(ke)throw ke;return Re}}),{data:R=[]}=pt({queryKey:["recruit-subject-overrides",s],queryFn:async()=>{const{data:Re,error:ke}=await V.from("recruit_brokerage_subject_overrides").select("*").eq("brokerage_id",s);if(ke)throw ke;return Re}}),O={};R.forEach(Re=>{O[Re.campaign_email_id]=Re.selected_subject_index});const B={first_name:((Ue=h==null?void 0:h.prospect)==null?void 0:Ue.first_name)||"Sarah",brokerage_name:((Be=P==null?void 0:P.merge_fields)==null?void 0:Be.brokerage_name)||(I==null?void 0:I.name)||"Your Brokerage",city:((je=P==null?void 0:P.merge_fields)==null?void 0:je.city)||(I==null?void 0:I.city)||"Your City",sender_name:((Ye=P==null?void 0:P.merge_fields)==null?void 0:Ye.sender_name)||(P==null?void 0:P.sender_name)||"Your Name"},U=Re=>{const ke=M[Re.campaign_id]||[],Fe=Re.current_email_number+1;return ke.find(Oe=>Oe.email_number===Fe)||null},{data:G=[],isLoading:H}=pt({queryKey:["recruit-campaign-assignments",s],queryFn:async()=>{let ke=[],Fe=0;for(;;){const{data:Oe,error:Ge}=await V.from("recruit_campaign_assignments").select(` *, prospect:recruit_prospects(first_name, last_name, email), campaign:recruit_campaigns(name, warmth_level) `).eq("brokerage_id",s).order("created_at",{ascending:!1}).range(Fe,Fe+1e3-1);if(Ge)throw Ge;if(ke=ke.concat(Oe??[]),!Oe||Oe.length<1e3)break;Fe+=1e3}return ke}}),{data:Y=[]}=pt({queryKey:["recruit-campaign-sends",s],queryFn:async()=>{const{data:Re,error:ke}=await V.from("recruit_campaign_sends").select(` *, prospect:recruit_prospects(first_name, last_name, email), campaign_email:recruit_campaign_emails(title, campaign_id) `).eq("brokerage_id",s).neq("status","failed").order("sent_at",{ascending:!1}).limit(500);if(ke)throw ke;return Re}}),{data:se=[]}=pt({queryKey:["recruit-campaigns"],queryFn:async()=>{const{data:Re,error:ke}=await V.from("recruit_campaigns").select("id, name, warmth_level").eq("is_active",!0).order("sort_order");if(ke)throw ke;return Re}}),{data:ee=[]}=pt({queryKey:["recruit-prospects-for-assign",s],queryFn:async()=>{let ke=[],Fe=0;for(;;){const{data:Oe,error:Ge}=await V.from("recruit_prospects").select("id, first_name, last_name, email").eq("brokerage_id",s).order("first_name").range(Fe,Fe+1e3-1);if(Ge)throw Ge;if(ke=ke.concat(Oe??[]),!Oe||Oe.length<1e3)break;Fe+=1e3}return ke}}),oe=new Set(G.map(Re=>`${Re.prospect_id}-${Re.campaign_id}`)),me=Nt({mutationFn:async()=>{if(!i||o.size===0)throw new Error("Select a campaign and at least one prospect");const Re=new Date,ke=Array.from(o).filter(Oe=>!oe.has(`${Oe}-${i}`)).map(Oe=>({prospect_id:Oe,campaign_id:i,brokerage_id:s,assigned_by:t.id,status:"active",current_email_number:0,next_send_at:Re.toISOString(),started_at:Re.toISOString()}));if(ke.length===0)throw new Error("All selected prospects are already assigned to this campaign");const{error:Fe}=await V.from("recruit_campaign_assignments").insert(ke);if(Fe)throw Fe},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-campaign-assignments",s]}),ae.success(`Campaign assigned to ${o.size} prospect(s)!`),a(!1),l(""),c(new Set)},onError:Re=>ae.error(Re.message)}),Q=Nt({mutationFn:async({id:Re,newStatus:ke})=>{const{error:Fe}=await V.from("recruit_campaign_assignments").update({status:ke,updated_at:new Date().toISOString()}).eq("id",Re);if(Fe)throw Fe},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-campaign-assignments",s]}),ae.success("Assignment updated")}}),te=Nt({mutationFn:async()=>{const{data:Re,error:ke}=await V.functions.invoke("ses-recruit-drip",{body:{action:"process_drips"}});if(ke)throw ke;return Re},onSuccess:Re=>{n.invalidateQueries({queryKey:["recruit-campaign-assignments",s]}),n.invalidateQueries({queryKey:["recruit-campaign-sends",s]}),ae.success(`Wave sent! ${Re.sent} emails delivered, ${Re.skipped} skipped, ${Re.failed} failed`)},onError:Re=>ae.error(`Send failed: ${Re.message}`)}),le=G.filter(Re=>Re.status==="active").length;G.filter(Re=>Re.status==="completed").length;const fe=G.filter(Re=>Re.status==="active"&&Re.next_send_at&&new Date(Re.next_send_at)<=new Date).length,{data:_e={}}=$Vt(s),ve=G.reduce((Re,ke)=>Re+Math.max(0,ke.current_email_number||0),0),he=Object.values(_e).reduce((Re,ke)=>Re+ke.opened,0),Se=Object.values(_e).reduce((Re,ke)=>Re+ke.clicked,0);Object.values(_e).reduce((Re,ke)=>Re+ke.failed,0);const Te=ve>0?Math.round(he/ve*100):0,Ie=ve>0?Se/ve*100:0;return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-xl font-bold",children:"Campaign Assignments"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Assign recruiting campaigns to prospects — emails auto-send weekly via SES"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[fe>0&&e.jsxs($,{variant:"outline",onClick:()=>{te.mutate()},disabled:te.isPending,className:"border-amber-500/50 text-amber-600 hover:bg-amber-500/10",children:[e.jsx(ix,{className:"h-4 w-4 mr-1"}),te.isPending?"Sending...":`Send Next Wave (${fe})`]}),e.jsxs($,{onClick:()=>a(!0),children:[e.jsx(Wr,{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(we,{children:e.jsxs(De,{className:"pt-3 pb-2 flex items-center gap-3",children:[e.jsx(Xn,{className:"h-7 w-7 text-primary"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xl font-bold",children:G.length}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Assigned"})]})]})}),e.jsx(we,{children:e.jsxs(De,{className:"pt-3 pb-2 flex items-center gap-3",children:[e.jsx(pu,{className:"h-7 w-7 text-green-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xl font-bold",children:le}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Active"})]})]})}),e.jsx(we,{children:e.jsxs(De,{className:"pt-3 pb-2 flex items-center gap-3",children:[e.jsx(pn,{className:"h-7 w-7 text-blue-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xl font-bold",children:ve.toLocaleString()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Emails Sent"})]})]})}),e.jsx(we,{children:e.jsxs(De,{className:"pt-3 pb-2 flex items-center gap-3",children:[e.jsx(ba,{className:"h-7 w-7 text-amber-500"}),e.jsxs("div",{children:[e.jsxs("p",{className:"text-xl font-bold",children:[Te,"%"]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Open Rate (",he.toLocaleString(),")"]})]})]})}),e.jsx(we,{children:e.jsxs(De,{className:"pt-3 pb-2 flex items-center gap-3",children:[e.jsx(rh,{className:"h-7 w-7 text-green-500"}),e.jsxs("div",{children:[e.jsxs("p",{className:"text-xl font-bold",children:[Ie.toFixed(1),"%"]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Click Rate (",Se.toLocaleString(),")"]})]})]})})]}),e.jsxs(ya,{value:d,onValueChange:u,children:[e.jsxs(va,{children:[e.jsxs(is,{value:"assignments",children:["Active Drips (",le,")"]}),e.jsxs(is,{value:"history",children:["Send History (",ve.toLocaleString(),")"]})]}),e.jsx(cs,{value:"assignments",className:"mt-4",children:H?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"})}):G.length===0?e.jsx(we,{children:e.jsxs(De,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(Wr,{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:G.map(Re=>{var tt,ut,nt,et;const ke=bbt[Re.status]||bbt.active,Fe=ke.icon,Ge=(M[Re.campaign_id]||[]).length||4,yt=U(Re);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(qe,{className:`text-xs ${ke.color} border-0`,children:[e.jsx(Fe,{className:"h-3 w-3 mr-1"}),ke.label]}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("p",{className:"font-medium text-sm",children:[(tt=Re.prospect)==null?void 0:tt.first_name," ",(ut=Re.prospect)==null?void 0:ut.last_name,e.jsx("span",{className:"text-muted-foreground font-normal ml-2",children:(nt=Re.prospect)==null?void 0:nt.email})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[(et=Re.campaign)==null?void 0:et.name," · Email ",Re.current_email_number,"/",Ge,Re.next_send_at&&Re.status==="active"&&e.jsxs(e.Fragment,{children:[" ","· ",e.jsx(sa,{className:"h-3 w-3 inline"})," Next: ",Ys(new Date(Re.next_send_at),"MMM d, h:mm a"),new Date(Re.next_send_at)<=new Date&&e.jsx(qe,{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:[yt&&e.jsx($,{variant:"ghost",size:"sm",title:"Preview next email",onClick:()=>m(Re),children:e.jsx(ba,{className:"h-3.5 w-3.5"})}),Re.status==="active"&&e.jsx($,{variant:"ghost",size:"sm",onClick:()=>Q.mutate({id:Re.id,newStatus:"paused"}),children:e.jsx(uv,{className:"h-3.5 w-3.5"})}),Re.status==="paused"&&e.jsx($,{variant:"ghost",size:"sm",onClick:()=>Q.mutate({id:Re.id,newStatus:"active"}),children:e.jsx(pu,{className:"h-3.5 w-3.5"})}),(Re.status==="active"||Re.status==="paused")&&e.jsx($,{variant:"ghost",size:"sm",className:"text-destructive",onClick:()=>Q.mutate({id:Re.id,newStatus:"cancelled"}),children:e.jsx(ju,{className:"h-3.5 w-3.5"})})]})]},Re.id)})})}),e.jsxs(cs,{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(bs,{value:x,onValueChange:y,children:[e.jsx(ys,{className:"w-[220px] h-8 text-xs",children:e.jsx(_s,{placeholder:"All campaigns"})}),e.jsxs(vs,{children:[e.jsx(We,{value:"all",children:"All campaigns"}),se.map(Re=>e.jsx(We,{value:Re.id,children:Re.name},Re.id))]})]}),e.jsxs(bs,{value:v,onValueChange:_,children:[e.jsx(ys,{className:"w-[160px] h-8 text-xs",children:e.jsx(_s,{placeholder:"All statuses"})}),e.jsxs(vs,{children:[e.jsx(We,{value:"all",children:"All statuses"}),e.jsx(We,{value:"sent",children:"Sent (no engagement)"}),e.jsx(We,{value:"opened",children:"Opened"}),e.jsx(We,{value:"clicked",children:"Clicked"})]})]}),(x!=="all"||v!=="all")&&e.jsx($,{variant:"ghost",size:"sm",className:"h-8 text-xs",onClick:()=>{y("all"),_("all")},children:"Clear"})]}),(()=>{var ke;const Re=Y.filter(Fe=>{var Oe;return!(x!=="all"&&((Oe=Fe.campaign_email)==null?void 0:Oe.campaign_id)!==x||v==="opened"&&!Fe.opened_at||v==="clicked"&&!Fe.clicked_at||v==="sent"&&(Fe.opened_at||Fe.clicked_at))});return Re.length===0?e.jsx(we,{children:e.jsxs(De,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(pn,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{className:"font-medium",children:Y.length===0?"No emails sent yet":"No emails match these filters"}),e.jsx("p",{className:"text-sm",children:Y.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 ",Re.length," of ",Y.length," recent sends",x!=="all"&&` · ${(ke=se.find(Fe=>Fe.id===x))==null?void 0:ke.name}`]}),e.jsx("div",{className:"space-y-1",children:Re.map(Fe=>{var tt,ut,nt;const Oe=_bt[Fe.status]||_bt.sent,Ge=Oe.icon,yt=(tt=se.find(et=>{var at;return et.id===((at=Fe.campaign_email)==null?void 0:at.campaign_id)}))==null?void 0:tt.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(Ge,{className:`h-4 w-4 flex-shrink-0 ${Oe.color}`}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("p",{className:"font-medium text-sm truncate",children:[(ut=Fe.prospect)==null?void 0:ut.first_name," ",(nt=Fe.prospect)==null?void 0:nt.last_name,e.jsxs("span",{className:"text-muted-foreground font-normal ml-2",children:["Email #",Fe.email_number]}),yt&&e.jsx(qe,{variant:"outline",className:"ml-2 text-[10px] px-1.5 py-0 font-normal",children:yt})]}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:Fe.subject})]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground flex-shrink-0",children:[Fe.opened_at&&e.jsxs("span",{className:"flex items-center gap-1 text-amber-500",children:[e.jsx(ba,{className:"h-3 w-3"})," ",Ys(new Date(Fe.opened_at),"MMM d")]}),Fe.clicked_at&&e.jsxs("span",{className:"flex items-center gap-1 text-green-500",children:[e.jsx(rh,{className:"h-3 w-3"})," ",Ys(new Date(Fe.clicked_at),"MMM d")]}),e.jsx("span",{children:Ys(new Date(Fe.sent_at),"MMM d, h:mm a")})]})]},Fe.id)})})]})})()]})]}),e.jsx(zs,{open:r,onOpenChange:Re=>{a(Re),Re||(g(""),c(new Set),l(""))},children:e.jsxs(Rs,{className:"max-w-lg max-h-[85vh] flex flex-col p-0",children:[e.jsxs(Vs,{className:"px-6 pt-6 pb-4",children:[e.jsx($s,{children:"Assign Campaign to Prospects"}),e.jsx(Cr,{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(re,{className:"text-sm font-medium",children:"1. Select Campaign"}),e.jsxs(bs,{value:i,onValueChange:l,children:[e.jsx(ys,{children:e.jsx(_s,{placeholder:"Choose a campaign..."})}),e.jsx(vs,{children:se.map(Re=>e.jsx(We,{value:Re.id,children:Re.name},Re.id))})]})]}),i&&(()=>{const Re=p.toLowerCase(),ke=ee.filter(Ge=>`${Ge.first_name} ${Ge.last_name}`.toLowerCase().includes(Re)||Ge.email.toLowerCase().includes(Re)),Fe=ke.filter(Ge=>!oe.has(`${Ge.id}-${i}`)),Oe=Fe.length>0&&Fe.every(Ge=>o.has(Ge.id));return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(re,{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(Yr,{className:"absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search by name or email...",value:p,onChange:Ge=>g(Ge.target.value),className:"pl-9 h-9"})]}),e.jsxs($,{variant:"outline",size:"sm",className:"h-9 whitespace-nowrap",onClick:()=>{if(Oe){const Ge=new Set(o);Fe.forEach(yt=>Ge.delete(yt.id)),c(Ge)}else{const Ge=new Set(o);Fe.forEach(yt=>Ge.add(yt.id)),c(Ge)}},children:[e.jsx(L8,{className:"h-3.5 w-3.5 mr-1"}),Oe?"Deselect All":`Select All (${Fe.length})`]})]}),e.jsx("div",{className:"border rounded-lg max-h-60 overflow-y-auto divide-y",children:ke.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:p?"No prospects match your search":"No prospects found for this brokerage"}):ke.map(Ge=>{const yt=oe.has(`${Ge.id}-${i}`);return e.jsxs("label",{className:`flex items-center gap-3 p-2.5 hover:bg-muted/50 cursor-pointer ${yt?"opacity-40":""}`,children:[e.jsx(Li,{checked:o.has(Ge.id),disabled:yt,onCheckedChange:tt=>{const ut=new Set(o);tt?ut.add(Ge.id):ut.delete(Ge.id),c(ut)}}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("p",{className:"text-sm font-medium truncate",children:[Ge.first_name," ",Ge.last_name]}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:Ge.email})]}),yt&&e.jsx(qe,{variant:"outline",className:"text-[10px] shrink-0",children:"Already assigned"})]},Ge.id)})}),ke.length>0&&e.jsxs("p",{className:"text-[11px] text-muted-foreground",children:["Showing ",ke.length," of ",ee.length," prospects",Fe.length0&&e.jsx(we,{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:(Ee=se.find(Re=>Re.id===i))==null?void 0:Ee.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(kr,{className:"px-6 py-4 border-t",children:[e.jsx($,{variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsxs($,{onClick:()=>{me.mutate()},disabled:me.isPending||!i||o.size===0,children:[e.jsx(Wr,{className:"h-4 w-4 mr-1"}),me.isPending?"Assigning...":`Assign & Start (${o.size})`]})]})]})}),h&&(()=>{const Re=U(h);return Re?e.jsx(BVt,{email:Re,mergeValues:B,selectedSubjectIndex:O[Re.id],onClose:()=>m(null)}):null})(),e.jsx(XEe,{open:j,onOpenChange:C,hasPending:A==null?void 0:A.hasPendingSes,pendingEmails:A==null?void 0:A.pendingEmails})]})}function VVt({brokerageId:s}){const t=ls(),[n,r]=k.useState([]),[a,i]=k.useState([]),[l,o]=k.useState(!1),c=k.useRef(!1),{data:d,isLoading:u}=pt({queryKey:["recruit-stages-editor",s],queryFn:async()=>{const{data:y,error:v}=await V.from("recruit_pipeline_stages").select("*").eq("brokerage_id",s).order("sort_order");if(v)throw v;return y},enabled:!!s});k.useEffect(()=>{if(d){if(c.current){c.current=!1;return}r(d.map(y=>({id:y.id,name:y.name,color:y.color,sort_order:y.sort_order}))),i([]),o(!1)}},[d]);const h=Nt({mutationFn:async()=>{for(const _ of a){const{error:j}=await V.from("recruit_pipeline_stages").delete().eq("id",_);if(j)throw j}const y=n.filter(_=>_.id&&!_.isNew),v=n.filter(_=>!_.id||_.isNew);for(const _ of y){const{error:j}=await V.from("recruit_pipeline_stages").update({name:_.name,color:_.color,sort_order:_.sort_order}).eq("id",_.id);if(j)throw j}if(v.length>0){const{error:_}=await V.from("recruit_pipeline_stages").insert(v.map(j=>({brokerage_id:s,name:j.name,color:j.color,sort_order:j.sort_order})));if(_)throw _}},onSuccess:()=>{i([]),t.invalidateQueries({queryKey:["recruit-stages-editor",s]}),t.invalidateQueries({queryKey:["recruit-stages",s]}),ae.success("Pipeline stages saved!"),o(!1)},onError:y=>ae.error(y.message)}),m=(y,v,_)=>{r(j=>j.map((C,A)=>A===y?{...C,[v]:_}:C)),o(!0)},p=()=>{const y=n.length>0?Math.max(...n.map(v=>v.sort_order)):0;r(v=>[...v,{name:"",color:"#6366f1",sort_order:y+1,isNew:!0}]),o(!0)},g=y=>{const v=n[y];v.id&&!v.isNew&&i(_=>[..._,v.id]),r(_=>_.filter((j,C)=>C!==y)),o(!0)},x=(y,v)=>{const _=y+v;if(_<0||_>=n.length)return;const j=[...n];[j[y],j[_]]=[j[_],j[y]],j.forEach((C,A)=>C.sort_order=A+1),r(j),o(!0)};return u?e.jsx("div",{className:"text-sm text-muted-foreground py-8 text-center",children:"Loading stages…"}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-semibold mb-1",children:"Pipeline Stages"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"Customize the recruiting pipeline stages for this brokerage. Changes will apply to the Kanban board and all prospect tracking."})]}),e.jsx("div",{className:"space-y-2",children:n.map((y,v)=>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:()=>x(v,-1),disabled:v===0,className:"text-muted-foreground hover:text-foreground disabled:opacity-30 text-xs",children:"▲"}),e.jsx("button",{type:"button",onClick:()=>x(v,1),disabled:v===n.length-1,className:"text-muted-foreground hover:text-foreground disabled:opacity-30 text-xs",children:"▼"})]}),e.jsx(Bp,{className:"h-4 w-4 text-muted-foreground/50 shrink-0"}),e.jsx("input",{type:"color",value:y.color,onChange:_=>m(v,"color",_.target.value),className:"h-8 w-8 rounded cursor-pointer border-0 p-0 shrink-0"}),e.jsx(be,{value:y.name,onChange:_=>m(v,"name",_.target.value),placeholder:"Stage name…",className:"flex-1"}),e.jsx("span",{className:"text-xs text-muted-foreground w-6 text-center shrink-0",children:v+1}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>g(v),className:"text-destructive hover:text-destructive shrink-0 h-8 w-8",children:e.jsx(Un,{className:"h-4 w-4"})})]},y.id||`new-${v}`))}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs($,{variant:"outline",size:"sm",onClick:p,className:"gap-1",children:[e.jsx(nn,{className:"h-4 w-4"})," Add Stage"]}),l&&e.jsxs($,{size:"sm",onClick:()=>h.mutate(),disabled:h.isPending,className:"gap-1",children:[e.jsx(Ml,{className:"h-4 w-4"})," Save Changes"]})]}),n.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No stages configured. Add stages to build your recruiting pipeline."})]})}function wOn({brokerageId:s}){const{data:t=[],isLoading:n}=pt({queryKey:["recruit-unsubscribed",s],queryFn:async()=>{const{data:r,error:a}=await V.from("recruit_prospects").select("id, first_name, last_name, email, unsubscribed_at, unsubscribe_reason, current_brokerage").eq("brokerage_id",s).not("unsubscribed_at","is",null).order("unsubscribed_at",{ascending:!1}).limit(500);if(a)throw a;return r||[]},enabled:!!s});return n?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"h-6 w-6 animate-spin rounded-full border-2 border-primary border-t-transparent"})}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs("h3",{className:"text-lg font-semibold flex items-center gap-2",children:[e.jsx(K8,{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(qe,{variant:"secondary",className:"text-base px-3 py-1",children:[t.length," total"]})]}),t.length===0?e.jsx(we,{children:e.jsxs(De,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(K8,{className:"h-10 w-10 mx-auto mb-3 opacity-40"}),e.jsx("p",{className:"text-sm",children:"No prospects have unsubscribed. Nice work!"})]})}):e.jsx("div",{className:"grid gap-3",children:t.map(r=>e.jsxs(we,{className:"hover:shadow-sm transition-shadow",children:[e.jsx(Vt,{className:"pb-3",children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs(Yt,{className:"text-base",children:[r.first_name," ",r.last_name]}),e.jsxs("div",{className:"flex items-center gap-3 text-xs text-muted-foreground mt-1",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(pn,{className:"h-3 w-3"}),r.email]}),r.current_brokerage&&e.jsxs("span",{children:["· ",r.current_brokerage]})]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-muted-foreground whitespace-nowrap",children:[e.jsx(ha,{className:"h-3 w-3"}),r.unsubscribed_at&&Ys(new Date(r.unsubscribed_at),"MMM d, yyyy")]})]})}),r.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:['"',r.unsubscribe_reason,'"']})})]},r.id))})]})}function jOn(){var o;const[s,t]=k.useState(""),[n,r]=k.useState("board"),{data:a=[],isLoading:i}=pt({queryKey:["all-brokerages"],queryFn:async()=>{const{data:c,error:d}=await V.from("brokerages").select("id, name").order("name");if(d)throw d;return c}}),l=s||((o=a[0])==null?void 0:o.id)||"";return i?e.jsx(Xs,{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(Xs,{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(bs,{value:l,onValueChange:t,children:[e.jsxs(ys,{className:"w-[280px]",children:[e.jsx(Gi,{className:"mr-2 h-4 w-4"}),e.jsx(_s,{placeholder:"Select brokerage"})]}),e.jsx(vs,{children:a.map(c=>e.jsx(We,{value:c.id,children:c.name},c.id))})]})]}):e.jsx("div",{}),l&&e.jsx(OVt,{brokerageId:l,trigger:e.jsxs($,{size:"sm",className:"gap-1.5",children:[e.jsx(ia,{className:"h-4 w-4"})," Record & Send Video"]})})]}),l?e.jsxs(ya,{defaultValue:"pipeline",className:"space-y-4",children:[e.jsxs(va,{className:"flex-wrap h-auto gap-1",children:[e.jsx(is,{value:"pipeline",children:"Pipeline"}),e.jsxs(is,{value:"contacts",children:[e.jsx(Xn,{className:"h-3.5 w-3.5 mr-1"}),"Contacts"]}),e.jsxs(is,{value:"video-outreach",children:[e.jsx(ia,{className:"h-3.5 w-3.5 mr-1"}),"Video Outreach"]}),e.jsx(is,{value:"follow-ups",children:"Follow-ups"}),e.jsx(is,{value:"referrals",children:"Referrals"}),e.jsx(is,{value:"interest",children:"Interest Form"}),e.jsx(is,{value:"landing-page",children:"Landing Page"}),e.jsx(is,{value:"goals",children:"Goals"}),e.jsx(is,{value:"metrics",children:"Metrics"}),e.jsx(is,{value:"templates",children:"Email Templates"}),e.jsxs(is,{value:"campaigns",children:[e.jsx(pn,{className:"h-3.5 w-3.5 mr-1"}),"Campaigns"]}),e.jsxs(is,{value:"drip-assignments",children:[e.jsx(Wr,{className:"h-3.5 w-3.5 mr-1"}),"Drip Assignments"]}),e.jsx(is,{value:"activity",children:"Recruiter Activity"}),e.jsxs(is,{value:"email-settings",children:[e.jsx(Yc,{className:"h-3.5 w-3.5 mr-1"}),"Email Settings"]}),e.jsxs(is,{value:"pipeline-stages",children:[e.jsx(tM,{className:"h-3.5 w-3.5 mr-1"}),"Pipeline Stages"]}),e.jsxs(is,{value:"unsubscribed",children:[e.jsx(K8,{className:"h-3.5 w-3.5 mr-1"}),"Unsubscribed"]})]}),e.jsxs(cs,{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($,{variant:n==="board"?"default":"ghost",size:"sm",className:"h-7 px-2.5 gap-1.5",onClick:()=>r("board"),children:[e.jsx(y0,{className:"h-3.5 w-3.5"})," Board"]}),e.jsxs($,{variant:n==="table"?"default":"ghost",size:"sm",className:"h-7 px-2.5 gap-1.5",onClick:()=>r("table"),children:[e.jsx(mB,{className:"h-3.5 w-3.5"})," Table"]})]})}),n==="board"?e.jsx(EVt,{brokerageId:l}):e.jsx(eCe,{brokerageId:l})]}),e.jsx(cs,{value:"contacts",children:e.jsx(eCe,{brokerageId:l})}),e.jsx(cs,{value:"video-outreach",children:e.jsx(FVt,{brokerageId:l})}),e.jsx(cs,{value:"follow-ups",children:e.jsx(RVt,{brokerageId:l})}),e.jsx(cs,{value:"referrals",children:e.jsx(IVt,{brokerageId:l})}),e.jsx(cs,{value:"interest",children:e.jsx(LVt,{brokerageId:l})}),e.jsx(cs,{value:"landing-page",children:e.jsx(DVt,{brokerageId:l})}),e.jsx(cs,{value:"goals",children:e.jsx(zVt,{brokerageId:l})}),e.jsx(cs,{value:"metrics",children:e.jsx(TVt,{brokerageId:l})}),e.jsx(cs,{value:"templates",children:e.jsx(MVt,{brokerageId:l})}),e.jsx(cs,{value:"campaigns",children:e.jsx(UVt,{brokerageId:l})}),e.jsx(cs,{value:"drip-assignments",children:e.jsx(qVt,{brokerageId:l})}),e.jsx(cs,{value:"activity",children:e.jsx(PVt,{brokerageId:l})}),e.jsx(cs,{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(bQe,{brokerageId:l})]})}),e.jsx(cs,{value:"pipeline-stages",children:e.jsx("div",{className:"max-w-2xl",children:e.jsx(VVt,{brokerageId:l})})}),e.jsx(cs,{value:"unsubscribed",children:e.jsx(wOn,{brokerageId:l})})]}):e.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[e.jsx(Gi,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No brokerages found. Create a brokerage first."})]})]})})}function NOn({brokerageId:s}){const[t,n]=k.useState(""),[r,a]=k.useState("all"),{data:i,isLoading:l}=pt({queryKey:["recruit-sent-emails",s],queryFn:async()=>{var y;const{data:d,error:u}=await V.from("recruit_prospects").select("id, first_name, last_name, email").eq("brokerage_id",s);if(u)throw u;const h=new Map((d||[]).map(v=>[v.id,v]));if(Array.from(h.keys()).length===0)return[];const{data:p}=await V.from("recruit_videos").select("id, prospect_id, share_token, sent_at, sent_via, view_count, first_viewed_at, cta_clicked_at, video:agent_videos(title)").eq("brokerage_id",s).not("sent_at","is",null).order("sent_at",{ascending:!1}),{data:g}=await V.from("recruit_campaign_sends").select("id, prospect_id, subject, status, sent_at, opened_at, clicked_at, error_message, email_number").eq("brokerage_id",s).order("sent_at",{ascending:!1,nullsFirst:!1}),x=[];for(const v of p||[]){const _=h.get(v.prospect_id);_&&x.push({id:`v-${v.id}`,kind:"video",prospect_id:v.prospect_id,prospect_name:`${_.first_name||""} ${_.last_name||""}`.trim()||"—",prospect_email:_.email,subject:(y=v.video)!=null&&y.title?`Video: ${v.video.title}`:"Recruiting Video",status:v.cta_clicked_at?"clicked":v.first_viewed_at?"viewed":"sent",sent_at:v.sent_at,opened_at:v.first_viewed_at,clicked_at:v.cta_clicked_at,view_count:v.view_count,share_token:v.share_token})}for(const v of g||[]){if(!v.sent_at)continue;const _=h.get(v.prospect_id);_&&x.push({id:`c-${v.id}`,kind:"campaign",prospect_id:v.prospect_id,prospect_name:`${_.first_name||""} ${_.last_name||""}`.trim()||"—",prospect_email:_.email,subject:v.subject||`Email #${v.email_number}`,status:v.status||"sent",sent_at:v.sent_at,opened_at:v.opened_at,clicked_at:v.clicked_at,error:v.error_message})}return x.sort((v,_)=>new Date(_.sent_at).getTime()-new Date(v.sent_at).getTime()),x}}),o=k.useMemo(()=>{const d=i||[];return{total:d.length,videos:d.filter(u=>u.kind==="video").length,campaigns:d.filter(u=>u.kind==="campaign").length,opened:d.filter(u=>u.opened_at).length,clicked:d.filter(u=>u.clicked_at).length}},[i]),c=k.useMemo(()=>(i||[]).filter(u=>{if(r!=="all"&&u.kind!==r)return!1;if(!t)return!0;const h=t.toLowerCase();return u.prospect_name.toLowerCase().includes(h)||(u.prospect_email||"").toLowerCase().includes(h)||u.subject.toLowerCase().includes(h)}),[i,t,r]);return e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-3",children:[{label:"Total Sent",value:o.total,icon:Wr,color:"text-primary"},{label:"Video Emails",value:o.videos,icon:ia,color:"text-blue-500"},{label:"Campaign Emails",value:o.campaigns,icon:pn,color:"text-violet-500"},{label:"Opened / Viewed",value:o.opened,icon:ba,color:"text-amber-500"},{label:"Clicked",value:o.clicked,icon:rh,color:"text-emerald-500"}].map(d=>e.jsx(we,{children:e.jsxs(De,{className:"p-3 flex items-center gap-2.5",children:[e.jsx("div",{className:`h-9 w-9 rounded-lg bg-muted flex items-center justify-center ${d.color}`,children:e.jsx(d.icon,{className:"h-4 w-4"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xl font-bold leading-tight",children:d.value}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:d.label})]})]})},d.label))}),e.jsxs(we,{children:[e.jsx(Vt,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between gap-2 flex-wrap",children:[e.jsx(Yt,{className:"text-lg",children:"Sent Emails"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ya,{value:r,onValueChange:d=>a(d),children:e.jsxs(va,{className:"h-8",children:[e.jsx(is,{value:"all",className:"text-xs h-7",children:"All"}),e.jsx(is,{value:"video",className:"text-xs h-7",children:"Video"}),e.jsx(is,{value:"campaign",className:"text-xs h-7",children:"Campaign"})]})}),e.jsxs("div",{className:"relative w-56",children:[e.jsx(Yr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search recruit, subject...",value:t,onChange:d=>n(d.target.value),className:"pl-9 h-9"})]})]})]})}),e.jsx(De,{children:l?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):c.length===0?e.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[e.jsx(pn,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{className:"font-medium",children:"No emails sent yet"}),e.jsx("p",{className:"text-sm mt-1",children:"Emails sent from Video Outreach or Drip Campaigns will appear here."})]}):e.jsx("div",{className:"rounded-lg border overflow-hidden",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-muted/40 text-xs text-muted-foreground",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left font-medium px-3 py-2",children:"Type"}),e.jsx("th",{className:"text-left font-medium px-3 py-2",children:"Recruit"}),e.jsx("th",{className:"text-left font-medium px-3 py-2",children:"Subject"}),e.jsx("th",{className:"text-left font-medium px-3 py-2",children:"Status"}),e.jsx("th",{className:"text-left font-medium px-3 py-2",children:"Sent"}),e.jsx("th",{className:"text-right font-medium px-3 py-2",children:"Engagement"})]})}),e.jsx("tbody",{children:c.map(d=>e.jsxs("tr",{className:"border-t hover:bg-muted/30 transition-colors",children:[e.jsx("td",{className:"px-3 py-2",children:d.kind==="video"?e.jsxs(qe,{variant:"outline",className:"gap-1",children:[e.jsx(ia,{className:"h-3 w-3"}),"Video"]}):e.jsxs(qe,{variant:"outline",className:"gap-1",children:[e.jsx(pn,{className:"h-3 w-3"}),"Campaign"]})}),e.jsxs("td",{className:"px-3 py-2",children:[e.jsx("div",{className:"font-medium",children:d.prospect_name}),d.prospect_email&&e.jsx("div",{className:"text-xs text-muted-foreground",children:d.prospect_email})]}),e.jsx("td",{className:"px-3 py-2 max-w-xs truncate",children:d.subject}),e.jsxs("td",{className:"px-3 py-2",children:[d.status==="failed"||d.status==="bounced"?e.jsxs(qe,{variant:"destructive",className:"gap-1",children:[e.jsx(Ho,{className:"h-3 w-3"}),d.status]}):d.clicked_at?e.jsxs(qe,{className:"bg-emerald-500/15 text-emerald-700 border-emerald-200 gap-1",children:[e.jsx(rh,{className:"h-3 w-3"}),"Clicked"]}):d.opened_at?e.jsxs(qe,{className:"bg-blue-500/15 text-blue-700 border-blue-200 gap-1",children:[e.jsx(ba,{className:"h-3 w-3"}),"Opened"]}):e.jsxs(qe,{variant:"secondary",className:"gap-1",children:[e.jsx(Wr,{className:"h-3 w-3"}),"Sent"]}),d.error&&e.jsx("p",{className:"text-[10px] text-destructive mt-0.5 max-w-[200px] truncate",title:d.error,children:d.error})]}),e.jsxs("td",{className:"px-3 py-2 text-xs text-muted-foreground whitespace-nowrap",children:[Ys(new Date(d.sent_at),"MMM d, yyyy"),e.jsx("div",{className:"text-[10px]",children:Ys(new Date(d.sent_at),"h:mm a")})]}),e.jsx("td",{className:"px-3 py-2 text-right",children:e.jsxs("div",{className:"flex items-center gap-2 justify-end text-xs text-muted-foreground",children:[d.kind==="video"&&d.view_count!=null&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ba,{className:"h-3 w-3"}),d.view_count]}),d.kind==="video"&&d.share_token&&e.jsx($,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>window.open(`/recruit-video/${d.share_token}`,"_blank"),title:"Open landing page",children:e.jsx(Ir,{className:"h-3.5 w-3.5"})})]})})]},d.id))})]})})})]})]})}function kOn(){var l;const{managedBrokerages:s,selectedBrokerageId:t,setSelectedBrokerageId:n}=ks(),[r,a]=k.useState("board"),i=t||((l=s[0])==null?void 0:l.id)||"";return s.length===0?e.jsx(Xs,{title:"Recruiting",description:"Agent Recruiting Pipeline",children:e.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[e.jsx(Gi,{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(Xs,{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(bs,{value:i,onValueChange:n,children:[e.jsxs(ys,{className:"w-[280px]",children:[e.jsx(Gi,{className:"mr-2 h-4 w-4"}),e.jsx(_s,{placeholder:"Select brokerage"})]}),e.jsx(vs,{children:s.map(o=>e.jsx(We,{value:o.id,children:o.name},o.id))})]})]}),i?e.jsxs(ya,{defaultValue:"pipeline",className:"space-y-4",children:[e.jsxs(va,{className:"flex-wrap h-auto gap-1",children:[e.jsx(is,{value:"pipeline",children:"Pipeline"}),e.jsxs(is,{value:"contacts",children:[e.jsx(Xn,{className:"h-3.5 w-3.5 mr-1"}),"Contacts"]}),e.jsxs(is,{value:"video-outreach",children:[e.jsx(ia,{className:"h-3.5 w-3.5 mr-1"}),"Video Outreach"]}),e.jsx(is,{value:"follow-ups",children:"Follow-ups"}),e.jsx(is,{value:"referrals",children:"Referrals"}),e.jsx(is,{value:"interest",children:"Interest Form"}),e.jsx(is,{value:"landing-page",children:"Landing Page"}),e.jsx(is,{value:"goals",children:"Goals"}),e.jsx(is,{value:"metrics",children:"Metrics"}),e.jsx(is,{value:"templates",children:"Email Templates"}),e.jsxs(is,{value:"campaigns",children:[e.jsx(pn,{className:"h-3.5 w-3.5 mr-1"}),"Campaigns"]}),e.jsxs(is,{value:"drip-assignments",children:[e.jsx(Wr,{className:"h-3.5 w-3.5 mr-1"}),"Drip Assignments"]}),e.jsxs(is,{value:"sent-emails",children:[e.jsx(HT,{className:"h-3.5 w-3.5 mr-1"}),"Sent Emails"]}),e.jsx(is,{value:"activity",children:"Recruiter Activity"}),e.jsxs(is,{value:"email-settings",children:[e.jsx(Yc,{className:"h-3.5 w-3.5 mr-1"}),"Email Settings"]}),e.jsxs(is,{value:"pipeline-stages",children:[e.jsx(tM,{className:"h-3.5 w-3.5 mr-1"}),"Pipeline Stages"]})]}),e.jsxs(cs,{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($,{variant:r==="board"?"default":"ghost",size:"sm",className:"h-7 px-2.5 gap-1.5",onClick:()=>a("board"),children:[e.jsx(y0,{className:"h-3.5 w-3.5"})," Board"]}),e.jsxs($,{variant:r==="table"?"default":"ghost",size:"sm",className:"h-7 px-2.5 gap-1.5",onClick:()=>a("table"),children:[e.jsx(mB,{className:"h-3.5 w-3.5"})," Table"]})]})}),r==="board"?e.jsx(EVt,{brokerageId:i}):e.jsx(eCe,{brokerageId:i})]}),e.jsx(cs,{value:"contacts",children:e.jsx(eCe,{brokerageId:i})}),e.jsx(cs,{value:"video-outreach",children:e.jsx(FVt,{brokerageId:i})}),e.jsx(cs,{value:"follow-ups",children:e.jsx(RVt,{brokerageId:i})}),e.jsx(cs,{value:"referrals",children:e.jsx(IVt,{brokerageId:i})}),e.jsx(cs,{value:"interest",children:e.jsx(LVt,{brokerageId:i})}),e.jsx(cs,{value:"landing-page",children:e.jsx(DVt,{brokerageId:i})}),e.jsx(cs,{value:"goals",children:e.jsx(zVt,{brokerageId:i})}),e.jsx(cs,{value:"metrics",children:e.jsx(TVt,{brokerageId:i})}),e.jsx(cs,{value:"templates",children:e.jsx(MVt,{brokerageId:i})}),e.jsx(cs,{value:"campaigns",children:e.jsx(UVt,{brokerageId:i})}),e.jsx(cs,{value:"drip-assignments",children:e.jsx(qVt,{brokerageId:i})}),e.jsx(cs,{value:"sent-emails",children:e.jsx(NOn,{brokerageId:i})}),e.jsx(cs,{value:"activity",children:e.jsx(PVt,{brokerageId:i})}),e.jsx(cs,{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(bQe,{brokerageId:i})]})}),e.jsx(cs,{value:"pipeline-stages",children:e.jsx("div",{className:"max-w-2xl",children:e.jsx(VVt,{brokerageId:i})})})]}):e.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[e.jsx(Gi,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No brokerages found."})]})]})})}function SOn(){const[s,t]=k.useState(""),{data:n,isLoading:r}=pt({queryKey:["admin-brokerage-content-activity"],queryFn:async()=>{const{data:o}=await V.from("brokerages").select("id, name");if(!o)return[];const{data:c}=await V.from("brokerage_content").select("id, brokerage_id, content_type, created_at"),{data:d}=await V.from("brokerage_content_categories").select("id, brokerage_id"),u=c||[],h=d||[],m=o.map(p=>{const g=u.filter(v=>v.brokerage_id===p.id),x=h.filter(v=>v.brokerage_id===p.id),y=g.length>0?g.reduce((v,_)=>_.created_at>v?_.created_at:v,g[0].created_at):null;return{brokerage_id:p.id,brokerage_name:p.name,total_items:g.length,videos:g.filter(v=>v.content_type==="video").length,pdfs:g.filter(v=>v.content_type==="pdf").length,links:g.filter(v=>v.content_type==="link"||v.content_type==="canva_link").length,events:g.filter(v=>v.content_type==="event").length,graphics:g.filter(v=>v.content_type==="graphic").length,latest_item_date:y,categories:x.length}});return m.sort((p,g)=>g.total_items-p.total_items),m}}),a=(n||[]).filter(o=>o.brokerage_name.toLowerCase().includes(s.toLowerCase())),i=a.reduce((o,c)=>o+c.total_items,0),l=a.filter(o=>o.total_items>0).length;return e.jsx(Xs,{title:"Brokerage Content Activity",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(nm,{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(we,{children:[e.jsx(Vt,{className:"pb-2",children:e.jsx(Yt,{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(we,{children:[e.jsx(Vt,{className:"pb-2",children:e.jsx(Yt,{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(we,{children:[e.jsx(Vt,{className:"pb-2",children:e.jsx(Yt,{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(Yr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search brokerages...",value:s,onChange:o=>t(o.target.value),className:"pl-9"})]}),e.jsx(we,{children:e.jsx(De,{className:"p-0",children:e.jsxs(Qa,{children:[e.jsx(Ja,{children:e.jsxs(vn,{children:[e.jsx(Dt,{children:"Brokerage"}),e.jsx(Dt,{className:"text-center",children:"Total"}),e.jsx(Dt,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(ia,{className:"h-3 w-3"})," Videos"]})}),e.jsx(Dt,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(ea,{className:"h-3 w-3"})," PDFs"]})}),e.jsx(Dt,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(pd,{className:"h-3 w-3"})," Links"]})}),e.jsx(Dt,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(fd,{className:"h-3 w-3"})," Events"]})}),e.jsx(Dt,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(zc,{className:"h-3 w-3"})," Graphics"]})}),e.jsx(Dt,{className:"text-center",children:"Categories"}),e.jsx(Dt,{children:"Last Upload"})]})}),e.jsx(ei,{children:r?e.jsx(vn,{children:e.jsx(_t,{colSpan:9,className:"text-center py-8 text-muted-foreground",children:"Loading..."})}):a.length===0?e.jsx(vn,{children:e.jsx(_t,{colSpan:9,className:"text-center py-8 text-muted-foreground",children:"No brokerages found"})}):a.map(o=>e.jsxs(vn,{className:o.total_items===0?"opacity-50":"",children:[e.jsx(_t,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Gi,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsx("span",{className:"font-medium",children:o.brokerage_name})]})}),e.jsx(_t,{className:"text-center",children:o.total_items>0?e.jsx(qe,{variant:"secondary",className:"font-bold",children:o.total_items}):e.jsx("span",{className:"text-muted-foreground",children:"0"})}),e.jsx(_t,{className:"text-center",children:o.videos||"–"}),e.jsx(_t,{className:"text-center",children:o.pdfs||"–"}),e.jsx(_t,{className:"text-center",children:o.links||"–"}),e.jsx(_t,{className:"text-center",children:o.events||"–"}),e.jsx(_t,{className:"text-center",children:o.graphics||"–"}),e.jsx(_t,{className:"text-center",children:o.categories||"–"}),e.jsx(_t,{children:o.latest_item_date?e.jsx("span",{className:"text-sm text-muted-foreground",children:Ys(new Date(o.latest_item_date),"MMM d, yyyy")}):e.jsx("span",{className:"text-muted-foreground",children:"–"})})]},o.brokerage_id))})]})})})]})})}const COn=[{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:"📉"}],wbt=[{value:"instagram-square",label:"Instagram Post",dimensions:"1080×1080",icon:e.jsx(Sf,{className:"h-4 w-4"})},{value:"instagram-story",label:"Instagram Story",dimensions:"1080×1920",icon:e.jsx(Sf,{className:"h-4 w-4"})},{value:"facebook-post",label:"Facebook Post",dimensions:"1200×630",icon:e.jsx(ax,{className:"h-4 w-4"})}],AOn=[{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:"📰"}],jbt=s=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s),Nbt={"luxury-dark":GKe,"modern-clean":WKe,"bold-colorful":KKe,editorial:YKe};function EOn(){const[s,t]=k.useState(""),[n,r]=k.useState("address"),[a,i]=k.useState(!1),[l,o]=k.useState([]),[c,d]=k.useState(null),[u,h]=k.useState(0),[m,p]=k.useState("just-listed"),[g,x]=k.useState(["instagram-square"]),[y,v]=k.useState("luxury-dark"),[_,j]=k.useState(!1),[C,A]=k.useState(""),[M,I]=k.useState(""),[P,R]=k.useState(""),[O,B]=k.useState(!1),[U,G]=k.useState(!1),[H,Y]=k.useState([]),[se,ee]=k.useState("search"),oe=k.useRef({});k.useEffect(()=>{(async()=>{const{data:{user:Te}}=await V.auth.getUser();if(!Te)return;const{data:Ie}=await V.from("profiles").select("name, avatar_url, brokerages(name)").eq("id",Te.id).single();if(Ie){A(Ie.name||""),R(Ie.avatar_url||"");const Ue=Ie.brokerages;I((Ue==null?void 0:Ue.name)||"")}})()},[]);const me=async()=>{var Se;if(s.trim()){i(!0),o([]);try{const{data:Te,error:Ie}=await V.functions.invoke("repliers-mls-search",{body:{searchType:n,query:s.trim()}});if(Ie)throw Ie;if(Te.error)throw new Error(Te.error);o(Te.listings||[]),((Se=Te.listings)==null?void 0:Se.length)===0&&ae.info("No listings found. Try a different search.")}catch(Te){ae.error(Te.message||"Search failed")}finally{i(!1)}}},Q=Se=>{var Te;d(Se),h(0),ee("customize"),Se.soldDate||(Te=Se.status)!=null&&Te.toLowerCase().includes("sold")?p("just-sold"):p("just-listed")},te=Se=>{x(Te=>Te.includes(Se)?Te.filter(Ie=>Ie!==Se):[...Te,Se])},le=k.useCallback(async()=>{if(!(!c||g.length===0)){B(!0),Y([]),ee("generate");try{await new Promise(Te=>setTimeout(Te,500));const Se=[];for(const Te of g){const Ie=`${y}-${Te}`,Ue=oe.current[Ie];if(!Ue)continue;const Be=NT[Te],je=await PU(Ue,{width:Be.width,height:Be.height,pixelRatio:1,cacheBust:!0,style:{transform:"none",transformOrigin:"top left"}});Se.push({format:Te,imageUrl:je})}Y(Se),ae.success(`Generated ${Se.length} social post${Se.length>1?"s":""}!`)}catch(Se){ae.error(Se.message||"Generation failed")}finally{B(!1)}}},[c,g,y,u,_,C,M,P,m]),fe=async()=>{if(!(!c||g.length===0)){B(!0),Y([]),ee("generate");try{const Se={...c,photos:c.photos.length>0?[c.photos[u]]:[]},Te=[];for(const Ie of g){const{data:Ue,error:Be}=await V.functions.invoke("generate-listing-social-post",{body:{listing:Se,postType:m,format:Ie,branding:_?{enabled:!0,agentName:C,brokerage:M}:{enabled:!1}}});if(Be)throw Be;if(Ue.error)throw new Error(Ue.error);Te.push({format:Ie,imageUrl:Ue.imageUrl})}Y(Te),ae.success(`Generated ${Te.length} AI post${Te.length>1?"s":""}!`)}catch(Se){ae.error(Se.message||"AI generation failed")}finally{B(!1)}}},_e=()=>U?fe():le(),ve=(Se,Te)=>{var Ue;const Ie=document.createElement("a");Ie.href=Se,Ie.download=`${((Ue=c==null?void 0:c.address)==null?void 0:Ue.replace(/\s+/g,"-"))||"listing"}-${m}-${Te}.png`,document.body.appendChild(Ie),Ie.click(),document.body.removeChild(Ie)},he=c?{listing:c,postType:m,format:"instagram-square",branding:_?{enabled:!0,agentName:C,brokerage:M,agentPhotoUrl:P||void 0}:{enabled:!1},selectedPhotoIndex:u}:null;return e.jsx(Xs,{children:e.jsxs("div",{className:"space-y-6 p-4 md:p-8",children:[e.jsx(nm,{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:()=>ee("search"),className:`flex items-center gap-1.5 px-3 py-1.5 rounded-full transition-colors ${se==="search"?"bg-primary text-primary-foreground":"bg-muted text-muted-foreground hover:text-foreground"}`,children:[e.jsx(Yr,{className:"h-3.5 w-3.5"})," 1. Find Listing"]}),e.jsx(fi,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("button",{onClick:()=>c&&ee("customize"),disabled:!c,className:`flex items-center gap-1.5 px-3 py-1.5 rounded-full transition-colors ${se==="customize"?"bg-primary text-primary-foreground":c?"bg-muted text-muted-foreground hover:text-foreground":"bg-muted text-muted-foreground/50 cursor-not-allowed"}`,children:[e.jsx(kn,{className:"h-3.5 w-3.5"})," 2. Customize"]}),e.jsx(fi,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("div",{className:`flex items-center gap-1.5 px-3 py-1.5 rounded-full ${se==="generate"?"bg-primary text-primary-foreground":"bg-muted text-muted-foreground/50"}`,children:[e.jsx(zc,{className:"h-3.5 w-3.5"})," 3. Generate"]})]}),se==="search"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs(we,{children:[e.jsxs(Vt,{children:[e.jsxs(Yt,{className:"flex items-center gap-2",children:[e.jsx(Yr,{className:"h-5 w-5 text-primary"})," Search MLS Listings ",e.jsx(UMt,{})]}),e.jsx(vr,{children:"Find a listing by MLS number or property address using Repliers.io"})]}),e.jsxs(De,{className:"space-y-4",children:[e.jsx(ya,{value:n,onValueChange:Se=>r(Se),children:e.jsxs(va,{children:[e.jsxs(is,{value:"address",children:[e.jsx(Si,{className:"h-4 w-4 mr-1.5"})," Address"]}),e.jsxs(is,{value:"mls",children:[e.jsx(kg,{className:"h-4 w-4 mr-1.5"})," MLS #"]})]})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(be,{value:s,onChange:Se=>t(Se.target.value),placeholder:n==="mls"?"Enter MLS number...":"Enter property address...",className:"flex-1",onKeyDown:Se=>Se.key==="Enter"&&me()}),e.jsxs($,{onClick:me,disabled:a||!s.trim(),children:[a?e.jsx(Jt,{className:"h-4 w-4 animate-spin"}):e.jsx(Yr,{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((Se,Te)=>{var Ie;return e.jsx(we,{className:"cursor-pointer hover:border-primary/50 hover:shadow-md transition-all group",onClick:()=>Q(Se),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:(Ie=Se.photos)!=null&&Ie[0]?e.jsx("img",{src:Se.photos[0],alt:Se.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(ua,{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:jbt(Se.price)}),e.jsx("p",{className:"text-sm text-muted-foreground truncate",children:Se.address}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[Se.city,", ",Se.state," ",Se.zip]}),e.jsxs("div",{className:"flex items-center gap-3 mt-1.5 text-xs text-muted-foreground",children:[Se.bedrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(f3,{className:"h-3 w-3"})," ",Se.bedrooms]}),Se.bathrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(p0,{className:"h-3 w-3"})," ",Se.bathrooms]}),Se.sqft>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(H8,{className:"h-3 w-3"})," ",Se.sqft.toLocaleString()]})]}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(qe,{variant:"outline",className:"text-[10px]",children:Se.mlsNumber}),e.jsx(qe,{variant:"outline",className:"text-[10px]",children:Se.status})]})]})]})})},Se.mlsNumber||Te)})})]})]}),se==="customize"&&c&&e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-6",children:[e.jsxs(we,{className:"lg:col-span-1",children:[e.jsx(Vt,{className:"pb-3",children:e.jsx(Yt,{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[u],alt:"Listing photo",className:"w-full h-full object-cover"})}),c.photos.length>1&&e.jsxs("div",{className:"flex items-center justify-between mt-2",children:[e.jsx($,{variant:"outline",size:"icon",className:"h-7 w-7",onClick:()=>h(Se=>Math.max(0,Se-1)),disabled:u===0,children:e.jsx(Ld,{className:"h-4 w-4"})}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[u+1," of ",c.photos.length]}),e.jsx($,{variant:"outline",size:"icon",className:"h-7 w-7",onClick:()=>h(Se=>Math.min(c.photos.length-1,Se+1)),disabled:u===c.photos.length-1,children:e.jsx(fi,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-bold text-lg",children:jbt(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($,{variant:"outline",size:"sm",className:"w-full",onClick:()=>{ee("search"),d(null)},children:[e.jsx(jm,{className:"h-3.5 w-3.5 mr-1.5"})," Choose Different Listing"]})]})]}),e.jsxs(we,{className:"lg:col-span-2",children:[e.jsxs(Vt,{children:[e.jsxs(Yt,{className:"flex items-center gap-2",children:[e.jsx(kn,{className:"h-5 w-5 text-primary"})," Customize Your Post"]}),e.jsx(vr,{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(gd,{className:"h-4 w-4 text-primary"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:U?"AI Custom Generation":"Template-Based (Free)"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:U?"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(On,{checked:U,onCheckedChange:G}),U&&e.jsx(vf,{className:"h-4 w-4 text-purple-500"})]})]}),!U&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(re,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(gd,{className:"h-4 w-4"})," Template Style"]}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-2",children:AOn.map(Se=>e.jsxs("button",{onClick:()=>v(Se.value),className:`flex flex-col items-center gap-1 px-3 py-3 rounded-lg border-2 transition-all text-center ${y===Se.value?"border-primary bg-primary/5":"border-border hover:border-primary/30"}`,children:[e.jsx("span",{className:"text-2xl",children:Se.preview}),e.jsx("span",{className:"text-sm font-medium",children:Se.label}),e.jsx("span",{className:"text-[10px] text-muted-foreground leading-tight",children:Se.description})]},Se.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-sm font-medium",children:"Post Type"}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-2",children:COn.map(Se=>e.jsxs("button",{onClick:()=>p(Se.value),className:`flex items-center gap-2 px-3 py-2.5 rounded-lg border-2 transition-all text-sm font-medium ${m===Se.value?"border-primary bg-primary/5":"border-border hover:border-primary/30"}`,children:[e.jsx("span",{className:"text-lg",children:Se.icon})," ",Se.label]},Se.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-sm font-medium",children:"Output Formats"}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-2",children:wbt.map(Se=>e.jsxs("button",{onClick:()=>te(Se.value),className:`flex items-center gap-2 px-3 py-2.5 rounded-lg border-2 transition-all text-sm ${g.includes(Se.value)?"border-primary bg-primary/5":"border-border hover:border-primary/30"}`,children:[Se.icon,e.jsxs("div",{className:"text-left",children:[e.jsx("p",{className:"font-medium",children:Se.label}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:Se.dimensions})]})]},Se.value))})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(re,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(el,{className:"h-4 w-4"})," Agent Branding"]}),e.jsx(On,{checked:_,onCheckedChange:j})]}),_&&e.jsxs("div",{className:"space-y-3 pl-6 border-l-2 border-primary/20",children:[P&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("img",{src:P,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(re,{className:"text-xs text-muted-foreground",children:"Agent Name"}),e.jsx(be,{value:C,onChange:Se=>A(Se.target.value),placeholder:"Jane Smith"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(re,{className:"text-xs text-muted-foreground",children:"Brokerage (optional)"}),e.jsx(be,{value:M,onChange:Se=>I(Se.target.value),placeholder:"XYZ Realty"})]})]})]})]}),!U&&he&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{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*(NT[g[0]||"instagram-square"].height/NT[g[0]||"instagram-square"].width)},children:(()=>{const Se=Nbt[y],Te=g[0]||"instagram-square";return e.jsx(Se,{...he,format:Te})})()})})]}),e.jsx($,{onClick:_e,disabled:g.length===0||O,size:"lg",className:"w-full gap-2",children:O?e.jsxs(e.Fragment,{children:[e.jsx(Jt,{className:"h-5 w-5 animate-spin"})," Generating ",g.length," post",g.length>1?"s":"","..."]}):e.jsxs(e.Fragment,{children:[U?e.jsx(vf,{className:"h-5 w-5"}):e.jsx(kn,{className:"h-5 w-5"}),"Generate ",g.length," Social Post",g.length>1?"s":"",U&&e.jsx(qe,{variant:"outline",className:"ml-2 text-[10px]",children:"Uses Credits"})]})})]})]})]}),se==="generate"&&e.jsxs("div",{className:"space-y-4",children:[O&&e.jsx(we,{children:e.jsxs(De,{className:"flex flex-col items-center justify-center py-16",children:[e.jsx(Jt,{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:U?"AI is creating your unique designs":"Rendering templates to high-res images"})]})}),H.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($,{variant:"outline",size:"sm",onClick:()=>ee("customize"),children:[e.jsx(jm,{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:H.map((Se,Te)=>{const Ie=wbt.find(Ue=>Ue.value===Se.format);return e.jsxs(we,{className:"overflow-hidden",children:[e.jsx("div",{className:"bg-muted/30 p-1",children:e.jsx("img",{src:Se.imageUrl,alt:`${Se.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:[Ie==null?void 0:Ie.icon,e.jsx("span",{className:"text-sm font-medium",children:Ie==null?void 0:Ie.label})]}),e.jsx(qe,{variant:"outline",className:"text-[10px]",children:Ie==null?void 0:Ie.dimensions})]}),e.jsxs($,{size:"sm",className:"w-full gap-1.5",onClick:()=>ve(Se.imageUrl,Se.format),children:[e.jsx(ji,{className:"h-3.5 w-3.5"})," Download"]})]})]},Te)})})]})]}),se==="generate"&&!U&&c&&he&&e.jsx("div",{style:{position:"absolute",left:"-9999px",top:0},"aria-hidden":!0,children:g.map(Se=>{const Te=Nbt[y],Ie=NT[Se];return e.jsx("div",{style:{width:Ie.width,height:Ie.height},children:e.jsx(Te,{ref:Ue=>{oe.current[`${y}-${Se}`]=Ue},...he,format:Se})},`${y}-${Se}`)})})]})})}function TOn(){return pt({queryKey:["lms-courses-admin"],queryFn:async()=>{const{data:s,error:t}=await V.from("lms_courses").select("*, modules:lms_modules(count), access:lms_course_access(*)").order("sort_order");if(t)throw t;return s}})}function MOn(s){return pt({queryKey:["lms-course-admin",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await V.from("lms_courses").select("*, modules:lms_modules(*, resources:lms_module_resources(*)), access:lms_course_access(*)").eq("id",s).single();if(n)throw n;return t!=null&&t.modules&&(t.modules.sort((r,a)=>r.sort_order-a.sort_order),t.modules.forEach(r=>{r.resources&&r.resources.sort((a,i)=>a.sort_order-i.sort_order)})),t},enabled:!!s})}function POn(){const s=ls();return Nt({mutationFn:async t=>{const{data:n,error:r}=await V.from("lms_courses").insert(t).select().single();if(r)throw r;return n},onSuccess:()=>s.invalidateQueries({queryKey:["lms-courses"]})})}function HVt(){const s=ls();return Nt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await V.from("lms_courses").update({...n,updated_at:new Date().toISOString()}).eq("id",t).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["lms-courses"]}),s.invalidateQueries({queryKey:["lms-course"]}),s.invalidateQueries({queryKey:["lms-courses-admin"]}),s.invalidateQueries({queryKey:["lms-course-admin"]})}})}function IOn(){const s=ls();return Nt({mutationFn:async t=>{const{error:n}=await V.from("lms_courses").delete().eq("id",t);if(n)throw n},onSuccess:()=>s.invalidateQueries({queryKey:["lms-courses"]})})}function LOn(){const s=ls();return Nt({mutationFn:async t=>{const{data:n,error:r}=await V.from("lms_modules").insert(t).select().single();if(r)throw r;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["lms-course"]}),s.invalidateQueries({queryKey:["lms-course-admin"]})}})}function ROn(){const s=ls();return Nt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await V.from("lms_modules").update({...n,updated_at:new Date().toISOString()}).eq("id",t).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["lms-course"]}),s.invalidateQueries({queryKey:["lms-course-admin"]})}})}function DOn(){const s=ls();return Nt({mutationFn:async t=>{const{error:n}=await V.from("lms_modules").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["lms-course"]}),s.invalidateQueries({queryKey:["lms-course-admin"]})}})}function OOn(){const s=ls();return Nt({mutationFn:async t=>{const{data:n,error:r}=await V.from("lms_module_resources").insert(t).select().single();if(r)throw r;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["lms-course"]}),s.invalidateQueries({queryKey:["lms-course-admin"]})}})}function FOn(){const s=ls();return Nt({mutationFn:async t=>{const{error:n}=await V.from("lms_module_resources").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["lms-course"]}),s.invalidateQueries({queryKey:["lms-course-admin"]})}})}function zOn(){const s=ls();return Nt({mutationFn:async({courseId:t,accessRules:n})=>{const{error:r}=await V.from("lms_course_access").delete().eq("course_id",t);if(r)throw r;if(n.length>0){const a=n.map(l=>({...l,course_id:t})),{error:i}=await V.from("lms_course_access").insert(a);if(i)throw i}},onSuccess:()=>{s.invalidateQueries({queryKey:["lms-courses"]}),s.invalidateQueries({queryKey:["lms-course"]})}})}function BOn(){return pt({queryKey:["lms-courses-agent"],queryFn:async()=>{const{data:s,error:t}=await V.from("lms_courses").select("*, modules:lms_modules(id)").eq("is_published",!0).order("sort_order");if(t)throw t;return s}})}function $On(s){return pt({queryKey:["lms-course-agent",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await V.from("lms_courses").select("*, modules:lms_modules(*, resources:lms_module_resources(*))").eq("id",s).single();if(n)throw n;return t!=null&&t.modules&&(t.modules.sort((r,a)=>r.sort_order-a.sort_order),t.modules.forEach(r=>{r.resources&&r.resources.sort((a,i)=>a.sort_order-i.sort_order)})),t},enabled:!!s})}function GVt(s){return pt({queryKey:["lms-progress",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await V.from("lms_progress").select("*").eq("course_id",s);if(n)throw n;return t},enabled:!!s})}function UOn(){const s=ls();return Nt({mutationFn:async({courseId:t,moduleId:n,userId:r})=>{const{data:a,error:i}=await V.from("lms_progress").upsert({user_id:r,course_id:t,module_id:n,completed:!0,completed_at:new Date().toISOString()},{onConflict:"user_id,module_id"}).select().single();if(i)throw i;return a},onSuccess:()=>s.invalidateQueries({queryKey:["lms-progress"]})})}function qOn(){const{user:s}=ks(),t=Jn(),{data:n,isLoading:r}=TOn(),a=POn(),i=HVt(),l=IOn(),[o,c]=k.useState(!1),[d,u]=k.useState(""),[h,m]=k.useState(""),[p,g]=k.useState(!0),x=async()=>{if(!(!d.trim()||!s))try{const _=await a.mutateAsync({title:d.trim(),description:h.trim()||void 0,is_sequential:p,created_by:s.id});ae.success("Course created"),c(!1),u(""),m(""),g(!0),t(`/admin/lms/${_.id}`)}catch{ae.error("Failed to create course")}},y=async _=>{try{await i.mutateAsync({id:_.id,is_published:!_.is_published}),ae.success(_.is_published?"Course unpublished":"Course published")}catch{ae.error("Failed to update course")}},v=async _=>{if(await io("Delete this course and all its modules? This cannot be undone."))try{await l.mutateAsync(_),ae.success("Course deleted")}catch{ae.error("Failed to delete")}};return e.jsxs(Xs,{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(Bm,{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($,{variant:"outline",onClick:()=>t("/admin/lms/stats"),children:[e.jsx(Ul,{className:"h-4 w-4 mr-2"}),"Analytics"]}),e.jsxs($,{onClick:()=>c(!0),children:[e.jsx(nn,{className:"h-4 w-4 mr-2"}),"New Course"]})]})]}),r?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4",children:[1,2,3].map(_=>e.jsx(we,{className:"animate-pulse",children:e.jsxs(Vt,{children:[e.jsx("div",{className:"h-5 bg-muted rounded w-2/3"}),e.jsx("div",{className:"h-3 bg-muted rounded w-1/2 mt-2"})]})},_))}):n!=null&&n.length?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4",children:n.map(_=>{var M,I;const j=((I=(M=_.modules)==null?void 0:M[0])==null?void 0:I.count)??0,C=_.access||[],A=C.length===0?"No access set":C.some(P=>P.access_type==="all")?"All agents":`${C.length} rule(s)`;return e.jsxs(we,{className:"group hover:shadow-md transition-all hover:border-primary/50 cursor-pointer",onClick:()=>t(`/admin/lms/${_.id}`),children:[e.jsx(Vt,{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(Yt,{className:"text-base truncate",children:_.title}),_.description&&e.jsx(vr,{className:"mt-1 line-clamp-2",children:_.description})]}),e.jsx(qe,{variant:_.is_published?"default":"secondary",className:"ml-2 shrink-0",children:_.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(wg,{className:"h-3.5 w-3.5"}),j," module",j!==1?"s":""]}),e.jsxs("span",{className:"flex items-center gap-1",children:[_.is_sequential?e.jsx(_2,{className:"h-3.5 w-3.5"}):e.jsx(Y8,{className:"h-3.5 w-3.5"}),_.is_sequential?"Sequential":"Free order"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Xn,{className:"h-3.5 w-3.5"}),A]})]}),e.jsxs("div",{className:"flex items-center gap-2 mt-3 opacity-0 group-hover:opacity-100 transition-opacity",children:[e.jsxs($,{size:"sm",variant:"ghost",onClick:P=>{P.stopPropagation(),y(_)},children:[_.is_published?e.jsx(x0,{className:"h-3.5 w-3.5 mr-1"}):e.jsx(ba,{className:"h-3.5 w-3.5 mr-1"}),_.is_published?"Unpublish":"Publish"]}),e.jsx($,{size:"sm",variant:"ghost",className:"text-destructive",onClick:P=>{P.stopPropagation(),v(_.id)},children:e.jsx(Un,{className:"h-3.5 w-3.5"})}),e.jsx("div",{className:"flex-1"}),e.jsx(xi,{className:"h-4 w-4 text-muted-foreground"})]})]})]},_.id)})}):e.jsx(we,{className:"border-dashed",children:e.jsxs(De,{className:"flex flex-col items-center justify-center py-16 text-center",children:[e.jsx(wg,{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($,{onClick:()=>c(!0),children:[e.jsx(nn,{className:"h-4 w-4 mr-2"}),"Create Course"]})]})})]}),e.jsx(zs,{open:o,onOpenChange:c,children:e.jsxs(Rs,{children:[e.jsxs(Vs,{children:[e.jsx($s,{children:"Create New Course"}),e.jsx(Cr,{children:"Set up a new training course for your agents"})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Course Title"}),e.jsx(be,{value:d,onChange:_=>u(_.target.value),placeholder:"e.g. LevelUp Onboarding"})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Description"}),e.jsx(Ls,{value:h,onChange:_=>m(_.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(On,{checked:p,onCheckedChange:g})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsx($,{onClick:x,disabled:!d.trim()||a.isPending,children:a.isPending?"Creating...":"Create Course"})]})]})})]})}function VOn(){const{courseId:s}=oo(),t=Jn(),{data:n,isLoading:r}=MOn(s),a=HVt(),i=LOn(),l=ROn(),o=DOn(),c=OOn(),d=FOn(),u=zOn(),{data:h}=pt({queryKey:["all-brokerages"],queryFn:async()=>{const{data:ut}=await V.from("brokerages").select("id, name").order("name");return ut||[]}}),[m,p]=k.useState(null),[g,x]=k.useState(!1),[y,v]=k.useState({title:"",description:"",video_url:"",text_content:"",duration_minutes:""}),[_,j]=k.useState(null),[C,A]=k.useState({title:"",resource_type:"link",url:""}),[M,I]=k.useState(new Set),[P,R]=k.useState(null),[O,B]=k.useState(0),[U,G]=k.useState(!1),H=k.useRef(null),Y=k.useRef(null),[se,ee]=k.useState(!1),[oe,me]=k.useState(""),[Q,te]=k.useState(""),[le,fe]=k.useState(""),[_e,ve]=k.useState(!1);if(r)return e.jsx(Xs,{title:"Loading...",children:e.jsx("div",{className:"flex items-center justify-center py-20",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})});if(!n)return e.jsx(Xs,{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($,{variant:"outline",className:"mt-4",onClick:()=>t("/admin/lms"),children:[e.jsx(Ia,{className:"h-4 w-4 mr-2"})," Back to Courses"]})]})});const he=n.modules||[],Se=n.access||[],Te=Se.some(ut=>ut.access_type==="all"),Ie=Se.filter(ut=>ut.access_type==="brokerage").map(ut=>ut.brokerage_id),Ue=(h||[]).filter(ut=>ut.name.toLowerCase().includes(oe.toLowerCase())),Be=ut=>{const nt=new Set(M);nt.has(ut)?nt.delete(ut):nt.add(ut),I(nt)},je=async()=>{if(!P)return null;G(!0),B(0);try{const{data:ut,error:nt}=await V.functions.invoke("bunny-upload",{body:{action:"create",title:P.name}});if(nt)throw new Error(nt.message);const{videoId:et,libraryId:at}=ut,{data:wt,error:rt}=await V.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:et,libraryId:at}});if(rt)throw new Error(rt.message);const Ft=new XMLHttpRequest;return await new Promise((Ut,Is)=>{Ft.upload.onprogress=xs=>{xs.lengthComputable&&B(Math.round(xs.loaded/xs.total*100))},Ft.onload=()=>Ft.status>=200&&Ft.status<300?Ut():Is(new Error(`Upload failed: ${Ft.status}`)),Ft.onerror=()=>Is(new Error("Upload failed")),Ft.open("PUT",wt.uploadUrl),Ft.setRequestHeader("AccessKey",wt.apiKey),Ft.send(P)}),`https://iframe.mediadelivery.net/embed/${at}/${et}`}catch(ut){return console.error("Bunny upload error:",ut),ae.error("Video upload failed"),null}finally{G(!1),B(0)}},Ye=async()=>{if(y.title.trim())try{let ut=y.video_url.trim()||void 0;if(P){const nt=await je();if(!nt)return;ut=nt}await i.mutateAsync({course_id:n.id,title:y.title.trim(),description:y.description.trim()||void 0,video_url:ut,text_content:y.text_content.trim()||void 0,duration_minutes:y.duration_minutes?parseInt(y.duration_minutes):void 0,sort_order:he.length}),ae.success("Module added"),x(!1),v({title:"",description:"",video_url:"",text_content:"",duration_minutes:""}),R(null)}catch{ae.error("Failed to add module")}},Ee=async()=>{if(m)try{let ut=y.video_url.trim()||null;if(P){const nt=await je();if(!nt)return;ut=nt}await l.mutateAsync({id:m.id,title:y.title.trim(),description:y.description.trim()||null,video_url:ut,text_content:y.text_content.trim()||null,duration_minutes:y.duration_minutes?parseInt(y.duration_minutes):null}),ae.success("Module updated"),p(null),R(null)}catch{ae.error("Failed to update")}},Re=async ut=>{if(await io("Delete this module?"))try{await o.mutateAsync(ut),ae.success("Module deleted")}catch{ae.error("Failed to delete")}},ke=async ut=>{if(C.title.trim())try{await c.mutateAsync({module_id:ut,title:C.title.trim(),resource_type:C.resource_type,url:C.url.trim()||void 0}),ae.success("Resource added"),j(null),A({title:"",resource_type:"link",url:""})}catch{ae.error("Failed to add resource")}},Fe=async()=>{try{await u.mutateAsync({courseId:n.id,accessRules:[{access_type:"all"}]}),ae.success("Access updated: All brokerages / all agents")}catch{ae.error("Failed to update access")}},Oe=async ut=>{const nt=Se.filter(rt=>rt.access_type==="brokerage").map(rt=>rt.brokerage_id),et=nt.includes(ut);let at;et?at=nt.filter(rt=>rt!==ut):at=[...nt,ut];const wt=at.map(rt=>({access_type:"brokerage",brokerage_id:rt}));try{await u.mutateAsync({courseId:n.id,accessRules:wt}),ae.success(et?"Brokerage removed":"Brokerage added")}catch{ae.error("Failed to update access")}},Ge=async()=>{try{await u.mutateAsync({courseId:n.id,accessRules:[]}),ae.success("Access cleared")}catch{ae.error("Failed")}},yt=async(ut,nt)=>{const et=nt==="up"?ut-1:ut+1;if(!(et<0||et>=he.length))try{await Promise.all([l.mutateAsync({id:he[ut].id,sort_order:et}),l.mutateAsync({id:he[et].id,sort_order:ut})])}catch{ae.error("Failed to reorder")}},tt=async()=>{try{await a.mutateAsync({id:n.id,title:Q,description:le||null}),ae.success("Course updated"),ve(!1)}catch{ae.error("Failed to update")}};return e.jsxs(Xs,{title:n.title,children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx($,{variant:"ghost",size:"icon",onClick:()=>t("/admin/lms"),children:e.jsx(Ia,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:n.title}),e.jsx(qe,{variant:n.is_published?"default":"secondary",children:n.is_published?"Published":"Draft"})]}),n.description&&e.jsx("p",{className:"text-muted-foreground mt-1",children:n.description}),e.jsxs("div",{className:"flex items-center gap-3 mt-2 text-xs text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[n.is_sequential?e.jsx(_2,{className:"h-3.5 w-3.5"}):e.jsx(Y8,{className:"h-3.5 w-3.5"}),n.is_sequential?"Sequential":"Free order"]}),e.jsxs("span",{children:[he.length," module",he.length!==1?"s":""]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs($,{variant:"outline",size:"sm",onClick:()=>{te(n.title),fe(n.description||""),ve(!0)},children:[e.jsx(ui,{className:"h-3.5 w-3.5 mr-1"})," Edit"]}),e.jsxs($,{variant:n.is_published?"secondary":"default",size:"sm",onClick:()=>a.mutateAsync({id:n.id,is_published:!n.is_published}).then(()=>ae.success(n.is_published?"Unpublished":"Published")),children:[n.is_published?e.jsx(x0,{className:"h-3.5 w-3.5 mr-1"}):e.jsx(ba,{className:"h-3.5 w-3.5 mr-1"}),n.is_published?"Unpublish":"Publish"]})]})]}),e.jsxs(ya,{defaultValue:"modules",className:"w-full",children:[e.jsxs(va,{children:[e.jsx(is,{value:"modules",children:"Modules"}),e.jsx(is,{value:"access",children:"Access & Permissions"}),e.jsx(is,{value:"settings",children:"Settings"})]}),e.jsxs(cs,{value:"modules",className:"mt-6 space-y-4",children:[he.map((ut,nt)=>e.jsxs(we,{className:"overflow-hidden",children:[e.jsxs("div",{className:"flex items-center gap-3 p-4 cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>Be(ut.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:et=>{et.stopPropagation(),yt(nt,"up")},disabled:nt===0,className:"hover:text-foreground disabled:opacity-30",children:e.jsx(Ny,{className:"h-3.5 w-3.5"})}),e.jsx("button",{onClick:et=>{et.stopPropagation(),yt(nt,"down")},disabled:nt===he.length-1,className:"hover:text-foreground disabled:opacity-30",children:e.jsx(Go,{className:"h-3.5 w-3.5"})})]})}),e.jsx(qe,{variant:"outline",className:"shrink-0 font-mono text-xs",children:nt+1}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:ut.title}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground mt-0.5",children:[ut.video_url&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(ia,{className:"h-3 w-3"})," Video"]}),ut.text_content&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(ea,{className:"h-3 w-3"})," Text"]}),ut.duration_minutes&&e.jsxs("span",{children:[ut.duration_minutes," min"]}),ut.resources&&ut.resources.length>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(pd,{className:"h-3 w-3"})," ",ut.resources.length," resource(s)"]})]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx($,{size:"sm",variant:"ghost",onClick:et=>{var at;et.stopPropagation(),p(ut),v({title:ut.title,description:ut.description||"",video_url:ut.video_url||"",text_content:ut.text_content||"",duration_minutes:((at=ut.duration_minutes)==null?void 0:at.toString())||""})},children:e.jsx(ui,{className:"h-3.5 w-3.5"})}),e.jsx($,{size:"sm",variant:"ghost",className:"text-destructive",onClick:et=>{et.stopPropagation(),Re(ut.id)},children:e.jsx(Un,{className:"h-3.5 w-3.5"})})]})]}),M.has(ut.id)&&e.jsxs("div",{className:"border-t bg-muted/30 p-4 space-y-3",children:[ut.description&&e.jsx("p",{className:"text-sm text-muted-foreground",children:ut.description}),ut.video_url&&e.jsxs("div",{className:"text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"Video: "}),e.jsx("a",{href:ut.video_url,target:"_blank",rel:"noreferrer",className:"text-primary hover:underline break-all",children:ut.video_url})]}),ut.text_content&&e.jsx("div",{className:"text-sm bg-background rounded-md p-3 border max-h-40 overflow-auto whitespace-pre-wrap",children:ut.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($,{size:"sm",variant:"outline",className:"h-7 text-xs",onClick:()=>{j(ut.id),A({title:"",resource_type:"link",url:""})},children:[e.jsx(nn,{className:"h-3 w-3 mr-1"})," Add Resource"]})]}),ut.resources&&ut.resources.length>0?e.jsx("div",{className:"space-y-1",children:ut.resources.map(et=>e.jsxs("div",{className:"flex items-center gap-2 text-sm bg-background rounded p-2 border",children:[e.jsx(qe,{variant:"outline",className:"text-[10px]",children:et.resource_type}),e.jsx("span",{className:"flex-1 truncate",children:et.title}),et.url&&e.jsx("a",{href:et.url,target:"_blank",rel:"noreferrer",className:"text-primary hover:underline text-xs",children:"Open"}),e.jsx($,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0 text-destructive",onClick:()=>d.mutateAsync(et.id),children:e.jsx(mr,{className:"h-3 w-3"})})]},et.id))}):e.jsx("p",{className:"text-xs text-muted-foreground",children:"No resources yet"})]})]})]},ut.id)),e.jsxs($,{variant:"outline",className:"w-full border-dashed",onClick:()=>{x(!0),v({title:"",description:"",video_url:"",text_content:"",duration_minutes:""})},children:[e.jsx(nn,{className:"h-4 w-4 mr-2"})," Add Module"]})]}),e.jsx(cs,{value:"access",className:"mt-6 space-y-4",children:e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsx(Yt,{className:"text-base",children:"Who can access this course?"})}),e.jsxs(De,{className:"space-y-5",children:[e.jsxs("div",{className:Ot("flex items-center gap-3 p-4 rounded-xl border-2 cursor-pointer transition-all",Te?"border-primary bg-primary/5":"border-muted hover:border-muted-foreground/30"),onClick:Fe,children:[e.jsx("div",{className:Ot("h-10 w-10 rounded-full flex items-center justify-center shrink-0",Te?"bg-primary/15 text-primary":"bg-muted text-muted-foreground"),children:e.jsx(kc,{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(On,{checked:Te,onCheckedChange:Fe})]}),!Te&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-semibold",children:"Select Brokerages"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:Ie.length===0?"No brokerages selected — agents won't see this course":`${Ie.length} brokerage${Ie.length!==1?"s":""} selected`})]}),Ie.length>0&&e.jsx($,{size:"sm",variant:"ghost",className:"text-xs text-muted-foreground",onClick:Ge,children:"Clear all"})]}),e.jsx(be,{placeholder:"Search brokerages...",value:oe,onChange:ut=>me(ut.target.value),className:"h-9"}),e.jsx("div",{className:"border rounded-lg divide-y max-h-[360px] overflow-auto",children:Ue.length===0?e.jsx("div",{className:"p-4 text-center text-sm text-muted-foreground",children:"No brokerages found"}):Ue.map(ut=>{const nt=Ie.includes(ut.id);return e.jsxs("div",{className:Ot("flex items-center gap-3 px-3 py-2.5 cursor-pointer transition-colors",nt?"bg-primary/5":"hover:bg-muted/50"),onClick:()=>Oe(ut.id),children:[e.jsx("div",{className:Ot("h-5 w-5 rounded border-2 flex items-center justify-center shrink-0 transition-colors",nt?"bg-primary border-primary":"border-muted-foreground/30"),children:nt&&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(Gi,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsx("span",{className:"text-sm flex-1 truncate",children:ut.name}),nt&&e.jsx(qe,{variant:"secondary",className:"text-[10px] shrink-0",children:"Active"})]},ut.id)})})]})]})]})}),e.jsxs(cs,{value:"settings",className:"mt-6 space-y-4",children:[e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsx(Yt,{className:"text-base",children:"Course Thumbnail"})}),e.jsx(De,{children:e.jsxs("div",{className:"flex items-start gap-6",children:[n.thumbnail_url?e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:n.thumbnail_url,alt:"Course thumbnail",className:"w-48 h-28 object-cover rounded-lg border"}),e.jsx("button",{onClick:()=>a.mutateAsync({id:n.id,thumbnail_url:null}).then(()=>ae.success("Thumbnail removed")),className:"absolute -top-2 -right-2 bg-destructive text-destructive-foreground rounded-full p-1 opacity-0 group-hover:opacity-100 transition-opacity",children:e.jsx(mr,{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(gb,{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:Y,type:"file",accept:"image/*",className:"hidden",onChange:async ut=>{var et;const nt=(et=ut.target.files)==null?void 0:et[0];if(!(!nt||!n)){ee(!0);try{const at=nt.name.split(".").pop(),wt=`${n.id}/thumbnail.${at}`,{error:rt}=await V.storage.from("lms-thumbnails").upload(wt,nt,{upsert:!0});if(rt)throw rt;const{data:Ft}=V.storage.from("lms-thumbnails").getPublicUrl(wt),Ut=`${Ft.publicUrl}?t=${Date.now()}`;await a.mutateAsync({id:n.id,thumbnail_url:Ut}),ae.success("Thumbnail uploaded")}catch{ae.error("Failed to upload thumbnail")}finally{ee(!1),Y.current&&(Y.current.value="")}}}}),e.jsxs($,{variant:"outline",size:"sm",disabled:se,onClick:()=>{var ut;return(ut=Y.current)==null?void 0:ut.click()},children:[se?e.jsx(Jt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(gi,{className:"h-4 w-4 mr-2"}),se?"Uploading...":"Upload Thumbnail"]})]})]})})]}),e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsx(Yt,{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(On,{checked:n.is_sequential,onCheckedChange:ut=>a.mutateAsync({id:n.id,is_sequential:ut}).then(()=>ae.success("Updated"))})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Published"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Make this course visible to agents with access"})]}),e.jsx(On,{checked:n.is_published,onCheckedChange:ut=>a.mutateAsync({id:n.id,is_published:ut}).then(()=>ae.success("Updated"))})]})]})]})]})]})]}),e.jsx(zs,{open:g||!!m,onOpenChange:ut=>{ut||(x(!1),p(null))},children:e.jsxs(Rs,{className:"max-w-lg",children:[e.jsxs(Vs,{children:[e.jsx($s,{children:m?"Edit Module":"Add Module"}),e.jsx(Cr,{children:"Configure the module content"})]}),e.jsxs("div",{className:"space-y-4 max-h-[60vh] overflow-auto",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Title"}),e.jsx(be,{value:y.title,onChange:ut=>v(nt=>({...nt,title:ut.target.value})),placeholder:"Module title"})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Description"}),e.jsx(Ls,{value:y.description,onChange:ut=>v(nt=>({...nt,description:ut.target.value})),placeholder:"Brief description",rows:2})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Video"}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:Ot("border-2 border-dashed rounded-lg p-4 text-center cursor-pointer transition-colors hover:border-primary/50",P?"border-primary bg-primary/5":"border-muted-foreground/25"),onClick:()=>{var ut;return(ut=H.current)==null?void 0:ut.click()},children:[e.jsx("input",{ref:H,type:"file",accept:"video/*",className:"hidden",onChange:ut=>{var et;const nt=(et=ut.target.files)==null?void 0:et[0];nt&&(R(nt),v(at=>({...at,video_url:""})))}}),P?e.jsxs("div",{className:"flex items-center justify-center gap-2 text-sm",children:[e.jsx(ia,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"font-medium text-primary",children:P.name}),e.jsx($,{type:"button",size:"sm",variant:"ghost",className:"h-6 w-6 p-0",onClick:ut=>{ut.stopPropagation(),R(null)},children:e.jsx(mr,{className:"h-3 w-3"})})]}):e.jsxs("div",{className:"flex flex-col items-center gap-1 text-muted-foreground",children:[e.jsx(gi,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs",children:"Click to upload a video file"})]})]}),U&&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(Jt,{className:"h-3.5 w-3.5 animate-spin"}),e.jsxs("span",{children:["Uploading to Bunny.net... ",O,"%"]})]}),e.jsx(ho,{value:O,className:"h-1.5"})]}),!P&&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(be,{value:y.video_url,onChange:ut=>v(nt=>({...nt,video_url:ut.target.value})),placeholder:"YouTube, Vimeo, or Bunny.net URL"})]})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Text Content"}),e.jsx(Ls,{value:y.text_content,onChange:ut=>v(nt=>({...nt,text_content:ut.target.value})),placeholder:"Additional text content, instructions, notes...",rows:4})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Duration (minutes)"}),e.jsx(be,{type:"number",value:y.duration_minutes,onChange:ut=>v(nt=>({...nt,duration_minutes:ut.target.value})),placeholder:"e.g. 15"})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>{x(!1),p(null),R(null)},children:"Cancel"}),e.jsxs($,{onClick:m?Ee:Ye,disabled:!y.title.trim()||U,children:[U?e.jsx(Jt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Ml,{className:"h-4 w-4 mr-2"}),U?"Uploading...":m?"Save Changes":"Add Module"]})]})]})}),e.jsx(zs,{open:!!_,onOpenChange:ut=>{ut||j(null)},children:e.jsxs(Rs,{children:[e.jsxs(Vs,{children:[e.jsx($s,{children:"Add Resource"}),e.jsx(Cr,{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(re,{children:"Title"}),e.jsx(be,{value:C.title,onChange:ut=>A(nt=>({...nt,title:ut.target.value})),placeholder:"Resource title"})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Type"}),e.jsxs(bs,{value:C.resource_type,onValueChange:ut=>A(nt=>({...nt,resource_type:ut})),children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"link",children:"Link"}),e.jsx(We,{value:"pdf",children:"PDF"}),e.jsx(We,{value:"template",children:"Template"}),e.jsx(We,{value:"worksheet",children:"Worksheet"})]})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"URL"}),e.jsx(be,{value:C.url,onChange:ut=>A(nt=>({...nt,url:ut.target.value})),placeholder:"https://..."})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>j(null),children:"Cancel"}),e.jsx($,{onClick:()=>_&&ke(_),disabled:!C.title.trim(),children:"Add Resource"})]})]})}),e.jsx(zs,{open:_e,onOpenChange:ve,children:e.jsxs(Rs,{children:[e.jsxs(Vs,{children:[e.jsx($s,{children:"Edit Course"}),e.jsx(Cr,{children:"Update the course title and description"})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Title"}),e.jsx(be,{value:Q,onChange:ut=>te(ut.target.value)})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Description"}),e.jsx(Ls,{value:le,onChange:ut=>fe(ut.target.value),rows:3})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>ve(!1),children:"Cancel"}),e.jsx($,{onClick:tt,disabled:!Q.trim(),children:"Save"})]})]})})]})}function HOn(){return pt({queryKey:["lms-stats-overview"],queryFn:async()=>{const{data:s,error:t}=await V.rpc("get_lms_stats");if(t)throw t;return s}})}function GOn(){return pt({queryKey:["lms-stats-courses"],queryFn:async()=>{const{data:s,error:t}=await V.rpc("get_lms_course_stats");if(t)throw t;return s||[]}})}function WOn(s){return pt({queryKey:["lms-stats-agents",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await V.rpc("get_lms_agent_progress",{p_course_id:s});if(n)throw n;return t||[]},enabled:!!s})}function KOn(){const s=Jn(),{data:t,isLoading:n}=HOn(),{data:r,isLoading:a}=GOn(),[i,l]=k.useState(null),{data:o,isLoading:c}=WOn(i),[d,u]=k.useState(""),h=r==null?void 0:r.find(g=>g.course_id===i),m=o==null?void 0:o.filter(g=>{var x,y;return!d||((x=g.agent_name)==null?void 0:x.toLowerCase().includes(d.toLowerCase()))||((y=g.email)==null?void 0:y.toLowerCase().includes(d.toLowerCase()))}),p=[{label:"Total Courses",value:(t==null?void 0:t.total_courses)??0,icon:wg,color:"text-primary"},{label:"Published",value:(t==null?void 0:t.published_courses)??0,icon:Gr,color:"text-emerald-500"},{label:"Enrolled Agents",value:(t==null?void 0:t.total_enrollments)??0,icon:Xn,color:"text-blue-500"},{label:"Modules Completed",value:(t==null?void 0:t.total_completions)??0,icon:ql,color:"text-amber-500"},{label:"Active (30d)",value:(t==null?void 0:t.active_learners)??0,icon:mc,color:"text-violet-500"},{label:"Total Modules",value:(t==null?void 0:t.total_modules)??0,icon:Ul,color:"text-rose-500"}];return e.jsx(Xs,{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($,{variant:"ghost",size:"icon",onClick:()=>s("/admin/lms"),children:e.jsx(Ia,{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(Bm,{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:p.map(g=>e.jsx(we,{className:Ot("transition-all",n&&"animate-pulse"),children:e.jsxs(De,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(g.icon,{className:Ot("h-4 w-4",g.color)}),e.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:g.label})]}),e.jsx("p",{className:"text-2xl font-bold text-foreground",children:n?"—":g.value})]})},g.label))}),e.jsxs("div",{className:"grid grid-cols-1 xl:grid-cols-5 gap-6",children:[e.jsxs("div",{className:"xl:col-span-2 space-y-3",children:[e.jsxs("h2",{className:"text-lg font-semibold text-foreground flex items-center gap-2",children:[e.jsx(Ul,{className:"h-5 w-5 text-primary"}),"Course Breakdown"]}),a?e.jsx("div",{className:"space-y-3",children:[1,2,3].map(g=>e.jsx(we,{className:"animate-pulse",children:e.jsx(De,{className:"p-4",children:e.jsx("div",{className:"h-16 bg-muted rounded"})})},g))}):r!=null&&r.length?e.jsx("div",{className:"space-y-2",children:r.map(g=>{const x=i===g.course_id;return e.jsx(we,{className:Ot("cursor-pointer transition-all hover:shadow-md",x?"border-primary ring-1 ring-primary/30 shadow-md":"hover:border-primary/40"),onClick:()=>l(x?null:g.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:g.course_title}),e.jsx(qe,{variant:g.is_published?"default":"secondary",className:"shrink-0 text-[10px] px-1.5 py-0",children:g.is_published?"Live":"Draft"})]})}),e.jsx(fi,{className:Ot("h-4 w-4 text-muted-foreground transition-transform shrink-0 ml-2",x&&"rotate-90")})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3 text-center",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-lg font-bold text-foreground",children:g.enrolled_agents}),e.jsx("p",{className:"text-[10px] text-muted-foreground uppercase tracking-wide",children:"Enrolled"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-lg font-bold text-foreground",children:g.total_completions}),e.jsx("p",{className:"text-[10px] text-muted-foreground uppercase tracking-wide",children:"Completed"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-lg font-bold text-foreground",children:g.total_modules}),e.jsx("p",{className:"text-[10px] text-muted-foreground uppercase tracking-wide",children:"Modules"})]})]}),e.jsxs("div",{className:"mt-3",children:[e.jsxs("div",{className:"flex items-center justify-between text-xs mb-1",children:[e.jsx("span",{className:"text-muted-foreground",children:"Avg. Completion"}),e.jsxs("span",{className:"font-semibold text-foreground",children:[g.avg_completion_pct,"%"]})]}),e.jsx(ho,{value:g.avg_completion_pct,className:"h-2"})]})]})},g.course_id)})}):e.jsx(we,{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(ck,{className:"h-5 w-5 text-primary"}),h?`Agent Progress — ${h.course_title}`:"Agent Progress"]}),i?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"relative",children:[e.jsx(Yr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{value:d,onChange:g=>u(g.target.value),placeholder:"Search agents...",className:"pl-9"})]}),c?e.jsx("div",{className:"space-y-2",children:[1,2,3,4].map(g=>e.jsx(we,{className:"animate-pulse",children:e.jsx(De,{className:"p-4",children:e.jsx("div",{className:"h-12 bg-muted rounded"})})},g))}):m!=null&&m.length?e.jsx("div",{className:"space-y-2 max-h-[600px] overflow-y-auto pr-1",children:m.map((g,x)=>{const y=g.completion_pct>=100;return e.jsx(we,{className:Ot("transition-all",y&&"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:Ot("flex items-center justify-center w-7 h-7 rounded-full text-xs font-bold shrink-0",x===0?"bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-400":x===1?"bg-slate-100 text-slate-600 dark:bg-slate-800 dark:text-slate-400":x===2?"bg-orange-100 text-orange-700 dark:bg-orange-900/30 dark:text-orange-400":"bg-muted text-muted-foreground"),children:x+1}),e.jsxs(Wa,{className:"h-9 w-9 shrink-0",children:[e.jsx(eo,{src:g.avatar_url||void 0}),e.jsx(Ka,{className:"text-xs bg-primary/10 text-primary",children:(g.agent_name||g.email||"?").charAt(0).toUpperCase()})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"text-sm font-medium text-foreground truncate",children:g.agent_name||g.email}),y&&e.jsxs(qe,{variant:"default",className:"text-[10px] px-1.5 py-0 bg-emerald-500 hover:bg-emerald-600 shrink-0",children:[e.jsx(Gr,{className:"h-3 w-3 mr-0.5"})," Complete"]})]}),e.jsxs("div",{className:"flex items-center gap-3 text-[11px] text-muted-foreground mt-0.5",children:[e.jsxs("span",{children:[g.modules_completed,"/",g.total_modules," modules"]}),g.last_activity&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(sa,{className:"h-3 w-3"}),Ys(new Date(g.last_activity),"MMM d, yyyy")]})]})]}),e.jsxs("div",{className:"text-right shrink-0 w-20",children:[e.jsxs("p",{className:Ot("text-sm font-bold",y?"text-emerald-600 dark:text-emerald-400":"text-foreground"),children:[g.completion_pct,"%"]}),e.jsx(ho,{value:g.completion_pct,className:"h-1.5 mt-1"})]})]})})},g.user_id)})}):e.jsx(we,{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(we,{className:"border-dashed",children:e.jsxs(De,{className:"py-16 text-center",children:[e.jsx(Xn,{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 YOn(){const{user:s}=ks(),t=Jn(),{data:n,isLoading:r}=BOn();return e.jsx(Xs,{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(Bm,{className:"h-6 w-6 text-primary"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"LevelUp U"}),e.jsx("p",{className:"text-muted-foreground text-sm",children:"Your training & development hub"})]})]})}),e.jsx("div",{className:"absolute top-0 right-0 w-64 h-64 bg-primary/5 rounded-full -translate-y-1/2 translate-x-1/2"})]}),r?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:[1,2,3].map(a=>e.jsx(we,{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))}):n!=null&&n.length?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:n.map(a=>e.jsx(ZOn,{course:a,userId:s==null?void 0:s.id,onClick:()=>t(`/levelup-u/${a.id}`)},a.id))}):e.jsx(we,{className:"border-dashed",children:e.jsxs(De,{className:"flex flex-col items-center justify-center py-16 text-center",children:[e.jsx(wg,{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 ZOn({course:s,userId:t,onClick:n}){var o;const r=((o=s.modules)==null?void 0:o.length)??0,{data:a}=GVt(s.id),i=(a==null?void 0:a.filter(c=>c.completed).length)??0,l=r>0?Math.round(i/r*100):0;return e.jsxs(we,{className:"group cursor-pointer hover:shadow-lg transition-all hover:border-primary/50 overflow-hidden",onClick:n,children:[s.thumbnail_url?e.jsx("div",{className:"aspect-video bg-muted overflow-hidden",children:e.jsx("img",{src:s.thumbnail_url,alt:s.title,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"})}):e.jsx("div",{className:"aspect-video bg-gradient-to-br from-primary/15 via-primary/5 to-muted flex items-center justify-center",children:e.jsx(Bm,{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(wg,{className:"h-3.5 w-3.5"}),r," module",r!==1?"s":""]}),e.jsxs("span",{className:"flex items-center gap-1",children:[s.is_sequential?e.jsx(_2,{className:"h-3.5 w-3.5"}):e.jsx(Y8,{className:"h-3.5 w-3.5"}),s.is_sequential?"In order":"Any order"]})]}),r>0&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsxs("span",{className:"text-muted-foreground",children:[i," of ",r," completed"]}),e.jsxs("span",{className:"font-medium text-foreground",children:[l,"%"]})]}),e.jsx(ho,{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(fi,{className:"h-3.5 w-3.5"})]})})]})]})}function XOn(){const{courseId:s}=oo(),t=Jn(),{user:n}=ks(),{data:r,isLoading:a}=$On(s),{data:i}=GVt(s),l=UOn(),[o,c]=k.useState(null),d=(r==null?void 0:r.modules)||[],u=new Set((i==null?void 0:i.filter(_=>_.completed).map(_=>_.module_id))||[]),h=u.size,m=d.length>0?Math.round(h/d.length*100):0;k.useEffect(()=>{if(d.length>0&&!o){const _=d.find(j=>!u.has(j.id));c((_==null?void 0:_.id)||d[0].id)}},[d,o,u]);const p=d.find(_=>_.id===o),g=d.findIndex(_=>_.id===o),x=(_,j)=>{if(!(r!=null&&r.is_sequential)||j===0)return!1;for(let C=0;C{if(!(!p||!n||!s))try{await l.mutateAsync({courseId:s,moduleId:p.id,userId:n.id}),ae.success("Module completed! 🎉"),g{const j=_.match(/(?:youtube\.com\/(?:watch\?v=|embed\/)|youtu\.be\/)([a-zA-Z0-9_-]{11})/);if(j)return`https://www.youtube.com/embed/${j[1]}`;const C=_.match(/vimeo\.com\/(\d+)/);if(C)return`https://player.vimeo.com/video/${C[1]}`;const A=_.match(/(?:iframe\.mediadelivery\.net|video\.bunnycdn\.com)\/(?:play|embed)\/(\d+)\/([a-f0-9-]+)/);return A?`https://iframe.mediadelivery.net/embed/${A[1]}/${A[2]}?responsive=true`:_};return a?e.jsx(Xs,{title:"Loading...",children:e.jsx("div",{className:"flex items-center justify-center py-20",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):r?e.jsx(Xs,{title:r.title,children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx($,{variant:"ghost",size:"icon",onClick:()=>t("/levelup-u"),children:e.jsx(Ia,{className:"h-5 w-5"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h1",{className:"text-xl font-bold text-foreground truncate",children:r.title}),e.jsxs("div",{className:"flex items-center gap-3 text-xs text-muted-foreground mt-0.5",children:[e.jsxs("span",{children:[h,"/",d.length," completed"]}),e.jsxs("span",{children:[m,"%"]})]})]}),e.jsx("div",{className:"w-32",children:e.jsx(ho,{value:m,className:"h-2"})})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-[320px_1fr] gap-4 items-start",children:[e.jsx(we,{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(Eo,{className:"max-h-[calc(100vh-280px)]",children:e.jsx("div",{className:"p-1",children:d.map((_,j)=>{const C=x(_,j),A=u.has(_.id),M=_.id===o;return e.jsxs("button",{disabled:C,onClick:()=>!C&&c(_.id),className:Ot("w-full flex items-center gap-3 p-3 rounded-lg text-left transition-all text-sm",M?"bg-primary/10 text-primary":"hover:bg-muted/50",C&&"opacity-50 cursor-not-allowed"),children:[e.jsx("div",{className:"shrink-0",children:C?e.jsx(fu,{className:"h-4 w-4 text-muted-foreground"}):A?e.jsx(Gr,{className:"h-4 w-4 text-green-500"}):e.jsx(rx,{className:"h-4 w-4 text-muted-foreground"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("p",{className:Ot("font-medium truncate",M&&"text-primary"),children:[j+1,". ",_.title]}),_.duration_minutes&&e.jsxs("span",{className:"text-[11px] text-muted-foreground flex items-center gap-0.5 mt-0.5",children:[e.jsx(sa,{className:"h-3 w-3"})," ",_.duration_minutes," min"]})]})]},_.id)})})})]})}),e.jsx("div",{className:"space-y-4",children:p?e.jsxs(e.Fragment,{children:[p.video_url&&e.jsx(we,{className:"overflow-hidden",children:e.jsx("div",{className:"aspect-video bg-black",children:e.jsx("iframe",{src:v(p.video_url),className:"w-full h-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0})})}),e.jsx(we,{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:p.title}),p.description&&e.jsx("p",{className:"text-muted-foreground mt-1",children:p.description})]}),u.has(p.id)?e.jsxs(qe,{className:"bg-green-500/15 text-green-600 border-green-500/30 shrink-0",children:[e.jsx(Gr,{className:"h-3.5 w-3.5 mr-1"})," Completed"]}):e.jsxs($,{size:"sm",onClick:y,disabled:l.isPending,children:[e.jsx(Gr,{className:"h-4 w-4 mr-1"}),"Mark Complete"]})]}),p.text_content&&e.jsx("div",{className:"prose prose-sm max-w-none text-foreground border-t pt-4 whitespace-pre-wrap",children:p.text_content}),p.resources&&p.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:p.resources.map(_=>e.jsxs("a",{href:_.url||_.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:[_.resource_type==="pdf"?e.jsx(ea,{className:"h-4 w-4 text-red-500 shrink-0"}):_.resource_type==="template"?e.jsx(Bm,{className:"h-4 w-4 text-purple-500 shrink-0"}):e.jsx(pd,{className:"h-4 w-4 text-blue-500 shrink-0"}),e.jsx("span",{className:"flex-1 truncate",children:_.title}),e.jsx(Ir,{className:"h-3.5 w-3.5 text-muted-foreground shrink-0"})]},_.id))})]}),e.jsxs("div",{className:"flex items-center justify-between border-t pt-4",children:[e.jsxs($,{variant:"outline",size:"sm",disabled:g===0,onClick:()=>g>0&&c(d[g-1].id),children:[e.jsx(Ia,{className:"h-3.5 w-3.5 mr-1"})," Previous"]}),gc(d[g+1].id),children:["Next ",e.jsx(fi,{className:"h-3.5 w-3.5 ml-1"})]}):m===100&&e.jsx(qe,{className:"bg-green-500/15 text-green-600 border-green-500/30 text-sm px-3 py-1.5",children:"🎉 Course Complete!"})]})]})})]}):e.jsx(we,{children:e.jsx(De,{className:"flex items-center justify-center py-16 text-muted-foreground",children:"Select a module to begin"})})})]})]})}):e.jsx(Xs,{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($,{variant:"outline",className:"mt-4",onClick:()=>t("/levelup-u"),children:[e.jsx(Ia,{className:"h-4 w-4 mr-2"})," Back"]})]})})}function QOn({headline:s,subtext:t,primaryColor:n,accentColor:r,heroImageUrl:a,logoUrl:i,brokerageName:l}){return e.jsxs("section",{className:"relative min-h-screen flex items-center justify-center overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0",style:{background:`linear-gradient(160deg, ${r} 0%, ${n} 50%, ${r}ee 100%)`}}),a&&e.jsx("div",{className:"absolute inset-0 bg-cover bg-center opacity-20",style:{backgroundImage:`url(${a})`}}),e.jsx("div",{className:"absolute inset-0 opacity-[0.03]",style:{backgroundImage:"radial-gradient(circle at 25% 25%, white 1px, transparent 1px), radial-gradient(circle at 75% 75%, white 1px, transparent 1px)",backgroundSize:"60px 60px"}}),e.jsx("div",{className:"absolute bottom-0 left-0 right-0 h-32 bg-gradient-to-t from-white to-transparent"}),e.jsxs("div",{className:"relative z-10 text-center max-w-4xl mx-auto px-6 py-24",children:[i&&e.jsx(_r.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(_r.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(_r.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(_r.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(_r.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{duration:.7,delay:.9},className:"flex flex-col sm:flex-row items-center justify-center gap-4",children:[e.jsxs("a",{href:"#apply",className:"group inline-flex items-center gap-3 px-10 py-4 rounded-full text-lg font-semibold shadow-2xl transition-all duration-300 hover:scale-105 hover:shadow-3xl",style:{backgroundColor:"white",color:r},children:["Get In Touch",e.jsx(xi,{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(_r.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 hj({children:s,className:t="",delay:n=0,direction:r="up"}){const a=k.useRef(null),i=m4s(a,{once:!0,margin:"-80px"}),l={hidden:{opacity:0,y:r==="up"?40:0,x:r==="left"?-40:r==="right"?40:0},visible:{opacity:1,y:0,x:0}};return e.jsx(_r.div,{ref:a,initial:"hidden",animate:i?"visible":"hidden",variants:l,transition:{duration:.7,delay:n,ease:[.25,.46,.45,.94]},className:t,children:s})}function JOn({benefits:s,accentColor:t,primaryColor:n}){return s.length===0?null:e.jsx("section",{id:"benefits",className:"py-24 md:py-32 px-6 bg-white",children:e.jsxs("div",{className:"max-w-6xl mx-auto",children:[e.jsx(hj,{children:e.jsxs("div",{className:"text-center mb-16",children:[e.jsx("span",{className:"text-sm font-semibold tracking-[0.15em] uppercase mb-4 block",style:{color:n},children:"Why Top Agents Choose Us"}),e.jsx("h2",{className:"text-3xl md:text-5xl font-bold mb-4 tracking-tight",style:{color:t},children:"Built For Your Success"}),e.jsx("div",{className:"w-16 h-1 mx-auto rounded-full mt-6",style:{backgroundColor:n}})]})}),e.jsx("div",{className:"grid md:grid-cols-2 lg:grid-cols-3 gap-6 md:gap-8",children:s.map((r,a)=>e.jsx(hj,{delay:a*.1,children:e.jsxs("div",{className:"group relative p-8 rounded-2xl border border-gray-100 bg-white hover:border-transparent hover:shadow-2xl transition-all duration-500 h-full",children:[e.jsx("div",{className:"absolute inset-0 rounded-2xl opacity-0 group-hover:opacity-100 transition-opacity duration-500",style:{background:`linear-gradient(135deg, ${n}08, ${t}05)`}}),e.jsxs("div",{className:"relative z-10",children:[e.jsx("div",{className:"w-14 h-14 rounded-xl flex items-center justify-center text-2xl mb-5 transition-transform duration-300 group-hover:scale-110",style:{backgroundColor:`${n}12`},children:r.icon}),e.jsx("h3",{className:"text-xl font-bold mb-3 tracking-tight",style:{color:t},children:r.title}),e.jsx("p",{className:"text-gray-500 leading-relaxed text-[15px]",children:r.description})]})]})},a))})]})})}function eFn({images:s,primaryColor:t,accentColor:n}){const[r,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(hj,{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(Xn,{className:"h-4 w-4",style:{color:t}}),e.jsx("span",{className:"text-sm font-medium text-gray-600",children:"Life at Our Brokerage"})]}),e.jsx("h2",{className:"text-3xl md:text-5xl font-bold tracking-tight",style:{color:n},children:"Our Team & Culture"})]})}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-3 md:gap-4",children:s.map((i,l)=>e.jsx(hj,{delay:l*.08,children:e.jsxs("button",{onClick:()=>a(l),className:"relative w-full aspect-[4/3] overflow-hidden rounded-xl group cursor-pointer",children:[e.jsx("img",{src:i,alt:`Team ${l+1}`,className:"w-full h-full object-cover transition-transform duration-700 group-hover:scale-110"}),e.jsx("div",{className:"absolute inset-0 bg-black/0 group-hover:bg-black/20 transition-all duration-500"})]})},l))})]})}),r!==null&&e.jsxs("div",{className:"fixed inset-0 z-50 bg-black/90 flex items-center justify-center p-4 cursor-pointer",onClick:()=>a(null),children:[e.jsx("button",{onClick:()=>a(null),className:"absolute top-6 right-6 text-white/80 hover:text-white transition-colors",children:e.jsx(mr,{className:"h-8 w-8"})}),e.jsx("img",{src:s[r],alt:"Gallery",className:"max-w-full max-h-[85vh] object-contain rounded-lg",onClick:i=>i.stopPropagation()})]})]})}function tFn({testimonials:s,primaryColor:t,accentColor:n}){return s.length===0?null:e.jsx("section",{className:"py-24 md:py-32 px-6 bg-white",children:e.jsxs("div",{className:"max-w-6xl mx-auto",children:[e.jsx(hj,{children:e.jsxs("div",{className:"text-center mb-16",children:[e.jsx("span",{className:"text-sm font-semibold tracking-[0.15em] uppercase mb-4 block",style:{color:t},children:"Agent Testimonials"}),e.jsx("h2",{className:"text-3xl md:text-5xl font-bold tracking-tight",style:{color:n},children:"Hear From Our Agents"}),e.jsx("div",{className:"w-16 h-1 mx-auto rounded-full mt-6",style:{backgroundColor:t}})]})}),e.jsx("div",{className:"grid md:grid-cols-2 gap-8",children:s.map((r,a)=>{var i;return e.jsx(hj,{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(ik,{className:"h-8 w-8 mb-5 opacity-20",style:{color:t}}),e.jsxs("p",{className:"text-gray-700 text-lg leading-relaxed mb-8 font-light italic",children:['"',r.quote,'"']}),e.jsxs("div",{className:"flex items-center gap-4",children:[r.photo_url?e.jsx("img",{src:r.photo_url,alt:r.name,className:"h-12 w-12 rounded-full object-cover ring-2 ring-white shadow-md"}):e.jsx("div",{className:"h-12 w-12 rounded-full flex items-center justify-center text-white text-base font-bold shadow-md",style:{background:`linear-gradient(135deg, ${t}, ${n})`},children:((i=r.name)==null?void 0:i[0])||"?"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold text-base",style:{color:n},children:r.name}),r.role&&e.jsx("p",{className:"text-sm text-gray-500",children:r.role})]})]})]})},a)})})]})})}function sFn({form:s,setForm:t,onSubmit:n,isPending:r,primaryColor:a,accentColor:i}){return e.jsxs("section",{id:"apply",className:"py-24 md:py-32 px-6 relative overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0 top-0 h-1/2",style:{background:`linear-gradient(160deg, ${i}, ${a})`}}),e.jsx("div",{className:"absolute inset-0 top-1/2 bg-gray-50"}),e.jsxs("div",{className:"relative z-10 max-w-xl mx-auto",children:[e.jsx(hj,{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(hj,{delay:.2,children:e.jsxs("form",{onSubmit:l=>{l.preventDefault(),n()},className:"bg-white rounded-3xl shadow-2xl p-8 md:p-10 space-y-5",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{className:"text-gray-700 text-sm font-medium",children:"First Name *"}),e.jsx(be,{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(re,{className:"text-gray-700 text-sm font-medium",children:"Last Name"}),e.jsx(be,{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(re,{className:"text-gray-700 text-sm font-medium",children:"Email *"}),e.jsx(be,{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(re,{className:"text-gray-700 text-sm font-medium",children:"Phone"}),e.jsx(be,{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(re,{className:"text-gray-700 text-sm font-medium",children:"Current Brokerage"}),e.jsx(be,{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(re,{className:"text-gray-700 text-sm font-medium",children:"License #"}),e.jsx(be,{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(re,{className:"text-gray-700 text-sm font-medium",children:"Years Experience"}),e.jsx(be,{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(re,{className:"text-gray-700 text-sm font-medium",children:"Annual Production"}),e.jsx(be,{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(re,{className:"text-gray-700 text-sm font-medium",children:"Why are you interested?"}),e.jsx(Ls,{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($,{type:"submit",className:"w-full h-13 text-base font-semibold rounded-xl group transition-all duration-300 hover:shadow-lg",style:{background:`linear-gradient(135deg, ${a}, ${i})`},disabled:r,children:r?e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-4 w-4 animate-spin rounded-full border-2 border-white border-t-transparent"}),"Submitting..."]}):e.jsxs("span",{className:"flex items-center gap-2",children:["Send My Info",e.jsx(xi,{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(Ng,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"Your information is confidential and will not be shared."})]})]})})]})]})}function nFn({form:s,setForm:t,onSubmit:n,isPending:r,primaryColor:a,accentColor:i,showConfidentialBadges:l=!0}){const[o,c]=k.useState(1),[d,u]=k.useState(""),h=3,m=!!s.first_name&&!!s.email,p=g=>{u(g),t(x=>({...x,why_interested:g})),setTimeout(()=>c(2),200)};return e.jsxs("section",{id:"apply",className:"py-24 md:py-32 px-6 relative overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0 top-0 h-1/2",style:{background:`linear-gradient(160deg, ${i}, ${a})`}}),e.jsx("div",{className:"absolute inset-0 top-1/2 bg-gray-50"}),e.jsxs("div",{className:"relative z-10 max-w-xl mx-auto",children:[e.jsx(hj,{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(fu,{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(hj,{delay:.15,children:e.jsxs("div",{className:"bg-white rounded-3xl shadow-2xl p-8 md:p-10",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-7",children:[[1,2,3].map(g=>e.jsx("div",{className:"h-1 flex-1 rounded-full transition-colors duration-500",style:{backgroundColor:g<=o?a:"#e5e7eb"}},g)),e.jsxs("span",{className:"text-xs text-gray-400 ml-2",children:[o,"/",h]})]}),e.jsxs(Yq,{mode:"wait",children:[o===1&&e.jsxs(_r.div,{initial:{opacity:0,x:20},animate:{opacity:1,x:0},exit:{opacity:0,x:-20},transition:{duration:.25},className:"space-y-3",children:[e.jsx("h3",{className:"text-lg font-semibold mb-1",style:{color:i},children:"What's most important to you?"}),e.jsx("p",{className:"text-sm text-gray-500 mb-5",children:"Pick the one that resonates most. We'll tailor the conversation."}),[{val:"Better commission split / cap",label:"Better Splits & Caps",icon:"💰"},{val:"Better technology and tools",label:"Better Tech & Tools",icon:"🛠️"},{val:"Better training and mentorship",label:"Better Training",icon:"📚"},{val:"Better culture and team",label:"Better Culture",icon:"🤝"},{val:"Just exploring options confidentially",label:"Just Exploring",icon:"🔍"}].map(g=>e.jsxs("button",{type:"button",onClick:()=>p(g.val),className:"w-full flex items-center gap-3 p-4 rounded-xl border-2 border-gray-100 hover:border-gray-300 transition-all text-left group",children:[e.jsx("span",{className:"text-2xl",children:g.icon}),e.jsx("span",{className:"font-medium text-gray-700 group-hover:text-gray-900 flex-1",children:g.label}),e.jsx(xi,{className:"h-4 w-4 text-gray-300 group-hover:text-gray-500 group-hover:translate-x-1 transition-all"})]},g.val))]},"step1"),o===2&&e.jsxs(_r.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(re,{className:"text-gray-700 text-sm font-medium",children:"First Name *"}),e.jsx(be,{required:!0,value:s.first_name,onChange:g=>t(x=>({...x,first_name:g.target.value})),className:"h-11",placeholder:"John"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{className:"text-gray-700 text-sm font-medium",children:"Last Name"}),e.jsx(be,{value:s.last_name,onChange:g=>t(x=>({...x,last_name:g.target.value})),className:"h-11",placeholder:"Smith"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{className:"text-gray-700 text-sm font-medium",children:"Email *"}),e.jsx(be,{type:"email",required:!0,value:s.email,onChange:g=>t(x=>({...x,email:g.target.value})),className:"h-11",placeholder:"john@email.com"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{className:"text-gray-700 text-sm font-medium",children:"Phone (preferred)"}),e.jsx(be,{value:s.phone,onChange:g=>t(x=>({...x,phone:g.target.value})),className:"h-11",placeholder:"(555) 123-4567"})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsxs($,{type:"button",variant:"ghost",onClick:()=>c(1),className:"h-11",children:[e.jsx(Ia,{className:"h-4 w-4 mr-1"})," Back"]}),e.jsxs($,{type:"button",disabled:!m,onClick:()=>c(3),className:"flex-1 h-11 text-white font-semibold",style:{background:`linear-gradient(135deg, ${a}, ${i})`},children:["Continue ",e.jsx(xi,{className:"h-4 w-4 ml-1"})]})]})]},"step2"),o===3&&e.jsxs(_r.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(re,{className:"text-gray-700 text-sm font-medium",children:"Current Brokerage"}),e.jsx(be,{value:s.current_brokerage,onChange:g=>t(x=>({...x,current_brokerage:g.target.value})),className:"h-11",placeholder:"(stays private)"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{className:"text-gray-700 text-sm font-medium",children:"Years Experience"}),e.jsx(be,{type:"number",min:"0",value:s.experience_years,onChange:g=>t(x=>({...x,experience_years:g.target.value})),className:"h-11"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{className:"text-gray-700 text-sm font-medium",children:"Annual Production"}),e.jsx(be,{value:s.annual_production,onChange:g=>t(x=>({...x,annual_production:g.target.value})),className:"h-11",placeholder:"e.g. $5M"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{className:"text-gray-700 text-sm font-medium",children:"Anything else?"}),e.jsx(Ls,{value:s.why_interested,onChange:g=>t(x=>({...x,why_interested:g.target.value})),rows:2,className:"resize-none",placeholder:"Optional message..."})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsxs($,{type:"button",variant:"ghost",onClick:()=>c(2),className:"h-11",children:[e.jsx(Ia,{className:"h-4 w-4 mr-1"})," Back"]}),e.jsx($,{type:"button",onClick:n,disabled:r,className:"flex-1 h-12 text-white font-semibold rounded-xl",style:{background:`linear-gradient(135deg, ${a}, ${i})`},children:r?e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-4 w-4 animate-spin rounded-full border-2 border-white border-t-transparent"}),"Sending..."]}):e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(ma,{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(Ng,{className:"h-3 w-3"})," Confidential"]}),e.jsxs("div",{className:"flex items-center gap-1 justify-center",children:[e.jsx(bo,{className:"h-3 w-3"})," Text first"]}),e.jsxs("div",{className:"flex items-center gap-1 justify-center",children:[e.jsx(ka,{className:"h-3 w-3"})," No spam"]})]})]})})]})]})}function rFn({config:s,primaryColor:t,accentColor:n,brokerageId:r,brokerageName:a}){const{toast:i}=Fi(),[l,o]=k.useState("250000"),[c,d]=k.useState("12"),[u,h]=k.useState("70"),[m,p]=k.useState("150"),[g,x]=k.useState(""),[y,v]=k.useState(!1),[_,j]=k.useState(!1),C=s.commission_split_pct??80,A=s.cap_amount??16e3,M=s.post_cap_split_pct??100,I=s.monthly_fee??99,P=s.transaction_fee??0,R=k.useMemo(()=>{const U=parseFloat(l)||0,G=Math.max(0,parseInt(c,10)||0),H=parseFloat(u)||0,Y=parseFloat(m)||0,se=U*(H/100)-Y*12-P*G,ee=1-C/100,oe=ee>0?A/ee:U,me=Math.min(U,oe),Q=Math.max(0,U-oe),te=me*ee+Q*(1-M/100),le=U-te-I*12-P*G,fe=le-se;return{currentNet:se,newNet:le,diff:fe}},[l,c,u,m,C,A,M,I,P]),O=U=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(U),B=async U=>{if(U.preventDefault(),!!g){j(!0);try{const{error:G}=await V.from("recruit_lead_magnet_downloads").insert({brokerage_id:r,email:g,source:"calculator"});if(G)throw G;const{error:H}=await V.functions.invoke("send-calculator-breakdown",{body:{brokerage_id:r,brokerage_name:a,email:g,inputs:{gci:parseFloat(l)||0,transactions:parseInt(c,10)||0,current_split_pct:parseFloat(u)||0,current_monthly_fee:parseFloat(m)||0},plan:{commission_split_pct:C,cap_amount:A,post_cap_split_pct:M,monthly_fee:I,transaction_fee:P},result:R,primary_color:t,accent_color:n}});H&&console.error("Breakdown email failed:",H),v(!0),i({title:"Sent!",description:"Check your email for the full breakdown."})}catch(G){i({title:"Error",description:G.message,variant:"destructive"})}finally{j(!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(hj,{children:e.jsxs("div",{className:"text-center mb-10",children:[e.jsxs("div",{className:"inline-flex items-center gap-2 px-4 py-1.5 rounded-full text-xs font-semibold mb-4",style:{backgroundColor:`${t}15`,color:n},children:[e.jsx(fu,{className:"h-3 w-3"})," 100% Confidential — No Signup Required"]}),e.jsx("h2",{className:"text-3xl md:text-4xl font-bold tracking-tight mb-3",style:{color:n},children:s.headline||"See What You Could Earn With Us"}),e.jsx("p",{className:"text-gray-500 text-lg font-light max-w-xl mx-auto",children:s.subtext||"Confidential 60-second calculator — no signup required."})]})}),e.jsx(hj,{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(C5,{className:"h-5 w-5",style:{color:t}}),e.jsx("h3",{className:"font-semibold",style:{color:n},children:"Your Numbers"})]}),e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{children:[e.jsx(re,{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(be,{type:"number",value:l,onChange:U=>o(U.target.value),className:"pl-7 h-11 text-base",placeholder:"250,000"})]})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-gray-600 text-sm",children:"Transactions per Year"}),e.jsx(be,{type:"number",min:"0",value:c,onChange:U=>d(U.target.value),className:"mt-1.5 h-11 text-base",placeholder:"12"})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-gray-600 text-sm",children:"Your Current Commission Split (%)"}),e.jsx(be,{type:"number",value:u,onChange:U=>h(U.target.value),className:"mt-1.5 h-11 text-base",placeholder:"70"})]}),e.jsxs("div",{children:[e.jsx(re,{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(be,{type:"number",value:m,onChange:U=>p(U.target.value),className:"pl-7 h-11 text-base",placeholder:"150"})]})]})]})]}),e.jsxs("div",{className:"p-8 md:p-10 text-white",style:{background:`linear-gradient(160deg, ${n}, ${t})`},children:[e.jsxs("div",{className:"flex items-center gap-2 mb-6",children:[e.jsx(mc,{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:O(R.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:O(R.newNet)})]})]}),e.jsxs(_r.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:R.diff>=0?"You could earn":"Difference"}),e.jsxs("p",{className:"text-4xl font-bold mb-1",children:[R.diff>=0?"+":"",O(R.diff)]}),e.jsx("p",{className:"text-white/70 text-xs",children:R.diff>=0?"more per year":"per year"})]},R.diff),s.show_email_capture&&!y&&e.jsxs("form",{onSubmit:B,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(be,{type:"email",required:!0,value:g,onChange:U=>x(U.target.value),placeholder:"you@email.com",className:"bg-white/95 border-0 text-gray-900 h-10 text-sm"}),e.jsx($,{type:"submit",disabled:_,className:"h-10 bg-white text-gray-900 hover:bg-white/90 text-sm font-semibold",children:"Send"})]})]}),y&&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(ma,{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 aFn({config:s,primaryColor:t,accentColor:n,brokerageId:r}){const{toast:a}=Fi(),[i,l]=k.useState(""),[o,c]=k.useState(""),[d,u]=k.useState(!1),[h,m]=k.useState(!1),p=async g=>{g.preventDefault(),m(!0);try{const{error:x}=await V.from("recruit_lead_magnet_downloads").insert({brokerage_id:r,email:i,first_name:o||null,source:"lead_magnet",user_agent:navigator.userAgent,referrer:document.referrer||null});if(x)throw x;u(!0),s.pdf_url&&window.open(s.pdf_url,"_blank","noopener,noreferrer")}catch(x){a({title:"Error",description:x.message,variant:"destructive"})}finally{m(!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(hj,{children:e.jsx("div",{className:"rounded-3xl p-8 md:p-12 shadow-xl border border-gray-100",style:{background:`linear-gradient(135deg, ${t}08, ${n}08)`},children:e.jsxs("div",{className:"flex flex-col md:flex-row items-center gap-8",children:[e.jsx("div",{className:"shrink-0 h-24 w-24 rounded-2xl flex items-center justify-center shadow-lg",style:{background:`linear-gradient(135deg, ${t}, ${n})`},children:e.jsx(y2,{className:"h-12 w-12 text-white"})}),e.jsxs("div",{className:"flex-1 text-center md:text-left",children:[e.jsxs("div",{className:"inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-[11px] font-semibold mb-3",style:{backgroundColor:`${t}15`,color:n},children:[e.jsx(fu,{className:"h-2.5 w-2.5"})," No call required — instant download"]}),e.jsx("h3",{className:"text-2xl md:text-3xl font-bold tracking-tight mb-2",style:{color:n},children:s.title||"Get the Full Comp Plan PDF"}),e.jsx("p",{className:"text-gray-500 leading-relaxed mb-5",children:s.description||"See exactly how splits, caps, and fees work — no call required."}),d?e.jsxs("div",{className:"flex items-center gap-2 p-4 rounded-xl bg-green-50 border border-green-200 text-green-800 text-sm",children:[e.jsx(ma,{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:p,className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[e.jsx(be,{value:o,onChange:g=>c(g.target.value),placeholder:"First name (optional)",className:"h-11"}),e.jsx(be,{type:"email",required:!0,value:i,onChange:g=>l(g.target.value),placeholder:"your@email.com",className:"h-11"})]}),e.jsxs($,{type:"submit",disabled:h,className:"w-full sm:w-auto h-12 px-6 text-white font-semibold",style:{background:`linear-gradient(135deg, ${t}, ${n})`},children:[e.jsx(y2,{className:"h-4 w-4 mr-2"}),h?"Sending...":s.button_text||"Email Me the PDF"]})]})]})]})})})})})}function iFn(){const{slug:s}=oo(),{toast:t}=Fi(),[n,r]=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 R=()=>{['[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(G=>document.querySelectorAll(G).forEach(H=>H.style.display="none"))};R();const O=[setTimeout(R,500),setTimeout(R,1500),setTimeout(R,3e3)],B=new MutationObserver(R);return B.observe(document.body,{childList:!0,subtree:!0}),()=>{document.body.classList.remove("recruit-landing-page"),O.forEach(clearTimeout),B.disconnect()}},[]);const{data:l,isLoading:o,error:c}=pt({queryKey:["recruit-form-brokerage",s],queryFn:async()=>{const{data:R,error:O}=await V.from("brokerages").select("id, name, recruit_form_enabled").eq("recruit_form_slug",s).single();if(O)throw O;return R},enabled:!!s}),{data:d}=pt({queryKey:["recruit-landing-public",l==null?void 0:l.id],queryFn:async()=>{const{data:R,error:O}=await V.from("recruit_landing_page_settings").select("*").eq("brokerage_id",l.id).single();if(O&&O.code!=="PGRST116")throw O;return R},enabled:!!(l!=null&&l.id)}),u=Nt({mutationFn:async()=>{const R={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:O}=await V.from("recruit_interest_submissions").insert(R);if(O)throw O;V.functions.invoke("recruit-lead-notify",{body:{lead:R,brokerage_id:l.id}}).catch(B=>console.error("Lead notification error:",B))},onSuccess:()=>r(!0),onError:R=>t({title:"Error",description:R.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(Gi,{className:"h-10 w-10 mx-auto text-gray-300 mb-4"}),e.jsx("p",{className:"text-gray-400 text-lg",children:"This page is not available."})]})});const h=d,m=(h==null?void 0:h.primary_color)||"#406E71",p=(h==null?void 0:h.accent_color)||"#2a4c64",g=(h==null?void 0:h.benefits)||[],x=(h==null?void 0:h.testimonials)||[],y=(h==null?void 0:h.gallery_images)||[],v=(h==null?void 0:h.hero_headline)||`Join ${l.name}`,_=(h==null?void 0:h.hero_subtext)||"Take your real estate career to the next level with a brokerage that invests in your growth.",j=(h==null?void 0:h.calculator_enabled)===!0,C=(h==null?void 0:h.calculator_config)||{},A=(h==null?void 0:h.lead_magnet_enabled)===!0,M=(h==null?void 0:h.lead_magnet_config)||{},I=(h==null?void 0:h.form_style)||"classic",P=(h==null?void 0:h.confidential_messaging)!==!1;return n?e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-white",children:e.jsxs(_r.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, ${m}, ${p})`},children:e.jsx(ma,{className:"h-10 w-10 text-white"})}),e.jsx("h2",{className:"text-3xl font-bold mb-3 tracking-tight",style:{color:p},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:p},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:m}})]})}):e.jsxs("div",{className:"min-h-screen bg-white",style:{"--recruit-primary":m,"--recruit-accent":p},children:[e.jsx("nav",{className:"fixed top-0 left-0 right-0 z-40 bg-white/80 backdrop-blur-lg border-b border-gray-100/50",children:e.jsxs("div",{className:"max-w-6xl mx-auto px-6 h-14 flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[(h==null?void 0:h.logo_url)&&e.jsx("img",{src:h.logo_url,alt:l.name,className:"h-8 w-auto"}),e.jsx("span",{className:"font-semibold text-sm tracking-tight",style:{color:p},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, ${m}, ${p})`},children:["Apply Now ",e.jsx(xi,{className:"h-3.5 w-3.5"})]})]})}),e.jsx(QOn,{headline:v,subtext:_,primaryColor:m,accentColor:p,heroImageUrl:h==null?void 0:h.hero_image_url,logoUrl:h==null?void 0:h.logo_url,brokerageName:l.name}),e.jsx(JOn,{benefits:g,accentColor:p,primaryColor:m}),e.jsx(eFn,{images:y,primaryColor:m,accentColor:p}),e.jsx(tFn,{testimonials:x,primaryColor:m,accentColor:p}),j&&e.jsx(rFn,{config:C,primaryColor:m,accentColor:p,brokerageId:l.id,brokerageName:l.name}),A&&e.jsx(aFn,{config:M,primaryColor:m,accentColor:p,brokerageId:l.id}),I==="multi_step"?e.jsx(nFn,{form:a,setForm:i,onSubmit:()=>u.mutate(),isPending:u.isPending,primaryColor:m,accentColor:p,showConfidentialBadges:P}):e.jsx(sFn,{form:a,setForm:i,onSubmit:()=>u.mutate(),isPending:u.isPending,primaryColor:m,accentColor:p}),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 oFn(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 lFn(){var m,p,g,x;const{shareToken:s}=oo(),t=k.useRef(!1),{data:n,isLoading:r,error:a}=pt({queryKey:["public-recruit-video",s],queryFn:async()=>{var A;if(!s)throw new Error("No token");const{data:y,error:v}=await V.from("recruit_videos").select(` *, prospect:recruit_prospects(first_name, last_name), video:agent_videos(id, title, playback_url, thumbnail_url, duration_seconds, owner_user_id) `).eq("share_token",s).single();if(v)throw v;const{data:_}=await V.from("profiles").select("name, avatar_url, title, recruit_cta_url").eq("id",(A=y.video)==null?void 0:A.owner_user_id).single(),{data:j}=await V.from("brokerages").select("name").eq("id",y.brokerage_id).single(),{data:C}=await V.from("recruit_landing_page_settings").select("logo_url, primary_color, accent_color, hero_headline").eq("brokerage_id",y.brokerage_id).maybeSingle();return{rv:y,profile:_,brokerage:j,settings:C}},enabled:!!s});if(k.useEffect(()=>{var y;!((y=n==null?void 0:n.rv)!=null&&y.id)||t.current||(t.current=!0,V.rpc("log_recruit_video_view",{p_recruit_video_id:n.rv.id,p_user_agent:navigator.userAgent,p_referrer:document.referrer||null}).then(()=>{}))},[(m=n==null?void 0:n.rv)==null?void 0:m.id]),r)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})});if(a||!n)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background",children:e.jsx("p",{className:"text-muted-foreground",children:"This video is no longer available."})});const{rv:i,profile:l,brokerage:o,settings:c}=n,d=(c==null?void 0:c.primary_color)||"#3b82f6",u=((p=i.prospect)==null?void 0:p.first_name)||"there",h=(g=i.video)!=null&&g.playback_url?oFn(i.video.playback_url):null;return e.jsxs(e.Fragment,{children:[e.jsx(Sc,{children:e.jsx("title",{children:o!=null&&o.name?`${o.name} — A Message For You`:"Personal Video Message"})}),e.jsxs("div",{className:"min-h-screen bg-gradient-to-br from-slate-50 to-slate-100",children:[e.jsx("header",{className:"border-b bg-white/80 backdrop-blur-sm",children:e.jsxs("div",{className:"max-w-3xl mx-auto px-4 py-4 flex items-center gap-3",children:[(c==null?void 0:c.logo_url)&&e.jsx("img",{src:c.logo_url,alt:"",className:"h-8 object-contain"}),e.jsx("span",{className:"font-semibold text-sm",style:{color:d},children:(o==null?void 0:o.name)||"Recruiting"})]})}),e.jsxs("main",{className:"max-w-3xl mx-auto px-4 py-8 space-y-6",children:[e.jsxs("div",{className:"text-center space-y-2",children:[e.jsxs("h1",{className:"text-2xl font-bold text-foreground",children:["Hey ",u,", ",l==null?void 0:l.name," has a message for you"]}),i.message&&e.jsx("p",{className:"text-muted-foreground max-w-xl mx-auto",children:i.message})]}),h&&e.jsx("div",{className:"rounded-xl overflow-hidden shadow-xl bg-black",children:e.jsx("div",{style:{position:"relative",paddingTop:"56.25%"},children:e.jsx("iframe",{src:h,loading:"lazy",style:{border:0,position:"absolute",top:0,left:0,width:"100%",height:"100%"},allow:"accelerometer; gyroscope; autoplay; encrypted-media; picture-in-picture",allowFullScreen:!0})})}),e.jsxs("div",{className:"bg-white rounded-xl shadow-sm border p-6 flex items-center gap-4",children:[l!=null&&l.avatar_url?e.jsx("img",{src:l.avatar_url,alt:"",className:"h-14 w-14 rounded-full object-cover"}):e.jsx("div",{className:"h-14 w-14 rounded-full flex items-center justify-center text-white text-lg font-bold",style:{backgroundColor:d},children:((x=l==null?void 0:l.name)==null?void 0:x.charAt(0))||"?"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"font-semibold",children:l==null?void 0:l.name}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[(l==null?void 0:l.title)||"Recruiter"," · ",o==null?void 0:o.name]})]})]}),(l==null?void 0:l.recruit_cta_url)&&e.jsx("div",{className:"text-center",children:e.jsx($,{size:"lg",asChild:!0,className:"text-white shadow-lg hover:shadow-xl transition-shadow px-8",style:{backgroundColor:d},onClick:()=>{V.from("recruit_videos").update({cta_clicked_at:new Date().toISOString()}).eq("id",i.id).then(()=>{})},children:e.jsxs("a",{href:l.recruit_cta_url,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(ha,{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 cFn="relzejiswnotikjgvjhz",kbt=`https://${cFn}.supabase.co/functions/v1/recruit-unsubscribe`;function dFn(){const[s]=Jc(),t=s.get("token")||"",[n,r]=k.useState(!0),[a,i]=k.useState(!1),[l,o]=k.useState(!1),[c,d]=k.useState(""),[u,h]=k.useState({});k.useEffect(()=>{document.body.classList.add("recruit-unsubscribe-page");const p=()=>{['[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(v=>document.querySelectorAll(v).forEach(_=>_.style.display="none"))};p();const g=[setTimeout(p,500),setTimeout(p,1500),setTimeout(p,3e3)],x=new MutationObserver(p);return x.observe(document.body,{childList:!0,subtree:!0}),()=>{document.body.classList.remove("recruit-unsubscribe-page"),g.forEach(clearTimeout),x.disconnect()}},[]),k.useEffect(()=>{if(!t){h({error:"Missing unsubscribe token in link."}),r(!1);return}fetch(`${kbt}?token=${encodeURIComponent(t)}`).then(async p=>{const g=await p.json();if(!p.ok)throw new Error(g.error||"Lookup failed");h(g),g.already_unsubscribed&&o(!0)}).catch(p=>h({error:p.message||"Could not load status"})).finally(()=>r(!1))},[t]);const m=async()=>{i(!0);try{const p=await fetch(kbt,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t,reason:c.trim()||null})}),g=await p.json();if(!p.ok)throw new Error(g.error||"Failed");o(!0)}catch(p){h({...u,error:p.message||"Could not unsubscribe"})}finally{i(!1)}};return e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-slate-50 via-white to-slate-100 flex items-center justify-center p-6",children:e.jsx("div",{className:"w-full max-w-lg bg-white rounded-2xl shadow-xl border border-slate-200 p-8 sm:p-10",children:n?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 gap-3 text-slate-500",children:[e.jsx(Jt,{className:"h-8 w-8 animate-spin"}),e.jsx("p",{className:"text-sm",children:"Loading…"})]}):u.error?e.jsxs("div",{className:"text-center space-y-3",children:[e.jsx("div",{className:"mx-auto w-14 h-14 rounded-full bg-red-50 flex items-center justify-center",children:e.jsx(Ho,{className:"h-7 w-7 text-red-500"})}),e.jsx("h1",{className:"text-xl font-semibold text-slate-800",children:"Link Invalid"}),e.jsx("p",{className:"text-sm text-slate-500",children:u.error}),e.jsx("p",{className:"text-xs text-slate-400 pt-2",children:"If you continue to receive emails you don't want, please reply directly to one of them and we'll remove you immediately."})]}):l?e.jsxs("div",{className:"text-center space-y-4",children:[e.jsx("div",{className:"mx-auto w-14 h-14 rounded-full bg-emerald-50 flex items-center justify-center",children:e.jsx(Gr,{className:"h-7 w-7 text-emerald-500"})}),e.jsxs("h1",{className:"text-xl font-semibold text-slate-800",children:["You're unsubscribed",u.first_name?`, ${u.first_name}`:""]}),e.jsxs("p",{className:"text-sm text-slate-500",children:["You won't receive any more recruiting emails from ",u.brokerage_name||"this brokerage",". Your conversation remains 100% confidential."]}),e.jsxs("div",{className:"flex items-center justify-center gap-2 text-xs text-slate-400 pt-2",children:[e.jsx(b0,{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(b0,{className:"h-7 w-7 text-slate-500"})}),e.jsxs("h1",{className:"text-xl font-semibold text-slate-800",children:["Unsubscribe",u.first_name?`, ${u.first_name}`:"","?"]}),e.jsxs("p",{className:"text-sm text-slate-500",children:["You'll be removed from ",u.brokerage_name||"this brokerage","'s recruiting emails immediately. Everything stays confidential."]}),u.email&&e.jsx("p",{className:"text-xs text-slate-400",children:u.email})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"reason",className:"text-xs text-slate-500",children:"Optional — what's the main reason? (helps us improve)"}),e.jsx(Ls,{id:"reason",value:c,onChange:p=>d(p.target.value),placeholder:"e.g. Not currently looking, too many emails, already moved…",rows:3,className:"resize-none"})]}),e.jsx($,{onClick:m,disabled:a,className:"w-full h-11",variant:"default",children:a?e.jsxs(e.Fragment,{children:[e.jsx(Jt,{className:"h-4 w-4 mr-2 animate-spin"}),"Unsubscribing…"]}):"Confirm Unsubscribe"}),e.jsx("p",{className:"text-[11px] text-slate-400 text-center",children:"No login required. We process your request instantly."})]})})})}const uFn="relzejiswnotikjgvjhz",Sbt=`https://${uFn}.supabase.co/functions/v1/event-invite-unsubscribe`;function hFn(){const[s]=Jc(),t=s.get("token")||"",[n,r]=k.useState(!0),[a,i]=k.useState(!1),[l,o]=k.useState(!1),[c,d]=k.useState({});k.useEffect(()=>(document.body.classList.add("event-invite-unsubscribe-page"),()=>{document.body.classList.remove("event-invite-unsubscribe-page")}),[]),k.useEffect(()=>{if(!t){d({error:"Missing unsubscribe token in link."}),r(!1);return}fetch(`${Sbt}?token=${encodeURIComponent(t)}`).then(async h=>{const m=await h.json();if(!h.ok)throw new Error(m.error||"Lookup failed");d(m),m.already_unsubscribed&&o(!0)}).catch(h=>d({error:h.message||"Could not load status"})).finally(()=>r(!1))},[t]);const u=async()=>{i(!0);try{const h=await fetch(Sbt,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t})}),m=await h.json();if(!h.ok)throw new Error(m.error||"Failed");o(!0)}catch(h){d({...c,error:h.message||"Could not unsubscribe"})}finally{i(!1)}};return e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-slate-50 via-white to-slate-100 flex items-center justify-center p-6",children:e.jsx("div",{className:"w-full max-w-lg bg-white rounded-2xl shadow-xl border border-slate-200 p-8 sm:p-10",children:n?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 gap-3 text-slate-500",children:[e.jsx(Jt,{className:"h-8 w-8 animate-spin"}),e.jsx("p",{className:"text-sm",children:"Loading…"})]}):c.error?e.jsxs("div",{className:"text-center space-y-3",children:[e.jsx("div",{className:"mx-auto w-14 h-14 rounded-full bg-red-50 flex items-center justify-center",children:e.jsx(Ho,{className:"h-7 w-7 text-red-500"})}),e.jsx("h1",{className:"text-xl font-semibold text-slate-800",children:"Link Invalid"}),e.jsx("p",{className:"text-sm text-slate-500",children:c.error})]}):l?e.jsxs("div",{className:"text-center space-y-4",children:[e.jsx("div",{className:"mx-auto w-14 h-14 rounded-full bg-emerald-50 flex items-center justify-center",children:e.jsx(Gr,{className:"h-7 w-7 text-emerald-500"})}),e.jsxs("h1",{className:"text-xl font-semibold text-slate-800",children:["You're unsubscribed",c.first_name?`, ${c.first_name}`:""]}),e.jsx("p",{className:"text-sm text-slate-500",children:"You won't receive event invite emails from LevelUp anymore."}),e.jsxs("div",{className:"mt-4 rounded-xl bg-slate-50 border border-slate-200 p-4 text-left",children:[e.jsx("p",{className:"text-sm font-medium text-slate-800 mb-1",children:"You'll still get:"}),e.jsxs("ul",{className:"text-sm text-slate-600 space-y-1 list-disc list-inside",children:[e.jsx("li",{children:"The Monday weekly digest"}),e.jsx("li",{children:"Account & billing notifications"}),e.jsx("li",{children:"Anything you directly requested"})]})]}),e.jsxs("div",{className:"flex items-center justify-center gap-2 text-xs text-slate-400 pt-2",children:[e.jsx(b0,{className:"h-3.5 w-3.5"}),"Preference saved · You can turn this back on anytime in your Profile."]})]}):e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"text-center space-y-2",children:[e.jsx("div",{className:"mx-auto w-14 h-14 rounded-full bg-slate-100 flex items-center justify-center",children:e.jsx(NK,{className:"h-7 w-7 text-slate-500"})}),e.jsxs("h1",{className:"text-xl font-semibold text-slate-800",children:["Unsubscribe from event invites",c.first_name?`, ${c.first_name}`:"","?"]}),e.jsxs("p",{className:"text-sm text-slate-500",children:["You'll stop receiving event invite emails from LevelUp. Your ",e.jsx("span",{className:"font-medium text-slate-700",children:"Monday weekly digest"})," will keep coming."]}),c.email&&e.jsx("p",{className:"text-xs text-slate-400",children:c.email})]}),e.jsx($,{onClick:u,disabled:a,className:"w-full h-11",variant:"default",children:a?e.jsxs(e.Fragment,{children:[e.jsx(Jt,{className:"h-4 w-4 mr-2 animate-spin"}),"Unsubscribing…"]}):"Unsubscribe from event invites only"}),e.jsx("p",{className:"text-[11px] text-slate-400 text-center",children:"No login required. You can re-enable event invites anytime in your Profile."})]})})})}function mFn(){const s=Jn(),t=ls(),{isAdmin:n}=ks(),[r,a]=k.useState(!1),[i,l]=k.useState(null),[o,c]=k.useState(null),{data:d,isLoading:u}=pt({queryKey:["my-social-accounts"],queryFn:async()=>{const{data:{user:C},error:A}=await V.auth.getUser();if(A)throw A;if(!C)return[];const{data:M,error:I}=await V.from("social_accounts").select("*").eq("user_id",C.id).order("created_at",{ascending:!1});if(I)throw I;return M}}),h=Nt({mutationFn:async C=>{const{data:{user:A},error:M}=await V.auth.getUser();if(M)throw M;if(!A)throw new Error("Not authenticated");const{error:I}=await V.from("social_accounts").delete().eq("id",C).eq("user_id",A.id);if(I)throw I},onSuccess:()=>{t.invalidateQueries({queryKey:["my-social-accounts"]}),t.invalidateQueries({queryKey:["social-accounts-for-post"]}),ae.success("Account disconnected successfully")},onError:()=>{ae.error("Failed to disconnect account")}}),m=async()=>{a(!0);try{const{data:C,error:A}=await V.functions.invoke("linkedin-oauth",{body:{action:"get_auth_url",callbackPath:"/social-connections/linkedin-callback"}});if(A)throw A;if(C!=null&&C.authUrl)window.location.href=C.authUrl;else throw new Error("Failed to get LinkedIn authorization URL")}catch(C){console.error("LinkedIn OAuth error:",C),ae.error("Failed to start LinkedIn connection. Please try again."),a(!1)}},p=async()=>{a(!0);try{const{data:C,error:A}=await V.functions.invoke("google-business-oauth",{body:{action:"get_auth_url"}});if(A)throw A;if(C!=null&&C.authUrl)window.location.href=C.authUrl;else throw new Error("Failed to get Google authorization URL")}catch(C){console.error("Google OAuth error:",C),ae.error("Failed to start Google connection. Please try again."),a(!1)}},g=(d==null?void 0:d.filter(C=>C.platform==="facebook"))||[],x=(d==null?void 0:d.filter(C=>C.platform==="instagram"))||[],y=(d==null?void 0:d.filter(C=>C.platform==="linkedin"))||[],v=(d==null?void 0:d.filter(C=>C.platform==="google_business"))||[],_=((d==null?void 0:d.length)||0)>0,j=async(C,A)=>{l(C),c(null);try{const{data:M,error:I}=await V.functions.invoke("meta-api-test",{body:{testType:"all",accountId:C}});if(I)throw I;c(M.results||[]),ae.success(M.summary||"API tests completed")}catch(M){console.error("Meta API test error:",M),ae.error("Failed to run API tests")}finally{l(null)}};return e.jsx(Xs,{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(qe,{variant:"secondary",className:"bg-white/20 text-white border-0 backdrop-blur-sm",children:[e.jsx(kn,{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($,{variant:"ghost",onClick:()=>s("/social-swag-2"),className:"gap-2",children:[e.jsx(Ia,{className:"h-4 w-4"}),"Back to Social Swag"]}),_&&e.jsx(we,{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(nl,{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(we,{children:[e.jsx(Vt,{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(ax,{className:"h-6 w-6 text-blue-600"})}),e.jsxs("div",{children:[e.jsxs(Yt,{className:"text-lg flex items-center gap-2",children:["Facebook",e.jsx(qe,{variant:"outline",className:"text-amber-600 border-amber-200 bg-amber-50",children:"Coming Soon"})]}),e.jsx(vr,{children:"Facebook integration is coming soon — stay tuned!"})]})]})}),e.jsxs(De,{className:"space-y-4",children:[u?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(yo,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):g.length>0?e.jsx("div",{className:"space-y-3",children:g.map(C=>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(Wa,{className:"h-10 w-10",children:[e.jsx(eo,{src:C.profile_picture_url||""}),e.jsx(Ka,{children:e.jsx(ax,{className:"h-5 w-5"})})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:C.page_name||C.platform_username||"Facebook Page"}),e.jsx(qe,{variant:C.is_active?"default":"secondary",className:"text-xs",children:C.is_active?"Connected":"Inactive"})]})]}),e.jsxs(oc,{children:[e.jsx(_g,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(Un,{className:"h-4 w-4"})})}),e.jsxs(Ql,{children:[e.jsxs(Jl,{children:[e.jsx(tc,{children:"Disconnect Facebook?"}),e.jsx(sc,{children:"This will remove the connection. You'll need to reconnect to post content."})]}),e.jsxs(ec,{children:[e.jsx(nc,{children:"Cancel"}),e.jsx(Vl,{onClick:()=>h.mutate(C.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]},C.id))}):e.jsx("p",{className:"text-sm text-muted-foreground py-4 text-center",children:"No Facebook pages connected yet"}),e.jsxs($,{disabled:!0,className:"w-full gap-2",variant:"outline",children:[e.jsx(sa,{className:"h-4 w-4"}),"Coming Soon"]})]})]}),e.jsxs(we,{children:[e.jsx(Vt,{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(Sf,{className:"h-6 w-6 text-pink-600"})}),e.jsxs("div",{children:[e.jsxs(Yt,{className:"text-lg flex items-center gap-2",children:["Instagram",e.jsx(qe,{variant:"outline",className:"text-amber-600 border-amber-200 bg-amber-50",children:"Coming Soon"})]}),e.jsx(vr,{children:"Instagram integration is coming soon — stay tuned!"})]})]})}),e.jsxs(De,{className:"space-y-4",children:[u?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(yo,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):x.length>0?e.jsx("div",{className:"space-y-3",children:x.map(C=>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(Wa,{className:"h-10 w-10",children:[e.jsx(eo,{src:C.profile_picture_url||""}),e.jsx(Ka,{children:e.jsx(Sf,{className:"h-5 w-5"})})]}),e.jsxs("div",{children:[e.jsxs("p",{className:"font-medium",children:["@",C.platform_username||"Instagram Account"]}),e.jsx(qe,{variant:C.is_active?"default":"secondary",className:"text-xs",children:C.is_active?"Connected":"Inactive"})]})]}),e.jsxs(oc,{children:[e.jsx(_g,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(Un,{className:"h-4 w-4"})})}),e.jsxs(Ql,{children:[e.jsxs(Jl,{children:[e.jsx(tc,{children:"Disconnect Instagram?"}),e.jsx(sc,{children:"This will remove the connection. You'll need to reconnect to post content."})]}),e.jsxs(ec,{children:[e.jsx(nc,{children:"Cancel"}),e.jsx(Vl,{onClick:()=>h.mutate(C.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]},C.id))}):e.jsx("p",{className:"text-sm text-muted-foreground py-4 text-center",children:"No Instagram accounts connected yet"}),e.jsxs($,{disabled:!0,className:"w-full gap-2",variant:"outline",children:[e.jsx(sa,{className:"h-4 w-4"}),"Coming Soon"]}),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(we,{children:[e.jsx(Vt,{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(dv,{className:"h-6 w-6 text-blue-700"})}),e.jsxs("div",{children:[e.jsx(Yt,{className:"text-lg",children:"LinkedIn"}),e.jsx(vr,{children:"Connect your LinkedIn profile"})]})]})}),e.jsxs(De,{className:"space-y-4",children:[u?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(yo,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):y.length>0?e.jsx("div",{className:"space-y-3",children:y.map(C=>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(Wa,{className:"h-10 w-10",children:[e.jsx(eo,{src:C.profile_picture_url||""}),e.jsx(Ka,{children:e.jsx(dv,{className:"h-5 w-5"})})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:C.platform_username||"LinkedIn Account"}),e.jsx(qe,{variant:C.is_active?"default":"secondary",className:"text-xs",children:C.is_active?"Connected":"Inactive"})]})]}),e.jsxs(oc,{children:[e.jsx(_g,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(Un,{className:"h-4 w-4"})})}),e.jsxs(Ql,{children:[e.jsxs(Jl,{children:[e.jsx(tc,{children:"Disconnect LinkedIn?"}),e.jsx(sc,{children:"This will remove the connection. You'll need to reconnect to post content."})]}),e.jsxs(ec,{children:[e.jsx(nc,{children:"Cancel"}),e.jsx(Vl,{onClick:()=>h.mutate(C.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]},C.id))}):e.jsx("p",{className:"text-sm text-muted-foreground py-4 text-center",children:"No LinkedIn account connected yet"}),e.jsxs($,{onClick:m,disabled:r,className:"w-full gap-2",variant:y.length>0?"outline":"default",children:[r?e.jsx(yo,{className:"h-4 w-4 animate-spin"}):e.jsx(nn,{className:"h-4 w-4"}),y.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(we,{className:`relative overflow-hidden ${n?"":"opacity-75"}`,children:[!n&&e.jsx("div",{className:"absolute top-3 right-3 z-10",children:e.jsx(qe,{variant:"secondary",className:"bg-amber-100 text-amber-800 dark:bg-amber-900/30 dark:text-amber-400",children:"Coming Soon"})}),n&&e.jsx("div",{className:"absolute top-3 right-3 z-10",children:e.jsx(qe,{variant:"secondary",className:"bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400",children:"Admin Testing"})}),e.jsx(Vt,{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(Si,{className:"h-6 w-6 text-red-600"})}),e.jsxs("div",{children:[e.jsx(Yt,{className:"text-lg",children:"Google Business"}),e.jsx(vr,{children:"Connect your Google Business Profile"})]})]})}),e.jsxs(De,{className:"space-y-4",children:[u?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(yo,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):v.length>0?e.jsx("div",{className:"space-y-3",children:v.map(C=>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(Wa,{className:"h-10 w-10",children:[e.jsx(eo,{src:C.profile_picture_url||""}),e.jsx(Ka,{children:e.jsx(Si,{className:"h-5 w-5"})})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:C.page_name||C.platform_username||"Google Business"}),e.jsx(qe,{variant:C.is_active?"default":"secondary",className:"text-xs",children:C.is_active?"Connected":"Inactive"})]})]}),e.jsxs(oc,{children:[e.jsx(_g,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(Un,{className:"h-4 w-4"})})}),e.jsxs(Ql,{children:[e.jsxs(Jl,{children:[e.jsx(tc,{children:"Disconnect Google Business?"}),e.jsx(sc,{children:"This will remove the connection. You'll need to reconnect to post content."})]}),e.jsxs(ec,{children:[e.jsx(nc,{children:"Cancel"}),e.jsx(Vl,{onClick:()=>h.mutate(C.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]},C.id))}):e.jsx("p",{className:"text-sm text-muted-foreground py-4 text-center",children:n?"No Google Business account connected yet":"Google Business Profile integration is coming soon!"}),e.jsxs($,{onClick:n?p:void 0,disabled:!n||r,className:"w-full gap-2",variant:v.length>0?"outline":"default",children:[r?e.jsx(yo,{className:"h-4 w-4 animate-spin"}):e.jsx(nn,{className:"h-4 w-4"}),v.length>0?"Reconnect Google Business":"Connect Google Business"]}),e.jsx("p",{className:"text-xs text-muted-foreground text-center",children:"Post updates directly to your Google Business Profile"})]})]})]}),n&&(g.length>0||x.length>0)&&e.jsxs(we,{className:"border-amber-200 bg-amber-50 dark:bg-amber-950/20 dark:border-amber-900",children:[e.jsx(Vt,{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(qT,{className:"h-6 w-6 text-amber-600"})}),e.jsxs("div",{children:[e.jsx(Yt,{className:"text-lg",children:"Meta API Testing (Admin Only)"}),e.jsx(vr,{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:[g.map(C=>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(ax,{className:"h-5 w-5 text-blue-600"}),e.jsx("span",{className:"font-medium",children:C.page_name||"Facebook Page"})]}),e.jsx($,{size:"sm",variant:"outline",onClick:()=>j(C.id),disabled:i===C.id,children:i===C.id?e.jsxs(e.Fragment,{children:[e.jsx(Jt,{className:"h-4 w-4 mr-2 animate-spin"}),"Testing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(qT,{className:"h-4 w-4 mr-2"}),"Run Tests"]})})]},`test-fb-${C.id}`)),x.map(C=>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(Sf,{className:"h-5 w-5 text-pink-600"}),e.jsxs("span",{className:"font-medium",children:["@",C.platform_username||"Instagram"]})]}),e.jsx($,{size:"sm",variant:"outline",onClick:()=>j(C.id),disabled:i===C.id,children:i===C.id?e.jsxs(e.Fragment,{children:[e.jsx(Jt,{className:"h-4 w-4 mr-2 animate-spin"}),"Testing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(qT,{className:"h-4 w-4 mr-2"}),"Run Tests"]})})]},`test-ig-${C.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((C,A)=>e.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[C.status==="success"?e.jsx(Gr,{className:"h-4 w-4 text-green-600 mt-0.5 shrink-0"}):C.status==="pending"?e.jsx(Jt,{className:"h-4 w-4 text-amber-600 mt-0.5 shrink-0"}):e.jsx(ju,{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:C.test}),e.jsx("span",{className:"ml-2 text-muted-foreground",children:C.details})]})]},A))})]}),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(we,{children:[e.jsx(Vt,{children:e.jsx(Yt,{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 fFn(){const[s]=Jc(),t=Jn(),[n,r]=k.useState("loading"),a=k.useRef(!1),[i,l]=k.useState("Processing your connection..."),o=(()=>{const c=sessionStorage.getItem("social-connect-return-to");return c&&c.startsWith("/")&&!c.startsWith("/admin")?c:"/social-connections"})();return k.useEffect(()=>{if(a.current)return;a.current=!0,(async()=>{var p;const d=s.get("code"),u=s.get("error"),h=s.get("error_description"),m=s.get("state");if(u){r("error"),l(h||"Authorization was denied"),ae.error("Connection failed: "+(h||u));return}if(!d){r("error"),l("No authorization code received"),ae.error("No authorization code received");return}try{const{data:g,error:x}=await V.functions.invoke("meta-oauth",{body:{action:"exchange_code",code:d,state:m,callbackPath:"/social-connections/callback"}});if(x)throw x;if(g!=null&&g.success)r("success"),l(`Successfully connected ${((p=g.accounts)==null?void 0:p.length)||0} account(s)!`),ae.success("Social accounts connected successfully!");else throw new Error((g==null?void 0:g.error)||"Unknown error")}catch(g){console.error("OAuth callback error:",g),r("error"),l(g instanceof Error?g.message:"Failed to connect accounts"),ae.error("Failed to connect: "+(g instanceof Error?g.message:"Unknown error"))}})()},[s]),e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background p-4",children:e.jsxs(we,{className:"w-full max-w-md",children:[e.jsxs(Vt,{className:"text-center",children:[n==="loading"&&e.jsx(Jt,{className:"h-12 w-12 animate-spin mx-auto text-primary"}),n==="success"&&e.jsx(nl,{className:"h-12 w-12 mx-auto text-green-500"}),n==="error"&&e.jsx(ju,{className:"h-12 w-12 mx-auto text-destructive"}),e.jsxs(Yt,{className:"mt-4",children:[n==="loading"&&"Connecting...",n==="success"&&"Connected!",n==="error"&&"Connection Failed"]}),e.jsx(vr,{children:i})]}),e.jsx(De,{className:"flex justify-center",children:n!=="loading"&&e.jsx($,{onClick:()=>t(o),children:n==="success"?"View Connected Accounts":"Try Again"})})]})})}function pFn(){const[s]=Jc(),t=Jn(),[n,r]=k.useState("loading"),[a,i]=k.useState("Connecting your Google Business Profile...");return k.useEffect(()=>{(async()=>{const o=s.get("code"),c=s.get("error"),d=s.get("error_description"),u=s.get("state");if(c){r("error"),i(d||"Authorization was denied"),ae.error("Connection failed: "+(d||c));return}if(!o){r("error"),i("No authorization code received"),ae.error("No authorization code received");return}try{const{data:h,error:m}=await V.functions.invoke("google-business-oauth",{body:{action:"exchange_code",code:o,state:u}});if(m)throw m;if(h!=null&&h.success)r("success"),i(h.message||"Successfully connected Google Business Profile!"),ae.success("Google Business Profile connected!");else throw new Error((h==null?void 0:h.error)||"Unknown error")}catch(h){console.error("Google OAuth callback error:",h),r("error"),i(h instanceof Error?h.message:"Failed to connect Google Business Profile"),ae.error("Failed to connect: "+(h instanceof Error?h.message:"Unknown error"))}})()},[s]),e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background p-4",children:e.jsxs(we,{className:"w-full max-w-md",children:[e.jsxs(Vt,{className:"text-center",children:[n==="loading"&&e.jsx(Jt,{className:"h-12 w-12 animate-spin mx-auto text-primary"}),n==="success"&&e.jsx(nl,{className:"h-12 w-12 mx-auto text-green-500"}),n==="error"&&e.jsx(ju,{className:"h-12 w-12 mx-auto text-destructive"}),e.jsxs(Yt,{className:"mt-4",children:[n==="loading"&&"Connecting...",n==="success"&&"Connected!",n==="error"&&"Connection Failed"]}),e.jsx(vr,{children:a})]}),e.jsx(De,{className:"flex justify-center",children:n!=="loading"&&e.jsx($,{onClick:()=>t("/social-connections"),children:n==="success"?"View Connected Accounts":"Try Again"})})]})})}function gFn(){const[s]=Jc(),t=Jn(),[n,r]=k.useState("loading"),[a,i]=k.useState("Connecting your LinkedIn account...");return k.useEffect(()=>{(async()=>{var h;const o=s.get("code"),c=s.get("state"),d=s.get("error"),u=s.get("error_description");if(d){console.error("LinkedIn OAuth error:",d,u),r("error"),i(u||"Failed to connect LinkedIn account"),ae.error(u||"Failed to connect LinkedIn");return}if(!o){r("error"),i("No authorization code received"),ae.error("No authorization code received");return}try{const{data:m,error:p}=await V.functions.invoke("linkedin-oauth",{body:{action:"exchange_code",code:o,state:c,callbackPath:"/social-connections/linkedin-callback"}});if(p)throw p;if(m!=null&&m.success)r("success"),i(`Successfully connected ${((h=m.accounts)==null?void 0:h.length)||1} LinkedIn account`),ae.success("LinkedIn connected successfully!");else throw new Error((m==null?void 0:m.error)||"Failed to connect LinkedIn account")}catch(m){console.error("LinkedIn callback error:",m),r("error"),i(m instanceof Error?m.message:"Failed to connect LinkedIn account"),ae.error("Failed to connect LinkedIn")}})()},[s]),e.jsx("div",{className:"min-h-screen flex items-center justify-center p-4 bg-background",children:e.jsxs(we,{className:"w-full max-w-md",children:[e.jsxs(Vt,{className:"text-center",children:[e.jsxs("div",{className:"mx-auto mb-4 rounded-full bg-blue-600/10 p-4 w-fit",children:[n==="loading"&&e.jsx(Jt,{className:"h-8 w-8 animate-spin text-blue-600"}),n==="success"&&e.jsx(nl,{className:"h-8 w-8 text-green-600"}),n==="error"&&e.jsx(ju,{className:"h-8 w-8 text-red-600"})]}),e.jsxs(Yt,{className:"flex items-center justify-center gap-2",children:[e.jsx(dv,{className:"h-5 w-5 text-blue-600"}),n==="loading"&&"Connecting...",n==="success"&&"Connected!",n==="error"&&"Connection Failed"]}),e.jsx(vr,{children:a})]}),e.jsx(De,{className:"flex justify-center",children:e.jsx($,{onClick:()=>t("/mission-control/integrations"),disabled:n==="loading",children:n==="success"?"View Integrations":"Back to Integrations"})})]})})}function xFn(){const s=Jn(),[t,n]=k.useState(null),{data:r,isLoading:a}=vVt(t||void 0,!0),{data:i,isLoading:l}=yQe(!0),{cartItems:o}=eAe(),c=o.reduce((u,h)=>u+h.quantity,0),d=u=>{s(`/marketplace/${u.id}`)};return a||l?e.jsx(Xs,{title:"Marketplace",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx("div",{className:"flex gap-2 overflow-x-auto pb-2",children:[1,2,3].map(u=>e.jsx(fn,{className:"h-10 w-24 flex-shrink-0"},u))}),e.jsx("div",{className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4",children:[1,2,3,4].map(u=>e.jsx(fn,{className:"h-72 w-full"},u))})]})}):e.jsx(Xs,{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($,{variant:"outline",onClick:()=>s("/marketplace/cart"),className:"relative",children:[e.jsx(ok,{className:"h-4 w-4 mr-2"}),"Cart",c>0&&e.jsx(qe,{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($,{variant:t===null?"default":"outline",size:"sm",onClick:()=>n(null),children:"All"}),i.map(u=>e.jsx($,{variant:t===u.id?"default":"outline",size:"sm",onClick:()=>n(u.id),children:u.name},u.id))]}),r&&r.length>0?e.jsx("div",{className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4",children:r.map(u=>{var h;return e.jsxs(we,{className:"overflow-hidden cursor-pointer hover:shadow-lg transition-shadow",onClick:()=>d(u),children:[e.jsxs("div",{className:"aspect-square bg-muted relative",children:[u.images&&u.images.length>0?e.jsx("img",{src:((h=u.images.find(m=>m.is_primary))==null?void 0:h.image_url)||u.images[0].image_url,alt:u.name,className:"w-full h-full object-cover"}):e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsx(bh,{className:"h-12 w-12 text-muted-foreground"})}),u.category&&e.jsx(qe,{className:"absolute top-2 left-2",variant:"secondary",children:u.category.name})]}),e.jsxs(De,{className:"p-4",children:[e.jsx("h3",{className:"font-semibold mb-1 line-clamp-1",children:u.name}),u.description&&e.jsx("p",{className:"text-sm text-muted-foreground mb-2 line-clamp-2",children:u.description}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"font-bold text-lg",children:["$",Number(u.base_price).toFixed(2)]}),u.variants&&u.variants.length>0&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:[u.variants.length," options"]})]})]})]},u.id)})}):e.jsxs("div",{className:"text-center py-12",children:[e.jsx(bh,{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 WVt=k.forwardRef(({...s},t)=>e.jsx("nav",{ref:t,"aria-label":"breadcrumb",...s}));WVt.displayName="Breadcrumb";const KVt=k.forwardRef(({className:s,...t},n)=>e.jsx("ol",{ref:n,className:Ot("flex flex-wrap items-center gap-1.5 break-words text-sm text-muted-foreground sm:gap-2.5",s),...t}));KVt.displayName="BreadcrumbList";const hke=k.forwardRef(({className:s,...t},n)=>e.jsx("li",{ref:n,className:Ot("inline-flex items-center gap-1.5",s),...t}));hke.displayName="BreadcrumbItem";const tqe=k.forwardRef(({asChild:s,className:t,...n},r)=>{const a=s?BVe:"a";return e.jsx(a,{ref:r,className:Ot("transition-colors hover:text-foreground",t),...n})});tqe.displayName="BreadcrumbLink";const YVt=k.forwardRef(({className:s,...t},n)=>e.jsx("span",{ref:n,role:"link","aria-disabled":"true","aria-current":"page",className:Ot("font-normal text-foreground",s),...t}));YVt.displayName="BreadcrumbPage";const sqe=({children:s,className:t,...n})=>e.jsx("li",{role:"presentation","aria-hidden":"true",className:Ot("[&>svg]:size-3.5",t),...n,children:s??e.jsx(fi,{})});sqe.displayName="BreadcrumbSeparator";function yFn(){var G,H;const{productId:s}=oo(),t=Jn(),{data:n,isLoading:r}=a8n(s||""),{addToCart:a,cartItems:i}=eAe(),[l,o]=k.useState(null),[c,d]=k.useState(1),[u,h]=k.useState(0),[m,p]=k.useState(null),[g,x]=k.useState(!1),[y,v]=k.useState(!1),_=(G=n==null?void 0:n.variants)==null?void 0:G.find(Y=>Y.id===l),j=((H=n==null?void 0:n.variants)==null?void 0:H.filter(Y=>Y.is_active))||[],C=Number((n==null?void 0:n.base_price)||0),A=_?Number(_.price_adjustment):0,M=C+A,I=Number((n==null?void 0:n.shipping_fee)||0),P=i.reduce((Y,se)=>Y+se.quantity,0),R=async Y=>{if(!Y.target.files||Y.target.files.length===0)return;x(!0);const se=Y.target.files[0],ee=se.name.split(".").pop(),oe=`artwork/${Date.now()}-${Math.random().toString(36).substring(7)}.${ee}`;try{const{error:me}=await V.storage.from("marketplace").upload(oe,se);if(me)throw me;const{data:{publicUrl:Q}}=V.storage.from("marketplace").getPublicUrl(oe);p(Q),ae.success("Artwork uploaded successfully")}catch(me){ae.error("Failed to upload artwork: "+me.message)}finally{x(!1)}},O=()=>{if(n){if(j.length>0&&!l){ae.error("Please select an option");return}a(n,_||void 0,c,m||void 0),v(!0),ae.success("Added to cart!"),setTimeout(()=>v(!1),2e3)}},B=()=>{n!=null&&n.images&&h(Y=>(Y+1)%n.images.length)},U=()=>{n!=null&&n.images&&h(Y=>(Y-1+n.images.length)%n.images.length)};return r?e.jsx(Xs,{title:"Product",children:e.jsxs("div",{className:"grid gap-8 lg:grid-cols-2",children:[e.jsx(fn,{className:"aspect-square w-full"}),e.jsxs("div",{className:"space-y-4",children:[e.jsx(fn,{className:"h-8 w-3/4"}),e.jsx(fn,{className:"h-6 w-1/4"}),e.jsx(fn,{className:"h-24 w-full"}),e.jsx(fn,{className:"h-12 w-full"})]})]})}):n?e.jsxs(Xs,{title:n.name,children:[e.jsx(WVt,{className:"mb-6",children:e.jsxs(KVt,{children:[e.jsx(hke,{children:e.jsx(tqe,{asChild:!0,children:e.jsx(nr,{to:"/marketplace",children:"Marketplace"})})}),n.category&&e.jsxs(e.Fragment,{children:[e.jsx(sqe,{}),e.jsx(hke,{children:e.jsx(tqe,{asChild:!0,children:e.jsx(nr,{to:`/marketplace?category=${n.category.id}`,children:n.category.name})})})]}),e.jsx(sqe,{}),e.jsx(hke,{children:e.jsx(YVt,{children:n.name})})]})}),e.jsxs("div",{className:"grid gap-8 lg:grid-cols-2",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"relative aspect-square bg-muted rounded-lg overflow-hidden flex items-center justify-center",children:n.images&&n.images.length>0?e.jsxs(e.Fragment,{children:[e.jsx("img",{src:n.images[u].image_url,alt:n.name,className:"max-w-full max-h-full object-contain"}),n.images.length>1&&e.jsxs(e.Fragment,{children:[e.jsx($,{variant:"ghost",size:"icon",className:"absolute left-2 top-1/2 -translate-y-1/2 bg-background/80 hover:bg-background",onClick:U,children:e.jsx(Ld,{className:"h-6 w-6"})}),e.jsx($,{variant:"ghost",size:"icon",className:"absolute right-2 top-1/2 -translate-y-1/2 bg-background/80 hover:bg-background",onClick:B,children:e.jsx(fi,{className:"h-6 w-6"})})]})]}):e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsx(bh,{className:"h-24 w-24 text-muted-foreground"})})}),n.images&&n.images.length>1&&e.jsx("div",{className:"flex gap-2 overflow-x-auto pb-2",children:n.images.map((Y,se)=>e.jsx("button",{onClick:()=>h(se),className:`w-16 h-16 flex-shrink-0 rounded-md overflow-hidden border-2 ${se===u?"border-primary":"border-transparent"}`,children:e.jsx("img",{src:Y.image_url,alt:"",className:"w-full h-full object-cover"})},Y.id))}),n.video&&e.jsx(we,{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:n.video.video_url,className:"w-full h-full rounded-lg",allowFullScreen:!0})})]})})]}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[n.category&&e.jsx(qe,{variant:"secondary",className:"mb-2",children:n.category.name}),e.jsx("h1",{className:"text-3xl font-bold mb-2",children:n.name}),e.jsxs("div",{className:"flex items-baseline gap-2",children:[e.jsxs("span",{className:"text-3xl font-bold",children:["$",M.toFixed(2)]}),I>0&&e.jsxs("span",{className:"text-muted-foreground",children:["+ $",I.toFixed(2)," shipping"]})]})]}),n.description&&e.jsx("div",{className:"prose prose-sm max-w-none",children:e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:n.description})}),j.length>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(re,{children:"Select Option"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:j.map(Y=>e.jsxs($,{variant:l===Y.id?"default":"outline",onClick:()=>o(Y.id),children:[Y.name,Number(Y.price_adjustment)!==0&&e.jsxs("span",{className:"ml-1 opacity-70",children:["(",Number(Y.price_adjustment)>0?"+":"","$",Number(Y.price_adjustment).toFixed(2),")"]})]},Y.id))})]}),n.allow_artwork_upload&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(re,{children:"Upload Your Artwork (Optional)"}),m?e.jsxs("div",{className:"relative inline-block",children:[e.jsx("img",{src:m,alt:"Your artwork",className:"h-24 w-auto rounded-lg border"}),e.jsx($,{variant:"ghost",size:"sm",className:"absolute -top-2 -right-2",onClick:()=>p(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:R,className:"hidden",id:"artwork-upload",disabled:g}),e.jsxs("label",{htmlFor:"artwork-upload",className:"flex flex-col items-center cursor-pointer",children:[e.jsx(gi,{className:"h-8 w-8 text-muted-foreground mb-2"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:g?"Uploading...":"Click to upload artwork"}),e.jsx("span",{className:"text-xs text-muted-foreground mt-1",children:"Supported: JPG, PNG, PDF, AI, EPS"})]})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(re,{children:"Quantity"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx($,{variant:"outline",size:"icon",onClick:()=>d(Y=>Math.max(1,Y-1)),children:"-"}),e.jsx(be,{type:"number",value:c,onChange:Y=>d(Math.max(1,parseInt(Y.target.value)||1)),className:"w-20 text-center",min:"1"}),e.jsx($,{variant:"outline",size:"icon",onClick:()=>d(Y=>Y+1),children:"+"})]})]}),e.jsxs("div",{className:"flex gap-4",children:[e.jsx($,{size:"lg",className:"flex-1",onClick:O,disabled:y,children:y?e.jsxs(e.Fragment,{children:[e.jsx(ma,{className:"h-5 w-5 mr-2"}),"Added!"]}):e.jsxs(e.Fragment,{children:[e.jsx(ok,{className:"h-5 w-5 mr-2"}),"Add to Cart"]})}),e.jsxs($,{variant:"outline",size:"lg",onClick:()=>t("/marketplace/cart"),className:"relative",children:[e.jsx(ok,{className:"h-5 w-5"}),P>0&&e.jsx(qe,{className:"absolute -top-2 -right-2 h-5 w-5 flex items-center justify-center p-0 text-xs",children:P})]})]}),n.requires_proof_approval&&e.jsx("p",{className:"text-sm text-muted-foreground bg-muted p-3 rounded-lg",children:"📋 This product requires proof approval before production. You'll receive a proof to review after your order is placed."})]})]})]}):e.jsx(Xs,{title:"Product Not Found",children:e.jsxs("div",{className:"text-center py-12",children:[e.jsx(bh,{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($,{onClick:()=>t("/marketplace"),children:"Back to Marketplace"})]})})}function vFn(){const s=Jn(),{cartItems:t,removeFromCart:n,updateQuantity:r,getItemPrice:a,getSubtotal:i,getShippingTotal:l,getTotal:o,clearCart:c}=eAe(),[d,u]=k.useState(!1),[h,m]=k.useState(""),p=async()=>{if(t.length===0){ae.error("Your cart is empty");return}u(!0);try{const{data:g,error:x}=await V.functions.invoke("marketplace-checkout",{body:{items:t.map(y=>{var v;return{product_id:y.product.id,variant_id:((v=y.variant)==null?void 0:v.id)||null,quantity:y.quantity,artwork_url:y.artworkUrl||null}}),notes:h.trim()||null}});if(x)throw x;if(g!=null&&g.url)c(),window.open(g.url,"_blank");else throw new Error("No checkout URL received")}catch(g){ae.error("Checkout failed: "+g.message)}finally{u(!1)}};return t.length===0?e.jsx(Xs,{title:"Shopping Cart",children:e.jsxs("div",{className:"text-center py-12",children:[e.jsx(I5,{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($,{onClick:()=>s("/marketplace"),children:"Browse Marketplace"})]})}):e.jsx(Xs,{title:"Shopping Cart",children:e.jsxs("div",{className:"grid gap-8 lg:grid-cols-3",children:[e.jsxs("div",{className:"lg:col-span-2 space-y-4",children:[t.map(g=>{var x,y;return e.jsx(we,{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:g.product.images&&g.product.images.length>0?e.jsx("img",{src:((x=g.product.images.find(v=>v.is_primary))==null?void 0:x.image_url)||g.product.images[0].image_url,alt:g.product.name,className:"w-full h-full object-cover"}):e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsx(I5,{className:"h-8 w-8 text-muted-foreground"})})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h3",{className:"font-semibold line-clamp-1",children:g.product.name}),g.variant&&e.jsx("p",{className:"text-sm text-muted-foreground",children:g.variant.name}),e.jsxs("p",{className:"font-medium mt-1",children:["$",a(g).toFixed(2),Number(g.product.shipping_fee)>0&&e.jsxs("span",{className:"text-sm text-muted-foreground ml-2",children:["+ $",Number(g.product.shipping_fee).toFixed(2)," shipping"]})]}),g.artworkUrl&&e.jsx("div",{className:"mt-2",children:e.jsx("span",{className:"text-xs text-muted-foreground",children:"Artwork uploaded ✓"})})]}),e.jsxs("div",{className:"flex flex-col items-end gap-2",children:[e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>{var v;return n(g.product.id,(v=g.variant)==null?void 0:v.id)},children:e.jsx(Un,{className:"h-4 w-4 text-destructive"})}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx($,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>{var v;return r(g.product.id,(v=g.variant)==null?void 0:v.id,g.quantity-1)},disabled:g.quantity<=1,children:e.jsx(ak,{className:"h-3 w-3"})}),e.jsx(be,{type:"number",value:g.quantity,onChange:v=>{var _;return r(g.product.id,(_=g.variant)==null?void 0:_.id,parseInt(v.target.value)||1)},className:"w-14 h-8 text-center text-sm",min:"1"}),e.jsx($,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>{var v;return r(g.product.id,(v=g.variant)==null?void 0:v.id,g.quantity+1)},children:e.jsx(nn,{className:"h-3 w-3"})})]})]})]})})},`${g.product.id}-${((y=g.variant)==null?void 0:y.id)||"base"}`)}),e.jsx($,{variant:"ghost",className:"text-destructive",onClick:c,children:"Clear Cart"})]}),e.jsx("div",{children:e.jsxs(we,{className:"sticky top-4",children:[e.jsx(Vt,{children:e.jsx(Yt,{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((g,x)=>g+x.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(Pc,{}),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(Pc,{}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"orderNotes",children:"Order Notes (Optional)"}),e.jsx(Ls,{id:"orderNotes",placeholder:"Add any special instructions, design notes, or comments for your order...",value:h,onChange:g=>m(g.target.value),rows:3,className:"resize-none"})]}),e.jsx($,{className:"w-full",size:"lg",onClick:p,disabled:d,children:d?e.jsxs(e.Fragment,{children:[e.jsx(Jt,{className:"h-5 w-5 mr-2 animate-spin"}),"Processing..."]}):e.jsxs(e.Fragment,{children:["Checkout",e.jsx(xi,{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 bFn(){const s=Jn(),{data:t,isLoading:n}=g8n();return n?e.jsx(Xs,{title:"My Orders",children:e.jsx("div",{className:"space-y-4",children:[1,2,3].map(r=>e.jsx(fn,{className:"h-32 w-full"},r))})}):!t||t.length===0?e.jsx(Xs,{title:"My Orders",children:e.jsxs("div",{className:"text-center py-12",children:[e.jsx(bh,{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($,{onClick:()=>s("/marketplace"),children:"Browse Marketplace"})]})}):e.jsx(Xs,{title:"My Orders",children:e.jsx("div",{className:"space-y-4",children:t.map(r=>{var a,i,l;return e.jsx(we,{className:"cursor-pointer hover:shadow-md transition-shadow",onClick:()=>s(`/marketplace/orders/${r.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:r.order_number}),e.jsx("span",{className:"text-muted-foreground text-sm ml-2",children:Ys(new Date(r.created_at),"MMM d, yyyy")})]}),e.jsx(qe,{className:xQe[r.status],children:qB[r.status]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"flex -space-x-2",children:[(a=r.items)==null?void 0:a.slice(0,3).map((o,c)=>e.jsxs("div",{className:"w-10 h-10 bg-muted rounded border-2 border-background flex items-center justify-center text-xs font-medium",style:{zIndex:3-c},children:[o.quantity,"×"]},o.id)),r.items&&r.items.length>3&&e.jsxs("div",{className:"w-10 h-10 bg-muted rounded border-2 border-background flex items-center justify-center text-xs font-medium",children:["+",r.items.length-3]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm",children:((i=r.items)==null?void 0:i.length)===1?r.items[0].product_name:`${(l=r.items)==null?void 0:l.length} items`}),e.jsxs("p",{className:"font-semibold",children:["$",Number(r.total).toFixed(2)]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[r.tracking_url&&e.jsxs($,{variant:"outline",size:"sm",onClick:o=>{o.stopPropagation(),window.open(r.tracking_url,"_blank")},children:[e.jsx(Ir,{className:"h-4 w-4 mr-1"}),"Track"]}),e.jsx(fi,{className:"h-5 w-5 text-muted-foreground"})]})]})]})},r.id)})})})}const Cbt=["order_submitted","awaiting_proof_approval","proof_approved","processing","in_production","shipped","completed"];function _Fn({currentStatus:s,statusHistory:t}){const n=Cbt.indexOf(s);return e.jsx("div",{className:"space-y-3",children:Cbt.map((r,a)=>{const i=t==null?void 0:t.find(d=>d.status===r),l=an;return e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:`mt-0.5 flex-shrink-0 w-6 h-6 rounded-full flex items-center justify-center ${l?"bg-green-500 text-white":o?"bg-primary text-primary-foreground":"bg-muted text-muted-foreground"}`,children:l?e.jsx(Gr,{className:"h-4 w-4"}):o?e.jsx(sa,{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:qB[r]}),i&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:[Ys(new Date(i.created_at),"MMM d, yyyy h:mm a"),i.notes&&` — ${i.notes}`]})]})]},r)})})}function wFn(){var v;const{orderId:s}=oo(),t=Jn(),{data:n,isLoading:r,refetch:a}=x8n(s||""),i=b8n(),l=_8n(),[o,c]=k.useState(!1),[d,u]=k.useState(null),[h,m]=k.useState(""),[p,g]=k.useState(null),x=async _=>{g(_);try{await i.mutateAsync({orderId:s,itemId:_}),ae.success("Proof approved!"),a()}catch{ae.error("Failed to approve proof")}finally{g(null)}},y=async()=>{if(d){g(d);try{await l.mutateAsync({orderId:s,itemId:d,reason:h}),ae.success("Revision requested"),c(!1),m(""),u(null),a()}catch{ae.error("Failed to request revision")}finally{g(null)}}};return r?e.jsx(Xs,{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(fn,{className:"h-64 w-full"}),e.jsx(fn,{className:"h-48 w-full"})]}),e.jsx(fn,{className:"h-96 w-full"})]})}):n?e.jsxs(Xs,{title:`Order ${n.order_number}`,children:[e.jsxs("div",{className:"grid gap-6 lg:grid-cols-3",children:[e.jsxs("div",{className:"lg:col-span-2 space-y-6",children:[e.jsxs(we,{children:[e.jsxs(Vt,{className:"flex flex-row items-center justify-between",children:[e.jsx(Yt,{children:"Order Status"}),e.jsx(qe,{className:xQe[n.status],children:qB[n.status]})]}),e.jsx(De,{children:e.jsx(_Fn,{currentStatus:n.status,statusHistory:n.status_history})})]}),e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsx(Yt,{children:"Items"})}),e.jsx(De,{className:"space-y-4",children:(v=n.items)==null?void 0:v.map(_=>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:_.product_name}),_.variant_name&&e.jsx("p",{className:"text-sm text-muted-foreground",children:_.variant_name}),e.jsxs("p",{className:"text-sm",children:["Qty: ",_.quantity," × $",Number(_.unit_price).toFixed(2)]})]}),e.jsxs("p",{className:"font-semibold",children:["$",(Number(_.unit_price)*_.quantity).toFixed(2)]})]}),_.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:_.artwork_url,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-2 text-primary hover:underline",children:[e.jsx(UT,{className:"h-4 w-4"}),"View Artwork",e.jsx(Ir,{className:"h-3 w-3"})]})]}),_.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:_.proof_url,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-2 text-primary hover:underline mb-3",children:[e.jsx(UT,{className:"h-4 w-4"}),"View Proof",e.jsx(Ir,{className:"h-3 w-3"})]}),_.proof_status==="pending"&&e.jsxs("div",{className:"flex gap-2 mt-3",children:[e.jsxs($,{size:"sm",onClick:()=>x(_.id),disabled:p===_.id,children:[p===_.id?e.jsx(Jt,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Ay,{className:"h-4 w-4 mr-1"}),"Approve"]}),e.jsxs($,{size:"sm",variant:"outline",onClick:()=>{u(_.id),c(!0)},disabled:p===_.id,children:[e.jsx(sY,{className:"h-4 w-4 mr-1"}),"Request Changes"]})]}),_.proof_status==="approved"&&e.jsxs(qe,{className:"bg-green-100 text-green-800",children:[e.jsx(Gr,{className:"h-3 w-3 mr-1"}),"Proof Approved"]}),_.proof_status==="rejected"&&_.proof_notes&&e.jsxs("div",{className:"mt-2",children:[e.jsx(qe,{variant:"destructive",className:"mb-2",children:"Revision Requested"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:_.proof_notes})]})]})]},_.id))})]}),n.shipping_name&&e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsxs(Yt,{className:"flex items-center gap-2",children:[e.jsx(nY,{className:"h-5 w-5"}),"Shipping"]})}),e.jsxs(De,{children:[e.jsx("p",{className:"font-medium",children:n.shipping_name}),e.jsxs("p",{className:"text-muted-foreground",children:[n.shipping_address,e.jsx("br",{}),n.shipping_city,", ",n.shipping_state," ",n.shipping_zip]}),n.tracking_number&&e.jsxs("div",{className:"mt-4 p-3 bg-muted rounded-lg",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Tracking Number:"}),e.jsx("p",{className:"font-mono font-medium",children:n.tracking_number}),n.tracking_url&&e.jsxs($,{variant:"link",className:"p-0 h-auto mt-1",onClick:()=>window.open(n.tracking_url,"_blank"),children:["Track Package",e.jsx(Ir,{className:"h-3 w-3 ml-1"})]})]})]})]})]}),e.jsx("div",{children:e.jsxs(we,{className:"sticky top-4",children:[e.jsx(Vt,{children:e.jsx(Yt,{children:"Order Summary"})}),e.jsxs(De,{className:"space-y-4",children:[e.jsxs("div",{className:"text-sm text-muted-foreground",children:["Placed on ",Ys(new Date(n.created_at),"MMMM d, yyyy")]}),e.jsx(Pc,{}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{children:"Subtotal"}),e.jsxs("span",{children:["$",Number(n.subtotal).toFixed(2)]})]}),e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{children:"Shipping"}),e.jsxs("span",{children:["$",Number(n.shipping_total).toFixed(2)]})]})]}),e.jsx(Pc,{}),e.jsxs("div",{className:"flex justify-between font-bold text-lg",children:[e.jsx("span",{children:"Total"}),e.jsxs("span",{children:["$",Number(n.total).toFixed(2)]})]}),n.notes&&e.jsxs(e.Fragment,{children:[e.jsx(Pc,{}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium mb-1",children:"Order Notes"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:n.notes})]})]})]})]})})]}),e.jsx(zs,{open:o,onOpenChange:c,children:e.jsxs(Rs,{children:[e.jsxs(Vs,{children:[e.jsx($s,{children:"Request Changes"}),e.jsx(Cr,{children:"Please describe what changes you'd like made to the proof."})]}),e.jsx(Ls,{placeholder:"Describe the changes needed...",value:h,onChange:_=>m(_.target.value),rows:4}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsxs($,{onClick:y,disabled:!h.trim()||p!==null,children:[p?e.jsx(Jt,{className:"h-4 w-4 mr-2 animate-spin"}):null,"Submit Request"]})]})]})})]}):e.jsx(Xs,{title:"Order Not Found",children:e.jsxs("div",{className:"text-center py-12",children:[e.jsx(bh,{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($,{onClick:()=>t("/marketplace/orders"),children:"View All Orders"})]})})}function jFn(){const s=Jn(),[t]=Jc();return t.get("session_id"),k.useEffect(()=>{localStorage.removeItem("marketplace-cart")},[]),e.jsx(Xs,{title:"Order Confirmed",children:e.jsx("div",{className:"max-w-lg mx-auto text-center py-8",children:e.jsx(we,{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(Gr,{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(bh,{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($,{className:"flex-1",onClick:()=>s("/marketplace/orders"),children:["View My Orders",e.jsx(xi,{className:"h-4 w-4 ml-2"})]}),e.jsx($,{variant:"outline",className:"flex-1",onClick:()=>s("/marketplace"),children:"Continue Shopping"})]})]})})})})}function NFn(){const{user:s}=ks(),[t,n]=k.useState("store"),[r,a]=k.useState(null),[i,l]=k.useState(null),[o,c]=k.useState(!1),[d,u]=k.useState(5),[h,m]=k.useState(""),[p,g]=k.useState(!1),[x,y]=k.useState(!1),[v,_]=k.useState(""),[j,C]=k.useState(null),[A,M]=k.useState(!1),{hasSubmittedReview:I,submitReview:P,markPostedToGoogle:R}=kAt(),{data:O}=_Vt(),{data:B,isLoading:U}=bVt(),{data:G,isLoading:H}=A8n(r),{data:Y,isLoading:se}=E8n(s==null?void 0:s.id),{data:ee=0}=M8n(s==null?void 0:s.id),oe=P8n(),me=new Set((Y==null?void 0:Y.map(he=>he.item_id))||[]),Q=async()=>{if(i)try{const he=await oe.mutateAsync(i.id);i.item_type==="reelflow_credits"?ae.success(`🎬 ${i.max_quantity} ReelFlow credits added to your balance!`):ae.success(`Successfully purchased "${i.name}"!`),l(null)}catch(he){ae.error(he.message||"Failed to purchase item")}},te=async()=>{if(!h.trim()){ae.error("Please write a review");return}g(!0);const he=await P(d,h);g(!1),he.success?(ae.success("Thank you for your review! You earned 25 points!"),_(h),y(!0),m(""),u(5)):ae.error(he.error||"Failed to submit review")},le=()=>{navigator.clipboard.writeText(v),ae.success("Review copied to clipboard!")},fe=()=>{R(),window.open("https://g.page/r/CT8bqTBTm7nJEBM/review","_blank")},_e=()=>{y(!1),c(!1),_("")};return U||H||se?e.jsx(Xs,{title:"Reward Store",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(fn,{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(he=>e.jsx(fn,{className:"h-64"},he))})]})}):e.jsxs(Xs,{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(we,{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(ri,{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:ee.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(ql,{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(iu,{className:"h-4 w-4 text-orange-500"}),e.jsx("span",{children:"Streak bonuses add extra points!"})]})]})]})})}),e.jsx(h1,{open:A,onOpenChange:M,children:e.jsxs(we,{className:"border-primary/20",children:[e.jsx(m1,{asChild:!0,children:e.jsx(Vt,{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(ql,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx(Yt,{className:"text-base",children:"How to Earn Points"}),e.jsx(vr,{children:"See all the ways you can earn spendable points"})]})]}),A?e.jsx(Ny,{className:"h-5 w-5 text-muted-foreground"}):e.jsx(Go,{className:"h-5 w-5 text-muted-foreground"})]})})}),e.jsx(f1,{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:[O==null?void 0:O.filter(he=>he.is_active).map(he=>{const Se=Te=>{switch(Te){case"event_attendance":return e.jsx(ha,{className:"h-5 w-5"});case"leave_review":return e.jsx(ri,{className:"h-5 w-5"});case"add_listing":return e.jsx(ua,{className:"h-5 w-5"});case"first_contact":return e.jsx(Xn,{className:"h-5 w-5"});case"first_video":return e.jsx(ia,{className:"h-5 w-5"});case"first_community_post":return e.jsx(bo,{className:"h-5 w-5"});default:return e.jsx(Zo,{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:Se(he.action_key)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm",children:he.action_name}),he.description&&e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:he.description})]}),e.jsxs(qe,{variant:"secondary",className:"font-bold shrink-0",children:["+",he.points]})]},he.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(iu,{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(qe,{variant:"outline",className:"font-bold shrink-0 border-orange-500/50 text-orange-600",children:"+Bonus"})]})]})})})]})}),!I&&e.jsx(we,{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(bo,{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($,{onClick:()=>c(!0),className:"bg-yellow-600 hover:bg-yellow-700",children:[e.jsx(ri,{className:"h-4 w-4 mr-2"}),"Leave Review"]})]})})}),e.jsxs(ya,{value:t,onValueChange:n,children:[e.jsxs(va,{children:[e.jsxs(is,{value:"store",className:"flex items-center gap-2",children:[e.jsx(I5,{className:"h-4 w-4"}),"Store"]}),e.jsxs(is,{value:"my-rewards",className:"flex items-center gap-2",children:[e.jsx(bh,{className:"h-4 w-4"}),"My Rewards",Y&&Y.length>0&&e.jsx(qe,{variant:"secondary",className:"ml-1",children:Y.length})]})]}),e.jsxs(cs,{value:"store",className:"mt-6",children:[B&&B.length>0&&e.jsxs("div",{className:"flex flex-wrap gap-2 mb-6",children:[e.jsx($,{variant:r===null?"default":"outline",size:"sm",onClick:()=>a(null),children:"All"}),B.map(he=>e.jsxs($,{variant:r===he.id?"default":"outline",size:"sm",onClick:()=>a(he.id),children:[he.icon&&`${he.icon} `,he.name]},he.id))]}),!G||G.length===0?e.jsx(we,{children:e.jsx(De,{className:"py-12",children:e.jsxs("div",{className:"text-center text-muted-foreground",children:[e.jsx(Zo,{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:G.map(he=>{const Se=he.item_type==="reelflow_credits",Te=!Se&&me.has(he.id),Ie=!Se&&he.max_quantity!==null&&he.current_quantity===0,Ue=ee>=he.points_cost;return e.jsxs(we,{className:`overflow-hidden transition-all cursor-pointer hover:shadow-lg ${Te?"ring-2 ring-green-500/50 bg-green-500/5":""}`,onClick:()=>C(he),children:[he.preview_image_url?e.jsxs("div",{className:"aspect-video relative overflow-hidden bg-muted",children:[e.jsx("img",{src:he.preview_image_url,alt:he.name,className:"w-full h-full object-cover"}),Te&&e.jsx("div",{className:"absolute top-2 right-2",children:e.jsxs(qe,{className:"bg-green-500 text-white",children:[e.jsx(Gr,{className:"h-3 w-3 mr-1"}),"Owned"]})}),Ie&&!Te&&e.jsx("div",{className:"absolute inset-0 bg-black/50 flex items-center justify-center",children:e.jsx(qe,{variant:"destructive",children:"Sold Out"})})]}):e.jsxs("div",{className:"aspect-video bg-muted flex items-center justify-center relative",children:[e.jsx(Zo,{className:"h-12 w-12 text-muted-foreground/50"}),Te&&e.jsx("div",{className:"absolute top-2 right-2",children:e.jsxs(qe,{className:"bg-green-500 text-white",children:[e.jsx(Gr,{className:"h-3 w-3 mr-1"}),"Owned"]})})]}),e.jsxs(Vt,{className:"pb-2",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsx(Yt,{className:"text-lg",children:he.name}),e.jsxs(qe,{variant:"secondary",className:"font-bold shrink-0",children:[e.jsx(ri,{className:"h-3 w-3 mr-1"}),he.points_cost]})]}),he.category&&e.jsxs(qe,{variant:"outline",className:"w-fit",children:[he.category.icon&&`${he.category.icon} `,he.category.name]})]}),e.jsxs(De,{children:[e.jsx(vr,{className:"mb-4 line-clamp-2",children:he.description||"No description available"}),he.max_quantity!==null&&!Te&&!Se&&e.jsxs("p",{className:"text-xs text-muted-foreground mb-3",children:[he.current_quantity," of ",he.max_quantity," remaining"]}),Se&&e.jsxs("p",{className:"text-xs text-violet-600 font-medium mb-3",children:["🎬 Grants ",he.max_quantity," ReelFlow credits per purchase"]}),Te?e.jsx($,{className:"w-full",onClick:Be=>{Be.stopPropagation(),he.file_url&&YDe(he.file_url,he.name)},disabled:!he.file_url,children:he.item_type==="file"?e.jsxs(e.Fragment,{children:[e.jsx(ji,{className:"h-4 w-4 mr-2"}),"Download"]}):e.jsxs(e.Fragment,{children:[e.jsx(Ir,{className:"h-4 w-4 mr-2"}),"Access"]})}):e.jsx($,{className:"w-full",onClick:Be=>{Be.stopPropagation(),l(he)},disabled:Ie||!Ue,children:Ie?"Sold Out":Ue?e.jsxs(e.Fragment,{children:[e.jsx(I5,{className:"h-4 w-4 mr-2"}),"Purchase"]}):`Need ${he.points_cost-ee} more pts`})]})]},he.id)})})]}),e.jsx(cs,{value:"my-rewards",className:"mt-6",children:!Y||Y.length===0?e.jsx(we,{children:e.jsx(De,{className:"py-12",children:e.jsxs("div",{className:"text-center text-muted-foreground",children:[e.jsx(bh,{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:Y.map(he=>{var Se,Te,Ie,Ue,Be,je,Ye;return e.jsxs(we,{className:"overflow-hidden",children:[(Se=he.item)!=null&&Se.preview_image_url?e.jsx("div",{className:"aspect-video relative overflow-hidden bg-muted",children:e.jsx("img",{src:he.item.preview_image_url,alt:((Te=he.item)==null?void 0:Te.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(Zo,{className:"h-12 w-12 text-muted-foreground/50"})}),e.jsxs(Vt,{className:"pb-2",children:[e.jsx(Yt,{className:"text-lg",children:((Ie=he.item)==null?void 0:Ie.name)||"Unknown Item"}),e.jsxs(vr,{className:"text-xs",children:["Purchased for ",he.points_spent," points • ",new Date(he.purchased_at).toLocaleDateString()]})]}),e.jsx(De,{children:((Ue=he.item)==null?void 0:Ue.item_type)==="reelflow_credits"?e.jsxs($,{className:"w-full",variant:"outline",disabled:!0,children:[e.jsx(Gr,{className:"h-4 w-4 mr-2 text-green-500"}),(Be=he.item)==null?void 0:Be.max_quantity," Credits Applied"]}):e.jsx($,{className:"w-full",onClick:()=>{var Ee,Re;(Ee=he.item)!=null&&Ee.file_url&&YDe(he.item.file_url,(Re=he.item)==null?void 0:Re.name)},disabled:!((je=he.item)!=null&&je.file_url),children:((Ye=he.item)==null?void 0:Ye.item_type)==="file"?e.jsxs(e.Fragment,{children:[e.jsx(ji,{className:"h-4 w-4 mr-2"}),"Download"]}):e.jsxs(e.Fragment,{children:[e.jsx(Ir,{className:"h-4 w-4 mr-2"}),"Access"]})})})]},he.id)})})})]})]}),e.jsx(oc,{open:!!i,onOpenChange:()=>l(null),children:e.jsxs(Ql,{children:[e.jsxs(Jl,{children:[e.jsx(tc,{children:"Confirm Purchase"}),e.jsxs(sc,{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:[ee," points"]}),". After this purchase, you'll have"," ",e.jsxs("strong",{children:[ee-((i==null?void 0:i.points_cost)||0)," points"]})," remaining."]})]}),e.jsxs(ec,{children:[e.jsx(nc,{children:"Cancel"}),e.jsx(Vl,{onClick:Q,disabled:oe.isPending,children:oe.isPending?"Purchasing...":"Confirm Purchase"})]})]})}),e.jsx(zs,{open:o,onOpenChange:he=>{!he&&x?_e():c(he)},children:e.jsx(Rs,{children:x?e.jsxs(e.Fragment,{children:[e.jsxs(Vs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(Gr,{className:"h-5 w-5 text-green-500"}),"Thank You for Your Review!"]}),e.jsx(Cr,{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:['"',v,'"']})]}),e.jsxs($,{variant:"outline",className:"w-full",onClick:le,children:[e.jsx(Da,{className:"h-4 w-4 mr-2"}),"Copy Review to Clipboard"]})]}),e.jsxs(kr,{className:"flex-col sm:flex-row gap-2",children:[e.jsx($,{variant:"outline",onClick:_e,children:"Maybe Later"}),e.jsxs($,{onClick:fe,className:"bg-blue-600 hover:bg-blue-700",children:[e.jsx(Ir,{className:"h-4 w-4 mr-2"}),"Leave Google Review"]})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs(Vs,{children:[e.jsx($s,{children:"Leave a Review"}),e.jsx(Cr,{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(he=>e.jsx("button",{type:"button",onClick:()=>u(he),className:"focus:outline-none",children:e.jsx(ri,{className:`h-8 w-8 transition-colors ${d>=he?"fill-yellow-400 text-yellow-400":"text-muted-foreground hover:text-yellow-400"}`})},he))})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium mb-2 block",children:"Your Review"}),e.jsx(Ls,{placeholder:"What do you love about LevelUp? How has it helped your business?",value:h,onChange:he=>m(he.target.value),rows:4})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsx($,{onClick:te,disabled:p,className:"bg-yellow-600 hover:bg-yellow-700",children:p?"Submitting...":"Submit & Earn 25 Points"})]})]})})}),e.jsx(zs,{open:!!j,onOpenChange:()=>C(null),children:e.jsxs(Rs,{className:"max-w-lg",children:[e.jsxs(Vs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[j==null?void 0:j.name,e.jsxs(qe,{variant:"secondary",className:"font-bold",children:[e.jsx(ri,{className:"h-3 w-3 mr-1"}),j==null?void 0:j.points_cost]})]}),(j==null?void 0:j.category)&&e.jsxs(qe,{variant:"outline",className:"w-fit",children:[j.category.icon&&`${j.category.icon} `,j.category.name]})]}),(j==null?void 0:j.preview_image_url)&&e.jsx("div",{className:"aspect-video relative overflow-hidden bg-muted rounded-lg",children:e.jsx("img",{src:j.preview_image_url,alt:j.name,className:"w-full h-full object-cover"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-muted-foreground",children:(j==null?void 0:j.description)||"No description available"}),(j==null?void 0:j.item_type)==="reelflow_credits"&&e.jsxs("p",{className:"text-sm text-violet-600 font-medium",children:["🎬 Grants ",j==null?void 0:j.max_quantity," ReelFlow credits per purchase"]}),(j==null?void 0:j.item_type)!=="reelflow_credits"&&(j==null?void 0:j.max_quantity)!==null&&!me.has((j==null?void 0:j.id)||"")&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:[j==null?void 0:j.current_quantity," of ",j==null?void 0:j.max_quantity," remaining"]})]}),e.jsx(kr,{children:j&&j.item_type!=="reelflow_credits"&&me.has(j.id)?e.jsx($,{className:"w-full",onClick:()=>{j.file_url&&YDe(j.file_url,j.name)},disabled:!j.file_url,children:j.item_type==="file"?e.jsxs(e.Fragment,{children:[e.jsx(ji,{className:"h-4 w-4 mr-2"}),"Download"]}):e.jsxs(e.Fragment,{children:[e.jsx(Ir,{className:"h-4 w-4 mr-2"}),"Access"]})}):j&&e.jsx($,{className:"w-full",onClick:()=>{C(null),l(j)},disabled:j.item_type!=="reelflow_credits"&&j.max_quantity!==null&&j.current_quantity===0||ee{s&&se()},[s==null?void 0:s.id]);const se=async()=>{if(!s)return;o(!0),v(!1),x(!0);const{data:Be}=await V.from("point_reward_settings").select("action_key, points").in("action_key",["referral_signup","referral_paid"]);Be==null||Be.forEach(Re=>{Re.action_key==="referral_signup"&&h(Re.points),Re.action_key==="referral_paid"&&p(Re.points)});const{data:je}=await V.from("profiles").select("name").eq("id",s.id).maybeSingle();je!=null&&je.name&&j(je.name);let{data:Ye}=await V.from("agent_referral_codes").select("code").eq("user_id",s.id).maybeSingle();if(!Ye){const{data:Re}=await V.rpc("generate_agent_referral_code",{_user_id:s.id}),ke=Re||`agent${s.id.slice(0,6)}`,{data:Fe,error:Oe}=await V.from("agent_referral_codes").insert({user_id:s.id,code:ke}).select("code").maybeSingle();!Oe&&Fe&&(Ye=Fe)}i((Ye==null?void 0:Ye.code)??null);const{data:Ee}=await V.from("agent_referrals").select("id, referred_user_id, status, signed_up_at, qualified_at, signup_points_awarded, paid_points_awarded").eq("referrer_user_id",s.id).order("signed_up_at",{ascending:!1});if(Ee&&Ee.length>0){const Re=Ee.map(Oe=>Oe.referred_user_id),{data:ke}=await V.from("profiles").select("id, name, email").in("id",Re),Fe=new Map((ke==null?void 0:ke.map(Oe=>[Oe.id,Oe]))??[]);d(Ee.map(Oe=>({...Oe,referred_profile:Fe.get(Oe.referred_user_id)??null})))}else d([]);o(!1)},ee=k.useMemo(()=>a?`${kFn}/trial?ref=${a}`:"",[a]),oe=c.length,me=c.filter(Be=>Be.status==="qualified").length,Q=c.filter(Be=>Be.signup_points_awarded).length*u+c.filter(Be=>Be.paid_points_awarded).length*m,te=async()=>{ee&&(await navigator.clipboard.writeText(ee),ae.success("Referral link copied!"))},le=()=>{const Be=encodeURIComponent("Join me on LevelUp"),je=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: ${ee} Let me know if you have any questions!`);window.location.href=`mailto:?subject=${Be}&body=${je}`},fe=()=>{const Be=encodeURIComponent(`Hey! I think you'd love LevelUp for your business — sign up with my link: ${ee}`);window.location.href=`sms:?&body=${Be}`},_e=async()=>{if(navigator.share&&ee)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:ee})}catch{}else te()},ve=Be=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(Be.trim()),he=Be=>{const je=(Be??M).trim().replace(/,$/,"");if(!je)return;const Ye=je.split(/[\s,;]+/).filter(Boolean),Ee=[...P];let Re=0;for(const ke of Ye){if(!ve(ke)){ae.error(`Invalid email: ${ke}`);continue}Ee.includes(ke)||(Ee.push(ke),Re++)}R(Ee),Re>0&&I("")},Se=Be=>R(P.filter(je=>je!==Be)),Te=()=>{G(`${_?_.split(" ")[0]+" invited you to":"Join me on"} LevelUp`),B("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."),A(!0)},Ie=Be=>{const je=Be.replace(/&/g,"&").replace(//g,">").replace(/\n/g,"
"),Ye=_||"A fellow agent",Ee="https://relzejiswnotikjgvjhz.supabase.co/storage/v1/object/public/email-assets/levelup-logo-email.png",Re=ee;return`
LevelUp
You're Invited

${Ye} thinks you'd love LevelUp 🎉

${je}

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

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

`.trim()},Ue=async()=>{if(P.length===0&&(M.trim()&&he(),P.length===0)){ae.error("Add at least one recipient");return}if(!U.trim()){ae.error("Subject is required");return}Y(!0);const Be=Ie(O);let je=0,Ye=0;for(const Ee of P)try{const{data:Re,error:ke}=await V.functions.invoke("gmail-send",{body:{to:Ee,subject:U,body:Be,source:"referral_invite"}});if(ke||Re!=null&&Re.error)throw new Error((ke==null?void 0:ke.message)||(Re==null?void 0:Re.error));je++}catch(Re){console.error("Gmail send failed for",Ee,Re),Ye++}Y(!1),je>0?(ae.success(`Invite sent to ${je} ${je===1?"person":"people"}`+(Ye>0?` (${Ye} failed)`:"")),R([]),I(""),A(!1)):ae.error("Failed to send invites")};return!y&&!g?e.jsx(Xs,{title:"Refer & Earn",children:e.jsxs("div",{className:"container max-w-3xl mx-auto p-4 md:p-8",children:[e.jsx(Sc,{children:e.jsx("title",{children:"Refer & Earn | LevelUp"})}),e.jsxs(we,{className:"border-2 border-dashed",children:[e.jsxs(Vt,{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(fu,{className:"h-6 w-6 text-muted-foreground"})}),e.jsx(Yt,{children:"Refer & Earn is for active members"}),e.jsx(vr,{children:"Activate your subscription to unlock your personal referral link and start earning points."})]}),e.jsx(De,{className:"flex justify-center",children:e.jsx($,{onClick:()=>t("/subscription"),children:"View Subscription"})})]})]})}):e.jsxs(Xs,{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(Sc,{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(Zo,{className:"h-7 w-7 text-primary"}),e.jsx("h1",{className:"text-3xl font-bold tracking-tight",children:"Refer & Earn"})]}),e.jsxs("p",{className:"text-muted-foreground",children:["Share LevelUp with peers, mentees, or fellow agents. Earn"," ",e.jsxs("span",{className:"font-semibold text-foreground",children:[u," points"]})," when they sign up and"," ",e.jsxs("span",{className:"font-semibold text-foreground",children:[m," more"]})," when they activate a paid plan."]})]}),e.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[e.jsx(we,{children:e.jsxs(De,{className:"p-4 flex items-center gap-3",children:[e.jsx(Xn,{className:"h-5 w-5 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold",children:oe}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Friends signed up"})]})]})}),e.jsx(we,{children:e.jsxs(De,{className:"p-4 flex items-center gap-3",children:[e.jsx(Gr,{className:"h-5 w-5 text-emerald-600"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold",children:me}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Activated paid plan"})]})]})}),e.jsx(we,{children:e.jsxs(De,{className:"p-4 flex items-center gap-3",children:[e.jsx(ql,{className:"h-5 w-5 text-amber-500"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold",children:Q.toLocaleString()}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Points earned"})]})]})})]}),e.jsxs(we,{children:[e.jsxs(Vt,{children:[e.jsxs(Yt,{className:"flex items-center gap-2",children:[e.jsx(kn,{className:"h-5 w-5 text-primary"}),"Your referral link"]}),e.jsx(vr,{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(be,{readOnly:!0,value:l?"Loading…":ee,className:"font-mono text-sm",onFocus:Be=>Be.currentTarget.select()}),e.jsxs($,{onClick:te,disabled:!ee,children:[e.jsx(Da,{className:"h-4 w-4 mr-2"}),"Copy link"]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[n&&e.jsxs($,{size:"sm",onClick:Te,disabled:!ee,className:"bg-primary hover:bg-primary/90",children:[e.jsx(Wr,{className:"h-4 w-4 mr-2"})," Send via Gmail"]}),e.jsxs($,{variant:"outline",size:"sm",onClick:le,disabled:!ee,children:[e.jsx(pn,{className:"h-4 w-4 mr-2"})," Email"]}),e.jsxs($,{variant:"outline",size:"sm",onClick:fe,disabled:!ee,children:[e.jsx(bo,{className:"h-4 w-4 mr-2"})," Text"]}),e.jsxs($,{variant:"outline",size:"sm",onClick:_e,disabled:!ee,children:[e.jsx(ou,{className:"h-4 w-4 mr-2"})," More…"]})]}),!n&&e.jsxs("div",{className:"text-xs text-muted-foreground",children:["💡 ",e.jsx("button",{onClick:()=>t("/integrations"),className:"underline hover:text-foreground",children:"Connect Gmail"})," to send branded invite emails directly from your inbox."]}),a&&e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Your code: ",e.jsx("span",{className:"font-mono font-semibold text-foreground",children:a})]})]})]}),e.jsxs(we,{children:[e.jsxs(Vt,{children:[e.jsx(Yt,{children:"Your Referrals"}),e.jsx(vr,{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(Xn,{className:"h-10 w-10 mx-auto text-muted-foreground/50"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No referrals yet. Share your link to get started!"})]}):e.jsx("div",{className:"divide-y",children:c.map(Be=>{var Ee,Re;const je=((Ee=Be.referred_profile)==null?void 0:Ee.name)||((Re=Be.referred_profile)==null?void 0:Re.email)||"New agent",Ye=new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",month:"short",day:"numeric",year:"numeric"}).format(new Date(Be.signed_up_at));return e.jsxs("div",{className:"py-3 flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-medium truncate",children:je}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Joined ",Ye]})]}),Be.status==="qualified"?e.jsxs(qe,{className:"bg-emerald-100 text-emerald-700 border-emerald-200 hover:bg-emerald-100",children:[e.jsx(Gr,{className:"h-3 w-3 mr-1"})," Paid · +",u+m," pts"]}):e.jsxs(qe,{variant:"secondary",children:[e.jsx(sa,{className:"h-3 w-3 mr-1"})," Signed up · +",u," pts"]})]},Be.id)})})})]}),e.jsx(we,{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(kn,{className:"h-4 w-4 text-primary"})," How it works"]}),e.jsxs("ol",{className:"text-sm text-muted-foreground space-y-2 list-decimal list-inside",children:[e.jsx("li",{children:"Share your unique link with peers, mentees, or other agents."}),e.jsxs("li",{children:["They sign up — you instantly earn ",e.jsxs("strong",{className:"text-foreground",children:[u," points"]}),"."]}),e.jsxs("li",{children:["When they activate a paid plan, you earn another ",e.jsxs("strong",{className:"text-foreground",children:[m," points"]}),"."]}),e.jsxs("li",{children:["Redeem points in the ",e.jsx("a",{href:"/reward-store",className:"text-primary underline",children:"Reward Store"}),"."]})]})]})}),e.jsx(Pc,{className:"opacity-0"})]}),e.jsx(zs,{open:C,onOpenChange:A,children:e.jsxs(Rs,{className:"sm:max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(Vs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(Wr,{className:"h-5 w-5 text-primary"})," Send referral invites via Gmail"]}),e.jsxs(Cr,{children:["Sending from ",e.jsx("span",{className:"font-medium text-foreground",children:r}),". We'll deliver a branded LevelUp invite with your personal note."]})]}),e.jsxs("div",{className:"space-y-4 py-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Recipients"}),e.jsxs("div",{className:"flex flex-wrap gap-1.5 p-2 border rounded-md min-h-[44px] bg-background",children:[P.map(Be=>e.jsxs(qe,{variant:"secondary",className:"gap-1 pr-1",children:[Be,e.jsx("button",{type:"button",onClick:()=>Se(Be),className:"hover:bg-muted-foreground/20 rounded-full p-0.5","aria-label":`Remove ${Be}`,children:e.jsx(mr,{className:"h-3 w-3"})})]},Be)),e.jsx("input",{type:"email",value:M,onChange:Be=>I(Be.target.value),onKeyDown:Be=>{Be.key==="Enter"||Be.key===","||Be.key===" "?(Be.preventDefault(),he()):Be.key==="Backspace"&&!M&&P.length>0&&R(P.slice(0,-1))},onBlur:()=>M.trim()&&he(),onPaste:Be=>{const je=Be.clipboardData.getData("text");/[\s,;]/.test(je)&&(Be.preventDefault(),he(je))},placeholder:P.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(re,{htmlFor:"email-subject",children:"Subject"}),e.jsx(be,{id:"email-subject",value:U,onChange:Be=>G(Be.target.value),placeholder:"Subject line"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"personal-note",children:"Your personal note"}),e.jsx(Ls,{id:"personal-note",value:O,onChange:Be=>B(Be.target.value),rows:4,placeholder:"Write a quick note explaining why they'd love LevelUp…"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Preview"}),e.jsxs("div",{className:"border rounded-md overflow-hidden bg-muted/30",children:[e.jsxs("div",{className:"px-3 py-2 bg-muted/60 border-b text-xs text-muted-foreground flex items-center justify-between",children:[e.jsxs("span",{className:"truncate",children:["From: ",r]}),e.jsxs("span",{className:"truncate ml-2",children:["Subject: ",U||"(no subject)"]})]}),e.jsx("iframe",{title:"Email preview",srcDoc:Ie(O),className:"w-full h-[420px] bg-white"})]})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>A(!1),disabled:H,children:"Cancel"}),e.jsxs($,{onClick:Ue,disabled:H,children:[e.jsx(Wr,{className:"h-4 w-4 mr-2"}),H?"Sending…":`Send${P.length>0?` to ${P.length}`:""}`]})]})]})})]})}const ZVt=()=>{const{user:s}=ks(),t=ls(),n=pt({queryKey:["smart-presentations",s==null?void 0:s.id],queryFn:async()=>{const{data:d,error:u}=await V.from("smart_presentations").select("*").eq("owner_user_id",s.id).neq("status","archived").order("created_at",{ascending:!1});if(u)throw u;return d||[]},enabled:!!s}),r=pt({queryKey:["smart-presentation-templates",s==null?void 0:s.id],queryFn:async()=>{const{data:d,error:u}=await V.from("smart_presentation_templates").select("*").eq("is_active",!0).order("created_at",{ascending:!0});if(u)throw u;return d||[]},enabled:!!s}),a=Nt({mutationFn:async d=>{const{data:u,error:h}=await V.from("smart_presentations").insert({owner_user_id:s.id,...d}).select().single();if(h)throw h;return u},onSuccess:()=>{t.invalidateQueries({queryKey:["smart-presentations"]})}}),i=Nt({mutationFn:async({id:d,...u})=>{const{data:h,error:m}=await V.from("smart_presentations").update(u).eq("id",d).select().single();if(m)throw m;return h},onSuccess:()=>{t.invalidateQueries({queryKey:["smart-presentations"]})}}),l=Nt({mutationFn:async d=>{const{data:u,error:h}=await V.from("smart_presentations").update({status:"published",published_at:new Date().toISOString()}).eq("id",d).select().single();if(h)throw h;return u},onSuccess:()=>{t.invalidateQueries({queryKey:["smart-presentations"]}),ae.success("Presentation published!")}}),o=Nt({mutationFn:async d=>{const{error:u}=await V.from("smart_presentations").update({status:"archived"}).eq("id",d);if(u)throw u},onSuccess:()=>{t.invalidateQueries({queryKey:["smart-presentations"]}),ae.success("Presentation archived")}}),c=Nt({mutationFn:async d=>{const{error:u}=await V.from("smart_presentation_templates").insert({owner_user_id:s.id,name:d.title+" Template",description:"Created from "+d.title,template_type:"custom",icon:"📄",sections:d.sections,cta_config:{type:d.cta_type,label:d.cta_label},is_system:!1});if(u)throw u},onSuccess:()=>{t.invalidateQueries({queryKey:["smart-presentation-templates"]}),ae.success("Saved as template!")}});return{presentations:n.data||[],templates:r.data||[],isLoading:n.isLoading,templatesLoading:r.isLoading,createPresentation:a,updatePresentation:i,publishPresentation:l,archivePresentation:o,saveAsTemplate:c}},CFn=()=>{const s=Jn(),{presentations:t,isLoading:n,archivePresentation:r,saveAsTemplate:a}=ZVt(),i=o=>o.status==="draft"?e.jsx(qe,{variant:"outline",className:"text-xs",children:"Draft"}):o.view_count>1?e.jsx(qe,{className:"text-xs bg-emerald-100 text-emerald-700 border-emerald-200",children:"Revisited"}):o.view_count===1?e.jsx(qe,{className:"text-xs bg-blue-100 text-blue-700 border-blue-200",children:"Opened"}):e.jsx(qe,{variant:"secondary",className:"text-xs",children:"Not Opened"}),l=o=>{const c=`https://presentations.relevelup.com/${o}`;navigator.clipboard.writeText(c),ae.success("Link copied!")};return e.jsx(Xs,{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($,{onClick:()=>s("/mission-control/presentations/new"),className:"gap-2",children:[e.jsx(nn,{className:"h-4 w-4"}),"Create Presentation"]})]}),n?e.jsx("div",{className:"space-y-3",children:[1,2,3].map(o=>e.jsx(fn,{className:"h-20 w-full rounded-lg"},o))}):t.length===0?e.jsx(we,{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(hv,{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($,{onClick:()=>s("/mission-control/presentations/new"),className:"gap-2",children:[e.jsx(nn,{className:"h-4 w-4"}),"Create Your First Presentation"]})]})}):e.jsx("div",{className:"space-y-3",children:t.map(o=>e.jsx(we,{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(ea,{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 ",Ys(new Date(o.created_at),"MMM d, yyyy")]}),o.view_count>0&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ba,{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($,{variant:"outline",size:"sm",onClick:()=>l(o.share_token),children:[e.jsx(Da,{className:"h-3.5 w-3.5 mr-1"}),"Copy Link"]}),o.status==="published"&&e.jsx($,{variant:"outline",size:"sm",onClick:()=>s(`/mission-control/presentations/${o.id}?edit=true`),children:"Edit"}),e.jsx($,{variant:"outline",size:"sm",onClick:()=>s(`/mission-control/presentations/${o.id}`),children:o.status==="draft"?"Edit":"View"}),e.jsxs(Au,{children:[e.jsx(Eu,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8",children:e.jsx(Z0,{className:"h-4 w-4"})})}),e.jsxs(gu,{align:"end",children:[o.status==="published"&&o.share_token&&e.jsxs(Pa,{onClick:()=>window.open(`https://presentations.relevelup.com/${o.share_token}`,"_blank"),children:[e.jsx(Ir,{className:"h-4 w-4 mr-2"}),"Preview Link"]}),e.jsxs(Pa,{onClick:()=>a.mutate(o),children:[e.jsx(ea,{className:"h-4 w-4 mr-2"}),"Save as Template"]}),e.jsxs(Pa,{onClick:()=>r.mutate(o.id),className:"text-destructive",children:[e.jsx(kf,{className:"h-4 w-4 mr-2"}),"Archive"]})]})]})]})]})})]})})},o.id))})]})})},Abt={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."}]},AFn=[{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 EFn(s){const t=Abt[s];if(t)return t;const n=s.toLowerCase();for(const[r,a]of Object.entries(Abt))if(n.includes(r.toLowerCase())||r.toLowerCase().includes(n))return a;return AFn}function TFn({sectionTitle:s,contactId:t,onVideoReady:n}){const[r,a]=k.useState(!1),[i,l]=k.useState("script"),[o,c]=k.useState(0),[d,u]=k.useState(0),{canRecord:h}=U7t(),m=o4(),[p,g]=k.useState(""),[x,y]=k.useState(!1),[v,_]=k.useState(!0),[j,C]=k.useState(!1),[A,M]=k.useState(null),I=EFn(s),P=()=>{l("script"),c(0),u(0),g(""),y(!1),_(!0),C(!1),M(null)},R=H=>{!H&&(i==="uploading"||i==="processing")||(a(H),H||P())},O=H=>{M(H),g(I[H].text),y(!1)},B=()=>{l("record"),_(p.trim().length>0)},U=()=>{g(""),_(!1),l("record")},G=k.useCallback(async(H,Y)=>{l("uploading");try{const se=s||"Presentation Video",{videoId:ee,uploadUrl:oe,libraryId:me}=await v6(se),{apiKey:Q}=await b6(ee),te=new XMLHttpRequest;te.upload.onprogress=he=>{he.lengthComputable&&c(he.loaded/he.total*100)},await new Promise((he,Se)=>{te.onload=()=>te.status>=200&&te.status<300?he():Se(new Error("Upload failed")),te.onerror=()=>Se(new Error("Upload failed")),te.open("PUT",oe),te.setRequestHeader("AccessKey",Q),te.send(H)}),l("processing");let le=0;const fe=Date.now(),_e=9e4;let ve=null;for(;le<4;){if(await new Promise(Se=>setTimeout(Se,3e3)),Date.now()-fe>_e){const Se=H.size/1048576,Te=`https://iframe.mediadelivery.net/embed/${me}/${ee}?responsive=true`;await m.mutateAsync({bunny_video_id:ee,playback_url:Te,file_size_mb:Se,title:se,contact_id:t||void 0,status:"processing",touch_type:"presentation"}),n(Te),ae.success("Video saved — still encoding. It will be ready shortly."),l("done"),setTimeout(()=>a(!1),1500);return}const he=await D2(ee);if(le=he.status,u(he.encodeProgress||0),le===4)ve={playbackUrl:he.directPlayUrl,thumbnailUrl:he.thumbnailUrl,previewUrl:he.previewUrl||null,duration:he.length||Y,fileSizeMb:(he.storageSize||H.size)/(1024*1024)};else if(le===5||le===6)throw new Error("Video processing failed")}if(!ve)throw new Error("No video data");await m.mutateAsync({bunny_video_id:ee,contact_id:t||void 0,playback_url:ve.playbackUrl,thumbnail_url:ve.thumbnailUrl,preview_url:ve.previewUrl,duration_seconds:ve.duration,file_size_mb:ve.fileSizeMb,title:se,status:"ready",touch_type:"presentation"}),n(ve.playbackUrl),ae.success("Video recorded, saved to library & attached!"),l("done"),setTimeout(()=>a(!1),1500)}catch(se){console.error("Recording upload error:",se),ae.error("Failed to process video. Please try again."),l("record")}},[s,t,n,m]);return e.jsxs(zs,{open:r,onOpenChange:R,children:[e.jsx(yl,{asChild:!0,children:e.jsxs($,{variant:"outline",size:"sm",className:"gap-1.5 shrink-0",title:"Record a video",children:[e.jsx(ia,{className:"h-3.5 w-3.5"}),"Record"]})}),e.jsxs(Rs,{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(Vs,{children:e.jsxs($s,{children:[i==="script"&&`Prepare your script for "${s}"`,i==="record"&&`Record video for "${s}"`,i==="uploading"&&"Uploading...",i==="processing"&&"Processing...",i==="done"&&"Done!"]})}),i==="script"&&e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Choose a starter script below, edit it to make it yours, or skip and speak freely."}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wide",children:"Starter Scripts"}),e.jsx("div",{className:"grid gap-2",children:I.map((H,Y)=>e.jsxs("button",{onClick:()=>O(Y),className:Ot("text-left p-3 rounded-lg border transition-all hover:bg-accent/50",A===Y?"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(ea,{className:"h-3.5 w-3.5 text-primary shrink-0"}),e.jsx("span",{className:"text-sm font-medium",children:H.label})]}),e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2 ml-5.5",children:H.text})]},Y))})]}),p&&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"}),!x&&e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>y(!0),className:"h-7 text-xs gap-1",children:[e.jsx(ui,{className:"h-3 w-3"}),"Edit"]})]}),x?e.jsx(Ls,{value:p,onChange:H=>g(H.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:p})]}),!p&&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(Ls,{value:p,onChange:H=>{g(H.target.value),M(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($,{variant:"ghost",size:"sm",onClick:U,className:"text-muted-foreground",children:"Skip — no teleprompter"}),e.jsx($,{onClick:B,disabled:!1,children:p.trim()?"Continue with Script":"Continue Without Script"})]})]}),!h&&i==="record"?e.jsxs("div",{className:"flex flex-col items-center gap-3 py-8 text-center",children:[e.jsx(Gd,{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."}),p.trim()&&e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>_(!v),className:"h-7 text-xs gap-1",children:[v?e.jsx(x0,{className:"h-3 w-3"}):e.jsx(ba,{className:"h-3 w-3"}),v?"Hide Script":"Show Script"]})]}),e.jsx(w6,{maxDurationSeconds:600,onRecordingComplete:G,onRecordingStateChange:C,onError:H=>ae.error(H),teleprompterContent:p.trim()?e.jsx(uQe,{text:p,isVisible:v,onToggleVisibility:()=>_(!v),isRecording:j,startCountdown:!1}):void 0}),e.jsx($,{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(Jt,{className:"h-10 w-10 animate-spin text-primary"}),e.jsxs("div",{className:"w-full max-w-xs space-y-2",children:[e.jsx(ho,{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(Jt,{className:"h-10 w-10 animate-spin text-primary"}),e.jsxs("div",{className:"w-full max-w-xs space-y-2",children:[e.jsx(ho,{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(nl,{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 MFn({sectionTitle:s,contactId:t,onVideoReady:n}){const[r,a]=k.useState(!1),[i,l]=k.useState(null),[o,c]=k.useState("idle"),[d,u]=k.useState(0),h=k.useRef(null),m=o4(),{data:p}=oTe(),g=(p==null?void 0:p.total_storage_mb)||0,y=((p==null?void 0:p.max_storage_mb)||1024)-g,v=()=>{l(null),c("idle"),u(0)},_=I=>{!I&&o!=="idle"&&o!=="done"||(a(I),I||v())},j=I=>{var O;const P=(O=I.target.files)==null?void 0:O[0];if(!P)return;if(!P.type.startsWith("video/")){ae.error("Please select a video file");return}const R=P.size/(1024*1024);if(R>500){ae.error("Video file must be less than 500MB");return}if(R>y){ae.error(`Not enough storage. You have ${y.toFixed(1)} MB remaining.`);return}l(P)},C=k.useCallback(async()=>{if(i){c("creating"),u(0);try{const I=s||i.name,{data:P,error:R}=await V.functions.invoke("bunny-upload",{body:{action:"create",title:I,isAgentVideo:!0}});if(R)throw new Error(R.message);const{videoId:O,libraryId:B}=P;c("uploading");const{data:U,error:G}=await V.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:O,isAgentVideo:!0}});if(G)throw new Error(G.message);await new Promise((se,ee)=>{const oe=new XMLHttpRequest;oe.upload.addEventListener("progress",me=>{me.lengthComputable&&u(Math.round(me.loaded/me.total*100))}),oe.addEventListener("load",()=>oe.status>=200&&oe.status<300?se():ee(new Error(`Upload failed (${oe.status})`))),oe.addEventListener("error",()=>ee(new Error("Upload failed"))),oe.open("PUT",U.uploadUrl),oe.setRequestHeader("AccessKey",U.apiKey),oe.send(i)}),c("processing");const H=i.size/(1024*1024),Y=`https://iframe.mediadelivery.net/embed/${B}/${O}`;await m.mutateAsync({bunny_video_id:O,playback_url:Y,file_size_mb:H,title:I,contact_id:t||void 0,status:"processing",touch_type:"presentation"}),n(Y),c("done"),ae.success("Video uploaded & attached to section!"),setTimeout(()=>a(!1),1200)}catch(I){console.error("Upload error:",I),ae.error(I instanceof Error?I.message:"Failed to upload video"),c("idle")}}},[i,s,t,n,m]),A=()=>{switch(o){case"creating":return"Preparing upload...";case"uploading":return`Uploading... ${d}%`;case"processing":return"Saving video...";case"done":return"Done!";default:return""}},M=o!=="idle"&&o!=="done";return e.jsxs(zs,{open:r,onOpenChange:_,children:[e.jsx(yl,{asChild:!0,children:e.jsxs($,{variant:"outline",size:"sm",className:"gap-1.5 shrink-0",title:"Upload a video file",children:[e.jsx(gi,{className:"h-3.5 w-3.5"}),"Upload"]})}),e.jsxs(Rs,{className:"sm:max-w-md",children:[e.jsx(Vs,{children:e.jsxs($s,{children:['Upload Video for "',s,'"']})}),e.jsxs("div",{className:"space-y-4 py-2",children:[i?e.jsxs("div",{className:"flex items-center gap-3 p-3 bg-muted rounded-lg",children:[e.jsx(ia,{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"]})]}),!M&&e.jsx($,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>l(null),children:e.jsx(mr,{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 I;return(I=h.current)==null?void 0:I.click()},children:[e.jsx(gi,{className:"h-8 w-8 mx-auto text-muted-foreground mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Click to select a video file"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"MP4, MOV, WebM (max 500MB)"})]}),e.jsx("input",{ref:h,type:"file",accept:"video/*",className:"hidden",onChange:j,disabled:M}),M&&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(Jt,{className:"h-4 w-4 animate-spin"}),e.jsx("span",{children:A()})]}),e.jsx(ho,{value:o==="uploading"?d:o==="processing"?100:10})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>_(!1),disabled:M,children:"Cancel"}),e.jsx($,{onClick:C,disabled:!i||M,children:M?e.jsxs(e.Fragment,{children:[e.jsx(Jt,{className:"h-4 w-4 mr-2 animate-spin"}),"Uploading..."]}):e.jsxs(e.Fragment,{children:[e.jsx(gi,{className:"h-4 w-4 mr-2"}),"Upload & Attach"]})})]})]})]})}const Ebt=[{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"}],Tbt=()=>{const s=Jn(),{id:t}=oo(),{user:n}=ks(),{templates:r,templatesLoading:a,createPresentation:i,updatePresentation:l,publishPresentation:o}=ZVt(),{isGmailConnected:c,gmailEmail:d}=dx(),[u,h]=k.useState(!1),[m,p]=k.useState("client"),[g,x]=k.useState(!1),[y,v]=k.useState(""),[_,j]=k.useState([]),[C,A]=k.useState(!1),[M,I]=k.useState(null),[P,R]=k.useState(!1),[O,B]=k.useState(""),[U,G]=k.useState(""),[H,Y]=k.useState(""),[se,ee]=k.useState("buyer"),[oe,me]=k.useState(""),[Q,te]=k.useState(null),[le,fe]=k.useState(""),[_e,ve]=k.useState([]),[he,Se]=k.useState("schedule_call"),[Te,Ie]=k.useState("Schedule a Call"),[Ue,Be]=k.useState(""),[je,Ye]=k.useState(""),[Ee,Re]=k.useState(null),[ke,Fe]=k.useState(t||null),[Oe,Ge]=k.useState(null),[yt,tt]=k.useState(!1),ut=async(gt,rs)=>{if(!n)return;const Ns=5*1024*1024;if(gt.size>Ns){ae.error("Image must be under 5MB");return}if(!gt.type.startsWith("image/")){ae.error("Please upload an image file");return}Re(rs);try{const us=gt.name.split(".").pop()||"jpg",Bs=`${n.id}/${Date.now()}.${us}`,{error:Ts}=await V.storage.from("listing-photos").upload(Bs,gt);if(Ts)throw Ts;const{data:{publicUrl:Fn}}=V.storage.from("listing-photos").getPublicUrl(Bs);Ft(rs,{image_url:Fn}),ae.success("Image uploaded")}catch{ae.error("Failed to upload image")}finally{Re(null)}};k.useEffect(()=>{t&&nt(t)},[t]);const nt=async gt=>{const{data:rs,error:Ns}=await V.from("smart_presentations").select("*").eq("id",gt).single();if(Ns||!rs)return;const us=rs;if(x(!0),fe(us.title),B(us.client_name||""),me(us.property_address||""),ve(us.sections||[]),Se(us.cta_type||"schedule_call"),Ie(us.cta_label||"Schedule a Call"),Be(us.cta_url||""),Ye(us.heading||""),Ge(us.share_token),tt(us.status==="published"),Fe(us.id),p("builder"),us.contact_id){const{data:Bs}=await V.from("innercircle_contacts").select("id, first_name, last_name, email, phone").eq("id",us.contact_id).maybeSingle();Bs&&(I(Bs),G(Bs.email||""),Y(Bs.phone||""))}};k.useEffect(()=>{if(!n||y.length<1){j([]);return}const gt=setTimeout(async()=>{A(!0);const{data:rs}=await V.from("innercircle_contacts").select("id, first_name, last_name, email, phone, lead_source").eq("owner_user_id",n.id).or(`first_name.ilike.%${y}%,last_name.ilike.%${y}%,email.ilike.%${y}%`).limit(10);j(rs||[]),A(!1)},300);return()=>clearTimeout(gt)},[y,n]);const et=gt=>{I(gt),B(`${gt.first_name} ${gt.last_name||""}`.trim()),G(gt.email||""),Y(gt.phone||""),R(!1)},at=async()=>{if(!O.trim()){ae.error("Client name is required");return}const gt=O.trim().split(" "),rs=gt[0],Ns=gt.slice(1).join(" ")||null,{data:us,error:Bs}=await V.from("innercircle_contacts").insert({owner_user_id:n.id,first_name:rs,last_name:Ns,email:U||null,phone:H||null,lead_source:"Smart Presentation"}).select().single();if(Bs){ae.error("Failed to create client");return}I(us),ae.success("Client created & saved to Agent OS"),p("template")},wt=gt=>{te(gt);const rs=(gt.sections||[]).map(Ns=>({...Ns,is_visible:!0,video_url:"",text:""}));if(ve(rs),fe(gt.name+(O?` for ${O}`:"")),gt.cta_config){const Ns=gt.cta_config;Se(Ns.type||"schedule_call"),Ie(Ns.label||"Schedule a Call")}p("builder")},rt=()=>{ve([{title:"Welcome",description:"A personal welcome",type:"video",icon:"👋",is_visible:!0}]),fe(O?`Presentation for ${O}`:"New Presentation"),p("builder")},Ft=(gt,rs)=>{ve(Ns=>Ns.map((us,Bs)=>Bs===gt?{...us,...rs}:us))},Ut=gt=>{Ft(gt,{is_visible:!_e[gt].is_visible})},Is=()=>{ve(gt=>[...gt,{title:"New Section",description:"",type:"video",icon:"📝",is_visible:!0}])},xs=gt=>{ve(rs=>rs.filter((Ns,us)=>us!==gt))},st=async()=>{if(!le.trim()){ae.error("Title is required");return}try{if(ke){const gt=await l.mutateAsync({id:ke,title:le,sections:_e,client_name:O,property_address:oe||null,cta_type:he,cta_label:Te,cta_url:Ue||null,heading:je||null});ae.success("Saved")}else{const gt=await i.mutateAsync({title:le,contact_id:(M==null?void 0:M.id)||void 0,client_name:O,property_address:oe||void 0,template_id:(Q==null?void 0:Q.id)||void 0,sections:_e,cta_type:he,cta_label:Te,cta_url:Ue||void 0,heading:je||void 0});Fe(gt.id),Ge(gt.share_token),ae.success("Presentation created!")}}catch(gt){console.error("Failed to save presentation:",gt);const rs=(gt==null?void 0:gt.message)||(gt==null?void 0:gt.toString())||"Unknown error";ae.error(`Failed to save: ${rs}`)}},dt=async()=>{try{await st();const gt=ke;if(gt){const rs=await o.mutateAsync(gt);Ge(rs.share_token),tt(!0),p("share")}}catch(gt){console.error("Failed to publish presentation:",gt),ae.error(`Failed to publish: ${(gt==null?void 0:gt.message)||"Unknown error"}`)}},jt=Oe?`https://presentations.relevelup.com/${Oe}`:"";return e.jsx(Xs,{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($,{variant:"ghost",size:"icon",onClick:()=>s("/mission-control/presentations"),children:e.jsx(Ia,{className:"h-4 w-4"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-xl font-serif font-bold text-foreground",children:g?"Edit Presentation":"Create Smart Presentation"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[m==="client"&&"Who is this presentation for?",m==="template"&&"Choose a starting template",m==="builder"&&"Customize your presentation",m==="share"&&"Share with your client"]})]})]}),!g&&e.jsx("div",{className:"flex items-center gap-2",children:["client","template","builder","share"].map((gt,rs)=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:Ot("w-8 h-8 rounded-full flex items-center justify-center text-sm font-medium transition-colors",m===gt?"bg-primary text-primary-foreground":rs<["client","template","builder","share"].indexOf(m)?"bg-emerald-100 text-emerald-700":"bg-muted text-muted-foreground"),children:rs<["client","template","builder","share"].indexOf(m)?e.jsx(ma,{className:"h-4 w-4"}):rs+1}),e.jsx("span",{className:"text-sm font-medium capitalize hidden sm:inline",children:gt}),rs<3&&e.jsx("div",{className:"w-8 h-px bg-border"})]},gt))}),m==="client"&&e.jsxs("div",{className:"space-y-6",children:[e.jsxs("button",{onClick:()=>{I(null),B(""),G(""),Y(""),R(!1),p("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(Wr,{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(xi,{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(we,{children:[e.jsx(Vt,{className:"pb-3",children:e.jsxs(Yt,{className:"text-base flex items-center gap-2",children:[e.jsx(Yr,{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(Yr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search by name or email...",value:y,onChange:gt=>v(gt.target.value),className:"pl-10"})]}),e.jsxs("div",{className:"space-y-2 max-h-56 overflow-y-auto",children:[C&&e.jsx(fn,{className:"h-12 w-full"}),_.map(gt=>e.jsxs("button",{onClick:()=>et(gt),className:Ot("w-full text-left p-3 rounded-lg border transition-colors",(M==null?void 0:M.id)===gt.id?"border-primary bg-primary/5":"border-border hover:border-primary/50"),children:[e.jsxs("p",{className:"font-medium text-sm",children:[gt.first_name," ",gt.last_name]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:gt.email||gt.phone||"No contact info"})]},gt.id)),!y&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-6",children:"Start typing to search your contacts"}),y&&_.length===0&&!C&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-6",children:"No clients found"})]}),M&&e.jsxs($,{onClick:()=>p("template"),className:"w-full gap-2",children:["Continue with ",M.first_name,e.jsx(xi,{className:"h-4 w-4"})]})]})]}),e.jsxs(we,{children:[e.jsx(Vt,{className:"pb-3",children:e.jsxs(Yt,{className:"text-base flex items-center gap-2",children:[e.jsx(Pl,{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(re,{className:"text-xs",children:"Name *"}),e.jsx(be,{value:O,onChange:gt=>{B(gt.target.value),R(!0),I(null)},placeholder:"Sarah & Mike Johnson"})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Email"}),e.jsx(be,{value:U,onChange:gt=>G(gt.target.value),placeholder:"Optional",type:"email"})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Phone"}),e.jsx(be,{value:H,onChange:gt=>Y(gt.target.value),placeholder:"Optional"})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Client Type"}),e.jsxs(bs,{value:se,onValueChange:ee,children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"buyer",children:"Buyer"}),e.jsx(We,{value:"seller",children:"Seller"}),e.jsx(We,{value:"recruit",children:"Recruit"}),e.jsx(We,{value:"other",children:"Other"})]})]})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Property Address"}),e.jsx(be,{value:oe,onChange:gt=>me(gt.target.value),placeholder:"Optional"})]})]}),P&&O&&e.jsxs($,{onClick:at,className:"w-full gap-2",children:["Create Client & Continue",e.jsx(xi,{className:"h-4 w-4"})]})]})]})]})]}),m==="template"&&e.jsxs("div",{className:"space-y-6",children:[e.jsxs(ya,{defaultValue:"system",children:[e.jsxs(va,{children:[e.jsx(is,{value:"mine",children:"My Core Templates"}),e.jsx(is,{value:"system",children:"LevelUp Smart Templates"}),e.jsx(is,{value:"blank",children:"+ Start Blank"})]}),e.jsx(cs,{value:"mine",className:"mt-4",children:a?e.jsx("div",{className:"grid grid-cols-2 gap-4",children:[1,2].map(gt=>e.jsx(fn,{className:"h-32"},gt))}):e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:r.filter(gt=>!gt.is_system).length===0?e.jsx("p",{className:"text-muted-foreground col-span-2 text-center py-8",children:"You haven't saved any templates yet. Create a presentation and save it as a template!"}):r.filter(gt=>!gt.is_system).map(gt=>e.jsx(Mbt,{template:gt,onSelect:wt},gt.id))})}),e.jsx(cs,{value:"system",className:"mt-4",children:e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:r.filter(gt=>gt.is_system).map(gt=>e.jsx(Mbt,{template:gt,onSelect:wt},gt.id))})}),e.jsx(cs,{value:"blank",className:"mt-4",children:e.jsx(we,{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($,{onClick:rt,children:"Start from Scratch"})]})})})]}),e.jsxs($,{variant:"outline",onClick:()=>p("client"),className:"gap-2",children:[e.jsx(Ia,{className:"h-4 w-4"}),"Back"]})]}),m==="builder"&&e.jsxs("div",{className:"space-y-6",children:[e.jsx(we,{children:e.jsxs(De,{className:"pt-6 space-y-4",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Presentation Title"}),e.jsx(be,{value:le,onChange:gt=>fe(gt.target.value)})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Page Heading"}),e.jsx(be,{value:je,onChange:gt=>Ye(gt.target.value),placeholder:O?`Welcome, ${O}!`:"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(re,{children:"Client Name"}),e.jsx(be,{value:O,onChange:gt=>B(gt.target.value)})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Property Address"}),e.jsx(be,{value:oe,onChange:gt=>me(gt.target.value),placeholder:"Optional"})]})]})]})}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Sections"}),e.jsx($,{variant:"outline",size:"sm",onClick:Is,children:"+ Add Section"})]}),e.jsx("div",{className:"space-y-3",children:_e.map((gt,rs)=>e.jsx(we,{className:Ot(!gt.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(Bp,{className:"h-4 w-4 text-muted-foreground cursor-grab"}),e.jsx("span",{className:"text-lg",children:gt.icon})]}),e.jsxs("div",{className:"flex-1 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(be,{value:gt.title,onChange:Ns=>Ft(rs,{title:Ns.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($,{variant:"ghost",size:"icon",onClick:()=>Ut(rs),children:gt.is_visible?e.jsx(ba,{className:"h-4 w-4"}):e.jsx(x0,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",onClick:()=>xs(rs),className:"text-destructive hover:text-destructive",children:e.jsx(Un,{className:"h-4 w-4"})})]})]}),e.jsx(be,{value:gt.description||"",onChange:Ns=>Ft(rs,{description:Ns.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(re,{className:"text-xs",children:"Video URL"}),e.jsx(be,{value:gt.video_url||"",onChange:Ns=>Ft(rs,{video_url:Ns.target.value}),placeholder:"Paste a YouTube or video URL...",className:"text-sm"})]}),e.jsx(TFn,{sectionTitle:gt.title,contactId:M==null?void 0:M.id,onVideoReady:Ns=>Ft(rs,{video_url:Ns})}),e.jsx(MFn,{sectionTitle:gt.title,contactId:M==null?void 0:M.id,onVideoReady:Ns=>Ft(rs,{video_url:Ns})}),e.jsx(BF,{userId:n==null?void 0:n.id,onSelect:Ns=>Ft(rs,{video_url:Ns})})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Image (optional — shown if no video is set)"}),gt.image_url?e.jsxs("div",{className:"relative mt-1 rounded-lg overflow-hidden border border-border bg-muted/30 group",children:[e.jsx("img",{src:gt.image_url,alt:"",className:"w-full max-h-40 object-cover"}),e.jsx($,{variant:"destructive",size:"icon",className:"absolute top-2 right-2 h-7 w-7 opacity-0 group-hover:opacity-100 transition-opacity",onClick:()=>Ft(rs,{image_url:""}),children:e.jsx(mr,{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:[Ee===rs?e.jsx(Jt,{className:"h-4 w-4 animate-spin text-muted-foreground"}):e.jsx(gb,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:Ee===rs?"Uploading...":"Click to upload an image"}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",disabled:Ee===rs,onChange:Ns=>{var Bs;const us=(Bs=Ns.target.files)==null?void 0:Bs[0];us&&ut(us,rs),Ns.target.value=""}})]})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Text (optional)"}),e.jsx(V2,{content:gt.text||"",onChange:Ns=>Ft(rs,{text:Ns}),placeholder:"Add supporting text...",minHeight:"80px",compact:!0})]})]})]})})},rs))})]}),e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsx(Yt,{className:"text-base",children:"Call to Action"})}),e.jsxs(De,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(re,{children:"CTA Type"}),e.jsxs(bs,{value:he,onValueChange:gt=>{Se(gt);const rs=Ebt.find(Ns=>Ns.value===gt);rs&&Ie(rs.label)},children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsx(vs,{children:Ebt.map(gt=>e.jsx(We,{value:gt.value,children:gt.label},gt.value))})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Button Label"}),e.jsx(be,{value:Te,onChange:gt=>Ie(gt.target.value)})]}),e.jsxs("div",{children:[e.jsxs(re,{children:["Link URL ",e.jsx("span",{className:"text-muted-foreground",children:"(optional — leave blank to show a lead capture form instead)"})]}),e.jsx(be,{value:Ue,onChange:gt=>Be(gt.target.value),placeholder:"https://calendly.com/..."}),!Ue&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Without a URL, clients will see a contact form — their info gets added to your contacts and you'll receive an email notification."})]})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[!g&&e.jsxs($,{variant:"outline",onClick:()=>p("template"),className:"gap-2",children:[e.jsx(Ia,{className:"h-4 w-4"}),"Back"]}),e.jsxs("div",{className:"flex gap-3 ml-auto",children:[e.jsx($,{variant:"outline",onClick:st,disabled:i.isPending||l.isPending,children:"Save Draft"}),e.jsxs($,{onClick:dt,disabled:o.isPending,className:"gap-2",children:[e.jsx(Wr,{className:"h-4 w-4"}),yt?"Update & Reshare":"Publish & Share"]})]})]})]}),m==="share"&&Oe&&e.jsxs("div",{className:"space-y-6",children:[e.jsx(we,{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(ma,{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 ",O||"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(be,{value:jt,readOnly:!0,className:"text-center font-mono text-sm"}),e.jsx($,{onClick:()=>{navigator.clipboard.writeText(jt),ae.success("Link copied!")},children:e.jsx(Da,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"flex gap-3 mt-6",children:[e.jsxs($,{variant:"outline",className:"gap-2",onClick:()=>{const gt=`Hi ${O||""}! I put together something for you — check it out: ${jt}`;navigator.clipboard.writeText(gt),ae.success("Message copied!")},children:[e.jsx(bo,{className:"h-4 w-4"}),"Copy Text Message"]}),e.jsxs($,{variant:"outline",className:"gap-2",onClick:()=>{c?h(!0):window.open(`mailto:${U||""}?subject=${encodeURIComponent(le)}&body=${encodeURIComponent(`Hi ${(M==null?void 0:M.first_name)||(O==null?void 0:O.split(" ")[0])||""}, I put together a personalized presentation for you: ${jt} Looking forward to connecting!`)}`)},children:[e.jsx(pn,{className:"h-4 w-4"}),"Send Email"]})]}),c&&e.jsx(W2,{open:u,onOpenChange:h,contact:M?{id:M.id,first_name:M.first_name,last_name:M.last_name,email:U||M.email||""}:U?{id:"",first_name:(O==null?void 0:O.split(" ")[0])||"",last_name:(O==null?void 0:O.split(" ").slice(1).join(" "))||"",email:U}:void 0,defaultSubject:le,defaultBody:`Hi ${(M==null?void 0:M.first_name)||(O==null?void 0:O.split(" ")[0])||""}, I put together a personalized presentation for you: ${jt} Looking forward to connecting!`,gmailEmail:d})]})}),e.jsxs("div",{className:"flex justify-between",children:[e.jsxs($,{variant:"outline",onClick:()=>p("builder"),children:[e.jsx(Ia,{className:"h-4 w-4 mr-2"}),"Edit Presentation"]}),e.jsx($,{onClick:()=>s("/mission-control/presentations"),children:"Done"})]})]})]})})},Mbt=({template:s,onSelect:t})=>e.jsx(we,{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(qe,{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($,{className:"w-full mt-4",size:"sm",onClick:()=>t(s),children:"Use Template"})]})}),PFn=()=>{var x;const{shareToken:s}=oo(),[t,n]=k.useState(null),[r,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:y,error:v}=await V.from("smart_presentations").select("*").eq("share_token",s).eq("status","published").single();if(v||!y){c(!0),a(!1);return}const{data:_}=await V.from("profiles").select("name, email, phone, avatar_url, title, brokerage_id").eq("id",y.owner_user_id).single();let j;if(_!=null&&_.brokerage_id){const{data:A}=await V.from("brokerages").select("name").eq("id",_.brokerage_id).single();j=(A==null?void 0:A.name)||void 0}let C=null;if(y.contact_id){const{data:A}=await V.from("innercircle_contacts").select("first_name, last_name, email, phone").eq("id",y.contact_id).single();C=A}n({...y,owner_name:_==null?void 0:_.name,owner_email:_==null?void 0:_.email,owner_phone:_==null?void 0:_.phone,owner_avatar:_==null?void 0:_.avatar_url,owner_title:(_==null?void 0:_.title)||void 0,brokerage_name:j,contact_name:C?[C.first_name,C.last_name].filter(Boolean).join(" "):void 0,contact_email:(C==null?void 0:C.email)||void 0,contact_phone:(C==null?void 0:C.phone)||void 0}),a(!1);try{await V.rpc("log_presentation_view",{p_presentation_id:y.id,p_section_index:0,p_cta_clicked:!1,p_ip_hash:null,p_user_agent:navigator.userAgent,p_referrer:document.referrer||null})}catch{}},u=async()=>{if(t){try{await V.rpc("log_presentation_view",{p_presentation_id:t.id,p_section_index:null,p_cta_clicked:!0,p_ip_hash:null,p_user_agent:navigator.userAgent,p_referrer:null})}catch{}t.cta_url&&window.open(t.cta_url,"_blank")}};if(r)return e.jsx("div",{className:"min-h-screen bg-white flex items-center justify-center",children:e.jsxs("div",{className:"space-y-4 w-full max-w-2xl px-4",children:[e.jsx(fn,{className:"h-12 w-3/4 mx-auto"}),e.jsx(fn,{className:"h-64 w-full"}),e.jsx(fn,{className:"h-8 w-1/2 mx-auto"})]})});if(o||!t)return e.jsx("div",{className:"min-h-screen bg-white flex items-center justify-center",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"text-2xl font-bold mb-2",children:"Presentation Not Found"}),e.jsx("p",{className:"text-gray-500",children:"This presentation may have been removed or is no longer available."})]})});const h=t.sections.filter(y=>y.is_visible!==!1),m=h[i],p=y=>{const v=y.match(/(?:youtube\.com\/watch\?v=|youtu\.be\/)([a-zA-Z0-9_-]+)/);if(v)return`https://www.youtube.com/embed/${v[1]}?rel=0`;if(y.includes("iframe.mediadelivery.net/play/")){const C=y.replace("/play/","/embed/"),A=C.includes("?")?"&":"?";return`${C}${A}responsive=true`}if(y.includes("iframe.mediadelivery.net")){if(y.match(/\/embed\/(\d+)\/([a-f0-9-]+)/)){const A=y.includes("?")?"&":"?";return`${y}${A}responsive=true`}return""}const _=y.match(/loom\.com\/share\/([a-zA-Z0-9]+)/);if(_)return`https://www.loom.com/embed/${_[1]}`;const j=y.match(/video\.bunnycdn\.com\/play\/(\d+)\/([a-f0-9-]+)/);return j?`https://iframe.mediadelivery.net/embed/${j[1]}/${j[2]}?responsive=true`:y},g=!!((x=t.cta_url)!=null&&x.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:[m!=null&&m.video_url&&p(m.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:p(m.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"})}):m!=null&&m.image_url?e.jsx("div",{className:"rounded-xl overflow-hidden shadow-lg",children:e.jsx("img",{src:m.image_url,alt:m.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:m==null?void 0:m.icon}),e.jsx("h3",{className:"text-xl font-semibold text-gray-800",children:m==null?void 0:m.title}),e.jsx("p",{className:"text-gray-500 mt-1 text-sm",children:m==null?void 0:m.description})]}),(m==null?void 0:m.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:m.text}})]}),e.jsx("div",{className:"md:col-span-2 space-y-3",children:h.map((y,v)=>e.jsx("button",{onClick:()=>l(v),className:Ot("w-full text-left p-4 rounded-xl border transition-all",i===v?"border-blue-500 bg-blue-50 shadow-sm":"border-gray-200 bg-white hover:border-blue-200 hover:bg-blue-50/50"),children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsxs("span",{className:"text-blue-600 font-bold text-sm mt-0.5",children:[String(v+1).padStart(2,"0"),"."]}),e.jsxs("div",{children:[e.jsx("span",{className:"mr-2",children:y.icon}),e.jsx("span",{className:"font-semibold text-gray-900",children:y.title}),e.jsx("p",{className:"text-xs text-gray-500 mt-0.5",children:y.description})]})]})},v))})]}),e.jsxs("div",{className:"mt-12 max-w-md mx-auto bg-white rounded-2xl border border-gray-200 shadow-sm p-6 text-center",children:[t.owner_avatar&&e.jsx("img",{src:t.owner_avatar,alt:t.owner_name||"Agent",className:"h-20 w-20 rounded-full object-cover mx-auto mb-3 border-2 border-gray-100"}),e.jsx("h3",{className:"text-lg font-bold text-gray-900",children:t.owner_name}),t.owner_title&&e.jsx("p",{className:"text-sm text-gray-500",children:t.owner_title}),t.brokerage_name&&e.jsx("p",{className:"text-sm text-gray-500",children:t.brokerage_name}),e.jsxs("div",{className:"mt-3 flex flex-col items-center gap-1 text-sm text-gray-600",children:[t.owner_phone&&e.jsx("a",{href:`tel:${t.owner_phone}`,className:"hover:text-blue-600 transition-colors",children:t.owner_phone}),t.owner_email&&e.jsx("a",{href:`mailto:${t.owner_email}`,className:"hover:text-blue-600 transition-colors",children:t.owner_email})]})]}),t.cta_label&&e.jsxs("div",{className:"text-center mt-8 py-8",children:[e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-4",children:"Ready to Get Started?"}),g?e.jsxs($,{size:"lg",onClick:u,className:"text-lg px-8 py-6 rounded-xl bg-blue-600 hover:bg-blue-700 text-white shadow-lg",children:[t.cta_label,e.jsx(Ir,{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(nEt,{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"})]})},XDe="__none__";function IFn({value:s,onChange:t}){const{data:n=[],isLoading:r}=rte(),a=BZe(),[i,l]=k.useState(!1),o=k.useMemo(()=>n.filter(h=>!h.is_starter),[n]),c=k.useMemo(()=>n.find(h=>h.is_starter&&/open house/i.test(h.name||"")),[n]),d=k.useMemo(()=>o.some(h=>/open house/i.test(h.name||"")),[o]),u=async()=>{if(c){l(!0);try{const h=await a.mutateAsync(c.id);h!=null&&h.id&&t(h.id),Ma({title:"Open House Follow-Up added",description:"The 6-email sequence is now in your library and selected here."})}catch(h){Ma({title:"Could not add campaign",description:(h==null?void 0:h.message)??"Please try again.",variant:"destructive"})}finally{l(!1)}}};return e.jsxs("div",{className:"space-y-2 rounded-lg border bg-muted/20 p-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsxs(re,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(sM,{className:"h-4 w-4 text-emerald-600"}),"Auto follow-up campaign"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Everyone who signs in with an email is automatically enrolled."})]}),s&&e.jsx(qe,{variant:"outline",className:"text-[10px] border-emerald-300 bg-emerald-500/10 text-emerald-700",children:"On"})]}),e.jsxs(bs,{value:s??XDe,onValueChange:h=>t(h===XDe?null:h),disabled:r,children:[e.jsx(ys,{children:e.jsx(_s,{placeholder:"No follow-up campaign"})}),e.jsxs(vs,{children:[e.jsx(We,{value:XDe,children:"No follow-up campaign"}),o.map(h=>e.jsxs(We,{value:h.id,children:[h.icon?`${h.icon} `:"",h.name,h.is_active?"":" (paused)"]},h.id))]})]}),c&&!d&&e.jsxs($,{type:"button",variant:"outline",size:"sm",className:"w-full gap-1.5 text-xs",onClick:u,disabled:i,children:[i?e.jsx(Jt,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(kn,{className:"h-3.5 w-3.5 text-primary"}),'Add the "Open House Follow-Up" starter (6 emails)']}),o.length===0&&!c&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"Create a campaign in Smart Drips first, then choose it here."})]})}function LFn({openHouseId:s,enableSurvey:t,onToggleSurvey:n}){const{data:r,isLoading:a}=Ajs(s),i=Pjs(),l=Ijs(),o=Ljs(),c=Rjs(),[d,u]=k.useState(""),[h,m]=k.useState("rating"),p=async v=>{n(v),v&&(!r||r.length===0)&&await c.mutateAsync(s)},g=async()=>{if(!d.trim())return;const v=(r==null?void 0:r.reduce((_,j)=>Math.max(_,j.sort_order),0))??0;await i.mutateAsync({open_house_id:s,question_type:h,question_text:d.trim(),sort_order:v+1}),u("")},x=async v=>{await l.mutateAsync({id:v.id,open_house_id:s,is_active:!v.is_active})},y=async v=>{await o.mutateAsync({id:v.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(re,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(lv,{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(On,{checked:t,onCheckedChange:p})]}),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(Jt,{className:"h-4 w-4 animate-spin text-muted-foreground"})}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"space-y-2",children:r==null?void 0:r.map(v=>e.jsxs("div",{className:"flex items-center gap-2 p-2 rounded-lg border border-border bg-muted/20",children:[e.jsx(Bp,{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:v.question_text}),e.jsx("p",{className:"text-xs text-muted-foreground capitalize",children:v.question_type.replace("_"," ")})]}),e.jsx(On,{checked:v.is_active,onCheckedChange:()=>x(v),className:"scale-75"}),e.jsx($,{variant:"ghost",size:"icon",className:"h-7 w-7 shrink-0 text-muted-foreground hover:text-destructive",onClick:()=>y(v),children:e.jsx(Un,{className:"h-3.5 w-3.5"})})]},v.id))}),e.jsxs("div",{className:"flex items-end gap-2",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx(re,{className:"text-xs text-muted-foreground",children:"Add Question"}),e.jsx(be,{value:d,onChange:v=>u(v.target.value),placeholder:"e.g. How did you hear about this listing?",className:"mt-1 h-9 text-sm",onKeyDown:v=>v.key==="Enter"&&g()})]}),e.jsxs(bs,{value:h,onValueChange:m,children:[e.jsx(ys,{className:"w-28 h-9 text-xs",children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"rating",children:"Rating"}),e.jsx(We,{value:"open_text",children:"Text"})]})]}),e.jsx($,{size:"sm",variant:"outline",onClick:g,disabled:!d.trim()||i.isPending,className:"h-9",children:e.jsx(nn,{className:"h-3.5 w-3.5"})})]})]})})]})}function RFn({openHouseId:s}){const{user:t}=ks(),{data:n=[],isLoading:r}=zjs(s),a=$js(),[i,l]=k.useState(""),[o,c]=k.useState(!1),d=async()=>{const u=i.trim();if(u){c(!0);try{await a.mutateAsync({open_house_id:s,name:u,sort_order:n.length}),l("")}finally{c(!1)}}};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(re,{className:"text-sm font-medium",children:"Rooms"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Add rooms and upload photos or videos. Visitors swipe through them on mobile and tab through them on desktop."})]}),r?e.jsxs("div",{className:"py-6 text-center text-sm text-muted-foreground",children:[e.jsx(Jt,{className:"h-4 w-4 animate-spin inline"})," Loading…"]}):n.length===0?e.jsx("p",{className:"text-xs text-muted-foreground italic",children:"No rooms yet — add your first below."}):e.jsx("div",{className:"space-y-3",children:n.map((u,h)=>e.jsx(DFn,{room:u,index:h,total:n.length,userId:(t==null?void 0:t.id)||"",openHouseId:s},u.id))}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsx(be,{value:i,onChange:u=>l(u.target.value),placeholder:"e.g. Kitchen, Primary Bedroom, Backyard…",onKeyDown:u=>{u.key==="Enter"&&(u.preventDefault(),d())}}),e.jsx($,{onClick:d,disabled:!i.trim()||o,size:"sm",children:o?e.jsx(Jt,{className:"h-4 w-4 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(nn,{className:"h-4 w-4 mr-1"})," Add"]})})]})]})}function DFn({room:s,index:t,total:n,userId:r,openHouseId:a}){const i=Ujs(),l=qjs(),o=Vjs(),c=Hjs(),d=k.useRef(null),[u,h]=k.useState(!0),[m,p]=k.useState(s.name),[g,x]=k.useState(s.description||""),[y,v]=k.useState(!1),_=k.useMemo(()=>s.media.filter(R=>R.kind==="video"&&R.agent_video_id).map(R=>R.agent_video_id),[s.media]),{data:j={}}=pt({queryKey:["room-video-statuses",s.id,_.join(",")],enabled:_.length>0,queryFn:async()=>{const{data:R,error:O}=await V.from("agent_videos").select("id, status, bunny_video_id, thumbnail_url, preview_url").in("id",_);if(O)throw O;const B=R||[],U=B.filter(H=>H.status==="processing"&&H.bunny_video_id);await Promise.all(U.map(async H=>{try{const{data:Y}=await V.functions.invoke("bunny-upload",{body:{action:"status",videoId:H.bunny_video_id,isAgentVideo:!0}});Y&&Y.status===4&&(await V.from("agent_videos").update({status:"ready",playback_url:Y.directPlayUrl,thumbnail_url:Y.thumbnailUrl,preview_url:Y.previewUrl,duration_seconds:Y.length||void 0,updated_at:new Date().toISOString()}).eq("id",H.id),H.status="ready",H.thumbnail_url=Y.thumbnailUrl,H.preview_url=Y.previewUrl)}catch{}}));const G={};return B.forEach(H=>{G[H.id]={status:H.status,thumbnail_url:H.thumbnail_url,preview_url:H.preview_url}}),G},refetchInterval:R=>{const O=R.state.data;return O?Object.values(O).some(B=>B.status!=="ready"&&B.status!=="failed")?5e3:!1:5e3}}),C=()=>{m.trim()&&m!==s.name&&i.mutate({id:s.id,open_house_id:a,name:m.trim()})},A=()=>{g!==(s.description||"")&&i.mutate({id:s.id,open_house_id:a,description:g.trim()||null})},M=async()=>{await io(`Delete "${s.name}" and all its media?`)&&l.mutate({id:s.id,open_house_id:a})},I=R=>{i.mutate({id:s.id,open_house_id:a,sort_order:t+R})},P=async R=>{const O=Array.from(R.target.files||[]);if(!(!O.length||!r)){v(!0);try{for(const B of O){const U=B.type.startsWith("video/"),G=U?500*1024*1024:15*1024*1024;if(B.size>G){Ma({title:`${B.name} is too large`,description:U?"Videos must be under 500MB":"Photos must be under 15MB",variant:"destructive"});continue}if(U){try{const oe=`${s.name} – ${B.name.replace(/\.[^/.]+$/,"")}`,{data:me,error:Q}=await V.functions.invoke("bunny-upload",{body:{action:"create",title:oe,isAgentVideo:!0}});if(Q||!me)throw new Error((Q==null?void 0:Q.message)||"Could not start upload");const{videoId:te,libraryId:le}=me,{data:fe,error:_e}=await V.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:te,isAgentVideo:!0}});if(_e||!fe)throw new Error((_e==null?void 0:_e.message)||"Could not get upload URL");await new Promise((Ie,Ue)=>{const Be=new XMLHttpRequest;Be.addEventListener("load",()=>{Be.status>=200&&Be.status<300?Ie():Ue(new Error(`Upload failed (${Be.status})`))}),Be.addEventListener("error",()=>Ue(new Error("Upload failed"))),Be.open("PUT",fe.uploadUrl),Be.setRequestHeader("AccessKey",fe.apiKey),Be.send(B)});const ve=`https://iframe.mediadelivery.net/embed/${le}/${te}`,he=B.size/(1024*1024),{data:Se,error:Te}=await V.from("agent_videos").insert({owner_user_id:r,bunny_video_id:te,playback_url:ve,file_size_mb:he,title:oe,status:"processing",touch_type:"open_house_tour",category:"open_house",page_template:"default"}).select().single();if(Te)throw Te;await o.mutateAsync({open_house_id:a,room_id:s.id,kind:"video",url:ve,sort_order:s.media.length,agent_video_id:Se.id}),Ma({title:"Video uploaded",description:"Processing in the background — it’ll appear in your Video Library too."})}catch(oe){Ma({title:"Video upload failed",description:(oe==null?void 0:oe.message)||"Try again",variant:"destructive"})}continue}const H=B.name.split(".").pop()||"jpg",Y=`${r}/${a}/rooms/${s.id}-${Date.now()}-${Math.random().toString(36).slice(2,7)}.${H}`,{error:se}=await V.storage.from("open-house-tour-media").upload(Y,B,{upsert:!1,contentType:B.type});if(se){Ma({title:"Upload failed",description:se.message,variant:"destructive"});continue}const{data:ee}=V.storage.from("open-house-tour-media").getPublicUrl(Y);await o.mutateAsync({open_house_id:a,room_id:s.id,kind:"photo",url:ee.publicUrl,sort_order:s.media.length})}}finally{v(!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(Bp,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("button",{onClick:()=>h(R=>!R),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($,{size:"icon",variant:"ghost",className:"h-7 w-7",onClick:()=>I(-1),disabled:t===0,children:e.jsx(Ny,{className:"h-4 w-4"})}),e.jsx($,{size:"icon",variant:"ghost",className:"h-7 w-7",onClick:()=>I(1),disabled:t===n-1,children:e.jsx(Go,{className:"h-4 w-4"})}),e.jsx($,{size:"icon",variant:"ghost",className:"h-7 w-7 text-destructive",onClick:M,children:e.jsx(Un,{className:"h-4 w-4"})})]}),u&&e.jsxs("div",{className:"p-3 space-y-3",children:[e.jsx(be,{value:m,onChange:R=>p(R.target.value),onBlur:C,placeholder:"Room name",className:"h-9"}),e.jsx(Ls,{value:g,onChange:R=>x(R.target.value),onBlur:A,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(R=>{const O=R.agent_video_id?j[R.agent_video_id]:void 0,B=O==null?void 0:O.status,U=R.kind==="video"&&B&&B!=="ready"&&B!=="failed",G=R.kind==="video"&&B==="failed",H=(O==null?void 0:O.thumbnail_url)||(O==null?void 0:O.preview_url);return e.jsxs("div",{className:"relative aspect-square rounded-md overflow-hidden bg-muted group",children:[R.kind==="video"?e.jsxs(e.Fragment,{children:[H?e.jsx("img",{src:H,alt:"",className:"w-full h-full object-cover"}):/iframe\.mediadelivery\.net\/embed\//.test(R.url)?e.jsx("div",{className:"w-full h-full bg-slate-800"}):e.jsx("video",{src:R.url,className:"w-full h-full object-cover"}),!U&&!G&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/30 pointer-events-none",children:e.jsx(ia,{className:"h-6 w-6 text-white"})}),U&&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(Jt,{className:"h-5 w-5 animate-spin"}),e.jsx("span",{className:"text-[10px] font-medium uppercase tracking-wide",children:"Processing"})]}),G&&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:R.url,alt:"",className:"w-full h-full object-cover"}),e.jsx("button",{onClick:()=>c.mutate({id:R.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(mr,{className:"h-3.5 w-3.5"})})]},R.id)})}),e.jsx("input",{ref:d,type:"file",accept:"image/*,video/*",multiple:!0,onChange:P,className:"hidden"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{variant:"outline",size:"sm",onClick:()=>{var R;return(R=d.current)==null?void 0:R.click()},disabled:y,className:"flex-1",children:y?e.jsx(Jt,{className:"h-4 w-4 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(gi,{className:"h-4 w-4 mr-2"})," Upload"]})}),e.jsx(BF,{userId:r,triggerLabel:"From Video Library",triggerClassName:"gap-1.5 flex-1 justify-center",onSelect:()=>{},onSelectVideo:async R=>{try{await o.mutateAsync({open_house_id:a,room_id:s.id,kind:"video",url:R.playback_url||"",sort_order:s.media.length,agent_video_id:R.id}),Ma({title:"Video added to room"})}catch(O){Ma({title:"Failed to add video",description:O==null?void 0:O.message,variant:"destructive"})}}})]})]})]})}function OFn({open:s,onOpenChange:t,openHouse:n}){const r=aEt(),{user:a}=ks(),i=k.useRef(null),l=k.useRef(null),o=k.useRef(null),c=n.kind==="virtual",[d,u]=k.useState(n.auto_forward_to_card??!1),[h,m]=k.useState(n.disclosure_pdf_url??""),[p,g]=k.useState(n.enable_survey??!1),[x,y]=k.useState(n.ask_visitor_intent??!0),[v,_]=k.useState(n.ask_visitor_address??!1),[j,C]=k.useState(n.photo_url??""),[A,M]=k.useState(!1),[I,P]=k.useState(!1),[R,O]=k.useState(!1),[B,U]=k.useState(n.hero_video_url??""),[G,H]=k.useState(!1),[Y,se]=k.useState(n.price!=null?String(n.price):""),[ee,oe]=k.useState(n.beds!=null?String(n.beds):""),[me,Q]=k.useState(n.baths!=null?String(n.baths):""),[te,le]=k.useState(n.sqft!=null?String(n.sqft):""),[fe,_e]=k.useState(n.enable_question??!0),[ve,he]=k.useState(n.enable_showing??!0),[Se,Te]=k.useState(n.enable_disclosures??!0),[Ie,Ue]=k.useState(n.enable_offer??!0),[Be,je]=k.useState(n.brand_color_override??""),[Ye,Ee]=k.useState(n.property_description??""),[Re,ke]=k.useState(n.drip_campaign_id??null),Fe=async nt=>{var Ut;const et=(Ut=nt.target.files)==null?void 0:Ut[0];if(!et||!a)return;if(et.size>200*1024*1024){Ma({title:"Video must be under 200MB",variant:"destructive"});return}if(!et.type.startsWith("video/")){Ma({title:"Please upload a video file",variant:"destructive"});return}H(!0);const at=et.name.split(".").pop()||"mp4",wt=`${a.id}/${n.id}/hero-${Date.now()}.${at}`,{error:rt}=await V.storage.from("open-house-tour-media").upload(wt,et,{upsert:!0,contentType:et.type});if(rt){Ma({title:"Upload failed",description:rt.message,variant:"destructive"}),H(!1);return}const{data:Ft}=V.storage.from("open-house-tour-media").getPublicUrl(wt);U(Ft.publicUrl),H(!1),Ma({title:"Video uploaded!"})},Oe=async nt=>{var Ut;const et=(Ut=nt.target.files)==null?void 0:Ut[0];if(!et||!a)return;if(et.size>10*1024*1024){Ma({title:"Image must be under 10MB",variant:"destructive"});return}if(!et.type.startsWith("image/")){Ma({title:"Please upload an image file",variant:"destructive"});return}P(!0);const at=et.name.split(".").pop()||"jpg",wt=`${a.id}/${n.id}-${Date.now()}.${at}`,{error:rt}=await V.storage.from("open-house-photos").upload(wt,et,{upsert:!0});if(rt){Ma({title:"Upload failed",description:rt.message,variant:"destructive"}),P(!1);return}const{data:Ft}=V.storage.from("open-house-photos").getPublicUrl(wt);C(Ft.publicUrl),P(!1),Ma({title:"Photo updated!"})},Ge=()=>{C(""),l.current&&(l.current.value="")},yt=async nt=>{var Ft;const et=(Ft=nt.target.files)==null?void 0:Ft[0];if(!et||!a)return;if(et.size>20*1024*1024){Ma({title:"File must be under 20MB",variant:"destructive"});return}if(et.type!=="application/pdf"){Ma({title:"Only PDF files are accepted",variant:"destructive"});return}M(!0);const at=`${a.id}/disclosures/${n.id}-${Date.now()}.pdf`,{error:wt}=await V.storage.from("open-house-photos").upload(at,et,{upsert:!0});if(wt){Ma({title:"Upload failed",description:wt.message,variant:"destructive"}),M(!1);return}const{data:rt}=V.storage.from("open-house-photos").getPublicUrl(at);m(rt.publicUrl),M(!1),Ma({title:"PDF uploaded!"})},tt=()=>{m(""),i.current&&(i.current.value="")},ut=async()=>{O(!0);try{const nt={id:n.id,auto_forward_to_card:d,disclosure_pdf_url:h||null,enable_survey:p,ask_visitor_intent:x,ask_visitor_address:v,photo_url:j||null,drip_campaign_id:Re};c&&(nt.hero_video_url=B||null,nt.price=Y.trim()?Number(Y):null,nt.beds=ee.trim()?parseInt(ee,10):null,nt.baths=me.trim()?Number(me):null,nt.sqft=te.trim()?parseInt(te,10):null,nt.enable_question=fe,nt.enable_showing=ve,nt.enable_disclosures=Se,nt.enable_offer=Ie,nt.brand_color_override=Be.trim()||null,nt.property_description=Ye.trim()||null),await r.mutateAsync(nt),Ma({title:"Settings saved!"}),t(!1)}catch{Ma({title:"Failed to save",variant:"destructive"})}finally{O(!1)}};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"sm:max-w-md max-h-[85vh] overflow-y-auto",children:[e.jsxs(Vs,{children:[e.jsx($s,{children:c?"Virtual Open House Settings":"Guest Book Settings"}),e.jsx(Cr,{className:"truncate",children:n.property_address})]}),e.jsxs("div",{className:"space-y-6 pt-2",children:[c&&e.jsxs(e.Fragment,{children:[n.tour_mode==="single_video"?e.jsxs("div",{className:"space-y-2",children:[e.jsxs(re,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(ia,{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:Fe,className:"hidden"}),B?e.jsxs("div",{className:"relative rounded-lg overflow-hidden border border-border bg-black",children:[e.jsx("video",{src:B,controls:!0,className:"w-full max-h-48"}),e.jsxs("div",{className:"absolute top-2 right-2 flex gap-2",children:[e.jsx($,{variant:"secondary",size:"sm",className:"h-8",onClick:()=>{var nt;return(nt=o.current)==null?void 0:nt.click()},disabled:G,children:G?e.jsx(Jt,{className:"h-3.5 w-3.5 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(gi,{className:"h-3.5 w-3.5 mr-1"}),"Replace"]})}),e.jsx($,{variant:"secondary",size:"icon",className:"h-8 w-8",onClick:()=>U(""),children:e.jsx(mr,{className:"h-4 w-4"})})]})]}):e.jsx("button",{type:"button",onClick:()=>{var nt;return(nt=o.current)==null?void 0:nt.click()},disabled:G,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:G?e.jsx(Jt,{className:"h-5 w-5 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(ia,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs",children:"Upload tour video (max 200MB)"})]})})]}):e.jsx(RFn,{openHouseId:n.id}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{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(re,{className:"text-xs text-muted-foreground",children:"Price (USD)"}),e.jsx(be,{type:"number",value:Y,onChange:nt=>se(nt.target.value),placeholder:"650000",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs text-muted-foreground",children:"Sq Ft"}),e.jsx(be,{type:"number",value:te,onChange:nt=>le(nt.target.value),placeholder:"2200",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs text-muted-foreground",children:"Beds"}),e.jsx(be,{type:"number",value:ee,onChange:nt=>oe(nt.target.value),placeholder:"3",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs text-muted-foreground",children:"Baths"}),e.jsx(be,{type:"number",step:"0.5",value:me,onChange:nt=>Q(nt.target.value),placeholder:"2.5",className:"mt-1"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{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(Ls,{value:Ye,onChange:nt=>Ee(nt.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(re,{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(On,{checked:fe,onCheckedChange:_e})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm",children:"Schedule a private showing"}),e.jsx(On,{checked:ve,onCheckedChange:he})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm",children:"Request seller disclosures"}),e.jsx(On,{checked:Se,onCheckedChange:Te})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm",children:"Make an offer / express interest"}),e.jsx(On,{checked:Ie,onCheckedChange:Ue})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-sm font-medium",children:"Brand Accent Color"}),e.jsx("p",{className:"text-xs text-muted-foreground -mt-1",children:"Used for highlights and CTA buttons on your virtual tour page. Leave blank to use the default."}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"color",value:Be||"#0f172a",onChange:nt=>je(nt.target.value),className:"h-10 w-14 rounded-md border border-input cursor-pointer bg-transparent"}),e.jsx(be,{value:Be,onChange:nt=>je(nt.target.value),placeholder:"#0f172a",className:"flex-1 font-mono text-sm"}),Be&&e.jsx($,{variant:"ghost",size:"sm",onClick:()=>je(""),children:"Reset"})]}),e.jsx("div",{className:"flex flex-wrap gap-1.5 pt-1",children:["#0f172a","#406E71","#2a4c64","#7c2d12","#1e3a8a","#581c87","#9f1239","#065f46"].map(nt=>e.jsx("button",{type:"button",onClick:()=>je(nt),className:"w-6 h-6 rounded-full border border-border hover:scale-110 transition-transform",style:{backgroundColor:nt},"aria-label":nt},nt))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{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:Oe,className:"hidden"}),j?e.jsxs("div",{className:"relative rounded-lg overflow-hidden border border-border",children:[e.jsx("img",{src:j,alt:"Property",className:"w-full h-40 object-cover"}),e.jsxs("div",{className:"absolute top-2 right-2 flex gap-2",children:[e.jsxs($,{variant:"secondary",size:"sm",className:"h-8",onClick:()=>{var nt;return(nt=l.current)==null?void 0:nt.click()},disabled:I,children:[I?e.jsx(Jt,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(gi,{className:"h-3.5 w-3.5 mr-1"}),I?"":"Replace"]}),e.jsx($,{variant:"secondary",size:"icon",className:"h-8 w-8",onClick:Ge,children:e.jsx(mr,{className:"h-4 w-4"})})]})]}):e.jsx("button",{type:"button",onClick:()=>{var nt;return(nt=l.current)==null?void 0:nt.click()},disabled:I,className:"w-full h-32 rounded-xl border-2 border-dashed border-muted-foreground/25 hover:border-muted-foreground/50 flex flex-col items-center justify-center gap-2 text-muted-foreground hover:text-foreground transition-colors",children:I?e.jsx(Jt,{className:"h-5 w-5 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(zc,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs",children:"Upload property photo (max 10MB)"})]})})]}),e.jsx(IFn,{value:Re,onChange:ke}),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(re,{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(On,{checked:d,onCheckedChange:u})]})}),!d&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{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:yt,className:"hidden"}),h?e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg border border-border bg-muted/30",children:[e.jsx(ea,{className:"h-5 w-5 text-primary shrink-0"}),e.jsx("span",{className:"text-sm truncate flex-1",children:"Disclosure PDF uploaded"}),e.jsx($,{variant:"ghost",size:"icon",className:"h-7 w-7 shrink-0",onClick:tt,children:e.jsx(mr,{className:"h-4 w-4"})})]}):e.jsx("button",{type:"button",onClick:()=>{var nt;return(nt=i.current)==null?void 0:nt.click()},disabled:A,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:A?e.jsx(Jt,{className:"h-5 w-5 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(gi,{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(re,{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(On,{checked:x,onCheckedChange:y})]})}),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(re,{className:"text-sm font-medium",children:"Ask for visitor's home address"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Adds an optional address field to the sign-in form — helpful for follow-up and market reports."})]}),e.jsx(On,{checked:v,onCheckedChange:_})]})}),e.jsx(LFn,{openHouseId:n.id,enableSurvey:p,onToggleSurvey:g}),e.jsx($,{onClick:ut,disabled:R,className:"w-full",children:R?"Saving...":"Save Settings"})]})]})})}const XVt={5:"Excellent",4:"Good",3:"Neutral",2:"Bad",1:"Very Bad"};function FFn({question:s,responses:t}){const n=t.filter(l=>l.question_id===s.id&&l.rating_value!=null),r=n.length;if(r===0)return null;const a=n.reduce((l,o)=>l+(o.rating_value||0),0)/r,i=[5,4,3,2,1].map(l=>({val:l,count:n.filter(o=>o.rating_value===l).length,pct:Math.round(n.filter(o=>o.rating_value===l).length/r*100)}));return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm font-medium",children:s.question_text}),e.jsxs("span",{className:"text-sm text-muted-foreground",children:[a.toFixed(1)," avg (",r," responses)"]})]}),e.jsx("div",{className:"space-y-1",children:i.map(l=>e.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[e.jsx("span",{className:"w-16 text-muted-foreground text-right",children:XVt[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 zFn({openHouseId:s}){const{data:t,isLoading:n}=Mjs(s),{data:r}=rEt(s),a=k.useMemo(()=>{const h={};return r==null||r.forEach(m=>{h[m.id]=m}),h},[r]);if(n||!t)return null;const{questions:i,responses:l}=t;if(i.length===0)return null;const o=i.filter(h=>h.question_type==="rating"),c=i.filter(h=>h.question_type!=="rating"),d=[...new Set(l.map(h=>h.visitor_id))],u=d.length;return u===0?e.jsxs(we,{children:[e.jsx(Vt,{className:"pb-3",children:e.jsxs(Yt,{className:"text-base flex items-center gap-2",children:[e.jsx(lv,{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(we,{children:[e.jsx(Vt,{className:"pb-3",children:e.jsxs(Yt,{className:"text-base flex items-center gap-2",children:[e.jsx(lv,{className:"h-4 w-4"}),"Survey Results",e.jsxs("span",{className:"text-xs font-normal text-muted-foreground ml-auto",children:[u," respondent",u!==1?"s":""]})]})}),e.jsx(De,{children:e.jsxs(ya,{defaultValue:"summary",children:[e.jsxs(va,{className:"mb-4",children:[e.jsxs(is,{value:"summary",className:"text-xs gap-1",children:[e.jsx(Ul,{className:"h-3.5 w-3.5"})," Summary"]}),e.jsxs(is,{value:"individual",className:"text-xs gap-1",children:[e.jsx(el,{className:"h-3.5 w-3.5"})," Per Visitor"]})]}),e.jsxs(cs,{value:"summary",className:"space-y-6",children:[o.map(h=>e.jsx(FFn,{question:h,responses:l},h.id)),c.map(h=>{const m=l.filter(p=>p.question_id===h.id&&p.text_value);return m.length===0?null:e.jsxs("div",{className:"space-y-2",children:[e.jsx("span",{className:"text-sm font-medium",children:h.question_text}),e.jsx("div",{className:"space-y-1.5 max-h-40 overflow-y-auto",children:m.map(p=>{const g=a[p.visitor_id];return e.jsxs("div",{className:"text-sm p-2 bg-muted/30 rounded-lg",children:[e.jsxs("span",{className:"text-muted-foreground text-xs",children:[g?`${g.first_name} ${g.last_name||""}`.trim():"Visitor",":"]}),e.jsx("p",{className:"mt-0.5",children:p.text_value})]},p.id)})})]},h.id)})]}),e.jsx(cs,{value:"individual",className:"space-y-4",children:d.map(h=>{const m=a[h],p=l.filter(g=>g.visitor_id===h);return e.jsxs("div",{className:"p-3 rounded-lg border border-border space-y-2",children:[e.jsxs("p",{className:"text-sm font-medium",children:[m?`${m.first_name} ${m.last_name||""}`.trim():"Unknown Visitor",(m==null?void 0:m.email)&&e.jsx("span",{className:"text-xs text-muted-foreground ml-2",children:m.email})]}),e.jsx("div",{className:"space-y-1",children:p.map(g=>{const x=i.find(y=>y.id===g.question_id);return x?e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:x.question_text}),e.jsx("span",{className:"font-medium",children:g.rating_value!=null?XVt[g.rating_value]||g.rating_value:g.text_value})]},g.id):null})})]},h)})})]})})]})}const BFn={question:{label:"Question",icon:bo,color:"text-sky-700 dark:text-sky-300",bg:"bg-sky-100 dark:bg-sky-950"},showing:{label:"Showing",icon:ha,color:"text-orange-700 dark:text-orange-300",bg:"bg-orange-100 dark:bg-orange-950"},disclosure:{label:"Disclosures",icon:ea,color:"text-indigo-700 dark:text-indigo-300",bg:"bg-indigo-100 dark:bg-indigo-950"},offer:{label:"Hot Lead",icon:Su,color:"text-emerald-700 dark:text-emerald-300",bg:"bg-emerald-100 dark:bg-emerald-950"}},Pbt={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 $Fn({openHouseId:s}){const{data:t=[],isLoading:n}=Gjs(s),r=Wjs(),[a,i]=k.useState(null),[l,o]=k.useState("all"),c=t.filter(h=>l==="all"?!0:l==="new"?h.status==="new":h.action_type===l),d={all:t.length,new:t.filter(h=>h.status==="new").length,question:t.filter(h=>h.action_type==="question").length,showing:t.filter(h=>h.action_type==="showing").length,disclosure:t.filter(h=>h.action_type==="disclosure").length,offer:t.filter(h=>h.action_type==="offer").length},u=(h,m)=>{r.mutate({id:h,status:m,open_house_id:s})};return n?e.jsx("div",{className:"text-sm text-muted-foreground py-4",children:"Loading leads…"}):e.jsxs("div",{className:"border rounded-lg overflow-hidden",children:[e.jsxs("div",{className:"px-4 py-3 bg-muted/40 border-b flex items-center justify-between flex-wrap gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold",children:[e.jsx(HT,{className:"h-4 w-4"}),"Virtual Open House Leads",e.jsx(qe,{variant:"secondary",className:"ml-1",children:d.all}),d.new>0&&e.jsxs(qe,{className:"bg-emerald-600 hover:bg-emerald-600",children:[d.new," new"]})]}),e.jsx("div",{className:"flex items-center gap-1 flex-wrap",children:[["all","All",d.all],["new","New",d.new],["offer","Hot",d.offer],["showing","Showings",d.showing],["question","Questions",d.question],["disclosure","Docs",d.disclosure]].map(([h,m,p])=>e.jsxs("button",{onClick:()=>o(h),className:`text-xs px-2.5 py-1 rounded-full transition-colors ${l===h?"bg-foreground text-background":"bg-background hover:bg-muted text-muted-foreground"}`,children:[m," ",e.jsx("span",{className:"opacity-60",children:p})]},h))})]}),c.length===0?e.jsx("div",{className:"px-4 py-10 text-center text-sm text-muted-foreground",children:t.length===0?"No leads yet. Share your virtual open house link to start capturing leads.":"No leads match this filter."}):e.jsx("ul",{className:"divide-y",children:c.map(h=>{const m=BFn[h.action_type],p=m.icon,g=h.payload||{},x=a===h.id,y=h.status==="contacted",v=h.status==="archived";return e.jsxs("li",{className:`transition-colors ${v?"opacity-60":""} ${h.status==="new"?"bg-emerald-50/40 dark:bg-emerald-950/10":""}`,children:[e.jsxs("button",{onClick:()=>i(x?null:h.id),className:"w-full text-left px-4 py-3 flex items-start gap-3 hover:bg-muted/40 transition-colors",children:[e.jsx("div",{className:`w-9 h-9 rounded-lg flex items-center justify-center shrink-0 ${m.bg}`,children:e.jsx(p,{className:`h-4 w-4 ${m.color}`})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"font-semibold text-sm truncate",children:g.visitor_name||"Visitor"}),e.jsx(qe,{variant:"outline",className:`text-[10px] ${m.color}`,children:m.label}),h.status==="new"&&e.jsx("span",{className:"text-[10px] font-bold text-emerald-600 uppercase tracking-wide",children:"New"}),y&&e.jsxs("span",{className:"text-[10px] font-bold text-muted-foreground uppercase tracking-wide flex items-center gap-1",children:[e.jsx(Gr,{className:"h-3 w-3"}),"Contacted"]})]}),g.message&&e.jsxs("p",{className:"text-sm text-muted-foreground line-clamp-1 mt-0.5 italic",children:['"',g.message,'"']}),e.jsxs("div",{className:"flex items-center gap-3 text-[11px] text-muted-foreground mt-1",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(sa,{className:"h-3 w-3"}),Ys(new Date(h.created_at),"MMM d, h:mm a")]}),g.email&&e.jsxs("span",{className:"flex items-center gap-1 truncate",children:[e.jsx(pn,{className:"h-3 w-3"}),g.email]}),g.phone&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ka,{className:"h-3 w-3"}),g.phone]})]})]}),x?e.jsx(Go,{className:"h-4 w-4 mt-1 text-muted-foreground"}):e.jsx(fi,{className:"h-4 w-4 mt-1 text-muted-foreground"})]}),x&&e.jsxs("div",{className:"px-4 pb-4 pl-16 space-y-3",children:[g.message&&e.jsxs("div",{className:"bg-muted/40 rounded-md p-3 text-sm border-l-2 border-foreground/30",children:['"',g.message,'"']}),Object.keys(Pbt).some(_=>g[_]!=null&&g[_]!==""&&!(Array.isArray(g[_])&&g[_].length===0))&&e.jsx("div",{className:"grid grid-cols-2 gap-x-4 gap-y-1.5 text-sm",children:Object.entries(Pbt).map(([_,j])=>{const C=g[_];return C==null||C===""||Array.isArray(C)&&C.length===0?null:e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] text-muted-foreground uppercase tracking-wide",children:j}),e.jsx("div",{className:"font-medium",children:Array.isArray(C)?C.join(", "):String(C)})]},_)})}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 pt-1",children:[g.email&&e.jsx("a",{href:`mailto:${g.email}?subject=${encodeURIComponent("Re: your open house inquiry")}`,children:e.jsxs($,{size:"sm",variant:"default",className:"gap-1.5",children:[e.jsx(pn,{className:"h-3.5 w-3.5"}),"Reply"]})}),g.phone&&e.jsx("a",{href:`tel:${String(g.phone).replace(/[^0-9+]/g,"")}`,children:e.jsxs($,{size:"sm",variant:"outline",className:"gap-1.5",children:[e.jsx(ka,{className:"h-3.5 w-3.5"}),"Call"]})}),!y&&e.jsxs($,{size:"sm",variant:"outline",className:"gap-1.5",onClick:()=>u(h.id,"contacted"),children:[e.jsx(Gr,{className:"h-3.5 w-3.5"}),"Mark contacted"]}),v?e.jsx($,{size:"sm",variant:"ghost",className:"gap-1.5 text-muted-foreground",onClick:()=>u(h.id,"new"),children:"Restore"}):e.jsxs($,{size:"sm",variant:"ghost",className:"gap-1.5 text-muted-foreground",onClick:()=>u(h.id,"archived"),children:[e.jsx(kf,{className:"h-3.5 w-3.5"}),"Archive"]})]})]})]},h.id)})})]})}function UFn({open:s,onOpenChange:t,openHouse:n}){const{isGmailConnected:r,gmailEmail:a}=dx(),i=ai(),[l,o]=k.useState([]),[c,d]=k.useState([]),[u,h]=k.useState(!1),[m,p]=k.useState(!1),[g,x]=k.useState(""),[y,v]=k.useState(""),[_,j]=k.useState(""),[C,A]=k.useState(!1),[M,I]=k.useState(!1),[P,R]=k.useState(!1),O=`https://guestbook.relevelup.com/${n.slug}`;k.useEffect(()=>{s&&(v(`Take a virtual tour of ${n.property_address}`),j(`I wanted to share an immersive virtual tour of ${n.property_address} with you. Step inside from anywhere — explore every room at your own pace.`),d([]),x(""),A(r),l.length===0&&B())},[s,n.id,r]);const B=async()=>{if(i){p(!0);try{const{data:me,error:Q}=await V.from("innercircle_contacts").select("id, first_name, last_name, email").eq("owner_user_id",i).not("email","is",null).neq("email","").order("first_name",{ascending:!0}).limit(1e3);if(Q)throw Q;o(me||[])}catch{ae.error("Failed to load contacts")}finally{p(!1)}}},U=me=>`${me.first_name} ${me.last_name||""}`.trim(),G=me=>{d(Q=>Q.find(te=>te.id===me.id)?Q.filter(te=>te.id!==me.id):[...Q,me])},H=()=>{const me=g.trim();if(!me)return;if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(me)){ae.error("Invalid email");return}d(te=>[...te,{id:`manual-${me}`,first_name:me.split("@")[0],last_name:null,email:me}]),x("")},Y=k.useMemo(()=>c.filter(me=>!!me.email).map(me=>({email:me.email,name:U(me)})),[c]),se=me=>{const Q=me?`Hi ${me},`:"Hi there,",te=_.split(/\n\n+/).map(le=>`

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

`).join("");return`

${Q}

${te}

▶ Start Virtual Tour

Or copy this link: ${O}

`},ee=async()=>{var me;if(Y.length===0){ae.error("Add at least one recipient");return}I(!0);try{if(C&&r){let Q=0;for(const te of Y){const{data:le,error:fe}=await V.functions.invoke("gmail-send",{body:{to:te.email,subject:y,body:se((me=te.name)==null?void 0:me.split(" ")[0])}});!fe&&(le!=null&&le.success)?Q+=1:console.warn("gmail-send error",fe,le)}if(Q===0)throw new Error("Gmail send failed");ae.success(`Sent to ${Q} of ${Y.length} via Gmail`)}else{const{data:Q,error:te}=await V.functions.invoke("send-virtual-tour-invite",{body:{openHouseId:n.id,recipients:Y,subject:y,personalMessage:_}});if(te)throw te;if(!(Q!=null&&Q.success))throw new Error((Q==null?void 0:Q.error)||"Send failed");ae.success(`Sent to ${Q.sent} of ${Q.total} recipient${Q.total===1?"":"s"}`)}t(!1)}catch(Q){ae.error((Q==null?void 0:Q.message)||"Failed to send")}finally{I(!1)}},oe=async()=>{await navigator.clipboard.writeText(O),R(!0),setTimeout(()=>R(!1),1500)};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"sm:max-w-[560px] w-[calc(100vw-2rem)] max-h-[90vh] overflow-y-auto overflow-x-hidden",children:[e.jsxs(Vs,{className:"min-w-0",children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(pn,{className:"h-5 w-5 text-primary"}),"Share Virtual Tour"]}),e.jsx(Cr,{className:"truncate",children:n.property_address})]}),e.jsxs("div",{className:"space-y-4 min-w-0",children:[e.jsxs("div",{className:"rounded-lg border bg-muted/30 p-3 flex items-center gap-2 min-w-0",children:[e.jsx(od,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsx("code",{className:"flex-1 min-w-0 text-xs truncate",children:O}),e.jsxs($,{variant:"ghost",size:"sm",onClick:oe,className:"shrink-0 h-7 gap-1",children:[P?e.jsx(ma,{className:"h-3.5 w-3.5 text-emerald-600"}):e.jsx(Da,{className:"h-3.5 w-3.5"}),P?"Copied":"Copy"]})]}),r&&e.jsxs("div",{className:"flex gap-2",children:[e.jsxs($,{type:"button",variant:C?"default":"outline",size:"sm",onClick:()=>A(!0),className:"gap-1.5",children:[e.jsx(pn,{className:"h-3.5 w-3.5"}),"Send from Gmail"]}),e.jsx($,{type:"button",variant:C?"outline":"default",size:"sm",onClick:()=>A(!1),className:"gap-1.5",children:"Send from LevelUp"})]}),C&&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(re,{className:"flex items-center gap-1.5",children:[e.jsx(Xn,{className:"h-3.5 w-3.5"}),"Recipients"]}),e.jsxs(Xc,{open:u,onOpenChange:h,modal:!0,children:[e.jsx(Qc,{asChild:!0,children:e.jsxs($,{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(v_,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(Bc,{className:"w-[440px] max-w-[calc(100vw-2rem)] p-0",align:"start",children:e.jsxs(M_,{children:[e.jsx(P_,{placeholder:"Search contacts..."}),e.jsxs(I_,{className:"max-h-[300px] overflow-y-auto",children:[e.jsx(L_,{children:m?"Loading...":"No contacts found."}),e.jsx(Nb,{children:l.map(me=>{const Q=!!c.find(fe=>fe.id===me.id),te=U(me).slice(0,80),le=(me.email||"").slice(0,80);return e.jsxs(rv,{value:`${te} ${le}`,onSelect:()=>G(me),className:"py-2",children:[e.jsx(ma,{className:Ot("mr-2 h-4 w-4 shrink-0",Q?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"font-medium text-sm truncate",children:te||"(no name)"}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:le})]})]},me.id)})})]})]})})]}),c.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1.5 pt-1",children:c.map(me=>e.jsxs(qe,{variant:"secondary",className:"gap-1 pl-2 pr-1 py-0.5",children:[e.jsx("span",{className:"text-xs",children:U(me)}),e.jsx("button",{onClick:()=>G(me),className:"hover:bg-muted-foreground/20 rounded p-0.5",children:e.jsx(mr,{className:"h-3 w-3"})})]},me.id))}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsx(be,{value:g,onChange:me=>x(me.target.value),placeholder:"Or type an email...",type:"email",onKeyDown:me=>{me.key==="Enter"&&(me.preventDefault(),H())}}),e.jsx($,{type:"button",variant:"outline",size:"sm",onClick:H,children:"Add"})]})]}),e.jsx(Pc,{}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{htmlFor:"vt-subject",children:"Subject"}),e.jsx(be,{id:"vt-subject",value:y,onChange:me=>v(me.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{htmlFor:"vt-message",children:"Personal Message"}),e.jsx(Ls,{id:"vt-message",value:_,onChange:me=>j(me.target.value),rows:4,className:"resize-y"})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),disabled:M,children:"Cancel"}),e.jsxs($,{onClick:ee,disabled:M||Y.length===0||!y.trim(),className:"gap-2",children:[M?e.jsx(Jt,{className:"h-4 w-4 animate-spin"}):e.jsx(Wr,{className:"h-4 w-4"}),M?"Sending...":`Send${Y.length?` to ${Y.length}`:""}`]})]})]})]})})}function qFn({summary:s,stats:t,search:n,onSearchChange:r,onCreate:a}){return e.jsx("section",{className:"hub-ink relative overflow-hidden rounded-2xl p-5 sm:p-6",children:e.jsxs("div",{className:"relative flex flex-col gap-5",children:[e.jsxs("div",{className:"flex flex-col gap-4 lg:flex-row lg:items-start lg:justify-between",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-xs uppercase tracking-wider hub-ink-muted",children:"Agent OS"}),e.jsx("h1",{className:"mt-1 text-2xl font-bold sm:text-3xl",children:"Guest Book"}),e.jsx("p",{className:"mt-1 text-sm hub-ink-muted",children:s})]}),e.jsxs("div",{className:"flex flex-col items-start gap-2 sm:items-end",children:[e.jsxs("button",{onClick:a,className:"inline-flex items-center gap-2 rounded-full bg-background px-4 py-2 text-sm font-semibold text-foreground shadow-sm transition-transform hover:scale-[1.02]",children:[e.jsx(nn,{className:"h-4 w-4"}),"New Open House"]}),e.jsxs("span",{className:"inline-flex items-center gap-1.5 text-xs hub-ink-muted",children:[e.jsx(Bx,{className:"h-3.5 w-3.5",style:{color:"hsl(var(--hub-glow))"}}),"Every event gets a sign-in page & QR code"]})]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(Yr,{className:"pointer-events-none absolute left-3.5 top-1/2 h-4 w-4 -translate-y-1/2 opacity-70"}),e.jsx(be,{value:n,onChange:i=>r(i.target.value),placeholder:"Search by address, event name, or city...",className:"h-11 rounded-xl border-transparent bg-white/10 pl-10 text-current placeholder:text-current/50 focus-visible:ring-2 focus-visible:ring-white/30"})]}),e.jsx("div",{className:"-mx-1 flex gap-2 overflow-x-auto px-1 pb-1 scrollbar-hide",children:t.map(i=>e.jsxs("button",{type:"button",onClick:i.onClick,disabled:!i.onClick,className:Ot("hub-glass min-w-[118px] shrink-0 rounded-xl px-4 py-3 text-left transition-all",i.onClick?"cursor-pointer hover:scale-[1.02]":"cursor-default opacity-80",i.active&&"ring-2 ring-white/50"),children:[e.jsx("div",{className:"text-lg font-bold leading-none",children:i.value}),e.jsx("div",{className:"mt-1.5 text-[11px] uppercase tracking-wide hub-ink-muted",children:i.label})]},i.key))})]})})}const Ibt={buying:"bg-emerald-500/10 text-emerald-700 dark:text-emerald-300 border-emerald-500/20",selling:"bg-blue-500/10 text-blue-700 dark:text-blue-300 border-blue-500/20",neighbor:"bg-amber-500/10 text-amber-700 dark:text-amber-300 border-amber-500/20",browsing:"bg-muted text-muted-foreground border-border"};function VFn({visitors:s,onExport:t,onShare:n}){if(!s.length)return e.jsxs("div",{className:"rounded-xl border border-dashed border-border bg-muted/20 px-6 py-10 text-center",children:[e.jsx("div",{className:"mx-auto mb-3 flex h-12 w-12 items-center justify-center rounded-2xl bg-primary/10",children:e.jsx(Xn,{className:"h-6 w-6 text-primary"})}),e.jsx("p",{className:"text-sm font-semibold text-foreground",children:"No sign-ins yet"}),e.jsx("p",{className:"mx-auto mt-1 max-w-sm text-xs text-muted-foreground",children:"Share the link or print the QR flyer so visitors can sign in from their phone."}),n&&e.jsxs($,{variant:"outline",size:"sm",className:"mt-4 gap-1.5",onClick:n,children:[e.jsx(ou,{className:"h-3.5 w-3.5"}),"Get the share link"]})]});const r=s.filter(a=>a.visitor_intent==="buying"&&!a.has_agent).length;return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("p",{className:"text-xs font-semibold text-foreground",children:[s.length," Visitor",s.length!==1?"s":""]}),r>0&&e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full border border-orange-500/20 bg-orange-500/10 px-2 py-0.5 text-[11px] font-medium text-orange-700 dark:text-orange-300",children:[e.jsx(iu,{className:"h-3 w-3"}),r," hot"]})]}),e.jsxs($,{variant:"outline",size:"sm",onClick:t,className:"h-7 gap-1 text-xs",children:[e.jsx(ji,{className:"h-3 w-3"}),"Export CSV"]})]}),e.jsx("div",{className:"max-h-[420px] overflow-auto rounded-xl border border-border",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"sticky top-0 z-10 bg-muted/80 backdrop-blur",children:e.jsxs("tr",{className:"text-[11px] uppercase tracking-wide text-muted-foreground",children:[e.jsx("th",{className:"p-2.5 text-left font-semibold",children:"Name"}),e.jsx("th",{className:"hidden p-2.5 text-left font-semibold sm:table-cell",children:"Contact"}),e.jsx("th",{className:"hidden p-2.5 text-left font-semibold md:table-cell",children:"Intent"}),e.jsx("th",{className:"p-2.5 text-left font-semibold",children:"Time"})]})}),e.jsx("tbody",{children:s.map(a=>{var o,c;const i=a.visitor_intent==="buying"&&!a.has_agent,l=Ibt[a.visitor_intent||""]||Ibt.browsing;return e.jsxs("tr",{className:Ot("border-t border-border/50 transition-colors hover:bg-muted/40",i&&"bg-orange-500/[0.06]"),children:[e.jsx("td",{className:"p-2.5",children:e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("div",{className:Ot("flex h-8 w-8 shrink-0 items-center justify-center rounded-full text-xs font-bold",i?"bg-orange-500/15 text-orange-700 dark:text-orange-300":"bg-primary/10 text-primary"),children:((c=(o=a.first_name)==null?void 0:o[0])==null?void 0:c.toUpperCase())||"?"}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"truncate font-medium text-foreground",children:[a.first_name,a.last_name?` ${a.last_name}`:""]}),i&&e.jsx("div",{className:"text-[11px] font-medium text-orange-600 dark:text-orange-400",children:"Buyer · no agent"})]})]})}),e.jsxs("td",{className:"hidden p-2.5 text-muted-foreground sm:table-cell",children:[a.email&&e.jsx("div",{className:"max-w-[200px] truncate",children:a.email}),a.phone&&e.jsx("div",{className:"text-xs",children:a.phone}),a.visitor_address?e.jsx("div",{className:"max-w-[200px] truncate text-xs",children:a.visitor_address}):null]}),e.jsx("td",{className:"hidden p-2.5 md:table-cell",children:a.visitor_intent?e.jsx("span",{className:Ot("inline-flex rounded-full border px-2 py-0.5 text-[11px] font-medium capitalize",l),children:a.visitor_intent}):a.partial_signin?e.jsx("span",{className:"inline-flex rounded-full border border-amber-500/20 bg-amber-500/10 px-2 py-0.5 text-[11px] font-medium text-amber-700 dark:text-amber-300",children:"Didn't finish"}):null}),e.jsx("td",{className:"p-2.5 text-xs text-muted-foreground",children:Ys(new Date(a.created_at),"h:mm a")})]},a.id)})})]})})]})}const nqe="guestbook.relevelup.com";function HFn(){const{data:s,isLoading:t}=Njs(),n=kjs(),r=aEt(),a=Sjs(),[i,l]=k.useState(!1),[o,c]=k.useState(null),[d,u]=k.useState(""),[h,m]=k.useState("all"),[p,g]=k.useState(!1),{user:x}=ks(),y=ai(),[v,_]=k.useState(null),[j,C]=k.useState(null),[A,M]=k.useState(!1),I=k.useRef(null),[P,R]=k.useState({property_address:"",city:"",state:"",zip:"",event_date:Ys(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"}),O=te=>{var fe;const le=(fe=te.target.files)==null?void 0:fe[0];if(le){if(le.size>5*1024*1024){Ma({title:"Photo must be under 5MB",variant:"destructive"});return}_(le),C(URL.createObjectURL(le))}},B=()=>{_(null),C(null),I.current&&(I.current.value="")},U=async()=>{if(!P.property_address){Ma({title:P.event_type==="community"?"Event name is required":"Address is required",variant:"destructive"});return}let te;if(v&&x){M(!0);const fe=v.name.split(".").pop(),_e=`${y}/${Date.now()}.${fe}`,{error:ve}=await V.storage.from("open-house-photos").upload(_e,v,{upsert:!0});if(ve){Ma({title:"Photo upload failed",description:ve.message,variant:"destructive"}),M(!1);return}const{data:he}=V.storage.from("open-house-photos").getPublicUrl(_e);te=he.publicUrl,M(!1)}const le=P.kind==="virtual"?{...P,start_time:void 0,end_time:void 0,photo_url:te}:{...P,photo_url:te};await n.mutateAsync(le),l(!1),R({property_address:"",city:"",state:"",zip:"",event_date:Ys(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"}),B()},G=te=>{navigator.clipboard.writeText(`https://${nqe}/${te}`),Ma({title:"Link copied!"})},H=Ys(new Date,"yyyy-MM-dd"),Y=k.useMemo(()=>{const te=s??[],le=d.trim().toLowerCase(),fe=je=>!le||[je.property_address,je.city,je.state].filter(Boolean).join(" ").toLowerCase().includes(le),_e=te.filter(fe),ve=_e.filter(je=>je.kind==="virtual"),he=_e.filter(je=>je.kind!=="virtual"),Se=he.filter(je=>je.event_date===H),Te=he.filter(je=>je.event_date>H).sort((je,Ye)=>je.event_date.localeCompare(Ye.event_date)),Ie=he.filter(je=>je.event_dateYe.event_date.localeCompare(je.event_date)),Ue=te.reduce((je,Ye)=>je+(Ye.visitor_count||0),0),Be=te.reduce((je,Ye)=>je+(Ye.qr_scan_count||0),0);return{today:Se,upcoming:Te,past:Ie,virtual:ve,totalSignIns:Ue,totalScans:Be}},[s,d,H]),se=Y.today.length+Y.upcoming.length,ee=se>0?`${se} upcoming · ${Y.totalSignIns.toLocaleString()} total sign-ins`:`${Y.totalSignIns.toLocaleString()} total sign-ins collected`,oe=te=>h==="all"||h===te,me=te=>m(le=>le===te?"all":te),Q=te=>e.jsx(GFn,{openHouse:te,isExpanded:o===te.id,onToggle:()=>c(o===te.id?null:te.id),onCopyLink:()=>G(te.slug||""),onToggleActive:()=>r.mutate({id:te.id,is_active:!te.is_active}),onDelete:()=>a.mutate(te.id),isToday:te.kind!=="virtual"&&te.event_date===H},te.id);return e.jsxs(Xs,{title:"Guest Book",children:[e.jsx(Sc,{children:e.jsx("title",{children:"Guest Book | LevelUp"})}),e.jsxs("div",{className:"space-y-6",children:[e.jsx(qFn,{summary:ee,search:d,onSearchChange:u,onCreate:()=>l(!0),stats:[{key:"today",label:"Live Today",value:Y.today.length,onClick:()=>me("today"),active:h==="today"},{key:"upcoming",label:"Upcoming",value:Y.upcoming.length,onClick:()=>me("upcoming"),active:h==="upcoming"},{key:"virtual",label:"Virtual Tours",value:Y.virtual.length,onClick:()=>me("virtual"),active:h==="virtual"},{key:"signins",label:"Total Sign-Ins",value:Y.totalSignIns.toLocaleString()},{key:"scans",label:"Total QR Scans",value:Y.totalScans.toLocaleString()}]}),e.jsx("div",{className:"flex justify-end",children:e.jsxs(zs,{open:i,onOpenChange:l,children:[e.jsx(yl,{asChild:!0,children:e.jsx("span",{className:"sr-only",children:"Open create dialog"})}),e.jsxs(Rs,{className:"sm:max-w-lg max-h-[90vh] flex flex-col",children:[e.jsxs(Vs,{children:[e.jsx($s,{children:"Create Open House"}),e.jsx(Cr,{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(re,{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:()=>R(te=>({...te,kind:"physical"})),className:`p-3 rounded-lg border text-left transition-all ${P.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:()=>R(te=>({...te,kind:"virtual",event_type:"property"})),className:`p-3 rounded-lg border text-left transition-all ${P.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"})]})]})]}),P.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:()=>R(te=>({...te,event_type:"property"})),className:`flex-1 px-3 py-2 rounded-md text-sm font-medium transition-colors ${P.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:()=>R(te=>({...te,event_type:"community"})),className:`flex-1 px-3 py-2 rounded-md text-sm font-medium transition-colors ${P.event_type==="community"?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:"Community Event"})]})}),P.kind==="virtual"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{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:()=>R(te=>({...te,tour_mode:"rooms"})),className:`p-3 rounded-lg border text-left transition-all ${P.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:()=>R(te=>({...te,tour_mode:"single_video"})),className:`p-3 rounded-lg border text-left transition-all ${P.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(re,{children:P.event_type==="community"?"Event Name *":"Property Address *"}),e.jsx(be,{value:P.property_address,onChange:te=>R(le=>({...le,property_address:te.target.value})),placeholder:P.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(re,{children:"City"}),e.jsx(be,{value:P.city,onChange:te=>R(le=>({...le,city:te.target.value})),placeholder:"Austin"})]}),e.jsxs("div",{children:[e.jsx(re,{children:"State"}),e.jsx(be,{value:P.state,onChange:te=>R(le=>({...le,state:te.target.value})),placeholder:"TX",maxLength:2})]}),e.jsxs("div",{children:[e.jsx(re,{children:"ZIP"}),e.jsx(be,{value:P.zip,onChange:te=>R(le=>({...le,zip:te.target.value})),placeholder:"78701"})]})]}),P.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(re,{children:"Date"}),e.jsx(be,{type:"date",value:P.event_date,onChange:te=>R(le=>({...le,event_date:te.target.value}))})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Start Time"}),e.jsx(be,{type:"time",value:P.start_time,onChange:te=>R(le=>({...le,start_time:te.target.value}))})]}),e.jsxs("div",{children:[e.jsx(re,{children:"End Time"}),e.jsx(be,{type:"time",value:P.end_time,onChange:te=>R(le=>({...le,end_time:te.target.value}))})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Welcome Message"}),e.jsx(Ls,{value:P.agent_greeting,onChange:te=>R(le=>({...le,agent_greeting:te.target.value})),placeholder:"Welcome! Please sign in below."})]}),e.jsxs("div",{children:[e.jsx(re,{children:P.event_type==="community"?"Event Photo":"Property Photo"}),e.jsx("input",{ref:I,type:"file",accept:"image/*",onChange:O,className:"hidden"}),j?e.jsxs("div",{className:"relative mt-1 rounded-xl overflow-hidden border border-border",children:[e.jsx("img",{src:j,alt:"Property preview",className:"w-full h-40 object-cover"}),e.jsx("button",{type:"button",onClick:B,className:"absolute top-2 right-2 bg-black/60 hover:bg-black/80 text-white rounded-full p-1 transition-colors",children:e.jsx(mr,{className:"h-4 w-4"})})]}):e.jsxs("button",{type:"button",onClick:()=>{var te;return(te=I.current)==null?void 0:te.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(gb,{className:"h-6 w-6"}),e.jsxs("span",{className:"text-sm",children:["Add a ",P.event_type==="community"?"cover":"property"," photo"]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"Max 5MB"})]})]}),e.jsx($,{onClick:U,disabled:n.isPending||A,className:"w-full",children:A?"Uploading photo...":n.isPending?"Creating...":P.kind==="virtual"?"Create Virtual Open House":P.event_type==="community"?"Create Community Event":"Create Open House"})]})]})]})}),t?e.jsx("div",{className:"grid gap-4",children:[1,2].map(te=>e.jsx(we,{className:"animate-pulse",children:e.jsxs(Vt,{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"})]})},te))}):s!=null&&s.length?e.jsxs("div",{className:"space-y-8",children:[Y.today.length>0&&oe("today")&&e.jsxs("section",{className:"space-y-3",children:[e.jsx(QDe,{title:"Happening Today",count:Y.today.length,accent:!0}),e.jsx("div",{className:"space-y-4",children:Y.today.map(Q)})]}),Y.upcoming.length>0&&oe("upcoming")&&e.jsxs("section",{className:"space-y-3",children:[e.jsx(QDe,{title:"Upcoming",count:Y.upcoming.length}),e.jsx("div",{className:"space-y-4",children:Y.upcoming.map(Q)})]}),Y.virtual.length>0&&oe("virtual")&&e.jsxs("section",{className:"space-y-3",children:[e.jsx(QDe,{title:"Virtual Tours",count:Y.virtual.length}),e.jsx("div",{className:"space-y-4",children:Y.virtual.map(Q)})]}),Y.past.length>0&&h==="all"&&e.jsxs("section",{className:"space-y-3",children:[e.jsxs("button",{onClick:()=>g(te=>!te),className:"flex w-full items-center justify-between rounded-xl border border-border bg-card px-4 py-3 text-left transition-colors hover:bg-muted/40",children:[e.jsxs("span",{className:"flex items-center gap-2 text-sm font-semibold text-foreground",children:[e.jsx(b2,{className:"h-4 w-4 text-muted-foreground"}),"Past Open Houses",e.jsx("span",{className:"rounded-full bg-muted px-2 py-0.5 text-[11px] font-medium text-muted-foreground",children:Y.past.length})]}),p?e.jsx(Ny,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(Go,{className:"h-4 w-4 text-muted-foreground"})]}),p&&e.jsx("div",{className:"space-y-4",children:Y.past.map(Q)})]}),se===0&&Y.virtual.length===0&&Y.past.length===0&&e.jsx(we,{className:"border-dashed",children:e.jsxs(De,{className:"py-12 text-center text-sm text-muted-foreground",children:["No open houses match “",d,"”."]})})]}):e.jsx(we,{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(Bx,{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($,{onClick:()=>l(!0),children:[e.jsx(nn,{className:"h-4 w-4 mr-2"}),"Create Your First Open House"]})]})})]})]})}function QDe({title:s,count:t,accent:n}){return e.jsxs("div",{className:"flex items-center gap-2.5",children:[n&&e.jsxs("span",{className:"relative flex h-2.5 w-2.5",children:[e.jsx("span",{className:"absolute inline-flex h-full w-full animate-ping rounded-full bg-emerald-400 opacity-70"}),e.jsx("span",{className:"relative inline-flex h-2.5 w-2.5 rounded-full bg-emerald-500"})]}),e.jsx("h2",{className:"text-sm font-semibold uppercase tracking-wide text-foreground",children:s}),e.jsx("span",{className:"rounded-full bg-muted px-2 py-0.5 text-[11px] font-medium text-muted-foreground",children:t}),e.jsx("div",{className:"h-px flex-1 bg-border"})]})}function GFn({openHouse:s,isExpanded:t,onToggle:n,onCopyLink:r,onToggleActive:a,onDelete:i,isToday:l}){const{data:o}=rEt(t?s.id:void 0),{data:c}=pt({queryKey:["agent-profile-flyer",s.agent_id],queryFn:async()=>{const{data:P,error:R}=await V.from("profiles").select("name, avatar_url, phone, title, brokerages:brokerage_id(name)").eq("id",s.agent_id).single();if(R)throw R;const O=P.brokerages;return{...P,brokerage_name:(O==null?void 0:O.name)||null}},enabled:!!s.agent_id}),[d,u]=k.useState(!1),[h,m]=k.useState(!1),[p,g]=k.useState(!1),[x,y]=k.useState(!1),v=k.useRef(null),_=`https://${nqe}/${s.slug}`,j=P=>{if(!P)return"";const[R,O]=P.split(":"),B=parseInt(R),U=B>=12?"PM":"AM";return`${B>12?B-12:B||12}:${O} ${U}`},C=()=>{if(!(o!=null&&o.length))return;const P=["First Name","Last Name","Email","Phone","Address","Intent","Wants Market Updates","Message","Signed In"],R=o.map(H=>[H.first_name,H.last_name||"",H.email||"",H.phone||"",H.visitor_address||"",H.visitor_intent||"",H.wants_market_updates?"Yes":"No",(H.message||"").replace(/"/g,'""'),Ys(new Date(H.created_at),"MM/dd/yyyy h:mm a")]),O=[P,...R].map(H=>H.map(Y=>`"${Y}"`).join(",")).join(` `),B=new Blob([O],{type:"text/csv"}),U=URL.createObjectURL(B),G=document.createElement("a");G.href=U,G.download=`${s.property_address.replace(/[^a-zA-Z0-9]/g,"-")}-visitors.csv`,G.click(),URL.revokeObjectURL(U)},A=k.useCallback(()=>{if(!v.current)return;const P=v.current.querySelector("svg");if(!P)return;const R=new XMLSerializer().serializeToString(P),O=document.createElement("canvas");O.width=1024,O.height=1024;const B=O.getContext("2d"),U=new Image;U.onload=()=>{B==null||B.drawImage(U,0,0,1024,1024);const G=document.createElement("a");G.download=`${s.property_address.replace(/[^a-zA-Z0-9]/g,"-")}-qr.png`,G.href=O.toDataURL("image/png"),G.click()},U.src="data:image/svg+xml;base64,"+btoa(unescape(encodeURIComponent(R)))},[s.property_address]),M=k.useCallback(()=>{var Re;if(!v.current)return;const P=v.current.querySelector("svg");if(!P)return;const R=new XMLSerializer().serializeToString(P),O="data:image/svg+xml;base64,"+btoa(unescape(encodeURIComponent(R))),B=Ys(new Date(s.event_date+"T00:00:00"),"EEEE, MMMM d, yyyy"),U=s.start_time?`${j(s.start_time)}${s.end_time?" – "+j(s.end_time):""}`:"",G=[s.city,s.state].filter(Boolean).join(", "),H=s.agent_greeting||"Welcome! Please sign in below.",Y=!!s.photo_url,se=!!c,ee=Y||se,oe=Y&&se,me=oe?"0.35in 0.75in 0.3in":"0.55in 0.75in 0.45in",Q=oe?"28px":"34px",te=oe?"0.2in 0.75in":ee?"0.3in 0.75in":"0.4in 0.75in",le=ee?"0.15in":"0.3in",fe=ee?"0.15in":"0.3in",_e=oe?"14px 36px":"22px 44px",ve=oe?"20px":"24px",he=ee?"0.2in":"0.35in",Se=oe?"1.8in":"2.4in",Te=ee?"0.15in":"0.3in",Ie=oe?"140px":ee?"160px":"200px",Ue=oe?"16px":"24px",Be=oe?"10px 20px":"16px 28px",je=oe?"44px":"56px",Ye="0.15in",Ee=window.open("","_blank");Ee&&(Ee.document.write(` Open House – ${s.property_address}
${s.event_type==="community"?"Community Event":"Open House"}
${s.property_address}
${G?`
${G}${s.zip?" "+s.zip:""}
`:""}
Date
${B}
${U?`
Time
${U}
`:""}
${H}
${c?`
${c.avatar_url?`${c.name}`:`
${((Re=c.name)==null?void 0:Re.charAt(0))||"A"}
`}
Hosted By
${c.name}
${c.title?`
${c.title}
`:""} ${c.brokerage_name?`
${c.brokerage_name}
`:""} ${c.phone?`
${c.phone}
`:""}
`:""} ${s.photo_url?`Property`:""}
QR Code
Scan to Sign In
Point your phone camera at the QR code
`),Ee.document.close(),setTimeout(()=>{Ee.focus(),Ee.print()},500))},[s,_,c]),I=async()=>{y(!0);try{const{error:P}=await V.functions.invoke("guestbook-email-link",{body:{openHouseId:s.id}});if(P)throw P;Ma({title:"Email sent!",description:"Check your inbox for the guest book link."})}catch(P){Ma({title:"Failed to send",description:P.message,variant:"destructive"})}finally{y(!1)}};return e.jsxs(we,{className:Ot("relative overflow-hidden transition-all",s.is_active?"border-border hover:border-primary/40 hover:shadow-md":"opacity-70",l&&"border-emerald-500/40 shadow-[0_0_0_1px_hsl(var(--primary)/0.06)]"),children:[e.jsx("span",{className:Ot("absolute inset-y-0 left-0 w-1",l?"bg-emerald-500":s.kind==="virtual"?"bg-purple-500/70":"bg-primary/40")}),e.jsx(Vt,{className:"pb-3 pl-5",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(Yt,{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:[l&&e.jsxs(qe,{className:"shrink-0 gap-1 border-none bg-emerald-500/15 text-[11px] text-emerald-700 dark:text-emerald-300",children:[e.jsx(Cy,{className:"h-3 w-3"}),"Today"]}),e.jsx(qe,{variant:s.is_active?"default":"secondary",className:"shrink-0 text-[11px]",children:s.is_active?"Active":"Inactive"}),s.kind==="virtual"?e.jsxs(qe,{variant:"outline",className:"shrink-0 gap-1 text-[11px] bg-purple-500/10 text-purple-700 dark:text-purple-300 border-purple-500/20",children:[e.jsx(ba,{className:"h-3 w-3"}),"Virtual"]}):e.jsxs(qe,{variant:"outline",className:"shrink-0 gap-1 text-[11px] bg-emerald-500/10 text-emerald-700 dark:text-emerald-300 border-emerald-500/20",children:[e.jsx(Si,{className:"h-3 w-3"}),"In-Person"]}),s.agent_name&&e.jsxs(qe,{variant:"outline",className:"shrink-0 gap-1 text-[11px] bg-blue-500/10 text-blue-700 dark:text-blue-300 border-blue-500/20",children:[e.jsx(el,{className:"h-3 w-3"}),s.agent_name]}),s.event_type==="community"&&e.jsxs(qe,{variant:"outline",className:"shrink-0 gap-1 text-[11px]",children:[e.jsx(Gi,{className:"h-3 w-3"}),"Community"]})]})]}),e.jsx($,{variant:"ghost",size:"icon",onClick:n,className:"shrink-0 -mr-2 -mt-1",children:t?e.jsx(Ny,{className:"h-4 w-4"}):e.jsx(Go,{className:"h-4 w-4"})})]}),e.jsxs(vr,{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(Si,{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(sa,{className:"h-3 w-3"}),"Always on"]}):e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ha,{className:"h-3 w-3"}),Ys(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(sa,{className:"h-3 w-3"}),j(s.start_time),s.end_time?` – ${j(s.end_time)}`:""]})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-lg bg-muted/60 px-2.5 py-1 text-xs font-semibold text-foreground",children:[e.jsx(Xn,{className:"h-3.5 w-3.5 text-primary"}),s.visitor_count,e.jsx("span",{className:"font-normal text-muted-foreground",children:"signed in"})]}),s.qr_scan_count>0&&e.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-lg bg-muted/60 px-2.5 py-1 text-xs font-semibold text-foreground",children:[e.jsx(Bx,{className:"h-3.5 w-3.5 text-primary"}),s.qr_scan_count,e.jsx("span",{className:"font-normal text-muted-foreground",children:"scans"})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs($,{variant:"outline",size:"sm",onClick:()=>window.location.href=`/mission-control/guest-book/live/${s.id}`,className:"h-8 gap-1.5 text-xs text-emerald-600 border-emerald-500/30 hover:bg-emerald-500/10 dark:text-emerald-400",children:[e.jsx(Cy,{className:"h-3.5 w-3.5"}),"Live"]}),e.jsxs($,{variant:"outline",size:"sm",onClick:r,className:"h-8 gap-1.5 text-xs",children:[e.jsx(Da,{className:"h-3.5 w-3.5"}),"Copy Link"]}),e.jsxs($,{variant:"outline",size:"sm",onClick:()=>u(!0),className:"h-8 gap-1.5 text-xs",children:[e.jsx(Bx,{className:"h-3.5 w-3.5"}),"QR Code"]}),s.kind==="virtual"?e.jsxs($,{variant:"outline",size:"sm",onClick:()=>g(!0),className:"h-8 gap-1.5 text-xs text-primary border-primary/30 hover:bg-primary/10",children:[e.jsx(ou,{className:"h-3.5 w-3.5"}),"Share Tour"]}):e.jsxs($,{variant:"outline",size:"sm",onClick:()=>window.open(`${_}?kiosk=1`,"_blank"),className:"h-8 gap-1.5 text-xs text-primary border-primary/30 hover:bg-primary/10",children:[e.jsx(fB,{className:"h-3.5 w-3.5"}),"Tablet Mode"]}),e.jsxs($,{variant:"outline",size:"sm",onClick:()=>m(!0),className:"h-8 gap-1.5 text-xs",children:[e.jsx(Yc,{className:"h-3.5 w-3.5"}),"Settings"]}),e.jsxs(Au,{children:[e.jsx(Eu,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0","aria-label":"More actions",children:e.jsx(u0,{className:"h-4 w-4"})})}),e.jsxs(gu,{align:"end",className:"w-52",children:[e.jsxs(Pa,{onClick:()=>window.open(_,"_blank"),children:[e.jsx(Ir,{className:"mr-2 h-4 w-4"}),"Preview sign-in page"]}),s.kind==="virtual"&&e.jsxs(Pa,{onClick:()=>window.open(`/guestbook/${s.slug}?preview=1`,"_blank"),children:[e.jsx(ba,{className:"mr-2 h-4 w-4"}),"Preview tour"]}),e.jsxs(Pa,{onClick:a,children:[s.is_active?e.jsx(x0,{className:"mr-2 h-4 w-4"}):e.jsx(ba,{className:"mr-2 h-4 w-4"}),s.is_active?"Deactivate":"Activate"]}),e.jsx(j0,{}),e.jsxs(Pa,{onClick:i,className:"text-destructive focus:text-destructive",children:[e.jsx(Un,{className:"mr-2 h-4 w-4"}),"Delete"]})]})]})]})]})}),t&&e.jsxs(De,{className:"pt-0",children:[e.jsx(Pc,{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://",nqe,"/",s.slug]})]}),e.jsx(VFn,{visitors:o??[],onExport:C}),s.kind==="virtual"&&e.jsx("div",{className:"mt-4",children:e.jsx($Fn,{openHouseId:s.id})}),s.enable_survey&&e.jsx("div",{className:"mt-4",children:e.jsx(zFn,{openHouseId:s.id})})]}),e.jsx(zs,{open:d,onOpenChange:u,children:e.jsxs(Rs,{className:"sm:max-w-sm",children:[e.jsxs(Vs,{children:[e.jsx($s,{children:"QR Code"}),e.jsx(Cr,{className:"truncate",children:s.property_address})]}),e.jsxs("div",{className:"flex flex-col items-center gap-4 py-4",children:[e.jsx("div",{ref:v,className:"bg-white p-4 rounded-xl",children:e.jsx(jk,{value:_,size:240,level:"H"})}),e.jsx("p",{className:"text-xs text-muted-foreground text-center break-all",children:_}),e.jsxs("div",{className:"flex gap-2 w-full",children:[e.jsxs($,{variant:"outline",className:"flex-1",onClick:A,children:[e.jsx(ji,{className:"h-4 w-4 mr-2"}),"Download"]}),e.jsxs($,{variant:"outline",className:"flex-1",onClick:M,children:[e.jsx(QT,{className:"h-4 w-4 mr-2"}),"Print Flyer"]})]}),e.jsxs($,{variant:"default",className:"w-full",onClick:I,disabled:x,children:[e.jsx(pn,{className:"h-4 w-4 mr-2"}),x?"Sending...":"Email Link to Me"]})]})]})}),e.jsx(OFn,{open:h,onOpenChange:m,openHouse:s}),s.kind==="virtual"&&e.jsx(UFn,{open:p,onOpenChange:g,openHouse:{id:s.id,slug:s.slug,property_address:s.property_address,city:s.city,state:s.state}})]})}function WFn(){const{slug:s}=oo();return s?e.jsx(oMt,{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 QVt({photoUrl:s,videoUrl:t,onPhotoChange:n,onVideoChange:r,contactId:a}){const{user:i}=ks(),l=o4(),o=k.useRef(null),c=k.useRef(null),[d,u]=k.useState(!1),[h,m]=k.useState(!1),[p,g]=k.useState(0),x=async v=>{if(i){u(!0);try{const _=v.name.split(".").pop()||"jpg",j=`${i.id}/card-${Date.now()}.${_}`,{error:C}=await V.storage.from("listing-photos").upload(j,v);if(C)throw C;const{data:{publicUrl:A}}=V.storage.from("listing-photos").getPublicUrl(j);n(A),ae.success("Photo uploaded")}catch(_){ae.error(_.message||"Failed to upload photo")}finally{u(!1)}}},y=async v=>{if(i){if(v.size>500*1024*1024){ae.error("Video must be under 500MB");return}m(!0),g(0);try{const{videoId:_,libraryId:j}=await v6(`Card Video - ${Date.now()}`),{uploadUrl:C,apiKey:A}=await b6(_);await new Promise((P,R)=>{const O=new XMLHttpRequest;O.upload.addEventListener("progress",B=>{B.lengthComputable&&g(Math.round(B.loaded/B.total*100))}),O.addEventListener("load",()=>{O.status>=200&&O.status<300?P():R(new Error("Upload failed"))}),O.addEventListener("error",()=>R(new Error("Upload failed"))),O.open("PUT",C),O.setRequestHeader("AccessKey",A),O.send(v)});const M=`https://iframe.mediadelivery.net/embed/${j}/${_}`;r(M);const I=parseFloat((v.size/(1024*1024)).toFixed(2));await l.mutateAsync({bunny_video_id:_,playback_url:`https://iframe.mediadelivery.net/play/${j}/${_}`,file_size_mb:I,title:"Card Video",status:"processing",touch_type:"video",contact_id:a||void 0}),ae.success("Video uploaded & added to your library")}catch(_){ae.error(_.message||"Failed to upload video")}finally{m(!1),g(0)}}};return e.jsxs("div",{className:"space-y-3",children:[e.jsx(re,{children:"Media (optional)"}),e.jsxs(ya,{defaultValue:"photo",className:"w-full",children:[e.jsxs(va,{className:"grid w-full grid-cols-2",children:[e.jsxs(is,{value:"photo",className:"gap-1.5 text-xs",children:[e.jsx(zc,{className:"h-3.5 w-3.5"}),"Photo"]}),e.jsxs(is,{value:"video",className:"gap-1.5 text-xs",children:[e.jsx(ia,{className:"h-3.5 w-3.5"}),"Video"]})]}),e.jsxs(cs,{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($,{variant:"destructive",size:"icon",className:"absolute top-2 right-2 h-7 w-7",onClick:()=>n(null),children:e.jsx(mr,{className:"h-3.5 w-3.5"})})]}):e.jsx("button",{onClick:()=>{var v;return(v=o.current)==null?void 0:v.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(Jt,{className:"h-6 w-6 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(g0,{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:v=>{var j;const _=(j=v.target.files)==null?void 0:j[0];_&&x(_),v.target.value=""}})]}),e.jsxs(cs,{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($,{variant:"destructive",size:"icon",className:"absolute top-2 right-2 h-7 w-7",onClick:()=>r(null),children:e.jsx(mr,{className:"h-3.5 w-3.5"})})]}):e.jsx("button",{onClick:()=>{var v;return(v=c.current)==null?void 0:v.click()},disabled:h,className:"w-full h-32 border-2 border-dashed border-border rounded-lg flex flex-col items-center justify-center gap-2 text-muted-foreground hover:border-primary/40 hover:bg-accent/50 transition-colors",children:h?e.jsxs("div",{className:"flex flex-col items-center gap-2",children:[e.jsx(Jt,{className:"h-6 w-6 animate-spin"}),e.jsxs("span",{className:"text-xs",children:["Uploading... ",p,"%"]}),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:`${p}%`}})})]}):e.jsxs(e.Fragment,{children:[e.jsx(gi,{className:"h-6 w-6"}),e.jsx("span",{className:"text-xs",children:"Upload a video (max 500MB)"})]})}),!t&&!h&&e.jsx("div",{className:"mt-2",children:e.jsx(hQe,{contactId:a,onVideoReady:v=>r(v)})}),e.jsx("input",{ref:c,type:"file",accept:"video/*",className:"hidden",onChange:v=>{var j;const _=(j=v.target.files)==null?void 0:j[0];_&&y(_),v.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 KFn=[{type:"home_anniversary",label:"Home Anniversary",emoji:"🏡",description:"Celebrate their homeownership milestone",gradient:"from-blue-500/20 to-slate-500/20 border-blue-200 dark:border-blue-800"},{type:"wedding_anniversary",label:"Wedding Anniversary",emoji:"💍",description:"Celebrate their special day together",gradient:"from-rose-500/20 to-fuchsia-500/20 border-rose-200 dark:border-rose-800"},{type:"birthday",label:"Birthday",emoji:"🎂",description:"Wish them a happy birthday",gradient:"from-pink-500/20 to-purple-500/20 border-pink-200 dark:border-pink-800"},{type:"just_sold",label:"Just Sold",emoji:"🎉",description:"Announce a successful closing",gradient:"from-emerald-500/20 to-teal-500/20 border-emerald-200 dark:border-emerald-800"},{type:"just_listed",label:"Just Listed",emoji:"🏠",description:"Share a new listing announcement",gradient:"from-amber-500/20 to-orange-500/20 border-amber-200 dark:border-amber-800"},{type:"thank_you",label:"Thank You",emoji:"💐",description:"Show your appreciation",gradient:"from-rose-500/20 to-pink-500/20 border-rose-200 dark:border-rose-800"},{type:"congratulations",label:"Congratulations",emoji:"🏆",description:"Celebrate their achievements",gradient:"from-yellow-500/20 to-amber-500/20 border-yellow-200 dark:border-yellow-800"},{type:"holiday",label:"Holiday",emoji:"🎄",description:"Send seasonal greetings",gradient:"from-red-500/20 to-green-500/20 border-red-200 dark:border-red-800"},{type:"thinking_of_you",label:"Thinking of You",emoji:"💭",description:"Stay top of mind with a personal touch",gradient:"from-violet-500/20 to-indigo-500/20 border-violet-200 dark:border-violet-800"}];function YFn({onSelect:s}){return e.jsx("div",{className:"grid grid-cols-2 gap-2.5",children:KFn.map((t,n)=>e.jsxs(_r.button,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:n*.04,duration:.25},onClick:()=>s(t.type),className:`group relative flex flex-col items-start gap-1 p-3.5 rounded-xl border bg-gradient-to-br ${t.gradient} hover:shadow-md hover:scale-[1.02] active:scale-[0.98] transition-all text-left`,children:[e.jsx("span",{className:"text-2xl",children:t.emoji}),e.jsx("span",{className:"text-sm font-semibold text-foreground",children:t.label}),e.jsx("span",{className:"text-[11px] text-muted-foreground leading-tight",children:t.description})]},t.type))})}const HV={home_anniversary:{title:["Happy Home","Anniversary"],icon:"🏡",emojis:["🏡","✨","🎉","❤️","🎊","🏠"],defaultMessage:"Wishing you many more wonderful years of memories in your beautiful home. Thank you for letting me be part of your journey."},wedding_anniversary:{title:["Happy","Anniversary"],icon:"💍",emojis:["💍","💐","❤️","🥂","💕","✨"],defaultMessage:"Wishing you both a wonderful anniversary filled with love, laughter, and cherished memories. Here's to many more years together!"},just_listed:{title:["Just","Listed!"],icon:"🏠",emojis:["🏠","📋","🔑","⭐","🎯","✨"],defaultMessage:"Exciting news — this beautiful property just hit the market! Contact me for a private showing."},just_sold:{title:["Just","Sold!"],icon:"🎉",emojis:["🎉","🏡","🔑","🥂","🎊","💰"],defaultMessage:"Another successful closing! Congratulations to the new homeowners. It was a pleasure making this happen."},congratulations:{title:["Congratulations!",""],icon:"🏆",emojis:["🎉","🥳","🏆","⭐","🎊","✨"],defaultMessage:"What an incredible milestone! I'm so happy for you. Wishing you all the best in this exciting new chapter."},birthday:{title:["Happy","Birthday!"],icon:"🎂",emojis:["🎂","🎈","🎁","🥳","🎉","🧁"],defaultMessage:"Wishing you the happiest of birthdays! May this year bring you joy, laughter, and everything you've been dreaming of."},holiday:{title:["Happy","Holidays!"],icon:"🎄",emojis:["🎄","❄️","🎁","⭐","🕯️","🎅"],defaultMessage:"Wishing you and your family a season filled with warmth, joy, and cherished moments. Happy Holidays!"},thank_you:{title:["Thank","You!"],icon:"💐",emojis:["💐","🙏","❤️","⭐","✨","🤝"],defaultMessage:"Thank you so much for your trust and confidence. It truly means the world to me. I'm always here for you!"},thinking_of_you:{title:["Thinking","Of You"],icon:"💭",emojis:["💭","❤️","🌸","☀️","🦋","💫"],defaultMessage:"Just wanted to reach out and let you know I'm thinking of you. I hope you're doing well — don't hesitate to reach out anytime!"}};function Lbt({initialOpen:s,initialCardType:t,initialContactId:n,initialRecipientName:r,initialAddress:a,initialDate:i,onOpenChange:l}){const{user:o}=ks(),c=ls(),[d,u]=k.useState(!1),[h,m]=k.useState("type"),[p,g]=k.useState(""),[x,y]=k.useState(null),[v,_]=k.useState(!1),[j,C]=k.useState("home_anniversary"),[A,M]=k.useState(""),[I,P]=k.useState(""),[R,O]=k.useState(""),[B,U]=k.useState(""),[G,H]=k.useState("elegant"),[Y,se]=k.useState(null),[ee,oe]=k.useState(null),me=k.useState(!1);!me[0]&&s&&t&&(me[1](!0),u(!0),C(t),n&&y(n),r&&M(r),a&&P(a),i&&O(i),m(r?"details":"contact"));const{data:Q}=pt({queryKey:["contacts-for-card",o==null?void 0:o.id,p],queryFn:async()=>{let Be=V.from("innercircle_contacts").select("id, first_name, last_name, address, city, state, home_anniversary, wedding_anniversary, email, phone").eq("owner_user_id",o.id).order("first_name").limit(20);p&&(Be=Be.or(`first_name.ilike.%${p}%,last_name.ilike.%${p}%`));const{data:je,error:Ye}=await Be;if(Ye)throw Ye;return je},enabled:!!(o!=null&&o.id)&&d}),{data:te}=pt({queryKey:["agent-profile-card",o==null?void 0:o.id],queryFn:async()=>{const{data:Be,error:je}=await V.from("profiles").select("name, email, phone, avatar_url, brokerage:brokerages(name)").eq("id",o.id).single();if(je)throw je;return Be},enabled:!!(o!=null&&o.id)}),le=Be=>{y(Be.id),M(`${Be.first_name}${Be.last_name?" "+Be.last_name:""}`),P([Be.address,Be.city,Be.state].filter(Boolean).join(", "));const je=j==="wedding_anniversary"?Be.wedding_anniversary:j==="home_anniversary"?Be.home_anniversary:"";O(je||""),m("details")},fe=Be=>{C(Be),m("contact")},_e=async()=>{var Be;if(!(!o||!te)){_(!0);try{const je={owner_user_id:o.id,contact_id:x,card_type:j,template:G,recipient_name:A,property_address:I||null,home_anniversary_date:R||null,custom_message:B||null,property_photo_url:Y||null,video_url:ee||null,agent_name:te.name||"Agent",agent_photo_url:te.avatar_url,agent_phone:te.phone,agent_email:te.email,agent_brokerage:((Be=te.brokerage)==null?void 0:Be.name)||null},{error:Ye}=await V.from("sendable_cards").insert(je);if(Ye)throw Ye;ae.success("Card created! Copy the link to share it."),c.invalidateQueries({queryKey:["sendable-cards"]}),ve()}catch(je){ae.error(je.message||"Failed to create card")}finally{_(!1)}}},ve=()=>{u(!1),m("type"),C("home_anniversary"),g(""),y(null),M(""),P(""),O(""),U(""),H("elegant"),se(null),oe(null)},he={home_anniversary:"Home Anniversary",wedding_anniversary:"Wedding Anniversary",just_listed:"Just Listed",just_sold:"Just Sold",congratulations:"Congratulations",birthday:"Birthday",holiday:"Holiday",thank_you:"Thank You",thinking_of_you:"Thinking of You"},Se=HV[j],Te=j==="home_anniversary"||j==="wedding_anniversary",Ie=j==="wedding_anniversary"?"Wedding Anniversary Date":"Home Anniversary Date",Ue=["home_anniversary","just_listed","just_sold"].includes(j);return e.jsxs(zs,{open:d,onOpenChange:Be=>{Be?u(!0):(ve(),l==null||l(!1))},children:[e.jsx(yl,{asChild:!0,children:e.jsxs($,{className:"gap-2",children:[e.jsx(nn,{className:"h-4 w-4"}),"Create Card"]})}),e.jsxs(Rs,{className:"sm:max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(Vs,{children:e.jsx($s,{children:h==="type"?"What type of card?":h==="contact"?`${he[j]} — Choose a Contact`:`${he[j]} — Customize`})}),h==="type"&&e.jsx(YFn,{onSelect:fe}),h==="contact"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs($,{variant:"ghost",size:"sm",className:"gap-1.5 -ml-2 text-muted-foreground",onClick:()=>m("type"),children:[e.jsx(Ia,{className:"h-3.5 w-3.5"})," Back to card types"]}),e.jsxs("div",{className:"relative",children:[e.jsx(Yr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search contacts...",value:p,onChange:Be=>g(Be.target.value),className:"pl-9"})]}),e.jsxs("div",{className:"space-y-1 max-h-64 overflow-y-auto",children:[Q==null?void 0:Q.map(Be=>e.jsxs("button",{onClick:()=>le(Be),className:"w-full flex items-center gap-3 p-3 rounded-lg hover:bg-accent text-left transition-colors",children:[e.jsx("div",{className:"h-9 w-9 rounded-full bg-primary/10 flex items-center justify-center shrink-0",children:e.jsx(el,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("p",{className:"text-sm font-medium truncate",children:[Be.first_name," ",Be.last_name]}),Be.address&&e.jsxs("p",{className:"text-xs text-muted-foreground truncate flex items-center gap-1",children:[e.jsx(ua,{className:"h-3 w-3"}),Be.address]})]}),(j==="home_anniversary"&&Be.home_anniversary||j==="wedding_anniversary"&&Be.wedding_anniversary)&&e.jsx("span",{className:"text-[10px] text-emerald-600 bg-emerald-500/10 px-2 py-0.5 rounded-full shrink-0",children:"Date set"})]},Be.id)),(Q==null?void 0:Q.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($,{variant:"outline",size:"sm",className:"w-full",onClick:()=>{m("details")},children:"Skip — enter details manually"})})]}),h==="details"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs($,{variant:"ghost",size:"sm",className:"gap-1.5 -ml-2 text-muted-foreground",onClick:()=>m("contact"),children:[e.jsx(Ia,{className:"h-3.5 w-3.5"})," Back"]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Recipient Name"}),e.jsx(be,{value:A,onChange:Be=>M(Be.target.value),placeholder:"John & Jane Smith"})]}),Ue&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Property Address"}),e.jsx(be,{value:I,onChange:Be=>P(Be.target.value),placeholder:"123 Main St, Austin, TX"})]}),Te&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:Ie}),e.jsx(be,{type:"date",value:R,onChange:Be=>O(Be.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Personal Message (optional)"}),e.jsx(Ls,{value:B,onChange:Be=>U(Be.target.value),placeholder:Se.defaultMessage,rows:3})]}),e.jsx(QVt,{photoUrl:Y,videoUrl:ee,onPhotoChange:se,onVideoChange:oe,contactId:x}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Template Style"}),e.jsx("div",{className:"grid grid-cols-5 gap-2",children:[{key:"elegant",label:"Elegant",gradient:"bg-gradient-to-br from-slate-100 to-blue-100 dark:from-slate-800 dark:to-slate-700"},{key:"bold",label:"Bold",gradient:"bg-gradient-to-br from-violet-500 to-fuchsia-500"},{key:"warm",label:"Warm",gradient:"bg-gradient-to-br from-amber-200 to-orange-300"},{key:"glass",label:"Glass",gradient:"bg-gradient-to-br from-slate-900 via-blue-900/50 to-slate-900 border border-white/10"},{key:"cinematic",label:"Cinema",gradient:"bg-gradient-to-br from-slate-950 via-blue-950 to-slate-950"}].map(({key:Be,label:je,gradient:Ye})=>e.jsxs("button",{onClick:()=>H(Be),className:`p-2 rounded-lg border-2 transition-all text-center ${G===Be?"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:je})]},Be))})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsx($,{variant:"outline",onClick:()=>m("contact"),className:"flex-1",children:"Back"}),e.jsx($,{onClick:_e,disabled:!A||v,className:"flex-1 gap-2",children:v?"Creating...":"Create Card"})]})]})]})]})}const ZFn={home_anniversary:"Home Anniversary",wedding_anniversary:"Wedding Anniversary",just_listed:"Just Listed",just_sold:"Just Sold",congratulations:"Congratulations",birthday:"Birthday",holiday:"Holiday",thank_you:"Thank You",thinking_of_you:"Thinking of You"};function XFn({card:s}){const{user:t}=ks(),{canSendEmail:n,sendMethod:r}=dx(),a=ls(),[i,l]=k.useState(!1),[o,c]=k.useState(!1),[d,u]=k.useState("");k.useEffect(()=>{i&&s.contact_id&&!d&&V.from("innercircle_contacts").select("email").eq("id",s.contact_id).maybeSingle().then(({data:j})=>{j!=null&&j.email&&u(j.email)})},[i,s.contact_id]);const h={home_anniversary:`🏡 Happy Home Anniversary, ${s.recipient_name}!`,wedding_anniversary:`💍 Happy Anniversary, ${s.recipient_name}!`,just_listed:`🏠 Just Listed — Check This Out, ${s.recipient_name}!`,just_sold:`🎉 Just Sold! Congrats, ${s.recipient_name}!`,congratulations:`🏆 Congratulations, ${s.recipient_name}!`,birthday:`🎂 Happy Birthday, ${s.recipient_name}!`,holiday:`🎄 Happy Holidays, ${s.recipient_name}!`,thank_you:`💐 Thank You, ${s.recipient_name}!`,thinking_of_you:`💭 Thinking of You, ${s.recipient_name}!`},[m,p]=k.useState(h[s.card_type]||`A Special Card for ${s.recipient_name}!`),[g,x]=k.useState(""),y=`https://cardstudio.relevelup.com/c/${s.share_token}`,v=Nt({mutationFn:async()=>{if(!d)throw new Error("Recipient email is required");const j=`
${g?`

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


`:""}

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

${s.property_address?`

${s.property_address}

`:""}
`,C=async()=>{const{data:P,error:R}=await V.functions.invoke("send-connect-invite",{body:{contactEmail:d,subject:m,htmlBody:j}});if(R)throw R;if(!(P!=null&&P.success))throw new Error((P==null?void 0:P.error)||"Failed to send");return"system"};if(!n)return await C();const{data:A,error:M}=await V.functions.invoke("gmail-send",{body:{to:d,subject:m,body:j,contactId:s.contact_id||void 0}});let I=A&&A.error?A:null;if(M){I={error:"send_failed",message:M.message};const P=M.context;if(P&&typeof P.json=="function")try{I=await P.clone().json()}catch{}}if(I){if(I.error==="insufficient_scope"||I.error==="no_integration")return await C(),ae.warning("Sent using system email — reconnect Gmail in Integrations to send from your own inbox.",{duration:8e3}),"system";throw new Error(I.message||I.error||"Failed to send")}if(!(A!=null&&A.success))throw new Error("Failed to send");return"gmail"},onSuccess:async j=>{await V.from("sendable_cards").update({sent_at:new Date().toISOString(),sent_via:j==="gmail"?"gmail":"system"}).eq("id",s.id),a.invalidateQueries({queryKey:["sendable-cards"]}),ae.success(`Card sent to ${d}!`),l(!1)},onError:j=>{ae.error(j.message||"Failed to send email")}}),_=r==="mass_email"?"Mass Email":r==="gmail"?"Gmail":"Email";return e.jsxs(zs,{open:i,onOpenChange:l,children:[e.jsx(yl,{asChild:!0,children:e.jsx($,{variant:"outline",size:"sm",className:"gap-1 text-xs",children:e.jsx(Wr,{className:"h-3 w-3"})})}),e.jsxs(Rs,{className:"sm:max-w-md",children:[e.jsx(Vs,{children:e.jsxs($s,{children:["Send Card via ",_]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"gmail-to",children:"To"}),e.jsx(I7t,{value:d,onChange:u,userId:t==null?void 0:t.id,placeholder:"Search contacts or type an email..."}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Pick from your Agent OS contacts, or type any email address."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Subject"}),e.jsx(be,{value:m,onChange:j=>p(j.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Personal Note (optional)"}),e.jsx(Ls,{value:g,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:[r==="mass_email"?e.jsx(e.Fragment,{children:"Sending via your verified Mass Email sender (Gmail isn't connected)."}):e.jsx(e.Fragment,{children:"The email will include a beautiful button linking to your card at:"}),e.jsx("br",{}),e.jsx("span",{className:"font-mono text-foreground",children:y})]}),e.jsx($,{onClick:()=>v.mutate(),disabled:!d||v.isPending,className:"w-full gap-2",children:v.isPending?e.jsxs(e.Fragment,{children:[e.jsx(Jt,{className:"h-4 w-4 animate-spin"})," Sending..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Wr,{className:"h-4 w-4"})," Send Card"]})})]})]})]})}function QFn({card:s}){const t=ls(),[n,r]=k.useState(!1),[a,i]=k.useState(!1),[l,o]=k.useState(s.recipient_name),[c,d]=k.useState(s.property_address||""),[u,h]=k.useState(s.home_anniversary_date||""),[m,p]=k.useState(s.custom_message||""),[g,x]=k.useState(s.template),[y,v]=k.useState(s.property_photo_url),[_,j]=k.useState(s.video_url||null),C=M=>{M&&(o(s.recipient_name),d(s.property_address||""),h(s.home_anniversary_date||""),p(s.custom_message||""),x(s.template),v(s.property_photo_url),j(s.video_url||null)),r(M)},A=async()=>{if(!l.trim()){ae.error("Recipient name is required");return}i(!0);try{const{error:M}=await V.from("sendable_cards").update({recipient_name:l.trim(),property_address:c.trim()||null,home_anniversary_date:u||null,custom_message:m.trim()||null,template:g,property_photo_url:y||null,video_url:_||null}).eq("id",s.id);if(M)throw M;t.invalidateQueries({queryKey:["sendable-cards"]}),ae.success("Card updated"),r(!1)}catch(M){ae.error(M.message||"Failed to update card")}finally{i(!1)}};return e.jsxs(zs,{open:n,onOpenChange:C,children:[e.jsx(yl,{asChild:!0,children:e.jsx($,{variant:"outline",size:"sm",className:"gap-1 text-xs",children:e.jsx(ui,{className:"h-3 w-3"})})}),e.jsxs(Rs,{className:"sm:max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(Vs,{children:e.jsx($s,{children:"Edit Card"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Recipient Name"}),e.jsx(be,{value:l,onChange:M=>o(M.target.value),placeholder:"John & Jane Smith"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Property Address"}),e.jsx(be,{value:c,onChange:M=>d(M.target.value),placeholder:"123 Main St, Austin, TX"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Home Anniversary Date"}),e.jsx(be,{type:"date",value:u,onChange:M=>h(M.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Personal Message (optional)"}),e.jsx(Ls,{value:m,onChange:M=>p(M.target.value),placeholder:"Wishing you many more happy years in your beautiful home!",rows:3})]}),e.jsx(QVt,{photoUrl:y,videoUrl:_,onPhotoChange:v,onVideoChange:j,contactId:s.contact_id}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Template Style"}),e.jsx("div",{className:"grid grid-cols-3 gap-2",children:["elegant","bold","warm"].map(M=>e.jsxs("button",{onClick:()=>x(M),className:`p-3 rounded-lg border-2 transition-all text-center ${g===M?"border-primary bg-primary/5":"border-border hover:border-primary/30"}`,children:[e.jsx("div",{className:`h-12 rounded-md mb-2 ${M==="elegant"?"bg-gradient-to-br from-slate-100 to-slate-200 dark:from-slate-800 dark:to-slate-700":M==="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:M})]},M))})]}),e.jsx($,{onClick:A,disabled:!l.trim()||a,className:"w-full gap-2",children:a?e.jsxs(e.Fragment,{children:[e.jsx(Jt,{className:"h-4 w-4 animate-spin"})," Saving..."]}):"Save Changes"})]})]})]})}function JFn(){const{user:s}=ks(),t=ls(),[n,r]=k.useState(""),[a,i]=Jc(),l=a.get("cardType"),o=a.get("contactId"),c=a.get("name"),d=a.get("address"),u=a.get("date"),h=!!l,{data:m,isLoading:p}=pt({queryKey:["sendable-cards",s==null?void 0:s.id],queryFn:async()=>{const{data:j,error:C}=await V.from("sendable_cards").select("*").eq("owner_user_id",s.id).order("created_at",{ascending:!1});if(C)throw C;return j},enabled:!!(s!=null&&s.id)}),g=Nt({mutationFn:async j=>{const{error:C}=await V.from("sendable_cards").delete().eq("id",j);if(C)throw C},onSuccess:()=>{t.invalidateQueries({queryKey:["sendable-cards"]}),ae.success("Card deleted")}}),x=j=>{const C=`https://cardstudio.relevelup.com/c/${j}`;navigator.clipboard.writeText(C),ae.success("Share link copied!")},y=m==null?void 0:m.filter(j=>{var C;return!n||j.recipient_name.toLowerCase().includes(n.toLowerCase())||((C=j.property_address)==null?void 0:C.toLowerCase().includes(n.toLowerCase()))}),v={elegant:"Elegant",bold:"Bold",warm:"Warm"},_={home_anniversary:"Home Anniversary",wedding_anniversary:"Wedding Anniversary",just_listed:"Just Listed",just_sold:"Just Sold",congratulations:"Congratulations",birthday:"Birthday",holiday:"Holiday",thank_you:"Thank You",thinking_of_you:"Thinking of You"};return e.jsx(Xs,{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(Lbt,{initialOpen:h,initialCardType:l,initialContactId:o||void 0,initialRecipientName:c||void 0,initialAddress:d||void 0,initialDate:u||void 0,onOpenChange:()=>i({})})]}),e.jsxs("div",{className:"relative max-w-sm",children:[e.jsx(Yr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{placeholder:"Search cards...",value:n,onChange:j=>r(j.target.value),className:"pl-9"})]}),p?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:[1,2,3].map(j=>e.jsx(we,{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"})]})},j))}):y!=null&&y.length?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:y.map(j=>e.jsxs(we,{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 ${j.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":j.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:[j.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"})]}),j.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%)]"})]}),j.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:j.card_type==="home_anniversary"?"🏡":j.card_type==="wedding_anniversary"?"💍":j.card_type==="birthday"?"🎂":j.card_type==="just_sold"?"🎉":j.card_type==="just_listed"?"🏠":j.card_type==="thank_you"?"💐":j.card_type==="congratulations"?"🏆":j.card_type==="holiday"?"🎄":j.card_type==="thinking_of_you"?"💭":"✉️"}),e.jsx("p",{className:`text-[10px] uppercase tracking-[0.2em] mb-1 ${j.template==="bold"?"text-white/70":"text-muted-foreground"}`,children:_[j.card_type]||j.card_type}),e.jsx("p",{className:`font-semibold text-base ${j.template==="bold"?"text-white":"text-foreground"}`,children:j.recipient_name}),j.property_address&&e.jsx("p",{className:`text-xs mt-1 ${j.template==="bold"?"text-white/60":"text-muted-foreground"}`,children:j.property_address})]}),e.jsx("div",{className:"absolute top-2 right-2 z-10",children:e.jsx(qe,{variant:j.template==="bold"?"outline":"secondary",className:`text-[10px] ${j.template==="bold"?"border-white/30 text-white/80":""}`,children:v[j.template]||j.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(ba,{className:"h-3 w-3"}),j.view_count," views"]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:Zc(new Date(j.created_at),{addSuffix:!0})})]}),j.sent_at&&e.jsxs("p",{className:"text-[10px] text-emerald-600 mb-2",children:["Sent ",Ys(new Date(j.sent_at),"MMM d, yyyy")," via ",j.sent_via]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsxs($,{variant:"outline",size:"sm",className:"flex-1 gap-1 text-xs",onClick:()=>x(j.share_token),children:[e.jsx(Da,{className:"h-3 w-3"}),"Copy Link"]}),e.jsx(QFn,{card:j}),e.jsx(XFn,{card:j}),e.jsx($,{variant:"outline",size:"sm",className:"gap-1 text-xs",onClick:()=>window.open(`https://cardstudio.relevelup.com/c/${j.share_token}`,"_blank"),children:e.jsx(Ir,{className:"h-3 w-3"})}),e.jsx($,{variant:"ghost",size:"sm",className:"text-destructive hover:text-destructive gap-1 text-xs",onClick:()=>g.mutate(j.id),children:e.jsx(Un,{className:"h-3 w-3"})})]})]})]},j.id))}):e.jsx(we,{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(pn,{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(Lbt,{initialOpen:h,initialCardType:l,initialContactId:o||void 0,initialRecipientName:c||void 0,initialAddress:d||void 0,initialDate:u||void 0,onOpenChange:()=>i({})})]})})]})})}const Qae=[{id:"mls",label:"MLS Description",tag:"Standard",icon:ua,accent:"from-sky-500 to-cyan-500",desc:"Polished MLS-ready listing",category:"listing"},{id:"luxury",label:"Luxury MLS",tag:"Premium",icon:ky,accent:"from-amber-500 to-orange-500",desc:"Evocative, high-end voice",category:"listing"},{id:"short",label:"Short MLS",tag:"Concise",icon:ix,accent:"from-violet-500 to-fuchsia-500",desc:"Punchy 60–90 words",category:"listing"},{id:"openHouse",label:"Open House",tag:"Promo",icon:x2,accent:"from-emerald-500 to-teal-500",desc:"Friendly invite copy",category:"listing",extras:["openHouse"]},{id:"newConstruction",label:"New Construction",tag:"Build",icon:PK,accent:"from-rose-500 to-pink-500",desc:"Builder-focused angle",category:"listing",extras:["newConstruction"]},{id:"investment",label:"Investment",tag:"ROI",icon:mc,accent:"from-indigo-500 to-blue-500",desc:"Cap rate & income hooks",category:"listing",extras:["investment"]},{id:"facebookPost",label:"Facebook Post",tag:"Social",icon:ax,accent:"from-blue-600 to-blue-400",desc:"Engaging FB caption",category:"social"},{id:"instagramPost",label:"Instagram Post",tag:"Social",icon:Sf,accent:"from-pink-500 via-fuchsia-500 to-orange-400",desc:"IG caption + hashtags",category:"social"},{id:"linkedinPost",label:"LinkedIn Post",tag:"Social",icon:dv,accent:"from-sky-700 to-sky-500",desc:"Professional tone",category:"social"},{id:"justListed",label:"Just Listed",tag:"Announce",icon:xm,accent:"from-emerald-500 to-green-500",desc:"Hit the market announcement",category:"social"},{id:"comingSoon",label:"Coming Soon",tag:"Tease",icon:sa,accent:"from-amber-500 to-yellow-500",desc:"Build pre-market buzz",category:"social",extras:["comingSoon"]},{id:"priceImprovement",label:"Price Improvement",tag:"Update",icon:lk,accent:"from-orange-500 to-red-500",desc:"New price announcement",category:"social",extras:["priceImprovement"]},{id:"openHousePost",label:"Open House Post",tag:"Event",icon:fd,accent:"from-teal-500 to-emerald-500",desc:"Social invite to OH",category:"social",extras:["openHouse"]},{id:"underContract",label:"Under Contract",tag:"Status",icon:AK,accent:"from-indigo-500 to-purple-500",desc:"Pending celebration",category:"social",extras:["underContract"]},{id:"justSold",label:"Just Sold",tag:"Celebrate",icon:jg,accent:"from-fuchsia-500 to-pink-500",desc:"Sold success post",category:"social",extras:["sold"]},{id:"propertyTourScript",label:"Property Tour",tag:"Script",icon:ia,accent:"from-red-500 to-rose-500",desc:"Full walkthrough script",category:"video",extras:["signoff"]},{id:"reelScript",label:"Reel Script",tag:"Short",icon:em,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:w2,accent:"from-violet-500 to-purple-500",desc:"5 scroll-stopping hooks",category:"video",extras:["vibe"]},{id:"luxuryWalkthrough",label:"Luxury Walkthrough",tag:"Premium",icon:ky,accent:"from-amber-500 to-yellow-500",desc:"Cinematic, refined tone",category:"video",extras:["signoff"]},{id:"droneScript",label:"Drone Script",tag:"Aerial",icon:HK,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:Si,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:pn,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:Xz,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:Xn,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:lk,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:p3,accent:"from-fuchsia-500 to-pink-500",desc:"Sold announcement email",category:"email",extras:["sold","signoff"]},{id:"neighborhoodEmail",label:"Neighborhood Email",tag:"Nurture",icon:Si,accent:"from-sky-500 to-indigo-500",desc:"Area update / market touch",category:"email",extras:["neighborhood","signoff"]}];function e7n(){var jh,Mu,dh,Jr,Uo,fc,Lc,Ss,wa,Ci,fa;const{user:s}=ks(),[t,n]=k.useState(""),[r,a]=k.useState(""),[i,l]=k.useState([]),[o,c]=k.useState(""),[d,u]=k.useState([]),[h,m]=k.useState(""),[p,g]=k.useState(""),[x,y]=k.useState(""),[v,_]=k.useState(""),[j,C]=k.useState(""),[A,M]=k.useState(""),[I,P]=k.useState(""),[R,O]=k.useState(null),[B,U]=k.useState(""),[G,H]=k.useState(""),[Y,se]=k.useState(""),[ee,oe]=k.useState(""),[me,Q]=k.useState(""),[te,le]=k.useState(""),[fe,_e]=k.useState(""),[ve,he]=k.useState(""),[Se,Te]=k.useState(""),[Ie,Ue]=k.useState(""),[Be,je]=k.useState(""),[Ye,Ee]=k.useState(""),[Re,ke]=k.useState(""),[Fe,Oe]=k.useState(""),[Ge,yt]=k.useState(""),[tt,ut]=k.useState(""),[nt,et]=k.useState(""),[at,wt]=k.useState(""),[rt,Ft]=k.useState(""),[Ut,Is]=k.useState(""),[xs,st]=k.useState(""),[dt,jt]=k.useState(""),[gt,rs]=k.useState(""),[Ns,us]=k.useState(""),[Bs,Ts]=k.useState(""),[Fn,An]=k.useState("listing"),[js,In]=k.useState("mls"),[un,jr]=k.useState({}),[Ln,Sr]=k.useState({}),[Qn,En]=k.useState(!1),[pr,xn]=k.useState(!1),Ar=zn=>{An(zn);const Rr=Qae.find(ja=>ja.category===zn);Rr&&In(Rr.id)},{data:Zr}=pt({queryKey:["listing-studio-listings",s==null?void 0:s.id],enabled:!!(s!=null&&s.id)&&Qn,queryFn:async()=>{const{data:zn,error:Rr}=await V.from("listings").select("id, property_address, city, state, price, bedrooms, bathrooms, square_footage, property_type, description").eq("agent_id",s.id).order("created_at",{ascending:!1}).limit(50);if(Rr)throw Rr;return zn||[]}}),dn=()=>{const zn=o.trim();zn&&(l(Rr=>[...Rr,zn]),c(""))},Kt=zn=>l(Rr=>Rr.filter((ja,Il)=>Il!==zn)),Er=zn=>{var Rr,ja,Il,zo;O(zn.id),n(zn.property_address||""),M(zn.city||""),P(zn.state||""),_(((Rr=zn.price)==null?void 0:Rr.toString())||""),m(((ja=zn.bedrooms)==null?void 0:ja.toString())||""),g(((Il=zn.bathrooms)==null?void 0:Il.toString())||""),y(((zo=zn.square_footage)==null?void 0:zo.toString())||""),C(zn.property_type||""),a(zn.description||""),En(!1),ae.success("Listing imported")},ti=async zn=>{if(!(!zn.target.files||!(s!=null&&s.id))){xn(!0);try{const Rr=[];for(const ja of Array.from(zn.target.files).slice(0,10)){const Il=`${s.id}/${Date.now()}-${ja.name.replace(/[^\w.-]/g,"_")}`,{error:zo}=await V.storage.from("listing-photos").upload(Il,ja,{upsert:!1});if(zo){console.error(zo);continue}const{data:Hl}=V.storage.from("listing-photos").getPublicUrl(Il);Rr.push(Hl.publicUrl)}u(ja=>[...ja,...Rr]),Rr.length&&ae.success(`${Rr.length} photo(s) uploaded`)}catch(Rr){ae.error(Rr.message||"Photo upload failed")}finally{xn(!1)}}},Ba=Qae.find(zn=>zn.id===js),lo=async zn=>{var ja,Il,zo;const Rr=Qae.find(Hl=>Hl.id===zn);if(!t.trim()&&!r.trim()&&i.length===0){ae.error("Add a property address, MLS remarks, or features first");return}if((ja=Rr.extras)!=null&&ja.includes("openHouse")&&(!B||!G||!Y)){ae.error("Add the open house date, start and end time");return}if((Il=Rr.extras)!=null&&Il.includes("priceImprovement")&&(!ee||!me)){ae.error("Add previous and new price");return}if((zo=Rr.extras)!=null&&zo.includes("sold")&&!te){ae.error("Add the sold price");return}In(zn),Sr(Hl=>({...Hl,[zn]:!0}));try{const{data:Hl,error:Cf}=await V.functions.invoke("listing-studio-generate",{body:{copyType:zn,propertyAddress:t,mlsRemarks:r,features:i,photoUrls:d,listingId:R,bedrooms:h?Number(h):null,bathrooms:p?Number(p):null,squareFootage:x?Number(x):null,price:v?Number(v):null,propertyType:j||null,city:A||null,state:I||null,openHouseDate:B||null,openHouseStart:G||null,openHouseEnd:Y||null,previousPrice:ee?Number(ee):null,newPrice:me?Number(me):null,soldPrice:te?Number(te):null,soldDate:fe||null,comingSoonDate:ve||null,builderName:Se||null,yearBuilt:Ie?Number(Ie):null,warrantyInfo:Be||null,monthlyRent:Ye?Number(Ye):null,capRate:Re||null,occupancy:Fe||null,daysOnMarket:Ge?Number(Ge):null,offerCount:tt?Number(tt):null,originalListPrice:nt?Number(nt):null,soldDaysOnMarket:at?Number(at):null,commissionOffered:rt||null,refreshments:Ut||null,vibe:xs||null,neighborhoodHighlights:dt||null,agentName:gt||null,agentBrokerage:Ns||null,agentContact:Bs||null}});if(Cf)throw Cf;if(Hl!=null&&Hl.error)throw new Error(Hl.error);jr(oi=>({...oi,[zn]:Hl.content}))}catch(Hl){ae.error(Hl.message||"Generation failed")}finally{Sr(Hl=>({...Hl,[zn]:!1}))}},Yn=zn=>{navigator.clipboard.writeText(zn),ae.success("Copied to clipboard")},Hr=Ba.icon,Ur=un[js]?un[js].trim().split(/\s+/).length:0,Ei=zn=>e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-3",children:Qae.filter(Rr=>Rr.category===zn).map(Rr=>{const ja=Rr.icon,Il=js===Rr.id,zo=!!un[Rr.id];return e.jsxs("button",{onClick:()=>In(Rr.id),className:Ot("relative text-left p-4 rounded-2xl border transition-all overflow-hidden group",Il?"border-primary shadow-lg shadow-primary/10 bg-card":"border-border/60 hover:border-border bg-card/50 hover:bg-card"),children:[Il&&e.jsx("div",{className:Ot("absolute inset-0 opacity-[0.07] bg-gradient-to-br",Rr.accent)}),e.jsxs("div",{className:"relative space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{className:Ot("h-9 w-9 rounded-xl grid place-items-center text-white bg-gradient-to-br shadow-sm",Rr.accent),children:e.jsx(ja,{className:"h-4 w-4"})}),zo&&e.jsx("div",{className:"h-5 w-5 rounded-full bg-emerald-500/15 text-emerald-600 grid place-items-center",children:e.jsx(ma,{className:"h-3 w-3"})})]}),e.jsxs("div",{children:[e.jsx("div",{className:"font-semibold text-sm",children:Rr.label}),e.jsx("div",{className:"text-xs text-muted-foreground line-clamp-1",children:Rr.desc})]})]})]},Rr.id)})}),fo=(jh=Ba.extras)==null?void 0:jh.includes("openHouse"),co=(Mu=Ba.extras)==null?void 0:Mu.includes("priceImprovement"),Tn=(dh=Ba.extras)==null?void 0:dh.includes("sold"),Mr=(Jr=Ba.extras)==null?void 0:Jr.includes("comingSoon"),Aa=(Uo=Ba.extras)==null?void 0:Uo.includes("newConstruction"),Lo=(fc=Ba.extras)==null?void 0:fc.includes("investment"),Ac=(Lc=Ba.extras)==null?void 0:Lc.includes("underContract"),vl=(Ss=Ba.extras)==null?void 0:Ss.includes("brokerOpen"),Ol=(wa=Ba.extras)==null?void 0:wa.includes("vibe"),To=(Ci=Ba.extras)==null?void 0:Ci.includes("neighborhood"),_a=(fa=Ba.extras)==null?void 0:fa.includes("signoff"),$o=fo||co||Tn||Mr||Aa||Lo||Ac||vl||Ol||To||_a;return e.jsx(Xs,{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(kn,{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(zs,{open:Qn,onOpenChange:En,children:[e.jsx(yl,{asChild:!0,children:e.jsxs($,{size:"lg",variant:"secondary",className:"shadow-lg shadow-fuchsia-500/10",children:[e.jsx(ea,{className:"h-4 w-4 mr-2"}),"Import from Listings"]})}),e.jsxs(Rs,{className:"max-w-2xl max-h-[80vh] overflow-y-auto",children:[e.jsx(Vs,{children:e.jsx($s,{children:"Import from Listing Exchange"})}),e.jsxs("div",{className:"space-y-2 mt-2",children:[!(Zr!=null&&Zr.length)&&e.jsx("p",{className:"text-sm text-muted-foreground py-8 text-center",children:"No listings found yet."}),Zr==null?void 0:Zr.map(zn=>e.jsxs("button",{onClick:()=>Er(zn),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:zn.property_address||"Untitled listing"}),e.jsxs("div",{className:"text-sm text-muted-foreground mt-0.5",children:[[zn.city,zn.state].filter(Boolean).join(", "),zn.price?` · $${Number(zn.price).toLocaleString()}`:"",zn.bedrooms?` · ${zn.bedrooms}bd`:"",zn.bathrooms?` · ${zn.bathrooms}ba`:""]})]},zn.id))]})]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-5 gap-6",children:[e.jsx(we,{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(ua,{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(re,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Address"}),e.jsx(be,{value:t,onChange:zn=>n(zn.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(re,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"City"}),e.jsx(be,{value:A,onChange:zn=>M(zn.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"State"}),e.jsx(be,{value:I,onChange:zn=>P(zn.target.value)})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Price"}),e.jsx(be,{type:"number",value:v,onChange:zn=>_(zn.target.value),placeholder:"$"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Type"}),e.jsx(be,{value:j,onChange:zn=>C(zn.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(re,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Beds"}),e.jsx(be,{type:"number",value:h,onChange:zn=>m(zn.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Baths"}),e.jsx(be,{type:"number",step:"0.5",value:p,onChange:zn=>g(zn.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Sqft"}),e.jsx(be,{type:"number",value:x,onChange:zn=>y(zn.target.value)})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"MLS Remarks / Notes"}),e.jsx(Ls,{value:r,onChange:zn=>a(zn.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(re,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Features"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(be,{value:o,onChange:zn=>c(zn.target.value),onKeyDown:zn=>zn.key==="Enter"&&(zn.preventDefault(),dn()),placeholder:"e.g. Quartz countertops"}),e.jsx($,{type:"button",size:"icon",variant:"secondary",onClick:dn,children:e.jsx(nn,{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((zn,Rr)=>e.jsxs(qe,{variant:"secondary",className:"pl-3 pr-1 py-1 gap-1",children:[zn,e.jsx("button",{onClick:()=>Kt(Rr),className:"ml-0.5 p-0.5 hover:bg-background/60 rounded-full",children:e.jsx(mr,{className:"h-3 w-3"})})]},Rr))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{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(gb,{className:"h-4 w-4"}),pr?"Uploading…":"Click to upload photos",e.jsx("input",{type:"file",accept:"image/*",multiple:!0,onChange:ti,disabled:pr,className:"hidden"})]}),d.length>0&&e.jsx("div",{className:"grid grid-cols-4 gap-2 mt-2",children:d.map((zn,Rr)=>e.jsxs("div",{className:"relative aspect-square rounded-lg overflow-hidden group",children:[e.jsx("img",{src:zn,alt:"",className:"w-full h-full object-cover"}),e.jsx("button",{onClick:()=>u(ja=>ja.filter((Il,zo)=>zo!==Rr)),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(mr,{className:"h-3 w-3"})})]},Rr))})]}),$o&&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(kn,{className:"h-4 w-4 text-primary"}),e.jsxs("div",{className:"text-sm font-semibold",children:["Extra info for ",Ba.label]})]}),fo&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Date"}),e.jsx(be,{type:"date",value:B,onChange:zn=>U(zn.target.value)})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Start"}),e.jsx(be,{type:"time",value:G,onChange:zn=>H(zn.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"End"}),e.jsx(be,{type:"time",value:Y,onChange:zn=>se(zn.target.value)})]})]})]}),co&&e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Previous Price"}),e.jsx(be,{type:"number",value:ee,onChange:zn=>oe(zn.target.value),placeholder:"$"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"New Price"}),e.jsx(be,{type:"number",value:me,onChange:zn=>Q(zn.target.value),placeholder:"$"})]})]}),Tn&&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(re,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Sold Price"}),e.jsx(be,{type:"number",value:te,onChange:zn=>le(zn.target.value),placeholder:"$"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Sold Date"}),e.jsx(be,{type:"date",value:fe,onChange:zn=>_e(zn.target.value)})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Original List Price (optional)"}),e.jsx(be,{type:"number",value:nt,onChange:zn=>et(zn.target.value),placeholder:"$"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Days on Market (optional)"}),e.jsx(be,{type:"number",value:at,onChange:zn=>wt(zn.target.value)})]})]})]}),Mr&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Expected Live Date (optional)"}),e.jsx(be,{type:"date",value:ve,onChange:zn=>he(zn.target.value)})]}),Aa&&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(re,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Builder Name"}),e.jsx(be,{value:Se,onChange:zn=>Te(zn.target.value),placeholder:"ABC Homes"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Year Built"}),e.jsx(be,{type:"number",value:Ie,onChange:zn=>Ue(zn.target.value),placeholder:"2026"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Warranty / Energy / Smart-home (optional)"}),e.jsx(be,{value:Be,onChange:zn=>je(zn.target.value),placeholder:"10-yr structural, ENERGY STAR, smart-home pkg"})]})]}),Lo&&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(re,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Monthly Rent (optional)"}),e.jsx(be,{type:"number",value:Ye,onChange:zn=>Ee(zn.target.value),placeholder:"$"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Cap Rate (optional)"}),e.jsx(be,{value:Re,onChange:zn=>ke(zn.target.value),placeholder:"6.5%"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Occupancy"}),e.jsxs("select",{value:Fe,onChange:zn=>Oe(zn.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"})]})]})]}),Ac&&e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Days on Market (optional)"}),e.jsx(be,{type:"number",value:Ge,onChange:zn=>yt(zn.target.value),placeholder:"e.g. 3"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"# of Offers (optional)"}),e.jsx(be,{type:"number",value:tt,onChange:zn=>ut(zn.target.value),placeholder:"e.g. 5"})]})]}),vl&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Commission / Co-op Offered (optional)"}),e.jsx(be,{value:rt,onChange:zn=>Ft(zn.target.value),placeholder:"2.5% buyer agent commission"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Refreshments / Perks (optional)"}),e.jsx(be,{value:Ut,onChange:zn=>Is(zn.target.value),placeholder:"Lunch + raffle for $100 gift card"})]})]}),Ol&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Vibe / Tone"}),e.jsxs("select",{value:xs,onChange:zn=>st(zn.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"})]})]}),To&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Nearby Highlights (optional)"}),e.jsx(Ls,{value:dt,onChange:zn=>jt(zn.target.value),rows:3,placeholder:"Top schools, parks, coffee shops, restaurants, commute, walkability…"})]}),_a&&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(re,{className:"text-xs font-medium text-muted-foreground",children:"Agent Name"}),e.jsx(be,{value:gt,onChange:zn=>rs(zn.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-xs font-medium text-muted-foreground",children:"Brokerage"}),e.jsx(be,{value:Ns,onChange:zn=>us(zn.target.value)})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-xs font-medium text-muted-foreground",children:"Phone / Email"}),e.jsx(be,{value:Bs,onChange:zn=>Ts(zn.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:ea},{key:"social",label:"Social Media",icon:Sf},{key:"video",label:"Video Scripts",icon:ia},{key:"email",label:"Email Marketing",icon:pn}].map(zn=>{const Rr=zn.icon,ja=Fn===zn.key;return e.jsxs("button",{onClick:()=>Ar(zn.key),className:Ot("flex-1 flex items-center justify-center gap-2 px-4 py-2.5 rounded-lg text-sm font-medium transition-all",ja?"bg-card shadow-sm text-foreground border border-border/60":"text-muted-foreground hover:text-foreground hover:bg-background/50"),children:[e.jsx(Rr,{className:"h-4 w-4"}),zn.label]},zn.key)})}),Ei(Fn),e.jsxs(we,{className:"border-border/60 shadow-sm overflow-hidden",children:[e.jsx("div",{className:Ot("h-1 bg-gradient-to-r",Ba.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:Ot("h-10 w-10 rounded-xl grid place-items-center text-white bg-gradient-to-br",Ba.accent),children:e.jsx(Hr,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsxs("div",{className:"font-semibold flex items-center gap-2",children:[Ba.label,e.jsx(qe,{variant:"outline",className:"text-[10px] font-normal",children:Ba.tag})]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:un[js]?`${Ur} words`:"Ready to generate"})]})]}),e.jsxs("div",{className:"flex gap-2",children:[un[js]&&e.jsxs($,{variant:"outline",size:"sm",onClick:()=>Yn(un[js]),children:[e.jsx(Da,{className:"h-4 w-4 mr-2"})," Copy"]}),e.jsx($,{onClick:()=>lo(js),disabled:Ln[js],className:Ot("shadow-lg shadow-primary/10 bg-gradient-to-r text-white border-0 hover:opacity-90",Ba.accent),size:"sm",children:Ln[js]?e.jsxs(e.Fragment,{children:[e.jsx(Jt,{className:"h-4 w-4 mr-2 animate-spin"})," Generating"]}):un[js]?e.jsxs(e.Fragment,{children:[e.jsx(yo,{className:"h-4 w-4 mr-2"})," Regenerate"]}):e.jsxs(e.Fragment,{children:[e.jsx(vf,{className:"h-4 w-4 mr-2"})," Generate"]})})]})]}),un[js]?e.jsx(Ls,{value:un[js],onChange:zn=>jr(Rr=>({...Rr,[js]:zn.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:Ot("mx-auto h-14 w-14 rounded-2xl grid place-items-center text-white bg-gradient-to-br mb-4",Ba.accent),children:e.jsx(vf,{className:"h-6 w-6"})}),e.jsxs("div",{className:"font-medium mb-1",children:["Generate a ",Ba.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 WG({delay:s,x:t,y:n,size:r}){return e.jsx(_r.div,{className:"absolute rounded-full bg-slate-300/30 dark:bg-slate-500/20",style:{left:t,top:n,width:r,height:r},animate:{y:[0,-20,0],opacity:[.3,.7,.3],scale:[1,1.2,1]},transition:{duration:4,delay:s,repeat:1/0,ease:"easeInOut"}})}function t7n(s){const{cardType:t,recipientName:n,propertyAddress:r,anniversaryYears:a,customMessage:i,agentName:l,agentPhotoUrl:o,agentPhone:c,agentEmail:d,agentBrokerage:u,propertyPhotoUrl:h,videoUrl:m}=s,p=HV[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(_r.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(_r.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(WG,{delay:0,x:"15%",y:"20%",size:8}),e.jsx(WG,{delay:1,x:"80%",y:"30%",size:6}),e.jsx(WG,{delay:2,x:"60%",y:"70%",size:10}),e.jsx(WG,{delay:.5,x:"25%",y:"80%",size:7}),e.jsx(WG,{delay:1.5,x:"70%",y:"15%",size:5})]}),e.jsxs(_r.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(_r.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(_r.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(_r.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(_r.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:p.icon})]}),t==="home_anniversary"&&a!==null&&a>0&&e.jsx(_r.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(_r.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:p.title[0]}),p.title[1]&&e.jsx(_r.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:p.title[1]}),e.jsxs(_r.div,{initial:{opacity:0},animate:{opacity:1},transition:{duration:.5,delay:1},children:[e.jsx("p",{className:"text-xl font-medium text-slate-700 dark:text-slate-200 mb-1",children:n}),r&&e.jsx("p",{className:"text-sm text-slate-400 dark:text-slate-500 mb-6",children:r})]}),e.jsx(_r.div,{className:"h-px bg-gradient-to-r from-transparent via-slate-300 dark:via-slate-600 to-transparent mx-auto mb-6",initial:{width:0},animate:{width:"80%"},transition:{duration:.8,delay:1.1},style:{margin:"0 auto 1.5rem"}}),h&&e.jsx(_r.div,{className:"mb-6 rounded-xl overflow-hidden shadow-md",initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},transition:{delay:1.15,duration:.5},children:e.jsx("img",{src:h,alt:"Property",className:"w-full h-48 object-cover"})}),m&&e.jsx(_r.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:`${m}?autoplay=false&responsive=true`,className:"w-full aspect-video",allow:"autoplay; encrypted-media",allowFullScreen:!0})}),e.jsx(_r.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||p.defaultMessage}),e.jsxs(_r.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(_r.img,{src:o,alt:l,className:"h-12 w-12 rounded-full object-cover ring-2 ring-slate-200 dark:ring-slate-700 shadow-md",whileHover:{scale:1.1}}):e.jsx("div",{className:"h-12 w-12 rounded-full bg-gradient-to-br from-slate-200 to-blue-100 dark:from-slate-700 dark:to-slate-600 flex items-center justify-center shadow-md",children:e.jsx("span",{className:"text-sm font-semibold text-slate-600 dark:text-slate-300",children:l.charAt(0)})}),e.jsxs("div",{className:"text-left",children:[e.jsx("p",{className:"text-sm font-semibold text-slate-700 dark:text-slate-200",children:l}),u&&e.jsx("p",{className:"text-xs text-slate-400 dark:text-slate-500",children:u})]})]}),e.jsxs("div",{className:"flex items-center justify-center gap-3 mt-4",children:[c&&e.jsxs(_r.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(ka,{className:"h-3.5 w-3.5"})," Call"]}),d&&e.jsxs(_r.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(pn,{className:"h-3.5 w-3.5"})," Email"]})]})]})]})]}),e.jsx(_r.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 JDe({delay:s,x:t,y:n,color:r,size:a}){return e.jsx(_r.div,{className:`absolute rounded-full blur-2xl ${r}`,style:{left:t,top:n,width:a,height:a},animate:{scale:[1,1.4,1],opacity:[.2,.5,.2]},transition:{duration:5,delay:s,repeat:1/0,ease:"easeInOut"}})}function KG({delay:s,x:t,y:n}){return e.jsx(_r.div,{className:"absolute text-white/30 text-lg",style:{left:t,top:n},animate:{opacity:[0,1,0],scale:[.5,1,.5],rotate:[0,180,360]},transition:{duration:3,delay:s,repeat:1/0,ease:"easeInOut"},children:"✦"})}const Rbt={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 s7n(s){const{cardType:t,recipientName:n,propertyAddress:r,anniversaryYears:a,customMessage:i,agentName:l,agentPhotoUrl:o,agentPhone:c,agentEmail:d,agentBrokerage:u,propertyPhotoUrl:h,videoUrl:m}=s,p=HV[t],g=Rbt[t]||Rbt.home_anniversary;return e.jsxs("div",{className:`min-h-screen bg-gradient-to-br ${g.bg} flex items-center justify-center p-4 overflow-hidden relative`,children:[e.jsx(JDe,{delay:0,x:"10%",y:"10%",color:g.orbs[0],size:200}),e.jsx(JDe,{delay:1,x:"70%",y:"60%",color:g.orbs[1],size:180}),e.jsx(JDe,{delay:2,x:"50%",y:"20%",color:g.orbs[2],size:150}),e.jsx(KG,{delay:0,x:"20%",y:"25%"}),e.jsx(KG,{delay:.8,x:"75%",y:"15%"}),e.jsx(KG,{delay:1.6,x:"85%",y:"65%"}),e.jsx(KG,{delay:2.4,x:"10%",y:"75%"}),e.jsx(KG,{delay:.4,x:"45%",y:"85%"}),e.jsxs(_r.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(_r.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(_r.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(_r.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(_r.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:p.icon})]}),t==="home_anniversary"&&a!==null&&a>0&&e.jsxs(_r.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(_r.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(_r.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:p.title[0]}),p.title[1]&&e.jsx(_r.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:p.title[1]}),e.jsx(_r.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:p.emojis.slice(0,3).join("")}),e.jsxs(_r.div,{initial:{opacity:0},animate:{opacity:1},transition:{delay:1.1},children:[e.jsx("p",{className:"text-xl font-semibold text-white/90 mb-1",children:n}),r&&e.jsxs("p",{className:"text-sm text-violet-300/70 mb-6 flex items-center justify-center gap-1.5",children:[e.jsx(ua,{className:"h-3.5 w-3.5"}),r]})]}),h&&e.jsx(_r.div,{className:"mb-6 rounded-2xl overflow-hidden border border-white/10 shadow-lg",initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},transition:{delay:1.2,duration:.5},children:e.jsx("img",{src:h,alt:"Property",className:"w-full h-48 object-cover"})}),m&&e.jsx(_r.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:`${m}?autoplay=false&responsive=true`,className:"w-full aspect-video",allow:"autoplay; encrypted-media",allowFullScreen:!0})}),e.jsx(_r.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||p.defaultMessage})}),e.jsxs(_r.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(_r.img,{src:o,alt:l,className:"h-12 w-12 rounded-xl object-cover ring-2 ring-violet-500/40 shadow-lg",whileHover:{scale:1.1}}):e.jsx("div",{className:"h-12 w-12 rounded-xl bg-gradient-to-br from-violet-500 to-fuchsia-500 flex items-center justify-center shadow-lg",children:e.jsx("span",{className:"text-sm font-bold text-white",children:l.charAt(0)})}),e.jsxs("div",{className:"text-left",children:[e.jsx("p",{className:"text-sm font-bold text-white",children:l}),u&&e.jsx("p",{className:"text-xs text-violet-300/60",children:u})]})]}),e.jsxs("div",{className:"flex items-center justify-center gap-2 mt-5",children:[c&&e.jsxs(_r.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(ka,{className:"h-3.5 w-3.5"})," Call Me"]}),d&&e.jsxs(_r.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(pn,{className:"h-3.5 w-3.5"})," Email"]})]})]})]})]}),e.jsx(_r.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 n7n({emoji:s,delay:t,x:n,duration:r}){return e.jsx(_r.div,{className:"absolute text-2xl pointer-events-none",style:{left:n,bottom:-20},animate:{y:[0,-600],opacity:[0,1,1,0],x:[0,15,-10,5],rotate:[0,20,-15,10]},transition:{duration:r,delay:t,repeat:1/0,ease:"easeOut"},children:s})}const Dbt={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 r7n(s){const{cardType:t,recipientName:n,propertyAddress:r,anniversaryYears:a,customMessage:i,agentName:l,agentPhotoUrl:o,agentPhone:c,agentEmail:d,agentBrokerage:u,propertyPhotoUrl:h,videoUrl:m}=s,p=HV[t],g=Dbt[t]||Dbt.home_anniversary;return e.jsxs("div",{className:`min-h-screen bg-gradient-to-b ${g.bg} flex items-center justify-center p-4 overflow-hidden relative`,children:[p.emojis.map((x,y)=>e.jsx(n7n,{emoji:x,delay:y*1.2,x:`${15+y*14}%`,duration:5+y%3},y)),e.jsx(_r.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(_r.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(_r.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(_r.div,{className:`h-28 bg-gradient-to-r ${g.header} relative overflow-hidden`,children:[e.jsx(_r.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(_r.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:p.emojis[0]}),e.jsx(_r.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:p.emojis[1]}),e.jsx(_r.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:p.emojis[2]})]}),e.jsxs("div",{className:"px-8 py-8 text-center -mt-10 relative",children:[e.jsx(_r.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(_r.div,{animate:{scale:[1,1.2,1]},transition:{duration:1.5,repeat:1/0,ease:"easeInOut"},children:e.jsx("span",{className:"text-3xl",children:p.icon})})}),t==="home_anniversary"&&a!==null&&a>0&&e.jsx(_r.div,{className:"mb-3",initial:{opacity:0,scale:.8},animate:{opacity:1,scale:1},transition:{delay:.6},children:e.jsxs("span",{className:`inline-flex items-baseline gap-1.5 ${g.accent}`,children:[e.jsx(_r.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(_r.h1,{className:`text-3xl font-bold ${g.accent} mb-1`,initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:.9},children:[p.title.join(" ")," ",p.emojis[4]]}),e.jsxs(_r.div,{initial:{opacity:0},animate:{opacity:1},transition:{delay:1.1},children:[e.jsx("p",{className:`text-lg font-semibold ${g.text} mb-1`,children:n}),r&&e.jsxs("p",{className:`text-sm ${g.text} opacity-70 flex items-center justify-center gap-1 mb-5`,children:[e.jsx(Si,{className:"h-3 w-3"}),r]})]}),h&&e.jsx(_r.div,{className:"mb-5 rounded-2xl overflow-hidden border border-amber-200 shadow-md",initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},transition:{delay:1.2,duration:.5},children:e.jsx("img",{src:h,alt:"Property",className:"w-full h-48 object-cover"})}),m&&e.jsx(_r.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:`${m}?autoplay=false&responsive=true`,className:"w-full aspect-video",allow:"autoplay; encrypted-media",allowFullScreen:!0})}),e.jsx(_r.div,{className:"bg-gradient-to-br from-amber-50 to-orange-50 rounded-2xl p-5 mb-6 border border-amber-100 shadow-inner",initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:1.3},children:e.jsxs("p",{className:`text-sm ${g.text} leading-relaxed italic`,children:['"',i||p.defaultMessage,'"']})}),e.jsxs(_r.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(_r.img,{src:o,alt:l,className:"h-12 w-12 rounded-full object-cover ring-2 ring-amber-200 shadow-md",whileHover:{scale:1.1}}):e.jsx("div",{className:`h-12 w-12 rounded-full bg-gradient-to-br ${g.header} flex items-center justify-center shadow-md`,children:e.jsx("span",{className:"text-sm font-bold text-white",children:l.charAt(0)})}),e.jsxs("div",{className:"text-left",children:[e.jsx("p",{className:`text-sm font-bold ${g.accent}`,children:l}),u&&e.jsx("p",{className:`text-xs ${g.text} opacity-60`,children:u})]})]}),e.jsxs("div",{className:"flex items-center justify-center gap-2 mt-4",children:[c&&e.jsxs(_r.a,{href:`tel:${c}`,className:`flex items-center gap-1.5 px-5 py-2.5 rounded-full bg-gradient-to-r ${g.header} text-xs font-semibold text-white shadow-md`,whileHover:{scale:1.05},whileTap:{scale:.95},children:[e.jsx(ka,{className:"h-3.5 w-3.5"})," Call"]}),d&&e.jsxs(_r.a,{href:`mailto:${d}`,className:`flex items-center gap-1.5 px-5 py-2.5 rounded-full bg-gradient-to-r ${g.header} text-xs font-semibold text-white shadow-md`,whileHover:{scale:1.05},whileTap:{scale:.95},children:[e.jsx(pn,{className:"h-3.5 w-3.5"})," Email"]})]})]})]})]}),e.jsx(_r.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 Jae({delay:s,x:t,y:n,size:r,color:a}){return e.jsx(_r.div,{className:`absolute rounded-full ${a} blur-3xl`,style:{left:t,top:n,width:r,height:r},animate:{scale:[1,1.3,1],opacity:[.4,.7,.4],x:[0,20,-10,0],y:[0,-15,10,0]},transition:{duration:8,delay:s,repeat:1/0,ease:"easeInOut"}})}function e8e({delay:s,x:t,y:n,size:r}){return e.jsx(_r.div,{className:"absolute rounded-full border border-white/10",style:{left:t,top:n,width:r,height:r},animate:{scale:[1,1.2,1],opacity:[.1,.3,.1],rotate:[0,180,360]},transition:{duration:12,delay:s,repeat:1/0,ease:"linear"}})}const Obt={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 a7n(s){const{cardType:t,recipientName:n,propertyAddress:r,anniversaryYears:a,customMessage:i,agentName:l,agentPhotoUrl:o,agentPhone:c,agentEmail:d,agentBrokerage:u,propertyPhotoUrl:h,videoUrl:m}=s,p=HV[t],g=Obt[t]||Obt.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(Jae,{delay:0,x:"5%",y:"10%",size:300,color:g.mesh[0]}),e.jsx(Jae,{delay:2,x:"60%",y:"50%",size:250,color:g.mesh[1]}),e.jsx(Jae,{delay:4,x:"30%",y:"70%",size:200,color:g.mesh[2]}),e.jsx(Jae,{delay:1,x:"80%",y:"15%",size:180,color:g.mesh[0]}),e.jsx(e8e,{delay:0,x:"15%",y:"20%",size:100}),e.jsx(e8e,{delay:3,x:"70%",y:"60%",size:140}),e.jsx(e8e,{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(_r.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(_r.div,{className:`relative rounded-[28px] overflow-hidden backdrop-blur-2xl bg-white/[0.06] border border-white/[0.12] shadow-2xl ${g.glow}`,initial:{scale:.92},animate:{scale:1},transition:{duration:.6,delay:.2,type:"spring",stiffness:120},children:[e.jsx("div",{className:"relative h-[2px] bg-gradient-to-r from-transparent via-white/20 to-transparent overflow-hidden",children:e.jsx(_r.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(_r.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(_r.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(_r.span,{className:"text-5xl",animate:{scale:[1,1.08,1]},transition:{duration:2,repeat:1/0,ease:"easeInOut"},children:p.icon})]}),t==="home_anniversary"&&a!==null&&a>0&&e.jsxs(_r.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(_r.span,{className:"text-3xl font-black text-white",initial:{opacity:0},animate:{opacity:1},transition:{delay:.8},children:a}),e.jsx("span",{className:`text-[10px] font-bold uppercase tracking-[0.2em] ${g.accent}`,children:a===1?"Year":"Years"})]}),e.jsx(_r.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:p.title[0]}),p.title[1]&&e.jsx(_r.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:p.title[1]}),e.jsxs(_r.div,{initial:{opacity:0},animate:{opacity:1},transition:{delay:1},children:[e.jsx("p",{className:"text-xl font-medium text-white/80 mb-1",children:n}),r&&e.jsxs("p",{className:"text-sm text-white/30 mb-6 flex items-center justify-center gap-1.5",children:[e.jsx(Si,{className:"h-3 w-3"})," ",r]})]}),e.jsx(_r.div,{className:"h-px bg-gradient-to-r from-transparent via-white/15 to-transparent mx-auto mb-6",initial:{width:0},animate:{width:"70%"},transition:{duration:1,delay:1.1},style:{margin:"0 auto 1.5rem"}}),h&&e.jsx(_r.div,{className:"mb-6 rounded-2xl overflow-hidden border border-white/10",initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},transition:{delay:1.15,duration:.5},children:e.jsx("img",{src:h,alt:"Property",className:"w-full h-48 object-cover"})}),m&&e.jsx(_r.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:`${m}?autoplay=false&responsive=true`,className:"w-full aspect-video",allow:"autoplay; encrypted-media",allowFullScreen:!0})}),e.jsx(_r.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||p.defaultMessage,'"']})}),e.jsxs(_r.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(_r.img,{src:o,alt:l,className:"h-12 w-12 rounded-2xl object-cover ring-1 ring-white/10",whileHover:{scale:1.08}}):e.jsx("div",{className:"h-12 w-12 rounded-2xl bg-white/[0.08] border border-white/[0.1] flex items-center justify-center",children:e.jsx("span",{className:"text-sm font-semibold text-white/60",children:l.charAt(0)})}),e.jsxs("div",{className:"text-left",children:[e.jsx("p",{className:"text-sm font-semibold text-white/80",children:l}),u&&e.jsx("p",{className:"text-xs text-white/30",children:u})]})]}),e.jsxs("div",{className:"flex items-center justify-center gap-2 mt-4",children:[c&&e.jsxs(_r.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(ka,{className:"h-3.5 w-3.5"})," Call"]}),d&&e.jsxs(_r.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(pn,{className:"h-3.5 w-3.5"})," Email"]})]})]})]})]}),e.jsx(_r.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 t8e({delay:s,x:t,angle:n,color:r}){return e.jsx(_r.div,{className:`absolute h-[400px] w-[1px] ${r} origin-top`,style:{left:t,top:"-10%",transform:`rotate(${n}deg)`},animate:{opacity:[0,.4,0],scaleY:[.5,1,.5]},transition:{duration:6,delay:s,repeat:1/0,ease:"easeInOut"}})}function eie({delay:s,x:t}){return e.jsx(_r.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 Fbt={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 i7n(s){const{cardType:t,recipientName:n,propertyAddress:r,anniversaryYears:a,customMessage:i,agentName:l,agentPhotoUrl:o,agentPhone:c,agentEmail:d,agentBrokerage:u,propertyPhotoUrl:h,videoUrl:m}=s,p=HV[t],g=Fbt[t]||Fbt.home_anniversary;return e.jsxs("div",{className:`min-h-screen bg-gradient-to-b ${g.gradient} flex items-center justify-center p-4 overflow-hidden relative`,children:[e.jsx("div",{className:"absolute inset-0 bg-[radial-gradient(ellipse_at_top,rgba(255,255,255,0.04)_0%,transparent_60%)]"}),e.jsx("div",{className:"absolute inset-0 bg-[radial-gradient(ellipse_at_bottom,rgba(0,0,0,0.6)_0%,transparent_60%)]"}),e.jsx(t8e,{delay:0,x:"20%",angle:15,color:g.stripe}),e.jsx(t8e,{delay:2,x:"75%",angle:-12,color:g.stripe}),e.jsx(t8e,{delay:4,x:"50%",angle:5,color:g.stripe}),e.jsx(eie,{delay:0,x:"30%"}),e.jsx(eie,{delay:1.5,x:"60%"}),e.jsx(eie,{delay:3,x:"45%"}),e.jsx(eie,{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(_r.div,{className:"w-full max-w-md relative z-10",initial:{opacity:0},animate:{opacity:1},transition:{duration:1.2},children:[e.jsx(_r.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(_r.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(_r.div,{className:`h-20 w-20 mx-auto rounded-2xl bg-gradient-to-br ${g.accent} flex items-center justify-center shadow-2xl`,animate:{boxShadow:["0 0 40px rgba(255,255,255,0.05)","0 0 80px rgba(255,255,255,0.1)","0 0 40px rgba(255,255,255,0.05)"]},transition:{duration:3,repeat:1/0,ease:"easeInOut"},children:e.jsx("span",{className:"text-4xl",children:p.icon})})}),t==="home_anniversary"&&a!==null&&a>0&&e.jsxs(_r.div,{className:"mb-6",initial:{opacity:0},animate:{opacity:1},transition:{delay:.7},children:[e.jsx(_r.span,{className:`text-6xl font-black bg-gradient-to-r ${g.accent} bg-clip-text text-transparent`,initial:{scale:.5,opacity:0},animate:{scale:1,opacity:1},transition:{delay:.9,type:"spring"},children:a}),e.jsx("p",{className:"text-[10px] font-bold uppercase tracking-[0.4em] text-white/30 mt-1",children:a===1?"Year":"Years"})]}),e.jsx("div",{className:"overflow-hidden mb-2",children:e.jsx(_r.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:p.title[0]})}),p.title[1]&&e.jsx("div",{className:"overflow-hidden mb-8",children:e.jsx(_r.h2,{className:`text-5xl font-black bg-gradient-to-r ${g.accent} bg-clip-text text-transparent`,initial:{y:"100%"},animate:{y:0},transition:{duration:.7,delay:.95,ease:[.16,1,.3,1]},children:p.title[1]})}),e.jsxs(_r.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:1.1,duration:.6},children:[e.jsx("p",{className:"text-lg font-light text-white/70 tracking-wide",children:n}),r&&e.jsxs("p",{className:"text-xs text-white/25 mt-1 flex items-center justify-center gap-1",children:[e.jsx(Si,{className:"h-3 w-3"})," ",r]})]}),e.jsxs(_r.div,{className:"flex items-center justify-center gap-3 my-8",initial:{opacity:0},animate:{opacity:1},transition:{delay:1.2},children:[e.jsx(_r.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(_r.span,{className:"text-white/10 text-xs",animate:{rotate:[0,360]},transition:{duration:20,repeat:1/0,ease:"linear"},children:"✦"}),e.jsx(_r.div,{className:"h-px flex-1 max-w-[60px] bg-gradient-to-l from-transparent to-white/15",initial:{scaleX:0},animate:{scaleX:1},transition:{delay:1.3,duration:.8},style:{transformOrigin:"left"}})]}),h&&e.jsxs(_r.div,{className:"mb-8 rounded-2xl overflow-hidden ring-1 ring-white/5",initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:1.3,duration:.6},children:[e.jsx("img",{src:h,alt:"Property",className:"w-full h-48 object-cover"}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-slate-950/30 to-transparent pointer-events-none"})]}),m&&e.jsx(_r.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:`${m}?autoplay=false&responsive=true`,className:"w-full aspect-video",allow:"autoplay; encrypted-media",allowFullScreen:!0})}),e.jsx(_r.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||p.defaultMessage}),e.jsxs(_r.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(_r.img,{src:o,alt:l,className:"h-12 w-12 rounded-full object-cover ring-2 ring-white/10 shadow-xl",whileHover:{scale:1.1}}):e.jsx("div",{className:`h-12 w-12 rounded-full bg-gradient-to-br ${g.accent} flex items-center justify-center shadow-xl`,children:e.jsx("span",{className:"text-sm font-bold text-slate-900",children:l.charAt(0)})}),e.jsxs("div",{className:"text-left",children:[e.jsx("p",{className:"text-sm font-medium text-white/70",children:l}),u&&e.jsx("p",{className:"text-[11px] text-white/25",children:u})]})]}),e.jsxs("div",{className:"flex items-center justify-center gap-2",children:[c&&e.jsxs(_r.a,{href:`tel:${c}`,className:`flex items-center gap-1.5 px-5 py-2.5 rounded-full bg-gradient-to-r ${g.accent} text-xs font-semibold text-slate-900 shadow-lg`,whileHover:{scale:1.05,boxShadow:"0 10px 40px rgba(255,255,255,0.15)"},whileTap:{scale:.95},children:[e.jsx(ka,{className:"h-3.5 w-3.5"})," Call"]}),d&&e.jsxs(_r.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(pn,{className:"h-3.5 w-3.5"})," Email"]})]})]})]})}),e.jsx(_r.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 JVt(){const{shareToken:s}=oo(),{data:t,isLoading:n,error:r}=pt({queryKey:["public-sendable-card",s],queryFn:async()=>{const{data:l,error:o}=await V.from("sendable_cards").select("*").eq("share_token",s).single();if(o)throw o;return l},enabled:!!s});if(k.useEffect(()=>{if(!t)return;const l=(t.recipient_name||"").trim().split(/\s+/)[0],c={home_anniversary:"Happy Home Anniversary",birthday:"Happy Birthday",wedding_anniversary:"Happy Anniversary",just_listed:"Just Listed",just_sold:"Just Sold",congratulations:"Congratulations",holiday:"Happy Holidays",thank_you:"Thank You",thinking_of_you:"Thinking of You"}[t.card_type]||"A card for you";document.title=l?`${c}, ${l}!`:`${c}!`},[t]),k.useEffect(()=>{s&&V.rpc("log_sendable_card_view",{p_share_token:s}).then(({error:l})=>{l&&console.error("Error tracking view:",l)})},[s]),n)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background",children:e.jsxs("div",{className:"animate-pulse space-y-4 text-center",children:[e.jsx("div",{className:"h-8 w-48 bg-muted rounded mx-auto"}),e.jsx("div",{className:"h-4 w-32 bg-muted rounded mx-auto"})]})});if(r||!t)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"text-2xl font-bold mb-2",children:"Card not found"}),e.jsx("p",{className:"text-muted-foreground",children:"This card may have been removed or the link is invalid."})]})});const a=t.home_anniversary_date?Math.floor((Date.now()-ih(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(s7n,{...i});case"warm":return e.jsx(r7n,{...i});case"glass":return e.jsx(a7n,{...i});case"cinematic":return e.jsx(i7n,{...i});case"elegant":default:return e.jsx(t7n,{...i})}}function o7n(){const s=ai();return pt({queryKey:["drip-settings",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await V.from("drip_settings").select("*").eq("user_id",s).maybeSingle();if(n)throw n;return t},enabled:!!s})}function l7n(){const s=ai(),t=ls();return Nt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r}=await V.from("drip_settings").select("id").eq("user_id",s).maybeSingle();if(r){const{data:a,error:i}=await V.from("drip_settings").update(n).eq("user_id",s).select().single();if(i)throw i;return a}else{const{data:a,error:i}=await V.from("drip_settings").insert({user_id:s,is_globally_enabled:n.is_globally_enabled??!1,append_signature:n.append_signature??!0}).select().single();if(i)throw i;return a}},onSuccess:()=>{t.invalidateQueries({queryKey:["drip-settings"]})}})}function c7n(){const s=Jn(),{isGmailConnected:t,gmailEmail:n}=dx(),{data:r,isLoading:a}=o7n(),i=l7n(),[l,o]=k.useState(!1),[c,d]=k.useState(!0),[u,h]=k.useState(!1);k.useEffect(()=>{r&&(o(r.is_globally_enabled),d(r.append_signature))},[r]);const m=async g=>{if(g&&!t){ae.error("Connect your Gmail account first before enabling Smart Drips");return}o(g);try{await i.mutateAsync({is_globally_enabled:g}),ae.success(g?"Smart Drips enabled globally":"Smart Drips paused globally")}catch{o(!g),ae.error("Failed to update settings")}},p=async g=>{d(g);try{await i.mutateAsync({append_signature:g}),ae.success(g?"Signature will be appended to drip emails":"Signature disabled for drip emails")}catch{d(!g),ae.error("Failed to update settings")}};return e.jsxs(zs,{open:u,onOpenChange:h,children:[e.jsx(yl,{asChild:!0,children:e.jsxs($,{variant:"outline",size:"sm",className:"gap-1.5",children:[e.jsx(Yc,{className:"h-3.5 w-3.5"}),"Settings"]})}),e.jsxs(Rs,{className:"sm:max-w-md",children:[e.jsxs(Vs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(Yc,{className:"h-5 w-5 text-primary"}),"Smart Drip Settings"]}),e.jsx(Cr,{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(pn,{className:`h-4 w-4 ${t?"text-emerald-600":"text-destructive"}`})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:t?"Gmail Connected":"Gmail Not Connected"}),n&&e.jsx("p",{className:"text-xs text-muted-foreground",children:n})]})]}),t?e.jsxs(qe,{variant:"outline",className:"gap-1 text-emerald-600 border-emerald-200 bg-emerald-500/10 text-[10px]",children:[e.jsx(Gr,{className:"h-3 w-3"}),"Active"]}):e.jsxs($,{variant:"outline",size:"sm",className:"text-xs gap-1",onClick:()=>{h(!1),s("/mission-control/integrations")},children:[e.jsx(Ir,{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(Pc,{}),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(GK,{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(On,{checked:l,onCheckedChange:m,disabled:a||i.isPending})]}),e.jsx(Pc,{}),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(s2,{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(On,{checked:c,onCheckedChange:p,disabled:a||i.isPending})]}),c&&e.jsxs($,{variant:"ghost",size:"sm",className:"w-full text-xs text-muted-foreground",onClick:()=>{h(!1),s("/profile")},children:[e.jsx(s2,{className:"h-3 w-3 mr-1"}),"Edit your email signature in Profile settings"]})]})]})]})}function d7n(){const s=ai();return pt({queryKey:["drip-templates",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await V.from("drip_templates").select("*").or(`owner_user_id.eq.${s},is_starter.eq.true`).order("sort_order",{ascending:!0});if(n)throw n;return t},enabled:!!s})}function u7n(){const s=ai();return pt({queryKey:["drip-pipeline-stages",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await V.from("deal_pipeline_stages").select("*").eq("owner_user_id",s).order("sort_order",{ascending:!0});if(n)throw n;return t},enabled:!!s})}function h7n(){const s=ai(),t=ls();return Nt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r,error:a}=await V.from("drip_templates").insert({owner_user_id:s,stage_id:n.stage_id,title:n.title||"",subject:n.subject||"",body:n.body||"",video_url:n.video_url||null,channel:n.channel||"email",delay_type:n.delay_type||"instant",delay_minutes:n.delay_minutes||0,is_enabled:!1,deal_type:n.deal_type||null,sort_order:n.sort_order||0}).select().single();if(a)throw a;return r},onSuccess:()=>{t.invalidateQueries({queryKey:["drip-templates"]})}})}function m7n(){const s=ls();return Nt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await V.from("drip_templates").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["drip-templates"]})}})}function f7n(){const s=ls();return Nt({mutationFn:async t=>{const{error:n}=await V.from("drip_templates").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["drip-templates"]})}})}function p7n(){const s=ai(),t=ls();return Nt({mutationFn:async({templateId:n,stageId:r})=>{if(!s)throw new Error("Not authenticated");const{data:a,error:i}=await V.from("drip_templates").select("*").eq("id",n).single();if(i)throw i;const{data:l,error:o}=await V.from("drip_templates").insert({owner_user_id:s,stage_id:r,title:a.title,subject:a.subject,body:a.body,video_url:a.video_url,channel:a.channel,delay_type:a.delay_type,delay_minutes:a.delay_minutes,is_enabled:!1,is_starter:!1,deal_type:a.deal_type}).select().single();if(o)throw o;return l},onSuccess:()=>{t.invalidateQueries({queryKey:["drip-templates"]})}})}const g7n=[{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"}],s8e=1e3;function eHt({open:s,onOpenChange:t,campaignId:n,campaignName:r,birthdayFocused:a,onSuccess:i}){const l=ai(),o=$Ze(),[c,d]=k.useState(""),[u,h]=k.useState(!!a),[m,p]=k.useState(new Set),{data:g,isLoading:x}=pt({queryKey:["campaign-contact-picker",l],queryFn:async()=>{const P=[];for(let R=0;;R+=s8e){const{data:O,error:B}=await V.from("innercircle_contacts").select("id, first_name, last_name, email, birthday").eq("owner_user_id",l).order("first_name").range(R,R+s8e-1);if(B)throw B;if(P.push(...O||[]),!O||O.length{const{data:P,error:R}=await V.from("drip_campaign_enrollments").select("contact_id, status").eq("campaign_id",n);if(R)throw R;return new Set((P||[]).filter(O=>O.status==="active"||O.status==="paused").map(O=>O.contact_id))},enabled:s&&!!n}),v=k.useMemo(()=>{const P=c.trim().toLowerCase();return(g||[]).filter(R=>u&&!R.birthday?!1:P?`${R.first_name||""} ${R.last_name||""}`.toLowerCase().includes(P)||(R.email||"").toLowerCase().includes(P):!0)},[g,c,u]),_=v.filter(P=>!(y!=null&&y.has(P.id))).map(P=>P.id),j=_.length>0&&_.every(P=>m.has(P)),C=P=>{p(R=>{const O=new Set(R);return O.has(P)?O.delete(P):O.add(P),O})},A=()=>{p(P=>{if(j){const R=new Set(P);return _.forEach(O=>R.delete(O)),R}return new Set([...P,..._])})},M=async()=>{if(!(!n||m.size===0))try{const P=await o.mutateAsync({campaignId:n,contactIds:Array.from(m)}),R=[`${P.enrolled} enrolled`];P.skipped>0&&R.push(`${P.skipped} already in`),P.errors>0&&R.push(`${P.errors} errors`),ae.success(R.join(" · ")),p(new Set),t(!1),i==null||i()}catch(P){ae.error(P.message||"Failed to add contacts")}},I=(g||[]).filter(P=>P.birthday).length;return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"max-w-lg max-h-[85vh] flex flex-col p-0 overflow-hidden",children:[e.jsxs(Vs,{className:"p-5 pb-3 border-b shrink-0 text-left",children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(Xn,{className:"h-4 w-4 text-primary"}),"Add contacts — ",r||"Campaign"]}),e.jsxs(Cr,{className:"text-xs",children:["Pick the people you want in this campaign. Contacts already enrolled are greyed out.",a&&" Birthday emails send automatically on each person's birthday once they're in."]})]}),e.jsxs("div",{className:"px-5 pt-3 space-y-2 shrink-0",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Yr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(be,{placeholder:"Search contacts by name or email...",value:c,onChange:P=>d(P.target.value),className:"pl-9 h-9"})]}),e.jsxs("div",{className:"flex items-center justify-between gap-3 flex-wrap",children:[e.jsxs("label",{className:"flex items-center gap-2 text-xs text-muted-foreground cursor-pointer",children:[e.jsx(Li,{checked:u,onCheckedChange:P=>h(!!P)}),e.jsx(ip,{className:"h-3.5 w-3.5 text-primary"}),"Only contacts with a birthday on file (",I,")"]}),e.jsx($,{variant:"ghost",size:"sm",className:"text-xs h-7",onClick:A,disabled:_.length===0,children:j?"Clear all":`Select all ${_.length}`})]})]}),e.jsx("div",{className:"flex-1 min-h-0 px-5 py-3",children:e.jsx(Eo,{className:"h-[320px] -mx-1 px-1",children:x?e.jsx("div",{className:"text-center py-10 text-sm text-muted-foreground",children:"Loading contacts..."}):v.length===0?e.jsx("div",{className:"text-center py-10 text-sm text-muted-foreground",children:u?"No contacts have a birthday saved yet. Add birthdays on a contact record first.":"No contacts match your search."}):e.jsx("div",{className:"space-y-1",children:v.map(P=>{const R=y==null?void 0:y.has(P.id);return e.jsxs("label",{className:`flex items-center gap-3 p-2.5 rounded-lg border transition-colors ${R?"opacity-50 border-transparent":m.has(P.id)?"border-primary bg-primary/5 cursor-pointer":"border-border hover:bg-muted/40 cursor-pointer"}`,children:[e.jsx(Li,{checked:R?!0:m.has(P.id),disabled:R,onCheckedChange:()=>C(P.id)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:[P.first_name,P.last_name].filter(Boolean).join(" ")||"Unnamed contact"}),e.jsxs("div",{className:"flex items-center gap-3 text-[11px] text-muted-foreground",children:[P.email&&e.jsxs("span",{className:"flex items-center gap-1 truncate",children:[e.jsx(pn,{className:"h-2.5 w-2.5"}),P.email]}),P.birthday&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ip,{className:"h-2.5 w-2.5"}),P.birthday]})]})]}),R&&e.jsx(qe,{variant:"outline",className:"text-[9px]",children:"In campaign"})]},P.id)})})})}),e.jsxs(kr,{className:"p-4 border-t shrink-0 gap-2 sm:gap-2",children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs($,{onClick:M,disabled:m.size===0||o.isPending,children:[o.isPending&&e.jsx(Jt,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}),"Add ",m.size||""," contact",m.size===1?"":"s"]})]})]})})}function x7n({open:s,onOpenChange:t,campaignId:n,campaignName:r}){const{data:a,isLoading:i}=ESn(n||void 0),l=MSn(),o=$Ze(),[c,d]=k.useState(!1),u=async(p,g)=>{try{await l.mutateAsync({id:p,status:g}),ae.success(`Enrollment ${g}`)}catch{ae.error("Failed to update")}},h=async p=>{if(n)try{const g=await o.mutateAsync({campaignId:n,contactIds:[p]});g.enrolled>0?ae.success("Contact re-enrolled — first email queued"):g.skipped>0?ae.message("Already active in this campaign"):ae.error("Could not re-enroll")}catch{ae.error("Failed to re-enroll")}},m=p=>{const g={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(qe,{variant:"outline",className:`text-[10px] capitalize ${g[p]||""}`,children:p})};return e.jsxs(zs,{open:s,onOpenChange:t,children:[e.jsxs(Rs,{className:"max-w-2xl max-h-[85vh] flex flex-col p-0 overflow-hidden",children:[e.jsxs("div",{className:"p-5 border-b shrink-0",children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(Xn,{className:"h-4 w-4 text-primary"}),"Enrollments — ",r||"Campaign"]}),e.jsx(Cr,{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:"mt-3",children:e.jsxs($,{size:"sm",variant:"outline",onClick:()=>d(!0),children:[e.jsx(Pl,{className:"h-3.5 w-3.5 mr-1.5"})," Add contacts"]})})]}),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(p=>e.jsx(fn,{className:"h-14"},p))}):!a||a.length===0?e.jsxs("div",{className:"text-center py-12",children:[e.jsx(Xn,{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 mb-3",children:"Add the contacts you want in this campaign — they'll start receiving it automatically."}),e.jsxs($,{size:"sm",onClick:()=>d(!0),children:[e.jsx(Pl,{className:"h-3.5 w-3.5 mr-1.5"})," Add contacts"]})]}):e.jsx("div",{className:"space-y-2",children:a.map(p=>{var g,x,y,v;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:[(g=p.contact)==null?void 0:g.first_name," ",(x=p.contact)==null?void 0:x.last_name]}),m(p.status)]}),e.jsxs("div",{className:"flex items-center gap-3 text-[11px] text-muted-foreground mt-0.5",children:[((y=p.contact)==null?void 0:y.email)&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(pn,{className:"h-2.5 w-2.5"})," ",p.contact.email]}),e.jsxs("span",{children:["Step ",p.current_step]}),p.next_send_at&&p.status==="active"&&e.jsxs("span",{children:["Next: ",Ys(new Date(p.next_send_at),"MMM d, h:mma")]}),p.exit_reason&&e.jsxs("span",{children:["Exit: ",p.exit_reason]})]})]}),p.status==="active"&&e.jsx($,{size:"sm",variant:"ghost",onClick:()=>u(p.id,"paused"),title:"Pause",children:e.jsx(uv,{className:"h-3.5 w-3.5"})}),p.status==="paused"&&e.jsx($,{size:"sm",variant:"ghost",onClick:()=>u(p.id,"active"),title:"Resume",children:e.jsx(pu,{className:"h-3.5 w-3.5"})}),(p.status==="active"||p.status==="paused")&&e.jsx($,{size:"sm",variant:"ghost",onClick:()=>u(p.id,"exited"),title:"Exit",children:e.jsx(mr,{className:"h-3.5 w-3.5 text-destructive"})}),(p.status==="exited"||p.status==="completed")&&((v=p.contact)==null?void 0:v.id)&&e.jsxs($,{size:"sm",variant:"outline",className:"h-7 text-[11px] gap-1",onClick:()=>h(p.contact.id),disabled:o.isPending,children:[e.jsx(jm,{className:"h-3 w-3"}),"Re-enroll"]})]},p.id)})})})})]}),e.jsx(eHt,{open:c,onOpenChange:d,campaignId:n,campaignName:r,birthdayFocused:/birthday/i.test(r||"")})]})}function y7n(){var A,M,I;const{data:s,isLoading:t}=rte(),{hasLeadSite:n}=Tg(),r=BZe(),a=kSn(),i=B7t(),[l,o]=k.useState(null),[c,d]=k.useState(!1),[u,h]=k.useState(null),[m,p]=k.useState(null),[g,x]=k.useState(null),y=(s||[]).filter(P=>!P.is_starter),v=(s||[]).filter(P=>P.is_starter).filter(P=>!P.requires_lead_site||n),_=async P=>{try{await r.mutateAsync(P),ae.success("Campaign added to your library — customize and activate it!"),o(null)}catch(R){ae.error(R.message||"Failed to copy campaign")}},j=async P=>{try{await i.mutateAsync({id:P.id,is_active:!P.is_active}),ae.success(P.is_active?"Campaign paused":"Campaign activated")}catch{ae.error("Failed to update")}},C=async P=>{if(await io("Delete this campaign? Active enrollments will be removed."))try{await a.mutateAsync(P),ae.success("Campaign deleted")}catch{ae.error("Failed to delete")}};return t?e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4",children:[1,2,3,4,5,6].map(P=>e.jsx(fn,{className:"h-44 rounded-xl"},P))}):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(T5,{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(_h,{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(Wr,{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.jsxs("p",{className:"text-muted-foreground",children:["Click ",e.jsx("strong",{children:"Add contacts"})," on any campaign card, pick the people you want, and they start receiving it. (You can also select contacts in your Contacts list and choose “Enroll in Campaign”.)"]})]})]})]}),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(Xn,{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($,{size:"sm",onClick:()=>{h(null),d(!0)},children:[e.jsx(nn,{className:"h-3.5 w-3.5 mr-1.5"})," New Campaign"]})]}),y.length===0?e.jsxs("div",{className:"text-center py-10 border border-dashed rounded-xl bg-muted/20",children:[e.jsx(kn,{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($,{size:"sm",onClick:()=>{h(null),d(!0)},children:[e.jsx(nn,{className:"h-3.5 w-3.5 mr-1.5"})," Create your first campaign"]})]}):e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4",children:y.map(P=>e.jsx(v7n,{campaign:P,onPreview:()=>o(P.id),onToggleActive:()=>j(P),onDelete:()=>C(P.id),onEdit:()=>{h(P.id),d(!0)},onViewEnrollments:()=>p(P.id),onAddContacts:()=>x(P.id)},P.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(kn,{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(qe,{variant:"outline",className:"text-[10px]",children:[v.length," templates"]})]}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4",children:v.map(P=>e.jsx(b7n,{campaign:P,onPreview:()=>o(P.id)},P.id))})]}),e.jsx(eHt,{open:!!g,onOpenChange:P=>!P&&x(null),campaignId:g,campaignName:(A=y.find(P=>P.id===g))==null?void 0:A.name,birthdayFocused:/birthday/i.test(((M=y.find(P=>P.id===g))==null?void 0:M.name)||"")}),e.jsx(_7n,{campaignId:l,open:!!l,onOpenChange:P=>!P&&o(null),onClone:_,isCloning:r.isPending,onEdit:P=>{o(null),h(P),d(!0)}}),e.jsx(V7t,{open:c,onOpenChange:d,campaignId:u}),e.jsx(x7n,{open:!!m,onOpenChange:P=>!P&&p(null),campaignId:m,campaignName:(I=y.find(P=>P.id===m))==null?void 0:I.name})]})}function v7n({campaign:s,onPreview:t,onToggleActive:n,onDelete:r,onEdit:a,onViewEnrollments:i,onAddContacts:l}){const c=TSn(s.id).data??0,d=!s.is_active&&c>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(qe,{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(qe,{variant:"outline",className:"text-[9px] mt-2",children:iTe[s.category]}),d&&e.jsxs("button",{onClick:n,className:"mt-2 w-full flex items-start gap-1.5 p-2 rounded-md bg-amber-500/10 border border-amber-500/30 text-left hover:bg-amber-500/15 transition-colors",children:[e.jsx(Gd,{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:[c," contact",c===1?"":"s"," enrolled"]})," but not sending — tap to activate"]})]}),e.jsxs($,{size:"sm",className:"w-full h-8 text-xs mt-3",onClick:l,children:[e.jsx(Pl,{className:"h-3.5 w-3.5 mr-1.5"})," Add contacts"]}),e.jsxs("div",{className:"grid grid-cols-2 gap-1.5 mt-1.5",children:[e.jsxs($,{size:"sm",variant:"outline",className:"h-7 text-xs",onClick:a,children:[e.jsx(ui,{className:"h-3 w-3 mr-1"})," Edit"]}),e.jsx($,{size:"sm",variant:s.is_active?"secondary":"default",className:"h-7 text-xs",onClick:n,children:s.is_active?"Pause":"Activate"})]}),e.jsxs("div",{className:"flex items-center justify-between mt-2 text-[10px]",children:[e.jsx("button",{onClick:i,className:"text-primary hover:underline",children:"View enrollments"}),e.jsx("button",{onClick:t,className:"text-muted-foreground hover:underline",children:"Preview"}),e.jsx("button",{onClick:r,className:"text-muted-foreground hover:text-destructive",children:"Delete"})]})]})]})}function b7n({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(qe,{className:"absolute top-2 right-2 bg-white/90 text-foreground hover:bg-white text-[10px]",children:[e.jsx(kn,{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(qe,{variant:"outline",className:"text-[9px] mt-2",children:iTe[s.category]})]})]})}function _7n({campaignId:s,open:t,onOpenChange:n,onClone:r,isCloning:a,onEdit:i}){const{data:l}=rte(),{data:o}=$7t(s||void 0),[c,d]=k.useState(new Set),u=l==null?void 0:l.find(p=>p.id===s);if(!u)return null;const h=p=>{d(g=>{const x=new Set(g);return x.has(p)?x.delete(p):x.add(p),x})},m=(p,g)=>{if(p.delay_type==="calendar_anchor"){const y=p.anchor_field==="birthday"?"birthday":"home anniversary",v=p.anchor_offset_days||0;return v===0?`On their ${y}`:v<0?`${Math.abs(v)} days before ${y}`:`${v} days after ${y}`}if(g===0&&p.delay_days===0&&p.delay_hours===0)return"Sends immediately";const x=[];return p.delay_days&&x.push(`${p.delay_days}d`),p.delay_hours&&x.push(`${p.delay_hours}h`),g===0?`After ${x.join(" ")}`:`+${x.join(" ")}`};return e.jsx(zs,{open:t,onOpenChange:n,children:e.jsxs(Rs,{className:"max-w-2xl max-h-[85vh] flex flex-col p-0 overflow-hidden",children:[e.jsx("div",{className:`bg-gradient-to-br ${u.cover_color} p-6 text-white shrink-0`,children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("span",{className:"text-5xl drop-shadow-sm",children:u.icon}),e.jsxs("div",{className:"flex-1",children:[e.jsx($s,{className:"text-xl font-bold text-white",children:u.name}),e.jsx(Cr,{className:"text-white/90 mt-1",children:u.description}),e.jsxs("div",{className:"flex gap-2 mt-3",children:[e.jsx(qe,{className:"bg-white/20 text-white border-white/20 hover:bg-white/20",children:iTe[u.category]}),e.jsxs(qe,{className:"bg-white/20 text-white border-white/20 hover:bg-white/20",children:[(o==null?void 0:o.length)||0," step",(o==null?void 0:o.length)!==1?"s":""]})]})]})]})}),e.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:e.jsxs("div",{className:"p-6 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("h4",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"The sequence"}),u.is_starter?e.jsx("span",{className:"text-[10px] text-muted-foreground italic",children:"Copy to your library to edit"}):e.jsx("span",{className:"text-[10px] text-muted-foreground italic",children:"Tap a step to expand · Edit to customize"})]}),o==null?void 0:o.map((p,g)=>{const x=c.has(p.id);return e.jsxs("div",{className:"flex gap-3",children:[e.jsxs("div",{className:"shrink-0 flex flex-col items-center",children:[e.jsx("div",{className:"h-8 w-8 rounded-full bg-primary/10 text-primary flex items-center justify-center text-xs font-semibold",children:g+1}),gh(p.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:[p.delay_type==="calendar_anchor"?e.jsx(ha,{className:"h-3 w-3"}):e.jsx(sa,{className:"h-3 w-3"}),e.jsx("span",{children:m(p,g)}),e.jsx("span",{children:"·"}),e.jsx(pn,{className:"h-3 w-3"}),e.jsx("span",{className:"capitalize",children:p.channel})]}),e.jsx("p",{className:"font-medium text-sm",children:p.subject}),(()=>{const y=p.body||"",v=/<\/?[a-z][\s\S]*>/i.test(y),_=v?y.replace(//gi,"").replace(/<[^>]+>/g," ").replace(/ /g," ").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/\s+/g," ").trim():y;return x?v?e.jsx("div",{className:"text-xs text-foreground mt-2 prose prose-sm max-w-none [&_a]:text-primary",dangerouslySetInnerHTML:{__html:y}}):e.jsx("p",{className:"text-xs text-muted-foreground mt-2 whitespace-pre-line",children:y}):e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2 mt-1",children:_})})(),p.body&&p.body.length>160&&e.jsx("span",{className:"text-[10px] text-primary mt-1.5 inline-block",children:x?"Show less":"Show full email"})]})})]},p.id)})]})}),e.jsxs(kr,{className:"border-t p-4 shrink-0",children:[e.jsx($,{variant:"outline",onClick:()=>n(!1),children:"Close"}),!u.is_starter&&i&&e.jsxs($,{variant:"secondary",onClick:()=>i(u.id),children:[e.jsx(ui,{className:"h-3.5 w-3.5 mr-1.5"})," Edit Campaign"]}),u.is_starter&&e.jsxs($,{onClick:()=>r(u.id),disabled:a,children:[a?e.jsx(Jt,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}):e.jsx(Da,{className:"h-3.5 w-3.5 mr-1.5"}),"Copy to my campaigns"]})]})]})})}const mke=[{value:"birthday",label:"Birthday",description:"Celebrate your contact's birthday",column:"birthday",emoji:"🎂"},{value:"home_anniversary",label:"Home Anniversary",description:"The date they closed on their home",column:"home_anniversary",emoji:"🏡"},{value:"spouse_birthday",label:"Spouse's Birthday",description:"Remember their partner's day too",column:"spouse_birthday",emoji:"💐"},{value:"wedding_anniversary",label:"Wedding Anniversary",description:"A thoughtful touch couples remember",column:"wedding_anniversary",emoji:"💍"}];function w7n(){const s=ai();return pt({queryKey:["drip-auto-rules",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await V.from("drip_auto_enroll_rules").select("*, campaign:drip_campaigns(id, name, category, cover_color)").eq("owner_user_id",s).order("created_at",{ascending:!0});if(n)throw n;return t||[]},enabled:!!s})}function j7n(){const s=ai(),t=ls();return Nt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const r={owner_user_id:s,campaign_id:n.campaign_id,trigger_type:n.trigger_type,lead_days:n.lead_days??14,filter_tags:n.filter_tags??[],filter_relationship_types:n.filter_relationship_types??[],require_email:n.require_email??!0,is_active:n.is_active??!0};n.id&&(r.id=n.id);const{data:a,error:i}=await V.from("drip_auto_enroll_rules").upsert(r).select().single();if(i)throw i;return a},onSuccess:()=>{t.invalidateQueries({queryKey:["drip-auto-rules"]})}})}function N7n(){const s=ls();return Nt({mutationFn:async({id:t,is_active:n})=>{const{error:r}=await V.from("drip_auto_enroll_rules").update({is_active:n}).eq("id",t);if(r)throw r},onSuccess:()=>s.invalidateQueries({queryKey:["drip-auto-rules"]})})}function k7n(){const s=ls();return Nt({mutationFn:async t=>{const{error:n}=await V.from("drip_auto_enroll_rules").delete().eq("id",t);if(n)throw n},onSuccess:()=>s.invalidateQueries({queryKey:["drip-auto-rules"]})})}function S7n(s=25){const t=ai();return pt({queryKey:["drip-auto-log",t,s],queryFn:async()=>{if(!t)return[];const{data:n,error:r}=await V.from("drip_auto_enroll_log").select("*, contact:innercircle_contacts(id, first_name, last_name, email)").eq("owner_user_id",t).order("created_at",{ascending:!1}).limit(s);if(r)throw r;return n||[]},enabled:!!t})}function C7n(){const s=ai();return pt({queryKey:["life-event-coverage",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await V.from("innercircle_contacts").select("birthday, home_anniversary, spouse_birthday, wedding_anniversary, email").eq("owner_user_id",s).limit(1e4);if(n)throw n;const r=t||[],a=(l,o)=>{if(!l)return!1;const[,c,d]=String(l).split("-").map(Number),u=new Date;let h=new Date(u.getFullYear(),c-1,d);return h{const o=r.filter(c=>!!c[l.column]);i[l.value]={total:o.length,upcoming30:o.filter(c=>a(c[l.column],30)).length}}),{totalContacts:r.length,counts:i}},enabled:!!s})}function A7n(){const s=ls();return Nt({mutationFn:async t=>{const{data:n,error:r}=await V.functions.invoke("process-life-event-drips",{body:t?{rule_id:t}:{}});if(r)throw r;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["drip-auto-rules"]}),s.invalidateQueries({queryKey:["drip-auto-log"]}),s.invalidateQueries({queryKey:["drip-campaign-enrollments"]})}})}const E7n={birthday:ip,home_anniversary:nk,spouse_birthday:Zo,wedding_anniversary:Bo};function T7n(){var C;const{data:s,isLoading:t}=w7n(),{data:n}=rte(),{data:r}=C7n(),{data:a}=S7n(10),i=j7n(),l=N7n(),o=k7n(),c=A7n(),d=BZe(),[u,h]=k.useState(null),m=k.useMemo(()=>(n||[]).filter(A=>!A.is_starter),[n]),p={birthday:"Birthday",home_anniversary:"Home Anniversary",spouse_birthday:"Spouse Birthday",wedding_anniversary:"Wedding Anniversary"},g=k.useMemo(()=>{if(!(u!=null&&u.trigger_type))return null;const A=p[u.trigger_type];return!A||m.some(I=>String(I.name||"").toLowerCase().includes(A.toLowerCase()))?null:(n||[]).find(I=>I.is_starter&&String(I.name||"").toLowerCase()===A.toLowerCase())??null},[n,m,u==null?void 0:u.trigger_type]),x=async()=>{if(g)try{const A=await d.mutateAsync(g.id);h(M=>({...M,campaign_id:A.id})),ae.success(`“${g.name}” template added to your campaigns`)}catch(A){ae.error((A==null?void 0:A.message)||"Could not copy the template")}},y=A=>(s||[]).find(M=>M.trigger_type===A),v=async()=>{if(!(u!=null&&u.campaign_id)||!(u!=null&&u.trigger_type)){ae.error("Pick a campaign first");return}try{await i.mutateAsync(u),ae.success("Autopilot rule saved"),h(null)}catch(A){ae.error((A==null?void 0:A.message)||"Could not save rule")}},_=async()=>{try{const A=await c.mutateAsync(void 0);ae.success(A!=null&&A.enrolled?`Enrolled ${A.enrolled} contact${A.enrolled===1?"":"s"} with upcoming life events`:"All caught up — nobody new to enroll right now")}catch(A){ae.error((A==null?void 0:A.message)||"Autopilot run failed")}},j=(s||[]).filter(A=>A.is_active).length;return e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"rounded-2xl border bg-gradient-to-br from-primary/10 via-card to-card p-5",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"h-11 w-11 rounded-xl bg-primary/15 flex items-center justify-center shrink-0",children:e.jsx(kn,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-bold leading-tight",children:"Life Event Autopilot"}),e.jsx("p",{className:"text-sm text-muted-foreground max-w-xl",children:"Every morning we scan your database for upcoming birthdays and anniversaries and quietly enroll those contacts in the campaign you choose. You never miss a moment again."})]})]}),e.jsxs($,{variant:"outline",onClick:_,disabled:c.isPending||j===0,className:"gap-2 shrink-0",children:[c.isPending?e.jsx(Jt,{className:"h-4 w-4 animate-spin"}):e.jsx(yo,{className:"h-4 w-4"}),"Run now"]})]}),r&&e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-2 mt-4",children:mke.map(A=>{const M=r.counts[A.value];return e.jsxs("div",{className:"rounded-xl bg-background/70 border px-3 py-2",children:[e.jsxs("p",{className:"text-[11px] text-muted-foreground truncate",children:[A.emoji," ",A.label]}),e.jsx("p",{className:"text-lg font-bold leading-tight",children:(M==null?void 0:M.total)??0}),e.jsxs("p",{className:"text-[11px] text-muted-foreground",children:[(M==null?void 0:M.upcoming30)??0," in next 30 days"]})]},A.value)})})]}),t?e.jsx("div",{className:"flex justify-center py-10",children:e.jsx(Jt,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):e.jsx("div",{className:"grid sm:grid-cols-2 gap-3",children:mke.map(A=>{var R;const M=y(A.value),I=E7n[A.value]||ip,P=r==null?void 0:r.counts[A.value];return e.jsxs("div",{className:Ot("rounded-xl border bg-card p-4 transition-colors",(M==null?void 0:M.is_active)&&"border-primary/40 bg-primary/[0.03]"),children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:Ot("h-10 w-10 rounded-lg flex items-center justify-center shrink-0",M!=null&&M.is_active?"bg-primary/15 text-primary":"bg-muted text-muted-foreground"),children:e.jsx(I,{className:"h-5 w-5"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"font-semibold text-sm",children:A.label}),(M==null?void 0:M.is_active)&&e.jsx(qe,{className:"text-[10px] bg-primary/10 text-primary hover:bg-primary/10",children:"On"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:M?`${((R=M.campaign)==null?void 0:R.name)??"Campaign"} · starts ${M.lead_days} days before`:A.description}),M&&M.total_enrolled>0&&e.jsxs("p",{className:"text-[11px] text-muted-foreground mt-1",children:[M.total_enrolled," contact",M.total_enrolled===1?"":"s"," enrolled so far"]}),!M&&((P==null?void 0:P.total)??0)===0&&e.jsx("p",{className:"text-[11px] text-amber-600 dark:text-amber-400 mt-1",children:"No contacts have this date on file yet."})]}),M?e.jsx(On,{checked:M.is_active,onCheckedChange:O=>l.mutate({id:M.id,is_active:O})}):null]}),e.jsxs("div",{className:"flex gap-2 mt-3",children:[e.jsxs($,{size:"sm",variant:M?"outline":"default",className:"flex-1 gap-1.5",onClick:()=>h(M??{trigger_type:A.value,lead_days:A.value==="birthday"?7:14,require_email:!0,is_active:!0,filter_tags:[],filter_relationship_types:[]}),children:[M?e.jsx(ix,{className:"h-3.5 w-3.5"}):e.jsx(nn,{className:"h-3.5 w-3.5"}),M?"Edit rule":"Turn on autopilot"]}),M&&e.jsx($,{size:"sm",variant:"ghost",className:"text-muted-foreground hover:text-destructive",onClick:()=>o.mutate(M.id),children:e.jsx(Un,{className:"h-3.5 w-3.5"})})]})]},A.value)})}),((a==null?void 0:a.length)??0)>0&&e.jsxs("div",{className:"rounded-xl border bg-card",children:[e.jsxs("div",{className:"px-4 py-3 border-b",children:[e.jsx("p",{className:"text-sm font-semibold",children:"Recently auto-enrolled"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Proof your autopilot is running while you sleep."})]}),e.jsx("div",{className:"divide-y",children:(a||[]).map(A=>{var M,I;return e.jsxs("div",{className:"flex items-center gap-3 px-4 py-2.5",children:[e.jsx(ma,{className:"h-4 w-4 text-emerald-500 shrink-0"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("p",{className:"text-sm font-medium truncate",children:[(M=A.contact)==null?void 0:M.first_name," ",(I=A.contact)==null?void 0:I.last_name]}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[String(A.trigger_type).replace(/_/g," ")," · ",A.note]})]}),e.jsx("span",{className:"text-[11px] text-muted-foreground shrink-0",children:new Date(A.created_at).toLocaleDateString("en-US",{month:"short",day:"numeric"})})]},A.id)})})]}),e.jsx(zs,{open:!!u,onOpenChange:A=>!A&&h(null),children:e.jsxs(Rs,{className:"sm:max-w-md",children:[e.jsxs(Vs,{children:[e.jsxs($s,{children:[(C=mke.find(A=>A.value===(u==null?void 0:u.trigger_type)))==null?void 0:C.label," autopilot"]}),e.jsx(Cr,{children:"Choose the campaign to run and how far ahead it should start."})]}),e.jsxs("div",{className:"space-y-5 py-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Campaign to enroll into"}),e.jsxs(bs,{value:(u==null?void 0:u.campaign_id)??"",onValueChange:A=>h(M=>({...M,campaign_id:A})),children:[e.jsx(ys,{children:e.jsx(_s,{placeholder:"Select one of your campaigns"})}),e.jsx(vs,{children:m.map(A=>e.jsx(We,{value:A.id,children:A.name},A.id))})]}),g&&e.jsx("div",{className:"rounded-lg border border-primary/25 bg-primary/5 p-3",children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(kn,{className:"mt-0.5 h-4 w-4 shrink-0 text-primary"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("p",{className:"text-sm font-medium leading-tight",children:["Use the LevelUp “",g.name,"” template"]}),e.jsx("p",{className:"mt-0.5 text-xs text-muted-foreground",children:"Beautifully designed, personalized emails written for this moment. We'll copy it into your campaigns so you can edit anything you like."}),e.jsxs($,{size:"sm",variant:"outline",className:"mt-2 gap-1.5",disabled:d.isPending,onClick:x,children:[d.isPending?e.jsx(Jt,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(nn,{className:"h-3.5 w-3.5"}),"Use this template"]})]})]})}),m.length===0&&!g&&e.jsx("p",{className:"text-xs text-amber-600 dark:text-amber-400",children:"You need one of your own campaigns first — clone a starter from the Campaigns tab."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(re,{children:"Start this many days before the event"}),e.jsxs("span",{className:"text-sm font-semibold tabular-nums",children:[(u==null?void 0:u.lead_days)??14,"d"]})]}),e.jsx(sx,{min:0,max:45,step:1,value:[(u==null?void 0:u.lead_days)??14],onValueChange:([A])=>h(M=>({...M,lead_days:A}))}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Gives your campaign time to warm up before the big day."})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx(re,{className:"text-sm",children:"Only contacts with an email"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Skip records that can't be reached."})]}),e.jsx(On,{checked:(u==null?void 0:u.require_email)??!0,onCheckedChange:A=>h(M=>({...M,require_email:A}))})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx(re,{className:"text-sm",children:"Autopilot active"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Runs every morning automatically."})]}),e.jsx(On,{checked:(u==null?void 0:u.is_active)??!0,onCheckedChange:A=>h(M=>({...M,is_active:A}))})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"ghost",onClick:()=>h(null),children:"Cancel"}),e.jsxs($,{onClick:v,disabled:i.isPending||!(u!=null&&u.campaign_id),children:[i.isPending&&e.jsx(Jt,{className:"h-4 w-4 mr-1.5 animate-spin"}),"Save rule"]})]})]})})]})}function M7n(){const s=ai(),t=Jn(),{isGmailConnected:n,gmailEmail:r,isLoading:a}=dx(),{data:i,isLoading:l}=d7n(),{data:o,isLoading:c}=u7n(),d=h7n(),u=m7n(),h=f7n(),m=p7n(),[p,g]=k.useState(null),[x,y]=k.useState(null),v=(i==null?void 0:i.filter(R=>!R.is_starter&&R.owner_user_id===s))||[],_=(i==null?void 0:i.filter(R=>R.is_starter))||[],j=R=>v.filter(O=>O.stage_id===R),C=async R=>{try{await u.mutateAsync({id:R.id,is_enabled:!R.is_enabled}),ae.success(R.is_enabled?"Drip disabled":"Drip enabled")}catch{ae.error("Failed to update")}},A=async R=>{try{const O=o==null?void 0:o.find(B=>B.id===R);await d.mutateAsync({stage_id:R,title:`${(O==null?void 0:O.name)||"Stage"} follow-up`,subject:"",body:"",channel:"email",delay_type:"instant",delay_minutes:0}),g(R),ae.success("Drip template created")}catch{ae.error("Failed to create template")}},M=async R=>{try{await h.mutateAsync(R),ae.success("Template deleted")}catch{ae.error("Failed to delete")}},I=async R=>{if(!o||o.length===0){ae.error("No pipeline stages found");return}const O=o[0].id;try{await m.mutateAsync({templateId:R,stageId:O}),ae.success("Template copied to your drips!")}catch{ae.error("Failed to copy template")}},P=l||c;return e.jsx(Xs,{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(ix,{className:"h-5 w-5 text-primary"}),e.jsx("h1",{className:"text-2xl font-bold",children:"Smart Drips"}),e.jsx(qe,{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(c7n,{})]}),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(T5,{className:"h-4 w-4 text-primary mt-0.5 shrink-0"}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[e.jsx("p",{className:"font-medium text-foreground mb-1",children:"How it works"}),e.jsxs("p",{children:["When a deal moves to a new stage in your pipeline, Smart Drips automatically sends your pre-written email to the client. Nothing sends until you create a template ",e.jsx("strong",{children:"and"})," toggle it on."]})]})]}),!a&&(n?e.jsxs("div",{className:"bg-emerald-500/5 border border-emerald-500/20 rounded-xl p-4 mb-6 flex items-start gap-3",children:[e.jsx(pn,{className:"h-4 w-4 text-emerald-600 mt-0.5 shrink-0"}),e.jsxs("div",{className:"text-sm flex-1",children:[e.jsxs("p",{className:"font-medium text-foreground mb-0.5",children:["Sending from your Gmail",r?` (${r})`:""]}),e.jsx("p",{className:"text-muted-foreground",children:"Drips will send directly from your connected Gmail for the most personal feel and best deliverability."})]})]}):e.jsxs("div",{className:"bg-amber-500/5 border border-amber-500/20 rounded-xl p-4 mb-6 flex items-start gap-3",children:[e.jsx(T5,{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($,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>t("/mission-control/integrations"),children:[e.jsx(pn,{className:"h-3 w-3 mr-1.5"}),"Connect Gmail"]})]})]})),e.jsxs(ya,{defaultValue:"my-drips",children:[e.jsxs(va,{className:"grid grid-cols-4 w-full max-w-2xl mb-6",children:[e.jsx(is,{value:"my-drips",children:"Stage Drips"}),e.jsxs(is,{value:"campaigns",children:["Campaigns",e.jsx(qe,{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(is,{value:"autopilot",children:["Life Events",e.jsx(qe,{variant:"outline",className:"ml-1.5 text-[9px] bg-primary/10 text-primary border-primary/20 px-1 py-0",children:"Auto"})]}),e.jsxs(is,{value:"starters",children:["Stage Starters",_.length>0&&e.jsx(qe,{variant:"secondary",className:"ml-1.5 text-[10px] px-1.5 py-0",children:_.length})]})]}),e.jsx(cs,{value:"campaigns",children:e.jsx(y7n,{})}),e.jsx(cs,{value:"autopilot",children:e.jsx(T7n,{})}),e.jsx(cs,{value:"my-drips",children:P?e.jsx("div",{className:"space-y-3",children:[1,2,3,4].map(R=>e.jsx(fn,{className:"h-16 w-full rounded-xl"},R))}):!o||o.length===0?e.jsxs("div",{className:"text-center py-12 border border-dashed rounded-xl",children:[e.jsx(ix,{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(R=>!R.is_won_stage&&!R.is_lost_stage).map(R=>{const O=j(R.id),B=p===R.id,U=O.some(G=>G.is_enabled);return e.jsxs("div",{className:"border rounded-xl overflow-hidden",children:[e.jsxs("button",{onClick:()=>g(B?null:R.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:R.color||"#94A3B8"}}),e.jsx("span",{className:"font-medium text-sm flex-1",children:R.name}),O.length>0&&e.jsxs(qe,{variant:"outline",className:`text-[10px] ${U?"bg-emerald-500/10 text-emerald-600 border-emerald-200":"text-muted-foreground"}`,children:[O.length," drip",O.length!==1?"s":"",U&&" · Active"]}),B?e.jsx(Go,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(fi,{className:"h-4 w-4 text-muted-foreground"})]}),B&&e.jsx("div",{className:"border-t bg-muted/10 p-4 space-y-3",children:O.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($,{variant:"outline",size:"sm",onClick:()=>A(R.id),disabled:d.isPending,children:[e.jsx(nn,{className:"h-3.5 w-3.5 mr-1.5"}),"Create Drip"]})]}):e.jsxs(e.Fragment,{children:[O.map(G=>e.jsx(zbt,{template:G,isEditing:x===G.id,onToggleEdit:()=>y(x===G.id?null:G.id),onToggleEnabled:()=>C(G),onUpdate:H=>u.mutateAsync({id:G.id,...H}),onDelete:()=>M(G.id),userId:s||""},G.id)),e.jsxs($,{variant:"ghost",size:"sm",className:"w-full text-xs text-muted-foreground",onClick:()=>A(R.id),children:[e.jsx(nn,{className:"h-3 w-3 mr-1"})," Add another drip"]})]})})]},R.id)}),o.filter(R=>R.is_won_stage||R.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(R=>R.is_won_stage||R.is_lost_stage).map(R=>{const O=j(R.id),B=p===R.id,U=O.some(G=>G.is_enabled);return e.jsxs("div",{className:"border rounded-xl overflow-hidden mb-2",children:[e.jsxs("button",{onClick:()=>g(B?null:R.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:R.color||"#94A3B8"}}),e.jsx("span",{className:"font-medium text-sm flex-1",children:R.name}),O.length>0&&e.jsxs(qe,{variant:"outline",className:`text-[10px] ${U?"bg-emerald-500/10 text-emerald-600 border-emerald-200":"text-muted-foreground"}`,children:[O.length," drip",O.length!==1?"s":"",U&&" · Active"]}),B?e.jsx(Go,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(fi,{className:"h-4 w-4 text-muted-foreground"})]}),B&&e.jsx("div",{className:"border-t bg-muted/10 p-4 space-y-3",children:O.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($,{variant:"outline",size:"sm",onClick:()=>A(R.id),disabled:d.isPending,children:[e.jsx(nn,{className:"h-3.5 w-3.5 mr-1.5"})," Create Drip"]})]}):e.jsxs(e.Fragment,{children:[O.map(G=>e.jsx(zbt,{template:G,isEditing:x===G.id,onToggleEdit:()=>y(x===G.id?null:G.id),onToggleEnabled:()=>C(G),onUpdate:H=>u.mutateAsync({id:G.id,...H}),onDelete:()=>M(G.id),userId:s||""},G.id)),e.jsxs($,{variant:"ghost",size:"sm",className:"w-full text-xs text-muted-foreground",onClick:()=>A(R.id),children:[e.jsx(nn,{className:"h-3 w-3 mr-1"})," Add another drip"]})]})})]},R.id)})]})]})}),e.jsx(cs,{value:"starters",children:_.length===0?e.jsxs("div",{className:"text-center py-12 border border-dashed rounded-xl",children:[e.jsx(kn,{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:_.map(R=>e.jsx(P7n,{template:R,onCopy:()=>I(R.id),isCopying:m.isPending},R.id))})})]})]})})}function zbt({template:s,isEditing:t,onToggleEdit:n,onToggleEnabled:r,onUpdate:a,onDelete:i,userId:l}){const[o,c]=k.useState(s.title),[d,u]=k.useState(s.subject),[h,m]=k.useState(s.body),[p,g]=k.useState(s.video_url||""),[x,y]=k.useState(s.channel),[v,_]=k.useState(s.delay_type),[j,C]=k.useState(s.delay_minutes),[A,M]=k.useState(!1),I=async()=>{M(!0);try{await a({title:o,subject:d,body:h,video_url:p||null,channel:x,delay_type:v,delay_minutes:j}),ae.success("Drip saved"),n()}catch{ae.error("Failed to save")}finally{M(!1)}},P=R=>{m(O=>O+R)};return e.jsxs("div",{className:"border rounded-lg bg-background overflow-hidden",children:[e.jsxs("div",{className:"flex items-center gap-3 p-3",children:[e.jsxs("div",{className:"flex-1 min-w-0",role:"button",onClick:n,children:[e.jsx("p",{className:"text-sm font-medium truncate",children:s.title||"Untitled drip"}),e.jsxs("div",{className:"flex items-center gap-2 mt-0.5",children:[s.channel==="sms"?e.jsx(bo,{className:"h-3 w-3 text-muted-foreground"}):e.jsx(pn,{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(ia,{className:"h-3 w-3 text-primary"})]})]}),e.jsx(On,{checked:s.is_enabled,onCheckedChange:r})]}),t&&e.jsxs("div",{className:"border-t p-4 space-y-4",children:[e.jsxs("div",{children:[e.jsx(re,{className:"text-xs font-medium",children:"Title (internal)"}),e.jsx(be,{value:o,onChange:R=>c(R.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(re,{className:"text-xs font-medium",children:"Channel"}),e.jsx("div",{className:"flex gap-1 mt-1",children:["email","sms"].map(R=>e.jsxs("button",{onClick:()=>y(R),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 ${x===R?"bg-primary text-primary-foreground border-primary":"bg-background text-muted-foreground border-input hover:border-primary/50"}`,children:[R==="sms"?e.jsx(bo,{className:"h-3 w-3"}):e.jsx(pn,{className:"h-3 w-3"}),R==="sms"?"SMS":"Email"]},R))})]}),e.jsxs("div",{className:"flex-1",children:[e.jsx(re,{className:"text-xs font-medium",children:"Timing"}),e.jsxs("div",{className:"flex gap-1 mt-1",children:[e.jsx("button",{onClick:()=>_("instant"),className:`flex-1 px-3 py-1.5 rounded-md text-xs font-medium border transition-colors ${v==="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:()=>_("scheduled"),className:`flex-1 px-3 py-1.5 rounded-md text-xs font-medium border transition-colors ${v==="scheduled"?"bg-primary text-primary-foreground border-primary":"bg-background text-muted-foreground border-input hover:border-primary/50"}`,children:[e.jsx(sa,{className:"h-3 w-3 mr-1 inline"}),"Delay"]})]})]})]}),v==="scheduled"&&e.jsxs("div",{children:[e.jsx(re,{className:"text-xs font-medium",children:"Delay"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(be,{type:"number",min:1,value:j>=60?Math.round(j/60):j,onChange:R=>{const O=parseInt(R.target.value)||0;C(j>=60?O*60:O)},className:"h-8 w-20 text-sm"}),e.jsx("div",{className:"flex gap-1",children:[{label:"Minutes",mins:j<60?j:30},{label:"Hours",mins:j>=60?j:60},{label:"Days",mins:j>=1440?j:1440}].map(R=>e.jsx("button",{className:`px-2 py-1 rounded text-xs border transition-colors ${R.label==="Minutes"&&j<60||R.label==="Hours"&&j>=60&&j<1440||R.label==="Days"&&j>=1440?"bg-primary/10 text-primary border-primary/30":"text-muted-foreground border-input"}`,onClick:()=>{R.label==="Minutes"?C(30):R.label==="Hours"?C(60):C(1440)},children:R.label},R.label))})]})]}),x==="email"&&e.jsxs("div",{children:[e.jsx(re,{className:"text-xs font-medium",children:"Subject Line"}),e.jsx(be,{value:d,onChange:R=>u(R.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(re,{className:"text-xs font-medium",children:x==="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:R=>{R.target.value&&P(R.target.value),R.target.value=""},children:[e.jsx("option",{value:"",children:"Merge variable..."}),g7n.map(R=>e.jsx("option",{value:R.key,children:R.label},R.key))]})]})]}),e.jsx("textarea",{value:h,onChange:R=>m(R.target.value),placeholder:x==="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(re,{className:"text-xs font-medium",children:"Attached Video"}),p?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(ia,{className:"h-3 w-3 inline mr-1 text-primary"}),p.length>50?p.slice(0,50)+"...":p]}),e.jsx($,{variant:"ghost",size:"sm",className:"h-7 text-xs text-destructive",onClick:()=>g(""),children:"Remove"})]}):e.jsxs("div",{className:"mt-1 flex items-center gap-1.5",children:[e.jsx(hQe,{onVideoReady:R=>g(R)}),e.jsx(BF,{userId:l,onSelect:R=>g(R),triggerSize:"sm",triggerClassName:"gap-1.5 flex-1"}),e.jsxs($,{variant:"ghost",size:"sm",className:"gap-1 text-xs text-muted-foreground flex-1",onClick:()=>{const R=prompt("Paste a YouTube or Loom URL:");R&&g(R)},children:[e.jsx(od,{className:"h-3 w-3"})," Paste URL"]})]})]}),e.jsxs("div",{className:"flex items-center justify-between pt-2 border-t",children:[e.jsxs($,{variant:"ghost",size:"sm",className:"text-xs text-destructive hover:text-destructive",onClick:i,children:[e.jsx(Un,{className:"h-3 w-3 mr-1"})," Delete"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{variant:"outline",size:"sm",className:"text-xs",onClick:n,children:"Cancel"}),e.jsx($,{size:"sm",className:"text-xs",onClick:I,disabled:A,children:A?"Saving...":"Save Drip"})]})]})]})]})}function P7n({template:s,onCopy:t,isCopying:n}){const[r,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(!r),className:"w-full flex items-start gap-3 p-4 text-left hover:bg-muted/30 transition-colors",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h4",{className:"font-medium text-sm",children:s.title}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 truncate",children:s.subject}),!r&&e.jsx("p",{className:"text-xs text-muted-foreground/70 line-clamp-1 mt-1",children:i})]}),e.jsxs("div",{className:"flex items-center gap-1.5 shrink-0 pt-0.5",children:[l&&e.jsx(qe,{variant:"secondary",className:"text-[10px] px-1.5 py-0",children:l}),e.jsxs(qe,{variant:"outline",className:"text-[10px] gap-1",children:[s.channel==="sms"?e.jsx(bo,{className:"h-3 w-3"}):e.jsx(pn,{className:"h-3 w-3"}),s.channel==="sms"?"SMS":"Email"]}),e.jsxs(qe,{variant:"outline",className:"text-[10px] gap-1",children:[e.jsx(sa,{className:"h-3 w-3"}),s.delay_type==="instant"?"Instant":o.replace("Sends ","")]}),r?e.jsx(Go,{className:"h-4 w-4 text-muted-foreground ml-1"}):e.jsx(fi,{className:"h-4 w-4 text-muted-foreground ml-1"})]})]}),r&&e.jsxs("div",{className:"border-t bg-muted/10 p-4 space-y-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] uppercase font-semibold text-muted-foreground tracking-wider mb-1",children:"Subject Line"}),e.jsx("p",{className:"text-sm font-medium",children:s.subject})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] uppercase font-semibold text-muted-foreground tracking-wider mb-1",children:"Email Body"}),e.jsx("div",{className:"text-sm text-foreground/80 bg-background rounded-lg border p-4 prose prose-sm max-w-none [&_ul]:list-disc [&_ul]:pl-5 [&_ol]:list-decimal [&_ol]:pl-5 [&_li]:my-0.5 [&_p]:my-2 [&_a]:text-primary [&_a]:underline",dangerouslySetInnerHTML:{__html:s.body}})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx(sa,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:o})]}),e.jsxs($,{onClick:c=>{c.stopPropagation(),t()},size:"sm",className:"w-full gap-1.5",disabled:n,children:[e.jsx(Da,{className:"h-3.5 w-3.5"}),"Use This Template"]})]})]})}const tHt=()=>{const s=Tu();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 I7n(){return k.useEffect(()=>(document.body.classList.add("cardstudio-page"),()=>{document.body.classList.remove("cardstudio-page")}),[]),e.jsxs($Z,{children:[e.jsx(fs,{path:"/c/:shareToken",element:e.jsx(JVt,{})}),e.jsx(fs,{path:"*",element:e.jsx(tHt,{})})]})}const n8e={Home:"🏠",Search:"🔍",DollarSign:"💰",Coffee:"☕",Calendar:"📅",Users:"👥",Phone:"📞",Video:"🎥"},L7n=["America/New_York","America/Chicago","America/Denver","America/Phoenix","America/Los_Angeles","America/Anchorage","Pacific/Honolulu","Europe/London","Europe/Paris","Asia/Dubai","Asia/Singapore","Asia/Tokyo","Australia/Sydney"];function R7n(s,t,n){const[r,a,i]=s.split("-").map(Number),[l,o]=t.split(":").map(Number),c=Date.UTC(r,a-1,i,l,o),d=new Intl.DateTimeFormat("en-US",{timeZone:n,hour12:!1,year:"numeric",month:"2-digit",day:"2-digit",hour:"2-digit",minute:"2-digit"}),u=Object.fromEntries(d.formatToParts(new Date(c)).filter(m=>m.type!=="literal").map(m=>[m.type,m.value])),h=Date.UTC(Number(u.year),Number(u.month)-1,Number(u.day),Number(u.hour)%24,Number(u.minute));return c+(c-h)}function r8e(s){var t;try{return((t=new Intl.DateTimeFormat("en-US",{timeZone:s,timeZoneName:"short"}).formatToParts(new Date).find(r=>r.type==="timeZoneName"))==null?void 0:t.value)||s}catch{return s}}function sHt({slugOverride:s}){const t=oo(),n=s||t.slug,[r,a]=k.useState("types"),[i,l]=k.useState(null),[o,c]=k.useState(null),[d,u]=k.useState(null),[h,m]=k.useState(new Date),[p,g]=k.useState({name:"",email:"",phone:"",message:""}),[x,y]=k.useState(!1),[v,_]=k.useState(null),[j,C]=k.useState(()=>{try{return Intl.DateTimeFormat().resolvedOptions().timeZone||"America/New_York"}catch{return"America/New_York"}}),{data:A,isLoading:M}=pt({queryKey:["public-booking-settings",n],queryFn:async()=>{const{data:Q,error:te}=await V.from("agent_booking_settings").select("*").eq("slug",n).eq("is_active",!0).single();if(te)throw te;return Q},enabled:!!n}),{data:I}=pt({queryKey:["public-booking-profile",A==null?void 0:A.user_id],queryFn:async()=>{const{data:Q,error:te}=await V.from("profiles").select("name, avatar_url, email, phone, title, bio").eq("id",A.user_id).single();if(te)throw te;return Q},enabled:!!(A!=null&&A.user_id)}),{data:P=[]}=pt({queryKey:["public-booking-types",A==null?void 0:A.user_id],queryFn:async()=>{const{data:Q,error:te}=await V.from("agent_booking_types").select("id, name, description, duration_minutes, color, icon, qualification_enabled").eq("user_id",A.user_id).eq("is_active",!0).eq("is_coaching_only",!1).order("sort_order");if(te)throw te;return Q},enabled:!!(A!=null&&A.user_id)}),R=Ys(h,"yyyy-MM"),{data:O={},isFetching:B}=pt({queryKey:["public-availability-map",n,i==null?void 0:i.id,R],enabled:!!n&&!!i,staleTime:6e4,queryFn:async()=>{const Q=new Date(h.getFullYear(),h.getMonth(),1),te=np(new Date),le=N_(te,Q)?te:Q,fe=new Date(h.getFullYear(),h.getMonth()+1,0),_e=Math.max(1,Math.round((fe.getTime()-le.getTime())/864e5)+1),{data:ve,error:he}=await V.functions.invoke("agent-booking",{body:{action:"availability",slug:n,booking_type_id:i.id,start:Ys(le,"yyyy-MM-dd"),days:Math.min(_e,90)}});if(he)throw he;if(ve!=null&&ve.error)throw new Error(ve.error);return(ve==null?void 0:ve.availability)||{}}}),U=Q=>{const te=np(new Date),le=wu(te,(A==null?void 0:A.max_advance_days)||30);return Xw(Q,te)||N_(Q,le)?!1:(O[Ys(Q,"yyyy-MM-dd")]||[]).length>0},G=k.useMemo(()=>o?O[Ys(o,"yyyy-MM-dd")]||[]:[],[o,O]),H=k.useMemo(()=>{const Q=h.getFullYear(),te=h.getMonth(),le=new Date(Q,te,1),fe=new Date(Q,te+1,0),_e=le.getDay(),ve=[];for(let he=0;he<_e;he++)ve.push(null);for(let he=1;he<=fe.getDate();he++)ve.push(new Date(Q,te,he));return ve},[h]),Y=async()=>{var Q,te;if(!(!i||!o||!d||!p.name||!A)){y(!0);try{const le=Ys(o,"yyyy-MM-dd"),{data:fe,error:_e}=await V.functions.invoke("agent-booking",{body:{action:"create",slug:n,booking_type_id:i.id,date:le,time:d,guest_name:p.name,guest_email:p.email||null,guest_phone:p.phone||null,guest_message:p.message||null,guest_timezone:j}});if(_e){let Se=_e.message;try{const Te=await((te=(Q=_e.context)==null?void 0:Q.json)==null?void 0:te.call(Q));Te!=null&&Te.error&&(Se=Te.error)}catch{}throw new Error(Se)}if(fe!=null&&fe.error)throw new Error(fe.error);const ve=(fe==null?void 0:fe.end_time)||d,he=fe!=null&&fe.manage_token?`${window.location.origin}/booking/manage/${fe.manage_token}`:null;_(he),V.functions.invoke("booking-notify",{body:{agentUserId:A.user_id,guestName:p.name,guestEmail:p.email||null,guestPhone:p.phone||null,guestMessage:p.message||null,bookingTypeName:i.name,bookingDate:le,startTime:d,endTime:ve,durationMinutes:i.duration_minutes,meetingLink:A.meeting_link||null,manageUrl:he}}).catch(Se=>console.error("Booking notify error:",Se)),a("confirmed")}catch(le){ae.error("Failed to book: "+le.message)}finally{y(!1)}}},se=Q=>{const[te,le]=Q.split(":").map(Number),fe=te>=12?"PM":"AM";return`${te%12||12}:${le.toString().padStart(2,"0")} ${fe}`},ee=(A==null?void 0:A.timezone)||"America/New_York",oe=j!==ee,me=(Q,te)=>{if(!oe)return se(te);try{return new Intl.DateTimeFormat("en-US",{timeZone:j,hour:"numeric",minute:"2-digit"}).format(new Date(R7n(Q,te,ee)))}catch{return se(te)}};return M?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..."})]})}):A?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:[I!=null&&I.avatar_url?e.jsx("img",{src:I.avatar_url,alt:(I==null?void 0:I.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(el,{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:(I==null?void 0:I.name)||"Agent"}),(I==null?void 0:I.title)&&e.jsx("p",{className:"text-sm text-slate-500 mt-0.5",children:I.title})]})]})}),e.jsxs("div",{className:"px-6 py-4 flex flex-wrap gap-2",children:[(I==null?void 0:I.phone)&&e.jsxs("a",{href:`tel:${I.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(ka,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"hidden sm:inline",children:I.phone}),e.jsx("span",{className:"sm:hidden",children:"Call"})]}),(I==null?void 0:I.email)&&e.jsxs("a",{href:`mailto:${I.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(pn,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"hidden sm:inline",children:I.email}),e.jsx("span",{className:"sm:hidden",children:"Email"})]})]})]}),e.jsx("div",{className:"bg-white rounded-2xl shadow-lg shadow-slate-200/60 border border-slate-100 overflow-hidden",children:e.jsxs("div",{className:"p-5 sm:p-6",children:[r==="types"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-base font-semibold text-slate-800",children:"Select a meeting type"}),e.jsx("p",{className:"text-xs text-slate-400 mt-0.5",children:"Choose the type of meeting you'd like to schedule"})]}),e.jsx("div",{className:"space-y-2.5",children:P.map(Q=>e.jsx("button",{onClick:()=>{l(Q),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:Q.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:n8e[Q.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:Q.name}),Q.description&&e.jsx("p",{className:"text-xs text-slate-500 mt-0.5 line-clamp-2",children:Q.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(sa,{className:"h-3 w-3"}),Q.duration_minutes,"m"]})]})})},Q.id))})]}),r==="date"&&i&&e.jsxs("div",{className:"space-y-5",children:[e.jsxs("button",{onClick:()=>{a("types"),c(null),u(null)},className:"flex items-center gap-1.5 text-xs font-medium text-slate-500 hover:text-slate-800 transition-colors",children:[e.jsx(Ia,{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:n8e[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(sa,{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:Ys(h,"MMMM yyyy")}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx("button",{className:"h-8 w-8 rounded-lg flex items-center justify-center text-slate-500 hover:bg-slate-100 hover:text-slate-800 transition-colors",onClick:()=>m(new Date(h.getFullYear(),h.getMonth()-1)),children:e.jsx(Ld,{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:()=>m(new Date(h.getFullYear(),h.getMonth()+1)),children:e.jsx(fi,{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(Q=>e.jsx("div",{className:"text-[10px] uppercase tracking-wider text-slate-400 font-semibold py-2",children:Q},Q)),H.map((Q,te)=>{if(!Q)return e.jsx("div",{},`pad-${te}`);const le=U(Q),fe=o&&ah(Q,o),_e=ah(Q,new Date);return e.jsx("button",{disabled:!le,onClick:()=>{c(Q),u(null)},className:`h-10 w-10 mx-auto rounded-xl text-sm font-medium transition-all duration-150 ${fe?"bg-[#406E71] text-white shadow-md shadow-[#406E71]/30 scale-105":le?"hover:bg-[#406E71]/10 text-slate-700 hover:text-[#406E71]":"text-slate-200 cursor-not-allowed"} ${_e&&!fe?"ring-1 ring-[#406E71]/40":""}`,children:Q.getDate()},Q.toISOString())})]})]}),o&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(fd,{className:"h-4 w-4 text-[#406E71]"}),e.jsx("h3",{className:"font-semibold text-sm text-slate-800",children:Ys(o,"EEEE, MMMM d")})]}),e.jsxs("div",{className:"flex items-center justify-between gap-2 rounded-xl bg-slate-50 border border-slate-100 px-3 py-2",children:[e.jsx("span",{className:"text-[11px] text-slate-500",children:"Times shown in your timezone"}),e.jsx("select",{value:j,onChange:Q=>C(Q.target.value),className:"text-[11px] font-medium text-slate-700 bg-transparent focus:outline-none cursor-pointer",children:Array.from(new Set([j,ee,...L7n])).map(Q=>e.jsxs("option",{value:Q,children:[Q.replace(/_/g," ")," (",r8e(Q),")"]},Q))})]}),B&&G.length===0?e.jsxs("div",{className:"text-center py-8 space-y-2",children:[e.jsx(Jt,{className:"h-6 w-6 text-slate-300 mx-auto animate-spin"}),e.jsx("p",{className:"text-sm text-slate-400",children:"Checking live availability…"})]}):G.length===0?e.jsxs("div",{className:"text-center py-8 space-y-2",children:[e.jsx(sa,{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:G.map(Q=>{const te=d===Q;return e.jsx("button",{onClick:()=>u(Q),className:`px-3 py-2.5 rounded-xl text-sm font-medium transition-all duration-150 ${te?"bg-[#406E71] text-white shadow-md shadow-[#406E71]/30 scale-[1.02]":"bg-slate-50 text-slate-700 hover:bg-[#406E71]/10 hover:text-[#406E71] border border-slate-150"}`,children:me(Ys(o,"yyyy-MM-dd"),Q)},Q)})}),d&&e.jsx($,{className:"w-full h-12 rounded-xl bg-[#406E71] hover:bg-[#365c5e] text-white font-semibold shadow-md shadow-[#406E71]/20 transition-all hover:shadow-lg",onClick:()=>a("form"),children:"Continue to Details"})]})]}),r==="form"&&i&&o&&d&&e.jsxs("div",{className:"space-y-5",children:[e.jsxs("button",{onClick:()=>a("date"),className:"flex items-center gap-1.5 text-xs font-medium text-slate-500 hover:text-slate-800 transition-colors",children:[e.jsx(Ia,{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:n8e[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(fd,{className:"h-3.5 w-3.5 text-[#406E71]"}),Ys(o,"EEE, MMM d, yyyy")]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(sa,{className:"h-3.5 w-3.5 text-[#406E71]"}),me(Ys(o,"yyyy-MM-dd"),d)," (",r8e(j),") · ",i.duration_minutes," min"]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{className:"text-xs font-semibold text-slate-700",children:"Full Name *"}),e.jsx(be,{value:p.name,onChange:Q=>g({...p,name:Q.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(re,{className:"text-xs font-semibold text-slate-700",children:"Email"}),e.jsxs("div",{className:"relative",children:[e.jsx(pn,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400"}),e.jsx(be,{type:"email",value:p.email,onChange:Q=>g({...p,email:Q.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(re,{className:"text-xs font-semibold text-slate-700",children:"Phone"}),e.jsxs("div",{className:"relative",children:[e.jsx(ka,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400"}),e.jsx(be,{type:"tel",value:p.phone,onChange:Q=>g({...p,phone:Q.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(re,{className:"text-xs font-semibold text-slate-700",children:"Message (optional)"}),e.jsx(Ls,{value:p.message,onChange:Q=>g({...p,message:Q.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($,{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:Y,disabled:!p.name||x,children:x?e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"animate-spin rounded-full h-4 w-4 border-2 border-white border-t-transparent"}),"Booking..."]}):"Confirm Booking"})]}),r==="confirmed"&&e.jsxs("div",{className:"text-center space-y-5 py-6",children:[e.jsxs("div",{className:"relative mx-auto w-20 h-20",children:[e.jsx("div",{className:"absolute inset-0 rounded-full bg-emerald-100 animate-ping opacity-30"}),e.jsx("div",{className:"relative w-20 h-20 rounded-full bg-gradient-to-br from-emerald-400 to-emerald-600 flex items-center justify-center shadow-lg shadow-emerald-200",children:e.jsx(Gr,{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 ",(I==null?void 0:I.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&&Ys(o,"EEEE, MMMM d, yyyy")}),e.jsxs("p",{className:"text-slate-500",children:[o&&d?`${me(Ys(o,"yyyy-MM-dd"),d)} (${r8e(j)})`:""," · ",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."}),v&&e.jsx("div",{className:"pt-1",children:e.jsx("a",{href:v,className:"inline-flex items-center gap-1.5 text-xs font-semibold text-[#406E71] underline underline-offset-4",children:"Reschedule or cancel this meeting"})}),((I==null?void 0:I.phone)||(I==null?void 0:I.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:[(I==null?void 0:I.phone)&&e.jsxs("a",{href:`tel:${I.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(ka,{className:"h-3.5 w-3.5"})," Call"]}),(I==null?void 0:I.email)&&e.jsxs("a",{href:`mailto:${I.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(pn,{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(fd,{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 D7n(){const t=Tu().pathname.slice(1).split("/")[0];return k.useEffect(()=>{document.body.classList.add("booking-page");const n=()=>{['[id*="lc_text_widget"]','[id*="lc_text-widget"]','[class*="lc-text-widget"]','[class*="lc_text-widget"]','[class*="lc_text_widget"]',".lc_text-widget--bubble",'[id*="chat-widget"]','[class*="chat-widget"]','iframe[src*="widgets.leadconnectorhq"]','iframe[src*="leadconnector"]','iframe[src*="msgsndr"]',"[data-chat-widget]","[data-widget-id]",'div[style*="z-index"][style*="position: fixed"][style*="bottom"]','div[id^="fc_"]','div[id^="hubspot"]',".widget-visible"].forEach(i=>{document.querySelectorAll(i).forEach(l=>{l.style.display="none"})})};n();const r=[setTimeout(n,500),setTimeout(n,1500),setTimeout(n,3e3),setTimeout(n,5e3)];return()=>{document.body.classList.remove("booking-page"),r.forEach(clearTimeout)}},[]),t?e.jsx(sHt,{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 O7n(){const t=Tu().pathname.slice(1);return k.useEffect(()=>{document.body.classList.add("connect-page");const n=()=>{['[id*="lc_text_widget"]','[id*="lc_text-widget"]','[class*="lc-text-widget"]','[class*="lc_text-widget"]','[class*="lc_text_widget"]',".lc_text-widget--bubble",'[id*="chat-widget"]','[class*="chat-widget"]','iframe[src*="widgets.leadconnectorhq"]','iframe[src*="leadconnector"]','iframe[src*="msgsndr"]',"[data-chat-widget]","[data-widget-id]",'div[style*="z-index"][style*="position: fixed"][style*="bottom"]','div[id^="fc_"]','div[id^="hubspot"]',".widget-visible"].forEach(i=>{document.querySelectorAll(i).forEach(l=>{l.style.display="none"})})};n();const r=[setTimeout(n,500),setTimeout(n,1500),setTimeout(n,3e3),setTimeout(n,5e3)];return()=>{document.body.classList.remove("connect-page"),r.forEach(clearTimeout)}},[]),!t||t===""?e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-slate-50 via-white to-slate-100 flex items-center justify-center p-6",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"text-2xl font-bold text-slate-800 mb-2",children:"Connect"}),e.jsx("p",{className:"text-slate-500",children:"Stay connected with your real estate professional."}),e.jsx("p",{className:"text-slate-400 text-sm mt-2",children:"Visit a specific agent link to get started."})]})}):e.jsx(EMt,{slugOverride:t})}function F7n(s){try{const t=document.createElement("canvas"),n=t.width=Math.min(s.naturalWidth,64),r=t.height=Math.min(s.naturalHeight,64),a=t.getContext("2d");if(!a)return!0;a.drawImage(s,0,0,n,r);const i=a.getImageData(0,0,n,r).data,l=[[0,0],[n-1,0],[0,r-1],[n-1,r-1],[Math.floor(n/2),0],[Math.floor(n/2),r-1],[0,Math.floor(r/2)],[n-1,Math.floor(r/2)]];for(const[o,c]of l)if(i[(c*n+o)*4+3]<250)return!0;return!1}catch{return!0}}const z7n={playfair:"'Playfair Display', Georgia, serif",baskerville:"'Libre Baskerville', Georgia, serif",instrument:"'Instrument Serif', Georgia, serif",sans:"'Inter', system-ui, sans-serif"};function B7n({page:s,fields:t,answers:n,setAnswers:r,onSubmit:a,isSubmitting:i,renderField:l}){const o=s.accent_color||"#E8B84A",c=s.primary_color||"#0F1B3D",d=z7n[s.heading_font||"playfair"],u=s.eyebrow||null,h=s.headline_accent||null,m=Array.isArray(s.trust_pills)?s.trust_pills:[],p=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($7n,{src:s.logo_url}),u&&e.jsx("p",{className:"text-xs md:text-sm font-semibold tracking-[0.22em] text-white/80 mb-4 uppercase",children:u}),e.jsxs("h1",{className:"font-bold leading-[1.04] mb-5 text-4xl sm:text-5xl md:text-6xl lg:text-[68px]",style:{fontFamily:d,letterSpacing:"-0.015em"},children:[s.hero_headline,h&&e.jsxs(e.Fragment,{children:[" ",e.jsx("span",{style:{color:o,fontStyle:"italic"},children:h})]})]}),s.hero_subtext&&e.jsx("p",{className:"text-base md:text-lg text-white/85 leading-relaxed max-w-xl",children:s.hero_subtext}),s.agent_name&&e.jsxs("div",{className:"mt-8 flex items-center gap-3",children:[s.agent_photo_url&&e.jsx("img",{src:s.agent_photo_url,alt:s.agent_name,className:"h-12 w-12 rounded-full object-cover ring-2 ring-white/30"}),e.jsxs("div",{className:"text-white/90",children:[e.jsx("p",{className:"font-semibold text-sm",children:s.agent_name}),e.jsxs("div",{className:"flex flex-wrap gap-x-4 gap-y-1 text-xs text-white/70 mt-0.5",children:[s.agent_phone&&e.jsxs("a",{href:`tel:${s.agent_phone}`,className:"flex items-center gap-1 hover:text-white",children:[e.jsx(ka,{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(pn,{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:[p.map(g=>e.jsxs("div",{children:[e.jsxs(re,{className:"block text-[11px] font-semibold tracking-wider uppercase text-white/85 mb-1.5",children:[g.label,g.is_required&&e.jsx("span",{className:"ml-1",style:{color:o},children:"*"})]}),e.jsx("div",{className:"[&_input]:bg-white/95 [&_input]:border-0 [&_input]:text-neutral-900 [&_input]:placeholder:text-neutral-400 [&_textarea]:bg-white/95 [&_textarea]:border-0 [&_textarea]:text-neutral-900 [&_textarea]:placeholder:text-neutral-400 [&_button[role=combobox]]:bg-white/95 [&_button[role=combobox]]:border-0 [&_button[role=combobox]]:text-neutral-900",children:l(g,n,r,c)})]},g.id)),e.jsx("button",{type:"submit",disabled:i,className:"w-full px-6 py-3.5 rounded-lg font-bold text-neutral-900 text-base md:text-lg shadow-lg hover:brightness-110 active:brightness-95 transition-all disabled:opacity-60 mt-2",style:{backgroundColor:o},children:i?"Submitting...":s.cta_text||"Get Started"})]}),m.length>0&&e.jsx("div",{className:"flex flex-wrap gap-x-5 gap-y-2 mt-4",children:m.map((g,x)=>e.jsxs("span",{className:"flex items-center gap-1.5 text-[11px] md:text-xs text-white/80 font-medium",children:[e.jsx("span",{className:"h-1 w-1 rounded-full",style:{backgroundColor:o}}),g]},x))})]})})]})})]})}function $7n({src:s}){const[t,n]=k.useState(null),r=e.jsx("img",{src:s,alt:"Logo",crossOrigin:"anonymous",className:"h-10 md:h-12 w-auto object-contain",onLoad:a=>n(F7n(a.currentTarget)),onError:()=>n(!0)});return t===!1?e.jsx("span",{className:"inline-flex items-center rounded-md bg-white/90 backdrop-blur px-3 py-2 mb-6 shadow-sm",children:r}):e.jsx("div",{className:"mb-6 inline-block drop-shadow-md",children:r})}function U7n(s){const t=Math.max(0,Math.floor(s/1e3));return{d:Math.floor(t/86400),h:Math.floor(t%86400/3600),m:Math.floor(t%3600/60),s:t%60}}function q7n(s,t,n){const r=new Date(t),a=new Date(r.getTime()+60*60*1e3),i=o=>o.toISOString().replace(/[-:]|\.\d{3}/g,""),l=new URL("https://www.google.com/calendar/render");return l.searchParams.set("action","TEMPLATE"),l.searchParams.set("text",s),l.searchParams.set("dates",`${i(r)}/${i(a)}`),n&&l.searchParams.set("location",n),l.toString()}function V7n(s,t,n){const r=new Date(t),a=new Date(r.getTime()+60*60*1e3),i=o=>o.toISOString().replace(/[-:]|\.\d{3}/g,""),l=["BEGIN:VCALENDAR","VERSION:2.0","BEGIN:VEVENT",`UID:${Date.now()}@levelup`,`DTSTAMP:${i(new Date)}`,`DTSTART:${i(r)}`,`DTEND:${i(a)}`,`SUMMARY:${s}`,n?`LOCATION:${n}`:"","END:VEVENT","END:VCALENDAR"].filter(Boolean).join(`\r `);return`data:text/calendar;charset=utf-8,${encodeURIComponent(l)}`}function H7n({startsAt:s,locationName:t,address:n,title:r,accent:a}){const[i,l]=k.useState(Date.now());k.useEffect(()=>{const p=setInterval(()=>l(Date.now()),1e3);return()=>clearInterval(p)},[]);const o=new Date(s).getTime();if(!Number.isFinite(o))return null;const c=U7n(o-i),d=o-i<=0,u=new Date(s).toLocaleString("en-US",{weekday:"long",month:"long",day:"numeric",hour:"numeric",minute:"2-digit"}),h=[t,n].filter(Boolean).join(" · "),m=n?`https://www.google.com/maps/search/?api=1&query=${encodeURIComponent(n)}`:null;return e.jsx("section",{className:"max-w-5xl mx-auto px-4 py-10",children:e.jsx("div",{className:"rounded-2xl border bg-white/80 backdrop-blur p-6 md:p-8 shadow-sm",children:e.jsxs("div",{className:"flex flex-col md:flex-row md:items-center md:justify-between gap-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("div",{className:"text-xs uppercase tracking-wider font-medium",style:{color:a},children:d?"Just happened":"Event starts in"}),d?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Missed this one? Submit the form and we'll let you know about the next one."}):e.jsx("div",{className:"flex items-baseline gap-3",children:[{v:c.d,l:"days"},{v:c.h,l:"hrs"},{v:c.m,l:"min"},{v:c.s,l:"sec"}].map(p=>e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"text-3xl md:text-4xl font-bold tabular-nums",style:{color:a},children:String(p.v).padStart(2,"0")}),e.jsx("div",{className:"text-[10px] uppercase tracking-wider text-muted-foreground",children:p.l})]},p.l))}),e.jsxs("div",{className:"flex flex-wrap items-center gap-x-4 gap-y-1 pt-2 text-sm text-neutral-700",children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx(sa,{className:"h-3.5 w-3.5"})," ",u]}),h&&e.jsxs("a",{href:m||"#",target:m?"_blank":void 0,rel:"noreferrer",className:"inline-flex items-center gap-1.5 hover:underline",children:[e.jsx(Si,{className:"h-3.5 w-3.5"})," ",h]})]})]}),!d&&e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs("a",{href:q7n(r,s,h||null),target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-2 text-sm font-medium rounded-lg border px-3 py-2 hover:bg-neutral-50",children:[e.jsx(ha,{className:"h-4 w-4"})," Add to Google"]}),e.jsxs("a",{href:V7n(r,s,h||null),download:`${r.replace(/\W+/g,"-").toLowerCase()}.ics`,className:"inline-flex items-center gap-2 text-sm font-medium rounded-lg border px-3 py-2 hover:bg-neutral-50",children:[e.jsx(ha,{className:"h-4 w-4"})," Apple / Outlook"]})]})]})})})}function G7n(){try{const s="_lp_sid";let t=sessionStorage.getItem(s);return t||(t=crypto.randomUUID?crypto.randomUUID():`s_${Date.now()}_${Math.random().toString(36).slice(2)}`,sessionStorage.setItem(s,t)),t}catch{return`s_${Date.now()}`}}function nHt({slugOverride:s}){var B;const{slug:t}=oo(),n=s||t,[r,a]=k.useState(!1),[i,l]=k.useState({}),[o,c]=k.useState(0),[d,u]=k.useState(!1),[h,m]=k.useState(""),[p]=k.useState(()=>Date.now()),g=k.useState(()=>G7n())[0],{data:x,isLoading:y}=pt({queryKey:["public-landing-page",n],queryFn:async()=>{const{data:U,error:G}=await V.from("landing_pages").select("*").eq("slug",n).eq("is_published",!0).single();if(G)throw G;return U},enabled:!!n}),{data:v=[]}=pt({queryKey:["public-landing-page-fields",x==null?void 0:x.id],queryFn:async()=>{const{data:U,error:G}=await V.from("landing_page_fields").select("*").eq("page_id",x.id).order("sort_order");if(G)throw G;return U},enabled:!!(x!=null&&x.id)});k.useEffect(()=>{x!=null&&x.id&&V.from("landing_pages").update({view_count:(x.view_count||0)+1}).eq("id",x.id).then(()=>{})},[x==null?void 0:x.id]),k.useEffect(()=>{if(!(x!=null&&x.id))return;const U=new URLSearchParams(window.location.search);V.functions.invoke("landing-page-track",{body:{page_id:x.id,event_type:"view",session_id:g,utm_source:U.get("utm_source"),utm_medium:U.get("utm_medium"),utm_campaign:U.get("utm_campaign"),referrer:document.referrer||null,device:window.matchMedia("(max-width: 768px)").matches?"mobile":"desktop"}}).catch(()=>{})},[x==null?void 0:x.id,g]);const _=Nt({mutationFn:async()=>{const U=v.find(te=>te.field_type==="text"&&te.label.toLowerCase().includes("name")),G=v.find(te=>te.field_type==="email"),H=v.find(te=>te.field_type==="phone"),Y=U?String(i[U.label]||""):null,se=G?String(i[G.label]||""):null,ee=H?String(i[H.label]||""):null,oe=new URLSearchParams(window.location.search),{data:me,error:Q}=await V.functions.invoke("landing-page-submit",{body:{page_id:x.id,answers:JSON.parse(JSON.stringify(i)),contact_name:Y,contact_email:se,contact_phone:ee,session_id:g,honeypot:h,rendered_at:p,utm_source:oe.get("utm_source"),utm_medium:oe.get("utm_medium"),utm_campaign:oe.get("utm_campaign"),referrer:document.referrer||null}});if(Q)throw Q;return me},onSuccess:U=>{a(!0),U!=null&&U.redirect_url&&setTimeout(()=>{window.location.href=U.redirect_url},1500)}}),j=U=>{U.preventDefault(),!(v.filter(H=>H.is_required&&!i[H.label]).length>0)&&_.mutate()};if(y)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(!x)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 C=x.primary_color||"#406E71",A=x.accent_color||"#2a4c64",M=x,I=x.page_type==="lead_magnet",P=x.page_type==="just_listed"||x.page_type==="just_sold",R=Array.isArray(M.property_photos)?M.property_photos:[],O=M.lead_magnet_file_url||M.lead_magnet_external_url;if(r)return e.jsx("div",{className:"min-h-screen flex items-center justify-center",style:{background:`linear-gradient(135deg, ${C}, ${A})`},children:e.jsxs("div",{className:"bg-white rounded-2xl shadow-2xl p-8 max-w-md mx-4 text-center",children:[e.jsx(Gr,{className:"h-16 w-16 mx-auto mb-4",style:{color:C}}),e.jsx("h2",{className:"text-2xl font-bold mb-2",children:I?"Your download is ready!":"Submitted!"}),e.jsx("p",{className:"text-gray-600",children:x.success_message}),I&&O&&e.jsxs("a",{href:O,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:C},children:[e.jsx(ji,{className:"h-5 w-5"}),"Download ",M.lead_magnet_file_name||"Your File"]}),x.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:x.agent_name}),x.agent_phone&&e.jsxs("a",{href:`tel:${x.agent_phone}`,className:"text-sm flex items-center justify-center gap-1 mt-1",style:{color:C},children:[e.jsx(ka,{className:"h-3 w-3"})," ",x.agent_phone]}),x.agent_email&&e.jsxs("a",{href:`mailto:${x.agent_email}`,className:"text-sm flex items-center justify-center gap-1 mt-1",style:{color:C},children:[e.jsx(pn,{className:"h-3 w-3"})," ",x.agent_email]})]})]})});if(P){const U=G=>{const H=parseFloat(G.replace(/[^0-9.]/g,""));return isNaN(H)?G:new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(H)};return e.jsxs("div",{className:"min-h-screen bg-gray-50",children:[d&&R.length>0&&e.jsxs("div",{className:"fixed inset-0 z-50 bg-black/95 flex items-center justify-center",onClick:()=>u(!1),children:[e.jsx("button",{onClick:()=>u(!1),className:"absolute top-4 right-4 text-white/80 hover:text-white z-10",children:e.jsx(mr,{className:"h-8 w-8"})}),e.jsx("button",{onClick:G=>{G.stopPropagation(),c(H=>H===0?R.length-1:H-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(Ld,{className:"h-6 w-6"})}),e.jsx("img",{src:R[o],alt:`Property photo ${o+1}`,className:"max-h-[90vh] max-w-[90vw] object-contain rounded-lg",onClick:G=>G.stopPropagation()}),e.jsx("button",{onClick:G=>{G.stopPropagation(),c(H=>H===R.length-1?0:H+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(fi,{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," / ",R.length]})]}),R.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:M.property_status==="just_sold"?"#e74c3c":C},children:M.property_status==="just_sold"?"🎉 Just Sold":"🏡 Just Listed"}),R.length===1?e.jsxs("div",{className:"rounded-2xl overflow-hidden cursor-pointer group",onClick:()=>{c(0),u(!0)},children:[e.jsx("img",{src:R[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(aM,{className:"h-4 w-4"})," View"]})]}):R.length===2?e.jsx("div",{className:"grid grid-cols-2 gap-2 rounded-2xl overflow-hidden",children:R.slice(0,2).map((G,H)=>e.jsx("div",{className:"cursor-pointer group relative",onClick:()=>{c(H),u(!0)},children:e.jsx("img",{src:G,alt:`Property ${H+1}`,className:"w-full h-[45vh] object-cover group-hover:scale-105 transition-transform duration-500"})},H))}):e.jsxs("div",{className:"grid grid-cols-4 gap-2 rounded-2xl overflow-hidden",style:{height:"55vh"},children:[e.jsx("div",{className:"col-span-2 row-span-2 cursor-pointer group relative",onClick:()=>{c(0),u(!0)},children:e.jsx("img",{src:R[0],alt:"Property main",className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-500"})}),R.slice(1,5).map((G,H)=>e.jsxs("div",{className:"cursor-pointer group relative",onClick:()=>{c(H+1),u(!0)},children:[e.jsx("img",{src:G,alt:`Property ${H+2}`,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-500"}),H===3&&R.length>5&&e.jsxs("div",{className:"absolute inset-0 bg-black/50 flex items-center justify-center text-white font-bold text-lg",children:["+",R.length-5," more"]})]},H))]}),R.length>2&&e.jsxs("button",{onClick:()=>{c(0),u(!0)},className:"absolute bottom-4 right-8 bg-white shadow-lg hover:shadow-xl text-gray-800 px-4 py-2 rounded-lg text-sm font-medium flex items-center gap-2 transition-shadow",children:[e.jsx(aM,{className:"h-4 w-4"})," View all ",R.length," photos"]})]}),R.length===0&&e.jsx("div",{className:"relative py-16 px-4",style:{background:x.hero_image_url?`linear-gradient(rgba(0,0,0,0.55), rgba(0,0,0,0.55)), url(${x.hero_image_url}) center/cover`:`linear-gradient(135deg, ${C}, ${A})`},children:e.jsxs("div",{className:"max-w-2xl mx-auto text-center text-white",children:[x.logo_url&&e.jsx("img",{src:x.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:x.hero_headline}),x.hero_subtext&&e.jsx("p",{className:"mt-3 text-lg opacity-90",children:x.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:[M.property_price&&e.jsx("p",{className:"text-3xl md:text-4xl font-bold mb-2",style:{color:C},children:U(M.property_price)}),M.property_address&&e.jsxs("p",{className:"text-gray-600 flex items-center gap-1.5 mb-5 text-lg",children:[e.jsx(Si,{className:"h-5 w-5 shrink-0"})," ",M.property_address]}),e.jsxs("div",{className:"flex gap-6 mb-5 py-4 border-y border-gray-100",children:[M.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(Yw,{className:"h-5 w-5",style:{color:C}})," ",M.property_beds]}),e.jsx("p",{className:"text-xs text-gray-500 mt-0.5",children:"Bedrooms"})]}),M.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(p0,{className:"h-5 w-5",style:{color:C}})," ",M.property_baths]}),e.jsx("p",{className:"text-xs text-gray-500 mt-0.5",children:"Bathrooms"})]}),M.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(b3,{className:"h-5 w-5",style:{color:C}})," ",Number(M.property_sqft).toLocaleString()]}),e.jsx("p",{className:"text-xs text-gray-500 mt-0.5",children:"Sq Ft"})]})]}),M.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:M.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:C},children:M.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!"}),x.agent_name&&e.jsxs("div",{className:"flex items-center gap-3 mb-5 pb-4 border-b",children:[x.agent_photo_url&&e.jsx("img",{src:x.agent_photo_url,alt:x.agent_name,className:"h-12 w-12 rounded-full object-cover"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold text-sm",children:x.agent_name}),e.jsxs("div",{className:"flex flex-col gap-0.5 text-xs text-gray-500",children:[x.agent_phone&&e.jsxs("a",{href:`tel:${x.agent_phone}`,className:"flex items-center gap-1 hover:underline",children:[e.jsx(ka,{className:"h-3 w-3"})," ",x.agent_phone]}),x.agent_email&&e.jsxs("a",{href:`mailto:${x.agent_email}`,className:"flex items-center gap-1 hover:underline",children:[e.jsx(pn,{className:"h-3 w-3"})," ",x.agent_email]})]})]})]}),e.jsxs("form",{onSubmit:j,className:"space-y-3",children:[v.map(G=>e.jsxs("div",{children:[e.jsxs(re,{className:"text-xs font-medium",children:[G.label,G.is_required&&e.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),a8e(G,i,l)]},G.id)),e.jsx($,{type:"submit",className:"w-full text-white",style:{backgroundColor:C},disabled:_.isPending,children:_.isPending?"Submitting...":"Submit"}),_.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 x.theme_style!=="classic"&&!I?e.jsxs("div",{className:"min-h-screen bg-neutral-50",children:[e.jsx("input",{type:"text",name:"company_website",tabIndex:-1,autoComplete:"off","aria-hidden":"true",value:h,onChange:U=>m(U.target.value),style:{position:"absolute",left:"-10000px",top:"auto",width:"1px",height:"1px",overflow:"hidden"}}),e.jsx(B7n,{page:x,fields:v,answers:i,setAnswers:l,onSubmit:j,isSubmitting:_.isPending,renderField:a8e}),x.page_type==="event_registration"&&((B=x.settings)==null?void 0:B.event_starts_at)&&e.jsx(H7n,{startsAt:x.settings.event_starts_at,locationName:x.settings.event_location_name,address:x.settings.event_address,title:x.hero_headline||x.title,accent:x.accent_color||x.primary_color||"#406E71"}),_.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:x.hero_image_url?`linear-gradient(rgba(0,0,0,0.55), rgba(0,0,0,0.55)), url(${x.hero_image_url}) center/cover`:`linear-gradient(135deg, ${C}, ${A})`},children:e.jsxs("div",{className:"max-w-2xl mx-auto text-center text-white",children:[x.logo_url&&e.jsx("img",{src:x.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:x.hero_headline}),x.hero_subtext&&e.jsx("p",{className:"mt-3 text-lg opacity-90",children:x.hero_subtext}),I&&M.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(ji,{className:"h-4 w-4"}),"Free Download: ",M.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:[I&&e.jsx("p",{className:"text-sm text-gray-500 mb-4 text-center",children:"Fill out the form below to get your free download!"}),x.agent_name&&e.jsxs("div",{className:"flex items-center gap-3 mb-6 pb-4 border-b",children:[x.agent_photo_url&&e.jsx("img",{src:x.agent_photo_url,alt:x.agent_name,className:"h-12 w-12 rounded-full object-cover"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold",children:x.agent_name}),e.jsxs("div",{className:"flex items-center gap-3 text-sm text-gray-500",children:[x.agent_phone&&e.jsxs("a",{href:`tel:${x.agent_phone}`,className:"flex items-center gap-1 hover:underline",children:[e.jsx(ka,{className:"h-3 w-3"})," ",x.agent_phone]}),x.agent_email&&e.jsxs("a",{href:`mailto:${x.agent_email}`,className:"flex items-center gap-1 hover:underline",children:[e.jsx(pn,{className:"h-3 w-3"})," ",x.agent_email]})]})]})]}),e.jsxs("form",{onSubmit:j,className:"space-y-4",children:[v.map(U=>e.jsxs("div",{children:[e.jsxs(re,{className:"text-sm font-medium",children:[U.label,U.is_required&&e.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),a8e(U,i,l)]},U.id)),e.jsx($,{type:"submit",className:"w-full text-white",style:{backgroundColor:C},disabled:_.isPending,children:_.isPending?"Submitting...":I?"Get My Free Download":"Submit"}),_.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 a8e(s,t,n,r){const a=t[s.label]||"",i=Array.isArray(s.options)?s.options:[];switch(s.field_type){case"text":case"email":case"phone":return e.jsx(be,{type:s.field_type==="email"?"email":s.field_type==="phone"?"tel":"text",value:String(a),onChange:l=>n(o=>({...o,[s.label]:l.target.value})),placeholder:s.placeholder||"",className:"mt-1"});case"textarea":return e.jsx(Ls,{value:String(a),onChange:l=>n(o=>({...o,[s.label]:l.target.value})),placeholder:s.placeholder||"",rows:3,className:"mt-1"});case"select":return e.jsxs(bs,{value:String(a),onValueChange:l=>n(o=>({...o,[s.label]:l})),children:[e.jsx(ys,{className:"mt-1",children:e.jsx(_s,{placeholder:"Select..."})}),e.jsx(vs,{children:i.map(l=>e.jsx(We,{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(Li,{checked:o.includes(l),onCheckedChange:c=>{const d=c?[...o,l]:o.filter(u=>u!==l);n(u=>({...u,[s.label]:d}))}}),e.jsx("span",{className:"text-sm",children:l})]},l)})});case"toggle":return e.jsxs("div",{className:"flex items-center gap-3 mt-1",children:[e.jsx(On,{checked:!!a,onCheckedChange:l=>n(o=>({...o,[s.label]:l?"Yes":"No"}))}),e.jsx("span",{className:"text-sm text-gray-600",children:a?"Yes":"No"})]});default:return e.jsx(be,{value:String(a),onChange:l=>n(o=>({...o,[s.label]:l.target.value})),className:"mt-1"})}}function W7n(){const t=Tu().pathname.slice(1).split("/")[0];return k.useEffect(()=>{document.body.classList.add("landing-page-public");const n=()=>{['[id*="lc_text_widget"]','[class*="lc-text-widget"]','[class*="lc_text_widget"]',".lc_text-widget--bubble",'[id*="chat-widget"]','[class*="chat-widget"]','iframe[src*="widgets.leadconnectorhq"]','iframe[src*="leadconnector"]','iframe[src*="msgsndr"]',"[data-chat-widget]","[data-widget-id]",'div[style*="z-index"][style*="position: fixed"][style*="bottom"]','div[id^="fc_"]','div[id^="hubspot"]',".widget-visible"].forEach(i=>{document.querySelectorAll(i).forEach(l=>{l.style.display="none"})})};n();const r=[setTimeout(n,500),setTimeout(n,1500),setTimeout(n,3e3),setTimeout(n,5e3)];return()=>{document.body.classList.remove("landing-page-public"),r.forEach(clearTimeout)}},[]),t?e.jsx(nHt,{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 K7n=[{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}],EJn={hero:"Hero Section",featured_listings:"Featured Listings",featured_areas:"Featured Areas",about:"About Me",testimonials:"Testimonials",cta_banner:"Call To Action",new_listings:"New Listings Carousel",open_houses:"Open Houses Carousel",my_listings:"My Listings Carousel",city_pages:"City Pages Grid",property_types:"Property Types Gallery",advantages:"Advantages / Why Choose Us",rate_my_agent:"RateMyAgent Reviews",lifestyle_gallery:"Lifestyle Gallery",market_pulse:"Market Pulse",concierge_services:"Concierge Services",credentials:"Credentials & Clientele",land_use_guide:"Land Use Guide",land_valuation_cta:"Land Valuation CTA",acreage_showcase:"Acreage Showcase",featured_video:"Featured Video",schedule_cta:"Schedule a Consultation"},TJn={hero:"Full-screen background image with headline, subtitle, and search bar",featured_listings:"Grid of highlighted properties from the MLS",featured_areas:"Spotlight regions or neighborhoods that link to property search",about:"Agent photo, bio, and credentials section",testimonials:"Client reviews carousel with quotes",cta_banner:"Call-to-action block to drive contact and search engagement",new_listings:"Horizontal carousel of newest listings, filterable by city",open_houses:"Horizontal carousel of open house listings, filterable by city",my_listings:"Showcase the agent's own active listings in a carousel",city_pages:"Grid of your city landing pages with photos and links",property_types:"Visual gallery of property categories (Ranch, Farm, Land, etc.)",advantages:"Feature cards highlighting your expertise and unique value",rate_my_agent:"Verified client reviews carousel powered by RateMyAgent",lifestyle_gallery:"Cinematic photo grid showcasing luxury living — pools, views, interiors",market_pulse:"Sleek market stats dashboard with avg price, days on market, inventory",concierge_services:"White-glove services showcase — staging, design, moving coordination",credentials:"Affiliation logos and specialty positioning (e.g. luxury and sports & entertainment divisions)",land_use_guide:"Interactive land use cards — Agriculture, Hunting, Equestrian, Recreational",land_valuation_cta:`"What's Your Land Worth?" — bold call-to-action for landowners`,acreage_showcase:"Large visual cards emphasizing lot size with aerial imagery",featured_video:"Embedded YouTube or Bunny video section for cinematic storytelling",schedule_cta:"Prominent booking section that sends visitors to your online scheduling calendar"},Bbt={basic:["hero","featured_listings","new_listings","open_houses","my_listings","city_pages","featured_areas","about","testimonials","rate_my_agent","featured_video","schedule_cta","cta_banner"],luxury:["hero","featured_listings","new_listings","open_houses","my_listings","city_pages","featured_areas","about","testimonials","rate_my_agent","cta_banner","lifestyle_gallery","market_pulse","concierge_services","credentials","featured_video","schedule_cta"],"land-ranch":["hero","featured_listings","new_listings","open_houses","my_listings","city_pages","featured_areas","about","testimonials","rate_my_agent","cta_banner","property_types","advantages","land_use_guide","land_valuation_cta","acreage_showcase","featured_video","schedule_cta"]};function MJn(s){return Bbt[s]||Bbt.basic}function Y7n(s){const t=s.theme_config||{};return{themeTier:s.theme_tier||"basic",brandColor:s.brand_color||"#0f172a",accentColor:s.accent_color||"#3b82f6",fontFamily:s.font_family||"Inter",heroImageUrl:s.hero_image_url||null,homepageModules:Array.isArray(s.homepage_modules)&&s.homepage_modules.length?s.homepage_modules.map(n=>typeof n=="string"?{type:n,enabled:!0}:{enabled:!0,...n}):K7n,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,divisionLogos:Array.isArray(t.divisionLogos)?t.divisionLogos:[],focusPages:Array.isArray(t.focusPages)?t.focusPages:[]}}const Z7n=new Set(["localhost","tile-portal.lovable.app","id-preview--b4ed24ae-0b44-4f4d-8676-c620f649ed8a.lovable.app","dashboard.relevelup.com","guestbook.relevelup.com","pages.relevelup.com","listings.relevelup.com"]);function X7n(s){const t=s.toLowerCase().replace(/:\d+$/,"");return!!(Z7n.has(t)||t.endsWith(".lovable.app")||t.endsWith(".lovableproject.com")||t.endsWith(".lovable.dev"))}function Q7n(){const s=new URLSearchParams(window.location.search).get("previewSlug");if(s)return s;const n=window.location.hostname.match(/^([^.]+)\.thelocalmove\.com$/i);return n?n[1]:null}function J7n(){const s=Q7n(),t=window.location.hostname,n=s?null:jkt(t),r=!s&&!X7n(t)&&t.includes(".")&&!wkt(t),a=s||n||(r?t:null),{data:i,isLoading:l,error:o}=pt({queryKey:["lead-site",a,r],queryFn:async()=>{var v;if(!a)return null;const d=V.from("lead_sites").select("*").eq("is_active",!0);let u;if(s)u=await d.eq("subdomain_slug",s).maybeSingle();else if(n)u=await d.ilike("custom_domain",n).maybeSingle();else if(r)u=await d.ilike("custom_domain",t).maybeSingle();else return null;const{data:h,error:m}=u;if(m)throw m;if(!h)return null;const{data:p}=await V.from("profiles").select("id, name, avatar_url, email, phone, title, bio, areas_served, years_experience, instagram_url, facebook_url, linkedin_url").eq("id",h.agent_id).single();let g=null;if(h.show_team_logo)if(h.team_logo_url)g=h.team_logo_url;else{const{data:_}=await V.from("team_members").select("team_id, teams(avatar_url, name)").eq("user_id",h.agent_id).limit(1).maybeSingle();_&&((v=_.teams)!=null&&v.avatar_url)&&(g=_.teams.avatar_url)}const x={id:h.id,agentId:h.agent_id,subdomainSlug:h.subdomain_slug,customDomain:h.custom_domain||null,mlsProviderId:h.mls_provider_id,siteTitle:h.site_title,siteTagline:h.site_tagline,leadRegistrationMode:h.lead_registration_mode||"disabled",registrationTriggerCount:h.registration_trigger_count??1,themeConfig:h.theme_config||{},themeTier:h.theme_tier||"basic",planTier:h.plan_tier||"paid",brandColor:h.brand_color||void 0,accentColor:h.accent_color||void 0,mlsServiceCities:Array.isArray(h.mls_service_cities)?h.mls_service_cities:[],isActive:h.is_active,brokerageLegalName:h.brokerage_legal_name||null,brokerageLicenseNumber:h.brokerage_license_number||null,agentLicenseNumber:h.agent_license_number||null,licenseState:h.license_state||null,mlsDisclaimerText:h.mls_disclaimer_text||null,mlsLogoUrl:h.mls_logo_url||null,equalHousingEnabled:h.equal_housing_enabled??!0,faviconUrl:h.favicon_url||null,ogImageUrl:h.og_image_url||null,showTeamLogo:h.show_team_logo??!1,teamLogoUrl:g,noMlsMode:h.no_mls_mode===!0,bookingUrl:h.booking_url||null,pageSubtitles:h.page_subtitles||{},agent:p?{id:p.id,full_name:p.name||"",avatar_url:p.avatar_url,email:p.email,phone:p.phone,title:p.title,bio:p.bio,areas_served:p.areas_served||null,years_experience:p.years_experience??null,instagram_url:p.instagram_url||null,facebook_url:p.facebook_url||null,linkedin_url:p.linkedin_url||null}:void 0,testimonials:Array.isArray(h.testimonials)?h.testimonials.filter(_=>_&&typeof _=="object"&&_.text).map(_=>({name:String(_.name||"Client"),text:String(_.text),rating:typeof _.rating=="number"?_.rating:5,location:_.location?String(_.location):void 0})):[],seoMetaTitle:h.seo_meta_title||null,seoMetaDescription:h.seo_meta_description||null},y=Y7n(h);return{siteConfig:x,themeConfig:y}},enabled:!!a,staleTime:5*60*1e3,gcTime:30*60*1e3,refetchOnWindowFocus:!1}),c=n||(r?t:null);return{siteConfig:(i==null?void 0:i.siteConfig)??null,themeConfig:(i==null?void 0:i.themeConfig)??null,isLoading:l,error:o,slug:s??(i==null?void 0:i.siteConfig.subdomainSlug)??null,customDomain:c}}async function e9n(s,t){try{await V.functions.invoke("lead-site-notify",{body:{lead:t,lead_site_id:s}})}catch(n){console.warn("Lead notification failed:",n)}}const rHt=k.createContext(null);function VTe(){const s=k.useContext(rHt);if(!s)throw new Error("useLeadSiteAuth must be used within LeadSiteAuthProvider");return s}function t9n({siteConfig:s,children:t}){const[n,r]=k.useState(null),[a,i]=k.useState(null),[l,o]=k.useState(!0);k.useEffect(()=>{const{data:{subscription:h}}=V.auth.onAuthStateChange(async(m,p)=>{const g=(p==null?void 0:p.user)??null;if(r(g),g){const{data:x}=await V.from("lead_site_consumer_profiles").select("id, name, phone").eq("user_id",g.id).eq("lead_site_id",s.id).maybeSingle();x&&i({...x,email:g.email||""})}else i(null);o(!1)});return V.auth.getSession().then(({data:{session:m}})=>{r((m==null?void 0:m.user)??null),m!=null&&m.user?V.from("lead_site_consumer_profiles").select("id, name, phone").eq("user_id",m.user.id).eq("lead_site_id",s.id).maybeSingle().then(({data:p})=>{p&&i({...p,email:m.user.email||""}),o(!1)}):o(!1)}),()=>h.unsubscribe()},[s.id]);const c=k.useCallback(async h=>{const m=h.email.toLowerCase().trim(),p=h.phone.replace(/\D/g,""),{data:g,error:x}=await V.auth.signUp({email:m,password:p,options:{data:{full_name:h.name,consumer_site_id:s.id},emailRedirectTo:window.location.origin}});if(x){if(x.message.includes("already registered")){await d(m,p);return}throw x}if(g.user){const{error:y}=await V.from("lead_site_consumer_profiles").insert({user_id:g.user.id,lead_site_id:s.id,name:h.name.trim(),phone:h.phone.trim()});y&&console.warn("Consumer profile insert error:",y);const{error:v}=await V.from("lead_site_leads").insert({lead_site_id:s.id,name:h.name.trim(),email:m,phone:h.phone.trim(),message:"Created account on website",source_page:window.location.pathname,lead_type:"website_registration",metadata:{registered:!0,has_account:!0}});v&&console.error("Lead insert error (CRM sync may not trigger):",v),e9n(s.id,{name:h.name.trim(),email:m,phone:h.phone.trim(),lead_type:"website_registration",message:"Created account on website",source_page:window.location.pathname})}},[s.id]),d=k.useCallback(async(h,m)=>{const p=m.replace(/\D/g,""),{error:g}=await V.auth.signInWithPassword({email:h.toLowerCase().trim(),password:p});if(g)throw g},[]),u=k.useCallback(async()=>{await V.auth.signOut(),r(null),i(null)},[]);return e.jsx(rHt.Provider,{value:{user:n,profile:a,isLoading:l,signUp:c,signIn:d,signOut:u},children:t})}const s9n=new Set(["7605cc2e-ce21-4f4f-8bb1-4c0f217b1109"]),n9n=new Set(["tomlois"]);function _Qe(s,t){var n;return s?(t==null?void 0:t.referralMode)===!0||((n=s.themeConfig)==null?void 0:n.referralMode)===!0||s.noMlsMode===!0||s9n.has(s.id||"")||n9n.has((s.subdomainSlug||"").toLowerCase())||!s.mlsProviderId:!1}function PJn(s){return`Contact ${s.split(" ")[0]||"Me"}`}const GV="#c9a96e",r9n="Schedule a Free Consultation",a9n={sm:"px-5 py-2.5 text-[11px]",md:"px-7 py-3.5 text-xs",lg:"px-9 py-4 text-xs"};function T3({bookingUrl:s,label:t=r9n,className:n="",variant:r="solid",color:a=GV,size:i="md",onDark:l=!0,source:o}){if(!s)return null;const c=`inline-flex items-center justify-center gap-2.5 font-semibold tracking-[0.18em] uppercase rounded-full transition-all duration-300 ${a9n[i]}`,d=r==="solid"?{backgroundColor:a,color:"#0d0b0a",boxShadow:`0 10px 30px -12px ${a}`}:{borderColor:a,color:a,borderWidth:1};return e.jsxs("a",{href:s,target:"_blank",rel:"noopener noreferrer","data-schedule-source":o,className:`${c} ${r==="solid"?"hover:brightness-110":`border hover:bg-[${a}]/10`} ${r==="outline"&&!l?"bg-white/0":""} ${n}`,style:d,children:[e.jsx(fb,{className:"h-4 w-4 flex-shrink-0"}),e.jsx("span",{children:t})]})}function IJn({bookingUrl:s,agentName:t,accentColor:n=GV,config:r={},luxury:a=!0}){const i=r.bookingUrl||s;if(!i)return null;const l=r.eyebrow||"No Cost. No Obligation.",o=r.sectionTitle||"Schedule a Free Consultation",c=r.subtitle||`Pick a time that works for you and ${t.split(" ")[0]} will personally call you for a free 30-minute real estate consultation.`,d=r.buttonLabel||"Book My Free Consultation",u=[{icon:sa,title:r.point1Title||"30 Minutes",text:r.point1Text||"A focused conversation about your goals, timeline, and options."},{icon:qK,title:r.point2Title||"A Personal Call",text:r.point2Text||`${t.split(" ")[0]} calls you at the time you choose — no phone tag.`},{icon:Gr,title:r.point3Title||"Real Answers",text:r.point3Text||"Pricing, strategy, and next steps for buying or selling — free of charge."}],h=a?"bg-[#12100e]":"bg-gray-950";return e.jsxs("section",{className:`relative py-24 ${h} overflow-hidden`,children:[e.jsx("div",{className:"absolute inset-0 opacity-[0.07] pointer-events-none",style:{background:`radial-gradient(circle at 50% 0%, ${n}, transparent 60%)`}}),e.jsx("div",{className:"relative max-w-5xl mx-auto px-6 text-center",children:e.jsxs(_r.div,{initial:{opacity:0,y:24},whileInView:{opacity:1,y:0},viewport:{once:!0},transition:{duration:.7},children:[e.jsxs("div",{className:"flex items-center justify-center gap-4 mb-5",children:[e.jsx("div",{className:"h-px w-12 bg-white/10"}),e.jsx("span",{className:"text-[11px] tracking-[0.4em] uppercase",style:{color:n},children:l}),e.jsx("div",{className:"h-px w-12 bg-white/10"})]}),e.jsx("h2",{className:"text-3xl md:text-5xl text-white tracking-tight",style:{fontFamily:"'Playfair Display', Georgia, serif"},children:o}),e.jsx("p",{className:"text-white/50 mt-5 text-lg max-w-2xl mx-auto leading-relaxed",style:{fontFamily:"'Playfair Display', Georgia, serif",fontStyle:"italic"},children:c}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4 mt-14 text-left",children:u.map((m,p)=>e.jsxs("div",{className:"border border-white/10 bg-white/[0.03] p-6",children:[e.jsx(m.icon,{className:"h-5 w-5 mb-4",style:{color:n}}),e.jsx("p",{className:"text-white text-sm tracking-[0.15em] uppercase mb-2",children:m.title}),e.jsx("p",{className:"text-white/45 text-sm leading-relaxed",children:m.text})]},p))}),e.jsxs("div",{className:"mt-12 flex flex-col items-center gap-4",children:[e.jsx(T3,{bookingUrl:i,label:d,size:"lg",color:n,source:"home_section"}),e.jsx("p",{className:"text-white/30 text-xs tracking-[0.2em] uppercase",children:"Opens in a new tab · Free 30-minute consultation"})]})]})})]})}function LJn({bookingUrl:s,accentColor:t=GV,headline:n="Prefer to talk it through?",subtext:r="Book a free 30-minute consultation at a time that works for you.",dark:a=!0,className:i="",source:l}){return s?e.jsxs("div",{className:`flex flex-col sm:flex-row sm:items-center sm:justify-between gap-5 p-6 md:p-8 border ${a?"border-white/10 bg-white/[0.03]":"border-gray-200 bg-gray-50 rounded-2xl"} ${i}`,children:[e.jsxs("div",{children:[e.jsx("p",{className:`text-lg ${a?"text-white":"text-gray-900"}`,style:{fontFamily:"'Playfair Display', Georgia, serif"},children:n}),e.jsx("p",{className:`text-sm mt-1 ${a?"text-white/45":"text-gray-600"}`,children:r})]}),e.jsx(T3,{bookingUrl:s,label:"Schedule Now",color:t,size:"sm",className:"flex-shrink-0",source:l})]}):null}function i9n({bookingUrl:s,accentColor:t=GV}){const[n,r]=k.useState(!1),[a,i]=k.useState(!1);if(k.useEffect(()=>{sessionStorage.getItem("schedule-cta-dismissed")==="1"&&i(!0);const o=()=>r(window.scrollY>260);return o(),window.addEventListener("scroll",o,{passive:!0}),()=>window.removeEventListener("scroll",o)},[]),!s||a)return null;const l=()=>{sessionStorage.setItem("schedule-cta-dismissed","1"),i(!0)};return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:`md:hidden fixed inset-x-0 bottom-0 z-[60] transition-transform duration-300 ${n?"translate-y-0":"translate-y-full"}`,style:{paddingBottom:"env(safe-area-inset-bottom)"},children:e.jsxs("div",{className:"bg-[#0d0b0a]/95 backdrop-blur-lg border-t border-white/10 px-4 py-3 flex items-center gap-3",children:[e.jsxs("a",{href:s,target:"_blank",rel:"noopener noreferrer",className:"flex-1 inline-flex items-center justify-center gap-2 rounded-full py-3 text-[11px] font-semibold tracking-[0.18em] uppercase",style:{backgroundColor:t,color:"#0d0b0a"},children:[e.jsx(fb,{className:"h-4 w-4"}),"Schedule Free Consultation"]}),e.jsx("button",{onClick:l,"aria-label":"Dismiss",className:"p-2 text-white/40 hover:text-white",children:e.jsx(mr,{className:"h-4 w-4"})})]})}),e.jsx("div",{className:`hidden md:flex fixed bottom-6 right-6 z-[60] items-center gap-2 transition-all duration-300 ${n?"opacity-100 translate-y-0":"opacity-0 translate-y-4 pointer-events-none"}`,children:e.jsx(T3,{bookingUrl:s,label:"Schedule a Free Consultation",size:"sm",color:t,source:"sticky"})})]})}function o9n({bookingUrl:s,agentName:t}){return k.useEffect(()=>{if(s){const n=setTimeout(()=>window.location.replace(s),400);return()=>clearTimeout(n)}},[s]),e.jsx("div",{className:"min-h-[70vh] flex items-center justify-center bg-[#0d0b0a] px-6 text-center",children:e.jsxs("div",{children:[e.jsx(fb,{className:"h-8 w-8 mx-auto mb-6",style:{color:GV}}),e.jsx("h1",{className:"text-3xl md:text-4xl text-white tracking-tight",style:{fontFamily:"'Playfair Display', Georgia, serif"},children:"Free 30-Minute Real Estate Consultation"}),e.jsx("p",{className:"text-white/45 mt-4",style:{fontFamily:"'Playfair Display', Georgia, serif",fontStyle:"italic"},children:s?`Taking you to ${t}'s booking calendar…`:"Online booking is not available yet — please use the contact page."}),s&&e.jsx("div",{className:"mt-8",children:e.jsx(T3,{bookingUrl:s,label:"Open Booking Calendar",size:"lg",source:"schedule_page"})})]})})}function wQe({open:s,mode:t,siteConfig:n,onComplete:r,onSkip:a,theme:i="default",accentColor:l}){var G;const{signUp:o,signIn:c}=VTe(),[d,u]=k.useState(!1),[h,m]=k.useState(""),[p,g]=k.useState(""),[x,y]=k.useState(""),[v,_]=k.useState(!1),[j,C]=k.useState(""),A=t==="required",M=i==="luxury",I=l||(M?"#c9a96e":"#2563eb"),P=((G=n.agent)==null?void 0:G.full_name)||"the agent",R={borderColor:`${I}66`,"--tw-ring-color":`${I}66`},O=async H=>{var se;if(H.preventDefault(),C(""),!p.trim()||!x.trim()){C("Email and phone number are required.");return}if(!d&&!h.trim()){C("Name is required.");return}if(x.replace(/\D/g,"").length<7){C("Please enter a valid phone number.");return}_(!0);try{d?await c(p,x):await o({name:h,email:p,phone:x}),r()}catch(ee){(se=ee==null?void 0:ee.message)!=null&&se.includes("Invalid login")?C("Invalid email or phone number. Please try again."):C((ee==null?void 0:ee.message)||"Something went wrong. Please try again.")}finally{_(!1)}},B=M?"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",U=M?R:void 0;return e.jsx(zs,{open:s,onOpenChange:A?void 0:H=>{H||a()},children:e.jsxs(Rs,{className:`sm:max-w-md ${M?"border-white/10 bg-[#f7f1e7] text-[#201915]":""}`,onPointerDownOutside:A?H=>H.preventDefault():void 0,onEscapeKeyDown:A?H=>H.preventDefault():void 0,children:[e.jsxs(Vs,{children:[e.jsx($s,{className:"text-xl",style:M?{fontFamily:"'Playfair Display', Georgia, serif"}:void 0,children:d?"Welcome Back":A?"Create a Free Account to Continue":"Save Your Search & Get Updates"}),e.jsx(Cr,{className:M?"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 ${P}.`})]}),e.jsxs("form",{onSubmit:O,className:"space-y-3 mt-2",children:[!d&&e.jsx("input",{type:"text",required:!0,placeholder:"Your name",value:h,onChange:H=>m(H.target.value),className:B,style:U}),e.jsx("input",{type:"email",required:!0,placeholder:"Email address",value:p,onChange:H=>g(H.target.value),className:B,style:U}),e.jsxs("div",{children:[e.jsx("input",{type:"tel",required:!0,placeholder:"Phone number",value:x,onChange:H=>y(H.target.value),className:B,style:U}),e.jsx("p",{className:`text-xs mt-1 ${M?"text-[#8a7869]":"text-gray-400"}`,children:d?"Your phone number is your password":"Your phone number will be used as your password"})]}),j&&e.jsx("p",{className:"text-red-600 text-sm",children:j}),e.jsx("button",{type:"submit",disabled:v,className:`w-full py-2.5 font-medium rounded-lg disabled:opacity-50 transition-colors ${M?"text-black hover:opacity-90 tracking-wider uppercase text-sm":"bg-blue-600 text-white hover:bg-blue-700"}`,style:M?{backgroundColor:I}:void 0,children:v?d?"Signing in...":"Creating account...":d?"Sign In":"Create Account"}),e.jsx("button",{type:"button",onClick:()=>{u(!d),C("")},className:"w-full text-center text-sm hover:opacity-80 transition-opacity",style:{color:I},children:d?"Don't have an account? Sign up":"Already have an account? Sign in"}),!A&&!d&&e.jsx("button",{type:"button",onClick:a,className:`w-full py-2 text-sm transition-colors ${M?"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 ${M?"text-[#8a7869]":"text-gray-400"}`,children:"By registering you agree to receive property updates. You can unsubscribe anytime."})]})})}function jQe({siteConfig:s,pagePath:t}){const n=s.agent;if(!n)return null;const r=s.customDomain?`https://${s.customDomain}`:`https://${s.subdomainSlug}.thelocalmove.com`,i=(n.areas_served||"").split(/,|;|\|/).map(j=>j.trim()).filter(Boolean),l=i[0]||"",[o,c]=l.split(/,\s*/),d=(n.bio||"").match(/\b(CRS|GRI|ABR|CNE|SRES|SRS|RENE|MRP|PSA|AHWD|C2EX|CIPS|CRB|e-?PRO)\b/gi)||[],u=[...new Set(d.map(j=>j.toUpperCase()))],h=s.testimonials||[],m=h.length?{"@type":"AggregateRating",ratingValue:(h.reduce((j,C)=>j+(C.rating||5),0)/h.length).toFixed(1),reviewCount:h.length,bestRating:5,worstRating:1}:void 0,p=[n.facebook_url,n.instagram_url,n.linkedin_url].filter(Boolean),g={"@context":"https://schema.org","@type":["RealEstateAgent","LocalBusiness"],"@id":`${r}/#agent`,name:n.full_name,url:r,image:n.avatar_url||s.ogImageUrl||void 0,logo:s.ogImageUrl||n.avatar_url||void 0,email:n.email,telephone:n.phone||void 0,jobTitle:n.title||"Real Estate Agent",description:n.bio||`${n.full_name} is a trusted local real estate professional${l?` serving ${l}`:""}.`,priceRange:"$$",...p.length&&{sameAs:p},...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(j=>{const[C,A]=j.split(/,\s*/);return{"@type":"City",name:C,...A&&{containedInPlace:{"@type":"State",name:A}}}})},...m&&{aggregateRating:m},...h.length&&{review:h.slice(0,10).map(j=>({"@type":"Review",author:{"@type":"Person",name:j.name},reviewBody:j.text,reviewRating:{"@type":"Rating",ratingValue:j.rating||5,bestRating:5,worstRating:1},...j.location&&{locationCreated:{"@type":"Place",name:j.location}}}))}},x={"@context":"https://schema.org","@type":"Person","@id":`${r}/#person`,name:n.full_name,jobTitle:n.title||"Real Estate Agent",description:n.bio||void 0,image:n.avatar_url||void 0,url:r,email:n.email,telephone:n.phone||void 0,...p.length&&{sameAs:p},...n.years_experience&&{knowsAbout:["Residential Real Estate","Home Buying","Home Selling",l?`${l} Real Estate`:"Local Real Estate"].filter(Boolean)},...u.length&&{hasCredential:u.map(j=>({"@type":"EducationalOccupationalCredential",credentialCategory:"designation",name:j}))},...s.brokerageLegalName&&{worksFor:{"@type":"Organization",name:s.brokerageLegalName}}},y={"@context":"https://schema.org","@type":"WebSite","@id":`${r}/#website`,name:s.siteTitle||`${n.full_name} Real Estate`,url:r,publisher:{"@id":`${r}/#agent`},potentialAction:{"@type":"SearchAction",target:{"@type":"EntryPoint",urlTemplate:`${r}/search?q={search_term_string}`},"query-input":"required name=search_term_string"}},v=[{name:"Search Homes",description:`Browse all current MLS listings${l?` in ${l}`:""}.`,path:"/search"},{name:"Featured Areas",description:"Explore featured neighborhoods, cities, and communities.",path:"/areas"},{name:"Sold Properties",description:"See recently sold homes and local market activity.",path:"/sold"},{name:"Home Valuation",description:"Get a free, no-obligation estimate of what your home is worth.",path:"/sell"},{name:"About",description:`Learn more about ${n.full_name}${s.brokerageLegalName?` and ${s.brokerageLegalName}`:""}.`,path:"/about"},{name:"Contact",description:`Get in touch with ${n.full_name} for buying, selling, or relocation help.`,path:"/contact"}],_={"@context":"https://schema.org","@type":"ItemList","@id":`${r}/#nav`,name:"Main Navigation",itemListElement:v.map((j,C)=>({"@type":"SiteNavigationElement",position:C+1,name:j.name,description:j.description,url:`${r}${j.path}`}))};return e.jsxs(Sc,{children:[e.jsx("script",{type:"application/ld+json",children:JSON.stringify(g)}),e.jsx("script",{type:"application/ld+json",children:JSON.stringify(x)}),e.jsx("script",{type:"application/ld+json",children:JSON.stringify(y)}),e.jsx("script",{type:"application/ld+json",children:JSON.stringify(_)})]})}function RJn({items:s,siteConfig:t}){const n=t.customDomain?`https://${t.customDomain}`:`https://${t.subdomainSlug}.thelocalmove.com`,r={"@context":"https://schema.org","@type":"BreadcrumbList",itemListElement:s.map((a,i)=>({"@type":"ListItem",position:i+1,name:a.name,item:`${n}${a.path}`}))};return e.jsx(Sc,{children:e.jsx("script",{type:"application/ld+json",children:JSON.stringify(r)})})}function DJn({listing:s,siteConfig:t}){var a;const n=t.customDomain?`https://${t.customDomain}`:`https://${t.subdomainSlug}.thelocalmove.com`,r={"@context":"https://schema.org","@type":"SingleFamilyResidence",name:`${s.address}, ${s.city}, ${s.state} ${s.zip}`,url:`${n}/listing/${s.mlsNumber}`,image:((a=s.photos)==null?void 0:a[0])||void 0,numberOfRooms:s.bedrooms,numberOfBathroomsTotal:s.bathrooms,floorSize:s.sqft?{"@type":"QuantitativeValue",value:s.sqft,unitCode:"FTK"}:void 0,address:{"@type":"PostalAddress",streetAddress:s.address,addressLocality:s.city,addressRegion:s.state,postalCode:s.zip},...s.latitude&&s.longitude&&{geo:{"@type":"GeoCoordinates",latitude:s.latitude,longitude:s.longitude}},offers:{"@type":"Offer",price:s.price,priceCurrency:"USD",availability:s.status==="Active"?"https://schema.org/InStock":"https://schema.org/SoldOut"},...s.yearBuilt&&{yearBuilt:s.yearBuilt}};return e.jsx(Sc,{children:e.jsx("script",{type:"application/ld+json",children:JSON.stringify(r)})})}function l9n({faqs:s}){if(!s.length)return null;const t={"@context":"https://schema.org","@type":"FAQPage",mainEntity:s.map(n=>({"@type":"Question",name:n.question,acceptedAnswer:{"@type":"Answer",text:n.answer}}))};return e.jsx(Sc,{children:e.jsx("script",{type:"application/ld+json",children:JSON.stringify(t)})})}function OJn({title:s,description:t,publishedAt:n,imageUrl:r,slug:a,siteConfig:i}){const l=i.customDomain?`https://${i.customDomain}`:`https://${i.subdomainSlug}.thelocalmove.com`,o=i.agent,c={"@context":"https://schema.org","@type":"Article",headline:s,description:t,url:`${l}/blog/${a}`,datePublished:n,...r&&{image:r},author:o?{"@type":"Person",name:o.full_name,url:l}:void 0,publisher:{"@type":"Organization",name:i.siteTitle||(o==null?void 0:o.full_name)||"Agent",url:l}};return e.jsx(Sc,{children:e.jsx("script",{type:"application/ld+json",children:JSON.stringify(c)})})}function FJn({videoId:s,title:t,description:n,thumbnailUrl:r,uploadDate:a,durationSeconds:i}){const l=i&&i>0?i:null,o=l?`PT${Math.floor(l/3600)?`${Math.floor(l/3600)}H`:""}${Math.floor(l%3600/60)}M${l%60}S`:void 0,c={"@context":"https://schema.org","@type":"VideoObject",name:t,description:n,thumbnailUrl:r||`https://i.ytimg.com/vi/${s}/maxresdefault.jpg`,...a&&{uploadDate:a},...o&&{duration:o},embedUrl:`https://www.youtube.com/embed/${s}`,contentUrl:`https://www.youtube.com/watch?v=${s}`};return e.jsx(Sc,{children:e.jsx("script",{type:"application/ld+json",children:JSON.stringify(c)})})}function NQe({siteConfig:s}){var p;const t=s.agent;if(!t)return null;const n=t.full_name,r=s.brokerageLegalName||"their brokerage",a=t.areas_served||"the local market",i=((p=a.split(/,|;|\|/)[0])==null?void 0:p.trim())||"the local area",l=t.years_experience,o=t.phone||"",c=t.email,d=s.agentLicenseNumber,u=(t.bio||"").match(/\b(CRS|GRI|ABR|CNE|SRES|SRS|RENE|MRP|PSA|AHWD|C2EX|CIPS|CRB|e-?PRO)\b/gi)||[],h=[...new Set(u.map(g=>g.toUpperCase()))],m=[{question:`Who is ${n}?`,answer:`${n} is a ${t.title||"REALTOR®"} with ${r}${l?`, with ${l}+ years of local real estate experience`:""} serving ${a}. ${t.bio?t.bio.slice(0,280):""}`.trim()},{question:`What areas does ${n} serve?`,answer:`${n} serves ${a} and surrounding communities. Whether you're buying, selling, relocating, or downsizing, ${n.split(" ")[0]} provides expert local guidance.`},{question:`How can I contact ${n}?`,answer:`You can reach ${n} by ${o?`phone at ${o}, `:""}email at ${c}, or by booking a consultation directly through this website.`},...h.length?[{question:`What real estate designations does ${n} hold?`,answer:`${n} holds the following professional designations: ${h.join(", ")}. These designations represent advanced training in specialized areas of real estate.`}]:[],...d?[{question:`Is ${n} a licensed real estate agent?`,answer:`Yes, ${n} is a fully licensed real estate professional (License #${d}) with ${r}.`}]:[],{question:`How do I search for homes for sale in ${i}?`,answer:`Use the property search on this site to view all current MLS listings in ${i}. You can filter by price, bedrooms, neighborhood, school district, and more. Save searches to receive instant email alerts when new homes match your criteria.`},{question:`What is the home buying process like in ${i}?`,answer:`${n} guides buyers through every step: getting pre-approved, searching MLS listings, touring homes, writing competitive offers, navigating inspections and appraisals, and closing on schedule. Contact ${n.split(" ")[0]} for a free buyer consultation.`},{question:`How do I find out what my home is worth in ${i}?`,answer:`Request a free, no-obligation home valuation from ${n}. ${n.split(" ")[0]} provides a comparative market analysis (CMA) using recent sold comps and current market conditions in ${i}.`}];return e.jsx(l9n,{faqs:m})}const $bt="ls_visitor_geo",c9n=1e3*60*60,i8e="lu_lc_attrib_v1",d9n=1e3*60*60*24*90;function u9n(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 h9n(s,t){switch(t){case"home":return"Home";case"search":return"Search";case"sell":return"Sell Your Home";case"blog":return"Blog";case"listing":return`Listing ${s.split("/listing/")[1]||""}`;case"city":return s.replace("/homes-for-sale-in-","").split("-").map(r=>r.charAt(0).toUpperCase()+r.slice(1)).join(" ");case"subdivision":return s.replace("/homes-in-","").split("-").map(r=>r.charAt(0).toUpperCase()+r.slice(1)).join(" ");case"dashboard":return"My Dashboard";default:return s}}async function m9n(){try{const s=localStorage.getItem($bt);if(s){const t=JSON.parse(s);if(Date.now()-t.ts{i.current||(i.current=!0,m9n().then(l=>{a.current=l}))},[]),k.useEffect(()=>{if(!(s!=null&&s.id))return;const l=n.pathname;if(l===r.current)return;r.current=l;const o=u9n(l),c=h9n(l,o),d=localStorage.getItem(`ls_visitor_fp_${s.id}`)||null,u=a.current;(async()=>{const m=new URLSearchParams(n.search),p=m.get("luc");if(p&&/^[0-9a-f-]{36}$/i.test(p)){try{localStorage.setItem(i8e,JSON.stringify({contact_id:p,ts:Date.now()}))}catch{}return p}const g=m.get("lc");if(g&&/^[0-9a-f-]{36}$/i.test(g)){const{data:x}=await V.from("listing_email_recipients").select("contact_id").eq("id",g).maybeSingle(),y=x==null?void 0:x.contact_id;if(y){try{localStorage.setItem(i8e,JSON.stringify({contact_id:y,ts:Date.now()}))}catch{}return y}}try{const x=localStorage.getItem(i8e);if(x){const y=JSON.parse(x);if(y!=null&&y.contact_id&&Date.now()-(y.ts||0){V.from("lead_site_page_views").insert({lead_site_id:s.id,page_type:o,page_path:l,page_title:c,visitor_fingerprint:d,auth_user_id:t||null,contact_id:m,visitor_city:(u==null?void 0:u.city)||null,visitor_region:(u==null?void 0:u.region)||null,visitor_country:(u==null?void 0:u.country)||null,visitor_lat:(u==null?void 0:u.lat)||null,visitor_lng:(u==null?void 0:u.lng)||null}).then(({error:p})=>{p&&console.error("[PageTracking] insert failed:",p.message)})})},[n.pathname,n.search,s==null?void 0:s.id,t])}const f9n=3e4;function SQe(s,t){const n=Tu(),r=k.useRef(null),a=k.useRef(null),i=k.useRef(0),l=n.pathname,o=p9n(l),c=g9n(l,o),d=o==="listing"&&l.split("/listing/")[1]||null;k.useEffect(()=>{if(!(s!=null&&s.id)||!t)return;o==="listing"&&(i.current+=1);const u=localStorage.getItem(`ls_visitor_fp_${s.id}`)||null,h=async()=>{const{data:m,error:p}=await V.from("lead_site_active_visitors").upsert({lead_site_id:s.id,auth_user_id:t,visitor_fingerprint:u,current_page_path:l,current_page_title:c,current_mls_number:d,last_seen_at:new Date().toISOString(),listing_views_count:i.current},{onConflict:"lead_site_id,coalesce(auth_user_id::text,visitor_fingerprint,'')"}).select("id, notified_agent").single();!p&&m&&(r.current=m.id,i.current>=2&&!m.notified_agent&&V.functions.invoke("lead-site-presence-notify",{body:{visitor_id:m.id,lead_site_id:s.id}}).catch(()=>{}))};return h(),a.current&&clearInterval(a.current),a.current=setInterval(h,f9n),()=>{a.current&&clearInterval(a.current)}},[s==null?void 0:s.id,t,l]),k.useEffect(()=>{if(!(s!=null&&s.id)||!t)return;const u=()=>{r.current&&V.from("lead_site_active_visitors").delete().eq("id",r.current).then(()=>{})};return window.addEventListener("beforeunload",u),()=>window.removeEventListener("beforeunload",u)},[s==null?void 0:s.id,t])}function p9n(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 g9n(s,t){switch(t){case"home":return"Home";case"search":return"Search";case"listing":return`Listing ${s.split("/listing/")[1]||""}`;case"city":return s.replace("/homes-for-sale-in-","").split("-").map(r=>r.charAt(0).toUpperCase()+r.slice(1)).join(" ");case"subdivision":return s.replace("/homes-in-","").split("-").map(r=>r.charAt(0).toUpperCase()+r.slice(1)).join(" ");default:return s}}const mi=Number.isFinite||function(s){return typeof s=="number"&&isFinite(s)},x9n=Number.isSafeInteger||function(s){return typeof s=="number"&&Math.abs(s)<=y9n},y9n=Number.MAX_SAFE_INTEGER||9007199254740991;let xo=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}({}),er=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.PLAYLIST_UNCHANGED_ERROR="playlistUnchangedError",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_APPEND_NO_PROGRESS="bufferAppendNoProgress",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.MEDIA_SOURCE_REQUIRES_RESET="mediaSourceRequiresReset",s.UNKNOWN="unknown",s}({}),Mt=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}({});function v9n(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}var o8e={exports:{}},Ubt;function b9n(){return Ubt||(Ubt=1,function(s,t){(function(n){var r=/^(?=((?:[a-zA-Z0-9+\-.]+:)?))\1(?=((?:\/\/[^\/?#]*)?))\2(?=((?:(?:[^?#\/]*\/)*[^;?#\/]*)?))\3((?:;[^?#]*)?)(\?[^#]*)?(#[^]*)?$/,a=/^(?=([^\/?#]*))\1([^]*)$/,i=/(?:\/|^)\.(?=\/)/g,l=/(?:\/|^)\.\.\/(?!\.\.\/)[^\/]*(?=\/)/g,o={buildAbsoluteURL:function(c,d,u){if(u=u||{},c=c.trim(),d=d.trim(),!d){if(!u.alwaysNormalize)return c;var h=o.parseURL(c);if(!h)throw new Error("Error trying to parse base URL.");return h.path=o.normalizePath(h.path),o.buildURLFromParts(h)}var m=o.parseURL(d);if(!m)throw new Error("Error trying to parse relative URL.");if(m.scheme)return u.alwaysNormalize?(m.path=o.normalizePath(m.path),o.buildURLFromParts(m)):d;var p=o.parseURL(c);if(!p)throw new Error("Error trying to parse base URL.");if(!p.netLoc&&p.path&&p.path[0]!=="/"){var g=a.exec(p.path);p.netLoc=g[1],p.path=g[2]}p.netLoc&&!p.path&&(p.path="/");var x={scheme:p.scheme,netLoc:m.netLoc,path:null,params:m.params,query:m.query,fragment:m.fragment};if(!m.netLoc&&(x.netLoc=p.netLoc,m.path[0]!=="/"))if(!m.path)x.path=p.path,m.params||(x.params=p.params,m.query||(x.query=p.query));else{var y=p.path,v=y.substring(0,y.lastIndexOf("/")+1)+m.path;x.path=o.normalizePath(v)}return x.path===null&&(x.path=u.alwaysNormalize?o.normalizePath(m.path):m.path),o.buildURLFromParts(x)},parseURL:function(c){var d=r.exec(c);return d?{scheme:d[1]||"",netLoc:d[2]||"",path:d[3]||"",params:d[4]||"",query:d[5]||"",fragment:d[6]||""}:null},normalizePath:function(c){for(c=c.split("").reverse().join("").replace(i,"");c.length!==(c=c.replace(l,"")).length;);return c.split("").reverse().join("")},buildURLFromParts:function(c){return c.scheme+c.netLoc+c.path+c.params+c.query+c.fragment}};s.exports=o})()}(o8e)),o8e.exports}var CQe=b9n();class AQe{constructor(){this.aborted=!1,this.loaded=0,this.retry=0,this.total=0,this.chunkCount=0,this.bwEstimate=0,this.loading={start:0,first:0,end:0},this.parsing={start:0,end:0},this.buffering={start:0,first:0,end:0}}}var Mc={MANIFEST:"manifest",LEVEL:"level",AUDIO_TRACK:"audioTrack",SUBTITLE_TRACK:"subtitleTrack",MEDIA_FRAGMENT:"media-fragment",KEY:"key",STEERING_MANIFEST:"steering-manifest",SERVER_CERTIFICATE:"server-certificate",INTERSTITIAL_ASSET_LIST:"interstitial-asset-list"},Ji={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"},Xh={AUDIO:"audio",VIDEO:"video",AUDIOVIDEO:"audiovideo"};class aHt{constructor(t){this._byteRange=null,this._url=null,this._stats=null,this._streams=null,this.base=void 0,this.relurl=void 0,typeof t=="string"&&(t={url:t}),this.base=t,w9n(this,"stats")}setByteRange(t,n){const r=t.split("@",2);let a;r.length===1?a=(n==null?void 0:n.byteRangeEndOffset)||0:a=parseInt(r[1]),this._byteRange=[a,parseInt(r[0])+a]}get baseurl(){return this.base.url}get byteRange(){return this._byteRange===null?[]:this._byteRange}get byteRangeStartOffset(){return this.byteRange[0]}get byteRangeEndOffset(){return this.byteRange[1]}get elementaryStreams(){return this._streams===null&&(this._streams={[Xh.AUDIO]:null,[Xh.VIDEO]:null,[Xh.AUDIOVIDEO]:null}),this._streams}set elementaryStreams(t){this._streams=t}get hasStats(){return this._stats!==null}get hasStreams(){return this._streams!==null}get stats(){return this._stats===null&&(this._stats=new AQe),this._stats}set stats(t){this._stats=t}get url(){return!this._url&&this.relurl&&(this._url=CQe.buildAbsoluteURL(this.baseurl,this.relurl,{alwaysNormalize:!0})),this._url||""}set url(t){this._url=t}clearElementaryStreamInfo(){const{elementaryStreams:t}=this;t[Xh.AUDIO]=null,t[Xh.VIDEO]=null,t[Xh.AUDIOVIDEO]=null,this.url=null}}function Lp(s){return s.sn!=="initSegment"}function rK(s,t){return s.sn===(t==null?void 0:t.sn)&&s.level===t.level}function rqe(s,t){return s.sn===(t==null?void 0:t.sn)&&s.level===t.level&&s.cc===t.cc}class tie extends aHt{constructor(t,n){super(n),this._decryptdata=null,this._programDateTime=null,this._ref=null,this._bitrate=void 0,this.rawProgramDateTime=null,this.tagList=[],this.duration=0,this.sn=0,this.levelkeys=void 0,this.type=void 0,this.loader=null,this.keyLoader=null,this.level=-1,this.cc=0,this.startPTS=void 0,this.endPTS=void 0,this.startDTS=void 0,this.endDTS=void 0,this.start=0,this.playlistOffset=0,this.deltaPTS=void 0,this.maxStartPTS=void 0,this.minEndPTS=void 0,this.data=void 0,this.bitrateTest=!1,this.title=null,this.initSegment=null,this.endList=void 0,this.gap=void 0,this.urlId=0,this.type=t}get byteLength(){if(this.hasStats){const t=this.stats.total;if(t)return t}if(this.byteRange.length){const t=this.byteRange[0],n=this.byteRange[1];if(mi(t)&&mi(n))return n-t}return null}get bitrate(){return this.byteLength?this.byteLength*8/this.duration:this._bitrate?this._bitrate:null}set bitrate(t){this._bitrate=t}get decryptdata(){var t;const{levelkeys:n}=this;if(!n||n.NONE)return null;if(n.identity)this._decryptdata||(this._decryptdata=n.identity.getDecryptData(this.sn));else if(!((t=this._decryptdata)!=null&&t.keyId)){const r=Object.keys(n);if(r.length===1){const a=this._decryptdata=n[r[0]]||null;a&&(this._decryptdata=a.getDecryptData(this.sn,n))}}return this._decryptdata}get end(){return this.start+this.duration}get endProgramDateTime(){if(this.programDateTime===null)return null;const t=mi(this.duration)?this.duration:0;return this.programDateTime+t*1e3}get encrypted(){var t;if((t=this._decryptdata)!=null&&t.encrypted)return!0;if(this.levelkeys){var n;const r=Object.keys(this.levelkeys),a=r.length;if(a>1||a===1&&(n=this.levelkeys[r[0]])!=null&&n.encrypted)return!0}return!1}get programDateTime(){return this._programDateTime===null&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime}set programDateTime(t){if(!mi(t)){this._programDateTime=this.rawProgramDateTime=null;return}this._programDateTime=t}get ref(){return Lp(this)?(this._ref||(this._ref={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime}),this._ref):null}addStart(t){this.setStart(this.start+t)}setStart(t){this.start=t,this._ref&&(this._ref.start=t)}setDuration(t){this.duration=t,this._ref&&(this._ref.duration=t)}setKeyFormat(t){const n=this.levelkeys;if(n){var r;const a=n[t];a&&!((r=this._decryptdata)!=null&&r.keyId)&&(this._decryptdata=a.getDecryptData(this.sn,n))}}abortRequests(){var t,n;(t=this.loader)==null||t.abort(),(n=this.keyLoader)==null||n.abort()}setElementaryStreamInfo(t,n,r,a,i,l=!1){const{elementaryStreams:o}=this,c=o[t];if(!c){o[t]={startPTS:n,endPTS:r,startDTS:a,endDTS:i,partial:l};return}c.startPTS=Math.min(c.startPTS,n),c.endPTS=Math.max(c.endPTS,r),c.startDTS=Math.min(c.startDTS,a),c.endDTS=Math.max(c.endDTS,i)}}class _9n extends aHt{constructor(t,n,r,a,i){super(r),this.fragOffset=0,this.duration=0,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.gap=!1,this.duration=t.decimalFloatingPoint("DURATION"),this.gap=t.bool("GAP"),this.independent=t.bool("INDEPENDENT"),this.relurl=t.enumeratedString("URI"),this.fragment=n,this.index=a;const l=t.enumeratedString("BYTERANGE");l&&this.setByteRange(l,i),i&&(this.fragOffset=i.fragOffset+i.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){const{elementaryStreams:t}=this;return!!(t.audio||t.video||t.audiovideo||this.fragment.type===Ji.SUBTITLE&&this.stats.loaded)}}function iHt(s,t){const n=Object.getPrototypeOf(s);if(n){const r=Object.getOwnPropertyDescriptor(n,t);return r||iHt(n,t)}}function w9n(s,t){const n=iHt(s,t);n&&(n.enumerable=!0,Object.defineProperty(s,t,n))}function j9n(s,t,n){return(t=S9n(t))in s?Object.defineProperty(s,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):s[t]=n,s}function wh(){return wh=Object.assign?Object.assign.bind():function(s){for(var t=1;t499)}function pQ(s){return s===0&&navigator.onLine===!1}function cHt(s,t){return t>0&&s.loadError>0&&s.loadErrorTime!==0&&self.performance.now()-s.loadErrorTime>t}class x9{constructor(t,n=0,r=0){this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=t,this.alpha_=t?Math.exp(Math.log(.5)/t):0,this.estimate_=n,this.totalWeight_=r}sample(t,n){const r=Math.pow(this.alpha_,t);this.estimate_=n*(1-r)+r*this.estimate_,this.totalWeight_+=t}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){const t=1-Math.pow(this.alpha_,this.totalWeight_);if(t)return this.estimate_/t}return this.estimate_}}class A9n{constructor(t,n,r,a=100){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=r,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new x9(t),this.fast_=new x9(n),this.defaultTTFB_=a,this.ttfb_=new x9(t)}update(t,n){const{slow_:r,fast_:a,ttfb_:i}=this;r.halfLife!==t&&(this.slow_=new x9(t,r.getEstimate(),r.getTotalWeight())),a.halfLife!==n&&(this.fast_=new x9(n,a.getEstimate(),a.getTotalWeight())),i.halfLife!==t&&(this.ttfb_=new x9(t,i.getEstimate(),i.getTotalWeight()))}sample(t,n){if(n<=0)return;const r=Math.min(this.minDelayMs_,n/1e5),a=8*n,i=Math.max(t,r)/1e3,l=a/i;this.fast_.sample(i,l),this.slow_.sample(i,l)}sampleTTFB(t){const n=t/1e3,r=Math.sqrt(2)*Math.exp(-Math.pow(n,2)/2);this.ttfb_.sample(r,Math.max(t,5))}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}getEstimateTTFB(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}get defaultEstimate(){return this.defaultEstimate_}destroy(){}}class wj{constructor(t,n){this.trace=void 0,this.debug=void 0,this.log=void 0,this.warn=void 0,this.info=void 0,this.error=void 0;const r=`[${t}]:`;this.trace=jE,this.debug=n.debug.bind(null,r),this.log=n.log.bind(null,r),this.warn=n.warn.bind(null,r),this.info=n.info.bind(null,r),this.error=n.error.bind(null,r)}}const jE=function(){},E9n={trace:jE,debug:jE,log:jE,warn:jE,info:jE,error:jE};function aqe(){return wh({},E9n)}function T9n(s,t){const n=self.console[s];return n?n.bind(self.console,`${t?"["+t+"] ":""}[${s}] >`):jE}function Gbt(s,t,n){return t[s]?t[s].bind(t):T9n(s,n)}const iqe=aqe();function M9n(s,t,n){const r=aqe();if(typeof console=="object"&&s===!0||typeof s=="object"){const a=["debug","log","info","warn","error"];a.forEach(i=>{r[i]=Gbt(i,s,n)});try{r.log(`Debug logs enabled for "${t}" in hls.js version 1.7.1`)}catch{return aqe()}a.forEach(i=>{iqe[i]=Gbt(i,s)})}else wh(iqe,r);return r}const ku=iqe;function zM(s=!0){return typeof self>"u"?void 0:(s||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function P9n(s){return typeof self<"u"&&s===self.ManagedMediaSource}function dHt(s,t){const n=Object.keys(s),r=Object.keys(t),a=n.length,i=r.length;return!a||!i||a===i&&!n.some(l=>r.indexOf(l)===-1)}function I9n(s){return btoa(String.fromCharCode(...s))}function GTe(s){return s instanceof ArrayBuffer||typeof SharedArrayBuffer<"u"&&s instanceof SharedArrayBuffer}const L9n="utf-16",l8e="utf-16be",Wbt="utf-16le",fke="utf-8";function R9n(s,t={}){let n;GTe(s)?n=new DataView(s):n=new DataView(s.buffer,s.byteOffset,s.byteLength);let r=0,{encoding:a}=t;if(!a){const d=n.getUint8(0),u=n.getUint8(1);d==239&&u==187&&n.getUint8(2)==191?(a=fke,r=3):d==254&&u==255?(a=l8e,r=2):d==255&&u==254?(a=Wbt,r=2):a=fke}if(typeof TextDecoder<"u")return new TextDecoder(a).decode(n);const{byteLength:i}=n,l=a!==l8e;let o="",c;for(;r=194&&c<=223)if(r+1=128&&d<=191?(c=(c&31)<<6|d&63,r+=2):r++}else r++;else if(c>=224&&c<=239)if(r+2<=i-1){const d=n.getUint8(r+1),u=n.getUint8(r+2);d>=128&&d<=191&&u>=128&&u<=191?(c=(c&15)<<12|(d&63)<<6|u&63,r+=3):r++}else r++;else if(c>=240&&c<=244)if(r+3<=i-1){const d=n.getUint8(r+1),u=n.getUint8(r+2),h=n.getUint8(r+3);d>=128&&d<=191&&u>=128&&u<=191&&h>=128&&h<=191?(c=(c&7)<<18|(d&63)<<12|(u&63)<<6|h&63,r+=4):r++}else r++;else r++;break;case l8e:case L9n:case Wbt:c=n.getUint16(r,l),r+=2;break}o+=String.fromCodePoint(c)}return o}function D9n(s){const t=typeof s=="string"?new URL(s):s;return t.origin+t.pathname.substring(0,t.pathname.lastIndexOf("/")+1)}function uHt(s,t){if(s<0)return-uHt(-s,t);const n=Math.pow(10,t);if(Math.abs(s*n%1-.5){const a=(n+Math.random()*16)%16|0;return n=Math.floor(n/16),(r=="x"?a:a&3|8).toString(16)})}}}function TQe(s,t){return t+10<=s.length&&s[t]===73&&s[t+1]===68&&s[t+2]===51&&s[t+3]<255&&s[t+4]<255&&s[t+6]<128&&s[t+7]<128&&s[t+8]<128&&s[t+9]<128}function WTe(s,t){let n=0;return n=(s[t]&127)<<21,n|=(s[t+1]&127)<<14,n|=(s[t+2]&127)<<7,n|=s[t+3]&127,n}function F9n(s,t){return TQe(s,t)&&WTe(s,t+6)+10<=s.length-t}function mHt(s,t){return t+10<=s.length&&s[t]===51&&s[t+1]===68&&s[t+2]===73&&s[t+3]<255&&s[t+4]<255&&s[t+6]<128&&s[t+7]<128&&s[t+8]<128&&s[t+9]<128}function gQ(s,t){const n=t;let r=0;for(;TQe(s,t);){r+=10;const a=WTe(s,t+6);r+=a,mHt(s,t+10)&&(r+=10),t+=r}if(r>0)return s.subarray(n,n+r)}function z9n(s){return GTe(s)?s:s.byteOffset==0&&s.byteLength==s.buffer.byteLength?s.buffer:new Uint8Array(s).buffer}function c8e(s,t=0,n=1/0){return B9n(s,t,n,Uint8Array)}function B9n(s,t,n,r){const a=$9n(s);let i=1;"BYTES_PER_ELEMENT"in r&&(i=r.BYTES_PER_ELEMENT);const l=U9n(s)?s.byteOffset:0,o=(l+s.byteLength)/i,c=(l+t)/i,d=Math.floor(Math.max(0,Math.min(c,o)));return new r(a,d,Math.floor(Math.min(d+Math.max(n,0),o))-d)}function $9n(s){return GTe(s)?s:s.buffer}function U9n(s){return s&>e(s.buffer)&&s.byteLength!==void 0&&s.byteOffset!==void 0}function ij(s,t=!1){const n=t?s.indexOf(0):s.length,r=R9n(new DataView(s.buffer,s.byteOffset,n),{encoding:fke});return t?r:r.replace(/\0/g,"")}function q9n(s){const t={key:s.type,description:"",data:"",mimeType:null,pictureType:null},n=3;if(s.size<2)return;if(s.data[0]!==n){console.log("Ignore frame with unrecognized character encoding");return}const r=s.data.subarray(1).indexOf(0);if(r===-1)return;const a=ij(c8e(s.data,1,r)),i=s.data[2+r],l=s.data.subarray(3+r).indexOf(0);if(l===-1)return;const o=ij(c8e(s.data,3+r,l));let c;return a==="-->"?c=ij(c8e(s.data,4+r+l)):c=z9n(s.data.subarray(4+r+l)),t.mimeType=a,t.pictureType=i,t.description=o,t.data=c,t}function V9n(s){if(s.size<2)return;const t=ij(s.data,!0),n=new Uint8Array(s.data.subarray(t.length+1));return{key:s.type,info:t,data:n.buffer}}function H9n(s){if(s.size<2)return;if(s.type==="TXXX"){let n=1;const{data:r}=s,a=ij(r.subarray(n),!0);n+=a.length+1;const i=ij(r.subarray(n));return{key:s.type,info:a,data:i}}const t=ij(s.data.subarray(1));return{key:s.type,info:"",data:t}}function G9n(s){if(s.type==="WXXX"){if(s.size<2)return;let n=1;const r=ij(s.data.subarray(n),!0);n+=r.length+1;const a=ij(s.data.subarray(n));return{key:s.type,info:r,data:a}}const t=ij(s.data);return{key:s.type,info:"",data:t}}function W9n(s){return s.type==="PRIV"?V9n(s):s.type[0]==="W"?G9n(s):s.type==="APIC"?q9n(s):H9n(s)}function K9n(s){const t=String.fromCharCode(s[0],s[1],s[2],s[3]),n=WTe(s,4),r=10;return{type:t,size:n,data:s.subarray(r,r+n)}}const sie=10,Y9n=10;function fHt(s){let t=0;const n=[];for(;TQe(s,t);){const r=WTe(s,t+6);s[t+5]>>6&1&&(t+=sie),t+=sie;const a=t+r;for(;t+Y9nt.charCodeAt(0))}function pk(s){return String.fromCharCode.apply(null,s)}const MS=Math.pow(2,32)-1,wl={avc1:1635148593,avcC:1635148611,hvc1:1752589105,hvcC:1752589123,btrt:1651798644,dinf:1684631142,dref:1685218662,esds:1702061171,free:1718773093,ftyp:1718909296,hdlr:1751411826,mdat:1835295092,mdhd:1835296868,mdia:1835297121,mfhd:1835427940,minf:1835626086,moof:1836019558,moov:1836019574,mp4a:1836069985,".mp3":778924083,dac3:1684103987,"ac-3":1633889587,mvex:1836475768,mvhd:1836476516,pasp:1885434736,sdtp:1935963248,stbl:1937007212,stco:1937007471,stsc:1937011555,stsd:1937011556,stsz:1937011578,stts:1937011827,tfdt:1952867444,tfhd:1952868452,traf:1953653094,trak:1953653099,trun:1953658222,trex:1953654136,tkhd:1953196132,vmhd:1986881636,smhd:1936549988},xHt={video:1,audio:2,id3:3,text:4};function yHt(s,t){const n=s[t]<<8|s[t+1];return n<0?65536+n:n}function Wi(s,t){const n=s[t]<<24|s[t+1]<<16|s[t+2]<<8|s[t+3];return n<0?4294967296+n:n}function Kbt(s,t){let n=Wi(s,t);return n*=Math.pow(2,32),n+=Wi(s,t+4),n}function nie(s,t){let n="";for(let r=t;r>24,s[t+1]=n>>16&255,s[t+2]=n>>8&255,s[t+3]=n&255}function Ybt(s,t,n){const r=t.byteOffset-s.byteOffset-8,a=8+n,i=t.byteLength+8-a;i<8||(Hg(s,r,a),Hg(s,r+a,i),Hg(s,r+a+4,wl.free))}function lqe(s,t){return[s.byteOffset-t-8,s.byteOffset-t+s.byteLength]}function vHt(s,t){t.sort((o,c)=>o[0]-c[0]);const n=t.reduce((o,[c,d])=>o+d-c,0),r=new Uint8Array(s.byteLength-n);let a=0,i=0;for(let o=0;ot.reduce((c,[d,u])=>u<=o?c+u-d:c,0)}}function X9n(s){const t=Tl(s,["moov"]);if(t.length!==1||Tl(s,["moof"]).length)return null;const n=s.byteOffset,r=[],a=[];let i=!1;const l=Tl(t[0],["trak"]);for(let p=0;p0;if(d.length){({result:m,dropped:p,droppedBefore:g}=vHt(s,d)),Hg(m,l.byteOffset-o-8,l.byteLength+8-p);for(let x=0;x8&&Wi(s,r+4)===wl[t])return!0;r=a>1?r+a:n}return!1}function Tl(s,t){const n=[];return t.length&&bHt(s,t,0,0,s.byteLength,n),n}function bHt(s,t,n,r,a,i){const l=t[n];if((l==null?void 0:l.length)!==4)return;const o=l.charCodeAt(0),c=l.charCodeAt(1),d=l.charCodeAt(2),u=l.charCodeAt(3),h=t.length-1;for(let m=r;m1?m+g:a;if(p&&s[m+4]===o&&s[m+5]===c&&s[m+6]===d&&s[m+7]===u){const y=Math.min(x,a);n===h?i.push(s.subarray(m+8,y)):bHt(s,t,n+1,m+8,y,i)}m=x}}function ezn(s){const t=[],n=s[0];let r=8;const a=Wi(s,r);r+=4;let i=0,l=0;n===0?(i=Wi(s,r),l=Wi(s,r+4),r+=8):(i=Kbt(s,r),l=Kbt(s,r+8),r+=16),r+=2;let o=s.length+l;const c=yHt(s,r);r+=2;for(let d=0;d>>31===1)return ku.warn("SIDX has hierarchical references (not supported)"),null;const g=Wi(s,u);u+=4,t.push({referenceSize:m,subsegmentDuration:g,info:{duration:g/a,start:o,end:o+m-1}}),o+=m,u+=4,r=u}return{earliestPresentationTime:i,timescale:a,version:n,referencesCount:c,references:t}}function _Ht(s){const t=[],n=Tl(s,["moov","trak"]);for(let a=0;a{const i=Wi(a,4),l=t[i];l&&(l.default={duration:Wi(a,12),sampleSize:Wi(a,16),flags:Wi(a,20)})}),t}function tzn(s){const t=s.subarray(8),n=t.subarray(86),r=pk(t.subarray(4,8));let a=r,i;const l=r==="enca"||r==="encv";if(l){const d=Tl(t,[r])[0].subarray(r==="enca"?28:78);Tl(d,["sinf"]).forEach(h=>{const m=Tl(h,["schm"])[0];if(m){const p=pk(m.subarray(4,8));if(p==="cbcs"||p==="cenc"){const g=Tl(h,["frma"])[0];g&&(a=pk(g))}}})}const o=a;switch(a){case"avc1":case"avc2":case"avc3":case"avc4":{const c=Tl(n,["avcC"])[0];c&&c.length>3&&(a+="."+aie(c[1])+aie(c[2])+aie(c[3]),i=rie(o==="avc1"?"dva1":"dvav",n));break}case"mp4a":{const c=Tl(t,[r])[0],d=Tl(c.subarray(28),["esds"])[0];if(d&&d.length>7){let u=4;if(d[u++]!==3)break;u=d8e(d,u),u+=2;const h=d[u++];if(h&128&&(u+=2),h&64&&(u+=d[u++]),d[u++]!==4)break;u=d8e(d,u);const m=d[u++];if(m===64)a+="."+aie(m);else break;if(u+=12,d[u++]!==5)break;u=d8e(d,u);const p=d[u++];let g=(p&248)>>3;g===31&&(g+=1+((p&7)<<3)+((d[u]&224)>>5)),a+="."+g}break}case"hvc1":case"hev1":{const c=Tl(n,["hvcC"])[0];if(c&&c.length>12){const d=c[1],u=["","A","B","C"][d>>6],h=d&31,m=Wi(c,2),p=(d&32)>>5?"H":"L",g=c[12],x=c.subarray(6,12);a+="."+u+h,a+="."+szn(m).toString(16).toUpperCase(),a+="."+p+g;let y="";for(let v=x.length;v--;){const _=x[v];(_||y)&&(y="."+_.toString(16).toUpperCase()+y)}a+=y}i=rie(o=="hev1"?"dvhe":"dvh1",n);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":{a=rie(a,n)||a;break}case"vp09":{const c=Tl(n,["vpcC"])[0];if(c&&c.length>6){const d=c[4],u=c[5],h=c[6]>>4&15;a+="."+PS(d)+"."+PS(u)+"."+PS(h)}break}case"av01":{const c=Tl(n,["av1C"])[0];if(c&&c.length>2){const d=c[1]>>>5,u=c[1]&31,h=c[2]>>>7?"H":"M",m=(c[2]&64)>>6,p=(c[2]&32)>>5,g=d===2&&m?p?12:10:m?10:8,x=(c[2]&16)>>4,y=(c[2]&8)>>3,v=(c[2]&4)>>2,_=c[2]&3;a+="."+d+"."+PS(u)+h+"."+PS(g)+"."+x+"."+y+v+_+"."+PS(1)+"."+PS(1)+"."+PS(1)+"."+0,i=rie("dav1",n)}break}}return{codec:a,encrypted:l,supplemental:i}}function rie(s,t){const n=Tl(t,["dvvC"]),r=n.length?n[0]:Tl(t,["dvcC"])[0];if(r){const a=r[2]>>1&127,i=r[2]<<5&32|r[3]>>3&31;return s+"."+PS(a)+"."+PS(i)}}function szn(s){let t=0;for(let n=0;n<32;n++)t|=(s>>n&1)<<31-n;return t>>>0}function d8e(s,t){const n=t+5;for(;s[t++]&128&&t{const i=r.subarray(8,24);i.some(l=>l!==0)||(ku.log(`[eme] Patching keyId in 'enc${a?"a":"v"}>sinf>>tenc' box: ${Ax(i)} -> ${Ax(n)}`),r.set(n,8))})}function rzn(s){const t=[];return wHt(s,n=>t.push(n.subarray(8,24))),t}function wHt(s,t){Tl(s,["moov","trak"]).forEach(r=>{const a=Tl(r,["mdia","minf","stbl","stsd"])[0];if(!a)return;const i=a.subarray(8);let l=Tl(i,["enca"]);const o=l.length>0;o||(l=Tl(i,["encv"])),l.forEach(c=>{const d=o?c.subarray(28):c.subarray(78);Tl(d,["sinf"]).forEach(h=>{const m=jHt(h);m&&t(m,o)})})})}function jHt(s){const t=Tl(s,["schm"])[0];if(t){const n=pk(t.subarray(4,8));if(n==="cbcs"||n==="cenc"){const r=Tl(s,["schi","tenc"])[0];if(r)return r}}}let Zbt;function azn(s){return typeof TextDecoder>"u"?ij(s):(Zbt||(Zbt=new TextDecoder("utf-8"))).decode(s).replace(/\0/g,"")}function izn(s){const t=s.byteLength,n=[];for(let r=0;r1?r+i:t;if(a&&s[r+4]===109&&s[r+5]===111&&s[r+6]===111&&s[r+7]===102){const o=Math.min(l,t);for(let c=r+8;c1?c+u:o;if(d&&s[c+4]===116&&s[c+5]===114&&s[c+6]===97&&s[c+7]===102){const m=Math.min(h,o);let p,g;const x=[];for(let y=c+8;y1?y+_:m;if(v&&s[y+4]===116){const C=Math.min(j,m);s[y+5]===102&&s[y+6]===104&&s[y+7]===100?g||(g=s.subarray(y+8,C)):s[y+5]===102&&s[y+6]===100&&s[y+7]===116?p||(p=s.subarray(y+8,C)):s[y+5]===114&&s[y+6]===117&&s[y+7]===110&&x.push(s.subarray(y+8,C))}y=j}n.push({moofOffset:s.byteOffset+r,tfdt:p,tfhd:g,truns:x})}c=h}}r=l}return n}function ozn(s,t,n,r,a=!0){return NHt(s,t,r,a)}function lzn(s,t,n,r,a=!1){const i=[],l=t.samples,o=NHt(l,n,r,a,{isHEVCFlavor:jte(t.codec),samples:i,timeOffset:s,timescale:t.timescale,trackId:t.id});return{samples:i,sampleData:{includeSampleDetails:a,tracks:o}}}function NHt(s,t,n,r,a){const i={};let l=!1;const o=izn(s),c=s.byteLength;for(let h=0;h0){let Ft=Ie;do{const Ut=s[Ft]===0?s[Ft+1]<<16|s[Ft+2]<<8|s[Ft+3]:Wi(s,Ft);Ft+=4;const Is=s[Ft],xs=tt?Is>>1&63:Is&31;(tt?xs===39||xs===40:xs===6)&&xQ(s.subarray(Ft,Ft+Ut),ut,Ge,a.samples),Ft+=Ut}while(Ftc)break;Oe=wt+1,at+=8}}if(C&&(a.timeOffset=Ge),ke!==-1&&Fe<=c&&_.keyFrameIndex===void 0&&(_.keyFrameIndex=ke,_.keyFrameStart=Ye+ke*I),Oe){(!mi(_.ptsMin)||Ye<_.ptsMin)&&(_.ptsMin=Ye);const et=Ye+Oe*I;(!mi(_.ptsMax)||et>_.ptsMax)&&(_.ptsMax=et)}const nt=I*me;H=Ye+nt,Y+=nt;continue}let Ue,Be;r&&(Ue=[],Be={sampleOffset:Ie,samples:Ue,defaultSampleDurationOffset:P},Ie<=c&&_.trun.push(Be));let je;for(let Ye=0;Ye_.ptsMax)&&(_.ptsMax=Oe+se),Ue&&(Ue[Ye]={cts:Fe,duration:se,flags:Re,size:je})}H+=se,Y+=se}!Y&&I&&(Y+=I*me)}_.duration+=Y,_.duration&&(l=!0)}if(!l){let h=1/0,m=0;const p=Tl(s,["sidx"]);for(let g=0;gv+_.info.duration||0,0);m=Math.max(m,y+x.earliestPresentationTime/x.timescale)}}m&&mi(m)&&Object.keys(i).forEach(g=>{i[g].duration||(i[g].duration=m*i[g].timescale-i[g].start)})}return i}function czn(s){const t={valid:null,remainder:null},n=Tl(s,["moof"]);if(n.length<2)return t.remainder=s,t;const r=n[n.length-1];return t.valid=s.slice(0,r.byteOffset-8),t.remainder=s.slice(r.byteOffset-8),t}function z2(s,t){const n=new Uint8Array(s.length+t.length);return n.set(s),n.set(t,s.length),n}function dzn(s,t){const n=[],r=t.samples,a=t.timescale,i=t.id;let l=!1;return Tl(r,["moof"]).map(c=>{const d=c.byteOffset-8;Tl(c,["traf"]).map(h=>{const m=Tl(h,["tfdt"]).map(p=>{const g=p[0];let x=Wi(p,4);return g===1&&(x*=Math.pow(2,32),x+=Wi(p,8)),x/a})[0];return m!==void 0&&(s=m),Tl(h,["tfhd"]).map(p=>{const g=Wi(p,4),x=Wi(p,0)&16777215,y=(x&1)!==0;let v=0;const _=(x&2)!==0,j=(x&8)!==0;let C=0;const A=(x&16)!==0;let M=0;const I=(x&32)!==0,P=!y&&(x&131072)!==0;let R=8;g===i&&(y?(v=Wi(p,R),R+=4,v*=Math.pow(2,32),v+=Wi(p,R),R+=4):P&&(v=d),_&&(R+=4),j&&(C=Wi(p,R),R+=4),A&&(M=Wi(p,R),R+=4),I&&(R+=4),t.type==="video"&&(l=jte(t.codec)),Tl(h,["trun"]).map(O=>{const B=O[0],U=Wi(O,0)&16777215,G=(U&1)!==0;let H=0;const Y=(U&4)!==0,se=(U&256)!==0;let ee=0;const oe=(U&512)!==0;let me=0;const Q=(U&1024)!==0,te=(U&2048)!==0;let le=0;const fe=Wi(O,4);let _e=8;G&&(H=Wi(O,_e),_e+=4),Y&&(_e+=4);let ve=v+H;for(let he=0;he>1&63;return n===39||n===40}else return(t&31)===6}function xQ(s,t,n,r){const a=SHt(s);let i=0;i+=t;let l=0,o=0,c=0;for(;i=a.length)break;c=a[i++],l+=c}while(c===255);o=0;do{if(i>=a.length)break;c=a[i++],o+=c}while(c===255);const d=a.length-i;let u=i;if(od){ku.error(`Malformed SEI payload. ${o} is too small, only ${d} bytes left to parse.`);break}if(l===4){if(a[u++]===181){const m=yHt(a,u);if(u+=2,m===49){const p=Wi(a,u);if(u+=4,p===1195456820){const g=a[u++];if(g===3){const x=a[u++],y=31&x,v=64&x,_=v?2+y*3:0,j=new Uint8Array(_);if(v){j[0]=x;for(let C=1;C<_;C++)j[C]=a[u++]}r.push({type:g,payloadType:l,pts:n,bytes:j})}}}}}else if(l===5&&o>16){const h=[];for(let g=0;g<16;g++){const x=a[u++].toString(16);h.push(x.length==1?"0"+x:x),(g===3||g===5||g===7||g===9)&&h.push("-")}const m=o-16,p=new Uint8Array(m);for(let g=0;g>24&255,i[1]=r>>16&255,i[2]=r>>8&255,i[3]=r&255,i.set(s,4),a=0,r=8;a0?(i=new Uint8Array(4),t.length>0&&new DataView(i.buffer).setUint32(0,t.length,!1)):i=new Uint8Array;const l=new Uint8Array(4);return n.byteLength>0&&new DataView(l.buffer).setUint32(0,n.byteLength,!1),hzn([112,115,115,104],new Uint8Array([r,0,0,0]),s,i,a,l,n)}function CHt(s){const t=[];if(s instanceof ArrayBuffer){const n=s.byteLength;let r=0;for(;r+32>3===2)if(i===32){const l=new Uint8Array(16);for(let o=0;o<16;o++)l[o]=parseInt(String.fromCharCode(s[n+o*2],s[n+o*2+1]),16);t.push(l)}else i===16&&t.push(s.subarray(n,n+16));n+=i}return t}function pzn(s){const t=s.getUint32(0),n=s.byteOffset,r=s.byteLength;if(r>>24;if(i!==0&&i!==1)return{offset:n,size:t};const l=s.buffer,o=Ax(new Uint8Array(l,n+12,16));let c=null,d=null,u=0;if(i===0)u=28;else{const m=s.getUint32(28);if(!m||r<32+m*16)return{offset:n,size:t};c=[];for(let p=0;p-1||/iPhone|iPad|iPod/.test(WV)}function bzn(){return/Android/.test(WV)}const vq={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},image:{mjpg:1}};function IQe(s,t){const n=vq[t];return!!n&&!!n[s.slice(0,4)]}function yQ(s,t,n=!0){return!s.split(",").some(r=>!LQe(r,t,n))}function LQe(s,t,n=!0){var r;const a=zM(n);return(r=a==null?void 0:a.isTypeSupported(vQ(s,t)))!=null?r:!1}function vQ(s,t){return`${t}/mp4;codecs=${s}`}function Xbt(s){if(s){const t=s.substring(0,4);return vq.video[t]}return 2}function sCe(s){const t=EHt();return s.split(",").reduce((n,r)=>{const i=t&&jte(r)?9:vq.video[r];return i?(i*2+n)/(n?3:2):(vq.audio[r]+n)/(n?2:1)},0)}const f8e={};function _zn(s,t=!0){if(f8e[s])return f8e[s];const n={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[s];for(let a=0;a_zn(n.toLowerCase(),t))}function jzn(s,t){const n=[];if(s){const r=s.split(",");for(let a=0;a4||["ac-3","ec-3","alac","fLaC","Opus"].indexOf(s)!==-1)&&(Qbt(s,"audio")||Qbt(s,"video")))return s;if(t){const n=t.split(",");if(n.length>1){if(s){for(let r=n.length;r--;)if(n[r].substring(0,4)===s.substring(0,4))return n[r]}return n[0]}}return t||s}function Qbt(s,t){return IQe(s,t)&&LQe(s,t)}function Nzn(s){const t=s.split(",");for(let n=0;n2&&r[0]==="avc1"&&(t[n]=`avc1.${parseInt(r[1]).toString(16)}${("000"+parseInt(r[2]).toString(16)).slice(-4)}`)}return t.join(",")}function kzn(s){if(s.startsWith("av01.")){const t=s.split("."),n=["0","111","01","01","01","0"];for(let r=t.length;r>4&&r<10;r++)t[r]=n[r-4];return t.join(".")}return s}function Jbt(s){const t=zM(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 cqe(s){return s.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}const Szn={supported:!0,powerEfficient:!0,smooth:!0},Czn={supported:!1,smooth:!1,powerEfficient:!1},THt={supported:!0,configurations:[],decodingInfoResults:[Szn]};function MHt(s,t){return{supported:!1,configurations:t,decodingInfoResults:[Czn],error:s}}function Azn(s,t,n,r,a,i){const l=s.videoCodec,o=s.audioCodec?s.audioGroups:null,c=i==null?void 0:i.audioCodec,d=i==null?void 0:i.channels,u=d?parseInt(d):c?1/0:2;let h=null;if(o!=null&&o.length)try{o.length===1&&o[0]?h=t.groups[o[0]].channels:h=o.reduce((m,p)=>{if(p){const g=t.groups[p];if(!g)throw new Error(`Audio track group ${p} not found`);Object.keys(g.channels).forEach(x=>{m[x]=(m[x]||0)+g.channels[x]})}return m},{2:0})}catch{return!0}return l!==void 0&&(l.split(",").some(m=>jte(m))||s.width>1920&&s.height>1088||s.height>1920&&s.width>1088||s.frameRate>Math.max(r,30)||s.videoRange!=="SDR"&&s.videoRange!==n||s.bitrate>Math.max(a,8e6))||!!h&&mi(u)&&Object.keys(h).some(m=>parseInt(m)>u)}function PHt(s,t,n,r={}){const a=s.videoCodec;if(!a&&!s.audioCodec||!n)return Promise.resolve(THt);const i=[],l=Ezn(s),o=l.length,c=Tzn(s,t,o>0),d=c.length;for(let u=o||1*d||1;u--;){const h={type:"media-source"};if(o&&(h.video=l[u%o]),d){h.audio=c[u%d];const m=h.audio.bitrate;h.video&&m&&(h.video.bitrate-=m)}i.push(h)}if(a){const u=navigator.userAgent;if(a.split(",").some(h=>jte(h))&&EHt())return Promise.resolve(MHt(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${u})`),i))}return Promise.all(i.map(u=>{const h=Mzn(u);return r[h]||(r[h]=n.decodingInfo(u))})).then(u=>({supported:!u.some(h=>!h.supported),configurations:i,decodingInfoResults:u})).catch(u=>({supported:!1,configurations:i,decodingInfoResults:[],error:u}))}function Ezn(s){var t;const n=(t=s.videoCodec)==null?void 0:t.split(","),r=LHt(s),a=s.width||640,i=s.height||480,l=s.frameRate||30,o=s.videoRange.toLowerCase();return n?n.map(c=>{const d={contentType:vQ(kzn(c),"video"),width:a,height:i,bitrate:r,framerate:l};return o!=="sdr"&&(d.transferFunction=o),d}):[]}function Tzn(s,t,n){var r;const a=(r=s.audioCodec)==null?void 0:r.split(","),i=LHt(s);return a&&s.audioGroups?s.audioGroups.reduce((l,o)=>{var c;const d=o?(c=t.groups[o])==null?void 0:c.tracks:null;return d?d.reduce((u,h)=>{if(h.groupId===o){const m=parseFloat(h.channels||"");a.forEach(p=>{const g={contentType:vQ(p,"audio"),bitrate:n?IHt(p,i):i};m&&(g.channels=""+m),u.push(g)})}return u},l):l},[]):[]}function IHt(s,t){if(t<=1)return 1;let n=128e3;return s==="ec-3"?n=768e3:s==="ac-3"&&(n=64e4),Math.min(t/2,n)}function LHt(s){return Math.ceil(Math.max(s.bitrate*.9,s.averageBitrate)/1e3)*1e3||1}function Mzn(s){let t="";const{audio:n,video:r}=s;if(r){const a=cqe(r.contentType);t+=`${a}_r${r.height}x${r.width}f${Math.ceil(r.framerate)}${r.transferFunction||"sd"}_${Math.ceil(r.bitrate/1e5)}`}if(n){const a=cqe(n.contentType);t+=`${r?"_":""}${a}_c${n.channels}`}return t}function xM(s,t,n){const r=encodeURIComponent(t),a=`${r}=${encodeURIComponent(n)}`;let i=!1;const l=[];s.search.substring(1).split("&").forEach(o=>{o===r||o.startsWith(r+"=")?i||(l.push(a),i=!0):o&&l.push(o)}),i||l.push(a),s.search=l.join("&")}const dqe=["NONE","TYPE-0","TYPE-1",null];function Pzn(s){return dqe.indexOf(s)>-1}const rCe=["SDR","PQ","HLG"];function Izn(s){return!!s&&rCe.indexOf(s)>-1}var gke={No:"",Yes:"YES",v2:"v2"};function e_t(s){const{canSkipUntil:t,canSkipDateRanges:n,age:r}=s,a=r!!r).map(r=>r.substring(0,4)).join(","),"supplemental"in t){var n;this.supplemental=t.supplemental;const r=(n=t.supplemental)==null?void 0:n.videoCodec;r&&r!==t.videoCodec&&(this.codecSet+=`,${r.substring(0,4)}`)}"iframes"in t&&t.iframes?this.iframes=!0:(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 s_t(this._audioGroups,t)}hasSubtitleGroup(t){return s_t(this._subtitleGroups,t)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(t,n){if(n){if(t==="audio"){let r=this._audioGroups;r||(r=this._audioGroups=[]),r.indexOf(n)===-1&&r.push(n)}else if(t==="text"){let r=this._subtitleGroups;r||(r=this._subtitleGroups=[]),r.indexOf(n)===-1&&r.push(n)}}}get urlId(){return 0}set urlId(t){}get audioGroupIds(){return this.audioGroups?[this.audioGroupId]:void 0}get textGroupIds(){return this.subtitleGroups?[this.textGroupId]:void 0}get audioGroupId(){var t;return(t=this.audioGroups)==null?void 0:t[0]}get textGroupId(){var t;return(t=this.subtitleGroups)==null?void 0:t[0]}addFallback(){}}function s_t(s,t){return!t||!s?!1:s.indexOf(t)!==-1}function Lzn(){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 Rzn(s,t){let n=!1,r=[];if(s&&(n=s!=="SDR",r=[s]),t){r=t.allowedVideoRanges||rCe.slice(0);const a=r.join("")!=="SDR"&&!t.videoCodec;n=t.preferHDR!==void 0?t.preferHDR:a&&Lzn(),n||(r=["SDR"])}return{preferHDR:n,allowedVideoRanges:r}}const Dzn=s=>{const t=new WeakSet;return(n,r)=>{if(s&&(r=s(n,r)),typeof r=="object"&&r!==null){if(t.has(r))return;t.add(r)}return r}},bm=(s,t)=>JSON.stringify(s,Dzn(t));function Ozn(s,t,n,r,a){const i=Object.keys(s),l=r==null?void 0:r.channels,o=r==null?void 0:r.audioCodec,c=a==null?void 0:a.videoCodec,d=l&&parseInt(l)===2;let u=!1,h=!1,m=1/0,p=1/0,g=1/0,x=1/0,y=0,v=[];const{preferHDR:_,allowedVideoRanges:j}=Rzn(t,a);for(let P=i.length;P--;){const R=s[i[P]];u||(u=R.channels[2]>0),m=Math.min(m,R.minHeight),p=Math.min(p,R.minFramerate),g=Math.min(g,R.minBitrate),j.filter(B=>R.videoRanges[B]>0).length>0&&(h=!0)}m=mi(m)?m:0,p=mi(p)?p:0;const C=Math.max(1080,m),A=Math.max(30,p);g=mi(g)?g:n,n=Math.max(g,n),h||(t=void 0);const M=i.length>1;return{codecSet:i.reduce((P,R)=>{const O=s[R];if(R===P)return P;if(v=h?j.filter(B=>O.videoRanges[B]>0):[],M){if(O.minBitrate>n)return pS(R,`min bitrate of ${O.minBitrate} > current estimate of ${n}`),P;if(!O.hasDefaultAudio)return pS(R,"no renditions with default or auto-select sound found"),P;if(o&&R.indexOf(o.substring(0,4))%5!==0)return pS(R,`audio codec preference "${o}" not found`),P;if(l&&!d){if(!O.channels[l])return pS(R,`no renditions with ${l} channel sound found (channels options: ${Object.keys(O.channels)})`),P}else if((!o||d)&&u&&O.channels[2]===0)return pS(R,"no renditions with stereo sound found"),P;if(O.minHeight>C)return pS(R,`min resolution of ${O.minHeight} > maximum of ${C}`),P;if(O.minFramerate>A)return pS(R,`min framerate of ${O.minFramerate} > maximum of ${A}`),P;if(!v.some(B=>O.videoRanges[B]>0))return pS(R,`no variants with VIDEO-RANGE of ${bm(v)} found`),P;if(c&&R.indexOf(c.substring(0,4))%5!==0)return pS(R,`video codec preference "${c}" not found`),P;if(O.maxScore=sCe(P)||O.fragmentError>s[P].fragmentError)?P:(x=O.minIndex,y=O.maxScore,R)},void 0),videoRanges:v,preferHDR:_,minFramerate:p,minBitrate:g,minIndex:x}}function pS(s,t){ku.log(`[abr] start candidates with "${s}" ignored because ${t}`)}function RHt(s){return s.reduce((t,n)=>{let r=t.groups[n.groupId];r||(r=t.groups[n.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),r.tracks.push(n);const a=n.channels||"2";return r.channels[a]=(r.channels[a]||0)+1,r.hasDefault=r.hasDefault||n.default,r.hasAutoSelect=r.hasAutoSelect||n.autoselect,r.hasDefault&&(t.hasDefaultAudio=!0),r.hasAutoSelect&&(t.hasAutoSelectAudio=!0),t},{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function Fzn(s,t,n,r){return s.slice(n,r+1).reduce((a,i,l)=>{if(!i.codecSet)return a;const o=i.audioGroups;let c=a[i.codecSet];c||(a[i.codecSet]=c={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:l,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!o,fragmentError:0}),c.minBitrate=Math.min(c.minBitrate,i.bitrate);const d=Math.min(i.height,i.width);return c.minHeight=Math.min(c.minHeight,d),c.minFramerate=Math.min(c.minFramerate,i.frameRate),c.minIndex=Math.min(c.minIndex,l),c.maxScore=Math.max(c.maxScore,i.score),c.fragmentError+=i.fragmentError,c.videoRanges[i.videoRange]=(c.videoRanges[i.videoRange]||0)+1,o&&o.forEach(u=>{if(!u)return;const h=t.groups[u];h&&(c.hasDefaultAudio=c.hasDefaultAudio||t.hasDefaultAudio?h.hasDefault:h.hasAutoSelect||!t.hasDefaultAudio&&!t.hasAutoSelectAudio,Object.keys(h.channels).forEach(m=>{c.channels[m]=(c.channels[m]||0)+h.channels[m]}))}),a},{})}function n_t(s){if(!s)return s;const{lang:t,assocLang:n,characteristics:r,channels:a,audioCodec:i}=s;return{lang:t,assocLang:n,characteristics:r,channels:a,audioCodec:i}}function b5(s,t,n){if("attrs"in s){const r=t.indexOf(s);if(r!==-1)return r}for(let r=0;rr.indexOf(a)===-1)}function qR(s,t){const{audioCodec:n,channels:r}=s;return(n===void 0||(t.audioCodec||"").substring(0,4)===n.substring(0,4))&&(r===void 0||r===(t.channels||"2"))}function $zn(s,t,n,r,a){const i=t[r],o=t.reduce((m,p,g)=>{const x=p.uri;return(m[x]||(m[x]=[])).push(g),m},{})[i.uri];o.length>1&&(r=Math.max.apply(Math,o));const c=i.videoRange,d=i.frameRate,u=i.codecSet.substring(0,4),h=r_t(t,r,m=>{if(m.videoRange!==c||m.frameRate!==d||m.codecSet.substring(0,4)!==u)return!1;const p=m.audioGroups,g=n.filter(x=>_Q(x.groupId,p));return b5(s,g,a)>-1});return h>-1?h:r_t(t,r,m=>{const p=m.audioGroups,g=n.filter(x=>_Q(x.groupId,p));return b5(s,g,a)>-1})}function r_t(s,t,n){for(let r=t;r>-1;r--)if(n(s[r]))return r;for(let r=t+1;r{var r;const{fragCurrent:a,partCurrent:i,hls:l}=this;if(!l)return;const{autoLevelEnabled:o,media:c}=l;if(!a||!c)return;const d=performance.now(),u=i?i.stats:a.stats,h=i?i.duration:a.duration,m=d-u.loading.start,p=l.minAutoLevel,g=a.level,x=this._nextAutoLevel;if(u.aborted||u.loaded&&u.loaded===u.total||g<=p){this.clearTimer(),this._nextAutoLevel=-1;return}if(!o)return;const y=x>-1&&x!==g,v=!!n||y;if(!v&&(c.paused||!c.playbackRate||!c.readyState))return;const _=l.mainForwardBufferInfo;if(!v&&_===null)return;const j=this.bwEstimator.getEstimateTTFB(),C=Math.abs(c.playbackRate);if(m<=Math.max(j,1e3*(h/(C*2))))return;const A=_?_.len/C:0,M=u.loading.first?u.loading.first-u.loading.start:-1,I=u.loaded&&M>-1,P=this.getBwEstimate(),R=l.levels,O=R[g],B=Math.max(u.loaded,Math.round(h*(a.bitrate||O.averageBitrate)/8));let U=I?m-M:m;U<1&&I&&(U=Math.min(m,u.loaded*8/P));const G=I?u.loaded*1e3/U:0,H=j/1e3,Y=G?(B-u.loaded)/G:B*8/P+H;if(Y<=A)return;const se=G?G*8:P,ee=((r=(n==null?void 0:n.details)||l.latestLevelDetails)==null?void 0:r.live)===!0,oe=l.config.abrBandWidthUpFactor;let me=Number.POSITIVE_INFINITY,Q;for(Q=g-1;Q>p;Q--){const _e=R[Q].maxBitrate,ve=!R[Q].details||ee;if(me=this.getTimeToLoadFrag(H,se,h*_e,ve),me=Y||me>h*10)return;I?this.bwEstimator.sample(m-Math.min(j,M),u.loaded):this.bwEstimator.sampleTTFB(m);const te=R[Q].maxBitrate;this.getBwEstimate()*oe>te&&(this.firstAutoFloor=Math.min(Q,l.firstLevel),this.resetEstimator(te));const le=this.findBestLevel(te,p,Q,0,A,1,1);le>-1&&(Q=le),this.warn(`Fragment ${a.sn}${i?" part "+i.index:""} of level ${g} is loading too slowly; Fragment duration: ${a.duration.toFixed(3)} Time to underbuffer: ${A.toFixed(3)} s Estimated load time for current fragment: ${Y.toFixed(3)} s Estimated load time for down switch fragment: ${me.toFixed(3)} s TTFB estimate: ${M|0} ms Current BW estimate: ${mi(P)?P|0:"Unknown"} bps New BW estimate: ${this.getBwEstimate()|0} bps Switching to level ${Q} @ ${te|0} bps`),l.nextLoadLevel=l.nextAutoLevel=Q,this.clearTimer();const fe=()=>{this.clearTimer();const _e=this.hls;if(this.fragCurrent===a&&_e.loadLevel===Q&&Q>0){const ve=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${Q>0?"and switching down":""} Fragment duration: ${a.duration.toFixed(3)} s Time to underbuffer: ${ve.toFixed(3)} s`),a.abortRequests(),this.fragCurrent=this.partCurrent=null,Q>p){let he=this.findBestLevel(_e.levels[p].bitrate,p,Q,0,ve,1,1);he===-1&&(he=p),_e.nextLoadLevel=_e.nextAutoLevel=he,this.firstAutoFloor=Math.min(he,_e.firstLevel),this.resetEstimator(_e.levels[he].bitrate)}}};y||Y>me*2?fe():this.timer=self.setInterval(fe,me*1e3),l.trigger(Mt.FRAG_LOAD_EMERGENCY_ABORTED,{frag:a,part:i,stats:u})},this.hls=t,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(t){this.hls&&(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 A9n(t.abrEwmaSlowVoD,t.abrEwmaFastVoD,t.abrEwmaDefaultEstimate)}registerListeners(){const t=this.hls;t.on(Mt.MANIFEST_LOADING,this.onManifestLoading,this),t.on(Mt.FRAG_LOADING,this.onFragLoading,this),t.on(Mt.FRAG_LOADED,this.onFragLoaded,this),t.on(Mt.FRAG_BUFFERED,this.onFragBuffered,this),t.on(Mt.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(Mt.LEVEL_LOADED,this.onLevelLoaded,this),t.on(Mt.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(Mt.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.on(Mt.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t&&(t.off(Mt.MANIFEST_LOADING,this.onManifestLoading,this),t.off(Mt.FRAG_LOADING,this.onFragLoading,this),t.off(Mt.FRAG_LOADED,this.onFragLoaded,this),t.off(Mt.FRAG_BUFFERED,this.onFragBuffered,this),t.off(Mt.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(Mt.LEVEL_LOADED,this.onLevelLoaded,this),t.off(Mt.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(Mt.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.off(Mt.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=this.supportedCache=null,this.audioTracksByGroup=this.codecTiers=this.fragCurrent=this.partCurrent=null}onManifestLoading(t,n){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.firstAutoFloor=-1,this.lastLevelLoadSec=0,this.supportedCache={},this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()}onLevelsUpdated(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null}onMaxAutoLevelUpdated(){this.firstSelection=-1,this.nextAutoLevelKey=""}onFragLoading(t,n){const r=n.frag;if(!this.ignoreFragment(r)){if(!r.bitrateTest){var a;this.fragCurrent=r,this.partCurrent=(a=n.part)!=null?a:null}this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100)}}onLevelSwitching(t,n){this.clearTimer()}onError(t,n){if(!n.fatal)switch(n.details){case er.BUFFER_ADD_CODEC_ERROR:case er.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case er.FRAG_LOAD_TIMEOUT:{const r=n.frag,{fragCurrent:a,partCurrent:i}=this;if(r&&rqe(r,a)){const l=performance.now(),o=i?i.stats:r.stats,c=l-o.loading.start,d=o.loading.first?o.loading.first-o.loading.start:-1;if(o.loaded&&d>-1){const h=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(c-Math.min(h,d),o.loaded)}else this.bwEstimator.sampleTTFB(c)}break}}}getTimeToLoadFrag(t,n,r,a){const i=t+r/n,l=a?t+this.lastLevelLoadSec:0;return i+l}onLevelLoaded(t,n){const r=this.hls.config,{loading:a}=n.stats,i=a.end-a.first;mi(i)&&(this.lastLevelLoadSec=i/1e3),n.details.live?this.bwEstimator.update(r.abrEwmaSlowLive,r.abrEwmaFastLive):this.bwEstimator.update(r.abrEwmaSlowVoD,r.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(n.levelInfo)}onFragLoaded(t,n){var r;const{frag:a,part:i}=n,l=i?i.stats:a.stats;if(a.type===Ji.MAIN&&this.bwEstimator.sampleTTFB(l.loading.first-l.loading.start),!this.ignoreFragment(a)){if(this.clearTimer(),a.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,(r=this.hls)!=null&&r.config.abrMaxWithRealBitrate){const o=i?i.duration:a.duration,c=this.hls.levels[a.level],d=(c.loaded?c.loaded.bytes:0)+l.loaded,u=(c.loaded?c.loaded.duration:0)+o;c.loaded={bytes:d,duration:u},c.realBitrate=Math.round(8*d/u)}if(a.bitrateTest){const o={stats:l,frag:a,part:i,id:a.type};this.onFragBuffered(Mt.FRAG_BUFFERED,o),a.bitrateTest=!1}else this.lastLoadedFragLevel=a.level}}onFragBuffered(t,n){const{frag:r,part:a}=n,i=a!=null&&a.stats.loaded?a.stats:r.stats;if(i.aborted||this.ignoreFragment(r))return;const o=((r.bitrate||0)>=1e5?i.parsing.end:i.loading.end)-i.loading.start-Math.min(i.loading.first-i.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(o,i.loaded),i.bwEstimate=this.getBwEstimate(),r.bitrateTest?this.bitrateTestDelay=o/1e3:(this.bitrateTestDelay=0,this.firstAutoFloor>-1&&this.bwEstimator.canEstimate()&&(this.firstAutoFloor=-1))}ignoreFragment(t){return t.type!==Ji.MAIN||t.sn==="initSegment"}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{hls:t}=this;if(!t)return 0;const{maxAutoLevel:n,minAutoLevel:r}=t,a=this.getBwEstimate(),i=this.getStarvationDelay(),l=t.config.maxStarvationDelay,o=this.findBestLevel(a,r,n,i/2,l,1,1);if(o>-1)return o;const c=t.firstLevel,d=this.firstAutoFloor===-1?1/0:this.firstAutoFloor,u=Math.min(Math.max(c,r),n,d);return this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${c} clamped to ${u}`),u}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){if(!this.hls)return-1;const t=this.forcedAutoLevel,r=this.bwEstimator.canEstimate(),a=this.lastLoadedFragLevel>-1;if(t!==-1&&(!r||!a||this.nextAutoLevelKey===this.getAutoLevelKey()))return t;const i=r&&a?this.getNextABRAutoLevel():this.firstAutoLevel;if(t!==-1){const l=this.hls.levels;if(l.length>Math.max(t,i)&&l[t].loadError<=l[i].loadError)return t}return this._nextAutoLevel=i,this.nextAutoLevelKey=this.getAutoLevelKey(),i}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){const{fragCurrent:t,partCurrent:n,hls:r}=this;if(!r)return-1;if(r.levels.length<=1)return r.loadLevel;const{maxAutoLevel:a,config:i,minAutoLevel:l}=r,o=n?n.duration:t?t.duration:0,c=this.getBwEstimate(),d=this.getStarvationDelay();let u=i.abrBandWidthFactor,h=i.abrBandWidthUpFactor;if(d){const y=this.findBestLevel(c,l,a,d,0,u,h);if(y>=0)return this.rebufferNotice=-1,y}let m=o?Math.min(o,i.maxStarvationDelay):i.maxStarvationDelay;if(!d){const y=this.bitrateTestDelay;y&&(m=(o?Math.min(o,i.maxLoadingDelay):i.maxLoadingDelay)-y,this.info(`bitrate test took ${Math.round(1e3*y)}ms, set first fragment max fetchDuration to ${Math.round(1e3*m)} ms`),u=h=1)}const p=this.findBestLevel(c,l,a,d,m,u,h);if(this.rebufferNotice!==p&&(this.rebufferNotice=p,this.info(`${d?"rebuffering expected":"buffer is empty"}, optimal quality level ${p}`)),p>-1)return p;const g=r.levels[l],x=r.loadLevelObj;return x&&(g==null?void 0:g.bitrate)=n;ee--){var se;const oe=g[ee],me=ee>p;if(!oe)continue;if(_.useMediaCapabilities&&!oe.supportedResult&&!oe.supportedPromise){const he=navigator.mediaCapabilities;typeof(he==null?void 0:he.decodingInfo)=="function"&&Azn(oe,B,I,P,t,R)?(oe.supportedPromise=PHt(oe,B,he,this.supportedCache),oe.supportedPromise.then(Se=>{if(!this.hls)return;oe.supportedResult=Se;const Te=this.hls.levels,Ie=Te.indexOf(oe);Se.error?this.warn(`MediaCapabilities decodingInfo error: "${Se.error}" for level ${Ie} ${bm(Se)}`):Se.supported?Se.decodingInfoResults.some(Ue=>Ue.smooth===!1||Ue.powerEfficient===!1)&&this.log(`MediaCapabilities decodingInfo for level ${Ie} not smooth or powerEfficient: ${bm(Se)}`):(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${Ie} ${bm(Se)}`),Ie>-1&&Te.length>1&&(this.log(`Removing unsupported level ${Ie}`),this.hls.removeLevel(Ie),this.hls.loadLevel===-1&&(this.hls.nextLoadLevel=0)))}).catch(Se=>{this.warn(`Error handling MediaCapabilities decodingInfo: ${Se}`)})):oe.supportedResult=THt}if((M&&oe.codecSet!==M||I&&oe.videoRange!==I||me&&P>oe.frameRate||!me&&P>0&&Phe.smooth===!1))&&(!A||ee!==U)){Y.push(ee);continue}const Q=oe.details,te=(h?Q==null?void 0:Q.partTarget:Q==null?void 0:Q.averagetargetduration)||G||1;let le;me?le=o*t:le=l*t;const fe=G&&a>=G*2&&i===0?oe.averageBitrate:oe.maxBitrate,_e=this.getTimeToLoadFrag(H,le,fe*te,!Q||Q.live);if(le>=fe&&(ee===d||oe.loadError===0&&oe.fragmentError===0||cHt(oe,_.errorPenaltyExpireMs))&&(_e<=H||!mi(_e)||C&&!this.bitrateTestDelay||_e${ee} adjustedbw(${Math.round(le)})-bitrate=${Math.round(le-fe)} ttfb:${H.toFixed(1)} avgDuration:${te.toFixed(1)} maxFetchDuration:${m.toFixed(1)} fetchDuration:${_e.toFixed(1)} firstSelection:${A} codecSet:${oe.codecSet} videoRange:${oe.videoRange} hls.loadLevel:${y}`)),A&&(this.firstSelection=ee),ee}}return-1}set nextAutoLevel(t){const n=this.deriveNextAutoLevel(t);this._nextAutoLevel!==n&&(this.nextAutoLevelKey="",this._nextAutoLevel=n)}deriveNextAutoLevel(t){if(!this.hls)return-1;const{maxAutoLevel:n,minAutoLevel:r}=this.hls;return Math.min(Math.max(t,r),n)}}const OHt={search:function(s,t){let n=0,r=s.length-1,a=null,i=null;for(;n<=r;){a=(n+r)/2|0,i=s[a];const l=t(i);if(l>0)n=a+1;else if(l<0)r=a-1;else return i}return null}};function qzn(s,t,n){if(t===null||!Array.isArray(s)||!s.length||!mi(t))return null;const r=s[0].programDateTime;if(t<(r||0))return null;const a=s[s.length-1].endProgramDateTime;if(t>=(a||0))return null;for(let i=0;i0&&o<15e-7&&(n+=15e-7),i&&s.level!==i.level&&i.end<=s.end&&(i=t[2+s.sn-t[0].sn]||null)}else n===0&&t[0].start===0&&(i=t[0]);if(i&&((!s||s.level===i.level)&&a_t(n,r,i)===0||Vzn(i,s,Math.min(a,r))))return i;const l=OHt.search(t,a_t.bind(null,n,r));return l&&(l!==s||!i)?l:i}function Vzn(s,t,n){if((t==null?void 0:t.start)===0&&t.level0){const r=t.tagList.reduce((a,i)=>(i[0]==="INF"&&(a+=parseFloat(i[1])),a),n);return s.start<=r}return!1}function a_t(s=0,t=0,n){if(n.start<=s&&n.start+n.duration>s)return 0;const r=Math.min(t,n.duration+(n.deltaPTS?n.deltaPTS:0));return n.start+n.duration-r<=s?1:n.start-r>s&&n.start?-1:0}function Hzn(s,t,n){const r=Math.min(t,n.duration+(n.deltaPTS?n.deltaPTS:0))*1e3;return(n.endProgramDateTime||0)-r>s}function FHt(s,t,n){if(s&&s.startCC<=t&&s.endCC>=t){let r=s.fragments;const{fragmentHint:a}=s;a&&(r=r.concat(a));let i;return OHt.search(r,l=>l.cct?-1:(i=l,l.end<=n?1:l.start>n?-1:0)),i||null}return null}function zHt(s,t){return t===s.endSN&&s.fragmentHint?s.fragmentHint:s.fragments[1+t-s.startSN]||null}var Y0={DoNothing:0,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,RetryRequest:5},Yy={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,MoveAllAlternatesMatchingKey:4,SwitchToSDR:8,ResetMediaSource:16};class Gzn extends wj{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(Mt.ERROR,this.onError,this),t.on(Mt.MANIFEST_LOADING,this.onManifestLoading,this),t.on(Mt.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const t=this.hls;t&&(t.off(Mt.ERROR,this.onError,this),t.off(Mt.ERROR,this.onErrorOut,this),t.off(Mt.MANIFEST_LOADING,this.onManifestLoading,this),t.off(Mt.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)===Ji.MAIN?t.level:this.getVariantIndex()}getVariantIndex(){var t;const n=this.hls,r=n.currentLevel;return(t=n.loadLevelObj)!=null&&t.details||r===-1?n.loadLevel:r}variantHasKey(t,n){if(t){var r;if((r=t.details)!=null&&r.hasKey(n))return!0;const a=t.audioGroups;if(a)return this.hls.allAudioTracks.filter(l=>a.indexOf(l.groupId)>=0).some(l=>{var o;return(o=l.details)==null?void 0:o.hasKey(n)})}return!1}onManifestLoading(){this.playlistError=0}onLevelUpdated(){this.playlistError=0}onError(t,n){var r;if(n.fatal)return;const a=this.hls,i=n.context;switch(n.details){case er.FRAG_LOAD_ERROR:case er.FRAG_LOAD_TIMEOUT:case er.KEY_LOAD_ERROR:case er.KEY_LOAD_TIMEOUT:n.errorAction=this.getFragRetryOrSwitchAction(n);return;case er.FRAG_PARSING_ERROR:if((r=n.frag)!=null&&r.gap){n.errorAction=cZ();return}case er.FRAG_GAP:case er.FRAG_DECRYPT_ERROR:{n.errorAction=this.getFragRetryOrSwitchAction(n),n.errorAction.action=Y0.SendAlternateToPenaltyBox;return}case er.PLAYLIST_UNCHANGED_ERROR:case er.LEVEL_EMPTY_ERROR:case er.LEVEL_PARSING_ERROR:{var l;const o=n.parent===Ji.MAIN?n.level:a.loadLevel;n.details===er.LEVEL_EMPTY_ERROR&&((l=n.context)!=null&&(l=l.levelDetails)!=null&&l.live)?n.errorAction=this.getPlaylistRetryOrSwitchAction(n,o):(n.levelRetry=!1,n.errorAction=this.getLevelSwitchAction(n,o))}return;case er.LEVEL_LOAD_ERROR:case er.LEVEL_LOAD_TIMEOUT:typeof(i==null?void 0:i.level)=="number"&&(n.errorAction=this.getPlaylistRetryOrSwitchAction(n,i.level));return;case er.AUDIO_TRACK_LOAD_ERROR:case er.AUDIO_TRACK_LOAD_TIMEOUT:case er.SUBTITLE_LOAD_ERROR:case er.SUBTITLE_TRACK_LOAD_TIMEOUT:if(i){const o=a.loadLevelObj;if(o&&(i.type===Mc.AUDIO_TRACK&&o.hasAudioGroup(i.groupId)||i.type===Mc.SUBTITLE_TRACK&&o.hasSubtitleGroup(i.groupId))){n.errorAction=this.getPlaylistRetryOrSwitchAction(n,a.loadLevel),n.errorAction.action=Y0.SendAlternateToPenaltyBox,n.errorAction.flags=Yy.MoveAllAlternatesMatchingHost;return}}return;case er.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:n.errorAction={action:Y0.SendAlternateToPenaltyBox,flags:Yy.MoveAllAlternatesMatchingHDCP};return;case er.KEY_SYSTEM_SESSION_UPDATE_FAILED:case er.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case er.KEY_SYSTEM_NO_SESSION:n.errorAction={action:Y0.SendAlternateToPenaltyBox,flags:Yy.MoveAllAlternatesMatchingKey};return;case er.BUFFER_ADD_CODEC_ERROR:case er.REMUX_ALLOC_ERROR:case er.BUFFER_APPEND_ERROR:n.errorAction||(n.errorAction=this.getLevelSwitchAction(n,n.level));return;case er.MEDIA_SOURCE_REQUIRES_RESET:n.errorAction||(n.errorAction=this.getLevelSwitchAction(n,n.level)),n.errorAction.flags|=Yy.ResetMediaSource|Yy.SwitchToSDR;return;case er.INTERNAL_EXCEPTION:case er.BUFFER_APPENDING_ERROR:case er.BUFFER_APPEND_NO_PROGRESS:case er.BUFFER_FULL_ERROR:case er.LEVEL_SWITCH_ERROR:case er.BUFFER_STALLED_ERROR:case er.BUFFER_SEEK_OVER_HOLE:case er.BUFFER_NUDGE_ON_STALL:n.errorAction=cZ();return}n.type===xo.KEY_SYSTEM_ERROR&&(n.levelRetry=!1,n.errorAction=cZ())}getPlaylistRetryOrSwitchAction(t,n){const r=this.hls,a=Vbt(r.config.playlistLoadPolicy,t),i=this.playlistError++;if(fQ(a,i,tCe(t),t.response))return{action:Y0.RetryRequest,flags:Yy.None,retryConfig:a,retryCount:i};const o=this.getLevelSwitchAction(t,n);return a&&(o.retryConfig=a,o.retryCount=i),o}getFragRetryOrSwitchAction(t){const n=this.hls,r=this.getVariantLevelIndex(t.frag),a=n.levels[r],{fragLoadPolicy:i,keyLoadPolicy:l}=n.config,o=Vbt(oHt(t)?l:i,t),c=n.levels.reduce((u,h)=>u+h.fragmentError,0);if(a&&(t.details!==er.FRAG_GAP&&a.fragmentError++,!lHt(t)&&fQ(o,c,tCe(t),t.response)))return{action:Y0.RetryRequest,flags:Yy.None,retryConfig:o,retryCount:c};const d=this.getLevelSwitchAction(t,r);return o&&(d.retryConfig=o,d.retryCount=c),d}getLevelSwitchAction(t,n){const r=this.hls;n==null&&(n=r.loadLevel);const a=this.hls.levels[n];if(a){var i,l;const d=t.details;a.loadError++,a.loadErrorTime=self.performance.now(),d===er.BUFFER_APPEND_ERROR&&a.fragmentError++;let u=-1;const{levels:h,loadLevel:m,minAutoLevel:p,maxAutoLevel:g}=r;!r.autoLevelEnabled&&!r.config.preserveManualLevelOnError&&(r.loadLevel=-1);const x=(i=t.frag)==null?void 0:i.type,v=(x===Ji.AUDIO&&d===er.FRAG_PARSING_ERROR||t.sourceBufferName==="audio"&&i_t(t))&&h.some(({audioCodec:M})=>a.audioCodec!==M),j=t.sourceBufferName==="video"&&i_t(t)&&h.some(({codecSet:M,audioCodec:I})=>a.codecSet!==M&&a.audioCodec===I),{type:C,groupId:A}=(l=t.context)!=null?l:{};for(let M=h.length;M--;){const I=(M+m)%h.length;if(I!==m&&I>=p&&I<=g&&(h[I].loadError===0||cHt(h[I],r.config.errorPenaltyExpireMs))){var o,c;const P=h[I];if(d===er.FRAG_GAP&&x===Ji.MAIN&&t.frag){const R=h[I].details;if(R){const O=bq(t.frag,R.fragments,t.frag.start);if(O!=null&&O.gap)continue}}else{if(C===Mc.AUDIO_TRACK&&P.hasAudioGroup(A)||C===Mc.SUBTITLE_TRACK&&P.hasSubtitleGroup(A))continue;if(x===Ji.AUDIO&&(o=a.audioGroups)!=null&&o.some(R=>P.hasAudioGroup(R))||x===Ji.SUBTITLE&&(c=a.subtitleGroups)!=null&&c.some(R=>P.hasSubtitleGroup(R))||v&&a.audioCodec===P.audioCodec||j&&a.codecSet===P.codecSet||!v&&a.audioCodec!==P.audioCodec)continue}u=I;break}}if(u>-1&&r.loadLevel!==u)return t.levelRetry=!0,this.playlistError=0,{action:Y0.SendAlternateToPenaltyBox,flags:Yy.None,nextAutoLevel:u}}return{action:Y0.SendAlternateToPenaltyBox,flags:Yy.MoveAllAlternatesMatchingHost}}onErrorOut(t,n){var r,a;switch((r=n.errorAction)==null?void 0:r.action){case Y0.DoNothing:break;case Y0.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(n),!n.errorAction.resolved&&n.details!==er.FRAG_GAP&&n.details!==er.PLAYLIST_UNCHANGED_ERROR&&!BHt(n)&&(n.fatal=!0);break}if((((a=n.errorAction)==null?void 0:a.flags)||0)&Yy.ResetMediaSource&&this.hls.recoverMediaError(),n.fatal){this.hls.stopLoad();return}}sendAlternateToPenaltyBox(t){const n=this.hls,r=t.errorAction;if(!r)return;let a=r.nextAutoLevel;if(r.flags===Yy.None)this.switchLevel(t,a);else if(r.flags&Yy.SwitchToSDR){const o=this.hls.levels,c=o.length;for(let d=c;d--;)o[d].videoRange!=="SDR"?(o[d].fragmentError++,o[d].loadError++):a===void 0&&(a=d)}else if(r.flags&Yy.MoveAllAlternatesMatchingHDCP){const o=this.getVariantLevelIndex(t.frag),c=n.levels[o],d=c==null?void 0:c.attrs["HDCP-LEVEL"];r.hdcpLevel=d;const u=d==="NONE";d&&!u?(n.maxHdcpLevel=dqe[dqe.indexOf(d)-1],r.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${n.maxHdcpLevel}" or lower`)):(u&&this.warn("HDCP policy resticted output with HDCP-LEVEL=NONE"),r.flags|=Yy.MoveAllAlternatesMatchingKey)}if(r.flags&Yy.MoveAllAlternatesMatchingKey){const o=t.decryptdata;if(o){const c=this.hls.levels,d=c.length;for(let h=d;h--;)if(this.variantHasKey(c[h],o)){var i,l;this.log(`Banned key found in level ${h} (${c[h].bitrate}bps) or audio group "${(i=c[h].audioGroups)==null?void 0:i.join(",")}" (${(l=t.frag)==null?void 0:l.type} fragment) ${Ax(o.keyId||[])}`),c[h].fragmentError++,c[h].loadError++,this.log(`Removing level ${h} with key error (${t.error})`),this.hls.removeLevel(h)}const u=t.frag;if(this.hls.levels.length{const d=this.fragments[c];if(!d||!this.hls)return;const u=d.body;if(o>=u.sn)return;if(!d.buffered&&(!d.loaded||l)){u.type===r&&this.removeFragment(u);return}const h=d.range[t];if(h){if(h.time.length===0){this.removeFragment(u);return}if(h.time.some(m=>{const p=!this.isTimeBuffered(m.startPTS,m.endPTS,n);return p&&this.removeFragment(u),p}),a&&a!==u&&lZ()){const m=a.endPTS,p=u.startPTS;if(m&&p&&d.range.video){const g=p-m;g<0&&g>-.1&&(this.removeFragment(u),this.hls.trigger(Mt.BUFFER_FLUSHING,{startOffset:m+.004,endOffset:1/0,type:"video"}))}}}})}detectPartialFragments(t){const n=this.timeRanges,{frag:r,part:a,id:i}=t;if(!n||!Lp(r))return;const l=y9(r),o=this.fragments[l];if(!o||o.buffered&&r.gap)return;const c=!r.relurl;Object.keys(n).forEach(u=>{const h=r.elementaryStreams[u];if(!h)return;const m=n[u],p=c||h.partial===!0;o.range[u]=this.getBufferedTimes(r,a,p,m),this.detectEvictedFragments(u,m,i,r,a)}),o.loaded=null;const d=Object.keys(o.range);if(d.length){if(this.bufferedEnd(o,r),iie(o)||this.removeParts(r.sn-1,r.type),!a){const u=Math.min(.004,r.duration);d.some(h=>{var m;const p=(m=o.range[h])==null?void 0:m.time,g=p.length===0||p.length===1&&p[0].endPTS-p[0].startPTSa.fragment.sn>=t))}fragBuffered(t,n){const r=y9(t);let a=this.fragments[r];return!a&&n&&(a=this.fragments[r]={body:t,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},t.gap&&(this.hasGaps=!0)),a&&(a.loaded=null,this.bufferedEnd(a,t)),a}getBufferedTimes(t,n,r,a){const i={time:[],partial:r},l=t.start,o=t.end,c=t.minEndPTS||o,d=t.maxStartPTS||l;for(let u=0;u=h&&c<=m){i.time.push({startPTS:Math.max(l,a.start(u)),endPTS:Math.min(o,a.end(u))});break}else if(lh){const p=Math.max(l,a.start(u)),g=Math.min(o,a.end(u));g>p&&(i.partial=!0,i.time.push({startPTS:p,endPTS:g}))}else if(o<=h)break}return i}getPartialFragment(t){let n=null,r,a,i,l=0;const{bufferPadding:o,fragments:c}=this;return Object.keys(c).forEach(d=>{const u=c[d];u&&iie(u)&&(a=u.body.start-o,i=u.body.end+o,t>=a&&t<=i&&(r=Math.min(t-a,i-t),l<=r&&(n=u.body,l=r)))}),n}isEndListAppended(t){const n=this.endListFragments[t];return n!==void 0&&(n.buffered||iie(n))}getState(t){const n=y9(t),r=this.fragments[n];return r?r.buffered?iie(r)?ep.PARTIAL:ep.OK:ep.APPENDING:ep.NOT_LOADED}isTimeBuffered(t,n,r){let a,i;for(let l=0;l=a&&n<=i)return!0;if(n<=a)return!1}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(t,n){if(!Lp(n.frag)||n.frag.bitrateTest)return;const r=n.frag,a=n.part?null:n,i=y9(r);this.fragments[i]={body:r,appendedPTS:null,loaded:a,buffered:!1,range:Object.create(null)}}onBufferAppended(t,n){const{frag:r,part:a,timeRanges:i}=n;if(!Lp(r))return;const l=r.type;if(a){let o=this.activePartLists[l];o||(this.activePartLists[l]=o=[]),o.push(a)}this.timeRanges=i}onFragBuffered(t,n){this.detectPartialFragments(n)}hasFragment(t){const n=y9(t);return!!this.fragments[n]}hasFragments(t){const{fragments:n}=this,r=Object.keys(n);if(!t)return r.length>0;for(let a=r.length;a--;){const i=n[r[a]];if((i==null?void 0:i.body.type)===t)return!0}return!1}hasParts(t){var n;return!!((n=this.activePartLists[t])!=null&&n.length)}getBackBufferEvictionEnd(t,n,r){const{fragments:a}=this;let i=0,l=0;const o=Object.keys(a);for(let c=0;c=r))return l}return l>0?l:0}removeFragmentsInRange(t,n,r,a,i){a&&!this.hasGaps||Object.keys(this.fragments).forEach(l=>{const o=this.fragments[l];if(!o)return;const c=o.body;c.type!==r||a&&!c.gap||c.startt&&(o.buffered||i)&&this.removeFragment(c)})}removeFragment(t){const n=y9(t);t.clearElementaryStreamInfo();const r=this.activePartLists[t.type];if(r){const a=t.sn;this.activePartLists[t.type]=o_t(r,i=>i.fragment.sn!==a)}delete this.fragments[n],t.endList&&delete this.endListFragments[t.type]}removeAllFragments(){var t;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1;const n=(t=this.hls)==null||(t=t.latestLevelDetails)==null?void 0:t.partList;n&&n.forEach(r=>r.clearElementaryStreamInfo())}}function iie(s){var t,n,r,a;return s.buffered&&!!(s.body.gap||(t=s.range.video)!=null&&t.partial||(n=s.range.audio)!=null&&n.partial||(r=s.range.audiovideo)!=null&&r.partial||(a=s.range.subs)!=null&&a.partial)}function y9(s){return`${s.type}_${s.level}_${s.sn}`}function o_t(s,t){return s.filter(n=>{const r=t(n);return r||n.clearElementaryStreamInfo(),r})}var BM={cbc:0,ctr:1};class Kzn{constructor(t,n,r){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=t,this.aesIV=n,this.aesMode=r}decrypt(t,n){switch(this.aesMode){case BM.cbc:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},n,t);case BM.ctr:return this.subtle.decrypt({name:"AES-CTR",counter:this.aesIV,length:64},n,t);default:throw new Error(`[AESCrypto] invalid aes mode ${this.aesMode}`)}}}function Yzn(s){const t=s.byteLength,n=t&&new DataView(s.buffer).getUint8(t-1);return n?s.slice(0,t-n):s}class Zzn{constructor(){this.rcon=[0,1,2,4,8,16,32,64,128,27,54],this.subMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.invSubMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.sBox=new Uint32Array(256),this.invSBox=new Uint32Array(256),this.key=new Uint32Array(0),this.ksRows=0,this.keySize=0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.initTable()}uint8ArrayToUint32Array_(t){const n=new DataView(t),r=new Uint32Array(4);for(let a=0;a<4;a++)r[a]=n.getUint32(a*4);return r}initTable(){const t=this.sBox,n=this.invSBox,r=this.subMix,a=r[0],i=r[1],l=r[2],o=r[3],c=this.invSubMix,d=c[0],u=c[1],h=c[2],m=c[3],p=new Uint32Array(256);let g=0,x=0,y=0;for(y=0;y<256;y++)y<128?p[y]=y<<1:p[y]=y<<1^283;for(y=0;y<256;y++){let v=x^x<<1^x<<2^x<<3^x<<4;v=v>>>8^v&255^99,t[g]=v,n[v]=g;const _=p[g],j=p[_],C=p[j];let A=p[v]*257^v*16843008;a[g]=A<<24|A>>>8,i[g]=A<<16|A>>>16,l[g]=A<<8|A>>>24,o[g]=A,A=C*16843009^j*65537^_*257^g*16843008,d[v]=A<<24|A>>>8,u[v]=A<<16|A>>>16,h[v]=A<<8|A>>>24,m[v]=A,g?(g=_^p[p[p[C^_]]],x^=p[p[x]]):g=x=1}}expandKey(t){const n=this.uint8ArrayToUint32Array_(t);let r=!0,a=0;for(;a=r.length?r:r.slice(a.start,a.end):Yzn(r)}reset(){this.currentResult=null,this.currentIV=null,this.remainderData=null,this.softwareDecrypter&&(this.softwareDecrypter=null)}decrypt(t,n,r,a,i){return this.decryptRange=i,this.useSoftware||i?new Promise((l,o)=>{const c=ArrayBuffer.isView(t)?t:new Uint8Array(t);this.softwareDecrypt(c,n,r,a);const d=this.flush();d?l(d.buffer):o(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(t),n,r,a)}softwareDecrypt(t,n,r,a){const{currentIV:i,currentResult:l,remainderData:o}=this;if(a!==BM.cbc||n.byteLength!==16)return ku.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),o&&(t=z2(o,t),this.remainderData=null);const c=this.getValidChunk(t);if(!c.length)return null;i&&(r=i);let d=this.softwareDecrypter;d||(d=this.softwareDecrypter=new Zzn),d.expandKey(n);const u=l;return this.currentResult=d.decrypt(c.buffer,0,r),this.currentIV=c.slice(-16).buffer,u||null}webCryptoDecrypt(t,n,r,a){if(this.key!==n||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(t,n,r,a));this.key=n,this.fastAesKey=new Xzn(this.subtle,n,a)}return this.fastAesKey.expandKey().then(i=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new Kzn(this.subtle,new Uint8Array(r),a).decrypt(t.buffer,i)):Promise.reject(new Error("web crypto not initialized"))).catch(i=>(ku.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${i.name}: ${i.message}`),this.onWebCryptoError(t,n,r,a)))}onWebCryptoError(t,n,r,a){const i=this.enableSoftwareAES;if(i){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(t,n,r,a);const l=this.flush();if(l)return l.buffer}throw new Error("WebCrypto"+(i?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(t){let n=t;const r=t.length-t.length%Jzn;return r!==t.length&&(n=t.slice(0,r),this.remainderData=t.slice(r)),n}logOnce(t){this.logEnabled&&(ku.log(`[decrypter]: ${t}`),this.logEnabled=!1)}}const l_t=Math.pow(2,17);class c_t{constructor(t){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=t}destroy(){this.loader&&(this.loader.destroy(),this.loader=null)}abort(){this.loader&&this.loader.abort()}load(t,n,r,a){const i=t.url;if(!i)return Promise.reject(new LS({type:xo.NETWORK_ERROR,details:er.FRAG_LOAD_ERROR,fatal:!1,frag:t,error:new Error(`Fragment does not have a ${i?"part list":"url"}`),networkDetails:null}));this.abort();const l=this.config,o=l.fLoader,c=l.loader;return new Promise((d,u)=>{if(this.loader&&this.loader.destroy(),t.gap)if(t.tagList.some(y=>y[0]==="GAP")){u(u_t(t));return}else t.gap=!1;const h=this.loader=o?new o(l):new c(l),m=d_t(t,null,n);t.loader=h;const p=Hbt(l.fragLoadPolicy.default),g={loadPolicy:p,timeout:p.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:t.sn==="initSegment"?1/0:l_t};h.stats.retry=t.stats.retry,t.stats=h.stats;const x={onSuccess:(y,v,_,j)=>{this.resetLoader(t,h);let C=y.data;_.resetIV&&t.decryptdata&&(t.decryptdata.iv=new Uint8Array(C.slice(0,16)),C=C.slice(16)),d({frag:t,part:null,payload:C,networkDetails:j})},onError:(y,v,_,j)=>{this.resetLoader(t,h),u(new LS({type:xo.NETWORK_ERROR,details:er.FRAG_LOAD_ERROR,fatal:!1,frag:t,response:wo({url:i,data:void 0},y),error:new Error(`HTTP Error ${y.code} ${y.text}`),networkDetails:_,stats:j}))},onAbort:(y,v,_)=>{this.resetLoader(t,h),u(new LS({type:xo.NETWORK_ERROR,details:er.INTERNAL_ABORTED,fatal:!1,frag:t,error:new Error("Aborted"),networkDetails:_,stats:y}))},onTimeout:(y,v,_)=>{this.resetLoader(t,h),u(new LS({type:xo.NETWORK_ERROR,details:er.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,error:new Error(`Timeout after ${g.timeout}ms`),networkDetails:_,stats:y}))}};if(r){const y=this.gateProgress(r,a);x.onProgress=(v,_,j,C)=>y({frag:t,part:null,payload:j,networkDetails:C})}h.load(m,g,x)})}gateProgress(t,n){let r=t;if(n){const a=[];let i=!1;n.then(()=>{i=!0,a.forEach(l=>t(l)),a.length=0}).catch(()=>{}),r=l=>{i?t(l):a.push(l)}}return r}loadPart(t,n,r){this.abort();const a=this.config,i=a.fLoader,l=a.loader;return new Promise((o,c)=>{if(this.loader&&this.loader.destroy(),t.gap||n.gap){c(u_t(t,n));return}const d=this.loader=i?new i(a):new l(a),u=d_t(t,n);t.loader=d;const h=Hbt(a.fragLoadPolicy.default),m={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:l_t};n.stats=d.stats,d.load(u,m,{onSuccess:(p,g,x,y)=>{this.resetLoader(t,d),this.updateStatsFromPart(t,n);const v={frag:t,part:n,payload:p.data,networkDetails:y};r(v),o(v)},onError:(p,g,x,y)=>{this.resetLoader(t,d),c(new LS({type:xo.NETWORK_ERROR,details:er.FRAG_LOAD_ERROR,fatal:!1,frag:t,part:n,response:wo({url:u.url,data:void 0},p),error:new Error(`HTTP Error ${p.code} ${p.text}`),networkDetails:x,stats:y}))},onAbort:(p,g,x)=>{t.stats.aborted=n.stats.aborted,this.resetLoader(t,d),c(new LS({type:xo.NETWORK_ERROR,details:er.INTERNAL_ABORTED,fatal:!1,frag:t,part:n,error:new Error("Aborted"),networkDetails:x,stats:p}))},onTimeout:(p,g,x)=>{this.resetLoader(t,d),c(new LS({type:xo.NETWORK_ERROR,details:er.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,part:n,error:new Error(`Timeout after ${m.timeout}ms`),networkDetails:x,stats:p}))}})})}updateStatsFromPart(t,n){const r=t.stats,a=n.stats,i=a.total;if(r.loaded+=a.loaded,i){const c=Math.round(t.duration/n.duration),d=Math.min(Math.round(r.loaded/i),c),h=(c-d)*Math.round(r.loaded/d);r.total=r.loaded+h}else r.total=Math.max(r.loaded,r.total);const l=r.loading,o=a.loading;l.start?l.first+=o.first-o.start:(l.start=o.start,l.first=o.first),l.end=o.end}resetLoader(t,n){t.loader=null,t.url=null,this.loader===n&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),n.destroy()}}function d_t(s,t=null,n){const r=t||s,a={type:Mc.MEDIA_FRAGMENT,frag:s,part:t,responseType:"arraybuffer",url:r.url,headers:{},rangeStart:0,rangeEnd:0},i=iCe(s,t,n);return i.resetIV&&(a.resetIV=!0),i.byteRange&&(a.rangeStart=i.byteRange.start,a.rangeEnd=i.byteRange.end),a}function iCe(s,t=null,n){const r={},a=t||s,i=a.byteRangeStartOffset,l=a.byteRangeEndOffset;if(mi(i)&&mi(l)){var o;if((s.sn==="initSegment"||n)&&eBn((o=s.decryptdata)==null?void 0:o.method)){let c=Math.floor(i/16)*16;const d=Math.ceil(l/16)*16;r.decryptRange={start:i-c,end:l-c},c>=16&&(r.resetIV=!0,c=c-16),r.byteRange={start:c,end:d}}else r.byteRange={start:i,end:l}}return r}function u_t(s,t){const n=new Error(`GAP ${s.gap?"tag":"attribute"} found`),r={type:xo.MEDIA_ERROR,details:er.FRAG_GAP,fatal:!1,frag:s,error:n,networkDetails:null};return t&&(r.part=t),(t||s).stats.aborted=!0,new LS(r)}function eBn(s){return s==="AES-128"||s==="AES-256"}class LS extends Error{constructor(t){super(t.error.message),this.data=void 0,this.data=t}}class $Ht extends wj{constructor(t,n){super(t,n),this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}destroy(){this.onHandlerDestroying(),this.onHandlerDestroyed()}onHandlerDestroying(){this.clearNextTick(),this.clearInterval()}onHandlerDestroyed(){}hasInterval(){return!!this._tickInterval}hasNextTick(){return!!this._tickTimer}setInterval(t){return this._tickInterval?!1:(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,t),!0)}clearInterval(){return this._tickInterval?(self.clearInterval(this._tickInterval),this._tickInterval=null,!0):!1}clearNextTick(){return this._tickTimer?(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0):!1}tick(){this._tickCallCount++,this._tickCallCount===1?(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0):(this.log(`possible exception thrown in task-loop (${this.constructor.name}.doTick)`),this._tickCallCount=0)}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}}class DQe{constructor(t,n,r,a=0,i=-1,l=!1,o,c,d){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.iframe=void 0,this.duration=void 0,this.decryptRange=void 0,this.transmuxing=oie(),this.buffering={audio:oie(),video:oie(),audiovideo:oie()},this.level=t,this.sn=n,this.id=r,this.size=a,this.part=i,this.partial=l,this.duration=o||0,this.decryptRange=d,this.iframe=c||!1}}function oie(){return{start:0,executeStart:0,executeEnd:0,end:0}}const h_t={length:0,start:()=>0,end:()=>0};class pl{static isBuffered(t,n){if(t){const r=pl.getBuffered(t);for(let a=r.length;a--;)if(n>=r.start(a)&&n<=r.end(a))return!0}return!1}static bufferedRanges(t){if(t){const n=pl.getBuffered(t);return pl.timeRangesToArray(n)}return[]}static timeRangesToArray(t){const n=[];for(let r=0;r1&&t.sort((u,h)=>u.start-h.start||h.end-u.end);let a=-1,i=[];if(r)for(let u=0;u=t[u].start&&n<=t[u].end&&(a=u);const h=i.length;if(h){const m=i[h-1].end;t[u].start-mm&&(i[h-1].end=t[u].end):i.push(t[u])}else i.push(t[u])}else i=t;let l=0,o,c=n,d=n;for(let u=0;u=h&&n<=m&&(a=u),n+r>=h&&n{const a=r.substring(2,r.length-1),i=n==null?void 0:n[a];return i===void 0?(s.playlistParsingError||(s.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${a}"`)),r):i})}return t}function f_t(s,t,n){let r=s.variableList;r||(s.variableList=r={});let a,i;if("QUERYPARAM"in t){a=t.QUERYPARAM;try{const l=new self.URL(n).searchParams;if(l.has(a))i=l.get(a);else throw new Error(`"${a}" does not match any query parameter in URI: "${n}"`)}catch(l){s.playlistParsingError||(s.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${l.message}`))}}else a=t.NAME,i=t.VALUE;a in r?s.playlistParsingError||(s.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${a}"`)):r[a]=i||""}function tBn(s,t,n){const r=t.IMPORT;if(n&&r in n){let a=s.variableList;a||(s.variableList=a={}),a[r]=n[r]}else s.playlistParsingError||(s.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${r}"`))}const sBn=/^(\d+)x(\d+)$/,p_t=/(.+?)=(".*?"|.*?)(?:,|$)/g;class Yf{constructor(t,n){typeof t=="string"&&(t=Yf.parseAttrList(t,n)),wh(this,t)}get clientAttrs(){return Object.keys(this).filter(t=>t.substring(0,2)==="X-")}decimalInteger(t){const n=parseInt(this[t],10);return n>Number.MAX_SAFE_INTEGER?1/0:n}hexadecimalInteger(t){if(this[t]){let n=(this[t]||"0x").slice(2);n=(n.length&1?"0":"")+n;const r=new Uint8Array(n.length/2);for(let a=0;aNumber.MAX_SAFE_INTEGER?1/0:n}decimalFloatingPoint(t){return parseFloat(this[t])}optionalFloat(t,n){const r=this[t];return r?parseFloat(r):n}enumeratedString(t){return this[t]}enumeratedStringList(t,n){const r=this[t];return(r?r.split(/[ ,]+/):[]).reduce((a,i)=>(a[i.toLowerCase()]=!0,a),n)}bool(t){return this[t]==="YES"}decimalResolution(t){const n=sBn.exec(this[t]);if(n!==null)return{width:parseInt(n[1],10),height:parseInt(n[2],10)}}static parseAttrList(t,n){let r;const a={},i='"';for(p_t.lastIndex=0;(r=p_t.exec(t))!==null;){const l=r[1].trim();let o=r[2];const c=o.indexOf(i)===0&&o.lastIndexOf(i)===o.length-1;let d=!1;if(c)o=o.slice(1,-1);else switch(l){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":d=!0}if(n&&(c||d))o=OQe(n,o);else if(!d&&!c)switch(l){case"CLOSED-CAPTIONS":if(o==="NONE")break;case"ALLOWED-CPC":case"CLASS":case"ASSOC-LANGUAGE":case"AUDIO":case"BYTERANGE":case"CHANNELS":case"CHARACTERISTICS":case"CODECS":case"DATA-ID":case"END-DATE":case"GROUP-ID":case"ID":case"IMPORT":case"INSTREAM-ID":case"KEYFORMAT":case"KEYFORMATVERSIONS":case"LANGUAGE":case"NAME":case"PATHWAY-ID":case"QUERYPARAM":case"RECENTLY-REMOVED-DATERANGES":case"SERVER-URI":case"STABLE-RENDITION-ID":case"STABLE-VARIANT-ID":case"START-DATE":case"SUBTITLES":case"SUPPLEMENTAL-CODECS":case"URI":case"VALUE":case"VIDEO":case"X-ASSET-LIST":case"X-ASSET-URI":ku.warn(`${t}: attribute ${l} is missing quotes`)}a[l]=o}return a}}const nBn="com.apple.hls.interstitial";function rBn(s){return s!=="ID"&&s!=="CLASS"&&s!=="CUE"&&s!=="START-DATE"&&s!=="DURATION"&&s!=="END-DATE"&&s!=="END-ON-NEXT"}function aBn(s){return s==="SCTE35-OUT"||s==="SCTE35-IN"||s==="SCTE35-CMD"}class qHt{constructor(t,n,r=0){var a;if(this.attr=void 0,this.tagAnchor=void 0,this.tagOrder=void 0,this._startDate=void 0,this._endDate=void 0,this._dateAtEnd=void 0,this._cue=void 0,this._badValueForSameId=void 0,this.tagAnchor=(n==null?void 0:n.tagAnchor)||null,this.tagOrder=(a=n==null?void 0:n.tagOrder)!=null?a:r,n){const i=n.attr;for(const l in i)if(Object.prototype.hasOwnProperty.call(t,l)&&t[l]!==i[l]){ku.warn(`DATERANGE tag attribute: "${l}" does not match for tags with ID: "${t.ID}"`),this._badValueForSameId=l;break}t=wh(new Yf({}),i,t)}if(this.attr=t,n?(this._startDate=n._startDate,this._cue=n._cue,this._endDate=n._endDate,this._dateAtEnd=n._dateAtEnd):this._startDate=new Date(t["START-DATE"]),"END-DATE"in t){const i=(n==null?void 0:n.endDate)||new Date(t["END-DATE"]);mi(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?(ku.warn(`Expected tagAnchor Fragment with PDT set for DateRange "${this.id}": ${t}`),NaN):t.start+(this.startDate.getTime()-t.programDateTime)/1e3}get startDate(){return this._startDate}get endDate(){const t=this._endDate||this._dateAtEnd;if(t)return t;const n=this.duration;return n!==null?this._dateAtEnd=new Date(this._startDate.getTime()+n*1e3):null}get duration(){if("DURATION"in this.attr){const t=this.attr.decimalFloatingPoint("DURATION");if(mi(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===nBn}get isValid(){return!!this.id&&!this._badValueForSameId&&mi(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)}get invalidReason(){return this.id?this._badValueForSameId?`Date range ${this._badValueForSameId} mismatch`:mi(this.startDate.getTime())?this.isInterstitial&&!("X-ASSET-URI"in this.attr||"X-ASSET-LIST"in this.attr)?"Interstitial Date range missing X-ASSET-(LIST|URI)":this.isValid?null:"Unknown (check DURATION(|END|NEXT), CLASS, and CUE)":"Date range invalid start date":"Missing ID"}}const VHt=10;class iBn{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.iframesOnly=!1,this.requestScheduled=-1,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.appliedTimelineOffset=void 0,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=t}reloaded(t){if(!t){this.advanced=!0,this.updated=!0;return}const n=this.lastPartSn-t.lastPartSn,r=this.lastPartIndex-t.lastPartIndex;this.updated=this.endSN!==t.endSN||!!r||!!n||!this.live,this.advanced=this.endSN>t.endSN||n>0||n===0&&r>0,this.updated||this.advanced?this.misses=0:this.misses=t.misses+1}hasKey(t){return this.encryptedFragments.some(n=>{let r=n.decryptdata;return r||(n.setKeyFormat(t.keyFormat),r=n.decryptdata),!!r&&t.matches(r)})}get hasProgramDateTime(){return this.fragments.length?mi(this.fragments[this.fragments.length-1].programDateTime):!1}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||VHt}get drift(){const t=this.driftEndTime-this.driftStartTime;return t>0?(this.driftEnd-this.driftStart)*1e3/t:1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var t;return(t=this.partList)!=null&&t.length?this.partList[this.partList.length-1].end:this.fragmentEnd}get fragmentEnd(){return this.fragments.length?this.fragments[this.fragments.length-1].end:0}get fragmentStart(){return this.fragments.length?this.fragments[0].start:0}get age(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}get lastPartIndex(){var t;return(t=this.partList)!=null&&t.length?this.partList[this.partList.length-1].index:-1}get maxPartIndex(){const t=this.partList;if(t){const n=this.lastPartIndex;if(n!==-1){for(let r=t.length;r--;)if(t[r].index>n)return t[r].index;return n}}return 0}get lastPartSn(){var t;return(t=this.partList)!=null&&t.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}get expired(){if(this.live&&this.age&&this.misses<3){const t=this.partEnd-this.fragmentStart;return this.age>Math.max(t,this.totalduration)+this.levelTargetDuration}return!1}}function oCe(s,t){return s.length===t.length?!s.some((n,r)=>n!==t[r]):!1}function g_t(s,t){return!s&&!t?!0:!s||!t?!1:oCe(s,t)}function VB(s){return s==="AES-128"||s==="AES-256"||s==="AES-256-CTR"}function FQe(s){switch(s){case"AES-128":case"AES-256":return BM.cbc;case"AES-256-CTR":return BM.ctr;default:throw new Error(`invalid full segment method ${s}`)}}function uqe(s){return Uint8Array.from(unescape(encodeURIComponent(s)),t=>t.charCodeAt(0))}function oBn(s){const t=uqe(s).subarray(0,16),n=new Uint8Array(16);return n.set(t,16-t.length),n}function HHt(s){const t=function(r,a,i){const l=r[a];r[a]=r[i],r[i]=l};t(s,0,3),t(s,1,2),t(s,4,5),t(s,6,7)}function GHt(s){const t=s.split(":");let n=null;if(t[0]==="data"&&t.length===2){const r=t[1].split(";"),a=r[r.length-1].split(",");if(a.length===2){const i=a[0]==="base64",l=a[1];i?(r.splice(-1,1),n=PQe(l)):n=oBn(l)}}return n}const lCe=typeof self<"u"?self:void 0;var bf={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},ev={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function lie(s){switch(s){case ev.FAIRPLAY:return bf.FAIRPLAY;case ev.PLAYREADY:return bf.PLAYREADY;case ev.WIDEVINE:return bf.WIDEVINE;case ev.CLEARKEY:return bf.CLEARKEY}}var WHt={WIDEVINE:"edef8ba979d64acea3c827dcd51d21ed"};function p8e(s){switch(s){case bf.FAIRPLAY:return ev.FAIRPLAY;case bf.PLAYREADY:return ev.PLAYREADY;case bf.WIDEVINE:return ev.WIDEVINE;case bf.CLEARKEY:return ev.CLEARKEY}}function YG(s){const{drmSystems:t,widevineLicenseUrl:n}=s,r=t?[bf.FAIRPLAY,bf.WIDEVINE,bf.PLAYREADY,bf.CLEARKEY].filter(a=>!!t[a]):[];return!r[bf.WIDEVINE]&&n&&r.push(bf.WIDEVINE),r}const KHt=function(s){return lCe!=null&&(s=lCe.navigator)!=null&&s.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null}();function lBn(s,t,n,r){let a;switch(s){case bf.FAIRPLAY:a=["cenc","sinf"];break;case bf.WIDEVINE:case bf.PLAYREADY:a=["cenc"];break;case bf.CLEARKEY:a=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${s}`)}return cBn(a,t,n,r)}function cBn(s,t,n,r){return[{initDataTypes:s,persistentState:r.persistentState||"optional",distinctiveIdentifier:r.distinctiveIdentifier||"optional",sessionTypes:r.sessionTypes||[r.sessionType||"temporary"],audioCapabilities:t.map(i=>({contentType:`audio/mp4; codecs=${i}`,robustness:r.audioRobustness||"",encryptionScheme:r.audioEncryptionScheme||null})),videoCapabilities:n.map(i=>({contentType:`video/mp4; codecs=${i}`,robustness:r.videoRobustness||"",encryptionScheme:r.videoEncryptionScheme||null}))}]}function dBn(s){var t;return!!s&&(s.sessionType==="persistent-license"||!!((t=s.sessionTypes)!=null&&t.some(n=>n==="persistent-license")))}function zQe(s){const t=new Uint16Array(s.buffer,s.byteOffset,s.byteLength/2),n=pk(t),r=n.substring(n.indexOf("<"),n.length),l=new DOMParser().parseFromString(r,"text/xml").getElementsByTagName("KID")[0];if(l){const o=l.childNodes[0]?l.childNodes[0].nodeValue:l.getAttribute("VALUE");if(o){const c=PQe(o).subarray(0,16);return HHt(c),c}}return null}let v9={};class M3{static clearKeyUriToKeyIdMap(){v9={}}static setKeyIdForUri(t,n){v9[t]=n}static addKeyIdForUri(t){const n=Object.keys(v9).length%Number.MAX_SAFE_INTEGER,r=new Uint8Array(16);return new DataView(r.buffer,12,4).setUint32(0,n),v9[t]=r,r}constructor(t,n,r,a=[1],i=null,l){this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.scheme=void 0,this.method=t,this.uri=n,this.keyFormat=r,this.keyFormatVersions=a,this.iv=i,this.encrypted=t?t!=="NONE":!1,this.isCommonEncryption=this.encrypted&&!VB(t),l!=null&&l.startsWith("0x")&&(this.keyId=new Uint8Array(gHt(l)))}matches(t){return t.uri===this.uri&&t.method===this.method&&t.encrypted===this.encrypted&&t.keyFormat===this.keyFormat&&oCe(t.keyFormatVersions,this.keyFormatVersions)&&g_t(t.iv,this.iv)&&g_t(t.keyId,this.keyId)}isSupported(){if(this.method){if(VB(this.method)||this.method==="NONE")return!0;if(this.keyFormat==="identity")return this.method==="SAMPLE-AES";switch(this.keyFormat){case ev.FAIRPLAY:case ev.WIDEVINE:case ev.PLAYREADY:case ev.CLEARKEY:return["SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)!==-1}}return!1}getDecryptData(t,n){var r;if(!this.encrypted||!this.uri)return null;if(VB(this.method)){let l=this.iv;return l||(typeof t!="number"&&(ku.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),t=0),l=hBn(t)),new M3(this.method,this.uri,"identity",this.keyFormatVersions,l)}if(this.keyId){const l=v9[this.uri];if(l&&!oCe(this.keyId,l)&&M3.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}const a=GHt(this.uri);if(a)switch(this.keyFormat){case ev.WIDEVINE:if(this.pssh=a,!this.keyId){const l=CHt(a.buffer).filter(o=>o.systemId===WHt.WIDEVINE);if(l.length){var i;const o=l[0];this.keyId=(i=o.kids)!=null&&i.length?o.kids[0]:null}}this.keyId||(this.keyId=x_t(n));break;case ev.PLAYREADY:{const l=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=mzn(l,null,a),this.keyId=zQe(a);break}default:{let l=a.subarray(0,16);if(l.length!==16){const o=new Uint8Array(16);o.set(l,16-l.length),l=o}this.keyId=l;break}}if(((r=this.keyId)==null?void 0:r.byteLength)!==16){let l;l=uBn(n),l||(l=x_t(n),l||(l=v9[this.uri])),l&&(this.keyId=l,M3.setKeyIdForUri(this.uri,l))}return this}}function uBn(s){const t=s==null?void 0:s[ev.WIDEVINE];return t?t.keyId:null}function x_t(s){const t=s==null?void 0:s[ev.PLAYREADY];if(t){const n=GHt(t.uri);if(n)return zQe(n)}return null}function hBn(s){const t=new Uint8Array(16);for(let n=12;n<16;n++)t[n]=s>>8*(15-n)&255;return t}const y_t=/#EXT-X-STREAM-INF:([^\r\n]*)(?:[\r\n](?:#[^\r\n]*)?)*([^\r\n]+)|#EXT-X-(I-FRAME-STREAM-INF|SESSION-DATA|SESSION-KEY|DEFINE|CONTENT-STEERING|START):([^\r\n]*)(?:[\r\n]+|$)/g,v_t=/#EXT-X-MEDIA:(.*)/g,mBn=/^#EXT(?:INF|-X-TARGETDURATION):/m,g8e=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),fBn=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|I-FRAMES-ONLY)/.source,/(#)([^:]*):(.*)/.source,/(#)(.*)(?:.*)\r?\n?/.source].join("|"));class _5{static findGroup(t,n){for(let r=0;r0&&i.length({id:d.attrs.AUDIO,audioCodec:d.audioCodec})),SUBTITLES:l.map(d=>({id:d.attrs.SUBTITLES,textCodec:d.textCodec})),"CLOSED-CAPTIONS":[]};let c=0;for(v_t.lastIndex=0;(a=v_t.exec(t))!==null;){const d=new Yf(a[1],r),u=d.TYPE;if(u){const h=o[u],m=i[u]||[];i[u]=m;const p=d.LANGUAGE,g=d["ASSOC-LANGUAGE"],x=d.CHANNELS,y=d.CHARACTERISTICS,v=d["INSTREAM-ID"],_={attrs:d,bitrate:0,id:c++,groupId:d["GROUP-ID"]||"",name:d.NAME||p||"",type:u,default:d.bool("DEFAULT"),autoselect:d.bool("AUTOSELECT"),forced:d.bool("FORCED"),lang:p,url:d.URI?_5.resolve(d.URI,n):""};if(g&&(_.assocLang=g),x&&(_.channels=x),y&&(_.characteristics=y),v&&(_.instreamId=v),h!=null&&h.length){const j=_5.findGroup(h,_.groupId)||h[0];N_t(_,j,"audioCodec"),N_t(_,j,"textCodec")}m.push(_)}}return i}static parseLevelPlaylist(t,n,r,a,i,l){var o;const c={url:n},d=new iBn(n),u=d.fragments,h=[];let m=null,p=0,g=0,x=0,y=0,v=0,_=null,j=new tie(a,c),C,A,M,I=-1,P=!1,R=null,O;if(g8e.lastIndex=0,d.m3u8=t,d.hasVariableRefs=m_t(t),((o=g8e.exec(t))==null?void 0:o[0])!=="#EXTM3U")return d.playlistParsingError=new Error("Missing format identifier #EXTM3U"),d;for(;(C=g8e.exec(t))!==null;){P&&(P=!1,j=new tie(a,c),j.playlistOffset=x,j.setStart(x),j.sn=p,j.cc=y,v&&(j.bitrate=v),j.level=r,m&&(j.initSegment=m,m.rawProgramDateTime&&(j.rawProgramDateTime=m.rawProgramDateTime,m.rawProgramDateTime=null),R&&(j.setByteRange(R),R=null)));const Y=C[1];if(Y){j.duration=parseFloat(Y);const se=(" "+C[2]).slice(1);j.title=se||null,j.tagList.push(se?["INF",Y,se]:["INF",Y])}else if(C[3]){if(mi(j.duration)){var B;j.playlistOffset=x,j.setStart(x),M&&S_t(j,M,d),j.sn=p,j.level=r,j.cc=y;const se=(" "+C[3]).slice(1);j.relurl=OQe(d,se),hqe(j,_,h),_=j,x+=j.duration,p++,g=0;const ee=j.byteRange;if(ee.length===2&&(j.bitrate=(ee[1]-ee[0])*8/j.duration|0),d.iframesOnly&&ee[0]&&((B=m)==null?void 0:B.cc)!==y){const oe=new tie(a,c);oe.relurl=j.relurl,oe.setByteRange(`${Math.min(ee[0],7*188)}@0`),oe.level=r,oe.sn="initSegment",M&&(oe.levelkeys=M,M.identity&&(oe._decryptdata=M.identity.getDecryptData(0))),m=oe,j.initSegment=m}u.push(j),P=!0}}else{if(C=C[0].match(fBn),!C){ku.warn("No matches on slow regex match for level playlist!");continue}for(A=1;Ame&&(me.cc=y));break;case"KEY":{const me=__t(ee,n,d);if(me.isSupported()){if(me.method==="NONE"){M=void 0;break}M||(M={});const Q=M[me.keyFormat];Q!=null&&Q.matches(me)||(Q&&(M=wh({},M)),M[me.keyFormat]=me)}else ku.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${ee}"`);break}case"START":d.startTimeOffset=w_t(ee);break;case"MAP":{const me=new Yf(ee,d);if(j.duration){const Q=new tie(a,c);k_t(Q,me,r,M),m=Q,j.initSegment=m,m.rawProgramDateTime&&!j.rawProgramDateTime&&(j.rawProgramDateTime=m.rawProgramDateTime)}else{const Q=j.byteRangeEndOffset;if(Q){const te=j.byteRangeStartOffset;R=`${Q-te}@${te}`}else R=null;k_t(j,me,r,M),m=j,P=!0}m.cc=y;break}case"SERVER-CONTROL":{O&&sC(d,se,C),O=new Yf(ee),d.canBlockReload=O.bool("CAN-BLOCK-RELOAD"),d.canSkipUntil=O.optionalFloat("CAN-SKIP-UNTIL",0),d.canSkipDateRanges=d.canSkipUntil>0&&O.bool("CAN-SKIP-DATERANGES"),d.partHoldBack=O.optionalFloat("PART-HOLD-BACK",0),d.holdBack=O.optionalFloat("HOLD-BACK",0);break}case"PART-INF":{d.partTarget&&sC(d,se,C);const me=new Yf(ee);d.partTarget=me.decimalFloatingPoint("PART-TARGET");break}case"PART":{let me=d.partList;me||(me=d.partList=[]);const Q=g>0?me[me.length-1]:void 0,te=g++,le=new Yf(ee,d),fe=new _9n(le,j,c,te,Q);me.push(fe),j.duration+=fe.duration;break}case"PRELOAD-HINT":{const me=new Yf(ee,d);d.preloadHint=me;break}case"RENDITION-REPORT":{const me=new Yf(ee,d);d.renditionReports=d.renditionReports||[],d.renditionReports.push(me);break}default:ku.warn(`line parsed but not handled: ${C}`);break}}}_&&!_.relurl?(u.pop(),x-=_.duration,d.partList&&(d.fragmentHint=_)):d.partList&&(hqe(j,_,h),j.cc=y,d.fragmentHint=j,M&&S_t(j,M,d)),d.targetduration||(d.playlistParsingError=new Error("Missing Target Duration"));const U=u.length,G=u[0],H=u[U-1];if(x+=d.skippedSegments*d.targetduration,x>0&&U&&H){d.averagetargetduration=x/U;const Y=H.sn;d.endSN=Y!=="initSegment"?Y:0,d.live||(H.endList=!0),I>0&&(gBn(u,I,I>U-1?j:null),G&&h.unshift(G))}return d.fragmentHint&&(x+=d.fragmentHint.duration),d.totalduration=x,h.length&&d.dateRangeTagCount&&G&&YHt(h,d),d.endCC=y,d}}function b_t(s,t,n,r,a,i){var l;if(t===void 0)return null;const o=OQe(r,t),c={attrs:s,bitrate:s.decimalInteger("BANDWIDTH")||s.decimalInteger("AVERAGE-BANDWIDTH"),name:s.NAME,url:_5.resolve(o,n)},d=s.decimalResolution("RESOLUTION");d&&(c.width=d.width,c.height=d.height),j_t(s.CODECS,c);const u=s["SUPPLEMENTAL-CODECS"];return u&&(c.supplemental={},j_t(u,c.supplemental)),(l=c.unknownCodecs)!=null&&l.length||a.push(c),i&&(c.iframes=!0),c}function YHt(s,t){let n=s.length;if(!n)if(t.hasProgramDateTime){const o=t.fragments[t.fragments.length-1];s.push(o),n++}else return;const r=s[n-1],a=t.live?1/0:t.totalduration,i=Object.keys(t.dateRanges);for(let o=i.length;o--;){const c=t.dateRanges[i[o]],d=c.startDate.getTime();c.tagAnchor=r.ref;for(let u=n;u--;){var l;if(((l=s[u])==null?void 0:l.sn)=o||r===0){var l;const c=(((l=n[r+1])==null?void 0:l.start)||a)-i.start;if(t<=o+c*1e3){const d=i.sn-s.startSN,u=s.fragments;if(d>=0&&dn.length){const h=n[r+1]||u[u.length-1],m=Math.min(h.sn-s.startSN,u.length-1);for(let p=m;p>d;p--){const g=u[p].programDateTime;if(t>=g&&tr);["video","audio","text","image"].forEach(r=>{const a=n.filter(i=>IQe(i,r));a.length&&(t[`${r}Codec`]=a.map(i=>i.split("/")[0]).join(","),n=n.filter(i=>a.indexOf(i)===-1))}),t.unknownCodecs=n}function N_t(s,t,n){const r=t[n];r&&(s[n]=r)}function gBn(s,t,n){if(n||(n=s[t]),!!n)for(let r=t;r--;){const a=s[r];if(!a)return;a.programDateTime=n.programDateTime-a.duration*1e3,n=a}}function hqe(s,t,n){s.rawProgramDateTime?n.push(s):t!=null&&t.programDateTime&&(s.programDateTime=t.endProgramDateTime)}function k_t(s,t,n,r){s.relurl=t.URI,t.BYTERANGE&&s.setByteRange(t.BYTERANGE),s.level=n,s.sn="initSegment",r&&(s.levelkeys=r),s.initSegment=null}function S_t(s,t,n){s.levelkeys=t;const{encryptedFragments:r}=n;(!r.length||r[r.length-1].levelkeys!==t)&&Object.keys(t).some(a=>t[a].isCommonEncryption)&&r.push(s)}function sC(s,t,n){s.playlistParsingError=new Error(`#EXT-X-${t} must not appear more than once (${n[0]})`)}function xBn(s,t,n){s.playlistParsingError=new Error(`#EXT-X-${t} must appear before the first Media Segment (${n[0]})`)}function x8e(s,t){const n=t.startPTS;if(mi(n)){let r=0,a;t.sn>s.sn?(r=n-s.start,a=s):(r=s.start-n,a=t),a.duration!==r&&a.setDuration(r)}else t.sn>s.sn?s.cc===t.cc&&s.minEndPTS?t.setStart(s.start+(s.minEndPTS-s.start)):t.setStart(s.start+s.duration):t.setStart(Math.max(s.start-t.duration,0))}function ZHt(s,t,n,r,a,i,l,o){r-n<=0&&(o.warn("Fragment should have a positive duration",t),r=n+t.duration,i=a+t.duration);let d=n,u=r;const h=t.startPTS,m=t.endPTS;if(mi(h)){const _=Math.abs(h-n);s&&_>s.totalduration?o.warn(`media timestamps and playlist times differ by ${_}s for level ${t.level} ${s.url}`):mi(t.deltaPTS)?t.deltaPTS=Math.max(_,t.deltaPTS):t.deltaPTS=_,d=Math.max(n,h),n=Math.min(n,h),a=t.startDTS!==void 0?Math.min(a,t.startDTS):a,u=Math.min(r,m),r=Math.max(r,m),i=t.endDTS!==void 0?Math.max(i,t.endDTS):i}const p=n-t.start;t.start!==0&&t.setStart(n),t.setDuration(r-t.start),t.startPTS=n,t.maxStartPTS=d,t.startDTS=a,t.endPTS=r,t.minEndPTS=u,t.endDTS=i;const g=t.sn;if(!s||gs.endSN)return 0;let x;const y=g-s.startSN,v=s.fragments;for(v[y]=t,x=y;x>0;x--)x8e(v[x],v[x-1]);for(x=y;x=0;u--){const h=a[u].initSegment;if(h){r=h;break}}s.fragmentHint&&delete s.fragmentHint.endPTS;let i;_Bn(s,t,(u,h,m,p)=>{if((!t.startCC||t.skippedSegments)&&h.cc!==u.cc){const g=u.cc-h.cc;for(let x=m;x{var h;u&&(!u.initSegment||u.initSegment.relurl===((h=r)==null?void 0:h.relurl))&&(u.initSegment=r)}),t.skippedSegments){if(t.deltaUpdateFailed=l.some(u=>!u),t.deltaUpdateFailed){n.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let u=t.skippedSegments;u--;)l.shift();t.startSN=l[0].sn}else{t.canSkipDateRanges&&(t.dateRanges=vBn(s.dateRanges,t,n));const u=s.fragments.filter(h=>h.rawProgramDateTime);if(s.hasProgramDateTime&&!t.hasProgramDateTime)for(let h=1;h{h.elementaryStreams=u.elementaryStreams,h.stats=u.stats,h.gap=u.gap||h.gap}),i){const u=t.iframesOnly&&i.type===Ji.MAIN;ZHt(t,i,i.startPTS,i.endPTS,i.startDTS,i.endDTS,u,n)}else XHt(s,t);l.length&&(t.totalduration=t.edge-l[0].start),t.driftStartTime=s.driftStartTime,t.driftStart=s.driftStart;const d=t.advancedDateTime;if(t.advanced&&d){const u=t.edge;t.driftStart||(t.driftStartTime=d,t.driftStart=u),t.driftEndTime=d,t.driftEnd=u}else t.driftEndTime=s.driftEndTime,t.driftEnd=s.driftEnd,t.advancedDateTime=s.advancedDateTime;t.requestScheduled===-1&&(t.requestScheduled=s.requestScheduled)}function vBn(s,t,n){const{dateRanges:r,recentlyRemovedDateranges:a}=t,i=wh({},s);a&&a.forEach(c=>{delete i[c]});const o=Object.keys(i).length;return o?(Object.keys(r).forEach(c=>{const d=i[c],u=new qHt(r[c].attr,d);u.isValid?(i[c]=u,d||(u.tagOrder+=o)):n.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${bm(r[c].attr)}"`)}),i):r}function bBn(s,t,n){if(s&&t){let r=0;for(let a=0,i=s.length;a=0;let o=0;if(l&&at){const i=r[r.length-1].duration*1e3;i{var r;(r=t.details)==null||r.fragments.forEach(a=>{a.level=n,a.initSegment&&(a.initSegment.level=n)})})}function jBn(s,t){return s!==t&&t?E_t(s)!==E_t(t):!1}function E_t(s){return s.replace(/\?[^?]*$/,"")}function dZ(s,t){for(let r=0,a=s.length;rs.startCC)}function T_t(s,t){const n=s.start+t;s.setStart(n)}function sGt(s,t){const n=t.fragments;for(let r=0,a=n.length;r!!m)[0],l=dZ(r,i.cc)||r[Math.floor(r.length/2)]);const c=i.programDateTime,d=l.programDateTime;if(!c||!d)return;const u=(d-c)/1e3;if(Math.abs(u)>Math.max(60,s.totalduration)){n.log(`Cannot align playlists using PDT without overlap (${Math.abs(u)} > ${s.totalduration})`);return}const h=u-(l.start-i.start);n.log(`Aligning playlists using PDT (diff: ${h})`),sGt(h,s)}function th(s,t,n){Bu(s,t,n),s.addEventListener(t,n)}function Bu(s,t,n){s.removeEventListener(t,n)}function dCe(s){let t="";const n=s.length;for(let r=0;r{const{config:l,fragCurrent:o,media:c,mediaBuffer:d,state:u}=this,h=c?c.currentTime:0,m=pl.bufferInfo(d||c,h,l.maxBufferHole),p=m.len;if(this.log(`Media seeking to ${h}, state: ${u}, ${p?"in":"out of"} buffer`),this.state===Kr.ENDED)this.resetLoadingState();else if(o){const x=l.maxFragLookUpTolerance,y=o.start-x,v=o.start+o.duration+x;if(!p||vm.end){const _=hv;(_||j)&&(o.loader&&(j||!this.isFragmentNearlyDownloaded(o))?(this.log(`Cancelling fragment load for seek (sn: ${o.sn}) - ${_?"backward":"forward"} seek`),o.abortRequests(),this.resetLoadingState()):this.fragPrevious=null)}}if(c){this.fragmentTracker.removeFragmentsInRange(h,1/0,this.playlistType,!0);const x=this.lastCurrentTime;if(h>x&&(this.lastCurrentTime=h),!this.loadingParts){const y=Math.max(m.end,h),v=this.shouldLoadParts(this.getLevelDetails(),y);v&&(this.log(`LL-Part loading ON after seeking to ${h} with buffer @${y}`),this.loadingParts=v)}}const g=!pl.isBuffered(c,h);(!this.hls.hasEnoughToStart||g)&&(this.log(`Setting ${g?"startPosition":"nextLoadPosition"} to ${h} for seek without enough to start`),this.nextLoadPosition=h,g&&(this.startPosition=h)),p<1&&this.state===Kr.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 c_t(t.config),this.initFragmentLoader=new c_t(t.config),this.keyLoader=r,this.fragmentTracker=n,this.config=t.config,this.decrypter=new RQe(t.config)}registerListeners(){const{hls:t}=this;t.on(Mt.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(Mt.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(Mt.MANIFEST_LOADING,this.onManifestLoading,this),t.on(Mt.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(Mt.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(Mt.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(Mt.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(Mt.MANIFEST_LOADING,this.onManifestLoading,this),t.off(Mt.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(Mt.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(t){}stopLoad(){if(this.state===Kr.STOPPED)return;this.fragmentLoader.abort(),this.initFragmentLoader.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=Kr.STOPPED}get startPositionValue(){const{nextLoadPosition:t,startPosition:n}=this;if(n===-1&&t){const r=this.getLevelDetails();return r!=null&&r.live?(this.hls.liveSyncPosition||r.fragmentStart)+this.timelineOffset:t}return n}get bufferingEnabled(){return this.buffering}get backtrackFragment(){}set backtrackFragment(t){}get couldBacktrack(){return!1}set couldBacktrack(t){}pauseBuffering(){this.buffering=!1}resumeBuffering(){this.buffering=!0}get inFlightFrag(){return{frag:this.fragCurrent,state:this.state}}_streamEnded(t,n){if(n.live||!this.media)return!1;const r=t.end||0,a=this.config.timelineOffset||0;if(r<=a)return!1;const i=t.buffered;this.config.maxBufferHole&&i&&i.length>1&&(t=pl.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}const o=++l.stats.chunkCount;this.log(`load progress ${l.type} sn: ${l.sn}${i.part?" part: "+i.part.index:""} of ${this.fragInfo(l,!1,i.part)} chunk: ${o}`),this._handleFragmentLoadProgress(i)};this._doFragLoad(t,n,r,a).then(i=>{if(!i)return;const l=this.state,o=i.frag;if(this.fragContextChanged(o)){(l===Kr.FRAG_LOADING||!this.fragCurrent&&l===Kr.PARSING)&&(this.fragmentTracker.removeFragment(o),this.state=Kr.IDLE);return}"payload"in i&&(this.log(`Loaded ${o.type} sn: ${o.sn} of ${this.playlistLabel()} ${o.level} (bytes ${o.stats.loaded})`),this.hls.trigger(Mt.FRAG_LOADED,i)),this._handleFragmentLoadComplete(i)}).catch(i=>{this.state===Kr.STOPPED||this.state===Kr.ERROR||(this.log(`Frag error ${t.type} sn:${t.sn} cc:${t.cc}: ${(i==null?void 0:i.message)||i}`),this.resetFragmentLoading(t))})}clearTrackerIfNeeded(t){var n;const{fragmentTracker:r}=this;if(r.getState(t)===ep.APPENDING){const i=t.type,l=this.getFwdBufferInfo(this.mediaBuffer,i),o=Math.max(t.duration,l?l.len:this.config.maxBufferLength),c=this.backtrackFragment;((c?t.sn-c.sn:0)===1||this.reduceMaxBufferLength(o,t.duration))&&r.removeFragment(t)}else((n=this.mediaBuffer)==null?void 0:n.buffered.length)===0?r.removeAllFragments():r.hasParts(t.type)&&(r.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type}),r.getState(t)===ep.PARTIAL&&r.removeFragment(t))}checkLiveUpdate(t){if(t.updated&&!t.live){const n=this.fragmentTracker,r=t.fragments[t.fragments.length-1];if(r.endList&&!n.isEndListAppended(this.playlistType)){const a=n.getPartialFragment(r.end);a&&(n.removeFragment(a),n.fragBuffered(r,!0))}n.detectPartialFragments({frag:r,part:null,stats:r.stats,id:r.type})}t.fragments[0]||(t.deltaUpdateFailed=!0)}waitForLive(t){const n=t.details;return(n==null?void 0:n.live)&&n.type!=="EVENT"&&(this.levelLastLoaded!==t||n.expired)}flushMainBuffer(t,n,r=null){if(!(t-n))return;const a={startOffset:t,endOffset:n,type:r};this.hls.trigger(Mt.BUFFER_FLUSHING,a)}_loadInitSegment(t){const{hls:n}=this;return this.initFragmentLoader.abort(),n.trigger(Mt.FRAG_LOADING,{frag:t,targetBufferTime:0}),this.initFragmentLoader.load(t).then(r=>{var a;const i=r.frag;if(!this.levels||!rqe(i,(a=this.fragCurrent)==null?void 0:a.initSegment))throw new LS({type:xo.NETWORK_ERROR,details:er.INTERNAL_ABORTED,error:new Error("init load aborted"),fatal:!1,frag:i,networkDetails:null});return r}).then(r=>{const{frag:a,payload:i}=r,l=a.decryptdata;if(i&&i.byteLength>0&&l!=null&&l.key&&l.iv&&VB(l.method)){const o=self.performance.now(),{decryptRange:c}=iCe(a,null,this.iframesOnly);return this.decrypter.decrypt(new Uint8Array(i),l.key.buffer,l.iv.buffer,FQe(l.method),c).catch(d=>{throw n.trigger(Mt.ERROR,{type:xo.MEDIA_ERROR,details:er.FRAG_DECRYPT_ERROR,fatal:!1,error:d,reason:d.message,frag:a}),this.fragmentLoader.abort(),d}).then(d=>{const u=self.performance.now();return n.trigger(Mt.FRAG_DECRYPTED,{frag:a,part:null,payload:d,stats:{tstart:o,tdecrypt:u}}),r.payload=d,this.completeInitSegmentLoad(r)})}return this.completeInitSegmentLoad(r)})}completeInitSegmentLoad(t){const n=t.frag.stats;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()}loadInitSegmentIfNeeded(t){const{initSegment:n}=t;if(!this.bitrateTest&&Lp(t)&&n&&!n.data){var r;return(n.encrypted&&!((r=n.decryptdata)!=null&&r.key)?this.keyLoader.load(n).then(()=>this._loadInitSegment(n)):this._loadInitSegment(n)).catch(i=>{throw this.state===Kr.STOPPED||this.state===Kr.ERROR||("data"in i&&(i.data.frag=t,this.fragmentLoader.abort(),this.handleFragLoadError(i)),this.resetFragmentLoading(t)),i})}}unhandledEncryptionError(t,n){var r,a;const i=t.tracks;if(i&&!n.encrypted&&((r=i.audio)!=null&&r.encrypted||(a=i.video)!=null&&a.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){const l=this.media,o=new Error(`Encrypted track with no key in ${this.fragInfo(n)} (media ${l?"attached mediaKeys: "+l.mediaKeys:"detached"})`);return this.warn(o.message),!l||l.mediaKeys?!1:(this.hls.trigger(Mt.ERROR,{type:xo.KEY_SYSTEM_ERROR,details:er.KEY_SYSTEM_NO_KEYS,fatal:!1,error:o,frag:n}),this.resetTransmuxer(),!0)}return!1}fragContextChanged(t){const{fragCurrent:n}=this;return!t||!rqe(t,n)}fragBufferedComplete(t,n){const r=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${t.type} sn: ${t.sn}${n?" part: "+n.index:""} of ${this.fragInfo(t,!1,n)} > buffer:${r?dCe(pl.getBuffered(r)):"(detached)"})`),Lp(t)){var a;if(t.type!==Ji.SUBTITLE){const l=t.elementaryStreams;if(!Object.keys(l).some(o=>!!l[o])){this.state=Kr.IDLE;return}}const i=(a=this.levels)==null?void 0:a[t.level];i!=null&&i.fragmentError&&(n||this.fragmentTracker.getState(t)!==ep.PARTIAL)&&(this.log(`Resetting level fragment error count of ${i.fragmentError} on frag buffered`),i.fragmentError=0,t.stats.retry=0)}this.state=Kr.IDLE}_handleFragmentLoadComplete(t){const{transmuxer:n}=this;if(!n)return;const r=t.frag,{part:a,partsLoaded:i}=t,l=!i||i.length===0||i.some(d=>!d),{decryptRange:o}=iCe(r,a),c=new DQe(r.level,r.sn,r.stats.chunkCount+1,0,a?a.index:-1,!l,r.duration,this.iframesOnly,o);this.log(`load complete ${r.type} sn: ${r.sn}${a?" part: "+a.index:""} of ${this.fragInfo(r,!1,a)}`),n.flush(c)}_handleFragmentLoadProgress(t){}loadKeyFor(t,n,r){var a;let i=null;return t.encrypted&&!((a=t.decryptdata)!=null&&a.key)?(this.log(`Loading key for ${t.sn} of [${n.startSN}-${n.endSN}], ${this.playlistLabel()} ${t.level}`),this.state=Kr.KEY_LOADING,i=this.keyLoader.load(t,r).then(l=>{if(!this.fragContextChanged(l.frag))return this.hls.trigger(Mt.KEY_LOADED,l),this.state===Kr.KEY_LOADING&&(this.state=Kr.IDLE),l}),this.hls.trigger(Mt.KEY_LOADING,{frag:t})):t.encrypted||(i=this.keyLoader.loadClear(t,n.encryptedFragments,this.startFragRequested),i&&this.log(`[eme] blocking frag sn: ${t.sn} load until media-keys acquired`)),i}_doFragLoad(t,n,r=null,a){this.fragCurrent=t;const i=n.details;if(!this.levels||!i)throw new Error(`frag load aborted, missing level${i?"":" detail"}s`);const l=this.fragPrevious;if(!rK(t,l)){const p=this.shouldLoadParts(n.details,t.end);p!==this.loadingParts&&(this.log(`LL-Part loading ${p?"ON":"OFF"} loading sn ${l==null?void 0:l.sn}->${t.sn}`),this.loadingParts=p)}if(r=Math.max(t.start,r||0),this.loadingParts){const p=i.partList;if(p&&a){r>i.fragmentEnd&&i.fragmentHint&&(t=i.fragmentHint);const g=this.getNextPart(p,t,r);if(g>-1){const x=p[g];if(t=this.fragCurrent=x.fragment,!rK(t,l)&&!this.shouldLoadParts(n.details,t.end))return this.log(`LL-Part loading OFF @${this.playhead} next part: ${this.fragInfo(t,!1,x)}`),this.loadingParts=!1,Promise.resolve(null);if(!this.filterReplacedPrimary(x,n.details))return Promise.resolve(null);const y=this.loadKeyFor(t,i);if(this.fragContextChanged(t))return Promise.resolve(null);this.log(`Loading ${t.type} sn: ${t.sn} part: ${x.index} (${g}/${p.length-1}) of ${this.fragInfo(t,!1,x)} cc: ${t.cc} [${i.startSN}-${i.endSN}], target: ${r}${x.byteRange.length?` range:${x.byteRange.join("-")}`:""}`),this.nextLoadPosition=x.start+x.duration,this.state=Kr.FRAG_LOADING;let v;const _=this.loadInitSegmentIfNeeded(t);if(y||_){const j=!!y;v=Promise.all([y,_]).then(([C])=>j&&(!C||this.fragContextChanged(C.frag))?null:this.doFragPartsLoad(t,x,n,a)).catch(C=>this.handleFragLoadError(C))}else v=this.doFragPartsLoad(t,x,n,a).catch(j=>this.handleFragLoadError(j));return this.hls.trigger(Mt.FRAG_LOADING,{frag:t,part:x,targetBufferTime:r}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):v}else if(!t.url||this.loadedEndOfParts(p,r))return Promise.resolve(null)}}if(this.loadingParts){var o;this.log(`LL-Part loading OFF after next part miss @${r} Check buffer at sn: ${t.sn} loaded parts: ${(o=i.partList)==null?void 0:o.filter(p=>p.loaded).map(p=>`[${p.start}-${p.end}]`)}`),this.loadingParts=!1}else if(!t.url)return Promise.resolve(null);if(!this.filterReplacedPrimary(t,n.details))return Promise.resolve(null);const c=this.loadInitSegmentIfNeeded(t),d=this.loadKeyFor(t,i,c);if(this.fragContextChanged(t)){var u;return this.log(`Context changed in KEY_LOADING sn: ${t.sn} ${t.relurl} > ${(u=this.fragCurrent)==null?void 0:u.relurl}`),c==null||c.catch(()=>null),d==null||d.catch(()=>null),Promise.resolve(null)}this.log(`Loading ${t.type} sn: ${t.sn} of ${this.fragInfo(t,!1)} cc: ${t.cc} ${"["+i.startSN+"-"+i.endSN+"]"}, target: ${r}${t.byteRange.length?` range:${t.byteRange.join("-")}`:""}`),mi(t.sn)&&!this.bitrateTest&&(this.nextLoadPosition=t.start+t.duration),this.state=Kr.FRAG_LOADING;const h=this.config.progressive&&t.type!==Ji.SUBTITLE;let m;return h&&d?m=d.then(p=>!p||this.fragContextChanged(p.frag)?null:this.fragmentLoader.load(t,this.iframesOnly,a,c)).catch(p=>this.handleFragLoadError(p)):m=Promise.all([this.fragmentLoader.load(t,this.iframesOnly,h?a:void 0,h?c:void 0),d,c]).then(([p])=>(!h&&a&&a(p),p)).catch(p=>this.handleFragLoadError(p)),this.hls.trigger(Mt.FRAG_LOADING,{frag:t,targetBufferTime:r}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):Promise.all([m,c]).then(([p])=>p)}doFragPartsLoad(t,n,r,a){return new Promise((i,l)=>{var o;const c=[],d=(o=r.details)==null?void 0:o.partList,u=h=>{this.fragmentLoader.loadPart(t,h,a).then(m=>{c[h.index]=m;const p=m.part;this.hls.trigger(Mt.FRAG_LOADED,m);const g=A_t(r.details,t.sn,h.index+1)||eGt(d,t.sn,h.index+1);if(g)u(g);else return i({frag:t,part:p,partsLoaded:c})}).catch(l)};u(n)})}handleFragLoadError(t){if("data"in t){const n=t.data;n.frag&&n.details===er.INTERNAL_ABORTED?this.handleFragLoadAborted(n.frag,n.part):n.frag&&n.type===xo.KEY_SYSTEM_ERROR&&!n.fatal&&(n.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(n.frag)),this.hls.trigger(Mt.ERROR,n)}else this.hls.trigger(Mt.ERROR,{type:xo.OTHER_ERROR,details:er.INTERNAL_EXCEPTION,err:t,error:t,fatal:!0});return null}_handleTransmuxerFlush(t){const n=this.getCurrentContext(t);if(!n||this.state!==Kr.PARSING){!this.fragCurrent&&this.state!==Kr.STOPPED&&this.state!==Kr.ERROR&&(this.state=Kr.IDLE);return}const{frag:r,part:a,level:i}=n,l=self.performance.now();r.stats.parsing.end=l,a&&(a.stats.parsing.end=l);const o=this.getLevelDetails(),d=o&&r.sn>o.endSN||this.shouldLoadParts(o,r.end);d!==this.loadingParts&&(this.log(`LL-Part loading ${d?"ON":"OFF"} after parsing segment ending @${r.end}`),this.loadingParts=d),this.updateLevelTiming(r,a,i,t)}shouldLoadParts(t,n){if(this.config.lowLatencyMode){if(!t)return this.loadingParts;if(t.partList&&!this.iframesOnly){var r;const a=t.partList[0],i=a.end+(((r=t.fragmentHint)==null?void 0:r.duration)||0);if(n>=i&&this.playhead>a.start-a.fragment.duration)return!0}}return!1}getCurrentContext(t){const{levels:n,fragCurrent:r}=this,{level:a,sn:i,part:l}=t;if(!(n!=null&&n[a]))return this.warn(`Levels object was unset while buffering fragment ${i} of ${this.playlistLabel()} ${a}. The current chunk will not be buffered.`),null;const o=n[a],c=o.details,d=l>-1?A_t(c,i,l):null,u=d?d.fragment:JHt(c,i,r);return u?(r&&r!==u&&(u.stats=r.stats),{frag:u,part:d,level:o}):null}bufferFragmentData(t,n,r,a,i){if(this.state!==Kr.PARSING)return;Lp(n)&&!this.fragContextChanged(n)&&(this.fragPrevious=n);const{data1:l,data2:o}=t;let c=l;if(o&&(c=z2(l,o)),!c.length)return;const d=this.initPTS[n.cc],u=d?-d.baseTime/d.timescale:void 0,h={type:t.type,frag:n,part:r,chunkMeta:a,offset:u,parent:n.type,data:c};if(this.hls.trigger(Mt.BUFFER_APPENDING,h),t.dropped&&t.independent&&!r){if(i)return;this.flushBufferGap(n)}}flushBufferGap(t){const n=this.media;if(!n)return;if(!pl.isBuffered(n,n.currentTime)){this.flushMainBuffer(0,t.start);return}const r=n.currentTime,a=pl.bufferInfo(n,r,0),i=t.duration,l=Math.min(this.config.maxFragLookUpTolerance*2,i*.25),o=Math.max(Math.min(t.start-l,a.end-l),r+l);t.start-o>l&&this.flushMainBuffer(o,t.start)}getFwdBufferInfo(t,n){var r;const a=this.playhead,l=this.lastCurrentTime>a||(r=this.media)!=null&&r.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(t,a,n,l)}getFwdBufferInfoAtPos(t,n,r,a){const i=pl.bufferInfo(t,n,a);if(i.len===0&&i.nextStart!==void 0){const l=this.fragmentTracker.getBufferedFrag(n,r);if(l&&(i.nextStart<=l.end||l.gap)){const o=Math.max(Math.min(i.nextStart,l.end)-n,a);return pl.bufferInfo(t,n,o)}}return i}getMaxBufferLength(t){const{config:n}=this;let r;return t?r=Math.max(8*n.maxBufferSize/t,n.maxBufferLength):r=n.maxBufferLength,Math.min(r,n.maxMaxBufferLength)}exceedsMaxBuffer(t,n,r){const a=t.nextStart;if(a&&r.start>a){const i=t.buffered;if(i){let l=t.len;const o=t.bufferedIndex;for(let c=i.length-1;c>o;c--)i[c].start=n}}return!1}reduceMaxBufferLength(t,n){const r=this.config,a=Math.max(Math.min(t-n,r.maxBufferLength),n/2),i=Math.max(t-n*3,r.maxMaxBufferLength/2,a);return i>=a?(r.maxMaxBufferLength=i,this.warn(`Reduce max buffer length to ${i}s`),!0):!1}getAppendedFrag(t){const n=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(t,this.playlistType):null;return n&&"fragment"in n?n.fragment:n}getNextFragment(t,n){const r=n.fragments,a=r.length;if(!a)return null;const{config:i}=this,l=n.fragmentStart,o=i.lowLatencyMode&&!!n.partList;let c=null;if(n.live){const h=i.initialLiveManifestSize;if(a=l?(y=p,v=p===m?"config":"next load start"):g?(y=g,v="live edge"):(y=t,v="buffer pos"),y1))}getNextFragmentLoopLoading(t,n,r,a,i){let l=null;if(t.gap&&(l=this.getNextFragment(this.nextLoadPosition,n),l&&!l.gap&&r.nextStart)){const o=this.getFwdBufferInfoAtPos(this.mediaBuffer?this.mediaBuffer:this.media,r.nextStart,a,0);if(o!==null&&r.len+o.len>=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(uCe(this.config)){var t;if((t=this.hls.interstitialsManager)==null||(t=t.playingItem)==null?void 0:t.event)return!0}return!1}filterReplacedPrimary(t,n){if(!t)return t;if(uCe(this.config)&&("type"in t?t:t.fragment).type!==Ji.SUBTITLE){const r=this.hls.interstitialsManager,a=r==null?void 0:r.bufferingItem;if(a){const i=a.event;if(i){if(!i.appendInPlace&&(Math.abs(t.start-a.start)>1||a.start===0))return null}else if(t.end<=a.start&&(n==null?void 0:n.live)===!1||t.start>=a.end&&a.nextEvent&&(a.nextEvent.appendInPlace&&!a.nextEvent.hasPlayed||t.start-a.end>1))return null}if(nGt(t,r==null?void 0:r.playerQueue,this.playhead))return null}return t}getNextPart(t,n,r){let a=-1,i=!1,l=!0;for(let c=0,d=t.length;c-1&&r ${o.fragment.sn})`),a}loadedEndOfParts(t,n){let r;for(let a=t.length;a--;){if(r=t[a],!r.loaded)return!1;if(n>r.start)return!0}return!1}getInitialLiveFragment(t){const n=t.fragments,r=this.fragPrevious;let a=null;if(r){if(t.hasProgramDateTime&&(a=qzn(n,r.endProgramDateTime,this.config.maxFragLookUpTolerance),a&&this.log(`Live playlist, switching playlist, load frag with same PDT: ${r.programDateTime}`)),!a){const i=r.sn+1;if(i>=t.startSN&&i<=t.endSN){const l=n[i-t.startSN];r.cc===l.cc&&(a=l,this.log(`Live playlist, switching playlist, load frag with next SN: ${a.sn}`))}a||(a=FHt(t,r.cc,r.end),a&&this.log(`Live playlist, switching playlist, load frag with same CC: ${a.sn}`))}}else{const i=this.hls.liveSyncPosition;i!==null&&(a=this.getFragmentAtPosition(i,this.bitrateTest?t.fragmentEnd:t.edge,t))}return a}getFragmentAtPosition(t,n,r){const{config:a}=this;let{fragPrevious:i}=this,{fragments:l,endSN:o}=r;const{fragmentHint:c}=r,{maxFragLookUpTolerance:d}=a,u=r.partList,h=!!(this.loadingParts&&u!=null&&u.length&&c);h&&!this.bitrateTest&&u[u.length-1].fragment.sn===c.sn&&(l=l.concat(c),o=c.sn),i&&this.fragmentTracker.getState(i)===ep.NOT_LOADED&&(i=null);let m;if(tn-d||(p=this.media)!=null&&p.paused||!this.startFragRequested?0:d;m=bq(i,l,t,x)}else m=l[l.length-1];if(m){const g=m.sn-r.startSN,x=this.fragmentTracker.getState(m);if((x===ep.OK||x===ep.PARTIAL&&m.gap)&&(i=m),rK(m,i)&&(!h||u[0].fragment.sn>m.sn||!r.live)){const y=l[g+1];m.sn${t.startSN} fragments: ${a}`),c}return i}waitForCdnTuneIn(t){return t.live&&t.canBlockReload&&t.partTarget&&t.tuneInGoal>Math.max(t.partHoldBack,t.partTarget*3)}setStartPosition(t,n){let r=this.startPosition;r=0&&(r=this.nextLoadPosition),r}get playhead(){var t;if((t=this.hls)!=null&&t.hasEnoughToStart){var n;const r=(n=this.media)==null?void 0:n.currentTime;return mi(r)?r:this.lastCurrentTime}return this.getLoadPosition()}get iframesOnly(){var t;if(this.playlistType!==Ji.MAIN)return!1;const n=this.getLevelDetails();return n?n.iframesOnly:(t=this.levelLastLoaded)==null?void 0:t.iframes}handleFragLoadAborted(t,n){this.transmuxer&&t.type===this.playlistType&&Lp(t)&&t.stats.aborted&&(this.log(`Fragment ${t.sn}${n?" part "+n.index:""} of ${this.playlistLabel()} ${t.level} was aborted`),this.resetFragmentLoading(t))}resetFragmentLoading(t){(!this.fragCurrent||!this.fragContextChanged(t)&&this.state!==Kr.FRAG_LOADING_WAITING_RETRY)&&(this.state=Kr.IDLE)}onFragmentOrKeyLoadError(t,n){if(n.chunkMeta&&!n.frag){const _=this.getCurrentContext(n.chunkMeta);_&&(n.frag=_.frag)}const{frag:r,part:a}=n;if(!r||!this.levels||r.type!==t)return;if(this.fragContextChanged(r)){var i;this.warn(`Frag load error must match current frag to retry ${r.relurl} > ${(i=this.fragCurrent)==null?void 0:i.relurl}`);return}const l=n.details===er.FRAG_GAP;l&&this.fragmentTracker.addAsGap(r);const o=n.errorAction;if(!o){this.state=Kr.ERROR;return}const{action:c,flags:d,retryCount:u=0,retryConfig:h}=o,m=!!h,p=m&&c===Y0.RetryRequest,g=m&&!o.resolved&&d&Yy.MoveAllAlternatesMatchingHost,x=this.hls.latestLevelDetails,y=x==null?void 0:x.live;if(!p&&g&&Lp(r)&&y&&r.sn=n||r&&!pQ(0))&&(r&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=Kr.IDLE)}reduceLengthAndFlushBuffer(t){if(this.state===Kr.PARSING||this.state===Kr.PARSED){const n=t.frag,r=t.parent,a=this.getFwdBufferInfo(this.mediaBuffer,r),i=a&&a.len>.5;i&&this.reduceMaxBufferLength(a.len,(n==null?void 0:n.duration)||10);const l=!i;return l?this.warn(`Buffer full error while media.currentTime (${this.playhead}) is not buffered, flush ${r} buffer`):a.nextStart&&n&&a.nextStart>n.start&&this.flushMainBuffer(a.nextStart,Number.POSITIVE_INFINITY,r===Ji.AUDIO?r:void 0),n&&(this.fragmentTracker.removeFragment(n),this.nextLoadPosition=n.start),this.resetLoadingState(),l}return!1}resetFragmentErrors(t){t===Ji.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==Kr.STOPPED&&(this.state=Kr.IDLE)}afterBufferFlushed(t,n){if(!t)return;const r=pl.getBuffered(t);this.fragmentTracker.detectEvictedFragments(n,r,this.playlistType),this.state===Kr.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==Kr.STOPPED&&(this.state=Kr.IDLE)}resetStartWhenNotLoaded(){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;const t=this.getLevelDetails();t!=null&&t.live?(this.log("resetting startPosition for live start"),this.startPosition=-1,this.setStartPosition(t,t.fragmentStart),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(t){this.log(`Loading context changed while buffering sn ${t.sn} of ${this.playlistLabel()} ${t.level===-1?"":t.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(),this.resetLoadingState()}removeUnbufferedFrags(t=0){this.fragmentTracker.removeFragmentsInRange(t,1/0,this.playlistType,!1,!0)}updateLevelTiming(t,n,r,a){const i=r.details;if(!i){this.warn("level.details undefined");return}if(this.log(`update level timing ${t.type} sn: ${t.sn}${n?" part: "+n.index:""} of ${this.fragInfo(t,!1,n)}`),!Object.keys(t.elementaryStreams).reduce((h,m)=>{const p=t.elementaryStreams[m];if(p){const g=p.endPTS-p.startPTS;if(g<=0)return this.warn(`Could not parse fragment ${t.sn} ${m} duration reliably (${g})`),h||!1;const x=a.partial?0:ZHt(i,t,p.startPTS,p.endPTS,p.startDTS,p.endDTS,this.iframesOnly,this);return this.hls.trigger(Mt.LEVEL_PTS_UPDATED,{details:i,level:r,drift:x,type:m,frag:t,start:p.startPTS,end:p.endPTS}),!0}return h},!1)){var o,c,d,u;const h=((o=this.transmuxer)==null?void 0:o.error)===null,m=((c=this.transmuxer)==null?void 0:c.error)!=null,p=((d=(u=this.levels)==null?void 0:u.length)!=null?d:0)>1;if((r.fragmentError===0||h&&(r.fragmentError<2||t.endList)||m&&p)&&this.treatAsGap(t,r),h){const g=new Error(`Found no media in ${this.playlistLabel()} ${t.level} ${n?`part: ${n.index} of `:""}sn: ${t.sn} at playlist time: ${t.start}. Resetting transmuxer to fallback to playlist timing`);if(this.warn(g.message),this.hls.trigger(Mt.ERROR,{type:xo.MEDIA_ERROR,details:er.FRAG_PARSING_ERROR,fatal:!1,error:g,frag:t,reason:`Found no media in msn ${t.sn} of ${this.playlistLabel()} "${r.url}"`}),!this.hls)return;this.resetTransmuxer()}}this.state=Kr.PARSED,this.log(`Parsed ${t.type} sn: ${t.sn}${n?" part: "+n.index:""} of ${this.fragInfo(t,!1,n)}`),this.hls.trigger(Mt.FRAG_PARSED,{frag:t,part:n,chunkMeta:a})}playlistLabel(){return`${this.playlistType} playlist`}fragInfo(t,n=!0,r){var a,i;return`${this.playlistLabel()} ${t.level} (${r?"part":"frag"}:[${(a=n&&!r?t.startPTS:(r||t).start)!=null?a:NaN}-${(i=n&&!r?t.endPTS:(r||t).end)!=null?i:NaN}]${r&&t.type==="main"?"INDEPENDENT="+(r.independent?"YES":"NO"):""})`}treatAsGap(t,n){n&&n.fragmentError++,this.fragmentTracker.addAsGap(t)}resetTransmuxer(){var t;(t=this.transmuxer)==null||t.reset()}isFragmentNearlyDownloaded(t){var n;const r=(n=t.loader)==null?void 0:n.stats;if(!r)return!1;const a=r.loading.first>0,l=(r.total-r.loaded)/(this.hls.bandwidthEstimate||this.hls.config.abrEwmaDefaultEstimate);return a&&l<=.15}recoverWorkerError(t){t.event==="demuxerWorker"&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),this.resetStartWhenNotLoaded(),this.resetLoadingState())}set state(t){const n=this._state;n!==t&&(this._state=t,this.log(`${n}->${t}`))}get state(){return this._state}calculateOptimalSwitchPoint(t,n){let r=0;const{hls:a,media:i,config:l,levels:o,playlistType:c}=this,d=this.getLevelDetails();if(i&&!i.paused&&o){var u;const p=c===Ji.AUDIO?IHt(t.audioCodec,128e3):t.maxBitrate,g=1+a.ttfbEstimate/1e3,x=a.bandwidthEstimate*l.abrBandWidthUpFactor,y=d&&(this.loadingParts?d.partTarget:d.averagetargetduration)||((u=this.fragCurrent)==null?void 0:u.duration)||6;r=g+p*y/x,t.details||(r+=g)}const h=this.playhead,m=!(d!=null&&d.live)||n.end-h>r*1.5;return{fetchdelay:r,okToFlushForwardBuffer:m}}scheduleTrackSwitch(t,n,r){const{media:a,playlistType:i}=this;if(!a||!t)return;const l=r?this.getBufferedFrag(this.playhead+n):null;if(l){const c=this.followingBufferedFrag(l);if(c){var o;this.abortCurrentFrag();const d=c.maxStartPTS?c.maxStartPTS:c.start,u=c.duration,h=Math.max(l.end,d+Math.min(Math.max(u-this.config.maxFragLookUpTolerance,u*(this.couldBacktrack?.5:.125)),u*(this.couldBacktrack?.75:.25)));if((((o=this.getLevelDetails())==null?void 0:o.fragmentStart)||0)>h)return;const p=i===Ji.MAIN?null:"audio";this.flushMainBuffer(h,Number.POSITIVE_INFINITY,p),this.cleanupBackBuffer()}}}cleanupBackBuffer(){const{media:t,playlistType:n}=this;if(!t)return;const r=this.getAppendedFrag(this.playhead);if(r&&r.start>1){const a=n===Ji.AUDIO;this.flushMainBuffer(0,r.start-(a?0:1),a?"audio":null)}}getBufferedFrag(t){return this.fragmentTracker.getBufferedFrag(t,this.playlistType)}followingBufferedFrag(t){return t?this.getBufferedFrag(t.end+.5):null}abortCurrentFrag(){const t=this.fragCurrent;switch(this.fragCurrent=null,t&&(t.abortRequests(),this.fragmentTracker.removeFragment(t)),this.state){case Kr.KEY_LOADING:case Kr.FRAG_LOADING:case Kr.FRAG_LOADING_WAITING_RETRY:case Kr.PARSING:case Kr.PARSED:this.state=Kr.IDLE;break}this.nextLoadPosition=this.playhead}checkFragPlaying(){const t=this.media;let n=null;if(t&&t.readyState>1&&t.seeking===!1){const r=t.currentTime;if(pl.isBuffered(t,r)?n=this.getAppendedFrag(r):pl.isBuffered(t,r+.1)&&(n=this.getAppendedFrag(r+.1)),n&&(this.backtrackFragment=void 0,!rK(n,this.fragPlaying)))return this.fragPlaying=n,!0}return!1}getBufferOutput(){return null}nextLevelSwitch(){const{levels:t,media:n,hls:r,config:a,playlistType:i}=this;if(n!=null&&n.readyState&&t&&r&&a){const l=this.getBufferOutput(),o=this.getFwdBufferInfo(l,i);if(!o)return;const c=i===Ji.AUDIO?r.nextAudioTrack:r.nextLoadLevel,d=t[c],{fetchdelay:u,okToFlushForwardBuffer:h}=this.calculateOptimalSwitchPoint(d,o);this.scheduleTrackSwitch(o,u,h)}this.tickImmediate()}}function nGt(s,t,n){if(t)for(let r=t.length;r--;){const a=t[r].interstitial,i=a.startTime,l=Math.min(i+a.duration,a.resumeTime);if(a.appendInPlace&&(s.start>=i&&s.end<=l||n>s.start&&s.end>i&&s.start>2&15;if(l>12){const y=new Error(`invalid ADTS sampling index:${l}`);s.emit(Mt.ERROR,Mt.ERROR,{type:xo.MEDIA_ERROR,details:er.FRAG_PARSING_ERROR,fatal:!0,error:y,reason:y.message});return}const o=(i>>6&3)+1,c=t[n+3]>>6&3|(i&1)<<2,d=a[l];let u=l;(o===5||o===29)&&(u-=3);let h;const m=(u&14)>>1,p=(u&1)<<7|c<<3;let g=0;if(o===1&&l>=6){g=5;const y=l-3;h=[g<<3|m,p|(y&14)>>1,(y&1)<<7|8,0]}else h=[o<<3|m,p];const x="mp4a.40."+(g||o);return ku.log(`manifest codec:${r}, parsed codec:${x}, channels:${c}, rate:${d} (ADTS object type:${o} sampling index:${l} esds config:[${h.join(",")}])`),{config:h,samplerate:d,channelCount:c,codec:x,parsedCodec:x,manifestCodec:r}}function aGt(s,t){return s[t]===255&&(s[t+1]&246)===240}function iGt(s,t){return s[t+1]&1?7:9}function UQe(s,t){return(s[t+3]&3)<<11|s[t+4]<<3|(s[t+5]&224)>>>5}function RBn(s,t){return t+5=s.length)return!1;const r=UQe(s,t);if(r<=n)return!1;const a=t+r;return a===s.length||hCe(s,a)}return!1}function oGt(s,t,n,r,a){if(!s.samplerate){const i=LBn(t,n,r,a);if(!i)return;wh(s,i)}}function lGt(s){return 1024*9e4/s}function FBn(s,t){const n=iGt(s,t);if(t+n<=s.length){const r=UQe(s,t)-n;if(r>0)return{headerLength:n,frameLength:r}}}function cGt(s,t,n,r,a){const i=lGt(s.samplerate),l=r+a*i,o=FBn(t,n);let c;if(o){const{frameLength:h,headerLength:m}=o,p=m+h,g=Math.max(0,n+p-t.length);g?(c=new Uint8Array(p-m),c.set(t.subarray(n+m,t.length),0)):c=t.subarray(n+m,n+p);const x={unit:c,pts:l};return g||s.samples.push(x),{sample:x,length:p,missing:g}}const d=t.length-n;return c=new Uint8Array(d),c.set(t.subarray(n,t.length),0),{sample:{unit:c,pts:l},length:d,missing:-1}}let nb=function(s){return s.audioId3="org.id3",s.dateRange="com.apple.quicktime.HLS",s.emsg="https://aomedia.org/emsg/ID3",s.misbklv="urn:misb:KLV:bin:1910.1",s}({});function i5(s="",t=9e4){return{type:s,id:-1,pid:-1,inputTimeScale:t,sequenceNumber:-1,samples:[],dropped:0}}class qQe{constructor(){this._audioTrack=void 0,this._id3Track=void 0,this.frameIndex=0,this.cachedData=null,this.basePTS=null,this.initPTS=null,this.lastPTS=null}resetInitSegment(t,n,r,a){this._id3Track={type:"id3",id:3,pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0}}resetTimeStamp(t){this.initPTS=t,this.resetContiguity()}resetContiguity(){this.basePTS=null,this.lastPTS=null,this.frameIndex=0}canParse(t,n){return!1}appendFrame(t,n,r){}demux(t,n){this.cachedData&&(t=z2(this.cachedData,t),this.cachedData=null);let r=gQ(t,0),a=r?r.length:0,i;const l=this._audioTrack,o=this._id3Track,c=r?MQe(r):void 0,d=t.length;for((this.basePTS===null||this.frameIndex===0&&mi(c))&&(this.basePTS=zBn(c,n,this.initPTS),this.lastPTS=this.basePTS),this.lastPTS===null&&(this.lastPTS=this.basePTS),r&&r.length>0&&o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:r,type:nb.audioId3,duration:Number.POSITIVE_INFINITY});a{if(mi(s))return s*90;const r=n?n.baseTime*9e4/n.timescale:0;return t*9e4+r},BBn=[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],$Bn=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],UBn=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],qBn=[0,1,1,4];function dGt(s,t,n,r,a){if(n+24>t.length)return;const i=uGt(t,n);if(i&&n+i.frameLength<=t.length){const l=i.samplesPerFrame*9e4/i.sampleRate,o=r+a*l,c={unit:t.subarray(n,n+i.frameLength),pts:o,dts:o};return s.config=[],s.channelCount=i.channelCount,s.samplerate=i.sampleRate,s.samples.push(c),{sample:c,length:i.frameLength,missing:0}}}function uGt(s,t){const n=s[t+1]>>3&3,r=s[t+1]>>1&3,a=s[t+2]>>4&15,i=s[t+2]>>2&3;if(n!==1&&a!==0&&a!==15&&i!==3){const l=s[t+2]>>1&1,o=s[t+3]>>6,c=n===3?3-r:r===3?3:4,d=BBn[c*14+a-1]*1e3,h=$Bn[(n===3?0:n===2?1:2)*3+i],m=o===3?1:2,p=UBn[n][r],g=qBn[r],x=p*8*g,y=Math.floor(p*d/h+l)*g,v=lZ();return!!v&&v<=87&&r===2&&d>=224e3&&o===0&&(s[t+3]=s[t+3]|128),{sampleRate:h,channelCount:m,frameLength:y,samplesPerFrame:x}}}function VQe(s,t){return s[t]===255&&(s[t+1]&224)===224&&(s[t+1]&6)!==0}function hGt(s,t){return t+1{const c=new Uint8Array(o);a.set(c,16),this.decrypter.isSync()||this.decryptAacSamples(t,n+1,r)}).catch(r)}decryptAacSamples(t,n,r){for(;;n++){if(n>=t.length){r();return}if(!(t[n].unit.length<32)&&(this.decryptAacSample(t,n,r),!this.decrypter.isSync()))return}}getAvcEncryptedData(t){const n=Math.floor((t.length-48)/160)*16+16,r=new Int8Array(n);let a=0;for(let i=32;i{i.data=this.getAvcDecryptedUnit(l,c),this.decrypter.isSync()||this.decryptAvcSamples(t,n,r+1,a)}).catch(a)}decryptAvcSamples(t,n,r,a){if(t instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;n++,r=0){if(n>=t.length){a();return}const i=t[n].units;for(;!(r>=i.length);r++){const l=i[r];if(!(l.data.length<=48||l.type!==1&&l.type!==5)&&(this.decryptAvcSample(t,n,r,a,l),!this.decrypter.isSync()))return}}}}class HBn extends qQe{constructor(t,n){super(),this.observer=void 0,this.config=void 0,this.sampleAes=null,this.observer=t,this.config=n}resetInitSegment(t,n,r,a){super.resetInitSegment(t,n,r,a),this._audioTrack={container:"audio/adts",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"aac",samples:[],manifestCodec:n,duration:a,inputTimeScale:9e4,dropped:0}}static probe(t,n){if(!t)return!1;const r=gQ(t,0);let a=(r==null?void 0:r.length)||0;if(mGt(t,a))return!1;for(let i=t.length;a{i.decryptAacSamples(a.audioTrack.samples,0,()=>{l(a)})})}}const pGt=(s,t)=>{let n=0,r=5;t+=r;const a=new Uint32Array(1),i=new Uint32Array(1),l=new Uint8Array(1);for(;r>0;){l[0]=s[t];const o=Math.min(r,8),c=8-o;i[0]=4278190080>>>24+c<>c,n=n?n<t.length||t[n]!==11||t[n+1]!==119)return-1;const i=t[n+4]>>6;if(i>=3)return-1;const o=[48e3,44100,32e3][i],c=t[n+4]&63,u=[64,69,96,64,70,96,80,87,120,80,88,120,96,104,144,96,105,144,112,121,168,112,122,168,128,139,192,128,140,192,160,174,240,160,175,240,192,208,288,192,209,288,224,243,336,224,244,336,256,278,384,256,279,384,320,348,480,320,349,480,384,417,576,384,418,576,448,487,672,448,488,672,512,557,768,512,558,768,640,696,960,640,697,960,768,835,1152,768,836,1152,896,975,1344,896,976,1344,1024,1114,1536,1024,1115,1536,1152,1253,1728,1152,1254,1728,1280,1393,1920,1280,1394,1920][c*3+i]*2;if(n+u>t.length)return-1;const h=t[n+6]>>5;let m=0;h===2?m+=2:(h&1&&h!==1&&(m+=2),h&4&&(m+=2));const p=(t[n+6]<<8|t[n+7])>>12-m&1,x=[2,1,2,3,3,4,4,5][h]+p,y=t[n+5]>>3,v=t[n+5]&7,_=new Uint8Array([i<<6|y<<1|v>>2,(v&3)<<6|h<<3|p<<2|c>>4,c<<4&224]),j=1536/o*9e4,C=r+a*j,A=t.subarray(n,n+u);return s.config=_,s.channelCount=x,s.samplerate=o,s.samples.push({unit:A,pts:C}),u}class WBn extends qQe{resetInitSegment(t,n,r,a){super.resetInitSegment(t,n,r,a),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:n,duration:a,inputTimeScale:9e4,dropped:0}}static probe(t){if(!t)return!1;const n=gQ(t,0);let r=(n==null?void 0:n.length)||0;if(n&&t[r]===11&&t[r+1]===119&&MQe(n)!==void 0&&pGt(t,r)<=16)return!1;for(let a=t.length;r{const l=uzn(i);if(KBn.test(l.schemeIdUri)){const o=P_t(l,n);let c=l.eventDuration===4294967295?Number.POSITIVE_INFINITY:l.eventDuration/l.timeScale;c<=.001&&(c=Number.POSITIVE_INFINITY);const d=l.payload;r.samples.push({data:d,len:d.byteLength,dts:o,pts:o,type:nb.emsg,duration:c})}else if(this.config.enableEmsgKLVMetadata){const o=this.config.emsgKLVSchemaUri||nb.misbklv;if(l.schemeIdUri.startsWith(o)){const c=P_t(l,n);r.samples.push({data:l.payload,len:l.payload.byteLength,dts:c,pts:c,type:nb.misbklv,duration:Number.POSITIVE_INFINITY})}}})}return r}demuxSampleAes(t,n,r){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){this.config=null,this.remainderData=null,this.videoTrack=this.audioTrack=this.id3Track=this.txtTrack=void 0,this.initData=void 0}}function P_t(s,t){return mi(s.presentationTime)?s.presentationTime/s.timeScale:t+s.presentationTimeDelta/s.timeScale}const ZBn=1,XBn=2,ZG=-1;class xGt{constructor(){this.VideoSample=null}createVideoSample(t,n,r){return{key:t,frame:!1,pts:n,dts:r,units:[],length:0}}getLastNalUnit(t){var n;let r=this.VideoSample,a;if((!r||r.units.length===0)&&(r=t[t.length-1]),(n=r)!=null&&n.units){const i=r.units;a=i[i.length-1]}return a}pushAccessUnit(t,n){if(t.units.length&&t.frame){if(t.pts===void 0){const r=n.samples,a=r.length;if(a){const i=r[a-1];t.pts=i.pts,t.dts=i.dts}else{n.dropped++;return}}n.samples.push(t)}}parseNALu(t,n,r){const a=n.byteLength;if(a===0)return[];const i=t.naluState||0,l=i===ZG?0:i,o=[];let c=0,d=0,u=-1,h=0;for(i===ZG&&(u=0,h=this.getNALuType(n,0),d=1);d0&&n[p-1]===0;)p--;if(!(m-p+(p===0?l:0)=0)o.push({data:n.subarray(u,p),type:h});else{const x=this.getLastNalUnit(t.samples);x&&(p>0?x.data=z2(x.data,n.subarray(0,p)):l>0&&(x.data=x.data.subarray(0,x.data.byteLength-l)),x.state=0)}if(d0&&n[m-1]===0;)m--;c=a-m+(m===0?l:0)}if(u>=0)o.push({data:n.subarray(u),type:h,state:c});else if(o.length===0&&c!==ZG){const m=this.getLastNalUnit(t.samples);m&&(m.data=z2(m.data,n),m.state=c)}return t.naluState=c,o}}class uZ{constructor(t){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=t,this.bytesAvailable=t.byteLength,this.word=0,this.bitsAvailable=0}loadWord(){const t=this.data,n=this.bytesAvailable,r=t.byteLength-n,a=new Uint8Array(4),i=Math.min(4,n);if(i===0)throw new Error("no bytes available");a.set(t.subarray(r,r+i)),this.word=new DataView(a.buffer).getUint32(0),this.bitsAvailable=i*8,this.bytesAvailable-=i}skipBits(t){let n;t=Math.min(t,this.bytesAvailable*8+this.bitsAvailable),this.bitsAvailable>t?(this.word<<=t,this.bitsAvailable-=t):(t-=this.bitsAvailable,n=t>>3,t-=n<<3,this.bytesAvailable-=n,this.loadWord(),this.word<<=t,this.bitsAvailable-=t)}readBits(t){let n=Math.min(this.bitsAvailable,t);const r=this.word>>>32-n;if(t>32&&ku.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=n,this.bitsAvailable>0)this.word<<=n;else if(this.bytesAvailable>0)this.loadWord();else throw new Error("no bits available");return n=t-n,n>0&&this.bitsAvailable?r<>>t)return this.word<<=t,this.bitsAvailable-=t,t;return this.loadWord(),t+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){const t=this.skipLZ();return this.readBits(t+1)-1}readEG(){const t=this.readUEG();return 1&t?1+t>>>1:-1*(t>>>1)}readBoolean(){return this.readBits(1)===1}readUByte(){return this.readBits(8)}}class QBn extends xGt{parsePES(t,n,r,a,i){const l=i.iframe,o=this.parseNALu(t,r.data,a);let c=this.VideoSample,d,u=!1;r.data=null,c&&o.length&&!t.audFound&&(this.pushAccessUnit(c,t),c=this.VideoSample=this.createVideoSample(!1,r.pts,r.dts)),o.forEach(h=>{var m,p;switch(h.type){case 1:{if(l)break;let v=!1;d=!0;const _=h.data;if(u&&_.length>4){const j=this.readSliceType(_);(j===2||j===4||j===7||j===9)&&(v=!0)}if(v){var g;(g=c)!=null&&g.frame&&!c.key&&(this.pushAccessUnit(c,t),c=this.VideoSample=null)}c||(c=this.VideoSample=this.createVideoSample(!0,r.pts,r.dts)),c.frame=!0,c.key=v;break}case 5:d=!0,(m=c)!=null&&m.frame&&!c.key&&(this.pushAccessUnit(c,t),c=this.VideoSample=null),c||(c=this.VideoSample=this.createVideoSample(!0,r.pts,r.dts)),c.key=!0,c.frame=!0;break;case 6:{if(l)break;d=!0,xQ(h.data,1,r.pts,n.samples);break}case 7:{var x,y;d=!0,u=!0;const v=h.data,_=this.readSPS(v);if(!t.sps||t.width!==_.width||t.height!==_.height||((x=t.pixelRatio)==null?void 0:x[0])!==_.pixelRatio[0]||((y=t.pixelRatio)==null?void 0:y[1])!==_.pixelRatio[1]){t.width=_.width,t.height=_.height,t.pixelRatio=_.pixelRatio,t.sps=[v];const j=v.subarray(1,4);let C="avc1.";for(let A=0;A<3;A++){let M=j[A].toString(16);M.length<2&&(M="0"+M),C+=M}t.codec=C}break}case 8:d=!0,t.pps=[h.data];break;case 9:d=!0,t.audFound=!0,(p=c)!=null&&p.frame&&(this.pushAccessUnit(c,t),c=null),c||(c=this.VideoSample=this.createVideoSample(!1,r.pts,r.dts));break;case 12:d=!0;break;default:d=!1;break}c&&d&&c.units.push(h)}),a&&c&&(this.pushAccessUnit(c,t),this.VideoSample=null)}getNALuType(t,n){return t[n]&31}readSliceType(t){const n=new uZ(t);return n.readUByte(),n.readUEG(),n.readUEG()}skipScalingList(t,n){let r=8,a=8,i;for(let l=0;l(l=this.VideoSample=this.createVideoSample(u,r.pts,r.dts),l);i.forEach((u,h)=>{var m,p;if(this.startsNewAccessUnit(l,t,u,h)){this.pushAccessUnit(l,t);const x=u.type>=16&&u.type<=23;l=d(x),c=!1}switch(u.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:l||(l=d(!1)),l.frame=!0,o=!0;break;case 16:case 17:case 18:case 21:case 22:case 23:if(o=!0,c){var g;(g=l)!=null&&g.frame&&!l.key&&(this.pushAccessUnit(l,t),l=this.VideoSample=null)}l||(l=d(!0)),l.key=!0,l.frame=!0;break;case 19:case 20:o=!0,(m=l)!=null&&m.frame&&!l.key&&(this.pushAccessUnit(l,t),l=this.VideoSample=null),l||(l=d(!0)),l.key=!0,l.frame=!0;break;case 39:o=!0,xQ(u.data,2,r.pts,n.samples);break;case 32:o=!0,t.vps||(typeof t.params!="object"&&(t.params={}),t.params=wh(t.params,this.readVPS(u.data)),this.initVPS=u.data),t.vps=[u.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],u.data)&&(this.initVPS=t.vps[0],t.sps=t.pps=void 0),!t.sps){const x=this.readSPS(u.data);t.width=x.width,t.height=x.height,t.pixelRatio=x.pixelRatio,t.codec=x.codecString,t.sps=[],typeof t.params!="object"&&(t.params={});for(const y in x.params)t.params[y]=x.params[y]}this.pushParameterSet(t.sps,u.data,t.vps),l||(l=d(!1));break;case 34:if(o=!0,typeof t.params=="object"){if(!t.pps){t.pps=[];const x=this.readPPS(u.data);for(const y in x)t.params[y]=x[y]}this.pushParameterSet(t.pps,u.data,t.vps)}break;case 35:o=!0,t.audFound=!0,(p=l)!=null&&p.frame&&(this.pushAccessUnit(l,t),l=null),l||(l=d(!1));break;default:o=!1;break}l&&o&&l.units.push(u)}),a&&l&&(this.pushAccessUnit(l,t),this.VideoSample=null)}pushParameterSet(t,n,r){(r&&r[0]===this.initVPS||!r&&!t.length)&&t.push(n)}startsNewAccessUnit(t,n,r,a){if(!t)return!1;if(!n.audFound&&a===0)return!0;if(!t.frame)return!1;const{type:i,data:l}=r;return i>=32&&i<=35||i===39||i>=41&&i<=44||i>=48&&i<=55?!0:i<=31&&l.length>2&&(l[2]&128)!==0}getNALuType(t,n){return(t[n]&126)>>>1}ebsp2rbsp(t){const n=new Uint8Array(t.byteLength);let r=0;for(let a=0;a=2&&t[a]===3&&t[a-1]===0&&t[a-2]===0||(n[r]=t[a],r++);return new Uint8Array(n.buffer,0,r)}pushAccessUnit(t,n){super.pushAccessUnit(t,n),this.initVPS&&(this.initVPS=null)}readVPS(t){const n=new uZ(t);n.readUByte(),n.readUByte(),n.readBits(4),n.skipBits(2),n.readBits(6);const r=n.readBits(3),a=n.readBoolean();return{numTemporalLayers:r+1,temporalIdNested:a}}readSPS(t){const n=new uZ(this.ebsp2rbsp(t));n.readUByte(),n.readUByte(),n.readBits(4);const r=n.readBits(3);n.readBoolean();const a=n.readBits(2),i=n.readBoolean(),l=n.readBits(5),o=n.readUByte(),c=n.readUByte(),d=n.readUByte(),u=n.readUByte(),h=n.readUByte(),m=n.readUByte(),p=n.readUByte(),g=n.readUByte(),x=n.readUByte(),y=n.readUByte(),v=n.readUByte(),_=[],j=[];for(let ke=0;ke0)for(let ke=r;ke<8;ke++)n.readBits(2);for(let ke=0;ke1&&n.readEG();for(let tt=0;tt0&&ut<16?(le=nt[ut-1],fe=et[ut-1]):ut===255&&(le=n.readBits(16),fe=n.readBits(16))}if(n.readBoolean()&&n.readBoolean(),n.readBoolean()&&(n.readBits(3),n.readBoolean(),n.readBoolean()&&(n.readUByte(),n.readUByte(),n.readUByte())),n.readBoolean()&&(n.readUEG(),n.readUEG()),n.readBoolean(),n.readBoolean(),n.readBoolean(),Se=n.readBoolean(),Se&&(n.skipUEG(),n.skipUEG(),n.skipUEG(),n.skipUEG()),n.readBoolean()&&(ve=n.readBits(32),he=n.readBits(32),n.readBoolean()&&n.readUEG(),n.readBoolean())){const et=n.readBoolean(),at=n.readBoolean();let wt=!1;(et||at)&&(wt=n.readBoolean(),wt&&(n.readUByte(),n.readBits(5),n.readBoolean(),n.readBits(5)),n.readBits(4),n.readBits(4),wt&&n.readBits(4),n.readBits(5),n.readBits(5),n.readBits(5));for(let rt=0;rt<=r;rt++){_e=n.readBoolean();const Ft=_e||n.readBoolean();let Ut=!1;Ft?n.readEG():Ut=n.readBoolean();const Is=Ut?1:n.readUEG()+1;if(et)for(let xs=0;xs>ke&1)<<31-ke)>>>0;let Ee=Ye.toString(16);return l===1&&Ee==="2"&&(Ee="6"),{codecString:`hvc1.${Be}${l}.${Ee}.${i?"H":"L"}${v}.B0`,params:{general_tier_flag:i,general_profile_idc:l,general_profile_space:a,general_profile_compatibility_flags:[o,c,d,u],general_constraint_indicator_flags:[h,m,p,g,x,y],general_level_idc:v,bit_depth:U+8,bit_depth_luma_minus8:U,bit_depth_chroma_minus8:G,min_spatial_segmentation_idc:te,chroma_format_idc:C,frame_rate:{fixed:_e,fps:he/ve}},width:Ie,height:Ue,pixelRatio:[le,fe]}}readPPS(t){const n=new uZ(this.ebsp2rbsp(t));n.readUByte(),n.readUByte(),n.skipUEG(),n.skipUEG(),n.skipBits(2),n.skipBits(3),n.skipBits(2),n.skipUEG(),n.skipUEG(),n.skipEG(),n.skipBits(2),n.readBoolean()&&n.skipUEG(),n.skipEG(),n.skipEG(),n.skipBits(4);const a=n.readBoolean(),i=n.readBoolean();let l=1;return i&&a?l=0:i?l=3:a&&(l=2),{parallelismType:l}}matchSPS(t,n){return pk(t).substring(3)===pk(n).substring(3)}}const jx=188;class NC{constructor(t,n,r,a){this.logger=void 0,this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this._klvPid=-1,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.videoIntegrityChecker=null,this.observer=t,this.config=n,this.typeSupported=r,this.logger=a,this.videoParser=null}static probe(t,n){const r=NC.syncOffset(t);return r>0&&n.warn(`MPEG2-TS detected but first sync word found @ offset ${r}`),r!==-1}static syncOffset(t){const n=t.length;let r=Math.min(jx*5,n-jx)+1,a=0;for(;a1&&(l===0&&o>2||c+jx>r))return l}else{if(o)return-1;break}a++}return-1}static createTrack(t,n){return{container:t==="video"||t==="audio"?"video/mp2t":void 0,type:t,id:xHt[t],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:t==="audio"?n:void 0}}resetInitSegment(t,n,r,a,i,l){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=NC.createTrack("video"),this._videoTrack.duration=a,this.videoIntegrityChecker=this.config.handleMpegTsVideoIntegrityErrors==="skip"?new s$n(this.logger):null,this._audioTrack=NC.createTrack("audio",a),this._id3Track=NC.createTrack("id3"),this._txtTrack=NC.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=n,this.videoCodec=r,t&&this.demux(t,0,l,(i==null?void 0:i.method)==="SAMPLE-AES")}resetTimeStamp(){}resetContiguity(){const{_audioTrack:t,_videoTrack:n,_id3Track:r}=this;t&&(t.pesData=null),n&&(n.pesData=null),r&&(r.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(t,n,r,a=!1,i=!1){a||(this.sampleAes=null);let l;const o=this._videoTrack,c=this.videoIntegrityChecker,d=this._audioTrack,u=this._id3Track,h=this._txtTrack,m=r.iframe;let p=o.pid,g=o.pesData,x=d.pid,y=u.pid,v=this._klvPid,_=d.pesData,j=u.pesData,C=null,A=null,M=this.pmtParsed,I=this._pmtId,P=t.length;if(this.remainderData&&(t=z2(this.remainderData,t),P=t.length,this.remainderData=null),P>4;let se;if(Y>1){if(se=U+5+t[U+4],se===U+jx)continue}else se=U+4;switch(H){case p:G&&(g&&!(c!=null&&c.isCorrupted)&&(l=fP(g,this.logger))&&(this.readyVideoParser(o.segmentCodec),this.videoParser!==null&&this.videoParser.parsePES(o,h,l,!1,r)),g={data:[],size:0},c==null||c.reset(p)),c==null||c.handlePacket(t.subarray(U)),g&&(g.data.push(t.subarray(se,U+jx)),g.size+=U+jx-se);break;case x:if(m)break;if(G){if(_&&(l=fP(_,this.logger)))switch(d.segmentCodec){case"aac":this.parseAACPES(d,l,r);break;case"mp3":this.parseMPEGPES(d,l);break;case"ac3":this.parseAC3PES(d,l);break}_={data:[],size:0}}_&&(_.data.push(t.subarray(se,U+jx)),_.size+=U+jx-se);break;case y:if(m)break;G&&(j&&(l=fP(j,this.logger))&&this.parseID3PES(u,l),j={data:[],size:0}),j&&(j.data.push(t.subarray(se,U+jx)),j.size+=U+jx-se);break;case v:if(m)break;G&&(C&&(l=fP(C,this.logger))&&this.parseKlvPES(u,l),C={data:[],size:0}),C&&(C.data.push(t.subarray(se,U+jx)),C.size+=U+jx-se);break;case 0:G&&(se+=t[se]+1),I=this._pmtId=e$n(t,se);break;case I:{G&&(se+=t[se]+1);const ee=t$n(t,se,this.typeSupported,a,this.observer,this.logger,this.config,r);p=ee.videoPid,p>0&&(o.pid=p,o.segmentCodec=ee.segmentVideoCodec),x=ee.audioPid,x>0&&(d.pid=x,d.segmentCodec=ee.segmentAudioCodec),y=ee.id3Pid,y>0&&(u.pid=y),v=ee.klvPid,v>0&&(this._klvPid=v),A!==null&&!M&&(this.logger.warn(`MPEG-TS PMT found at ${U} after unknown PID '${A}'. Backtracking to sync byte @${R} to parse all TS packets.`),A=null,U=R-188),M=this.pmtParsed=!0;break}case 17:case 8191:break;default:A=H;break}}else O++;O>0&&mqe(this.observer,new Error(`Found ${O} TS packet/s that do not start with 0x47`),r,void 0,this.logger),o.pesData=g,d.pesData=_,u.pesData=j;const B={audioTrack:d,videoTrack:o,id3Track:u,textTrack:h};return i&&this.extractRemainingSamples(B,r),B}flush(t,n){const{remainderData:r}=this;this.remainderData=null;let a;return r?a=this.demux(r,0,n,!1,!0):a={videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(a,n),this.sampleAes?this.decrypt(a,this.sampleAes):a}extractRemainingSamples(t,n){const{audioTrack:r,videoTrack:a,id3Track:i,textTrack:l}=t,o=a.pesData,c=r.pesData,d=i.pesData,u=this.videoIntegrityChecker;let h;if(o&&!(u!=null&&u.isCorrupted)&&(h=fP(o,this.logger))?(this.readyVideoParser(a.segmentCodec),this.videoParser!==null&&(this.videoParser.parsePES(a,l,h,!0,n),a.pesData=null)):a.pesData=o,c&&(h=fP(c,this.logger))){switch(r.segmentCodec){case"aac":this.parseAACPES(r,h,n);break;case"mp3":this.parseMPEGPES(r,h);break;case"ac3":this.parseAC3PES(r,h);break}r.pesData=null}else c!=null&&c.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),r.pesData=c;d&&(h=fP(d,this.logger))?(this.parseID3PES(i,h),i.pesData=null):i.pesData=d}demuxSampleAes(t,n,r,a){const i=this.demux(t,r,a,!0,!this.config.progressive),l=this.sampleAes=new fGt(this.observer,this.config,n);return this.decrypt(i,l)}readyVideoParser(t){this.videoParser===null&&(t==="avc"?this.videoParser=new QBn:t==="hevc"&&(this.videoParser=new JBn))}decrypt(t,n){return new Promise(r=>{const{audioTrack:a,videoTrack:i}=t;a.samples&&a.segmentCodec==="aac"?n.decryptAacSamples(a.samples,0,()=>{i.samples?n.decryptAvcSamples(i.samples,0,0,()=>{r(t)}):r(t)}):i.samples&&n.decryptAvcSamples(i.samples,0,0,()=>{r(t)})})}destroy(){this.observer&&this.observer.removeAllListeners(),this.config=this.logger=this.observer=null,this.aacOverFlow=this.videoParser=this.remainderData=this.sampleAes=null,this._videoTrack=this._audioTrack=this._id3Track=this._txtTrack=void 0,this.videoIntegrityChecker=null}parseAACPES(t,n,r){let a=0;const i=this.aacOverFlow;let l=n.data;if(i){this.aacOverFlow=null;const m=i.missing,p=i.sample.unit.byteLength;if(m===-1)l=z2(i.sample.unit,l);else{const g=p-m;i.sample.unit.set(l.subarray(0,m),g),t.samples.push(i.sample),a=i.missing}}let o,c;for(o=a,c=l.length;o0;)o+=c}}parseID3PES(t,n){if(n.pts===void 0){this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");return}const r=wh({},n,{type:this._videoTrack?nb.emsg:nb.audioId3,duration:Number.POSITIVE_INFINITY});t.samples.push(r)}parseKlvPES(t,n){var r;const a=(r=n.pts)!=null?r:n.dts;if(a===void 0){this.logger.warn("[tsdemuxer]: KLV PES unknown PTS and DTS");return}const i=n.data;if(i.length<16){this.logger.warn("[tsdemuxer]: KLV PES payload too short");return}let l=0;for(;li.length)break;const c=l;if(l+=16,l>=i.length)break;const d=i[l];l+=1;let u=0;if(d&128){const g=d&127;if(g===0||g>4||l+g>i.length){this.logger.warn("[tsdemuxer]: Invalid KLV length encoding");break}for(let x=0;xi.length){this.logger.warn("[tsdemuxer]: KLV value extends beyond PES payload");break}const h=l+u,m=i.subarray(c,h),p={data:m,len:m.byteLength,pts:a,dts:(o=n.dts)!=null?o:a,type:nb.misbklv,duration:Number.POSITIVE_INFINITY};t.samples.push(p),l=h}}}function mCe(s,t){return((s[t+1]&31)<<8)+s[t+2]}function e$n(s,t){return(s[t+10]&31)<<8|s[t+11]}function t$n(s,t,n,r,a,i,l,o){const c={audioPid:-1,videoPid:-1,id3Pid:-1,klvPid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},d=(s[t+1]&15)<<8|s[t+2],u=t+3+d-4,h=(s[t+10]&15)<<8|s[t+11];for(t+=12+h;t0){let g=t+5,x=p;for(;x>2;){switch(s[g]){case 106:c.audioPid===-1&&(n.ac3!==!0?i.log("AC-3 audio found, not supported in this browser for now"):(c.audioPid=m,c.segmentAudioCodec="ac3"));break;case 5:c.klvPid===-1&&l.enableEmsgKLVMetadata&&(c.klvPid=m,i.log(`KLV metadata PID found: ${m}`));break}const v=s[g+1]+2;g+=v,x-=v}}break;case 194:case 135:return mqe(a,new Error("Unsupported EC-3 in M2TS found"),o,void 0,i),c;case 36:c.videoPid===-1&&(c.videoPid=m,c.segmentVideoCodec="hevc",i.log("HEVC in M2TS found"));break}t+=p+5}return c}function mqe(s,t,n,r,a){a.warn(`parsing error: ${t.message}`),s.emit(Mt.ERROR,Mt.ERROR,{type:xo.MEDIA_ERROR,details:er.FRAG_PARSING_ERROR,fatal:!1,levelRetry:r,chunkMeta:n,error:t,reason:t.message})}function v8e(s,t){t.log(`${s} with AES-128-CBC encryption found in unencrypted stream`)}function fP(s,t){let n=0,r,a,i,l,o;const c=s.data;if(!s||s.size===0)return null;for(;c[0].length<19&&c.length>1;)c[0]=z2(c[0],c[1]),c.splice(1,1);if(r=c[0],(r[0]<<16)+(r[1]<<8)+r[2]===1){if(a=(r[4]<<8)+r[5],a&&a>s.size-6)return null;const u=r[7];u&192&&(l=(r[9]&14)*536870912+(r[10]&255)*4194304+(r[11]&254)*16384+(r[12]&255)*128+(r[13]&254)/2,u&64?(o=(r[14]&14)*536870912+(r[15]&255)*4194304+(r[16]&254)*16384+(r[17]&255)*128+(r[18]&254)/2,l-o>60*9e4&&(t.warn(`${Math.round((l-o)/9e4)}s delta between PTS and DTS, align them`),l=o)):o=l),i=r[8];let h=i+9;if(s.size<=h)return null;s.size-=h;const m=new Uint8Array(s.size);for(let p=0,g=c.length;px){h-=x;continue}else r=r.subarray(h),x-=h,h=0;m.set(r,n),n+=x}return a&&(a-=i+3),{data:m,pts:l,dts:o,len:a}}return null}class s$n{constructor(t){this.logger=void 0,this.pid=0,this.lastContinuityCounter=-1,this.integrityState="ok",this.logger=t}get isCorrupted(){return this.integrityState!=="ok"}reset(t){this.pid=t,this.lastContinuityCounter=-1,this.integrityState="ok"}handlePacket(t){if(t.byteLength<4)return;const n=mCe(t,0);if(n!==this.pid){this.logger.debug(`Packet PID mismatch, expected ${this.pid} got ${n}`);return}const r=(t[3]&48)>>4;if(r===0)return;const a=t[3]&15,i=this.lastContinuityCounter;this.lastContinuityCounter=a;const l=(r&1)!=0;if((r&2)!=0&&t[4]!=0&&(t[5]&128)!=0||i<0)return;const d=l?i+1&15:i;if(a!==d){this.logger.warn(`MPEG-TS Continuity Counter check failed for PID='${n}', CC=${a}, Expected-CC=${d} Last-CC=${i}`),this.integrityState="cc-failed";return}if(t[1]&128){this.logger.warn(`MPEG-TS Packet had TEI flag set for PID='${n}'`),this.integrityState="tei-bit";return}}}class n$n{static getSilentFrame(t,n){switch(t){case"mp4a.40.2":if(n===1)return new Uint8Array([0,200,0,128,35,128]);if(n===2)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(n===3)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(n===4)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(n===5)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);if(n===6)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224]);break;default:if(n===1)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(n===2)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(n===3)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);break}}}var fCe;const r$n={video: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]),audio: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])},b8e=new Uint8Array([0,0,0,0,0,0,0,0]),a$n=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),i$n=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),o$n=new Uint8Array([0,0,0,0,0,0,0,0]),XG=new Uint8Array([0,0,0,0,0,0,0,1]),I_t=new Uint8Array([105,115,111,109]),l$n=new Uint8Array([97,118,99,49]),c$n=new Uint8Array([0,0,0,1]);class ki{static box(t,...n){let r=8,a=n.length;const i=a;for(;a--;)r+=n[a].byteLength;const l=new Uint8Array(r);for(Hg(l,0,r),Hg(l,4,t),a=0,r=8;a>24&255,t>>16&255,t>>8&255,t&255,r>>24,r>>16&255,r>>8&255,r&255,a>>24,a>>16&255,a>>8&255,a&255,85,196,0,0]))}static mdia(t){return ki.box(wl.mdia,ki.mdhd(t.timescale||0,t.duration||0),ki.hdlr(t.type),ki.minf(t))}static mfhd(t){return ki.box(wl.mfhd,new Uint8Array([0,0,0,0,t>>24,t>>16&255,t>>8&255,t&255]))}static minf(t){return t.type==="audio"?ki.box(wl.minf,ki.box(wl.smhd,o$n),ki.DINF,ki.stbl(t)):ki.box(wl.minf,ki.box(wl.vmhd,i$n),ki.DINF,ki.stbl(t))}static moof(t,n,r){return ki.box(wl.moof,ki.mfhd(t),ki.traf(r,n))}static moov(t){let n=t.length;const r=[];for(;n--;)r[n]=ki.trak(t[n]);return ki.box.apply(null,[wl.moov,ki.mvhd(t[0].timescale||0,t[0].duration||0)].concat(r).concat(ki.mvex(t)))}static mvex(t){let n=t.length;const r=[];for(;n--;)r[n]=ki.trex(t[n]);return ki.box.apply(null,[wl.mvex,...r])}static mvhd(t,n){n*=t;const r=Math.floor(n/(MS+1)),a=Math.floor(n%(MS+1)),i=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,t&255,r>>24,r>>16&255,r>>8&255,r&255,a>>24,a>>16&255,a>>8&255,a&255,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return ki.box(wl.mvhd,i)}static sdtp(t){const n=t.samples||[],r=new Uint8Array(4+n.length);let a,i;for(a=0;a>>8&255),n.push(l&255),n=n.concat(Array.prototype.slice.call(i));for(a=0;a>>8&255),r.push(l&255),r=r.concat(Array.prototype.slice.call(i));const o=ki.box(wl.avcC,new Uint8Array([1,n[3],n[4],n[5],255,224|t.sps.length].concat(n).concat([t.pps.length]).concat(r))),c=t.width,d=t.height,u=t.pixelRatio[0],h=t.pixelRatio[1];return ki.box(wl.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,ki.box(wl.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),ki.box(wl.pasp,new Uint8Array([u>>24,u>>16&255,u>>8&255,u&255,h>>24,h>>16&255,h>>8&255,h&255])))}static esds(t){const n=t.config,r=n.length;return new Uint8Array([0,0,0,0,3,23+r,0,1,0,4,15+r,64,21,0,0,0,0,0,0,0,0,0,0,0,5,r,...n,6,1,2])}static audioStsd(t){const n=t.samplerate||0;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,t.channelCount||0,0,16,0,0,0,0,n>>8&255,n&255,0,0])}static mp4a(t){return ki.box(wl.mp4a,ki.audioStsd(t),ki.box(wl.esds,ki.esds(t)))}static mp3(t){return ki.box(wl[".mp3"],ki.audioStsd(t))}static ac3(t){return ki.box(wl["ac-3"],ki.audioStsd(t),ki.box(wl.dac3,t.config))}static stsd(t){const{segmentCodec:n}=t;if(t.type==="audio"){if(n==="aac")return ki.box(wl.stsd,XG,ki.mp4a(t));if(n==="ac3"&&t.config)return ki.box(wl.stsd,XG,ki.ac3(t));if(n==="mp3"&&t.codec==="mp3")return ki.box(wl.stsd,XG,ki.mp3(t))}else if(t.pps&&t.sps){if(n==="avc")return ki.box(wl.stsd,XG,ki.avc1(t));if(n==="hevc"&&t.vps)return ki.box(wl.stsd,XG,ki.hvc1(t))}else throw new Error("video track missing pps or sps");throw new Error(`unsupported ${t.type} segment codec (${n}/${t.codec})`)}static tkhd(t){const n=t.id,r=(t.duration||0)*(t.timescale||0),a=t.width||0,i=t.height||0,l=Math.floor(r/(MS+1)),o=Math.floor(r%(MS+1));return ki.box(wl.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,n>>24&255,n>>16&255,n>>8&255,n&255,0,0,0,0,l>>24,l>>16&255,l>>8&255,l&255,o>>24,o>>16&255,o>>8&255,o&255,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,a>>8&255,a&255,0,0,i>>8&255,i&255,0,0]))}static traf(t,n){const r=ki.sdtp(t),a=t.id,i=Math.floor(n/(MS+1)),l=Math.floor(n%(MS+1));return ki.box(wl.traf,ki.box(wl.tfhd,new Uint8Array([0,0,0,0,a>>24,a>>16&255,a>>8&255,a&255])),ki.box(wl.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])),ki.trun(t,r.length+16+20+8+16+8+8),r)}static trak(t){return t.duration=t.duration||4294967295,ki.box(wl.trak,ki.tkhd(t),ki.mdia(t))}static trex(t){const n=t.id;return ki.box(wl.trex,new Uint8Array([0,0,0,0,n>>24,n>>16&255,n>>8&255,n&255,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(t,n){const r=t.samples||[],a=r.length,i=12+16*a,l=new Uint8Array(i);let o,c,d,u,h,m;for(n+=8+i,l.set([t.type==="video"?1:0,0,15,1,a>>>24&255,a>>>16&255,a>>>8&255,a&255,n>>>24&255,n>>>16&255,n>>>8&255,n&255],0),o=0;o>>24&255,d>>>16&255,d>>>8&255,d&255,u>>>24&255,u>>>16&255,u>>>8&255,u&255,h.isLeading<<2|h.dependsOn,h.isDependedOn<<6|h.hasRedundancy<<4|h.paddingValue<<1|h.isNonSync,h.degradPrio&61440,h.degradPrio&15,m>>>24&255,m>>>16&255,m>>>8&255,m&255],12+16*o);return ki.box(wl.trun,l)}static initSegment(t){const n=ki.moov(t);return z2(ki.FTYP,n)}static hvc1(t){const n=t.params,r=[t.vps,t.sps,t.pps],a=4,i=new Uint8Array([1,n.general_profile_space<<6|(n.general_tier_flag?32:0)|n.general_profile_idc,n.general_profile_compatibility_flags[0],n.general_profile_compatibility_flags[1],n.general_profile_compatibility_flags[2],n.general_profile_compatibility_flags[3],n.general_constraint_indicator_flags[0],n.general_constraint_indicator_flags[1],n.general_constraint_indicator_flags[2],n.general_constraint_indicator_flags[3],n.general_constraint_indicator_flags[4],n.general_constraint_indicator_flags[5],n.general_level_idc,240|n.min_spatial_segmentation_idc>>8,255&n.min_spatial_segmentation_idc,252|n.parallelismType,252|n.chroma_format_idc,248|n.bit_depth_luma_minus8,248|n.bit_depth_chroma_minus8,0,parseInt(n.frame_rate.fps),a-1|n.temporal_id_nested<<2|n.num_temporal_layers<<3|(n.frame_rate.fixed?64:0),r.length]);let l=i.length;for(let g=0;g>8,r[g][x].length&255]),l),l+=2,o.set(r[g][x],l),l+=r[g][x].length}const d=ki.box(wl.hvcC,o),u=t.width,h=t.height,m=t.pixelRatio[0],p=t.pixelRatio[1];return ki.box(wl.hvc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,u>>8&255,u&255,h>>8&255,h&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),d,ki.box(wl.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),ki.box(wl.pasp,new Uint8Array([m>>24,m>>16&255,m>>8&255,m&255,p>>24,p>>16&255,p>>8&255,p&255])))}}fCe=ki;ki.FTYP=fCe.box(wl.ftyp,I_t,c$n,I_t,l$n);ki.DINF=fCe.box(wl.dinf,fCe.box(wl.dref,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1])));const yGt=9e4;function HQe(s,t,n=1,r=!1){const a=s*t*n;return r?Math.round(a):a}function d$n(s,t,n=1,r=!1){return HQe(s,t,1/n,r)}function QG(s,t=!1){return HQe(s,1e3,1/yGt,t)}function u$n(s,t=1){return HQe(s,yGt,1/t)}function L_t(s){const{baseTime:t,timescale:n,trackId:r}=s;return`${t/n} (${t}/${n}) trackId: ${r}`}const h$n=10*1e3,m$n=1024,f$n=1152,p$n=1536,fqe=8589934592;function R_t(s,t,n,r){return{duration:t,size:n,cts:r,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:s?2:1,isNonSync:s?0:1,paddingValue:0}}}class xke extends wj{constructor(t,n,r,a){super("mp4-remuxer",a),this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextVideoTs=null,this.nextAudioTs=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=t,this.config=n,this.typeSupported=r,this.ISGenerated=!1}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(t){const n=this._initPTS;(!n||!t||t.trackId!==n.trackId||t.baseTime!==n.baseTime||t.timescale!==n.timescale)&&this.log(`Reset initPTS: ${n&&L_t(n)} > ${t&&L_t(t)}`),this._initPTS=this._initDTS=t}resetNextTimestamp(){this.log("reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){this.log("ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(t){let n=!1;const r=t[0].pts,a=t.reduce((i,l)=>{let o=l.pts,c=o-i;return c<-4294967296&&(n=!0,o=Pw(o,r),c=o-i),c>0?i:o},r);return n&&this.debug("PTS rollover detected"),a}remux(t,n,r,a,i,l,o,c,d){let u,h,m,p,g,x,y=i,v=i;const j=!d.iframe&&t.pid>-1,C=n.pid>-1,A=n.samples.length,M=t.samples.length>0,I=o&&A>0||A>1;if((!j||M)&&(!C||I)||this.ISGenerated||o){if(this.ISGenerated){var R,O,B,U;const se=this.videoTrackConfig;(se&&(n.width!==se.width||n.height!==se.height||((R=n.pixelRatio)==null?void 0:R[0])!==((O=se.pixelRatio)==null?void 0:O[0])||((B=n.pixelRatio)==null?void 0:B[1])!==((U=se.pixelRatio)==null?void 0:U[1]))||!se&&I||this.nextAudioTs===null&&M)&&this.resetInitSegment()}this.ISGenerated||(m=this.generateIS(t,n,i,l));const G=this.isVideoContiguous;let H=-1,Y;if(I&&(H=g$n(n.samples),!G&&this.config.forceKeyFrameOnDiscontinuity))if(x=!0,H>0){this.warn(`Dropped ${H} out of ${A} video samples due to a missing keyframe`);const se=this.getVideoStartPts(n.samples);n.samples=n.samples.slice(H),n.dropped+=H,v+=(n.samples[0].pts-se)/n.inputTimeScale,Y=v}else H===-1&&(this.warn(`No keyframe found out of ${A} video samples`),x=!1);if(this.ISGenerated){if(M&&I&&i){const se=this.getVideoStartPts(n.samples),oe=(Pw(t.samples[0].pts,se)-se)/n.inputTimeScale;y+=Math.max(0,oe),v+=Math.max(0,-oe)}if(M){if(t.samplerate||(this.warn("regenerate InitSegment as audio detected"),m=this.generateIS(t,n,i,l)),h=this.remuxAudio(t,y,this.isAudioContiguous,l,C||I||c===Ji.AUDIO?v:void 0,d),I){const se=h?h.endPTS-h.startPTS:0;n.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),m=this.generateIS(t,n,i,l)),u=this.remuxVideo(n,v,G,se,d)}}else I&&(u=this.remuxVideo(n,v,G,0,d));u&&(u.firstKeyFrame=H,u.independent=H!==-1,u.firstKeyFramePTS=Y)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(r.samples.length&&(g=vGt(r,i,this._initPTS,this._initDTS)),a.samples.length&&(p=bGt(a,i,this._initPTS))),{audio:h,video:u,initSegment:m,independent:x,text:p,id3:g}}computeInitPts(t,n,r,a){const i=Math.round(r*n);let l=Pw(t,i);if(l0?te-1:te].dts&&(j=!0)}j&&o.sort(function(te,le){const fe=te.dts-le.dts,_e=te.pts-le.pts;return fe||_e}),x=o[0].dts,y=o[o.length-1].dts;const A=y-x,M=A?Math.round(A/(d-1)):g||t.inputTimeScale/30;if(r){const te=x-C,le=te>M,fe=te<-1;if((le||fe)&&(le?this.warn(`${(t.segmentCodec||"").toUpperCase()}: ${QG(te,!0)} ms (${te}dts) hole between fragments detected at ${n.toFixed(3)}`):this.warn(`${(t.segmentCodec||"").toUpperCase()}: ${QG(-te,!0)} ms (${te}dts) overlapping between fragments detected at ${n.toFixed(3)}`),!fe||C>=o[0].pts||lZ())){x=C;const _e=o[0].pts-te;if(le)o[0].dts=x,o[0].pts=_e;else{let ve=!0;for(let he=0;he_e&&ve);he++){const Se=o[he].pts;if(o[he].dts-=te,o[he].pts-=te,he0?le.dts-o[te-1].dts:M;if(ve=te>0?le.pts-o[te-1].pts:M,Se.stretchShortVideoTrack&&this.nextAudioTs!==null){const Ie=Math.floor(Se.maxBufferHole*l),Ue=(a?v+a*l:this.nextAudioTs+h)-le.pts;Ue>Ie?(g=Ue-Te,g<0?g=Te:U=!0,this.log(`It is approximately ${Ue/90} ms to the next segment; using duration ${g/90} ms for the last video frame.`)):g=Te}else g=Te}let he=Math.round(le.pts-le.dts);if(G=Math.min(G,g),Y=Math.max(Y,g),H=Math.min(H,ve),se=Math.max(se,ve),!r&&te===0&&he>g){const Se=Math.round(he/M)*M;Se-he===1&&(this.log(`pad first CTS ${he} -> ${Se} of sn: ${i.sn}`),he=Se)}c.push(R_t(le.key,g,_e,he))}if(c.length){const te=lZ();if(te){if(te<70){const le=c[0].flags;le.dependsOn=2,le.isNonSync=0}}else if(xzn()&&se-H0&&(a&&Math.abs(C-(_+j))<9e3||Math.abs(Pw(y[0].pts,C)-(_+j))<20*h),y.forEach(function(ee){ee.pts=Pw(ee.pts,C)}),!r||_<0){const ee=y.length;if(y=y.filter(oe=>oe.pts>=0),ee!==y.length&&this.warn(`Removed ${y.length-ee} of ${ee} samples (initPTS ${j} / ${o})`),!y.length)return;i===0?_=0:a&&!x?_=Math.max(0,C-j):_=y[0].pts-j}if(t.segmentCodec==="aac"){const ee=this.config.maxAudioFramesDrift;for(let oe=0,me=_+j;oe=ee*h&&fe0){P+=v;try{I=new Uint8Array(P)}catch(fe){this.observer.emit(Mt.ERROR,Mt.ERROR,{type:xo.MUX_ERROR,details:er.REMUX_ALLOC_ERROR,fatal:!1,chunkMeta:l,error:fe,bytes:P,reason:`fail allocating audio mdat ${P}`});return}p||(Hg(I,0,P),Hg(I,4,wl.mdat))}else return;I&&I.set(Q,v);const le=Q.byteLength;v+=le,g.push(R_t(!0,u,le,0)),M=te}const O=g.length;if(!O)return;const B=g[g.length-1];_=M-j,this.nextAudioTs=_+d*B.duration;const U=p?new Uint8Array(0):ki.moof(t.sequenceNumber++,A/d,wh({},t,{samples:g}));t.samples=[];const G=(A-j)/o,H=this.nextAudioTs/o,se={data1:U,data2:I,startPTS:G,endPTS:H,startDTS:G,endDTS:H,type:"audio",hasAudio:!0,hasVideo:!1,nb:O};return this.isAudioContiguous=!0,se}}function Pw(s,t){let n;if(t===null)return s;for(t4294967296;)s+=n;return s}function g$n(s){for(let t=0;tl.pts-o.pts);const i=s.samples;return s.samples=[],{samples:i}}class x$n extends wj{constructor(t,n,r,a){super("passthrough-remuxer",a),this.observer=void 0,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,this.videoOnlyRemux=!1,this.decryptdata=null,this.pendingInitSegment=void 0,this.observer=t}destroy(){this.observer&&this.observer.removeAllListeners(),this.observer=null}resetTimeStamp(t){this.lastEndTime=null;const n=this.initPTS;n&&t&&n.baseTime===t.baseTime&&n.timescale===t.timescale||(this.initPTS=t)}resetNextTimestamp(){this.isVideoContiguous=!1,this.lastEndTime=null}resetInitSegment(t,n,r,a){this.audioCodec=n,this.videoCodec=r,this.decryptdata=a,this.pendingInitSegment=t,this.videoOnlyRemux=!1,this.initTracks=void 0,this.initData=void 0,this.emitInitSegment=!0}generateInitSegment(t,n,r){this.videoOnlyRemux=!1;let{audioCodec:a,videoCodec:i}=this;if(!(t!=null&&t.byteLength)){this.initTracks=void 0,this.initData=void 0;return}const{audio:l,video:o}=this.initData=r||_Ht(t);if(n)nzn(t,n);else{const d=l||o;d!=null&&d.encrypted&&this.warn(`Init segment with encrypted track with has no key ("${d.codec}")!`)}l&&(a=D_t(l,Xh.AUDIO,this)),o&&(i=D_t(o,Xh.VIDEO,this));const c={};l&&o?c.audiovideo={container:"video/mp4",codec:a+","+i,supplemental:o.supplemental,encrypted:o.encrypted,initSegment:t,id:"main"}:l?c.audio={container:"audio/mp4",codec:a,encrypted:l.encrypted,initSegment:t,id:"audio"}:o?c.video={container:"video/mp4",codec:i,supplemental:o.supplemental,encrypted:o.encrypted,initSegment:t,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=c}remux(t,n,r,a,i,l,o,c,d,u,h){var m,p;let{initPTS:g,lastEndTime:x}=this;const y={audio:void 0,video:void 0,text:void 0,id3:r,initSegment:void 0};mi(x)||(x=this.lastEndTime=i||0);const v=n.samples;if(!v.length)return y;const _=this.pendingInitSegment;_&&(this.pendingInitSegment=void 0,this.generateInitSegment(_,this.decryptdata,u));const j={initPTS:void 0,timescale:void 0,trackId:void 0};let C=this.initData;if((m=C)!=null&&m.length||(this.generateInitSegment(v),C=this.initData),!((p=C)!=null&&p.length))return this.warn("Failed to generate initSegment."),y;if(d.iframe&&C.audio&&C.video){var A;const ke=(A=this.initTracks)==null||(A=A.audiovideo)==null?void 0:A.initSegment,Fe=ke?X9n(ke):null;if(Fe){var M;this.log("Converted muxed init segment to video-only for I-Frame playback"),this.generateInitSegment(Fe,this.decryptdata),(M=this.initData)!=null&&M.length&&(C=this.initData,this.emitInitSegment=!0,this.videoOnlyRemux=!0)}}this.emitInitSegment&&(j.tracks=this.initTracks,y.initSegment=j,this.emitInitSegment=!1);const I=d.iframe,P=h&&(!I||h.includeSampleDetails)?h.tracks:ozn(v,C,d,this,I),R=C.audio?P[C.audio.id]:null,O=C.video?P[C.video.id]:null,B=!!C.audio,U=!!C.video;let G="";B&&(G+="audio"),U&&(G+="video");const H=cie(O,1/0),Y=cie(R,1/0),se=cie(O,0,!0),ee=cie(R,0,!0);let oe=i,me=0;O&&R&&C.audio&&(Y>se||H>ee)&&this.warn(`audio and video track sample timestamps do not overlap. v: ${H}-${se} a: ${Y}-${ee}}`,O,R);const Q=!!R&&(!O||!g&&Y=1&&C.video&&d.iframe){const{trun:ke,start:Fe}=O,Oe=ke.length===1,Ge=ke.length?Oe?ke[0].samples:ke[0].samples.concat(...ke.slice(1).map(yt=>yt.samples)):[];if(Ge.length){const yt=ke[0];let tt=yt;for(let rt=ke.length;rt--;)if(ke[rt].samples.length){tt=ke[rt];break}const ut=tt.lastSampleDurationOffset,{defaultSampleDurationOffset:nt}=yt,et=Math.abs(d.duration-(se-H))>.05,at=Ge.lengthxs+st.size,0):void 0,Ft=et?d.duration:se-H,Ut=v$n(Ge,Ft*C.video.timescale,ut,nt),Is=Q9n(v,C.video.id,Ge.length,rt,Ut);Is?(le=Is,_e=y$n(Fe,Ge)):this.warn(`IFrame remux skipped (sn ${d.sn}); using native sample duration`),me=Is&&Ut?Ft:se-H}}else this.warn(`Could not remux IFrame track fragment (no samples in range, trun count ${ke.length})`),me=se-H}else me=Q?ee-Y:se-H;if(this.videoOnlyRemux&&le===v)return this.warn(`Dropping muxed I-Frame fragment that could not be remuxed to video-only (sn: ${d.sn})`),y;const ve=te.timescale,he=te.start-i*ve,Se=Q?C.audio.id:C.video.id;if(oe=te.start/ve,(l||!g)&&(b$n(g,oe,i,me)||ve!==g.timescale)){let ke=!1;const Fe=Q?"audio":"video";if(g){const Oe=i!==0?oe/i:1+oe/1;ke=oe>=0&&Math.abs(1-Oe)<.001,this.log(`${Fe} timestamps in track ${Se} at playlist time: ${l?"":"~"}${i} maps to ${oe} with initPTS: ${g.baseTime/g.timescale} (${he/ve-g.baseTime/g.timescale}s diff) (${G}) drift estimate: ${Oe} ${ke?"(ignoring drift)":"remapping timestamps (initPTS)"}`)}ke||(this.log(`Found initPTS in ${Fe} track ${Se} at playlist time: ${i} offset: ${oe-i} (${he}/${ve})`),g=null,j.initPTS=he,j.timescale=ve,j.trackId=Se)}g?(j.initPTS=g.baseTime,j.timescale=g.timescale,j.trackId=g.trackId):((!j.timescale||j.trackId===void 0||j.initPTS===void 0)&&(this.warn("Could not set initPTS"),j.initPTS=oe,j.timescale=1,j.trackId=-1),this.initPTS=g={baseTime:j.initPTS,timescale:j.timescale,trackId:j.trackId});const Te=oe-g.baseTime/g.timescale,Ie=Te+me,Ue=U&&(te==null?void 0:te.ptsMin)!==void 0?te.ptsMin/te.timescale-g.baseTime/g.timescale:Te,Be=_e!==void 0&&O?_e/O.timescale-g.baseTime/g.timescale:U&&te!=null&&te.ptsMax?te.ptsMax/te.timescale-g.baseTime/g.timescale:Ie;me>0?this.lastEndTime=Ie:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const je=(C.audio?C.audio.encrypted:!1)||(C.video?C.video.encrypted:!1),Ye={data1:le,data2:fe,startPTS:Ue,startDTS:Te,endPTS:Be,endDTS:Ie,type:G,hasAudio:B,hasVideo:U,nb:1,dropped:0,encrypted:je};y.audio=B&&!U?Ye:void 0,y.video=U?Ye:void 0;const Ee=this.isVideoContiguous,Re=O==null?void 0:O.sampleCount;if(Re){const ke=O.keyFrameIndex,Fe=ke!==-1;Ye.nb=Re,Ye.dropped=ke===0||Ee?0:Fe?ke:Re,Ye.independent=Fe,Ye.firstKeyFrame=ke,Fe&&O.keyFrameStart&&(Ye.firstKeyFramePTS=(O.keyFrameStart-g.baseTime)/g.timescale),Ee||(y.independent=Fe),this.isVideoContiguous||(this.isVideoContiguous=Fe),Ye.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${ke}/${Re} dropped: ${Ye.dropped} start: ${Ye.firstKeyFramePTS||"NA"}`)}return y.initSegment=j,y.id3=vGt(r,i,g,g),a.samples.length&&(y.text=bGt(a,i,g)),y}}function cie(s,t,n=!1){return(s==null?void 0:s.start)!==void 0?(s.start+(n?s.duration:0))/s.timescale:t}function y$n(s,t){let n=s,r=s;for(let a=0;a=a}function D_t(s,t,n){const r=s.codec;return r&&r.length>4?r:t===Xh.AUDIO?r==="ec-3"||r==="ac-3"||r==="alac"?r:r==="fLaC"||r==="Opus"?nCe(r,!1):(n.warn(`Unhandled audio codec "${r}" in mp4 MAP`),r||"mp4a"):r==="mjpg"?r:(n.warn(`Unhandled video codec "${r}" in mp4 MAP`),r||"avc1")}let NE;try{NE=self.performance.now.bind(self.performance)}catch{NE=Date.now}const yke=[{demux:YBn,remux:x$n},{demux:NC,remux:xke},{demux:HBn,remux:xke},{demux:WBn,remux:xke}];yke.splice(2,0,{demux:GBn,remux:xke});class O_t{constructor(t,n,r,a,i,l){this.asyncResult=!1,this.logger=void 0,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=t,this.typeSupported=n,this.config=r,this.id=i,this.logger=l}configure(t){this.transmuxConfig=t,this.decrypter&&this.decrypter.reset()}push(t,n,r,a){if(!this.observer)return die(r);const i=r.transmuxing;i.executeStart=NE();const l=new Uint8Array(t),{currentTransmuxState:o,transmuxConfig:c}=this;a&&(this.currentTransmuxState=a);const{contiguous:d,discontinuity:u,trackSwitch:h,accurateTimeOffset:m,timeOffset:p,initSegmentChange:g}=a||o,{audioCodec:x,videoCodec:y,defaultInitPts:v,duration:_,initSegmentData:j}=c,C=_$n(l,n);if(C&&VB(C.method)){const P=this.getDecrypter(),R=FQe(C.method);return this.asyncResult=!0,this.decryptionPromise=P.decrypt(l,C.key.buffer,C.iv.buffer,R,r.decryptRange).then(O=>{const B=this.push(O,null,r);return this.decryptionPromise=null,B}),this.decryptionPromise}const A=this.needsProbing(u,h);if(A){const P=r.iframe&&j&&NC.probe(j,this.logger)?j:l,R=this.configureTransmuxer(P);if(R)return this.logger.warn(`[transmuxer] ${R.message}`),this.observer.emit(Mt.ERROR,Mt.ERROR,{type:xo.MEDIA_ERROR,details:er.FRAG_PARSING_ERROR,fatal:!1,error:R,reason:R.message}),i.executeEnd=NE(),die(r)}(u||h||g||A)&&this.resetInitSegment(j,x,y,_,n,r),(u||g||A)&&this.resetInitialTimestamp(v),d||this.resetContiguity();const M=this.transmux(l,C,p,m,r);this.asyncResult=jQ(M);const I=this.currentTransmuxState;return I.contiguous=!0,I.discontinuity=!1,I.trackSwitch=!1,i.executeEnd=NE(),M}flush(t){const n=t.transmuxing;n.executeStart=NE();const{decrypter:r,currentTransmuxState:a,decryptionPromise:i}=this;if(i)return this.asyncResult=!0,i.then(()=>this.flush(t));const l=[],{timeOffset:o}=a;if(r){const h=r.flush();h&&l.push(this.push(h.buffer,null,t))}const{demuxer:c,remuxer:d}=this;if(!c||!d){n.executeEnd=NE();const h=[die(t)];return this.asyncResult?Promise.resolve(h):h}const u=c.flush(o,t);return jQ(u)?(this.asyncResult=!0,u.then(h=>(this.flushRemux(l,h,t),l))):(this.flushRemux(l,u,t),this.asyncResult?Promise.resolve(l):l)}flushRemux(t,n,r){if(!this.remuxer)return;const{audioTrack:a,videoTrack:i,id3Track:l,textTrack:o}=n,{accurateTimeOffset:c,timeOffset:d}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${r.sn}${r.part>-1?" part: "+r.part:""} of ${this.id} playlist ${r.level}`);const u=this.remuxer.remux(a,i,l,o,d,c,!0,this.id,r,n.initData,n.sampleData);t.push({remuxResult:u,chunkMeta:r}),r.transmuxing.executeEnd=NE()}resetInitialTimestamp(t){const{demuxer:n,remuxer:r}=this;!n||!r||(n.resetTimeStamp(t),r.resetTimeStamp(t))}resetContiguity(){const{demuxer:t,remuxer:n}=this;!t||!n||(t.resetContiguity(),n.resetNextTimestamp())}resetInitSegment(t,n,r,a,i,l){const{demuxer:o,remuxer:c}=this;!o||!c||(o.resetInitSegment(t,n,r,a,i,l),c.resetInitSegment(t,n,r,i))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0),this.observer&&this.observer.removeAllListeners(),this.decryptionPromise=null,this.decrypter=this.observer=void 0,this.logger=this.config=this.probe=void 0}transmux(t,n,r,a,i){let l;return(n==null?void 0:n.method)==="SAMPLE-AES"?l=this.transmuxSampleAes(t,n,r,a,i):l=this.transmuxUnencrypted(t,r,a,i),l}transmuxUnencrypted(t,n,r,a){const{demuxer:i,remuxer:l}=this;if(!i||!l)return die(a);const o=i.demux(t,n,a,!1,!this.config.progressive),{audioTrack:c,videoTrack:d,id3Track:u,textTrack:h}=o;return{remuxResult:l.remux(c,d,u,h,n,r,!1,this.id,a,o.initData,o.sampleData),chunkMeta:a}}transmuxSampleAes(t,n,r,a,i){return this.demuxer?this.demuxer.demuxSampleAes(t,n,r,i).then(l=>({remuxResult:this.remuxer.remux(l.audioTrack,l.videoTrack,l.id3Track,l.textTrack,r,a,!1,this.id,i,l.initData,l.sampleData),chunkMeta:i})):Promise.reject(new Error("no demuxer"))}configureTransmuxer(t){const{config:n,observer:r,typeSupported:a}=this;if(!r)return;let i;try{for(let h=0,m=yke.length;h0&&(t==null?void 0:t.key)!=null&&t.iv!==null&&t.method!=null&&(n=t),n}const die=s=>({remuxResult:{},chunkMeta:s});function jQ(s){return"then"in s&&s.then instanceof Function}class w$n{constructor(t,n,r,a,i){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=t,this.videoCodec=n,this.initSegmentData=r,this.duration=a,this.defaultInitPts=i||null}}class j$n{constructor(t,n,r,a,i,l){this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=t,this.contiguous=n,this.accurateTimeOffset=r,this.trackSwitch=a,this.timeOffset=i,this.initSegmentChange=l}}let F_t=0;class _Gt{constructor(t,n,r,a){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=F_t++,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0,this.onWorkerMessage=c=>{const d=c.data,u=this.hls;if(!(!u||!(d!=null&&d.event)||d.instanceNo!==this.instanceNo))switch(d.event){case"init":{var h;const m=(h=this.workerContext)==null?void 0:h.objectURL;m&&self.URL.revokeObjectURL(m);break}case"transmuxComplete":{this.handleTransmuxComplete(d.data);break}case"flush":{this.onFlush(d.data);break}case"workerLog":{u.logger[d.data.logType]&&u.logger[d.data.logType](d.data.message);break}default:{d.data=d.data||{},d.data.frag=this.frag,d.data.part=this.part,d.data.id=this.id,u.trigger(d.event,d.data);break}}},this.onWorkerError=c=>{if(!this.hls)return;const d=new Error(`${c.message} (${c.filename}:${c.lineno})`);this.hls.config.enableWorker=!1,this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`),this.hls.trigger(Mt.ERROR,{type:xo.OTHER_ERROR,details:er.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:d})};const i=t.config;this.hls=t,this.id=n,this.useWorker=!!i.enableWorker,this.onTransmuxComplete=r,this.onFlush=a;const l=(c,d)=>{d=d||{},d.frag=this.frag||void 0,c===Mt.ERROR&&(d=d,d.parent=this.id,d.part=this.part,this.error=d.error),this.hls.trigger(c,d)};this.observer=new $Qe,this.observer.on(Mt.FRAG_DECRYPTED,l),this.observer.on(Mt.ERROR,l);const o=Jbt(i.preferManagedMediaSource);if(this.useWorker&&typeof Worker<"u"){const c=this.hls.logger;if(i.workerPath||TBn()){try{i.workerPath?(c.log(`loading Web Worker ${i.workerPath} for "${n}"`),this.workerContext=PBn(i.workerPath)):(c.log(`injecting Web Worker for "${n}"`),this.workerContext=MBn());const{worker:u}=this.workerContext;u.addEventListener("message",this.onWorkerMessage),u.addEventListener("error",this.onWorkerError),u.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:o,id:n,config:bm(i)})}catch(u){c.warn(`Error setting up "${n}" Web Worker, fallback to inline`,u),this.terminateWorker(),this.error=null,this.transmuxer=new O_t(this.observer,o,i,"",n,t.logger)}return}}this.transmuxer=new O_t(this.observer,o,i,"",n,t.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const t=this.instanceNo;this.instanceNo=F_t++;const n=this.hls.config,r=Jbt(n.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:t,typeSupported:r,id:this.id,config:bm(n)})}}terminateWorker(){if(this.workerContext){const{worker:t}=this.workerContext;this.workerContext=null,t.removeEventListener("message",this.onWorkerMessage),t.removeEventListener("error",this.onWorkerError),IBn(this.hls.config.workerPath)}}destroy(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{const n=this.transmuxer;n&&(n.destroy(),this.transmuxer=null)}const t=this.observer;t&&t.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null}push(t,n,r,a,i,l,o,c,d,u){var h,m;d.transmuxing.start=self.performance.now();const{instanceNo:p,transmuxer:g}=this,x=l?l.start:i.start,y=i.decryptdata,v=this.frag,_=v?i.cc!==v.cc:!0,j=v?d.level!==v.level:!0,C=v?d.sn-v.sn:-1,A=this.part?d.part-this.part.index:-1,M=C===0&&d.id>1&&d.id===(v==null?void 0:v.stats.chunkCount),I=!j&&(C===1||C===0&&(A===1||M&&A<=0)),P=self.performance.now();(j||C||i.stats.parsing.start===0)&&(i.stats.parsing.start=P),l&&(A||!I)&&(l.stats.parsing.start=P);const R=!(v&&((h=i.initSegment)==null?void 0:h.url)===((m=v.initSegment)==null?void 0:m.url)),O=new j$n(_,I,c,j,x,R);if(!I||_||R){this.hls.logger.log(`[transmuxer-interface]: Starting new transmux session for ${i.type} sn: ${d.sn}${d.part>-1?" part: "+d.part:""} ${this.id} playlist: ${d.level} id: ${d.id} discontinuity: ${_} trackSwitch: ${j} contiguous: ${I} accurateTimeOffset: ${c} timeOffset: ${x} initSegmentChange: ${R}`);const B=new w$n(r,a,n,o,u);this.configureTransmuxer(B)}if(this.frag=i,this.part=l,this.workerContext)this.workerContext.worker.postMessage({instanceNo:p,cmd:"demux",data:t,decryptdata:y,chunkMeta:d,state:O},t instanceof ArrayBuffer?[t]:[]);else if(g){const B=g.push(t,y,d,O);jQ(B)?B.then(U=>{this.handleTransmuxComplete(U)}).catch(U=>{this.transmuxerError(U,d,"transmuxer-interface push error")}):this.handleTransmuxComplete(B)}}flush(t){t.transmuxing.start=self.performance.now();const{instanceNo:n,transmuxer:r}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:n,cmd:"flush",chunkMeta:t});else if(r){const a=r.flush(t);jQ(a)?a.then(i=>{this.handleFlushResult(i,t)}).catch(i=>{this.transmuxerError(i,t,"transmuxer-interface flush error")}):this.handleFlushResult(a,t)}}transmuxerError(t,n,r){this.hls&&(this.error=t,this.hls.trigger(Mt.ERROR,{type:xo.MEDIA_ERROR,details:er.FRAG_PARSING_ERROR,chunkMeta:n,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:t,err:t,reason:r}))}handleFlushResult(t,n){t.forEach(r=>{this.handleTransmuxComplete(r)}),this.onFlush(n)}configureTransmuxer(t){const{instanceNo:n,transmuxer:r}=this;this.workerContext?this.workerContext.worker.postMessage({instanceNo:n,cmd:"configure",config:t}):r&&r.configure(t)}handleTransmuxComplete(t){t.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(t)}}const z_t=100;class N$n extends BQe{constructor(t,n,r){super(t,n,r,"audio-stream-controller",Ji.AUDIO),this.mainAnchor=null,this.mainFragLoading=null,this.audioOnly=!1,this.bufferedTrack=null,this.switchingTrack=null,this.trackId=-1,this.nextTrackId=-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(Mt.LEVEL_LOADED,this.onLevelLoaded,this),t.on(Mt.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.on(Mt.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(Mt.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on(Mt.BUFFER_RESET,this.onBufferReset,this),t.on(Mt.BUFFER_CREATED,this.onBufferCreated,this),t.on(Mt.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(Mt.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(Mt.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(Mt.FRAG_LOADING,this.onFragLoading,this),t.on(Mt.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){const{hls:t}=this;t&&(super.unregisterListeners(),t.off(Mt.LEVEL_LOADED,this.onLevelLoaded,this),t.off(Mt.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.off(Mt.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(Mt.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off(Mt.BUFFER_RESET,this.onBufferReset,this),t.off(Mt.BUFFER_CREATED,this.onBufferCreated,this),t.off(Mt.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(Mt.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(Mt.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(Mt.FRAG_LOADING,this.onFragLoading,this),t.off(Mt.FRAG_BUFFERED,this.onFragBuffered,this))}onInitPtsFound(t,n){const{frag:r,id:a,initPTS:i,timescale:l,trackId:o,timestampOffsets:c}=n;if(a===Ji.MAIN){const d=r.cc,u=this.fragCurrent;if(this.initPTS=c,this.log(`InitPTS for cc: ${d} found from main: ${i/l} (${i}/${l}) trackId: ${o}`),this.mainAnchor=r,this.state===Kr.WAITING_INIT_PTS){const h=this.waitingData;(!h&&!this.loadingParts||h&&h.frag.cc!==d)&&this.syncWithAnchor(r,h==null?void 0:h.frag)}else!this.hls.hasEnoughToStart&&u&&u.cc!==d?(u.abortRequests(),this.syncWithAnchor(r,u)):this.state===Kr.IDLE&&this.tick()}}getLoadPosition(){var t;return!this.startFragRequested&&this.nextLoadPosition>=0&&((t=this.switchingTrack)==null?void 0:t.flushImmediate)!==!1?this.nextLoadPosition:super.getLoadPosition()}syncWithAnchor(t,n){var r;const a=((r=this.mainFragLoading)==null?void 0:r.frag)||null;if(n&&(a==null?void 0:a.cc)===n.cc)return;const i=(a||t).cc,l=this.getLevelDetails(),o=this.getLoadPosition(),c=FHt(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===Kr.IDLE&&this.doTickIdle())}startLoad(t,n){if(!this.levels){this.startPosition=t,this.state=Kr.STOPPED;return}const r=this.lastCurrentTime;this.stopLoad(),this.setInterval(z_t),r>0&&t===-1&&!n&&this.initPTS.length&&(this.log(`Override startPosition with lastCurrentTime @${r.toFixed(3)}`),t=r),this.state=Kr.IDLE,this.nextLoadPosition=this.lastCurrentTime=t+this.timelineOffset,this.startPosition=n?-1:t,!n&&!this.fragmentTracker.hasFragments(this.playlistType)&&(this.startFragRequested=!1),this.tick()}doTick(){switch(this.state){case Kr.IDLE:this.doTickIdle();break;case Kr.WAITING_TRACK:{const{levels:t,trackId:n}=this,r=t==null?void 0:t[n],a=r==null?void 0:r.details;if(a&&!this.waitForLive(r)){if(this.waitForCdnTuneIn(a))break;this.state=Kr.WAITING_INIT_PTS}break}case Kr.FRAG_LOADING_WAITING_RETRY:{this.checkRetryDate();break}case Kr.WAITING_INIT_PTS:{const t=this.waitingData;if(t){const{frag:n,part:r,cache:a,complete:i}=t,l=this.mainAnchor;if(this.initPTS[n.cc]!==void 0){this.waitingData=null,this.state=Kr.FRAG_LOADING;const o=a.flush().buffer,c={frag:n,part:r,payload:o,networkDetails:null};this._handleFragmentLoadProgress(c),i&&super._handleFragmentLoadComplete(c)}else l&&l.cc!==t.frag.cc&&this.syncWithAnchor(l,t.frag)}else this.state=Kr.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,this.checkFragmentChanged())}doTickIdle(){var t;const{hls:n,levels:r,media:a,trackId:i}=this,l=n.config;if(!this.buffering||!a&&!this.primaryPrefetch&&(this.startFragRequested||!l.startFragPrefetch)||!(r!=null&&r[i]))return;const o=r[i],c=o.details;if(!c||this.waitForLive(o)||this.waitForCdnTuneIn(c)){this.state=Kr.WAITING_TRACK,this.startFragRequested=!1;return}const d=this.getBufferOutput();this.bufferFlushed&&d&&(this.bufferFlushed=!1,this.afterBufferFlushed(d,Xh.AUDIO));const u=this.getFwdBufferInfo();if(u===null)return;if(!this.switchingTrack&&this._streamEnded(u,c)){n.trigger(Mt.BUFFER_EOS,{type:"audio"}),this.state=Kr.ENDED;return}const h=u.len,m=n.maxBufferLength,p=c.fragments,g=p[0].start,x=this.getLoadPosition(),y=this.flushing||this.switchingTrack&&!this.switchingTrack.flushImmediate?x:u.end;if(this.switchingTrack&&a){const j=x;c.PTSKnown&&j=this.timelineOffset&&(u.end>g||u.nextStart)&&(this.log(`Alt audio track ahead of main track, seek to start of alt audio track ${j} -> ${g} + 0.05`),a.currentTime=g+.05)}if(h>=m&&!this.switchingTrack&&y_.end){const C=this.fragmentTracker.getFragAtPos(y,Ji.MAIN);C&&C.end>_.end&&(_=C,this.mainFragLoading={frag:C,targetBufferTime:null})}if(v.start>_.end)return}this.loadFragment(v,o,y)}onMediaDetaching(t,n){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(t,n)}onAudioTracksUpdated(t,{audioTracks:n}){this.resetTransmuxer(),this.levels=n.map(r=>new bQ(r))}onAudioTrackSwitching(t,n){const r=!!n.url;this.trackId=n.id;const{fragCurrent:a}=this;a&&(a.abortRequests(),this.removeUnbufferedFrags(a.start)),this.resetLoadingState(),r?(this.switchingTrack=n,n.flushImmediate||(this.nextTrackId=n.id,this.nextLevelSwitch()),this.flushAudioIfNeeded(n),this.state!==Kr.STOPPED&&(this.setInterval(z_t),this.state=Kr.IDLE,this.tick())):(this.resetTransmuxer(),this.switchingTrack=null,this.bufferedTrack=n,this.clearInterval())}onManifestLoading(){super.onManifestLoading(),this.bufferFlushed=this.flushing=this.audioOnly=!1,this.resetItem(),this.trackId=-1}onLevelLoaded(t,n){this.mainDetails=n.details;const r=this.cachedTrackLoadedData;r&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(Mt.AUDIO_TRACK_LOADED,r))}onAudioTrackLoaded(t,n){var r;const{levels:a}=this,{details:i,id:l,groupId:o,track:c}=n;if(!a){this.warn(`Audio tracks reset while loading track ${l} "${c.name}" of "${o}"`);return}const d=this.mainDetails;if(!d||i.endCC>d.endCC||d.expired){this.cachedTrackLoadedData=n,this.state!==Kr.STOPPED&&(this.state=Kr.WAITING_TRACK);return}this.cachedTrackLoadedData=null,this.log(`Audio track ${l} "${c.name}" of "${o}" loaded [${i.startSN},${i.endSN}]${i.lastPartSn?`[part-${i.lastPartSn}-${i.lastPartIndex}]`:""},duration:${i.totalduration}`);const u=a[l];let h=0;if(i.live||(r=u.details)!=null&&r.live){if(this.checkLiveUpdate(i),i.deltaUpdateFailed)return;if(u.details){var m;h=this.alignPlaylists(i,u.details,(m=this.levelLastLoaded)==null?void 0:m.details)}i.alignedSliding||(cCe(d,i,this),h=i.fragmentStart)}u.details=i,this.levelLastLoaded=u,this.startFragRequested||this.setStartPosition(d,h),this.hls.trigger(Mt.AUDIO_TRACK_UPDATED,{details:i,id:l,groupId:n.groupId}),this.state===Kr.WAITING_TRACK&&!this.waitForCdnTuneIn(i)&&(this.state=Kr.IDLE),this.tick()}_handleFragmentLoadProgress(t){var n;const r=t.frag,{part:a,payload:i}=t,{config:l,trackId:o,levels:c}=this;if(!c){this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${r.sn} of level ${r.level} will not be buffered`);return}const d=c[o];if(!d){this.warn("Audio track is undefined on fragment load progress");return}const u=d.details;if(!u){this.warn("Audio track details undefined on fragment load progress"),this.removeUnbufferedFrags(r.start);return}const h=l.defaultAudioCodec||d.audioCodec||"mp4a.40.2";let m=this.transmuxer;m||(m=this.transmuxer=new _Gt(this.hls,Ji.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const p=this.initPTS[r.cc],g=(n=r.initSegment)==null?void 0:n.data;if(p!==void 0){const y=a?a.index:-1,v=y!==-1,_=new DQe(r.level,r.sn,r.stats.chunkCount,i.byteLength,y,v,r.duration);m.push(i,g,h,"",r,a,u.totalduration,!1,_,p)}else{this.log(`Unknown video PTS for cc ${r.cc}, waiting for video PTS before demuxing audio frag ${r.sn} of [${u.startSN} ,${u.endSN}],track ${o}`);const{cache:x}=this.waitingData=this.waitingData||{frag:r,part:a,cache:new rGt,complete:!1};x.push(new Uint8Array(i)),this.state!==Kr.STOPPED&&(this.state=Kr.WAITING_INIT_PTS)}}_handleFragmentLoadComplete(t){if(this.waitingData){this.waitingData.complete=!0;return}super._handleFragmentLoadComplete(t)}onBufferReset(){this.mediaBuffer=null}onBufferCreated(t,n){this.bufferFlushed=this.flushing=!1;const r=n.tracks.audio;r&&(this.mediaBuffer=r.buffer||null)}onFragLoading(t,n){!this.audioOnly&&n.frag.type===Ji.MAIN&&Lp(n.frag)&&(this.mainFragLoading=n,this.state===Kr.IDLE&&this.tick())}onFragBuffered(t,n){const{frag:r,part:a}=n;if(r.type!==Ji.AUDIO){!this.audioOnly&&r.type===Ji.MAIN&&!r.elementaryStreams.video&&!r.elementaryStreams.audiovideo&&(this.audioOnly=!0,this.mainFragLoading=null);return}if(this.fragContextChanged(r)){this.warn(`Fragment ${r.sn}${a?" p: "+a.index:""} of level ${r.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);return}if(Lp(r)){const i=this.switchingTrack;i&&(this.bufferedTrack=i)}this.fragBufferedComplete(r,a),this.media&&this.tick()}getFwdBufferInfo(){const t=this.getBufferOutput();return super.getFwdBufferInfo(t,Ji.AUDIO)}getBufferOutput(){return this.mediaBuffer?this.mediaBuffer:this.media}checkFragmentChanged(){const t=this.fragPlaying;if(!this.checkFragPlaying())return!1;const r=this.fragPlaying,a=t==null?void 0:t.level;return(!r||r.level!==a)&&(t&&this.cleanupBackBuffer(),this.switchingTrack&&this.completeAudioSwitch(this.switchingTrack)),!0}onError(t,n){var r;if(n.fatal){this.state=Kr.ERROR;return}switch(n.details){case er.FRAG_GAP:case er.FRAG_PARSING_ERROR:case er.FRAG_DECRYPT_ERROR:case er.FRAG_LOAD_ERROR:case er.FRAG_LOAD_TIMEOUT:case er.KEY_LOAD_ERROR:case er.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(Ji.AUDIO,n);break;case er.AUDIO_TRACK_LOAD_ERROR:case er.AUDIO_TRACK_LOAD_TIMEOUT:case er.LEVEL_PARSING_ERROR:!n.levelRetry&&this.state===Kr.WAITING_TRACK&&((r=n.context)==null?void 0:r.type)===Mc.AUDIO_TRACK&&(this.state=Kr.IDLE);break;case er.BUFFER_APPEND_NO_PROGRESS:if(n.parent!=="audio")return;n.frag&&(n.appendsWithoutProgress||0)>=this.config.appendErrorMaxRetry&&(this.warn(`Marking fragment ${n.frag.sn} of track ${n.frag.level} as a gap after ${n.appendsWithoutProgress} appends without buffered range growth, to prevent loop loading`),this.fragmentTracker.addAsGap(n.frag));break;case er.BUFFER_ADD_CODEC_ERROR:case er.BUFFER_APPEND_ERROR:if(n.parent!=="audio")return;this.reduceLengthAndFlushBuffer(n)||this.resetLoadingState();break;case er.BUFFER_FULL_ERROR:if(n.parent!=="audio")return;this.reduceLengthAndFlushBuffer(n)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case er.INTERNAL_EXCEPTION:this.recoverWorkerError(n);break}}onBufferFlushing(t,{type:n}){n!==Xh.VIDEO&&(this.flushing=!0)}onBufferFlushed(t,{type:n}){if(n!==Xh.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===Kr.ENDED&&(this.state=Kr.IDLE);const r=this.getBufferOutput();r&&(this.afterBufferFlushed(r,n),this.tick())}}_handleTransmuxComplete(t){var n;const r="audio",{hls:a}=this,{remuxResult:i,chunkMeta:l}=t,o=this.getCurrentContext(l);if(!o){this.resetWhenMissingContext(l);return}const{frag:c,part:d,level:u}=o,{details:h}=u,{audio:m,text:p,id3:g,initSegment:x}=i;if(this.fragContextChanged(c)||!h){this.fragmentTracker.removeFragment(c),x!=null&&x.tracks&&this.resetTransmuxer();return}if(this.state=Kr.PARSING,m&&this.switchingTrack&&!this.switchingTrack.flushImmediate){const{config:y}=this,v=y.nextAudioTrackBufferFlushForwardOffset,_=Math.max(this.getLoadPosition()+v,c.start);super.flushMainBuffer(_,Number.POSITIVE_INFINITY,Ji.AUDIO)}if(x!=null&&x.tracks){const y=c.initSegment||c;if(this.unhandledEncryptionError(x,c))return;this._bufferInitSegment(u,x.tracks,y,l),a.trigger(Mt.FRAG_PARSING_INIT_SEGMENT,{frag:y,id:r,tracks:x.tracks})}if(m){const{startPTS:y,endPTS:v,startDTS:_,endDTS:j}=m;d&&(d.elementaryStreams[Xh.AUDIO]={startPTS:y,endPTS:v,startDTS:_,endDTS:j}),c.setElementaryStreamInfo(Xh.AUDIO,y,v,_,j),this.bufferFragmentData(m,c,d,l)}if(g!=null&&(n=g.samples)!=null&&n.length){const y=wh({id:r,frag:c,details:h},g);a.trigger(Mt.FRAG_PARSING_METADATA,y)}if(p){const y=wh({id:r,frag:c,details:h},p);a.trigger(Mt.FRAG_PARSING_USERDATA,y)}}_bufferInitSegment(t,n,r,a){if(this.state!==Kr.PARSING||(n.video&&delete n.video,n.audiovideo&&delete n.audiovideo,!n.audio))return;const i=n.audio;i.id=Ji.AUDIO;const l=t.audioCodec;this.log(`Init audio buffer, container:${i.container}, codecs[level/parsed]=[${l}/${i.codec}]`),(l==null?void 0:l.split(",").length)===1&&(i.levelCodec=l),this.hls.trigger(Mt.BUFFER_CODECS,n);const o=i.initSegment;if(o!=null&&o.byteLength){const c={type:"audio",frag:r,part:null,chunkMeta:a,parent:r.type,data:o};this.hls.trigger(Mt.BUFFER_APPENDING,c)}this.tickImmediate()}loadFragment(t,n,r){const a=this.fragmentTracker.getState(t);if(this.switchingTrack||a===ep.NOT_LOADED||a===ep.PARTIAL){var i;if((i=n.details)!=null&&i.live&&!this.initPTS[t.cc]){this.log(`Waiting for video PTS in continuity counter ${t.cc} of live stream before loading audio fragment ${t.sn} of level ${this.trackId}`),this.state=Kr.WAITING_INIT_PTS;const l=this.mainDetails;l&&l.fragmentStart!==n.details.fragmentStart&&cCe(l,n.details,this)}else super.loadFragment(t,n,r)}else this.clearTrackerIfNeeded(t)}flushAudioIfNeeded(t){if(this.media&&this.bufferedTrack&&t.flushImmediate){const{name:n,lang:r,assocLang:a,characteristics:i,audioCodec:l,channels:o}=this.bufferedTrack;bO({name:n,lang:r,assocLang:a,characteristics:i,audioCodec:l,channels:o},t,qR)||(aCe(t.url,this.hls)?(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null):this.bufferedTrack=t)}}completeAudioSwitch(t){const{hls:n}=this;this.bufferedTrack=t,this.switchingTrack=null,n.trigger(Mt.AUDIO_TRACK_SWITCHED,wo({},t))}get nextAudioTrack(){return this.nextTrackId}}class GQe extends wj{constructor(t,n){super(n,t.logger),this.hls=void 0,this.canLoad=!1,this.timer=-1,this.hls=t}destroy(){this.clearTimer(),this.hls=null}clearTimer(){this.timer!==-1&&(self.clearTimeout(this.timer),this.timer=-1)}startLoad(){this.canLoad=!0,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(t,n,r){const a=n==null?void 0:n.renditionReports;if(a){let i=-1;for(let l=0;l=0&&u>n.partTarget&&(c+=1)}const d=r&&e_t(r);return new t_t(o,c>=0?c:void 0,d)}}}loadPlaylist(t){this.clearTimer()}loadingPlaylist(t,n){this.clearTimer()}shouldLoadPlaylist(t){return this.canLoad&&!!t&&!!t.url&&(!t.details||t.details.live)}getUrlWithDirectives(t,n){if(n)try{return n.addDirectives(t)}catch(r){this.warn(`Could not construct new URL with HLS Delivery Directives: ${r}`)}return t}playlistLoaded(t,n,r){const{details:a,stats:i}=n,l=a.fragments,o=self.performance.now(),c=i.loading.first?Math.max(0,Math.floor(o-i.loading.first)):0;a.advancedDateTime=Date.now()-c;const d=this.hls.config.timelineOffset;if(d!==a.appliedTimelineOffset){const h=Math.max(d||0,0);a.appliedTimelineOffset=h,l.forEach(m=>{m==null||m.setStart(m.playlistOffset+h)})}if(a.live||r!=null&&r.live){var u;const h="levelInfo"in n?n.levelInfo:n.track;a.reloaded(r);const m=(u=l[l.length-1])==null?void 0:u.type;if(a.misses>=this.hls.config.liveMaxUnchangedPlaylistRefresh){const A=new Error(`${m} playlist ${h.id} hit max allowed unchanged reloads.`);this.warn(A);const{networkDetails:M,context:I}=n;this.hls.trigger(Mt.ERROR,{type:xo.NETWORK_ERROR,details:er.PLAYLIST_UNCHANGED_ERROR,fatal:!1,url:a.url,error:A,reason:A.message,level:n.level,parent:m,context:I,networkDetails:M,stats:i});return}if(r){yBn(r,a,this);const A=a.playlistParsingError;if(A){this.warn(A);const M=this.hls;if(!M.config.ignorePlaylistParsingErrors){const{networkDetails:I}=n;M.trigger(Mt.ERROR,{type:xo.NETWORK_ERROR,details:er.LEVEL_PARSING_ERROR,fatal:!1,url:a.url,error:A,reason:A.message,level:n.level,parent:m,networkDetails:I,stats:i});return}a.playlistParsingError=null}}a.requestScheduled===-1&&(a.requestScheduled=i.loading.start);const p=this.hls.mainForwardBufferInfo,g=p?p.end-p.len:0,x=(a.edge-g)*1e3,y=QHt(a,x);a.requestScheduled+y0){if(U>a.targetduration*3)this.log(`Playlist last advanced ${B.toFixed(2)}s ago. Omitting segment and part directives.`),j=void 0,C=void 0;else if(r!=null&&r.tuneInGoal&&U-a.partTarget>r.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${r.tuneInGoal} to: ${G} with playlist age: ${a.age}`),G=0;else{const H=Math.floor(G/a.targetduration);if(j+=H,C!==void 0){const Y=Math.round(G%a.targetduration/a.partTarget);C+=Y}this.log(`CDN Tune-in age: ${a.ageHeader}s last advanced ${B.toFixed(2)}s goal: ${G} skip sn ${H} to part ${C}`)}a.tuneInGoal=G}if(_=this.getDeliveryDirectives(a,n.deliveryDirectives,j,C),A||!O){a.requestScheduled=o,this.loadingPlaylist(h,_);return}}else(a.canBlockReload||a.canSkipUntil)&&(_=this.getDeliveryDirectives(a,n.deliveryDirectives,j,C));_&&j!==void 0&&a.canBlockReload&&(a.requestScheduled=i.loading.first+Math.max(y-c*2,y/2)),this.scheduleLoading(h,_,a)}else this.clearTimer()}scheduleLoading(t,n,r){const a=r||t.details;if(!a){this.loadingPlaylist(t,n);return}const i=self.performance.now(),l=a.requestScheduled;if(i>=l){this.loadingPlaylist(t,n);return}const o=l-i;this.log(`reload live playlist ${t.name||t.bitrate+"bps"} in ${Math.round(o)} ms`),this.clearTimer(),this.timer=self.setTimeout(()=>this.loadingPlaylist(t,n),o)}getDeliveryDirectives(t,n,r,a){let i=e_t(t);return n!=null&&n.skip&&t.deltaUpdateFailed&&(r=n.msn,a=n.part,i=gke.No),new t_t(r,a,i)}checkRetry(t){const n=t.details,r=tCe(t),a=t.errorAction,{action:i,retryCount:l=0,retryConfig:o}=a||{},c=!!a&&!!o&&(i===Y0.RetryRequest||!a.resolved&&i===Y0.SendAlternateToPenaltyBox);if(c){var d;if(l>=o.maxNumRetry)return!1;if(r&&(d=t.context)!=null&&d.deliveryDirectives)this.warn(`Retrying playlist loading ${l+1}/${o.maxNumRetry} after "${n}" without delivery-directives`),this.loadPlaylist();else{var u;const h=pQ((u=t.response)==null?void 0:u.code);if(this.clearTimer(),h)this.log("Waiting for connection (offline)"),t.reason="offline",this.timer=self.setTimeout(()=>this.checkOfflineStatus(),1e3);else{const m=EQe(o,l);this.warn(`Retrying playlist loading ${l+1}/${o.maxNumRetry} after "${n}" in ${m}ms`),this.timer=self.setTimeout(()=>this.loadPlaylist(),m)}}t.levelRetry=!0,a.resolved=!0}return c}checkOfflineStatus(){this.clearTimer(),pQ(0)?this.timer=self.setTimeout(()=>this.checkOfflineStatus(),1e3):(this.log("Connection restored (online)"),this.loadPlaylist())}}function wGt(s,t){if(s.length!==t.length)return!1;for(let n=0;ns[a]!==t[a])}class k$n extends GQe{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(Mt.MANIFEST_LOADING,this.onManifestLoading,this),t.on(Mt.MANIFEST_PARSED,this.onManifestParsed,this),t.on(Mt.LEVEL_LOADING,this.onLevelLoading,this),t.on(Mt.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(Mt.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on(Mt.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(Mt.MANIFEST_LOADING,this.onManifestLoading,this),t.off(Mt.MANIFEST_PARSED,this.onManifestParsed,this),t.off(Mt.LEVEL_LOADING,this.onLevelLoading,this),t.off(Mt.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(Mt.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off(Mt.ERROR,this.onError,this)}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,super.destroy()}onManifestLoading(){this.tracks=[],this.tracksInGroup=[],this.groupIds=null,this.currentTrack=null,this.trackId=-1,this.selectDefaultTrack=!0}onManifestParsed(t,n){this.tracks=n.audioTracks||[]}onAudioTrackLoaded(t,n){const{id:r,groupId:a,details:i}=n,l=this.tracksInGroup[r];if(!l||l.groupId!==a){this.warn(`Audio track with id:${r} and group:${a} not found in active group ${l==null?void 0:l.groupId}`);return}const o=l.details;l.details=n.details,this.log(`Audio track ${r} "${l.name}" lang:${l.lang} group:${a} loaded [${i.startSN}-${i.endSN}]`),r===this.trackId&&this.playlistLoaded(r,n,o)}onLevelLoading(t,n){this.switchLevel(n.level)}onLevelSwitching(t,n){this.switchLevel(n.level)}switchLevel(t){const n=this.hls.levels[t];if(!n)return;const r=n.audioGroups||null,a=this.groupIds;let i=this.currentTrack;if(!r||(a==null?void 0:a.length)!==(r==null?void 0:r.length)||r!=null&&r.some(o=>(a==null?void 0:a.indexOf(o))===-1)){this.groupIds=r,this.trackId=-1,this.currentTrack=null;const o=this.tracks.filter(m=>_Q(m.groupId,r));if(o.length)this.selectDefaultTrack&&!o.some(m=>m.default)&&(this.selectDefaultTrack=!1),o.forEach((m,p)=>{m.id=p});else if(!i&&!this.tracksInGroup.length)return;this.tracksInGroup=o;const c=this.hls.config.audioPreference;if(!i&&c){const m=b5(c,o,qR);if(m>-1)i=o[m];else{const p=b5(c,this.tracks);i=this.tracks[p]}}let d=this.findTrackId(i);d===-1&&i&&(d=this.findTrackId(null));const u={audioTracks:o};this.log(`Updating audio tracks, ${o.length} track(s) found in group(s): ${r==null?void 0:r.join(",")}`),this.hls.trigger(Mt.AUDIO_TRACKS_UPDATED,u);const h=this.trackId;if(d!==-1&&h===-1)this.setAudioTrack(d);else if(o.length&&h===-1){var l;const m=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(m.message),this.hls.trigger(Mt.ERROR,{type:xo.MEDIA_ERROR,details:er.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:m})}}}onError(t,n){n.fatal||!n.context||n.context.type===Mc.AUDIO_TRACK&&n.context.id===this.trackId&&_Q(n.context.groupId,this.groupIds)&&this.checkRetry(n)}get allAudioTracks(){return this.tracks}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(t){this.selectDefaultTrack=!1,this.setAudioTrack(t)}get nextAudioTrack(){return this.trackId}set nextAudioTrack(t){this.selectDefaultTrack=!1,this.setAudioTrack(t,!1)}setAudioOption(t){const n=this.hls;if(n.config.audioPreference=t,t){const r=this.allAudioTracks;if(this.selectDefaultTrack=!1,r.length){const a=this.currentTrack;if(a&&bO(t,a,qR))return a;const i=b5(t,this.tracksInGroup,qR);if(i>-1){const l=this.tracksInGroup[i];return this.setAudioTrack(i,"flushImmediate"in t&&t.flushImmediate),l}else if(a){let l=n.loadLevel;l===-1&&(l=n.firstAutoLevel);const o=$zn(t,n.levels,r,l,qR);if(o===-1)return null;n.nextLoadLevel=o}if(t.channels||t.audioCodec){const l=b5(t,r);if(l>-1)return r[l]}}}return null}setAudioTrack(t,n=!0){const r=this.tracksInGroup;if(t<0||t>=r.length){this.warn(`Invalid audio track id: ${t}`);return}this.selectDefaultTrack=!1;const a=this.currentTrack,i=r[t],l=i.details&&!i.details.live;if(t===this.trackId&&i===a&&l||(this.log(`Switching to audio-track ${t} "${i.name}" lang:${i.lang} group:${i.groupId} channels:${i.channels}`),this.trackId=t,this.currentTrack=i,this.hls.trigger(Mt.AUDIO_TRACK_SWITCHING,wo(wo({},i),{},{flushImmediate:n})),l))return;const o=this.switchParams(i.url,a==null?void 0:a.details,i.details);this.loadPlaylist(o)}findTrackId(t){const n=this.tracksInGroup;for(let r=0;r{const r={label:"async-blocker",execute:n,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.append(r,t)})}prependBlocker(t){return new Promise(n=>{if(this.queues){const r={label:"async-blocker-prepend",execute:n,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.queues[t].unshift(r)}})}removeBlockers(){this.queues!==null&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach(t=>{var n;const r=(n=t[0])==null?void 0:n.label;r==="async-blocker"||r==="async-blocker-prepend"?(t[0].execute(),t.splice(0,1)):r==="block-audio"&&t.splice(0,1)})}insertNext(t,n){this.queues!==null&&this.queues[n].splice(1,0,...t)}unblockAudio(){var t;this.queues!==null&&((t=this.current("audio"))==null?void 0:t.label)==="block-audio"&&this.shiftAndExecuteNext("audio")}audioBlocking(){return this.queues===null?!1:this.queues.audio.some(t=>t.label==="block-audio")}executeNext(t){if(this.queues===null||this.tracks===null)return;const n=this.queues[t];if(n.length){const a=n[0];try{a.execute()}catch(i){var r;if(a.onError(i),this.queues===null||this.tracks===null)return;const l=(r=this.tracks[t])==null?void 0:r.buffer;l!=null&&l.updating||this.shiftAndExecuteNext(t)}}}shiftAndExecuteNext(t){this.queues!==null&&(this.queues[t].shift(),this.executeNext(t))}current(t){var n;return((n=this.queues)==null?void 0:n[t][0])||null}toString(){const{queues:t,tracks:n}=this;return t===null||n===null?"":` ${this.list("video")} ${this.list("audio")} ${this.list("audiovideo")}}`}list(t){var n,r;return(n=this.queues)!=null&&n[t]||(r=this.tracks)!=null&&r[t]?`${t}: (${this.listSbInfo(t)}) ${this.listOps(t)}`:""}listSbInfo(t){var n;const r=(n=this.tracks)==null?void 0:n[t],a=r==null?void 0:r.buffer;return a?`SourceBuffer${a.updating?" updating":""}${r.ended?" ended":""}${r.ending?" ending":""}`:"none"}listOps(t){var n;return((n=this.queues)==null?void 0:n[t].map(r=>r.label).join(", "))||""}}const B_t=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,jGt="HlsJsTrackRemovedError",C$n=.25,A$n=.001;class E$n extends Error{constructor(t){super(t),this.name=jGt}}class T$n extends wj{constructor(t,n){super("buffer-controller",t.logger),this.hls=void 0,this.fragmentTracker=void 0,this.fragmentAppendProgress=Object.create(null),this.appendsWithoutProgress=Object.create(null),this.details=null,this._objectUrl=null,this.operationQueue=null,this.bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=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.appendError=void 0,this._quotaEvictionPending={},this.tracks={},this.sourceBuffers=[[null,null],[null,null]],this._onEndStreaming=r=>{var a;this.hls&&((a=this.mediaSource)==null?void 0:a.readyState)==="open"&&(!this.media||this.media.seeking||this.hls.pauseBuffering())},this._onStartStreaming=r=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=r=>{const{media:a,mediaSource:i}=this;r&&this.log("Media source opened"),!(!a||!i)&&(Bu(i,"sourceopen",this._onMediaSourceOpen),Bu(a,"emptied",this._onMediaEmptied),this.updateDuration(),this.hls.trigger(Mt.MEDIA_ATTACHED,{media:a,mediaSource:i}),this.mediaSource!==null&&this.checkPendingTracks())},this._onMediaSourceClose=()=>{if(this.log("Media source closed"),this.media){const r=this.media.error,{appendError:a,appendErrors:i}=this;let l=!1;!a&&r&&(l=Math.max(++i.audio,++i.video,++i.audiovideo)>=this.hls.config.appendErrorMaxRetry);const o=new Error(`MediaSource closed while media attached${U_t(l,r)}`);this.warn(o),this.hls.trigger(Mt.ERROR,wh({fatal:l},a,{type:xo.MEDIA_ERROR,details:er.MEDIA_SOURCE_REQUIRES_RESET,error:o}))}},this._onMediaSourceEnded=()=>{this.log("Media source ended")},this._onMediaEmptied=()=>{const{mediaSrc:r,_objectUrl:a}=this;r!==a&&this.error(`Media element src was set while attaching MediaSource (${a} > ${r})`)},this._onMediaError=()=>{const{media:r}=this;if(r){var a,i;this.log(`Media error (code: ${(a=r.error)==null?void 0:a.code}): ${(i=r.error)==null?void 0:i.message}`)}},this.hls=t,this.fragmentTracker=n,this.appendSource=P9n(zM(t.config.preferManagedMediaSource)),this.initTracks(),this.registerListeners()}hasSourceTypes(){return Object.keys(this.tracks).length>0}destroy(){this.unregisterListeners(),this.details=null,this.lastMpegAudioChunk=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,this._onMediaEmptied=this._onMediaError=null}registerListeners(){const{hls:t}=this;t.on(Mt.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(Mt.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(Mt.MANIFEST_LOADING,this.onManifestLoading,this),t.on(Mt.MANIFEST_PARSED,this.onManifestParsed,this),t.on(Mt.BUFFER_RESET,this.onBufferReset,this),t.on(Mt.BUFFER_APPENDING,this.onBufferAppending,this),t.on(Mt.BUFFER_CODECS,this.onBufferCodecs,this),t.on(Mt.BUFFER_EOS,this.onBufferEos,this),t.on(Mt.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(Mt.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(Mt.FRAG_PARSED,this.onFragParsed,this),t.on(Mt.FRAG_CHANGED,this.onFragChanged,this),t.on(Mt.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(Mt.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(Mt.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(Mt.MANIFEST_LOADING,this.onManifestLoading,this),t.off(Mt.MANIFEST_PARSED,this.onManifestParsed,this),t.off(Mt.BUFFER_RESET,this.onBufferReset,this),t.off(Mt.BUFFER_APPENDING,this.onBufferAppending,this),t.off(Mt.BUFFER_CODECS,this.onBufferCodecs,this),t.off(Mt.BUFFER_EOS,this.onBufferEos,this),t.off(Mt.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(Mt.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(Mt.FRAG_PARSED,this.onFragParsed,this),t.off(Mt.FRAG_CHANGED,this.onFragChanged,this),t.off(Mt.ERROR,this.onError,this)}transferMedia(){const{media:t,mediaSource:n}=this;if(!t)return null;const r={};if(this.operationQueue){const i=this.isUpdating();i||this.operationQueue.removeBlockers();const l=this.isQueued();(i||l)&&this.warn(`Transfering MediaSource with${l?" operations in queue":""}${i?" updating SourceBuffer(s)":""} ${this.operationQueue}`),this.operationQueue.destroy()}const a=this.transferData;return a&&!this.sourceBufferCount&&a.mediaSource===n?wh(r,a.tracks):this.sourceBuffers.forEach(i=>{const[l]=i;l&&(r[l]=wh({},this.tracks[l]),this.removeBuffer(l)),i[0]=i[1]=null}),{media:t,mediaSource:n,tracks:r}}initTracks(){const t={};this.resetAppendProgress(),this.sourceBuffers=[[null,null],[null,null]],this.tracks=t,this.resetQueue(),this.lastMpegAudioChunk=null,this.lastVideoAppendEnd=0}onManifestLoading(){this.bufferCodecEventsTotal=0,this.details=null,this.resetAppendErrors(),this.resetAppendProgress()}onManifestParsed(t,n){var r;let a=2;(n.audio&&!n.video||!n.altAudio)&&(a=1),this.bufferCodecEventsTotal=a,this.log(`${a} bufferCodec event(s) expected.`),(r=this.transferData)!=null&&r.mediaSource&&this.sourceBufferCount&&a&&this.bufferCreated()}onMediaAttaching(t,n){const r=this.media=n.media;this.transferData=this.overrides=void 0;const a=zM(this.appendSource);if(a){const i=!!n.mediaSource;(i||n.overrides)&&(this.transferData=n,this.overrides=n.overrides);const l=this.mediaSource=n.mediaSource||new a;if(this.assignMediaSource(l),i)this._objectUrl=r.src,this.attachTransferred();else{const o=this._objectUrl=self.URL.createObjectURL(l);if(this.appendSource)try{r.removeAttribute("src");const c=self.ManagedMediaSource;r.disableRemotePlayback=r.disableRemotePlayback||c&&l instanceof c,$_t(r),M$n(r,o),r.load()}catch{r.src=o}else r.src=o}th(r,"emptied",this._onMediaEmptied),th(r,"error",this._onMediaError),this.appendSource&&th(r,"seeking",this._onStartStreaming)}}assignMediaSource(t){var n,r;this.log(`${((n=this.transferData)==null?void 0:n.mediaSource)===t?"transferred":"created"} media source: ${(r=t.constructor)==null?void 0:r.name}`),th(t,"sourceopen",this._onMediaSourceOpen),th(t,"sourceended",this._onMediaSourceEnded),th(t,"sourceclose",this._onMediaSourceClose),this.appendSource&&(th(t,"startstreaming",this._onStartStreaming),th(t,"endstreaming",this._onEndStreaming))}attachTransferred(){const t=this.media,n=this.transferData;if(!n||!t)return;const r=this.tracks,a=n.tracks,i=a?Object.keys(a):null,l=i?i.length:0,o=()=>{Promise.resolve().then(()=>{this.media&&this.mediaSourceOpenOrEnded&&this._onMediaSourceOpen()})};if(a&&i&&l){if(!this.tracksReady){this.hls.config.startFragPrefetch=!0,this.log("attachTransferred: waiting for SourceBuffer track info");return}if(this.log(`attachTransferred: (bufferCodecEventsTotal ${this.bufferCodecEventsTotal}) required tracks: ${bm(r,(c,d)=>c==="initSegment"?void 0:d)}; transfer tracks: ${bm(a,(c,d)=>c==="initSegment"?void 0:d)}}`),!dHt(a,r)){n.mediaSource=null,n.tracks=void 0;const c=t.currentTime,d=this.details,u=Math.max(c,(d==null?void 0:d.fragments[0].start)||0);if(u-c>1){this.log(`attachTransferred: waiting for playback to reach new tracks start time ${c} -> ${u}`);return}this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(a)}"->"${Object.keys(r)}") start time: ${u} currentTime: ${c}`),this.onMediaDetaching(Mt.MEDIA_DETACHING,{}),this.onMediaAttaching(Mt.MEDIA_ATTACHING,n),t.currentTime=u;return}this.transferData=void 0,i.forEach(c=>{const d=c,u=a[d];if(u){const h=u.buffer;if(h){const m=this.fragmentTracker,p=u.id;if(m.hasFragments(p)||m.hasParts(p)){const y=pl.getBuffered(h);m.detectEvictedFragments(d,y,p,null,null,!0)}const g=_8e(d),x=[d,h];this.sourceBuffers[g]=x,h.updating&&this.operationQueue&&this.operationQueue.prependBlocker(d),this.trackSourceBuffer(d,u)}}}),o(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),o()}get mediaSourceOpenOrEnded(){var t;const n=(t=this.mediaSource)==null?void 0:t.readyState;return n==="open"||n==="ended"}onMediaDetaching(t,n){const r=!!n.transferMedia;this.transferData=this.overrides=void 0;const{media:a,mediaSource:i,_objectUrl:l}=this;if(i){if(this.log(`media source ${r?"transferring":"detaching"}`),r)this.sourceBuffers.forEach(([o])=>{o&&this.removeBuffer(o)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){const o=i.readyState==="open";try{const c=i.sourceBuffers;for(let d=c.length;d--;)o&&c[d].abort(),i.removeSourceBuffer(c[d]);o&&i.endOfStream()}catch(c){this.warn(`onMediaDetaching: ${c.message} while calling endOfStream`)}}this.sourceBufferCount&&this.onBufferReset()}Bu(i,"sourceopen",this._onMediaSourceOpen),Bu(i,"sourceended",this._onMediaSourceEnded),Bu(i,"sourceclose",this._onMediaSourceClose),this.appendSource&&(Bu(i,"startstreaming",this._onStartStreaming),Bu(i,"endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}a&&(Bu(a,"emptied",this._onMediaEmptied),Bu(a,"error",this._onMediaError),Bu(a,"seeking",this._onStartStreaming),r||(l&&self.URL.revokeObjectURL(l),this.mediaSrc===l?(a.removeAttribute("src"),this.appendSource&&$_t(a),a.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null)}onBufferReset(){this.sourceBuffers.forEach(([t])=>{t&&this.resetBuffer(t)}),this.initTracks()}resetBuffer(t){var n;const r=(n=this.tracks[t])==null?void 0:n.buffer;if(this.removeBuffer(t),r)try{var a;(a=this.mediaSource)!=null&&a.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(r)}catch(i){this.warn(`onBufferReset ${t}`,i)}delete this.tracks[t]}removeBuffer(t){this.removeBufferListeners(t),this.sourceBuffers[_8e(t)]=[null,null];const n=this.tracks[t];n&&(this.clearBufferAppendTimeoutId(n),n.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new S$n(this.tracks)}onBufferCodecs(t,n){var r;const a=this.tracks,i=Object.keys(n);this.log(`BUFFER_CODECS: "${i}" (current SB count ${this.sourceBufferCount})`);const l="audiovideo"in n&&(a.audio||a.video)||a.audiovideo&&("audio"in n||"video"in n),o=!l&&this.sourceBufferCount&&this.media&&i.some(c=>!a[c]);if(l||o){this.warn(`Unsupported transition between "${Object.keys(a)}" and "${i}" SourceBuffers`);return}i.forEach(c=>{var d,u;const h=n[c],{id:m,codec:p,levelCodec:g,container:x,metadata:y,supplemental:v}=h;let _=a[c];const j=(d=this.transferData)==null||(d=d.tracks)==null?void 0:d[c],C=j!=null&&j.buffer?j:_,A=(C==null?void 0:C.pendingCodec)||(C==null?void 0:C.codec),M=C==null?void 0:C.levelCodec;_||(_=a[c]={buffer:void 0,listeners:[],codec:p,supplemental:v,container:x,levelCodec:g,metadata:y,id:m});const I=pke(A,M),P=I==null?void 0:I.replace(B_t,"$1");let R=pke(p,g);const O=(u=R)==null?void 0:u.replace(B_t,"$1");R&&I&&P!==O&&(c.slice(0,5)==="audio"&&(R=nCe(R,this.appendSource)),this.log(`switching codec ${A} to ${R}`),R!==(_.pendingCodec||_.codec)&&(_.pendingCodec=R),_.container=x,this.appendChangeType(c,x,R))}),(this.tracksReady||this.sourceBufferCount)&&(n.tracks=this.sourceBufferTracks),!this.sourceBufferCount&&(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!n.video&&((r=n.audio)==null?void 0:r.id)==="main"&&(this.log("Main audio-only"),this.bufferCodecEventsTotal=1),this.mediaSourceOpenOrEnded&&this.checkPendingTracks())}get sourceBufferTracks(){return Object.keys(this.tracks).reduce((t,n)=>{const r=this.tracks[n];return t[n]={id:r.id,container:r.container,codec:r.codec,levelCodec:r.levelCodec},t},{})}appendChangeType(t,n,r){const a=`${n};codecs=${r}`,i={label:`change-type=${a}`,execute:()=>{const l=this.tracks[t];if(l){const o=l.buffer;o!=null&&o.changeType&&(this.log(`changing ${t} sourceBuffer type to ${a}`),o.changeType(a),l.codec=r,l.container=n)}this.shiftAndExecuteNext(t)},onStart:()=>{},onComplete:()=>{},onError:l=>{this.warn(`Failed to change ${t} SourceBuffer type`,l)}};this.append(i,t,this.isPending(this.tracks[t]))}blockAudio(t){var n;const r=t.start,a=r+t.duration*.05;if(((n=this.fragmentTracker.getAppendedFrag(r,Ji.MAIN))==null?void 0:n.gap)===!0)return;const l={label:"block-audio",execute:()=>{var o,c;(this.lastVideoAppendEnd>a||pl.isBuffered((o=this.tracks.video)==null?void 0:o.buffer,a)||((c=this.fragmentTracker.getAppendedFrag(a,Ji.MAIN))==null?void 0:c.gap)===!0)&&this.unblockAudio()},onStart:()=>{},onComplete:()=>{},onError:o=>{this.warn("Error executing block-audio operation",o)}};this.append(l,"audio",!0)}unblockAudio(){this.operationQueue&&this.operationQueue.unblockAudio()}onBufferAppending(t,n){const{tracks:r}=this,{data:a,type:i,parent:l,frag:o,part:c,chunkMeta:d,offset:u}=n,h=d.buffering[i],m=Lp(o)&&!c&&!o.gap&&!d.partial&&!d.iframe;let p=null,g=!1;const{sn:x,cc:y}=o,v=self.performance.now();h.start=v;const _=o.stats.buffering,j=c?c.stats.buffering:null;_.start===0&&(_.start=v),(j==null?void 0:j.start)===0&&(j.start=v);const C=r.audio;let A=!1;i==="audio"&&(C==null?void 0:C.container)==="audio/mpeg"&&(A=!this.lastMpegAudioChunk||d.id===1||this.lastMpegAudioChunk.sn!==d.sn,this.lastMpegAudioChunk=d);const M=r.video,I=M==null?void 0:M.buffer;if(I&&x!=="initSegment"&&u!==void 0){const O=C==null?void 0:C.buffer,B=c||o;if(i==="audio"&&l!=="main"&&!(M.ending||M.ended)&&O&&pl.getBuffered(O).length){const G=B.start+B.duration*.05,H=pl.getBuffered(I),Y=this.currentOp("video");!H.length&&!Y?this.blockAudio(B):!pl.isBuffered(I,G)&&this.lastVideoAppendEndB.duration?this.unblockAudio():this.isAudioBlocked()&&this.executeNext("audio")}}const P=(c||o).start,R={label:`append-${i}`,execute:()=>{var O;h.executeStart=self.performance.now();const B=(O=this.tracks[i])==null?void 0:O.buffer;B&&(m&&(p=pl.timeRangesToArray(pl.getBuffered(B)),g=V_t(w8e(p,o),o)),A?this.updateTimestampOffset(B,P,.1,i,x,y):u!==void 0&&mi(u)&&this.updateTimestampOffset(B,u,1e-6,i,x,y)),this.appendExecutor(a,i)},onStart:()=>{},onComplete:()=>{this.clearBufferAppendTimeoutId(this.tracks[i]);const O=self.performance.now();h.executeEnd=h.end=O,_.first===0&&(_.first=O),(j==null?void 0:j.first)===0&&(j.first=O);const B={};if(this.sourceBuffers.forEach(([U,G])=>{U&&(B[U]=pl.getBuffered(G))}),m){const U=this.getFragmentAppendProgress(o),G=B[i];if(G&&p){const H=pl.timeRangesToArray(G),Y=w8e(H,o);U.progressed||(U.progressed=Y-w8e(p,o)>A$n);const se=g&&V_t(Y,o);U.fullyBuffered[i]=(U.fullyBuffered[i]===void 0||U.fullyBuffered[i])&&se}}this.hls.trigger(Mt.BUFFER_APPENDED,{type:i,frag:o,part:c,chunkMeta:d,parent:l,timeRanges:B})},onError:O=>{var B;this.clearBufferAppendTimeoutId(this.tracks[i]);const U=O.code===DOMException.QUOTA_EXCEEDED_ERR||O.name=="QuotaExceededError"||"quota"in O;if(U&&!this._quotaEvictionPending[i]){const se=this.getBackBufferEvictionTarget(i,a.byteLength,o.type);if(se>0){this._quotaEvictionPending[i]=!0,this.log(`QuotaExceededError on "${i}" append sn: ${x} - evicting back buffer to ${se.toFixed(3)}s and retrying`);const ee=this.getFlushOp(i,0,se),oe=this.getClearEvictionPendingOp(i);this.insertNext([ee,R,oe],i);return}this.warn(`QuotaExceededError on "${i}" sn: ${x} - no back buffer available to evict`)}m&&(this.getFragmentAppendProgress(o).errored=!0);const G={type:xo.MEDIA_ERROR,parent:l,details:er.BUFFER_APPEND_ERROR,sourceBufferName:i,frag:o,part:c,chunkMeta:d,error:O,err:O,fatal:!1},H=(B=this.media)==null?void 0:B.error;if(O.name===jGt&&this.sourceBufferCount===0&&(!this.media||this.pendingTrackCount===0))G.errorAction=cZ(!0);else{var Y;U&&(G.details=er.BUFFER_FULL_ERROR);const se=++this.appendErrors[i],ee=this.hls.config.appendErrorMaxRetry;this.warn(`Failed ${se}/${ee+1} times to append segment in "${i}" sourceBuffer with error: ${O.message}`),se>=ee&&(G.fatal=!U);const oe=(Y=this.mediaSource)==null?void 0:Y.readyState;(oe==="ended"||oe==="closed"||H)&&(this.warn(`MediaSource readyState "${oe}" during SourceBuffer${U_t(G.fatal,H)}`),G.details=er.MEDIA_SOURCE_REQUIRES_RESET)}this.appendError=G,this.hls.trigger(Mt.ERROR,G),U&&this.hls&&this.trimBuffers(o.start,1)}};this.log(`queuing "${i}" append sn: ${x}${c?" p: "+c.index:""} of ${l} playlist ${o.level} cc: ${y} offset: ${u} bytes: ${a.byteLength}`),this.append(R,i,this.isPending(this.tracks[i]))}getClearEvictionPendingOp(t){return{label:"clear",execute:()=>{this._quotaEvictionPending[t]=!1,this.shiftAndExecuteNext(t)},onStart:()=>{},onComplete:()=>{},onError:()=>{}}}getFlushOp(t,n,r){return this.log(`queuing "${t}" remove ${n}-${r}`),{label:"remove",execute:()=>{this.removeExecutor(t,n,r)},onStart:()=>{},onComplete:()=>{var a;const i=(a=this.tracks[t])==null?void 0:a.buffer;this.log(`Remove request ${n}-${r} from ${t} Source Buffer complete > buffer: ${i?dCe(pl.getBuffered(i)):"(detached)"}`),this.hls.trigger(Mt.BUFFER_FLUSHED,{type:t,start:n,end:r})},onError:a=>{this.warn(`Failed to remove ${n}-${r} from "${t}" SourceBuffer`,a),this.hls.trigger(Mt.BUFFER_FLUSHED,{type:t,start:0,end:0,error:a})}}}onBufferFlushing(t,n){const{type:r,startOffset:a,endOffset:i}=n;(!r||r==="audio")&&this.unblockAudio(),r?this.append(this.getFlushOp(r,a,i),r):this.sourceBuffers.forEach(([l])=>{l&&this.append(this.getFlushOp(l,a,i),l)})}onFragParsed(t,n){const{frag:r,part:a,chunkMeta:i}=n,l=[],o=a?a.elementaryStreams:r.elementaryStreams;o[Xh.AUDIOVIDEO]?l.push("audiovideo"):(o[Xh.AUDIO]&&l.push("audio"),o[Xh.VIDEO]&&l.push("video"));const c=()=>{const d=self.performance.now();r.stats.buffering.end=d,a&&(a.stats.buffering.end=d);const u=a?a.stats:r.stats;this.checkAppendProgress(r,a,i,l),this.hls&&(this.hls.trigger(Mt.FRAG_BUFFERED,{frag:r,part:a,stats:u,id:r.type,chunkMeta:i}),!a&&r.gap&&u.retry&&this.log(`Nothing buffered for ${r.type} level: ${r.level} sn: ${r.sn} retries ${u.retry}`))};l.length===0&&this.log(`Fragments must have at least one ElementaryStreamType set. ${r.type} ${r.level} ${a?`part: ${a.index} of `:""}sn: ${r.sn}`),this.blockBuffers(c,l).catch(d=>{this.warn(`Fragment buffered callback ${d.message}`),this.stepOperationQueue(this.sourceBufferTypes)})}onFragChanged(t,n){var r,a;const i=(r=this.hls)==null?void 0:r.config;if(!i)return;const{backBufferLength:l,frontBufferFlushThreshold:o}=i;this.trimBuffers(o,l,n.frag,n.previousFrag);const c=n.frag.elementaryStreams,{appendErrors:d}=this,u=(a=this.appendError)==null?void 0:a.sourceBufferName;Object.keys(c).forEach(h=>{c[h]&&(d[h]=0,h===u&&(this.appendError=void 0),h==="audio"||h==="video"?(d.audiovideo=0,u==="audiovideo"&&(this.appendError=void 0)):(d.audio=0,d.video=0,u!=="audiovideo"&&(this.appendError=void 0)))})}get bufferedToEnd(){return this.sourceBufferCount>0&&!this.sourceBuffers.some(([t])=>{if(t){const n=this.tracks[t];if(n)return!n.ended||n.ending}return!1})}onBufferEos(t,n){var r;this.sourceBuffers.forEach(([l])=>{if(l){const o=this.tracks[l];(!n.type||n.type===l)&&(o.ending=!0,o.ended||(o.ended=!0,this.log(`${l} buffer reached EOS`)))}});const a=((r=this.overrides)==null?void 0:r.endOfStream)!==!1;this.sourceBufferCount>0&&!this.sourceBuffers.some(([l])=>{var o;return l&&!((o=this.tracks[l])!=null&&o.ended)})?(this.unblockAudio(),a?(this.log("Queueing EOS"),this.blockUntilOpen(()=>{this.tracksEnded();const{mediaSource:l}=this;if((l==null?void 0: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(Mt.BUFFERED_TO_END,void 0)})):(this.tracksEnded(),this.hls.trigger(Mt.BUFFERED_TO_END,void 0))):n.type==="video"&&this.unblockAudio()}tracksEnded(){this.sourceBuffers.forEach(([t])=>{if(t!==null){const n=this.tracks[t];n&&(n.ending=!1)}})}onLevelUpdated(t,{details:n}){n.fragments.length&&(this.details=n,this.updateDuration())}updateDuration(){this.blockUntilOpen(()=>{const t=this.getDurationAndRange();t&&this.updateMediaSource(t)})}onError(t,n){if(n.details===er.BUFFER_APPEND_ERROR&&n.frag){var r;const a=(r=n.errorAction)==null?void 0:r.nextAutoLevel;mi(a)&&a!==n.frag.level&&this.resetAppendErrors()}}getBackBufferEvictionTarget(t,n,r){const{media:a}=this;return a?this.fragmentTracker.getBackBufferEvictionEnd(a.currentTime,r,n):0}getFragmentAppendProgress(t){var n;const r=q_t(t);let a=this.fragmentAppendProgress[r];return((n=a)==null?void 0:n.stats)!==t.stats&&(a={stats:t.stats,progressed:!1,errored:!1,fullyBuffered:Object.create(null)},this.fragmentAppendProgress[r]=a),a}checkAppendProgress(t,n,r,a){if(n||!Lp(t)||t.gap||r.iframe||r.partial)return;const i=q_t(t),l=this.fragmentAppendProgress[i];delete this.fragmentAppendProgress[i];const o=t.stats.buffering;if(o.start&&!o.first)return;const c=(l==null?void 0:l.stats)===t.stats?l:void 0;if(c!=null&&c.errored)return;const d=a.length>0&&a.every(p=>(c==null?void 0:c.fullyBuffered[p])===!0);if(c!=null&&c.progressed||d){delete this.appendsWithoutProgress[i];return}if(!c&&a.length===0)return;const u=(this.appendsWithoutProgress[i]||0)+1,h=this.hls;u>=h.config.appendErrorMaxRetry?delete this.appendsWithoutProgress[i]:this.appendsWithoutProgress[i]=u,this.warn(`Fragment ${t.sn} of ${t.type} playlist ${t.level} appended ${u} time${u>1?"s":""} without buffered range growth`),h.trigger(Mt.ERROR,{type:xo.MEDIA_ERROR,details:er.BUFFER_APPEND_NO_PROGRESS,fatal:!1,frag:t,chunkMeta:r,parent:t.type,appendsWithoutProgress:u,error:new Error(`Fragment append did not increase buffered coverage (${u})`)})}resetAppendProgress(){this.fragmentAppendProgress=Object.create(null),this.appendsWithoutProgress=Object.create(null)}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0},this.appendError=void 0}trimBuffers(t,n,r,a){const{hls:i,details:l,media:o}=this;if(!o||l===null||!this.sourceBufferCount)return;const c=i.config,d=o.currentTime,u=l.levelTargetDuration;n=l.live&&c.liveBackBufferLength!==null?c.liveBackBufferLength:n;let h=-1/0;if(mi(n)&&n>=0){const m=Math.max(n,u);h=Math.floor(d/u)*u-m}if(r){const m=this.getLoopBackBufferFlushEnd(r,a??null);m>0&&(h=Math.max(h,m))}if(h>0&&this.flushBackBuffer(d,u,h),mi(t)&&t>0){const m=Math.max(c.maxBufferLength,t),p=Math.max(m,u),g=Math.floor(d/u)*u+p;this.flushFrontBuffer(d,u,g)}}getLoopBackBufferFlushEnd(t,n){var r;const{media:a}=this;if(((r=this.hls)==null?void 0:r.config.loopBackBufferFlush)===!1||!(a!=null&&a.loop)||!n||t.level<=n.level)return 0;const{video:i,audiovideo:l}=t.elementaryStreams;if(i!=null&&i.partial||l!=null&&l.partial)return 0;const o=this.getEarliestElementaryStreamStart(t)-C$n;return o<=0?0:(this.log(`Flushing lower quality back buffer for loop: level ${t.level}, range [0-${o.toFixed(3)}]`),o)}getEarliestElementaryStreamStart(t){const{audio:n,video:r,audiovideo:a}=t.elementaryStreams;let i=t.start;return a?i=Math.min(i,a.startDTS):(n&&(i=Math.min(i,n.startDTS)),r&&(i=Math.min(i,r.startDTS))),i}flushBackBuffer(t,n,r){this.sourceBuffers.forEach(([a,i])=>{if(i){const d=pl.getBuffered(i);if(d.length>0&&r>d.start(0)){var l,o,c;this.hls.trigger(Mt.BACK_BUFFER_REACHED,{bufferEnd:r});const u=this.tracks[a];if((l=this.details)!=null&&l.live)this.hls.trigger(Mt.LIVE_BACK_BUFFER_REACHED,{bufferEnd:r});else if(u!=null&&u.ended&&!((o=this.media)!=null&&o.loop&&((c=this.hls)==null?void 0:c.config.loopBackBufferFlush)!==!1)){this.log(`Cannot flush ${a} back buffer while SourceBuffer is in ended state`);return}this.hls.trigger(Mt.BUFFER_FLUSHING,{startOffset:0,endOffset:r,type:a})}}})}flushFrontBuffer(t,n,r){this.sourceBuffers.forEach(([a,i])=>{if(i){const l=pl.getBuffered(i),o=l.length;if(o<2)return;const c=l.start(o-1),d=l.end(o-1);if(r>c||t>=c&&t<=d)return;this.hls.trigger(Mt.BUFFER_FLUSHING,{startOffset:c,endOffset:1/0,type:a})}})}getDurationAndRange(){var t;const{details:n,mediaSource:r}=this;if(!n||!this.media||(r==null?void 0:r.readyState)!=="open")return null;const a=n.edge;if(n.live&&this.hls.config.liveDurationInfinity){if(n.fragments.length&&r.setLiveSeekableRange){const d=Math.max(0,n.fragmentStart),u=Math.max(d,a);return{duration:1/0,start:d,end:u}}return{duration:1/0}}const i=(t=this.overrides)==null?void 0:t.duration;if(i)return mi(i)?{duration:i}:null;const l=this.media.duration,o=mi(r.duration)?r.duration:0;return a>o&&a>l||!mi(l)?{duration:a}:null}updateMediaSource({duration:t,start:n,end:r}){const a=this.mediaSource;!a||!this.media||a.readyState!=="open"||(a.duration!==t&&(mi(t)&&this.log(`Updating MediaSource duration to ${t.toFixed(3)}`),a.duration=t),n!==void 0&&r!==void 0&&(this.log(`MediaSource duration is set to ${a.duration}. Setting seekable range to ${n}-${r}.`),a.setLiveSeekableRange(n,r)))}get tracksReady(){const t=this.pendingTrackCount;return t>0&&(t>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){const{bufferCodecEventsTotal:t,pendingTrackCount:n,tracks:r}=this;if(this.log(`checkPendingTracks (pending: ${n} codec events expected: ${t}) ${bm(r)}`),this.tracksReady){var a;const i=(a=this.transferData)==null?void 0:a.tracks;i&&Object.keys(i).length?this.attachTransferred():this.createSourceBuffers()}}bufferCreated(){if(this.sourceBufferCount){const t={};this.sourceBuffers.forEach(([n,r])=>{if(n){const a=this.tracks[n];t[n]={buffer:r,container:a.container,codec:a.codec,supplemental:a.supplemental,levelCodec:a.levelCodec,id:a.id,metadata:a.metadata}}}),this.hls.trigger(Mt.BUFFER_CREATED,{tracks:t}),this.log(`SourceBuffers created. Running queue: ${this.operationQueue}`),this.sourceBuffers.forEach(([n])=>{this.executeNext(n)})}else{const t=new Error("could not create source buffer for media codec(s)");this.hls.trigger(Mt.ERROR,{type:xo.MEDIA_ERROR,details:er.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:t,reason:t.message})}}createSourceBuffers(){const{tracks:t,sourceBuffers:n,mediaSource:r}=this;if(!r)throw new Error("createSourceBuffers called when mediaSource was null");for(const i in t){const l=i,o=t[l];if(this.isPending(o)){const c=this.getTrackCodec(o,l),d=`${o.container};codecs=${c}`;o.codec=c,this.log(`creating sourceBuffer(${d})${this.currentOp(l)?" Queued":""} ${bm(o)}`);try{const u=r.addSourceBuffer(d),h=_8e(l),m=[l,u];n[h]=m,o.buffer=u}catch(u){var a;this.error(`error while trying to add sourceBuffer: ${u.message}`),this.shiftAndExecuteNext(l),(a=this.operationQueue)==null||a.removeBlockers(),delete this.tracks[l],this.hls.trigger(Mt.ERROR,{type:xo.MEDIA_ERROR,details:er.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:u,sourceBufferName:l,mimeType:d,parent:o.id});return}this.trackSourceBuffer(l,o)}}this.bufferCreated()}clearBufferAppendTimeoutId(t){t&&(self.clearTimeout(t.bufferAppendTimeoutId),t.bufferAppendTimeoutId=void 0)}getTrackCodec(t,n){const r=t.supplemental;let a=t.codec;r&&(n==="video"||n==="audiovideo")&&yQ(r,"video")&&(a=jzn(a,r));const i=pke(a,t.levelCodec);return i?n.slice(0,5)==="audio"?nCe(i,this.appendSource):i:""}trackSourceBuffer(t,n){const r=n.buffer;if(!r)return;const a=this.getTrackCodec(n,t);this.tracks[t]={buffer:r,codec:a,container:n.container,levelCodec:n.levelCodec,supplemental:n.supplemental,metadata:n.metadata,id:n.id,listeners:[]},this.removeBufferListeners(t),this.addBufferListener(t,"updatestart",this.onSBUpdateStart),this.addBufferListener(t,"updateend",this.onSBUpdateEnd),this.addBufferListener(t,"error",this.onSBUpdateError),this.appendSource&&this.addBufferListener(t,"bufferedchange",(i,l)=>{const o=l.removedRanges;o!=null&&o.length&&(this.log(`${i} buffer removed ${dCe(o)}`),this.hls.trigger(Mt.BUFFER_FLUSHED,{type:i,start:o.start(0),end:o.end(o.length-1)}))})}get mediaSrc(){var t,n;const r=((t=this.media)==null||(n=t.querySelector)==null?void 0:n.call(t,"source"))||this.media;return r==null?void 0:r.src}onSBUpdateStart(t){const n=this.currentOp(t);n&&n.onStart()}onSBUpdateEnd(t){var n,r;if(((n=this.mediaSource)==null?void 0:n.readyState)==="closed"){this.resetBuffer(t);return}const a=this.currentOp(t);if(!a)return;if(a.onComplete(),(r=this.tracks[t])==null||(r=r.buffer)==null?void 0:r.updating){this.log(`${t} SourceBuffer updating on "updateend"`),this.blockUntilOpen(()=>{this.shiftAndExecuteNext(t)});return}this.shiftAndExecuteNext(t)}onSBUpdateError(t,n){var r;const a=(r=this.mediaSource)==null?void 0:r.readyState,i=new Error(`${t} SourceBuffer error. MediaSource readyState: ${a}`);this.error(`${i.message}`,n),this.hls.trigger(Mt.ERROR,{type:xo.MEDIA_ERROR,details:er.BUFFER_APPENDING_ERROR,sourceBufferName:t,error:i,fatal:!1});const l=this.currentOp(t);l&&l.onError(i)}updateTimestampOffset(t,n,r,a,i,l){const o=n-t.timestampOffset;Math.abs(o)>=r&&(this.log(`Updating ${a} SourceBuffer timestampOffset to ${n} (sn: ${i} cc: ${l})`),t.timestampOffset=n)}removeExecutor(t,n,r){const{media:a,mediaSource:i}=this,l=this.tracks[t],o=l==null?void 0:l.buffer;if(!a||!i||!o)throw new Error(`Attempting to remove from the ${t} SourceBuffer, but it does not exist`);const c=mi(a.duration)?a.duration:1/0,d=mi(i.duration)?i.duration:1/0,u=Math.max(0,n);if(u>=d){var h;(h=this.currentOp(t))==null||h.onComplete(),this.shiftAndExecuteNext(t);return}const m=Math.min(r,c,d);if(m>u&&(!l.ending||l.ended))l.ended=!1,this.log(`Removing [${u},${m}] from the ${t} SourceBuffer`),o.remove(u,m);else throw new Error(`Cannot remove ${m<=u?`invalid range (${u} >= ${m}) `:""}from the ${t} SourceBuffer${l.ending?" while track ending":""}`)}appendExecutor(t,n){const r=this.tracks[n],a=r==null?void 0:r.buffer;if(!a)throw new E$n(`Attempting to append to the ${n} SourceBuffer, but it does not exist`);if(r.ending=!1,r.ended=!1,this.hls.config.appendTimeout!==1/0){const i=this.calculateAppendTimeoutTime(a);r.bufferAppendTimeoutId=self.setTimeout(()=>this.appendTimeoutHandler(n,a,i),i)}a.appendBuffer(t)}appendTimeoutHandler(t,n,r){this.log(`Received timeout after ${r}ms for append on ${t} source buffer. Aborting and triggering error.`);try{n.abort()}catch{this.log(`Failed to abort append on ${t} source buffer after timeout.`)}const a=this.currentOp(t);a&&a.onError(new Error(`${t}-append-timeout`))}calculateAppendTimeoutTime(t){let n=VHt;this.details&&(n=this.details.levelTargetDuration);let r=2*n*1e3;if(this.media===null)return r;const a=pl.bufferInfo(t,this.media.currentTime,0);return a.len?(r=Math.max(a.len*1e3,r),Math.max(this.hls.config.appendTimeout,r)):r}blockUntilOpen(t){if(this.isUpdating()||this.isQueued())this.blockBuffers(t).catch(n=>{this.warn(`SourceBuffer blocked callback ${n}`),this.stepOperationQueue(this.sourceBufferTypes)});else try{t()}catch(n){this.warn(`Callback run without blocking ${this.operationQueue} ${n}`)}}isUpdating(){return this.sourceBuffers.some(([t,n])=>t&&n.updating)}isQueued(){return this.sourceBuffers.some(([t])=>t&&!!this.currentOp(t))}isPending(t){return!!t&&!t.buffer}isAudioBlocked(){var t;return((t=this.currentOp("audio"))==null?void 0:t.label)==="block-audio"}isAudioBlocking(){return this.operationQueue?this.operationQueue.audioBlocking():!1}blockBuffers(t,n=this.sourceBufferTypes){if(!n.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(t);const{operationQueue:r}=this,i=n.length===2&&this.isAudioBlocking()?[this.appendBlocker("video")]:n.map(l=>this.appendBlocker(l));return Promise.all(i).then(l=>{r===this.operationQueue&&(t(),this.stepOperationQueue(this.sourceBufferTypes))})}stepOperationQueue(t){t.forEach(n=>{var r;const a=(r=this.tracks[n])==null?void 0:r.buffer;!a||a.updating||n==="audio"&&this.isAudioBlocked()||this.shiftAndExecuteNext(n)})}append(t,n,r){this.operationQueue&&this.operationQueue.append(t,n,r)}insertNext(t,n){this.operationQueue&&this.operationQueue.insertNext(t,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,n)=>t+(this.isPending(this.tracks[n])?1:0),0)}get sourceBufferCount(){return this.sourceBuffers.reduce((t,[n])=>t+(n?1:0),0)}get sourceBufferTypes(){return this.sourceBuffers.map(([t])=>t).filter(t=>!!t)}addBufferListener(t,n,r){const a=this.tracks[t];if(!a)return;const i=a.buffer;if(!i)return;const l=r.bind(this,t);a.listeners.push({event:n,listener:l}),th(i,n,l)}removeBufferListeners(t){const n=this.tracks[t];if(!n)return;const r=n.buffer;r&&(n.listeners.forEach(a=>{Bu(r,a.event,a.listener)}),n.listeners.length=0)}}function $_t(s){const t=s.querySelectorAll("source");[].slice.call(t).forEach(n=>{s.removeChild(n)})}function M$n(s,t){const n=self.document.createElement("source");n.type="video/mp4",n.src=t,s.appendChild(n)}function _8e(s){return s==="audio"?1:0}function U_t(s,t){return`${s?"":" - triggering recovery"}${t?" with HTMLMediaElement Error: "+t.message:""}`}function q_t(s){return`${s.type}_${s.sn}_${s.level}`}function w8e(s,t){const{start:n,end:r}=t;let a=0;for(let i=0;i=r)break;const o=Math.max(n,l.start),c=Math.min(r,l.end);c>o&&(a+=c-o)}return a}function V_t(s,t){return t.duration-s<=.05}class WQe{constructor(t){this.hls=null,this.autoLevelCapping=void 0,this.media=void 0,this.restrictedLevels=void 0,this.timer=void 0,this.observer=void 0,this.clientRect=void 0,this.streamController=void 0,this.hls=t,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.media=null,this.restrictedLevels=[],this.clientRect=null,this.registerListeners()}setStreamController(t){this.streamController=t}destroy(){this.hls&&this.unregisterListener(),(this.timer||this.observer)&&this.stopCapping(),this.media=this.clientRect=this.hls=null,this.streamController=void 0}registerListeners(){const{hls:t}=this;t&&(t.on(Mt.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.on(Mt.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(Mt.MANIFEST_PARSED,this.onManifestParsed,this),t.on(Mt.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(Mt.BUFFER_CODECS,this.onBufferCodecs,this),t.on(Mt.MEDIA_DETACHING,this.onMediaDetaching,this))}unregisterListener(){const{hls:t}=this;t&&(t.off(Mt.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.off(Mt.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(Mt.MANIFEST_PARSED,this.onManifestParsed,this),t.off(Mt.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(Mt.BUFFER_CODECS,this.onBufferCodecs,this),t.off(Mt.MEDIA_DETACHING,this.onMediaDetaching,this))}onFpsDropLevelCapping(t,n){if(!this.hls)return;const r=this.hls.levels[n.droppedLevel];this.isLevelAllowed(r)&&this.restrictedLevels.push({bitrate:r.bitrate,height:r.height,width:r.width})}onMediaAttaching(t,n){const r=n.media;this.clientRect=null,this.hls&&(r instanceof HTMLVideoElement?(this.media=r,this.hls.config.capLevelToPlayerSize&&this.observe()):this.media=null,(this.timer||this.observer)&&this.hls.levels.length>1&&this.detectPlayerSize())}onManifestParsed(t,n){this.restrictedLevels=[],n.video&&this.startCapping()}onLevelsUpdated(t,{levels:n}){(this.timer||this.observer)&&mi(this.autoLevelCapping)?this.detectPlayerSize():this.observer===void 0&&this.timer===void 0&&n.length>1&&n.some(r=>!!r.videoCodec)&&this.startCapping()}onBufferCodecs(t,n){n.video&&this.startCapping()}onMediaDetaching(){this.stopCapping(),this.media=null}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0||!this.hls){this.clientRect=null;return}const t=this.hls.levels;if(t.length>1){const n=this.hls,r=this.getMaxLevel(t.length-1);r!==this.autoLevelCapping&&n.logger.log(`Setting autoLevelCapping to ${r}: ${t[r].height}p@${t[r].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),n.autoLevelCapping=r,n.autoLevelEnabled&&n.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=n.autoLevelCapping}else t.length===1&&this.stopCapping()}}getMaxLevel(t){if(!this.hls)return-1;const n=this.hls.levels;if(!n.length)return-1;const r=n.filter((a,i)=>this.isLevelAllowed(a)&&i<=t);return this.observer||(this.clientRect=null),WQe.getMaxLevelByMediaSize(r,this.mediaWidth,this.mediaHeight)}observe(){const t=self.ResizeObserver;t&&(this.observer=new t(n=>{var r;const a=(r=n[0])==null?void 0:r.contentRect;a&&(this.clientRect=a,this.detectPlayerSize())})),this.observer&&this.media&&this.observer.observe(this.media)}startCapping(){var t;this.timer||this.observer||!((t=this.hls)!=null&&t.config.capLevelToPlayerSize)||(self.clearInterval(this.timer),this.timer=void 0,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.observe(),this.observer||(this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3)),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0),this.observer&&(this.observer.disconnect(),this.observer=void 0)}getDimensions(){if(this.clientRect)return this.clientRect;const t=this.media,n={width:0,height:0};if(t){const r=t.getBoundingClientRect();n.width=r.width,n.height=r.height,!n.width&&!n.height&&(n.width=r.right-r.left||t.width||0,n.height=r.bottom-r.top||t.height||0)}return this.clientRect=n,n}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let t=1;if(!this.hls)return t;const{ignoreDevicePixelRatio:n,maxDevicePixelRatio:r}=this.hls.config;if(!n)try{t=self.devicePixelRatio}catch{}return Math.min(t,r)}isLevelAllowed(t){return!this.restrictedLevels.some(r=>t.bitrate===r.bitrate&&t.width===r.width&&t.height===r.height)}static getMaxLevelByMediaSize(t,n,r){if(!(t!=null&&t.length))return-1;const a=(o,c)=>c?o.width!==c.width||o.height!==c.height:!0;let i=t.length-1;const l=Math.max(n,r);for(let o=0;o=l||c.height>=l)&&a(c,t[o+1])){i=o;break}}return i}}var R_=class pqe{constructor(t,n){Array.isArray(t)&&(t=t.map(r=>r instanceof pqe?r:new pqe(r))),this.value=t,this.params=n}};const P$n="Dict";function I$n(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 L$n(s,t,n,r){return new Error(`failed to ${s} "${I$n(t)}" as ${n}`,{cause:r})}const H_t="Bare Item",R$n="Boolean",D$n="Byte Sequence",O$n="Decimal",F$n="Integer";function z$n(s){return s<-999999999999999||99999999999999912)throw X5(s,O$n);const n=t.toString();return n.includes(".")?n:`${n}.0`}function K$n(s){if($$n.test(s))throw X5(s,B$n);return`"${s.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function Y$n(s){return s.description||s.toString().slice(7,-1)}function G_t(s){const t=Y$n(s);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(t)===!1)throw X5(t,U$n);return t}function gqe(s){switch(typeof s){case"number":if(!mi(s))throw X5(s,H_t);return Number.isInteger(s)?kGt(s):W$n(s);case"string":return K$n(s);case"symbol":return G_t(s);case"boolean":return V$n(s);case"object":if(s instanceof Date)return G$n(s);if(s instanceof Uint8Array)return H$n(s);if(s instanceof NGt)return G_t(s);default:throw X5(s,H_t)}}function xqe(s){if(/^[a-z*][a-z0-9\-_.*]*$/.test(s)===!1)throw X5(s,q$n);return s}function KQe(s){return s==null?"":Object.entries(s).map(([t,n])=>n===!0?`;${xqe(t)}`:`;${xqe(t)}=${gqe(n)}`).join("")}function SGt(s){return s instanceof R_?`${gqe(s.value)}${KQe(s.params)}`:gqe(s)}function Z$n(s){return`(${s.value.map(SGt).join(" ")})${KQe(s.params)}`}function X$n(s,t={whitespace:!0}){if(typeof s!="object"||s==null)throw X5(s,P$n);const n=s instanceof Map?s.entries():Object.entries(s),r=t!=null&&t.whitespace?" ":"";return Array.from(n).map(([a,i])=>{i instanceof R_||(i=new R_(i));let l=xqe(a);return i.value===!0?l+=KQe(i.params):(l+="=",Array.isArray(i.value)?l+=Z$n(i):l+=SGt(i)),l}).join(`,${r}`)}function CGt(s,t){return X$n(s,t)}const Q$n=["url"],J$n=["version","eventTargets","sid","transmissionMode"],eUn=["customData","headers"],W_t=s=>s instanceof R_?new R_(Math.round(s.value),s.params):Math.round(s),j8e=s=>Array.isArray(s)?s.map(W_t):W_t(s),yqe=(s,t)=>Array.isArray(s)?s.map(n=>yqe(n,t)):s instanceof R_&&typeof s.value=="string"?new R_(yqe(s.value,t),s.params):(t.baseUrl&&(s=O9n(s,D9n(t.baseUrl))),t.version===1?encodeURIComponent(s):s),K_t=s=>s instanceof R_?new R_(Math.round(s.value/100)*100,s.params):Math.round(s/100)*100,uie=s=>Array.isArray(s)?s.map(K_t):K_t(s),tUn=(s,t)=>{let n=s;return t.version>=2&&(s instanceof R_&&typeof s.value=="string"?n=new R_([s]):typeof s=="string"&&(n=[s])),yqe(n,t)},sUn={br:j8e,d:j8e,bl:uie,dl:uie,mtp:uie,nor:tUn,rtp:uie,tb:j8e},kQ=2,AGt="bc",nUn="ps",EGt="pr",rUn="e",Y_t="t",aUn="c",TGt="b",YQe="rr",MGt="ce",hie={BITRATE_CHANGE:AGt,ERROR:rUn,RESPONSE_RECEIVED:YQe,CUSTOM_EVENT:MGt},PGt=new Map([[nUn,"sta"],[EGt,"pr"],[aUn,"cid"],[TGt,"bg"],[AGt,"br"]]),ZQe="event",XQe="request",IGt=["cen","e","h","ts"],LGt=["ab","bg","bl","br","bs","bsa","bsd","bsda","cdn","cid","cs","d","dfa","dl","ec","lab","lb","ltc","msd","mtp","nor","nr","ot","pb","pr","pt","rtp","sf","sid","sn","st","sta","su","tab","tb","tbl","tpb","v"],iUn=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function QQe(s){return iUn.test(s)}const oUn=new Set(LGt);function RGt(s){return oUn.has(s)||QQe(s)}const DGt=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"],lUn=new Set(DGt);function OGt(s){return lUn.has(s)}const cUn=new Set(IGt);function dUn(s){return RGt(s)||OGt(s)||cUn.has(s)}const uUn=new Set(["ab","bl","br","bsa","bsd","bsda","lab","lb","mtp","pb","tab","tb","tbl","tpb"]),KTe=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"],hUn=new Set(KTe);function mUn(s){return hUn.has(s)||QQe(s)}const fUn=new Set(["ot","sf","st","e","sta"]);function pUn(s){return fUn.has(s)}function gUn(s){return typeof s=="number"?mi(s):s!=null&&s!==""&&s!==!1}const xUn={[ZQe]:dUn,[XQe]:RGt};function FGt(s,t){if(Array.isArray(s)){let n;return t&&(n=s.find(r=>{var a;return((a=r.params)==null?void 0:a.ot)===t})),n||(n=s[0]),FGt(n)}return s instanceof R_?s.value:s}function yUn(s){const t={};for(const[r,a]of Object.entries(s)){if(a==null){t[r]=a;continue}if(r==="nor"){const i=(Array.isArray(a)?a:[a])[0];if(i instanceof R_){var n;t.nor=i.value,(n=i.params)!=null&&n.r&&(t.nrr=i.params.r)}else t.nor=i}else uUn.has(r)?t[r]=FGt(a,s.ot):t[r]=a}return t}function zGt(s,t={}){const n={};if(s==null||typeof s!="object")return n;const r=t.version||s.v||kQ,a=t.reportingMode||XQe,i=r===1?yUn(s):s,l=r===1?mUn:xUn[a];let o=Object.keys(i).filter(l);i.e&&i.e!==YQe&&(o=o.filter(p=>!OGt(p)));const c=t.filter;typeof c=="function"&&(o=o.filter(c));const d=a===ZQe;if(d){const p=i.e;!o.includes("e")&&p!=null&&o.push("e"),o.includes("ts")||o.push("ts"),!o.includes("cen")&&i.cen!=null&&p===MGt&&o.push("cen");const g=p?PGt.get(p):void 0;g&&i[g]!=null&&!o.includes(g)&&o.push(g)}if(o.length===0)return n;r>1&&!o.includes("v")&&o.push("v");const u={version:r,reportingMode:a,baseUrl:t.baseUrl};o.sort();for(const p of o){var h,m;let g=i[p];const x=(h=(m=t.formatters)==null?void 0:m[p])!=null?h:sUn[p];if(typeof x=="function"&&(g=x(g,u)),p==="v"){if(r===1)continue;g=r}if(p==="pr"&&g===1&&!(d&&i.e===EGt))continue;d&&p==="ts"&&!mi(g)&&(g=Date.now());const y=d&&g===!1&&p==="bg"&&i.e===TGt;!gUn(g)&&!y||(pUn(p)&&typeof g=="string"&&(g=new NGt(g)),n[p]=g)}return n}const nC="CMCD-Object",Xb="CMCD-Request",b9="CMCD-Session",fN="CMCD-Status",vUn={REQUEST:Xb},bUn={ab:nC,br:nC,d:nC,lab:nC,lb:nC,ot:nC,tab:nC,tb:nC,tpb:nC,bl:Xb,cs:Xb,dfa:Xb,dl:Xb,ltc:Xb,mtp:Xb,nor:Xb,nrr:Xb,pb:Xb,sn:Xb,sta:Xb,su:Xb,tbl:Xb,cid:b9,msd:b9,sf:b9,sid:b9,st:b9,v:b9,bg:fN,bs:fN,bsa:fN,bsd:fN,bsda:fN,cdn:fN,ec:fN,nr:fN,pr:fN,pt:fN,rtp:fN};function _Un(s){return Object.keys(s).reduce((t,n)=>{var r;return(r=s[n])==null||r.forEach(a=>t[a]=n),t},{})}function wUn(s,t){const n={};if(!s)return n;const r=Object.keys(s),a=t?_Un(t):{};for(const l of r){var i;const o=bUn[l]||a[l]||vUn.REQUEST,c=(i=n[o])!=null?i:n[o]={};c[l]=s[l]}return n}function jUn(s,t){const n={},r=wUn(s,t);for(const[a,i]of Object.entries(r)){const l=CGt(i,{whitespace:!1});l&&(n[a]=l)}return n}const Z_t="CMCD";function BGt(s){return CGt(s,{whitespace:!1})}function NUn(s,t={}){return s?BGt(zGt(s,t)):""}const kUn=30,vqe=[...KTe,...LGt,...DGt,...IGt].filter((s,t,n)=>n.indexOf(s)===t),SUn="application/cmcd",CUn=1,z0={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},pN={STARTING:"s",PLAYING:"p",SEEKING:"k",REBUFFERING:"r",PAUSED:"a",ENDED:"e",FATAL_ERROR:"f",PRELOADING:"d"},JQe="query",$Gt="headers";function X_t(s,t,n){var r;const a=new Set((r=t.enabledKeys)!=null?r:[]);return{version:t.version||kQ,reportingMode:s,filter:i=>a.has(i),baseUrl:n}}function AUn(s,t){if(s===t)return!0;if(s.length!==t.length)return!1;for(let n=0;ns,UGt=Array.from(PGt,([s,t])=>t==="br"?{event:s,field:t,equal:(n,r)=>n===void 0||r===void 0?n===r:AUn(n,r),snapshot:n=>n.slice()}:{event:s,field:t,equal:EUn,snapshot:TUn}),MUn=new Map(UGt.map(s=>[s.event,s]));function PUn(s){const{url:t}=s,n=HTe(s,Q$n);return fetch(t,n)}function IUn(s){const{version:t=kQ,eventTargets:n=[],sid:r=hHt(),transmissionMode:a=JQe}=s,i=HTe(s,J$n);return wo(wo({},i),{},{version:t,transmissionMode:a,sid:r,eventTargets:n.reduce((l,o)=>{var c,d,u;return o!=null&&o.url&&(c=o.events)!=null&&c.length&&l.push({version:o.version||kQ,enabledKeys:((d=o.enabledKeys)==null?void 0:d.slice())||[],url:o.url,events:o.events.slice(),interval:(u=o.interval)!=null?u:kUn,batchSize:o.batchSize||1}),l},[])})}var LUn=class{constructor(s,t=PUn){var n;this.timeOrigin=performance.timeOrigin||((n=performance.timing)==null?void 0:n.fetchStart)||Date.now()-performance.now(),this.data={},this.msd=NaN,this.eventTargets=new Map,this.lastEmitted={},this.requestTarget={sn:0,msdSent:!1},this.config=IUn(s),this.data={cid:this.config.cid,sid:this.config.sid,v:this.config.version},this.requester=t;for(const r of this.config.eventTargets)this.eventTargets.set(r,{intervalId:void 0,sn:0,msdSent:!1,queue:[]})}start(){this.eventTargets.forEach((s,t)=>{if(this.disarmInterval(s),t.interval===0||!t.events.includes(Y_t))return;const n=()=>{this.recordTargetEvent(s,t,Y_t),this.processEventTargets()};s.intervalId=setInterval(n,t.interval*1e3),n()})}stop(s=!1){s&&this.flush(),this.eventTargets.forEach(t=>{this.disarmInterval(t)})}flush(){this.processEventTargets(!0)}update(s){s.sid&&s.sid!==this.data.sid&&this.resetSession(),s.msd&&!isNaN(s.msd)&&(this.msd=s.msd),this.data=wo(wo(wo({},this.data),s),{},{msd:void 0});for(const t of UGt)t.field in s&&!t.equal(this.data[t.field],this.lastEmitted[t.field])&&this.recordEvent(t.event)}recordEvent(s,t={}){const n=MUn.get(s);if(n){const r=n.field,a=t[r];a!==void 0&&wh(this.data,{[r]:a});const i=this.data[r];if(i===void 0||n.equal(i,this.lastEmitted[r]))return;wh(this.lastEmitted,{[r]:n.snapshot(i)})}this.eventTargets.forEach((r,a)=>{this.recordTargetEvent(r,a,s,t)}),this.processEventTargets()}recordTargetEvent(s,t,n,r={}){var a;if(!t.events.includes(n))return;const i=wo(wo(wo({},this.data),r),{},{e:n,ts:(a=r.ts)!=null?a:Date.now(),sn:s.sn++});!isNaN(this.msd)&&!s.msdSent&&(i.msd=this.msd,s.msdSent=!0),s.queue.push(i)}recordResponseReceived(s,t={}){var n,r,a;const{request:i}=s,l=(n=t.url)!=null?n:i==null?void 0:i.url;if(!l)return;const o=new URL(l);o.searchParams.delete(Z_t);const c={url:o.toString(),rc:s.status},d=s.resourceTiming;d&&(d.startTime!=null&&(c.ts=Math.round(this.timeOrigin+d.startTime),d.responseStart!=null&&(c.ttfb=Math.round(d.responseStart-d.startTime))),d.duration!=null&&(c.ttlb=Math.round(d.duration)));const u=(r=(a=i.customData)==null?void 0:a.cmcd)!=null?r:{};this.recordEvent(YQe,wo(wo(wo({},u),c),t))}applyRequestReport(s){var t;return(t=this.createRequestReport(s))!=null?t:s}isRequestReportingEnabled(){var s;return!!((s=this.config.enabledKeys)!=null&&s.length)}createRequestReport(s,t){var n;const{customData:r={},headers:a={}}=s,i=HTe(s,eUn),l=wo(wo({},i),{},{headers:wo({},a),customData:wo(wo({},r),{},{cmcd:{}})});if(!((n=this.config.enabledKeys)!=null&&n.length)||!l.url)return l;const o=new URL(l.url),c=wo(wo(wo({},this.data),t),{},{sn:this.requestTarget.sn++}),d=X_t(XQe,this.config,l.url);!isNaN(this.msd)&&!this.requestTarget.msdSent&&(c.msd=this.msd,this.requestTarget.msdSent=!0);const u=l.customData.cmcd=zGt(c,d);switch(this.config.transmissionMode){case JQe:const h=BGt(u);h&&(o.searchParams.set(Z_t,h),l.url=o.toString());break;case $Gt:wh(l.headers,jUn(u,d.customHeaderMap));break}return l}processEventTargets(s=!1){let t=!1;this.eventTargets.forEach((n,r)=>{const{queue:a}=n;if(!a.length||a.length{n.queue.unshift(...l)}),t||(t=a.length>0)}),t&&this.processEventTargets()}async sendEventReport(s,t){const n=X_t(ZQe,s),{status:r}=await this.requester({url:s.url,method:"POST",headers:{"Content-Type":SUn},body:t.map(a=>NUn(a,n)).join(` `)+` `});if(r===410)this.disposeEventTarget(s);else if(r===429||r>499&&r<600)throw new Error(`Event report failed with status ${r}`)}disarmInterval(s){clearInterval(s.intervalId),s.intervalId=void 0}disposeEventTarget(s){const t=this.eventTargets.get(s);t&&(this.disarmInterval(t),this.eventTargets.delete(s))}resetSession(){this.eventTargets.forEach(s=>s.sn=0),this.requestTarget.sn=0,this.lastEmitted={}}};const RUn={HLS:"h"},N8e={VOD:"v",LIVE:"l",LOW_LATENCY:"ll"};function DUn(s,t){return new R_(s,t)}new Set(KTe);new Set(vqe);const OUn=["includeKeys"];function Q_t(s){return Object.keys(s).every(QQe)}class FUn{constructor(t){this.hls=void 0,this.config=void 0,this.media=void 0,this.initialized=!1,this.starved=!1,this.buffering=!0,this.playerState=void 0,this.reporter=void 0,this.playheadLevel=void 0,this.onWaiting=()=>{this.initialized&&(this.starved=!0,this.setPlayerState(pN.REBUFFERING)),this.buffering=!0},this.onPlay=()=>{this.initialized||this.setPlayerState(pN.STARTING)},this.onPlaying=()=>{this.initialized||(this.initialized=!0),this.buffering=!1,this.setPlayerState(pN.PLAYING)},this.onPause=()=>{this.media&&!this.media.ended&&this.setPlayerState(pN.PAUSED)},this.onSeeking=()=>{this.initialized&&this.setPlayerState(pN.SEEKING)},this.onSeeked=()=>{var a;this.initialized&&(a=this.media)!=null&&a.paused&&this.setPlayerState(pN.PAUSED)},this.onRateChange=()=>{this.reporter&&this.media&&this.reporter.update({pr:this.media.playbackRate})},this.applyPlaylistData=a=>{try{this.apply(a,{ot:z0.MANIFEST,su:!this.initialized})}catch(i){this.hls.logger.warn("Could not generate manifest CMCD data.",i)}},this.applyFragmentData=a=>{try{const{frag:o,part:c}=a,d=this.hls.levels[o.level],u=this.getObjectType(o,d),h={d:(c||o).duration*1e3,ot:u};if(u===z0.VIDEO||u===z0.AUDIO||u===z0.MUXED||u==null&&(o.type==="main"||o.type==="audio")){var i;const p=d.bitrate/1e3;h.br=[p];const{cmcd:g}=this.config,x=(i=g==null?void 0:g.rtpSafetyFactor)!=null?i:5;if(h.rtp=Math.round(p*x/100)*100,u===z0.MUXED||u==null&&o.type==="main"){const _=this.getTopBandwidth()/1e3;mi(_)&&(h.tb=[_]);const j=this.getLowestBandwidth()/1e3;mi(j)&&(h.lb=[j])}const y=this.getBufferLength(o);if(mi(y)){var l;h.bl=[y];const _=((l=this.media)==null?void 0:l.playbackRate)||1;h.dl=Math.round(y/_/100)*100}this.playheadLevel&&(h.pb=[this.playheadLevel.bitrate/1e3]);const v=this.hls.maxAutoLevel;if(v>=0){const _=this.hls.levels[v];_&&(h.tpb=[_.bitrate/1e3])}}const m=c?this.getNextPart(c):this.getNextFrag(o);m!=null&&m.url&&m.url!==o.url&&(m.byteRange.length>0?h.nor=[DUn(m.url,{r:`${m.byteRange[0]}-${m.byteRange[1]}`})]:h.nor=[m.url]),this.apply(a,h)}catch(o){this.hls.logger.warn("Could not generate segment CMCD data.",o)}},this.recordFragmentResponse=(a,i,l)=>{var o;const{cmcd:c}=this.config,d=c==null||(o=c.eventTargets)==null?void 0:o.some(u=>{var h;return(h=u.events)==null?void 0:h.includes(hie.RESPONSE_RECEIVED)});if(!(!this.reporter||!(l.loading.first>0)||!d))try{this.reporter.recordResponseReceived({request:{url:a},status:i.code,resourceTiming:{startTime:l.loading.start,responseStart:l.loading.first,duration:l.loading.end-l.loading.start,encodedBodySize:l.total}})}catch(u){this.hls.logger.warn("Could not record fragment response CMCD data.",u)}},this.hls=t;const n=this.config=t.config,{cmcd:r}=n;r!=null&&(n.pLoader=this.createPlaylistLoader(),n.fLoader=this.createFragmentLoader(),this.registerListeners())}createReporter(){var t,n;const{cmcd:r}=this.config;if(r==null)return;const a=r.version||CUn;if(this.reporter=new LUn({sid:r.sessionId||this.hls.sessionId,cid:r.contentId,version:a,transmissionMode:r.useHeaders===!0?$Gt:JQe,enabledKeys:(t=r.includeKeys)!=null?t:[...a>=kQ?vqe:KTe],eventTargets:((n=r.eventTargets)!=null?n:[]).map(i=>{let{includeKeys:l}=i,o=HTe(i,OUn);return wo(wo({},o),{},{enabledKeys:l??vqe})})},r.loader),this.reporter.update({sf:RUn.HLS,sta:this.playerState}),r.reporterCallback){const i=this.reporter,l={updateCustomData:o=>{Q_t(o)&&i.update(o)},recordCustomEvent:(o,c={})=>{Q_t(c)&&i.recordEvent(hie.CUSTOM_EVENT,wo({cen:o},c))}};r.reporterCallback(l)}this.reporter.start()}registerListeners(){const t=this.hls;t.on(Mt.MANIFEST_LOADING,this.onManifestLoading,this),t.on(Mt.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(Mt.MEDIA_DETACHED,this.onMediaDetached,this),t.on(Mt.MEDIA_ENDED,this.onMediaEnded,this),t.on(Mt.ERROR,this.onError,this),t.on(Mt.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(Mt.LEVEL_SWITCHED,this.onLevelSwitched,this),t.on(Mt.BUFFER_APPENDED,this.onBufferInfoChange,this),t.on(Mt.BUFFER_FLUSHED,this.onBufferInfoChange,this)}unregisterListeners(){const t=this.hls;t.off(Mt.MANIFEST_LOADING,this.onManifestLoading,this),t.off(Mt.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(Mt.MEDIA_DETACHED,this.onMediaDetached,this),t.off(Mt.MEDIA_ENDED,this.onMediaEnded,this),t.off(Mt.ERROR,this.onError,this),t.off(Mt.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(Mt.LEVEL_SWITCHED,this.onLevelSwitched,this),t.off(Mt.BUFFER_APPENDED,this.onBufferInfoChange,this),t.off(Mt.BUFFER_FLUSHED,this.onBufferInfoChange,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.reporter&&(this.reporter.stop(!0),this.reporter=void 0),this.hls=this.config=null,this.onWaiting=this.onPlay=this.onPlaying=this.onPause=null,this.onSeeking=this.onSeeked=this.onRateChange=this.media=null}onMediaAttaching(t,n){const r=this.media=n.media;this.setPlayerState(this.media.autoplay?pN.STARTING:pN.PRELOADING),th(r,"waiting",this.onWaiting),th(r,"play",this.onPlay),th(r,"playing",this.onPlaying),th(r,"pause",this.onPause),th(r,"seeking",this.onSeeking),th(r,"seeked",this.onSeeked),th(r,"ratechange",this.onRateChange)}onMediaDetached(){const t=this.media;t&&(Bu(t,"waiting",this.onWaiting),Bu(t,"play",this.onPlay),Bu(t,"playing",this.onPlaying),Bu(t,"pause",this.onPause),Bu(t,"seeking",this.onSeeking),Bu(t,"seeked",this.onSeeked),Bu(t,"ratechange",this.onRateChange),this.media=null)}onMediaEnded(t,n){this.setPlayerState(pN.ENDED)}onManifestLoading(t,n){this.initialized=!1,this.starved=!1,this.buffering=!0,this.reporter&&(this.reporter.stop(!0),this.reporter=void 0),this.createReporter(),this.media||this.setPlayerState(pN.PRELOADING)}onError(t,n){n.fatal&&(this.setPlayerState(pN.FATAL_ERROR),this.reporter&&this.reporter.recordEvent(hie.ERROR,{ec:[n.details]}))}onLevelSwitching(t,n){var r;if(!this.reporter)return;const a={br:[n.bitrate/1e3]},i=(r=n.details)==null?void 0:r.fragments[0];i&&(a.ot=this.getObjectType(i,n)),this.reporter.recordEvent(hie.BITRATE_CHANGE,a)}onLevelSwitched(t,n){const r=this.hls.levels[n.level];r&&(this.playheadLevel=r)}setPlayerState(t){this.playerState=t,this.reporter&&this.reporter.update({sta:t})}getStreamType(){const t=this.hls.latestLevelDetails;if(t)return t.live?t.partList&&t.canBlockReload?N8e.LOW_LATENCY:N8e.LIVE:N8e.VOD}apply(t,n={}){var r;if(!this.reporter)return;this.reporter.update({mtp:[this.hls.bandwidthEstimate/1e3],pr:(r=this.media)==null?void 0:r.playbackRate,st:this.getStreamType()});const a=n.ot===z0.INIT||n.ot===z0.VIDEO||n.ot===z0.MUXED;this.starved&&a&&(n.bs=!0,n.su=!0,this.starved=!1),n.su==null&&(n.su=this.buffering);const i=this.reporter.createRequestReport({url:t.url,headers:t.headers},n);t.url=i.url,t.headers=i.headers}getNextFrag(t){var n;const r=(n=this.hls.levels[t.level])==null?void 0:n.details;if(r){const a=t.sn-r.startSN;return r.fragments[a+1]}}getNextPart(t){var n;const{index:r,fragment:a}=t,i=(n=this.hls.levels[a.level])==null||(n=n.details)==null?void 0:n.partList;if(i){const{sn:l}=a;for(let o=i.length-1;o>=0;o--){const c=i[o];if(c.index===r&&c.fragment.sn===l)return i[o+1]}}}getObjectType(t,n){const{type:r}=t;if(r==="subtitle")return z0.TIMED_TEXT;if(t.sn==="initSegment")return z0.INIT;if(r==="audio")return z0.AUDIO;if(r==="main"){if(t.hasStreams){const a=t.elementaryStreams;if(a.audiovideo)return z0.MUXED;if(a.video)return z0.VIDEO;if(a.audio)return z0.AUDIO}if(n){const{audioCodec:a,videoCodec:i}=n;if(!this.hls.audioTracks.length){if(a&&i)return z0.MUXED;if(a)return z0.AUDIO}if(i)return z0.VIDEO}}}getTopBandwidth(){let t=0;const n=this.hls,r=n.maxAutoLevel,a=r>-1?r+1:n.levels.length;return n.levels.slice(0,a).forEach(l=>{l.bitrate>t&&(t=l.bitrate)}),t>0?t:NaN}getLowestBandwidth(){let t=1/0;const n=this.hls,r=n.maxAutoLevel,a=r>-1?r+1:n.levels.length;return n.levels.slice(0,a).forEach(l=>{l.bitrate{d(u,h,m,p),r(l.url,u,h)}}))}}}}const zUn=3e5;class BUn extends wj{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(Mt.MANIFEST_LOADING,this.onManifestLoading,this),t.on(Mt.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(Mt.MANIFEST_PARSED,this.onManifestParsed,this),t.on(Mt.ERROR,this.onError,this)}unregisterListeners(){const t=this.hls;t&&(t.off(Mt.MANIFEST_LOADING,this.onManifestLoading,this),t.off(Mt.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(Mt.MANIFEST_PARSED,this.onManifestParsed,this),t.off(Mt.ERROR,this.onError,this))}pathways(){return(this.levels||[]).reduce((t,n)=>(t.indexOf(n.pathwayId)===-1&&t.push(n.pathwayId),t),[])}get pathwayPriority(){return this._pathwayPriority}set pathwayPriority(t){this.updatePathwayPriority(t)}startLoad(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){const t=this.timeToLoad*1e3-(performance.now()-this.updated);if(t>0){this.scheduleRefresh(this.uri,t);return}}this.loadSteeringManifest(this.uri)}}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()}clearTimeout(){this.reloadTimer!==-1&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(t){const n=this.levels;n&&(this.levels=n.filter(r=>r!==t))}onManifestLoading(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null}onManifestLoaded(t,n){const{contentSteering:r}=n;r!==null&&(this.pathwayId=r.pathwayId,this.uri=r.uri,this.started&&this.startLoad())}onManifestParsed(t,n){this.audioTracks=n.audioTracks,this.subtitleTracks=n.subtitleTracks}onError(t,n){const{errorAction:r}=n;if((r==null?void 0:r.action)===Y0.SendAlternateToPenaltyBox&&r.flags&Yy.MoveAllAlternatesMatchingHost){const a=this.levels;let i=this._pathwayPriority,l=this.pathwayId;if(n.context){const{groupId:o,pathwayId:c,type:d}=n.context;o&&a?l=this.getPathwayForGroupId(o,d,l):c&&(l=c)}l in this.penalizedPathways||(this.penalizedPathways[l]=performance.now()),!i&&a&&(i=this.pathways()),i&&i.length>1&&(this.updatePathwayPriority(i),r.resolved=this.pathwayId!==l,!r.resolved&&(n.details!==er.BUFFER_APPEND_ERROR||n.fatal)&&this.warn(`Could not resolve ${n.details} ("${n.error.message}") with content-steering for Pathway: ${l} levels: ${a&&a.length} priorities: ${bm(i)} penalized: ${bm(this.penalizedPathways)}`))}}filterParsedLevels(t){this.levels=t;let n=this.getLevelsForPathway(this.pathwayId);if(n.length===0){const r=t[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${r}"`),n=this.getLevelsForPathway(r),this.pathwayId=r}return n.length!==t.length&&this.log(`Found ${n.length}/${t.length} levels in Pathway "${this.pathwayId}"`),n}getLevelsForPathway(t){return this.levels===null?[]:this.levels.filter(n=>t===n.pathwayId)}updatePathwayPriority(t){this._pathwayPriority=t;let n;const r=this.penalizedPathways,a=performance.now();Object.keys(r).forEach(i=>{a-r[i]>zUn&&delete r[i]});for(let i=0;i0){this.log(`Setting Pathway to "${l}"`),this.pathwayId=l,tGt(n),this.hls.trigger(Mt.LEVELS_UPDATED,{levels:n});const d=this.hls.levels[o];c&&d&&this.levels&&(d.attrs["STABLE-VARIANT-ID"]!==c.attrs["STABLE-VARIANT-ID"]&&d.bitrate!==c.bitrate&&this.log(`Unstable Pathways change from bitrate ${c.bitrate} to ${d.bitrate}`),this.hls.nextLoadLevel=o);break}}}getPathwayForGroupId(t,n,r){const a=this.getLevelsForPathway(r).concat(this.levels||[]);for(let i=0;i{const{ID:l,"BASE-ID":o,"URI-REPLACEMENT":c}=i;if(n.some(u=>u.pathwayId===l))return;const d=this.getLevelsForPathway(o).map(u=>{const h=new Yf(u.attrs);h["PATHWAY-ID"]=l;const m=h.AUDIO&&`${h.AUDIO}_clone_${l}`,p=h.SUBTITLES&&`${h.SUBTITLES}_clone_${l}`;m&&(r[h.AUDIO]=m,h.AUDIO=m),p&&(a[h.SUBTITLES]=p,h.SUBTITLES=p);const g=qGt(u.uri,h["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",c),x=new bQ({attrs:h,audioCodec:u.audioCodec,bitrate:u.bitrate,height:u.height,name:u.name,url:g,videoCodec:u.videoCodec,width:u.width});if(u.audioGroups)for(let y=1;y{this.log(`Loaded steering manifest: "${a}"`);const g=u.data;if((g==null?void 0:g.VERSION)!==1){this.log(`Steering VERSION ${g.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=g.TTL;const{"RELOAD-URI":x,"PATHWAY-CLONES":y,"PATHWAY-PRIORITY":v}=g;if(x)try{this.uri=new self.URL(x,a).href}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${x}`);return}this.scheduleRefresh(this.uri||m.url),y&&this.clonePathways(y);const _={steeringManifest:g,url:a.toString()};this.hls.trigger(Mt.STEERING_MANIFEST_LOADED,_),v&&this.updatePathwayPriority(v)},onError:(u,h,m,p)=>{if(this.log(`Error loading steering manifest: ${u.code} ${u.text} (${h.url})`),this.stopLoad(),u.code===410){this.enabled=!1,this.log(`Steering manifest ${h.url} no longer available`);return}let g=this.timeToLoad*1e3;if(u.code===429){const x=this.loader;if(typeof(x==null?void 0:x.getResponseHeader)=="function"){const y=x.getResponseHeader("Retry-After");y&&(g=parseFloat(y)*1e3)}this.log(`Steering manifest ${h.url} rate limited`);return}this.scheduleRefresh(this.uri||h.url,g)},onTimeout:(u,h,m)=>{this.log(`Timeout loading steering manifest (${h.url})`),this.scheduleRefresh(this.uri||h.url)}};this.log(`Requesting steering manifest: ${a}`),this.loader.load(i,c,d)}scheduleRefresh(t,n=this.timeToLoad*1e3){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var r;const a=(r=this.hls)==null?void 0:r.media;if(a&&!a.ended){this.loadSteeringManifest(t);return}this.scheduleRefresh(t,this.timeToLoad*1e3)},n)}}function J_t(s,t,n,r){s&&Object.keys(t).forEach(a=>{const i=s.filter(l=>l.groupId===a).map(l=>{const o=wh({},l);return o.details=void 0,o.attrs=new Yf(o.attrs),o.url=o.attrs.URI=qGt(l.url,l.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",n),o.groupId=o.attrs["GROUP-ID"]=t[a],o.attrs["PATHWAY-ID"]=r,o});s.push(...i)})}function qGt(s,t,n,r){if(t){const{[n]:o}=r;if(o){const c=o[t];if(c)return c}}const{HOST:a,PARAMS:i}=r,l=new self.URL(s);return a&&(l.hostname=a),i&&Object.keys(i).sort().forEach(o=>{o&&xM(l,o,i[o])}),l.href}class gN extends Error{constructor(t,n){super(n),this.data=void 0,t.error||(t.error=new Error(n)),this.data=t,t.err=t.error}}class HB extends wj{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.sessionSetupByUri={},this.mediaKeySessions=[],this.activeKeys={},this.mediaKeys=null,this.setMediaKeysQueue=HB.CDMCleanupPromise?[HB.CDMCleanupPromise]:[],this.onMediaEncrypted=n=>{const{initDataType:r,initData:a}=n,i=`"${n.type}" event: init data type: "${r}"`;if(this.log(i),a!==null){if(!this.keyFormatPromise){let l=Object.keys(this.keySystemAccessPromises);l.length||(l=YG(this.config));const o=l.map(p8e).filter(c=>!!c);this.keyFormatPromise=this.getKeyFormatPromise(o)}this.keyFormatPromise.then(l=>{let o;const c=lie(l),d=this.activeLevelKeys();if(c===bf.FAIRPLAY&&r==="sinf")try{const g=pk(new Uint8Array(a)),x=PQe(JSON.parse(g).sinf),y=jHt(x);if(!y)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");o=new Uint8Array(y.subarray(8,24))}catch(g){this.warn(`${i} Failed to parse sinf: ${g}`);return}else if(c===bf.PLAYREADY)o=zQe(new Uint8Array(a));else if(c===bf.WIDEVINE){const g=CHt(a).filter(x=>x.systemId===WHt.WIDEVINE);if(g.length){var u;const x=g[0];o=(u=x.kids)!=null&&u.length?x.kids[0]:null}}let h;if(o){const g=Ax(o);for(let x=0;xthis.handleError(l))}},this.onWaitingForKey=n=>{this.log(`"${n.type}" event`)},this.hls=t,this.config=t.config,this.registerListeners()}destroy(){this.onDestroying(),this.onMediaDetached();const t=this.config;t.requestMediaKeySystemAccessFunc=null,t.licenseXhrSetup=t.licenseResponseCallback=void 0,t.drmSystems=t.drmSystemOptions={},this.hls=this.config=null,this.onMediaEncrypted=this.onWaitingForKey=null}registerListeners(){const{hls:t}=this;t&&(t.on(Mt.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(Mt.MEDIA_DETACHED,this.onMediaDetached,this),t.on(Mt.MANIFEST_LOADING,this.onManifestLoading,this),t.on(Mt.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(Mt.DESTROYING,this.onDestroying,this))}unregisterListeners(){const{hls:t}=this;t&&(t.off(Mt.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(Mt.MEDIA_DETACHED,this.onMediaDetached,this),t.off(Mt.MANIFEST_LOADING,this.onManifestLoading,this),t.off(Mt.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(Mt.DESTROYING,this.onDestroying,this))}attemptKeySystemAccess(t){if(!this.hls)return Promise.reject(new Error("destroyed"));const n=this.hls.levels,r=(l,o,c)=>!!l&&c.indexOf(l)===o,a=n.map(l=>l.audioCodec).filter(r),i=n.map(l=>l.videoCodec).filter(r);return a.length+i.length===0&&i.push("avc1.42e01e"),new Promise((l,o)=>{const c=d=>{const u=d.shift();this.getMediaKeysPromise(u,a,i).then(h=>l({keySystem:u,mediaKeys:h})).catch(h=>{d.length?c(d):h instanceof gN?o(h):o(new gN({type:xo.KEY_SYSTEM_ERROR,details:er.KEY_SYSTEM_NO_ACCESS,error:h,fatal:!0},h.message))})};c(t)})}requestMediaKeySystemAccess(t,n){const{requestMediaKeySystemAccessFunc:r}=this.config;if(typeof r!="function"){let a=`Configured requestMediaKeySystemAccess is not a function ${r}`;return KHt===null&&self.location.protocol==="http:"&&(a=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(a))}return r(t,n)}getMediaKeysPromise(t,n,r){var a;const i=lBn(t,n,r,this.config.drmSystemOptions||{});let l=this.keySystemAccessPromises[t],o=(a=l)==null?void 0:a.keySystemAccess;if(!o){this.log(`Requesting encrypted media "${t}" key-system access with config: ${bm(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.throwIfDestroyed(),this.log(`Access for key-system "${d.keySystem}" obtained`);const u=this.fetchServerCertificate(t);this.log(`Create media-keys for "${t}"`);const h=c.mediaKeys=d.createMediaKeys().then(m=>(this.log(`Media-keys created for "${t}"`),c.hasMediaKeys=!0,u.then(p=>p?this.setMediaKeysServerCertificate(m,t,p):m)));return h.catch(m=>{this.error(`Failed to create media-keys for "${t}"}: ${m}`)}),h})}return o.then(()=>l.mediaKeys)}getMediaKeySessionContext(t,n,r,a){const{mediaKeySessions:i}=this,l=` key-session "${t}" keyId: ${Ax(r.keyId||[])} keyUri: ${r.uri} for "${a}"`;for(let d=0;d({keySystem:t,hasMediaKeys:this.keySystemAccessPromises[t].hasMediaKeys})).filter(({hasMediaKeys:t})=>!!t).map(({keySystem:t})=>p8e(t)).filter(t=>!!t)}getKeySystemAccess(t){return this.getKeySystemSelectionPromise(t).then(({keySystem:n,mediaKeys:r})=>this.attemptSetMediaKeys(n,r))}selectKeySystem(t){return this.getKeySystemSelectionPromise(t).then(({keySystem:n})=>{const r=p8e(n);if(!r)throw new Error(`Unable to find format for key-system "${n}"`);return r})}selectKeySystemFormat(t){const n=Object.keys(t.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${t.sn} ${t.type}: ${t.level}) key formats ${n.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(n)),this.keyFormatPromise}getKeyFormatPromise(t){const n=YG(this.config),r=t.map(lie).filter(a=>!!a&&n.indexOf(a)!==-1);return this.selectKeySystem(r)}loadClear(t,n,r){if(this.config.emeEnabled&&!this.getSelectedKeySystemFormats().length){if(n.length)for(let a=0,i=n.length;a{if(!this.hls)return;l.setKeyFormat(o);const c=lie(o);if(c)return this.getKeySystemAccess([c])})}if(this.config.requireKeySystemAccessOnStart){const a=YG(this.config);if(a.length)return this.getKeySystemAccess(a)}}return null}getKeyStatus(t){const{mediaKeySessions:n}=this;for(let r=0;r(this.throwIfDestroyed(),this.updateUsablePromise(t,"expired")))}updateUsablePromise(t,n,r){const a=this.getSessionForKey(t,n);return a.catch(i=>this.handleError(i,r)),a.then(i=>t)}getSessionForKey(t,n){const r=this.findContextForKey(t);if(r!==void 0)return Promise.resolve(r);const a=t.uri,i=this.sessionSetupByUri[a];let l;i===void 0?l=this.resolveSessionForKey(t,n):l=i.catch(()=>{}).then(()=>(this.throwIfDestroyed(),this.resolveSessionForKey(t,n))),this.sessionSetupByUri[a]=l;const o=()=>{this.sessionSetupByUri[a]===l&&delete this.sessionSetupByUri[a]};return l.then(o,o),l}findContextForKey(t){const{mediaKeySessions:n}=this;for(let r=n.length;r--;){const a=n[r];if(k8e(t,a))return a}}resolveSessionForKey(t,n){return this.getKeySystemForKeyPromise(t).then(({keySystem:r,mediaKeys:a})=>{this.throwIfDestroyed();for(let i=this.mediaKeySessions.length;i--;){const l=this.mediaKeySessions[i];if(k8e(t,l))return l;const o=this.getUsableKeyPromise(l,t,n);if(o)return o}return this.attemptSetMediaKeys(r,a).then(()=>(this.throwIfDestroyed(),this.getMediaKeySessionContext(r,a,t,n))).then(i=>{this.throwIfDestroyed();const l=t.scheme||"cenc",o=t.pssh?t.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(i,t,l,o,n)})})}getUsableKeyPromise(t,n,r){const a=t.keyRequests[n.uri];if(a)return this.log(`Waiting for usable key (${r} keyId: ${qUn(n)} format: "${n.keyFormat}" URI: ${n.uri})`),twt(a).then(()=>t)}throwIfDestroyed(t="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(t,n){if(this.hls)if(t instanceof gN){n&&(t.data.frag=n);const r=t.data.decryptdata;this.error(`${t.message}${r?` (${Ax(r.keyId||[])})`:""}`),this.hls.trigger(Mt.ERROR,t.data)}else this.error(t.message),this.hls.trigger(Mt.ERROR,{type:xo.KEY_SYSTEM_ERROR,details:er.KEY_SYSTEM_NO_KEYS,error:t,fatal:!0})}getKeySystemForKeyPromise(t){const n=lie(t.keyFormat),r=n?[n]:YG(this.config);return this.attemptKeySystemAccess(r)}getKeySystemSelectionPromise(t){if(t.length||(t=YG(this.config)),t.length===0)throw new gN({type:xo.KEY_SYSTEM_ERROR,details:er.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${bm({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(t)}activeLevelKeys(){const t=this.activeKeys,n=(t.previous||[]).map(r=>r.decryptdata);return t.audio&&n.unshift(t.audio.decryptdata),t.main&&n.unshift(t.main.decryptdata),n}attemptSetMediaKeys(t,n){if(this.mediaResolved=void 0,this.mediaKeys===n)return Promise.resolve();const r=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${t}"`);const a=Promise.all(r).then(()=>this.media?this.media.setMediaKeys(n):new Promise((i,l)=>{this.mediaResolved=()=>{if(this.mediaResolved=void 0,!this.media)return l(new Error("Attempted to set mediaKeys without media element attached"));this.mediaKeys=n,this.media.setMediaKeys(n).then(i).catch(l)}}));return this.mediaKeys=n,this.setMediaKeysQueue.push(a),a.then(()=>{this.log(`Media-keys set for "${t}"`),r.push(a),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(i=>r.indexOf(i)===-1)})}filterInitData(t,n,r,a,i){var l;const o=(l=this.config.drmSystems)==null||(l=l[t.keySystem])==null?void 0:l.generateRequest;if(o)try{const d=o.call(this.hls,r,a,wh({},t,{decryptdata:n,reason:i}),i);if(!d)throw new Error("Invalid response from configured generateRequest filter");n.scheme=d.initDataType?d.initDataType:"cenc";const u=d.initData?d.initData:null;return n.pssh=u?new Uint8Array(u):null,d}catch(d){var c;if(this.warn(d.message),(c=this.hls)!=null&&c.config.debug)throw d}return{initDataType:r,initData:a}}generateRequestWithPreferredKeySession(t,n,r,a,i){const l=this.getUsableKeyPromise(t,n,i);if(l)return l;const o=this.filterInitData(t,n,r,a,i);if(o&&(a=o.initData?o.initData:null,r=o.initDataType),a===null)return i.startsWith("encrypted-event")?Promise.reject(new Error(`missing initialization data for "${i}"`)):(this.log(`Skipping key-session request for "${i}" (no initData)`),Promise.resolve(t));const c=n.uri,d=new $Qe;d.status="initialized",d.requestErrors=[],t.keyRequests[c]=d;const u=m=>{const p=t.mediaKeysSession;if(!p){const y=new Error("invalid state");d.errored=y,d.emit("error",y);return}const{messageType:g,message:x}=m;d.status=g,this.log(`"${g}" message event for session "${p.sessionId}" message size: ${x.byteLength}`),g==="license-request"||g==="license-renewal"?this.renewLicense(t,n,x).catch(y=>{d.errored=y,d.eventNames().length?d.emit("error",y):this.handleError(y),this.removeSession(t)}):g==="license-release"?t.keySystem===bf.FAIRPLAY&&this.updateKeySession(t,n,uqe("acknowledged")).then(()=>this.removeSession(t)).catch(y=>this.handleError(y)):this.warn(`unhandled media key message type "${g}"`)};return d.onmessage=u,th(t.mediaKeysSession,"message",u),this.generateRequest(t,n,r,a,i,!1)}generateRequest(t,n,r,a,i,l){if(l){const p=this.filterInitData(t,n,r,a,i);p&&(a=p.initData?p.initData:a,r=p.initDataType)}const o=n.uri,c=t.keyRequests[o],d=Ax(n.keyId||[]),u=p=>{let g;p.startsWith("usable")?(c.resolved=!0,c.emit("resolved")):p==="internal-error"||p==="output-restricted"||p==="output-downscaled"?g=ewt(p,n):p==="expired"?g=new Error(`key expired (keyId: ${d})`):p==="released"?g=new Error("key released"):p==="status-pending"||this.warn(`unhandled key status change "${p}" (keyId: ${d})`),g&&(c.errored=g,c.eventNames().length?c.emit("error",g):this.handleError(g))},h=p=>{if(!t.mediaKeysSession){const A=new Error("invalid state");c.errored=A,c.emit("error",A);return}const x=t.keyStatuses=this.getKeyStatuses(t);if(!Object.keys(x).some(A=>x[A]!=="status-pending"))return;const v=this.activeLevelKeys();for(let A=0;Athis.handleError(I));break}}let j=x[d];if(j)u(j);else{var C;t.keyStatusTimeouts||(t.keyStatusTimeouts={}),(C=t.keyStatusTimeouts)[d]||(C[d]=self.setTimeout(()=>{var M;if(!t.mediaKeysSession)return;const I=this.getKeyStatus(n);if(I&&I!=="status-pending"){var P;return this.log(`No status for keyId ${d} in key-session "${(P=t.mediaKeysSession)==null?void 0:P.sessionId}". Using session key-status ${I} from other session.`),u(I)}this.log(`key status for ${d} in key-session "${(M=t.mediaKeysSession)==null?void 0:M.sessionId}" timed out after 1000ms`),j="internal-error",u(j)},1e3)),this.log(`No status for keyId ${d} (${bm(x)}).`)}};c.onkeystatuseschange=h,th(t.mediaKeysSession,"keystatuseschange",h);const m=twt(c);return this.log(`Generating key-session request for "${i}" keyId: ${d} URI: ${o} (init data type: ${r} length: ${a.byteLength})`),c.status="started",t.initialized=!0,t.mediaKeysSession.generateRequest(r,a).then(()=>{var p;c.status="generated",this.log(`Request generated for key-session "${(p=t.mediaKeysSession)==null?void 0:p.sessionId}" keyId: ${d} URI: ${o}`)}).catch(p=>{throw this.log(`mediaKeysSession.generateRequest failed: ${p}`),new gN({type:xo.KEY_SYSTEM_ERROR,details:er.KEY_SYSTEM_NO_SESSION,error:p,decryptdata:n,fatal:!1},`Error generating key-session request: ${p}`)}).then(()=>m).catch(p=>{var g;this.log(`mediaKeysSession.generateRequest failed: ${p}`);const x=(g=p.data)==null?void 0:g.details;return(x===er.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED||x===er.KEY_SYSTEM_STATUS_INTERNAL_ERROR)&&Object.keys(t.keyStatuses).some(y=>t.keyStatuses[y]==="usable")?(this.handleError(p),t):(c.removeAllListeners(),this.removeSession(t).then(()=>{throw p}))}).then(()=>t)}getKeyStatuses(t){const n={},r=t.mediaKeysSession.sessionId;return t.mediaKeysSession.keyStatuses.forEach((a,i)=>{if(typeof i=="string"&&typeof a=="object"){const c=i;i=a,a=c}const l="buffer"in i?new Uint8Array(i.buffer,i.byteOffset,i.byteLength):new Uint8Array(i);if(t.keySystem===bf.PLAYREADY&&l.length===16){const c=Ax(l);n[c]=a,HHt(l)}const o=Ax(l);this.log(`key status change "${a}" for keyStatuses keyId: ${o} key-session "${r}"`),n[o]=a}),n}fetchServerCertificate(t){const n=this.config,r=n.loader,a=new r(n),i=UUn(t,n);return i?(this.log(`Fetching server certificate for "${t}"`),new Promise((l,o)=>{const c={type:Mc.SERVER_CERTIFICATE,responseType:"arraybuffer",url:i},d=n.certLoadPolicy.default,u={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:(m,p,g,x)=>{l(m.data)},onError:(m,p,g,x)=>{o(new gN({type:xo.KEY_SYSTEM_ERROR,details:er.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:g,response:wo({url:c.url,data:void 0},m)},`"${t}" certificate request failed (${i}). Status: ${m.code} (${m.text})`))},onTimeout:(m,p,g)=>{o(new gN({type:xo.KEY_SYSTEM_ERROR,details:er.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:g,response:{url:c.url,data:void 0}},`"${t}" certificate request timed out (${i})`))},onAbort:(m,p,g)=>{o(new Error("aborted"))}};a.load(c,u,h)})):(this.log(`No Server Certificate in config.drmSystems["${t}"]`),Promise.resolve())}setMediaKeysServerCertificate(t,n,r){return new Promise((a,i)=>{t.setServerCertificate(r).then(l=>{this.log(`setServerCertificate ${l?"success":"not supported by CDM"} (${r.byteLength}) on "${n}"`),a(t)}).catch(l=>{i(new gN({type:xo.KEY_SYSTEM_ERROR,details:er.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:l,fatal:!0},l.message))})})}renewLicense(t,n,r){return this.requestLicense(t,n,new Uint8Array(r)).then(a=>this.updateKeySession(t,n,new Uint8Array(a)).catch(i=>{throw new gN({type:xo.KEY_SYSTEM_ERROR,details:er.KEY_SYSTEM_SESSION_UPDATE_FAILED,decryptdata:n,error:i,fatal:!1},i.message)}))}unpackPlayReadyKeyMessage(t,n){const r=pk(new Uint16Array(n.buffer));if(!r.includes("PlayReadyKeyMessage"))return t.setRequestHeader("Content-Type","text/xml; charset=utf-8"),n;const a=new DOMParser().parseFromString(r,"application/xml"),i=a.querySelectorAll("HttpHeader");if(i.length>0){let u;for(let h=0,m=i.length;h in key message");return uqe(atob(d))}setupLicenseXHR(t,n,r,a,i){const l=this.config.licenseXhrSetup;return l?Promise.resolve().then(()=>(this.throwIfDestroyed(),l.call(this.hls,t,n,wo(wo({},r),{},{decryptdata:a}),i))).catch(o=>{if(!r.mediaKeysSession)throw o;return t.open("POST",n,!0),l.call(this.hls,t,n,wo(wo({},r),{},{decryptdata:a}),i)}).then(o=>(t.readyState||t.open("POST",n,!0),{xhr:t,licenseChallenge:o||i})):(t.open("POST",n,!0),Promise.resolve({xhr:t,licenseChallenge:i}))}requestLicense(t,n,r){return new Promise((a,i)=>{const l=$Un(t.keySystem,this.config);if(!l)return i(new Error(`no license server URL configured for key-system "${t.keySystem}"`));const o=t.keyRequests[n.uri];if(!o)return i(new Error("License emitter removed"));this.log(`Sending license request to URL: ${l}`);const c=this.config.keyLoadPolicy.default,d=new XMLHttpRequest;d.responseType="arraybuffer",d.onreadystatechange=()=>{if(!this.hls||!t.mediaKeysSession)return i(new Error("invalid state"));if(d.readyState===4)if(d.status===200){o.requestErrors=[];let u=d.response;this.log(`License received ${u instanceof ArrayBuffer?u.byteLength:u}`);const h=this.config.licenseResponseCallback;if(h)try{u=h.call(this.hls,d,l,wo(wo({},t),{},{decryptdata:n}))}catch(m){this.error(m)}a(u)}else{const u=c.errorRetry,h=u?u.maxNumRetry:0;if(o.requestErrors.push({status:d.status,message:d.statusText}),o.requestErrors.length>h||d.status>=400&&d.status<500)i(new gN({type:xo.KEY_SYSTEM_ERROR,details:er.KEY_SYSTEM_LICENSE_REQUEST_FAILED,decryptdata:n,fatal:!0,networkDetails:d,response:{url:l,data:void 0,code:d.status,text:d.statusText}},`License Request XHR failed (${l}). Status: ${d.status} (${d.statusText})`));else{const m=h-o.requestErrors.length;this.warn(`Retrying license request, ${m} attempts left`),this.requestLicense(t,n,r).then(a,i)}}},o.licenseXhr&&o.licenseXhr.readyState!==XMLHttpRequest.DONE&&o.licenseXhr.abort(),o.licenseXhr=d,this.setupLicenseXHR(d,l,t,n,r).then(({xhr:u,licenseChallenge:h})=>{t.keySystem==bf.PLAYREADY&&(h=this.unpackPlayReadyKeyMessage(u,h)),u.send(h)}).catch(i)})}onDestroying(){this.unregisterListeners(),this._clear()}onMediaAttached(t,n){if(!this.config.emeEnabled)return;const r=n.media;this.media=r,th(r,"encrypted",this.onMediaEncrypted),th(r,"waitingforkey",this.onWaitingForKey);const a=this.mediaResolved;a?a():this.mediaKeys=r.mediaKeys}onMediaDetached(){const t=this.media;t&&(Bu(t,"encrypted",this.onMediaEncrypted),Bu(t,"waitingforkey",this.onWaitingForKey),this.media=null,this.mediaKeys=null)}_clear(){var t;this.keyFormatPromise=null,this.keySystemAccessPromises={},this.activeKeys={},this.sessionSetupByUri={};const n=this.mediaResolved;if(n&&n(),!this.mediaKeys&&!this.mediaKeySessions.length)return;const r=this.media,a=this.mediaKeySessions.slice();this.mediaKeySessions=[],this.mediaKeys=null,M3.clearKeyUriToKeyIdMap();const i=a.length;HB.CDMCleanupPromise=Promise.all(a.map(l=>this.removeSession(l)).concat((r==null||(t=r.setMediaKeys(null))==null?void 0:t.catch(l=>{this.log(`Could not clear media keys: ${l}`),this.hls&&this.hls.trigger(Mt.ERROR,{type:xo.OTHER_ERROR,details:er.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(Mt.ERROR,{type:xo.OTHER_ERROR,details:er.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(),this.keyFormatPromise=null}onManifestLoaded(t,{sessionKeys:n}){if(!(!n||!this.config.emeEnabled)&&!this.keyFormatPromise){const r=n.reduce((a,i)=>(a.indexOf(i.keyFormat)===-1&&a.push(i.keyFormat),a),[]);this.log(`Selecting key-system from session-keys ${r.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(r),this.keyFormatPromise.catch(()=>{})}}removeSession(t){const{mediaKeysSession:n}=t;if(n){this.log(`Remove licenses and keys and close session "${n.sessionId}"`),Object.keys(t.keyRequests).forEach(o=>{const c=t.keyRequests[o];c.onmessage&&(n.removeEventListener("message",c.onmessage),c.onmessage=void 0),c.onkeystatuseschange&&(n.removeEventListener("keystatuseschange",c.onkeystatuseschange),c.onkeystatuseschange=void 0);const d=c.licenseXhr;d&&(d.readyState!==XMLHttpRequest.DONE&&d.abort(),c.licenseXhr=void 0),t.keyRequests[o]=void 0}),t.mediaKeysSession=void 0;const r=this.mediaKeySessions.indexOf(t);r>-1&&this.mediaKeySessions.splice(r,1);const{keyStatusTimeouts:a}=t;a&&Object.keys(a).forEach(o=>self.clearTimeout(a[o]));const{drmSystemOptions:i}=this.config;return(dBn(i)?new Promise((o,c)=>{self.setTimeout(()=>c(new Error("MediaKeySession.remove() timeout")),8e3),n.remove().then(o).catch(c)}):Promise.resolve()).catch(o=>{this.log(`Could not remove session: ${o}`),this.hls&&this.hls.trigger(Mt.ERROR,{type:xo.OTHER_ERROR,details:er.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error(`Could not remove session: ${o}`)})}).then(()=>n.close()).then(()=>n.closed).catch(o=>{this.log(`Could not close session: ${o}`),this.hls&&this.hls.trigger(Mt.ERROR,{type:xo.OTHER_ERROR,details:er.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${o}`)})})}return Promise.resolve()}}HB.CDMCleanupPromise=void 0;function $Un(s,t){const{drmSystems:n,widevineLicenseUrl:r}=t,a=n==null?void 0:n[s];if(a)return a.licenseUrl;if(s===bf.WIDEVINE&&r)return r}function UUn(s,t){const{drmSystems:n}=t,r=n==null?void 0:n[s];if(r)return r.serverCertificateUrl}function qUn(s){if(s.keyFormat===ev.FAIRPLAY)return s.uri;if(s.keyId===null)throw new Error("keyId is null");return Ax(s.keyId)}function k8e(s,t){const n=s.keyId,r=t.mediaKeysSession;if(n&&r){const a=t.mediaKeysSession.keyStatuses;if(a.size)return a.has(n)?a.get(n):t.keyStatuses[Ax(n)]}}function ewt(s,t){const n=s==="output-restricted",r=n?er.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:er.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new gN({type:xo.KEY_SYSTEM_ERROR,details:r,fatal:!1,decryptdata:t},n?"HDCP level output restricted":`key status changed to "${s}"`)}function twt(s){return new Promise((t,n)=>{if(s.resolved)return t();if(s.errored)return n(s.errored);s.on("error",n),s.on("resolved",t)})}class VUn{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(Mt.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(Mt.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(Mt.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(Mt.MEDIA_DETACHING,this.onMediaDetaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(t,n){const r=this.hls.config;if(r.capLevelOnFPSDrop){const a=n.media instanceof self.HTMLVideoElement?n.media:null;this.media=a,a&&typeof a.getVideoPlaybackQuality=="function"&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),r.fpsDroppedMonitoringPeriod)}}onMediaDetaching(){this.media=null}checkFPS(t,n,r){const a=performance.now();if(n){if(this.lastTime){const i=a-this.lastTime,l=r-this.lastDroppedFrames,o=n-this.lastDecodedFrames,c=1e3*l/i,d=this.hls;if(d.trigger(Mt.FPS_DROP,{currentDropped:l,currentDecoded:o,totalDroppedFrames:r}),c>0&&l>d.config.fpsDroppedMonitoringThreshold*o){let u=d.currentLevel;d.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+u),u>0&&(d.autoLevelCapping===-1||d.autoLevelCapping>=u)&&(u=u-1,d.trigger(Mt.FPS_DROP_LEVEL_CAPPING,{level:u,droppedLevel:d.currentLevel}),d.autoLevelCapping=u,this.streamController.nextLevelSwitch())}}this.lastTime=a,this.lastDroppedFrames=r,this.lastDecodedFrames=n}}checkFPSInterval(){const t=this.media;if(t)if(this.isVideoPlaybackQualityAvailable){const n=t.getVideoPlaybackQuality();this.checkFPS(t,n.totalVideoFrames,n.droppedVideoFrames)}else this.checkFPS(t,t.webkitDecodedFrameCount,t.webkitDroppedFrameCount)}}var eJe=function(){if(lCe!=null&&lCe.VTTCue)return self.VTTCue;const s=["","lr","rl"],t=["start","middle","end","left","right"];function n(o,c){if(typeof c!="string"||!Array.isArray(o))return!1;const d=c.toLowerCase();return~o.indexOf(d)?d:!1}function r(o){return n(s,o)}function a(o){return n(t,o)}function i(o,...c){let d=1;for(;d100)throw new Error("Position must be between 0 and 100.");M=O,this.hasBeenReset=!0}})),Object.defineProperty(u,"positionAlign",i({},h,{get:function(){return I},set:function(O){const B=a(O);if(!B)throw new SyntaxError("An invalid or illegal string was specified.");I=B,this.hasBeenReset=!0}})),Object.defineProperty(u,"size",i({},h,{get:function(){return P},set:function(O){if(O<0||O>100)throw new Error("Size must be between 0 and 100.");P=O,this.hasBeenReset=!0}})),Object.defineProperty(u,"align",i({},h,{get:function(){return R},set:function(O){const B=a(O);if(!B)throw new SyntaxError("An invalid or illegal string was specified.");R=B,this.hasBeenReset=!0}})),u.displayState=void 0}return l.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},l}();class HUn{decode(t,n){if(!t)return"";if(typeof t!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(t))}}function VGt(s){function t(r,a,i,l){return(r|0)*3600+(a|0)*60+(i|0)+parseFloat(l||0)}const n=s.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return n?parseFloat(n[2])>59?t(n[2],n[3],0,n[4]):t(n[1],n[2],n[3],n[4]):null}class GUn{constructor(){this.values=Object.create(null)}set(t,n){!this.get(t)&&n!==""&&(this.values[t]=n)}get(t,n,r){return r?this.has(t)?this.values[t]:n[r]:this.has(t)?this.values[t]:n}has(t){return t in this.values}alt(t,n,r){for(let a=0;a=0&&r<=100)return this.set(t,r),!0}return!1}}function HGt(s,t,n,r){const a=r?s.split(r):[s];for(const i in a){if(typeof a[i]!="string")continue;const l=a[i].split(n);if(l.length!==2)continue;const o=l[0],c=l[1];t(o,c)}}const bqe=new eJe(0,0,""),mie=bqe.align==="middle"?"middle":"center";function WUn(s,t,n){const r=s;function a(){const o=VGt(s);if(o===null)throw new Error("Malformed timestamp: "+r);return s=s.replace(/^[^\sa-zA-Z-]+/,""),o}function i(o,c){const d=new GUn;HGt(o,function(m,p){let g;switch(m){case"region":for(let x=n.length-1;x>=0;x--)if(n[x].id===p){d.set(m,n[x].region);break}break;case"vertical":d.alt(m,p,["rl","lr"]);break;case"line":g=p.split(","),d.integer(m,g[0]),d.percent(m,g[0])&&d.set("snapToLines",!1),d.alt(m,g[0],["auto"]),g.length===2&&d.alt("lineAlign",g[1],["start",mie,"end"]);break;case"position":g=p.split(","),d.percent(m,g[0]),g.length===2&&d.alt("positionAlign",g[1],["start",mie,"end","line-left","line-right","auto"]);break;case"size":d.percent(m,p);break;case"align":d.alt(m,p,["start",mie,"end","left","right"]);break}},/:/,/\s/),c.region=d.get("region",null),c.vertical=d.get("vertical","");let u=d.get("line","auto");u==="auto"&&bqe.line===-1&&(u=-1),c.line=u,c.lineAlign=d.get("lineAlign","start"),c.snapToLines=d.get("snapToLines",!0),c.size=d.get("size",100),c.align=d.get("align",mie);let h=d.get("position","auto");h==="auto"&&bqe.position===50&&(h=c.align==="start"||c.align==="left"?0:c.align==="end"||c.align==="right"?100:50),c.position=h}function l(){s=s.replace(/^\s+/,"")}if(l(),t.startTime=a(),l(),s.slice(0,3)!=="-->")throw new Error("Malformed time stamp (time stamps must be separated by '-->'): "+r);s=s.slice(3),l(),t.endTime=a(),l(),i(s,t)}function GGt(s){return s.replace(//gi,` `)}class KUn{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new HUn,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(t){const n=this;t&&(n.buffer+=n.decoder.decode(t,{stream:!0}));function r(){let i=n.buffer,l=0;for(i=GGt(i);l")===-1){n.cue.id=i;continue}case"CUE":if(!n.cue){n.state="BADCUE";continue}try{WUn(i,n.cue,n.regionList)}catch{n.cue=null,n.state="BADCUE";continue}n.state="CUETEXT";continue;case"CUETEXT":{const o=i.indexOf("-->")!==-1;if(!i||o&&(l=!0)){n.oncue&&n.cue&&n.oncue(n.cue),n.cue=null,n.state="ID";continue}if(n.cue===null)continue;n.cue.text&&(n.cue.text+=` `),n.cue.text+=i}continue;case"BADCUE":i||(n.state="ID")}}}catch{n.state==="CUETEXT"&&n.cue&&n.oncue&&n.oncue(n.cue),n.cue=null,n.state=n.state==="INITIAL"?"BADWEBVTT":"BADCUE"}return this}flush(){const t=this;try{if((t.cue||t.state==="HEADER")&&(t.buffer+=` `,t.parse()),t.state==="INITIAL"||t.state==="BADWEBVTT")throw new Error("Malformed WebVTT signature.")}catch(n){t.onparsingerror&&t.onparsingerror(n)}return t.onflush&&t.onflush(),this}}function hZ(s){let t=5381,n=s.length;for(;n;)t=t*33^s.charCodeAt(--n);return(t>>>0).toString()}const YUn=/\r\n|\n\r|\n|\r/g,swt="Missing initPTS for VTT ",ZUn=function(t){let n=parseInt(t.slice(-3));const r=parseInt(t.slice(-6,-4)),a=parseInt(t.slice(-9,-7)),i=t.length>9?parseInt(t.substring(0,t.indexOf(":"))):0;if(!mi(n)||!mi(r)||!mi(a)||!mi(i))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${t}`);return n+=1e3*r,n+=60*1e3*a,n+=60*60*1e3*i,n};function tJe(s,t,n){return hZ(s.toString())+hZ(t.toString())+hZ(n)}function XUn(s,t,n,r,a,i,l){const o=new KUn,c=ij(new Uint8Array(s)).trim().replace(YUn,` `).split(` `),d=[],u=t?u$n(t.baseTime,t.timescale):0;let h="00:00.000",m=0,p=0,g=!1,x,y=!0;o.oncue=function(v){const _=n[r];let j=n.ccOffset;const C=(m-u)/9e4;if(g){if(_!=null&&_.new&&(j=n.ccOffset=_.start),C){if(!t){x=new Error(swt+"MPEGTS");return}j=C-n.presentationOffset}}else if(t)j=-t.baseTime/t.timescale;else{x=new Error(swt+"without X-TIMESTAMP-MAP");return}const A=v.endTime-v.startTime,M=Pw((v.startTime+j-p)*9e4,a*9e4)/9e4;v.startTime=Math.max(M,0),v.endTime=Math.max(M+A,0);const I=v.text.trim();v.text=decodeURIComponent(encodeURIComponent(I)),v.id?r&&(v.id=`hlsjscc${r}_${v.id}`):v.id=tJe(v.startTime,v.endTime,I),v.endTime>0&&d.push(v)},o.onparsingerror=function(v){x=v},o.onflush=function(){if(x){l(x);return}i(d)},c.forEach(v=>{if(y)if(v.startsWith("X-TIMESTAMP-MAP=")){y=!1,g=!0,v.slice(16).split(",").forEach(_=>{_.startsWith("LOCAL:")?h=_.slice(6):_.startsWith("MPEGTS:")&&(m=parseInt(_.slice(7)))});try{p=ZUn(h)/1e3}catch(_){x=_}return}else v===""&&(y=!1);o.parse(v+` `)}),o.flush()}const _qe="stpp.ttml.im1t",WGt=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,KGt=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,QUn={left:"start",center:"center",right:"end",start:"start",end:"end"};function nwt(s,t,n,r){const a=Tl(new Uint8Array(s),["mdat"]);if(a.length===0){r(new Error("Could not parse IMSC1 mdat"));return}const i=a.map(o=>ij(o)),l=d$n(t.baseTime,1,t.timescale);try{i.forEach(o=>n(JUn(o,l)))}catch(o){r(o)}}function JUn(s,t){const a=new DOMParser().parseFromString(s,"text/xml").getElementsByTagName("tt")[0];if(!a)throw new Error("Invalid ttml");const i={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},l=Object.keys(i).reduce((h,m)=>(h[m]=a.getAttribute(`ttp:${m}`)||i[m],h),{}),o=a.getAttribute("xml:space")!=="preserve",c=rwt(S8e(a,"styling","style")),d=rwt(S8e(a,"layout","region")),u=S8e(a,"body","[begin]");return[].map.call(u,h=>{const m=YGt(h,o);if(!m||!h.hasAttribute("begin"))return null;const p=A8e(h.getAttribute("begin"),l),g=A8e(h.getAttribute("dur"),l);let x=A8e(h.getAttribute("end"),l);if(p===null)throw awt(h);if(x===null){if(g===null)throw awt(h);x=p+g}const y=new eJe(p-t,x-t,m);y.id=tJe(y.startTime,y.endTime,y.text);const v=d[h.getAttribute("region")],_=c[h.getAttribute("style")],j=eqn(v,_,c),{textAlign:C}=j;if(C){const A=QUn[C];A&&(y.lineAlign=A),y.align=C}return wh(y,j),y}).filter(h=>h!==null)}function S8e(s,t,n){const r=s.getElementsByTagName(t)[0];return r?[].slice.call(r.querySelectorAll(n)):[]}function rwt(s){return s.reduce((t,n)=>{const r=n.getAttribute("xml:id");return r&&(t[r]=n),t},{})}function YGt(s,t){return[].slice.call(s.childNodes).reduce((n,r,a)=>{var i;return r.nodeName==="br"&&a?n+` `:(i=r.childNodes)!=null&&i.length?YGt(r,t):t?n+r.textContent.trim().replace(/\s+/g," "):n+r.textContent},"")}function eqn(s,t,n){const r="http://www.w3.org/ns/ttml#styling";let a=null;const i=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],l=s!=null&&s.hasAttribute("style")?s.getAttribute("style"):null;return l&&n.hasOwnProperty(l)&&(a=n[l]),i.reduce((o,c)=>{const d=C8e(t,r,c)||C8e(s,r,c)||C8e(a,r,c);return d&&(o[c]=d),o},{})}function C8e(s,t,n){return s&&s.hasAttributeNS(t,n)?s.getAttributeNS(t,n):null}function awt(s){return new Error(`Could not parse ttml timestamp ${s}`)}function A8e(s,t){if(!s)return null;let n=VGt(s);return n===null&&(WGt.test(s)?n=tqn(s,t):KGt.test(s)&&(n=sqn(s,t))),n}function tqn(s,t){const n=WGt.exec(s),r=(n[4]|0)+(n[5]|0)/t.subFrameRate;return(n[1]|0)*3600+(n[2]|0)*60+(n[3]|0)+r/t.frameRate}function sqn(s,t){const n=KGt.exec(s),r=Number(n[1]);switch(n[2]){case"h":return r*3600;case"m":return r*60;case"ms":return r*1e3;case"f":return r/t.frameRate;case"t":return r/t.tickRate}return r}function sJe(s,t,n,r="",a="disabled"){const i=s.ownerDocument.createElement("track");return i.kind=t,i.label=n,r&&(i.srclang=r),i.src="data:,WEBVTT",i.track.mode=a,s.appendChild(i),i}function nqn(s){return s.forced&&vzn()?"forced":s.characteristics&&/transcribes-spoken-dialog/gi.test(s.characteristics)&&/describes-music-and-sound/gi.test(s.characteristics)?"captions":"subtitles"}function wqe(s,t){const n=s.mode;if(n==="disabled"&&(s.mode="hidden"),s.cues&&!s.cues.getCueById(t.id))try{if(s.addCue(t),!s.cues.getCueById(t.id))throw new Error(`addCue is failed for: ${t}`)}catch(r){ku.debug(`[texttrack-utils]: ${r}`);try{const a=new self.TextTrackCue(t.startTime,t.endTime,t.text);a.id=t.id,s.addCue(a)}catch(a){ku.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${a}`)}}n==="disabled"&&(s.mode=n)}function jqe(s,t,n,r){const a=s.mode;if(a==="disabled"&&(s.mode="hidden"),s.cues&&s.cues.length>0){const i=aqn(s.cues,t,n);for(let l=0;ls[n].endTime)return-1;let r=0,a=n,i;for(;r<=a;)if(i=Math.floor((a+r)/2),ts[i].startTime&&r-1)for(let i=a,l=s.length;i=t&&o.endTime<=n)r.push(o);else if(o.startTime>n)return r}return r}class iqn extends GQe{constructor(t){super(t,"subtitle-track-controller"),this.media=null,this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0,this.queuedDefaultTrack=-1,this.useTextTrackPolling=!1,this.subtitlePollingInterval=-1,this._subtitleDisplay=!0,this.asyncPollTrackChange=()=>this.pollTrackChange(0),this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let n=-1,r=!1;if(this.currentTrack){var a;const o=(a=this.currentTrack.trackNode)==null?void 0:a.track.mode;o==="showing"?(n=this.trackId,r=!0):o==="hidden"&&(n=this.trackId)}if(!r)for(let o=0;o-1){var l;this._subtitleDisplay=((l=this.tracksInGroup[n].trackNode)==null?void 0:l.track.mode)==="showing"}this.setSubtitleTrack(n,!0)},this.registerListeners()}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,this.onTextTracksChanged=this.asyncPollTrackChange=null,super.destroy()}get subtitleDisplay(){return this._subtitleDisplay}set subtitleDisplay(t){this._subtitleDisplay=t,this.trackId>-1&&this.toggleTrackModes()}registerListeners(){const{hls:t}=this;t.on(Mt.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(Mt.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(Mt.MANIFEST_LOADING,this.onManifestLoading,this),t.on(Mt.MANIFEST_PARSED,this.onManifestParsed,this),t.on(Mt.LEVEL_LOADING,this.onLevelLoading,this),t.on(Mt.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(Mt.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(Mt.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(Mt.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(Mt.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(Mt.MANIFEST_LOADING,this.onManifestLoading,this),t.off(Mt.MANIFEST_PARSED,this.onManifestParsed,this),t.off(Mt.LEVEL_LOADING,this.onLevelLoading,this),t.off(Mt.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(Mt.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(Mt.ERROR,this.onError,this)}createTracksInGroup(){var t;if(!this.media||!this.hls.config.renderTextTracksNatively)return;this.tracksInGroup.forEach(r=>{r.trackNode||(r.trackNode=sJe(this.media,nqn(r),r.name,r.lang))});const n=(t=this.currentTrack)==null||(t=t.trackNode)==null?void 0:t.track;(n==null?void 0:n.mode)==="disabled"&&(n.mode=this._subtitleDisplay?"showing":"hidden")}onMediaAttached(t,n){const r=n.media;this.media=r;let a=this.trackId;this.queuedDefaultTrack>-1&&(a=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.setSubtitleTrack(a),this.createTracksInGroup(),this.useTextTrackPolling=!(r.textTracks&&"onchange"in r.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):r.textTracks.addEventListener("change",this.asyncPollTrackChange)}pollTrackChange(t){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,t)}onMediaDetaching(t,n){const r=this.media;if(!r)return;const a=!!n.transferMedia;self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||r.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId,this.setSubtitleTrack(-1)),this.media=null,!a&&this.hls.config.renderTextTracksNatively&&this.tracksInGroup.forEach(i=>{const l=i.trackNode;l&&(l.track.mode="hidden",l.remove(),i.trackNode=void 0)})}onManifestLoading(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(t,n){this.tracks=n.subtitleTracks}onSubtitleTrackLoaded(t,n){const{id:r,groupId:a,details:i}=n,l=this.tracksInGroup[r];if(!l||l.groupId!==a){this.warn(`Subtitle track with id:${r} and group:${a} not found in active group ${l==null?void 0:l.groupId}`);return}const o=l.details;l.details=n.details,this.log(`Subtitle track ${r} "${l.name}" lang:${l.lang} group:${a} loaded [${i.startSN}-${i.endSN}]`),r===this.trackId&&this.playlistLoaded(r,n,o)}onLevelLoading(t,n){this.switchLevel(n.level)}onLevelSwitching(t,n){this.switchLevel(n.level)}switchLevel(t){const n=this.hls.levels[t];if(!n)return;const r=n.subtitleGroups||null,a=this.groupIds;let i=this.currentTrack;if(!r||(a==null?void 0:a.length)!==(r==null?void 0:r.length)||r!=null&&r.some(l=>(a==null?void 0:a.indexOf(l))===-1)){this.groupIds=r;const l=[];if(this.tracks.forEach(u=>{(u.textCodec===_qe?this.hls.config.enableIMSC1:this.hls.config.enableWebVTT)&&(!r||r.indexOf(u.groupId)>-1?(u.id=l.length,l.push(u)):u.trackNode&&(u.trackNode.remove(),u.trackNode=void 0))}),l.length===this.tracksInGroup.length){let u=!1;for(let h=0;hu.default)&&(this.selectDefaultTrack=!1),this.tracksInGroup=l,this.trackId=-1,this.currentTrack=null;const o=this.hls.config.subtitlePreference;if(!i&&o){this.selectDefaultTrack=!1;const u=b5(o,l);if(u>-1)i=l[u];else{const h=b5(o,this.tracks);i=this.tracks[h]}}let c=this.findTrackId(i);c===-1&&i&&(c=this.findTrackId(null));const d={subtitleTracks:l};this.log(`Updating subtitle tracks, ${l.length} track(s) found in "${r==null?void 0:r.join(",")}" group-id`),this.hls.trigger(Mt.SUBTITLE_TRACKS_UPDATED,d),this.setSubtitleTrack(c),this.createTracksInGroup()}}findTrackId(t){const n=this.tracksInGroup,r=this.selectDefaultTrack;for(let a=0;a-1){const i=this.tracksInGroup[a];return this.setSubtitleTrack(a,!0),i}else{if(r)return null;{const i=b5(t,n);if(i>-1)return n[i]}}}}return null}loadPlaylist(t){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,t)}loadingPlaylist(t,n){super.loadingPlaylist(t,n);const r=t.id,a=t.groupId,i=this.getUrlWithDirectives(t.url,n),l=t.details,o=l==null?void 0:l.age;this.log(`Loading subtitle ${r} "${t.name}" lang:${t.lang} group:${a}${(n==null?void 0:n.msn)!==void 0?" at sn "+n.msn+" part "+n.part:""}${o&&l.live?" age "+o.toFixed(1)+(l.type&&" "+l.type||""):""} ${i}`),this.hls.trigger(Mt.SUBTITLE_TRACK_LOADING,{url:i,id:r,groupId:a,deliveryDirectives:n||null,track:t})}toggleTrackModes(){if(!this.media||!this.hls.config.renderTextTracksNatively)return;const t=this.currentTrack;this.tracksInGroup.forEach(n=>{if(n.trackNode){const r=n===t?this._subtitleDisplay?"showing":"hidden":"disabled",a=n.trackNode.track;a.mode!==r&&(a.mode=r)}})}setSubtitleTrack(t,n=!1){const r=this.tracksInGroup;if(this.media||(this.queuedDefaultTrack=t),t<-1||t>=r.length||!mi(t)){this.warn(`Invalid subtitle track id: ${t}`);return}const a=this.currentTrack,i=r[t]||null;if(this.trackId=t,this.currentTrack=i,n&&this.toggleTrackModes(),!i){a&&this.hls.trigger(Mt.SUBTITLE_TRACK_SWITCH,{id:t});return}const l=!!i.details&&!i.details.live;if(i===a&&l)return;this.log(`Switching to subtitle-track ${t}`+(i?` "${i.name}" lang:${i.lang} group:${i.groupId}`:""));const{id:o,groupId:c="",name:d,type:u,url:h}=i;this.hls.trigger(Mt.SUBTITLE_TRACK_SWITCH,{id:o,groupId:c,name:d,type:u,url:h});const m=this.switchParams(i.url,a==null?void 0:a.details,i.details);this.loadPlaylist(m)}}const vke=2,oqn=100;class lqn extends $Ht{constructor(t,n){super("gap-controller",t.logger),this.hls=void 0,this.fragmentTracker=void 0,this.media=null,this.mediaSource=void 0,this.nudgeRetry=0,this.skipRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.buffered={},this.lastCurrentTime=void 0,this.ended=0,this.waiting=0,this.onMediaPlaying=()=>{this.ended=0,this.waiting=0},this.onMediaWaiting=()=>{var r;(r=this.media)!=null&&r.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{if(this.hls){var r;this.ended=((r=this.media)==null?void 0:r.currentTime)||1,this.hls.trigger(Mt.MEDIA_ENDED,{stalled:!1})}},this.hls=t,this.fragmentTracker=n,this.lastCurrentTime=this.getCurrentTime(),this.registerListeners()}registerListeners(){const{hls:t}=this;t&&(t.on(Mt.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(Mt.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(Mt.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){const{hls:t}=this;t&&(t.off(Mt.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(Mt.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(Mt.BUFFER_APPENDED,this.onBufferAppended,this))}destroy(){super.destroy(),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0}onMediaAttached(t,n){this.setInterval(oqn),this.mediaSource=n.mediaSource;const r=this.media=n.media;th(r,"playing",this.onMediaPlaying),th(r,"waiting",this.onMediaWaiting),th(r,"ended",this.onMediaEnded)}onMediaDetaching(t,n){this.clearInterval();const{media:r}=this;r&&(Bu(r,"playing",this.onMediaPlaying),Bu(r,"waiting",this.onMediaWaiting),Bu(r,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0}onBufferAppended(t,n){this.buffered=n.timeRanges}get hasBuffered(){return Object.keys(this.buffered).length>0}getCurrentTime(){var t;const n=((t=this.hls)==null?void 0:t.config.timelineOffset)||0;return this.media?Math.max(this.media.currentTime,n):n}tick(){var t;if(!((t=this.media)!=null&&t.readyState)||!this.hasBuffered)return;const n=this.getCurrentTime();this.media.currentTimen&&this.nudgeOnVideoHole(t,n)),this.waiting===0&&this.stallResolved(t);return}if(d||c){c&&this.stallResolved(t);return}if(u){this.skipRetry=this.nudgeRetry=0,this.stallResolved(t),!this.ended&&l.ended&&this.hls&&(this.ended=t||1,this.hls.trigger(Mt.MEDIA_ENDED,{stalled:!1}));return}if(!pl.getBuffered(l).length){this.skipRetry=this.nudgeRetry=0;return}const h=pl.bufferInfo(l,t,0),m=this.fragmentTracker;m&&this.hls&&lwt(h,t,m,this.hls);const p=h.nextStart||0;if(o&&m&&this.hls){const M=iwt(this.hls.inFlightFragments,t),I=h.len>vke,P=!p||M||p-t>vke&&!m.getPartialFragment(t);if(I||P)return;this.moved=!1}const g=(a=this.hls)==null?void 0:a.latestLevelDetails;if(!this.moved&&this.stalled!==null&&m){if(!(h.len>0)&&!p)return;const I=Math.max(p,h.start||0)-t,R=!!(g!=null&&g.live)?g.targetduration*2:vke,O=aK(t,m);if(I>0&&(I<=R||O)){l.paused||this._trySkipBufferHole(O);return}}const x=i.detectStallWithCurrentTimeMs,y=self.performance.now(),v=this.waiting;let _=this.stalled;if(_===null)if(v>0&&y-v=x||v&&this.moved)&&this.hls){var C;if(((C=this.mediaSource)==null?void 0:C.readyState)==="ended"&&!(g!=null&&g.live)&&Math.abs(t-((g==null?void 0:g.edge)||0))<1){if(this.ended)return;this.ended=t||1,this.hls.trigger(Mt.MEDIA_ENDED,{stalled:!0});return}if(this._reportStall(h),!this.media||!this.hls)return;if(l.currentTime!==t){const M=t;t=l.currentTime,this.moved=!0,this.log(`currentTime changed ${M} > ${t}`);return}}const A=pl.bufferInfo(l,t,i.maxBufferHole);this._tryFixBufferStall(A,j,t)}stallResolved(t){const n=this.stalled;if(n&&this.hls&&(this.stalled=null,this.stallReported)){const r=self.performance.now()-n;this.log(`playback not stuck anymore @${t}, after ${Math.round(r)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger(Mt.STALL_RESOLVED,{})}}nudgeOnVideoHole(t,n){var r;const a=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&(r=this.buffered.audio)!=null&&r.length&&a&&a.length>1&&t>a.end(0)){const i=pl.bufferedInfo(pl.timeRangesToArray(this.buffered.audio),t,0);if(i.len>1&&n>=i.start){const l=pl.timeRangesToArray(a),o=pl.bufferedInfo(l,n,0).bufferedIndex;if(o>-1&&oo)&&u-d<1&&t-d<2){const h=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${t} hole: ${d} -> ${u} buffered index: ${c}`);this.warn(h.message),this.media.currentTime+=1e-6;let m=aK(t,this.fragmentTracker);m&&"fragment"in m?m=m.fragment:m||(m=void 0);const p=pl.bufferInfo(this.media,t,0);this.hls.trigger(Mt.ERROR,{type:xo.MEDIA_ERROR,details:er.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:h,reason:h.message,frag:m,buffer:p.len,bufferInfo:p})}}}}}_tryFixBufferStall(t,n,r){var a,i;const{fragmentTracker:l,media:o}=this,c=(a=this.hls)==null?void 0:a.config;if(!o||!l||!c)return;const d=(i=this.hls)==null?void 0:i.latestLevelDetails,u=aK(r,l);if((u||d!=null&&d.live&&r1&&t.len>c.maxBufferHole||t.nextStart&&(t.nextStart-rc.highBufferWatchdogPeriod*1e3||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(t))}adjacentTraversal(t,n){const r=this.fragmentTracker,a=t.nextStart;if(r&&a){const i=r.getFragAtPos(n,Ji.MAIN),l=r.getFragAtPos(a,Ji.MAIN);if(i&&l)return l.sn-i.sn<2}return!1}_reportStall(t){const{hls:n,media:r,stallReported:a,stalled:i}=this;if(!a&&i!==null&&r&&n){this.stallReported=!0;const l=new Error(`Playback stalling at @${r.currentTime} due to low buffer (${bm(t)})`);this.warn(l.message),n.trigger(Mt.ERROR,{type:xo.MEDIA_ERROR,details:er.BUFFER_STALLED_ERROR,fatal:!1,error:l,buffer:t.len,bufferInfo:t,stalled:{start:i}})}}_trySkipBufferHole(t){const{fragmentTracker:n,media:r,hls:a}=this,i=a==null?void 0:a.config;if(!r||!n||!i)return 0;const l=r.currentTime,o=pl.bufferInfo(r,l,0);lwt(o,l,n,a);const c=l0&&o.len<1&&r.readyState<3,m=c-l;if(m>0&&(u||h)){if(m>i.maxBufferHole){let v=!1;if(l===0){const _=n.getAppendedFrag(0,Ji.MAIN);_&&c<_.end&&(v=!0)}if(!v&&t){var d;if(!((d=a.loadLevelObj)!=null&&d.details)||iwt(a.inFlightFragments,c))return 0;let j=!1,C=t.end;for(;C0)C+=M;else{j=!0;break}}if(j)return 0}}const{nudgeMaxRetry:p,skipBufferHolePadding:g}=i,x=++this.skipRetry>p,y=Math.max(c,l)+g;if(x||(this.warn(`skipping hole, adjusting currentTime from ${l} to ${y}`),this.moved=!0,r.currentTime=y),!(t!=null&&t.gap)||x){const v=new Error(x?`Playhead still not moving after seeking over buffer hole from ${l} to ${y} after ${i.nudgeMaxRetry} attempts.`:`fragment loaded with buffer holes, seeking from ${l} to ${y}`),_={type:xo.MEDIA_ERROR,details:er.BUFFER_SEEK_OVER_HOLE,fatal:x,error:v,reason:v.message,buffer:o.len,bufferInfo:o};t&&("fragment"in t?_.part=t:_.frag=t),a.trigger(Mt.ERROR,_)}return y}}return 0}_tryNudgeBuffer(t){const{hls:n,media:r,nudgeRetry:a}=this,i=n==null?void 0:n.config;if(!r||!i)return 0;const l=r.currentTime;if(this.nudgeRetry++,a"u"))return self.VTTCue||self.TextTrackCue}function E8e(s,t,n,r,a){let i=new s(t,n,"");try{i.value=r,a&&(i.type=a)}catch{i=new s(t,n,bm(a?wo({type:a},r):r))}return i}const fie=(()=>{const s=Nqe();try{s&&new s(0,Number.POSITIVE_INFINITY,"")}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();class dqn{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(Mt.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(Mt.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(Mt.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(Mt.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(Mt.MANIFEST_LOADING,this.onManifestLoading,this),t.on(Mt.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.on(Mt.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(Mt.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(Mt.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}_unregisterListeners(){const{hls:t}=this;t&&(t.off(Mt.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(Mt.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(Mt.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(Mt.MANIFEST_LOADING,this.onManifestLoading,this),t.off(Mt.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.off(Mt.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(Mt.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(Mt.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}onMediaAttaching(t,n){this.media=n.media}onMediaAttached(){var t;const n=(t=this.hls)==null?void 0:t.latestLevelDetails;n&&this.updateDateRangeCues(n)}onMediaDetaching(t,n){this.media=null,!n.transferMedia&&(this.id3Track&&(this.id3Track.remove(),this.id3Track=null),this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(t){return sJe(t,"metadata","id3","","hidden")}onFragParsingMetadata(t,n){if(!this.media||!this.hls)return;const{enableEmsgMetadataCues:r,enableID3MetadataCues:a}=this.hls.config;if(!r&&!a)return;const{samples:i}=n;this.id3Track||(this.id3Track=this.createTrack(this.media));const l=Nqe();if(l)for(let o=0;ofie&&(h=fie),h-u<=0&&(h=u+cqn);for(let p=0;pu.type===nb.audioId3&&c:a==="video"?d=u=>u.type===nb.emsg&&o:d=u=>u.type===nb.audioId3&&c||u.type===nb.emsg&&o,jqe(i.track,n,r,d)}}onLevelUpdated(t,{details:n}){this.updateDateRangeCues(n,!0)}onLevelPtsUpdated(t,n){Math.abs(n.drift)>.01&&this.updateDateRangeCues(n.details)}updateDateRangeCues(t,n){if(!this.hls||!this.media)return;const{assetPlayerId:r,timelineOffset:a,enableDateRangeMetadataCues:i,interstitialsController:l}=this.hls.config;if(!i)return;const o=Nqe();if(r&&a&&!l){const{fragmentStart:x,fragmentEnd:y}=t;let v=this.assetCue;v?(v.startTime=x,v.endTime=y):o&&(v=this.assetCue=E8e(o,x,y,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"),v&&(v.id=r,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.track.addCue(v),v.addEventListener("enter",this.onEventCueEnter)))}if(!t.hasProgramDateTime)return;const{id3Track:c}=this,{dateRanges:d}=t,u=Object.keys(d);let h=this.dateRangeCuesAppended;if(c&&n){var m;if((m=c.track.cues)!=null&&m.length){const x=Object.keys(h).filter(y=>u.indexOf(y)===-1);for(let y=x.length;y--;){var p;const v=x[y],_=(p=h[v])==null?void 0:p.cues;delete h[v],_&&Object.keys(_).forEach(j=>{const C=_[j];if(C){C.removeEventListener("enter",this.onEventCueEnter);try{c.track.removeCue(C)}catch{}}})}}else h=this.dateRangeCuesAppended={}}const g=t.fragments[t.fragments.length-1];if(!(u.length===0||!mi(g==null?void 0:g.programDateTime))){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let x=0;x{if(U!==v.id){const G=d[U];if(G.class===v.class&&G.startDate>v.startDate&&(!B||v.startDate.01&&(U.startTime=_,U.endTime=M);else if(o){let G=v.attr[B];aBn(B)&&(G=gHt(G));const Y=E8e(o,_,M,{key:B,data:G},nb.dateRange);Y&&(Y.id=y,this.id3Track.track.addCue(Y),C[B]=Y,l&&(B==="X-ASSET-LIST"||B==="X-ASSET-URL")&&Y.addEventListener("enter",this.onEventCueEnter))}}h[y]={cues:C,dateRange:v,durationKnown:A}}}}}function ZGt(){return self.SourceBuffer||self.WebKitSourceBuffer}function XGt(){if(!zM())return!1;const t=ZGt();return!t||t.prototype&&typeof t.prototype.appendBuffer=="function"&&typeof t.prototype.remove=="function"}function uqn(){if(!XGt())return!1;const s=zM();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(vQ(t,"video")))||["mp4a.40.2","fLaC"].some(t=>s.isTypeSupported(vQ(t,"audio"))))}function hqn(){var s;const t=ZGt();return typeof(t==null||(s=t.prototype)==null?void 0:s.changeType)=="function"}var gS={DISABLED:0,SWITCHING:1,SWITCHED:2};const mqn=100;class QGt extends BQe{constructor(t,n,r){super(t,n,r,"stream-controller",Ji.MAIN),this.audioCodecSwap=!1,this.level=-1,this._forceStartLoad=!1,this._hasEnoughToStart=!1,this.altAudio=gS.DISABLED,this.audioOnly=!1,this._couldBacktrack=!1,this._backtrackFragment=void 0,this.audioCodecSwitch=!1,this.videoBuffer=null,this.onMediaPlaying=()=>{this.tick()},this.onMediaSeeked=()=>{const a=this.media,i=a?a.currentTime:null;if(i===null||!mi(i)||(this.log(`Media seeked to ${i}`),!this.getBufferedFrag(i)))return;const l=this.getFwdBufferInfoAtPos(a,i,Ji.MAIN,0);if(!l||l.len===0){this.log(`Main buffer empty at ${i} on "seeked" event: ${l&&l.len}`);return}this.tick()},this.registerListeners()}registerListeners(){super.registerListeners();const{hls:t}=this;t.on(Mt.MANIFEST_PARSED,this.onManifestParsed,this),t.on(Mt.LEVEL_LOADING,this.onLevelLoading,this),t.on(Mt.LEVEL_LOADED,this.onLevelLoaded,this),t.on(Mt.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.on(Mt.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(Mt.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.on(Mt.BUFFER_CREATED,this.onBufferCreated,this),t.on(Mt.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(Mt.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(Mt.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();const{hls:t}=this;t.off(Mt.MANIFEST_PARSED,this.onManifestParsed,this),t.off(Mt.LEVEL_LOADED,this.onLevelLoaded,this),t.off(Mt.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.off(Mt.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(Mt.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.off(Mt.BUFFER_CREATED,this.onBufferCreated,this),t.off(Mt.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(Mt.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(Mt.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),super.onHandlerDestroying()}startLoad(t,n){if(this.levels){const{lastCurrentTime:r,hls:a}=this;if(this.stopLoad(),this.setInterval(mqn),this.level=-1,!this.startFragRequested){let i=a.startLevel;i===-1&&(a.config.testBandwidth&&this.levels.length>1?(i=0,this.bitrateTest=!0):i=a.firstAutoLevel),a.nextLoadLevel=i,this.level=a.loadLevel,this._hasEnoughToStart=!!n}r>0&&t===-1&&!n&&this.initPTS.length&&(this.log(`Override startPosition with lastCurrentTime @${r}`),t=r),this.state=Kr.IDLE,this.nextLoadPosition=this.lastCurrentTime=t+this.timelineOffset,this.startPosition=n?-1:t,!n&&!this.fragmentTracker.hasFragments(this.playlistType)&&(this._hasEnoughToStart=this.startFragRequested=!1),this.tick()}else this._forceStartLoad=!0,this.state=Kr.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case Kr.WAITING_LEVEL:{const{levels:t,level:n}=this,r=t==null?void 0:t[n],a=r==null?void 0:r.details;if(a&&(!a.live||this.levelLastLoaded===r&&!this.waitForLive(r))){if(this.waitForCdnTuneIn(a))break;this.state=Kr.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=Kr.IDLE;break}break}case Kr.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate();break}this.state===Kr.IDLE&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){var t;super.onTickEnd(),(t=this.media)!=null&&t.readyState&&this.media.seeking===!1&&(this.lastCurrentTime=this.media.currentTime),this.checkFragmentChanged()}doTickIdle(){const{hls:t,levelLastLoaded:n,levels:r,media:a}=this;if(n===null||!a&&!this.primaryPrefetch&&(this.startFragRequested||!t.config.startFragPrefetch)||this.altAudio&&this.audioOnly)return;const i=this.buffering?t.nextLoadLevel:t.loadLevel;if(!(r!=null&&r[i]))return;const l=r[i],o=this.getMainFwdBufferInfo();if(o===null)return;const c=this.getLevelDetails();if(c&&this._streamEnded(o,c)){const x={type:this.targetBufferType()};this.hls.trigger(Mt.BUFFER_EOS,x),this.state=Kr.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===Kr.WAITING_LEVEL||this.waitForLive(l)){this.level=i,this.state=Kr.WAITING_LEVEL,this.startFragRequested=!1;return}const u=o.len,h=this.getMaxBufferLength(l.maxBitrate);if(u>=h)return;this.backtrackFragment&&this.backtrackFragment.start>o.end&&(this.backtrackFragment=void 0);const m=this.backtrackFragment?this.backtrackFragment.start:o.end;let p=this.getNextFragment(m,d);if(this.couldBacktrack&&!this.fragPrevious&&p&&Lp(p)&&this.fragmentTracker.getState(p)!==ep.OK){var g;const y=((g=this.backtrackFragment)!=null?g:p).sn-d.startSN,v=d.fragments[y-1];v&&p.cc===v.cc&&(p=v,this.fragmentTracker.removeFragment(v))}else this.backtrackFragment&&o.len&&(this.backtrackFragment=void 0);if(p&&this.isLoopLoading(p,m)){if(!p.gap){const y=this.audioOnly&&!this.altAudio?Xh.AUDIO:Xh.VIDEO,v=(y===Xh.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;v&&this.afterBufferFlushed(v,y)}p=this.getNextFragmentLoopLoading(p,d,o,Ji.MAIN,h)}p&&(this.exceedsMaxBuffer(o,h,p)||this.loadFragment(p,l,m))}loadFragment(t,n,r){const a=this.fragmentTracker.getState(t);a===ep.NOT_LOADED||a===ep.PARTIAL?this.bitrateTest?(this.log(`Fragment ${t.sn} of level ${t.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(t,n)):super.loadFragment(t,n,r):this.clearTrackerIfNeeded(t)}immediateLevelSwitch(){if(this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY),this.altAudio!==gS.DISABLED){var t;(((t=this.getLevelDetails())==null?void 0:t.fragmentStart)||0)>this.lastCurrentTime&&super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio")}}getBufferOutput(){return this.mediaBuffer&&this.altAudio===gS.SWITCHED?this.mediaBuffer:this.media}checkFragmentChanged(){const t=this.fragPlaying;if(!this.checkFragPlaying())return!1;const r=this.fragPlaying;if(r){const a=r.level;this.hls.trigger(Mt.FRAG_CHANGED,{frag:r,previousFrag:t}),(t==null?void 0:t.level)!==a&&this.hls.trigger(Mt.LEVEL_SWITCHED,{level:a})}return!0}get backtrackFragment(){return this._backtrackFragment}set backtrackFragment(t){this._backtrackFragment=t}get couldBacktrack(){return this._couldBacktrack}set couldBacktrack(t){this._couldBacktrack=t}abortCurrentFrag(){this.backtrackFragment=void 0,super.abortCurrentFrag()}flushMainBuffer(t,n){super.flushMainBuffer(t,n,this.targetBufferType())}targetBufferType(){return this.altAudio===gS.SWITCHED&&!this.audioOnly?"video":null}onMediaAttached(t,n){super.onMediaAttached(t,n);const r=n.media;th(r,"playing",this.onMediaPlaying),th(r,"seeked",this.onMediaSeeked)}onMediaDetaching(t,n){const{media:r}=this;r&&(Bu(r,"playing",this.onMediaPlaying),Bu(r,"seeked",this.onMediaSeeked)),this.videoBuffer=null,super.onMediaDetaching(t,n),!n.transferMedia&&(this._hasEnoughToStart=!1)}onManifestLoading(){super.onManifestLoading(),this.log("Trigger BUFFER_RESET"),this.hls.trigger(Mt.BUFFER_RESET,void 0),this.couldBacktrack=!1,this.backtrackFragment=void 0,this.altAudio=gS.DISABLED,this.audioOnly=!1}onManifestParsed(t,n){let r=!1,a=!1;for(let i=0;i{if(g>=o.startCC)return!0;delete this.initPTS[g]}),this.tick()}synchronizeToLiveEdge(t){const{config:n,media:r}=this;if(!r)return;const a=this.hls.liveSyncPosition,i=this.playhead,l=t.fragmentStart,o=t.edge,c=i>=l-n.maxFragLookUpTolerance&&i<=o;if(a!==null&&r.duration>a&&(i{this.hls&&this.hls.trigger(Mt.AUDIO_TRACK_SWITCHED,n)}),r.trigger(Mt.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});return}r.trigger(Mt.AUDIO_TRACK_SWITCHED,n)}}onAudioTrackSwitched(t,n){const r=aCe(n.url,this.hls);if(r){const a=this.videoBuffer;a&&this.mediaBuffer!==a&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=a)}this.altAudio=r?gS.SWITCHED:gS.DISABLED,this.tick()}onBufferCreated(t,n){const r=n.tracks;let a,i,l=!1;for(const o in r){const c=r[o];if(c.id==="main"){if(i=o,a=c,o==="video"){const d=r[o];d&&(this.videoBuffer=d.buffer)}}else l=!0}l&&a?(this.log(`Alternate track found, use ${i}.buffered to schedule main fragment loading`),this.mediaBuffer=a.buffer):this.mediaBuffer=this.media}onFragBuffered(t,n){const{frag:r,part:a}=n,i=r.type===Ji.MAIN;if(i){if(this.fragContextChanged(r)){this.warn(`Fragment ${r.sn}${a?" p: "+a.index:""} of level ${r.level} finished buffering, but was aborted. state: ${this.state}`),this.state===Kr.PARSED&&(this.state=Kr.IDLE);return}let c=!1;if(Lp(r)&&(c=!!r.gap&&!r.tagList.some(d=>d[0]==="GAP")),this.fragBufferedComplete(r,a),c){var l;r.stats.retry++;const d=(l=this.levels)==null?void 0:l[r.level];d&&d.fragmentError++}}const o=this.media;o&&(!this._hasEnoughToStart&&pl.getBuffered(o).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),i&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(t,n){var r;if(n.fatal){this.state=Kr.ERROR;return}switch(n.details){case er.FRAG_GAP:case er.FRAG_PARSING_ERROR:case er.FRAG_DECRYPT_ERROR:case er.FRAG_LOAD_ERROR:case er.FRAG_LOAD_TIMEOUT:case er.KEY_LOAD_ERROR:case er.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(Ji.MAIN,n);break;case er.LEVEL_LOAD_ERROR:case er.LEVEL_LOAD_TIMEOUT:case er.LEVEL_PARSING_ERROR:!n.levelRetry&&this.state===Kr.WAITING_LEVEL&&((r=n.context)==null?void 0:r.type)===Mc.LEVEL&&(this.state=Kr.IDLE);break;case er.BUFFER_APPEND_NO_PROGRESS:if(n.parent!=="main")return;n.frag&&(n.appendsWithoutProgress||0)>=this.config.appendErrorMaxRetry&&(this.warn(`Marking fragment ${n.frag.sn} of level ${n.frag.level} as a gap after ${n.appendsWithoutProgress} appends without buffered range growth, to prevent loop loading`),this.fragmentTracker.addAsGap(n.frag));break;case er.BUFFER_ADD_CODEC_ERROR:case er.BUFFER_APPEND_ERROR:if(n.parent!=="main")return;this.reduceLengthAndFlushBuffer(n)&&this.resetLoadingState();break;case er.BUFFER_FULL_ERROR:if(n.parent!=="main")return;this.reduceLengthAndFlushBuffer(n)&&(!this.config.interstitialsController&&this.config.assetPlayerId?this._hasEnoughToStart=!0:this.flushMainBuffer(0,Number.POSITIVE_INFINITY));break;case er.INTERNAL_EXCEPTION:this.recoverWorkerError(n);break}}onFragLoadEmergencyAborted(){this.state=Kr.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(t,{type:n}){if(n!==Xh.AUDIO||!this.altAudio){const r=(n===Xh.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;r&&(this.afterBufferFlushed(r,n),this.tick())}}onLevelsUpdated(t,n){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,this.level===-1&&this.resetWhenMissingContext(this.fragCurrent)),this.levels=n.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){const{media:t}=this;if(!t)return;const n=t.currentTime;let r=this.startPosition;if(r>=0&&n0&&(c{const{hls:a}=this,i=r==null?void 0:r.frag;if(!i||this.fragContextChanged(i))return;n.fragmentError=0,this.state=Kr.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(Mt.FRAG_LOADED,r),i.bitrateTest=!1}).catch(r=>{this.state===Kr.STOPPED||this.state===Kr.ERROR||(this.warn(r),this.resetFragmentLoading(t))})}_handleTransmuxComplete(t){const n=this.playlistType,{hls:r}=this,{remuxResult:a,chunkMeta:i}=t,l=this.getCurrentContext(i);if(!l){this.resetWhenMissingContext(i);return}const{frag:o,part:c,level:d}=l,{video:u,text:h,id3:m,initSegment:p}=a,{details:g}=d,x=this.altAudio?void 0:a.audio;if(this.fragContextChanged(o)){this.fragmentTracker.removeFragment(o);return}if(this.state=Kr.PARSING,p){const y=p.tracks;if(y){const C=o.initSegment||o;if(this.unhandledEncryptionError(p,o))return;this._bufferInitSegment(d,y,C,i),r.trigger(Mt.FRAG_PARSING_INIT_SEGMENT,{frag:C,id:n,tracks:y})}const v=p.initPTS,_=p.timescale,j=this.initPTS[o.cc];if(mi(v)&&(!j||j.baseTime!==v||j.timescale!==_)){const C=p.trackId;this.initPTS[o.cc]={baseTime:v,timescale:_,trackId:C};const A=this.initPTS.slice(0);r.trigger(Mt.INIT_PTS_FOUND,{timestampOffsets:A,frag:o,id:n,initPTS:v,timescale:_,trackId:C})}}if(u&&g){x&&u.type==="audiovideo"&&this.logMuxedErr(o);const y=g.fragments[o.sn-1-g.startSN],v=o.sn===g.startSN,_=!y||o.cc>y.cc;if(a.independent!==!1){const{startPTS:j,endPTS:C,startDTS:A,endDTS:M}=u;if(c)c.elementaryStreams[u.type]={startPTS:j,endPTS:C,startDTS:A,endDTS:M};else if(u.firstKeyFrame&&u.independent&&i.id===1&&!_&&(this.couldBacktrack=!0),u.dropped&&u.independent){const I=this.getMainFwdBufferInfo(),P=(I?I.end:this.getLoadPosition())+this.config.maxBufferHole,R=u.firstKeyFramePTS?u.firstKeyFramePTS:j;if(!v&&Pvke&&(o.gap=!0);o.setElementaryStreamInfo(u.type,j,C,A,M),this.backtrackFragment&&(this.backtrackFragment=o),this.bufferFragmentData(u,o,c,i,v||_)}else if(v||_)o.gap=!0;else{this.backtrack(o);return}}if(x){const{startPTS:y,endPTS:v,startDTS:_,endDTS:j}=x;c&&(c.elementaryStreams[Xh.AUDIO]={startPTS:y,endPTS:v,startDTS:_,endDTS:j}),o.setElementaryStreamInfo(Xh.AUDIO,y,v,_,j),this.bufferFragmentData(x,o,c,i)}if(g&&m!=null&&m.samples.length){const y={id:n,frag:o,details:g,samples:m.samples};r.trigger(Mt.FRAG_PARSING_METADATA,y)}if(g&&h){const y={id:n,frag:o,details:g,samples:h.samples};r.trigger(Mt.FRAG_PARSING_USERDATA,y)}}logMuxedErr(t){this.warn(`${Lp(t)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${t.url}`)}_bufferInitSegment(t,n,r,a){if(this.state!==Kr.PARSING)return;this.audioOnly=!!n.audio&&!n.video,this.altAudio&&!this.audioOnly&&(delete n.audio,n.audiovideo&&this.logMuxedErr(r));const{audio:i,video:l,audiovideo:o}=n;if(i){const d=t.audioCodec;let u=pke(i.codec,d);if(u==="mp4a"&&(u="mp4a.40.5"),this.audioCodecSwitch){u&&(u.indexOf("mp4a.40.5")!==-1?u="mp4a.40.2":u="mp4a.40.5");const h=i.metadata;h&&"channelCount"in h&&(h.channelCount||1)!==1&&!yzn()&&(u="mp4a.40.5")}u&&u.indexOf("mp4a.40.5")!==-1&&bzn()&&i.container!=="audio/mpeg"&&(u="mp4a.40.2",this.log(`Android: force audio codec to ${u}`)),d&&d!==u&&this.log(`Swapping manifest audio codec "${d}" for "${u}"`),i.levelCodec=u,i.id=Ji.MAIN,this.log(`Init audio buffer, container:${i.container}, codecs[selected/level/parsed]=[${u||""}/${d||""}/${i.codec}]`),delete n.audiovideo}if(l){l.levelCodec=t.videoCodec,l.id=Ji.MAIN;const d=l.codec;if((d==null?void 0:d.length)===4)switch(d){case"hvc1":case"hev1":l.codec="hvc1.1.6.L120.90";break;case"av01":l.codec="av01.0.04M.08";break;case"avc1":l.codec="avc1.42e01e";break}this.log(`Init video buffer, container:${l.container}, codecs[level/parsed]=[${t.videoCodec||""}/${d}]${l.codec!==d?" parsed-corrected="+l.codec:""}${l.supplemental?" supplemental="+l.supplemental:""}`),delete n.audiovideo}o&&(this.iframesOnly&&this.logMuxedErr(r),this.log(`Init audiovideo buffer, container:${o.container}, codecs[level/parsed]=[${t.codecs}/${o.codec}]`),delete n.video,delete n.audio);const c=Object.keys(n);if(c.length){if(this.hls.trigger(Mt.BUFFER_CODECS,n),!this.hls)return;c.forEach(d=>{const h=n[d].initSegment;h!=null&&h.byteLength&&this.hls.trigger(Mt.BUFFER_APPENDING,{type:d,data:h,frag:r,part:null,chunkMeta:a,parent:r.type})})}this.tickImmediate()}getMainFwdBufferInfo(){const t=this.getBufferOutput();return this.getFwdBufferInfo(t,Ji.MAIN)}get maxBufferLength(){const{levels:t,level:n}=this,r=t==null?void 0:t[n];return r?this.getMaxBufferLength(r.maxBitrate):this.config.maxBufferLength}backtrack(t){this.couldBacktrack=!0,this.backtrackFragment=t,this.resetTransmuxer(),this.flushBufferGap(t),this.fragmentTracker.removeFragment(t),this.fragPrevious=null,this.nextLoadPosition=t.start,this.state=Kr.IDLE}get nextLevel(){const t=this.nextBufferedFrag;return t?t.level:-1}get currentFrag(){var t;if(this.fragPlaying)return this.fragPlaying;const n=((t=this.media)==null?void 0:t.currentTime)||this.lastCurrentTime;return mi(n)?this.getAppendedFrag(n):null}get currentProgramDateTime(){var t;const n=((t=this.media)==null?void 0:t.currentTime)||this.lastCurrentTime;if(mi(n)){const r=this.getLevelDetails(),a=this.currentFrag||(r?bq(null,r.fragments,n):null);if(a){const i=a.programDateTime;if(i!==null){const l=i+(n-a.start)*1e3;return new Date(l)}}}return null}get currentLevel(){const t=this.currentFrag;return t?t.level:-1}get nextBufferedFrag(){const t=this.currentFrag;return t?this.followingBufferedFrag(t):null}get forceStartLoad(){return this._forceStartLoad}}class JGt extends QGt{constructor(...t){super(...t),this.currentOp=void 0,this.nextOp=void 0,this.cached=[],this.cachedSize=0,this.cacheFragmentData=!0,this.initDetails=void 0,this.onBufferedToEnd=()=>{const n=this.media;n!=null&&n.seeking&&(n.currentTime=n.currentTime)},this.onMediaSeeking=()=>{}}setInitPts(t){this.initPTS=t.slice()}loadMediaAt(t,n){if(!this.hls)return;const{seekOnAppend:r}=n,a=t+this.timelineOffset;switch(this.nextLoadPosition=this.lastCurrentTime=a,this.startPosition=t,this.state){case Kr.STOPPED:case Kr.ENDED:case Kr.ERROR:this.state=Kr.IDLE}this.state===Kr.IDLE?(this.hls.resumeBuffering(),this.tick(),this.currentOp=[a,n]):this.nextOp=[a,n],this.hls.off(Mt.BUFFERED_TO_END,this.onBufferedToEnd);const i=this.media;r&&i&&this.seekTo(a)&&(this.currentOp=[a,n],this.nextOp=void 0,this.flushPipeline(a,!0))}seekTo(t){const n=this.media;if(n){var r;const a=(r=this.getLevelDetails())==null?void 0:r.edge,i=a!==void 0?a:n.duration;if(t>=i&&(t=i-.01),pl.bufferInfo(n,t,0).len>0&&this.getBufferedAt(t))return n.currentTime=t,!0}return!1}getBufferedAt(t){return this.fragmentTracker.getBufferedFrag(t,Ji.MAIN)}cacheSet(t,n){if(!this.hls)return;t.data=n;const r=this.cached;r.push(t),this.cachedSize+=n.buffer.byteLength;const a=this.hls.config.iframeCacheLimit;for(;this.cachedSize>a&&r.length>1;){const i=r.shift();if(i.data)this.cachedSize-=i.data.byteLength,i.data=void 0;else{this.cached=r.filter(l=>!!l.data),this.cachedSize=r.reduce((l,{data:o})=>o?o.buffer.byteLength:0,0);break}}}onHandlerDestroying(){this.cached.length=0,this.cachedSize=0,super.onHandlerDestroying()}_handleFragmentLoadProgress(t){const n=t.frag,{part:r,payload:a}=t;this.cacheFragmentData&&!r&&a!=null&&a.byteLength&&!n.data&&Lp(n)&&this.cacheSet(n,new Uint8Array(a.slice(0))),super._handleFragmentLoadProgress(t)}loadFragment(t,n,r){const a=this.fragmentTracker.getState(t);if((a===ep.NOT_LOADED||a===ep.PARTIAL)&&this.canReplayCached(t)){this.replayCachedFragment(t);return}super.loadFragment(t,n,r)}canReplayCached(t){var n;if(!this.cacheFragmentData||!((n=t.data)!=null&&n.byteLength))return!1;const r=t.decryptdata;return(r==null?void 0:r.keyFormat)!=="identity"||!!r.key}replayCachedFragment(t){const n=t.data.slice().buffer;this.log(`Buffering cached ${t.type} sn: ${t.sn} of level ${t.level} (${n.byteLength} bytes)`),this.fragCurrent=t,this.startFragRequested=!0;const r=t.stats=new AQe;r.loading.start=r.loading.first=r.loading.end=self.performance.now(),r.loaded=r.total=n.byteLength,r.chunkCount=1,this.state=Kr.FRAG_LOADING;const a={frag:t,part:null,payload:n,networkDetails:null};this._handleFragmentLoadProgress(a),this.hls.trigger(Mt.FRAG_LOADED,a),this._handleFragmentLoadComplete(a)}fragBufferedComplete(t,n){super.fragBufferedComplete(t,n);const{currentOp:r,nextOp:a}=this;this.currentOp=this.nextOp=void 0,this.state=Kr.STOPPED,r!=null&&r[1].seekOnAppend&&(this.flushPipeline(r[0],!a),this.seekTo(r[0])||this.log(`Could not seek to ${r[0]} after fragment buffered (superseded or flushed) buffer: ${this.media?dCe(pl.getBuffered(this.media)):"none"}`)),a&&this.loadMediaAt.apply(this,a)}flushPipeline(t,n){if(n){const r=this.media;if(r){const a=pl.bufferInfo(r,t,0),i=a.len?a.nextStart:0;i&&(this.fragmentTracker.removeFragmentsInRange(i,1/0,Ji.MAIN),this.flushMainBuffer(i,1/0))}this.hls.once(Mt.BUFFERED_TO_END,this.onBufferedToEnd)}this.hls.trigger(Mt.BUFFER_EOS,{type:"video"})}get playhead(){return this.nextLoadPosition}startLoad(){if(!this.startFragRequested){const t=this.hls;t.nextLoadLevel=t.startLevel===-1?0:t.firstAutoLevel}}seekToStartPos(){}setStartPosition(){}alignPlaylists(t,n,r){const a=this.initDetails;return this.initDetails=null,super.alignPlaylists(t,n,r||a||void 0)}getMainFwdBufferInfo(){const t=this.playhead,n=this.getBufferedAt(t);if(n){const r=n.duration;return{len:r,start:t,end:t+r,bufferedIndex:-1}}return{len:0,start:t,end:t,bufferedIndex:-1}}_streamEnded(){const t=this.playhead,n=this.fragmentTracker.getBufferedFrag(t,Ji.MAIN);return!!(n!=null&&n.endList)}}class fqn extends JGt{constructor(...t){super(...t),this._img=void 0,this.queued=void 0,this.cacheFragmentData=!1}get image(){return this._img}set image(t){var n;const r=(n=this._img)==null?void 0:n.src;r&&self.URL.revokeObjectURL(r),this._img=t}loadMediaAt(t){if(!this.hls)return;const n=t+this.timelineOffset;switch(this.nextLoadPosition=this.lastCurrentTime=n,this.startPosition=t,this.state){case Kr.STOPPED:case Kr.ENDED:case Kr.ERROR:this.state=Kr.IDLE}if(this.state===Kr.IDLE){if(this.hls.resumeBuffering(),this.media||(this.media={}),this.tick(),this.state===Kr.IDLE){const r=this.getBufferedAt(t);r&&(this.fragCurrent=r,this.updateImage(r,null))}}else{const r=this.fragCurrent;(!r||t>=r.start&&t{if(!this.hls)return;const u=this.hls.levels[t.level];u!=null&&u.fragmentError&&(u.fragmentError=0,t.stats.retry=0);const h=self.performance.now(),m=n?n.stats:t.stats;m.buffering.end=t.stats.buffering.end=h,this.hls.trigger(Mt.FRAG_BUFFERED,{frag:t,part:n,stats:m,id:t.type,chunkMeta:r})},i.onerror=()=>{this.handleError("Image decode error",t,n,r)};const c=i.src;c&&self.URL.revokeObjectURL(c);const d=new Blob([a],{type:"image/jpeg"});i.src=self.URL.createObjectURL(d)}else this.state=Kr.STOPPED,this.processQueued()}processQueued(){const t=this.queued;this.queued=void 0,t&&this.loadMediaAt.apply(this,t)}handleError(t,n,r,a){if(!this.hls)return;const i=new Error(t);this.hls.trigger(Mt.ERROR,{type:xo.MEDIA_ERROR,details:er.FRAG_PARSING_ERROR,chunkMeta:a,frag:n,part:r,fatal:!1,error:i,err:i})}_bufferInitSegment(){}bufferFragmentData(t,n,r,a){super.bufferFragmentData(t,n,r,a,!0);const i=Tl(new Uint8Array(t.data1),["mdat"]);if(i.length===0){this.handleError("Could not find I-Frame mdat",n,r,a);return}const l=n;this.cacheSet(l,i[0]),this.updateImage(l,r,a)}fragBufferedComplete(t,n){this.fragmentTracker.fragBuffered(t,!0),super.fragBufferedComplete(t,n),this.processQueued()}checkFragPlaying(){var t;const n=(t=this.fragPrevious)==null?void 0:t.start;if(n!==void 0){const r=this.getAppendedFrag(n);if(r&&!rK(r,this.fragPlaying))return this.fragPlaying=r,!0}return!1}getMainFwdBufferInfo(){return{len:0,start:this.playhead,end:this.playhead,bufferedIndex:-1}}}const pqn=10,gqn="Image I-Frame player does not accept HTMLMediaElements",cwt={seekOnAppend:!0};let pie,T8e;class xqn extends wj{constructor(t,n){super("iframes",t.logger),this.hls=void 0,this.stats=void 0,this.variableList=null,this.initPTS=[],this.iframeInstances=void 0,this.instanceCounter=0,pie||(pie=yqn(n)),T8e||(T8e=vqn(pie)),this.hls=t,this.iframeInstances=[],this.registerListeners()}registerListeners(){const t=this.hls;t&&(t.on(Mt.MANIFEST_LOADING,this.clearAsset,this),t.on(Mt.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(Mt.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(Mt.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(Mt.FRAG_BUFFERED,this.onFragBuffered,this),t.on(Mt.DESTROYING,this.onDestroying,this))}unregisterListeners(){const t=this.hls;t&&(t.off(Mt.MANIFEST_LOADING,this.clearAsset,this),t.off(Mt.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(Mt.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(Mt.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(Mt.FRAG_BUFFERED,this.onFragBuffered,this),t.off(Mt.DESTROYING,this.onDestroying,this))}clearAsset(){this.stats=void 0,this.variableList=null,this.initPTS=[],this.iframeInstances.forEach(t=>t.destroy()),this.iframeInstances.length=0}onDestroying(){this.unregisterListeners(),this.clearAsset(),this.hls=void 0}onManifestLoaded(t,n){this.stats=n.stats,this.variableList=n.variableList}onLevelsUpdated(t,{levels:n}){var r;const a=(r=this.hls)==null?void 0:r.pathwayPriority;n.length&&a&&this.iframeInstances.forEach(i=>{i.pathwayPriority=a})}onInitPtsFound(t,{id:n,timestampOffsets:r}){n===Ji.MAIN&&(this.initPTS=r)}onFragBuffered(t,n){var r;const a=this.hls;a&&a.hasEnoughToStart&&(((r=a.mainForwardBufferInfo)==null?void 0:r.len)||0)>pqn&&this.iframeInstances.forEach(i=>{if(!i.loadingEnabled){var l;i.startLoad(((l=this.hls)==null||(l=l.media)==null?void 0:l.currentTime)||0)}})}createIFramePlayer(t){var n;return this.createInstance(pie,(n=this.hls)==null?void 0:n.iframeVariants,t)}createImageIFramePlayer(t){var n;const r=(n=this.hls)==null?void 0:n.iframeVariants.filter(a=>a.imageCodec);return this.createInstance(T8e,r,t,"image-")}createInstance(t,n,r,a){const{hls:i}=this;if(!i)return null;const{url:l,userConfig:o,latestLevelDetails:c,loadLevelObj:d,loadLevel:u,bandwidthEstimate:h,sessionId:m}=i,{stats:p,variableList:g}=this;if(!(n!=null&&n.length)||!p||!l)return null;const x=`${a||""}iframe-player-${this.instanceCounter++}`,y=i.levels,v=d||y[u],_=DHt(v,o.videoPreference),j=(v==null?void 0:v.pathwayId)||".",C=wo(wo({},o),{},{loggerId:x,primarySessionId:m,videoPreference:_,abrEwmaDefaultEstimate:h,streamController:void 0,audioStreamController:void 0,audioTrackController:void 0,subtitleStreamController:void 0,subtitleTrackController:void 0,timelineController:void 0,id3TrackController:void 0,fpsController:void 0,gapController:void 0,iframeController:void 0,cmcd:void 0,interstitialsController:void 0,backBufferLength:1/0,maxMaxBufferLength:1,capLevelToPlayerSize:!0,enableWorker:!1,autoStartLoad:!1,startFragPrefetch:!1,testBandwidth:!1,progressive:!1},r),A=new t(C,l,this.initPTS,c);return this.iframeInstances=this.iframeInstances.filter(M=>!M.url),this.iframeInstances.push(A),A.trigger(Mt.MANIFEST_LOADED,{levels:n,contentSteering:{uri:"",pathwayId:j},sessionKeys:null,audioTracks:[],iframeVariants:[],sessionData:null,startTimeOffset:null,stats:p,networkDetails:null,url:l,variableList:g}),A}}function yqn(s){return class extends s{constructor(n,r,a,i){n.streamController||(n.streamController=JGt),super(n),this._url=r,this.streamController.setInitPts(a),this.streamController.initDetails=i}loadSource(){}loadMediaAt(n,r=cwt){if(n<0)return;const a=wo(wo({},cwt),r);this.loadingEnabled||this.startLoad(n),this.streamController.loadMediaAt(n,a)}}}function vqn(s){return class extends s{constructor(n,r,a,i){n.cmcdController=void 0,n.emeController=void 0,n.streamController||(n.streamController=fqn),n.capLevelController=void 0,n.bufferController=void 0,super(n,r,a,i)}attachImage(n){this.streamController.image=n}detachImage(){this.streamController.image=void 0}loadSource(){}attachMedia(){throw new Error(gqn)}detachMedia(){}recoverMediaError(){}transferMedia(){return null}loadMediaAt(n){if(n<0)return null;this.loadingEnabled||this.startLoad(n),this.streamController.loadMediaAt(n)}}}const yM=.025;let pCe=function(s){return s[s.Point=0]="Point",s[s.Range=1]="Range",s}({});function bqn(s,t,n){return`${s.identifier}-${n+1}-${hZ(t)}`}class _qn{constructor(t,n){this.base=void 0,this._duration=null,this._timelineStart=null,this.appendInPlaceDisabled=void 0,this.appendInPlaceStarted=void 0,this.dateRange=void 0,this.hasPlayed=!1,this.cumulativeDuration=0,this.resumeOffset=NaN,this.playoutLimit=NaN,this.restrictions={skip:!1,jump:!1},this.snapOptions={out:!1,in:!1},this.assetList=[],this.assetListLoader=void 0,this.assetListResponse=null,this.resumeAnchor=void 0,this.error=void 0,this.resetOnResume=void 0,this.base=n,this.dateRange=t,this.setDateRange(t)}setDateRange(t){this.dateRange=t,this.resumeOffset=t.attr.optionalFloat("X-RESUME-OFFSET",this.resumeOffset),this.playoutLimit=t.attr.optionalFloat("X-PLAYOUT-LIMIT",this.playoutLimit),this.restrictions=t.attr.enumeratedStringList("X-RESTRICT",this.restrictions),this.snapOptions=t.attr.enumeratedStringList("X-SNAP",this.snapOptions)}reset(){var t;this.appendInPlaceStarted=!1,(t=this.assetListLoader)==null||t.destroy(),this.assetListLoader=void 0,this.supplementsPrimary||(this.assetListResponse=null,this.assetList=[],this._duration=null)}isAssetPastPlayoutLimit(t){var n;if(t>0&&t>=this.assetList.length)return!0;const r=this.playoutLimit;return t<=0||isNaN(r)?!1:r===0?!0:(((n=this.assetList[t])==null?void 0:n.startOffset)||0)>r}findAssetIndex(t){return this.assetList.indexOf(t)}get identifier(){return this.dateRange.id}get startDate(){return this.dateRange.startDate}get startTime(){const t=this.dateRange.startTime;if(this.snapOptions.out){const n=this.dateRange.tagAnchor;if(n)return dwt(n,t)?bke(t,n):t}return t}get startOffset(){return this.cue.pre?0:this.startTime}get startIsAligned(){if(this.startTime===0||this.snapOptions.out)return!0;const t=this.dateRange.tagAnchor;if(t){const n=this.dateRange.startTime,r=bke(n,t);return n-r<.1}return!1}get resumptionOffset(){const t=this.resumeOffset,n=mi(t)?t:this.duration;return this.cumulativeDuration+n}get resumeTime(){const t=this.startOffset+this.resumptionOffset;if(this.snapOptions.in){const n=this.resumeAnchor;if(n)return dwt(n,t)?bke(t,n):t}return t}get appendInPlace(){return this.appendInPlaceStarted?!0:this.appendInPlaceDisabled?!1:!!(!this.cue.once&&!this.cue.pre&&this.startIsAligned&&(isNaN(this.playoutLimit)&&isNaN(this.resumeOffset)||this.resumeOffset&&this.duration&&Math.abs(this.resumeOffset-this.duration)0||this.assetListResponse!==null}toString(){return wqn(this)}}function bke(s,t){return s-t.starts.start-yM&&t":s.cue.post?"":""}${s.timelineStart.toFixed(2)}-${s.resumeTime.toFixed(2)}]`}function Z9(s){const t=s.timelineStart,n=s.duration||0;return`["${s.identifier}" ${t.toFixed(2)}-${(t+n).toFixed(2)}]`}class jqn{constructor(t,n,r,a){this.hls=void 0,this.interstitial=void 0,this.assetItem=void 0,this.tracks=null,this.hasDetails=!1,this.mediaAttached=null,this._currentTime=void 0,this._bufferedEosTime=void 0,this.checkPlayout=()=>{this.reachedPlayout(this.currentTime)&&this.hls&&this.hls.trigger(Mt.PLAYOUT_LIMIT_REACHED,{})};const i=this.hls=new t(n);this.interstitial=r,this.assetItem=a;const l=()=>{this.hasDetails=!0};i.once(Mt.LEVEL_LOADED,l),i.once(Mt.AUDIO_TRACK_LOADED,l),i.once(Mt.SUBTITLE_TRACK_LOADED,l),i.on(Mt.MEDIA_ATTACHING,(o,{media:c})=>{this.removeMediaListeners(),this.mediaAttached=c,this.interstitial.playoutLimit&&(c.addEventListener("timeupdate",this.checkPlayout),this.appendInPlace&&i.on(Mt.BUFFER_APPENDED,()=>{const u=this.bufferedEnd;this.reachedPlayout(u)&&(this._bufferedEosTime=u,i.trigger(Mt.BUFFERED_TO_END,void 0))}))})}get appendInPlace(){return this.interstitial.appendInPlace}loadSource(){const t=this.hls;if(t)if(t.url)t.levels.length&&!t.started&&t.startLoad(-1,!0);else{let n=this.assetItem.uri;try{n=eWt(n,t.config.primarySessionId||"").href}catch{}t.loadSource(n)}}bufferedInPlaceToEnd(t,n){var r;if(!this.appendInPlace)return!1;if((r=this.hls)!=null&&r.bufferedToEnd)return!0;if(!t)return!1;const a=Math.min(this._bufferedEosTime||1/0,this.duration),i=this.timelineOffset+(n||0),l=pl.bufferInfo(t,i,.02);return this.getAssetTime(l.end)>=a-.02}reachedPlayout(t){const r=this.interstitial.playoutLimit;return this.startOffset+t>=r}get destroyed(){var t;return!((t=this.hls)!=null&&t.userConfig)}get assetId(){return this.assetItem.identifier}get interstitialId(){return this.assetItem.parentIdentifier}get media(){var t;return((t=this.hls)==null?void 0:t.media)||null}get bufferedEnd(){const t=this.media||this.mediaAttached;if(!t)return this._bufferedEosTime?this._bufferedEosTime:this.currentTime;const n=pl.bufferInfo(t,t.currentTime,.001);return this.getAssetTime(n.end)}get currentTime(){const t=this.media||this.mediaAttached;return t?this.getAssetTime(t.currentTime):this._currentTime||0}get duration(){const t=this.assetItem.duration;if(!t)return 0;const n=this.interstitial.playoutLimit;if(n){const r=n-this.startOffset;if(r>0&&r1/9e4&&this.hls){if(this.hasDetails)throw new Error("Cannot set timelineOffset after playlists are loaded");this.hls.config.timelineOffset=t}}}getAssetTime(t){const n=this.timelineOffset,r=this.duration;return Math.min(Math.max(0,t-n),r)}removeMediaListeners(){const t=this.mediaAttached;t&&(this._currentTime=t.currentTime,this.bufferSnapShot(),t.removeEventListener("timeupdate",this.checkPlayout))}bufferSnapShot(){if(this.mediaAttached){var t;(t=this.hls)!=null&&t.bufferedToEnd&&(this._bufferedEosTime=this.bufferedEnd)}}destroy(){this.removeMediaListeners(),this.hls&&this.hls.destroy(),this.hls=null,this.tracks=this.mediaAttached=this.checkPlayout=null}attachMedia(t){var n;this.loadSource(),(n=this.hls)==null||n.attachMedia(t)}detachMedia(){var t;this.removeMediaListeners(),this.mediaAttached=null,(t=this.hls)==null||t.detachMedia()}resumeBuffering(){var t;(t=this.hls)==null||t.resumeBuffering()}pauseBuffering(){var t;(t=this.hls)==null||t.pauseBuffering()}transferMedia(){var t;return this.bufferSnapShot(),((t=this.hls)==null?void 0:t.transferMedia())||null}resetDetails(){const t=this.hls;if(t&&this.hasDetails){t.stopLoad();const n=r=>delete r.details;t.levels.forEach(n),t.allAudioTracks.forEach(n),t.allSubtitleTracks.forEach(n),this.hasDetails=!1}}on(t,n,r){var a;(a=this.hls)==null||a.on(t,n)}once(t,n,r){var a;(a=this.hls)==null||a.once(t,n)}off(t,n,r){var a;(a=this.hls)==null||a.off(t,n)}toString(){var t;return`HlsAssetPlayer: ${Z9(this.assetItem)} ${(t=this.hls)==null?void 0:t.sessionId} ${this.appendInPlace?"append-in-place":""}`}}const P8e=.033;class Nqn extends wj{constructor(t,n){super("interstitials-sched",n),this.onScheduleUpdate=void 0,this.eventMap={},this.events=null,this.items=null,this.durations={primary:0,playout:0,integrated:0},this.onScheduleUpdate=t}destroy(){this.reset(),this.onScheduleUpdate=null}reset(){this.eventMap={},this.setDurations(0,0,0),this.events&&this.events.forEach(t=>t.reset()),this.events=this.items=null}resetErrorsInRange(t,n){return this.events?this.events.reduce((r,a)=>t<=a.startOffset&&n>a.startOffset?(delete a.error,r+1):r,0):0}get duration(){const t=this.items;return t?t[t.length-1].end:0}get length(){return this.items?this.items.length:0}getEvent(t){return t&&this.eventMap[t]||null}hasEvent(t){return t in this.eventMap}findItemIndex(t,n){if(t.event)return this.findEventIndex(t.event.identifier);let r=-1;t.nextEvent?r=this.findEventIndex(t.nextEvent.identifier)-1:t.previousEvent&&(r=this.findEventIndex(t.previousEvent.identifier)+1);const a=this.items;if(a)for(a[r]||(n===void 0&&(n=t.start),r=this.findItemIndexAtTime(n));r>=0&&(i=a[r])!=null&&i.event;){var i;r--}return r}findItemIndexAtTime(t,n){const r=this.items;if(r)for(let a=0;al&&t1)for(let i=0;io&&(nc.indexOf(u.identifier)===-1):[];o.length&&o.sort((u,h)=>{const m=u.cue.pre,p=u.cue.post,g=h.cue.pre,x=h.cue.post;if(m&&!g)return-1;if(g&&!m||p&&!x)return 1;if(x&&!p)return-1;if(!m&&!g&&!p&&!x){const y=u.startTime,v=h.startTime;if(y!==v)return y-v}return u.dateRange.tagOrder-h.dateRange.tagOrder}),this.events=o,d.forEach(u=>{this.removeEvent(u)}),this.updateSchedule(t,d,r)}updateSchedule(t,n=[],r=0,a=!1){const i=this.events||[];if(i.length||n.length||this.length<2){const l=this.items,o=this.parseSchedule(i,t,r);(a||n.length||(l==null?void 0:l.length)!==o.length||o.some((d,u)=>Math.abs(d.playout.start-l[u].playout.start)>.005||Math.abs(d.playout.end-l[u].playout.end)>.005))&&(this.items=o,this.onScheduleUpdate(n,l))}}parseDateRanges(t,n,r){const a=[],i=Object.keys(t);for(let l=0;l!d.error&&!(d.cue.once&&d.hasPlayed)),t.length){this.resolveOffsets(t,n);let d=0,u=0;if(t.forEach((h,m)=>{const p=h.cue.pre,g=h.cue.post,x=t[m-1]||null,y=h.appendInPlace,v=g?l:h.startOffset,_=h.duration,j=h.timelineOccupancy===pCe.Range?_:0,C=p&&i.live?r+(h.resumeOffset||0):0,A=C||h.resumptionOffset,M=(x==null?void 0:x.startTime)===v,I=v+h.cumulativeDuration;let P=y?I+_:v+A;if(p||!g&&v<=0){const O=u;u+=j,h.timelineStart=I;const B=o;o+=_,a.push({event:h,start:I,end:P,playout:{start:B,end:o},integrated:{start:O,end:u}})}else if(v<=l){if(!M){const U=v-d;if(U>P8e){const G=d,H=u;u+=U;const Y=o;o+=U;const se={previousEvent:t[m-1]||null,nextEvent:h,start:G,end:G+U,playout:{start:Y,end:o},integrated:{start:H,end:u}};a.push(se)}else U>0&&x&&(x.cumulativeDuration+=U,a[a.length-1].end=v)}g&&(P=I),h.timelineStart=I;const O=u;u+=j;const B=o;o+=_,a.push({event:h,start:I,end:P,playout:{start:B,end:o},integrated:{start:O,end:u}})}else return;const R=C||h.resumeTime;g||R>l?d=l:!p&&P&&h.appendInPlaceStarted&&R-P>P8e?d=P:d=R}),d{const d=o.cue.pre,u=o.cue.post,h=d?0:u?a:o.startTime;this.updateAssetDurations(o),l===h?o.cumulativeDuration=i:(i=0,l=h),!u&&o.snapOptions.in&&(o.resumeAnchor=bq(null,r.fragments,o.startOffset+o.resumptionOffset,0,0)||void 0),o.appendInPlace&&!o.appendInPlaceStarted&&(this.primaryCanResumeInPlaceAt(o,n)||(o.appendInPlace=!1)),!o.appendInPlace&&c+1yM?(this.log(`"${t.identifier}" resumption ${r} not aligned with estimated timeline end ${a}`),!1):!Object.keys(n).some(l=>{const o=n[l].details,c=o.edge;if(r>=c)return this.log(`"${t.identifier}" resumption ${r} past ${l} playlist end ${c}`),!1;const d=bq(null,o.fragments,r);if(!d)return this.log(`"${t.identifier}" resumption ${r} does not align with any fragments in ${l} playlist (${o.fragStart}-${o.fragmentEnd})`),!0;const u=l==="audio"?.175:0;return Math.abs(d.start-r){const y=m.data,v=y==null?void 0:y.ASSETS;if(!Array.isArray(v)){const _=this.assignAssetListError(t,er.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),g.url,p,x);this.hls.trigger(Mt.ERROR,_);return}t.assetListResponse=y,this.hls.trigger(Mt.ASSET_LIST_LOADED,{event:t,assetListResponse:y,networkDetails:x})},onError:(m,p,g,x)=>{const y=this.assignAssetListError(t,er.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${m.code} ${m.text} (${p.url})`),p.url,x,g);this.hls.trigger(Mt.ERROR,y)},onTimeout:(m,p,g)=>{const x=this.assignAssetListError(t,er.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${p.url})`),p.url,m,g);this.hls.trigger(Mt.ERROR,x)}};return o.load(c,u,h),this.hls.trigger(Mt.ASSET_LIST_LOADING,{event:t}),o}assignAssetListError(t,n,r,a,i,l){return t.error=r,{type:xo.NETWORK_ERROR,details:n,fatal:!1,interstitial:t,url:a,error:r,networkDetails:l,stats:i}}}function uwt(s){var t;s==null||(t=s.play())==null||t.catch(()=>{})}function pP(s,t){return`[${s}] Advancing timeline position to ${t}`}class Sqn extends wj{constructor(t,n){super("interstitials",t.logger),this.HlsPlayerClass=void 0,this.hls=void 0,this.assetListLoader=void 0,this.mediaSelection=null,this.altSelection=null,this.media=null,this.detachedData=null,this.requiredTracks=null,this.manager=null,this.playerQueue=[],this.bufferedPos=-1,this.timelinePos=-1,this.schedule=void 0,this.playingItem=null,this.bufferingItem=null,this.waitingItem=null,this.endedItem=null,this.playingAsset=null,this.endedAsset=null,this.bufferingAsset=null,this.bufferPastEdge=!1,this.shouldPlay=!1,this.onPlay=()=>{this.shouldPlay=!0},this.onPause=()=>{this.shouldPlay=!1},this.onSeeking=()=>{const r=this.currentTime;if(r===void 0||this.playbackDisabled||!this.schedule)return;const a=r-this.timelinePos;if(Math.abs(a)<1/7056e5)return;const l=a<=-.01;this.timelinePos===-1&&!this.effectivePlayingItem&&this.checkStart(),this.timelinePos=r,this.bufferedPos=r;const o=this.playingItem;if(!o){this.checkBuffer();return}if(l&&this.schedule.resetErrorsInRange(r,r-a)&&this.updateSchedule(!0),this.checkBuffer(),l&&r=o.end){var c;const p=this.findItemIndex(o);let g=this.schedule.findItemIndexAtTime(r);if(g===-1&&(g=p+(l?-1:1),this.log(`seeked ${l?"back ":""}to position not covered by schedule ${r} (resolving from ${p} to ${g})`)),!this.isInterstitial(o)&&(c=this.media)!=null&&c.paused&&(this.shouldPlay=!1),!l&&g>p){const x=this.schedule.findJumpRestrictedIndex(p+1,g);if(x>p){this.setSchedulePosition(x);return}}this.setSchedulePosition(g);return}const d=this.playingAsset;if(!d){if(this.playingLastItem&&this.isInterstitial(o)){const p=o.event.assetList[0];p&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(r,p))}return}const u=d.timelineStart,h=d.duration||0;if(l&&r=u+h){var m;(m=o.event)!=null&&m.appendInPlace&&(this.clearAssetPlayers(o.event,o),this.flushFrontBuffer(r)),this.setScheduleToAssetAtTime(r,d)}},this.onTimeupdate=()=>{const r=this.currentTime;if(r===void 0||this.playbackDisabled)return;if(this.timelinePos===-1&&!this.effectivePlayingItem&&this.checkStart(),r>this.timelinePos)this.timelinePos=r,r>this.bufferedPos&&this.checkBuffer();else return;const a=this.playingItem;if(!a||this.playingLastItem)return;if(r>=a.end){this.timelinePos=a.end;const o=this.findItemIndex(a);this.setSchedulePosition(o+1)}const i=this.playingAsset;if(!i)return;const l=i.timelineStart+(i.duration||0);r>=l&&this.setScheduleToAssetAtTime(r,i)},this.onScheduleUpdate=(r,a)=>{const i=this.schedule;if(!i)return;const l=this.playingItem,o=i.events||[],c=i.items||[],d=i.durations,u=r.map(x=>x.identifier),h=!!(o.length||u.length);(h||a)&&this.log(`INTERSTITIALS_UPDATED (${o.length}): ${o} Schedule: ${c.map(x=>gw(x))} pos: ${this.timelinePos}`),u.length&&this.log(`Removed events ${u}`);let m=null,p=null;l&&(m=this.updateItem(l,this.timelinePos),this.itemsMatch(l,m)?this.playingItem=m:this.waitingItem=null),this.waitingItem=this.updateItem(this.waitingItem);const g=this.bufferingItem;if(g&&(p=this.updateItem(g,this.bufferedPos),this.itemsMatch(g,p)?this.bufferingItem=p:g.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(g.event,null))),r.forEach(x=>{x.assetList.forEach(y=>{this.clearAssetPlayer(y.identifier,null)})}),this.playerQueue.forEach(x=>{if(x.interstitial.appendInPlace){const y=x.assetItem.timelineStart,v=x.timelineOffset-y;if(v)try{x.timelineOffset=y}catch(_){Math.abs(v)>yM&&this.warn(`${_} ("${x.assetId}" ${x.timelineOffset}->${y})`)}}}),h||a){if(this.hls.trigger(Mt.INTERSTITIALS_UPDATED,{events:o.slice(0),schedule:c.slice(0),durations:d,removedIds:u}),this.isInterstitial(l)&&u.indexOf(l.event.identifier)>-1){this.warn(`Interstitial "${l.event.identifier}" removed while playing`),this.primaryFallback(l.event);return}l&&this.trimInPlace(m,l),g&&p!==m&&this.trimInPlace(p,g),this.checkBuffer()}},this.hls=t,this.HlsPlayerClass=n,this.assetListLoader=new kqn(t),this.schedule=new Nqn(this.onScheduleUpdate,t.logger),this.registerListeners()}registerListeners(){const t=this.hls;t&&(t.on(Mt.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(Mt.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(Mt.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(Mt.MANIFEST_LOADING,this.onManifestLoading,this),t.on(Mt.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(Mt.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(Mt.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),t.on(Mt.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.on(Mt.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),t.on(Mt.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),t.on(Mt.ASSET_LIST_LOADED,this.onAssetListLoaded,this),t.on(Mt.BUFFER_APPENDED,this.onBufferAppended,this),t.on(Mt.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(Mt.BUFFERED_TO_END,this.onBufferedToEnd,this),t.on(Mt.MEDIA_ENDED,this.onMediaEnded,this),t.on(Mt.ERROR,this.onError,this),t.on(Mt.DESTROYING,this.onDestroying,this))}unregisterListeners(){const t=this.hls;t&&(t.off(Mt.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(Mt.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(Mt.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(Mt.MANIFEST_LOADING,this.onManifestLoading,this),t.off(Mt.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(Mt.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(Mt.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),t.off(Mt.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.off(Mt.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),t.off(Mt.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),t.off(Mt.ASSET_LIST_LOADED,this.onAssetListLoaded,this),t.off(Mt.BUFFER_CODECS,this.onBufferCodecs,this),t.off(Mt.BUFFER_APPENDED,this.onBufferAppended,this),t.off(Mt.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(Mt.BUFFERED_TO_END,this.onBufferedToEnd,this),t.off(Mt.MEDIA_ENDED,this.onMediaEnded,this),t.off(Mt.ERROR,this.onError,this),t.off(Mt.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=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){Bu(t,"play",this.onPlay),Bu(t,"pause",this.onPause),Bu(t,"seeking",this.onSeeking),Bu(t,"timeupdate",this.onTimeupdate)}onMediaAttaching(t,n){const r=this.media=n.media;th(r,"seeking",this.onSeeking),th(r,"timeupdate",this.onTimeupdate),th(r,"play",this.onPlay),th(r,"pause",this.onPause)}onMediaAttached(t,n){const r=this.effectivePlayingItem,a=this.detachedData;if(this.detachedData=null,r===null)this.checkStart();else if(!a){this.clearScheduleState();const i=this.findItemIndex(r);this.setSchedulePosition(i)}}clearScheduleState(){this.log("clear schedule state"),this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null}onMediaDetaching(t,n){const r=!!n.transferMedia,a=this.media;if(this.media=null,!r&&(a&&this.removeMediaListeners(a),this.detachedData)){const i=this.getBufferingPlayer();i&&(this.log(`Removing schedule state for detachedData and ${i}`),this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,i.detachMedia()),this.shouldPlay=!1}}get interstitialsManager(){if(!this.hls)return null;if(this.manager)return this.manager;const t=this,n=()=>t.bufferingItem||t.waitingItem,r=h=>h&&t.getAssetPlayer(h.identifier),a=(h,m,p,g,x)=>{if(h){let y=h[m].start;const v=h.event;if(v){if(m==="playout"||v.timelineOccupancy!==pCe.Point){const _=r(p);(_==null?void 0:_.interstitial)===v&&(y+=_.assetItem.startOffset+_[x])}}else{const _=g==="bufferedPos"?l():t[g];y+=_-h.start}return y}return 0},i=(h,m)=>{var p;if(h!==0&&m!=="primary"&&(p=t.schedule)!=null&&p.length){var g;const x=t.schedule.findItemIndexAtTime(h),y=(g=t.schedule.items)==null?void 0:g[x];if(y){const v=y[m].start-y.start;return h+v}}return h},l=()=>{const h=t.bufferedPos;return h===Number.MAX_VALUE?o("primary"):Math.max(h,0)},o=h=>{var m,p;return(m=t.primaryDetails)!=null&&m.live?t.primaryDetails.edge:((p=t.schedule)==null?void 0:p.durations[h])||0},c=(h,m)=>{var p,g;const x=t.effectivePlayingItem;if(x!=null&&(p=x.event)!=null&&p.restrictions.skip||!t.schedule)return;t.log(`seek to ${h} "${m}"`);const y=t.effectivePlayingItem,v=t.schedule.findItemIndexAtTime(h,m),_=(g=t.schedule.items)==null?void 0:g[v],j=t.getBufferingPlayer(),C=j==null?void 0:j.interstitial,A=C==null?void 0:C.appendInPlace,M=y&&t.itemsMatch(y,_);if(y&&(A||M)){const I=r(t.playingAsset),P=(I==null?void 0:I.media)||t.primaryMedia;if(P){const R=m==="primary"?P.currentTime:a(y,m,t.playingAsset,"timelinePos","currentTime"),O=h-R,B=(A?R:P.currentTime)+O;if(B>=0&&(!I||A||B<=I.duration)){P.currentTime=B;return}}}if(_){let I=h;if(m!=="primary"){const R=_[m].start,O=h-R;I=_.start+O}const P=!t.isInterstitial(_);if((!t.isInterstitial(y)||y.event.appendInPlace)&&(P||_.event.appendInPlace)){const R=t.media||(A?j==null?void 0:j.media:null);R&&(R.currentTime=I)}else if(y){const R=t.findItemIndex(y);if(v>R){const B=t.schedule.findJumpRestrictedIndex(R+1,v);if(B>R){t.setSchedulePosition(B);return}}let O=0;if(P)t.timelinePos=I,t.checkBuffer();else{const B=_.event.assetList,U=h-(_[m]||_).start;for(let G=B.length;G--;){const H=B[G];if(H.duration&&U>=H.startOffset&&U{const h=t.effectivePlayingItem;if(t.isInterstitial(h))return h;const m=n();return t.isInterstitial(m)?m:null},u={get bufferedEnd(){const h=n(),m=t.bufferingItem;if(m&&m===h){var p;return a(m,"playout",t.bufferingAsset,"bufferedPos","bufferedEnd")-m.playout.start||((p=t.bufferingAsset)==null?void 0:p.startOffset)||0}return 0},get currentTime(){const h=d(),m=t.effectivePlayingItem;return m&&m===h?a(m,"playout",t.effectivePlayingAsset,"timelinePos","currentTime")-m.playout.start:0},set currentTime(h){const m=d(),p=t.effectivePlayingItem;p&&p===m&&c(h+p.playout.start,"playout")},get duration(){const h=d();return h?h.playout.end-h.playout.start:0},get assetPlayers(){var h;const m=(h=d())==null?void 0:h.event.assetList;return m?m.map(p=>t.getAssetPlayer(p.identifier)):[]},get playingIndex(){var h;const m=(h=d())==null?void 0:h.event;return m&&t.effectivePlayingAsset?m.findAssetIndex(t.effectivePlayingAsset):-1},get scheduleItem(){return d()}};return this.manager={get events(){var h;return((h=t.schedule)==null||(h=h.events)==null?void 0:h.slice(0))||[]},get schedule(){var h;return((h=t.schedule)==null||(h=h.items)==null?void 0:h.slice(0))||[]},get interstitialPlayer(){return d()?u:null},get playerQueue(){return t.playerQueue.slice(0)},get bufferingAsset(){return t.bufferingAsset},get bufferingItem(){return n()},get bufferingIndex(){const h=n();return t.findItemIndex(h)},get playingAsset(){return t.effectivePlayingAsset},get playingItem(){return t.effectivePlayingItem},get playingIndex(){const h=t.effectivePlayingItem;return t.findItemIndex(h)},primary:{get bufferedEnd(){return l()},get currentTime(){const h=t.timelinePos;return h>0?h:0},set currentTime(h){c(h,"primary")},get duration(){return o("primary")},get seekableStart(){return t.seekableStart}},integrated:{get bufferedEnd(){return a(n(),"integrated",t.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return a(t.effectivePlayingItem,"integrated",t.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(h){c(h,"integrated")},get duration(){return o("integrated")},get seekableStart(){return i(t.seekableStart,"integrated")}},skip:()=>{const h=t.effectivePlayingItem,m=h==null?void 0:h.event;if(m&&!m.restrictions.skip){const p=t.findItemIndex(h);if(m.appendInPlace){const g=h.playout.start+h.event.duration;c(g+.001,"playout")}else t.advanceAfterAssetEnded(m,p,1/0)}}}}get effectivePlayingItem(){return this.waitingItem||this.playingItem||this.endedItem}get effectivePlayingAsset(){return this.playingAsset||this.endedAsset}get playingLastItem(){var t;const n=this.playingItem,r=(t=this.schedule)==null?void 0:t.items;return!this.playbackStarted||!n||!r?!1:this.findItemIndex(n)===r.length-1}get playbackStarted(){return this.effectivePlayingItem!==null}get currentTime(){var t,n;if(this.mediaSelection===null)return;const r=this.waitingItem||this.playingItem;if(this.isInterstitial(r)&&!r.event.appendInPlace)return;let a=this.media;!a&&(t=this.bufferingItem)!=null&&(t=t.event)!=null&&t.appendInPlace&&(a=this.primaryMedia);const i=(n=a)==null?void 0:n.currentTime;if(!(i===void 0||!mi(i)))return i}get primaryMedia(){var t;return this.media||((t=this.detachedData)==null?void 0:t.media)||null}isInterstitial(t){return!!(t!=null&&t.event)}retreiveMediaSource(t,n){const r=this.getAssetPlayer(t);r&&this.transferMediaFromPlayer(r,n)}transferMediaFromPlayer(t,n){const r=t.interstitial.appendInPlace,a=t.media;if(r&&a===this.primaryMedia){if(this.bufferingAsset=null,(!n||this.isInterstitial(n)&&!n.event.appendInPlace)&&n&&a){this.detachedData={media:a};return}const i=t.transferMedia();this.log(`transfer MediaSource from ${t} ${bm(i)}`),this.detachedData=i}else n&&a&&(this.shouldPlay||(this.shouldPlay=!a.paused))}transferMediaTo(t,n){var r,a;if(t.media===n)return;let i=null;const l=this.hls,o=t!==l,c=o&&t.interstitial.appendInPlace,d=(r=this.detachedData)==null?void 0:r.mediaSource;let u;if(l.media)c&&(i=l.transferMedia(),this.detachedData=i),u="Primary";else{const g=this.getBufferingPlayer();g?(i=g.transferMedia(),this.detachedData=i,u=`${g}`):d?u="detached MediaSource":u="detached media"}if(!i){if(d)i=this.detachedData,this.log(`using detachedData: MediaSource ${bm(i)}`);else if(!this.detachedData||l.media===n){const g=this.playerQueue;g.length>1&&g.forEach(x=>{if(o&&x.interstitial.appendInPlace!==c){const y=x.interstitial;this.clearInterstitial(x.interstitial,null),y.appendInPlace=!1,y.appendInPlace&&this.warn(`Could not change append strategy for queued assets ${y}`)}}),this.hls.detachMedia(),this.detachedData={media:n}}}const h=i&&"mediaSource"in i&&((a=i.mediaSource)==null?void 0:a.readyState)!=="closed";if(this.log(`${h?"transfering MediaSource":"attaching media"} to ${o?t:"Primary"} from ${u} (media.currentTime: ${n.currentTime})`),!h&&!o){t.attachMedia(n);return}const m=h&&i?wo({},i):{media:n},p=this.schedule;if(p&&o){const g=t.assetId===p.assetIdAtEnd;m.overrides={duration:p.duration,endOfStream:g||t.appendInPlace===!1}}if(!h&&c){const g=t,x=g.assetItem.timelineStart;if(x){const y=g.hls,v=Math.max(this.timelinePos-x,Number.EPSILON);y.startPosition!==v&&(this.log(`Set ${g} startPosition: ${v}`),y.config.startPosition=v,y.loadingEnabled&&y.startLoad(v))}}t.attachMedia(m)}onInterstitialCueEnter(){this.onTimeupdate()}checkStart(){const t=this.schedule,n=t==null?void 0:t.events,r=this.hls;if(!n||this.playbackDisabled||!this.media||!r)return;this.bufferedPos===-1&&(this.bufferedPos=0);const a=this.timelinePos,i=this.effectivePlayingItem;if(a===-1){if(!r.loadingEnabled){this.log("waiting for startLoad( )");return}const l=r.startPosition;if(this.timelinePos=l,n.length===0)this.setSchedulePosition(0);else if(n[0].cue.pre){this.log(pP("checkStart (preroll)",l));const o=t.findEventIndex(n[0].identifier);this.setSchedulePosition(o)}else if(l>=0||!this.primaryLive){this.log(pP("checkStart",l));const o=this.timelinePos=l>0?l:0,c=t.findItemIndexAtTime(o);this.setSchedulePosition(c)}else r.liveSyncPosition===0?this.setSchedulePosition(0):this.log("[checkStart] waiting for live start")}else if(i&&!this.playingItem){this.log(pP("checkStart (playing item)",i.start));const l=t.findItemIndex(i);this.setSchedulePosition(l)}}advanceAssetBuffering(t,n){const r=t.event,a=r.findAssetIndex(n),i=M8e(r,a);if(!r.isAssetPastPlayoutLimit(i))this.bufferedToEvent(t,i);else if(this.schedule){var l;const o=this.getNextItemIndex(t,!0),c=(l=this.schedule.items)==null?void 0:l[o];c&&this.bufferedToItem(c)}}livePrerollResumption(t,n){if(t.cue.pre&&this.primaryLive&&!mi(t.resumeOffset)&&this.hls){const r=this.getLiveStartPos();if(n){const a=this.getBufferingPlayer(),i=a!=null&&a.interstitial.cue.pre?a.remaining:0;return r+i}return r}}getNextItemIndex(t,n){if(this.schedule){const r=this.livePrerollResumption(t.event,n);if(r!==void 0)return this.log(`find next item index @${r}`),this.schedule.findItemIndexAtTime(r)}return this.findItemIndex(t)+1}advanceAfterAssetEnded(t,n,r){const a=M8e(t,r);if(t.isAssetPastPlayoutLimit(a)){if(this.schedule){const i=this.schedule.items;if(i){const l=i[n],o=l.event?this.getNextItemIndex(l):n+1,c=i.length;if(o>=c){this.setSchedulePosition(-1);return}const d=t.resumeTime;this.timelinePos=0?a[t]:null;this.log(`setSchedulePosition ${t}, ${n} (${i&&gw(i)}) pos: ${this.timelinePos}`);const l=this.waitingItem||this.playingItem,o=this.playingLastItem;if(this.isInterstitial(l)){const h=l.event,m=this.playingAsset,p=m==null?void 0:m.identifier,g=p?this.getAssetPlayer(p):null;if(g&&p&&(!this.eventItemsMatch(l,i)||n!==void 0&&p!==h.assetList[n].identifier)){var c;const x=h.findAssetIndex(m);if(this.log(`INTERSTITIAL_ASSET_ENDED ${x+1}/${h.assetList.length} ${Z9(m)}`),this.endedAsset=m,this.playingAsset=null,this.hls.trigger(Mt.INTERSTITIAL_ASSET_ENDED,{asset:m,assetListIndex:x,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),x);return}this.retreiveMediaSource(p,i),g.media&&!((c=this.detachedData)!=null&&c.mediaSource)&&g.detachMedia()}if(!this.eventItemsMatch(l,i)&&(this.endedItem=l,this.playingItem=this.waitingItem=null,this.log(`INTERSTITIAL_ENDED ${h} ${gw(l)}`),h.hasPlayed=!0,this.hls.trigger(Mt.INTERSTITIAL_ENDED,{event:h,schedule:a.slice(0),scheduleIndex:t}),h.cue.once&&this.hls)){var d;this.updateSchedule();const x=(d=this.schedule)==null?void 0:d.items;if(i&&x){const y=this.findItemIndex(i),v=this.livePrerollResumption(h);if(v!==void 0){let _=v;const j=this.getNextItemIndex(l);if(!this.isInterstitial(a[j])){var u;const C=(u=this.primaryDetails)==null?void 0:u.fragments;if(h.snapOptions.in&&C){const A=bq(null,C,v);A&&(_=Math.min(Math.max(a[j].start,bke(_,A)),a[j].end))}}if(this.log(pP("live join (preroll)",_)),this.timelinePos=_,j!==y&&(j||j===0)){this.advanceSchedule(j,x,void 0,l,o);return}}this.advanceSchedule(y,x,n,l,o)}return}}this.advanceSchedule(t,a,n,l,o)}advanceSchedule(t,n,r,a,i){const l=this.schedule;if(!l)return;const o=n[t]||null,c=this.primaryMedia,d=this.playerQueue;if(d.length&&d.forEach(u=>{const h=u.interstitial,m=l.findEventIndex(h.identifier);(mt+1)&&this.clearInterstitial(h,o)}),this.isInterstitial(o)){this.timelinePos=Math.min(Math.max(this.timelinePos,o.start),o.end);const u=o.event;if(r===void 0){r=u.cue.pre?0:l.findAssetIndex(u,this.timelinePos);const g=M8e(u,r-1);if(u.isAssetPastPlayoutLimit(g)||u.appendInPlace&&this.timelinePos===o.end){this.advanceAfterAssetEnded(u,t,r);return}r=g}const h=this.waitingItem;this.assetsBuffered(o,c)||this.setBufferingItem(o);let m=this.preloadAssets(u,r);if(this.eventItemsMatch(o,h||a)||(this.waitingItem=o,this.log(`INTERSTITIAL_STARTED ${gw(o)} ${u.appendInPlace?"append in place":""}`),u.hasPlayed=!1,this.hls.trigger(Mt.INTERSTITIAL_STARTED,{event:u,schedule:n.slice(0),scheduleIndex:t})),!u.assetListLoaded){this.log(`Waiting for ASSET-LIST to complete loading ${u}`);return}if(u.assetListLoader&&(u.assetListLoader.destroy(),u.assetListLoader=void 0),!c){this.log(`Waiting for attachMedia to start Interstitial ${u}`);return}this.waitingItem=this.endedItem=null,this.playingItem=o;const p=u.assetList[r];if(!p){this.advanceAfterAssetEnded(u,t,r||0);return}if(m||(m=this.getAssetPlayer(p.identifier)),m===null||m.destroyed){const g=u.assetList.length;this.warn(`asset ${r+1}/${g} player destroyed ${u}`),m=this.createAssetPlayer(u,p,r),m.loadSource()}if(!this.eventItemsMatch(o,this.bufferingItem)&&u.appendInPlace&&this.isAssetBuffered(p))return;this.startAssetPlayer(m,r,n,t,c),this.shouldPlay&&uwt(m.media)}else o?(this.resumePrimary(o,t,a),this.shouldPlay&&uwt(this.hls.media)):i&&this.isInterstitial(a)&&(this.endedItem=null,this.playingItem=a,a.event.appendInPlace||this.attachPrimary(l.durations.primary,null))}get playbackDisabled(){return this.hls.config.enableInterstitialPlayback===!1}get primaryDetails(){var t;return(t=this.mediaSelection)==null?void 0:t.main.details}get primaryLive(){var t;return!!((t=this.primaryDetails)!=null&&t.live)}resumePrimary(t,n,r){var a,i;this.playingItem=t,this.playingAsset=this.endedAsset=null,this.waitingItem=null,this.bufferedToItem(t),this.endedItem=null,this.log(`resuming ${gw(t)}`);let l=this.timelinePos;if((a=this.detachedData)!=null&&a.mediaSource?this.primaryLive&&this.startLoadingPrimaryAt(l):((l=t.end||ld&&!r){const u=this.hls.liveSyncPosition;return this.log(`primary resumption out of bounds (${a} [${c}-${d}]) snapping to liveSync ${u}`),u||c}}}return this.log(`primary resumption itemStart: ${a}`),a}getLiveStartPos(){var t;const n=this.hls.startPosition,r=this.hls.liveSyncPosition||0,a=(((t=this.primaryDetails)==null?void 0:t.targetduration)||10)*3;return n===-1||r&&r-n=t.timelineStart+(t.duration||0)}attachPrimary(t,n,r){n?this.setBufferingItem(n):this.bufferingItem=this.playingItem,this.bufferingAsset=null;const a=this.primaryMedia;if(!a)return;const i=this.hls;i.media?this.checkBuffer():(this.transferMediaTo(i,a),r&&this.startLoadingPrimaryAt(t,r)),r||(this.log(pP("attachPrimary",t)),this.timelinePos=t,this.startLoadingPrimaryAt(t,r))}startLoadingPrimaryAt(t,n){const r=this.hls,{loadingEnabled:a,bufferingEnabled:i,startPosition:l}=r,o=r.hasEnoughToStart;if(this.log(`Start loading primary @${t} bufferedPos: ${this.bufferedPos} startPosition: ${l} skip seek: ${n} has enough ${o} loadingEnabled: ${a} bufferingEnabled: ${i}`),!n&&o||!a||Math.abs(l-t)>.1){const c=this.primaryDetails;if(c!=null&&c.live&&t+.5>=c.edge){const d=this.bufferingItem;this.log(`Resume primary loading when live passes ${t} buffering item: ${d?gw(d):null}`),r.pauseBuffering(),this.bufferPastEdge=!0;return}r.startLoad(t,n)}else i||r.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(Mt.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(Mt.BUFFER_CODECS,this.onBufferCodecs,this)}onLevelUpdated(t,n){if(n.level===-1||!this.schedule)return;const r=this.hls.levels[n.level];if(!r.details)return;const a=wo(wo({},this.mediaSelection||this.altSelection),{},{main:r});this.mediaSelection=a;const i=this.hls.startPosition;if(this.schedule.parseInterstitialDateRanges(a,this.hls.config.interstitialAppendInPlace,i===-1?0:i),!!this.schedule.items){if(!this.effectivePlayingItem)this.checkStart();else if(this.bufferPastEdge){const o=this.primaryDetails,c=this.bufferedPos;if(o!=null&&o.live&&c+.5a&&(a.setAudioOption(n)||a.setAudioOption(r)))}onSubtitleTrackSwitch(t,n){const r=n_t(n);this.playerQueue.forEach(({hls:a})=>a&&(a.setSubtitleOption(n)||n.id!==-1&&a.setSubtitleOption(r)))}onBufferCodecs(t,n){const r=n.tracks;r&&(this.requiredTracks=r)}onBufferAppended(t,n){this.checkBuffer()}onBufferFlushed(t,n){const r=this.playingItem;if(r&&!this.itemsMatch(r,this.bufferingItem)&&!this.isInterstitial(r)){const a=this.timelinePos;this.bufferedPos=a,this.checkBuffer()}}onBufferedToEnd(t){if(!this.schedule)return;const n=this.schedule.events;if(this.bufferedPos.25){t.event.assetList.forEach((i,l)=>{t.event.isAssetPastPlayoutLimit(l)&&this.clearAssetPlayer(i.identifier,null)});const r=t.end+.25,a=pl.bufferInfo(this.primaryMedia,r,0);(a.end>r||(a.nextStart||0)>r)&&(this.log(`trim buffered interstitial ${gw(t)} (was ${gw(n)})`),this.attachPrimary(r,null,!0),this.flushFrontBuffer(r))}}itemsMatch(t,n){return!!n&&(t===n||t.event&&n.event&&this.eventItemsMatch(t,n)||!t.event&&!n.event&&this.findItemIndex(t)===this.findItemIndex(n))}eventItemsMatch(t,n){var r;return!!n&&(t===n||t.event.identifier===((r=n.event)==null?void 0:r.identifier))}findEventIndex(t){return this.schedule?this.schedule.findEventIndex(t):-1}getEventItem(t){if(this.schedule){var n;const r=(n=this.schedule.items)==null?void 0:n[this.findEventIndex(t)];if(this.isInterstitial(r)&&r.event.identifier===t)return r}}findItemIndex(t,n){return t&&this.schedule?this.schedule.findItemIndex(t,n):-1}updateSchedule(t=!1){var n,r;const a=this.mediaSelection;if(!a)return;const i=((n=this.hls)==null?void 0:n.liveSyncPosition)||0;(r=this.schedule)==null||r.updateSchedule(a,[],i,t)}checkBuffer(t){var n;const r=(n=this.schedule)==null?void 0:n.items;if(!r)return;const a=pl.bufferInfo(this.primaryMedia,this.timelinePos,0);t&&(this.bufferedPos=this.timelinePos),t||(t=a.len<1),this.updateBufferedPos(a.end,r,t)}updateBufferedPos(t,n,r){const a=this.schedule,i=this.bufferingItem;if(this.bufferedPos>t||!a)return;if(n.length===1&&this.itemsMatch(n[0],i)){this.bufferedPos=t;return}const l=this.playingItem,o=this.findItemIndex(l);let c=a.findItemIndexAtTime(t);if(this.bufferedPos=i.end||(d=m.event)!=null&&d.appendInPlace&&t+.01>=m.start)&&(c=h),this.isInterstitial(i)){const p=i.event;if(h-o>1&&p.appendInPlace===!1||p.assetList.length===0&&p.assetListLoader)return}if(this.bufferedPos=t,c>u&&c>o)this.bufferedToItem(m);else{const p=this.primaryDetails;this.primaryLive&&p&&t>p.edge-p.targetduration&&m.start{const i=this.getAssetPlayer(a.identifier);return!(i!=null&&i.bufferedInPlaceToEnd(n))})}setBufferingItem(t){const n=this.bufferingItem,r=this.schedule;if(!this.itemsMatch(t,n)&&r){const{items:a,events:i}=r;if(!a||!i)return n;const l=this.isInterstitial(t),o=this.getBufferingPlayer();this.bufferingItem=t,this.bufferedPos=Math.max(t.start,Math.min(t.end,this.timelinePos));const c=o?o.remaining:n?n.end-this.timelinePos:0;if(this.log(`INTERSTITIALS_BUFFERED_TO_BOUNDARY ${gw(t)}`+(n?` (${c.toFixed(2)} remaining)`:"")),!this.playbackDisabled)if(l){const d=r.findAssetIndex(t.event,this.bufferedPos);t.event.assetList.forEach((u,h)=>{const m=this.getAssetPlayer(u.identifier);m&&(h===d&&m.loadSource(),m.resumeBuffering())})}else this.hls.resumeBuffering(),this.playerQueue.forEach(d=>d.pauseBuffering());this.hls.trigger(Mt.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:i.slice(0),schedule:a.slice(0),bufferingIndex:this.findItemIndex(t),playingIndex:this.findItemIndex(this.playingItem)})}else this.bufferingItem!==t&&(this.bufferingItem=t);return n}bufferedToItem(t,n=0){const r=this.setBufferingItem(t);if(!this.playbackDisabled){if(this.isInterstitial(t))this.bufferedToEvent(t,n);else if(r!==null){this.bufferingAsset=null;const a=this.getPrimaryResumption(t,this.findItemIndex(t),!0),i=this.bufferedPos=Math.max(a,Math.min(this.bufferedPos,t.end),this.timelinePos,t.start),l=this.detachedData;if(l)l.mediaSource?this.attachPrimary(i,t,!0):this.startLoadingPrimaryAt(i);else{const o=this.playingItem,c=this.isInterstitial(o)&&o.event.appendInPlace;this.startLoadingPrimaryAt(i,c)}}}}bufferedToEvent(t,n){const r=t.event,a=r.assetList.length===0&&!r.assetListLoader,i=r.cue.once;if(a||!i){const l=this.preloadAssets(r,n);if(l!=null&&l.interstitial.appendInPlace){const o=this.primaryMedia;o&&this.bufferAssetPlayer(l,o)}}}preloadAssets(t,n){const r=t.assetUrl,a=t.assetList.length,i=a===0&&!t.assetListLoader,l=t.cue.once;if(i){const c=t.timelineStart,d=this.playingItem,u=this.getBufferingPlayer();if(t.appendInPlace){var o;!this.isInterstitial(d)&&(d==null||(o=d.nextEvent)==null?void 0:o.identifier)===t.identifier&&this.flushFrontBuffer(c+.25)}let h,m=0;if((!u||u.interstitial.cue.pre)&&this.primaryLive&&(m=this.getLiveStartPos(),u&&(m+=u.remaining)),m&&!(t.cue.pre||t.cue.post)){const g=m-c;g>0&&(h=Math.round(g*1e3)/1e3)}if(this.log(`Load interstitial asset ${n+1}/${r?1:a} ${t}${m?` live-start: ${m} start-offset: ${h} (timeline-start: ${c})`:""}`),r)return this.createAsset(t,0,0,c,t.duration,r);const p=this.assetListLoader.loadAssetList(t,h);p&&(t.assetListLoader=p)}else if(!l&&a){for(let d=n;d=r.edge)return;this.log(`Removing front buffer starting at ${t}`),Object.keys(n).forEach(i=>{this.hls.trigger(Mt.BUFFER_FLUSHING,{startOffset:t,endOffset:1/0,type:i})})}getAssetPlayerQueueIndex(t){const n=this.playerQueue;for(let r=0;r=0){const A=n.duration;A&&C{if(C.live){const I=new Error(`Interstitials MUST be VOD assets ${t}`),P={fatal:!0,type:xo.OTHER_ERROR,details:er.INTERSTITIAL_ASSET_ITEM_ERROR,error:I},R=this.findEventIndex(t.identifier);this.handleAssetItemError(P,t,R,r,I.message);return}const A=C.edge-C.fragmentStart,M=n.duration;(x||M===null||A>M)&&(x=!1,this.log(`Interstitial asset "${h}" duration change ${M} > ${A}`),n.duration=A,this.updateSchedule())};g.on(Mt.LEVEL_UPDATED,(C,{details:A})=>y(A)),g.on(Mt.LEVEL_PTS_UPDATED,(C,{details:A})=>y(A)),g.on(Mt.EVENT_CUE_ENTER,()=>this.onInterstitialCueEnter());const v=(C,A)=>{const M=this.getAssetPlayer(h);if(M&&A.tracks){M.off(Mt.BUFFER_CODECS,v),M.tracks=A.tracks;const I=this.primaryMedia;this.bufferingAsset===M.assetItem&&I&&!M.media&&this.bufferAssetPlayer(M,I)}};g.on(Mt.BUFFER_CODECS,v);const _=()=>{const C=this.getAssetPlayer(h);if(this.log(`buffered to end of asset ${C}`),!C||!this.schedule)return;const A=this.getEventItem(t.identifier);A&&this.advanceAssetBuffering(A,C.assetItem)};g.on(Mt.BUFFERED_TO_END,_);const j=C=>()=>{if(!this.getAssetPlayer(h)||!this.schedule)return;this.shouldPlay=!0;const M=this.findEventIndex(t.identifier);this.advanceAfterAssetEnded(t,M,C)};return g.once(Mt.MEDIA_ENDED,j(r)),g.once(Mt.PLAYOUT_LIMIT_REACHED,j(1/0)),g.on(Mt.ERROR,(C,A)=>{if(!this.schedule)return;const M=this.getAssetPlayer(h);if(A.details===er.BUFFER_STALLED_ERROR){if(M!=null&&M.appendInPlace){this.handleInPlaceStall(t);return}this.onTimeupdate(),this.checkBuffer(!0);return}else if(A.details===er.BUFFER_SEEK_OVER_HOLE)return;this.handleAssetItemError(A,t,this.findEventIndex(t.identifier),r,`Asset player error ${A.error} ${t}`)}),g.on(Mt.DESTROYING,()=>{if(!this.getAssetPlayer(h)||!this.schedule)return;const A=new Error(`Asset player destroyed unexpectedly ${h}`),M={fatal:!0,type:xo.OTHER_ERROR,details:er.INTERSTITIAL_ASSET_ITEM_ERROR,error:A};this.handleAssetItemError(M,t,this.findEventIndex(t.identifier),r,A.message)}),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${Z9(n)}`),this.hls.trigger(Mt.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:n,assetListIndex:r,event:t,player:g}),g}clearInterstitial(t,n){this.clearAssetPlayers(t,n),t.reset()}clearAssetPlayers(t,n){t.assetList.forEach(r=>{this.clearAssetPlayer(r.identifier,n)})}resetAssetPlayer(t){const n=this.getAssetPlayerQueueIndex(t);if(n!==-1){this.log(`reset asset player "${t}" after error`);const r=this.playerQueue[n];this.transferMediaFromPlayer(r,null),r.resetDetails()}}clearAssetPlayer(t,n){const r=this.getAssetPlayerQueueIndex(t);if(r!==-1){const a=this.playerQueue[r];this.log(`clear ${a} toSegment: ${n&&gw(n)}`),this.transferMediaFromPlayer(a,n),this.playerQueue.splice(r,1),a.destroy()}}emptyPlayerQueue(){let t;for(;t=this.playerQueue.pop();)t.destroy();this.playerQueue=[]}startAssetPlayer(t,n,r,a,i){const{interstitial:l,assetItem:o,assetId:c}=t,d=l.assetList.length,u=this.playingAsset;this.endedAsset=null,this.playingAsset=o,(u==null?void 0:u.identifier)!==c&&(u&&(this.clearAssetPlayer(u.identifier,r[a]),delete u.error),this.log(`INTERSTITIAL_ASSET_STARTED ${n+1}/${d} ${Z9(o)}`),this.hls.trigger(Mt.INTERSTITIAL_ASSET_STARTED,{asset:o,assetListIndex:n,event:l,schedule:r.slice(0),scheduleIndex:a,player:t})),this.bufferAssetPlayer(t,i)}bufferAssetPlayer(t,n){var r;if(!this.schedule)return;const{interstitial:a,assetItem:i}=t,l=this.getEventItem(a.identifier);if(!l)return;if(t.loadSource(),this.setBufferingItem(l),this.bufferingAsset=i,t.bufferedInPlaceToEnd(this.primaryMedia,t.currentTime)){this.advanceAssetBuffering(l,i);return}const o=this.getBufferingPlayer();if(o===t)return;const c=a.appendInPlace;if(c&&(o==null?void 0:o.interstitial.appendInPlace)===!1)return;const d=(o==null?void 0:o.tracks)||((r=this.detachedData)==null?void 0:r.tracks)||this.requiredTracks;if(c&&i!==this.playingAsset){if(!t.tracks){this.log(`Waiting for track info before buffering ${t}`);return}if(d&&!dHt(d,t.tracks)){const u=new Error(`Asset ${Z9(i)} SourceBuffer tracks ('${Object.keys(t.tracks)}') are not compatible with primary content tracks ('${Object.keys(d)}')`),h={fatal:!0,type:xo.OTHER_ERROR,details:er.INTERSTITIAL_ASSET_ITEM_ERROR,error:u},m=a.findAssetIndex(i);this.handleAssetItemError(h,a,this.findEventIndex(a.identifier),m,u.message);return}}this.transferMediaTo(t,n)}handleInPlaceStall(t){const n=this.schedule,r=this.primaryMedia;if(!n||!r)return;const a=r.currentTime,i=n.findAssetIndex(t,a),l=t.assetList[i];if(l){const o=this.getAssetPlayer(l.identifier);if(o){const c=o.currentTime||a-l.timelineStart,d=o.duration-c;if(this.warn(`Stalled at ${c} of ${c+d} in ${o} ${t} (media.currentTime: ${a})`),c&&(d/r.playbackRate<.5||o.bufferedInPlaceToEnd(r,o.currentTime))&&o.hls){const u=n.findEventIndex(t.identifier);this.advanceAfterAssetEnded(t,u,i)}}}}advanceInPlace(t){const n=this.primaryMedia;if(n&&n.currentTimet?(this.log(r),n.currentTime=t):this.log(`Cannot ${r}`)}}handleAssetItemError(t,n,r,a,i){if(t.details===er.BUFFER_STALLED_ERROR)return;const l=n.assetList[a]||null;if(this.warn(`INTERSTITIAL_ASSET_ERROR ${l&&Z9(l)} ${t.error}`),!this.schedule)return;const o=(l==null?void 0:l.identifier)||"",c=this.getAssetPlayerQueueIndex(o),d=this.playerQueue[c]||null,u=this.schedule.items,h=wh({},t,{fatal:!1,errorAction:cZ(!0),asset:l,assetListIndex:a,event:n,schedule:u,scheduleIndex:r,player:d});if(this.hls.trigger(Mt.INTERSTITIAL_ASSET_ERROR,h),!t.fatal)return;const m=this.playingAsset,p=this.bufferingAsset,g=new Error(i);if(l&&(this.clearAssetPlayer(o,null),l.error=g),!n.assetList.some(x=>!x.error))n.error=g;else for(let x=a;x{const y=parseFloat(g.DURATION);this.createAsset(i,x,u,c+u,y,g.URI),u+=y}),i.duration=u,this.log(`Loaded asset-list with duration: ${u} (was: ${d}) ${i}`);const h=this.waitingItem,m=(h==null?void 0:h.event.identifier)===l;this.updateSchedule();const p=(a=this.bufferingItem)==null?void 0:a.event;if(m){const g=this.findEventIndex(l),x=this.getEventItem(l);if(x){if(!this.playingItem&&this.timelinePos>x.end&&this.schedule.findItemIndexAtTime(this.timelinePos)!==g){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(x)}this.setSchedulePosition(g)}else if((p==null?void 0:p.identifier)===l){const g=i.assetList[0];if(g){const x=this.getAssetPlayer(g.identifier);if(p.appendInPlace){const y=this.primaryMedia;x&&y&&this.bufferAssetPlayer(x,y)}else x&&x.loadSource()}}}onError(t,n){if(this.schedule)switch(n.details){case er.ASSET_LIST_PARSING_ERROR:case er.ASSET_LIST_LOAD_ERROR:case er.ASSET_LIST_LOAD_TIMEOUT:{const r=n.interstitial;r&&(this.updateSchedule(!0),this.primaryFallback(r));break}case er.BUFFER_STALLED_ERROR:{const r=this.endedItem||this.waitingItem||this.playingItem;if(this.isInterstitial(r)&&r.event.appendInPlace){this.handleInPlaceStall(r.event);return}const a=this.primaryMedia;this.log(`Primary player stall @${this.timelinePos} currentTime: ${a==null?void 0:a.currentTime} bufferedPos: ${this.bufferedPos}`),this.onTimeupdate(),this.checkBuffer(!0);break}}}}class Cqn{constructor(t){this.hls=void 0,this.media=null,this.currentTime=0,this.stallCount=0,this._latency=null,this._targetLatencyUpdated=!1,this.onTimeupdate=()=>{var n;const{media:r}=this,a=this.levelDetails;if(!r||!a||!this.hls)return;this.currentTime=r.currentTime;const i=this.hls.config,l=this.computeLatency();if(l===null)return;this._latency=l;const{lowLatencyMode:o,maxLiveSyncPlaybackRate:c}=i;if(!o||c===1||!a.live)return;const d=this.targetLatency;if(d===null)return;const u=l-d,h=Math.min(this.maxLatency,d+a.targetduration),m=u.05&&this.forwardBufferLength>1&&!p){const g=Math.min(2,Math.max(1,c)),x=Math.round(2/(1+Math.exp(-.75*u-this.edgeStalled))*20)/20,y=Math.min(g,Math.max(1,x));this.changeMediaPlaybackRate(r,y)}else r.playbackRate!==1&&r.playbackRate!==0&&this.changeMediaPlaybackRate(r,1)},this.hls=t,this.registerListeners()}get levelDetails(){var t;return((t=this.hls)==null?void 0:t.latestLevelDetails)||null}get latency(){return this._latency||0}get maxLatency(){var t;const n=(t=this.hls)==null?void 0:t.config;if(!n)return 0;if(n.liveMaxLatencyDuration!==void 0)return n.liveMaxLatencyDuration;const r=this.levelDetails;return r?n.liveMaxLatencyDurationCount*r.targetduration:0}get targetLatency(){const t=this.levelDetails;if(t===null||!this.hls)return null;const n=this.hls.config,{holdBack:r,partHoldBack:a,targetduration:i}=t,{liveSyncDuration:l,liveSyncDurationCount:o,lowLatencyMode:c}=n,d=this.hls.userConfig;let u=c&&a||r;(this._targetLatencyUpdated||d.liveSyncDuration||d.liveSyncDurationCount||u===0)&&(u=l!==void 0?l:o*i);const h=i;return u+Math.min(this.stallCount*n.liveSyncOnStallIncrease,h)}set targetLatency(t){this.hls&&(this.stallCount=0,this.hls.config.liveSyncDuration=t,this._targetLatencyUpdated=!0)}get liveSyncPosition(){const t=this.estimateLiveEdge(),n=this.targetLatency;if(t===null||n===null||!this.hls)return null;const r=this.levelDetails;if(r===null)return null;const a=r.edge,i=t-n-this.edgeStalled,l=a-r.totalduration,o=a-(this.hls.config.lowLatencyMode&&r.partTarget||r.targetduration);return Math.min(Math.max(l,i),o)}get drift(){const t=this.levelDetails;return t===null?1:t.drift}get edgeStalled(){const t=this.levelDetails;if(t===null||!this.hls)return 0;const n=(this.hls.config.lowLatencyMode&&t.partTarget||t.targetduration)*3;return Math.max(t.age-n,0)}get forwardBufferLength(){const{media:t}=this,n=this.levelDetails;if(!t||!n)return 0;const r=t.buffered.length;return(r?t.buffered.end(r-1):n.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null}registerListeners(){const{hls:t}=this;t&&(t.on(Mt.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(Mt.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(Mt.MANIFEST_LOADING,this.onManifestLoading,this),t.on(Mt.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(Mt.ERROR,this.onError,this),t.on(Mt.INTERSTITIAL_ASSET_STARTED,this.onAssetStarted,this))}unregisterListeners(){const{hls:t}=this;t&&(t.off(Mt.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(Mt.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(Mt.MANIFEST_LOADING,this.onManifestLoading,this),t.off(Mt.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(Mt.ERROR,this.onError,this),t.off(Mt.INTERSTITIAL_ASSET_STARTED,this.onAssetStarted,this))}onMediaAttached(t,n){this.media=n.media,this.media.addEventListener("timeupdate",this.onTimeupdate)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.onTimeupdate),this.media=null)}onManifestLoading(){this._latency=null,this.stallCount=0}onLevelUpdated(t,{details:n}){n.advanced&&this.onTimeupdate(),!n.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)}onAssetStarted(t,n){var r;const a=this.hls,i=this.media||n.event.appendInPlace&&(a==null||(r=a.interstitialsManager)==null?void 0:r.playerQueue.reduce((l,o)=>l||o.media,null));a&&i&&i.playbackRate>1&&i.playbackRate<=a.config.maxLiveSyncPlaybackRate&&this.changeMediaPlaybackRate(i,1)}onError(t,n){var r;n.details===er.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&(r=this.levelDetails)!=null&&r.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))}changeMediaPlaybackRate(t,n){var r,a;t.playbackRate!==n&&((r=this.hls)==null||r.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${(a=this.targetLatency)==null?void 0:a.toFixed(3)}, forwardBufferLength=${this.forwardBufferLength.toFixed(3)}: adjusting playback rate from ${t.playbackRate} to ${n}`),t.playbackRate=n)}estimateLiveEdge(){const t=this.levelDetails;return t===null?null:t.edge+t.age}computeLatency(){const t=this.estimateLiveEdge();return t===null?null:t-this.currentTime}}const hwt=500;class Aqn extends BQe{constructor(t,n,r){super(t,n,r,"subtitle-stream-controller",Ji.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(Mt.LEVEL_LOADED,this.onLevelLoaded,this),t.on(Mt.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(Mt.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.on(Mt.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(Mt.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.on(Mt.BUFFER_FLUSHING,this.onBufferFlushing,this)}unregisterListeners(){super.unregisterListeners();const{hls:t}=this;t.off(Mt.LEVEL_LOADED,this.onLevelLoaded,this),t.off(Mt.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(Mt.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.off(Mt.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(Mt.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.off(Mt.BUFFER_FLUSHING,this.onBufferFlushing,this)}startLoad(t,n){this.stopLoad(),this.state=Kr.IDLE,this.setInterval(hwt),this.nextLoadPosition=this.lastCurrentTime=t+this.timelineOffset,this.startPosition=n?-1:t,this.tick()}onManifestLoading(){super.onManifestLoading(),this.mainDetails=null}onMediaDetaching(t,n){this.tracksBuffered=[],super.onMediaDetaching(t,n)}onLevelLoaded(t,n){this.mainDetails=n.details}onSubtitleFragProcessed(t,n){const{frag:r,part:a,success:i}=n;if(!i)return;const l=this.tracksBuffered[this.currentTrackId];if(!l)return;let o;const c=(a||r).start;for(let u=0;u=l[u].start&&c<=l[u].end){o=l[u];break}const d=c+(a||r).duration;if(o?o.end=d:(o={start:c,end:d},l.push(o)),!a||d>=r.end){const u=this.fragmentTracker.fragBuffered(r);a&&u&&(u.range.subs={time:[{startPTS:r.start,endPTS:d}],partial:!0}),Lp(r)&&!this.fragContextChanged(r)&&(this.fragPrevious=r),this.fragBufferedComplete(r,a),this.media&&this.tickImmediate()}}onBufferFlushing(t,n){const{startOffset:r,endOffset:a}=n;if(r===0&&a!==Number.POSITIVE_INFINITY){const i=a-1;if(i<=0)return;n.endOffsetSubtitles=Math.max(0,i),this.tracksBuffered.forEach(l=>{if(l)for(let o=0;onew bQ(r));return}this.tracksBuffered=[],this.levels=n.map(r=>{const a=new bQ(r);return this.tracksBuffered[a.id]=[],a}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,Ji.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null}onSubtitleTrackSwitch(t,n){var r;if(this.currentTrackId=n.id,!((r=this.levels)!=null&&r.length)||this.currentTrackId===-1){this.clearInterval();return}const a=this.levels[this.currentTrackId];if(!(a!=null&&a.details)){this.mediaBuffer=null;return}this.mediaBuffer=this.mediaBufferTimeRanges,this.state!==Kr.STOPPED&&this.setInterval(hwt)}onSubtitleTrackLoaded(t,n){var r;const{currentTrackId:a,levels:i}=this,{details:l,id:o}=n;if(!i){this.warn(`Subtitle tracks were reset while loading level ${o}`);return}const c=i[o];if(o>=i.length||!c)return;this.log(`Subtitle track ${o} loaded [${l.startSN},${l.endSN}]${l.lastPartSn?`[part-${l.lastPartSn}-${l.lastPartIndex}]`:""},duration:${l.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;const d=this.mainDetails;let u=0;if(l.live||(r=c.details)!=null&&r.live){if(l.deltaUpdateFailed)return;if(!d){this.startFragRequested=!1;return}if(c.details){var h;u=this.alignPlaylists(l,c.details,(h=this.levelLastLoaded)==null?void 0:h.details)}l.alignedSliding||(cCe(d,l,this),u=l.fragmentStart)}c.details=l,this.levelLastLoaded=c,d&&!this.startFragRequested&&this.setStartPosition(d,u),o===a&&(this.hls.trigger(Mt.SUBTITLE_TRACK_UPDATED,{details:l,id:o,groupId:n.groupId}),this.tickImmediate())}_handleFragmentLoadProgress(t){const{frag:n,part:r,payload:a}=t;!r||!(a!=null&&a.byteLength)||!this.shouldDecrypt(n)||this.decryptPayload(a,n,r)}_handleFragmentLoadComplete(t){const{frag:n,payload:r}=t;this.fragContextChanged(n)||!(r!=null&&r.byteLength)||!this.shouldDecrypt(n)||this.decryptPayload(r,n,null)}shouldDecrypt(t){const n=t.decryptdata;return!!(n!=null&&n.key&&n.iv&&VB(n.method))}decryptPayload(t,n,r){const a=n.decryptdata,i=performance.now();this.decrypter.decrypt(new Uint8Array(t),a.key.buffer,a.iv.buffer,FQe(a.method)).then(l=>{this.fragContextChanged(n)||this.hls.trigger(Mt.FRAG_DECRYPTED,{frag:n,part:r,payload:l,stats:{tstart:i,tdecrypt:performance.now()}})}).catch(l=>{this.hls.trigger(Mt.ERROR,{type:xo.MEDIA_ERROR,details:er.FRAG_DECRYPT_ERROR,fatal:!1,error:l,reason:l.message,frag:n,part:r}),r||(this.warn(`${l.name}: ${l.message}`),this.state=Kr.IDLE)})}doTick(){if(this.state===Kr.IDLE&&this.levels){var t;if(!this.media&&!this.primaryPrefetch&&(this.startFragRequested||!this.config.startFragPrefetch))return;const{currentTrackId:r,levels:a}=this,i=a[r],l=i==null?void 0:i.details;if(!l||this.waitForLive(i)||this.waitForCdnTuneIn(l)){this.startFragRequested=!1;return}const{config:o}=this,c=this.playhead,d=pl.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],c,o.maxBufferHole),{end:u,len:h}=d,m=Math.max(this.hls.maxBufferLength+l.levelTargetDuration,((t=this.hls.mainForwardBufferInfo)==null?void 0:t.len)||0);if(h>m||h&&!this.buffering)return;let p=this.getNextFragment(u,l);if(!p)return;if(Lp(p)){var n;const g=p.sn-l.startSN,x=l.fragments[g-1];p.cc===(x==null?void 0:x.cc)&&!((n=l.partList)!=null&&n.length)&&this.fragmentTracker.getState(x)===ep.NOT_LOADED&&(p=x)}this.loadFragment(p,i,u)}}loadFragment(t,n,r){const a=this.fragmentTracker.getState(t);(a===ep.NOT_LOADED||a===ep.PARTIAL)&&super.loadFragment(t,n,r)}get mediaBufferTimeRanges(){return new Eqn(this.tracksBuffered[this.currentTrackId]||[])}}class Eqn{constructor(t){this.buffered=void 0;const n=(r,a,i)=>{if(a=a>>>0,a>i-1)throw new DOMException(`Failed to execute '${r}' on 'TimeRanges': The index provided (${a}) is greater than the maximum bound (${i})`);return t[a][r]};this.buffered={get length(){return t.length},end(r){return n("end",r,t.length)},start(r){return n("start",r,t.length)}}}}const Tqn={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},tWt=s=>String.fromCharCode(Tqn[s]||s),_N=15,xN=42,Mqn={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},Pqn={17:2,18:4,21:6,22:8,23:10,19:13,20:15},Iqn={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},Lqn={25:2,26:4,29:6,30:8,31:10,27:13,28:15},Rqn=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class Dqn{constructor(){this.time=null,this.verboseLevel=0}log(t,n){if(this.verboseLevel>=t){const r=typeof n=="function"?n():n;ku.log(`${this.time} [${t}] ${r}`)}}}const gP=function(t){const n=[];for(let r=0;r=xN&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=xN-1)}moveCursor(t){const n=Math.min(this.pos+t,xN);if(t>1)for(let r=this.pos+1;r=144&&this.backSpace();const n=tWt(t);if(this.pos>=xN){this.logger.log(0,()=>"Cannot insert "+t.toString(16)+" ("+n+") at position "+this.pos+". Skipping it!");return}this.chars[this.pos].setChar(n,this.currPenState),this.moveCursor(1)}clearFromPos(t){let n;for(n=t;n"pacData = "+bm(t));let n=t.row-1;if(this.nrRollUpRows&&n"bkgData = "+bm(t)),this.backSpace(),this.setPen(t),this.insertChar(32)}setRollUpRows(t){this.nrRollUpRows=t}rollUp(){if(this.nrRollUpRows===null){this.logger.log(3,"roll_up but nrRollUpRows not set yet");return}this.logger.log(1,()=>this.getDisplayText());const t=this.currRow+1-this.nrRollUpRows,n=this.rows.splice(t,1)[0];n.clear(),this.rows.splice(this.currRow,0,n),this.logger.log(2,"Rolling up")}getDisplayText(t){t=t||!1;const n=[];let r="",a=-1;for(let i=0;i<_N;i++){const l=this.rows[i].getTextString();l&&(a=i+1,t?n.push("Row "+a+": '"+l+"'"):n.push(l.trim()))}return n.length>0&&(t?r="["+n.join(" | ")+"]":r=n.join(` `)),r}getTextAndFormat(){return this.rows}}class zqn{constructor(t,n,r){this.chNr=void 0,this.outputFilter=void 0,this.mode=void 0,this.verbose=void 0,this.displayedMemory=void 0,this.nonDisplayedMemory=void 0,this.lastOutputScreen=void 0,this.currRollUpRow=void 0,this.writeScreen=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chNr=t,this.outputFilter=n,this.mode=null,this.verbose=0,this.displayedMemory=new I8e(r),this.nonDisplayedMemory=new I8e(r),this.lastOutputScreen=new I8e(r),this.currRollUpRow=this.displayedMemory.rows[_N-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=r}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[_N-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}getHandler(){return this.outputFilter}setHandler(t){this.outputFilter=t}setPAC(t){this.writeScreen.setPAC(t)}setBkgData(t){this.writeScreen.setBkgData(t)}setMode(t){t!==this.mode&&(this.mode=t,this.logger.log(2,()=>"MODE="+t),this.mode==="MODE_POP-ON"?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),this.mode!=="MODE_ROLL-UP"&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=t)}insertChars(t){for(let r=0;rn+": "+this.writeScreen.getDisplayText(!0)),(this.mode==="MODE_PAINT-ON"||this.mode==="MODE_ROLL-UP")&&(this.logger.log(1,()=>"DISPLAYED: "+this.displayedMemory.getDisplayText(!0)),this.outputDataUpdate())}ccRCL(){this.logger.log(2,"RCL - Resume Caption Loading"),this.setMode("MODE_POP-ON")}ccBS(){this.logger.log(2,"BS - BackSpace"),this.mode!=="MODE_TEXT"&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())}ccAOF(){}ccAON(){}ccDER(){this.logger.log(2,"DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()}ccRU(t){this.logger.log(2,"RU("+t+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(t)}ccFON(){this.logger.log(2,"FON - Flash On"),this.writeScreen.setPen({flash:!0})}ccRDC(){this.logger.log(2,"RDC - Resume Direct Captioning"),this.setMode("MODE_PAINT-ON")}ccTR(){this.logger.log(2,"TR"),this.setMode("MODE_TEXT")}ccRTD(){this.logger.log(2,"RTD"),this.setMode("MODE_TEXT")}ccEDM(){this.logger.log(2,"EDM - Erase Displayed Memory"),this.displayedMemory.reset(),this.outputDataUpdate(!0)}ccCR(){this.logger.log(2,"CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate(!0)}ccENM(){this.logger.log(2,"ENM - Erase Non-displayed Memory"),this.nonDisplayedMemory.reset()}ccEOC(){if(this.logger.log(2,"EOC - End Of Caption"),this.mode==="MODE_POP-ON"){const t=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=t,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,()=>"DISP: "+this.displayedMemory.getDisplayText())}this.outputDataUpdate(!0)}ccTO(t){this.logger.log(2,"TO("+t+") - Tab Offset"),this.writeScreen.moveCursor(t)}ccMIDROW(t){const n={flash:!1};if(n.underline=t%2===1,n.italics=t>=46,n.italics)n.foreground="white";else{const r=Math.floor(t/2)-16,a=["white","green","blue","cyan","red","yellow","magenta"];n.foreground=a[r]}this.logger.log(2,"MIDROW: "+bm(n)),this.writeScreen.setPen(n)}outputDataUpdate(t=!1){const n=this.logger.time;n!==null&&this.outputFilter&&(this.cueStartTime===null&&!this.displayedMemory.isEmpty()?this.cueStartTime=n:this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,n,this.lastOutputScreen),t&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:n),this.lastOutputScreen.copy(this.displayedMemory))}cueSplitAtTime(t){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,t,this.displayedMemory),this.cueStartTime=t))}}class mwt{constructor(t,n,r){this.channels=[null,null,null],this.currentChannel=0,this.cmdHistory=$qn(),this.logger=void 0,this.field=void 0,this.outputFilters=void 0,this.logger=new Dqn,this.field=t,this.outputFilters=[null,n,r]}getHandler(t){return this.outputFilters[t]}setHandler(t,n){var r;this.outputFilters[t]=n,(r=this.channels[t])==null||r.setHandler(n)}getChannel(t){let n=this.channels[t];return n||(n=this.channels[t]=new zqn(this.field+t-1,this.outputFilters[t],this.logger)),n}addData(t,n){this.logger.time=t;for(let r=0;r"["+gP([n[r],n[r+1]])+"] -> ("+gP([a,i])+")");const c=this.cmdHistory;if(a>=16&&a<=31){if(Bqn(a,i,c)){gie(null,null,c),this.logger.log(3,()=>"Repeated command ("+gP([a,i])+") is dropped");continue}gie(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 gie(null,null,c);if(!l&&(o=this.parseChars(a,i),o)){const u=this.currentChannel;u&&u>0?this.getChannel(u).insertChars(o):this.logger.log(2,"No channel found yet. TEXT-MODE?")}!l&&!o&&this.logger.log(2,()=>"Couldn't parse cleaned data "+gP([a,i])+" orig: "+gP([n[r],n[r+1]]))}}parseCmd(t,n){const r=(t===20||t===28||t===21||t===29)&&n>=32&&n<=47,a=(t===23||t===31)&&n>=33&&n<=35;if(!(r||a))return!1;const i=t===20||t===21||t===23?1:2,l=this.getChannel(i);return t===20||t===21||t===28||t===29?n===32?l.ccRCL():n===33?l.ccBS():n===34?l.ccAOF():n===35?l.ccAON():n===36?l.ccDER():n===37?l.ccRU(2):n===38?l.ccRU(3):n===39?l.ccRU(4):n===40?l.ccFON():n===41?l.ccRDC():n===42?l.ccTR():n===43?l.ccRTD():n===44?l.ccEDM():n===45?l.ccCR():n===46?l.ccENM():n===47&&l.ccEOC():l.ccTO(n-32),this.currentChannel=i,!0}parseMidrow(t,n){let r=0;if((t===17||t===25)&&n>=32&&n<=47){if(t===17?r=1:r=2,r!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;const a=this.channels[r];return a?(a.ccMIDROW(n),this.logger.log(3,()=>"MIDROW ("+gP([t,n])+")"),!0):!1}return!1}parsePAC(t,n){let r;const a=(t>=17&&t<=23||t>=25&&t<=31)&&n>=64&&n<=127,i=(t===16||t===24)&&n>=64&&n<=95;if(!(a||i))return!1;const l=t<=23?1:2;return n>=64&&n<=95?r=l===1?Mqn[t]:Iqn[t]:r=l===1?Pqn[t]:Lqn[t],this.getChannel(l).setPAC(this.interpretPAC(r,n)),this.currentChannel=l,!0}interpretPAC(t,n){let r;const a={color:null,italics:!1,indent:null,underline:!1,row:t};return n>95?r=n-96:r=n-64,a.underline=(r&1)===1,r<=13?a.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(r/2)]:r<=15?(a.italics=!0,a.color="white"):a.indent=Math.floor((r-16)/2)*4,a}parseChars(t,n){let r,a=null,i=null;if(t>=25?(r=2,i=t-8):(r=1,i=t),i>=17&&i<=19){let l;i===17?l=n+80:i===18?l=n+112:l=n+144,this.logger.log(2,()=>"Special char '"+tWt(l)+"' in channel "+r),a=[l]}else t>=32&&t<=127&&(a=n===0?[t]:[t,n]);return a&&this.logger.log(3,()=>"Char codes = "+gP(a).join(",")),a}parseBackgroundAttributes(t,n){const r=(t===16||t===24)&&n>=32&&n<=47,a=(t===23||t===31)&&n>=45&&n<=47;if(!(r||a))return!1;let i;const l={};t===16||t===24?(i=Math.floor((n-32)/2),l.background=Rqn[i],n%2===1&&(l.background=l.background+"_semi")):n===45?l.background="transparent":(l.foreground="black",n===47&&(l.underline=!0));const o=t<=23?1:2;return this.getChannel(o).setBkgData(l),!0}reset(){for(let t=0;tt)&&(this.startTime=t),this.endTime=n,this.screen=r,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}}class Uqn{constructor(t){this.hls=void 0,this.media=null,this.config=void 0,this.enabled=!0,this.Cues=void 0,this.tracks=[],this.initPTS=[],this.unparsedVttFrags=[],this.captionsTracks={},this.cueCache={},this.nonNativeCaptionsTracks={},this.cea608Parser1=void 0,this.cea608Parser2=void 0,this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=fwt(),this.captionsProperties=void 0,this.hls=t,this.config=t.config,this.Cues=t.config.cueHandler,this.cueCache={},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(Mt.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(Mt.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(Mt.MANIFEST_LOADING,this.onManifestLoading,this),t.on(Mt.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(Mt.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(Mt.FRAG_LOADING,this.onFragLoading,this),t.on(Mt.FRAG_LOADED,this.onFragLoaded,this),t.on(Mt.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.on(Mt.FRAG_DECRYPTED,this.onFragDecrypted,this),t.on(Mt.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(Mt.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.on(Mt.BUFFER_APPENDED,this.onBufferAppended,this),t.on(Mt.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:t}=this;t.off(Mt.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(Mt.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(Mt.MANIFEST_LOADING,this.onManifestLoading,this),t.off(Mt.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(Mt.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(Mt.FRAG_LOADING,this.onFragLoading,this),t.off(Mt.FRAG_LOADED,this.onFragLoaded,this),t.off(Mt.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.off(Mt.FRAG_DECRYPTED,this.onFragDecrypted,this),t.off(Mt.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(Mt.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.off(Mt.BUFFER_APPENDED,this.onBufferAppended,this),t.off(Mt.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){const t=new xie(this,"textTrack1"),n=new xie(this,"textTrack2"),r=new xie(this,"textTrack3"),a=new xie(this,"textTrack4");this.cea608Parser1=new mwt(1,t,n),this.cea608Parser2=new mwt(3,r,a)}addCues(t,n,r,a,i){let l=!1;for(let c=i.length;c--;){const d=i[c],u=qqn(d[0],d[1],n,r);if(u>=0&&(d[0]=Math.min(d[0],n),d[1]=Math.max(d[1],r),l=!0,u/(r-n)>.5))return}if(l||i.push([n,r]),this.config.renderTextTracksNatively){const c=this.cueCache[t];if(c){const d=this.Cues.newCue(null,n,r,a);d.length&&c.push.apply(c,d)}else{const d=this.captionsTracks[t].track;this.Cues.newCue(d,n,r,a)}}else{var o;const c=this.Cues.newCue(null,n,r,a),d=(o=this.captionsProperties[t])==null?void 0:o.media;this.hls.trigger(Mt.CUES_PARSED,{type:"captions",cues:c,track:t,closedCaptions:d})}}onInitPtsFound(t,{id:n,timestampOffsets:r}){const{unparsedVttFrags:a}=this;n===Ji.MAIN&&(this.initPTS=r),a.length&&(this.unparsedVttFrags=[],a.forEach(i=>{this.initPTS[i.frag.cc]?this.onFragLoaded(Mt.FRAG_LOADED,i):this.hls.trigger(Mt.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:i.frag,part:null,error:new Error("Subtitle discontinuity domain does not match main")})}))}createCaptionsTrack(t){this.config.renderTextTracksNatively?this.createNativeTrack(t):this.createNonNativeTrack(t)}createNativeTrack(t){if(this.captionsTracks[t])return;const{captionsProperties:n,captionsTracks:r,cueCache:a,media:i}=this,{label:l,languageCode:o}=n[t];i&&(a[t]=[],r[t]=sJe(i,"captions",l,o,"hidden"))}createNonNativeTrack(t){if(this.nonNativeCaptionsTracks[t])return;const n=this.captionsProperties[t];if(!n)return;const r=n.label,a={_id:t,label:r,kind:"captions",default:n.media?!!n.media.default:!1,closedCaptions:n.media};this.nonNativeCaptionsTracks[t]=a,this.hls.trigger(Mt.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:[a]})}onMediaAttaching(t,n){this.media=n.media}onMediaDetaching(t,n){const r=!!n.transferMedia;if(this.media=null,!r){if(this.config.renderTextTracksNatively){const{captionsTracks:a,cueCache:i}=this;for(const l in a)a[l].remove(),delete i[l]}this.cueCache={},this.captionsTracks={},this.nonNativeCaptionsTracks={}}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=fwt(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}onSubtitleTracksUpdated(t,n){const r=n.subtitleTracks||[];if(r.length&&!this.config.renderTextTracksNatively&&!wGt(this.tracks,r)){const a=r.map(i=>({label:i.name,kind:i.type.toLowerCase(),default:i.default,subtitleTrack:i}));this.hls.trigger(Mt.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:a})}this.tracks=r}onManifestLoaded(t,n){this.config.enableCEA708Captions&&n.captions&&n.captions.forEach(r=>{const a=/(?:CC|SERVICE)([1-4])/.exec(r.instreamId);if(!a)return;const i=`textTrack${a[1]}`,l=this.captionsProperties[i];l&&(l.label=r.name,r.lang&&(l.languageCode=r.lang),l.media=r)})}closedCaptionsForLevel(t){const n=this.hls.levels[t.level];return n==null?void 0:n.attrs["CLOSED-CAPTIONS"]}onFragLoading(t,n){if(this.enabled&&n.frag.type===Ji.MAIN){var r,a;const{cea608Parser1:i,cea608Parser2:l,lastSn:o}=this,{cc:c,sn:d}=n.frag,u=(r=(a=n.part)==null?void 0:a.index)!=null?r:-1;i&&l&&(d!==o+1||d===o&&u!==this.lastPartIndex+1||c!==this.lastCc)&&(i.reset(),l.reset()),this.lastCc=c,this.lastSn=d,this.lastPartIndex=u}}onFragLoaded(t,n){const{frag:r,payload:a}=n;if(r.level{this._appendCues(l,n.level),i.trigger(Mt.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:n,part:a})},l=>{i.logger.log(`Cannot parse IMSC1 (sn: ${n.sn} @${n.start}): ${l}`),i.trigger(Mt.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:n,part:a,error:l})})}_parseVTTs(t){var n;const{frag:r,payload:a}=t,i="part"in t?t.part:null,{initPTS:l,unparsedVttFrags:o}=this,c=l.length-1;if(!l[r.cc]&&c===-1){o.push(t);return}const d=this.hls,u=(n=r.initSegment)==null?void 0:n.data,h=u?z2(u,new Uint8Array(a)).buffer:a;XUn(h,this.initPTS[r.cc],this.vttCCs,r.cc,(i&&!u?i:r).start,m=>{this._appendCues(m,r.level),d.trigger(Mt.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:r,part:i})},m=>{const p=m.message.startsWith("Missing initPTS");if(d.logger.log(`${p?"Deferred parsing of":"Cannot parse"} VTT cue (sn: ${r.sn} @${r.start}): ${m}`),p){o.push(t);return}else this.config.enableIMSC1&&this._fallbackToIMSC1(t);d.trigger(Mt.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:r,part:i,error:m})})}_fallbackToIMSC1(t){const{frag:n,payload:r}=t,a=this.tracks[n.level];a.textCodec||nwt(r,this.initPTS[n.cc],()=>{a.textCodec=_qe,this._parseIMSC1(t)},()=>{a.textCodec="wvtt"})}_appendCues(t,n){const r=this.hls;if(this.config.renderTextTracksNatively){var a;const i=(a=this.tracks[n].trackNode)==null?void 0:a.track;if(!i||i.mode==="disabled")return;t.forEach(l=>wqe(i,l))}else{const i=this.tracks[n];if(!i)return;const l=i.default?"default":"subtitles"+n;r.trigger(Mt.CUES_PARSED,{type:"subtitles",cues:t,track:l,subtitleTrack:i})}}onFragDecrypted(t,n){const{frag:r}=n;r.type===Ji.SUBTITLE&&this.onFragLoaded(Mt.FRAG_LOADED,n)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(t,n){if(!this.enabled||!this.config.enableCEA708Captions)return;const{frag:r,samples:a}=n;if(!(r.type===Ji.MAIN&&this.closedCaptionsForLevel(r)==="NONE"))for(let i=0;i{var d;const u=(d=l[c])==null?void 0:d.track;if(u){const h=o[c];for(let m=0;mjqe(c[u].track,r,a)),Object.keys(d).forEach(u=>{const h=d[u];for(let m=h.length;m--;){const p=h[m];p.startTime>=r&&p.endTime<=a&&h.splice(m,1)}})}this.config.renderTextTracksNatively&&r===0&&i!==void 0&&this.tracks.forEach(c=>{var d;const u=(d=c.trackNode)==null?void 0:d.track;u&&jqe(u,r,i)})}}extractCea608Data(t){const n=[[],[]],r=t[0]&31;let a=2;for(let i=0;i=16?c--:c++;const p=GGt(d.trim()),g=tJe(t,n,p);s!=null&&(h=s.cues)!=null&&h.getCueById(g)||(l=new u(t,n,p),l.id=g,l.line=m+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((m,p)=>m.line==="auto"||p.line==="auto"?0:m.line>8&&p.line>8?p.line-m.line:m.line-p.line),a.forEach(m=>wqe(s,m))),a}};class nWt{constructor(){this.requestTimeout=void 0,this.retryTimeout=void 0,this.retryDelay=0,this.config=null,this.callbacks=null,this.context=null,this.stats=new AQe}destroy(){this.callbacks=this.context=this.config=null,this.abortInternal(),this.stats=null}load(t,n,r){const a=this.stats;if(a.loading.start)throw new Error("Loader can only be used once.");a.loading.start=self.performance.now(),this.context=t,this.config=n,this.callbacks=r,this.loadInternal()}abort(){var t;this.abortInternal(),(t=this.callbacks)!=null&&t.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.getNetworkDetails())}loadtimeout(){if(!this.config)return;const t=this.config.loadPolicy.timeoutRetry,n=this.stats.retry;if(fQ(t,n,!0))this.retry(t);else{var r;ku.warn(`timeout while loading ${(r=this.context)==null?void 0:r.url}`);const a=this.callbacks;a&&(this.abortInternal(),a.onTimeout(this.stats,this.context,this.getNetworkDetails()))}}retry(t){const{context:n,stats:r}=this;this.retryDelay=EQe(t,r.retry),r.retry++,ku.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${n==null?void 0:n.url}, retrying ${r.retry}/${t.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.resetInternalLoader(),self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(()=>this.loadInternal(),this.retryDelay)}}function Gqn(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}const Wqn=/(\d+)-(\d+)\/(\d+)/;class pwt extends nWt{constructor(t){super(),this.fetchSetup=void 0,this.request=null,this.response=null,this.controller=null,this.fetchSetup=t.fetchSetup||Xqn}destroy(){this.request=null,super.destroy(),this.response=null,this.controller=null,this.fetchSetup=null}abortInternal(){self.clearTimeout(this.retryTimeout),this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())}getNetworkDetails(){return this.response}resetInternalLoader(){this.response=null}loadInternal(){const{config:t,context:n,stats:r}=this;if(!t||!n)return;r.loading.first=0,r.loaded=0,r.aborted=!1,this.controller=new self.AbortController;const a=Kqn(n,this.controller.signal),i=n.responseType==="arraybuffer",l=i?"byteLength":"length",{maxTimeToFirstByteMs:o,maxLoadTimeMs:c}=t.loadPolicy;this.request=this.fetchSetup(n,a),self.clearTimeout(this.requestTimeout),t.timeout=o&&mi(o)?o:c,this.requestTimeout=self.setTimeout(()=>{this.loadtimeout()},t.timeout),(jQ(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(u=>{var h;this.response=u;const m=Math.max(self.performance.now(),r.loading.start);if(self.clearTimeout(this.requestTimeout),t.timeout=c,this.requestTimeout=self.setTimeout(()=>{this.loadtimeout()},c-(m-r.loading.start)),!u.ok){const{status:g,statusText:x}=u;throw new Qqn(x||"fetch, bad network response",g,u)}r.loading.first=m,r.total=Zqn(u.headers)||r.total;const p=(h=this.callbacks)==null?void 0:h.onProgress;return p&&mi(t.highWaterMark)?this.loadProgressively(u,r,n,t.highWaterMark,p):i?u.arrayBuffer():n.responseType==="json"?u.json():u.text()}).then(u=>{var h,m;const p=this.response;if(!p)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),r.loading.end=Math.max(self.performance.now(),r.loading.first);const g=u[l];g&&(r.loaded=r.total=g);const x={url:p.url,data:u,code:p.status},y=(h=this.callbacks)==null?void 0:h.onProgress;y&&!mi(t.highWaterMark)&&y(r,n,u,p),(m=this.callbacks)==null||m.onSuccess(x,r,n,p)}).catch(u=>{if(self.clearTimeout(this.requestTimeout),r.aborted)return;const h=u&&u.code||0,m=u?u.message:null,p=t.loadPolicy.errorRetry,g=r.retry,x={url:n.url,data:void 0,code:h};if(fQ(p,g,!1,x))this.retry(p);else{var y;ku.error(`${h} while loading ${n.url}`),(y=this.callbacks)==null||y.onError({code:h,text:m},n,u?u.details:null,r)}})}getCacheAge(){let t=null;if(this.response){const n=this.response.headers.get("age");t=n?parseFloat(n):null}return t}getResponseHeader(t){return this.response?this.response.headers.get(t):null}loadProgressively(t,n,r,a=0,i){const l=new rGt,o=t.body.getReader(),c=()=>o.read().then(d=>{if(d.done)return l.dataLength&&i(n,r,l.flush().buffer,t),Promise.resolve(new ArrayBuffer(0));const u=d.value,h=u.length;return n.loaded+=h,h=a&&i(n,r,l.flush().buffer,t)):i(n,r,u.buffer,t),c()}).catch(()=>Promise.reject());return c()}}function Kqn(s,t){const n={method:"GET",mode:"cors",credentials:"same-origin",signal:t,headers:new self.Headers(wh({},s.headers))};return s.rangeEnd&&n.headers.set("Range","bytes="+s.rangeStart+"-"+String(s.rangeEnd-1)),n}function Yqn(s){const t=Wqn.exec(s);if(t)return parseInt(t[2])-parseInt(t[1])+1}function Zqn(s){const t=s.get("Content-Range");if(t){const r=Yqn(t);if(mi(r))return r}const n=s.get("Content-Length");if(n)return parseInt(n)}function Xqn(s,t){return new self.Request(s.url,t)}class Qqn extends Error{constructor(t,n,r){super(t),this.code=void 0,this.details=void 0,this.code=n,this.details=r}}const Jqn=(s,t,n)=>Math.max(t,Math.min(s,n)),eVn=/^age:\s*[\d.]+\s*$/im;class rWt extends nWt{constructor(t){super(),this.xhrSetup=void 0,this.loader=null,this.xhrSetup=t.xhrSetup||null}destroy(){super.destroy(),this.loader=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()))}getNetworkDetails(){return this.loader}resetInternalLoader(){this.loader=null}loadInternal(){const{config:t,context:n}=this;if(!t||!n)return;const r=this.loader=new self.XMLHttpRequest,a=this.stats;a.loading.first=0,a.loaded=0,a.aborted=!1;const i=this.xhrSetup;i?Promise.resolve().then(()=>{if(!(this.loader!==r||this.stats.aborted))return i.call(this,r,n.url,n)}).catch(l=>{if(!(this.loader!==r||this.stats.aborted))return r.open("GET",n.url,!0),i.call(this,r,n.url,n)}).then(()=>{this.loader!==r||this.stats.aborted||this.openAndSendXhr(r,n,t)}).catch(l=>{var o;(o=this.callbacks)==null||o.onError({code:r.status,text:l.message},n,r,a)}):this.openAndSendXhr(r,n,t)}openAndSendXhr(t,n,r){t.readyState||t.open("GET",n.url,!0);const a=n.headers,{maxTimeToFirstByteMs:i,maxLoadTimeMs:l}=r.loadPolicy;if(a)for(const o in a)t.setRequestHeader(o,a[o]);n.rangeEnd&&t.setRequestHeader("Range",`bytes=${n.rangeStart}-${n.rangeEnd-1}`),t.onreadystatechange=this.readystatechange.bind(this),t.onprogress=this.loadprogress.bind(this),t.responseType=n.responseType,self.clearTimeout(this.requestTimeout),r.timeout=i&&mi(i)?i:l,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),r.timeout),t.send()}readystatechange(){const{context:t,loader:n,stats:r}=this;if(!t||!n)return;const a=n.readyState,i=this.config;if(!r.aborted&&a>=2&&(r.loading.first===0&&(r.loading.first=Math.max(self.performance.now(),r.loading.start),i.timeout!==i.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),i.timeout=i.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),i.loadPolicy.maxLoadTimeMs-(r.loading.first-r.loading.start)))),a===4)){self.clearTimeout(this.requestTimeout),n.onreadystatechange=null,n.onprogress=null;const d=n.status,u=n.responseType==="text"?n.responseText:null;if(d>=200&&d<300){const g=u??n.response;if(g!=null){var l,o;r.loading.end=Math.max(self.performance.now(),r.loading.first);const x=n.responseType==="arraybuffer"?g.byteLength:g.length;r.loaded=r.total=x,r.bwEstimate=r.total*8e3/(r.loading.end-r.loading.first);const y=(l=this.callbacks)==null?void 0:l.onProgress;y&&y(r,t,g,n);const v={url:n.responseURL,data:g,code:d};t.rangeEnd&&x!==t.rangeEnd-t.rangeStart&&ku.warn(`Payload length ${x} does not match requested Range: bytes=${t.rangeStart}-${t.rangeEnd-1}`),(o=this.callbacks)==null||o.onSuccess(v,r,t,n);return}}const h=i.loadPolicy.errorRetry,m=r.retry,p={url:t.url,data:void 0,code:d};if(fQ(h,m,!1,p))this.retry(h);else{var c;ku.error(`${d} while loading ${t.url}`),(c=this.callbacks)==null||c.onError({code:d,text:n.statusText},t,n,r)}}}loadprogress(t){const n=this.stats;n.loaded=t.loaded,t.lengthComputable&&(n.total=t.total)}getCacheAge(){let t=null;if(this.loader&&eVn.test(this.loader.getAllResponseHeaders())){const n=this.loader.getResponseHeader("age");t=n?parseFloat(n):null}return t}getResponseHeader(t){return this.loader&&new RegExp(`^${t}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(t):null}}const tVn={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},sVn=wo(wo({autoStartLoad:!0,startPosition:-1,defaultAudioCodec:void 0,debug:!1,capLevelOnFPSDrop:!1,capLevelToPlayerSize:!1,ignoreDevicePixelRatio:!1,maxDevicePixelRatio:Number.POSITIVE_INFINITY,preferManagedMediaSource:!1,initialLiveManifestSize:1,maxBufferLength:30,backBufferLength:1/0,frontBufferFlushThreshold:1/0,loopBackBufferFlush:void 0,startOnSegmentBoundary:!1,nextAudioTrackBufferFlushForwardOffset:.25,maxBufferSize:60*1e3*1e3,maxFragLookUpTolerance:.25,maxBufferHole:.1,detectStallWithCurrentTimeMs:1250,highBufferWatchdogPeriod:2,nudgeOffset:.1,nudgeMaxRetry:3,nudgeOnVideoHole:!0,skipBufferHolePadding:.1,liveSyncMode:"edge",liveSyncDurationCount:3,liveSyncOnStallIncrease:1,liveMaxLatencyDurationCount:1/0,liveMaxUnchangedPlaylistRefresh: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,appendTimeout:1/0,ignorePlaylistParsingErrors:!1,loader:rWt,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,stretchShortVideoTrack:!1,maxAudioFramesDrift:1,forceKeyFrameOnDiscontinuity:!0,handleMpegTsVideoIntegrityErrors:"process",abrEwmaFastLive:3,abrEwmaSlowLive:9,abrEwmaFastVoD:3,abrEwmaSlowVoD:9,abrEwmaDefaultEstimate:5e5,abrEwmaDefaultEstimateMax:5e6,abrBandWidthFactor:.95,abrBandWidthUpFactor:.7,abrMaxWithRealBitrate:!1,abrSwitchInterval:0,maxStarvationDelay:4,maxLoadingDelay:4,minAutoBitrate:0,emeEnabled:!1,widevineLicenseUrl:void 0,drmSystems:{},drmSystemOptions:{},requestMediaKeySystemAccessFunc:KHt,requireKeySystemAccessOnStart:!1,testBandwidth:!0,progressive:!1,lowLatencyMode:!0,cmcd:void 0,enableDateRangeMetadataCues:!0,enableEmsgMetadataCues:!0,enableEmsgKLVMetadata:!1,enableID3MetadataCues:!0,emsgKLVSchemaUri:void 0,enableInterstitialPlayback:!0,interstitialAppendInPlace:!0,interstitialLiveLookAhead:10,iframeCacheLimit:2*1024*1024,useMediaCapabilities:!0,preserveManualLevelOnError:!1,errorPenaltyExpireMs:0,certLoadPolicy:{default:tVn},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,streamController:QGt,abrController:Uzn,bufferController:T$n,capLevelController:WQe,errorController:Gzn,fpsController:VUn,id3TrackController:dqn,gapController:lqn,latencyController:Cqn},nVn()),{},{subtitleStreamController:Aqn,subtitleTrackController:iqn,timelineController:Uqn,audioStreamController:N$n,audioTrackController:k$n,emeController:HB,cmcdController:FUn,contentSteeringController:BUn,iframeController:xqn,interstitialsController:Sqn});function nVn(){return{cueHandler:Hqn,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 rVn(s,t,n){if((t.liveSyncDurationCount||t.liveMaxLatencyDurationCount)&&(t.liveSyncDuration||t.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(t.liveMaxLatencyDurationCount!==void 0&&(t.liveSyncDurationCount===void 0||t.liveMaxLatencyDurationCount<=t.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(t.liveMaxLatencyDuration!==void 0&&(t.liveSyncDuration===void 0||t.liveMaxLatencyDuration<=t.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');if(t.liveMaxUnchangedPlaylistRefresh!==void 0){const l=t.liveMaxUnchangedPlaylistRefresh,o=Jqn(l,2,1/0);o!==l&&n.warn(`hls.js config: "liveMaxUnchangedPlaylistRefresh" clamped from ${l} to ${o}.`),t.liveMaxUnchangedPlaylistRefresh=o}const r=Sqe(s),a=["manifest","level","frag"],i=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return a.forEach(l=>{const o=`${l==="level"?"playlist":l}LoadPolicy`,c=t[o]===void 0,d=[];i.forEach(u=>{const h=`${l}Loading${u}`,m=t[h];if(m!==void 0&&c){d.push(h);const p=r[o].default;switch(t[o]={default:p},u){case"TimeOut":p.maxLoadTimeMs=m,p.maxTimeToFirstByteMs=m;break;case"MaxRetry":p.errorRetry.maxNumRetry=m,p.timeoutRetry.maxNumRetry=m;break;case"RetryDelay":p.errorRetry.retryDelayMs=m,p.timeoutRetry.retryDelayMs=m;break;case"MaxRetryTimeout":p.errorRetry.maxRetryDelayMs=m,p.timeoutRetry.maxRetryDelayMs=m;break}}}),d.length&&n.warn(`hls.js config: "${d.join('", "')}" setting(s) are deprecated, use "${o}": ${bm(t[o])}`)}),wo(wo({},r),t)}function Sqe(s){return s&&typeof s=="object"?Array.isArray(s)?s.map(Sqe):Object.keys(s).reduce((t,n)=>(t[n]=Sqe(s[n]),t),{}):s}function aVn(s,t){const n=s.loader;n!==pwt&&n!==rWt?(t.log("[config]: Custom loader detected, cannot enable progressive streaming"),s.progressive=!1):Gqn()&&(s.loader=pwt,s.progressive=!0,s.enableSoftwareAES=!0,t.log("[config]: Progressive streaming enabled, using FetchLoader"))}class iVn extends GQe{constructor(t,n){super(t,"level-controller"),this._levels=[],this._firstLevel=-1,this._maxAutoLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.lastABRSwitchTime=-1,this._iframeVariants=[],this.onParsedComplete=void 0,this.steering=n,this._registerListeners()}_registerListeners(){const{hls:t}=this;t.on(Mt.MANIFEST_LOADING,this.onManifestLoading,this),t.on(Mt.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(Mt.LEVEL_LOADED,this.onLevelLoaded,this),t.on(Mt.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(Mt.FRAG_BUFFERED,this.onFragBuffered,this),t.on(Mt.ERROR,this.onError,this)}_unregisterListeners(){const{hls:t}=this;t.off(Mt.MANIFEST_LOADING,this.onManifestLoading,this),t.off(Mt.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(Mt.LEVEL_LOADED,this.onLevelLoaded,this),t.off(Mt.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(Mt.FRAG_BUFFERED,this.onFragBuffered,this),t.off(Mt.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}stopLoad(){this._levels.forEach(n=>{n.loadError=0,n.fragmentError=0}),super.stopLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1,this._iframeVariants=[]}onManifestLoading(t,n){this.resetLevels()}onManifestLoaded(t,n){const r=this.hls.config.preferManagedMediaSource,a=[],i={},l={};let o=!1,c=!1,d=!1,u=!1;n.levels.forEach(h=>{const m=h.attrs,p=gwt(h,r),{audioCodec:g,videoCodec:x,imageCodec:y,width:v,height:_}=h;if(!p){this.log(`Some or all CODECS not supported "${m.CODECS}"`);return}o||(o=!!(v&&_)),c||(c=!!x),d||(d=!!g),u||(u=!!y);const{CODECS:j,"FRAME-RATE":C,"HDCP-LEVEL":A,"PATHWAY-ID":M,RESOLUTION:I,"VIDEO-RANGE":P}=m,O=`${`${M||"."}-`}${h.bitrate}-${I}-${C}-${j}-${P}-${A}`;if(i[O])if(i[O].uri!==h.url&&!h.attrs["PATHWAY-ID"]){const B=l[O]+=1;h.attrs["PATHWAY-ID"]=new Array(B+1).join(".");const U=this.createLevel(h);i[O]=U,a.push(U)}else h.iframes||(i[O].addGroupId("audio",m.AUDIO),i[O].addGroupId("text",m.SUBTITLES));else{const B=this.createLevel(h);i[O]=B,l[O]=1,a.push(B)}}),this.filterAndSortMediaOptions(a,n,o,c,d,u)}createLevel(t){const n=new bQ(t),r=t.supplemental;if(r!=null&&r.videoCodec&&!iWt(r.videoCodec,this.hls.config.preferManagedMediaSource)){const a=new Error(`SUPPLEMENTAL-CODECS not supported "${r.videoCodec}"`);this.log(a.message),n.supportedResult=MHt(a,[])}return n}filterAndSortMediaOptions(t,n,r,a,i,l){var o;let c=[],d=[],u=t;const h=((o=n.stats)==null?void 0:o.parsing)||{},m=this.hls.config.preferManagedMediaSource;if((r||a)&&i&&(u=u.filter(({videoCodec:A,videoRange:M,width:I,height:P})=>(!!A||!!(I&&P))&&Izn(M))),a&&l&&(u=u.filter(A=>!A.imageCodec)),u.length===0){Promise.resolve().then(()=>{if(this.hls){let A="no level with compatible codecs found in manifest",M=A;n.levels.length&&(M=`one or more CODECS in variant not supported: ${bm(n.levels.map(P=>P.attrs.CODECS).filter((P,R,O)=>O.indexOf(P)===R))}`,this.warn(M),A+=` (${M})`);const I=new Error(A);this.hls.trigger(Mt.ERROR,{type:xo.MEDIA_ERROR,details:er.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:n.url,error:I,reason:M})}}),h.end=performance.now();return}n.audioTracks&&(c=n.audioTracks.filter(A=>!A.audioCodec||aWt(A.audioCodec,m)),xwt(c)),n.subtitles&&(d=n.subtitles,xwt(d));const p=u.slice(0);u.sort((A,M)=>{if(A.attrs["HDCP-LEVEL"]!==M.attrs["HDCP-LEVEL"])return(A.attrs["HDCP-LEVEL"]||"")>(M.attrs["HDCP-LEVEL"]||"")?1:-1;if(r&&A.height!==M.height)return A.height-M.height;if(A.frameRate!==M.frameRate)return A.frameRate-M.frameRate;if(A.videoRange!==M.videoRange)return rCe.indexOf(A.videoRange)-rCe.indexOf(M.videoRange);if(A.videoCodec!==M.videoCodec){const I=Xbt(A.videoCodec),P=Xbt(M.videoCodec);if(I!==P)return P-I}if(A.uri===M.uri&&A.codecSet!==M.codecSet){const I=sCe(A.codecSet),P=sCe(M.codecSet);if(I!==P)return P-I}return A.averageBitrate!==M.averageBitrate?A.averageBitrate-M.averageBitrate:0});let g=p[0];if(this.steering&&(u=this.steering.filterParsedLevels(u),u.length!==p.length)){for(let A=0;AI&&I===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=P)}break}const y=n.iframeVariants.filter(A=>gwt(A,m));this._iframeVariants=y;const v=i&&!a,_=this.hls.config,j=!!(_.audioStreamController&&_.audioTrackController),C={levels:u,audioTracks:c,subtitleTracks:d,iframeVariants:y,sessionData:n.sessionData,sessionKeys:n.sessionKeys,firstLevel:this._firstLevel,stats:n.stats,audio:i,video:a,altAudio:j&&!v&&c.some(A=>!!A.url)};h.end=performance.now(),this.hls.trigger(Mt.MANIFEST_PARSED,C)}get iframeVariants(){return this._iframeVariants.length===0?null:this._iframeVariants}get levels(){return this._levels.length===0?null:this._levels}get loadLevelObj(){return this.currentLevel}get level(){return this.currentLevelIndex}set level(t){const n=this._levels;if(n.length===0)return;if(t<0||t>=n.length){const u=new Error("invalid level idx"),h=t<0;if(this.hls.trigger(Mt.ERROR,{type:xo.OTHER_ERROR,details:er.LEVEL_SWITCH_ERROR,level:t,fatal:h,error:u,reason:u.message}),h)return;t=Math.min(t,n.length-1)}const r=this.currentLevelIndex,a=this.currentLevel,i=a?a.attrs["PATHWAY-ID"]:void 0,l=n[t],o=l.attrs["PATHWAY-ID"];if(this.currentLevelIndex=t,this.currentLevel=l,r===t&&a&&i===o)return;this.log(`Switching to level ${t} (${l.height?l.height+"p ":""}${l.videoRange?l.videoRange+" ":""}${l.codecSet?l.codecSet+" ":""}@${l.bitrate})${o?" with Pathway "+o:""} from level ${r}${i?" with Pathway "+i:""}`);const c={level:t,attrs:l.attrs,details:l.details,bitrate:l.bitrate,averageBitrate:l.averageBitrate,maxBitrate:l.maxBitrate,realBitrate:l.realBitrate,width:l.width,height:l.height,codecSet:l.codecSet,audioCodec:l.audioCodec,videoCodec:l.videoCodec,audioGroups:l.audioGroups,subtitleGroups:l.subtitleGroups,loaded:l.loaded,loadError:l.loadError,fragmentError:l.fragmentError,name:l.name,id:l.id,uri:l.uri,url:l.url,urlId:0,audioGroupIds:l.audioGroupIds,textGroupIds:l.textGroupIds};this.hls.trigger(Mt.LEVEL_SWITCHING,c);const d=l.details;if(!d||d.live){const u=this.switchParams(l.uri,a==null?void 0:a.details,d);this.loadPlaylist(u)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(t){this.manualLevelIndex=t,this._startLevel===void 0&&(this._startLevel=t),t!==-1&&(this.level=t)}get firstLevel(){return this._firstLevel}set firstLevel(t){this._firstLevel=t}get startLevel(){if(this._startLevel===void 0){const t=this.hls.config.startLevel;return t!==void 0?t:this.hls.firstAutoLevel}return this._startLevel}set startLevel(t){this._startLevel=t}get pathways(){return this.steering?this.steering.pathways():[]}get pathwayPriority(){return this.steering?this.steering.pathwayPriority:null}set pathwayPriority(t){if(this.steering){const n=this.steering.pathways(),r=t.filter(a=>n.indexOf(a)!==-1);if(t.length<1){this.warn(`pathwayPriority ${t} should contain at least one pathway from list: ${n}`);return}this.steering.pathwayPriority=r}}onError(t,n){n.fatal||!n.context||n.context.type===Mc.LEVEL&&n.context.level===this.level&&this.checkRetry(n)}onFragBuffered(t,{frag:n}){if(n.type===Ji.MAIN){const r=n.elementaryStreams;if(!Object.keys(r).some(i=>!!r[i]))return;const a=this._levels[n.level];a!=null&&a.loadError&&(this.log(`Resetting level error count of ${a.loadError} on frag buffered`),a.loadError=0)}}onLevelLoaded(t,n){var r;const{level:a,details:i}=n,l=n.levelInfo;if(!l){var o;this.warn(`Invalid level index ${a}`),(o=n.deliveryDirectives)!=null&&o.skip&&(i.deltaUpdateFailed=!0);return}if(l===this.currentLevel||n.withoutMultiVariant){l.fragmentError===0&&(l.loadError=0);let c=l.details;c===n.details&&c.advanced&&(c=void 0),this.playlistLoaded(a,n,c)}else(r=n.deliveryDirectives)!=null&&r.skip&&(i.deltaUpdateFailed=!0)}loadPlaylist(t){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,t)}loadingPlaylist(t,n){super.loadingPlaylist(t,n);const r=this.getUrlWithDirectives(t.uri,n),a=this.currentLevelIndex,i=t.attrs["PATHWAY-ID"],l=t.details,o=l==null?void 0:l.age;this.log(`Loading level index ${a}${(n==null?void 0:n.msn)!==void 0?" at sn "+n.msn+" part "+n.part:""}${i?" Pathway "+i:""}${o&&l.live?" age "+o.toFixed(1)+(l.type&&" "+l.type||""):""} ${r}`),this.hls.trigger(Mt.LEVEL_LOADING,{url:r,level:a,levelInfo:t,pathwayId:t.attrs["PATHWAY-ID"],id:0,deliveryDirectives:n||null})}get nextLoadLevel(){return this.manualLevelIndex!==-1?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(t){const n=this.currentLevelIndex;if(this.manualLevelIndex===-1&&t!==n&&t!==-1){const a=this.hls.config.abrSwitchInterval;if(a>0){const i=performance.now(),l=i-this.lastABRSwitchTime,o=a*1e3;if(this.lastABRSwitchTime>-1&&l ${t} (${Math.round(l)}ms < ${o}ms / ${a}s)`);return}this.lastABRSwitchTime=i,this.log(`Allowing ABR level switch: ${n} -> ${t} (${Math.round(l)}ms >= ${o}ms / ${a}s)`)}}this.level=t,this.manualLevelIndex===-1&&(this.hls.nextAutoLevel=t)}removeLevel(t){var n;if(this._levels.length===1)return;const r=this._levels.filter((i,l)=>l!==t?!0:(this.steering&&this.steering.removeLevel(i),i===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,i.details&&i.details.fragments.forEach(o=>o.level=-1)),!1));tGt(r),this._levels=r,this.currentLevelIndex>-1&&(n=this.currentLevel)!=null&&n.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.manualLevelIndex>-1&&(this.manualLevelIndex=this.currentLevelIndex);const a=r.length-1;this._firstLevel=Math.min(this._firstLevel,a),this._startLevel&&(this._startLevel=Math.min(this._startLevel,a)),this.hls.trigger(Mt.LEVELS_UPDATED,{levels:r})}onLevelsUpdated(t,{levels:n}){this._levels=n}checkMaxAutoUpdated(){const{autoLevelCapping:t,maxAutoLevel:n,maxHdcpLevel:r}=this.hls;this._maxAutoLevel!==n&&(this._maxAutoLevel=n,this.hls.trigger(Mt.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:t,levels:this.levels,maxAutoLevel:n,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:r}))}}function aWt(s,t){return yQ(s,"audio",t)}function iWt(s,t){return yQ(s,"video",t)}function gwt(s,t){let{audioCodec:n,videoCodec:r}=s;n&&(s.audioCodec=n=nCe(n,t)||void 0),r&&(r=s.videoCodec=Nzn(r));const{unknownCodecs:a}=s;return!((a==null?void 0:a.length)||0||n&&!aWt(n,t)||r&&!iWt(r,t))}function xwt(s){const t={};s.forEach(n=>{const r=n.groupId||"";n.id=t[r]=t[r]||0,t[r]++})}class oVn extends wj{constructor(t,n){super("key-loader",n),this.config=void 0,this.keyLoaderInfo={},this.emeController=null,this.config=t}abort(t){for(const r in this.keyLoaderInfo){const a=this.keyLoaderInfo[r].loader;if(a){var n;if(t&&t!==((n=a.context)==null?void 0:n.frag.type))return;a.abort()}}}destroy(){for(const t in this.keyLoaderInfo){const n=this.keyLoaderInfo[t].loader;n&&n.destroy()}this.emeController=null,this.keyLoaderInfo={}}loadClear(t,n,r){return this.emeController?this.emeController.loadClear(t,n,r):null}load(t,n){return!t.decryptdata&&t.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(t).then(r=>this.loadInternal(t,n,r)):this.loadInternal(t,n)}loadInternal(t,n,r){r&&t.setKeyFormat(r);const a=t.decryptdata;if(!a){const l=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(KA(t,er.KEY_LOAD_ERROR,l))}const i=t;switch(a.method){case"SAMPLE-AES":case"SAMPLE-AES-CENC":case"SAMPLE-AES-CTR":return a.keyFormat==="identity"?this.loadKeyHTTP(i):n?n.then(()=>this.loadKeyEME(i)):this.loadKeyEME(i);case"AES-128":case"AES-256":case"AES-256-CTR":return this.loadKeyHTTP(i);default:return Promise.reject(KA(t,er.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${a.method}"`)))}}loadKeyEME(t){if(this.emeController&&this.config.emeEnabled){var n;if(!t.decryptdata.keyId&&(n=t.initSegment)!=null&&n.data){const r=rzn(t.initSegment.data);if(r.length){let a=r[0];const i=t.decryptdata.uri;if(a.some(l=>l!==0))this.log(`Using keyId found in init segment ${Ax(a)} keyUri: ${i}`),M3.setKeyIdForUri(i,a);else{const l=M3.addKeyIdForUri(i);this.log(`Patching empty keyId with ${Ax(l)} keyUri: ${i}`),a=l}t.decryptdata.keyId=a}}return this.emeController.loadKey(t).then(()=>({frag:t,keyInfo:{decryptdata:t.decryptdata}}))}return Promise.reject(KA(t,er.KEY_LOAD_ERROR,new Error(`emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`)))}loadKeyHTTP(t){const n=t.decryptdata,r=n.uri;if(!r)return Promise.reject(KA(t,er.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${r}"`)));const a=this.keyLoaderInfo[r];if(a){if(a.decryptdata.key)return n.key=a.decryptdata.key,a.keyLoadPromise=null,Promise.resolve({frag:t,keyInfo:a});if(a.keyLoadPromise)return a.keyLoadPromise.then(d=>(n.key=a.decryptdata.key,wo(wo({},d),{},{frag:t})))}this.log(`Loading${n.keyId?" keyId: "+Ax(n.keyId):""} URI: ${n.uri} from ${t.type} ${t.level}`);const i=this.config,l=i.loader,o=new l(i);t.keyLoader=o;const c=this.keyLoaderInfo[r]={decryptdata:n,keyLoadPromise:null,loader:o};return c.keyLoadPromise=new Promise((d,u)=>{const h={type:Mc.KEY,keyInfo:c,frag:t,responseType:"arraybuffer",url:r},m=i.keyLoadPolicy.default,p={loadPolicy:m,timeout:m.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},g={onSuccess:(x,y,v,_)=>{const{frag:j,keyInfo:C,url:A}=v;if(!j.decryptdata||C!==this.keyLoaderInfo[A])return u(KA(j,er.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),_));C.decryptdata.key=j.decryptdata.key=new Uint8Array(x.data),j.keyLoader=C.loader=C.keyLoadPromise=null,d({frag:j,keyInfo:C})},onError:(x,y,v,_)=>{this.resetLoader(y),u(KA(t,er.KEY_LOAD_ERROR,new Error(`HTTP Error ${x.code} loading key ${x.text}`),v,wo({url:r,data:void 0},x)))},onTimeout:(x,y,v)=>{this.resetLoader(y),u(KA(t,er.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),v))},onAbort:(x,y,v)=>{this.resetLoader(y),u(KA(t,er.INTERNAL_ABORTED,new Error("key loading aborted"),v))}};o.load(h,p,g)})}resetLoader(t){const{frag:n,keyInfo:r,url:a}=t,i=r.loader;n.keyLoader===i&&(n.keyLoader=r.loader=r.keyLoadPromise=null),delete this.keyLoaderInfo[a],i&&i.destroy()}}function KA(s,t=er.KEY_LOAD_ERROR,n,r,a){return new LS({type:xo.NETWORK_ERROR,details:t,fatal:!1,frag:s,response:a,error:n,networkDetails:r||null})}function ywt(s){const{type:t}=s;switch(t){case Mc.AUDIO_TRACK:return Ji.AUDIO;case Mc.SUBTITLE_TRACK:return Ji.SUBTITLE;default:return Ji.MAIN}}function L8e(s,t){let n=s.url;return(n===void 0||n.indexOf("data:")===0)&&(n=t.url),n}class lVn{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(Mt.MANIFEST_LOADING,this.onManifestLoading,this),t.on(Mt.LEVEL_LOADING,this.onLevelLoading,this),t.on(Mt.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.on(Mt.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),t.on(Mt.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){const{hls:t}=this;t.off(Mt.MANIFEST_LOADING,this.onManifestLoading,this),t.off(Mt.LEVEL_LOADING,this.onLevelLoading,this),t.off(Mt.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.off(Mt.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),t.off(Mt.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(t){const n=this.hls.config,r=n.pLoader,a=n.loader,i=r||a,l=new i(n);return this.loaders[t.type]=l,l}getInternalLoader(t){return this.loaders[t.type]}resetInternalLoader(t){this.loaders[t]&&delete this.loaders[t]}destroyInternalLoaders(){for(const t in this.loaders){const n=this.loaders[t];n&&n.destroy(),this.resetInternalLoader(t)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(t,n){const{url:r}=n;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:Mc.MANIFEST,url:r,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(t,n){const{id:r,level:a,pathwayId:i,url:l,deliveryDirectives:o,levelInfo:c}=n;this.load({id:r,level:a,pathwayId:i,responseType:"text",type:Mc.LEVEL,url:l,deliveryDirectives:o,levelOrTrack:c})}onAudioTrackLoading(t,n){const{id:r,groupId:a,url:i,deliveryDirectives:l,track:o}=n;this.load({id:r,groupId:a,level:null,responseType:"text",type:Mc.AUDIO_TRACK,url:i,deliveryDirectives:l,levelOrTrack:o})}onSubtitleTrackLoading(t,n){const{id:r,groupId:a,url:i,deliveryDirectives:l,track:o}=n;this.load({id:r,groupId:a,level:null,responseType:"text",type:Mc.SUBTITLE_TRACK,url:i,deliveryDirectives:l,levelOrTrack:o})}onLevelsUpdated(t,n){const r=this.loaders[Mc.LEVEL];if(r){const a=r.context;a&&!n.levels.some(i=>i===a.levelOrTrack)&&(r.abort(),delete this.loaders[Mc.LEVEL])}}load(t){var n;const r=this.hls.config;let a=this.getInternalLoader(t);if(a){const d=this.hls.logger,u=a.context;if((u==null?void 0:u.levelOrTrack)===t.levelOrTrack&&(u.url===t.url||u.deliveryDirectives&&!t.deliveryDirectives)){u.url===t.url?d.log(`[playlist-loader]: ignore ${t.url} ongoing request`):d.log(`[playlist-loader]: ignore ${t.url} in favor of ${u.url}`);return}d.log(`[playlist-loader]: aborting previous loader for type: ${t.type}`),a.abort()}let i;if(t.type===Mc.MANIFEST?i=r.manifestLoadPolicy.default:i=wh({},r.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),a=this.createInternalLoader(t),mi((n=t.deliveryDirectives)==null?void 0:n.part)){let d;if(t.type===Mc.LEVEL&&t.level!==null?d=this.hls.levels[t.level].details:t.type===Mc.AUDIO_TRACK&&t.id!==null?d=this.hls.audioTracks[t.id].details:t.type===Mc.SUBTITLE_TRACK&&t.id!==null&&(d=this.hls.subtitleTracks[t.id].details),d){const u=d.partTarget,h=d.targetduration;if(u&&h){const m=Math.max(u*3,h*.8)*1e3;i=wh({},i,{maxTimeToFirstByteMs:Math.min(m,i.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(m,i.maxTimeToFirstByteMs)})}}}const l=i.errorRetry||i.timeoutRetry||{},o={loadPolicy:i,timeout:i.maxLoadTimeMs,maxRetry:l.maxNumRetry||0,retryDelay:l.retryDelayMs||0,maxRetryDelay:l.maxRetryDelayMs||0},c={onSuccess:(d,u,h,m)=>{const p=this.getInternalLoader(h);this.resetInternalLoader(h.type);const g=d.data;u.parsing.start=performance.now(),_5.isMediaPlaylist(g)||h.type!==Mc.MANIFEST?this.handleTrackOrLevelPlaylist(d,u,h,m||null,p):this.handleMasterPlaylist(d,u,h,m)},onError:(d,u,h,m)=>{this.handleNetworkError(u,h,!1,d,m)},onTimeout:(d,u,h)=>{this.handleNetworkError(u,h,!0,void 0,d)}};a.load(t,o,c)}checkAutostartLoad(){if(!this.hls)return;const{config:{autoStartLoad:t,startPosition:n},forceStartLoad:r}=this.hls;(t||r)&&(this.hls.logger.log(`${t?"auto":"force"} startLoad with configured startPosition ${n}`),this.hls.startLoad(n))}handleMasterPlaylist(t,n,r,a){const i=this.hls,l=t.data,o=L8e(t,r),c=_5.parseMasterPlaylist(l,o);if(c.playlistParsingError){n.parsing.end=performance.now(),this.handleManifestParsingError(t,r,c.playlistParsingError,a,n);return}const{contentSteering:d,levels:u,iframeVariants:h,sessionData:m,sessionKeys:p,startTimeOffset:g,variableList:x}=c;this.variableList=x,u.forEach(j=>{const{unknownCodecs:C}=j;if(C){const{preferManagedMediaSource:A}=this.hls.config;let{audioCodec:M,videoCodec:I}=j;for(let P=C.length;P--;){const R=C[P];yQ(R,"audio",A)?(j.audioCodec=M=M?`${M},${R}`:R,vq.audio[M.substring(0,4)]=2,C.splice(P,1)):yQ(R,"video",A)&&(j.videoCodec=I=I?`${I},${R}`:R,vq.video[I.substring(0,4)]=2,C.splice(P,1))}}});const{AUDIO:y=[],SUBTITLES:v,"CLOSED-CAPTIONS":_}=_5.parseMasterPlaylistMedia(l,o,c);y.length&&!y.some(C=>!C.url)&&u[0].audioCodec&&!u[0].attrs.AUDIO&&(this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),y.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new Yf({}),bitrate:0,url:""})),i.trigger(Mt.MANIFEST_LOADED,{levels:u,audioTracks:y,subtitles:v,iframeVariants:h,captions:_,contentSteering:d,url:o,stats:n,networkDetails:a,sessionData:m,sessionKeys:p,startTimeOffset:g,variableList:x})}handleTrackOrLevelPlaylist(t,n,r,a,i){const l=this.hls,{id:o,level:c,type:d}=r,u=L8e(t,r),h=mi(c)?c:mi(o)?o:0,m=ywt(r),p=_5.parseLevelPlaylist(t.data,u,h,m,0,this.variableList);if(d===Mc.MANIFEST){const g={attrs:new Yf({}),bitrate:0,details:p,name:"",url:u};p.requestScheduled=n.loading.start+QHt(p,0),l.trigger(Mt.MANIFEST_LOADED,{levels:[g],audioTracks:[],iframeVariants:[],url:u,stats:n,networkDetails:a,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}n.parsing.end=performance.now(),r.levelDetails=p,this.handlePlaylistLoaded(p,t,n,r,a,i)}handleManifestParsingError(t,n,r,a,i){this.hls.trigger(Mt.ERROR,{type:xo.NETWORK_ERROR,details:er.MANIFEST_PARSING_ERROR,fatal:n.type===Mc.MANIFEST,url:t.url,err:r,error:r,reason:r.message,response:t,context:n,networkDetails:a,stats:i})}handleNetworkError(t,n,r=!1,a,i){let l=`A network ${r?"timeout":"error"+(a?" (status "+a.code+")":"")} occurred while loading ${t.type}`;t.type===Mc.LEVEL?l+=`: ${t.level} id: ${t.id}`:(t.type===Mc.AUDIO_TRACK||t.type===Mc.SUBTITLE_TRACK)&&(l+=` id: ${t.id} group-id: "${t.groupId}"`);const o=new Error(l);this.hls.logger.warn(`[playlist-loader]: ${l}`);let c=er.UNKNOWN,d=!1;const u=this.getInternalLoader(t);switch(t.type){case Mc.MANIFEST:c=r?er.MANIFEST_LOAD_TIMEOUT:er.MANIFEST_LOAD_ERROR,d=!0;break;case Mc.LEVEL:c=r?er.LEVEL_LOAD_TIMEOUT:er.LEVEL_LOAD_ERROR,d=!1;break;case Mc.AUDIO_TRACK:c=r?er.AUDIO_TRACK_LOAD_TIMEOUT:er.AUDIO_TRACK_LOAD_ERROR,d=!1;break;case Mc.SUBTITLE_TRACK:c=r?er.SUBTITLE_TRACK_LOAD_TIMEOUT:er.SUBTITLE_LOAD_ERROR,d=!1;break}u&&this.resetInternalLoader(t.type);const h={type:xo.NETWORK_ERROR,details:c,fatal:d,url:t.url,loader:u,context:t,error:o,networkDetails:n,stats:i};if(a){let m=t.url;n&&"url"in n&&(m=n.url),h.response=wo({url:m,data:void 0},a)}this.hls.trigger(Mt.ERROR,h)}handlePlaylistLoaded(t,n,r,a,i,l){const o=this.hls,{type:c,level:d,levelOrTrack:u,id:h,groupId:m,deliveryDirectives:p}=a,g=L8e(n,a),x=ywt(a);let y=typeof a.level=="number"&&x===Ji.MAIN?d:void 0;u&&"iframes"in u&&u.iframes&&!t.iframesOnly&&(t.playlistParsingError=new Error("EXT-X-I-FRAME-STREAM-INF media playlist MUST contain an EXT-X-I-FRAMES-ONLY tag"),t.iframesOnly=!0);const v=t.playlistParsingError;if(v){if(this.hls.logger.warn(`${v} ${t.url}`),!o.config.ignorePlaylistParsingErrors){o.trigger(Mt.ERROR,{type:xo.NETWORK_ERROR,details:er.LEVEL_PARSING_ERROR,fatal:!1,url:g,error:v,reason:v.message,response:n,context:a,level:y,parent:x,networkDetails:i,stats:r});return}t.playlistParsingError=null}if(!t.fragments.length){const _=t.playlistParsingError=new Error("No Segments found in Playlist");o.trigger(Mt.ERROR,{type:xo.NETWORK_ERROR,details:er.LEVEL_EMPTY_ERROR,fatal:!1,url:g,error:_,reason:_.message,response:n,context:a,level:y,parent:x,networkDetails:i,stats:r});return}switch(t.live&&l&&(l.getCacheAge&&(t.ageHeader=l.getCacheAge()||0),(!l.getCacheAge||isNaN(t.ageHeader))&&(t.ageHeader=0)),c){case Mc.MANIFEST:case Mc.LEVEL:if(y){if(!u)y=0;else if(u!==o.levels[y]){const _=o.levels.indexOf(u);_>-1&&(y=_)}}o.trigger(Mt.LEVEL_LOADED,{details:t,levelInfo:u||o.levels[0],level:y||0,id:h||0,stats:r,networkDetails:i,deliveryDirectives:p,withoutMultiVariant:c===Mc.MANIFEST,context:a});break;case Mc.AUDIO_TRACK:o.trigger(Mt.AUDIO_TRACK_LOADED,{details:t,track:u,id:h||0,groupId:m||"",stats:r,networkDetails:i,deliveryDirectives:p,context:a});break;case Mc.SUBTITLE_TRACK:o.trigger(Mt.SUBTITLE_TRACK_LOADED,{details:t,track:u,id:h||0,groupId:m||"",stats:r,networkDetails:i,deliveryDirectives:p,context:a});break}}}class KN{static get version(){return wQ}static isMSESupported(){return XGt()}static isSupported(){return uqn()}static getMediaSource(){return zM()}static get Events(){return Mt}static get MetadataSchema(){return nb}static get ErrorTypes(){return xo}static get ErrorDetails(){return er}static get DefaultConfig(){return KN.defaultConfig?KN.defaultConfig:sVn}static set DefaultConfig(t){KN.defaultConfig=t}constructor(t={}){this.config=void 0,this.userConfig=void 0,this.logger=void 0,this._url=null,this.streamController=void 0,this.coreComponents=void 0,this.networkControllers=void 0,this._emitter=new $Qe,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.audioStreamController=void 0,this.subtititleStreamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.interstitialsController=void 0,this.iframeController=void 0,this.gapController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this._sessionId=void 0,this.triggeringException=void 0,this.started=!1;const n=this.logger=M9n(t.debug||!1,"Hls instance",t.loggerId||t.assetPlayerId),r=this.config=rVn(KN.DefaultConfig,t,n);this.userConfig=t,r.progressive&&aVn(r,n);const{streamController:a,abrController:i,bufferController:l,capLevelController:o,errorController:c,fpsController:d,id3TrackController:u,iframeController:h,gapController:m}=r,p=new c(this),g=this.abrController=new i(this),x=new Wzn(this),y=r.interstitialsController,v=y?this.interstitialsController=new y(this,KN):null,_=l?this.bufferController=new l(this,x):null,j=o?this.capLevelController=new o(this):null,C=d?new d(this):null,A=r.cmcdController,M=A?this.cmcdController=new A(this):null,I=new lVn(this),P=r.contentSteeringController,R=P?new P(this):null,O=this.levelController=new iVn(this,R),B=u?new u(this):void 0,U=new oVn(this.config,this.logger),G=this.streamController=new a(this,x,U),H=this.gapController=m?new m(this,x):void 0;j&&j.setStreamController(G);const Y=[I,O,G];v&&Y.splice(1,0,v),R&&Y.splice(1,0,R),this.networkControllers=Y;const se=[g];_&&se.push(_),H&&se.push(H),j&&se.push(j),C&&(C.setStreamController(G),se.push(C)),B&&se.push(B),se.push(x),this.audioTrackController=this.createController(r.audioTrackController,Y);const ee=r.audioStreamController;ee&&Y.push(this.audioStreamController=new ee(this,x,U)),this.subtitleTrackController=this.createController(r.subtitleTrackController,Y);const oe=r.subtitleStreamController;oe&&Y.push(this.subtititleStreamController=new oe(this,x,U)),this.createController(r.timelineController,se),U.emeController=this.emeController=this.createController(r.emeController,se),M&&se.push(M),this.latencyController=this.createController(r.latencyController,se),this.coreComponents=se,this.iframeController=h?new h(this,KN):void 0,Y.push(p);const me=p.onErrorOut;typeof me=="function"&&this.on(Mt.ERROR,me,p),this.on(Mt.MANIFEST_LOADED,I.onManifestLoaded,I)}createController(t,n){if(t){const r=new t(this);return n&&n.push(r),r}return null}on(t,n,r=this){this._emitter.on(t,n,r)}once(t,n,r=this){this._emitter.once(t,n,r)}removeAllListeners(t){this._emitter.removeAllListeners(t)}off(t,n,r=this,a){this._emitter.off(t,n,r,a)}listeners(t){return this._emitter.listeners(t)}emit(t,n,r){return this._emitter.emit(t,n,r)}trigger(t,n){if(this.config.debug)return this.emit(t,t,n);try{return this.emit(t,t,n)}catch(r){if(this.logger.error("An internal error happened while handling event "+t+'. Error message: "'+r.message+'". Here is a stacktrace:',r),!this.triggeringException){this.triggeringException=!0;const a=t===Mt.ERROR;this.trigger(Mt.ERROR,{type:xo.OTHER_ERROR,details:er.INTERNAL_EXCEPTION,fatal:a,event:t,error:r}),this.triggeringException=!1}}return!1}listenerCount(t){return this._emitter.listenerCount(t)}destroy(){this.logger.log("destroy"),this.trigger(Mt.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this._url=null,this.networkControllers.forEach(n=>n.destroy()),this.networkControllers.length=0,this.coreComponents.forEach(n=>n.destroy()),this.coreComponents.length=0,this.iframeController=void 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(Mt.ERROR,{type:xo.OTHER_ERROR,details:er.ATTACH_MEDIA_ERROR,fatal:!0,error:i});return}this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia());const n="media"in t,r=n?t.media:t,a=n?t:{media:r};this._media=r,this.trigger(Mt.MEDIA_ATTACHING,a)}detachMedia(){this.logger.log("detachMedia");const t={};this.trigger(Mt.MEDIA_DETACHING,t),this._media=null,this.trigger(Mt.MEDIA_DETACHED,t)}transferMedia(){var t;this._media=null;const n=((t=this.bufferController)==null?void 0:t.transferMedia())||null,r={transferMedia:n};return this.trigger(Mt.MEDIA_DETACHING,r),this.trigger(Mt.MEDIA_DETACHED,r),n}loadSource(t){var n;this.stopLoad();const r=this.media,a=this._url,i=this._url=CQe.buildAbsoluteURL(self.location.href,t,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${i}`),r&&a&&(a!==i||(n=this.bufferController)!=null&&n.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(r)),this.trigger(Mt.MANIFEST_LOADING,{url:t})}get url(){return this._url}get hasEnoughToStart(){return this.streamController.hasEnoughToStart}get startPosition(){return this.streamController.startPositionValue}startLoad(t=-1,n){this.logger.log(`startLoad(${t+(n?", ":"")})`),this.started=!0,this.resumeBuffering();for(let r=0;r{t.resumeBuffering&&t.resumeBuffering()}))}pauseBuffering(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach(t=>{t.pauseBuffering&&t.pauseBuffering()}))}get inFlightFragments(){const t={[Ji.MAIN]:this.streamController.inFlightFrag};return this.audioStreamController&&(t[Ji.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(t[Ji.SUBTITLE]=this.subtititleStreamController.inFlightFrag),t}swapAudioCodec(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){this.logger.log("recoverMediaError");const t=this._media,n=this.started,r=t==null?void 0:t.currentTime;this.detachMedia(),t&&(this.attachMedia(t),n&&(r?this.startLoad(r):this.config.autoStartLoad||this.startLoad()))}removeLevel(t){this.levelController.removeLevel(t)}get sessionId(){let t=this._sessionId;return t||(t=this._sessionId=hHt()),t}get levels(){const t=this.levelController.levels;return t||[]}get latestLevelDetails(){return this.streamController.getLevelDetails()||null}get loadLevelObj(){return this.levelController.loadLevelObj}get currentLevel(){return this.streamController.currentLevel}set currentLevel(t){this.logger.log(`set currentLevel:${t}`),this.levelController.manualLevel=t,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(t){this.logger.log(`set nextLevel:${t}`),this.levelController.manualLevel=t,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(t){this.logger.log(`set loadLevel:${t}`),this.levelController.manualLevel=t}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(t){this.levelController.nextLoadLevel=t}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(t){this.logger.log(`set firstLevel:${t}`),this.levelController.firstLevel=t}get startLevel(){const t=this.levelController.startLevel;return t===-1&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:t}set startLevel(t){this.logger.log(`set startLevel:${t}`),t!==-1&&(t=Math.max(t,this.minAutoLevel)),this.levelController.startLevel=t}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(t){const n=this.capLevelController,r=!!t;n&&r!==this.config.capLevelToPlayerSize&&(r?n.startCapping():(n.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){Pzn(t)&&this._maxHdcpLevel!==t&&(this._maxHdcpLevel=t,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return this.levelController.manualLevel===-1}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){const{levels:t,config:{minAutoBitrate:n}}=this;if(!t)return 0;const r=t.length;for(let a=0;a=n)return a;return 0}get maxAutoLevel(){const{levels:t,autoLevelCapping:n,maxHdcpLevel:r}=this;let a;if(n===-1&&t!=null&&t.length?a=t.length-1:a=n,r)for(let i=a;i--;){const l=t[i].attrs["HDCP-LEVEL"];if(l&&l<=r)return i}return a}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(t){this.abrController.nextAutoLevel=t}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}get audioForwardBufferInfo(){var t;return((t=this.audioStreamController)==null?void 0:t.getFwdBufferInfo())||null}get maxBufferLength(){return this.streamController.maxBufferLength}setAudioOption(t){var n;return((n=this.audioTrackController)==null?void 0:n.setAudioOption(t))||null}setSubtitleOption(t){var n;return((n=this.subtitleTrackController)==null?void 0:n.setSubtitleOption(t))||null}get allAudioTracks(){const t=this.audioTrackController;return t?t.allAudioTracks:[]}get audioTracks(){const t=this.audioTrackController;return t?t.audioTracks:[]}get audioTrack(){const t=this.audioTrackController;return t?t.audioTrack:-1}set audioTrack(t){const n=this.audioTrackController;n&&(n.audioTrack=t)}get nextAudioTrack(){var t,n;return(t=(n=this.audioStreamController)==null?void 0:n.nextAudioTrack)!=null?t:-1}set nextAudioTrack(t){const{audioTrackController:n}=this;n&&(n.nextAudioTrack=t)}get allSubtitleTracks(){const t=this.subtitleTrackController;return t?t.allSubtitleTracks:[]}get subtitleTracks(){const t=this.subtitleTrackController;return t?t.subtitleTracks:[]}get subtitleTrack(){const t=this.subtitleTrackController;return t?t.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(t){const n=this.subtitleTrackController;n&&(n.subtitleTrack=t)}get subtitleDisplay(){const t=this.subtitleTrackController;return t?t.subtitleDisplay:!1}set subtitleDisplay(t){const n=this.subtitleTrackController;n&&(n.subtitleDisplay=t)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(t){this.config.lowLatencyMode=t}get liveSyncPosition(){var t,n;return(t=(n=this.latencyController)==null?void 0:n.liveSyncPosition)!=null?t:null}get latency(){var t;return((t=this.latencyController)==null?void 0:t.latency)||0}get maxLatency(){var t;return((t=this.latencyController)==null?void 0:t.maxLatency)||0}get targetLatency(){var t;return((t=this.latencyController)==null?void 0:t.targetLatency)||null}set targetLatency(t){this.latencyController&&(this.latencyController.targetLatency=t)}get drift(){var t;return((t=this.latencyController)==null?void 0:t.drift)||null}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(){return this.interstitialsController?this.interstitialsController.interstitialsManager:null}get iframeVariants(){const t=this.levelController.iframeVariants;return t||[]}createIFramePlayer(t){return this._url&&this.iframeController?this.iframeController.createIFramePlayer(t):null}createImageIFramePlayer(t){return this._url&&this.iframeController?this.iframeController.createImageIFramePlayer(t):null}getMediaDecodingInfo(t,n=this.allAudioTracks){const r=RHt(n);return PHt(t,r,navigator.mediaCapabilities)}}KN.defaultConfig=void 0;const cVn=/(?:player\.mediadelivery\.net|iframe\.mediadelivery\.net|iframe\.n\.net|video\.bunnycdn\.com|[a-z0-9-]+\.b-cdn\.net)/i;function Az(s){return!!s&&cVn.test(s)&&!/\.mp4($|\?)/i.test(s)}function dVn(s){const t=s.match(/\/(?:play|embed)\/(\d+)\/([a-z0-9-]+)/i);return t?{libraryId:t[1],videoId:t[2]}:null}function uVn(s,t){if(!s)return null;const n=dVn(s);if(n){const r=new URLSearchParams({autoplay:t!=null&&t.autoplay?"true":"false",muted:t!=null&&t.muted?"true":"false",loop:t!=null&&t.loop?"true":"false",preload:"true",responsive:"true",playsinline:"true"});return`https://player.mediadelivery.net/embed/${n.libraryId}/${n.videoId}?${r.toString()}`}return/player\.mediadelivery\.net\/embed\//i.test(s)?s:/iframe\.mediadelivery\.net\/(?:play|embed)\//i.test(s)?s.replace("iframe.mediadelivery.net/play/","player.mediadelivery.net/embed/").replace("iframe.mediadelivery.net/embed/","player.mediadelivery.net/embed/"):s}function hVn(s){const t=s.match(/https:\/\/[^"']+playlist\.m3u8[^"']*/i);return t?t[0].replace(/&/g,"&").replace(/\u0026/g,"&"):null}const Cqe=k.forwardRef(function({sourceUrl:t,thumbnailUrl:n,autoPlay:r,muted:a,loop:i,playsInline:l=!0,...o},c){const d=k.useRef(null),[u,h]=k.useState(null),m=k.useMemo(()=>uVn(t,{autoplay:!!r,muted:!!a,loop:!!i}),[t,r,a,i]);k.useEffect(()=>{let g=!1;if(!t){h(null);return}if(!Az(t)){h(t);return}if(!m){h(null);return}return h(null),fetch(m).then(async x=>{if(!x.ok)throw new Error(`Failed to load Bunny embed (${x.status})`);const y=await x.text();return hVn(y)}).then(x=>{g||h(x)}).catch(()=>{g||h(null)}),()=>{g=!0}},[m,t]),k.useEffect(()=>{const g=d.current;if(!g||!u)return;let x=null;const y=()=>{if(!r)return;const _=g.play();_&&_.catch(()=>{})};if(g.muted=!!a,g.loop=!!i,u.endsWith(".m3u8")){if(g.canPlayType("application/vnd.apple.mpegurl")){g.src=u;const _=()=>y();return g.addEventListener("loadedmetadata",_),()=>{g.removeEventListener("loadedmetadata",_),g.removeAttribute("src"),g.load()}}return KN.isSupported()?(x=new KN({enableWorker:!0,lowLatencyMode:!0}),x.loadSource(u),x.attachMedia(g),x.on(KN.Events.MANIFEST_PARSED,y),()=>{x==null||x.destroy(),g.removeAttribute("src"),g.load()}):void 0}g.src=u;const v=()=>y();return g.addEventListener("loadedmetadata",v),()=>{g.removeEventListener("loadedmetadata",v),g.removeAttribute("src"),g.load()}},[r,i,a,u]),k.useEffect(()=>{const g=d.current;if(g){if(g.muted=!!a,g.loop=!!i,r&&u){const x=g.play();x&&x.catch(()=>{});return}g.pause()}},[r,i,a,u]);const p=g=>{if(d.current=g,typeof c=="function"){c(g);return}c&&(c.current=g)};return e.jsx("video",{ref:p,poster:n||void 0,autoPlay:r,muted:a,loop:i,playsInline:l,preload:"metadata",...o})}),mVn={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 fVn(){try{let s=localStorage.getItem("vg_visitor_token");return s||(s=crypto.randomUUID(),localStorage.setItem("vg_visitor_token",s)),s}catch{return null}}function vwt(s,t){return!s||s.length===0?!1:s.some(n=>n?n===t?!0:n.endsWith("*")?t.startsWith(n.slice(0,-1)):t.startsWith(n):!1)}function nJe({config:s,appSlug:t="video_greeter",preview:n=!1,embedded:r=!1}){const[a,i]=k.useState(!1),[l,o]=k.useState(!1),[c,d]=k.useState(!0),[u,h]=k.useState(!1),[m,p]=k.useState("portrait"),[g,x]=k.useState(!1),[y,v]=k.useState(!1),[_,j]=k.useState({name:"",email:"",phone:""}),[C,A]=k.useState(()=>({width:typeof window<"u"?window.innerWidth:1280,height:typeof window<"u"?window.innerHeight:720})),M=k.useRef(null),I=k.useRef(null),P=k.useRef(!1),R=async(ke,Fe)=>{if(!n)try{await V.from("widget_events").insert({user_id:s.user_id,app_slug:t,event_type:ke,visitor_token:fVn(),page_url:typeof window<"u"?window.location.href:null,metadata:Fe||{}})}catch{}};k.useEffect(()=>{if(u)return;const ke=typeof window<"u"?window.location.pathname:"/",Fe=s.targeting||{mode:"all"};if(Fe.mode==="include"&&!vwt(Fe.include,ke)||Fe.mode==="exclude"&&vwt(Fe.exclude,ke))return;const Oe=s.trigger||{type:"immediate"};if(Oe.type==="immediate"||n){i(!0);return}if(Oe.type==="delay"){const Ge=(Oe.value||3)*1e3,yt=setTimeout(()=>i(!0),Ge);return()=>clearTimeout(yt)}if(Oe.type==="scroll"){const Ge=(Oe.value||25)/100,yt=()=>{(window.scrollY+window.innerHeight)/document.documentElement.scrollHeight>=Ge&&(i(!0),window.removeEventListener("scroll",yt))};return window.addEventListener("scroll",yt,{passive:!0}),()=>window.removeEventListener("scroll",yt)}if(Oe.type==="exit_intent"){const Ge=yt=>{yt.clientY<=0&&i(!0)};return document.addEventListener("mouseleave",Ge),()=>document.removeEventListener("mouseleave",Ge)}},[u,s.targeting,s.trigger,n]),k.useEffect(()=>{a&&!P.current&&(P.current=!0,R("impression"))},[a]),k.useEffect(()=>{if(l&&I.current&&!Az(s.video_url)){I.current.currentTime=0,I.current.muted=!1,d(!1);const ke=I.current.play();ke&&ke.catch(()=>{})}else l&&Az(s.video_url)&&d(!1)},[l,s.video_url]),k.useEffect(()=>{if(!s.thumbnail_url)return;let ke=!1;const Fe=new Image;return Fe.onload=()=>{ke||p(Fe.naturalWidth>Fe.naturalHeight?"landscape":"portrait")},Fe.src=s.thumbnail_url,()=>{ke=!0}},[s.thumbnail_url]),k.useEffect(()=>{const ke=()=>{A({width:window.innerWidth,height:window.innerHeight})};return ke(),window.addEventListener("resize",ke),()=>window.removeEventListener("resize",ke)},[]);const O=()=>{o(!0),R("expand")},B=ke=>{ke.stopPropagation(),h(!0),o(!1)},U=ke=>{R("cta_click",{cta_id:ke.id,label:ke.label,url:ke.url})},G=async ke=>{if(ke.preventDefault(),n){x(!0);return}if(!(!_.email||!_.name)){v(!0);try{const{error:Fe}=await V.functions.invoke("submit-widget-lead",{body:{user_id:s.user_id,app_slug:t,name:_.name,email:_.email,phone:_.phone||void 0,page_url:window.location.href}});if(Fe)throw Fe;R("lead_capture",{email:_.email}),x(!0)}catch(Fe){console.error("lead submit failed",Fe)}finally{v(!1)}}};if(!a||u||!s.video_url&&!s.video_embed_url)return null;const H=mVn[m][s.size||"md"],Y=r?"absolute left-2 bottom-2":n?s.position==="bottom-right"?"absolute right-4 bottom-4":"absolute left-4 bottom-4":s.position==="bottom-right"?"fixed right-4 bottom-4 md:right-6 md:bottom-6":"fixed left-4 bottom-4 md:left-6 md:bottom-6",se=s.shape==="circle"?"rounded-full":"rounded-2xl",ee=n?m==="landscape"?"w-[280px]":"w-[220px]":m==="landscape"?"w-[360px] sm:w-[420px]":"w-[300px] sm:w-[340px]",oe=m==="landscape"?"aspect-video":"aspect-[9/16]",me=s.agent||{},Q=s.lead_form_fields||["name","email","phone"],te=!!(s.show_socials&&(me.instagram_url||me.facebook_url||me.linkedin_url)),le=108+(s.ctas||[]).length*48+(s.lead_form_enabled&&!g?72+Q.length*42:0)+(g?40:0)+(te?34:0),fe=Math.max(300,C.height-32),_e=Math.max(220,C.width-32),ve=Math.max(150,fe-le),he=Math.floor(m==="landscape"?ve*(16/9):ve*(9/16)),Se=m==="landscape"?Math.max(220,Math.min(420,_e,he)):Math.max(180,Math.min(340,_e,he)),Te=r?"bg-white rounded-2xl shadow-2xl overflow-hidden border border-black/10 animate-in fade-in zoom-in-95 duration-300 flex flex-col":`${ee} max-h-[calc(100dvh-2rem)] bg-white rounded-2xl shadow-2xl overflow-hidden border border-black/10 animate-in fade-in zoom-in-95 duration-300 flex flex-col`,Ie=r?{width:`${Se}px`,maxHeight:"calc(100dvh - 2rem)"}:void 0,Ue=r?"p-3 space-y-2.5":"p-4 space-y-3",Be=r?"w-9 h-9 rounded-full object-cover":"w-10 h-10 rounded-full object-cover",je=r?"font-bold text-[15px] text-gray-900 leading-tight":"font-bold text-gray-900 leading-tight",Ye=r?"text-[11px] text-gray-500 mt-0.5":"text-xs text-gray-500 mt-0.5",Ee=r?"w-full px-3 py-1.5 text-sm rounded-lg border border-gray-200 focus:border-gray-900 focus:outline-none bg-white text-gray-900 placeholder:text-gray-400":"w-full px-3 py-2 text-sm rounded-lg border border-gray-200 focus:border-gray-900 focus:outline-none bg-white text-gray-900 placeholder:text-gray-400",Re=r?"w-full flex items-center justify-center gap-2 px-3 py-2 bg-gray-900 text-white rounded-xl text-sm font-semibold hover:bg-black transition-colors disabled:opacity-60":"w-full flex items-center justify-center gap-2 px-3 py-2.5 bg-gray-900 text-white rounded-xl text-sm font-semibold hover:bg-black transition-colors disabled:opacity-60";return e.jsx("div",{"data-vg-widget":!0,"data-expanded":l?"true":"false",className:`${Y} z-[70]`,style:{paddingBottom:"env(safe-area-inset-bottom)"},children:l?e.jsxs("div",{className:Te,style:Ie,children:[e.jsxs("div",{className:`relative bg-black ${oe}`,children:[Az(s.video_url)?e.jsx(Cqe,{ref:I,sourceUrl:s.video_url,thumbnailUrl:s.thumbnail_url,autoPlay:!0,muted:c,loop:!1,className:"w-full h-full object-cover",onLoadedMetadata:ke=>{const{videoWidth:Fe,videoHeight:Oe}=ke.currentTarget;Fe&&Oe&&p(Fe>Oe?"landscape":"portrait")},onEnded:()=>R("watch_complete")},`expanded-${s.video_url}-${s.thumbnail_url||"no-thumb"}-${l?"on":"off"}`):e.jsx("video",{ref:I,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:()=>R("watch_complete"),onLoadedMetadata:ke=>{const{videoWidth:Fe,videoHeight:Oe}=ke.currentTarget;Fe&&Oe&&p(Fe>Oe?"landscape":"portrait")}}),e.jsx("button",{onClick:()=>{I.current&&(I.current.muted=!I.current.muted,d(I.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(lY,{className:"w-4 h-4"}):e.jsx(oY,{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(mr,{className:"w-4 h-4"})})]}),e.jsxs("div",{className:Ue,children:[e.jsxs("div",{className:"flex items-center gap-3",children:[me.avatar_url&&e.jsx("img",{src:me.avatar_url,alt:me.name||"",className:Be}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:je,children:s.greeting_title||"Glad you're here!"}),s.greeting_subtitle&&e.jsx("p",{className:Ye,children:s.greeting_subtitle})]})]}),(s.ctas||[]).length>0&&e.jsx("div",{className:"space-y-2",children:(s.ctas||[]).map(ke=>{var Fe;return e.jsxs("a",{href:ke.url,target:(Fe=ke.url)!=null&&Fe.startsWith("http")?"_blank":void 0,rel:"noopener noreferrer",onClick:()=>U(ke),className:`flex items-center justify-between gap-2 ${r?"px-3 py-2":"px-3.5 py-2.5"} rounded-xl text-sm font-semibold transition-colors ${ke.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:ke.label}),e.jsx(Ir,{className:"w-3.5 h-3.5 opacity-60"})]},ke.id)})}),s.lead_form_enabled&&!g&&e.jsxs("form",{onSubmit:G,className:"space-y-2 pt-1",children:[Q.includes("name")&&e.jsx("input",{type:"text",placeholder:"Name",required:!0,value:_.name,onChange:ke=>j({..._,name:ke.target.value}),className:Ee}),Q.includes("email")&&e.jsx("input",{type:"email",placeholder:"Email",required:!0,value:_.email,onChange:ke=>j({..._,email:ke.target.value}),className:Ee}),Q.includes("phone")&&e.jsx("input",{type:"tel",placeholder:"Phone (optional)",value:_.phone,onChange:ke=>j({..._,phone:ke.target.value}),className:Ee}),e.jsxs("button",{type:"submit",disabled:y,className:Re,children:[e.jsx(Wr,{className:"w-3.5 h-3.5"}),y?"Sending...":"Send"]})]}),g&&e.jsx("p",{className:"text-sm text-emerald-600 font-medium text-center py-2",children:"Thanks! I'll be in touch shortly."}),s.show_socials&&(me.instagram_url||me.facebook_url||me.linkedin_url)&&e.jsxs("div",{className:"flex items-center justify-center gap-3 pt-2 border-t border-gray-100",children:[me.instagram_url&&e.jsx("a",{href:me.instagram_url,target:"_blank",rel:"noopener noreferrer",className:"text-gray-400 hover:text-gray-900",onClick:()=>R("cta_click",{social:"instagram"}),children:e.jsx(Sf,{className:"w-4 h-4"})}),me.facebook_url&&e.jsx("a",{href:me.facebook_url,target:"_blank",rel:"noopener noreferrer",className:"text-gray-400 hover:text-gray-900",onClick:()=>R("cta_click",{social:"facebook"}),children:e.jsx(ax,{className:"w-4 h-4"})}),me.linkedin_url&&e.jsx("a",{href:me.linkedin_url,target:"_blank",rel:"noopener noreferrer",className:"text-gray-400 hover:text-gray-900",onClick:()=>R("cta_click",{social:"linkedin"}),children:e.jsx(dv,{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:O,className:`relative ${se} overflow-hidden shadow-2xl ring-2 ring-white/40 hover:ring-white/80 hover:scale-105 transition-all bg-black`,style:{width:H.w,height:H.h},"aria-label":"Play video greeting",children:[Az(s.video_url)?e.jsx(Cqe,{ref:M,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:ke=>{const{videoWidth:Fe,videoHeight:Oe}=ke.currentTarget;Fe&&Oe&&p(Fe>Oe?"landscape":"portrait")}},`collapsed-${s.video_url}-${s.thumbnail_url||"no-thumb"}`):e.jsx("video",{ref:M,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:ke=>{const{videoWidth:Fe,videoHeight:Oe}=ke.currentTarget;Fe&&Oe&&p(Fe>Oe?"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:B,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(mr,{className:"w-3.5 h-3.5"})})]})})}function rJe({slug:s}){const[t,n]=k.useState(null);return k.useEffect(()=>{if(!s)return;let r=!1;return(async()=>{const{data:a,error:i}=await V.rpc("get_public_video_greeter_config",{_slug:s});!r&&!i&&a&&n(a)})(),()=>{r=!0}},[s]),t?e.jsx(nJe,{config:t}):null}const oWt="eip_last_shown",bwt="eip_visitor_token";function pVn(){try{let s=localStorage.getItem(bwt);return s||(s=crypto.randomUUID(),localStorage.setItem(bwt,s)),s}catch{return}}function gVn(s){try{const t=Number(localStorage.getItem(oWt)||0);return t?Date.now()-t>s*24*60*60*1e3:!0}catch{return!0}}function xVn(s){if(!s||s.mode==="all")return!0;const t=window.location.pathname,r=(s.mode==="include"?s.include||[]:s.exclude||[]).some(a=>t.startsWith(a));return s.mode==="include"?r:!r}function lWt({config:s,preview:t=!1,forceOpen:n=!1}){const[r,a]=k.useState(n),[i,l]=k.useState(!1),[o,c]=k.useState(!1),[d,u]=k.useState({name:"",email:"",phone:""}),h=k.useRef(!1),m=k.useRef(!1),p=async(M,I={})=>{if(!t)try{await V.from("widget_events").insert({user_id:s.user_id,app_slug:"exit_intent",event_type:M,visitor_token:pVn(),page_url:window.location.href,metadata:I})}catch{}};k.useEffect(()=>{if(t||!xVn(s.targeting)||!gVn(s.frequency_days))return;const M=/Mobi|Android/i.test(navigator.userAgent),I={low:5,medium:15,high:30}[s.trigger_sensitivity]||15,P=U=>{if(!h.current){h.current=!0,a(!0);try{localStorage.setItem(oWt,String(Date.now()))}catch{}p("impression",{reason:U})}},R=U=>{U.clientY<=I&&P("mouse_leave")},O=()=>{s.enable_mobile_back&&M&&P("back_button")};if(s.enable_mobile_back&&M){try{window.history.pushState({eip:!0},"")}catch{}window.addEventListener("popstate",O)}else document.addEventListener("mouseleave",R);let B;return s.enable_time_fallback&&(B=window.setTimeout(()=>P("time_fallback"),Math.max(5,s.time_fallback_seconds)*1e3)),()=>{document.removeEventListener("mouseleave",R),window.removeEventListener("popstate",O),B&&window.clearTimeout(B)}},[s,t]),k.useEffect(()=>{r&&!m.current&&!t&&!h.current&&(m.current=!0)},[r,t]);const g=()=>{a(!1),t||p("close")},x=async M=>{if(M.preventDefault(),t){l(!0);return}if(!(!d.email||!d.name)){c(!0);try{const{error:I}=await V.functions.invoke("submit-widget-lead",{body:{user_id:s.user_id,app_slug:"exit_intent",name:d.name,email:d.email,phone:d.phone||void 0,page_url:window.location.href}});if(I)throw I;p("lead_capture",{email:d.email}),l(!0),s.cta_url&&setTimeout(()=>{window.location.href=s.cta_url},1200)}catch(I){console.error("exit intent submit failed",I)}finally{c(!1)}}};if(!r)return null;const y=s.form_fields||["name","email"],v=s.agent||{},_=[v.first_name,v.last_name].filter(Boolean).join(" "),j=s.use_agent_photo&&v.avatar_url||s.image_url,C=s.theme_color||"#f97316",A=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:A,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:M=>M.stopPropagation(),children:[e.jsx("div",{className:"h-2 w-full",style:{background:`linear-gradient(90deg, ${C}, ${R8e(C,-25)})`}}),e.jsx("button",{onClick:g,className:"absolute top-3 right-3 z-10 w-8 h-8 rounded-full bg-background/80 backdrop-blur hover:bg-background flex items-center justify-center text-muted-foreground hover:text-foreground transition","aria-label":"Close",children:e.jsx(mr,{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:[j&&e.jsx("img",{src:j,alt:_||"Agent",className:"w-14 h-14 rounded-full object-cover ring-2 shadow-md",style:{boxShadow:`0 0 0 2px ${C}33`,"--tw-ring-color":C}}),e.jsxs("div",{className:"inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-semibold",style:{background:`${C}1A`,color:C},children:[e.jsx(kn,{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:`${C}10`,color:C},children:[e.jsx("div",{className:"text-3xl",children:"🎉"}),e.jsx("p",{className:"text-sm font-medium",style:{color:C},children:s.success_message})]}):s.form_enabled?e.jsxs("form",{onSubmit:x,className:"space-y-2.5",children:[y.includes("name")&&e.jsx("input",{type:"text",placeholder:"Your name",value:d.name,onChange:M=>u({...d,name:M.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":C},required:!0}),y.includes("email")&&e.jsx("input",{type:"email",placeholder:"you@email.com",value:d.email,onChange:M=>u({...d,email:M.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":C},required:!0}),y.includes("phone")&&e.jsx("input",{type:"tel",placeholder:"Phone (optional)",value:d.phone,onChange:M=>u({...d,phone:M.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":C}}),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, ${C}, ${R8e(C,-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:()=>p("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, ${C}, ${R8e(C,-20)})`},children:s.cta_label}),_&&e.jsxs("p",{className:"text-[11px] text-center text-muted-foreground pt-1",children:["Sent personally by ",_]})]})]})})}function R8e(s,t){try{const n=parseInt(s.slice(1),16),r=t<0?0:255,a=Math.abs(t)/100,i=n>>16,l=n>>8&255,o=n&255,c=Math.round((r-i)*a)+i,d=Math.round((r-l)*a)+l,u=Math.round((r-o)*a)+o;return"#"+(16777216+(c<<16)+(d<<8)+u).toString(16).slice(1)}catch{return s}}function aJe({slug:s}){const[t,n]=k.useState(null);return k.useEffect(()=>{if(!s)return;let r=!1;return(async()=>{const{data:a,error:i}=await V.rpc("get_public_exit_intent_config",{_slug:s});!r&&!i&&a&&n(a)})(),()=>{r=!0}},[s]),t?e.jsx(lWt,{config:t}):null}const _wt="lm_dismissed",wwt="lm_visitor_token";function yVn(){try{let s=localStorage.getItem(wwt);return s||(s=crypto.randomUUID(),localStorage.setItem(wwt,s)),s}catch{return}}function vVn(s){if(!s||s.mode==="all")return!0;const t=window.location.pathname,r=(s.mode==="include"?s.include||[]:s.exclude||[]).some(a=>t.startsWith(a));return s.mode==="include"?r:!r}function iJe({config:s,preview:t=!1}){const[n,r]=k.useState(!1),[a,i]=k.useState(!1),[l,o]=k.useState(!1),[c,d]=k.useState(!1),[u,h]=k.useState({name:"",email:"",phone:""}),m=k.useRef(!1),p=async(j,C={})=>{if(!t)try{await V.from("widget_events").insert({user_id:s.user_id,app_slug:"lead_magnet",event_type:j,visitor_token:yVn(),page_url:window.location.href,metadata:C})}catch{}};k.useEffect(()=>{if(t){r(!0);return}if(!vVn(s.targeting))return;try{if(sessionStorage.getItem(_wt))return}catch{}const j=()=>{m.current||(m.current=!0,r(!0),p("impression"))};if(s.trigger_type==="immediate")j();else if(s.trigger_type==="delay"){const C=window.setTimeout(j,Math.max(0,s.trigger_value)*1e3);return()=>window.clearTimeout(C)}else if(s.trigger_type==="scroll"){const C=()=>{(window.scrollY+window.innerHeight)/document.documentElement.scrollHeight*100>=(s.trigger_value||30)&&j()};return window.addEventListener("scroll",C,{passive:!0}),()=>window.removeEventListener("scroll",C)}},[s,t]);const g=()=>{r(!1);try{sessionStorage.setItem(_wt,"1")}catch{}t||p("close")},x=async j=>{if(j.preventDefault(),t){o(!0);return}if(!(!u.email||!u.name)){d(!0);try{const{error:C}=await V.functions.invoke("submit-widget-lead",{body:{user_id:s.user_id,app_slug:"lead_magnet",name:u.name,email:u.email,phone:u.phone||void 0,page_url:window.location.href}});if(C)throw C;p("lead_capture",{email:u.email}),o(!0),(s.delivery_method==="instant"||s.delivery_method==="both")&&s.download_url&&setTimeout(()=>{const A=document.createElement("a");A.href=s.download_url,A.target="_blank",A.rel="noopener",A.download="",document.body.appendChild(A),A.click(),A.remove()},600)}catch(C){console.error("lead magnet submit failed",C)}finally{d(!1)}}};if(!n)return null;const y=s.theme_color||"#2563eb",v=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, ${y}, ${JG(y,-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(Zo,{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),p("expand")},className:"px-4 py-2 rounded-lg text-sm font-semibold bg-white shrink-0 hover:bg-white/95 transition",style:{color:y},children:s.download_label}),e.jsx("button",{onClick:g,className:"text-white/80 hover:text-white","aria-label":"Close",children:e.jsx(mr,{className:"w-4 h-4"})})]})}),a&&_()]});if(!a)return e.jsxs(e.Fragment,{children:[e.jsxs("button",{onClick:()=>{i(!0),p("expand")},className:`${v} 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, ${y}, ${JG(y,-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(wg,{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:j=>{j.stopPropagation(),g()},className:"ml-1 w-6 h-6 rounded-full bg-white/20 hover:bg-white/30 flex items-center justify-center text-white","aria-label":"Close",children:e.jsx(mr,{className:"w-3 h-3"})})]}),a&&_()]});return _();function _(){const j=s.form_fields||["name","email"],C=s.agent||{},A=[C.first_name,C.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:M=>M.stopPropagation(),children:[e.jsxs("div",{className:"relative h-44 sm:h-52 overflow-hidden",style:{background:`linear-gradient(135deg, ${y}, ${JG(y,-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(ea,{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:y},children:[e.jsx(Zo,{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(mr,{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:`${y}10`},children:[e.jsx(ji,{className:"w-8 h-8 mx-auto",style:{color:y}}),e.jsx("p",{className:"text-sm font-medium",style:{color:y},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:y},children:"Click here if download didn't start"})]}):s.form_enabled?e.jsxs("form",{onSubmit:x,className:"space-y-2.5",children:[j.includes("name")&&e.jsx("input",{type:"text",placeholder:"Your name",value:u.name,onChange:M=>h({...u,name:M.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":y},required:!0}),j.includes("email")&&e.jsx("input",{type:"email",placeholder:"you@email.com",value:u.email,onChange:M=>h({...u,email:M.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":y},required:!0}),j.includes("phone")&&e.jsx("input",{type:"tel",placeholder:"Phone (optional)",value:u.phone,onChange:M=>h({...u,phone:M.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":y}}),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, ${y}, ${JG(y,-20)})`},children:[e.jsx(ji,{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:()=>p("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, ${y}, ${JG(y,-20)})`},children:s.download_label}),A&&e.jsxs("p",{className:"text-[11px] text-center text-muted-foreground",children:["Curated by ",A]})]})]})})}}function JG(s,t){try{const n=parseInt(s.slice(1),16),r=t<0?0:255,a=Math.abs(t)/100,i=n>>16,l=n>>8&255,o=n&255,c=Math.round((r-i)*a)+i,d=Math.round((r-l)*a)+l,u=Math.round((r-o)*a)+o;return"#"+(16777216+(c<<16)+(d<<8)+u).toString(16).slice(1)}catch{return s}}function oJe({slug:s}){const[t,n]=k.useState(null);return k.useEffect(()=>{if(!s)return;let r=!1;return(async()=>{const{data:a,error:i}=await V.rpc("get_public_lead_magnet_config",{_slug:s});!r&&!i&&a&&n(a)})(),()=>{r=!0}},[s]),t?e.jsx(iJe,{config:t}):null}const cWt=` id, slug, property_address, city, state, neighborhood, price, property_type, status, bedrooms, bathrooms, square_footage, lot_size, year_built, description, video_link, mls_link, co_agent_name, co_agent_brokerage, co_agent_phone, co_agent_email, co_agent_photo_url, photos:listing_photos(id, photo_url, is_primary, sort_order) `;function dWt(s){return pt({queryKey:["lead-site-exchange-listings",s],enabled:!!s,staleTime:5*60*1e3,queryFn:async()=>{const{data:t,error:n}=await V.from("listings").select(cWt).eq("agent_id",s).eq("show_on_lead_site",!0).eq("is_approved",!0).order("created_at",{ascending:!1});if(n)throw n;return t||[]}})}function VJn(s,t){return pt({queryKey:["lead-site-exchange-listing",s,t],enabled:!!s&&!!t,queryFn:async()=>{const n=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(t);let r=V.from("listings").select(cWt).eq("agent_id",s).eq("show_on_lead_site",!0).eq("is_approved",!0);r=n?r.eq("id",t):r.eq("slug",t);const{data:a,error:i}=await r.maybeSingle();if(i)throw i;return a??null}})}function HJn(s){var t;return(t=s==null?void 0:s.photos)!=null&&t.length?[...s.photos].sort((n,r)=>Number(r.is_primary)-Number(n.is_primary)||(n.sort_order??0)-(r.sort_order??0)).map(n=>n.photo_url):[]}function GJn(s){return s?`$${s.toLocaleString()}`:"Price upon request"}function bVn({children:s,siteConfig:t}){var he,Se,Te,Ie,Ue,Be,je,Ye,Ee;const n=Tu(),r=Jn(),[a,i]=k.useState(!1),[l,o]=k.useState(!1),[c,d]=k.useState(!1),[u,h]=k.useState([]),[m,p]=k.useState([]),[g,x]=k.useState(null),y=k.useRef(null),v=k.useRef(null),{user:_,profile:j,signOut:C}=VTe();kQe(t,_==null?void 0:_.id),SQe(t,_==null?void 0:_.id);const A=((he=t.agent)==null?void 0:he.full_name)||"Agent",M=t.siteTitle||`${A} Real Estate`,I=n.pathname==="/search",P=n.pathname==="/",R=t.leadRegistrationMode!=="disabled";k.useEffect(()=>{(async()=>{const{data:ke}=await V.from("lead_site_city_pages").select("city_name, city_slug").eq("site_id",t.id).eq("is_published",!0).order("sort_order",{ascending:!0});h(ke||[])})()},[t.id]),k.useEffect(()=>{(async()=>{const{data:ke}=await V.from("lead_site_menu_items").select("*").eq("site_id",t.id).eq("is_visible",!0).order("sort_order",{ascending:!0});p(ke||[])})()},[t.id]),k.useEffect(()=>{const Re=ke=>{y.current&&!y.current.contains(ke.target)&&d(!1),v.current&&!v.current.contains(ke.target)&&x(null)};return document.addEventListener("mousedown",Re),()=>document.removeEventListener("mousedown",Re)},[]);const O=_Qe(t),B=t==null?void 0:t.bookingUrl,{data:U}=dWt(O?t.agentId:null),G=((U==null?void 0:U.length)??0)>0,H=O?m.filter(Re=>{const ke=String(Re.target_url||"").toLowerCase(),Fe=String(Re.label||"").toLowerCase();return ke!=="/search"&&!ke.startsWith("/search?")&&!Fe.includes("search")}):m,Y=O&&G&&H.length>0&&!H.some(Re=>String(Re.target_url||"").toLowerCase().startsWith("/listings"))?[...H,{id:"__my-listings",label:"My Listings",target_url:"/listings",parent_id:null,is_visible:!0}]:H,se=Y.length>0,ee=[{to:"/",label:"Home"},...O?[]:[{to:"/search",label:"Search"}],...O&&G?[{to:"/listings",label:"My Listings"}]:[],{to:"/sell",label:"Sell"},{to:"/blog",label:"Blog"},{to:"/community",label:"Community"},{to:"/about",label:"About"},{to:"/contact",label:"Contact"}],oe=se?[]:ee,me=Y.filter(Re=>!Re.parent_id),Q=Re=>Y.filter(ke=>ke.parent_id===Re),te=P?"bg-transparent text-white":"bg-white/95 backdrop-blur text-gray-900 border-b border-gray-100 shadow-sm",le=t.siteTitle||`${A} - Real Estate`,fe=t.siteTagline||`Browse homes and listings with ${A}`,_e=t.ogImageUrl||((Se=t.agent)==null?void 0:Se.avatar_url)||"",ve=`https://${t.subdomainSlug||""}.thelocalmove.com`;return e.jsxs("div",{className:`flex flex-col ${I?"h-screen overflow-hidden":"min-h-screen"} bg-white`,children:[e.jsx(jQe,{siteConfig:t,pagePath:n.pathname}),e.jsx(NQe,{siteConfig:t}),e.jsxs(Sc,{children:[e.jsx("title",{children:le}),e.jsx("meta",{name:"description",content:fe}),e.jsx("meta",{property:"og:title",content:le}),e.jsx("meta",{property:"og:description",content:fe}),e.jsx("meta",{property:"og:type",content:"website"}),e.jsx("meta",{property:"og:url",content:ve+n.pathname}),_e&&e.jsx("meta",{property:"og:image",content:_e}),e.jsx("meta",{name:"twitter:card",content:"summary_large_image"}),e.jsx("meta",{name:"twitter:title",content:le}),e.jsx("meta",{name:"twitter:description",content:fe}),_e&&e.jsx("meta",{name:"twitter:image",content:_e}),t.faviconUrl&&e.jsx("link",{rel:"icon",href:t.faviconUrl,type:"image/png"}),e.jsx("link",{rel:"canonical",href:`${ve}${n.pathname}`}),t.subdomainSlug==="matthogg"&&e.jsx("script",{src:"https://analytics.ahrefs.com/analytics.js","data-key":"kyFjzruyvE0yTdMokzgCBw",async:!0})]}),e.jsxs("header",{className:`${P?"absolute":"sticky"} top-0 left-0 right-0 z-50 transition-all ${te}`,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(nr,{to:"/",className:"flex items-center gap-3",children:[t.showTeamLogo&&t.teamLogoUrl?e.jsx("img",{src:t.teamLogoUrl,alt:`${M} logo`,className:"h-10 sm:h-12 w-auto max-w-[180px] object-contain"}):(Te=t.agent)!=null&&Te.avatar_url?e.jsx("img",{src:t.agent.avatar_url,alt:A,className:"h-10 w-10 rounded-full object-cover ring-2 ring-white/20"}):null,e.jsx("div",{children:e.jsx("span",{className:"font-bold text-lg leading-none tracking-tight",children:M})})]}),e.jsxs("nav",{className:"hidden md:flex items-center gap-1",children:[t.bookingUrl&&e.jsx(T3,{bookingUrl:t.bookingUrl,label:"Schedule",size:"sm",className:"order-last ml-3",source:"nav"}),oe.map(Re=>e.jsx(nr,{to:Re.to,className:`px-4 py-2 rounded-lg text-sm font-medium tracking-wide transition-colors ${n.pathname===Re.to?P?"bg-white/15 text-white":"bg-gray-100 text-gray-900":P?"text-white/70 hover:text-white hover:bg-white/10":"text-gray-500 hover:text-gray-900 hover:bg-gray-50"}`,children:Re.label},Re.to)),se&&me.map(Re=>{if(Re.item_type==="dropdown"){const ke=Q(Re.id);return e.jsxs("div",{ref:v,className:"relative",children:[e.jsxs("button",{onClick:()=>x(g===Re.id?null:Re.id),className:`flex items-center gap-1 px-4 py-2 rounded-lg text-sm font-medium tracking-wide transition-colors ${P?"text-white/70 hover:text-white hover:bg-white/10":"text-gray-500 hover:text-gray-900 hover:bg-gray-50"}`,children:[Re.label," ",e.jsx(Go,{className:`h-3.5 w-3.5 transition-transform ${g===Re.id?"rotate-180":""}`})]}),g===Re.id&&ke.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:ke.map(Fe=>e.jsx(yie,{item:Fe,onClick:()=>x(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"},Fe.id))})]},Re.id)}return e.jsx(yie,{item:Re,className:`px-4 py-2 rounded-lg text-sm font-medium tracking-wide transition-colors ${P?"text-white/70 hover:text-white hover:bg-white/10":"text-gray-500 hover:text-gray-900 hover:bg-gray-50"}`},Re.id)}),u.length>0&&e.jsxs("div",{ref:y,className:"relative",children:[e.jsxs("button",{onClick:()=>d(!c),className:`flex items-center gap-1 px-4 py-2 rounded-lg text-sm font-medium tracking-wide transition-colors ${n.pathname.startsWith("/homes-for-sale-in-")?P?"bg-white/15 text-white":"bg-gray-100 text-gray-900":P?"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(Go,{className:`h-3.5 w-3.5 transition-transform ${c?"rotate-180":""}`})]}),c&&e.jsx("div",{className:"absolute top-full right-0 mt-2 w-52 bg-white rounded-xl shadow-xl border border-gray-100 py-2 z-50 animate-in fade-in slide-in-from-top-2 duration-150",children:u.map(Re=>e.jsx("button",{onClick:()=>{r(`/homes-for-sale-in-${Re.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:Re.city_name},Re.city_slug))})]}),_?e.jsxs("div",{className:"flex items-center gap-1 ml-2",children:[e.jsxs(nr,{to:"/account",className:`flex items-center gap-1.5 px-3 py-2 rounded-lg text-sm font-medium transition-colors ${P?"text-white/70 hover:text-white hover:bg-white/10":"text-gray-500 hover:text-gray-900 hover:bg-gray-50"}`,children:[e.jsx(Bo,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden lg:inline",children:"Saved"})]}),e.jsxs(nr,{to:"/account",className:`flex items-center gap-1.5 px-3 py-2 rounded-lg text-sm font-medium transition-colors ${P?"text-white/70 hover:text-white hover:bg-white/10":"text-gray-500 hover:text-gray-900 hover:bg-gray-50"}`,children:[e.jsx(el,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden lg:inline",children:((Ie=j==null?void 0:j.name)==null?void 0:Ie.split(" ")[0])||"Account"})]})]}):R?e.jsx("button",{onClick:()=>o(!0),className:`ml-2 px-4 py-2 rounded-lg text-sm font-medium transition-colors ${P?"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 ${P?"text-white hover:bg-white/10":"text-gray-600 hover:bg-gray-100"}`,children:a?e.jsx(mr,{className:"h-5 w-5"}):e.jsx(WT,{className:"h-5 w-5"})})]})}),a&&e.jsx("div",{className:`md:hidden border-t ${P?"border-white/10 bg-black/95 backdrop-blur":"border-gray-100 bg-white"} max-h-[calc(100vh-5rem)] overflow-y-auto overscroll-contain`,children:e.jsxs("div",{className:"px-4 py-3 space-y-1 pb-8",children:[t.bookingUrl&&e.jsx(T3,{bookingUrl:t.bookingUrl,label:"Schedule a Free Consultation",size:"sm",className:"w-full mb-3",source:"mobile_nav"}),oe.map(Re=>e.jsx(nr,{to:Re.to,onClick:()=>i(!1),className:`block px-3 py-2.5 rounded-lg text-sm font-medium ${n.pathname===Re.to?P?"bg-white/15 text-white":"bg-gray-100 text-gray-900":P?"text-white/70 hover:bg-white/10":"text-gray-500 hover:bg-gray-50"}`,children:Re.label},Re.to)),se&&me.map(Re=>{if(Re.item_type==="dropdown"){const ke=Q(Re.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 ${P?"text-white/40":"text-gray-400"}`,children:Re.label}),ke.map(Fe=>e.jsx(yie,{item:Fe,onClick:()=>i(!1),className:`block px-3 py-2.5 rounded-lg text-sm font-medium ${P?"text-white/70 hover:bg-white/10":"text-gray-500 hover:bg-gray-50"}`},Fe.id))]},Re.id)}return e.jsx(yie,{item:Re,onClick:()=>i(!1),className:`block px-3 py-2.5 rounded-lg text-sm font-medium ${P?"text-white/70 hover:bg-white/10":"text-gray-500 hover:bg-gray-50"}`},Re.id)}),u.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:`px-3 pt-3 pb-1 text-xs font-semibold uppercase tracking-wider ${P?"text-white/40":"text-gray-400"}`,children:"Cities"}),u.map(Re=>e.jsx(nr,{to:`/homes-for-sale-in-${Re.city_slug}`,onClick:()=>i(!1),className:`block px-3 py-2.5 rounded-lg text-sm font-medium ${n.pathname===`/homes-for-sale-in-${Re.city_slug}`?P?"bg-white/15 text-white":"bg-gray-100 text-gray-900":P?"text-white/70 hover:bg-white/10":"text-gray-500 hover:bg-gray-50"}`,children:Re.city_name},Re.city_slug))]}),_?e.jsxs(e.Fragment,{children:[e.jsx(nr,{to:"/account",onClick:()=>i(!1),className:`block px-3 py-2.5 rounded-lg text-sm font-medium ${P?"text-white/70 hover:bg-white/10":"text-gray-500 hover:bg-gray-50"}`,children:"My Account"}),e.jsx("button",{onClick:async()=>{await C(),i(!1)},className:`block w-full text-left px-3 py-2.5 rounded-lg text-sm font-medium ${P?"text-white/70 hover:bg-white/10":"text-gray-500 hover:bg-gray-50"}`,children:"Sign Out"})]}):R?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 ${P?"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}),!I&&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:[((Ue=t.agent)==null?void 0:Ue.avatar_url)&&e.jsx("img",{src:t.agent.avatar_url,alt:A,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:A}),e.jsx("p",{className:"text-sm text-gray-500",children:((Be=t.agent)==null?void 0:Be.title)||"Real Estate Professional"})]})]}),((je=t.agent)==null?void 0:je.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(ka,{className:"h-3.5 w-3.5"})," ",t.agent.phone]})}),((Ye=t.agent)==null?void 0:Ye.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(pn,{className:"h-3.5 w-3.5"})," ",t.agent.email]})})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-semibold text-white mb-4 text-sm tracking-wider uppercase",children:"Quick Links"}),e.jsxs("ul",{className:"space-y-3 text-sm",children:[oe.map(Re=>e.jsx("li",{children:e.jsx(nr,{to:Re.to,className:"hover:text-white transition-colors",children:Re.label})},Re.to)),B&&e.jsx("li",{children:e.jsx("a",{href:B,target:"_blank",rel:"noopener noreferrer",className:"hover:text-white transition-colors",children:"Schedule a Call"})})]})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-semibold text-white mb-4 text-sm tracking-wider uppercase",children:"Get In Touch"}),e.jsx("p",{className:"text-sm text-gray-500 leading-relaxed mb-4",children:O?"Have a real estate question or need a trusted connection? Get in touch today.":"Ready to find your dream home? Get in touch today for a personalized consultation."}),e.jsx(nr,{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:[A," · ",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()," ",A,". Powered by LevelUp."]})]})]})]})}),!I&&((Ee=t.agent)==null?void 0:Ee.avatar_url)&&e.jsx(_Vn,{agent:t.agent,bookingUrl:B}),l&&e.jsx(wQe,{open:l,mode:"optional",siteConfig:t,onComplete:()=>o(!1),onSkip:()=>o(!1)}),e.jsx(rJe,{slug:t.subdomainSlug}),e.jsx(aJe,{slug:t.subdomainSlug}),e.jsx(oJe,{slug:t.subdomainSlug})]})}function _Vn({agent:s,bookingUrl:t}){var i;const[n,r]=k.useState(!1),a=Jn();return s?e.jsx("div",{className:"fixed bottom-6 right-6 z-40",children:n?e.jsxs("div",{className:"bg-white rounded-2xl shadow-2xl border border-gray-200 w-72 overflow-hidden animate-in slide-in-from-bottom-4 fade-in duration-200",children:[e.jsxs("div",{className:"p-5",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-3",children:[e.jsx("img",{src:s.avatar_url,alt:s.full_name,className:"h-12 w-12 rounded-full object-cover ring-2 ring-gray-100"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-bold text-gray-900 text-sm",children:s.full_name}),e.jsx("p",{className:"text-xs text-gray-500",children:s.title||"Real Estate Professional"})]})]}),e.jsx("p",{className:"text-xs text-gray-500 mb-4",children:"Have questions about a property or the area? I'm here to help!"}),e.jsxs("div",{className:"space-y-2",children:[s.phone&&e.jsxs("a",{href:`tel:${s.phone}`,className:"flex items-center gap-2 w-full px-3 py-2 bg-gray-50 hover:bg-gray-100 rounded-xl text-sm text-gray-700 transition-colors",children:[e.jsx(ka,{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(pn,{className:"h-4 w-4 text-gray-400"}),"Email Me"]}),e.jsx("button",{onClick:()=>{r(!1),a("/contact")},className:"w-full px-3 py-2.5 bg-blue-600 hover:bg-blue-700 text-white text-sm font-semibold rounded-xl transition-colors",children:"Ask a Question"}),t&&e.jsx("a",{href:t,target:"_blank",rel:"noopener noreferrer",className:"block text-center w-full px-3 py-2.5 bg-gray-900 hover:bg-gray-800 text-white text-sm font-semibold rounded-xl transition-colors",children:"Schedule a Call"})]})]}),e.jsx("button",{onClick:()=>r(!1),className:"absolute top-3 right-3 p-1 text-gray-400 hover:text-gray-600 rounded-full hover:bg-gray-100",children:e.jsx(mr,{className:"h-4 w-4"})})]}):e.jsxs("button",{onClick:()=>r(!0),className:"group flex items-center gap-3 bg-white pl-1.5 pr-5 py-1.5 rounded-full shadow-xl border border-gray-200 hover:shadow-2xl transition-all hover:scale-105",children:[e.jsx("img",{src:s.avatar_url,alt:s.full_name,className:"h-10 w-10 rounded-full object-cover ring-2 ring-blue-100"}),e.jsxs("div",{className:"text-left",children:[e.jsx("p",{className:"text-xs font-bold text-gray-900 leading-none",children:(i=s.full_name)==null?void 0:i.split(" ")[0]}),e.jsx("p",{className:"text-[10px] text-blue-600 font-medium mt-0.5",children:"Chat with me →"})]})]})}):null}function yie({item:s,className:t,onClick:n}){const r=s.target_url||"#";return s.item_type==="external"||s.open_in_new_tab?e.jsx("a",{href:r,target:"_blank",rel:"noopener noreferrer",className:t,onClick:n,children:s.label}):e.jsx(nr,{to:r,className:t,onClick:n,children:s.label})}const jwt={california:"California DRE License",ca:"California DRE License"};function Aqe(s){const t=(s||"").trim();if(!t)return"Real Estate License";const n=t.toLowerCase();return jwt[n]?jwt[n]:`${t.replace(/\b\w/g,a=>a.toUpperCase())} Real Estate License`}function Nwt(s){if(s)return s.replace(/^\s*DRE\s*#?\s*/i,"").replace(/^\s*#/,"").trim()||void 0}function wVn({children:s,siteConfig:t}){var Ie,Ue,Be,je,Ye,Ee,Re,ke;const n=Tu(),r=Jn(),[a,i]=k.useState(!1),[l,o]=k.useState(!1),[c,d]=k.useState(!1),[u,h]=k.useState(!1),[m,p]=k.useState([]),[g,x]=k.useState(!1),y=k.useRef(null),v=k.useRef(null),{user:_,profile:j,signOut:C}=VTe();kQe(t,_==null?void 0:_.id),SQe(t,_==null?void 0:_.id);const A=((Ie=t.agent)==null?void 0:Ie.full_name)||"Agent",M=Nwt(t.agentLicenseNumber),I=Nwt(t.brokerageLicenseNumber),P=t.siteTitle||`${A} Real Estate`,R=Fe=>{if(!Fe)return Fe;const Oe=A.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),Ge=new RegExp(`^\\s*${Oe}\\s*[|\\-–—:]\\s*`,"i");return Fe.replace(Ge,"").trim()},O=P&&P!==`${A} Real Estate`?P:null,B=O?R(O):null,U=B&&B.toLowerCase()!==A.toLowerCase()?B:null,G=n.pathname==="/search",H=n.pathname==="/",Y=t.leadRegistrationMode!=="disabled",se="#c9a96e",ee=t.bookingUrl;k.useEffect(()=>{const Fe=()=>x(window.scrollY>80);return window.addEventListener("scroll",Fe,{passive:!0}),()=>window.removeEventListener("scroll",Fe)},[]),k.useEffect(()=>{(async()=>{const{data:Oe}=await V.from("lead_site_city_pages").select("city_name, city_slug").eq("site_id",t.id).eq("is_published",!0).order("sort_order",{ascending:!0});p(Oe||[])})()},[t.id]),k.useEffect(()=>{const Fe=Oe=>{y.current&&!y.current.contains(Oe.target)&&d(!1),v.current&&!v.current.contains(Oe.target)&&h(!1)};return document.addEventListener("mousedown",Fe),()=>document.removeEventListener("mousedown",Fe)},[]);const oe=(((Ue=t.themeConfig)==null?void 0:Ue.focusPages)??[]).filter(Fe=>Fe==null?void 0:Fe.slug).map(Fe=>({to:`/${Fe.slug}`,label:Fe.navLabel||Fe.title})),me=r9t(t)||_Qe(t),{data:Q}=dWt(me?t.agentId:null),te=((Q==null?void 0:Q.length)??0)>0,le=[{to:"/",label:"Home"},...me?te?[{to:"/listings",label:"My Listings"}]:[]:[{to:"/search",label:"Search"}],{to:"/sell",label:"Sell"},{to:"/blog",label:"Blog"},{to:"/community",label:"Community"},{to:"/about",label:"About"},{to:"/contact",label:"Contact"}],fe=[...le,...oe],_e=t.siteTitle||`${A} - Real Estate`,ve=t.siteTagline||`Browse homes and listings with ${A}`,he=t.ogImageUrl||((Be=t.agent)==null?void 0:Be.avatar_url)||"",Se=`https://${t.subdomainSlug||""}.thelocalmove.com`,Te=H?g?"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 ${G?"h-screen overflow-hidden":"min-h-screen"} bg-[#0d0b0a]`,children:[e.jsx(jQe,{siteConfig:t,pagePath:n.pathname}),e.jsx(NQe,{siteConfig:t}),e.jsxs(Sc,{children:[e.jsx("title",{children:_e}),e.jsx("meta",{name:"description",content:ve}),e.jsx("meta",{property:"og:title",content:_e}),e.jsx("meta",{property:"og:description",content:ve}),e.jsx("meta",{property:"og:type",content:"website"}),e.jsx("meta",{property:"og:url",content:Se+n.pathname}),he&&e.jsx("meta",{property:"og:image",content:he}),e.jsx("meta",{name:"twitter:card",content:"summary_large_image"}),e.jsx("meta",{name:"twitter:title",content:_e}),e.jsx("meta",{name:"twitter:description",content:ve}),he&&e.jsx("meta",{name:"twitter:image",content:he}),t.faviconUrl&&e.jsx("link",{rel:"icon",href:t.faviconUrl,type:"image/png"}),e.jsx("link",{rel:"canonical",href:`${Se}${n.pathname}`}),e.jsx("link",{href:"https://fonts.googleapis.com/css2?family=Playfair+Display:ital,wght@0,400;0,500;0,600;0,700;1,400;1,500&display=swap",rel:"stylesheet"})]}),e.jsxs("header",{className:`${H?"fixed":"sticky"} top-0 left-0 right-0 z-50 transition-all duration-500 ${Te}`,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 min-h-20 py-3 gap-6",children:[e.jsxs(nr,{to:"/",className:"flex items-center gap-3 shrink-0",children:[t.showTeamLogo&&t.teamLogoUrl&&e.jsx("img",{src:t.teamLogoUrl,alt:`${A} brokerage logo`,className:"h-9 sm:h-11 w-auto max-w-[150px] object-contain"}),e.jsxs("span",{className:"flex flex-col leading-tight",children:[e.jsx("span",{className:"block whitespace-nowrap text-white text-base sm:text-lg xl:text-xl tracking-tight",style:{fontFamily:"'Playfair Display', Georgia, serif"},children:A}),t.brokerageLegalName&&e.jsx("span",{className:"hidden sm:block whitespace-nowrap text-[10px] sm:text-[11px] tracking-[0.14em] uppercase text-white/60",children:t.brokerageLegalName}),U&&e.jsx("span",{className:"hidden xl:block whitespace-nowrap text-[10px] tracking-[0.18em] uppercase text-white/40",children:U})]})]}),e.jsxs("nav",{className:"hidden lg:flex items-center justify-end gap-0 flex-1 min-w-0",children:[le.map(Fe=>e.jsx(nr,{to:Fe.to,className:`whitespace-nowrap px-2.5 xl:px-4 py-2 text-xs tracking-[0.15em] uppercase transition-colors duration-300 ${n.pathname===Fe.to?"text-white":"text-white/40 hover:text-white"}`,children:Fe.label},Fe.to)),oe.length>0&&e.jsxs("div",{ref:v,className:"relative",children:[e.jsxs("button",{onClick:()=>h(!u),className:`flex items-center gap-1 whitespace-nowrap px-2.5 xl:px-4 py-2 text-xs tracking-[0.15em] uppercase transition-colors duration-300 ${oe.some(Fe=>n.pathname===Fe.to)?"text-white":"text-white/40 hover:text-white"}`,children:["Specialty"," ",e.jsx(Go,{className:`h-3 w-3 transition-transform ${u?"rotate-180":""}`})]}),u&&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:oe.map(Fe=>e.jsx(nr,{to:Fe.to,onClick:()=>h(!1),className:`block px-5 py-2.5 text-xs tracking-wider text-white/50 hover:text-white hover:bg-white/5 uppercase transition-colors ${n.pathname===Fe.to?"text-white":""}`,children:Fe.label},Fe.to))})]}),m.length>0&&e.jsxs("div",{ref:y,className:"relative",children:[e.jsxs("button",{onClick:()=>d(!c),className:`flex items-center gap-1 whitespace-nowrap px-2.5 xl:px-4 py-2 text-xs tracking-[0.15em] uppercase transition-colors duration-300 ${n.pathname.startsWith("/homes-for-sale-in-")?"text-white":"text-white/40 hover:text-white"}`,children:["Cities ",e.jsx(Go,{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:m.map(Fe=>e.jsx("button",{onClick:()=>{r(`/homes-for-sale-in-${Fe.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:Fe.city_name},Fe.city_slug))})]}),_?e.jsxs("div",{className:"flex items-center gap-1 ml-3",children:[e.jsxs(nr,{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(Bo,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"hidden xl:inline",children:"Saved"})]}),e.jsxs(nr,{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(el,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"hidden xl:inline",children:((je=j==null?void 0:j.name)==null?void 0:je.split(" ")[0])||"Account"})]})]}):Y?e.jsx("button",{onClick:()=>o(!0),className:"ml-3 px-5 py-2 text-xs tracking-[0.2em] uppercase border border-white/20 text-white/60 hover:bg-white hover:text-black transition-all duration-500",children:"Sign In"}):null,ee&&e.jsx(T3,{bookingUrl:ee,label:"Schedule",size:"sm",className:"ml-3",source:"nav"})]}),e.jsxs("button",{onClick:()=>i(!a),className:"lg:hidden p-2 text-white/60 hover:text-white",children:[e.jsx("div",{className:"flex flex-col items-center gap-0.5",children:a?e.jsx(mr,{className:"h-5 w-5"}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"w-6 h-px bg-current"}),e.jsx("div",{className:"w-4 h-px bg-current mt-1.5"}),e.jsx("div",{className:"w-6 h-px bg-current mt-1.5"})]})}),e.jsx("span",{className:"text-[8px] tracking-[0.3em] uppercase mt-1 block",children:"MENU"})]})]})}),a&&e.jsx("div",{className:"lg:hidden border-t border-white/5 bg-[#0d0b0a]/98 backdrop-blur-lg",children:e.jsxs("div",{className:"px-6 py-4 space-y-1",children:[ee&&e.jsx(T3,{bookingUrl:ee,label:"Schedule a Free Consultation",size:"sm",className:"w-full mb-3",source:"mobile_nav"}),le.map(Fe=>e.jsx(nr,{to:Fe.to,onClick:()=>i(!1),className:`block px-3 py-3 text-xs tracking-[0.2em] uppercase transition-colors ${n.pathname===Fe.to?"text-white":"text-white/40 hover:text-white"}`,children:Fe.label},Fe.to)),oe.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:se},children:"Specialty"}),oe.map(Fe=>e.jsx(nr,{to:Fe.to,onClick:()=>i(!1),className:`block px-3 py-2.5 text-xs tracking-wider uppercase transition-colors ${n.pathname===Fe.to?"text-white":"text-white/40 hover:text-white"}`,children:Fe.label},Fe.to))]}),m.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:se},children:"Cities"}),m.map(Fe=>e.jsx(nr,{to:`/homes-for-sale-in-${Fe.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:Fe.city_name},Fe.city_slug))]}),_?e.jsxs(e.Fragment,{children:[e.jsx(nr,{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 C(),i(!1)},className:"block w-full text-left px-3 py-3 text-xs tracking-[0.2em] uppercase text-white/40 hover:text-white",children:"Sign Out"})]}):Y?e.jsx("button",{onClick:()=>{o(!0),i(!1)},className:"block w-full text-left px-3 py-3 text-xs tracking-[0.2em] uppercase text-white/40 hover:text-white",children:"Sign In / Register"}):null]})})]}),e.jsx("main",{className:"flex-1 min-h-0 flex flex-col",children:s}),!G&&e.jsx("footer",{className:"bg-[#0a0908] text-white/70 border-t border-white/10",children:e.jsxs("div",{className:"max-w-7xl mx-auto px-6 lg:px-8 py-20",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-16",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-white text-xl tracking-tight mb-3",style:{fontFamily:"'Playfair Display', Georgia, serif"},children:A}),e.jsx("p",{className:"text-white/70 text-xs tracking-[0.15em] uppercase mb-6",children:((Ye=t.agent)==null?void 0:Ye.title)||"Real Estate Professional"}),(M||I)&&e.jsxs("div",{className:"mb-6 p-4 border border-white/10 bg-white/5",children:[M&&e.jsxs("p",{className:"text-sm text-white font-medium tracking-wide",children:[Aqe(t.licenseState)," #",M]}),I&&e.jsxs("p",{className:"text-xs text-white/70 tracking-wider uppercase mt-1",children:["Brokerage License #",I]})]}),((Ee=t.agent)==null?void 0:Ee.phone)&&e.jsxs("a",{href:`tel:${t.agent.phone}`,className:"flex items-center gap-3 text-sm text-white/70 hover:text-white transition-colors mb-3",children:[e.jsx(ka,{className:"h-3.5 w-3.5"})," ",t.agent.phone]}),((Re=t.agent)==null?void 0:Re.email)&&e.jsxs("a",{href:`mailto:${t.agent.email}`,className:"flex items-center gap-3 text-sm text-white/70 hover:text-white transition-colors",children:[e.jsx(pn,{className:"h-3.5 w-3.5"})," ",t.agent.email]})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"text-xs tracking-[0.3em] uppercase mb-6 text-white",style:{color:se},children:"Quick Links"}),e.jsxs("ul",{className:"space-y-3",children:[fe.map(Fe=>e.jsx("li",{children:e.jsx(nr,{to:Fe.to,className:"text-xs tracking-wider uppercase text-white/70 hover:text-white transition-colors",children:Fe.label})},Fe.to)),ee&&e.jsx("li",{children:e.jsx("a",{href:ee,target:"_blank",rel:"noopener noreferrer",className:"text-xs tracking-wider uppercase transition-colors hover:opacity-80",style:{color:GV},children:"Schedule a Free Consultation"})})]})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"text-xs tracking-[0.3em] uppercase mb-6 text-white",style:{color:se},children:"Get In Touch"}),e.jsx("p",{className:"text-sm text-white/70 leading-relaxed mb-6",style:{fontFamily:"'Playfair Display', Georgia, serif",fontStyle:"italic"},children:"Ready to experience luxury real estate? Let's connect."}),e.jsxs("div",{className:"flex flex-col items-start gap-3",children:[ee&&e.jsx(T3,{bookingUrl:ee,label:"Schedule a Free Consultation",size:"sm",source:"footer"}),e.jsx(nr,{to:"/contact",className:"inline-block px-8 py-3 text-xs tracking-[0.3em] uppercase border border-white/20 text-white/90 hover:bg-white hover:text-black transition-all duration-500",children:"Contact Me"})]})]})]}),e.jsxs("div",{className:"mt-16 pt-8 border-t border-white/10",children:[t.showTeamLogo&&t.teamLogoUrl&&e.jsx("div",{className:"flex items-center justify-center mb-6",children:e.jsx("img",{src:t.teamLogoUrl,alt:"Team",className:"h-10 w-auto object-contain opacity-70"})}),t.brokerageLegalName&&e.jsxs("div",{className:"flex flex-wrap items-center justify-center gap-x-4 gap-y-1 text-[11px] text-white/70 tracking-wider uppercase mb-3",children:[e.jsxs("span",{children:[A," · ",t.brokerageLegalName]}),M&&e.jsxs("span",{children:[Aqe(t.licenseState)," #",M]}),I&&e.jsxs("span",{children:["Brokerage #",I]})]}),t.mlsDisclaimerText&&e.jsxs("div",{className:"flex items-start justify-center gap-3 mb-4",children:[t.mlsLogoUrl&&e.jsx("img",{src:t.mlsLogoUrl,alt:"MLS",className:"h-6 w-auto flex-shrink-0 mt-0.5 opacity-70"}),e.jsx("p",{className:"text-[11px] text-white/70 leading-relaxed max-w-3xl text-center",children:t.mlsDisclaimerText})]}),e.jsxs("div",{className:"flex items-center justify-center gap-4 text-[11px] text-white/70 tracking-wider uppercase",children:[t.equalHousingEnabled&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("svg",{viewBox:"0 0 24 24",fill:"currentColor",className:"h-4 w-4",children:e.jsx("path",{d:"M12 2L2 8v2h20V8L12 2zm0 2.5L18.5 8h-13L12 4.5zM4 12v8h4v-6h8v6h4v-8H4zm6 8v-4h4v4h-4z"})}),e.jsx("span",{children:"Equal Housing Opportunity"})]}),e.jsxs("span",{children:["© ",new Date().getFullYear()," ",A,". Powered by LevelUp."]})]})]})]})}),!G&&((ke=t.agent)==null?void 0:ke.avatar_url)&&e.jsx(jVn,{agent:t.agent,agentLicense:M,siteConfig:t,accentColor:se}),l&&e.jsx(wQe,{open:l,mode:"optional",siteConfig:t,onComplete:()=>o(!1),onSkip:()=>o(!1),theme:"luxury",accentColor:se}),e.jsx(rJe,{slug:t.subdomainSlug}),e.jsx(aJe,{slug:t.subdomainSlug}),e.jsx(oJe,{slug:t.subdomainSlug})]})}function jVn({agent:s,agentLicense:t,siteConfig:n,accentColor:r}){var o;const[a,i]=k.useState(!1),l=Jn();return s?e.jsx("div",{className:"fixed bottom-6 right-6 z-40",children:a?e.jsxs("div",{className:"bg-[#1a1715] border border-white/10 w-72 overflow-hidden animate-in slide-in-from-bottom-4 fade-in duration-200",children:[e.jsxs("div",{className:"p-5",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[e.jsx("img",{src:s.avatar_url,alt:s.full_name,className:"h-12 w-12 rounded-full object-cover ring-1 ring-white/10"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-white text-sm font-medium",style:{fontFamily:"'Playfair Display', Georgia, serif"},children:s.full_name}),e.jsx("p",{className:"text-white/50 text-[10px] tracking-[0.1em] uppercase",children:s.title||"Real Estate Professional"})]})]}),t&&e.jsxs("div",{className:"mb-3 px-3 py-2 bg-white/5 border border-white/10",children:[e.jsx("p",{className:"text-[10px] text-white/50 tracking-wider uppercase",children:Aqe(n.licenseState)}),e.jsxs("p",{className:"text-xs text-white font-medium",children:["#",t]})]}),e.jsxs("div",{className:"space-y-2",children:[s.phone&&e.jsxs("a",{href:`tel:${s.phone}`,className:"flex items-center gap-2 w-full px-3 py-2.5 bg-white/5 hover:bg-white/10 text-xs text-white/70 hover:text-white transition-colors tracking-wider",children:[e.jsx(ka,{className:"h-3.5 w-3.5"})," ",s.phone]}),s.email&&e.jsxs("a",{href:`mailto:${s.email}`,className:"flex items-center gap-2 w-full px-3 py-2.5 bg-white/5 hover:bg-white/10 text-xs text-white/70 hover:text-white transition-colors tracking-wider",children:[e.jsx(pn,{className:"h-3.5 w-3.5"})," Email Me"]}),e.jsx("button",{onClick:()=>{i(!1),l("/contact")},className:"w-full px-3 py-2.5 text-xs tracking-[0.2em] uppercase text-black hover:opacity-90 transition-colors",style:{backgroundColor:r},children:"Send a Message"})]})]}),e.jsx("button",{onClick:()=>i(!1),className:"absolute top-3 right-3 p-1 text-white/20 hover:text-white/50",children:e.jsx(mr,{className:"h-4 w-4"})})]}):e.jsxs("button",{onClick:()=>i(!0),className:"group flex items-center gap-3 bg-[#1a1715] border border-white/10 pl-1.5 pr-5 py-1.5 hover:border-white/20 transition-all",children:[e.jsx("img",{src:s.avatar_url,alt:s.full_name,className:"h-10 w-10 rounded-full object-cover ring-1 ring-white/10"}),e.jsxs("div",{className:"text-left",children:[e.jsx("p",{className:"text-[11px] text-white leading-none",style:{fontFamily:"'Playfair Display', Georgia, serif"},children:(o=s.full_name)==null?void 0:o.split(" ")[0]}),e.jsx("p",{className:"text-[9px] tracking-[0.15em] uppercase mt-1",style:{color:r},children:"Let's connect →"})]})]})}):null}const eW="#2c1810",xS="#b8860b";function NVn({children:s,siteConfig:t}){var P,R,O;const n=Tu();Jn();const[r,a]=k.useState(!1),[i,l]=k.useState(!1),[o,c]=k.useState(!1),[d,u]=k.useState([]),[h,m]=k.useState(!1),p=k.useRef(null),{user:g,profile:x,signOut:y}=VTe();kQe(t,g==null?void 0:g.id),SQe(t,g==null?void 0:g.id);const v=((P=t.agent)==null?void 0:P.full_name)||"Agent",_=t.siteTitle||`${v} Land & Ranch`,j=n.pathname==="/",C=t.leadRegistrationMode!=="disabled";k.useEffect(()=>{const B=()=>m(window.scrollY>80);return window.addEventListener("scroll",B,{passive:!0}),()=>window.removeEventListener("scroll",B)},[]),k.useEffect(()=>{(async()=>{const{data:U}=await V.from("lead_site_city_pages").select("city_name, city_slug").eq("site_id",t.id).eq("is_published",!0).order("sort_order");U&&u(U)})()},[t.id]),k.useEffect(()=>{const B=U=>{p.current&&!p.current.contains(U.target)&&c(!1)};return document.addEventListener("mousedown",B),()=>document.removeEventListener("mousedown",B)},[]);const A=[{label:"Home",path:"/"},{label:"Search Properties",path:"/search"},{label:"About",path:"/about"},{label:"Blog",path:"/blog"},{label:"Contact",path:"/contact"}],M=h||!j?"bg-white/95 backdrop-blur-md shadow-sm":"bg-transparent",I=h||!j?eW:"#ffffff";return e.jsxs("div",{className:"min-h-screen",style:{fontFamily:"'Lora', Georgia, serif"},children:[e.jsxs(Sc,{children:[e.jsx("title",{children:_}),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(jQe,{siteConfig:t}),e.jsx(NQe,{siteConfig:t}),e.jsxs("header",{className:`fixed top-0 left-0 right-0 z-50 transition-all duration-300 ${M}`,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(nr,{to:"/",className:"flex items-center gap-2.5",children:[e.jsx(D8,{className:"w-7 h-7",style:{color:xS}}),e.jsx("span",{className:"text-lg font-bold tracking-wide",style:{color:I,fontFamily:"'Playfair Display', Georgia, serif"},children:_})]}),e.jsxs("nav",{className:"hidden md:flex items-center gap-1",children:[A.map(B=>e.jsx(nr,{to:B.path,className:"px-4 py-2 text-sm font-medium tracking-wide uppercase transition-colors hover:opacity-80",style:{color:n.pathname===B.path?xS:I},children:B.label},B.path)),d.length>0&&e.jsxs("div",{ref:p,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:I},children:["Areas ",e.jsx(Go,{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(B=>e.jsx(nr,{to:`/homes-for-sale-in-${B.city_slug}`,className:"block px-4 py-2.5 text-sm hover:bg-gray-50 transition-colors",style:{color:eW},onClick:()=>c(!1),children:B.city_name},B.city_slug))})]}),g?e.jsx("div",{className:"flex items-center gap-2 ml-3",children:e.jsxs(nr,{to:"/account",className:"px-4 py-2 text-sm font-medium rounded-full border-2 transition-all hover:scale-105",style:{borderColor:xS,color:I},children:[e.jsx(el,{className:"w-4 h-4 inline mr-1.5"}),(x==null?void 0:x.name)||"Account"]})}):C?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:xS},children:"Sign In"}):null]}),e.jsx("button",{onClick:()=>a(!r),className:"md:hidden p-2",style:{color:I},children:r?e.jsx(mr,{className:"w-6 h-6"}):e.jsx(WT,{className:"w-6 h-6"})})]})}),r&&e.jsx("div",{className:"md:hidden bg-white border-t border-gray-100 shadow-xl animate-in slide-in-from-top-2",children:e.jsxs("div",{className:"px-4 py-4 space-y-1",children:[A.map(B=>e.jsx(nr,{to:B.path,className:"block px-4 py-3 text-base font-medium rounded-lg hover:bg-gray-50 transition-colors",style:{color:n.pathname===B.path?xS:eW},onClick:()=>a(!1),children:B.label},B.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(B=>e.jsx(nr,{to:`/homes-for-sale-in-${B.city_slug}`,className:"block px-4 py-2.5 text-sm rounded-lg hover:bg-gray-50",style:{color:eW},onClick:()=>a(!1),children:B.city_name},B.city_slug))]}),!g&&C&&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:xS},children:"Sign In"})]})})]}),e.jsx("main",{children:s}),e.jsx("footer",{className:"py-16 px-4",style:{backgroundColor:eW},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(D8,{className:"w-6 h-6",style:{color:xS}}),e.jsx("span",{className:"text-lg font-bold text-white",style:{fontFamily:"'Playfair Display', Georgia, serif"},children:_})]}),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:A.map(B=>e.jsx(nr,{to:B.path,className:"block text-white/60 hover:text-white text-sm transition-colors",children:B.label},B.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:[((R=t.agent)==null?void 0:R.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(ka,{className:"w-4 h-4",style:{color:xS}}),t.agent.phone]}),((O=t.agent)==null?void 0:O.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(pn,{className:"w-4 h-4",style:{color:xS}}),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()," ",_,". All rights reserved."]}),e.jsx("div",{className:"h-px w-16",style:{backgroundColor:xS}})]})]})}),i&&e.jsx(wQe,{open:i,mode:t.leadRegistrationMode==="required"?"required":"optional",siteConfig:t,onSkip:()=>l(!1),onComplete:()=>l(!1)}),e.jsx(rJe,{slug:t.subdomainSlug}),e.jsx(aJe,{slug:t.subdomainSlug}),e.jsx(oJe,{slug:t.subdomainSlug})]})}function kVn(){const{pathname:s}=Tu();return k.useEffect(()=>{window.scrollTo({top:0,left:0,behavior:"auto"})},[s]),null}const SVn=k.lazy(()=>Ai(()=>import("./LeadSiteHome-l_Dtxo9y.js"),__vite__mapDeps([0,1,2,3,4]))),CVn=k.lazy(()=>Ai(()=>import("./LeadSiteLuxuryHome-BRnbSWRq.js"),__vite__mapDeps([5,2,3,4,6]))),AVn=k.lazy(()=>Ai(()=>import("./LeadSiteLandRanchHome-Dz-9G-_m.js"),__vite__mapDeps([7,1,2,3,4]))),EVn=k.lazy(()=>Ai(()=>import("./LeadSiteSearch-Bgq6QvRO.js"),__vite__mapDeps([8,1,9,4,10]))),TVn=k.lazy(()=>Ai(()=>import("./LeadSiteLuxurySearch-_fx39hKj.js"),__vite__mapDeps([11,1,9,4,10]))),MVn=k.lazy(()=>Ai(()=>import("./LeadSiteListingDetail-BGm0VZXC.js"),__vite__mapDeps([12,13,4,14]))),PVn=k.lazy(()=>Ai(()=>import("./LeadSiteLuxuryListingDetail-B3SNeXJZ.js"),__vite__mapDeps([15,13,4,14]))),IVn=k.lazy(()=>Ai(()=>import("./LeadSiteAbout-VQ36e6b8.js"),[])),LVn=k.lazy(()=>Ai(()=>import("./LeadSiteLuxuryAbout-Dn96-45m.js"),[])),RVn=k.lazy(()=>Ai(()=>import("./LeadSiteContact-DUFIihTi.js"),[])),DVn=k.lazy(()=>Ai(()=>import("./LeadSiteLuxuryContact-C-2KXohQ.js"),[])),OVn=k.lazy(()=>Ai(()=>import("./LeadSiteConsumerDashboard-CAlZxzfE.js"),[])),kwt=k.lazy(()=>Ai(()=>import("./LeadSiteBlog-1zP7zOCS.js"),__vite__mapDeps([16,17]))),FVn=k.lazy(()=>Ai(()=>import("./LeadSiteCommunity-B64PFPRR.js"),[])),zVn=k.lazy(()=>Ai(()=>import("./LeadSiteSellers-DfBLh-Ex.js"),[])),BVn=k.lazy(()=>Ai(()=>import("./LeadSiteCityPage-DqpbE5lG.js"),__vite__mapDeps([18,4,10]))),$Vn=k.lazy(()=>Ai(()=>import("./LeadSiteSubdivisionPage-DdD6P9f-.js"),__vite__mapDeps([19,4]))),UVn=k.lazy(()=>Ai(()=>import("./LeadSiteCustomPage-C9bovAyH.js"),[])),qVn=k.lazy(()=>Ai(()=>import("./LeadSiteFocusPage-CVhnrqN0.js"),__vite__mapDeps([20,3,4]))),VVn=k.lazy(()=>Ai(()=>import("./LeadSiteExchangeListings-DXMF0GLh.js"),[]).then(s=>({default:s.LeadSiteExchangeListingsIndex}))),HVn=k.lazy(()=>Ai(()=>import("./LeadSiteExchangeListings-DXMF0GLh.js"),[]).then(s=>({default:s.LeadSiteExchangeListingDetail})));function GVn(){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 WVn(){var u;const{siteConfig:s,themeConfig:t,isLoading:n,error:r}=J7n();if(n)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-white",children:e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-blue-600 border-t-transparent mx-auto mb-4"}),e.jsx("p",{className:"text-gray-500",children:"Loading..."})]})});if(r||!s)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-gray-50 p-6",children:e.jsxs("div",{className:"text-center max-w-md",children:[e.jsx("h1",{className:"text-2xl font-bold text-gray-900 mb-2",children:"Site Not Found"}),e.jsx("p",{className:"text-gray-500",children:"This lead site is not available or has not been set up yet."})]})});const a=(t==null?void 0:t.themeTier)==="luxury",i=(t==null?void 0:t.themeTier)==="land-ranch",l=i?NVn:a?wVn:bVn,o=r9t(s),c=!o&&_Qe(s,t),d=i?e.jsx(AVn,{siteConfig:s,themeConfig:t??void 0}):a?e.jsx(CVn,{siteConfig:s,themeConfig:t??void 0}):e.jsx(SVn,{siteConfig:s,themeConfig:t??void 0});return e.jsxs(t9n,{siteConfig:s,children:[e.jsx(kVn,{}),e.jsxs(l,{siteConfig:s,children:[e.jsx(k.Suspense,{fallback:e.jsx(GVn,{}),children:e.jsxs($Z,{children:[e.jsx(fs,{path:"/",element:d}),e.jsx(fs,{path:"/listings",element:e.jsx(VVn,{siteConfig:s})}),e.jsx(fs,{path:"/listings/:slug",element:e.jsx(HVn,{siteConfig:s})}),e.jsx(fs,{path:"/search",element:o?e.jsx(ab,{to:"/listings",replace:!0}):c?e.jsx(ab,{to:"/contact",replace:!0}):a?e.jsx(TVn,{siteConfig:s}):e.jsx(EVn,{siteConfig:s})}),e.jsx(fs,{path:"/listing/:mlsNumber",element:o?e.jsx(ab,{to:"/listings",replace:!0}):c?e.jsx(ab,{to:"/contact",replace:!0}):a?e.jsx(PVn,{siteConfig:s}):e.jsx(MVn,{siteConfig:s})}),e.jsx(fs,{path:"/about",element:a?e.jsx(LVn,{siteConfig:s}):e.jsx(IVn,{siteConfig:s})}),e.jsx(fs,{path:"/contact",element:a?e.jsx(DVn,{siteConfig:s}):e.jsx(RVn,{siteConfig:s})}),e.jsx(fs,{path:"/account",element:e.jsx(OVn,{siteConfig:s})}),e.jsx(fs,{path:"/blog",element:e.jsx(kwt,{siteConfig:s,isLuxury:a})}),e.jsx(fs,{path:"/blog/:slug",element:e.jsx(kwt,{siteConfig:s,isLuxury:a})}),e.jsx(fs,{path:"/sell",element:e.jsx(zVn,{siteConfig:s,themeConfig:t??void 0,isLuxury:a})}),e.jsx(fs,{path:"/community",element:e.jsx(FVn,{siteConfig:s,isLuxury:a})}),e.jsx(fs,{path:"/schedule",element:e.jsx(o9n,{bookingUrl:s.bookingUrl,agentName:((u=s.agent)==null?void 0:u.full_name)||"your agent"})}),((t==null?void 0:t.focusPages)??[]).map(h=>e.jsx(fs,{path:`/${h.slug}`,element:e.jsx(qVn,{siteConfig:s,page:h,accentColor:(t==null?void 0:t.accentColor)||s.accentColor||"#c9a96e"})},h.slug)),e.jsx(fs,{path:"/p/:pageSlug",element:e.jsx(UVn,{siteConfig:s})}),e.jsx(fs,{path:"/*",element:e.jsx(KVn,{siteConfig:s,referralMode:c})})]})}),e.jsx(i9n,{bookingUrl:s.bookingUrl})]})]})}function KVn({siteConfig:s,referralMode:t}){const n=Tu(),r=n.pathname.match(/^\/homes-in-(.+)$/);if(r)return e.jsx($Vn,{siteConfig:s,subdivisionSlug:r[1]});const a=n.pathname.match(/^\/homes-for-sale-in-(.+)$/);return a?e.jsx(BVn,{siteConfig:s,citySlugOverride:a[1],referralMode:t}):null}function YVn(){const{user:s,loading:t}=ks(),{data:n,isLoading:r}=pt({queryKey:["feature-entitlement","levelup_attract",s==null?void 0:s.id],enabled:!!s,staleTime:5*60*1e3,queryFn:async()=>{const{data:a,error:i}=await V.from("feature_entitlements").select("enabled, expires_at, tier").eq("user_id",s.id).eq("feature_key","levelup_attract").maybeSingle();if(i)throw i;return a?{hasAccess:a.enabled&&(!a.expires_at||new Date(a.expires_at).getTime()>Date.now()),tier:a.tier??null}:{hasAccess:!1,tier:null}}});return{hasAccess:!!(n!=null&&n.hasAccess),tier:(n==null?void 0:n.tier)??null,isLoading:t||r}}function ZVn({children:s}){const{user:t,loading:n}=ks(),{hasAccess:r,isLoading:a}=YVn(),i=Tu();return k.useEffect(()=>{!n&&!a&&t&&!r&&ae.error("LevelUp Attract isn't available for your account yet.")},[n,a,t,r]),n||t&&a?e.jsx("div",{className:"flex min-h-screen items-center justify-center bg-background",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):t?r?e.jsx(e.Fragment,{children:s}):e.jsx(ab,{to:"/dashboard",replace:!0}):(sessionStorage.setItem("redirectAfterLogin",i.pathname),e.jsx(ab,{to:"/auth",replace:!0}))}function Swt({children:s}){const{user:t,loading:n}=ks(),{hasAccess:r,isLoading:a}=I3e(),i=Tu();return n||t&&a?e.jsx("div",{className:"flex min-h-screen items-center justify-center bg-background",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):t?r?e.jsx(e.Fragment,{children:s}):e.jsx(ab,{to:"/dashboard",replace:!0}):(sessionStorage.setItem("redirectAfterLogin",i.pathname),e.jsx(ab,{to:"/auth",replace:!0}))}const Eqe={buyer:"Buyer",seller:"Seller",local_community:"Local & Community",luxury:"Luxury",new_homes:"New Homes",open_house:"Open House",sphere:"Sphere",personal_brand:"Personal Brand",market_update:"Market Update"},XVn=["First-time buyers","Move-up buyers","Luxury","New construction","Investors","Relocation","Downsizing / seniors","Military / VA","Land & ranch","Waterfront","Condos","Multi-family"],QVn=["Buyers","Sellers","Both equally","Investors","Renters","Builders / developers"],JVn=["Warm & approachable","Bold & direct","Educational & analytical","Playful & funny","Polished & luxury","Down-to-earth & local","High-energy & motivational"],eHn=[{value:"none",label:"Keep it straight — no jokes"},{value:"light",label:"Light — an occasional wink"},{value:"medium",label:"Medium — genuinely funny"},{value:"high",label:"High — lead with the humor"}],tHn=["Under $250k","$250k – $500k","$500k – $750k","$750k – $1M","$1M – $2M","$2M+"],sHn=["Brand new (under 1 year)","1–3 years","3–5 years","5–10 years","10–20 years","20+ years"],nHn=[{value:"dm_keyword",label:"DM me a keyword"},{value:"comment",label:"Comment below"},{value:"link_in_bio",label:"Link in bio"},{value:"call_text",label:"Call or text me"},{value:"soft",label:"Soft — no hard ask"}],rHn=[{value:"instagram",label:"Instagram"},{value:"tiktok",label:"TikTok"},{value:"facebook",label:"Facebook"},{value:"youtube",label:"YouTube Shorts"},{value:"linkedin",label:"LinkedIn"}],aHn=[{value:"15-30s",label:"15–30 seconds"},{value:"30-45s",label:"30–45 seconds"},{value:"45-60s",label:"45–60 seconds"}],iHn=[{value:"new",label:"Brand new to video — go easy on me"},{value:"building",label:"Building confidence"},{value:"comfortable",label:"Comfortable on camera"},{value:"pro",label:"Very comfortable — push me"}],oHn=[{value:"local",label:"Mostly local market content"},{value:"evergreen",label:"Mostly evergreen content"},{value:"mix",label:"A healthy mix of both"}];function uWt({value:s,label:t}){const[n,r]=k.useState(!1);return s?e.jsxs($,{type:"button",size:"sm",variant:"ghost",className:"h-7 px-2 text-[11px] font-medium text-muted-foreground hover:text-foreground",onClick:async()=>{await navigator.clipboard.writeText(s),r(!0),ae.success(`${t} copied`),setTimeout(()=>r(!1),1600)},children:[n?e.jsx(ma,{className:"h-3.5 w-3.5 mr-1"}):e.jsx(Da,{className:"h-3.5 w-3.5 mr-1"}),"Copy"]}):null}function xP({label:s,children:t,copyValue:n}){return e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"text-[11px] font-semibold uppercase tracking-[0.09em] text-muted-foreground",children:s}),n?e.jsx(uWt,{value:n,label:s}):null]}),e.jsx("div",{className:"text-[14.5px] leading-relaxed text-foreground whitespace-pre-wrap",children:t})]})}function _ke({reel:s,index:t,onUpdate:n,readOnly:r}){var c;const[a,i]=k.useState(t===0),l=!!s.recorded_at,o=!!s.posted_at;return e.jsx(we,{className:"rounded-2xl border-border/70 overflow-hidden",children:e.jsxs("div",{className:"p-5 sm:p-6",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(qe,{className:"bg-primary text-primary-foreground border-0 text-[10.5px] font-bold tracking-[0.09em] px-2.5",children:["REEL ",t+1]}),s.category?e.jsx(qe,{variant:"outline",className:"text-[10.5px] font-medium text-muted-foreground",children:Eqe[s.category]??s.category}):null,o?e.jsx(qe,{className:"bg-emerald-100 text-emerald-800 border-0 text-[10.5px]",children:"Posted"}):l?e.jsx(qe,{className:"bg-amber-100 text-amber-800 border-0 text-[10.5px]",children:"Recorded"}):null]}),e.jsx("h3",{className:"mt-3 text-lg sm:text-xl font-semibold tracking-tight text-foreground",children:s.topic})]}),!r&&n?e.jsx($,{type:"button",size:"icon",variant:"ghost","aria-label":s.favorited?"Remove from saved":"Save this reel",className:Ot("h-9 w-9 shrink-0",s.favorited&&"text-amber-500"),onClick:()=>n({favorited:!s.favorited}),children:e.jsx(ri,{className:Ot("h-4.5 w-4.5",s.favorited&&"fill-current")})}):null]}),e.jsxs("div",{className:"mt-5 rounded-xl bg-muted/60 p-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"text-[11px] font-semibold uppercase tracking-[0.09em] text-muted-foreground",children:"On-screen hook"}),e.jsx(uWt,{value:s.hook,label:"Hook"})]}),e.jsx("p",{className:"mt-1.5 text-[16px] font-semibold leading-snug text-foreground",children:s.hook})]}),e.jsx("div",{className:"mt-5",children:e.jsx(xP,{label:"Script · 30–45 seconds",copyValue:s.script,children:s.script})}),!r&&n?e.jsxs("div",{className:"mt-5 flex flex-wrap gap-2",children:[e.jsxs($,{type:"button",size:"sm",variant:l?"default":"outline",className:"rounded-full",onClick:()=>n({recorded_at:l?null:new Date().toISOString()}),children:[e.jsx(ia,{className:"h-3.5 w-3.5 mr-1.5"}),l?"Recorded":"Mark as recorded"]}),e.jsxs($,{type:"button",size:"sm",variant:o?"default":"outline",className:"rounded-full",onClick:()=>n({posted_at:o?null:new Date().toISOString()}),children:[e.jsx(Wr,{className:"h-3.5 w-3.5 mr-1.5"}),o?"Posted":"Mark as posted"]})]}):null,e.jsxs(h1,{open:a,onOpenChange:i,children:[e.jsx(m1,{asChild:!0,children:e.jsxs($,{type:"button",variant:"ghost",size:"sm",className:"mt-4 w-full justify-between text-[13px] font-medium text-muted-foreground hover:text-foreground",children:[a?"Hide caption, hashtags & coaching":"Caption, hashtags & coaching",e.jsx(Go,{className:Ot("h-4 w-4 transition-transform",a&&"rotate-180")})]})}),e.jsxs(f1,{className:"space-y-5 pt-2",children:[e.jsx(Pc,{}),s.filming_directions?e.jsx(xP,{label:"How to film it",children:e.jsxs("span",{className:"flex gap-2",children:[e.jsx(Bz,{className:"h-4 w-4 mt-0.5 shrink-0 text-muted-foreground"}),e.jsx("span",{children:s.filming_directions})]})}):null,s.caption?e.jsx(xP,{label:"Caption",copyValue:s.caption,children:s.caption}):null,(c=s.hashtags)!=null&&c.length?e.jsx(xP,{label:"Hashtags",copyValue:s.hashtags.join(" "),children:e.jsx("span",{className:"flex flex-wrap gap-1.5",children:s.hashtags.map(d=>e.jsx("span",{className:"rounded-full bg-primary/10 px-2.5 py-1 text-[12.5px] font-medium text-primary",children:d},d))})}):null,s.pinned_comment?e.jsx(xP,{label:"Pinned comment",copyValue:s.pinned_comment,children:s.pinned_comment}):null,s.reply_strategy?e.jsx(xP,{label:"Reply strategy",children:e.jsxs("span",{className:"flex gap-2",children:[e.jsx(bo,{className:"h-4 w-4 mt-0.5 shrink-0 text-muted-foreground"}),e.jsx("span",{children:s.reply_strategy})]})}):null,s.why_it_works?e.jsxs("div",{className:"rounded-xl border border-primary/20 bg-primary/5 p-4",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-[11px] font-semibold uppercase tracking-[0.09em] text-primary",children:[e.jsx(kn,{className:"h-3.5 w-3.5"})," Why this will work"]}),e.jsx("p",{className:"mt-1.5 text-[14px] leading-relaxed text-foreground",children:s.why_it_works})]}):null,s.bonus_idea?e.jsx(xP,{label:"Bonus content idea",children:e.jsxs("span",{className:"flex gap-2",children:[e.jsx(P5,{className:"h-4 w-4 mt-0.5 shrink-0 text-muted-foreground"}),e.jsx("span",{children:s.bonus_idea})]})}):null]})]})]})})}function hWt(s=new Date){const t=new Intl.DateTimeFormat("en-CA",{timeZone:"America/New_York",year:"numeric",month:"2-digit",day:"2-digit",weekday:"short"}).formatToParts(s),n=i=>t.find(l=>l.type===i).value,r=["Mon","Tue","Wed","Thu","Fri","Sat","Sun"].indexOf(n("weekday")),a=new Date(`${n("year")}-${n("month")}-${n("day")}T12:00:00Z`);return a.setUTCDate(a.getUTCDate()-(r<0?0:r)),a.toISOString().slice(0,10)}function Cwt(){const s=hWt(),[t,n,r]=s.split("-").map(Number),a=new Date(Date.UTC(t,n-1,r));return a.setUTCDate(a.getUTCDate()+7),new Intl.DateTimeFormat("en-US",{weekday:"long",month:"long",day:"numeric",timeZone:"UTC"}).format(a)}function mZ(s){const[t,n,r]=s.split("-").map(Number);return new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric",year:"numeric",timeZone:"UTC"}).format(new Date(Date.UTC(t,n-1,r)))}function lJe(s){const{user:t}=ks(),n=s??(t==null?void 0:t.id),r=ls(),a=pt({queryKey:["weekly-reels-profile",n],enabled:!!n,queryFn:async()=>{const{data:h,error:m}=await V.from("weekly_reel_profiles").select("*").eq("user_id",n).maybeSingle();if(m)throw m;return h??null}}),i=pt({queryKey:["weekly-reels-packs",n],enabled:!!n,queryFn:async()=>{const{data:h,error:m}=await V.from("weekly_reel_packs").select("*").eq("user_id",n).order("week_start_date",{ascending:!1}).limit(52);if(m)throw m;const p=(h??[]).map(x=>x.id);let g=[];if(p.length){const{data:x,error:y}=await V.from("weekly_reels").select("*").in("pack_id",p).order("position",{ascending:!0});if(y)throw y;g=x??[]}return(h??[]).map(x=>({...x,reels:g.filter(y=>y.pack_id===x.id)}))}}),l=Nt({mutationFn:async h=>{if(!n)throw new Error("Not signed in");const m={...h,user_id:n,...h.onboarding_completed?{onboarding_completed_at:new Date().toISOString()}:{}},{error:p}=await V.from("weekly_reel_profiles").upsert(m,{onConflict:"user_id"});if(p)throw p},onSuccess:()=>{r.invalidateQueries({queryKey:["weekly-reels-profile",n]})},onError:h=>ae.error(h.message)}),o=Nt({mutationFn:async({id:h,values:m})=>{const{error:p}=await V.from("weekly_reels").update(m).eq("id",h);if(p)throw p},onSuccess:()=>r.invalidateQueries({queryKey:["weekly-reels-packs",n]}),onError:h=>ae.error(h.message)}),c=hWt(),d=(i.data??[]).find(h=>h.week_start_date===c)??null,u=(i.data??[]).filter(h=>h.week_start_date!==c);return{profile:a,packs:i,currentPack:d,history:u,saveProfile:l,updateReel:o,userId:n}}function vie({icon:s,label:t,value:n}){return e.jsxs("div",{className:"neon-tile neon-topline px-4 py-3.5",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-[10.5px] font-semibold uppercase tracking-[0.18em] text-muted-foreground",children:[e.jsx(s,{className:"h-3.5 w-3.5"})," ",t]}),e.jsx("div",{className:"neon-stat mt-1.5 text-[17px] font-black leading-snug",children:n})]})}function lHn(){var R,O,B,U,G;const s=Jn(),{user:t}=ks(),{profile:n,packs:r,currentPack:a,saveProfile:i,updateReel:l}=lJe(),[o,c]=k.useState(!1),[d,u]=k.useState(!1),[h,m]=k.useState(""),[p,g]=k.useState("all"),[x,y]=k.useState("all"),v=(((R=n.data)==null?void 0:R.full_name)||((O=t==null?void 0:t.user_metadata)==null?void 0:O.full_name)||"there").split(" ")[0],_=!!((B=n.data)!=null&&B.onboarding_completed),j=k.useMemo(()=>(r.data??[]).flatMap(H=>H.reels.map(Y=>({reel:Y,pack:H}))),[r.data]),C=k.useMemo(()=>{const H=h.trim().toLowerCase();return j.filter(({pack:Y})=>x==="all"?!0:Y.week_start_date===x).filter(({reel:Y})=>p==="all"?!0:Y.category===p).filter(({reel:Y})=>H?`${Y.topic} ${Y.hook} ${Y.script}`.toLowerCase().includes(H):!0)},[j,h,p,x]),A=j.filter(({reel:H})=>H.favorited),M=async()=>{c(!0);try{const{data:H,error:Y}=await V.functions.invoke("weekly-reels-generate",{body:{action:"generate_pack",force:!0}});if(Y)throw Y;if(H!=null&&H.error)throw new Error(H.error);await r.refetch(),ae.success(H!=null&&H.skipped?String(H.skipped):"Your pack is ready")}catch(H){ae.error(H instanceof Error?H.message:"Generation failed")}finally{c(!1)}},I=async()=>{if(a){u(!0);try{const{data:H,error:Y}=await V.functions.invoke("weekly-reels-generate",{body:{action:"send_pack_email",packId:a.id}});if(Y)throw Y;if(H!=null&&H.error)throw new Error(H.error);await r.refetch(),ae.success(`Sent to ${(H==null?void 0:H.recipient)??"your inbox"}`)}catch(H){ae.error(H instanceof Error?H.message:"Could not send the email")}finally{u(!1)}}},P=H=>Y=>l.mutate({id:H.id,values:Y});return!n.isLoading&&!_?e.jsx(Xs,{title:"Weekly Reels",children:e.jsx("div",{className:"program-theme-neon relative min-h-screen",children:e.jsx("div",{className:"relative mx-auto w-full max-w-2xl px-4 py-16 sm:px-6",children:e.jsxs(we,{className:"neon-topline p-8 text-center sm:p-12",children:[e.jsx("div",{className:"mx-auto flex h-14 w-14 items-center justify-center rounded-2xl bg-primary/15",children:e.jsx(em,{className:"h-7 w-7 text-primary"})}),e.jsx("p",{className:"neon-eyebrow mt-6 font-semibold",children:"Weekly Reels"}),e.jsx("h1",{className:"neon-title mx-auto mt-2 w-fit text-3xl font-black uppercase tracking-tight sm:text-4xl",children:"5 Reels. Every Monday."}),e.jsx("p",{className:"mx-auto mt-3 max-w-md text-[15px] leading-relaxed text-muted-foreground",children:"Tell us about your market, your niche and how you actually talk. Then every Monday at 9:00 AM you get five ready-to-film Reels written for you — hook, word-for-word script, caption, hashtags and all."}),e.jsxs($,{size:"lg",className:"neon-cta mt-7",onClick:()=>s("/weekly-reels/onboarding"),children:[e.jsx(kn,{className:"h-4 w-4 mr-2"})," Start setup — about 5 minutes"]})]})})})}):e.jsx(Xs,{title:"Weekly Reels",children:e.jsx("div",{className:"program-theme-neon relative min-h-screen",children:e.jsxs("div",{className:"relative mx-auto w-full max-w-5xl px-4 py-8 sm:px-6",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"neon-eyebrow font-semibold",children:"Weekly Reels"}),e.jsxs("h1",{className:"neon-title mt-2 w-fit text-3xl font-black uppercase tracking-tight sm:text-4xl",children:["Welcome back, ",v]}),e.jsx("p",{className:"mt-2 text-[15px] text-muted-foreground",children:"Your Reels for the week, written around your market and your voice."})]}),e.jsxs($,{variant:"outline",onClick:()=>s("/weekly-reels/onboarding"),children:[e.jsx(eM,{className:"h-4 w-4 mr-2"})," Edit my profile"]})]}),e.jsxs(we,{className:"mt-6 p-5 sm:p-6",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-4",children:[e.jsx(vie,{icon:Gr,label:"Onboarding",value:_?"Complete":"Incomplete"}),e.jsx(vie,{icon:Bz,label:"Weekly delivery",value:(U=n.data)!=null&&U.delivery_active?"Active":"Paused"}),e.jsx(vie,{icon:wm,label:"Next pack",value:Cwt()}),e.jsx(vie,{icon:pn,label:"Email this week",value:(a==null?void 0:a.delivery_status)==="sent"?"Delivered":(a==null?void 0:a.delivery_status)==="failed"?"Failed":"Scheduled"})]}),e.jsxs("div",{className:"mt-5 flex flex-wrap items-center justify-between gap-3 border-t border-border/60 pt-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(On,{checked:!!((G=n.data)!=null&&G.delivery_active),onCheckedChange:H=>i.mutate({delivery_active:H}),"aria-label":"Weekly email delivery"}),e.jsx("span",{className:"text-[14px] text-muted-foreground",children:"Email me my pack every Monday at 9:00 AM ET"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[a&&a.reels.length?e.jsxs($,{variant:"outline",size:"sm",onClick:I,disabled:d,children:[d?e.jsx(Jt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(pn,{className:"h-4 w-4 mr-2"}),"Email me this week's pack"]}):null,e.jsxs($,{size:"sm",className:"neon-cta",onClick:M,disabled:o,children:[o?e.jsx(Jt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(kn,{className:"h-4 w-4 mr-2"}),a&&a.reels.length?"Regenerate this week":"Generate this week's pack"]})]})]})]}),e.jsxs(ya,{defaultValue:"current",className:"mt-8",children:[e.jsxs(va,{children:[e.jsx(is,{value:"current",children:"This week"}),e.jsx(is,{value:"history",children:"History"}),e.jsxs(is,{value:"saved",children:["Saved",A.length?` (${A.length})`:""]})]}),e.jsx(cs,{value:"current",className:"mt-6",children:r.isLoading?e.jsx("div",{className:"flex justify-center py-16",children:e.jsx(Jt,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):a&&a.reels.length?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"mb-4 flex flex-wrap items-center gap-2",children:[e.jsxs(qe,{variant:"outline",className:"text-[11.5px]",children:["Week of ",mZ(a.week_start_date)]}),e.jsxs("span",{className:"text-[13px] text-muted-foreground",children:[a.reels.filter(H=>H.posted_at).length," of ",a.reels.length," posted"]})]}),e.jsx("div",{className:"space-y-4",children:a.reels.map((H,Y)=>e.jsx(_ke,{reel:H,index:Y,onUpdate:P(H)},H.id))})]}):e.jsxs(we,{className:"neon-topline p-10 text-center sm:p-14",children:[e.jsx("div",{className:"mx-auto flex h-12 w-12 items-center justify-center rounded-xl bg-muted",children:e.jsx(em,{className:"h-6 w-6 text-muted-foreground"})}),e.jsx("h3",{className:"mt-5 text-lg font-semibold text-foreground",children:"This week's pack isn't ready yet"}),e.jsxs("p",{className:"mx-auto mt-2 max-w-sm text-[14.5px] leading-relaxed text-muted-foreground",children:["Packs land every Monday at 9:00 AM Eastern, and we email them to you the moment they're written. Next delivery: ",Cwt(),". Don't want to wait? Write them now."]}),e.jsxs($,{className:"neon-cta mt-6",onClick:M,disabled:o,children:[o?e.jsx(Jt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(kn,{className:"h-4 w-4 mr-2"}),"Generate it now"]})]})}),e.jsxs(cs,{value:"history",className:"mt-6",children:[e.jsx(we,{className:"rounded-2xl p-4 sm:p-5",children:e.jsxs("div",{className:"grid gap-3 sm:grid-cols-[1fr_auto_auto]",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Yr,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(be,{value:h,onChange:H=>m(H.target.value),placeholder:"Search topics and scripts...",className:"pl-9"})]}),e.jsxs(bs,{value:p,onValueChange:g,children:[e.jsx(ys,{className:"sm:w-[190px]",children:e.jsx(_s,{placeholder:"All topics"})}),e.jsxs(vs,{children:[e.jsx(We,{value:"all",children:"All topics"}),Object.entries(Eqe).map(([H,Y])=>e.jsx(We,{value:H,children:Y},H))]})]}),e.jsxs(bs,{value:x,onValueChange:y,children:[e.jsx(ys,{className:"sm:w-[180px]",children:e.jsx(_s,{placeholder:"All weeks"})}),e.jsxs(vs,{children:[e.jsx(We,{value:"all",children:"All weeks"}),(r.data??[]).map(H=>e.jsx(We,{value:H.week_start_date,children:mZ(H.week_start_date)},H.id))]})]})]})}),C.length?e.jsx(SF,{type:"multiple",className:"mt-4 space-y-3",children:C.map(({reel:H,pack:Y})=>e.jsxs(r6,{value:H.id,className:"rounded-2xl border border-border/70 bg-card px-4 sm:px-5",children:[e.jsx(a6,{className:"py-4 hover:no-underline",children:e.jsxs("div",{className:"flex min-w-0 flex-1 flex-wrap items-center gap-2 pr-3 text-left",children:[e.jsx(qe,{variant:"outline",className:"text-[10.5px] shrink-0",children:mZ(Y.week_start_date)}),H.category?e.jsx(qe,{className:"bg-muted text-muted-foreground border-0 text-[10.5px] shrink-0",children:Eqe[H.category]??H.category}):null,e.jsx("span",{className:"truncate text-[14.5px] font-medium text-foreground",children:H.topic})]})}),e.jsx(i6,{className:"pb-4",children:e.jsx(_ke,{reel:H,index:H.position-1,onUpdate:P(H)})})]},H.id))}):e.jsxs(we,{className:"mt-4 rounded-2xl p-10 text-center sm:p-14",children:[e.jsx("div",{className:"mx-auto flex h-12 w-12 items-center justify-center rounded-xl bg-muted",children:e.jsx(Yr,{className:"h-6 w-6 text-muted-foreground"})}),e.jsx("h3",{className:"mt-5 text-lg font-semibold text-foreground",children:"Nothing here yet"}),e.jsx("p",{className:"mx-auto mt-2 max-w-sm text-[14.5px] text-muted-foreground",children:j.length?"No Reels match these filters. Try widening your search.":"Your past packs will collect here once a few weeks have gone by."})]})]}),e.jsx(cs,{value:"saved",className:"mt-6",children:A.length?e.jsx("div",{className:"space-y-4",children:A.map(({reel:H},Y)=>e.jsx(_ke,{reel:H,index:Y,onUpdate:P(H)},H.id))}):e.jsxs(we,{className:"rounded-2xl p-10 text-center sm:p-14",children:[e.jsx("div",{className:"mx-auto flex h-12 w-12 items-center justify-center rounded-xl bg-muted",children:e.jsx(ri,{className:"h-6 w-6 text-muted-foreground"})}),e.jsx("h3",{className:"mt-5 text-lg font-semibold text-foreground",children:"No saved Reels yet"}),e.jsx("p",{className:"mx-auto mt-2 max-w-sm text-[14.5px] text-muted-foreground",children:"Tap the star on any Reel to keep it here — handy for the ones you want to film again next quarter."})]})})]})]})})})}const yP=[{id:"about",title:"About you",blurb:"The basics we put on every script."},{id:"business",title:"Your business",blurb:"Who you serve and where you serve them."},{id:"voice",title:"Your voice",blurb:"So the scripts sound like you, not a robot."},{id:"content",title:"Content preferences",blurb:"Format, length and the ask at the end."},{id:"goals",title:"Goals & compliance",blurb:"What we drive toward, and what we avoid."}];function cHn(){const s=Jn(),{user:t}=ks(),{profile:n,saveProfile:r}=lJe(),[a,i]=k.useState(0),[l,o]=k.useState({specialties:[],client_types:[],brand_voice:[],preferred_reel_length:"30-45s",main_platform:"instagram",content_mix:"mix"}),[c,d]=k.useState(!1),[u,h]=k.useState(!1);k.useEffect(()=>{u||n.isLoading||(o(_=>{var j,C,A,M,I,P;return{..._,...n.data??{},full_name:((j=n.data)==null?void 0:j.full_name)??((C=t==null?void 0:t.user_metadata)==null?void 0:C.full_name)??"",email:((A=n.data)==null?void 0:A.email)??(t==null?void 0:t.email)??"",specialties:((M=n.data)==null?void 0:M.specialties)??[],client_types:((I=n.data)==null?void 0:I.client_types)??[],brand_voice:((P=n.data)==null?void 0:P.brand_voice)??[]}}),h(!0))},[n.isLoading,n.data,t,u]);const m=(_,j)=>o(C=>({...C,[_]:j})),p=(_,j)=>o(C=>{const A=C[_]??[];return{...C,[_]:A.includes(j)?A.filter(M=>M!==j):[...A,j]}}),g=k.useMemo(()=>{var _,j,C;return a===0?!!((_=l.full_name)!=null&&_.trim())&&!!((j=l.email)!=null&&j.trim()):a===1?!!((C=l.primary_market)!=null&&C.trim()):a===2?(l.brand_voice??[]).length>0:!0},[a,l]),x=async(_,j)=>{if(t){d(!0);try{const C=_.name.split(".").pop(),A=`${t.id}/weekly-reels-${j}-${Date.now()}.${C}`,{error:M}=await V.storage.from("avatars").upload(A,_,{upsert:!0});if(M)throw M;const{data:I}=V.storage.from("avatars").getPublicUrl(A);m(j,I.publicUrl),ae.success("Image uploaded")}catch(C){ae.error(C instanceof Error?C.message:"Upload failed")}finally{d(!1)}}},y=async()=>{await r.mutateAsync({...l,onboarding_completed:!0}),ae.success("You're all set — your first pack is on the way."),s("/weekly-reels")},v=async()=>{await r.mutateAsync(l),ae.success("Progress saved")};return e.jsx(Xs,{title:"Weekly Reels",children:e.jsx("div",{className:"program-theme-neon relative min-h-screen",children:e.jsxs("div",{className:"relative mx-auto w-full max-w-3xl px-4 py-8 sm:px-6",children:[e.jsxs("div",{className:"mb-8",children:[e.jsx("p",{className:"neon-eyebrow font-semibold",children:"Weekly Reels"}),e.jsx("h1",{className:"neon-title mt-2 w-fit text-3xl font-black uppercase tracking-tight sm:text-4xl",children:"Let's make these scripts sound like you"}),e.jsx("p",{className:"mt-2 text-[15px] leading-relaxed text-muted-foreground",children:"Five minutes now means every Monday you get 5 Reels built around your market, your niche and your personality — not generic real estate filler."})]}),e.jsxs("div",{className:"mb-6",children:[e.jsxs("div",{className:"flex items-center justify-between text-[12.5px] font-medium text-muted-foreground",children:[e.jsxs("span",{children:["Step ",a+1," of ",yP.length," · ",yP[a].title]}),e.jsxs("span",{className:"neon-stat font-black",children:[Math.round((a+1)/yP.length*100),"%"]})]}),e.jsx(ho,{value:(a+1)/yP.length*100,className:"mt-2 h-1.5"})]}),e.jsxs(we,{className:"neon-topline rounded-2xl p-5 sm:p-7",children:[e.jsx("h2",{className:"text-lg font-semibold tracking-tight text-foreground",children:yP[a].title}),e.jsx("p",{className:"mt-1 text-[14px] text-muted-foreground",children:yP[a].blurb}),e.jsxs("div",{className:"mt-6 space-y-5",children:[a===0&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Full name *"}),e.jsx(be,{value:l.full_name??"",onChange:_=>m("full_name",_.target.value),placeholder:"Jane Realtor"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Email *"}),e.jsx(be,{type:"email",value:l.email??"",onChange:_=>m("email",_.target.value),placeholder:"jane@brokerage.com"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Mobile number"}),e.jsx(be,{value:l.mobile_number??"",onChange:_=>m("mobile_number",_.target.value),placeholder:"Optional"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Brokerage"}),e.jsx(be,{value:l.brokerage??"",onChange:_=>m("brokerage",_.target.value)})]})]}),e.jsx("div",{className:"grid gap-4 sm:grid-cols-2",children:["headshot_url","logo_url"].map(_=>e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(re,{children:[_==="headshot_url"?"Headshot":"Logo"," (optional)"]}),e.jsxs("div",{className:"flex items-center gap-3",children:[l[_]?e.jsx("img",{src:l[_],alt:_==="headshot_url"?"Your headshot":"Your logo",className:"h-12 w-12 rounded-lg object-cover"}):null,e.jsxs("label",{className:"flex-1",children:[e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:j=>{var A;const C=(A=j.target.files)==null?void 0:A[0];C&&x(C,_)}}),e.jsxs("span",{className:"flex h-10 cursor-pointer items-center justify-center gap-2 rounded-md border border-input text-[13.5px] text-muted-foreground hover:bg-accent",children:[c?e.jsx(Jt,{className:"h-4 w-4 animate-spin"}):e.jsx(gi,{className:"h-4 w-4"}),"Upload"]})]})]})]},_))})]}),a===1&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Primary market — city & state *"}),e.jsx(be,{value:l.primary_market??"",onChange:_=>m("primary_market",_.target.value),placeholder:"Tulsa, OK"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Neighborhoods or service areas"}),e.jsx(Ls,{rows:2,value:l.service_areas??"",onChange:_=>m("service_areas",_.target.value),placeholder:"Jenks, Bixby, Broken Arrow, midtown Tulsa"})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Years in real estate"}),e.jsxs(bs,{value:l.years_in_real_estate??"",onValueChange:_=>m("years_in_real_estate",_),children:[e.jsx(ys,{children:e.jsx(_s,{placeholder:"Select"})}),e.jsx(vs,{children:sHn.map(_=>e.jsx(We,{value:_,children:_},_))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Typical price point"}),e.jsxs(bs,{value:l.typical_price_point??"",onValueChange:_=>m("typical_price_point",_),children:[e.jsx(ys,{children:e.jsx(_s,{placeholder:"Select"})}),e.jsx(vs,{children:tHn.map(_=>e.jsx(We,{value:_,children:_},_))})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Primary specialties / niches"}),e.jsx("div",{className:"grid gap-2 sm:grid-cols-2",children:XVn.map(_=>e.jsxs("label",{className:"flex items-center gap-2.5 text-[14px]",children:[e.jsx(Li,{checked:(l.specialties??[]).includes(_),onCheckedChange:()=>p("specialties",_)}),_]},_))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Client types you serve"}),e.jsx("div",{className:"grid gap-2 sm:grid-cols-2",children:QVn.map(_=>e.jsxs("label",{className:"flex items-center gap-2.5 text-[14px]",children:[e.jsx(Li,{checked:(l.client_types??[]).includes(_),onCheckedChange:()=>p("client_types",_)}),_]},_))})]})]}),a===2&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Brand voice — pick everything that fits *"}),e.jsx("div",{className:"grid gap-2 sm:grid-cols-2",children:JVn.map(_=>e.jsxs("label",{className:"flex items-center gap-2.5 text-[14px]",children:[e.jsx(Li,{checked:(l.brand_voice??[]).includes(_),onCheckedChange:()=>p("brand_voice",_)}),_]},_))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Anything else about how you talk?"}),e.jsx(Ls,{rows:2,value:l.brand_voice_notes??"",onChange:_=>m("brand_voice_notes",_.target.value),placeholder:"I say 'y'all' a lot and I hate corporate jargon."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Humor level"}),e.jsx(m_,{value:l.humor_level??"",onValueChange:_=>m("humor_level",_),className:"space-y-1.5",children:eHn.map(_=>e.jsxs("label",{className:"flex items-center gap-2.5 text-[14px]",children:[e.jsx(Yh,{value:_.value}),_.label]},_.value))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Personal interests & hobbies"}),e.jsx(Ls,{rows:2,value:l.personal_interests??"",onChange:_=>m("personal_interests",_.target.value),placeholder:"Golf, smoking brisket, coaching my son's baseball team"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Family or community details you're happy to reference"}),e.jsx(Ls,{rows:2,value:l.family_community_notes??"",onChange:_=>m("family_community_notes",_.target.value),placeholder:"Married with two kids, active in the Jenks chamber"})]})]}),a===3&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Preferred Reel length"}),e.jsxs(bs,{value:l.preferred_reel_length??"30-45s",onValueChange:_=>m("preferred_reel_length",_),children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsx(vs,{children:aHn.map(_=>e.jsx(We,{value:_.value,children:_.label},_.value))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Preferred CTA style"}),e.jsxs(bs,{value:l.preferred_cta_style??"",onValueChange:_=>m("preferred_cta_style",_),children:[e.jsx(ys,{children:e.jsx(_s,{placeholder:"Select"})}),e.jsx(vs,{children:nHn.map(_=>e.jsx(We,{value:_.value,children:_.label},_.value))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Main social platform"}),e.jsxs(bs,{value:l.main_platform??"instagram",onValueChange:_=>m("main_platform",_),children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsx(vs,{children:rHn.map(_=>e.jsx(We,{value:_.value,children:_.label},_.value))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Instagram handle"}),e.jsx(be,{value:l.instagram_handle??"",onChange:_=>m("instagram_handle",_.target.value),placeholder:"@janerealtor"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Website"}),e.jsx(be,{value:l.website??"",onChange:_=>m("website",_.target.value),placeholder:"https://janerealtor.com"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"On-camera comfort level"}),e.jsx(m_,{value:l.content_comfort_level??"",onValueChange:_=>m("content_comfort_level",_),className:"space-y-1.5",children:iHn.map(_=>e.jsxs("label",{className:"flex items-center gap-2.5 text-[14px]",children:[e.jsx(Yh,{value:_.value}),_.label]},_.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Local vs evergreen content"}),e.jsx(m_,{value:l.content_mix??"mix",onValueChange:_=>m("content_mix",_),className:"space-y-1.5",children:oHn.map(_=>e.jsxs("label",{className:"flex items-center gap-2.5 text-[14px]",children:[e.jsx(Yh,{value:_.value}),_.label]},_.value))})]})]}),a===4&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Topics you love talking about"}),e.jsx(Ls,{rows:2,value:l.topics_enjoyed??"",onChange:_=>m("topics_enjoyed",_.target.value),placeholder:"Renovation ROI, negotiating repairs, small-town living"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Topics you never want to cover"}),e.jsx(Ls,{rows:2,value:l.topics_avoided??"",onChange:_=>m("topics_avoided",_.target.value),placeholder:"Politics, interest rate predictions, dancing trends"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Lead magnets or offers to promote"}),e.jsx(Ls,{rows:2,value:l.lead_magnets??"",onChange:_=>m("lead_magnets",_.target.value),placeholder:"Free home value report, first-time buyer guide"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Current business goals"}),e.jsx(Ls,{rows:2,value:l.business_goals??"",onChange:_=>m("business_goals",_.target.value),placeholder:"Two listings a month and more sphere referrals"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Compliance or brokerage disclaimer notes"}),e.jsx(Ls,{rows:2,value:l.compliance_notes??"",onChange:_=>m("compliance_notes",_.target.value),placeholder:"Must include brokerage name on any listing content"})]})]})]}),e.jsxs("div",{className:"mt-8 flex flex-wrap items-center justify-between gap-3",children:[e.jsxs($,{type:"button",variant:"ghost",disabled:a===0,onClick:()=>i(_=>Math.max(0,_-1)),children:[e.jsx(Ia,{className:"h-4 w-4 mr-1.5"})," Back"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx($,{type:"button",variant:"outline",onClick:v,disabled:r.isPending,children:"Save draft"}),ai(_=>_+1),children:["Continue ",e.jsx(xi,{className:"h-4 w-4 ml-1.5"})]}):e.jsxs($,{className:"neon-cta",type:"button",onClick:y,disabled:r.isPending,children:[r.isPending?e.jsx(Jt,{className:"h-4 w-4 mr-1.5 animate-spin"}):e.jsx(ma,{className:"h-4 w-4 mr-1.5"}),"Finish setup"]})]})]})]})]})})})}function mWt(s,t=!1){const{user:n}=ks(),r=ls(),a=pt({queryKey:["wr-admin-members",s,t,n==null?void 0:n.id],enabled:!!n,queryFn:async()=>{let x=null;if(t){const{data:O,error:B}=await V.from("feature_entitlements").select("user_id").eq("feature_key",dz).eq("enabled",!0);if(B)throw B;if(x=(O??[]).map(U=>U.user_id),!x.length)return[]}let y=V.from("profiles").select("id, email, name").order("name",{ascending:!0}).limit(t?1e3:100);if(x&&(y=y.in("id",x)),s.trim()){const O=`%${s.trim()}%`;y=y.or(`email.ilike.${O},name.ilike.${O}`)}const{data:v,error:_}=await y;if(_)throw _;const j=(v??[]).map(O=>O.id);if(!j.length)return[];const[{data:C},{data:A},{data:M}]=await Promise.all([V.from("feature_entitlements").select("user_id, enabled, tier, expires_at").eq("feature_key",dz).in("user_id",j),V.from("weekly_reel_profiles").select("user_id, onboarding_completed, delivery_active, primary_market").in("user_id",j),V.from("weekly_reel_packs").select("id, user_id, week_start_date, generation_status, delivery_status").in("user_id",j).order("week_start_date",{ascending:!1})]),I=new Map((C??[]).map(O=>[O.user_id,O])),P=new Map((A??[]).map(O=>[O.user_id,O])),R=new Map;return(M??[]).forEach(O=>{R.has(O.user_id)||R.set(O.user_id,O)}),(v??[]).map(O=>{const B=I.get(O.id),U=P.get(O.id),G=R.get(O.id);return{user_id:O.id,email:O.email,full_name:O.name,enabled:!!(B!=null&&B.enabled),tier:(B==null?void 0:B.tier)??null,expires_at:(B==null?void 0:B.expires_at)??null,onboarded:!!(U!=null&&U.onboarding_completed),delivery_active:(U==null?void 0:U.delivery_active)??!1,primary_market:(U==null?void 0:U.primary_market)??null,latest_week:(G==null?void 0:G.week_start_date)??null,latest_pack_id:(G==null?void 0:G.id)??null,latest_generation_status:(G==null?void 0:G.generation_status)??null,latest_delivery_status:(G==null?void 0:G.delivery_status)??null}})}}),i=pt({queryKey:["wr-admin-generation-logs"],enabled:!!n,queryFn:async()=>{const{data:x,error:y}=await V.from("weekly_reel_generation_logs").select("*").order("created_at",{ascending:!1}).limit(100);if(y)throw y;return x??[]}}),l=pt({queryKey:["wr-admin-delivery-logs"],enabled:!!n,queryFn:async()=>{const{data:x,error:y}=await V.from("weekly_reel_delivery_logs").select("*").order("created_at",{ascending:!1}).limit(100);if(y)throw y;return x??[]}}),o=()=>{r.invalidateQueries({queryKey:["wr-admin-members"]}),r.invalidateQueries({queryKey:["wr-admin-generation-logs"]}),r.invalidateQueries({queryKey:["wr-admin-delivery-logs"]})},c=Nt({mutationFn:async({userId:x,enabled:y})=>{const{error:v}=await V.from("feature_entitlements").upsert({user_id:x,feature_key:dz,enabled:y,tier:"member",enabled_by:n.id,enabled_at:new Date().toISOString()},{onConflict:"user_id,feature_key"});if(v)throw v;await V.from("feature_entitlement_audit").insert({feature_key:dz,target_user_id:x,action:y?"grant":"revoke",performed_by:n.id})},onSuccess:(x,y)=>{o(),ae.success(y.enabled?"Access granted":"Access revoked")},onError:x=>ae.error(x.message)}),d=async x=>{const{data:y,error:v}=await V.functions.invoke("weekly-reels-generate",{body:x});if(v)throw v;if(y!=null&&y.error)throw new Error(String(y.error));return y},u=Nt({mutationFn:x=>d({action:"generate_pack",userId:x.userId,force:x.force??!0}),onSuccess:()=>{o(),ae.success("Pack generated")},onError:x=>ae.error(x.message)}),h=Nt({mutationFn:x=>d({action:"regenerate_reel",reelId:x.reelId,instructions:x.instructions}),onSuccess:()=>{o(),ae.success("Reel regenerated")},onError:x=>ae.error(x.message)}),m=Nt({mutationFn:x=>d({action:"send_pack_email",packId:x.packId}),onSuccess:()=>{o(),ae.success("Pack emailed")},onError:x=>ae.error(x.message)}),p=Nt({mutationFn:x=>d({action:"send_test_email",packId:x.packId,to:x.to}),onSuccess:()=>ae.success("Test email sent"),onError:x=>ae.error(x.message)}),g=Nt({mutationFn:()=>d({action:"run_weekly"}),onSuccess:x=>{o(),ae.success(`Weekly run complete${(x==null?void 0:x.processed)!=null?` — ${x.processed} agents`:""}`)},onError:x=>ae.error(x.message)});return{members:a,generationLogs:i,deliveryLogs:l,setAccess:c,generatePack:u,regenerateReel:h,sendPack:m,sendTest:p,runWeekly:g}}function Ez({value:s}){if(!s)return e.jsx("span",{className:"text-muted-foreground",children:"—"});const t=s==="complete"||s==="sent"?"bg-emerald-100 text-emerald-800":s==="failed"?"bg-red-100 text-red-800":"bg-amber-100 text-amber-800";return e.jsx(qe,{className:`${t} border-0 text-[11px] capitalize`,children:s})}function dHn({member:s,onClose:t}){var m,p,g;const n=mWt(""),{packs:r,profile:a}=lJe(s==null?void 0:s.user_id),[i,l]=k.useState(""),[o,c]=k.useState(""),[d,u]=k.useState(null),h=((m=r.data)==null?void 0:m[0])??null;return e.jsx(zs,{open:!!s,onOpenChange:x=>!x&&t(),children:e.jsxs(Rs,{className:"max-w-3xl max-h-[88vh] overflow-y-auto",children:[e.jsxs(Vs,{children:[e.jsx($s,{children:(s==null?void 0:s.full_name)||(s==null?void 0:s.email)}),e.jsxs(Cr,{children:[((p=a.data)==null?void 0:p.primary_market)??"No market on file"," ·"," ",(g=a.data)!=null&&g.onboarding_completed?"Onboarded":"Onboarding incomplete"]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs($,{size:"sm",onClick:()=>s&&n.generatePack.mutate({userId:s.user_id}),disabled:n.generatePack.isPending,children:[n.generatePack.isPending?e.jsx(Jt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(kn,{className:"h-4 w-4 mr-2"}),"Generate pack"]}),e.jsxs($,{size:"sm",variant:"outline",disabled:!h||n.sendPack.isPending,onClick:()=>h&&n.sendPack.mutate({packId:h.id}),children:[e.jsx(pn,{className:"h-4 w-4 mr-2"})," Email latest pack"]})]}),e.jsxs("div",{className:"flex flex-wrap items-end gap-2 rounded-xl bg-muted/60 p-3",children:[e.jsxs("div",{className:"flex-1 min-w-[200px] space-y-1.5",children:[e.jsx(re,{className:"text-[12px]",children:"Send a test copy to"}),e.jsx(be,{value:i,onChange:x=>l(x.target.value),placeholder:"you@relevelup.com"})]}),e.jsxs($,{size:"sm",variant:"outline",disabled:!h||!i||n.sendTest.isPending,onClick:()=>h&&n.sendTest.mutate({packId:h.id,to:i}),children:[e.jsx(Wr,{className:"h-4 w-4 mr-2"})," Send test"]})]}),h?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-[13px] text-muted-foreground",children:[e.jsxs(qe,{variant:"outline",children:["Week of ",mZ(h.week_start_date)]}),e.jsx(Ez,{value:h.generation_status}),e.jsx(Ez,{value:h.delivery_status})]}),h.reels.map((x,y)=>e.jsxs("div",{className:"space-y-2",children:[e.jsx(_ke,{reel:x,index:y,readOnly:!0}),d===x.id?e.jsxs("div",{className:"rounded-xl border border-border/70 p-3 space-y-2",children:[e.jsx(Ls,{rows:2,value:o,onChange:v=>c(v.target.value),placeholder:"Optional guidance: make it more local, less salesy, focus on sellers..."}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs($,{size:"sm",disabled:n.regenerateReel.isPending,onClick:()=>n.regenerateReel.mutate({reelId:x.id,instructions:o||void 0},{onSuccess:()=>{u(null),c(""),r.refetch()}}),children:[n.regenerateReel.isPending?e.jsx(Jt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(yo,{className:"h-4 w-4 mr-2"}),"Regenerate"]}),e.jsx($,{size:"sm",variant:"ghost",onClick:()=>u(null),children:"Cancel"})]})]}):e.jsxs($,{size:"sm",variant:"outline",onClick:()=>u(x.id),children:[e.jsx(yo,{className:"h-4 w-4 mr-2"})," Regenerate this reel"]})]},x.id))]}):e.jsx("p",{className:"py-6 text-center text-[14px] text-muted-foreground",children:"No packs generated for this agent yet."}),e.jsx(kr,{children:e.jsx($,{variant:"outline",onClick:t,children:"Close"})})]})})}function uHn(){const[s,t]=k.useState(""),[n,r]=k.useState(!1),[a,i]=k.useState(null),l=mWt(s,n),o=k.useMemo(()=>l.members.data??[],[l.members.data]);return e.jsxs(Xs,{title:"Weekly Reels Admin",children:[e.jsxs("div",{className:"mx-auto w-full max-w-6xl px-4 py-8 sm:px-6",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-semibold tracking-tight text-foreground",children:"Weekly Reels"}),e.jsx("p",{className:"mt-1.5 text-[15px] text-muted-foreground",children:"Manage access, generate packs and monitor Monday delivery."})]}),e.jsxs($,{onClick:()=>l.runWeekly.mutate(),disabled:l.runWeekly.isPending,children:[l.runWeekly.isPending?e.jsx(Jt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(kn,{className:"h-4 w-4 mr-2"}),"Run this week now"]})]}),e.jsxs(ya,{defaultValue:"members",className:"mt-7",children:[e.jsxs(va,{children:[e.jsx(is,{value:"members",children:"Members"}),e.jsx(is,{value:"generation",children:"Generation log"}),e.jsx(is,{value:"delivery",children:"Delivery log"})]}),e.jsxs(cs,{value:"members",className:"mt-5",children:[e.jsx(we,{className:"rounded-2xl p-4 sm:p-5",children:e.jsxs("div",{className:"flex flex-wrap items-center gap-4",children:[e.jsxs("div",{className:"relative min-w-[220px] flex-1",children:[e.jsx(Yr,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(be,{value:s,onChange:c=>t(c.target.value),placeholder:"Search by name or email...",className:"pl-9"})]}),e.jsxs("label",{className:"flex items-center gap-2.5 text-[14px] text-muted-foreground",children:[e.jsx(On,{checked:n,onCheckedChange:r}),"Only members with access"]})]})}),e.jsx(we,{className:"mt-4 rounded-2xl overflow-hidden",children:e.jsxs(Qa,{children:[e.jsx(Ja,{children:e.jsxs(vn,{children:[e.jsx(Dt,{children:"Agent"}),e.jsx(Dt,{children:"Market"}),e.jsx(Dt,{children:"Onboarded"}),e.jsx(Dt,{children:"Latest week"}),e.jsx(Dt,{children:"Generation"}),e.jsx(Dt,{children:"Delivery"}),e.jsx(Dt,{className:"text-right",children:"Access"}),e.jsx(Dt,{})]})}),e.jsx(ei,{children:l.members.isLoading?e.jsx(vn,{children:e.jsx(_t,{colSpan:8,className:"py-10 text-center",children:e.jsx(Jt,{className:"mx-auto h-5 w-5 animate-spin text-muted-foreground"})})}):o.length?o.map(c=>e.jsxs(vn,{children:[e.jsxs(_t,{children:[e.jsx("div",{className:"font-medium text-foreground",children:c.full_name||"—"}),e.jsx("div",{className:"text-[12.5px] text-muted-foreground",children:c.email})]}),e.jsx(_t,{className:"text-[13.5px] text-muted-foreground",children:c.primary_market||"—"}),e.jsx(_t,{children:c.onboarded?e.jsx(qe,{className:"bg-emerald-100 text-emerald-800 border-0 text-[11px]",children:"Yes"}):e.jsx("span",{className:"text-muted-foreground",children:"No"})}),e.jsx(_t,{className:"text-[13.5px] text-muted-foreground",children:c.latest_week?mZ(c.latest_week):"—"}),e.jsx(_t,{children:e.jsx(Ez,{value:c.latest_generation_status})}),e.jsx(_t,{children:e.jsx(Ez,{value:c.latest_delivery_status})}),e.jsx(_t,{className:"text-right",children:e.jsx(On,{checked:c.enabled,onCheckedChange:d=>l.setAccess.mutate({userId:c.user_id,enabled:d}),"aria-label":`Weekly Reels access for ${c.full_name||c.email}`})}),e.jsx(_t,{className:"text-right",children:e.jsx($,{size:"sm",variant:"ghost",onClick:()=>i(c),children:"Manage"})})]},c.user_id)):e.jsx(vn,{children:e.jsx(_t,{colSpan:8,className:"py-10 text-center text-muted-foreground",children:"No members match this search."})})})]})})]}),e.jsx(cs,{value:"generation",className:"mt-5",children:e.jsx(we,{className:"rounded-2xl overflow-hidden",children:e.jsxs(Qa,{children:[e.jsx(Ja,{children:e.jsxs(vn,{children:[e.jsx(Dt,{children:"When"}),e.jsx(Dt,{children:"Status"}),e.jsx(Dt,{children:"Model"}),e.jsx(Dt,{children:"Tokens"}),e.jsx(Dt,{children:"Cost"}),e.jsx(Dt,{children:"Error"})]})}),e.jsx(ei,{children:(l.generationLogs.data??[]).map(c=>e.jsxs(vn,{children:[e.jsx(_t,{className:"text-[13px]",children:new Date(c.created_at).toLocaleString("en-US",{timeZone:"America/New_York"})}),e.jsx(_t,{children:e.jsx(Ez,{value:c.status})}),e.jsx(_t,{className:"text-[13px] text-muted-foreground",children:c.model??"—"}),e.jsx(_t,{className:"text-[13px]",children:c.total_tokens??0}),e.jsxs(_t,{className:"text-[13px]",children:["$",Number(c.estimated_cost??0).toFixed(4)]}),e.jsx(_t,{className:"max-w-[280px] truncate text-[12.5px] text-muted-foreground",children:c.error_message??"—"})]},c.id))})]})})}),e.jsx(cs,{value:"delivery",className:"mt-5",children:e.jsx(we,{className:"rounded-2xl overflow-hidden",children:e.jsxs(Qa,{children:[e.jsx(Ja,{children:e.jsxs(vn,{children:[e.jsx(Dt,{children:"When"}),e.jsx(Dt,{children:"Recipient"}),e.jsx(Dt,{children:"Status"}),e.jsx(Dt,{children:"Error"})]})}),e.jsx(ei,{children:(l.deliveryLogs.data??[]).map(c=>e.jsxs(vn,{children:[e.jsx(_t,{className:"text-[13px]",children:new Date(c.created_at).toLocaleString("en-US",{timeZone:"America/New_York"})}),e.jsx(_t,{className:"text-[13px]",children:c.recipient_email??"—"}),e.jsx(_t,{children:e.jsx(Ez,{value:c.status})}),e.jsx(_t,{className:"max-w-[280px] truncate text-[12.5px] text-muted-foreground",children:c.failure_reason??"—"})]},c.id))})]})})})]})]}),e.jsx(dHn,{member:a,onClose:()=>i(null)})]})}function KV(){const{user:s}=ks(),t=ls(),n=pt({queryKey:["attract-settings",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:i,error:l}=await V.from("attract_settings").select("*").eq("user_id",s.id).maybeSingle();if(l)throw l;return i}}),r=Nt({mutationFn:async i=>{const l={...i,user_id:s.id},{data:o,error:c}=await V.from("attract_settings").upsert(l,{onConflict:"user_id"}).select().single();if(c)throw c;return o},onSuccess:()=>{t.invalidateQueries({queryKey:["attract-settings"]}),ae.success("Settings saved")},onError:i=>ae.error(i.message)}),a=Nt({mutationFn:async()=>{const{error:i}=await V.from("attract_settings").update({onboarding_completed_at:null}).eq("user_id",s.id);if(i)throw i},onSuccess:()=>{t.invalidateQueries({queryKey:["attract-settings"]}),ae.success("Onboarding reset — run it again anytime")}});return{settings:n.data,isLoading:n.isLoading,save:r,upsert:r,resetOnboarding:a}}const fWt="v1",cm={recency:22,consistency:16,value_delivered:14,kit_engagement:16,event_participation:12,follow_up_discipline:10,pipeline_momentum:10};Object.values(cm).reduce((s,t)=>s+t,0);const pWt=864e5,hy=(s,t=new Date)=>Math.floor((new Date(t).getTime()-new Date(s).getTime())/pWt),gWt=["touch_logged","call","text","email","dm","meeting","note"];function hHn(s,t,n=new Date){var x,y,v;const a=t.activities.filter(_=>_.agent_id===s.id).filter(_=>gWt.includes(_.activity_type)).sort((_,j)=>+new Date(j.created_at)-+new Date(_.created_at)),i=s.last_touch_at||((x=a[0])==null?void 0:x.created_at)||null,l=t.shares.filter(_=>_.agent_id===s.id),o=new Set(l.map(_=>_.id)),c=t.kitEvents.filter(_=>o.has(_.share_id)),d={};for(const _ of l)d[_.id]=[];for(const _ of c)(d[y=_.share_id]||(d[y]=[])).push(_);const u=t.attendees.filter(_=>_.agent_id===s.id),h=t.followUps.filter(_=>_.agent_id===s.id),m=h.filter(_=>!_.completed_at),p=t.stageChanges.filter(_=>_.agent_id===s.id).sort((_,j)=>+new Date(j.created_at)-+new Date(_.created_at)),g=new Set(a.filter(_=>hy(_.created_at,n)<=180).map(_=>_.created_at.slice(0,7)));return{agent:s,touches:a,lastTouchAt:i,daysSinceTouch:i?hy(i,n):null,touches90:a.filter(_=>hy(_.created_at,n)<=90).length,touches30:a.filter(_=>hy(_.created_at,n)<=30).length,distinctTouchMonths:g.size,shares:l,shareEvents:d,highIntentShares:l.filter(_=>_.engagement_level==="high_intent"||_.engagement_level==="engaged"),lastShareAt:l.map(_=>_.created_at).sort().reverse()[0]||null,totalKitOpens:l.reduce((_,j)=>_+(j.open_count||0),0),downloads:c.filter(_=>_.event_type==="file_download").length,ctaClicks:c.filter(_=>_.event_type==="primary_cta_click"||_.event_type==="external_link_click").length,questions:c.filter(_=>_.event_type==="question_submitted").length,meetingRequests:c.filter(_=>_.event_type==="meeting_requested").length+u.filter(_=>_.meeting_requested).length,attendees:u,attended:u.filter(_=>!!_.checked_in_at||_.status==="attended").length,noShows:u.filter(_=>!!_.no_show_at||_.status==="no_show").length,invitedNotRegistered:u.filter(_=>!!_.invited_at&&!_.registered_at&&!_.checked_in_at).length,openFollowUps:m,overdueFollowUps:m.filter(_=>_.due_at&&new Date(_.due_at)!!_.completed_at),stageChanges:p,lastStageChangeAt:((v=p[0])==null?void 0:v.created_at)||null,daysSinceStageChange:p[0]?hy(p[0].created_at,n):null,scoreEvents:t.scoreEvents.filter(_=>_.agent_id===s.id)}}const wke=["new_connection","building_relationship","engaging_with_value","active_conversation","exploring_options","brokerage_presentation","decision_pending","joined"],jke=["not_right_now","not_a_fit","long_term_relationship"];function mHn(s,t=new Date){const n=[],r=[],a=[],i=[],l=s.daysSinceTouch;let o=0,c;l===null?(o=0,c="No meaningful touch has ever been logged.",a.push("No logged conversation yet"),i.push("Log your first real conversation with this agent.")):l<=10?(o=cm.recency,c=`Last meaningful touch ${l} day(s) ago.`,r.push("Recent personal contact")):l<=21?(o=cm.recency*.85,c=`Last touch ${l} days ago.`,r.push("Contact is still fresh")):l<=45?(o=cm.recency*.6,c=`Last touch ${l} days ago.`,i.push("Reach out within the next week to keep momentum.")):l<=90?(o=cm.recency*.3,c=`Last touch ${l} days ago.`,a.push(`${l} days since a real conversation`),i.push("A personal check-in would meaningfully lift this score.")):(o=cm.recency*.05,c=`Last touch ${l} days ago.`,a.push(`Relationship has been quiet for ${l} days`),i.push("Restart the relationship with a no-ask personal check-in.")),n.push({key:"recency",label:"Recency of personal contact",weight:cm.recency,earned:Math.round(o),detail:c,direction:o>=cm.recency*.6?"positive":"negative"});const d=Math.min(s.distinctTouchMonths,6),u=cm.consistency*(d/6),h=s.touches30>6;n.push({key:"consistency",label:"Consistency of touches",weight:cm.consistency,earned:Math.round(u),detail:`${d} of the last 6 months had at least one logged touch (${s.touches90} touches in 90 days).`,direction:u>=cm.consistency*.5?"positive":"neutral"}),d>=4&&r.push("Consistent rhythm across months"),d<=1&&i.push("Aim for at least one touch per month rather than bursts."),h&&a.push(`${s.touches30} touches in the last 30 days — give them room to breathe`);const m=s.shares.length,p=cm.value_delivered*Math.min(m/3,1);n.push({key:"value_delivered",label:"Value delivered",weight:cm.value_delivered,earned:Math.round(p),detail:m?`${m} resource kit share(s) sent.`:"No resource kit shared yet.",direction:m?"positive":"neutral"}),m?r.push(`${m} resource kit share(s) delivered`):i.push("Share a relevant Resource Kit — value first, no ask.");const g=(s.totalKitOpens>0?4:0)+Math.min(s.downloads,2)*2+Math.min(s.ctaClicks,2)*2+(s.questions>0?2:0)+(s.meetingRequests>0?4:0),x=Math.min(g,cm.kit_engagement);n.push({key:"kit_engagement",label:"Kit engagement",weight:cm.kit_engagement,earned:x,detail:m?`${s.totalKitOpens} open(s), ${s.downloads} download(s), ${s.ctaClicks} link click(s), ${s.questions} question(s), ${s.meetingRequests} meeting request(s).`:"Nothing shared yet, so no engagement to measure.",direction:x>0?"positive":"neutral"}),s.meetingRequests>0&&r.push("They asked for a conversation"),m&&s.totalKitOpens===0&&(a.push("Shared kit has never been opened"),i.push("Follow up personally — the kit link was never opened."));const y=Math.min(s.attended,2)*5+(s.attendees.length?2:0)-Math.min(s.noShows,2)*2,v=Math.max(0,Math.min(y,cm.event_participation));n.push({key:"event_participation",label:"Event participation",weight:cm.event_participation,earned:v,detail:s.attendees.length?`${s.attended} attended, ${s.noShows} no-show(s), ${s.attendees.length} total invitation(s)/registration(s).`:"Never invited to an event.",direction:v>0?"positive":"neutral"}),s.attended>0&&r.push(`${s.attended} event(s) attended`),s.attendees.length||i.push("Invite them to your next event or mastermind."),s.noShows>0&&a.push(`${s.noShows} no-show(s)`);const _=s.completedFollowUps.length+s.openFollowUps.length;let j=_===0?cm.follow_up_discipline*.4:cm.follow_up_discipline*(s.completedFollowUps.length/_);j-=Math.min(s.overdueFollowUps.length,3)*2,j=Math.max(0,Math.min(j,cm.follow_up_discipline)),n.push({key:"follow_up_discipline",label:"Follow-up discipline",weight:cm.follow_up_discipline,earned:Math.round(j),detail:_?`${s.completedFollowUps.length} of ${_} follow-ups completed, ${s.overdueFollowUps.length} overdue.`:"No follow-ups created yet.",direction:s.overdueFollowUps.length?"negative":"positive"}),s.overdueFollowUps.length&&(a.push(`${s.overdueFollowUps.length} overdue commitment(s)`),i.push("Clear the overdue follow-up you promised."));const C=wke.indexOf(s.agent.stage);let A=0,M;if(jke.includes(s.agent.stage))A=cm.pipeline_momentum*.3,M="Relationship is intentionally parked — long-term nurture.";else if(C<0)A=cm.pipeline_momentum*.3,M=`Stage "${s.agent.stage}" is outside the advancing ladder.`;else{const R=cm.pipeline_momentum*(C/(wke.length-1)),O=s.daysSinceStageChange!==null&&s.daysSinceStageChange>60;A=O?R*.5:R,M=`Stage ${C+1} of ${wke.length}`+(s.daysSinceStageChange!==null?`, last moved ${s.daysSinceStageChange} days ago.`:", never moved."),O&&(a.push("Stage has not moved in over 60 days"),i.push("Have the next real conversation that would justify a stage move."))}n.push({key:"pipeline_momentum",label:"Pipeline momentum",weight:cm.pipeline_momentum,earned:Math.round(A),detail:M,direction:A>cm.pipeline_momentum*.5?"positive":"neutral"});let I=n.reduce((R,O)=>R+O.earned,0);s.agent.temperature==="hot"&&(I+=4,r.push("You marked this relationship hot")),s.agent.temperature==="cold"&&(I-=4,a.push("You marked this relationship cold")),h&&(I-=3),I=Math.max(0,Math.min(100,Math.round(I)));const P=I>=75?"thriving":I>=55?"healthy":I>=35?"cooling":"at_risk";return{agent_id:s.agent.id,score:I,band:P,components:n,positives:r,negatives:a,improvements:Array.from(new Set(i)).slice(0,4),inputs:{days_since_touch:s.daysSinceTouch,touches_90:s.touches90,touches_30:s.touches30,distinct_touch_months_6mo:s.distinctTouchMonths,shares:s.shares.length,kit_opens:s.totalKitOpens,downloads:s.downloads,cta_clicks:s.ctaClicks,questions:s.questions,meeting_requests:s.meetingRequests,events_attended:s.attended,no_shows:s.noShows,invited_not_registered:s.invitedNotRegistered,open_follow_ups:s.openFollowUps.length,overdue_follow_ups:s.overdueFollowUps.length,completed_follow_ups:s.completedFollowUps.length,stage:s.agent.stage,days_since_stage_change:s.daysSinceStageChange,temperature:s.agent.temperature},weights:{...cm},engine_version:fWt,calculated_at:t.toISOString()}}const xWt=[{key:"high_intent",label:"High-intent engagement",blurb:"They took a real action — respond while it is warm.",tone:"rose"},{key:"renewed_interest",label:"Renewed interest",blurb:"Someone quiet came back and engaged again.",tone:"violet"},{key:"event_follow_up",label:"Event follow-up needed",blurb:"Within 48 hours of an event is where relationships are made.",tone:"indigo"},{key:"resource_follow_up",label:"Resource follow-up needed",blurb:"You shared value — close the loop personally.",tone:"teal"},{key:"overdue_commitment",label:"Overdue commitment",blurb:"You said you would follow up. Keep your word.",tone:"orange"},{key:"going_cold",label:"Relationship going cold",blurb:"Momentum is fading. A no-ask check-in resets it.",tone:"amber"},{key:"no_touch",label:"No meaningful touch recently",blurb:"Long silence. Restart the relationship, do not pitch.",tone:"slate"},{key:"ready_deeper",label:"Ready for a deeper conversation",blurb:"Signals suggest they are open to going further.",tone:"green"}],fHn={urgent:100,high:70,medium:40,low:15},$j=(s,t=new Date)=>new Date(t.getTime()+s*pWt).toISOString(),jS=s=>s.first_name||"there",pHn=3;function Uj(s,t,n={}){var o,c;const r=jS(t.agent),a=(o=t.agent.goals)==null?void 0:o.trim(),i=(c=t.agent.challenges)==null?void 0:c.trim(),l=i?` You mentioned ${i.replace(/\.$/,"")} — that's still on my mind.`:a?` You mentioned ${a.replace(/\.$/,"")} — still thinking about that with you.`:"";switch(s){case"high_intent":return`Hey ${r} — saw you spent some time in the ${n.kitTitle??"resources"} I sent over. No agenda here; I'd just love to hear what stood out and what questions came up.${l} Any chance for a quick call this week?`;case"renewed_interest":return`${r}! You popped back into ${n.kitTitle??"that resource"} I shared a while back — figured I'd check in. How's everything going on your end?${l}`;case"event_follow_up":return`${r}, really glad you were at ${n.eventTitle??"the session"}. What was the most useful part for you? Happy to send over anything specific that would help you put it to work.`;case"event_no_show":return`Hey ${r} — noticed you couldn't make ${n.eventTitle??"the session"}, no worries at all. Life happens. Want me to send you the highlights, or would a quick 1:1 be more useful?`;case"event_invite_nudge":return`${r} — I've got ${n.eventTitle??"a small session"} coming up${n.eventWhen?` on ${n.eventWhen}`:""} and thought of you. Small group, real conversation, nothing salesy. Want me to save you a seat?`;case"resource_follow_up":return`Hey ${r} — I sent over ${n.kitTitle??"a few resources"} a bit ago. Didn't want it to get buried. Did any of it land, or is there something more specific I can pull together for you?`;case"resource_unopened":return`${r}, I sent you ${n.kitTitle??"something"} that I genuinely think would help — might've gone to spam. Want me to just walk you through the short version instead?`;case"overdue_commitment":return`Hey ${r} — I owe you a follow-up on "${n.followUpTitle??"what we talked about"}". Circling back now.${l} When's a good time?`;case"going_cold":return`${r} — it's been a bit. No agenda, genuinely just checking in on you. How's business feeling right now?${l}`;case"no_touch":return`Hey ${r} — long overdue message from me. I've been thinking about our last conversation and wanted to see how you're doing. No pitch, just catching up.`;case"ready_deeper":return`${r}, based on what you've shared I think it's worth a real conversation about what you actually want the next chapter to look like — no pressure either direction. Coffee or a call this week?`;case"share_value":return`${r} — put together ${n.kitTitle?`"${n.kitTitle}"`:"a small set of resources"} that I think fits exactly where you are right now. Sending it because it's useful, not because I want anything. Let me know if it helps.`;default:return`Hey ${r} — checking in. How are things going?${l}`}}function gHn(s,t,n=new Date){const r=[],a=s.agent;if(a.stage==="not_a_fit")return r;const i=s.daysSinceTouch!==null&&s.daysSinceTouch{var v;return(v=t.kits.find(_=>_.id===y))==null?void 0:v.title},o=y=>{r.push({...y,message_source:"rules",rank_score:y.rank_score??fHn[y.priority]})},c=s.shares.find(y=>y.engagement_level==="high_intent");if(s.meetingRequests>0||s.questions>0||c){const y=c?l(c.kit_id):void 0,v=[s.meetingRequests>0&&`${s.meetingRequests} meeting request(s) submitted`,s.questions>0&&`${s.questions} question(s) asked inside a shared kit`,c&&`Kit engagement is classified High Intent (${c.open_count} opens)`,s.downloads>0&&`${s.downloads} file download(s)`].filter(Boolean);o({agent_id:a.id,rec_key:"high_intent",signal_group:"high_intent",signal_label:"High-intent engagement",action_type:"respond_to_intent",channel:s.meetingRequests>0?"call":"text",title:`Call ${jS(a)} — they are actively engaging`,reasons:v,priority:"urgent",suggested_due_at:$j(1,n),draft_message:Uj("high_intent",s,{kitTitle:y}),suggested_kit_id:(c==null?void 0:c.kit_id)??null,source_signals:{meeting_requests:s.meetingRequests,questions:s.questions,downloads:s.downloads,share_id:c==null?void 0:c.id},rank_score:100+s.meetingRequests*5})}const d=s.shares.find(y=>y.last_opened_at&&y.first_opened_at&&hy(y.last_opened_at,n)<=7&&hy(y.first_opened_at,y.last_opened_at)>=14&&(y.open_count||0)>1);d&&(s.daysSinceTouch===null||s.daysSinceTouch>21)&&o({agent_id:a.id,rec_key:"renewed_interest",signal_group:"renewed_interest",signal_label:"Renewed interest",action_type:"reengage",channel:"text",title:`${jS(a)} came back to a kit you shared`,reasons:[`Re-opened "${l(d.kit_id)??"a shared kit"}" ${hy(d.last_opened_at,n)} day(s) ago`,`${d.open_count} total opens`,s.daysSinceTouch===null?"No personal touch logged":`${s.daysSinceTouch} days since your last personal touch`],priority:"high",suggested_due_at:$j(2,n),draft_message:Uj("renewed_interest",s,{kitTitle:l(d.kit_id)}),suggested_kit_id:d.kit_id,source_signals:{share_id:d.id,open_count:d.open_count},rank_score:88});const u=s.attendees.filter(y=>y.checked_in_at&&hy(y.checked_in_at,n)<=7&&y.followup_status!=="done").sort((y,v)=>+new Date(v.checked_in_at)-+new Date(y.checked_in_at))[0];if(u){const y=t.events.find(_=>_.id===u.event_id),v=Math.round((n.getTime()-new Date(u.checked_in_at).getTime())/36e5);o({agent_id:a.id,rec_key:`event_follow_up:${u.event_id}`,signal_group:"event_follow_up",signal_label:"Event follow-up needed",action_type:"event_follow_up",channel:"call",title:`Follow up on ${(y==null?void 0:y.title)??"the event"} — ${v}h since they attended`,reasons:[`Checked in to "${(y==null?void 0:y.title)??"event"}" ${v} hours ago`,`Follow-up status is "${u.followup_status??"pending"}"`,v<=48?"Inside the 48-hour window where follow-up matters most":"Past the ideal 48-hour window — still worth doing today"],priority:v<=48?"urgent":"high",suggested_due_at:$j(v<=48?1:0,n),draft_message:Uj("event_follow_up",s,{eventTitle:y==null?void 0:y.title}),suggested_event_id:u.event_id,suggested_kit_id:(y==null?void 0:y.resource_kit_id)??null,source_signals:{attendee_id:u.id,hours_since:v},rank_score:v<=48?96:74})}else{const y=s.attendees.find(v=>v.no_show_at&&hy(v.no_show_at,n)<=10);if(y){const v=t.events.find(_=>_.id===y.event_id);o({agent_id:a.id,rec_key:`event_no_show:${y.event_id}`,signal_group:"event_follow_up",signal_label:"Event follow-up needed",action_type:"no_show_recovery",channel:"text",title:`${jS(a)} missed ${(v==null?void 0:v.title)??"an event"} — recover gracefully`,reasons:[`Registered but did not attend "${(v==null?void 0:v.title)??"event"}"`,"No-show recovery works best within a week, with zero guilt"],priority:"medium",suggested_due_at:$j(2,n),draft_message:Uj("event_no_show",s,{eventTitle:v==null?void 0:v.title}),suggested_event_id:y.event_id,source_signals:{attendee_id:y.id},rank_score:52})}}const h=s.shares.find(y=>y.first_opened_at&&hy(y.first_opened_at,n)>=3&&hy(y.first_opened_at,n)<=30&&(s.daysSinceTouch===null||s.lastTouchAt&&new Date(s.lastTouchAt)!y.first_opened_at&&hy(y.created_at,n)>=5&&y.status==="active");h?o({agent_id:a.id,rec_key:`resource_follow_up:${h.id}`,signal_group:"resource_follow_up",signal_label:"Resource follow-up needed",action_type:"resource_follow_up",channel:"text",title:`Close the loop on "${l(h.kit_id)??"the kit"}"`,reasons:[`Opened ${hy(h.first_opened_at,n)} day(s) ago`,`${h.open_count} open(s), engagement level "${h.engagement_level}"`,"No personal touch logged since they viewed it"],priority:"high",suggested_due_at:$j(2,n),draft_message:Uj("resource_follow_up",s,{kitTitle:l(h.kit_id)}),suggested_kit_id:h.kit_id,source_signals:{share_id:h.id},rank_score:78}):m&&o({agent_id:a.id,rec_key:`resource_unopened:${m.id}`,signal_group:"resource_follow_up",signal_label:"Resource follow-up needed",action_type:"resource_nudge",channel:"text",title:`Shared kit never opened — nudge ${jS(a)} personally`,reasons:[`Shared ${hy(m.created_at,n)} days ago and never opened`,"A personal message beats a resend"],priority:"medium",suggested_due_at:$j(2,n),draft_message:Uj("resource_unopened",s,{kitTitle:l(m.kit_id)}),suggested_kit_id:m.kit_id,source_signals:{share_id:m.id},rank_score:46});const p=s.overdueFollowUps.sort((y,v)=>+new Date(y.due_at)-+new Date(v.due_at))[0];if(p){const y=hy(p.due_at,n);o({agent_id:a.id,rec_key:`overdue:${p.id}`,signal_group:"overdue_commitment",signal_label:"Overdue commitment",action_type:"clear_overdue",channel:p.touch_type||"call",title:`Overdue ${y} day(s): ${p.title}`,reasons:[`Follow-up "${p.title}" was due ${y} day(s) ago`,`Priority: ${p.priority??"medium"}`],priority:y>7?"urgent":"high",suggested_due_at:$j(0,n),draft_message:Uj("overdue_commitment",s,{followUpTitle:p.title}),source_signals:{follow_up_id:p.id,days_late:y},rank_score:92+Math.min(y,8)})}const g=wke.indexOf(a.stage);if(!jke.includes(a.stage)&&g>=2&&s.attended>0&&(s.totalKitOpens>0||s.downloads>0)&&(s.daysSinceStageChange===null||s.daysSinceStageChange>21)&&o({agent_id:a.id,rec_key:"ready_deeper",signal_group:"ready_deeper",signal_label:"Ready for a deeper conversation",action_type:"deeper_conversation",channel:"call",title:`Have the honest next-chapter conversation with ${jS(a)}`,reasons:[`Stage "${a.stage}" with real engagement behind it`,`${s.attended} event(s) attended and ${s.totalKitOpens} kit open(s)`,s.daysSinceStageChange!==null?`Stage unchanged for ${s.daysSinceStageChange} days`:"Stage has never moved"],priority:"high",suggested_due_at:$j(4,n),draft_message:Uj("ready_deeper",s),source_signals:{stage:a.stage,attended:s.attended},rank_score:72}),s.daysSinceTouch===null&&hy(a.created_at,n)>7)o({agent_id:a.id,rec_key:"no_first_touch",signal_group:"no_touch",signal_label:"No meaningful touch recently",action_type:"first_conversation",channel:"personal_check_in",title:`You have never logged a conversation with ${jS(a)}`,reasons:[`Added to your pipeline ${hy(a.created_at,n)} days ago`,"No touch, kit, or event activity logged"],priority:"medium",suggested_due_at:$j(3,n),draft_message:Uj("no_touch",s),source_signals:{created_at:a.created_at},rank_score:48});else if(s.daysSinceTouch!==null){const y=a.temperature==="hot"?14:a.temperature==="cold"?90:45;if(s.daysSinceTouch>y){const v=s.daysSinceTouch>y*2;o({agent_id:a.id,rec_key:v?"no_touch_long":"going_cold",signal_group:v?"no_touch":"going_cold",signal_label:v?"No meaningful touch recently":"Relationship going cold",action_type:"check_in",channel:"personal_check_in",title:`${jS(a)} has been quiet for ${s.daysSinceTouch} days`,reasons:[`Last meaningful touch ${s.daysSinceTouch} days ago`,`Your cadence for a "${a.temperature??"warm"}" relationship is ${y} days`,s.touches90?`${s.touches90} touch(es) in the last 90 days`:"No touches in the last 90 days"],priority:v?"high":"medium",suggested_due_at:$j(3,n),draft_message:Uj(v?"no_touch":"going_cold",s),source_signals:{days_since_touch:s.daysSinceTouch,threshold:y},rank_score:v?62:44})}}if(!s.shares.length&&!jke.includes(a.stage)&&t.primaryPillar==="provide"){const y=t.kits.find(v=>v.status==="published"&&(!v.audience||!a.production_context||!0));y&&o({agent_id:a.id,rec_key:"share_first_kit",signal_group:"resource_follow_up",signal_label:"Resource follow-up needed",action_type:"share_kit",channel:"resource_share",title:`Share "${y.title}" with ${jS(a)}`,reasons:["No resource has been shared with this agent yet","Your 90-day plan primary pillar is Provide — lead with value"],priority:"medium",suggested_due_at:$j(5,n),draft_message:Uj("share_value",s,{kitTitle:y.title}),suggested_kit_id:y.id,source_signals:{pillar:"provide"},rank_score:38})}if(!s.attendees.length&&!jke.includes(a.stage)&&t.primaryPillar==="connect"){const y=t.events.filter(v=>v.status==="published"&&v.starts_at&&new Date(v.starts_at)>n).sort((v,_)=>+new Date(v.starts_at)-+new Date(_.starts_at))[0];y&&o({agent_id:a.id,rec_key:`invite_event:${y.id}`,signal_group:"ready_deeper",signal_label:"Ready for a deeper conversation",action_type:"invite_to_event",channel:"event_invitation",title:`Invite ${jS(a)} to ${y.title}`,reasons:["Never invited to an event",`"${y.title}" is published and upcoming`,"Your 90-day plan primary pillar is Connect"],priority:"medium",suggested_due_at:$j(4,n),draft_message:Uj("event_invite_nudge",s,{eventTitle:y.title,eventWhen:y.starts_at?new Date(y.starts_at).toLocaleDateString():void 0}),suggested_event_id:y.id,source_signals:{pillar:"connect",event_id:y.id},rank_score:40})}return(i?r.filter(y=>y.priority==="urgent"):r).sort((y,v)=>v.rank_score-y.rank_score).slice(0,3)}const Awt=[{key:"all",label:"Everything",kinds:[]},{key:"conversations",label:"Conversations",kinds:["touch","note","activity"]},{key:"pipeline",label:"Pipeline",kinds:["stage_change","temperature"]},{key:"follow_ups",label:"Follow-ups",kinds:["follow_up_created","follow_up_completed","follow_up_missed"]},{key:"value",label:"Value shared",kinds:["kit_shared","kit_engagement"]},{key:"events",label:"Events",kinds:["event_invited","event_registered","event_attended","event_no_show","event_note"]},{key:"score",label:"Score",kinds:["score"]}],xHn={page_view:"Viewed the kit",resource_open:"Opened a resource",file_download:"Downloaded a file",video_start:"Started a video",video_complete:"Finished a video",external_link_click:"Clicked a link",primary_cta_click:"Clicked the main call to action",question_submitted:"Submitted a question",meeting_requested:"Requested a meeting"};function yHn(s,t,n=[],r=new Date){const a=[],i=t.activities.filter(c=>c.agent_id===s.agent.id),l=c=>{var d;return((d=t.kits.find(u=>u.id===c))==null?void 0:d.title)??"Resource kit"},o=c=>{var d;return((d=t.events.find(u=>u.id===c))==null?void 0:d.title)??"Event"};for(const c of i)a.push({id:`act:${c.id}`,kind:gWt.includes(c.activity_type)?c.activity_type==="note"?"note":"touch":"activity",at:c.created_at,title:c.title,detail:c.description??void 0,meta:{activity_type:c.activity_type,pillar:c.pillar}});for(const c of s.stageChanges)a.push({id:`stage:${c.id}`,kind:"stage_change",at:c.created_at,title:`Stage moved to ${c.to_stage.replace(/_/g," ")}`,detail:c.from_stage?`From ${c.from_stage.replace(/_/g," ")}`:void 0});for(const c of t.followUps.filter(d=>d.agent_id===s.agent.id))a.push({id:`fuc:${c.id}`,kind:"follow_up_created",at:c.created_at,title:`Follow-up created: ${c.title}`,detail:c.due_at?`Due ${new Date(c.due_at).toLocaleDateString()}`:void 0}),c.completed_at?a.push({id:`fud:${c.id}`,kind:"follow_up_completed",at:c.completed_at,title:`Follow-up completed: ${c.title}`}):c.due_at&&new Date(c.due_at)d.agent_id===s.agent.id))a.push({id:`en:${c.id}`,kind:"event_note",at:c.created_at,title:`Event note — ${o(c.event_id)}`,detail:c.note});for(const c of s.scoreEvents)a.push({id:`sc:${c.id}`,kind:"score",at:c.created_at,title:`${c.points>0?"+":""}${c.points} Attract score — ${c.category}`,detail:c.description??void 0});return a.sort((c,d)=>+new Date(d.at)-+new Date(c.at))}function vHn(s,t,n){return s.shares.slice().sort((r,a)=>+new Date(a.created_at)-+new Date(r.created_at)).map(r=>{var m;const a=s.shareEvents[r.id]??[],i=a.filter(p=>p.event_type==="file_download").length,l=a.filter(p=>p.event_type==="primary_cta_click"||p.event_type==="external_link_click").length,o=a.filter(p=>p.event_type==="question_submitted").length,c=a.filter(p=>p.event_type==="meeting_requested").length,d=r.engagement_level==="high_intent"||c>0?"High Intent":r.engagement_level==="engaged"||i>0||l>0||o>0?"Engaged":r.first_opened_at?"Viewed":"Sent",u=t.followUps.filter(p=>p.agent_id===s.agent.id&&new Date(p.created_at)>=new Date(r.created_at)).sort((p,g)=>+new Date(p.created_at)-+new Date(g.created_at))[0]??null,h=s.stageChanges.filter(p=>new Date(p.created_at)>new Date(r.created_at)).sort((p,g)=>+new Date(p.created_at)-+new Date(g.created_at))[0]??null;return{share:r,kitTitle:((m=t.kits.find(p=>p.id===r.kit_id))==null?void 0:m.title)??"Resource kit",shareUrl:`${n}/attract-kit/${r.share_token}`,events:a,firstViewedAt:r.first_opened_at??null,lastViewedAt:r.last_opened_at??null,visits:r.open_count??0,downloads:i,ctaClicks:l,questions:o,meetingRequests:c,classification:d,followUp:u,stageAdvancedAfter:h}})}function bHn(s,t){const n=new Set(s.shares.map(l=>l.kit_id)),r=t.kits.filter(l=>l.status==="published"&&!n.has(l.id));if(!r.length)return null;const a=r.find(l=>l.pillar&&l.pillar===s.agent.primary_pillar);if(a)return{kit:a,why:`Matches this agent's primary pillar (${s.agent.primary_pillar}) and has not been shared yet.`};const i=r.find(l=>(l.audience??"").toLowerCase().includes("new"));return i&&s.agent.stage==="new_connection"?{kit:i,why:"They are a new connection and this kit is built for early-stage relationships."}:{kit:r[0],why:"Published, relevant, and not yet shared with this agent."}}const Kh=V;function _Hn(){const{user:s}=ks();return pt({queryKey:["attract-intel-data",s==null?void 0:s.id],enabled:!!s,staleTime:3e4,queryFn:async()=>{var g,x;const[t,n,r,a,i,l,o,c,d,u,h,m]=await Promise.all([Kh.from("attract_agents").select("*").order("updated_at",{ascending:!1}),Kh.from("attract_activities").select("*").order("created_at",{ascending:!1}).limit(2e3),Kh.from("attract_follow_ups").select("*").order("created_at",{ascending:!1}).limit(2e3),Kh.from("attract_kit_shares").select("*").order("created_at",{ascending:!1}).limit(1e3),Kh.from("attract_kit_events").select("*").order("created_at",{ascending:!1}).limit(2e3),Kh.from("attract_event_attendees").select("*").order("created_at",{ascending:!1}).limit(2e3),Kh.from("attract_events").select("id, title, starts_at, status, resource_kit_id, public_slug").limit(500),Kh.from("attract_pipeline_history").select("*").order("created_at",{ascending:!1}).limit(2e3),Kh.from("attract_score_events").select("*").order("created_at",{ascending:!1}).limit(2e3),Kh.from("attract_resource_kits").select("id, title, audience, pillar, status, is_template").eq("is_template",!1),Kh.from("attract_event_notes").select("*").order("created_at",{ascending:!1}).limit(1e3),Kh.from("attract_settings").select("primary_pillar, attraction_style, ninety_day_plan").eq("user_id",s.id).maybeSingle()]),p=[t,n,r,a,i,l,o,c,d,u,h].find(y=>y.error);if(p)throw p.error;return{agents:t.data??[],activities:n.data??[],followUps:r.data??[],shares:a.data??[],kitEvents:i.data??[],attendees:l.data??[],events:o.data??[],stageChanges:c.data??[],scoreEvents:d.data??[],kits:u.data??[],eventNotes:h.data??[],primaryPillar:((g=m==null?void 0:m.data)==null?void 0:g.primary_pillar)??((x=m==null?void 0:m.data)==null?void 0:x.attraction_style)??null}}})}function k6(){const s=_Hn(),t=k.useMemo(()=>{if(!s.data)return[];const r=new Date;return s.data.agents.map(a=>{const i=hHn(a,s.data,r),l=mHn(i,r),o=gHn(i,s.data,r);return{agent:a,signals:i,score:l,recommendations:o,primary:o[0]??null}})},[s.data]),n=k.useMemo(()=>new Map(t.map(r=>[r.agent.id,r])),[t]);return{...s,dataset:s.data,intel:t,byId:n}}function wHn(s){const{dataset:t,byId:n,isLoading:r,error:a,refetch:i}=k6(),l=s?n.get(s)??null:null,o=k.useMemo(()=>l&&t?yHn(l.signals,t,t.eventNotes??[]):[],[l,t]),c=k.useMemo(()=>l&&t?vHn(l.signals,t,typeof window<"u"?window.location.origin:""):[],[l,t]),d=k.useMemo(()=>l&&t?bHn(l.signals,t):null,[l,t]);return{item:l,dataset:t,timeline:o,valueShared:c,nextKit:d,isLoading:r,error:a,refetch:i}}function yWt(){const{user:s}=ks(),t=ls();return Nt({mutationFn:async({items:n,silent:r})=>{if(!s||!n.length)return{count:0,silent:r};const a=n.map(i=>({user_id:s.id,agent_id:i.agent.id,score:i.score.score,band:i.score.band,components:i.score.components,positives:i.score.positives,negatives:i.score.negatives,improvements:i.score.improvements,inputs:i.score.inputs,weights:i.score.weights,engine_version:fWt,calculated_at:i.score.calculated_at}));for(let i=0;i{t.invalidateQueries({queryKey:["attract-score-snapshots"]}),n&&!r&&ae.success(`Recalculated ${n} relationship score${n===1?"":"s"}`)},onError:n=>ae.error(n.message??"Could not save scores")})}function Nte(){const{user:s}=ks();return pt({queryKey:["attract-recommendations",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await Kh.from("attract_recommendations").select("*").order("rank_score",{ascending:!1});if(n)throw n;return t??[]}})}function YTe(){const{user:s}=ks(),t=ls();return Nt({mutationFn:async n=>{if(!s)return{inserted:0,refreshed:0};const r=n.flatMap(u=>u.recommendations),{data:a,error:i}=await Kh.from("attract_recommendations").select("id, agent_id, rec_key, status, snoozed_until");if(i)throw i;const l=new Map((a??[]).map(u=>[`${u.agent_id}|${u.rec_key}`,u])),o=[],c=[],d=new Date;for(const u of r){const h=`${u.agent_id}|${u.rec_key}`,m=l.get(h),p={user_id:s.id,agent_id:u.agent_id,rec_key:u.rec_key,signal_group:u.signal_group,action_type:u.action_type,channel:u.channel,title:u.title,reasons:u.reasons,priority:u.priority,rank_score:u.rank_score,suggested_due_at:u.suggested_due_at,draft_message:u.draft_message,message_source:u.message_source,suggested_kit_id:u.suggested_kit_id??null,suggested_event_id:u.suggested_event_id??null,source_signals:u.source_signals};m?m.status==="open"?c.push({id:m.id,patch:{...p,generated_at:d.toISOString()}}):m.status==="snoozed"&&m.snoozed_until&&new Date(m.snoozed_until)<=d&&c.push({id:m.id,patch:{...p,status:"open",snoozed_until:null,generated_at:d.toISOString()}}):o.push(p)}if(o.length){const{error:u}=await Kh.from("attract_recommendations").insert(o);if(u)throw u}for(const u of c)await Kh.from("attract_recommendations").update(u.patch).eq("id",u.id);return{inserted:o.length,refreshed:c.length}},onSuccess:()=>t.invalidateQueries({queryKey:["attract-recommendations"]}),onError:n=>ae.error(n.message??"Could not sync recommendations")})}function vWt(){const{user:s}=ks(),t=ls(),n=()=>{t.invalidateQueries({queryKey:["attract-recommendations"]}),t.invalidateQueries({queryKey:["attract-followups"]}),t.invalidateQueries({queryKey:["attract-intel-data"]}),t.invalidateQueries({queryKey:["attract-activities"]})},r=Nt({mutationFn:async({id:c,patch:d})=>{const{error:u}=await Kh.from("attract_recommendations").update(d).eq("id",c);if(u)throw u},onSuccess:n,onError:c=>ae.error(c.message)}),a=Nt({mutationFn:async c=>{const{error:d}=await Kh.from("attract_recommendations").update({status:"dismissed",dismissed_at:new Date().toISOString()}).eq("id",c);if(d)throw d},onSuccess:()=>{n(),ae.success("Dismissed")}}),i=Nt({mutationFn:async({id:c,days:d})=>{const u=new Date(Date.now()+d*864e5).toISOString(),{error:h}=await Kh.from("attract_recommendations").update({status:"snoozed",snoozed_until:u}).eq("id",c);if(h)throw h},onSuccess:()=>{n(),ae.success("Snoozed")}}),l=Nt({mutationFn:async c=>{if(c.follow_up_id){const{data:h}=await Kh.from("attract_follow_ups").select("id, completed_at").eq("id",c.follow_up_id).maybeSingle();if(h&&!h.completed_at)return{id:h.id,existed:!0}}const{data:d,error:u}=await Kh.from("attract_follow_ups").insert({user_id:s.id,agent_id:c.agent_id,title:c.title,touch_type:c.channel,due_at:c.suggested_due_at,priority:c.priority==="urgent"?"high":c.priority,notes:[c.draft_message,"","Why: "+(c.reasons??[]).join(" · ")].join(` `)}).select("id").single();if(u)throw u;return await Kh.from("attract_recommendations").update({follow_up_id:d.id}).eq("id",c.id),{id:d.id,existed:!1}},onSuccess:c=>{n(),ae.success(c.existed?"Follow-up already exists":"Follow-up created")},onError:c=>ae.error(c.message)}),o=Nt({mutationFn:async({rec:c,note:d})=>{const u=new Date().toISOString(),{error:h}=await Kh.from("attract_activities").insert({user_id:s.id,agent_id:c.agent_id,activity_type:"touch_logged",title:c.title,description:d||c.draft_message,pillar:c.signal_group==="event_follow_up"?"connect":c.signal_group==="resource_follow_up"?"provide":null,metadata:{recommendation_id:c.id,channel:c.channel,rec_key:c.rec_key}});if(h)throw h;c.follow_up_id&&await Kh.from("attract_follow_ups").update({completed_at:u}).eq("id",c.follow_up_id).is("completed_at",null),await Kh.from("attract_score_events").insert({user_id:s.id,agent_id:c.agent_id,category:"follow_up",points:2,description:`Completed: ${c.title}`});const{error:m}=await Kh.from("attract_recommendations").update({status:"completed",completed_at:u}).eq("id",c.id);if(m)throw m},onSuccess:()=>{n(),t.invalidateQueries({queryKey:["attract-score"]}),ae.success("Logged — timeline and score updated")},onError:c=>ae.error(c.message)});return{update:r,dismiss:a,snooze:i,createFollowUp:l,logCompleted:o}}function jHn(){const{user:s}=ks(),t=ls();return Nt({mutationFn:async n=>{const{error:r}=await Kh.from("attract_activities").insert({user_id:s.id,...n});if(r)throw r},onSuccess:()=>{t.invalidateQueries({queryKey:["attract-intel-data"]}),t.invalidateQueries({queryKey:["attract-activities"]}),t.invalidateQueries({queryKey:["attract-agents"]}),ae.success("Logged")},onError:n=>ae.error(n.message)})}const Ewt={thriving:{label:"Thriving",ring:"ring-emerald-200",text:"text-emerald-700",bg:"bg-emerald-50"},healthy:{label:"Healthy",ring:"ring-teal-200",text:"text-teal-700",bg:"bg-teal-50"},cooling:{label:"Cooling",ring:"ring-amber-200",text:"text-amber-700",bg:"bg-amber-50"},at_risk:{label:"At risk",ring:"ring-rose-200",text:"text-rose-700",bg:"bg-rose-50"}};function cJe({score:s,className:t}){const n=Ewt[s.band]??Ewt.cooling;return e.jsxs(qe,{variant:"outline",className:Ot("rounded-full gap-1.5 font-medium",n.bg,n.text,"border-transparent ring-1",n.ring,t),children:[e.jsx("span",{className:"tabular-nums font-semibold",children:s.score}),e.jsx("span",{className:"opacity-70",children:"·"}),e.jsx("span",{children:n.label})]})}function bWt({score:s}){return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-baseline gap-3",children:[e.jsx("div",{className:"text-4xl font-semibold tabular-nums text-slate-900",children:s.score}),e.jsx("div",{className:"text-slate-400 text-sm",children:"/ 100"}),e.jsx(cJe,{score:s})]}),e.jsxs("div",{className:"text-[12px] text-slate-500",children:["Calculated ",new Date(s.calculated_at).toLocaleString()," · engine ",s.engine_version," · rules only, no AI guessing."]}),e.jsx("div",{className:"space-y-2.5",children:s.components.map(t=>{const n=t.weight?Math.round(t.earned/t.weight*100):0;return e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between text-[13px]",children:[e.jsx("span",{className:"font-medium text-slate-800",children:t.label}),e.jsxs("span",{className:"tabular-nums text-slate-500",children:[t.earned,e.jsxs("span",{className:"text-slate-300",children:["/",t.weight]})]})]}),e.jsx("div",{className:"h-1.5 rounded-full bg-slate-100 mt-1 overflow-hidden",children:e.jsx("div",{className:Ot("h-full rounded-full transition-all",n>=70?"bg-emerald-500":n>=40?"bg-amber-400":"bg-rose-400"),style:{width:`${Math.max(n,2)}%`}})}),e.jsx("div",{className:"text-[11.5px] text-slate-500 mt-1 leading-snug",children:t.detail})]},t.key)})}),!!s.positives.length&&e.jsxs("div",{className:"rounded-xl bg-emerald-50 p-3",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-[11px] uppercase tracking-wider font-semibold text-emerald-700 mb-1.5",children:[e.jsx(mc,{className:"h-3.5 w-3.5"})," Helping"]}),e.jsx("ul",{className:"text-[12.5px] text-emerald-900/80 space-y-1 list-disc pl-4",children:s.positives.map((t,n)=>e.jsx("li",{children:t},n))})]}),!!s.negatives.length&&e.jsxs("div",{className:"rounded-xl bg-rose-50 p-3",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-[11px] uppercase tracking-wider font-semibold text-rose-700 mb-1.5",children:[e.jsx(lk,{className:"h-3.5 w-3.5"})," Hurting"]}),e.jsx("ul",{className:"text-[12.5px] text-rose-900/80 space-y-1 list-disc pl-4",children:s.negatives.map((t,n)=>e.jsx("li",{children:t},n))})]}),!!s.improvements.length&&e.jsxs("div",{className:"rounded-xl bg-violet-50 p-3",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-[11px] uppercase tracking-wider font-semibold text-violet-700 mb-1.5",children:[e.jsx(ak,{className:"h-3.5 w-3.5"})," What would improve it"]}),e.jsx("ul",{className:"text-[12.5px] text-violet-900/80 space-y-1 list-disc pl-4",children:s.improvements.map((t,n)=>e.jsx("li",{children:t},n))})]})]})}function Twt({className:s}){const{intel:t}=k6(),[n,r]=k.useState(""),[a,i]=k.useState(!1),l=Jn(),o=k.useMemo(()=>{const c=n.trim().toLowerCase();return c?t.filter(d=>{const u=d.agent;return[u.first_name,u.last_name,u.brokerage,u.city,u.email,...u.tags??[]].filter(Boolean).join(" ").toLowerCase().includes(c)}).slice(0,6):[]},[t,n]);return e.jsxs("div",{className:Ot("relative",s),children:[e.jsx(Yr,{className:"h-3.5 w-3.5 absolute left-3 top-1/2 -translate-y-1/2 text-slate-400"}),e.jsx("input",{value:n,onChange:c=>{r(c.target.value),i(!0)},onFocus:()=>i(!0),onBlur:()=>setTimeout(()=>i(!1),150),placeholder:"Search relationships","aria-label":"Search relationships",className:"w-full h-9 rounded-full bg-white/5 border border-white/10 pl-9 pr-3 text-[12.5px] text-white placeholder:text-slate-500 focus:outline-none focus:ring-1 focus:ring-violet-500/60"}),a&&!!o.length&&e.jsx("div",{className:"absolute z-50 mt-1.5 w-full rounded-xl bg-white shadow-xl ring-1 ring-slate-200 overflow-hidden",children:o.map(c=>e.jsxs("button",{onMouseDown:()=>{l(`/attract/agents/${c.agent.id}`),r(""),i(!1)},className:"w-full text-left px-3 py-2.5 hover:bg-slate-50 flex items-center justify-between gap-2",children:[e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:"block text-[13px] font-medium text-slate-900 truncate",children:[c.agent.first_name,c.agent.last_name].filter(Boolean).join(" ")}),e.jsxs("span",{className:"block text-[11px] text-slate-500 truncate capitalize",children:[c.agent.stage.replace(/_/g," "),c.agent.brokerage?` · ${c.agent.brokerage}`:""]})]}),e.jsx(cJe,{score:c.score})]},c.agent.id))}),a&&!!n.trim()&&!o.length&&e.jsxs("div",{className:"absolute z-50 mt-1.5 w-full rounded-xl bg-white shadow-xl ring-1 ring-slate-200 px-3 py-2.5 text-[12.5px] text-slate-500",children:['No relationships match "',n,'".']})]})}const D8e=[{to:"/attract",label:"Today",icon:S2,exact:!0},{to:"/attract/relationships",label:"Relationships",icon:Xn},{to:"/attract/share",label:"Share Value",icon:z8},{to:"/attract/create",label:"Create Content",icon:vf},{to:"/attract/results",label:"Results",icon:Ul},{to:"/attract/settings",label:"Settings",icon:Yc}],Mwt=[{to:"/attract/plan",label:"90-Day Plan"},{to:"/attract/opportunities",label:"Opportunities"},{to:"/attract/pipeline",label:"Agent Pipeline (legacy)"},{to:"/attract/follow-up",label:"Follow-Up Center"},{to:"/attract/landing-page",label:"Attraction Page"},{to:"/attract/events",label:"Events"},{to:"/attract/provide/kits",label:"Resource Kits"},{to:"/attract/provide/masterclasses",label:"Masterclasses"},{to:"/attract/resources",label:"Resources"},{to:"/attract/templates",label:"Templates & Scripts"},{to:"/attract/digest",label:"Weekly Digest"},{to:"/attract/produce",label:"Produce tools"},{to:"/attract/influence",label:"Influence tools"},{to:"/attract/connect",label:"Connect tools"}];function NHn(){const s=Tu(),{settings:t,isLoading:n}=KV(),r=!n&&!!t&&!t.onboarding_completed_at,a=s.pathname==="/attract/onboarding";if(r&&!a&&!s.pathname.startsWith("/attract/settings"))return e.jsx(ab,{to:"/attract/onboarding",replace:!0});const i=D8e.slice(0,5);return e.jsxs("div",{className:"attract-root min-h-screen bg-[#F7F7FB] text-slate-900",children:[e.jsx("style",{children:` .attract-root { --a-primary: 139 92 246; --a-primary-strong: 109 40 217; --a-indigo: 79 70 229; --a-teal: 20 184 166; --a-green: 22 163 74; --a-orange: 249 115 22; --a-rose: 244 63 94; } .attract-root .btn-primary { background: linear-gradient(135deg, rgb(var(--a-primary)) 0%, rgb(var(--a-indigo)) 100%); } `}),e.jsxs("div",{className:"flex min-h-screen",children:[e.jsxs("aside",{className:"hidden lg:flex w-72 flex-col bg-[#0B0F1E] text-slate-200 border-r border-white/5",children:[e.jsxs("div",{className:"px-6 py-6 border-b border-white/10",children:[e.jsxs(JA,{to:"/dashboard",className:"inline-flex items-center gap-1.5 text-[11px] uppercase tracking-widest text-slate-400 hover:text-white transition-colors",children:[e.jsx(Ia,{className:"h-3 w-3"})," LevelUp Hub"]}),e.jsxs("div",{className:"mt-3 flex items-center gap-2.5",children:[e.jsx("div",{className:"h-9 w-9 rounded-xl bg-gradient-to-br from-violet-500 to-indigo-600 grid place-items-center shadow-lg shadow-violet-900/40",children:e.jsx(_3,{className:"h-4 w-4 text-white"})}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[15px] font-semibold tracking-tight text-white",children:"LEVELUP ATTRACT"}),e.jsx("div",{className:"text-[10.5px] text-slate-400 leading-tight",children:"Attract through value. Grow through relationships."})]})]})]}),e.jsx("div",{className:"px-4 pt-3",children:e.jsx(Twt,{})}),e.jsxs("nav",{className:"flex-1 overflow-y-auto py-3 px-3",children:[D8e.map(l=>{const o=l.icon;return e.jsxs(JA,{to:l.to,end:l.exact,className:({isActive:c})=>Ot("group flex items-center gap-3 px-3 py-2.5 rounded-xl text-[13.5px] font-medium transition-all",c?"bg-gradient-to-r from-violet-600/30 to-indigo-600/10 text-white ring-1 ring-inset ring-violet-500/40":"text-slate-300 hover:bg-white/5 hover:text-white"),children:[e.jsx(o,{className:"h-4 w-4 flex-shrink-0 opacity-80 group-hover:opacity-100"}),e.jsx("span",{className:"flex-1",children:l.label})]},l.to)}),e.jsxs(h1,{className:"mt-4",children:[e.jsxs(m1,{className:"w-full flex items-center justify-between px-3 py-2 text-[11px] uppercase tracking-[0.14em] text-slate-500 font-semibold hover:text-slate-300",children:["All tools ",e.jsx(Go,{className:"h-3.5 w-3.5"})]}),e.jsx(f1,{className:"pt-1",children:Mwt.map(l=>e.jsx(JA,{to:l.to,className:({isActive:o})=>Ot("block rounded-lg px-3 py-2 text-[12.5px]",o?"bg-white/10 text-white":"text-slate-400 hover:text-white hover:bg-white/5"),children:l.label},l.to))})]})]}),e.jsx("div",{className:"px-4 py-4 border-t border-white/5",children:e.jsxs("div",{className:"rounded-xl bg-white/5 p-3",children:[e.jsx("div",{className:"text-[11px] font-medium text-violet-300",children:"Beta preview"}),e.jsx("div",{className:"text-[11.5px] text-slate-400 mt-1 leading-snug",children:"Build relationships first. Personalize every message and verify brokerage and compensation info before sharing."})]})})]}),e.jsxs("div",{className:"lg:hidden fixed top-0 inset-x-0 z-40 bg-[#0B0F1E] text-white px-4 py-3 flex items-center gap-3 border-b border-white/10",children:[e.jsx(JA,{to:"/dashboard",className:"text-slate-400",children:e.jsx(Ia,{className:"h-4 w-4"})}),e.jsx("div",{className:"h-8 w-8 rounded-lg bg-gradient-to-br from-violet-500 to-indigo-600 grid place-items-center",children:e.jsx(_3,{className:"h-4 w-4"})}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[13px] font-semibold tracking-tight",children:"LEVELUP ATTRACT"}),e.jsx("div",{className:"text-[10px] text-slate-400",children:"Attract through value"})]})]}),e.jsxs("div",{className:"lg:hidden fixed bottom-0 inset-x-0 z-40 bg-[#0B0F1E]/95 backdrop-blur border-t border-white/10 flex",children:[i.map(l=>{const o=l.icon;return e.jsxs(JA,{to:l.to,end:l.exact,className:({isActive:c})=>Ot("flex-1 min-w-0 flex flex-col items-center gap-1 py-2 text-[10px]",c?"text-white":"text-slate-400"),children:[e.jsx(o,{className:"h-4 w-4"}),e.jsx("span",{className:"truncate max-w-[70px]",children:l.label})]},l.to)}),e.jsxs(D_,{children:[e.jsx(uee,{asChild:!0,children:e.jsxs("button",{className:"flex-1 min-w-0 flex flex-col items-center gap-1 py-2 text-[10px] text-slate-400",children:[e.jsx(u0,{className:"h-4 w-4"}),e.jsx("span",{children:"More"})]})}),e.jsx(Mb,{side:"bottom",className:"bg-[#0B0F1E] text-slate-200 border-white/10 rounded-t-3xl max-h-[75vh] overflow-y-auto",children:e.jsxs("div",{className:"pt-4 pb-8",children:[e.jsx(Twt,{className:"mb-4"}),e.jsx("div",{className:"text-[10px] uppercase tracking-widest text-slate-500 font-semibold mb-2",children:"All sections"}),D8e.map(l=>{const o=l.icon;return e.jsxs(JA,{to:l.to,end:l.exact,className:({isActive:c})=>Ot("flex items-center gap-3 rounded-xl px-3 py-3 text-[13.5px] font-medium",c?"bg-violet-600/30 text-white":"text-slate-300 hover:bg-white/5"),children:[e.jsx(o,{className:"h-4 w-4 opacity-80"}),e.jsx("span",{children:l.label})]},l.to)}),e.jsx("div",{className:"mt-4 mb-1 text-[10px] uppercase tracking-widest text-slate-500 font-semibold",children:"All tools"}),Mwt.map(l=>e.jsx(JA,{to:l.to,className:({isActive:o})=>Ot("block rounded-xl px-3 py-2.5 text-[13px]",o?"bg-white/10 text-white":"text-slate-400 hover:bg-white/5"),children:l.label},l.to))]})})]})]}),e.jsx("main",{className:"flex-1 min-w-0 pt-16 lg:pt-0 pb-24 lg:pb-0",children:e.jsx("div",{className:"max-w-[1400px] mx-auto px-4 sm:px-6 lg:px-10 py-6 lg:py-10",children:e.jsx(V5t,{})},s.pathname)})]})]})}function tW({label:s,value:t,delta:n,icon:r,tone:a="violet"}){const i={violet:"from-violet-500 to-indigo-600",teal:"from-teal-500 to-cyan-600",green:"from-emerald-500 to-green-600",orange:"from-orange-500 to-amber-600",rose:"from-rose-500 to-pink-600"};return e.jsx(we,{className:"p-5 rounded-2xl border-slate-200/70 bg-white shadow-sm hover:shadow-md transition-shadow",children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11.5px] uppercase tracking-wider font-medium text-slate-500",children:s}),e.jsx("div",{className:"mt-2 text-[26px] font-semibold tracking-tight text-slate-900",children:t}),n&&e.jsxs("div",{className:"mt-1 text-[11.5px] font-medium text-emerald-600 flex items-center gap-1",children:[e.jsx(FT,{className:"h-3 w-3"}),n]})]}),e.jsx("div",{className:Ot("h-10 w-10 rounded-xl bg-gradient-to-br grid place-items-center shadow-sm",i[a]),children:e.jsx(r,{className:"h-5 w-5 text-white"})})]})})}function kHn(){const{user:s}=ks();return pt({queryKey:["attract-score",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await V.from("attract_score_events").select("category, points, description, created_at");if(n)throw n;const r=t??[],a=r.reduce((l,o)=>l+(o.points??0),0),i={};for(const l of r)i[l.category]=(i[l.category]??0)+l.points;return{total:Math.min(a,100),rows:r,byCategory:i}}})}const SHn=[{key:"relationships_added",label:"Relationships Added",icon:tb,target:15},{key:"follow_ups_completed",label:"Follow-Ups Completed",icon:Gr,target:15},{key:"resources_shared",label:"Resources Shared",icon:ou,target:15},{key:"content_posted",label:"Agent Content Posted",icon:xm,target:15},{key:"events_connections",label:"Events / Connections",icon:nk,target:20},{key:"brokerage_conversations",label:"Brokerage Conversations",icon:sB,target:20}];function _Wt(){const{data:s}=kHn(),t=(s==null?void 0:s.total)??0,n=(s==null?void 0:s.byCategory)??{},r=2*Math.PI*54,a=t/100*r;return e.jsxs(we,{className:"p-6 rounded-2xl border-slate-200/70 bg-white shadow-sm",children:[e.jsxs("div",{className:"flex items-start justify-between mb-5",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11.5px] uppercase tracking-wider font-medium text-violet-600",children:"Your Attract Score"}),e.jsx("div",{className:"text-[19px] font-semibold text-slate-900 mt-1",children:"Great progress! Keep building relationships and providing value."})]}),e.jsx(mc,{className:"h-5 w-5 text-violet-500"})]}),e.jsxs("div",{className:"flex items-center gap-6 flex-col sm:flex-row",children:[e.jsxs("div",{className:"relative h-36 w-36 flex-shrink-0",children:[e.jsxs("svg",{viewBox:"0 0 120 120",className:"h-full w-full -rotate-90",children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"attract-score",x1:"0",x2:"1",y1:"0",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:"rgb(139 92 246)"}),e.jsx("stop",{offset:"100%",stopColor:"rgb(79 70 229)"})]})}),e.jsx("circle",{cx:"60",cy:"60",r:"54",stroke:"rgb(226 232 240)",strokeWidth:"10",fill:"none"}),e.jsx("circle",{cx:"60",cy:"60",r:"54",stroke:"url(#attract-score)",strokeWidth:"10",fill:"none",strokeLinecap:"round",strokeDasharray:`${a} ${r}`,style:{transition:"stroke-dasharray 800ms ease"}})]}),e.jsxs("div",{className:"absolute inset-0 grid place-items-center flex-col text-center",children:[e.jsxs("div",{className:"flex items-baseline gap-1",children:[e.jsx("span",{className:"text-4xl font-semibold tracking-tight text-slate-900",children:t}),e.jsx("span",{className:"text-sm text-slate-500 font-medium",children:"/100"})]}),e.jsx("div",{className:"text-[10px] uppercase tracking-wider text-slate-400",children:"this cycle"})]})]}),e.jsx("div",{className:"flex-1 space-y-2 w-full",children:SHn.map(i=>{const l=n[i.key]??0,o=Math.min(100,Math.round(l/i.target*100)),c=i.icon;return e.jsxs("div",{className:"grid grid-cols-[16px_1fr_60px_auto] items-center gap-2.5",children:[e.jsx(c,{className:"h-4 w-4 text-slate-500"}),e.jsx("span",{className:"text-[12.5px] text-slate-700 truncate",children:i.label}),e.jsx("div",{className:"h-1.5 rounded-full bg-slate-100 overflow-hidden",children:e.jsx("div",{className:"h-full rounded-full bg-gradient-to-r from-violet-500 to-indigo-500",style:{width:`${o}%`}})}),e.jsx("span",{className:"text-[11px] tabular-nums text-slate-500 font-medium w-8 text-right",children:l})]},i.key)})})]}),e.jsx("div",{className:"mt-5 flex justify-end",children:e.jsx($,{variant:"outline",size:"sm",className:"rounded-full",children:"View Score Breakdown"})})]})}const sW=V;function A0(){const{user:s}=ks(),t=ls(),n=pt({queryKey:["attract-agents",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:d,error:u}=await V.from("attract_agents").select("*").order("updated_at",{ascending:!1});if(u)throw u;return d??[]}}),r=()=>{["attract-agents","attract-intel","attract-intelligence","attract-agent-intel","attract-activities","attract-followups","attract-recommendations","attract-score","attract_milestones","attract-daily-plan"].forEach(d=>t.invalidateQueries({queryKey:[d]}))},a=Nt({mutationFn:async d=>{const u={...d,user_id:s.id},{data:h,error:m}=d.id?await V.from("attract_agents").update(u).eq("id",d.id).select().single():await V.from("attract_agents").insert(u).select().single();if(m)throw m;return h},onSuccess:()=>{r(),ae.success("Saved")},onError:d=>ae.error(d.message)}),i=Nt({mutationFn:async({id:d,to_stage:u,from_stage:h})=>{const{error:m}=await V.from("attract_agents").update({stage:u}).eq("id",d);if(m)throw m;await V.from("attract_pipeline_history").insert({user_id:s.id,agent_id:d,from_stage:h??null,to_stage:u})},onSuccess:()=>r(),onError:d=>ae.error(d.message)}),l=Nt({mutationFn:async({id:d,values:u,changedLabels:h,previousStage:m})=>{const{stage:p,...g}=u;if(Object.keys(g).length){const{error:x}=await sW.from("attract_agents").update(g).eq("id",d);if(x)throw x}if(p&&p!==m){const{error:x}=await sW.from("attract_agents").update({stage:p}).eq("id",d);if(x)throw x;await sW.from("attract_pipeline_history").insert({user_id:s.id,agent_id:d,from_stage:m??null,to_stage:p})}h.length&&await sW.rpc("award_attract_activity",{_user_id:s.id,_activity_type:"note",_title:"Contact details updated",_description:`Updated: ${h.join(", ")}`,_pillar:"connect",_agent_id:d,_metadata:{},_dedupe_minutes:1})},onSuccess:()=>{r(),ae.success("Contact updated")},onError:d=>ae.error(d.message??"Could not save contact")}),o=Nt({mutationFn:async({id:d,archived:u})=>{const{error:h}=await sW.from("attract_agents").update({is_archived:u}).eq("id",d);if(h)throw h},onSuccess:(d,u)=>{r(),ae.success(u.archived?"Removed from active pipeline":"Restored to pipeline")},onError:d=>ae.error(d.message)}),c=Nt({mutationFn:async d=>{const{error:u}=await V.from("attract_agents").delete().eq("id",d);if(u)throw u},onSuccess:()=>{r(),ae.success("Contact permanently deleted")},onError:d=>ae.error(d.message)});return{agents:n.data??[],activeAgents:(n.data??[]).filter(d=>!d.is_archived),isLoading:n.isLoading,upsertAgent:a,saveAgentDetails:l,moveStage:i,archiveAgent:o,deleteAgent:c}}const O8e=[{key:"new_connection",label:"New Connection"},{key:"building_relationship",label:"Building Relationship"},{key:"engaging_with_value",label:"Engaging With Value"},{key:"active_conversation",label:"Active Conversation"},{key:"exploring_options",label:"Exploring Options"},{key:"brokerage_presentation",label:"Brokerage Presentation"},{key:"decision_pending",label:"Decision Pending"},{key:"joined",label:"Joined"}];function CHn(){const{agents:s}=A0(),t=Math.max(1,...O8e.map(n=>s.filter(r=>r.stage===n.key).length));return e.jsxs(we,{className:"p-6 rounded-2xl border-slate-200/70 bg-white shadow-sm",children:[e.jsxs("div",{className:"flex items-start justify-between mb-5",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11.5px] uppercase tracking-wider font-medium text-violet-600",children:"Pipeline Overview"}),e.jsx("div",{className:"text-[18px] font-semibold text-slate-900 mt-0.5",children:"Where relationships live right now"})]}),e.jsx($,{asChild:!0,variant:"outline",size:"sm",className:"rounded-full gap-1",children:e.jsxs(nr,{to:"/attract/relationships",children:["View All Relationships ",e.jsx(fi,{className:"h-3.5 w-3.5"})]})})]}),e.jsx("div",{className:"space-y-2",children:O8e.map((n,r)=>{const a=s.filter(o=>o.stage===n.key).length,i=30+a/t*70,l=.35+(1-r/O8e.length)*.55;return e.jsxs("div",{className:"grid grid-cols-[180px_1fr_36px] items-center gap-3",children:[e.jsx("span",{className:"text-[12.5px] text-slate-700 font-medium",children:n.label}),e.jsx("div",{className:"h-8 rounded-lg bg-slate-50 overflow-hidden",children:e.jsx("div",{className:"h-full rounded-lg flex items-center justify-end pr-3 text-white text-[11.5px] font-semibold",style:{width:`${i}%`,background:`linear-gradient(90deg, rgba(139,92,246,${l}) 0%, rgba(79,70,229,${l}) 100%)`},children:a>0&&a})}),e.jsx("span",{className:"text-[11px] tabular-nums text-slate-500 text-right",children:a})]},n.key)})})]})}function wWt(){const{user:s}=ks(),t=ls(),n=pt({queryKey:["attract-daily-plan",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:a,error:i}=await V.from("attract_daily_plan").select("*").order("sort_order");if(i)throw i;return a??[]}}),r=Nt({mutationFn:async a=>{const i=!a.completed,{error:l}=await V.from("attract_daily_plan").update({completed:i,progress:i?a.target:0}).eq("id",a.id);if(l)throw l},onSuccess:()=>t.invalidateQueries({queryKey:["attract-daily-plan"]})});return{items:n.data??[],isLoading:n.isLoading,toggle:r}}function ZTe(s=!0){const{intel:t,isLoading:n}=k6(),r=yWt(),a=YTe(),i=k.useRef(!1);return k.useEffect(()=>{if(!s||n||i.current||!t.length)return;const o=sessionStorage.getItem("attract-intel-sync"),c=new Date().toISOString().slice(0,13);if(o===c){i.current=!0;return}i.current=!0,sessionStorage.setItem("attract-intel-sync",c),r.mutate({items:t,silent:!0}),a.mutate(t)},[s,n,t]),{runNow:()=>{r.mutate({items:t}),a.mutate(t)},isSyncing:r.isPending||a.isPending}}function AHn(){const{items:s,toggle:t}=wWt(),{data:n=[]}=Nte(),{byId:r}=k6(),{logCompleted:a}=vWt();ZTe();const i=s.filter(u=>u.completed).length,l=s.length?Math.round(i/s.length*100):0,o=Date.now(),c=n.filter(u=>u.status==="open"||u.status==="snoozed"&&u.snoozed_until&&+new Date(u.snoozed_until)<=o).sort((u,h)=>h.rank_score-u.rank_score).slice(0,3),d=u=>{var m;const h=(m=r.get(u))==null?void 0:m.agent;return h?[h.first_name,h.last_name].filter(Boolean).join(" "):"this relationship"};return e.jsxs(we,{className:"p-6 rounded-2xl border-slate-200/70 bg-white shadow-sm",children:[e.jsxs("div",{className:"flex items-start justify-between mb-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11.5px] uppercase tracking-wider font-medium text-violet-600",children:"Today's Attraction Plan"}),e.jsx("div",{className:"text-[18px] font-semibold text-slate-900 mt-0.5",children:"Small daily reps compound."})]}),e.jsxs("div",{className:"text-right",children:[e.jsxs("div",{className:"text-2xl font-semibold tabular-nums text-slate-900",children:[i,e.jsxs("span",{className:"text-slate-400 text-base",children:["/",s.length]})]}),e.jsx("div",{className:"text-[11px] text-slate-500 uppercase tracking-wider",children:"complete"})]})]}),e.jsx("div",{className:"h-1.5 rounded-full bg-slate-100 mb-4 overflow-hidden",children:e.jsx("div",{className:"h-full rounded-full bg-gradient-to-r from-violet-500 to-indigo-500 transition-all",style:{width:`${l}%`}})}),e.jsx("ul",{className:"space-y-1.5",children:s.map(u=>e.jsxs("li",{onClick:()=>t.mutate(u),className:"group flex items-center gap-3 px-3 py-2.5 rounded-xl hover:bg-slate-50 cursor-pointer transition-colors",children:[e.jsx(Li,{checked:u.completed,className:"border-slate-300 data-[state=checked]:bg-violet-600 data-[state=checked]:border-violet-600"}),e.jsx("span",{className:`flex-1 text-[13.5px] ${u.completed?"line-through text-slate-400":"text-slate-800"}`,children:u.label}),e.jsxs("span",{className:"text-[11px] tabular-nums text-slate-400",children:[u.progress,"/",u.target]}),u.completed&&e.jsx(Gr,{className:"h-4 w-4 text-emerald-500"})]},u.id))}),e.jsxs("div",{className:"mt-5 pt-5 border-t border-slate-100",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wider font-semibold text-slate-500 mb-2.5",children:"Who to reach today"}),c.length?e.jsx("ul",{className:"space-y-2",children:c.map(u=>e.jsx("li",{className:"rounded-xl bg-slate-50 px-3 py-2.5",children:e.jsxs("div",{className:"flex items-start justify-between gap-2 flex-wrap",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx(nr,{to:`/attract/agents/${u.agent_id}`,className:"text-[13.5px] font-medium text-slate-900 hover:text-violet-700",children:d(u.agent_id)}),e.jsx("div",{className:"text-[12px] text-slate-600 mt-0.5",children:u.title}),e.jsx("div",{className:"text-[11.5px] text-slate-500 mt-0.5",children:(u.reasons??[]).slice(0,2).join(" · ")})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(qe,{variant:"outline",className:Ot("rounded-full text-[10.5px] capitalize",u.priority==="urgent"&&"bg-rose-50 text-rose-700 border-rose-200"),children:u.priority}),e.jsx($,{size:"sm",variant:"ghost",className:"rounded-full h-7 px-2 text-[11.5px]",onClick:()=>a.mutate({rec:u}),disabled:a.isPending,children:"Done"})]})]})},u.id))}):e.jsx("div",{className:"text-[13px] text-slate-500",children:"No recommendations right now — Attract only surfaces conversations backed by a real signal."})]}),e.jsxs("div",{className:"mt-4 flex justify-end gap-2",children:[e.jsx($,{variant:"ghost",size:"sm",className:"text-violet-700 hover:text-violet-900",asChild:!0,children:e.jsxs(nr,{to:"/attract/relationships",children:["All relationships ",e.jsx(xi,{className:"h-3.5 w-3.5 ml-1.5"})]})}),e.jsx($,{variant:"ghost",size:"sm",className:"text-violet-700 hover:text-violet-900",asChild:!0,children:e.jsx(nr,{to:"/attract/plan",children:"View full plan"})})]})]})}function dJe(s=12){const{user:t}=ks(),n=pt({queryKey:["attract-activities",t==null?void 0:t.id,s],enabled:!!t,queryFn:async()=>{const{data:r,error:a}=await V.from("attract_activities").select("*").order("created_at",{ascending:!1}).limit(s);if(a)throw a;return r??[]}});return{activities:n.data??[],isLoading:n.isLoading}}const EHn={agent_joined:kn,resource_shared:ou,presentation:hv,conversation:sB,social_engagement:Bo,new_agent:Pl,content_posted:xm,follow_up:op};function THn(){const{activities:s}=dJe(8);return e.jsxs(we,{className:"p-6 rounded-2xl border-slate-200/70 bg-white shadow-sm",children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("div",{className:"text-[11.5px] uppercase tracking-wider font-medium text-violet-600",children:"Recent Activity"}),e.jsx("div",{className:"text-[18px] font-semibold text-slate-900 mt-0.5",children:"Momentum from the past few days"})]}),e.jsxs("ol",{className:"relative space-y-4",children:[s.map(t=>{const n=EHn[t.activity_type]??kn;return e.jsxs("li",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"h-8 w-8 rounded-full bg-violet-50 grid place-items-center flex-shrink-0 mt-0.5",children:e.jsx(n,{className:"h-4 w-4 text-violet-600"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-[13.5px] font-medium text-slate-900 truncate",children:t.title}),t.description&&e.jsx("div",{className:"text-[12px] text-slate-500 truncate",children:t.description}),e.jsxs("div",{className:"text-[11px] text-slate-400 mt-0.5",children:[Zc(new Date(t.created_at),{addSuffix:!0}),t.pillar&&e.jsxs(e.Fragment,{children:[" · ",e.jsx("span",{className:"capitalize",children:t.pillar})]})]})]})]},t.id)}),s.length===0&&e.jsx("li",{className:"text-sm text-slate-500 text-center py-6",children:"No activity yet — start with one small touch today."})]})]})}function XTe(s){const{user:t}=ks();return pt({queryKey:["attract-events",t==null?void 0:t.id,s],enabled:!!t,queryFn:async()=>{let n=V.from("attract_events").select("*").eq("is_template",!1).order("starts_at",{ascending:!0});const{data:r,error:a}=await n;if(a)throw a;return r??[]}})}function uJe(s){return pt({queryKey:["attract-event",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await V.from("attract_events").select("*").eq("id",s).single();if(n)throw n;return t}})}function jWt(s){return pt({queryKey:["attract-event-attendees",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await V.from("attract_event_attendees").select("*, attract_agents(id, first_name, last_name, primary_pillar, stage)").eq("event_id",s).order("created_at",{ascending:!1});if(n)throw n;return t??[]}})}function MHn(s){return pt({queryKey:["attract-event-invitations",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await V.from("attract_event_invitations").select("*, attract_agents(id, first_name, last_name)").eq("event_id",s).order("created_at",{ascending:!1});if(n)throw n;return t??[]}})}function PHn(s){return pt({queryKey:["attract-event-notes",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await V.from("attract_event_notes").select("*").eq("event_id",s).order("created_at",{ascending:!1});if(n)throw n;return t??[]}})}function NWt(){return pt({queryKey:["attract-event-templates"],queryFn:async()=>{const{data:s,error:t}=await V.from("attract_event_templates").select("*").order("title");if(t)throw t;return s??[]}})}function kWt(){const{user:s}=ks(),t=ls();return Nt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const r={user_id:s.id,title:n.title||"Untitled event",starts_at:n.starts_at||new Date(Date.now()+7*864e5).toISOString(),status:"draft",...n},{data:a,error:i}=await V.from("attract_events").insert(r).select().single();if(i)throw i;return a},onSuccess:()=>t.invalidateQueries({queryKey:["attract-events"]})})}function SWt(){const s=ls();return Nt({mutationFn:async({id:t,patch:n})=>{const{data:r,error:a}=await V.from("attract_events").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:t=>{s.invalidateQueries({queryKey:["attract-events"]}),s.invalidateQueries({queryKey:["attract-event",t.id]})}})}function IHn(){const s=ls();return Nt({mutationFn:async t=>{const{error:n}=await V.from("attract_events").delete().eq("id",t);if(n)throw n},onSuccess:()=>s.invalidateQueries({queryKey:["attract-events"]})})}function CWt(){const{user:s}=ks(),t=ls();return Nt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const r={user_id:s.id,...n},{data:a,error:i}=n.id?await V.from("attract_event_attendees").update(r).eq("id",n.id).select().single():await V.from("attract_event_attendees").insert(r).select().single();if(i)throw i;return a},onSuccess:n=>{t.invalidateQueries({queryKey:["attract-event-attendees",n.event_id]}),t.invalidateQueries({queryKey:["attract-event",n.event_id]})}})}function LHn(){const{user:s}=ks(),t=ls();return Nt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r,error:a}=await V.from("attract_event_notes").insert({user_id:s.id,...n}).select().single();if(a)throw a;return r},onSuccess:n=>t.invalidateQueries({queryKey:["attract-event-notes",n.event_id]})})}function RHn(){const{user:s}=ks(),t=ls();return Nt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r,error:a}=await V.from("attract_event_invitations").insert({user_id:s.id,...n}).select().single();if(a)throw a;return r},onSuccess:n=>t.invalidateQueries({queryKey:["attract-event-invitations",n.event_id]})})}function DHn(){const{user:s}=ks(),t=ls();return Nt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r,error:a}=await V.from("attract_events").select("*").eq("id",n).single();if(a)throw a;const{id:i,public_slug:l,check_in_token:o,published_at:c,registration_count:d,attendance_count:u,created_at:h,updated_at:m,...p}=r,{data:g,error:x}=await V.from("attract_events").insert({...p,title:r.title+" (Copy)",status:"draft"}).select().single();if(x)throw x;return g},onSuccess:()=>t.invalidateQueries({queryKey:["attract-events"]})})}function QTe(s){return`${window.location.origin}/attract-event/${s}`}function OHn(s,t){return`${window.location.origin}/attract-event-checkin/${s}?a=${encodeURIComponent(t)}`}function AWt(s){const t=l=>l.toISOString().replace(/[-:]/g,"").replace(/\.\d{3}/,""),n=new Date(s.starts_at),r=s.ends_at?new Date(s.ends_at):new Date(n.getTime()+60*60*1e3),a=[s.location,s.address,s.virtual_url].filter(Boolean).join(" — ");return["BEGIN:VCALENDAR","VERSION:2.0","PRODID:-//LevelUp Attract//EN","BEGIN:VEVENT",`UID:${`${Date.now()}@attract.levelup`}`,`DTSTAMP:${t(new Date)}`,`DTSTART:${t(n)}`,`DTEND:${t(r)}`,`SUMMARY:${(s.title||"").replace(/\n/g," ")}`,`DESCRIPTION:${(s.description||"").replace(/\n/g,"\\n")}`,`LOCATION:${a.replace(/\n/g," ")}`,"END:VEVENT","END:VCALENDAR"].join(`\r `)}function EWt(){const{data:s=[]}=XTe(),t=s.slice(0,3);return e.jsxs(we,{className:"p-6 rounded-2xl border-slate-200/70 bg-white shadow-sm",children:[e.jsxs("div",{className:"flex items-start justify-between mb-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11.5px] uppercase tracking-wider font-medium text-violet-600",children:"Upcoming Events"}),e.jsx("div",{className:"text-[18px] font-semibold text-slate-900 mt-0.5",children:"Places where relationships happen"})]}),e.jsxs($,{variant:"outline",size:"sm",className:"rounded-full gap-1",children:[e.jsx(nn,{className:"h-3.5 w-3.5"})," Create"]})]}),e.jsxs("div",{className:"space-y-3",children:[t.map(n=>{var i,l;const r=new Date(n.starts_at),a=((l=(i=n.attract_event_attendees)==null?void 0:i[0])==null?void 0:l.count)??0;return e.jsxs("div",{className:"flex items-center gap-4 p-3 rounded-xl hover:bg-slate-50 transition-colors",children:[e.jsxs("div",{className:"w-14 flex-shrink-0 text-center rounded-xl bg-gradient-to-br from-violet-500 to-indigo-600 text-white py-2",children:[e.jsx("div",{className:"text-[10.5px] uppercase tracking-wider opacity-90",children:Ys(r,"MMM")}),e.jsx("div",{className:"text-xl font-semibold leading-tight",children:Ys(r,"d")})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-[14px] font-semibold text-slate-900 truncate",children:n.title}),e.jsxs("div",{className:"text-[12px] text-slate-500 flex items-center gap-2 mt-0.5",children:[e.jsx("span",{children:Ys(r,"p")}),"·",n.event_type==="virtual"?e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ia,{className:"h-3 w-3"})," Virtual"]}):e.jsxs("span",{className:"flex items-center gap-1 truncate",children:[e.jsx(Si,{className:"h-3 w-3"})," ",n.location]})]})]}),e.jsxs("div",{className:"text-right",children:[e.jsx("div",{className:"text-[13px] font-semibold text-slate-900",children:a}),e.jsx("div",{className:"text-[10px] text-slate-400 uppercase tracking-wider",children:"RSVPs"})]})]},n.id)}),t.length===0&&e.jsxs("div",{className:"text-center py-8 text-slate-500",children:[e.jsx(nk,{className:"h-6 w-6 mx-auto text-slate-300 mb-2"}),e.jsx("div",{className:"text-sm",children:"No upcoming events yet."})]})]})]})}function TWt(){const{user:s}=ks(),t=pt({queryKey:["attract-resources",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:r,error:a}=await V.from("attract_resources").select("*").order("created_at",{ascending:!1});if(a)throw a;return r??[]}}),n=pt({queryKey:["attract-resource-shares",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:r,error:a}=await V.from("attract_resource_shares").select("*").order("created_at",{ascending:!1});if(a)throw a;return r??[]}});return{resources:t.data??[],shares:n.data??[],isLoading:t.isLoading}}function FHn(){const{shares:s}=TWt(),t={resources:s.length,emails:s.filter(r=>r.channel==="email").length,opens:s.filter(r=>r.opened_at).length,clicks:s.filter(r=>r.clicked_at).length},n=[{label:"Resources Shared",value:t.resources,icon:ou,tone:"text-violet-600 bg-violet-50"},{label:"Emails Sent",value:t.emails,icon:Wr,tone:"text-teal-600 bg-teal-50"},{label:"Agent Opens",value:t.opens,icon:Xz,tone:"text-emerald-600 bg-emerald-50"},{label:"Clicks",value:t.clicks,icon:rh,tone:"text-orange-600 bg-orange-50"}];return e.jsxs(we,{className:"p-6 rounded-2xl border-slate-200/70 bg-white shadow-sm",children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("div",{className:"text-[11.5px] uppercase tracking-wider font-medium text-violet-600",children:"Value Shared This Week"}),e.jsx("div",{className:"text-[18px] font-semibold text-slate-900 mt-0.5",children:"Small gifts, measured."})]}),e.jsx("div",{className:"grid grid-cols-2 gap-3",children:n.map(r=>e.jsxs("div",{className:"rounded-xl border border-slate-100 p-3.5",children:[e.jsx("div",{className:`h-8 w-8 rounded-lg grid place-items-center ${r.tone}`,children:e.jsx(r.icon,{className:"h-4 w-4"})}),e.jsx("div",{className:"text-[22px] font-semibold tabular-nums text-slate-900 mt-2 leading-none",children:r.value}),e.jsx("div",{className:"text-[11.5px] text-slate-500 mt-1",children:r.label})]},r.label))})]})}function zHn(){const{agents:s}=A0(),t=s.filter(r=>r.stage==="joined").sort((r,a)=>(a.joined_at??"").localeCompare(r.joined_at??"")),n=t.reduce((r,a)=>r+(Number(a.est_revenue_share)||0),0);return e.jsxs(we,{className:"p-6 rounded-2xl border-slate-200/70 bg-white shadow-sm",children:[e.jsxs("div",{className:"flex items-start justify-between mb-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11.5px] uppercase tracking-wider font-medium text-violet-600",children:"Agents Joined"}),e.jsxs("div",{className:"text-[18px] font-semibold text-slate-900 mt-0.5",children:["Est. annual rev share ",e.jsx("span",{className:"text-violet-700",children:yh(n)})]})]}),e.jsx(kn,{className:"h-5 w-5 text-violet-500"})]}),e.jsxs("ul",{className:"space-y-2.5",children:[t.map(r=>{var a;return e.jsxs("li",{className:"flex items-center gap-3 p-2.5 rounded-xl hover:bg-slate-50",children:[e.jsxs("div",{className:"h-9 w-9 rounded-full bg-gradient-to-br from-violet-500 to-indigo-600 text-white grid place-items-center text-[13px] font-semibold flex-shrink-0",children:[r.first_name[0],((a=r.last_name)==null?void 0:a[0])??""]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"text-[13.5px] font-semibold text-slate-900 truncate",children:[r.first_name," ",r.last_name]}),e.jsxs("div",{className:"text-[11.5px] text-slate-500 truncate",children:[r.brokerage," · ",r.city,", ",r.state]})]}),e.jsxs("div",{className:"text-right",children:[e.jsx("div",{className:"text-[13px] font-semibold text-emerald-600 tabular-nums",children:r.est_revenue_share?yh(Number(r.est_revenue_share)):"—"}),e.jsx("div",{className:"text-[10.5px] text-slate-400",children:r.joined_at?Zc(new Date(r.joined_at),{addSuffix:!0}):""})]})]},r.id)}),t.length===0&&e.jsx("li",{className:"text-sm text-slate-500 text-center py-6",children:"No joined agents yet."})]})]})}function QF(){const{user:s}=ks(),t=ls(),n=pt({queryKey:["attract-followups",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:a,error:i}=await V.from("attract_follow_ups").select("*").order("due_at",{ascending:!0,nullsFirst:!1});if(i)throw i;return a??[]}}),r=Nt({mutationFn:async a=>{const{error:i}=await V.from("attract_follow_ups").update({completed_at:new Date().toISOString()}).eq("id",a);if(i)throw i},onSuccess:()=>t.invalidateQueries({queryKey:["attract-followups"]})});return{followUps:n.data??[],isLoading:n.isLoading,complete:r}}function BHn(s){var r;const t=(s==null?void 0:s.user_metadata)??{},n=t.full_name||t.name||((r=s==null?void 0:s.email)==null?void 0:r.split("@")[0])||"there";return String(n).split(" ")[0]}const Pwt={produce:{label:"Your primary pillar is Produce — log one recent transaction today.",cta:"Open Transaction Tracker",to:"/attract/produce/transaction-tracker"},influence:{label:"Your primary pillar is Influence — create one authority post today.",cta:"Open Content Studio",to:"/attract/influence/content-studio"},provide:{label:"Your primary pillar is Provide — share one resource with an agent today.",cta:"Open Resources",to:"/attract/resources"},connect:{label:"Your primary pillar is Connect — schedule one 1:1 this week.",cta:"Open Follow-Up Center",to:"/attract/follow-up"},balanced:{label:"Balanced plan — pick one pillar for today and go deep.",cta:"View 90-Day Plan",to:"/attract/plan"}};function $Hn(){const{user:s}=ks(),t=Jn(),{agents:n}=A0(),{followUps:r}=QF(),{settings:a}=KV(),[i,l]=k.useState(!1),o=k.useMemo(()=>{const h=np(new Date),m=n.filter(_=>!["joined","not_a_fit","not_right_now"].includes(_.stage)).length,p=n.filter(_=>new Date(_.created_at)>wu(h,-30)).length,g=r.filter(_=>!_.completed_at&&_.due_at&&ah(new Date(_.due_at),h)).length,x=r.filter(_=>!_.completed_at&&_.due_at&&Xw(new Date(_.due_at),h)).length,v=n.filter(_=>_.stage==="joined").reduce((_,j)=>_+(Number(j.est_revenue_share)||0),0);return{inPipeline:m,newRels:p,dueToday:g,overdue:x,revShare:v}},[n,r]),c=(a==null?void 0:a.primary_pillar)||(a==null?void 0:a.attraction_style)||"balanced",d=Pwt[c]??Pwt.balanced,u=a==null?void 0:a.ninety_day_plan;return e.jsxs("div",{children:[e.jsxs("div",{className:"flex flex-col md:flex-row md:items-center md:justify-between gap-4 mb-8",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-violet-600 font-semibold mb-2",children:"LevelUp Attract"}),e.jsxs("h1",{className:"text-3xl md:text-[34px] font-semibold tracking-tight text-slate-900",children:["Good to see you, ",BHn(s),"."]}),e.jsxs("p",{className:"text-slate-600 mt-1.5",children:["Here's your attraction overview for today · ",Ys(new Date,"EEEE, MMM d")]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(bs,{defaultValue:"week",children:[e.jsx(ys,{className:"w-[150px] rounded-full bg-white",children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"week",children:"This Week"}),e.jsx(We,{value:"month",children:"This Month"}),e.jsx(We,{value:"90",children:"Last 90 Days"})]})]}),e.jsx($,{variant:"outline",size:"icon",className:"rounded-full",children:e.jsx(Fx,{className:"h-4 w-4"})}),e.jsxs(Au,{children:[e.jsx(Eu,{asChild:!0,children:e.jsxs($,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600 hover:from-violet-700 hover:to-indigo-700 gap-1.5 shadow-sm",children:[e.jsx(nn,{className:"h-4 w-4"})," Add New ",e.jsx(Go,{className:"h-3.5 w-3.5 opacity-70"})]})}),e.jsxs(gu,{align:"end",className:"w-64",children:[e.jsx(TO,{children:"Quick add"}),e.jsx(j0,{}),e.jsxs(Pa,{onClick:()=>t("/attract/pipeline?new=1"),children:[e.jsx(Pl,{className:"h-4 w-4 mr-2"})," Add Agent to Pipeline"]}),e.jsxs(Pa,{onClick:()=>t("/attract/produce/transaction-tracker"),children:[e.jsx(ri,{className:"h-4 w-4 mr-2"})," Log a Transaction"]}),e.jsxs(Pa,{onClick:()=>t("/attract/influence/content-studio"),children:[e.jsx(vf,{className:"h-4 w-4 mr-2"})," Create Authority Content"]}),e.jsxs(Pa,{onClick:()=>t("/attract/follow-up"),children:[e.jsx(op,{className:"h-4 w-4 mr-2"})," Add Follow-Up"]}),e.jsxs(Pa,{onClick:()=>t("/attract/events/new"),children:[e.jsx(i1,{className:"h-4 w-4 mr-2"})," Plan an Event"]}),e.jsxs(Pa,{onClick:()=>t("/attract/resources"),children:[e.jsx(xb,{className:"h-4 w-4 mr-2"})," Add Resource"]})]})]})]})]}),e.jsx(we,{className:"p-4 rounded-2xl mb-6 bg-gradient-to-r from-violet-50 to-indigo-50 border-violet-100",children:e.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[e.jsx("div",{className:"h-10 w-10 rounded-xl bg-white grid place-items-center text-violet-700 shadow-sm",children:e.jsx(_h,{className:"h-5 w-5"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-[10.5px] uppercase tracking-widest text-violet-700 font-semibold",children:"Today's move"}),e.jsx("div",{className:"text-[14px] font-semibold text-slate-900",children:d.label}),u&&e.jsxs("div",{className:"text-[12px] text-slate-600 mt-0.5",children:["Weekly goal: ",u.weekly_targets.new_relationships," new relationships · ",u.weekly_targets.content_pieces," content pieces"]})]}),e.jsx($,{size:"sm",className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>t(d.to),children:d.cta})]})}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 xl:grid-cols-5 gap-4 mb-6",children:[e.jsx(tW,{label:"Agents in Pipeline",value:o.inPipeline,delta:"+3 this week",icon:tb,tone:"violet"}),e.jsx(tW,{label:"New Relationships",value:o.newRels,delta:"+2 this week",icon:mc,tone:"teal"}),e.jsx(tW,{label:"Follow-Ups Due Today",value:o.dueToday,icon:kK,tone:"orange"}),e.jsx(tW,{label:"Overdue Follow-Ups",value:o.overdue,icon:Gd,tone:"rose"}),e.jsx(tW,{label:"Est. Revenue Share",value:yh(o.revShare,!0),delta:"annualized",icon:Su,tone:"green"})]}),e.jsxs("div",{className:"grid grid-cols-1 xl:grid-cols-3 gap-6",children:[e.jsxs("div",{className:"xl:col-span-2 space-y-6",children:[e.jsx(_Wt,{}),e.jsx(CHn,{}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[e.jsx(THn,{}),e.jsx(EWt,{})]})]}),e.jsxs("div",{className:"space-y-6",children:[e.jsx(AHn,{}),e.jsx(FHn,{}),e.jsx(zHn,{})]})]}),e.jsx("div",{className:"mt-8 rounded-2xl overflow-hidden bg-gradient-to-r from-violet-600 via-indigo-600 to-violet-700 p-6 md:p-7 text-white shadow-lg",children:e.jsxs("div",{className:"flex items-center justify-between gap-4 flex-wrap",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] opacity-80 mb-1",children:"Your 90-day promise"}),e.jsx("div",{className:"text-lg md:text-xl font-semibold",children:(u==null?void 0:u.outcome)??"Show up for agents the way you'd want someone to show up for you."}),e.jsx("div",{className:"text-white/80 mt-1 text-[13.5px]",children:"Small daily reps compound. Keep the rhythm."})]}),e.jsx($,{asChild:!0,variant:"secondary",className:"rounded-full bg-white text-violet-700 hover:bg-white/90",children:e.jsx(nr,{to:"/attract/plan",children:"View 90-Day Plan"})})]})})]})}const Iwt={call:{icon:ka,label:"Call"},text:{icon:bo,label:"Text"},email:{icon:pn,label:"Email"},dm:{icon:Wr,label:"DM"},resource_share:{icon:xb,label:"Share a kit"},event_invitation:{icon:i1,label:"Invite to event"},personal_check_in:{icon:B8,label:"Personal check-in"}},Lwt={urgent:"bg-rose-50 text-rose-700 ring-rose-200",high:"bg-orange-50 text-orange-700 ring-orange-200",medium:"bg-amber-50 text-amber-700 ring-amber-200",low:"bg-slate-50 text-slate-600 ring-slate-200"};function UHn(s){var t;return((t=xWt.find(n=>n.key===s))==null?void 0:t.blurb)??""}function MWt(s){var t;return((t=xWt.find(n=>n.key===s))==null?void 0:t.label)??s.replace(/_/g," ")}function gCe({rec:s,agentName:t,agentStage:n,kitTitle:r,eventTitle:a,compact:i,showAgentLink:l=!0,className:o}){const{update:c,dismiss:d,snooze:u,createFollowUp:h,logCompleted:m}=vWt(),[p,g]=k.useState(!1),[x,y]=k.useState(s.draft_message??""),v=c.isPending||d.isPending||u.isPending||h.isPending||m.isPending,_=Iwt[s.channel]??Iwt.personal_check_in,j=s.suggested_due_at?new Date(s.suggested_due_at):null,C=j?j{c.mutate({id:s.id,patch:{draft_message:x}},{onSuccess:()=>{g(!1),ae.success("Opening message updated")}})},M=async()=>{try{await navigator.clipboard.writeText(s.draft_message??""),ae.success("Opening message copied — send it yourself from your phone or inbox")}catch{ae.error("Could not copy — select the text manually")}};return e.jsx(we,{className:Ot("rounded-2xl border-slate-200/70 bg-white shadow-sm overflow-hidden",o),children:e.jsxs("div",{className:"p-4 sm:p-5",children:[e.jsxs("div",{className:"flex items-start gap-3 flex-wrap",children:[e.jsx("div",{className:"h-10 w-10 rounded-xl bg-gradient-to-br from-violet-500 to-indigo-600 text-white grid place-items-center shadow-sm flex-shrink-0",children:e.jsx(_.icon,{className:"h-4.5 w-4.5","aria-hidden":!0})}),e.jsxs("div",{className:"flex-1 min-w-[180px]",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx(qe,{variant:"outline",className:Ot("rounded-full text-[10.5px] uppercase tracking-wider font-semibold ring-1 border-transparent",Lwt[s.priority]??Lwt.medium),children:s.priority}),e.jsx("span",{className:"text-[11px] text-violet-700 font-medium",children:MWt(s.signal_group)}),s.is_demo&&e.jsx(qe,{variant:"outline",className:"rounded-full text-[10px] bg-slate-100 text-slate-500 border-transparent",children:"Demo data"})]}),e.jsx("h3",{className:"text-[15px] font-semibold text-slate-900 mt-1.5 leading-snug",children:s.title}),e.jsxs("div",{className:"text-[12px] text-slate-500 mt-1 flex items-center gap-2 flex-wrap",children:[l?e.jsxs(nr,{to:`/attract/agents/${s.agent_id}`,className:"font-medium text-slate-700 hover:text-violet-700 inline-flex items-center gap-0.5",children:[t," ",e.jsx(fi,{className:"h-3 w-3"})]}):e.jsx("span",{className:"font-medium text-slate-700",children:t}),n&&e.jsxs("span",{className:"capitalize",children:["· ",n.replace(/_/g," ")]}),e.jsxs("span",{children:["· ",_.label]}),j&&e.jsxs("span",{className:Ot("inline-flex items-center gap-1",C?"text-rose-600 font-medium":""),children:["· ",e.jsx(sa,{className:"h-3 w-3"})," ",C?"Due now":`Do by ${j.toLocaleDateString()}`]})]})]}),e.jsxs(Au,{children:[e.jsx(Eu,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:"rounded-full","aria-label":"More recommendation actions",children:e.jsx(Z0,{className:"h-4 w-4"})})}),e.jsxs(gu,{align:"end",className:"w-56",children:[e.jsx(TO,{children:"Recommendation"}),e.jsx(j0,{}),e.jsxs(Pa,{onClick:()=>g(I=>!I),children:[e.jsx(ui,{className:"h-4 w-4 mr-2"})," Edit opening message"]}),e.jsxs(Pa,{onClick:M,children:[e.jsx(Da,{className:"h-4 w-4 mr-2"})," Copy message"]}),e.jsx(j0,{}),e.jsxs(Pa,{onClick:()=>u.mutate({id:s.id,days:3}),children:[e.jsx(sa,{className:"h-4 w-4 mr-2"})," Snooze 3 days"]}),e.jsxs(Pa,{onClick:()=>u.mutate({id:s.id,days:7}),children:[e.jsx(sa,{className:"h-4 w-4 mr-2"})," Snooze 1 week"]}),e.jsxs(Pa,{className:"text-rose-600",onClick:()=>d.mutate(s.id),children:[e.jsx(mr,{className:"h-4 w-4 mr-2"})," Dismiss"]})]})]})]}),!!(s.reasons??[]).length&&e.jsxs("div",{className:"mt-3 rounded-xl bg-slate-50 p-3",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-[10.5px] uppercase tracking-wider font-semibold text-slate-500 mb-1.5",children:[e.jsx(T5,{className:"h-3 w-3"})," Why this, right now"]}),e.jsx("ul",{className:"space-y-1",children:s.reasons.map((I,P)=>e.jsxs("li",{className:"text-[12.5px] text-slate-700 flex gap-2",children:[e.jsx("span",{className:"text-violet-500",children:"•"}),e.jsx("span",{children:I})]},P))}),e.jsx("div",{className:"text-[11px] text-slate-400 mt-2",children:UHn(s.signal_group)})]}),!i&&e.jsxs("div",{className:"mt-3",children:[e.jsx("div",{className:"text-[10.5px] uppercase tracking-wider font-semibold text-slate-500 mb-1.5",children:"Suggested opening"}),p?e.jsxs("div",{className:"space-y-2",children:[e.jsx(Ls,{value:x,onChange:I=>y(I.target.value),rows:4,className:"text-[13.5px]","aria-label":"Opening message"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{size:"sm",className:"rounded-full btn-primary text-white",onClick:A,disabled:v,children:"Save message"}),e.jsx($,{size:"sm",variant:"ghost",className:"rounded-full",onClick:()=>{y(s.draft_message??""),g(!1)},children:"Cancel"})]})]}):e.jsxs("button",{onClick:()=>g(!0),className:"w-full text-left rounded-xl border border-slate-200 bg-white p-3 text-[13.5px] leading-relaxed text-slate-700 hover:border-violet-300 transition-colors",children:[s.draft_message||"No draft message yet — click to write one.",e.jsx("span",{className:"block text-[11px] text-violet-600 mt-1.5",children:"Click to edit before you send"})]})]}),(r||a)&&e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2 text-[11.5px]",children:[r&&e.jsxs("span",{className:"rounded-full bg-teal-50 text-teal-700 px-2.5 py-1",children:["Suggested kit: ",r]}),a&&e.jsxs("span",{className:"rounded-full bg-indigo-50 text-indigo-700 px-2.5 py-1",children:["Suggested event: ",a]})]}),e.jsxs("div",{className:"mt-4 flex flex-wrap gap-2",children:[e.jsxs($,{size:"sm",className:"rounded-full btn-primary text-white",disabled:v,onClick:()=>m.mutate({rec:s}),children:[e.jsx(ma,{className:"h-3.5 w-3.5 mr-1.5"})," I did this"]}),e.jsxs($,{size:"sm",variant:"outline",className:"rounded-full",disabled:v,onClick:()=>h.mutate(s),children:[e.jsx(i1,{className:"h-3.5 w-3.5 mr-1.5"})," ",s.follow_up_id?"Follow-up created":"Create follow-up"]}),e.jsxs($,{size:"sm",variant:"ghost",className:"rounded-full",onClick:M,children:[e.jsx(Da,{className:"h-3.5 w-3.5 mr-1.5"})," Copy message"]})]}),e.jsx("div",{className:"text-[10.5px] text-slate-400 mt-2",children:"Attract never sends messages for you — copy the opening and send it from your own phone or inbox."})]})})}function qHn({label:s="Nothing needs attention right now."}){return e.jsxs(we,{className:"rounded-2xl border-dashed border-slate-300 bg-white/60 p-8 text-center",children:[e.jsx("div",{className:"h-11 w-11 rounded-2xl bg-emerald-50 text-emerald-600 grid place-items-center mx-auto mb-3",children:e.jsx(ma,{className:"h-5 w-5"})}),e.jsx("div",{className:"text-[15px] font-semibold text-slate-800",children:s}),e.jsx("div",{className:"text-[13px] text-slate-500 mt-1",children:"Log a conversation, share a resource kit, or invite someone to an event and new opportunities will appear here."})]})}const vM=[{key:"new_relationship",label:"New Relationship",help:"You know each other, but you haven’t built much yet.",color:"#94a3b8",legacy:["new_connection"],canonical:"new_connection"},{key:"building",label:"Building Relationship",help:"Real conversations and value are going back and forth.",color:"#38bdf8",legacy:["building_relationship","engaging_with_value","long_term_relationship"],canonical:"building_relationship"},{key:"curious",label:"Brokerage Curious",help:"They’ve started asking questions about how you work.",color:"#8b5cf6",legacy:["active_conversation","exploring_options"],canonical:"active_conversation"},{key:"considering",label:"Considering a Move",help:"They’re actively weighing a change.",color:"#f59e0b",legacy:["brokerage_presentation","decision_pending"],canonical:"decision_pending"},{key:"joined",label:"Joined",help:"They made the move.",color:"#16a34a",legacy:["joined"],canonical:"joined"}],JTe={key:"set_aside",label:"Set Aside",help:"Not a fit right now — the relationship still matters.",color:"#cbd5e1",legacy:["not_right_now","not_a_fit"],canonical:"not_right_now"},PWt=new Map;for(const s of[...vM,JTe])for(const t of s.legacy)PWt.set(t,s);function GB(s){return s?PWt.get(s)??vM[0]:vM[0]}function IWt(s){return GB(s).label}function hJe(s){var n;return((n=[...vM,JTe].find(r=>r.key===s))==null?void 0:n.canonical)??"new_connection"}const F8e={first_name:"",last_name:"",brokerage:"",email:"",phone:"",city:"",source:"",notes:""};function LWt({open:s,onOpenChange:t,defaultStageKey:n,onAdded:r}){const{upsertAgent:a,agents:i}=A0(),[l,o]=k.useState({...F8e}),c=h=>m=>o(p=>({...p,[h]:m.target.value})),d=i.find(h=>{var m;return!!l.email&&((m=h.email)==null?void 0:m.toLowerCase())===l.email.trim().toLowerCase()||!!l.phone&&(h.phone??"").replace(/\D/g,"")===l.phone.replace(/\D/g,"")&&l.phone.replace(/\D/g,"").length>6}),u=()=>{a.mutate({...l,first_name:l.first_name.trim(),stage:hJe(n??"new_relationship"),temperature:"warm"},{onSuccess:h=>{o({...F8e}),t(!1),r==null||r(h==null?void 0:h.id)}})};return e.jsx(zs,{open:s,onOpenChange:h=>{t(h),h||o({...F8e})},children:e.jsxs(Rs,{className:"max-w-lg",children:[e.jsxs(Vs,{children:[e.jsx($s,{children:"Add a relationship"}),e.jsx(Cr,{className:"text-[13px]",children:"Just the basics. You can fill in the rest whenever it comes up naturally."})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(re,{children:"First name *"}),e.jsx(be,{value:l.first_name,onChange:c("first_name"),autoFocus:!0})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Last name"}),e.jsx(be,{value:l.last_name,onChange:c("last_name")})]}),e.jsxs("div",{className:"col-span-2",children:[e.jsx(re,{children:"Brokerage"}),e.jsx(be,{value:l.brokerage,onChange:c("brokerage"),placeholder:"Where they hang their license"})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Email"}),e.jsx(be,{type:"email",value:l.email,onChange:c("email")})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Phone"}),e.jsx(be,{value:l.phone,onChange:c("phone")})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Market"}),e.jsx(be,{value:l.city,onChange:c("city"),placeholder:"City or area"})]}),e.jsxs("div",{children:[e.jsx(re,{children:"How you know each other"}),e.jsx(be,{value:l.source,onChange:c("source"),placeholder:"Co-op deal, event, referral…"})]}),e.jsxs("div",{className:"col-span-2",children:[e.jsx(re,{children:"Note (optional)"}),e.jsx(Ls,{rows:2,value:l.notes,onChange:c("notes"),placeholder:"Anything worth remembering"})]})]}),d&&e.jsxs("div",{className:"rounded-xl bg-amber-50 border border-amber-200 px-3 py-2 text-[12.5px] text-amber-900",children:["Heads up — ",d.first_name," ",d.last_name??""," already has this contact info in your relationships."]}),e.jsxs(kr,{children:[e.jsx($,{variant:"ghost",onClick:()=>t(!1),children:"Cancel"}),e.jsx($,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600 text-white",disabled:!l.first_name.trim()||a.isPending,onClick:u,children:"Add relationship"})]})]})})}function VHn(s){var r;const t=(s==null?void 0:s.user_metadata)??{},n=t.full_name||t.name||((r=s==null?void 0:s.email)==null?void 0:r.split("@")[0])||"there";return String(n).split(" ")[0]}function HHn(){const s=new Date().getHours();return s<12?"Good morning":s<18?"Good afternoon":"Good evening"}const Rwt=20;function GHn(){const{user:s}=ks(),{intel:t,byId:n,isLoading:r}=k6(),{data:a=[],isLoading:i}=Nte(),l=YTe();ZTe();const{items:o,toggle:c}=wWt(),{agents:d,isLoading:u}=A0(),{followUps:h}=QF(),{activities:m}=dJe(200),[p,g]=k.useState(!1),x=r||i||u,y=k.useMemo(()=>{const C=Date.now();return a.filter(A=>A.status==="open"||A.status==="snoozed"&&A.snoozed_until&&+new Date(A.snoozed_until)<=C).sort((A,M)=>M.rank_score-A.rank_score).slice(0,5)},[a]),v=k.useMemo(()=>{const C=new Date;C.setHours(0,0,0,0),C.setDate(C.getDate()-(C.getDay()+6)%7);const A=m.filter(P=>new Date(P.created_at)>=C).length,M=h.filter(P=>P.completed_at&&new Date(P.completed_at)>=C).length,I=A+M;return{moves:I,pct:Math.min(100,Math.round(I/Rwt*100))}},[m,h]),_=C=>{var M;const A=(M=n.get(C))==null?void 0:M.agent;return A?[A.first_name,A.last_name].filter(Boolean).join(" "):"this relationship"},j=d.length>0;return e.jsxs("div",{className:"max-w-3xl mx-auto",children:[e.jsx(LWt,{open:p,onOpenChange:g}),e.jsxs("div",{className:"mb-7",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-violet-600 font-semibold mb-2",children:"LevelUp Attract"}),e.jsxs("h1",{className:"text-[28px] md:text-[34px] font-semibold tracking-tight text-slate-900 leading-tight",children:[HHn(),", ",VHn(s),". Here are your best moves today."]}),e.jsx("p",{className:"text-slate-600 mt-2 text-[14.5px]",children:"Build relationships. Provide value. Let the opportunity develop naturally."}),e.jsxs("div",{className:"mt-5 rounded-2xl bg-white border border-slate-200/70 px-4 py-3.5 shadow-sm",children:[e.jsxs("div",{className:"flex items-baseline justify-between gap-3",children:[e.jsxs("div",{className:"text-[13.5px] text-slate-700",children:[e.jsxs("span",{className:"font-semibold text-slate-900 tabular-nums",children:[v.moves," of ",Rwt]})," meaningful moves completed this week"]}),e.jsx("span",{className:"text-[11px] uppercase tracking-wider text-slate-400",children:"This week"})]}),e.jsx("div",{className:"h-1.5 rounded-full bg-slate-100 mt-2.5 overflow-hidden",children:e.jsx("div",{className:"h-full rounded-full bg-gradient-to-r from-violet-500 to-indigo-500 transition-all",style:{width:`${v.pct}%`}})})]})]}),e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsx("h2",{className:"text-[13px] font-semibold uppercase tracking-wider text-slate-600",children:"Today’s actions"}),!x&&e.jsxs($,{variant:"ghost",size:"sm",className:"rounded-full text-slate-500 h-8",onClick:()=>l.mutate(t),disabled:l.isPending,children:[e.jsx(yo,{className:Ot("h-3.5 w-3.5 mr-1.5",l.isPending&&"animate-spin")})," Refresh"]})]}),x?e.jsxs("div",{className:"space-y-3","aria-busy":"true",children:[e.jsx("div",{className:"text-[13px] text-slate-500",children:"Looking at your relationships…"}),[0,1,2].map(C=>e.jsx(fn,{className:"h-40 w-full rounded-2xl"},C))]}):y.length?e.jsx("div",{className:"space-y-3",children:y.map(C=>{var A;return e.jsx(gCe,{rec:C,agentName:_(C.agent_id),agentStage:IWt((A=n.get(C.agent_id))==null?void 0:A.agent.stage)},C.id)})}):j?e.jsxs(we,{className:"rounded-2xl border-dashed border-slate-300 bg-white/60 p-8 text-center",children:[e.jsx(kn,{className:"h-6 w-6 mx-auto text-violet-500 mb-2"}),e.jsx("div",{className:"text-[15px] font-semibold text-slate-800",children:"You’re caught up."}),e.jsx("p",{className:"text-[13px] text-slate-500 mt-1 max-w-md mx-auto",children:"No follow-ups are due. This is a great time to reconnect with someone you haven’t spoken with recently, or share one useful resource."}),e.jsxs("div",{className:"flex gap-2 justify-center mt-4 flex-wrap",children:[e.jsx($,{className:"rounded-full btn-primary text-white",asChild:!0,children:e.jsx(nr,{to:"/attract/relationships?view=attention",children:"See who’s gone quiet"})}),e.jsx($,{variant:"outline",className:"rounded-full",asChild:!0,children:e.jsx(nr,{to:"/attract/share",children:"Share something useful"})})]})]}):e.jsxs(we,{className:"rounded-2xl border-dashed border-slate-300 bg-white/60 p-8 text-center",children:[e.jsx("div",{className:"h-11 w-11 rounded-2xl bg-violet-50 text-violet-600 grid place-items-center mx-auto mb-3",children:e.jsx(Pl,{className:"h-5 w-5"})}),e.jsx("div",{className:"text-[15px] font-semibold text-slate-800",children:"Start with five people you already know."}),e.jsx("p",{className:"text-[13px] text-slate-500 mt-1 max-w-md mx-auto",children:"Add your first five relationships and Attract will begin recommending meaningful next steps — based only on things that actually happened."}),e.jsxs($,{className:"rounded-full btn-primary text-white mt-4",onClick:()=>g(!0),children:[e.jsx(Pl,{className:"h-4 w-4 mr-1.5"})," Add your first relationship"]})]}),!!o.length&&e.jsxs(we,{className:"mt-6 p-5 rounded-2xl border-slate-200/70 bg-white shadow-sm",children:[e.jsx("div",{className:"text-[13px] font-semibold uppercase tracking-wider text-slate-600 mb-3",children:"Your daily rhythm"}),e.jsx("ul",{className:"space-y-1",children:o.map(C=>e.jsxs("li",{onClick:()=>c.mutate(C),className:"flex items-center gap-3 px-2 py-2 rounded-xl hover:bg-slate-50 cursor-pointer transition-colors",children:[e.jsx(Li,{checked:C.completed,className:"border-slate-300 data-[state=checked]:bg-violet-600 data-[state=checked]:border-violet-600"}),e.jsx("span",{className:Ot("flex-1 text-[13.5px]",C.completed?"line-through text-slate-400":"text-slate-800"),children:C.label}),e.jsxs("span",{className:"text-[11px] tabular-nums text-slate-400",children:[C.progress,"/",C.target]})]},C.id))})]}),e.jsxs("div",{className:"mt-6 grid grid-cols-1 sm:grid-cols-3 gap-3",children:[e.jsx(z8e,{icon:Pl,label:"Add a relationship",onClick:()=>g(!0)}),e.jsx(z8e,{icon:xb,label:"Share something useful",to:"/attract/share"}),e.jsx(z8e,{icon:vf,label:"Create content",to:"/attract/create"})]}),e.jsxs("div",{className:"mt-6 space-y-3",children:[e.jsxs(h1,{children:[e.jsxs(m1,{className:"w-full flex items-center justify-between rounded-2xl bg-white border border-slate-200/70 px-4 py-3 text-[13.5px] font-medium text-slate-700 hover:bg-slate-50",children:[e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(nk,{className:"h-4 w-4 text-violet-500"})," Upcoming conversations & events"]}),e.jsx(Go,{className:"h-4 w-4 text-slate-400"})]}),e.jsx(f1,{className:"pt-3",children:e.jsx(EWt,{})})]}),e.jsxs(h1,{children:[e.jsxs(m1,{className:"w-full flex items-center justify-between rounded-2xl bg-white border border-slate-200/70 px-4 py-3 text-[13.5px] font-medium text-slate-700 hover:bg-slate-50",children:[e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(kn,{className:"h-4 w-4 text-violet-500"})," View coaching insights"]}),e.jsx(Go,{className:"h-4 w-4 text-slate-400"})]}),e.jsx(f1,{className:"pt-3",children:e.jsx(_Wt,{})})]})]}),e.jsx("div",{className:"mt-6 flex justify-center",children:e.jsx($,{variant:"ghost",className:"rounded-full text-violet-700",asChild:!0,children:e.jsxs(nr,{to:"/attract/relationships?view=attention",children:["See everyone who needs attention ",e.jsx(xi,{className:"h-3.5 w-3.5 ml-1.5"})]})})}),e.jsx("p",{className:"mt-6 text-center text-[11.5px] text-slate-400 max-w-lg mx-auto",children:"Attract never sends messages for you, and it only recommends actions backed by something that actually happened. Verify brokerage and compensation details before you share them."})]})}function z8e({icon:s,label:t,to:n,onClick:r}){const a=e.jsxs("div",{className:"rounded-2xl bg-white border border-slate-200/70 px-4 py-4 text-left hover:border-violet-300 hover:shadow-sm transition-all h-full",children:[e.jsx(s,{className:"h-4.5 w-4.5 text-violet-600 mb-2"}),e.jsx("div",{className:"text-[13.5px] font-medium text-slate-800",children:t})]});return n?e.jsx(nr,{to:n,children:a}):e.jsx("button",{className:"text-left w-full",onClick:r,children:a})}function Hm({eyebrow:s,title:t,description:n,actions:r,className:a}){return e.jsxs("div",{className:Ot("flex flex-col md:flex-row md:items-end md:justify-between gap-4 mb-8",a),children:[e.jsxs("div",{children:[s&&e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-violet-600 font-semibold mb-2",children:s}),e.jsx("h1",{className:"text-3xl md:text-[34px] font-semibold tracking-tight text-slate-900",children:t}),n&&e.jsx("p",{className:"text-slate-600 mt-2 max-w-2xl",children:n})]}),r&&e.jsx("div",{className:"flex items-center gap-2 flex-wrap",children:r})]})}function JF(){return e.jsxs("div",{className:"rounded-2xl border border-violet-200 bg-violet-50/60 px-5 py-3.5 text-[13px] text-violet-900 flex items-start gap-3",children:[e.jsx("div",{className:"h-6 w-6 rounded-full bg-violet-600 grid place-items-center flex-shrink-0 mt-0.5",children:e.jsx("span",{className:"text-white text-[11px] font-bold",children:"✓"})}),e.jsxs("div",{children:[e.jsx("span",{className:"font-semibold",children:"Build relationships first."})," ","Personalize every message and verify brokerage and compensation information before sharing."]})]})}function WHn(s){const t=[];let n="",r=[],a=!1;for(let o=0;oo.some(c=>c.trim()!==""));if(!i.length)return[];const l=i[0].map(o=>o.trim().toLowerCase());return i.slice(1).map(o=>{const c={};return l.forEach((d,u)=>{c[d]=(o[u]??"").trim()}),c})}const rC=(s,t)=>{for(const n of t)if(s[n])return s[n];return""};function KHn({open:s,onOpenChange:t}){const{user:n}=ks(),r=ls(),[a,i]=k.useState([]),[l,o]=k.useState(""),[c,d]=k.useState(!1),u=()=>{i([]),o("")},h=async g=>{if(!g)return;const x=await g.text(),y=WHn(x);if(!y.length){ae.error("That file looks empty.");return}o(g.name),i(y)},m=a.map(g=>{const x=rC(g,["name","full name","full_name"]),y=rC(g,["first name","first_name","firstname"])||x.split(" ")[0]||"",v=rC(g,["last name","last_name","lastname"])||x.split(" ").slice(1).join(" ")||null;return{first_name:y,last_name:v,email:rC(g,["email","email address","e-mail"])||null,phone:rC(g,["phone","phone number","mobile","cell"])||null,brokerage:rC(g,["brokerage","company","office"])||null,city:rC(g,["city"])||null,state:rC(g,["state","province"])||null,notes:rC(g,["notes","note"])||null,source:"csv_import",stage:"prospect"}}).filter(g=>g.first_name),p=async()=>{if(!(!n||!m.length)){d(!0);try{const g=m.map(y=>({...y,user_id:n.id}));let x=0;for(let y=0;y{g||u(),t(g)},children:e.jsxs(Rs,{className:"sm:max-w-lg",children:[e.jsxs(Vs,{children:[e.jsx($s,{children:"Import relationships"}),e.jsx(Cr,{children:"Upload a CSV. We'll look for columns like name, email, phone, brokerage, city, state and notes."})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(be,{type:"file",accept:".csv,text/csv",onChange:g=>{var x;return h((x=g.target.files)==null?void 0:x[0])}}),!!a.length&&e.jsxs("div",{className:"rounded-xl border p-3 text-sm space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2 font-medium",children:[e.jsx(rk,{className:"h-4 w-4"})," ",l]}),e.jsxs("div",{className:"text-muted-foreground",children:[m.length," of ",a.length," rows ready to import."]}),e.jsxs("div",{className:"text-muted-foreground text-xs",children:["Preview: ",m.slice(0,3).map(g=>`${g.first_name} ${g.last_name??""}`.trim()).join(", "),m.length>3?"…":""]})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs($,{onClick:p,disabled:c||!m.length,children:[e.jsx(gi,{className:"h-4 w-4 mr-1.5"}),c?"Importing…":`Import ${m.length||""}`.trim()]})]})]})})}const YHn=["new_connection","building_relationship","engaging_with_value","active_conversation","exploring_options","brokerage_presentation","decision_pending","joined","long_term_relationship","not_right_now","not_a_fit"],ZHn={first_name:"first name",last_name:"last name",preferred_name:"preferred name",email:"email",phone:"phone",website_url:"website",instagram_url:"Instagram",linkedin_url:"LinkedIn",facebook_url:"Facebook",other_url:"other link",brokerage:"brokerage",team_name:"team",city:"city",state:"state",postal_code:"ZIP",market_area:"market area",source:"source",relationship_owner:"relationship owner",stage:"stage",temperature:"temperature",primary_pillar:"primary pillar",tags:"tags",goals:"goals",challenges:"challenges",interests:"interests",production_context:"production context",notes:"notes",birthday_on:"birthday",work_anniversary_on:"work anniversary",license_anniversary_on:"license anniversary",next_follow_up_at:"next follow-up",photo_url:"photo"},Wy=s=>typeof s=="string"&&s.trim()===""?null:s,_9=s=>{const t=s.trim();return t?/^https?:\/\//i.test(t)?t:`https://${t}`:null},XHn=s=>{const t=s.trim();if(!t)return null;const n=t.replace(/[^\d]/g,"");return n.length===10?`(${n.slice(0,3)}) ${n.slice(3,6)}-${n.slice(6)}`:t},nW=s=>(s??"").replace(/[^\d]/g,""),QHn=s=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(s.trim()),bie=s=>s?String(s).slice(0,10):"";function Dwt(s){return{first_name:s.first_name??"",last_name:s.last_name??"",preferred_name:s.preferred_name??"",email:s.email??"",phone:s.phone??"",website_url:s.website_url??"",instagram_url:s.instagram_url??"",linkedin_url:s.linkedin_url??"",facebook_url:s.facebook_url??"",other_url:s.other_url??"",photo_url:s.photo_url??"",brokerage:s.brokerage??"",team_name:s.team_name??"",city:s.city??"",state:s.state??"",postal_code:s.postal_code??"",market_area:s.market_area??"",source:s.source??"",relationship_owner:s.relationship_owner??"",stage:s.stage,temperature:s.temperature??"warm",primary_pillar:s.primary_pillar??"none",tags:(s.tags??[]).join(", "),goals:s.goals??"",challenges:s.challenges??"",interests:s.interests??"",production_context:s.production_context??"",notes:s.notes??"",birthday_on:bie(s.birthday_on),work_anniversary_on:bie(s.work_anniversary_on),license_anniversary_on:bie(s.license_anniversary_on),next_follow_up_at:bie(s.next_follow_up_at)}}function w9({title:s,hint:t,children:n}){return e.jsxs("section",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-[11px] uppercase tracking-wider font-semibold text-violet-600",children:s}),t&&e.jsx("p",{className:"text-[12px] text-slate-500 mt-0.5",children:t})]}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:n})]})}function Hf({label:s,value:t,onChange:n,className:r,...a}){return e.jsxs("div",{className:r,children:[e.jsx(re,{className:"text-[12px] text-slate-600",children:s}),e.jsx(be,{className:"mt-1",value:t,onChange:i=>n(i.target.value),...a})]})}function mJe({agent:s,open:t,onOpenChange:n,onDeleted:r}){const{agents:a,saveAgentDetails:i,archiveAgent:l,deleteAgent:o}=A0(),[c,d]=k.useState({}),[u,h]=k.useState(!1),[m,p]=k.useState(!1),[g,x]=k.useState(!1);k.useEffect(()=>{s&&t&&(d(Dwt(s)),x(!1))},[s==null?void 0:s.id,t]);const y=k.useMemo(()=>s?Dwt(s):{},[s]),v=k.useMemo(()=>Object.keys(c).filter(P=>String(c[P]??"")!==String(y[P]??"")),[c,y]),_=v.length>0,j=(P,R)=>d(O=>({...O,[P]:R}));if(!s)return null;const C=P=>{if(!P&&_){h(!0);return}n(P)},A=()=>{var B;const P=(B=c.email)==null?void 0:B.trim().toLowerCase(),R=nW(c.phone),O=`${c.first_name} ${c.last_name}`.trim().toLowerCase();return a.filter(U=>{var G;return U.id===s.id||U.is_archived?!1:!!(P&&((G=U.email)==null?void 0:G.toLowerCase())===P||R.length>=10&&nW(U.phone)===R||O&&`${U.first_name} ${U.last_name??""}`.trim().toLowerCase()===O)})},M=()=>{var U,G,H;if(!((U=c.first_name)!=null&&U.trim())){ae.error("First name is required");return}if((G=c.email)!=null&&G.trim()&&!QHn(c.email)){ae.error("That email address looks incomplete");return}const P=A(),R=P.some(Y=>{var se,ee;return((se=c.email)==null?void 0:se.trim())&&((ee=Y.email)==null?void 0:ee.toLowerCase())===c.email.trim().toLowerCase()||nW(c.phone).length>=10&&nW(Y.phone)===nW(c.phone)});if(P.length&&!g){x(!0),ae.warning(R?`${P[0].first_name} ${P[0].last_name??""} already uses this email or phone. Save again to confirm.`:"A contact named the same already exists. Save again to confirm.");return}const O={first_name:c.first_name.trim(),last_name:Wy(c.last_name),preferred_name:Wy(c.preferred_name),email:(H=c.email)!=null&&H.trim()?c.email.trim().toLowerCase():null,phone:XHn(c.phone??""),website_url:_9(c.website_url??""),instagram_url:_9(c.instagram_url??""),linkedin_url:_9(c.linkedin_url??""),facebook_url:_9(c.facebook_url??""),other_url:_9(c.other_url??""),photo_url:_9(c.photo_url??""),brokerage:Wy(c.brokerage),team_name:Wy(c.team_name),city:Wy(c.city),state:Wy(c.state),postal_code:Wy(c.postal_code),market_area:Wy(c.market_area),source:Wy(c.source),relationship_owner:Wy(c.relationship_owner),temperature:c.temperature,primary_pillar:c.primary_pillar==="none"?null:c.primary_pillar,tags:String(c.tags??"").split(",").map(Y=>Y.trim()).filter(Boolean),goals:Wy(c.goals),challenges:Wy(c.challenges),interests:Wy(c.interests),production_context:Wy(c.production_context),notes:Wy(c.notes),birthday_on:Wy(c.birthday_on),work_anniversary_on:Wy(c.work_anniversary_on),license_anniversary_on:Wy(c.license_anniversary_on),next_follow_up_at:c.next_follow_up_at?new Date(`${c.next_follow_up_at}T12:00:00`).toISOString():null,stage:c.stage},B={};if(v.forEach(Y=>{Y in O&&(B[Y]=O[Y])}),!Object.keys(B).length){n(!1);return}i.mutate({id:s.id,values:B,changedLabels:v.map(Y=>ZHn[Y]??Y),previousStage:s.stage},{onSuccess:()=>n(!1)})},I=A();return e.jsxs(e.Fragment,{children:[e.jsx(D_,{open:t,onOpenChange:C,children:e.jsxs(Mb,{side:"right",className:"w-full sm:max-w-xl overflow-y-auto p-0",children:[e.jsx("div",{className:"sticky top-0 z-10 bg-gradient-to-r from-[#0B0F1E] to-[#1d1b4b] text-white px-5 py-4",children:e.jsxs(xj,{className:"space-y-1 text-left",children:[e.jsxs(yj,{className:"text-white text-lg",children:["Edit ",[s.first_name,s.last_name].filter(Boolean).join(" ")]}),e.jsx(hee,{className:"text-slate-300 text-[12.5px]",children:"Only the fields you change are saved. Stage changes are recorded in pipeline history."})]})}),e.jsxs("div",{className:"px-5 py-5 space-y-7 pb-40",children:[!!I.length&&e.jsxs("div",{className:"rounded-xl bg-amber-50 ring-1 ring-amber-200 p-3 text-[12.5px] text-amber-800 flex gap-2",children:[e.jsx(Gd,{className:"h-4 w-4 mt-0.5 shrink-0"}),e.jsxs("span",{children:["Possible duplicate: ",I.slice(0,3).map(P=>`${P.first_name} ${P.last_name??""}`.trim()).join(", "),". You can still save — just double-check first."]})]}),e.jsxs(w9,{title:"Basic info",children:[e.jsx(Hf,{label:"First name *",value:c.first_name,onChange:P=>j("first_name",P)}),e.jsx(Hf,{label:"Last name",value:c.last_name,onChange:P=>j("last_name",P)}),e.jsx(Hf,{label:"Preferred name",value:c.preferred_name,onChange:P=>j("preferred_name",P),placeholder:"What they go by"}),e.jsx(Hf,{label:"Photo / headshot URL",value:c.photo_url,onChange:P=>j("photo_url",P),placeholder:"https://…"})]}),e.jsxs(w9,{title:"Contact & social",children:[e.jsx(Hf,{label:"Email",type:"email",value:c.email,onChange:P=>j("email",P)}),e.jsx(Hf,{label:"Phone",value:c.phone,onChange:P=>j("phone",P)}),e.jsx(Hf,{label:"Website",value:c.website_url,onChange:P=>j("website_url",P)}),e.jsx(Hf,{label:"Instagram",value:c.instagram_url,onChange:P=>j("instagram_url",P)}),e.jsx(Hf,{label:"LinkedIn",value:c.linkedin_url,onChange:P=>j("linkedin_url",P)}),e.jsx(Hf,{label:"Facebook",value:c.facebook_url,onChange:P=>j("facebook_url",P)}),e.jsx(Hf,{label:"Other link",value:c.other_url,onChange:P=>j("other_url",P),className:"sm:col-span-2"})]}),e.jsxs(w9,{title:"Brokerage & market",children:[e.jsx(Hf,{label:"Brokerage",value:c.brokerage,onChange:P=>j("brokerage",P)}),e.jsx(Hf,{label:"Team",value:c.team_name,onChange:P=>j("team_name",P)}),e.jsx(Hf,{label:"City",value:c.city,onChange:P=>j("city",P)}),e.jsx(Hf,{label:"State",value:c.state,onChange:P=>j("state",P)}),e.jsx(Hf,{label:"ZIP / postal code",value:c.postal_code,onChange:P=>j("postal_code",P)}),e.jsx(Hf,{label:"Market / service area",value:c.market_area,onChange:P=>j("market_area",P)})]}),e.jsxs(w9,{title:"Relationship intelligence",hint:"These drive scoring, recommendations, filters and reports.",children:[e.jsxs("div",{children:[e.jsx(re,{className:"text-[12px] text-slate-600",children:"Pipeline stage"}),e.jsxs(bs,{value:c.stage,onValueChange:P=>j("stage",P),children:[e.jsx(ys,{className:"mt-1",children:e.jsx(_s,{})}),e.jsx(vs,{children:YHn.map(P=>e.jsx(We,{value:P,className:"capitalize",children:P.replace(/_/g," ")},P))})]})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-[12px] text-slate-600",children:"Temperature"}),e.jsxs(bs,{value:c.temperature,onValueChange:P=>j("temperature",P),children:[e.jsx(ys,{className:"mt-1",children:e.jsx(_s,{})}),e.jsx(vs,{children:["cold","warm","hot"].map(P=>e.jsx(We,{value:P,className:"capitalize",children:P},P))})]})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-[12px] text-slate-600",children:"Primary pillar"}),e.jsxs(bs,{value:c.primary_pillar,onValueChange:P=>j("primary_pillar",P),children:[e.jsx(ys,{className:"mt-1",children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"none",children:"Not set"}),["produce","influence","provide","connect"].map(P=>e.jsx(We,{value:P,className:"capitalize",children:P},P))]})]})]}),e.jsx(Hf,{label:"Source",value:c.source,onChange:P=>j("source",P),placeholder:"Event, referral, social…"}),e.jsx(Hf,{label:"Relationship owner",value:c.relationship_owner,onChange:P=>j("relationship_owner",P),placeholder:"You, or a teammate"}),e.jsx(Hf,{label:"Tags (comma separated)",value:c.tags,onChange:P=>j("tags",P),className:"sm:col-span-2"}),!!String(c.tags??"").trim()&&e.jsx("div",{className:"sm:col-span-2 flex flex-wrap gap-1.5 -mt-1",children:String(c.tags).split(",").map(P=>P.trim()).filter(Boolean).map(P=>e.jsx(qe,{variant:"outline",className:"rounded-full text-[11px]",children:P},P))})]}),e.jsxs(w9,{title:"Important dates",hint:"Birthdays and anniversaries feed Milestones & Celebrations automatically — no duplicate entry needed.",children:[e.jsx(Hf,{label:"Birthday",type:"date",value:c.birthday_on,onChange:P=>j("birthday_on",P)}),e.jsx(Hf,{label:"Work anniversary",type:"date",value:c.work_anniversary_on,onChange:P=>j("work_anniversary_on",P)}),e.jsx(Hf,{label:"License anniversary",type:"date",value:c.license_anniversary_on,onChange:P=>j("license_anniversary_on",P)}),e.jsx(Hf,{label:"Next follow-up",type:"date",value:c.next_follow_up_at,onChange:P=>j("next_follow_up_at",P)})]}),e.jsxs(w9,{title:"Notes",children:[e.jsxs("div",{className:"sm:col-span-2",children:[e.jsx(re,{className:"text-[12px] text-slate-600",children:"Goals"}),e.jsx(Ls,{className:"mt-1",rows:2,value:c.goals,onChange:P=>j("goals",P.target.value)})]}),e.jsxs("div",{className:"sm:col-span-2",children:[e.jsx(re,{className:"text-[12px] text-slate-600",children:"Challenges"}),e.jsx(Ls,{className:"mt-1",rows:2,value:c.challenges,onChange:P=>j("challenges",P.target.value)})]}),e.jsxs("div",{className:"sm:col-span-2",children:[e.jsx(re,{className:"text-[12px] text-slate-600",children:"Interests"}),e.jsx(Ls,{className:"mt-1",rows:2,value:c.interests,onChange:P=>j("interests",P.target.value)})]}),e.jsxs("div",{className:"sm:col-span-2",children:[e.jsx(re,{className:"text-[12px] text-slate-600",children:"Production context"}),e.jsx(Ls,{className:"mt-1",rows:2,value:c.production_context,onChange:P=>j("production_context",P.target.value)})]}),e.jsxs("div",{className:"sm:col-span-2",children:[e.jsx(re,{className:"text-[12px] text-slate-600",children:"Personal notes"}),e.jsx(Ls,{className:"mt-1",rows:4,value:c.notes,onChange:P=>j("notes",P.target.value)})]})]}),e.jsxs("section",{className:"rounded-xl ring-1 ring-rose-200 bg-rose-50/60 p-4 space-y-3",children:[e.jsx("h3",{className:"text-[11px] uppercase tracking-wider font-semibold text-rose-700",children:"Danger zone"}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs($,{variant:"outline",size:"sm",className:"rounded-full",onClick:()=>l.mutate({id:s.id,archived:!s.is_archived},{onSuccess:()=>n(!1)}),children:[e.jsx(kf,{className:"h-3.5 w-3.5 mr-1.5"}),s.is_archived?"Restore to pipeline":"Remove from pipeline (archive)"]}),e.jsxs($,{variant:"destructive",size:"sm",className:"rounded-full",onClick:()=>p(!0),children:[e.jsx(Un,{className:"h-3.5 w-3.5 mr-1.5"})," Delete permanently"]})]}),e.jsx("p",{className:"text-[12px] text-rose-700/80",children:"Archiving keeps every note, touch and score. Deleting is permanent."})]})]}),e.jsxs("div",{className:"sticky bottom-0 bg-white/95 backdrop-blur border-t px-5 py-3 flex items-center justify-between gap-3",children:[e.jsx("span",{className:"text-[12px] text-slate-500",children:i.isPending?"Saving…":_?`${v.length} unsaved change${v.length>1?"s":""}`:"All changes saved"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs($,{variant:"ghost",className:"rounded-full",onClick:()=>C(!1),children:[e.jsx(mr,{className:"h-4 w-4 mr-1"})," Cancel"]}),e.jsxs($,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600 text-white",disabled:!_||i.isPending,onClick:M,children:[i.isPending&&e.jsx(Jt,{className:"h-4 w-4 mr-1.5 animate-spin"}),"Save changes"]})]})]})]})}),e.jsx(oc,{open:u,onOpenChange:h,children:e.jsxs(Ql,{children:[e.jsxs(Jl,{children:[e.jsx(tc,{children:"Discard unsaved changes?"}),e.jsxs(sc,{children:["You have ",v.length," unsaved change(s) on this contact."]})]}),e.jsxs(ec,{children:[e.jsx(nc,{children:"Keep editing"}),e.jsx(Vl,{onClick:()=>{h(!1),n(!1)},children:"Discard"})]})]})}),e.jsx(oc,{open:m,onOpenChange:p,children:e.jsxs(Ql,{children:[e.jsxs(Jl,{children:[e.jsx(tc,{children:"Delete this contact permanently?"}),e.jsx(sc,{children:"This removes their timeline, follow-ups, pipeline history, scores and recommendations. Event, kit and transaction records will stay but will no longer be linked to anyone. This cannot be undone."})]}),e.jsxs(ec,{children:[e.jsx(nc,{children:"Cancel"}),e.jsx(Vl,{className:"bg-rose-600 hover:bg-rose-700",onClick:()=>o.mutate(s.id,{onSuccess:()=>{p(!1),n(!1),r==null||r()}}),children:"Delete forever"})]})]})})]})}function JHn(){const s=Jn(),[t,n]=Jc(),{agents:r,activeAgents:a,isLoading:i,moveStage:l}=A0(),{followUps:o,complete:c}=QF(),{data:d=[]}=Nte();ZTe();const u=t.get("view")||"attention",h=Y=>n(se=>(se.set("view",Y),se),{replace:!0}),[m,p]=k.useState(""),[g,x]=k.useState("all"),[y,v]=k.useState(!1),[_,j]=k.useState(!1),[C,A]=k.useState(!1),[M,I]=k.useState(null),[P,R]=k.useState(null),O=Y=>!!Y.is_archived!==y||g!=="all"&&GB(Y.stage).key!==g?!1:m.trim()?`${Y.first_name} ${Y.last_name??""} ${Y.brokerage??""} ${Y.city??""} ${(Y.tags??[]).join(" ")} ${Y.email??""}`.toLowerCase().includes(m.trim().toLowerCase()):!0,B=k.useMemo(()=>r.filter(O),[r,m,g,y]),U=k.useMemo(()=>{const Y=np(new Date),se=o.filter(le=>!le.completed_at),ee=d.filter(le=>le.status==="open"),oe=se.filter(le=>le.due_at&&Xw(new Date(le.due_at),Y)),me=se.filter(le=>le.due_at&&m0(new Date(le.due_at))),Q=a.filter(le=>{const fe=le.last_touch_at?new Date(le.last_touch_at):null;return fe?Date.now()-+fe>45*864e5:!!le.created_at&&Date.now()-+new Date(le.created_at)>14*864e5}),te=a.filter(le=>!le.next_follow_up_at&&!se.some(fe=>fe.agent_id===le.id));return{overdue:oe,dueToday:me,quiet:Q,noNextStep:te,openRecs:ee}},[o,d,a]),G=Y=>{const se=r.find(ee=>ee.id===Y);return se?`${se.first_name} ${se.last_name??""}`.trim():"Someone"},H=[{label:"Relationships",value:a.length,icon:tb},{label:"Overdue",value:U.overdue.length,icon:Ho,tone:"text-rose-600"},{label:"Due today",value:U.dueToday.length,icon:Ho,tone:"text-orange-600"},{label:"Gone quiet",value:U.quiet.length,icon:Ho,tone:"text-slate-600"}];return e.jsxs("div",{children:[e.jsx(LWt,{open:_,onOpenChange:j,onAdded:Y=>Y&&s(`/attract/agents/${Y}`)}),e.jsx(KHn,{open:C,onOpenChange:A}),e.jsx(mJe,{agent:M?r.find(Y=>Y.id===M.id)??M:null,open:!!M,onOpenChange:Y=>!Y&&I(null)}),e.jsx(Hm,{eyebrow:"Relationships",title:"The people you're building with",description:"Everyone you know, who needs attention, and what you promised — in one place.",actions:e.jsxs(e.Fragment,{children:[e.jsxs($,{variant:"outline",className:"rounded-full",onClick:()=>A(!0),children:[e.jsx(gi,{className:"h-3.5 w-3.5 mr-1.5"})," Import"]}),e.jsxs($,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600 text-white",onClick:()=>j(!0),children:[e.jsx(nn,{className:"h-4 w-4 mr-1"})," Add relationship"]})]})}),e.jsx("div",{className:"grid grid-cols-2 lg:grid-cols-4 gap-3 mb-5",children:H.map(Y=>e.jsxs(we,{className:"p-4 rounded-2xl",children:[e.jsx("div",{className:Ot("text-2xl font-semibold tabular-nums text-slate-900",Y.tone),children:Y.value}),e.jsx("div",{className:"text-[11.5px] text-slate-500 mt-0.5",children:Y.label})]},Y.label))}),e.jsxs(we,{className:"p-3 rounded-2xl flex flex-wrap items-center gap-2 mb-5",children:[e.jsxs("div",{className:"relative flex-1 min-w-[220px]",children:[e.jsx(Yr,{className:"h-4 w-4 absolute left-3 top-1/2 -translate-y-1/2 text-slate-400"}),e.jsx(be,{value:m,onChange:Y=>p(Y.target.value),placeholder:"Search name, brokerage, market, tag…",className:"pl-9 rounded-full h-9","aria-label":"Search relationships"})]}),e.jsxs(bs,{value:g,onValueChange:x,children:[e.jsx(ys,{className:"w-[190px] h-9 rounded-full text-[13px]",children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"all",children:"All stages"}),[...vM,JTe].map(Y=>e.jsx(We,{value:Y.key,children:Y.label},Y.key))]})]}),e.jsxs($,{variant:y?"default":"outline",size:"sm",className:"rounded-full h-9",onClick:()=>v(Y=>!Y),children:[e.jsx(kf,{className:"h-3.5 w-3.5 mr-1.5"})," ",y?"Archived":"Active"]}),e.jsx("div",{className:"flex bg-slate-100 rounded-full p-0.5",children:[["attention","Needs attention"],["stages","Stages"],["list","List"]].map(([Y,se])=>e.jsxs("button",{onClick:()=>h(Y),className:Ot("rounded-full h-8 px-3 text-[12.5px] font-medium transition-colors",u===Y?"bg-white text-slate-900 shadow-sm":"text-slate-500 hover:text-slate-800"),children:[Y==="stages"?e.jsx(y0,{className:"h-3.5 w-3.5 mr-1 inline"}):Y==="list"?e.jsx(Sy,{className:"h-3.5 w-3.5 mr-1 inline"}):null,se]},Y))})]}),i?e.jsxs("div",{className:"space-y-3","aria-busy":"true",children:[e.jsx("div",{className:"text-[13px] text-slate-500",children:"Loading your relationships…"}),[0,1,2].map(Y=>e.jsx(fn,{className:"h-24 w-full rounded-2xl"},Y))]}):r.length?u==="attention"?e.jsxs("div",{className:"space-y-6",children:[e.jsx(_ie,{title:"Overdue commitments",tone:"#f43f5e",items:U.overdue,render:Y=>e.jsx(Owt,{f:Y,name:G(Y.agent_id),onDone:()=>c.mutate(Y.id)},Y.id)}),e.jsx(_ie,{title:"Due today",tone:"#f97316",items:U.dueToday,render:Y=>e.jsx(Owt,{f:Y,name:G(Y.agent_id),onDone:()=>c.mutate(Y.id)},Y.id)}),e.jsx(_ie,{title:"Haven't talked in a while",tone:"#8b5cf6",items:U.quiet.filter(O),render:Y=>e.jsx(B8e,{a:Y,note:Y.last_touch_at?`Last touch ${Ys(new Date(Y.last_touch_at),"MMM d")}`:"No meaningful touch yet"},Y.id)}),e.jsx(_ie,{title:"No next step set",tone:"#94a3b8",items:U.noNextStep.filter(O),render:Y=>e.jsx(B8e,{a:Y,note:"Decide one small next step"},Y.id)}),!U.overdue.length&&!U.dueToday.length&&!U.quiet.length&&!U.noNextStep.length&&e.jsxs(we,{className:"rounded-2xl border-dashed border-slate-300 bg-white/60 p-8 text-center",children:[e.jsx("div",{className:"text-[15px] font-semibold text-slate-800",children:"Nothing needs attention."}),e.jsx("p",{className:"text-[13px] text-slate-500 mt-1",children:"Great time to reconnect with someone you haven’t spoken with recently."})]})]}):u==="stages"?e.jsxs(Eo,{className:"w-full",children:[e.jsx("div",{className:"flex gap-4 pb-4",style:{minWidth:vM.length*290},children:vM.map(Y=>{const se=B.filter(ee=>GB(ee.stage).key===Y.key);return e.jsxs("div",{className:"w-[275px] flex-shrink-0",onDragOver:ee=>{ee.preventDefault(),ee.dataTransfer.dropEffect="move"},onDrop:ee=>{ee.preventDefault();const oe=r.find(me=>me.id===P);oe&&GB(oe.stage).key!==Y.key&&l.mutate({id:oe.id,to_stage:hJe(Y.key),from_stage:oe.stage}),R(null)},children:[e.jsxs("div",{className:"px-1 mb-2.5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"h-2.5 w-2.5 rounded-full",style:{background:Y.color}}),e.jsx("h3",{className:"text-[13px] font-semibold text-slate-800",children:Y.label}),e.jsx(qe,{variant:"secondary",className:"text-[10px] h-5 px-1.5",children:se.length})]}),e.jsx("div",{className:"text-[11px] text-slate-400 mt-0.5 pl-4.5",children:Y.help})]}),e.jsxs("div",{className:"rounded-2xl bg-slate-100/60 p-2 space-y-2 min-h-[180px]",children:[se.map(ee=>e.jsxs("div",{draggable:!0,onDragStart:()=>R(ee.id),onClick:()=>s(`/attract/agents/${ee.id}`),className:"bg-white rounded-xl p-3 cursor-pointer hover:shadow-md border-l-[3px] transition-all",style:{borderLeftColor:Y.color},children:[e.jsxs("div",{className:"text-[13.5px] font-semibold text-slate-900 truncate",children:[ee.first_name," ",ee.last_name]}),e.jsxs("div",{className:"text-[11.5px] text-slate-500 flex items-center gap-1 mt-0.5 truncate",children:[e.jsx(Gi,{className:"h-3 w-3"}),e.jsx("span",{className:"truncate",children:ee.brokerage??"Brokerage not set"})]}),!ee.email&&!ee.phone&&e.jsx("div",{className:"mt-1.5 text-[10.5px] text-amber-700",children:"No contact info yet"})]},ee.id)),!se.length&&e.jsx("div",{className:"text-[11.5px] text-slate-400 text-center py-4",children:"Drag someone here"})]})]},Y.key)})}),e.jsx(Uq,{orientation:"horizontal"})]}):e.jsxs(we,{className:"rounded-2xl divide-y divide-slate-100 overflow-hidden",children:[B.map(Y=>e.jsx(B8e,{a:Y,onEdit:()=>I(Y)},Y.id)),!B.length&&e.jsx("div",{className:"p-10 text-center text-[13px] text-slate-500",children:"No one matches this view."})]}):e.jsx(eGn,{onAdd:()=>j(!0)})]})}function _ie({title:s,tone:t,items:n,render:r}){return n.length?e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2.5",children:[e.jsx("span",{className:"h-2.5 w-2.5 rounded-full",style:{background:t}}),e.jsx("h3",{className:"text-[13px] font-semibold uppercase tracking-wider text-slate-700",children:s}),e.jsx(qe,{variant:"secondary",className:"text-[10px]",children:n.length})]}),e.jsx(we,{className:"rounded-2xl divide-y divide-slate-100 overflow-hidden",children:n.slice(0,12).map(r)})]}):null}function Owt({f:s,name:t,onDone:n}){return e.jsxs("div",{className:"flex items-start gap-3 p-4 hover:bg-slate-50",children:[e.jsx(Li,{checked:!1,onCheckedChange:n,className:"mt-0.5","aria-label":"Mark complete"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-[13.5px] font-medium text-slate-900",children:s.title}),e.jsxs("div",{className:"text-[12px] text-slate-500 mt-0.5",children:[s.agent_id?e.jsxs(nr,{to:`/attract/agents/${s.agent_id}`,className:"hover:text-violet-700",children:["for ",t]}):"Personal task",s.due_at&&e.jsxs(e.Fragment,{children:[" · due ",Ys(new Date(s.due_at),"MMM d")]})]})]})]})}function B8e({a:s,note:t,onEdit:n}){var i,l;const r=GB(s.stage),a=`${((i=s.first_name)==null?void 0:i[0])??""}${((l=s.last_name)==null?void 0:l[0])??""}`.toUpperCase();return e.jsxs("div",{className:"flex items-center gap-3 p-4 hover:bg-slate-50",children:[e.jsx("div",{className:"h-9 w-9 rounded-full bg-violet-100 text-violet-700 grid place-items-center text-[12px] font-semibold flex-shrink-0",children:a||"?"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs(nr,{to:`/attract/agents/${s.id}`,className:"text-[13.5px] font-medium text-slate-900 hover:text-violet-700",children:[s.first_name," ",s.last_name]}),e.jsxs("div",{className:"text-[12px] text-slate-500 mt-0.5 flex items-center gap-2 flex-wrap",children:[e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(Gi,{className:"h-3 w-3"}),s.brokerage??"Brokerage not set"]}),s.city&&e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(Si,{className:"h-3 w-3"}),s.city]}),t&&e.jsxs("span",{className:"text-slate-400",children:["· ",t]})]})]}),e.jsx(qe,{variant:"outline",className:"rounded-full text-[10.5px] hidden sm:inline-flex",style:{borderColor:`${r.color}55`,color:r.color},children:r.label}),n&&e.jsx($,{variant:"ghost",size:"sm",className:"rounded-full",onClick:n,children:"Edit"})]})}function eGn({onAdd:s}){return e.jsxs(we,{className:"rounded-2xl border-dashed border-slate-300 bg-white/60 p-10 text-center",children:[e.jsx("div",{className:"h-11 w-11 rounded-2xl bg-violet-50 text-violet-600 grid place-items-center mx-auto mb-3",children:e.jsx(tb,{className:"h-5 w-5"})}),e.jsx("div",{className:"text-[15px] font-semibold text-slate-800",children:"Add your first five relationships"}),e.jsx("p",{className:"text-[13px] text-slate-500 mt-1 max-w-md mx-auto",children:"Start with agents you already know — co-op partners, people from your office, agents you met at an event. Attract will begin recommending meaningful next steps."}),e.jsxs($,{className:"rounded-full btn-primary text-white mt-4",onClick:s,children:[e.jsx(nn,{className:"h-4 w-4 mr-1.5"})," Add a relationship"]})]})}const tGn=[{icon:xb,title:"Helpful Resource",blurb:"One useful document, guide or tool.",to:"/attract/resources"},{icon:bh,title:"Resource Kit",blurb:"A themed bundle you can personalize and track.",to:"/attract/provide/kits"},{icon:Bm,title:"Training or Masterclass",blurb:"Invite someone to learn something with you.",to:"/attract/provide/masterclasses"},{icon:nk,title:"Event Invitation",blurb:"A room worth being in — online or in person.",to:"/attract/events"},{icon:b_,title:"Coffee Invitation",blurb:"One conversation is enough.",to:"/attract/relationships?view=attention"},{icon:_3,title:"My Brokerage Story",blurb:"Your personal “why I’m here” page.",to:"/attract/landing-page"},{icon:Gi,title:"Brokerage Information",blurb:"Approved, verified brokerage facts only.",to:"/attract/templates"},{icon:KK,title:"Comparison Guide",blurb:"A fair, honest side-by-side.",to:"/attract/templates"}],sGn=["Agent Business Planning Kit","Open House Conversion Kit","Listing Marketing Kit","Database Follow-Up Kit","AI for Realtors Kit","New Agent Success Kit","Team-Building Guide","Brokerage Evaluation Checklist","Production Growth Kit","90-Day Agent Business Plan","Social Media Planning Kit","Buyer & Seller Lead Conversion Kit"];function nGn(){return e.jsxs("div",{className:"max-w-4xl mx-auto",children:[e.jsx(Hm,{eyebrow:"Share Value",title:"What would you like to share?",description:"Give something genuinely useful. Curiosity follows value — it never has to be pushed."}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:tGn.map(s=>e.jsxs(nr,{to:s.to,className:"rounded-2xl bg-white border border-slate-200/70 p-4 hover:border-violet-300 hover:shadow-sm transition-all flex items-start gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-xl bg-violet-50 text-violet-600 grid place-items-center flex-shrink-0",children:e.jsx(s.icon,{className:"h-4.5 w-4.5"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-[14px] font-semibold text-slate-900",children:s.title}),e.jsx("div",{className:"text-[12.5px] text-slate-500 mt-0.5",children:s.blurb})]})]},s.title))}),e.jsxs(we,{className:"mt-6 p-5 rounded-2xl",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 flex-wrap",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[13px] font-semibold uppercase tracking-wider text-slate-600",children:"Ready-to-personalize kits"}),e.jsx("p",{className:"text-[13px] text-slate-500 mt-1 max-w-xl",children:"LevelUp-built starting points. Your headshot, contact details and branding are added automatically — you never re-enter your profile."})]}),e.jsx($,{variant:"outline",className:"rounded-full",asChild:!0,children:e.jsxs(nr,{to:"/attract/provide/kits/templates",children:["Browse kit templates ",e.jsx(xi,{className:"h-3.5 w-3.5 ml-1.5"})]})})]}),e.jsx("div",{className:"mt-4 flex flex-wrap gap-2",children:sGn.map(s=>e.jsx("span",{className:"rounded-full bg-slate-50 border border-slate-200 px-3 py-1.5 text-[12px] text-slate-700",children:s},s))})]}),e.jsx("p",{className:"mt-6 text-center text-[11.5px] text-slate-400 max-w-lg mx-auto",children:"Engagement means someone found your resource useful — not that they want to change brokerages. Treat it as a reason to keep the relationship going."})]})}function rGn(){const{settings:s}=KV(),{activeAgents:t}=A0(),n=k.useMemo(()=>{const r=(s==null?void 0:s.primary_pillar)??(s==null?void 0:s.attraction_style)??"balanced",a=((s==null?void 0:s.audiences)??[])[0];return[{icon:ia,kind:"Talking-head video",title:"Share one thing that changed in your business this year",why:"Personal experience is the only thing no other agent can copy.",to:"/attract/influence/content-studio"},{icon:Wz,kind:"Educational carousel",title:"Break down a system other agents could steal from you",why:r==="provide"?"Teaching is your strongest pillar — this plays to it.":"Useful teaching creates curiosity without a pitch.",to:"/attract/influence/content-studio"},{icon:eB,kind:"Conversation starter",title:a?`Ask ${a} what they’re struggling with right now`:"Ask agents what they’re struggling with right now",why:t.length?`Replies become real conversations with the ${t.length} people you’re already building with.`:"Replies are the easiest way to start new relationships.",to:"/attract/influence/content-studio"}]},[s,t.length]);return e.jsxs("div",{className:"max-w-3xl mx-auto",children:[e.jsx(Hm,{eyebrow:"Create Content",title:"Here are three ways to build attraction through content this week.",description:"Start from a real thing that happened in your business — not a blank page."}),e.jsx("div",{className:"space-y-3",children:n.map(r=>e.jsx(we,{className:"p-5 rounded-2xl border-slate-200/70",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-xl bg-violet-50 text-violet-600 grid place-items-center flex-shrink-0",children:e.jsx(r.icon,{className:"h-4.5 w-4.5"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx(qe,{variant:"outline",className:"rounded-full text-[10.5px] uppercase tracking-wider",children:r.kind}),e.jsx("h3",{className:"text-[15px] font-semibold text-slate-900 mt-1.5 leading-snug",children:r.title}),e.jsx("p",{className:"text-[12.5px] text-slate-500 mt-1",children:r.why}),e.jsx($,{size:"sm",className:"rounded-full btn-primary text-white mt-3",asChild:!0,children:e.jsxs(nr,{to:r.to,children:[e.jsx(vf,{className:"h-3.5 w-3.5 mr-1.5"})," Build it"]})})]})]})},r.title))}),e.jsxs("div",{className:"mt-6 grid grid-cols-1 sm:grid-cols-3 gap-3",children:[e.jsx($8e,{icon:vf,label:"Content Studio",to:"/attract/influence/content-studio"}),e.jsx($8e,{icon:pn,label:"Content calendar",to:"/attract/influence/content-calendar"}),e.jsx($8e,{icon:w2,label:"Speaking opportunities",to:"/attract/influence/speaking"})]}),e.jsx("p",{className:"mt-6 text-center text-[11.5px] text-slate-400",children:"Every piece you mark as posted counts toward your weekly attraction plan."})]})}function $8e({icon:s,label:t,to:n}){return e.jsxs(nr,{to:n,className:"rounded-2xl bg-white border border-slate-200/70 px-4 py-4 hover:border-violet-300 hover:shadow-sm transition-all block",children:[e.jsx(s,{className:"h-4.5 w-4.5 text-violet-600 mb-2"}),e.jsxs("div",{className:"text-[13.5px] font-medium text-slate-800 flex items-center gap-1",children:[t," ",e.jsx(xi,{className:"h-3 w-3 opacity-40"})]})]})}const wie=[{key:"new_connection",label:"New Connection",color:"#94a3b8"},{key:"building_relationship",label:"Building Relationship",color:"#38bdf8"},{key:"engaging_with_value",label:"Engaging With Value",color:"#14b8a6"},{key:"active_conversation",label:"Active Conversation",color:"#8b5cf6"},{key:"exploring_options",label:"Exploring Options",color:"#6366f1"},{key:"brokerage_presentation",label:"Brokerage Presentation",color:"#f97316"},{key:"decision_pending",label:"Decision Pending",color:"#f59e0b"},{key:"joined",label:"Joined",color:"#16a34a"},{key:"not_right_now",label:"Not Right Now",color:"#64748b"},{key:"long_term_relationship",label:"Long-Term Relationship",color:"#a78bfa"},{key:"not_a_fit",label:"Not a Fit",color:"#cbd5e1"}],Fwt={hot:"bg-rose-100 text-rose-700 border-rose-200",warm:"bg-orange-100 text-orange-700 border-orange-200",cold:"bg-sky-100 text-sky-700 border-sky-200"};function aGn(){const s=Jn(),{agents:t,isLoading:n,upsertAgent:r,moveStage:a,archiveAgent:i}=A0(),[l,o]=k.useState("kanban"),[c,d]=k.useState(""),[u,h]=k.useState(!1),[m,p]=k.useState(!1),[g,x]=k.useState(),[y,v]=k.useState(null),[_,j]=k.useState(null),[C,A]=k.useState(null),[M,I]=k.useState(null),{gmailEmail:P}=dx(),R=t.filter(U=>!!U.is_archived!==u?!1:c?`${U.first_name} ${U.last_name??""} ${U.brokerage??""} ${U.city??""} ${(U.tags??[]).join(" ")} ${U.email??""}`.toLowerCase().includes(c.toLowerCase()):!0),O=y?t.find(U=>U.id===y.id)??y:null,B=({agent:U})=>e.jsxs(Au,{children:[e.jsx(Eu,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:"h-6 w-6 -mr-1",onClick:G=>G.stopPropagation(),"aria-label":"Agent actions",children:e.jsx(Z0,{className:"h-3.5 w-3.5"})})}),e.jsxs(gu,{align:"end",onClick:G=>G.stopPropagation(),children:[e.jsxs(Pa,{onClick:()=>j(U),children:[e.jsx(ui,{className:"h-3.5 w-3.5 mr-2"})," Edit contact"]}),e.jsxs(Pa,{onClick:()=>s(`/attract/agents/${U.id}`),children:[e.jsx(Ir,{className:"h-3.5 w-3.5 mr-2"})," Open relationship"]}),e.jsx(j0,{}),e.jsxs(Pa,{onClick:()=>i.mutate({id:U.id,archived:!U.is_archived}),children:[e.jsx(kf,{className:"h-3.5 w-3.5 mr-2"})," ",U.is_archived?"Restore to pipeline":"Remove from pipeline"]})]})]});return e.jsxs("div",{children:[e.jsx(Hm,{eyebrow:"Agent Pipeline",title:"Where relationships live",description:"Move agents through relationship-first stages. Never a target — always a real conversation.",actions:e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex bg-white border rounded-full p-0.5",children:[e.jsxs($,{size:"sm",variant:l==="kanban"?"default":"ghost",className:"rounded-full h-8 px-3",onClick:()=>o("kanban"),children:[e.jsx(y0,{className:"h-3.5 w-3.5 mr-1"})," Board"]}),e.jsxs($,{size:"sm",variant:l==="list"?"default":"ghost",className:"rounded-full h-8 px-3",onClick:()=>o("list"),children:[e.jsx(Sy,{className:"h-3.5 w-3.5 mr-1"})," List"]})]}),e.jsxs($,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600 hover:opacity-95",onClick:()=>{x(void 0),p(!0)},children:[e.jsx(nn,{className:"h-4 w-4 mr-1"})," Add Agent"]})]})}),e.jsxs("div",{className:"mb-4 flex items-center gap-3 flex-wrap",children:[e.jsxs("div",{className:"relative flex-1 min-w-[220px] max-w-md",children:[e.jsx(Yr,{className:"h-4 w-4 text-slate-400 absolute left-3 top-1/2 -translate-y-1/2"}),e.jsx(be,{value:c,onChange:U=>d(U.target.value),placeholder:"Search name, brokerage, city, tag, email…",className:"pl-9 rounded-full bg-white"})]}),e.jsxs($,{variant:u?"default":"outline",size:"sm",className:"rounded-full",onClick:()=>h(U=>!U),children:[e.jsx(kf,{className:"h-3.5 w-3.5 mr-1.5"})," ",u?"Viewing archived":"Archived"]}),e.jsxs("div",{className:"text-[12.5px] text-slate-500",children:[R.length," agents"]})]}),e.jsx("div",{className:"mb-4",children:e.jsx(JF,{})}),n?e.jsx("div",{className:"py-24 text-center text-slate-500",children:"Loading pipeline…"}):l==="kanban"?e.jsxs(Eo,{className:"w-full",children:[e.jsx("div",{className:"flex gap-4 pb-4",style:{minWidth:wie.length*300},children:wie.map(U=>{const G=R.filter(H=>H.stage===U.key);return e.jsxs("div",{className:"w-[280px] flex-shrink-0 flex flex-col",onDragOver:H=>{H.preventDefault(),H.dataTransfer.dropEffect="move"},onDrop:H=>{if(H.preventDefault(),C){const Y=t.find(se=>se.id===C);Y&&Y.stage!==U.key&&a.mutate({id:C,to_stage:U.key,from_stage:Y.stage}),A(null)}},children:[e.jsxs("div",{className:"flex items-center justify-between px-1 mb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"h-2.5 w-2.5 rounded-full",style:{background:U.color}}),e.jsx("h3",{className:"text-[13px] font-semibold text-slate-800",children:U.label}),e.jsx(qe,{variant:"secondary",className:"text-[10px] h-5 px-1.5",children:G.length})]}),e.jsx($,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>{x(U.key),p(!0)},children:e.jsx(nn,{className:"h-3.5 w-3.5"})})]}),e.jsxs("div",{className:"rounded-2xl bg-slate-100/60 p-2 space-y-2 min-h-[200px]",children:[G.map(H=>e.jsxs("div",{draggable:!0,onDragStart:()=>A(H.id),onClick:()=>v(H),className:"bg-white rounded-xl p-3 cursor-pointer hover:shadow-md border-l-[3px] transition-all",style:{borderLeftColor:U.color},children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"text-[13.5px] font-semibold text-slate-900 truncate",children:[H.first_name," ",H.last_name]}),e.jsxs("div",{className:"text-[11.5px] text-slate-500 flex items-center gap-1 mt-0.5 truncate",children:[e.jsx(Gi,{className:"h-3 w-3"}),e.jsx("span",{className:"truncate",children:H.brokerage??"—"})]})]}),H.temperature&&e.jsxs(qe,{variant:"outline",className:`text-[9.5px] px-1.5 py-0 ${Fwt[H.temperature]}`,children:[e.jsx(tY,{className:"h-2.5 w-2.5 mr-0.5"}),H.temperature]}),e.jsx(B,{agent:H})]}),e.jsxs("div",{className:"mt-2 flex items-center gap-2 text-[11px] text-slate-500",children:[e.jsx(Si,{className:"h-3 w-3"}),e.jsxs("span",{className:"truncate",children:[H.city,H.state&&`, ${H.state}`]})]}),H.next_follow_up_at&&e.jsxs("div",{className:"mt-1.5 text-[10.5px] text-violet-700 font-medium",children:["Next touch · ",Ys(new Date(H.next_follow_up_at),"MMM d")]})]},H.id)),G.length===0&&e.jsx("div",{className:"text-[11.5px] text-slate-400 text-center py-4",children:"Drop an agent here"})]})]},U.key)})}),e.jsx(Uq,{orientation:"horizontal"})]}):e.jsx(we,{className:"rounded-2xl overflow-hidden",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-slate-50 text-[11px] uppercase tracking-wider text-slate-500",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left px-4 py-3",children:"Agent"}),e.jsx("th",{className:"text-left px-4 py-3",children:"Brokerage"}),e.jsx("th",{className:"text-left px-4 py-3",children:"Location"}),e.jsx("th",{className:"text-left px-4 py-3",children:"Stage"}),e.jsx("th",{className:"text-left px-4 py-3",children:"Temp"}),e.jsx("th",{className:"text-left px-4 py-3",children:"Next Follow-Up"}),e.jsx("th",{className:"text-right px-4 py-3",children:"Actions"})]})}),e.jsxs("tbody",{children:[R.map(U=>{const G=wie.find(H=>H.key===U.stage);return e.jsxs("tr",{onClick:()=>v(U),className:"border-t border-slate-100 hover:bg-slate-50 cursor-pointer",children:[e.jsxs("td",{className:"px-4 py-3 font-medium text-slate-900",children:[U.first_name," ",U.last_name]}),e.jsx("td",{className:"px-4 py-3 text-slate-600",children:U.brokerage}),e.jsxs("td",{className:"px-4 py-3 text-slate-600",children:[U.city,", ",U.state]}),e.jsx("td",{className:"px-4 py-3",children:e.jsx(qe,{style:{background:G==null?void 0:G.color,color:"white"},children:G==null?void 0:G.label})}),e.jsx("td",{className:"px-4 py-3",children:U.temperature&&e.jsx(qe,{variant:"outline",className:Fwt[U.temperature],children:U.temperature})}),e.jsx("td",{className:"px-4 py-3 text-slate-600",children:U.next_follow_up_at?Ys(new Date(U.next_follow_up_at),"MMM d"):"—"}),e.jsx("td",{className:"px-4 py-3 text-right",children:e.jsx(B,{agent:U})})]},U.id)}),R.length===0&&e.jsx("tr",{children:e.jsx("td",{colSpan:7,className:"px-4 py-10 text-center text-slate-500",children:"No agents match this view."})})]})]})}),e.jsx(iGn,{open:m,onOpenChange:p,defaultStage:g,onSubmit:U=>r.mutate(U,{onSuccess:()=>p(!1)})}),e.jsx(mJe,{agent:_?t.find(U=>U.id===_.id)??_:null,open:!!_,onOpenChange:U=>!U&&j(null),onDeleted:()=>v(null)}),e.jsx(D_,{open:!!y,onOpenChange:U=>!U&&v(null),children:e.jsx(Mb,{className:"w-full sm:max-w-lg overflow-y-auto",children:O&&e.jsxs(e.Fragment,{children:[e.jsxs(xj,{children:[e.jsxs(yj,{className:"text-xl",children:[O.first_name," ",O.last_name]}),e.jsxs("div",{className:"text-[12.5px] text-slate-500 flex items-center gap-2",children:[e.jsx(Gi,{className:"h-3.5 w-3.5"})," ",O.brokerage??"—"," · ",O.city,", ",O.state]})]}),e.jsxs("div",{className:"mt-6 space-y-5",children:[e.jsxs("div",{className:"flex gap-2 flex-wrap",children:[e.jsxs($,{size:"sm",className:"gap-1.5 bg-gradient-to-r from-violet-600 to-indigo-600 text-white",onClick:()=>j(O),children:[e.jsx(ui,{className:"h-3.5 w-3.5"})," Edit contact"]}),e.jsxs($,{variant:"outline",size:"sm",className:"gap-1.5",onClick:()=>s(`/attract/agents/${O.id}`),children:[e.jsx(Ir,{className:"h-3.5 w-3.5"})," Open relationship"]}),O.email&&e.jsxs($,{variant:"outline",size:"sm",className:"gap-1.5",onClick:()=>I(O),children:[e.jsx(pn,{className:"h-3.5 w-3.5"})," Email"]}),O.phone&&e.jsx($,{variant:"outline",size:"sm",className:"gap-1.5",asChild:!0,children:e.jsxs("a",{href:`tel:${O.phone}`,children:[e.jsx(ka,{className:"h-3.5 w-3.5"})," Call"]})}),e.jsxs($,{variant:"outline",size:"sm",className:"gap-1.5",onClick:()=>s(`/attract/agents/${O.id}`),children:[e.jsx(bo,{className:"h-3.5 w-3.5"})," Log touch"]})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-[11px] uppercase tracking-wider text-slate-500",children:"Stage"}),e.jsxs(bs,{value:O.stage,onValueChange:U=>a.mutate({id:O.id,to_stage:U,from_stage:O.stage}),children:[e.jsx(ys,{className:"mt-1",children:e.jsx(_s,{})}),e.jsx(vs,{children:wie.map(U=>e.jsx(We,{value:U.key,children:U.label},U.key))})]})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-[11px] uppercase tracking-wider text-slate-500",children:"Temperature"}),e.jsxs(bs,{value:O.temperature??"warm",onValueChange:U=>r.mutate({id:O.id,first_name:O.first_name,temperature:U}),children:[e.jsx(ys,{className:"mt-1",children:e.jsx(_s,{})}),e.jsx(vs,{children:["cold","warm","hot"].map(U=>e.jsx(We,{value:U,className:"capitalize",children:U},U))})]})]}),!!(O.tags??[]).length&&e.jsx("div",{className:"flex flex-wrap gap-1.5",children:(O.tags??[]).map(U=>e.jsx(qe,{variant:"outline",className:"rounded-full",children:U},U))}),e.jsx(U8e,{label:"Notes",value:O.notes}),e.jsx(U8e,{label:"Goals",value:O.goals}),e.jsx(U8e,{label:"Challenges",value:O.challenges}),e.jsxs("div",{className:"pt-4 border-t flex justify-between",children:[e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>i.mutate({id:O.id,archived:!O.is_archived}),children:[e.jsx(kf,{className:"h-4 w-4 mr-1"})," ",O.is_archived?"Restore":"Remove from pipeline"]}),e.jsxs($,{variant:"ghost",size:"sm",className:"text-rose-600",onClick:()=>j(O),children:[e.jsx(Un,{className:"h-4 w-4 mr-1"})," Delete…"]})]})]})]})})}),(M==null?void 0:M.email)&&e.jsx(W2,{open:!!M,onOpenChange:U=>!U&&I(null),contact:{id:M.id,first_name:M.preferred_name||M.first_name,last_name:M.last_name||"",email:M.email},gmailEmail:P,sendSource:"attract",logTouchpoint:!1})]})}function U8e({label:s,value:t}){return e.jsxs("div",{children:[e.jsx(re,{className:"text-[11px] uppercase tracking-wider text-slate-500",children:s}),e.jsx("div",{className:"mt-1 text-[13.5px] text-slate-800 whitespace-pre-wrap min-h-[24px]",children:t||e.jsx("span",{className:"text-slate-400",children:"Not set"})})]})}function iGn({open:s,onOpenChange:t,defaultStage:n,onSubmit:r}){const[a,i]=k.useState({first_name:"",last_name:"",brokerage:"",city:"",state:"",temperature:"warm",primary_pillar:"connect",stage:n??"new_connection",notes:""});return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"max-w-lg",children:[e.jsx(Vs,{children:e.jsx($s,{children:"Add an agent to your pipeline"})}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(re,{children:"First name *"}),e.jsx(be,{value:a.first_name,onChange:l=>i({...a,first_name:l.target.value})})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Last name"}),e.jsx(be,{value:a.last_name,onChange:l=>i({...a,last_name:l.target.value})})]}),e.jsxs("div",{className:"col-span-2",children:[e.jsx(re,{children:"Current brokerage"}),e.jsx(be,{value:a.brokerage,onChange:l=>i({...a,brokerage:l.target.value})})]}),e.jsxs("div",{children:[e.jsx(re,{children:"City"}),e.jsx(be,{value:a.city,onChange:l=>i({...a,city:l.target.value})})]}),e.jsxs("div",{children:[e.jsx(re,{children:"State"}),e.jsx(be,{value:a.state,onChange:l=>i({...a,state:l.target.value})})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Temperature"}),e.jsxs(bs,{value:a.temperature,onValueChange:l=>i({...a,temperature:l}),children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"cold",children:"Cold"}),e.jsx(We,{value:"warm",children:"Warm"}),e.jsx(We,{value:"hot",children:"Hot"})]})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Primary pillar"}),e.jsxs(bs,{value:a.primary_pillar,onValueChange:l=>i({...a,primary_pillar:l}),children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"produce",children:"Produce"}),e.jsx(We,{value:"influence",children:"Influence"}),e.jsx(We,{value:"provide",children:"Provide"}),e.jsx(We,{value:"connect",children:"Connect"})]})]})]}),e.jsxs("div",{className:"col-span-2",children:[e.jsx(re,{children:"Notes"}),e.jsx(Ls,{rows:3,value:a.notes,onChange:l=>i({...a,notes:l.target.value})})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"ghost",onClick:()=>t(!1),children:"Cancel"}),e.jsx($,{disabled:!a.first_name,className:"bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>r(a),children:"Add Agent"})]})]})})}const oGn={call:ka,email:pn,coffee:b_,gift:Zo,text:pn,event:wm};function lGn(){const{followUps:s,complete:t}=QF(),{agents:n}=A0(),r=k.useMemo(()=>{const l=np(new Date),o=[],c=[],d=[],u=[],h=[];for(const m of s){if(m.completed_at){h.push(m);continue}if(!m.due_at){u.push(m);continue}const p=new Date(m.due_at);Xw(p,l)?o.push(m):m0(p)?c.push(m):rbs(p)?d.push(m):u.push(m)}return{overdue:o,today:c,tomorrow:d,later:u,done:h}},[s]),a=new Map(n.map(l=>[l.id,l])),i=[{label:"Overdue",value:r.overdue.length,tone:"text-rose-600 bg-rose-50",icon:Ho},{label:"Due Today",value:r.today.length,tone:"text-orange-600 bg-orange-50",icon:sa},{label:"Completed This Week",value:r.done.filter(l=>l.completed_at&&new Date(l.completed_at)>wu(new Date,-7)).length,tone:"text-emerald-600 bg-emerald-50",icon:Gr}];return e.jsxs("div",{children:[e.jsx(Hm,{eyebrow:"Follow-Up Center",title:"One list. One rhythm. One relationship at a time.",description:"Everything you promised to do — organized so it never feels like a to-do list."}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4 mb-6",children:i.map(l=>e.jsxs(we,{className:"p-5 rounded-2xl flex items-center gap-4",children:[e.jsx("div",{className:`h-11 w-11 rounded-xl grid place-items-center ${l.tone}`,children:e.jsx(l.icon,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-semibold text-slate-900",children:l.value}),e.jsx("div",{className:"text-[12px] uppercase tracking-wider text-slate-500",children:l.label})]})]},l.label))}),e.jsx("div",{className:"mb-6",children:e.jsx(JF,{})}),e.jsxs("div",{className:"space-y-6",children:[e.jsx(rW,{title:"Overdue",items:r.overdue,agentMap:a,onComplete:l=>t.mutate(l),tone:"rose"}),e.jsx(rW,{title:"Today",items:r.today,agentMap:a,onComplete:l=>t.mutate(l),tone:"orange"}),e.jsx(rW,{title:"Tomorrow",items:r.tomorrow,agentMap:a,onComplete:l=>t.mutate(l),tone:"violet"}),e.jsx(rW,{title:"Later This Week",items:r.later,agentMap:a,onComplete:l=>t.mutate(l),tone:"slate"}),r.done.length>0&&e.jsx(rW,{title:"Recently Completed",items:r.done.slice(0,5),agentMap:a,onComplete:()=>{},tone:"emerald",done:!0})]})]})}function rW({title:s,items:t,agentMap:n,onComplete:r,tone:a,done:i}){if(t.length===0)return null;const l={rose:"#f43f5e",orange:"#f97316",violet:"#8b5cf6",slate:"#94a3b8",emerald:"#10b981"};return e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx("span",{className:"h-2.5 w-2.5 rounded-full",style:{background:l[a]}}),e.jsx("h3",{className:"text-[13px] font-semibold uppercase tracking-wider text-slate-700",children:s}),e.jsx(qe,{variant:"secondary",className:"text-[10px]",children:t.length})]}),e.jsx(we,{className:"rounded-2xl divide-y divide-slate-100 overflow-hidden",children:t.map(o=>{const c=n.get(o.agent_id),d=oGn[o.touch_type??""]??pn;return e.jsxs("div",{className:`flex items-start gap-3 p-4 hover:bg-slate-50 ${i?"opacity-60":""}`,children:[e.jsx(Li,{checked:!!o.completed_at,onCheckedChange:()=>r(o.id),className:"mt-1"}),e.jsx("div",{className:"h-8 w-8 rounded-lg grid place-items-center flex-shrink-0",style:{background:`${l[a]}18`,color:l[a]},children:e.jsx(d,{className:"h-4 w-4"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-[13.5px] font-medium text-slate-900",children:o.title}),c&&e.jsxs("div",{className:"text-[12px] text-slate-500 mt-0.5",children:["for ",c.first_name," ",c.last_name," · ",c.brokerage]}),o.notes&&e.jsx("div",{className:"text-[12.5px] text-slate-600 mt-1",children:o.notes})]}),o.due_at&&e.jsx("div",{className:"text-[11.5px] text-slate-500 whitespace-nowrap",children:Ys(new Date(o.due_at),"MMM d")}),e.jsx($,{variant:"ghost",size:"sm",children:"Snooze"})]},o.id)})})]})}const cGn={pdf:ea,link:pd,video:ia,tool:L5,guide:wg},dGn={script:"bg-violet-100 text-violet-700",checklist:"bg-teal-100 text-teal-700",tool:"bg-orange-100 text-orange-700",guide:"bg-indigo-100 text-indigo-700",masterclass:"bg-rose-100 text-rose-700"};function uGn(){const{resources:s,isLoading:t}=TWt(),[n,r]=k.useState(""),[a,i]=k.useState("all"),l=Array.from(new Set(s.map(c=>c.category).filter(Boolean))),o=s.filter(c=>(a==="all"||c.category===a)&&(!n||`${c.title} ${c.description??""}`.toLowerCase().includes(n.toLowerCase())));return e.jsxs("div",{children:[e.jsx(Hm,{eyebrow:"Resource Library",title:"The stack you share with future teammates.",description:"Every resource, script, and tool you use — ready to share in one click.",actions:e.jsxs($,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",children:[e.jsx(nn,{className:"h-4 w-4 mr-1"})," Add Resource"]})}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 mb-5",children:[e.jsxs("div",{className:"relative flex-1 min-w-[240px] max-w-md",children:[e.jsx(Yr,{className:"h-4 w-4 text-slate-400 absolute left-3 top-1/2 -translate-y-1/2"}),e.jsx(be,{value:n,onChange:c=>r(c.target.value),placeholder:"Search resources…",className:"pl-9 rounded-full bg-white"})]}),e.jsxs("div",{className:"flex gap-1.5 flex-wrap",children:[e.jsx($,{size:"sm",variant:a==="all"?"default":"outline",className:"rounded-full h-8",onClick:()=>i("all"),children:"All"}),l.map(c=>e.jsx($,{size:"sm",variant:a===c?"default":"outline",className:"rounded-full h-8 capitalize",onClick:()=>i(c),children:c},c))]})]}),t?e.jsx("div",{className:"py-24 text-center text-slate-500",children:"Loading resources…"}):o.length===0?e.jsx(we,{className:"p-12 text-center rounded-2xl",children:e.jsx("div",{className:"text-slate-500",children:"No resources yet. Add your first shareable asset above."})}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4",children:o.map(c=>{const d=cGn[c.resource_type]??ea;return e.jsxs(we,{className:"p-5 rounded-2xl hover:shadow-md transition-all group",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsx("div",{className:"h-11 w-11 rounded-xl bg-violet-50 grid place-items-center text-violet-600",children:e.jsx(d,{className:"h-5 w-5"})}),c.category&&e.jsx(qe,{className:`${dGn[c.category]??"bg-slate-100 text-slate-700"} border-0 capitalize`,children:c.category})]}),e.jsxs("div",{className:"mt-4",children:[e.jsx("div",{className:"font-semibold text-slate-900",children:c.title}),c.description&&e.jsx("div",{className:"text-[13px] text-slate-600 mt-1 line-clamp-2",children:c.description})]}),e.jsxs("div",{className:"mt-4 pt-4 border-t border-slate-100 flex items-center justify-between text-[12px] text-slate-500",children:[e.jsx("div",{children:"Shared 0×"}),e.jsxs($,{size:"sm",variant:"outline",className:"rounded-full gap-1",children:[e.jsx(ou,{className:"h-3.5 w-3.5"})," Share"]})]})]},c.id)})})]})}const hGn=[{category:"First Touch",icon:bo,color:"#7c3aed",items:[{title:"Warm intro after meeting",body:"Hey {{first_name}} — really enjoyed meeting you at {{event}}. Would love to grab coffee sometime and hear more about what you're building at {{brokerage}}."},{title:"Congrats on a recent close",body:"Saw your closing at {{property}} pop up — nice work {{first_name}}. Those aren't easy right now. If you ever want to compare notes on how you're getting deals across the line, I'm always up for a coffee."}]},{category:"Value Share",icon:pn,color:"#4f46e5",items:[{title:"Sending a helpful resource",body:"Hey {{first_name}} — thought of you when I put this together. No agenda, just something I think you'll actually use: {{resource_link}}"},{title:"Market update forward",body:"Sending along this month's local market snapshot — figured you might want it for your buyer conversations this week: {{link}}"}]},{category:"Coffee Invite",icon:b_,color:"#0d9488",items:[{title:"Casual 30-min coffee",body:"Hey {{first_name}}, are you free for a 30-min coffee sometime in the next couple weeks? No agenda — just want to hear how the year is going for you."},{title:"Follow-up after coffee",body:"Really enjoyed catching up {{first_name}}. Here's the {{resource}} I mentioned — and I'll circle back in a few weeks. In the meantime, if I can help with anything, just text."}]},{category:"Check-In",icon:ka,color:"#9333ea",items:[{title:"Quarterly check-in",body:"Hey {{first_name}} — just thinking of you. How's the quarter shaping up? No ask, just checking in."},{title:"Birthday message",body:"Happy birthday {{first_name}}! Hope you get to slow down for a minute today. 🎉"}]}];function mGn(){const s=t=>{navigator.clipboard.writeText(t),ae.success("Template copied")};return e.jsxs("div",{children:[e.jsx(Hm,{eyebrow:"Message Templates",title:"Words that sound like you.",description:"Starting points — never scripts. Personalize the details and let the relationship speak."}),e.jsx("div",{className:"space-y-8",children:hGn.map(t=>{const n=t.icon;return e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[e.jsx("div",{className:"h-10 w-10 rounded-xl grid place-items-center",style:{background:`${t.color}18`,color:t.color},children:e.jsx(n,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-semibold text-slate-900",children:t.category}),e.jsxs("div",{className:"text-[12.5px] text-slate-500",children:[t.items.length," templates"]})]})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:t.items.map(r=>e.jsxs(we,{className:"p-5 rounded-2xl",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsx("div",{className:"font-semibold text-slate-900",children:r.title}),e.jsx(qe,{variant:"outline",className:"text-[10px]",children:t.category})]}),e.jsx("p",{className:"mt-3 text-[13.5px] text-slate-700 leading-relaxed whitespace-pre-wrap",children:r.body}),e.jsx("div",{className:"mt-4 pt-4 border-t border-slate-100 flex justify-end",children:e.jsxs($,{variant:"outline",size:"sm",className:"rounded-full gap-1",onClick:()=>s(r.body),children:[e.jsx(Da,{className:"h-3.5 w-3.5"})," Copy"]})})]},r.title))})]},t.category)})})]})}const fGn={produce:"#7c3aed",influence:"#4f46e5",provide:"#0d9488",connect:"#9333ea"};function zwt(){const{agents:s}=A0(),{activities:t}=dJe(180),n=k.useMemo(()=>Array.from({length:12},(l,o)=>My(yY(new Date,(11-o)*7))).map(l=>{const o=wu(l,7),c=t.filter(d=>new Date(d.created_at)>=l&&new Date(d.created_at){const i={produce:0,influence:0,provide:0,connect:0};for(const l of t)l.pillar&&(i[l.pillar]=(i[l.pillar]||0)+1);return Object.entries(i).map(([l,o])=>({name:l,value:o,color:fGn[l]}))},[t]),a=k.useMemo(()=>["new_connection","building_relationship","engaging_with_value","active_conversation","brokerage_presentation","joined"].map(l=>({stage:l.replace(/_/g," "),count:s.filter(o=>o.stage===l).length})),[s]);return e.jsxs("div",{children:[e.jsx(Hm,{eyebrow:"Reports & Insights",title:"See the compounding effect.",description:"Attraction is a long game. These reports show you the small consistent trend lines that matter."}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[e.jsxs(we,{className:"p-6 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wider text-slate-500 mb-1",children:"Weekly Activity"}),e.jsx("div",{className:"text-lg font-semibold text-slate-900 mb-4",children:"Attraction activities · Last 12 weeks"}),e.jsx(C_,{width:"100%",height:260,children:e.jsxs(gZe,{data:n,children:[e.jsx(Cb,{dataKey:"week",tick:{fontSize:11}}),e.jsx(Ab,{tick:{fontSize:11}}),e.jsx(vg,{}),e.jsx(FF,{type:"monotone",dataKey:"activities",stroke:"#7c3aed",strokeWidth:2.5,dot:{r:3}})]})})]}),e.jsxs(we,{className:"p-6 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wider text-slate-500 mb-1",children:"Pillar Balance"}),e.jsx("div",{className:"text-lg font-semibold text-slate-900 mb-4",children:"Where you're investing time"}),e.jsx(C_,{width:"100%",height:260,children:e.jsxs(xZe,{children:[e.jsx(Mk,{data:r,dataKey:"value",nameKey:"name",cx:"50%",cy:"50%",innerRadius:55,outerRadius:90,paddingAngle:2,children:r.map((i,l)=>e.jsx(vV,{fill:i.color},l))}),e.jsx(vg,{}),e.jsx(lO,{})]})})]}),e.jsxs(we,{className:"p-6 rounded-2xl lg:col-span-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wider text-slate-500 mb-1",children:"Pipeline Distribution"}),e.jsx("div",{className:"text-lg font-semibold text-slate-900 mb-4",children:"Agents by stage"}),e.jsx(C_,{width:"100%",height:280,children:e.jsxs(YEe,{data:a,children:[e.jsx(Cb,{dataKey:"stage",tick:{fontSize:10}}),e.jsx(Ab,{tick:{fontSize:11}}),e.jsx(vg,{}),e.jsx(R2,{dataKey:"count",fill:"#4f46e5",radius:[8,8,0,0]})]})})]})]})]})}function pGn(){const{settings:s,upsert:t,resetOnboarding:n}=KV(),[r,a]=k.useState({});k.useEffect(()=>{s&&a(s)},[s]);const i=l=>a({...r,...l});return e.jsxs("div",{className:"max-w-3xl",children:[e.jsx(Hm,{eyebrow:"Attract Settings",title:"Your attraction philosophy.",description:"A one-time setup that keeps every touch you send true to who you are."}),e.jsxs(we,{className:"p-5 rounded-2xl mb-6 flex flex-col md:flex-row md:items-center gap-4 bg-gradient-to-r from-violet-50 to-indigo-50 border-violet-100",children:[e.jsx("div",{className:"h-11 w-11 rounded-xl bg-white text-violet-700 grid place-items-center shadow-sm",children:e.jsx(_h,{className:"h-5 w-5"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"text-[13.5px] font-semibold text-slate-900",children:"Your 90-day plan"}),e.jsx("div",{className:"text-[12.5px] text-slate-600",children:s!=null&&s.onboarding_completed_at?`Primary pillar: ${s.primary_pillar??s.attraction_style??"balanced"} · Outcome: ${s.ninety_day_outcome??"—"}`:"You haven't completed onboarding yet."})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{asChild:!0,variant:"outline",className:"rounded-full",children:e.jsx(nr,{to:"/attract/plan",children:"View plan"})}),e.jsxs($,{variant:"outline",className:"rounded-full",onClick:()=>n.mutate(),children:[e.jsx(jm,{className:"h-4 w-4 mr-1.5"})," Rerun onboarding"]})]})]}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs(we,{className:"p-6 rounded-2xl",children:[e.jsx("h3",{className:"text-lg font-semibold text-slate-900 mb-1",children:"Your voice & story"}),e.jsx("p",{className:"text-[13px] text-slate-600 mb-5",children:"Used to personalize scripts, invites, and shared content."}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Elevator introduction"}),e.jsx(Ls,{rows:3,value:r.elevator_intro??"",onChange:l=>i({elevator_intro:l.target.value}),placeholder:"I help agents scale their business by trading isolation for a real team..."})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Focus market"}),e.jsx(be,{value:r.focus_market??"",onChange:l=>i({focus_market:l.target.value}),placeholder:"Orange County, CA"})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Annual attraction goal"}),e.jsx(be,{type:"number",value:r.annual_attract_goal??"",onChange:l=>i({annual_attract_goal:Number(l.target.value)||null}),placeholder:"12"})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:'Your "why" for attraction'}),e.jsx(Ls,{rows:3,value:r.why_statement??"",onChange:l=>i({why_statement:l.target.value}),placeholder:"Because the right agents in the right room change everyone's business..."})]})]})]}),e.jsxs(we,{className:"p-6 rounded-2xl",children:[e.jsx("h3",{className:"text-lg font-semibold text-slate-900 mb-1",children:"Cadence & rhythm"}),e.jsx("p",{className:"text-[13px] text-slate-600 mb-5",children:"How often should we remind you to show up for agents at each stage?"}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Hot leads follow-up"}),e.jsxs(bs,{value:String(r.hot_cadence_days??3),onValueChange:l=>i({hot_cadence_days:Number(l)}),children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"1",children:"Every day"}),e.jsx(We,{value:"3",children:"Every 3 days"}),e.jsx(We,{value:"7",children:"Every week"})]})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Warm leads follow-up"}),e.jsxs(bs,{value:String(r.warm_cadence_days??14),onValueChange:l=>i({warm_cadence_days:Number(l)}),children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"7",children:"Weekly"}),e.jsx(We,{value:"14",children:"Every 2 weeks"}),e.jsx(We,{value:"30",children:"Monthly"})]})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Long-term nurture"}),e.jsxs(bs,{value:String(r.longterm_cadence_days??60),onValueChange:l=>i({longterm_cadence_days:Number(l)}),children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"30",children:"Monthly"}),e.jsx(We,{value:"60",children:"Every 2 months"}),e.jsx(We,{value:"90",children:"Quarterly"})]})]})]}),e.jsx("div",{className:"flex flex-col justify-end",children:e.jsxs("div",{className:"flex items-center justify-between rounded-xl bg-slate-50 p-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[13px] font-medium text-slate-900",children:"Weekly digest email"}),e.jsx("div",{className:"text-[11.5px] text-slate-500",children:"Every Sunday at 6pm"})]}),e.jsx(On,{checked:r.weekly_digest_enabled??!0,onCheckedChange:l=>i({weekly_digest_enabled:l})})]})})]})]}),e.jsxs(we,{className:"p-6 rounded-2xl bg-gradient-to-br from-violet-50 to-indigo-50 border-violet-100",children:[e.jsx("h3",{className:"text-lg font-semibold text-slate-900 mb-1",children:"The Attract Trust Reminder"}),e.jsx("p",{className:"text-[13.5px] text-slate-700 leading-relaxed",children:"Attract is never a sales funnel. Every touch you make here should be something you'd be proud of if the agent saw every note you'd taken about them. Real relationships. On a rhythm. For years."})]}),e.jsx("div",{className:"flex justify-end",children:e.jsx($,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600 px-8",onClick:()=>t.mutate(r),disabled:t.isPending,children:"Save Settings"})})]})]})}const Tqe=[{key:"transaction_tracker",pillar:"produce",title:"Transaction-to-Relationship Tracker",route:"/attract/produce/transaction-tracker",status:"live",tables:["attract_transactions","attract_agents"],notes:"Full CRUD, converts co-op agents into pipeline relationships."},{key:"production_goals",pillar:"produce",title:"Production Goals",route:"/attract/produce/goals",status:"live",tables:["attract_production_goals","attract_transactions"],notes:"Annual/quarterly/monthly targets, pace vs actual, auto closings from logged transactions, weekly breakdown."},{key:"awards",pillar:"produce",title:"Awards & Recognition",route:"/attract/produce/awards",status:"live",tables:["attract_awards"],notes:"CRUD + copyable proof points into Content Studio."},{key:"content_calendar",pillar:"produce",title:"Content Calendar",route:"/attract/influence/content-calendar",status:"live",tables:["attract_content_drafts","attract_market_presence","attract_speaking_opportunities"],notes:"Unified month grid; schedules undated drafts."},{key:"market_presence",pillar:"produce",title:"Market Presence",route:"/attract/produce/market-presence",status:"live",tables:["attract_market_presence"],notes:"Cadence commitments with status pipeline, past-due tracking, task + activity wiring."},{key:"testimonials",pillar:"produce",title:"Client Testimonials",route:"/attract/produce/testimonials",status:"live",tables:["attract_testimonials"],notes:"Permission tracking, approval gate, usage counter to prevent overexposure."},{key:"content_studio",pillar:"influence",title:"Authority Content Studio",route:"/attract/influence/content-studio",status:"live",tables:["attract_content_drafts"],notes:"AI-assisted drafts with status workflow."},{key:"speaking",pillar:"influence",title:"Speaking Calendar",route:"/attract/influence/speaking",status:"live",tables:["attract_speaking_opportunities","attract_follow_ups","attract_activities"],notes:"Month/week/agenda, full CRUD, status pipeline, ICS export, follow-up + activity wiring."},{key:"masterclass",pillar:"influence",title:"Masterclass Builder",route:"/attract/provide/masterclasses",status:"live",tables:["attract_masterclasses","attract_events","attract_resource_kits","attract_follow_ups"],notes:"Lives under Provide; 6-step builder, autosave, event + kit conversion."},{key:"podcast",pillar:"influence",title:"Podcast & Guest Spots",route:"/attract/influence/speaking",status:"partial",tables:["attract_speaking_opportunities"],notes:"Tracked as event_type = podcast inside the Speaking Calendar."},{key:"roundtables",pillar:"influence",title:"Agent Roundtables",route:"/attract/events/new",status:"partial",tables:["attract_events"],notes:"Uses the Connect Event Engine rather than a separate system."},{key:"resource_kits",pillar:"provide",title:"Resource Kit Builder",route:"/attract/provide/kits",status:"live",tables:["attract_resource_kits","attract_resource_kit_items","attract_kit_shares","attract_kit_events"],notes:"Flagship — build, share, track engagement."},{key:"kit_templates",pillar:"provide",title:"Starter Kit Library",route:"/attract/provide/kits/templates",status:"live",tables:["attract_kit_templates"],notes:"10 starter kits, clone to own."},{key:"masterclass_builder",pillar:"provide",title:"Masterclass Builder",route:"/attract/provide/masterclasses",status:"live",tables:["attract_masterclasses"],notes:"8 starter templates, deterministic copy generation, no auto-send."},{key:"value_library",pillar:"provide",title:"Value Library",route:"/attract/resources",status:"partial",tables:["attract_resources"],notes:"Read + save works; no categorization/search yet."},{key:"event_engine",pillar:"connect",title:"Event & Mastermind Engine",route:"/attract/events",status:"live",tables:["attract_events","attract_event_attendees","attract_event_invitations","attract_event_notes"],notes:"Builder, public registration, invitations, QR check-in, follow-up."},{key:"checkin",pillar:"connect",title:"Mobile Check-In",route:"/attract/events/:eventId/checkin",status:"live",tables:["attract_event_attendees"],notes:"QR + manual check-in."},{key:"coffee_meetings",pillar:"connect",title:"Coffee & Meetings",route:"/attract/follow-up",status:"partial",tables:["attract_follow_ups"],notes:"Handled as follow-ups; no dedicated meeting scheduler."},{key:"milestones",pillar:"connect",title:"Milestones & Celebrations",route:"/attract/connect/milestones",status:"live",tables:["attract_milestones","attract_follow_ups"],notes:"Recurring annual dates roll forward; reach-out tasks + celebration logging."},{key:"checkins",pillar:"connect",title:"Personal Check-Ins",route:"/attract/opportunities",status:"partial",tables:["attract_recommendations"],notes:"Surfaced by the intelligence layer as recommendations."},{key:"circles",pillar:"connect",title:"Agent Circles",route:"/attract/events/new",status:"partial",tables:["attract_events"],notes:"Create as a recurring mastermind event."},{key:"opportunities",pillar:"core",title:"Relationship Opportunities",route:"/attract/opportunities",status:"live",tables:["attract_recommendations","attract_agent_scores"],notes:"Ranked, explainable recommendations."},{key:"digest",pillar:"core",title:"Weekly Digest",route:"/attract/digest",status:"live",tables:["attract_digests","attract_digest_items","attract_digest_settings"],notes:"Manual send + preview via attract-send-digest."},{key:"plan",pillar:"core",title:"90-Day Plan",route:"/attract/plan",status:"live",tables:["attract_settings","attract_daily_plan"],notes:""},{key:"pipeline",pillar:"core",title:"Agent Pipeline",route:"/attract/pipeline",status:"live",tables:["attract_agents","attract_pipeline_history"],notes:"Kanban with stage history."},{key:"reports",pillar:"core",title:"Reports",route:"/attract/reports",status:"partial",tables:["attract_activities","attract_agents"],notes:"Core charts only; no export."}],Mqe={live:"Live",partial:"Partial",placeholder:"Placeholder",integration_required:"Integration required"},RWt={live:"bg-emerald-50 text-emerald-700 border-emerald-200",partial:"bg-amber-50 text-amber-700 border-amber-200",placeholder:"bg-slate-100 text-slate-600 border-slate-200",integration_required:"bg-rose-50 text-rose-700 border-rose-200"};function gGn({tool:s,accent:t}){const[n,r]=k.useState(!1),a=Jn(),i=s.icon,l=!!s.to,o=Tqe.find(u=>u.key===s.key),c=(o==null?void 0:o.status)??(l?"live":"placeholder"),d=()=>{l&&s.to?a(s.to):r(!0)};return e.jsxs(e.Fragment,{children:[e.jsxs(we,{onClick:d,className:"group p-5 rounded-2xl border-slate-200/70 bg-white shadow-sm hover:shadow-md cursor-pointer transition-all hover:-translate-y-0.5 relative",children:[e.jsxs("div",{className:`absolute top-3 right-3 inline-flex items-center gap-1 text-[10px] font-semibold uppercase tracking-wider rounded-full px-2 py-0.5 border ${RWt[c]}`,children:[c==="live"&&e.jsx(kn,{className:"h-2.5 w-2.5"}),Mqe[c]]}),e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"h-11 w-11 rounded-xl grid place-items-center flex-shrink-0",style:{background:`${t}18`,color:t},children:e.jsx(i,{className:"h-5 w-5"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-[15px] font-semibold text-slate-900",children:s.title}),e.jsx("div",{className:"text-[13px] text-slate-600 mt-1 leading-relaxed",children:s.description}),e.jsxs("div",{className:"mt-3 inline-flex items-center gap-1 text-[12.5px] font-semibold",style:{color:t},children:[s.cta??(l?"Open Tool":"Preview")," ",e.jsx(fi,{className:"h-3.5 w-3.5 group-hover:translate-x-0.5 transition-transform"})]})]})]})]}),e.jsx(zs,{open:n,onOpenChange:r,children:e.jsxs(Rs,{className:"max-w-lg",children:[e.jsxs(Vs,{children:[e.jsx("div",{className:"h-12 w-12 rounded-2xl grid place-items-center mb-2",style:{background:`${t}18`,color:t},children:e.jsx(i,{className:"h-6 w-6"})}),e.jsx($s,{children:s.title})]}),e.jsxs("div",{className:"text-[14px] text-slate-700 leading-relaxed",children:[s.description,e.jsx("div",{className:"mt-4 rounded-xl bg-violet-50 border border-violet-100 p-4 text-[13px] text-violet-900",children:"This tool is on the roadmap. Mark your interest and it will jump the queue in your next release."})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"ghost",onClick:()=>r(!1),children:"Close"}),e.jsx($,{className:"bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>{ae.success("Added to your plan"),r(!1)},children:"Add to My Plan"})]})]})})]})}function fJe({pillar:s,title:t,tagline:n,intro:r,accent:a,icon:i,tools:l,stats:o}){return e.jsxs("div",{children:[e.jsxs("div",{className:"rounded-3xl p-7 md:p-10 mb-8 relative overflow-hidden text-white",style:{background:`linear-gradient(135deg, ${a} 0%, #4f46e5 100%)`},children:[e.jsx("div",{className:"absolute -right-16 -top-16 h-64 w-64 rounded-full bg-white/10 blur-2xl"}),e.jsxs("div",{className:"relative",children:[e.jsxs("div",{className:"inline-flex items-center gap-2 text-[11px] uppercase tracking-[0.18em] font-semibold opacity-80 mb-3",children:[e.jsx(i,{className:"h-4 w-4"})," Pillar ",s]}),e.jsx("h1",{className:"text-4xl md:text-5xl font-semibold tracking-tight",children:t}),e.jsx("p",{className:"text-white/85 text-lg mt-2",children:n}),e.jsx("p",{className:"text-white/70 mt-4 max-w-2xl leading-relaxed",children:r}),o&&e.jsx("div",{className:"mt-6 grid grid-cols-2 md:grid-cols-4 gap-3 max-w-2xl",children:o.map(c=>e.jsxs("div",{className:"rounded-xl bg-white/10 backdrop-blur px-4 py-3",children:[e.jsx("div",{className:"text-2xl font-semibold tabular-nums",children:c.value}),e.jsx("div",{className:"text-[11.5px] uppercase tracking-wider opacity-80",children:c.label})]},c.label))})]})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4",children:l.map(c=>e.jsx(gGn,{tool:c,accent:a},c.key))})]})}function Bwt(){return e.jsx(fJe,{pillar:"01",title:"Produce",accent:"#7c3aed",icon:ql,tagline:"Become the agent others want to be around.",intro:"Production isn't ego — it's proof. When you're actively closing, learning, and getting recognized, agents naturally lean in. Use these tools to make your production visible without bragging.",stats:[{label:"Closed YTD",value:24},{label:"Awards",value:3},{label:"Content Pieces",value:12},{label:"Speaking",value:2}],tools:[{key:"transaction_tracker",icon:ri,title:"Transaction-to-Relationship Tracker",description:"Turn great cooperating agents from real transactions into long-term professional relationships.",to:"/attract/produce/transaction-tracker"},{key:"production_goals",icon:v0,title:"Production Goals",description:"Set annual, quarterly, and monthly targets, then track whether you are ahead or behind pace.",to:"/attract/produce/goals"},{key:"awards",icon:oh,title:"Awards & Recognition",description:"Track brokerage and industry awards so you can reference them naturally in agent conversations.",to:"/attract/produce/awards"},{key:"content_calendar",icon:N2,title:"Content Calendar",description:"One month view of every draft, market update, and speaking date you have committed to.",to:"/attract/influence/content-calendar"},{key:"market_presence",icon:mc,title:"Market Presence",description:"Publish market updates on a set cadence so agents see you as the local voice.",to:"/attract/produce/market-presence"},{key:"testimonials",icon:ri,title:"Client Testimonials",description:"A permission-tracked library of client quotes that make future agent conversations easier.",to:"/attract/produce/testimonials"}]})}function $wt(){return e.jsx(fJe,{pillar:"02",title:"Influence",accent:"#4f46e5",icon:kn,tagline:"Show up in ways that draw the right agents to you.",intro:"Influence is earned by helping publicly and consistently. These tools give you simple ways to teach, speak, and be seen — so the right agents come to you first.",stats:[{label:"Speaking Slots",value:4},{label:"Podcast Guests",value:2},{label:"Masterclasses",value:6},{label:"Reach",value:"12.4k"}],tools:[{key:"content_studio",icon:v3,title:"Authority Content Studio",description:"Turn your real experience into agent-focused content — script, caption, carousel, email — in one shot.",to:"/attract/influence/content-studio"},{key:"content_calendar",icon:fd,title:"Content Calendar",description:"See drafts, market updates, and speaking dates on one month grid — and schedule what has no date.",to:"/attract/influence/content-calendar"},{key:"speaking",icon:w2,title:"Speaking Calendar",description:"Track panels, MLS talks, podcasts, and keynotes from first idea through post-event follow-up.",to:"/attract/influence/speaking"},{key:"masterclass",icon:Bm,title:"Masterclass Builder",description:"Turn what you already know into a 45-minute teaching moment agents actually attend.",to:"/attract/provide/masterclasses"},{key:"podcast",icon:ia,title:"Podcast & Guest Spots",description:"Log podcast appearances in the Speaking Calendar and repurpose clips into agent touch points.",to:"/attract/influence/speaking"},{key:"roundtables",icon:Xn,title:"Agent Roundtables",description:"Host small-group conversations using the Connect Event Engine — value first, no pitching.",to:"/attract/events/new"}]})}const X9=["attract-kits"],aW=s=>["attract-kit-items",s],iW=s=>["attract-kit-shares",s??"all"],xGn=s=>["attract-kit-events",s??"all"],yGn=["attract-kit-templates"];function YV(){const{user:s}=ks(),t=ls(),n=pt({queryKey:[...X9,s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:o,error:c}=await V.from("attract_resource_kits").select("*").order("updated_at",{ascending:!1});if(c)throw c;return o??[]}}),r=Nt({mutationFn:async o=>{if(!s)throw new Error("not authenticated");const{data:c,error:d}=await V.from("attract_resource_kits").insert({user_id:s.id,title:o.title||"Untitled Kit",...o}).select("*").single();if(d)throw d;return c},onSuccess:()=>t.invalidateQueries({queryKey:X9})}),a=Nt({mutationFn:async({id:o,patch:c})=>{const{data:d,error:u}=await V.from("attract_resource_kits").update(c).eq("id",o).select("*").single();if(u)throw u;return d},onSuccess:()=>t.invalidateQueries({queryKey:X9})}),i=Nt({mutationFn:async o=>{const{error:c}=await V.from("attract_resource_kits").delete().eq("id",o);if(c)throw c},onSuccess:()=>t.invalidateQueries({queryKey:X9})}),l=Nt({mutationFn:async o=>{const{data:c,error:d}=await V.rpc("duplicate_attract_kit",{_kit_id:o});if(d)throw d;return c},onSuccess:()=>t.invalidateQueries({queryKey:X9})});return{kits:n.data??[],isLoading:n.isLoading,create:r,update:a,remove:i,duplicate:l}}function DWt(s){return pt({queryKey:["attract-kit",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await V.from("attract_resource_kits").select("*").eq("id",s).single();if(n)throw n;return t}})}function vGn(s){const t=ls(),n=pt({queryKey:aW(s??""),enabled:!!s,queryFn:async()=>{const{data:o,error:c}=await V.from("attract_resource_kit_items").select("*").eq("kit_id",s).order("sort_order");if(c)throw c;return o??[]}}),r=Nt({mutationFn:async o=>{var u;const{data:c,error:d}=await V.from("attract_resource_kit_items").insert({kit_id:s,type:"text",title:"New item",sort_order:((u=n.data)==null?void 0:u.length)??0,...o}).select("*").single();if(d)throw d;return c},onSuccess:()=>t.invalidateQueries({queryKey:aW(s??"")})}),a=Nt({mutationFn:async({id:o,patch:c})=>{const{error:d}=await V.from("attract_resource_kit_items").update(c).eq("id",o);if(d)throw d},onSuccess:()=>t.invalidateQueries({queryKey:aW(s??"")})}),i=Nt({mutationFn:async o=>{const{error:c}=await V.from("attract_resource_kit_items").delete().eq("id",o);if(c)throw c},onSuccess:()=>t.invalidateQueries({queryKey:aW(s??"")})}),l=Nt({mutationFn:async o=>{await Promise.all(o.map((c,d)=>V.from("attract_resource_kit_items").update({sort_order:d}).eq("id",c)))},onSuccess:()=>t.invalidateQueries({queryKey:aW(s??"")})});return{items:n.data??[],isLoading:n.isLoading,add:r,update:a,remove:i,reorder:l}}function OWt(s){const{user:t}=ks(),n=ls(),r=pt({queryKey:iW(s),enabled:!!t,queryFn:async()=>{let l=V.from("attract_kit_shares").select("*").order("created_at",{ascending:!1});s&&(l=l.eq("kit_id",s));const{data:o,error:c}=await l;if(c)throw c;return o??[]}}),a=Nt({mutationFn:async l=>{if(!t)throw new Error("not authenticated");const{data:o,error:c}=await V.from("attract_kit_shares").insert({owner_user_id:t.id,...l}).select("*").single();if(c)throw c;return o},onSuccess:l=>{var o;n.invalidateQueries({queryKey:iW(s)}),n.invalidateQueries({queryKey:iW()});try{(o=navigator.clipboard)==null||o.writeText(zWt(l.share_token)),ae.success("Share link created and copied")}catch{ae.success("Share link created")}},onError:l=>ae.error((l==null?void 0:l.message)||"Could not create share link")}),i=Nt({mutationFn:async l=>{const{error:o}=await V.from("attract_kit_shares").update({status:"revoked"}).eq("id",l);if(o)throw o},onSuccess:()=>{n.invalidateQueries({queryKey:iW(s)}),n.invalidateQueries({queryKey:iW()}),ae.success("Link revoked")},onError:l=>ae.error((l==null?void 0:l.message)||"Could not revoke link")});return{shares:r.data??[],isLoading:r.isLoading,create:a,revoke:i}}function FWt(s){return pt({queryKey:xGn(s),queryFn:async()=>{let t=V.from("attract_kit_events").select("*").order("created_at",{ascending:!1}).limit(500);s&&(t=t.eq("kit_id",s));const{data:n,error:r}=await t;if(r)throw r;return n??[]}})}function bGn(){return pt({queryKey:yGn,queryFn:async()=>{const{data:s,error:t}=await V.from("attract_kit_templates").select("*").eq("is_active",!0).order("sort_order");if(t)throw t;return s??[]}})}function _Gn(){const s=ls();return Nt({mutationFn:async t=>{const{data:n,error:r}=await V.rpc("clone_attract_kit_template",{_template_id:t});if(r)throw r;return n},onSuccess:()=>s.invalidateQueries({queryKey:X9})})}function zWt(s){return`${typeof window<"u"?window.location.origin:""}/attract-kit/${s}`}function Uwt(){const{kits:s}=YV(),{data:t=[]}=FWt(),{followUps:n}=QF(),r=k.useMemo(()=>{const l=o=>t.filter(c=>c.event_type===o).length;return{published:s.filter(o=>o.status==="published").length,drafts:s.filter(o=>o.status==="draft").length,views:l("page_view"),downloads:l("file_download"),cta:l("primary_cta_click"),questions:l("question_submitted")}},[s,t]),a=t.slice(0,8),i=n.filter(l=>!l.completed_at&&l.touch_type==="kit_engagement").slice(0,6);return e.jsxs("div",{className:"space-y-6",children:[e.jsx(Hm,{eyebrow:"Pillar 03 · Provide",title:"Give more value than any agent expected.",description:"Package the value you already share into beautiful, trackable kits. See exactly which value creates conversations.",actions:e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{variant:"outline",asChild:!0,className:"rounded-full",children:e.jsxs(nr,{to:"/attract/provide/kits/templates",children:[e.jsx(xb,{className:"h-4 w-4 mr-2"}),"Starter library"]})}),e.jsx($,{asChild:!0,className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",children:e.jsxs(nr,{to:"/attract/provide/kits/new",children:[e.jsx(nn,{className:"h-4 w-4 mr-2"}),"New kit"]})})]})}),e.jsx(we,{className:"p-6 md:p-8 rounded-2xl bg-gradient-to-br from-teal-50 via-violet-50 to-indigo-50 border-slate-200",children:e.jsxs("div",{className:"flex items-start gap-4 flex-wrap",children:[e.jsx("div",{className:"h-12 w-12 rounded-2xl bg-white grid place-items-center shadow-sm",children:e.jsx(z8,{className:"h-6 w-6 text-teal-600"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-[15px] font-semibold text-slate-900",children:"Resource Kits — the flagship of Provide"}),e.jsx("p",{className:"text-[13.5px] text-slate-700 mt-1 max-w-3xl",children:"Bundle 3–7 pieces of real value (scripts, checklists, videos, tools) into a beautiful shareable kit. Send a personalized link to an agent, then let engagement recommend the next relationship touch. No pressure. Just real value that compounds."}),e.jsxs("div",{className:"flex gap-2 mt-4",children:[e.jsx($,{asChild:!0,size:"sm",className:"bg-gradient-to-r from-violet-600 to-indigo-600",children:e.jsx(nr,{to:"/attract/provide/kits/new",children:"Start a kit"})}),e.jsx($,{variant:"outline",size:"sm",asChild:!0,children:e.jsx(nr,{to:"/attract/provide/kits/templates",children:"Browse 10 starter kits"})})]})]})]})}),e.jsx(we,{className:"p-6 rounded-2xl border-slate-200",children:e.jsxs("div",{className:"flex items-start gap-4 flex-wrap",children:[e.jsx("div",{className:"h-12 w-12 rounded-2xl bg-violet-50 grid place-items-center",children:e.jsx(kn,{className:"h-6 w-6 text-violet-600"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-[15px] font-semibold text-slate-900",children:"Masterclass Builder"}),e.jsx("p",{className:"text-[13.5px] text-slate-700 mt-1 max-w-3xl",children:"Turn what you already know into a 45-minute teaching moment. Build the curriculum, workbook, promotion drafts and run-of-show — then convert it into a Connect event or a Resource Kit in one click."}),e.jsx("div",{className:"flex gap-2 mt-4",children:e.jsx($,{asChild:!0,size:"sm",className:"bg-gradient-to-r from-violet-600 to-indigo-600",children:e.jsx(nr,{to:"/attract/provide/masterclasses",children:"Open Masterclass Builder"})})})]})]})}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-6 gap-3",children:[e.jsx(j9,{label:"Published",value:r.published}),e.jsx(j9,{label:"Drafts",value:r.drafts}),e.jsx(j9,{label:"Views",value:r.views,icon:ba}),e.jsx(j9,{label:"Downloads",value:r.downloads,icon:ji}),e.jsx(j9,{label:"CTA clicks",value:r.cta,icon:rh}),e.jsx(j9,{label:"Questions",value:r.questions,icon:Vu})]}),e.jsxs("div",{className:"grid grid-cols-1 xl:grid-cols-3 gap-6",children:[e.jsxs(we,{className:"p-5 rounded-2xl xl:col-span-2",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-violet-700 font-semibold",children:"Recent kit engagement"}),e.jsx("div",{className:"text-[12.5px] text-slate-500",children:"Live signals from agents opening your value."})]}),e.jsx($,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs(nr,{to:"/attract/provide/kits",children:["View kits ",e.jsx(xi,{className:"h-3.5 w-3.5 ml-1"})]})})]}),a.length===0?e.jsx("div",{className:"text-sm text-slate-500 py-8 text-center border border-dashed rounded-xl",children:"No engagement yet. Share a published kit to start seeing activity."}):e.jsx("div",{className:"space-y-2",children:a.map(l=>e.jsxs("div",{className:"flex items-center justify-between border-b py-2 text-[13px]",children:[e.jsx("div",{className:"capitalize",children:l.event_type.replace(/_/g," ")}),e.jsx("div",{className:"text-slate-500 text-[11.5px]",children:Zc(new Date(l.created_at),{addSuffix:!0})})]},l.id))})]}),e.jsxs(we,{className:"p-5 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-violet-700 font-semibold mb-2",children:"Recommended follow-ups"}),i.length===0?e.jsx("div",{className:"text-sm text-slate-500 py-6 text-center border border-dashed rounded-xl",children:"We'll surface follow-ups here as agents engage."}):e.jsx("div",{className:"space-y-2",children:i.map(l=>e.jsxs("div",{className:"border rounded-lg p-2.5 text-[12.5px]",children:[e.jsx("div",{className:"font-medium text-slate-900 line-clamp-2",children:l.title}),l.due_at&&e.jsxs("div",{className:"text-slate-500 text-[11px] mt-1",children:["Due ",Zc(new Date(l.due_at),{addSuffix:!0})]})]},l.id))})]})]}),e.jsxs(we,{className:"p-5 rounded-2xl",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-violet-700 font-semibold",children:"My kits"}),e.jsx($,{size:"sm",variant:"ghost",asChild:!0,children:e.jsxs(nr,{to:"/attract/provide/kits",children:["See all ",e.jsx(xi,{className:"h-3.5 w-3.5 ml-1"})]})})]}),s.length===0?e.jsxs("div",{className:"text-sm text-slate-500 py-8 text-center border border-dashed rounded-xl",children:["No kits yet. ",e.jsx(nr,{to:"/attract/provide/kits/templates",className:"text-violet-700 underline",children:"Start from a template"}),"."]}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-3",children:s.slice(0,6).map(l=>e.jsxs(nr,{to:`/attract/provide/kits/${l.id}/edit`,className:"block p-4 rounded-xl border hover:border-violet-300 hover:shadow-sm transition",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(qe,{variant:"outline",className:"capitalize",children:l.status}),l.pillar&&e.jsx(qe,{variant:"secondary",className:"capitalize",children:l.pillar})]}),e.jsx("div",{className:"font-semibold text-slate-900 line-clamp-2",children:l.title}),l.description&&e.jsx("div",{className:"text-[12.5px] text-slate-500 line-clamp-2 mt-1",children:l.description})]},l.id))})]}),e.jsx(JF,{})]})}function j9({label:s,value:t,icon:n}){return e.jsxs(we,{className:"p-4 rounded-2xl",children:[n&&e.jsx(n,{className:"h-4 w-4 text-violet-600"}),e.jsx("div",{className:"mt-1 text-[20px] font-semibold tabular-nums text-slate-900",children:t}),e.jsx("div",{className:"text-[11.5px] text-slate-500",children:s})]})}function qwt(){return e.jsx(fJe,{pillar:"04",title:"Connect",accent:"#9333ea",icon:B8,tagline:"Real relationships. On a rhythm. For years.",intro:"Connect is the pillar that makes the other three matter. It's showing up in the small, consistent ways real friendships require — birthdays, coffees, check-ins, celebrations.",stats:[{label:"Coffees This Q",value:14},{label:"Events Hosted",value:3},{label:"Birthdays Sent",value:22},{label:"On Cadence",value:"87%"}],tools:[{key:"coffee_meetings",icon:b_,title:"Coffee & Meetings",description:"The coffees to book this month, tracked as follow-ups in your Follow-Up Center.",to:"/attract/follow-up"},{key:"event_engine",icon:ha,title:"Attraction Events",description:"Design intimate gatherings — happy hours, dinners, mastermind lunches — with registration and check-in.",to:"/attract/events"},{key:"milestones",icon:ip,title:"Milestones & Celebrations",description:"Never miss a birthday, license anniversary, or business milestone for a prospective agent.",to:"/attract/connect/milestones"},{key:"checkins",icon:Vu,title:"Personal Check-Ins",description:"Relationship-first check-ins surfaced by your intelligence layer, ranked by signal.",to:"/attract/opportunities"},{key:"circles",icon:tb,title:"Agent Circles",description:"Small peer groups you host quarterly — built on the Connect Event Engine.",to:"/attract/events/new"}]})}const wGn=[{key:"coffee",label:"Coffee & Conversation",icon:b_,tone:"from-amber-500 to-orange-500",description:"A 1:1 or 3-person coffee where the goal is one real conversation."},{key:"roundtable",label:"Agent Roundtable",icon:tb,tone:"from-violet-500 to-indigo-500",description:"4–6 agents share what is actually working right now."},{key:"mastermind",label:"Mastermind",icon:kn,tone:"from-fuchsia-500 to-pink-500",description:"A quarterly small group solving each other’s biggest questions."},{key:"workshop",label:"Workshop / Webinar",icon:_h,tone:"from-sky-500 to-blue-500",description:"A live hands-on session that delivers one clear outcome."},{key:"dinner",label:"Dinner or Happy Hour",icon:dY,tone:"from-rose-500 to-red-500",description:"The relationship-first gathering. No agenda, just presence."},{key:"networking_plan",label:"Networking Game Plan",icon:B8,tone:"from-teal-500 to-emerald-500",description:"Not an event — a plan for the next 5 rooms you will walk into."}];function jGn(){const s=Jn(),{data:t=[]}=XTe(),{followUps:n}=QF(),{agents:r}=A0(),a=k.useMemo(()=>{const l=new Date,o=wu(l,7),c=t.filter(m=>m.status==="published"&&N_(new Date(m.starts_at),l)),d=t.filter(m=>m.status==="draft").length,u=t.reduce((m,p)=>m+(N_(new Date(p.created_at),wu(l,-7))?p.registration_count:0),0),h=n.filter(m=>!m.completed_at&&m.due_at&&Xw(new Date(m.due_at),o)&&(m.touch_type==="event_followup"||m.touch_type==="event_no_show")).length;return{upcoming:c,draftsNeedingInvites:d,regs:u,dueSoon:h}},[t,n]),i=a.upcoming[0];return e.jsxs("div",{className:"space-y-8",children:[e.jsxs("div",{className:"flex flex-col md:flex-row md:items-center md:justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-violet-600 font-semibold mb-2",children:"Pillar 04 · Connect"}),e.jsx("h1",{className:"text-3xl md:text-[34px] font-semibold tracking-tight text-slate-900",children:"Real events. Small rooms. Long relationships."}),e.jsx("p",{className:"text-slate-600 mt-1.5 max-w-2xl",children:"Build the room, invite personally, host with care, capture one honest note, and follow up within 48 hours."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs($,{variant:"outline",className:"rounded-full",onClick:()=>s("/attract/events"),children:[e.jsx(ha,{className:"h-4 w-4 mr-2"})," All events"]}),e.jsxs($,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600 hover:from-violet-700 hover:to-indigo-700",onClick:()=>s("/attract/events/new"),children:[e.jsx(nn,{className:"h-4 w-4 mr-2"})," Create an event"]})]})]}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[{label:"Upcoming events",value:a.upcoming.length,icon:ha,tone:"text-violet-700 bg-violet-100"},{label:"Drafts needing invites",value:a.draftsNeedingInvites,icon:Wr,tone:"text-amber-700 bg-amber-100"},{label:"Registrations this week",value:a.regs,icon:mc,tone:"text-emerald-700 bg-emerald-100"},{label:"48-hour follow-ups due",value:a.dueSoon,icon:op,tone:"text-rose-700 bg-rose-100"}].map(l=>e.jsxs(we,{className:"p-5 rounded-2xl border-slate-200 bg-white",children:[e.jsx("div",{className:`h-9 w-9 rounded-xl grid place-items-center ${l.tone}`,children:e.jsx(l.icon,{className:"h-4.5 w-4.5"})}),e.jsx("div",{className:"text-[26px] font-semibold tabular-nums mt-3",children:l.value}),e.jsx("div",{className:"text-[12.5px] text-slate-500 mt-0.5",children:l.label})]},l.label))}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-6",children:[e.jsxs(we,{className:"lg:col-span-2 p-6 rounded-2xl border-slate-200 bg-gradient-to-br from-slate-900 to-slate-800 text-white overflow-hidden relative",children:[e.jsx("div",{className:"text-[10.5px] uppercase tracking-widest text-white/60 mb-2",children:"Your next event"}),i?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-xl md:text-2xl font-semibold",children:i.title}),e.jsxs("div",{className:"text-white/70 mt-1",children:[Ys(new Date(i.starts_at),"EEE, MMM d · h:mm a")," · ",i.format.replace("_"," ")]}),e.jsxs("div",{className:"flex flex-wrap gap-2 mt-4",children:[e.jsxs(qe,{variant:"secondary",className:"bg-white/10 border-white/10 text-white",children:[i.registration_count," registered"]}),i.capacity&&e.jsxs(qe,{variant:"secondary",className:"bg-white/10 border-white/10 text-white",children:[Math.max(0,i.capacity-i.registration_count)," seats left"]})]}),e.jsxs("div",{className:"mt-5 flex gap-2 flex-wrap",children:[e.jsxs($,{size:"sm",className:"rounded-full bg-white text-slate-900 hover:bg-white/90",onClick:()=>s(`/attract/events/${i.id}`),children:["Open command center ",e.jsx(xi,{className:"h-3.5 w-3.5 ml-1"})]}),e.jsx($,{size:"sm",variant:"outline",className:"rounded-full bg-transparent text-white border-white/30 hover:bg-white/10",onClick:()=>s(`/attract/events/${i.id}/checkin`),children:"Mobile check-in"})]})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-xl font-semibold",children:"No upcoming events yet"}),e.jsx("div",{className:"text-white/70 mt-1",children:"Start with a small coffee. One conversation is enough."}),e.jsx($,{size:"sm",className:"mt-5 rounded-full bg-white text-slate-900 hover:bg-white/90",onClick:()=>s("/attract/events/new?type=coffee"),children:"Plan a coffee"})]})]}),e.jsxs(we,{className:"p-6 rounded-2xl border-amber-200 bg-amber-50",children:[e.jsx("div",{className:"text-[10.5px] uppercase tracking-widest text-amber-700 font-semibold mb-2",children:"Reminder"}),e.jsx("div",{className:"text-[15px] text-slate-900 leading-relaxed",children:"Build relationships first. Personalize every invitation and follow-up, and verify brokerage and compensation information before sharing."})]})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold",children:"Quick starts"}),e.jsx("div",{className:"text-lg font-semibold text-slate-900",children:"What kind of room do you want to build?"})]}),e.jsxs(nr,{to:"/attract/events/new",className:"text-[13px] text-violet-700 hover:underline flex items-center gap-1",children:["Start from scratch ",e.jsx(fi,{className:"h-3.5 w-3.5"})]})]}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4",children:wGn.map(l=>e.jsxs("button",{onClick:()=>s(`/attract/events/new?type=${l.key}`),className:"group text-left rounded-2xl border border-slate-200 bg-white p-5 hover:border-violet-300 hover:shadow-md transition",children:[e.jsx("div",{className:`h-10 w-10 rounded-xl grid place-items-center bg-gradient-to-br ${l.tone} text-white shadow-sm`,children:e.jsx(l.icon,{className:"h-5 w-5"})}),e.jsx("div",{className:"text-[15px] font-semibold text-slate-900 mt-3",children:l.label}),e.jsx("div",{className:"text-[13px] text-slate-600 mt-1 leading-snug",children:l.description}),e.jsxs("div",{className:"text-[12px] text-violet-700 mt-3 flex items-center gap-1 opacity-0 group-hover:opacity-100 transition",children:["Start planning ",e.jsx(xi,{className:"h-3 w-3"})]})]},l.key))})]}),e.jsxs(we,{className:"p-6 rounded-2xl border-slate-200 bg-white",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold",children:"Personal connection goals"}),e.jsx("div",{className:"text-lg font-semibold text-slate-900",children:"This week"})]}),e.jsx($,{variant:"outline",size:"sm",className:"rounded-full",onClick:()=>s("/attract/follow-up"),children:"Open Follow-Up Center"})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[{label:"Coffees booked",target:3,actual:a.upcoming.filter(l=>(l.event_type_key||l.event_type)==="coffee").length,icon:b_,tone:"text-amber-600 bg-amber-50"},{label:"Roundtables/masterminds",target:1,actual:a.upcoming.filter(l=>["roundtable","mastermind"].includes(l.event_type_key||l.event_type)).length,icon:kn,tone:"text-violet-600 bg-violet-50"},{label:"People in pipeline",target:r.length,actual:r.length,icon:tb,tone:"text-emerald-600 bg-emerald-50"}].map(l=>e.jsxs("div",{className:"rounded-xl border border-slate-100 p-4",children:[e.jsx("div",{className:`h-8 w-8 rounded-lg grid place-items-center ${l.tone}`,children:e.jsx(l.icon,{className:"h-4 w-4"})}),e.jsxs("div",{className:"text-[22px] font-semibold tabular-nums mt-2 leading-none",children:[l.actual,e.jsxs("span",{className:"text-slate-400 text-[15px] font-normal",children:[" / ",l.target]})]}),e.jsx("div",{className:"text-[12px] text-slate-500 mt-1",children:l.label})]},l.label))})]})]})}function NGn(){const s=Jn(),{data:t=[],isLoading:n}=XTe(),r=DHn(),a=IHn(),[i,l]=k.useState("all"),[o,c]=k.useState(""),d=k.useMemo(()=>t.filter(u=>!(i!=="all"&&u.status!==i||o&&!u.title.toLowerCase().includes(o.toLowerCase()))),[t,i,o]);return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col md:flex-row md:items-center md:justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-violet-600 font-semibold mb-2",children:"Connect · Events"}),e.jsx("h1",{className:"text-3xl font-semibold tracking-tight text-slate-900",children:"Events"}),e.jsx("p",{className:"text-slate-600 mt-1",children:"Every room you have built — drafted, live, and complete."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Yr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400"}),e.jsx(be,{placeholder:"Search events",className:"pl-9 rounded-full w-[240px] bg-white",value:o,onChange:u=>c(u.target.value)})]}),e.jsxs($,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600 hover:from-violet-700 hover:to-indigo-700",onClick:()=>s("/attract/events/new"),children:[e.jsx(nn,{className:"h-4 w-4 mr-2"})," New event"]})]})]}),e.jsxs(ya,{value:i,onValueChange:u=>l(u),children:[e.jsxs(va,{className:"rounded-full bg-white border border-slate-200",children:[e.jsxs(is,{value:"all",className:"rounded-full",children:["All (",t.length,")"]}),e.jsxs(is,{value:"draft",className:"rounded-full",children:["Drafts (",t.filter(u=>u.status==="draft").length,")"]}),e.jsxs(is,{value:"published",className:"rounded-full",children:["Published (",t.filter(u=>u.status==="published").length,")"]}),e.jsxs(is,{value:"completed",className:"rounded-full",children:["Completed (",t.filter(u=>u.status==="completed").length,")"]})]}),e.jsx(cs,{value:i,className:"mt-5",children:n?e.jsx(we,{className:"p-12 rounded-2xl text-center text-slate-500",children:"Loading events…"}):d.length===0?e.jsxs(we,{className:"p-12 rounded-2xl text-center border-dashed",children:[e.jsx(ha,{className:"h-8 w-8 text-slate-300 mx-auto"}),e.jsx("div",{className:"text-lg font-semibold text-slate-900 mt-3",children:"No events here yet"}),e.jsx("div",{className:"text-slate-500 mt-1",children:"Start with a small coffee or a mastermind — one conversation is enough."}),e.jsxs($,{className:"mt-4 rounded-full",onClick:()=>s("/attract/events/new"),children:[e.jsx(nn,{className:"h-4 w-4 mr-2"})," Create your first event"]})]}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-5",children:d.map(u=>e.jsxs(we,{className:"group rounded-2xl border-slate-200 bg-white overflow-hidden hover:shadow-md transition",children:[e.jsxs("div",{className:"h-32 bg-gradient-to-br from-violet-500 to-indigo-600 relative",children:[u.cover_image_url&&e.jsx("img",{src:u.cover_image_url,alt:"",className:"absolute inset-0 h-full w-full object-cover"}),e.jsxs("div",{className:"absolute top-3 left-3 flex gap-2",children:[e.jsx(qe,{className:u.status==="published"?"bg-emerald-500":u.status==="completed"?"bg-slate-500":u.status==="cancelled"?"bg-rose-500":"bg-amber-500",children:u.status}),u.related_pillar&&e.jsx(qe,{variant:"secondary",className:"bg-white/90 text-slate-800 capitalize",children:u.related_pillar})]})]}),e.jsxs("div",{className:"p-4",children:[e.jsxs("button",{onClick:()=>s(`/attract/events/${u.id}`),className:"text-left block w-full",children:[e.jsx("div",{className:"text-[15.5px] font-semibold text-slate-900 line-clamp-1",children:u.title}),e.jsx("div",{className:"text-[12.5px] text-slate-500 mt-0.5",children:Ys(new Date(u.starts_at),"EEE, MMM d · h:mm a")})]}),e.jsxs("div",{className:"flex items-center gap-3 text-[12px] text-slate-500 mt-3",children:[u.format==="virtual"?e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ia,{className:"h-3.5 w-3.5"})," Virtual"]}):u.format==="hybrid"?e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ia,{className:"h-3.5 w-3.5"})," Hybrid"]}):e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Si,{className:"h-3.5 w-3.5"})," ",u.location||"In person"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Xn,{className:"h-3.5 w-3.5"})," ",u.registration_count,u.capacity?` / ${u.capacity}`:""]})]}),e.jsxs("div",{className:"flex items-center justify-between mt-4",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsxs($,{variant:"ghost",size:"sm",className:"h-8 rounded-full text-slate-500",onClick:()=>r.mutate(u.id),children:[e.jsx(Da,{className:"h-3.5 w-3.5 mr-1"})," Duplicate"]}),u.status==="published"&&u.public_slug&&e.jsxs($,{variant:"ghost",size:"sm",className:"h-8 rounded-full text-slate-500",onClick:()=>{navigator.clipboard.writeText(QTe(u.public_slug)),ae.success("Registration link copied")},children:[e.jsx(Ir,{className:"h-3.5 w-3.5 mr-1"})," Link"]})]}),e.jsx($,{variant:"ghost",size:"sm",className:"h-8 rounded-full text-rose-600 hover:bg-rose-50",onClick:async()=>{await io("Delete this event?")&&a.mutate(u.id)},children:e.jsx(Un,{className:"h-3.5 w-3.5"})})]})]})]},u.id))})})]})]})}const kGn=[{key:"coffee",label:"Coffee & Conversation"},{key:"roundtable",label:"Roundtable"},{key:"mastermind",label:"Mastermind"},{key:"workshop",label:"Workshop / Webinar"},{key:"dinner",label:"Dinner / Happy Hour"},{key:"networking",label:"Networking Event"},{key:"custom",label:"Custom"}];function Vwt(){const{eventId:s}=oo(),t=Jn(),[n]=Jc(),r=n.get("type"),a=!!s,{data:i}=uJe(s),{data:l=[]}=NWt(),{kits:o}=YV(),c=kWt(),d=SWt(),[u,h]=k.useState({title:"",description:"",event_type_key:r||"coffee",intended_audience:"",related_pillar:"connect",starts_at:new Date(Date.now()+7*864e5).toISOString().slice(0,16),ends_at:"",timezone:"America/New_York",format:"in_person",location:"",address:"",virtual_url:"",capacity:"",waitlist_enabled:!0,host_name:"",cohosts:[],agenda:[],learning_outcomes:[],registration_questions:[],confirmation_message:"",resource_kit_id:null,kit_delivery_trigger:"after_attendance",followup_hours:48});k.useEffect(()=>{i&&h({...i,starts_at:i.starts_at?i.starts_at.slice(0,16):"",ends_at:i.ends_at?i.ends_at.slice(0,16):"",capacity:i.capacity??"",cohosts:i.cohosts||[],agenda:i.agenda||[],learning_outcomes:i.learning_outcomes||[],registration_questions:i.registration_questions||[]})},[i]);const m=v=>h(_=>({..._,...v})),p=k.useMemo(()=>l.slice(0,4),[l]),g=v=>{m({title:v.title,description:v.description,event_type_key:v.event_type_key,related_pillar:v.related_pillar,intended_audience:v.intended_audience,agenda:v.suggested_agenda||[],learning_outcomes:v.suggested_outcomes||[],registration_questions:v.suggested_questions||[],confirmation_message:v.suggested_confirmation}),ae.success(`Loaded "${v.title}"`)},x=async(v={})=>{const _={...u,starts_at:u.starts_at?new Date(u.starts_at).toISOString():new Date().toISOString(),ends_at:u.ends_at?new Date(u.ends_at).toISOString():null,capacity:u.capacity===""?null:Number(u.capacity),status:v.publish?"published":u.status||"draft"};if(a)await d.mutateAsync({id:s,patch:_}),ae.success(v.publish?"Published":"Saved");else{const j=await c.mutateAsync(_);ae.success(v.publish?"Event published":"Draft saved"),t(`/attract/events/${j.id}${v.publish?"":"/edit"}`,{replace:!0})}},y=i!=null&&i.public_slug?QTe(i.public_slug):null;return e.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs($,{variant:"ghost",size:"sm",className:"rounded-full",onClick:()=>t("/attract/events"),children:[e.jsx(Ia,{className:"h-4 w-4 mr-2"})," All events"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[y&&e.jsxs($,{variant:"outline",size:"sm",className:"rounded-full",onClick:()=>{navigator.clipboard.writeText(y),ae.success("Registration link copied")},children:[e.jsx(od,{className:"h-3.5 w-3.5 mr-2"})," Copy link"]}),e.jsxs($,{variant:"outline",size:"sm",className:"rounded-full",onClick:()=>x(),children:[e.jsx(Ml,{className:"h-4 w-4 mr-2"})," Save draft"]}),e.jsxs($,{size:"sm",className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>x({publish:!0}),children:[e.jsx(v0,{className:"h-4 w-4 mr-2"})," ",(i==null?void 0:i.status)==="published"?"Update published":"Publish"]})]})]}),!a&&p.length>0&&e.jsxs(we,{className:"p-5 rounded-2xl border-violet-200 bg-gradient-to-br from-violet-50 to-indigo-50",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(kn,{className:"h-4 w-4 text-violet-600"}),e.jsx("div",{className:"text-[13px] font-semibold text-slate-900",children:"Start from a premium template"})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-2",children:p.map(v=>e.jsxs("button",{onClick:()=>g(v),className:"text-left rounded-xl bg-white/70 border border-white p-3 hover:bg-white transition",children:[e.jsx("div",{className:"text-[13.5px] font-semibold text-slate-900",children:v.title}),e.jsx("div",{className:"text-[12px] text-slate-600 line-clamp-2 mt-0.5",children:v.description})]},v.id))})]}),e.jsxs(we,{className:"p-6 rounded-2xl border-slate-200 bg-white",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-1",children:"Step 1"}),e.jsx("div",{className:"text-lg font-semibold text-slate-900 mb-4",children:"Event basics"}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(re,{children:"Title"}),e.jsx(be,{value:u.title,onChange:v=>m({title:v.target.value}),placeholder:"Coffee & Systems Roundtable"})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Event type"}),e.jsxs(bs,{value:u.event_type_key,onValueChange:v=>m({event_type_key:v}),children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsx(vs,{children:kGn.map(v=>e.jsx(We,{value:v.key,children:v.label},v.key))})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Related pillar"}),e.jsxs(bs,{value:u.related_pillar||"connect",onValueChange:v=>m({related_pillar:v}),children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"produce",children:"Produce"}),e.jsx(We,{value:"influence",children:"Influence"}),e.jsx(We,{value:"provide",children:"Provide"}),e.jsx(We,{value:"connect",children:"Connect"})]})]})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(re,{children:"Intended audience"}),e.jsx(be,{value:u.intended_audience||"",onChange:v=>m({intended_audience:v.target.value}),placeholder:"Producing agents 1–5 years in"})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(re,{children:"Description"}),e.jsx(Ls,{rows:4,value:u.description||"",onChange:v=>m({description:v.target.value}),placeholder:"What is this event and why does it matter?"})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Starts at"}),e.jsx(be,{type:"datetime-local",value:u.starts_at||"",onChange:v=>m({starts_at:v.target.value})})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Ends at"}),e.jsx(be,{type:"datetime-local",value:u.ends_at||"",onChange:v=>m({ends_at:v.target.value})})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Time zone"}),e.jsxs(bs,{value:u.timezone||"America/New_York",onValueChange:v=>m({timezone:v}),children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsx(vs,{children:["America/New_York","America/Chicago","America/Denver","America/Los_Angeles","America/Phoenix"].map(v=>e.jsx(We,{value:v,children:v},v))})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Format"}),e.jsxs(bs,{value:u.format,onValueChange:v=>m({format:v}),children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"in_person",children:"In person"}),e.jsx(We,{value:"virtual",children:"Virtual"}),e.jsx(We,{value:"hybrid",children:"Hybrid"})]})]})]}),u.format!=="virtual"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsx(re,{children:"Venue / location name"}),e.jsx(be,{value:u.location||"",onChange:v=>m({location:v.target.value}),placeholder:"Rise Coffee — Downtown"})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Address"}),e.jsx(be,{value:u.address||"",onChange:v=>m({address:v.target.value}),placeholder:"123 Main St, City, ST"})]})]}),u.format!=="in_person"&&e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(re,{children:"Virtual meeting URL"}),e.jsx(be,{value:u.virtual_url||"",onChange:v=>m({virtual_url:v.target.value}),placeholder:"https://zoom.us/…"})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Capacity (optional)"}),e.jsx(be,{type:"number",value:u.capacity,onChange:v=>m({capacity:v.target.value}),placeholder:"No limit"})]}),e.jsxs("div",{className:"flex items-center gap-3 pt-6",children:[e.jsx(On,{checked:u.waitlist_enabled,onCheckedChange:v=>m({waitlist_enabled:v}),id:"wl"}),e.jsx(re,{htmlFor:"wl",className:"cursor-pointer",children:"Allow waitlist if full"})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Host name (as shown publicly)"}),e.jsx(be,{value:u.host_name||"",onChange:v=>m({host_name:v.target.value}),placeholder:"Jeremy from LevelUp"})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Cover image URL"}),e.jsx(be,{value:u.cover_image_url||"",onChange:v=>m({cover_image_url:v.target.value}),placeholder:"https://…"})]})]})]}),e.jsxs(we,{className:"p-6 rounded-2xl border-slate-200 bg-white",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-1",children:"Step 2"}),e.jsx("div",{className:"text-lg font-semibold text-slate-900 mb-4",children:"Experience & agenda"}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(re,{children:"Agenda"}),e.jsxs($,{size:"sm",variant:"ghost",className:"rounded-full",onClick:()=>m({agenda:[...u.agenda||[],{time:"",item:""}]}),children:[e.jsx(nn,{className:"h-3.5 w-3.5 mr-1"})," Add item"]})]}),e.jsxs("div",{className:"space-y-2",children:[(u.agenda||[]).map((v,_)=>e.jsxs("div",{className:"flex gap-2",children:[e.jsx(be,{className:"w-24",value:v.time||"",onChange:j=>{const C=[...u.agenda];C[_]={...C[_],time:j.target.value},m({agenda:C})},placeholder:"0:00"}),e.jsx(be,{value:v.item||"",onChange:j=>{const C=[...u.agenda];C[_]={...C[_],item:j.target.value},m({agenda:C})},placeholder:"What happens here"}),e.jsx($,{size:"icon",variant:"ghost",onClick:()=>m({agenda:u.agenda.filter((j,C)=>C!==_)}),children:e.jsx(mr,{className:"h-4 w-4"})})]},_)),(u.agenda||[]).length===0&&e.jsx("div",{className:"text-[12px] text-slate-400",children:"Add each moment of the event so attendees know what to expect."})]})]}),e.jsx(Pc,{}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(re,{children:"What attendees will receive"}),e.jsxs($,{size:"sm",variant:"ghost",className:"rounded-full",onClick:()=>m({learning_outcomes:[...u.learning_outcomes||[],""]}),children:[e.jsx(nn,{className:"h-3.5 w-3.5 mr-1"})," Add outcome"]})]}),e.jsx("div",{className:"space-y-2",children:(u.learning_outcomes||[]).map((v,_)=>e.jsxs("div",{className:"flex gap-2",children:[e.jsx(be,{value:v,onChange:j=>{const C=[...u.learning_outcomes];C[_]=j.target.value,m({learning_outcomes:C})},placeholder:"One clear, honest outcome"}),e.jsx($,{size:"icon",variant:"ghost",onClick:()=>m({learning_outcomes:u.learning_outcomes.filter((j,C)=>C!==_)}),children:e.jsx(mr,{className:"h-4 w-4"})})]},_))})]})]})]}),e.jsxs(we,{className:"p-6 rounded-2xl border-slate-200 bg-white",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-1",children:"Step 3"}),e.jsx("div",{className:"text-lg font-semibold text-slate-900 mb-4",children:"Registration page"}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(re,{children:"Registration questions"}),e.jsxs($,{size:"sm",variant:"ghost",className:"rounded-full",onClick:()=>m({registration_questions:[...u.registration_questions||[],{key:`q${(u.registration_questions||[]).length+1}`,label:"",type:"text"}]}),children:[e.jsx(nn,{className:"h-3.5 w-3.5 mr-1"})," Add question"]})]}),e.jsx("div",{className:"space-y-2",children:(u.registration_questions||[]).map((v,_)=>e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx(be,{className:"flex-1",value:v.label,onChange:j=>{const C=[...u.registration_questions];C[_]={...C[_],label:j.target.value,key:v.key||`q${_+1}`},m({registration_questions:C})},placeholder:"Question shown to registrants"}),e.jsxs(bs,{value:v.type,onValueChange:j=>{const C=[...u.registration_questions];C[_]={...C[_],type:j},m({registration_questions:C})},children:[e.jsx(ys,{className:"w-32",children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"text",children:"Short text"}),e.jsx(We,{value:"long",children:"Long text"})]})]}),e.jsx($,{size:"icon",variant:"ghost",onClick:()=>m({registration_questions:u.registration_questions.filter((j,C)=>C!==_)}),children:e.jsx(mr,{className:"h-4 w-4"})})]},_))})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Confirmation message (shown after registration)"}),e.jsx(Ls,{rows:3,value:u.confirmation_message||"",onChange:v=>m({confirmation_message:v.target.value}),placeholder:"You are in — come with one honest question."})]})]})]}),e.jsxs(we,{className:"p-6 rounded-2xl border-slate-200 bg-white",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-1",children:"Step 4"}),e.jsx("div",{className:"text-lg font-semibold text-slate-900 mb-4",children:"Resource Kit & 48-hour follow-up"}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Attach a Resource Kit"}),e.jsxs(bs,{value:u.resource_kit_id||"none",onValueChange:v=>m({resource_kit_id:v==="none"?null:v}),children:[e.jsx(ys,{children:e.jsx(_s,{placeholder:"None"})}),e.jsxs(vs,{children:[e.jsx(We,{value:"none",children:"None"}),(o||[]).map(v=>e.jsx(We,{value:v.id,children:v.title},v.id))]})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Deliver kit"}),e.jsxs(bs,{value:u.kit_delivery_trigger||"after_attendance",onValueChange:v=>m({kit_delivery_trigger:v}),children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"on_registration",children:"On registration"}),e.jsx(We,{value:"on_confirmation",children:"On confirmation"}),e.jsx(We,{value:"on_check_in",children:"At check-in"}),e.jsx(We,{value:"after_attendance",children:"After attendance"}),e.jsx(We,{value:"manual",children:"Only manually"})]})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Default follow-up window (hours)"}),e.jsx(be,{type:"number",value:u.followup_hours??48,onChange:v=>m({followup_hours:Number(v.target.value)})})]})]}),!u.resource_kit_id&&e.jsx("div",{className:"text-[12px] text-amber-700 bg-amber-50 border border-amber-200 rounded-lg p-3 mt-4",children:"Tip: attach a Resource Kit so attendees leave with something valuable — and so follow-ups have a natural reason."})]}),e.jsxs(we,{className:"p-6 rounded-2xl border-slate-200 bg-white",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-1",children:"Step 5"}),e.jsx("div",{className:"text-lg font-semibold text-slate-900 mb-3",children:"Review & publish"}),e.jsxs("div",{className:"text-[13px] text-slate-600 leading-relaxed",children:["Publishing generates a premium public registration page at"," ",e.jsxs("code",{className:"bg-slate-100 px-1.5 py-0.5 rounded text-slate-800",children:["/attract-event/",(i==null?void 0:i.public_slug)||""]})," ","and enables the personal invitation flow. You can unpublish or cancel at any time."]}),e.jsxs("div",{className:"flex flex-wrap gap-2 mt-4",children:[(!u.title||!u.starts_at)&&e.jsx(qe,{variant:"secondary",className:"bg-rose-50 text-rose-700 border-rose-200",children:"Add title and start time"}),(u.agenda||[]).length===0&&e.jsx(qe,{variant:"secondary",className:"bg-amber-50 text-amber-700 border-amber-200",children:"No agenda yet"}),(u.learning_outcomes||[]).length===0&&e.jsx(qe,{variant:"secondary",className:"bg-amber-50 text-amber-700 border-amber-200",children:"No stated outcomes"}),!u.resource_kit_id&&e.jsx(qe,{variant:"secondary",className:"bg-amber-50 text-amber-700 border-amber-200",children:"No Resource Kit attached"})]}),e.jsxs("div",{className:"flex justify-end gap-2 mt-5",children:[e.jsxs($,{variant:"outline",className:"rounded-full",onClick:()=>x(),children:[e.jsx(Ml,{className:"h-4 w-4 mr-2"})," Save draft"]}),e.jsxs($,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>x({publish:!0}),children:[e.jsx(v0,{className:"h-4 w-4 mr-2"})," Publish"]})]})]})]})}const Nke=s=>s?[s.first_name,s.last_name].filter(Boolean).join(" "):"";function SGn(){const{eventId:s}=oo(),t=Jn(),{data:n}=uJe(s),{data:r=[]}=jWt(s),{data:a=[]}=MHn(s),{data:i=[]}=PHn(s),{agents:l}=A0(),{data:o=[]}=NWt(),c=CWt(),d=LHn(),u=RHn(),h=SWt(),m=k.useMemo(()=>{const x=r.length,y=r.filter(R=>R.status==="registered"||R.status==="confirmed").length,v=r.filter(R=>R.status==="attended").length,_=r.filter(R=>R.status==="no_show").length,j=r.filter(R=>R.status==="waitlisted").length,C=y+v+_,A=C>0?Math.round(v/C*100):0,M=a.length>0?Math.round(a.filter(R=>R.viewed_at).length/a.length*100):0,I=r.filter(R=>R.followup_status==="done").length,P=v>0?Math.round(I/v*100):0;return{total:x,registered:y,attended:v,noShow:_,waitlist:j,attendRate:A,invView:M,followed:I,followedRate:P}},[r,a]);if(!n)return e.jsx("div",{className:"p-8 text-slate-500",children:"Loading…"});const p=n.public_slug?QTe(n.public_slug):null,g=()=>{const x=new Blob([AWt(n)],{type:"text/calendar"}),y=URL.createObjectURL(x),v=document.createElement("a");v.href=y,v.download=`${n.public_slug||"event"}.ics`,v.click(),URL.revokeObjectURL(y)};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-3",children:[e.jsxs($,{variant:"ghost",size:"sm",className:"rounded-full",onClick:()=>t("/attract/events"),children:[e.jsx(Ia,{className:"h-4 w-4 mr-2"})," All events"]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs($,{variant:"outline",size:"sm",className:"rounded-full",onClick:g,children:[e.jsx(ji,{className:"h-3.5 w-3.5 mr-2"})," ICS"]}),p&&e.jsxs($,{variant:"outline",size:"sm",className:"rounded-full",onClick:()=>{navigator.clipboard.writeText(p),ae.success("Link copied")},children:[e.jsx(Da,{className:"h-3.5 w-3.5 mr-2"})," Copy link"]}),p&&e.jsx($,{variant:"outline",size:"sm",className:"rounded-full",asChild:!0,children:e.jsxs("a",{href:p,target:"_blank",rel:"noreferrer",children:[e.jsx(Ir,{className:"h-3.5 w-3.5 mr-2"})," Preview page"]})}),e.jsxs($,{size:"sm",className:"rounded-full",onClick:()=>t(`/attract/events/${n.id}/checkin`),children:[e.jsx(Bx,{className:"h-3.5 w-3.5 mr-2"})," Check-in mode"]}),e.jsx($,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>t(`/attract/events/${n.id}/edit`),children:"Edit"})]})]}),e.jsx(we,{className:"p-6 rounded-2xl border-slate-200 bg-gradient-to-br from-slate-900 to-slate-800 text-white",children:e.jsxs("div",{className:"flex items-start justify-between gap-4 flex-wrap",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(qe,{className:n.status==="published"?"bg-emerald-500":n.status==="completed"?"bg-slate-500":n.status==="cancelled"?"bg-rose-500":"bg-amber-500",children:n.status}),n.related_pillar&&e.jsx(qe,{variant:"secondary",className:"bg-white/10 border-white/10 text-white capitalize",children:n.related_pillar}),n.event_type_key&&e.jsx(qe,{variant:"secondary",className:"bg-white/10 border-white/10 text-white capitalize",children:n.event_type_key.replace("_"," ")})]}),e.jsx("div",{className:"text-2xl md:text-3xl font-semibold",children:n.title}),e.jsxs("div",{className:"text-white/70 mt-1 flex items-center gap-4 flex-wrap",children:[e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(ha,{className:"h-4 w-4"})," ",Ys(new Date(n.starts_at),"EEE, MMM d · h:mm a")]}),n.format==="virtual"?e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(ia,{className:"h-4 w-4"})," Virtual"]}):e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Si,{className:"h-4 w-4"})," ",n.location||"In person"]}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Xn,{className:"h-4 w-4"})," ",n.registration_count," registered",n.capacity?` / ${n.capacity}`:""]})]})]}),n.status==="draft"&&e.jsx($,{className:"rounded-full bg-white text-slate-900 hover:bg-white/90",onClick:async()=>{await h.mutateAsync({id:n.id,patch:{status:"published"}}),ae.success("Published")},children:"Publish now"}),n.status==="published"&&new Date(n.starts_at){await h.mutateAsync({id:n.id,patch:{status:"completed"}}),ae.success("Marked completed")},children:"Mark completed"})]})}),e.jsxs(ya,{defaultValue:"overview",children:[e.jsxs(va,{className:"rounded-full bg-white border border-slate-200 flex-wrap h-auto",children:[e.jsx(is,{value:"overview",className:"rounded-full",children:"Overview"}),e.jsxs(is,{value:"invitations",className:"rounded-full",children:["Invitations (",a.length,")"]}),e.jsxs(is,{value:"registrations",className:"rounded-full",children:["Registrations (",r.length,")"]}),e.jsxs(is,{value:"notes",className:"rounded-full",children:["Notes (",i.length,")"]}),e.jsx(is,{value:"kit",className:"rounded-full",children:"Resource Kit"}),e.jsx(is,{value:"followup",className:"rounded-full",children:"48-hour follow-up"}),e.jsx(is,{value:"analytics",className:"rounded-full",children:"Analytics"})]}),e.jsxs(cs,{value:"overview",className:"mt-5",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4 mb-6",children:[e.jsx(qj,{icon:Xn,label:"Registered",value:m.registered+m.attended}),e.jsx(qj,{icon:ma,label:"Attended",value:m.attended}),e.jsx(qj,{icon:Ul,label:"Attendance rate",value:`${m.attendRate}%`}),e.jsx(qj,{icon:op,label:"Follow-up completion",value:`${m.followedRate}%`})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-6",children:[e.jsxs(we,{className:"p-5 rounded-2xl border-slate-200 bg-white lg:col-span-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-2",children:"Agenda"}),(n.agenda||[]).length===0?e.jsx("div",{className:"text-[13px] text-slate-400",children:"No agenda yet"}):e.jsx("ul",{className:"space-y-2",children:n.agenda.map((x,y)=>e.jsxs("li",{className:"flex gap-3 text-[14px]",children:[e.jsx("span",{className:"text-slate-500 tabular-nums w-16 shrink-0",children:x.time||""}),e.jsx("span",{className:"text-slate-800",children:x.item})]},y))}),(n.learning_outcomes||[]).length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mt-6 mb-2",children:"What attendees receive"}),e.jsx("ul",{className:"space-y-1.5",children:n.learning_outcomes.map((x,y)=>e.jsxs("li",{className:"text-[13.5px] text-slate-700 flex gap-2",children:[e.jsx(ma,{className:"h-4 w-4 text-emerald-600 shrink-0 mt-0.5"})," ",x]},y))})]})]}),e.jsxs(we,{className:"p-5 rounded-2xl border-slate-200 bg-white",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-2",children:"Share"}),p?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-[12px] text-slate-500 mb-1",children:"Registration page"}),e.jsx("div",{className:"text-[12.5px] font-mono bg-slate-50 border border-slate-200 rounded-lg p-2 break-all",children:p}),e.jsxs($,{size:"sm",variant:"outline",className:"rounded-full mt-2 w-full",onClick:()=>{navigator.clipboard.writeText(p),ae.success("Copied")},children:[e.jsx(Da,{className:"h-3.5 w-3.5 mr-2"})," Copy link"]})]}):e.jsx("div",{className:"text-[13px] text-slate-500",children:"Publish the event to generate a shareable registration link."}),n.check_in_token&&e.jsxs("div",{className:"mt-4",children:[e.jsx("div",{className:"text-[12px] text-slate-500 mb-1",children:"Check-in mode"}),e.jsxs($,{size:"sm",variant:"outline",className:"rounded-full w-full",onClick:()=>t(`/attract/events/${n.id}/checkin`),children:[e.jsx(Bx,{className:"h-3.5 w-3.5 mr-2"})," Open check-in"]})]})]})]})]}),e.jsx(cs,{value:"invitations",className:"mt-5",children:e.jsx(CGn,{eventId:n.id,eventSlug:n.public_slug,agents:l,invitations:a,templates:o,onCreate:u.mutate})}),e.jsx(cs,{value:"registrations",className:"mt-5",children:e.jsx(AGn,{eventId:n.id,attendees:r,onUpsert:c.mutate,checkInToken:n.check_in_token})}),e.jsx(cs,{value:"notes",className:"mt-5",children:e.jsx(EGn,{eventId:n.id,attendees:r,notes:i,onCreate:d.mutate})}),e.jsx(cs,{value:"kit",className:"mt-5",children:e.jsxs(we,{className:"p-6 rounded-2xl border-slate-200 bg-white",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-1",children:"Resource Kit"}),n.resource_kit_id?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-[15px] font-semibold text-slate-900",children:"A Resource Kit is attached to this event."}),e.jsxs("div",{className:"text-[13px] text-slate-600 mt-1",children:["Deliver trigger: ",e.jsx("span",{className:"font-medium capitalize",children:(n.kit_delivery_trigger||"after_attendance").replace(/_/g," ")})]}),e.jsx($,{variant:"outline",className:"rounded-full mt-4",onClick:()=>t(`/attract/provide/kits/${n.resource_kit_id}/analytics`),children:"Open kit analytics"})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-[15px] text-slate-700",children:"No kit attached yet. Attach one so attendees leave with something valuable."}),e.jsxs("div",{className:"flex gap-2 mt-4",children:[e.jsx($,{className:"rounded-full",onClick:()=>t(`/attract/events/${n.id}/edit`),children:"Attach a kit"}),e.jsx($,{variant:"outline",className:"rounded-full",onClick:()=>t("/attract/provide/kits/new"),children:"Create a new kit"})]})]})]})}),e.jsx(cs,{value:"followup",className:"mt-5",children:e.jsx(TGn,{eventId:n.id,attendees:r,onUpsert:c.mutate})}),e.jsxs(cs,{value:"analytics",className:"mt-5",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsx(qj,{icon:Wr,label:"Invitations sent",value:a.length}),e.jsx(qj,{icon:Ir,label:"Invitation view rate",value:`${m.invView}%`}),e.jsx(qj,{icon:Xn,label:"Registered",value:m.registered+m.attended}),e.jsx(qj,{icon:ma,label:"Attended",value:m.attended}),e.jsx(qj,{icon:Ul,label:"Attendance rate",value:`${m.attendRate}%`}),e.jsx(qj,{icon:op,label:"Follow-up complete (48h)",value:`${m.followedRate}%`}),e.jsx(qj,{icon:v3,label:"Notes captured",value:i.length}),e.jsx(qj,{icon:Pl,label:"Meetings requested",value:r.filter(x=>x.meeting_requested).length})]}),e.jsxs("div",{className:"text-[12px] text-slate-500 mt-3",children:["Where attribution is uncertain, we label movement as ",e.jsx("em",{children:"influenced"})," rather than caused."]})]})]})]})}function qj({icon:s,label:t,value:n}){return e.jsxs(we,{className:"p-4 rounded-2xl border-slate-200 bg-white",children:[e.jsxs("div",{className:"flex items-center gap-2 text-slate-500 text-[12px]",children:[e.jsx(s,{className:"h-3.5 w-3.5"})," ",t]}),e.jsx("div",{className:"text-[24px] font-semibold tabular-nums text-slate-900 mt-2",children:n})]})}function CGn({eventId:s,eventSlug:t,agents:n,invitations:r,templates:a,onCreate:i}){const[l,o]=k.useState(""),[c,d]=k.useState(""),[u,h]=k.useState(""),[m,p]=k.useState("email"),[g,x]=k.useState(""),y=a==null?void 0:a[0],v=()=>{if(!y)return;const j=m==="sms"?y.suggested_invitation_sms:m==="dm"?y.suggested_invitation_dm:y.suggested_invitation_email,C=t?`${window.location.origin}/attract-event/${t}`:"";x((j||"").replaceAll("{{first_name}}",(c||"friend").split(" ")[0]).replaceAll("{{link}}",C).replaceAll("{{date}}",""))},_=()=>{if(!c||m==="email"&&!u){ae.error("Add a name and email");return}const j=n.find(C=>C.id===l);i({event_id:s,agent_id:l||null,recipient_name:c||Nke(j),recipient_email:u||(j==null?void 0:j.email),channel:m,message_body:g,status:"sent"}),d(""),h(""),x(""),o(""),ae.success("Invitation logged")};return e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-6",children:[e.jsxs(we,{className:"p-5 rounded-2xl border-slate-200 bg-white lg:col-span-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-3",children:"Log a personal invitation"}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Attract agent (optional)"}),e.jsxs(bs,{value:l||"none",onValueChange:j=>{o(j==="none"?"":j);const C=n.find(A=>A.id===j);C&&(d(Nke(C)),h(C.email||""))},children:[e.jsx(ys,{children:e.jsx(_s,{placeholder:"Pick an agent"})}),e.jsxs(vs,{children:[e.jsx(We,{value:"none",children:"Guest (not in pipeline)"}),n.map(j=>e.jsx(We,{value:j.id,children:Nke(j)},j.id))]})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Channel"}),e.jsxs(bs,{value:m,onValueChange:p,children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"email",children:"Email"}),e.jsx(We,{value:"sms",children:"Text message"}),e.jsx(We,{value:"dm",children:"DM"}),e.jsx(We,{value:"call",children:"Phone call"}),e.jsx(We,{value:"in_person",children:"In person"})]})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Recipient name"}),e.jsx(be,{value:c,onChange:j=>d(j.target.value)})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Recipient email"}),e.jsx(be,{value:u,onChange:j=>h(j.target.value)})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx(re,{children:"Message"}),y&&e.jsxs($,{size:"sm",variant:"ghost",className:"rounded-full text-xs",onClick:v,children:[e.jsx(kn,{className:"h-3 w-3 mr-1"})," Draft from template"]})]}),e.jsx(Ls,{rows:5,value:g,onChange:j=>x(j.target.value),placeholder:"Write it like you would to a friend."})]})]}),e.jsxs("div",{className:"flex justify-between items-center mt-4",children:[e.jsx("div",{className:"text-[12px] text-slate-500",children:"Never auto-sent. This just logs that you invited them."}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs($,{variant:"outline",className:"rounded-full",onClick:()=>{g&&(navigator.clipboard.writeText(g),ae.success("Copied"))},children:[e.jsx(Da,{className:"h-3.5 w-3.5 mr-2"})," Copy message"]}),e.jsxs($,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:_,children:[e.jsx(Wr,{className:"h-3.5 w-3.5 mr-2"})," Log invitation"]})]})]})]}),e.jsxs(we,{className:"p-5 rounded-2xl border-slate-200 bg-white",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-3",children:"Recent invitations"}),r.length===0?e.jsx("div",{className:"text-[13px] text-slate-400",children:"None yet."}):e.jsx("div",{className:"space-y-2 max-h-[520px] overflow-auto",children:r.map(j=>e.jsxs("div",{className:"rounded-xl border border-slate-100 p-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{className:"text-[13px] font-medium text-slate-900",children:j.recipient_name||j.recipient_email}),e.jsx(qe,{variant:"secondary",className:"capitalize",children:j.status})]}),e.jsxs("div",{className:"text-[11.5px] text-slate-500 mt-0.5",children:["via ",j.channel," · ",Zc(new Date(j.sent_at))," ago",j.view_count>0?` · viewed ${j.view_count}×`:""]})]},j.id))})]})]})}function AGn({eventId:s,attendees:t,onUpsert:n,checkInToken:r}){const[a,i]=k.useState(""),[l,o]=k.useState(""),c=()=>{if(!a){ae.error("Add a name");return}n({event_id:s,guest_name:a,guest_email:l||null,status:"attended",checked_in_at:new Date().toISOString(),invitation_source:"walk_in"}),i(""),o(""),ae.success("Walk-in added")};return e.jsxs("div",{className:"space-y-5",children:[e.jsxs(we,{className:"p-4 rounded-2xl border-slate-200 bg-white",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-2",children:"Add a walk-in guest"}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-2",children:[e.jsx(be,{placeholder:"Name",value:a,onChange:d=>i(d.target.value)}),e.jsx(be,{placeholder:"Email (optional)",value:l,onChange:d=>o(d.target.value)}),e.jsxs($,{className:"rounded-full md:col-span-2",onClick:c,children:[e.jsx(Pl,{className:"h-4 w-4 mr-2"})," Add & check in"]})]})]}),e.jsx(we,{className:"rounded-2xl border-slate-200 bg-white overflow-hidden",children:t.length===0?e.jsx("div",{className:"p-8 text-center text-slate-400",children:"No registrations yet"}):e.jsx("div",{className:"divide-y divide-slate-100",children:t.map(d=>e.jsxs("div",{className:"p-4 flex items-center justify-between gap-3 flex-wrap",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-[14px] font-semibold text-slate-900",children:d.guest_name||Nke(d.attract_agents)||d.guest_email}),e.jsxs("div",{className:"text-[12px] text-slate-500",children:[d.guest_email," · ",d.invitation_source||"direct"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(qe,{variant:"secondary",className:"capitalize",children:d.status}),e.jsxs(bs,{value:d.status,onValueChange:u=>n({id:d.id,event_id:s,status:u,checked_in_at:u==="attended"&&!d.checked_in_at?new Date().toISOString():d.checked_in_at}),children:[e.jsx(ys,{className:"h-8 w-40 text-xs",children:e.jsx(_s,{})}),e.jsx(vs,{children:["invited","registered","confirmed","waitlisted","attended","no_show","cancelled"].map(u=>e.jsx(We,{value:u,className:"text-xs",children:u.replace("_"," ")},u))})]}),r&&d.personalized_token&&e.jsx($,{variant:"ghost",size:"sm",className:"rounded-full text-xs",onClick:()=>{navigator.clipboard.writeText(OHn(r,d.personalized_token)),ae.success("Check-in link copied")},children:e.jsx(Da,{className:"h-3.5 w-3.5"})})]})]},d.id))})})]})}function EGn({eventId:s,attendees:t,notes:n,onCreate:r}){const[a,i]=k.useState(""),[l,o]=k.useState(""),[c,d]=k.useState("warm"),[u,h]=k.useState(!1),[m,p]=k.useState(""),g=()=>{if(!l.trim()){ae.error("Add a note");return}const x=t.find(y=>y.id===a);r({event_id:s,attendee_id:a||null,agent_id:(x==null?void 0:x.agent_id)||null,note:l,temperature:c,recommended_next_action:m||null,wants_one_on_one:u}),o(""),i(""),p(""),h(!1),ae.success("Note captured")};return e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-6",children:[e.jsxs(we,{className:"p-5 rounded-2xl border-slate-200 bg-white lg:col-span-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-3",children:"Capture one honest note"}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Attendee (optional)"}),e.jsxs(bs,{value:a||"none",onValueChange:x=>i(x==="none"?"":x),children:[e.jsx(ys,{children:e.jsx(_s,{placeholder:"Anyone in the room"})}),e.jsxs(vs,{children:[e.jsx(We,{value:"none",children:"General note"}),t.map(x=>e.jsx(We,{value:x.id,children:x.guest_name||x.guest_email},x.id))]})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Note"}),e.jsx(Ls,{rows:4,value:l,onChange:x=>o(x.target.value),placeholder:"One real thing they said. One thing you noticed."})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-3",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Relationship temperature"}),e.jsxs(bs,{value:c,onValueChange:d,children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsx(vs,{children:["cold","warm","hot"].map(x=>e.jsx(We,{value:x,children:x},x))})]})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(re,{children:"Recommended next action"}),e.jsx(be,{value:m,onChange:x=>p(x.target.value),placeholder:"Text them the resource. Book a coffee."})]})]}),e.jsxs("label",{className:"flex items-center gap-2 text-[13px] text-slate-700",children:[e.jsx("input",{type:"checkbox",checked:u,onChange:x=>h(x.target.checked)}),"They should get a one-on-one conversation"]})]}),e.jsx("div",{className:"flex justify-end mt-4",children:e.jsxs($,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:g,children:[e.jsx(nn,{className:"h-4 w-4 mr-2"})," Save note"]})})]}),e.jsxs(we,{className:"p-5 rounded-2xl border-slate-200 bg-white",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-3",children:"Notes from this event"}),n.length===0?e.jsx("div",{className:"text-[13px] text-slate-400",children:"None yet."}):e.jsx("div",{className:"space-y-3 max-h-[520px] overflow-auto",children:n.map(x=>{const y=t.find(v=>v.id===x.attendee_id);return e.jsxs("div",{className:"rounded-xl border border-slate-100 p-3",children:[e.jsx("div",{className:"text-[13px] font-semibold text-slate-900",children:(y==null?void 0:y.guest_name)||"General"}),e.jsx("div",{className:"text-[13px] text-slate-700 mt-1 whitespace-pre-wrap",children:x.note}),e.jsxs("div",{className:"flex items-center gap-2 mt-2 flex-wrap text-[11px] text-slate-500",children:[x.temperature&&e.jsx(qe,{variant:"secondary",className:"capitalize",children:x.temperature}),x.wants_one_on_one&&e.jsx(qe,{className:"bg-emerald-500",children:"Wants 1:1"}),x.recommended_next_action&&e.jsxs("span",{children:["Next: ",x.recommended_next_action]})]})]},x.id)})})]})]})}function TGn({eventId:s,attendees:t,onUpsert:n}){const r=k.useMemo(()=>({attended_engaged:t.filter(l=>l.status==="attended"&&l.temperature==="hot"),attended_no_notes:t.filter(l=>l.status==="attended"),no_show:t.filter(l=>l.status==="no_show"),meeting_requested:t.filter(l=>l.meeting_requested),not_followed:t.filter(l=>l.status==="attended"&&l.followup_status!=="done")}),[t]),a=(l,o)=>n({id:l,event_id:s,followup_status:o}),i=({title:l,list:o,color:c})=>e.jsxs(we,{className:"p-5 rounded-2xl border-slate-200 bg-white",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx("div",{className:`h-2 w-2 rounded-full ${c}`}),e.jsx("div",{className:"text-[13px] font-semibold text-slate-900",children:l}),e.jsxs("div",{className:"text-[12px] text-slate-500",children:["(",o.length,")"]})]}),o.length===0?e.jsx("div",{className:"text-[12px] text-slate-400",children:"Nobody here."}):e.jsx("div",{className:"space-y-2",children:o.map(d=>e.jsxs("div",{className:"flex items-center justify-between gap-2 rounded-xl border border-slate-100 p-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[13px] font-semibold text-slate-900",children:d.guest_name||d.guest_email}),e.jsxs("div",{className:"text-[11.5px] text-slate-500",children:[d.status," · followup: ",d.followup_status||"pending"]})]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx($,{size:"sm",variant:"ghost",className:"rounded-full h-8",onClick:()=>a(d.id,"in_progress"),children:"In progress"}),e.jsx($,{size:"sm",className:"rounded-full h-8 bg-emerald-600 hover:bg-emerald-700",onClick:()=>a(d.id,"done"),children:e.jsx(ma,{className:"h-3 w-3"})})]})]},d.id))})]});return e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsx(i,{title:"Attended and engaged",list:r.attended_engaged,color:"bg-emerald-500"}),e.jsx(i,{title:"Attended (no notes yet)",list:r.attended_no_notes,color:"bg-violet-500"}),e.jsx(i,{title:"Registered but no-show",list:r.no_show,color:"bg-amber-500"}),e.jsx(i,{title:"Meeting requested",list:r.meeting_requested,color:"bg-pink-500"}),e.jsx(i,{title:"Not yet followed up",list:r.not_followed,color:"bg-rose-500"})]})}var ZV={},MGn=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then},BWt={},jj={};let pJe;const PGn=[0,26,44,70,100,134,172,196,242,292,346,404,466,532,581,655,733,815,901,991,1085,1156,1258,1364,1474,1588,1706,1828,1921,2051,2185,2323,2465,2611,2761,2876,3034,3196,3362,3532,3706];jj.getSymbolSize=function(t){if(!t)throw new Error('"version" cannot be null or undefined');if(t<1||t>40)throw new Error('"version" should be in range from 1 to 40');return t*4+17};jj.getSymbolTotalCodewords=function(t){return PGn[t]};jj.getBCHDigit=function(s){let t=0;for(;s!==0;)t++,s>>>=1;return t};jj.setToSJISFunction=function(t){if(typeof t!="function")throw new Error('"toSJISFunc" is not a valid function.');pJe=t};jj.isKanjiModeEnabled=function(){return typeof pJe<"u"};jj.toSJIS=function(t){return pJe(t)};var eMe={};(function(s){s.L={bit:1},s.M={bit:0},s.Q={bit:3},s.H={bit:2};function t(n){if(typeof n!="string")throw new Error("Param is not a string");switch(n.toLowerCase()){case"l":case"low":return s.L;case"m":case"medium":return s.M;case"q":case"quartile":return s.Q;case"h":case"high":return s.H;default:throw new Error("Unknown EC Level: "+n)}}s.isValid=function(r){return r&&typeof r.bit<"u"&&r.bit>=0&&r.bit<4},s.from=function(r,a){if(s.isValid(r))return r;try{return t(r)}catch{return a}}})(eMe);function $Wt(){this.buffer=[],this.length=0}$Wt.prototype={get:function(s){const t=Math.floor(s/8);return(this.buffer[t]>>>7-s%8&1)===1},put:function(s,t){for(let n=0;n>>t-n-1&1)===1)},getLengthInBits:function(){return this.length},putBit:function(s){const t=Math.floor(this.length/8);this.buffer.length<=t&&this.buffer.push(0),s&&(this.buffer[t]|=128>>>this.length%8),this.length++}};var IGn=$Wt;function kte(s){if(!s||s<1)throw new Error("BitMatrix size must be defined and greater than 0");this.size=s,this.data=new Uint8Array(s*s),this.reservedBit=new Uint8Array(s*s)}kte.prototype.set=function(s,t,n,r){const a=s*this.size+t;this.data[a]=n,r&&(this.reservedBit[a]=!0)};kte.prototype.get=function(s,t){return this.data[s*this.size+t]};kte.prototype.xor=function(s,t,n){this.data[s*this.size+t]^=n};kte.prototype.isReserved=function(s,t){return this.reservedBit[s*this.size+t]};var LGn=kte,UWt={};(function(s){const t=jj.getSymbolSize;s.getRowColCoords=function(r){if(r===1)return[];const a=Math.floor(r/7)+2,i=t(r),l=i===145?26:Math.ceil((i-13)/(2*a-2))*2,o=[i-7];for(let c=1;c=0&&a<=7},s.from=function(a){return s.isValid(a)?parseInt(a,10):void 0},s.getPenaltyN1=function(a){const i=a.size;let l=0,o=0,c=0,d=null,u=null;for(let h=0;h=5&&(l+=t.N1+(o-5)),d=p,o=1),p=a.get(m,h),p===u?c++:(c>=5&&(l+=t.N1+(c-5)),u=p,c=1)}o>=5&&(l+=t.N1+(o-5)),c>=5&&(l+=t.N1+(c-5))}return l},s.getPenaltyN2=function(a){const i=a.size;let l=0;for(let o=0;o=10&&(o===1488||o===93)&&l++,c=c<<1&2047|a.get(u,d),u>=10&&(c===1488||c===93)&&l++}return l*t.N3},s.getPenaltyN4=function(a){let i=0;const l=a.data.length;for(let c=0;c=0;){const l=i[0];for(let c=0;c0){const i=new Uint8Array(this.degree);return i.set(r,a),i}return r};var DGn=gJe,WWt={},S6={},xJe={};xJe.isValid=function(t){return!isNaN(t)&&t>=1&&t<=40};var p4={};const KWt="[0-9]+",OGn="[A-Z $%*+\\-./:]+";let SQ="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";SQ=SQ.replace(/u/g,"\\u");const FGn="(?:(?![A-Z0-9 $%*+\\-./:]|"+SQ+`)(?:.|[\r ]))+`;p4.KANJI=new RegExp(SQ,"g");p4.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g");p4.BYTE=new RegExp(FGn,"g");p4.NUMERIC=new RegExp(KWt,"g");p4.ALPHANUMERIC=new RegExp(OGn,"g");const zGn=new RegExp("^"+SQ+"$"),BGn=new RegExp("^"+KWt+"$"),$Gn=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");p4.testKanji=function(t){return zGn.test(t)};p4.testNumeric=function(t){return BGn.test(t)};p4.testAlphanumeric=function(t){return $Gn.test(t)};(function(s){const t=xJe,n=p4;s.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]},s.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]},s.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]},s.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]},s.MIXED={bit:-1},s.getCharCountIndicator=function(i,l){if(!i.ccBits)throw new Error("Invalid mode: "+i);if(!t.isValid(l))throw new Error("Invalid version: "+l);return l>=1&&l<10?i.ccBits[0]:l<27?i.ccBits[1]:i.ccBits[2]},s.getBestModeForData=function(i){return n.testNumeric(i)?s.NUMERIC:n.testAlphanumeric(i)?s.ALPHANUMERIC:n.testKanji(i)?s.KANJI:s.BYTE},s.toString=function(i){if(i&&i.id)return i.id;throw new Error("Invalid mode")},s.isValid=function(i){return i&&i.bit&&i.ccBits};function r(a){if(typeof a!="string")throw new Error("Param is not a string");switch(a.toLowerCase()){case"numeric":return s.NUMERIC;case"alphanumeric":return s.ALPHANUMERIC;case"kanji":return s.KANJI;case"byte":return s.BYTE;default:throw new Error("Unknown mode: "+a)}}s.from=function(i,l){if(s.isValid(i))return i;try{return r(i)}catch{return l}}})(S6);(function(s){const t=jj,n=tMe,r=eMe,a=S6,i=xJe,l=7973,o=t.getBCHDigit(l);function c(m,p,g){for(let x=1;x<=40;x++)if(p<=s.getCapacity(x,g,m))return x}function d(m,p){return a.getCharCountIndicator(m,p)+4}function u(m,p){let g=0;return m.forEach(function(x){const y=d(x.mode,p);g+=y+x.getBitsLength()}),g}function h(m,p){for(let g=1;g<=40;g++)if(u(m,g)<=s.getCapacity(g,p,a.MIXED))return g}s.from=function(p,g){return i.isValid(p)?parseInt(p,10):g},s.getCapacity=function(p,g,x){if(!i.isValid(p))throw new Error("Invalid QR Code version");typeof x>"u"&&(x=a.BYTE);const y=t.getSymbolTotalCodewords(p),v=n.getTotalCodewordsCount(p,g),_=(y-v)*8;if(x===a.MIXED)return _;const j=_-d(x,p);switch(x){case a.NUMERIC:return Math.floor(j/10*3);case a.ALPHANUMERIC:return Math.floor(j/11*2);case a.KANJI:return Math.floor(j/13);case a.BYTE:default:return Math.floor(j/8)}},s.getBestVersionForData=function(p,g){let x;const y=r.from(g,r.M);if(Array.isArray(p)){if(p.length>1)return h(p,y);if(p.length===0)return 1;x=p[0]}else x=p;return c(x.mode,x.getLength(),y)},s.getEncodedBits=function(p){if(!i.isValid(p)||p<7)throw new Error("Invalid QR Code version");let g=p<<12;for(;t.getBCHDigit(g)-o>=0;)g^=l<=0;)a^=ZWt<0&&(r=this.data.substr(n),a=parseInt(r,10),t.put(a,i*3+1))};var VGn=wq;const HGn=S6,q8e=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"," ","$","%","*","+","-",".","/",":"];function jq(s){this.mode=HGn.ALPHANUMERIC,this.data=s}jq.getBitsLength=function(t){return 11*Math.floor(t/2)+6*(t%2)};jq.prototype.getLength=function(){return this.data.length};jq.prototype.getBitsLength=function(){return jq.getBitsLength(this.data.length)};jq.prototype.write=function(t){let n;for(n=0;n+2<=this.data.length;n+=2){let r=q8e.indexOf(this.data[n])*45;r+=q8e.indexOf(this.data[n+1]),t.put(r,11)}this.data.length%2&&t.put(q8e.indexOf(this.data[n]),6)};var GGn=jq;const WGn=S6;function Nq(s){this.mode=WGn.BYTE,typeof s=="string"?this.data=new TextEncoder().encode(s):this.data=new Uint8Array(s)}Nq.getBitsLength=function(t){return t*8};Nq.prototype.getLength=function(){return this.data.length};Nq.prototype.getBitsLength=function(){return Nq.getBitsLength(this.data.length)};Nq.prototype.write=function(s){for(let t=0,n=this.data.length;t=33088&&n<=40956)n-=33088;else if(n>=57408&&n<=60351)n-=49472;else throw new Error("Invalid SJIS character: "+this.data[t]+` Make sure your charset is UTF-8`);n=(n>>>8&255)*192+(n&255),s.put(n,13)}};var XGn=kq,QWt={exports:{}};(function(s){var t={single_source_shortest_paths:function(n,r,a){var i={},l={};l[r]=0;var o=t.PriorityQueue.make();o.push(r,0);for(var c,d,u,h,m,p,g,x,y;!o.empty();){c=o.pop(),d=c.value,h=c.cost,m=n[d]||{};for(u in m)m.hasOwnProperty(u)&&(p=m[u],g=h+p,x=l[u],y=typeof l[u]>"u",(y||x>g)&&(l[u]=g,o.push(u,g),i[u]=d))}if(typeof a<"u"&&typeof l[a]>"u"){var v=["Could not find a path from ",r," to ",a,"."].join("");throw new Error(v)}return i},extract_shortest_path_from_predecessor_list:function(n,r){for(var a=[],i=r;i;)a.push(i),n[i],i=n[i];return a.reverse(),a},find_path:function(n,r,a){var i=t.single_source_shortest_paths(n,r,a);return t.extract_shortest_path_from_predecessor_list(i,a)},PriorityQueue:{make:function(n){var r=t.PriorityQueue,a={},i;n=n||{};for(i in r)r.hasOwnProperty(i)&&(a[i]=r[i]);return a.queue=[],a.sorter=n.sorter||r.default_sorter,a},default_sorter:function(n,r){return n.cost-r.cost},push:function(n,r){var a={value:n,cost:r};this.queue.push(a),this.queue.sort(this.sorter)},pop:function(){return this.queue.shift()},empty:function(){return this.queue.length===0}}};s.exports=t})(QWt);var QGn=QWt.exports;(function(s){const t=S6,n=VGn,r=GGn,a=KGn,i=XGn,l=p4,o=jj,c=QGn;function d(v){return unescape(encodeURIComponent(v)).length}function u(v,_,j){const C=[];let A;for(;(A=v.exec(j))!==null;)C.push({data:A[0],index:A.index,mode:_,length:A[0].length});return C}function h(v){const _=u(l.NUMERIC,t.NUMERIC,v),j=u(l.ALPHANUMERIC,t.ALPHANUMERIC,v);let C,A;return o.isKanjiModeEnabled()?(C=u(l.BYTE,t.BYTE,v),A=u(l.KANJI,t.KANJI,v)):(C=u(l.BYTE_KANJI,t.BYTE,v),A=[]),_.concat(j,C,A).sort(function(I,P){return I.index-P.index}).map(function(I){return{data:I.data,mode:I.mode,length:I.length}})}function m(v,_){switch(_){case t.NUMERIC:return n.getBitsLength(v);case t.ALPHANUMERIC:return r.getBitsLength(v);case t.KANJI:return i.getBitsLength(v);case t.BYTE:return a.getBitsLength(v)}}function p(v){return v.reduce(function(_,j){const C=_.length-1>=0?_[_.length-1]:null;return C&&C.mode===j.mode?(_[_.length-1].data+=j.data,_):(_.push(j),_)},[])}function g(v){const _=[];for(let j=0;j=0&&o<=6&&(c===0||c===6)||c>=0&&c<=6&&(o===0||o===6)||o>=2&&o<=4&&c>=2&&c<=4?s.set(i+o,l+c,!0,!0):s.set(i+o,l+c,!1,!0))}}function oWn(s){const t=s.size;for(let n=8;n>o&1)===1,s.set(a,i,l,!0),s.set(i,a,l,!0)}function G8e(s,t,n){const r=s.size,a=rWn.getEncodedBits(t,n);let i,l;for(i=0;i<15;i++)l=(a>>i&1)===1,i<6?s.set(i,8,l,!0):i<8?s.set(i+1,8,l,!0):s.set(r-15+i,8,l,!0),i<8?s.set(8,r-i-1,l,!0):i<9?s.set(8,15-i-1+1,l,!0):s.set(8,15-i-1,l,!0);s.set(r-8,8,1,!0)}function dWn(s,t){const n=s.size;let r=-1,a=n-1,i=7,l=0;for(let o=n-1;o>0;o-=2)for(o===6&&o--;;){for(let c=0;c<2;c++)if(!s.isReserved(a,o-c)){let d=!1;l>>i&1)===1),s.set(a,o-c,d),i--,i===-1&&(l++,i=7)}if(a+=r,a<0||n<=a){a-=r,r=-r;break}}}function uWn(s,t,n){const r=new JGn;n.forEach(function(c){r.put(c.mode.bit,4),r.put(c.getLength(),aWn.getCharCountIndicator(c.mode,s)),c.write(r)});const a=nMe.getSymbolTotalCodewords(s),i=Lqe.getTotalCodewordsCount(s,t),l=(a-i)*8;for(r.getLengthInBits()+4<=l&&r.put(0,4);r.getLengthInBits()%8!==0;)r.putBit(0);const o=(l-r.getLengthInBits())/8;for(let c=0;c=7&&cWn(c,t),dWn(c,l),isNaN(r)&&(r=Iqe.getBestMask(c,G8e.bind(null,c,n))),Iqe.applyMask(r,c),G8e(c,n,r),{modules:c,version:t,errorCorrectionLevel:n,maskPattern:r,segments:a}}BWt.create=function(t,n){if(typeof t>"u"||t==="")throw new Error("No input text");let r=V8e.M,a,i;return typeof n<"u"&&(r=V8e.from(n.errorCorrectionLevel,V8e.M),a=yCe.from(n.version),i=Iqe.from(n.maskPattern),n.toSJISFunc&&nMe.setToSJISFunction(n.toSJISFunc)),mWn(t,a,r,i)};var JWt={},yJe={};(function(s){function t(n){if(typeof n=="number"&&(n=n.toString()),typeof n!="string")throw new Error("Color should be defined as hex string");let r=n.slice().replace("#","").split("");if(r.length<3||r.length===5||r.length>8)throw new Error("Invalid hex color: "+n);(r.length===3||r.length===4)&&(r=Array.prototype.concat.apply([],r.map(function(i){return[i,i]}))),r.length===6&&r.push("F","F");const a=parseInt(r.join(""),16);return{r:a>>24&255,g:a>>16&255,b:a>>8&255,a:a&255,hex:"#"+r.slice(0,6).join("")}}s.getOptions=function(r){r||(r={}),r.color||(r.color={});const a=typeof r.margin>"u"||r.margin===null||r.margin<0?4:r.margin,i=r.width&&r.width>=21?r.width:void 0,l=r.scale||4;return{width:i,scale:i?4:l,margin:a,color:{dark:t(r.color.dark||"#000000ff"),light:t(r.color.light||"#ffffffff")},type:r.type,rendererOpts:r.rendererOpts||{}}},s.getScale=function(r,a){return a.width&&a.width>=r+a.margin*2?a.width/(r+a.margin*2):a.scale},s.getImageWidth=function(r,a){const i=s.getScale(r,a);return Math.floor((r+a.margin*2)*i)},s.qrToImageData=function(r,a,i){const l=a.modules.size,o=a.modules.data,c=s.getScale(l,i),d=Math.floor((l+i.margin*2)*c),u=i.margin*c,h=[i.color.light,i.color.dark];for(let m=0;m=u&&p>=u&&m"u"&&(!l||!l.getContext)&&(c=l,l=void 0),l||(d=r()),c=t.getOptions(c);const u=t.getImageWidth(i.modules.size,c),h=d.getContext("2d"),m=h.createImageData(u,u);return t.qrToImageData(m.data,i,c),n(h,d,u),h.putImageData(m,0,0),d},s.renderToDataURL=function(i,l,o){let c=o;typeof c>"u"&&(!l||!l.getContext)&&(c=l,l=void 0),c||(c={});const d=s.render(i,l,c),u=c.type||"image/png",h=c.rendererOpts||{};return d.toDataURL(u,h.quality)}})(JWt);var eKt={};const fWn=yJe;function Wwt(s,t){const n=s.a/255,r=t+'="'+s.hex+'"';return n<1?r+" "+t+'-opacity="'+n.toFixed(2).slice(1)+'"':r}function W8e(s,t,n){let r=s+t;return typeof n<"u"&&(r+=" "+n),r}function pWn(s,t,n){let r="",a=0,i=!1,l=0;for(let o=0;o0&&c>0&&s[o-1]||(r+=i?W8e("M",c+n,.5+d+n):W8e("m",a,0),a=0,i=!1),c+1':"",d="',u='viewBox="0 0 '+o+" "+o+'"',m=''+c+d+` `;return typeof r=="function"&&r(null,m),m};const gWn=MGn,Rqe=BWt,tKt=JWt,xWn=eKt;function vJe(s,t,n,r,a){const i=[].slice.call(arguments,1),l=i.length,o=typeof i[l-1]=="function";if(!o&&!gWn())throw new Error("Callback required as last argument");if(o){if(l<2)throw new Error("Too few arguments provided");l===2?(a=n,n=t,t=r=void 0):l===3&&(t.getContext&&typeof a>"u"?(a=r,r=void 0):(a=r,r=n,n=t,t=void 0))}else{if(l<1)throw new Error("Too few arguments provided");return l===1?(n=t,t=r=void 0):l===2&&!t.getContext&&(r=n,n=t,t=void 0),new Promise(function(c,d){try{const u=Rqe.create(n,r);c(s(u,t,r))}catch(u){d(u)}})}try{const c=Rqe.create(n,r);a(null,s(c,t,r))}catch(c){a(c)}}ZV.create=Rqe.create;ZV.toCanvas=vJe.bind(null,tKt.render);ZV.toDataURL=vJe.bind(null,tKt.renderToDataURL);ZV.toString=vJe.bind(null,function(s,t,n){return xWn.render(s,n)});function yWn(){const{eventId:s}=oo(),t=Jn(),{data:n}=uJe(s),{data:r=[]}=jWt(s),a=CWt(),[i,l]=k.useState(""),[o,c]=k.useState(""),[d,u]=k.useState(""),[h,m]=k.useState(""),p=n!=null&&n.public_slug?QTe(n.public_slug):"";k.useEffect(()=>{p&&ZV.toDataURL(p,{width:320,margin:1}).then(m).catch(()=>{})},[p]);const g=k.useMemo(()=>i?r.filter(v=>(v.guest_name||"").toLowerCase().includes(i.toLowerCase())||(v.guest_email||"").toLowerCase().includes(i.toLowerCase())):r,[r,i]),x=v=>{a.mutate({id:v.id,event_id:s,status:"attended",checked_in_at:new Date().toISOString()}),ae.success(`${v.guest_name||"Guest"} checked in`)},y=()=>{o&&(a.mutate({event_id:s,guest_name:o,guest_email:d||null,status:"attended",checked_in_at:new Date().toISOString(),invitation_source:"walk_in"}),c(""),u(""),ae.success("Walk-in checked in"))};return n?e.jsx("div",{className:"min-h-screen bg-slate-50",children:e.jsxs("div",{className:"max-w-2xl mx-auto p-4 md:p-6",children:[e.jsxs($,{variant:"ghost",size:"sm",className:"rounded-full mb-3",onClick:()=>t(`/attract/events/${s}`),children:[e.jsx(Ia,{className:"h-4 w-4 mr-2"})," Back to event"]}),e.jsxs(we,{className:"p-5 rounded-2xl bg-gradient-to-br from-slate-900 to-slate-800 text-white border-0",children:[e.jsx("div",{className:"text-[10.5px] uppercase tracking-widest text-white/60",children:"Check-in mode"}),e.jsx("div",{className:"text-xl font-semibold mt-1",children:n.title}),e.jsxs("div",{className:"text-white/70 text-[13px] mt-0.5",children:[n.registration_count," registered · ",n.attendance_count," checked in"]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4 mt-4",children:[e.jsxs(we,{className:"p-5 rounded-2xl border-slate-200 bg-white",children:[e.jsxs("div",{className:"flex items-center gap-2 text-[13px] font-semibold text-slate-900",children:[e.jsx(Bx,{className:"h-4 w-4"})," Registration QR"]}),h?e.jsx("img",{src:h,alt:"QR code",className:"mx-auto mt-3 h-56 w-56"}):e.jsx("div",{className:"text-[12px] text-slate-400 mt-3",children:"Publish this event to generate a QR code."}),p&&e.jsx("div",{className:"text-[11px] font-mono text-center text-slate-500 mt-2 break-all",children:p})]}),e.jsxs(we,{className:"p-5 rounded-2xl border-slate-200 bg-white",children:[e.jsx("div",{className:"text-[13px] font-semibold text-slate-900 mb-3",children:"Add walk-in"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(be,{placeholder:"Name",value:o,onChange:v=>c(v.target.value)}),e.jsx(be,{placeholder:"Email (optional)",value:d,onChange:v=>u(v.target.value)}),e.jsxs($,{className:"w-full rounded-full",onClick:y,children:[e.jsx(Pl,{className:"h-4 w-4 mr-2"})," Add & check in"]})]})]})]}),e.jsxs(we,{className:"mt-4 rounded-2xl border-slate-200 bg-white overflow-hidden",children:[e.jsxs("div",{className:"p-3 border-b border-slate-100 relative",children:[e.jsx(Yr,{className:"absolute left-6 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400"}),e.jsx(be,{placeholder:"Search attendees",value:i,onChange:v=>l(v.target.value),className:"pl-9 rounded-full border-slate-200"})]}),g.length===0?e.jsx("div",{className:"p-8 text-center text-slate-400 text-[13px]",children:"No matches."}):e.jsx("div",{className:"divide-y divide-slate-100 max-h-[60vh] overflow-auto",children:g.map(v=>{const _=v.status==="attended";return e.jsxs("div",{className:"p-4 flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-[15px] font-semibold text-slate-900 truncate",children:v.guest_name||v.guest_email}),e.jsx("div",{className:"text-[12px] text-slate-500 truncate",children:v.guest_email})]}),_?e.jsxs(qe,{className:"bg-emerald-500",children:[e.jsx(ma,{className:"h-3 w-3 mr-1"})," Checked in"]}):e.jsxs($,{size:"lg",className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>x(v),children:[e.jsx(ma,{className:"h-5 w-5 mr-2"})," Check in"]})]},v.id)})})]})]})}):e.jsx("div",{className:"p-8 text-slate-500",children:"Loading…"})}const vWn=["Brand-new agents","Producing solo agents","Team leaders","Luxury agents","New construction agents","Agents struggling with marketing","Agents needing better systems/support","Agents interested in additional income"],bWn=["Lead generation","Database marketing","Listing marketing","Social media/video","Open houses","Negotiation","Systems and technology","Team building","Leadership","New construction","Luxury","Business planning"],Kwt=[{key:"produce",icon:ql,title:"Produce",blurb:"Attract through visible production and excellence.",example:"Publish weekly market updates, share every closing story with the lesson attached."},{key:"influence",icon:kn,title:"Influence",blurb:"Teach publicly and earn a following of agents.",example:"Host a monthly masterclass. Post 3 authority pieces a week."},{key:"provide",icon:z8,title:"Provide",blurb:"Give resources, tools, and referrals that make agents better.",example:"Send curated resource kits and warm referrals to the right people."},{key:"connect",icon:nk,title:"Connect",blurb:"Bring the right people into the same room.",example:"Host quarterly masterminds and 1:1 coffees on a repeatable rhythm."},{key:"balanced",icon:_3,title:"Balanced Plan",blurb:"A little of all four. Best for veteran attractors.",example:"Rotate weekly focus between production, teaching, providing, and connecting."}],_Wn=[{key:"new_relationships",label:"New agent relationships / month"},{key:"follow_ups",label:"Meaningful follow-ups / month"},{key:"content_pieces",label:"Agent-focused posts / month"},{key:"resources_shared",label:"Resources shared / month"},{key:"events",label:"Events hosted or attended / month"},{key:"brokerage_conversations",label:"Brokerage curiosity conversations / month"}],Ywt=["Build 25 meaningful agent relationships","Host 3 masterminds or events","Start a weekly agent newsletter","Share 30 valuable resources","Schedule 10 brokerage curiosity conversations","Help 5 agents solve a meaningful business challenge"];function Zwt(s){const t=(o,c=2)=>Math.max(2,Math.ceil((o||1)*c)),n={new_relationships:t(s.baseline.new_relationships/4,1.6),follow_ups:t(s.baseline.follow_ups/4,1.4),content_pieces:t(s.baseline.content_pieces/4,1.5),resources_shared:t(s.baseline.resources_shared/4,1.5),events:Math.max(1,Math.round((s.baseline.events||0)/4)),brokerage_conversations:Math.max(1,Math.round((s.baseline.brokerage_conversations||0)/4))},r=["Add 3 agents you already know to your Attract Pipeline","Review your last 5 closed transactions in the Transaction Tracker","Write your first Authority Content piece in Content Studio","Send one thoughtful resource to an agent you respect","Schedule one coffee or Zoom this week","Set your Follow-Up cadence in Settings","Book your next agent event on the calendar"],a={produce:"Post one production story + one market insight per week.",influence:"Post 3 authority pieces per week; go long-form once a month.",provide:"Share 2 resources per week and 1 warm referral per month.",connect:"One 1:1 per week + one small event per month.",balanced:"Rotate a Produce, Influence, Provide, and Connect focus week each month."},i={produce:"Transaction-to-Relationship Tracker",influence:"Authority Content Studio",provide:"Resource Library",connect:"Events & Follow-Up Center",balanced:"Dashboard Daily Plan"},l={produce:"Publish a 90-day production journal recap",influence:"Host a free 45-minute masterclass on your best system",provide:'Curate a "Top 10 tools every agent needs" resource kit',connect:"Invite 8 agents to a small-format mastermind",balanced:"Run a single flagship event featuring all four pillars"};return{primary_pillar:s.style,weekly_targets:n,first_7_days:r,content_rhythm:a[s.style],suggested_tool:i[s.style],suggested_offer:l[s.style],outcome:s.outcome,generated_at:new Date().toISOString()}}function wWn(){const s=Jn(),{settings:t,save:n}=KV(),[r,a]=k.useState(0),[i,l]=k.useState([]),[o,c]=k.useState([]),[d,u]=k.useState(null),[h,m]=k.useState({}),[p,g]=k.useState("");k.useEffect(()=>{var j,C;t&&((j=t.audiences)!=null&&j.length&&l(t.audiences),(C=t.teachables)!=null&&C.length&&c(t.teachables),t.attraction_style&&u(t.attraction_style),t.activity_baseline&&m(t.activity_baseline),t.ninety_day_outcome&&g(t.ninety_day_outcome))},[t==null?void 0:t.user_id]);const x=["Welcome","Audience","Teach","Style","Baseline","Outcome","Plan"],y=k.useMemo(()=>r===1?i.length>0:r===2?o.length>0:r===3?!!d:r===5?!!p:!0,[r,i,o,d,p]),v=(j,C,A)=>{A(j.includes(C)?j.filter(M=>M!==C):[...j,C])},_=async()=>{if(!d)return;const j=Zwt({style:d,baseline:h,outcome:p});await n.mutateAsync({audiences:i,teachables:o,attraction_style:d,activity_baseline:h,ninety_day_outcome:p,ninety_day_plan:j,primary_pillar:d,onboarding_completed_at:new Date().toISOString()}),ae.success("Your 90-day plan is ready."),s("/attract")};return e.jsxs("div",{className:"max-w-3xl mx-auto",children:[e.jsx("div",{className:"flex items-center gap-2 mb-8",children:x.map((j,C)=>e.jsx("div",{className:Ot("h-1.5 flex-1 rounded-full transition-colors",C<=r?"bg-violet-600":"bg-slate-200")},j))}),e.jsx(Yq,{mode:"wait",children:e.jsxs(_r.div,{initial:{opacity:0,y:12},animate:{opacity:1,y:0},exit:{opacity:0,y:-8},transition:{duration:.25},children:[r===0&&e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-violet-600 font-semibold mb-2",children:"A strategy session"}),e.jsx("h1",{className:"text-4xl md:text-5xl font-semibold tracking-tight text-slate-900",children:"Build an attraction business people want to be part of."}),e.jsx("p",{className:"text-slate-600 mt-4 text-lg leading-relaxed",children:"Attract isn't a recruiting funnel. It's a way of doing business where the right agents naturally find you — because you produce, teach, provide, and connect at a rhythm no one else in your market keeps."}),e.jsx("div",{className:"mt-8 grid grid-cols-2 md:grid-cols-4 gap-3",children:Kwt.filter(j=>j.key!=="balanced").map(j=>e.jsxs(we,{className:"p-4 rounded-2xl border-slate-200",children:[e.jsx(j.icon,{className:"h-5 w-5 text-violet-600 mb-2"}),e.jsx("div",{className:"text-[13px] font-semibold text-slate-900",children:j.title}),e.jsx("div",{className:"text-[11.5px] text-slate-500 mt-0.5",children:j.blurb})]},j.key))})]}),r===1&&e.jsx(oW,{icon:Xn,eyebrow:"Who can you best help?",title:"Pick every audience where you naturally shine.",subtitle:"You can adjust these anytime.",children:e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-2",children:vWn.map(j=>e.jsx(K8e,{label:j,active:i.includes(j),onClick:()=>v(i,j,l)},j))})}),r===2&&e.jsx(oW,{icon:Bm,eyebrow:"What can you genuinely teach?",title:"Choose the areas you'd feel proud to teach on stage.",subtitle:"Content and events will pull from here.",children:e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-2",children:bWn.map(j=>e.jsx(K8e,{label:j,active:o.includes(j),onClick:()=>v(o,j,c)},j))})}),r===3&&e.jsx(oW,{icon:_3,eyebrow:"Your primary attraction style",title:"Which of these fits how you already show up?",subtitle:"This becomes your default pillar and shapes every recommendation.",children:e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:Kwt.map(j=>e.jsx(we,{onClick:()=>u(j.key),className:Ot("p-5 rounded-2xl cursor-pointer transition-all border-2",d===j.key?"border-violet-600 bg-violet-50/70 shadow-md":"border-slate-200 hover:border-violet-300"),children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-xl bg-violet-100 text-violet-700 grid place-items-center",children:e.jsx(j.icon,{className:"h-5 w-5"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"text-[14px] font-semibold text-slate-900",children:j.title}),e.jsx("div",{className:"text-[12.5px] text-slate-600 mt-0.5",children:j.blurb}),e.jsxs("div",{className:"text-[11.5px] text-slate-500 italic mt-2",children:["Example: ",j.example]})]}),d===j.key&&e.jsx(ma,{className:"h-5 w-5 text-violet-600"})]})},j.key))})}),r===4&&e.jsx(oW,{icon:zp,eyebrow:"Current baseline",title:"Roughly, what are you doing today?",subtitle:"Estimate is fine. We use this to set realistic 90-day targets.",children:e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:_Wn.map(j=>e.jsxs("div",{children:[e.jsx(re,{className:"text-[12.5px] text-slate-700",children:j.label}),e.jsx(be,{type:"number",min:0,value:h[j.key]??"",onChange:C=>m({...h,[j.key]:Number(C.target.value)||0})})]},j.key))})}),r===5&&e.jsx(oW,{icon:_h,eyebrow:"90-day outcome",title:"Pick one outcome to chase for the next 90 days.",subtitle:"One clear promise to yourself is worth ten vague hopes.",children:e.jsxs("div",{className:"space-y-2",children:[Ywt.map(j=>e.jsx(K8e,{label:j,active:p===j,onClick:()=>g(j),full:!0},j)),e.jsxs("div",{className:"mt-3",children:[e.jsx(re,{className:"text-[12.5px] text-slate-700",children:"Or write your own"}),e.jsx(Ls,{rows:2,placeholder:"A specific outcome you can measure in 90 days...",value:Ywt.includes(p)?"":p,onChange:j=>g(j.target.value)})]})]})}),r===6&&d&&e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-violet-600 font-semibold mb-2",children:"Your plan"}),e.jsx("h2",{className:"text-3xl font-semibold tracking-tight text-slate-900",children:"You're ready. Here's your 90-day plan."}),e.jsx(sKt,{plan:Zwt({style:d,baseline:h,outcome:p})})]})]},r)}),e.jsxs("div",{className:"mt-10 flex items-center justify-between",children:[e.jsxs($,{variant:"ghost",onClick:()=>r===0?s("/attract"):a(r-1),children:[e.jsx(Ia,{className:"h-4 w-4 mr-1"})," ",r===0?"Skip for now":"Back"]}),r<6?e.jsxs($,{className:"bg-gradient-to-r from-violet-600 to-indigo-600 rounded-full px-6",disabled:!y,onClick:()=>a(r+1),children:["Continue ",e.jsx(xi,{className:"h-4 w-4 ml-1"})]}):e.jsxs($,{className:"bg-gradient-to-r from-violet-600 to-indigo-600 rounded-full px-6",onClick:_,disabled:n.isPending,children:[e.jsx(v0,{className:"h-4 w-4 mr-1.5"})," Activate my 90-day plan"]})]})]})}function oW({icon:s,eyebrow:t,title:n,subtitle:r,children:a}){return e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 text-[11px] uppercase tracking-[0.18em] text-violet-600 font-semibold mb-2",children:[e.jsx(s,{className:"h-3.5 w-3.5"})," ",t]}),e.jsx("h2",{className:"text-3xl font-semibold tracking-tight text-slate-900",children:n}),r&&e.jsx("p",{className:"text-slate-600 mt-1.5 mb-6",children:r}),e.jsx("div",{className:"mt-6",children:a})]})}function K8e({label:s,active:t,onClick:n,full:r}){return e.jsx("button",{type:"button",onClick:n,className:Ot("text-left rounded-xl border px-4 py-3 text-[13.5px] transition-colors",r?"w-full":"",t?"border-violet-600 bg-violet-50 text-violet-900 shadow-sm":"border-slate-200 bg-white hover:border-violet-300 text-slate-800"),children:e.jsxs("span",{className:"inline-flex items-center gap-2",children:[t&&e.jsx(ma,{className:"h-4 w-4 text-violet-600"})," ",s]})})}function sKt({plan:s}){return e.jsxs("div",{className:"mt-6 space-y-6",children:[e.jsxs(we,{className:"p-6 rounded-2xl bg-gradient-to-br from-violet-600 to-indigo-700 text-white border-0",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] opacity-80",children:"Primary focus"}),e.jsx("div",{className:"text-3xl font-semibold mt-1 capitalize",children:s.primary_pillar}),e.jsx("div",{className:"text-white/85 mt-2",children:s.content_rhythm}),e.jsxs("div",{className:"text-[13px] mt-4 rounded-xl bg-white/10 p-3",children:[e.jsx("span",{className:"opacity-80",children:"90-day outcome:"})," ",s.outcome]})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-3",children:"Weekly targets"}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-3",children:Object.entries(s.weekly_targets).map(([t,n])=>e.jsxs(we,{className:"p-4 rounded-2xl",children:[e.jsx("div",{className:"text-2xl font-semibold text-slate-900 tabular-nums",children:n}),e.jsx("div",{className:"text-[11.5px] text-slate-500 capitalize mt-0.5",children:t.replace(/_/g," ")})]},t))})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-3",children:"First 7 days"}),e.jsx(we,{className:"p-5 rounded-2xl",children:e.jsx("ul",{className:"space-y-2",children:s.first_7_days.map((t,n)=>e.jsxs("li",{className:"flex items-start gap-2.5 text-[13.5px] text-slate-800",children:[e.jsx("div",{className:"h-5 w-5 rounded-full bg-violet-100 text-violet-700 grid place-items-center text-[11px] font-semibold flex-shrink-0 mt-0.5",children:n+1}),t]},n))})})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs(we,{className:"p-5 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-2",children:"Recommended first tool"}),e.jsx("div",{className:"text-[15px] font-semibold text-slate-900",children:s.suggested_tool})]}),e.jsxs(we,{className:"p-5 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-2",children:"Suggested first offer"}),e.jsx("div",{className:"text-[15px] font-semibold text-slate-900",children:s.suggested_offer})]})]})]})}function jWn(){const{settings:s,resetOnboarding:t}=KV(),n=s==null?void 0:s.ninety_day_plan;return e.jsxs("div",{className:"max-w-4xl",children:[e.jsx(Hm,{eyebrow:"90-Day Plan",title:"Your personalized attraction plan.",description:"Generated from your onboarding responses. Adjust any time by rerunning onboarding.",actions:e.jsxs($,{variant:"outline",className:"rounded-full",onClick:()=>t.mutate(),children:[e.jsx(jm,{className:"h-4 w-4 mr-1.5"})," Rerun onboarding"]})}),n?e.jsx(sKt,{plan:n}):e.jsxs(we,{className:"p-8 rounded-2xl text-center",children:[e.jsx("p",{className:"text-slate-700 mb-4",children:"You haven't set up your 90-day plan yet."}),e.jsx($,{asChild:!0,className:"bg-gradient-to-r from-violet-600 to-indigo-600 rounded-full",children:e.jsx(nr,{to:"/attract/onboarding",children:"Start onboarding"})})]})]})}async function Xwt(s,t,n,r={}){await V.rpc("award_attract_activity",{_user_id:s,_activity_type:t,_title:n,_description:r.description??null,_pillar:r.pillar??null,_agent_id:r.agent_id??null,_metadata:r.metadata??{},_dedupe_minutes:30})}function nKt(){const{user:s}=ks(),t=ls(),n=pt({queryKey:["attract-transactions",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:o,error:c}=await V.from("attract_transactions").select("*").order("closing_date",{ascending:!1,nullsFirst:!1});if(c)throw c;return o??[]}}),r=Nt({mutationFn:async o=>{const c=[o.rating_communication,o.rating_professionalism,o.rating_problem_solving].filter(g=>typeof g=="number"),d=c.length?Number((c.reduce((g,x)=>g+x,0)/c.length).toFixed(2)):null,u={...o,user_id:s.id,overall_rating:d},{data:h,error:m}=o.id?await V.from("attract_transactions").update(u).eq("id",o.id).select().single():await V.from("attract_transactions").insert(u).select().single();if(m)throw m;const p=h;return o.id||await Xwt(s.id,"transaction_logged",`Reviewed ${p.property_address}`,{description:p.cooperating_first_name?`Cooperating agent: ${p.cooperating_first_name} ${p.cooperating_last_name??""}`:null,pillar:"produce",metadata:{transaction_id:p.id,overall_rating:d}}),p},onSuccess:()=>{t.invalidateQueries({queryKey:["attract-transactions"]}),t.invalidateQueries({queryKey:["attract-activities"]}),ae.success("Transaction saved")},onError:o=>ae.error(o.message)}),a=Nt({mutationFn:async({id:o,decision:c,notes:d})=>{const{data:u,error:h}=await V.from("attract_transactions").update({decision:c,decision_notes:d??null}).eq("id",o).select().single();if(h)throw h;return u},onSuccess:()=>{t.invalidateQueries({queryKey:["attract-transactions"]})}}),i=Nt({mutationFn:async o=>{let c=o.attract_agent_id;if(!c){const{data:d}=await V.from("attract_agents").select("id").eq("user_id",s.id).eq("first_name",o.cooperating_first_name??"").eq("last_name",o.cooperating_last_name??"").maybeSingle();if(d!=null&&d.id)c=d.id;else{const{data:u,error:h}=await V.from("attract_agents").insert({user_id:s.id,first_name:o.cooperating_first_name??"Unknown",last_name:o.cooperating_last_name,email:o.cooperating_email,phone:o.cooperating_phone,brokerage:o.cooperating_brokerage,source:"cooperating_transaction",stage:"new_connection",temperature:o.enjoy_business_with==="yes"?"warm":"cold",notes:o.stood_out}).select("id").single();if(h)throw h;c=u.id}}return await V.from("attract_transactions").update({attract_agent_id:c,decision:"add_pipeline"}).eq("id",o.id),await Xwt(s.id,"agent_added_from_transaction",`Added ${o.cooperating_first_name??"agent"} to pipeline`,{pillar:"produce",agent_id:c,metadata:{transaction_id:o.id}}),c},onSuccess:()=>{t.invalidateQueries({queryKey:["attract-transactions"]}),t.invalidateQueries({queryKey:["attract-agents"]}),t.invalidateQueries({queryKey:["attract-activities"]}),ae.success("Added to Agent Pipeline")},onError:o=>ae.error(o.message)}),l=Nt({mutationFn:async o=>{const{error:c}=await V.from("attract_transactions").delete().eq("id",o);if(c)throw c},onSuccess:()=>{t.invalidateQueries({queryKey:["attract-transactions"]}),ae.success("Transaction removed")}});return{transactions:n.data??[],isLoading:n.isLoading,upsert:r,setDecision:a,addToPipeline:i,remove:l}}function NWn({value:s,onChange:t}){return e.jsx("div",{className:"flex gap-1",children:[1,2,3,4,5].map(n=>e.jsx("button",{type:"button",onClick:()=>t(n),children:e.jsx(ri,{className:Ot("h-5 w-5",(s??0)>=n?"fill-amber-400 text-amber-400":"text-slate-300")})},n))})}function kWn(s,t){var l;const n=s.cooperating_first_name||"there",r=s.property_address||"the transaction",a=(l=s.stood_out)==null?void 0:l.trim(),i=a?`You ${a.replace(/^You\s+/i,"").replace(/[.!]$/,"")}.`:"You communicated clearly and handled the inevitable curveballs with real professionalism.";switch(t){case"warm":return`Hi ${n}, I really enjoyed working with you on ${r}. ${i} It made the deal feel smooth for both sides — and that's rare. Would love to stay connected. Grab coffee or a Zoom sometime this month? — `;case"peer":return`${n} — quick note. Working with you on ${r} was refreshing. ${i} We should stay in touch — I like being around agents who operate that way.`;case"text":return`Hey ${n} — just wanted to say thanks for the way you handled ${r}. ${i} Let's grab coffee soon.`;case"email":default:return`Subject: A quick thank you Hi ${n}, Wrapping up on ${r} and I wanted to send a note. ${i} It's the kind of transaction I remember for a long time. Would love to stay in touch — coffee, a Zoom, or a shared MLS thought when it hits. Whatever works. All the best, `}}const SWn={1:"Poor",2:"Fair",3:"OK",4:"Good",5:"Excellent"},Y8e={add_pipeline:{label:"In Pipeline",color:"bg-emerald-100 text-emerald-800"},send_compliment:{label:"Compliment sent",color:"bg-violet-100 text-violet-800"},invite_coffee:{label:"Coffee invited",color:"bg-amber-100 text-amber-800"},share_resource:{label:"Resource shared",color:"bg-sky-100 text-sky-800"},no_action:{label:"No action",color:"bg-slate-100 text-slate-700"},pending:{label:"Needs review",color:"bg-rose-100 text-rose-800"}};function CWn(){const{transactions:s,isLoading:t,upsert:n,setDecision:r,addToPipeline:a,remove:i}=nKt(),[l,o]=k.useState(""),[c,d]=k.useState(!1),[u,h]=k.useState(null),[m,p]=k.useState(null),g=k.useMemo(()=>{const y=l.trim().toLowerCase();return y?s.filter(v=>[v.property_address,v.cooperating_first_name,v.cooperating_last_name,v.cooperating_brokerage,v.city].filter(Boolean).some(_=>String(_).toLowerCase().includes(y))):s},[s,l]),x=k.useMemo(()=>{const y=s.length,v=s.filter(C=>C.enjoy_business_with==="yes").length,_=s.filter(C=>C.decision==="add_pipeline").length,j=s.filter(C=>C.follow_up_created).length;return{reviewed:y,highFit:v,inPipeline:_,followUps:j}},[s]);return e.jsxs("div",{children:[e.jsxs(nr,{to:"/attract/produce",className:"inline-flex items-center gap-1.5 text-[12px] text-slate-500 hover:text-violet-700 mb-3",children:[e.jsx(Ia,{className:"h-3.5 w-3.5"})," Back to Produce"]}),e.jsx(Hm,{eyebrow:"Produce → Tool",title:"Transaction-to-Relationship Tracker",description:"Every good cooperating agent is a future relationship. Log the transaction, note what stood out, and turn the best experiences into real professional friendships.",actions:e.jsxs($,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>d(!0),children:[e.jsx(nn,{className:"h-4 w-4 mr-1.5"})," Add Transaction"]})}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3 mb-6",children:[e.jsx(kie,{label:"Transactions reviewed",value:x.reviewed}),e.jsx(kie,{label:"High-fit agents",value:x.highFit,tone:"emerald"}),e.jsx(kie,{label:"Added to pipeline",value:x.inPipeline,tone:"violet"}),e.jsx(kie,{label:"Follow-ups created",value:x.followUps,tone:"amber"})]}),e.jsx("div",{className:"flex items-center gap-3 mb-4",children:e.jsxs("div",{className:"relative flex-1 max-w-md",children:[e.jsx(Yr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400"}),e.jsx(be,{value:l,onChange:y=>o(y.target.value),placeholder:"Search property, agent, brokerage...",className:"pl-9 rounded-full"})]})}),t?e.jsx("div",{className:"space-y-3",children:[0,1,2].map(y=>e.jsx(we,{className:"p-5 rounded-2xl h-24 animate-pulse bg-slate-100"},y))}):g.length===0?e.jsxs(we,{className:"p-10 rounded-2xl text-center",children:[e.jsx("div",{className:"h-14 w-14 rounded-2xl bg-violet-100 grid place-items-center mx-auto mb-4",children:e.jsx(kn,{className:"h-6 w-6 text-violet-700"})}),e.jsx("h3",{className:"text-lg font-semibold text-slate-900",children:"Turn transactions into relationships"}),e.jsx("p",{className:"text-[13.5px] text-slate-600 max-w-md mx-auto mt-2",children:"Add your last 5 closed transactions to spot the agents you'd love to be in business with — then send a thoughtful compliment that opens the door."}),e.jsxs($,{className:"mt-6 rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>d(!0),children:[e.jsx(nn,{className:"h-4 w-4 mr-1.5"})," Add your first transaction"]})]}):e.jsx("div",{className:"space-y-3",children:g.map(y=>{var v,_;return e.jsx(we,{className:"p-5 rounded-2xl hover:shadow-md transition-shadow",children:e.jsxs("div",{className:"flex flex-col md:flex-row md:items-center gap-4",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("div",{className:"text-[14px] font-semibold text-slate-900 truncate",children:y.property_address}),y.closing_date&&e.jsx(qe,{variant:"outline",className:"text-[10.5px]",children:Ys(new Date(y.closing_date),"MMM d, yyyy")}),e.jsx(qe,{className:Ot("text-[10.5px] border-0",((v=Y8e[y.decision])==null?void 0:v.color)??Y8e.pending.color),children:((_=Y8e[y.decision])==null?void 0:_.label)??"Needs review"})]}),e.jsxs("div",{className:"text-[12.5px] text-slate-600 mt-1",children:[y.cooperating_first_name||y.cooperating_last_name?`${y.cooperating_first_name??""} ${y.cooperating_last_name??""}`:"Cooperating agent",y.cooperating_brokerage?` · ${y.cooperating_brokerage}`:""]}),e.jsxs("div",{className:"flex items-center gap-3 mt-2 text-[12px] text-slate-600",children:[y.overall_rating!=null&&e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(ri,{className:"h-3.5 w-3.5 fill-amber-400 text-amber-400"})," ",y.overall_rating]}),y.enjoy_business_with&&e.jsxs("span",{className:"capitalize",children:["Fit: ",e.jsx("span",{className:Ot("font-medium",y.enjoy_business_with==="yes"?"text-emerald-700":y.enjoy_business_with==="maybe"?"text-amber-700":"text-slate-600"),children:y.enjoy_business_with})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs($,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>h(y),children:["Review ",e.jsx(fi,{className:"h-3.5 w-3.5 ml-1"})]}),e.jsxs($,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>p(y),children:[e.jsx(tB,{className:"h-3.5 w-3.5 mr-1"})," Message"]}),e.jsx($,{size:"sm",variant:"ghost",className:"text-rose-600 hover:text-rose-700",onClick:()=>i.mutate(y.id),children:"Remove"})]})]})},y.id)})}),e.jsx("div",{className:"mt-8",children:e.jsx(JF,{})}),e.jsx(AWn,{open:c,onClose:()=>d(!1),onSaved:y=>{d(!1),h(y)},upsert:n}),e.jsx(EWn,{tx:u,onClose:()=>h(null),onDecision:y=>u&&r.mutate({id:u.id,decision:y}),onAddToPipeline:()=>u&&a.mutate(u),onMessage:()=>{p(u),h(null)}}),e.jsx(TWn,{tx:m,onClose:()=>p(null)})]})}function kie({label:s,value:t,tone:n="slate"}){const r={slate:"text-slate-900",emerald:"text-emerald-700",violet:"text-violet-700",amber:"text-amber-700"};return e.jsxs(we,{className:"p-4 rounded-2xl",children:[e.jsx("div",{className:Ot("text-2xl font-semibold tabular-nums",r[n]),children:t}),e.jsx("div",{className:"text-[11.5px] text-slate-500 mt-0.5",children:s})]})}function AWn({open:s,onClose:t,onSaved:n,upsert:r}){const[a,i]=k.useState({enjoy_business_with:"maybe"}),l=c=>i({...a,...c}),o=async()=>{var d;if(!((d=a.property_address)!=null&&d.trim())){ae.error("Property address is required");return}const c=await r.mutateAsync(a);i({enjoy_business_with:"maybe"}),n(c)};return e.jsx(zs,{open:s,onOpenChange:c=>!c&&t(),children:e.jsxs(Rs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(Vs,{children:[e.jsx($s,{children:"Add Transaction"}),e.jsx(Cr,{children:"Capture what stood out while it's fresh."})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(re,{children:"Property address *"}),e.jsx(be,{value:a.property_address??"",onChange:c=>l({property_address:c.target.value})})]}),e.jsxs("div",{children:[e.jsx(re,{children:"City"}),e.jsx(be,{value:a.city??"",onChange:c=>l({city:c.target.value})})]}),e.jsxs("div",{children:[e.jsx(re,{children:"State"}),e.jsx(be,{value:a.state??"",onChange:c=>l({state:c.target.value})})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Closing date"}),e.jsx(be,{type:"date",value:a.closing_date??"",onChange:c=>l({closing_date:c.target.value})})]}),e.jsxs("div",{children:[e.jsx(re,{children:"You represented"}),e.jsxs(bs,{value:a.represented??"",onValueChange:c=>l({represented:c}),children:[e.jsx(ys,{children:e.jsx(_s,{placeholder:"Buyer or seller"})}),e.jsxs(vs,{children:[e.jsx(We,{value:"buyer",children:"Buyer"}),e.jsx(We,{value:"seller",children:"Seller"}),e.jsx(We,{value:"both",children:"Both"}),e.jsx(We,{value:"other",children:"Other"})]})]})]})]}),e.jsxs("div",{className:"border-t pt-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-3",children:"Cooperating agent"}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(re,{children:"First name"}),e.jsx(be,{value:a.cooperating_first_name??"",onChange:c=>l({cooperating_first_name:c.target.value})})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Last name"}),e.jsx(be,{value:a.cooperating_last_name??"",onChange:c=>l({cooperating_last_name:c.target.value})})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Email"}),e.jsx(be,{type:"email",value:a.cooperating_email??"",onChange:c=>l({cooperating_email:c.target.value})})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Phone"}),e.jsx(be,{value:a.cooperating_phone??"",onChange:c=>l({cooperating_phone:c.target.value})})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(re,{children:"Brokerage"}),e.jsx(be,{value:a.cooperating_brokerage??"",onChange:c=>l({cooperating_brokerage:c.target.value})})]})]})]}),e.jsxs("div",{className:"border-t pt-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-3",children:"Experience"}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[["rating_communication","Communication"],["rating_professionalism","Professionalism"],["rating_problem_solving","Problem solving"]].map(([c,d])=>e.jsxs("div",{children:[e.jsx(re,{children:d}),e.jsx(NWn,{value:a[c],onChange:u=>l({[c]:u})}),e.jsx("div",{className:"text-[11px] text-slate-500 mt-1",children:SWn[a[c]]??"—"})]},c))}),e.jsxs("div",{className:"mt-4",children:[e.jsx(re,{children:"Would you enjoy being in business with this agent?"}),e.jsx("div",{className:"flex gap-2 mt-2",children:["yes","maybe","no"].map(c=>e.jsx("button",{type:"button",onClick:()=>l({enjoy_business_with:c}),className:Ot("rounded-full px-4 py-1.5 text-[12.5px] font-medium border capitalize",a.enjoy_business_with===c?"bg-violet-600 text-white border-violet-600":"bg-white text-slate-700 border-slate-200"),children:c},c))})]}),e.jsxs("div",{className:"mt-4",children:[e.jsx(re,{children:"What stood out?"}),e.jsx(Ls,{rows:2,value:a.stood_out??"",onChange:c=>l({stood_out:c.target.value})})]}),e.jsxs("div",{className:"mt-4",children:[e.jsx(re,{children:"Private notes"}),e.jsx(Ls,{rows:2,value:a.private_notes??"",onChange:c=>l({private_notes:c.target.value}),placeholder:"Only you can see these."})]})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"ghost",onClick:t,children:"Cancel"}),e.jsx($,{onClick:o,disabled:r.isPending,className:"bg-gradient-to-r from-violet-600 to-indigo-600",children:"Save & review"})]})]})})}function EWn({tx:s,onClose:t,onDecision:n,onAddToPipeline:r,onMessage:a}){return s?e.jsx(zs,{open:!!s,onOpenChange:i=>!i&&t(),children:e.jsxs(Rs,{className:"max-w-lg",children:[e.jsxs(Vs,{children:[e.jsx($s,{children:"Would you like to build a relationship?"}),e.jsxs(Cr,{children:[s.cooperating_first_name?`${s.cooperating_first_name} ${s.cooperating_last_name??""}`:"This agent"," on ",s.property_address,"."]})]}),e.jsxs("div",{className:"grid grid-cols-1 gap-2",children:[e.jsx(lW,{icon:Pl,label:"Add to Agent Pipeline",tone:"violet",onClick:r}),e.jsx(lW,{icon:tB,label:"Send a professional compliment",tone:"teal",onClick:()=>{n("send_compliment"),a()}}),e.jsx(lW,{icon:b_,label:"Invite to coffee",tone:"amber",onClick:()=>{n("invite_coffee"),a()}}),e.jsx(lW,{icon:kn,label:"Share a relevant resource",tone:"sky",onClick:()=>n("share_resource")}),e.jsx(lW,{icon:ju,label:"No action right now",tone:"slate",onClick:()=>{n("no_action"),t()}})]})]})}):null}function lW({icon:s,label:t,tone:n,onClick:r}){const a={violet:"bg-violet-50 text-violet-700 hover:bg-violet-100",teal:"bg-teal-50 text-teal-700 hover:bg-teal-100",amber:"bg-amber-50 text-amber-700 hover:bg-amber-100",sky:"bg-sky-50 text-sky-700 hover:bg-sky-100",slate:"bg-slate-50 text-slate-700 hover:bg-slate-100"};return e.jsxs("button",{onClick:r,className:Ot("flex items-center gap-3 rounded-xl px-4 py-3 text-left transition-colors",a[n]),children:[e.jsx(s,{className:"h-5 w-5"}),e.jsx("div",{className:"flex-1 text-[13.5px] font-medium",children:t}),e.jsx(fi,{className:"h-4 w-4 opacity-60"})]})}function TWn({tx:s,onClose:t}){const[n,r]=k.useState("warm");if(!s)return null;const a=kWn(s,n);return e.jsx(zs,{open:!!s,onOpenChange:i=>!i&&t(),children:e.jsxs(Rs,{className:"max-w-lg",children:[e.jsxs(Vs,{children:[e.jsx($s,{children:"Personalized message"}),e.jsx(Cr,{children:"Adjust the tone, then copy and send from your usual inbox."})]}),e.jsx("div",{className:"flex gap-1.5 mb-3",children:[["warm","Warm & pro"],["peer","Casual peer"],["text","Short text"],["email","Email"]].map(([i,l])=>e.jsx("button",{onClick:()=>r(i),className:Ot("rounded-full px-3 py-1 text-[11.5px] font-medium border",n===i?"bg-violet-600 text-white border-violet-600":"bg-white text-slate-700 border-slate-200"),children:l},i))}),e.jsx(Ls,{value:a,readOnly:!0,rows:10,className:"font-mono text-[12.5px]"}),e.jsxs(kr,{children:[e.jsx($,{variant:"ghost",onClick:t,children:"Close"}),e.jsxs($,{className:"bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>{navigator.clipboard.writeText(a),ae.success("Copied to clipboard")},children:[e.jsx(Da,{className:"h-4 w-4 mr-1.5"})," Copy"]})]})]})})}function rKt(){const{user:s}=ks(),t=ls(),n=pt({queryKey:["attract-content",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:o,error:c}=await V.from("attract_content_drafts").select("*").order("updated_at",{ascending:!1});if(c)throw c;return o??[]}}),r=Nt({mutationFn:async o=>{const{data:c,error:d}=await V.functions.invoke("attract-content-generate",{body:o});if(d)throw d;if(c!=null&&c.error)throw new Error(c.error);return c},onSuccess:o=>{t.invalidateQueries({queryKey:["attract-content"]}),o.demo?ae.info("Demo generation used — configure AI provider for live results"):ae.success("Content generated")},onError:o=>ae.error(o.message)}),a=Nt({mutationFn:async o=>{const{data:c,error:d}=await V.from("attract_content_drafts").update(o).eq("id",o.id).select().single();if(d)throw d;return c},onSuccess:()=>{t.invalidateQueries({queryKey:["attract-content"]}),ae.success("Saved")}}),i=Nt({mutationFn:async o=>{const{error:c}=await V.from("attract_content_drafts").update({status:"posted",posted_at:new Date().toISOString()}).eq("id",o);if(c)throw c;await V.rpc("award_attract_activity",{_user_id:s.id,_activity_type:"content_posted",_title:"Posted authority content",_description:null,_pillar:"influence",_agent_id:null,_metadata:{draft_id:o},_dedupe_minutes:30})},onSuccess:()=>{t.invalidateQueries({queryKey:["attract-content"]}),t.invalidateQueries({queryKey:["attract-activities"]}),ae.success("Marked as posted")}}),l=Nt({mutationFn:async o=>{const{error:c}=await V.from("attract_content_drafts").delete().eq("id",o);if(c)throw c},onSuccess:()=>{t.invalidateQueries({queryKey:["attract-content"]}),ae.success("Draft removed")}});return{drafts:n.data??[],isLoading:n.isLoading,generate:r,save:a,markPosted:i,remove:l}}const Dqe=[{key:"transaction_lesson",label:"Transaction Lesson",blurb:"A real story from a recent deal that teaches something.",fields:[{key:"what_happened",label:"What happened?",placeholder:"A short version of the story."},{key:"challenge",label:"What challenge came up?"},{key:"what_you_did",label:"What did you do?"},{key:"lesson",label:"What can another agent learn?"}]},{key:"behind_the_business",label:"Behind the Business",blurb:"A peek behind how you run the day-to-day.",fields:[{key:"topic",label:"What are you sharing?",placeholder:"A morning routine, tool stack, client system..."},{key:"why",label:"Why does it matter?"},{key:"takeaway",label:"What can they take away?"}]},{key:"unpopular_opinion",label:"Unpopular Industry Opinion",blurb:"Say what most people are afraid to say.",fields:[{key:"opinion",label:"What is your actual opinion?"},{key:"why",label:"Why do you believe it?"},{key:"example",label:"What real example supports it?"}]},{key:"system_win",label:"A System That Improved My Business",blurb:"A specific system with a before/after.",fields:[{key:"system",label:"What is the system?"},{key:"before",label:"What was life like before?"},{key:"after",label:"What changed after?"}]},{key:"mistake_to_avoid",label:"Mistake Agents Can Avoid",blurb:"A mistake you made or watched happen — and the fix.",fields:[{key:"mistake",label:"What is the mistake?"},{key:"result",label:"What did it cost?"},{key:"fix",label:"How do you avoid it now?"}]},{key:"do_differently",label:"What I Would Do Differently",blurb:"Reflection on a past year, launch, or transaction.",fields:[{key:"period",label:"What period are you reflecting on?"},{key:"what",label:"What would you do differently?"},{key:"why",label:"Why?"}]},{key:"leadership_lesson",label:"Leadership Lesson",blurb:"A moment that shaped how you lead.",fields:[{key:"story",label:"The moment/story"},{key:"lesson",label:"The lesson"}]},{key:"tool_tip",label:"Tool or Technology Tip",blurb:"A tool + how you use it + why it matters.",fields:[{key:"tool",label:"Which tool?"},{key:"how",label:"How do you use it?"},{key:"impact",label:"The impact on your business"}]},{key:"market_strategy",label:"Market Strategy",blurb:"Something you're seeing in your market that others are missing.",fields:[{key:"observation",label:"What are you seeing?"},{key:"strategy",label:"What are you doing about it?"},{key:"takeaway",label:"How can they apply it?"}]},{key:"event_promo",label:"Event Promotion",blurb:"Promote an event without sounding like a pitch.",fields:[{key:"event",label:"Event name"},{key:"who",label:"Who is it for?"},{key:"walk_away",label:"What will they walk away with?"},{key:"when_where",label:"When and where"}]}],MWn=["Direct","Educational","Fun","Contrarian","Encouraging"],PWn=["short","medium","long"],IWn=["instagram","linkedin","facebook","youtube","email"],vCe={idea:{label:"Idea",color:"bg-slate-100 text-slate-700"},draft:{label:"Draft",color:"bg-amber-100 text-amber-800"},ready:{label:"Ready",color:"bg-emerald-100 text-emerald-800"},posted:{label:"Posted",color:"bg-violet-100 text-violet-800"}};function LWn(){const{drafts:s,isLoading:t,generate:n,save:r,markPosted:a,remove:i}=rKt(),[l,o]=k.useState(!1),[c,d]=k.useState(null),u=k.useMemo(()=>({ready:s.filter(h=>h.status==="ready"),draft:s.filter(h=>h.status==="draft"),idea:s.filter(h=>h.status==="idea"),posted:s.filter(h=>h.status==="posted")}),[s]);return e.jsxs("div",{children:[e.jsxs(nr,{to:"/attract/influence",className:"inline-flex items-center gap-1.5 text-[12px] text-slate-500 hover:text-violet-700 mb-3",children:[e.jsx(Ia,{className:"h-3.5 w-3.5"})," Back to Influence"]}),e.jsx(Hm,{eyebrow:"Influence → Tool",title:"Authority Content Studio",description:"Turn your real experience into agent-focused content that builds authority — without sounding like a brokerage pitch.",actions:e.jsxs($,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>{d(null),o(!0)},children:[e.jsx(vf,{className:"h-4 w-4 mr-1.5"})," New Content"]})}),e.jsxs("div",{className:"mb-6 rounded-2xl border border-amber-200 bg-amber-50/70 px-5 py-3.5 text-[13px] text-amber-900 flex items-start gap-3",children:[e.jsx(kn,{className:"h-4 w-4 mt-0.5"}),e.jsxs("div",{children:[e.jsx("span",{className:"font-semibold",children:"80/20 rule:"})," Aim for 80% useful industry, business, and personal content — and no more than 20% direct brokerage content."]})]}),e.jsxs(ya,{defaultValue:"all",className:"mb-8",children:[e.jsxs(va,{children:[e.jsxs(is,{value:"all",children:["All (",s.length,")"]}),e.jsxs(is,{value:"ready",children:["Ready (",u.ready.length,")"]}),e.jsxs(is,{value:"draft",children:["Draft (",u.draft.length,")"]}),e.jsxs(is,{value:"posted",children:["Posted (",u.posted.length,")"]})]}),e.jsx(cs,{value:"all",children:e.jsx(Sie,{drafts:s,isLoading:t,onOpen:h=>{d(h),o(!0)},onPosted:h=>a.mutate(h),onRemove:h=>i.mutate(h),onEmpty:()=>{d(null),o(!0)}})}),e.jsx(cs,{value:"ready",children:e.jsx(Sie,{drafts:u.ready,isLoading:t,onOpen:h=>{d(h),o(!0)},onPosted:h=>a.mutate(h),onRemove:h=>i.mutate(h),onEmpty:()=>{d(null),o(!0)}})}),e.jsx(cs,{value:"draft",children:e.jsx(Sie,{drafts:u.draft,isLoading:t,onOpen:h=>{d(h),o(!0)},onPosted:h=>a.mutate(h),onRemove:h=>i.mutate(h),onEmpty:()=>{d(null),o(!0)}})}),e.jsx(cs,{value:"posted",children:e.jsx(Sie,{drafts:u.posted,isLoading:t,onOpen:h=>{d(h),o(!0)},onPosted:()=>{},onRemove:h=>i.mutate(h),onEmpty:()=>{d(null),o(!0)}})})]}),e.jsx(JF,{}),e.jsx(RWn,{open:l,editing:c,onClose:()=>{o(!1),d(null)},generate:n,save:r,markPosted:h=>a.mutate(h)})]})}function Sie({drafts:s,isLoading:t,onOpen:n,onPosted:r,onRemove:a,onEmpty:i}){return t?e.jsx("div",{className:"space-y-3 mt-4",children:[0,1,2].map(l=>e.jsx(we,{className:"p-5 rounded-2xl h-24 animate-pulse bg-slate-100"},l))}):s.length===0?e.jsxs(we,{className:"p-10 rounded-2xl text-center mt-4",children:[e.jsx("div",{className:"h-14 w-14 rounded-2xl bg-violet-100 grid place-items-center mx-auto mb-4",children:e.jsx(WN,{className:"h-6 w-6 text-violet-700"})}),e.jsx("h3",{className:"text-lg font-semibold text-slate-900",children:"Start your first authority piece"}),e.jsx("p",{className:"text-[13.5px] text-slate-600 max-w-md mx-auto mt-2",children:"Pick a real experience, answer 3 quick questions, and get a script, caption, carousel outline, and email — all in one shot."}),e.jsxs($,{className:"mt-6 rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:i,children:[e.jsx(nn,{className:"h-4 w-4 mr-1.5"})," Create your first draft"]})]}):e.jsx("div",{className:"space-y-3 mt-4",children:s.map(l=>{var c,d;const o=((c=Dqe.find(u=>u.key===l.mode))==null?void 0:c.label)??l.mode;return e.jsx(we,{className:"p-5 rounded-2xl hover:shadow-md transition-shadow",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx(qe,{className:Ot("text-[10.5px] border-0",vCe[l.status].color),children:vCe[l.status].label}),e.jsx(qe,{variant:"outline",className:"text-[10.5px]",children:o}),l.tone&&e.jsx(qe,{variant:"outline",className:"text-[10.5px]",children:l.tone}),l.ratio_flag&&e.jsxs(qe,{className:"text-[10.5px] bg-amber-100 text-amber-900 border-0 gap-1",children:[e.jsx(Gd,{className:"h-3 w-3"})," Sounds promotional"]})]}),e.jsx("div",{className:"text-[14px] font-semibold text-slate-900 mt-2 line-clamp-1",children:l.topic??((d=l.hook_options)==null?void 0:d[0])??"Untitled draft"}),e.jsx("div",{className:"text-[12.5px] text-slate-600 mt-1 line-clamp-2",children:l.caption??l.script??""}),e.jsx("div",{className:"text-[11px] text-slate-500 mt-2",children:l.posted_at?`Posted ${Ys(new Date(l.posted_at),"MMM d")}`:`Updated ${Ys(new Date(l.updated_at),"MMM d")}`})]}),e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx($,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>n(l),children:"Open"}),l.status!=="posted"&&e.jsxs($,{size:"sm",variant:"ghost",className:"text-emerald-700",onClick:()=>r(l.id),children:[e.jsx(ma,{className:"h-3.5 w-3.5 mr-1"})," Posted"]}),e.jsx($,{size:"sm",variant:"ghost",className:"text-rose-600",onClick:()=>a(l.id),children:e.jsx(Un,{className:"h-3.5 w-3.5"})})]})]})},l.id)})})}function RWn({open:s,editing:t,onClose:n,generate:r,save:a,markPosted:i}){const[l,o]=k.useState((t==null?void 0:t.mode)??"transaction_lesson"),[c,d]=k.useState((t==null?void 0:t.input_json)??{}),[u,h]=k.useState((t==null?void 0:t.topic)??""),[m,p]=k.useState((t==null?void 0:t.tone)??"Educational"),[g,x]=k.useState((t==null?void 0:t.length)??"medium"),[y,v]=k.useState((t==null?void 0:t.platforms)??["instagram"]),[_,j]=k.useState((t==null?void 0:t.include_brokerage_reference)??!1),[C,A]=k.useState(t??null),[M,I]=k.useState(""),[P,R]=k.useState((t==null?void 0:t.status)??"draft"),O=Dqe.find(G=>G.key===l),B=async G=>{const H=await r.mutateAsync({mode:l,topic:u,inputs:c,tone:m,length:g,platforms:y,include_brokerage_reference:_,refinement:G??M,draft_id:C==null?void 0:C.id});H!=null&&H.draft&&A(H.draft),I("")},U=async G=>{if(!C)return;const H=await a.mutateAsync({id:C.id,...G});A(H)};return e.jsx(zs,{open:s,onOpenChange:G=>!G&&n(),children:e.jsx(Rs,{className:"max-w-5xl max-h-[92vh] overflow-hidden p-0",children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-[320px_1fr] max-h-[92vh]",children:[e.jsxs("div",{className:"border-r bg-slate-50 p-5 overflow-y-auto",children:[e.jsxs(Vs,{children:[e.jsx($s,{className:"text-base",children:"Content Studio"}),e.jsx(Cr,{className:"text-[12px]",children:O.blurb})]}),e.jsxs("div",{className:"mt-4 space-y-3",children:[e.jsxs("div",{children:[e.jsx(re,{className:"text-[12px]",children:"Content mode"}),e.jsxs(bs,{value:l,onValueChange:G=>{o(G),d({})},children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsx(vs,{children:Dqe.map(G=>e.jsx(We,{value:G.key,children:G.label},G.key))})]})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-[12px]",children:"Topic (optional)"}),e.jsx(be,{value:u,onChange:G=>h(G.target.value),placeholder:"1-line summary"})]}),O.fields.map(G=>e.jsxs("div",{children:[e.jsx(re,{className:"text-[12px]",children:G.label}),e.jsx(Ls,{rows:2,value:c[G.key]??"",onChange:H=>d({...c,[G.key]:H.target.value}),placeholder:G.placeholder})]},G.key)),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{children:[e.jsx(re,{className:"text-[12px]",children:"Tone"}),e.jsxs(bs,{value:m,onValueChange:p,children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsx(vs,{children:MWn.map(G=>e.jsx(We,{value:G,children:G},G))})]})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-[12px]",children:"Length"}),e.jsxs(bs,{value:g,onValueChange:x,children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsx(vs,{children:PWn.map(G=>e.jsx(We,{value:G,children:G},G))})]})]})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-[12px]",children:"Platforms"}),e.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1",children:IWn.map(G=>e.jsx("button",{type:"button",onClick:()=>v(y.includes(G)?y.filter(H=>H!==G):[...y,G]),className:Ot("rounded-full px-2.5 py-1 text-[11px] capitalize border",y.includes(G)?"bg-violet-600 text-white border-violet-600":"bg-white border-slate-200 text-slate-700"),children:G},G))})]}),e.jsxs("label",{className:"flex items-center gap-2 text-[12px] text-slate-700",children:[e.jsx("input",{type:"checkbox",checked:_,onChange:G=>j(G.target.checked)}),"Include a light brokerage reference"]}),e.jsxs($,{className:"w-full bg-gradient-to-r from-violet-600 to-indigo-600 rounded-full",onClick:()=>B(),disabled:r.isPending,children:[e.jsx(vf,{className:"h-4 w-4 mr-1.5"})," ",r.isPending?"Generating…":C?"Regenerate":"Generate content"]})]})]}),e.jsx("div",{className:"overflow-y-auto p-6",children:C?e.jsxs("div",{className:"space-y-5",children:[C.ratio_flag&&e.jsxs("div",{className:"rounded-xl border border-amber-200 bg-amber-50 p-3 text-[12.5px] text-amber-900 flex items-start gap-2",children:[e.jsx(Gd,{className:"h-4 w-4 mt-0.5"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"font-semibold",children:"Heads up — this leans promotional."}),e.jsx("div",{children:"Not blocking anything, but you can rewrite it to feel more like teaching."})]}),e.jsx($,{size:"sm",variant:"outline",onClick:()=>B("Make this less salesy — focus purely on the lesson."),children:"Less salesy"})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx(qe,{className:Ot("text-[10.5px] border-0",vCe[P].color),children:vCe[P].label}),e.jsxs(bs,{value:P,onValueChange:G=>{R(G),U({status:G})},children:[e.jsx(ys,{className:"h-8 w-32 text-[12px]",children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"idea",children:"Idea"}),e.jsx(We,{value:"draft",children:"Draft"}),e.jsx(We,{value:"ready",children:"Ready"}),e.jsx(We,{value:"posted",children:"Posted"})]})]}),e.jsx(be,{type:"date",className:"h-8 w-40 text-[12px]",value:C.planned_at?C.planned_at.slice(0,10):"",onChange:G=>U({planned_at:G.target.value?new Date(G.target.value).toISOString():null})}),C.status!=="posted"&&e.jsxs($,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>i(C.id),children:[e.jsx(Wr,{className:"h-3.5 w-3.5 mr-1"})," Mark posted"]}),e.jsx($,{size:"sm",variant:"outline",className:"rounded-full",asChild:!0,children:e.jsxs(nr,{to:`/attract/provide/kits/new?seed=${encodeURIComponent(C.topic||C.mode)}`,children:[e.jsx(nn,{className:"h-3.5 w-3.5 mr-1"})," Turn into a kit"]})})]}),e.jsx(N9,{title:"Hook options",children:e.jsx("div",{className:"space-y-1.5",children:(C.hook_options??[]).map((G,H)=>e.jsxs("div",{className:"rounded-xl bg-slate-50 p-3 text-[13.5px] text-slate-800 flex items-start gap-2",children:[e.jsxs("span",{className:"text-violet-600 font-semibold",children:[H+1,"."]}),e.jsx("span",{className:"flex-1",children:G}),e.jsx(Oqe,{value:G})]},H))})}),e.jsx(N9,{title:"Teleprompter script",children:e.jsx(Z8e,{value:C.script??"",onSave:G=>U({script:G})})}),e.jsx(N9,{title:"Social caption",children:e.jsx(Z8e,{value:C.caption??"",onSave:G=>U({caption:G})})}),e.jsx(N9,{title:"Carousel outline",children:e.jsx("div",{className:"space-y-1.5",children:(C.carousel_outline??[]).map((G,H)=>e.jsxs("div",{className:"rounded-xl bg-slate-50 p-3 text-[13px]",children:[e.jsxs("div",{className:"text-[10.5px] uppercase tracking-wider text-slate-500 font-semibold",children:["Slide ",G.slide??H+1]}),e.jsx("div",{className:"text-slate-800 mt-0.5",children:G.text})]},H))})}),e.jsx(N9,{title:"Email lesson",children:e.jsx(Z8e,{value:C.email_lesson??"",onSave:G=>U({email_lesson:G})})}),e.jsx(N9,{title:"CTA options",children:e.jsx("div",{className:"space-y-1.5",children:(C.cta_options??[]).map((G,H)=>e.jsxs("div",{className:"rounded-xl bg-slate-50 p-3 text-[13px] text-slate-800 flex items-start gap-2",children:[e.jsx("span",{className:"flex-1",children:G}),e.jsx(Oqe,{value:G})]},H))})}),e.jsxs("div",{className:"rounded-xl border border-slate-200 p-3",children:[e.jsx("div",{className:"text-[12px] font-semibold text-slate-700 mb-2",children:"Refine further"}),e.jsx("div",{className:"flex flex-wrap gap-1.5 mb-2",children:["Make this sound more like me","Shorten the hook","Add a real example","Make it less salesy"].map(G=>e.jsx($,{size:"sm",variant:"outline",className:"text-[11.5px]",onClick:()=>B(G),children:G},G))}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(be,{value:M,onChange:G=>I(G.target.value),placeholder:"Custom refinement…"}),e.jsxs($,{variant:"outline",onClick:()=>B(),disabled:r.isPending,children:[e.jsx(yo,{className:"h-3.5 w-3.5 mr-1"})," Regenerate"]})]})]})]}):e.jsx("div",{className:"h-full flex items-center justify-center text-center text-slate-500",children:e.jsxs("div",{children:[e.jsx(YK,{className:"h-10 w-10 text-violet-300 mx-auto mb-3"}),e.jsx("div",{className:"text-[14px] font-medium text-slate-700",children:"Fill in the story on the left, then generate."}),e.jsx("div",{className:"text-[12.5px] mt-1",children:"You'll get a script, caption, carousel, email, and hooks in one shot."})]})})})]})})})}function N9({title:s,children:t}){return e.jsxs("div",{children:[e.jsxs("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-2 flex items-center gap-1.5",children:[e.jsx(ha,{className:"h-3 w-3 opacity-0"})," ",s]}),t]})}function Z8e({value:s,onSave:t}){const[n,r]=k.useState(s);return e.jsxs("div",{children:[e.jsx(Ls,{rows:5,value:n,onChange:a=>r(a.target.value),className:"text-[13.5px]"}),e.jsxs("div",{className:"flex gap-2 mt-2",children:[e.jsx($,{size:"sm",variant:"outline",onClick:()=>t(n),children:"Save edit"}),e.jsx(Oqe,{value:n})]})]})}function Oqe({value:s}){return e.jsx($,{size:"sm",variant:"ghost",onClick:()=>{navigator.clipboard.writeText(s),ae.success("Copied")},children:e.jsx(Da,{className:"h-3.5 w-3.5"})})}const DWn={draft:"bg-slate-100 text-slate-700",published:"bg-emerald-100 text-emerald-800",archived:"bg-amber-100 text-amber-800"};function OWn(){const{kits:s,isLoading:t,create:n,duplicate:r,remove:a}=YV(),i=Jn(),l=async()=>{const o=await n.mutateAsync({title:"Untitled Kit",status:"draft"});i(`/attract/provide/kits/${o.id}/edit`)};return e.jsxs("div",{children:[e.jsx(Hm,{eyebrow:"Provide · Resource Kits",title:"Your Resource Kits",description:"Package the value you already share, then track what actually creates conversations.",actions:e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{variant:"outline",asChild:!0,className:"rounded-full",children:e.jsxs(nr,{to:"/attract/provide/kits/templates",children:[e.jsx(xb,{className:"h-4 w-4 mr-2"}),"Starter library"]})}),e.jsxs($,{onClick:l,className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",children:[e.jsx(nn,{className:"h-4 w-4 mr-2"}),"New kit"]})]})}),t&&e.jsx("div",{className:"text-slate-500 text-sm",children:"Loading kits…"}),!t&&s.length===0&&e.jsxs(we,{className:"p-10 text-center rounded-2xl border-dashed border-slate-300 bg-white",children:[e.jsx(kn,{className:"h-8 w-8 mx-auto text-violet-500"}),e.jsx("div",{className:"mt-3 text-lg font-semibold",children:"You haven't built a kit yet."}),e.jsx("p",{className:"text-slate-600 max-w-md mx-auto mt-1 text-sm",children:"Start from a starter template or a blank kit. Bundle 3–7 pieces of real value and share with agents you'd love to work alongside."}),e.jsxs("div",{className:"flex gap-2 justify-center mt-5",children:[e.jsx($,{variant:"outline",asChild:!0,children:e.jsx(nr,{to:"/attract/provide/kits/templates",children:"Browse starter library"})}),e.jsx($,{onClick:l,className:"bg-gradient-to-r from-violet-600 to-indigo-600",children:"Start a blank kit"})]})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4",children:s.map(o=>{var c;return e.jsxs(we,{className:"p-5 rounded-2xl border-slate-200 bg-white hover:shadow-md transition-shadow flex flex-col",children:[e.jsx("div",{className:"flex items-start justify-between gap-2",children:e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(qe,{className:DWn[o.status]+" capitalize",children:o.status}),o.pillar&&e.jsx(qe,{variant:"outline",className:"capitalize",children:o.pillar})]}),e.jsx("div",{className:"mt-2 text-[16px] font-semibold text-slate-900 line-clamp-2",children:o.title}),o.audience&&e.jsxs("div",{className:"text-[12px] text-slate-500 mt-0.5",children:["For ",o.audience]})]})}),o.description&&e.jsx("p",{className:"text-[13px] text-slate-600 mt-3 line-clamp-3",children:o.description}),e.jsx("div",{className:"mt-4 flex flex-wrap gap-1",children:(c=o.tags)==null?void 0:c.slice(0,4).map(d=>e.jsxs(qe,{variant:"secondary",className:"text-[10.5px]",children:["#",d]},d))}),e.jsxs("div",{className:"mt-auto pt-4 flex items-center gap-2 flex-wrap",children:[e.jsx($,{size:"sm",variant:"outline",asChild:!0,children:e.jsxs(nr,{to:`/attract/provide/kits/${o.id}/edit`,children:[e.jsx(aB,{className:"h-3.5 w-3.5 mr-1.5"}),"Edit"]})}),e.jsx($,{size:"sm",variant:"outline",asChild:!0,children:e.jsxs(nr,{to:`/attract/provide/kits/${o.id}/analytics`,children:[e.jsx(Ul,{className:"h-3.5 w-3.5 mr-1.5"}),"Analytics"]})}),e.jsx($,{size:"sm",variant:"ghost",onClick:async()=>{const d=await r.mutateAsync(o.id);ae.success("Duplicated"),i(`/attract/provide/kits/${d}/edit`)},children:e.jsx(Da,{className:"h-3.5 w-3.5"})}),e.jsx($,{size:"sm",variant:"ghost",onClick:async()=>{await io("Delete this kit? Shares and events will also be removed.")&&a.mutate(o.id,{onSuccess:()=>ae.success("Deleted")})},children:e.jsx(Un,{className:"h-3.5 w-3.5 text-rose-600"})})]})]},o.id)})})]})}const FWn={pdf:ea,video:pu,link:od,checklist:op,template:v3,text:ea,content_studio:kn,resource:ea};function aKt({kit:s,items:t,owner:n,personalNote:r,mode:a="public",onEvent:i}){const l=(o,c,d)=>i==null?void 0:i(o,c,d);return e.jsxs("div",{className:"bg-[#0B0F1E] text-slate-100 rounded-2xl overflow-hidden",children:[s.cover_image_url?e.jsxs("div",{className:"aspect-[16/7] bg-slate-800 relative",children:[e.jsx("img",{src:s.cover_image_url,alt:"",className:"w-full h-full object-cover"}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-[#0B0F1E] to-transparent"})]}):e.jsx("div",{className:"h-24 bg-gradient-to-br from-violet-700 via-indigo-700 to-slate-900"}),e.jsxs("div",{className:"p-5 md:p-8",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[n.avatar_url?e.jsx("img",{src:n.avatar_url,alt:"",className:"h-11 w-11 rounded-full object-cover ring-2 ring-white/10"}):e.jsx("div",{className:"h-11 w-11 rounded-full bg-white/10 grid place-items-center text-white/70 font-semibold",children:n.display_name.slice(0,1)}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-[13.5px] font-semibold",children:n.display_name}),n.brokerage&&e.jsx("div",{className:"text-[11px] text-slate-400",children:n.brokerage})]})]}),e.jsx("h1",{className:"mt-5 text-2xl md:text-3xl font-semibold tracking-tight text-white",children:s.title}),s.audience&&e.jsxs("div",{className:"text-[12px] uppercase tracking-widest text-violet-300 mt-1",children:["For ",s.audience]}),s.description&&e.jsx("p",{className:"text-slate-300 mt-3 text-[14.5px] leading-relaxed",children:s.description}),(r||s.intro_text)&&e.jsxs(we,{className:"mt-6 p-4 bg-white/5 border-white/10 text-slate-200",children:[r&&e.jsx("div",{className:"text-[13px] whitespace-pre-line",children:r}),r&&s.intro_text&&e.jsx("div",{className:"my-2 border-t border-white/10"}),s.intro_text&&e.jsx("div",{className:"text-[13px] whitespace-pre-line text-slate-300",children:s.intro_text})]}),s.intro_video_url&&e.jsx("div",{className:"mt-5 aspect-video rounded-xl overflow-hidden bg-black",children:e.jsx("iframe",{src:zWn(s.intro_video_url),className:"w-full h-full",allow:"autoplay; encrypted-media; picture-in-picture",allowFullScreen:!0,title:"Intro video",onLoad:()=>l("video_start")})}),e.jsx("div",{className:"mt-8 space-y-3",children:t.filter(o=>!o.is_hidden).map(o=>{var d,u;const c=FWn[o.type]??ea;return e.jsx(we,{className:"p-4 bg-white/5 border-white/10 text-slate-100",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"h-9 w-9 rounded-lg bg-violet-600/20 text-violet-300 grid place-items-center flex-shrink-0",children:e.jsx(c,{className:"h-4 w-4"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-[14px] font-semibold text-white",children:o.title}),o.description&&e.jsx("div",{className:"text-[12.5px] text-slate-300 mt-0.5",children:o.description}),o.type==="checklist"&&((d=o.content)==null?void 0:d.items)&&e.jsx("ul",{className:"mt-2 space-y-1 text-[13px] text-slate-200",children:o.content.items.map((h,m)=>e.jsxs("li",{className:"flex gap-2",children:[e.jsx("span",{className:"text-violet-400",children:"•"}),h]},m))}),(o.type==="text"||o.type==="template")&&((u=o.content)==null?void 0:u.body)&&e.jsx("div",{className:"mt-2 text-[13px] text-slate-300 whitespace-pre-line",children:o.content.body}),o.url&&["video","pdf","link","resource"].includes(o.type)&&e.jsxs("div",{className:"mt-3 flex gap-2 flex-wrap",children:[e.jsx($,{size:"sm",variant:"secondary",asChild:!0,onClick:()=>l("resource_open",o.id),children:e.jsxs("a",{href:o.url,target:"_blank",rel:"noreferrer",children:[e.jsx(Ir,{className:"h-3.5 w-3.5 mr-1.5"}),"Open"]})}),o.allow_download&&o.type!=="link"&&e.jsx($,{size:"sm",variant:"outline",asChild:!0,onClick:()=>l("file_download",o.id),children:e.jsxs("a",{href:o.url,target:"_blank",rel:"noreferrer",download:!0,children:[e.jsx(ji,{className:"h-3.5 w-3.5 mr-1.5"}),"Download"]})}),o.type==="link"&&e.jsx($,{size:"sm",variant:"outline",asChild:!0,onClick:()=>l("external_link_click",o.id),children:e.jsx("a",{href:o.url,target:"_blank",rel:"noreferrer",children:"Visit"})})]})]})]})},o.id)})}),s.cta_label&&s.cta_url&&e.jsx("div",{className:"mt-8 text-center",children:e.jsx($,{size:"lg",asChild:!0,className:"bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>l("primary_cta_click"),children:e.jsx("a",{href:s.cta_url,target:"_blank",rel:"noreferrer",children:s.cta_label})})}),e.jsx("div",{className:"mt-10 pt-6 border-t border-white/10 text-[11px] text-slate-500 leading-relaxed",children:"Brokerage and compensation information should always be verified in writing. Nothing shared here constitutes a formal offer, agreement, or guarantee of income."})]})]})}function zWn(s){try{const t=new URL(s);if(t.hostname.includes("youtube.com")||t.hostname.includes("youtu.be")){const n=t.hostname.includes("youtu.be")?t.pathname.slice(1):t.searchParams.get("v");if(n)return`https://www.youtube.com/embed/${n}`}if(t.hostname.includes("vimeo.com")){const n=t.pathname.split("/").filter(Boolean).pop();if(n)return`https://player.vimeo.com/video/${n}`}return t.hostname.includes("loom.com")?s.replace("/share/","/embed/"):s}catch{return s}}const BWn=[{value:"text",label:"Text lesson"},{value:"checklist",label:"Checklist"},{value:"template",label:"Template / Script"},{value:"video",label:"Video / Embed"},{value:"pdf",label:"PDF / File"},{value:"link",label:"External link"},{value:"content_studio",label:"Content Studio output"},{value:"resource",label:"Existing resource"}];function Qwt(){var G,H;const{kitId:s}=oo(),[t]=Jc(),n=Jn(),{user:r}=ks(),a=s===void 0,{create:i,update:l}=YV(),{data:o,isLoading:c}=DWt(s),{items:d,add:u,update:h,remove:m,reorder:p}=vGn(s),{shares:g,create:x,revoke:y}=OWt(s),{agents:v}=A0(),[_,j]=k.useState(null),[C,A]=k.useState("desktop"),[M,I]=k.useState("idle"),P=k.useRef(null);k.useEffect(()=>{a&&!_&&(async()=>{const Y=t.get("seed"),se=await i.mutateAsync({title:Y?`From: ${Y}`:"Untitled Kit",status:"draft"});n(`/attract/provide/kits/${se.id}/edit`,{replace:!0})})()},[a]),k.useEffect(()=>{o&&j(o)},[o==null?void 0:o.id]);const R=Y=>{s&&(j(se=>({...se,...Y})),I("saving"),clearTimeout(P.current),P.current=setTimeout(async()=>{try{await l.mutateAsync({id:s,patch:Y}),I("saved"),setTimeout(()=>I("idle"),1500)}catch(se){ae.error(se.message??"Save failed"),I("idle")}},800))},O=async Y=>{!s||!r||await u.mutateAsync({user_id:r.id,type:Y,title:`New ${Y.replace("_"," ")}`})},B=(Y,se)=>{const ee=[...d],oe=Y+se;oe<0||oe>=ee.length||([ee[Y],ee[oe]]=[ee[oe],ee[Y]],p.mutate(ee.map(me=>me.id)))},U=g.filter(Y=>Y.status==="active");return a||!_?e.jsx("div",{className:"text-slate-500 text-sm",children:"Preparing your kit…"}):c?e.jsx("div",{className:"text-slate-500 text-sm",children:"Loading…"}):e.jsxs("div",{children:[e.jsx(Hm,{eyebrow:"Provide · Kit builder",title:_.title||"Untitled Kit",description:M==="saving"?"Saving…":M==="saved"?"Saved":`Last edited ${Ys(new Date(_.updated_at),"MMM d, h:mm a")}`,actions:e.jsxs("div",{className:"flex gap-2 flex-wrap",children:[e.jsx($,{variant:"outline",size:"sm",asChild:!0,className:"rounded-full",children:e.jsxs(nr,{to:"/attract/provide/kits",children:[e.jsx(Ia,{className:"h-4 w-4 mr-1"}),"Kits"]})}),e.jsx($,{variant:"outline",size:"sm",asChild:!0,className:"rounded-full",children:e.jsx(nr,{to:`/attract/provide/kits/${s}/analytics`,children:"Analytics"})}),e.jsxs(bs,{value:_.status,onValueChange:Y=>R({status:Y}),children:[e.jsx(ys,{className:"w-[130px] rounded-full",children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"draft",children:"Draft"}),e.jsx(We,{value:"published",children:"Published"}),e.jsx(We,{value:"archived",children:"Archived"})]})]})]})}),e.jsxs("div",{className:"grid grid-cols-1 xl:grid-cols-12 gap-6",children:[e.jsxs("div",{className:"xl:col-span-4 space-y-4",children:[e.jsxs(we,{className:"p-5 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-violet-700 font-semibold",children:"Kit details"}),e.jsxs("div",{className:"space-y-3 mt-3",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Title"}),e.jsx(be,{value:_.title??"",onChange:Y=>R({title:Y.target.value})})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Short description"}),e.jsx(Ls,{rows:3,value:_.description??"",onChange:Y=>R({description:Y.target.value})})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Cover image URL"}),e.jsx(be,{placeholder:"https://…",value:_.cover_image_url??"",onChange:Y=>R({cover_image_url:Y.target.value})})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Audience"}),e.jsx(be,{placeholder:"e.g. New agents",value:_.audience??"",onChange:Y=>R({audience:Y.target.value})})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Pillar"}),e.jsxs(bs,{value:_.pillar??"",onValueChange:Y=>R({pillar:Y}),children:[e.jsx(ys,{children:e.jsx(_s,{placeholder:"Choose"})}),e.jsxs(vs,{children:[e.jsx(We,{value:"produce",children:"Produce"}),e.jsx(We,{value:"influence",children:"Influence"}),e.jsx(We,{value:"provide",children:"Provide"}),e.jsx(We,{value:"connect",children:"Connect"})]})]})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Tags (comma separated)"}),e.jsx(be,{value:(_.tags??[]).join(", "),onChange:Y=>R({tags:Y.target.value.split(",").map(se=>se.trim()).filter(Boolean)})})]})]})]}),e.jsxs(we,{className:"p-5 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-violet-700 font-semibold",children:"Personal welcome"}),e.jsxs("div",{className:"space-y-3 mt-3",children:[e.jsx(Ls,{rows:4,placeholder:"Write a short personal note that opens the kit.",value:_.intro_text??"",onChange:Y=>R({intro_text:Y.target.value})}),e.jsxs("div",{children:[e.jsx(re,{children:"Intro video URL (optional)"}),e.jsx(be,{placeholder:"Loom/YouTube/Vimeo",value:_.intro_video_url??"",onChange:Y=>R({intro_video_url:Y.target.value})})]})]})]}),e.jsxs(we,{className:"p-5 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-violet-700 font-semibold",children:"Call to action"}),e.jsxs("div",{className:"grid grid-cols-2 gap-2 mt-3",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Button label"}),e.jsx(be,{value:_.cta_label??"",onChange:Y=>R({cta_label:Y.target.value})})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Button URL"}),e.jsx(be,{placeholder:"https://…",value:_.cta_url??"",onChange:Y=>R({cta_url:Y.target.value})})]})]}),e.jsxs("div",{className:"mt-3",children:[e.jsx(re,{children:"Expiration (optional)"}),e.jsx(be,{type:"datetime-local",value:_.expires_at?_.expires_at.slice(0,16):"",onChange:Y=>R({expires_at:Y.target.value?new Date(Y.target.value).toISOString():null})})]})]}),e.jsxs(we,{className:"p-5 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-violet-700 font-semibold",children:"Share this kit"}),e.jsx($Wn,{kitId:s,agents:v,shares:U,onCreate:Y=>x.mutate(Y),onRevoke:Y=>y.mutate(Y),status:_.status})]})]}),e.jsx("div",{className:"xl:col-span-5 space-y-4",children:e.jsxs(we,{className:"p-5 rounded-2xl",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-violet-700 font-semibold",children:"Kit sections"}),e.jsx("div",{className:"text-[13px] text-slate-600",children:"Drag order using arrows. Reorder to change how visitors experience the kit."})]}),e.jsxs(bs,{onValueChange:Y=>O(Y),children:[e.jsx(ys,{className:"w-[180px]",children:e.jsx(_s,{placeholder:"+ Add item"})}),e.jsx(vs,{children:BWn.map(Y=>e.jsx(We,{value:Y.value,children:Y.label},Y.value))})]})]}),e.jsxs("div",{className:"mt-4 space-y-3",children:[d.length===0&&e.jsx("div",{className:"text-center text-sm text-slate-500 py-10 border border-dashed rounded-xl",children:"No sections yet. Add your first item above."}),d.map((Y,se)=>{var ee,oe;return e.jsx(we,{className:"p-4 border-slate-200",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("button",{className:"text-slate-400 hover:text-slate-700",onClick:()=>B(se,-1),children:e.jsx(ap,{className:"h-4 w-4"})}),e.jsx("button",{className:"text-slate-400 hover:text-slate-700",onClick:()=>B(se,1),children:e.jsx(nx,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"flex-1 min-w-0 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(qe,{variant:"outline",className:"capitalize",children:Y.type.replace("_"," ")}),e.jsx(be,{className:"flex-1",value:Y.title,onChange:me=>h.mutate({id:Y.id,patch:{title:me.target.value}})})]}),e.jsx(Ls,{rows:2,placeholder:"Short description",value:Y.description??"",onChange:me=>h.mutate({id:Y.id,patch:{description:me.target.value}})}),["video","pdf","link","resource"].includes(Y.type)&&e.jsx(be,{placeholder:"URL",value:Y.url??"",onChange:me=>h.mutate({id:Y.id,patch:{url:me.target.value}})}),["text","template"].includes(Y.type)&&e.jsx(Ls,{rows:4,placeholder:"Body text or script",value:((ee=Y.content)==null?void 0:ee.body)??"",onChange:me=>h.mutate({id:Y.id,patch:{content:{...Y.content??{},body:me.target.value}}})}),Y.type==="checklist"&&e.jsx(Ls,{rows:5,placeholder:"One item per line",value:(((oe=Y.content)==null?void 0:oe.items)??[]).join(` `),onChange:me=>h.mutate({id:Y.id,patch:{content:{items:me.target.value.split(` `).map(Q=>Q.trim()).filter(Boolean)}}})}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("label",{className:"flex items-center gap-2 text-[12px] text-slate-600",children:[e.jsx(On,{checked:Y.allow_download,onCheckedChange:me=>h.mutate({id:Y.id,patch:{allow_download:me}})}),"Allow download"]}),e.jsxs("label",{className:"flex items-center gap-2 text-[12px] text-slate-600",children:[e.jsx(On,{checked:!Y.is_hidden,onCheckedChange:me=>h.mutate({id:Y.id,patch:{is_hidden:!me}})}),"Visible"]}),e.jsxs("button",{className:"ml-auto text-rose-600 text-[12px] flex items-center gap-1",onClick:()=>m.mutate(Y.id),children:[e.jsx(Un,{className:"h-3.5 w-3.5"}),"Delete"]})]})]})]})},Y.id)})]})]})}),e.jsx("div",{className:"xl:col-span-3",children:e.jsxs(we,{className:"p-4 rounded-2xl xl:sticky xl:top-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-violet-700 font-semibold",children:"Live preview"}),e.jsx(ya,{value:C,onValueChange:Y=>A(Y),children:e.jsxs(va,{className:"h-8",children:[e.jsx(is,{value:"desktop",className:"h-6 px-2",children:e.jsx(j2,{className:"h-3.5 w-3.5"})}),e.jsx(is,{value:"mobile",className:"h-6 px-2",children:e.jsx(yb,{className:"h-3.5 w-3.5"})})]})})]}),e.jsx("div",{className:C==="mobile"?"max-w-[320px] mx-auto":"",children:e.jsx(aKt,{kit:_,items:d,owner:{display_name:((G=r==null?void 0:r.user_metadata)==null?void 0:G.full_name)||(r==null?void 0:r.email)||"You",avatar_url:((H=r==null?void 0:r.user_metadata)==null?void 0:H.avatar_url)??null,brokerage:null},mode:"preview"})})]})})]})]})}function $Wn({kitId:s,agents:t,shares:n,onCreate:r,onRevoke:a,status:i}){const[l,o]=k.useState("general"),[c,d]=k.useState("");return i!=="published"?e.jsx("div",{className:"text-[12.5px] text-slate-500 mt-3",children:"Publish this kit to generate share links."}):e.jsxs("div",{className:"mt-3 space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-1 gap-2",children:[e.jsxs(bs,{value:l,onValueChange:u=>o(u),children:[e.jsx(ys,{children:e.jsx(_s,{placeholder:"Choose agent"})}),e.jsxs(vs,{children:[e.jsx(We,{value:"general",children:"General share link"}),t.map(u=>e.jsxs(We,{value:u.id,children:[u.first_name," ",u.last_name??""]},u.id))]})]}),e.jsx(Ls,{rows:2,placeholder:"Optional personal note shown on the page",value:c,onChange:u=>d(u.target.value)}),e.jsxs($,{size:"sm",className:"bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>{r({kit_id:s,agent_id:l==="general"?null:l,personal_note:c||null}),d("")},children:[e.jsx(ou,{className:"h-4 w-4 mr-2"}),"Create share link"]})]}),e.jsxs("div",{className:"space-y-2",children:[n.length===0&&e.jsx("div",{className:"text-[12px] text-slate-500",children:"No active links yet."}),n.map(u=>{var p;const h=zWt(u.share_token),m=u.agent_id?((p=t.find(g=>g.id===u.agent_id))==null?void 0:p.first_name)??"Agent":"General";return e.jsxs("div",{className:"border rounded-lg p-2.5 text-[12.5px]",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"font-medium",children:m}),e.jsx(qe,{variant:"secondary",className:"capitalize",children:u.engagement_level.replace("_"," ")})]}),e.jsx("div",{className:"text-slate-500 truncate mt-1",children:h}),e.jsxs("div",{className:"flex gap-1 mt-2",children:[e.jsxs($,{size:"sm",variant:"outline",onClick:()=>{navigator.clipboard.writeText(h),ae.success("Link copied")},children:[e.jsx(Da,{className:"h-3.5 w-3.5 mr-1"}),"Copy"]}),e.jsx($,{size:"sm",variant:"outline",asChild:!0,children:e.jsxs("a",{href:h,target:"_blank",rel:"noreferrer",children:[e.jsx(Ir,{className:"h-3.5 w-3.5 mr-1"}),"Open"]})}),e.jsxs($,{size:"sm",variant:"ghost",className:"text-rose-600",onClick:()=>a(u.id),children:[e.jsx(Fz,{className:"h-3.5 w-3.5 mr-1"}),"Revoke"]})]})]},u.id)})]})]})}const UWn={page_view:"Views",resource_open:"Resource opens",file_download:"Downloads",video_start:"Video starts",video_complete:"Video completes",external_link_click:"Link clicks",primary_cta_click:"CTA clicks",question_submitted:"Questions",meeting_requested:"Meetings requested"};function qWn(){const{kitId:s}=oo(),{data:t}=DWt(s),{shares:n}=OWt(s),{data:r=[]}=FWt(s),a=k.useMemo(()=>{const l=d=>r.filter(u=>u.event_type===d).length,o=new Set(n.filter(d=>d.agent_id).map(d=>d.agent_id)).size,c=n.filter(d=>d.first_opened_at).length;return{shares:n.length,uniqueAgents:o,viewRate:n.length?Math.round(c/n.length*100):0,engaged:n.filter(d=>["engaged","high_intent"].includes(d.engagement_level)).length,downloads:l("file_download"),ctaClicks:l("primary_cta_click"),questions:l("question_submitted"),meetings:l("meeting_requested")}},[n,r]),i=k.useMemo(()=>{const l=new Map;return r.forEach(o=>{const c=Ys(new Date(o.created_at),"MMM d");l.set(c,(l.get(c)??0)+1)}),Array.from(l.entries()).reverse().map(([o,c])=>({date:o,count:c}))},[r]);return e.jsxs("div",{children:[e.jsx(Hm,{eyebrow:"Kit analytics",title:(t==null?void 0:t.title)??"Kit",description:"Which value is actually creating conversations.",actions:e.jsx($,{variant:"outline",size:"sm",asChild:!0,className:"rounded-full",children:e.jsxs(nr,{to:`/attract/provide/kits/${s}/edit`,children:[e.jsx(Ia,{className:"h-4 w-4 mr-1"}),"Edit"]})})}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3 mb-6",children:[e.jsx(YA,{label:"Shares",value:a.shares,icon:ba,tone:"violet"}),e.jsx(YA,{label:"Unique agents",value:a.uniqueAgents,icon:ba,tone:"indigo"}),e.jsx(YA,{label:"View rate",value:`${a.viewRate}%`,icon:ba,tone:"teal"}),e.jsx(YA,{label:"Engaged",value:a.engaged,icon:rh,tone:"emerald"}),e.jsx(YA,{label:"Downloads",value:a.downloads,icon:ji,tone:"orange"}),e.jsx(YA,{label:"CTA clicks",value:a.ctaClicks,icon:rh,tone:"rose"}),e.jsx(YA,{label:"Questions",value:a.questions,icon:Vu,tone:"violet"}),e.jsx(YA,{label:"Meetings",value:a.meetings,icon:wm,tone:"indigo"})]}),e.jsxs("div",{className:"grid grid-cols-1 xl:grid-cols-3 gap-6",children:[e.jsxs(we,{className:"p-5 rounded-2xl xl:col-span-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-violet-700 font-semibold mb-2",children:"Engagement over time"}),e.jsx("div",{className:"h-64",children:e.jsx(C_,{width:"100%",height:"100%",children:e.jsxs(gZe,{data:i,children:[e.jsx(XO,{strokeDasharray:"3 3",stroke:"#eee"}),e.jsx(Cb,{dataKey:"date",fontSize:11}),e.jsx(Ab,{fontSize:11,allowDecimals:!1}),e.jsx(vg,{}),e.jsx(FF,{type:"monotone",dataKey:"count",stroke:"#7c3aed",strokeWidth:2})]})})})]}),e.jsxs(we,{className:"p-5 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-violet-700 font-semibold mb-2",children:"By event type"}),e.jsx("div",{className:"space-y-2",children:Object.entries(UWn).map(([l,o])=>{const c=r.filter(d=>d.event_type===l).length;return e.jsxs("div",{className:"flex justify-between text-[13px]",children:[e.jsx("span",{className:"text-slate-600",children:o}),e.jsx("span",{className:"font-semibold tabular-nums",children:c})]},l)})})]})]}),e.jsxs(we,{className:"p-5 rounded-2xl mt-6",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-violet-700 font-semibold mb-3",children:"Recipients"}),e.jsxs("div",{className:"space-y-2",children:[n.length===0&&e.jsx("div",{className:"text-sm text-slate-500",children:"No one has been shared this kit yet."}),n.map(l=>e.jsxs("div",{className:"flex items-center justify-between border-b py-2 text-[13px]",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:l.agent_id?"Personalized":"General link"}),e.jsxs("div",{className:"text-slate-500 text-[11.5px]",children:["Created ",Ys(new Date(l.created_at),"MMM d")," · ",l.open_count," opens",l.last_opened_at&&` · last opened ${Ys(new Date(l.last_opened_at),"MMM d")}`]})]}),e.jsx(qe,{variant:"secondary",className:"capitalize",children:l.engagement_level.replace("_"," ")})]},l.id))]})]})]})}function YA({label:s,value:t,icon:n,tone:r}){const a={violet:"text-violet-700 bg-violet-50",indigo:"text-indigo-700 bg-indigo-50",teal:"text-teal-700 bg-teal-50",emerald:"text-emerald-700 bg-emerald-50",orange:"text-orange-700 bg-orange-50",rose:"text-rose-700 bg-rose-50"};return e.jsxs(we,{className:"p-4 rounded-2xl",children:[e.jsx("div",{className:`h-8 w-8 rounded-lg grid place-items-center ${a[r]}`,children:e.jsx(n,{className:"h-4 w-4"})}),e.jsx("div",{className:"mt-2 text-[22px] font-semibold tabular-nums",children:t}),e.jsx("div",{className:"text-[11.5px] text-slate-500",children:s})]})}function VWn(){const{data:s=[],isLoading:t}=bGn(),n=_Gn(),r=Jn(),a=async i=>{try{const l=await n.mutateAsync(i);ae.success("Added to your drafts"),r(`/attract/provide/kits/${l}/edit`)}catch(l){ae.error(l.message??"Could not clone template")}};return e.jsxs("div",{children:[e.jsx(Hm,{eyebrow:"Starter library",title:"LevelUp Starter Kits",description:"Ten proven relationship-first kits. Duplicate any of them into your workspace and personalize the parts that matter.",actions:e.jsx($,{variant:"outline",asChild:!0,className:"rounded-full",children:e.jsxs(nr,{to:"/attract/provide/kits",children:[e.jsx(Ia,{className:"h-4 w-4 mr-2"}),"Back to my kits"]})})}),t&&e.jsx("div",{className:"text-slate-500 text-sm",children:"Loading templates…"}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4",children:s.map(i=>{var l;return e.jsxs(we,{className:"p-6 rounded-2xl border-slate-200 bg-white flex flex-col",children:[e.jsxs("div",{className:"flex items-center gap-2 text-[10.5px] uppercase tracking-widest text-violet-700 font-semibold",children:[e.jsx(kn,{className:"h-3.5 w-3.5"})," Starter kit"]}),e.jsx("div",{className:"mt-2 text-[17px] font-semibold text-slate-900",children:i.title}),i.audience&&e.jsxs("div",{className:"text-[12px] text-slate-500 mt-0.5",children:["For ",i.audience]}),e.jsx("p",{className:"text-[13px] text-slate-600 mt-2 line-clamp-3",children:i.description}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-1",children:[i.pillar&&e.jsx(qe,{variant:"outline",className:"capitalize",children:i.pillar}),(i.tags??[]).slice(0,4).map(o=>e.jsxs(qe,{variant:"secondary",className:"text-[10.5px]",children:["#",o]},o))]}),e.jsxs("div",{className:"text-[12px] text-slate-500 mt-3",children:[((l=i.suggested_items)==null?void 0:l.length)??0," suggested sections"]}),e.jsxs($,{className:"mt-4 bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>a(i.id),children:[e.jsx(vf,{className:"h-4 w-4 mr-2"}),"Use this kit"]})]},i.id)})})]})}const HWn=V,GWn=[...vM,JTe],WWn={hot:iu,warm:S2,cold:Hw},cW=({label:s})=>e.jsxs("span",{className:"text-slate-400 italic",children:["Not recorded",s?` — add ${s}`:""]}),ZA=s=>[s.first_name,s.last_name].filter(Boolean).join(" "),KWn=s=>{var t,n;return`${((t=s.first_name)==null?void 0:t[0])??""}${((n=s.last_name)==null?void 0:n[0])??""}`.toUpperCase()||"?"};function k9({label:s,children:t}){return e.jsxs("div",{children:[e.jsx("div",{className:"text-[10.5px] uppercase tracking-wider text-slate-400 font-semibold",children:s}),e.jsx("div",{className:"text-[13.5px] text-slate-800 mt-0.5 break-words",children:t})]})}const YWn={touch:"bg-violet-500",note:"bg-slate-400",stage_change:"bg-indigo-500",follow_up_created:"bg-amber-400",follow_up_completed:"bg-emerald-500",follow_up_missed:"bg-rose-500",kit_shared:"bg-teal-500",kit_engagement:"bg-teal-400",event_invited:"bg-indigo-300",event_registered:"bg-indigo-400",event_attended:"bg-emerald-500",event_no_show:"bg-rose-400",event_note:"bg-slate-400",score:"bg-green-500",temperature:"bg-orange-400",activity:"bg-slate-300"};function ZWn(){const{agentId:s}=oo(),t=Jn(),{item:n,timeline:r,valueShared:a,nextKit:i,isLoading:l,error:o,refetch:c}=wHn(s),{data:d=[]}=Nte(),{upsertAgent:u,moveStage:h}=A0(),{followUps:m,complete:p}=QF(),g=jHn(),{gmailEmail:x}=dx(),[y,v]=k.useState("all"),[_,j]=k.useState(!1),[C,A]=k.useState(!1),[M,I]=k.useState("call"),[P,R]=k.useState(""),[O,B]=k.useState(""),[U,G]=k.useState(!1),[H,Y]=k.useState(""),[se,ee]=k.useState(!1),[oe,me]=k.useState(""),[Q,te]=k.useState(new Date(Date.now()+3*864e5).toISOString().slice(0,10)),[le,fe]=k.useState(null),[_e,ve]=k.useState(!1),he=k.useMemo(()=>d.filter(ke=>ke.agent_id===s&&ke.status==="open").sort((ke,Fe)=>Fe.rank_score-ke.rank_score),[d,s]),Se=k.useMemo(()=>m.filter(ke=>ke.agent_id===s),[m,s]),Te=k.useMemo(()=>{const ke=Awt.find(Fe=>Fe.key===y);return!ke||!ke.kinds.length?r:r.filter(Fe=>ke.kinds.includes(Fe.kind))},[r,y]);if(l)return e.jsxs("div",{className:"space-y-4",children:[e.jsx(fn,{className:"h-8 w-40"}),e.jsx(fn,{className:"h-40 w-full rounded-2xl"}),e.jsx(fn,{className:"h-64 w-full rounded-2xl"})]});if(o)return e.jsxs(we,{className:"p-8 rounded-2xl text-center",children:[e.jsx("div",{className:"text-[15px] font-semibold text-slate-800",children:"We couldn't load this relationship."}),e.jsx("div",{className:"text-[13px] text-slate-500 mt-1",children:o.message}),e.jsxs($,{className:"rounded-full mt-4",onClick:()=>c(),children:[e.jsx(yo,{className:"h-4 w-4 mr-2"})," Try again"]})]});if(!n)return e.jsxs(we,{className:"p-8 rounded-2xl text-center",children:[e.jsx("div",{className:"text-[15px] font-semibold text-slate-800",children:"Agent not found"}),e.jsx("div",{className:"text-[13px] text-slate-500 mt-1",children:"This relationship may have been removed from your pipeline."}),e.jsx($,{className:"rounded-full mt-4",onClick:()=>t("/attract/relationships"),children:"Back to relationships"})]});const Ie=n.agent,Ue=n.signals,Be=WWn[Ie.temperature??""]??S2,je=()=>{g.mutate({agent_id:Ie.id,activity_type:M,title:P||`${M.replace(/_/g," ")} with ${ZA(Ie)}`,description:O||void 0},{onSuccess:()=>{j(!1),R(""),B("")}})},Ye=async()=>{var Fe;if(!H.trim())return;const ke=[(Fe=Ie.notes)==null?void 0:Fe.trim(),`[${new Date().toLocaleDateString()}] ${H.trim()}`].filter(Boolean).join(` `);u.mutate({id:Ie.id,first_name:Ie.first_name,notes:ke},{onSuccess:()=>{G(!1),Y(""),c()}}),g.mutate({agent_id:Ie.id,activity_type:"note",title:"Note added",description:H.trim()})},Ee=async()=>{if(!oe.trim()){ae.error("Give the follow-up a title");return}if(Se.find(Ge=>!Ge.completed_at&&Ge.title.trim().toLowerCase()===oe.trim().toLowerCase())){ae.error("An open follow-up with that title already exists");return}const{data:Fe}=await V.auth.getUser(),{error:Oe}=await HWn.from("attract_follow_ups").insert({user_id:Fe.user.id,agent_id:Ie.id,title:oe.trim(),due_at:new Date(`${Q}T12:00:00`).toISOString(),touch_type:"call",priority:"medium"});if(Oe){ae.error(Oe.message);return}ae.success("Follow-up created"),ee(!1),me(""),c()},Re=()=>{le&&(window.open(le.href,"_self"),g.mutate({agent_id:Ie.id,activity_type:le.kind,title:`${le.kind==="call"?"Called":le.kind==="text"?"Texted":"Emailed"} ${ZA(Ie)}`}),fe(null))};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-[12px] text-slate-500",children:[e.jsx(nr,{to:"/attract",className:"hover:text-violet-700",children:"Attract"}),e.jsx(fi,{className:"h-3 w-3"}),e.jsx(nr,{to:"/attract/relationships",className:"hover:text-violet-700",children:"Relationships"}),e.jsx(fi,{className:"h-3 w-3"}),e.jsx("span",{className:"text-slate-800 font-medium truncate",children:ZA(Ie)})]}),e.jsxs(we,{className:"rounded-2xl border-slate-200/70 overflow-hidden",children:[e.jsxs("div",{className:"bg-gradient-to-r from-[#0B0F1E] via-[#141a33] to-[#1d1b4b] p-5 sm:p-6 text-white",children:[e.jsxs($,{variant:"ghost",size:"sm",className:"text-slate-300 hover:text-white -ml-2 mb-3 rounded-full",onClick:()=>t(-1),children:[e.jsx(Ia,{className:"h-3.5 w-3.5 mr-1.5"})," Back"]}),e.jsxs("div",{className:"flex items-start gap-4 flex-wrap",children:[Ie.photo_url?e.jsx("img",{src:Ie.photo_url,alt:`${ZA(Ie)} headshot`,className:"h-16 w-16 rounded-2xl object-cover ring-2 ring-white/20"}):e.jsx("div",{className:"h-16 w-16 rounded-2xl bg-gradient-to-br from-violet-500 to-indigo-600 grid place-items-center text-xl font-semibold ring-2 ring-white/10",children:KWn(Ie)}),e.jsxs("div",{className:"flex-1 min-w-[220px]",children:[e.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:ZA(Ie)}),e.jsxs("div",{className:"text-[13px] text-slate-300 mt-1 flex flex-wrap items-center gap-x-2 gap-y-1",children:[e.jsx("span",{children:Ie.brokerage||"Brokerage not recorded"}),e.jsx("span",{className:"opacity-40",children:"·"}),e.jsx("span",{children:[Ie.city,Ie.state].filter(Boolean).join(", ")||"Market not recorded"}),Ie.is_demo&&e.jsx(qe,{className:"bg-amber-400/20 text-amber-200 border-transparent rounded-full",children:"Demo record"})]}),e.jsxs("div",{className:"flex flex-wrap gap-2 mt-3",children:[e.jsx(qe,{className:"rounded-full bg-white/10 text-white border-transparent",children:IWt(Ie.stage)}),e.jsxs(qe,{className:"rounded-full bg-white/10 text-white border-transparent capitalize inline-flex items-center gap-1",children:[e.jsx(Be,{className:"h-3 w-3"})," ",Ie.temperature??"temperature unset"]}),e.jsx(cJe,{score:n.score,className:"bg-white/10 text-white ring-white/20"}),(Ie.tags??[]).map(ke=>e.jsx(qe,{variant:"outline",className:"rounded-full bg-transparent text-slate-200 border-white/20",children:ke},ke))]})]}),e.jsxs("div",{className:"text-[12px] text-slate-300 space-y-1 min-w-[190px]",children:[e.jsx("div",{children:Ie.email?e.jsx("a",{className:"hover:text-white underline decoration-white/30",href:`mailto:${Ie.email}`,children:Ie.email}):"No email on file"}),e.jsx("div",{children:Ie.phone?e.jsx("a",{className:"hover:text-white underline decoration-white/30",href:`tel:${Ie.phone}`,children:Ie.phone}):"No phone on file"}),e.jsxs("div",{children:["Last meaningful touch: ",Ue.lastTouchAt?`${new Date(Ue.lastTouchAt).toLocaleDateString()} (${Ue.daysSinceTouch}d ago)`:"never logged"]}),e.jsxs("div",{children:["Next follow-up: ",Ie.next_follow_up_at?new Date(Ie.next_follow_up_at).toLocaleDateString():"none scheduled"]}),e.jsxs("div",{children:["Source: ",Ie.source||"not recorded"," · Owner: ",Ie.relationship_owner||"you"]})]})]})]}),e.jsxs("div",{className:"p-3 sm:p-4 bg-white flex flex-wrap gap-2",children:[e.jsxs($,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>A(!0),children:[e.jsx(ui,{className:"h-3.5 w-3.5 mr-1.5"})," Edit contact"]}),e.jsxs(zs,{open:_,onOpenChange:j,children:[e.jsx(yl,{asChild:!0,children:e.jsxs($,{size:"sm",className:"rounded-full btn-primary text-white",children:[e.jsx(Gr,{className:"h-3.5 w-3.5 mr-1.5"})," Log touch"]})}),e.jsxs(Rs,{children:[e.jsxs(Vs,{children:[e.jsx($s,{children:"Log a conversation"}),e.jsx(Cr,{children:"This records what already happened — it does not send anything."})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Type"}),e.jsxs(bs,{value:M,onValueChange:I,children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsx(vs,{children:["call","text","email","dm","meeting","note"].map(ke=>e.jsx(We,{value:ke,className:"capitalize",children:ke},ke))})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Title"}),e.jsx(be,{value:P,onChange:ke=>R(ke.target.value),placeholder:`Call with ${Ie.first_name}`})]}),e.jsxs("div",{children:[e.jsx(re,{children:"What happened"}),e.jsx(Ls,{rows:4,value:O,onChange:ke=>B(ke.target.value)})]})]}),e.jsx(kr,{children:e.jsx($,{className:"rounded-full btn-primary text-white",onClick:je,disabled:g.isPending,children:"Log it"})})]})]}),e.jsxs(zs,{open:U,onOpenChange:G,children:[e.jsx(yl,{asChild:!0,children:e.jsxs($,{size:"sm",variant:"outline",className:"rounded-full",children:[e.jsx(Z8,{className:"h-3.5 w-3.5 mr-1.5"})," Add note"]})}),e.jsxs(Rs,{children:[e.jsx(Vs,{children:e.jsx($s,{children:"Add a relationship note"})}),e.jsx(Ls,{rows:5,value:H,onChange:ke=>Y(ke.target.value),placeholder:"What did you learn about them?"}),e.jsx(kr,{children:e.jsx($,{className:"rounded-full btn-primary text-white",onClick:Ye,children:"Save note"})})]})]}),e.jsxs($,{size:"sm",variant:"outline",className:"rounded-full",disabled:!Ie.phone,onClick:()=>Ie.phone&&fe({kind:"call",href:`tel:${Ie.phone}`}),children:[e.jsx(ka,{className:"h-3.5 w-3.5 mr-1.5"})," Call"]}),e.jsxs($,{size:"sm",variant:"outline",className:"rounded-full",disabled:!Ie.phone,onClick:()=>Ie.phone&&fe({kind:"text",href:`sms:${Ie.phone}`}),children:[e.jsx(bo,{className:"h-3.5 w-3.5 mr-1.5"})," Text"]}),e.jsxs($,{size:"sm",variant:"outline",className:"rounded-full",disabled:!Ie.email,onClick:()=>Ie.email&&ve(!0),children:[e.jsx(pn,{className:"h-3.5 w-3.5 mr-1.5"})," Email"]}),e.jsx($,{size:"sm",variant:"outline",className:"rounded-full",asChild:!0,children:e.jsxs(nr,{to:"/attract/provide/kits",children:[e.jsx(xb,{className:"h-3.5 w-3.5 mr-1.5"})," Share kit"]})}),e.jsx($,{size:"sm",variant:"outline",className:"rounded-full",asChild:!0,children:e.jsxs(nr,{to:"/attract/events",children:[e.jsx(i1,{className:"h-3.5 w-3.5 mr-1.5"})," Invite to event"]})}),e.jsxs(zs,{open:se,onOpenChange:ee,children:[e.jsx(yl,{asChild:!0,children:e.jsxs($,{size:"sm",variant:"outline",className:"rounded-full",children:[e.jsx(sa,{className:"h-3.5 w-3.5 mr-1.5"})," Create follow-up"]})}),e.jsxs(Rs,{children:[e.jsx(Vs,{children:e.jsx($s,{children:"Create a follow-up"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(re,{children:"What will you do?"}),e.jsx(be,{value:oe,onChange:ke=>me(ke.target.value),placeholder:"Call about their Q3 goals"})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Due"}),e.jsx(be,{type:"date",value:Q,onChange:ke=>te(ke.target.value)})]})]}),e.jsx(kr,{children:e.jsx($,{className:"rounded-full btn-primary text-white",onClick:Ee,children:"Create"})})]})]}),e.jsxs(bs,{value:GB(Ie.stage).key,onValueChange:ke=>{const Fe=hJe(ke);Fe!==Ie.stage&&h.mutate({id:Ie.id,to_stage:Fe,from_stage:Ie.stage})},children:[e.jsxs(ys,{className:"w-[230px] h-9 rounded-full text-[13px]","aria-label":"Change relationship stage",children:[e.jsx(N5,{className:"h-3.5 w-3.5 mr-1.5 opacity-60"}),e.jsx(_s,{})]}),e.jsx(vs,{children:GWn.map(ke=>e.jsx(We,{value:ke.key,children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"h-2 w-2 rounded-full",style:{background:ke.color}}),ke.label]})},ke.key))})]})]})]}),e.jsx(zs,{open:!!le,onOpenChange:ke=>!ke&&fe(null),children:e.jsxs(Rs,{children:[e.jsxs(Vs,{children:[e.jsxs($s,{children:["Open your ",(le==null?void 0:le.kind)==="email"?"email app":(le==null?void 0:le.kind)==="text"?"messaging app":"phone app","?"]}),e.jsx(Cr,{children:"Attract will open your own device app so you send it personally. Nothing is sent by LevelUp. We'll log this as a touch."})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"ghost",className:"rounded-full",onClick:()=>fe(null),children:"Cancel"}),e.jsx($,{className:"rounded-full btn-primary text-white",onClick:Re,children:"Continue"})]})]})}),e.jsxs(ya,{defaultValue:"overview",children:[e.jsx(va,{className:"rounded-full bg-white border border-slate-200 p-1 flex-wrap h-auto",children:["overview","timeline","value","events","followups","notes"].map(ke=>e.jsx(is,{value:ke,className:"rounded-full text-[13px] capitalize data-[state=active]:bg-violet-600 data-[state=active]:text-white",children:ke==="value"?"Value shared":ke==="followups"?"Follow-ups":ke==="notes"?"Notes & insights":ke},ke))}),e.jsxs(cs,{value:"overview",className:"mt-5 space-y-5",children:[e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-5",children:[e.jsxs("div",{className:"lg:col-span-2 space-y-5",children:[e.jsxs(we,{className:"p-5 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wider font-semibold text-violet-600 mb-3",children:"Next best relationship touch"}),he[0]?e.jsx(gCe,{rec:he[0],agentName:ZA(Ie),agentStage:Ie.stage,showAgentLink:!1,className:"border-0 shadow-none"}):e.jsx("div",{className:"text-[13.5px] text-slate-500",children:"No open recommendation right now. Recommendations appear when real signals exist — a kit opened, an event attended, an overdue commitment, or silence beyond your cadence."})]}),e.jsxs(we,{className:"p-5 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wider font-semibold text-slate-500 mb-3",children:"What we actually know"}),e.jsxs("div",{className:"grid sm:grid-cols-2 gap-4",children:[e.jsx(k9,{label:"Goals",children:Ie.goals||e.jsx(cW,{label:"their goals"})}),e.jsx(k9,{label:"Challenges",children:Ie.challenges||e.jsx(cW,{label:"their challenges"})}),e.jsx(k9,{label:"Interests",children:Ie.interests||e.jsx(cW,{label:"interests"})}),e.jsx(k9,{label:"Production context",children:Ie.production_context||e.jsx(cW,{label:"production context"})}),e.jsx(k9,{label:"Primary pillar",children:Ie.primary_pillar?e.jsx("span",{className:"capitalize",children:Ie.primary_pillar}):e.jsx(cW,{label:"a pillar"})}),e.jsx(k9,{label:"Added to pipeline",children:new Date(Ie.created_at).toLocaleDateString()})]})]}),e.jsx("div",{className:"grid sm:grid-cols-2 lg:grid-cols-4 gap-3",children:[{label:"Touches (90d)",value:Ue.touches90},{label:"Kits shared",value:Ue.shares.length},{label:"Kit opens",value:Ue.totalKitOpens},{label:"Events attended",value:Ue.attended}].map(ke=>e.jsxs(we,{className:"p-4 rounded-2xl",children:[e.jsx("div",{className:"text-2xl font-semibold tabular-nums text-slate-900",children:ke.value}),e.jsx("div",{className:"text-[11.5px] text-slate-500 mt-0.5",children:ke.label})]},ke.label))})]}),e.jsxs(we,{className:"p-5 rounded-2xl h-fit",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wider font-semibold text-slate-500 mb-3",children:"Relationship health"}),e.jsx(bWt,{score:n.score})]})]}),he.length>1&&e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wider font-semibold text-slate-500",children:"Other open recommendations"}),he.slice(1).map(ke=>e.jsx(gCe,{rec:ke,agentName:ZA(Ie),showAgentLink:!1,compact:!0},ke.id))]})]}),e.jsx(cs,{value:"timeline",className:"mt-5",children:e.jsxs(we,{className:"p-4 sm:p-5 rounded-2xl",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 flex-wrap mb-4",children:[e.jsx("div",{className:"flex gap-1.5 flex-wrap",children:Awt.map(ke=>e.jsx("button",{onClick:()=>v(ke.key),className:Ot("rounded-full px-3 py-1.5 text-[12px] font-medium transition-colors",y===ke.key?"bg-violet-600 text-white":"bg-slate-100 text-slate-600 hover:bg-slate-200"),children:ke.label},ke.key))}),e.jsxs($,{size:"sm",className:"rounded-full btn-primary text-white",onClick:()=>j(!0),children:[e.jsx(Gr,{className:"h-3.5 w-3.5 mr-1.5"})," Log something"]})]}),Te.length?e.jsxs("ol",{className:"relative pl-5 sm:pl-6",children:[e.jsx("span",{"aria-hidden":!0,className:"absolute left-1.5 top-1 bottom-1 w-px bg-slate-200"}),Te.map(ke=>e.jsxs("li",{className:"relative pb-5",children:[e.jsx("span",{"aria-hidden":!0,className:Ot("absolute -left-[15px] sm:-left-[18px] top-1.5 h-2.5 w-2.5 rounded-full ring-2 ring-white",YWn[ke.kind]??"bg-slate-300")}),e.jsx("div",{className:"text-[13.5px] font-medium text-slate-900",children:ke.title}),ke.detail&&e.jsx("div",{className:"text-[12.5px] text-slate-600 mt-0.5 whitespace-pre-wrap",children:ke.detail}),e.jsxs("div",{className:"text-[11px] text-slate-400 mt-1",children:[new Date(ke.at).toLocaleString()," · ",e.jsx("span",{className:"capitalize",children:ke.kind.replace(/_/g," ")})]})]},ke.id))]}):e.jsx("div",{className:"py-10 text-center text-[13.5px] text-slate-500",children:"Nothing in this view yet. Log a conversation to start the history."})]})}),e.jsxs(cs,{value:"value",className:"mt-5 space-y-4",children:[i&&e.jsxs(we,{className:"p-4 rounded-2xl bg-gradient-to-r from-teal-50 to-emerald-50 border-teal-100",children:[e.jsx("div",{className:"text-[10.5px] uppercase tracking-wider font-semibold text-teal-700",children:"Suggested next kit"}),e.jsx("div",{className:"text-[15px] font-semibold text-slate-900 mt-1",children:i.kit.title}),e.jsx("div",{className:"text-[12.5px] text-slate-600 mt-0.5",children:i.why}),e.jsx($,{size:"sm",className:"rounded-full mt-3 btn-primary text-white",asChild:!0,children:e.jsx(nr,{to:"/attract/provide/kits",children:"Open Resource Kits"})})]}),a.length?a.map(ke=>e.jsxs(we,{className:"p-4 sm:p-5 rounded-2xl",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 flex-wrap",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[15px] font-semibold text-slate-900",children:ke.kitTitle}),e.jsxs("div",{className:"text-[12px] text-slate-500 mt-0.5",children:["Sent ",new Date(ke.share.created_at).toLocaleDateString()," ·",ke.firstViewedAt?` first viewed ${new Date(ke.firstViewedAt).toLocaleDateString()}`:" never viewed",ke.lastViewedAt?` · last viewed ${new Date(ke.lastViewedAt).toLocaleDateString()}`:""]})]}),e.jsx(qe,{variant:"outline",className:Ot("rounded-full border-transparent ring-1",ke.classification==="High Intent"?"bg-rose-50 text-rose-700 ring-rose-200":ke.classification==="Engaged"?"bg-teal-50 text-teal-700 ring-teal-200":ke.classification==="Viewed"?"bg-amber-50 text-amber-700 ring-amber-200":"bg-slate-50 text-slate-600 ring-slate-200"),children:ke.classification})]}),e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-5 gap-3 mt-4",children:[["Visits",ke.visits],["Downloads",ke.downloads],["Link clicks",ke.ctaClicks],["Questions",ke.questions],["Meeting asks",ke.meetingRequests]].map(([Fe,Oe])=>e.jsxs("div",{className:"rounded-xl bg-slate-50 p-2.5",children:[e.jsx("div",{className:"text-[17px] font-semibold tabular-nums text-slate-900",children:Oe}),e.jsx("div",{className:"text-[10.5px] text-slate-500",children:Fe})]},Fe))}),e.jsxs("div",{className:"mt-3 text-[12.5px] text-slate-600 space-y-1",children:[e.jsxs("div",{children:["Link status: ",e.jsx("span",{className:"capitalize font-medium",children:ke.share.status})]}),e.jsxs("div",{children:["Follow-up after sharing: ",ke.followUp?`${ke.followUp.title}${ke.followUp.completed_at?" (completed)":" (open)"}`:"none created"]}),e.jsxs("div",{children:["Stage movement after sharing: ",ke.stageAdvancedAfter?`moved to ${ke.stageAdvancedAfter.to_stage.replace(/_/g," ")} on ${new Date(ke.stageAdvancedAfter.created_at).toLocaleDateString()}`:"no stage movement yet"]})]}),e.jsx($,{size:"sm",variant:"outline",className:"rounded-full mt-3",asChild:!0,children:e.jsxs("a",{href:ke.shareUrl,target:"_blank",rel:"noreferrer",children:["Open share link ",e.jsx(Ir,{className:"h-3.5 w-3.5 ml-1.5"})]})})]},ke.share.id)):e.jsxs(we,{className:"p-8 rounded-2xl text-center",children:[e.jsx("div",{className:"text-[15px] font-semibold text-slate-800",children:"Nothing shared yet"}),e.jsx("div",{className:"text-[13px] text-slate-500 mt-1",children:"Value first is how this whole system works. Share a Resource Kit to begin."})]})]}),e.jsx(cs,{value:"events",className:"mt-5 space-y-3",children:Ue.attendees.length?Ue.attendees.map(ke=>e.jsx(we,{className:"p-4 rounded-2xl",children:e.jsxs("div",{className:"flex items-center justify-between gap-3 flex-wrap",children:[e.jsxs("div",{children:[e.jsx(nr,{to:`/attract/events/${ke.event_id}`,className:"text-[14.5px] font-semibold text-slate-900 hover:text-violet-700",children:"View event"}),e.jsxs("div",{className:"text-[12px] text-slate-500 mt-0.5",children:[ke.invited_at&&`Invited ${new Date(ke.invited_at).toLocaleDateString()} · `,ke.registered_at?`Registered ${new Date(ke.registered_at).toLocaleDateString()}`:"Not registered",ke.checked_in_at&&` · Attended ${new Date(ke.checked_in_at).toLocaleDateString()}`,ke.no_show_at&&" · No-show"]})]}),e.jsx(qe,{variant:"outline",className:"rounded-full capitalize",children:ke.followup_status?`follow-up ${ke.followup_status}`:ke.status??"invited"})]})},ke.id)):e.jsxs(we,{className:"p-8 rounded-2xl text-center",children:[e.jsx(tb,{className:"h-6 w-6 mx-auto text-slate-400 mb-2"}),e.jsx("div",{className:"text-[15px] font-semibold text-slate-800",children:"Never invited to an event"}),e.jsx("div",{className:"text-[13px] text-slate-500 mt-1",children:"Events are the fastest way to deepen a relationship."}),e.jsx($,{size:"sm",className:"rounded-full mt-4 btn-primary text-white",asChild:!0,children:e.jsx(nr,{to:"/attract/events",children:"See your events"})})]})}),e.jsx(cs,{value:"followups",className:"mt-5 space-y-3",children:Se.length?Se.map(ke=>{const Fe=!ke.completed_at&&ke.due_at&&new Date(ke.due_at)p.mutate(ke.id),children:[e.jsx(Gr,{className:"h-3.5 w-3.5 mr-1.5"})," Complete"]})]},ke.id)}):e.jsxs(we,{className:"p-8 rounded-2xl text-center",children:[e.jsx("div",{className:"text-[15px] font-semibold text-slate-800",children:"No follow-ups yet"}),e.jsx($,{size:"sm",className:"rounded-full mt-4 btn-primary text-white",onClick:()=>ee(!0),children:"Create one"})]})}),e.jsxs(cs,{value:"notes",className:"mt-5 space-y-4",children:[e.jsxs(we,{className:"p-5 rounded-2xl",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wider font-semibold text-slate-500",children:"Your notes"}),e.jsx($,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>G(!0),children:"Add note"})]}),Ie.notes?e.jsx("div",{className:"text-[13.5px] text-slate-700 whitespace-pre-wrap",children:Ie.notes}):e.jsx("div",{className:"text-[13px] text-slate-500",children:"No notes recorded yet."})]}),e.jsxs(we,{className:"p-5 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wider font-semibold text-slate-500 mb-2",children:"What the data says"}),e.jsx("ul",{className:"text-[13px] text-slate-700 space-y-1.5 list-disc pl-4",children:[...n.score.positives.map(ke=>`Strength: ${ke}`),...n.score.negatives.map(ke=>`Risk: ${ke}`),...n.score.improvements.map(ke=>`Next: ${ke}`)].map((ke,Fe)=>e.jsx("li",{children:ke},Fe))})]})]})]}),e.jsx(mJe,{agent:Ie,open:C,onOpenChange:A,onDeleted:()=>t("/attract/relationships")}),Ie.email&&e.jsx(W2,{open:_e,onOpenChange:ve,contact:{id:Ie.id,first_name:Ie.preferred_name||Ie.first_name,last_name:Ie.last_name||"",email:Ie.email},gmailEmail:x,sendSource:"attract",logTouchpoint:!1,onSendComplete:()=>{g.mutate({agent_id:Ie.id,activity_type:"email",title:`Emailed ${ZA(Ie)}`})}})]})}const XWn=[{key:"all",label:"Everything"},{key:"high_intent",label:"High intent"},{key:"resource_follow_up",label:"Value shared"},{key:"event_follow_up",label:"Events"},{key:"commitment",label:"Commitments"},{key:"silence",label:"Going quiet"},{key:"stage",label:"Stage momentum"},{key:"new_relationship",label:"New connections"}];function QWn(){const{intel:s,byId:t,isLoading:n,error:r,refetch:a}=k6(),{data:i=[],isLoading:l}=Nte(),o=YTe();ZTe();const[c,d]=k.useState(""),[u,h]=k.useState("all"),[m,p]=k.useState("open"),g=v=>{var j;const _=(j=t.get(v))==null?void 0:j.agent;return _?[_.first_name,_.last_name].filter(Boolean).join(" "):"Unknown agent"},x=k.useMemo(()=>{const v=Date.now();return i.filter(_=>m==="open"?_.status==="open"||_.status==="snoozed"&&_.snoozed_until&&+new Date(_.snoozed_until)<=v:m==="snoozed"?_.status==="snoozed":m==="done"?_.status==="completed":m==="dismissed"?_.status==="dismissed":!0).filter(_=>u==="all"||_.signal_group===u).filter(_=>{if(!c.trim())return!0;const j=c.toLowerCase();return g(_.agent_id).toLowerCase().includes(j)||_.title.toLowerCase().includes(j)||(_.reasons??[]).join(" ").toLowerCase().includes(j)}).sort((_,j)=>j.rank_score-_.rank_score)},[i,m,u,c,t]),y=k.useMemo(()=>{const v=i.filter(_=>_.status==="open");return{open:v.length,urgent:v.filter(_=>_.priority==="urgent").length,highIntent:v.filter(_=>_.signal_group==="high_intent").length,overdue:v.filter(_=>_.suggested_due_at&&+new Date(_.suggested_due_at)e.jsx(fn,{className:"h-28 w-full rounded-2xl"},v))}):r?e.jsxs(we,{className:"p-8 rounded-2xl text-center",children:[e.jsx("div",{className:"text-[15px] font-semibold text-slate-800",children:"We couldn't load your opportunities."}),e.jsx("div",{className:"text-[13px] text-slate-500 mt-1",children:r.message}),e.jsxs($,{className:"rounded-full mt-4",onClick:()=>a(),children:[e.jsx(yo,{className:"h-4 w-4 mr-2"})," Try again"]})]}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-end justify-between gap-4 flex-wrap",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11.5px] uppercase tracking-wider font-medium text-violet-600",children:"Relationship Intelligence"}),e.jsx("h1",{className:"text-2xl font-semibold tracking-tight text-slate-900 mt-0.5",children:"Who needs attention"}),e.jsx("p",{className:"text-[13.5px] text-slate-500 mt-1 max-w-2xl",children:"Ranked by real signals only — value they engaged with, events they attended, commitments you made, and silence past your cadence. Nothing here is invented."})]}),e.jsxs($,{variant:"outline",className:"rounded-full",onClick:()=>o.mutate(s),disabled:o.isPending,children:[e.jsx(yo,{className:Ot("h-3.5 w-3.5 mr-1.5",o.isPending&&"animate-spin")})," Recalculate"]})]}),e.jsx("div",{className:"grid grid-cols-2 lg:grid-cols-4 gap-3",children:[{label:"Open recommendations",value:y.open},{label:"Urgent",value:y.urgent},{label:"High intent signals",value:y.highIntent},{label:"Past suggested date",value:y.overdue}].map(v=>e.jsxs(we,{className:"p-4 rounded-2xl",children:[e.jsx("div",{className:"text-2xl font-semibold tabular-nums text-slate-900",children:v.value}),e.jsx("div",{className:"text-[11.5px] text-slate-500 mt-0.5",children:v.label})]},v.label))}),e.jsxs(we,{className:"p-3 rounded-2xl flex flex-wrap items-center gap-2",children:[e.jsxs("div",{className:"relative flex-1 min-w-[220px]",children:[e.jsx(Yr,{className:"h-4 w-4 absolute left-3 top-1/2 -translate-y-1/2 text-slate-400"}),e.jsx(be,{value:c,onChange:v=>d(v.target.value),placeholder:"Search agents or reasons",className:"pl-9 rounded-full h-9","aria-label":"Search recommendations"})]}),e.jsxs(bs,{value:u,onValueChange:h,children:[e.jsxs(ys,{className:"w-[190px] h-9 rounded-full text-[13px]",children:[e.jsx(v2,{className:"h-3.5 w-3.5 mr-1.5 opacity-60"}),e.jsx(_s,{})]}),e.jsx(vs,{children:XWn.map(v=>e.jsx(We,{value:v.key,children:v.label},v.key))})]}),e.jsxs(bs,{value:m,onValueChange:p,children:[e.jsx(ys,{className:"w-[150px] h-9 rounded-full text-[13px]",children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"open",children:"Needs action"}),e.jsx(We,{value:"snoozed",children:"Snoozed"}),e.jsx(We,{value:"done",children:"Completed"}),e.jsx(We,{value:"dismissed",children:"Dismissed"}),e.jsx(We,{value:"all",children:"All"})]})]})]}),x.length?e.jsx("div",{className:"space-y-3",children:x.map(v=>{var _;return e.jsx(gCe,{rec:v,agentName:g(v.agent_id),agentStage:(_=t.get(v.agent_id))==null?void 0:_.agent.stage},v.id)})}):i.length?e.jsx(qHn,{label:"Nothing matches this view. Try switching the filter."}):e.jsxs(we,{className:"p-10 rounded-2xl text-center",children:[e.jsx(kn,{className:"h-6 w-6 mx-auto text-violet-500 mb-2"}),e.jsx("div",{className:"text-[15px] font-semibold text-slate-800",children:"No recommendations yet"}),e.jsx("p",{className:"text-[13px] text-slate-500 mt-1 max-w-md mx-auto",children:"Attract only recommends what it can prove. Add agents to your pipeline, share a Resource Kit, or invite someone to an event — real signals will show up here."}),e.jsxs("div",{className:"flex gap-2 justify-center mt-4",children:[e.jsx($,{className:"rounded-full btn-primary text-white",asChild:!0,children:e.jsx(nr,{to:"/attract/pipeline",children:"Open pipeline"})}),e.jsx($,{variant:"outline",className:"rounded-full",asChild:!0,children:e.jsx(nr,{to:"/attract/provide/kits",children:"Share a kit"})})]})]}),!!x.length&&e.jsxs("div",{className:"text-[11.5px] text-slate-400",children:["Showing ",x.length," of ",i.length," tracked recommendations · grouped signals: ",[...new Set(x.map(v=>MWt(v.signal_group)))].join(", ")]})]})}const X8e=s=>[s.first_name,s.last_name].filter(Boolean).join(" ");function JWn(s=new Date){const t=new Date(s),n=t.getDay(),r=n===0?-6:1-n;return t.setDate(t.getDate()+r),t.setHours(0,0,0,0),t}function iKt(s,t,n=new Date){const r=JWn(n),a=new Date(r.getTime()+6*864e5),i=new Date(n.getTime()-7*864e5),c=s.filter(P=>P.primary).slice().sort((P,R)=>R.primary.rank_score-P.primary.rank_score||P.score.score-R.score.score).slice(0,5).map((P,R)=>({agent_id:P.agent.id,agent_name:X8e(P.agent),rank:R+1,reason:P.primary.reasons.join(" · "),channel:P.primary.channel,draft_message:P.primary.draft_message,score:P.score.score,stage:P.agent.stage})),d=P=>s.map(R=>{const O=P(R);return O?{agent_id:R.agent.id,agent_name:X8e(R.agent),detail:O}:null}).filter(Boolean).slice(0,8),u=d(P=>P.signals.meetingRequests>0||P.signals.questions>0||P.signals.highIntentShares.some(R=>R.engagement_level==="high_intent")?`${P.signals.meetingRequests} meeting request(s), ${P.signals.questions} question(s), ${P.signals.totalKitOpens} kit open(s)`:null),h=d(P=>P.recommendations.some(R=>R.rec_key==="renewed_interest")?"Came back to a kit you shared after going quiet":null),m=d(P=>P.signals.overdueFollowUps.length?`${P.signals.overdueFollowUps.length} overdue follow-up(s) — oldest: ${P.signals.overdueFollowUps[0].title}`:null),p=d(P=>P.signals.daysSinceTouch!==null&&P.signals.daysSinceTouch>60?`${P.signals.daysSinceTouch} days since a real conversation`:null),g=t.shares.filter(P=>new Date(P.created_at)>=i),x={shares:g.length,opened:t.shares.filter(P=>P.first_opened_at&&new Date(P.first_opened_at)>=i).length,engaged:t.shares.filter(P=>P.engagement_level==="engaged").length,high_intent:t.shares.filter(P=>P.engagement_level==="high_intent").length,downloads:t.kitEvents.filter(P=>P.event_type==="file_download"&&new Date(P.created_at)>=i).length,questions:t.kitEvents.filter(P=>P.event_type==="question_submitted"&&new Date(P.created_at)>=i).length},y={invited:t.attendees.filter(P=>P.invited_at&&new Date(P.invited_at)>=i).length,registered:t.attendees.filter(P=>P.registered_at&&new Date(P.registered_at)>=i).length,attended:t.attendees.filter(P=>P.checked_in_at&&new Date(P.checked_in_at)>=i).length,no_shows:t.attendees.filter(P=>P.no_show_at&&new Date(P.no_show_at)>=i).length,follow_ups_pending:t.attendees.filter(P=>P.checked_in_at&&P.followup_status!=="done").length,upcoming:t.events.filter(P=>P.starts_at&&new Date(P.starts_at)>n&&P.status==="published").sort((P,R)=>+new Date(P.starts_at)-+new Date(R.starts_at)).slice(0,3).map(P=>({title:P.title,starts_at:P.starts_at??null}))},v=[...s.filter(P=>P.agent.next_follow_up_at&&new Date(P.agent.next_follow_up_at)>n&&hy(n,P.agent.next_follow_up_at)<=7).slice(0,5).map(P=>({label:X8e(P.agent),detail:`Follow-up scheduled ${new Date(P.agent.next_follow_up_at).toLocaleDateString()}`})),...y.upcoming.map(P=>({label:P.title,detail:P.starts_at?`Event on ${new Date(P.starts_at).toLocaleDateString()}`:"Event scheduled"}))].slice(0,6),_=t.activities.filter(P=>new Date(P.created_at)>=i),j={produce:0,influence:0,provide:0,connect:0};for(const P of _)P.pillar&&j[P.pillar]!==void 0&&j[P.pillar]++;const C=Object.entries(j).map(([P,R])=>({pillar:P,count:R})),A=C.slice().sort((P,R)=>P.count-R.count)[0],M=t.primaryPillar?`Your 90-day primary pillar is ${t.primaryPillar}. This week your lightest pillar was ${A.pillar} (${A.count} activities) — give it one deliberate rep.`:`Your lightest pillar this week was ${A.pillar} (${A.count} activities). Pick one action there.`,I={advanced:t.stageChanges.filter(P=>new Date(P.created_at)>=i).length,follow_ups_completed:t.followUps.filter(P=>P.completed_at&&new Date(P.completed_at)>=i).length,conversations_logged:_.filter(P=>["touch_logged","call","text","email","dm","meeting"].includes(P.activity_type)).length,kits_shared:g.length};return{week_start:r.toISOString().slice(0,10),week_end:a.toISOString().slice(0,10),generated_at:n.toISOString(),conversations:c,high_intent:u,renewed:h,overdue:m,stale:p,kit_summary:x,event_summary:y,upcoming_opportunities:v,pillar_balance:C,recommended_focus:M,wins:I}}function Jwt(s,t){const n=l=>String(l??"").replace(/[<>&]/g,o=>({"<":"<",">":">","&":"&"})[o]),r=(l,o)=>o?`
${n(l)}
${o}`:"",a=l=>l.length?`
    ${l.map(o=>`
  • ${n(o.agent_name)} — ${n(o.detail)}
  • `).join("")}
`:"",i=s.conversations.map(l=>`
${l.rank}. ${n(l.agent_name)} ${n(l.channel.replace(/_/g," "))} health ${l.score}
Why: ${n(l.reason)}
${n(l.draft_message)}
Open relationship →
`).join("");return`
${r("Five conversations for this week",i||'
No recommended conversations yet — add agents to your pipeline.
')} ${r("High-intent signals",a(s.high_intent))} ${r("Renewed interest",a(s.renewed))} ${r("Overdue commitments",a(s.overdue))} ${r("Going quiet",a(s.stale))} ${r("Resource kit engagement",`
${s.kit_summary.shares} shared · ${s.kit_summary.opened} opened · ${s.kit_summary.engaged} engaged · ${s.kit_summary.high_intent} high intent · ${s.kit_summary.downloads} downloads · ${s.kit_summary.questions} questions
`)} ${r("Events",`
${s.event_summary.invited} invited · ${s.event_summary.registered} registered · ${s.event_summary.attended} attended · ${s.event_summary.no_shows} no-shows · ${s.event_summary.follow_ups_pending} follow-ups pending
`)} ${r("Four-pillar balance",`
${s.pillar_balance.map(l=>`${l.pillar}: ${l.count}`).join(" · ")}
${n(s.recommended_focus)}
`)} ${r("Wins this week",`
${s.wins.advanced} relationships advanced · ${s.wins.follow_ups_completed} follow-ups completed · ${s.wins.conversations_logged} conversations logged · ${s.wins.kits_shared} kits shared
`)}
LevelUp Attract
Your Weekly Attraction Digest
Week of ${s.week_start} → ${s.week_end}
Open Relationship Opportunities
`}const h3=V;function eKn(){const{user:s}=ks(),t=ls(),n=pt({queryKey:["attract-digest-settings",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:a,error:i}=await h3.from("attract_digest_settings").select("*").eq("user_id",s.id).maybeSingle();if(i)throw i;return a??null}}),r=Nt({mutationFn:async a=>{const{error:i}=await h3.from("attract_digest_settings").upsert({user_id:s.id,...a},{onConflict:"user_id"});if(i)throw i},onSuccess:()=>{t.invalidateQueries({queryKey:["attract-digest-settings"]}),ae.success("Digest settings saved")},onError:a=>ae.error(a.message)});return{settings:n.data,isLoading:n.isLoading,save:r}}function tKn(){const{user:s}=ks();return pt({queryKey:["attract-digests",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await h3.from("attract_digests").select("*").order("week_start",{ascending:!1}).limit(26);if(n)throw n;return t??[]}})}function sKn(s){const t=ls(),n=pt({queryKey:["attract-digest-items",s],enabled:!!s,queryFn:async()=>{const{data:a,error:i}=await h3.from("attract_digest_items").select("*").eq("digest_id",s).order("rank");if(i)throw i;return a??[]}}),r=Nt({mutationFn:async a=>{const{error:i}=await h3.from("attract_digest_items").update({completed_at:new Date().toISOString()}).eq("id",a);if(i)throw i},onSuccess:()=>{t.invalidateQueries({queryKey:["attract-digest-items",s]}),ae.success("Marked as done")}});return{items:n.data??[],isLoading:n.isLoading,markComplete:r}}function nKn(){const{user:s}=ks(),t=ls();return Nt({mutationFn:async n=>{const{data:r,error:a}=await h3.from("attract_digests").upsert({user_id:s.id,week_start:n.week_start,payload:n,delivery_status:"generated",generated_at:n.generated_at},{onConflict:"user_id,week_start"}).select("id").single();if(a)throw a;const i=r.id;await h3.from("attract_digest_items").delete().eq("digest_id",i).is("completed_at",null);const{data:l}=await h3.from("attract_digest_items").select("agent_id").eq("digest_id",i),o=new Set((l??[]).map(d=>d.agent_id)),c=n.conversations.filter(d=>!o.has(d.agent_id)).map(d=>({digest_id:i,user_id:s.id,agent_id:d.agent_id,rank:d.rank,agent_name:d.agent_name,reason:d.reason,channel:d.channel,draft_message:d.draft_message}));if(c.length){const{error:d}=await h3.from("attract_digest_items").insert(c);if(d)throw d}return i},onSuccess:()=>{t.invalidateQueries({queryKey:["attract-digests"]}),t.invalidateQueries({queryKey:["attract-digest-items"]})},onError:n=>ae.error(n.message)})}function rKn(){const s=ls();return Nt({mutationFn:async t=>{const{data:n,error:r}=await V.functions.invoke("attract-send-digest",{body:t});if(r)throw r;return n},onSuccess:t=>{s.invalidateQueries({queryKey:["attract-digests"]}),t!=null&&t.ok?ae.success("Digest email sent"):ae.error((t==null?void 0:t.reason)||"Email delivery is not configured yet")},onError:t=>ae.error(t.message??"Send failed")})}const aKn=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];function S9({title:s,children:t}){return e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wider font-semibold text-slate-500 mb-2",children:s}),t]})}function Cie({rows:s,empty:t}){return s.length?e.jsx("ul",{className:"space-y-1.5",children:s.map(n=>e.jsxs("li",{className:"text-[13px] text-slate-700",children:[e.jsx(nr,{to:`/attract/agents/${n.agent_id}`,className:"font-medium text-slate-900 hover:text-violet-700",children:n.agent_name}),e.jsxs("span",{className:"text-slate-500",children:[" — ",n.detail]})]},n.agent_id+n.detail))}):e.jsx("div",{className:"text-[13px] text-slate-500",children:t})}function iKn(){var M;const{user:s}=ks(),{intel:t,dataset:n,isLoading:r}=k6(),{settings:a,save:i}=eKn(),{data:l=[]}=tKn(),o=nKn(),c=rKn(),[d,u]=k.useState(),h=d??((M=l[0])==null?void 0:M.id),{items:m,markComplete:p}=sKn(h),[g,x]=k.useState(""),y=k.useMemo(()=>n?iKt(t,n):null,[t,n]),v=l.find(I=>I.id===h),_=(v==null?void 0:v.payload)??y,j=g||(a==null?void 0:a.email)||(s==null?void 0:s.email)||"",C=()=>{y&&o.mutate(y,{onSuccess:I=>{u(I),ae.success("This week's digest is ready")}})},A=I=>{if(!_)return;if(!j){ae.error("Add an email address first");return}const P=R=>c.mutate({digestId:R,to:j,subject:`Your Weekly Attraction Digest — ${_.week_start}`,html:Jwt(_,window.location.origin),test:I});v?P(v.id):y&&o.mutate(y,{onSuccess:R=>{u(R),P(R)}})};return r||!_?e.jsxs("div",{className:"space-y-4",children:[e.jsx(fn,{className:"h-10 w-56"}),e.jsx(fn,{className:"h-72 w-full rounded-2xl"})]}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-end justify-between gap-4 flex-wrap",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11.5px] uppercase tracking-wider font-medium text-violet-600",children:"Relationship Intelligence"}),e.jsx("h1",{className:"text-2xl font-semibold tracking-tight text-slate-900 mt-0.5",children:"Weekly Attraction Digest"}),e.jsxs("p",{className:"text-[13.5px] text-slate-500 mt-1",children:["Week of ",new Date(`${_.week_start}T12:00:00`).toLocaleDateString()," – ",new Date(`${_.week_end}T12:00:00`).toLocaleDateString(),v&&e.jsxs(e.Fragment,{children:[" · ",e.jsx("span",{className:"capitalize",children:v.delivery_status.replace(/_/g," ")}),v.sent_at?` ${new Date(v.sent_at).toLocaleString()}`:""]})]})]}),e.jsxs("div",{className:"flex gap-2 flex-wrap",children:[e.jsxs($,{variant:"outline",className:"rounded-full",onClick:C,disabled:o.isPending,children:[e.jsx(yo,{className:Ot("h-3.5 w-3.5 mr-1.5",o.isPending&&"animate-spin")})," Regenerate"]}),e.jsxs($,{variant:"outline",className:"rounded-full",onClick:()=>{navigator.clipboard.writeText(Jwt(_,window.location.origin)),ae.success("Digest HTML copied")},children:[e.jsx(Da,{className:"h-3.5 w-3.5 mr-1.5"})," Copy HTML"]}),e.jsxs($,{className:"rounded-full btn-primary text-white",onClick:()=>A(!0),disabled:c.isPending,children:[e.jsx(Wr,{className:"h-3.5 w-3.5 mr-1.5"})," Email it to me"]})]})]}),e.jsxs(ya,{defaultValue:"digest",children:[e.jsx(va,{className:"rounded-full bg-white border border-slate-200 p-1",children:[["digest","This week"],["history","History"],["settings","Delivery settings"]].map(([I,P])=>e.jsx(is,{value:I,className:"rounded-full text-[13px] data-[state=active]:bg-violet-600 data-[state=active]:text-white",children:P},I))}),e.jsxs(cs,{value:"digest",className:"mt-5 space-y-5",children:[e.jsx("div",{className:"grid grid-cols-2 lg:grid-cols-4 gap-3",children:[["Conversations logged",_.wins.conversations_logged],["Stage moves",_.wins.advanced],["Follow-ups completed",_.wins.follow_ups_completed],["Kits shared",_.wins.kits_shared]].map(([I,P])=>e.jsxs(we,{className:"p-4 rounded-2xl",children:[e.jsx("div",{className:"text-2xl font-semibold tabular-nums text-slate-900",children:P}),e.jsx("div",{className:"text-[11.5px] text-slate-500 mt-0.5",children:I})]},I))}),e.jsxs(we,{className:"p-5 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wider font-semibold text-violet-600 mb-3",children:"Your five conversations this week"}),_.conversations.length?e.jsx("div",{className:"space-y-3",children:_.conversations.map(I=>{const P=m.find(O=>O.agent_id===I.agent_id),R=!!(P!=null&&P.completed_at);return e.jsxs("div",{className:Ot("rounded-xl border border-slate-200 p-4",R&&"bg-emerald-50/60 border-emerald-200"),children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 flex-wrap",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"text-[14.5px] font-semibold text-slate-900",children:[I.rank,". ",e.jsx(nr,{to:`/attract/agents/${I.agent_id}`,className:"hover:text-violet-700",children:I.agent_name})]}),e.jsx("div",{className:"text-[12.5px] text-slate-600 mt-0.5",children:I.reason})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(qe,{variant:"outline",className:"rounded-full capitalize",children:I.channel}),e.jsxs(qe,{variant:"outline",className:"rounded-full",children:["Health ",I.score]})]})]}),I.draft_message&&e.jsx("div",{className:"mt-3 rounded-lg bg-slate-50 p-3 text-[13px] text-slate-700 whitespace-pre-wrap",children:I.draft_message}),e.jsxs("div",{className:"flex gap-2 mt-3",children:[e.jsxs($,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>{navigator.clipboard.writeText(I.draft_message||""),ae.success("Copied")},children:[e.jsx(Da,{className:"h-3.5 w-3.5 mr-1.5"})," Copy"]}),P&&!R&&e.jsxs($,{size:"sm",className:"rounded-full btn-primary text-white",onClick:()=>p.mutate(P.id),children:[e.jsx(Gr,{className:"h-3.5 w-3.5 mr-1.5"})," Mark done"]}),R&&e.jsx("span",{className:"text-[12.5px] text-emerald-700 font-medium self-center",children:"Completed"}),e.jsx($,{size:"sm",variant:"ghost",className:"rounded-full",asChild:!0,children:e.jsx(nr,{to:`/attract/agents/${I.agent_id}`,children:"Open relationship"})})]})]},I.agent_id)})}):e.jsx("div",{className:"text-[13px] text-slate-500",children:"No conversations to recommend yet — Attract needs real signals first."})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-4",children:[e.jsxs(we,{className:"p-5 rounded-2xl space-y-4",children:[e.jsx(S9,{title:"High intent",children:e.jsx(Cie,{rows:_.high_intent,empty:"No high-intent signals this week."})}),e.jsx(S9,{title:"Renewed interest",children:e.jsx(Cie,{rows:_.renewed,empty:"Nobody re-engaged after going quiet."})})]}),e.jsxs(we,{className:"p-5 rounded-2xl space-y-4",children:[e.jsx(S9,{title:"Overdue commitments",children:e.jsx(Cie,{rows:_.overdue,empty:"Nothing overdue. Well kept."})}),e.jsx(S9,{title:"Going cold",children:e.jsx(Cie,{rows:_.stale,empty:"No relationships past 60 days of silence."})})]}),e.jsx(we,{className:"p-5 rounded-2xl",children:e.jsx(S9,{title:"Value shared",children:e.jsxs("div",{className:"text-[13px] text-slate-700 space-y-1",children:[e.jsxs("div",{children:[_.kit_summary.shares," kits shared · ",_.kit_summary.opened," opened"]}),e.jsxs("div",{children:[_.kit_summary.downloads," downloads · ",_.kit_summary.questions," questions asked"]}),e.jsxs("div",{children:[_.kit_summary.engaged," engaged · ",_.kit_summary.high_intent," high intent"]})]})})}),e.jsx(we,{className:"p-5 rounded-2xl",children:e.jsx(S9,{title:"Events",children:e.jsxs("div",{className:"text-[13px] text-slate-700 space-y-1",children:[e.jsxs("div",{children:[_.event_summary.invited," invited · ",_.event_summary.registered," registered"]}),e.jsxs("div",{children:[_.event_summary.attended," attended · ",_.event_summary.no_shows," no-shows"]}),e.jsxs("div",{children:[_.event_summary.follow_ups_pending," attendee follow-ups still pending"]}),_.event_summary.upcoming.map(I=>e.jsxs("div",{className:"text-slate-600 flex items-center gap-1.5",children:[e.jsx(fd,{className:"h-3.5 w-3.5"})," ",I.title,I.starts_at?` — ${new Date(I.starts_at).toLocaleDateString()}`:""]},I.title))]})})})]}),e.jsxs(we,{className:"p-5 rounded-2xl bg-gradient-to-r from-violet-50 to-indigo-50 border-violet-100",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wider font-semibold text-violet-700",children:"Recommended focus"}),e.jsx("p",{className:"text-[14px] text-slate-800 mt-1.5",children:_.recommended_focus}),e.jsx("div",{className:"flex gap-2 mt-3 flex-wrap",children:_.pillar_balance.map(I=>e.jsxs(qe,{variant:"outline",className:"rounded-full capitalize bg-white/70",children:[I.pillar,": ",I.count]},I.pillar))})]})]}),e.jsx(cs,{value:"history",className:"mt-5 space-y-3",children:l.length?l.map(I=>e.jsxs(we,{className:Ot("p-4 rounded-2xl flex items-center justify-between gap-3 flex-wrap",I.id===h&&"ring-1 ring-violet-300"),children:[e.jsxs("div",{children:[e.jsxs("div",{className:"text-[14px] font-semibold text-slate-900",children:["Week of ",new Date(`${I.week_start}T12:00:00`).toLocaleDateString()]}),e.jsxs("div",{className:"text-[12px] text-slate-500 mt-0.5",children:[e.jsx("span",{className:"capitalize",children:I.delivery_status.replace(/_/g," ")}),I.sent_at&&` · sent ${new Date(I.sent_at).toLocaleString()}`,I.delivery_note&&` · ${I.delivery_note}`]})]}),e.jsx($,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>u(I.id),children:"View"})]},I.id)):e.jsx(we,{className:"p-8 rounded-2xl text-center text-[13.5px] text-slate-500",children:"No digests generated yet."})}),e.jsx(cs,{value:"settings",className:"mt-5",children:e.jsxs(we,{className:"p-5 rounded-2xl max-w-xl space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[14px] font-medium text-slate-900",children:"Weekly email"}),e.jsx("div",{className:"text-[12.5px] text-slate-500",children:"Send the digest automatically each week."})]}),e.jsx(On,{checked:!!(a!=null&&a.enabled),onCheckedChange:I=>i.mutate({enabled:I})})]}),e.jsxs("div",{className:"grid sm:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Day"}),e.jsxs(bs,{value:String((a==null?void 0:a.weekday)??1),onValueChange:I=>i.mutate({weekday:Number(I)}),children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsx(vs,{children:aKn.map((I,P)=>e.jsx(We,{value:String(P),children:I},I))})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Hour (local)"}),e.jsxs(bs,{value:String((a==null?void 0:a.send_hour)??7),onValueChange:I=>i.mutate({send_hour:Number(I)}),children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsx(vs,{children:Array.from({length:24},(I,P)=>e.jsxs(We,{value:String(P),children:[P,":00"]},P))})]})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Send to"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(be,{value:g||(a==null?void 0:a.email)||(s==null?void 0:s.email)||"",onChange:I=>x(I.target.value),placeholder:"you@example.com"}),e.jsx($,{variant:"outline",className:"rounded-full",onClick:()=>i.mutate({email:j}),children:"Save"})]})]}),e.jsxs("div",{className:"rounded-xl bg-amber-50 border border-amber-200 p-3 text-[12.5px] text-amber-900 flex gap-2",children:[e.jsx(pn,{className:"h-4 w-4 mt-0.5 shrink-0"}),`Automatic weekly scheduling is not wired to a scheduler yet — use "Email it to me" to send on demand. If delivery isn't configured, the digest is still saved here and the status will say so honestly.`]})]})})]})]})}const vP=V,oKn=[{first_name:"Dana",last_name:"Reyes (Demo)",stage:"engaging_with_value",temperature:"hot",brokerage:"Summit Realty",city:"Tulsa",state:"OK",goals:"Wants to double GCI",challenges:"No systems"},{first_name:"Marcus",last_name:"Webb (Demo)",stage:"building_relationship",temperature:"warm",brokerage:"Keystone Group",city:"Jenks",state:"OK",goals:"More listings",challenges:"Lead follow-up"},{first_name:"Priya",last_name:"Nair (Demo)",stage:"active_conversation",temperature:"hot",brokerage:"Northline",city:"Bixby",state:"OK",goals:"Team building",challenges:"Time management"}];function lKn(){const{user:s}=ks(),t=ls(),{intel:n,dataset:r,isLoading:a,refetch:i}=k6(),l=YTe(),o=yWt(),[c,d]=k.useState(""),[u,h]=k.useState(!1),m=k.useMemo(()=>r?iKt(n,r):null,[n,r]),p=k.useMemo(()=>{const y=c.toLowerCase().trim();return n.filter(v=>!y||`${v.agent.first_name} ${v.agent.last_name??""}`.toLowerCase().includes(y))},[n,c]),g=async()=>{if(!s)return;h(!0);const{data:y}=await vP.from("attract_agents").select("id").eq("user_id",s.id).eq("is_demo",!0);if((y??[]).length){ae.info("Demo agents already exist"),h(!1);return}const{data:v,error:_}=await vP.from("attract_agents").insert(oKn.map(C=>({...C,user_id:s.id,is_demo:!0,source:"demo_seed"}))).select("id, first_name");if(_){ae.error(_.message),h(!1);return}const j=Date.now();await vP.from("attract_activities").insert((v??[]).map((C,A)=>({user_id:s.id,agent_id:C.id,activity_type:"touch_logged",pillar:"connect",title:`Demo conversation with ${C.first_name}`,created_at:new Date(j-(A+1)*14*864e5).toISOString()}))),await vP.from("attract_follow_ups").insert({user_id:s.id,agent_id:v[0].id,title:"Demo overdue commitment",touch_type:"call",priority:"high",due_at:new Date(j-6*864e5).toISOString()}),ae.success("Demo relationships seeded"),h(!1),t.invalidateQueries({queryKey:["attract-intel-data"]}),i()},x=async()=>{if(!s)return;h(!0);const{data:y}=await vP.from("attract_agents").select("id").eq("user_id",s.id).eq("is_demo",!0),v=(y??[]).map(_=>_.id);if(!v.length){ae.info("No demo data to clear"),h(!1);return}for(const _ of["attract_recommendations","attract_agent_scores","attract_follow_ups","attract_activities"])await vP.from(_).delete().in("agent_id",v);await vP.from("attract_agents").delete().in("id",v),ae.success("Demo data removed"),h(!1),t.invalidateQueries({queryKey:["attract-intel-data"]}),i()};return a?e.jsx(fn,{className:"h-72 w-full rounded-2xl"}):e.jsxs("div",{className:"p-4 sm:p-6 max-w-6xl mx-auto space-y-5",children:[e.jsx($,{variant:"ghost",size:"sm",className:"rounded-full -ml-2",asChild:!0,children:e.jsxs(nr,{to:"/admin",children:[e.jsx(Ia,{className:"h-3.5 w-3.5 mr-1.5"})," Admin"]})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:"Attract Intelligence Debug"}),e.jsx("p",{className:"text-[13.5px] text-muted-foreground mt-1",children:"Full transparency into scores, signals and recommendations for your own Attract data. Demo records are flagged and removable."})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs($,{variant:"outline",className:"rounded-full",onClick:()=>{o.mutate({items:n}),l.mutate(n)},disabled:l.isPending||o.isPending,children:[e.jsx(yo,{className:"h-3.5 w-3.5 mr-1.5"})," Recompute & persist"]}),e.jsxs($,{variant:"outline",className:"rounded-full",onClick:g,disabled:u,children:[e.jsx(_K,{className:"h-3.5 w-3.5 mr-1.5"})," Seed demo relationships"]}),e.jsxs($,{variant:"outline",className:"rounded-full text-destructive",onClick:x,disabled:u,children:[e.jsx(Un,{className:"h-3.5 w-3.5 mr-1.5"})," Clear demo data"]})]}),e.jsxs(ya,{defaultValue:"agents",children:[e.jsxs(va,{className:"rounded-full",children:[e.jsx(is,{value:"agents",className:"rounded-full",children:"Scores & signals"}),e.jsx(is,{value:"digest",className:"rounded-full",children:"Digest payload"})]}),e.jsxs(cs,{value:"agents",className:"mt-4 space-y-3",children:[e.jsx(be,{value:c,onChange:y=>d(y.target.value),placeholder:"Filter by name",className:"max-w-sm rounded-full"}),!p.length&&e.jsx(we,{className:"p-6 rounded-2xl text-[13.5px] text-muted-foreground",children:"No agents in your Attract pipeline."}),p.map(y=>e.jsxs(we,{className:"p-4 rounded-2xl",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 flex-wrap",children:[e.jsxs("div",{children:[e.jsx(nr,{to:`/attract/agents/${y.agent.id}`,className:"text-[15px] font-semibold hover:text-violet-700",children:[y.agent.first_name,y.agent.last_name].filter(Boolean).join(" ")}),e.jsxs("div",{className:"text-[12px] text-muted-foreground mt-0.5 capitalize",children:[y.agent.stage.replace(/_/g," ")," · ",y.agent.temperature??"no temperature"," · ",y.signals.daysSinceTouch??"—"," days since touch"]})]}),y.agent.is_demo&&e.jsx(qe,{variant:"outline",className:"rounded-full",children:"Demo"})]}),e.jsxs("div",{className:"grid md:grid-cols-2 gap-4 mt-4",children:[e.jsx(bWt,{score:y.score}),e.jsxs("div",{children:[e.jsxs("div",{className:"text-[11px] uppercase tracking-wider font-semibold text-muted-foreground mb-1.5",children:["Recommendations (",y.recommendations.length,")"]}),y.recommendations.length?e.jsx("ul",{className:"space-y-2",children:y.recommendations.map(v=>e.jsxs("li",{className:"text-[12.5px]",children:[e.jsx("span",{className:"font-medium",children:v.title}),e.jsxs("span",{className:"text-muted-foreground",children:[" · ",v.signal_group," · rank ",v.rank_score," · ",v.priority]}),e.jsx("div",{className:"text-muted-foreground",children:v.reasons.join(" · ")})]},v.rec_key))}):e.jsx("div",{className:"text-[13px] text-muted-foreground",children:"None generated."})]})]}),e.jsxs("details",{className:"mt-3",children:[e.jsx("summary",{className:"text-[12px] cursor-pointer text-muted-foreground",children:"Raw signals"}),e.jsx("pre",{className:"text-[11px] bg-muted p-3 rounded-lg overflow-auto mt-2 max-h-72",children:JSON.stringify({touches90:y.signals.touches90,kitShares:y.signals.shares.length,kitOpens:y.signals.totalKitOpens,questions:y.signals.questions,meetingRequests:y.signals.meetingRequests,overdueFollowUps:y.signals.overdueFollowUps.length,attended:y.signals.attended},null,2)})]})]},y.agent.id))]}),e.jsx(cs,{value:"digest",className:"mt-4",children:e.jsx(we,{className:"p-4 rounded-2xl",children:e.jsx("pre",{className:"text-[11px] bg-muted p-3 rounded-lg overflow-auto max-h-[600px]",children:JSON.stringify(m,null,2)})})})]})]})}function cKn(){const[s,t]=k.useState(""),[n,r]=k.useState("all"),a=k.useMemo(()=>Tqe.filter(l=>{const o=s.toLowerCase().trim();return n!=="all"&&l.status!==n?!1:!o||`${l.title} ${l.pillar} ${l.route??""}`.toLowerCase().includes(o)}),[s,n]),i=k.useMemo(()=>{const l={live:0,partial:0,placeholder:0,integration_required:0};return Tqe.forEach(o=>{l[o.status]++}),l},[]);return e.jsxs("div",{className:"p-4 sm:p-6 max-w-6xl mx-auto space-y-5",children:[e.jsx($,{variant:"ghost",size:"sm",className:"rounded-full -ml-2",asChild:!0,children:e.jsxs(nr,{to:"/admin",children:[e.jsx(Ia,{className:"h-3.5 w-3.5 mr-1.5"})," Admin"]})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:"Attract Pillar Tools QA"}),e.jsx("p",{className:"text-[13.5px] text-muted-foreground mt-1",children:"Private status map of every Attract tool — route, database dependencies, and what still needs work."})]}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:Object.keys(i).map(l=>e.jsxs(we,{className:"p-4 rounded-2xl cursor-pointer",onClick:()=>r(n===l?"all":l),children:[e.jsx("div",{className:"text-[22px] font-semibold tabular-nums",children:i[l]}),e.jsx("div",{className:"text-[12px] text-muted-foreground",children:Mqe[l]})]},l))}),e.jsxs("div",{className:"flex gap-2 flex-wrap",children:[e.jsx(be,{value:s,onChange:l=>t(l.target.value),placeholder:"Filter tools",className:"max-w-sm rounded-full"}),n!=="all"&&e.jsx($,{variant:"outline",className:"rounded-full",onClick:()=>r("all"),children:"Clear status filter"})]}),e.jsx("div",{className:"space-y-2",children:a.map(l=>e.jsx(we,{className:"p-4 rounded-2xl",children:e.jsxs("div",{className:"flex items-start justify-between gap-3 flex-wrap",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"text-[15px] font-semibold",children:l.title}),e.jsx(qe,{variant:"outline",className:"rounded-full capitalize",children:l.pillar}),e.jsx(qe,{variant:"outline",className:`rounded-full ${RWt[l.status]}`,children:Mqe[l.status]})]}),e.jsx("div",{className:"text-[12.5px] text-muted-foreground mt-1",children:l.notes||"—"}),e.jsxs("div",{className:"text-[11.5px] text-muted-foreground mt-1",children:["Tables: ",l.tables.length?l.tables.join(", "):"none"]})]}),l.route&&!l.route.includes(":")?e.jsx($,{variant:"outline",size:"sm",className:"rounded-full",asChild:!0,children:e.jsxs(nr,{to:l.route,children:[l.route," ",e.jsx(Ir,{className:"h-3 w-3 ml-1.5"})]})}):e.jsx("span",{className:"text-[12px] text-muted-foreground",children:l.route??"No route"})]})},`${l.pillar}-${l.key}`))})]})}const bP=V,ejt=["idea","researching","pitching","applied","tentative","confirmed","completed","declined","archived"],tjt=["panel","keynote","mls_talk","podcast","webinar","mastermind","training","conference","other"],sjt=["attract-speaking"];function oKt(){const{user:s}=ks(),t=ls(),n=pt({queryKey:[...sjt,s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:u,error:h}=await bP.from("attract_speaking_opportunities").select("*").order("starts_at",{ascending:!0,nullsFirst:!1});if(h)throw h;return u??[]}}),r=()=>{t.invalidateQueries({queryKey:sjt}),t.invalidateQueries({queryKey:["attract-followups"]}),t.invalidateQueries({queryKey:["attract-activities"]})},a=Nt({mutationFn:async u=>{const{data:h,error:m}=await bP.from("attract_speaking_opportunities").insert({...u,user_id:s.id}).select("*").single();if(m)throw m;return h},onSuccess:()=>{r(),ae.success("Speaking opportunity saved")},onError:u=>ae.error(u.message)}),i=Nt({mutationFn:async({id:u,...h})=>{const{error:m}=await bP.from("attract_speaking_opportunities").update(h).eq("id",u);if(m)throw m},onSuccess:()=>{r(),ae.success("Updated")},onError:u=>ae.error(u.message)}),l=Nt({mutationFn:async u=>{const{id:h,created_at:m,updated_at:p,user_id:g,...x}=u,{data:y,error:v}=await bP.from("attract_speaking_opportunities").insert({...x,title:`${u.title} (copy)`,status:"idea",user_id:s.id}).select("id").single();if(v)throw v;return y},onSuccess:()=>{r(),ae.success("Duplicated")},onError:u=>ae.error(u.message)}),o=Nt({mutationFn:async u=>{const{error:h}=await bP.from("attract_speaking_opportunities").delete().eq("id",u);if(h)throw h},onSuccess:()=>{r(),ae.success("Deleted")},onError:u=>ae.error(u.message)}),c=Nt({mutationFn:async({title:u,dueAt:h,notes:m,touchType:p="speaking"})=>{const{error:g}=await bP.from("attract_follow_ups").insert({user_id:s.id,title:u,due_at:h??null,notes:m??null,touch_type:p,priority:"medium"});if(g)throw g},onSuccess:()=>{r(),ae.success("Added to Follow-Up Center")},onError:u=>ae.error(u.message)}),d=Nt({mutationFn:async({title:u,pillar:h="influence",activityType:m="speaking_outreach",agentId:p})=>{const{error:g}=await bP.from("attract_activities").insert({user_id:s.id,title:u,pillar:h,activity_type:m,agent_id:p??null});if(g)throw g},onSuccess:()=>{r(),ae.success("Outreach logged")},onError:u=>ae.error(u.message)});return{items:n.data??[],isLoading:n.isLoading,error:n.error,refetch:n.refetch,create:a,update:i,duplicate:l,remove:o,addTask:c,logActivity:d}}const Fqe={idea:"bg-slate-100 text-slate-700 border-slate-200",researching:"bg-sky-50 text-sky-700 border-sky-200",pitching:"bg-amber-50 text-amber-700 border-amber-200",applied:"bg-orange-50 text-orange-700 border-orange-200",tentative:"bg-violet-50 text-violet-700 border-violet-200",confirmed:"bg-emerald-50 text-emerald-700 border-emerald-200",completed:"bg-teal-50 text-teal-700 border-teal-200",declined:"bg-rose-50 text-rose-700 border-rose-200",archived:"bg-slate-100 text-slate-500 border-slate-200"},Q8e={title:"",organization:"",event_type:"panel",status:"idea",timezone:"America/New_York",pillar:"influence",linked_agent_ids:[]};function dKn(){const{items:s,isLoading:t,create:n,update:r,duplicate:a,remove:i,addTask:l,logActivity:o}=oKt(),{agents:c=[]}=A0(),{kits:d=[]}=YV(),u=XTe(),h=(u==null?void 0:u.events)??(u==null?void 0:u.data)??[],[m,p]=k.useState("month"),[g,x]=k.useState(new Date),[y,v]=k.useState("all"),[_,j]=k.useState("all"),[C,A]=k.useState("all"),[M,I]=k.useState(!1),[P,R]=k.useState(null),[O,B]=k.useState(null),U=k.useMemo(()=>s.filter(te=>!(!M&&(te.is_archived||te.status==="archived")||y!=="all"&&te.status!==y||_!=="all"&&te.event_type!==_||C!=="all"&&!(te.linked_agent_ids??[]).includes(C))),[s,y,_,C,M]),G=U.filter(te=>te.starts_at),H=U.filter(te=>!te.starts_at),Y=new Date,se=k.useMemo(()=>{const te=G.filter(he=>N_(Mp(he.starts_at),Y)&&["confirmed","tentative"].includes(he.status)),le=U.filter(he=>he.submission_deadline&&N_(Mp(he.submission_deadline),Y)),fe=U.filter(he=>["pitching","applied","researching"].includes(he.status)),_e=U.filter(he=>he.status==="confirmed"),ve=U.filter(he=>he.follow_up_date&&he.status==="completed");return{upcoming:te,deadlines:le,pitches:fe,confirmed:_e,followUps:ve}},[U,G]),ee=k.useMemo(()=>p7e(m==="week"?{start:My(g),end:wU(g)}:{start:My(Ih(g)),end:wU(eb(g))}),[g,m]),oe=te=>G.filter(le=>ah(Mp(le.starts_at),te)),me=async()=>{var le;if(!((le=P==null?void 0:P.title)!=null&&le.trim())){ae.error("Give the talk a title");return}const te={...P};delete te.created_at,delete te.updated_at,delete te.user_id,(te.fee===""||te.fee==null)&&(te.fee=null),["starts_at","ends_at","submission_deadline","follow_up_date","linked_event_id","linked_kit_id"].forEach(fe=>{te[fe]===""&&(te[fe]=null)}),P.id?await r.mutateAsync(te):await n.mutateAsync(te),R(null)},Q=te=>{if(!te.starts_at){ae.error("Add a date first");return}const le=Se=>new Date(Se).toISOString().replace(/[-:]|\.\d{3}/g,""),fe=te.ends_at??new Date(new Date(te.starts_at).getTime()+60*6e4).toISOString(),_e=["BEGIN:VCALENDAR","VERSION:2.0","PRODID:-//LevelUp Attract//Speaking//EN","BEGIN:VEVENT",`UID:${te.id}@levelup-attract`,`DTSTAMP:${le(new Date().toISOString())}`,`DTSTART:${le(te.starts_at)}`,`DTEND:${le(fe)}`,`SUMMARY:${(te.title||"").replace(/\n/g," ")}`,`LOCATION:${(te.location||te.virtual_link||"").replace(/\n/g," ")}`,`DESCRIPTION:${[te.organization,te.topic].filter(Boolean).join(" — ").replace(/\n/g," ")}`,"END:VEVENT","END:VCALENDAR"].join(`\r `),ve=URL.createObjectURL(new Blob([_e],{type:"text/calendar"})),he=document.createElement("a");he.href=ve,he.download=`${te.title.replace(/\W+/g,"-").toLowerCase()}.ics`,he.click(),URL.revokeObjectURL(ve)};return t?e.jsxs("div",{className:"space-y-4",children:[e.jsx(fn,{className:"h-32 rounded-2xl"}),e.jsx(fn,{className:"h-96 rounded-2xl"})]}):e.jsxs("div",{className:"space-y-6",children:[e.jsx(Hm,{eyebrow:"Pillar 02 · Influence",title:"Speaking Calendar",description:"Every stage, panel, podcast, and MLS talk — from first idea to post-event follow-up.",actions:e.jsxs($,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>R({...Q8e}),children:[e.jsx(nn,{className:"h-4 w-4 mr-2"}),"New opportunity"]})}),e.jsxs("div",{className:"grid grid-cols-2 lg:grid-cols-5 gap-3",children:[e.jsx(dW,{label:"Upcoming talks",value:se.upcoming.length,icon:w2}),e.jsx(dW,{label:"Deadlines ahead",value:se.deadlines.length,icon:sa}),e.jsx(dW,{label:"Pitches in flight",value:se.pitches.length,icon:Wr}),e.jsx(dW,{label:"Confirmed",value:se.confirmed.length,icon:Gr}),e.jsx(dW,{label:"Post-event follow-ups",value:se.followUps.length,icon:op})]}),e.jsxs(we,{className:"p-3 rounded-2xl flex flex-wrap items-center gap-2",children:[e.jsx("div",{className:"flex rounded-full bg-slate-100 p-1",children:["month","week","agenda"].map(te=>e.jsx("button",{onClick:()=>p(te),className:`px-3 py-1.5 rounded-full text-[12.5px] font-medium capitalize ${m===te?"bg-white shadow-sm text-slate-900":"text-slate-500"}`,children:te},te))}),m!=="agenda"&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx($,{variant:"ghost",size:"icon",className:"rounded-full",onClick:()=>x(m==="week"?a3(g,-1):Ux(g,-1)),children:e.jsx(Ld,{className:"h-4 w-4"})}),e.jsx("div",{className:"text-[13.5px] font-semibold min-w-[130px] text-center",children:Ys(g,m==="week"?"'Week of' MMM d":"MMMM yyyy")}),e.jsx($,{variant:"ghost",size:"icon",className:"rounded-full",onClick:()=>x(m==="week"?a3(g,1):Ux(g,1)),children:e.jsx(fi,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"sm",className:"rounded-full",onClick:()=>x(new Date),children:"Today"})]}),e.jsx("div",{className:"flex-1"}),e.jsxs(bs,{value:y,onValueChange:v,children:[e.jsx(ys,{className:"w-[140px] rounded-full h-9",children:e.jsx(_s,{placeholder:"Status"})}),e.jsxs(vs,{children:[e.jsx(We,{value:"all",children:"All statuses"}),ejt.map(te=>e.jsx(We,{value:te,className:"capitalize",children:te.replace(/_/g," ")},te))]})]}),e.jsxs(bs,{value:_,onValueChange:j,children:[e.jsx(ys,{className:"w-[140px] rounded-full h-9",children:e.jsx(_s,{placeholder:"Type"})}),e.jsxs(vs,{children:[e.jsx(We,{value:"all",children:"All types"}),tjt.map(te=>e.jsx(We,{value:te,className:"capitalize",children:te.replace(/_/g," ")},te))]})]}),e.jsxs(bs,{value:C,onValueChange:A,children:[e.jsx(ys,{className:"w-[160px] rounded-full h-9",children:e.jsx(_s,{placeholder:"Relationship"})}),e.jsxs(vs,{children:[e.jsx(We,{value:"all",children:"All relationships"}),c.map(te=>e.jsx(We,{value:te.id,children:[te.first_name,te.last_name].filter(Boolean).join(" ")},te.id))]})]}),e.jsxs($,{variant:M?"default":"outline",size:"sm",className:"rounded-full",onClick:()=>I(te=>!te),children:[e.jsx(kf,{className:"h-3.5 w-3.5 mr-1.5"}),"Archived"]})]}),s.length===0?e.jsxs(we,{className:"p-10 rounded-2xl text-center",children:[e.jsx(w2,{className:"h-8 w-8 mx-auto text-violet-500"}),e.jsx("div",{className:"text-[16px] font-semibold mt-3",children:"No speaking opportunities yet"}),e.jsx("p",{className:"text-[13.5px] text-slate-500 mt-1 max-w-md mx-auto",children:"Start with the rooms you already have access to — your office meeting, a local MLS class, a peer's podcast. Track the pitch, the deadline, and the follow-up in one place."}),e.jsxs($,{className:"mt-4 rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>R({...Q8e}),children:[e.jsx(nn,{className:"h-4 w-4 mr-2"}),"Add your first opportunity"]})]}):m==="agenda"?e.jsxs("div",{className:"space-y-3",children:[[...G,...H].length===0&&e.jsx(we,{className:"p-8 rounded-2xl text-center text-[13.5px] text-slate-500",children:"Nothing matches these filters."}),[...G,...H].map(te=>e.jsx(uKn,{o:te,onEdit:()=>R(te),onComplete:()=>B(te),onDuplicate:()=>a.mutate(te),onDelete:()=>i.mutate(te.id),onArchive:()=>r.mutate({id:te.id,is_archived:!te.is_archived,status:te.is_archived?"idea":"archived"}),onIcs:()=>Q(te),onPitchTask:()=>l.mutate({title:`Pitch: ${te.title}${te.organization?` (${te.organization})`:""}`,dueAt:te.submission_deadline?new Date(te.submission_deadline).toISOString():null,notes:te.notes??void 0}),onLogOutreach:()=>o.mutate({title:`Outreach for ${te.title}`}),onConfirm:()=>r.mutate({id:te.id,status:"confirmed"})},te.id))]}):e.jsxs(we,{className:"rounded-2xl overflow-hidden",children:[e.jsx("div",{className:"grid grid-cols-7 border-b bg-slate-50",children:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"].map(te=>e.jsx("div",{className:"px-2 py-2 text-[11px] uppercase tracking-wider font-semibold text-slate-500 text-center",children:te},te))}),e.jsx("div",{className:"grid grid-cols-7",children:ee.map(te=>{const le=oe(te);return e.jsxs("div",{className:`min-h-[92px] sm:min-h-[112px] border-b border-r p-1.5 ${Vq(te,g)||m==="week"?"bg-white":"bg-slate-50/60"}`,children:[e.jsx("button",{onClick:()=>R({...Q8e,starts_at:new Date(te.setHours(10,0,0,0)).toISOString()}),className:`text-[11.5px] font-semibold h-6 w-6 rounded-full grid place-items-center ${ah(te,Y)?"bg-violet-600 text-white":"text-slate-500 hover:bg-slate-100"}`,children:Ys(te,"d")}),e.jsxs("div",{className:"mt-1 space-y-1",children:[le.slice(0,3).map(fe=>e.jsx("button",{onClick:()=>R(fe),className:`w-full text-left text-[11px] px-1.5 py-1 rounded-md border truncate ${Fqe[fe.status]??""}`,children:fe.title},fe.id)),le.length>3&&e.jsxs("div",{className:"text-[10.5px] text-slate-400 pl-1",children:["+",le.length-3," more"]})]})]},te.toISOString())})}),H.length>0&&e.jsxs("div",{className:"p-3 bg-slate-50 border-t",children:[e.jsxs("div",{className:"text-[11px] uppercase tracking-wider font-semibold text-slate-500 mb-2",children:["Undated (",H.length,")"]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:H.map(te=>e.jsx("button",{onClick:()=>R(te),className:`text-[12px] px-2.5 py-1 rounded-full border ${Fqe[te.status]??""}`,children:te.title},te.id))})]})]}),e.jsx(JF,{}),e.jsx(zs,{open:!!P,onOpenChange:te=>!te&&R(null),children:e.jsxs(Rs,{className:"max-w-3xl max-h-[90vh] overflow-y-auto",children:[e.jsx(Vs,{children:e.jsx($s,{children:P!=null&&P.id?"Edit speaking opportunity":"New speaking opportunity"})}),P&&e.jsxs("div",{className:"grid sm:grid-cols-2 gap-3",children:[e.jsx(Pm,{label:"Title",className:"sm:col-span-2",children:e.jsx(be,{value:P.title??"",onChange:te=>R({...P,title:te.target.value}),placeholder:"Panel: Winning listings in a shifting market"})}),e.jsx(Pm,{label:"Event / organization",children:e.jsx(be,{value:P.organization??"",onChange:te=>R({...P,organization:te.target.value})})}),e.jsx(Pm,{label:"Event type",children:e.jsxs(bs,{value:P.event_type??"panel",onValueChange:te=>R({...P,event_type:te}),children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsx(vs,{children:tjt.map(te=>e.jsx(We,{value:te,className:"capitalize",children:te.replace(/_/g," ")},te))})]})}),e.jsx(Pm,{label:"Contact name",children:e.jsx(be,{value:P.contact_name??"",onChange:te=>R({...P,contact_name:te.target.value})})}),e.jsx(Pm,{label:"Contact email",children:e.jsx(be,{type:"email",value:P.contact_email??"",onChange:te=>R({...P,contact_email:te.target.value})})}),e.jsx(Pm,{label:"Contact phone",children:e.jsx(be,{value:P.contact_phone??"",onChange:te=>R({...P,contact_phone:te.target.value})})}),e.jsx(Pm,{label:"Audience",children:e.jsx(be,{value:P.audience??"",onChange:te=>R({...P,audience:te.target.value}),placeholder:"120 local agents"})}),e.jsx(Pm,{label:"Location",children:e.jsx(be,{value:P.location??"",onChange:te=>R({...P,location:te.target.value})})}),e.jsx(Pm,{label:"Virtual link",children:e.jsx(be,{value:P.virtual_link??"",onChange:te=>R({...P,virtual_link:te.target.value})})}),e.jsx(Pm,{label:"Starts",children:e.jsx(be,{type:"datetime-local",value:njt(P.starts_at),onChange:te=>R({...P,starts_at:te.target.value?new Date(te.target.value).toISOString():null})})}),e.jsx(Pm,{label:"Ends",children:e.jsx(be,{type:"datetime-local",value:njt(P.ends_at),onChange:te=>R({...P,ends_at:te.target.value?new Date(te.target.value).toISOString():null})})}),e.jsx(Pm,{label:"Status",children:e.jsxs(bs,{value:P.status??"idea",onValueChange:te=>R({...P,status:te}),children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsx(vs,{children:ejt.map(te=>e.jsx(We,{value:te,className:"capitalize",children:te},te))})]})}),e.jsx(Pm,{label:"Fee / honorarium",children:e.jsx(be,{type:"number",value:P.fee??"",onChange:te=>R({...P,fee:te.target.value===""?null:Number(te.target.value)})})}),e.jsx(Pm,{label:"Submission deadline",children:e.jsx(be,{type:"date",value:P.submission_deadline??"",onChange:te=>R({...P,submission_deadline:te.target.value||null})})}),e.jsx(Pm,{label:"Follow-up date",children:e.jsx(be,{type:"date",value:P.follow_up_date??"",onChange:te=>R({...P,follow_up_date:te.target.value||null})})}),e.jsx(Pm,{label:"Application URL",className:"sm:col-span-2",children:e.jsx(be,{value:P.application_url??"",onChange:te=>R({...P,application_url:te.target.value})})}),e.jsx(Pm,{label:"Topic",className:"sm:col-span-2",children:e.jsx(be,{value:P.topic??"",onChange:te=>R({...P,topic:te.target.value})})}),e.jsx(Pm,{label:"Linked Connect event",children:e.jsxs(bs,{value:P.linked_event_id??"none",onValueChange:te=>R({...P,linked_event_id:te==="none"?null:te}),children:[e.jsx(ys,{children:e.jsx(_s,{placeholder:"None"})}),e.jsxs(vs,{children:[e.jsx(We,{value:"none",children:"None"}),h.map(te=>e.jsx(We,{value:te.id,children:te.title},te.id))]})]})}),e.jsx(Pm,{label:"Linked Resource Kit",children:e.jsxs(bs,{value:P.linked_kit_id??"none",onValueChange:te=>R({...P,linked_kit_id:te==="none"?null:te}),children:[e.jsx(ys,{children:e.jsx(_s,{placeholder:"None"})}),e.jsxs(vs,{children:[e.jsx(We,{value:"none",children:"None"}),d.map(te=>e.jsx(We,{value:te.id,children:te.title},te.id))]})]})}),e.jsx(Pm,{label:"Linked agent relationships",className:"sm:col-span-2",children:e.jsxs("div",{className:"flex flex-wrap gap-1.5 max-h-32 overflow-y-auto",children:[c.length===0&&e.jsx("div",{className:"text-[12.5px] text-slate-500",children:"No agents in your pipeline yet."}),c.map(te=>{const le=(P.linked_agent_ids??[]).includes(te.id);return e.jsx("button",{type:"button",onClick:()=>R({...P,linked_agent_ids:le?(P.linked_agent_ids??[]).filter(fe=>fe!==te.id):[...P.linked_agent_ids??[],te.id]}),className:`text-[12px] px-2.5 py-1 rounded-full border ${le?"bg-violet-600 text-white border-violet-600":"bg-white text-slate-600"}`,children:[te.first_name,te.last_name].filter(Boolean).join(" ")},te.id)})]})}),e.jsx(Pm,{label:"Travel notes",className:"sm:col-span-2",children:e.jsx(Ls,{rows:2,value:P.travel_notes??"",onChange:te=>R({...P,travel_notes:te.target.value})})}),e.jsx(Pm,{label:"Notes",className:"sm:col-span-2",children:e.jsx(Ls,{rows:3,value:P.notes??"",onChange:te=>R({...P,notes:te.target.value})})})]}),e.jsxs(kr,{className:"gap-2",children:[e.jsx($,{variant:"ghost",onClick:()=>R(null),children:"Cancel"}),e.jsx($,{onClick:me,disabled:n.isPending||r.isPending,className:"bg-gradient-to-r from-violet-600 to-indigo-600",children:"Save"})]})]})}),e.jsx(hKn,{item:O,onClose:()=>B(null),onSave:async(te,le)=>{await r.mutateAsync({id:O.id,status:"completed",outcome:te}),le&&await l.mutateAsync({title:`Post-event follow-up: ${O.title}`,dueAt:new Date(Date.now()+2*864e5).toISOString(),notes:te.next_actions}),await o.mutateAsync({title:`Spoke at ${O.title}`,activityType:"speaking_completed"}),B(null)}})]})}function njt(s){if(!s)return"";const t=new Date(s),n=t.getTimezoneOffset();return new Date(t.getTime()-n*6e4).toISOString().slice(0,16)}function Pm({label:s,children:t,className:n}){return e.jsxs("div",{className:n,children:[e.jsx(re,{className:"text-[12px] text-slate-600 mb-1 block",children:s}),t]})}function dW({label:s,value:t,icon:n}){return e.jsxs(we,{className:"p-4 rounded-2xl",children:[e.jsx(n,{className:"h-4 w-4 text-violet-600"}),e.jsx("div",{className:"mt-1 text-[22px] font-semibold tabular-nums text-slate-900",children:t}),e.jsx("div",{className:"text-[11.5px] text-slate-500",children:s})]})}function uKn({o:s,onEdit:t,onComplete:n,onDuplicate:r,onDelete:a,onArchive:i,onIcs:l,onPitchTask:o,onLogOutreach:c,onConfirm:d}){var m;const u=s,h=u.submission_deadline?o1(Mp(u.submission_deadline),new Date):null;return e.jsx(we,{className:"p-4 rounded-2xl",children:e.jsxs("div",{className:"flex items-start justify-between gap-3 flex-wrap",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("button",{onClick:t,className:"text-[15px] font-semibold text-slate-900 hover:text-violet-700 text-left",children:u.title}),e.jsx("div",{className:"text-[12.5px] text-slate-500 mt-0.5",children:[u.organization,(m=u.event_type)==null?void 0:m.replace(/_/g," "),u.audience].filter(Boolean).join(" · ")||"No details yet"}),e.jsxs("div",{className:"text-[12.5px] text-slate-600 mt-1 flex items-center gap-3 flex-wrap",children:[u.starts_at&&e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(fd,{className:"h-3.5 w-3.5"}),Ys(Mp(u.starts_at),"EEE MMM d, h:mm a")]}),h!==null&&e.jsxs("span",{className:`inline-flex items-center gap-1 ${h<7?"text-orange-600":""}`,children:[e.jsx(sa,{className:"h-3.5 w-3.5"}),"Deadline in ",h,"d"]}),(u.linked_agent_ids??[]).length>0&&e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(Xn,{className:"h-3.5 w-3.5"}),u.linked_agent_ids.length," linked"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(qe,{variant:"outline",className:`capitalize rounded-full ${Fqe[u.status]??""}`,children:u.status}),e.jsxs(Au,{children:[e.jsx(Eu,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:"rounded-full",children:e.jsx(u0,{className:"h-4 w-4"})})}),e.jsxs(gu,{align:"end",children:[e.jsx(Pa,{onClick:t,children:"Edit"}),e.jsxs(Pa,{onClick:o,children:[e.jsx(op,{className:"h-3.5 w-3.5 mr-2"}),"Add pitch task"]}),e.jsxs(Pa,{onClick:c,children:[e.jsx(Wr,{className:"h-3.5 w-3.5 mr-2"}),"Log outreach"]}),e.jsxs(Pa,{onClick:d,children:[e.jsx(Gr,{className:"h-3.5 w-3.5 mr-2"}),"Mark confirmed"]}),e.jsxs(Pa,{onClick:n,children:[e.jsx(Gr,{className:"h-3.5 w-3.5 mr-2"}),"Mark completed"]}),e.jsxs(Pa,{onClick:l,children:[e.jsx(ji,{className:"h-3.5 w-3.5 mr-2"}),"Download .ics"]}),e.jsxs(Pa,{onClick:r,children:[e.jsx(Da,{className:"h-3.5 w-3.5 mr-2"}),"Duplicate"]}),e.jsxs(Pa,{onClick:i,children:[e.jsx(kf,{className:"h-3.5 w-3.5 mr-2"}),u.is_archived?"Unarchive":"Archive"]}),e.jsxs(Pa,{className:"text-destructive",onClick:a,children:[e.jsx(Un,{className:"h-3.5 w-3.5 mr-2"}),"Delete"]})]})]})]})]})})}function hKn({item:s,onClose:t,onSave:n}){const[r,a]=k.useState(""),[i,l]=k.useState(""),[o,c]=k.useState(""),[d,u]=k.useState("");return e.jsx(zs,{open:!!s,onOpenChange:h=>!h&&t(),children:e.jsxs(Rs,{className:"max-w-lg",children:[e.jsx(Vs,{children:e.jsx($s,{children:"Capture the outcome"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(Pm,{label:"Attendance",children:e.jsx(be,{value:r,onChange:h=>a(h.target.value),placeholder:"How many were in the room?"})}),e.jsx(Pm,{label:"Leads / relationships created",children:e.jsx(Ls,{rows:2,value:i,onChange:h=>l(h.target.value)})}),e.jsx(Pm,{label:"Content captured",children:e.jsx(Ls,{rows:2,value:o,onChange:h=>c(h.target.value),placeholder:"Photos, clips, quotes"})}),e.jsx(Pm,{label:"Next actions",children:e.jsx(Ls,{rows:2,value:d,onChange:h=>u(h.target.value)})})]}),e.jsxs(kr,{className:"gap-2",children:[e.jsx($,{variant:"ghost",onClick:t,children:"Cancel"}),e.jsx($,{variant:"outline",onClick:()=>n({attendance:r,leads:i,content:o,next_actions:d},!1),children:"Save only"}),e.jsx($,{className:"bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>n({attendance:r,leads:i,content:o,next_actions:d},!0),children:"Save + create follow-up"})]})]})})}const Tz=V,zqe=["attract-masterclasses"];function mKn(){const{user:s}=ks(),t=ls(),n=pt({queryKey:[...zqe,s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:o,error:c}=await Tz.from("attract_masterclasses").select("*").order("updated_at",{ascending:!1});if(c)throw c;return o??[]}}),r=()=>t.invalidateQueries({queryKey:zqe}),a=Nt({mutationFn:async o=>{const{data:c,error:d}=await Tz.from("attract_masterclasses").insert({title:"Untitled masterclass",...o,user_id:s.id}).select("*").single();if(d)throw d;return c},onSuccess:()=>r(),onError:o=>ae.error(o.message)}),i=Nt({mutationFn:async o=>{const{id:c,created_at:d,updated_at:u,user_id:h,...m}=o,{data:p,error:g}=await Tz.from("attract_masterclasses").insert({...m,title:`${o.title} (copy)`,status:"draft",user_id:s.id}).select("id").single();if(g)throw g;return p},onSuccess:()=>{r(),ae.success("Duplicated")},onError:o=>ae.error(o.message)}),l=Nt({mutationFn:async o=>{const{error:c}=await Tz.from("attract_masterclasses").delete().eq("id",o);if(c)throw c},onSuccess:()=>{r(),ae.success("Deleted")},onError:o=>ae.error(o.message)});return{items:n.data??[],isLoading:n.isLoading,refetch:n.refetch,create:a,duplicate:i,remove:l}}function fKn(s){const t=ls(),n=pt({queryKey:["attract-masterclass",s],enabled:!!s,queryFn:async()=>{const{data:a,error:i}=await Tz.from("attract_masterclasses").select("*").eq("id",s).maybeSingle();if(i)throw i;return a}}),r=Nt({mutationFn:async a=>{const{error:i}=await Tz.from("attract_masterclasses").update(a).eq("id",s);if(i)throw i},onSuccess:()=>{t.invalidateQueries({queryKey:["attract-masterclass",s]}),t.invalidateQueries({queryKey:zqe})},onError:a=>ae.error(a.message)});return{masterclass:n.data??null,isLoading:n.isLoading,save:r}}const Gf=(s,t)=>({id:crypto.randomUUID(),title:s,lessons:t.map(([n,r,a])=>({id:crypto.randomUUID(),title:n,minutes:r,talking_points:a}))}),rjt=[{key:"listing_presentation",title:"Listing Presentation Masterclass",promise:"Walk out with a listing presentation that wins the room in the first five minutes.",target_audience:"Agents who get appointments but lose listings to bigger names.",problem_solved:"Presentations that talk about the agent instead of the seller outcome.",desired_outcome:"A rebuilt opening, pricing story, and close they can use this week.",pillar:"provide",duration_minutes:60,curriculum:[Gf("Open strong",[["Why sellers decide in 5 minutes",8,"Trust signals, pacing, the first question you ask"],["The pre-listing package",7,"What to send ahead and why it changes the room"]]),Gf("The pricing conversation",[["Framing price without arguing",12,"Data as a story, not a spreadsheet"],["Handling the overpriced seller",10,"Language patterns and walking-away criteria"]]),Gf("Close and next steps",[["Asking for the signature",8,"Assumptive close variations"],[`Follow-up if they say "we'll think about it"`,8,"48-hour sequence"]])]},{key:"database_revival",title:"Database Revival Workshop",promise:"Reactivate a cold database into real conversations in 30 days.",target_audience:"Agents with 200+ contacts and no consistent outreach.",problem_solved:"A database that exists but produces nothing.",desired_outcome:"A cleaned list, a cadence, and 10 conversations started live in class.",pillar:"provide",duration_minutes:60,curriculum:[Gf("Audit",[["Sorting your list into A/B/C",10,"Criteria that actually predict referrals"],["Fixing missing data",8,"Birthdays, anniversaries, spouse names"]]),Gf("The reach-out",[["The no-ask message",12,"Scripts that do not feel like prospecting"],["Voice notes and video",10,"Why they convert 3x text"]]),Gf("The cadence",[["Building a 12-touch year",12,"Pop-bys, events, market notes"],["Tracking without a CRM headache",8,"Simple weekly rhythm"]])]},{key:"open_house_conversion",title:"Open House Lead Conversion",promise:"Turn a normal open house into 3-5 real buyer conversations.",target_audience:"Newer agents relying on open houses for pipeline.",problem_solved:"Sign-in sheets full of names that never convert.",desired_outcome:"A pre-, during-, and post-open-house system.",pillar:"produce",duration_minutes:45,curriculum:[Gf("Before",[["Neighborhood invites",8,"Door knocking and digital invites"],["Setting the stage",7,"Materials that create conversations"]]),Gf("During",[["The three questions",10,"How to qualify without interrogating"],["Capturing real contact info",8,"Sign-in that people actually complete"]]),Gf("After",[["The 10-minute follow-up",7,"Speed to lead"],["Week-one nurture",5,"What to send day 1, 3, 7"]])]},{key:"social_authority",title:"Social Media Authority",promise:"Build a local social presence that makes agents and clients come to you.",target_audience:"Agents posting inconsistently with little engagement.",problem_solved:"Random posting with no positioning.",desired_outcome:"A content pillar map and 30 days of planned posts.",pillar:"influence",duration_minutes:60,curriculum:[Gf("Positioning",[["Pick your lane",10,"Neighborhood, niche, or narrative"],["What to never post",6,"The credibility killers"]]),Gf("Content system",[["The four content types",14,"Teach, prove, connect, invite"],["Batch filming",10,"One hour, ten pieces"]]),Gf("Distribution",[["Captions and hooks",10,"First-line formulas"],["Turning comments into DMs",10,"Relationship-first outreach"]])]},{key:"ai_for_agents",title:"AI for Agents",promise:"Use AI to save 5 hours a week without sounding like a robot.",target_audience:"Agents curious about AI but unsure where to start.",problem_solved:"Tool overwhelm and generic AI output.",desired_outcome:"Three working workflows they set up live.",pillar:"influence",duration_minutes:60,curriculum:[Gf("Foundations",[["What AI is good and bad at",10,"Drafting vs deciding"],["Prompting basics",10,"Context, role, constraints"]]),Gf("Workflows",[["Listing descriptions and marketing",12,"Brand voice inputs"],["Follow-up and email drafts",12,"Never auto-send"]]),Gf("Guardrails",[["Compliance and fair housing",10,"What to always review"],["Keeping your voice",6,"Editing pass checklist"]])]},{key:"new_construction",title:"New Construction Buyer Workshop",promise:"Represent new construction buyers with confidence and get paid.",target_audience:"Agents losing buyers to builder sales offices.",problem_solved:"Not knowing builder contracts or registration rules.",desired_outcome:"A registration process and builder relationship plan.",pillar:"produce",duration_minutes:60,curriculum:[Gf("The builder landscape",[["How builder comp works",12,"Registration rules that protect you"],["Local builders worth knowing",8,"Relationship map"]]),Gf("Representing the buyer",[["Contract differences",14,"What is negotiable"],["Inspections and walkthroughs",10,"Timeline checkpoints"]]),Gf("Winning the relationship",[["First-visit protocol",8,"Always accompany"],["Post-close referrals",8,"The neighborhood effect"]])]},{key:"luxury_experience",title:"Luxury Client Experience",promise:"Deliver an experience that earns luxury referrals.",target_audience:"Agents moving into a higher price band.",problem_solved:"Marketing and service that feels mid-market.",desired_outcome:"An upgraded listing experience and presentation standard.",pillar:"provide",duration_minutes:60,curriculum:[Gf("Standards",[["What luxury clients notice",12,"Response time, discretion, detail"],["Your materials",10,"Photography, print, web"]]),Gf("The listing experience",[["Pre-market strategy",12,"Whisper listings and staging"],["Private showings",8,"Choreography"]]),Gf("Referral engine",[["Post-close cadence",10,"Gifting and anniversaries"],["Building the circle",8,"Vendors and advisors"]])]},{key:"recruiting_value",title:"Recruiting Through Value",promise:"Attract agents by helping them, not pitching them.",target_audience:"Team leaders and agents building revenue share.",problem_solved:"Recruiting that feels salesy and gets ignored.",desired_outcome:"A value-first attraction plan for 20 named agents.",pillar:"connect",duration_minutes:60,curriculum:[Gf("Mindset",[["Why value beats pitching",10,"Relationship-first framing"],["Choosing your 20",8,"Fit criteria"]]),Gf("The value plan",[["Resource kits that help",14,"What agents actually want"],["Events and masterminds",10,"Small rooms win"]]),Gf("The conversation",[["When to talk business",10,"Earned invitation"],['Handling "I am happy where I am"',8,"Stay in relationship"]])]}];function pKn(s){return{title:s.title,promise:s.promise,target_audience:s.target_audience,problem_solved:s.problem_solved,desired_outcome:s.desired_outcome,pillar:s.pillar,duration_minutes:s.duration_minutes,curriculum:s.curriculum,source_template_key:s.key,status:"draft"}}function gKn(s){const t=s.title||"Untitled masterclass",n=s.delivery_date?new Date(s.delivery_date).toLocaleString("en-US",{timeZone:"America/New_York",dateStyle:"full",timeStyle:"short"}):"Date to be announced",r=(s.curriculum??[]).flatMap(i=>i.lessons.map(l=>`• ${l.title}`)).slice(0,6).join(` `),a=s.promise||"A practical, no-pitch training session.";return{registration_copy:`${t} ${n} · ${s.duration_minutes??45} minutes · ${s.format??"virtual"} ${a} Who it's for: ${s.target_audience||"Agents who want a practical system."} What we'll cover: ${r||"• Curriculum coming soon"} What you'll leave with: ${s.desired_outcome||"A plan you can use immediately."}`,email_invite:`Subject: ${t} Hi {{first_name}}, I'm hosting ${t} on ${n}. ${a} It's built for ${s.target_audience||"agents like you"} — no pitch, just the system. We'll cover: ${r||"• Curriculum coming soon"} Want me to save you a seat? {{my_name}}`,social_post:`${a} I'm teaching ${t} on ${n}. ${r||""} Free. Comment "SEAT" and I'll send the link.`,dm_invite:`Hey {{first_name}} — I'm running a short session called "${t}" on ${n}. Thought of you because of ${s.problem_solved||"what we talked about"}. Want the link?`,reminder:`Hi {{first_name}} — quick reminder that ${t} starts ${n}. Here's the link: {{join_link}}. Bring one question.`,follow_up:`Hi {{first_name}} — thanks for joining ${t}. Here's the recording and the workbook: {{resource_link}}. One thing to try this week: ${s.desired_outcome||"pick a single takeaway and run it."} Happy to walk through it one-on-one if useful.`}}function xKn(s){const t=[`RUN OF SHOW — ${s.title||"Masterclass"}`,""];let n=0;return t.push("0:00 Welcome, why we're here, one-line promise"),n+=3,(s.curriculum??[]).forEach(r=>{t.push("",`${Aie(n)} SECTION: ${r.title}`),r.lessons.forEach(a=>{t.push(`${Aie(n)} ${a.title}${a.minutes?` (${a.minutes}m)`:""}${a.talking_points?` — ${a.talking_points}`:""}`),n+=a.minutes??5})}),t.push("",`${Aie(n)} Q&A`,`${Aie(n+7)} Close: next step + resource kit`),t.join(` `)}function Aie(s){const t=Math.floor(s/60),n=s%60;return`${t}:${String(n).padStart(2,"0")}`}function yKn(){const{items:s,isLoading:t,create:n,duplicate:r,remove:a}=mKn(),i=Jn(),[l,o]=k.useState(!1),c=s.filter(m=>!m.is_archived),d=s.filter(m=>m.is_archived),u=async()=>{const m=await n.mutateAsync({title:"Untitled masterclass"});i(`/attract/provide/masterclasses/${m.id}`)},h=async m=>{const p=rjt.find(x=>x.key===m),g=await n.mutateAsync(pKn(p));i(`/attract/provide/masterclasses/${g.id}`)};return t?e.jsxs("div",{className:"space-y-4",children:[e.jsx(fn,{className:"h-28 rounded-2xl"}),e.jsx(fn,{className:"h-64 rounded-2xl"})]}):e.jsxs("div",{className:"space-y-6",children:[e.jsx(Hm,{eyebrow:"Pillar 03 · Provide",title:"Masterclass Builder",description:"Turn what you already know into a 45-minute teaching moment agents actually attend — curriculum, assets, promotion, run-of-show, and follow-up.",actions:e.jsxs("div",{className:"flex gap-2",children:[e.jsxs($,{variant:"outline",className:"rounded-full",onClick:()=>o(m=>!m),children:[e.jsx(kn,{className:"h-4 w-4 mr-2"}),"Starter templates"]}),e.jsxs($,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:u,disabled:n.isPending,children:[e.jsx(nn,{className:"h-4 w-4 mr-2"}),"New masterclass"]})]})}),(l||s.length===0)&&e.jsxs(we,{className:"p-5 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-violet-700 font-semibold mb-3",children:"Starter templates"}),e.jsx("div",{className:"grid sm:grid-cols-2 xl:grid-cols-4 gap-3",children:rjt.map(m=>e.jsxs("button",{onClick:()=>h(m.key),className:"text-left p-4 rounded-xl border hover:border-violet-300 hover:shadow-sm transition",children:[e.jsx(qe,{variant:"secondary",className:"capitalize mb-2",children:m.pillar}),e.jsx("div",{className:"font-semibold text-[14px] text-slate-900",children:m.title}),e.jsx("div",{className:"text-[12.5px] text-slate-500 mt-1 line-clamp-3",children:m.promise}),e.jsxs("div",{className:"text-[11.5px] text-slate-400 mt-2",children:[m.duration_minutes," min · ",m.curriculum.length," sections"]})]},m.key))})]}),c.length===0?e.jsxs(we,{className:"p-10 rounded-2xl text-center",children:[e.jsx(Bm,{className:"h-8 w-8 mx-auto text-violet-500"}),e.jsx("div",{className:"text-[16px] font-semibold mt-3",children:"No masterclasses yet"}),e.jsx("p",{className:"text-[13.5px] text-slate-500 mt-1 max-w-md mx-auto",children:"Pick a starter template above or build one from scratch. Nothing sends automatically — every piece of copy stays an editable draft."})]}):e.jsx("div",{className:"grid sm:grid-cols-2 xl:grid-cols-3 gap-3",children:c.map(m=>e.jsxs(we,{className:"p-4 rounded-2xl",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsx(qe,{variant:"outline",className:"capitalize rounded-full",children:m.status}),e.jsxs(Au,{children:[e.jsx(Eu,{asChild:!0,children:e.jsx($,{variant:"ghost",size:"icon",className:"rounded-full h-7 w-7",children:e.jsx(u0,{className:"h-4 w-4"})})}),e.jsxs(gu,{align:"end",children:[e.jsx(Pa,{onClick:()=>i(`/attract/provide/masterclasses/${m.id}`),children:"Open builder"}),e.jsxs(Pa,{onClick:()=>r.mutate(m),children:[e.jsx(Da,{className:"h-3.5 w-3.5 mr-2"}),"Duplicate"]}),e.jsxs(Pa,{className:"text-destructive",onClick:()=>a.mutate(m.id),children:[e.jsx(Un,{className:"h-3.5 w-3.5 mr-2"}),"Delete"]})]})]})]}),e.jsxs(nr,{to:`/attract/provide/masterclasses/${m.id}`,className:"block mt-2",children:[e.jsx("div",{className:"font-semibold text-slate-900 line-clamp-2",children:m.title}),m.promise&&e.jsx("div",{className:"text-[12.5px] text-slate-500 line-clamp-2 mt-1",children:m.promise})]}),e.jsxs("div",{className:"text-[11.5px] text-slate-400 mt-3",children:[(m.curriculum??[]).length," sections · ",m.duration_minutes??45," min",m.delivery_date&&` · ${Ys(new Date(m.delivery_date),"MMM d")}`]})]},m.id))}),d.length>0&&e.jsxs(we,{className:"p-4 rounded-2xl",children:[e.jsxs("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-2 flex items-center gap-1.5",children:[e.jsx(kf,{className:"h-3.5 w-3.5"}),"Archived"]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:d.map(m=>e.jsx(nr,{to:`/attract/provide/masterclasses/${m.id}`,className:"text-[12.5px] px-2.5 py-1 rounded-full border text-slate-600",children:m.title},m.id))})]}),e.jsx(JF,{})]})}const ajt=V,vKn=["Strategy","Curriculum","Assets","Promotion","Delivery","Follow-up"];function bKn(){var G,H,Y,se,ee,oe,me,Q,te,le,fe,_e,ve;const{masterclassId:s}=oo(),t=Jn(),{user:n}=ks(),{masterclass:r,isLoading:a,save:i}=fKn(s),l=kWt(),{create:o}=YV(),[c,d]=k.useState(null),[u,h]=k.useState(0),[m,p]=k.useState(!1),[g,x]=k.useState("idle"),y=k.useRef(null),v=k.useRef(!1);k.useEffect(()=>{r&&!c&&d(r)},[r,c]);const _=he=>{d(Se=>Se&&{...Se,...he}),v.current=!0,x("saving"),clearTimeout(y.current),y.current=setTimeout(()=>j({...c??{},...he}),900)},j=async he=>{const{id:Se,user_id:Te,created_at:Ie,updated_at:Ue,...Be}=he;await i.mutateAsync(Be),v.current=!1,x("saved"),setTimeout(()=>x(je=>je==="saved"?"idle":je),1800)},C=(c==null?void 0:c.curriculum)??[],A=he=>_({curriculum:he}),M=k.useMemo(()=>C.reduce((he,Se)=>he+Se.lessons.reduce((Te,Ie)=>Te+(Ie.minutes??0),0),0),[C]);if(a||!c)return e.jsxs("div",{className:"space-y-4",children:[e.jsx(fn,{className:"h-24 rounded-2xl"}),e.jsx(fn,{className:"h-96 rounded-2xl"})]});const I=()=>{_({promotion:{...c.promotion,...gKn(c)}}),ae.success("Draft copy generated — edit before you send anything")},P=()=>{_({delivery:{...c.delivery,run_of_show:xKn(c)}}),ae.success("Run of show generated")},R=async()=>{const he=await l.mutateAsync({title:c.title,description:c.promise??void 0,event_type:"masterclass",intended_audience:c.target_audience??void 0,related_pillar:c.pillar??"provide",starts_at:c.delivery_date??new Date(Date.now()+12096e5).toISOString(),format:c.format==="in_person"?"in_person":"virtual",agenda:C.flatMap(Se=>Se.lessons.map(Te=>({item:`${Se.title}: ${Te.title}`}))),learning_outcomes:c.desired_outcome?[c.desired_outcome]:[]});await i.mutateAsync({linked_event_id:he.id,status:"scheduled"}),d(Se=>Se&&{...Se,linked_event_id:he.id,status:"scheduled"}),ae.success("Connect event created as a draft"),t(`/attract/events/${he.id}/edit`)},O=async()=>{var Te,Ie,Ue,Be,je;const he=await o.mutateAsync({title:`${c.title} — Resource Kit`,description:c.promise??void 0,audience:c.target_audience??void 0,pillar:c.pillar??"provide",intro_text:((Te=c.assets)==null?void 0:Te.workbook)??void 0,cta_label:((Ie=c.assets)==null?void 0:Ie.cta_label)??void 0,cta_url:((Ue=c.assets)==null?void 0:Ue.cta_url)??void 0}),Se=[...(((Be=c.assets)==null?void 0:Be.downloads)??[]).map((Ye,Ee)=>({type:"link",title:Ye.title,url:Ye.url,sort_order:Ee})),...(((je=c.assets)==null?void 0:je.videos)??[]).map((Ye,Ee)=>({type:"video",title:Ye.title,url:Ye.url,sort_order:100+Ee}))];Se.length&&await ajt.from("attract_resource_kit_items").insert(Se.map(Ye=>({...Ye,kit_id:he.id,user_id:n.id}))),await i.mutateAsync({linked_kit_id:he.id}),d(Ye=>Ye&&{...Ye,linked_kit_id:he.id}),ae.success("Resource Kit created from your assets"),t(`/attract/provide/kits/${he.id}/edit`)},B=async()=>{const he=Date.now(),Se=[{title:`Send recap + resources: ${c.title}`,due_at:new Date(he+1*864e5).toISOString()},{title:`Personal check-in with attendees: ${c.title}`,due_at:new Date(he+3*864e5).toISOString()},{title:`Invite engaged attendees to a 1:1: ${c.title}`,due_at:new Date(he+7*864e5).toISOString()}],{error:Te}=await ajt.from("attract_follow_ups").insert(Se.map(Ie=>({...Ie,user_id:n.id,touch_type:"masterclass",priority:"medium"})));if(Te){ae.error(Te.message);return}ae.success("3 follow-ups added to your Follow-Up Center")};return e.jsxs("div",{className:"space-y-5",children:[e.jsx($,{variant:"ghost",size:"sm",className:"rounded-full -ml-2",asChild:!0,children:e.jsxs(nr,{to:"/attract/provide/masterclasses",children:[e.jsx(Ia,{className:"h-3.5 w-3.5 mr-1.5"}),"All masterclasses"]})}),e.jsx(Hm,{eyebrow:"Pillar 03 · Provide",title:c.title||"Untitled masterclass",description:c.promise??"Build the promise, curriculum, assets, promotion, delivery and follow-up.",actions:e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"text-[12px] text-slate-500 inline-flex items-center gap-1.5",children:g==="saving"?e.jsxs(e.Fragment,{children:[e.jsx(Jt,{className:"h-3.5 w-3.5 animate-spin"}),"Saving…"]}):g==="saved"?e.jsxs(e.Fragment,{children:[e.jsx(ma,{className:"h-3.5 w-3.5 text-emerald-600"}),"Saved"]}):"All changes saved"}),e.jsxs($,{variant:"outline",className:"rounded-full",onClick:()=>p(he=>!he),children:[e.jsx(ba,{className:"h-4 w-4 mr-2"}),m?"Edit":"Preview"]})]})}),e.jsx(we,{className:"p-2 rounded-2xl flex gap-1 overflow-x-auto",children:vKn.map((he,Se)=>e.jsxs("button",{onClick:()=>{p(!1),h(Se)},className:`px-3.5 py-2 rounded-xl text-[13px] font-medium whitespace-nowrap ${u===Se&&!m?"bg-violet-600 text-white":"text-slate-600 hover:bg-slate-100"}`,children:[Se+1,". ",he]},he))}),m?e.jsx(wKn,{m:c}):e.jsxs(we,{className:"p-5 rounded-2xl space-y-4",children:[u===0&&e.jsxs("div",{className:"grid sm:grid-cols-2 gap-3",children:[e.jsx(lg,{label:"Title",className:"sm:col-span-2",children:e.jsx(be,{value:c.title,onChange:he=>_({title:he.target.value})})}),e.jsx(lg,{label:"The promise",className:"sm:col-span-2",children:e.jsx(Ls,{rows:2,value:c.promise??"",onChange:he=>_({promise:he.target.value}),placeholder:"Walk out with…"})}),e.jsx(lg,{label:"Target audience",children:e.jsx(be,{value:c.target_audience??"",onChange:he=>_({target_audience:he.target.value})})}),e.jsx(lg,{label:"Problem solved",children:e.jsx(be,{value:c.problem_solved??"",onChange:he=>_({problem_solved:he.target.value})})}),e.jsx(lg,{label:"Desired outcome",className:"sm:col-span-2",children:e.jsx(be,{value:c.desired_outcome??"",onChange:he=>_({desired_outcome:he.target.value})})}),e.jsx(lg,{label:"Pillar",children:e.jsxs(bs,{value:c.pillar??"provide",onValueChange:he=>_({pillar:he}),children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsx(vs,{children:["produce","influence","provide","connect"].map(he=>e.jsx(We,{value:he,className:"capitalize",children:he},he))})]})}),e.jsx(lg,{label:"Format",children:e.jsxs(bs,{value:c.format??"virtual",onValueChange:he=>_({format:he}),children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsx(vs,{children:["virtual","in_person","hybrid"].map(he=>e.jsx(We,{value:he,className:"capitalize",children:he.replace("_"," ")},he))})]})}),e.jsx(lg,{label:"Duration (minutes)",children:e.jsx(be,{type:"number",value:c.duration_minutes??45,onChange:he=>_({duration_minutes:Number(he.target.value)})})}),e.jsx(lg,{label:"Delivery date",children:e.jsx(be,{type:"datetime-local",value:_Kn(c.delivery_date),onChange:he=>_({delivery_date:he.target.value?new Date(he.target.value).toISOString():null})})}),e.jsx(lg,{label:"Status",children:e.jsxs(bs,{value:c.status,onValueChange:he=>_({status:he}),children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsx(vs,{children:["draft","ready","scheduled","delivered","archived"].map(he=>e.jsx(We,{value:he,className:"capitalize",children:he},he))})]})})]}),u===1&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"text-[12.5px] text-slate-500",children:[C.length," sections · ",M," minutes planned"]}),e.jsxs($,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>A([...C,{id:crypto.randomUUID(),title:"New section",lessons:[]}]),children:[e.jsx(nn,{className:"h-3.5 w-3.5 mr-1.5"}),"Add section"]})]}),C.length===0&&e.jsx("div",{className:"text-[13.5px] text-slate-500 border border-dashed rounded-xl p-8 text-center",children:"No sections yet. Add your first one."}),C.map((he,Se)=>e.jsxs(we,{className:"p-4 rounded-xl bg-slate-50/60",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(be,{value:he.title,onChange:Te=>A(C.map(Ie=>Ie.id===he.id?{...Ie,title:Te.target.value}:Ie)),className:"font-semibold"}),e.jsx($,{variant:"ghost",size:"icon",disabled:Se===0,onClick:()=>A(Eie(C,Se,Se-1)),children:e.jsx(Ny,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",disabled:Se===C.length-1,onClick:()=>A(Eie(C,Se,Se+1)),children:e.jsx(Go,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",className:"text-destructive",onClick:()=>A(C.filter(Te=>Te.id!==he.id)),children:e.jsx(Un,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"mt-3 space-y-3",children:[he.lessons.map((Te,Ie)=>e.jsxs("div",{className:"rounded-lg border bg-white p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(be,{value:Te.title,placeholder:"Lesson title",onChange:Ue=>U(he.id,Te.id,{title:Ue.target.value})}),e.jsx(be,{type:"number",className:"w-20",value:Te.minutes??"",placeholder:"min",onChange:Ue=>U(he.id,Te.id,{minutes:Number(Ue.target.value)})}),e.jsx($,{variant:"ghost",size:"icon",disabled:Ie===0,onClick:()=>A(C.map(Ue=>Ue.id===he.id?{...Ue,lessons:Eie(Ue.lessons,Ie,Ie-1)}:Ue)),children:e.jsx(Ny,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",disabled:Ie===he.lessons.length-1,onClick:()=>A(C.map(Ue=>Ue.id===he.id?{...Ue,lessons:Eie(Ue.lessons,Ie,Ie+1)}:Ue)),children:e.jsx(Go,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"icon",className:"text-destructive",onClick:()=>A(C.map(Ue=>Ue.id===he.id?{...Ue,lessons:Ue.lessons.filter(Be=>Be.id!==Te.id)}:Ue)),children:e.jsx(Un,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"grid sm:grid-cols-2 gap-2",children:[e.jsx(Ls,{rows:2,placeholder:"Talking points",value:Te.talking_points??"",onChange:Ue=>U(he.id,Te.id,{talking_points:Ue.target.value})}),e.jsx(Ls,{rows:2,placeholder:"Exercise",value:Te.exercise??"",onChange:Ue=>U(he.id,Te.id,{exercise:Ue.target.value})}),e.jsx(Ls,{rows:2,placeholder:"Example / story",value:Te.example??"",onChange:Ue=>U(he.id,Te.id,{example:Ue.target.value})}),e.jsx(Ls,{rows:2,placeholder:"Speaker notes",value:Te.speaker_notes??"",onChange:Ue=>U(he.id,Te.id,{speaker_notes:Ue.target.value})})]})]},Te.id)),e.jsxs($,{size:"sm",variant:"ghost",onClick:()=>A(C.map(Te=>Te.id===he.id?{...Te,lessons:[...Te.lessons,{id:crypto.randomUUID(),title:""}]}:Te)),children:[e.jsx(nn,{className:"h-3.5 w-3.5 mr-1.5"}),"Add lesson"]})]})]},he.id))]}),u===2&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(lg,{label:"Slide outline",children:e.jsx(Ls,{rows:5,value:((G=c.assets)==null?void 0:G.slide_outline)??"",onChange:he=>_({assets:{...c.assets,slide_outline:he.target.value}})})}),e.jsx(lg,{label:"Workbook / checklist outline",children:e.jsx(Ls,{rows:5,value:((H=c.assets)==null?void 0:H.workbook)??"",onChange:he=>_({assets:{...c.assets,workbook:he.target.value}})})}),e.jsx(ijt,{label:"Downloads",items:((Y=c.assets)==null?void 0:Y.downloads)??[],onChange:he=>_({assets:{...c.assets,downloads:he}})}),e.jsx(ijt,{label:"Videos",items:((se=c.assets)==null?void 0:se.videos)??[],onChange:he=>_({assets:{...c.assets,videos:he}})}),e.jsxs("div",{className:"grid sm:grid-cols-2 gap-3",children:[e.jsx(lg,{label:"CTA label",children:e.jsx(be,{value:((ee=c.assets)==null?void 0:ee.cta_label)??"",onChange:he=>_({assets:{...c.assets,cta_label:he.target.value}})})}),e.jsx(lg,{label:"CTA URL",children:e.jsx(be,{value:((oe=c.assets)==null?void 0:oe.cta_url)??"",onChange:he=>_({assets:{...c.assets,cta_url:he.target.value}})})})]}),e.jsxs($,{variant:"outline",className:"rounded-full",onClick:O,disabled:o.isPending,children:[e.jsx(UK,{className:"h-4 w-4 mr-2"}),"Create Resource Kit from these assets"]}),c.linked_kit_id&&e.jsx(qe,{variant:"outline",className:"ml-2",children:"Kit linked"})]}),u===3&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-2",children:[e.jsx("div",{className:"text-[12.5px] text-slate-500",children:"Every piece stays an editable draft. Nothing sends automatically."}),e.jsxs($,{variant:"outline",className:"rounded-full",onClick:I,children:[e.jsx(vf,{className:"h-4 w-4 mr-2"}),"Generate draft copy"]})]}),[["registration_copy","Registration page copy"],["email_invite","Email invite"],["social_post","Social post"],["dm_invite","DM / text invite"],["reminder","Reminder message"],["follow_up","Follow-up message"]].map(([he,Se])=>{var Te;return e.jsx(lg,{label:Se,children:e.jsx(Ls,{rows:5,value:((Te=c.promotion)==null?void 0:Te[he])??"",onChange:Ie=>_({promotion:{...c.promotion,[he]:Ie.target.value}})})},he)})]}),u===4&&e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"flex justify-end",children:e.jsxs($,{variant:"outline",className:"rounded-full",onClick:P,children:[e.jsx(vf,{className:"h-4 w-4 mr-2"}),"Build run of show"]})}),e.jsx(lg,{label:"Run of show",children:e.jsx(Ls,{rows:12,className:"font-mono text-[12.5px]",value:((me=c.delivery)==null?void 0:me.run_of_show)??"",onChange:he=>_({delivery:{...c.delivery,run_of_show:he.target.value}})})}),e.jsx(lg,{label:"Check-in link",children:e.jsx(be,{value:((Q=c.delivery)==null?void 0:Q.checkin_link)??"",onChange:he=>_({delivery:{...c.delivery,checkin_link:he.target.value}}),placeholder:"Paste the Connect event check-in URL"})}),e.jsx(lg,{label:"Event notes",children:e.jsx(Ls,{rows:4,value:((te=c.delivery)==null?void 0:te.event_notes)??"",onChange:he=>_({delivery:{...c.delivery,event_notes:he.target.value}})})}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs($,{variant:"outline",className:"rounded-full",onClick:R,disabled:l.isPending,children:[e.jsx(i1,{className:"h-4 w-4 mr-2"}),"Convert to a Connect event"]}),c.linked_event_id&&e.jsx($,{variant:"ghost",className:"rounded-full",asChild:!0,children:e.jsx(nr,{to:`/attract/events/${c.linked_event_id}`,children:"Open linked event"})})]})]}),u===5&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(lg,{label:"Attendee segmentation",children:e.jsx(Ls,{rows:3,value:((le=c.follow_up)==null?void 0:le.segments)??"",onChange:he=>_({follow_up:{...c.follow_up,segments:he.target.value}}),placeholder:"Attended + asked a question / attended / registered no-show"})}),e.jsx(lg,{label:"Resource kit sharing note",children:e.jsx(Ls,{rows:3,value:((fe=c.follow_up)==null?void 0:fe.kit_note)??"",onChange:he=>_({follow_up:{...c.follow_up,kit_note:he.target.value}})})}),e.jsx(lg,{label:"Suggested personal follow-ups",children:e.jsx(Ls,{rows:3,value:((_e=c.follow_up)==null?void 0:_e.personal_touches)??"",onChange:he=>_({follow_up:{...c.follow_up,personal_touches:he.target.value}})})}),e.jsx(lg,{label:"Conversion / relationship outcomes",children:e.jsx(Ls,{rows:3,value:((ve=c.follow_up)==null?void 0:ve.outcomes)??"",onChange:he=>_({follow_up:{...c.follow_up,outcomes:he.target.value}})})}),e.jsxs($,{variant:"outline",className:"rounded-full",onClick:B,children:[e.jsx(op,{className:"h-4 w-4 mr-2"}),"Add 3 follow-ups to Follow-Up Center"]})]})]})]});function U(he,Se,Te){A(C.map(Ie=>Ie.id===he?{...Ie,lessons:Ie.lessons.map(Ue=>Ue.id===Se?{...Ue,...Te}:Ue)}:Ie))}}function Eie(s,t,n){const r=[...s],[a]=r.splice(t,1);return r.splice(n,0,a),r}function _Kn(s){if(!s)return"";const t=new Date(s);return new Date(t.getTime()-t.getTimezoneOffset()*6e4).toISOString().slice(0,16)}function lg({label:s,children:t,className:n}){return e.jsxs("div",{className:n,children:[e.jsx(re,{className:"text-[12px] text-slate-600 mb-1 block",children:s}),t]})}function ijt({label:s,items:t,onChange:n}){return e.jsxs("div",{children:[e.jsx(re,{className:"text-[12px] text-slate-600 mb-1 block",children:s}),e.jsxs("div",{className:"space-y-2",children:[t.map((r,a)=>e.jsxs("div",{className:"flex gap-2",children:[e.jsx(be,{value:r.title,placeholder:"Title",onChange:i=>n(t.map((l,o)=>o===a?{...l,title:i.target.value}:l))}),e.jsx(be,{value:r.url,placeholder:"https://",onChange:i=>n(t.map((l,o)=>o===a?{...l,url:i.target.value}:l))}),e.jsx($,{variant:"ghost",size:"icon",className:"text-destructive",onClick:()=>n(t.filter((i,l)=>l!==a)),children:e.jsx(Un,{className:"h-4 w-4"})})]},a)),e.jsxs($,{size:"sm",variant:"ghost",onClick:()=>n([...t,{title:"",url:""}]),children:[e.jsx(nn,{className:"h-3.5 w-3.5 mr-1.5"}),"Add ",s.toLowerCase().slice(0,-1)]})]})]})}function wKn({m:s}){var t,n,r;return e.jsxs("div",{className:"grid lg:grid-cols-2 gap-4",children:[e.jsxs(we,{className:"p-5 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-violet-700 font-semibold mb-2",children:"Curriculum"}),(s.curriculum??[]).length===0?e.jsx("div",{className:"text-[13px] text-slate-500",children:"Nothing yet."}):(s.curriculum??[]).map(a=>e.jsxs("div",{className:"mb-3",children:[e.jsx("div",{className:"font-semibold text-[14px]",children:a.title}),e.jsx("ul",{className:"mt-1 space-y-1",children:a.lessons.map(i=>e.jsxs("li",{className:"text-[13px] text-slate-600",children:["• ",i.title,i.minutes?` (${i.minutes}m)`:""]},i.id))})]},a.id))]}),e.jsxs(we,{className:"p-5 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-violet-700 font-semibold mb-2",children:"Workbook outline"}),e.jsx("pre",{className:"text-[12.5px] whitespace-pre-wrap text-slate-700",children:((t=s.assets)==null?void 0:t.workbook)||"Nothing yet."})]}),e.jsxs(we,{className:"p-5 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-violet-700 font-semibold mb-2",children:"Registration copy"}),e.jsx("pre",{className:"text-[12.5px] whitespace-pre-wrap text-slate-700",children:((n=s.promotion)==null?void 0:n.registration_copy)||"Nothing yet."})]}),e.jsxs(we,{className:"p-5 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-violet-700 font-semibold mb-2",children:"Presenter run of show"}),e.jsx("pre",{className:"text-[12.5px] whitespace-pre-wrap font-mono text-slate-700",children:((r=s.delivery)==null?void 0:r.run_of_show)||"Nothing yet."})]})]})}const kE=V;function Ste(s,t={}){const{orderBy:n="created_at",ascending:r=!1,titleField:a="title",duplicateOverrides:i={},label:l="Record"}=t,{user:o}=ks(),c=ls(),d=[s,o==null?void 0:o.id],u=pt({queryKey:d,enabled:!!o,queryFn:async()=>{const{data:v,error:_}=await kE.from(s).select("*").order(n,{ascending:r,nullsFirst:!1});if(_)throw _;return v??[]}}),h=()=>{c.invalidateQueries({queryKey:[s]}),c.invalidateQueries({queryKey:["attract-followups"]}),c.invalidateQueries({queryKey:["attract-activities"]})},m=Nt({mutationFn:async v=>{const{data:_,error:j}=await kE.from(s).insert({...v,user_id:o.id}).select("*").single();if(j)throw j;return _},onSuccess:()=>{h(),ae.success(`${l} saved`)},onError:v=>ae.error(v.message)}),p=Nt({mutationFn:async({id:v,..._})=>{const{error:j}=await kE.from(s).update(_).eq("id",v);if(j)throw j},onSuccess:()=>{h(),ae.success("Updated")},onError:v=>ae.error(v.message)}),g=Nt({mutationFn:async v=>{const{id:_,created_at:j,updated_at:C,user_id:A,...M}=v,I={...M,...i,user_id:o.id};a&&I[a]&&(I[a]=`${I[a]} (copy)`);const{data:P,error:R}=await kE.from(s).insert(I).select("id").single();if(R)throw R;return P},onSuccess:()=>{h(),ae.success("Duplicated")},onError:v=>ae.error(v.message)}),x=Nt({mutationFn:async({id:v,archived:_})=>{const{error:j}=await kE.from(s).update({is_archived:_}).eq("id",v);if(j)throw j},onSuccess:(v,_)=>{h(),ae.success(_.archived?"Archived":"Restored")},onError:v=>ae.error(v.message)}),y=Nt({mutationFn:async v=>{const{error:_}=await kE.from(s).delete().eq("id",v);if(_)throw _},onSuccess:()=>{h(),ae.success("Deleted")},onError:v=>ae.error(v.message)});return{items:u.data??[],isLoading:u.isLoading,error:u.error,refetch:u.refetch,create:m,update:p,duplicate:g,archive:x,remove:y,userId:o==null?void 0:o.id}}function rMe(){const{user:s}=ks(),t=ls();return Nt({mutationFn:async({title:n,dueAt:r,notes:a,touchType:i="task",agentId:l})=>{const{error:o}=await kE.from("attract_follow_ups").insert({user_id:s.id,title:n,due_at:r??null,notes:a??null,touch_type:i,priority:"medium",agent_id:l??null});if(o)throw o},onSuccess:()=>{t.invalidateQueries({queryKey:["attract-followups"]}),t.invalidateQueries({queryKey:["attract-daily-plan"]}),ae.success("Added to Follow-Up Center & Today’s Plan")},onError:n=>ae.error(n.message)})}function Cte(){const{user:s}=ks(),t=ls();return Nt({mutationFn:async({title:n,description:r,pillar:a="produce",activityType:i="tool_action",agentId:l,metadata:o})=>{const{error:c}=await kE.rpc("award_attract_activity",{_user_id:s.id,_activity_type:i,_title:n,_description:r??null,_pillar:a,_agent_id:l??null,_metadata:o??{},_dedupe_minutes:5});if(c)throw c},onSuccess:()=>{t.invalidateQueries({queryKey:["attract-activities"]}),t.invalidateQueries({queryKey:["attract-score"]})},onError:n=>ae.error(n.message)})}const jKn=["annual","quarterly","monthly"],C9=[{key:"closings",label:"Closings",target:"closings_target",actual:"closings_actual",format:"number"},{key:"gci",label:"GCI",target:"gci_target",actual:"gci_actual",format:"currency"},{key:"volume",label:"Volume",target:"volume_target",actual:"volume_actual",format:"currency"},{key:"listings",label:"Listings",target:"listings_target",actual:"listings_actual",format:"number"},{key:"buyer_sides",label:"Buyer Sides",target:"buyer_sides_target",actual:"buyer_sides_actual",format:"number"},{key:"appointments",label:"Appointments",target:"appointments_target",actual:"appointments_actual",format:"number"}];function A9(s){return s.period_type==="quarterly"?`Q${s.quarter??1} ${s.year}`:s.period_type==="monthly"?`${new Date(2e3,(s.month??1)-1,1).toLocaleString("en-US",{month:"long"})} ${s.year}`:`${s.year}`}function NKn(s,t=new Date){let n,r;if(s.period_type==="monthly"){const l=(s.month??1)-1;n=new Date(s.year,l,1),r=new Date(s.year,l+1,1)}else if(s.period_type==="quarterly"){const l=(s.quarter??1)-1;n=new Date(s.year,l*3,1),r=new Date(s.year,l*3+3,1)}else n=new Date(s.year,0,1),r=new Date(s.year+1,0,1);const a=r.getTime()-n.getTime(),i=t.getTime()-n.getTime();return Math.max(0,Math.min(1,i/a))}function kKn(s,t){if(!s)return!1;const[n,r]=s.split(/[-/T]/).map(Number);return n!==t.year?!1:t.period_type==="monthly"?r===t.month:t.period_type==="quarterly"?Math.ceil(r/3)===t.quarter:!0}function SKn(){const s=Ste("attract_production_goals",{orderBy:"year",ascending:!1,titleField:"label",label:"Goal",duplicateOverrides:{closings_actual:0,gci_actual:0,volume_actual:0,listings_actual:0,buyer_sides_actual:0,appointments_actual:0,is_archived:!1}}),{transactions:t}=nKt(),n=rMe(),r=Cte(),a=k.useMemo(()=>{const i={};return s.items.forEach(l=>{i[l.id]={closings:t.filter(o=>kKn(o.closing_date,l)).length}}),i},[s.items,t]);return{...s,goals:s.items,autoProgress:a,quickTask:n,logActivity:r}}function CKn(s){const t=Number(s??0);return t?{monthly:t/12,weekly:t/52}:null}const AKn=Array.from({length:12},(s,t)=>({value:t+1,label:new Date(2e3,t,1).toLocaleString("en-US",{month:"long"})}));function aC(s,t){return Number.isFinite(s)?t==="currency"?s>=1e3?`$${Math.round(s).toLocaleString()}`:`$${s.toFixed(0)}`:Number.isInteger(s)?String(s):s.toFixed(1):"—"}function EKn({pct:s,size:t=92}){const n=(t-12)/2,r=2*Math.PI*n,a=Math.max(0,Math.min(1,s));return e.jsxs("svg",{width:t,height:t,className:"-rotate-90 flex-shrink-0",children:[e.jsx("circle",{cx:t/2,cy:t/2,r:n,stroke:"#ede9fe",strokeWidth:9,fill:"none"}),e.jsx("circle",{cx:t/2,cy:t/2,r:n,stroke:"#7c3aed",strokeWidth:9,fill:"none",strokeLinecap:"round",strokeDasharray:r,strokeDashoffset:r*(1-a)})]})}const ojt={period_type:"annual",year:new Date().getFullYear(),quarter:1,month:new Date().getMonth()+1,use_auto_progress:!0};function TKn(){const{goals:s,isLoading:t,error:n,refetch:r,create:a,update:i,duplicate:l,archive:o,remove:c,autoProgress:d,quickTask:u,logActivity:h}=SKn(),[m,p]=k.useState(!1),[g,x]=k.useState(null),[y,v]=k.useState(null),[_,j]=k.useState(null),C=k.useMemo(()=>s.filter(P=>m?P.is_archived:!P.is_archived),[s,m]),A=(P,R)=>{var B;const O=Number(P[R.actual]??0);return P.use_auto_progress&&R.key==="closings"?Math.max(O,((B=d[P.id])==null?void 0:B.closings)??0):O},M=async()=>{var R;if(!g)return;const P={label:((R=g.label)==null?void 0:R.trim())||null,period_type:g.period_type??"annual",year:Number(g.year)||new Date().getFullYear(),quarter:g.period_type==="quarterly"?Number(g.quarter)||1:null,month:g.period_type==="monthly"?Number(g.month)||1:null,closings_target:g.closings_target??null,gci_target:g.gci_target??null,volume_target:g.volume_target??null,listings_target:g.listings_target??null,buyer_sides_target:g.buyer_sides_target??null,appointments_target:g.appointments_target??null,use_auto_progress:g.use_auto_progress??!0,notes:g.notes??null};g.id?await i.mutateAsync({id:g.id,...P}):await a.mutateAsync(P),x(null)},I=async()=>{if(!y)return;const P={};C9.forEach(R=>{P[R.actual]=Number(y[R.actual]??0)}),await i.mutateAsync({id:y.id,...P}),await h.mutateAsync({title:`Updated production progress — ${A9(y)}`,pillar:"produce",activityType:"goal_progress"}),v(null)};return e.jsxs("div",{children:[e.jsxs(nr,{to:"/attract/produce",className:"inline-flex items-center gap-1.5 text-[12px] text-slate-500 hover:text-violet-700 mb-3",children:[e.jsx(Ia,{className:"h-3.5 w-3.5"})," Back to Produce"]}),e.jsx(Hm,{eyebrow:"Produce → Tool",title:"Production Goals",description:"Set the annual, quarterly, and monthly numbers you're playing for — then track pace, not just totals. Progress can be updated manually or pulled from the transactions you log.",actions:e.jsxs(e.Fragment,{children:[e.jsx($,{variant:"outline",className:"rounded-full",onClick:()=>p(P=>!P),children:m?"Show active":"Show archived"}),e.jsxs($,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>x({...ojt}),children:[e.jsx(nn,{className:"h-4 w-4 mr-1.5"})," New Goal"]})]})}),t&&e.jsx("div",{className:"grid gap-4 md:grid-cols-2",children:[0,1].map(P=>e.jsx(fn,{className:"h-56 rounded-2xl"},P))}),!t&&n&&e.jsxs(we,{className:"p-8 rounded-2xl text-center",children:[e.jsx(Ho,{className:"h-6 w-6 text-rose-500 mx-auto mb-2"}),e.jsx("div",{className:"font-semibold text-slate-900",children:"Couldn't load your goals"}),e.jsx("div",{className:"text-[13px] text-slate-600 mt-1",children:n.message}),e.jsxs($,{variant:"outline",className:"rounded-full mt-4",onClick:()=>r(),children:[e.jsx(jm,{className:"h-3.5 w-3.5 mr-1.5"})," Retry"]})]}),!t&&!n&&C.length===0&&e.jsxs(we,{className:"p-10 rounded-2xl text-center border-dashed",children:[e.jsx("div",{className:"h-12 w-12 rounded-2xl bg-violet-50 text-violet-600 grid place-items-center mx-auto mb-3",children:e.jsx(_h,{className:"h-6 w-6"})}),e.jsx("div",{className:"text-[16px] font-semibold text-slate-900",children:m?"No archived goals":"No production goals yet"}),e.jsx("p",{className:"text-[13.5px] text-slate-600 mt-1.5 max-w-md mx-auto",children:"Start with one annual goal. Attract will break it into monthly and weekly activity targets and show whether you're ahead or behind pace."}),!m&&e.jsxs($,{className:"rounded-full mt-4 bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>x({...ojt}),children:[e.jsx(nn,{className:"h-4 w-4 mr-1.5"})," Create your first goal"]})]}),e.jsx("div",{className:"grid gap-4 md:grid-cols-2",children:C.map(P=>{const R=NKn(P),O=C9.find(ee=>P[ee.target])??C9[0],B=Number(P[O.target]??0),U=A(P,O),G=B?U/B:0,H=B*R,Y=U>=H,se=CKn(B);return e.jsxs(we,{className:"p-5 rounded-2xl",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 flex-wrap",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"text-[16px] font-semibold text-slate-900",children:P.label||`${A9(P)} Goals`}),e.jsx(qe,{variant:"outline",className:"rounded-full capitalize",children:P.period_type}),e.jsx(qe,{variant:"outline",className:"rounded-full",children:A9(P)})]}),P.notes&&e.jsx("div",{className:"text-[12.5px] text-slate-600 mt-1 line-clamp-2",children:P.notes})]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx($,{size:"icon",variant:"ghost",className:"h-8 w-8",title:"Edit",onClick:()=>x(P),children:e.jsx(ui,{className:"h-3.5 w-3.5"})}),e.jsx($,{size:"icon",variant:"ghost",className:"h-8 w-8",title:"Duplicate",onClick:()=>l.mutate(P),children:e.jsx(Da,{className:"h-3.5 w-3.5"})}),e.jsx($,{size:"icon",variant:"ghost",className:"h-8 w-8",title:P.is_archived?"Restore":"Archive",onClick:()=>o.mutate({id:P.id,archived:!P.is_archived}),children:e.jsx(kf,{className:"h-3.5 w-3.5"})}),e.jsx($,{size:"icon",variant:"ghost",className:"h-8 w-8 text-rose-600",title:"Delete",onClick:()=>j(P),children:e.jsx(Un,{className:"h-3.5 w-3.5"})})]})]}),e.jsxs("div",{className:"flex items-center gap-4 mt-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(EKn,{pct:G}),e.jsx("div",{className:"absolute inset-0 grid place-items-center",children:e.jsxs("div",{className:"text-[15px] font-semibold tabular-nums text-slate-900",children:[Math.round(G*100),"%"]})})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-[12px] uppercase tracking-wider text-slate-500",children:O.label}),e.jsxs("div",{className:"text-[22px] font-semibold tabular-nums text-slate-900",children:[aC(U,O.format)," ",e.jsxs("span",{className:"text-slate-400 text-[15px]",children:["/ ",aC(B,O.format)]})]}),e.jsxs("div",{className:`text-[12.5px] mt-0.5 font-medium ${Y?"text-emerald-600":"text-amber-600"}`,children:[Y?"Ahead of pace":"Behind pace"," · pace target ",aC(H,O.format)," (",Math.round(R*100),"% of period elapsed)"]})]})]}),e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-2 mt-4",children:C9.filter(ee=>P[ee.target]).map(ee=>{const oe=Number(P[ee.target]),me=A(P,ee);return e.jsxs("div",{className:"rounded-xl bg-slate-50 px-3 py-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wider text-slate-500",children:ee.label}),e.jsxs("div",{className:"text-[13.5px] font-semibold tabular-nums text-slate-900",children:[aC(me,ee.format)," / ",aC(oe,ee.format)]}),e.jsx("div",{className:"h-1.5 rounded-full bg-slate-200 mt-1.5 overflow-hidden",children:e.jsx("div",{className:"h-full bg-violet-600",style:{width:`${Math.min(100,oe?me/oe*100:0)}%`}})})]},ee.key)})}),P.period_type==="annual"&&se&&e.jsxs("div",{className:"mt-3 rounded-xl border border-violet-100 bg-violet-50/60 px-3.5 py-2.5 text-[12.5px] text-violet-900",children:["Break it down: ",e.jsx("strong",{children:aC(se.monthly,O.format)})," per month ·"," ",e.jsx("strong",{children:aC(se.weekly,O.format)})," per week of ",O.label.toLowerCase(),"."]}),e.jsxs("div",{className:"flex gap-2 mt-4 flex-wrap",children:[e.jsx($,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>v({...P}),children:"Update progress"}),e.jsxs($,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>u.mutate({title:`Goal push: ${O.label} — ${aC(se?se.weekly:B,O.format)} this week`,dueAt:new Date().toISOString(),notes:`From ${A9(P)} production goal`,touchType:"goal"}),children:[e.jsx(op,{className:"h-3.5 w-3.5 mr-1.5"})," Add to Today's Plan"]}),e.jsxs($,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>h.mutate({title:`Win logged toward ${A9(P)} goals`,pillar:"produce",activityType:"goal_win"}),children:[e.jsx(ql,{className:"h-3.5 w-3.5 mr-1.5"})," Log a win"]})]})]},P.id)})}),e.jsx(zs,{open:!!g,onOpenChange:P=>!P&&x(null),children:e.jsxs(Rs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(Vs,{children:[e.jsx($s,{children:g!=null&&g.id?"Edit goal":"New production goal"}),e.jsx(Cr,{children:"Only fill in the targets you actually track. Blank targets are hidden."})]}),g&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid sm:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Label (optional)"}),e.jsx(be,{value:g.label??"",onChange:P=>x({...g,label:P.target.value}),placeholder:"e.g. 2026 Big Rock"})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Period"}),e.jsxs(bs,{value:g.period_type,onValueChange:P=>x({...g,period_type:P}),children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsx(vs,{children:jKn.map(P=>e.jsx(We,{value:P,className:"capitalize",children:P},P))})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Year"}),e.jsx(be,{type:"number",value:g.year??"",onChange:P=>x({...g,year:Number(P.target.value)})})]}),g.period_type==="quarterly"&&e.jsxs("div",{children:[e.jsx(re,{children:"Quarter"}),e.jsxs(bs,{value:String(g.quarter??1),onValueChange:P=>x({...g,quarter:Number(P)}),children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsx(vs,{children:[1,2,3,4].map(P=>e.jsxs(We,{value:String(P),children:["Q",P]},P))})]})]}),g.period_type==="monthly"&&e.jsxs("div",{children:[e.jsx(re,{children:"Month"}),e.jsxs(bs,{value:String(g.month??1),onValueChange:P=>x({...g,month:Number(P)}),children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsx(vs,{children:AKn.map(P=>e.jsx(We,{value:String(P.value),children:P.label},P.value))})]})]})]}),e.jsx("div",{className:"grid sm:grid-cols-3 gap-3",children:C9.map(P=>e.jsxs("div",{children:[e.jsxs(re,{children:[P.label," target"]}),e.jsx(be,{type:"number",value:g[P.target]??"",onChange:R=>x({...g,[P.target]:R.target.value===""?null:Number(R.target.value)})})]},P.key))}),e.jsxs("div",{className:"flex items-center justify-between rounded-xl border border-slate-200 px-4 py-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[13.5px] font-medium text-slate-900",children:"Pull closings from logged transactions"}),e.jsx("div",{className:"text-[12px] text-slate-600",children:"Uses the transactions in your Transaction-to-Relationship Tracker for this period."})]}),e.jsx(On,{checked:g.use_auto_progress??!0,onCheckedChange:P=>x({...g,use_auto_progress:P})})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Notes"}),e.jsx(Ls,{value:g.notes??"",onChange:P=>x({...g,notes:P.target.value}),rows:3})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"ghost",onClick:()=>x(null),children:"Cancel"}),e.jsx($,{className:"bg-gradient-to-r from-violet-600 to-indigo-600",onClick:M,disabled:a.isPending||i.isPending,children:"Save goal"})]})]})}),e.jsx(zs,{open:!!y,onOpenChange:P=>!P&&v(null),children:e.jsxs(Rs,{className:"max-w-lg",children:[e.jsxs(Vs,{children:[e.jsx($s,{children:"Update progress"}),e.jsxs(Cr,{children:[y?A9(y):""," — enter your actuals to date."]})]}),y&&e.jsx("div",{className:"grid sm:grid-cols-2 gap-3",children:C9.filter(P=>y[P.target]).map(P=>e.jsxs("div",{children:[e.jsx(re,{children:P.label}),e.jsx(be,{type:"number",value:y[P.actual]??0,onChange:R=>v({...y,[P.actual]:Number(R.target.value)})})]},P.key))}),e.jsxs(kr,{children:[e.jsx($,{variant:"ghost",onClick:()=>v(null),children:"Cancel"}),e.jsx($,{className:"bg-gradient-to-r from-violet-600 to-indigo-600",onClick:I,children:"Save progress"})]})]})}),e.jsx(zs,{open:!!_,onOpenChange:P=>!P&&j(null),children:e.jsxs(Rs,{className:"max-w-md",children:[e.jsxs(Vs,{children:[e.jsx($s,{children:"Delete this goal?"}),e.jsx(Cr,{children:"This can't be undone. Archive it instead if you want to keep the history."})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"ghost",onClick:()=>j(null),children:"Cancel"}),e.jsx($,{variant:"destructive",onClick:()=>{c.mutate(_.id),j(null)},children:"Delete"})]})]})})]})}const J8e=[{value:"award",label:"Award"},{value:"ranking",label:"Ranking"},{value:"certification",label:"Certification"},{value:"milestone",label:"Milestone"},{value:"media",label:"Media Mention"},{value:"production",label:"Production Recognition"}];function MKn(){const s=Ste("attract_awards",{orderBy:"awarded_on",ascending:!1,label:"Award",duplicateOverrides:{is_archived:!1}}),t=Cte();return{...s,awards:s.items,logActivity:t}}const ljt={category:"award",status:"active",is_public:!0};function cjt(s){if(!s)return"No date";const[t,n,r]=s.split(/[-/T]/).map(Number);return new Date(t,n-1,r).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"})}function PKn(){const{awards:s,isLoading:t,error:n,refetch:r,create:a,update:i,duplicate:l,archive:o,remove:c,logActivity:d}=MKn(),[u,h]=k.useState(!1),[m,p]=k.useState("all"),[g,x]=k.useState(""),[y,v]=k.useState(null),[_,j]=k.useState(null),C=k.useMemo(()=>s.filter(I=>{if(u!==!!I.is_archived||m!=="all"&&I.category!==m)return!1;const P=g.toLowerCase().trim();return!P||`${I.title} ${I.issuer??""} ${I.description??""}`.toLowerCase().includes(P)}),[s,u,m,g]),A=async()=>{var P;if(!((P=y==null?void 0:y.title)!=null&&P.trim())){ae.error("Add a title");return}const I={title:y.title.trim(),issuer:y.issuer||null,awarded_on:y.awarded_on||null,category:y.category??"award",description:y.description||null,proof_url:y.proof_url||null,production_period:y.production_period||null,is_public:y.is_public??!0};y.id?await i.mutateAsync({id:y.id,...I}):(await a.mutateAsync(I),await d.mutateAsync({title:`Added recognition: ${I.title}`,pillar:"produce",activityType:"award_added"})),v(null)},M=I=>{var R;const P=[I.title,I.issuer&&`— ${I.issuer}`,I.awarded_on&&`(${cjt(I.awarded_on)})`].filter(Boolean).join(" ");(R=navigator.clipboard)==null||R.writeText(P),ae.success("Proof point copied — paste it into Content Studio")};return e.jsxs("div",{children:[e.jsxs(nr,{to:"/attract/produce",className:"inline-flex items-center gap-1.5 text-[12px] text-slate-500 hover:text-violet-700 mb-3",children:[e.jsx(Ia,{className:"h-3.5 w-3.5"})," Back to Produce"]}),e.jsx(Hm,{eyebrow:"Produce → Tool",title:"Awards & Recognition",description:"Your credibility file. Keep every award, ranking, and certification in one place so proof points are ready when you write content or pitch a speaking slot.",actions:e.jsxs(e.Fragment,{children:[e.jsx($,{variant:"outline",className:"rounded-full",onClick:()=>h(I=>!I),children:u?"Show active":"Show archived"}),e.jsxs($,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>v({...ljt}),children:[e.jsx(nn,{className:"h-4 w-4 mr-1.5"})," Add Recognition"]})]})}),e.jsxs("div",{className:"flex gap-2 flex-wrap mb-4",children:[e.jsx(be,{value:g,onChange:I=>x(I.target.value),placeholder:"Search recognitions",className:"max-w-xs rounded-full"}),e.jsxs(bs,{value:m,onValueChange:p,children:[e.jsx(ys,{className:"w-[190px] rounded-full",children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"all",children:"All categories"}),J8e.map(I=>e.jsx(We,{value:I.value,children:I.label},I.value))]})]})]}),t&&e.jsx("div",{className:"grid gap-3 md:grid-cols-2",children:[0,1,2,3].map(I=>e.jsx(fn,{className:"h-36 rounded-2xl"},I))}),!t&&n&&e.jsxs(we,{className:"p-8 rounded-2xl text-center",children:[e.jsx(Ho,{className:"h-6 w-6 text-rose-500 mx-auto mb-2"}),e.jsx("div",{className:"font-semibold text-slate-900",children:"Couldn't load recognitions"}),e.jsx("div",{className:"text-[13px] text-slate-600 mt-1",children:n.message}),e.jsxs($,{variant:"outline",className:"rounded-full mt-4",onClick:()=>r(),children:[e.jsx(jm,{className:"h-3.5 w-3.5 mr-1.5"})," Retry"]})]}),!t&&!n&&C.length===0&&e.jsxs(we,{className:"p-10 rounded-2xl text-center border-dashed",children:[e.jsx("div",{className:"h-12 w-12 rounded-2xl bg-violet-50 text-violet-600 grid place-items-center mx-auto mb-3",children:e.jsx(oh,{className:"h-6 w-6"})}),e.jsx("div",{className:"text-[16px] font-semibold text-slate-900",children:u?"Nothing archived":"No recognitions logged yet"}),e.jsx("p",{className:"text-[13.5px] text-slate-600 mt-1.5 max-w-md mx-auto",children:"Add awards, production rankings, and designations. Copy any one of them as a proof point when writing authority content."}),!u&&e.jsxs($,{className:"rounded-full mt-4 bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>v({...ljt}),children:[e.jsx(nn,{className:"h-4 w-4 mr-1.5"})," Add your first"]})]}),e.jsx("div",{className:"grid gap-3 md:grid-cols-2",children:C.map(I=>{var P;return e.jsxs(we,{className:"p-5 rounded-2xl",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"text-[15.5px] font-semibold text-slate-900",children:I.title}),e.jsx(qe,{variant:"outline",className:"rounded-full capitalize",children:((P=J8e.find(R=>R.value===I.category))==null?void 0:P.label)??I.category})]}),e.jsx("div",{className:"text-[12.5px] text-slate-500 mt-1",children:[I.issuer,cjt(I.awarded_on),I.production_period].filter(Boolean).join(" · ")}),I.description&&e.jsx("p",{className:"text-[13px] text-slate-600 mt-2 line-clamp-3",children:I.description})]}),e.jsxs("div",{className:"flex gap-1 flex-shrink-0",children:[e.jsx($,{size:"icon",variant:"ghost",className:"h-8 w-8",title:"Edit",onClick:()=>v(I),children:e.jsx(ui,{className:"h-3.5 w-3.5"})}),e.jsx($,{size:"icon",variant:"ghost",className:"h-8 w-8",title:"Duplicate",onClick:()=>l.mutate(I),children:e.jsx(Da,{className:"h-3.5 w-3.5"})}),e.jsx($,{size:"icon",variant:"ghost",className:"h-8 w-8",title:I.is_archived?"Restore":"Archive",onClick:()=>o.mutate({id:I.id,archived:!I.is_archived}),children:e.jsx(kf,{className:"h-3.5 w-3.5"})}),e.jsx($,{size:"icon",variant:"ghost",className:"h-8 w-8 text-rose-600",title:"Delete",onClick:()=>j(I),children:e.jsx(Un,{className:"h-3.5 w-3.5"})})]})]}),e.jsxs("div",{className:"flex gap-2 mt-4 flex-wrap",children:[e.jsxs($,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>M(I),children:[e.jsx(pd,{className:"h-3.5 w-3.5 mr-1.5"})," Copy proof point"]}),e.jsx($,{size:"sm",variant:"outline",className:"rounded-full",asChild:!0,children:e.jsxs(nr,{to:"/attract/influence/content-studio",children:[e.jsx(kn,{className:"h-3.5 w-3.5 mr-1.5"})," Write about it"]})}),I.proof_url&&e.jsx($,{size:"sm",variant:"ghost",className:"rounded-full",asChild:!0,children:e.jsxs("a",{href:I.proof_url,target:"_blank",rel:"noreferrer",children:["Proof ",e.jsx(Ir,{className:"h-3 w-3 ml-1.5"})]})})]})]},I.id)})}),e.jsx(zs,{open:!!y,onOpenChange:I=>!I&&v(null),children:e.jsxs(Rs,{className:"max-w-xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(Vs,{children:[e.jsx($s,{children:y!=null&&y.id?"Edit recognition":"Add recognition"}),e.jsx(Cr,{children:"Keep it factual — this feeds the proof points you use publicly."})]}),y&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Title *"}),e.jsx(be,{value:y.title??"",onChange:I=>v({...y,title:I.target.value}),placeholder:"e.g. Top 1% Producer"})]}),e.jsxs("div",{className:"grid sm:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Issued by"}),e.jsx(be,{value:y.issuer??"",onChange:I=>v({...y,issuer:I.target.value}),placeholder:"Board, brokerage, publication"})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Category"}),e.jsxs(bs,{value:y.category??"award",onValueChange:I=>v({...y,category:I}),children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsx(vs,{children:J8e.map(I=>e.jsx(We,{value:I.value,children:I.label},I.value))})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Date awarded"}),e.jsx(be,{type:"date",value:y.awarded_on??"",onChange:I=>v({...y,awarded_on:I.target.value})})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Production period"}),e.jsx(be,{value:y.production_period??"",onChange:I=>v({...y,production_period:I.target.value}),placeholder:"e.g. 2025"})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Proof link"}),e.jsx(be,{value:y.proof_url??"",onChange:I=>v({...y,proof_url:I.target.value}),placeholder:"https://"})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Description"}),e.jsx(Ls,{rows:3,value:y.description??"",onChange:I=>v({...y,description:I.target.value})})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"ghost",onClick:()=>v(null),children:"Cancel"}),e.jsx($,{className:"bg-gradient-to-r from-violet-600 to-indigo-600",onClick:A,disabled:a.isPending||i.isPending,children:"Save"})]})]})}),e.jsx(zs,{open:!!_,onOpenChange:I=>!I&&j(null),children:e.jsxs(Rs,{className:"max-w-md",children:[e.jsxs(Vs,{children:[e.jsx($s,{children:"Delete this recognition?"}),e.jsx(Cr,{children:"This can't be undone."})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"ghost",onClick:()=>j(null),children:"Cancel"}),e.jsx($,{variant:"destructive",onClick:()=>{c.mutate(_.id),j(null)},children:"Delete"})]})]})})]})}const IKn=V,djt=[{value:"pending",label:"Permission pending"},{value:"granted",label:"Permission granted"},{value:"anonymous_only",label:"Anonymous use only"},{value:"declined",label:"Permission declined"}],LKn=["buyer","seller","both","investor","referral_partner","agent","other"];function Tie(s){return s.status==="approved"&&(s.permission_status==="granted"||s.permission_status==="anonymous_only")}function RKn(){const s=Ste("attract_testimonials",{orderBy:"created_at",ascending:!1,titleField:"client_name",label:"Testimonial",duplicateOverrides:{use_count:0,last_used_at:null,usage_log:[],status:"draft",is_archived:!1}}),t=Cte(),n=ls(),r=Nt({mutationFn:async({item:a,kind:i,note:l})=>{const o=[...a.usage_log??[],{at:new Date().toISOString(),kind:i,note:l}].slice(-25),{error:c}=await IKn.from("attract_testimonials").update({use_count:(a.use_count??0)+1,last_used_at:new Date().toISOString(),usage_log:o}).eq("id",a.id);if(c)throw c},onSuccess:()=>{n.invalidateQueries({queryKey:["attract_testimonials"]}),ae.success("Usage recorded")},onError:a=>ae.error(a.message)});return{...s,testimonials:s.items,recordUse:r,logActivity:t}}const ujt={permission_status:"pending",status:"draft",rating:5,tags:[]};function DKn(){const{testimonials:s,isLoading:t,error:n,refetch:r,create:a,update:i,duplicate:l,archive:o,remove:c,recordUse:d,logActivity:u}=RKn(),[h,m]=k.useState(!1),[p,g]=k.useState("all"),[x,y]=k.useState(""),[v,_]=k.useState(null),[j,C]=k.useState(null),A=k.useMemo(()=>s.filter(R=>{if(h!==!!R.is_archived||p==="usable"&&!Tie(R)||p==="pending"&&R.permission_status!=="pending")return!1;const O=x.toLowerCase().trim();return!O||`${R.client_name} ${R.quote} ${(R.tags??[]).join(" ")}`.toLowerCase().includes(O)}),[s,h,p,x]),M=s.filter(R=>!R.is_archived&&Tie(R)).length,I=async()=>{var O,B;if(!((O=v==null?void 0:v.client_name)!=null&&O.trim())||!((B=v==null?void 0:v.quote)!=null&&B.trim())){ae.error("Client name and quote are required");return}const R={client_name:v.client_name.trim(),quote:v.quote.trim(),relationship_type:v.relationship_type||null,transaction_type:v.transaction_type||null,rating:v.rating??null,received_on:v.received_on||null,source_url:v.source_url||null,permission_status:v.permission_status??"pending",market:v.market||null,status:v.status??"draft",tags:v.tags??[]};v.id?await i.mutateAsync({id:v.id,...R}):(await a.mutateAsync(R),await u.mutateAsync({title:`Captured a testimonial from ${R.client_name}`,pillar:"produce",activityType:"testimonial_added"})),_(null)},P=(R,O)=>{var B;if(!Tie(R)){ae.error("Mark it approved with permission before using it publicly");return}(B=navigator.clipboard)==null||B.writeText(`"${R.quote}" — ${R.permission_status==="anonymous_only"?"Client":R.client_name}`),d.mutate({item:R,kind:O})};return e.jsxs("div",{children:[e.jsxs(nr,{to:"/attract/produce",className:"inline-flex items-center gap-1.5 text-[12px] text-slate-500 hover:text-violet-700 mb-3",children:[e.jsx(Ia,{className:"h-3.5 w-3.5"})," Back to Produce"]}),e.jsx(Hm,{eyebrow:"Produce → Tool",title:"Client Testimonials",description:"Your social proof library. Capture the exact words clients use, track who gave permission, and see which quotes you've already used so nothing gets overexposed.",actions:e.jsxs(e.Fragment,{children:[e.jsx($,{variant:"outline",className:"rounded-full",onClick:()=>m(R=>!R),children:h?"Show active":"Show archived"}),e.jsxs($,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>_({...ujt}),children:[e.jsx(nn,{className:"h-4 w-4 mr-1.5"})," Add Testimonial"]})]})}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-3 mb-4",children:[e.jsxs(we,{className:"p-4 rounded-2xl",children:[e.jsx("div",{className:"text-[22px] font-semibold tabular-nums text-slate-900",children:s.filter(R=>!R.is_archived).length}),e.jsx("div",{className:"text-[12px] text-slate-500",children:"In library"})]}),e.jsxs(we,{className:"p-4 rounded-2xl",children:[e.jsx("div",{className:"text-[22px] font-semibold tabular-nums text-emerald-600",children:M}),e.jsx("div",{className:"text-[12px] text-slate-500",children:"Cleared for use"})]}),e.jsxs(we,{className:"p-4 rounded-2xl",children:[e.jsx("div",{className:"text-[22px] font-semibold tabular-nums text-amber-600",children:s.filter(R=>!R.is_archived&&R.permission_status==="pending").length}),e.jsx("div",{className:"text-[12px] text-slate-500",children:"Permission pending"})]})]}),e.jsxs("div",{className:"flex gap-2 flex-wrap mb-4",children:[e.jsx(be,{value:x,onChange:R=>y(R.target.value),placeholder:"Search quotes, clients, tags",className:"max-w-xs rounded-full"}),e.jsxs(bs,{value:p,onValueChange:R=>g(R),children:[e.jsx(ys,{className:"w-[200px] rounded-full",children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"all",children:"All testimonials"}),e.jsx(We,{value:"usable",children:"Cleared for use"}),e.jsx(We,{value:"pending",children:"Permission pending"})]})]})]}),t&&e.jsx("div",{className:"grid gap-3 md:grid-cols-2",children:[0,1,2,3].map(R=>e.jsx(fn,{className:"h-40 rounded-2xl"},R))}),!t&&n&&e.jsxs(we,{className:"p-8 rounded-2xl text-center",children:[e.jsx(Ho,{className:"h-6 w-6 text-rose-500 mx-auto mb-2"}),e.jsx("div",{className:"font-semibold text-slate-900",children:"Couldn't load testimonials"}),e.jsx("div",{className:"text-[13px] text-slate-600 mt-1",children:n.message}),e.jsxs($,{variant:"outline",className:"rounded-full mt-4",onClick:()=>r(),children:[e.jsx(jm,{className:"h-3.5 w-3.5 mr-1.5"})," Retry"]})]}),!t&&!n&&A.length===0&&e.jsxs(we,{className:"p-10 rounded-2xl text-center border-dashed",children:[e.jsx("div",{className:"h-12 w-12 rounded-2xl bg-violet-50 text-violet-600 grid place-items-center mx-auto mb-3",children:e.jsx(ik,{className:"h-6 w-6"})}),e.jsx("div",{className:"text-[16px] font-semibold text-slate-900",children:"No testimonials match"}),e.jsx("p",{className:"text-[13.5px] text-slate-600 mt-1.5 max-w-md mx-auto",children:"Paste in the reviews and thank-you notes you already have. Mark permission so you always know what's safe to publish."}),!h&&e.jsxs($,{className:"rounded-full mt-4 bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>_({...ujt}),children:[e.jsx(nn,{className:"h-4 w-4 mr-1.5"})," Add one"]})]}),e.jsx("div",{className:"grid gap-3 md:grid-cols-2",children:A.map(R=>{var O;return e.jsxs(we,{className:"p-5 rounded-2xl flex flex-col",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"text-[15px] font-semibold text-slate-900",children:R.client_name}),R.relationship_type&&e.jsx(qe,{variant:"outline",className:"rounded-full capitalize",children:R.relationship_type.replace("_"," ")}),e.jsx(qe,{variant:"outline",className:`rounded-full ${Tie(R)?"bg-emerald-50 text-emerald-700 border-emerald-200":"bg-amber-50 text-amber-700 border-amber-200"}`,children:((O=djt.find(B=>B.value===R.permission_status))==null?void 0:O.label)??R.permission_status})]}),!!R.rating&&e.jsx("div",{className:"flex gap-0.5 mt-1.5",children:Array.from({length:5}).map((B,U)=>e.jsx(ri,{className:`h-3.5 w-3.5 ${U<(R.rating??0)?"text-amber-500 fill-amber-500":"text-slate-200"}`},U))})]}),e.jsxs("div",{className:"flex gap-1 flex-shrink-0",children:[e.jsx($,{size:"icon",variant:"ghost",className:"h-8 w-8",title:"Edit",onClick:()=>_(R),children:e.jsx(ui,{className:"h-3.5 w-3.5"})}),e.jsx($,{size:"icon",variant:"ghost",className:"h-8 w-8",title:"Duplicate",onClick:()=>l.mutate(R),children:e.jsx(Da,{className:"h-3.5 w-3.5"})}),e.jsx($,{size:"icon",variant:"ghost",className:"h-8 w-8",title:R.is_archived?"Restore":"Archive",onClick:()=>o.mutate({id:R.id,archived:!R.is_archived}),children:e.jsx(kf,{className:"h-3.5 w-3.5"})}),e.jsx($,{size:"icon",variant:"ghost",className:"h-8 w-8 text-rose-600",title:"Delete",onClick:()=>C(R),children:e.jsx(Un,{className:"h-3.5 w-3.5"})})]})]}),e.jsxs("blockquote",{className:"mt-3 text-[13.5px] text-slate-700 border-l-2 border-violet-200 pl-3 italic",children:['"',R.quote,'"']}),e.jsxs("div",{className:"text-[11.5px] text-slate-500 mt-3",children:["Used ",R.use_count??0," ",R.use_count===1?"time":"times",R.last_used_at?` · last ${new Date(R.last_used_at).toLocaleDateString("en-US")}`:"",R.status==="approved"?"":" · draft"]}),e.jsxs("div",{className:"flex gap-2 mt-3 flex-wrap",children:[e.jsxs($,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>P(R,"copied"),children:[e.jsx(Da,{className:"h-3.5 w-3.5 mr-1.5"})," Copy & log use"]}),e.jsx($,{size:"sm",variant:"outline",className:"rounded-full",asChild:!0,children:e.jsxs(nr,{to:"/attract/influence/content-studio",children:[e.jsx(kn,{className:"h-3.5 w-3.5 mr-1.5"})," Draft social proof"]})}),R.status!=="approved"&&e.jsxs($,{size:"sm",variant:"ghost",className:"rounded-full text-emerald-700",onClick:()=>i.mutate({id:R.id,status:"approved"}),children:[e.jsx(b0,{className:"h-3.5 w-3.5 mr-1.5"})," Mark approved"]})]})]},R.id)})}),e.jsx(zs,{open:!!v,onOpenChange:R=>!R&&_(null),children:e.jsxs(Rs,{className:"max-w-xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(Vs,{children:[e.jsx($s,{children:v!=null&&v.id?"Edit testimonial":"Add testimonial"}),e.jsx(Cr,{children:"Use the client's own words. Only publish quotes where permission is granted."})]}),v&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"grid sm:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Client name *"}),e.jsx(be,{value:v.client_name??"",onChange:R=>_({...v,client_name:R.target.value})})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Relationship"}),e.jsxs(bs,{value:v.relationship_type??"",onValueChange:R=>_({...v,relationship_type:R}),children:[e.jsx(ys,{children:e.jsx(_s,{placeholder:"Select"})}),e.jsx(vs,{children:LKn.map(R=>e.jsx(We,{value:R,className:"capitalize",children:R.replace("_"," ")},R))})]})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Quote *"}),e.jsx(Ls,{rows:4,value:v.quote??"",onChange:R=>_({...v,quote:R.target.value})})]}),e.jsxs("div",{className:"grid sm:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Rating"}),e.jsxs(bs,{value:String(v.rating??5),onValueChange:R=>_({...v,rating:Number(R)}),children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsx(vs,{children:[5,4,3,2,1].map(R=>e.jsxs(We,{value:String(R),children:[R," star",R>1?"s":""]},R))})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Received on"}),e.jsx(be,{type:"date",value:v.received_on??"",onChange:R=>_({...v,received_on:R.target.value})})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Permission"}),e.jsxs(bs,{value:v.permission_status??"pending",onValueChange:R=>_({...v,permission_status:R}),children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsx(vs,{children:djt.map(R=>e.jsx(We,{value:R.value,children:R.label},R.value))})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Status"}),e.jsxs(bs,{value:v.status??"draft",onValueChange:R=>_({...v,status:R}),children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"draft",children:"Draft"}),e.jsx(We,{value:"approved",children:"Approved"})]})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Market / area"}),e.jsx(be,{value:v.market??"",onChange:R=>_({...v,market:R.target.value})})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Source link"}),e.jsx(be,{value:v.source_url??"",onChange:R=>_({...v,source_url:R.target.value}),placeholder:"https://"})]})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"ghost",onClick:()=>_(null),children:"Cancel"}),e.jsx($,{className:"bg-gradient-to-r from-violet-600 to-indigo-600",onClick:I,disabled:a.isPending||i.isPending,children:"Save"})]})]})}),e.jsx(zs,{open:!!j,onOpenChange:R=>!R&&C(null),children:e.jsxs(Rs,{className:"max-w-md",children:[e.jsxs(Vs,{children:[e.jsx($s,{children:"Delete this testimonial?"}),e.jsx(Cr,{children:"This can't be undone."})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"ghost",onClick:()=>C(null),children:"Cancel"}),e.jsx($,{variant:"destructive",onClick:()=>{c.mutate(j.id),C(null)},children:"Delete"})]})]})})]})}const hjt=[{value:"market_update",label:"Market Update"},{value:"local_video",label:"Local Video"},{value:"newsletter",label:"Newsletter"},{value:"stats_post",label:"Stats Post"},{value:"neighborhood",label:"Neighborhood Content"},{value:"speaking",label:"Speaking Opportunity"}],mjt=["idea","planned","drafted","scheduled","published","skipped"],OKn=["weekly","biweekly","monthly","quarterly","one_off"];function lKt(){const s=Ste("attract_market_presence",{orderBy:"planned_for",ascending:!0,label:"Commitment",duplicateOverrides:{status:"idea",published_url:null,results_notes:null,is_archived:!1}}),t=rMe(),n=Cte();return{...s,commitments:s.items,quickTask:t,logActivity:n}}const fjt={content_type:"market_update",cadence:"monthly",status:"planned"};function FKn(s){if(!s)return"Unscheduled";const[t,n,r]=s.split(/[-/T]/).map(Number);return new Date(t,n-1,r).toLocaleDateString("en-US",{weekday:"short",month:"short",day:"numeric"})}const zKn={idea:"bg-slate-100 text-slate-600 border-slate-200",planned:"bg-blue-50 text-blue-700 border-blue-200",drafted:"bg-violet-50 text-violet-700 border-violet-200",scheduled:"bg-amber-50 text-amber-700 border-amber-200",published:"bg-emerald-50 text-emerald-700 border-emerald-200",skipped:"bg-rose-50 text-rose-700 border-rose-200"};function BKn(){const{commitments:s,isLoading:t,error:n,refetch:r,create:a,update:i,duplicate:l,archive:o,remove:c,quickTask:d,logActivity:u}=lKt(),[h,m]=k.useState(!1),[p,g]=k.useState("all"),[x,y]=k.useState(null),[v,_]=k.useState(null),j=k.useMemo(()=>s.filter(P=>h!==!!P.is_archived?!1:p==="all"||P.status===p),[s,h,p]),C=s.filter(P=>{if(P.status!=="published"||!P.planned_for)return!1;const[R,O,B]=P.planned_for.split(/[-/T]/).map(Number);return(Date.now()-new Date(R,O-1,B).getTime())/864e5<=30}).length,A=s.filter(P=>{if(P.is_archived||!P.planned_for||["published","skipped"].includes(P.status))return!1;const[R,O,B]=P.planned_for.split(/[-/T]/).map(Number);return new Date(R,O-1,B){var R;if(!((R=x==null?void 0:x.title)!=null&&R.trim())){ae.error("Add a title");return}const P={title:x.title.trim(),content_type:x.content_type??"market_update",cadence:x.cadence??"monthly",planned_for:x.planned_for||null,status:x.status??"planned",channel:x.channel||null,audience:x.audience||null,campaign:x.campaign||null,notes:x.notes||null,published_url:x.published_url||null,results_notes:x.results_notes||null};x.id?await i.mutateAsync({id:x.id,...P}):await a.mutateAsync(P),y(null)},I=async P=>{await i.mutateAsync({id:P.id,status:"published"}),await u.mutateAsync({title:`Published market presence: ${P.title}`,pillar:"produce",activityType:"market_presence_published"})};return e.jsxs("div",{children:[e.jsxs(nr,{to:"/attract/produce",className:"inline-flex items-center gap-1.5 text-[12px] text-slate-500 hover:text-violet-700 mb-3",children:[e.jsx(Ia,{className:"h-3.5 w-3.5"})," Back to Produce"]}),e.jsx(Hm,{eyebrow:"Produce → Tool",title:"Market Presence",description:"Consistency beats intensity. Commit to a cadence of market updates and local content, then track whether you actually shipped it.",actions:e.jsxs(e.Fragment,{children:[e.jsx($,{variant:"outline",className:"rounded-full",onClick:()=>m(P=>!P),children:h?"Show active":"Show archived"}),e.jsxs($,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>y({...fjt}),children:[e.jsx(nn,{className:"h-4 w-4 mr-1.5"})," New Commitment"]})]})}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-3 mb-4",children:[e.jsxs(we,{className:"p-4 rounded-2xl",children:[e.jsx("div",{className:"text-[22px] font-semibold tabular-nums text-slate-900",children:s.filter(P=>!P.is_archived).length}),e.jsx("div",{className:"text-[12px] text-slate-500",children:"Active commitments"})]}),e.jsxs(we,{className:"p-4 rounded-2xl",children:[e.jsx("div",{className:"text-[22px] font-semibold tabular-nums text-emerald-600",children:C}),e.jsx("div",{className:"text-[12px] text-slate-500",children:"Published last 30 days"})]}),e.jsxs(we,{className:"p-4 rounded-2xl",children:[e.jsx("div",{className:"text-[22px] font-semibold tabular-nums text-amber-600",children:A.length}),e.jsx("div",{className:"text-[12px] text-slate-500",children:"Past due"})]})]}),e.jsx("div",{className:"flex gap-2 flex-wrap mb-4",children:e.jsxs(bs,{value:p,onValueChange:g,children:[e.jsx(ys,{className:"w-[190px] rounded-full",children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"all",children:"All statuses"}),mjt.map(P=>e.jsx(We,{value:P,className:"capitalize",children:P},P))]})]})}),t&&e.jsx("div",{className:"space-y-2",children:[0,1,2].map(P=>e.jsx(fn,{className:"h-24 rounded-2xl"},P))}),!t&&n&&e.jsxs(we,{className:"p-8 rounded-2xl text-center",children:[e.jsx(Ho,{className:"h-6 w-6 text-rose-500 mx-auto mb-2"}),e.jsx("div",{className:"font-semibold text-slate-900",children:"Couldn't load commitments"}),e.jsx("div",{className:"text-[13px] text-slate-600 mt-1",children:n.message}),e.jsxs($,{variant:"outline",className:"rounded-full mt-4",onClick:()=>r(),children:[e.jsx(jm,{className:"h-3.5 w-3.5 mr-1.5"})," Retry"]})]}),!t&&!n&&j.length===0&&e.jsxs(we,{className:"p-10 rounded-2xl text-center border-dashed",children:[e.jsx("div",{className:"h-12 w-12 rounded-2xl bg-violet-50 text-violet-600 grid place-items-center mx-auto mb-3",children:e.jsx(Cy,{className:"h-6 w-6"})}),e.jsx("div",{className:"text-[16px] font-semibold text-slate-900",children:"No commitments yet"}),e.jsx("p",{className:"text-[13.5px] text-slate-600 mt-1.5 max-w-md mx-auto",children:"Start with one: a monthly market update. Set the date, ship it, mark it published — that rhythm is what agents notice."}),!h&&e.jsxs($,{className:"rounded-full mt-4 bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>y({...fjt}),children:[e.jsx(nn,{className:"h-4 w-4 mr-1.5"})," Add a commitment"]})]}),e.jsx("div",{className:"space-y-2",children:j.map(P=>{var R;return e.jsxs(we,{className:"p-4 rounded-2xl",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 flex-wrap",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"text-[15px] font-semibold text-slate-900",children:P.title}),e.jsx(qe,{variant:"outline",className:"rounded-full",children:((R=hjt.find(O=>O.value===P.content_type))==null?void 0:R.label)??P.content_type}),e.jsx(qe,{variant:"outline",className:`rounded-full capitalize ${zKn[P.status]??""}`,children:P.status}),e.jsx(qe,{variant:"outline",className:"rounded-full capitalize",children:P.cadence.replace("_"," ")})]}),e.jsx("div",{className:"text-[12.5px] text-slate-500 mt-1",children:[FKn(P.planned_for),P.channel,P.audience].filter(Boolean).join(" · ")}),P.notes&&e.jsx("div",{className:"text-[12.5px] text-slate-600 mt-1 line-clamp-2",children:P.notes})]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx($,{size:"icon",variant:"ghost",className:"h-8 w-8",title:"Edit",onClick:()=>y(P),children:e.jsx(ui,{className:"h-3.5 w-3.5"})}),e.jsx($,{size:"icon",variant:"ghost",className:"h-8 w-8",title:"Duplicate",onClick:()=>l.mutate(P),children:e.jsx(Da,{className:"h-3.5 w-3.5"})}),e.jsx($,{size:"icon",variant:"ghost",className:"h-8 w-8",title:P.is_archived?"Restore":"Archive",onClick:()=>o.mutate({id:P.id,archived:!P.is_archived}),children:e.jsx(kf,{className:"h-3.5 w-3.5"})}),e.jsx($,{size:"icon",variant:"ghost",className:"h-8 w-8 text-rose-600",title:"Delete",onClick:()=>_(P),children:e.jsx(Un,{className:"h-3.5 w-3.5"})})]})]}),e.jsxs("div",{className:"flex gap-2 mt-3 flex-wrap",children:[P.status!=="published"&&e.jsxs($,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>I(P),children:[e.jsx(Gr,{className:"h-3.5 w-3.5 mr-1.5"})," Mark published"]}),e.jsxs($,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>d.mutate({title:`Create: ${P.title}`,dueAt:P.planned_for?`${P.planned_for}T09:00:00`:new Date().toISOString(),notes:P.notes,touchType:"content"}),children:[e.jsx(op,{className:"h-3.5 w-3.5 mr-1.5"})," Add task"]}),e.jsx($,{size:"sm",variant:"ghost",className:"rounded-full",asChild:!0,children:e.jsxs(nr,{to:"/attract/influence/content-studio",children:[e.jsx(kn,{className:"h-3.5 w-3.5 mr-1.5"})," Draft it"]})})]})]},P.id)})}),e.jsx(zs,{open:!!x,onOpenChange:P=>!P&&y(null),children:e.jsxs(Rs,{className:"max-w-xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(Vs,{children:[e.jsx($s,{children:x!=null&&x.id?"Edit commitment":"New commitment"}),e.jsx(Cr,{children:"Pick something you can genuinely sustain."})]}),x&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Title *"}),e.jsx(be,{value:x.title??"",onChange:P=>y({...x,title:P.target.value}),placeholder:"e.g. October market update video"})]}),e.jsxs("div",{className:"grid sm:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Type"}),e.jsxs(bs,{value:x.content_type??"market_update",onValueChange:P=>y({...x,content_type:P}),children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsx(vs,{children:hjt.map(P=>e.jsx(We,{value:P.value,children:P.label},P.value))})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Cadence"}),e.jsxs(bs,{value:x.cadence??"monthly",onValueChange:P=>y({...x,cadence:P}),children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsx(vs,{children:OKn.map(P=>e.jsx(We,{value:P,className:"capitalize",children:P.replace("_"," ")},P))})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Planned for"}),e.jsx(be,{type:"date",value:x.planned_for??"",onChange:P=>y({...x,planned_for:P.target.value})})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Status"}),e.jsxs(bs,{value:x.status??"planned",onValueChange:P=>y({...x,status:P}),children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsx(vs,{children:mjt.map(P=>e.jsx(We,{value:P,className:"capitalize",children:P},P))})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Channel"}),e.jsx(be,{value:x.channel??"",onChange:P=>y({...x,channel:P.target.value}),placeholder:"Instagram, email, YouTube"})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Audience"}),e.jsx(be,{value:x.audience??"",onChange:P=>y({...x,audience:P.target.value}),placeholder:"Agents, sphere, neighborhood"})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Notes"}),e.jsx(Ls,{rows:3,value:x.notes??"",onChange:P=>y({...x,notes:P.target.value})})]}),e.jsxs("div",{className:"grid sm:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Published URL"}),e.jsx(be,{value:x.published_url??"",onChange:P=>y({...x,published_url:P.target.value}),placeholder:"https://"})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Results"}),e.jsx(be,{value:x.results_notes??"",onChange:P=>y({...x,results_notes:P.target.value}),placeholder:"Reach, replies, leads"})]})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"ghost",onClick:()=>y(null),children:"Cancel"}),e.jsx($,{className:"bg-gradient-to-r from-violet-600 to-indigo-600",onClick:M,disabled:a.isPending||i.isPending,children:"Save"})]})]})}),e.jsx(zs,{open:!!v,onOpenChange:P=>!P&&_(null),children:e.jsxs(Rs,{className:"max-w-md",children:[e.jsxs(Vs,{children:[e.jsx($s,{children:"Delete this commitment?"}),e.jsx(Cr,{children:"This can't be undone."})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"ghost",onClick:()=>_(null),children:"Cancel"}),e.jsx($,{variant:"destructive",onClick:()=>{c.mutate(v.id),_(null)},children:"Delete"})]})]})})]})}function pjt(s){if(!s)return null;const[t]=s.split("T");return t||null}const Mie={draft:{label:"Content",icon:kn,cls:"bg-violet-50 text-violet-700 border-violet-200"},presence:{label:"Market presence",icon:Cy,cls:"bg-blue-50 text-blue-700 border-blue-200"},speaking:{label:"Speaking",icon:w2,cls:"bg-amber-50 text-amber-700 border-amber-200"}};function $Kn(){const{drafts:s,isLoading:t,save:n}=rKt(),{commitments:r,isLoading:a}=lKt(),i=oKt(),l=rMe(),[o,c]=k.useState(()=>{const A=new Date;return new Date(A.getFullYear(),A.getMonth(),1)}),[d,u]=k.useState("all"),[h,m]=k.useState(null),p=k.useMemo(()=>(i.items??[]).filter(A=>!A.is_archived).map(A=>({id:A.id,kind:"speaking",title:A.title,date:pjt(A.starts_at),status:A.status,href:"/attract/influence/speaking"})),[i.items]),g=k.useMemo(()=>{const A=s.map(I=>({id:I.id,kind:"draft",title:I.topic||I.mode.replace(/_/g," "),date:pjt(I.planned_at??I.posted_at??null),status:I.status,href:"/attract/influence/content-studio"})),M=r.filter(I=>!I.is_archived).map(I=>({id:I.id,kind:"presence",title:I.title,date:I.planned_for,status:I.status,href:"/attract/produce/market-presence"}));return[...A,...M,...p].filter(I=>d==="all"||I.kind===d)},[s,r,p,d]),x=`${o.getFullYear()}-${String(o.getMonth()+1).padStart(2,"0")}`,y=g.filter(A=>{var M;return(M=A.date)==null?void 0:M.startsWith(x)}),v=g.filter(A=>!A.date),_=k.useMemo(()=>{const A=new Date(o.getFullYear(),o.getMonth(),1),M=new Date(A);return M.setDate(A.getDate()-A.getDay()),Array.from({length:42},(I,P)=>{const R=new Date(M);R.setDate(M.getDate()+P);const O=`${R.getFullYear()}-${String(R.getMonth()+1).padStart(2,"0")}-${String(R.getDate()).padStart(2,"0")}`;return{date:R,key:O,inMonth:R.getMonth()===o.getMonth(),items:g.filter(B=>B.date===O)}})},[o,g]),j=(()=>{const A=new Date;return`${A.getFullYear()}-${String(A.getMonth()+1).padStart(2,"0")}-${String(A.getDate()).padStart(2,"0")}`})(),C=t||a;return e.jsxs("div",{children:[e.jsxs(nr,{to:"/attract/influence",className:"inline-flex items-center gap-1.5 text-[12px] text-slate-500 hover:text-violet-700 mb-3",children:[e.jsx(Ia,{className:"h-3.5 w-3.5"})," Back to Influence"]}),e.jsx(Hm,{eyebrow:"Produce + Influence → Tool",title:"Content Calendar",description:"One month view of everything you've committed to publish — Content Studio drafts, market presence commitments, and speaking dates.",actions:e.jsx($,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",asChild:!0,children:e.jsxs(nr,{to:"/attract/influence/content-studio",children:[e.jsx(nn,{className:"h-4 w-4 mr-1.5"})," New Draft"]})})}),e.jsxs("div",{className:"flex items-center justify-between gap-2 flex-wrap mb-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx($,{size:"icon",variant:"outline",className:"rounded-full h-9 w-9",onClick:()=>c(new Date(o.getFullYear(),o.getMonth()-1,1)),children:e.jsx(Ld,{className:"h-4 w-4"})}),e.jsx("div",{className:"text-[16px] font-semibold text-slate-900 min-w-[170px] text-center",children:o.toLocaleString("en-US",{month:"long",year:"numeric"})}),e.jsx($,{size:"icon",variant:"outline",className:"rounded-full h-9 w-9",onClick:()=>c(new Date(o.getFullYear(),o.getMonth()+1,1)),children:e.jsx(fi,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",className:"rounded-full",onClick:()=>{const A=new Date;c(new Date(A.getFullYear(),A.getMonth(),1))},children:"Today"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(qe,{variant:"outline",className:"rounded-full",children:[y.length," scheduled this month"]}),e.jsxs(bs,{value:d,onValueChange:A=>u(A),children:[e.jsx(ys,{className:"w-[180px] rounded-full",children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"all",children:"All types"}),e.jsx(We,{value:"draft",children:"Content drafts"}),e.jsx(We,{value:"presence",children:"Market presence"}),e.jsx(We,{value:"speaking",children:"Speaking"})]})]})]})]}),C?e.jsx(fn,{className:"h-[560px] rounded-2xl"}):e.jsxs(we,{className:"rounded-2xl overflow-hidden",children:[e.jsx("div",{className:"grid grid-cols-7 bg-slate-50 border-b",children:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"].map(A=>e.jsx("div",{className:"px-2 py-2 text-[11px] uppercase tracking-wider text-slate-500 font-semibold text-center",children:A},A))}),e.jsx("div",{className:"grid grid-cols-7",children:_.map(A=>e.jsxs("div",{className:`min-h-[96px] border-b border-r p-1.5 ${A.inMonth?"":"bg-slate-50/60"}`,children:[e.jsx("div",{className:`text-[11.5px] font-medium mb-1 ${A.key===j?"text-violet-700":A.inMonth?"text-slate-700":"text-slate-400"}`,children:A.date.getDate()}),e.jsxs("div",{className:"space-y-1",children:[A.items.slice(0,3).map(M=>{const I=Mie[M.kind];return e.jsx(nr,{to:M.href,className:`block truncate rounded-md border px-1.5 py-0.5 text-[11px] ${I.cls}`,title:M.title,children:M.title},`${M.kind}-${M.id}`)}),A.items.length>3&&e.jsxs("div",{className:"text-[10.5px] text-slate-500 px-1",children:["+",A.items.length-3," more"]})]})]},A.key))})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2 mt-5",children:[e.jsxs(we,{className:"p-5 rounded-2xl",children:[e.jsxs("div",{className:"text-[15px] font-semibold text-slate-900 mb-1",children:["Unscheduled (",v.length,")"]}),e.jsx("p",{className:"text-[12.5px] text-slate-600 mb-3",children:"Give these a date so they show on the calendar."}),v.length===0&&e.jsx("div",{className:"text-[13px] text-slate-500",children:"Everything has a date. Nice."}),e.jsx("div",{className:"space-y-2",children:v.slice(0,8).map(A=>e.jsxs("div",{className:"flex items-center justify-between gap-2 rounded-xl bg-slate-50 px-3 py-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-[13px] font-medium text-slate-900 truncate capitalize",children:A.title}),e.jsxs("div",{className:"text-[11.5px] text-slate-500",children:[Mie[A.kind].label," · ",A.status]})]}),A.kind==="draft"?e.jsx($,{size:"sm",variant:"outline",className:"rounded-full flex-shrink-0",onClick:()=>m({id:A.id,title:A.title,date:j}),children:"Schedule"}):e.jsx($,{size:"sm",variant:"ghost",className:"rounded-full flex-shrink-0",asChild:!0,children:e.jsx(nr,{to:A.href,children:"Open"})})]},`${A.kind}-${A.id}`))})]}),e.jsxs(we,{className:"p-5 rounded-2xl",children:[e.jsx("div",{className:"text-[15px] font-semibold text-slate-900 mb-1",children:"This month at a glance"}),e.jsx("p",{className:"text-[12.5px] text-slate-600 mb-3",children:"Keep a steady rhythm across all three surfaces."}),e.jsx("div",{className:"space-y-2",children:Object.keys(Mie).map(A=>{const M=Mie[A],I=M.icon,P=y.filter(R=>R.kind===A).length;return e.jsxs("div",{className:"flex items-center gap-3 rounded-xl bg-slate-50 px-3 py-2",children:[e.jsx("div",{className:`h-8 w-8 rounded-lg grid place-items-center border ${M.cls}`,children:e.jsx(I,{className:"h-4 w-4"})}),e.jsx("div",{className:"text-[13.5px] font-medium text-slate-900 flex-1",children:M.label}),e.jsx("div",{className:"text-[16px] font-semibold tabular-nums text-slate-900",children:P})]},A)})}),e.jsxs($,{variant:"outline",className:"rounded-full mt-4 w-full",onClick:()=>l.mutate({title:`Plan content for ${o.toLocaleString("en-US",{month:"long"})}`,dueAt:new Date().toISOString(),touchType:"content"}),children:[e.jsx(op,{className:"h-3.5 w-3.5 mr-1.5"})," Add planning block to Today's Plan"]}),e.jsx($,{variant:"ghost",className:"rounded-full mt-2 w-full",asChild:!0,children:e.jsxs(nr,{to:"/attract/produce/market-presence",children:[e.jsx(fd,{className:"h-3.5 w-3.5 mr-1.5"})," Manage market presence cadence"]})})]})]}),e.jsx(zs,{open:!!h,onOpenChange:A=>!A&&m(null),children:e.jsxs(Rs,{className:"max-w-md",children:[e.jsxs(Vs,{children:[e.jsx($s,{children:"Schedule draft"}),e.jsx(Cr,{className:"capitalize",children:h==null?void 0:h.title})]}),h&&e.jsxs("div",{children:[e.jsx(re,{children:"Planned date"}),e.jsx(be,{type:"date",value:h.date,onChange:A=>m({...h,date:A.target.value})})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"ghost",onClick:()=>m(null),children:"Cancel"}),e.jsx($,{className:"bg-gradient-to-r from-violet-600 to-indigo-600",onClick:async()=>{h&&(await n.mutateAsync({id:h.id,planned_at:`${h.date}T09:00:00`}),m(null))},children:"Save"})]})]})})]})}const gjt=[{value:"birthday",label:"Birthday"},{value:"work_anniversary",label:"Work Anniversary"},{value:"license_anniversary",label:"License Anniversary"},{value:"production_milestone",label:"Production Milestone"},{value:"team_milestone",label:"Team Milestone"},{value:"family_milestone",label:"Family Milestone"},{value:"custom",label:"Custom Date"}];function UKn(s){const[t,n,r]=s.split(/[-/T]/).map(Number);return{y:t,m:n,d:r}}function Bqe(s,t=new Date){const{y:n,m:r,d:a}=UKn(s.milestone_on);if(!s.recurs_annually)return new Date(n,r-1,a);const i=new Date(t.getFullYear(),r-1,a),l=new Date(t.getFullYear(),t.getMonth(),t.getDate());return i{const l=[];return r.forEach(o=>{const c=[o.preferred_name||o.first_name,o.last_name].filter(Boolean).join(" ");[["birthday",o.birthday_on,`${c} — Birthday`],["work_anniversary",o.work_anniversary_on,`${c} — Work Anniversary`],["license_anniversary",o.license_anniversary_on,`${c} — License Anniversary`]].forEach(([d,u,h])=>{u&&l.push({id:`agent:${o.id}:${d}`,user_id:o.user_id,title:h,milestone_type:d,milestone_on:String(u).slice(0,10),recurs_annually:!0,linked_agent_ids:[o.id],notes:null,last_celebrated_at:null,is_archived:!1,created_at:o.created_at,updated_at:o.updated_at})})}),l},[r]),i=k.useMemo(()=>{const l=new Set(s.items.filter(c=>!c.is_archived).map(c=>{var d;return`${c.milestone_type}|${c.milestone_on.slice(5,10)}|${((d=c.linked_agent_ids)==null?void 0:d[0])??""}`}));return[...s.items.filter(c=>!c.is_archived),...a.filter(c=>!l.has(`${c.milestone_type}|${c.milestone_on.slice(5,10)}|${c.linked_agent_ids[0]}`))].map(c=>({item:c,next:Bqe(c)})).map(c=>({...c,days:cKt(c.next)})).filter(c=>c.days>=0).sort((c,d)=>c.days-d.days)},[s.items,a]);return{...s,milestones:s.items,derived:a,upcoming:i,quickTask:t,logActivity:n}}const xjt={milestone_type:"birthday",recurs_annually:!0,linked_agent_ids:[]};function VKn(s){return s.toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"})}function HKn(){var O;const{milestones:s,upcoming:t,isLoading:n,error:r,refetch:a,create:i,update:l,duplicate:o,archive:c,remove:d,quickTask:u,logActivity:h}=qKn(),m=A0(),p=(m==null?void 0:m.agents)??(m==null?void 0:m.items)??[],[g,x]=k.useState(!1),[y,v]=k.useState("90"),[_,j]=k.useState(null),[C,A]=k.useState(null),M=k.useMemo(()=>{if(g)return s.filter(U=>U.is_archived).map(U=>({item:U,next:Bqe(U),days:cKt(Bqe(U))}));const B=y==="all"?1/0:Number(y);return t.filter(U=>U.days<=B)},[s,t,g,y]),I=B=>{const U=p.find(G=>G.id===B);return U?[U.preferred_name||U.first_name,U.last_name].filter(Boolean).join(" "):"Agent"},P=async()=>{var U;if(!((U=_==null?void 0:_.title)!=null&&U.trim())||!(_!=null&&_.milestone_on)){ae.error("Title and date are required");return}const B={title:_.title.trim(),milestone_type:_.milestone_type??"birthday",milestone_on:_.milestone_on,recurs_annually:_.recurs_annually??!0,linked_agent_ids:_.linked_agent_ids??[],notes:_.notes||null};_.id?await l.mutateAsync({id:_.id,...B}):await i.mutateAsync(B),j(null)},R=async B=>{var U;await l.mutateAsync({id:B.id,last_celebrated_at:new Date().toISOString()}),await h.mutateAsync({title:`Celebrated: ${B.title}`,pillar:"connect",activityType:"milestone_celebrated",agentId:((U=B.linked_agent_ids)==null?void 0:U[0])??null})};return e.jsxs("div",{children:[e.jsxs(nr,{to:"/attract/connect",className:"inline-flex items-center gap-1.5 text-[12px] text-slate-500 hover:text-violet-700 mb-3",children:[e.jsx(Ia,{className:"h-3.5 w-3.5"})," Back to Connect"]}),e.jsx(Hm,{eyebrow:"Connect → Tool",title:"Milestones & Celebrations",description:"Remember the dates that matter to the agents in your pipeline. Recurring milestones roll forward every year so you never miss the reason to reach out.",actions:e.jsxs(e.Fragment,{children:[e.jsx($,{variant:"outline",className:"rounded-full",onClick:()=>x(B=>!B),children:g?"Show upcoming":"Show archived"}),e.jsxs($,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>j({...xjt}),children:[e.jsx(nn,{className:"h-4 w-4 mr-1.5"})," Add Milestone"]})]})}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-3 mb-4",children:[e.jsxs(we,{className:"p-4 rounded-2xl",children:[e.jsx("div",{className:"text-[22px] font-semibold tabular-nums text-slate-900",children:t.filter(B=>B.days<=7).length}),e.jsx("div",{className:"text-[12px] text-slate-500",children:"Next 7 days"})]}),e.jsxs(we,{className:"p-4 rounded-2xl",children:[e.jsx("div",{className:"text-[22px] font-semibold tabular-nums text-violet-600",children:t.filter(B=>B.days<=30).length}),e.jsx("div",{className:"text-[12px] text-slate-500",children:"Next 30 days"})]}),e.jsxs(we,{className:"p-4 rounded-2xl",children:[e.jsx("div",{className:"text-[22px] font-semibold tabular-nums text-slate-900",children:s.filter(B=>!B.is_archived).length}),e.jsx("div",{className:"text-[12px] text-slate-500",children:"Tracked total"})]})]}),!g&&e.jsx("div",{className:"flex gap-2 flex-wrap mb-4",children:e.jsxs(bs,{value:y,onValueChange:B=>v(B),children:[e.jsx(ys,{className:"w-[190px] rounded-full",children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"30",children:"Next 30 days"}),e.jsx(We,{value:"90",children:"Next 90 days"}),e.jsx(We,{value:"all",children:"All upcoming"})]})]})}),n&&e.jsx("div",{className:"space-y-2",children:[0,1,2].map(B=>e.jsx(fn,{className:"h-20 rounded-2xl"},B))}),!n&&r&&e.jsxs(we,{className:"p-8 rounded-2xl text-center",children:[e.jsx(Ho,{className:"h-6 w-6 text-rose-500 mx-auto mb-2"}),e.jsx("div",{className:"font-semibold text-slate-900",children:"Couldn't load milestones"}),e.jsx("div",{className:"text-[13px] text-slate-600 mt-1",children:r.message}),e.jsxs($,{variant:"outline",className:"rounded-full mt-4",onClick:()=>a(),children:[e.jsx(jm,{className:"h-3.5 w-3.5 mr-1.5"})," Retry"]})]}),!n&&!r&&M.length===0&&e.jsxs(we,{className:"p-10 rounded-2xl text-center border-dashed",children:[e.jsx("div",{className:"h-12 w-12 rounded-2xl bg-violet-50 text-violet-600 grid place-items-center mx-auto mb-3",children:e.jsx(ip,{className:"h-6 w-6"})}),e.jsx("div",{className:"text-[16px] font-semibold text-slate-900",children:g?"Nothing archived":"No milestones in this window"}),e.jsx("p",{className:"text-[13.5px] text-slate-600 mt-1.5 max-w-md mx-auto",children:"Add birthdays, license anniversaries, and production milestones for the agents you're building relationships with."}),!g&&e.jsxs($,{className:"rounded-full mt-4 bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>j({...xjt}),children:[e.jsx(nn,{className:"h-4 w-4 mr-1.5"})," Add a milestone"]})]}),e.jsx("div",{className:"space-y-2",children:M.map(({item:B,next:U,days:G})=>{var Y,se;const H=String(B.id).startsWith("agent:");return e.jsxs(we,{className:"p-4 rounded-2xl",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 flex-wrap",children:[e.jsxs("div",{className:"flex items-start gap-3 min-w-0",children:[e.jsx("div",{className:"h-11 w-11 rounded-xl bg-violet-50 text-violet-700 grid place-items-center flex-shrink-0",children:e.jsxs("div",{className:"text-center leading-none",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-wider",children:U.toLocaleString("en-US",{month:"short"})}),e.jsx("div",{className:"text-[15px] font-semibold",children:U.getDate()})]})}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"text-[15px] font-semibold text-slate-900",children:B.title}),e.jsx(qe,{variant:"outline",className:"rounded-full",children:((Y=gjt.find(ee=>ee.value===B.milestone_type))==null?void 0:Y.label)??B.milestone_type}),H&&e.jsx(qe,{variant:"outline",className:"rounded-full bg-violet-50 text-violet-700 border-violet-200",children:"From contact record"}),!g&&e.jsx(qe,{variant:"outline",className:`rounded-full ${G<=7?"bg-amber-50 text-amber-700 border-amber-200":""}`,children:G===0?"Today":G===1?"Tomorrow":`in ${G} days`}),B.recurs_annually&&e.jsx(qe,{variant:"outline",className:"rounded-full",children:"Annual"})]}),e.jsxs("div",{className:"text-[12.5px] text-slate-500 mt-1",children:[VKn(U),(se=B.linked_agent_ids)!=null&&se.length?` · ${B.linked_agent_ids.map(I).join(", ")}`:"",B.last_celebrated_at?` · last celebrated ${new Date(B.last_celebrated_at).toLocaleDateString("en-US")}`:""]}),B.notes&&e.jsx("div",{className:"text-[12.5px] text-slate-600 mt-1 line-clamp-2",children:B.notes})]})]}),e.jsx("div",{className:"flex gap-1",children:H?e.jsx($,{size:"sm",variant:"ghost",className:"rounded-full text-[12px]",asChild:!0,children:e.jsx(nr,{to:`/attract/agents/${B.linked_agent_ids[0]}`,children:"Open contact"})}):e.jsxs(e.Fragment,{children:[e.jsx($,{size:"icon",variant:"ghost",className:"h-8 w-8",title:"Edit",onClick:()=>j(B),children:e.jsx(ui,{className:"h-3.5 w-3.5"})}),e.jsx($,{size:"icon",variant:"ghost",className:"h-8 w-8",title:"Duplicate",onClick:()=>o.mutate(B),children:e.jsx(Da,{className:"h-3.5 w-3.5"})}),e.jsx($,{size:"icon",variant:"ghost",className:"h-8 w-8",title:B.is_archived?"Restore":"Archive",onClick:()=>c.mutate({id:B.id,archived:!B.is_archived}),children:e.jsx(kf,{className:"h-3.5 w-3.5"})}),e.jsx($,{size:"icon",variant:"ghost",className:"h-8 w-8 text-rose-600",title:"Delete",onClick:()=>A(B),children:e.jsx(Un,{className:"h-3.5 w-3.5"})})]})})]}),e.jsxs("div",{className:"flex gap-2 mt-3 flex-wrap",children:[e.jsxs($,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>{var ee;return u.mutate({title:`Reach out: ${B.title}`,dueAt:U.toISOString(),notes:B.notes,touchType:"celebration",agentId:((ee=B.linked_agent_ids)==null?void 0:ee[0])??null})},children:[e.jsx(op,{className:"h-3.5 w-3.5 mr-1.5"})," Add reach-out task"]}),!H&&e.jsxs($,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>R(B),children:[e.jsx(jg,{className:"h-3.5 w-3.5 mr-1.5"})," Mark celebrated"]})]})]},B.id)})}),e.jsx(zs,{open:!!_,onOpenChange:B=>!B&&j(null),children:e.jsxs(Rs,{className:"max-w-xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(Vs,{children:[e.jsx($s,{children:_!=null&&_.id?"Edit milestone":"Add milestone"}),e.jsx(Cr,{children:"Annual milestones roll forward automatically each year."})]}),_&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Title *"}),e.jsx(be,{value:_.title??"",onChange:B=>j({..._,title:B.target.value}),placeholder:"e.g. Sarah's birthday"})]}),e.jsxs("div",{className:"grid sm:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Type"}),e.jsxs(bs,{value:_.milestone_type??"birthday",onValueChange:B=>j({..._,milestone_type:B}),children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsx(vs,{children:gjt.map(B=>e.jsx(We,{value:B.value,children:B.label},B.value))})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Date *"}),e.jsx(be,{type:"date",value:_.milestone_on??"",onChange:B=>j({..._,milestone_on:B.target.value})})]})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-xl border border-slate-200 px-4 py-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[13.5px] font-medium text-slate-900",children:"Repeats every year"}),e.jsx("div",{className:"text-[12px] text-slate-600",children:"Turn off for one-time milestones."})]}),e.jsx(On,{checked:_.recurs_annually??!0,onCheckedChange:B=>j({..._,recurs_annually:B})})]}),p.length>0&&e.jsxs("div",{children:[e.jsx(re,{children:"Link to agent"}),e.jsxs(bs,{value:((O=_.linked_agent_ids)==null?void 0:O[0])??"none",onValueChange:B=>j({..._,linked_agent_ids:B==="none"?[]:[B]}),children:[e.jsx(ys,{children:e.jsx(_s,{placeholder:"Optional"})}),e.jsxs(vs,{children:[e.jsx(We,{value:"none",children:"No agent"}),p.map(B=>e.jsx(We,{value:B.id,children:I(B.id)},B.id))]})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Notes"}),e.jsx(Ls,{rows:3,value:_.notes??"",onChange:B=>j({..._,notes:B.target.value}),placeholder:"Gift ideas, personal details, how you'll reach out"})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"ghost",onClick:()=>j(null),children:"Cancel"}),e.jsx($,{className:"bg-gradient-to-r from-violet-600 to-indigo-600",onClick:P,disabled:i.isPending||l.isPending,children:"Save"})]})]})}),e.jsx(zs,{open:!!C,onOpenChange:B=>!B&&A(null),children:e.jsxs(Rs,{className:"max-w-md",children:[e.jsxs(Vs,{children:[e.jsx($s,{children:"Delete this milestone?"}),e.jsx(Cr,{children:"This can't be undone."})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"ghost",onClick:()=>A(null),children:"Cancel"}),e.jsx($,{variant:"destructive",onClick:()=>{d.mutate(C.id),A(null)},children:"Delete"})]})]})})]})}function GKn(){var c;const{shareToken:s}=oo(),[t,n]=k.useState("loading"),[r,a]=k.useState(null),[i,l]=k.useState(!1);k.useEffect(()=>{(async()=>{if(!s){n("not_found");return}const{data:d,error:u}=await V.rpc("public_get_attract_kit",{_token:s});if(u){n("error");return}if(!d||d.status!=="ok"){n((d==null?void 0:d.status)??"not_found");return}a(d),n("ok"),V.rpc("public_log_attract_kit_event",{_token:s,_event_type:"page_view",_item_id:null,_metadata:{}})})()},[s]);const o=(d,u,h)=>{s&&V.rpc("public_log_attract_kit_event",{_token:s,_event_type:d,_item_id:u??null,_metadata:h??{}})};return t==="loading"?e.jsx("div",{className:"min-h-screen bg-[#05070f] grid place-items-center text-slate-300",children:"Loading…"}):t!=="ok"?e.jsx("div",{className:"min-h-screen bg-[#05070f] grid place-items-center px-6",children:e.jsxs(we,{className:"max-w-md w-full p-8 bg-white/5 border-white/10 text-slate-100 rounded-2xl text-center",children:[e.jsx(Ho,{className:"h-8 w-8 text-amber-400 mx-auto"}),e.jsx("div",{className:"mt-3 text-xl font-semibold",children:t==="expired"?"This kit has expired":t==="revoked"?"This kit is no longer available":t==="not_found"?"This kit could not be found":"Something went wrong"}),e.jsx("p",{className:"text-slate-400 mt-2 text-sm",children:"Please reach out to the person who shared it with you for an updated link."})]})}):e.jsx("div",{className:"min-h-screen bg-[#05070f]",children:e.jsxs("div",{className:"max-w-3xl mx-auto py-6 px-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-[10.5px] uppercase tracking-widest text-violet-400 font-semibold justify-center py-3",children:[e.jsx(kn,{className:"h-3.5 w-3.5"})," A LevelUp Attract kit"]}),e.jsx(aKt,{kit:r.kit,items:r.items,owner:r.owner,personalNote:(c=r.share)==null?void 0:c.personal_note,mode:"public",onEvent:o}),e.jsx(we,{className:"mt-6 p-6 bg-white/5 border-white/10 text-slate-100 rounded-2xl",children:i?e.jsx(WKn,{token:s,onSent:()=>l(!1),onEvent:o}):e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"text-[15px] font-semibold",children:"Have a question about this?"}),e.jsxs("p",{className:"text-slate-400 text-[13px] mt-1",children:["Send a private note — ",r.owner.display_name," will get it right away."]}),e.jsx($,{className:"mt-4 bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>l(!0),children:"Ask a question"})]})}),e.jsx("div",{className:"text-center text-[11px] text-slate-600 mt-6 pb-10",children:"Powered by LevelUp Attract"})]})})}function WKn({token:s,onSent:t,onEvent:n}){const[r,a]=k.useState(""),[i,l]=k.useState(""),[o,c]=k.useState(""),[d,u]=k.useState(!1),h=async()=>{if(o.trim().length<2)return ae.error("Please add a short message");u(!0);const{data:m,error:p}=await V.rpc("public_submit_attract_kit_question",{_token:s,_name:r,_email:i,_message:o});if(u(!1),p||!(m!=null&&m.ok))return ae.error("Could not send — please try again");ae.success("Sent — thank you!"),t()};return e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"text-[14px] font-semibold",children:"Send a private message"}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-2",children:[e.jsx(be,{placeholder:"Your name (optional)",value:r,onChange:m=>a(m.target.value),className:"bg-white/5 border-white/10 text-white placeholder:text-slate-500"}),e.jsx(be,{placeholder:"Your email (optional)",value:i,onChange:m=>l(m.target.value),className:"bg-white/5 border-white/10 text-white placeholder:text-slate-500"})]}),e.jsx(Ls,{rows:4,placeholder:"What's your question?",value:o,onChange:m=>c(m.target.value),className:"bg-white/5 border-white/10 text-white placeholder:text-slate-500"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx($,{variant:"outline",onClick:()=>{n("meeting_requested"),ae.success("Request sent")},children:"Request a conversation"}),e.jsx($,{onClick:h,disabled:d,className:"bg-gradient-to-r from-violet-600 to-indigo-600 ml-auto",children:d?"Sending…":"Send question"})]})]})}function KKn(){const{slug:s}=oo(),[t]=Jc(),n=t.get("inv")||null,[r,a]=k.useState("loading"),[i,l]=k.useState(null),[o,c]=k.useState({name:"",email:"",phone:"",answers:{}}),[d,u]=k.useState(!1),[h,m]=k.useState(null);k.useEffect(()=>{s&&(async()=>{const{data:x,error:y}=await V.rpc("public_get_attract_event",{_slug:s});if(y||!x||x.error){a((x==null?void 0:x.error)||"not_found");return}l(x),a("ok"),n&&V.rpc("public_track_attract_invitation_view",{_token:n})})()},[s,n]);const p=async()=>{u(!0);const{data:x,error:y}=await V.rpc("public_register_attract_event",{_slug:s,_name:o.name,_email:o.email,_phone:o.phone||null,_answers:o.answers||{},_invitation_token:n});if(u(!1),y){alert("Something went wrong. Please try again.");return}const v=x;if(v!=null&&v.error){alert(v.error==="invalid_email"?"That email looks off.":v.error==="full"?"This event is full.":"Could not register.");return}m(v)},g=()=>{if(!i)return;const x=new Blob([AWt(i)],{type:"text/calendar"}),y=document.createElement("a");y.href=URL.createObjectURL(x),y.download=`${s}.ics`,y.click()};if(r==="loading")return e.jsx("div",{className:"min-h-screen grid place-items-center text-slate-400",children:"Loading…"});if(r!=="ok"||!i){const x=r==="cancelled"?"This event was cancelled.":r==="not_available"?"This event is not open for registration.":"This event could not be found.";return e.jsx("div",{className:"min-h-screen grid place-items-center px-6 text-center",children:e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-semibold text-slate-900",children:x}),e.jsx("div",{className:"text-slate-500 mt-2",children:"The link may have expired."})]})})}return e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-slate-50 via-white to-violet-50",children:e.jsxs("div",{className:"max-w-3xl mx-auto px-4 py-10 md:py-16",children:[i.cover_image_url&&e.jsx("div",{className:"rounded-3xl overflow-hidden mb-8 aspect-[16/7] bg-slate-100",children:e.jsx("img",{src:i.cover_image_url,alt:"",className:"w-full h-full object-cover"})}),e.jsxs("div",{className:"text-center mb-8",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.2em] text-violet-600 font-semibold mb-3",children:"You are invited"}),e.jsx("h1",{className:"text-3xl md:text-5xl font-semibold tracking-tight text-slate-900",children:i.title}),i.host&&e.jsxs("div",{className:"text-slate-600 mt-3 text-[15px]",children:["Hosted by ",e.jsx("span",{className:"font-semibold",children:i.host.name}),i.host.brokerage_name?` · ${i.host.brokerage_name}`:""]})]}),e.jsxs(we,{className:"p-6 rounded-3xl border-slate-200 bg-white",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4 text-[14px]",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(ha,{className:"h-5 w-5 text-violet-600 mt-0.5"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-slate-500 text-[12px]",children:"When"}),e.jsx("div",{className:"font-semibold text-slate-900",children:Ys(new Date(i.starts_at),"EEEE, MMMM d · h:mm a")}),e.jsx("div",{className:"text-slate-500 text-[12px]",children:i.timezone})]})]}),e.jsxs("div",{className:"flex items-start gap-3",children:[i.format==="virtual"?e.jsx(ia,{className:"h-5 w-5 text-violet-600 mt-0.5"}):e.jsx(Si,{className:"h-5 w-5 text-violet-600 mt-0.5"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-slate-500 text-[12px]",children:"Where"}),e.jsx("div",{className:"font-semibold text-slate-900",children:i.format==="virtual"?"Virtual — link sent after registration":i.location||"In person"}),i.address&&e.jsx("div",{className:"text-slate-500 text-[12px]",children:i.address})]})]}),i.capacity&&e.jsxs("div",{className:"flex items-start gap-3 md:col-span-2",children:[e.jsx(Xn,{className:"h-5 w-5 text-violet-600 mt-0.5"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-slate-500 text-[12px]",children:"Room size"}),e.jsx("div",{className:"font-semibold text-slate-900",children:i.seats_left===0?"Waitlist only":`${i.seats_left} of ${i.capacity} seats left`})]})]})]}),i.description&&e.jsx("p",{className:"text-[15px] text-slate-700 leading-relaxed mt-5",children:i.description}),(i.learning_outcomes||[]).length>0&&e.jsxs("div",{className:"mt-5",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-2",children:"What you will receive"}),e.jsx("ul",{className:"space-y-1.5",children:i.learning_outcomes.map((x,y)=>e.jsxs("li",{className:"flex gap-2 text-[14px] text-slate-800",children:[e.jsx(ma,{className:"h-4 w-4 text-emerald-600 shrink-0 mt-0.5"})," ",x]},y))})]}),(i.agenda||[]).length>0&&e.jsxs("div",{className:"mt-5",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-2",children:"Agenda"}),e.jsx("ul",{className:"space-y-1",children:i.agenda.map((x,y)=>e.jsxs("li",{className:"flex gap-3 text-[13.5px]",children:[e.jsx("span",{className:"text-slate-500 tabular-nums w-16 shrink-0",children:x.time}),e.jsx("span",{className:"text-slate-800",children:x.item})]},y))})]})]}),h?e.jsxs(we,{className:"mt-6 p-8 rounded-3xl border-emerald-200 bg-emerald-50 text-center",children:[e.jsx("div",{className:"mx-auto h-14 w-14 rounded-full bg-emerald-500 text-white grid place-items-center",children:e.jsx(ma,{className:"h-7 w-7"})}),e.jsx("div",{className:"text-2xl font-semibold text-slate-900 mt-4",children:h.status==="waitlisted"?"You are on the waitlist":"You are in."}),i.confirmation_message&&e.jsx("div",{className:"text-[15px] text-slate-700 mt-2 max-w-lg mx-auto",children:i.confirmation_message}),e.jsxs($,{variant:"outline",className:"rounded-full mt-5",onClick:g,children:[e.jsx(ji,{className:"h-4 w-4 mr-2"})," Add to calendar"]})]}):e.jsxs(we,{className:"mt-6 p-6 rounded-3xl border-slate-200 bg-white",children:[e.jsxs("div",{className:"text-lg font-semibold text-slate-900 mb-1 flex items-center gap-2",children:[e.jsx(kn,{className:"h-4 w-4 text-violet-600"})," Save your seat"]}),e.jsx("div",{className:"text-[13px] text-slate-500 mb-4",children:"The room is small on purpose."}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Full name"}),e.jsx(be,{value:o.name,onChange:x=>c({...o,name:x.target.value})})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Email"}),e.jsx(be,{type:"email",value:o.email,onChange:x=>c({...o,email:x.target.value})})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Phone (optional)"}),e.jsx(be,{value:o.phone,onChange:x=>c({...o,phone:x.target.value})})]})]}),(i.registration_questions||[]).map(x=>e.jsxs("div",{children:[e.jsx(re,{children:x.label}),x.type==="long"?e.jsx(Ls,{rows:3,value:o.answers[x.key]||"",onChange:y=>c({...o,answers:{...o.answers,[x.key]:y.target.value}})}):e.jsx(be,{value:o.answers[x.key]||"",onChange:y=>c({...o,answers:{...o.answers,[x.key]:y.target.value}})})]},x.key))]}),e.jsx($,{disabled:d,className:"w-full mt-5 rounded-full bg-gradient-to-r from-violet-600 to-indigo-600 h-11",onClick:p,children:d?"Saving…":i.seats_left===0?"Join the waitlist":"Save my seat"}),e.jsx("div",{className:"text-[11.5px] text-slate-400 text-center mt-3",children:"Build relationships first. We will only email you about this event."})]})]})})}function YKn(){const{token:s}=oo(),[t]=Jc(),n=t.get("a"),[r,a]=k.useState("loading"),[i,l]=k.useState("");return k.useEffect(()=>{if(!s||!n){a("error");return}(async()=>{const{data:o}=await V.rpc("public_check_in_attendee",{_check_in_token:s,_attendee_token:n}),c=o;c!=null&&c.ok?(l(c.name||""),a(c.already?"already":"ok")):a("error")})()},[s,n]),e.jsx("div",{className:"min-h-screen grid place-items-center bg-slate-50 px-4",children:e.jsxs(we,{className:"p-8 rounded-3xl border-slate-200 bg-white max-w-md w-full text-center",children:[r==="loading"&&e.jsx("div",{className:"text-slate-500",children:"Checking you in…"}),(r==="ok"||r==="already")&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mx-auto h-14 w-14 rounded-full bg-emerald-500 text-white grid place-items-center",children:e.jsx(ma,{className:"h-7 w-7"})}),e.jsx("div",{className:"text-2xl font-semibold mt-4 text-slate-900",children:r==="already"?"Already checked in":"You are in!"}),i&&e.jsxs("div",{className:"text-slate-600 mt-1",children:["Welcome, ",i,"."]}),e.jsx("div",{className:"text-[13px] text-slate-500 mt-4",children:"Find your seat and enjoy the room."})]}),r==="error"&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-xl font-semibold text-slate-900",children:"We could not check you in."}),e.jsx("div",{className:"text-slate-500 mt-2",children:"Please see the host at the door."})]})]})})}const Pie=s=>s.toLocaleString("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0});function ZKn(s){if(!s)return"";const t=s.match(/(?:youtu\.be\/|youtube\.com\/(?:watch\?v=|embed\/|shorts\/))([\w-]{6,})/);if(t)return`https://www.youtube.com/embed/${t[1]}?autoplay=1&rel=0`;const n=s.match(/vimeo\.com\/(\d+)/);if(n)return`https://player.vimeo.com/video/${n[1]}?autoplay=1`;const r=s.match(/loom\.com\/(?:share|embed)\/([\w-]+)/);return r?`https://www.loom.com/embed/${r[1]}`:s}function dKt({cfg:s,onSubmitLead:t,onTrack:n,preview:r}){var I,P,R;const a=s.primary_color||"#0f1b3d",i=s.accent_color||"#c9a84c",l=s.sections||{},[o,c]=k.useState(!1),[d,u]=k.useState(null),[h,m]=k.useState(!1),[p,g]=k.useState({first_name:"",last_name:"",email:"",phone:"",brokerage:"",message:""}),[x,y]=k.useState({first_name:"",email:""}),v=s.calculator||{},[_,j]=k.useState(15e4),C=k.useMemo(()=>{const O=Number(v.cap??16e3),B=Number(v.split??80)/100,U=Number(v.transaction_fee??250),G=Number(v.current_split??70)/100,H=Number(v.current_monthly_fees??150),Y=Math.min(_*(1-B),O),se=_-Y-U*12,ee=_*G-H*12;return{here:Math.max(se,0),current:Math.max(ee,0),diff:Math.max(se-ee,0),capped:Y>=O}},[_,v]),A=async(O,B,U)=>{if(r||!t){u(O);return}m(!0);try{await t({first_name:B.first_name||"",last_name:B.last_name||"",email:B.email||"",phone:B.phone||"",brokerage:B.brokerage||"",message:B.message||"",source:O,metadata:U}),u(O)}catch(G){Ma({title:"We couldn't send that",description:(G==null?void 0:G.message)||"Please try again in a moment.",variant:"destructive"})}finally{m(!1)}},M=O=>e.jsxs("a",{href:"#connect",onClick:()=>n==null?void 0:n("cta_click","hero"),className:"group inline-flex items-center gap-3 rounded-full px-8 py-4 text-base font-semibold shadow-2xl transition-transform hover:scale-[1.03]",style:{backgroundColor:i,color:"#10131c"},children:[O||s.cta_label||"Book a confidential 15-min call",e.jsx(xi,{className:"h-4 w-4 transition-transform group-hover:translate-x-1"})]});return e.jsxs("div",{className:"min-h-screen bg-[#0b0e17] text-white antialiased",children:[l.hero!==!1&&e.jsxs("section",{className:"relative overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0",style:{background:`linear-gradient(160deg, ${a} 0%, #05070d 75%)`}}),s.hero_image_url&&e.jsx("div",{className:"absolute inset-0 bg-cover bg-center opacity-20",style:{backgroundImage:`url(${s.hero_image_url})`}}),e.jsx("div",{className:"absolute inset-0 opacity-[0.06]",style:{backgroundImage:"radial-gradient(circle at 20% 20%, white 1px, transparent 1px)",backgroundSize:"48px 48px"}}),e.jsxs("div",{className:"relative z-10 mx-auto grid max-w-6xl items-center gap-12 px-6 py-24 md:grid-cols-[1.2fr_.8fr] md:py-32",children:[e.jsxs("div",{children:[s.logo_url&&e.jsx("img",{src:s.logo_url,alt:"",className:"mb-8 h-10 w-auto"}),s.eyebrow&&e.jsx("span",{className:"mb-5 inline-block text-xs font-medium uppercase tracking-[0.22em]",style:{color:i},children:s.eyebrow}),e.jsx("h1",{className:"mb-6 text-4xl font-bold leading-[1.08] tracking-tight md:text-6xl",children:s.headline}),e.jsx("p",{className:"mb-10 max-w-xl text-lg font-light leading-relaxed text-white/70",children:s.subheadline}),e.jsxs("div",{className:"flex flex-wrap items-center gap-4",children:[M(),s.calendar_url&&e.jsxs("a",{href:s.calendar_url,target:"_blank",rel:"noreferrer",onClick:()=>n==null?void 0:n("cta_click","calendar"),className:"inline-flex items-center gap-2 rounded-full border border-white/25 px-6 py-4 text-sm font-medium text-white/85 backdrop-blur transition-colors hover:bg-white/10",children:[e.jsx(ha,{className:"h-4 w-4"})," See my calendar"]})]})]}),s.headshot_url&&e.jsxs("div",{className:"relative mx-auto w-full max-w-xs",children:[e.jsx("div",{className:"absolute -inset-3 rounded-[2rem] opacity-40 blur-2xl",style:{background:i}}),e.jsx("img",{src:s.headshot_url,alt:s.agent_name||"",className:"relative w-full rounded-[1.75rem] object-cover shadow-2xl"}),e.jsxs("div",{className:"relative mt-5 text-center",children:[e.jsx("div",{className:"text-lg font-semibold",children:s.agent_name}),e.jsx("div",{className:"text-sm text-white/55",children:s.agent_title})]})]})]})]}),l.credibility!==!1&&(s.credibility||[]).length>0&&e.jsx("section",{className:"border-y border-white/10 bg-white/[0.03]",children:e.jsx("div",{className:"mx-auto grid max-w-6xl grid-cols-2 gap-8 px-6 py-10 md:grid-cols-4",children:(s.credibility||[]).map((O,B)=>e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"text-2xl font-bold md:text-3xl",style:{color:i},children:O.value}),e.jsx("div",{className:"mt-1 text-xs uppercase tracking-wider text-white/50",children:O.label})]},B))})}),l.story!==!1&&(s.story_body||s.story_video_url)&&e.jsxs("section",{className:"mx-auto max-w-5xl px-6 py-20 md:py-28",children:[e.jsx("h2",{className:"mb-6 text-3xl font-bold tracking-tight md:text-4xl",children:s.story_title||"Why I moved"}),s.story_video_url&&e.jsx("div",{className:"mb-8 aspect-video overflow-hidden rounded-2xl border border-white/10 bg-black",children:o?e.jsx("iframe",{src:ZKn(s.story_video_url),className:"h-full w-full",allow:"autoplay; fullscreen",allowFullScreen:!0,title:"Story"}):e.jsxs("button",{onClick:()=>{c(!0),n==null||n("cta_click","story_video")},className:"group relative flex h-full w-full items-center justify-center bg-cover bg-center",style:{backgroundImage:s.hero_image_url?`url(${s.hero_image_url})`:void 0},children:[e.jsx("div",{className:"absolute inset-0 bg-black/55"}),e.jsx(mm,{className:"relative h-20 w-20 text-white/90 transition-transform group-hover:scale-110"})]})}),e.jsx("p",{className:"max-w-3xl whitespace-pre-line text-lg font-light leading-relaxed text-white/70",children:s.story_body})]}),l.value_stack!==!1&&(s.value_cards||[]).length>0&&e.jsx("section",{className:"border-y border-white/10 bg-white/[0.02] py-20 md:py-28",children:e.jsxs("div",{className:"mx-auto max-w-6xl px-6",children:[e.jsx("h2",{className:"mb-3 text-3xl font-bold tracking-tight md:text-4xl",children:"What you actually get"}),e.jsx("p",{className:"mb-12 max-w-2xl text-white/60",children:"No hype. Here is the model, in plain English."}),e.jsx("div",{className:"grid gap-5 md:grid-cols-2 lg:grid-cols-3",children:(s.value_cards||[]).map((O,B)=>e.jsxs("div",{className:"rounded-2xl border border-white/10 bg-white/[0.03] p-6 transition-colors hover:border-white/25",children:[e.jsx("div",{className:"mb-3 flex h-9 w-9 items-center justify-center rounded-lg",style:{backgroundColor:`${i}22`,color:i},children:e.jsx(ma,{className:"h-4 w-4"})}),e.jsx("h3",{className:"mb-2 text-lg font-semibold",children:O.title}),e.jsx("p",{className:"text-sm leading-relaxed text-white/65",children:O.body}),O.proof&&e.jsx("p",{className:"mt-3 text-xs uppercase tracking-wider text-white/40",children:O.proof})]},B))})]})}),l.calculator!==!1&&v.enabled!==!1&&e.jsx("section",{className:"py-20 md:py-28",children:e.jsx("div",{className:"mx-auto max-w-4xl px-6",children:e.jsxs("div",{className:"rounded-3xl border border-white/10 bg-gradient-to-b from-white/[0.06] to-transparent p-8 md:p-12",children:[e.jsx("h2",{className:"mb-2 text-3xl font-bold tracking-tight md:text-4xl",children:v.title||"Run your own numbers"}),e.jsx("p",{className:"mb-8 text-white/60",children:"Move the slider to your gross commission income for the year."}),e.jsxs("div",{className:"mb-8",children:[e.jsxs("div",{className:"mb-3 flex items-baseline justify-between",children:[e.jsx(re,{className:"text-white/70",children:"Your annual GCI"}),e.jsx("span",{className:"text-2xl font-bold",style:{color:i},children:Pie(_)})]}),e.jsx("input",{type:"range",min:25e3,max:1e6,step:5e3,value:_,onChange:O=>j(Number(O.target.value)),onMouseUp:()=>n==null?void 0:n("calculator_run","calculator",{gci:_}),onTouchEnd:()=>n==null?void 0:n("calculator_run","calculator",{gci:_}),className:"w-full accent-white"})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-3",children:[e.jsxs("div",{className:"rounded-2xl border border-white/10 p-5",children:[e.jsx("div",{className:"text-xs uppercase tracking-wider text-white/45",children:"Where you are now"}),e.jsx("div",{className:"mt-2 text-2xl font-semibold text-white/80",children:Pie(C.current)})]}),e.jsxs("div",{className:"rounded-2xl border p-5",style:{borderColor:i},children:[e.jsx("div",{className:"text-xs uppercase tracking-wider",style:{color:i},children:"With me"}),e.jsx("div",{className:"mt-2 text-2xl font-bold",children:Pie(C.here)}),C.capped&&e.jsx("div",{className:"mt-1 text-xs text-white/50",children:"You would cap this year."})]}),e.jsxs("div",{className:"rounded-2xl border border-white/10 bg-white/[0.04] p-5",children:[e.jsx("div",{className:"text-xs uppercase tracking-wider text-white/45",children:"Difference"}),e.jsxs("div",{className:"mt-2 text-2xl font-bold",style:{color:i},children:["+",Pie(C.diff)]})]})]}),e.jsx("p",{className:"mt-6 text-xs leading-relaxed text-white/35",children:"Estimates only, based on the assumptions above. Your actual numbers depend on your production and agreements."}),e.jsx("div",{className:"mt-8",children:M("Show me my exact numbers")})]})})}),l.sponsor!==!1&&(s.sponsor_cards||[]).length>0&&e.jsx("section",{className:"border-y border-white/10 bg-white/[0.02] py-20 md:py-28",children:e.jsxs("div",{className:"mx-auto max-w-5xl px-6",children:[e.jsx("h2",{className:"mb-3 text-3xl font-bold tracking-tight md:text-4xl",children:"What you get from me"}),e.jsx("p",{className:"mb-12 max-w-2xl text-white/60",children:"The brokerage is the same for everyone. Who you partner with is not."}),e.jsx("div",{className:"grid gap-5 md:grid-cols-2",children:(s.sponsor_cards||[]).map((O,B)=>e.jsxs("div",{className:"flex gap-4 rounded-2xl border border-white/10 p-6",children:[e.jsx("div",{className:"mt-1 flex h-8 w-8 shrink-0 items-center justify-center rounded-full text-sm font-bold",style:{backgroundColor:i,color:"#10131c"},children:B+1}),e.jsxs("div",{children:[e.jsx("h3",{className:"mb-1.5 font-semibold",children:O.title}),e.jsx("p",{className:"text-sm leading-relaxed text-white/65",children:O.body})]})]},B))})]})}),l.testimonials!==!1&&(s.testimonials||[]).length>0&&e.jsx("section",{className:"py-20 md:py-28",children:e.jsxs("div",{className:"mx-auto max-w-6xl px-6",children:[e.jsx("h2",{className:"mb-12 text-3xl font-bold tracking-tight md:text-4xl",children:"Agents who made the move"}),e.jsx("div",{className:"grid gap-5 md:grid-cols-3",children:(s.testimonials||[]).map((O,B)=>e.jsxs("div",{className:"rounded-2xl border border-white/10 bg-white/[0.03] p-6",children:[e.jsx(ik,{className:"mb-4 h-6 w-6",style:{color:i}}),e.jsxs("p",{className:"text-sm leading-relaxed text-white/75",children:['"',O.quote,'"']}),e.jsxs("div",{className:"mt-5 flex items-center gap-3",children:[O.photo_url?e.jsx("img",{src:O.photo_url,alt:O.name,className:"h-10 w-10 rounded-full object-cover"}):e.jsx("div",{className:"flex h-10 w-10 items-center justify-center rounded-full bg-white/10",children:e.jsx(ri,{className:"h-4 w-4 text-white/50"})}),e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium",children:O.name}),O.role&&e.jsx("div",{className:"text-xs text-white/45",children:O.role})]})]})]},B))})]})}),l.faq!==!1&&(s.faqs||[]).length>0&&e.jsx("section",{className:"border-y border-white/10 bg-white/[0.02] py-20 md:py-28",children:e.jsxs("div",{className:"mx-auto max-w-3xl px-6",children:[e.jsx("h2",{className:"mb-10 text-3xl font-bold tracking-tight md:text-4xl",children:"The questions everyone asks"}),e.jsx(SF,{type:"single",collapsible:!0,className:"w-full",children:(s.faqs||[]).map((O,B)=>e.jsxs(r6,{value:`faq-${B}`,className:"border-white/10",children:[e.jsx(a6,{className:"text-left text-base font-medium text-white hover:no-underline",children:O.q}),e.jsx(i6,{className:"text-sm leading-relaxed text-white/65",children:O.a})]},B))})]})}),l.lead_magnet!==!1&&((I=s.lead_magnet)==null?void 0:I.enabled)!==!1&&((P=s.lead_magnet)==null?void 0:P.title)&&e.jsx("section",{className:"py-20",children:e.jsx("div",{className:"mx-auto max-w-3xl px-6",children:e.jsxs("div",{className:"rounded-3xl border border-white/10 bg-white/[0.04] p-8 md:p-10",children:[e.jsxs("div",{className:"mb-2 flex items-center gap-2 text-xs uppercase tracking-widest",style:{color:i},children:[e.jsx(ji,{className:"h-3.5 w-3.5"})," Free, no strings"]}),e.jsx("h3",{className:"mb-2 text-2xl font-bold",children:s.lead_magnet.title}),e.jsx("p",{className:"mb-6 text-white/65",children:s.lead_magnet.body}),d==="lead_magnet"?e.jsxs("div",{className:"rounded-xl border border-white/15 p-4 text-sm text-white/80",children:["On its way. Check your inbox",s.lead_magnet.file_url?" — or grab it now:":"."," ",s.lead_magnet.file_url&&e.jsx("a",{href:s.lead_magnet.file_url,target:"_blank",rel:"noreferrer",className:"underline",style:{color:i},children:"download"})]}):e.jsxs("form",{className:"flex flex-col gap-3 sm:flex-row",onSubmit:O=>{O.preventDefault(),A("lead_magnet",{first_name:x.first_name,email:x.email,message:`Requested: ${s.lead_magnet.title}`})},children:[e.jsx(be,{required:!0,placeholder:"First name",value:x.first_name,onChange:O=>y(B=>({...B,first_name:O.target.value})),className:"h-12 border-white/15 bg-white/5 text-white placeholder:text-white/35"}),e.jsx(be,{required:!0,type:"email",placeholder:"Email",value:x.email,onChange:O=>y(B=>({...B,email:O.target.value})),className:"h-12 border-white/15 bg-white/5 text-white placeholder:text-white/35"}),e.jsx($,{type:"submit",disabled:h,className:"h-12 shrink-0 font-semibold",style:{backgroundColor:i,color:"#10131c"},children:s.lead_magnet.cta||"Send it"})]})]})})}),l.event!==!1&&((R=s.event_block)==null?void 0:R.title)&&e.jsx("section",{className:"pb-20",children:e.jsx("div",{className:"mx-auto max-w-3xl px-6",children:e.jsxs("div",{className:"flex flex-col items-start justify-between gap-5 rounded-2xl border p-6 md:flex-row md:items-center",style:{borderColor:`${i}55`},children:[e.jsxs("div",{children:[e.jsx("div",{className:"mb-1 text-xs uppercase tracking-widest",style:{color:i},children:"Coming up"}),e.jsx("div",{className:"text-lg font-semibold",children:s.event_block.title}),s.event_block.when&&e.jsx("div",{className:"text-sm text-white/55",children:s.event_block.when})]}),s.event_block.url&&e.jsx("a",{href:s.event_block.url,target:"_blank",rel:"noreferrer",onClick:()=>n==null?void 0:n("cta_click","event"),className:"rounded-full px-6 py-3 text-sm font-semibold",style:{backgroundColor:i,color:"#10131c"},children:"Save my seat"})]})})}),l.final_cta!==!1&&e.jsxs("section",{id:"connect",className:"relative overflow-hidden py-24",children:[e.jsx("div",{className:"absolute inset-0",style:{background:`linear-gradient(200deg, ${a}, #05070d)`}}),e.jsxs("div",{className:"relative z-10 mx-auto max-w-xl px-6",children:[e.jsxs("div",{className:"mb-8 text-center",children:[e.jsx("h2",{className:"mb-3 text-3xl font-bold tracking-tight md:text-4xl",children:"Let's have a confidential conversation"}),e.jsx("p",{className:"text-white/60",children:"No pitch, no pressure. You will get straight answers and your real numbers."})]}),d&&d!=="lead_magnet"?e.jsxs("div",{className:"rounded-3xl border border-white/15 bg-white/5 p-10 text-center",children:[e.jsx("div",{className:"mx-auto mb-4 flex h-12 w-12 items-center justify-center rounded-full",style:{backgroundColor:i,color:"#10131c"},children:e.jsx(ma,{className:"h-6 w-6"})}),e.jsx("h3",{className:"mb-2 text-xl font-semibold",children:"Got it — talk soon."}),e.jsxs("p",{className:"text-white/60",children:[s.agent_name||"I"," will reach out personally.",s.calendar_url&&" Want to skip the wait? Grab a time below."]}),s.calendar_url&&e.jsxs("a",{href:s.calendar_url,target:"_blank",rel:"noreferrer",className:"mt-6 inline-flex items-center gap-2 rounded-full px-6 py-3 text-sm font-semibold",style:{backgroundColor:i,color:"#10131c"},children:[e.jsx(ha,{className:"h-4 w-4"})," Pick a time"]})]}):e.jsxs("form",{onSubmit:O=>{O.preventDefault(),A("attraction_page",p,{gci:_})},className:"space-y-4 rounded-3xl border border-white/10 bg-white/[0.05] p-8 backdrop-blur",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{className:"text-sm text-white/70",children:"First name *"}),e.jsx(be,{required:!0,value:p.first_name,onChange:O=>g(B=>({...B,first_name:O.target.value})),className:"h-11 border-white/15 bg-white/5 text-white"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{className:"text-sm text-white/70",children:"Last name"}),e.jsx(be,{value:p.last_name,onChange:O=>g(B=>({...B,last_name:O.target.value})),className:"h-11 border-white/15 bg-white/5 text-white"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{className:"text-sm text-white/70",children:"Email *"}),e.jsx(be,{required:!0,type:"email",value:p.email,onChange:O=>g(B=>({...B,email:O.target.value})),className:"h-11 border-white/15 bg-white/5 text-white"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{className:"text-sm text-white/70",children:"Phone"}),e.jsx(be,{value:p.phone,onChange:O=>g(B=>({...B,phone:O.target.value})),className:"h-11 border-white/15 bg-white/5 text-white"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{className:"text-sm text-white/70",children:"Current brokerage"}),e.jsx(be,{value:p.brokerage,onChange:O=>g(B=>({...B,brokerage:O.target.value})),className:"h-11 border-white/15 bg-white/5 text-white"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{className:"text-sm text-white/70",children:"What would you want to know?"}),e.jsx(Ls,{rows:3,value:p.message,onChange:O=>g(B=>({...B,message:O.target.value})),className:"resize-none border-white/15 bg-white/5 text-white"})]}),e.jsx($,{type:"submit",disabled:h,className:"h-12 w-full text-base font-semibold",style:{backgroundColor:i,color:"#10131c"},children:h?"Sending…":s.cta_label||"Book a confidential 15-min call"}),e.jsxs("div",{className:"flex items-center justify-center gap-2 pt-1 text-xs text-white/40",children:[e.jsx(Ng,{className:"h-3.5 w-3.5"})," 100% confidential. Never shared with your broker."]})]}),(s.phone||s.email)&&e.jsxs("div",{className:"mt-6 flex flex-wrap justify-center gap-5 text-sm text-white/50",children:[s.phone&&e.jsxs("a",{href:`tel:${s.phone}`,className:"inline-flex items-center gap-2 hover:text-white",children:[e.jsx(ka,{className:"h-4 w-4"})," ",s.phone]}),s.email&&e.jsx("a",{href:`mailto:${s.email}`,className:"hover:text-white",children:s.email})]})]})]}),l.disclaimer!==!1&&s.disclaimer&&e.jsx("footer",{className:"border-t border-white/10 px-6 py-10",children:e.jsx("p",{className:"mx-auto max-w-3xl text-center text-xs leading-relaxed text-white/35",children:s.disclaimer})}),l.final_cta!==!1&&e.jsx("div",{className:"sticky bottom-0 z-40 border-t border-white/10 bg-[#0b0e17]/95 p-3 backdrop-blur md:hidden",children:e.jsxs("a",{href:"#connect",onClick:()=>n==null?void 0:n("cta_click","sticky"),className:"flex items-center justify-center gap-2 rounded-full py-3.5 text-sm font-semibold",style:{backgroundColor:i,color:"#10131c"},children:[s.cta_label||"Book a confidential 15-min call"," ",e.jsx(xi,{className:"h-4 w-4"})]})})]})}const Iie=V;function XKn(){const{slug:s}=oo(),[t,n]=k.useState(null),[r,a]=k.useState("loading");k.useEffect(()=>{if(!s)return;let o=!1;return(async()=>{const{data:c,error:d}=await Iie.rpc("public_get_attract_landing_page",{_slug:s});if(!o){if(d||!c||c.error){a("missing");return}n(c),a("ready"),Iie.rpc("public_track_attract_landing_event",{_slug:s,_event_type:"view",_section_key:null,_metadata:{referrer:document.referrer||null}})}})(),()=>{o=!0}},[s]);const i=(o,c,d)=>{s&&Iie.rpc("public_track_attract_landing_event",{_slug:s,_event_type:o,_section_key:c??null,_metadata:d??{}})},l=async o=>{const{data:c,error:d}=await Iie.rpc("public_submit_attract_landing_lead",{_slug:s,_first_name:o.first_name,_last_name:o.last_name,_email:o.email,_phone:o.phone,_brokerage:o.brokerage,_message:o.message,_source:o.source,_metadata:o.metadata??{}});if(d)throw d;if(c&&c.error)throw new Error(String(c.error))};return r==="loading"?e.jsx("div",{className:"flex min-h-screen items-center justify-center bg-[#0b0e17]",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-white/20 border-t-white"})}):r==="missing"?e.jsxs("div",{className:"flex min-h-screen flex-col items-center justify-center bg-[#0b0e17] px-6 text-center text-white",children:[e.jsx("h1",{className:"mb-2 text-2xl font-semibold",children:"This page isn't available"}),e.jsx("p",{className:"text-white/50",children:"The link may have changed or the page is no longer published."})]}):e.jsxs(e.Fragment,{children:[e.jsxs(Sc,{children:[e.jsx("title",{children:t.seo_title||`${t.agent_name} | Partner with me`}),e.jsx("meta",{name:"description",content:t.seo_description||""}),t.noindex&&e.jsx("meta",{name:"robots",content:"noindex,nofollow"}),e.jsx("meta",{property:"og:title",content:t.seo_title||t.headline||""}),e.jsx("meta",{property:"og:description",content:t.seo_description||t.subheadline||""}),e.jsx("meta",{property:"og:type",content:"website"}),e.jsx("meta",{name:"twitter:card",content:"summary_large_image"})]}),e.jsx(dKt,{cfg:t,onSubmitLead:l,onTrack:i})]})}const yjt={media_mode:"photo",show_property_snapshot:!0,show_discover:!0,show_testimonial:!0};function uKt(s){const t=(s??"").trim();if(!t)return null;const n=t.match(/(?:youtube\.com\/(?:watch\?v=|embed\/|shorts\/)|youtu\.be\/)([\w-]{6,})/);if(n)return{kind:"iframe",src:`https://www.youtube.com/embed/${n[1]}`};const r=t.match(/vimeo\.com\/(?:video\/)?(\d+)/);if(r)return{kind:"iframe",src:`https://player.vimeo.com/video/${r[1]}`};const a=t.match(/loom\.com\/(?:share|embed)\/([\w-]+)/);return a?{kind:"iframe",src:`https://www.loom.com/embed/${a[1]}`}:/\.(mp4|webm|mov|m4v)(\?|$)/i.test(t)?{kind:"file",src:t}:{kind:"iframe",src:t}}const WB=[{id:"fresh_perspective",name:"Fresh Perspective",tagline:"A new set of eyes",description:"Optimistic and forward-looking. Perfect for sellers who are frustrated but still motivated.",accent:"from-sky-500/20 to-sky-500/0",previewHeadline:"A Fresh Look At Your Home",previewBody:"Sometimes all a great home needs is a new perspective — and a plan built for today’s buyer."},{id:"second_chance",name:"Second Chance",tagline:"Empathy first",description:"Warm and human. Acknowledges the disappointment, then pivots to hope and a concrete plan.",accent:"from-amber-500/25 to-amber-500/0",previewHeadline:"Let’s Give Your Home A Second Chance It Deserves",previewBody:"Many great homes don’t sell the first time for reasons that can be fixed with the right strategy."},{id:"luxury_relaunch",name:"Luxury Relaunch",tagline:"Refined & understated",description:"Premium positioning language for higher price points and discerning sellers.",accent:"from-yellow-600/25 to-yellow-600/0",previewHeadline:"A Considered Relaunch For A Distinctive Home",previewBody:"Presentation, positioning and buyer curation — the three levers that move exceptional properties."},{id:"marketing_review",name:"Marketing Review",tagline:"Data forward",description:"Analytical and consultative. Leads with exposure gaps and a marketing scorecard.",accent:"from-emerald-500/22 to-emerald-500/0",previewHeadline:"Your Property Marketing Score",previewBody:"I reviewed your previous listing across six marketing dimensions. Here’s what I found."},{id:"neighborhood_expert",name:"Neighborhood Expert",tagline:"Hyper-local",description:"Leans on local buyer demand and comparable activity in the immediate area.",accent:"from-teal-500/22 to-teal-500/0",previewHeadline:"What’s Really Happening On Your Street",previewBody:"Buyer activity in your neighborhood tells a very different story than the headlines."},{id:"personal_introduction",name:"Personal Introduction",tagline:"Neighbor to neighbor",description:"Conversational and personal — feels like a handwritten note, not a marketing piece.",accent:"from-rose-500/22 to-rose-500/0",previewHeadline:"Hi — I’m Your Neighbor Who Happens To Sell Homes",previewBody:"I noticed your home came off the market and I wanted to reach out personally."},{id:"professional_review",name:"Professional Review",tagline:"Credible & structured",description:"Polished, businesslike and process-driven. Great for analytical sellers.",accent:"from-indigo-500/22 to-indigo-500/0",previewHeadline:"A Professional Review Of Your Previous Listing",previewBody:"A clear, structured assessment — and the exact process I would use to relaunch."}],hKt=[{id:"professional",name:"Professional",note:"Clean structure, confident tone"},{id:"luxury",name:"Luxury",note:"Serif headlines, gold rules, generous space"},{id:"friendly",name:"Friendly",note:"Warm, conversational, approachable"},{id:"minimal",name:"Minimal",note:"Short, direct, nothing extra"},{id:"modern",name:"Modern",note:"Crisp sans type, bold accents"}],QKn=["New Lead","Attempting Contact","Conversation Started","Nurturing","Appointment Requested","Appointment Scheduled","Listing Presentation","Listing Signed","Long Term Follow Up","Lost"],JKn=[{value:"immediately",label:"As soon as possible"},{value:"1-3",label:"In the next 1–3 months"},{value:"3-6",label:"In 3–6 months"},{value:"6-12",label:"In 6–12 months"},{value:"just_curious",label:"Just curious for now"}],eYn=["Not enough showings","No offers","Marketing felt thin","Communication from my agent","Priced too high","Timing / market conditions","Something else"];function tYn(s){return s.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)}function sYn(s){const t=tYn(s)||"property",n=Math.random().toString(36).slice(2,7);return`${t}-${n}`}function $M(s){return s==null?"—":`$${Number(s).toLocaleString("en-US",{maximumFractionDigits:0})}`}const vjt="https://dashboard.relevelup.com";function $qe(){if(typeof window>"u")return vjt;const s=window.location.hostname;return s==="localhost"||s==="127.0.0.1"||s==="dashboard.relevelup.com"?window.location.origin:vjt}function mKt(s){return`${$qe()}/revival/${s}`}const bjt=[Yr,Ul,g0,_h,D8,kn];function _jt(){const s="revival_sid";let t=sessionStorage.getItem(s);return t||(t=Math.random().toString(36).slice(2)+Date.now().toString(36),sessionStorage.setItem(s,t)),t}async function eOe(s){const{data:t,error:n}=await V.functions.invoke("listing-revival-public",{body:s});if(n)throw n;if(t!=null&&t.error)throw new Error(String(t.error));return t}function nYn(){var R,O;const{slug:s=""}=oo(),[t]=Jc(),[n,r]=k.useState(null),[a,i]=k.useState(!0),[l,o]=k.useState(!1),[c,d]=k.useState(!1),u=k.useRef(null),[h,m]=k.useState({first_name:"",last_name:"",email:"",phone:"",still_selling:"",timeline:"",frustration:"",preferred_contact:"email",comments:"",wants_plan:!0,honeypot:""}),p=(B,U)=>m(G=>({...G,[B]:U}));k.useEffect(()=>{let B=!0;return(async()=>{try{const U=await eOe({action:"get",slug:s});if(!B)return;r(U),await eOe({action:"track",slug:s,event_type:t.get("src")==="qr"?"qr_scan":"page_view",session_id:_jt(),metadata:{referrer:document.referrer||null}})}catch{B&&r(null)}finally{B&&i(!1)}})(),()=>{B=!1}},[s,t]);const x=((n==null?void 0:n.campaign.content)??{}).landing,y=(n==null?void 0:n.campaign.landing_config)??{},v=(n==null?void 0:n.property)??((R=n==null?void 0:n.campaign)==null?void 0:R.property),_=n==null?void 0:n.agent,j=y.media_mode??"photo",C=uKt(y.video_url),A=y.media_image_url||(v==null?void 0:v.photo_url)||null;k.useEffect(()=>{v!=null&&v.property_address&&(document.title=`Your Free Property Review — ${v.property_address}`)},[v==null?void 0:v.property_address]);const M=k.useMemo(()=>(x==null?void 0:x.discover)??[],[x]),I=async B=>{if(B.preventDefault(),!(!h.first_name.trim()||!h.email.trim()&&!h.phone.trim())){o(!0);try{await eOe({action:"submit",slug:s,session_id:_jt(),...h}),d(!0),window.scrollTo({top:0,behavior:"smooth"})}catch{o(!1)}}};if(a)return e.jsx("div",{className:"min-h-screen grid place-items-center bg-[#f7f5f1]",children:e.jsx(Jt,{className:"h-6 w-6 animate-spin text-[#0f2540]"})});if(!n)return e.jsx("div",{className:"min-h-screen grid place-items-center bg-[#f7f5f1] px-6 text-center",children:e.jsxs("div",{children:[e.jsx(ua,{className:"h-8 w-8 mx-auto text-[#0f2540]"}),e.jsx("h1",{className:"revival-serif text-2xl mt-3 text-[#0f2540]",children:"This review is no longer available"}),e.jsx("p",{className:"text-[#4a5568] mt-1",children:"The link may have expired. Please reach out to your agent directly."})]})});const P=n.campaign.theme??"estate";return e.jsxs("div",{className:`revival-theme revival-theme-${P} min-h-screen`,children:[e.jsxs("header",{className:"revival-dark relative overflow-hidden",children:[v!=null&&v.photo_url?e.jsx("img",{src:v.photo_url,alt:v.property_address,className:"absolute inset-0 h-full w-full object-cover opacity-25"}):null,e.jsx("div",{className:"relative mx-auto max-w-5xl px-6 py-16 sm:py-24 text-center",children:e.jsxs(_r.div,{initial:{opacity:0,y:18},animate:{opacity:1,y:0},transition:{duration:.6},children:[e.jsx("div",{className:"revival-eyebrow text-accent",children:(x==null?void 0:x.eyebrow)??"A complimentary review"}),e.jsx("h1",{className:"revival-serif text-4xl sm:text-[54px] leading-[1.08] mt-3",children:(x==null?void 0:x.headline)??"Your Free Real Estate Relaunch Review"}),e.jsx("p",{className:"text-white/75 text-lg mt-4 max-w-2xl mx-auto",children:(x==null?void 0:x.subheadline)??"A personalized look at why your home didn’t sell — and exactly what to do next."}),e.jsxs("div",{className:"mt-4 inline-flex items-center gap-2 rounded-full bg-white/10 px-4 py-2 text-sm",children:[e.jsx(ua,{className:"h-4 w-4 text-accent"})," ",v==null?void 0:v.property_address]}),e.jsx("div",{className:"mt-8",children:e.jsx($,{size:"lg",className:"bg-accent text-accent-foreground hover:bg-accent/90",onClick:()=>{var B;return(B=u.current)==null?void 0:B.scrollIntoView({behavior:"smooth"})},children:(x==null?void 0:x.cta)??"Get my free review"})})]})})]}),e.jsxs("main",{className:"mx-auto max-w-5xl px-6 py-14 space-y-14",children:[c?e.jsxs(_r.div,{initial:{opacity:0,scale:.97},animate:{opacity:1,scale:1},className:"revival-tile p-10 text-center",children:[e.jsx(Gr,{className:"h-12 w-12 mx-auto text-accent"}),e.jsx("h2",{className:"revival-serif text-3xl mt-4",children:"Your review is on its way"}),e.jsxs("p",{className:"text-muted-foreground mt-2 max-w-lg mx-auto",children:[(_==null?void 0:_.name)??"Your agent"," has been notified and will personally prepare your Property Revival Plan. Watch your inbox — you’ll hear back shortly."]}),e.jsx($,{className:"mt-6",asChild:!0,children:e.jsx("a",{href:`/revival/${s}/plan`,children:"View your Property Revival Plan"})})]}):null,e.jsxs("section",{className:`grid gap-8 items-center ${j==="none"?"":"lg:grid-cols-2"}`,children:[e.jsxs("div",{children:[e.jsxs("div",{className:"revival-eyebrow text-muted-foreground",children:["A word from ",(_==null?void 0:_.name)??"your agent"]}),e.jsx("p",{className:"mt-3 text-lg leading-relaxed",children:x==null?void 0:x.intro}),_?e.jsxs("div",{className:"mt-6 flex items-center gap-4",children:[_.avatar_url?e.jsx("img",{src:_.avatar_url,alt:_.name??"",className:"h-14 w-14 rounded-full object-cover"}):null,e.jsxs("div",{children:[e.jsx("div",{className:"font-semibold",children:_.name}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[_.title??"Real Estate Specialist",_.brokerage_name?` · ${_.brokerage_name}`:""]})]})]}):null]}),j==="video"&&C?e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"revival-tile aspect-video overflow-hidden",children:C.kind==="file"?e.jsx("video",{src:C.src,controls:!0,playsInline:!0,className:"h-full w-full object-cover"}):e.jsx("iframe",{src:C.src,title:"Agent introduction",className:"h-full w-full",allowFullScreen:!0})}),y.video_caption?e.jsx("p",{className:"text-sm text-muted-foreground text-center",children:y.video_caption}):null]}):j==="photo"&&A?e.jsx("div",{className:"revival-tile aspect-video overflow-hidden",children:e.jsx("img",{src:A,alt:(v==null?void 0:v.property_address)??"Property",className:"h-full w-full object-cover"})}):j!=="none"?e.jsx("div",{className:"revival-tile aspect-video grid place-items-center bg-muted/70",children:e.jsxs("div",{className:"text-center",children:[e.jsx(mm,{className:"h-12 w-12 mx-auto text-accent"}),e.jsxs("p",{className:"text-sm text-muted-foreground mt-2",children:["A personal introduction from ",(_==null?void 0:_.name)??"your agent"]})]})}):null]}),v&&y.show_property_snapshot!==!1?e.jsxs("section",{className:"revival-tile overflow-hidden grid md:grid-cols-[1.1fr_1fr]",children:[v.photo_url?e.jsx("img",{src:v.photo_url,alt:v.property_address,className:"h-full w-full object-cover min-h-[220px]"}):e.jsx("div",{className:"revival-dark min-h-[220px]"}),e.jsxs("div",{className:"p-7",children:[e.jsx("div",{className:"revival-eyebrow text-muted-foreground",children:"Your property"}),e.jsx("h3",{className:"revival-serif text-2xl mt-1",children:v.property_address}),e.jsx("p",{className:"text-muted-foreground",children:[v.city,v.state].filter(Boolean).join(", ")}),e.jsxs("div",{className:"grid grid-cols-3 gap-3 mt-5",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"Original"}),e.jsx("div",{className:"text-lg font-semibold",children:$M(v.original_price)})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"Final"}),e.jsx("div",{className:"text-lg font-semibold",children:$M(v.final_price)})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"Days listed"}),e.jsx("div",{className:"text-lg font-semibold",children:v.days_on_market??"—"})]})]})]})]}):null,M.length&&y.show_discover!==!1?e.jsxs("section",{children:[e.jsx("h2",{className:"revival-serif text-3xl text-center",children:"Inside your free review"}),e.jsx("div",{className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-3 mt-7",children:M.map((B,U)=>{const G=bjt[U%bjt.length];return e.jsxs(_r.div,{initial:{opacity:0,y:18},whileInView:{opacity:1,y:0},viewport:{once:!0},transition:{delay:U*.06,duration:.45},className:"revival-tile p-6",children:[e.jsx("div",{className:"h-11 w-11 rounded-xl bg-accent/15 grid place-items-center",children:e.jsx(G,{className:"h-5 w-5 text-accent-foreground"})}),e.jsx("div",{className:"font-semibold mt-3",children:B.title}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1 leading-relaxed",children:B.body})]},U)})})]}):null,(O=x==null?void 0:x.testimonial)!=null&&O.quote&&y.show_testimonial!==!1?e.jsxs("section",{className:"revival-dark rounded-3xl p-10 text-center",children:[e.jsxs("p",{className:"revival-serif text-2xl leading-relaxed max-w-3xl mx-auto",children:["“",x.testimonial.quote,"”"]}),e.jsx("p",{className:"text-accent text-sm mt-4 uppercase tracking-[0.2em]",children:x.testimonial.author})]}):null,e.jsxs("section",{ref:u,className:"revival-tile p-7 sm:p-10",children:[e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"revival-eyebrow text-muted-foreground",children:"No obligation, no pressure"}),e.jsx("h2",{className:"revival-serif text-3xl mt-1",children:"Request your free review"}),e.jsx("p",{className:"text-muted-foreground mt-2",children:"Takes 60 seconds. Your information is never shared."})]}),e.jsxs("form",{onSubmit:I,className:"grid gap-4 sm:grid-cols-2 mt-7 max-w-2xl mx-auto",children:[e.jsx("input",{type:"text",tabIndex:-1,autoComplete:"off",className:"hidden",value:h.honeypot,onChange:B=>p("honeypot",B.target.value)}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"First name *"}),e.jsx(be,{required:!0,value:h.first_name,onChange:B=>p("first_name",B.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Last name"}),e.jsx(be,{value:h.last_name,onChange:B=>p("last_name",B.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Email"}),e.jsx(be,{type:"email",value:h.email,onChange:B=>p("email",B.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Phone"}),e.jsx(be,{value:h.phone,onChange:B=>p("phone",B.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Are you still interested in selling?"}),e.jsxs(bs,{value:h.still_selling,onValueChange:B=>p("still_selling",B),children:[e.jsx(ys,{children:e.jsx(_s,{placeholder:"Select one"})}),e.jsxs(vs,{children:[e.jsx(We,{value:"yes",children:"Yes"}),e.jsx(We,{value:"maybe",children:"Maybe — depends on the plan"}),e.jsx(We,{value:"no",children:"Not right now"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Your timeline"}),e.jsxs(bs,{value:h.timeline,onValueChange:B=>p("timeline",B),children:[e.jsx(ys,{children:e.jsx(_s,{placeholder:"Select one"})}),e.jsx(vs,{children:JKn.map(B=>e.jsx(We,{value:B.value,children:B.label},B.value))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Biggest frustration last time"}),e.jsxs(bs,{value:h.frustration,onValueChange:B=>p("frustration",B),children:[e.jsx(ys,{children:e.jsx(_s,{placeholder:"Select one"})}),e.jsx(vs,{children:eYn.map(B=>e.jsx(We,{value:B,children:B},B))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Preferred contact method"}),e.jsxs(bs,{value:h.preferred_contact,onValueChange:B=>p("preferred_contact",B),children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"email",children:"Email"}),e.jsx(We,{value:"phone",children:"Phone call"}),e.jsx(We,{value:"text",children:"Text message"})]})]})]}),e.jsxs("div",{className:"sm:col-span-2 space-y-1.5",children:[e.jsx(re,{children:"Anything you'd like me to know?"}),e.jsx(Ls,{rows:3,value:h.comments,onChange:B=>p("comments",B.target.value)})]}),e.jsxs("label",{className:"sm:col-span-2 flex items-center gap-3 text-sm",children:[e.jsx(Li,{checked:h.wants_plan,onCheckedChange:B=>p("wants_plan",!!B)}),"Send me the full Property Revival Plan for my home"]}),e.jsx("div",{className:"sm:col-span-2",children:e.jsx($,{type:"submit",size:"lg",className:"w-full bg-accent text-accent-foreground hover:bg-accent/90",disabled:l,children:l?e.jsxs(e.Fragment,{children:[e.jsx(Jt,{className:"h-4 w-4 mr-2 animate-spin"})," Sending…"]}):(x==null?void 0:x.cta)??"Get my free review"})})]})]})]}),e.jsxs("footer",{className:"revival-dark py-10 text-center",children:[e.jsx("div",{className:"text-lg font-semibold",children:_==null?void 0:_.name}),e.jsx("div",{className:"text-accent text-sm",children:(_==null?void 0:_.title)??"Real Estate Specialist"}),e.jsx("div",{className:"text-white/60 text-sm mt-2",children:[_==null?void 0:_.phone,_==null?void 0:_.email].filter(Boolean).join(" · ")}),_!=null&&_.brokerage_name?e.jsx("div",{className:"text-white/40 text-xs mt-3",children:_.brokerage_name}):null]})]})}const bw="#0f2540",RS="#c9a227";function uW({children:s,className:t,footer:n,page:r}){return e.jsxs("div",{"data-revival-plan-page":"",className:Ot("revival-plan-page relative mx-auto w-full max-w-[816px] bg-white text-[#1a2230]","aspect-[8.5/11] overflow-hidden flex flex-col shadow-[0_30px_70px_-40px_rgba(15,37,64,.6)]",t),children:[s,n!==void 0?e.jsxs("div",{className:"absolute bottom-0 inset-x-0 flex items-center justify-between px-10 pb-6 text-[10px] tracking-[0.22em] uppercase text-[#0f2540]/45",children:[e.jsx("span",{children:n}),r?e.jsx("span",{children:String(r).padStart(2,"0")}):null]}):null]})}function Lie({eyebrow:s,title:t}){return e.jsxs("div",{children:[e.jsx("div",{className:"text-[10.5px] tracking-[0.28em] uppercase font-bold",style:{color:RS},children:s}),e.jsx("h2",{className:"revival-serif text-[30px] leading-tight mt-1",style:{color:bw},children:t}),e.jsx("div",{className:"mt-3 h-[3px] w-14 rounded-full",style:{background:RS}})]})}function rYn({label:s,value:t}){const n=Math.max(0,Math.min(5,Number(t)||0));return e.jsxs("div",{className:"rounded-xl border border-[#0f2540]/12 px-4 py-3",children:[e.jsxs("div",{className:"flex items-baseline justify-between",children:[e.jsx("span",{className:"text-[12.5px] font-semibold capitalize",style:{color:bw},children:s.replace(/_/g," ")}),e.jsxs("span",{className:"text-[12px] tabular-nums text-[#0f2540]/60",children:[n," ",e.jsx("span",{className:"text-[10px]",children:"/ 5"})]})]}),e.jsx("div",{className:"mt-2 flex gap-1",children:[1,2,3,4,5].map(r=>e.jsx("span",{className:"h-[6px] flex-1 rounded-full",style:{background:r<=n?RS:"rgba(15,37,64,.10)"}},r))})]})}function Uqe({plan:s,property:t,agent:n,url:r,className:a}){var u,h,m;const i=t.property_address??"Your Property",l=[t.city,t.state].filter(Boolean).join(", "),o=Object.entries((s==null?void 0:s.scores)??{}),c=(s==null?void 0:s.strategy_weeks)??[],d=n.name?`${n.name} · Property Revival Plan`:"Property Revival Plan";return e.jsxs("div",{className:Ot("space-y-8",a),children:[e.jsxs(uW,{children:[e.jsxs("div",{className:"relative h-[52%] overflow-hidden",style:{background:bw},children:[t.photo_url?e.jsx("img",{src:t.photo_url,alt:i,className:"absolute inset-0 h-full w-full object-cover opacity-55"}):null,e.jsx("div",{className:"absolute inset-0",style:{background:`linear-gradient(180deg, rgba(15,37,64,.35), ${bw})`}}),e.jsxs("div",{className:"relative h-full flex flex-col justify-end px-12 pb-9 text-white",children:[n.brokerage_name?e.jsx("div",{className:"text-[10.5px] tracking-[0.3em] uppercase text-white/70 font-bold",children:n.brokerage_name}):null,e.jsxs("div",{className:"text-[11px] tracking-[0.3em] uppercase font-bold mt-3",style:{color:RS},children:["Prepared exclusively for ",t.seller_name||"you"]}),e.jsx("h1",{className:"revival-serif text-[46px] leading-[1.05] mt-2",children:"Property Revival Plan"}),e.jsxs("p",{className:"text-white/80 mt-2 text-[15px]",children:[i,l?` · ${l}`:""]})]})]}),e.jsxs("div",{className:"flex-1 px-12 pt-8 flex flex-col",children:[e.jsx("div",{className:"grid grid-cols-3 gap-4",children:[{k:"Original price",v:$M(t.original_price)},{k:"Final price",v:$M(t.final_price)},{k:"Days on market",v:t.days_on_market??"—"}].map(p=>e.jsxs("div",{className:"rounded-xl border border-[#0f2540]/12 px-4 py-4 text-center",children:[e.jsx("div",{className:"text-[9.5px] tracking-[0.22em] uppercase text-[#0f2540]/50",children:p.k}),e.jsx("div",{className:"text-[20px] font-bold mt-1",style:{color:bw},children:p.v})]},p.k))}),s!=null&&s.intro?e.jsx("p",{className:"mt-7 text-[14.5px] leading-7 text-[#28313f]",children:s.intro}):null,e.jsxs("div",{className:"mt-auto mb-12 flex items-center gap-5 border-t border-[#0f2540]/10 pt-6",children:[n.avatar_url?e.jsx("img",{src:n.avatar_url,alt:n.name??"",className:"h-[74px] w-[74px] rounded-full object-cover"}):null,e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"text-[17px] font-bold",style:{color:bw},children:n.name}),e.jsxs("div",{className:"text-[12px] text-[#0f2540]/60",children:[n.title??"Real Estate Specialist",n.brokerage_name?` · ${n.brokerage_name}`:""]}),e.jsx("div",{className:"text-[12px] text-[#0f2540]/70 mt-1",children:[n.phone,n.email].filter(Boolean).join(" · ")})]}),r?e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"rounded-lg border border-[#0f2540]/15 p-2 bg-white",children:e.jsx(jk,{value:r,size:64,level:"M",fgColor:bw})}),e.jsx("div",{className:"text-[8.5px] tracking-[0.18em] uppercase text-[#0f2540]/45 mt-1",children:"View online"})]}):null]})]})]}),o.length?e.jsx(uW,{footer:d,page:2,children:e.jsxs("div",{className:"px-12 pt-12 flex-1 flex flex-col",children:[e.jsx(Lie,{eyebrow:"Section One",title:"Marketing scorecard"}),e.jsx("p",{className:"mt-4 text-[14px] leading-7 text-[#28313f]",children:"A review of how the previous listing performed across the six areas that most influence a sale. Each area is rated on a 1–5 scale, where 5 means the listing was doing everything today’s buyers respond to."}),e.jsx("div",{className:"mt-6 grid grid-cols-2 gap-3",children:o.map(([p,g])=>e.jsx(rYn,{label:p,value:Number(g)},p))}),(u=s==null?void 0:s.buyers_experienced)!=null&&u.length?e.jsxs("div",{className:"mt-8",children:[e.jsx("div",{className:"text-[10.5px] tracking-[0.28em] uppercase font-bold",style:{color:RS},children:"What buyers experienced"}),e.jsx("ul",{className:"mt-3 space-y-2",children:s.buyers_experienced.slice(0,5).map((p,g)=>e.jsxs("li",{className:"flex gap-3 text-[13.5px] leading-6 text-[#28313f]",children:[e.jsx("span",{className:"mt-[7px] h-[6px] w-[6px] shrink-0 rounded-full",style:{background:RS}}),p]},g))})]}):null]})}):null,(h=s==null?void 0:s.differently)!=null&&h.length?e.jsx(uW,{footer:d,page:3,children:e.jsxs("div",{className:"px-12 pt-12 flex-1 flex flex-col",children:[e.jsx(Lie,{eyebrow:"Section Two",title:"What we would do differently"}),e.jsxs("p",{className:"mt-4 text-[14px] leading-7 text-[#28313f]",children:["Every point below is part of the plan for ",i," — not a general list."]}),e.jsx("div",{className:"mt-6 grid grid-cols-2 gap-3",children:s.differently.slice(0,10).map((p,g)=>e.jsxs("div",{className:"rounded-xl border border-[#0f2540]/12 px-4 py-3 flex gap-3",children:[e.jsx("span",{className:"h-[22px] w-[22px] shrink-0 rounded-full grid place-items-center text-[11px] font-bold text-white",style:{background:bw},children:g+1}),e.jsx("span",{className:"text-[13px] leading-6 text-[#28313f]",children:p})]},g))})]})}):null,c.length?e.jsx(uW,{footer:d,page:4,children:e.jsxs("div",{className:"px-12 pt-12 flex-1 flex flex-col",children:[e.jsx(Lie,{eyebrow:"Section Three",title:"Your relaunch strategy"}),e.jsxs("p",{className:"mt-4 text-[14px] leading-7 text-[#28313f]",children:["A week-by-week plan for bringing ",i," back to market with momentum."]}),e.jsx("div",{className:"mt-6 space-y-3",children:c.slice(0,5).map((p,g)=>e.jsxs("div",{className:"rounded-xl border border-[#0f2540]/12 p-5 flex gap-5",children:[e.jsx("div",{className:"h-11 w-11 shrink-0 rounded-xl grid place-items-center text-white font-bold",style:{background:bw},children:g+1}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[10px] tracking-[0.26em] uppercase font-bold",style:{color:RS},children:p.week}),e.jsx("div",{className:"text-[16px] font-semibold mt-0.5",style:{color:bw},children:p.title}),e.jsx("p",{className:"text-[13px] leading-6 text-[#28313f] mt-1",children:p.body})]})]},g))})]})}):null,e.jsx(uW,{footer:d,page:5,children:e.jsxs("div",{className:"px-12 pt-12 flex-1 flex flex-col",children:[e.jsx(Lie,{eyebrow:"Section Four",title:"Your next steps"}),(m=s==null?void 0:s.questions)!=null&&m.length?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mt-5 text-[10.5px] tracking-[0.28em] uppercase font-bold",style:{color:RS},children:"Questions to ask any agent"}),e.jsx("ol",{className:"mt-3 space-y-2",children:s.questions.slice(0,6).map((p,g)=>e.jsxs("li",{className:"flex gap-3 text-[13.5px] leading-6 text-[#28313f]",children:[e.jsxs("span",{className:"text-[12px] font-bold tabular-nums",style:{color:bw},children:[g+1,"."]}),p]},g))})]}):null,e.jsxs("div",{className:"mt-8 rounded-2xl p-8 text-white",style:{background:bw},children:[e.jsx("div",{className:"text-[10.5px] tracking-[0.28em] uppercase font-bold",style:{color:RS},children:"An invitation"}),e.jsx("p",{className:"mt-3 text-[14.5px] leading-7 text-white/85",children:(s==null?void 0:s.invitation)??"Let’s walk through this plan together — no pressure, just helpful guidance."}),e.jsxs("div",{className:"mt-6 flex items-center gap-5",children:[n.avatar_url?e.jsx("img",{src:n.avatar_url,alt:n.name??"",className:"h-[64px] w-[64px] rounded-full object-cover"}):null,e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"text-[16px] font-bold",children:n.name}),e.jsx("div",{className:"text-[12px] text-white/60",children:n.title??"Real Estate Specialist"}),e.jsx("div",{className:"text-[12.5px] mt-1",style:{color:RS},children:[n.phone,n.email,n.website_url].filter(Boolean).join(" · ")})]}),r?e.jsx("div",{className:"rounded-lg bg-white p-2",children:e.jsx(jk,{value:r,size:60,level:"M",fgColor:bw})}):null]})]})]})})]})}const hW=[15,37,64],tOe=[201,162,39],wjt=[31,41,55],Rie=[107,114,128];async function aYn(s,t=8){return ZV.toDataURL(s,{margin:0,scale:t,color:{dark:"#0f2540",light:"#ffffff"}})}function iYn(s){return[s.title,s.brokerage_name,s.phone,s.email,s.website_url].filter(Boolean).map(String)}function bJe(s){return s.replace(/[^a-z0-9]+/gi,"-").replace(/^-+|-+$/g,"").toLowerCase().slice(0,60)}async function oYn(s){const{campaign:t,agent:n,url:r,photoDataUrl:a}=s,i=t.property,l=new Oo({unit:"pt",format:[648,432],orientation:"landscape"}),o=648,c=432;if(l.setFillColor(...hW),l.rect(0,0,o,c,"F"),a)try{l.addImage(a,"JPEG",0,0,o,c*.62)}catch{}l.setFillColor(...hW),l.rect(0,c*.6,o,c*.4,"F"),l.setFillColor(...tOe),l.rect(0,c*.6-4,o,4,"F"),l.setTextColor(...tOe),l.setFont("helvetica","bold"),l.setFontSize(9),l.text("LISTING REVIVAL",44,c*.6+34),l.setTextColor(255,255,255),l.setFont("times","normal"),l.setFontSize(28),l.text(l.splitTextToSize(s.headline??"Your home deserves a second chance.",o-88),44,c*.6+68),l.setFont("helvetica","normal"),l.setFontSize(11),l.setTextColor(220,224,232),l.text(l.splitTextToSize(s.subhead??`A complimentary marketing review for ${(i==null?void 0:i.property_address)??"your property"}.`,o-88),44,c*.6+118),l.addPage([648,432],"landscape"),l.setFillColor(255,255,255),l.rect(0,0,o,c,"F"),l.setFillColor(...hW),l.rect(0,0,10,c,"F");const d=44;l.setTextColor(...hW),l.setFont("times","normal"),l.setFontSize(19),l.text(n.name??"",d,54),l.setFont("helvetica","normal"),l.setFontSize(9),l.setTextColor(...Rie),l.text(iYn(n).join(" · "),d,72,{maxWidth:o/2+40}),l.setDrawColor(...tOe),l.setLineWidth(1),l.line(d,88,o/2+60,88),l.setTextColor(...wjt),l.setFont("times","normal"),l.setFontSize(11.5);const u=s.message??`I noticed ${(i==null?void 0:i.property_address)??"your home"} recently came off the market. I put together a private, no-obligation review of what buyers saw — and exactly what I would do differently to get it sold. Scan the code and it's yours in seconds.`;l.text(l.splitTextToSize(u,o/2+16),d,112);const h=await aYn(r);l.addImage(h,"PNG",d,c-150,108,108),l.setFont("helvetica","bold"),l.setFontSize(10),l.setTextColor(...hW),l.text("Scan for your free review",d+122,c-112),l.setFont("helvetica","normal"),l.setFontSize(8.5),l.setTextColor(...Rie),l.text(r,d+122,c-96,{maxWidth:220});const m=o/2+96;l.setDrawColor(210,214,220),l.setLineWidth(.7),l.rect(m,132,o-m-44,116),l.setFontSize(8),l.setTextColor(...Rie),l.text("MAILING ADDRESS",m+10,126),l.setFontSize(11),l.setTextColor(...wjt),[(i==null?void 0:i.seller_name)??"Current Resident",(i==null?void 0:i.mailing_address)??(i==null?void 0:i.property_address)??"",[(i==null?void 0:i.mailing_city)??(i==null?void 0:i.city),(i==null?void 0:i.mailing_state)??(i==null?void 0:i.state),(i==null?void 0:i.mailing_zip)??(i==null?void 0:i.zip)].filter(Boolean).join(", ")].filter(Boolean).forEach((g,x)=>l.text(String(g),m+14,162+x*18,{maxWidth:o-m-72})),l.setDrawColor(210,214,220),l.rect(o-118,40,74,62),l.setFontSize(7.5),l.setTextColor(...Rie),l.text("POSTAGE",o-96,74),l.save(`revival-postcard-${bJe((i==null?void 0:i.property_address)??t.name)}.pdf`)}async function fKt(s){try{const n=await(await fetch(s,{mode:"cors"})).blob();return await new Promise(r=>{const a=new FileReader;a.onloadend=()=>r(String(a.result)),a.onerror=()=>r(null),a.readAsDataURL(n)})}catch{return null}}async function lYn(s,t){const{toPng:n}=await Ai(async()=>{const{toPng:d}=await Promise.resolve().then(()=>eRt);return{toPng:d}},void 0),r=Array.from(s.querySelectorAll("img")),a=r.map(d=>d.getAttribute("src")??"");await Promise.all(r.map(async(d,u)=>{const h=a[u];if(!h||h.startsWith("data:"))return;const m=await fKt(h);m&&d.setAttribute("src",m)}));let i;try{i=await n(s,{pixelRatio:3,cacheBust:!0,backgroundColor:"#ffffff",width:s.offsetWidth,height:s.offsetHeight})}finally{r.forEach((d,u)=>{a[u]&&d.setAttribute("src",a[u])})}const l=new Oo({unit:"pt",format:"letter",compress:!0}),o=l.internal.pageSize.getWidth(),c=l.internal.pageSize.getHeight();l.addImage(i,"PNG",0,0,o,c,void 0,"FAST"),l.save(`revival-letter-${bJe(t)}.pdf`)}async function pKt(s,t){const{toPng:n}=await Ai(async()=>{const{toPng:d}=await Promise.resolve().then(()=>eRt);return{toPng:d}},void 0),r=Array.from(s.querySelectorAll("[data-revival-plan-page]"));if(!r.length)return;const a=Array.from(s.querySelectorAll("img")),i=a.map(d=>d.getAttribute("src")??"");await Promise.all(a.map(async(d,u)=>{const h=i[u];if(!h||h.startsWith("data:"))return;const m=await fKt(h);m&&d.setAttribute("src",m)}));const l=new Oo({unit:"pt",format:"letter",compress:!0}),o=l.internal.pageSize.getWidth(),c=l.internal.pageSize.getHeight();try{for(let d=0;d0&&l.addPage(),l.addImage(h,"PNG",0,0,o,c,void 0,"FAST")}}finally{a.forEach((d,u)=>{i[u]&&d.setAttribute("src",i[u])})}l.save(`revival-plan-${bJe(t)}.pdf`)}function jjt(){var m,p,g;const{slug:s=""}=oo(),[t,n]=k.useState(null),[r,a]=k.useState(!0),[i,l]=k.useState(!1),o=k.useRef(null),c=((m=t==null?void 0:t.campaign)==null?void 0:m.property)??(t==null?void 0:t.property)??null,d=async()=>{if(o.current){l(!0);try{await pKt(o.current,(c==null?void 0:c.property_address)??"plan")}finally{l(!1)}}};if(k.useEffect(()=>{let x=!0;return(async()=>{try{const{data:y,error:v}=await V.functions.invoke("listing-revival-public",{body:{action:"get",slug:s}});if(v)throw v;if(!x)return;n(y),await V.functions.invoke("listing-revival-public",{body:{action:"track",slug:s,event_type:"plan_view"}})}catch{x&&n(null)}finally{x&&a(!1)}})(),()=>{x=!1}},[s]),k.useEffect(()=>{c!=null&&c.property_address&&(document.title=`Property Revival Plan — ${c.property_address}`)},[c==null?void 0:c.property_address]),r)return e.jsx("div",{className:"min-h-screen grid place-items-center bg-[#f7f5f1]",children:e.jsx(Jt,{className:"h-6 w-6 animate-spin text-[#0f2540]"})});if(!t||!((g=(p=t.campaign)==null?void 0:p.content)!=null&&g.plan))return e.jsx("div",{className:"min-h-screen grid place-items-center bg-[#f7f5f1] px-6 text-center",children:e.jsxs("div",{children:[e.jsx(ua,{className:"h-8 w-8 mx-auto text-[#0f2540]"}),e.jsx("h1",{className:"revival-serif text-2xl mt-3 text-[#0f2540]",children:"This plan is no longer available"})]})});const{agent:u}=t,h=t.campaign.content.plan;return e.jsxs("div",{className:`revival-theme revival-theme-${t.campaign.theme??"estate"} min-h-screen bg-[#f7f5f1]`,children:[e.jsxs("div",{className:"mx-auto max-w-[900px] px-4 sm:px-6 py-8 sm:py-12",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3 mb-6",children:[e.jsxs("div",{className:"revival-eyebrow text-[#0f2540]/60",children:["Prepared for ",(c==null?void 0:c.property_address)??"your home"]}),e.jsxs("button",{onClick:d,disabled:i,className:"inline-flex items-center gap-2 rounded-full bg-[#0f2540] text-white px-5 py-2.5 text-sm font-semibold disabled:opacity-60",children:[i?e.jsx(Jt,{className:"h-4 w-4 animate-spin"}):e.jsx(ji,{className:"h-4 w-4"}),"Download PDF"]})]}),e.jsx("div",{ref:o,children:e.jsx(Uqe,{plan:h,property:c??{property_address:"",city:null,state:null,photo_url:null,original_price:null,final_price:null,days_on_market:null},agent:u})}),u!=null&&u.phone||u!=null&&u.email?e.jsxs("div",{className:"mt-10 flex flex-wrap justify-center gap-3",children:[u.phone?e.jsxs("a",{href:`tel:${u.phone}`,className:"rounded-full bg-[#c9a227] text-[#0f2540] px-6 py-3 font-semibold",children:["Call ",u.phone]}):null,u.email?e.jsxs("a",{href:`mailto:${u.email}`,className:"rounded-full border border-[#0f2540]/25 text-[#0f2540] px-6 py-3 font-semibold",children:["Email ",u.name]}):null]}):null]}),e.jsxs("footer",{className:"py-10 text-center border-t border-border",children:[u!=null&&u.avatar_url?e.jsx("img",{src:u.avatar_url,alt:u.name??"",className:"h-16 w-16 rounded-full object-cover mx-auto"}):null,e.jsx("div",{className:"text-lg font-semibold mt-3",children:u==null?void 0:u.name}),e.jsx("div",{className:"text-sm text-muted-foreground",children:(u==null?void 0:u.title)??"Real Estate Specialist"}),u!=null&&u.brokerage_name?e.jsx("div",{className:"text-xs text-muted-foreground mt-2",children:u.brokerage_name}):null]})]})}function cYn(){const{user:s}=ks();return pt({queryKey:["revival-campaigns",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await V.from("listing_revival_campaigns").select("*, property:listing_revival_properties(*)").order("created_at",{ascending:!1});if(n)throw n;return t??[]}})}function dYn(s){return pt({queryKey:["revival-campaign",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await V.from("listing_revival_campaigns").select("*, property:listing_revival_properties(*)").eq("id",s).maybeSingle();if(n)throw n;return t??null}})}function uYn(){const{user:s}=ks();return pt({queryKey:["revival-properties",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await V.from("listing_revival_properties").select("*").order("created_at",{ascending:!1});if(n)throw n;return t??[]}})}function gKt(){const{user:s}=ks();return pt({queryKey:["revival-leads",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await V.from("listing_revival_leads").select("*").order("created_at",{ascending:!1});if(n)throw n;return t??[]}})}function hYn(){const{user:s}=ks();return pt({queryKey:["revival-tasks",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await V.from("listing_revival_tasks").select("*").order("due_date",{ascending:!0});if(n)throw n;return t??[]}})}function xKt(){const{user:s}=ks();return pt({queryKey:["revival-events",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await V.from("listing_revival_events").select("*").order("created_at",{ascending:!1}).limit(1e3);if(n)throw n;return t??[]}})}function _Je(){const s=ls(),t=()=>{["revival-campaigns","revival-campaign","revival-properties","revival-leads","revival-tasks","revival-events"].forEach(o=>s.invalidateQueries({queryKey:[o]}))},n=Nt({mutationFn:async o=>{const{data:c,error:d}=await V.functions.invoke("listing-revival-generate",{body:o});if(d)throw d;if(c!=null&&c.error)throw new Error(String(c.error));return c},onSuccess:t,onError:o=>ae.error(o.message)}),r=Nt({mutationFn:async o=>{const{error:c}=await V.from("listing_revival_campaigns").update(o.patch).eq("id",o.id);if(c)throw c},onSuccess:()=>{t(),ae.success("Saved")},onError:o=>ae.error(o.message)}),a=Nt({mutationFn:async o=>{const{error:c}=await V.from("listing_revival_campaigns").delete().eq("id",o);if(c)throw c},onSuccess:()=>{t(),ae.success("Campaign deleted")},onError:o=>ae.error(o.message)}),i=Nt({mutationFn:async o=>{const{error:c}=await V.from("listing_revival_campaigns").update({status:o.archived?"archived":"active",published:!o.archived}).eq("id",o.id);if(c)throw c;return o},onSuccess:o=>{t(),ae.success(o.archived?"Campaign archived":"Campaign restored")},onError:o=>ae.error(o.message)}),l=Nt({mutationFn:async o=>{const{error:c}=await V.from("listing_revival_tasks").update({completed_at:o.done?new Date().toISOString():null}).eq("id",o.id);if(c)throw c},onSuccess:t,onError:o=>ae.error(o.message)});return{generate:n,saveCampaign:r,deleteCampaign:a,archiveCampaign:i,toggleTask:l,invalidate:t}}const mYn=[{id:"dashboard",label:"Dashboard",icon:zp},{id:"campaigns",label:"Campaigns",icon:kn},{id:"properties",label:"Properties",icon:ua},{id:"letters",label:"Letters",icon:pn},{id:"landing",label:"Landing Pages",icon:kc},{id:"plans",label:"Revival Plans",icon:ea},{id:"followup",label:"Follow Up",icon:lv},{id:"analytics",label:"Analytics",icon:Ul},{id:"templates",label:"Templates",icon:Zw},{id:"settings",label:"Settings",icon:eM}];function Yb({label:s,value:t,icon:n,delay:r=0,hint:a}){return e.jsxs(_r.div,{initial:{opacity:0,y:14},animate:{opacity:1,y:0},transition:{delay:r,duration:.45,ease:[.22,1,.36,1]},className:"revival-tile p-5",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsx("span",{className:"revival-eyebrow text-muted-foreground",children:s}),e.jsx(n,{className:"h-4 w-4 text-accent"})]}),e.jsx("div",{className:"mt-3 text-3xl font-bold tabular-nums tracking-tight",children:t}),a?e.jsx("div",{className:"text-xs text-muted-foreground mt-1",children:a}):null]})}function fYn(){const s=Jn(),[t,n]=k.useState("dashboard"),[r,a]=k.useState(""),[i,l]=k.useState(!1),[o,c]=k.useState(null);X8n();const d=cYn(),u=uYn(),h=gKt(),m=hYn(),p=xKt(),{toggleTask:g,archiveCampaign:x,deleteCampaign:y}=_Je(),v=d.data??[],_=h.data??[],j=p.data??[],C=m.data??[],A=k.useMemo(()=>{const G=H=>j.filter(Y=>Y.event_type===H).length;return{properties:(u.data??[]).length,campaigns:v.length,letters:v.filter(H=>{var Y;return(Y=H.content)==null?void 0:Y.letter}).length,qr:G("qr_scan"),visits:G("page_view"),planViews:G("plan_view"),leads:_.length,appointments:G("appointment"),won:_.filter(H=>H.stage==="listing_signed").length,hot:_.filter(H=>H.temperature==="hot").length}},[v,_,j,u.data]),M=k.useMemo(()=>{const G=[];for(let H=13;H>=0;H--){const Y=new Date(Date.now()-H*864e5),se=Y.toISOString().slice(0,10);G.push({day:Ys(Y,"MMM d"),visits:j.filter(ee=>ee.event_type==="page_view"&&ee.created_at.startsWith(se)).length,scans:j.filter(ee=>ee.event_type==="qr_scan"&&ee.created_at.startsWith(se)).length,leads:_.filter(ee=>ee.created_at.startsWith(se)).length})}return G},[j,_]),I=G=>G.status==="archived",P=v.filter(G=>{var Y,se;if(i?!I(G):I(G))return!1;const H=r.trim().toLowerCase();return H?`${G.name} ${((Y=G.property)==null?void 0:Y.property_address)??""} ${((se=G.property)==null?void 0:se.seller_name)??""}`.toLowerCase().includes(H):!0}),R=v.filter(I).length,O=G=>s(`/apps/listing-revival/campaigns/${G}`),B=G=>{navigator.clipboard.writeText(mKt(G)),ae.success("Landing page link copied")},U=G=>e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs("div",{className:"relative max-w-sm flex-1 min-w-[200px]",children:[e.jsx(Yr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{value:r,onChange:H=>a(H.target.value),placeholder:"Search campaigns…",className:"pl-9"})]}),e.jsxs($,{variant:i?"default":"outline",size:"sm",onClick:()=>l(H=>!H),children:[e.jsx(kf,{className:"h-3.5 w-3.5 mr-1.5"}),i?"Viewing archived":`Archived (${R})`]})]}),P.length===0?e.jsx("div",{className:"revival-tile p-10 text-center text-muted-foreground",children:i?"No archived campaigns.":G}):e.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:P.map((H,Y)=>{var Q,te,le,fe;const se=WB.find(_e=>_e.id===H.style),ee=_.filter(_e=>_e.campaign_id===H.id).length,oe=j.filter(_e=>_e.campaign_id===H.id&&_e.event_type==="page_view").length,me=I(H);return e.jsxs(_r.div,{initial:{opacity:0,y:14},animate:{opacity:1,y:0},transition:{delay:Math.min(Y*.04,.3),duration:.4},className:Ot("revival-tile overflow-hidden",me&&"opacity-80"),children:[e.jsxs("div",{className:"h-28 bg-muted relative",children:[(Q=H.property)!=null&&Q.photo_url?e.jsx("img",{src:H.property.photo_url,alt:H.property.property_address??"",className:"h-full w-full object-cover",loading:"lazy"}):e.jsx("div",{className:"h-full w-full revival-dark grid place-items-center",children:e.jsx(ua,{className:"h-7 w-7 text-accent"})}),e.jsx(qe,{className:"absolute top-3 left-3 bg-background/90 text-foreground border-0",children:(se==null?void 0:se.name)??H.style}),me?e.jsx(qe,{className:"absolute top-3 right-3 bg-foreground/85 text-background border-0",children:"Archived"}):null]}),e.jsxs("div",{className:"p-4",children:[e.jsx("div",{className:"font-semibold leading-tight",children:((te=H.property)==null?void 0:te.property_address)??H.name}),e.jsx("div",{className:"text-sm text-muted-foreground",children:((le=H.property)==null?void 0:le.seller_name)??"Homeowner"}),e.jsxs("div",{className:"mt-3 flex items-center gap-4 text-xs text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(kc,{className:"h-3.5 w-3.5"}),oe]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Xn,{className:"h-3.5 w-3.5"}),ee]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ua,{className:"h-3.5 w-3.5"}),((fe=H.property)==null?void 0:fe.days_on_market)??"—"," DOM"]})]}),e.jsxs("div",{className:"mt-4 flex gap-2",children:[e.jsxs($,{size:"sm",className:"flex-1",onClick:()=>O(H.id),children:["Open ",e.jsx(xi,{className:"h-3.5 w-3.5 ml-1"})]}),e.jsx($,{size:"sm",variant:"outline",onClick:()=>B(H.slug),children:e.jsx(Da,{className:"h-3.5 w-3.5"})}),e.jsx($,{size:"sm",variant:"outline",asChild:!0,children:e.jsx("a",{href:`/revival/${H.slug}`,target:"_blank",rel:"noreferrer",children:e.jsx(Ir,{className:"h-3.5 w-3.5"})})}),e.jsxs(Au,{children:[e.jsx(Eu,{asChild:!0,children:e.jsx($,{size:"sm",variant:"outline",children:e.jsx(Z0,{className:"h-3.5 w-3.5"})})}),e.jsxs(gu,{align:"end",children:[e.jsx(Pa,{onClick:()=>x.mutate({id:H.id,archived:!me}),children:me?e.jsxs(e.Fragment,{children:[e.jsx(OT,{className:"h-4 w-4 mr-2"})," Restore campaign"]}):e.jsxs(e.Fragment,{children:[e.jsx(kf,{className:"h-4 w-4 mr-2"})," Archive campaign"]})}),e.jsx(j0,{}),e.jsxs(Pa,{className:"text-destructive focus:text-destructive",onClick:()=>{var _e;return c({id:H.id,name:((_e=H.property)==null?void 0:_e.property_address)??H.name})},children:[e.jsx(Un,{className:"h-4 w-4 mr-2"})," Delete permanently"]})]})]})]})]})]},H.id)})}),e.jsx(oc,{open:!!o,onOpenChange:H=>!H&&c(null),children:e.jsxs(Ql,{children:[e.jsxs(Jl,{children:[e.jsx(tc,{children:"Delete this campaign?"}),e.jsxs(sc,{children:[o==null?void 0:o.name," — the letter, landing page, QR link, plan and follow-up tasks will be permanently removed. This can't be undone. Archive instead if you may need it later."]})]}),e.jsxs(ec,{children:[e.jsx(nc,{children:"Cancel"}),e.jsx(Vl,{className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",onClick:()=>{o&&y.mutate(o.id),c(null)},children:"Delete permanently"})]})]})})]});return e.jsx(Xs,{title:"Listing Revival",children:e.jsxs("div",{className:"revival-theme relative -m-4 sm:-m-6 p-4 sm:p-6 min-h-[calc(100vh-4rem)]",children:[e.jsxs(_r.div,{initial:{opacity:0,y:18},animate:{opacity:1,y:0},transition:{duration:.55,ease:[.22,1,.36,1]},className:"revival-dark rounded-3xl px-6 sm:px-10 py-9 relative overflow-hidden",children:[e.jsx("div",{className:"absolute -right-10 -top-16 h-56 w-56 rounded-full bg-accent/20 blur-3xl"}),e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"revival-eyebrow text-accent",children:"Listing Revival"}),e.jsx("h1",{className:"revival-serif text-3xl sm:text-[42px] leading-tight mt-2 max-w-2xl",children:"Turn Expired Listings Into Listing Appointments."}),e.jsx("p",{className:"text-white/70 mt-3 max-w-xl",children:"Import a property, choose a style, click once. Your letter, QR code, landing page, Property Revival Plan, emails, texts and follow-up tasks are built in under two minutes."}),e.jsxs("div",{className:"mt-6 flex flex-wrap gap-3",children:[e.jsxs($,{size:"lg",className:"bg-accent text-accent-foreground hover:bg-accent/90",onClick:()=>s("/apps/listing-revival/new"),children:[e.jsx(nn,{className:"h-4 w-4 mr-1"})," New Campaign"]}),e.jsx($,{size:"lg",variant:"outline",className:"bg-transparent text-white border-white/25 hover:bg-white/10",onClick:()=>n("campaigns"),children:"View campaigns"})]})]})]}),e.jsxs(ya,{value:t,onValueChange:n,className:"mt-6",children:[e.jsx(va,{className:"flex w-full overflow-x-auto no-scrollbar justify-start bg-transparent p-0 gap-2 h-auto",children:mYn.map(G=>e.jsxs(is,{value:G.id,className:"data-[state=active]:bg-primary data-[state=active]:text-primary-foreground rounded-full border border-border bg-card px-4 py-2 text-sm whitespace-nowrap",children:[e.jsx(G.icon,{className:"h-3.5 w-3.5 mr-1.5"}),G.label]},G.id))}),e.jsxs(cs,{value:"dashboard",className:"mt-6 space-y-6",children:[e.jsxs("div",{className:"grid gap-3 grid-cols-2 lg:grid-cols-5",children:[e.jsx(Yb,{label:"Properties",value:A.properties,icon:ua,delay:0}),e.jsx(Yb,{label:"Campaigns",value:A.campaigns,icon:kn,delay:.04}),e.jsx(Yb,{label:"Letters",value:A.letters,icon:pn,delay:.08}),e.jsx(Yb,{label:"QR Scans",value:A.qr,icon:Bx,delay:.12}),e.jsx(Yb,{label:"Page Visits",value:A.visits,icon:kc,delay:.16}),e.jsx(Yb,{label:"Plans Viewed",value:A.planViews,icon:ea,delay:.2}),e.jsx(Yb,{label:"Seller Leads",value:A.leads,icon:Xn,delay:.24}),e.jsx(Yb,{label:"Appointments",value:A.appointments,icon:fb,delay:.28}),e.jsx(Yb,{label:"Listings Won",value:A.won,icon:ql,delay:.32}),e.jsx(Yb,{label:"Hot Leads",value:A.hot,icon:iu,delay:.36,hint:"Score 75+"})]}),e.jsxs("div",{className:"grid gap-4 lg:grid-cols-3",children:[e.jsxs("div",{className:"revival-tile p-5 lg:col-span-2",children:[e.jsx("div",{className:"revival-eyebrow text-muted-foreground",children:"Last 14 days"}),e.jsx("div",{className:"text-lg font-semibold mt-1",children:"Homeowner engagement"}),e.jsx("div",{className:"h-64 mt-4",children:e.jsx(C_,{width:"100%",height:"100%",children:e.jsxs(yZe,{data:M,children:[e.jsxs("defs",{children:[e.jsxs("linearGradient",{id:"revVisits",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:"hsl(var(--primary))",stopOpacity:.4}),e.jsx("stop",{offset:"100%",stopColor:"hsl(var(--primary))",stopOpacity:0})]}),e.jsxs("linearGradient",{id:"revLeads",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:"hsl(var(--accent))",stopOpacity:.5}),e.jsx("stop",{offset:"100%",stopColor:"hsl(var(--accent))",stopOpacity:0})]})]}),e.jsx(XO,{strokeDasharray:"3 3",stroke:"hsl(var(--border))",vertical:!1}),e.jsx(Cb,{dataKey:"day",tick:{fontSize:11},stroke:"hsl(var(--muted-foreground))"}),e.jsx(Ab,{allowDecimals:!1,tick:{fontSize:11},stroke:"hsl(var(--muted-foreground))",width:28}),e.jsx(vg,{contentStyle:{borderRadius:12,border:"1px solid hsl(var(--border))"}}),e.jsx(A_,{type:"monotone",dataKey:"visits",stroke:"hsl(var(--primary))",fill:"url(#revVisits)",strokeWidth:2}),e.jsx(A_,{type:"monotone",dataKey:"leads",stroke:"hsl(var(--accent))",fill:"url(#revLeads)",strokeWidth:2})]})})})]}),e.jsxs("div",{className:"revival-tile p-5",children:[e.jsx("div",{className:"revival-eyebrow text-muted-foreground",children:"Recent activity"}),e.jsxs("div",{className:"mt-3 space-y-3 max-h-64 overflow-auto pr-1",children:[j.slice(0,20).map(G=>e.jsxs("div",{className:"flex items-start gap-3 text-sm",children:[e.jsx("div",{className:"h-2 w-2 rounded-full bg-accent mt-1.5 shrink-0"}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium capitalize",children:G.event_type.replace(/_/g," ")}),e.jsx("div",{className:"text-xs text-muted-foreground",children:Ys(new Date(G.created_at),"MMM d, h:mm a")})]})]},G.id)),j.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No activity yet. Mail your first letter to start tracking."}):null]})]})]}),e.jsxs("div",{className:"revival-tile p-5",children:[e.jsx("div",{className:"revival-eyebrow text-muted-foreground",children:"Upcoming follow ups"}),e.jsxs("div",{className:"mt-3 space-y-2",children:[C.filter(G=>!G.completed_at).slice(0,6).map(G=>e.jsxs("div",{className:"flex items-center gap-3 rounded-xl border border-border px-4 py-3",children:[e.jsx(Li,{checked:!!G.completed_at,onCheckedChange:H=>g.mutate({id:G.id,done:!!H})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"font-medium truncate",children:G.title}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:G.detail})]}),e.jsx(qe,{variant:"outline",children:Ys(new Date(`${G.due_date}T12:00:00`),"MMM d")})]},G.id)),C.filter(G=>!G.completed_at).length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Nothing due. Create a campaign to generate your follow-up plan."}):null]})]})]}),e.jsx(cs,{value:"campaigns",className:"mt-6",children:U("No campaigns yet — click New Campaign to build your first one.")}),e.jsx(cs,{value:"properties",className:"mt-6",children:e.jsx("div",{className:"revival-tile overflow-hidden",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-muted/60 text-left",children:e.jsxs("tr",{children:[e.jsx("th",{className:"px-4 py-3 font-semibold",children:"Property"}),e.jsx("th",{className:"px-4 py-3 font-semibold",children:"Seller"}),e.jsx("th",{className:"px-4 py-3 font-semibold",children:"Original"}),e.jsx("th",{className:"px-4 py-3 font-semibold",children:"Final"}),e.jsx("th",{className:"px-4 py-3 font-semibold",children:"DOM"}),e.jsx("th",{className:"px-4 py-3 font-semibold",children:"Expired"})]})}),e.jsxs("tbody",{children:[(u.data??[]).map(G=>e.jsxs("tr",{className:"border-t border-border",children:[e.jsx("td",{className:"px-4 py-3 font-medium",children:G.property_address}),e.jsx("td",{className:"px-4 py-3",children:G.seller_name??"—"}),e.jsx("td",{className:"px-4 py-3",children:$M(G.original_price)}),e.jsx("td",{className:"px-4 py-3",children:$M(G.final_price)}),e.jsx("td",{className:"px-4 py-3",children:G.days_on_market??"—"}),e.jsx("td",{className:"px-4 py-3",children:G.expiration_date??"—"})]},G.id)),(u.data??[]).length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:6,className:"px-4 py-10 text-center text-muted-foreground",children:"No properties imported yet."})}):null]})]})})}),e.jsx(cs,{value:"letters",className:"mt-6",children:U("Letters appear here once you create a campaign.")}),e.jsx(cs,{value:"landing",className:"mt-6",children:U("Landing pages appear here once you create a campaign.")}),e.jsx(cs,{value:"plans",className:"mt-6",children:U("Property Revival Plans appear here once you create a campaign.")}),e.jsxs(cs,{value:"followup",className:"mt-6 space-y-4",children:[e.jsxs("div",{className:"grid gap-4 lg:grid-cols-2",children:[e.jsxs("div",{className:"revival-tile p-5",children:[e.jsx("div",{className:"revival-eyebrow text-muted-foreground",children:"Open tasks"}),e.jsxs("div",{className:"mt-3 space-y-2",children:[C.filter(G=>!G.completed_at).map(G=>e.jsxs("div",{className:"flex items-center gap-3 rounded-xl border border-border px-4 py-3",children:[e.jsx(Li,{checked:!1,onCheckedChange:()=>g.mutate({id:G.id,done:!0})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"font-medium truncate",children:G.title}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:G.detail})]}),e.jsx(qe,{variant:"outline",className:"capitalize",children:G.channel})]},G.id)),C.filter(G=>!G.completed_at).length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"All caught up."}):null]})]}),e.jsxs("div",{className:"revival-tile p-5",children:[e.jsx("div",{className:"revival-eyebrow text-muted-foreground",children:"Seller leads"}),e.jsxs("div",{className:"mt-3 space-y-2",children:[_.map(G=>e.jsxs("div",{className:"rounded-xl border border-border px-4 py-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"font-medium",children:[G.first_name,G.last_name].filter(Boolean).join(" ")||"Homeowner"}),e.jsxs(qe,{className:Ot("capitalize border-0",G.temperature==="hot"&&"bg-red-500/15 text-red-600",G.temperature==="warm"&&"bg-amber-500/15 text-amber-700",G.temperature==="nurture"&&"bg-sky-500/15 text-sky-700",G.temperature==="low"&&"bg-muted text-muted-foreground"),children:[G.temperature," · ",G.lead_score]})]}),e.jsxs("div",{className:"text-xs text-muted-foreground mt-1",children:[G.timeline?`Timeline: ${G.timeline} · `:"",G.next_action]})]},G.id)),_.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No seller leads captured yet."}):null]})]})]}),e.jsxs("div",{className:"revival-tile p-5",children:[e.jsx("div",{className:"revival-eyebrow text-muted-foreground",children:"Opportunity pipeline"}),e.jsx("div",{className:"mt-4 flex gap-2 overflow-x-auto no-scrollbar pb-1",children:QKn.map(G=>{const H=G.toLowerCase().replace(/ /g,"_"),Y=_.filter(se=>se.stage===H).length;return e.jsxs("div",{className:"min-w-[150px] rounded-xl border border-border p-3",children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:G}),e.jsx("div",{className:"text-2xl font-bold tabular-nums",children:Y})]},G)})})]})]}),e.jsxs(cs,{value:"analytics",className:"mt-6 space-y-4",children:[e.jsxs("div",{className:"grid gap-3 grid-cols-2 lg:grid-cols-4",children:[e.jsx(Yb,{label:"Lead capture %",value:`${A.visits?Math.round(A.leads/A.visits*100):0}%`,icon:Xn}),e.jsx(Yb,{label:"Scan → visit",value:`${A.qr?Math.round(A.visits/A.qr*100):0}%`,icon:Bx}),e.jsx(Yb,{label:"Appointments",value:A.appointments,icon:fb}),e.jsx(Yb,{label:"Conversion %",value:`${A.leads?Math.round(A.won/A.leads*100):0}%`,icon:ql})]}),e.jsxs("div",{className:"revival-tile p-5",children:[e.jsx("div",{className:"revival-eyebrow text-muted-foreground",children:"Campaign performance"}),e.jsx("div",{className:"h-72 mt-4",children:e.jsx(C_,{width:"100%",height:"100%",children:e.jsxs(YEe,{data:v.slice(0,10).map(G=>{var H;return{name:(((H=G.property)==null?void 0:H.property_address)??G.name).slice(0,18),visits:j.filter(Y=>Y.campaign_id===G.id&&Y.event_type==="page_view").length,leads:_.filter(Y=>Y.campaign_id===G.id).length}}),children:[e.jsx(XO,{strokeDasharray:"3 3",stroke:"hsl(var(--border))",vertical:!1}),e.jsx(Cb,{dataKey:"name",tick:{fontSize:10},stroke:"hsl(var(--muted-foreground))"}),e.jsx(Ab,{allowDecimals:!1,tick:{fontSize:11},stroke:"hsl(var(--muted-foreground))",width:28}),e.jsx(vg,{contentStyle:{borderRadius:12,border:"1px solid hsl(var(--border))"}}),e.jsx(R2,{dataKey:"visits",fill:"hsl(var(--primary))",radius:[6,6,0,0]}),e.jsx(R2,{dataKey:"leads",fill:"hsl(var(--accent))",radius:[6,6,0,0]})]})})})]})]}),e.jsxs(cs,{value:"templates",className:"mt-6 space-y-5",children:[e.jsxs("div",{children:[e.jsx("div",{className:"revival-eyebrow text-muted-foreground",children:"Campaign styles"}),e.jsx("div",{className:"grid gap-3 mt-3 md:grid-cols-2 xl:grid-cols-3",children:WB.map(G=>e.jsxs("div",{className:"revival-tile p-5",children:[e.jsx("div",{className:Ot("h-1.5 w-full rounded-full bg-gradient-to-r mb-4",G.accent)}),e.jsx("div",{className:"font-semibold",children:G.name}),e.jsx("div",{className:"text-xs uppercase tracking-wider text-accent-foreground/70",children:G.tagline}),e.jsx("p",{className:"text-sm text-muted-foreground mt-2",children:G.description}),e.jsxs("p",{className:"revival-serif text-[15px] mt-3 leading-snug",children:["“",G.previewHeadline,"”"]})]},G.id))})]}),e.jsxs("div",{children:[e.jsx("div",{className:"revival-eyebrow text-muted-foreground",children:"Letter templates"}),e.jsx("div",{className:"grid gap-3 mt-3 sm:grid-cols-2 lg:grid-cols-5",children:hKt.map(G=>e.jsxs("div",{className:"revival-tile p-4",children:[e.jsx("div",{className:"font-semibold",children:G.name}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:G.note})]},G.id))})]})]}),e.jsx(cs,{value:"settings",className:"mt-6",children:e.jsxs("div",{className:"revival-tile p-6 space-y-4 max-w-2xl",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-semibold",children:"Branding"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Letters, landing pages and emails automatically pull your name, photo, phone, brokerage and website from your LevelUp profile."}),e.jsx($,{variant:"outline",size:"sm",className:"mt-3",onClick:()=>s("/profile"),children:"Edit my profile"})]}),e.jsxs("div",{className:"border-t border-border pt-4",children:[e.jsx("div",{className:"font-semibold",children:"Agent OS integration"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Every seller submission creates or updates a contact, applies the ListingRevival, ExpiredSeller and LandingPageLead tags, opens an opportunity in your pipeline, logs the activity and creates your next follow-up task automatically."})]}),e.jsxs("div",{className:"border-t border-border pt-4",children:[e.jsx("div",{className:"font-semibold",children:"Availability"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Listing Revival is currently in private beta and visible to LevelUp admins only."})]})]})})]})]})})}const Njt=["Import the property","Choose the campaign style","Generate everything"];function pYn(){var _;const s=Jn(),{user:t}=ks(),{generate:n,invalidate:r}=_Je(),[a,i]=k.useState(0),[l,o]=k.useState(!1),[c,d]=k.useState(WB[0].id),[u,h]=k.useState("professional"),[m,p]=k.useState({property_address:"",city:"",state:"",zip:"",seller_name:"",seller_email:"",seller_phone:"",mailing_address:"",mailing_city:"",mailing_state:"",mailing_zip:"",original_price:"",final_price:"",days_on_market:"",expiration_date:"",mls_link:"",photo_url:"",agent_notes:""}),g=(j,C)=>p(A=>({...A,[j]:C})),x=a===0?m.property_address.trim().length>3:!0,y=async()=>{if(t){o(!0);try{const{data:j,error:C}=await V.from("listing_revival_properties").insert({owner_user_id:t.id,property_address:m.property_address.trim(),city:m.city||null,state:m.state||null,zip:m.zip||null,seller_name:m.seller_name||null,seller_email:m.seller_email||null,seller_phone:m.seller_phone||null,mailing_address:m.mailing_address||null,mailing_city:m.mailing_city||null,mailing_state:m.mailing_state||null,mailing_zip:m.mailing_zip||null,original_price:m.original_price?Number(m.original_price):null,final_price:m.final_price?Number(m.final_price):null,days_on_market:m.days_on_market?Number(m.days_on_market):null,expiration_date:m.expiration_date||null,mls_link:m.mls_link||null,photo_url:m.photo_url||null,agent_notes:m.agent_notes||null}).select().single();if(C)throw C;const{data:A,error:M}=await V.from("listing_revival_campaigns").insert({owner_user_id:t.id,property_id:j.id,name:m.property_address.trim(),slug:sYn(m.property_address),style:c,letter_template:u,status:"generating",published:!0}).select().single();if(M)throw M;await n.mutateAsync({campaignId:A.id}),r(),ae.success("Campaign built — everything is ready."),s(`/apps/listing-revival/campaigns/${A.id}`)}catch(j){ae.error(j instanceof Error?j.message:"Could not create the campaign")}finally{o(!1)}}},v=(j,C,A={})=>e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{className:"text-xs uppercase tracking-wider text-muted-foreground",children:C}),e.jsx(be,{value:m[j],onChange:M=>g(j,M.target.value),...A})]});return e.jsx(Xs,{title:"New Revival Campaign",children:e.jsxs("div",{className:"revival-theme -m-4 sm:-m-6 p-4 sm:p-6 min-h-[calc(100vh-4rem)]",children:[e.jsxs($,{variant:"ghost",size:"sm",className:"gap-2 mb-4",onClick:()=>s("/apps/listing-revival"),children:[e.jsx(Ia,{className:"h-4 w-4"})," Back to Listing Revival"]}),e.jsx("div",{className:"flex items-center gap-3 mb-6",children:Njt.map((j,C)=>e.jsxs("div",{className:"flex items-center gap-3 flex-1",children:[e.jsx("div",{className:Ot("h-9 w-9 rounded-full grid place-items-center text-sm font-bold shrink-0 transition-colors",Cg("photo_url",j??""),label:"Property photo",prefix:"revival-property"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"Agent notes"}),e.jsx(Ls,{rows:6,value:m.agent_notes,onChange:j=>g("agent_notes",j.target.value),placeholder:"Anything you know: why it didn't sell, condition, seller's motivation, photos were poor, etc."})]})]})]}):null,a===1?e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"revival-tile p-6",children:[e.jsx("div",{className:"revival-eyebrow text-muted-foreground",children:"Step two"}),e.jsx("h2",{className:"revival-serif text-2xl mt-1",children:"Pick the voice of the campaign"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"The style shapes the letter, the landing page and the whole email and text sequence."}),e.jsx("div",{className:"grid gap-3 mt-5 md:grid-cols-2 xl:grid-cols-3",children:WB.map(j=>e.jsxs("button",{type:"button",onClick:()=>d(j.id),className:Ot("text-left rounded-2xl border p-5 transition-all",c===j.id?"border-accent ring-2 ring-accent/40 bg-accent/[0.04]":"border-border hover:border-accent/50"),children:[e.jsx("div",{className:Ot("h-1.5 w-full rounded-full bg-gradient-to-r mb-4",j.accent)}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{className:"font-semibold",children:j.name}),c===j.id?e.jsx(ma,{className:"h-4 w-4 text-accent"}):null]}),e.jsx("div",{className:"text-[11px] uppercase tracking-wider text-muted-foreground",children:j.tagline}),e.jsx("p",{className:"text-sm text-muted-foreground mt-2",children:j.description}),e.jsxs("div",{className:"mt-3 rounded-xl bg-muted/60 p-3",children:[e.jsx("p",{className:"revival-serif text-[14px] leading-snug",children:j.previewHeadline}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:j.previewBody})]})]},j.id))})]}),e.jsxs("div",{className:"revival-tile p-6",children:[e.jsx("div",{className:"font-semibold",children:"Letter design"}),e.jsx("div",{className:"grid gap-3 mt-3 sm:grid-cols-3 lg:grid-cols-5",children:hKt.map(j=>e.jsxs("button",{type:"button",onClick:()=>h(j.id),className:Ot("rounded-xl border p-4 text-left transition-all",u===j.id?"border-accent ring-2 ring-accent/40":"border-border hover:border-accent/50"),children:[e.jsx("div",{className:"font-medium",children:j.name}),e.jsx("div",{className:"text-xs text-muted-foreground mt-1",children:j.note})]},j.id))})]})]}):null,a===2?e.jsxs("div",{className:"revival-tile p-8 text-center max-w-2xl mx-auto",children:[e.jsx("div",{className:"mx-auto h-16 w-16 rounded-2xl revival-dark grid place-items-center",children:e.jsx(vf,{className:"h-7 w-7 text-accent"})}),e.jsx("h2",{className:"revival-serif text-2xl mt-4",children:"Build the full campaign"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-2",children:"One click creates the personalized letter with its QR code, the private landing page, the Property Revival Plan, a 7-email sequence, 5 texts, your call and video scripts, and a 30-day follow-up task plan."}),e.jsxs("div",{className:"mt-6 rounded-2xl border border-border p-5 text-left space-y-2 text-sm",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Property"}),e.jsx("span",{className:"font-medium",children:m.property_address||"—"})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Seller"}),e.jsx("span",{className:"font-medium",children:m.seller_name||"Homeowner"})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Style"}),e.jsx("span",{className:"font-medium",children:(_=WB.find(j=>j.id===c))==null?void 0:_.name})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Letter"}),e.jsx("span",{className:"font-medium capitalize",children:u})]})]}),e.jsx($,{size:"lg",className:"mt-6 w-full bg-accent text-accent-foreground hover:bg-accent/90",disabled:l,onClick:y,children:l?e.jsxs(e.Fragment,{children:[e.jsx(Jt,{className:"h-4 w-4 mr-2 animate-spin"})," Building your campaign…"]}):e.jsxs(e.Fragment,{children:[e.jsx(kn,{className:"h-4 w-4 mr-2"})," Generate campaign"]})})]}):null]},a)}),a<2?e.jsxs("div",{className:"flex justify-between mt-6",children:[e.jsx($,{variant:"outline",disabled:a===0,onClick:()=>i(j=>j-1),children:"Back"}),e.jsxs($,{disabled:!x,onClick:()=>i(j=>j+1),children:["Continue ",e.jsx(xi,{className:"h-4 w-4 ml-1"})]})]}):e.jsx("div",{className:"flex justify-start mt-6",children:e.jsx($,{variant:"outline",disabled:l,onClick:()=>i(1),children:"Back"})})]})})}const kjt={professional:{head:"font-semibold tracking-tight",body:"",rule:"bg-[#0f2540]",size:15},luxury:{head:"revival-serif font-normal tracking-tight",body:"revival-serif",rule:"bg-[#c9a227]",size:15.5},friendly:{head:"font-semibold",body:"",rule:"bg-[#c9a227]",size:15},minimal:{head:"font-medium tracking-tight",body:"",rule:"bg-neutral-300",size:14.5},modern:{head:"font-bold tracking-tighter uppercase",body:"",rule:"bg-[#0f2540]",size:15}};function gYn(s){return s<=900?1:s<=1150?.94:s<=1400?.88:s<=1700?.82:s<=2100?.76:.7}function Sjt({campaign:s,letter:t,agent:n,url:r,className:a}){var h,m;const i=kjt[s.letter_template]??kjt.professional,l=s.property,o=t.paragraphs??[],c=o.join(" ").length+(((h=t.closing)==null?void 0:h.length)??0)+(((m=t.greeting)==null?void 0:m.length)??0),d=gYn(c),u={fontSize:`${(i.size*d).toFixed(2)}px`,lineHeight:1.6};return e.jsxs("div",{id:"revival-letter-sheet",className:Ot("mx-auto w-full max-w-[816px] bg-white text-[#1a2230] shadow-[0_30px_70px_-40px_rgba(15,37,64,.6)]","aspect-[8.5/11] overflow-hidden flex flex-col",a),children:[e.jsxs("div",{className:"flex items-stretch",children:[e.jsxs("div",{className:"flex-1 px-10 pt-9 pb-6",children:[n.brokerage_name?e.jsx("div",{className:"text-[11px] tracking-[0.28em] uppercase text-[#0f2540]/70 font-bold",children:n.brokerage_name}):null,e.jsx("div",{className:"text-2xl font-bold tracking-tight text-[#0f2540] mt-1",children:n.name??"Your Name"})]}),e.jsxs("div",{className:"w-[46%] bg-[#0f2540] text-white px-8 py-6 flex flex-col justify-center [clip-path:polygon(9%_0,100%_0,100%_100%,0_100%)]",children:[e.jsx("div",{className:"text-[10.5px] tracking-[0.2em] uppercase text-white/70",children:"A personal review prepared"}),e.jsx("div",{className:"text-[12px] tracking-[0.2em] uppercase font-bold text-[#c9a227]",children:"exclusively for you"})]})]}),e.jsxs("div",{className:"grid grid-cols-[1.15fr_1fr] gap-8 px-10 flex-1 min-h-0 pb-2",children:[e.jsxs("div",{className:"min-h-0 flex flex-col",children:[e.jsx("h1",{className:Ot("text-[#0f2540]",i.head),style:{fontSize:`${(30*Math.max(d,.82)).toFixed(1)}px`,lineHeight:1.12},children:t.greeting.replace(/,$/,"")}),e.jsx("div",{className:Ot("mt-1 h-[3px] w-16 rounded-full",i.rule)}),e.jsxs("div",{className:Ot("mt-4 text-[#28313f] flex flex-col",i.body),style:{...u,gap:`${(.7*d).toFixed(2)}em`},children:[o.map((p,g)=>e.jsx("p",{children:p},g)),t.closing?e.jsx("p",{className:"font-semibold text-[#0f2540]",children:t.closing}):null]}),e.jsxs("div",{className:"mt-auto pt-4",children:[e.jsx("div",{style:{fontSize:`${(13*d).toFixed(1)}px`},className:"text-[#28313f]",children:"Sincerely,"}),e.jsx("div",{className:"revival-serif italic text-[#0f2540] leading-tight mt-1",style:{fontSize:`${(26*d).toFixed(1)}px`},children:t.signature||n.name})]})]}),e.jsxs("div",{className:"min-h-0 space-y-4 pt-2",children:[l!=null&&l.photo_url?e.jsxs("div",{className:"overflow-hidden rounded-lg",children:[e.jsx("img",{src:l.photo_url,alt:l.property_address??"Property",className:"h-[190px] w-full object-cover",loading:"lazy"}),e.jsxs("div",{className:"bg-[#0f2540] text-white px-4 py-3 text-[11.5px] grid grid-cols-2 gap-2",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-white/60",children:"Property"}),e.jsx("div",{className:"font-semibold leading-tight",children:l.property_address})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-white/60",children:"Days on market"}),e.jsx("div",{className:"font-semibold",children:l.days_on_market??"—"})]})]})]}):null,e.jsxs("div",{className:"rounded-xl border border-[#c9a227]/45 p-4 text-center",children:[e.jsx("div",{className:"inline-block bg-[#c9a227] text-[#0f2540] text-[10px] font-extrabold tracking-[0.18em] uppercase px-3 py-1 rounded",children:"Scan to unlock"}),e.jsxs("div",{className:"revival-serif text-[19px] text-[#0f2540] leading-tight mt-2",children:["Your Private",e.jsx("br",{}),"Property Review"]}),e.jsx("div",{className:"flex justify-center my-3",children:e.jsx(jk,{value:r,size:116,level:"M",fgColor:"#0f2540"})}),e.jsx("div",{className:"text-[11px] text-[#28313f]",children:"Scan the QR code or visit"}),e.jsx("div",{className:"text-[11.5px] font-bold text-[#0f2540] break-all",children:r.replace(/^https?:\/\//,"")})]}),e.jsx("p",{className:"text-[11px] leading-5 text-[#4a5568] italic",children:t.ps})]})]}),e.jsxs("div",{className:"mt-4 bg-[#0f2540] text-white px-10 py-5 flex items-center gap-5",children:[n.avatar_url?e.jsx("img",{src:n.avatar_url,alt:n.name??"Agent",className:"h-16 w-16 rounded-lg object-cover"}):null,e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"text-lg font-bold tracking-wide uppercase",children:n.name}),e.jsx("div",{className:"text-[#c9a227] text-[12.5px] font-semibold",children:n.title??"Real Estate Specialist"})]}),e.jsxs("div",{className:"text-[12px] space-y-0.5 text-right text-white/85",children:[n.phone?e.jsx("div",{children:n.phone}):null,n.email?e.jsx("div",{children:n.email}):null,n.website_url?e.jsx("div",{children:n.website_url.replace(/^https?:\/\//,"")}):null]})]})]})}function yKt({letter:s,saving:t,onSave:n,onCancel:r}){const[a,i]=k.useState(s);k.useEffect(()=>{i(s)},[s]);const l=(u,h)=>i(m=>({...m,[u]:h})),o=(u,h)=>i(m=>({...m,paragraphs:m.paragraphs.map((p,g)=>g===u?h:p)})),c=()=>i(u=>({...u,paragraphs:[...u.paragraphs,""]})),d=u=>i(h=>({...h,paragraphs:h.paragraphs.filter((m,p)=>p!==u)}));return e.jsxs("div",{className:"rounded-xl border border-border bg-card p-5 space-y-5 max-w-3xl",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-semibold",children:"Edit letter"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Your edits are saved to this campaign and used in the PDF."})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs($,{size:"sm",variant:"ghost",onClick:r,disabled:t,children:[e.jsx(mr,{className:"h-3.5 w-3.5 mr-1.5"})," Cancel"]}),e.jsxs($,{size:"sm",onClick:()=>n({...a,paragraphs:a.paragraphs.map(u=>u.trim()).filter(Boolean)}),disabled:t,children:[t?e.jsx(Jt,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}):e.jsx(Ml,{className:"h-3.5 w-3.5 mr-1.5"}),"Save letter"]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-xs",children:"Greeting"}),e.jsx(be,{value:a.greeting??"",onChange:u=>l("greeting",u.target.value),placeholder:"Dear Jane,"})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(re,{className:"text-xs",children:"Body paragraphs"}),e.jsxs($,{size:"sm",variant:"outline",onClick:c,children:[e.jsx(nn,{className:"h-3.5 w-3.5 mr-1.5"})," Add paragraph"]})]}),a.paragraphs.map((u,h)=>e.jsxs("div",{className:"flex gap-2 items-start",children:[e.jsx(Ls,{value:u,onChange:m=>o(h,m.target.value),rows:4,className:"flex-1"}),e.jsx($,{size:"icon",variant:"ghost",onClick:()=>d(h),"aria-label":"Remove paragraph",children:e.jsx(Un,{className:"h-4 w-4 text-muted-foreground"})})]},h))]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-xs",children:"Closing line"}),e.jsx(be,{value:a.closing??"",onChange:u=>l("closing",u.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-xs",children:"Signature"}),e.jsx(be,{value:a.signature??"",onChange:u=>l("signature",u.target.value)})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"text-xs",children:"P.S."}),e.jsx(Ls,{value:a.ps??"",onChange:u=>l("ps",u.target.value),rows:2})]})]})}function Cjt(s){if(!s)return null;const t=Math.floor(s/60),n=Math.round(s%60);return`${t}:${String(n).padStart(2,"0")}`}function xYn(s){return s.share_token?`https://video.relevelup.com/thumb/${s.share_token}`:s.thumbnail_url}function yYn({video:s}){const[t,n]=k.useState(!1),r=xYn(s);return!r||t?e.jsx("div",{className:"h-full w-full grid place-items-center bg-gradient-to-br from-muted to-muted/40",children:e.jsx(mm,{className:"h-7 w-7 text-muted-foreground/70"})}):e.jsx("img",{src:r,alt:s.title??"Video thumbnail",loading:"lazy",onError:()=>n(!0),className:"h-full w-full object-cover transition-transform duration-300 group-hover:scale-[1.04]"})}const vYn=(()=>{if(typeof window>"u"||window.self===window.top)return!1;try{const s=document.featurePolicy;if(s!=null&&s.allowsFeature)return!(s.allowsFeature("camera")&&s.allowsFeature("microphone"))}catch{}return!0})();function bYn({open:s,onOpenChange:t,onSelect:n,propertyAddress:r}){const{user:a}=ks(),[i,l]=k.useState("library"),[o,c]=k.useState([]),[d,u]=k.useState(!1),[h,m]=k.useState(""),[p,g]=k.useState("record"),[x,y]=k.useState(0),[v,_]=k.useState(0),j=o4(),C=k.useCallback(async()=>{if(a){u(!0);try{const{data:R,error:O}=await V.from("agent_videos").select("id, title, recipient_name, playback_url, thumbnail_url, share_token, duration_seconds, created_at").eq("owner_user_id",a.id).eq("is_deleted",!1).eq("status","ready").order("created_at",{ascending:!1}).limit(60);if(O)throw O;c(R??[])}catch{ae.error("Could not load your video library")}finally{u(!1)}}},[a]);k.useEffect(()=>{s&&C()},[s,C]);const A=k.useMemo(()=>{const R=h.trim().toLowerCase();return R?o.filter(O=>`${O.title??""} ${O.recipient_name??""}`.toLowerCase().includes(R)):o},[o,h]),M=R=>{if(!R.playback_url){ae.error("That video has no playable link yet");return}n(R.playback_url),t(!1)},I=R=>{!R&&(p==="uploading"||p==="processing")||(t(R),R||(g("record"),y(0),_(0)))},P=k.useCallback(async(R,O)=>{g("uploading");const B=r?`Listing Revival — ${r}`:"Listing Revival intro";try{const{videoId:U,libraryId:G}=await v6(B),{uploadUrl:H,apiKey:Y}=await b6(U),se=new XMLHttpRequest;se.upload.onprogress=le=>{le.lengthComputable&&y(le.loaded/le.total*100)},await new Promise((le,fe)=>{se.onload=()=>se.status>=200&&se.status<300?le():fe(new Error("Upload failed")),se.onerror=()=>fe(new Error("Upload failed")),se.open("PUT",H),se.setRequestHeader("AccessKey",Y),se.send(R)}),g("processing");const ee=`https://iframe.mediadelivery.net/embed/${G}/${U}`,oe=Date.now(),me=9e4;let Q=0;for(;Q<4;){if(await new Promise(fe=>setTimeout(fe,3e3)),Date.now()-oe>me){await j.mutateAsync({bunny_video_id:U,playback_url:`https://iframe.mediadelivery.net/play/${G}/${U}`,file_size_mb:R.size/(1024*1024),title:B,status:"processing",touch_type:"video"}),n(ee),ae.success("Video saved — still encoding, it will appear shortly."),g("done"),setTimeout(()=>I(!1),1200);return}const le=await D2(U);if(Q=le.status,_(le.encodeProgress||0),Q===5||Q===6)throw new Error("Video processing failed")}const te=await D2(U);await j.mutateAsync({bunny_video_id:U,playback_url:te.directPlayUrl||ee,thumbnail_url:te.thumbnailUrl,preview_url:te.previewUrl||null,duration_seconds:te.length||O,file_size_mb:(te.storageSize||R.size)/(1024*1024),title:B,status:"ready",touch_type:"video"}),n(te.directPlayUrl||ee),ae.success("Video recorded and added to your landing page!"),g("done"),setTimeout(()=>I(!1),1200)}catch(U){console.error("Revival recording upload error:",U),ae.error("Failed to process video. Please try again."),g("record")}},[j,n,r]);return e.jsx(zs,{open:s,onOpenChange:I,children:e.jsxs(Rs,{className:"max-w-4xl max-h-[92vh] overflow-y-auto",children:[e.jsxs(Vs,{children:[e.jsx($s,{children:"Add a video to your landing page"}),e.jsx(Cr,{children:"Pick one you already recorded, or record a brand new one right here without leaving Listing Revival."})]}),e.jsxs(ya,{value:i,onValueChange:l,children:[e.jsxs(va,{className:"grid w-full grid-cols-2",children:[e.jsxs(is,{value:"library",children:[e.jsx(em,{className:"h-3.5 w-3.5 mr-1.5"})," My library"]}),e.jsxs(is,{value:"record",children:[e.jsx(ia,{className:"h-3.5 w-3.5 mr-1.5"})," Record new"]})]}),e.jsxs(cs,{value:"library",className:"mt-4 space-y-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Yr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{value:h,onChange:R=>m(R.target.value),placeholder:"Search your videos…",className:"pl-9"})]}),d?e.jsx("div",{className:"grid gap-3 sm:grid-cols-3",children:Array.from({length:6}).map((R,O)=>e.jsx(fn,{className:"aspect-video rounded-xl"},O))}):A.length===0?e.jsxs("div",{className:"rounded-xl border border-dashed border-border p-10 text-center",children:[e.jsx(mm,{className:"h-8 w-8 mx-auto text-muted-foreground/60"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-2",children:o.length===0?"No finished videos yet — record one on the next tab.":"No videos match that search."}),e.jsxs($,{size:"sm",variant:"outline",className:"mt-3",onClick:()=>l("record"),children:[e.jsx(ia,{className:"h-3.5 w-3.5 mr-1.5"})," Record a video now"]})]}):e.jsx("div",{className:"grid gap-3 sm:grid-cols-3 max-h-[55vh] overflow-y-auto pr-1",children:A.map(R=>e.jsxs("button",{type:"button",onClick:()=>M(R),className:"group text-left rounded-xl border border-border bg-card overflow-hidden transition hover:border-primary hover:shadow-md focus:outline-none focus-visible:ring-2 focus-visible:ring-ring",children:[e.jsxs("div",{className:"aspect-video bg-muted overflow-hidden relative",children:[e.jsx(yYn,{video:R}),Cjt(R.duration_seconds)?e.jsx("span",{className:"absolute bottom-1.5 right-1.5 rounded bg-foreground/80 px-1.5 py-0.5 text-[10px] font-medium text-background",children:Cjt(R.duration_seconds)}):null]}),e.jsxs("div",{className:"p-2.5",children:[e.jsx("div",{className:"text-sm font-medium truncate",children:R.title||R.recipient_name||"Untitled video"}),R.created_at?e.jsx("div",{className:"text-[11px] text-muted-foreground",children:Ys(new Date(R.created_at),"MMM d, yyyy")}):null]})]},R.id))})]}),e.jsxs(cs,{value:"record",className:"mt-4",children:[p==="record"?e.jsxs("div",{className:"space-y-3",children:[vYn?e.jsxs("div",{className:"rounded-xl border border-border bg-muted/40 p-3 flex flex-wrap items-center gap-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground flex-1 min-w-[220px]",children:"This editor preview blocks camera access. Open the app in its own browser tab — recording works right here in the popup for your agents."}),e.jsxs($,{size:"sm",variant:"outline",onClick:()=>window.open(window.location.href,"_blank","noopener"),children:[e.jsx(Ir,{className:"h-3.5 w-3.5 mr-1.5"})," Open in new tab"]})]}):null,e.jsx(w6,{maxDurationSeconds:600,onRecordingComplete:P,onError:R=>ae.error(R)})]}):null,p==="uploading"?e.jsxs("div",{className:"flex flex-col items-center gap-4 py-12",children:[e.jsx(Jt,{className:"h-10 w-10 animate-spin text-primary"}),e.jsx("p",{className:"text-sm font-medium",children:"Uploading your video…"}),e.jsx(ho,{value:x,className:"w-64"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[Math.round(x),"%"]})]}):null,p==="processing"?e.jsxs("div",{className:"flex flex-col items-center gap-4 py-12",children:[e.jsx(Jt,{className:"h-10 w-10 animate-spin text-primary"}),e.jsx("p",{className:"text-sm font-medium",children:"Processing your video…"}),e.jsx(ho,{value:v,className:"w-64"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[Math.round(v),"%"]})]}):null,p==="done"?e.jsxs("div",{className:"flex flex-col items-center gap-3 py-12",children:[e.jsx(nl,{className:"h-12 w-12 text-emerald-500"}),e.jsx("p",{className:"text-sm font-medium",children:"Video added to your landing page!"})]}):null]})]})]})})}const _Yn=[{id:"photo",label:"Property photo",hint:"Shows the listing photo. Best if you have no video.",icon:zc},{id:"video",label:"Video",hint:"Record one here, pick from your library, or paste a link.",icon:ia},{id:"none",label:"Nothing",hint:"Hide the media block entirely for a clean, text-only intro.",icon:x0}];function wYn({campaignId:s,content:t,landingConfig:n,propertyPhotoUrl:r,saving:a,onSave:i}){var A;const[l,o]=k.useState(t.landing),[c,d]=k.useState({...yjt,...n}),[u,h]=k.useState(!1),[m,p]=k.useState(!1);k.useEffect(()=>{o(t.landing)},[t.landing]),k.useEffect(()=>{d({...yjt,...n})},[n]);const g=(M,I)=>{o(P=>({...P??{},[M]:I})),h(!0)},x=(M,I)=>{d(P=>({...P,[M]:I})),h(!0)},y=(l==null?void 0:l.discover)??[],v=M=>g("discover",M),_=k.useMemo(()=>uKt(c.video_url),[c.video_url]),j=c.media_image_url||r||null,C=()=>{i({content:{...t,landing:l},landing_config:c}),h(!1)};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"revival-eyebrow text-muted-foreground",children:"Landing page editor"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Everything here updates your public page instantly after saving."})]}),e.jsxs($,{size:"sm",onClick:C,disabled:!u||a,children:[a?e.jsx(Jt,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}):e.jsx(Ml,{className:"h-3.5 w-3.5 mr-1.5"}),"Save changes"]})]}),e.jsxs("div",{className:"revival-tile p-6 space-y-4",children:[e.jsx("div",{className:"font-semibold",children:"Headline & intro"}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Eyebrow"}),e.jsx(be,{value:(l==null?void 0:l.eyebrow)??"",onChange:M=>g("eyebrow",M.target.value),placeholder:"A complimentary review"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Button text"}),e.jsx(be,{value:(l==null?void 0:l.cta)??"",onChange:M=>g("cta",M.target.value),placeholder:"Get my free review"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Headline"}),e.jsx(be,{value:(l==null?void 0:l.headline)??"",onChange:M=>g("headline",M.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Subheadline"}),e.jsx(Ls,{rows:2,value:(l==null?void 0:l.subheadline)??"",onChange:M=>g("subheadline",M.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Personal intro paragraph"}),e.jsx(Ls,{rows:5,value:(l==null?void 0:l.intro)??"",onChange:M=>g("intro",M.target.value)})]})]}),e.jsxs("div",{className:"revival-tile p-6 space-y-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-semibold",children:"Intro media"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No video? Choose the property photo and the page still looks complete."})]}),e.jsx("div",{className:"grid gap-3 sm:grid-cols-3",children:_Yn.map(M=>{const I=(c.media_mode??"photo")===M.id;return e.jsxs("button",{type:"button",onClick:()=>x("media_mode",M.id),className:`text-left rounded-xl border p-4 transition ${I?"border-accent ring-1 ring-accent":"border-border hover:border-accent/50"}`,children:[e.jsx(M.icon,{className:`h-5 w-5 ${I?"text-accent":"text-muted-foreground"}`}),e.jsx("div",{className:"font-medium mt-2",children:M.label}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:M.hint})]},M.id)})}),(c.media_mode??"photo")==="video"?e.jsxs("div",{className:"space-y-3 rounded-xl border border-border p-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Video link"}),e.jsx(be,{value:c.video_url??"",onChange:M=>x("video_url",M.target.value),placeholder:"Paste a YouTube, Vimeo, Loom or .mp4 link"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Or record a new video right here — it saves to your library automatically."})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs($,{type:"button",size:"sm",onClick:()=>p(!0),children:[e.jsx(ia,{className:"h-3.5 w-3.5 mr-1.5"})," Record or choose a video"]}),c.video_url?e.jsxs($,{type:"button",size:"sm",variant:"ghost",onClick:()=>x("video_url",""),children:[e.jsx(Un,{className:"h-3.5 w-3.5 mr-1.5"})," Remove video"]}):null]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Caption under the video"}),e.jsx(be,{value:c.video_caption??"",onChange:M=>x("video_caption",M.target.value),placeholder:"A personal introduction"})]}),e.jsx("div",{className:"aspect-video rounded-lg overflow-hidden bg-muted grid place-items-center",children:(_==null?void 0:_.kind)==="file"?e.jsx("video",{src:_.src,controls:!0,className:"h-full w-full object-cover"}):_?e.jsx("iframe",{src:_.src,title:"Video preview",className:"h-full w-full",allowFullScreen:!0}):e.jsxs("div",{className:"text-center text-sm text-muted-foreground",children:[e.jsx(mm,{className:"h-8 w-8 mx-auto mb-1 opacity-60"})," Your video preview appears here"]})})]}):null,(c.media_mode??"photo")==="photo"?e.jsxs("div",{className:"space-y-3 rounded-xl border border-border p-4",children:[e.jsx(bte,{label:"Photo shown next to your intro",value:c.media_image_url??"",onChange:M=>x("media_image_url",M),prefix:"revival-landing",hint:"Leave empty to use the property photo from this campaign."}),j?e.jsx("img",{src:j,alt:"Landing media",className:"rounded-lg w-full max-h-64 object-cover"}):e.jsx("p",{className:"text-xs text-muted-foreground",children:"No property photo on this campaign yet — add one here or the media block will be hidden."})]}):null]}),e.jsxs("div",{className:"revival-tile p-6 space-y-4",children:[e.jsx("div",{className:"font-semibold",children:"Sections"}),[["show_property_snapshot","Property snapshot","Address, pricing history and days on market."],["show_discover","Inside your free review","The cards explaining what the seller receives."],["show_testimonial","Testimonial","The quote from a past client."]].map(([M,I,P])=>e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-sm",children:I}),e.jsx("p",{className:"text-xs text-muted-foreground",children:P})]}),e.jsx(On,{checked:c[M]!==!1,onCheckedChange:R=>x(M,R)})]},M))]}),e.jsxs("div",{className:"revival-tile p-6 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{className:"font-semibold",children:"Review highlights"}),e.jsxs($,{size:"sm",variant:"outline",onClick:()=>v([...y,{title:"",body:""}]),children:[e.jsx(nn,{className:"h-3.5 w-3.5 mr-1.5"})," Add card"]})]}),y.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No highlight cards yet."}):null,y.map((M,I)=>e.jsxs("div",{className:"rounded-xl border border-border p-4 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(qe,{variant:"outline",children:I+1}),e.jsx(be,{value:M.title,placeholder:"Card title",onChange:P=>v(y.map((R,O)=>O===I?{...R,title:P.target.value}:R))}),e.jsx($,{size:"icon",variant:"ghost",onClick:()=>v(y.filter((P,R)=>R!==I)),children:e.jsx(Un,{className:"h-4 w-4"})})]}),e.jsx(Ls,{rows:2,value:M.body,placeholder:"What this card explains",onChange:P=>v(y.map((R,O)=>O===I?{...R,body:P.target.value}:R))})]},I))]}),e.jsx("div",{className:"flex justify-end",children:e.jsxs($,{onClick:C,disabled:!u||a,children:[a?e.jsx(Jt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Ml,{className:"h-4 w-4 mr-2"}),"Save changes"]})}),e.jsx(bYn,{open:m,onOpenChange:p,propertyAddress:((A=t==null?void 0:t.landing)==null?void 0:A.headline)??null,onSelect:M=>{x("video_url",M),x("media_mode","video")}})]})}const sOe={intro:"",scores:{},buyers_experienced:[],differently:[],strategy_weeks:[],questions:[],resources:[],invitation:""},jYn=s=>Math.min(5,Math.max(1,Math.round(s||1)));function NYn({plan:s,saving:t,onSave:n}){const[r,a]=k.useState({...sOe,...s});k.useEffect(()=>{a({...sOe,...s})},[s]);const i=(o,c)=>a(d=>({...d,[o]:c})),l=(o,c,d)=>e.jsxs("section",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(re,{children:c}),e.jsxs($,{type:"button",size:"sm",variant:"ghost",onClick:()=>i(o,[...r[o]??[],""]),children:[e.jsx(nn,{className:"h-3.5 w-3.5 mr-1"})," Add"]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:d}),e.jsxs("div",{className:"space-y-2",children:[(r[o]??[]).map((u,h)=>e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ls,{value:u,rows:2,onChange:m=>{const p=[...r[o]??[]];p[h]=m.target.value,i(o,p)}}),e.jsx($,{type:"button",size:"icon",variant:"ghost",onClick:()=>i(o,(r[o]??[]).filter((m,p)=>p!==h)),children:e.jsx(Un,{className:"h-4 w-4 text-destructive"})})]},h)),(r[o]??[]).length===0?e.jsx("p",{className:"text-xs text-muted-foreground italic",children:"Nothing yet."}):null]})]});return e.jsxs("div",{className:"revival-tile p-5 space-y-7",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"revival-eyebrow text-accent-foreground/70",children:"Edit plan"}),e.jsx("h3",{className:"revival-serif text-xl mt-1",children:"Make it yours"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Every word in the seller presentation can be rewritten here. Changes update the preview, the PDF and the live plan page."})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs($,{type:"button",size:"sm",variant:"ghost",onClick:()=>a({...sOe,...s}),children:[e.jsx(jm,{className:"h-3.5 w-3.5 mr-1.5"})," Reset"]}),e.jsxs($,{type:"button",size:"sm",disabled:t,className:"bg-accent text-accent-foreground hover:bg-accent/90",onClick:()=>n(r),children:[t?e.jsx(Jt,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}):e.jsx(Ml,{className:"h-3.5 w-3.5 mr-1.5"}),"Save plan"]})]})]}),e.jsxs("section",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"plan-intro",children:"Introduction"}),e.jsx(Ls,{id:"plan-intro",rows:4,value:r.intro,onChange:o=>i("intro",o.target.value)})]}),e.jsxs("section",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(re,{children:"Marketing scorecard (1–5)"}),e.jsxs($,{type:"button",size:"sm",variant:"ghost",onClick:()=>i("scores",{...r.scores,[`Category ${Object.keys(r.scores??{}).length+1}`]:3}),children:[e.jsx(nn,{className:"h-3.5 w-3.5 mr-1"})," Add category"]})]}),e.jsx("div",{className:"space-y-2",children:Object.entries(r.scores??{}).map(([o,c],d)=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(be,{value:o,onChange:u=>{const h=Object.entries(r.scores??{});h[d]=[u.target.value,c],i("scores",Object.fromEntries(h))}}),e.jsx(be,{type:"number",min:1,max:5,className:"w-20",value:c,onChange:u=>i("scores",{...r.scores,[o]:jYn(Number(u.target.value))})}),e.jsx($,{type:"button",size:"icon",variant:"ghost",onClick:()=>{const u={...r.scores??{}};delete u[o],i("scores",u)},children:e.jsx(Un,{className:"h-4 w-4 text-destructive"})})]},`${o}-${d}`))})]}),l("buyers_experienced","What buyers experienced","Honest observations about the previous listing."),l("differently","What we will do differently","The concrete changes you are proposing."),e.jsxs("section",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(re,{children:"Relaunch timeline"}),e.jsxs($,{type:"button",size:"sm",variant:"ghost",onClick:()=>i("strategy_weeks",[...r.strategy_weeks??[],{week:`Week ${(r.strategy_weeks??[]).length+1}`,title:"",body:""}]),children:[e.jsx(nn,{className:"h-3.5 w-3.5 mr-1"})," Add week"]})]}),e.jsx("div",{className:"space-y-3",children:(r.strategy_weeks??[]).map((o,c)=>e.jsxs("div",{className:"rounded-xl border p-3 space-y-2",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(be,{className:"w-28",value:o.week,placeholder:"Week 1",onChange:d=>{const u=[...r.strategy_weeks??[]];u[c]={...o,week:d.target.value},i("strategy_weeks",u)}}),e.jsx(be,{value:o.title,placeholder:"Title",onChange:d=>{const u=[...r.strategy_weeks??[]];u[c]={...o,title:d.target.value},i("strategy_weeks",u)}}),e.jsx($,{type:"button",size:"icon",variant:"ghost",onClick:()=>i("strategy_weeks",(r.strategy_weeks??[]).filter((d,u)=>u!==c)),children:e.jsx(Un,{className:"h-4 w-4 text-destructive"})})]}),e.jsx(Ls,{rows:2,value:o.body,placeholder:"What happens this week",onChange:d=>{const u=[...r.strategy_weeks??[]];u[c]={...o,body:d.target.value},i("strategy_weeks",u)}})]},c))})]}),l("questions","Questions for the seller","Prompts you want to discuss at the appointment."),e.jsxs("section",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(re,{children:"Resources"}),e.jsxs($,{type:"button",size:"sm",variant:"ghost",onClick:()=>i("resources",[...r.resources??[],{title:"",body:""}]),children:[e.jsx(nn,{className:"h-3.5 w-3.5 mr-1"})," Add resource"]})]}),e.jsx("div",{className:"space-y-3",children:(r.resources??[]).map((o,c)=>e.jsxs("div",{className:"rounded-xl border p-3 space-y-2",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(be,{value:o.title,placeholder:"Title",onChange:d=>{const u=[...r.resources??[]];u[c]={...o,title:d.target.value},i("resources",u)}}),e.jsx($,{type:"button",size:"icon",variant:"ghost",onClick:()=>i("resources",(r.resources??[]).filter((d,u)=>u!==c)),children:e.jsx(Un,{className:"h-4 w-4 text-destructive"})})]}),e.jsx(Ls,{rows:2,value:o.body,onChange:d=>{const u=[...r.resources??[]];u[c]={...o,body:d.target.value},i("resources",u)}})]},c))})]}),e.jsxs("section",{className:"space-y-2",children:[e.jsx(re,{htmlFor:"plan-invitation",children:"Closing invitation"}),e.jsx(Ls,{id:"plan-invitation",rows:3,value:r.invitation,onChange:o=>i("invitation",o.target.value)})]}),e.jsx("div",{className:"flex justify-end",children:e.jsxs($,{type:"button",disabled:t,className:"bg-accent text-accent-foreground hover:bg-accent/90",onClick:()=>n(r),children:[t?e.jsx(Jt,{className:"h-4 w-4 mr-1.5 animate-spin"}):e.jsx(Ml,{className:"h-4 w-4 mr-1.5"}),"Save plan"]})})]})}const kYn=[{key:"letter",label:"Letter",icon:pn,blurb:"Personalized print-ready letter mailed to the homeowner."},{key:"qr_scan",label:"QR Scan",icon:Bx,blurb:"Homeowner scans the unique code on the letter."},{key:"page_view",label:"Landing Page",icon:kc,blurb:"Private property review page opens on their phone."},{key:"form_submit",label:"Lead Form",icon:lv,blurb:"They request the plan — Agent OS is updated instantly."},{key:"plan_view",label:"Revival Plan",icon:ea,blurb:"The full Property Revival Plan is delivered."},{key:"email",label:"Email Sequence",icon:Wr,blurb:"Seven branded emails nurture the conversation."},{key:"sms",label:"Text Sequence",icon:bo,blurb:"Five short texts keep momentum going."},{key:"appointment",label:"Appointment",icon:fb,blurb:"They book a complimentary strategy session."},{key:"listing",label:"Listing Signed",icon:oh,blurb:"The relaunch begins."}];function SYn({counts:s,onStep:t,activeStep:n}){return e.jsx("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-3",children:kYn.map((r,a)=>{const i=r.icon,l=s[r.key]??0,o=l>0;return e.jsxs(_r.button,{type:"button",onClick:()=>t==null?void 0:t(r.key),initial:{opacity:0,y:16},animate:{opacity:1,y:0},transition:{delay:a*.05,duration:.45,ease:[.22,1,.36,1]},className:Ot("revival-tile text-left p-5 relative overflow-hidden group",n===r.key&&"ring-2 ring-accent"),children:[e.jsx("div",{className:"absolute right-4 top-4 text-[11px] font-bold tracking-widest text-muted-foreground",children:String(a+1).padStart(2,"0")}),e.jsx("div",{className:Ot("h-11 w-11 rounded-xl grid place-items-center transition-colors",o?"bg-accent/20 text-accent-foreground":"bg-muted text-muted-foreground"),children:e.jsx(i,{className:"h-5 w-5"})}),e.jsx("div",{className:"mt-3 font-semibold",children:r.label}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1 leading-relaxed",children:r.blurb}),e.jsxs("div",{className:"mt-3 flex items-baseline gap-2",children:[e.jsx("span",{className:"text-2xl font-bold tabular-nums",children:l}),e.jsx("span",{className:"text-xs uppercase tracking-wider text-muted-foreground",children:o?"recorded":"waiting"})]}),e.jsx("div",{className:"absolute inset-x-0 bottom-0 h-1 bg-gradient-to-r from-accent to-accent/0 origin-left transition-transform duration-500 scale-x-0 group-hover:scale-x-100"})]},r.key)})})}function CYn({open:s,onOpenChange:t,campaignId:n,email:r,ctaUrl:a,seller:i}){const{user:l}=ks(),[o,c]=k.useState([]),[d,u]=k.useState(""),[h,m]=k.useState([]),[p,g]=k.useState(""),[x,y]=k.useState(""),[v,_]=k.useState("View your property review"),[j,C]=k.useState(""),[A,M]=k.useState(!1),[I,P]=k.useState(!1),R=k.useRef(null);k.useEffect(()=>{!s||!r||(c([]),u(""),m([]),g(r.subject||""),y(r.body||""),C(""))},[s,r==null?void 0:r.key,r==null?void 0:r.subject]),k.useEffect(()=>{if(!s||!r)return;const H=setTimeout(async()=>{M(!0);try{const{data:Y,error:se}=await V.functions.invoke("listing-revival-email",{body:{campaign_id:n,subject:p,body:x,preview_text:r.preview,cta_label:v,cta_url:a,preview_only:!0}});if(se)throw se;Y!=null&&Y.html&&C(Y.html)}catch{}finally{M(!1)}},400);return()=>clearTimeout(H)},[s,n,p,x,v,a,r==null?void 0:r.key]),k.useEffect(()=>{R.current&&clearTimeout(R.current);const H=d.trim();if(!l||H.length<2||/\S+@\S+\.\S+/.test(H)){m([]);return}return R.current=setTimeout(async()=>{const Y=`%${H}%`,se=V,{data:ee}=await se.from("innercircle_contacts").select("id, first_name, last_name, email").eq("owner_user_id",l.id).not("email","is",null).or(`first_name.ilike.${Y},last_name.ilike.${Y},email.ilike.${Y}`).order("first_name",{ascending:!0}).limit(6);m(ee||[])},200),()=>{R.current&&clearTimeout(R.current)}},[d,l==null?void 0:l.id]);const O=H=>{H.email&&(c(Y=>Y.some(se=>se.email.toLowerCase()===H.email.toLowerCase())?Y:[...Y,H]),u(""),m([]))},B=()=>{const H=d.trim();if(!/\S+@\S+\.\S+/.test(H)){ae.error("Enter a valid email address");return}O({email:H})},U=k.useMemo(()=>!!r&&o.length>0&&p.trim().length>0&&!I,[r,o,p,I]),G=async()=>{if(r){P(!0);try{const{data:H,error:Y}=await V.functions.invoke("listing-revival-email",{body:{campaign_id:n,subject:p,body:x,preview_text:r.preview,cta_label:v,cta_url:a,email_key:r.key,recipients:o}});if(Y)throw Y;if(!(H!=null&&H.success))throw new Error((H==null?void 0:H.error)||"Could not send the email");ae.success(H.failed?`Sent to ${H.sent} · ${H.failed} failed`:`Email sent to ${H.sent} ${H.sent===1?"contact":"contacts"}`),t(!1)}catch(H){ae.error((H==null?void 0:H.message)||"Could not send the email")}finally{P(!1)}}};return e.jsx(zs,{open:s,onOpenChange:t,children:e.jsxs(Rs,{className:"max-w-5xl max-h-[92vh] overflow-y-auto",children:[e.jsxs(Vs,{children:[e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(pn,{className:"h-4 w-4"})," Send this email"]}),e.jsx(Cr,{children:"Pick contacts from your Agent OS database — they receive the fully branded HTML version."})]}),e.jsxs("div",{className:"grid gap-6 lg:grid-cols-[1fr_1.1fr]",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Recipients"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(be,{value:d,onChange:H=>u(H.target.value),placeholder:"Search contacts or type an email",onKeyDown:H=>{H.key==="Enter"&&(H.preventDefault(),B())}}),e.jsx($,{type:"button",variant:"outline",size:"icon",onClick:B,children:e.jsx(nn,{className:"h-4 w-4"})})]}),h.length>0&&e.jsx("div",{className:"rounded-xl border divide-y overflow-hidden",children:h.map(H=>e.jsxs("button",{type:"button",className:"w-full text-left px-3 py-2 hover:bg-muted/60 flex items-center gap-2",onClick:()=>O({email:H.email,first_name:H.first_name,last_name:H.last_name,contact_id:H.id}),children:[e.jsx(el,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"text-sm",children:[H.first_name,H.last_name].filter(Boolean).join(" ")||H.email}),e.jsx("span",{className:"text-xs text-muted-foreground ml-auto",children:H.email})]},H.id))}),(i==null?void 0:i.email)&&!o.some(H=>H.email.toLowerCase()===i.email.toLowerCase())&&e.jsxs($,{type:"button",size:"sm",variant:"ghost",onClick:()=>O({email:i.email,first_name:(i.name||"").split(" ")[0]}),children:[e.jsx(nn,{className:"h-3.5 w-3.5 mr-1.5"})," Add seller (",i.email,")"]}),o.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2 pt-1",children:o.map(H=>e.jsxs(qe,{variant:"secondary",className:"gap-1",children:[[H.first_name,H.last_name].filter(Boolean).join(" ")||H.email,e.jsx("button",{type:"button",onClick:()=>c(Y=>Y.filter(se=>se.email!==H.email)),children:e.jsx(mr,{className:"h-3 w-3"})})]},H.email))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Subject"}),e.jsx(be,{value:p,onChange:H=>g(H.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Message"}),e.jsx(Ls,{rows:10,value:x,onChange:H=>y(H.target.value)}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Use ",e.jsx("code",{children:"{{first_name}}"}),", ",e.jsx("code",{children:"{{address}}"})," or ",e.jsx("code",{children:"{{agent_name}}"})," to personalize."]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Button label"}),e.jsx(be,{value:v,onChange:H=>_(H.target.value)})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(re,{className:"flex items-center gap-2",children:["Live preview ",A&&e.jsx(Jt,{className:"h-3 w-3 animate-spin"})]}),e.jsx("div",{className:"rounded-xl border overflow-hidden bg-muted/30 h-[520px]",children:j?e.jsx("iframe",{title:"Email preview",srcDoc:j,className:"w-full h-full border-0"}):e.jsx("div",{className:"h-full grid place-items-center text-sm text-muted-foreground",children:"Building preview…"})})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"ghost",onClick:()=>t(!1),children:"Cancel"}),e.jsxs($,{onClick:G,disabled:!U,children:[I?e.jsx(Jt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Wr,{className:"h-4 w-4 mr-2"}),"Send to ",o.length||0]})]})]})})}const AYn=[{id:"estate",name:"Estate Navy",description:"The signature look — deep navy, gold rules, serif headlines.",bg:"#0f2540",surface:"#ffffff",ink:"#1f2937",muted:"#6b7280",accent:"#c9a227",accentInk:"#0f2540",headingFont:'Georgia, "Times New Roman", serif',bodyFont:'"Helvetica Neue", Helvetica, Arial, sans-serif',swatch:["#0f2540","#c9a227","#ffffff"]},{id:"coastal",name:"Coastal",description:"Airy sea-glass blues and sand — perfect for beach markets.",bg:"#0d3b45",surface:"#fbfaf6",ink:"#12303a",muted:"#5c7a80",accent:"#4ea6a0",accentInk:"#04262b",headingFont:'"Iowan Old Style", Georgia, serif',bodyFont:'"Helvetica Neue", Helvetica, Arial, sans-serif',swatch:["#0d3b45","#4ea6a0","#fbfaf6"]},{id:"ranch",name:"Land & Ranch",description:"Earthy clay and saddle tones for land, farm and ranch.",bg:"#2f2a22",surface:"#fdfaf4",ink:"#2b2620",muted:"#7a6f60",accent:"#b4703a",accentInk:"#fff8ef",headingFont:"Georgia, serif",bodyFont:'"Helvetica Neue", Helvetica, Arial, sans-serif',swatch:["#2f2a22","#b4703a","#fdfaf4"]},{id:"modern",name:"Modern Mono",description:"Editorial black and white with a single sharp accent.",bg:"#111113",surface:"#ffffff",ink:"#111113",muted:"#6d6d73",accent:"#e0483c",accentInk:"#ffffff",headingFont:'"Helvetica Neue", Helvetica, Arial, sans-serif',bodyFont:'"Helvetica Neue", Helvetica, Arial, sans-serif',swatch:["#111113","#e0483c","#ffffff"]}],Ajt="c0a11111-0000-4000-8000-000000000030";function EYn(){var oe,me,Q,te,le,fe,_e,ve,he,Se,Te,Ie,Ue,Be,je,Ye,Ee,Re,ke,Fe,Oe,Ge,yt,tt,ut,nt,et,at,wt;const{id:s}=oo(),t=Jn(),{user:n}=ks(),r=dYn(s),a=xKt(),i=gKt(),{generate:l,saveCampaign:o,deleteCampaign:c}=_Je(),[d,u]=k.useState(""),[h,m]=k.useState(null),[p,g]=k.useState(!1),[x,y]=k.useState(!1),[v,_]=k.useState(null),j=pt({queryKey:["revival-drip-campaigns",n==null?void 0:n.id],enabled:!!n,queryFn:async()=>{const{data:rt}=await V.from("drip_campaigns").select("id, name").eq("owner_user_id",n.id).order("name");return rt??[]}}),C=Nt({mutationFn:async()=>{if(!n)throw new Error("Not signed in");const[{data:rt},{data:Ft}]=await Promise.all([V.from("drip_campaigns").select("*").eq("id",Ajt).maybeSingle(),V.from("drip_campaign_steps").select("*").eq("campaign_id",Ajt).order("step_order")]);if(!rt)throw new Error("Starter campaign not found");const{data:Ut,error:Is}=await V.from("drip_campaigns").insert({owner_user_id:n.id,name:rt.name,description:rt.description,category:rt.category,icon:rt.icon,cover_color:rt.cover_color,goal:rt.goal,is_active:!0,is_starter:!1}).select("id, name").single();if(Is)throw Is;if(Ft!=null&&Ft.length){const{error:xs}=await V.from("drip_campaign_steps").insert(Ft.map(st=>({campaign_id:Ut.id,step_order:st.step_order,channel:st.channel,subject:st.subject,body:st.body,delay_type:st.delay_type,delay_days:st.delay_days,delay_hours:st.delay_hours,send_window_start:st.send_window_start,send_window_end:st.send_window_end})));if(xs)throw xs}return Ut},onSuccess:async rt=>{await j.refetch(),o.mutate({id:s,patch:{drip_campaign_id:rt.id}}),ae.success("Expired Listing Revival drip installed and assigned")},onError:rt=>ae.error(rt.message)}),A=(j.data??[]).some(rt=>{var Ft;return(Ft=rt.name)==null?void 0:Ft.startsWith("Expired Listing Revival")}),M=pt({queryKey:["revival-agent-profile",n==null?void 0:n.id],enabled:!!n,queryFn:async()=>{const{data:rt}=await V.from("profiles").select("name, email, phone, avatar_url, brokerage_name, website_url, title").eq("id",n.id).maybeSingle();return rt}}),I=r.data,P=(I==null?void 0:I.content)??{},R=I?mKt(I.slug):"",O={name:(oe=M.data)==null?void 0:oe.name,title:(me=M.data)==null?void 0:me.title,phone:(Q=M.data)==null?void 0:Q.phone,email:(te=M.data)==null?void 0:te.email,website_url:(le=M.data)==null?void 0:le.website_url,avatar_url:(fe=M.data)==null?void 0:fe.avatar_url,brokerage_name:(_e=M.data)==null?void 0:_e.brokerage_name},B=k.useRef(null),U=async()=>{var Ft,Ut;const rt=(Ft=B.current)==null?void 0:Ft.firstElementChild;if(rt){m("letter");try{await lYn(rt,((Ut=I==null?void 0:I.property)==null?void 0:Ut.property_address)??(I==null?void 0:I.name)??"letter"),ae.success("Letter PDF downloaded")}catch{ae.error("Could not build the letter PDF")}finally{m(null)}}},G=k.useRef(null),H=async()=>{var Ft;const rt=G.current;if(rt){m("plan");try{await pKt(rt,((Ft=I==null?void 0:I.property)==null?void 0:Ft.property_address)??(I==null?void 0:I.name)??"plan"),ae.success("Plan PDF downloaded")}catch{ae.error("Could not build the plan PDF")}finally{m(null)}}},Y=k.useMemo(()=>{var Ut,Is;const rt=(a.data??[]).filter(xs=>xs.campaign_id===s),Ft={};return rt.forEach(xs=>{Ft[xs.event_type]=(Ft[xs.event_type]??0)+1}),Ft.letter=P.letter?1:0,Ft.email=((Ut=P.emails)==null?void 0:Ut.length)??0,Ft.sms=((Is=P.sms)==null?void 0:Is.length)??0,Ft.form_submit=(i.data??[]).filter(xs=>xs.campaign_id===s).length,Ft},[a.data,i.data,s,P]);if(r.isLoading)return e.jsx(Xs,{title:"Campaign",children:e.jsx("div",{className:"grid place-items-center py-24",children:e.jsx(Jt,{className:"h-6 w-6 animate-spin"})})});if(!I)return e.jsx(Xs,{title:"Campaign",children:e.jsx("div",{className:"py-24 text-center text-muted-foreground",children:"Campaign not found."})});const se=WB.find(rt=>rt.id===I.style),ee=rt=>l.mutate({campaignId:I.id,section:rt,instruction:d||void 0});return e.jsxs(Xs,{title:I.name,children:[e.jsxs("div",{className:"revival-theme -m-4 sm:-m-6 p-4 sm:p-6 min-h-[calc(100vh-4rem)]",children:[e.jsxs($,{variant:"ghost",size:"sm",className:"gap-2 mb-4",onClick:()=>t("/apps/listing-revival"),children:[e.jsx(Ia,{className:"h-4 w-4"})," Back to Listing Revival"]}),e.jsx(_r.div,{initial:{opacity:0,y:14},animate:{opacity:1,y:0},transition:{duration:.45},className:"revival-dark rounded-3xl overflow-hidden",children:e.jsxs("div",{className:"grid lg:grid-cols-[1.4fr_1fr]",children:[e.jsxs("div",{className:"p-7",children:[e.jsx("div",{className:"revival-eyebrow text-accent",children:(se==null?void 0:se.name)??I.style}),e.jsx("h1",{className:"revival-serif text-3xl mt-1",children:(ve=I.property)==null?void 0:ve.property_address}),e.jsxs("p",{className:"text-white/70 mt-1",children:[((he=I.property)==null?void 0:he.seller_name)??"Homeowner",(Se=I.property)!=null&&Se.city?` · ${I.property.city}, ${I.property.state??""}`:""]}),e.jsxs("div",{className:"mt-5 grid grid-cols-3 gap-4 max-w-md",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-white/50 text-xs uppercase tracking-wider",children:"Original"}),e.jsx("div",{className:"text-lg font-semibold",children:$M((Te=I.property)==null?void 0:Te.original_price)})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-white/50 text-xs uppercase tracking-wider",children:"Final"}),e.jsx("div",{className:"text-lg font-semibold",children:$M((Ie=I.property)==null?void 0:Ie.final_price)})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-white/50 text-xs uppercase tracking-wider",children:"Days on market"}),e.jsx("div",{className:"text-lg font-semibold",children:((Ue=I.property)==null?void 0:Ue.days_on_market)??"—"})]})]}),e.jsxs("div",{className:"mt-6 flex flex-wrap gap-2",children:[e.jsx($,{size:"sm",className:"bg-accent text-accent-foreground hover:bg-accent/90",asChild:!0,children:e.jsxs("a",{href:`/revival/${I.slug}`,target:"_blank",rel:"noreferrer",children:[e.jsx(Ir,{className:"h-3.5 w-3.5 mr-1.5"})," View landing page"]})}),e.jsxs($,{size:"sm",variant:"outline",className:"bg-transparent text-white border-white/25 hover:bg-white/10",onClick:()=>{navigator.clipboard.writeText(R),ae.success("Link copied")},children:[e.jsx(Da,{className:"h-3.5 w-3.5 mr-1.5"})," Copy link"]}),e.jsxs($,{size:"sm",variant:"outline",className:"bg-transparent text-white border-white/25 hover:bg-white/10",disabled:l.isPending,onClick:()=>ee(),children:[l.isPending?e.jsx(Jt,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}):e.jsx(yo,{className:"h-3.5 w-3.5 mr-1.5"}),"Regenerate all"]})]})]}),e.jsxs("div",{className:"relative min-h-[220px]",children:[(Be=I.property)!=null&&Be.photo_url?e.jsx("img",{src:I.property.photo_url,alt:I.property.property_address??"",className:"absolute inset-0 h-full w-full object-cover"}):null,e.jsx("div",{className:"absolute inset-0 bg-gradient-to-r from-[hsl(var(--revival-navy))] via-transparent to-transparent"})]})]})}),e.jsxs(ya,{defaultValue:"journey",className:"mt-6",children:[e.jsx(va,{className:"flex w-full overflow-x-auto no-scrollbar justify-start bg-transparent p-0 gap-2 h-auto",children:["journey","letter","print","landing","plan","emails","texts","scripts","settings"].map(rt=>e.jsx(is,{value:rt,className:"capitalize data-[state=active]:bg-primary data-[state=active]:text-primary-foreground rounded-full border border-border bg-card px-4 py-2 text-sm",children:rt},rt))}),e.jsxs(cs,{value:"journey",className:"mt-6 space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(cB,{className:"h-4 w-4"})," The homeowner's journey, tracked end to end."]}),e.jsx(SYn,{counts:Y})]}),e.jsxs(cs,{value:"letter",className:"mt-6 space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap gap-2 items-center print:hidden",children:[e.jsxs($,{size:"sm",disabled:!P.letter||h==="letter",onClick:U,children:[h==="letter"?e.jsx(Jt,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}):e.jsx(QT,{className:"h-3.5 w-3.5 mr-1.5"}),"Download print-ready PDF"]}),e.jsxs($,{size:"sm",variant:"outline",disabled:!P.letter,onClick:()=>y(rt=>!rt),children:[e.jsx(ui,{className:"h-3.5 w-3.5 mr-1.5"})," ",x?"Close editor":"Edit letter"]}),e.jsxs($,{size:"sm",variant:"outline",disabled:l.isPending,onClick:()=>ee("letter"),children:[e.jsx(kn,{className:"h-3.5 w-3.5 mr-1.5"})," Rewrite letter"]}),e.jsx(be,{value:d,onChange:rt=>u(rt.target.value),placeholder:"Optional instruction: e.g. shorter, warmer, mention the pool",className:"max-w-sm"})]}),x&&P.letter?e.jsx(yKt,{letter:P.letter,saving:o.isPending,onCancel:()=>y(!1),onSave:rt=>{o.mutate({id:s,patch:{content:{...P,letter:rt}}},{onSuccess:()=>y(!1)})}}):null,P.letter?e.jsx(Sjt,{campaign:I,letter:P.letter,url:R,agent:O}):e.jsx("p",{className:"text-muted-foreground",children:"No letter generated yet."})]}),e.jsx(cs,{value:"print",className:"mt-6 space-y-4",children:e.jsxs("div",{className:"revival-tile p-6 space-y-5 max-w-2xl",children:[e.jsxs("div",{children:[e.jsx("div",{className:"revival-eyebrow text-muted-foreground",children:"Print & mail"}),e.jsx("h3",{className:"revival-serif text-2xl mt-1",children:"Print-ready files"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Vector PDFs built at true print size with the QR code baked in — send them to your printer or mail house as-is."})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsxs("div",{className:"rounded-xl border border-border p-4",children:[e.jsx("div",{className:"font-semibold",children:"Personalized letter"}),e.jsx("div",{className:"text-xs text-muted-foreground mt-1",children:"8.5″ × 11″ · letterhead + signature block"}),e.jsxs($,{size:"sm",className:"mt-3",disabled:!P.letter||h==="letter",onClick:U,children:[h==="letter"?e.jsx(Jt,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}):e.jsx(y2,{className:"h-3.5 w-3.5 mr-1.5"}),"Download letter PDF"]})]}),e.jsxs("div",{className:"rounded-xl border border-border p-4",children:[e.jsx("div",{className:"font-semibold",children:"Revival postcard"}),e.jsx("div",{className:"text-xs text-muted-foreground mt-1",children:"6″ × 9″ · front and back, mail-ready"}),e.jsxs($,{size:"sm",className:"mt-3",disabled:h==="postcard",onClick:async()=>{var rt,Ft,Ut,Is,xs,st,dt,jt,gt,rs;m("postcard");try{await oYn({campaign:I,url:R,headline:(rt=P.landing)==null?void 0:rt.headline,subhead:(Ft=P.landing)==null?void 0:Ft.subheadline,message:(Ut=P.landing)==null?void 0:Ut.intro,photoDataUrl:((Is=I.property)==null?void 0:Is.photo_url)??null,agent:{name:(xs=M.data)==null?void 0:xs.name,title:(st=M.data)==null?void 0:st.title,phone:(dt=M.data)==null?void 0:dt.phone,email:(jt=M.data)==null?void 0:jt.email,website_url:(gt=M.data)==null?void 0:gt.website_url,brokerage_name:(rs=M.data)==null?void 0:rs.brokerage_name}}),ae.success("Postcard PDF downloaded")}catch{ae.error("Could not build the postcard PDF")}finally{m(null)}},children:[h==="postcard"?e.jsx(Jt,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}):e.jsx(y2,{className:"h-3.5 w-3.5 mr-1.5"}),"Download postcard PDF"]})]})]}),e.jsxs("div",{className:"rounded-xl bg-muted/50 p-4 text-sm text-muted-foreground",children:["Mailing address on file:"," ",e.jsxs("span",{className:"text-foreground font-medium",children:[((je=I.property)==null?void 0:je.mailing_address)??((Ye=I.property)==null?void 0:Ye.property_address)??"—",(Ee=I.property)!=null&&Ee.mailing_city?`, ${I.property.mailing_city} ${I.property.mailing_state??""} ${I.property.mailing_zip??""}`:""]})]})]})}),e.jsxs(cs,{value:"landing",className:"mt-6 space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap gap-2 items-center",children:[e.jsxs($,{size:"sm",variant:"outline",disabled:l.isPending,onClick:()=>ee("landing"),children:[e.jsx(kn,{className:"h-3.5 w-3.5 mr-1.5"})," Rewrite landing copy"]}),e.jsx($,{size:"sm",variant:"outline",asChild:!0,children:e.jsxs("a",{href:`/revival/${I.slug}`,target:"_blank",rel:"noreferrer",children:[e.jsx(Ir,{className:"h-3.5 w-3.5 mr-1.5"})," Open live page"]})})]}),e.jsxs("div",{className:"grid gap-4 lg:grid-cols-[1fr_auto] items-start",children:[e.jsx(wYn,{campaignId:I.id,content:P,landingConfig:I.landing_config??{},propertyPhotoUrl:(Re=I.property)==null?void 0:Re.photo_url,saving:o.isPending,onSave:rt=>o.mutate({id:I.id,patch:rt})}),e.jsxs("div",{className:"revival-tile p-6 text-center h-fit",children:[e.jsx("div",{className:"revival-eyebrow text-muted-foreground",children:"Campaign QR"}),e.jsx("div",{className:"mt-3",children:e.jsx(jk,{value:R,size:168,level:"M"})}),e.jsx("p",{className:"text-xs text-muted-foreground mt-3 max-w-[180px] break-all",children:R})]})]})]}),e.jsxs(cs,{value:"plan",className:"mt-6 space-y-4",children:[e.jsx("div",{className:"revival-tile p-5",children:e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"revival-eyebrow text-accent-foreground/70",children:"Seller deliverable"}),e.jsx("h3",{className:"revival-serif text-xl mt-1",children:"The Property Revival Plan"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1 max-w-2xl",children:"This is the branded presentation your seller receives after they opt in from the landing page or QR code. Preview it below, download it as a PDF to bring to the listing appointment, or share the live link."})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs($,{size:"sm",variant:"outline",disabled:l.isPending,onClick:()=>ee("plan"),children:[e.jsx(kn,{className:"h-3.5 w-3.5 mr-1.5"})," Rewrite plan"]}),e.jsxs($,{size:"sm",variant:p?"secondary":"outline",onClick:()=>g(rt=>!rt),children:[e.jsx(ui,{className:"h-3.5 w-3.5 mr-1.5"})," ",p?"Done editing":"Edit plan"]}),e.jsx($,{size:"sm",variant:"outline",asChild:!0,children:e.jsxs("a",{href:`/revival/${I.slug}/plan`,target:"_blank",rel:"noreferrer",children:[e.jsx(Ir,{className:"h-3.5 w-3.5 mr-1.5"})," View live plan"]})}),e.jsxs($,{size:"sm",className:"bg-accent text-accent-foreground hover:bg-accent/90",disabled:!P.plan||h==="plan",onClick:H,children:[h==="plan"?e.jsx(Jt,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}):e.jsx(y2,{className:"h-3.5 w-3.5 mr-1.5"}),"Download plan PDF"]})]})]})}),p&&P.plan?e.jsx(NYn,{plan:P.plan,saving:o.isPending,onSave:rt=>o.mutate({id:I.id,patch:{content:{...P,plan:rt}}},{onSuccess:()=>ae.success("Plan updated")})}):null,P.plan?e.jsx("div",{className:"rounded-3xl bg-muted/40 p-4 sm:p-8",children:e.jsx(Uqe,{plan:P.plan,property:{...I.property??{},seller_name:(ke=I.property)==null?void 0:ke.seller_name},agent:O,url:`${$qe()}/revival/${I.slug}/plan`})}):e.jsx("div",{className:"revival-tile p-10 text-center text-muted-foreground",children:"No plan generated yet — use “Rewrite plan”."})]}),e.jsxs(cs,{value:"emails",className:"mt-6 space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs($,{size:"sm",variant:"outline",disabled:l.isPending,onClick:()=>ee("emails"),children:[e.jsx(kn,{className:"h-3.5 w-3.5 mr-1.5"})," Rewrite emails"]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"Each email sends as a fully branded HTML email to contacts you choose."})]}),(P.emails??[]).map((rt,Ft)=>e.jsxs("div",{className:"revival-tile p-5",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsx("div",{className:"font-semibold",children:rt.subject}),e.jsx(qe,{variant:"outline",children:rt.key})]}),e.jsx("div",{className:"text-xs text-muted-foreground mt-0.5",children:rt.preview}),e.jsx("p",{className:"mt-3 text-sm whitespace-pre-wrap leading-relaxed",children:rt.body}),e.jsxs("div",{className:"mt-2 flex flex-wrap gap-1",children:[e.jsxs($,{size:"sm",onClick:()=>_(rt),children:[e.jsx(pn,{className:"h-3.5 w-3.5 mr-1.5"})," Preview & send"]}),e.jsxs($,{size:"sm",variant:"ghost",onClick:()=>{navigator.clipboard.writeText(`${rt.subject} ${rt.body}`),ae.success("Email copied")},children:[e.jsx(Da,{className:"h-3.5 w-3.5 mr-1.5"})," Copy"]})]})]},Ft))]}),e.jsxs(cs,{value:"texts",className:"mt-6 space-y-3",children:[e.jsxs($,{size:"sm",variant:"outline",disabled:l.isPending,onClick:()=>ee("sms"),children:[e.jsx(kn,{className:"h-3.5 w-3.5 mr-1.5"})," Rewrite texts"]}),e.jsx("div",{className:"grid gap-3 sm:grid-cols-2",children:(P.sms??[]).map((rt,Ft)=>e.jsxs("div",{className:"revival-tile p-5",children:[e.jsx(qe,{variant:"outline",children:rt.key}),e.jsx("p",{className:"mt-2 text-sm leading-relaxed",children:rt.body}),e.jsxs($,{size:"sm",variant:"ghost",className:"mt-2",onClick:()=>{navigator.clipboard.writeText(rt.body),ae.success("Text copied")},children:[e.jsx(Da,{className:"h-3.5 w-3.5 mr-1.5"})," Copy"]})]},Ft))})]}),e.jsxs(cs,{value:"scripts",className:"mt-6 space-y-3",children:[e.jsxs($,{size:"sm",variant:"outline",disabled:l.isPending,onClick:()=>ee("scripts"),children:[e.jsx(kn,{className:"h-3.5 w-3.5 mr-1.5"})," Rewrite scripts"]}),[["Phone script",(Fe=P.scripts)==null?void 0:Fe.phone],["Voicemail",(Oe=P.scripts)==null?void 0:Oe.voicemail],["Video script",(Ge=P.scripts)==null?void 0:Ge.video],["Door knock",(yt=P.scripts)==null?void 0:yt.door_knock]].map(([rt,Ft])=>Ft?e.jsxs("div",{className:"revival-tile p-5",children:[e.jsx("div",{className:"font-semibold",children:rt}),e.jsx("p",{className:"mt-2 text-sm whitespace-pre-wrap leading-relaxed",children:Ft})]},rt):null),(((tt=P.scripts)==null?void 0:tt.objections)??[]).length?e.jsxs("div",{className:"revival-tile p-5",children:[e.jsx("div",{className:"font-semibold",children:"Objection handlers"}),e.jsx("div",{className:"mt-3 space-y-3",children:(((ut=P.scripts)==null?void 0:ut.objections)??[]).map((rt,Ft)=>e.jsxs("div",{children:[e.jsxs("div",{className:"text-sm font-medium",children:["“",rt.objection,"”"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:rt.response})]},Ft))})]}):null]}),e.jsx(cs,{value:"settings",className:"mt-6",children:e.jsxs("div",{className:"revival-tile p-6 space-y-5 max-w-xl",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(re,{className:"font-semibold",children:"Landing page live"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Turn off to take the public page offline."})]}),e.jsx(On,{checked:I.published,onCheckedChange:rt=>o.mutate({id:I.id,patch:{published:rt}})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{className:"font-semibold",children:"Campaign name"}),e.jsx(be,{defaultValue:I.name,onBlur:rt=>rt.target.value!==I.name&&o.mutate({id:I.id,patch:{name:rt.target.value}})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{className:"font-semibold",children:"Landing page theme"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Changes the look of the public page instantly."}),e.jsx("div",{className:"grid gap-2 sm:grid-cols-2",children:AYn.map(rt=>e.jsxs("button",{type:"button",onClick:()=>o.mutate({id:I.id,patch:{theme:rt.id}}),className:`text-left rounded-xl border p-3 transition-all ${(I.theme??"estate")===rt.id?"border-accent ring-2 ring-accent/40":"border-border hover:border-accent/50"}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[rt.swatch.map(Ft=>e.jsx("span",{className:"h-4 w-4 rounded-full border border-black/10",style:{background:Ft}},Ft)),e.jsx("span",{className:"font-medium ml-1",children:rt.name})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1.5",children:rt.description})]},rt.id))})]}),e.jsxs("div",{className:"flex items-center justify-between border-t border-border pt-4",children:[e.jsxs("div",{children:[e.jsxs(re,{className:"font-semibold flex items-center gap-1.5",children:[e.jsx(p3,{className:"h-4 w-4"})," Alert me on engagement"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Email me the first time this homeowner scans or visits."})]}),e.jsx(On,{checked:!!I.alert_on_engagement,onCheckedChange:rt=>o.mutate({id:I.id,patch:{alert_on_engagement:rt}})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(re,{className:"font-semibold flex items-center gap-1.5",children:[e.jsx(pn,{className:"h-4 w-4"})," Auto-enroll new leads in a drip"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Sellers who submit the form get added to this campaign automatically."}),e.jsxs(bs,{value:I.drip_campaign_id??"none",onValueChange:rt=>o.mutate({id:I.id,patch:{drip_campaign_id:rt==="none"?null:rt}}),children:[e.jsx(ys,{children:e.jsx(_s,{placeholder:"No drip campaign"})}),e.jsxs(vs,{children:[e.jsx(We,{value:"none",children:"No drip campaign"}),(j.data??[]).map(rt=>e.jsx(We,{value:rt.id,children:rt.name},rt.id))]})]}),!A&&e.jsxs("div",{className:"mt-3 rounded-xl border border-amber-500/30 bg-amber-500/5 p-4",children:[e.jsx("p",{className:"text-sm font-semibold text-foreground",children:"Recommended: Expired Listing Revival (8 emails, 45 days)"}),e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:"A luxury-styled nurture written for homeowners whose listing expired — confirmation, why homes expire, the 5-part relaunch plan, pricing truth, presentation, a case study, and two graceful closes."}),e.jsx($,{size:"sm",className:"mt-3",disabled:C.isPending,onClick:()=>C.mutate(),children:C.isPending?"Installing…":"Install & assign to this campaign"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{className:"font-semibold",children:"Internal notes"}),e.jsx(Ls,{rows:4,defaultValue:((nt=I.branding)==null?void 0:nt.notes)??"",onBlur:rt=>o.mutate({id:I.id,patch:{branding:{...I.branding,notes:rt.target.value}}})})]}),e.jsx("div",{className:"border-t border-border pt-4",children:e.jsxs($,{variant:"destructive",size:"sm",onClick:async()=>{await io("Delete this campaign? The landing page will stop working.")&&c.mutate(I.id,{onSuccess:()=>t("/apps/listing-revival")})},children:[e.jsx(Un,{className:"h-3.5 w-3.5 mr-1.5"})," Delete campaign"]})})]})})]}),P.letter?e.jsx("div",{ref:B,"aria-hidden":!0,className:"pointer-events-none fixed left-[-10000px] top-0 w-[816px]",children:e.jsx(Sjt,{campaign:I,letter:P.letter,url:R,agent:O,className:"shadow-none"})}):null,P.plan?e.jsx("div",{ref:G,"aria-hidden":!0,className:"pointer-events-none fixed left-[-10000px] top-0 w-[816px]",children:e.jsx(Uqe,{plan:P.plan,property:{...I.property??{},seller_name:(et=I.property)==null?void 0:et.seller_name},agent:O,url:`${$qe()}/revival/${I.slug}/plan`})}):null]}),e.jsx(CYn,{open:!!v,onOpenChange:rt=>!rt&&_(null),campaignId:I.id,email:v,ctaUrl:R,seller:{name:(at=I.property)==null?void 0:at.seller_name,email:(wt=I.property)==null?void 0:wt.seller_email}})]})}function vKt(){const{user:s}=ks();return pt({queryKey:["fsbo-campaigns",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await V.from("fsbo_campaigns").select("*, property:fsbo_properties(*)").order("created_at",{ascending:!1});if(n)throw n;return t??[]}})}function TYn(s){return pt({queryKey:["fsbo-campaign",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await V.from("fsbo_campaigns").select("*, property:fsbo_properties(*)").eq("id",s).maybeSingle();if(n)throw n;return t??null}})}function bKt(){const{user:s}=ks();return pt({queryKey:["fsbo-properties",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await V.from("fsbo_properties").select("*").order("created_at",{ascending:!1});if(n)throw n;return t??[]}})}function wJe(){const{user:s}=ks();return pt({queryKey:["fsbo-leads",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await V.from("fsbo_leads").select("*").order("created_at",{ascending:!1});if(n)throw n;return t??[]}})}function MYn(){const{user:s}=ks();return pt({queryKey:["fsbo-tasks",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await V.from("fsbo_tasks").select("*").order("due_date",{ascending:!0});if(n)throw n;return t??[]}})}function jJe(){const{user:s}=ks();return pt({queryKey:["fsbo-events",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await V.from("fsbo_events").select("*").order("created_at",{ascending:!1}).limit(1e3);if(n)throw n;return t??[]}})}function NJe(){const s=ls(),t=()=>{["fsbo-campaigns","fsbo-campaign","fsbo-properties","fsbo-leads","fsbo-tasks","fsbo-events"].forEach(o=>s.invalidateQueries({queryKey:[o]}))},n=Nt({mutationFn:async o=>{const{data:c,error:d}=await V.functions.invoke("fsbo-generate",{body:o});if(d)throw d;if(c!=null&&c.error)throw new Error(String(c.error));return c},onSuccess:t,onError:o=>ae.error(o.message)}),r=Nt({mutationFn:async o=>{const{error:c}=await V.from("fsbo_campaigns").update(o.patch).eq("id",o.id);if(c)throw c},onSuccess:()=>{t(),ae.success("Saved")},onError:o=>ae.error(o.message)}),a=Nt({mutationFn:async o=>{const{error:c}=await V.from("fsbo_campaigns").delete().eq("id",o);if(c)throw c},onSuccess:()=>{t(),ae.success("Campaign deleted")},onError:o=>ae.error(o.message)}),i=Nt({mutationFn:async o=>{const{error:c}=await V.from("fsbo_campaigns").update({status:o.archived?"archived":"draft",published:!o.archived}).eq("id",o.id);if(c)throw c;return o},onSuccess:o=>{t(),ae.success(o.archived?"Campaign archived":"Campaign restored")},onError:o=>ae.error(o.message)}),l=Nt({mutationFn:async o=>{const{error:c}=await V.from("fsbo_tasks").update({completed_at:o.done?new Date().toISOString():null}).eq("id",o.id);if(c)throw c},onSuccess:t,onError:o=>ae.error(o.message)});return{generate:n,saveCampaign:r,deleteCampaign:a,archiveCampaign:i,toggleTask:l,invalidate:t}}function PYn(s){const t=(s??"").trim();if(!t)return null;const n=t.match(/(?:youtube\.com\/(?:watch\?v=|embed\/|shorts\/)|youtu\.be\/)([\w-]{6,})/);if(n)return{kind:"iframe",src:`https://www.youtube.com/embed/${n[1]}`};const r=t.match(/vimeo\.com\/(?:video\/)?(\d+)/);if(r)return{kind:"iframe",src:`https://player.vimeo.com/video/${r[1]}`};const a=t.match(/loom\.com\/(?:share|embed)\/([\w-]+)/);return a?{kind:"iframe",src:`https://www.loom.com/embed/${a[1]}`}:/\.(mp4|webm|mov|m4v)(\?|$)/i.test(t)?{kind:"file",src:t}:{kind:"iframe",src:t}}const bCe=[{id:"market_expert",name:"Market Expert",tagline:"Data, not pressure",description:"Consultative and informed. Shows the seller what the market is actually doing without pushing them toward an agent.",accent:"from-teal-500/20 to-teal-500/0",previewHeadline:"What the Market Is Really Telling You",previewBody:"A clear look at buyer activity, pricing, and the places FSBO sellers most often miss."},{id:"friendly_neighbor",name:"Friendly Neighbor",tagline:"Helpful advice first",description:"Warm and personal — feels like a neighbor who knows the street and wants the best outcome.",accent:"from-amber-500/20 to-amber-500/0",previewHeadline:"A Friendly Note From the Neighborhood",previewBody:"I saw your home is for sale by owner and I wanted to share a guide that might help."},{id:"professional_review",name:"Professional Review",tagline:"Structured & credible",description:"Polished and businesslike. A clear assessment of the FSBO process with a proven next-step plan.",accent:"from-indigo-500/20 to-indigo-500/0",previewHeadline:"A Professional FSBO Review",previewBody:"An honest, structured look at the advantages, risks, and what a pro would watch."},{id:"equity_advocate",name:"Equity Advocate",tagline:"Maximize net proceeds",description:"Focuses on the money. Helps the seller understand hidden costs and the math behind selling alone.",accent:"from-emerald-500/20 to-emerald-500/0",previewHeadline:"The True Math of Selling On Your Own",previewBody:"Commission isn't the only number that matters. Here's what to count before you decide."},{id:"second_opinion",name:"Second Opinion",tagline:"No pressure perspective",description:"Respectful and non-defensive. Offers a free second opinion for a smart seller who may simply want a fresh set of eyes.",accent:"from-sky-500/20 to-sky-500/0",previewHeadline:"Would a Second Opinion Help?",previewBody:"You know your home best. I just want to offer a free, no-obligation perspective if it's useful."}],_Kt=[{id:"professional",name:"Professional",note:"Polished and businesslike"},{id:"friendly",name:"Friendly",note:"Warm and conversational"},{id:"consultative",name:"Consultative",note:"Curious and patient"},{id:"minimal",name:"Minimal",note:"Short and direct"},{id:"modern",name:"Modern",note:"Crisp and confident"}],IYn=[{value:"single_family",label:"Single Family"},{value:"condo",label:"Condo"},{value:"townhouse",label:"Townhouse"},{value:"multi_family",label:"Multi-Family"},{value:"land",label:"Land"},{value:"luxury",label:"Luxury"},{value:"commercial",label:"Commercial"},{value:"other",label:"Other"}],LYn=[{value:"immediately",label:"As soon as possible"},{value:"0-30",label:"In the next 30 days"},{value:"1-3",label:"In the next 1–3 months"},{value:"3-6",label:"In 3–6 months"},{value:"6-12",label:"In 6–12 months"},{value:"just_curious",label:"Just curious for now"}],RYn=["Need to sell quickly","Want to maximize net proceeds","Testing the market","Already bought another home","Relocating","Downsizing / Upsizing","Estate sale","Other"],DYn=[{value:"email",label:"Email"},{value:"phone",label:"Phone"},{value:"text",label:"Text"}];function qqe(s){return s.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)}function OYn(s){const t=qqe(s)||"property",n=Math.random().toString(36).slice(2,7);return`${t}-${n}`}function wKt(s){return s==null?"—":`$${Number(s).toLocaleString("en-US",{maximumFractionDigits:0})}`}function FYn(){return typeof window>"u"?"":window.location.origin}function jKt(s){return`${FYn()}/fsbo/${s}`}const Ejt="fsbo_breakthrough";function zYn(){const{user:s,loading:t,isAdmin:n}=ks(),{data:r}=pt({queryKey:["feature-entitlement",Ejt,s==null?void 0:s.id],enabled:!!s&&!n,staleTime:5*60*1e3,queryFn:async()=>{const{data:a,error:i}=await V.from("feature_entitlements").select("enabled, expires_at, tier").eq("user_id",s.id).eq("feature_key",Ejt).maybeSingle();if(i)throw i;return{tier:(a==null?void 0:a.tier)??null}}});return{hasAccess:!0,tier:n?"admin":(r==null?void 0:r.tier)??null,isLoading:t}}const BYn=[{id:"dashboard",label:"Dashboard",icon:zp},{id:"campaigns",label:"Campaigns",icon:kn},{id:"properties",label:"Properties",icon:ua},{id:"letters",label:"Letters",icon:pn},{id:"landing",label:"Landing Pages",icon:kc},{id:"guides",label:"Seller Guides",icon:ea},{id:"followup",label:"Follow Up",icon:lv},{id:"analytics",label:"Analytics",icon:Ul},{id:"templates",label:"Templates",icon:Zw},{id:"settings",label:"Settings",icon:eM}];function yS({label:s,value:t,icon:n,delay:r=0,hint:a}){return e.jsxs(_r.div,{initial:{opacity:0,y:14},animate:{opacity:1,y:0},transition:{delay:r,duration:.45,ease:[.22,1,.36,1]},className:"fsbo-tile p-5",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsx("span",{className:"fsbo-eyebrow text-muted-foreground",children:s}),e.jsx(n,{className:"h-4 w-4 text-accent"})]}),e.jsx("div",{className:"mt-3 text-3xl font-bold tabular-nums tracking-tight",children:t}),a?e.jsx("div",{className:"text-xs text-muted-foreground mt-1",children:a}):null]})}function $Yn(){const s=Jn(),[t,n]=k.useState("dashboard"),[r,a]=k.useState(""),[i,l]=k.useState(!1),[o,c]=k.useState(null);zYn();const d=vKt(),u=bKt(),h=wJe(),m=MYn(),p=jJe(),{toggleTask:g,archiveCampaign:x,deleteCampaign:y}=NJe(),v=d.data??[],_=h.data??[],j=p.data??[],C=m.data??[],A=k.useMemo(()=>{const G=H=>j.filter(Y=>Y.event_type===H).length;return{properties:(u.data??[]).length,campaigns:v.length,letters:v.filter(H=>{var Y;return(Y=H.content)==null?void 0:Y.letter}).length,qr:G("qr_scan"),visits:G("page_view"),guideViews:G("guide_view"),leads:_.length,appointments:G("appointment"),listed:_.filter(H=>H.temperature==="hot").length,hot:_.filter(H=>H.temperature==="hot").length}},[v,_,j,u.data]),M=k.useMemo(()=>{const G=[];for(let H=13;H>=0;H--){const Y=new Date(Date.now()-H*864e5),se=Y.toISOString().slice(0,10);G.push({day:Ys(Y,"MMM d"),visits:j.filter(ee=>ee.event_type==="page_view"&&ee.created_at.startsWith(se)).length,scans:j.filter(ee=>ee.event_type==="qr_scan"&&ee.created_at.startsWith(se)).length,leads:_.filter(ee=>ee.created_at.startsWith(se)).length})}return G},[j,_]),I=G=>G.status==="archived",P=v.filter(G=>{var Y,se;if(i?!I(G):I(G))return!1;const H=r.trim().toLowerCase();return H?`${G.name} ${((Y=G.property)==null?void 0:Y.property_address)??""} ${((se=G.property)==null?void 0:se.seller_name)??""}`.toLowerCase().includes(H):!0}),R=v.filter(I).length,O=G=>s(`/apps/fsbo-breakthrough/campaigns/${G}`),B=G=>{navigator.clipboard.writeText(jKt(G)),ae.success("Landing page link copied")},U=G=>e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs("div",{className:"relative max-w-sm flex-1 min-w-[200px]",children:[e.jsx(Yr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{value:r,onChange:H=>a(H.target.value),placeholder:"Search campaigns…",className:"pl-9"})]}),e.jsxs($,{variant:i?"default":"outline",size:"sm",onClick:()=>l(H=>!H),children:[e.jsx(kf,{className:"h-3.5 w-3.5 mr-1.5"}),i?"Viewing archived":`Archived (${R})`]})]}),P.length===0?e.jsx("div",{className:"fsbo-tile p-10 text-center text-muted-foreground",children:i?"No archived campaigns.":G}):e.jsx("div",{className:"grid gap-3 md:grid-cols-2 xl:grid-cols-3",children:P.map((H,Y)=>{var Q,te,le,fe;const se=bCe.find(_e=>_e.id===H.style),ee=_.filter(_e=>_e.campaign_id===H.id).length,oe=j.filter(_e=>_e.campaign_id===H.id&&_e.event_type==="page_view").length,me=I(H);return e.jsxs(_r.div,{initial:{opacity:0,y:14},animate:{opacity:1,y:0},transition:{delay:Math.min(Y*.04,.3),duration:.4},className:Ot("fsbo-tile overflow-hidden",me&&"opacity-80"),children:[e.jsxs("div",{className:"h-28 bg-muted relative",children:[(Q=H.property)!=null&&Q.photo_url?e.jsx("img",{src:H.property.photo_url,alt:H.property.property_address??"",className:"h-full w-full object-cover",loading:"lazy"}):e.jsx("div",{className:"h-full w-full fsbo-dark grid place-items-center",children:e.jsx(ua,{className:"h-7 w-7 text-accent"})}),e.jsx(qe,{className:"absolute top-3 left-3 bg-background/90 text-foreground border-0",children:(se==null?void 0:se.name)??H.style}),me?e.jsx(qe,{className:"absolute top-3 right-3 bg-foreground/85 text-background border-0",children:"Archived"}):null]}),e.jsxs("div",{className:"p-4",children:[e.jsx("div",{className:"font-semibold leading-tight",children:((te=H.property)==null?void 0:te.property_address)??H.name}),e.jsx("div",{className:"text-sm text-muted-foreground",children:((le=H.property)==null?void 0:le.seller_name)??"Homeowner"}),e.jsxs("div",{className:"mt-3 flex items-center gap-4 text-xs text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(kc,{className:"h-3.5 w-3.5"}),oe]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Xn,{className:"h-3.5 w-3.5"}),ee]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ua,{className:"h-3.5 w-3.5"}),((fe=H.property)==null?void 0:fe.property_type)??"—"]})]}),e.jsxs("div",{className:"mt-4 flex gap-2",children:[e.jsxs($,{size:"sm",className:"flex-1",onClick:()=>O(H.id),children:["Open ",e.jsx(xi,{className:"h-3.5 w-3.5 ml-1"})]}),e.jsx($,{size:"sm",variant:"outline",onClick:()=>B(H.slug),children:e.jsx(Da,{className:"h-3.5 w-3.5"})}),e.jsx($,{size:"sm",variant:"outline",asChild:!0,children:e.jsx("a",{href:`/fsbo/${H.slug}`,target:"_blank",rel:"noreferrer",children:e.jsx(Ir,{className:"h-3.5 w-3.5"})})}),e.jsxs(Au,{children:[e.jsx(Eu,{asChild:!0,children:e.jsx($,{size:"sm",variant:"outline",children:e.jsx(Z0,{className:"h-3.5 w-3.5"})})}),e.jsxs(gu,{align:"end",children:[e.jsx(Pa,{onClick:()=>x.mutate({id:H.id,archived:!me}),children:me?e.jsxs(e.Fragment,{children:[e.jsx(OT,{className:"h-4 w-4 mr-2"})," Restore campaign"]}):e.jsxs(e.Fragment,{children:[e.jsx(kf,{className:"h-4 w-4 mr-2"})," Archive campaign"]})}),e.jsx(j0,{}),e.jsxs(Pa,{className:"text-destructive focus:text-destructive",onClick:()=>{var _e;return c({id:H.id,name:((_e=H.property)==null?void 0:_e.property_address)??H.name})},children:[e.jsx(Un,{className:"h-4 w-4 mr-2"})," Delete permanently"]})]})]})]})]})]},H.id)})}),e.jsx(oc,{open:!!o,onOpenChange:H=>!H&&c(null),children:e.jsxs(Ql,{children:[e.jsxs(Jl,{children:[e.jsx(tc,{children:"Delete this campaign?"}),e.jsxs(sc,{children:[o==null?void 0:o.name," — the letter, landing page, QR link, seller guide and follow-up tasks will be permanently removed. This can't be undone. Archive instead if you may need it later."]})]}),e.jsxs(ec,{children:[e.jsx(nc,{children:"Cancel"}),e.jsx(Vl,{className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",onClick:()=>{o&&y.mutate(o.id),c(null)},children:"Delete permanently"})]})]})})]});return e.jsx(Xs,{title:"By-Owner Breakthrough",children:e.jsxs("div",{className:"fsbo-theme relative -m-4 sm:-m-6 p-4 sm:p-6 min-h-[calc(100vh-4rem)]",children:[e.jsxs(_r.div,{initial:{opacity:0,y:18},animate:{opacity:1,y:0},transition:{duration:.55,ease:[.22,1,.36,1]},className:"fsbo-dark rounded-3xl px-6 sm:px-10 py-9 relative overflow-hidden",children:[e.jsx("div",{className:"absolute -right-10 -top-16 h-56 w-56 rounded-full bg-accent/20 blur-3xl"}),e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"fsbo-eyebrow text-accent",children:"By-Owner Breakthrough"}),e.jsx("h1",{className:"fsbo-serif text-3xl sm:text-[42px] leading-tight mt-2 max-w-2xl",children:"Turn FSBOs Into Listing Appointments."}),e.jsx("p",{className:"text-white/70 mt-3 max-w-xl",children:"Add a for-sale-by-owner property, choose a voice, and generate a complete campaign: letter, QR code, landing page, seller guide, scripts, and follow-up tasks."}),e.jsxs("div",{className:"mt-6 flex flex-wrap gap-3",children:[e.jsxs($,{size:"lg",className:"bg-accent text-accent-foreground hover:bg-accent/90",onClick:()=>s("/apps/fsbo-breakthrough/new"),children:[e.jsx(nn,{className:"h-4 w-4 mr-1"})," New Campaign"]}),e.jsx($,{size:"lg",variant:"outline",className:"bg-transparent text-white border-white/25 hover:bg-white/10",onClick:()=>n("campaigns"),children:"View campaigns"})]})]})]}),e.jsxs(ya,{value:t,onValueChange:n,className:"mt-6",children:[e.jsx(va,{className:"flex w-full overflow-x-auto no-scrollbar justify-start bg-transparent p-0 gap-2 h-auto",children:BYn.map(G=>e.jsxs(is,{value:G.id,className:"data-[state=active]:bg-primary data-[state=active]:text-primary-foreground rounded-full border border-border bg-card px-4 py-2 text-sm whitespace-nowrap",children:[e.jsx(G.icon,{className:"h-3.5 w-3.5 mr-1.5"}),G.label]},G.id))}),e.jsxs(cs,{value:"dashboard",className:"mt-6 space-y-6",children:[e.jsxs("div",{className:"grid gap-3 grid-cols-2 lg:grid-cols-5",children:[e.jsx(yS,{label:"Properties",value:A.properties,icon:ua,delay:0}),e.jsx(yS,{label:"Campaigns",value:A.campaigns,icon:kn,delay:.04}),e.jsx(yS,{label:"Letters",value:A.letters,icon:pn,delay:.08}),e.jsx(yS,{label:"QR Scans",value:A.qr,icon:Bx,delay:.12}),e.jsx(yS,{label:"Page Visits",value:A.visits,icon:kc,delay:.16}),e.jsx(yS,{label:"Guide Views",value:A.guideViews,icon:ea,delay:.2}),e.jsx(yS,{label:"Seller Leads",value:A.leads,icon:Xn,delay:.24}),e.jsx(yS,{label:"Appointments",value:A.appointments,icon:fb,delay:.28}),e.jsx(yS,{label:"Hot Leads",value:A.hot,icon:iu,delay:.32,hint:"Score 75+"}),e.jsx(yS,{label:"Listings Won",value:A.listed,icon:ql,delay:.36})]}),e.jsxs("div",{className:"grid gap-4 lg:grid-cols-3",children:[e.jsxs("div",{className:"fsbo-tile p-5 lg:col-span-2",children:[e.jsx("div",{className:"fsbo-eyebrow text-muted-foreground",children:"Last 14 days"}),e.jsx("div",{className:"text-lg font-semibold mt-1",children:"Homeowner engagement"}),e.jsx("div",{className:"h-64 mt-4",children:e.jsx(C_,{width:"100%",height:"100%",children:e.jsxs(yZe,{data:M,children:[e.jsxs("defs",{children:[e.jsxs("linearGradient",{id:"fsboVisits",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:"hsl(var(--primary))",stopOpacity:.4}),e.jsx("stop",{offset:"100%",stopColor:"hsl(var(--primary))",stopOpacity:0})]}),e.jsxs("linearGradient",{id:"fsboLeads",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:"hsl(var(--accent))",stopOpacity:.5}),e.jsx("stop",{offset:"100%",stopColor:"hsl(var(--accent))",stopOpacity:0})]})]}),e.jsx(XO,{strokeDasharray:"3 3",stroke:"hsl(var(--border))",vertical:!1}),e.jsx(Cb,{dataKey:"day",tick:{fontSize:11},stroke:"hsl(var(--muted-foreground))"}),e.jsx(Ab,{allowDecimals:!1,tick:{fontSize:11},stroke:"hsl(var(--muted-foreground))",width:28}),e.jsx(vg,{contentStyle:{borderRadius:12,border:"1px solid hsl(var(--border))"}}),e.jsx(A_,{type:"monotone",dataKey:"visits",stroke:"hsl(var(--primary))",fill:"url(#fsboVisits)",strokeWidth:2}),e.jsx(A_,{type:"monotone",dataKey:"leads",stroke:"hsl(var(--accent))",fill:"url(#fsboLeads)",strokeWidth:2})]})})})]}),e.jsxs("div",{className:"fsbo-tile p-5",children:[e.jsx("div",{className:"fsbo-eyebrow text-muted-foreground",children:"Next up"}),e.jsx("div",{className:"text-lg font-semibold mt-1",children:"Your tasks"}),e.jsxs("div",{className:"mt-4 space-y-2",children:[C.filter(G=>!G.completed_at).slice(0,5).map(G=>e.jsxs("div",{className:"flex items-start gap-3 p-3 rounded-lg bg-muted/40",children:[e.jsx(Li,{checked:!!G.completed_at,onCheckedChange:H=>g.mutate({id:G.id,done:!!H})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-sm font-medium",children:G.title}),e.jsx("div",{className:"text-xs text-muted-foreground",children:G.detail}),G.due_date?e.jsxs("div",{className:"text-xs text-muted-foreground mt-1",children:["Due ",G.due_date]}):null]})]},G.id)),!C.filter(G=>!G.completed_at).length&&e.jsx("div",{className:"text-sm text-muted-foreground py-4 text-center",children:"No open tasks — create a campaign to get started."})]})]})]})]}),e.jsx(cs,{value:"campaigns",className:"mt-6",children:U("No campaigns yet. Start with a new FSBO property.")}),e.jsx(cs,{value:"properties",className:"mt-6",children:e.jsx("div",{className:"space-y-3",children:(u.data??[]).length===0?e.jsx("div",{className:"fsbo-tile p-10 text-center text-muted-foreground",children:"No FSBO properties added yet."}):e.jsx("div",{className:"grid gap-3 md:grid-cols-2 lg:grid-cols-3",children:(u.data??[]).map(G=>e.jsxs("div",{className:"fsbo-tile p-4",children:[e.jsx("div",{className:"font-semibold",children:G.property_address}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[G.city,G.city&&G.state?", ":"",G.state]}),e.jsx("div",{className:"mt-2 text-sm",children:G.seller_name||"—"}),e.jsxs("div",{className:"mt-1 text-sm text-muted-foreground",children:["Est. value ",wKt(G.estimated_value)]})]},G.id))})})}),e.jsx(cs,{value:"followup",className:"mt-6",children:e.jsxs("div",{className:"fsbo-tile p-5",children:[e.jsx("div",{className:"text-lg font-semibold",children:"All follow-up tasks"}),e.jsx("div",{className:"mt-4 space-y-2",children:C.map(G=>e.jsxs("div",{className:Ot("flex items-start gap-3 p-3 rounded-lg",G.completed_at?"bg-muted/30":"bg-muted/40"),children:[e.jsx(Li,{checked:!!G.completed_at,onCheckedChange:H=>g.mutate({id:G.id,done:!!H})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:Ot("text-sm font-medium",G.completed_at&&"line-through text-muted-foreground"),children:G.title}),e.jsx("div",{className:"text-xs text-muted-foreground",children:G.detail}),e.jsxs("div",{className:"text-xs text-muted-foreground mt-1 capitalize",children:[G.channel," · ",G.due_date??"No due date"]})]})]},G.id))})]})}),e.jsx(cs,{value:"analytics",className:"mt-6",children:e.jsxs("div",{className:"fsbo-tile p-5",children:[e.jsx("div",{className:"text-lg font-semibold",children:"Recent events"}),e.jsx("div",{className:"mt-4 space-y-2",children:j.slice(0,50).map(G=>e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg bg-muted/40",children:[e.jsx("div",{className:"text-sm capitalize",children:G.event_type.replace(/_/g," ")}),e.jsx("div",{className:"text-xs text-muted-foreground",children:Ys(new Date(G.created_at),"MMM d, h:mm a")})]},G.id))})]})}),e.jsx(cs,{value:"letters",className:"mt-6",children:U("Generate letter content by creating a campaign first.")}),e.jsx(cs,{value:"landing",className:"mt-6",children:U("Generate landing pages by creating a campaign first.")}),e.jsx(cs,{value:"guides",className:"mt-6",children:U("Generate seller guides by creating a campaign first.")}),e.jsx(cs,{value:"templates",className:"mt-6",children:e.jsx("div",{className:"grid gap-3 md:grid-cols-2 lg:grid-cols-3",children:_Kt.map(G=>e.jsxs("div",{className:"fsbo-tile p-4",children:[e.jsx("div",{className:"font-semibold",children:G.name}),e.jsx("div",{className:"text-sm text-muted-foreground",children:G.note})]},G.id))})}),e.jsx(cs,{value:"settings",className:"mt-6",children:e.jsxs("div",{className:"fsbo-tile p-5 max-w-xl",children:[e.jsx("div",{className:"text-lg font-semibold",children:"Settings"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-2",children:"Campaign style, tone, and landing page settings are managed inside each campaign."})]})})]})]})})}const Tjt=["Add the property","Choose the campaign voice","Generate everything"];function UYn(){const s=Jn(),{user:t}=ks(),{generate:n,invalidate:r}=NJe(),[a,i]=k.useState(0),[l,o]=k.useState(!1),[c,d]=k.useState(bCe[0].id),[u,h]=k.useState("professional"),[m,p]=k.useState({property_address:"",city:"",state:"",zip:"",property_type:"single_family",estimated_value:"",seller_name:"",seller_email:"",seller_phone:"",notes:"",photo_url:""}),g=(_,j)=>p(C=>({...C,[_]:j})),x=a===0?m.property_address.trim().length>3:!0,y=async()=>{if(t){o(!0);try{const{data:_,error:j}=await V.from("fsbo_properties").insert({owner_user_id:t.id,property_address:m.property_address.trim(),city:m.city||null,state:m.state||null,zip:m.zip||null,property_type:m.property_type||"single_family",estimated_value:m.estimated_value?Number(m.estimated_value):null,seller_name:m.seller_name||null,seller_email:m.seller_email||null,seller_phone:m.seller_phone||null,notes:m.notes||null,photo_url:m.photo_url||null}).select().single();if(j)throw j;const{data:C,error:A}=await V.from("fsbo_campaigns").insert({owner_user_id:t.id,property_id:_.id,name:m.property_address.trim(),slug:OYn(m.property_address),style:c,tone:u,status:"generating",published:!0}).select().single();if(A)throw A;await n.mutateAsync({campaignId:C.id}),r(),ae.success("Campaign built — everything is ready."),s(`/apps/fsbo-breakthrough/campaigns/${C.id}`)}catch(_){ae.error(_ instanceof Error?_.message:"Could not create the campaign")}finally{o(!1)}}},v=(_,j,C={})=>e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{className:"text-xs uppercase tracking-wider text-muted-foreground",children:j}),e.jsx(be,{value:m[_],onChange:A=>g(_,A.target.value),...C})]});return e.jsx(Xs,{title:"New FSBO Campaign",children:e.jsxs("div",{className:"fsbo-theme -m-4 sm:-m-6 p-4 sm:p-6 min-h-[calc(100vh-4rem)]",children:[e.jsxs($,{variant:"ghost",size:"sm",className:"gap-2 mb-4",onClick:()=>s("/apps/fsbo-breakthrough"),children:[e.jsx(Ia,{className:"h-4 w-4"})," Back to By-Owner Breakthrough"]}),e.jsx("div",{className:"flex items-center gap-3 mb-6",children:Tjt.map((_,j)=>e.jsxs("div",{className:"flex items-center gap-3 flex-1",children:[e.jsx("div",{className:Ot("h-9 w-9 rounded-full grid place-items-center text-sm font-bold shrink-0 transition-colors",jg("property_type",_.target.value),children:IYn.map(_=>e.jsx("option",{value:_.value,children:_.label},_.value))})]}),v("seller_name","Seller name"),v("seller_email","Seller email",{type:"email"}),v("seller_phone","Seller phone")]}),e.jsxs("div",{className:"grid gap-4 lg:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"Property photo"}),e.jsx(bte,{value:m.photo_url,onChange:_=>g("photo_url",_??""),label:"Property photo",prefix:"fsbo-property"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"Agent notes"}),e.jsx(Ls,{rows:6,value:m.notes,onChange:_=>g("notes",_.target.value),placeholder:"Anything you know: asking price, why they're selling solo, motivation, photos, etc."})]})]})]}):null,a===1?e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"fsbo-tile p-6",children:[e.jsx("div",{className:"fsbo-eyebrow text-muted-foreground",children:"Step two"}),e.jsx("h2",{className:"fsbo-serif text-2xl mt-1",children:"Pick the voice of the campaign"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"The style shapes the letter, the landing page and the whole follow-up sequence."}),e.jsx("div",{className:"grid gap-3 mt-5 md:grid-cols-2 xl:grid-cols-3",children:bCe.map(_=>e.jsxs("button",{onClick:()=>d(_.id),className:Ot("text-left p-5 rounded-xl border transition-all relative overflow-hidden",c===_.id?"border-primary bg-primary/5":"border-border bg-card hover:border-primary/30"),children:[e.jsx("div",{className:Ot("absolute inset-x-0 top-0 h-1 bg-gradient-to-r",_.accent)}),e.jsx("div",{className:"font-semibold",children:_.name}),e.jsx("div",{className:"text-xs text-muted-foreground mt-1",children:_.tagline}),e.jsx("div",{className:"text-sm text-muted-foreground mt-2",children:_.description}),e.jsx("div",{className:"mt-3 text-xs text-primary font-medium",children:_.previewHeadline}),e.jsx("div",{className:"text-xs text-muted-foreground",children:_.previewBody})]},_.id))})]}),e.jsxs("div",{className:"fsbo-tile p-6",children:[e.jsx("div",{className:"fsbo-eyebrow text-muted-foreground",children:"Letter tone"}),e.jsx("div",{className:"grid gap-3 mt-3 sm:grid-cols-2 lg:grid-cols-5",children:_Kt.map(_=>e.jsxs("button",{onClick:()=>h(_.id),className:Ot("p-4 rounded-xl border text-left transition-all",u===_.id?"border-primary bg-primary/5":"border-border bg-card hover:border-primary/30"),children:[e.jsx("div",{className:"font-medium",children:_.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:_.note})]},_.id))})]})]}):null,a===2?e.jsxs("div",{className:"fsbo-tile p-10 text-center",children:[e.jsx("div",{className:"mx-auto h-14 w-14 rounded-full bg-primary/10 grid place-items-center mb-4",children:e.jsx(vf,{className:"h-6 w-6 text-primary"})}),e.jsx("h2",{className:"fsbo-serif text-2xl",children:"Ready to build your campaign"}),e.jsxs("p",{className:"text-muted-foreground mt-2 max-w-md mx-auto",children:["We'll generate the letter, landing page, seller guide, follow-up scripts, and task sequence for",e.jsxs("span",{className:"font-semibold text-foreground",children:[" ",m.property_address||"this property"]}),"."]}),e.jsx("div",{className:"mt-6 flex justify-center",children:e.jsxs($,{size:"lg",onClick:y,disabled:l,children:[l?e.jsx(Jt,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(kn,{className:"h-4 w-4 mr-2"}),"Generate campaign"]})})]}):null]},a)}),e.jsxs("div",{className:"flex justify-between mt-6",children:[e.jsxs($,{variant:"outline",disabled:a===0,onClick:()=>i(_=>_-1),children:[e.jsx(Ia,{className:"h-4 w-4 mr-1"})," Back"]}),a<2&&e.jsxs($,{disabled:!x,onClick:()=>i(_=>_+1),children:["Next ",e.jsx(xi,{className:"h-4 w-4 ml-1"})]})]})]})})}function qYn(){var te,le,fe,_e,ve,he,Se,Te,Ie,Ue,Be,je,Ye,Ee,Re,ke;const{id:s}=oo(),t=Jn(),{user:n}=ks(),r=TYn(s),a=jJe(),i=wJe(),{generate:l,saveCampaign:o,deleteCampaign:c}=NJe(),[d,u]=k.useState(""),[h,m]=k.useState(!1),[p,g]=k.useState("letter"),[x,y]=k.useState(!1),v=r.data,_=(v==null?void 0:v.content)??{},j=v?jKt(v.slug):"",C=pt({queryKey:["fsbo-agent-profile",n==null?void 0:n.id],enabled:!!n,queryFn:async()=>{const{data:Fe}=await V.from("profiles").select("name, email, phone, avatar_url, brokerage_name, website_url, title").eq("id",n.id).maybeSingle();return Fe}}),A={name:(te=C.data)==null?void 0:te.name,title:(le=C.data)==null?void 0:le.title,phone:(fe=C.data)==null?void 0:fe.phone,email:(_e=C.data)==null?void 0:_e.email,website_url:(ve=C.data)==null?void 0:ve.website_url,avatar_url:(he=C.data)==null?void 0:he.avatar_url,brokerage_name:(Se=C.data)==null?void 0:Se.brokerage_name},M=k.useRef(null),I=k.useRef(null),P=k.useMemo(()=>{var Ge,yt;const Fe=(a.data??[]).filter(tt=>tt.campaign_id===s),Oe={};return Fe.forEach(tt=>{Oe[tt.event_type]=(Oe[tt.event_type]??0)+1}),Oe.letter=_.letter?1:0,Oe.email=((Ge=_.emails)==null?void 0:Ge.length)??0,Oe.sms=((yt=_.sms)==null?void 0:yt.length)??0,Oe.form_submit=(i.data??[]).filter(tt=>tt.campaign_id===s).length,Oe},[a.data,i.data,s,_]),R=async()=>{var Fe;if(M.current){m(!0);try{const Oe=await PU(M.current,{pixelRatio:2}),Ge=document.createElement("a");Ge.href=Oe;const yt=qqe(((Fe=v==null?void 0:v.property)==null?void 0:Fe.property_address)??"letter");Ge.download=`${yt||"letter"}.png`,Ge.click(),ae.success("Letter image downloaded")}catch{ae.error("Could not download letter")}finally{m(!1)}}},O=async()=>{var Fe;if(I.current){m(!0);try{const Oe=await PU(I.current,{pixelRatio:2}),Ge=document.createElement("a");Ge.href=Oe;const yt=qqe(((Fe=v==null?void 0:v.property)==null?void 0:Fe.property_address)??"guide");Ge.download=`${yt||"guide"}-guide.png`,Ge.click(),ae.success("Guide image downloaded")}catch{ae.error("Could not download guide")}finally{m(!1)}}},B=Fe=>{var nt;const Oe=document.querySelector("[data-print-root]"),Ge=Oe?document.createElement("div"):null;Oe&&Ge&&((nt=Oe.parentNode)==null||nt.insertBefore(Ge,Oe),document.body.appendChild(Oe));const yt=document.title;document.title=Fe,document.body.classList.add("printing-doc");let tt=!1;const ut=()=>{tt||(tt=!0,Oe&&(Ge!=null&&Ge.parentNode)&&Ge.parentNode.replaceChild(Oe,Ge),document.body.classList.remove("printing-doc"),document.title=yt,window.removeEventListener("afterprint",ut))};window.addEventListener("afterprint",ut);try{window.print()}finally{setTimeout(ut,1e3)}},U=(((Te=v==null?void 0:v.property)==null?void 0:Te.property_address)??"Campaign").replace(/[\\/:*?"<>|]/g,"-").trim(),G=Fe=>{s&&(l.mutate({campaignId:s,section:Fe,instruction:d}),u(""))};if(r.isLoading)return e.jsx(Xs,{title:"Campaign",children:e.jsx("div",{className:"grid place-items-center py-24",children:e.jsx(Jt,{className:"h-6 w-6 animate-spin"})})});if(!v)return e.jsx(Xs,{title:"Campaign",children:e.jsx("div",{className:"py-12 text-center text-muted-foreground",children:"Campaign not found."})});const H=bCe.find(Fe=>Fe.id===v.style),Y=_.letter,se=_.landing,ee=_.guide,oe=_.emails??[],me=_.sms??[],Q=_.scripts;return e.jsx(Xs,{title:"FSBO Campaign",children:e.jsxs("div",{className:"fsbo-theme -m-4 sm:-m-6 p-4 sm:p-6 min-h-[calc(100vh-4rem)]",children:[e.jsxs($,{variant:"ghost",size:"sm",className:"gap-2 mb-4",onClick:()=>t("/apps/fsbo-breakthrough"),children:[e.jsx(Ia,{className:"h-4 w-4"})," Back to By-Owner Breakthrough"]}),e.jsxs("div",{className:"fsbo-dark rounded-2xl p-6 sm:p-8 relative overflow-hidden",children:[e.jsx("div",{className:"absolute -right-10 -top-16 h-56 w-56 rounded-full bg-accent/20 blur-3xl"}),e.jsxs("div",{className:"relative flex flex-col lg:flex-row lg:items-center justify-between gap-6",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"fsbo-eyebrow text-accent",children:[(H==null?void 0:H.name)??v.style," · ",v.status]}),e.jsx("h1",{className:"fsbo-serif text-2xl sm:text-3xl mt-1",children:((Ie=v.property)==null?void 0:Ie.property_address)??v.name}),e.jsxs("p",{className:"text-white/70 mt-1",children:[((Ue=v.property)==null?void 0:Ue.seller_name)||"Homeowner"," · ",(Be=v.property)==null?void 0:Be.city,(je=v.property)!=null&&je.city&&((Ye=v.property)!=null&&Ye.state)?", ":"",(Ee=v.property)==null?void 0:Ee.state,(Re=v.property)!=null&&Re.estimated_value?` · Est. ${wKt(v.property.estimated_value)}`:""]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx($,{size:"sm",variant:"outline",className:"bg-white/10 border-white/20 text-white hover:bg-white/20",asChild:!0,children:e.jsxs("a",{href:j,target:"_blank",rel:"noreferrer",children:[e.jsx(kc,{className:"h-4 w-4 mr-1"})," Preview"]})}),e.jsxs($,{size:"sm",variant:"outline",className:"bg-white/10 border-white/20 text-white hover:bg-white/20",onClick:()=>{navigator.clipboard.writeText(j),ae.success("Copied")},children:[e.jsx(Da,{className:"h-4 w-4 mr-1"})," Copy link"]}),e.jsxs($,{size:"sm",variant:"outline",className:"bg-white/10 border-white/20 text-white hover:bg-white/20",onClick:()=>G(),children:[e.jsx(yo,{className:"h-4 w-4 mr-1"})," Regenerate"]}),e.jsx($,{size:"sm",variant:"outline",className:"bg-white/10 border-white/20 text-white hover:bg-white/20 hover:text-destructive",onClick:()=>c.mutate(v.id),children:e.jsx(Un,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"mt-6 grid grid-cols-2 sm:grid-cols-4 gap-3",children:[e.jsxs("div",{className:"bg-white/10 rounded-lg p-3",children:[e.jsx("div",{className:"text-xs text-white/60",children:"Page visits"}),e.jsx("div",{className:"text-xl font-bold",children:P.page_view??0})]}),e.jsxs("div",{className:"bg-white/10 rounded-lg p-3",children:[e.jsx("div",{className:"text-xs text-white/60",children:"QR scans"}),e.jsx("div",{className:"text-xl font-bold",children:P.qr_scan??0})]}),e.jsxs("div",{className:"bg-white/10 rounded-lg p-3",children:[e.jsx("div",{className:"text-xs text-white/60",children:"Leads"}),e.jsx("div",{className:"text-xl font-bold",children:P.form_submit??0})]}),e.jsxs("div",{className:"bg-white/10 rounded-lg p-3",children:[e.jsx("div",{className:"text-xs text-white/60",children:"Guide views"}),e.jsx("div",{className:"text-xl font-bold",children:P.guide_view??0})]})]})]}),e.jsxs("div",{className:"mt-4 flex gap-2",children:[e.jsx(be,{placeholder:"Tell AI what to change (e.g., 'make it shorter', 'focus on luxury buyers')...",value:d,onChange:Fe=>u(Fe.target.value),className:"max-w-xl"}),e.jsx($,{variant:"outline",onClick:()=>G(),disabled:l.isPending,children:l.isPending?e.jsx(Jt,{className:"h-4 w-4 animate-spin"}):e.jsx(kn,{className:"h-4 w-4"})})]}),e.jsxs(ya,{value:p,onValueChange:g,className:"mt-6",children:[e.jsx(va,{className:"flex w-full overflow-x-auto no-scrollbar justify-start bg-transparent p-0 gap-2 h-auto",children:[{id:"letter",label:"Letter",icon:pn},{id:"landing",label:"Landing Page",icon:kc},{id:"guide",label:"Seller Guide",icon:ea},{id:"scripts",label:"Scripts & Drip",icon:bo},{id:"leads",label:"Leads",icon:ka}].map(Fe=>e.jsxs(is,{value:Fe.id,className:"data-[state=active]:bg-primary data-[state=active]:text-primary-foreground rounded-full border border-border bg-card px-4 py-2 text-sm whitespace-nowrap",children:[e.jsx(Fe.icon,{className:"h-3.5 w-3.5 mr-1.5"})," ",Fe.label]},Fe.id))}),e.jsxs(cs,{value:"letter",className:"mt-6",children:[e.jsxs("div",{className:"flex justify-between items-center mb-4","data-print-hide":!0,children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-lg font-semibold",children:"Mail-ready letter"}),e.jsx("div",{className:"text-xs text-muted-foreground mt-0.5",children:"Prints as a single clean 8.5×11 sheet — no browser header or footer."})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs($,{size:"sm",variant:"outline",onClick:()=>y(Fe=>!Fe),disabled:!Y,children:[e.jsx(ui,{className:"h-4 w-4 mr-1"})," ",x?"Close editor":"Edit letter"]}),e.jsxs($,{size:"sm",variant:"outline",onClick:R,disabled:h,children:[e.jsx(y2,{className:"h-4 w-4 mr-1"})," Download image"]}),e.jsxs($,{size:"sm",variant:"outline",onClick:()=>B(U),children:[e.jsx(QT,{className:"h-4 w-4 mr-1"})," Print"]})]})]}),x&&Y?e.jsx("div",{className:"mb-6 print:hidden","data-print-hide":!0,children:e.jsx(yKt,{letter:Y,saving:o.isPending,onCancel:()=>y(!1),onSave:Fe=>{o.mutate({id:s,patch:{content:{..._,letter:Fe}}},{onSuccess:()=>y(!1)})}})}):null,e.jsx("div",{className:"fsbo-tile p-6 max-w-3xl mx-auto",children:e.jsxs("div",{ref:M,"data-print-root":!0,className:"bg-white text-foreground p-8 sm:p-12 rounded-lg shadow-sm",children:[e.jsxs("div",{className:"flex items-center justify-between mb-8",children:[e.jsxs("div",{children:[A.name?e.jsx("div",{className:"font-bold text-lg",children:A.name}):null,A.title?e.jsx("div",{className:"text-sm text-gray-600",children:A.title}):null,A.brokerage_name?e.jsx("div",{className:"text-sm text-gray-600",children:A.brokerage_name}):null]}),A.avatar_url?e.jsx("img",{src:A.avatar_url,alt:A.name??"",className:"h-16 w-16 rounded-full object-cover"}):null]}),Y?e.jsxs("div",{className:"space-y-4 text-[15px] leading-relaxed",children:[e.jsx("div",{children:Y.greeting}),Y.paragraphs.map((Fe,Oe)=>e.jsx("p",{children:Fe},Oe)),e.jsx("div",{children:Y.closing}),e.jsx("div",{className:"font-semibold","data-print-keep":!0,children:Y.signature}),e.jsx("div",{className:"text-sm text-gray-600 italic mt-4","data-print-keep":!0,children:Y.ps})]}):e.jsx("div",{className:"text-muted-foreground",children:"Letter content not generated yet."}),e.jsxs("div",{className:"mt-8 pt-6 border-t flex items-center gap-4","data-print-keep":!0,children:[e.jsx("div",{className:"h-24 w-24 shrink-0",children:e.jsx(jk,{value:j,size:96})}),e.jsxs("div",{className:"text-sm text-gray-600",children:[e.jsx("div",{className:"font-semibold",children:"Scan for your free guide"}),e.jsx("div",{children:j})]})]})]})})]}),e.jsxs(cs,{value:"landing",className:"mt-6",children:[e.jsxs("div",{className:"flex justify-between items-center mb-4",children:[e.jsx("div",{className:"text-lg font-semibold",children:"Landing page copy"}),e.jsx($,{size:"sm",variant:"outline",asChild:!0,children:e.jsxs("a",{href:j,target:"_blank",rel:"noreferrer",children:[e.jsx(Ir,{className:"h-4 w-4 mr-1"})," Live preview"]})})]}),e.jsx("div",{className:"fsbo-tile p-6 max-w-3xl mx-auto space-y-4",children:se?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-sm uppercase tracking-wider text-primary",children:se.eyebrow}),e.jsx("h2",{className:"text-3xl font-bold",children:se.headline}),e.jsx("p",{className:"text-lg text-muted-foreground",children:se.subheadline}),e.jsx("p",{className:"text-foreground",children:se.intro}),e.jsx("div",{className:"grid gap-3 sm:grid-cols-2 mt-4",children:se.discover.map((Fe,Oe)=>e.jsxs("div",{className:"bg-muted/40 p-4 rounded-lg",children:[e.jsx("div",{className:"font-semibold",children:Fe.title}),e.jsx("div",{className:"text-sm text-muted-foreground",children:Fe.body})]},Oe))}),e.jsxs("div",{className:"mt-4 p-4 bg-primary/5 border-l-4 border-primary rounded-r-lg",children:[e.jsxs("div",{className:"italic",children:['"',se.testimonial.quote,'"']}),e.jsxs("div",{className:"text-sm font-semibold mt-2",children:["— ",se.testimonial.author]})]}),e.jsx("div",{className:"mt-4",children:e.jsx($,{size:"lg",children:se.cta})})]}):e.jsx("div",{className:"text-muted-foreground",children:"Landing page content not generated yet."})})]}),e.jsxs(cs,{value:"guide",className:"mt-6",children:[e.jsxs("div",{className:"flex justify-between items-center mb-4","data-print-hide":!0,children:[e.jsx("div",{className:"text-lg font-semibold",children:"Seller guide"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs($,{size:"sm",variant:"outline",onClick:O,disabled:h,children:[e.jsx(y2,{className:"h-4 w-4 mr-1"})," Download image"]}),e.jsxs($,{size:"sm",variant:"outline",onClick:()=>B(U),children:[e.jsx(QT,{className:"h-4 w-4 mr-1"})," Print"]}),e.jsx($,{size:"sm",variant:"outline",asChild:!0,children:e.jsxs("a",{href:`${j}/guide`,target:"_blank",rel:"noreferrer",children:[e.jsx(Ir,{className:"h-4 w-4 mr-1"})," Public view"]})})]})]}),e.jsx("div",{ref:I,"data-print-root":!0,className:"fsbo-tile p-8 max-w-4xl mx-auto space-y-6 bg-white text-foreground",children:ee?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"text-center pb-6 border-b",children:[e.jsx("div",{className:"text-sm uppercase tracking-wider text-primary",children:"By-Owner Breakthrough"}),e.jsx("h2",{className:"text-3xl font-bold mt-2",children:"FSBO Seller Guide"}),e.jsx("p",{className:"text-muted-foreground mt-2",children:(ke=v.property)==null?void 0:ke.property_address})]}),e.jsx("p",{className:"text-lg leading-relaxed",children:ee.intro}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-xl font-semibold mb-3",children:"FSBO Reality Checklist"}),e.jsx("ul",{className:"space-y-2",children:ee.checklist.map((Fe,Oe)=>e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"text-primary",children:"✓"}),e.jsx("span",{children:Fe})]},Oe))})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-xl font-semibold mb-3",children:"Common Pitfalls"}),e.jsx("div",{className:"grid gap-3 sm:grid-cols-2",children:ee.pitfalls.map((Fe,Oe)=>e.jsxs("div",{className:"bg-muted/30 p-4 rounded-lg",children:[e.jsx("div",{className:"font-semibold",children:Fe.title}),e.jsx("div",{className:"text-sm text-muted-foreground",children:Fe.body})]},Oe))})]}),e.jsxs("div",{className:"grid gap-6 sm:grid-cols-2",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-xl font-semibold mb-3",children:"Your Advantages"}),e.jsx("ul",{className:"space-y-2",children:ee.seller_advantages.map((Fe,Oe)=>e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"text-primary",children:"+"}),e.jsx("span",{children:Fe})]},Oe))})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-xl font-semibold mb-3",children:"What an Agent Brings"}),e.jsx("ul",{className:"space-y-2",children:ee.agent_value.map((Fe,Oe)=>e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"text-primary",children:"→"}),e.jsx("span",{children:Fe})]},Oe))})]})]}),e.jsxs("div",{className:"bg-primary/10 p-6 rounded-xl text-center",children:[e.jsx("h3",{className:"text-xl font-semibold mb-2",children:ee.cta}),e.jsx("p",{className:"text-muted-foreground mb-4",children:ee.cta_body}),e.jsx($,{size:"lg",children:"Request a Free Consultation"})]})]}):e.jsx("div",{className:"text-muted-foreground",children:"Guide content not generated yet."})})]}),e.jsx(cs,{value:"scripts",className:"mt-6",children:e.jsxs("div",{className:"grid gap-4 lg:grid-cols-2",children:[e.jsxs("div",{className:"fsbo-tile p-5",children:[e.jsx("div",{className:"text-lg font-semibold mb-4",children:"Agent scripts"}),Q?e.jsxs("div",{className:"space-y-4",children:[e.jsx(Die,{label:"Phone",text:Q.phone}),e.jsx(Die,{label:"Voicemail",text:Q.voicemail}),e.jsx(Die,{label:"Video",text:Q.video}),e.jsx(Die,{label:"Door knock",text:Q.door_knock}),e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-semibold mb-2",children:"Objection responses"}),e.jsx("div",{className:"space-y-2",children:Q.objections.map((Fe,Oe)=>e.jsxs("div",{className:"bg-muted/40 p-3 rounded-lg",children:[e.jsxs("div",{className:"text-sm font-medium text-destructive",children:['"',Fe.objection,'"']}),e.jsx("div",{className:"text-sm mt-1",children:Fe.response})]},Oe))})]})]}):e.jsx("div",{className:"text-muted-foreground",children:"Scripts not generated yet."})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"fsbo-tile p-5",children:[e.jsx("div",{className:"text-lg font-semibold mb-4",children:"Email sequence"}),e.jsxs("div",{className:"space-y-2",children:[oe.map((Fe,Oe)=>e.jsxs("div",{className:"bg-muted/40 p-3 rounded-lg",children:[e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Day ",Oe*4+1]}),e.jsx("div",{className:"font-medium",children:Fe.subject}),e.jsx("div",{className:"text-sm text-muted-foreground truncate",children:Fe.preview})]},Fe.key)),!oe.length&&e.jsx("div",{className:"text-muted-foreground",children:"No emails generated yet."})]})]}),e.jsxs("div",{className:"fsbo-tile p-5",children:[e.jsx("div",{className:"text-lg font-semibold mb-4",children:"SMS sequence"}),e.jsxs("div",{className:"space-y-2",children:[me.map((Fe,Oe)=>e.jsxs("div",{className:"bg-muted/40 p-3 rounded-lg",children:[e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Step ",Oe+1]}),e.jsx("div",{className:"text-sm",children:Fe.body})]},Fe.key)),!me.length&&e.jsx("div",{className:"text-muted-foreground",children:"No SMS messages generated yet."})]})]})]})]})}),e.jsx(cs,{value:"leads",className:"mt-6",children:e.jsxs("div",{className:"fsbo-tile p-5",children:[e.jsx("div",{className:"text-lg font-semibold mb-4",children:"Seller leads"}),e.jsx("div",{className:"space-y-3",children:(i.data??[]).filter(Fe=>Fe.campaign_id===s).length===0?e.jsx("div",{className:"text-muted-foreground",children:"No leads yet. Share the landing page to start collecting them."}):(i.data??[]).filter(Fe=>Fe.campaign_id===s).map(Fe=>e.jsxs("div",{className:"flex items-center justify-between p-4 rounded-lg bg-muted/40",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"font-medium",children:[Fe.first_name," ",Fe.last_name]}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[Fe.email," · ",Fe.phone]}),e.jsxs("div",{className:"text-sm text-muted-foreground mt-1",children:["Timeline: ",Fe.timeline??"—"," · Motivation: ",Fe.motivation??"—"]}),e.jsx("div",{className:"text-sm mt-1",children:Fe.message})]}),e.jsxs("div",{className:"text-right",children:[e.jsxs(qe,{className:Ot(Fe.temperature==="hot"?"bg-red-500/15 text-red-600":"bg-amber-500/15 text-amber-600"),children:[Fe.temperature," · ",Fe.lead_score]}),e.jsx("div",{className:"text-xs text-muted-foreground mt-1",children:Ys(new Date(Fe.created_at),"MMM d")})]})]},Fe.id))})]})})]})]})})}function Die({label:s,text:t}){return e.jsxs("div",{className:"bg-muted/40 p-3 rounded-lg",children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx("div",{className:"text-sm font-semibold",children:s}),e.jsx($,{size:"sm",variant:"ghost",className:"h-6 px-2",onClick:()=>{navigator.clipboard.writeText(t),ae.success("Copied")},children:e.jsx(Da,{className:"h-3.5 w-3.5"})})]}),e.jsx("div",{className:"text-sm text-muted-foreground",children:t})]})}const VYn="https://relzejiswnotikjgvjhz.supabase.co/functions/v1/fsbo-public",Mjt="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InJlbHplamlzd25vdGlramd2amh6Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjE5NTAzNDQsImV4cCI6MjA3NzUyNjM0NH0.dzIkIr_oFSbFE3oWS0ktIr83iKHHkZxt40Gc7SpC_mM";async function _D(s){try{const t=await fetch(VYn,{method:"POST",headers:{"Content-Type":"application/json",apikey:Mjt,Authorization:`Bearer ${Mjt}`},body:JSON.stringify(s)});return t.ok?await t.json():null}catch{return null}}function HYn(){const{slug:s}=oo(),[t,n]=k.useState(null),[r,a]=k.useState(!0),[i,l]=k.useState(!1),[o,c]=k.useState(!1),[d,u]=k.useState({first_name:"",last_name:"",email:"",phone:"",timeline:"",motivation:"",preferred_contact:"email",message:""});k.useEffect(()=>{s&&(a(!0),_D({action:"get",slug:s}).then(j=>{j!=null&&j.campaign&&n(j),a(!1)}))},[s]),k.useEffect(()=>{if(!s)return;const j=sessionStorage.getItem(`fsbo-${s}`)||crypto.randomUUID();sessionStorage.setItem(`fsbo-${s}`,j),_D({action:"track",slug:s,event_type:"page_view",session_id:j})},[s]);const h=async j=>{if(j.preventDefault(),!s)return;c(!0);const C=sessionStorage.getItem(`fsbo-${s}`)||void 0,A=await _D({action:"submit",slug:s,...d,session_id:C,wants_guide:!0});c(!1),A?l(!0):alert("Could not submit. Please try again.")};if(r)return e.jsx("div",{className:"min-h-screen grid place-items-center bg-stone-50",children:e.jsx(Jt,{className:"h-6 w-6 animate-spin text-primary"})});if(!t)return e.jsx("div",{className:"min-h-screen grid place-items-center text-muted-foreground",children:"Landing page not found."});const m=t.campaign,p=m.content??{},g=p.landing,x=t.agent,y=m.property??{},v=p.landing_config??{show_property_snapshot:!0,show_discover:!0,show_testimonial:!0},_=v.video_url?PYn(v.video_url):null;return e.jsxs("div",{className:"min-h-screen bg-stone-50 text-stone-900",children:[e.jsxs(Sc,{children:[e.jsxs("title",{children:[(g==null?void 0:g.headline)||"Selling On Your Own?"," — ",(x==null?void 0:x.name)||"LevelUp"]}),e.jsx("meta",{name:"description",content:(g==null?void 0:g.subheadline)||"Free FSBO seller guide from a local agent."})]}),e.jsx("div",{className:"bg-gradient-to-br from-[#4a6741] to-[#2d5a3d] text-white",children:e.jsx("div",{className:"max-w-7xl mx-auto px-4 sm:px-6 py-12 lg:py-20",children:e.jsxs("div",{className:"grid lg:grid-cols-2 gap-10 items-center",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm uppercase tracking-wider text-[#f4d06f] font-semibold",children:(g==null?void 0:g.eyebrow)||"Free FSBO Seller Guide"}),e.jsx("h1",{className:"text-3xl sm:text-5xl font-bold mt-4 leading-tight",children:(g==null?void 0:g.headline)||"Selling On Your Own? Here's What You Should Know."}),e.jsx("p",{className:"text-lg text-white/80 mt-4",children:(g==null?void 0:g.subheadline)||`A complimentary guide for ${y.property_address||"your home"} created by a local agent.`}),e.jsxs("div",{className:"mt-6 flex flex-wrap gap-3",children:[e.jsxs("a",{href:"#form",className:"inline-flex items-center gap-2 bg-[#f4d06f] text-[#0f4c5c] px-5 py-3 rounded-lg font-semibold hover:bg-[#f4d06f]/90",children:[(g==null?void 0:g.cta)||"Send Me the Free Guide"," ",e.jsx(xi,{className:"h-4 w-4"})]}),e.jsx("a",{href:`/fsbo/${s}/guide`,className:"inline-flex items-center gap-2 bg-white/10 text-white px-5 py-3 rounded-lg font-semibold hover:bg-white/20",children:"Read the guide"})]})]}),e.jsx("div",{className:"rounded-2xl overflow-hidden shadow-2xl bg-white/10 ring-1 ring-white/15",children:(_==null?void 0:_.kind)==="iframe"?e.jsx("iframe",{src:_.src,className:"w-full aspect-video block border-0",scrolling:"no",allowFullScreen:!0,title:"Property media"}):(_==null?void 0:_.kind)==="file"?e.jsx("video",{src:_.src,className:"w-full aspect-video object-cover block",controls:!0}):typeof y.photo_url=="string"&&y.photo_url?e.jsx("img",{src:y.photo_url,alt:String(y.property_address||"Property photo"),loading:"eager",className:"w-full aspect-[4/3] object-cover object-center block"}):e.jsx("div",{className:"aspect-[4/3] grid place-items-center text-white/60",children:e.jsx(ua,{className:"h-12 w-12"})})})]})})}),v.show_property_snapshot!==!1&&e.jsx("div",{className:"max-w-5xl mx-auto px-4 sm:px-6 -mt-8",children:e.jsxs("div",{className:"bg-white rounded-xl shadow-lg p-5 flex flex-wrap gap-6 justify-center items-center",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Si,{className:"h-4 w-4 text-[#4a6741]"})," ",e.jsx("span",{className:"font-semibold",children:y.property_address})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ua,{className:"h-4 w-4 text-[#4a6741]"})," ",e.jsx("span",{className:"capitalize",children:String(y.property_type||"").replace("_"," ")})]}),y.estimated_value?e.jsx("div",{className:"flex items-center gap-2",children:e.jsxs("span",{className:"font-semibold",children:["Est. $",Number(y.estimated_value).toLocaleString()]})}):null]})}),e.jsx("div",{className:"max-w-7xl mx-auto px-4 sm:px-6 py-16",children:e.jsxs("div",{className:"grid lg:grid-cols-5 gap-12",children:[e.jsxs("div",{className:"lg:col-span-3 space-y-6",children:[e.jsx("div",{className:"text-lg leading-relaxed text-stone-700",children:g==null?void 0:g.intro}),v.show_discover!==!1&&(g==null?void 0:g.discover)&&e.jsx("div",{className:"grid sm:grid-cols-2 gap-4 mt-6",children:g.discover.map((j,C)=>e.jsxs("div",{className:"bg-white p-5 rounded-xl shadow-sm border border-stone-100",children:[e.jsx("div",{className:"font-semibold text-[#4a6741] mb-1",children:j.title}),e.jsx("div",{className:"text-sm text-stone-600",children:j.body})]},C))}),v.show_testimonial!==!1&&(g==null?void 0:g.testimonial)&&e.jsxs("div",{className:"mt-8 bg-[#4a6741]/10 p-6 rounded-2xl border-l-4 border-[#4a6741]",children:[e.jsx("div",{className:"flex gap-1 text-[#f4d06f] mb-2",children:[...Array(5)].map((j,C)=>e.jsx(ri,{className:"h-4 w-4 fill-current"},C))}),e.jsxs("div",{className:"italic text-lg text-stone-800",children:['"',g.testimonial.quote,'"']}),e.jsxs("div",{className:"font-semibold text-sm mt-3",children:["— ",g.testimonial.author]})]})]}),e.jsx("div",{id:"form",className:"lg:col-span-2",children:e.jsx("div",{className:"bg-white rounded-2xl shadow-lg p-6 sm:p-8 sticky top-6",children:i?e.jsxs("div",{className:"text-center py-8",children:[e.jsx("div",{className:"mx-auto h-14 w-14 rounded-full bg-green-100 grid place-items-center mb-4",children:e.jsx(Gr,{className:"h-7 w-7 text-green-600"})}),e.jsx("h3",{className:"text-xl font-bold",children:"Your guide is on the way!"}),e.jsxs("p",{className:"text-stone-600 mt-2",children:["Check your email for the guide. ",(x==null?void 0:x.name)||"The agent"," will follow up soon."]}),e.jsx("a",{href:`/fsbo/${s}/guide`,className:"inline-block mt-4 text-[#4a6741] font-semibold underline",children:"Read it now"})]}):e.jsxs("form",{onSubmit:h,className:"space-y-4",children:[e.jsx("h3",{className:"text-xl font-bold",children:(g==null?void 0:g.form_subhead)||"Get your free guide"}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(re,{className:"text-xs",children:"First"}),e.jsx(be,{value:d.first_name,onChange:j=>u(C=>({...C,first_name:j.target.value})),required:!0})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(re,{className:"text-xs",children:"Last"}),e.jsx(be,{value:d.last_name,onChange:j=>u(C=>({...C,last_name:j.target.value})),required:!0})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(re,{className:"text-xs",children:"Email"}),e.jsx(be,{type:"email",value:d.email,onChange:j=>u(C=>({...C,email:j.target.value})),required:!0})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(re,{className:"text-xs",children:"Phone"}),e.jsx(be,{type:"tel",value:d.phone,onChange:j=>u(C=>({...C,phone:j.target.value}))})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(re,{className:"text-xs",children:"Timeline"}),e.jsxs("select",{className:"w-full h-10 rounded-md border border-input bg-background px-3 py-2 text-sm",value:d.timeline,onChange:j=>u(C=>({...C,timeline:j.target.value})),children:[e.jsx("option",{value:"",children:"Select…"}),LYn.map(j=>e.jsx("option",{value:j.value,children:j.label},j.value))]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(re,{className:"text-xs",children:"Preferred contact"}),e.jsx("select",{className:"w-full h-10 rounded-md border border-input bg-background px-3 py-2 text-sm",value:d.preferred_contact,onChange:j=>u(C=>({...C,preferred_contact:j.target.value})),children:DYn.map(j=>e.jsx("option",{value:j.value,children:j.label},j.value))})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(re,{className:"text-xs",children:"What prompted you to sell on your own?"}),e.jsxs("select",{className:"w-full h-10 rounded-md border border-input bg-background px-3 py-2 text-sm",value:d.motivation,onChange:j=>u(C=>({...C,motivation:j.target.value})),children:[e.jsx("option",{value:"",children:"Select…"}),RYn.map(j=>e.jsx("option",{value:j,children:j},j))]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(re,{className:"text-xs",children:"Message (optional)"}),e.jsx(Ls,{rows:3,value:d.message,onChange:j=>u(C=>({...C,message:j.target.value}))})]}),e.jsxs($,{type:"submit",className:"w-full",size:"lg",disabled:o,children:[o?e.jsx(Jt,{className:"h-4 w-4 animate-spin mr-2"}):null,(g==null?void 0:g.cta)||"Send Me the Free Guide"]}),e.jsxs("p",{className:"text-xs text-stone-500 text-center",children:["No spam. Unsubscribe anytime. Your info helps ",(x==null?void 0:x.name)||"the agent"," tailor the guide."]})]})})})]})}),e.jsx("div",{className:"bg-white border-t border-stone-100",children:e.jsx("div",{className:"max-w-7xl mx-auto px-4 sm:px-6 py-12",children:e.jsxs("div",{className:"flex flex-col sm:flex-row items-center gap-6",children:[x!=null&&x.avatar_url?e.jsx("img",{src:x.avatar_url,alt:x.name||"",className:"h-24 w-24 rounded-full object-cover shadow-md"}):null,e.jsxs("div",{className:"text-center sm:text-left",children:[e.jsx("div",{className:"text-xl font-bold",children:x==null?void 0:x.name}),e.jsxs("div",{className:"text-stone-600",children:[x==null?void 0:x.title,x!=null&&x.title&&(x!=null&&x.brokerage)?" · ":"",x==null?void 0:x.brokerage]}),e.jsxs("div",{className:"flex flex-wrap justify-center sm:justify-start gap-2 mt-3",children:[x!=null&&x.phone?e.jsx($,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:`tel:${x.phone}`,children:[e.jsx(ka,{className:"h-4 w-4 mr-1"})," Call"]})}):null,x!=null&&x.email?e.jsx($,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:`mailto:${x.email}`,children:[e.jsx(pn,{className:"h-4 w-4 mr-1"})," Email"]})}):null,x!=null&&x.website_url?e.jsx($,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:x.website_url,target:"_blank",rel:"noreferrer",children:[e.jsx(bo,{className:"h-4 w-4 mr-1"})," Website"]})}):null]})]})]})})})]})}function GYn(){const{slug:s}=oo(),[t,n]=k.useState(null),[r,a]=k.useState(!0),[i,l]=k.useState({first_name:"",last_name:"",email:"",phone:"",message:""}),[o,c]=k.useState(!1),[d,u]=k.useState(!1);k.useEffect(()=>{s&&(a(!0),_D({action:"get",slug:s}).then(v=>{v!=null&&v.campaign&&n(v),a(!1)}))},[s]),k.useEffect(()=>{s&&_D({action:"track",slug:s,event_type:"guide_view"})},[s]);const h=async v=>{if(v.preventDefault(),!s||o)return;c(!0);const _=await _D({action:"submit",slug:s,...i,message:`Requested a free consultation from the guide page.${i.message?` — ${i.message}`:""}`,preferred_contact:"either",wants_guide:!1});c(!1),_?(u(!0),_D({action:"track",slug:s,event_type:"consultation_request"})):alert("Could not send your request. Please try again.")};if(r)return e.jsx("div",{className:"min-h-screen grid place-items-center bg-stone-50",children:e.jsx(Jt,{className:"h-6 w-6 animate-spin text-primary"})});if(!t)return e.jsx("div",{className:"min-h-screen grid place-items-center text-muted-foreground",children:"Guide not found."});const m=t.campaign,g=(m.content??{}).guide,x=t.agent,y=m.property??{};return e.jsxs("div",{className:"min-h-screen bg-stone-50 text-stone-900",children:[e.jsxs(Sc,{children:[e.jsxs("title",{children:["FSBO Seller Guide — ",(y==null?void 0:y.property_address)||"Your home"]}),e.jsx("meta",{name:"description",content:"Free guide for selling your home by owner."})]}),e.jsx("div",{className:"bg-gradient-to-br from-[#4a6741] to-[#2d5a3d] text-white",children:e.jsx("div",{className:"max-w-5xl mx-auto px-4 sm:px-6 py-6",children:e.jsxs(nr,{to:`/fsbo/${s}`,className:"inline-flex items-center gap-1 text-sm text-white/80 hover:text-white",children:[e.jsx(Ia,{className:"h-4 w-4"})," Back to landing page"]})})}),e.jsx("div",{className:"max-w-5xl mx-auto px-4 sm:px-6 py-12",children:e.jsxs("div",{className:"bg-white rounded-2xl shadow-lg p-8 sm:p-12",children:[e.jsxs("div",{className:"text-center pb-8 border-b border-stone-100",children:[e.jsx("div",{className:"text-sm uppercase tracking-wider text-[#4a6741] font-semibold",children:"By-Owner Breakthrough"}),e.jsx("h1",{className:"text-3xl sm:text-4xl font-bold mt-2 text-stone-900",children:"FSBO Seller Guide"}),e.jsx("p",{className:"text-stone-600 mt-2 text-lg",children:y==null?void 0:y.property_address})]}),g?e.jsxs("div",{className:"space-y-10 mt-8",children:[e.jsx("p",{className:"text-lg leading-relaxed text-stone-700",children:g.intro}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold mb-4",children:"FSBO Reality Checklist"}),e.jsx("ul",{className:"space-y-3",children:g.checklist.map((v,_)=>e.jsxs("li",{className:"flex items-start gap-3 p-3 bg-stone-50 rounded-lg",children:[e.jsx("span",{className:"text-[#4a6741] font-bold text-lg",children:"✓"}),e.jsx("span",{className:"text-stone-700",children:v})]},_))})]}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold mb-4",children:"Common Pitfalls"}),e.jsx("div",{className:"grid gap-4 sm:grid-cols-2",children:g.pitfalls.map((v,_)=>e.jsxs("div",{className:"bg-stone-50 p-5 rounded-xl",children:[e.jsx("div",{className:"font-semibold text-stone-900 mb-1",children:v.title}),e.jsx("div",{className:"text-sm text-stone-600",children:v.body})]},_))})]}),e.jsxs("div",{className:"grid gap-8 sm:grid-cols-2",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold mb-4",children:"Your Advantages"}),e.jsx("ul",{className:"space-y-3",children:g.seller_advantages.map((v,_)=>e.jsxs("li",{className:"flex items-start gap-3",children:[e.jsx("span",{className:"text-[#4a6741] font-bold",children:"+"}),e.jsx("span",{className:"text-stone-700",children:v})]},_))})]}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold mb-4",children:"What an Agent Brings"}),e.jsx("ul",{className:"space-y-3",children:g.agent_value.map((v,_)=>e.jsxs("li",{className:"flex items-start gap-3",children:[e.jsx("span",{className:"text-[#4a6741] font-bold",children:"→"}),e.jsx("span",{className:"text-stone-700",children:v})]},_))})]})]}),e.jsxs("div",{id:"consult",className:"bg-[#4a6741]/10 p-8 rounded-2xl",children:[e.jsxs("div",{className:"text-center",children:[e.jsx("h3",{className:"text-2xl font-bold mb-3 text-stone-900",children:g.cta}),e.jsx("p",{className:"text-stone-600 mb-6 max-w-lg mx-auto",children:g.cta_body})]}),d?e.jsxs("div",{className:"text-center py-6",children:[e.jsx("div",{className:"mx-auto h-14 w-14 rounded-full bg-green-100 grid place-items-center mb-3",children:e.jsx(Gr,{className:"h-7 w-7 text-green-600"})}),e.jsx("div",{className:"font-semibold text-lg",children:"Request received"}),e.jsxs("p",{className:"text-stone-600 mt-1",children:[(x==null?void 0:x.name)||"Your agent"," will reach out shortly with an objective look at your home."]})]}):e.jsxs("form",{onSubmit:h,className:"max-w-xl mx-auto space-y-3 bg-white rounded-xl p-6 shadow-sm",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(re,{className:"text-xs",children:"First"}),e.jsx(be,{value:i.first_name,onChange:v=>l(_=>({..._,first_name:v.target.value})),required:!0})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(re,{className:"text-xs",children:"Last"}),e.jsx(be,{value:i.last_name,onChange:v=>l(_=>({..._,last_name:v.target.value})),required:!0})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(re,{className:"text-xs",children:"Email"}),e.jsx(be,{type:"email",value:i.email,onChange:v=>l(_=>({..._,email:v.target.value})),required:!0})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(re,{className:"text-xs",children:"Phone"}),e.jsx(be,{type:"tel",value:i.phone,onChange:v=>l(_=>({..._,phone:v.target.value}))})]})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(re,{className:"text-xs",children:"Best time / anything I should know (optional)"}),e.jsx(Ls,{rows:3,value:i.message,onChange:v=>l(_=>({..._,message:v.target.value}))})]}),e.jsxs($,{type:"submit",size:"lg",className:"w-full",disabled:o,children:[o?e.jsx(Jt,{className:"h-4 w-4 animate-spin mr-2"}):null,"Request a Free Consultation"]}),e.jsx("p",{className:"text-xs text-stone-500 text-center",children:"No obligation. No pressure — just clear facts about your home's market."})]})]})]}):e.jsx("div",{className:"text-stone-500 text-center py-12",children:"Guide content not available yet."}),e.jsxs("div",{className:"mt-12 pt-8 border-t border-stone-100 flex flex-col sm:flex-row items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[x!=null&&x.avatar_url?e.jsx("img",{src:x.avatar_url,alt:x.name??"",className:"h-16 w-16 rounded-full object-cover"}):null,e.jsxs("div",{children:[e.jsx("div",{className:"font-semibold text-lg",children:x==null?void 0:x.name}),e.jsxs("div",{className:"text-sm text-stone-600",children:[x==null?void 0:x.title,x!=null&&x.title&&(x!=null&&x.brokerage)?" · ":"",x==null?void 0:x.brokerage]})]})]}),e.jsxs("div",{className:"flex gap-2",children:[x!=null&&x.phone?e.jsx($,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:`tel:${x.phone}`,children:[e.jsx(ka,{className:"h-4 w-4 mr-1"})," Call"]})}):null,x!=null&&x.email?e.jsx($,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:`mailto:${x.email}`,children:[e.jsx(pn,{className:"h-4 w-4 mr-1"})," Email"]})}):null]})]})]})})]})}function WYn(){const s=vKt(),t=bKt(),n=wJe(),r=jJe(),a=ls(),[i,l]=k.useState(""),o=Nt({mutationFn:async()=>{const{data:h,error:m}=await V.from("profiles").select("id");if(m)throw m;const p=new Date().toISOString(),g=(h??[]).map(y=>({user_id:y.id,feature_key:"fsbo_breakthrough",enabled:!0,tier:"beta",expires_at:null,created_at:p,updated_at:p})),{error:x}=await V.from("feature_entitlements").upsert(g,{onConflict:"user_id,feature_key"});if(x)throw x},onSuccess:()=>{ae.success("Enabled for all members"),a.invalidateQueries({queryKey:["fsbo-breakthrough-access"]})},onError:h=>ae.error(h.message)}),c=k.useMemo(()=>{const h=m=>(r.data??[]).filter(p=>p.event_type===m).length;return{properties:(t.data??[]).length,campaigns:(s.data??[]).length,letters:(s.data??[]).filter(m=>{var p;return(p=m.content)==null?void 0:p.letter}).length,qr:h("qr_scan"),visits:h("page_view"),guideViews:h("guide_view"),leads:(n.data??[]).length,appointments:h("appointment")}},[s.data,r.data,n.data,t.data]),d=k.useMemo(()=>{const h=[];for(let m=13;m>=0;m--){const p=new Date(Date.now()-m*864e5),g=p.toISOString().slice(0,10);h.push({day:Ys(p,"MMM d"),visits:(r.data??[]).filter(x=>x.event_type==="page_view"&&x.created_at.startsWith(g)).length,scans:(r.data??[]).filter(x=>x.event_type==="qr_scan"&&x.created_at.startsWith(g)).length,leads:(n.data??[]).filter(x=>x.created_at.startsWith(g)).length})}return h},[r.data,n.data]),u=(s.data??[]).filter(h=>{var m;return`${h.name} ${((m=h.property)==null?void 0:m.property_address)??""}`.toLowerCase().includes(i.trim().toLowerCase())});return s.isLoading||t.isLoading||n.isLoading||r.isLoading?e.jsx(Xs,{title:"By-Owner Breakthrough Admin",children:e.jsx("div",{className:"grid place-items-center py-24",children:e.jsx(Jt,{className:"h-6 w-6 animate-spin"})})}):e.jsx(Xs,{title:"By-Owner Breakthrough Admin",children:e.jsxs("div",{className:"fsbo-theme -m-4 sm:-m-6 p-4 sm:p-6 min-h-[calc(100vh-4rem)]",children:[e.jsxs("div",{className:"flex items-center justify-between mb-6",children:[e.jsxs("div",{children:[e.jsx("div",{className:"fsbo-eyebrow text-muted-foreground",children:"Admin"}),e.jsx("h1",{className:"fsbo-serif text-2xl",children:"By-Owner Breakthrough"})]}),e.jsxs($,{onClick:()=>o.mutate(),disabled:o.isPending,children:[o.isPending?e.jsx(Jt,{className:"h-4 w-4 animate-spin mr-2"}):null," Enable all members"]})]}),e.jsxs("div",{className:"grid gap-3 grid-cols-2 lg:grid-cols-4 mb-6",children:[e.jsx(XA,{label:"Properties",value:c.properties,icon:ua}),e.jsx(XA,{label:"Campaigns",value:c.campaigns,icon:pn}),e.jsx(XA,{label:"Page visits",value:c.visits,icon:kc}),e.jsx(XA,{label:"QR scans",value:c.qr,icon:Bx}),e.jsx(XA,{label:"Guide views",value:c.guideViews,icon:ea}),e.jsx(XA,{label:"Leads",value:c.leads,icon:Xn}),e.jsx(XA,{label:"Appointments",value:c.appointments,icon:Xn}),e.jsx(XA,{label:"Letters",value:c.letters,icon:pn})]}),e.jsxs("div",{className:"fsbo-tile p-5 mb-6",children:[e.jsx("div",{className:"fsbo-eyebrow text-muted-foreground",children:"Last 14 days"}),e.jsx("div",{className:"text-lg font-semibold mt-1",children:"Network-wide engagement"}),e.jsx("div",{className:"h-64 mt-4",children:e.jsx(C_,{width:"100%",height:"100%",children:e.jsxs(yZe,{data:d,children:[e.jsxs("defs",{children:[e.jsxs("linearGradient",{id:"fsboAdminVisits",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:"hsl(var(--primary))",stopOpacity:.4}),e.jsx("stop",{offset:"100%",stopColor:"hsl(var(--primary))",stopOpacity:0})]}),e.jsxs("linearGradient",{id:"fsboAdminLeads",x1:"0",y1:"0",x2:"0",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:"hsl(var(--accent))",stopOpacity:.5}),e.jsx("stop",{offset:"100%",stopColor:"hsl(var(--accent))",stopOpacity:0})]})]}),e.jsx(XO,{strokeDasharray:"3 3",stroke:"hsl(var(--border))",vertical:!1}),e.jsx(Cb,{dataKey:"day",tick:{fontSize:11},stroke:"hsl(var(--muted-foreground))"}),e.jsx(Ab,{allowDecimals:!1,tick:{fontSize:11},stroke:"hsl(var(--muted-foreground))",width:28}),e.jsx(vg,{contentStyle:{borderRadius:12,border:"1px solid hsl(var(--border))"}}),e.jsx(A_,{type:"monotone",dataKey:"visits",stroke:"hsl(var(--primary))",fill:"url(#fsboAdminVisits)",strokeWidth:2}),e.jsx(A_,{type:"monotone",dataKey:"scans",stackId:"1",stroke:"hsl(var(--accent))",fill:"url(#fsboAdminLeads)",strokeWidth:2}),e.jsx(A_,{type:"monotone",dataKey:"leads",stackId:"1",stroke:"#5b8a5c",fill:"#5b8a5c",fillOpacity:.15,strokeWidth:2})]})})})]}),e.jsxs("div",{className:"fsbo-tile p-5",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("div",{className:"text-lg font-semibold",children:"All campaigns"}),e.jsxs("div",{className:"relative w-64",children:[e.jsx(Yr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(be,{className:"pl-9",placeholder:"Search campaigns…",value:i,onChange:h=>l(h.target.value)})]})]}),e.jsxs("div",{className:"space-y-3",children:[u.map(h=>{var g,x,y,v,_,j;const m=(n.data??[]).filter(C=>C.campaign_id===h.id).length,p=(r.data??[]).filter(C=>C.campaign_id===h.id&&C.event_type==="page_view").length;return e.jsxs("a",{href:`/apps/fsbo-breakthrough/campaigns/${h.id}`,className:"flex items-center justify-between p-4 rounded-xl bg-muted/40 hover:bg-muted/60 transition-colors",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-semibold",children:((g=h.property)==null?void 0:g.property_address)??h.name}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[((x=h.property)==null?void 0:x.seller_name)||"Homeowner"," · ",(y=h.property)==null?void 0:y.city,(v=h.property)!=null&&v.city&&((_=h.property)!=null&&_.state)?", ":"",(j=h.property)==null?void 0:j.state]})]}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs(qe,{variant:"secondary",children:[e.jsx(kc,{className:"h-3 w-3 mr-1"}),p]}),e.jsxs(qe,{variant:"secondary",children:[e.jsx(Xn,{className:"h-3 w-3 mr-1"}),m]}),e.jsx(xi,{className:"h-4 w-4 text-muted-foreground"})]})]},h.id)}),u.length===0&&e.jsx("div",{className:"text-muted-foreground text-center py-8",children:"No campaigns match."})]})]})]})})}function XA({label:s,value:t,icon:n}){return e.jsxs("div",{className:"fsbo-tile p-4",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsx("span",{className:"fsbo-eyebrow text-muted-foreground",children:s}),e.jsx(n,{className:"h-4 w-4 text-accent"})]}),e.jsx("div",{className:"mt-2 text-2xl font-bold",children:t})]})}const NKt={hero:!0,credibility:!0,story:!0,value_stack:!0,calculator:!0,sponsor:!0,testimonials:!0,faq:!0,lead_magnet:!0,event:!0,final_cta:!0,disclaimer:!0},Pjt={hero:"Hero",credibility:"Credibility strip",story:"Why I moved (story)",value_stack:"Value stack",calculator:"Earnings / cap calculator",sponsor:"What you get from me",testimonials:"Proof / testimonials",faq:"Objection-handling FAQ",lead_magnet:"Free download",event:"Upcoming event",final_cta:"Final CTA",disclaimer:"Income disclaimer"},KYn=[{title:"80/20 split with a $16K cap",body:"Keep 100% of your commission after you cap — no desk fees, no royalty fees, no franchise fees.",proof:"Capped agents keep 100% for the rest of their anniversary year."},{title:"Revenue share",body:"Get paid on the production of agents you attract — income that keeps working when you are not.",proof:"7 tiers, paid monthly, willable to your family."},{title:"Stock awards & ICON",body:"Earn equity for your first transaction, capping, and attracting — plus ICON Agent stock awards.",proof:"Ownership in a publicly traded company (NASDAQ: EXPI)."},{title:"Healthcare options",body:"Access to health, dental and vision plan options built for independent contractors.",proof:"Available through the eXp agent healthcare program."},{title:"Tools included",body:"CRM, IDX website, lead engine, transaction management, and marketing tools with no monthly bill.",proof:"Included in your annual technology fee."},{title:"80+ hours of live training weekly",body:"Cloud campus training with top producers — join from anywhere, replays on demand.",proof:"Live in eXp World, every week."},{title:"Worldwide referral network",body:"Tens of thousands of agents across the globe you can refer to and receive from.",proof:"One brokerage, 20+ countries."},{title:"Keep your brand",body:"Run your team, your brand and your business your way — no office politics, no cap on growth.",proof:"You own your database and your brand."}],YYn=[{q:"Is this an MLM?",a:"No. You are paid on real estate commissions you earn. Revenue share is a marketing expense the brokerage pays out of company dollar for agents you personally attract — you never buy inventory, pay to join a downline, or recruit to get paid."},{q:"Do I lose my brand or my team?",a:"No. You keep your name, your team, your logo, and your database. Brokerage branding requirements are minimal and your marketing stays yours."},{q:"What happens to my pending deals?",a:"Most agents close pendings at their current brokerage, or transfer them depending on their agreement. We map every pending file before you sign anything."},{q:"How long does the transition take?",a:"Typically 24-72 hours. Application, license transfer with the state, MLS update, and onboarding. I walk you through each step personally."},{q:"What if I need support or a broker on the phone?",a:"State broker support is available and free. Plus you get me — direct access, not a call center."},{q:"What does it actually cost?",a:"A one-time start-up fee, a small monthly technology fee, and a per-transaction broker review fee until you cap. No desk, royalty, or franchise fees. I will show you the exact math for your production."}],ZYn=[{title:"A 30-day onboarding plan",body:"A written plan for your first 30 days — systems set up, database imported, first campaign live."},{title:"Weekly mastermind",body:"A small-group call with agents at your level, focused on real pipeline, not theory."},{title:"Lead & listing systems",body:"The exact marketing systems I use — plug them into your business on day one."},{title:"Direct access to me",body:"Text me. I answer. You are not a number in someone’s downline."}],XYn="Any income or earnings figures shown are illustrative examples only and are not a guarantee of results. Individual results depend entirely on individual effort, market conditions, and business decisions. Nothing here is an offer of employment or of securities.",QYn={enabled:!0,title:"The Brokerage Comparison Worksheet",body:"A one-page worksheet that shows exactly what you are paying today vs. what you would keep here. No pressure, no follow-up spam.",cta:"Send me the worksheet",file_url:""},JYn={enabled:!0,title:"What would you have kept last year?",cap:16e3,split:80,transaction_fee:250,current_split:70,current_monthly_fees:150};function eZn(s){return{template:"exp_2026",agent_name:s,agent_title:"eXp Realty",eyebrow:"For agents who are done paying for a desk they never use",headline:"Keep more of what you earn — and build something that pays you after the closing.",subheadline:"A private look at how the business actually works here: the numbers, the tools, the support, and what I personally do for the agents who join with me.",cta_label:"Book a confidential 15-min call",story_title:"Why I moved",story_body:"I was not unhappy. I was capped out — paying for an office I never used, watching my splits shrink, and with nothing to show for the agents I sent business to. Here is exactly what changed after I moved, the numbers included.",primary_color:"#0f1b3d",accent_color:"#c9a84c",value_cards:KYn,sponsor_cards:ZYn,faqs:YYn,lead_magnet:QYn,calculator:JYn,sections:NKt,disclaimer:XYn,credibility:[],seo_title:`${s} | A confidential look at joining eXp Realty`,seo_description:"See the real numbers, tools, and support behind the move — plus what you get personally when you partner with me."}}function kKt(s){return s.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)}const mW=V;function tZn(){const{user:s}=ks(),t=ls(),n=["attract-landing-page",s==null?void 0:s.id],{data:r,isLoading:a}=pt({queryKey:n,enabled:!!s,queryFn:async()=>{const{data:c,error:d}=await mW.from("attract_landing_pages").select("*").eq("user_id",s.id).order("created_at",{ascending:!0}).limit(1).maybeSingle();if(d)throw d;return c||null}}),{data:i}=pt({queryKey:["attract-landing-analytics",r==null?void 0:r.id],enabled:!!(r!=null&&r.id),queryFn:async()=>{const{data:c,error:d}=await mW.from("attract_landing_events").select("event_type, section_key, created_at").eq("page_id",r.id).order("created_at",{ascending:!1}).limit(1e3);if(d)throw d;const u=c||[],h=u.filter(g=>g.event_type==="view").length,m=u.filter(g=>g.event_type==="cta_click").length,p=u.filter(g=>g.event_type==="calculator_run").length;return{views:h,ctas:m,calcs:p,conversion:h?Math.round(m/h*100):0}}}),l=Nt({mutationFn:async c=>{const d=kKt(c||"my-attraction-page")||"attraction-page";let u=d;for(let g=0;g<5;g++){const{data:x}=await mW.from("attract_landing_pages").select("id").eq("slug",u).maybeSingle();if(!x)break;u=`${d}-${Math.random().toString(36).slice(2,6)}`}const h=eZn(c||"Your Name"),{data:m,error:p}=await mW.from("attract_landing_pages").insert({...h,user_id:s.id,slug:u}).select("*").single();if(p)throw p;return m},onSuccess:()=>{t.invalidateQueries({queryKey:n}),ae.success("Attraction page created")},onError:c=>ae.error(c.message||"Could not create the page")}),o=Nt({mutationFn:async c=>{const{error:d}=await mW.from("attract_landing_pages").update(c).eq("id",r.id);if(d)throw d},onSuccess:()=>{t.invalidateQueries({queryKey:n}),ae.success("Saved")},onError:c=>{var d;return ae.error((d=c.message)!=null&&d.includes("duplicate")?"That web address is already taken":c.message||"Could not save")}});return{page:r,isLoading:a,analytics:i,createPage:l,savePage:o}}function sZn(){var y,v,_,j,C,A,M,I,P,R,O,B;const{user:s}=ks(),{page:t,isLoading:n,analytics:r,createPage:a,savePage:i}=tZn(),[l,o]=k.useState(null),[c,d]=k.useState(!1);k.useEffect(()=>{t&&o({...t})},[t]);const u=k.useMemo(()=>l!=null&&l.slug?`${window.location.origin}/join/${l.slug}`:"",[l==null?void 0:l.slug]),h=U=>o(G=>({...G,...U})),m=(U,G)=>h({[U]:G}),p=(U,G,H)=>m(U,l[U].map((Y,se)=>se===G?{...Y,...H}:Y)),g=()=>{const{id:U,user_id:G,created_at:H,updated_at:Y,...se}=l;i.mutate({...se,slug:kKt(se.slug)})};if(n)return e.jsx("div",{className:"p-10 text-center text-muted-foreground",children:"Loading…"});if(!t)return e.jsxs("div",{className:"mx-auto max-w-2xl px-6 py-16 text-center",children:[e.jsx("div",{className:"mx-auto mb-6 flex h-14 w-14 items-center justify-center rounded-2xl bg-primary/10 text-primary",children:e.jsx(kn,{className:"h-7 w-7"})}),e.jsx("h1",{className:"mb-3 text-3xl font-bold tracking-tight",children:"Your Attraction Landing Page"}),e.jsx("p",{className:"mb-8 text-muted-foreground",children:"A public page built to convert agents — value stack, earnings calculator, objection-handling FAQ, and a confidential contact form that drops every lead straight into your Attract pipeline."}),e.jsx($,{size:"lg",onClick:()=>{var U;return a.mutate(((U=s==null?void 0:s.user_metadata)==null?void 0:U.full_name)||"My Attraction Page")},disabled:a.isPending,children:a.isPending?"Creating…":"Create my page"})]});if(!l)return null;if(c)return e.jsxs("div",{children:[e.jsxs("div",{className:"sticky top-0 z-50 flex items-center justify-between border-b bg-background px-4 py-3",children:[e.jsx("span",{className:"text-sm font-medium",children:"Preview"}),e.jsx($,{variant:"outline",size:"sm",onClick:()=>d(!1),children:"Back to editor"})]}),e.jsx(dKt,{cfg:l,preview:!0})]});const x={...NKt,...l.sections||{}};return e.jsxs("div",{className:"mx-auto max-w-5xl px-4 py-8 md:px-6",children:[e.jsxs("div",{className:"mb-6 flex flex-wrap items-start justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold tracking-tight md:text-3xl",children:"Attraction Landing Page"}),e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:"Built to convert producing agents into conversations."})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs($,{variant:"outline",size:"sm",onClick:()=>d(!0),children:[e.jsx(ba,{className:"mr-2 h-4 w-4"})," Preview"]}),l.is_published&&e.jsx($,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("a",{href:u,target:"_blank",rel:"noreferrer",children:[e.jsx(Ir,{className:"mr-2 h-4 w-4"})," View live"]})}),e.jsxs($,{size:"sm",onClick:g,disabled:i.isPending,children:[e.jsx(Ml,{className:"mr-2 h-4 w-4"})," ",i.isPending?"Saving…":"Save changes"]})]})]}),e.jsx("div",{className:"mb-6 grid gap-3 sm:grid-cols-4",children:[{label:"Page views",value:(r==null?void 0:r.views)??0},{label:"CTA clicks",value:(r==null?void 0:r.ctas)??0},{label:"Calculator runs",value:(r==null?void 0:r.calcs)??0},{label:"Click rate",value:`${(r==null?void 0:r.conversion)??0}%`}].map(U=>e.jsx(we,{children:e.jsxs(De,{className:"p-4",children:[e.jsx("div",{className:"text-xs uppercase tracking-wider text-muted-foreground",children:U.label}),e.jsx("div",{className:"mt-1 text-2xl font-bold",children:U.value})]})},U.label))}),e.jsxs(ya,{defaultValue:"content",children:[e.jsxs(va,{className:"mb-6 flex-wrap",children:[e.jsx(is,{value:"content",children:"Content"}),e.jsx(is,{value:"proof",children:"Proof & FAQ"}),e.jsx(is,{value:"calculator",children:"Calculator"}),e.jsx(is,{value:"sections",children:"Sections"}),e.jsx(is,{value:"publish",children:"Publish"})]}),e.jsxs(cs,{value:"content",className:"space-y-6",children:[e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsx(Yt,{className:"text-base",children:"Hero"})}),e.jsxs(De,{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(Em,{label:"Your name",value:l.agent_name,onChange:U=>h({agent_name:U})}),e.jsx(Em,{label:"Title / brokerage",value:l.agent_title,onChange:U=>h({agent_title:U})}),e.jsx(Em,{label:"Eyebrow line",value:l.eyebrow,onChange:U=>h({eyebrow:U}),className:"md:col-span-2"}),e.jsxs("div",{className:"md:col-span-2 space-y-1.5",children:[e.jsx(re,{children:"Headline"}),e.jsx(Ls,{rows:2,value:l.headline||"",onChange:U=>h({headline:U.target.value})})]}),e.jsxs("div",{className:"md:col-span-2 space-y-1.5",children:[e.jsx(re,{children:"Subheadline"}),e.jsx(Ls,{rows:3,value:l.subheadline||"",onChange:U=>h({subheadline:U.target.value})})]}),e.jsx(Em,{label:"Button text",value:l.cta_label,onChange:U=>h({cta_label:U})}),e.jsx(Em,{label:"Scheduling link (Calendly etc.)",value:l.calendar_url,onChange:U=>h({calendar_url:U})}),e.jsx(Em,{label:"Headshot URL",value:l.headshot_url,onChange:U=>h({headshot_url:U})}),e.jsx(Em,{label:"Hero background image URL",value:l.hero_image_url,onChange:U=>h({hero_image_url:U})}),e.jsx(Em,{label:"Logo URL",value:l.logo_url,onChange:U=>h({logo_url:U})}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsx(Em,{label:"Primary color",type:"color",value:l.primary_color,onChange:U=>h({primary_color:U})}),e.jsx(Em,{label:"Accent color",type:"color",value:l.accent_color,onChange:U=>h({accent_color:U})})]}),e.jsx(Em,{label:"Phone",value:l.phone,onChange:U=>h({phone:U})}),e.jsx(Em,{label:"Email",value:l.email,onChange:U=>h({email:U})})]})]}),e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsx(Yt,{className:"text-base",children:"Credibility strip"})}),e.jsxs(De,{className:"space-y-3",children:[(l.credibility||[]).map((U,G)=>e.jsxs(fW,{onRemove:()=>m("credibility",l.credibility.filter((H,Y)=>Y!==G)),children:[e.jsx(be,{placeholder:"Value (e.g. $42M)",value:U.value||"",onChange:H=>p("credibility",G,{value:H.target.value})}),e.jsx(be,{placeholder:"Label (e.g. Closed volume)",value:U.label||"",onChange:H=>p("credibility",G,{label:H.target.value})})]},G)),e.jsx(pW,{onClick:()=>m("credibility",[...l.credibility||[],{value:"",label:""}]),label:"Add stat"})]})]}),e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsx(Yt,{className:"text-base",children:"Your story"})}),e.jsxs(De,{className:"space-y-4",children:[e.jsx(Em,{label:"Section title",value:l.story_title,onChange:U=>h({story_title:U})}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Story"}),e.jsx(Ls,{rows:6,value:l.story_body||"",onChange:U=>h({story_body:U.target.value})})]}),e.jsx(Em,{label:"Story video URL (YouTube, Vimeo, Loom, MP4)",value:l.story_video_url,onChange:U=>h({story_video_url:U})})]})]}),e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsx(Yt,{className:"text-base",children:"Value stack"})}),e.jsxs(De,{className:"space-y-4",children:[(l.value_cards||[]).map((U,G)=>e.jsxs(fW,{vertical:!0,onRemove:()=>m("value_cards",l.value_cards.filter((H,Y)=>Y!==G)),children:[e.jsx(be,{placeholder:"Title",value:U.title||"",onChange:H=>p("value_cards",G,{title:H.target.value})}),e.jsx(Ls,{rows:2,placeholder:"Description",value:U.body||"",onChange:H=>p("value_cards",G,{body:H.target.value})}),e.jsx(be,{placeholder:"Proof point (optional)",value:U.proof||"",onChange:H=>p("value_cards",G,{proof:H.target.value})})]},G)),e.jsx(pW,{onClick:()=>m("value_cards",[...l.value_cards||[],{title:"",body:""}]),label:"Add value card"})]})]}),e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsx(Yt,{className:"text-base",children:"What you get from me"})}),e.jsxs(De,{className:"space-y-4",children:[(l.sponsor_cards||[]).map((U,G)=>e.jsxs(fW,{vertical:!0,onRemove:()=>m("sponsor_cards",l.sponsor_cards.filter((H,Y)=>Y!==G)),children:[e.jsx(be,{placeholder:"Title",value:U.title||"",onChange:H=>p("sponsor_cards",G,{title:H.target.value})}),e.jsx(Ls,{rows:2,placeholder:"Description",value:U.body||"",onChange:H=>p("sponsor_cards",G,{body:H.target.value})})]},G)),e.jsx(pW,{onClick:()=>m("sponsor_cards",[...l.sponsor_cards||[],{title:"",body:""}]),label:"Add commitment"})]})]}),e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsx(Yt,{className:"text-base",children:"Free download & upcoming event"})}),e.jsxs(De,{className:"space-y-4",children:[e.jsx(Em,{label:"Download title",value:(y=l.lead_magnet)==null?void 0:y.title,onChange:U=>h({lead_magnet:{...l.lead_magnet,title:U}})}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Download description"}),e.jsx(Ls,{rows:2,value:((v=l.lead_magnet)==null?void 0:v.body)||"",onChange:U=>h({lead_magnet:{...l.lead_magnet,body:U.target.value}})})]}),e.jsx(Em,{label:"File URL",value:(_=l.lead_magnet)==null?void 0:_.file_url,onChange:U=>h({lead_magnet:{...l.lead_magnet,file_url:U}})}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-3",children:[e.jsx(Em,{label:"Event title",value:(j=l.event_block)==null?void 0:j.title,onChange:U=>h({event_block:{...l.event_block,title:U}})}),e.jsx(Em,{label:"When",value:(C=l.event_block)==null?void 0:C.when,onChange:U=>h({event_block:{...l.event_block,when:U}})}),e.jsx(Em,{label:"Registration link",value:(A=l.event_block)==null?void 0:A.url,onChange:U=>h({event_block:{...l.event_block,url:U}})})]})]})]})]}),e.jsxs(cs,{value:"proof",className:"space-y-6",children:[e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsx(Yt,{className:"text-base",children:"Testimonials"})}),e.jsxs(De,{className:"space-y-4",children:[(l.testimonials||[]).map((U,G)=>e.jsxs(fW,{vertical:!0,onRemove:()=>m("testimonials",l.testimonials.filter((H,Y)=>Y!==G)),children:[e.jsx(Ls,{rows:3,placeholder:"Quote",value:U.quote||"",onChange:H=>p("testimonials",G,{quote:H.target.value})}),e.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[e.jsx(be,{placeholder:"Name",value:U.name||"",onChange:H=>p("testimonials",G,{name:H.target.value})}),e.jsx(be,{placeholder:"Role / market",value:U.role||"",onChange:H=>p("testimonials",G,{role:H.target.value})}),e.jsx(be,{placeholder:"Photo URL",value:U.photo_url||"",onChange:H=>p("testimonials",G,{photo_url:H.target.value})})]})]},G)),e.jsx(pW,{onClick:()=>m("testimonials",[...l.testimonials||[],{quote:"",name:""}]),label:"Add testimonial"})]})]}),e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsx(Yt,{className:"text-base",children:"Objection-handling FAQ"})}),e.jsxs(De,{className:"space-y-4",children:[(l.faqs||[]).map((U,G)=>e.jsxs(fW,{vertical:!0,onRemove:()=>m("faqs",l.faqs.filter((H,Y)=>Y!==G)),children:[e.jsx(be,{placeholder:"Question",value:U.q||"",onChange:H=>p("faqs",G,{q:H.target.value})}),e.jsx(Ls,{rows:3,placeholder:"Answer",value:U.a||"",onChange:H=>p("faqs",G,{a:H.target.value})})]},G)),e.jsx(pW,{onClick:()=>m("faqs",[...l.faqs||[],{q:"",a:""}]),label:"Add question"})]})]}),e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsx(Yt,{className:"text-base",children:"Income disclaimer"})}),e.jsx(De,{children:e.jsx(Ls,{rows:4,value:l.disclaimer||"",onChange:U=>h({disclaimer:U.target.value})})})]})]}),e.jsx(cs,{value:"calculator",children:e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsx(Yt,{className:"text-base",children:"Earnings calculator"})}),e.jsxs(De,{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(Em,{label:"Section title",value:(M=l.calculator)==null?void 0:M.title,onChange:U=>h({calculator:{...l.calculator,title:U}}),className:"md:col-span-2"}),e.jsx(Em,{label:"Cap ($)",type:"number",value:(I=l.calculator)==null?void 0:I.cap,onChange:U=>h({calculator:{...l.calculator,cap:Number(U)}})}),e.jsx(Em,{label:"Your split (%)",type:"number",value:(P=l.calculator)==null?void 0:P.split,onChange:U=>h({calculator:{...l.calculator,split:Number(U)}})}),e.jsx(Em,{label:"Per-transaction fee ($)",type:"number",value:(R=l.calculator)==null?void 0:R.transaction_fee,onChange:U=>h({calculator:{...l.calculator,transaction_fee:Number(U)}})}),e.jsx(Em,{label:"Typical competitor split (%)",type:"number",value:(O=l.calculator)==null?void 0:O.current_split,onChange:U=>h({calculator:{...l.calculator,current_split:Number(U)}})}),e.jsx(Em,{label:"Typical competitor monthly fees ($)",type:"number",value:(B=l.calculator)==null?void 0:B.current_monthly_fees,onChange:U=>h({calculator:{...l.calculator,current_monthly_fees:Number(U)}})}),e.jsx("p",{className:"text-xs text-muted-foreground md:col-span-2",children:"The calculator shows estimates only and always displays your disclaimer at the bottom of the page."})]})]})}),e.jsx(cs,{value:"sections",children:e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsx(Yt,{className:"text-base",children:"Show or hide sections"})}),e.jsx(De,{className:"divide-y",children:Object.keys(Pjt).map(U=>e.jsxs("div",{className:"flex items-center justify-between py-3",children:[e.jsx("span",{className:"text-sm",children:Pjt[U]}),e.jsx(On,{checked:x[U]!==!1,onCheckedChange:G=>h({sections:{...x,[U]:G}})})]},U))})]})}),e.jsxs(cs,{value:"publish",className:"space-y-6",children:[e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsx(Yt,{className:"text-base",children:"Publishing"})}),e.jsxs(De,{className:"space-y-5",children:[e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:"Page is live"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Turn on to make your page publicly reachable."})]}),e.jsx(On,{checked:!!l.is_published,onCheckedChange:U=>h({is_published:U})})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:"Hide from search engines"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Recommended — keep this page for direct outreach only."})]}),e.jsx(On,{checked:!!l.noindex,onCheckedChange:U=>h({noindex:U})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Web address"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(be,{value:l.slug||"",onChange:U=>h({slug:U.target.value})}),e.jsx($,{variant:"outline",onClick:()=>{navigator.clipboard.writeText(u),ae.success("Link copied")},children:e.jsx(Da,{className:"h-4 w-4"})})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:u})]}),e.jsx(Em,{label:"Search title",value:l.seo_title,onChange:U=>h({seo_title:U})}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Search description"}),e.jsx(Ls,{rows:2,value:l.seo_description||"",onChange:U=>h({seo_description:U.target.value})})]})]})]}),e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsxs(Yt,{className:"flex items-center gap-2 text-base",children:[e.jsx(Ul,{className:"h-4 w-4"})," Where leads go"]})}),e.jsx(De,{className:"text-sm text-muted-foreground",children:"Every submission creates or updates a prospect in your Attract pipeline, logs an activity, and emails you a notification. Calculator runs and CTA clicks are tracked so you can see what is working."})]})]})]}),e.jsx("div",{className:"mt-8 flex justify-end",children:e.jsxs($,{onClick:g,disabled:i.isPending,children:[e.jsx(Ml,{className:"mr-2 h-4 w-4"})," ",i.isPending?"Saving…":"Save changes"]})})]})}function Em({label:s,value:t,onChange:n,type:r="text",className:a}){return e.jsxs("div",{className:`space-y-1.5 ${a||""}`,children:[e.jsx(re,{children:s}),e.jsx(be,{type:r,value:t??"",onChange:i=>n(i.target.value)})]})}function fW({children:s,onRemove:t,vertical:n}){return e.jsxs("div",{className:"flex items-start gap-3 rounded-lg border p-3",children:[e.jsx("div",{className:n?"flex-1 space-y-2":"grid flex-1 gap-2 md:grid-cols-2",children:s}),e.jsx($,{variant:"ghost",size:"icon",onClick:t,className:"text-muted-foreground hover:text-destructive",children:e.jsx(Un,{className:"h-4 w-4"})})]})}function pW({onClick:s,label:t}){return e.jsxs($,{variant:"outline",size:"sm",onClick:s,children:[e.jsx(nn,{className:"mr-2 h-4 w-4"})," ",t]})}function nZn(s){const{user:t}=ks(),n=ls(),r=pt({queryKey:["admin-attract-list",s,t==null?void 0:t.id],enabled:!!t,queryFn:async()=>{let o=V.from("profiles").select("id, email, full_name").order("full_name",{ascending:!0}).limit(100);if(s.trim()){const m=`%${s.trim()}%`;o=o.or(`email.ilike.${m},full_name.ilike.${m}`)}const{data:c,error:d}=await o;if(d)throw d;const u=(c??[]).map(m=>m.id);let h={};if(u.length){const{data:m,error:p}=await V.from("feature_entitlements").select("user_id, enabled, tier, enabled_at, expires_at, notes, enabled_by").eq("feature_key","levelup_attract").in("user_id",u);if(p)throw p;(m??[]).forEach(g=>{h[g.user_id]=g})}return(c??[]).map(m=>{var p,g,x,y,v,_;return{user_id:m.id,email:m.email,full_name:m.full_name,enabled:!!((p=h[m.id])!=null&&p.enabled),tier:((g=h[m.id])==null?void 0:g.tier)??null,enabled_at:((x=h[m.id])==null?void 0:x.enabled_at)??null,expires_at:((y=h[m.id])==null?void 0:y.expires_at)??null,notes:((v=h[m.id])==null?void 0:v.notes)??null,enabled_by:((_=h[m.id])==null?void 0:_.enabled_by)??null}})}}),a=pt({queryKey:["admin-attract-audit",t==null?void 0:t.id],enabled:!!t,queryFn:async()=>{const{data:o,error:c}=await V.from("feature_entitlement_audit").select("*").eq("feature_key","levelup_attract").order("created_at",{ascending:!1}).limit(50);if(c)throw c;return o??[]}}),i=Nt({mutationFn:async({target_user_id:o,tier:c,expires_at:d,notes:u})=>{const h={user_id:o,feature_key:"levelup_attract",enabled:!0,tier:c??"beta",enabled_by:t.id,enabled_at:new Date().toISOString(),expires_at:d??null,notes:u??null},{error:m}=await V.from("feature_entitlements").upsert(h,{onConflict:"user_id,feature_key"});if(m)throw m;await V.from("feature_entitlement_audit").insert({feature_key:"levelup_attract",target_user_id:o,action:"grant",tier:h.tier,expires_at:h.expires_at,notes:h.notes,performed_by:t.id})},onSuccess:()=>{n.invalidateQueries({queryKey:["admin-attract-list"]}),n.invalidateQueries({queryKey:["admin-attract-audit"]}),ae.success("Access granted")},onError:o=>ae.error(o.message)}),l=Nt({mutationFn:async o=>{const{error:c}=await V.from("feature_entitlements").update({enabled:!1}).eq("user_id",o).eq("feature_key","levelup_attract");if(c)throw c;await V.from("feature_entitlement_audit").insert({feature_key:"levelup_attract",target_user_id:o,action:"revoke",performed_by:t.id})},onSuccess:()=>{n.invalidateQueries({queryKey:["admin-attract-list"]}),n.invalidateQueries({queryKey:["admin-attract-audit"]}),ae.success("Access revoked")},onError:o=>ae.error(o.message)});return{list:r,audit:a,grant:i,revoke:l}}function rZn(){const[s,t]=k.useState(""),{list:n,audit:r,grant:a,revoke:i}=nZn(s),[l,o]=k.useState(null),[c,d]=k.useState(null),[u,h]=k.useState("beta"),[m,p]=k.useState(""),[g,x]=k.useState(""),y=_=>{d(_),h(_.tier??"beta"),p(_.expires_at?_.expires_at.slice(0,10):""),x(_.notes??"")},v=async()=>{c&&(await a.mutateAsync({target_user_id:c.user_id,tier:u,expires_at:m?new Date(m).toISOString():null,notes:g||void 0}),d(null))};return e.jsxs("div",{className:"p-6",children:[e.jsx(nm,{title:"LevelUp Attract — Access Management",description:"Grant or revoke access to LevelUp Attract for individual members. Every change is audited."}),e.jsx(we,{className:"p-4 rounded-2xl mb-4",children:e.jsxs("div",{className:"relative max-w-md",children:[e.jsx(Yr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400"}),e.jsx(be,{value:s,onChange:_=>t(_.target.value),placeholder:"Search by name or email...",className:"pl-9"})]})}),e.jsxs(we,{className:"rounded-2xl overflow-hidden mb-8",children:[e.jsxs("div",{className:"grid grid-cols-[1fr_auto_auto_auto] gap-3 px-5 py-3 text-[11px] uppercase tracking-widest text-slate-500 font-semibold border-b",children:[e.jsx("div",{children:"Member"}),e.jsx("div",{children:"Access"}),e.jsx("div",{children:"Enabled"}),e.jsx("div",{children:"Actions"})]}),n.isLoading&&e.jsx("div",{className:"p-6 text-center text-slate-500 text-sm",children:"Loading members…"}),!n.isLoading&&(n.data??[]).length===0&&e.jsx("div",{className:"p-6 text-center text-slate-500 text-sm",children:"No members match."}),(n.data??[]).map(_=>e.jsxs("div",{className:"grid grid-cols-[1fr_auto_auto_auto] gap-3 px-5 py-3 items-center border-b last:border-0 hover:bg-slate-50",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-[13.5px] font-medium text-slate-900 truncate",children:_.full_name||_.email||_.user_id}),e.jsx("div",{className:"text-[11.5px] text-slate-500 truncate",children:_.email})]}),e.jsx("div",{children:_.enabled?e.jsxs(qe,{className:"bg-emerald-100 text-emerald-800 border-0 gap-1",children:[e.jsx(kn,{className:"h-3 w-3"})," ",_.tier??"enabled"]}):e.jsx(qe,{variant:"outline",className:"text-slate-500",children:"Not enabled"})}),e.jsx("div",{className:"text-[11.5px] text-slate-500 whitespace-nowrap",children:_.enabled_at?Ys(new Date(_.enabled_at),"MMM d, yyyy"):"—"}),e.jsx("div",{className:"flex gap-1.5",children:_.enabled?e.jsxs(e.Fragment,{children:[e.jsx($,{size:"sm",variant:"outline",onClick:()=>y(_),children:"Edit"}),e.jsx($,{size:"sm",variant:"ghost",className:"text-rose-600",onClick:()=>o({user:_,action:"revoke"}),children:"Revoke"})]}):e.jsxs($,{size:"sm",className:"bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>y(_),children:[e.jsx(b0,{className:"h-3.5 w-3.5 mr-1"})," Enable"]})})]},_.user_id))]}),e.jsxs(we,{className:"rounded-2xl p-5",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3 text-[12px] uppercase tracking-widest text-slate-500 font-semibold",children:[e.jsx(b2,{className:"h-3.5 w-3.5"})," Recent audit history"]}),r.isLoading&&e.jsx("div",{className:"text-slate-500 text-sm",children:"Loading…"}),(r.data??[]).length===0&&!r.isLoading&&e.jsx("div",{className:"text-slate-500 text-sm",children:"No changes yet."}),e.jsx("div",{className:"space-y-1.5",children:(r.data??[]).map(_=>e.jsxs("div",{className:"text-[12.5px] text-slate-700 flex items-center gap-2",children:[e.jsx(qe,{variant:"outline",className:"text-[10.5px] capitalize",children:_.action}),e.jsx("span",{className:"font-mono text-[11px] text-slate-500",children:_.target_user_id.slice(0,8)}),_.tier&&e.jsxs("span",{className:"text-slate-500",children:["· ",_.tier]}),_.notes&&e.jsxs("span",{className:"text-slate-500",children:["· ",_.notes]}),e.jsx("span",{className:"text-slate-400 ml-auto",children:Ys(new Date(_.created_at),"MMM d h:mm a")})]},_.id))})]}),e.jsx(zs,{open:!!c,onOpenChange:_=>!_&&d(null),children:e.jsxs(Rs,{children:[e.jsxs(Vs,{children:[e.jsxs($s,{children:[c!=null&&c.enabled?"Update":"Enable"," Attract access"]}),e.jsx(Cr,{children:(c==null?void 0:c.full_name)||(c==null?void 0:c.email)})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Tier"}),e.jsxs(bs,{value:u,onValueChange:h,children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"beta",children:"Beta"}),e.jsx(We,{value:"standard",children:"Standard"}),e.jsx(We,{value:"pro",children:"Pro"}),e.jsx(We,{value:"founder",children:"Founder"})]})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Expires (optional)"}),e.jsx(be,{type:"date",value:m,onChange:_=>p(_.target.value)})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Internal notes (optional)"}),e.jsx(Ls,{rows:2,value:g,onChange:_=>x(_.target.value)})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"ghost",onClick:()=>d(null),children:"Cancel"}),e.jsx($,{className:"bg-gradient-to-r from-violet-600 to-indigo-600",onClick:v,disabled:a.isPending,children:c!=null&&c.enabled?"Save changes":"Enable access"})]})]})}),e.jsx(oc,{open:!!l,onOpenChange:_=>!_&&o(null),children:e.jsxs(Ql,{children:[e.jsxs(Jl,{children:[e.jsx(tc,{children:"Revoke Attract access?"}),e.jsxs(sc,{children:[(l==null?void 0:l.user.full_name)||(l==null?void 0:l.user.email)," will lose access to LevelUp Attract immediately. Their data is preserved and access can be re-enabled."]})]}),e.jsxs(ec,{children:[e.jsx(nc,{children:"Cancel"}),e.jsxs(Vl,{className:"bg-rose-600 hover:bg-rose-700",onClick:async()=>{l&&await i.mutateAsync(l.user.user_id),o(null)},children:[e.jsx(ju,{className:"h-4 w-4 mr-1.5"})," Revoke access"]})]})]})})]})}const aZn=({team:s,onSelect:t})=>{const{data:n}=pt({queryKey:["team-card-info",s.id],queryFn:async()=>{const{data:r}=await V.from("team_members").select("user_id, role").eq("team_id",s.id),a=(r==null?void 0:r.length)||0,i=r==null?void 0:r.find(o=>o.role==="team_leader");let l=null;if(i){const{data:o}=await V.from("profiles").select("name, avatar_url").eq("id",i.user_id).single();l=o}return{count:a,leaderProfile:l}}});return e.jsxs(we,{className:"cursor-pointer hover:shadow-md transition-shadow group",onClick:t,children:[e.jsx(Vt,{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(Yt,{className:"text-lg truncate",children:s.name}),s.description&&e.jsx(vr,{className:"mt-1 line-clamp-2",children:s.description})]}),e.jsxs(qe,{variant:"secondary",className:"ml-2 shrink-0",children:[e.jsx(Xn,{className:"h-3 w-3 mr-1"}),(n==null?void 0:n.count)??"…"]})]})}),e.jsxs(De,{className:"space-y-3",children:[(n==null?void 0:n.leaderProfile)&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(Wa,{className:"h-6 w-6",children:[e.jsx(eo,{src:n.leaderProfile.avatar_url||""}),e.jsx(Ka,{className:"text-xs",children:(n.leaderProfile.name||"?").charAt(0).toUpperCase()})]}),e.jsxs("span",{className:"text-sm text-muted-foreground flex items-center gap-1",children:[e.jsx(ky,{className:"h-3 w-3 text-[hsl(var(--chart-4))]"}),n.leaderProfile.name||"Team Leader"]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap text-sm text-muted-foreground",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Ng,{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(qe,{variant:"outline",className:"text-xs py-0",children:"Lead Pond"}),s.shared_assets_enabled&&e.jsx(qe,{variant:"outline",className:"text-xs py-0",children:"Shared Assets"}),s.shared_videos_enabled&&e.jsx(qe,{variant:"outline",className:"text-xs py-0",children:"Shared Videos"})]})]})]})},iZn=()=>{const{user:s,isAdmin:t,isBrokerageManager:n,brokerageId:r,managedBrokerages:a,selectedBrokerageId:i}=ks(),l=i||(a.length>0?a[0].id:r),o=t?void 0:l||void 0,{teams:c,isLoading:d,createTeam:u,updateTeam:h,deleteTeam:m,addMember:p,removeMember:g,updateMemberRole:x}=dA(o),[y,v]=k.useState(!1),[_,j]=k.useState(null),{data:C}=pt({queryKey:["all-brokerages-for-teams"],queryFn:async()=>{const{data:I,error:P}=await V.from("brokerages").select("id, name").order("name");if(P)throw P;return I||[]},enabled:t}),{data:A}=pt({queryKey:["brokerage-agents-for-teams",l],queryFn:async()=>{const{data:I,error:P}=await V.from("profiles").select("id, name, email, avatar_url").eq("brokerage_id",l).order("name");if(P)throw P;return I||[]},enabled:!!l}),M=async I=>{const P=I.brokerage_id||l||null,R=await u.mutateAsync({name:I.name,brokerage_id:P,description:I.description});if(I.leaderId&&I.leaderId!=="none"&&await p.mutateAsync({team_id:R.id,user_id:I.leaderId,role:"team_leader"}),I.memberIds)for(const O of I.memberIds)await p.mutateAsync({team_id:R.id,user_id:O,role:"team_member"});v(!1)};return!n&&!t?e.jsx(Xs,{title:"Teams",description:"Team Management",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Xn,{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(Xs,{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($,{onClick:()=>v(!0),children:[e.jsx(nn,{className:"mr-2 h-4 w-4"}),"Create Team"]})]}),e.jsx(ARt,{open:y,onOpenChange:v,onCreateTeam:M,isCreating:u.isPending,brokerageAgents:A||[],isAdmin:t,allBrokerages:C,activeBrokerageId:l}),d&&e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:[1,2,3].map(I=>e.jsx(we,{children:e.jsxs(De,{className:"p-6",children:[e.jsx(fn,{className:"h-5 w-32 mb-3"}),e.jsx(fn,{className:"h-4 w-48 mb-4"}),e.jsx(fn,{className:"h-8 w-full"})]})},I))}),!d&&c.length===0&&!_&&e.jsx(we,{children:e.jsxs(De,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Xn,{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($,{onClick:()=>v(!0),children:[e.jsx(nn,{className:"mr-2 h-4 w-4"}),"Create Your First Team"]})]})}),!d&&c.length>0&&!_&&e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:c.map(I=>e.jsx(aZn,{team:I,onSelect:()=>j(I)},I.id))}),_&&e.jsx(CRt,{team:_,brokerageAgents:A||[],onBack:()=>j(null),onUpdate:I=>h.mutateAsync({id:_.id,...I}).then(P=>j(P)),onAddMember:(I,P)=>p.mutateAsync({team_id:_.id,user_id:I,role:P}),onRemoveMember:I=>g.mutateAsync({team_id:_.id,member_id:I}),onUpdateRole:(I,P)=>x.mutateAsync({team_id:_.id,member_id:I,role:P}),onDeleteTeam:()=>m.mutate(_.id),isUpdating:h.isPending,isAddingMember:p.isPending})]})})},oZn=({team:s})=>{const{updateTeam:t}=dA(),n=r=>t.mutate({id:s.id,...r});return e.jsxs("div",{className:"space-y-6",children:[e.jsxs(we,{children:[e.jsxs(Vt,{children:[e.jsx(Yt,{className:"text-lg",children:"Team Settings"}),e.jsx(vr,{children:"Control how your team shares contacts, leads, and assets."})]}),e.jsxs(De,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Contact Visibility"}),e.jsxs(bs,{defaultValue:s.contact_visibility,onValueChange:r=>n({contact_visibility:r}),children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"private",children:"Private — Members keep their contacts private"}),e.jsx(We,{value:"leader_only",children:"Leader Only — Only team leaders can see member contacts"}),e.jsx(We,{value:"full_team",children:"Full Team — All team members can see shared contacts"})]})]})]}),e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Lead Pond"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Shared lead pool — anyone on the team can contribute leads and claim them."})]}),e.jsx(On,{checked:s.lead_pond_enabled,onCheckedChange:r=>n({lead_pond_enabled:r})})]}),e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx(re,{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(On,{checked:s.shared_assets_enabled,onCheckedChange:r=>n({shared_assets_enabled:r})})]})]})]}),s.lead_pond_enabled&&e.jsx(jRt,{teamId:s.id})]})},lZn=()=>{const{data:s,isLoading:t,teams:n,activeTeamId:r,setActiveTeamId:a}=gj(),{useTeamMembers:i}=dA(),{data:l=[],isLoading:o}=i((s==null?void 0:s.teamId)||"");if(t)return e.jsx(Xs,{title:"My Team",description:"Your team",children:e.jsxs("div",{className:"space-y-4",children:[e.jsx(fn,{className:"h-8 w-48"}),e.jsx(fn,{className:"h-40 w-full"})]})});if(!s)return e.jsx(Xs,{title:"My Team",description:"Your team",children:e.jsx(we,{children:e.jsxs(De,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Xn,{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 c=s.team;return e.jsx(Xs,{title:"My Team",description:c.name,children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[n.length>1&&e.jsx("div",{className:"flex flex-wrap gap-2 mb-3",children:n.map(d=>{var u;return e.jsxs("button",{onClick:()=>a(d.teamId),className:"rounded-full border px-3 py-1 text-sm transition-colors "+(d.teamId===r?"bg-primary text-primary-foreground border-primary":"bg-background text-muted-foreground hover:bg-muted"),children:[(u=d.team)==null?void 0:u.name,d.role==="team_leader"&&e.jsx(ky,{className:"ml-1 inline h-3 w-3"})]},d.teamId)})}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("h2",{className:"text-2xl font-bold tracking-tight",children:c.name}),e.jsx(qe,{variant:s.role==="team_leader"?"default":"secondary",className:"capitalize",children:s.role==="team_leader"?e.jsxs(e.Fragment,{children:[e.jsx(ky,{className:"mr-1 h-3 w-3"})," Leader"]}):"Member"})]}),c.description&&e.jsx("p",{className:"text-muted-foreground mt-1",children:c.description})]}),e.jsxs(ya,{defaultValue:"members",className:"space-y-4",children:[e.jsxs(va,{className:"flex-wrap",children:[e.jsx(is,{value:"members",children:"Members"}),c.contact_visibility!=="private"&&e.jsxs(is,{value:"contacts",children:[e.jsx(O8,{className:"mr-1 h-3.5 w-3.5"}),"Team Contacts"]}),c.lead_pond_enabled&&e.jsxs(is,{value:"lead-pond",children:[e.jsx(pb,{className:"mr-1 h-3.5 w-3.5"}),"Lead Pond"]}),c.shared_assets_enabled&&e.jsxs(is,{value:"shared-assets",children:[e.jsx(d1,{className:"mr-1 h-3.5 w-3.5"}),"Shared Assets"]}),s.role==="team_leader"&&e.jsxs(is,{value:"settings",children:[e.jsx(Yc,{className:"mr-1 h-3.5 w-3.5"}),"Settings"]})]}),e.jsx(cs,{value:"members",className:"space-y-2",children:o?e.jsx("div",{className:"space-y-3",children:[1,2,3].map(d=>e.jsx(fn,{className:"h-16 w-full"},d))}):l.map(d=>{var u,h,m,p;return e.jsx(we,{children:e.jsxs(De,{className:"flex items-center gap-3 p-4",children:[e.jsxs(Wa,{className:"h-10 w-10",children:[e.jsx(eo,{src:((u=d.profile)==null?void 0:u.avatar_url)||""}),e.jsx(Ka,{children:(((h=d.profile)==null?void 0:h.name)||"?").charAt(0).toUpperCase()})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium",children:((m=d.profile)==null?void 0:m.name)||"Unknown"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:(p=d.profile)==null?void 0:p.email})]}),d.role==="team_leader"?e.jsxs(qe,{className:"ml-auto bg-amber-500/10 text-amber-600 border-amber-500",children:[e.jsx(ky,{className:"mr-1 h-3 w-3"})," Leader"]}):e.jsx(qe,{variant:"secondary",className:"ml-auto",children:"Member"})]})},d.id)})}),c.contact_visibility!=="private"&&e.jsx(cs,{value:"contacts",className:"space-y-4",children:e.jsx(tYe,{})}),c.lead_pond_enabled&&e.jsx(cs,{value:"lead-pond",className:"space-y-4",children:e.jsx(sYe,{teamId:s.teamId})}),c.shared_assets_enabled&&e.jsx(cs,{value:"shared-assets",className:"space-y-4",children:e.jsx(SRt,{teamId:s.teamId})}),s.role==="team_leader"&&e.jsx(cs,{value:"settings",className:"space-y-4",children:e.jsx(oZn,{team:c})})]},s.teamId)]})})},Ijt={Home:"🏠",Search:"🔍",DollarSign:"💰",Coffee:"☕",Calendar:"📅",Users:"👥",Phone:"📞",Video:"🎥"};function cZn({types:s,onSave:t,onDelete:n}){const[r,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,is_coaching_only:!1}),l(!0)},c=u=>{a({...u}),l(!0)},d=()=>{r!=null&&r.name&&(t(r),l(!1),a(null))};return e.jsxs(e.Fragment,{children:[e.jsxs(we,{children:[e.jsxs(Vt,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Yt,{children:"Booking Types"}),e.jsx(vr,{children:"The meeting types prospects can book with you"})]}),e.jsxs($,{onClick:o,size:"sm",children:[e.jsx(nn,{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(u=>e.jsxs("div",{className:"flex items-center justify-between p-4 rounded-lg border hover:bg-muted/50 transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-lg flex items-center justify-center text-lg",style:{backgroundColor:u.color+"20"},children:Ijt[u.icon]||"📅"}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"font-medium",children:u.name}),!u.is_active&&e.jsx(qe,{variant:"secondary",className:"text-xs",children:"Inactive"}),u.is_coaching_only&&e.jsx(qe,{variant:"outline",className:"text-xs",children:"Coaching only"}),u.qualification_enabled&&e.jsxs(qe,{variant:"outline",className:"text-xs gap-1",children:[e.jsx(zK,{className:"h-3 w-3"})," Qualifying"]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(sa,{className:"h-3 w-3"}),u.duration_minutes," min",u.description&&e.jsxs("span",{children:["· ",u.description.slice(0,60),u.description.length>60?"...":""]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx($,{variant:"ghost",size:"sm",onClick:()=>c(u),children:e.jsx(ui,{className:"h-4 w-4"})}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>n(u.id),className:"text-destructive hover:text-destructive",children:e.jsx(Un,{className:"h-4 w-4"})})]})]},u.id))})})]}),e.jsx(zs,{open:i,onOpenChange:l,children:e.jsxs(Rs,{children:[e.jsx(Vs,{children:e.jsxs($s,{children:[r!=null&&r.id?"Edit":"New"," Booking Type"]})}),r&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Name"}),e.jsx(be,{value:r.name||"",onChange:u=>a({...r,name:u.target.value}),placeholder:"e.g. Listing Consultation"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Description"}),e.jsx(Ls,{value:r.description||"",onChange:u=>a({...r,description:u.target.value}),placeholder:"Brief description for prospects",rows:2})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Duration (minutes)"}),e.jsx(be,{type:"number",min:15,max:180,step:15,value:r.duration_minutes||30,onChange:u=>a({...r,duration_minutes:parseInt(u.target.value)||30})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Color"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"color",value:r.color||"#3B82F6",onChange:u=>a({...r,color:u.target.value}),className:"h-10 w-10 rounded border cursor-pointer"}),e.jsx(be,{value:r.color||"#3B82F6",onChange:u=>a({...r,color:u.target.value}),className:"flex-1"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Max bookings per day"}),e.jsx(be,{type:"number",min:0,max:50,value:r.max_per_day??"",onChange:u=>a({...r,max_per_day:u.target.value===""?null:parseInt(u.target.value)||0}),placeholder:"Unlimited"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Leave blank for unlimited. Once this many are booked on a day, the day closes."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Icon"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:Object.entries(Ijt).map(([u,h])=>e.jsx("button",{onClick:()=>a({...r,icon:u}),className:`w-10 h-10 rounded-lg text-lg flex items-center justify-center border transition-colors ${r.icon===u?"border-primary bg-primary/10":"hover:bg-muted"}`,children:h},u))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Meeting Link Override (optional)"}),e.jsx(be,{value:r.meeting_link_override||"",onChange:u=>a({...r,meeting_link_override:u.target.value||null}),placeholder:"Use a different link for this type"})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Pre-Qualification Questions"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Ask qualifying questions before booking"})]}),e.jsx(On,{checked:r.qualification_enabled||!1,onCheckedChange:u=>a({...r,qualification_enabled:u})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Coaching sessions only"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Hidden from your public booking page — only your coaching agents can book it"})]}),e.jsx(On,{checked:r.is_coaching_only||!1,onCheckedChange:u=>a({...r,is_coaching_only:u})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(re,{children:"Active"}),e.jsx(On,{checked:r.is_active??!0,onCheckedChange:u=>a({...r,is_active:u})})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsx($,{onClick:d,children:"Save"})]})]})})]})}const dZn={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 uZn({bookings:s,onCancel:t}){const n=s.filter(i=>i.status==="confirmed"&&new Date(i.booking_date)>=new Date(new Date().toDateString())),r=s.filter(i=>i.status!=="confirmed"||new Date(i.booking_date){var o,c;return e.jsxs("div",{className:"flex items-start justify-between p-4 rounded-lg border hover:bg-muted/30 transition-colors",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(el,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"font-medium",children:i.guest_name}),e.jsx(qe,{className:`text-xs ${dZn[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(fd,{className:"h-3.5 w-3.5"}),Ys(new Date(i.booking_date+"T00:00:00"),"MMM d, yyyy")]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(sa,{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(pn,{className:"h-3 w-3"}),i.guest_email]}),i.guest_phone&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ka,{className:"h-3 w-3"}),i.guest_phone]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 mt-1",children:[i.booking_type&&e.jsx(qe,{variant:"outline",className:"text-xs",children:i.booking_type.name}),i.google_sync_status==="synced"&&e.jsxs(qe,{variant:"outline",className:"text-xs gap-1 text-emerald-700 border-emerald-300 dark:text-emerald-400",children:[e.jsx(fb,{className:"h-3 w-3"})," On Google Calendar"]}),i.google_sync_status==="failed"&&e.jsxs(qe,{variant:"outline",className:"text-xs gap-1 text-amber-700 border-amber-300 dark:text-amber-400",children:[e.jsx(zz,{className:"h-3 w-3"})," Not synced to Google"]})]}),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($,{variant:"ghost",size:"sm",onClick:()=>t(i.id),className:"text-destructive hover:text-destructive",children:[e.jsx(ju,{className:"h-4 w-4 mr-1"})," Cancel"]})]},i.id)};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs(we,{children:[e.jsxs(Vt,{children:[e.jsx(Yt,{children:"Upcoming Bookings"}),e.jsxs(vr,{children:[n.length," upcoming appointment",n.length!==1?"s":""]})]}),e.jsx(De,{children:n.length===0?e.jsx("p",{className:"text-center text-muted-foreground py-8",children:"No upcoming bookings"}):e.jsx("div",{className:"space-y-3",children:n.map(i=>a(i,!0))})})]}),r.length>0&&e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsx(Yt,{children:"Past & Cancelled"})}),e.jsx(De,{children:e.jsx("div",{className:"space-y-3",children:r.slice(0,20).map(i=>a(i))})})]})]})}function hZn(){const{settings:s,bookingTypes:t,availability:n,blockedDates:r,bookings:a,isLoading:i,initializeSettings:l,updateSettings:o,upsertBookingType:c,deleteBookingType:d,upsertAvailability:u,deleteAvailability:h,addBlockedDate:m,removeBlockedDate:p,cancelBooking:g}=NMt(),[x,y]=k.useState(""),[v,_]=k.useState(15);x||s!=null&&s.meeting_link;const j=s!=null&&s.slug?`https://booking.relevelup.com/${s.slug}`:null;return i?e.jsx(Xs,{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(Xs,{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(fd,{className:"h-6 w-6 text-primary"}),"LevelUp Scheduler"]}),e.jsx("p",{className:"text-muted-foreground",children:"Manage your booking types, availability, and appointments"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[j&&e.jsxs(e.Fragment,{children:[e.jsxs($,{variant:"outline",size:"sm",onClick:()=>{navigator.clipboard.writeText(j),ae.success("Booking link copied!")},children:[e.jsx(Da,{className:"h-4 w-4 mr-1"})," Copy Link"]}),e.jsx($,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("a",{href:j,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(Ir,{className:"h-4 w-4 mr-1"})," Preview"]})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(re,{htmlFor:"scheduler-active",className:"text-sm",children:"Active"}),e.jsx(On,{id:"scheduler-active",checked:s.is_active,onCheckedChange:C=>o.mutate({is_active:C})})]})]})]}),e.jsxs(ya,{defaultValue:"types",className:"space-y-4",children:[e.jsxs(va,{children:[e.jsx(is,{value:"types",children:"Booking Types"}),e.jsx(is,{value:"availability",children:"Availability"}),e.jsx(is,{value:"settings",children:"Settings"}),e.jsxs(is,{value:"bookings",children:["Bookings",a.filter(C=>C.status==="confirmed").length>0&&e.jsx(qe,{variant:"secondary",className:"ml-1.5 text-xs",children:a.filter(C=>C.status==="confirmed").length})]})]}),e.jsx(cs,{value:"types",children:e.jsx(cZn,{types:t,onSave:C=>c.mutate(C),onDelete:C=>d.mutate(C)})}),e.jsx(cs,{value:"availability",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(kMt,{slots:n,onSave:C=>u.mutate(C),onDelete:C=>h.mutate(C)}),e.jsx(SMt,{blockedDates:r,onAdd:C=>m.mutate(C),onRemove:C=>p.mutate(C)})]})}),e.jsxs(cs,{value:"settings",className:"space-y-6",children:[e.jsx(CMt,{scope:"agent"}),e.jsxs(we,{children:[e.jsxs(Vt,{children:[e.jsxs(Yt,{className:"flex items-center gap-2",children:[e.jsx(eM,{className:"h-5 w-5"}),"General Settings"]}),e.jsx(vr,{children:"Configure your booking page defaults"})]}),e.jsxs(De,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Booking Page URL"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(be,{value:s.slug,readOnly:!0,className:"bg-muted"}),e.jsx($,{variant:"outline",size:"sm",onClick:()=>{j&&(navigator.clipboard.writeText(j),ae.success("Copied!"))},children:e.jsx(Da,{className:"h-4 w-4"})})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:j})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(re,{htmlFor:"meeting-link",children:[e.jsx(pd,{className:"h-4 w-4 inline mr-1"}),"Default Meeting Link"]}),e.jsx(be,{id:"meeting-link",placeholder:"https://zoom.us/j/your-personal-link",defaultValue:s.meeting_link||"",onBlur:C=>o.mutate({meeting_link:C.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(re,{children:"Buffer Between Meetings"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(be,{type:"number",min:0,max:60,defaultValue:s.buffer_minutes,onBlur:C=>o.mutate({buffer_minutes:parseInt(C.target.value)||15})}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"min"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Minimum Notice"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(be,{type:"number",min:0,max:72,defaultValue:s.min_notice_hours,onBlur:C=>o.mutate({min_notice_hours:parseInt(C.target.value)||2})}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"hours"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(re,{children:"Max Advance Booking"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(be,{type:"number",min:1,max:90,defaultValue:s.max_advance_days,onBlur:C=>o.mutate({max_advance_days:parseInt(C.target.value)||30})}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"days"})]})]})]}),e.jsxs("div",{className:"space-y-3 pt-2 border-t",children:[e.jsx(re,{className:"text-sm font-semibold",children:"Guest Reminders"}),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:"Email reminders"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Sends 24 hours and 1 hour before the meeting, with reschedule and cancel links."})]}),e.jsx(On,{checked:s.reminders_enabled!==!1,onCheckedChange:C=>o.mutate({reminders_enabled:C})})]}),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:"Text message reminders"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Texts guests who left a phone number. Standard opt-out language is included."})]}),e.jsx(On,{checked:!!s.sms_reminders_enabled,onCheckedChange:C=>o.mutate({sms_reminders_enabled:C})})]})]}),e.jsxs("div",{className:"space-y-2 pt-2 border-t",children:[e.jsx(re,{className:"text-sm font-semibold",children:"Embed on your website"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Paste this snippet anywhere on your site to show your booking page inline."}),e.jsx("pre",{className:"text-[11px] bg-muted rounded-lg p-3 overflow-x-auto whitespace-pre-wrap",children:``}),e.jsxs($,{variant:"outline",size:"sm",onClick:()=>{navigator.clipboard.writeText(``),ae.success("Embed code copied")},children:[e.jsx(Da,{className:"h-4 w-4 mr-1.5"})," Copy embed code"]})]})]})]})]}),e.jsx(cs,{value:"bookings",children:e.jsx(uZn,{bookings:a,onCancel:C=>g.mutate({id:C})})})]})]})}):e.jsx(Xs,{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(fd,{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(we,{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(C=>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:C.icon}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:C.title}),e.jsx("p",{className:"text-xs text-muted-foreground",children:C.desc})]})]},C.title))}),e.jsx(Pc,{}),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($,{onClick:()=>l.mutate(),disabled:l.isPending,className:"w-full",size:"lg",children:[e.jsx(kn,{className:"h-4 w-4 mr-2"}),l.isPending?"Setting up...":"Activate Scheduler"]})]})})]})})}function Oie(s){const[t,n]=String(s).split(":").map(Number),r=t>=12?"PM":"AM";return`${t%12||12}:${String(n).padStart(2,"0")} ${r}`}function mZn(s){const[t,n,r]=s.split(/[-/T]/).map(Number);return Ys(new Date(t,n-1,r),"EEEE, MMMM d, yyyy")}function fZn(){var me;const{token:s}=oo(),[t]=Jc(),[n,r]=k.useState(null),[a,i]=k.useState(!0),[l,o]=k.useState(null),[c,d]=k.useState("details"),[u,h]=k.useState(!1),[m,p]=k.useState(""),[g,x]=k.useState(null),[y,v]=k.useState(new Date),[_,j]=k.useState({}),[C,A]=k.useState(!1),[M,I]=k.useState(null),[P,R]=k.useState(null),O=async Q=>{var fe,_e;const{data:te,error:le}=await V.functions.invoke("agent-booking",{body:Q});if(le){let ve=le.message;try{const he=await((_e=(fe=le.context)==null?void 0:fe.json)==null?void 0:_e.call(fe));he!=null&&he.error&&(ve=he.error)}catch{}throw new Error(ve)}if(te!=null&&te.error)throw new Error(te.error);return te};k.useEffect(()=>{s&&(async()=>{try{const Q=await O({action:"manage_get",manage_token:s});r(Q),t.get("cancel")==="1"&&d("cancel")}catch(Q){o(Q.message)}finally{i(!1)}})()},[s]),k.useEffect(()=>{if(c!=="reschedule"||!(n!=null&&n.booking_type))return;let Q=!1;return(async()=>{A(!0);try{const te=new Date(y.getFullYear(),y.getMonth(),1),le=np(new Date),fe=N_(le,te)?le:te,_e=new Date(y.getFullYear(),y.getMonth()+1,0),ve=Math.max(1,Math.round((_e.getTime()-fe.getTime())/864e5)+1),he=await O({action:"availability",slug:n.slug,booking_type_id:n.booking_type.id,start:Ys(fe,"yyyy-MM-dd"),days:Math.min(ve,90),ignore_booking_id:n.booking.id});Q||j((he==null?void 0:he.availability)||{})}catch(te){Q||ae.error(te.message)}finally{Q||A(!1)}})(),()=>{Q=!0}},[c,y,(me=n==null?void 0:n.booking_type)==null?void 0:me.id]);const B=k.useMemo(()=>{const Q=y.getFullYear(),te=y.getMonth(),le=new Date(Q,te,1),fe=new Date(Q,te+1,0),_e=[];for(let ve=0;ve{h(!0);try{await O({action:"manage_cancel",manage_token:s,reason:m}),x("cancelled"),d("done")}catch(Q){ae.error(Q.message)}finally{h(!1)}},H=async()=>{if(!(!M||!P)){h(!0);try{await O({action:"manage_reschedule",manage_token:s,date:Ys(M,"yyyy-MM-dd"),time:P}),x("rescheduled"),d("done")}catch(Q){ae.error(Q.message)}finally{h(!1)}}};if(a)return 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(Jt,{className:"h-8 w-8 animate-spin text-[#406E71]"}),e.jsx("p",{className:"text-sm text-slate-500",children:"Loading your booking…"})]})});if(l||!n)return e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-[#f0f4f8] via-white to-[#e8f0f8] flex items-center justify-center px-4",children:e.jsxs("div",{className:"bg-white rounded-2xl shadow-lg p-8 max-w-sm text-center space-y-3",children:[e.jsx(ju,{className:"h-10 w-10 text-slate-300 mx-auto"}),e.jsx("h1",{className:"text-lg font-bold text-slate-800",children:"Booking not found"}),e.jsx("p",{className:"text-sm text-slate-500",children:l||"This management link is no longer valid."})]})});const{booking:Y,booking_type:se,agent:ee}=n,oe=Y.status==="cancelled";return e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-[#f0f4f8] via-white to-[#e8f0f8] py-10 px-4",children:e.jsxs("div",{className:"max-w-lg mx-auto",children:[e.jsxs("div",{className:"bg-white rounded-2xl shadow-xl overflow-hidden",children:[e.jsxs("div",{className:"bg-gradient-to-br from-[#406E71] to-[#2a4c64] px-8 py-7 text-center",children:[e.jsx("h1",{className:"text-xl font-bold text-white",children:c==="done"?g==="cancelled"?"Booking cancelled":"Booking rescheduled":"Manage your booking"}),e.jsxs("p",{className:"text-white/80 text-sm mt-1",children:[(se==null?void 0:se.name)||"Meeting",ee!=null&&ee.name?` with ${ee.name}`:""]})]}),e.jsxs("div",{className:"p-7 space-y-6",children:[c!=="reschedule"&&e.jsxs("div",{className:"rounded-xl border border-slate-100 bg-slate-50 p-4 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-slate-800 font-semibold",children:[e.jsx(fd,{className:"h-4 w-4 text-[#406E71]"}),mZn(Y.booking_date)]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm text-slate-600",children:[e.jsx(sa,{className:"h-4 w-4 text-[#406E71]"}),Oie(String(Y.start_time).slice(0,5))," –"," ",Oie(String(Y.end_time).slice(0,5)),e.jsxs("span",{className:"text-xs text-slate-400",children:["(",n.timezone.replace(/_/g," "),")"]})]}),oe&&e.jsx("p",{className:"text-xs font-semibold text-red-600 pt-1",children:"This booking is cancelled."})]}),c==="details"&&!oe&&e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[n.allow_reschedule&&e.jsx($,{className:"h-12 rounded-xl bg-[#406E71] hover:bg-[#365c5e] text-white font-semibold",onClick:()=>d("reschedule"),children:"Reschedule"}),n.allow_cancel&&e.jsx($,{variant:"outline",className:"h-12 rounded-xl border-red-200 text-red-600 hover:bg-red-50 font-semibold",onClick:()=>d("cancel"),children:"Cancel booking"})]}),c==="cancel"&&!oe&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("p",{className:"text-sm text-slate-600",children:["Let ",(ee==null?void 0:ee.name)||"your host"," know why you can't make it (optional)."]}),e.jsx(Ls,{value:m,onChange:Q=>p(Q.target.value),placeholder:"Something came up…",className:"rounded-xl",rows:3}),e.jsxs("div",{className:"flex gap-3",children:[e.jsx($,{variant:"ghost",className:"flex-1 h-11 rounded-xl",onClick:()=>d("details"),disabled:u,children:"Keep booking"}),e.jsx($,{className:"flex-1 h-11 rounded-xl bg-red-600 hover:bg-red-700 text-white font-semibold",onClick:G,disabled:u,children:u?e.jsx(Jt,{className:"h-4 w-4 animate-spin"}):"Cancel booking"})]})]}),c==="reschedule"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("button",{onClick:()=>d("details"),className:"flex items-center gap-1.5 text-xs font-medium text-slate-500 hover:text-slate-800",children:[e.jsx(Ia,{className:"h-3.5 w-3.5"})," Back"]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("button",{className:"p-2 rounded-lg hover:bg-slate-100",onClick:()=>v(new Date(y.getFullYear(),y.getMonth()-1,1)),children:e.jsx(Ld,{className:"h-4 w-4 text-slate-500"})}),e.jsx("span",{className:"text-sm font-semibold text-slate-800",children:Ys(y,"MMMM yyyy")}),e.jsx("button",{className:"p-2 rounded-lg hover:bg-slate-100",onClick:()=>v(new Date(y.getFullYear(),y.getMonth()+1,1)),children:e.jsx(fi,{className:"h-4 w-4 text-slate-500"})})]}),e.jsxs("div",{className:"grid grid-cols-7 gap-1 text-center",children:[["S","M","T","W","T","F","S"].map((Q,te)=>e.jsx("div",{className:"text-[11px] font-semibold text-slate-400 py-1",children:Q},te)),B.map((Q,te)=>{if(!Q)return e.jsx("div",{},`p${te}`);const le=Ys(Q,"yyyy-MM-dd"),fe=(_[le]||[]).length>0&&!Xw(Q,np(new Date)),_e=M&&ah(Q,M);return e.jsx("button",{disabled:!fe,onClick:()=>{I(Q),R(null)},className:`aspect-square rounded-lg text-sm font-medium transition-colors ${_e?"bg-[#406E71] text-white":fe?"bg-[#406E71]/10 text-[#406E71] hover:bg-[#406E71]/20":"text-slate-300"}`,children:Q.getDate()},le)})]}),C&&e.jsxs("p",{className:"text-center text-xs text-slate-400 flex items-center justify-center gap-2",children:[e.jsx(Jt,{className:"h-3.5 w-3.5 animate-spin"})," Checking availability…"]}),M&&e.jsx("div",{className:"grid grid-cols-3 sm:grid-cols-4 gap-2 max-h-48 overflow-y-auto",children:U.length===0?e.jsx("p",{className:"col-span-full text-center text-sm text-slate-400 py-4",children:"No open times on this day"}):U.map(Q=>e.jsx("button",{onClick:()=>R(Q),className:`px-3 py-2.5 rounded-xl text-sm font-medium ${P===Q?"bg-[#406E71] text-white":"bg-slate-50 text-slate-700 hover:bg-[#406E71]/10"}`,children:Oie(Q)},Q))}),e.jsx($,{className:"w-full h-12 rounded-xl bg-[#406E71] hover:bg-[#365c5e] text-white font-semibold",disabled:!M||!P||u,onClick:H,children:u?e.jsx(Jt,{className:"h-4 w-4 animate-spin"}):"Confirm new time"}),e.jsxs("p",{className:"text-center text-[11px] text-slate-400",children:["Times shown in ",n.timezone.replace(/_/g," ")]})]}),c==="done"&&e.jsxs("div",{className:"text-center space-y-4 py-4",children:[g==="cancelled"?e.jsx(ju,{className:"h-12 w-12 text-red-500 mx-auto"}):e.jsx(Gr,{className:"h-12 w-12 text-emerald-500 mx-auto"}),e.jsx("p",{className:"text-sm text-slate-600",children:g==="cancelled"?`Your meeting has been cancelled and ${(ee==null?void 0:ee.name)||"your host"} has been notified.`:`Your meeting is now on ${M?Ys(M,"EEEE, MMMM d"):""} at ${P?Oie(P):""}. A confirmation is on its way.`})]})]})]}),e.jsx("p",{className:"text-center text-[11px] text-slate-400 mt-6",children:"Powered by LevelUp Scheduler"})]})})}const Ljt=[{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 pZn(){const{user:s}=ks(),t=ai(),{toast:n}=Fi(),r=Jn(),a=ls(),[i,l]=k.useState(!1),[o,c]=k.useState(null),[d,u]=k.useState(null),[h,m]=k.useState({title:"",description:"",page_type:"lead_capture"}),{data:p=[],isLoading:g}=pt({queryKey:["landing-pages",t],queryFn:async()=>{const{data:_,error:j}=await V.from("landing_pages").select("*").eq("user_id",t).is("deleted_at",null).order("created_at",{ascending:!1});if(j)throw j;return _},enabled:!!t}),x=Nt({mutationFn:async()=>{const _=h.title.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/(^-|-$)/g,"")+"-"+Date.now().toString(36),{data:j}=await V.from("profiles").select("name, phone, avatar_url, email").eq("id",t).single(),C=h.page_type==="just_listed"||h.page_type==="just_sold",{data:A,error:M}=await V.from("landing_pages").insert({user_id:t,title:h.title,description:h.description||null,page_type:h.page_type,slug:_,hero_headline:C?h.page_type==="just_listed"?"🏡 Just Listed":"🎉 Just Sold":h.page_type==="lead_magnet"?"📥 Free Download":h.title,agent_name:(j==null?void 0:j.name)||null,agent_phone:(j==null?void 0:j.phone)||null,agent_email:(j==null?void 0:j.email)||s.email||null,agent_photo_url:(j==null?void 0:j.avatar_url)||null,property_status:C?h.page_type.replace("just_",""):null}).select().single();if(M)throw M;const I=gZn(h.page_type);if(I.length>0){const{error:P}=await V.from("landing_page_fields").insert(I.map((R,O)=>({...R,page_id:A.id,sort_order:O})));if(P)throw P}return A},onSuccess:_=>{a.invalidateQueries({queryKey:["landing-pages"]}),l(!1),m({title:"",description:"",page_type:"lead_capture"}),n({title:"Landing page created!"}),r(`/mission-control/landing-pages/${_.id}`)},onError:_=>n({title:"Error",description:_.message,variant:"destructive"})}),y=Nt({mutationFn:async _=>{const{error:j}=await V.from("landing_pages").update({deleted_at:new Date().toISOString(),is_published:!1}).eq("id",_);if(j)throw j},onSuccess:()=>{a.invalidateQueries({queryKey:["landing-pages"]}),c(null),n({title:"Landing page deleted"})}}),v=_=>`https://pages.relevelup.com/${_}`;return e.jsxs(Xs,{title:"Landing Pages",children:[e.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Landing Pages"}),e.jsx("p",{className:"text-muted-foreground text-sm mt-1",children:"Create branded lead capture pages for events, consultations, and more"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs($,{variant:"outline",onClick:()=>r("/mission-control/landing-pages/defaults"),children:[e.jsx(Yc,{className:"h-4 w-4 mr-2"})," Defaults"]}),e.jsxs($,{onClick:()=>l(!0),children:[e.jsx(nn,{className:"h-4 w-4 mr-2"})," New Page"]})]})]}),g?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):p.length===0?e.jsx(we,{children:e.jsxs(De,{className:"flex flex-col items-center justify-center py-16",children:[e.jsx(ea,{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($,{onClick:()=>l(!0),children:[e.jsx(nn,{className:"h-4 w-4 mr-2"})," Create Landing Page"]})]})}):e.jsx("div",{className:"grid gap-4",children:p.map(_=>{var j;return e.jsx(we,{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:()=>r(`/mission-control/landing-pages/${_.id}`),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"font-semibold truncate",children:_.title}),e.jsx(qe,{variant:_.is_published?"default":"secondary",className:"text-[10px]",children:_.is_published?"Published":"Draft"}),e.jsx(qe,{variant:"outline",className:"text-[10px]",children:((j=Ljt.find(C=>C.id===_.page_type))==null?void 0:j.label)||_.page_type})]}),_.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1 truncate",children:_.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(ba,{className:"h-3 w-3"})," ",_.view_count," views"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ea,{className:"h-3 w-3"})," ",_.submission_count," submissions"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 ml-4",children:[_.is_published&&e.jsxs(e.Fragment,{children:[e.jsx($,{size:"sm",variant:"outline",onClick:()=>u(v(_.slug)),children:e.jsx(Bx,{className:"h-3.5 w-3.5"})}),e.jsx($,{size:"sm",variant:"outline",onClick:()=>{navigator.clipboard.writeText(v(_.slug)),n({title:"Link copied!"})},children:e.jsx(Da,{className:"h-3.5 w-3.5"})}),e.jsx($,{size:"sm",variant:"outline",asChild:!0,children:e.jsx("a",{href:v(_.slug),target:"_blank",rel:"noopener noreferrer",children:e.jsx(Ir,{className:"h-3.5 w-3.5"})})})]}),e.jsxs(Au,{children:[e.jsx(Eu,{asChild:!0,children:e.jsx($,{size:"sm",variant:"ghost",children:e.jsx(Z0,{className:"h-4 w-4"})})}),e.jsxs(gu,{align:"end",children:[e.jsxs(Pa,{onClick:()=>r(`/mission-control/landing-pages/${_.id}`),children:[e.jsx(ui,{className:"h-3.5 w-3.5 mr-2"})," Edit"]}),e.jsxs(Pa,{onClick:()=>c(_.id),className:"text-destructive",children:[e.jsx(Un,{className:"h-3.5 w-3.5 mr-2"})," Delete"]})]})]})]})]})})},_.id)})})]}),e.jsx(zs,{open:i,onOpenChange:l,children:e.jsxs(Rs,{children:[e.jsx(Vs,{children:e.jsx($s,{children:"Create Landing Page"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Page Title"}),e.jsx(be,{value:h.title,onChange:_=>m(j=>({...j,title:_.target.value})),placeholder:"e.g. Veterans Home & Land Expo"})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Description (optional)"}),e.jsx(Ls,{value:h.description,onChange:_=>m(j=>({...j,description:_.target.value})),placeholder:"Brief internal description...",rows:2})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Page Template"}),e.jsxs(bs,{value:h.page_type,onValueChange:_=>m(j=>({...j,page_type:_})),children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsx(vs,{children:Ljt.map(_=>e.jsx(We,{value:_.id,children:e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:_.label}),e.jsx("div",{className:"text-xs text-muted-foreground",children:_.description})]})},_.id))})]})]})]}),e.jsxs(kr,{children:[e.jsx($,{variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsx($,{onClick:()=>x.mutate(),disabled:!h.title.trim()||x.isPending,children:x.isPending?"Creating...":"Create Page"})]})]})}),e.jsx(oc,{open:!!o,onOpenChange:()=>c(null),children:e.jsxs(Ql,{children:[e.jsxs(Jl,{children:[e.jsx(tc,{children:"Delete Landing Page?"}),e.jsx(sc,{children:"This will permanently delete this page and all its submissions."})]}),e.jsxs(ec,{children:[e.jsx(nc,{children:"Cancel"}),e.jsx(Vl,{onClick:()=>o&&y.mutate(o),children:"Delete"})]})]})}),e.jsx(zs,{open:!!d,onOpenChange:()=>u(null),children:e.jsxs(Rs,{className:"max-w-sm",children:[e.jsx(Vs,{children:e.jsx($s,{children:"QR Code"})}),e.jsxs("div",{className:"flex flex-col items-center gap-4 py-4",children:[d&&e.jsx(jk,{value:d,size:240}),e.jsx("p",{className:"text-xs text-muted-foreground text-center break-all",children:d}),e.jsxs($,{variant:"outline",size:"sm",onClick:()=>{d&&(navigator.clipboard.writeText(d),n({title:"URL copied!"}))},children:[e.jsx(Da,{className:"h-3.5 w-3.5 mr-1"})," Copy URL"]})]})]})})]})}function gZn(s){const t=[{field_type:"text",label:"Full Name",placeholder:"Your name",is_required:!0},{field_type:"email",label:"Email",placeholder:"your@email.com",is_required:!0},{field_type:"phone",label:"Phone",placeholder:"(555) 123-4567",is_required:!1}];switch(s){case"event_registration":return[...t,{field_type:"select",label:"How did you hear about this event?",options:JSON.stringify(["Social Media","Friend/Referral","Email","Flyer/Sign","Other"]),is_required:!1},{field_type:"textarea",label:"Any questions or special needs?",placeholder:"Let us know...",is_required:!1}];case"buyer_consultation":return[...t,{field_type:"select",label:"Interested in",options:JSON.stringify(["Buying","Selling","Both"]),is_required:!0},{field_type:"select",label:"Timeline",options:JSON.stringify(["0-3 months","3-6 months","6-12 months","Just exploring"]),is_required:!1},{field_type:"toggle",label:"Already working with a Realtor?",is_required:!1},{field_type:"toggle",label:"Do you have property to sell?",is_required:!1},{field_type:"textarea",label:"Anything else we should know?",placeholder:"Tell us about your situation...",is_required:!1}];case"home_valuation":return[...t,{field_type:"text",label:"Property Address",placeholder:"123 Main St, City, State",is_required:!0},{field_type:"select",label:"Reason for Valuation",options:JSON.stringify(["Thinking of selling","Refinancing","Curiosity","Estate planning","Other"]),is_required:!1},{field_type:"select",label:"Timeline to Sell",options:JSON.stringify(["ASAP","1-3 months","3-6 months","6+ months","Not sure"]),is_required:!1}];case"lead_magnet":return[...t,{field_type:"select",label:"Are you currently working with a Realtor?",options:JSON.stringify(["Yes","No","Not yet"]),is_required:!1}];case"just_listed":return[...t,{field_type:"select",label:"I am interested in",options:JSON.stringify(["Scheduling a showing","Getting more details","Similar properties","Selling my home"]),is_required:!0},{field_type:"textarea",label:"Message",placeholder:"Tell me more about this property...",is_required:!1}];case"just_sold":return[...t,{field_type:"select",label:"I am looking to",options:JSON.stringify(["Sell my home","Buy a home","Both","Just curious"]),is_required:!0},{field_type:"text",label:"My Property Address",placeholder:"123 Main St, City, State",is_required:!1}];default:return[...t,{field_type:"textarea",label:"Message",placeholder:"How can we help you?",is_required:!1}]}}function xZn(s,t){return t?`${(s/t*100).toFixed(1)}%`:"0%"}function yZn({pageId:s}){const{data:t=[],isLoading:n}=pt({queryKey:["landing-page-events",s],queryFn:async()=>{const l=new Date(Date.now()-2592e6).toISOString(),{data:o,error:c}=await V.from("landing_page_events").select("event_type, session_id, utm_source, utm_medium, utm_campaign, referrer, device, created_at").eq("page_id",s).gte("created_at",l).order("created_at",{ascending:!1}).limit(1e3);if(c)throw c;return o||[]}}),{data:r=[]}=pt({queryKey:["landing-page-submissions-analytics",s],queryFn:async()=>{const{data:l}=await V.from("landing_page_submissions").select("id, created_at").eq("page_id",s);return l||[]}}),a=k.useMemo(()=>{const l=t.filter(g=>g.event_type==="view"),o=t.filter(g=>g.event_type==="click"),c=new Set(l.map(g=>g.session_id).filter(Boolean)),d=new Map,u=new Map,h=new Map;for(const g of l){const x=g.utm_source||"Direct / unknown";if(d.set(x,(d.get(x)||0)+1),g.referrer)try{const v=new URL(g.referrer).hostname.replace(/^www\./,"");u.set(v,(u.get(v)||0)+1)}catch{}const y=g.device||"unknown";h.set(y,(h.get(y)||0)+1)}const m=[];for(let g=13;g>=0;g--){const x=new Date;x.setHours(0,0,0,0),x.setDate(x.getDate()-g);const y=new Date(x);y.setDate(x.getDate()+1);const v=x.toLocaleDateString("en-US",{month:"numeric",day:"numeric"}),_=l.filter(C=>{const A=new Date(C.created_at);return A>=x&&A{const A=new Date(C.created_at);return A>=x&&Ag.views));return{views:l.length,sessions:c.size,clicks:o.length,submissions:r.length,conversion:xZn(r.length,c.size||l.length),sourceCounts:[...d.entries()].sort((g,x)=>x[1]-g[1]).slice(0,6),referrerCounts:[...u.entries()].sort((g,x)=>x[1]-g[1]).slice(0,6),deviceCounts:[...h.entries()].sort((g,x)=>x[1]-g[1]),days:m,maxBar:p}},[t,r]);if(n)return e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:Array.from({length:4}).map((l,o)=>e.jsx(fn,{className:"h-24"},o))});const i=[{label:"Views (30d)",value:a.views,icon:ba},{label:"Unique visitors",value:a.sessions,icon:Xn},{label:"Submissions",value:a.submissions,icon:Wr},{label:"Conversion rate",value:a.conversion,icon:mc}];return e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:i.map(l=>e.jsx(we,{children:e.jsxs(De,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx(l.icon,{className:"h-3.5 w-3.5"})," ",l.label]}),e.jsx("div",{className:"text-2xl font-semibold mt-1",children:l.value})]})},l.label))}),e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsx(Yt,{className:"text-base",children:"Last 14 days"})}),e.jsxs(De,{children:[a.views===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No traffic yet. Share your page link or QR code to start collecting visits."}):e.jsx("div",{className:"flex items-end gap-1.5 h-32",children:a.days.map((l,o)=>e.jsxs("div",{className:"flex-1 flex flex-col items-center gap-1",children:[e.jsxs("div",{className:"w-full flex flex-col justify-end h-24",children:[e.jsx("div",{title:`${l.views} views · ${l.submits} submits`,className:"w-full rounded-t bg-primary/70",style:{height:`${l.views/a.maxBar*100}%`,minHeight:l.views?2:0}}),l.submits>0&&e.jsx("div",{className:"w-full bg-emerald-500",style:{height:`${Math.max(2,l.submits/a.maxBar*100)}%`}})]}),e.jsx("span",{className:"text-[10px] text-muted-foreground",children:l.label})]},o))}),e.jsxs("div",{className:"flex items-center gap-4 mt-3 text-xs text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"w-2 h-2 rounded-sm bg-primary/70"})," Views"]}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"w-2 h-2 rounded-sm bg-emerald-500"})," Submissions"]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-3",children:[e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsxs(Yt,{className:"text-base flex items-center gap-2",children:[e.jsx(rh,{className:"h-4 w-4"})," Top sources"]})}),e.jsx(De,{children:a.sourceCounts.length===0?e.jsx("p",{className:"text-xs text-muted-foreground",children:"No UTM data yet."}):e.jsx("ul",{className:"space-y-1.5 text-sm",children:a.sourceCounts.map(([l,o])=>e.jsxs("li",{className:"flex justify-between",children:[e.jsx("span",{className:"truncate",children:l}),e.jsx("span",{className:"text-muted-foreground",children:o})]},l))})})]}),e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsx(Yt,{className:"text-base",children:"Top referrers"})}),e.jsx(De,{children:a.referrerCounts.length===0?e.jsx("p",{className:"text-xs text-muted-foreground",children:"No external referrers tracked."}):e.jsx("ul",{className:"space-y-1.5 text-sm",children:a.referrerCounts.map(([l,o])=>e.jsxs("li",{className:"flex justify-between",children:[e.jsx("span",{className:"truncate",children:l}),e.jsx("span",{className:"text-muted-foreground",children:o})]},l))})})]}),e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsx(Yt,{className:"text-base",children:"Devices"})}),e.jsx(De,{children:a.deviceCounts.length===0?e.jsx("p",{className:"text-xs text-muted-foreground",children:"No device data."}):e.jsx("ul",{className:"space-y-1.5 text-sm",children:a.deviceCounts.map(([l,o])=>e.jsxs("li",{className:"flex justify-between",children:[e.jsx("span",{className:"capitalize",children:l}),e.jsx("span",{className:"text-muted-foreground",children:o})]},l))})})]})]})]})}const vZn=[{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 bZn=0;const Rjt=()=>`f_${Date.now()}_${++bZn}`;function _Zn({field:s,index:t,updateField:n,removeField:r}){const{attributes:a,listeners:i,setNodeRef:l,transform:o,transition:c,isDragging:d}=nEe({id:s.clientId}),u={transform:PM.Transform.toString(o),transition:c,zIndex:d?50:void 0,opacity:d?.85:1};return e.jsx(we,{ref:l,style:u,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(Bp,{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(re,{className:"text-xs",children:"Field Type"}),e.jsxs(bs,{value:s.field_type,onValueChange:h=>n(t,{field_type:h}),children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsx(vs,{children:vZn.map(h=>e.jsx(We,{value:h.value,children:h.label},h.value))})]})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Label"}),e.jsx(be,{value:s.label,onChange:h=>n(t,{label:h.target.value}),placeholder:"e.g. Full Name"})]}),e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Placeholder"}),e.jsx(be,{value:s.placeholder||"",onChange:h=>n(t,{placeholder:h.target.value}),placeholder:"Optional hint text"})]})]}),(s.field_type==="select"||s.field_type==="multiselect")&&e.jsxs("div",{children:[e.jsx(re,{className:"text-xs",children:"Options (comma-separated)"}),e.jsx(be,{value:s.options?(typeof s.options=="string"?JSON.parse(s.options):s.options).join(", "):"",onChange:h=>n(t,{options:JSON.stringify(h.target.value.split(",").map(m=>m.trim()).filter(Boolean))}),placeholder:"Option 1, Option 2, Option 3"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(On,{checked:s.is_required,onCheckedChange:h=>n(t,{is_required:h})}),e.jsx(re,{className:"text-xs",children:"Required"})]})]}),e.jsx($,{variant:"ghost",size:"sm",onClick:()=>r(t),children:e.jsx(Un,{className:"h-3.5 w-3.5 text-destructive"})})]})})})}function wZn(){const{pageId:s}=oo(),t=Jn(),{user:n}=ks(),r=ai(),{toast:a}=Fi(),i=ls(),[l,o]=k.useState(null),[c,d]=k.useState(!1),{data:u,isLoading:h}=pt({queryKey:["landing-page",s],queryFn:async()=>{const{data:Q,error:te}=await V.from("landing_pages").select("*").eq("id",s).single();if(te)throw te;return Q},enabled:!!s}),{data:m=[],isLoading:p}=pt({queryKey:["landing-page-fields",s],queryFn:async()=>{const{data:Q,error:te}=await V.from("landing_page_fields").select("*").eq("page_id",s).order("sort_order");if(te)throw te;return Q},enabled:!!s}),{data:g=[]}=pt({queryKey:["landing-page-submissions",s],queryFn:async()=>{const{data:Q,error:te}=await V.from("landing_page_submissions").select("*").eq("page_id",s).order("created_at",{ascending:!1});if(te)throw te;return Q},enabled:!!s}),{data:x=[]}=pt({queryKey:["my-listings-for-pages",r],queryFn:async()=>{const{data:Q,error:te}=await V.from("listings").select("id, property_address, city, state, price, bedrooms, bathrooms, square_footage, description, status").eq("agent_id",r).order("created_at",{ascending:!1});if(te)throw te;return Q},enabled:!!n&&((u==null?void 0:u.page_type)==="just_listed"||(u==null?void 0:u.page_type)==="just_sold")}),{data:y=[]}=pt({queryKey:["drips-for-landing",r],queryFn:async()=>{const{data:Q}=await V.from("drip_campaigns").select("id, name").eq("owner_user_id",r).eq("is_active",!0).order("name");return Q||[]},enabled:!!r}),{data:v}=pt({queryKey:["agent-landing-defaults",r],queryFn:async()=>{const{data:Q}=await V.from("agent_landing_page_defaults").select("*").eq("user_id",r).maybeSingle();return Q},enabled:!!r}),[_,j]=k.useState({title:"",hero_headline:"",hero_subtext:"",hero_image_url:null,logo_url:null,primary_color:"#406E71",accent_color:"#2a4c64",agent_name:"",agent_phone:"",agent_email:"",agent_photo_url:null,success_message:"Thank you! We'll be in touch soon.",is_published:!1,description:"",lead_magnet_file_url:null,lead_magnet_file_name:null,lead_magnet_external_url:null,listing_id:null,property_address:"",property_price:"",property_beds:"",property_baths:"",property_sqft:"",property_description:"",property_photos:[],property_status:"just_listed",theme_style:"premium",eyebrow:"",headline_accent:"",heading_font:"playfair",trust_pills:["No obligation","100% free","60 seconds or less"],settings_redirect_url:"",settings_auto_responder_subject:"",settings_auto_responder_body:"",settings_drip_campaign_id:null,settings_disable_auto_responder:!1,settings_disable_drip:!1,settings_event_starts_at:"",settings_event_location_name:"",settings_event_address:""}),[C,A]=k.useState([]);k.useEffect(()=>{var Q,te,le,fe,_e,ve,he,Se,Te;u&&j({title:u.title,hero_headline:u.hero_headline,hero_subtext:u.hero_subtext||"",hero_image_url:u.hero_image_url,logo_url:u.logo_url,primary_color:u.primary_color,accent_color:u.accent_color,agent_name:u.agent_name||"",agent_phone:u.agent_phone||"",agent_email:u.agent_email||"",agent_photo_url:u.agent_photo_url,success_message:u.success_message||"Thank you! We'll be in touch soon.",is_published:u.is_published,description:u.description||"",lead_magnet_file_url:u.lead_magnet_file_url||null,lead_magnet_file_name:u.lead_magnet_file_name||null,lead_magnet_external_url:u.lead_magnet_external_url||null,listing_id:u.listing_id||null,property_address:u.property_address||"",property_price:u.property_price||"",property_beds:u.property_beds||"",property_baths:u.property_baths||"",property_sqft:u.property_sqft||"",property_description:u.property_description||"",property_photos:Array.isArray(u.property_photos)?u.property_photos:[],property_status:u.property_status||"just_listed",theme_style:u.theme_style||"premium",eyebrow:u.eyebrow||"",headline_accent:u.headline_accent||"",heading_font:u.heading_font||"playfair",trust_pills:Array.isArray(u.trust_pills)?u.trust_pills:["No obligation","100% free","60 seconds or less"],settings_redirect_url:((Q=u.settings)==null?void 0:Q.redirect_url)||"",settings_auto_responder_subject:((te=u.settings)==null?void 0:te.auto_responder_subject)||"",settings_auto_responder_body:((le=u.settings)==null?void 0:le.auto_responder_body)||"",settings_drip_campaign_id:((fe=u.settings)==null?void 0:fe.drip_campaign_id)||null,settings_disable_auto_responder:!!((_e=u.settings)!=null&&_e.disable_auto_responder),settings_disable_drip:!!((ve=u.settings)!=null&&ve.disable_drip),settings_event_starts_at:((he=u.settings)==null?void 0:he.event_starts_at)||"",settings_event_location_name:((Se=u.settings)==null?void 0:Se.event_location_name)||"",settings_event_address:((Te=u.settings)==null?void 0:Te.event_address)||""})},[u]),k.useEffect(()=>{m.length>0&&A(m.map(Q=>({id:Q.id,clientId:Q.id||Rjt(),field_type:Q.field_type,label:Q.label,placeholder:Q.placeholder,is_required:Q.is_required,options:typeof Q.options=="string"?Q.options:Q.options?JSON.stringify(Q.options):null,sort_order:Q.sort_order})))},[m]);const M=Nt({mutationFn:async()=>{const{error:Q}=await V.from("landing_pages").update({title:_.title,hero_headline:_.hero_headline,hero_subtext:_.hero_subtext||null,hero_image_url:_.hero_image_url,logo_url:_.logo_url,primary_color:_.primary_color,accent_color:_.accent_color,agent_name:_.agent_name||null,agent_phone:_.agent_phone||null,agent_email:_.agent_email||null,agent_photo_url:_.agent_photo_url,success_message:_.success_message,is_published:_.is_published,description:_.description||null,lead_magnet_file_url:_.lead_magnet_file_url,lead_magnet_file_name:_.lead_magnet_file_name,lead_magnet_external_url:_.lead_magnet_external_url,listing_id:_.listing_id,property_address:_.property_address||null,property_price:_.property_price||null,property_beds:_.property_beds||null,property_baths:_.property_baths||null,property_sqft:_.property_sqft||null,property_description:_.property_description||null,property_photos:_.property_photos,property_status:_.property_status,theme_style:_.theme_style,eyebrow:_.eyebrow||null,headline_accent:_.headline_accent||null,heading_font:_.heading_font,trust_pills:_.trust_pills,redirect_url:_.settings_redirect_url||null,auto_responder_enabled:!_.settings_disable_auto_responder,auto_responder_subject:_.settings_auto_responder_subject||null,auto_responder_body:_.settings_auto_responder_body||null,drip_campaign_id:_.settings_disable_drip?null:_.settings_drip_campaign_id||null,settings:{...(u==null?void 0:u.settings)||{},redirect_url:_.settings_redirect_url||null,auto_responder_subject:_.settings_auto_responder_subject||null,auto_responder_body:_.settings_auto_responder_body||null,drip_campaign_id:_.settings_drip_campaign_id||null,disable_auto_responder:!!_.settings_disable_auto_responder,disable_drip:!!_.settings_disable_drip,event_starts_at:_.settings_event_starts_at||null,event_location_name:_.settings_event_location_name||null,event_address:_.settings_event_address||null},updated_at:new Date().toISOString()}).eq("id",s);if(Q)throw Q;if(await V.from("landing_page_fields").delete().eq("page_id",s),C.length>0){const{error:te}=await V.from("landing_page_fields").insert(C.map((le,fe)=>({page_id:s,field_type:le.field_type,label:le.label,placeholder:le.placeholder||null,is_required:le.is_required,options:le.options?JSON.parse(le.options):null,sort_order:fe})));if(te)throw te}},onSuccess:()=>{i.invalidateQueries({queryKey:["landing-page",s]}),i.invalidateQueries({queryKey:["landing-page-fields",s]}),a({title:"Page saved!"})},onError:Q=>a({title:"Error",description:Q.message,variant:"destructive"})}),I=async(Q,te)=>{const le=Q.name.split(".").pop(),fe=`landing-pages/${n.id}/${te}-${Date.now()}.${le}`,{error:_e}=await V.storage.from("recruit-landing").upload(fe,Q);if(_e)throw _e;const{data:{publicUrl:ve}}=V.storage.from("recruit-landing").getPublicUrl(fe);return ve},P=async(Q,te)=>{var fe;const le=(fe=Q.target.files)==null?void 0:fe[0];if(le){o(te);try{const _e=await I(le,te);j(ve=>({...ve,[te]:_e})),a({title:"Image uploaded!"})}catch(_e){a({title:"Upload failed",description:_e.message,variant:"destructive"})}finally{o(null)}}},R=async Q=>{var le;const te=(le=Q.target.files)==null?void 0:le[0];if(te){o("lead_magnet");try{const fe=await I(te,"lead-magnet");j(_e=>({..._e,lead_magnet_file_url:fe,lead_magnet_file_name:te.name})),a({title:"File uploaded!"})}catch(fe){a({title:"Upload failed",description:fe.message,variant:"destructive"})}finally{o(null)}}},O=async Q=>{const te=Q.target.files;if(!(!te||te.length===0)){o("property_photos");try{const le=[];for(const fe of Array.from(te)){const _e=await I(fe,"property-photo");le.push(_e)}j(fe=>({...fe,property_photos:[...fe.property_photos,...le]})),a({title:`${le.length} photo(s) uploaded!`})}catch(le){a({title:"Upload failed",description:le.message,variant:"destructive"})}finally{o(null)}}},B=async Q=>{const te=x.find(fe=>fe.id===Q);if(!te)return;const{data:le}=await V.from("listing_photos").select("photo_url").eq("listing_id",Q).order("sort_order");j(fe=>({...fe,listing_id:Q,property_address:te.property_address||`${te.city}, ${te.state}`,property_price:te.price?`$${te.price.toLocaleString()}`:"",property_beds:te.bedrooms?String(te.bedrooms):"",property_baths:te.bathrooms?String(te.bathrooms):"",property_sqft:te.square_footage?te.square_footage.toLocaleString():"",property_description:te.description||"",property_photos:(le==null?void 0:le.map(_e=>_e.photo_url))||fe.property_photos})),a({title:"Listing data imported!"})},U=()=>{A(Q=>[...Q,{clientId:Rjt(),field_type:"text",label:"",placeholder:"",is_required:!1,options:null,sort_order:Q.length}])},G=(Q,te)=>{A(le=>le.map((fe,_e)=>_e===Q?{...fe,...te}:fe))},H=Q=>{A(te=>te.filter((le,fe)=>fe!==Q))},Y=KAe(LU(cV,{activationConstraint:{distance:6}}),LU(XAe,{coordinateGetter:XRt})),se=Q=>{const{active:te,over:le}=Q;!le||te.id===le.id||A(fe=>{const _e=fe.findIndex(he=>he.clientId===te.id),ve=fe.findIndex(he=>he.clientId===le.id);return _e<0||ve<0?fe:tEe(fe,_e,ve).map((he,Se)=>({...he,sort_order:Se}))})},ee=u?`https://pages.relevelup.com/${u.slug}`:"",oe=(u==null?void 0:u.page_type)==="lead_magnet",me=(u==null?void 0:u.page_type)==="just_listed"||(u==null?void 0:u.page_type)==="just_sold";return h||p?e.jsx(Xs,{title:"Loading...",children:e.jsx("div",{className:"flex justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):u?e.jsxs(Xs,{title:_.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($,{variant:"ghost",size:"sm",onClick:()=>t("/mission-control/landing-pages"),children:e.jsx(Ia,{className:"h-4 w-4"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-xl font-bold",children:_.title||"Untitled Page"}),e.jsxs("div",{className:"flex items-center gap-2 mt-0.5",children:[e.jsx(qe,{variant:_.is_published?"default":"secondary",className:"text-[10px]",children:_.is_published?"Published":"Draft"}),e.jsxs("span",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(ba,{className:"h-3 w-3"})," ",u.view_count," views"]}),e.jsxs("span",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Xn,{className:"h-3 w-3"})," ",g.length," submissions"]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[_.is_published&&e.jsxs(e.Fragment,{children:[e.jsx($,{size:"sm",variant:"outline",onClick:()=>d(!0),children:e.jsx(Bx,{className:"h-3.5 w-3.5"})}),e.jsxs($,{size:"sm",variant:"outline",onClick:()=>{navigator.clipboard.writeText(ee),a({title:"Link copied!"})},children:[e.jsx(Da,{className:"h-3.5 w-3.5 mr-1"})," Copy Link"]}),e.jsx($,{size:"sm",variant:"outline",asChild:!0,children:e.jsxs("a",{href:ee,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(Ir,{className:"h-3.5 w-3.5 mr-1"})," Preview"]})})]}),e.jsxs($,{onClick:()=>M.mutate(),disabled:M.isPending,children:[e.jsx(Ml,{className:"h-4 w-4 mr-2"}),M.isPending?"Saving...":"Save"]})]})]}),e.jsxs(ya,{defaultValue:"design",children:[e.jsxs(va,{children:[e.jsx(is,{value:"design",children:"Design"}),oe&&e.jsx(is,{value:"lead_magnet",children:"Lead Magnet"}),me&&e.jsx(is,{value:"property",children:"Property Details"}),e.jsxs(is,{value:"fields",children:["Form Fields (",C.length,")"]}),e.jsxs(is,{value:"submissions",children:["Submissions (",g.length,")"]}),e.jsx(is,{value:"automation",children:"Automation"}),e.jsx(is,{value:"analytics",children:"Analytics"}),e.jsx(is,{value:"settings",children:"Settings"})]}),e.jsxs(cs,{value:"design",className:"space-y-4 mt-4",children:[e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsx(Yt,{className:"text-base",children:"Page Details"})}),e.jsxs(De,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Page Title (internal)"}),e.jsx(be,{value:_.title,onChange:Q=>j(te=>({...te,title:Q.target.value}))})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Description (internal)"}),e.jsx(be,{value:_.description,onChange:Q=>j(te=>({...te,description:Q.target.value}))})]})]})]}),e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsxs(Yt,{className:"text-base flex items-center gap-2",children:["Theme & Style",e.jsx(qe,{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(re,{children:"Theme Style"}),e.jsxs(bs,{value:_.theme_style,onValueChange:Q=>j(te=>({...te,theme_style:Q})),children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"premium",children:"Premium — cinematic + glass form"}),e.jsx(We,{value:"classic",children:"Classic — centered card"})]})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Headline Font"}),e.jsxs(bs,{value:_.heading_font,onValueChange:Q=>j(te=>({...te,heading_font:Q})),children:[e.jsx(ys,{children:e.jsx(_s,{})}),e.jsxs(vs,{children:[e.jsx(We,{value:"playfair",children:"Playfair Display (editorial serif)"}),e.jsx(We,{value:"baskerville",children:"Libre Baskerville (classic serif)"}),e.jsx(We,{value:"instrument",children:"Instrument Serif (modern serif)"}),e.jsx(We,{value:"sans",children:"Inter (clean sans-serif)"})]})]})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Trust Pills (comma separated, shown under CTA)"}),e.jsx(be,{value:_.trust_pills.join(", "),onChange:Q=>j(te=>({...te,trust_pills:Q.target.value.split(",").map(le=>le.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(we,{children:[e.jsx(Vt,{children:e.jsx(Yt,{className:"text-base",children:"Hero Section"})}),e.jsxs(De,{className:"space-y-4",children:[_.theme_style==="premium"&&e.jsxs("div",{children:[e.jsx(re,{children:"Eyebrow (small label above headline)"}),e.jsx(be,{value:_.eyebrow,onChange:Q=>j(te=>({...te,eyebrow:Q.target.value})),placeholder:"HOME VALUE"})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Headline"}),e.jsx(be,{value:_.hero_headline,onChange:Q=>j(te=>({...te,hero_headline:Q.target.value})),placeholder:"What Is Your Home"})]}),_.theme_style==="premium"&&e.jsxs("div",{children:[e.jsx(re,{children:"Accent Word(s) — italic & colored (optional)"}),e.jsx(be,{value:_.headline_accent,onChange:Q=>j(te=>({...te,headline_accent:Q.target.value})),placeholder:"Actually Worth?"})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Subtext"}),e.jsx(Ls,{value:_.hero_subtext,onChange:Q=>j(te=>({...te,hero_subtext:Q.target.value})),rows:3,placeholder:"A brief description..."})]}),e.jsxs("div",{children:[e.jsxs(re,{children:["Background Image ",_.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:[_.hero_image_url&&e.jsx("img",{src:_.hero_image_url,alt:"Hero",className:"h-16 w-28 object-cover rounded"}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx($,{variant:"outline",size:"sm",asChild:!0,disabled:l==="hero_image_url",children:e.jsxs("span",{children:[e.jsx(gi,{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:Q=>P(Q,"hero_image_url")})]}),_.hero_image_url&&e.jsx($,{variant:"ghost",size:"sm",onClick:()=>j(Q=>({...Q,hero_image_url:null})),children:e.jsx(Un,{className:"h-3.5 w-3.5"})})]})]})]})]}),e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsx(Yt,{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(re,{children:"Logo"}),e.jsxs("div",{className:"flex items-center gap-3 mt-1",children:[_.logo_url&&e.jsx("img",{src:_.logo_url,alt:"Logo",className:"h-10 w-auto rounded"}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx($,{variant:"outline",size:"sm",asChild:!0,disabled:l==="logo_url",children:e.jsxs("span",{children:[e.jsx(gi,{className:"h-3.5 w-3.5 mr-1"}),l==="logo_url"?"...":"Upload"]})}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:Q=>P(Q,"logo_url")})]})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Agent Photo"}),e.jsxs("div",{className:"flex items-center gap-3 mt-1",children:[_.agent_photo_url&&e.jsx("img",{src:_.agent_photo_url,alt:"Agent",className:"h-10 w-10 rounded-full object-cover"}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx($,{variant:"outline",size:"sm",asChild:!0,disabled:l==="agent_photo_url",children:e.jsxs("span",{children:[e.jsx(gi,{className:"h-3.5 w-3.5 mr-1"}),l==="agent_photo_url"?"...":"Upload"]})}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:Q=>P(Q,"agent_photo_url")})]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Primary Color"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx("input",{type:"color",value:_.primary_color,onChange:Q=>j(te=>({...te,primary_color:Q.target.value})),className:"h-9 w-12 rounded border cursor-pointer"}),e.jsx(be,{value:_.primary_color,onChange:Q=>j(te=>({...te,primary_color:Q.target.value})),className:"font-mono text-xs"})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Accent Color"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx("input",{type:"color",value:_.accent_color,onChange:Q=>j(te=>({...te,accent_color:Q.target.value})),className:"h-9 w-12 rounded border cursor-pointer"}),e.jsx(be,{value:_.accent_color,onChange:Q=>j(te=>({...te,accent_color:Q.target.value})),className:"font-mono text-xs"})]})]})]})]})]}),e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsx(Yt,{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(re,{children:"Name"}),e.jsx(be,{value:_.agent_name,onChange:Q=>j(te=>({...te,agent_name:Q.target.value}))})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Phone"}),e.jsx(be,{value:_.agent_phone,onChange:Q=>j(te=>({...te,agent_phone:Q.target.value}))})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Email"}),e.jsx(be,{value:_.agent_email,onChange:Q=>j(te=>({...te,agent_email:Q.target.value}))})]})]})})]})]}),oe&&e.jsx(cs,{value:"lead_magnet",className:"space-y-4 mt-4",children:e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsxs(Yt,{className:"text-base flex items-center gap-2",children:[e.jsx(ji,{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(re,{children:"Upload File (PDF, guide, checklist, etc.)"}),e.jsxs("div",{className:"flex items-center gap-3 mt-1",children:[_.lead_magnet_file_name&&e.jsxs(qe,{variant:"outline",className:"gap-1",children:[e.jsx(ji,{className:"h-3 w-3"})," ",_.lead_magnet_file_name]}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx($,{variant:"outline",size:"sm",asChild:!0,disabled:l==="lead_magnet",children:e.jsxs("span",{children:[e.jsx(gi,{className:"h-3.5 w-3.5 mr-1"}),l==="lead_magnet"?"Uploading...":"Upload File"]})}),e.jsx("input",{type:"file",className:"hidden",onChange:R})]}),_.lead_magnet_file_url&&e.jsx($,{variant:"ghost",size:"sm",onClick:()=>j(Q=>({...Q,lead_magnet_file_url:null,lead_magnet_file_name:null})),children:e.jsx(Un,{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(re,{className:"flex items-center gap-1",children:[e.jsx(pd,{className:"h-3.5 w-3.5"})," External URL"]}),e.jsx(be,{value:_.lead_magnet_external_url||"",onChange:Q=>j(te=>({...te,lead_magnet_external_url:Q.target.value||null})),placeholder:"https://drive.google.com/... or https://dropbox.com/...",className:"mt-1"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Link to a file on Google Drive, Dropbox, or any URL"})]})]})]})}),me&&e.jsxs(cs,{value:"property",className:"space-y-4 mt-4",children:[e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsxs(Yt,{className:"text-base flex items-center gap-2",children:[e.jsx(ua,{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(bs,{value:_.listing_id||"",onValueChange:Q=>B(Q),children:[e.jsx(ys,{children:e.jsx(_s,{placeholder:"Select a listing to import..."})}),e.jsx(vs,{children:x.map(Q=>{var te;return e.jsxs(We,{value:Q.id,children:[Q.property_address||`${Q.city}, ${Q.state}`," — $",(te=Q.price)==null?void 0:te.toLocaleString()]},Q.id)})})]})]})]}),e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsx(Yt,{className:"text-base",children:"Property Information"})}),e.jsxs(De,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Property Address"}),e.jsx(be,{value:_.property_address,onChange:Q=>j(te=>({...te,property_address:Q.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(re,{children:"Price"}),e.jsx(be,{value:_.property_price,onChange:Q=>j(te=>({...te,property_price:Q.target.value})),placeholder:"$450,000"})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Beds"}),e.jsx(be,{value:_.property_beds,onChange:Q=>j(te=>({...te,property_beds:Q.target.value})),placeholder:"4"})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Baths"}),e.jsx(be,{value:_.property_baths,onChange:Q=>j(te=>({...te,property_baths:Q.target.value})),placeholder:"3"})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Sq Ft"}),e.jsx(be,{value:_.property_sqft,onChange:Q=>j(te=>({...te,property_sqft:Q.target.value})),placeholder:"2,400"})]})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Description"}),e.jsx(Ls,{value:_.property_description,onChange:Q=>j(te=>({...te,property_description:Q.target.value})),rows:3,placeholder:"Beautiful home in a great neighborhood..."})]})]})]}),e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsx(Yt,{className:"text-base",children:"Property Photos"})}),e.jsxs(De,{className:"space-y-4",children:[_.property_photos.length>0&&e.jsx("div",{className:"grid grid-cols-3 md:grid-cols-4 gap-2",children:_.property_photos.map((Q,te)=>e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:Q,alt:`Property ${te+1}`,className:"h-24 w-full object-cover rounded"}),e.jsx($,{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:()=>j(le=>({...le,property_photos:le.property_photos.filter((fe,_e)=>_e!==te)})),children:e.jsx(Un,{className:"h-3 w-3"})})]},te))}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx($,{variant:"outline",size:"sm",asChild:!0,disabled:l==="property_photos",children:e.jsxs("span",{children:[e.jsx(gi,{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:O})]})]})]})]}),e.jsxs(cs,{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($,{size:"sm",onClick:U,children:[e.jsx(nn,{className:"h-3.5 w-3.5 mr-1"})," Add Field"]})]}),C.length===0?e.jsx(we,{children:e.jsx(De,{className:"py-8 text-center text-muted-foreground",children:"No fields yet. Add fields to build your form."})}):e.jsx(eEe,{sensors:Y,collisionDetection:YAe,onDragEnd:se,children:e.jsx(sEe,{items:C.map(Q=>Q.clientId),strategy:kGs,children:e.jsx("div",{className:"space-y-3",children:C.map((Q,te)=>e.jsx(_Zn,{field:Q,index:te,updateField:G,removeField:H},Q.clientId))})})})]}),e.jsx(cs,{value:"submissions",className:"mt-4",children:g.length===0?e.jsx(we,{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:g.map(Q=>e.jsx(we,{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:Q.contact_name||"Anonymous"}),Q.synced_to_crm&&e.jsx(qe,{variant:"outline",className:"text-[10px]",children:"Synced"})]}),e.jsxs("div",{className:"text-sm text-muted-foreground mt-0.5",children:[Q.contact_email&&e.jsx("span",{className:"mr-3",children:Q.contact_email}),Q.contact_phone&&e.jsx("span",{children:Q.contact_phone})]}),Q.answers&&typeof Q.answers=="object"&&e.jsx("div",{className:"mt-2 text-sm space-y-1",children:Object.entries(Q.answers).map(([te,le])=>e.jsxs("div",{children:[e.jsxs("span",{className:"font-medium text-muted-foreground",children:[te,":"]})," ",e.jsx("span",{children:String(le)})]},te))})]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:new Date(Q.created_at).toLocaleDateString()})]})})},Q.id))})}),e.jsxs(cs,{value:"automation",className:"space-y-4 mt-4",children:[(u==null?void 0:u.page_type)==="event_registration"&&e.jsxs(we,{children:[e.jsxs(Vt,{children:[e.jsx(Yt,{className:"text-base",children:"Event details"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Shown to visitors as a live countdown with add-to-calendar buttons."})]}),e.jsxs(De,{className:"grid gap-3 md:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1.5 md:col-span-2",children:[e.jsx(re,{children:"Starts at"}),e.jsx(be,{type:"datetime-local",value:_.settings_event_starts_at,onChange:Q=>j(te=>({...te,settings_event_starts_at:Q.target.value}))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Venue / location name"}),e.jsx(be,{placeholder:"e.g. The Grand Hotel",value:_.settings_event_location_name,onChange:Q=>j(te=>({...te,settings_event_location_name:Q.target.value}))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(re,{children:"Address (for map link)"}),e.jsx(be,{placeholder:"123 Main St, City, ST",value:_.settings_event_address,onChange:Q=>j(te=>({...te,settings_event_address:Q.target.value}))})]})]})]}),e.jsxs(we,{children:[e.jsxs(Vt,{children:[e.jsx(Yt,{className:"text-base",children:"Instant auto-reply to lead"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Sent the moment someone submits this page. Leave blank to use your",v!=null&&v.default_auto_responder_body?" account default":" built-in template",". Merge fields: ",e.jsx("code",{children:"{{client_first_name}}"}),", ",e.jsx("code",{children:"{{agent_name}}"}),", ",e.jsx("code",{children:"{{page_title}}"}),", ",e.jsx("code",{children:"{{calendar_link}}"}),"."]})]}),e.jsxs(De,{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(re,{children:"Send auto-reply for this page"}),e.jsx(On,{checked:!_.settings_disable_auto_responder,onCheckedChange:Q=>j(te=>({...te,settings_disable_auto_responder:!Q}))})]}),!_.settings_disable_auto_responder&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsx(re,{children:"Subject (override)"}),e.jsx(be,{value:_.settings_auto_responder_subject,onChange:Q=>j(te=>({...te,settings_auto_responder_subject:Q.target.value})),placeholder:(v==null?void 0:v.default_auto_responder_subject)||"Thanks for reaching out, {{client_first_name}}!"})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Body (override)"}),e.jsx(Ls,{rows:8,value:_.settings_auto_responder_body,onChange:Q=>j(te=>({...te,settings_auto_responder_body:Q.target.value})),placeholder:(v==null?void 0:v.default_auto_responder_body)||`Hi {{client_first_name}}, Thanks for reaching out…`})]})]})]})]}),e.jsxs(we,{children:[e.jsxs(Vt,{children:[e.jsx(Yt,{className:"text-base",children:"Smart Drip enrollment"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Automatically enroll every new lead into a drip campaign.",(v==null?void 0:v.default_drip_campaign_id)&&" Account default applies if no override is selected."]})]}),e.jsxs(De,{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(re,{children:"Enroll new leads in a drip"}),e.jsx(On,{checked:!_.settings_disable_drip,onCheckedChange:Q=>j(te=>({...te,settings_disable_drip:!Q}))})]}),!_.settings_disable_drip&&e.jsxs("div",{children:[e.jsx(re,{children:"Drip override for this page"}),e.jsxs("select",{className:"mt-1 w-full rounded-md border bg-background px-3 py-2 text-sm",value:_.settings_drip_campaign_id||"",onChange:Q=>j(te=>({...te,settings_drip_campaign_id:Q.target.value||null})),children:[e.jsx("option",{value:"",children:"— Use account default —"}),y.map(Q=>e.jsx("option",{value:Q.id,children:Q.name},Q.id))]})]})]})]}),e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsx(Yt,{className:"text-base",children:"Redirect after submit"})}),e.jsxs(De,{children:[e.jsx(be,{value:_.settings_redirect_url,onChange:Q=>j(te=>({...te,settings_redirect_url:Q.target.value})),placeholder:(v==null?void 0:v.default_redirect_url)||"https://your-site.com/thank-you (optional)"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-2",children:"Leave blank to keep the inline Thank-You message."})]})]})]}),e.jsx(cs,{value:"analytics",className:"space-y-4 mt-4",children:e.jsx(yZn,{pageId:s})}),e.jsxs(cs,{value:"settings",className:"space-y-4 mt-4",children:[e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsx(Yt,{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(re,{children:"Published"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Make this page publicly accessible"})]}),e.jsx(On,{checked:_.is_published,onCheckedChange:Q=>j(te=>({...te,is_published:Q}))})]}),_.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:ee})]})]})]}),e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsx(Yt,{className:"text-base",children:"Thank You Message"})}),e.jsx(De,{children:e.jsx(Ls,{value:_.success_message,onChange:Q=>j(te=>({...te,success_message:Q.target.value})),rows:2,placeholder:"Message shown after form submission"})})]})]})]})]}),e.jsx(zs,{open:c,onOpenChange:d,children:e.jsxs(Rs,{className:"max-w-sm",children:[e.jsx(Vs,{children:e.jsx($s,{children:"QR Code"})}),e.jsxs("div",{className:"flex flex-col items-center gap-4 py-4",children:[e.jsx(jk,{value:ee,size:240}),e.jsx("p",{className:"text-xs text-muted-foreground text-center break-all",children:ee})]})]})})]}):e.jsx(Xs,{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($,{variant:"link",onClick:()=>t("/mission-control/landing-pages"),children:"Go back"})]})})}const jZn={default_auto_responder_subject:"",default_auto_responder_body:"",default_drip_campaign_id:null,default_redirect_url:"",default_calendar_link:"",text_agent_on_lead:!1,agent_sms_phone:"",use_brand_kit:!0},NZn=`Hi {{client_first_name}}, Thanks for reaching out — I've got your information and will personally follow up within one business day. If it's easier, you can also call or text me directly at {{agent_phone}}. Talk soon, {{agent_name}}`;function kZn(){const s=ai(),{toast:t}=Fi(),n=Jn(),r=ls(),[a,i]=k.useState(jZn),{data:l}=pt({queryKey:["landing-page-defaults",s],queryFn:async()=>{const{data:d}=await V.from("agent_landing_page_defaults").select("*").eq("user_id",s).maybeSingle();return d||null},enabled:!!s}),{data:o=[]}=pt({queryKey:["drip-campaigns-mine",s],queryFn:async()=>{const{data:d}=await V.from("drip_campaigns").select("id, name").eq("owner_user_id",s).eq("is_active",!0).order("name");return d||[]},enabled:!!s});k.useEffect(()=>{l&&i({default_auto_responder_subject:l.default_auto_responder_subject??"",default_auto_responder_body:l.default_auto_responder_body??"",default_drip_campaign_id:l.default_drip_campaign_id??null,default_redirect_url:l.default_redirect_url??"",default_calendar_link:l.default_calendar_link??"",text_agent_on_lead:!!l.text_agent_on_lead,agent_sms_phone:l.agent_sms_phone??"",use_brand_kit:l.use_brand_kit??!0})},[l]);const c=Nt({mutationFn:async()=>{const{error:d}=await V.from("agent_landing_page_defaults").upsert({user_id:s,...a},{onConflict:"user_id"});if(d)throw d},onSuccess:()=>{r.invalidateQueries({queryKey:["landing-page-defaults"]}),t({title:"Defaults saved"})},onError:d=>t({title:"Save failed",description:d.message,variant:"destructive"})});return e.jsx(Xs,{title:"Landing Page Defaults",children:e.jsxs("div",{className:"space-y-6 max-w-3xl mx-auto",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs($,{variant:"ghost",size:"sm",onClick:()=>n("/mission-control/landing-pages"),children:[e.jsx(Ia,{className:"h-4 w-4 mr-1"})," Back to pages"]}),e.jsxs($,{onClick:()=>c.mutate(),disabled:c.isPending,children:[e.jsx(Ml,{className:"h-4 w-4 mr-2"})," ",c.isPending?"Saving…":"Save Defaults"]})]}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Landing Page Defaults"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"These run on every landing page automatically. Any page can override them in its own settings."})]}),e.jsxs(we,{children:[e.jsxs(Vt,{children:[e.jsx(Yt,{children:"Instant auto-reply to the lead"}),e.jsxs(vr,{children:["Sent the moment someone submits one of your pages. Uses your Gmail if connected, otherwise your verified sender. Merge fields: ",e.jsx("code",{children:"{{client_first_name}}"}),", ",e.jsx("code",{children:"{{agent_name}}"}),", ",e.jsx("code",{children:"{{agent_phone}}"}),", ",e.jsx("code",{children:"{{page_title}}"}),", ",e.jsx("code",{children:"{{calendar_link}}"}),"."]})]}),e.jsxs(De,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Subject"}),e.jsx(be,{value:a.default_auto_responder_subject||"",onChange:d=>i(u=>({...u,default_auto_responder_subject:d.target.value})),placeholder:"Thanks for reaching out, {{client_first_name}}!"})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Message body"}),e.jsx(Ls,{rows:10,value:a.default_auto_responder_body||"",onChange:d=>i(u=>({...u,default_auto_responder_body:d.target.value})),placeholder:NZn}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Leave blank to use the polished built-in template that adapts to each page type."})]})]})]}),e.jsxs(we,{children:[e.jsxs(Vt,{children:[e.jsx(Yt,{children:"Default Smart Drip"}),e.jsx(vr,{children:"Every new lead drops into this drip unless a page overrides it."})]}),e.jsx(De,{children:e.jsxs(bs,{value:a.default_drip_campaign_id||"none",onValueChange:d=>i(u=>({...u,default_drip_campaign_id:d==="none"?null:d})),children:[e.jsx(ys,{children:e.jsx(_s,{placeholder:"Pick a drip…"})}),e.jsxs(vs,{children:[e.jsx(We,{value:"none",children:"— No default drip —"}),o.map(d=>e.jsx(We,{value:d.id,children:d.name},d.id))]})]})})]}),e.jsxs(we,{children:[e.jsx(Vt,{children:e.jsx(Yt,{children:"Defaults for every page"})}),e.jsxs(De,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(re,{children:"Default booking / calendar link"}),e.jsx(be,{value:a.default_calendar_link||"",onChange:d=>i(u=>({...u,default_calendar_link:d.target.value})),placeholder:"https://calendly.com/your-name/intro"})]}),e.jsxs("div",{children:[e.jsx(re,{children:"Default redirect after submit (optional)"}),e.jsx(be,{value:a.default_redirect_url||"",onChange:d=>i(u=>({...u,default_redirect_url:d.target.value})),placeholder:"https://your-site.com/thanks"})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx(re,{className:"text-base",children:"Use my brand kit colors"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"New pages pick up your brand colors/logo automatically."})]}),e.jsx(On,{checked:a.use_brand_kit,onCheckedChange:d=>i(u=>({...u,use_brand_kit:d}))})]})]})]}),e.jsxs(we,{children:[e.jsxs(Vt,{children:[e.jsx(Yt,{children:"Text me when a lead submits"}),e.jsx(vr,{children:"Get an SMS the second a lead hits your inbox. Coming soon — requires SMS sender setup."})]}),e.jsxs(De,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsx(re,{className:"text-base",children:"SMS me new leads"}),e.jsx(On,{checked:a.text_agent_on_lead,onCheckedChange:d=>i(u=>({...u,text_agent_on_lead:d}))})]}),a.text_agent_on_lead&&e.jsxs("div",{children:[e.jsx(re,{children:"Phone number for alerts"}),e.jsx(be,{type:"tel",value:a.agent_sms_phone||"",onChange:d=>i(u=>({...u,agent_sms_phone:d.target.value})),placeholder:"(555) 123-4567"})]})]})]})]})})}function SKt({hasLeadSite:s}){const t=Jn(),n=ls(),[r,a]=k.useState(!1),{offer:i}=Y3e(!s);if(s||!i)return null;const l=async()=>{a(!0);try{const{data:o,error:c}=await V.functions.invoke("claim-free-lead-site",{body:{}});if(c)throw c;if(o!=null&&o.error)throw new Error(o.error);await n.invalidateQueries({queryKey:["agent-lead-site"]}),ae.success("Your website is live! Let’s make it yours."),t(`/admin/lead-sites/${o.siteId}/edit`)}catch(o){ae.error((o==null?void 0:o.message)||"Could not create your website")}finally{a(!1)}};return e.jsx(we,{className:"p-6 border-2 border-amber-300 bg-gradient-to-br from-amber-50 via-background to-background",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-amber-400 to-amber-600 text-white flex items-center justify-center flex-shrink-0",children:e.jsx(ky,{className:"w-5 h-5"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h3",{className:"font-semibold text-base",children:i.offer_headline||"Claim your free luxury website"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:i.offer_description||"A designer luxury website included with your brokerage — your bio, your branding, your Listing Exchange listings and lead capture. Upgrade any time to add full MLS home search."}),e.jsx("ul",{className:"mt-3 space-y-1.5",children:["Luxury design, fully editable in the Site Builder","Your own listings featured automatically","Blog, city pages, contact and lead capture included"].map(o=>e.jsxs("li",{className:"flex items-start gap-2 text-xs text-muted-foreground",children:[e.jsx(kn,{className:"w-3.5 h-3.5 mt-0.5 text-amber-500 shrink-0"}),o]},o))}),e.jsxs("div",{className:"flex items-center gap-3 mt-4",children:[e.jsx($,{onClick:l,disabled:r,children:r?"Creating your site…":"Claim my free website"}),e.jsxs("a",{href:"https://danicapatton.thelocalmove.com",target:"_blank",rel:"noreferrer",className:"text-xs text-muted-foreground hover:text-foreground inline-flex items-center gap-1",children:["See an example ",e.jsx(Ir,{className:"w-3 h-3"})]})]})]})]})})}function SZn(){return pt({queryKey:["website-apps"],queryFn:async()=>{const{data:s,error:t}=await V.from("website_apps").select("*").order("sort_order",{ascending:!0});if(t)throw t;return s||[]}})}function aMe(){const{user:s}=ks();return pt({queryKey:["agent-website-app-installs",s==null?void 0:s.id],queryFn:async()=>{if(!(s!=null&&s.id))return[];const{data:t,error:n}=await V.from("agent_website_app_installs").select("*").eq("user_id",s.id);if(n)throw n;return t||[]},enabled:!!(s!=null&&s.id)})}function iMe(){const{user:s}=ks(),t=ls();return Nt({mutationFn:async({app_slug:n,enabled:r})=>{if(!(s!=null&&s.id))throw new Error("Not authenticated");const{error:a}=await V.from("agent_website_app_installs").upsert({user_id:s.id,app_slug:n,enabled:r},{onConflict:"user_id,app_slug"});if(a)throw a},onSuccess:(n,r)=>{t.invalidateQueries({queryKey:["agent-website-app-installs"]}),ae.success(r.enabled?"App installed":"App turned off")},onError:n=>ae.error(n.message||"Failed to update app")})}const CZn={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"}},AZn={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 EZn(){const s=Jn(),{data:t=[],isLoading:n}=SZn(),{data:r=[]}=aMe(),{hasLeadSite:a,siteUrl:i}=Tg(),l=iMe(),[o,c]=k.useState(!1),d=h=>{var m;return((m=r.find(p=>p.app_slug===h))==null?void 0:m.enabled)??!1},u=h=>r.some(m=>m.app_slug===h);return e.jsxs(Xs,{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(ix,{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(kn,{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($,{onClick:()=>c(!0),className:"mt-5 bg-white text-indigo-700 hover:bg-white/90 shadow-lg font-semibold gap-2",children:[e.jsx(mm,{className:"w-5 h-5"}),"Watch: How to use Website Apps"]})]})]}),e.jsx(SKt,{hasLeadSite:a}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(we,{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(kc,{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(qe,{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(Ir,{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(Ir,{className:"w-3 h-3"})]})," ","to learn more — apps install automatically once you have one."]})]})]})}),e.jsx(we,{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(wC,{className:"w-5 h-5"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h3",{className:"font-semibold text-sm",children:"Option 2 — Your existing website"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Already have a site (Wix, Squarespace, WordPress, custom)? Paste a one-line snippet and the widget appears anywhere."}),e.jsx("p",{className:"text-[11px] text-indigo-700 mt-2 font-medium",children:'Open any app below → "Install on my website" tab to copy your code.'})]})]})})]}),n?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading apps..."}):e.jsx("div",{className:"grid gap-5 sm:grid-cols-2 lg:grid-cols-3",children:t.map(h=>{const m=n3e[h.icon||"Sparkles"]||kn,p=d(h.slug),g=u(h.slug),x=h.status==="coming_soon",y=CZn[h.slug]||AZn;return e.jsxs(we,{className:`group relative overflow-hidden border-0 ring-1 ring-border ${y.ring} hover:ring-2 transition-all hover:shadow-xl ${x?"opacity-70":""}`,children:[e.jsx("div",{className:`h-1.5 w-full bg-gradient-to-r ${y.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 ${y.iconBg} ${y.iconText} flex items-center justify-center shadow-md group-hover:scale-105 transition-transform`,children:e.jsx(m,{className:"w-7 h-7"})}),x?e.jsx(qe,{variant:"secondary",children:"Coming soon"}):p?e.jsxs(qe,{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"]}):g?e.jsx(qe,{variant:"outline",children:"Paused"}):e.jsx(qe,{className:y.chip+" hover:"+y.chip,children:"New"})]}),e.jsxs("div",{className:"space-y-1 flex-1",children:[e.jsx("h3",{className:"font-bold text-lg",children:h.name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:h.description})]}),!x&&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(On,{checked:p,onCheckedChange:v=>l.mutate({app_slug:h.slug,enabled:v})}),e.jsx("span",{className:"text-sm font-medium text-muted-foreground",children:p?"On":"Off"})]}),e.jsxs($,{size:"sm",className:`bg-gradient-to-r ${y.gradient} text-white hover:opacity-90 shadow-md border-0`,onClick:()=>s(`/website-apps/${h.slug}`),children:[e.jsx(Yc,{className:"w-3.5 h-3.5 mr-1.5"}),"Configure",e.jsx(xi,{className:"w-3.5 h-3.5 ml-1"})]})]})]})]},h.id)})})]}),e.jsx(zs,{open:o,onOpenChange:c,children:e.jsxs(Rs,{className:"max-w-4xl p-0 overflow-hidden bg-black border-0",children:[e.jsx(Vs,{className:"px-5 pt-4 pb-2 bg-background",children:e.jsx($s,{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"})]})})]})}function TZn(){const{leadSite:s,hasLeadSite:t,isLoading:n}=Tg(),{hasOffer:r,isLoading:a}=Y3e(!t);return t&&s?e.jsx(ab,{to:`/my-website/${s.id}/edit`,replace:!0}):e.jsx(Xs,{title:"Get My Website",description:"Claim your complimentary luxury website",children:e.jsx("div",{className:"max-w-3xl mx-auto p-6 lg:p-8 space-y-6",children:n||a?e.jsx("div",{className:"h-40 flex items-center justify-center",children:e.jsx("div",{className:"h-6 w-6 animate-spin rounded-full border-2 border-primary border-t-transparent"})}):r?e.jsx(SKt,{hasLeadSite:!1}):e.jsxs("div",{className:"rounded-xl border border-border p-8 text-center",children:[e.jsx("h2",{className:"text-lg font-semibold",children:"No website yet"}),e.jsxs("p",{className:"text-sm text-muted-foreground mt-2",children:["Your brokerage doesn’t currently offer a complimentary website. Visit"," ",e.jsx("a",{href:"https://www.thelocalmove.com",target:"_blank",rel:"noreferrer",className:"text-primary hover:underline",children:"thelocalmove.com"})," ","to get started with a full IDX website."]})]})})})}const nOe={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 MZn(){const{user:s}=ks();return pt({queryKey:["video-greeter-config",s==null?void 0:s.id],queryFn:async()=>{if(!(s!=null&&s.id))return nOe;const{data:t,error:n}=await V.from("video_greeter_configs").select("*").eq("user_id",s.id).maybeSingle();if(n)throw n;return t?{...nOe,...t}:nOe},enabled:!!(s!=null&&s.id)})}function PZn(){const{user:s}=ks(),t=ls();return Nt({mutationFn:async n=>{if(!(s!=null&&s.id))throw new Error("Not authenticated");const{error:r}=await V.from("video_greeter_configs").upsert({user_id:s.id,...n},{onConflict:"user_id"});if(r)throw r},onSuccess:()=>{t.invalidateQueries({queryKey:["video-greeter-config"]}),ae.success("Saved")},onError:n=>ae.error(n.message||"Failed to save")})}function IZn({label:s,value:t,onChange:n,thumbnailUrl:r,placeholder:a="https://...",hint:i}){const l=k.useRef(null),[o,c]=k.useState(!1),d=async u=>{var m;const h=(m=u.target.files)==null?void 0:m[0];if(h){if(!h.type.startsWith("video/")){ae.error("Please select a video file");return}if(h.size>50*1024*1024){ae.error("Video must be under 50MB");return}c(!0);try{const p=h.name.split(".").pop()||"mp4",g=`lead-site/videos/${Date.now()}-${Math.random().toString(36).slice(2,6)}.${p}`,{error:x}=await V.storage.from("agent-uploads").upload(g,h,{upsert:!0});if(x)throw x;const{data:{publicUrl:y}}=V.storage.from("agent-uploads").getPublicUrl(g);n(y),ae.success("Video uploaded!")}catch(p){ae.error(p.message||"Upload failed")}finally{c(!1),l.current&&(l.current.value="")}}};return e.jsxs("div",{children:[e.jsx(re,{children:s}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(be,{value:t,onChange:u=>n(u.target.value),placeholder:a,className:"flex-1"}),e.jsxs($,{type:"button",variant:"outline",size:"sm",className:"shrink-0 gap-1.5 h-9",onClick:()=>{var u;return(u=l.current)==null?void 0:u.click()},disabled:o,children:[o?e.jsx(Jt,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(gi,{className:"h-3.5 w-3.5"}),o?"Uploading...":"Upload"]}),e.jsx("input",{ref:l,type:"file",accept:"video/*",className:"hidden",onChange:d})]}),i&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:i}),t&&(()=>{const u=t.match(/(?:youtube\.com\/(?:watch\?v=|embed\/|shorts\/)|youtu\.be\/)([A-Za-z0-9_-]{11})/),h=u==null?void 0:u[1];return e.jsxs("div",{className:"relative group mt-2",children:[e.jsx("div",{className:`rounded-lg border border-border overflow-hidden bg-black w-full mx-auto ${h?"max-w-xl aspect-video":"max-w-sm aspect-[9/16]"}`,children:h?e.jsx("iframe",{src:`https://www.youtube.com/embed/${h}`,className:"w-full h-full",title:"Video preview",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0}):Az(t)?e.jsx(Cqe,{sourceUrl:t,thumbnailUrl:r,autoPlay:!0,muted:!0,loop:!0,className:"w-full h-full object-contain"}):e.jsx("video",{src:t,className:"w-full h-full object-contain",controls:!0,muted:!0,preload:"metadata"})}),e.jsx($,{type:"button",variant:"destructive",size:"icon",className:"absolute top-1 right-1 h-6 w-6 opacity-0 group-hover:opacity-100 transition-opacity",onClick:()=>n(""),children:e.jsx(mr,{className:"h-3 w-3"})})]})})()]})}const LZn=[{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 RZn({onVideoReady:s}){const[t,n]=k.useState(!1),[r,a]=k.useState("script"),[i,l]=k.useState(""),[o,c]=k.useState(!0),[d,u]=k.useState(!1),[h,m]=k.useState(0),[p,g]=k.useState(0),x=o4(),y=()=>{a("script"),l(""),m(0),g(0),c(!0)},v=j=>{!j&&(r==="uploading"||r==="processing")||(n(j),j||y())},_=k.useCallback(async(j,C)=>{a("uploading");try{const A="Video Greeter",{videoId:M,libraryId:I}=await v6(A),{uploadUrl:P,apiKey:R}=await b6(M),O=new XMLHttpRequest;O.upload.onprogress=me=>{me.lengthComputable&&m(me.loaded/me.total*100)},await new Promise((me,Q)=>{O.onload=()=>O.status>=200&&O.status<300?me():Q(new Error("Upload failed")),O.onerror=()=>Q(new Error("Upload failed")),O.open("PUT",P),O.setRequestHeader("AccessKey",R),O.send(j)}),a("processing");let B=0;const U=Date.now(),G=9e4,H=`https://iframe.mediadelivery.net/embed/${I}/${M}`,Y=`https://iframe.mediadelivery.net/play/${I}/${M}`;for(;B<4;){if(await new Promise(Q=>setTimeout(Q,3e3)),Date.now()-U>G){const Q=j.size/1048576,te=await x.mutateAsync({bunny_video_id:M,playback_url:Y,file_size_mb:Q,title:A,status:"processing",touch_type:"video"});s({videoId:(te==null?void 0:te.id)||M,playbackUrl:H,thumbnailUrl:null}),ae.success("Video saved — still encoding. Will be ready shortly."),a("done"),setTimeout(()=>{n(!1),y()},1500);return}const me=await D2(M);if(B=me.status,g(me.encodeProgress||0),B===5||B===6)throw new Error("Video processing failed")}const se=await D2(M),ee=(se.storageSize||j.size)/(1024*1024),oe=await x.mutateAsync({bunny_video_id:M,playback_url:se.directPlayUrl||H,thumbnail_url:se.thumbnailUrl,preview_url:se.previewUrl||null,duration_seconds:se.length||C,file_size_mb:ee,title:A,status:"ready",touch_type:"video"});s({videoId:(oe==null?void 0:oe.id)||M,playbackUrl:se.directPlayUrl||H,thumbnailUrl:se.thumbnailUrl||null}),ae.success("Video recorded & added to your library!"),a("done"),setTimeout(()=>{n(!1),y()},1500)}catch(A){console.error(A),ae.error("Failed to process video. Please try again."),a("record")}},[x,s]);return e.jsxs(zs,{open:t,onOpenChange:v,children:[e.jsx(yl,{asChild:!0,children:e.jsxs($,{variant:"default",size:"sm",className:"gap-1.5",children:[e.jsx(ia,{className:"h-4 w-4"}),"Record now"]})}),e.jsxs(Rs,{className:"sm:max-w-3xl max-h-[92vh] overflow-y-auto",children:[e.jsx(Vs,{children:e.jsxs($s,{className:"flex items-center gap-2",children:[e.jsx(kn,{className:"h-5 w-5 text-primary"}),"Record your Video Greeter"]})}),r==="script"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-sm mb-1",children:"1. Pick a script (optional)"}),e.jsx("p",{className:"text-xs text-muted-foreground mb-3",children:"Edit it to sound like you, or skip and freestyle."}),e.jsx(Eo,{className:"h-[280px] pr-3",children:e.jsx("div",{className:"grid sm:grid-cols-2 gap-3",children:LZn.map(j=>e.jsxs(we,{className:"p-3 cursor-pointer hover:border-primary transition-colors",onClick:()=>l(j.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:j.title}),e.jsx(qe,{variant:"outline",className:"text-[10px] shrink-0",children:j.duration})]}),e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2",children:j.description})]},j.id))})})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-sm mb-1",children:"2. Edit your script"}),e.jsx(Ls,{rows:5,value:i,onChange:j=>l(j.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($,{variant:"ghost",onClick:()=>{l(""),a("record")},children:"Skip — freestyle"}),e.jsxs($,{onClick:()=>a("record"),children:[e.jsx(ea,{className:"h-4 w-4 mr-1.5"})," Continue to recorder"]})]})]}),r==="record"&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(w6,{maxDurationSeconds:60,onRecordingComplete:_,onRecordingStateChange:u,onError:j=>ae.error(j),teleprompterContent:o&&i?e.jsx(uQe,{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($,{variant:"ghost",size:"sm",onClick:()=>a("script"),children:"← Back to script"}),i&&!o&&e.jsxs($,{variant:"outline",size:"sm",onClick:()=>c(!0),children:[e.jsx(ea,{className:"h-4 w-4 mr-1.5"})," Show teleprompter"]})]})]}),r==="uploading"&&e.jsxs("div",{className:"flex flex-col items-center gap-4 py-12",children:[e.jsx(Jt,{className:"h-10 w-10 animate-spin text-primary"}),e.jsx("p",{className:"text-sm font-medium",children:"Uploading video..."}),e.jsx(ho,{value:h,className:"w-64"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[Math.round(h),"%"]})]}),r==="processing"&&e.jsxs("div",{className:"flex flex-col items-center gap-4 py-12",children:[e.jsx(Jt,{className:"h-10 w-10 animate-spin text-primary"}),e.jsx("p",{className:"text-sm font-medium",children:"Processing video..."}),e.jsx(ho,{value:p,className:"w-64"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[Math.round(p),"%"]})]}),r==="done"&&e.jsxs("div",{className:"flex flex-col items-center gap-3 py-12",children:[e.jsx(nl,{className:"h-12 w-12 text-emerald-500"}),e.jsx("p",{className:"text-sm font-medium",children:"Video attached to your greeter!"})]})]})]})}function DZn(){var C;const s=Jn(),{user:t}=ks(),{leadSite:n}=Tg(),{data:r}=MZn(),a=PZn(),{data:i=[]}=aMe(),l=iMe(),[o,c]=k.useState(null),[d,u]=k.useState({impressions:0,expands:0,ctaClicks:0,leads:0});if(k.useEffect(()=>{r&&!o&&c(r)},[r,o]),k.useEffect(()=>{t!=null&&t.id&&V.from("widget_events").select("event_type",{count:"exact"}).eq("user_id",t.id).eq("app_slug","video_greeter").then(({data:A})=>{const M=A||[];u({impressions:M.filter(I=>I.event_type==="impression").length,expands:M.filter(I=>I.event_type==="expand").length,ctaClicks:M.filter(I=>I.event_type==="cta_click").length,leads:M.filter(I=>I.event_type==="lead_capture").length})})},[t==null?void 0:t.id]),!o)return e.jsx(Xs,{title:"Video Greeter",children:e.jsx("div",{className:"p-8 text-sm text-muted-foreground",children:"Loading..."})});const h=((C=i.find(A=>A.app_slug==="video_greeter"))==null?void 0:C.enabled)??!1,m=A=>c({...o,...A}),p=A=>m({ctas:A}),g=()=>p([...o.ctas||[],{id:crypto.randomUUID(),label:"New Button",url:"https://",style:"primary"}]),x=A=>p((o.ctas||[]).filter(M=>M.id!==A)),y=(A,M)=>p((o.ctas||[]).map(I=>I.id===A?{...I,...M}:I)),v=()=>a.mutate(o),_=(n==null?void 0:n.subdomain_slug)||(t==null?void 0:t.id)||"",j=`